]> Zhao Yanbai Git Server - minix.git/commitdiff
Import unmodified NetBSD libc in trunk
authorGianluca Guida <gianluca@minix3.org>
Mon, 14 Feb 2011 19:36:03 +0000 (19:36 +0000)
committerGianluca Guida <gianluca@minix3.org>
Mon, 14 Feb 2011 19:36:03 +0000 (19:36 +0000)
This patch imports the unmodified current version of NetBSD libc.
The NetBSD includes are in /nbsd_include, while the libc code itself is
split between lib/nbsd_libc and common/lib/libc.

3215 files changed:
common/lib/libc/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/alpha/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/alpha/atomic/atomic_add.S [new file with mode: 0644]
common/lib/libc/arch/alpha/atomic/atomic_and.S [new file with mode: 0644]
common/lib/libc/arch/alpha/atomic/atomic_cas.S [new file with mode: 0644]
common/lib/libc/arch/alpha/atomic/atomic_dec.S [new file with mode: 0644]
common/lib/libc/arch/alpha/atomic/atomic_inc.S [new file with mode: 0644]
common/lib/libc/arch/alpha/atomic/atomic_op_asm.h [new file with mode: 0644]
common/lib/libc/arch/alpha/atomic/atomic_or.S [new file with mode: 0644]
common/lib/libc/arch/alpha/atomic/atomic_swap.S [new file with mode: 0644]
common/lib/libc/arch/alpha/atomic/membar_ops.S [new file with mode: 0644]
common/lib/libc/arch/alpha/gen/byte_swap_2.S [new file with mode: 0644]
common/lib/libc/arch/alpha/gen/byte_swap_4.S [new file with mode: 0644]
common/lib/libc/arch/alpha/gmon/_mcount.S [new file with mode: 0644]
common/lib/libc/arch/alpha/string/bcopy.S [new file with mode: 0644]
common/lib/libc/arch/alpha/string/bzero.S [new file with mode: 0644]
common/lib/libc/arch/alpha/string/ffs.S [new file with mode: 0644]
common/lib/libc/arch/alpha/string/memcpy.S [new file with mode: 0644]
common/lib/libc/arch/alpha/string/memmove.S [new file with mode: 0644]
common/lib/libc/arch/arm/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/arm/atomic/atomic_add_32.S [new file with mode: 0644]
common/lib/libc/arch/arm/atomic/atomic_and_32.S [new file with mode: 0644]
common/lib/libc/arch/arm/atomic/atomic_cas_32.S [new file with mode: 0644]
common/lib/libc/arch/arm/atomic/atomic_cas_8.S [new file with mode: 0644]
common/lib/libc/arch/arm/atomic/atomic_cas_up.S [new file with mode: 0644]
common/lib/libc/arch/arm/atomic/atomic_dec_32.S [new file with mode: 0644]
common/lib/libc/arch/arm/atomic/atomic_inc_32.S [new file with mode: 0644]
common/lib/libc/arch/arm/atomic/atomic_op_asm.h [new file with mode: 0644]
common/lib/libc/arch/arm/atomic/atomic_or_32.S [new file with mode: 0644]
common/lib/libc/arch/arm/atomic/atomic_swap.S [new file with mode: 0644]
common/lib/libc/arch/arm/atomic/membar_ops.S [new file with mode: 0644]
common/lib/libc/arch/arm/gen/byte_swap_2.S [new file with mode: 0644]
common/lib/libc/arch/arm/gen/byte_swap_4.S [new file with mode: 0644]
common/lib/libc/arch/arm/gen/divsi3.S [new file with mode: 0644]
common/lib/libc/arch/arm/string/ffs.S [new file with mode: 0644]
common/lib/libc/arch/arm/string/memcmp.S [new file with mode: 0644]
common/lib/libc/arch/arm/string/memcpy.S [new file with mode: 0644]
common/lib/libc/arch/arm/string/memcpy_arm.S [new file with mode: 0644]
common/lib/libc/arch/arm/string/memcpy_xscale.S [new file with mode: 0644]
common/lib/libc/arch/arm/string/memmove.S [new file with mode: 0644]
common/lib/libc/arch/arm/string/memset.S [new file with mode: 0644]
common/lib/libc/arch/arm/string/strcmp.S [new file with mode: 0644]
common/lib/libc/arch/arm/string/strncmp.S [new file with mode: 0644]
common/lib/libc/arch/hppa/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/hppa/atomic/atomic_cas_up.S [new file with mode: 0644]
common/lib/libc/arch/hppa/atomic/membar_ops.S [new file with mode: 0644]
common/lib/libc/arch/i386/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/i386/atomic/atomic.S [new file with mode: 0644]
common/lib/libc/arch/i386/gen/byte_swap_2.S [new file with mode: 0644]
common/lib/libc/arch/i386/gen/byte_swap_4.S [new file with mode: 0644]
common/lib/libc/arch/i386/string/ffs.S [new file with mode: 0644]
common/lib/libc/arch/i386/string/memchr.S [new file with mode: 0644]
common/lib/libc/arch/i386/string/memcmp.S [new file with mode: 0644]
common/lib/libc/arch/i386/string/memcpy.S [new file with mode: 0644]
common/lib/libc/arch/i386/string/memmove.S [new file with mode: 0644]
common/lib/libc/arch/i386/string/memset.S [new file with mode: 0644]
common/lib/libc/arch/i386/string/strcat.S [new file with mode: 0644]
common/lib/libc/arch/i386/string/strchr.S [new file with mode: 0644]
common/lib/libc/arch/i386/string/strcmp.S [new file with mode: 0644]
common/lib/libc/arch/i386/string/strcpy.S [new file with mode: 0644]
common/lib/libc/arch/i386/string/strlen.S [new file with mode: 0644]
common/lib/libc/arch/i386/string/strrchr.S [new file with mode: 0644]
common/lib/libc/arch/ia64/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/ia64/atomic/atomic.S [new file with mode: 0644]
common/lib/libc/arch/m68k/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/m68k/atomic/atomic_add.S [new file with mode: 0644]
common/lib/libc/arch/m68k/atomic/atomic_and.S [new file with mode: 0644]
common/lib/libc/arch/m68k/atomic/atomic_cas.S [new file with mode: 0644]
common/lib/libc/arch/m68k/atomic/atomic_cas_68000.S [new file with mode: 0644]
common/lib/libc/arch/m68k/atomic/atomic_dec.S [new file with mode: 0644]
common/lib/libc/arch/m68k/atomic/atomic_inc.S [new file with mode: 0644]
common/lib/libc/arch/m68k/atomic/atomic_op_asm.h [new file with mode: 0644]
common/lib/libc/arch/m68k/atomic/atomic_or.S [new file with mode: 0644]
common/lib/libc/arch/m68k/atomic/atomic_swap.S [new file with mode: 0644]
common/lib/libc/arch/m68k/gen/bswap16.S [new file with mode: 0644]
common/lib/libc/arch/m68k/gen/bswap32.S [new file with mode: 0644]
common/lib/libc/arch/m68k/gen/bswap64.S [new file with mode: 0644]
common/lib/libc/arch/m68k/gen/divsi3.S [new file with mode: 0644]
common/lib/libc/arch/m68k/gen/modsi3.S [new file with mode: 0644]
common/lib/libc/arch/m68k/gen/mulsi3.S [new file with mode: 0644]
common/lib/libc/arch/m68k/gen/udivsi3.S [new file with mode: 0644]
common/lib/libc/arch/m68k/gen/umodsi3.S [new file with mode: 0644]
common/lib/libc/arch/m68k/net/htonl.S [new file with mode: 0644]
common/lib/libc/arch/m68k/net/htons.S [new file with mode: 0644]
common/lib/libc/arch/m68k/net/ntohl.S [new file with mode: 0644]
common/lib/libc/arch/m68k/net/ntohs.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/bcmp.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/bcopy.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/bzero.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/ffs.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/memcmp.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/memcpy.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/memmove.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/memset.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/strcat.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/strchr.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/strcmp.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/strcpy.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/strlen.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/strncmp.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/strncpy.S [new file with mode: 0644]
common/lib/libc/arch/m68k/string/strrchr.S [new file with mode: 0644]
common/lib/libc/arch/mips/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/mips/atomic/atomic_add.S [new file with mode: 0644]
common/lib/libc/arch/mips/atomic/atomic_and.S [new file with mode: 0644]
common/lib/libc/arch/mips/atomic/atomic_cas.S [new file with mode: 0644]
common/lib/libc/arch/mips/atomic/atomic_cas_up.S [new file with mode: 0644]
common/lib/libc/arch/mips/atomic/atomic_dec.S [new file with mode: 0644]
common/lib/libc/arch/mips/atomic/atomic_inc.S [new file with mode: 0644]
common/lib/libc/arch/mips/atomic/atomic_op_asm.h [new file with mode: 0644]
common/lib/libc/arch/mips/atomic/atomic_or.S [new file with mode: 0644]
common/lib/libc/arch/mips/atomic/atomic_swap.S [new file with mode: 0644]
common/lib/libc/arch/mips/atomic/membar_ops.S [new file with mode: 0644]
common/lib/libc/arch/mips/gen/byte_swap_2.S [new file with mode: 0644]
common/lib/libc/arch/mips/gen/byte_swap_4.S [new file with mode: 0644]
common/lib/libc/arch/mips/gen/byte_swap_8.S [new file with mode: 0644]
common/lib/libc/arch/mips/string/bcopy.S [new file with mode: 0644]
common/lib/libc/arch/mips/string/ffs.S [new file with mode: 0644]
common/lib/libc/arch/mips/string/memcpy.S [new file with mode: 0644]
common/lib/libc/arch/mips/string/memmove.S [new file with mode: 0644]
common/lib/libc/arch/mips/string/strchr.S [new file with mode: 0644]
common/lib/libc/arch/mips/string/strcmp.S [new file with mode: 0644]
common/lib/libc/arch/mips/string/strlen.S [new file with mode: 0644]
common/lib/libc/arch/mips/string/strrchr.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/powerpc/atomic/atomic_add.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/atomic/atomic_and.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/atomic/atomic_cas.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/atomic/atomic_dec.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/atomic/atomic_inc.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/atomic/atomic_op_asm.h [new file with mode: 0644]
common/lib/libc/arch/powerpc/atomic/atomic_or.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/atomic/atomic_swap.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/atomic/membar_ops.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/string/bcopy.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/string/ffs.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/string/memcmp.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/string/memcpy.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/string/memmove.S [new file with mode: 0644]
common/lib/libc/arch/powerpc/string/strlen.S [new file with mode: 0644]
common/lib/libc/arch/powerpc64/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/powerpc64/atomic/atomic_add.S [new file with mode: 0644]
common/lib/libc/arch/powerpc64/atomic/atomic_and.S [new file with mode: 0644]
common/lib/libc/arch/powerpc64/atomic/atomic_cas.S [new file with mode: 0644]
common/lib/libc/arch/powerpc64/atomic/atomic_dec.S [new file with mode: 0644]
common/lib/libc/arch/powerpc64/atomic/atomic_inc.S [new file with mode: 0644]
common/lib/libc/arch/powerpc64/atomic/atomic_op_asm.h [new file with mode: 0644]
common/lib/libc/arch/powerpc64/atomic/atomic_or.S [new file with mode: 0644]
common/lib/libc/arch/powerpc64/atomic/atomic_swap.S [new file with mode: 0644]
common/lib/libc/arch/powerpc64/atomic/membar_ops.S [new file with mode: 0644]
common/lib/libc/arch/powerpc64/string/ffs.S [new file with mode: 0644]
common/lib/libc/arch/powerpc64/string/strlen.S [new file with mode: 0644]
common/lib/libc/arch/sh3/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/sh3/string/ffs.S [new file with mode: 0644]
common/lib/libc/arch/sh3/string/memcpy.S [new file with mode: 0644]
common/lib/libc/arch/sh3/string/memmove.S [new file with mode: 0644]
common/lib/libc/arch/sh3/string/memset.S [new file with mode: 0644]
common/lib/libc/arch/sparc/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/sparc/atomic/atomic_cas.S [new file with mode: 0644]
common/lib/libc/arch/sparc/atomic/atomic_op_asm.h [new file with mode: 0644]
common/lib/libc/arch/sparc/atomic/membar_ops.S [new file with mode: 0644]
common/lib/libc/arch/sparc/gen/mul.S [new file with mode: 0644]
common/lib/libc/arch/sparc/gen/saveregs.S [new file with mode: 0644]
common/lib/libc/arch/sparc/gen/umul.S [new file with mode: 0644]
common/lib/libc/arch/sparc/net/htonl.S [new file with mode: 0644]
common/lib/libc/arch/sparc/net/htons.S [new file with mode: 0644]
common/lib/libc/arch/sparc/net/ntohl.S [new file with mode: 0644]
common/lib/libc/arch/sparc/net/ntohs.S [new file with mode: 0644]
common/lib/libc/arch/sparc/string/bzero.S [new file with mode: 0644]
common/lib/libc/arch/sparc/string/ffs.S [new file with mode: 0644]
common/lib/libc/arch/sparc/string/memset.S [new file with mode: 0644]
common/lib/libc/arch/sparc/string/strlen.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/sparc64/atomic/atomic_add.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/atomic/atomic_and.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/atomic/atomic_cas.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/atomic/atomic_dec.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/atomic/atomic_inc.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/atomic/atomic_op_asm.h [new file with mode: 0644]
common/lib/libc/arch/sparc64/atomic/atomic_or.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/atomic/atomic_swap.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/atomic/membar_ops.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/gen/mul.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/gen/saveregs.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/gen/umul.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/net/htonl.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/net/htons.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/net/ntohl.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/net/ntohs.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/string/ffs.S [new file with mode: 0644]
common/lib/libc/arch/sparc64/string/strlen.S [new file with mode: 0644]
common/lib/libc/arch/vax/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/vax/gen/bswap16.S [new file with mode: 0644]
common/lib/libc/arch/vax/gen/bswap32.S [new file with mode: 0644]
common/lib/libc/arch/vax/gen/bswap64.S [new file with mode: 0644]
common/lib/libc/arch/vax/gen/udiv.S [new file with mode: 0644]
common/lib/libc/arch/vax/gen/urem.S [new file with mode: 0644]
common/lib/libc/arch/vax/string/memcpy.S [new file with mode: 0644]
common/lib/libc/arch/vax/string/memmove.S [new file with mode: 0644]
common/lib/libc/arch/vax/string/memset.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/atomic/Makefile.inc [new file with mode: 0644]
common/lib/libc/arch/x86_64/atomic/atomic.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/gen/byte_swap_2.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/gen/byte_swap_4.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/gen/byte_swap_8.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/bcmp.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/bcopy.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/bzero.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/ffs.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/memchr.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/memcmp.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/memcpy.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/memmove.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/memset.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/strcat.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/strchr.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/strcmp.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/strcpy.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/strlen.S [new file with mode: 0644]
common/lib/libc/arch/x86_64/string/strrchr.S [new file with mode: 0644]
common/lib/libc/atomic/atomic_add_32_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_add_32_nv_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_add_64_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_add_64_nv_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_and_32_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_and_32_nv_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_and_64_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_and_64_nv_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_dec_32_add.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_dec_32_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_dec_32_nv_add.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_dec_32_nv_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_dec_64_add.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_dec_64_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_dec_64_nv_add.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_dec_64_nv_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_inc_32_add.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_inc_32_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_inc_32_nv_add.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_inc_32_nv_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_inc_64_add.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_inc_64_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_inc_64_nv_add.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_inc_64_nv_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_init_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_init_testset.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_op_namespace.h [new file with mode: 0644]
common/lib/libc/atomic/atomic_or_32_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_or_32_nv_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_or_64_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_or_64_nv_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_swap_32_cas.c [new file with mode: 0644]
common/lib/libc/atomic/atomic_swap_64_cas.c [new file with mode: 0644]
common/lib/libc/atomic/membar_ops_nop.c [new file with mode: 0644]
common/lib/libc/gen/bswap16.c [new file with mode: 0644]
common/lib/libc/gen/bswap32.c [new file with mode: 0644]
common/lib/libc/gen/bswap64.c [new file with mode: 0644]
common/lib/libc/gen/ptree.c [new file with mode: 0644]
common/lib/libc/gen/rb.c [new file with mode: 0644]
common/lib/libc/gen/rpst.c [new file with mode: 0644]
common/lib/libc/gmon/mcount.c [new file with mode: 0644]
common/lib/libc/hash/rmd160/rmd160.c [new file with mode: 0644]
common/lib/libc/hash/sha1/sha1.c [new file with mode: 0644]
common/lib/libc/hash/sha2/sha2.c [new file with mode: 0644]
common/lib/libc/inet/inet_addr.c [new file with mode: 0644]
common/lib/libc/md/md4c.c [new file with mode: 0644]
common/lib/libc/md/md5c.c [new file with mode: 0644]
common/lib/libc/net/__cmsg_alignbytes.c [new file with mode: 0644]
common/lib/libc/net/htonl.c [new file with mode: 0644]
common/lib/libc/net/htons.c [new file with mode: 0644]
common/lib/libc/net/ntohl.c [new file with mode: 0644]
common/lib/libc/net/ntohs.c [new file with mode: 0644]
common/lib/libc/quad/adddi3.c [new file with mode: 0644]
common/lib/libc/quad/anddi3.c [new file with mode: 0644]
common/lib/libc/quad/ashldi3.c [new file with mode: 0644]
common/lib/libc/quad/ashrdi3.c [new file with mode: 0644]
common/lib/libc/quad/cmpdi2.c [new file with mode: 0644]
common/lib/libc/quad/divdi3.c [new file with mode: 0644]
common/lib/libc/quad/iordi3.c [new file with mode: 0644]
common/lib/libc/quad/lshldi3.c [new file with mode: 0644]
common/lib/libc/quad/lshrdi3.c [new file with mode: 0644]
common/lib/libc/quad/moddi3.c [new file with mode: 0644]
common/lib/libc/quad/muldi3.c [new file with mode: 0644]
common/lib/libc/quad/negdi2.c [new file with mode: 0644]
common/lib/libc/quad/notdi2.c [new file with mode: 0644]
common/lib/libc/quad/qdivrem.c [new file with mode: 0644]
common/lib/libc/quad/quad.h [new file with mode: 0644]
common/lib/libc/quad/subdi3.c [new file with mode: 0644]
common/lib/libc/quad/ucmpdi2.c [new file with mode: 0644]
common/lib/libc/quad/udivdi3.c [new file with mode: 0644]
common/lib/libc/quad/umoddi3.c [new file with mode: 0644]
common/lib/libc/quad/xordi3.c [new file with mode: 0644]
common/lib/libc/stdlib/_strtol.h [new file with mode: 0644]
common/lib/libc/stdlib/_strtoul.h [new file with mode: 0644]
common/lib/libc/stdlib/heapsort.c [new file with mode: 0644]
common/lib/libc/stdlib/random.c [new file with mode: 0644]
common/lib/libc/stdlib/strtoll.c [new file with mode: 0644]
common/lib/libc/stdlib/strtoul.c [new file with mode: 0644]
common/lib/libc/stdlib/strtoull.c [new file with mode: 0644]
common/lib/libc/stdlib/strtoumax.c [new file with mode: 0644]
common/lib/libc/string/bcmp.c [new file with mode: 0644]
common/lib/libc/string/bcopy.c [new file with mode: 0644]
common/lib/libc/string/bzero.c [new file with mode: 0644]
common/lib/libc/string/bzero2.c [new file with mode: 0644]
common/lib/libc/string/ffs.c [new file with mode: 0644]
common/lib/libc/string/memchr.c [new file with mode: 0644]
common/lib/libc/string/memcmp.c [new file with mode: 0644]
common/lib/libc/string/memcpy.c [new file with mode: 0644]
common/lib/libc/string/memmove.c [new file with mode: 0644]
common/lib/libc/string/memset.c [new file with mode: 0644]
common/lib/libc/string/memset2.c [new file with mode: 0644]
common/lib/libc/string/popcount32.c [new file with mode: 0644]
common/lib/libc/string/popcount64.c [new file with mode: 0644]
common/lib/libc/string/strcasecmp.c [new file with mode: 0644]
common/lib/libc/string/strcat.c [new file with mode: 0644]
common/lib/libc/string/strchr.c [new file with mode: 0644]
common/lib/libc/string/strcmp.c [new file with mode: 0644]
common/lib/libc/string/strcpy.c [new file with mode: 0644]
common/lib/libc/string/strlcat.c [new file with mode: 0644]
common/lib/libc/string/strlcpy.c [new file with mode: 0644]
common/lib/libc/string/strlen.c [new file with mode: 0644]
common/lib/libc/string/strncasecmp.c [new file with mode: 0644]
common/lib/libc/string/strncmp.c [new file with mode: 0644]
common/lib/libc/string/strncpy.c [new file with mode: 0644]
common/lib/libc/string/strrchr.c [new file with mode: 0644]
common/lib/libc/string/strsep.c [new file with mode: 0644]
common/lib/libc/string/strstr.c [new file with mode: 0644]
common/lib/libc/sys/cpuset.c [new file with mode: 0644]
lib/nbsd_libc/Makefile [new file with mode: 0644]
lib/nbsd_libc/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/__longjmp14.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/__setjmp14.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/__sigsetjmp14.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/_resumecontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/divrem.m4 [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/fabs.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/flt_rounds.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/fpgetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/fpgetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/fpgetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/fpsetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/fpsetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/fpsetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/nanf.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/resumecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/genassym.cf [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/gmon/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/__sigtramp2.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/alpha/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/arm/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gen/_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gen/alloca.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gen/fabs.c [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gen/flt_rounds.c [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gen/nanf.c [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gen/resumecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gen/setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gen/sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/hardfloat/fpgetmask.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/hardfloat/fpgetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/arm/hardfloat/fpgetsticky.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/hardfloat/fpsetmask.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/hardfloat/fpsetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/arm/hardfloat/fpsetsticky.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/arm/softfloat/arm-gcc.h [new file with mode: 0644]
lib/nbsd_libc/arch/arm/softfloat/milieu.h [new file with mode: 0644]
lib/nbsd_libc/arch/arm/softfloat/softfloat.h [new file with mode: 0644]
lib/nbsd_libc/arch/arm/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/arm/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/arm/string/bcopy.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/string/bzero.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/__sigtramp2.S [new file with mode: 0755]
lib/nbsd_libc/arch/arm/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/arm/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/DEFS.h [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/__longjmp14.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/__setjmp14.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/__sigsetjmp14.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/_resumecontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/fabs.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/flt_rounds.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/fpgetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/fpgetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/fpgetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/fpsetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/fpsetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/fpsetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/nanf.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/resumecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/string/bcmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/string/bzero.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/string/ffs.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/string/strlcpy.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/__sigtramp2.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/hppa/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/i386/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/alloca.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/divsi3.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/fabs.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/fixdfsi.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/fixunsdfsi.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/flt_rounds.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/fpclassifyl.c [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/fpgetmask.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/fpgetround.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/fpgetsticky.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/fpsetmask.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/fpsetround.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/fpsetsticky.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/infinityl.c [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/isfinitel.c [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/isinfl.c [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/isnanl.c [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/nanf.c [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/resumecontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/signbitl.c [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/gen/udivsi3.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/i386/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/i386/stdlib/abs.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/stdlib/div.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/stdlib/labs.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/stdlib/ldiv.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/stdlib/llabs.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/i386/string/bcmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/string/bcopy.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/string/bzero.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/string/index.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/string/rindex.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/string/strncmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/string/swab.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/__sigtramp2.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/i386/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/gen/flt_rounds.c [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/gen/fpgetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/gen/fpgetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/gen/fpsetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/gen/fpsetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/__sigtramp2.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/ia64/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/DEFS.h [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/adddf3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/addsf3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/alloca.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/ashlsi3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/ashrsi3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/cmpdf2.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/cmpsf2.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/divdf3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/divsf3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/extendsfdf2.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/fabs.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/fixdfsi.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/fixunsdfsi.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/floatsidf.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/flt_rounds.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/flt_rounds_softfloat.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/fpclassifyl.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/fpfake.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/fpgetmask.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/fpgetround.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/fpgetsticky.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/fpsetmask.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/fpsetround.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/fpsetsticky.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/infinityl.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/isfinitel.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/isinfl.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/isnanl.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/ldexp_881.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/longjmp.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/lshlsi3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/lshrsi3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/modf.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/muldf3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/mulsf3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/nanf.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/negdf2.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/negsf2.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/resumecontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/signbitl.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/subdf3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/subsf3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/truncdfsf2.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/gen/umulsi3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/quad/ashldi3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/quad/ashrdi3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/quad/lshrdi3.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/softfloat/m68k-gcc.h [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/softfloat/milieu.h [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/softfloat/softfloat.h [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/stdlib/abs.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/stdlib/llabs.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/string/memccpy.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/string/swab.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/__mmap.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/__sigtramp2.S [new file with mode: 0755]
lib/nbsd_libc/arch/m68k/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/_lwp_getprivate.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/mremap.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/m68k/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/mips/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/_resumecontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/cacheflush.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/fabs.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/flt_rounds.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/fpgetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/fpgetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/fpgetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/fpsetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/fpsetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/fpsetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/ldexp.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/longjmp.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/modf.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/nanf.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/resumecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/genassym.cf [new file with mode: 0644]
lib/nbsd_libc/arch/mips/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/mips/softfloat/milieu.h [new file with mode: 0644]
lib/nbsd_libc/arch/mips/softfloat/mips-gcc.h [new file with mode: 0644]
lib/nbsd_libc/arch/mips/softfloat/softfloat.h [new file with mode: 0644]
lib/nbsd_libc/arch/mips/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/mips/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/mips/string/bcmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/string/bzero.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/__sigtramp2.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/mips/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/__setjmp14.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/__sigsetjmp14.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/fabs.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/flt_rounds.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/fpgetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/fpgetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/fpgetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/fpsetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/fpsetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/fpsetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/nanf.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/resumecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/gen/syncicache.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/genassym.cf [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/softfloat/milieu.h [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/softfloat/powerpc-gcc.h [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/softfloat/softfloat.h [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/string/bzero.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/__sigtramp2.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/__setjmp14.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/__sigsetjmp14.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/fabs.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/flt_rounds.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/fpgetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/fpgetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/fpgetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/fpsetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/fpsetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/fpsetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/nanf.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/resumecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/gen/syncicache.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/string/bzero.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/__sigtramp2.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/powerpc64/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gen/_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gen/fabs.c [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gen/flt_rounds.c [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gen/nanf.c [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gen/resumecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gen/setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gen/sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/net/htonl.c [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/net/htons.c [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/net/ntohl.c [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/net/ntohs.c [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/softfloat/milieu.h [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/softfloat/sh3-gcc.h [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/softfloat/softfloat.h [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/string/bcopy.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/string/bzero.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/__sigtramp2.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/sh3/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/divrem.m4 [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/fabs.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/fixunsdfsi.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/flt_rounds.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/fpgetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/fpgetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/fpgetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/fpsetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/fpsetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/fpsetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/longjmp.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/modf.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/nanf.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/resumecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/stdlib/llabs.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/__sigtramp2.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/divrem.m4 [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/fabs.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/fixunsdfsi.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/flt_rounds.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/fpclassifyl.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/fpgetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/fpgetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/fpgetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/fpsetmask.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/fpsetround.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/fpsetsticky.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/infinityl.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/isfinitel.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/isinfl.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/isnanl.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/longjmp.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/modf.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/nanf.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/resumecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/signbitl.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/softfloat/milieu.h [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/softfloat/qp.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/softfloat/softfloat-qp.h [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/softfloat/softfloat-wrapper.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/softfloat/softfloat.h [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/softfloat/sparc64-gcc.h [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/stdlib/abs.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/string/memcpy.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/string/memset.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/__sigtramp2.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/sparc64/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/DEFS.h [new file with mode: 0644]
lib/nbsd_libc/arch/vax/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/vax/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/__longjmp14.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/__setjmp14.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/__sigsetjmp14.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/alloca.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/byte_swap_2.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/byte_swap_4.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/fabs.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/fpclassifyd.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/fpclassifyf.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/frexp.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/infinity.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/infinityf.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/infinityl.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/isfinited.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/isfinitef.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/isinf.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/isnan.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/ldexp.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/modf.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/resumecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/signbitd.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/signbitf.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/genassym.cf [new file with mode: 0644]
lib/nbsd_libc/arch/vax/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/vax/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/vax/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/vax/string/bcmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/string/bcopy.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/string/bzero.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/string/ffs.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/string/index.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/string/memcmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/__sigtramp3.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/execl.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/execle.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/execlp.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/vax/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/SYS.h [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gdtoa/arith.h [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gdtoa/gd_qnan.h [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/__setjmp14.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/__sigsetjmp14.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/_lwp.c [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/alloca.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/fabs.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/flt_rounds.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/fpclassifyl.c [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/fpgetmask.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/fpgetround.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/fpgetsticky.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/fpsetmask.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/fpsetround.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/fpsetsticky.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/infinityl.c [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/isfinitel.c [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/isinfl.c [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/isnanl.c [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/makecontext.c [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/nanf.c [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/resumecontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/signbitl.c [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/gen/swapcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/stdlib/abs.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/stdlib/div.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/stdlib/labs.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/stdlib/ldiv.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/string/strncmp.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/string/swab.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/__clone.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/__sigaction14_sigtramp.c [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/__sigtramp2.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/__syscall.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/__vfork14.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/brk.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/cerror.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/exect.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/fork.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/getcontext.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/pipe.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/ptrace.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/sbrk.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/shmat.S [new file with mode: 0644]
lib/nbsd_libc/arch/x86_64/sys/syscall.S [new file with mode: 0644]
lib/nbsd_libc/atomic/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/atomic/atomic_add.3 [new file with mode: 0644]
lib/nbsd_libc/atomic/atomic_and.3 [new file with mode: 0644]
lib/nbsd_libc/atomic/atomic_cas.3 [new file with mode: 0644]
lib/nbsd_libc/atomic/atomic_dec.3 [new file with mode: 0644]
lib/nbsd_libc/atomic/atomic_inc.3 [new file with mode: 0644]
lib/nbsd_libc/atomic/atomic_ops.3 [new file with mode: 0644]
lib/nbsd_libc/atomic/atomic_or.3 [new file with mode: 0644]
lib/nbsd_libc/atomic/atomic_swap.3 [new file with mode: 0644]
lib/nbsd_libc/atomic/membar_ops.3 [new file with mode: 0644]
lib/nbsd_libc/cdb/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/cdb/cdb.5 [new file with mode: 0644]
lib/nbsd_libc/cdb/cdbr.3 [new file with mode: 0644]
lib/nbsd_libc/cdb/cdbr.c [new file with mode: 0644]
lib/nbsd_libc/cdb/cdbw.3 [new file with mode: 0644]
lib/nbsd_libc/cdb/cdbw.c [new file with mode: 0644]
lib/nbsd_libc/citrus/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_aliasname_local.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_bcs.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_bcs.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_bcs_strtol.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_bcs_strtoul.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_csmapper.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_csmapper.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_ctype.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_ctype.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_ctype_fallback.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_ctype_fallback.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_ctype_local.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_ctype_template.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_db.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_db.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_db_factory.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_db_factory.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_db_file.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_db_hash.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_db_hash.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_esdb.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_esdb.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_esdb_file.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_fix_grouping.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_hash.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_hash.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_iconv.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_iconv.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_iconv_local.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lc_ctype.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lc_messages.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lc_messages.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lc_monetary.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lc_monetary.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lc_numeric.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lc_numeric.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lc_template.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lc_template_decl.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lc_time.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lc_time.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lookup.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lookup.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lookup_factory.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lookup_factory.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_lookup_file.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_mapper.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_mapper.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_mapper_local.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_memstream.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_memstream.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_mmap.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_mmap.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_module.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_module.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_namespace.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_none.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_none.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_pivot_factory.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_pivot_factory.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_pivot_file.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_prop.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_prop.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_region.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_stdenc.c [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_stdenc.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_stdenc_local.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_stdenc_template.h [new file with mode: 0644]
lib/nbsd_libc/citrus/citrus_types.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_big5.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_big5.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_dechanyu.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_dechanyu.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_euc.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_euc.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_euctw.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_euctw.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_gbk2k.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_gbk2k.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_hz.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_hz.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_iconv_none.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_iconv_none.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_iconv_std.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_iconv_std.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_iconv_std_local.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_iso2022.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_iso2022.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_johab.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_johab.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mapper_646.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mapper_646.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mapper_none.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mapper_none.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mapper_serial.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mapper_serial.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mapper_std.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mapper_std.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mapper_std_file.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mapper_std_local.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mapper_zone.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mapper_zone.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mskanji.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_mskanji.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_ues.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_ues.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_utf1632.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_utf1632.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_utf7.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_utf7.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_utf8.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_utf8.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_viqr.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_viqr.h [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_zw.c [new file with mode: 0644]
lib/nbsd_libc/citrus/modules/citrus_zw.h [new file with mode: 0644]
lib/nbsd_libc/compat-43/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat-43/creat.3 [new file with mode: 0644]
lib/nbsd_libc/compat-43/creat.c [new file with mode: 0644]
lib/nbsd_libc/compat-43/getdtablesize.3 [new file with mode: 0644]
lib/nbsd_libc/compat-43/getdtablesize.c [new file with mode: 0644]
lib/nbsd_libc/compat-43/gethostid.3 [new file with mode: 0644]
lib/nbsd_libc/compat-43/gethostid.c [new file with mode: 0644]
lib/nbsd_libc/compat-43/getwd.c [new file with mode: 0644]
lib/nbsd_libc/compat-43/killpg.3 [new file with mode: 0644]
lib/nbsd_libc/compat-43/killpg.c [new file with mode: 0644]
lib/nbsd_libc/compat-43/sethostid.c [new file with mode: 0644]
lib/nbsd_libc/compat-43/setpgrp.c [new file with mode: 0644]
lib/nbsd_libc/compat-43/setrgid.c [new file with mode: 0644]
lib/nbsd_libc/compat-43/setruid.3 [new file with mode: 0644]
lib/nbsd_libc/compat-43/setruid.c [new file with mode: 0644]
lib/nbsd_libc/compat-43/sigblock.3 [new file with mode: 0644]
lib/nbsd_libc/compat-43/sigcompat.c [new file with mode: 0644]
lib/nbsd_libc/compat-43/sigpause.3 [new file with mode: 0644]
lib/nbsd_libc/compat-43/sigsetmask.3 [new file with mode: 0644]
lib/nbsd_libc/compat-43/sigvec.3 [new file with mode: 0644]
lib/nbsd_libc/compat/Makefile [new file with mode: 0644]
lib/nbsd_libc/compat/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/gen/compat__setjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/gen/compat_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/gen/compat_sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/sys/compat_Ovfork.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/sys/compat___sigreturn14.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/sys/compat___sigtramp1.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/sys/compat_sigaction.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/sys/compat_sigpending.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/sys/compat_sigprocmask.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/sys/compat_sigreturn.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/alpha/sys/compat_sigsuspend.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/gen/compat_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/gen/compat_sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/sys/compat_Ovfork.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/sys/compat___sigreturn14.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/sys/compat___sigtramp1.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/sys/compat_sigaction.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/sys/compat_sigpending.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/sys/compat_sigprocmask.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/sys/compat_sigreturn.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/arm/sys/compat_sigsuspend.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/locale/compat_setlocale32.c [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/sys/compat_Ovfork.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/sys/compat___sigreturn14.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/sys/compat_sigaction.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/sys/compat_sigpending.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/sys/compat_sigprocmask.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/sys/compat_sigreturn.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/hppa/sys/compat_sigsuspend.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/gen/compat_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/gen/compat_sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/sys/compat_Ovfork.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/sys/compat___sigreturn14.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/sys/compat___sigtramp1.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/sys/compat_sigaction.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/sys/compat_sigpending.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/sys/compat_sigprocmask.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/sys/compat_sigreturn.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/i386/sys/compat_sigsuspend.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/ia64/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/ia64/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/ia64/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/gen/compat_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/gen/compat_sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/sys/compat_Ovfork.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/sys/compat___sigreturn14.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/sys/compat___sigtramp1.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/sys/compat_sigaction.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/sys/compat_sigpending.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/sys/compat_sigprocmask.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/sys/compat_sigreturn.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/m68k/sys/compat_sigsuspend.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/gen/compat_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/gen/compat_sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/sys/compat_Ovfork.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/sys/compat___sigreturn14.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/sys/compat___sigtramp1.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/sys/compat_sigaction.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/sys/compat_sigpending.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/sys/compat_sigprocmask.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/sys/compat_sigreturn.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/mips/sys/compat_sigsuspend.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/gen/compat_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/gen/compat_sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/sys/compat_Ovfork.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/sys/compat___sigreturn14.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/sys/compat___sigtramp1.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigaction13.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigpending13.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigprocmask13.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigreturn13.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigsuspend13.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc64/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc64/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc64/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc64/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc64/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/powerpc64/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/gen/compat_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/gen/compat_sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/sys/compat_Ovfork.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/sys/compat___sigreturn14.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/sys/compat___sigtramp1.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/sys/compat_sigaction.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/sys/compat_sigpending.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/sys/compat_sigprocmask.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/sys/compat_sigreturn.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sh3/sys/compat_sigsuspend.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/gen/compat_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/gen/compat_sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/sys/compat_Ovfork.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/sys/compat___sigreturn14.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/sys/compat___sigtramp1.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/sys/compat_sigaction.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/sys/compat_sigpending.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/sys/compat_sigprocmask.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/sys/compat_sigreturn.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc/sys/compat_sigsuspend.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/gen/compat_setjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/gen/compat_sigsetjmp.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/sys/compat_Ovfork.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/sys/compat___sigreturn14.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/sys/compat___sigtramp1.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigaction.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigpending.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigprocmask.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigreturn.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigsuspend.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/sys/compat_Ovfork.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/sys/compat___sigreturn14.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/sys/compat___sigtramp2.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/sys/compat_sigaction13.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/sys/compat_sigpending13.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/sys/compat_sigprocmask13.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/sys/compat_sigreturn13.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/vax/sys/compat_sigsuspend13.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/sys/compat_Ovfork.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/sys/compat___semctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/sys/compat___sigreturn14.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/sys/compat_msgctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/sys/compat_shmctl.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigaction.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigpending.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigprocmask.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigreturn.S [new file with mode: 0644]
lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigsuspend.S [new file with mode: 0644]
lib/nbsd_libc/compat/db/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/db/hash/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/db/hash/compat_ndbmdatum.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat___fts13.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat___fts30.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat___fts31.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat___fts32.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat___fts50.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat___glob13.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat__readdir_unlocked30.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat__sys_errlist.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat__sys_nerr.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat__sys_siglist.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_alphasort.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_devname.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_errlist.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_frexp_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_fts.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_getmntinfo.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_getpwent.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_glob.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_lastlogx.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_ldexp_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_modf_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_opendir.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_readdir.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_scandir.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_siglist.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_signame.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_sigsetops.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_time.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_times.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_timezone.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_unvis.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_utime.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_utmp.c [new file with mode: 0644]
lib/nbsd_libc/compat/gen/compat_utmpx.c [new file with mode: 0644]
lib/nbsd_libc/compat/include/aio.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/dirent.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/fstypes.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/fts.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/glob.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/locale.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/lwp.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/mqueue.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/ndbm.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/ns.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/pwd.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/rpc/pmap_clnt.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/rpc/rpcb_clnt.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/setjmp.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/signal.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/stdlib.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/time.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/unistd.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/utime.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/utmp.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/utmpx.h [new file with mode: 0644]
lib/nbsd_libc/compat/include/vis.h [new file with mode: 0644]
lib/nbsd_libc/compat/locale/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/locale/compat_setlocale1.c [new file with mode: 0644]
lib/nbsd_libc/compat/locale/compat_setlocale32.c [new file with mode: 0644]
lib/nbsd_libc/compat/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/net/compat_ns_addr.c [new file with mode: 0644]
lib/nbsd_libc/compat/net/compat_ns_ntoa.c [new file with mode: 0644]
lib/nbsd_libc/compat/rpc/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/rpc/compat_pmap_rmtcall.c [new file with mode: 0644]
lib/nbsd_libc/compat/rpc/compat_rpcb.c [new file with mode: 0644]
lib/nbsd_libc/compat/shlib_version [new file with mode: 0644]
lib/nbsd_libc/compat/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/stdlib/compat_unsetenv.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/Lint_Ovfork.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat___fhstat30.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat___msgctl13.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat___ntp_gettime30.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat___semctl13.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat___shmctl13.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat___stat13.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat___stat30.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat__lwp_park.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_adjtime.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_aio_suspend.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_clock.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_fhopen.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_fhstatvfs.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_fhstatvfs1.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_getdents.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_getdirentries.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_getfh.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_getrusage.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_gettimeofday.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_itimer.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_kevent.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_lfs_segwait.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_mknod.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_mount.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_mqueue.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_msync.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_nanosleep.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_ntp_gettime.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_sched.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_select.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_semctl.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_settimeofday.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_sigaltstack.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_sigtimedwait.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_socket.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_stat.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_statfs.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_timer.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_utimes.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/compat_wait4.c [new file with mode: 0644]
lib/nbsd_libc/compat/sys/getdirentries.3 [new file with mode: 0644]
lib/nbsd_libc/compat/time/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/compat/time/compat_difftime.c [new file with mode: 0644]
lib/nbsd_libc/compat/time/compat_localtime.c [new file with mode: 0644]
lib/nbsd_libc/db/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/db/README [new file with mode: 0644]
lib/nbsd_libc/db/btree/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_close.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_conv.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_debug.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_delete.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_get.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_open.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_overflow.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_page.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_put.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_search.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_seq.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_split.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/bt_utils.c [new file with mode: 0644]
lib/nbsd_libc/db/btree/btree.h [new file with mode: 0644]
lib/nbsd_libc/db/btree/extern.h [new file with mode: 0644]
lib/nbsd_libc/db/changelog [new file with mode: 0644]
lib/nbsd_libc/db/db/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/db/db/db.c [new file with mode: 0644]
lib/nbsd_libc/db/db2netbsd [new file with mode: 0755]
lib/nbsd_libc/db/hash/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/db/hash/README [new file with mode: 0644]
lib/nbsd_libc/db/hash/extern.h [new file with mode: 0644]
lib/nbsd_libc/db/hash/hash.c [new file with mode: 0644]
lib/nbsd_libc/db/hash/hash.h [new file with mode: 0644]
lib/nbsd_libc/db/hash/hash_bigkey.c [new file with mode: 0644]
lib/nbsd_libc/db/hash/hash_buf.c [new file with mode: 0644]
lib/nbsd_libc/db/hash/hash_func.c [new file with mode: 0644]
lib/nbsd_libc/db/hash/hash_log2.c [new file with mode: 0644]
lib/nbsd_libc/db/hash/hash_page.c [new file with mode: 0644]
lib/nbsd_libc/db/hash/ndbm.c [new file with mode: 0644]
lib/nbsd_libc/db/hash/ndbmdatum.c [new file with mode: 0644]
lib/nbsd_libc/db/hash/page.h [new file with mode: 0644]
lib/nbsd_libc/db/man/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/db/man/btree.3 [new file with mode: 0644]
lib/nbsd_libc/db/man/dbm_clearerr.3 [new file with mode: 0644]
lib/nbsd_libc/db/man/dbopen.3 [new file with mode: 0644]
lib/nbsd_libc/db/man/hash.3 [new file with mode: 0644]
lib/nbsd_libc/db/man/mpool.3 [new file with mode: 0644]
lib/nbsd_libc/db/man/recno.3 [new file with mode: 0644]
lib/nbsd_libc/db/mpool/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/db/mpool/README [new file with mode: 0644]
lib/nbsd_libc/db/mpool/mpool.c [new file with mode: 0644]
lib/nbsd_libc/db/recno/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/db/recno/extern.h [new file with mode: 0644]
lib/nbsd_libc/db/recno/rec_close.c [new file with mode: 0644]
lib/nbsd_libc/db/recno/rec_delete.c [new file with mode: 0644]
lib/nbsd_libc/db/recno/rec_get.c [new file with mode: 0644]
lib/nbsd_libc/db/recno/rec_open.c [new file with mode: 0644]
lib/nbsd_libc/db/recno/rec_put.c [new file with mode: 0644]
lib/nbsd_libc/db/recno/rec_search.c [new file with mode: 0644]
lib/nbsd_libc/db/recno/rec_seq.c [new file with mode: 0644]
lib/nbsd_libc/db/recno/rec_utils.c [new file with mode: 0644]
lib/nbsd_libc/db/recno/recno.h [new file with mode: 0644]
lib/nbsd_libc/dlfcn/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/dlfcn/dlfcn_elf.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/gdtoa/README [new file with mode: 0644]
lib/nbsd_libc/gdtoa/_strtof.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/_strtold.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/arithchk.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/dmisc.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/dtoa.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/g_Qfmt.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/g__fmt.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/g_ddfmt.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/g_dfmt.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/g_ffmt.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/g_xLfmt.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/g_xfmt.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/gdtoa.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/gdtoa.h [new file with mode: 0644]
lib/nbsd_libc/gdtoa/gdtoa_locks.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/gdtoaimp.h [new file with mode: 0644]
lib/nbsd_libc/gdtoa/gethex.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/gmisc.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/hd_init.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/hdtoa.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/hexnan.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/ldtoa.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/makefile [new file with mode: 0644]
lib/nbsd_libc/gdtoa/misc.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/qnan.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/smisc.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtoIQ.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtoId.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtoIdd.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtoIf.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtoIg.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtoIx.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtoIxL.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtod.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtodI.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtodg.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtodnrp.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtof.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtof_vaxf.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtold_pQ.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtold_px.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtold_pxL.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtold_subr.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtopQ.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtopd.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtopdd.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtopf.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtopx.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtopxL.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtorQ.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtord.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtordd.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtorf.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtorx.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/strtorxL.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/sum.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/ulp.c [new file with mode: 0644]
lib/nbsd_libc/gdtoa/xsum0.out [new file with mode: 0644]
lib/nbsd_libc/gen/Lint___setjmp14.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint___sigsetjmp14.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint__setjmp.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_alloca.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_bswap16.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_bswap32.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_bswap64.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_fabs.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_flt_rounds.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_fpgetmask.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_fpgetround.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_fpgetsticky.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_fpsetmask.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_fpsetround.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_fpsetsticky.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_frexp.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_ldexp.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_modf.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_resumecontext.c [new file with mode: 0644]
lib/nbsd_libc/gen/Lint_swapcontext.c [new file with mode: 0644]
lib/nbsd_libc/gen/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/gen/_err.c [new file with mode: 0644]
lib/nbsd_libc/gen/_errno.c [new file with mode: 0644]
lib/nbsd_libc/gen/_errx.c [new file with mode: 0644]
lib/nbsd_libc/gen/_lwp_makecontext.3 [new file with mode: 0644]
lib/nbsd_libc/gen/_sysconf.c [new file with mode: 0644]
lib/nbsd_libc/gen/_verr.c [new file with mode: 0644]
lib/nbsd_libc/gen/_verrx.c [new file with mode: 0644]
lib/nbsd_libc/gen/_vwarn.c [new file with mode: 0644]
lib/nbsd_libc/gen/_vwarnx.c [new file with mode: 0644]
lib/nbsd_libc/gen/_warn.c [new file with mode: 0644]
lib/nbsd_libc/gen/_warnx.c [new file with mode: 0644]
lib/nbsd_libc/gen/alarm.3 [new file with mode: 0644]
lib/nbsd_libc/gen/alarm.c [new file with mode: 0644]
lib/nbsd_libc/gen/alphasort.c [new file with mode: 0644]
lib/nbsd_libc/gen/arc4random.3 [new file with mode: 0644]
lib/nbsd_libc/gen/arc4random.c [new file with mode: 0644]
lib/nbsd_libc/gen/assert.c [new file with mode: 0644]
lib/nbsd_libc/gen/basename.3 [new file with mode: 0644]
lib/nbsd_libc/gen/basename.c [new file with mode: 0644]
lib/nbsd_libc/gen/bswap.3 [new file with mode: 0644]
lib/nbsd_libc/gen/cgetcap.3 [new file with mode: 0644]
lib/nbsd_libc/gen/clock.3 [new file with mode: 0644]
lib/nbsd_libc/gen/clock.c [new file with mode: 0644]
lib/nbsd_libc/gen/closedir.c [new file with mode: 0644]
lib/nbsd_libc/gen/closefrom.3 [new file with mode: 0644]
lib/nbsd_libc/gen/closefrom.c [new file with mode: 0644]
lib/nbsd_libc/gen/confstr.3 [new file with mode: 0644]
lib/nbsd_libc/gen/confstr.c [new file with mode: 0644]
lib/nbsd_libc/gen/cpuset.3 [new file with mode: 0644]
lib/nbsd_libc/gen/ctermid.3 [new file with mode: 0644]
lib/nbsd_libc/gen/ctermid.c [new file with mode: 0644]
lib/nbsd_libc/gen/ctype.3 [new file with mode: 0644]
lib/nbsd_libc/gen/ctype_.c [new file with mode: 0644]
lib/nbsd_libc/gen/daemon.3 [new file with mode: 0644]
lib/nbsd_libc/gen/daemon.c [new file with mode: 0644]
lib/nbsd_libc/gen/dehumanize_number.c [new file with mode: 0644]
lib/nbsd_libc/gen/devname.3 [new file with mode: 0644]
lib/nbsd_libc/gen/devname.c [new file with mode: 0644]
lib/nbsd_libc/gen/directory.3 [new file with mode: 0644]
lib/nbsd_libc/gen/dirent_private.h [new file with mode: 0644]
lib/nbsd_libc/gen/dirname.3 [new file with mode: 0644]
lib/nbsd_libc/gen/dirname.c [new file with mode: 0644]
lib/nbsd_libc/gen/disklabel.c [new file with mode: 0644]
lib/nbsd_libc/gen/endutxent.3 [new file with mode: 0644]
lib/nbsd_libc/gen/err.3 [new file with mode: 0644]
lib/nbsd_libc/gen/err.c [new file with mode: 0644]
lib/nbsd_libc/gen/errlist.awk [new file with mode: 0644]
lib/nbsd_libc/gen/errno.c [new file with mode: 0644]
lib/nbsd_libc/gen/errx.c [new file with mode: 0644]
lib/nbsd_libc/gen/exec.3 [new file with mode: 0644]
lib/nbsd_libc/gen/execl.c [new file with mode: 0644]
lib/nbsd_libc/gen/execle.c [new file with mode: 0644]
lib/nbsd_libc/gen/execlp.c [new file with mode: 0644]
lib/nbsd_libc/gen/execv.c [new file with mode: 0644]
lib/nbsd_libc/gen/execvp.c [new file with mode: 0644]
lib/nbsd_libc/gen/extattr.3 [new file with mode: 0644]
lib/nbsd_libc/gen/extattr.c [new file with mode: 0644]
lib/nbsd_libc/gen/fabs_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/fmtcheck.3 [new file with mode: 0644]
lib/nbsd_libc/gen/fmtcheck.c [new file with mode: 0644]
lib/nbsd_libc/gen/fmtmsg.3 [new file with mode: 0644]
lib/nbsd_libc/gen/fmtmsg.c [new file with mode: 0644]
lib/nbsd_libc/gen/fnmatch.3 [new file with mode: 0644]
lib/nbsd_libc/gen/fnmatch.c [new file with mode: 0644]
lib/nbsd_libc/gen/fpclassify.3 [new file with mode: 0644]
lib/nbsd_libc/gen/fpclassifyd_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/fpclassifyf_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/fpclassifyl_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/fpgetmask.3 [new file with mode: 0644]
lib/nbsd_libc/gen/fstab.c [new file with mode: 0644]
lib/nbsd_libc/gen/ftok.3 [new file with mode: 0644]
lib/nbsd_libc/gen/ftok.c [new file with mode: 0644]
lib/nbsd_libc/gen/fts.3 [new file with mode: 0644]
lib/nbsd_libc/gen/fts.c [new file with mode: 0644]
lib/nbsd_libc/gen/ftw.3 [new file with mode: 0644]
lib/nbsd_libc/gen/ftw.c [new file with mode: 0644]
lib/nbsd_libc/gen/getbsize.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getbsize.c [new file with mode: 0644]
lib/nbsd_libc/gen/getcap.c [new file with mode: 0644]
lib/nbsd_libc/gen/getcwd.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getcwd.c [new file with mode: 0644]
lib/nbsd_libc/gen/getdevmajor.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getdevmajor.c [new file with mode: 0644]
lib/nbsd_libc/gen/getdiskbyname.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getdomainname.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getdomainname.c [new file with mode: 0644]
lib/nbsd_libc/gen/getfsent.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getgrent.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getgrent.c [new file with mode: 0644]
lib/nbsd_libc/gen/getgrouplist.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getgrouplist.c [new file with mode: 0644]
lib/nbsd_libc/gen/getgroupmembership.c [new file with mode: 0644]
lib/nbsd_libc/gen/gethostname.3 [new file with mode: 0644]
lib/nbsd_libc/gen/gethostname.c [new file with mode: 0644]
lib/nbsd_libc/gen/getlastlogx.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getloadavg.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getloadavg.c [new file with mode: 0644]
lib/nbsd_libc/gen/getlogin.c [new file with mode: 0644]
lib/nbsd_libc/gen/getmntinfo.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getmntinfo.c [new file with mode: 0644]
lib/nbsd_libc/gen/getnetgrent.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getnetgrent.c [new file with mode: 0644]
lib/nbsd_libc/gen/getpagesize.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getpagesize.c [new file with mode: 0644]
lib/nbsd_libc/gen/getpass.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getpass.c [new file with mode: 0644]
lib/nbsd_libc/gen/getprogname.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getprogname.c [new file with mode: 0644]
lib/nbsd_libc/gen/getpwent.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getpwent.c [new file with mode: 0644]
lib/nbsd_libc/gen/getttyent.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getttyent.c [new file with mode: 0644]
lib/nbsd_libc/gen/getusershell.3 [new file with mode: 0644]
lib/nbsd_libc/gen/getusershell.c [new file with mode: 0644]
lib/nbsd_libc/gen/glob.3 [new file with mode: 0644]
lib/nbsd_libc/gen/glob.c [new file with mode: 0644]
lib/nbsd_libc/gen/gr_private.h [new file with mode: 0644]
lib/nbsd_libc/gen/humanize_number.3 [new file with mode: 0644]
lib/nbsd_libc/gen/humanize_number.c [new file with mode: 0644]
lib/nbsd_libc/gen/infinity_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/infinityf_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/infinityl_dbl_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/infinityl_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/initdir.c [new file with mode: 0644]
lib/nbsd_libc/gen/initgroups.3 [new file with mode: 0644]
lib/nbsd_libc/gen/initgroups.c [new file with mode: 0644]
lib/nbsd_libc/gen/isalnum.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isalpha.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isascii.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isascii.c [new file with mode: 0644]
lib/nbsd_libc/gen/isatty.c [new file with mode: 0644]
lib/nbsd_libc/gen/isblank.3 [new file with mode: 0644]
lib/nbsd_libc/gen/iscntrl.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isctype.c [new file with mode: 0644]
lib/nbsd_libc/gen/isdigit.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isfinite.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isfinited_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/isfinitef_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/isfinitel_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/isgraph.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isgreater.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isinf.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isinfd_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/isinff_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/isinfl_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/islower.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isnan.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isnand_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/isnanf_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/isnanl_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/isnormal.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isprint.3 [new file with mode: 0644]
lib/nbsd_libc/gen/ispunct.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isspace.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isupper.3 [new file with mode: 0644]
lib/nbsd_libc/gen/isxdigit.3 [new file with mode: 0644]
lib/nbsd_libc/gen/ldexp_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/lockf.3 [new file with mode: 0644]
lib/nbsd_libc/gen/lockf.c [new file with mode: 0644]
lib/nbsd_libc/gen/makecontext.3 [new file with mode: 0644]
lib/nbsd_libc/gen/modf_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/nftw.c [new file with mode: 0644]
lib/nbsd_libc/gen/nice.3 [new file with mode: 0644]
lib/nbsd_libc/gen/nice.c [new file with mode: 0644]
lib/nbsd_libc/gen/nlist.3 [new file with mode: 0644]
lib/nbsd_libc/gen/nlist.c [new file with mode: 0644]
lib/nbsd_libc/gen/nlist_aout.c [new file with mode: 0644]
lib/nbsd_libc/gen/nlist_coff.c [new file with mode: 0644]
lib/nbsd_libc/gen/nlist_ecoff.c [new file with mode: 0644]
lib/nbsd_libc/gen/nlist_elf32.c [new file with mode: 0644]
lib/nbsd_libc/gen/nlist_elf64.c [new file with mode: 0644]
lib/nbsd_libc/gen/nlist_private.h [new file with mode: 0644]
lib/nbsd_libc/gen/opendir.c [new file with mode: 0644]
lib/nbsd_libc/gen/pause.3 [new file with mode: 0644]
lib/nbsd_libc/gen/pause.c [new file with mode: 0644]
lib/nbsd_libc/gen/popen.3 [new file with mode: 0644]
lib/nbsd_libc/gen/popen.c [new file with mode: 0644]
lib/nbsd_libc/gen/psignal.3 [new file with mode: 0644]
lib/nbsd_libc/gen/psignal.c [new file with mode: 0644]
lib/nbsd_libc/gen/pthread_atfork.3 [new file with mode: 0644]
lib/nbsd_libc/gen/pthread_atfork.c [new file with mode: 0644]
lib/nbsd_libc/gen/pw_private.h [new file with mode: 0644]
lib/nbsd_libc/gen/pw_scan.c [new file with mode: 0644]
lib/nbsd_libc/gen/pwcache.3 [new file with mode: 0644]
lib/nbsd_libc/gen/pwcache.c [new file with mode: 0644]
lib/nbsd_libc/gen/pwcache.h [new file with mode: 0644]
lib/nbsd_libc/gen/raise.3 [new file with mode: 0644]
lib/nbsd_libc/gen/raise.c [new file with mode: 0644]
lib/nbsd_libc/gen/randomid.3 [new file with mode: 0644]
lib/nbsd_libc/gen/randomid.c [new file with mode: 0644]
lib/nbsd_libc/gen/readdir.c [new file with mode: 0644]
lib/nbsd_libc/gen/realpath.3 [new file with mode: 0644]
lib/nbsd_libc/gen/rewinddir.c [new file with mode: 0644]
lib/nbsd_libc/gen/scandir.3 [new file with mode: 0644]
lib/nbsd_libc/gen/scandir.c [new file with mode: 0644]
lib/nbsd_libc/gen/seekdir.c [new file with mode: 0644]
lib/nbsd_libc/gen/setdomainname.c [new file with mode: 0644]
lib/nbsd_libc/gen/sethostname.c [new file with mode: 0644]
lib/nbsd_libc/gen/setjmp.3 [new file with mode: 0644]
lib/nbsd_libc/gen/setjmperr.c [new file with mode: 0644]
lib/nbsd_libc/gen/setmode.3 [new file with mode: 0644]
lib/nbsd_libc/gen/setmode.c [new file with mode: 0644]
lib/nbsd_libc/gen/setproctitle.3 [new file with mode: 0644]
lib/nbsd_libc/gen/setproctitle.c [new file with mode: 0644]
lib/nbsd_libc/gen/setprogname.c [new file with mode: 0644]
lib/nbsd_libc/gen/shquote.3 [new file with mode: 0644]
lib/nbsd_libc/gen/shquote.c [new file with mode: 0644]
lib/nbsd_libc/gen/shquotev.c [new file with mode: 0644]
lib/nbsd_libc/gen/sighold.3 [new file with mode: 0644]
lib/nbsd_libc/gen/sighold.c [new file with mode: 0644]
lib/nbsd_libc/gen/sigignore.3 [new file with mode: 0644]
lib/nbsd_libc/gen/sigignore.c [new file with mode: 0644]
lib/nbsd_libc/gen/siginterrupt.3 [new file with mode: 0644]
lib/nbsd_libc/gen/siginterrupt.c [new file with mode: 0644]
lib/nbsd_libc/gen/siglist.c [new file with mode: 0644]
lib/nbsd_libc/gen/signal.3 [new file with mode: 0644]
lib/nbsd_libc/gen/signal.c [new file with mode: 0644]
lib/nbsd_libc/gen/signame.c [new file with mode: 0644]
lib/nbsd_libc/gen/signbit.3 [new file with mode: 0644]
lib/nbsd_libc/gen/signbitd_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/signbitf_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/signbitl_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/gen/sigrelse.3 [new file with mode: 0644]
lib/nbsd_libc/gen/sigrelse.c [new file with mode: 0644]
lib/nbsd_libc/gen/sigset.3 [new file with mode: 0644]
lib/nbsd_libc/gen/sigset.c [new file with mode: 0644]
lib/nbsd_libc/gen/sigsetops.3 [new file with mode: 0644]
lib/nbsd_libc/gen/sigsetops.c [new file with mode: 0644]
lib/nbsd_libc/gen/sleep.3 [new file with mode: 0644]
lib/nbsd_libc/gen/sleep.c [new file with mode: 0644]
lib/nbsd_libc/gen/stringlist.3 [new file with mode: 0644]
lib/nbsd_libc/gen/stringlist.c [new file with mode: 0644]
lib/nbsd_libc/gen/sysconf.3 [new file with mode: 0644]
lib/nbsd_libc/gen/sysconf.c [new file with mode: 0644]
lib/nbsd_libc/gen/sysctl.3 [new file with mode: 0644]
lib/nbsd_libc/gen/sysctl.c [new file with mode: 0644]
lib/nbsd_libc/gen/sysctlbyname.c [new file with mode: 0644]
lib/nbsd_libc/gen/sysctlgetmibinfo.c [new file with mode: 0644]
lib/nbsd_libc/gen/sysctlnametomib.c [new file with mode: 0644]
lib/nbsd_libc/gen/syslog.3 [new file with mode: 0644]
lib/nbsd_libc/gen/syslog.c [new file with mode: 0644]
lib/nbsd_libc/gen/telldir.c [new file with mode: 0644]
lib/nbsd_libc/gen/time.3 [new file with mode: 0644]
lib/nbsd_libc/gen/time.c [new file with mode: 0644]
lib/nbsd_libc/gen/times.3 [new file with mode: 0644]
lib/nbsd_libc/gen/times.c [new file with mode: 0644]
lib/nbsd_libc/gen/timezone.3 [new file with mode: 0644]
lib/nbsd_libc/gen/toascii.3 [new file with mode: 0644]
lib/nbsd_libc/gen/toascii.c [new file with mode: 0644]
lib/nbsd_libc/gen/tolower.3 [new file with mode: 0644]
lib/nbsd_libc/gen/tolower_.c [new file with mode: 0644]
lib/nbsd_libc/gen/toupper.3 [new file with mode: 0644]
lib/nbsd_libc/gen/toupper_.c [new file with mode: 0644]
lib/nbsd_libc/gen/ttyname.3 [new file with mode: 0644]
lib/nbsd_libc/gen/ttyname.c [new file with mode: 0644]
lib/nbsd_libc/gen/ttyslot.c [new file with mode: 0644]
lib/nbsd_libc/gen/ualarm.3 [new file with mode: 0644]
lib/nbsd_libc/gen/ualarm.c [new file with mode: 0644]
lib/nbsd_libc/gen/ulimit.3 [new file with mode: 0644]
lib/nbsd_libc/gen/ulimit.c [new file with mode: 0644]
lib/nbsd_libc/gen/uname.3 [new file with mode: 0644]
lib/nbsd_libc/gen/uname.c [new file with mode: 0644]
lib/nbsd_libc/gen/unvis.3 [new file with mode: 0644]
lib/nbsd_libc/gen/unvis.c [new file with mode: 0644]
lib/nbsd_libc/gen/usleep.3 [new file with mode: 0644]
lib/nbsd_libc/gen/usleep.c [new file with mode: 0644]
lib/nbsd_libc/gen/utime.3 [new file with mode: 0644]
lib/nbsd_libc/gen/utime.c [new file with mode: 0644]
lib/nbsd_libc/gen/utmp.c [new file with mode: 0644]
lib/nbsd_libc/gen/utmpx.c [new file with mode: 0644]
lib/nbsd_libc/gen/valloc.3 [new file with mode: 0644]
lib/nbsd_libc/gen/valloc.c [new file with mode: 0644]
lib/nbsd_libc/gen/verr.c [new file with mode: 0644]
lib/nbsd_libc/gen/verrx.c [new file with mode: 0644]
lib/nbsd_libc/gen/vis.3 [new file with mode: 0644]
lib/nbsd_libc/gen/vis.c [new file with mode: 0644]
lib/nbsd_libc/gen/vwarn.c [new file with mode: 0644]
lib/nbsd_libc/gen/vwarnx.c [new file with mode: 0644]
lib/nbsd_libc/gen/wait.c [new file with mode: 0644]
lib/nbsd_libc/gen/wait3.c [new file with mode: 0644]
lib/nbsd_libc/gen/waitpid.c [new file with mode: 0644]
lib/nbsd_libc/gen/warn.c [new file with mode: 0644]
lib/nbsd_libc/gen/warnx.c [new file with mode: 0644]
lib/nbsd_libc/gen/wordexp.3 [new file with mode: 0644]
lib/nbsd_libc/gen/wordexp.c [new file with mode: 0644]
lib/nbsd_libc/gmon/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/gmon/gmon.c [new file with mode: 0644]
lib/nbsd_libc/gmon/moncontrol.3 [new file with mode: 0644]
lib/nbsd_libc/hash/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/hash/hashhl.c [new file with mode: 0644]
lib/nbsd_libc/hash/md2/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/hash/md2/md2.3 [new file with mode: 0644]
lib/nbsd_libc/hash/md2/md2.c [new file with mode: 0644]
lib/nbsd_libc/hash/md2/md2hl.c [new file with mode: 0644]
lib/nbsd_libc/hash/rmd160/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/hash/rmd160/rmd160.3 [new file with mode: 0644]
lib/nbsd_libc/hash/rmd160/rmd160hl.c [new file with mode: 0644]
lib/nbsd_libc/hash/sha1/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/hash/sha1/sha1.3 [new file with mode: 0644]
lib/nbsd_libc/hash/sha1/sha1hl.c [new file with mode: 0644]
lib/nbsd_libc/hash/sha2/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/hash/sha2/sha2.3 [new file with mode: 0644]
lib/nbsd_libc/hash/sha2/sha224hl.c [new file with mode: 0644]
lib/nbsd_libc/hash/sha2/sha256hl.c [new file with mode: 0644]
lib/nbsd_libc/hash/sha2/sha384hl.c [new file with mode: 0644]
lib/nbsd_libc/hash/sha2/sha512hl.c [new file with mode: 0644]
lib/nbsd_libc/iconv/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/iconv/iconv.3 [new file with mode: 0644]
lib/nbsd_libc/iconv/iconv.c [new file with mode: 0644]
lib/nbsd_libc/include/env.h [new file with mode: 0644]
lib/nbsd_libc/include/extern.h [new file with mode: 0644]
lib/nbsd_libc/include/fd_setsize.h [new file with mode: 0644]
lib/nbsd_libc/include/isc/assertions.h [new file with mode: 0644]
lib/nbsd_libc/include/isc/dst.h [new file with mode: 0644]
lib/nbsd_libc/include/isc/eventlib.h [new file with mode: 0644]
lib/nbsd_libc/include/isc/heap.h [new file with mode: 0644]
lib/nbsd_libc/include/isc/list.h [new file with mode: 0644]
lib/nbsd_libc/include/isc/memcluster.h [new file with mode: 0644]
lib/nbsd_libc/include/namespace.h [new file with mode: 0644]
lib/nbsd_libc/include/pathnames.h [new file with mode: 0644]
lib/nbsd_libc/include/port_after.h [new file with mode: 0644]
lib/nbsd_libc/include/port_before.h [new file with mode: 0644]
lib/nbsd_libc/include/reentrant.h [new file with mode: 0644]
lib/nbsd_libc/include/resolv_mt.h [new file with mode: 0644]
lib/nbsd_libc/inet/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/inet/_inet_aton.c [new file with mode: 0644]
lib/nbsd_libc/inet/_inet_pton.c [new file with mode: 0644]
lib/nbsd_libc/inet/inet.3 [new file with mode: 0644]
lib/nbsd_libc/inet/inet6_option_space.3 [new file with mode: 0644]
lib/nbsd_libc/inet/inet6_rthdr_space.3 [new file with mode: 0644]
lib/nbsd_libc/inet/inet_cidr_ntop.c [new file with mode: 0644]
lib/nbsd_libc/inet/inet_cidr_pton.c [new file with mode: 0644]
lib/nbsd_libc/inet/inet_lnaof.c [new file with mode: 0644]
lib/nbsd_libc/inet/inet_makeaddr.c [new file with mode: 0644]
lib/nbsd_libc/inet/inet_net.3 [new file with mode: 0644]
lib/nbsd_libc/inet/inet_net_ntop.c [new file with mode: 0644]
lib/nbsd_libc/inet/inet_net_pton.c [new file with mode: 0644]
lib/nbsd_libc/inet/inet_neta.c [new file with mode: 0644]
lib/nbsd_libc/inet/inet_netof.c [new file with mode: 0644]
lib/nbsd_libc/inet/inet_network.c [new file with mode: 0644]
lib/nbsd_libc/inet/inet_ntoa.c [new file with mode: 0644]
lib/nbsd_libc/inet/inet_ntop.c [new file with mode: 0644]
lib/nbsd_libc/inet/inet_pton.c [new file with mode: 0644]
lib/nbsd_libc/inet/nsap_addr.c [new file with mode: 0644]
lib/nbsd_libc/isc/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/isc/assertions.c [new file with mode: 0644]
lib/nbsd_libc/isc/ev_streams.c [new file with mode: 0644]
lib/nbsd_libc/isc/ev_timers.c [new file with mode: 0644]
lib/nbsd_libc/isc/eventlib_p.h [new file with mode: 0644]
lib/nbsd_libc/libcincludes.mk [new file with mode: 0644]
lib/nbsd_libc/locale/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/locale/__mb_cur_max.c [new file with mode: 0644]
lib/nbsd_libc/locale/__wctoint.h [new file with mode: 0644]
lib/nbsd_libc/locale/_def_messages.c [new file with mode: 0644]
lib/nbsd_libc/locale/_def_monetary.c [new file with mode: 0644]
lib/nbsd_libc/locale/_def_numeric.c [new file with mode: 0644]
lib/nbsd_libc/locale/_def_time.c [new file with mode: 0644]
lib/nbsd_libc/locale/_wcstod.h [new file with mode: 0644]
lib/nbsd_libc/locale/_wcstol.h [new file with mode: 0644]
lib/nbsd_libc/locale/_wcstoul.h [new file with mode: 0644]
lib/nbsd_libc/locale/_wctrans.c [new file with mode: 0644]
lib/nbsd_libc/locale/_wctrans_local.h [new file with mode: 0644]
lib/nbsd_libc/locale/_wctype.c [new file with mode: 0644]
lib/nbsd_libc/locale/_wctype_local.h [new file with mode: 0644]
lib/nbsd_libc/locale/aliasname.c [new file with mode: 0644]
lib/nbsd_libc/locale/aliasname_local.h [new file with mode: 0644]
lib/nbsd_libc/locale/bsdctype.c [new file with mode: 0644]
lib/nbsd_libc/locale/bsdctype_file.h [new file with mode: 0644]
lib/nbsd_libc/locale/bsdctype_local.h [new file with mode: 0644]
lib/nbsd_libc/locale/btowc.3 [new file with mode: 0644]
lib/nbsd_libc/locale/ctype_local.h [new file with mode: 0644]
lib/nbsd_libc/locale/current_locale.c [new file with mode: 0644]
lib/nbsd_libc/locale/dummy_lc_collate.c [new file with mode: 0644]
lib/nbsd_libc/locale/dummy_lc_template.h [new file with mode: 0644]
lib/nbsd_libc/locale/fix_grouping.c [new file with mode: 0644]
lib/nbsd_libc/locale/fix_grouping.h [new file with mode: 0644]
lib/nbsd_libc/locale/generic_lc_all.c [new file with mode: 0644]
lib/nbsd_libc/locale/generic_lc_template.h [new file with mode: 0644]
lib/nbsd_libc/locale/generic_lc_template_decl.h [new file with mode: 0644]
lib/nbsd_libc/locale/global_locale.c [new file with mode: 0644]
lib/nbsd_libc/locale/iswalnum.3 [new file with mode: 0644]
lib/nbsd_libc/locale/iswctype.3 [new file with mode: 0644]
lib/nbsd_libc/locale/iswctype_mb.c [new file with mode: 0644]
lib/nbsd_libc/locale/iswctype_sb.c [new file with mode: 0644]
lib/nbsd_libc/locale/localeconv.c [new file with mode: 0644]
lib/nbsd_libc/locale/localeio.c [new file with mode: 0644]
lib/nbsd_libc/locale/localeio.h [new file with mode: 0644]
lib/nbsd_libc/locale/localeio_lc_ctype.c [new file with mode: 0644]
lib/nbsd_libc/locale/localeio_lc_messages.c [new file with mode: 0644]
lib/nbsd_libc/locale/localeio_lc_monetary.c [new file with mode: 0644]
lib/nbsd_libc/locale/localeio_lc_numeric.c [new file with mode: 0644]
lib/nbsd_libc/locale/localeio_lc_time.c [new file with mode: 0644]
lib/nbsd_libc/locale/mblen.3 [new file with mode: 0644]
lib/nbsd_libc/locale/mbrlen.3 [new file with mode: 0644]
lib/nbsd_libc/locale/mbrtowc.3 [new file with mode: 0644]
lib/nbsd_libc/locale/mbsinit.3 [new file with mode: 0644]
lib/nbsd_libc/locale/mbsrtowcs.3 [new file with mode: 0644]
lib/nbsd_libc/locale/mbstowcs.3 [new file with mode: 0644]
lib/nbsd_libc/locale/mbtowc.3 [new file with mode: 0644]
lib/nbsd_libc/locale/multibyte.h [new file with mode: 0644]
lib/nbsd_libc/locale/multibyte_amd1.c [new file with mode: 0644]
lib/nbsd_libc/locale/multibyte_c90.c [new file with mode: 0644]
lib/nbsd_libc/locale/multibyte_sb.c [new file with mode: 0644]
lib/nbsd_libc/locale/nb_lc_messages_misc.h [new file with mode: 0644]
lib/nbsd_libc/locale/nb_lc_monetary_misc.h [new file with mode: 0644]
lib/nbsd_libc/locale/nb_lc_numeric_misc.h [new file with mode: 0644]
lib/nbsd_libc/locale/nb_lc_template.h [new file with mode: 0644]
lib/nbsd_libc/locale/nb_lc_template_decl.h [new file with mode: 0644]
lib/nbsd_libc/locale/nb_lc_time_misc.h [new file with mode: 0644]
lib/nbsd_libc/locale/nl_langinfo.3 [new file with mode: 0644]
lib/nbsd_libc/locale/nl_langinfo.c [new file with mode: 0644]
lib/nbsd_libc/locale/rune.c [new file with mode: 0644]
lib/nbsd_libc/locale/runetable.c [new file with mode: 0644]
lib/nbsd_libc/locale/runetype_file.h [new file with mode: 0644]
lib/nbsd_libc/locale/runetype_local.h [new file with mode: 0644]
lib/nbsd_libc/locale/runetype_misc.h [new file with mode: 0644]
lib/nbsd_libc/locale/setlocale.3 [new file with mode: 0644]
lib/nbsd_libc/locale/setlocale.c [new file with mode: 0644]
lib/nbsd_libc/locale/setlocale_local.h [new file with mode: 0644]
lib/nbsd_libc/locale/towctrans.3 [new file with mode: 0644]
lib/nbsd_libc/locale/towlower.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wcrtomb.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wcscoll.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wcscoll.c [new file with mode: 0644]
lib/nbsd_libc/locale/wcsftime.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wcsftime.c [new file with mode: 0644]
lib/nbsd_libc/locale/wcsrtombs.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wcstod.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wcstod.c [new file with mode: 0644]
lib/nbsd_libc/locale/wcstof.c [new file with mode: 0644]
lib/nbsd_libc/locale/wcstoimax.c [new file with mode: 0644]
lib/nbsd_libc/locale/wcstol.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wcstol.c [new file with mode: 0644]
lib/nbsd_libc/locale/wcstold.c [new file with mode: 0644]
lib/nbsd_libc/locale/wcstoll.c [new file with mode: 0644]
lib/nbsd_libc/locale/wcstombs.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wcstoul.c [new file with mode: 0644]
lib/nbsd_libc/locale/wcstoull.c [new file with mode: 0644]
lib/nbsd_libc/locale/wcstoumax.c [new file with mode: 0644]
lib/nbsd_libc/locale/wcsxfrm.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wcsxfrm.c [new file with mode: 0644]
lib/nbsd_libc/locale/wctob.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wctomb.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wctrans.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wctype.3 [new file with mode: 0644]
lib/nbsd_libc/locale/wcwidth.3 [new file with mode: 0644]
lib/nbsd_libc/md/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/md/md2hl.c [new file with mode: 0644]
lib/nbsd_libc/md/md4.copyright [new file with mode: 0644]
lib/nbsd_libc/md/md4hl.c [new file with mode: 0644]
lib/nbsd_libc/md/md5.copyright [new file with mode: 0644]
lib/nbsd_libc/md/md5hl.c [new file with mode: 0644]
lib/nbsd_libc/md/mdX.3 [new file with mode: 0644]
lib/nbsd_libc/md/mdXhl.c [new file with mode: 0644]
lib/nbsd_libc/misc/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/misc/initfini.c [new file with mode: 0644]
lib/nbsd_libc/misc/stack_protector.c [new file with mode: 0644]
lib/nbsd_libc/nameser/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/nameser/ns_name.c [new file with mode: 0644]
lib/nbsd_libc/nameser/ns_netint.c [new file with mode: 0644]
lib/nbsd_libc/nameser/ns_parse.c [new file with mode: 0644]
lib/nbsd_libc/nameser/ns_print.c [new file with mode: 0644]
lib/nbsd_libc/nameser/ns_samedomain.c [new file with mode: 0644]
lib/nbsd_libc/nameser/ns_ttl.c [new file with mode: 0644]
lib/nbsd_libc/net/Lint_htonl.c [new file with mode: 0644]
lib/nbsd_libc/net/Lint_htons.c [new file with mode: 0644]
lib/nbsd_libc/net/Lint_ntohl.c [new file with mode: 0644]
lib/nbsd_libc/net/Lint_ntohs.c [new file with mode: 0644]
lib/nbsd_libc/net/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/net/base64.c [new file with mode: 0644]
lib/nbsd_libc/net/byteorder.3 [new file with mode: 0644]
lib/nbsd_libc/net/ethers.3 [new file with mode: 0644]
lib/nbsd_libc/net/ethers.c [new file with mode: 0644]
lib/nbsd_libc/net/gai_strerror.3 [new file with mode: 0644]
lib/nbsd_libc/net/getaddrinfo.3 [new file with mode: 0644]
lib/nbsd_libc/net/getaddrinfo.c [new file with mode: 0644]
lib/nbsd_libc/net/gethnamaddr.c [new file with mode: 0644]
lib/nbsd_libc/net/gethostbyname.3 [new file with mode: 0644]
lib/nbsd_libc/net/getifaddrs.3 [new file with mode: 0644]
lib/nbsd_libc/net/getifaddrs.c [new file with mode: 0644]
lib/nbsd_libc/net/getnameinfo.3 [new file with mode: 0644]
lib/nbsd_libc/net/getnameinfo.c [new file with mode: 0644]
lib/nbsd_libc/net/getnetent.3 [new file with mode: 0644]
lib/nbsd_libc/net/getnetent.c [new file with mode: 0644]
lib/nbsd_libc/net/getnetnamadr.c [new file with mode: 0644]
lib/nbsd_libc/net/getpeereid.3 [new file with mode: 0644]
lib/nbsd_libc/net/getpeereid.c [new file with mode: 0644]
lib/nbsd_libc/net/getprotobyname.c [new file with mode: 0644]
lib/nbsd_libc/net/getprotobyname_r.c [new file with mode: 0644]
lib/nbsd_libc/net/getprotobynumber.c [new file with mode: 0644]
lib/nbsd_libc/net/getprotobynumber_r.c [new file with mode: 0644]
lib/nbsd_libc/net/getprotoent.3 [new file with mode: 0644]
lib/nbsd_libc/net/getprotoent.c [new file with mode: 0644]
lib/nbsd_libc/net/getprotoent_r.c [new file with mode: 0644]
lib/nbsd_libc/net/getservbyname.c [new file with mode: 0644]
lib/nbsd_libc/net/getservbyname_r.c [new file with mode: 0644]
lib/nbsd_libc/net/getservbyport.c [new file with mode: 0644]
lib/nbsd_libc/net/getservbyport_r.c [new file with mode: 0644]
lib/nbsd_libc/net/getservent.3 [new file with mode: 0644]
lib/nbsd_libc/net/getservent.c [new file with mode: 0644]
lib/nbsd_libc/net/getservent_r.c [new file with mode: 0644]
lib/nbsd_libc/net/hesiod.3 [new file with mode: 0644]
lib/nbsd_libc/net/hesiod.c [new file with mode: 0644]
lib/nbsd_libc/net/if_indextoname.3 [new file with mode: 0644]
lib/nbsd_libc/net/if_indextoname.c [new file with mode: 0644]
lib/nbsd_libc/net/if_nameindex.c [new file with mode: 0644]
lib/nbsd_libc/net/if_nametoindex.c [new file with mode: 0644]
lib/nbsd_libc/net/inet6_opt_init.3 [new file with mode: 0644]
lib/nbsd_libc/net/inet6_option_space.3 [new file with mode: 0644]
lib/nbsd_libc/net/inet6_rth_space.3 [new file with mode: 0644]
lib/nbsd_libc/net/inet6_rthdr_space.3 [new file with mode: 0644]
lib/nbsd_libc/net/ip6opt.c [new file with mode: 0644]
lib/nbsd_libc/net/iso_addr.3 [new file with mode: 0644]
lib/nbsd_libc/net/iso_addr.c [new file with mode: 0644]
lib/nbsd_libc/net/linkaddr.3 [new file with mode: 0644]
lib/nbsd_libc/net/linkaddr.c [new file with mode: 0644]
lib/nbsd_libc/net/nsdispatch.3 [new file with mode: 0644]
lib/nbsd_libc/net/nsdispatch.c [new file with mode: 0644]
lib/nbsd_libc/net/nslexer.l [new file with mode: 0644]
lib/nbsd_libc/net/nsparser.y [new file with mode: 0644]
lib/nbsd_libc/net/protoent.h [new file with mode: 0644]
lib/nbsd_libc/net/rcmd.3 [new file with mode: 0644]
lib/nbsd_libc/net/rcmd.c [new file with mode: 0644]
lib/nbsd_libc/net/recv.c [new file with mode: 0644]
lib/nbsd_libc/net/resolver.3 [new file with mode: 0644]
lib/nbsd_libc/net/rthdr.c [new file with mode: 0644]
lib/nbsd_libc/net/send.c [new file with mode: 0644]
lib/nbsd_libc/net/servent.h [new file with mode: 0644]
lib/nbsd_libc/net/sethostent.c [new file with mode: 0644]
lib/nbsd_libc/net/sockatmark.3 [new file with mode: 0644]
lib/nbsd_libc/net/sockatmark.c [new file with mode: 0644]
lib/nbsd_libc/net/vars6.c [new file with mode: 0644]
lib/nbsd_libc/nls/C.msg [new file with mode: 0644]
lib/nbsd_libc/nls/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/nls/Pig.msg [new file with mode: 0644]
lib/nbsd_libc/nls/_catclose.c [new file with mode: 0644]
lib/nbsd_libc/nls/_catgets.c [new file with mode: 0644]
lib/nbsd_libc/nls/_catopen.c [new file with mode: 0644]
lib/nbsd_libc/nls/ca.msg [new file with mode: 0644]
lib/nbsd_libc/nls/catclose.3 [new file with mode: 0644]
lib/nbsd_libc/nls/catclose.c [new file with mode: 0644]
lib/nbsd_libc/nls/catgets.3 [new file with mode: 0644]
lib/nbsd_libc/nls/catgets.c [new file with mode: 0644]
lib/nbsd_libc/nls/catopen.3 [new file with mode: 0644]
lib/nbsd_libc/nls/catopen.c [new file with mode: 0644]
lib/nbsd_libc/nls/cs.msg [new file with mode: 0644]
lib/nbsd_libc/nls/de.msg [new file with mode: 0644]
lib/nbsd_libc/nls/es.msg [new file with mode: 0644]
lib/nbsd_libc/nls/fi.msg [new file with mode: 0644]
lib/nbsd_libc/nls/fr.msg [new file with mode: 0644]
lib/nbsd_libc/nls/nl.msg [new file with mode: 0644]
lib/nbsd_libc/nls/no.msg [new file with mode: 0644]
lib/nbsd_libc/nls/pl.msg [new file with mode: 0644]
lib/nbsd_libc/nls/sk.msg [new file with mode: 0644]
lib/nbsd_libc/nls/sv.msg [new file with mode: 0644]
lib/nbsd_libc/quad/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/quad/TESTS/Makefile [new file with mode: 0644]
lib/nbsd_libc/quad/TESTS/divrem.c [new file with mode: 0644]
lib/nbsd_libc/quad/TESTS/mul.c [new file with mode: 0644]
lib/nbsd_libc/quad/fixdfdi.c [new file with mode: 0644]
lib/nbsd_libc/quad/fixsfdi.c [new file with mode: 0644]
lib/nbsd_libc/quad/fixunsdfdi.c [new file with mode: 0644]
lib/nbsd_libc/quad/fixunssfdi.c [new file with mode: 0644]
lib/nbsd_libc/quad/floatdidf.c [new file with mode: 0644]
lib/nbsd_libc/quad/floatdisf.c [new file with mode: 0644]
lib/nbsd_libc/quad/floatunsdidf.c [new file with mode: 0644]
lib/nbsd_libc/regex/COPYRIGHT [new file with mode: 0644]
lib/nbsd_libc/regex/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/regex/WHATSNEW [new file with mode: 0644]
lib/nbsd_libc/regex/cclass.h [new file with mode: 0644]
lib/nbsd_libc/regex/cname.h [new file with mode: 0644]
lib/nbsd_libc/regex/engine.c [new file with mode: 0644]
lib/nbsd_libc/regex/re_format.7 [new file with mode: 0644]
lib/nbsd_libc/regex/regcomp.c [new file with mode: 0644]
lib/nbsd_libc/regex/regerror.c [new file with mode: 0644]
lib/nbsd_libc/regex/regex.3 [new file with mode: 0644]
lib/nbsd_libc/regex/regex2.h [new file with mode: 0644]
lib/nbsd_libc/regex/regexec.c [new file with mode: 0644]
lib/nbsd_libc/regex/regfree.c [new file with mode: 0644]
lib/nbsd_libc/regex/utils.h [new file with mode: 0644]
lib/nbsd_libc/resolv/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/resolv/__dn_comp.c [new file with mode: 0644]
lib/nbsd_libc/resolv/__res_close.c [new file with mode: 0644]
lib/nbsd_libc/resolv/__res_send.c [new file with mode: 0644]
lib/nbsd_libc/resolv/h_errno.c [new file with mode: 0644]
lib/nbsd_libc/resolv/herror.c [new file with mode: 0644]
lib/nbsd_libc/resolv/mtctxres.c [new file with mode: 0644]
lib/nbsd_libc/resolv/res_comp.c [new file with mode: 0644]
lib/nbsd_libc/resolv/res_compat.c [new file with mode: 0644]
lib/nbsd_libc/resolv/res_data.c [new file with mode: 0644]
lib/nbsd_libc/resolv/res_debug.c [new file with mode: 0644]
lib/nbsd_libc/resolv/res_debug.h [new file with mode: 0644]
lib/nbsd_libc/resolv/res_init.c [new file with mode: 0644]
lib/nbsd_libc/resolv/res_mkquery.c [new file with mode: 0644]
lib/nbsd_libc/resolv/res_private.h [new file with mode: 0644]
lib/nbsd_libc/resolv/res_query.c [new file with mode: 0644]
lib/nbsd_libc/resolv/res_send.c [new file with mode: 0644]
lib/nbsd_libc/resolv/res_state.c [new file with mode: 0644]
lib/nbsd_libc/rpc/DISCLAIMER [new file with mode: 0644]
lib/nbsd_libc/rpc/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/rpc/README [new file with mode: 0644]
lib/nbsd_libc/rpc/__rpc_getxid.c [new file with mode: 0644]
lib/nbsd_libc/rpc/auth_none.c [new file with mode: 0644]
lib/nbsd_libc/rpc/auth_unix.c [new file with mode: 0644]
lib/nbsd_libc/rpc/authunix_prot.c [new file with mode: 0644]
lib/nbsd_libc/rpc/bindresvport.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/bindresvport.c [new file with mode: 0644]
lib/nbsd_libc/rpc/clnt_bcast.c [new file with mode: 0644]
lib/nbsd_libc/rpc/clnt_dg.c [new file with mode: 0644]
lib/nbsd_libc/rpc/clnt_generic.c [new file with mode: 0644]
lib/nbsd_libc/rpc/clnt_perror.c [new file with mode: 0644]
lib/nbsd_libc/rpc/clnt_raw.c [new file with mode: 0644]
lib/nbsd_libc/rpc/clnt_simple.c [new file with mode: 0644]
lib/nbsd_libc/rpc/clnt_vc.c [new file with mode: 0644]
lib/nbsd_libc/rpc/getnetconfig.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/getnetconfig.c [new file with mode: 0644]
lib/nbsd_libc/rpc/getnetpath.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/getnetpath.c [new file with mode: 0644]
lib/nbsd_libc/rpc/getrpcent.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/getrpcent.c [new file with mode: 0644]
lib/nbsd_libc/rpc/getrpcport.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/getrpcport.c [new file with mode: 0644]
lib/nbsd_libc/rpc/mt_misc.c [new file with mode: 0644]
lib/nbsd_libc/rpc/pmap_clnt.c [new file with mode: 0644]
lib/nbsd_libc/rpc/pmap_getmaps.c [new file with mode: 0644]
lib/nbsd_libc/rpc/pmap_getport.c [new file with mode: 0644]
lib/nbsd_libc/rpc/pmap_prot.c [new file with mode: 0644]
lib/nbsd_libc/rpc/pmap_prot2.c [new file with mode: 0644]
lib/nbsd_libc/rpc/pmap_rmt.c [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_callmsg.c [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_clnt_auth.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_clnt_calls.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_clnt_create.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_commondata.c [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_dtablesize.c [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_generic.c [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_internal.h [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_prot.c [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_soc.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_soc.c [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_svc_calls.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_svc_create.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_svc_err.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_svc_reg.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/rpc_xdr.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/rpcb_clnt.c [new file with mode: 0644]
lib/nbsd_libc/rpc/rpcb_prot.c [new file with mode: 0644]
lib/nbsd_libc/rpc/rpcb_st_xdr.c [new file with mode: 0644]
lib/nbsd_libc/rpc/rpcbind.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/svc.c [new file with mode: 0644]
lib/nbsd_libc/rpc/svc_auth.c [new file with mode: 0644]
lib/nbsd_libc/rpc/svc_auth_unix.c [new file with mode: 0644]
lib/nbsd_libc/rpc/svc_dg.c [new file with mode: 0644]
lib/nbsd_libc/rpc/svc_dg.h [new file with mode: 0644]
lib/nbsd_libc/rpc/svc_generic.c [new file with mode: 0644]
lib/nbsd_libc/rpc/svc_raw.c [new file with mode: 0644]
lib/nbsd_libc/rpc/svc_run.c [new file with mode: 0644]
lib/nbsd_libc/rpc/svc_simple.c [new file with mode: 0644]
lib/nbsd_libc/rpc/svc_vc.c [new file with mode: 0644]
lib/nbsd_libc/rpc/xdr.3 [new file with mode: 0644]
lib/nbsd_libc/rpc/xdr.c [new file with mode: 0644]
lib/nbsd_libc/rpc/xdr_array.c [new file with mode: 0644]
lib/nbsd_libc/rpc/xdr_float.c [new file with mode: 0644]
lib/nbsd_libc/rpc/xdr_mem.c [new file with mode: 0644]
lib/nbsd_libc/rpc/xdr_rec.c [new file with mode: 0644]
lib/nbsd_libc/rpc/xdr_reference.c [new file with mode: 0644]
lib/nbsd_libc/rpc/xdr_stdio.c [new file with mode: 0644]
lib/nbsd_libc/shlib_version [new file with mode: 0644]
lib/nbsd_libc/softfloat/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/softfloat/README.NetBSD [new file with mode: 0644]
lib/nbsd_libc/softfloat/README.txt [new file with mode: 0644]
lib/nbsd_libc/softfloat/bits32/softfloat-macros [new file with mode: 0644]
lib/nbsd_libc/softfloat/bits32/softfloat.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/bits64/softfloat-macros [new file with mode: 0644]
lib/nbsd_libc/softfloat/bits64/softfloat.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/eqdf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/eqsf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/eqtf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/fpgetmask.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/fpgetround.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/fpgetsticky.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/fpsetmask.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/fpsetround.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/fpsetsticky.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/gedf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/gesf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/getf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/gexf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/gtdf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/gtsf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/gttf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/gtxf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/ledf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/lesf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/letf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/ltdf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/ltsf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/lttf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/nedf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/negdf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/negsf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/negtf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/negxf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/nesf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/netf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/nexf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/softfloat-for-gcc.h [new file with mode: 0644]
lib/nbsd_libc/softfloat/softfloat-history.txt [new file with mode: 0644]
lib/nbsd_libc/softfloat/softfloat-source.txt [new file with mode: 0644]
lib/nbsd_libc/softfloat/softfloat-specialize [new file with mode: 0644]
lib/nbsd_libc/softfloat/softfloat.txt [new file with mode: 0644]
lib/nbsd_libc/softfloat/templates/milieu.h [new file with mode: 0644]
lib/nbsd_libc/softfloat/templates/softfloat-specialize [new file with mode: 0644]
lib/nbsd_libc/softfloat/templates/softfloat.h [new file with mode: 0644]
lib/nbsd_libc/softfloat/timesoftfloat.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/timesoftfloat.txt [new file with mode: 0644]
lib/nbsd_libc/softfloat/unorddf2.c [new file with mode: 0644]
lib/nbsd_libc/softfloat/unordsf2.c [new file with mode: 0644]
lib/nbsd_libc/ssp/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/ssp/__builtin_object_size.3 [new file with mode: 0644]
lib/nbsd_libc/ssp/fgets_chk.c [new file with mode: 0644]
lib/nbsd_libc/ssp/gets_chk.c [new file with mode: 0644]
lib/nbsd_libc/ssp/memcpy_chk.c [new file with mode: 0644]
lib/nbsd_libc/ssp/memmove_chk.c [new file with mode: 0644]
lib/nbsd_libc/ssp/memset_chk.c [new file with mode: 0644]
lib/nbsd_libc/ssp/snprintf_chk.c [new file with mode: 0644]
lib/nbsd_libc/ssp/sprintf_chk.c [new file with mode: 0644]
lib/nbsd_libc/ssp/ssp.3 [new file with mode: 0644]
lib/nbsd_libc/ssp/strcat_chk.c [new file with mode: 0644]
lib/nbsd_libc/ssp/strcpy_chk.c [new file with mode: 0644]
lib/nbsd_libc/ssp/strncat_chk.c [new file with mode: 0644]
lib/nbsd_libc/ssp/strncpy_chk.c [new file with mode: 0644]
lib/nbsd_libc/ssp/vsnprintf_chk.c [new file with mode: 0644]
lib/nbsd_libc/ssp/vsprintf_chk.c [new file with mode: 0644]
lib/nbsd_libc/stdio/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/stdio/_fileno.c [new file with mode: 0644]
lib/nbsd_libc/stdio/_fseeko.c [new file with mode: 0644]
lib/nbsd_libc/stdio/_ftello.c [new file with mode: 0644]
lib/nbsd_libc/stdio/asprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/clrerr.c [new file with mode: 0644]
lib/nbsd_libc/stdio/dprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fclose.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fclose.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fdopen.c [new file with mode: 0644]
lib/nbsd_libc/stdio/feof.c [new file with mode: 0644]
lib/nbsd_libc/stdio/ferror.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/ferror.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fflush.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fflush.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fgetc.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fgetln.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fgetln.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fgetpos.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fgets.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fgets.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fgetstr.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fgetwc.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fgetwln.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fgetwln.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fgetws.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fgetws.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fileext.h [new file with mode: 0644]
lib/nbsd_libc/stdio/fileno.c [new file with mode: 0644]
lib/nbsd_libc/stdio/findfp.c [new file with mode: 0644]
lib/nbsd_libc/stdio/flags.c [new file with mode: 0644]
lib/nbsd_libc/stdio/floatio.h [new file with mode: 0644]
lib/nbsd_libc/stdio/flockfile.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/flockfile.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fmemopen.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fmemopen.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fopen.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fopen.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fparseln.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fparseln.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fpurge.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fputc.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fputs.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fputs.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fputwc.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fputws.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fputws.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fread.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fread.c [new file with mode: 0644]
lib/nbsd_libc/stdio/freopen.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fscanf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fseek.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fseek.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fseeko.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fsetpos.c [new file with mode: 0644]
lib/nbsd_libc/stdio/ftell.c [new file with mode: 0644]
lib/nbsd_libc/stdio/ftello.c [new file with mode: 0644]
lib/nbsd_libc/stdio/funopen.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/funopen.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fvwrite.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fvwrite.h [new file with mode: 0644]
lib/nbsd_libc/stdio/fwalk.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fwide.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/fwide.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fwprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fwrite.c [new file with mode: 0644]
lib/nbsd_libc/stdio/fwscanf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/getc.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/getc.c [new file with mode: 0644]
lib/nbsd_libc/stdio/getchar.c [new file with mode: 0644]
lib/nbsd_libc/stdio/getdelim.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/getdelim.c [new file with mode: 0644]
lib/nbsd_libc/stdio/getline.c [new file with mode: 0644]
lib/nbsd_libc/stdio/gets.c [new file with mode: 0644]
lib/nbsd_libc/stdio/gettemp.c [new file with mode: 0644]
lib/nbsd_libc/stdio/getw.c [new file with mode: 0644]
lib/nbsd_libc/stdio/getwc.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/getwc.c [new file with mode: 0644]
lib/nbsd_libc/stdio/getwchar.c [new file with mode: 0644]
lib/nbsd_libc/stdio/glue.h [new file with mode: 0644]
lib/nbsd_libc/stdio/local.h [new file with mode: 0644]
lib/nbsd_libc/stdio/makebuf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/mkdtemp.c [new file with mode: 0644]
lib/nbsd_libc/stdio/mkstemp.c [new file with mode: 0644]
lib/nbsd_libc/stdio/mktemp.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/mktemp.c [new file with mode: 0644]
lib/nbsd_libc/stdio/perror.c [new file with mode: 0644]
lib/nbsd_libc/stdio/printf.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/printf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/putc.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/putc.c [new file with mode: 0644]
lib/nbsd_libc/stdio/putchar.c [new file with mode: 0644]
lib/nbsd_libc/stdio/puts.c [new file with mode: 0644]
lib/nbsd_libc/stdio/putw.c [new file with mode: 0644]
lib/nbsd_libc/stdio/putwc.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/putwc.c [new file with mode: 0644]
lib/nbsd_libc/stdio/putwchar.c [new file with mode: 0644]
lib/nbsd_libc/stdio/refill.c [new file with mode: 0644]
lib/nbsd_libc/stdio/remove.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/remove.c [new file with mode: 0644]
lib/nbsd_libc/stdio/rewind.c [new file with mode: 0644]
lib/nbsd_libc/stdio/rget.c [new file with mode: 0644]
lib/nbsd_libc/stdio/scanf.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/scanf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/setbuf.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/setbuf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/setbuffer.c [new file with mode: 0644]
lib/nbsd_libc/stdio/setvbuf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/snprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/snprintf_ss.c [new file with mode: 0644]
lib/nbsd_libc/stdio/sprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/sscanf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/stdio.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/stdio.c [new file with mode: 0644]
lib/nbsd_libc/stdio/swprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/swscanf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/tempnam.c [new file with mode: 0644]
lib/nbsd_libc/stdio/tmpfile.c [new file with mode: 0644]
lib/nbsd_libc/stdio/tmpnam.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/tmpnam.c [new file with mode: 0644]
lib/nbsd_libc/stdio/ungetc.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/ungetc.c [new file with mode: 0644]
lib/nbsd_libc/stdio/ungetwc.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/ungetwc.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vasprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vdprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vfprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vfscanf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vfwprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vfwscanf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vscanf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vsnprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vsnprintf_ss.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vsprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vsscanf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vswprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vswscanf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vwprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/vwscanf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/wbuf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/wcio.h [new file with mode: 0644]
lib/nbsd_libc/stdio/wprintf.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/wprintf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/wscanf.3 [new file with mode: 0644]
lib/nbsd_libc/stdio/wscanf.c [new file with mode: 0644]
lib/nbsd_libc/stdio/wsetup.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/Lint_abs.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/Lint_div.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/Lint_imaxabs.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/Lint_labs.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/Lint_ldiv.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/Lint_llabs.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/stdlib/_env.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/_rand48.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/a64l.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/a64l.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/abort.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/abort.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/abs.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/abs.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/alloca.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/atexit.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/atexit.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/atexit.h [new file with mode: 0644]
lib/nbsd_libc/stdlib/atof.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/atof.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/atoi.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/atoi.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/atol.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/atol.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/atoll.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/atoll.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/bsearch.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/bsearch.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/div.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/div.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/drand48.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/erand48.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/erand48_ieee754.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/exit.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/exit.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/getenv.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/getenv.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/getopt.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/getopt.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/getopt_long.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/getopt_long.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/getsubopt.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/getsubopt.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/grantpt.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/hcreate.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/hcreate.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/imaxabs.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/imaxabs.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/imaxdiv.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/imaxdiv.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/insque.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/insque.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/jemalloc.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/jemalloc.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/jrand48.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/l64a.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/labs.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/labs.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/lcong48.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/ldiv.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/ldiv.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/llabs.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/llabs.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/lldiv.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/lldiv.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/local.h [new file with mode: 0644]
lib/nbsd_libc/stdlib/lrand48.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/lsearch.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/lsearch.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/malloc.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/malloc.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/memory.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/merge.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/mi_vector_hash.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/mi_vector_hash.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/mrand48.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/nrand48.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/posix_memalign.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/posix_openpt.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/posix_openpt.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/ptsname.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/pty.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/putenv.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/qabs.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/qabs.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/qdiv.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/qdiv.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/qsort.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/qsort.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/radixsort.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/radixsort.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/rand.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/rand.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/rand48.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/rand48.h [new file with mode: 0644]
lib/nbsd_libc/stdlib/rand_r.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/random.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/remque.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/seed48.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/setenv.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/srand48.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/strfmon.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/strfmon.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/strsuftoll.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/strsuftoll.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/strtod.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/strtoimax.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/strtol.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/strtol.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/strtoq.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/strtoul.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/strtouq.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/system.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/system.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/tdelete.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/tfind.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/tsearch.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/tsearch.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/twalk.c [new file with mode: 0644]
lib/nbsd_libc/stdlib/unlockpt.3 [new file with mode: 0644]
lib/nbsd_libc/stdlib/unsetenv.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_bcmp.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_bcopy.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_bzero.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_ffs.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_index.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_memccpy.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_memchr.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_memcmp.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_memcpy.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_memmove.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_memset.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_rindex.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_strcat.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_strchr.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_strcmp.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_strcpy.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_strlen.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_strncat.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_strncmp.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_strncpy.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_strrchr.c [new file with mode: 0644]
lib/nbsd_libc/string/Lint_swab.c [new file with mode: 0644]
lib/nbsd_libc/string/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/string/__strsignal.c [new file with mode: 0644]
lib/nbsd_libc/string/_strerror_r.c [new file with mode: 0644]
lib/nbsd_libc/string/_strlcat.c [new file with mode: 0644]
lib/nbsd_libc/string/_strlcpy.c [new file with mode: 0644]
lib/nbsd_libc/string/bcmp.3 [new file with mode: 0644]
lib/nbsd_libc/string/bcopy.3 [new file with mode: 0644]
lib/nbsd_libc/string/bm.3 [new file with mode: 0644]
lib/nbsd_libc/string/bm.c [new file with mode: 0644]
lib/nbsd_libc/string/bstring.3 [new file with mode: 0644]
lib/nbsd_libc/string/bzero.3 [new file with mode: 0644]
lib/nbsd_libc/string/ffs.3 [new file with mode: 0644]
lib/nbsd_libc/string/index.3 [new file with mode: 0644]
lib/nbsd_libc/string/index.c [new file with mode: 0644]
lib/nbsd_libc/string/memccpy.3 [new file with mode: 0644]
lib/nbsd_libc/string/memccpy.c [new file with mode: 0644]
lib/nbsd_libc/string/memchr.3 [new file with mode: 0644]
lib/nbsd_libc/string/memcmp.3 [new file with mode: 0644]
lib/nbsd_libc/string/memcpy.3 [new file with mode: 0644]
lib/nbsd_libc/string/memmem.3 [new file with mode: 0644]
lib/nbsd_libc/string/memmem.c [new file with mode: 0644]
lib/nbsd_libc/string/memmove.3 [new file with mode: 0644]
lib/nbsd_libc/string/memrchr.c [new file with mode: 0644]
lib/nbsd_libc/string/memset.3 [new file with mode: 0644]
lib/nbsd_libc/string/popcount.3 [new file with mode: 0644]
lib/nbsd_libc/string/rindex.3 [new file with mode: 0644]
lib/nbsd_libc/string/rindex.c [new file with mode: 0644]
lib/nbsd_libc/string/stpcpy.c [new file with mode: 0644]
lib/nbsd_libc/string/stpncpy.c [new file with mode: 0644]
lib/nbsd_libc/string/strcasecmp.3 [new file with mode: 0644]
lib/nbsd_libc/string/strcasestr.c [new file with mode: 0644]
lib/nbsd_libc/string/strcat.3 [new file with mode: 0644]
lib/nbsd_libc/string/strchr.3 [new file with mode: 0644]
lib/nbsd_libc/string/strcmp.3 [new file with mode: 0644]
lib/nbsd_libc/string/strcoll.3 [new file with mode: 0644]
lib/nbsd_libc/string/strcoll.c [new file with mode: 0644]
lib/nbsd_libc/string/strcpy.3 [new file with mode: 0644]
lib/nbsd_libc/string/strcspn.3 [new file with mode: 0644]
lib/nbsd_libc/string/strcspn.c [new file with mode: 0644]
lib/nbsd_libc/string/strdup.3 [new file with mode: 0644]
lib/nbsd_libc/string/strdup.c [new file with mode: 0644]
lib/nbsd_libc/string/strerror.3 [new file with mode: 0644]
lib/nbsd_libc/string/strerror.c [new file with mode: 0644]
lib/nbsd_libc/string/strerror_r.c [new file with mode: 0644]
lib/nbsd_libc/string/stresep.c [new file with mode: 0644]
lib/nbsd_libc/string/string.3 [new file with mode: 0644]
lib/nbsd_libc/string/strings.3 [new file with mode: 0644]
lib/nbsd_libc/string/strlcpy.3 [new file with mode: 0644]
lib/nbsd_libc/string/strlen.3 [new file with mode: 0644]
lib/nbsd_libc/string/strmode.3 [new file with mode: 0644]
lib/nbsd_libc/string/strmode.c [new file with mode: 0644]
lib/nbsd_libc/string/strncat.c [new file with mode: 0644]
lib/nbsd_libc/string/strndup.c [new file with mode: 0644]
lib/nbsd_libc/string/strnlen.c [new file with mode: 0644]
lib/nbsd_libc/string/strpbrk.3 [new file with mode: 0644]
lib/nbsd_libc/string/strpbrk.c [new file with mode: 0644]
lib/nbsd_libc/string/strrchr.3 [new file with mode: 0644]
lib/nbsd_libc/string/strsep.3 [new file with mode: 0644]
lib/nbsd_libc/string/strsignal.3 [new file with mode: 0644]
lib/nbsd_libc/string/strsignal.c [new file with mode: 0644]
lib/nbsd_libc/string/strspn.3 [new file with mode: 0644]
lib/nbsd_libc/string/strspn.c [new file with mode: 0644]
lib/nbsd_libc/string/strstr.3 [new file with mode: 0644]
lib/nbsd_libc/string/strtok.3 [new file with mode: 0644]
lib/nbsd_libc/string/strtok.c [new file with mode: 0644]
lib/nbsd_libc/string/strtok_r.c [new file with mode: 0644]
lib/nbsd_libc/string/strxfrm.3 [new file with mode: 0644]
lib/nbsd_libc/string/strxfrm.c [new file with mode: 0644]
lib/nbsd_libc/string/swab.3 [new file with mode: 0644]
lib/nbsd_libc/string/swab.c [new file with mode: 0644]
lib/nbsd_libc/string/wcscasecmp.3 [new file with mode: 0644]
lib/nbsd_libc/string/wcscasecmp.c [new file with mode: 0644]
lib/nbsd_libc/string/wcscat.c [new file with mode: 0644]
lib/nbsd_libc/string/wcschr.c [new file with mode: 0644]
lib/nbsd_libc/string/wcscmp.c [new file with mode: 0644]
lib/nbsd_libc/string/wcscpy.c [new file with mode: 0644]
lib/nbsd_libc/string/wcscspn.c [new file with mode: 0644]
lib/nbsd_libc/string/wcsdup.3 [new file with mode: 0644]
lib/nbsd_libc/string/wcsdup.c [new file with mode: 0644]
lib/nbsd_libc/string/wcslcat.c [new file with mode: 0644]
lib/nbsd_libc/string/wcslcpy.c [new file with mode: 0644]
lib/nbsd_libc/string/wcslen.c [new file with mode: 0644]
lib/nbsd_libc/string/wcsncasecmp.c [new file with mode: 0644]
lib/nbsd_libc/string/wcsncat.c [new file with mode: 0644]
lib/nbsd_libc/string/wcsncmp.c [new file with mode: 0644]
lib/nbsd_libc/string/wcsncpy.c [new file with mode: 0644]
lib/nbsd_libc/string/wcspbrk.c [new file with mode: 0644]
lib/nbsd_libc/string/wcsrchr.c [new file with mode: 0644]
lib/nbsd_libc/string/wcsspn.c [new file with mode: 0644]
lib/nbsd_libc/string/wcsstr.c [new file with mode: 0644]
lib/nbsd_libc/string/wcstok.3 [new file with mode: 0644]
lib/nbsd_libc/string/wcstok.c [new file with mode: 0644]
lib/nbsd_libc/string/wcswcs.c [new file with mode: 0644]
lib/nbsd_libc/string/wcswidth.3 [new file with mode: 0644]
lib/nbsd_libc/string/wmemchr.3 [new file with mode: 0644]
lib/nbsd_libc/string/wmemchr.c [new file with mode: 0644]
lib/nbsd_libc/string/wmemcmp.c [new file with mode: 0644]
lib/nbsd_libc/string/wmemcpy.c [new file with mode: 0644]
lib/nbsd_libc/string/wmemmove.c [new file with mode: 0644]
lib/nbsd_libc/string/wmemset.c [new file with mode: 0644]
lib/nbsd_libc/sys/Lint___clone.c [new file with mode: 0644]
lib/nbsd_libc/sys/Lint___sigaction14.c [new file with mode: 0644]
lib/nbsd_libc/sys/Lint___syscall.c [new file with mode: 0644]
lib/nbsd_libc/sys/Lint___vfork14.c [new file with mode: 0644]
lib/nbsd_libc/sys/Lint_brk.c [new file with mode: 0644]
lib/nbsd_libc/sys/Lint_clone.c [new file with mode: 0644]
lib/nbsd_libc/sys/Lint_exect.c [new file with mode: 0644]
lib/nbsd_libc/sys/Lint_getcontext.c [new file with mode: 0644]
lib/nbsd_libc/sys/Lint_pipe.c [new file with mode: 0644]
lib/nbsd_libc/sys/Lint_ptrace.c [new file with mode: 0644]
lib/nbsd_libc/sys/Lint_sbrk.c [new file with mode: 0644]
lib/nbsd_libc/sys/Lint_syscall.c [new file with mode: 0644]
lib/nbsd_libc/sys/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/sys/_brk.c [new file with mode: 0644]
lib/nbsd_libc/sys/_exit.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_fork.c [new file with mode: 0644]
lib/nbsd_libc/sys/_getcontext.c [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_create.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_ctl.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_detach.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_exit.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_getname.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_getprivate.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_kill.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_park.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_self.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_setname.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_suspend.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_unpark.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_unpark_all.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_wait.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_lwp_wakeup.2 [new file with mode: 0644]
lib/nbsd_libc/sys/_pipe.c [new file with mode: 0644]
lib/nbsd_libc/sys/_sbrk.c [new file with mode: 0644]
lib/nbsd_libc/sys/accept.2 [new file with mode: 0644]
lib/nbsd_libc/sys/access.2 [new file with mode: 0644]
lib/nbsd_libc/sys/acct.2 [new file with mode: 0644]
lib/nbsd_libc/sys/adjtime.2 [new file with mode: 0644]
lib/nbsd_libc/sys/adjtime.c [new file with mode: 0644]
lib/nbsd_libc/sys/bind.2 [new file with mode: 0644]
lib/nbsd_libc/sys/brk.2 [new file with mode: 0644]
lib/nbsd_libc/sys/chdir.2 [new file with mode: 0644]
lib/nbsd_libc/sys/chflags.2 [new file with mode: 0644]
lib/nbsd_libc/sys/chmod.2 [new file with mode: 0644]
lib/nbsd_libc/sys/chown.2 [new file with mode: 0644]
lib/nbsd_libc/sys/chroot.2 [new file with mode: 0644]
lib/nbsd_libc/sys/clock_settime.2 [new file with mode: 0644]
lib/nbsd_libc/sys/clock_settime.c [new file with mode: 0644]
lib/nbsd_libc/sys/clone.2 [new file with mode: 0644]
lib/nbsd_libc/sys/close.2 [new file with mode: 0644]
lib/nbsd_libc/sys/connect.2 [new file with mode: 0644]
lib/nbsd_libc/sys/dup.2 [new file with mode: 0644]
lib/nbsd_libc/sys/execve.2 [new file with mode: 0644]
lib/nbsd_libc/sys/extattr_get_file.2 [new file with mode: 0644]
lib/nbsd_libc/sys/fcntl.2 [new file with mode: 0644]
lib/nbsd_libc/sys/fdatasync.2 [new file with mode: 0644]
lib/nbsd_libc/sys/fhopen.2 [new file with mode: 0644]
lib/nbsd_libc/sys/flock.2 [new file with mode: 0644]
lib/nbsd_libc/sys/fork.2 [new file with mode: 0644]
lib/nbsd_libc/sys/fsync.2 [new file with mode: 0644]
lib/nbsd_libc/sys/ftruncate.c [new file with mode: 0644]
lib/nbsd_libc/sys/getcontext.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getdents.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getfh.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getgid.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getgroups.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getitimer.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getlogin.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getpeername.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getpgrp.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getpid.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getpriority.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getrlimit.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getrusage.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getsid.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getsockname.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getsockopt.2 [new file with mode: 0644]
lib/nbsd_libc/sys/gettimeofday.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getuid.2 [new file with mode: 0644]
lib/nbsd_libc/sys/getvfsstat.2 [new file with mode: 0644]
lib/nbsd_libc/sys/intro.2 [new file with mode: 0644]
lib/nbsd_libc/sys/ioctl.2 [new file with mode: 0644]
lib/nbsd_libc/sys/issetugid.2 [new file with mode: 0644]
lib/nbsd_libc/sys/kill.2 [new file with mode: 0644]
lib/nbsd_libc/sys/kqueue.2 [new file with mode: 0644]
lib/nbsd_libc/sys/ktrace.2 [new file with mode: 0644]
lib/nbsd_libc/sys/lfs_bmapv.2 [new file with mode: 0644]
lib/nbsd_libc/sys/lfs_markv.2 [new file with mode: 0644]
lib/nbsd_libc/sys/lfs_segclean.2 [new file with mode: 0644]
lib/nbsd_libc/sys/lfs_segwait.2 [new file with mode: 0644]
lib/nbsd_libc/sys/link.2 [new file with mode: 0644]
lib/nbsd_libc/sys/listen.2 [new file with mode: 0644]
lib/nbsd_libc/sys/lseek.2 [new file with mode: 0644]
lib/nbsd_libc/sys/lseek.c [new file with mode: 0644]
lib/nbsd_libc/sys/madvise.2 [new file with mode: 0644]
lib/nbsd_libc/sys/makelintstub [new file with mode: 0755]
lib/nbsd_libc/sys/mincore.2 [new file with mode: 0644]
lib/nbsd_libc/sys/minherit.2 [new file with mode: 0644]
lib/nbsd_libc/sys/mkdir.2 [new file with mode: 0644]
lib/nbsd_libc/sys/mkfifo.2 [new file with mode: 0644]
lib/nbsd_libc/sys/mknod.2 [new file with mode: 0644]
lib/nbsd_libc/sys/mlock.2 [new file with mode: 0644]
lib/nbsd_libc/sys/mlockall.2 [new file with mode: 0644]
lib/nbsd_libc/sys/mmap.2 [new file with mode: 0644]
lib/nbsd_libc/sys/mmap.c [new file with mode: 0644]
lib/nbsd_libc/sys/modctl.2 [new file with mode: 0644]
lib/nbsd_libc/sys/mount.2 [new file with mode: 0644]
lib/nbsd_libc/sys/mprotect.2 [new file with mode: 0644]
lib/nbsd_libc/sys/mremap.2 [new file with mode: 0644]
lib/nbsd_libc/sys/msgctl.2 [new file with mode: 0644]
lib/nbsd_libc/sys/msgget.2 [new file with mode: 0644]
lib/nbsd_libc/sys/msgrcv.2 [new file with mode: 0644]
lib/nbsd_libc/sys/msgsnd.2 [new file with mode: 0644]
lib/nbsd_libc/sys/msync.2 [new file with mode: 0644]
lib/nbsd_libc/sys/munmap.2 [new file with mode: 0644]
lib/nbsd_libc/sys/nanosleep.2 [new file with mode: 0644]
lib/nbsd_libc/sys/nfssvc.2 [new file with mode: 0644]
lib/nbsd_libc/sys/ntp_adjtime.2 [new file with mode: 0644]
lib/nbsd_libc/sys/ntp_adjtime.c [new file with mode: 0644]
lib/nbsd_libc/sys/open.2 [new file with mode: 0644]
lib/nbsd_libc/sys/pathconf.2 [new file with mode: 0644]
lib/nbsd_libc/sys/pipe.2 [new file with mode: 0644]
lib/nbsd_libc/sys/pmc_control.2 [new file with mode: 0644]
lib/nbsd_libc/sys/poll.2 [new file with mode: 0644]
lib/nbsd_libc/sys/posix_fadvise.2 [new file with mode: 0644]
lib/nbsd_libc/sys/posix_fadvise.c [new file with mode: 0644]
lib/nbsd_libc/sys/posix_madvise.c [new file with mode: 0644]
lib/nbsd_libc/sys/pread.c [new file with mode: 0644]
lib/nbsd_libc/sys/preadv.c [new file with mode: 0644]
lib/nbsd_libc/sys/profil.2 [new file with mode: 0644]
lib/nbsd_libc/sys/ptrace.2 [new file with mode: 0644]
lib/nbsd_libc/sys/pwrite.c [new file with mode: 0644]
lib/nbsd_libc/sys/pwritev.c [new file with mode: 0644]
lib/nbsd_libc/sys/quotactl.2 [new file with mode: 0644]
lib/nbsd_libc/sys/rasctl.2 [new file with mode: 0644]
lib/nbsd_libc/sys/read.2 [new file with mode: 0644]
lib/nbsd_libc/sys/readlink.2 [new file with mode: 0644]
lib/nbsd_libc/sys/reboot.2 [new file with mode: 0644]
lib/nbsd_libc/sys/recv.2 [new file with mode: 0644]
lib/nbsd_libc/sys/rename.2 [new file with mode: 0644]
lib/nbsd_libc/sys/revoke.2 [new file with mode: 0644]
lib/nbsd_libc/sys/rmdir.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sa_enable.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sa_register.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sa_setconcurrency.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sa_stacks.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sa_yield.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sched.c [new file with mode: 0644]
lib/nbsd_libc/sys/select.2 [new file with mode: 0644]
lib/nbsd_libc/sys/semctl.2 [new file with mode: 0644]
lib/nbsd_libc/sys/semctl.c [new file with mode: 0644]
lib/nbsd_libc/sys/semget.2 [new file with mode: 0644]
lib/nbsd_libc/sys/semop.2 [new file with mode: 0644]
lib/nbsd_libc/sys/send.2 [new file with mode: 0644]
lib/nbsd_libc/sys/setgroups.2 [new file with mode: 0644]
lib/nbsd_libc/sys/setpgid.2 [new file with mode: 0644]
lib/nbsd_libc/sys/setregid.2 [new file with mode: 0644]
lib/nbsd_libc/sys/setreuid.2 [new file with mode: 0644]
lib/nbsd_libc/sys/setsid.2 [new file with mode: 0644]
lib/nbsd_libc/sys/settimeofday.c [new file with mode: 0644]
lib/nbsd_libc/sys/setuid.2 [new file with mode: 0644]
lib/nbsd_libc/sys/shmat.2 [new file with mode: 0644]
lib/nbsd_libc/sys/shmctl.2 [new file with mode: 0644]
lib/nbsd_libc/sys/shmget.2 [new file with mode: 0644]
lib/nbsd_libc/sys/shutdown.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sigaction.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sigaltstack.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sigpending.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sigprocmask.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sigqueue.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sigqueue.c [new file with mode: 0644]
lib/nbsd_libc/sys/sigstack.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sigsuspend.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sigtimedwait.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sigtimedwait.c [new file with mode: 0644]
lib/nbsd_libc/sys/sigwait.c [new file with mode: 0644]
lib/nbsd_libc/sys/sigwaitinfo.c [new file with mode: 0644]
lib/nbsd_libc/sys/socket.2 [new file with mode: 0644]
lib/nbsd_libc/sys/socketpair.2 [new file with mode: 0644]
lib/nbsd_libc/sys/stat.2 [new file with mode: 0644]
lib/nbsd_libc/sys/statvfs.2 [new file with mode: 0644]
lib/nbsd_libc/sys/statvfs.c [new file with mode: 0644]
lib/nbsd_libc/sys/swapctl.2 [new file with mode: 0644]
lib/nbsd_libc/sys/swapon.3 [new file with mode: 0644]
lib/nbsd_libc/sys/swapon.c [new file with mode: 0644]
lib/nbsd_libc/sys/symlink.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sync.2 [new file with mode: 0644]
lib/nbsd_libc/sys/sysarch.2 [new file with mode: 0644]
lib/nbsd_libc/sys/syscall.2 [new file with mode: 0644]
lib/nbsd_libc/sys/timer_create.2 [new file with mode: 0644]
lib/nbsd_libc/sys/timer_delete.2 [new file with mode: 0644]
lib/nbsd_libc/sys/timer_settime.2 [new file with mode: 0644]
lib/nbsd_libc/sys/truncate.2 [new file with mode: 0644]
lib/nbsd_libc/sys/truncate.c [new file with mode: 0644]
lib/nbsd_libc/sys/umask.2 [new file with mode: 0644]
lib/nbsd_libc/sys/undelete.2 [new file with mode: 0644]
lib/nbsd_libc/sys/unlink.2 [new file with mode: 0644]
lib/nbsd_libc/sys/utimes.2 [new file with mode: 0644]
lib/nbsd_libc/sys/utrace.2 [new file with mode: 0644]
lib/nbsd_libc/sys/uuidgen.2 [new file with mode: 0644]
lib/nbsd_libc/sys/vfork.2 [new file with mode: 0644]
lib/nbsd_libc/sys/wait.2 [new file with mode: 0644]
lib/nbsd_libc/sys/write.2 [new file with mode: 0644]
lib/nbsd_libc/termios/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/termios/cfgetispeed.c [new file with mode: 0644]
lib/nbsd_libc/termios/cfgetospeed.c [new file with mode: 0644]
lib/nbsd_libc/termios/cfmakeraw.c [new file with mode: 0644]
lib/nbsd_libc/termios/cfsetispeed.c [new file with mode: 0644]
lib/nbsd_libc/termios/cfsetospeed.c [new file with mode: 0644]
lib/nbsd_libc/termios/cfsetspeed.c [new file with mode: 0644]
lib/nbsd_libc/termios/tcdrain.c [new file with mode: 0644]
lib/nbsd_libc/termios/tcflow.c [new file with mode: 0644]
lib/nbsd_libc/termios/tcflush.c [new file with mode: 0644]
lib/nbsd_libc/termios/tcgetattr.c [new file with mode: 0644]
lib/nbsd_libc/termios/tcgetpgrp.3 [new file with mode: 0644]
lib/nbsd_libc/termios/tcgetpgrp.c [new file with mode: 0644]
lib/nbsd_libc/termios/tcgetsid.3 [new file with mode: 0644]
lib/nbsd_libc/termios/tcgetsid.c [new file with mode: 0644]
lib/nbsd_libc/termios/tcsendbreak.3 [new file with mode: 0644]
lib/nbsd_libc/termios/tcsendbreak.c [new file with mode: 0644]
lib/nbsd_libc/termios/tcsetattr.3 [new file with mode: 0644]
lib/nbsd_libc/termios/tcsetattr.c [new file with mode: 0644]
lib/nbsd_libc/termios/tcsetpgrp.3 [new file with mode: 0644]
lib/nbsd_libc/termios/tcsetpgrp.c [new file with mode: 0644]
lib/nbsd_libc/thread-stub/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/thread-stub/__isthreaded.c [new file with mode: 0644]
lib/nbsd_libc/thread-stub/thread-stub.c [new file with mode: 0644]
lib/nbsd_libc/time/Makefile [new file with mode: 0644]
lib/nbsd_libc/time/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/time/README [new file with mode: 0644]
lib/nbsd_libc/time/Theory [new file with mode: 0644]
lib/nbsd_libc/time/_daylight.c [new file with mode: 0644]
lib/nbsd_libc/time/asctime.c [new file with mode: 0644]
lib/nbsd_libc/time/checktab.awk [new file with mode: 0644]
lib/nbsd_libc/time/ctime.3 [new file with mode: 0644]
lib/nbsd_libc/time/difftime.c [new file with mode: 0644]
lib/nbsd_libc/time/getdate.3 [new file with mode: 0644]
lib/nbsd_libc/time/getdate.c [new file with mode: 0644]
lib/nbsd_libc/time/ialloc.c [new file with mode: 0644]
lib/nbsd_libc/time/localtime.c [new file with mode: 0644]
lib/nbsd_libc/time/offtime.3 [new file with mode: 0644]
lib/nbsd_libc/time/private.h [new file with mode: 0644]
lib/nbsd_libc/time/scheck.c [new file with mode: 0644]
lib/nbsd_libc/time/strftime.3 [new file with mode: 0644]
lib/nbsd_libc/time/strftime.c [new file with mode: 0644]
lib/nbsd_libc/time/strptime.3 [new file with mode: 0644]
lib/nbsd_libc/time/strptime.c [new file with mode: 0644]
lib/nbsd_libc/time/time2posix.3 [new file with mode: 0644]
lib/nbsd_libc/time/tz-art.htm [new file with mode: 0644]
lib/nbsd_libc/time/tz-link.htm [new file with mode: 0644]
lib/nbsd_libc/time/tzcode2netbsd [new file with mode: 0755]
lib/nbsd_libc/time/tzfile.5 [new file with mode: 0644]
lib/nbsd_libc/time/tzfile.h [new file with mode: 0644]
lib/nbsd_libc/time/tzselect.8 [new file with mode: 0644]
lib/nbsd_libc/time/tzselect.ksh [new file with mode: 0644]
lib/nbsd_libc/time/tzset.3 [new file with mode: 0644]
lib/nbsd_libc/time/zdump.8 [new file with mode: 0644]
lib/nbsd_libc/time/zdump.c [new file with mode: 0644]
lib/nbsd_libc/time/zic.8 [new file with mode: 0644]
lib/nbsd_libc/time/zic.c [new file with mode: 0644]
lib/nbsd_libc/uuid/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/uuid/uuid.3 [new file with mode: 0644]
lib/nbsd_libc/uuid/uuid_compare.c [new file with mode: 0644]
lib/nbsd_libc/uuid/uuid_create.c [new file with mode: 0644]
lib/nbsd_libc/uuid/uuid_create_nil.c [new file with mode: 0644]
lib/nbsd_libc/uuid/uuid_equal.c [new file with mode: 0644]
lib/nbsd_libc/uuid/uuid_from_string.c [new file with mode: 0644]
lib/nbsd_libc/uuid/uuid_hash.c [new file with mode: 0644]
lib/nbsd_libc/uuid/uuid_is_nil.c [new file with mode: 0644]
lib/nbsd_libc/uuid/uuid_stream.c [new file with mode: 0644]
lib/nbsd_libc/uuid/uuid_to_string.c [new file with mode: 0644]
lib/nbsd_libc/yp/Makefile.inc [new file with mode: 0644]
lib/nbsd_libc/yp/local.h [new file with mode: 0644]
lib/nbsd_libc/yp/xdryp.c [new file with mode: 0644]
lib/nbsd_libc/yp/yp_all.c [new file with mode: 0644]
lib/nbsd_libc/yp/yp_first.c [new file with mode: 0644]
lib/nbsd_libc/yp/yp_maplist.c [new file with mode: 0644]
lib/nbsd_libc/yp/yp_master.c [new file with mode: 0644]
lib/nbsd_libc/yp/yp_match.c [new file with mode: 0644]
lib/nbsd_libc/yp/yp_order.c [new file with mode: 0644]
lib/nbsd_libc/yp/ypclnt.3 [new file with mode: 0644]
lib/nbsd_libc/yp/yperr_string.c [new file with mode: 0644]
lib/nbsd_libc/yp/yplib.c [new file with mode: 0644]
lib/nbsd_libc/yp/ypprot_err.c [new file with mode: 0644]
nbsd_include/Makefile [new file with mode: 0644]
nbsd_include/a.out.h [new file with mode: 0644]
nbsd_include/aio.h [new file with mode: 0644]
nbsd_include/ar.h [new file with mode: 0644]
nbsd_include/arpa/ftp.h [new file with mode: 0644]
nbsd_include/arpa/inet.h [new file with mode: 0644]
nbsd_include/arpa/nameser.h [new file with mode: 0644]
nbsd_include/arpa/nameser_compat.h [new file with mode: 0644]
nbsd_include/arpa/telnet.h [new file with mode: 0644]
nbsd_include/arpa/tftp.h [new file with mode: 0644]
nbsd_include/assert.h [new file with mode: 0644]
nbsd_include/atomic.h [new file with mode: 0644]
nbsd_include/bitstring.h [new file with mode: 0644]
nbsd_include/bm.h [new file with mode: 0644]
nbsd_include/cdbr.h [new file with mode: 0644]
nbsd_include/cdbw.h [new file with mode: 0644]
nbsd_include/complex.h [new file with mode: 0644]
nbsd_include/cpio.h [new file with mode: 0644]
nbsd_include/ctype.h [new file with mode: 0644]
nbsd_include/db.h [new file with mode: 0644]
nbsd_include/dirent.h [new file with mode: 0644]
nbsd_include/disktab.h [new file with mode: 0644]
nbsd_include/dlfcn.h [new file with mode: 0644]
nbsd_include/err.h [new file with mode: 0644]
nbsd_include/errno.h [new file with mode: 0644]
nbsd_include/fenv.h [new file with mode: 0644]
nbsd_include/fmtmsg.h [new file with mode: 0644]
nbsd_include/fnmatch.h [new file with mode: 0644]
nbsd_include/fstab.h [new file with mode: 0644]
nbsd_include/fts.h [new file with mode: 0644]
nbsd_include/ftw.h [new file with mode: 0644]
nbsd_include/getopt.h [new file with mode: 0644]
nbsd_include/glob.h [new file with mode: 0644]
nbsd_include/grp.h [new file with mode: 0644]
nbsd_include/heimdal/config.h [new file with mode: 0644]
nbsd_include/heimdal/crypto-headers.h [new file with mode: 0644]
nbsd_include/heimdal/hx509_err.h [new file with mode: 0644]
nbsd_include/heimdal/krb5-types.h [new file with mode: 0644]
nbsd_include/heimdal/krb_err.h [new file with mode: 0644]
nbsd_include/heimdal/protos.h [new file with mode: 0644]
nbsd_include/heimdal/roken.h [new file with mode: 0644]
nbsd_include/heimdal/version.h [new file with mode: 0644]
nbsd_include/hesiod.h [new file with mode: 0644]
nbsd_include/iconv.h [new file with mode: 0644]
nbsd_include/ieeefp.h [new file with mode: 0644]
nbsd_include/ifaddrs.h [new file with mode: 0644]
nbsd_include/inttypes.h [new file with mode: 0644]
nbsd_include/iso646.h [new file with mode: 0644]
nbsd_include/kvm.h [new file with mode: 0644]
nbsd_include/langinfo.h [new file with mode: 0644]
nbsd_include/libgen.h [new file with mode: 0644]
nbsd_include/limits.h [new file with mode: 0644]
nbsd_include/link.h [new file with mode: 0644]
nbsd_include/link_aout.h [new file with mode: 0644]
nbsd_include/link_elf.h [new file with mode: 0644]
nbsd_include/locale.h [new file with mode: 0644]
nbsd_include/login_cap.h [new file with mode: 0644]
nbsd_include/lwp.h [new file with mode: 0644]
nbsd_include/malloc.h [new file with mode: 0644]
nbsd_include/math.h [new file with mode: 0644]
nbsd_include/md2.h [new file with mode: 0644]
nbsd_include/memory.h [new file with mode: 0644]
nbsd_include/mntopts.h [new file with mode: 0644]
nbsd_include/monetary.h [new file with mode: 0644]
nbsd_include/mpool.h [new file with mode: 0644]
nbsd_include/mqueue.h [new file with mode: 0644]
nbsd_include/ndbm.h [new file with mode: 0644]
nbsd_include/netconfig.h [new file with mode: 0644]
nbsd_include/netdb.h [new file with mode: 0644]
nbsd_include/netgroup.h [new file with mode: 0644]
nbsd_include/nl_types.h [new file with mode: 0644]
nbsd_include/nlist.h [new file with mode: 0644]
nbsd_include/nsswitch.h [new file with mode: 0644]
nbsd_include/paths.h [new file with mode: 0644]
nbsd_include/protocols/dumprestore.h [new file with mode: 0644]
nbsd_include/protocols/routed.h [new file with mode: 0644]
nbsd_include/protocols/rwhod.h [new file with mode: 0644]
nbsd_include/protocols/talkd.h [new file with mode: 0644]
nbsd_include/protocols/timed.h [new file with mode: 0644]
nbsd_include/pwd.h [new file with mode: 0644]
nbsd_include/randomid.h [new file with mode: 0644]
nbsd_include/ranlib.h [new file with mode: 0644]
nbsd_include/re_comp.h [new file with mode: 0644]
nbsd_include/regex.h [new file with mode: 0644]
nbsd_include/regexp.h [new file with mode: 0644]
nbsd_include/res_update.h [new file with mode: 0644]
nbsd_include/resolv.h [new file with mode: 0644]
nbsd_include/rmt.h [new file with mode: 0644]
nbsd_include/rpc/Makefile [new file with mode: 0644]
nbsd_include/rpc/auth.h [new file with mode: 0644]
nbsd_include/rpc/auth_unix.h [new file with mode: 0644]
nbsd_include/rpc/clnt.h [new file with mode: 0644]
nbsd_include/rpc/clnt_soc.h [new file with mode: 0644]
nbsd_include/rpc/nettype.h [new file with mode: 0644]
nbsd_include/rpc/pmap_clnt.h [new file with mode: 0644]
nbsd_include/rpc/pmap_prot.h [new file with mode: 0644]
nbsd_include/rpc/pmap_rmt.h [new file with mode: 0644]
nbsd_include/rpc/raw.h [new file with mode: 0644]
nbsd_include/rpc/rpc.h [new file with mode: 0644]
nbsd_include/rpc/rpc_com.h [new file with mode: 0644]
nbsd_include/rpc/rpc_msg.h [new file with mode: 0644]
nbsd_include/rpc/rpcb_clnt.h [new file with mode: 0644]
nbsd_include/rpc/rpcb_prot.x [new file with mode: 0644]
nbsd_include/rpc/rpcent.h [new file with mode: 0644]
nbsd_include/rpc/svc.h [new file with mode: 0644]
nbsd_include/rpc/svc_auth.h [new file with mode: 0644]
nbsd_include/rpc/svc_soc.h [new file with mode: 0644]
nbsd_include/rpc/types.h [new file with mode: 0644]
nbsd_include/rpc/xdr.h [new file with mode: 0644]
nbsd_include/rpcsvc/yp_prot.h [new file with mode: 0644]
nbsd_include/rpcsvc/ypclnt.h [new file with mode: 0644]
nbsd_include/sa.h [new file with mode: 0644]
nbsd_include/sched.h [new file with mode: 0644]
nbsd_include/search.h [new file with mode: 0644]
nbsd_include/semaphore.h [new file with mode: 0644]
nbsd_include/setjmp.h [new file with mode: 0644]
nbsd_include/sgtty.h [new file with mode: 0644]
nbsd_include/signal.h [new file with mode: 0644]
nbsd_include/ssp/ssp.h [new file with mode: 0644]
nbsd_include/ssp/stdio.h [new file with mode: 0644]
nbsd_include/ssp/string.h [new file with mode: 0644]
nbsd_include/ssp/strings.h [new file with mode: 0644]
nbsd_include/ssp/unistd.h [new file with mode: 0644]
nbsd_include/stab.h [new file with mode: 0644]
nbsd_include/stdbool.h [new file with mode: 0644]
nbsd_include/stddef.h [new file with mode: 0644]
nbsd_include/stdio.h [new file with mode: 0644]
nbsd_include/stdlib.h [new file with mode: 0644]
nbsd_include/string.h [new file with mode: 0644]
nbsd_include/stringlist.h [new file with mode: 0644]
nbsd_include/strings.h [new file with mode: 0644]
nbsd_include/struct.h [new file with mode: 0644]
nbsd_include/sysexits.h [new file with mode: 0644]
nbsd_include/tar.h [new file with mode: 0644]
nbsd_include/tgmath.h [new file with mode: 0644]
nbsd_include/time.h [new file with mode: 0644]
nbsd_include/ttyent.h [new file with mode: 0644]
nbsd_include/tzfile.h [new file with mode: 0644]
nbsd_include/ucontext.h [new file with mode: 0644]
nbsd_include/ulimit.h [new file with mode: 0644]
nbsd_include/unistd.h [new file with mode: 0644]
nbsd_include/util.h [new file with mode: 0644]
nbsd_include/utime.h [new file with mode: 0644]
nbsd_include/utmp.h [new file with mode: 0644]
nbsd_include/utmpx.h [new file with mode: 0644]
nbsd_include/uuid.h [new file with mode: 0644]
nbsd_include/varargs.h [new file with mode: 0644]
nbsd_include/vis.h [new file with mode: 0644]
nbsd_include/wchar.h [new file with mode: 0644]
nbsd_include/wctype.h [new file with mode: 0644]
nbsd_include/wordexp.h [new file with mode: 0644]

diff --git a/common/lib/libc/Makefile.inc b/common/lib/libc/Makefile.inc
new file mode 100644 (file)
index 0000000..1370edd
--- /dev/null
@@ -0,0 +1,37 @@
+# $NetBSD: Makefile.inc,v 1.10 2008/10/26 07:22:50 mrg Exp $
+
+COMMON_DIR:=${.PARSEDIR}
+COMMON_CODEDIRS=atomic gen gmon inet md net quad stdlib string sys
+COMMON_CODEDIRS+=hash/sha1 hash/sha2 hash/rmd160
+
+.if defined(COMMON_MACHINE_ARCH) && !empty(COMMON_MACHINE_ARCH) && \
+    exists(${COMMON_DIR}/arch/${COMMON_MACHINE_ARCH})
+COMMON_ARCHSUBDIR=     ${COMMON_MACHINE_ARCH}
+.elif defined(LIBKERN_ARCH) && !empty(LIBKERN_ARCH) && \
+    exists(${KERNDIR}/arch/${LIBKERN_ARCH})
+COMMON_ARCHSUBDIR=     ${LIBKERN_ARCH}
+.elif exists(${COMMON_DIR}/arch/${MACHINE_ARCH})
+COMMON_ARCHSUBDIR=     ${MACHINE_ARCH}
+.elif exists(${COMMON_DIR}/arch/${MACHINE_CPU})
+COMMON_ARCHSUBDIR=     ${MACHINE_CPU}
+.endif
+
+COMMON_ARCHDIR=${COMMON_DIR}/arch/${COMMON_ARCHSUBDIR}
+
+.for i in ${COMMON_CODEDIRS}
+.if exists(${COMMON_DIR}/$i)
+.PATH.c: ${COMMON_DIR}/$i
+.endif
+.if exists(${COMMON_ARCHDIR}/${i}/Makefile.inc)
+.include "${COMMON_ARCHDIR}/${i}/Makefile.inc"
+.endif
+.if exists(${COMMON_ARCHDIR}/$i)
+.PATH.c: ${COMMON_ARCHDIR}/$i
+.PATH.S: ${COMMON_ARCHDIR}/$i
+.endif
+.endfor
+
+CPPFLAGS+=-I${COMMON_DIR}/quad -I${COMMON_DIR}/string
+.if defined(COMMON_ARCHSUBDIR)
+CPPFLAGS+=-I${COMMON_ARCHDIR}/string
+.endif
diff --git a/common/lib/libc/arch/alpha/atomic/Makefile.inc b/common/lib/libc/arch/alpha/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..d0e0486
--- /dev/null
@@ -0,0 +1,15 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/01/04 17:54:29 pooka Exp $
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "c" || ${LIB} == "pthread" \
+       || ${LIB} == "rump")
+
+SRCS+= atomic_add.S atomic_and.S atomic_cas.S atomic_dec.S \
+       atomic_inc.S atomic_or.S atomic_swap.S membar_ops.S
+
+.endif
+
+.if defined(LIB) && (${LIB} == "c" || ${LIB} == "pthread")
+
+SRCS+= atomic_init_cas.c
+
+.endif
diff --git a/common/lib/libc/arch/alpha/atomic/atomic_add.S b/common/lib/libc/arch/alpha/atomic/atomic_add.S
new file mode 100644 (file)
index 0000000..e4fdb25
--- /dev/null
@@ -0,0 +1,88 @@
+/*     $NetBSD: atomic_add.S,v 1.4 2008/05/25 15:56:11 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+LEAF(_atomic_add_32, 2)
+1:     ldl_l   t1, 0(a0)
+       addl    t1, a1, t2
+       stl_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_32,_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_int,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_int,_atomic_add_32)
+
+LEAF(_atomic_add_32_nv, 2)
+1:     ldl_l   t1, 0(a0)
+       addl    t1, a1, t2
+       mov     t2, v0
+       stl_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_32_nv,_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_int_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_int_nv,_atomic_add_32_nv)
+
+LEAF(_atomic_add_64, 2)
+1:     ldq_l   t1, 0(a0)
+       addq    t1, a1, t2
+       stq_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_add_64)
+ATOMIC_OP_ALIAS(atomic_add_64,_atomic_add_64)
+ATOMIC_OP_ALIAS(atomic_add_long,_atomic_add_64)
+STRONG_ALIAS(_atomic_add_long,_atomic_add_64)
+ATOMIC_OP_ALIAS(atomic_add_ptr,_atomic_add_64)
+STRONG_ALIAS(_atomic_add_ptr,_atomic_add_64)
+
+LEAF(_atomic_add_64_nv, 2)
+1:     ldq_l   t1, 0(a0)
+       addq    t1, a1, t2
+       mov     t2, v0
+       stq_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_add_64_nv)
+ATOMIC_OP_ALIAS(atomic_add_64_nv,_atomic_add_64_nv)
+ATOMIC_OP_ALIAS(atomic_add_long_nv,_atomic_add_64_nv)
+STRONG_ALIAS(_atomic_add_long_nv,_atomic_add_64_nv)
+ATOMIC_OP_ALIAS(atomic_add_ptr_nv,_atomic_add_64_nv)
+STRONG_ALIAS(_atomic_add_ptr_nv,_atomic_add_64_nv)
diff --git a/common/lib/libc/arch/alpha/atomic/atomic_and.S b/common/lib/libc/arch/alpha/atomic/atomic_and.S
new file mode 100644 (file)
index 0000000..bc5daca
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: atomic_and.S,v 1.4 2008/05/25 15:56:11 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+LEAF(_atomic_and_32, 2)
+1:     ldl_l   t1, 0(a0)
+       and     t1, a1, t2
+       stl_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_32,_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_uint,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_uint,_atomic_and_32)
+
+LEAF(_atomic_and_32_nv, 2)
+1:     ldl_l   t1, 0(a0)
+       and     t1, a1, t2
+       mov     t2, v0
+       stl_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_and_32_nv)
+ATOMIC_OP_ALIAS(atomic_and_32_nv,_atomic_and_32_nv)
+ATOMIC_OP_ALIAS(atomic_and_uint_nv,_atomic_and_32_nv)
+STRONG_ALIAS(_atomic_and_uint_nv,_atomic_and_32_nv)
+
+LEAF(_atomic_and_64, 2)
+1:     ldq_l   t1, 0(a0)
+       and     t1, a1, t2
+       stq_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_and_64)
+ATOMIC_OP_ALIAS(atomic_and_64,_atomic_and_64)
+ATOMIC_OP_ALIAS(atomic_and_ulong,_atomic_and_64)
+STRONG_ALIAS(_atomic_and_ulong,_atomic_and_64)
+
+LEAF(_atomic_and_64_nv, 2)
+1:     ldq_l   t1, 0(a0)
+       and     t1, a1, t2
+       mov     t2, v0
+       stq_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_and_64_nv)
+ATOMIC_OP_ALIAS(atomic_and_64_nv,_atomic_and_64_nv)
+ATOMIC_OP_ALIAS(atomic_and_ulong_nv,_atomic_and_64_nv)
+STRONG_ALIAS(_atomic_and_ulong_nv,_atomic_and_64_nv)
diff --git a/common/lib/libc/arch/alpha/atomic/atomic_cas.S b/common/lib/libc/arch/alpha/atomic/atomic_cas.S
new file mode 100644 (file)
index 0000000..d959485
--- /dev/null
@@ -0,0 +1,78 @@
+/*     $NetBSD: atomic_cas.S,v 1.5 2008/05/25 15:56:11 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007, 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+LEAF(_atomic_cas_32, 3)
+1:     mov     a2, t2
+       ldl_l   v0, 0(a0)
+       cmpeq   v0, a1, t1
+       beq     t1, 2f
+       stl_c   t2, 0(a0)
+       beq     t2, 3f
+2:     RET
+3:     br      1b
+       END(_atomic_cas_32)
+
+ATOMIC_OP_ALIAS(atomic_cas_32,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_uint,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_uint,_atomic_cas_32)
+
+ATOMIC_OP_ALIAS(atomic_cas_32_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_32_ni,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_uint_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_uint_ni,_atomic_cas_32)
+
+LEAF(_atomic_cas_64, 3)
+1:     mov     a2, t2
+       ldq_l   v0, 0(a0)
+       cmpeq   v0, a1, t1
+       beq     t1, 2f
+       stq_c   t2, 0(a0)
+       beq     t2, 3f
+2:     RET
+3:     br      1b
+       END(_atomic_cas_64)
+
+ATOMIC_OP_ALIAS(atomic_cas_64,_atomic_cas_64)
+ATOMIC_OP_ALIAS(atomic_cas_ulong,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ulong,_atomic_cas_64)
+ATOMIC_OP_ALIAS(atomic_cas_ptr,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ptr,_atomic_cas_64)
+
+ATOMIC_OP_ALIAS(atomic_cas_64_ni,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_64_ni,_atomic_cas_64)
+ATOMIC_OP_ALIAS(atomic_cas_ulong_ni,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ulong_ni,_atomic_cas_64)
+ATOMIC_OP_ALIAS(atomic_cas_ptr_ni,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ptr_ni,_atomic_cas_64)
diff --git a/common/lib/libc/arch/alpha/atomic/atomic_dec.S b/common/lib/libc/arch/alpha/atomic/atomic_dec.S
new file mode 100644 (file)
index 0000000..982a1da
--- /dev/null
@@ -0,0 +1,88 @@
+/*     $NetBSD: atomic_dec.S,v 1.4 2008/05/25 15:56:11 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+LEAF(_atomic_dec_32, 1)
+1:     ldl_l   t1, 0(a0)
+       subl    t1, 1, t2
+       stl_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_32,_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_uint,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_uint,_atomic_dec_32)
+
+LEAF(_atomic_dec_32_nv, 1)
+1:     ldl_l   t1, 0(a0)
+       subl    t1, 1, t2
+       mov     t2, v0
+       stl_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_32_nv,_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_uint_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_uint_nv,_atomic_dec_32_nv)
+
+LEAF(_atomic_dec_64, 1)
+1:     ldq_l   t1, 0(a0)
+       subq    t1, 1, t2
+       stq_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_dec_64)
+ATOMIC_OP_ALIAS(atomic_dec_64,_atomic_dec_64)
+ATOMIC_OP_ALIAS(atomic_dec_ulong,_atomic_dec_64)
+STRONG_ALIAS(_atomic_dec_ulong,_atomic_dec_64)
+ATOMIC_OP_ALIAS(atomic_dec_ptr,_atomic_dec_64)
+STRONG_ALIAS(_atomic_dec_ptr,_atomic_dec_64)
+
+LEAF(_atomic_dec_64_nv, 1)
+1:     ldq_l   t1, 0(a0)
+       subq    t1, 1, t2
+       mov     t2, v0
+       stq_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_dec_64_nv)
+ATOMIC_OP_ALIAS(atomic_dec_64_nv,_atomic_dec_64_nv)
+ATOMIC_OP_ALIAS(atomic_dec_ulong_nv,_atomic_dec_64_nv)
+STRONG_ALIAS(_atomic_dec_ulong_nv,_atomic_dec_64_nv)
+ATOMIC_OP_ALIAS(atomic_dec_ptr_nv,_atomic_dec_64_nv)
+STRONG_ALIAS(_atomic_dec_ptr_nv,_atomic_dec_64_nv)
diff --git a/common/lib/libc/arch/alpha/atomic/atomic_inc.S b/common/lib/libc/arch/alpha/atomic/atomic_inc.S
new file mode 100644 (file)
index 0000000..6796cbf
--- /dev/null
@@ -0,0 +1,88 @@
+/*     $NetBSD: atomic_inc.S,v 1.4 2008/05/25 15:56:11 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+LEAF(_atomic_inc_32, 1)
+1:     ldl_l   t1, 0(a0)
+       addl    t1, 1, t2
+       stl_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_32,_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_uint,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_uint,_atomic_inc_32)
+
+LEAF(_atomic_inc_32_nv, 1)
+1:     ldl_l   t1, 0(a0)
+       addl    t1, 1, t2
+       mov     t2, v0
+       stl_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_32_nv,_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_uint_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_uint_nv,_atomic_inc_32_nv)
+
+LEAF(_atomic_inc_64, 1)
+1:     ldq_l   t1, 0(a0)
+       addq    t1, 1, t2
+       stq_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_inc_64)
+ATOMIC_OP_ALIAS(atomic_inc_64,_atomic_inc_64)
+ATOMIC_OP_ALIAS(atomic_inc_ulong,_atomic_inc_64)
+STRONG_ALIAS(_atomic_inc_ulong,_atomic_inc_64)
+ATOMIC_OP_ALIAS(atomic_inc_ptr,_atomic_inc_64)
+STRONG_ALIAS(_atomic_inc_ptr,_atomic_inc_64)
+
+LEAF(_atomic_inc_64_nv, 1)
+1:     ldq_l   t1, 0(a0)
+       addq    t1, 1, t2
+       mov     t2, v0
+       stq_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_inc_64_nv)
+ATOMIC_OP_ALIAS(atomic_inc_64_nv,_atomic_inc_64_nv)
+ATOMIC_OP_ALIAS(atomic_inc_ulong_nv,_atomic_inc_64_nv)
+STRONG_ALIAS(_atomic_inc_ulong_nv,_atomic_inc_64_nv)
+ATOMIC_OP_ALIAS(atomic_inc_ptr_nv,_atomic_inc_64_nv)
+STRONG_ALIAS(_atomic_inc_ptr_nv,_atomic_inc_64_nv)
diff --git a/common/lib/libc/arch/alpha/atomic/atomic_op_asm.h b/common/lib/libc/arch/alpha/atomic/atomic_op_asm.h
new file mode 100644 (file)
index 0000000..5f01f3f
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: atomic_op_asm.h,v 1.3 2008/04/28 20:22:52 martin Exp $ */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _ATOMIC_OP_ASM_H_
+#define        _ATOMIC_OP_ASM_H_
+
+#include <machine/asm.h>
+
+#if defined(_KERNEL)
+
+#define        ATOMIC_OP_ALIAS(a,s)    STRONG_ALIAS(a,s)
+
+#else /* _KERNEL */
+
+#define        ATOMIC_OP_ALIAS(a,s)    WEAK_ALIAS(a,s)
+
+#endif /* _KERNEL */
+
+#endif /* _ATOMIC_OP_ASM_H_ */
diff --git a/common/lib/libc/arch/alpha/atomic/atomic_or.S b/common/lib/libc/arch/alpha/atomic/atomic_or.S
new file mode 100644 (file)
index 0000000..a08a71c
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: atomic_or.S,v 1.4 2008/05/25 15:56:11 chs Exp $        */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+LEAF(_atomic_or_32, 2)
+1:     ldl_l   t1, 0(a0)
+       bis     t1, a1, t2
+       stl_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_32,_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_uint,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_uint,_atomic_or_32)
+
+LEAF(_atomic_or_32_nv, 2)
+1:     ldl_l   t1, 0(a0)
+       bis     t1, a1, t2
+       mov     t2, v0
+       stl_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_or_32_nv)
+ATOMIC_OP_ALIAS(atomic_or_32_nv,_atomic_or_32_nv)
+ATOMIC_OP_ALIAS(atomic_or_uint_nv,_atomic_or_32_nv)
+STRONG_ALIAS(_atomic_or_uint_nv,_atomic_or_32_nv)
+
+LEAF(_atomic_or_64, 2)
+1:     ldq_l   t1, 0(a0)
+       bis     t1, a1, t2
+       stq_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_or_64)
+ATOMIC_OP_ALIAS(atomic_or_64,_atomic_or_64)
+ATOMIC_OP_ALIAS(atomic_or_ulong,_atomic_or_64)
+STRONG_ALIAS(_atomic_or_ulong,_atomic_or_64)
+
+LEAF(_atomic_or_64_nv, 2)
+1:     ldq_l   t1, 0(a0)
+       bis     t1, a1, t2
+       mov     t2, v0
+       stq_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_or_64_nv)
+ATOMIC_OP_ALIAS(atomic_or_64_nv,_atomic_or_64_nv)
+ATOMIC_OP_ALIAS(atomic_or_ulong_nv,_atomic_or_64_nv)
+STRONG_ALIAS(_atomic_or_ulong_nv,_atomic_or_64_nv)
diff --git a/common/lib/libc/arch/alpha/atomic/atomic_swap.S b/common/lib/libc/arch/alpha/atomic/atomic_swap.S
new file mode 100644 (file)
index 0000000..3ccfe2f
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: atomic_swap.S,v 1.4 2008/05/25 15:56:11 chs Exp $      */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+LEAF(_atomic_swap_32, 2)
+1:     ldl_l   v0, 0(a0)
+       mov     a1, t2
+       stl_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_32,_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_uint,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_uint,_atomic_swap_32)
+
+LEAF(_atomic_swap_64, 2)
+1:     ldq_l   v0, 0(a0)
+       mov     a1, t2
+       stq_c   t2, 0(a0)
+       beq     t2, 2f
+       RET
+2:     br      1b
+       END(_atomic_swap_64)
+ATOMIC_OP_ALIAS(atomic_swap_64,_atomic_swap_64)
+ATOMIC_OP_ALIAS(atomic_swap_ulong,_atomic_swap_64)
+STRONG_ALIAS(_atomic_swap_ulong,_atomic_swap_64)
+ATOMIC_OP_ALIAS(atomic_swap_ptr,_atomic_swap_64)
+STRONG_ALIAS(_atomic_swap_ptr,_atomic_swap_64)
diff --git a/common/lib/libc/arch/alpha/atomic/membar_ops.S b/common/lib/libc/arch/alpha/atomic/membar_ops.S
new file mode 100644 (file)
index 0000000..f0162ec
--- /dev/null
@@ -0,0 +1,89 @@
+/*     $NetBSD: membar_ops.S,v 1.6 2008/05/25 15:56:11 chs Exp $       */
+
+/*-
+ * Copyright (c) 2006, 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+#ifdef _KERNEL
+
+/*
+ * We start out with no-op versions that do nothing.  We hot-patch when
+ * we detect a MP system.
+ */
+LEAF(_membar_producer, 0)
+       RET
+       nop
+       END(_membar_producer)
+EXPORT(_membar_producer_end)
+
+LEAF(_membar_sync, 0)
+       RET
+       nop
+       END(_membar_sync)
+EXPORT(_membar_sync_end)
+
+LEAF(_membar_producer_mp, 0)
+       wmb
+       RET
+       END(_membar_producer_mp)
+EXPORT(_membar_producer_mp_end)
+
+LEAF(_membar_sync_mp, 0)
+       mb
+       RET
+       END(_membar_sync_mp)
+EXPORT(_membar_sync_mp_end)
+
+#else  /* _KERNEL */
+
+LEAF(_membar_producer, 0)
+       mb
+       RET
+       END(_membar_producer)
+EXPORT(_membar_producer_end)
+
+LEAF(_membar_sync, 0)
+       mb
+       RET
+       END(_membar_sync)
+EXPORT(_membar_sync_end)
+
+#endif /* _KERNEL */
+
+ATOMIC_OP_ALIAS(membar_producer,_membar_producer)
+ATOMIC_OP_ALIAS(membar_sync,_membar_sync)
+ATOMIC_OP_ALIAS(membar_enter,_membar_sync)
+STRONG_ALIAS(_membar_enter,_membar_sync)
+ATOMIC_OP_ALIAS(membar_exit,_membar_sync)
+STRONG_ALIAS(_membar_exit,_membar_sync)
+ATOMIC_OP_ALIAS(membar_consumer,_membar_sync)
+STRONG_ALIAS(_membar_consumer,_membar_sync)
diff --git a/common/lib/libc/arch/alpha/gen/byte_swap_2.S b/common/lib/libc/arch/alpha/gen/byte_swap_2.S
new file mode 100644 (file)
index 0000000..95dab09
--- /dev/null
@@ -0,0 +1,49 @@
+/* $NetBSD: byte_swap_2.S,v 1.3 2008/02/16 17:37:13 apb Exp $ */
+
+/*
+ * Copyright (c) 1996 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ *
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ *
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ *
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+
+/*
+ * Byte-swap a 2-byte quantity.  (Convert 0x0123 to 0x2301.)
+ *
+ * Argument is an unsigned 2-byte integer (uint16_t).
+ */
+#if defined(_KERNEL) || defined(_STANDALONE)
+#define        BSWAP16 bswap16
+#else /* defined(_KERNEL) || defined(_STANDALONE) */
+#define        BSWAP16 __bswap16
+#endif /* defined(_KERNEL) || defined(_STANDALONE) */
+LEAF(BSWAP16, 1)               /* a0 contains 0x0123 */
+XLEAF(htons, 1)
+XLEAF(ntohs, 1)
+       insbl   a0, 1, t0       /* t0 = 0x23   */
+       extbl   a0, 1, t1       /* t1 = 0x  01 */
+       or      t0, t1, v0      /* v0 = 0x2301 */
+       RET
+END(BSWAP16)
diff --git a/common/lib/libc/arch/alpha/gen/byte_swap_4.S b/common/lib/libc/arch/alpha/gen/byte_swap_4.S
new file mode 100644 (file)
index 0000000..38b11f8
--- /dev/null
@@ -0,0 +1,55 @@
+/* $NetBSD: byte_swap_4.S,v 1.3 2008/02/16 17:37:13 apb Exp $ */
+
+/*
+ * Copyright (c) 1996 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ *
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ *
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ *
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+
+/*
+ * Byte-swap a 4-byte quantity.  (Convert 0x01234567 to 0x67452301.)
+ *
+ * Argument is an unsigned 4-byte integer (uint32_t).
+ */
+#if defined(_KERNEL) || defined(_STANDALONE)
+#define        BSWAP32 bswap32
+#else /* defined(_KERNEL) || defined(_STANDALONE) */
+#define        BSWAP32 __bswap32
+#endif /* defined(_KERNEL) || defined(_STANDALONE) */
+LEAF(BSWAP32, 1)               /* a0 contains 0x01234567 */
+XLEAF(htonl, 1)
+XLEAF(ntohl, 1)
+       insbl   a0, 3, t0       /* t0 = 0x67       */
+       extbl   a0, 1, t1       /* t1 = 0x      45 */
+       extbl   a0, 2, t2       /* t2 = 0x      23 */
+       extbl   a0, 3, t3       /* t3 = 0x      01 */
+       sll     t1, 16, t1      /* t1 = 0x  45     */
+       sll     t2, 8, t2       /* t2 = 0x    23   */
+       or      t3, t0, v0      /* v0 = 0x67    01 */
+       or      t1, t2, t1      /* t1 = 0x  4523   */
+       or      t1, v0, v0      /* v0 = 0x67452301 */
+       RET
+END(BSWAP32)
diff --git a/common/lib/libc/arch/alpha/gmon/_mcount.S b/common/lib/libc/arch/alpha/gmon/_mcount.S
new file mode 100644 (file)
index 0000000..53d92e6
--- /dev/null
@@ -0,0 +1,128 @@
+/* $NetBSD: _mcount.S,v 1.2 2005/12/21 18:11:11 christos Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995, 1996 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#if defined(GPROF) && !defined(_STANDALONE)
+
+#include <machine/asm.h>
+#include <machine/profile.h>
+
+#define        OFFSET_AT       (0 * 8)
+#define OFFSET_V0      (1 * 8)
+#define OFFSET_T0      (2 * 8)
+#define OFFSET_T1      (3 * 8)
+#define OFFSET_T2      (4 * 8)
+#define OFFSET_T3      (5 * 8)
+#define OFFSET_T4      (6 * 8)
+#define OFFSET_T5      (7 * 8)
+#define OFFSET_T6      (8 * 8)
+#define OFFSET_T7      (9 * 8)
+#define OFFSET_S6      (10 * 8)
+#define OFFSET_A0      (11 * 8)
+#define OFFSET_A1      (12 * 8)
+#define OFFSET_A2      (13 * 8)
+#define OFFSET_A3      (14 * 8)
+#define OFFSET_A4      (15 * 8)
+#define OFFSET_A5      (16 * 8)
+#define OFFSET_T8      (17 * 8)
+#define OFFSET_T9      (18 * 8)
+#define OFFSET_T10     (19 * 8)
+#define OFFSET_T11     (20 * 8)
+#define OFFSET_RA      (21 * 8)
+#define OFFSET_T12     (22 * 8)
+#define OFFSET_GP      (23 * 8)
+#define        FRAME_SIZE      (24 * 8)
+
+LEAF_NOPROFILE(_mcount,0)              /* XXX */
+       .set noat
+       .set noreorder
+
+       lda     sp, -FRAME_SIZE(sp)
+
+       stq     at_reg, OFFSET_AT(sp)
+       stq     v0, OFFSET_V0(sp)
+       stq     t0, OFFSET_T0(sp)
+       stq     t1, OFFSET_T1(sp)
+       stq     t2, OFFSET_T2(sp)
+       stq     t3, OFFSET_T3(sp)
+       stq     t4, OFFSET_T4(sp)
+       stq     t5, OFFSET_T5(sp)
+       stq     t6, OFFSET_T6(sp)
+       stq     t7, OFFSET_T7(sp)
+       stq     s6, OFFSET_S6(sp)       /* XXX because run _after_ prologue. */
+       stq     a0, OFFSET_A0(sp)
+       stq     a1, OFFSET_A1(sp)
+       stq     a2, OFFSET_A2(sp)
+       stq     a3, OFFSET_A3(sp)
+       stq     a4, OFFSET_A4(sp)
+       stq     a5, OFFSET_A5(sp)
+       stq     t8, OFFSET_T8(sp)
+       stq     t9, OFFSET_T9(sp)
+       stq     t10, OFFSET_T10(sp)
+       stq     t11, OFFSET_T11(sp)
+       stq     ra, OFFSET_RA(sp)
+       stq     t12, OFFSET_T12(sp)
+       stq     gp, OFFSET_GP(sp)
+
+       br      pv, 1f
+1:     LDGP(pv)
+       mov     ra, a0
+       mov     at_reg, a1
+       CALL(_MCOUNT_FUNC)
+
+       ldq     v0, OFFSET_V0(sp)
+       ldq     t0, OFFSET_T0(sp)
+       ldq     t1, OFFSET_T1(sp)
+       ldq     t2, OFFSET_T2(sp)
+       ldq     t3, OFFSET_T3(sp)
+       ldq     t4, OFFSET_T4(sp)
+       ldq     t5, OFFSET_T5(sp)
+       ldq     t6, OFFSET_T6(sp)
+       ldq     t7, OFFSET_T7(sp)
+       ldq     s6, OFFSET_S6(sp)       /* XXX because run _after_ prologue. */
+       ldq     a0, OFFSET_A0(sp)
+       ldq     a1, OFFSET_A1(sp)
+       ldq     a2, OFFSET_A2(sp)
+       ldq     a3, OFFSET_A3(sp)
+       ldq     a4, OFFSET_A4(sp)
+       ldq     a5, OFFSET_A5(sp)
+       ldq     t8, OFFSET_T8(sp)
+       ldq     t9, OFFSET_T9(sp)
+       ldq     t10, OFFSET_T10(sp)
+       ldq     t11, OFFSET_T11(sp)
+       ldq     ra, OFFSET_RA(sp)
+       ldq     t12, OFFSET_T12(sp)
+       ldq     gp, OFFSET_GP(sp)
+
+       ldq     at_reg, OFFSET_AT(sp)
+
+       lda     sp, FRAME_SIZE(sp)
+       ret     zero, (at_reg), 1
+
+       END(_mcount)
+#endif
diff --git a/common/lib/libc/arch/alpha/string/bcopy.S b/common/lib/libc/arch/alpha/string/bcopy.S
new file mode 100644 (file)
index 0000000..785e354
--- /dev/null
@@ -0,0 +1,288 @@
+/* $NetBSD: bcopy.S,v 1.1 2005/12/20 19:28:49 christos Exp $ */
+
+/*
+ * Copyright (c) 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Trevor Blackwell.  Support for use as memcpy() and memmove()
+ *        added by Chris Demetriou.
+ *
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ *
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ *
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+
+#if defined(MEMCOPY) || defined(MEMMOVE)
+#ifdef MEMCOPY
+#define        FUNCTION        memcpy
+#else
+#define FUNCTION       memmove
+#endif
+#define        SRCREG          a1
+#define        DSTREG          a0
+#else /* !(defined(MEMCOPY) || defined(MEMMOVE)) */
+#define        FUNCTION        bcopy
+#define        SRCREG          a0
+#define        DSTREG          a1
+#endif /* !(defined(MEMCOPY) || defined(MEMMOVE)) */
+
+#define        SIZEREG         a2
+
+/*
+ * Copy bytes.
+ *
+ * void bcopy(char *from, char *to, size_t len);
+ * char *memcpy(void *to, const void *from, size_t len);
+ * char *memmove(void *to, const void *from, size_t len);
+ *
+ * No matter how invoked, the source and destination registers
+ * for calculation.  There's no point in copying them to "working"
+ * registers, since the code uses their values "in place," and
+ * copying them would be slower.
+ */
+
+LEAF(FUNCTION,3)
+
+#if defined(MEMCOPY) || defined(MEMMOVE)
+       /* set up return value, while we still can */
+       mov     DSTREG,v0
+#endif
+
+       /* Check for negative length */
+       ble     SIZEREG,bcopy_done
+
+       /* Check for overlap */
+       subq    DSTREG,SRCREG,t5
+       cmpult  t5,SIZEREG,t5
+       bne     t5,bcopy_overlap
+
+       /* a3 = end address */
+       addq    SRCREG,SIZEREG,a3
+
+       /* Get the first word */
+       ldq_u   t2,0(SRCREG)
+
+       /* Do they have the same alignment? */
+       xor     SRCREG,DSTREG,t0
+       and     t0,7,t0
+       and     DSTREG,7,t1
+       bne     t0,bcopy_different_alignment
+
+       /* src & dst have same alignment */
+       beq     t1,bcopy_all_aligned
+
+       ldq_u   t3,0(DSTREG)
+       addq    SIZEREG,t1,SIZEREG
+       mskqh   t2,SRCREG,t2
+       mskql   t3,SRCREG,t3
+       or      t2,t3,t2
+
+       /* Dst is 8-byte aligned */
+
+bcopy_all_aligned:
+       /* If less than 8 bytes,skip loop */
+       subq    SIZEREG,1,t0
+       and     SIZEREG,7,SIZEREG
+       bic     t0,7,t0
+       beq     t0,bcopy_samealign_lp_end
+
+bcopy_samealign_lp:
+       stq_u   t2,0(DSTREG)
+       addq    DSTREG,8,DSTREG
+       ldq_u   t2,8(SRCREG)
+       subq    t0,8,t0
+       addq    SRCREG,8,SRCREG
+       bne     t0,bcopy_samealign_lp
+
+bcopy_samealign_lp_end:
+       /* If we're done, exit */
+       bne     SIZEREG,bcopy_small_left
+       stq_u   t2,0(DSTREG)
+       RET
+
+bcopy_small_left:
+       mskql   t2,SIZEREG,t4
+       ldq_u   t3,0(DSTREG)
+       mskqh   t3,SIZEREG,t3
+       or      t4,t3,t4
+       stq_u   t4,0(DSTREG)
+       RET
+
+bcopy_different_alignment:
+       /*
+        * this is the fun part
+        */
+       addq    SRCREG,SIZEREG,a3
+       cmpule  SIZEREG,8,t0
+       bne     t0,bcopy_da_finish
+
+       beq     t1,bcopy_da_noentry
+
+       /* Do the initial partial word */
+       subq    zero,DSTREG,t0
+       and     t0,7,t0
+       ldq_u   t3,7(SRCREG)
+       extql   t2,SRCREG,t2
+       extqh   t3,SRCREG,t3
+       or      t2,t3,t5
+       insql   t5,DSTREG,t5
+       ldq_u   t6,0(DSTREG)
+       mskql   t6,DSTREG,t6
+       or      t5,t6,t5
+       stq_u   t5,0(DSTREG)
+       addq    SRCREG,t0,SRCREG
+       addq    DSTREG,t0,DSTREG
+       subq    SIZEREG,t0,SIZEREG
+       ldq_u   t2,0(SRCREG)
+
+bcopy_da_noentry:
+       subq    SIZEREG,1,t0
+       bic     t0,7,t0
+       and     SIZEREG,7,SIZEREG
+       beq     t0,bcopy_da_finish2
+
+bcopy_da_lp:
+       ldq_u   t3,7(SRCREG)
+       addq    SRCREG,8,SRCREG
+       extql   t2,SRCREG,t4
+       extqh   t3,SRCREG,t5
+       subq    t0,8,t0
+       or      t4,t5,t5
+       stq     t5,0(DSTREG)
+       addq    DSTREG,8,DSTREG
+       beq     t0,bcopy_da_finish1
+       ldq_u   t2,7(SRCREG)
+       addq    SRCREG,8,SRCREG
+       extql   t3,SRCREG,t4
+       extqh   t2,SRCREG,t5
+       subq    t0,8,t0
+       or      t4,t5,t5
+       stq     t5,0(DSTREG)
+       addq    DSTREG,8,DSTREG
+       bne     t0,bcopy_da_lp
+
+bcopy_da_finish2:
+       /* Do the last new word */
+       mov     t2,t3
+
+bcopy_da_finish1:
+       /* Do the last partial word */
+       ldq_u   t2,-1(a3)
+       extql   t3,SRCREG,t3
+       extqh   t2,SRCREG,t2
+       or      t2,t3,t2
+       br      zero,bcopy_samealign_lp_end
+
+bcopy_da_finish:
+       /* Do the last word in the next source word */
+       ldq_u   t3,-1(a3)
+       extql   t2,SRCREG,t2
+       extqh   t3,SRCREG,t3
+       or      t2,t3,t2
+       insqh   t2,DSTREG,t3
+       insql   t2,DSTREG,t2
+       lda     t4,-1(zero)
+       mskql   t4,SIZEREG,t5
+       cmovne  t5,t5,t4
+       insqh   t4,DSTREG,t5
+       insql   t4,DSTREG,t4
+       addq    DSTREG,SIZEREG,a4
+       ldq_u   t6,0(DSTREG)
+       ldq_u   t7,-1(a4)
+       bic     t6,t4,t6
+       bic     t7,t5,t7
+       and     t2,t4,t2
+       and     t3,t5,t3
+       or      t2,t6,t2
+       or      t3,t7,t3
+       stq_u   t3,-1(a4)
+       stq_u   t2,0(DSTREG)
+       RET
+
+bcopy_overlap:
+       /*
+        * Basically equivalent to previous case, only backwards.
+        * Not quite as highly optimized
+        */
+       addq    SRCREG,SIZEREG,a3
+       addq    DSTREG,SIZEREG,a4
+
+       /* less than 8 bytes - don't worry about overlap */
+       cmpule  SIZEREG,8,t0
+       bne     t0,bcopy_ov_short
+
+       /* Possibly do a partial first word */
+       and     a4,7,t4
+       beq     t4,bcopy_ov_nostart2
+       subq    a3,t4,a3
+       subq    a4,t4,a4
+       ldq_u   t1,0(a3)
+       subq    SIZEREG,t4,SIZEREG
+       ldq_u   t2,7(a3)
+       ldq     t3,0(a4)
+       extql   t1,a3,t1
+       extqh   t2,a3,t2
+       or      t1,t2,t1
+       mskqh   t3,t4,t3
+       mskql   t1,t4,t1
+       or      t1,t3,t1
+       stq     t1,0(a4)
+
+bcopy_ov_nostart2:
+       bic     SIZEREG,7,t4
+       and     SIZEREG,7,SIZEREG
+       beq     t4,bcopy_ov_lp_end
+
+bcopy_ov_lp:
+       /* This could be more pipelined, but it doesn't seem worth it */
+       ldq_u   t0,-8(a3)
+       subq    a4,8,a4
+       ldq_u   t1,-1(a3)
+       subq    a3,8,a3
+       extql   t0,a3,t0
+       extqh   t1,a3,t1
+       subq    t4,8,t4
+       or      t0,t1,t0
+       stq     t0,0(a4)
+       bne     t4,bcopy_ov_lp
+
+bcopy_ov_lp_end:
+       beq     SIZEREG,bcopy_done
+
+       ldq_u   t0,0(SRCREG)
+       ldq_u   t1,7(SRCREG)
+       ldq_u   t2,0(DSTREG)
+       extql   t0,SRCREG,t0
+       extqh   t1,SRCREG,t1
+       or      t0,t1,t0
+       insql   t0,DSTREG,t0
+       mskql   t2,DSTREG,t2
+       or      t2,t0,t2
+       stq_u   t2,0(DSTREG)
+
+bcopy_done:
+       RET
+
+bcopy_ov_short:
+       ldq_u   t2,0(SRCREG)
+       br      zero,bcopy_da_finish
+
+       END(FUNCTION)
diff --git a/common/lib/libc/arch/alpha/string/bzero.S b/common/lib/libc/arch/alpha/string/bzero.S
new file mode 100644 (file)
index 0000000..a808b0d
--- /dev/null
@@ -0,0 +1,110 @@
+/*     $NetBSD: bzero.S,v 1.1 2005/12/20 19:28:49 christos Exp $       */
+
+/*
+ * Copyright (c) 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Trevor Blackwell
+ *
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ *
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ *
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+
+LEAF(bzero,2)
+       ble     a1,bzero_done
+       bic     a1,63,t3        /* t3 is # bytes to do 64 bytes at a time */
+
+       /* If nothing in first word, ignore it */
+       subq    zero,a0,t0
+       and     t0,7,t0         /* t0 = (0-size)%8 */
+       beq     t0,bzero_nostart1
+
+       cmpult  a1,t0,t1        /* if size > size%8 goto noshort */
+       beq     t1,bzero_noshort
+
+       /*
+        * The whole thing is less than a word.
+        * Mask off 1..7 bytes, and finish.
+        */
+       ldq_u   t2,0(a0)
+       lda     t0,-1(zero)     /* t0=-1 */
+       mskql   t0,a1,t0        /* Get ff in bytes (a0%8)..((a0+a1-1)%8) */
+       insql   t0,a0,t0
+       bic     t2,t0,t2        /* zero those bytes in word */
+       stq_u   t2,0(a0)
+       RET
+
+bzero_noshort:
+       /* Handle the first partial word */
+       ldq_u   t2,0(a0)
+       subq    a1,t0,a1
+       mskql   t2,a0,t2        /* zero bytes (a0%8)..7 in word */
+       stq_u   t2,0(a0)
+
+       addq    a0,t0,a0        /* round a0 up to next word */
+       bic     a1,63,t3        /* recalc t3 (# bytes to do 64 bytes at a
+                                  time) */
+
+bzero_nostart1:
+       /*
+        * Loop, zeroing 64 bytes at a time
+        */
+       beq     t3,bzero_lp_done
+bzero_lp:
+       stq     zero,0(a0)
+       stq     zero,8(a0)
+       stq     zero,16(a0)
+       stq     zero,24(a0)
+       subq    t3,64,t3
+       stq     zero,32(a0)
+       stq     zero,40(a0)
+       stq     zero,48(a0)
+       stq     zero,56(a0)
+       addq    a0,64,a0
+       bne     t3,bzero_lp
+
+bzero_lp_done:
+       /*
+        * Handle the last 0..7 words.
+        * We mask off the low bits, so we don't need an extra
+        * compare instruction for the loop (just a bne. heh-heh)
+        */
+       and     a1,0x38,t4
+       beq     t4,bzero_finish_lp_done
+bzero_finish_lp:
+       stq     zero,0(a0)
+       subq    t4,8,t4
+       addq    a0,8,a0
+       bne     t4,bzero_finish_lp
+
+       /* Do the last partial word */
+bzero_finish_lp_done:
+       and     a1,7,t5         /* 0..7 bytes left */
+       beq     t5,bzero_done   /* mskqh won't change t0 if t5==0, but I
+                                  don't want to touch, say, a new VM page */
+       ldq     t0,0(a0)
+       mskqh   t0,t5,t0
+       stq     t0,0(a0)
+bzero_done:
+       RET
+
+       END(bzero)
diff --git a/common/lib/libc/arch/alpha/string/ffs.S b/common/lib/libc/arch/alpha/string/ffs.S
new file mode 100644 (file)
index 0000000..788089a
--- /dev/null
@@ -0,0 +1,94 @@
+/* $NetBSD: ffs.S,v 1.1 2005/12/20 19:28:49 christos Exp $ */
+
+/*
+ * Copyright (c) 1995 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <machine/asm.h>
+
+LEAF(ffs, 1)
+       addl    a0, 0, t0
+       beq     t0, Lallzero
+
+       /*
+        * Initialize return value (v0), and set up t1 so that it
+        * contains the mask with only the lowest bit set.
+        */
+       subl    zero, t0, t1
+       ldil    v0, 1
+       and     t0, t1, t1
+
+       and     t1, 0xff, t2
+       bne     t2, Ldo8
+
+       /*
+        * If lower 16 bits empty, add 16 to result and use upper 16.
+        */
+       zapnot  t1, 0x03, t3
+       bne     t3, Ldo16
+       sra     t1, 16, t1
+       addl    v0, 16, v0
+
+Ldo16:
+       /*
+        * If lower 8 bits empty, add 8 to result and use upper 8.
+        */
+       and     t1, 0xff, t4
+       bne     t4, Ldo8
+       sra     t1, 8, t1
+       addl    v0, 8, v0
+
+Ldo8:
+       and     t1, 0x0f, t5            /* lower 4 of 8 empty? */
+       and     t1, 0x33, t6            /* lower 2 of each 4 empty? */
+       and     t1, 0x55, t7            /* lower 1 of each 2 empty? */
+
+       /* If lower 4 bits empty, add 4 to result. */
+       bne     t5, Ldo4
+       addl    v0, 4, v0
+
+Ldo4:  /* If lower 2 bits of each 4 empty, add 2 to result. */
+       bne     t6, Ldo2
+       addl    v0, 2, v0
+
+Ldo2:  /* If lower bit of each 2 empty, add 1 to result. */
+       bne     t7, Ldone
+       addl    v0, 1, v0
+
+Ldone:
+       RET
+
+Lallzero:
+       bis     zero, zero, v0
+       RET
+END(ffs)
diff --git a/common/lib/libc/arch/alpha/string/memcpy.S b/common/lib/libc/arch/alpha/string/memcpy.S
new file mode 100644 (file)
index 0000000..11245b4
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: memcpy.S,v 1.1 2005/12/20 19:28:49 christos Exp $      */
+
+#define MEMCOPY
+#include "bcopy.S"
diff --git a/common/lib/libc/arch/alpha/string/memmove.S b/common/lib/libc/arch/alpha/string/memmove.S
new file mode 100644 (file)
index 0000000..d9d5186
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: memmove.S,v 1.1 2005/12/20 19:28:49 christos Exp $     */
+
+#define MEMMOVE
+#include "bcopy.S"
diff --git a/common/lib/libc/arch/arm/atomic/Makefile.inc b/common/lib/libc/arch/arm/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..9f02337
--- /dev/null
@@ -0,0 +1,19 @@
+#      $NetBSD: Makefile.inc,v 1.8 2009/01/04 17:54:29 pooka Exp $
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "c" || ${LIB} == "pthread" \
+       || ${LIB} == "rump")
+
+SRCS+= atomic_add_32_cas.c atomic_add_32_nv_cas.c atomic_and_32_cas.c \
+       atomic_and_32_nv_cas.c atomic_dec_32_cas.c atomic_dec_32_nv_cas.c \
+       atomic_inc_32_cas.c atomic_inc_32_nv_cas.c atomic_or_32_cas.c \
+       atomic_or_32_nv_cas.c atomic_swap_32_cas.c membar_ops_nop.c
+
+.endif
+
+.if defined(LIB) && (${LIB} == "c" || ${LIB} == "pthread")
+
+SRCS+= atomic_init_testset.c
+SRCS+= atomic_cas_up.S
+CPPFLAGS+= -D__HAVE_ASM_ATOMIC_CAS_UP
+
+.endif
diff --git a/common/lib/libc/arch/arm/atomic/atomic_add_32.S b/common/lib/libc/arch/arm/atomic/atomic_add_32.S
new file mode 100644 (file)
index 0000000..e03472c
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: atomic_add_32.S,v 1.2 2008/08/16 07:12:39 matt Exp $   */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#ifdef _ARM_ARCH_6
+
+ENTRY_NP(_atomic_add_32)
+       mov     r3, r0                  /* need r0 for return value */
+1:     ldrex   r0, [r3]                /* load old value (to be returned) */
+       add     r2, r0, r1              /* calculate new value */
+       strex   ip, r2, [r3]            /* try to store */
+       cmp     ip, #0                  /*   succeed? */
+       bne     1b                      /*     no, try again */
+       RET                             /* return old value */
+       END(_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_32,_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_int,_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_long,_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_ptr,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_int,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_long,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_ptr,_atomic_add_32)
+
+ENTRY_NP(_atomic_add_32_nv)
+       mov     r3, r0                  /* need r0 for return value */
+1:     ldrex   r0, [r3]                /* load old value */
+       add     r0, r0, r1              /* calculate new value (return value) */
+       strex   r2, r0, [r3]            /* try to store */
+       cmp     r2, #0                  /*   succeed? */
+       bne     1b                      /*     no, try again? */
+       RET                             /* return new value */
+       END(_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_32_nv,_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_int_nv,_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_long_nv,_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_ptr_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_int_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_long_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_ptr_nv,_atomic_add_32_nv)
+
+#endif /* _ARM_ARCH_6 */
diff --git a/common/lib/libc/arch/arm/atomic/atomic_and_32.S b/common/lib/libc/arch/arm/atomic/atomic_and_32.S
new file mode 100644 (file)
index 0000000..d34bf0d
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: atomic_and_32.S,v 1.2 2008/08/16 07:12:39 matt Exp $   */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#ifdef _ARM_ARCH_6
+
+ENTRY_NP(_atomic_and_32)
+       mov     r3, r0                  /* need r0 for return value */
+1:     ldrex   r0, [r3]                /* load old value (to be returned) */
+       and     r2, r0, r1              /* calculate new value */
+       strex   ip, r2, [r3]            /* try to store */
+       cmp     ip, #0                  /*   succeed? */
+       bne     1b                      /*     no, try again */
+       RET                             /* return old value */
+       END(_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_32,_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_uint,_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_ulong,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_uint,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_ulong,_atomic_and_32)
+
+ENTRY_NP(_atomic_and_32_nv)
+       mov     r3, r0                  /* need r0 for return value */
+1:     ldrex   r0, [r3]                /* load old value */
+       and     r0, r0, r1              /* calculate new value (return value) */
+       strex   r2, r0, [r3]            /* try to store */
+       cmp     r2, #0                  /*   succeed? */
+       bne     1b                      /*     no, try again? */
+       RET                             /* return new value */
+       END(_atomic_and_32_nv)
+ATOMIC_OP_ALIAS(atomic_and_32_nv,_atomic_and_32_nv)
+ATOMIC_OP_ALIAS(atomic_and_uint_nv,_atomic_and_32_nv)
+ATOMIC_OP_ALIAS(atomic_and_ulong_nv,_atomic_and_32_nv)
+STRONG_ALIAS(_atomic_and_uint_nv,_atomic_and_32_nv)
+STRONG_ALIAS(_atomic_and_ulong_nv,_atomic_and_32_nv)
+
+#endif /* _ARM_ARCH_6 */
diff --git a/common/lib/libc/arch/arm/atomic/atomic_cas_32.S b/common/lib/libc/arch/arm/atomic/atomic_cas_32.S
new file mode 100644 (file)
index 0000000..a77cfba
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: atomic_cas_32.S,v 1.2 2008/08/16 07:12:39 matt Exp $   */
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#if defined(_ARM_ARCH_6)
+/*
+ * ARMv6 has load-exclusive/store-exclusive which works for both user
+ * and kernel.
+ */
+ENTRY_NP(_atomic_cas_32)
+       mov     r3, r0                  /* we need r0 for return value */
+1:
+       ldrex   r0, [r3]                /* load old value */
+       teq     r0, r1                  /*   compare? */
+       RETc(ne)                        /*     return if different */
+       strex   ip, r2, [r3]            /* store new value */
+       cmp     ip, #0                  /*   succeed? */
+       bne     1b                      /*     nope, try again. */
+       RET                             /*    yes, return. */
+       END(_atomic_cas_32)
+
+ATOMIC_OP_ALIAS(atomic_cas_32,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_uint,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_ulong,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_ptr,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_uint,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ptr,_atomic_cas_32)
+
+#endif /* _ARCH_ARM_6 */
diff --git a/common/lib/libc/arch/arm/atomic/atomic_cas_8.S b/common/lib/libc/arch/arm/atomic/atomic_cas_8.S
new file mode 100644 (file)
index 0000000..98ebf21
--- /dev/null
@@ -0,0 +1,63 @@
+/* $NetBSD: atomic_cas_8.S,v 1.1 2008/11/18 15:22:56 matt Exp $ */
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+RCSID("$NetBSD: atomic_cas_8.S,v 1.1 2008/11/18 15:22:56 matt Exp $")
+
+ENTRY(atomic_cas_8)
+       XPUSH   {r4,r5}                 /* we need some more registers */
+       and     r3, r0, #3              /* which byte do we replace? */
+#if __ARMEB__
+       eor     r3, r3, #3              /* bytes are reversed on BE */
+#endif
+       mov     r3, r3, lsl #3          /* multiply by 8 */
+       mov     r1, r1, lsl r3          /* mov old value to correct byte */
+       eor     r2, r1, r2, lsl r3      /* move new value to correct byte */
+/*     eor     r2, r2, r1 */           /* new value is now (old ^ new) */
+       mov     r5, #0xff               /* load mask */
+       mov     r5, r5, lsl r3          /* and move to correct byte */
+       mov     r3, r0                  /* move pointer */
+
+1:     ldrex   r4, [r3]                /* load 32bit value */
+       and     r0, r4, r5              /* clear other bytes */
+       teq     r0, r1                  /* equal old value? */
+       bne     2f                      /*   nope, bail. */
+       eor     r4, r4, r2              /* new == old ^ (old ^ new) */
+       strex   ip, r4, [r3]            /* attempt to store it */
+       cmp     ip, #0                  /*   succeed? */
+       bne     1b                      /* nope, try again. */
+
+2:     XPOP    {r4,r5}                 /* don't need these anymore */
+       and     r1, r3, #3
+#if __ARMEB__
+       eor     r1, r1, #3
+#endif
+       mov     r0, r0, lsr r1          /* shift it back to lsb byte */
+       RET
diff --git a/common/lib/libc/arch/arm/atomic/atomic_cas_up.S b/common/lib/libc/arch/arm/atomic/atomic_cas_up.S
new file mode 100644 (file)
index 0000000..9fe854e
--- /dev/null
@@ -0,0 +1,43 @@
+/*     $NetBSD: atomic_cas_up.S,v 1.2 2008/05/25 15:56:11 chs Exp $    */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Steve C. Woodford.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/ras.h>
+#include <machine/asm.h>
+
+ENTRY(_atomic_cas_up)
+       .hidden _C_LABEL(_atomic_cas_up)
+       mov     r3, r0
+RAS_START_ASM_HIDDEN(_atomic_cas)
+       ldr     r0, [r3]
+       cmp     r0, r1
+       streq   r2, [r3]
+RAS_END_ASM_HIDDEN(_atomic_cas)
+       RET
diff --git a/common/lib/libc/arch/arm/atomic/atomic_dec_32.S b/common/lib/libc/arch/arm/atomic/atomic_dec_32.S
new file mode 100644 (file)
index 0000000..68466d2
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: atomic_dec_32.S,v 1.2 2008/08/16 07:12:39 matt Exp $   */
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#ifdef _ARM_ARCH_6
+
+ENTRY_NP(_atomic_dec_32)
+       mov     r2, r0                  /* need r0 for return value */
+1:     ldrex   r0, [r2]                /* load old value (return value) */
+       sub     r1, r0, #1              /* calculate new value */
+       strex   r3, r1, [r2]            /* try to store */
+       cmp     r3, #0                  /*   succeed? */
+       bne     1b                      /*     no, try again? */
+       RET                             /* return new value */
+       END(_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_32,_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_uint,_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_ulong,_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_ptr,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_uint,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_ulong,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_ptr,_atomic_dec_32)
+
+ENTRY_NP(_atomic_dec_32_nv)
+       mov     r2, r0                  /* need r0 for return value */
+1:     ldrex   r0, [r2]                /* load old value */
+       sub     r0, r0, #1              /* calculate new value (return value) */
+       strex   r1, r0, [r2]            /* try to store */
+       cmp     r1, #0                  /*   succeed? */
+       bne     1b                      /*     no, try again? */
+       RET                             /* return new value */
+       END(_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_32_nv,_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_uint_nv,_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_ulong_nv,_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_ptr_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_uint_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_ulong_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_ptr_nv,_atomic_dec_32_nv)
+
+#endif /* _ARM_ARCH_6 */
diff --git a/common/lib/libc/arch/arm/atomic/atomic_inc_32.S b/common/lib/libc/arch/arm/atomic/atomic_inc_32.S
new file mode 100644 (file)
index 0000000..01aa130
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: atomic_inc_32.S,v 1.2 2008/08/16 07:12:39 matt Exp $   */
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#ifdef _ARM_ARCH_6
+
+ENTRY_NP(_atomic_inc_32)
+       mov     r2, r0                  /* need r0 for return value */
+1:     ldrex   r0, [r2]                /* load old value (return value) */
+       add     r1, r0, #1              /* calculate new value */
+       strex   r3, r1, [r2]            /* try to store */
+       cmp     r3, #0                  /*   succeed? */
+       bne     1b                      /*     no, try again? */
+       RET                             /* return new value */
+       END(_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_32,_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_uint,_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_ulong,_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_ptr,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_uint,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_ulong,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_ptr,_atomic_inc_32)
+
+ENTRY_NP(_atomic_inc_32_nv)
+       mov     r2, r0                  /* need r0 for return value */
+1:     ldrex   r0, [r2]                /* load old value */
+       add     r0, r0, #1              /* calculate new value (return value) */
+       strex   r1, r0, [r2]            /* try to store */
+       cmp     r1, #0                  /*   succeed? */
+       bne     1b                      /*     no, try again? */
+       RET                             /* return new value */
+       END(_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_32_nv,_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_uint_nv,_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_ulong_nv,_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_ptr_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_uint_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_ulong_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_ptr_nv,_atomic_inc_32_nv)
+
+#endif /* _ARCH_ARM_6 */
diff --git a/common/lib/libc/arch/arm/atomic/atomic_op_asm.h b/common/lib/libc/arch/arm/atomic/atomic_op_asm.h
new file mode 100644 (file)
index 0000000..40548fb
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: atomic_op_asm.h,v 1.2 2008/08/16 07:12:39 matt Exp $   */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the NetBSD
+ *     Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _ATOMIC_OP_ASM_H_
+#define        _ATOMIC_OP_ASM_H_
+
+#include <machine/asm.h>
+
+#if defined(_KERNEL)
+
+#define        ATOMIC_OP_ALIAS(a,s)    STRONG_ALIAS(a,s)
+
+#else /* _KERNEL */
+
+#define        ATOMIC_OP_ALIAS(a,s)    WEAK_ALIAS(a,s)
+
+#endif /* _KERNEL */
+
+#endif /* _ATOMIC_OP_ASM_H_ */
diff --git a/common/lib/libc/arch/arm/atomic/atomic_or_32.S b/common/lib/libc/arch/arm/atomic/atomic_or_32.S
new file mode 100644 (file)
index 0000000..380f6f5
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: atomic_or_32.S,v 1.2 2008/08/16 07:12:39 matt Exp $    */
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#ifdef _ARM_ARCH_6
+
+ENTRY_NP(_atomic_or_32)
+       mov     r3, r0                  /* need r0 for return value */
+1:     ldrex   r0, [r3]                /* load old value (to be returned) */
+       orr     r2, r0, r1              /* calculate new value */
+       strex   ip, r2, [r3]            /* try to store */
+       cmp     ip, #0                  /*   succeed? */
+       bne     1b                      /*     no, try again */
+       RET                             /* return old value */
+       END(_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_32,_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_uint,_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_ulong,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_uint,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_ulong,_atomic_or_32)
+
+ENTRY_NP(_atomic_or_32_nv)
+       mov     r3, r0                  /* need r0 for return value */
+1:     ldrex   r0, [r3]                /* load old value */
+       orr     r0, r0, r1              /* calculate new value (return value) */
+       strex   r2, r0, [r3]            /* try to store */
+       cmp     r2, #0                  /*   succeed? */
+       bne     1b                      /*     no, try again? */
+       RET                             /* return new value */
+       END(_atomic_or_32_nv)
+ATOMIC_OP_ALIAS(atomic_or_32_nv,_atomic_or_32_nv)
+ATOMIC_OP_ALIAS(atomic_or_uint_nv,_atomic_or_32_nv)
+ATOMIC_OP_ALIAS(atomic_or_ulong_nv,_atomic_or_32_nv)
+STRONG_ALIAS(_atomic_or_uint_nv,_atomic_or_32_nv)
+STRONG_ALIAS(_atomic_or_ulong_nv,_atomic_or_32_nv)
+
+#endif /* _ARM_ARCH_6 */
diff --git a/common/lib/libc/arch/arm/atomic/atomic_swap.S b/common/lib/libc/arch/arm/atomic/atomic_swap.S
new file mode 100644 (file)
index 0000000..42a7897
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: atomic_swap.S,v 1.2 2008/08/16 07:12:40 matt Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe and Matt Thomas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the NetBSD
+ *     Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+ENTRY_NP(_atomic_swap_32)
+       swp     r0, r1, [r0]
+       RET
+       END(_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_32,_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_uint,_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_ulong,_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_ptr,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_uint,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_ulong,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_ptr,_atomic_swap_32)
+
+ENTRY_NP(_atomic_swap_8)
+       swpb    r0, r1, [r0]
+       RET
+       END(_atomic_swap_8)
+ATOMIC_OP_ALIAS(atomic_swap_8,_atomic_swap_8)
+ATOMIC_OP_ALIAS(atomic_swap_char,_atomic_swap_8)
+ATOMIC_OP_ALIAS(atomic_swap_uchar,_atomic_swap_8)
+STRONG_ALIAS(_atomic_swap_char,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_uchar,_atomic_swap_32)
diff --git a/common/lib/libc/arch/arm/atomic/membar_ops.S b/common/lib/libc/arch/arm/atomic/membar_ops.S
new file mode 100644 (file)
index 0000000..c8af9f9
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: membar_ops.S,v 1.2 2008/08/16 07:12:40 matt Exp $      */
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#ifdef _ARM_ARCH_6
+
+ENTRY_NP(_membar_producer)
+       mcr     p15, 0, r0, c7, c10, 4   /* Data Synchronization Barrier */
+       RET
+       END(_membar_producer)
+ATOMIC_OP_ALIAS(membar_producer,_membar_producer)
+ATOMIC_OP_ALIAS(membar_write,_membar_producer)
+STRONG_ALIAS(_membar_write,_membar_producer)
+
+ENTRY_NP(_membar_sync)
+       mcr     p15, 0, r0, c7, c10, 5  /* Data Memory Barrier */
+       RET
+       END(_membar_sync)
+ATOMIC_OP_ALIAS(membar_sync,_membar_sync)
+ATOMIC_OP_ALIAS(membar_enter,_membar_sync)
+ATOMIC_OP_ALIAS(membar_exit,_membar_sync)
+ATOMIC_OP_ALIAS(membar_consumer,_membar_sync)
+ATOMIC_OP_ALIAS(membar_read,_membar_sync)
+STRONG_ALIAS(_membar_enter,_membar_sync)
+STRONG_ALIAS(_membar_exit,_membar_sync)
+STRONG_ALIAS(_membar_consumer,_membar_sync)
+STRONG_ALIAS(_membar_read,_membar_sync)
+
+#endif /* _ARM_ARCH_6 */
diff --git a/common/lib/libc/arch/arm/gen/byte_swap_2.S b/common/lib/libc/arch/arm/gen/byte_swap_2.S
new file mode 100644 (file)
index 0000000..843bd92
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: byte_swap_2.S,v 1.4 2008/04/28 20:22:52 martin Exp $   */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Charles M. Hannum.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+_ENTRY(_C_LABEL(bswap16))
+#else
+_ENTRY(_C_LABEL(__bswap16))
+#endif
+#if BYTE_ORDER == LITTLE_ENDIAN
+_ENTRY(_C_LABEL(ntohs))
+_ENTRY(_C_LABEL(htons))
+#endif
+_PROF_PROLOGUE
+       and             r1, r0, #0xff
+       mov             r0, r0, lsr #8
+       orr             r0, r0, r1, lsl #8
+       RET
diff --git a/common/lib/libc/arch/arm/gen/byte_swap_4.S b/common/lib/libc/arch/arm/gen/byte_swap_4.S
new file mode 100644 (file)
index 0000000..265b898
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: byte_swap_4.S,v 1.4 2008/04/28 20:22:52 martin Exp $   */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Neil A. Carson
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+_ENTRY(_C_LABEL(bswap32))
+#else
+_ENTRY(_C_LABEL(__bswap32))
+#endif
+#if BYTE_ORDER == LITTLE_ENDIAN
+_ENTRY(_C_LABEL(ntohl))
+_ENTRY(_C_LABEL(htonl))
+#endif
+_PROF_PROLOGUE
+       eor             r1, r0, r0, ror #16
+       bic             r1, r1, #0x00FF0000
+       mov             r0, r0, ror #8
+       eor             r0, r0, r1, lsr #8
+       RET
diff --git a/common/lib/libc/arch/arm/gen/divsi3.S b/common/lib/libc/arch/arm/gen/divsi3.S
new file mode 100644 (file)
index 0000000..75a927b
--- /dev/null
@@ -0,0 +1,386 @@
+/*     $NetBSD: divsi3.S,v 1.1 2005/12/20 19:28:49 christos Exp $      */
+
+/*
+ * 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 <machine/asm.h>
+
+/* 
+ * stack is aligned as there's a possibility of branching to .L_overflow
+ * which makes a C call
+ */
+
+ENTRY(__umodsi3)
+       stmfd   sp!, {lr}
+       sub     sp, sp, #4      /* align stack */
+       bl      .L_udivide
+       add     sp, sp, #4      /* unalign stack */
+       mov     r0, r1
+       ldmfd   sp!, {pc}
+
+ENTRY(__modsi3)
+       stmfd   sp!, {lr}
+       sub     sp, sp, #4      /* align stack */
+       bl      .L_divide
+       add     sp, sp, #4      /* unalign stack */
+       mov     r0, r1
+       ldmfd   sp!, {pc}
+
+.L_overflow:
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+       mov     r0, #8                  /* SIGFPE */
+       bl      PIC_SYM(_C_LABEL(raise), PLT)   /* raise it */
+       mov     r0, #0
+#else
+       /* XXX should cause a fatal error */
+       mvn     r0, #0
+#endif
+       RET
+
+ENTRY(__udivsi3)
+.L_udivide:                            /* r0 = r0 / r1; r1 = r0 % r1 */
+       eor     r0, r1, r0 
+       eor     r1, r0, r1 
+       eor     r0, r1, r0 
+                                       /* r0 = r1 / r0; r1 = r1 % r0 */
+       cmp     r0, #1
+       bcc     .L_overflow
+       beq     .L_divide_l0
+       mov     ip, #0
+       movs    r1, r1
+       bpl     .L_divide_l1
+       orr     ip, ip, #0x20000000     /* ip bit 0x20000000 = -ve r1 */
+       movs    r1, r1, lsr #1
+       orrcs   ip, ip, #0x10000000     /* ip bit 0x10000000 = bit 0 of r1 */
+       b       .L_divide_l1
+
+.L_divide_l0:                          /* r0 == 1 */
+       mov     r0, r1
+       mov     r1, #0
+       RET
+
+ENTRY(__divsi3)
+.L_divide:                             /* r0 = r0 / r1; r1 = r0 % r1 */
+       eor     r0, r1, r0 
+       eor     r1, r0, r1 
+       eor     r0, r1, r0 
+                                       /* r0 = r1 / r0; r1 = r1 % r0 */
+       cmp     r0, #1
+       bcc     .L_overflow
+       beq     .L_divide_l0
+       ands    ip, r0, #0x80000000
+       rsbmi   r0, r0, #0
+       ands    r2, r1, #0x80000000
+       eor     ip, ip, r2
+       rsbmi   r1, r1, #0
+       orr     ip, r2, ip, lsr #1      /* ip bit 0x40000000 = -ve division */
+                                       /* ip bit 0x80000000 = -ve remainder */
+
+.L_divide_l1:
+       mov     r2, #1
+       mov     r3, #0
+
+       /*
+        * If the highest bit of the dividend is set, we have to be
+        * careful when shifting the divisor. Test this. 
+        */
+       movs    r1,r1
+       bpl     .L_old_code
+
+       /*
+        * At this point, the highest bit of r1 is known to be set.
+        * We abuse this below in the tst instructions.
+        */
+       tst     r1, r0 /*, lsl #0 */
+       bmi     .L_divide_b1
+       tst     r1, r0, lsl #1
+       bmi     .L_divide_b2
+       tst     r1, r0, lsl #2
+       bmi     .L_divide_b3
+       tst     r1, r0, lsl #3
+       bmi     .L_divide_b4
+       tst     r1, r0, lsl #4
+       bmi     .L_divide_b5
+       tst     r1, r0, lsl #5
+       bmi     .L_divide_b6
+       tst     r1, r0, lsl #6
+       bmi     .L_divide_b7
+       tst     r1, r0, lsl #7
+       bmi     .L_divide_b8
+       tst     r1, r0, lsl #8
+       bmi     .L_divide_b9
+       tst     r1, r0, lsl #9
+       bmi     .L_divide_b10
+       tst     r1, r0, lsl #10
+       bmi     .L_divide_b11
+       tst     r1, r0, lsl #11
+       bmi     .L_divide_b12
+       tst     r1, r0, lsl #12
+       bmi     .L_divide_b13
+       tst     r1, r0, lsl #13
+       bmi     .L_divide_b14
+       tst     r1, r0, lsl #14
+       bmi     .L_divide_b15
+       tst     r1, r0, lsl #15
+       bmi     .L_divide_b16
+       tst     r1, r0, lsl #16
+       bmi     .L_divide_b17
+       tst     r1, r0, lsl #17
+       bmi     .L_divide_b18
+       tst     r1, r0, lsl #18
+       bmi     .L_divide_b19
+       tst     r1, r0, lsl #19
+       bmi     .L_divide_b20
+       tst     r1, r0, lsl #20
+       bmi     .L_divide_b21
+       tst     r1, r0, lsl #21
+       bmi     .L_divide_b22
+       tst     r1, r0, lsl #22
+       bmi     .L_divide_b23
+       tst     r1, r0, lsl #23
+       bmi     .L_divide_b24
+       tst     r1, r0, lsl #24
+       bmi     .L_divide_b25
+       tst     r1, r0, lsl #25
+       bmi     .L_divide_b26
+       tst     r1, r0, lsl #26
+       bmi     .L_divide_b27
+       tst     r1, r0, lsl #27
+       bmi     .L_divide_b28
+       tst     r1, r0, lsl #28
+       bmi     .L_divide_b29
+       tst     r1, r0, lsl #29
+       bmi     .L_divide_b30
+       tst     r1, r0, lsl #30
+       bmi     .L_divide_b31
+/*
+ * instead of:
+ *     tst     r1, r0, lsl #31
+ *     bmi     .L_divide_b32
+ */
+       b       .L_divide_b32
+
+.L_old_code:
+       cmp     r1, r0
+       bcc     .L_divide_b0
+       cmp     r1, r0, lsl #1
+       bcc     .L_divide_b1
+       cmp     r1, r0, lsl #2
+       bcc     .L_divide_b2
+       cmp     r1, r0, lsl #3
+       bcc     .L_divide_b3
+       cmp     r1, r0, lsl #4
+       bcc     .L_divide_b4
+       cmp     r1, r0, lsl #5
+       bcc     .L_divide_b5
+       cmp     r1, r0, lsl #6
+       bcc     .L_divide_b6
+       cmp     r1, r0, lsl #7
+       bcc     .L_divide_b7
+       cmp     r1, r0, lsl #8
+       bcc     .L_divide_b8
+       cmp     r1, r0, lsl #9
+       bcc     .L_divide_b9
+       cmp     r1, r0, lsl #10
+       bcc     .L_divide_b10
+       cmp     r1, r0, lsl #11
+       bcc     .L_divide_b11
+       cmp     r1, r0, lsl #12
+       bcc     .L_divide_b12
+       cmp     r1, r0, lsl #13
+       bcc     .L_divide_b13
+       cmp     r1, r0, lsl #14
+       bcc     .L_divide_b14
+       cmp     r1, r0, lsl #15
+       bcc     .L_divide_b15
+       cmp     r1, r0, lsl #16
+       bcc     .L_divide_b16
+       cmp     r1, r0, lsl #17
+       bcc     .L_divide_b17
+       cmp     r1, r0, lsl #18
+       bcc     .L_divide_b18
+       cmp     r1, r0, lsl #19
+       bcc     .L_divide_b19
+       cmp     r1, r0, lsl #20
+       bcc     .L_divide_b20
+       cmp     r1, r0, lsl #21
+       bcc     .L_divide_b21
+       cmp     r1, r0, lsl #22
+       bcc     .L_divide_b22
+       cmp     r1, r0, lsl #23
+       bcc     .L_divide_b23
+       cmp     r1, r0, lsl #24
+       bcc     .L_divide_b24
+       cmp     r1, r0, lsl #25
+       bcc     .L_divide_b25
+       cmp     r1, r0, lsl #26
+       bcc     .L_divide_b26
+       cmp     r1, r0, lsl #27
+       bcc     .L_divide_b27
+       cmp     r1, r0, lsl #28
+       bcc     .L_divide_b28
+       cmp     r1, r0, lsl #29
+       bcc     .L_divide_b29
+       cmp     r1, r0, lsl #30
+       bcc     .L_divide_b30
+.L_divide_b32:
+       cmp     r1, r0, lsl #31
+       subhs   r1, r1,r0, lsl #31
+       addhs   r3, r3,r2, lsl #31
+.L_divide_b31:
+       cmp     r1, r0, lsl #30
+       subhs   r1, r1,r0, lsl #30
+       addhs   r3, r3,r2, lsl #30
+.L_divide_b30:
+       cmp     r1, r0, lsl #29
+       subhs   r1, r1,r0, lsl #29
+       addhs   r3, r3,r2, lsl #29
+.L_divide_b29:
+       cmp     r1, r0, lsl #28
+       subhs   r1, r1,r0, lsl #28
+       addhs   r3, r3,r2, lsl #28
+.L_divide_b28:
+       cmp     r1, r0, lsl #27
+       subhs   r1, r1,r0, lsl #27
+       addhs   r3, r3,r2, lsl #27
+.L_divide_b27:
+       cmp     r1, r0, lsl #26
+       subhs   r1, r1,r0, lsl #26
+       addhs   r3, r3,r2, lsl #26
+.L_divide_b26:
+       cmp     r1, r0, lsl #25
+       subhs   r1, r1,r0, lsl #25
+       addhs   r3, r3,r2, lsl #25
+.L_divide_b25:
+       cmp     r1, r0, lsl #24
+       subhs   r1, r1,r0, lsl #24
+       addhs   r3, r3,r2, lsl #24
+.L_divide_b24:
+       cmp     r1, r0, lsl #23
+       subhs   r1, r1,r0, lsl #23
+       addhs   r3, r3,r2, lsl #23
+.L_divide_b23:
+       cmp     r1, r0, lsl #22
+       subhs   r1, r1,r0, lsl #22
+       addhs   r3, r3,r2, lsl #22
+.L_divide_b22:
+       cmp     r1, r0, lsl #21
+       subhs   r1, r1,r0, lsl #21
+       addhs   r3, r3,r2, lsl #21
+.L_divide_b21:
+       cmp     r1, r0, lsl #20
+       subhs   r1, r1,r0, lsl #20
+       addhs   r3, r3,r2, lsl #20
+.L_divide_b20:
+       cmp     r1, r0, lsl #19
+       subhs   r1, r1,r0, lsl #19
+       addhs   r3, r3,r2, lsl #19
+.L_divide_b19:
+       cmp     r1, r0, lsl #18
+       subhs   r1, r1,r0, lsl #18
+       addhs   r3, r3,r2, lsl #18
+.L_divide_b18:
+       cmp     r1, r0, lsl #17
+       subhs   r1, r1,r0, lsl #17
+       addhs   r3, r3,r2, lsl #17
+.L_divide_b17:
+       cmp     r1, r0, lsl #16
+       subhs   r1, r1,r0, lsl #16
+       addhs   r3, r3,r2, lsl #16
+.L_divide_b16:
+       cmp     r1, r0, lsl #15
+       subhs   r1, r1,r0, lsl #15
+       addhs   r3, r3,r2, lsl #15
+.L_divide_b15:
+       cmp     r1, r0, lsl #14
+       subhs   r1, r1,r0, lsl #14
+       addhs   r3, r3,r2, lsl #14
+.L_divide_b14:
+       cmp     r1, r0, lsl #13
+       subhs   r1, r1,r0, lsl #13
+       addhs   r3, r3,r2, lsl #13
+.L_divide_b13:
+       cmp     r1, r0, lsl #12
+       subhs   r1, r1,r0, lsl #12
+       addhs   r3, r3,r2, lsl #12
+.L_divide_b12:
+       cmp     r1, r0, lsl #11
+       subhs   r1, r1,r0, lsl #11
+       addhs   r3, r3,r2, lsl #11
+.L_divide_b11:
+       cmp     r1, r0, lsl #10
+       subhs   r1, r1,r0, lsl #10
+       addhs   r3, r3,r2, lsl #10
+.L_divide_b10:
+       cmp     r1, r0, lsl #9
+       subhs   r1, r1,r0, lsl #9
+       addhs   r3, r3,r2, lsl #9
+.L_divide_b9:
+       cmp     r1, r0, lsl #8
+       subhs   r1, r1,r0, lsl #8
+       addhs   r3, r3,r2, lsl #8
+.L_divide_b8:
+       cmp     r1, r0, lsl #7
+       subhs   r1, r1,r0, lsl #7
+       addhs   r3, r3,r2, lsl #7
+.L_divide_b7:
+       cmp     r1, r0, lsl #6
+       subhs   r1, r1,r0, lsl #6
+       addhs   r3, r3,r2, lsl #6
+.L_divide_b6:
+       cmp     r1, r0, lsl #5
+       subhs   r1, r1,r0, lsl #5
+       addhs   r3, r3,r2, lsl #5
+.L_divide_b5:
+       cmp     r1, r0, lsl #4
+       subhs   r1, r1,r0, lsl #4
+       addhs   r3, r3,r2, lsl #4
+.L_divide_b4:
+       cmp     r1, r0, lsl #3
+       subhs   r1, r1,r0, lsl #3
+       addhs   r3, r3,r2, lsl #3
+.L_divide_b3:
+       cmp     r1, r0, lsl #2
+       subhs   r1, r1,r0, lsl #2
+       addhs   r3, r3,r2, lsl #2
+.L_divide_b2:
+       cmp     r1, r0, lsl #1
+       subhs   r1, r1,r0, lsl #1
+       addhs   r3, r3,r2, lsl #1
+.L_divide_b1:
+       cmp     r1, r0
+       subhs   r1, r1, r0
+       addhs   r3, r3, r2
+.L_divide_b0:
+
+       tst     ip, #0x20000000
+       bne     .L_udivide_l1
+       mov     r0, r3
+       cmp     ip, #0
+       rsbmi   r1, r1, #0
+       movs    ip, ip, lsl #1
+       bicmi   r0, r0, #0x80000000     /* Fix incase we divided 0x80000000 */
+       rsbmi   r0, r0, #0
+       RET
+
+.L_udivide_l1:
+       tst     ip, #0x10000000
+       mov     r1, r1, lsl #1
+       orrne   r1, r1, #1
+       mov     r3, r3, lsl #1
+       cmp     r1, r0
+       subhs   r1, r1, r0
+       addhs   r3, r3, r2
+       mov     r0, r3
+       RET
diff --git a/common/lib/libc/arch/arm/string/ffs.S b/common/lib/libc/arch/arm/string/ffs.S
new file mode 100644 (file)
index 0000000..a1f108e
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: ffs.S,v 1.1 2005/12/20 19:28:49 christos Exp $ */
+/*
+ * Copyright (c) 2001 Christopher Gilbert
+ * 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.
+ * 3. The name of the company nor the name of the author may be used to
+ *    endorse or promote products derived from this software without specific
+ *    prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 <machine/asm.h>
+
+RCSID("$NetBSD: ffs.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+
+/*
+ * ffs - find first set bit, this algorithm isolates the first set
+ * bit, then multiplies the number by 0x0450fbaf which leaves the top
+ * 6 bits as an index into the table.  This algorithm should be a win
+ * over the checking each bit in turn as per the C compiled version.
+ *
+ * On ARMv5 we use CLZ (count leading Zero's) and then subtract the result
+ * from 32.
+ *
+ * This is the ffs algorithm devised by d.seal and posted to comp.sys.arm on
+ * 16 Feb 1994.
+ */
+
+ENTRY(ffs)
+#ifdef _ARM_ARCH_5
+       /* (X & -X) gives LSB or zero.  */
+       rsb     r1, r0, #0
+       and     r0, r0, r1
+       clz     r0, r0
+       rsb     r0, r0, #32
+       RET
+#else
+       /* Standard trick to isolate bottom bit in r0 or 0 if r0 = 0 on entry */
+       rsb     r1, r0, #0
+       ands    r0, r0, r1
+       /*
+        * now r0 has at most one set bit, call this X
+        * if X = 0, all further instructions are skipped
+        */
+       adrne   r2, .L_ffs_table
+       orrne   r0, r0, r0, lsl #4  /* r0 = X * 0x11 */ 
+       orrne   r0, r0, r0, lsl #6  /* r0 = X * 0x451 */
+       rsbne   r0, r0, r0, lsl #16 /* r0 = X * 0x0450fbaf */
+              
+       /* now lookup in table indexed on top 6 bits of r0 */
+       ldrneb  r0, [ r2, r0, lsr #26 ]
+
+        RET
+.text;
+.type .L_ffs_table, _ASM_TYPE_OBJECT;
+.L_ffs_table:
+/*               0   1   2   3   4   5   6   7           */
+       .byte    0,  1,  2, 13,  3,  7,  0, 14  /*  0- 7 */
+       .byte    4,  0,  8,  0,  0,  0,  0, 15  /*  8-15 */
+       .byte   11,  5,  0,  0,  9,  0,  0, 26  /* 16-23 */
+       .byte    0,  0,  0,  0,  0, 22, 28, 16  /* 24-31 */
+       .byte   32, 12,  6,  0,  0,  0,  0,  0  /* 32-39 */
+       .byte   10,  0,  0, 25,  0,  0, 21, 27  /* 40-47 */
+       .byte   31,  0,  0,  0,  0, 24,  0, 20  /* 48-55 */
+       .byte   30,  0, 23, 19, 29, 18, 17,  0  /* 56-63 */
+#endif
diff --git a/common/lib/libc/arch/arm/string/memcmp.S b/common/lib/libc/arch/arm/string/memcmp.S
new file mode 100644 (file)
index 0000000..eb2e0a8
--- /dev/null
@@ -0,0 +1,180 @@
+/*      $NetBSD: memcmp.S,v 1.1 2005/12/20 19:28:49 christos Exp $ */
+
+/*
+ * Copyright 2003 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Steve C. Woodford for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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.
+ */
+/*
+ * Copyright (c) 2002 ARM Ltd
+ * 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.
+ * 3. The name of the company may not be used to endorse or promote
+ *    products derived from this software without specific prior written
+ *    permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY ARM LTD ``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 ARM LTD 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 <machine/asm.h>
+
+RCSID("$NetBSD: memcmp.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+
+ENTRY(memcmp)
+       mov     ip, r0
+#if defined(_KERNEL) && !defined(_STANDALONE)
+       cmp     r2, #0x06
+       beq     .Lmemcmp_6bytes
+#endif
+       mov     r0, #0x00
+
+       /* Are both addresses aligned the same way? */
+       cmp     r2, #0x00
+       eornes  r3, ip, r1
+       RETc(eq)                        /* len == 0, or same addresses! */
+       tst     r3, #0x03
+       subne   r2, r2, #0x01
+       bne     .Lmemcmp_bytewise2      /* Badly aligned. Do it the slow way */
+
+       /* Word-align the addresses, if necessary */
+       sub     r3, r1, #0x05
+       ands    r3, r3, #0x03
+       add     r3, r3, r3, lsl #1
+       addne   pc, pc, r3, lsl #3
+       nop
+
+       /* Compare up to 3 bytes */
+       ldrb    r0, [ip], #0x01
+       ldrb    r3, [r1], #0x01
+       subs    r0, r0, r3
+       RETc(ne)
+       subs    r2, r2, #0x01
+       RETc(eq)
+
+       /* Compare up to 2 bytes */
+       ldrb    r0, [ip], #0x01
+       ldrb    r3, [r1], #0x01
+       subs    r0, r0, r3
+       RETc(ne)
+       subs    r2, r2, #0x01
+       RETc(eq)
+
+       /* Compare 1 byte */
+       ldrb    r0, [ip], #0x01
+       ldrb    r3, [r1], #0x01
+       subs    r0, r0, r3
+       RETc(ne)
+       subs    r2, r2, #0x01
+       RETc(eq)
+
+       /* Compare 4 bytes at a time, if possible */
+       subs    r2, r2, #0x04
+       bcc     .Lmemcmp_bytewise
+.Lmemcmp_word_aligned:
+       ldr     r0, [ip], #0x04
+       ldr     r3, [r1], #0x04
+       subs    r2, r2, #0x04
+       cmpcs   r0, r3
+       beq     .Lmemcmp_word_aligned
+       sub     r0, r0, r3
+
+       /* Correct for extra subtraction, and check if done */
+       adds    r2, r2, #0x04
+       cmpeq   r0, #0x00               /* If done, did all bytes match? */
+       RETc(eq)                        /* Yup. Just return */
+
+       /* Re-do the final word byte-wise */
+       sub     ip, ip, #0x04
+       sub     r1, r1, #0x04
+
+.Lmemcmp_bytewise:
+       add     r2, r2, #0x03
+.Lmemcmp_bytewise2:
+       ldrb    r0, [ip], #0x01
+       ldrb    r3, [r1], #0x01
+       subs    r2, r2, #0x01
+       cmpcs   r0, r3
+       beq     .Lmemcmp_bytewise2
+       sub     r0, r0, r3
+       RET
+
+#if defined(_KERNEL) && !defined(_STANDALONE)
+       /*
+        * 6 byte compares are very common, thanks to the network stack.
+        * This code is hand-scheduled to reduce the number of stalls for
+        * load results. Everything else being equal, this will be ~32%
+        * faster than a byte-wise memcmp.
+        */
+       .align  5
+.Lmemcmp_6bytes:
+       ldrb    r3, [r1, #0x00]         /* r3 = b2#0 */
+       ldrb    r0, [ip, #0x00]         /* r0 = b1#0 */
+       ldrb    r2, [r1, #0x01]         /* r2 = b2#1 */
+       subs    r0, r0, r3              /* r0 = b1#0 - b2#0 */
+       ldreqb  r3, [ip, #0x01]         /* r3 = b1#1 */
+       RETc(ne)                        /* Return if mismatch on #0 */
+       subs    r0, r3, r2              /* r0 = b1#1 - b2#1 */
+       ldreqb  r3, [r1, #0x02]         /* r3 = b2#2 */
+       ldreqb  r0, [ip, #0x02]         /* r0 = b1#2 */
+       RETc(ne)                        /* Return if mismatch on #1 */
+       ldrb    r2, [r1, #0x03]         /* r2 = b2#3 */
+       subs    r0, r0, r3              /* r0 = b1#2 - b2#2 */
+       ldreqb  r3, [ip, #0x03]         /* r3 = b1#3 */
+       RETc(ne)                        /* Return if mismatch on #2 */
+       subs    r0, r3, r2              /* r0 = b1#3 - b2#3 */
+       ldreqb  r3, [r1, #0x04]         /* r3 = b2#4 */
+       ldreqb  r0, [ip, #0x04]         /* r0 = b1#4 */
+       RETc(ne)                        /* Return if mismatch on #3 */
+       ldrb    r2, [r1, #0x05]         /* r2 = b2#5 */
+       subs    r0, r0, r3              /* r0 = b1#4 - b2#4 */
+       ldreqb  r3, [ip, #0x05]         /* r3 = b1#5 */
+       RETc(ne)                        /* Return if mismatch on #4 */
+       sub     r0, r3, r2              /* r0 = b1#5 - b2#5 */
+       RET
+#endif
diff --git a/common/lib/libc/arch/arm/string/memcpy.S b/common/lib/libc/arch/arm/string/memcpy.S
new file mode 100644 (file)
index 0000000..c2c65a0
--- /dev/null
@@ -0,0 +1,7 @@
+/*     $NetBSD: memcpy.S,v 1.1 2005/12/20 19:28:49 christos Exp $      */
+
+#if !defined(__XSCALE__) || defined(_STANDALONE)
+#include "memcpy_arm.S"
+#else
+#include "memcpy_xscale.S"
+#endif
diff --git a/common/lib/libc/arch/arm/string/memcpy_arm.S b/common/lib/libc/arch/arm/string/memcpy_arm.S
new file mode 100644 (file)
index 0000000..81c1a55
--- /dev/null
@@ -0,0 +1,332 @@
+/*     $NetBSD: memcpy_arm.S,v 1.2 2008/04/28 20:22:52 martin Exp $    */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Neil A. Carson and Mark Brinicombe
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+/*
+ * This is one fun bit of code ...
+ * Some easy listening music is suggested while trying to understand this
+ * code e.g. Iron Maiden
+ *
+ * For anyone attempting to understand it :
+ *
+ * The core code is implemented here with simple stubs for memcpy().
+ *
+ * All local labels are prefixed with Lmemcpy_
+ * Following the prefix a label starting f is used in the forward copy code
+ * while a label using b is used in the backwards copy code
+ * The source and destination addresses determine whether a forward or
+ * backward copy is performed.
+ * Separate bits of code are used to deal with the following situations
+ * for both the forward and backwards copy.
+ * unaligned source address
+ * unaligned destination address
+ * Separate copy routines are used to produce an optimised result for each
+ * of these cases.
+ * The copy code will use LDM/STM instructions to copy up to 32 bytes at
+ * a time where possible.
+ *
+ * Note: r12 (aka ip) can be trashed during the function along with
+ * r0-r3 although r0-r2 have defined uses i.e. src, dest, len through out.
+ * Additional registers are preserved prior to use i.e. r4, r5 & lr
+ *
+ * Apologies for the state of the comments ;-)
+ */
+/* LINTSTUB: Func: void *memcpy(void *dst, const void *src, size_t len) */
+ENTRY(memcpy)
+       /* save leaf functions having to store this away */
+       stmdb   sp!, {r0, lr}           /* memcpy() returns dest addr */
+
+       subs    r2, r2, #4
+       blt     .Lmemcpy_l4             /* less than 4 bytes */
+       ands    r12, r0, #3
+       bne     .Lmemcpy_destul         /* oh unaligned destination addr */
+       ands    r12, r1, #3
+       bne     .Lmemcpy_srcul          /* oh unaligned source addr */
+
+.Lmemcpy_t8:
+       /* We have aligned source and destination */
+       subs    r2, r2, #8
+       blt     .Lmemcpy_l12            /* less than 12 bytes (4 from above) */
+       subs    r2, r2, #0x14
+       blt     .Lmemcpy_l32            /* less than 32 bytes (12 from above) */
+       stmdb   sp!, {r4}               /* borrow r4 */
+
+       /* blat 32 bytes at a time */
+       /* XXX for really big copies perhaps we should use more registers */
+.Lmemcpy_loop32:
+       ldmia   r1!, {r3, r4, r12, lr}
+       stmia   r0!, {r3, r4, r12, lr}
+       ldmia   r1!, {r3, r4, r12, lr}
+       stmia   r0!, {r3, r4, r12, lr}
+       subs    r2, r2, #0x20
+       bge     .Lmemcpy_loop32
+
+       cmn     r2, #0x10
+       ldmgeia r1!, {r3, r4, r12, lr}  /* blat a remaining 16 bytes */
+       stmgeia r0!, {r3, r4, r12, lr}
+       subge   r2, r2, #0x10
+       ldmia   sp!, {r4}               /* return r4 */
+
+.Lmemcpy_l32:
+       adds    r2, r2, #0x14
+
+       /* blat 12 bytes at a time */
+.Lmemcpy_loop12:
+       ldmgeia r1!, {r3, r12, lr}
+       stmgeia r0!, {r3, r12, lr}
+       subges  r2, r2, #0x0c
+       bge     .Lmemcpy_loop12
+
+.Lmemcpy_l12:
+       adds    r2, r2, #8
+       blt     .Lmemcpy_l4
+
+       subs    r2, r2, #4
+       ldrlt   r3, [r1], #4
+       strlt   r3, [r0], #4
+       ldmgeia r1!, {r3, r12}
+       stmgeia r0!, {r3, r12}
+       subge   r2, r2, #4
+
+.Lmemcpy_l4:
+       /* less than 4 bytes to go */
+       adds    r2, r2, #4
+#ifdef __APCS_26_
+       ldmeqia sp!, {r0, pc}^          /* done */
+#else
+       ldmeqia sp!, {r0, pc}           /* done */
+#endif
+       /* copy the crud byte at a time */
+       cmp     r2, #2
+       ldrb    r3, [r1], #1
+       strb    r3, [r0], #1
+       ldrgeb  r3, [r1], #1
+       strgeb  r3, [r0], #1
+       ldrgtb  r3, [r1], #1
+       strgtb  r3, [r0], #1
+       ldmia   sp!, {r0, pc}
+
+       /* erg - unaligned destination */
+.Lmemcpy_destul:
+       rsb     r12, r12, #4
+       cmp     r12, #2
+
+       /* align destination with byte copies */
+       ldrb    r3, [r1], #1
+       strb    r3, [r0], #1
+       ldrgeb  r3, [r1], #1
+       strgeb  r3, [r0], #1
+       ldrgtb  r3, [r1], #1
+       strgtb  r3, [r0], #1
+       subs    r2, r2, r12
+       blt     .Lmemcpy_l4             /* less the 4 bytes */
+
+       ands    r12, r1, #3
+       beq     .Lmemcpy_t8             /* we have an aligned source */
+
+       /* erg - unaligned source */
+       /* This is where it gets nasty ... */
+.Lmemcpy_srcul:
+       bic     r1, r1, #3
+       ldr     lr, [r1], #4
+       cmp     r12, #2
+       bgt     .Lmemcpy_srcul3
+       beq     .Lmemcpy_srcul2
+       cmp     r2, #0x0c
+       blt     .Lmemcpy_srcul1loop4
+       sub     r2, r2, #0x0c
+       stmdb   sp!, {r4, r5}
+
+.Lmemcpy_srcul1loop16:
+#ifdef __ARMEB__
+       mov     r3, lr, lsl #8
+#else
+       mov     r3, lr, lsr #8
+#endif
+       ldmia   r1!, {r4, r5, r12, lr}
+#ifdef __ARMEB__
+       orr     r3, r3, r4, lsr #24
+       mov     r4, r4, lsl #8
+       orr     r4, r4, r5, lsr #24
+       mov     r5, r5, lsl #8
+       orr     r5, r5, r12, lsr #24
+       mov     r12, r12, lsl #8
+       orr     r12, r12, lr, lsr #24
+#else
+       orr     r3, r3, r4, lsl #24
+       mov     r4, r4, lsr #8
+       orr     r4, r4, r5, lsl #24
+       mov     r5, r5, lsr #8
+       orr     r5, r5, r12, lsl #24
+       mov     r12, r12, lsr #8
+       orr     r12, r12, lr, lsl #24
+#endif
+       stmia   r0!, {r3-r5, r12}
+       subs    r2, r2, #0x10
+       bge     .Lmemcpy_srcul1loop16
+       ldmia   sp!, {r4, r5}
+       adds    r2, r2, #0x0c
+       blt     .Lmemcpy_srcul1l4
+
+.Lmemcpy_srcul1loop4:
+#ifdef __ARMEB__
+       mov     r12, lr, lsl #8
+#else
+       mov     r12, lr, lsr #8
+#endif
+       ldr     lr, [r1], #4
+#ifdef __ARMEB__
+       orr     r12, r12, lr, lsr #24
+#else
+       orr     r12, r12, lr, lsl #24
+#endif
+       str     r12, [r0], #4
+       subs    r2, r2, #4
+       bge     .Lmemcpy_srcul1loop4
+
+.Lmemcpy_srcul1l4:
+       sub     r1, r1, #3
+       b       .Lmemcpy_l4
+
+.Lmemcpy_srcul2:
+       cmp     r2, #0x0c
+       blt     .Lmemcpy_srcul2loop4
+       sub     r2, r2, #0x0c
+       stmdb   sp!, {r4, r5}
+
+.Lmemcpy_srcul2loop16:
+#ifdef __ARMEB__
+       mov     r3, lr, lsl #16
+#else
+       mov     r3, lr, lsr #16
+#endif
+       ldmia   r1!, {r4, r5, r12, lr}
+#ifdef __ARMEB__
+       orr     r3, r3, r4, lsr #16
+       mov     r4, r4, lsl #16
+       orr     r4, r4, r5, lsr #16
+       mov     r5, r5, lsl #16
+       orr     r5, r5, r12, lsr #16
+       mov     r12, r12, lsl #16
+       orr     r12, r12, lr, lsr #16
+#else
+       orr     r3, r3, r4, lsl #16
+       mov     r4, r4, lsr #16
+       orr     r4, r4, r5, lsl #16
+       mov     r5, r5, lsr #16
+       orr     r5, r5, r12, lsl #16
+       mov     r12, r12, lsr #16
+       orr     r12, r12, lr, lsl #16
+#endif
+       stmia   r0!, {r3-r5, r12}
+       subs    r2, r2, #0x10
+       bge     .Lmemcpy_srcul2loop16
+       ldmia   sp!, {r4, r5}
+       adds    r2, r2, #0x0c
+       blt     .Lmemcpy_srcul2l4
+
+.Lmemcpy_srcul2loop4:
+#ifdef __ARMEB__
+       mov     r12, lr, lsl #16
+#else
+       mov     r12, lr, lsr #16
+#endif
+       ldr     lr, [r1], #4
+#ifdef __ARMEB__
+       orr     r12, r12, lr, lsr #16
+#else
+       orr     r12, r12, lr, lsl #16
+#endif
+       str     r12, [r0], #4
+       subs    r2, r2, #4
+       bge     .Lmemcpy_srcul2loop4
+
+.Lmemcpy_srcul2l4:
+       sub     r1, r1, #2
+       b       .Lmemcpy_l4
+
+.Lmemcpy_srcul3:
+       cmp     r2, #0x0c
+       blt     .Lmemcpy_srcul3loop4
+       sub     r2, r2, #0x0c
+       stmdb   sp!, {r4, r5}
+
+.Lmemcpy_srcul3loop16:
+#ifdef __ARMEB__
+       mov     r3, lr, lsl #24
+#else
+       mov     r3, lr, lsr #24
+#endif
+       ldmia   r1!, {r4, r5, r12, lr}
+#ifdef __ARMEB__
+       orr     r3, r3, r4, lsr #8
+       mov     r4, r4, lsl #24
+       orr     r4, r4, r5, lsr #8
+       mov     r5, r5, lsl #24
+       orr     r5, r5, r12, lsr #8
+       mov     r12, r12, lsl #24
+       orr     r12, r12, lr, lsr #8
+#else
+       orr     r3, r3, r4, lsl #8
+       mov     r4, r4, lsr #24
+       orr     r4, r4, r5, lsl #8
+       mov     r5, r5, lsr #24
+       orr     r5, r5, r12, lsl #8
+       mov     r12, r12, lsr #24
+       orr     r12, r12, lr, lsl #8
+#endif
+       stmia   r0!, {r3-r5, r12}
+       subs    r2, r2, #0x10
+       bge     .Lmemcpy_srcul3loop16
+       ldmia   sp!, {r4, r5}
+       adds    r2, r2, #0x0c
+       blt     .Lmemcpy_srcul3l4
+
+.Lmemcpy_srcul3loop4:
+#ifdef __ARMEB__
+       mov     r12, lr, lsl #24
+#else
+       mov     r12, lr, lsr #24
+#endif
+       ldr     lr, [r1], #4
+#ifdef __ARMEB__
+       orr     r12, r12, lr, lsr #8
+#else
+       orr     r12, r12, lr, lsl #8
+#endif
+       str     r12, [r0], #4
+       subs    r2, r2, #4
+       bge     .Lmemcpy_srcul3loop4
+
+.Lmemcpy_srcul3l4:
+       sub     r1, r1, #1
+       b       .Lmemcpy_l4
diff --git a/common/lib/libc/arch/arm/string/memcpy_xscale.S b/common/lib/libc/arch/arm/string/memcpy_xscale.S
new file mode 100644 (file)
index 0000000..3e157d0
--- /dev/null
@@ -0,0 +1,1893 @@
+/*     $NetBSD: memcpy_xscale.S,v 1.2 2007/06/21 21:37:04 scw Exp $    */
+
+/*
+ * Copyright 2003 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Steve C. Woodford for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 <machine/asm.h>
+
+/* LINTSTUB: Func: void *memcpy(void *dst, const void *src, size_t len) */
+ENTRY(memcpy)
+       pld     [r1]
+       cmp     r2, #0x0c
+       ble     .Lmemcpy_short          /* <= 12 bytes */
+       mov     r3, r0                  /* We must not clobber r0 */
+
+       /* Word-align the destination buffer */
+       ands    ip, r3, #0x03           /* Already word aligned? */
+       beq     .Lmemcpy_wordaligned    /* Yup */
+       cmp     ip, #0x02
+       ldrb    ip, [r1], #0x01
+       sub     r2, r2, #0x01
+       strb    ip, [r3], #0x01
+       ldrleb  ip, [r1], #0x01
+       suble   r2, r2, #0x01
+       strleb  ip, [r3], #0x01
+       ldrltb  ip, [r1], #0x01
+       sublt   r2, r2, #0x01
+       strltb  ip, [r3], #0x01
+
+       /* Destination buffer is now word aligned */
+.Lmemcpy_wordaligned:
+       ands    ip, r1, #0x03           /* Is src also word-aligned? */
+       bne     .Lmemcpy_bad_align      /* Nope. Things just got bad */
+
+       /* Quad-align the destination buffer */
+       tst     r3, #0x07               /* Already quad aligned? */
+       ldrne   ip, [r1], #0x04
+       stmfd   sp!, {r4-r9}            /* Free up some registers */
+       subne   r2, r2, #0x04
+       strne   ip, [r3], #0x04
+
+       /* Destination buffer quad aligned, source is at least word aligned */
+       subs    r2, r2, #0x80
+       blt     .Lmemcpy_w_lessthan128
+
+       /* Copy 128 bytes at a time */
+.Lmemcpy_w_loop128:
+       ldr     r4, [r1], #0x04         /* LD:00-03 */
+       ldr     r5, [r1], #0x04         /* LD:04-07 */
+       pld     [r1, #0x18]             /* Prefetch 0x20 */
+       ldr     r6, [r1], #0x04         /* LD:08-0b */
+       ldr     r7, [r1], #0x04         /* LD:0c-0f */
+       ldr     r8, [r1], #0x04         /* LD:10-13 */
+       ldr     r9, [r1], #0x04         /* LD:14-17 */
+       strd    r4, [r3], #0x08         /* ST:00-07 */
+       ldr     r4, [r1], #0x04         /* LD:18-1b */
+       ldr     r5, [r1], #0x04         /* LD:1c-1f */
+       strd    r6, [r3], #0x08         /* ST:08-0f */
+       ldr     r6, [r1], #0x04         /* LD:20-23 */
+       ldr     r7, [r1], #0x04         /* LD:24-27 */
+       pld     [r1, #0x18]             /* Prefetch 0x40 */
+       strd    r8, [r3], #0x08         /* ST:10-17 */
+       ldr     r8, [r1], #0x04         /* LD:28-2b */
+       ldr     r9, [r1], #0x04         /* LD:2c-2f */
+       strd    r4, [r3], #0x08         /* ST:18-1f */
+       ldr     r4, [r1], #0x04         /* LD:30-33 */
+       ldr     r5, [r1], #0x04         /* LD:34-37 */
+       strd    r6, [r3], #0x08         /* ST:20-27 */
+       ldr     r6, [r1], #0x04         /* LD:38-3b */
+       ldr     r7, [r1], #0x04         /* LD:3c-3f */
+       strd    r8, [r3], #0x08         /* ST:28-2f */
+       ldr     r8, [r1], #0x04         /* LD:40-43 */
+       ldr     r9, [r1], #0x04         /* LD:44-47 */
+       pld     [r1, #0x18]             /* Prefetch 0x60 */
+       strd    r4, [r3], #0x08         /* ST:30-37 */
+       ldr     r4, [r1], #0x04         /* LD:48-4b */
+       ldr     r5, [r1], #0x04         /* LD:4c-4f */
+       strd    r6, [r3], #0x08         /* ST:38-3f */
+       ldr     r6, [r1], #0x04         /* LD:50-53 */
+       ldr     r7, [r1], #0x04         /* LD:54-57 */
+       strd    r8, [r3], #0x08         /* ST:40-47 */
+       ldr     r8, [r1], #0x04         /* LD:58-5b */
+       ldr     r9, [r1], #0x04         /* LD:5c-5f */
+       strd    r4, [r3], #0x08         /* ST:48-4f */
+       ldr     r4, [r1], #0x04         /* LD:60-63 */
+       ldr     r5, [r1], #0x04         /* LD:64-67 */
+       pld     [r1, #0x18]             /* Prefetch 0x80 */
+       strd    r6, [r3], #0x08         /* ST:50-57 */
+       ldr     r6, [r1], #0x04         /* LD:68-6b */
+       ldr     r7, [r1], #0x04         /* LD:6c-6f */
+       strd    r8, [r3], #0x08         /* ST:58-5f */
+       ldr     r8, [r1], #0x04         /* LD:70-73 */
+       ldr     r9, [r1], #0x04         /* LD:74-77 */
+       strd    r4, [r3], #0x08         /* ST:60-67 */
+       ldr     r4, [r1], #0x04         /* LD:78-7b */
+       ldr     r5, [r1], #0x04         /* LD:7c-7f */
+       strd    r6, [r3], #0x08         /* ST:68-6f */
+       strd    r8, [r3], #0x08         /* ST:70-77 */
+       subs    r2, r2, #0x80
+       strd    r4, [r3], #0x08         /* ST:78-7f */
+       bge     .Lmemcpy_w_loop128
+
+.Lmemcpy_w_lessthan128:
+       adds    r2, r2, #0x80           /* Adjust for extra sub */
+       ldmeqfd sp!, {r4-r9}
+       bxeq    lr                      /* Return now if done */
+       subs    r2, r2, #0x20
+       blt     .Lmemcpy_w_lessthan32
+
+       /* Copy 32 bytes at a time */
+.Lmemcpy_w_loop32:
+       ldr     r4, [r1], #0x04
+       ldr     r5, [r1], #0x04
+       pld     [r1, #0x18]
+       ldr     r6, [r1], #0x04
+       ldr     r7, [r1], #0x04
+       ldr     r8, [r1], #0x04
+       ldr     r9, [r1], #0x04
+       strd    r4, [r3], #0x08
+       ldr     r4, [r1], #0x04
+       ldr     r5, [r1], #0x04
+       strd    r6, [r3], #0x08
+       strd    r8, [r3], #0x08
+       subs    r2, r2, #0x20
+       strd    r4, [r3], #0x08
+       bge     .Lmemcpy_w_loop32
+
+.Lmemcpy_w_lessthan32:
+       adds    r2, r2, #0x20           /* Adjust for extra sub */
+       ldmeqfd sp!, {r4-r9}
+       bxeq    lr                      /* Return now if done */
+
+       and     r4, r2, #0x18
+       rsbs    r4, r4, #0x18
+       addne   pc, pc, r4, lsl #1
+       nop
+
+       /* At least 24 bytes remaining */
+       ldr     r4, [r1], #0x04
+       ldr     r5, [r1], #0x04
+       sub     r2, r2, #0x08
+       strd    r4, [r3], #0x08
+
+       /* At least 16 bytes remaining */
+       ldr     r4, [r1], #0x04
+       ldr     r5, [r1], #0x04
+       sub     r2, r2, #0x08
+       strd    r4, [r3], #0x08
+
+       /* At least 8 bytes remaining */
+       ldr     r4, [r1], #0x04
+       ldr     r5, [r1], #0x04
+       subs    r2, r2, #0x08
+       strd    r4, [r3], #0x08
+
+       /* Less than 8 bytes remaining */
+       ldmfd   sp!, {r4-r9}
+       bxeq    lr                      /* Return now if done */
+       subs    r2, r2, #0x04
+       ldrge   ip, [r1], #0x04
+       strge   ip, [r3], #0x04
+       bxeq    lr                      /* Return now if done */
+       addlt   r2, r2, #0x04
+       ldrb    ip, [r1], #0x01
+       cmp     r2, #0x02
+       ldrgeb  r2, [r1], #0x01
+       strb    ip, [r3], #0x01
+       ldrgtb  ip, [r1]
+       strgeb  r2, [r3], #0x01
+       strgtb  ip, [r3]
+       bx      lr
+
+
+/*
+ * At this point, it has not been possible to word align both buffers.
+ * The destination buffer is word aligned, but the source buffer is not.
+ */
+.Lmemcpy_bad_align:
+       stmfd   sp!, {r4-r7}
+       bic     r1, r1, #0x03
+       cmp     ip, #2
+       ldr     ip, [r1], #0x04
+       bgt     .Lmemcpy_bad3
+       beq     .Lmemcpy_bad2
+       b       .Lmemcpy_bad1
+
+.Lmemcpy_bad1_loop16:
+#ifdef __ARMEB__
+       mov     r4, ip, lsl #8
+#else
+       mov     r4, ip, lsr #8
+#endif
+       ldr     r5, [r1], #0x04
+       pld     [r1, #0x018]
+       ldr     r6, [r1], #0x04
+       ldr     r7, [r1], #0x04
+       ldr     ip, [r1], #0x04
+#ifdef __ARMEB__
+       orr     r4, r4, r5, lsr #24
+       mov     r5, r5, lsl #8
+       orr     r5, r5, r6, lsr #24
+       mov     r6, r6, lsl #8
+       orr     r6, r6, r7, lsr #24
+       mov     r7, r7, lsl #8
+       orr     r7, r7, ip, lsr #24
+#else
+       orr     r4, r4, r5, lsl #24
+       mov     r5, r5, lsr #8
+       orr     r5, r5, r6, lsl #24
+       mov     r6, r6, lsr #8
+       orr     r6, r6, r7, lsl #24
+       mov     r7, r7, lsr #8
+       orr     r7, r7, ip, lsl #24
+#endif
+       str     r4, [r3], #0x04
+       str     r5, [r3], #0x04
+       str     r6, [r3], #0x04
+       str     r7, [r3], #0x04
+       sub     r2, r2, #0x10
+
+.Lmemcpy_bad1:
+       cmp     r2, #0x20
+       bge     .Lmemcpy_bad1_loop16
+       cmp     r2, #0x10
+       blt     .Lmemcpy_bad1_loop16_short
+
+       /* copy last 16 bytes (without preload) */
+#ifdef __ARMEB__
+       mov     r4, ip, lsl #8
+#else
+       mov     r4, ip, lsr #8
+#endif
+       ldr     r5, [r1], #0x04
+       ldr     r6, [r1], #0x04
+       ldr     r7, [r1], #0x04
+       ldr     ip, [r1], #0x04
+#ifdef __ARMEB__
+       orr     r4, r4, r5, lsr #24
+       mov     r5, r5, lsl #8
+       orr     r5, r5, r6, lsr #24
+       mov     r6, r6, lsl #8
+       orr     r6, r6, r7, lsr #24
+       mov     r7, r7, lsl #8
+       orr     r7, r7, ip, lsr #24
+#else
+       orr     r4, r4, r5, lsl #24
+       mov     r5, r5, lsr #8
+       orr     r5, r5, r6, lsl #24
+       mov     r6, r6, lsr #8
+       orr     r6, r6, r7, lsl #24
+       mov     r7, r7, lsr #8
+       orr     r7, r7, ip, lsl #24
+#endif
+       str     r4, [r3], #0x04
+       str     r5, [r3], #0x04
+       str     r6, [r3], #0x04
+       str     r7, [r3], #0x04
+       subs    r2, r2, #0x10
+       ldmeqfd sp!, {r4-r7}
+       bxeq    lr                      /* Return now if done */
+
+.Lmemcpy_bad1_loop16_short:
+       subs    r2, r2, #0x04
+       sublt   r1, r1, #0x03
+       blt     .Lmemcpy_bad_done
+
+.Lmemcpy_bad1_loop4:
+#ifdef __ARMEB__
+       mov     r4, ip, lsl #8
+#else
+       mov     r4, ip, lsr #8
+#endif
+       ldr     ip, [r1], #0x04
+       subs    r2, r2, #0x04
+#ifdef __ARMEB__
+       orr     r4, r4, ip, lsr #24
+#else
+       orr     r4, r4, ip, lsl #24
+#endif
+       str     r4, [r3], #0x04
+       bge     .Lmemcpy_bad1_loop4
+       sub     r1, r1, #0x03
+       b       .Lmemcpy_bad_done
+
+.Lmemcpy_bad2_loop16:
+#ifdef __ARMEB__
+       mov     r4, ip, lsl #16
+#else
+       mov     r4, ip, lsr #16
+#endif
+       ldr     r5, [r1], #0x04
+       pld     [r1, #0x018]
+       ldr     r6, [r1], #0x04
+       ldr     r7, [r1], #0x04
+       ldr     ip, [r1], #0x04
+#ifdef __ARMEB__
+       orr     r4, r4, r5, lsr #16
+       mov     r5, r5, lsl #16
+       orr     r5, r5, r6, lsr #16
+       mov     r6, r6, lsl #16
+       orr     r6, r6, r7, lsr #16
+       mov     r7, r7, lsl #16
+       orr     r7, r7, ip, lsr #16
+#else
+       orr     r4, r4, r5, lsl #16
+       mov     r5, r5, lsr #16
+       orr     r5, r5, r6, lsl #16
+       mov     r6, r6, lsr #16
+       orr     r6, r6, r7, lsl #16
+       mov     r7, r7, lsr #16
+       orr     r7, r7, ip, lsl #16
+#endif
+       str     r4, [r3], #0x04
+       str     r5, [r3], #0x04
+       str     r6, [r3], #0x04
+       str     r7, [r3], #0x04
+       sub     r2, r2, #0x10
+
+.Lmemcpy_bad2:
+       cmp     r2, #0x20
+       bge     .Lmemcpy_bad2_loop16
+       cmp     r2, #0x10
+       blt     .Lmemcpy_bad2_loop16_short
+
+       /* copy last 16 bytes (without preload) */
+#ifdef __ARMEB__
+       mov     r4, ip, lsl #16
+#else
+       mov     r4, ip, lsr #16
+#endif
+       ldr     r5, [r1], #0x04
+       ldr     r6, [r1], #0x04
+       ldr     r7, [r1], #0x04
+       ldr     ip, [r1], #0x04
+#ifdef __ARMEB__
+       orr     r4, r4, r5, lsr #16
+       mov     r5, r5, lsl #16
+       orr     r5, r5, r6, lsr #16
+       mov     r6, r6, lsl #16
+       orr     r6, r6, r7, lsr #16
+       mov     r7, r7, lsl #16
+       orr     r7, r7, ip, lsr #16
+#else
+       orr     r4, r4, r5, lsl #16
+       mov     r5, r5, lsr #16
+       orr     r5, r5, r6, lsl #16
+       mov     r6, r6, lsr #16
+       orr     r6, r6, r7, lsl #16
+       mov     r7, r7, lsr #16
+       orr     r7, r7, ip, lsl #16
+#endif
+       str     r4, [r3], #0x04
+       str     r5, [r3], #0x04
+       str     r6, [r3], #0x04
+       str     r7, [r3], #0x04
+       subs    r2, r2, #0x10
+       ldmeqfd sp!, {r4-r7}
+       bxeq    lr                      /* Return now if done */
+
+.Lmemcpy_bad2_loop16_short:
+       subs    r2, r2, #0x04
+       sublt   r1, r1, #0x02
+       blt     .Lmemcpy_bad_done
+
+.Lmemcpy_bad2_loop4:
+#ifdef __ARMEB__
+       mov     r4, ip, lsl #16
+#else
+       mov     r4, ip, lsr #16
+#endif
+       ldr     ip, [r1], #0x04
+       subs    r2, r2, #0x04
+#ifdef __ARMEB__
+       orr     r4, r4, ip, lsr #16
+#else
+       orr     r4, r4, ip, lsl #16
+#endif
+       str     r4, [r3], #0x04
+       bge     .Lmemcpy_bad2_loop4
+       sub     r1, r1, #0x02
+       b       .Lmemcpy_bad_done
+
+.Lmemcpy_bad3_loop16:
+#ifdef __ARMEB__
+       mov     r4, ip, lsl #24
+#else
+       mov     r4, ip, lsr #24
+#endif
+       ldr     r5, [r1], #0x04
+       pld     [r1, #0x018]
+       ldr     r6, [r1], #0x04
+       ldr     r7, [r1], #0x04
+       ldr     ip, [r1], #0x04
+#ifdef __ARMEB__
+       orr     r4, r4, r5, lsr #8
+       mov     r5, r5, lsl #24
+       orr     r5, r5, r6, lsr #8
+       mov     r6, r6, lsl #24
+       orr     r6, r6, r7, lsr #8
+       mov     r7, r7, lsl #24
+       orr     r7, r7, ip, lsr #8
+#else
+       orr     r4, r4, r5, lsl #8
+       mov     r5, r5, lsr #24
+       orr     r5, r5, r6, lsl #8
+       mov     r6, r6, lsr #24
+       orr     r6, r6, r7, lsl #8
+       mov     r7, r7, lsr #24
+       orr     r7, r7, ip, lsl #8
+#endif
+       str     r4, [r3], #0x04
+       str     r5, [r3], #0x04
+       str     r6, [r3], #0x04
+       str     r7, [r3], #0x04
+       sub     r2, r2, #0x10
+
+.Lmemcpy_bad3:
+       cmp     r2, #0x20
+       bge     .Lmemcpy_bad3_loop16
+       cmp     r2, #0x10
+       blt     .Lmemcpy_bad3_loop16_short
+
+       /* copy last 16 bytes (without preload) */
+#ifdef __ARMEB__
+       mov     r4, ip, lsl #24
+#else
+       mov     r4, ip, lsr #24
+#endif
+       ldr     r5, [r1], #0x04
+       ldr     r6, [r1], #0x04
+       ldr     r7, [r1], #0x04
+       ldr     ip, [r1], #0x04
+#ifdef __ARMEB__
+       orr     r4, r4, r5, lsr #8
+       mov     r5, r5, lsl #24
+       orr     r5, r5, r6, lsr #8
+       mov     r6, r6, lsl #24
+       orr     r6, r6, r7, lsr #8
+       mov     r7, r7, lsl #24
+       orr     r7, r7, ip, lsr #8
+#else
+       orr     r4, r4, r5, lsl #8
+       mov     r5, r5, lsr #24
+       orr     r5, r5, r6, lsl #8
+       mov     r6, r6, lsr #24
+       orr     r6, r6, r7, lsl #8
+       mov     r7, r7, lsr #24
+       orr     r7, r7, ip, lsl #8
+#endif
+       str     r4, [r3], #0x04
+       str     r5, [r3], #0x04
+       str     r6, [r3], #0x04
+       str     r7, [r3], #0x04
+       subs    r2, r2, #0x10
+       ldmeqfd sp!, {r4-r7}
+       bxeq    lr                      /* Return now if done */
+
+.Lmemcpy_bad3_loop16_short:
+       subs    r2, r2, #0x04
+       sublt   r1, r1, #0x01
+       blt     .Lmemcpy_bad_done
+
+.Lmemcpy_bad3_loop4:
+#ifdef __ARMEB__
+       mov     r4, ip, lsl #24
+#else
+       mov     r4, ip, lsr #24
+#endif
+       ldr     ip, [r1], #0x04
+       subs    r2, r2, #0x04
+#ifdef __ARMEB__
+       orr     r4, r4, ip, lsr #8
+#else
+       orr     r4, r4, ip, lsl #8
+#endif
+       str     r4, [r3], #0x04
+       bge     .Lmemcpy_bad3_loop4
+       sub     r1, r1, #0x01
+
+.Lmemcpy_bad_done:
+       ldmfd   sp!, {r4-r7}
+       adds    r2, r2, #0x04
+       bxeq    lr
+       ldrb    ip, [r1], #0x01
+       cmp     r2, #0x02
+       ldrgeb  r2, [r1], #0x01
+       strb    ip, [r3], #0x01
+       ldrgtb  ip, [r1]
+       strgeb  r2, [r3], #0x01
+       strgtb  ip, [r3]
+       bx      lr
+
+
+/*
+ * Handle short copies (less than 16 bytes), possibly misaligned.
+ * Some of these are *very* common, thanks to the network stack,
+ * and so are handled specially.
+ */
+.Lmemcpy_short:
+#ifndef _STANDALONE
+       add     pc, pc, r2, lsl #2
+       nop
+       bx      lr                      /* 0x00 */
+       b       .Lmemcpy_bytewise       /* 0x01 */
+       b       .Lmemcpy_bytewise       /* 0x02 */
+       b       .Lmemcpy_bytewise       /* 0x03 */
+       b       .Lmemcpy_4              /* 0x04 */
+       b       .Lmemcpy_bytewise       /* 0x05 */
+       b       .Lmemcpy_6              /* 0x06 */
+       b       .Lmemcpy_bytewise       /* 0x07 */
+       b       .Lmemcpy_8              /* 0x08 */
+       b       .Lmemcpy_bytewise       /* 0x09 */
+       b       .Lmemcpy_bytewise       /* 0x0a */
+       b       .Lmemcpy_bytewise       /* 0x0b */
+       b       .Lmemcpy_c              /* 0x0c */
+#endif
+.Lmemcpy_bytewise:
+       mov     r3, r0                  /* We must not clobber r0 */
+       ldrb    ip, [r1], #0x01
+1:     subs    r2, r2, #0x01
+       strb    ip, [r3], #0x01
+       ldrneb  ip, [r1], #0x01
+       bne     1b
+       bx      lr
+
+#ifndef _STANDALONE
+/******************************************************************************
+ * Special case for 4 byte copies
+ */
+#define        LMEMCPY_4_LOG2  6       /* 64 bytes */
+#define        LMEMCPY_4_PAD   .align LMEMCPY_4_LOG2
+       LMEMCPY_4_PAD
+.Lmemcpy_4:
+       and     r2, r1, #0x03
+       orr     r2, r2, r0, lsl #2
+       ands    r2, r2, #0x0f
+       sub     r3, pc, #0x14
+       addne   pc, r3, r2, lsl #LMEMCPY_4_LOG2
+
+/*
+ * 0000: dst is 32-bit aligned, src is 32-bit aligned
+ */
+       ldr     r2, [r1]
+       str     r2, [r0]
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 0001: dst is 32-bit aligned, src is 8-bit aligned
+ */
+       ldr     r3, [r1, #-1]           /* BE:r3 = x012  LE:r3 = 210x */
+       ldr     r2, [r1, #3]            /* BE:r2 = 3xxx  LE:r2 = xxx3 */
+#ifdef __ARMEB__
+       mov     r3, r3, lsl #8          /* r3 = 012. */
+       orr     r3, r3, r2, lsr #24     /* r3 = 0123 */
+#else
+       mov     r3, r3, lsr #8          /* r3 = .210 */
+       orr     r3, r3, r2, lsl #24     /* r3 = 3210 */
+#endif
+       str     r3, [r0]
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 0010: dst is 32-bit aligned, src is 16-bit aligned
+ */
+#ifdef __ARMEB__
+       ldrh    r3, [r1]
+       ldrh    r2, [r1, #0x02]
+#else
+       ldrh    r3, [r1, #0x02]
+       ldrh    r2, [r1]
+#endif
+       orr     r3, r2, r3, lsl #16
+       str     r3, [r0]
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 0011: dst is 32-bit aligned, src is 8-bit aligned
+ */
+       ldr     r3, [r1, #-3]           /* BE:r3 = xxx0  LE:r3 = 0xxx */
+       ldr     r2, [r1, #1]            /* BE:r2 = 123x  LE:r2 = x321 */
+#ifdef __ARMEB__
+       mov     r3, r3, lsl #24         /* r3 = 0... */
+       orr     r3, r3, r2, lsr #8      /* r3 = 0123 */
+#else
+       mov     r3, r3, lsr #24         /* r3 = ...0 */
+       orr     r3, r3, r2, lsl #8      /* r3 = 3210 */
+#endif
+       str     r3, [r0]
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 0100: dst is 8-bit aligned, src is 32-bit aligned
+ */
+       ldr     r2, [r1]
+#ifdef __ARMEB__
+       strb    r2, [r0, #0x03]
+       mov     r3, r2, lsr #8
+       mov     r1, r2, lsr #24
+       strb    r1, [r0]
+#else
+       strb    r2, [r0]
+       mov     r3, r2, lsr #8
+       mov     r1, r2, lsr #24
+       strb    r1, [r0, #0x03]
+#endif
+       strh    r3, [r0, #0x01]
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 0101: dst is 8-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r2, [r1]
+       ldrh    r3, [r1, #0x01]
+       ldrb    r1, [r1, #0x03]
+       strb    r2, [r0]
+       strh    r3, [r0, #0x01]
+       strb    r1, [r0, #0x03]
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 0110: dst is 8-bit aligned, src is 16-bit aligned
+ */
+       ldrh    r2, [r1]                /* BE:r2 = ..01  LE:r2 = ..10 */
+       ldrh    r3, [r1, #0x02]         /* LE:r3 = ..23  LE:r3 = ..32 */
+#ifdef __ARMEB__
+       mov     r1, r2, lsr #8          /* r1 = ...0 */
+       strb    r1, [r0]
+       mov     r2, r2, lsl #8          /* r2 = .01. */
+       orr     r2, r2, r3, lsr #8      /* r2 = .012 */
+#else
+       strb    r2, [r0]
+       mov     r2, r2, lsr #8          /* r2 = ...1 */
+       orr     r2, r2, r3, lsl #8      /* r2 = .321 */
+       mov     r3, r3, lsr #8          /* r3 = ...3 */
+#endif
+       strh    r2, [r0, #0x01]
+       strb    r3, [r0, #0x03]
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 0111: dst is 8-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r2, [r1]
+       ldrh    r3, [r1, #0x01]
+       ldrb    r1, [r1, #0x03]
+       strb    r2, [r0]
+       strh    r3, [r0, #0x01]
+       strb    r1, [r0, #0x03]
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 1000: dst is 16-bit aligned, src is 32-bit aligned
+ */
+       ldr     r2, [r1]
+#ifdef __ARMEB__
+       strh    r2, [r0, #0x02]
+       mov     r3, r2, lsr #16
+       strh    r3, [r0]
+#else
+       strh    r2, [r0]
+       mov     r3, r2, lsr #16
+       strh    r3, [r0, #0x02]
+#endif
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 1001: dst is 16-bit aligned, src is 8-bit aligned
+ */
+       ldr     r2, [r1, #-1]           /* BE:r2 = x012  LE:r2 = 210x */
+       ldr     r3, [r1, #3]            /* BE:r3 = 3xxx  LE:r3 = xxx3 */
+       mov     r1, r2, lsr #8          /* BE:r1 = .x01  LE:r1 = .210 */
+       strh    r1, [r0]
+#ifdef __ARMEB__
+       mov     r2, r2, lsl #8          /* r2 = 012. */
+       orr     r2, r2, r3, lsr #24     /* r2 = 0123 */
+#else
+       mov     r2, r2, lsr #24         /* r2 = ...2 */
+       orr     r2, r2, r3, lsl #8      /* r2 = xx32 */
+#endif
+       strh    r2, [r0, #0x02]
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 1010: dst is 16-bit aligned, src is 16-bit aligned
+ */
+       ldrh    r2, [r1]
+       ldrh    r3, [r1, #0x02]
+       strh    r2, [r0]
+       strh    r3, [r0, #0x02]
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 1011: dst is 16-bit aligned, src is 8-bit aligned
+ */
+       ldr     r3, [r1, #1]            /* BE:r3 = 123x  LE:r3 = x321 */
+       ldr     r2, [r1, #-3]           /* BE:r2 = xxx0  LE:r2 = 0xxx */
+       mov     r1, r3, lsr #8          /* BE:r1 = .123  LE:r1 = .x32 */
+       strh    r1, [r0, #0x02]
+#ifdef __ARMEB__
+       mov     r3, r3, lsr #24         /* r3 = ...1 */
+       orr     r3, r3, r2, lsl #8      /* r3 = xx01 */
+#else
+       mov     r3, r3, lsl #8          /* r3 = 321. */
+       orr     r3, r3, r2, lsr #24     /* r3 = 3210 */
+#endif
+       strh    r3, [r0]
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 1100: dst is 8-bit aligned, src is 32-bit aligned
+ */
+       ldr     r2, [r1]                /* BE:r2 = 0123  LE:r2 = 3210 */
+#ifdef __ARMEB__
+       strb    r2, [r0, #0x03]
+       mov     r3, r2, lsr #8
+       mov     r1, r2, lsr #24
+       strh    r3, [r0, #0x01]
+       strb    r1, [r0]
+#else
+       strb    r2, [r0]
+       mov     r3, r2, lsr #8
+       mov     r1, r2, lsr #24
+       strh    r3, [r0, #0x01]
+       strb    r1, [r0, #0x03]
+#endif
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 1101: dst is 8-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r2, [r1]
+       ldrh    r3, [r1, #0x01]
+       ldrb    r1, [r1, #0x03]
+       strb    r2, [r0]
+       strh    r3, [r0, #0x01]
+       strb    r1, [r0, #0x03]
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 1110: dst is 8-bit aligned, src is 16-bit aligned
+ */
+#ifdef __ARMEB__
+       ldrh    r3, [r1, #0x02]         /* BE:r3 = ..23  LE:r3 = ..32 */
+       ldrh    r2, [r1]                /* BE:r2 = ..01  LE:r2 = ..10 */
+       strb    r3, [r0, #0x03]
+       mov     r3, r3, lsr #8          /* r3 = ...2 */
+       orr     r3, r3, r2, lsl #8      /* r3 = ..12 */
+       strh    r3, [r0, #0x01]
+       mov     r2, r2, lsr #8          /* r2 = ...0 */
+       strb    r2, [r0]
+#else
+       ldrh    r2, [r1]                /* BE:r2 = ..01  LE:r2 = ..10 */
+       ldrh    r3, [r1, #0x02]         /* BE:r3 = ..23  LE:r3 = ..32 */
+       strb    r2, [r0]
+       mov     r2, r2, lsr #8          /* r2 = ...1 */
+       orr     r2, r2, r3, lsl #8      /* r2 = .321 */
+       strh    r2, [r0, #0x01]
+       mov     r3, r3, lsr #8          /* r3 = ...3 */
+       strb    r3, [r0, #0x03]
+#endif
+       bx      lr
+       LMEMCPY_4_PAD
+
+/*
+ * 1111: dst is 8-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r2, [r1]
+       ldrh    r3, [r1, #0x01]
+       ldrb    r1, [r1, #0x03]
+       strb    r2, [r0]
+       strh    r3, [r0, #0x01]
+       strb    r1, [r0, #0x03]
+       bx      lr
+       LMEMCPY_4_PAD
+
+
+/******************************************************************************
+ * Special case for 6 byte copies
+ */
+#define        LMEMCPY_6_LOG2  6       /* 64 bytes */
+#define        LMEMCPY_6_PAD   .align LMEMCPY_6_LOG2
+       LMEMCPY_6_PAD
+.Lmemcpy_6:
+       and     r2, r1, #0x03
+       orr     r2, r2, r0, lsl #2
+       ands    r2, r2, #0x0f
+       sub     r3, pc, #0x14
+       addne   pc, r3, r2, lsl #LMEMCPY_6_LOG2
+
+/*
+ * 0000: dst is 32-bit aligned, src is 32-bit aligned
+ */
+       ldr     r2, [r1]
+       ldrh    r3, [r1, #0x04]
+       str     r2, [r0]
+       strh    r3, [r0, #0x04]
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 0001: dst is 32-bit aligned, src is 8-bit aligned
+ */
+       ldr     r2, [r1, #-1]           /* BE:r2 = x012  LE:r2 = 210x */
+       ldr     r3, [r1, #0x03]         /* BE:r3 = 345x  LE:r3 = x543 */
+#ifdef __ARMEB__
+       mov     r2, r2, lsl #8          /* r2 = 012. */
+       orr     r2, r2, r3, lsr #24     /* r2 = 0123 */
+#else
+       mov     r2, r2, lsr #8          /* r2 = .210 */
+       orr     r2, r2, r3, lsl #24     /* r2 = 3210 */
+#endif
+       mov     r3, r3, lsr #8          /* BE:r3 = .345  LE:r3 = .x54 */
+       str     r2, [r0]
+       strh    r3, [r0, #0x04]
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 0010: dst is 32-bit aligned, src is 16-bit aligned
+ */
+       ldr     r3, [r1, #0x02]         /* BE:r3 = 2345  LE:r3 = 5432 */
+       ldrh    r2, [r1]                /* BE:r2 = ..01  LE:r2 = ..10 */
+#ifdef __ARMEB__
+       mov     r1, r3, lsr #16         /* r1 = ..23 */
+       orr     r1, r1, r2, lsl #16     /* r1 = 0123 */
+       str     r1, [r0]
+       strh    r3, [r0, #0x04]
+#else
+       mov     r1, r3, lsr #16         /* r1 = ..54 */
+       orr     r2, r2, r3, lsl #16     /* r2 = 3210 */
+       str     r2, [r0]
+       strh    r1, [r0, #0x04]
+#endif
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 0011: dst is 32-bit aligned, src is 8-bit aligned
+ */
+       ldr     r2, [r1, #-3]           /* BE:r2 = xxx0  LE:r2 = 0xxx */
+       ldr     r3, [r1, #1]            /* BE:r3 = 1234  LE:r3 = 4321 */
+       ldr     r1, [r1, #5]            /* BE:r1 = 5xxx  LE:r3 = xxx5 */
+#ifdef __ARMEB__
+       mov     r2, r2, lsl #24         /* r2 = 0... */
+       orr     r2, r2, r3, lsr #8      /* r2 = 0123 */
+       mov     r3, r3, lsl #8          /* r3 = 234. */
+       orr     r1, r3, r1, lsr #24     /* r1 = 2345 */
+#else
+       mov     r2, r2, lsr #24         /* r2 = ...0 */
+       orr     r2, r2, r3, lsl #8      /* r2 = 3210 */
+       mov     r1, r1, lsl #8          /* r1 = xx5. */
+       orr     r1, r1, r3, lsr #24     /* r1 = xx54 */
+#endif
+       str     r2, [r0]
+       strh    r1, [r0, #0x04]
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 0100: dst is 8-bit aligned, src is 32-bit aligned
+ */
+       ldr     r3, [r1]                /* BE:r3 = 0123  LE:r3 = 3210 */
+       ldrh    r2, [r1, #0x04]         /* BE:r2 = ..45  LE:r2 = ..54 */
+       mov     r1, r3, lsr #8          /* BE:r1 = .012  LE:r1 = .321 */
+       strh    r1, [r0, #0x01]
+#ifdef __ARMEB__
+       mov     r1, r3, lsr #24         /* r1 = ...0 */
+       strb    r1, [r0]
+       mov     r3, r3, lsl #8          /* r3 = 123. */
+       orr     r3, r3, r2, lsr #8      /* r3 = 1234 */
+#else
+       strb    r3, [r0]
+       mov     r3, r3, lsr #24         /* r3 = ...3 */
+       orr     r3, r3, r2, lsl #8      /* r3 = .543 */
+       mov     r2, r2, lsr #8          /* r2 = ...5 */
+#endif
+       strh    r3, [r0, #0x03]
+       strb    r2, [r0, #0x05]
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 0101: dst is 8-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r2, [r1]
+       ldrh    r3, [r1, #0x01]
+       ldrh    ip, [r1, #0x03]
+       ldrb    r1, [r1, #0x05]
+       strb    r2, [r0]
+       strh    r3, [r0, #0x01]
+       strh    ip, [r0, #0x03]
+       strb    r1, [r0, #0x05]
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 0110: dst is 8-bit aligned, src is 16-bit aligned
+ */
+       ldrh    r2, [r1]                /* BE:r2 = ..01  LE:r2 = ..10 */
+       ldr     r1, [r1, #0x02]         /* BE:r1 = 2345  LE:r1 = 5432 */
+#ifdef __ARMEB__
+       mov     r3, r2, lsr #8          /* r3 = ...0 */
+       strb    r3, [r0]
+       strb    r1, [r0, #0x05]
+       mov     r3, r1, lsr #8          /* r3 = .234 */
+       strh    r3, [r0, #0x03]
+       mov     r3, r2, lsl #8          /* r3 = .01. */
+       orr     r3, r3, r1, lsr #24     /* r3 = .012 */
+       strh    r3, [r0, #0x01]
+#else
+       strb    r2, [r0]
+       mov     r3, r1, lsr #24
+       strb    r3, [r0, #0x05]
+       mov     r3, r1, lsr #8          /* r3 = .543 */
+       strh    r3, [r0, #0x03]
+       mov     r3, r2, lsr #8          /* r3 = ...1 */
+       orr     r3, r3, r1, lsl #8      /* r3 = 4321 */
+       strh    r3, [r0, #0x01]
+#endif
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 0111: dst is 8-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r2, [r1]
+       ldrh    r3, [r1, #0x01]
+       ldrh    ip, [r1, #0x03]
+       ldrb    r1, [r1, #0x05]
+       strb    r2, [r0]
+       strh    r3, [r0, #0x01]
+       strh    ip, [r0, #0x03]
+       strb    r1, [r0, #0x05]
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 1000: dst is 16-bit aligned, src is 32-bit aligned
+ */
+#ifdef __ARMEB__
+       ldr     r2, [r1]                /* r2 = 0123 */
+       ldrh    r3, [r1, #0x04]         /* r3 = ..45 */
+       mov     r1, r2, lsr #16         /* r1 = ..01 */
+       orr     r3, r3, r2, lsl#16      /* r3 = 2345 */
+       strh    r1, [r0]
+       str     r3, [r0, #0x02]
+#else
+       ldrh    r2, [r1, #0x04]         /* r2 = ..54 */
+       ldr     r3, [r1]                /* r3 = 3210 */
+       mov     r2, r2, lsl #16         /* r2 = 54.. */
+       orr     r2, r2, r3, lsr #16     /* r2 = 5432 */
+       strh    r3, [r0]
+       str     r2, [r0, #0x02]
+#endif
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 1001: dst is 16-bit aligned, src is 8-bit aligned
+ */
+       ldr     r3, [r1, #-1]           /* BE:r3 = x012  LE:r3 = 210x */
+       ldr     r2, [r1, #3]            /* BE:r2 = 345x  LE:r2 = x543 */
+       mov     r1, r3, lsr #8          /* BE:r1 = .x01  LE:r1 = .210 */
+#ifdef __ARMEB__
+       mov     r2, r2, lsr #8          /* r2 = .345 */
+       orr     r2, r2, r3, lsl #24     /* r2 = 2345 */
+#else
+       mov     r2, r2, lsl #8          /* r2 = 543. */
+       orr     r2, r2, r3, lsr #24     /* r2 = 5432 */
+#endif
+       strh    r1, [r0]
+       str     r2, [r0, #0x02]
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 1010: dst is 16-bit aligned, src is 16-bit aligned
+ */
+       ldrh    r2, [r1]
+       ldr     r3, [r1, #0x02]
+       strh    r2, [r0]
+       str     r3, [r0, #0x02]
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 1011: dst is 16-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r3, [r1]                /* r3 = ...0 */
+       ldr     r2, [r1, #0x01]         /* BE:r2 = 1234  LE:r2 = 4321 */
+       ldrb    r1, [r1, #0x05]         /* r1 = ...5 */
+#ifdef __ARMEB__
+       mov     r3, r3, lsl #8          /* r3 = ..0. */
+       orr     r3, r3, r2, lsr #24     /* r3 = ..01 */
+       orr     r1, r1, r2, lsl #8      /* r1 = 2345 */
+#else
+       orr     r3, r3, r2, lsl #8      /* r3 = 3210 */
+       mov     r1, r1, lsl #24         /* r1 = 5... */
+       orr     r1, r1, r2, lsr #8      /* r1 = 5432 */
+#endif
+       strh    r3, [r0]
+       str     r1, [r0, #0x02]
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 1100: dst is 8-bit aligned, src is 32-bit aligned
+ */
+       ldr     r2, [r1]                /* BE:r2 = 0123  LE:r2 = 3210 */
+       ldrh    r1, [r1, #0x04]         /* BE:r1 = ..45  LE:r1 = ..54 */
+#ifdef __ARMEB__
+       mov     r3, r2, lsr #24         /* r3 = ...0 */
+       strb    r3, [r0]
+       mov     r2, r2, lsl #8          /* r2 = 123. */
+       orr     r2, r2, r1, lsr #8      /* r2 = 1234 */
+#else
+       strb    r2, [r0]
+       mov     r2, r2, lsr #8          /* r2 = .321 */
+       orr     r2, r2, r1, lsl #24     /* r2 = 4321 */
+       mov     r1, r1, lsr #8          /* r1 = ...5 */
+#endif
+       str     r2, [r0, #0x01]
+       strb    r1, [r0, #0x05]
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 1101: dst is 8-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r2, [r1]
+       ldrh    r3, [r1, #0x01]
+       ldrh    ip, [r1, #0x03]
+       ldrb    r1, [r1, #0x05]
+       strb    r2, [r0]
+       strh    r3, [r0, #0x01]
+       strh    ip, [r0, #0x03]
+       strb    r1, [r0, #0x05]
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 1110: dst is 8-bit aligned, src is 16-bit aligned
+ */
+       ldrh    r2, [r1]                /* BE:r2 = ..01  LE:r2 = ..10 */
+       ldr     r1, [r1, #0x02]         /* BE:r1 = 2345  LE:r1 = 5432 */
+#ifdef __ARMEB__
+       mov     r3, r2, lsr #8          /* r3 = ...0 */
+       strb    r3, [r0]
+       mov     r2, r2, lsl #24         /* r2 = 1... */
+       orr     r2, r2, r1, lsr #8      /* r2 = 1234 */
+#else
+       strb    r2, [r0]
+       mov     r2, r2, lsr #8          /* r2 = ...1 */
+       orr     r2, r2, r1, lsl #8      /* r2 = 4321 */
+       mov     r1, r1, lsr #24         /* r1 = ...5 */
+#endif
+       str     r2, [r0, #0x01]
+       strb    r1, [r0, #0x05]
+       bx      lr
+       LMEMCPY_6_PAD
+
+/*
+ * 1111: dst is 8-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r2, [r1]
+       ldr     r3, [r1, #0x01]
+       ldrb    r1, [r1, #0x05]
+       strb    r2, [r0]
+       str     r3, [r0, #0x01]
+       strb    r1, [r0, #0x05]
+       bx      lr
+       LMEMCPY_6_PAD
+
+
+/******************************************************************************
+ * Special case for 8 byte copies
+ */
+#define        LMEMCPY_8_LOG2  6       /* 64 bytes */
+#define        LMEMCPY_8_PAD   .align LMEMCPY_8_LOG2
+       LMEMCPY_8_PAD
+.Lmemcpy_8:
+       and     r2, r1, #0x03
+       orr     r2, r2, r0, lsl #2
+       ands    r2, r2, #0x0f
+       sub     r3, pc, #0x14
+       addne   pc, r3, r2, lsl #LMEMCPY_8_LOG2
+
+/*
+ * 0000: dst is 32-bit aligned, src is 32-bit aligned
+ */
+       ldr     r2, [r1]
+       ldr     r3, [r1, #0x04]
+       str     r2, [r0]
+       str     r3, [r0, #0x04]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 0001: dst is 32-bit aligned, src is 8-bit aligned
+ */
+       ldr     r3, [r1, #-1]           /* BE:r3 = x012  LE:r3 = 210x */
+       ldr     r2, [r1, #0x03]         /* BE:r2 = 3456  LE:r2 = 6543 */
+       ldrb    r1, [r1, #0x07]         /* r1 = ...7 */
+#ifdef __ARMEB__
+       mov     r3, r3, lsl #8          /* r3 = 012. */
+       orr     r3, r3, r2, lsr #24     /* r3 = 0123 */
+       orr     r2, r1, r2, lsl #8      /* r2 = 4567 */
+#else
+       mov     r3, r3, lsr #8          /* r3 = .210 */
+       orr     r3, r3, r2, lsl #24     /* r3 = 3210 */
+       mov     r1, r1, lsl #24         /* r1 = 7... */
+       orr     r2, r1, r2, lsr #8      /* r2 = 7654 */
+#endif
+       str     r3, [r0]
+       str     r2, [r0, #0x04]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 0010: dst is 32-bit aligned, src is 16-bit aligned
+ */
+       ldrh    r2, [r1]                /* BE:r2 = ..01  LE:r2 = ..10 */
+       ldr     r3, [r1, #0x02]         /* BE:r3 = 2345  LE:r3 = 5432 */
+       ldrh    r1, [r1, #0x06]         /* BE:r1 = ..67  LE:r1 = ..76 */
+#ifdef __ARMEB__
+       mov     r2, r2, lsl #16         /* r2 = 01.. */
+       orr     r2, r2, r3, lsr #16     /* r2 = 0123 */
+       orr     r3, r1, r3, lsl #16     /* r3 = 4567 */
+#else
+       orr     r2, r2, r3, lsl #16     /* r2 = 3210 */
+       mov     r3, r3, lsr #16         /* r3 = ..54 */
+       orr     r3, r3, r1, lsl #16     /* r3 = 7654 */
+#endif
+       str     r2, [r0]
+       str     r3, [r0, #0x04]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 0011: dst is 32-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r3, [r1]                /* r3 = ...0 */
+       ldr     r2, [r1, #0x01]         /* BE:r2 = 1234  LE:r2 = 4321 */
+       ldr     r1, [r1, #0x05]         /* BE:r1 = 567x  LE:r1 = x765 */
+#ifdef __ARMEB__
+       mov     r3, r3, lsl #24         /* r3 = 0... */
+       orr     r3, r3, r2, lsr #8      /* r3 = 0123 */
+       mov     r2, r2, lsl #24         /* r2 = 4... */
+       orr     r2, r2, r1, lsr #8      /* r2 = 4567 */
+#else
+       orr     r3, r3, r2, lsl #8      /* r3 = 3210 */
+       mov     r2, r2, lsr #24         /* r2 = ...4 */
+       orr     r2, r2, r1, lsl #8      /* r2 = 7654 */
+#endif
+       str     r3, [r0]
+       str     r2, [r0, #0x04]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 0100: dst is 8-bit aligned, src is 32-bit aligned
+ */
+       ldr     r3, [r1]                /* BE:r3 = 0123  LE:r3 = 3210 */
+       ldr     r2, [r1, #0x04]         /* BE:r2 = 4567  LE:r2 = 7654 */
+#ifdef __ARMEB__
+       mov     r1, r3, lsr #24         /* r1 = ...0 */
+       strb    r1, [r0]
+       mov     r1, r3, lsr #8          /* r1 = .012 */
+       strb    r2, [r0, #0x07]
+       mov     r3, r3, lsl #24         /* r3 = 3... */
+       orr     r3, r3, r2, lsr #8      /* r3 = 3456 */
+#else
+       strb    r3, [r0]
+       mov     r1, r2, lsr #24         /* r1 = ...7 */
+       strb    r1, [r0, #0x07]
+       mov     r1, r3, lsr #8          /* r1 = .321 */
+       mov     r3, r3, lsr #24         /* r3 = ...3 */
+       orr     r3, r3, r2, lsl #8      /* r3 = 6543 */
+#endif
+       strh    r1, [r0, #0x01]
+       str     r3, [r0, #0x03]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 0101: dst is 8-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r2, [r1]
+       ldrh    r3, [r1, #0x01]
+       ldr     ip, [r1, #0x03]
+       ldrb    r1, [r1, #0x07]
+       strb    r2, [r0]
+       strh    r3, [r0, #0x01]
+       str     ip, [r0, #0x03]
+       strb    r1, [r0, #0x07]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 0110: dst is 8-bit aligned, src is 16-bit aligned
+ */
+       ldrh    r2, [r1]                /* BE:r2 = ..01  LE:r2 = ..10 */
+       ldr     r3, [r1, #0x02]         /* BE:r3 = 2345  LE:r3 = 5432 */
+       ldrh    r1, [r1, #0x06]         /* BE:r1 = ..67  LE:r1 = ..76 */
+#ifdef __ARMEB__
+       mov     ip, r2, lsr #8          /* ip = ...0 */
+       strb    ip, [r0]
+       mov     ip, r2, lsl #8          /* ip = .01. */
+       orr     ip, ip, r3, lsr #24     /* ip = .012 */
+       strb    r1, [r0, #0x07]
+       mov     r3, r3, lsl #8          /* r3 = 345. */
+       orr     r3, r3, r1, lsr #8      /* r3 = 3456 */
+#else
+       strb    r2, [r0]                /* 0 */
+       mov     ip, r1, lsr #8          /* ip = ...7 */
+       strb    ip, [r0, #0x07]         /* 7 */
+       mov     ip, r2, lsr #8          /* ip = ...1 */
+       orr     ip, ip, r3, lsl #8      /* ip = 4321 */
+       mov     r3, r3, lsr #8          /* r3 = .543 */
+       orr     r3, r3, r1, lsl #24     /* r3 = 6543 */
+#endif
+       strh    ip, [r0, #0x01]
+       str     r3, [r0, #0x03]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 0111: dst is 8-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r3, [r1]                /* r3 = ...0 */
+       ldr     ip, [r1, #0x01]         /* BE:ip = 1234  LE:ip = 4321 */
+       ldrh    r2, [r1, #0x05]         /* BE:r2 = ..56  LE:r2 = ..65 */
+       ldrb    r1, [r1, #0x07]         /* r1 = ...7 */
+       strb    r3, [r0]
+       mov     r3, ip, lsr #16         /* BE:r3 = ..12  LE:r3 = ..43 */
+#ifdef __ARMEB__
+       strh    r3, [r0, #0x01]
+       orr     r2, r2, ip, lsl #16     /* r2 = 3456 */
+#else
+       strh    ip, [r0, #0x01]
+       orr     r2, r3, r2, lsl #16     /* r2 = 6543 */
+#endif
+       str     r2, [r0, #0x03]
+       strb    r1, [r0, #0x07]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 1000: dst is 16-bit aligned, src is 32-bit aligned
+ */
+       ldr     r2, [r1]                /* BE:r2 = 0123  LE:r2 = 3210 */
+       ldr     r3, [r1, #0x04]         /* BE:r3 = 4567  LE:r3 = 7654 */
+       mov     r1, r2, lsr #16         /* BE:r1 = ..01  LE:r1 = ..32 */
+#ifdef __ARMEB__
+       strh    r1, [r0]
+       mov     r1, r3, lsr #16         /* r1 = ..45 */
+       orr     r2, r1 ,r2, lsl #16     /* r2 = 2345 */
+#else
+       strh    r2, [r0]
+       orr     r2, r1, r3, lsl #16     /* r2 = 5432 */
+       mov     r3, r3, lsr #16         /* r3 = ..76 */
+#endif
+       str     r2, [r0, #0x02]
+       strh    r3, [r0, #0x06]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 1001: dst is 16-bit aligned, src is 8-bit aligned
+ */
+       ldr     r2, [r1, #-1]           /* BE:r2 = x012  LE:r2 = 210x */
+       ldr     r3, [r1, #0x03]         /* BE:r3 = 3456  LE:r3 = 6543 */
+       ldrb    ip, [r1, #0x07]         /* ip = ...7 */
+       mov     r1, r2, lsr #8          /* BE:r1 = .x01  LE:r1 = .210 */
+       strh    r1, [r0]
+#ifdef __ARMEB__
+       mov     r1, r2, lsl #24         /* r1 = 2... */
+       orr     r1, r1, r3, lsr #8      /* r1 = 2345 */
+       orr     r3, ip, r3, lsl #8      /* r3 = 4567 */
+#else
+       mov     r1, r2, lsr #24         /* r1 = ...2 */
+       orr     r1, r1, r3, lsl #8      /* r1 = 5432 */
+       mov     r3, r3, lsr #24         /* r3 = ...6 */
+       orr     r3, r3, ip, lsl #8      /* r3 = ..76 */
+#endif
+       str     r1, [r0, #0x02]
+       strh    r3, [r0, #0x06]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 1010: dst is 16-bit aligned, src is 16-bit aligned
+ */
+       ldrh    r2, [r1]
+       ldr     ip, [r1, #0x02]
+       ldrh    r3, [r1, #0x06]
+       strh    r2, [r0]
+       str     ip, [r0, #0x02]
+       strh    r3, [r0, #0x06]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 1011: dst is 16-bit aligned, src is 8-bit aligned
+ */
+       ldr     r3, [r1, #0x05]         /* BE:r3 = 567x  LE:r3 = x765 */
+       ldr     r2, [r1, #0x01]         /* BE:r2 = 1234  LE:r2 = 4321 */
+       ldrb    ip, [r1]                /* ip = ...0 */
+       mov     r1, r3, lsr #8          /* BE:r1 = .567  LE:r1 = .x76 */
+       strh    r1, [r0, #0x06]
+#ifdef __ARMEB__
+       mov     r3, r3, lsr #24         /* r3 = ...5 */
+       orr     r3, r3, r2, lsl #8      /* r3 = 2345 */
+       mov     r2, r2, lsr #24         /* r2 = ...1 */
+       orr     r2, r2, ip, lsl #8      /* r2 = ..01 */
+#else
+       mov     r3, r3, lsl #24         /* r3 = 5... */
+       orr     r3, r3, r2, lsr #8      /* r3 = 5432 */
+       orr     r2, ip, r2, lsl #8      /* r2 = 3210 */
+#endif
+       str     r3, [r0, #0x02]
+       strh    r2, [r0]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 1100: dst is 8-bit aligned, src is 32-bit aligned
+ */
+       ldr     r3, [r1, #0x04]         /* BE:r3 = 4567  LE:r3 = 7654 */
+       ldr     r2, [r1]                /* BE:r2 = 0123  LE:r2 = 3210 */
+       mov     r1, r3, lsr #8          /* BE:r1 = .456  LE:r1 = .765 */
+       strh    r1, [r0, #0x05]
+#ifdef __ARMEB__
+       strb    r3, [r0, #0x07]
+       mov     r1, r2, lsr #24         /* r1 = ...0 */
+       strb    r1, [r0]
+       mov     r2, r2, lsl #8          /* r2 = 123. */
+       orr     r2, r2, r3, lsr #24     /* r2 = 1234 */
+       str     r2, [r0, #0x01]
+#else
+       strb    r2, [r0]
+       mov     r1, r3, lsr #24         /* r1 = ...7 */
+       strb    r1, [r0, #0x07]
+       mov     r2, r2, lsr #8          /* r2 = .321 */
+       orr     r2, r2, r3, lsl #24     /* r2 = 4321 */
+       str     r2, [r0, #0x01]
+#endif
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 1101: dst is 8-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r3, [r1]                /* r3 = ...0 */
+       ldrh    r2, [r1, #0x01]         /* BE:r2 = ..12  LE:r2 = ..21 */
+       ldr     ip, [r1, #0x03]         /* BE:ip = 3456  LE:ip = 6543 */
+       ldrb    r1, [r1, #0x07]         /* r1 = ...7 */
+       strb    r3, [r0]
+       mov     r3, ip, lsr #16         /* BE:r3 = ..34  LE:r3 = ..65 */
+#ifdef __ARMEB__
+       strh    ip, [r0, #0x05]
+       orr     r2, r3, r2, lsl #16     /* r2 = 1234 */
+#else
+       strh    r3, [r0, #0x05]
+       orr     r2, r2, ip, lsl #16     /* r2 = 4321 */
+#endif
+       str     r2, [r0, #0x01]
+       strb    r1, [r0, #0x07]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 1110: dst is 8-bit aligned, src is 16-bit aligned
+ */
+       ldrh    r2, [r1]                /* BE:r2 = ..01  LE:r2 = ..10 */
+       ldr     r3, [r1, #0x02]         /* BE:r3 = 2345  LE:r3 = 5432 */
+       ldrh    r1, [r1, #0x06]         /* BE:r1 = ..67  LE:r1 = ..76 */
+#ifdef __ARMEB__
+       mov     ip, r2, lsr #8          /* ip = ...0 */
+       strb    ip, [r0]
+       mov     ip, r2, lsl #24         /* ip = 1... */
+       orr     ip, ip, r3, lsr #8      /* ip = 1234 */
+       strb    r1, [r0, #0x07]
+       mov     r1, r1, lsr #8          /* r1 = ...6 */
+       orr     r1, r1, r3, lsl #8      /* r1 = 3456 */
+#else
+       strb    r2, [r0]
+       mov     ip, r2, lsr #8          /* ip = ...1 */
+       orr     ip, ip, r3, lsl #8      /* ip = 4321 */
+       mov     r2, r1, lsr #8          /* r2 = ...7 */
+       strb    r2, [r0, #0x07]
+       mov     r1, r1, lsl #8          /* r1 = .76. */
+       orr     r1, r1, r3, lsr #24     /* r1 = .765 */
+#endif
+       str     ip, [r0, #0x01]
+       strh    r1, [r0, #0x05]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/*
+ * 1111: dst is 8-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r2, [r1]
+       ldr     ip, [r1, #0x01]
+       ldrh    r3, [r1, #0x05]
+       ldrb    r1, [r1, #0x07]
+       strb    r2, [r0]
+       str     ip, [r0, #0x01]
+       strh    r3, [r0, #0x05]
+       strb    r1, [r0, #0x07]
+       bx      lr
+       LMEMCPY_8_PAD
+
+/******************************************************************************
+ * Special case for 12 byte copies
+ */
+#define        LMEMCPY_C_LOG2  7       /* 128 bytes */
+#define        LMEMCPY_C_PAD   .align LMEMCPY_C_LOG2
+       LMEMCPY_C_PAD
+.Lmemcpy_c:
+       and     r2, r1, #0x03
+       orr     r2, r2, r0, lsl #2
+       ands    r2, r2, #0x0f
+       sub     r3, pc, #0x14
+       addne   pc, r3, r2, lsl #LMEMCPY_C_LOG2
+
+/*
+ * 0000: dst is 32-bit aligned, src is 32-bit aligned
+ */
+       ldr     r2, [r1]
+       ldr     r3, [r1, #0x04]
+       ldr     r1, [r1, #0x08]
+       str     r2, [r0]
+       str     r3, [r0, #0x04]
+       str     r1, [r0, #0x08]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 0001: dst is 32-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r2, [r1, #0xb]          /* r2 = ...B */
+       ldr     ip, [r1, #0x07]         /* BE:ip = 789A  LE:ip = A987 */
+       ldr     r3, [r1, #0x03]         /* BE:r3 = 3456  LE:r3 = 6543 */
+       ldr     r1, [r1, #-1]           /* BE:r1 = x012  LE:r1 = 210x */
+#ifdef __ARMEB__
+       orr     r2, r2, ip, lsl #8      /* r2 = 89AB */
+       str     r2, [r0, #0x08]
+       mov     r2, ip, lsr #24         /* r2 = ...7 */
+       orr     r2, r2, r3, lsl #8      /* r2 = 4567 */
+       mov     r1, r1, lsl #8          /* r1 = 012. */
+       orr     r1, r1, r3, lsr #24     /* r1 = 0123 */
+#else
+       mov     r2, r2, lsl #24         /* r2 = B... */
+       orr     r2, r2, ip, lsr #8      /* r2 = BA98 */
+       str     r2, [r0, #0x08]
+       mov     r2, ip, lsl #24         /* r2 = 7... */
+       orr     r2, r2, r3, lsr #8      /* r2 = 7654 */
+       mov     r1, r1, lsr #8          /* r1 = .210 */
+       orr     r1, r1, r3, lsl #24     /* r1 = 3210 */
+#endif
+       str     r2, [r0, #0x04]
+       str     r1, [r0]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 0010: dst is 32-bit aligned, src is 16-bit aligned
+ */
+       ldrh    r2, [r1]                /* BE:r2 = ..01  LE:r2 = ..10 */
+       ldr     r3, [r1, #0x02]         /* BE:r3 = 2345  LE:r3 = 5432 */
+       ldr     ip, [r1, #0x06]         /* BE:ip = 6789  LE:ip = 9876 */
+       ldrh    r1, [r1, #0x0a]         /* BE:r1 = ..AB  LE:r1 = ..BA */
+#ifdef __ARMEB__
+       mov     r2, r2, lsl #16         /* r2 = 01.. */
+       orr     r2, r2, r3, lsr #16     /* r2 = 0123 */
+       str     r2, [r0]
+       mov     r3, r3, lsl #16         /* r3 = 45.. */
+       orr     r3, r3, ip, lsr #16     /* r3 = 4567 */
+       orr     r1, r1, ip, lsl #16     /* r1 = 89AB */
+#else
+       orr     r2, r2, r3, lsl #16     /* r2 = 3210 */
+       str     r2, [r0]
+       mov     r3, r3, lsr #16         /* r3 = ..54 */
+       orr     r3, r3, ip, lsl #16     /* r3 = 7654 */
+       mov     r1, r1, lsl #16         /* r1 = BA.. */
+       orr     r1, r1, ip, lsr #16     /* r1 = BA98 */
+#endif
+       str     r3, [r0, #0x04]
+       str     r1, [r0, #0x08]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 0011: dst is 32-bit aligned, src is 8-bit aligned
+ */
+       ldrb    r2, [r1]                /* r2 = ...0 */
+       ldr     r3, [r1, #0x01]         /* BE:r3 = 1234  LE:r3 = 4321 */
+       ldr     ip, [r1, #0x05]         /* BE:ip = 5678  LE:ip = 8765 */
+       ldr     r1, [r1, #0x09]         /* BE:r1 = 9ABx  LE:r1 = xBA9 */
+#ifdef __ARMEB__
+       mov     r2, r2, lsl #24         /* r2 = 0... */
+       orr     r2, r2, r3, lsr #8      /* r2 = 0123 */
+       str     r2, [r0]
+       mov     r3, r3, lsl #24         /* r3 = 4... */
+       orr     r3, r3, ip, lsr #8      /* r3 = 4567 */
+       mov     r1, r1, lsr #8          /* r1 = .9AB */
+       orr     r1, r1, ip, lsl #24     /* r1 = 89AB */
+#else
+       orr     r2, r2, r3, lsl #8      /* r2 = 3210 */
+       str     r2, [r0]
+       mov     r3, r3, lsr #24         /* r3 = ...4 */
+       orr     r3, r3, ip, lsl #8      /* r3 = 7654 */
+       mov     r1, r1, lsl #8          /* r1 = BA9. */
+       orr     r1, r1, ip, lsr #24     /* r1 = BA98 */
+#endif
+       str     r3, [r0, #0x04]
+       str     r1, [r0, #0x08]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 0100: dst is 8-bit aligned (byte 1), src is 32-bit aligned
+ */
+       ldr     r2, [r1]                /* BE:r2 = 0123  LE:r2 = 3210 */
+       ldr     r3, [r1, #0x04]         /* BE:r3 = 4567  LE:r3 = 7654 */
+       ldr     ip, [r1, #0x08]         /* BE:ip = 89AB  LE:ip = BA98 */
+       mov     r1, r2, lsr #8          /* BE:r1 = .012  LE:r1 = .321 */
+       strh    r1, [r0, #0x01]
+#ifdef __ARMEB__
+       mov     r1, r2, lsr #24         /* r1 = ...0 */
+       strb    r1, [r0]
+       mov     r1, r2, lsl #24         /* r1 = 3... */
+       orr     r2, r1, r3, lsr #8      /* r1 = 3456 */
+       mov     r1, r3, lsl #24         /* r1 = 7... */
+       orr     r1, r1, ip, lsr #8      /* r1 = 789A */
+#else
+       strb    r2, [r0]
+       mov     r1, r2, lsr #24         /* r1 = ...3 */
+       orr     r2, r1, r3, lsl #8      /* r1 = 6543 */
+       mov     r1, r3, lsr #24         /* r1 = ...7 */
+       orr     r1, r1, ip, lsl #8      /* r1 = A987 */
+       mov     ip, ip, lsr #24         /* ip = ...B */
+#endif
+       str     r2, [r0, #0x03]
+       str     r1, [r0, #0x07]
+       strb    ip, [r0, #0x0b]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 0101: dst is 8-bit aligned (byte 1), src is 8-bit aligned (byte 1)
+ */
+       ldrb    r2, [r1]
+       ldrh    r3, [r1, #0x01]
+       ldr     ip, [r1, #0x03]
+       strb    r2, [r0]
+       ldr     r2, [r1, #0x07]
+       ldrb    r1, [r1, #0x0b]
+       strh    r3, [r0, #0x01]
+       str     ip, [r0, #0x03]
+       str     r2, [r0, #0x07]
+       strb    r1, [r0, #0x0b]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 0110: dst is 8-bit aligned (byte 1), src is 16-bit aligned
+ */
+       ldrh    r2, [r1]                /* BE:r2 = ..01  LE:r2 = ..10 */
+       ldr     r3, [r1, #0x02]         /* BE:r3 = 2345  LE:r3 = 5432 */
+       ldr     ip, [r1, #0x06]         /* BE:ip = 6789  LE:ip = 9876 */
+       ldrh    r1, [r1, #0x0a]         /* BE:r1 = ..AB  LE:r1 = ..BA */
+#ifdef __ARMEB__
+       mov     r2, r2, ror #8          /* r2 = 1..0 */
+       strb    r2, [r0]
+       mov     r2, r2, lsr #16         /* r2 = ..1. */
+       orr     r2, r2, r3, lsr #24     /* r2 = ..12 */
+       strh    r2, [r0, #0x01]
+       mov     r2, r3, lsl #8          /* r2 = 345. */
+       orr     r3, r2, ip, lsr #24     /* r3 = 3456 */
+       mov     r2, ip, lsl #8          /* r2 = 789. */
+       orr     r2, r2, r1, lsr #8      /* r2 = 789A */
+#else
+       strb    r2, [r0]
+       mov     r2, r2, lsr #8          /* r2 = ...1 */
+       orr     r2, r2, r3, lsl #8      /* r2 = 4321 */
+       strh    r2, [r0, #0x01]
+       mov     r2, r3, lsr #8          /* r2 = .543 */
+       orr     r3, r2, ip, lsl #24     /* r3 = 6543 */
+       mov     r2, ip, lsr #8          /* r2 = .987 */
+       orr     r2, r2, r1, lsl #24     /* r2 = A987 */
+       mov     r1, r1, lsr #8          /* r1 = ...B */
+#endif
+       str     r3, [r0, #0x03]
+       str     r2, [r0, #0x07]
+       strb    r1, [r0, #0x0b]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 0111: dst is 8-bit aligned (byte 1), src is 8-bit aligned (byte 3)
+ */
+       ldrb    r2, [r1]
+       ldr     r3, [r1, #0x01]         /* BE:r3 = 1234  LE:r3 = 4321 */
+       ldr     ip, [r1, #0x05]         /* BE:ip = 5678  LE:ip = 8765 */
+       ldr     r1, [r1, #0x09]         /* BE:r1 = 9ABx  LE:r1 = xBA9 */
+       strb    r2, [r0]
+#ifdef __ARMEB__
+       mov     r2, r3, lsr #16         /* r2 = ..12 */
+       strh    r2, [r0, #0x01]
+       mov     r3, r3, lsl #16         /* r3 = 34.. */
+       orr     r3, r3, ip, lsr #16     /* r3 = 3456 */
+       mov     ip, ip, lsl #16         /* ip = 78.. */
+       orr     ip, ip, r1, lsr #16     /* ip = 789A */
+       mov     r1, r1, lsr #8          /* r1 = .9AB */
+#else
+       strh    r3, [r0, #0x01]
+       mov     r3, r3, lsr #16         /* r3 = ..43 */
+       orr     r3, r3, ip, lsl #16     /* r3 = 6543 */
+       mov     ip, ip, lsr #16         /* ip = ..87 */
+       orr     ip, ip, r1, lsl #16     /* ip = A987 */
+       mov     r1, r1, lsr #16         /* r1 = ..xB */
+#endif
+       str     r3, [r0, #0x03]
+       str     ip, [r0, #0x07]
+       strb    r1, [r0, #0x0b]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 1000: dst is 16-bit aligned, src is 32-bit aligned
+ */
+       ldr     ip, [r1]                /* BE:ip = 0123  LE:ip = 3210 */
+       ldr     r3, [r1, #0x04]         /* BE:r3 = 4567  LE:r3 = 7654 */
+       ldr     r2, [r1, #0x08]         /* BE:r2 = 89AB  LE:r2 = BA98 */
+       mov     r1, ip, lsr #16         /* BE:r1 = ..01  LE:r1 = ..32 */
+#ifdef __ARMEB__
+       strh    r1, [r0]
+       mov     r1, ip, lsl #16         /* r1 = 23.. */
+       orr     r1, r1, r3, lsr #16     /* r1 = 2345 */
+       mov     r3, r3, lsl #16         /* r3 = 67.. */
+       orr     r3, r3, r2, lsr #16     /* r3 = 6789 */
+#else
+       strh    ip, [r0]
+       orr     r1, r1, r3, lsl #16     /* r1 = 5432 */
+       mov     r3, r3, lsr #16         /* r3 = ..76 */
+       orr     r3, r3, r2, lsl #16     /* r3 = 9876 */
+       mov     r2, r2, lsr #16         /* r2 = ..BA */
+#endif
+       str     r1, [r0, #0x02]
+       str     r3, [r0, #0x06]
+       strh    r2, [r0, #0x0a]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 1001: dst is 16-bit aligned, src is 8-bit aligned (byte 1)
+ */
+       ldr     r2, [r1, #-1]           /* BE:r2 = x012  LE:r2 = 210x */
+       ldr     r3, [r1, #0x03]         /* BE:r3 = 3456  LE:r3 = 6543 */
+       mov     ip, r2, lsr #8          /* BE:ip = .x01  LE:ip = .210 */
+       strh    ip, [r0]
+       ldr     ip, [r1, #0x07]         /* BE:ip = 789A  LE:ip = A987 */
+       ldrb    r1, [r1, #0x0b]         /* r1 = ...B */
+#ifdef __ARMEB__
+       mov     r2, r2, lsl #24         /* r2 = 2... */
+       orr     r2, r2, r3, lsr #8      /* r2 = 2345 */
+       mov     r3, r3, lsl #24         /* r3 = 6... */
+       orr     r3, r3, ip, lsr #8      /* r3 = 6789 */
+       orr     r1, r1, ip, lsl #8      /* r1 = 89AB */
+#else
+       mov     r2, r2, lsr #24         /* r2 = ...2 */
+       orr     r2, r2, r3, lsl #8      /* r2 = 5432 */
+       mov     r3, r3, lsr #24         /* r3 = ...6 */
+       orr     r3, r3, ip, lsl #8      /* r3 = 9876 */
+       mov     r1, r1, lsl #8          /* r1 = ..B. */
+       orr     r1, r1, ip, lsr #24     /* r1 = ..BA */
+#endif
+       str     r2, [r0, #0x02]
+       str     r3, [r0, #0x06]
+       strh    r1, [r0, #0x0a]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 1010: dst is 16-bit aligned, src is 16-bit aligned
+ */
+       ldrh    r2, [r1]
+       ldr     r3, [r1, #0x02]
+       ldr     ip, [r1, #0x06]
+       ldrh    r1, [r1, #0x0a]
+       strh    r2, [r0]
+       str     r3, [r0, #0x02]
+       str     ip, [r0, #0x06]
+       strh    r1, [r0, #0x0a]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 1011: dst is 16-bit aligned, src is 8-bit aligned (byte 3)
+ */
+       ldr     r2, [r1, #0x09]         /* BE:r2 = 9ABx  LE:r2 = xBA9 */
+       ldr     r3, [r1, #0x05]         /* BE:r3 = 5678  LE:r3 = 8765 */
+       mov     ip, r2, lsr #8          /* BE:ip = .9AB  LE:ip = .xBA */
+       strh    ip, [r0, #0x0a]
+       ldr     ip, [r1, #0x01]         /* BE:ip = 1234  LE:ip = 4321 */
+       ldrb    r1, [r1]                /* r1 = ...0 */
+#ifdef __ARMEB__
+       mov     r2, r2, lsr #24         /* r2 = ...9 */
+       orr     r2, r2, r3, lsl #8      /* r2 = 6789 */
+       mov     r3, r3, lsr #24         /* r3 = ...5 */
+       orr     r3, r3, ip, lsl #8      /* r3 = 2345 */
+       mov     r1, r1, lsl #8          /* r1 = ..0. */
+       orr     r1, r1, ip, lsr #24     /* r1 = ..01 */
+#else
+       mov     r2, r2, lsl #24         /* r2 = 9... */
+       orr     r2, r2, r3, lsr #8      /* r2 = 9876 */
+       mov     r3, r3, lsl #24         /* r3 = 5... */
+       orr     r3, r3, ip, lsr #8      /* r3 = 5432 */
+       orr     r1, r1, ip, lsl #8      /* r1 = 3210 */
+#endif
+       str     r2, [r0, #0x06]
+       str     r3, [r0, #0x02]
+       strh    r1, [r0]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 1100: dst is 8-bit aligned (byte 3), src is 32-bit aligned
+ */
+       ldr     r2, [r1]                /* BE:r2 = 0123  LE:r2 = 3210 */
+       ldr     ip, [r1, #0x04]         /* BE:ip = 4567  LE:ip = 7654 */
+       ldr     r1, [r1, #0x08]         /* BE:r1 = 89AB  LE:r1 = BA98 */
+#ifdef __ARMEB__
+       mov     r3, r2, lsr #24         /* r3 = ...0 */
+       strb    r3, [r0]
+       mov     r2, r2, lsl #8          /* r2 = 123. */
+       orr     r2, r2, ip, lsr #24     /* r2 = 1234 */
+       str     r2, [r0, #0x01]
+       mov     r2, ip, lsl #8          /* r2 = 567. */
+       orr     r2, r2, r1, lsr #24     /* r2 = 5678 */
+       str     r2, [r0, #0x05]
+       mov     r2, r1, lsr #8          /* r2 = ..9A */
+       strh    r2, [r0, #0x09]
+       strb    r1, [r0, #0x0b]
+#else
+       strb    r2, [r0]
+       mov     r3, r2, lsr #8          /* r3 = .321 */
+       orr     r3, r3, ip, lsl #24     /* r3 = 4321 */
+       str     r3, [r0, #0x01]
+       mov     r3, ip, lsr #8          /* r3 = .765 */
+       orr     r3, r3, r1, lsl #24     /* r3 = 8765 */
+       str     r3, [r0, #0x05]
+       mov     r1, r1, lsr #8          /* r1 = .BA9 */
+       strh    r1, [r0, #0x09]
+       mov     r1, r1, lsr #16         /* r1 = ...B */
+       strb    r1, [r0, #0x0b]
+#endif
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 1101: dst is 8-bit aligned (byte 3), src is 8-bit aligned (byte 1)
+ */
+       ldrb    r2, [r1, #0x0b]         /* r2 = ...B */
+       ldr     r3, [r1, #0x07]         /* BE:r3 = 789A  LE:r3 = A987 */
+       ldr     ip, [r1, #0x03]         /* BE:ip = 3456  LE:ip = 6543 */
+       ldr     r1, [r1, #-1]           /* BE:r1 = x012  LE:r1 = 210x */
+       strb    r2, [r0, #0x0b]
+#ifdef __ARMEB__
+       strh    r3, [r0, #0x09]
+       mov     r3, r3, lsr #16         /* r3 = ..78 */
+       orr     r3, r3, ip, lsl #16     /* r3 = 5678 */
+       mov     ip, ip, lsr #16         /* ip = ..34 */
+       orr     ip, ip, r1, lsl #16     /* ip = 1234 */
+       mov     r1, r1, lsr #16         /* r1 = ..x0 */
+#else
+       mov     r2, r3, lsr #16         /* r2 = ..A9 */
+       strh    r2, [r0, #0x09]
+       mov     r3, r3, lsl #16         /* r3 = 87.. */
+       orr     r3, r3, ip, lsr #16     /* r3 = 8765 */
+       mov     ip, ip, lsl #16         /* ip = 43.. */
+       orr     ip, ip, r1, lsr #16     /* ip = 4321 */
+       mov     r1, r1, lsr #8          /* r1 = .210 */
+#endif
+       str     r3, [r0, #0x05]
+       str     ip, [r0, #0x01]
+       strb    r1, [r0]
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 1110: dst is 8-bit aligned (byte 3), src is 16-bit aligned
+ */
+#ifdef __ARMEB__
+       ldrh    r2, [r1, #0x0a]         /* r2 = ..AB */
+       ldr     ip, [r1, #0x06]         /* ip = 6789 */
+       ldr     r3, [r1, #0x02]         /* r3 = 2345 */
+       ldrh    r1, [r1]                /* r1 = ..01 */
+       strb    r2, [r0, #0x0b]
+       mov     r2, r2, lsr #8          /* r2 = ...A */
+       orr     r2, r2, ip, lsl #8      /* r2 = 789A */
+       mov     ip, ip, lsr #8          /* ip = .678 */
+       orr     ip, ip, r3, lsl #24     /* ip = 5678 */
+       mov     r3, r3, lsr #8          /* r3 = .234 */
+       orr     r3, r3, r1, lsl #24     /* r3 = 1234 */
+       mov     r1, r1, lsr #8          /* r1 = ...0 */
+       strb    r1, [r0]
+       str     r3, [r0, #0x01]
+       str     ip, [r0, #0x05]
+       strh    r2, [r0, #0x09]
+#else
+       ldrh    r2, [r1]                /* r2 = ..10 */
+       ldr     r3, [r1, #0x02]         /* r3 = 5432 */
+       ldr     ip, [r1, #0x06]         /* ip = 9876 */
+       ldrh    r1, [r1, #0x0a]         /* r1 = ..BA */
+       strb    r2, [r0]
+       mov     r2, r2, lsr #8          /* r2 = ...1 */
+       orr     r2, r2, r3, lsl #8      /* r2 = 4321 */
+       mov     r3, r3, lsr #24         /* r3 = ...5 */
+       orr     r3, r3, ip, lsl #8      /* r3 = 8765 */
+       mov     ip, ip, lsr #24         /* ip = ...9 */
+       orr     ip, ip, r1, lsl #8      /* ip = .BA9 */
+       mov     r1, r1, lsr #8          /* r1 = ...B */
+       str     r2, [r0, #0x01]
+       str     r3, [r0, #0x05]
+       strh    ip, [r0, #0x09]
+       strb    r1, [r0, #0x0b]
+#endif
+       bx      lr
+       LMEMCPY_C_PAD
+
+/*
+ * 1111: dst is 8-bit aligned (byte 3), src is 8-bit aligned (byte 3)
+ */
+       ldrb    r2, [r1]
+       ldr     r3, [r1, #0x01]
+       ldr     ip, [r1, #0x05]
+       strb    r2, [r0]
+       ldrh    r2, [r1, #0x09]
+       ldrb    r1, [r1, #0x0b]
+       str     r3, [r0, #0x01]
+       str     ip, [r0, #0x05]
+       strh    r2, [r0, #0x09]
+       strb    r1, [r0, #0x0b]
+       bx      lr
+#endif /* !_STANDALONE */
diff --git a/common/lib/libc/arch/arm/string/memmove.S b/common/lib/libc/arch/arm/string/memmove.S
new file mode 100644 (file)
index 0000000..606d705
--- /dev/null
@@ -0,0 +1,581 @@
+/*     $NetBSD: memmove.S,v 1.3 2008/04/28 20:22:52 martin Exp $       */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Neil A. Carson and Mark Brinicombe
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#ifndef _BCOPY
+/* LINTSTUB: Func: void *memmove(void *, const void *, size_t) */
+ENTRY(memmove)
+#else
+/* bcopy = memcpy/memmove with arguments reversed. */
+/* LINTSTUB: Func: void bcopy(void *, void *, size_t) */
+ENTRY(bcopy)
+       /* switch the source and destination registers */
+       eor     r0, r1, r0
+       eor     r1, r0, r1
+       eor     r0, r1, r0
+#endif
+       /* Do the buffers overlap? */
+       cmp     r0, r1
+       RETc(eq)                /* Bail now if src/dst are the same */
+       subhs   r3, r0, r1      /* if (dst > src) r3 = dst - src */
+       sublo   r3, r1, r0      /* if (src > dst) r3 = src - dst */
+       cmp     r3, r2          /* if (r3 >= len) we have an overlap */
+       bhs     PIC_SYM(_C_LABEL(memcpy), PLT)
+
+       /* Determine copy direction */
+       cmp     r1, r0
+       bcc     .Lmemmove_backwards
+
+       moveq   r0, #0                  /* Quick abort for len=0 */
+       RETc(eq)
+
+       stmdb   sp!, {r0, lr}           /* memmove() returns dest addr */
+       subs    r2, r2, #4
+       blt     .Lmemmove_fl4           /* less than 4 bytes */
+       ands    r12, r0, #3
+       bne     .Lmemmove_fdestul       /* oh unaligned destination addr */
+       ands    r12, r1, #3
+       bne     .Lmemmove_fsrcul                /* oh unaligned source addr */
+
+.Lmemmove_ft8:
+       /* We have aligned source and destination */
+       subs    r2, r2, #8
+       blt     .Lmemmove_fl12          /* less than 12 bytes (4 from above) */
+       subs    r2, r2, #0x14
+       blt     .Lmemmove_fl32          /* less than 32 bytes (12 from above) */
+       stmdb   sp!, {r4}               /* borrow r4 */
+
+       /* blat 32 bytes at a time */
+       /* XXX for really big copies perhaps we should use more registers */
+.Lmemmove_floop32:
+       ldmia   r1!, {r3, r4, r12, lr}
+       stmia   r0!, {r3, r4, r12, lr}
+       ldmia   r1!, {r3, r4, r12, lr}
+       stmia   r0!, {r3, r4, r12, lr}
+       subs    r2, r2, #0x20
+       bge     .Lmemmove_floop32
+
+       cmn     r2, #0x10
+       ldmgeia r1!, {r3, r4, r12, lr}  /* blat a remaining 16 bytes */
+       stmgeia r0!, {r3, r4, r12, lr}
+       subge   r2, r2, #0x10
+       ldmia   sp!, {r4}               /* return r4 */
+
+.Lmemmove_fl32:
+       adds    r2, r2, #0x14
+
+       /* blat 12 bytes at a time */
+.Lmemmove_floop12:
+       ldmgeia r1!, {r3, r12, lr}
+       stmgeia r0!, {r3, r12, lr}
+       subges  r2, r2, #0x0c
+       bge     .Lmemmove_floop12
+
+.Lmemmove_fl12:
+       adds    r2, r2, #8
+       blt     .Lmemmove_fl4
+
+       subs    r2, r2, #4
+       ldrlt   r3, [r1], #4
+       strlt   r3, [r0], #4
+       ldmgeia r1!, {r3, r12}
+       stmgeia r0!, {r3, r12}
+       subge   r2, r2, #4
+
+.Lmemmove_fl4:
+       /* less than 4 bytes to go */
+       adds    r2, r2, #4
+       ldmeqia sp!, {r0, pc}           /* done */
+
+       /* copy the crud byte at a time */
+       cmp     r2, #2
+       ldrb    r3, [r1], #1
+       strb    r3, [r0], #1
+       ldrgeb  r3, [r1], #1
+       strgeb  r3, [r0], #1
+       ldrgtb  r3, [r1], #1
+       strgtb  r3, [r0], #1
+       ldmia   sp!, {r0, pc}
+
+       /* erg - unaligned destination */
+.Lmemmove_fdestul:
+       rsb     r12, r12, #4
+       cmp     r12, #2
+
+       /* align destination with byte copies */
+       ldrb    r3, [r1], #1
+       strb    r3, [r0], #1
+       ldrgeb  r3, [r1], #1
+       strgeb  r3, [r0], #1
+       ldrgtb  r3, [r1], #1
+       strgtb  r3, [r0], #1
+       subs    r2, r2, r12
+       blt     .Lmemmove_fl4           /* less the 4 bytes */
+
+       ands    r12, r1, #3
+       beq     .Lmemmove_ft8           /* we have an aligned source */
+
+       /* erg - unaligned source */
+       /* This is where it gets nasty ... */
+.Lmemmove_fsrcul:
+       bic     r1, r1, #3
+       ldr     lr, [r1], #4
+       cmp     r12, #2
+       bgt     .Lmemmove_fsrcul3
+       beq     .Lmemmove_fsrcul2
+       cmp     r2, #0x0c
+       blt     .Lmemmove_fsrcul1loop4
+       sub     r2, r2, #0x0c
+       stmdb   sp!, {r4, r5}
+
+.Lmemmove_fsrcul1loop16:
+#ifdef __ARMEB__
+       mov     r3, lr, lsl #8
+#else
+       mov     r3, lr, lsr #8
+#endif
+       ldmia   r1!, {r4, r5, r12, lr}
+#ifdef __ARMEB__
+       orr     r3, r3, r4, lsr #24
+       mov     r4, r4, lsl #8
+       orr     r4, r4, r5, lsr #24
+       mov     r5, r5, lsl #8
+       orr     r5, r5, r12, lsr #24
+       mov     r12, r12, lsl #8
+       orr     r12, r12, lr, lsr #24
+#else
+       orr     r3, r3, r4, lsl #24
+       mov     r4, r4, lsr #8
+       orr     r4, r4, r5, lsl #24
+       mov     r5, r5, lsr #8
+       orr     r5, r5, r12, lsl #24
+       mov     r12, r12, lsr #8
+       orr     r12, r12, lr, lsl #24
+#endif
+       stmia   r0!, {r3-r5, r12}
+       subs    r2, r2, #0x10
+       bge     .Lmemmove_fsrcul1loop16
+       ldmia   sp!, {r4, r5}
+       adds    r2, r2, #0x0c
+       blt     .Lmemmove_fsrcul1l4
+
+.Lmemmove_fsrcul1loop4:
+#ifdef __ARMEB__
+       mov     r12, lr, lsl #8
+#else
+       mov     r12, lr, lsr #8
+#endif
+       ldr     lr, [r1], #4
+#ifdef __ARMEB__
+       orr     r12, r12, lr, lsr #24
+#else
+       orr     r12, r12, lr, lsl #24
+#endif
+       str     r12, [r0], #4
+       subs    r2, r2, #4
+       bge     .Lmemmove_fsrcul1loop4
+
+.Lmemmove_fsrcul1l4:
+       sub     r1, r1, #3
+       b       .Lmemmove_fl4
+
+.Lmemmove_fsrcul2:
+       cmp     r2, #0x0c
+       blt     .Lmemmove_fsrcul2loop4
+       sub     r2, r2, #0x0c
+       stmdb   sp!, {r4, r5}
+
+.Lmemmove_fsrcul2loop16:
+#ifdef __ARMEB__
+       mov     r3, lr, lsl #16
+#else
+       mov     r3, lr, lsr #16
+#endif
+       ldmia   r1!, {r4, r5, r12, lr}
+#ifdef __ARMEB__
+       orr     r3, r3, r4, lsr #16
+       mov     r4, r4, lsl #16
+       orr     r4, r4, r5, lsr #16
+       mov     r5, r5, lsl #16
+       orr     r5, r5, r12, lsr #16
+       mov     r12, r12, lsl #16
+       orr     r12, r12, lr, lsr #16
+#else
+       orr     r3, r3, r4, lsl #16
+       mov     r4, r4, lsr #16
+       orr     r4, r4, r5, lsl #16
+       mov     r5, r5, lsr #16
+       orr     r5, r5, r12, lsl #16
+       mov     r12, r12, lsr #16
+       orr     r12, r12, lr, lsl #16
+#endif
+       stmia   r0!, {r3-r5, r12}
+       subs    r2, r2, #0x10
+       bge     .Lmemmove_fsrcul2loop16
+       ldmia   sp!, {r4, r5}
+       adds    r2, r2, #0x0c
+       blt     .Lmemmove_fsrcul2l4
+
+.Lmemmove_fsrcul2loop4:
+#ifdef __ARMEB__
+       mov     r12, lr, lsl #16
+#else
+       mov     r12, lr, lsr #16
+#endif
+       ldr     lr, [r1], #4
+#ifdef __ARMEB__
+       orr     r12, r12, lr, lsr #16
+#else
+       orr     r12, r12, lr, lsl #16
+#endif
+       str     r12, [r0], #4
+       subs    r2, r2, #4
+       bge     .Lmemmove_fsrcul2loop4
+
+.Lmemmove_fsrcul2l4:
+       sub     r1, r1, #2
+       b       .Lmemmove_fl4
+
+.Lmemmove_fsrcul3:
+       cmp     r2, #0x0c
+       blt     .Lmemmove_fsrcul3loop4
+       sub     r2, r2, #0x0c
+       stmdb   sp!, {r4, r5}
+
+.Lmemmove_fsrcul3loop16:
+#ifdef __ARMEB__
+       mov     r3, lr, lsl #24
+#else
+       mov     r3, lr, lsr #24
+#endif
+       ldmia   r1!, {r4, r5, r12, lr}
+#ifdef __ARMEB__
+       orr     r3, r3, r4, lsr #8
+       mov     r4, r4, lsl #24
+       orr     r4, r4, r5, lsr #8
+       mov     r5, r5, lsl #24
+       orr     r5, r5, r12, lsr #8
+       mov     r12, r12, lsl #24
+       orr     r12, r12, lr, lsr #8
+#else
+       orr     r3, r3, r4, lsl #8
+       mov     r4, r4, lsr #24
+       orr     r4, r4, r5, lsl #8
+       mov     r5, r5, lsr #24
+       orr     r5, r5, r12, lsl #8
+       mov     r12, r12, lsr #24
+       orr     r12, r12, lr, lsl #8
+#endif
+       stmia   r0!, {r3-r5, r12}
+       subs    r2, r2, #0x10
+       bge     .Lmemmove_fsrcul3loop16
+       ldmia   sp!, {r4, r5}
+       adds    r2, r2, #0x0c
+       blt     .Lmemmove_fsrcul3l4
+
+.Lmemmove_fsrcul3loop4:
+#ifdef __ARMEB__
+       mov     r12, lr, lsl #24
+#else
+       mov     r12, lr, lsr #24
+#endif
+       ldr     lr, [r1], #4
+#ifdef __ARMEB__
+       orr     r12, r12, lr, lsr #8
+#else
+       orr     r12, r12, lr, lsl #8
+#endif
+       str     r12, [r0], #4
+       subs    r2, r2, #4
+       bge     .Lmemmove_fsrcul3loop4
+
+.Lmemmove_fsrcul3l4:
+       sub     r1, r1, #1
+       b       .Lmemmove_fl4
+
+.Lmemmove_backwards:
+       add     r1, r1, r2
+       add     r0, r0, r2
+       subs    r2, r2, #4
+       blt     .Lmemmove_bl4           /* less than 4 bytes */
+       ands    r12, r0, #3
+       bne     .Lmemmove_bdestul       /* oh unaligned destination addr */
+       ands    r12, r1, #3
+       bne     .Lmemmove_bsrcul                /* oh unaligned source addr */
+
+.Lmemmove_bt8:
+       /* We have aligned source and destination */
+       subs    r2, r2, #8
+       blt     .Lmemmove_bl12          /* less than 12 bytes (4 from above) */
+       stmdb   sp!, {r4, lr}
+       subs    r2, r2, #0x14           /* less than 32 bytes (12 from above) */
+       blt     .Lmemmove_bl32
+
+       /* blat 32 bytes at a time */
+       /* XXX for really big copies perhaps we should use more registers */
+.Lmemmove_bloop32:
+       ldmdb   r1!, {r3, r4, r12, lr}
+       stmdb   r0!, {r3, r4, r12, lr}
+       ldmdb   r1!, {r3, r4, r12, lr}
+       stmdb   r0!, {r3, r4, r12, lr}
+       subs    r2, r2, #0x20
+       bge     .Lmemmove_bloop32
+
+.Lmemmove_bl32:
+       cmn     r2, #0x10
+       ldmgedb r1!, {r3, r4, r12, lr}  /* blat a remaining 16 bytes */
+       stmgedb r0!, {r3, r4, r12, lr}
+       subge   r2, r2, #0x10
+       adds    r2, r2, #0x14
+       ldmgedb r1!, {r3, r12, lr}      /* blat a remaining 12 bytes */
+       stmgedb r0!, {r3, r12, lr}
+       subge   r2, r2, #0x0c
+       ldmia   sp!, {r4, lr}
+
+.Lmemmove_bl12:
+       adds    r2, r2, #8
+       blt     .Lmemmove_bl4
+       subs    r2, r2, #4
+       ldrlt   r3, [r1, #-4]!
+       strlt   r3, [r0, #-4]!
+       ldmgedb r1!, {r3, r12}
+       stmgedb r0!, {r3, r12}
+       subge   r2, r2, #4
+
+.Lmemmove_bl4:
+       /* less than 4 bytes to go */
+       adds    r2, r2, #4
+       RETc(eq)
+
+       /* copy the crud byte at a time */
+       cmp     r2, #2
+       ldrb    r3, [r1, #-1]!
+       strb    r3, [r0, #-1]!
+       ldrgeb  r3, [r1, #-1]!
+       strgeb  r3, [r0, #-1]!
+       ldrgtb  r3, [r1, #-1]!
+       strgtb  r3, [r0, #-1]!
+       RET
+
+       /* erg - unaligned destination */
+.Lmemmove_bdestul:
+       cmp     r12, #2
+
+       /* align destination with byte copies */
+       ldrb    r3, [r1, #-1]!
+       strb    r3, [r0, #-1]!
+       ldrgeb  r3, [r1, #-1]!
+       strgeb  r3, [r0, #-1]!
+       ldrgtb  r3, [r1, #-1]!
+       strgtb  r3, [r0, #-1]!
+       subs    r2, r2, r12
+       blt     .Lmemmove_bl4           /* less than 4 bytes to go */
+       ands    r12, r1, #3
+       beq     .Lmemmove_bt8           /* we have an aligned source */
+
+       /* erg - unaligned source */
+       /* This is where it gets nasty ... */
+.Lmemmove_bsrcul:
+       bic     r1, r1, #3
+       ldr     r3, [r1, #0]
+       cmp     r12, #2
+       blt     .Lmemmove_bsrcul1
+       beq     .Lmemmove_bsrcul2
+       cmp     r2, #0x0c
+       blt     .Lmemmove_bsrcul3loop4
+       sub     r2, r2, #0x0c
+       stmdb   sp!, {r4, r5, lr}
+
+.Lmemmove_bsrcul3loop16:
+#ifdef __ARMEB__
+       mov     lr, r3, lsr #8
+#else
+       mov     lr, r3, lsl #8
+#endif
+       ldmdb   r1!, {r3-r5, r12}
+#ifdef __ARMEB__
+       orr     lr, lr, r12, lsl #24
+       mov     r12, r12, lsr #8
+       orr     r12, r12, r5, lsl #24
+       mov     r5, r5, lsr #8
+       orr     r5, r5, r4, lsl #24
+       mov     r4, r4, lsr #8
+       orr     r4, r4, r3, lsl #24
+#else
+       orr     lr, lr, r12, lsr #24
+       mov     r12, r12, lsl #8
+       orr     r12, r12, r5, lsr #24
+       mov     r5, r5, lsl #8
+       orr     r5, r5, r4, lsr #24
+       mov     r4, r4, lsl #8
+       orr     r4, r4, r3, lsr #24
+#endif
+       stmdb   r0!, {r4, r5, r12, lr}
+       subs    r2, r2, #0x10
+       bge     .Lmemmove_bsrcul3loop16
+       ldmia   sp!, {r4, r5, lr}
+       adds    r2, r2, #0x0c
+       blt     .Lmemmove_bsrcul3l4
+
+.Lmemmove_bsrcul3loop4:
+#ifdef __ARMEB__
+       mov     r12, r3, lsr #8
+#else
+       mov     r12, r3, lsl #8
+#endif
+       ldr     r3, [r1, #-4]!
+#ifdef __ARMEB__
+       orr     r12, r12, r3, lsl #24
+#else
+       orr     r12, r12, r3, lsr #24
+#endif
+       str     r12, [r0, #-4]!
+       subs    r2, r2, #4
+       bge     .Lmemmove_bsrcul3loop4
+
+.Lmemmove_bsrcul3l4:
+       add     r1, r1, #3
+       b       .Lmemmove_bl4
+
+.Lmemmove_bsrcul2:
+       cmp     r2, #0x0c
+       blt     .Lmemmove_bsrcul2loop4
+       sub     r2, r2, #0x0c
+       stmdb   sp!, {r4, r5, lr}
+
+.Lmemmove_bsrcul2loop16:
+#ifdef __ARMEB__
+       mov     lr, r3, lsr #16
+#else
+       mov     lr, r3, lsl #16
+#endif
+       ldmdb   r1!, {r3-r5, r12}
+#ifdef __ARMEB__
+       orr     lr, lr, r12, lsl #16
+       mov     r12, r12, lsr #16
+       orr     r12, r12, r5, lsl #16
+       mov     r5, r5, lsr #16
+       orr     r5, r5, r4, lsl #16
+       mov     r4, r4, lsr #16
+       orr     r4, r4, r3, lsl #16
+#else
+       orr     lr, lr, r12, lsr #16
+       mov     r12, r12, lsl #16
+       orr     r12, r12, r5, lsr #16
+       mov     r5, r5, lsl #16
+       orr     r5, r5, r4, lsr #16
+       mov     r4, r4, lsl #16
+       orr     r4, r4, r3, lsr #16
+#endif
+       stmdb   r0!, {r4, r5, r12, lr}
+       subs    r2, r2, #0x10
+       bge     .Lmemmove_bsrcul2loop16
+       ldmia   sp!, {r4, r5, lr}
+       adds    r2, r2, #0x0c
+       blt     .Lmemmove_bsrcul2l4
+
+.Lmemmove_bsrcul2loop4:
+#ifdef __ARMEB__
+       mov     r12, r3, lsr #16
+#else
+       mov     r12, r3, lsl #16
+#endif
+       ldr     r3, [r1, #-4]!
+#ifdef __ARMEB__
+       orr     r12, r12, r3, lsl #16
+#else
+       orr     r12, r12, r3, lsr #16
+#endif
+       str     r12, [r0, #-4]!
+       subs    r2, r2, #4
+       bge     .Lmemmove_bsrcul2loop4
+
+.Lmemmove_bsrcul2l4:
+       add     r1, r1, #2
+       b       .Lmemmove_bl4
+
+.Lmemmove_bsrcul1:
+       cmp     r2, #0x0c
+       blt     .Lmemmove_bsrcul1loop4
+       sub     r2, r2, #0x0c
+       stmdb   sp!, {r4, r5, lr}
+
+.Lmemmove_bsrcul1loop32:
+#ifdef __ARMEB__
+       mov     lr, r3, lsr #24
+#else
+       mov     lr, r3, lsl #24
+#endif
+       ldmdb   r1!, {r3-r5, r12}
+#ifdef __ARMEB__
+       orr     lr, lr, r12, lsl #8
+       mov     r12, r12, lsr #24
+       orr     r12, r12, r5, lsl #8
+       mov     r5, r5, lsr #24
+       orr     r5, r5, r4, lsl #8
+       mov     r4, r4, lsr #24
+       orr     r4, r4, r3, lsl #8
+#else
+       orr     lr, lr, r12, lsr #8
+       mov     r12, r12, lsl #24
+       orr     r12, r12, r5, lsr #8
+       mov     r5, r5, lsl #24
+       orr     r5, r5, r4, lsr #8
+       mov     r4, r4, lsl #24
+       orr     r4, r4, r3, lsr #8
+#endif
+       stmdb   r0!, {r4, r5, r12, lr}
+       subs    r2, r2, #0x10
+       bge     .Lmemmove_bsrcul1loop32
+       ldmia   sp!, {r4, r5, lr}
+       adds    r2, r2, #0x0c
+       blt     .Lmemmove_bsrcul1l4
+
+.Lmemmove_bsrcul1loop4:
+#ifdef __ARMEB__
+       mov     r12, r3, lsr #24
+#else
+       mov     r12, r3, lsl #24
+#endif
+       ldr     r3, [r1, #-4]!
+#ifdef __ARMEB__
+       orr     r12, r12, r3, lsl #8
+#else
+       orr     r12, r12, r3, lsr #8
+#endif
+       str     r12, [r0, #-4]!
+       subs    r2, r2, #4
+       bge     .Lmemmove_bsrcul1loop4
+
+.Lmemmove_bsrcul1l4:
+       add     r1, r1, #1
+       b       .Lmemmove_bl4
diff --git a/common/lib/libc/arch/arm/string/memset.S b/common/lib/libc/arch/arm/string/memset.S
new file mode 100644 (file)
index 0000000..cd9c6fa
--- /dev/null
@@ -0,0 +1,235 @@
+/*     $NetBSD: memset.S,v 1.1 2005/12/20 19:28:49 christos Exp $      */
+
+/*
+ * Copyright 2003 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Steve C. Woodford for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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.
+ */
+/*
+ * Copyright (c) 1995 Mark Brinicombe.
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe.
+ * 4. The name of the company nor the name of the author may be used to
+ *    endorse or promote products derived from this software without specific
+ *    prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 <machine/asm.h>
+
+/*
+ * memset: Sets a block of memory to the specified value
+ *
+ * On entry:
+ *   r0 - dest address
+ *   r1 - byte to write
+ *   r2 - number of bytes to write
+ *
+ * On exit:
+ *   r0 - dest address
+ */
+#ifdef _BZERO
+/* LINTSTUB: Func: void bzero(void *, size_t) */
+ENTRY(bzero)
+       mov     r3, #0x00
+#else
+/* LINTSTUB: Func: void *memset(void *, int, size_t) */
+ENTRY(memset)
+       and     r3, r1, #0xff           /* We deal with bytes */
+       mov     r1, r2
+#endif
+       cmp     r1, #0x04               /* Do we have less than 4 bytes */
+       mov     ip, r0
+       blt     .Lmemset_lessthanfour
+
+       /* Ok first we will word align the address */
+       ands    r2, ip, #0x03           /* Get the bottom two bits */
+       bne     .Lmemset_wordunaligned  /* The address is not word aligned */
+
+       /* We are now word aligned */
+.Lmemset_wordaligned:
+#ifndef _BZERO
+       orr     r3, r3, r3, lsl #8      /* Extend value to 16-bits */
+#endif
+#ifdef __XSCALE__
+       tst     ip, #0x04               /* Quad-align for Xscale */
+#else
+       cmp     r1, #0x10
+#endif
+#ifndef _BZERO
+       orr     r3, r3, r3, lsl #16     /* Extend value to 32-bits */
+#endif
+#ifdef __XSCALE__
+       subne   r1, r1, #0x04           /* Quad-align if necessary */
+       strne   r3, [ip], #0x04
+       cmp     r1, #0x10
+#endif
+       blt     .Lmemset_loop4          /* If less than 16 then use words */
+       mov     r2, r3                  /* Duplicate data */
+       cmp     r1, #0x80               /* If < 128 then skip the big loop */
+       blt     .Lmemset_loop32
+
+       /* Do 128 bytes at a time */
+.Lmemset_loop128:
+       subs    r1, r1, #0x80
+#ifdef __XSCALE__
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+#else
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+#endif
+       bgt     .Lmemset_loop128
+       RETc(eq)                        /* Zero length so just exit */
+
+       add     r1, r1, #0x80           /* Adjust for extra sub */
+
+       /* Do 32 bytes at a time */
+.Lmemset_loop32:
+       subs    r1, r1, #0x20
+#ifdef __XSCALE__
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+#else
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+#endif
+       bgt     .Lmemset_loop32
+       RETc(eq)                        /* Zero length so just exit */
+
+       adds    r1, r1, #0x10           /* Partially adjust for extra sub */
+
+       /* Deal with 16 bytes or more */
+#ifdef __XSCALE__
+       strged  r2, [ip], #0x08
+       strged  r2, [ip], #0x08
+#else
+       stmgeia ip!, {r2-r3}
+       stmgeia ip!, {r2-r3}
+#endif
+       RETc(eq)                        /* Zero length so just exit */
+
+       addlt   r1, r1, #0x10           /* Possibly adjust for extra sub */
+
+       /* We have at least 4 bytes so copy as words */
+.Lmemset_loop4:
+       subs    r1, r1, #0x04
+       strge   r3, [ip], #0x04
+       bgt     .Lmemset_loop4
+       RETc(eq)                        /* Zero length so just exit */
+
+#ifdef __XSCALE__
+       /* Compensate for 64-bit alignment check */
+       adds    r1, r1, #0x04
+       RETc(eq)
+       cmp     r1, #2
+#else
+       cmp     r1, #-2
+#endif
+
+       strb    r3, [ip], #0x01         /* Set 1 byte */
+       strgeb  r3, [ip], #0x01         /* Set another byte */
+       strgtb  r3, [ip]                /* and a third */
+       RET                             /* Exit */
+
+.Lmemset_wordunaligned:
+       rsb     r2, r2, #0x004
+       strb    r3, [ip], #0x01         /* Set 1 byte */
+       cmp     r2, #0x02
+       strgeb  r3, [ip], #0x01         /* Set another byte */
+       sub     r1, r1, r2
+       strgtb  r3, [ip], #0x01         /* and a third */
+       cmp     r1, #0x04               /* More than 4 bytes left? */
+       bge     .Lmemset_wordaligned    /* Yup */
+
+.Lmemset_lessthanfour:
+       cmp     r1, #0x00
+       RETc(eq)                                /* Zero length so exit */
+       strb    r3, [ip], #0x01         /* Set 1 byte */
+       cmp     r1, #0x02
+       strgeb  r3, [ip], #0x01         /* Set another byte */
+       strgtb  r3, [ip]                /* and a third */
+       RET                             /* Exit */
diff --git a/common/lib/libc/arch/arm/string/strcmp.S b/common/lib/libc/arch/arm/string/strcmp.S
new file mode 100644 (file)
index 0000000..a00cbbf
--- /dev/null
@@ -0,0 +1,43 @@
+/*      $NetBSD: strcmp.S,v 1.1 2005/12/20 19:28:49 christos Exp $ */
+
+/*
+ * Copyright (c) 2002 ARM Ltd
+ * 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.
+ * 3. The name of the company may not be used to endorse or promote
+ *    products derived from this software without specific prior written
+ *    permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY ARM LTD ``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 ARM LTD 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 <machine/asm.h>
+
+RCSID("$NetBSD: strcmp.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+
+ENTRY(strcmp)
+1:
+       ldrb    r2, [r0], #1
+       ldrb    r3, [r1], #1
+       cmp     r2, #1
+       cmpcs   r2, r3
+       beq     1b
+       sub     r0, r2, r3
+       RET
diff --git a/common/lib/libc/arch/arm/string/strncmp.S b/common/lib/libc/arch/arm/string/strncmp.S
new file mode 100644 (file)
index 0000000..fe77052
--- /dev/null
@@ -0,0 +1,51 @@
+/*      $NetBSD: strncmp.S,v 1.1 2005/12/20 19:28:49 christos Exp $ */
+
+/*
+ * Copyright (c) 2002 ARM Ltd
+ * 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.
+ * 3. The name of the company may not be used to endorse or promote
+ *    products derived from this software without specific prior written
+ *    permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY ARM LTD ``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 ARM LTD 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 <machine/asm.h>
+
+RCSID("$NetBSD: strncmp.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+
+ENTRY(strncmp)
+/* if ((len - 1) < 0) return 0 */
+       subs    r2, r2, #1
+       movmi   r0, #0
+       RETc(mi)
+
+/* ip == last src address to compare */
+       add     ip, r0, r2
+1:
+       ldrb    r2, [r0], #1
+       ldrb    r3, [r1], #1
+       cmp     ip, r0
+       cmpcs   r2, #1
+       cmpcs   r2, r3
+       beq     1b
+       sub     r0, r2, r3
+       RET
diff --git a/common/lib/libc/arch/hppa/atomic/Makefile.inc b/common/lib/libc/arch/hppa/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..fe0a950
--- /dev/null
@@ -0,0 +1,23 @@
+#      $NetBSD: Makefile.inc,v 1.8 2011/01/17 07:29:17 skrll Exp $
+
+.if defined(LIB)
+
+.  if (${LIB} == "kern" || ${LIB} == "c" || ${LIB} == "pthread" || \
+    ${LIB} == "rump")
+
+SRCS+= atomic_add_32_cas.c atomic_add_32_nv_cas.c atomic_and_32_cas.c \
+       atomic_and_32_nv_cas.c atomic_dec_32_cas.c atomic_dec_32_nv_cas.c \
+       atomic_inc_32_cas.c atomic_inc_32_nv_cas.c atomic_or_32_cas.c \
+       atomic_or_32_nv_cas.c atomic_swap_32_cas.c membar_ops_nop.c
+
+.  endif
+
+.  if (${LIB} == "c" || ${LIB} == "pthread")
+
+SRCS+= atomic_init_testset.c
+SRCS+= atomic_cas_up.S
+CPPFLAGS+= -D__HAVE_ASM_ATOMIC_CAS_UP
+
+.  endif
+
+.endif
diff --git a/common/lib/libc/arch/hppa/atomic/atomic_cas_up.S b/common/lib/libc/arch/hppa/atomic/atomic_cas_up.S
new file mode 100644 (file)
index 0000000..8304631
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: atomic_cas_up.S,v 1.2 2011/01/16 12:07:26 skrll Exp $  */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Nick Hudson
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/ras.h>
+#include <machine/asm.h>
+
+LEAF_ENTRY_NOPROFILE(_atomic_cas_up)
+       .hidden _C_LABEL(_atomic_cas_up)
+
+RAS_START_ASM_HIDDEN(_atomic_cas)
+       ldw     0(%arg0), %ret0
+       comb,<>,n       %arg1, %ret0, 1f
+       stw     %arg2, 0(%arg0)
+RAS_END_ASM_HIDDEN(_atomic_cas)
+1:
+       bv,n    %r0(%rp)
+
+EXIT(_atomic_cas_up)
diff --git a/common/lib/libc/arch/hppa/atomic/membar_ops.S b/common/lib/libc/arch/hppa/atomic/membar_ops.S
new file mode 100644 (file)
index 0000000..a732c64
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: membar_ops.S,v 1.1 2011/01/17 07:40:21 skrll Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe, and by Andrew Doran.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+RCSID("$NetBSD: membar_ops.S,v 1.1 2011/01/17 07:40:21 skrll Exp $")
+
+       .text
+
+LEAF_ENTRY(_membar_consumer)
+       sync
+       nop
+       nop
+       nop
+       nop
+       nop
+       bv      %r0(%rp)
+        nop
+EXIT(_membar_consumer)
+
+LEAF_ENTRY(_membar_producer)
+       sync
+       nop
+       nop
+       nop
+       nop
+       nop
+       bv      %r0(%rp)
+        nop
+EXIT(_membar_producer)
+
+ATOMIC_OP_ALIAS(membar_producer,_membar_producer)
+ATOMIC_OP_ALIAS(membar_consumer,_membar_consumer)
+ATOMIC_OP_ALIAS(membar_enter,_membar_consumer)
+STRONG_ALIAS(_membar_enter,_membar_consumer)
+ATOMIC_OP_ALIAS(membar_exit,_membar_producer)
+STRONG_ALIAS(_membar_exit,_membar_producer)
+ATOMIC_OP_ALIAS(membar_sync,_membar_producer)
+STRONG_ALIAS(_membar_sync,_membar_producer)
diff --git a/common/lib/libc/arch/i386/atomic/Makefile.inc b/common/lib/libc/arch/i386/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..5a7ca58
--- /dev/null
@@ -0,0 +1,17 @@
+#      $NetBSD: Makefile.inc,v 1.7 2009/01/04 17:54:29 pooka Exp $
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "c" || ${LIB} == "pthread" \
+       || ${LIB} == "rump")
+
+SRCS+= atomic_add_64_cas.c atomic_add_64_nv_cas.c atomic_and_64_cas.c \
+       atomic_and_64_nv_cas.c atomic_dec_64_cas.c atomic_dec_64_nv_cas.c \
+       atomic_inc_64_cas.c atomic_inc_64_nv_cas.c atomic_or_64_cas.c \
+       atomic_or_64_nv_cas.c atomic_swap_64_cas.c atomic.S
+
+.endif
+
+.if defined(LIB) && (${LIB} == "c" || ${LIB} == "pthread")
+
+SRCS+= atomic_init_cas.c
+
+.endif
diff --git a/common/lib/libc/arch/i386/atomic/atomic.S b/common/lib/libc/arch/i386/atomic/atomic.S
new file mode 100644 (file)
index 0000000..81c321b
--- /dev/null
@@ -0,0 +1,384 @@
+/*     $NetBSD: atomic.S,v 1.19 2011/01/12 23:12:10 joerg Exp $        */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe, and by Andrew Doran.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/param.h>
+#include <machine/asm.h>
+
+#ifdef _KERNEL
+#define        ALIAS(f, t)     STRONG_ALIAS(f,t)
+#else
+#define        ALIAS(f, t)     WEAK_ALIAS(f,t)
+#endif
+
+#ifdef _HARDKERNEL
+#define        LOCK(n)         .Lpatch ## n:   lock
+#define        ENDLABEL(a)     _ALIGN_TEXT; LABEL(a)
+#else
+#define        LOCK(n)         lock
+#define        ENDLABEL(a)     /* nothing */
+#endif
+
+       .text
+
+ENTRY(_atomic_add_32)
+       movl    4(%esp), %edx
+       movl    8(%esp), %eax
+       LOCK(1)
+       addl    %eax, (%edx)
+       ret
+
+ENTRY(_atomic_add_32_nv)
+       movl    4(%esp), %edx
+       movl    8(%esp), %eax
+       movl    %eax, %ecx
+       LOCK(2)
+       xaddl   %eax, (%edx)
+       addl    %ecx, %eax
+       ret
+
+ENTRY(_atomic_and_32)
+       movl    4(%esp), %edx
+       movl    8(%esp), %eax
+       LOCK(3)
+       andl    %eax, (%edx)
+       ret
+
+ENTRY(_atomic_and_32_nv)
+       movl    4(%esp), %edx
+       movl    (%edx), %eax
+0:
+       movl    %eax, %ecx
+       andl    8(%esp), %ecx
+       LOCK(4)
+       cmpxchgl %ecx, (%edx)
+       jnz     1f
+       movl    %ecx, %eax
+       ret
+1:
+       jmp     0b
+
+ENTRY(_atomic_dec_32)
+       movl    4(%esp), %edx
+       LOCK(5)
+       decl    (%edx)
+       ret
+
+ENTRY(_atomic_dec_32_nv)
+       movl    4(%esp), %edx
+       movl    $-1, %eax
+       LOCK(6)
+       xaddl   %eax, (%edx)
+       decl    %eax
+       ret
+
+ENTRY(_atomic_inc_32)
+       movl    4(%esp), %edx
+       LOCK(7)
+       incl    (%edx)
+       ret
+
+ENTRY(_atomic_inc_32_nv)
+       movl    4(%esp), %edx
+       movl    $1, %eax
+       LOCK(8)
+       xaddl   %eax, (%edx)
+       incl    %eax
+       ret
+
+ENTRY(_atomic_or_32)
+       movl    4(%esp), %edx
+       movl    8(%esp), %eax
+       LOCK(9)
+       orl     %eax, (%edx)
+       ret
+
+ENTRY(_atomic_or_32_nv)
+       movl    4(%esp), %edx
+       movl    (%edx), %eax
+0:
+       movl    %eax, %ecx
+       orl     8(%esp), %ecx
+       LOCK(10)
+       cmpxchgl %ecx, (%edx)
+       jnz     1f
+       movl    %ecx, %eax
+       ret
+1:
+       jmp     0b
+
+ENTRY(_atomic_swap_32)
+       movl    4(%esp), %edx
+       movl    8(%esp), %eax
+       xchgl   %eax, (%edx)
+       ret
+
+ENTRY(_atomic_cas_32)
+       movl    4(%esp), %edx
+       movl    8(%esp), %eax
+       movl    12(%esp), %ecx
+       LOCK(12)
+       cmpxchgl %ecx, (%edx)
+       /* %eax now contains the old value */
+       ret
+
+ENTRY(_atomic_cas_32_ni)
+       movl    4(%esp), %edx
+       movl    8(%esp), %eax
+       movl    12(%esp), %ecx
+       cmpxchgl %ecx, (%edx)
+       /* %eax now contains the old value */
+       ret
+
+ENTRY(_membar_consumer)
+       LOCK(13)
+       addl    $0, -4(%esp)
+       ret
+ENDLABEL(membar_consumer_end)
+
+ENTRY(_membar_producer)
+       /* A store is enough */
+       movl    $0, -4(%esp)
+       ret
+ENDLABEL(membar_producer_end)
+
+ENTRY(_membar_sync)
+       LOCK(14)
+       addl    $0, -4(%esp)
+       ret
+ENDLABEL(membar_sync_end)
+
+#ifdef _HARDKERNEL
+ENTRY(_atomic_cas_64)
+       pushf
+       cli
+       pushl   %edi
+       pushl   %ebx
+       movl    12(%esp), %edi
+       movl    16(%esp), %eax
+       movl    20(%esp), %edx
+       movl    24(%esp), %ebx
+       movl    28(%esp), %ecx
+       cmpl    0(%edi), %eax
+       jne     2f
+       cmpl    4(%edi), %edx
+       jne     2f
+       movl    %ebx, 0(%edi)
+       movl    %ecx, 4(%edi)
+1:
+       popl    %ebx
+       popl    %edi
+       popf
+       ret
+2:
+       movl    0(%edi), %eax
+       movl    4(%edi), %edx
+       jmp     1b
+ENDLABEL(_atomic_cas_64_end)
+
+ENTRY(_atomic_cas_cx8)
+       pushl   %edi
+       pushl   %ebx
+       movl    12(%esp), %edi
+       movl    16(%esp), %eax
+       movl    20(%esp), %edx
+       movl    24(%esp), %ebx
+       movl    28(%esp), %ecx
+       LOCK(15)
+       cmpxchg8b (%edi)
+       popl    %ebx
+       popl    %edi
+       ret
+#ifdef GPROF
+       .space  16, 0x90
+#else
+       .space  32, 0x90
+#endif
+ENDLABEL(_atomic_cas_cx8_end)
+
+ENTRY(sse2_lfence)
+       lfence
+       ret
+ENDLABEL(sse2_lfence_end)
+
+ENTRY(sse2_mfence)
+       mfence
+       ret
+ENDLABEL(sse2_mfence_end)
+
+atomic_lockpatch:
+       .globl  atomic_lockpatch
+       .long   .Lpatch1, .Lpatch2, .Lpatch3, .Lpatch4, .Lpatch5
+       .long   .Lpatch6, .Lpatch7, .Lpatch8, .Lpatch9, .Lpatch10
+       .long   .Lpatch12, .Lpatch13, .Lpatch14, .Lpatch15, 0
+#else
+ENTRY(_atomic_cas_64)
+       pushl   %edi
+       pushl   %ebx
+       movl    12(%esp), %edi
+       movl    16(%esp), %eax
+       movl    20(%esp), %edx
+       movl    24(%esp), %ebx
+       movl    28(%esp), %ecx
+       lock
+       cmpxchg8b (%edi)
+       popl    %ebx
+       popl    %edi
+       ret
+#endif /* _HARDKERNEL */
+
+ALIAS(atomic_add_32,_atomic_add_32)
+ALIAS(atomic_add_int,_atomic_add_32)
+ALIAS(atomic_add_long,_atomic_add_32)
+ALIAS(atomic_add_ptr,_atomic_add_32)
+
+ALIAS(atomic_add_32_nv,_atomic_add_32_nv)
+ALIAS(atomic_add_int_nv,_atomic_add_32_nv)
+ALIAS(atomic_add_long_nv,_atomic_add_32_nv)
+ALIAS(atomic_add_ptr_nv,_atomic_add_32_nv)
+
+ALIAS(atomic_and_32,_atomic_and_32)
+ALIAS(atomic_and_uint,_atomic_and_32)
+ALIAS(atomic_and_ulong,_atomic_and_32)
+ALIAS(atomic_and_ptr,_atomic_and_32)
+
+ALIAS(atomic_and_32_nv,_atomic_and_32_nv)
+ALIAS(atomic_and_uint_nv,_atomic_and_32_nv)
+ALIAS(atomic_and_ulong_nv,_atomic_and_32_nv)
+ALIAS(atomic_and_ptr_nv,_atomic_and_32_nv)
+
+ALIAS(atomic_dec_32,_atomic_dec_32)
+ALIAS(atomic_dec_uint,_atomic_dec_32)
+ALIAS(atomic_dec_ulong,_atomic_dec_32)
+ALIAS(atomic_dec_ptr,_atomic_dec_32)
+
+ALIAS(atomic_dec_32_nv,_atomic_dec_32_nv)
+ALIAS(atomic_dec_uint_nv,_atomic_dec_32_nv)
+ALIAS(atomic_dec_ulong_nv,_atomic_dec_32_nv)
+ALIAS(atomic_dec_ptr_nv,_atomic_dec_32_nv)
+
+ALIAS(atomic_inc_32,_atomic_inc_32)
+ALIAS(atomic_inc_uint,_atomic_inc_32)
+ALIAS(atomic_inc_ulong,_atomic_inc_32)
+ALIAS(atomic_inc_ptr,_atomic_inc_32)
+
+ALIAS(atomic_inc_32_nv,_atomic_inc_32_nv)
+ALIAS(atomic_inc_uint_nv,_atomic_inc_32_nv)
+ALIAS(atomic_inc_ulong_nv,_atomic_inc_32_nv)
+ALIAS(atomic_inc_ptr_nv,_atomic_inc_32_nv)
+
+ALIAS(atomic_or_32,_atomic_or_32)
+ALIAS(atomic_or_uint,_atomic_or_32)
+ALIAS(atomic_or_ulong,_atomic_or_32)
+ALIAS(atomic_or_ptr,_atomic_or_32)
+
+ALIAS(atomic_or_32_nv,_atomic_or_32_nv)
+ALIAS(atomic_or_uint_nv,_atomic_or_32_nv)
+ALIAS(atomic_or_ulong_nv,_atomic_or_32_nv)
+ALIAS(atomic_or_ptr_nv,_atomic_or_32_nv)
+
+ALIAS(atomic_swap_32,_atomic_swap_32)
+ALIAS(atomic_swap_uint,_atomic_swap_32)
+ALIAS(atomic_swap_ulong,_atomic_swap_32)
+ALIAS(atomic_swap_ptr,_atomic_swap_32)
+
+ALIAS(atomic_cas_32,_atomic_cas_32)
+ALIAS(atomic_cas_uint,_atomic_cas_32)
+ALIAS(atomic_cas_ulong,_atomic_cas_32)
+ALIAS(atomic_cas_ptr,_atomic_cas_32)
+
+ALIAS(atomic_cas_32_ni,_atomic_cas_32_ni)
+ALIAS(atomic_cas_uint_ni,_atomic_cas_32_ni)
+ALIAS(atomic_cas_ulong_ni,_atomic_cas_32_ni)
+ALIAS(atomic_cas_ptr_ni,_atomic_cas_32_ni)
+
+ALIAS(atomic_cas_64,_atomic_cas_64)
+ALIAS(atomic_cas_64_ni,_atomic_cas_64)
+
+ALIAS(membar_consumer,_membar_consumer)
+ALIAS(membar_producer,_membar_producer)
+ALIAS(membar_enter,_membar_consumer)
+ALIAS(membar_exit,_membar_producer)
+ALIAS(membar_sync,_membar_sync)
+
+STRONG_ALIAS(_atomic_add_int,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_long,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_ptr,_atomic_add_32)
+
+STRONG_ALIAS(_atomic_add_int_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_long_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_ptr_nv,_atomic_add_32_nv)
+
+STRONG_ALIAS(_atomic_and_uint,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_ulong,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_ptr,_atomic_and_32)
+
+STRONG_ALIAS(_atomic_and_uint_nv,_atomic_and_32_nv)
+STRONG_ALIAS(_atomic_and_ulong_nv,_atomic_and_32_nv)
+STRONG_ALIAS(_atomic_and_ptr_nv,_atomic_and_32_nv)
+
+STRONG_ALIAS(_atomic_dec_uint,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_ulong,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_ptr,_atomic_dec_32)
+
+STRONG_ALIAS(_atomic_dec_uint_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_ulong_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_ptr_nv,_atomic_dec_32_nv)
+
+STRONG_ALIAS(_atomic_inc_uint,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_ulong,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_ptr,_atomic_inc_32)
+
+STRONG_ALIAS(_atomic_inc_uint_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_ulong_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_ptr_nv,_atomic_inc_32_nv)
+
+STRONG_ALIAS(_atomic_or_uint,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_ulong,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_ptr,_atomic_or_32)
+
+STRONG_ALIAS(_atomic_or_uint_nv,_atomic_or_32_nv)
+STRONG_ALIAS(_atomic_or_ulong_nv,_atomic_or_32_nv)
+STRONG_ALIAS(_atomic_or_ptr_nv,_atomic_or_32_nv)
+
+STRONG_ALIAS(_atomic_swap_uint,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_ulong,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_ptr,_atomic_swap_32)
+
+STRONG_ALIAS(_atomic_cas_uint,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ptr,_atomic_cas_32)
+
+STRONG_ALIAS(_atomic_cas_uint_ni,_atomic_cas_32_ni)
+STRONG_ALIAS(_atomic_cas_ulong_ni,_atomic_cas_32_ni)
+STRONG_ALIAS(_atomic_cas_ptr_ni,_atomic_cas_32_ni)
+
+STRONG_ALIAS(_membar_enter,_membar_consumer)
+STRONG_ALIAS(_membar_exit,_membar_producer)
diff --git a/common/lib/libc/arch/i386/gen/byte_swap_2.S b/common/lib/libc/arch/i386/gen/byte_swap_2.S
new file mode 100644 (file)
index 0000000..5150f17
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: byte_swap_2.S,v 1.3 2007/11/28 17:03:35 ad Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)htons.s       5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: byte_swap_2.S,v 1.3 2007/11/28 17:03:35 ad Exp $")
+#endif
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+_ENTRY(_C_LABEL(bswap16))
+#else /* defined(_KERNEL) || defined(_STANDALONE) */
+_ENTRY(_C_LABEL(__bswap16))
+#endif /* defined(_KERNEL) || defined(_STANDALONE) */
+_ENTRY(_C_LABEL(ntohs))
+_ENTRY(_C_LABEL(htons))
+_PROF_PROLOGUE
+       movzwl  4(%esp),%eax
+       xchgb   %al, %ah
+       ret
diff --git a/common/lib/libc/arch/i386/gen/byte_swap_4.S b/common/lib/libc/arch/i386/gen/byte_swap_4.S
new file mode 100644 (file)
index 0000000..0c48ae9
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: byte_swap_4.S,v 1.3 2007/11/28 17:03:35 ad Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)htonl.s       5.3 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: byte_swap_4.S,v 1.3 2007/11/28 17:03:35 ad Exp $")
+#endif
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+_ENTRY(_C_LABEL(bswap32))
+#else /* defined(_KERNEL) || defined(_STANDALONE) */
+_ENTRY(_C_LABEL(__bswap32))
+#endif /* defined(_KERNEL) || defined(_STANDALONE) */
+_ENTRY(_C_LABEL(ntohl))
+_ENTRY(_C_LABEL(htonl))
+_PROF_PROLOGUE
+       movl    4(%esp),%eax
+       bswap   %eax
+       ret
diff --git a/common/lib/libc/arch/i386/string/ffs.S b/common/lib/libc/arch/i386/string/ffs.S
new file mode 100644 (file)
index 0000000..d532262
--- /dev/null
@@ -0,0 +1,20 @@
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: ffs.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+
+ENTRY(ffs)
+       bsfl    4(%esp),%eax
+       jz      L1                      /* ZF is set if all bits are 0 */
+       incl    %eax                    /* bits numbered from 1, not 0 */
+       ret
+
+       _ALIGN_TEXT
+L1:    xorl    %eax,%eax               /* clear result */
+       ret
diff --git a/common/lib/libc/arch/i386/string/memchr.S b/common/lib/libc/arch/i386/string/memchr.S
new file mode 100644 (file)
index 0000000..4aaddf3
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ * Written by J.T. Conklin <jtc@acorntoolworks.com>
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: memchr.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+
+ENTRY(memchr)
+       pushl   %esi
+       movl    8(%esp),%eax
+       movzbl  12(%esp),%ecx
+       movl    16(%esp),%esi
+
+       /*
+        * Align to word boundary. 
+        * Consider unrolling loop?
+        */
+       testl   %esi,%esi       /* nbytes == 0? */
+       je      .Lzero
+.Lalign:
+       testb   $3,%al
+       je      .Lword_aligned
+       cmpb    (%eax),%cl
+       je      .Ldone
+       incl    %eax
+       decl    %esi
+       jnz     .Lalign
+       jmp     .Lzero
+
+.Lword_aligned:
+       /* copy char to all bytes in word */
+       movb    %cl,%ch
+       movl    %ecx,%edx
+       sall    $16,%ecx
+       orl     %edx,%ecx
+
+       _ALIGN_TEXT
+.Lloop:
+       cmpl    $3,%esi         /* nbytes > 4 */
+       jbe     .Lbyte
+       movl    (%eax),%edx
+       addl    $4,%eax
+       xorl    %ecx,%edx
+       subl    $4,%esi
+       subl    $0x01010101,%edx
+       testl   $0x80808080,%edx
+       je      .Lloop
+
+       /*
+        * In rare cases, the above loop may exit prematurely. We must
+        * return to the loop if none of the bytes in the word are
+        * equal to ch.
+        */
+
+       /*
+        * High load-use latency on the Athlon leads to significant
+        * stalls, so we preload the next char as soon as possible
+        * instead of using cmp mem8, reg8.
+        *
+        * Alignment here avoids a stall on the Athlon, even though
+        * it's not a branch target.
+        */
+       _ALIGN_TEXT
+       cmpb    -4(%eax),%cl    /* 1st byte == ch? */
+       movb    -3(%eax),%dl
+       jne     1f
+       subl    $4,%eax
+       jmp     .Ldone
+
+       _ALIGN_TEXT
+1:     cmpb    %dl,%cl         /* 2nd byte == ch? */
+       movb    -2(%eax),%dl
+       jne     1f
+       subl    $3,%eax
+       jmp     .Ldone
+
+       _ALIGN_TEXT
+1:     cmpb    %dl,%cl         /* 3rd byte == ch? */
+       movb    -1(%eax),%dl
+       jne     1f
+       subl    $2,%eax
+       jmp     .Ldone
+
+       _ALIGN_TEXT
+1:     cmpb    %dl,%cl         /* 4th byte == ch? */
+       jne     .Lloop
+       decl    %eax
+       jmp     .Ldone
+
+.Lbyte:
+       testl   %esi,%esi
+       je      .Lzero
+.Lbyte_loop:
+       cmpb    (%eax),%cl
+       je      .Ldone
+       incl    %eax
+       decl    %esi
+       jnz     .Lbyte_loop
+
+.Lzero:
+       xorl    %eax,%eax
+
+.Ldone:
+       popl    %esi
+       ret
diff --git a/common/lib/libc/arch/i386/string/memcmp.S b/common/lib/libc/arch/i386/string/memcmp.S
new file mode 100644 (file)
index 0000000..a3ad404
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: memcmp.S,v 1.2 2007/11/12 18:41:59 ad Exp $")
+#endif
+
+ENTRY(memcmp)
+       pushl   %edi
+       pushl   %esi
+       movl    12(%esp),%edi
+       movl    16(%esp),%esi
+
+       movl    20(%esp),%ecx           /* compare by words */
+       shrl    $2,%ecx
+       repe
+       cmpsl
+       jne     L5                      /* do we match so far? */
+
+       movl    20(%esp),%ecx           /* compare remainder by bytes */
+       andl    $3,%ecx
+       repe
+       cmpsb
+       jne     L6                      /* do we match? */
+
+       xorl    %eax,%eax               /* we match, return zero        */
+       popl    %esi
+       popl    %edi
+       ret
+
+L5:    movl    $4,%ecx                 /* We know that one of the next */
+       subl    %ecx,%edi               /* four pairs of bytes do not   */
+       subl    %ecx,%esi               /* match.                       */
+       repe
+       cmpsb
+L6:    xorl    %eax,%eax               /* Perform unsigned comparison  */
+       movb    -1(%edi),%al
+       xorl    %edx,%edx
+       movb    -1(%esi),%dl
+       subl    %edx,%eax
+       popl    %esi
+       popl    %edi
+       ret
diff --git a/common/lib/libc/arch/i386/string/memcpy.S b/common/lib/libc/arch/i386/string/memcpy.S
new file mode 100644 (file)
index 0000000..abb1b97
--- /dev/null
@@ -0,0 +1,133 @@
+/*     $NetBSD: memcpy.S,v 1.3 2007/11/12 18:41:59 ad Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from locore.s.
+ * Optimised by David Laight 2003
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: memcpy.S,v 1.3 2007/11/12 18:41:59 ad Exp $")
+#endif
+
+       /*
+        * (ov)bcopy (src,dst,cnt)
+        *  ws@tools.de     (Wolfgang Solfrank, TooLs GmbH) +49-228-985800
+        */
+
+#ifdef BCOPY
+ENTRY(bcopy)
+#else
+#ifdef MEMMOVE
+ENTRY(memmove)
+#else
+#define MEMCPY
+#define NO_OVERLAP
+ENTRY(memcpy)
+#endif
+#endif
+       push    %esi
+       mov     %edi,%edx
+#if defined(MEMCPY) || defined(MEMMOVE)
+       movl    8(%esp),%edi
+       movl    12(%esp),%esi
+#else
+       movl    8(%esp),%esi
+       movl    12(%esp),%edi
+#endif
+       movl    16(%esp),%ecx
+#if defined(NO_OVERLAP)
+       movl    %ecx,%eax
+#else
+       movl    %edi,%eax
+       subl    %esi,%eax
+       cmpl    %ecx,%eax       /* overlapping? */
+       movl    %ecx,%eax
+       jb      .Lbackwards
+#endif
+       /* nope, copy forwards. */
+       shrl    $2,%ecx         /* copy by words */
+       rep
+       movsl
+       and     $3,%eax         /* any bytes left? */
+       jnz     .Ltrailing
+.Ldone:
+#if defined(MEMCPY) || defined(MEMMOVE)
+       movl    8(%esp),%eax
+#endif
+       mov     %edx,%edi
+       pop     %esi
+       ret
+
+.Ltrailing:
+       cmp     $2,%eax
+       jb      1f
+       movw    (%esi),%ax
+       movw    %ax,(%edi)
+       je      .Ldone
+       movb    2(%esi),%al
+       movb    %al,2(%edi)
+       jmp     .Ldone
+1:     movb    (%esi),%al
+       movb    %al,(%edi)
+       jmp     .Ldone
+
+#if !defined(NO_OVERLAP)
+.Lbackwards:
+       addl    %ecx,%edi       /* copy backwards. */
+       addl    %ecx,%esi
+       and     $3,%eax         /* any fractional bytes? */
+       jnz     .Lback_align
+.Lback_aligned:
+       shrl    $2,%ecx
+       subl    $4,%esi
+       subl    $4,%edi
+       std
+       rep
+       movsl
+       cld
+       jmp     .Ldone
+
+.Lback_align:
+       sub     %eax,%esi
+       sub     %eax,%edi
+       cmp     $2,%eax
+       jb      1f
+       je      2f
+       movb    2(%esi),%al
+       movb    %al,2(%edi)
+2:     movw    (%esi),%ax
+       movw    %ax,(%edi)
+       jmp     .Lback_aligned
+1:     movb    (%esi),%al
+       movb    %al,(%edi)
+       jmp     .Lback_aligned
+#endif
diff --git a/common/lib/libc/arch/i386/string/memmove.S b/common/lib/libc/arch/i386/string/memmove.S
new file mode 100644 (file)
index 0000000..2b8ea6d
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: memmove.S,v 1.1 2005/12/20 19:28:49 christos Exp $     */
+
+#define MEMMOVE
+#include "memcpy.S"
diff --git a/common/lib/libc/arch/i386/string/memset.S b/common/lib/libc/arch/i386/string/memset.S
new file mode 100644 (file)
index 0000000..91009a3
--- /dev/null
@@ -0,0 +1,106 @@
+/*     $NetBSD: memset.S,v 1.4 2008/04/29 06:53:01 martin Exp $        */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by David Laight.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: memset.S,v 1.4 2008/04/29 06:53:01 martin Exp $")
+#endif
+
+#ifdef BZERO
+ENTRY(bzero)
+#else
+ENTRY(memset)
+#endif
+#ifdef BZERO
+       movl    8(%esp),%ecx
+       xor     %eax,%eax
+#else
+       movl    12(%esp),%ecx
+       movzbl  8(%esp),%eax            /* unsigned char, zero extend */
+#endif
+       cmpl    $0x0f,%ecx              /* avoid mispredicted branch... */
+
+       pushl   %edi
+       movl    8(%esp),%edi
+
+       /*
+        * if the string is too short, it's really not worth the overhead
+        * of aligning to word boundries, etc.  So we jump to a plain
+        * unaligned set.
+        *
+        * NB aligning the transfer is actually pointless on my athlon 700,
+        * It does make a difference to a PII though.
+        *
+        * The PII, PIII and PIV all seem to have a massive performance
+        * drop when the initial target address is an odd multiple of 4.
+        */
+       jbe     .Lby_bytes
+
+#ifndef BZERO
+       movb    %al,%ah                 /* copy char to all bytes in word */
+       movl    %eax,%edx
+       sall    $16,%eax
+       orl     %edx,%eax
+#endif
+
+       movl    %edi,%edx               /* detect misalignment */
+       neg     %edx
+       andl    $7,%edx
+       jnz     .Lalign
+.Laligned:
+       movl    %eax,-4(%edi,%ecx)      /* zap last 4 bytes */
+       shrl    $2,%ecx                 /* zero by words */
+       rep
+       stosl
+.Ldone:
+#ifndef BZERO
+       movl    8(%esp),%eax            /* return address of buffer */
+#endif
+       pop     %edi
+       ret
+
+.Lalign:
+       movl    %eax,(%edi)             /* zap first 8 bytes */
+       movl    %eax,4(%edi)
+       subl    %edx,%ecx               /* remove from main count */
+       add     %edx,%edi
+       jmp     .Laligned
+
+.Lby_bytes:
+       rep
+       stosb
+
+#ifndef BZERO
+       movl    8(%esp),%eax            /* return address of buffer */
+#endif
+       popl    %edi
+       ret
diff --git a/common/lib/libc/arch/i386/string/strcat.S b/common/lib/libc/arch/i386/string/strcat.S
new file mode 100644 (file)
index 0000000..8196f4e
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ * Written by J.T. Conklin <jtc@acorntoolworks.com>
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strcat.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+
+ENTRY(strcat)
+       pushl   %ebx
+       movl    8(%esp),%ecx
+       movl    12(%esp),%eax
+
+       /*
+        * Align destination to word boundary.
+        * Consider unrolling loop?
+        */
+.Lscan:
+.Lscan_align:
+       testb   $3,%cl
+       je      .Lscan_aligned
+       cmpb    $0,(%ecx)
+       je      .Lcopy
+       incl    %ecx
+       jmp     .Lscan_align
+
+       _ALIGN_TEXT
+.Lscan_aligned:
+.Lscan_loop:
+       movl    (%ecx),%ebx
+       addl    $4,%ecx
+       leal    -0x01010101(%ebx),%edx
+       testl   $0x80808080,%edx
+       je      .Lscan_loop
+
+       /*
+        * In rare cases, the above loop may exit prematurely. We must
+        * return to the loop if none of the bytes in the word equal 0.
+        */
+
+       /*
+        * The optimal code for determining whether each byte is zero
+        * differs by processor.  This space-optimized code should be
+        * acceptable on all, especially since we don't expect it to
+        * be run frequently,
+        */
+
+       testb   %bl,%bl         /* 1st byte == 0? */
+       jne     1f
+       subl    $4,%ecx
+       jmp     .Lcopy
+
+1:     testb   %bh,%bh         /* 2nd byte == 0? */
+       jne     1f
+       subl    $3,%ecx
+       jmp     .Lcopy
+
+1:     shrl    $16,%ebx
+       testb   %bl,%bl         /* 3rd byte == 0? */
+       jne     1f
+       subl    $2,%ecx
+       jmp     .Lcopy
+
+1:     testb   %bh,%bh         /* 4th byte == 0? */
+       jne     .Lscan_loop
+       subl    $1,%ecx
+
+       /*
+        * Align source to a word boundary.
+        * Consider unrolling loop?
+        */
+.Lcopy:
+.Lcopy_align:
+       testl   $3,%eax
+       je      .Lcopy_aligned
+       movb    (%eax),%bl
+       incl    %eax
+       movb    %bl,(%ecx)
+       incl    %ecx
+       testb   %bl,%bl
+       jne     .Lcopy_align
+       jmp     .Ldone
+
+       _ALIGN_TEXT
+.Lcopy_loop:
+       movl    %ebx,(%ecx)
+       addl    $4,%ecx
+.Lcopy_aligned:
+       movl    (%eax),%ebx
+       addl    $4,%eax
+       leal    -0x01010101(%ebx),%edx
+       testl   $0x80808080,%edx
+       je      .Lcopy_loop
+
+       /*
+        * In rare cases, the above loop may exit prematurely. We must
+        * return to the loop if none of the bytes in the word equal 0.
+        */
+
+       movb    %bl,(%ecx)
+       incl    %ecx
+       testb   %bl,%bl
+       je      .Ldone
+
+       movb    %bh,(%ecx)
+       incl    %ecx
+       testb   %bh,%bh
+       je      .Ldone
+
+       shrl    $16,%ebx
+       movb    %bl,(%ecx)
+       incl    %ecx
+       testb   %bl,%bl
+       je      .Ldone
+
+       movb    %bh,(%ecx)
+       incl    %ecx
+       testb   %bh,%bh
+       jne     .Lcopy_aligned
+
+.Ldone:
+       movl    8(%esp),%eax
+       popl    %ebx
+       ret
diff --git a/common/lib/libc/arch/i386/string/strchr.S b/common/lib/libc/arch/i386/string/strchr.S
new file mode 100644 (file)
index 0000000..400bcda
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * Written by J.T. Conklin <jtc@acorntoolworks.com>
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strchr.S,v 1.2 2009/07/17 19:37:57 dsl Exp $")
+#endif
+
+ENTRY(strchr)
+       pushl   %esi
+       pushl   %ebx
+       movl    12(%esp),%eax
+       movzbl  16(%esp),%ecx
+
+       /*
+        * Align to word boundary.
+        * Consider unrolling loop?
+        */
+.Lalign:
+       testb   $3,%al
+       je      .Lword_aligned
+       movb    (%eax),%bl
+       cmpb    %cl,%bl
+       je      .Ldone
+       testb   %bl,%bl
+       je      .Lzero
+       incl    %eax
+       jmp     .Lalign
+
+.Lword_aligned:
+       /* copy char to all bytes in word */
+       movb    %cl,%ch
+       movl    %ecx,%edx
+       sall    $16,%ecx
+       orl     %edx,%ecx
+
+       /* Check whether any byte in the word is equal to ch or 0. */
+       _ALIGN_TEXT
+.Lloop:
+       movl    (%eax),%ebx
+       addl    $4,%eax
+       movl    %ebx,%esi
+       leal    -0x01010101(%ebx),%edx
+       xorl    %ecx,%esi
+       subl    $0x01010101,%esi
+       orl     %esi,%edx
+       testl   $0x80808080,%edx
+       je      .Lloop
+
+       /*
+        * In rare cases, the above loop may exit prematurely. We must
+        * return to the loop if none of the bytes in the word match
+        * ch or are equal to 0.
+        */
+
+       /*
+        * Alignment here avoids a stall on the Athlon, even though
+        * it's not a branch target.
+        */
+
+       _ALIGN_TEXT
+       cmpb    %cl,%bl         /* 1st byte == ch? */
+       jne     1f
+       subl    $4,%eax
+       jmp     .Ldone
+1:     testb   %bl,%bl         /* 1st byte == 0? */
+       je      .Lzero
+
+       cmpb    %cl,%bh         /* 2nd byte == ch? */
+       jne     1f
+       subl    $3,%eax
+       jmp     .Ldone
+1:     testb   %bh,%bh         /* 2nd byte == 0? */
+       je      .Lzero
+
+       shrl    $16,%ebx
+       cmpb    %cl,%bl         /* 3rd byte == ch? */
+       jne     1f
+       subl    $2,%eax
+       jmp     .Ldone
+1:     testb   %bl,%bl         /* 3rd byte == 0? */
+       je      .Lzero
+
+       cmpb    %cl,%bh         /* 4th byte == ch? */
+       jne     1f
+       decl    %eax
+       jmp     .Ldone
+1:     testb   %bh,%bh         /* 4th byte == 0? */
+       jne     .Lloop
+
+.Lzero:
+       /* If a ch wasn't found, return 0. */
+       xorl    %eax,%eax
+
+.Ldone:
+       popl    %ebx
+       popl    %esi
+       ret
+
+STRONG_ALIAS(index,strchr)
diff --git a/common/lib/libc/arch/i386/string/strcmp.S b/common/lib/libc/arch/i386/string/strcmp.S
new file mode 100644 (file)
index 0000000..341ed82
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * Written by J.T. Conklin <jtc@acorntoolworks.com>
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strcmp.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+
+ENTRY(strcmp)
+       pushl   %esi
+       pushl   %ebx
+       movl    12(%esp),%ebx
+       movl    16(%esp),%esi
+
+       /*
+        * Align s1 to word boundary.
+        * Consider unrolling loop?
+        */
+.Ls1align:
+       testb   $3,%bl
+       je      .Ls1aligned
+       movb    (%ebx),%al
+       incl    %ebx
+       movb    (%esi),%dl
+       incl    %esi
+       testb   %al,%al
+       je      .Ldone
+       cmpb    %al,%dl
+       je      .Ls1align
+       jmp     .Ldone
+
+       /*
+        * Check whether s2 is aligned to a word boundary.  If it is, we
+        * can compare by words.  Otherwise we have to compare by bytes.
+        */
+.Ls1aligned:
+       testl   $3,%esi
+       jne     .Lbyte_loop
+
+       subl    $4,%ebx
+       subl    $4,%esi
+
+       _ALIGN_TEXT
+.Lword_loop:
+       movl    4(%ebx),%eax
+       addl    $4,%ebx
+       movl    4(%esi),%edx
+       addl    $4,%esi
+       cmpl    %eax,%edx
+       jne     .Lbyte_loop
+       subl    $0x01010101,%edx
+       notl    %eax
+       andl    %eax,%edx
+       testl   $0x80808080,%edx
+       je      .Lword_loop
+
+       _ALIGN_TEXT
+.Lbyte_loop:
+       movb    (%ebx),%al
+       incl    %ebx
+       movb    (%esi),%dl
+       incl    %esi
+       testb   %al,%al
+       je      .Ldone
+       cmpb    %al,%dl
+       je      .Lbyte_loop
+
+.Ldone:
+       movzbl  %al,%eax
+       movzbl  %dl,%edx
+       subl    %edx,%eax
+       popl    %ebx
+       popl    %esi
+       ret
diff --git a/common/lib/libc/arch/i386/string/strcpy.S b/common/lib/libc/arch/i386/string/strcpy.S
new file mode 100644 (file)
index 0000000..f14281a
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * Written by J.T. Conklin <jtc@acorntoolworks.com>
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strcpy.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+
+/*
+ * This strcpy implementation copies a byte at a time until the
+ * source pointer is aligned to a word boundary, it then copies by
+ * words until it finds a word containing a zero byte, and finally
+ * copies by bytes until the end of the string is reached.
+ *     
+ * While this may result in unaligned stores if the source and
+ * destination pointers are unaligned with respect to each other,
+ * it is still faster than either byte copies or the overhead of
+ * an implementation suitable for machines with strict alignment
+ * requirements.
+ */
+
+ENTRY(strcpy)
+       pushl   %ebx
+       movl    8(%esp),%ecx
+       movl    12(%esp),%eax
+
+       /*
+        * Align source to a word boundary.
+        * Consider unrolling loop?
+        */
+       _ALIGN_TEXT
+.Lalign:
+       testl   $3,%eax
+       je      .Lword_aligned
+       movb    (%eax),%bl
+       incl    %eax
+       movb    %bl,(%ecx)
+       incl    %ecx
+       testb   %bl,%bl
+       jne     .Lalign
+       jmp     .Ldone
+
+       _ALIGN_TEXT
+.Lloop:
+       movl    %ebx,(%ecx)
+       addl    $4,%ecx
+.Lword_aligned:
+       movl    (%eax),%ebx
+       addl    $4,%eax
+       leal    -0x01010101(%ebx),%edx
+       testl   $0x80808080,%edx
+       je      .Lloop
+       
+       /*
+        * In rare cases, the above loop may exit prematurely. We must
+        * return to the loop if none of the bytes in the word equal 0.
+        */
+
+       movb    %bl,(%ecx)
+       incl    %ecx
+       testb   %bl,%bl
+       je      .Ldone
+
+       movb    %bh,(%ecx)
+       incl    %ecx
+       testb   %bh,%bh
+       je      .Ldone
+
+       shrl    $16,%ebx
+       movb    %bl,(%ecx)
+       incl    %ecx
+       testb   %bl,%bl
+       je      .Ldone
+
+       movb    %bh,(%ecx)
+       incl    %ecx
+       testb   %bh,%bh
+       jne     .Lword_aligned
+
+.Ldone:
+       movl    8(%esp),%eax
+       popl    %ebx
+       ret
diff --git a/common/lib/libc/arch/i386/string/strlen.S b/common/lib/libc/arch/i386/string/strlen.S
new file mode 100644 (file)
index 0000000..8914339
--- /dev/null
@@ -0,0 +1,141 @@
+/*
+ * Written by J.T. Conklin <jtc@acorntoolworks.com>
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strlen.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+
+ENTRY(strlen)
+       movl    4(%esp),%eax
+
+.Lalign:
+       /* Consider unrolling loop? */
+       testb   $3,%al
+       je      .Lword_aligned
+       cmpb    $0,(%eax)
+       je      .Ldone
+       incl    %eax
+       jmp     .Lalign
+
+       /*
+        * There are many well known branch-free sequences which are used
+        * for determining whether a zero-byte is contained within a word.
+        * These sequences are generally much more efficent than loading
+        * and comparing each byte individually.
+        *
+        * The expression [1,2]:
+        *
+        * (1)  ~(((x & 0x7f7f7f7f) + 0x7f7f7f7f) | (x | 0x7f7f7f7f))
+        *
+        * evaluates to a non-zero value if any of the bytes in the
+        * original word is zero.
+        *
+        * It also has the useful property that bytes in the result word
+        * that correspond to non-zero bytes in the original word have
+        * the value 0x00, while bytes corresponding to zero bytes have
+        * the value 0x80. This allows calculation of the first (and
+        * last) occurrence of a zero byte within the word (useful for C's
+        * str* primitives) by counting the number of leading (or
+        * trailing) zeros and dividing the result by 8.  On machines
+        * without (or with slow) clz() / ctz() instructions, testing
+        * each byte in the result word for zero is necessary.
+        *
+        * This typically takes 4 instructions (5 on machines without
+        * "not-or") not including those needed to load the constant.
+        *
+        *
+        * The expression:
+        *
+        * (2)  ((x - 0x01010101) & ~x & 0x80808080)
+        *
+        * evaluates to a non-zero value if any of the bytes in the
+        * original word is zero.
+        *
+        * On little endian machines, the first byte in the result word
+        * that corresponds to a zero byte in the original byte is 0x80,
+        * so clz() can be used as above.  On big endian machines, and
+        * little endian machines without (or with a slow) clz() insn,
+        * testing each byte in the original for zero is necessary.
+        *
+        * This typically takes 3 instructions (4 on machines without
+        * "and with complement") not including those needed to load
+        * constants.
+        *
+        *
+        * The expression:
+        *
+        * (3)  ((x - 0x01010101) & 0x80808080)
+        *
+        * always evaluates to a non-zero value if any of the bytes in
+        * the original word is zero.  However, in rare cases, it also
+        * evaluates to a non-zero value when none of the bytes in the
+        * original word is zero.
+        *
+        * To account for possible false positives, each byte of the
+        * original word must be checked when the expression evaluates to
+        * a non-zero value.  However, because it is simpler than those
+        * presented above, code that uses it will be faster as long as
+        * the rate of false positives is low.
+        *
+        * This is likely, because the the false positive can only occur
+        * if the most siginificant bit of a byte within the word is set.
+        * The expression will never fail for typical 7-bit ASCII strings.
+        *
+        * This typically takes 2 instructions not including those needed
+        * to load constants.
+        *
+        *
+        * [1] Henry S. Warren Jr., "Hacker's Delight", Addison-Westley 2003
+        *
+        * [2] International Business Machines, "The PowerPC Compiler Writer's
+        *     Guide", Warthman Associates, 1996
+        */
+
+       _ALIGN_TEXT
+.Lword_aligned:
+.Lloop:
+       movl    (%eax),%ecx
+       addl    $4,%eax
+       leal    -0x01010101(%ecx),%edx
+       testl   $0x80808080,%edx
+       je      .Lloop
+
+       /*
+        * In rare cases, the above loop may exit prematurely. We must
+        * return to the loop if none of the bytes in the word equal 0.
+        */
+
+       /*
+        * The optimal code for determining whether each byte is zero
+        * differs by processor.  This space-optimized code should be
+        * acceptable on all, especially since we don't expect it to
+        * be run frequently,
+        */
+
+       testb   %cl,%cl         /* 1st byte == 0? */
+       jne     1f
+       subl    $4,%eax
+       jmp     .Ldone
+
+1:     testb   %ch,%ch         /* 2nd byte == 0? */
+       jne     1f
+       subl    $3,%eax
+       jmp     .Ldone
+
+1:     shrl    $16,%ecx
+       testb   %cl,%cl         /* 3rd byte == 0? */
+       jne     1f
+       subl    $2,%eax
+       jmp     .Ldone
+
+1:     testb   %ch,%ch         /* 4th byte == 0? */
+       jne     .Lloop
+       decl    %eax
+
+.Ldone:
+       subl    4(%esp),%eax
+       ret
diff --git a/common/lib/libc/arch/i386/string/strrchr.S b/common/lib/libc/arch/i386/string/strrchr.S
new file mode 100644 (file)
index 0000000..26ef544
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * Written by J.T. Conklin <jtc@acorntoolworks.com>
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strrchr.S,v 1.2 2009/07/17 19:37:57 dsl Exp $")
+#endif
+
+ENTRY(strrchr)
+       pushl   %esi
+       pushl   %edi
+       pushl   %ebx
+       movl    16(%esp),%edx
+       movzbl  20(%esp),%ecx
+
+       /* zero return value */
+       xorl    %eax,%eax
+
+       /*
+        * Align to word boundary.
+        * Consider unrolling loop?
+        */
+.Lalign:
+       testb   $3,%dl
+       je      .Lword_aligned
+       movb    (%edx),%bl
+       cmpb    %cl,%bl
+       jne     1f
+       movl    %edx,%eax
+1:     testb   %bl,%bl
+       je      .Ldone
+       incl    %edx
+       jmp     .Lalign
+
+.Lword_aligned:
+       /* copy char to all bytes in word */
+       movb    %cl,%ch
+       movl    %ecx,%edi
+       sall    $16,%ecx
+       orl     %edi,%ecx
+
+       /* Check whether any byte in the word is equal to ch or 0.  */
+       _ALIGN_TEXT
+.Lloop:
+       movl    (%edx),%ebx
+       addl    $4,%edx
+       movl    %ebx,%esi
+       leal    -0x01010101(%ebx),%edi
+       xorl    %ecx,%esi
+       subl    $0x01010101,%esi
+       orl     %esi,%edi
+       testl   $0x80808080,%edi
+       je      .Lloop
+
+       /*
+        * In rare cases, the above loop may exit prematurely. We must
+        * return to the loop if none of the bytes in the word match
+        * ch or are equal to 0.
+        */
+
+       _ALIGN_TEXT
+       cmpb    %cl,%bl         /* 1st byte == ch? */
+       jne     1f
+       leal    -4(%edx),%eax
+1:     testb   %bl,%bl         /* 1st byte == 0? */
+       je      .Ldone
+
+       cmpb    %cl,%bh         /* 2nd byte == ch? */
+       jne     1f
+       leal    -3(%edx),%eax
+1:     testb   %bh,%bh         /* 2nd byte == 0? */
+       je      .Ldone
+
+       shrl    $16,%ebx
+       cmpb    %cl,%bl         /* 3rd byte == ch? */
+       jne     1f
+       leal    -2(%edx),%eax
+1:     testb   %bl,%bl         /* 3rd byte == 0? */
+       je      .Ldone
+
+       cmpb    %cl,%bh         /* 4th byte == ch? */
+       jne     1f
+       leal    -1(%edx),%eax
+1:     testb   %bh,%bh         /* 4th byte == 0? */
+       jne     .Lloop
+
+.Ldone:
+       popl    %ebx
+       popl    %edi
+       popl    %esi
+       ret
+
+STRONG_ALIAS(rindex,strrchr)
diff --git a/common/lib/libc/arch/ia64/atomic/Makefile.inc b/common/lib/libc/arch/ia64/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..2bef12c
--- /dev/null
@@ -0,0 +1,21 @@
+#      $NetBSD: Makefile.inc,v 1.3 2009/01/04 17:54:29 pooka Exp $
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "c"  || ${LIB} == "pthread" \
+       || ${LIB} == "rump")
+
+SRCS+= atomic_add_32_cas.c atomic_add_32_nv_cas.c \
+       atomic_add_64_cas.c atomic_add_64_nv_cas.c \
+       atomic_and_32_cas.c atomic_and_32_nv_cas.c \
+       atomic_and_64_cas.c atomic_and_64_nv_cas.c \
+       atomic_or_32_cas.c atomic_or_32_nv_cas.c \
+       atomic_or_64_cas.c atomic_or_64_nv_cas.c
+
+SRCS+= atomic.S
+
+.endif
+
+.if defined(LIB) && (${LIB} == "c"  || ${LIB} == "pthread")
+
+SRCS += atomic_init_cas.c
+
+.endif
diff --git a/common/lib/libc/arch/ia64/atomic/atomic.S b/common/lib/libc/arch/ia64/atomic/atomic.S
new file mode 100644 (file)
index 0000000..192d242
--- /dev/null
@@ -0,0 +1,270 @@
+/*     $NetBSD: atomic.S,v 1.5 2009/11/09 14:22:02 skrll Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Takayoshi Kochi.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#ifdef _KERNEL
+#define        ALIAS(f, t)     STRONG_ALIAS(f,t)
+#else
+#define        ALIAS(f, t)     WEAK_ALIAS(f,t)
+#endif
+
+       .text
+
+ENTRY(_atomic_dec_32,1)
+       fetchadd4.rel   r8=[r32],-1
+       br.ret.sptk     rp
+END(_atomic_dec_32)
+
+ENTRY(_atomic_dec_64,1)
+       fetchadd8.rel   r8=[r32],-1
+       br.ret.sptk     rp
+END(_atomic_dec_64)
+
+ENTRY(_atomic_dec_32_nv,1)
+       fetchadd4.rel   r8=[r32],-1
+       br.ret.sptk     rp
+END(_atomic_dec_32_nv)
+
+ENTRY(_atomic_dec_64_nv,1)
+       fetchadd8.rel   r8=[r32],-1
+       br.ret.sptk     rp
+END(_atomic_dec_64_nv)
+
+ENTRY(_atomic_inc_32,1)
+       fetchadd4.rel   r8=[r32],1
+       br.ret.sptk     rp
+END(_atomic_inc_32)
+
+ENTRY(_atomic_inc_64,1)
+       fetchadd8.rel   r8=[r32],1
+       br.ret.sptk     rp
+END(_atomic_inc_64)
+
+ENTRY(_atomic_inc_32_nv,1)
+       fetchadd4.rel   r8=[r32],1
+       br.ret.sptk     rp
+END(_atomic_inc_32_nv)
+
+ENTRY(_atomic_inc_64_nv,1)
+       fetchadd8.rel   r8=[r32],1
+       br.ret.sptk     rp
+END(_atomic_inc_64_nv)
+
+ENTRY(_atomic_swap_32,2)
+       xchg4           r8=[r32],r33
+       ;;
+       mov             r33=r8
+       br.ret.sptk     rp
+END(_atomic_swap_32)
+
+ENTRY(_atomic_swap_64,2)
+       xchg8           r8=[r32],r33
+       ;;
+       mov             r33=r8
+       br.ret.sptk     rp
+END(_atomic_swap_64)
+
+ENTRY(_atomic_cas_32,3)
+       mov             ar.ccv=r33
+       ;;
+       cmpxchg4.acq    r8=[r32],r34,ar.ccv
+       br.ret.sptk     rp
+END(_atomic_cas_32)
+
+ENTRY(_atomic_cas_64,3)
+       mov             ar.ccv=r33
+       ;;
+       cmpxchg8.acq    r8=[r32],r34,ar.ccv
+       br.ret.sptk     rp
+END(_atomic_cas_64)
+
+ENTRY(_membar_consumer,0)
+       mf
+       br.ret.sptk     rp
+END(_membar_consumer)
+
+ENTRY(_membar_producer,0)
+       mf
+       br.ret.sptk     rp
+END(_membar_producer)
+
+ENTRY(_membar_enter,0)
+       mf
+       br.ret.sptk     rp
+END(_membar_enter)
+
+ENTRY(_membar_exit,0)
+       mf
+       br.ret.sptk     rp
+END(_membar_exit)
+
+ENTRY(_membar_sync,0)
+       mf
+       br.ret.sptk     rp
+END(_membar_sync)
+
+
+ALIAS(atomic_add_32,_atomic_add_32)
+ALIAS(atomic_add_int,_atomic_add_32)
+ALIAS(atomic_add_64,_atomic_add_64)
+ALIAS(atomic_add_long,_atomic_add_64)
+ALIAS(atomic_add_ptr,_atomic_add_64)
+
+ALIAS(atomic_add_32_nv,_atomic_add_32_nv)
+ALIAS(atomic_add_int_nv,_atomic_add_32_nv)
+ALIAS(atomic_add_64_nv,_atomic_add_64_nv)
+ALIAS(atomic_add_long_nv,_atomic_add_64_nv)
+ALIAS(atomic_add_ptr_nv,_atomic_add_64_nv)
+
+ALIAS(atomic_and_32,_atomic_and_32)
+ALIAS(atomic_and_uint,_atomic_and_32)
+ALIAS(atomic_and_64,_atomic_and_64)
+ALIAS(atomic_and_ulong,_atomic_and_64)
+ALIAS(atomic_and_ptr,_atomic_and_64)
+
+ALIAS(atomic_and_32_nv,_atomic_and_32_nv)
+ALIAS(atomic_and_uint_nv,_atomic_and_32_nv)
+ALIAS(atomic_and_64_nv,_atomic_and_64_nv)
+ALIAS(atomic_and_ulong_nv,_atomic_and_64_nv)
+ALIAS(atomic_and_ptr_nv,_atomic_and_64_nv)
+
+ALIAS(atomic_dec_32,_atomic_dec_32)
+ALIAS(atomic_dec_uint,_atomic_dec_32)
+ALIAS(atomic_dec_64,_atomic_dec_64)
+ALIAS(atomic_dec_ulong,_atomic_dec_64)
+ALIAS(atomic_dec_ptr,_atomic_dec_64)
+
+ALIAS(atomic_dec_32_nv,_atomic_dec_32_nv)
+ALIAS(atomic_dec_uint_nv,_atomic_dec_32_nv)
+ALIAS(atomic_dec_64_nv,_atomic_dec_64_nv)
+ALIAS(atomic_dec_ulong_nv,_atomic_dec_64_nv)
+ALIAS(atomic_dec_ptr_nv,_atomic_dec_64_nv)
+
+ALIAS(atomic_inc_32,_atomic_inc_32)
+ALIAS(atomic_inc_uint,_atomic_inc_32)
+ALIAS(atomic_inc_64,_atomic_inc_64)
+ALIAS(atomic_inc_ulong,_atomic_inc_64)
+ALIAS(atomic_inc_ptr,_atomic_inc_64)
+
+ALIAS(atomic_inc_32_nv,_atomic_inc_32_nv)
+ALIAS(atomic_inc_uint_nv,_atomic_inc_32_nv)
+ALIAS(atomic_inc_64_nv,_atomic_inc_64_nv)
+ALIAS(atomic_inc_ulong_nv,_atomic_inc_64_nv)
+ALIAS(atomic_inc_ptr_nv,_atomic_inc_64_nv)
+
+ALIAS(atomic_or_32,_atomic_or_32)
+ALIAS(atomic_or_uint,_atomic_or_32)
+ALIAS(atomic_or_64,_atomic_or_64)
+ALIAS(atomic_or_ulong,_atomic_or_64)
+ALIAS(atomic_or_ptr,_atomic_or_64)
+
+ALIAS(atomic_or_32_nv,_atomic_or_32_nv)
+ALIAS(atomic_or_uint_nv,_atomic_or_32_nv)
+ALIAS(atomic_or_64_nv,_atomic_or_64_nv)
+ALIAS(atomic_or_ulong_nv,_atomic_or_64_nv)
+ALIAS(atomic_or_ptr_nv,_atomic_or_64_nv)
+
+ALIAS(atomic_swap_32,_atomic_swap_32)
+ALIAS(atomic_swap_uint,_atomic_swap_32)
+ALIAS(atomic_swap_64,_atomic_swap_64)
+ALIAS(atomic_swap_ulong,_atomic_swap_64)
+ALIAS(atomic_swap_ptr,_atomic_swap_64)
+
+ALIAS(atomic_cas_32,_atomic_cas_32)
+ALIAS(atomic_cas_uint,_atomic_cas_32)
+ALIAS(atomic_cas_64,_atomic_cas_64)
+ALIAS(atomic_cas_ulong,_atomic_cas_64)
+ALIAS(atomic_cas_ptr,_atomic_cas_64)
+
+ALIAS(atomic_cas_32_ni,_atomic_cas_32)
+ALIAS(atomic_cas_uint_ni,_atomic_cas_32)
+ALIAS(atomic_cas_64_ni,_atomic_cas_64)
+ALIAS(atomic_cas_ulong_ni,_atomic_cas_64)
+ALIAS(atomic_cas_ptr_ni,_atomic_cas_64)
+
+ALIAS(membar_consumer,_membar_consumer)
+ALIAS(membar_producer,_membar_producer)
+ALIAS(membar_enter,_membar_enter)
+ALIAS(membar_exit,_membar_exit)
+ALIAS(membar_sync,_membar_sync)
+
+STRONG_ALIAS(_atomic_add_int,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_long,_atomic_add_64)
+STRONG_ALIAS(_atomic_add_ptr,_atomic_add_64)
+
+STRONG_ALIAS(_atomic_add_int_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_long_nv,_atomic_add_64_nv)
+STRONG_ALIAS(_atomic_add_ptr_nv,_atomic_add_64_nv)
+
+STRONG_ALIAS(_atomic_and_uint,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_ulong,_atomic_and_64)
+STRONG_ALIAS(_atomic_and_ptr,_atomic_and_64)
+
+STRONG_ALIAS(_atomic_and_uint_nv,_atomic_and_32_nv)
+STRONG_ALIAS(_atomic_and_ulong_nv,_atomic_and_64_nv)
+STRONG_ALIAS(_atomic_and_ptr_nv,_atomic_and_64_nv)
+
+STRONG_ALIAS(_atomic_dec_uint,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_ulong,_atomic_dec_64)
+STRONG_ALIAS(_atomic_dec_ptr,_atomic_dec_64)
+
+STRONG_ALIAS(_atomic_dec_uint_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_ulong_nv,_atomic_dec_64_nv)
+STRONG_ALIAS(_atomic_dec_ptr_nv,_atomic_dec_64_nv)
+
+STRONG_ALIAS(_atomic_inc_uint,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_ulong,_atomic_inc_64)
+STRONG_ALIAS(_atomic_inc_ptr,_atomic_inc_64)
+
+STRONG_ALIAS(_atomic_inc_uint_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_ulong_nv,_atomic_inc_64_nv)
+STRONG_ALIAS(_atomic_inc_ptr_nv,_atomic_inc_64_nv)
+
+STRONG_ALIAS(_atomic_or_uint,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_ulong,_atomic_or_64)
+STRONG_ALIAS(_atomic_or_ptr,_atomic_or_64)
+
+STRONG_ALIAS(_atomic_or_uint_nv,_atomic_or_32_nv)
+STRONG_ALIAS(_atomic_or_ulong_nv,_atomic_or_64_nv)
+STRONG_ALIAS(_atomic_or_ptr_nv,_atomic_or_64_nv)
+
+STRONG_ALIAS(_atomic_swap_uint,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_ulong,_atomic_swap_64)
+STRONG_ALIAS(_atomic_swap_ptr,_atomic_swap_64)
+
+STRONG_ALIAS(_atomic_cas_uint,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ptr,_atomic_cas_64)
+
+STRONG_ALIAS(_atomic_cas_uint_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong_ni,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ptr_ni,_atomic_cas_64)
diff --git a/common/lib/libc/arch/m68k/atomic/Makefile.inc b/common/lib/libc/arch/m68k/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..f4e3676
--- /dev/null
@@ -0,0 +1,41 @@
+#      $NetBSD: Makefile.inc,v 1.9 2009/01/04 17:54:29 pooka Exp $
+
+#
+# Note: The atomic operations here in these assembly files are atomic
+# only with respect to regular memory on uniprocessor systems.  Since
+# we don't support any MP m68k systems, this is just fine.  If we ever
+# do, then these routines will probably need to be replaced with CAS-
+# based routines (CAS generates an atomic bus cycle, whereas these
+# others are merely single-instruction).
+#
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "c" || ${LIB} == "pthread" \
+       || ${LIB} == "rump")
+.if ${MACHINE_ARCH} != "m68000"
+
+SRCS+= atomic_add.S atomic_and.S atomic_cas.S atomic_dec.S \
+       atomic_inc.S atomic_or.S atomic_swap.S membar_ops_nop.c
+
+.else
+
+SRCS+=  atomic_add_32_cas.c atomic_add_32_nv_cas.c atomic_and_32_cas.c \
+       atomic_and_32_nv_cas.c atomic_dec_32_cas.c atomic_dec_32_nv_cas.c \
+       atomic_inc_32_cas.c atomic_inc_32_nv_cas.c atomic_or_32_cas.c \
+       atomic_or_32_nv_cas.c atomic_swap_32_cas.c membar_ops_nop.c
+
+.endif
+.endif
+
+.if defined(LIB) && (${LIB} == "c" || ${LIB} == "pthread")
+.if ${MACHINE_ARCH} != "m68000"
+
+SRCS+= atomic_init_cas.c
+
+.else
+
+SRCS+= atomic_init_testset.c
+SRCS+= atomic_cas_68000.S
+CPPFLAGS+= -D__HAVE_ASM_ATOMIC_CAS_UP
+
+.endif
+.endif
diff --git a/common/lib/libc/arch/m68k/atomic/atomic_add.S b/common/lib/libc/arch/m68k/atomic/atomic_add.S
new file mode 100644 (file)
index 0000000..e8c5d90
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: atomic_add.S,v 1.4 2008/05/25 15:56:11 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+       .align  2
+
+ENTRY(_atomic_add_32)
+       movl    %sp@(4), %a0
+       movl    %sp@(8), %d0
+       addl    %d0, %a0@
+       rts
+ATOMIC_OP_ALIAS(atomic_add_32,_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_int,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_int,_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_long,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_long,_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_ptr,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_ptr,_atomic_add_32)
+
+ENTRY(_atomic_add_32_nv)
+       movl    %sp@(4), %a0
+1:     movl    %a0@, %d0
+       movl    %d0, %d1
+       addl    %sp@(8), %d0
+       casl    %d1, %d0, %a0@
+       bne     1b
+       movl    %d0, %a0        /* pointers return also in %a0 */
+       rts
+ATOMIC_OP_ALIAS(atomic_add_32_nv,_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_int_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_int_nv,_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_long_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_long_nv,_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_ptr_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_ptr_nv,_atomic_add_32_nv)
diff --git a/common/lib/libc/arch/m68k/atomic/atomic_and.S b/common/lib/libc/arch/m68k/atomic/atomic_and.S
new file mode 100644 (file)
index 0000000..4426fd0
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: atomic_and.S,v 1.6 2008/05/25 15:56:11 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_and_32)
+       movl    %sp@(4), %a0
+       movl    %sp@(8), %d0
+       andl    %d0, %a0@
+       rts
+ATOMIC_OP_ALIAS(atomic_and_32,_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_uint,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_uint,_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_ulong,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_ulong,_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_ptr,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_ptr,_atomic_and_32)
+
+ENTRY(_atomic_and_32_nv)
+       movl    %sp@(4), %a0
+1:     movl    %a0@, %d0
+       movl    %d0, %d1
+       andl    %sp@(8), %d0
+       casl    %d1, %d0, %a0@
+       bne     1b
+       rts
+ATOMIC_OP_ALIAS(atomic_and_32_nv,_atomic_and_32_nv)
+ATOMIC_OP_ALIAS(atomic_and_uint_nv,_atomic_and_32_nv)
+STRONG_ALIAS(_atomic_and_uint_nv,_atomic_and_32_nv)
+ATOMIC_OP_ALIAS(atomic_and_ulong_nv,_atomic_and_32_nv)
+STRONG_ALIAS(_atomic_and_ulong_nv,_atomic_and_32_nv)
+ATOMIC_OP_ALIAS(atomic_and_ptr_nv,_atomic_and_32_nv)
+STRONG_ALIAS(_atomic_and_ptr_nv,_atomic_and_32_nv)
diff --git a/common/lib/libc/arch/m68k/atomic/atomic_cas.S b/common/lib/libc/arch/m68k/atomic/atomic_cas.S
new file mode 100644 (file)
index 0000000..c5f5036
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: atomic_cas.S,v 1.5 2008/05/25 15:56:11 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007, 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_cas_32)
+       movl    %sp@(4), %a0
+       movl    %sp@(8), %d0
+       movl    %sp@(12), %d1
+       casl    %d0, %d1, %a0@
+       /* %d0 now contains the old value */
+       movl    %d0, %a0        /* pointers return also in %a0 */
+       rts
+
+ATOMIC_OP_ALIAS(atomic_cas_32,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_uint,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_uint,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_ulong,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_ptr,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ptr,_atomic_cas_32)
+
+ATOMIC_OP_ALIAS(atomic_cas_32_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_32_ni,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_uint_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_uint_ni,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_ulong_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong_ni,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_ptr_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ptr_ni,_atomic_cas_32)
diff --git a/common/lib/libc/arch/m68k/atomic/atomic_cas_68000.S b/common/lib/libc/arch/m68k/atomic/atomic_cas_68000.S
new file mode 100644 (file)
index 0000000..c3daead
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: atomic_cas_68000.S,v 1.3 2008/05/25 15:56:11 chs Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Steve C. Woodford.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/ras.h>
+#include "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_cas_up)
+       .hidden _C_LABEL(_atomic_cas_up)
+
+       movl    %sp@(4), %a0            /* Fetch ptr */
+
+RAS_START_ASM_HIDDEN(_atomic_cas)
+       movl    %a0@, %d0               /* d0 = *ptr */
+       cmpl    %sp@(8), %d0            /* Same as old? */
+       jne     1f                      /* Nope */
+       movl    %sp@(12), %a0@          /* *ptr = new */
+RAS_END_ASM_HIDDEN(_atomic_cas)
+1:     rts
+
diff --git a/common/lib/libc/arch/m68k/atomic/atomic_dec.S b/common/lib/libc/arch/m68k/atomic/atomic_dec.S
new file mode 100644 (file)
index 0000000..d5cd3e7
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: atomic_dec.S,v 1.4 2008/05/25 15:56:11 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_dec_32)
+       movl    %sp@(4), %a0
+       subql   #1, %a0@
+       rts
+ATOMIC_OP_ALIAS(atomic_dec_32,_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_uint,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_uint,_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_ulong,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_ulong,_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_ptr,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_ptr,_atomic_dec_32)
+
+ENTRY(_atomic_dec_32_nv)
+       movl    %sp@(4), %a0
+1:     movl    %a0@, %d0
+       movl    %d0, %d1
+       subql   #1, %d0
+       casl    %d1, %d0, %a0@
+       bne     1b
+       movl    %d0, %a0        /* pointers return also in %a0 */
+       rts
+ATOMIC_OP_ALIAS(atomic_dec_32_nv,_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_uint_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_uint_nv,_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_ulong_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_ulong_nv,_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_ptr_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_ptr_nv,_atomic_dec_32_nv)
diff --git a/common/lib/libc/arch/m68k/atomic/atomic_inc.S b/common/lib/libc/arch/m68k/atomic/atomic_inc.S
new file mode 100644 (file)
index 0000000..bed844a
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: atomic_inc.S,v 1.4 2008/05/25 15:56:11 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_inc_32)
+       movl    %sp@(4), %a0
+       addql   #1, %a0@
+       rts
+ATOMIC_OP_ALIAS(atomic_inc_32,_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_uint,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_uint,_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_ulong,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_ulong,_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_ptr,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_ptr,_atomic_inc_32)
+
+ENTRY(_atomic_inc_32_nv)
+       movl    %sp@(4), %a0
+1:     movl    %a0@, %d0
+       movl    %d0, %d1
+       addql   #1, %d0
+       casl    %d1, %d0, %a0@
+       bne     1b
+       movl    %d0, %a0        /* pointers return also in %a0 */
+       rts
+ATOMIC_OP_ALIAS(atomic_inc_32_nv,_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_uint_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_uint_nv,_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_ulong_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_ulong_nv,_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_ptr_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_ptr_nv,_atomic_inc_32_nv)
diff --git a/common/lib/libc/arch/m68k/atomic/atomic_op_asm.h b/common/lib/libc/arch/m68k/atomic/atomic_op_asm.h
new file mode 100644 (file)
index 0000000..56015db
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: atomic_op_asm.h,v 1.3 2008/04/28 20:22:52 martin Exp $ */
+
+/*-
+ * Copyright (c) 2006, 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _ATOMIC_OP_ASM_H_
+#define        _ATOMIC_OP_ASM_H_
+
+#include <machine/asm.h>
+
+#if defined(_KERNEL)
+
+#define        ATOMIC_OP_ALIAS(a,s)    STRONG_ALIAS(a,s)
+
+#else /* _KERNEL */
+
+#define        ATOMIC_OP_ALIAS(a,s)    WEAK_ALIAS(a,s)
+
+#endif /* _KERNEL */
+
+#endif /* _ATOMIC_OP_ASM_H_ */
diff --git a/common/lib/libc/arch/m68k/atomic/atomic_or.S b/common/lib/libc/arch/m68k/atomic/atomic_or.S
new file mode 100644 (file)
index 0000000..bb739b6
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: atomic_or.S,v 1.6 2008/05/25 15:56:11 chs Exp $        */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_or_32)
+       movl    %sp@(4), %a0
+       movl    %sp@(8), %d0
+       orl     %d0, %a0@
+       rts
+ATOMIC_OP_ALIAS(atomic_or_32,_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_uint,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_uint,_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_ulong,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_ulong,_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_ptr,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_ptr,_atomic_or_32)
+
+ENTRY(_atomic_or_32_nv)
+       movl    %sp@(4), %a0
+1:     movl    %a0@, %d0
+       movl    %d0, %d1
+       orl     %sp@(8), %d0
+       casl    %d1, %d0, %a0@
+       bne     1b
+       rts
+ATOMIC_OP_ALIAS(atomic_or_32_nv,_atomic_or_32_nv)
+ATOMIC_OP_ALIAS(atomic_or_uint_nv,_atomic_or_32_nv)
+STRONG_ALIAS(_atomic_or_uint_nv,_atomic_or_32_nv)
+ATOMIC_OP_ALIAS(atomic_or_ulong_nv,_atomic_or_32_nv)
+STRONG_ALIAS(_atomic_or_ulong_nv,_atomic_or_32_nv)
+ATOMIC_OP_ALIAS(atomic_or_ptr_nv,_atomic_or_32_nv)
+STRONG_ALIAS(_atomic_or_ptr_nv,_atomic_or_32_nv)
diff --git a/common/lib/libc/arch/m68k/atomic/atomic_swap.S b/common/lib/libc/arch/m68k/atomic/atomic_swap.S
new file mode 100644 (file)
index 0000000..53389ae
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: atomic_swap.S,v 1.4 2008/05/25 15:56:11 chs Exp $      */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_swap_32)
+       movl    %sp@(4), %a0
+1:     movl    %a0@, %d0
+       movl    %sp@(8), %d1
+       casl    %d0, %d1, %a0@
+       bne     1b
+       /* %d0 now contains the old value */
+       movl    %d0, %a0        /* pointers return also in %a0 */
+       rts
+ATOMIC_OP_ALIAS(atomic_swap_32,_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_uint,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_uint,_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_ulong,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_ulong,_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_ptr,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_ptr,_atomic_swap_32)
diff --git a/common/lib/libc/arch/m68k/gen/bswap16.S b/common/lib/libc/arch/m68k/gen/bswap16.S
new file mode 100644 (file)
index 0000000..f7c8471
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: bswap16.S,v 1.2 2007/09/19 20:31:34 he Exp $   */
+
+/*
+ * Copyright (C) 1996 Scott Reynolds.  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.
+ * 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 ``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 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 <machine/asm.h>
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+_ENTRY(_C_LABEL(bswap16))
+#else /* defined(_KERNEL) || defined(_STANDALONE) */
+_ENTRY(_C_LABEL(__bswap16))
+#endif /* defined(_KERNEL) || defined(_STANDALONE) */
+       movl    %sp@(4),%d0
+       rolw    #8,%d0
+       rts
diff --git a/common/lib/libc/arch/m68k/gen/bswap32.S b/common/lib/libc/arch/m68k/gen/bswap32.S
new file mode 100644 (file)
index 0000000..f8b0b92
--- /dev/null
@@ -0,0 +1,40 @@
+/*     $NetBSD: bswap32.S,v 1.2 2007/09/19 20:31:34 he Exp $   */
+
+/*
+ * Copyright (C) 1996 Scott Reynolds.  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.
+ * 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 ``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 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 <machine/asm.h>
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+_ENTRY(_C_LABEL(bswap32))
+#else /* defined(_KERNEL) || defined(_STANDALONE) */
+_ENTRY(_C_LABEL(__bswap32))
+#endif /* defined(_KERNEL) || defined(_STANDALONE) */
+       movl    %sp@(4),%d0
+       rolw    #8,%d0
+       swap    %d0
+       rolw    #8,%d0
+       rts
diff --git a/common/lib/libc/arch/m68k/gen/bswap64.S b/common/lib/libc/arch/m68k/gen/bswap64.S
new file mode 100644 (file)
index 0000000..ebce236
--- /dev/null
@@ -0,0 +1,40 @@
+/*     $NetBSD: bswap64.S,v 1.1 2005/12/20 19:28:49 christos Exp $     */
+
+/*
+ * Copyright (C) 1996 Scott Reynolds.  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.
+ * 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 ``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 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 <machine/asm.h>
+
+ENTRY(bswap64)
+       movl    %sp@(4),%d1
+       movl    %sp@(8),%d0
+       rolw    #8,%d1
+       rolw    #8,%d0
+       swap    %d1
+       swap    %d0
+       rolw    #8,%d0
+       rolw    #8,%d1
+       rts
diff --git a/common/lib/libc/arch/m68k/gen/divsi3.S b/common/lib/libc/arch/m68k/gen/divsi3.S
new file mode 100644 (file)
index 0000000..a49bec9
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: divsi3.S,v 1.2 2006/01/05 22:33:34 he Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)divsi3.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: divsi3.S,v 1.2 2006/01/05 22:33:34 he Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* int / int */
+ENTRY(__divsi3)
+#ifndef __mc68010__
+       movel   %sp@(4),%d0
+       divsl   %sp@(8),%d0
+       rts
+#else
+| NB: this requires that __udivsi3 preserve %a0:
+       movel   %sp@(4), %d1    | load the dividend
+       bpl     1f
+       negl    %sp@(4)         | store abs(dividend)
+1:     movel   %sp@(8), %d0    | load the divisor
+       bpl     2f
+       negl    %sp@(8)         | store abs(divisor)
+2:     eorl    %d1, %d0
+       bpl     3f              | branch if sgn(divisor) == sgn(dividend)
+       movel   %sp@+, %a0      | pop return address
+       pea     %pc@(Lret)      | push our return address
+3:     jmp     _C_LABEL(__udivsi3)
+Lret:  negl    %d0             | negate quotient
+       jmp     %a0@
+#endif /* __mc68010__ */
diff --git a/common/lib/libc/arch/m68k/gen/modsi3.S b/common/lib/libc/arch/m68k/gen/modsi3.S
new file mode 100644 (file)
index 0000000..4808e80
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: modsi3.S,v 1.3 2006/01/13 16:07:59 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)modsi3.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: modsi3.S,v 1.3 2006/01/13 16:07:59 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* int % int */
+ENTRY(__modsi3)
+#ifndef __mc68010__
+       movel   %sp@(4),%d1
+       divsll  %sp@(8),%d0:%d1
+       rts
+#else
+| NB: this requires that __udivsi3 preserve %a0 and return
+| the modulus in %d1:
+       movel   %sp@+, %a0      | pop return address
+       movel   %sp@(4), %d1    | load the divisor
+       bpl     1f
+       negl    %sp@(4)         | store abs(divisor)
+1:     movel   %sp@, %d0       | load the dividend
+       pea     %pc@(Lret)      | push our return address
+       bpl     2f
+       negl    %sp@(4)         | store abs(dividend)
+       subql   #2, %sp@        | adjust return address
+2:     jmp     _C_LABEL(__udivsi3)
+       negl    %d1             | negate modulus
+Lret:  movl    %d1, %d0        | move modulus into %d0
+       jmp     %a0@
+#endif /* __mc68010__ */
diff --git a/common/lib/libc/arch/m68k/gen/mulsi3.S b/common/lib/libc/arch/m68k/gen/mulsi3.S
new file mode 100644 (file)
index 0000000..2a34faf
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: mulsi3.S,v 1.2 2006/01/05 22:33:34 he Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)mulsi3.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: mulsi3.S,v 1.2 2006/01/05 22:33:34 he Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* int * int */
+ENTRY(__mulsi3)
+#ifndef __mc68010__
+       movel   %sp@(4),%d0
+       mulsl   %sp@(8),%d0
+#else
+| NB: this requires that __udivsi3 preserve %a0 and return
+| the modulus in %d1:
+       movew   %sp@(6), %d0
+       movel   %d0, %a0        | save B
+       muluw   %sp@(8), %d0    | %d0 holds B * C
+       movew   %sp@(10), %d1
+       movel   %d1, %a1        | save D
+       muluw   %sp@(4), %d1    | %d1 holds A * D
+       addw    %d1, %d0        | %d0 holds (B * C) + (A * D)
+       swap    %d0
+       clrw    %d0             | %d0 holds ((B * C) + (A * D)) << 16
+       exg     %a0, %d0        | restore B
+       movel   %a1, %d1        | restore D
+       muluw   %d1, %d0        | %d0 holds B * D
+       addl    %a0, %d0        | final result
+#endif /* __mc68010__ */
+       rts
diff --git a/common/lib/libc/arch/m68k/gen/udivsi3.S b/common/lib/libc/arch/m68k/gen/udivsi3.S
new file mode 100644 (file)
index 0000000..d2da961
--- /dev/null
@@ -0,0 +1,126 @@
+/*     $NetBSD: udivsi3.S,v 1.2 2006/01/05 22:33:34 he Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)udivsi3.s      5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: udivsi3.S,v 1.2 2006/01/05 22:33:34 he Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* unsigned / unsigned */
+ENTRY(__udivsi3)
+#ifndef __mc68010__
+       movel   %sp@(4),%d0
+       divul   %sp@(8),%d0
+       rts
+#else
+       movel   %d2, %sp@-      | save %d2
+       movel   %sp@(12), %d0   | load divisor
+       movel   %sp@(8), %d1    | load dividend
+
+| first, we divide the divisor and dividend by two until 
+| the divisor fits into 16 bits:
+1:     cmpil   #0x10000, %d0
+       bcs     2f
+       lsrl    #1, %d0
+       lsrl    #1, %d1
+       bra     1b
+2:
+
+| now we can do the divide.  to avoid overflow, we have to 
+| do the divide in two parts, high and low, and add the 
+| results together:
+       movew   %d1, %d2        | save low(dividend)
+       clrw    %d1
+       swap    %d1             | %d1 = dividend >> 16
+       divuw   %d0, %d1        | do the high divide
+       moveal  %d1, %a1        | save high divide result
+       movew   %d2, %d1        | concat(remainder, low(dividend))
+       divuw   %d0, %d1        | do the low divide
+       movel   %a1, %d0        | recover high divide result
+       swap    %d0
+       clrw    %d0             | %d0 = finished high divide result
+       andil   #0xffff, %d1    | %d1 = finished low divide result
+       addl    %d1, %d0        | %d0 = quotient guess
+
+| the quotient we have so far is only a guess.  the divide we 
+| did above was really the divide of some dividendB by some 
+| divisorB, where the following hold:
+|
+| (dividend - divisor) <= dividendB <= dividend
+| (divisor / 2) < divisorB <= divisor
+|
+| so our guess quotient cannot be less than our real desired
+| quotient.  however, it might be one too big.
+|
+| to adjust this quotient, we multiply it by the original 
+| divisor and subtract the result from the original dividend.  
+| if the result is nonnegative, our guessed quotient was 
+| correct, and the subtraction result is our remainder.  
+| if the result is negative, our guessed quotient was one 
+| too big, and the subtraction result plus the original 
+| divisor is our remainder.
+|
+| as in mulsi3, we have to do the multiply in stages to avoid 
+| overflow:
+
+       movel   %sp@(12), %d2   | load divisor
+       swap    %d2
+       movel   %d0, %d1
+       muluw   %d2, %d1        | high(divisor) * low(guess)
+       moveal  %d1, %a1        | save high(divisor) * low(guess)
+       swap    %d2
+       movel   %d0, %d1
+       swap    %d1
+       muluw   %d2, %d1        | low(divisor) * high(guess)
+       addl    %a1, %d1
+       swap    %d1
+       clrw    %d1             | %d1 = finished high multiply result
+       moveal  %d2, %a1        | save original divisor
+       muluw   %d0, %d2        | low(guess) * low(divisor)
+       addl    %d1, %d2        | %d2 = guess * divisor
+       
+       movel   %sp@(8), %d1    | load original dividend
+       subl    %d2, %d1        | subtract
+       bcc     3f
+       subql   #1, %d0         | adjust quotient
+       addl    %a1, %d1        | adjust remainder
+3:     movel   %sp@+, %d2      | restore %d2
+       rts
+#endif /* __mc68010__ */
diff --git a/common/lib/libc/arch/m68k/gen/umodsi3.S b/common/lib/libc/arch/m68k/gen/umodsi3.S
new file mode 100644 (file)
index 0000000..c07b761
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: umodsi3.S,v 1.2 2006/01/05 22:33:34 he Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)umodsi3.s      5.1 (Berkeley) 6/7/90")(
+#else
+       RCSID("$NetBSD: umodsi3.S,v 1.2 2006/01/05 22:33:34 he Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* unsigned % unsigned */
+ENTRY(__umodsi3)
+#ifndef __mc68010__
+       movel   %sp@(4),%d1
+       divull  %sp@(8),%d0:%d1
+       rts
+#else
+| NB: this requires that __udivsi3 preserve the %a0
+| register, and that it returns the modulus in %d1:
+       movel   %sp@+, %a0      | pop the return address
+       jsr     _C_LABEL(__udivsi3)
+       movel   %d1, %d0        | move the modulus into %d0
+       jmp     %a0@            | return
+#endif /* __mc68010__ */
diff --git a/common/lib/libc/arch/m68k/net/htonl.S b/common/lib/libc/arch/m68k/net/htonl.S
new file mode 100644 (file)
index 0000000..05c7ed8
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: htonl.S,v 1.1 2005/12/20 19:28:49 christos Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)htonl.s        5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: htonl.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* netorder = htonl(hostorder) */
+
+ENTRY(htonl)
+       movl    %sp@(4),%d0
+       rts
diff --git a/common/lib/libc/arch/m68k/net/htons.S b/common/lib/libc/arch/m68k/net/htons.S
new file mode 100644 (file)
index 0000000..306aee3
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: htons.S,v 1.1 2005/12/20 19:28:49 christos Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)htons.s        5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: htons.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* hostorder = htons(netorder) */
+
+ENTRY(htons)
+       clrl    %d0
+       movw    %sp@(6),%d0
+       rts
diff --git a/common/lib/libc/arch/m68k/net/ntohl.S b/common/lib/libc/arch/m68k/net/ntohl.S
new file mode 100644 (file)
index 0000000..ed2a5fa
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: ntohl.S,v 1.1 2005/12/20 19:28:49 christos Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)ntohl.s        5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: ntohl.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* hostorder = ntohl(netorder) */
+
+ENTRY(ntohl)
+       movl    %sp@(4),%d0
+       rts
diff --git a/common/lib/libc/arch/m68k/net/ntohs.S b/common/lib/libc/arch/m68k/net/ntohs.S
new file mode 100644 (file)
index 0000000..38438d6
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: ntohs.S,v 1.1 2005/12/20 19:28:49 christos Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)ntohs.s        5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: ntohs.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* hostorder = ntohs(netorder) */
+
+ENTRY(ntohs)
+       clrl    %d0
+       movw    %sp@(6),%d0
+       rts
diff --git a/common/lib/libc/arch/m68k/string/bcmp.S b/common/lib/libc/arch/m68k/string/bcmp.S
new file mode 100644 (file)
index 0000000..80a254c
--- /dev/null
@@ -0,0 +1,167 @@
+/*     $NetBSD: bcmp.S,v 1.2 2008/04/28 20:22:52 martin Exp $  */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)bcmp.s 5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: bcmp.S,v 1.2 2008/04/28 20:22:52 martin Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(bcmp)
+       movl    %sp@(4),%a0             | string 1
+       movl    %sp@(8),%a1             | string 2
+       movl    %sp@(12),%d1            | length
+
+       /*
+        * It isn't worth the overhead of aligning to {long}word boundries
+        * if the string is too short.
+        */
+       cmpl    #8,%d1
+       jlt     Lbcbyte                 
+
+#ifdef __mc68010__
+       /*
+        * The 68010 cannot access a word or long on an odd boundary,
+        * period.  If the source and the destination addresses aren't
+        * of the same evenness, we're forced to do a bytewise compare.
+        */
+       movl    %a0,%d0
+       addl    %a1,%d0
+       btst    #0,%d0
+       jne     Lbcbyte
+#endif /* __mc68010__ */
+       
+       /* word align */
+       movl    %a0,%d0
+       btst    #0,%d0
+       jeq     Lbcalgndw
+       cmpmb   %a0@+,%a1@+
+       jne     Lbcnoteq
+       subql   #1,%d1
+Lbcalgndw:
+       /* long word align */
+       btst    #1,%d0
+       jeq     Lbcalgndl
+       cmpmw   %a0@+,%a1@+
+       jne     Lbcnoteq
+       subql   #2,%d1
+Lbcalgndl:
+       /* compare by 8 longwords */
+       movl    %d1,%d0
+       lsrl    #5,%d0                  | cnt = len / 32
+       jeq     Lbclong                 | if (cnt)
+       andl    #31,%d1                 |       len %= 32
+       subql   #1,%d0                  |       set up for dbf
+Lbc32loop:
+       cmpml   %a0@+,%a1@+             |       compare 8 longwords
+       jne     Lbcnoteq                |       not equal, return non-zero
+       cmpml   %a0@+,%a1@+
+       jne     Lbcnoteq
+       cmpml   %a0@+,%a1@+
+       jne     Lbcnoteq
+       cmpml   %a0@+,%a1@+
+       jne     Lbcnoteq
+       cmpml   %a0@+,%a1@+
+       jne     Lbcnoteq
+       cmpml   %a0@+,%a1@+
+       jne     Lbcnoteq
+       cmpml   %a0@+,%a1@+
+       jne     Lbcnoteq
+       cmpml   %a0@+,%a1@+
+       jne     Lbcnoteq
+       dbf     %d0,Lbc32loop           |       till done
+       clrw    %d0
+       subql   #1,%d0
+       jcc     Lbc32loop
+
+Lbclong:
+       /* compare by longwords */
+       movl    %d1,%d0
+       lsrl    #2,%d0                  | cnt = len / 4
+       jeq     Lbcbyte                 | if (cnt)
+       subql   #1,%d0                  |       set up for dbf
+Lbclloop:
+       cmpml   %a0@+,%a1@+             |       compare a longword
+       jne     Lbcnoteq                |       not equal, return non-zero
+       dbf     %d0,Lbclloop            |       till done
+       andl    #3,%d1                  |       len %= 4
+       jeq     Lbcdone 
+
+       subql   #1,%d1                  | set up for dbf
+Lbcbloop:
+       cmpmb   %a0@+,%a1@+             | compare a byte
+       jne     Lbcnoteq                | not equal, return non-zero
+Lbcbyte:
+       dbf     %d1,Lbcbloop
+Lbcdone:
+       movql   #0,%d0
+       rts
+
+Lbcnoteq:
+       movql   #1,%d0
+       rts
diff --git a/common/lib/libc/arch/m68k/string/bcopy.S b/common/lib/libc/arch/m68k/string/bcopy.S
new file mode 100644 (file)
index 0000000..3082948
--- /dev/null
@@ -0,0 +1,256 @@
+/*     $NetBSD: bcopy.S,v 1.2 2008/04/28 20:22:52 martin Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)bcopy.s        5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: bcopy.S,v 1.2 2008/04/28 20:22:52 martin Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+
+#ifdef MEMCOPY
+ENTRY(memcpy)
+#else
+#ifdef MEMMOVE
+ENTRY(memmove)
+#else
+ENTRY(bcopy)
+#endif
+#endif
+#if defined(MEMCOPY) || defined(MEMMOVE)
+       movl    %sp@(4),%a1             | dest address
+       movl    %sp@(8),%a0             | src address
+#else
+       movl    %sp@(4),%a0             | src address
+       movl    %sp@(8),%a1             | dest address
+#endif
+       movl    %sp@(12),%d1            | count
+
+       cmpl    %a1,%a0                 | src after dest?
+       jlt     Lbcback                 | yes, must copy backwards
+
+       /* 
+        * It isn't worth the overhead of aligning to {long}word boundries
+        * if the string is too short.
+        */
+       cmpl    #8,%d1
+       jlt     Lbcfbyte
+
+#ifdef __mc68010__
+       /*
+        * The 68010 cannot access a word or long on an odd boundary,
+        * period.  If the source and the destination addresses aren't
+        * of the same evenness, we're forced to do a bytewise copy.
+        */
+       movl    %a0,%d0
+       addl    %a1,%d0
+       btst    #0,%d0
+       jne     Lbcfbyte
+#endif /* __mc68010__ */
+       
+       /* word align */
+       movl    %a1,%d0
+       btst    #0,%d0          | if (dst & 1)
+       jeq     Lbcfalgndw      | 
+       movb    %a0@+,%a1@+     |       *(char *)dst++ = *(char *) src++
+       subql   #1,%d1          |       len--
+Lbcfalgndw:
+       /* long word align */
+       btst    #1,%d0          | if (dst & 2)
+       jeq     Lbcfalgndl
+       movw    %a0@+,%a1@+     |       *(short *)dst++ = *(short *) dst++
+       subql   #2,%d1          |       len -= 2
+Lbcfalgndl:
+       /* copy by 8 longwords */
+       movel   %d1,%d0
+       lsrl    #5,%d0          | cnt = len / 32
+       jeq     Lbcflong        | if (cnt)
+       andl    #31,%d1         |       len %= 32
+       subql   #1,%d0          |       set up for dbf
+Lbcf32loop:
+       movl    %a0@+,%a1@+     |       copy 8 long words
+       movl    %a0@+,%a1@+
+       movl    %a0@+,%a1@+
+       movl    %a0@+,%a1@+
+       movl    %a0@+,%a1@+
+       movl    %a0@+,%a1@+
+       movl    %a0@+,%a1@+
+       movl    %a0@+,%a1@+
+       dbf     %d0,Lbcf32loop  |       till done
+       clrw    %d0
+       subql   #1,%d0
+       jcc     Lbcf32loop
+
+Lbcflong:
+       /* copy by longwords */
+       movel   %d1,%d0
+       lsrl    #2,%d0          | cnt = len / 4
+       jeq     Lbcfbyte        | if (cnt)
+       subql   #1,%d0          |       set up for dbf
+Lbcflloop:
+       movl    %a0@+,%a1@+     |       copy longwords
+       dbf     %d0,Lbcflloop   |       til done
+       andl    #3,%d1          |       len %= 4
+       jeq     Lbcdone
+
+       subql   #1,%d1          | set up for dbf
+Lbcfbloop:
+       movb    %a0@+,%a1@+     | copy bytes
+Lbcfbyte:
+       dbf     %d1,Lbcfbloop   | till done
+Lbcdone:
+#if defined(MEMCOPY) || defined(MEMMOVE)
+       movl    %sp@(4),%d0     | dest address
+#if defined(__SVR4_ABI__)
+       moveal  %d0,%a0
+#endif
+#endif
+       rts
+
+
+Lbcback:
+       addl    %d1,%a0         | src pointer to end
+       addl    %d1,%a1         | dest pointer to end
+
+       /* 
+        * It isn't worth the overhead of aligning to {long}word boundries
+        * if the string is too short.
+        */
+       cmpl    #8,%d1
+       jlt     Lbcbbyte
+
+#ifdef __mc68010__
+       /*
+        * The 68010 cannot access a word or long on an odd boundary,
+        * period.  If the source and the destination addresses aren't
+        * of the same evenness, we're forced to do a bytewise copy.
+        */
+       movl    %a0,%d0
+       addl    %a1,%d0
+       btst    #0,%d0
+       jne     Lbcbbyte
+#endif /* __mc68010__ */
+       
+       /* word align */
+       movl    %a1,%d0
+       btst    #0,%d0          | if (dst & 1)
+       jeq     Lbcbalgndw      | 
+       movb    %a0@-,%a1@-     |       *(char *)dst-- = *(char *) src--
+       subql   #1,%d1          |       len--
+Lbcbalgndw:
+       /* long word align */
+       btst    #1,%d0          | if (dst & 2)
+       jeq     Lbcbalgndl
+       movw    %a0@-,%a1@-     |       *(short *)dst-- = *(short *) dst--
+       subql   #2,%d1          |       len -= 2
+Lbcbalgndl:
+       /* copy by 8 longwords */
+       movel   %d1,%d0
+       lsrl    #5,%d0          | cnt = len / 32
+       jeq     Lbcblong        | if (cnt)
+       andl    #31,%d1         |       len %= 32
+       subql   #1,%d0          |       set up for dbf
+Lbcb32loop:
+       movl    %a0@-,%a1@-     |       copy 8 long words
+       movl    %a0@-,%a1@-
+       movl    %a0@-,%a1@-
+       movl    %a0@-,%a1@-
+       movl    %a0@-,%a1@-
+       movl    %a0@-,%a1@-
+       movl    %a0@-,%a1@-
+       movl    %a0@-,%a1@-
+       dbf     %d0,Lbcb32loop  |       till done
+       clrw    %d0
+       subql   #1,%d0
+       jcc     Lbcb32loop
+       
+Lbcblong:
+       /* copy by longwords */
+       movel   %d1,%d0
+       lsrl    #2,%d0          | cnt = len / 4
+       jeq     Lbcbbyte        | if (cnt)
+       subql   #1,%d0          |       set up for dbf
+Lbcblloop:
+       movl    %a0@-,%a1@-     |       copy longwords
+       dbf     %d0,Lbcblloop   |       til done
+       andl    #3,%d1          |       len %= 4
+       jeq     Lbcdone
+
+       subql   #1,%d1          | set up for dbf
+Lbcbbloop:
+       movb    %a0@-,%a1@-     | copy bytes
+Lbcbbyte:
+       dbf     %d1,Lbcbbloop   | till done
+
+#if defined(MEMCOPY) || defined(MEMMOVE)
+       movl    %sp@(4),%d0     | dest address
+#if defined(__SVR4_ABI__)
+       moveal  %d0,%a0
+#endif
+#endif
+       rts
diff --git a/common/lib/libc/arch/m68k/string/bzero.S b/common/lib/libc/arch/m68k/string/bzero.S
new file mode 100644 (file)
index 0000000..4d04ddf
--- /dev/null
@@ -0,0 +1,141 @@
+/*     $NetBSD: bzero.S,v 1.2 2008/04/28 20:22:52 martin Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)bzero.s        5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: bzero.S,v 1.2 2008/04/28 20:22:52 martin Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(bzero)
+       movl    %d2,%sp@-
+       movl    %sp@(8),%a0             | destination
+       movl    %sp@(12),%d1            | count
+
+       movql   #0,%d2
+
+       /* 
+        * It isn't worth the overhead of aligning to {long}word boundries
+        * if the string is too short.
+        */
+       cmpl    #8,%d1
+       jlt     Lbzbyte
+
+       /* word align */
+       movl    %a0,%d0
+       btst    #0,%d0                  | if (dst & 1)
+       jeq     Lbzalgndw               | 
+       movb    %d2,%a0@+               |       *(char *)dst++ = 0
+       subql   #1,%d1                  |       len--
+Lbzalgndw:
+       /* long word align */
+       btst    #1,%d0                  | if (dst & 2)
+       jeq     Lbzalgndl               |
+       movw    %d2,%a0@+               |       *(short *)dst++ = 0
+       subql   #2,%d1                  |       len -= 2
+Lbzalgndl:
+       /* zero by 8 longwords */
+       movel   %d1,%d0
+       lsrl    #5,%d0                  | cnt = len / 32
+       jeq     Lbzlong                 | if (cnt)
+       andl    #31,%d1                 |       len %= 32
+       subql   #1,%d0                  |       set up for dbf
+Lbz32loop:
+       movl    %d2,%a0@+               |       zero 8 long words
+       movl    %d2,%a0@+
+       movl    %d2,%a0@+
+       movl    %d2,%a0@+
+       movl    %d2,%a0@+
+       movl    %d2,%a0@+
+       movl    %d2,%a0@+
+       movl    %d2,%a0@+
+       dbf     %d0,Lbz32loop           |       till done
+       clrw    %d0
+       subql   #1,%d0
+       jcc     Lbz32loop
+
+Lbzlong:
+       /* copy by longwords */
+       movel   %d1,%d0
+       lsrl    #2,%d0                  | cnt = len / 4
+       jeq     Lbzbyte                 | if (cnt)
+       subql   #1,%d0                  |       set up for dbf
+Lbzlloop:
+       movl    %d2,%a0@+               |       clear longwords
+       dbf     %d0,Lbzlloop            |       till done
+       andl    #3,%d1                  |       len %= 4
+       jeq     Lbzdone
+
+       subql   #1,%d1                  | set up for dbf
+Lbzbloop:
+       movb    %d2,%a0@+               | zero bytes
+Lbzbyte:
+       dbf     %d1,Lbzbloop            | till done
+Lbzdone:
+       movl    %sp@+,%d2
+       rts
diff --git a/common/lib/libc/arch/m68k/string/ffs.S b/common/lib/libc/arch/m68k/string/ffs.S
new file mode 100644 (file)
index 0000000..f29ff47
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: ffs.S,v 1.1 2005/12/20 19:28:49 christos Exp $ */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)ffs.s  5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: ffs.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* bit = ffs(value) */
+
+#ifndef        __mc68010__
+
+ENTRY(ffs)
+       movl    %sp@(4),%d0
+       movl    %d0,%d1
+       negl    %d0
+       andl    %d0,%d1
+       movql   #32,%d0
+       bfffo   %d1{#0:#32},%d1
+       subl    %d1,%d0
+       rts
+
+#else  /* __mc68010__ */
+
+ENTRY(ffs)
+       movl    %sp@(4),%d0
+       jeq     L2
+       movql   #31,%d1
+L1:    
+       lsrl    #1,%d0
+       dbcs    %d1,L1
+       movql   #32,%d0
+       subl    %d1,%d0
+L2:
+       rts
+
+#endif /* __mc68010__ */
diff --git a/common/lib/libc/arch/m68k/string/memcmp.S b/common/lib/libc/arch/m68k/string/memcmp.S
new file mode 100644 (file)
index 0000000..760a1ff
--- /dev/null
@@ -0,0 +1,100 @@
+/*     $NetBSD: memcmp.S,v 1.1 2005/12/20 19:28:49 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)bcmp.s 5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: memcmp.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* memcmp(s1, s2, n) */
+
+/*
+ * This is probably not the best we can do, but it is still 2-10 times
+ * faster than the C version in the portable gen directory.
+ *
+ * Things that might help:
+ *     - longword align when possible (only on the 68020)
+ *     - use nested DBcc instructions or use one and limit size to 64K
+ */
+ENTRY(memcmp)
+       movl    %sp@(4),%a0             | string 1
+       movl    %sp@(8),%a1             | string 2
+       movl    %sp@(12),%d0            | length
+       jeq     bcdone                  | if zero, nothing to do
+       movl    %a0,%d1
+       btst    #0,%d1                  | string 1 address odd?
+       jeq     bceven                  | no, skip alignment
+       cmpmb   %a0@+,%a1@+             | yes, compare a byte
+       jne     bcnoteq                 | not equal, return non-zero
+       subql   #1,%d0                  | adjust count
+       jeq     bcdone                  | count 0, reutrn zero
+bceven:
+       movl    %a1,%d1
+       btst    #0,%d1                  | string 2 address odd?
+       jne     bcbloop                 | yes, no hope for alignment, compare bytes
+       movl    %d0,%d1                 | no, both even
+       lsrl    #2,%d1                  | convert count to longword count
+       jeq     bcbloop                 | count 0, skip longword loop
+bclloop:
+       cmpml   %a0@+,%a1@+             | compare a longword
+       jne     bcnoteql                | not equal, return non-zero
+       subql   #1,%d1                  | adjust count
+       jne     bclloop                 | still more, keep comparing
+       andl    #3,%d0                  | what remains
+       jeq     bcdone                  | nothing, all done
+bcbloop:
+       cmpmb   %a0@+,%a1@+             | compare a byte
+       jne     bcnoteq                 | not equal, return non-zero
+       subql   #1,%d0                  | adjust count
+       jne     bcbloop                 | still more, keep going
+       rts
+bcnoteql:
+       subql   #4,%a0
+       subql   #4,%a1
+       movl    #4,%d0
+       jra     bcbloop
+bcnoteq:
+       clrl    %d0
+       clrl    %d1
+       movb    %a0@-,%d0
+       movb    %a1@-,%d1
+       subl    %d1,%d0
+bcdone:
+       rts
diff --git a/common/lib/libc/arch/m68k/string/memcpy.S b/common/lib/libc/arch/m68k/string/memcpy.S
new file mode 100644 (file)
index 0000000..11245b4
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: memcpy.S,v 1.1 2005/12/20 19:28:49 christos Exp $      */
+
+#define MEMCOPY
+#include "bcopy.S"
diff --git a/common/lib/libc/arch/m68k/string/memmove.S b/common/lib/libc/arch/m68k/string/memmove.S
new file mode 100644 (file)
index 0000000..d9d5186
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: memmove.S,v 1.1 2005/12/20 19:28:49 christos Exp $     */
+
+#define MEMMOVE
+#include "bcopy.S"
diff --git a/common/lib/libc/arch/m68k/string/memset.S b/common/lib/libc/arch/m68k/string/memset.S
new file mode 100644 (file)
index 0000000..ff5d5b8
--- /dev/null
@@ -0,0 +1,162 @@
+/*     $NetBSD: memset.S,v 1.2 2008/04/28 20:22:52 martin Exp $        */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)bzero.s        5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: memset.S,v 1.2 2008/04/28 20:22:52 martin Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(memset)
+       movl    %d2,%sp@-
+       movl    %sp@(8),%a0             | destination
+       movl    %sp@(16),%d1            | count
+       movb    %sp@(15),%d2            | character
+
+       /* 
+        * It isn't worth the overhead of aligning to {long}word boundries
+        * if the string is too short.
+        */
+       cmpl    #15,%d1
+       jlt     Lbzbyte
+
+       clrl    %d0                     | replicate byte to fill longword
+       movb    %d2,%d0
+       movl    %d0,%d2
+       lsll    #8,%d0
+       orl     %d0,%d2
+       lsll    #8,%d0 
+       orl     %d0,%d2
+       lsll    #8,%d0
+       orl     %d0,%d2
+
+       /* word align */
+       movl    %a0,%d0
+       btst    #0,%d0                  | if (dst & 1)
+       jeq     Lbzalgndw               | 
+       movb    %d2,%a0@+               |       *(char *)dst++ = X
+       subql   #1,%d1                  |       len--
+       addql   #1,%d0
+Lbzalgndw:
+#ifndef        __mc68010__
+       /* long word align */
+       btst    #1,%d0                  | if (dst & 2)
+       jeq     Lbzalgndl               |
+       movw    %d2,%a0@+               |       *(short *)dst++ = X
+       subql   #2,%d1                  |       len -= 2
+Lbzalgndl:
+       /* set by 8 longwords */
+       movel   %d1,%d0
+       lsrl    #5,%d0                  | cnt = len / 32
+       jeq     Lbzlong                 | if (cnt)
+       andl    #31,%d1                 |       len %= 32
+       subql   #1,%d0                  |       set up for dbf
+Lbz32loop:
+       movl    %d2,%a0@+               |       set 8 long words
+       movl    %d2,%a0@+
+       movl    %d2,%a0@+
+       movl    %d2,%a0@+
+       movl    %d2,%a0@+
+       movl    %d2,%a0@+
+       movl    %d2,%a0@+
+       movl    %d2,%a0@+
+       dbf     %d0,Lbz32loop           |       till done
+       clrw    %d0
+       subql   #1,%d0
+       jcc     Lbz32loop
+#endif /* !__mc68010__ */
+
+Lbzlong:
+       /* set by longwords */
+       movel   %d1,%d0
+       lsrl    #2,%d0                  | cnt = len / 4
+       jeq     Lbzbyte                 | if (cnt)
+       subql   #1,%d0                  |       set up for dbf
+Lbzlloop:
+       movl    %d2,%a0@+               |       clear longwords
+       dbf     %d0,Lbzlloop            |       till done
+#ifdef __mc68010__
+       clrw    %d0
+       subql   #1,%d0
+       jcc     Lbzlloop
+#endif /* __mc68010__ */
+       andl    #3,%d1                  |       len %= 4
+       jeq     Lbzdone
+
+       subql   #1,%d1                  | set up for dbf
+Lbzbloop:
+       movb    %d2,%a0@+               | set bytes
+Lbzbyte:
+       dbf     %d1,Lbzbloop            | till done
+Lbzdone:
+       movl    %sp@(8),%d0             | return destination
+#ifdef __SVR4_ABI__
+       moveal  %d0,%a0
+#endif
+       movl    %sp@+,%d2
+       rts
diff --git a/common/lib/libc/arch/m68k/string/strcat.S b/common/lib/libc/arch/m68k/string/strcat.S
new file mode 100644 (file)
index 0000000..0f144d1
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: strcat.S,v 1.1 2005/12/20 19:28:49 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)strcpy.s       5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: strcat.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(strcat)
+       movl    %sp@(8),%a0             | a0 = fromaddr
+       movl    %sp@(4),%d0             | return value is toaddr
+       movl    %d0,%a1                 | a1 = toaddr
+Lslloop:
+       tstb    %a1@+                   | null?
+       jne     Lslloop                 | no, keep going
+       subql   #1,%a1
+Lscloop:
+       movb    %a0@+,%a1@+             | copy a byte
+       jne     Lscloop                 | copied non-null, keep going
+#ifdef __SVR4_ABI__
+       moveal  %d0,%a0
+#endif
+       rts
diff --git a/common/lib/libc/arch/m68k/string/strchr.S b/common/lib/libc/arch/m68k/string/strchr.S
new file mode 100644 (file)
index 0000000..10412c5
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: strchr.S,v 1.2 2009/07/17 19:37:57 dsl Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)index.s        5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: strchr.S,v 1.2 2009/07/17 19:37:57 dsl Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(strchr)
+       movl    %sp@(4),%a0             | string
+       movb    %sp@(11),%d0            | char to look for
+ixloop:
+       cmpb    %a0@,%d0                | found our char?
+       jeq     ixfound                 | yes, break out
+       tstb    %a0@+                   | null?
+       jne     ixloop                  | no, keep going
+       moveq   #0,%d0                  | not found, return null
+#ifdef __SVR4_ABI__
+       moveal  %d0,%a0
+#endif
+       rts
+ixfound:
+       movl    %a0,%d0                 | found, return pointer
+       rts
+
+STRONG_ALIAS(index,strchr)
diff --git a/common/lib/libc/arch/m68k/string/strcmp.S b/common/lib/libc/arch/m68k/string/strcmp.S
new file mode 100644 (file)
index 0000000..04bdbfc
--- /dev/null
@@ -0,0 +1,71 @@
+/*     $NetBSD: strcmp.S,v 1.2 2008/04/28 20:22:52 martin Exp $        */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Hiroshi Horimoto <horimoto@cs-aoi.cs.sist.ac.jp> and
+ * by J.T. Conklin <jtc@NetBSD.org>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: strcmp.S,v 1.2 2008/04/28 20:22:52 martin Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(strcmp)
+       movl    %sp@(4),%a0
+       movl    %sp@(8),%a1
+L1:                            /* unrolled by 4 for 680[23]0's */
+       movb    %a0@+,%d1
+       jeq     L2
+       subb    %a1@+,%d1
+       jne     L3
+
+       movb    %a0@+,%d1
+       jeq     L2
+       subb    %a1@+,%d1
+       jne     L3
+
+       movb    %a0@+,%d1
+       jeq     L2
+       subb    %a1@+,%d1
+       jne     L3
+
+       movb    %a0@+,%d1
+       jeq     L2
+       subb    %a1@+,%d1
+       jeq     L1
+
+L3:    scs     %d0
+       EXTBL(%d0)
+       movb    %d1,%d0
+       rts
+
+L2:    movq    #0,%d0
+       movb    %a1@,%d0
+       negl    %d0
+       rts
diff --git a/common/lib/libc/arch/m68k/string/strcpy.S b/common/lib/libc/arch/m68k/string/strcpy.S
new file mode 100644 (file)
index 0000000..2aa681f
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: strcpy.S,v 1.1 2005/12/20 19:28:49 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)strcpy.s       5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: strcpy.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(strcpy)
+       movl    %sp@(8),%a0             | a0 = fromaddr
+       movl    %sp@(4),%d0             | return value is toaddr
+       movl    %d0,%a1                 | a1 = toaddr
+Lscloop:
+       movb    %a0@+,%a1@+             | copy a byte
+       jne     Lscloop                 | copied non-null, keep going
+#ifdef __SVR4_ABI__
+       moveal  %d0,%a0
+#endif
+       rts
diff --git a/common/lib/libc/arch/m68k/string/strlen.S b/common/lib/libc/arch/m68k/string/strlen.S
new file mode 100644 (file)
index 0000000..9a9a589
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: strlen.S,v 1.1 2005/12/20 19:28:49 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)strlen.s       5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: strlen.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(strlen)
+       movl    %sp@(4),%a0             | string
+       movl    %a0,%d0
+       notl    %d0
+Lslloop:
+       tstb    %a0@+                   | null?
+       jne     Lslloop                 | no, keep going
+       addl    %a0,%d0
+       rts
diff --git a/common/lib/libc/arch/m68k/string/strncmp.S b/common/lib/libc/arch/m68k/string/strncmp.S
new file mode 100644 (file)
index 0000000..7bee4c6
--- /dev/null
@@ -0,0 +1,78 @@
+/*     $NetBSD: strncmp.S,v 1.2 2008/04/28 20:22:52 martin Exp $       */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Hiroshi Horimoto <horimoto@cs-aoi.cs.sist.ac.jp> and
+ * by J.T. Conklin <jtc@NetBSD.org>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: strncmp.S,v 1.2 2008/04/28 20:22:52 martin Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(strncmp)
+       movl    %sp@(12),%d0
+       jeq     L4
+       movl    %sp@(4),%a0
+       movl    %sp@(8),%a1
+L1:                            /* unroll by 4 for m680[23]0's */
+       movb    %a0@+,%d1
+       jeq     L2
+       subb    %a1@+,%d1
+       jne     L3
+       subql   #1,%d0
+       jeq     L4
+
+       movb    %a0@+,%d1
+       jeq     L2
+       subb    %a1@+,%d1
+       jne     L3
+       subql   #1,%d0
+       jeq     L4
+
+       movb    %a0@+,%d1
+       jeq     L2
+       subb    %a1@+,%d1
+       jne     L3
+       subql   #1,%d0
+       jeq     L4
+
+       movb    %a0@+,%d1
+       jeq     L2
+       subb    %a1@+,%d1
+       jne     L3
+       subql   #1,%d0
+       jne     L1
+L4:    rts
+
+L2:    subb    %a1@,%d1
+L3:    scs     %d0
+       EXTBL(%d0)
+       movb    %d1,%d0
+       rts
diff --git a/common/lib/libc/arch/m68k/string/strncpy.S b/common/lib/libc/arch/m68k/string/strncpy.S
new file mode 100644 (file)
index 0000000..d08c95b
--- /dev/null
@@ -0,0 +1,73 @@
+/*     $NetBSD: strncpy.S,v 1.1 2005/12/20 19:28:49 christos Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)strncpy.s      5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: strncpy.S,v 1.1 2005/12/20 19:28:49 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(strncpy)
+       movl    %sp@(4),%d0             | return value is toaddr
+       movl    %sp@(12),%d1            | count
+       jeq     Lscdone                 | nothing to do
+       movl    %sp@(8),%a0             | a0 = fromaddr
+       movl    %d0,%a1                 | a1 = toaddr
+       subql   #1,%d1
+Lscloop:
+       movb    %a0@+,%a1@+             | copy a byte
+       dbeq    %d1,Lscloop             | loop through low word of d1
+       jeq     Lscpadding              | copied null, padding if necessary
+       clrw    %d1                     | clear low word of d1
+       subql   #1,%d1                  | adjust count for long copies
+       jcc     Lscloop                 | more room, keep going
+Lscdone:
+#ifdef __SVR4_ABI__
+       moveal  %d0,%a0
+#endif
+       rts
+
+Lscploop:
+       clrb    %a1@+                   | clear a byte
+       dbra    %d1,Lscploop            | keep going
+       clrw    %d1
+Lscpadding:
+       subql   #1,%d1
+       jcc     Lscploop
+       jra     Lscdone
diff --git a/common/lib/libc/arch/m68k/string/strrchr.S b/common/lib/libc/arch/m68k/string/strrchr.S
new file mode 100644 (file)
index 0000000..c9b5f6b
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: strrchr.S,v 1.2 2009/07/17 19:37:57 dsl Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)rindex.s       5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: strrchr.S,v 1.2 2009/07/17 19:37:57 dsl Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(strrchr)
+       movl    %sp@(4),%a1             | string
+       movb    %sp@(11),%d0            | char to look for
+       subl    %a0,%a0                 | clear rindex pointer
+rixloop:
+       cmpb    %a1@,%d0                | found our char?
+       jne     rixnope                 | no, check for null
+       movl    %a1,%a0                 | yes, remember location
+rixnope:
+       tstb    %a1@+                   | null?
+       jne     rixloop                 | no, keep going
+       movl    %a0,%d0                 | return value
+       rts
+
+STRONG_ALIAS(rindex,strrchr)
diff --git a/common/lib/libc/arch/mips/atomic/Makefile.inc b/common/lib/libc/arch/mips/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..aa0ef90
--- /dev/null
@@ -0,0 +1,45 @@
+#      $NetBSD: Makefile.inc,v 1.10 2009/12/14 00:38:59 matt Exp $
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "c" || ${LIB} == "pthread" \
+       || ${LIB} == "rump")
+
+.if ${MACHINE_ARCH:Mmips64*} == ""
+SRCS+= atomic_add_32_cas.c atomic_add_32_nv_cas.c \
+       atomic_and_32_cas.c atomic_and_32_nv_cas.c \
+       atomic_dec_32_cas.c atomic_dec_32_nv_cas.c \
+       atomic_inc_32_cas.c atomic_inc_32_nv_cas.c \
+       atomic_or_32_cas.c atomic_or_32_nv_cas.c \
+       atomic_swap_32_cas.c \
+       atomic_add_64_cas.c atomic_add_64_nv_cas.c \
+       atomic_and_64_cas.c atomic_and_64_nv_cas.c \
+       atomic_dec_64_cas.c atomic_dec_64_nv_cas.c \
+       atomic_inc_64_cas.c atomic_inc_64_nv_cas.c \
+       atomic_or_64_cas.c atomic_or_64_nv_cas.c \
+       atomic_swap_64_cas.c
+
+CPPFLAGS+= -D__HAVE_ASM_ATOMIC_CAS_UP
+
+.else
+SRCS+= atomic_add.S atomic_dec.S atomic_inc.S
+SRCS+= atomic_and.S atomic_or.S
+SRCS+= atomic_swap.S
+.endif
+
+SRCS+= membar_ops.S
+.endif
+
+.if defined(LIB) && (${LIB} == "c" || ${LIB} == "pthread")
+
+.if ${MACHINE_ARCH:Mmips64*} == ""
+SRCS+= atomic_init_testset.c atomic_cas_up.S
+.else
+SRCS+= atomic_cas.S atomic_init_cas.c
+.endif
+
+.endif
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "rump")
+
+SRCS+= membar_ops.S
+
+.endif
diff --git a/common/lib/libc/arch/mips/atomic/atomic_add.S b/common/lib/libc/arch/mips/atomic/atomic_add.S
new file mode 100644 (file)
index 0000000..298ad24
--- /dev/null
@@ -0,0 +1,111 @@
+/*     $NetBSD: atomic_add.S,v 1.2 2009/12/14 00:38:59 matt Exp $      */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#include <machine/asm.h>
+#include "atomic_op_asm.h"
+
+RCSID("$NetBSD: atomic_add.S,v 1.2 2009/12/14 00:38:59 matt Exp $")
+
+       .text
+       .set    noat
+       .set    noreorder
+       .set    nomacro
+
+LEAF(_atomic_add_32)
+1:     INT_LL          t0, 0(a0)
+        nop
+       INT_ADDU        t0, a1
+       INT_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_32, _atomic_add_32)
+
+LEAF(_atomic_add_32_nv)
+1:     INT_LL          v0, 0(a0)
+        nop
+       INT_ADDU        v0, a1
+       move            t0, v0
+       INT_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_32_nv, _atomic_add_32_nv)
+
+#if !defined(__mips_o32)
+LEAF(_atomic_add_64)
+1:     REG_LL          t0, 0(a0)
+        nop
+       REG_ADDU        t0, a1
+       REG_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_add_64)
+ATOMIC_OP_ALIAS(atomic_add_64, _atomic_add_64)
+
+LEAF(_atomic_add_64_nv)
+1:     REG_LL          v0, 0(a0)
+        nop
+       REG_ADDU        v0, a1
+       move            t0, v0
+       REG_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_add_64_nv)
+ATOMIC_OP_ALIAS(atomic_add_64_nv, _atomic_add_64_nv)
+#endif
+
+#ifdef _LP64
+STRONG_ALIAS(_atomic_add_long,         _atomic_add_64)
+STRONG_ALIAS(_atomic_add_long_nv,      _atomic_add_64_nv)
+STRONG_ALIAS(_atomic_add_ptr,          _atomic_add_64)
+STRONG_ALIAS(_atomic_add_ptr_nv,       _atomic_add_64_nv)
+#else
+STRONG_ALIAS(_atomic_add_long,         _atomic_add_32)
+STRONG_ALIAS(_atomic_add_long_nv,      _atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_ptr,          _atomic_add_32)
+STRONG_ALIAS(_atomic_add_ptr_nv,       _atomic_add_32_nv)
+#endif
+STRONG_ALIAS(_atomic_add_int,          _atomic_add_32)
+STRONG_ALIAS(_atomic_add_int_nv,       _atomic_add_32_nv)
+
+ATOMIC_OP_ALIAS(atomic_add_int,                _atomic_add_int)
+ATOMIC_OP_ALIAS(atomic_add_int_nv,     _atomic_add_int_nv)
+ATOMIC_OP_ALIAS(atomic_add_ptr,                _atomic_add_ptr)
+ATOMIC_OP_ALIAS(atomic_add_ptr_nv,     _atomic_add_ptr_nv)
+ATOMIC_OP_ALIAS(atomic_add_long,       _atomic_add_long)
+ATOMIC_OP_ALIAS(atomic_add_long_nv,    _atomic_add_long_nv)
diff --git a/common/lib/libc/arch/mips/atomic/atomic_and.S b/common/lib/libc/arch/mips/atomic/atomic_and.S
new file mode 100644 (file)
index 0000000..7d233d0
--- /dev/null
@@ -0,0 +1,105 @@
+/*     $NetBSD: atomic_and.S,v 1.2 2009/12/14 00:38:59 matt Exp $      */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#include <machine/asm.h>
+#include "atomic_op_asm.h"
+
+RCSID("$NetBSD: atomic_and.S,v 1.2 2009/12/14 00:38:59 matt Exp $")
+
+       .text
+       .set    noat
+       .set    noreorder
+       .set    nomacro
+
+LEAF(_atomic_and_32)
+1:     INT_LL          t0, 0(a0)
+        nop
+       and             t0, a1
+       INT_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_32, _atomic_and_32)
+
+LEAF(_atomic_and_32_nv)
+1:     INT_LL          v0, 0(a0)
+        nop
+       and             v0, a1
+       move            t0, v0
+       INT_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_and_32_nv)
+ATOMIC_OP_ALIAS(atomic_and_32_nv, _atomic_and_32_nv)
+
+#if !defined(__mips_o32)
+LEAF(_atomic_and_64)
+1:     REG_LL          t0, 0(a0)
+        nop
+       and             t0, a1
+       REG_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_and_64)
+ATOMIC_OP_ALIAS(atomic_and_64, _atomic_and_64)
+
+LEAF(_atomic_and_64_nv)
+1:     REG_LL          v0, 0(a0)
+        nop
+       and             v0, a1
+       move            t0, v0
+       REG_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_and_64_nv)
+ATOMIC_OP_ALIAS(atomic_and_64_nv, _atomic_and_64_nv)
+#endif
+
+#ifdef _LP64
+STRONG_ALIAS(_atomic_and_ulong,                _atomic_and_64)
+STRONG_ALIAS(_atomic_and_ulong_nv,     _atomic_and_64_nv)
+#else
+STRONG_ALIAS(_atomic_and_ulong,                _atomic_and_32)
+STRONG_ALIAS(_atomic_and_ulong_nv,     _atomic_and_32_nv)
+#endif
+STRONG_ALIAS(_atomic_and_uint,         _atomic_and_32)
+STRONG_ALIAS(_atomic_and_uint_nv,      _atomic_and_32_nv)
+
+ATOMIC_OP_ALIAS(atomic_and_uint,       _atomic_and_uint)
+ATOMIC_OP_ALIAS(atomic_and_uint_nv,    _atomic_and_uint_nv)
+ATOMIC_OP_ALIAS(atomic_and_ulong,      _atomic_and_ulong)
+ATOMIC_OP_ALIAS(atomic_and_ulong_nv,   _atomic_and_ulong_nv)
diff --git a/common/lib/libc/arch/mips/atomic/atomic_cas.S b/common/lib/libc/arch/mips/atomic/atomic_cas.S
new file mode 100644 (file)
index 0000000..d1747f8
--- /dev/null
@@ -0,0 +1,93 @@
+/*     $NetBSD: atomic_cas.S,v 1.2 2009/12/14 00:39:00 matt Exp $      */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#include <machine/asm.h>
+#include "atomic_op_asm.h"
+
+RCSID("$NetBSD: atomic_cas.S,v 1.2 2009/12/14 00:39:00 matt Exp $")
+
+       .text
+       .set    noat
+       .set    noreorder
+       .set    nomacro
+
+LEAF(_atomic_cas_32)
+1:     INT_LL          v0, 0(a0)
+        nop
+       bne             v0, a1, 2f
+        nop
+       move            t0, a2
+       INT_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       move            v0, a1
+2:
+       j               ra
+        nop
+END(_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_32, _atomic_cas_32)
+
+#if !defined(__mips_o32)
+LEAF(_atomic_cas_64)
+1:     REG_LL          v0, 0(a0)
+        nop
+       bne             v0, a1, 2f
+        nop
+       move            t0, a2
+       REG_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       move            v0, a1
+2:
+       j               ra
+        nop
+END(_atomic_cas_64)
+ATOMIC_OP_ALIAS(atomic_cas_64, _atomic_cas_64)
+#endif
+
+#ifdef _LP64
+STRONG_ALIAS(_atomic_cas_ptr,          _atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ptr_ni,       _atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ulong,                _atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ulong_ni,     _atomic_cas_64)
+#else
+STRONG_ALIAS(_atomic_cas_ptr,          _atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ptr_ni,       _atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong,                _atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong_ni,     _atomic_cas_32)
+#endif
+STRONG_ALIAS(_atomic_cas_uint,         _atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_uint_ni,      _atomic_cas_32)
+
+ATOMIC_OP_ALIAS(atomic_cas_ptr,                _atomic_cas_ptr)
+ATOMIC_OP_ALIAS(atomic_cas_ptr_ni,     _atomic_cas_ptr_ni)
+ATOMIC_OP_ALIAS(atomic_cas_uint,       _atomic_cas_uint)
+ATOMIC_OP_ALIAS(atomic_cas_uint_ni,    _atomic_cas_uint_ni)
+ATOMIC_OP_ALIAS(atomic_cas_ulong,      _atomic_cas_ulong)
+ATOMIC_OP_ALIAS(atomic_cas_ulong_ni,   _atomic_cas_ulong_ni)
diff --git a/common/lib/libc/arch/mips/atomic/atomic_cas_up.S b/common/lib/libc/arch/mips/atomic/atomic_cas_up.S
new file mode 100644 (file)
index 0000000..6f3040d
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: atomic_cas_up.S,v 1.2 2008/05/25 15:56:12 chs Exp $    */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/ras.h>
+#include "atomic_op_asm.h"
+
+       .text
+       .set    noat
+       .set    noreorder
+
+LEAF(_atomic_cas_up)
+       .hidden _C_LABEL(_atomic_cas_up)
+RAS_START_ASM_HIDDEN(_atomic_cas)
+       lw      t0, (a0)
+        nop
+       bne     t0, a1, 1f
+        nop
+       sw      a2, (a0)
+RAS_END_ASM_HIDDEN(_atomic_cas)
+       j       ra
+        addu   v0, zero, a1
+1:
+       j       ra
+        addu   v0, zero, t0
+END(_atomic_cas_up)
diff --git a/common/lib/libc/arch/mips/atomic/atomic_dec.S b/common/lib/libc/arch/mips/atomic/atomic_dec.S
new file mode 100644 (file)
index 0000000..f44850f
--- /dev/null
@@ -0,0 +1,111 @@
+/*     $NetBSD: atomic_dec.S,v 1.2 2009/12/14 00:39:00 matt Exp $      */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#include <machine/asm.h>
+#include "atomic_op_asm.h"
+
+RCSID("$NetBSD: atomic_dec.S,v 1.2 2009/12/14 00:39:00 matt Exp $")
+
+       .text
+       .set    noat
+       .set    noreorder
+       .set    nomacro
+
+LEAF(_atomic_dec_32)
+1:     INT_LL          t0, 0(a0)
+        nop
+       INT_ADDU        t0, -1
+       INT_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_32, _atomic_dec_32)
+
+LEAF(_atomic_dec_32_nv)
+1:     INT_LL          v0, 0(a0)
+        nop
+       INT_ADDU        v0, -1
+       move            t0, v0
+       INT_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_32_nv, _atomic_dec_32_nv)
+
+#if !defined(__mips_o32)
+LEAF(_atomic_dec_64)
+1:     REG_LL          t0, 0(a0)
+        nop
+       REG_ADDU        t0, -1
+       REG_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_dec_64)
+ATOMIC_OP_ALIAS(atomic_dec_64, _atomic_dec_64)
+
+LEAF(_atomic_dec_64_nv)
+1:     REG_LL          v0, 0(a0)
+        nop
+       REG_ADDU        v0, -1
+       move            t0, v0
+       REG_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_dec_64_nv)
+ATOMIC_OP_ALIAS(atomic_dec_64_nv, _atomic_dec_64_nv)
+#endif
+
+#ifdef _LP64
+STRONG_ALIAS(_atomic_dec_ptr,          _atomic_dec_64)
+STRONG_ALIAS(_atomic_dec_ptr_nv,       _atomic_dec_64_nv)
+STRONG_ALIAS(_atomic_dec_ulong,                _atomic_dec_64)
+STRONG_ALIAS(_atomic_dec_ulong_nv,     _atomic_dec_64_nv)
+#else
+STRONG_ALIAS(_atomic_dec_ptr,          _atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_ptr_nv,       _atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_ulong,                _atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_ulong_nv,     _atomic_dec_32_nv)
+#endif
+STRONG_ALIAS(_atomic_dec_uint,         _atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_uint_nv,      _atomic_dec_32_nv)
+
+ATOMIC_OP_ALIAS(atomic_dec_ptr,                _atomic_dec_ptr)
+ATOMIC_OP_ALIAS(atomic_dec_ptr_nv,     _atomic_dec_ptr_nv)
+ATOMIC_OP_ALIAS(atomic_dec_uint,       _atomic_dec_uint)
+ATOMIC_OP_ALIAS(atomic_dec_uint_nv,    _atomic_dec_uint_nv)
+ATOMIC_OP_ALIAS(atomic_dec_ulong,      _atomic_dec_ulong)
+ATOMIC_OP_ALIAS(atomic_dec_ulong_nv,   _atomic_dec_ulong_nv)
diff --git a/common/lib/libc/arch/mips/atomic/atomic_inc.S b/common/lib/libc/arch/mips/atomic/atomic_inc.S
new file mode 100644 (file)
index 0000000..5ab8e49
--- /dev/null
@@ -0,0 +1,111 @@
+/*     $NetBSD: atomic_inc.S,v 1.2 2009/12/14 00:39:00 matt Exp $      */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#include <machine/asm.h>
+#include "atomic_op_asm.h"
+
+RCSID("$NetBSD: atomic_inc.S,v 1.2 2009/12/14 00:39:00 matt Exp $")
+
+       .text
+       .set    noat
+       .set    noreorder
+       .set    nomacro
+
+LEAF(_atomic_inc_32)
+1:     INT_LL          t0, 0(a0)
+        nop
+       INT_ADDU        t0, 1
+       INT_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_32, _atomic_inc_32)
+
+LEAF(_atomic_inc_32_nv)
+1:     INT_LL          v0, 0(a0)
+        nop
+       INT_ADDU        v0, 1
+       move            t0, v0
+       INT_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_32_nv, _atomic_inc_32_nv)
+
+#if !defined(__mips_o32)
+LEAF(_atomic_inc_64)
+1:     REG_LL          t0, 0(a0)
+        nop
+       REG_ADDU        t0, 1
+       REG_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_inc_64)
+ATOMIC_OP_ALIAS(atomic_inc_64, _atomic_inc_64)
+
+LEAF(_atomic_inc_64_nv)
+1:     REG_LL          v0, 0(a0)
+        nop
+       REG_ADDU        v0, 1
+       move            t0, v0
+       REG_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_inc_64_nv)
+ATOMIC_OP_ALIAS(atomic_inc_64_nv, _atomic_inc_64_nv)
+#endif
+
+#ifdef _LP64
+STRONG_ALIAS(_atomic_inc_ptr,          _atomic_inc_64)
+STRONG_ALIAS(_atomic_inc_ptr_nv,       _atomic_inc_64_nv)
+STRONG_ALIAS(_atomic_inc_ulong,                _atomic_inc_64)
+STRONG_ALIAS(_atomic_inc_ulong_nv,     _atomic_inc_64_nv)
+#else
+STRONG_ALIAS(_atomic_inc_ptr,          _atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_ptr_nv,       _atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_ulong,                _atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_ulong_nv,     _atomic_inc_32_nv)
+#endif
+STRONG_ALIAS(_atomic_inc_uint,         _atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_uint_nv,      _atomic_inc_32_nv)
+
+ATOMIC_OP_ALIAS(atomic_inc_ptr,                _atomic_inc_ptr)
+ATOMIC_OP_ALIAS(atomic_inc_ptr_nv,     _atomic_inc_ptr_nv)
+ATOMIC_OP_ALIAS(atomic_inc_uint,       _atomic_inc_uint)
+ATOMIC_OP_ALIAS(atomic_inc_uint_nv,    _atomic_inc_uint_nv)
+ATOMIC_OP_ALIAS(atomic_inc_ulong,      _atomic_inc_ulong)
+ATOMIC_OP_ALIAS(atomic_inc_ulong_nv,   _atomic_inc_ulong_nv)
diff --git a/common/lib/libc/arch/mips/atomic/atomic_op_asm.h b/common/lib/libc/arch/mips/atomic/atomic_op_asm.h
new file mode 100644 (file)
index 0000000..34bdd3b
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: atomic_op_asm.h,v 1.2 2008/04/28 20:22:52 martin Exp $ */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _ATOMIC_OP_ASM_H_
+#define        _ATOMIC_OP_ASM_H_
+
+#include <machine/asm.h>
+
+#if defined(_KERNEL)
+
+#define        ATOMIC_OP_ALIAS(a,s)    STRONG_ALIAS(a,s)
+
+#else /* _KERNEL */
+
+#define        ATOMIC_OP_ALIAS(a,s)    WEAK_ALIAS(a,s)
+
+#endif /* _KERNEL */
+
+#endif /* _ATOMIC_OP_ASM_H_ */
diff --git a/common/lib/libc/arch/mips/atomic/atomic_or.S b/common/lib/libc/arch/mips/atomic/atomic_or.S
new file mode 100644 (file)
index 0000000..bf25d89
--- /dev/null
@@ -0,0 +1,103 @@
+/*     $NetBSD: atomic_or.S,v 1.2 2009/12/14 00:39:00 matt Exp $       */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#include <machine/asm.h>
+#include "atomic_op_asm.h"
+
+       .text
+       .set    noat
+       .set    noreorder
+       .set    nomacro
+
+LEAF(_atomic_or_32)
+1:     INT_LL          t0, 0(a0)
+        nop
+       or              t0, a1
+       INT_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_32, _atomic_or_32)
+
+LEAF(_atomic_or_32_nv)
+1:     INT_LL          v0, 0(a0)
+        nop
+       or              v0, a1
+       move            t0, v0
+       INT_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_or_32_nv)
+ATOMIC_OP_ALIAS(atomic_or_32_nv, _atomic_or_32_nv)
+
+#if !defined(__mips_o32)
+LEAF(_atomic_or_64)
+1:     REG_LL          t0, 0(a0)
+        nop
+       or              t0, a1
+       REG_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_or_64)
+ATOMIC_OP_ALIAS(atomic_or_64, _atomic_or_64)
+
+LEAF(_atomic_or_64_nv)
+1:     REG_LL          v0, 0(a0)
+        nop
+       or              v0, a1
+       move            t0, v0
+       REG_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+       j               ra
+        nop
+END(_atomic_or_64_nv)
+ATOMIC_OP_ALIAS(atomic_or_64_nv, _atomic_or_64_nv)
+#endif
+
+#ifdef _LP64
+STRONG_ALIAS(_atomic_or_ulong,         _atomic_or_64)
+STRONG_ALIAS(_atomic_or_ulong_nv,      _atomic_or_64_nv)
+#else
+STRONG_ALIAS(_atomic_or_ulong,         _atomic_or_32)
+STRONG_ALIAS(_atomic_or_ulong_nv,      _atomic_or_32_nv)
+#endif
+STRONG_ALIAS(_atomic_or_uint,          _atomic_or_32)
+STRONG_ALIAS(_atomic_or_uint_nv,       _atomic_or_32_nv)
+
+ATOMIC_OP_ALIAS(atomic_or_uint,                _atomic_or_uint)
+ATOMIC_OP_ALIAS(atomic_or_uint_nv,     _atomic_or_uint_nv)
+ATOMIC_OP_ALIAS(atomic_or_ulong,       _atomic_or_ulong)
+ATOMIC_OP_ALIAS(atomic_or_ulong_nv,    _atomic_or_ulong_nv)
diff --git a/common/lib/libc/arch/mips/atomic/atomic_swap.S b/common/lib/libc/arch/mips/atomic/atomic_swap.S
new file mode 100644 (file)
index 0000000..b5f9477
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: atomic_swap.S,v 1.2 2009/12/14 00:39:00 matt Exp $     */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#include <machine/asm.h>
+#include "atomic_op_asm.h"
+
+RCSID("$NetBSD: atomic_swap.S,v 1.2 2009/12/14 00:39:00 matt Exp $")
+
+       .text
+       .set    noat
+       .set    noreorder
+       .set    nomacro
+
+LEAF(_atomic_swap_32)
+1:     INT_LL          v0, 0(a0)
+        nop
+       move            t0, a1
+       INT_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+2:
+       j               ra
+        nop
+END(_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_32, _atomic_swap_32)
+
+#if !defined(__mips_o32)
+LEAF(_atomic_swap_64)
+1:     REG_LL          v0, 0(a0)
+        nop
+       move            t0, a1
+       REG_SC          t0, 0(a0)
+       beq             t0, zero, 1b
+        nop
+2:
+       j               ra
+        nop
+END(_atomic_swap_64)
+ATOMIC_OP_ALIAS(atomic_swap_64, _atomic_swap_64)
+#endif
+
+#ifdef _LP64
+STRONG_ALIAS(_atomic_swap_ptr,         _atomic_swap_64)
+STRONG_ALIAS(_atomic_swap_ulong,       _atomic_swap_64)
+#else
+STRONG_ALIAS(_atomic_swap_ptr,         _atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_ulong,       _atomic_swap_32)
+#endif
+STRONG_ALIAS(_atomic_swap_uint,                _atomic_swap_32)
+
+ATOMIC_OP_ALIAS(atomic_swap_ptr,       _atomic_swap_ptr)
+ATOMIC_OP_ALIAS(atomic_swap_uint,      _atomic_swap_uint)
+ATOMIC_OP_ALIAS(atomic_swap_ulong,     _atomic_swap_ulong)
diff --git a/common/lib/libc/arch/mips/atomic/membar_ops.S b/common/lib/libc/arch/mips/atomic/membar_ops.S
new file mode 100644 (file)
index 0000000..4d01624
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: membar_ops.S,v 1.4 2009/12/14 00:39:00 matt Exp $      */
+
+/*-
+ * Copyright (c) 2006, 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe, and by Andrew Doran.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#if defined(_KERNEL)
+
+#ifdef _KERNEL_OPT
+#include "opt_cputype.h"
+#include "opt_lockdebug.h"
+#include "opt_multiprocessor.h"
+#endif
+
+
+#include <machine/cpu.h>
+
+#if (MIPS_HAS_LLSC != 0 && defined(MULTIPROCESSOR)) || !defined(__mips_o32)
+#define        SYNC            sync
+#endif
+#elif !defined(__mips_o32)
+#define        SYNC            sync
+#endif
+
+       .text
+
+LEAF(_membar_sync)
+       j       ra
+#ifdef SYNC
+       SYNC
+#else
+         nop
+#endif
+END(_membar_sync)
+
+#ifdef _KERNEL
+STRONG_ALIAS(mb_read, _membar_sync)
+STRONG_ALIAS(mb_write, _membar_sync)
+STRONG_ALIAS(mb_memory, _membar_sync)
+#endif
+
+ATOMIC_OP_ALIAS(membar_sync,_membar_sync)
+ATOMIC_OP_ALIAS(membar_enter,_membar_sync)
+STRONG_ALIAS(_membar_enter,_membar_sync)
+ATOMIC_OP_ALIAS(membar_exit,_membar_sync)
+STRONG_ALIAS(_membar_exit,_membar_sync)
+ATOMIC_OP_ALIAS(membar_producer,_membar_sync)
+STRONG_ALIAS(_membar_producer,_membar_sync)
+ATOMIC_OP_ALIAS(membar_consumer,_membar_sync)
+STRONG_ALIAS(_membar_consumer,_membar_sync)
diff --git a/common/lib/libc/arch/mips/gen/byte_swap_2.S b/common/lib/libc/arch/mips/gen/byte_swap_2.S
new file mode 100644 (file)
index 0000000..52c6a97
--- /dev/null
@@ -0,0 +1,83 @@
+/*     $NetBSD: byte_swap_2.S,v 1.3 2009/12/14 00:39:00 matt Exp $     */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)htons.s        8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: byte_swap_2.S,v 1.3 2009/12/14 00:39:00 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#undef _LOCORE
+#define _LOCORE                /* XXX not really, just assembly-code source */
+#include <machine/endian.h>
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+#define        BSWAP16_NAME    bswap16
+#else
+#define        BSWAP16_NAME    __bswap16
+#endif
+
+NLEAF(BSWAP16_NAME)
+#if BYTE_ORDER == LITTLE_ENDIAN
+ALEAF(htons)
+ALEAF(ntohs)
+#endif
+#if (__mips == 32 || __mips == 64) && __mips_isa_rev == 2
+       /*
+        * If we are on MIPS32r2 or MIPS64r2, use the new instructions
+        */
+       wsbh    a0, a0                  # word swap bytes within halfwords
+       and     v0, a0, 0xffff          # bound it to 16bits
+       j       ra
+#else
+       srl     v0, a0, 8
+       and     v0, v0, 0xff
+       sll     v1, a0, 8
+       and     v1, v1, 0xff00
+       or      v0, v0, v1
+       j       ra
+#endif
+END(BSWAP16_NAME)
+
+#if BYTE_ORDER == BIG_ENDIAN
+NLEAF(htons)
+ALEAF(ntohs)
+       move    v0, a0
+       j       ra
+END(htons)
+#endif
diff --git a/common/lib/libc/arch/mips/gen/byte_swap_4.S b/common/lib/libc/arch/mips/gen/byte_swap_4.S
new file mode 100644 (file)
index 0000000..aa13e25
--- /dev/null
@@ -0,0 +1,87 @@
+/*     $NetBSD: byte_swap_4.S,v 1.3 2009/12/14 00:39:00 matt Exp $     */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)htonl.s        8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: byte_swap_4.S,v 1.3 2009/12/14 00:39:00 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#undef _LOCORE
+#define _LOCORE                /* XXX not really, just assembly-code source */
+#include <machine/endian.h>
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+#define        BSWAP32_NAME    bswap32
+#else
+#define        BSWAP32_NAME    __bswap32
+#endif
+
+NLEAF(BSWAP32_NAME)                    # a0 = 0x11223344, return 0x44332211
+#if BYTE_ORDER == LITTLE_ENDIAN
+ALEAF(htonl)                           # a0 = 0x11223344, return 0x44332211
+ALEAF(ntohl)
+#endif
+#if (__mips == 32 || __mips == 64) && __mips_isa_rev == 2
+       /*
+        * If we are on MIPS32R2 or MIPS64R2 it's much easier
+        */
+       wsbh    a0, a0                  # word swap bytes within halfwords
+       rotr    v0, a0, 16              # rotate word 16bits
+       j       ra
+#else
+       srl     v1, a0, 24              # v1 = 0x00000011
+       sll     v0, a0, 24              # v0 = 0x44000000
+       or      v0, v0, v1
+       and     v1, a0, 0xff00
+       sll     v1, v1, 8               # v1 = 0x00330000
+       or      v0, v0, v1
+       srl     v1, a0, 8
+       and     v1, v1, 0xff00          # v1 = 0x00002200
+       or      v0, v0, v1
+       j       ra
+#endif
+END(BSWAP32_NAME)
+
+#if BYTE_ORDER == BIG_ENDIAN
+NLEAF(htonl)                           # a0 = 0x11223344, return 0x44332211
+ALEAF(ntohl)
+       move    v0, a0
+       j       ra
+END(htonl)
+#endif
diff --git a/common/lib/libc/arch/mips/gen/byte_swap_8.S b/common/lib/libc/arch/mips/gen/byte_swap_8.S
new file mode 100644 (file)
index 0000000..4b3cb85
--- /dev/null
@@ -0,0 +1,118 @@
+/*     $NetBSD: byte_swap_8.S,v 1.2 2009/12/14 00:39:00 matt Exp $     */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: byte_swap_8.S,v 1.2 2009/12/14 00:39:00 matt Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+#undef _LOCORE
+#define _LOCORE                /* XXX not really, just assembly-code source */
+#include <machine/endian.h>
+
+NLEAF(bswap64) # a0 = 0xffeeddccbbaa9988 return 0x8899aabbccddeeff
+#if (__mips == 32 || __mips == 64) && __mips_isa_rev == 2
+#if !defined(__mips_o32)
+       /*
+        * If we are on MIPS32r2 or MIPS64r2 use the new instructions.
+        */
+       dsbh    v0, a0                  # dwords swap bytes within halfwords
+       dshd    v0, v0                  # dwords swap halwords within dwords
+       j       ra
+#else /* defined(__mips_o32) */
+       /*
+        * If we are on MIPS32r2 or MIPS64r2 use the new instructions.
+        * (except we must use the 32bit versions) 
+        */
+       wsbh    v1, a0                  # word swap bytes within halfwords
+       wsbh    v0, a1                  # word swap bytes within halfwords
+       rotr    v1, v1, 16              # rotate word 16bits and swap word
+       rotr    v0, v0, 16              # rotate word 16bits and swap word
+       j       ra
+#endif /* defined(__mips_o32) */
+#elif !defined(__mips_o32)
+                                       # a0  = 0xffeeddccbbaa9988
+       li      t0, 0xffff              # t0  = 0x000000000000ffff
+       dsll    t1, t0, 32              # t1  = 0x0000ffff00000000
+       or      t0, t1                  # t0  = 0x0000ffff0000ffff
+       dsll    t2, t0, 8               # t2  = 0x00ffff0000ffff00
+       xor     t2, t0                  # t2  = 0x00ff00ff00ff00ff
+       /*
+        * We could swap by halfword, but that would be one instruction longer.
+        */
+       dsrl    ta0, a0, 32             # ta0 = 0x00000000ffeeddcc
+       dsll    ta1, a0, 32             # ta1 = 0xbbaa998800000000
+       or      a1, ta0, ta1            # a1  = 0xbbaa9988ffeeddcc
+                                       # words swapped
+       and     ta0, a1, t0             # ta0 = 0x000099880000ddcc
+       dsrl    ta1, a1, 16             # ta1 = 0x0000bbaa9988ffee
+       and     ta1, t0                 # ta1 = 0x0000bbaa0000ffee
+       dsll    a2, ta0, 16             # a2  = 0x99880000ddcc0000
+       or      a2, ta1                 # a2  = 0x9988bbaaddccffee
+                                       # halfwords swapped
+       and     ta0, a2, t2             # ta0 = 0x008800aa00cc00ee
+       dsrl    ta1, a2, 8              # ta1 = 0x009988bbaaddccff
+       and     ta1, t2                 # ta1 = 0x009900bb00dd00ff
+       dsll    v0, ta0, 8              # v0  = 0x8800aa00cc00ee00
+       or      v0, ta1                 # v0  = 0x8899aabbccddeeff
+                                       # bytes swapped
+       j       ra
+#else /* defined(__mips_o32) */
+       /*
+        * 32bit ABI.
+        */
+                                       # a0  = 0xccddeeff
+                                       # a1  = 0x8899aabb
+       srl     t0, a0, 24              # t0  = 0x000000cc
+       srl     t1, a1, 24              # t1  = 0x00000088
+       sll     ta0, a0, 24             # ta0 = 0xff000000
+       sll     ta1, a1, 24             # ta1 = 0xbb000000
+       or      ta0, ta0, t0            # ta0 = 0xff0000cc
+       or      ta1, ta1, t1            # ta1 = 0xbb000088
+       and     t0, a0, 0xff00          # t0  = 0x0000ee00
+       and     t1, a1, 0xff00          # t1  = 0x0000aa00
+       sll     t0, t0, 8               # t0  = 0x00ee0000
+       sll     t1, t1, 8               # t1  = 0x00aa0000
+       or      ta0, ta0, t0            # ta0 = 0xffee00cc
+       or      ta1, ta1, t1            # ta1 = 0xbbaa0088
+       srl     t0, a0, 8               # t0  = 0x00ccddee
+       srl     t1, a1, 8               # t1  = 0x008899aa
+       and     t0, t0, 0xff00          # t0  = 0x0000dd00
+       and     t1, t1, 0xff00          # t1  = 0x00009900
+       or      v1, ta0, t0             # v1  = 0xffeeddcc
+       or      v0, ta1, t1             # v0  = 0xbbaa9988
+       j       ra
+#endif /* defined(__mips_o32) */
+END(bswap64)
diff --git a/common/lib/libc/arch/mips/string/bcopy.S b/common/lib/libc/arch/mips/string/bcopy.S
new file mode 100644 (file)
index 0000000..05f6777
--- /dev/null
@@ -0,0 +1,294 @@
+/*     $NetBSD: bcopy.S,v 1.3 2009/12/14 00:39:00 matt Exp $   */
+
+/*
+ * Mach Operating System
+ * Copyright (c) 1993 Carnegie Mellon University
+ * All Rights Reserved.
+ *
+ * Permission to use, copy, modify and distribute this software and its
+ * documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ *
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
+ * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ *
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie Mellon
+ * the rights to redistribute these changes.
+ */
+
+/*
+ *     File:   mips_bcopy.s
+ *     Author: Chris Maeda
+ *     Date:   June 1993
+ *
+ *     Fast copy routine.  Derived from aligned_block_copy.
+ */
+
+
+#include <mips/asm.h>
+#ifndef _LOCORE
+#define _LOCORE                /* XXX not really, just assembly-code source */
+#endif
+#include <machine/endian.h>
+
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)mips_bcopy.s   2.2 CMU 18/06/93")
+#else
+       RCSID("$NetBSD: bcopy.S,v 1.3 2009/12/14 00:39:00 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ *     bcopy(caddr_t src, caddr_t dst, unsigned int len)
+ *
+ *     a0      src address
+ *     a1      dst address
+ *     a2      length
+ */
+
+#if defined(MEMCOPY) || defined(MEMMOVE)
+#ifdef MEMCOPY
+#define        FUNCTION        memcpy
+#else
+#define FUNCTION       memmove
+#endif
+#define        SRCREG          a1
+#define        DSTREG          a0
+#else
+#define        FUNCTION        bcopy
+#define        SRCREG          a0
+#define        DSTREG          a1
+#endif
+
+#define        SIZEREG         a2
+
+LEAF(FUNCTION)
+       .set    noat
+       .set    noreorder
+
+#if defined(MEMCOPY) || defined(MEMMOVE)
+       /* set up return value, while we still can */
+       move    v0,DSTREG
+#endif
+       /*
+        *      Make sure we can copy forwards.
+        */
+       sltu    t0,SRCREG,DSTREG        # t0 == SRCREG < DSTREG
+       bne     t0,zero,6f              # copy backwards
+
+       /*
+        *      There are four alignment cases (with frequency)
+        *      (Based on measurements taken with a DECstation 5000/200
+        *       inside a Mach kernel.)
+        *
+        *      aligned   -> aligned            (mostly)
+        *      unaligned -> aligned            (sometimes)
+        *      aligned,unaligned -> unaligned  (almost never)
+        *
+        *      Note that we could add another case that checks if
+        *      the destination and source are unaligned but the
+        *      copy is alignable.  eg if src and dest are both
+        *      on a halfword boundary.
+        */
+       andi            t1,DSTREG,(SZREG-1)     # get last bits of dest
+       bne             t1,zero,3f              # dest unaligned
+       andi            t0,SRCREG,(SZREG-1)     # get last bits of src
+       bne             t0,zero,5f
+
+       /*
+        *      Forward aligned->aligned copy, 8 words at a time.
+        */
+98:
+       li              AT,-(SZREG*8)
+       and             t0,SIZEREG,AT           # count truncated to multiples
+       PTR_ADDU        a3,SRCREG,t0            # run fast loop up to this addr
+       sltu            AT,SRCREG,a3            # any work to do?
+       beq             AT,zero,2f
+       PTR_SUBU        SIZEREG,t0
+
+       /*
+        *      loop body
+        */
+1:     # cp
+       REG_L           t3,(0*SZREG)(SRCREG)
+       REG_L           v1,(1*SZREG)(SRCREG)
+       REG_L           t0,(2*SZREG)(SRCREG)
+       REG_L           t1,(3*SZREG)(SRCREG)
+       PTR_ADDU        SRCREG,SZREG*8
+       REG_S           t3,(0*SZREG)(DSTREG)
+       REG_S           v1,(1*SZREG)(DSTREG)
+       REG_S           t0,(2*SZREG)(DSTREG)
+       REG_S           t1,(3*SZREG)(DSTREG)
+       REG_L           t1,(-1*SZREG)(SRCREG)
+       REG_L           t0,(-2*SZREG)(SRCREG)
+       REG_L           v1,(-3*SZREG)(SRCREG)
+       REG_L           t3,(-4*SZREG)(SRCREG)
+       PTR_ADDU        DSTREG,SZREG*8
+       REG_S           t1,(-1*SZREG)(DSTREG)
+       REG_S           t0,(-2*SZREG)(DSTREG)
+       REG_S           v1,(-3*SZREG)(DSTREG)
+       bne             SRCREG,a3,1b
+       REG_S           t3,(-4*SZREG)(DSTREG)
+
+       /*
+        *      Copy a word at a time, no loop unrolling.
+        */
+2:     # wordcopy
+       andi            t2,SIZEREG,(SZREG-1)    # get byte count / SZREG
+       PTR_SUBU        t2,SIZEREG,t2           # t2 = words to copy * SZREG
+       beq             t2,zero,3f
+       PTR_ADDU        t0,SRCREG,t2            # stop at t0
+       PTR_SUBU        SIZEREG,SIZEREG,t2
+1:
+       REG_L           t3,0(SRCREG)
+       PTR_ADDU        SRCREG,SZREG
+       REG_S           t3,0(DSTREG)
+       bne             SRCREG,t0,1b
+       PTR_ADDU        DSTREG,SZREG
+
+3:     # bytecopy
+       beq             SIZEREG,zero,4f         # nothing left to do?
+       nop
+1:
+       lb              t3,0(SRCREG)
+       PTR_ADDU        SRCREG,1
+       sb              t3,0(DSTREG)
+       PTR_SUBU        SIZEREG,1
+       bgtz            SIZEREG,1b
+       PTR_ADDU        DSTREG,1
+
+4:     # copydone
+       j       ra
+       nop
+
+       /*
+        *      Copy from unaligned source to aligned dest.
+        */
+5:     # destaligned
+       andi            t0,SIZEREG,(SZREG-1)    # t0 = bytecount mod SZREG
+       PTR_SUBU        a3,SIZEREG,t0           # number of words to transfer
+       beq             a3,zero,3b
+       nop
+       move            SIZEREG,t0              # this many to do after we are done
+       PTR_ADDU        a3,SRCREG,a3            # stop point
+
+1:
+       REG_LHI         t3,0(SRCREG)
+       REG_LLO         t3,SZREG-1(SRCREG)
+       PTR_ADDI        SRCREG,SZREG
+       REG_S           t3,0(DSTREG)
+       bne             SRCREG,a3,1b
+       PTR_ADDI        DSTREG,SZREG
+
+       b               3b
+       nop
+
+6:     # backcopy -- based on above
+       PTR_ADDU        SRCREG,SIZEREG
+       PTR_ADDU        DSTREG,SIZEREG
+       andi            t1,DSTREG,SZREG-1       # get last 3 bits of dest
+       bne             t1,zero,3f
+       andi            t0,SRCREG,SZREG-1       # get last 3 bits of src
+       bne             t0,zero,5f
+
+       /*
+        *      Forward aligned->aligned copy, 8*4 bytes at a time.
+        */
+       li              AT,(-8*SZREG)
+       and             t0,SIZEREG,AT           # count truncated to multiple of 32
+       beq             t0,zero,2f              # any work to do?
+       PTR_SUBU        SIZEREG,t0
+       PTR_SUBU        a3,SRCREG,t0
+
+       /*
+        *      loop body
+        */
+1:     # cp
+       REG_L           t3,(-4*SZREG)(SRCREG)
+       REG_L           v1,(-3*SZREG)(SRCREG)
+       REG_L           t0,(-2*SZREG)(SRCREG)
+       REG_L           t1,(-1*SZREG)(SRCREG)
+       PTR_SUBU        SRCREG,8*SZREG
+       REG_S           t3,(-4*SZREG)(DSTREG)
+       REG_S           v1,(-3*SZREG)(DSTREG)
+       REG_S           t0,(-2*SZREG)(DSTREG)
+       REG_S           t1,(-1*SZREG)(DSTREG)
+       REG_L           t1,(3*SZREG)(SRCREG)
+       REG_L           t0,(2*SZREG)(SRCREG)
+       REG_L           v1,(1*SZREG)(SRCREG)
+       REG_L           t3,(0*SZREG)(SRCREG)
+       PTR_SUBU        DSTREG,8*SZREG
+       REG_S           t1,(3*SZREG)(DSTREG)
+       REG_S           t0,(2*SZREG)(DSTREG)
+       REG_S           v1,(1*SZREG)(DSTREG)
+       bne             SRCREG,a3,1b
+       REG_S           t3,(0*SZREG)(DSTREG)
+
+       /*
+        *      Copy a word at a time, no loop unrolling.
+        */
+2:     # wordcopy
+       andi            t2,SIZEREG,SZREG-1      # get byte count / 4
+       PTR_SUBU        t2,SIZEREG,t2           # t2 = number of words to copy
+       beq             t2,zero,3f
+       PTR_SUBU        t0,SRCREG,t2            # stop at t0
+       PTR_SUBU        SIZEREG,SIZEREG,t2
+1:
+       REG_L           t3,-SZREG(SRCREG)
+       PTR_SUBU        SRCREG,SZREG
+       REG_S           t3,-SZREG(DSTREG)
+       bne             SRCREG,t0,1b
+       PTR_SUBU        DSTREG,SZREG
+
+3:     # bytecopy
+       beq             SIZEREG,zero,4f         # nothing left to do?
+       nop
+1:
+       lb              t3,-1(SRCREG)
+       PTR_SUBU        SRCREG,1
+       sb              t3,-1(DSTREG)
+       PTR_SUBU        SIZEREG,1
+       bgtz            SIZEREG,1b
+       PTR_SUBU        DSTREG,1
+
+4:     # copydone
+       j       ra
+       nop
+
+       /*
+        *      Copy from unaligned source to aligned dest.
+        */
+5:     # destaligned
+       andi            t0,SIZEREG,SZREG-1      # t0 = bytecount mod 4
+       PTR_SUBU        a3,SIZEREG,t0           # number of words to transfer
+       beq             a3,zero,3b
+       nop
+       move            SIZEREG,t0              # this many to do after we are done
+       PTR_SUBU        a3,SRCREG,a3            # stop point
+
+1:
+       REG_LHI         t3,-SZREG(SRCREG)
+       REG_LLO         t3,-1(SRCREG)
+       PTR_SUBU        SRCREG,SZREG
+       REG_S           t3,-SZREG(DSTREG)
+       bne             SRCREG,a3,1b
+       PTR_SUBU        DSTREG,SZREG
+
+       b               3b
+       nop
+
+       .set    reorder
+       .set    at
+       END(FUNCTION)
diff --git a/common/lib/libc/arch/mips/string/ffs.S b/common/lib/libc/arch/mips/string/ffs.S
new file mode 100644 (file)
index 0000000..62f2d0a
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: ffs.S,v 1.2 2009/12/14 00:39:00 matt Exp $     */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       /* RCSID("from: @(#)ffs.s       8.1 (Berkeley) 6/4/93") */
+       RCSID("$NetBSD: ffs.S,v 1.2 2009/12/14 00:39:00 matt Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+/* bit = ffs(value) */
+
+LEAF(ffs)
+       move    v0, zero
+       beq     a0, zero, done
+1:
+       and     v1, a0, 1               # bit set?
+       addu    v0, v0, 1
+       srl     a0, a0, 1
+       beq     v1, zero, 1b            # no, continue
+done:
+       j       ra
+END(ffs)
diff --git a/common/lib/libc/arch/mips/string/memcpy.S b/common/lib/libc/arch/mips/string/memcpy.S
new file mode 100644 (file)
index 0000000..564d86c
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: memcpy.S,v 1.1 2005/12/20 19:28:50 christos Exp $      */
+
+
+#define MEMCOPY
+#include "bcopy.S"
diff --git a/common/lib/libc/arch/mips/string/memmove.S b/common/lib/libc/arch/mips/string/memmove.S
new file mode 100644 (file)
index 0000000..fa1922b
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: memmove.S,v 1.1 2005/12/20 19:28:50 christos Exp $     */
+
+
+#define MEMMOVE
+#include "bcopy.S"
diff --git a/common/lib/libc/arch/mips/string/strchr.S b/common/lib/libc/arch/mips/string/strchr.S
new file mode 100644 (file)
index 0000000..2e49a4c
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: strchr.S,v 1.3 2011/01/02 02:58:52 matt Exp $  */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       ASMSTR("from: @(#)index.s       8.1 (Berkeley) 6/4/93")
+       ASMSTR("$NetBSD: strchr.S,v 1.3 2011/01/02 02:58:52 matt Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef __ABICALLS__
+       .abicalls
+#endif
+
+LEAF(strchr)
+XLEAF(index)
+1:
+       lbu     a2, 0(a0)               # get a byte
+       PTR_ADDU a0, 1
+       beq     a2, a1, fnd
+       bne     a2, zero, 1b
+notfnd:
+       move    v0, zero
+       j       ra
+fnd:
+       PTR_SUBU v0, a0, 1
+       j       ra
+END(strchr)
diff --git a/common/lib/libc/arch/mips/string/strcmp.S b/common/lib/libc/arch/mips/string/strcmp.S
new file mode 100644 (file)
index 0000000..6d57692
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: strcmp.S,v 1.2 2009/12/14 00:39:00 matt Exp $  */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       /* RCSID("from: @(#)strcmp.s    8.1 (Berkeley) 6/4/93") */
+       RCSID("$NetBSD: strcmp.S,v 1.2 2009/12/14 00:39:00 matt Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * NOTE: this version assumes unsigned chars in order to be "8 bit clean".
+ */
+LEAF(strcmp)
+1:
+       lbu     t0, 0(a0)               # get two bytes and compare them
+       lbu     t1, 0(a1)
+       beq     t0, zero, LessOrEq      # end of first string?
+       bne     t0, t1, NotEq
+       lbu     t0, 1(a0)               # unroll loop
+       lbu     t1, 1(a1)
+       PTR_ADD a0, a0, 2
+       beq     t0, zero, LessOrEq      # end of first string?
+       PTR_ADD a1, a1, 2
+       beq     t0, t1, 1b
+NotEq:
+       subu    v0, t0, t1
+       j       ra
+LessOrEq:
+       subu    v0, zero, t1
+       j       ra
+END(strcmp)
diff --git a/common/lib/libc/arch/mips/string/strlen.S b/common/lib/libc/arch/mips/string/strlen.S
new file mode 100644 (file)
index 0000000..842dcf9
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: strlen.S,v 1.2 2009/12/14 00:39:00 matt Exp $  */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       /* RCSID("from: @(#)strlen.s    8.1 (Berkeley) 6/4/93") */
+       RCSID("$NetBSD: strlen.S,v 1.2 2009/12/14 00:39:00 matt Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+LEAF(strlen)
+       PTR_ADDU        v1, a0, 1
+1:
+       lb              v0, 0(a0)       # get byte from string
+       PTR_ADDU        a0, a0, 1       # increment pointer
+       bne             v0, zero, 1b    # continue if not end
+       PTR_SUBU        v0, a0, v1      # compute length - 1 for '\0' char
+       j               ra
+END(strlen)
diff --git a/common/lib/libc/arch/mips/string/strrchr.S b/common/lib/libc/arch/mips/string/strrchr.S
new file mode 100644 (file)
index 0000000..8b90edc
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: strrchr.S,v 1.2 2011/01/02 02:58:52 matt Exp $ */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       ASMSTR("from: @(#)rindex.s      8.1 (Berkeley) 6/4/93")
+       ASMSTR("$NetBSD: strrchr.S,v 1.2 2011/01/02 02:58:52 matt Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef __ABICALLS__
+       .abicalls
+#endif
+
+LEAF(strrchr)
+XLEAF(rindex)
+       move    v0, zero                # default if not found
+1:
+       lbu     a3, 0(a0)               # get a byte
+       PTR_ADDU a0, a0, 1
+       bne     a3, a1, 2f
+       PTR_SUBU v0, a0, 1              # save address of last match
+2:
+       bne     a3, zero, 1b            # continue if not end
+       j       ra
+END(strrchr)
diff --git a/common/lib/libc/arch/powerpc/atomic/Makefile.inc b/common/lib/libc/arch/powerpc/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..bc05890
--- /dev/null
@@ -0,0 +1,15 @@
+#      $NetBSD: Makefile.inc,v 1.6 2009/01/04 17:54:29 pooka Exp $
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "c" || ${LIB} == "pthread" \
+       || ${LIB} == "rump")
+
+SRCS+= atomic_add.S atomic_and.S atomic_cas.S atomic_dec.S \
+       atomic_inc.S atomic_or.S atomic_swap.S membar_ops.S
+
+.endif
+
+.if defined(LIB) && (${LIB} == "c" || ${LIB} == "pthread")
+
+SRCS+= atomic_init_cas.c
+
+.endif
diff --git a/common/lib/libc/arch/powerpc/atomic/atomic_add.S b/common/lib/libc/arch/powerpc/atomic/atomic_add.S
new file mode 100644 (file)
index 0000000..fa69943
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: atomic_add.S,v 1.7 2011/01/15 07:31:11 matt Exp $      */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+__RCSID("$NetBSD: atomic_add.S,v 1.7 2011/01/15 07:31:11 matt Exp $")
+
+       .text
+ENTRY(_atomic_add_32)
+1:     lwarx   %r10,0,%r3
+       add     %r10,%r10,%r4
+       stwcx.  %r10,0,%r3
+       bne-    1b
+       blr
+END(_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_32,_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_int,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_int,_atomic_add_32)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_add_long,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_long,_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_ptr,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_ptr,_atomic_add_32)
+#endif
+
+ENTRY(_atomic_add_32_nv)
+1:     lwarx   %r10,0,%r3
+       add     %r10,%r10,%r4
+       stwcx.  %r10,0,%r3
+       bne-    1b
+       mr      %r3,%r10
+       blr
+END(_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_32_nv,_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_int_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_int_nv,_atomic_add_32_nv)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_add_long_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_long_nv,_atomic_add_32_nv)
+ATOMIC_OP_ALIAS(atomic_add_ptr_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_ptr_nv,_atomic_add_32_nv)
+#endif
diff --git a/common/lib/libc/arch/powerpc/atomic/atomic_and.S b/common/lib/libc/arch/powerpc/atomic/atomic_and.S
new file mode 100644 (file)
index 0000000..97ba1ee
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: atomic_and.S,v 1.6 2011/01/15 07:31:11 matt Exp $      */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+__RCSID("$NetBSD: atomic_and.S,v 1.6 2011/01/15 07:31:11 matt Exp $")
+
+       .text
+ENTRY(_atomic_and_32)
+1:     lwarx   %r10,0,%r3
+       and     %r10,%r10,%r4
+       stwcx.  %r10,0,%r3
+       bne-    1b
+       blr
+END(_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_32,_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_uint,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_uint,_atomic_and_32)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_and_ulong,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_ulong,_atomic_and_32)
+#endif
+
+ENTRY(_atomic_and_32_nv)
+1:     lwarx   %r10,0,%r3
+       and     %r10,%r10,%r4
+       stwcx.  %r10,0,%r3
+       bne-    1b
+       mr      %r3,%r10
+       blr
+END(_atomic_and_32_nv)
+ATOMIC_OP_ALIAS(atomic_and_32_nv,_atomic_and_32_nv)
+ATOMIC_OP_ALIAS(atomic_and_uint_nv,_atomic_and_32_nv)
+STRONG_ALIAS(_atomic_and_uint_nv,_atomic_and_32_nv)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_and_ulong_nv,_atomic_and_32_nv)
+STRONG_ALIAS(_atomic_and_ulong_nv,_atomic_and_32_nv)
+#endif
diff --git a/common/lib/libc/arch/powerpc/atomic/atomic_cas.S b/common/lib/libc/arch/powerpc/atomic/atomic_cas.S
new file mode 100644 (file)
index 0000000..2ecaffd
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: atomic_cas.S,v 1.7 2011/01/15 07:31:11 matt Exp $      */
+
+/*-
+ * Copyright (c) 2007, 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+__RCSID("$NetBSD: atomic_cas.S,v 1.7 2011/01/15 07:31:11 matt Exp $")
+
+       .text
+ENTRY(_atomic_cas_32)
+1:     lwarx   %r10,0,%r3
+       cmpw    %r10,%r4
+       bne-    2f
+       stwcx.  %r5,0,%r3
+       bne-    1b
+2:     mr      %r3,%r10
+       blr
+END(_atomic_cas_32)
+
+ATOMIC_OP_ALIAS(atomic_cas_32,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_uint,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_uint,_atomic_cas_32)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_cas_ulong,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_ptr,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ptr,_atomic_cas_32)
+#endif
+
+ATOMIC_OP_ALIAS(atomic_cas_32_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_32_ni,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_uint_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_uint_ni,_atomic_cas_32)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_cas_ulong_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong_ni,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_ptr_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ptr_ni,_atomic_cas_32)
+#endif
diff --git a/common/lib/libc/arch/powerpc/atomic/atomic_dec.S b/common/lib/libc/arch/powerpc/atomic/atomic_dec.S
new file mode 100644 (file)
index 0000000..9ee07cf
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: atomic_dec.S,v 1.6 2011/01/15 07:31:11 matt Exp $      */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+__RCSID("$NetBSD: atomic_dec.S,v 1.6 2011/01/15 07:31:11 matt Exp $")
+       .text
+
+ENTRY(_atomic_dec_32)
+1:     lwarx   %r10,0,%r3
+       addi    %r10,%r10,-1
+       stwcx.  %r10,0,%r3
+       bne-    1b
+       blr
+END(_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_32,_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_uint,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_uint,_atomic_dec_32)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_dec_ulong,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_ulong,_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_ptr,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_ptr,_atomic_dec_32)
+#endif
+
+ENTRY(_atomic_dec_32_nv)
+1:     lwarx   %r10,0,%r3
+       addi    %r10,%r10,-1
+       stwcx.  %r10,0,%r3
+       bne-    1b
+       mr      %r3,%r10
+       blr
+END(_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_32_nv,_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_uint_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_uint_nv,_atomic_dec_32_nv)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_dec_ulong_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_ulong_nv,_atomic_dec_32_nv)
+ATOMIC_OP_ALIAS(atomic_dec_ptr_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_ptr_nv,_atomic_dec_32_nv)
+#endif
diff --git a/common/lib/libc/arch/powerpc/atomic/atomic_inc.S b/common/lib/libc/arch/powerpc/atomic/atomic_inc.S
new file mode 100644 (file)
index 0000000..b466947
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: atomic_inc.S,v 1.6 2011/01/15 07:31:11 matt Exp $      */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+__RCSID("$NetBSD: atomic_inc.S,v 1.6 2011/01/15 07:31:11 matt Exp $")
+
+       .text
+ENTRY(_atomic_inc_32)
+1:     lwarx   %r10,0,%r3
+       addi    %r10,%r10,1
+       stwcx.  %r10,0,%r3
+       bne-    1b
+       blr
+END(_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_32,_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_uint,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_uint,_atomic_inc_32)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_inc_ulong,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_ulong,_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_ptr,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_ptr,_atomic_inc_32)
+#endif
+
+ENTRY(_atomic_inc_32_nv)
+1:     lwarx   %r10,0,%r3
+       addi    %r10,%r10,1
+       stwcx.  %r10,0,%r3
+       bne-    1b
+       mr      %r3,%r10
+       blr
+END(_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_32_nv,_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_uint_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_uint_nv,_atomic_inc_32_nv)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_inc_ulong_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_ulong_nv,_atomic_inc_32_nv)
+ATOMIC_OP_ALIAS(atomic_inc_ptr_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_ptr_nv,_atomic_inc_32_nv)
+#endif
diff --git a/common/lib/libc/arch/powerpc/atomic/atomic_op_asm.h b/common/lib/libc/arch/powerpc/atomic/atomic_op_asm.h
new file mode 100644 (file)
index 0000000..456fb7f
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: atomic_op_asm.h,v 1.5 2011/01/15 07:31:11 matt Exp $   */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _ATOMIC_OP_ASM_H_
+#define        _ATOMIC_OP_ASM_H_
+
+#include <machine/asm.h>
+
+#if defined(_KERNEL)
+
+#define        ATOMIC_OP_ALIAS(a,s)    STRONG_ALIAS(a,s)
+
+#else /* _KERNEL */
+
+#define        ATOMIC_OP_ALIAS(a,s)    WEAK_ALIAS(a,s)
+
+#endif /* _KERNEL */
+
+#endif /* _ATOMIC_OP_ASM_H_ */
diff --git a/common/lib/libc/arch/powerpc/atomic/atomic_or.S b/common/lib/libc/arch/powerpc/atomic/atomic_or.S
new file mode 100644 (file)
index 0000000..5c634f9
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: atomic_or.S,v 1.6 2011/01/15 07:31:11 matt Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+__RCSID("$NetBSD: atomic_or.S,v 1.6 2011/01/15 07:31:11 matt Exp $")
+
+       .text
+ENTRY(_atomic_or_32)
+1:     lwarx   %r10,0,%r3
+       or      %r10,%r10,%r4
+       stwcx.  %r10,0,%r3
+       bne-    1b
+       blr
+END(_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_32,_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_uint,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_uint,_atomic_or_32)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_or_ulong,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_ulong,_atomic_or_32)
+#endif
+
+ENTRY(_atomic_or_32_nv)
+1:     lwarx   %r10,0,%r3
+       or      %r10,%r10,%r4
+       stwcx.  %r10,0,%r3
+       bne-    1b
+       mr      %r3,%r10
+       blr
+END(_atomic_or_32_nv)
+ATOMIC_OP_ALIAS(atomic_or_32_nv,_atomic_or_32_nv)
+ATOMIC_OP_ALIAS(atomic_or_uint_nv,_atomic_or_32_nv)
+STRONG_ALIAS(_atomic_or_uint_nv,_atomic_or_32_nv)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_or_ulong_nv,_atomic_or_32_nv)
+STRONG_ALIAS(_atomic_or_ulong_nv,_atomic_or_32_nv)
+#endif
diff --git a/common/lib/libc/arch/powerpc/atomic/atomic_swap.S b/common/lib/libc/arch/powerpc/atomic/atomic_swap.S
new file mode 100644 (file)
index 0000000..db96dc4
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: atomic_swap.S,v 1.6 2011/01/15 07:31:11 matt Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+__RCSID("$NetBSD: atomic_swap.S,v 1.6 2011/01/15 07:31:11 matt Exp $")
+
+       .text
+ENTRY(_atomic_swap_32)
+1:     lwarx   %r10,0,%r3
+       stwcx.  %r4,0,%r3
+       bne-    1b
+       mr      %r3,%r10
+       blr
+END(_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_32,_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_uint,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_uint,_atomic_swap_32)
+#if !defined(_LP64)
+ATOMIC_OP_ALIAS(atomic_swap_ulong,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_ulong,_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_ptr,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_ptr,_atomic_swap_32)
+#endif
diff --git a/common/lib/libc/arch/powerpc/atomic/membar_ops.S b/common/lib/libc/arch/powerpc/atomic/membar_ops.S
new file mode 100644 (file)
index 0000000..dd103cf
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: membar_ops.S,v 1.4 2011/01/15 07:31:11 matt Exp $      */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe, and by Andrew Doran.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+__RCSID("$NetBSD: membar_ops.S,v 1.4 2011/01/15 07:31:11 matt Exp $")
+
+       .text
+/* These assume Total Store Order (TSO) */
+
+ENTRY(_membar_consumer)
+       isync
+       blr
+END(_membar_consumer)
+
+ENTRY(_membar_producer)
+       sync
+       blr
+END(_membar_producer)
+
+ATOMIC_OP_ALIAS(membar_producer,_membar_producer)
+ATOMIC_OP_ALIAS(membar_consumer,_membar_consumer)
+ATOMIC_OP_ALIAS(membar_enter,_membar_consumer)
+STRONG_ALIAS(_membar_enter,_membar_consumer)
+ATOMIC_OP_ALIAS(membar_exit,_membar_producer)
+STRONG_ALIAS(_membar_exit,_membar_producer)
+ATOMIC_OP_ALIAS(membar_sync,_membar_producer)
+STRONG_ALIAS(_membar_sync,_membar_producer)
diff --git a/common/lib/libc/arch/powerpc/string/bcopy.S b/common/lib/libc/arch/powerpc/string/bcopy.S
new file mode 100644 (file)
index 0000000..35582a8
--- /dev/null
@@ -0,0 +1,4 @@
+/* $NetBSD: bcopy.S,v 1.1 2008/02/21 17:35:47 garbled Exp $ */
+
+#define _BCOPY
+#include "memmove.S"
diff --git a/common/lib/libc/arch/powerpc/string/ffs.S b/common/lib/libc/arch/powerpc/string/ffs.S
new file mode 100644 (file)
index 0000000..9a8c312
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: ffs.S,v 1.5 2011/01/15 07:31:12 matt Exp $ */
+
+/*-
+ * Copyright (C) 2001  Martin J. Laubach <mjl@NetBSD.org>
+ * 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.
+ * 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 ``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 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 <machine/asm.h>
+
+__RCSID("$NetBSD: ffs.S,v 1.5 2011/01/15 07:31:12 matt Exp $")
+
+       .align 4
+ENTRY(ffs)
+       neg     %r4, %r3
+       and     %r3, %r4, %r3
+       cntlzw  %r3, %r3
+       li      %r0, 32
+       subf    %r3, %r3, %r0
+       blr
+END(ffs)
+
+/*----------------------------------------------------------------------*/
diff --git a/common/lib/libc/arch/powerpc/string/memcmp.S b/common/lib/libc/arch/powerpc/string/memcmp.S
new file mode 100644 (file)
index 0000000..2e5f6d6
--- /dev/null
@@ -0,0 +1,270 @@
+/* $NetBSD: memcmp.S,v 1.3 2011/01/15 07:31:12 matt Exp $ */
+
+/* stropt/memcmp.S, pl_string_common, pl_linux 10/11/04 11:45:35
+ * ==========================================================================
+ * Optimized memcmp implementation for IBM PowerPC 405/440.
+ *
+ *     Copyright (c) 2003, IBM Corporation
+ *     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.                                              
+ *     * 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.                         
+ *     * Neither the name of IBM 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 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.
+ *                                                                             
+ * ==========================================================================
+ *
+ * Function: Compare two character strings (up to n characters)
+ *
+ *             int memcmp(const char *s1, const char *s2, int n)
+ *
+ * Input:      r3 - buffer 1 address
+ *             r4 - buffer 2 address
+ *             r5 - maximum characters to compare
+ * Output: r3 <0 (less), 0 (equal), >0 (greater)
+ *
+ * ==========================================================================
+ */
+
+#include <machine/asm.h>
+
+        .text
+        .align 4
+/* LINTSTUB: Func: void *memcmp(const void *, const void *, size_t) */
+ENTRY(memcmp)
+
+       /*
+        * Check count passed in R5. If zero, return 0; otherwise continue.
+        */
+       cmpwi   %r5,0
+       beq-    ret_0;
+
+       /*
+        * Most of the time the difference is found in the first
+        * several bytes.  The following code minimizes the number
+        * of load operations for short compares.
+        */
+
+       mr      %r11, %r3               /* Save buffer 1                */
+
+again:
+
+       not     %r10, %r4               /* buffer 2: bytes to page bdy  */
+       rlwinm. %r10, %r10,29,23,31     /* buffer 2: dwords to page bdy */
+       beq-    bytebybyte              /* If < 8 bytes to the page bdy */
+                                       /* do byte by byte              */
+       lwz     %r8, 0(%r4)             /* load 1st buffer 2 word       */
+
+       not     %r12, %r11              /* buffer 1: bytes to page bdy  */
+       rlwinm. %r12, %r12,29,23,31     /* buffer 1: dwords to page bdy */
+       beq-    bytebybyte              /* If < 8 bytes to the page bdy */
+                                       /* do byte by byte              */
+       lwz     %r6, 0(%r11)            /* load 1st buffer 1 word       */
+
+       cmpwi   %r5, 4                  /* If remaining count <= 4      */
+       ble+    first4                  /* handle specially.    DWG     */
+
+       cmplw   %r8, %r6                /* compare buffer 2 and buffer 1*/
+       bne+    all_done                /* different => we're done      */
+
+       lwzu    %r9, 4(%r4)             /* load 2nd buffer 2 word       */
+       lwzu    %r7, 4(%r11)            /* load 2nd buffer 1 word       */
+
+       cmpwi   %r5, 8                  /* If remaining count <= 8      */
+       ble+    last4                   /* handle specially.    DWG     */
+
+       cmplw   %r9, %r7                /* compare buffer 2 and buffer 1*/
+       bne+    all_done                /* different => we're done      */
+
+       addi    %r5, %r5, -8            /* Update character counter DWG */
+       addi    %r10, %r4, 0x0004       /* DWG*/
+       not     %r10, %r10              /* buffer 2: bytes to page bdy DWG */
+       rlwinm. %r10, %r10,29,23,31     /* buffer 2: dwords to page bdy DWG */
+       addi    %r12, %r11, 0x0004      /* DWG */
+       not     %r12, %r12              /* buffer 1: bytes to page bdy DWG */
+       rlwinm. %r12, %r12,29,23,31     /* buffer 1: dwords to page bdy DWG */
+       
+       /* The following section prior to loop: figures out whether     */
+       /* the buffer 1 or buffer 2 is closer to the page boundary.     */
+       /* The main loop count is then set up to reflect the number of  */
+       /* double words of the buffer that is closest                   */
+
+       cmpw    %r10, %r12              /* Find closest                 */
+       blt     lt
+
+       mr      %r10, %r12
+
+lt:
+
+       srwi    %r12, %r5, 3            /* Double check the total count */
+       cmpw    %r10, %r12              /* limitation                   */
+       blt     lt2
+
+       mr      %r10, %r12              /* DWG */
+lt2:                                   /* DWG */
+       cmpwi   %r10, 0                 /* DWG */
+       bne     lt3                     /* DWG */
+       addi    %r4, %r4, 0x0004        /* DWG */
+       addi    %r11,%r11,0x0004        /* DWG */
+       b       again                   /* DWG */
+lt3:                                   /* DWG */
+       mtctr   %r10                    /* dword count for loop         */
+       lwzu    %r6, 4(%r11)            /* pre-load buffer 1 word       */
+
+       b       in                      /* To the loop                  */
+
+loop:                                  /* main loop                    */
+
+       cmplw   %r8, %r6                /* Compare first buffer 2 word  */
+       bne-    all_done                /* with first buffer 1 word     */
+                                       /* If different, we're done     */
+       cmplw   %r9, %r7                /* Compare second buffer 2 word */
+                                       /* with second buffer 1 word    */
+       lwzu    %r6, 4(%r11)            /* pre-load buffer 1 word       */
+
+       bne-    all_done                /* If different, we're done     */
+
+in:
+
+       lwzu    %r7, 4(%r11)            /* pre-load buffer 1 word       */
+       lwzu    %r8, 4(%r4)             /* pre-load buffer 2 word       */
+       lwzu    %r9, 4(%r4)             /* pre-load buffer 2 word       */
+
+       bdnz+   loop                    /* Do more DW's if cnt > 0      */
+
+       /*mfctr %r12*/ /*DWG*/          /* number of dwords left        */
+       /*subf  %r10, %r12, %r10*/ /*DWG*//* number of dwords compared  */
+       slwi    %r10, %r10, 3
+       subf    %r5, %r10, %r5          /* adjust byte counter          */
+       /*bne+  partial*/ /*DWG*/       /* If less than 8 bytes, handle */
+                                       /* specially                    */
+       /*cmpwi %r5, 8*/                /* Removed.              DWG */
+       /*blt   partial*/               /* Removed.              DWG */
+
+       /*addic %r5, %r5, -8*/ /*DWG*/  /* Subtract two words from count*/
+
+       cmplw   %r8, %r6                /* compare last dword           */
+       addi    %r4, %r4, 4
+       bne-    all_done
+
+       cmplw   %r9, %r7
+       addi    %r11, %r11, 4
+       bne-    all_done
+
+bytebybyte:
+
+       /* We've gotten close to a page boundary: do a byte-byte-byte
+        * compare for the following 8 bytes, and then go back to
+        * the full-word compare loop.
+        */
+
+       li      %r3, 8                  /* loop count                   */
+       cmpw    %r3, %r5                /* take min(8, counter)         */
+       ble     f2
+
+       mr.     %r3, %r5
+
+       beqlr
+
+f2:
+
+       mtctr   %r3
+       subf    %r5, %r3, %r5           /* adjust counter               */
+
+bbb:
+
+       lbz     %r6, 0(%r11)            /* byte copy loop               */
+
+       addi    %r11, %r11, 1
+
+       lbz     %r8, 0(%r4)
+
+       addi    %r4, %r4, 1
+
+       cmplw   %r8, %r6
+
+       bdnzt+  eq, bbb
+
+       bne     all_done
+
+       cmpwi   %r5, 0
+       bgt     again                   /* handle the rest              */
+
+       xor     %r3,%r3,%r3
+
+       blr
+
+#if 0 /* Removed code section. DWG */
+partial:
+
+       mr.     %r3, %r5
+
+       beqlr                           /* If count -> 0, we're done    */
+
+f1:
+
+       subfic  %r3, %r3, 4             /* zero/end in first word?      */
+       cmpwi   %r3, 0
+       blt     last4
+#endif /* DWG */
+
+first4:
+       subfic  %r3, %r5, 4             /* If count <= 4, handle        */
+       rlwinm  %r3, %r3, 3, 0, 31      /* count *= 8                   */
+       srw     %r6, %r6, %r3           /* align 1st buffer 1 word      */
+       srw     %r8, %r8, %r3           /* align 1st buffer 2 word      */
+
+       cmplw   %r8, %r6                /* get result                   */
+       bne     all_done
+       xor     %r3,%r3,%r3
+       blr
+
+last4:
+       subfic  %r10, %r5, 8            /*DWG*/
+       rlwinm  %r10, %r10, 3, 0, 31    /* count *= 8                   */
+       srw     %r7, %r7, %r10          /* align 2nd buffer 1 word      */
+       srw     %r9, %r9, %r10          /* align 2nd buffer 2 word      */
+
+       cmplw   %r9, %r7                /* get result                   */
+       bne     all_done
+ret_0:
+       xor     %r3,%r3,%r3             /* Equal result          */
+       blr
+
+all_done:
+
+       blt     finish_lt
+
+       addi    %r3,0,-1                /* Less than result             */
+
+       blr
+
+finish_lt:
+
+       addi    %r3,0,1                 /* Greater than result          */
+
+       blr
+END(memcmp)
diff --git a/common/lib/libc/arch/powerpc/string/memcpy.S b/common/lib/libc/arch/powerpc/string/memcpy.S
new file mode 100644 (file)
index 0000000..b987961
--- /dev/null
@@ -0,0 +1,117 @@
+/* $NetBSD: memcpy.S,v 1.3 2011/01/15 07:31:12 matt Exp $ */
+
+/* stropt/memcpy_440.S, pl_string_common, pl_linux 10/11/04 11:45:36
+ * ==========================================================================
+ * Optimized memcpy implementation for IBM PowerPC 440.
+ *
+ *  Copyright (c) 2003, IBM Corporation
+ *  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.                                             
+ *    * 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.                             
+ *    * Neither the name of IBM 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 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.
+ *                                                                       
+ * ==========================================================================
+ *
+ * Function: Copy n bytes of the source to the destination. Behavior is
+ *        undefined for objects that overlap.
+ *
+ *
+ *        void *memcpy(void * dest, const void * src, int n)
+ *
+ * Input:  r3 - destination address
+ *      r4 - source address
+ *      r5 - byte count
+ * Output: r3 - destination address
+ *
+ * ==========================================================================
+ */
+
+#include <machine/asm.h>
+
+       .text
+       .align 4
+/* LINTSTUB: Func: void *memcpy(void *, const void *, size_t) */
+ENTRY(memcpy)
+       /*
+        * Check count passed in R5. If zero, return; otherwise continue.
+        */
+       cmpwi   %r5,0
+       beqlr-
+
+       mr      %r8, %r3                /* Copy dst (return value)      */
+
+       addi    %r4, %r4, -4            /* Prepare for main loop's auto */
+       addi    %r8, %r8, -4            /* update                      */
+
+       srwi.   %r9,%r5,2               /* Word count -> r9             */
+       beq-    last1                   /* Partial copy if <4 bytes     */
+
+       mtctr   %r9                     /* Word cnt in CTR for loop     */
+       lwzu    %r7, 4(%r4)             /* Preload for main loop        */
+
+       b       g1
+
+g0:                                    /* Main loop                    */
+
+       lwzu    %r7, 4(%r4)             /* Load a new word              */
+       stwu    %r6, 4(%r8)             /* Store previous word          */
+
+g1:
+
+       bdz-    last                    /* Dec ctr and exit loop if no  */
+                                       /* more words              */
+       lwzu    %r6, 4(%r4)             /* Load another word            */
+       stwu    %r7, 4(%r8)             /* Store previous word          */
+       bdnz+   g0                      /* Dec ctr and continue loop if */
+                                       /* more words              */
+
+       mr      %r7, %r6
+
+last:
+
+       stwu    %r7, 4(%r8)             /* Store last word              */
+
+last1:                                 /* Byte-by-byte copy            */
+
+       clrlwi. %r5,%r5,30
+       beqlr
+
+       mtctr   %r5
+
+       lbzu    %r6, 4(%r4)             /* 1st byte: update by word     */
+       stbu    %r6, 4(%r8)
+       bdzlr-
+
+last2:
+
+       lbzu    %r6, 1(%r4)             /* Handle the rest              */
+       stbu    %r6, 1(%r8)
+       bdnz+   last2
+
+       blr
+END(memcpy)
diff --git a/common/lib/libc/arch/powerpc/string/memmove.S b/common/lib/libc/arch/powerpc/string/memmove.S
new file mode 100644 (file)
index 0000000..cd676ca
--- /dev/null
@@ -0,0 +1,182 @@
+/* $NetBSD: memmove.S,v 1.3 2011/01/15 07:31:12 matt Exp $ */
+
+/* stropt/memmove.S, pl_string_common, pl_linux 10/11/04 11:45:37
+ * ==========================================================================
+ * Optimized memmove implementation for IBM PowerPC 405/440.
+ *
+ *     Copyright (c) 2003, IBM Corporation
+ *     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.                                              
+ *     * 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.                         
+ *     * Neither the name of IBM 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 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.
+ *                                                                             
+ * ==========================================================================
+ *
+ * Function: Move memory area (handles overlapping regions)
+ *
+ *             void *memmove(void * dest, const void * src, int n) 
+ *     
+ * Input:      r3 - destination address 
+ *      r4 - source address 
+ *      r5 - byte count
+ * Output: r3 - destination address
+ *
+ * ==========================================================================
+ */
+
+#include <machine/asm.h>
+
+        .text
+        .align 4
+#ifdef _BCOPY
+/* bcopy = memcpy/memmove with arguments reversed. */
+/* LINTSTUB: Func: void bcopy(void *, void *, size_t) */
+ENTRY(bcopy)
+       mr      %r6, %r3                /* swap src/dst */
+       mr      %r3, %r4
+       mr      %r4, %r6
+#else
+/* LINTSTUB: Func: void *memmove(void *, const void *, size_t) */
+ENTRY(memmove)
+#endif
+
+       mr      %r8, %r3                /* Save dst (return value)      */
+       
+       cmpw    %r4, %r8                /* Branch to reverse if         */
+       blt     reverse                 /* src < dest. Don't want to    */
+                                       /* overwrite end of src with    */
+                                       /* start of dest                */
+
+       addi    %r4, %r4, -4            /* Back up src and dst pointers */
+       addi    %r8, %r8, -4            /* due to auto-update of 'load' */ 
+       
+       srwi.   %r9,%r5,2                       /* How many words in total cnt  */
+       beq-    last1                   /* Handle byte by byte if < 4   */
+                                       /* bytes total                  */
+       mtctr   %r9                     /* Count of words for loop              */
+       lwzu    %r7, 4(%r4)             /* Preload first word           */
+       
+       b       g1
+
+g0:                                    /* Main loop                    */
+
+       lwzu    %r7, 4(%r4)             /* Load a new word              */
+       stwu    %r6, 4(%r8)             /* Store previous word          */
+       
+g1:
+
+       bdz-    last                    /* Dec cnt, and branch if just  */
+                                       /* one word to store            */
+       lwzu    %r6, 4(%r4)             /* Load another word            */
+       stwu    %r7, 4(%r8)             /* Store previous word          */
+       bdnz+   g0                      /* Dec cnt, and loop again if   */
+                                       /* more words                   */
+       mr      %r7, %r6                        /* If word count -> 0, then...  */
+       
+last:
+
+       stwu    %r7, 4(%r8)             /* ... store last word          */
+
+last1:                                 /* Byte-by-byte copy            */
+
+       clrlwi. %r5,%r5,30              /* If count -> 0, then ...      */
+       beqlr                           /* we're done                   */
+       
+       mtctr   %r5                     /* else load count for loop     */
+       
+       lbzu    %r6, 4(%r4)             /* 1st byte: update addr by 4   */
+       stbu    %r6, 4(%r8)             /* since we pre-adjusted by 4   */
+       bdzlr-                          /* in anticipation of main loop */
+       
+last2:
+
+       lbzu    %r6, 1(%r4)             /* But handle the rest by               */
+       stbu    %r6, 1(%r8)             /* updating addr by 1           */
+       bdnz+   last2
+       
+       blr
+
+       /* We're here since src < dest. Don't want to overwrite end of  */
+       /* src with start of dest                                               */
+
+reverse:
+
+       add     %r4, %r4, %r5           /* Work from end to beginning   */
+       add     %r8, %r8, %r5           /* so add count to string ptrs  */
+       srwi.   %r9,%r5,2                       /* Words in total count         */
+       beq-    rlast1                  /* Handle byte by byte if < 4   */
+                                       /* bytes total                  */
+       
+       mtctr   %r9                     /* Count of words for loop      */
+       
+       lwzu    %r7, -4(%r4)            /* Preload first word           */
+       b       rg1
+
+rg0:                                   /* Main loop                    */
+
+       lwzu    %r7, -4(%r4)            /* Load a new word              */
+       stwu    %r6, -4(%r8)            /* Store previous word          */
+       
+rg1:
+
+       bdz-    rlast                   /* Dec cnt, and branch if just  */
+                                       /* one word to store            */
+
+       lwzu    %r6, -4(%r4)            /* Load another word            */
+       stwu    %r7, -4(%r8)            /* Store previous word          */
+       
+       bdnz+   rg0                     /* Dec cnt, and loop again if   */
+                                       /* more words                   */
+
+       mr      %r7, %r6                        /* If word count -> 0, then...  */
+       
+rlast:
+
+       stwu    %r7, -4(%r8)            /* ... store last word          */
+
+rlast1:                                        /* Byte-by-byte copy            */
+
+       clrlwi. %r5,%r5,30              /* If count -> 0, then...       */
+       beqlr                           /* ... we're done               */
+       
+       mtctr   %r5                     /* else load count for loop     */
+       
+rlast2:
+
+       lbzu    %r6, -1(%r4)            /* Handle the rest, byte by     */
+       stbu    %r6, -1(%r8)            /* byte                         */
+       
+       bdnz+   rlast2                  /* Dec ctr, and branch if more  */
+                                       /* bytes left                   */
+       blr
+
+#ifdef _BCOPY
+END(bcopy)
+#else
+END(memmove)
+#endif
diff --git a/common/lib/libc/arch/powerpc/string/strlen.S b/common/lib/libc/arch/powerpc/string/strlen.S
new file mode 100644 (file)
index 0000000..e822e89
--- /dev/null
@@ -0,0 +1,118 @@
+/*     $NetBSD: strlen.S,v 1.6 2011/01/15 07:31:12 matt Exp $ */
+
+/*-
+ * Copyright (C) 2001  Martin J. Laubach <mjl@NetBSD.org>
+ * 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.
+ * 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 ``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 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 <machine/asm.h>
+
+__RCSID("$NetBSD: strlen.S,v 1.6 2011/01/15 07:31:12 matt Exp $");
+
+/*----------------------------------------------------------------------*/
+/* The algorithm here uses the following techniques:
+
+   1) Given a word 'x', we can test to see if it contains any 0 bytes
+      by subtracting 0x01010101, and seeing if any of the high bits of each
+      byte changed from 0 to 1. This works because the least significant
+      0 byte must have had no incoming carry (otherwise it's not the least
+      significant), so it is 0x00 - 0x01 == 0xff. For all other
+      byte values, either they have the high bit set initially, or when
+      1 is subtracted you get a value in the range 0x00-0x7f, none of which
+      have their high bit set. The expression here is
+      (x + 0xfefefeff) & ~(x | 0x7f7f7f7f), which gives 0x00000000 when
+      there were no 0x00 bytes in the word.
+
+   2) Given a word 'x', we can test to see _which_ byte was zero by
+      calculating ~(((x & 0x7f7f7f7f) + 0x7f7f7f7f) | x | 0x7f7f7f7f).
+      This produces 0x80 in each byte that was zero, and 0x00 in all
+      the other bytes. The '| 0x7f7f7f7f' clears the low 7 bits in each
+      byte, and the '| x' part ensures that bytes with the high bit set
+      produce 0x00. The addition will carry into the high bit of each byte
+      iff that byte had one of its low 7 bits set. We can then just see
+      which was the most significant bit set and divide by 8 to find how
+      many to add to the index.
+      This is from the book 'The PowerPC Compiler Writer's Guide',
+      by Steve Hoxey, Faraydon Karim, Bill Hay and Hank Warren.
+*/
+/*----------------------------------------------------------------------*/
+
+               .text
+               .align 4
+
+ENTRY(strlen)
+
+               /* Setup constants */
+               lis     %r10, 0x7f7f
+               lis     %r9, 0xfefe
+               ori     %r10, %r10, 0x7f7f
+               ori     %r9, %r9, 0xfeff
+
+               /* Mask out leading bytes on non aligned strings */
+               rlwinm. %r8, %r3, 3, 27, 28     /* leading bits to mask */
+#ifdef _LP64
+               clrrdi  %r5, %r3, 2             /*  clear low 2 addr bits */
+#else
+               clrrwi  %r5, %r3, 2             /*  clear low 2 addr bits */
+#endif
+               li      %r0, -1
+               beq+    3f                      /* skip alignment if already */
+                                               /* aligned */
+
+               srw     %r0, %r0, %r8           /* make 0000...1111 mask */
+
+               lwz     %r7, 0(%r5)
+               nor     %r0, %r0, %r0           /* invert mask */
+               or      %r7, %r7, %r0           /* make leading bytes != 0 */
+               b       2f
+
+3:             subi    %r5, %r5, 4
+
+1:             lwzu    %r7, 4(%r5)             /* fetch data word */
+
+2:             nor     %r0, %r7, %r10          /* do step 1 */
+               add     %r6, %r7, %r9
+               and.    %r0, %r0, %r6
+
+               beq+    1b                      /* no NUL bytes here */
+       
+               and     %r8, %r7, %r10          /* ok, a NUL is somewhere */
+               or      %r7, %r7, %r10          /* do step 2 to find out */
+               add     %r0, %r8, %r10          /* where */
+               nor     %r8, %r7, %r0
+
+               cntlzw  %r0, %r8                /* offset from this word */
+               srwi    %r4, %r0, 3
+
+               add     %r4, %r5, %r4           /* r4 contains end pointer */
+               /* NOTE: Keep it so this function returns the end pointer
+                  in r4, so we can it use from other str* calls (strcat
+                  comes to mind */
+
+               subf    %r3, %r3, %r4
+               blr
+END(strlen)
+/*----------------------------------------------------------------------*/
diff --git a/common/lib/libc/arch/powerpc64/atomic/Makefile.inc b/common/lib/libc/arch/powerpc64/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..bc05890
--- /dev/null
@@ -0,0 +1,15 @@
+#      $NetBSD: Makefile.inc,v 1.6 2009/01/04 17:54:29 pooka Exp $
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "c" || ${LIB} == "pthread" \
+       || ${LIB} == "rump")
+
+SRCS+= atomic_add.S atomic_and.S atomic_cas.S atomic_dec.S \
+       atomic_inc.S atomic_or.S atomic_swap.S membar_ops.S
+
+.endif
+
+.if defined(LIB) && (${LIB} == "c" || ${LIB} == "pthread")
+
+SRCS+= atomic_init_cas.c
+
+.endif
diff --git a/common/lib/libc/arch/powerpc64/atomic/atomic_add.S b/common/lib/libc/arch/powerpc64/atomic/atomic_add.S
new file mode 100644 (file)
index 0000000..c8345e2
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: atomic_add.S,v 1.5 2009/03/08 12:08:19 he Exp $        */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#include "../../powerpc/atomic/atomic_add.S"
+
+       .text
+
+ENTRY(_atomic_add_64)
+1:     ldarx   %r10,0,%r3
+       add     %r10,%r10,%r4
+       stdcx.  %r10,0,%r3
+       bne-    1b
+       blr
+ATOMIC_OP_ALIAS(atomic_add_64,_atomic_add_64)
+ATOMIC_OP_ALIAS(atomic_add_long,_atomic_add_64)
+STRONG_ALIAS(_atomic_add_long,_atomic_add_64)
+ATOMIC_OP_ALIAS(atomic_add_ptr,_atomic_add_64)
+STRONG_ALIAS(_atomic_add_ptr,_atomic_add_64)
+
+ENTRY(_atomic_add_64_nv)
+1:     ldarx   %r10,0,%r3
+       add     %r10,%r10,%r4
+       stdcx.  %r10,0,%r3
+       bne-    1b
+       mr      %r3,%r10
+       blr
+ATOMIC_OP_ALIAS(atomic_add_64_nv,_atomic_add_64_nv)
+ATOMIC_OP_ALIAS(atomic_add_long_nv,_atomic_add_64_nv)
+STRONG_ALIAS(_atomic_add_long_nv,_atomic_add_64_nv)
+ATOMIC_OP_ALIAS(atomic_add_ptr_nv,_atomic_add_64_nv)
+STRONG_ALIAS(_atomic_add_ptr_nv,_atomic_add_64_nv)
diff --git a/common/lib/libc/arch/powerpc64/atomic/atomic_and.S b/common/lib/libc/arch/powerpc64/atomic/atomic_and.S
new file mode 100644 (file)
index 0000000..ad21582
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: atomic_and.S,v 1.5 2009/03/08 12:08:19 he Exp $        */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#include "../../powerpc/atomic/atomic_and.S"
+
+       .text
+
+ENTRY(_atomic_and_64)
+1:     ldarx   %r10,0,%r3
+       and     %r10,%r10,%r4
+       stdcx.  %r10,0,%r3
+       bne-    1b
+       blr
+ATOMIC_OP_ALIAS(atomic_and_64,_atomic_and_64)
+ATOMIC_OP_ALIAS(atomic_and_ulong,_atomic_and_64)
+STRONG_ALIAS(_atomic_and_ulong,_atomic_and_64)
+
+ENTRY(_atomic_and_64_nv)
+1:     ldarx   %r10,0,%r3
+       and     %r10,%r10,%r4
+       stdcx.  %r10,0,%r3
+       bne-    1b
+       mr      %r3,%r10
+       blr
+ATOMIC_OP_ALIAS(atomic_and_64_nv,_atomic_and_64_nv)
+ATOMIC_OP_ALIAS(atomic_and_ulong_nv,_atomic_and_64_nv)
+STRONG_ALIAS(_atomic_and_ulong_nv,_atomic_and_64_nv)
diff --git a/common/lib/libc/arch/powerpc64/atomic/atomic_cas.S b/common/lib/libc/arch/powerpc64/atomic/atomic_cas.S
new file mode 100644 (file)
index 0000000..fbebd03
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: atomic_cas.S,v 1.6 2009/03/08 12:08:19 he Exp $        */
+
+/*-
+ * Copyright (c) 2007, 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#include "../../powerpc/atomic/atomic_cas.S"
+
+       .text
+
+ENTRY(_atomic_cas_64)
+1:     ldarx   %r10,0,%r3
+       cmpd    %r10,%r4
+       bne-    2f
+       stdcx.  %r5,0,%r3
+       bne-    1b
+2:     mr      %r3,%r10
+       blr
+
+ATOMIC_OP_ALIAS(atomic_cas_64,_atomic_cas_64)
+ATOMIC_OP_ALIAS(atomic_cas_ulong,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ulong,_atomic_cas_64)
+ATOMIC_OP_ALIAS(atomic_cas_ptr,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ptr,_atomic_cas_64)
+
+ATOMIC_OP_ALIAS(atomic_cas_64_ni,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_64_ni,_atomic_cas_64)
+ATOMIC_OP_ALIAS(atomic_cas_ulong_ni,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ulong_ni,_atomic_cas_64)
+ATOMIC_OP_ALIAS(atomic_cas_ptr_ni,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ptr_ni,_atomic_cas_64)
diff --git a/common/lib/libc/arch/powerpc64/atomic/atomic_dec.S b/common/lib/libc/arch/powerpc64/atomic/atomic_dec.S
new file mode 100644 (file)
index 0000000..3c6d046
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: atomic_dec.S,v 1.5 2009/03/08 12:08:19 he Exp $        */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#include "../../powerpc/atomic/atomic_dec.S"
+
+       .text
+
+ENTRY(_atomic_dec_64)
+1:     ldarx   %r10,0,%r3
+       addi    %r10,%r10,-1
+       stdcx.  %r10,0,%r3
+       bne-    1b
+       blr
+ATOMIC_OP_ALIAS(atomic_dec_64,_atomic_dec_64)
+ATOMIC_OP_ALIAS(atomic_dec_ulong,_atomic_dec_64)
+STRONG_ALIAS(_atomic_dec_ulong,_atomic_dec_64)
+ATOMIC_OP_ALIAS(atomic_dec_ptr,_atomic_dec_64)
+STRONG_ALIAS(_atomic_dec_ptr,_atomic_dec_64)
+
+ENTRY(_atomic_dec_64_nv)
+1:     ldarx   %r10,0,%r3
+       addi    %r10,%r10,-1
+       stdcx.  %r10,0,%r3
+       bne-    1b
+       mr      %r3,%r10
+       blr
+ATOMIC_OP_ALIAS(atomic_dec_64_nv,_atomic_dec_64_nv)
+ATOMIC_OP_ALIAS(atomic_dec_ulong_nv,_atomic_dec_64_nv)
+STRONG_ALIAS(_atomic_dec_ulong_nv,_atomic_dec_64_nv)
+ATOMIC_OP_ALIAS(atomic_dec_ptr_nv,_atomic_dec_64_nv)
+STRONG_ALIAS(_atomic_dec_ptr_nv,_atomic_dec_64_nv)
diff --git a/common/lib/libc/arch/powerpc64/atomic/atomic_inc.S b/common/lib/libc/arch/powerpc64/atomic/atomic_inc.S
new file mode 100644 (file)
index 0000000..962c0f6
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: atomic_inc.S,v 1.5 2009/03/08 12:08:19 he Exp $        */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#include "../../powerpc/atomic/atomic_inc.S"
+
+       .text
+
+ENTRY(_atomic_inc_64)
+1:     ldarx   %r10,0,%r3
+       addi    %r10,%r10,1
+       stdcx.  %r10,0,%r3
+       bne-    1b
+       blr
+ATOMIC_OP_ALIAS(atomic_inc_64,_atomic_inc_64)
+ATOMIC_OP_ALIAS(atomic_inc_ulong,_atomic_inc_64)
+STRONG_ALIAS(_atomic_inc_ulong,_atomic_inc_64)
+ATOMIC_OP_ALIAS(atomic_inc_ptr,_atomic_inc_64)
+STRONG_ALIAS(_atomic_inc_ptr,_atomic_inc_64)
+
+ENTRY(_atomic_inc_64_nv)
+1:     ldarx   %r10,0,%r3
+       addi    %r10,%r10,1
+       stdcx.  %r10,0,%r3
+       bne-    1b
+       mr      %r3,%r10
+       blr
+ATOMIC_OP_ALIAS(atomic_inc_64_nv,_atomic_inc_64_nv)
+ATOMIC_OP_ALIAS(atomic_inc_ulong_nv,_atomic_inc_64_nv)
+STRONG_ALIAS(_atomic_inc_ulong_nv,_atomic_inc_64_nv)
+ATOMIC_OP_ALIAS(atomic_inc_ptr_nv,_atomic_inc_64_nv)
+STRONG_ALIAS(_atomic_inc_ptr_nv,_atomic_inc_64_nv)
diff --git a/common/lib/libc/arch/powerpc64/atomic/atomic_op_asm.h b/common/lib/libc/arch/powerpc64/atomic/atomic_op_asm.h
new file mode 100644 (file)
index 0000000..34a15b6
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: atomic_op_asm.h,v 1.4 2010/03/22 02:22:32 mrg Exp $    */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _ATOMIC_OP_ASM_H_
+#define        _ATOMIC_OP_ASM_H_
+
+#define _NOREGNAMES
+#include <machine/asm.h>
+
+#if defined(_KERNEL)
+
+#define        ATOMIC_OP_ALIAS(a,s)    STRONG_ALIAS(a,s)
+
+#else /* _KERNEL */
+
+#define        ATOMIC_OP_ALIAS(a,s)    WEAK_ALIAS(a,s)
+
+#endif /* _KERNEL */
+
+#endif /* _ATOMIC_OP_ASM_H_ */
diff --git a/common/lib/libc/arch/powerpc64/atomic/atomic_or.S b/common/lib/libc/arch/powerpc64/atomic/atomic_or.S
new file mode 100644 (file)
index 0000000..eee4027
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: atomic_or.S,v 1.5 2009/03/08 12:08:19 he Exp $ */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#include "../../powerpc/atomic/atomic_or.S"
+
+       .text
+
+ENTRY(_atomic_or_64)
+1:     ldarx   %r10,0,%r3
+       or      %r10,%r10,%r4
+       stdcx.  %r10,0,%r3
+       bne-    1b
+       blr
+ATOMIC_OP_ALIAS(atomic_or_64,_atomic_or_64)
+ATOMIC_OP_ALIAS(atomic_or_ulong,_atomic_or_64)
+STRONG_ALIAS(_atomic_or_ulong,_atomic_or_64)
+
+ENTRY(_atomic_or_64_nv)
+1:     ldarx   %r10,0,%r3
+       or      %r10,%r10,%r4
+       stdcx.  %r10,0,%r3
+       bne-    1b
+       mr      %r3,%r10
+       blr
+ATOMIC_OP_ALIAS(atomic_or_64_nv,_atomic_or_64_nv)
+ATOMIC_OP_ALIAS(atomic_or_ulong_nv,_atomic_or_64_nv)
+STRONG_ALIAS(_atomic_or_ulong_nv,_atomic_or_64_nv)
diff --git a/common/lib/libc/arch/powerpc64/atomic/atomic_swap.S b/common/lib/libc/arch/powerpc64/atomic/atomic_swap.S
new file mode 100644 (file)
index 0000000..bba9800
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: atomic_swap.S,v 1.5 2009/03/08 12:08:19 he Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+#include "../../powerpc/atomic/atomic_swap.S"
+
+       .text
+
+ENTRY(_atomic_swap_64)
+1:     ldarx   %r10,0,%r3
+       stdcx.  %r4,0,%r3
+       bne-    1b
+       mr      %r3,%r10
+       blr
+ATOMIC_OP_ALIAS(atomic_swap_64,_atomic_swap_64)
+ATOMIC_OP_ALIAS(atomic_swap_ulong,_atomic_swap_64)
+STRONG_ALIAS(_atomic_swap_ulong,_atomic_swap_64)
+ATOMIC_OP_ALIAS(atomic_swap_ptr,_atomic_swap_64)
+STRONG_ALIAS(_atomic_swap_ptr,_atomic_swap_64)
diff --git a/common/lib/libc/arch/powerpc64/atomic/membar_ops.S b/common/lib/libc/arch/powerpc64/atomic/membar_ops.S
new file mode 100644 (file)
index 0000000..6805207
--- /dev/null
@@ -0,0 +1,3 @@
+/*     $NetBSD: membar_ops.S,v 1.1 2007/11/28 21:47:02 ad Exp $        */
+
+#include "../../powerpc/atomic/membar_ops.S"
diff --git a/common/lib/libc/arch/powerpc64/string/ffs.S b/common/lib/libc/arch/powerpc64/string/ffs.S
new file mode 100644 (file)
index 0000000..4cce87c
--- /dev/null
@@ -0,0 +1,3 @@
+/*     $NetBSD: ffs.S,v 1.1 2006/07/07 07:37:44 ross Exp $ */
+
+#include "../../powerpc/string/ffs.S"
diff --git a/common/lib/libc/arch/powerpc64/string/strlen.S b/common/lib/libc/arch/powerpc64/string/strlen.S
new file mode 100644 (file)
index 0000000..871907b
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: strlen.S,v 1.1 2006/07/07 07:37:44 ross Exp $ */
+
+/* XXX could be optimized for ppc64 */
+
+#include "../../powerpc/string/strlen.S"
diff --git a/common/lib/libc/arch/sh3/atomic/Makefile.inc b/common/lib/libc/arch/sh3/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..1bafd20
--- /dev/null
@@ -0,0 +1,17 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/01/04 17:54:29 pooka Exp $
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "c" || ${LIB} == "pthread" \
+       || ${LIB} == "rump")
+
+SRCS+= atomic_add_32_cas.c atomic_add_32_nv_cas.c atomic_and_32_cas.c \
+       atomic_and_32_nv_cas.c atomic_dec_32_cas.c atomic_dec_32_nv_cas.c \
+       atomic_inc_32_cas.c atomic_inc_32_nv_cas.c atomic_or_32_cas.c \
+       atomic_or_32_nv_cas.c atomic_swap_32_cas.c membar_ops_nop.c
+
+.endif
+
+.if defined(LIB) && (${LIB} == "c" || ${LIB} == "pthread")
+
+SRCS+= atomic_init_testset.c
+
+.endif
diff --git a/common/lib/libc/arch/sh3/string/ffs.S b/common/lib/libc/arch/sh3/string/ffs.S
new file mode 100644 (file)
index 0000000..f7189be
--- /dev/null
@@ -0,0 +1,96 @@
+/*     $NetBSD: ffs.S,v 1.2 2008/04/28 20:22:52 martin Exp $   */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by ITOH Yasufumi.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: ffs.S,v 1.2 2008/04/28 20:22:52 martin Exp $")
+#endif
+
+/*
+ * ffs - find first bit set
+ *
+ * This code makes use of ``test 8bit'' and ``shift 8bit'' instructions.
+ * The remaining 8bit is tested in every 2bit.
+ */
+
+ENTRY(ffs)
+       mov     r4,r0           ! using r0 specific instructions
+       tst     #0xff,r0
+       bf/s    L8bit
+       mov     #0+1,r1         ! ret = 1..8
+
+       tst     r0,r0           ! ffs(0) is 0
+       bt      Lzero           ! testing here to accelerate ret=1..8 cases
+
+       shlr8   r0
+       tst     #0xff,r0
+       bf/s    L8bit
+       mov     #8+1,r1         ! ret = 9..16
+
+       shlr8   r0
+       tst     #0xff,r0
+       bf/s    L8bit
+       mov     #16+1,r1        ! ret = 17..24
+
+       shlr8   r0
+       mov     #24+1,r1        ! ret = 25..32
+
+L8bit:
+       tst     #0x0f,r0
+       bt      4f
+
+       tst     #0x03,r0
+       bt      2f
+       tst     #0x01,r0        ! not bit 0 -> T
+       mov     #0,r0
+       rts
+        addc   r1,r0           ! 0 + r1 + T -> r0
+
+2:     tst     #0x04,r0
+       mov     #2,r0
+       rts
+        addc   r1,r0
+
+4:     tst     #0x30,r0
+       bt      6f
+       tst     #0x10,r0
+       mov     #4,r0
+       rts
+        addc   r1,r0
+
+6:     tst     #0x40,r0
+       mov     #6,r0
+       rts
+        addc   r1,r0
+
+Lzero: rts
+        nop
diff --git a/common/lib/libc/arch/sh3/string/memcpy.S b/common/lib/libc/arch/sh3/string/memcpy.S
new file mode 100644 (file)
index 0000000..aca97dd
--- /dev/null
@@ -0,0 +1,271 @@
+/*     $NetBSD: memcpy.S,v 1.2 2006/04/22 23:53:47 uwe Exp $   */
+
+/*
+ * Copyright (c) 2000 SHIMIZU Ryo <ryo@misakimix.org>
+ * 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.
+ * 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 ``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 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 <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: memcpy.S,v 1.2 2006/04/22 23:53:47 uwe Exp $")
+#endif
+
+#if !defined(MEMCOPY) && !defined(MEMMOVE) && !defined(BCOPY)
+#define MEMCOPY
+#endif
+
+#if defined(MEMCOPY) || defined(MEMMOVE)
+#define        REG_DST0        r3
+#define        REG_SRC         r5
+#define        REG_DST         r4
+#else
+#define        REG_SRC         r4
+#define        REG_DST         r5
+#endif
+
+#define        REG_LEN         r6
+
+#if defined(MEMCOPY)
+ENTRY(memcpy)
+#elif defined(MEMMOVE)
+ENTRY(memmove)
+#elif defined(BCOPY)
+ENTRY(bcopy)
+#endif
+#ifdef REG_DST0
+       mov     REG_DST,REG_DST0
+#endif
+       cmp/eq  REG_DST,REG_SRC /* if ( src == dst ) return; */
+       bt/s    bcopy_return
+       cmp/hi  REG_DST,REG_SRC
+       bf/s    bcopy_overlap
+
+       mov     REG_SRC,r0
+       xor     REG_DST,r0
+       and     #3,r0
+       mov     r0,r1
+       tst     r0,r0           /* (src ^ dst) & 3         */
+       bf/s    word_align
+
+longword_align:
+       tst     REG_LEN,REG_LEN /* if ( len==0 ) return;   */
+       bt/s    bcopy_return
+
+
+       mov     REG_SRC,r0
+       tst     #1,r0           /* if ( src & 1 )          */
+       bt      1f
+       mov.b   @REG_SRC+,r0    /*    *dst++ = *src++;     */
+       add     #-1,REG_LEN
+       mov.b   r0,@REG_DST
+       add     #1,REG_DST
+1:
+
+
+       mov     #1,r0
+       cmp/hi  r0,REG_LEN      /* if ( (len > 1) &&       */
+       bf/s    1f
+       mov     REG_SRC,r0
+       tst     #2,r0           /*      (src & 2) {        */
+       bt      1f
+       mov.w   @REG_SRC+,r0    /*        *((unsigned short*)dst)++ = *((unsigned short*)src)++; */
+       add     #-2,REG_LEN     /*        len -= 2;                                              */
+       mov.w   r0,@REG_DST
+       add     #2,REG_DST      /* }                       */
+1:
+
+
+       mov     #3,r1
+       cmp/hi  r1,REG_LEN      /* while ( len > 3 ) {     */
+       bf/s    no_align_delay
+       tst     REG_LEN,REG_LEN
+2:
+       mov.l   @REG_SRC+,r0    /*   *((unsigned long*)dst)++ = *((unsigned long*)src)++;        */
+       add     #-4,REG_LEN     /*   len -= 4;                                                   */
+       mov.l   r0,@REG_DST
+       cmp/hi  r1,REG_LEN
+       bt/s    2b
+       add     #4,REG_DST      /* }                       */
+
+       bra     no_align_delay
+       tst     REG_LEN,REG_LEN
+
+
+word_align:
+       mov     r1,r0
+       tst     #1,r0
+       bf/s    no_align_delay
+       tst     REG_LEN,REG_LEN /* if ( len == 0 ) return; */
+       bt      bcopy_return
+
+
+       mov     REG_SRC,r0      /* if ( src & 1 )          */
+       tst     #1,r0
+       bt      1f
+       mov.b   @REG_SRC+,r0    /*    *dst++ = *src++;     */
+       add     #-1,REG_LEN
+       mov.b   r0,@REG_DST
+       add     #1,REG_DST
+1:
+
+
+       mov     #1,r1
+       cmp/hi  r1,REG_LEN      /* while ( len > 1 ) {     */
+       bf/s    no_align_delay
+       tst     REG_LEN,REG_LEN
+2:
+       mov.w   @REG_SRC+,r0    /*   *((unsigned short*)dst)++ = *((unsigned short*)src)++;      */
+       add     #-2,REG_LEN     /*   len -= 2;                                                   */
+       mov.w   r0,@REG_DST
+       cmp/hi  r1,REG_LEN
+       bt/s    2b
+       add     #2,REG_DST      /* }                       */
+
+
+no_align:
+       tst     REG_LEN,REG_LEN /* while ( len!= ) {       */
+no_align_delay:
+       bt      bcopy_return
+1:
+       mov.b   @REG_SRC+,r0    /*    *dst++ = *src++;     */
+       add     #-1,REG_LEN     /*    len--;               */
+       mov.b   r0,@REG_DST
+       tst     REG_LEN,REG_LEN
+       bf/s    1b
+       add     #1,REG_DST      /* }                       */
+bcopy_return:
+       rts
+#ifdef REG_DST0
+       mov     REG_DST0,r0
+#else
+       nop
+#endif
+
+
+bcopy_overlap:
+       add     REG_LEN,REG_SRC
+       add     REG_LEN,REG_DST
+
+       mov     REG_SRC,r0
+       xor     REG_DST,r0
+       and     #3,r0
+       mov     r0,r1
+       tst     r0,r0           /* (src ^ dst) & 3         */
+       bf/s    ov_word_align
+
+ov_longword_align:
+       tst     REG_LEN,REG_LEN /* if ( len==0 ) return;   */
+       bt/s    bcopy_return
+
+
+       mov     REG_SRC,r0
+       tst     #1,r0           /* if ( src & 1 )          */
+       bt      1f
+       add     #-1,REG_SRC     /*    *--dst = *--src;     */
+       mov.b   @REG_SRC,r0
+       mov.b   r0,@-REG_DST
+       add     #-1,REG_LEN
+1:
+
+
+       mov     #1,r0
+       cmp/hi  r0,REG_LEN      /* if ( (len > 1) &&       */
+       bf/s    1f
+       mov     REG_SRC,r0
+       tst     #2,r0           /*      (src & 2) {        */
+       bt      1f
+       add     #-2,REG_SRC     /*        *--((unsigned short*)dst) = *--((unsigned short*)src); */
+       mov.w   @REG_SRC,r0
+       add     #-2,REG_LEN     /*        len -= 2;                                              */
+       mov.w   r0,@-REG_DST    /* }                       */
+1:
+
+
+       mov     #3,r1
+       cmp/hi  r1,REG_LEN      /* while ( len > 3 ) {     */
+       bf/s    ov_no_align_delay
+       tst     REG_LEN,REG_LEN
+2:
+       add     #-4,REG_SRC
+       mov.l   @REG_SRC,r0     /*   *((unsigned long*)dst)++ = *((unsigned long*)src)++;        */
+       add     #-4,REG_LEN     /*   len -= 4;                                                   */
+       cmp/hi  r1,REG_LEN
+       bt/s    2b
+       mov.l   r0,@-REG_DST    /* }                       */
+
+       bra     ov_no_align_delay
+       tst     REG_LEN,REG_LEN
+
+
+ov_word_align:
+       mov     r1,r0
+       tst     #1,r0
+       bf/s    ov_no_align_delay
+       tst     REG_LEN,REG_LEN /* if ( len == 0 ) return; */
+       bt      bcopy_return
+
+
+       mov     REG_SRC,r0      /* if ( src & 1 )          */
+       tst     #1,r0
+       bt      1f
+       add     #-1,REG_SRC
+       mov.b   @REG_SRC,r0     /*    *--dst = *--src;     */
+       add     #-1,REG_LEN
+       mov.b   r0,@-REG_DST
+1:
+
+
+       mov     #1,r1
+       cmp/hi  r1,REG_LEN      /* while ( len > 1 ) {     */
+       bf/s    ov_no_align_delay
+       tst     REG_LEN,REG_LEN
+2:
+       add     #-2,REG_SRC
+       mov.w   @REG_SRC,r0     /*   *--((unsigned short*)dst) = *--((unsigned short*)src);      */
+       add     #-2,REG_LEN     /*   len -= 2;                                                   */
+       cmp/hi  r1,REG_LEN
+       bt/s    2b
+       mov.w   r0,@-REG_DST    /* }                       */
+
+
+ov_no_align:
+       tst     REG_LEN,REG_LEN /* while ( len!= ) {       */
+ov_no_align_delay:
+       bt      9f
+1:
+       add     #-1,REG_SRC
+       mov.b   @REG_SRC,r0     /*    *--dst = *--src;     */
+       add     #-1,REG_LEN     /*    len--;               */
+       tst     REG_LEN,REG_LEN
+       bf/s    1b
+       mov.b   r0,@-REG_DST    /* }                       */
+9:
+       rts
+#ifdef REG_DST0
+       mov     REG_DST0,r0
+#else
+       nop
+#endif
diff --git a/common/lib/libc/arch/sh3/string/memmove.S b/common/lib/libc/arch/sh3/string/memmove.S
new file mode 100644 (file)
index 0000000..0ccd67b
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: memmove.S,v 1.2 2006/04/22 23:53:47 uwe Exp $  */
+
+#define MEMMOVE
+#include "memcpy.S"
diff --git a/common/lib/libc/arch/sh3/string/memset.S b/common/lib/libc/arch/sh3/string/memset.S
new file mode 100644 (file)
index 0000000..c0ab171
--- /dev/null
@@ -0,0 +1,298 @@
+/*     $NetBSD: memset.S,v 1.2 2008/02/16 17:37:13 apb Exp $   */
+
+/*-
+ * Copyright (c) 2002 SHIMIZU Ryo.  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.
+ * 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 ``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 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 <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: memset.S,v 1.2 2008/02/16 17:37:13 apb Exp $")
+#endif
+
+#define        REG_PTR                         r0
+#define        REG_TMP1                        r1
+
+#ifdef BZERO
+# define       REG_C                   r2
+# define       REG_DST                 r4
+# define       REG_LEN                 r5
+#else
+# define       REG_DST0                r3
+# define       REG_DST                 r4
+# define       REG_C                   r5
+# define       REG_LEN                 r6
+#endif
+
+#ifdef BZERO
+ENTRY(bzero)
+#else
+ENTRY(memset)
+       mov     REG_DST,REG_DST0        /* for return value */
+#endif
+       /* small amount to fill ? */
+       mov     #28,REG_TMP1
+       cmp/hs  REG_TMP1,REG_LEN        /* if (len >= 28) goto large; */
+       bt/s    large
+       mov     #12,REG_TMP1            /* if (len >= 12) goto small; */
+       cmp/hs  REG_TMP1,REG_LEN
+       bt/s    small
+#ifdef BZERO
+       mov     #0,REG_C
+#endif
+       /* very little fill (0 ~ 11 bytes) */
+       tst     REG_LEN,REG_LEN
+       add     REG_DST,REG_LEN
+       bt/s    done
+       add     #1,REG_DST
+
+       /* unroll 4 loops */
+       cmp/eq  REG_DST,REG_LEN
+1:     mov.b   REG_C,@-REG_LEN
+       bt/s    done
+       cmp/eq  REG_DST,REG_LEN
+       mov.b   REG_C,@-REG_LEN
+       bt/s    done
+       cmp/eq  REG_DST,REG_LEN
+       mov.b   REG_C,@-REG_LEN
+       bt/s    done
+       cmp/eq  REG_DST,REG_LEN
+       mov.b   REG_C,@-REG_LEN
+       bf/s    1b
+       cmp/eq  REG_DST,REG_LEN
+done:
+#ifdef BZERO
+       rts
+       nop
+#else
+       rts
+       mov     REG_DST0,r0
+#endif
+
+
+small:
+       mov     REG_DST,r0
+       tst     #1,r0
+       bt/s    small_aligned
+       mov     REG_DST,REG_TMP1
+       shll    REG_LEN
+       mova    1f,r0                   /* 1f must be 4bytes aligned! */
+       add     #16,REG_TMP1            /* REG_TMP1 = dst+16; */
+       sub     REG_LEN,r0
+       jmp     @r0
+       mov     REG_C,r0
+
+       .align  2
+       mov.b   r0,@(15,REG_TMP1)
+       mov.b   r0,@(14,REG_TMP1)
+       mov.b   r0,@(13,REG_TMP1)
+       mov.b   r0,@(12,REG_TMP1)
+       mov.b   r0,@(11,REG_TMP1)
+       mov.b   r0,@(10,REG_TMP1)
+       mov.b   r0,@(9,REG_TMP1)
+       mov.b   r0,@(8,REG_TMP1)
+       mov.b   r0,@(7,REG_TMP1)
+       mov.b   r0,@(6,REG_TMP1)
+       mov.b   r0,@(5,REG_TMP1)
+       mov.b   r0,@(4,REG_TMP1)
+       mov.b   r0,@(3,REG_TMP1)
+       mov.b   r0,@(2,REG_TMP1)
+       mov.b   r0,@(1,REG_TMP1)
+       mov.b   r0,@REG_TMP1
+       mov.b   r0,@(15,REG_DST)
+       mov.b   r0,@(14,REG_DST)
+       mov.b   r0,@(13,REG_DST)
+       mov.b   r0,@(12,REG_DST)
+       mov.b   r0,@(11,REG_DST)
+       mov.b   r0,@(10,REG_DST)
+       mov.b   r0,@(9,REG_DST)
+       mov.b   r0,@(8,REG_DST)
+       mov.b   r0,@(7,REG_DST)
+       mov.b   r0,@(6,REG_DST)
+       mov.b   r0,@(5,REG_DST)
+       mov.b   r0,@(4,REG_DST)
+       mov.b   r0,@(3,REG_DST)
+       mov.b   r0,@(2,REG_DST)
+       mov.b   r0,@(1,REG_DST)
+#ifdef BZERO
+       rts
+1:     mov.b   r0,@REG_DST
+#else
+       mov.b   r0,@REG_DST
+1:     rts
+       mov     REG_DST0,r0
+#endif
+
+
+/* 2 bytes aligned small fill */
+small_aligned:
+#ifndef BZERO
+       extu.b  REG_C,REG_TMP1          /* REG_C = ??????xx, REG_TMP1 = ????00xx */
+       shll8   REG_C                   /* REG_C = ????xx00, REG_TMP1 = ????00xx */
+       or      REG_TMP1,REG_C          /* REG_C = ????xxxx */
+#endif
+
+       mov     REG_LEN,r0
+       tst     #1,r0                   /* len is aligned? */
+       bt/s    1f
+       add     #-1,r0
+       mov.b   REG_C,@(r0,REG_DST)     /* fill last a byte */
+       mov     r0,REG_LEN
+1:
+
+       mova    1f,r0                   /* 1f must be 4bytes aligned! */
+       sub     REG_LEN,r0
+       jmp     @r0
+       mov     REG_C,r0
+
+       .align  2
+       mov.w   r0,@(30,REG_DST)
+       mov.w   r0,@(28,REG_DST)
+       mov.w   r0,@(26,REG_DST)
+       mov.w   r0,@(24,REG_DST)
+       mov.w   r0,@(22,REG_DST)
+       mov.w   r0,@(20,REG_DST)
+       mov.w   r0,@(18,REG_DST)
+       mov.w   r0,@(16,REG_DST)
+       mov.w   r0,@(14,REG_DST)
+       mov.w   r0,@(12,REG_DST)
+       mov.w   r0,@(10,REG_DST)
+       mov.w   r0,@(8,REG_DST)
+       mov.w   r0,@(6,REG_DST)
+       mov.w   r0,@(4,REG_DST)
+       mov.w   r0,@(2,REG_DST)
+#ifdef BZERO
+       rts
+1:     mov.w   r0,@REG_DST
+#else
+       mov.w   r0,@REG_DST
+1:     rts
+       mov     REG_DST0,r0
+#endif
+
+
+
+       .align  2
+large:
+#ifdef BZERO
+       mov     #0,REG_C
+#else
+       extu.b  REG_C,REG_TMP1          /* REG_C = ??????xx, REG_TMP1 = ????00xx */
+       shll8   REG_C                   /* REG_C = ????xx00, REG_TMP1 = ????00xx */
+       or      REG_C,REG_TMP1          /* REG_C = ????xx00, REG_TMP1 = ????xxxx */
+       swap.w  REG_TMP1,REG_C          /* REG_C = xxxx????, REG_TMP1 = ????xxxx */
+       xtrct   REG_TMP1,REG_C          /* REG_C = xxxxxxxx */
+#endif
+
+       mov     #3,REG_TMP1
+       tst     REG_TMP1,REG_DST
+       mov     REG_DST,REG_PTR
+       bf/s    unaligned_dst
+       add     REG_LEN,REG_PTR         /* REG_PTR = dst + len; */
+       tst     REG_TMP1,REG_LEN
+       bf/s    unaligned_len
+
+aligned:
+       /* fill 32*n bytes */
+       mov     #32,REG_TMP1
+       cmp/hi  REG_LEN,REG_TMP1
+       bt      9f
+       .align  2
+1:     sub     REG_TMP1,REG_PTR
+       mov.l   REG_C,@REG_PTR
+       sub     REG_TMP1,REG_LEN
+       mov.l   REG_C,@(4,REG_PTR)
+       cmp/hi  REG_LEN,REG_TMP1
+       mov.l   REG_C,@(8,REG_PTR)
+       mov.l   REG_C,@(12,REG_PTR)
+       mov.l   REG_C,@(16,REG_PTR)
+       mov.l   REG_C,@(20,REG_PTR)
+       mov.l   REG_C,@(24,REG_PTR)
+       bf/s    1b
+       mov.l   REG_C,@(28,REG_PTR)
+9:
+
+       /* fill left 4*n bytes */
+       cmp/eq  REG_DST,REG_PTR
+       bt      9f
+       add     #4,REG_DST
+       cmp/eq  REG_DST,REG_PTR
+1:     mov.l   REG_C,@-REG_PTR
+       bt/s    9f
+       cmp/eq  REG_DST,REG_PTR
+       mov.l   REG_C,@-REG_PTR
+       bt/s    9f
+       cmp/eq  REG_DST,REG_PTR
+       mov.l   REG_C,@-REG_PTR
+       bt/s    9f
+       cmp/eq  REG_DST,REG_PTR
+       mov.l   REG_C,@-REG_PTR
+       bf/s    1b
+       cmp/eq  REG_DST,REG_PTR
+9:
+#ifdef BZERO
+       rts
+       nop
+#else
+       rts
+       mov     REG_DST0,r0
+#endif
+
+
+unaligned_dst:
+       mov     #1,REG_TMP1
+       tst     REG_TMP1,REG_DST        /* if (dst & 1) {               */
+       add     #1,REG_TMP1
+       bt/s    2f
+       tst     REG_TMP1,REG_DST
+       mov.b   REG_C,@REG_DST          /*   *dst++ = c;                */
+       add     #1,REG_DST
+       tst     REG_TMP1,REG_DST
+2:                                     /* }                            */
+                                       /* if (dst & 2) {               */
+       bt      4f
+       mov.w   REG_C,@REG_DST          /*   *(uint16_t*)dst++ = c;    */
+       add     #2,REG_DST
+4:                                     /* }                            */
+
+
+       tst     #3,REG_PTR              /* if (ptr & 3) {               */
+       bt/s    4f                      /*                              */
+unaligned_len:
+       tst     #1,REG_PTR              /*   if (ptr & 1) {             */
+       bt/s    2f
+       tst     #2,REG_PTR
+       mov.b   REG_C,@-REG_PTR         /*     --ptr = c;               */
+2:                                     /*   }                          */
+                                       /*   if (ptr & 2) {             */
+       bt      4f
+       mov.w   REG_C,@-REG_PTR         /*     *--(uint16_t*)ptr = c;  */
+4:                                     /*   }                          */
+                                       /* }                            */
+
+       mov     REG_PTR,REG_LEN
+       bra     aligned
+       sub     REG_DST,REG_LEN
+
diff --git a/common/lib/libc/arch/sparc/atomic/Makefile.inc b/common/lib/libc/arch/sparc/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..dd8c33b
--- /dev/null
@@ -0,0 +1,37 @@
+#      $NetBSD: Makefile.inc,v 1.14 2009/03/13 19:16:46 abs Exp $
+
+.include <bsd.own.mk>
+
+# This is called with MACHINE=sparc64 && MACHINE_ARCH=sparc when building
+# 32 bit kernels for ultrasparc hardware
+.if ${MACHINE} == "sparc64"
+
+SPARC64DIR=    ${.PARSEDIR}/../../sparc64/atomic
+.PATH.c: ${SPARC64DIR}
+.PATH.S: ${SPARC64DIR}
+
+.include "${SPARC64DIR}/Makefile.inc"
+
+.else
+
+. if defined(LIB)
+
+.  if (${LIB} == "kern" || ${LIB} == "c"  || ${LIB} == "pthread"       \
+    || ${LIB} == "rump")
+SRCS+= atomic_add_32_cas.c atomic_add_32_nv_cas.c atomic_and_32_cas.c \
+       atomic_and_32_nv_cas.c atomic_dec_32_cas.c atomic_dec_32_nv_cas.c \
+       atomic_inc_32_cas.c atomic_inc_32_nv_cas.c atomic_or_32_cas.c \
+       atomic_or_32_nv_cas.c atomic_swap_32_cas.c membar_ops.S
+.  endif
+
+.  if (${LIB} == "kern" || ${LIB} == "rump")
+SRCS+= atomic_cas.S
+.  endif
+
+.  if (${LIB} == "c" || ${LIB} == "pthread")
+SRCS+= atomic_init_testset.c
+.  endif
+
+. endif
+
+.endif
diff --git a/common/lib/libc/arch/sparc/atomic/atomic_cas.S b/common/lib/libc/arch/sparc/atomic/atomic_cas.S
new file mode 100644 (file)
index 0000000..ab0f293
--- /dev/null
@@ -0,0 +1,144 @@
+/*     $NetBSD: atomic_cas.S,v 1.10 2009/03/13 16:40:22 nakayama Exp $ */
+
+/*-
+ * Copyright (c) 2007, 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Andrew Doran and Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/param.h>
+#include "atomic_op_asm.h"
+
+#if defined(_HARDKERNEL)
+
+#include <machine/psl.h>
+
+#include "opt_multiprocessor.h"
+
+#define        DISABLE_INTERRUPTS                                               \
+       rd      %psr, %o4                       /* disable interrupts */;\
+       or      %o4, PSR_PIL, %o5                                       ;\
+       wr      %o5, 0, %psr                                            ;\
+       nop                                                             ;\
+       nop                                                             ;\
+       nop
+
+#define        RESTORE_INTERRUPTS                                               \
+       wr      %o4, 0, %psr                    /* enable interrupts */ ;\
+       nop                                                             ;\
+       nop                                                             ;\
+       nop
+
+#else  /* _HARDKERNEL */
+
+#define        MULTIPROCESSOR  1
+#define        DISABLE_INTERRUPTS              /* nothing */
+#define        RESTORE_INTERRUPTS              /* nothing */
+
+#endif /* _HARDKERNEL */
+
+#if defined(MULTIPROCESSOR)
+       .section .bss
+       .align  1024
+OTYPE(_C_LABEL(_atomic_cas_locktab))
+_C_LABEL(_atomic_cas_locktab):
+       .space  1024
+
+#define        ACQUIRE_INTERLOCK                                                \
+       DISABLE_INTERRUPTS                                              ;\
+       srl     %o0, 3, %o5                     /* get lock address */  ;\
+       and     %o5, 1023, %o5                                          ;\
+       sethi   %hi(_C_LABEL(_atomic_cas_locktab)), %o3                 ;\
+       add     %o5, %o3, %o5                                           ;\
+                                                                       ;\
+       /* %o5 has interlock address */                                 ;\
+                                                                       ;\
+1:     ldstub  [%o5], %o3                      /* acquire lock */      ;\
+       tst     %o3                                                     ;\
+       bz,a    2f                                                      ;\
+        nop                                                            ;\
+       nop                                                             ;\
+       nop                                                             ;\
+       b,a     1b                              /* spin */              ;\
+        nop                                                            ;\
+       /* We now hold the interlock */                                 ;\
+2:
+
+#define        RELEASE_INTERLOCK                                                \
+       stb     %g0, [%o5]                      /* release interlock */ ;\
+       RESTORE_INTERRUPTS
+
+#else /* ! MULTIPROCESSOR */
+
+#define        ACQUIRE_INTERLOCK       DISABLE_INTERRUPTS
+
+#define        RELEASE_INTERLOCK       RESTORE_INTERRUPTS
+
+#endif /* MULTIPROCESSOR */
+
+       .text
+
+/*
+ * The v7 and v8 SPARC doesn't have compare-and-swap, so we block interrupts
+ * and use an interlock.
+ *
+ * XXX On single CPU systems, this should use a restartable sequence:
+ * XXX there we don't need the overhead of interlocking.
+ *
+ * XXX NOTE!  The interlock trick only works if EVERYTHING writes to
+ * XXX the memory cell through this code path!
+ */
+ENTRY(_atomic_cas_32)
+       ACQUIRE_INTERLOCK
+       ! %o4 has saved PSR value
+       ! %o5 has interlock address
+
+       ld      [%o0], %o3                      ! get old value
+       cmp     %o1, %o3                        ! old == new?
+       beq,a   3f                              ! yes, do the store
+        st     %o2, [%o0]                      ! (in the delay slot)
+
+3:     RELEASE_INTERLOCK
+
+       retl
+        mov    %o3, %o0                        ! return old value
+
+ATOMIC_OP_ALIAS(atomic_cas_32,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_uint,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_uint,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_ulong,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_ptr,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ptr,_atomic_cas_32)
+
+ATOMIC_OP_ALIAS(atomic_cas_32_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_32_ni,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_uint_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_uint_ni,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_ulong_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong_ni,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_ptr_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ptr_ni,_atomic_cas_32)
diff --git a/common/lib/libc/arch/sparc/atomic/atomic_op_asm.h b/common/lib/libc/arch/sparc/atomic/atomic_op_asm.h
new file mode 100644 (file)
index 0000000..f7472d6
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: atomic_op_asm.h,v 1.6 2011/01/17 18:11:09 joerg Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _ATOMIC_OP_ASM_H_
+#define        _ATOMIC_OP_ASM_H_
+
+#include <machine/asm.h>
+
+#if defined(_KERNEL)
+
+#define        ATOMIC_OP_ALIAS(a,s)            STRONG_ALIAS(a,s)
+
+#ifdef __arch64__
+#define        ATOMIC_OP_ALIAS_SIZE(a,s)       STRONG_ALIAS(a,s ## _64)
+#else
+#define        ATOMIC_OP_ALIAS_SIZE(a,s)       STRONG_ALIAS(a,s ## _32)
+#endif
+
+#else /* _KERNEL */
+
+#define        ATOMIC_OP_ALIAS(a,s)            WEAK_ALIAS(a,s)
+
+#ifdef __arch64__
+#define        ATOMIC_OP_ALIAS_SIZE(a,s)       WEAK_ALIAS(a,s ## _64)
+#else
+#define        ATOMIC_OP_ALIAS_SIZE(a,s)       WEAK_ALIAS(a,s ## _32)
+#endif
+
+#endif /* _KERNEL */
+
+#ifdef __arch64__
+#define        STRONG_ALIAS_SIZE(a,s)          STRONG_ALIAS(a,s ## _64)
+#else
+#define        STRONG_ALIAS_SIZE(a,s)          STRONG_ALIAS(a,s ## _32)
+#endif
+
+#endif /* _ATOMIC_OP_ASM_H_ */
diff --git a/common/lib/libc/arch/sparc/atomic/membar_ops.S b/common/lib/libc/arch/sparc/atomic/membar_ops.S
new file mode 100644 (file)
index 0000000..f3317c8
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: membar_ops.S,v 1.4 2008/05/25 15:56:12 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe, and by Andrew Doran.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+/* These assume Total Store Order (TSO) */
+
+ENTRY(_membar_producer)
+       retl
+        nop
+
+ENTRY(_membar_consumer)
+       add     %sp, -112, %sp
+       st      %g0, [%sp+100]
+       retl
+        sub    %sp, -112, %sp
+
+ATOMIC_OP_ALIAS(membar_producer,_membar_producer)
+ATOMIC_OP_ALIAS(membar_consumer,_membar_consumer)
+ATOMIC_OP_ALIAS(membar_enter,_membar_consumer)
+STRONG_ALIAS(_membar_enter,_membar_consumer)
+ATOMIC_OP_ALIAS(membar_exit,_membar_consumer)
+STRONG_ALIAS(_membar_exit,_membar_consumer)
+ATOMIC_OP_ALIAS(membar_sync,_membar_consumer)
+STRONG_ALIAS(_membar_sync,_membar_consumer)
diff --git a/common/lib/libc/arch/sparc/gen/mul.S b/common/lib/libc/arch/sparc/gen/mul.S
new file mode 100644 (file)
index 0000000..a10a9e6
--- /dev/null
@@ -0,0 +1,156 @@
+/*     $NetBSD: mul.S,v 1.1 2005/12/20 19:28:50 christos Exp $ */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: mul.s,v 1.5 92/06/25 13:24:03 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)mul.s       8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: mul.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Signed multiply, from Appendix E of the Sparc Version 8
+ * Architecture Manual.
+ *
+ * Returns %o0 * %o1 in %o1%o0 (i.e., %o1 holds the upper 32 bits of
+ * the 64-bit product).
+ *
+ * This code optimizes short (less than 13-bit) multiplies.
+ */
+
+FUNC(.mul)
+       mov     %o0, %y         ! multiplier -> Y
+       andncc  %o0, 0xfff, %g0 ! test bits 12..31
+       be      Lmul_shortway   ! if zero, can do it the short way
+       andcc   %g0, %g0, %o4   ! zero the partial product and clear N and V
+
+       /*
+        * Long multiply.  32 steps, followed by a final shift step.
+        */
+       mulscc  %o4, %o1, %o4   ! 1
+       mulscc  %o4, %o1, %o4   ! 2
+       mulscc  %o4, %o1, %o4   ! 3
+       mulscc  %o4, %o1, %o4   ! 4
+       mulscc  %o4, %o1, %o4   ! 5
+       mulscc  %o4, %o1, %o4   ! 6
+       mulscc  %o4, %o1, %o4   ! 7
+       mulscc  %o4, %o1, %o4   ! 8
+       mulscc  %o4, %o1, %o4   ! 9
+       mulscc  %o4, %o1, %o4   ! 10
+       mulscc  %o4, %o1, %o4   ! 11
+       mulscc  %o4, %o1, %o4   ! 12
+       mulscc  %o4, %o1, %o4   ! 13
+       mulscc  %o4, %o1, %o4   ! 14
+       mulscc  %o4, %o1, %o4   ! 15
+       mulscc  %o4, %o1, %o4   ! 16
+       mulscc  %o4, %o1, %o4   ! 17
+       mulscc  %o4, %o1, %o4   ! 18
+       mulscc  %o4, %o1, %o4   ! 19
+       mulscc  %o4, %o1, %o4   ! 20
+       mulscc  %o4, %o1, %o4   ! 21
+       mulscc  %o4, %o1, %o4   ! 22
+       mulscc  %o4, %o1, %o4   ! 23
+       mulscc  %o4, %o1, %o4   ! 24
+       mulscc  %o4, %o1, %o4   ! 25
+       mulscc  %o4, %o1, %o4   ! 26
+       mulscc  %o4, %o1, %o4   ! 27
+       mulscc  %o4, %o1, %o4   ! 28
+       mulscc  %o4, %o1, %o4   ! 29
+       mulscc  %o4, %o1, %o4   ! 30
+       mulscc  %o4, %o1, %o4   ! 31
+       mulscc  %o4, %o1, %o4   ! 32
+       mulscc  %o4, %g0, %o4   ! final shift
+
+       ! If %o0 was negative, the result is
+       !       (%o0 * %o1) + (%o1 << 32))
+       ! We fix that here.
+
+       tst     %o0
+       bge     1f
+       rd      %y, %o0
+
+       ! %o0 was indeed negative; fix upper 32 bits of result by subtracting 
+       ! %o1 (i.e., return %o4 - %o1 in %o1).
+       retl
+       sub     %o4, %o1, %o1
+
+1:
+       retl
+       mov     %o4, %o1
+
+Lmul_shortway:
+       /*
+        * Short multiply.  12 steps, followed by a final shift step.
+        * The resulting bits are off by 12 and (32-12) = 20 bit positions,
+        * but there is no problem with %o0 being negative (unlike above).
+        */
+       mulscc  %o4, %o1, %o4   ! 1
+       mulscc  %o4, %o1, %o4   ! 2
+       mulscc  %o4, %o1, %o4   ! 3
+       mulscc  %o4, %o1, %o4   ! 4
+       mulscc  %o4, %o1, %o4   ! 5
+       mulscc  %o4, %o1, %o4   ! 6
+       mulscc  %o4, %o1, %o4   ! 7
+       mulscc  %o4, %o1, %o4   ! 8
+       mulscc  %o4, %o1, %o4   ! 9
+       mulscc  %o4, %o1, %o4   ! 10
+       mulscc  %o4, %o1, %o4   ! 11
+       mulscc  %o4, %o1, %o4   ! 12
+       mulscc  %o4, %g0, %o4   ! final shift
+
+       /*
+        *  %o4 has 20 of the bits that should be in the low part of the
+        * result; %y has the bottom 12 (as %y's top 12).  That is:
+        *
+        *        %o4               %y
+        * +----------------+----------------+
+        * | -12- |   -20-  | -12- |   -20-  |
+        * +------(---------+------)---------+
+        *  --hi-- ----low-part----
+        *
+        * The upper 12 bits of %o4 should be sign-extended to form the
+        * high part of the product (i.e., highpart = %o4 >> 20).
+        */
+
+       rd      %y, %o5
+       sll     %o4, 12, %o0    ! shift middle bits left 12
+       srl     %o5, 20, %o5    ! shift low bits right 20, zero fill at left
+       or      %o5, %o0, %o0   ! construct low part of result
+       retl
+       sra     %o4, 20, %o1    ! ... and extract high part of result
diff --git a/common/lib/libc/arch/sparc/gen/saveregs.S b/common/lib/libc/arch/sparc/gen/saveregs.S
new file mode 100644 (file)
index 0000000..9b497ac
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: saveregs.S,v 1.1 2005/12/20 19:28:50 christos Exp $    */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: saveregs.s,v 1.1 91/07/06 17:22:33 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: saveregs.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Save register arguments in caller's `arg dump' area, so that
+ * stdarg functions work.
+ *
+ * This really should be done with a pointer to the arg dump area;
+ * our caller should allocate that area, not our caller's caller.
+ * But then, they did not let me invent the calling sequence....
+ *
+ * We assume the caller has executed a `save' instruction.
+ */
+
+ENTRY(__builtin_saveregs)
+       st      %i0, [%fp + 0x44]       ! fr->fr_argd[0]
+       st      %i1, [%fp + 0x48]       ! fr->fr_argd[1]
+       st      %i2, [%fp + 0x4c]       ! fr->fr_argd[2]
+       st      %i3, [%fp + 0x50]       ! fr->fr_argd[3]
+       st      %i4, [%fp + 0x54]       ! fr->fr_argd[4]
+       retl
+       st      %i5, [%fp + 0x58]       ! fr->fr_argd[5]
diff --git a/common/lib/libc/arch/sparc/gen/umul.S b/common/lib/libc/arch/sparc/gen/umul.S
new file mode 100644 (file)
index 0000000..1622237
--- /dev/null
@@ -0,0 +1,189 @@
+/*     $NetBSD: umul.S,v 1.1 2005/12/20 19:28:50 christos Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: umul.s,v 1.4 92/06/25 13:24:05 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)umul.s      8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: umul.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Unsigned multiply.  Returns %o0 * %o1 in %o1%o0 (i.e., %o1 holds the
+ * upper 32 bits of the 64-bit product).
+ *
+ * This code optimizes short (less than 13-bit) multiplies.  Short
+ * multiplies require 25 instruction cycles, and long ones require
+ * 45 instruction cycles.
+ *
+ * On return, overflow has occurred (%o1 is not zero) if and only if
+ * the Z condition code is clear, allowing, e.g., the following:
+ *
+ *     call    .umul
+ *     nop
+ *     bnz     overflow        (or tnz)
+ */
+
+FUNC(.umul)
+       or      %o0, %o1, %o4
+       mov     %o0, %y         ! multiplier -> Y
+       andncc  %o4, 0xfff, %g0 ! test bits 12..31 of *both* args
+       be      Lmul_shortway   ! if zero, can do it the short way
+       andcc   %g0, %g0, %o4   ! zero the partial product and clear N and V
+
+       /*
+        * Long multiply.  32 steps, followed by a final shift step.
+        */
+       mulscc  %o4, %o1, %o4   ! 1
+       mulscc  %o4, %o1, %o4   ! 2
+       mulscc  %o4, %o1, %o4   ! 3
+       mulscc  %o4, %o1, %o4   ! 4
+       mulscc  %o4, %o1, %o4   ! 5
+       mulscc  %o4, %o1, %o4   ! 6
+       mulscc  %o4, %o1, %o4   ! 7
+       mulscc  %o4, %o1, %o4   ! 8
+       mulscc  %o4, %o1, %o4   ! 9
+       mulscc  %o4, %o1, %o4   ! 10
+       mulscc  %o4, %o1, %o4   ! 11
+       mulscc  %o4, %o1, %o4   ! 12
+       mulscc  %o4, %o1, %o4   ! 13
+       mulscc  %o4, %o1, %o4   ! 14
+       mulscc  %o4, %o1, %o4   ! 15
+       mulscc  %o4, %o1, %o4   ! 16
+       mulscc  %o4, %o1, %o4   ! 17
+       mulscc  %o4, %o1, %o4   ! 18
+       mulscc  %o4, %o1, %o4   ! 19
+       mulscc  %o4, %o1, %o4   ! 20
+       mulscc  %o4, %o1, %o4   ! 21
+       mulscc  %o4, %o1, %o4   ! 22
+       mulscc  %o4, %o1, %o4   ! 23
+       mulscc  %o4, %o1, %o4   ! 24
+       mulscc  %o4, %o1, %o4   ! 25
+       mulscc  %o4, %o1, %o4   ! 26
+       mulscc  %o4, %o1, %o4   ! 27
+       mulscc  %o4, %o1, %o4   ! 28
+       mulscc  %o4, %o1, %o4   ! 29
+       mulscc  %o4, %o1, %o4   ! 30
+       mulscc  %o4, %o1, %o4   ! 31
+       mulscc  %o4, %o1, %o4   ! 32
+       mulscc  %o4, %g0, %o4   ! final shift
+
+
+       /*
+        * Normally, with the shift-and-add approach, if both numbers are
+        * positive you get the correct result.  WIth 32-bit two's-complement
+        * numbers, -x is represented as
+        *
+        *                x                 32
+        *      ( 2  -  ------ ) mod 2  *  2
+        *                 32
+        *                2
+        *
+        * (the `mod 2' subtracts 1 from 1.bbbb).  To avoid lots of 2^32s,
+        * we can treat this as if the radix point were just to the left
+        * of the sign bit (multiply by 2^32), and get
+        *
+        *      -x  =  (2 - x) mod 2
+        *
+        * Then, ignoring the `mod 2's for convenience:
+        *
+        *   x *  y     = xy
+        *  -x *  y     = 2y - xy
+        *   x * -y     = 2x - xy
+        *  -x * -y     = 4 - 2x - 2y + xy
+        *
+        * For signed multiplies, we subtract (x << 32) from the partial
+        * product to fix this problem for negative multipliers (see mul.s).
+        * Because of the way the shift into the partial product is calculated
+        * (N xor V), this term is automatically removed for the multiplicand,
+        * so we don't have to adjust.
+        *
+        * But for unsigned multiplies, the high order bit wasn't a sign bit,
+        * and the correction is wrong.  So for unsigned multiplies where the
+        * high order bit is one, we end up with xy - (y << 32).  To fix it
+        * we add y << 32.
+        */
+       tst     %o1
+       bl,a    1f              ! if %o1 < 0 (high order bit = 1),
+       add     %o4, %o0, %o4   ! %o4 += %o0 (add y to upper half)
+1:     rd      %y, %o0         ! get lower half of product
+       retl
+       addcc   %o4, %g0, %o1   ! put upper half in place and set Z for %o1==0
+
+Lmul_shortway:
+       /*
+        * Short multiply.  12 steps, followed by a final shift step.
+        * The resulting bits are off by 12 and (32-12) = 20 bit positions,
+        * but there is no problem with %o0 being negative (unlike above),
+        * and overflow is impossible (the answer is at most 24 bits long).
+        */
+       mulscc  %o4, %o1, %o4   ! 1
+       mulscc  %o4, %o1, %o4   ! 2
+       mulscc  %o4, %o1, %o4   ! 3
+       mulscc  %o4, %o1, %o4   ! 4
+       mulscc  %o4, %o1, %o4   ! 5
+       mulscc  %o4, %o1, %o4   ! 6
+       mulscc  %o4, %o1, %o4   ! 7
+       mulscc  %o4, %o1, %o4   ! 8
+       mulscc  %o4, %o1, %o4   ! 9
+       mulscc  %o4, %o1, %o4   ! 10
+       mulscc  %o4, %o1, %o4   ! 11
+       mulscc  %o4, %o1, %o4   ! 12
+       mulscc  %o4, %g0, %o4   ! final shift
+
+       /*
+        * %o4 has 20 of the bits that should be in the result; %y has
+        * the bottom 12 (as %y's top 12).  That is:
+        *
+        *        %o4               %y
+        * +----------------+----------------+
+        * | -12- |   -20-  | -12- |   -20-  |
+        * +------(---------+------)---------+
+        *         -----result-----
+        *
+        * The 12 bits of %o4 left of the `result' area are all zero;
+        * in fact, all top 20 bits of %o4 are zero.
+        */
+
+       rd      %y, %o5
+       sll     %o4, 12, %o0    ! shift middle bits left 12
+       srl     %o5, 20, %o5    ! shift low bits right 20
+       or      %o5, %o0, %o0
+       retl
+       addcc   %g0, %g0, %o1   ! %o1 = zero, and set Z
diff --git a/common/lib/libc/arch/sparc/net/htonl.S b/common/lib/libc/arch/sparc/net/htonl.S
new file mode 100644 (file)
index 0000000..17e1986
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: htonl.S,v 1.1 2005/12/20 19:28:50 christos Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: htonl.s,v 1.1 92/06/25 12:47:05 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)htonl.s     8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: htonl.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* netorder = htonl(hostorder) */
+
+
+ENTRY(htonl)
+       retl
+        nop
diff --git a/common/lib/libc/arch/sparc/net/htons.S b/common/lib/libc/arch/sparc/net/htons.S
new file mode 100644 (file)
index 0000000..14daafa
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: htons.S,v 1.1 2005/12/20 19:28:50 christos Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: htons.s,v 1.1 92/06/25 12:47:05 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)htons.s     8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: htons.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* netorder = htons(hostorder) */
+ENTRY(htons)
+       sethi   %hi(0xffff0000), %o1
+       retl
+        andn   %o0, %o1, %o0
diff --git a/common/lib/libc/arch/sparc/net/ntohl.S b/common/lib/libc/arch/sparc/net/ntohl.S
new file mode 100644 (file)
index 0000000..4fc522a
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: ntohl.S,v 1.1 2005/12/20 19:28:50 christos Exp $       */
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: ntohl.s,v 1.1 92/06/25 12:47:06 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)ntohl.s     8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: ntohl.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* hostorder = ntohl(netorder) */
+ENTRY(ntohl)
+       retl
+        nop
diff --git a/common/lib/libc/arch/sparc/net/ntohs.S b/common/lib/libc/arch/sparc/net/ntohs.S
new file mode 100644 (file)
index 0000000..8ab7511
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: ntohs.S,v 1.1 2005/12/20 19:28:50 christos Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: ntohs.s,v 1.1 92/06/25 12:47:07 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)ntohs.s     8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: ntohs.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* hostorder = ntohs(netorder) */
+
+ENTRY(ntohs)
+       sethi   %hi(0xffff0000), %o1
+       retl
+        andn   %o0, %o1, %o0
diff --git a/common/lib/libc/arch/sparc/string/bzero.S b/common/lib/libc/arch/sparc/string/bzero.S
new file mode 100644 (file)
index 0000000..857bf20
--- /dev/null
@@ -0,0 +1,179 @@
+/*     $NetBSD: bzero.S,v 1.1 2005/12/20 19:28:50 christos Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: bzero.s,v 1.1 92/06/25 12:52:46 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)bzero.s     8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: bzero.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif  /* LIBC_SCCS and not lint */
+
+/*
+ * We should unroll the loop, but at the moment this would
+ * gain nothing since the `std' instructions are what limits us.
+ */
+
+#ifdef MEMSET
+/*
+ * void *
+ * memset(void *addr, int pattern, size_t len)
+ */
+ENTRY(memset)
+       ! %o0 = addr, %o1 = pattern, %o2 = len
+       /*
+        * Expand the byte pattern to fill 64 bits in an even-aligned
+        * register pair; shuffle arguments to match those of bzero.
+        */
+       and     %o1, 0xff, %o3
+       mov     %o2, %o1                ! shuffle argument
+       sll     %o3, 8, %o2
+       or      %o2, %o3, %o2
+       mov     %o0, %g1                ! save original pointer
+       sll     %o2, 16, %o3
+       or      %o2, %o3, %o2
+       ! Optimize a common case: addr and len are both multiples of 8.
+       or      %o0, %o1, %o5
+       btst    7, %o5                  ! ((addr | len) & 7) != 0?
+       bnz     1f                      ! if so, cannot optimize
+        mov    %o2, %o3                ! in any case, complete pat expansion
+#else
+/*
+ * void
+ * bzero(void *addr, size_t len)
+ */
+ENTRY(bzero)
+       ! %o0 = addr, %o1 = len
+
+       clr     %o2
+       ! Optimize a common case: addr and len are both multiples of 8.
+       or      %o0, %o1, %o5
+       btst    7, %o5                  ! ((addr | len) & 7) != 0?
+       bnz     1f                      ! if so, cannot optimize
+        clr    %o3                     ! in any case, we want o3=0
+#endif
+
+       /* `Good' operands, can just store doubles. */
+0:
+       deccc   8, %o1                  ! while ((len -= 8) >= 0)
+       bge,a   0b
+        std    %o2, [%o0 + %o1]        !       *(quad *)(addr + len) = 0;
+       retl
+        nop
+
+       /*
+        * Either the address is unaligned, or the count is not a
+        * multiple of 8, or both.  We will have to align the address
+        * in order to use anything `better' than stb.
+        */
+1:
+       cmp     %o1, 15                 ! len >= 15?
+       bge,a   Lstd                    ! yes, use std
+        btst   1, %o0                  ! (but first check alignment)
+
+       ! not enough to bother: do byte-at-a-time loop.
+2:
+       deccc   %o1                     ! while (--len >= 0)
+       bge,a   2b
+        stb    %o2, [%o0 + %o1]        !       addr[len] = 0;
+       retl
+        nop
+
+Lstd:
+       /*
+        * There are at least 15 bytes to zero.
+        * We may have to zero some initial stuff to align
+        * the address.
+        */
+       bz,a    1f                      ! if (addr & 1) {
+        btst   2, %o0
+       stb     %o2, [%o0]              !       *addr = 0;
+       inc     %o0                     !       addr++;
+       dec     %o1                     !       len--;
+       btst    2, %o0                  ! }
+1:
+       bz,a    1f                      ! if (addr & 2) {
+        btst   4, %o0
+       sth     %o2, [%o0]              !       *(short *)addr = 0;
+       inc     2, %o0                  !       addr += 2;
+       dec     2, %o1                  !       len -= 2;
+       btst    4, %o0                  ! }
+1:
+       bz      1f                      ! if (addr & 4) {
+        dec    8, %o1
+       st      %o2, [%o0]              !       *(int *)addr = 0;
+       inc     4, %o0                  !       addr += 4;
+       dec     4, %o1                  !       len -= 4;
+                                       ! }
+       /*
+        * Address is double word aligned; len is 8 less than
+        * the number of bytes remaining (i.e., len is 0 if
+        * the remaining count is 8, 1 if it is 9, etc.).
+        */
+1:
+       std     %o2, [%o0]              ! do {
+2:                                     !       *(quad *)addr = 0;
+       inc     8, %o0                  !       addr += 8;
+       deccc   8, %o1                  ! } while ((len -= 8) >= 0);
+        bge,a  2b
+       std     %o2, [%o0]
+
+       /*
+        * Len is in [-8..-1] where -8 => done, -7 => 1 byte to zero,
+        * -6 => two bytes, etc.  Mop up this remainder, if any.
+        */
+       btst    4, %o1
+       bz      1f                      ! if (len & 4) {
+        btst   2, %o1
+       st      %o2, [%o0]              !       *(int *)addr = 0;
+       inc     4, %o0                  !       addr += 4;
+1:
+       bz      1f                      ! if (len & 2) {
+        btst   1, %o1
+       sth     %o2, [%o0]              !       *(short *)addr = 0;
+       inc     2, %o0                  !       addr += 2;
+1:
+       bnz,a   1f                      ! if (len & 1)
+        stb    %o2, [%o0]              !       *addr = 0;
+1:
+       retl
+#ifdef MEMSET
+        mov    %g1, %o0                ! restore original pointer
+#else
+        nop
+#endif
diff --git a/common/lib/libc/arch/sparc/string/ffs.S b/common/lib/libc/arch/sparc/string/ffs.S
new file mode 100644 (file)
index 0000000..104e362
--- /dev/null
@@ -0,0 +1,113 @@
+/*     $NetBSD: ffs.S,v 1.2 2009/12/19 19:09:48 pooka Exp $    */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: ffs.s,v 1.3 92/07/07 00:23:57 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)ffs.s       8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: ffs.S,v 1.2 2009/12/19 19:09:48 pooka Exp $")
+#endif
+#endif  /* LIBC_SCCS and not lint */
+
+/*
+ * ffs returns the number of the rightmost bit set in its argument,
+ * i.e., the lowest value such that (x & (ffs(x) - 1)) is nonzero.
+ * If no bits are set, ffs returns 0.
+ *
+ * We use a table lookup on each byte.
+ *
+ * In each section below, %o1 is the current byte (0, 1, 2, or 3).
+ * The last byte is handled specially: for the first three,
+ * if that byte is nonzero, we return the table value
+ * (plus 0, 8, or 16 for the byte number), but for the last
+ * one, we just return the table value plus 24.  This means
+ * that ffstab[0] must be -24 so that ffs(0) will return 0.
+ */
+ENTRY(ffs)
+#ifdef PIC
+       PICCY_SET(ffstab, %o2, %o3)
+#else
+       set     ffstab, %o2
+#endif
+       andcc   %o0, 0xff, %o1  ! get low byte
+       be,a    1f              ! try again if 0
+        srl    %o0, 8, %o0     ! delay slot, get ready for next byte
+
+       retl                    ! return ffstab[%o1]
+        ldsb   [%o2 + %o1], %o0
+
+1:
+       andcc   %o0, 0xff, %o1  ! byte 1 like byte 0...
+       be,a    2f
+        srl    %o0, 8, %o0     ! (use delay to prepare for byte 2)
+
+       ldsb    [%o2 + %o1], %o0
+       retl                    ! return ffstab[%o1] + 8
+        add    %o0, 8, %o0
+
+2:
+       andcc   %o0, 0xff, %o1
+       be,a    3f
+        srl    %o0, 8, %o0     ! (prepare for byte 3)
+
+       ldsb    [%o2 + %o1], %o0
+       retl                    ! return ffstab[%o1] + 16
+        add    %o0, 16, %o0
+
+3:                             ! just return ffstab[%o0] + 24
+       ldsb    [%o2 + %o0], %o0
+       retl
+        add    %o0, 24, %o0
+
+ffstab:
+       .byte   -24,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 00-0f */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 10-1f */
+       .byte   6,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 20-2f */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 30-3f */
+       .byte   7,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 40-4f */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 50-5f */
+       .byte   6,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 60-6f */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 70-7f */
+       .byte   8,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 80-8f */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 10-9f */
+       .byte   6,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* a0-af */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* b0-bf */
+       .byte   7,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* c0-cf */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* d0-df */
+       .byte   6,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* e0-ef */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* f0-ff */
diff --git a/common/lib/libc/arch/sparc/string/memset.S b/common/lib/libc/arch/sparc/string/memset.S
new file mode 100644 (file)
index 0000000..9bbf1eb
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: memset.S,v 1.1 2005/12/20 19:28:50 christos Exp $      */
+
+#define MEMSET
+#include "bzero.S"
diff --git a/common/lib/libc/arch/sparc/string/strlen.S b/common/lib/libc/arch/sparc/string/strlen.S
new file mode 100644 (file)
index 0000000..0bb811e
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: strlen.S,v 1.1 2005/12/20 19:28:50 christos Exp $      */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: strlen.s,v 1.1 92/06/25 12:52:47 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)strlen.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: strlen.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(strlen)
+       add     %o0, 1, %o1     ! save starting point + 1
+1:
+       ldsb    [%o0], %o2      ! fetch byte
+       tst     %o2             ! null?
+       bne     1b              ! no, keep going
+       inc     %o0             ! always increment pointer
+       retl
+       sub     %o0, %o1, %o0   ! return length (ptr - (origptr+1))
diff --git a/common/lib/libc/arch/sparc64/atomic/Makefile.inc b/common/lib/libc/arch/sparc64/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..bc05890
--- /dev/null
@@ -0,0 +1,15 @@
+#      $NetBSD: Makefile.inc,v 1.6 2009/01/04 17:54:29 pooka Exp $
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "c" || ${LIB} == "pthread" \
+       || ${LIB} == "rump")
+
+SRCS+= atomic_add.S atomic_and.S atomic_cas.S atomic_dec.S \
+       atomic_inc.S atomic_or.S atomic_swap.S membar_ops.S
+
+.endif
+
+.if defined(LIB) && (${LIB} == "c" || ${LIB} == "pthread")
+
+SRCS+= atomic_init_cas.c
+
+.endif
diff --git a/common/lib/libc/arch/sparc64/atomic/atomic_add.S b/common/lib/libc/arch/sparc64/atomic/atomic_add.S
new file mode 100644 (file)
index 0000000..f9df717
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: atomic_add.S,v 1.6 2008/05/25 15:56:12 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_add_32)
+       ld      [%o0], %o2
+1:     add     %o1, %o2, %o3
+       cas     [%o0], %o2, %o3
+       cmp     %o2, %o3
+       bne,a,pn %icc, 1b
+        mov    %o3, %o2
+       retl
+        add    %o1, %o2, %o0
+ATOMIC_OP_ALIAS(atomic_add_32,_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_int,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_int,_atomic_add_32)
+
+ATOMIC_OP_ALIAS(atomic_add_32_nv,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_32_nv,_atomic_add_32)
+ATOMIC_OP_ALIAS(atomic_add_int_nv,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_int_nv,_atomic_add_32)
+
+ENTRY(_atomic_add_64)
+       ldx     [%o0], %o2
+1:     add     %o1, %o2, %o3
+       casx    [%o0], %o2, %o3
+       cmp     %o2, %o3
+       bne,a,pn %xcc, 1b
+        mov    %o3, %o2
+       retl
+        add    %o1, %o2, %o0
+ATOMIC_OP_ALIAS(atomic_add_64,_atomic_add_64)
+
+ATOMIC_OP_ALIAS(atomic_add_64_nv,_atomic_add_64)
+STRONG_ALIAS(_atomic_add_64_nv,_atomic_add_64)
+
+ATOMIC_OP_ALIAS_SIZE(atomic_add_long,_atomic_add)
+STRONG_ALIAS_SIZE(_atomic_add_long,_atomic_add)
+ATOMIC_OP_ALIAS_SIZE(atomic_add_ptr,_atomic_add)
+STRONG_ALIAS_SIZE(_atomic_add_ptr,_atomic_add)
+
+ATOMIC_OP_ALIAS_SIZE(atomic_add_long_nv,_atomic_add)
+STRONG_ALIAS_SIZE(_atomic_add_long_nv,_atomic_add)
+ATOMIC_OP_ALIAS_SIZE(atomic_add_ptr_nv,_atomic_add)
+STRONG_ALIAS_SIZE(_atomic_add_ptr_nv,_atomic_add)
diff --git a/common/lib/libc/arch/sparc64/atomic/atomic_and.S b/common/lib/libc/arch/sparc64/atomic/atomic_and.S
new file mode 100644 (file)
index 0000000..d60b3b5
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: atomic_and.S,v 1.6 2008/05/25 15:56:12 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_and_32)
+       ld      [%o0], %o2
+1:     and     %o1, %o2, %o3
+       cas     [%o0], %o2, %o3
+       cmp     %o2, %o3
+       bne,a,pn %icc, 1b
+        mov    %o3, %o2
+       retl
+        and    %o1, %o2, %o0
+ATOMIC_OP_ALIAS(atomic_and_32,_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_uint,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_uint,_atomic_and_32)
+
+ATOMIC_OP_ALIAS(atomic_and_32_nv,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_32_nv,_atomic_and_32)
+ATOMIC_OP_ALIAS(atomic_and_uint_nv,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_uint_nv,_atomic_and_32)
+
+ENTRY(_atomic_and_64)
+       ldx     [%o0], %o2
+1:     and     %o1, %o2, %o3
+       casx    [%o0], %o2, %o3
+       cmp     %o2, %o3
+       bne,a,pn %xcc, 1b
+        mov    %o3, %o2
+       retl
+        and    %o1, %o2, %o0
+ATOMIC_OP_ALIAS(atomic_and_64,_atomic_and_64)
+
+ATOMIC_OP_ALIAS(atomic_and_64_nv,_atomic_and_64)
+STRONG_ALIAS(_atomic_and_64_nv,_atomic_and_64)
+
+ATOMIC_OP_ALIAS_SIZE(atomic_and_ulong,_atomic_and)
+STRONG_ALIAS_SIZE(_atomic_and_ulong,_atomic_and)
+
+ATOMIC_OP_ALIAS_SIZE(atomic_and_ulong_nv,_atomic_and)
+STRONG_ALIAS_SIZE(_atomic_and_ulong_nv,_atomic_and)
diff --git a/common/lib/libc/arch/sparc64/atomic/atomic_cas.S b/common/lib/libc/arch/sparc64/atomic/atomic_cas.S
new file mode 100644 (file)
index 0000000..03668b5
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: atomic_cas.S,v 1.6 2008/05/25 15:56:12 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007, 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_cas_32)
+       cas     [%o0], %o1, %o2
+       retl
+        mov    %o2, %o0
+
+ATOMIC_OP_ALIAS(atomic_cas_32,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_uint,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_uint,_atomic_cas_32)
+
+ATOMIC_OP_ALIAS(atomic_cas_32_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_32_ni,_atomic_cas_32)
+ATOMIC_OP_ALIAS(atomic_cas_uint_ni,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_uint_ni,_atomic_cas_32)
+
+ENTRY(_atomic_cas_64)
+       casx    [%o0], %o1, %o2
+       retl
+        mov    %o2, %o0
+
+ATOMIC_OP_ALIAS(atomic_cas_64,_atomic_cas_64)
+ATOMIC_OP_ALIAS_SIZE(atomic_cas_ulong,_atomic_cas)
+STRONG_ALIAS_SIZE(_atomic_cas_ulong,_atomic_cas)
+ATOMIC_OP_ALIAS_SIZE(atomic_cas_ptr,_atomic_cas)
+STRONG_ALIAS_SIZE(_atomic_cas_ptr,_atomic_cas)
+
+ATOMIC_OP_ALIAS(atomic_cas_64_ni,_atomic_cas_64)
+STRONG_ALIAS_SIZE(_atomic_cas_64_ni,_atomic_cas)
+ATOMIC_OP_ALIAS_SIZE(atomic_cas_ulong_ni,_atomic_cas)
+STRONG_ALIAS_SIZE(_atomic_cas_ulong_ni,_atomic_cas)
+ATOMIC_OP_ALIAS_SIZE(atomic_cas_ptr_ni,_atomic_cas)
+STRONG_ALIAS_SIZE(_atomic_cas_ptr_ni,_atomic_cas)
diff --git a/common/lib/libc/arch/sparc64/atomic/atomic_dec.S b/common/lib/libc/arch/sparc64/atomic/atomic_dec.S
new file mode 100644 (file)
index 0000000..79dbac8
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: atomic_dec.S,v 1.7 2008/05/25 15:56:12 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_dec_32)
+       ld      [%o0], %o2
+1:     add     %o2, -1, %o3
+       cas     [%o0], %o2, %o3
+       cmp     %o2, %o3
+       bne,a,pn %icc, 1b
+        mov    %o3, %o2
+       retl
+        add    %o2, -1, %o0
+ATOMIC_OP_ALIAS(atomic_dec_32,_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_uint,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_uint,_atomic_dec_32)
+
+ATOMIC_OP_ALIAS(atomic_dec_32_nv,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_32_nv,_atomic_dec_32)
+ATOMIC_OP_ALIAS(atomic_dec_uint_nv,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_uint_nv,_atomic_dec_32)
+
+ENTRY(_atomic_dec_64)
+       ldx     [%o0], %o2
+1:     add     %o2, -1, %o3
+       casx    [%o0], %o2, %o3
+       cmp     %o2, %o3
+       bne,a,pn %xcc, 1b
+        mov    %o3, %o2
+       retl
+        add    %o2, -1, %o0
+ATOMIC_OP_ALIAS(atomic_dec_64,_atomic_dec_64)
+
+ATOMIC_OP_ALIAS(atomic_dec_64_nv,_atomic_dec_64)
+STRONG_ALIAS(_atomic_dec_64_nv,_atomic_dec_64)
+
+ATOMIC_OP_ALIAS_SIZE(atomic_dec_ulong,_atomic_dec)
+STRONG_ALIAS_SIZE(_atomic_dec_ulong,_atomic_dec)
+ATOMIC_OP_ALIAS_SIZE(atomic_dec_ptr,_atomic_dec)
+STRONG_ALIAS_SIZE(_atomic_dec_ptr,_atomic_dec)
+
+ATOMIC_OP_ALIAS_SIZE(atomic_dec_ulong_nv,_atomic_dec)
+STRONG_ALIAS_SIZE(_atomic_dec_ulong_nv,_atomic_dec)
+ATOMIC_OP_ALIAS_SIZE(atomic_dec_ptr_nv,_atomic_dec)
+STRONG_ALIAS_SIZE(_atomic_dec_ptr_nv,_atomic_dec)
diff --git a/common/lib/libc/arch/sparc64/atomic/atomic_inc.S b/common/lib/libc/arch/sparc64/atomic/atomic_inc.S
new file mode 100644 (file)
index 0000000..7c01286
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: atomic_inc.S,v 1.6 2008/05/25 15:56:12 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_inc_32)
+       ld      [%o0], %o2
+1:     add     %o2, 1, %o3
+       cas     [%o0], %o2, %o3
+       cmp     %o2, %o3
+       bne,a,pn %icc, 1b
+        mov    %o3, %o2
+       retl
+        add    %o2, 1, %o0
+ATOMIC_OP_ALIAS(atomic_inc_32,_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_uint,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_uint,_atomic_inc_32)
+
+ATOMIC_OP_ALIAS(atomic_inc_32_nv,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_32_nv,_atomic_inc_32)
+ATOMIC_OP_ALIAS(atomic_inc_uint_nv,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_uint_nv,_atomic_inc_32)
+
+ENTRY(_atomic_inc_64)
+       ldx     [%o0], %o2
+1:     add     %o2, 1, %o3
+       casx    [%o0], %o2, %o3
+       cmp     %o2, %o3
+       bne,a,pn %xcc, 1b
+        mov    %o3, %o2
+       retl
+        add    %o2, 1, %o0
+ATOMIC_OP_ALIAS(atomic_inc_64,_atomic_inc_64)
+
+ATOMIC_OP_ALIAS(atomic_inc_64_nv,_atomic_inc_64)
+STRONG_ALIAS(_atomic_inc_64_nv,_atomic_inc_64)
+
+ATOMIC_OP_ALIAS_SIZE(atomic_inc_ulong,_atomic_inc)
+STRONG_ALIAS_SIZE(_atomic_inc_ulong,_atomic_inc)
+ATOMIC_OP_ALIAS_SIZE(atomic_inc_ptr,_atomic_inc)
+STRONG_ALIAS_SIZE(_atomic_inc_ptr,_atomic_inc)
+
+ATOMIC_OP_ALIAS_SIZE(atomic_inc_ulong_nv,_atomic_inc)
+STRONG_ALIAS_SIZE(_atomic_inc_ulong_nv,_atomic_inc)
+ATOMIC_OP_ALIAS_SIZE(atomic_inc_ptr_nv,_atomic_inc)
+STRONG_ALIAS_SIZE(_atomic_inc_ptr_nv,_atomic_inc)
diff --git a/common/lib/libc/arch/sparc64/atomic/atomic_op_asm.h b/common/lib/libc/arch/sparc64/atomic/atomic_op_asm.h
new file mode 100644 (file)
index 0000000..68c6112
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: atomic_op_asm.h,v 1.6 2011/01/17 18:11:10 joerg Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _ATOMIC_OP_ASM_H_
+#define        _ATOMIC_OP_ASM_H_
+
+#include <machine/asm.h>
+
+#if defined(_KERNEL)
+
+#define        ATOMIC_OP_ALIAS(a,s)            STRONG_ALIAS(a,s)
+
+#ifdef __arch64__
+#define        ATOMIC_OP_ALIAS_SIZE(a,s)       STRONG_ALIAS(a,s ## _64)
+#else
+#define        ATOMIC_OP_ALIAS_SIZE(a,s)       STRONG_ALIAS(a,s ## _32)
+#endif
+
+#else /* _KERNEL */
+
+#define        ATOMIC_OP_ALIAS(a,s)            WEAK_ALIAS(a,s)
+
+#ifdef __arch64__
+#define        ATOMIC_OP_ALIAS_SIZE(a,s)       WEAK_ALIAS(a,s ## _64)
+#else
+#define        ATOMIC_OP_ALIAS_SIZE(a,s)       WEAK_ALIAS(a,s ## _32)
+#endif
+
+#endif /* _KERNEL */
+
+#ifdef __arch64__
+#define        STRONG_ALIAS_SIZE(a,s)          STRONG_ALIAS(a,s ## _64)
+#else
+#define        STRONG_ALIAS_SIZE(a,s)          STRONG_ALIAS(a,s ## _32)
+#endif
+
+#endif /* _ATOMIC_OP_ASM_H_ */
diff --git a/common/lib/libc/arch/sparc64/atomic/atomic_or.S b/common/lib/libc/arch/sparc64/atomic/atomic_or.S
new file mode 100644 (file)
index 0000000..edb82d3
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: atomic_or.S,v 1.7 2008/05/25 15:56:12 chs Exp $        */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_or_32)
+       ld      [%o0], %o2
+1:     or      %o1, %o2, %o3
+       cas     [%o0], %o2, %o3
+       cmp     %o2, %o3
+       bne,a,pn %icc, 1b
+        mov    %o3, %o2
+       retl
+        or     %o1, %o2, %o0
+ATOMIC_OP_ALIAS(atomic_or_32,_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_uint,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_uint,_atomic_or_32)
+
+ATOMIC_OP_ALIAS(atomic_or_32_nv,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_32_nv,_atomic_or_32)
+ATOMIC_OP_ALIAS(atomic_or_uint_nv,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_uint_nv,_atomic_or_32)
+
+ENTRY(_atomic_or_64)
+       ldx     [%o0], %o2
+1:     or      %o1, %o2, %o3
+       casx    [%o0], %o2, %o3
+       cmp     %o2, %o3
+       bne,a,pn %xcc, 1b
+        mov    %o3, %o2
+       retl
+        or     %o1, %o2, %o0
+ATOMIC_OP_ALIAS(atomic_or_64,_atomic_or_64)
+
+ATOMIC_OP_ALIAS(atomic_or_64_nv,_atomic_or_64)
+STRONG_ALIAS(_atomic_or_64_nv,_atomic_or_64)
+
+ATOMIC_OP_ALIAS_SIZE(atomic_or_ulong,_atomic_or)
+STRONG_ALIAS_SIZE(_atomic_or_ulong,_atomic_or)
+
+ATOMIC_OP_ALIAS_SIZE(atomic_or_ulong_nv,_atomic_or)
+STRONG_ALIAS_SIZE(_atomic_or_ulong_nv,_atomic_or)
diff --git a/common/lib/libc/arch/sparc64/atomic/atomic_swap.S b/common/lib/libc/arch/sparc64/atomic/atomic_swap.S
new file mode 100644 (file)
index 0000000..03f3288
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: atomic_swap.S,v 1.6 2008/05/25 15:56:12 chs Exp $      */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+ENTRY(_atomic_swap_32)
+       ld      [%o0], %o2
+1:     mov     %o1, %o3
+       cas     [%o0], %o2, %o3
+       cmp     %o2, %o3
+       bne,a,pn %icc, 1b
+        mov    %o3, %o2
+       retl
+        mov    %o3, %o0
+ATOMIC_OP_ALIAS(atomic_swap_32,_atomic_swap_32)
+ATOMIC_OP_ALIAS(atomic_swap_uint,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_uint,_atomic_swap_32)
+
+ENTRY(_atomic_swap_64)
+       ldx     [%o0], %o2
+1:     mov     %o1, %o3
+       casx    [%o0], %o2, %o3
+       cmp     %o2, %o3
+       bne,a,pn %xcc, 1b
+        mov    %o3, %o2
+       retl
+        mov    %o3, %o0
+ATOMIC_OP_ALIAS(atomic_swap_64,_atomic_swap_64)
+
+ATOMIC_OP_ALIAS_SIZE(atomic_swap_ulong,_atomic_swap)
+STRONG_ALIAS_SIZE(_atomic_swap_ulong,_atomic_swap)
+ATOMIC_OP_ALIAS_SIZE(atomic_swap_ptr,_atomic_swap)
+STRONG_ALIAS_SIZE(_atomic_swap_ptr,_atomic_swap)
diff --git a/common/lib/libc/arch/sparc64/atomic/membar_ops.S b/common/lib/libc/arch/sparc64/atomic/membar_ops.S
new file mode 100644 (file)
index 0000000..a3f5cb5
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: membar_ops.S,v 1.5 2008/05/25 15:56:12 chs Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe, and by Andrew Doran.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_asm.h"
+
+       .text
+
+/* These assume Total Store Order (TSO) */
+
+ENTRY(_membar_producer)
+       retl
+        nop
+
+ENTRY(_membar_consumer)
+       membar  #LoadLoad
+       retl
+        nop
+
+ATOMIC_OP_ALIAS(membar_producer,_membar_producer)
+ATOMIC_OP_ALIAS(membar_consumer,_membar_consumer)
+ATOMIC_OP_ALIAS(membar_enter,_membar_consumer)
+STRONG_ALIAS(_membar_enter,_membar_consumer)
+ATOMIC_OP_ALIAS(membar_exit,_membar_consumer)
+STRONG_ALIAS(_membar_exit,_membar_consumer)
+ATOMIC_OP_ALIAS(membar_sync,_membar_consumer)
+STRONG_ALIAS(_membar_sync,_membar_consumer)
diff --git a/common/lib/libc/arch/sparc64/gen/mul.S b/common/lib/libc/arch/sparc64/gen/mul.S
new file mode 100644 (file)
index 0000000..b4f9f34
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: mul.S,v 1.1 2005/12/20 19:28:50 christos Exp $ */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: mul.s,v 1.5 92/06/25 13:24:03 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)mul.s       8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: mul.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Signed multiply.
+ *
+ * Returns %o0 * %o1 in %o0 
+ *
+ * According to the manual the smaller parameter should be in
+ * rs1, so we'll move it there.  
+ */
+
+FUNC(.mul)
+       cmp     %o0, %o1
+       bge     1f
+        nop
+       retl
+        mulx   %o0, %o1, %o0
+1:
+       retl
+        mulx   %o1, %o0, %o0
diff --git a/common/lib/libc/arch/sparc64/gen/saveregs.S b/common/lib/libc/arch/sparc64/gen/saveregs.S
new file mode 100644 (file)
index 0000000..0cd77ba
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: saveregs.S,v 1.1 2005/12/20 19:28:50 christos Exp $    */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: saveregs.s,v 1.1 91/07/06 17:22:33 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: saveregs.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Save register arguments in caller's `arg dump' area, so that
+ * stdarg functions work.
+ *
+ * This really should be done with a pointer to the arg dump area;
+ * our caller should allocate that area, not our caller's caller.
+ * But then, they did not let me invent the calling sequence....
+ *
+ * We assume the caller has executed a `save' instruction.
+ */
+#define        REGOFF  (BIAS - CC64FSZ)
+       
+ENTRY(__builtin_saveregs)
+       stx     %i0, [%fp + REGOFF + 0x00]      ! fr->fr_argd[0]
+       stx     %i1, [%fp + REGOFF + 0x08]      ! fr->fr_argd[1]
+       stx     %i2, [%fp + REGOFF + 0x10]      ! fr->fr_argd[2]
+       stx     %i3, [%fp + REGOFF + 0x18]      ! fr->fr_argd[3]
+       stx     %i4, [%fp + REGOFF + 0x20]      ! fr->fr_argd[4]
+       retl
+        stx    %i5, [%fp + REGOFF + 0x28]      ! fr->fr_argd[5]
diff --git a/common/lib/libc/arch/sparc64/gen/umul.S b/common/lib/libc/arch/sparc64/gen/umul.S
new file mode 100644 (file)
index 0000000..d97d01b
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: umul.S,v 1.1 2005/12/20 19:28:50 christos Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: umul.s,v 1.4 92/06/25 13:24:05 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)umul.s      8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: umul.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Unsigned multiply.  Returns %o0 * %o1 in %o0
+ *     
+ * According to the manual the smaller parameter should be in
+ * rs1, so we'll move it there.  
+ */
+
+FUNC(.umul)
+       cmp     %o0, %o1
+       bge     1f
+        nop
+       retl
+        mulx   %o0, %o1, %o0
+1:
+       retl
+        mulx   %o1, %o0, %o0
diff --git a/common/lib/libc/arch/sparc64/net/htonl.S b/common/lib/libc/arch/sparc64/net/htonl.S
new file mode 100644 (file)
index 0000000..15f0e4e
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: htonl.S,v 1.1 2005/12/20 19:28:50 christos Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: htonl.s,v 1.1 92/06/25 12:47:05 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)htonl.s     8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: htonl.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* netorder = htonl(hostorder) */
+
+
+ENTRY(htonl)
+       retl
+        srl    %o0, 0, %o0     /* zero extend -- or do we sign extend? */
diff --git a/common/lib/libc/arch/sparc64/net/htons.S b/common/lib/libc/arch/sparc64/net/htons.S
new file mode 100644 (file)
index 0000000..2d06027
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: htons.S,v 1.1 2005/12/20 19:28:50 christos Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: htons.s,v 1.1 92/06/25 12:47:05 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)htons.s     8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: htons.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* netorder = htons(hostorder) */
+ENTRY(htons)
+       sethi   %hi(0xffff0000), %o1
+       signx   %o1, %o1
+       retl
+        andn   %o0, %o1, %o0
diff --git a/common/lib/libc/arch/sparc64/net/ntohl.S b/common/lib/libc/arch/sparc64/net/ntohl.S
new file mode 100644 (file)
index 0000000..cb5bde8
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: ntohl.S,v 1.1 2005/12/20 19:28:50 christos Exp $       */
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: ntohl.s,v 1.1 92/06/25 12:47:06 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)ntohl.s     8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: ntohl.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* hostorder = ntohl(netorder) */
+ENTRY(ntohl)
+       retl
+        signx  %o0, %o0
diff --git a/common/lib/libc/arch/sparc64/net/ntohs.S b/common/lib/libc/arch/sparc64/net/ntohs.S
new file mode 100644 (file)
index 0000000..f377d97
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: ntohs.S,v 1.1 2005/12/20 19:28:50 christos Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: ntohs.s,v 1.1 92/06/25 12:47:07 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)ntohs.s     8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: ntohs.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* hostorder = ntohs(netorder) */
+
+ENTRY(ntohs)
+       sethi   %hi(0xffff0000), %o1
+       signx   %o1, %o1
+       retl
+        andn   %o0, %o1, %o0
+
diff --git a/common/lib/libc/arch/sparc64/string/ffs.S b/common/lib/libc/arch/sparc64/string/ffs.S
new file mode 100644 (file)
index 0000000..93e620a
--- /dev/null
@@ -0,0 +1,135 @@
+/*     $NetBSD: ffs.S,v 1.2 2009/12/19 19:09:48 pooka Exp $    */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: ffs.s,v 1.3 92/07/07 00:23:57 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)ffs.s       8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: ffs.S,v 1.2 2009/12/19 19:09:48 pooka Exp $")
+#endif
+#endif  /* LIBC_SCCS and not lint */
+
+#if 0
+       /*
+        * We have a popcount instruction -- use it.
+        * only uses %o0, %o1, %o2
+        *
+        * Here's the pseudo-code from the v9 spec:
+        *
+        * int ffs(unsigned zz) {
+        *      return popc( zz ^ ( ~ (-zz)));
+        * }
+        *
+        * XXXX sptifires and blackbirds don't implement popc,
+        * so we won't use this nice clean code 8^(.
+        */
+ENTRY(ffs)
+       neg     %o0, %o1                                ! %o1 = -zz
+       xnor    %o0, %o1, %o2                           ! %o2 = zz ^ ~ -zz
+       popc    %o2, %o1
+       movrz   %o0, %g0, %o1                           ! result of ffs(0) should be zero
+       retl
+        mov    %o1, %o0
+#endif
+/*
+ * ffs returns the number of the rightmost bit set in its argument,
+ * i.e., the lowest value such that (x & (ffs(x) - 1)) is nonzero.
+ * If no bits are set, ffs returns 0.
+ *
+ * We use a table lookup on each byte.
+ *
+ * In each section below, %o1 is the current byte (0, 1, 2, or 3).
+ * The last byte is handled specially: for the first three,
+ * if that byte is nonzero, we return the table value
+ * (plus 0, 8, or 16 for the byte number), but for the last
+ * one, we just return the table value plus 24.  This means
+ * that ffstab[0] must be -24 so that ffs(0) will return 0.
+ */
+ENTRY(ffs)
+#ifdef PIC
+       PICCY_SET(ffstab, %o2, %o3)
+#else
+       set     ffstab, %o2
+#endif
+       andcc   %o0, 0xff, %o1  ! get low byte
+       be,a    1f              ! try again if 0
+        srl    %o0, 8, %o0     ! delay slot, get ready for next byte
+
+       retl                    ! return ffstab[%o1]
+        ldsb   [%o2 + %o1], %o0
+
+1:
+       andcc   %o0, 0xff, %o1  ! byte 1 like byte 0...
+       be,a    2f
+        srl    %o0, 8, %o0     ! (use delay to prepare for byte 2)
+
+       ldsb    [%o2 + %o1], %o0
+       retl                    ! return ffstab[%o1] + 8
+        add    %o0, 8, %o0
+
+2:
+       andcc   %o0, 0xff, %o1
+       be,a    3f
+        srl    %o0, 8, %o0     ! (prepare for byte 3)
+
+       ldsb    [%o2 + %o1], %o0
+       retl                    ! return ffstab[%o1] + 16
+        add    %o0, 16, %o0
+
+3:                             ! just return ffstab[%o0] + 24
+       ldsb    [%o2 + %o0], %o0
+       retl
+        add    %o0, 24, %o0
+
+ffstab:
+       .byte   -24,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 00-0f */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 10-1f */
+       .byte   6,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 20-2f */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 30-3f */
+       .byte   7,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 40-4f */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 50-5f */
+       .byte   6,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 60-6f */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 70-7f */
+       .byte   8,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 80-8f */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* 10-9f */
+       .byte   6,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* a0-af */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* b0-bf */
+       .byte   7,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* c0-cf */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* d0-df */
+       .byte   6,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* e0-ef */
+       .byte   5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1 /* f0-ff */
diff --git a/common/lib/libc/arch/sparc64/string/strlen.S b/common/lib/libc/arch/sparc64/string/strlen.S
new file mode 100644 (file)
index 0000000..82c52be
--- /dev/null
@@ -0,0 +1,165 @@
+/*     $NetBSD: strlen.S,v 1.1 2005/12/20 19:28:50 christos Exp $      */
+
+/*
+ * Copyright 2002 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Eduardo Horvath for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: strlen.S,v 1.1 2005/12/20 19:28:50 christos Exp $")
+#endif /* LIBC_SCCS and not lint */
+       
+/* The algorithm here uses the following techniques:
+ *
+ * 1) Given a word 'x', we can test to see if it contains any 0 bytes
+ *    by subtracting 0x01010101, and seeing if any of the high bits of each
+ *    byte changed from 0 to 1. This works because the least significant
+ *    0 byte must have had no incoming carry (otherwise it's not the least
+ *    significant), so it is 0x00 - 0x01 == 0xff. For all other
+ *    byte values, either they have the high bit set initially, or when
+ *    1 is subtracted you get a value in the range 0x00-0x7f, none of which
+ *    have their high bit set. The expression here is
+ *    (x + 0xfefefeff) & ~(x | 0x7f7f7f7f), which gives 0x00000000 when
+ *    there were no 0x00 bytes in the word.
+ *
+ * 2) Now just hunt for the first byte that's 0x00 in 'x'.
+ *
+ *    This is from the book 'The PowerPC Compiler Writer's Guide',
+ *    by Steve Hoxey, Faraydon Karim, Bill Hay and Hank Warren.
+ */
+
+ENTRY(strlen)
+       /*
+        * Calculate address for and load the first xword.
+        */
+       andn    %o0, 0x7, %o1
+       ldx     [%o1], %g1
+
+       /*
+        * Now prepare some constants while the data arrives...
+        */
+       sethi   %hi(0xfefefefe), %o3
+       sethi   %hi(0x7f7f7f7f), %o2
+       
+       or      %o3, %lo(0xfefefefe), %o3
+       or      %o2, %lo(0x7f7f7f7f), %o2
+       
+       sllx    %o3, 32, %o5
+       andcc   %o0, 0x7, %g5   ! Hoisted from below to fill a slot
+       
+       sllx    %o2, 32, %o4
+       or      %o3, %o5, %o3
+       
+       sll     %g5, 3, %g5     ! Convert to bytes. hoisted
+       or      %o2, %o4, %o2
+       
+       inc     %o3
+       neg     %g5             ! hoisted
+
+       /*
+        * Mask off the leading bits:
+        *
+        * if (ptr & 0x7)
+        *      mask = -1 << (64 - ((ptr & 0x7) << 3));
+        */
+       
+!      andcc   %o0, 0x7, %g5   ! Hoisted above
+       bz,pt   %icc, 0f
+       
+       
+!       sll    %g5, 3, %g5     ! Convert to bytes. Also hoisted
+
+!      neg     %g5             ! Hoisted
+       
+        add    %g5, 64, %g5
+       mov     -1, %o4
+       
+       sllx    %o4, %g5, %o4
+
+       or      %o4, %g1, %g1   ! Make leading bytes != 0
+       
+0:
+       or      %g1, %o2, %o5   ! Do step 1 -- use or/andn instead of nor/and
+       add     %g1, %o3, %g5
+       
+       inc     8, %o1          ! Point to next word
+       andncc  %g5, %o5, %g0
+       bz,a,pt %xcc, 0b
+        ldx    [%o1], %g1
+       
+       mov     -1, %o4
+       dec     8, %o1
+       
+       sllx    %o4, 64-8, %o5
+       
+       btst    %g1, %o5        ! Check high byte
+       bz      %xcc,0f
+        srlx   %o5, 8, %o5
+
+       inc     %o1
+       btst    %g1, %o5        ! Check 2nd byte
+       bz      %xcc,0f
+        srlx   %o5, 8, %o5
+       
+       inc     %o1
+       btst    %g1, %o5        ! Check 3rd byte
+       bz      %xcc,0f
+        srlx   %o5, 8, %o5
+
+       inc     %o1
+       btst    %g1, %o5        ! Check 4th byte
+       bz      %xcc,0f
+        srlx   %o5, 8, %o5
+                       
+       inc     %o1
+       btst    %g1, %o5        ! Check 5th byte
+       bz      %xcc,0f
+        srlx   %o5, 8, %o5
+                       
+       inc     %o1
+       btst    %g1, %o5        ! Check 6th byte
+       bz      %xcc,0f
+        srlx   %o5, 8, %o5
+                       
+       inc     %o1
+       btst    %g1, %o5        ! Check 7th byte
+       bz      %xcc,0f
+        nop
+
+       inc     %o1
+0:
+       retl
+        sub    %o1, %o0, %o0   ! return length (ptr - (origptr+1))
diff --git a/common/lib/libc/arch/vax/atomic/Makefile.inc b/common/lib/libc/arch/vax/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..1bafd20
--- /dev/null
@@ -0,0 +1,17 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/01/04 17:54:29 pooka Exp $
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "c" || ${LIB} == "pthread" \
+       || ${LIB} == "rump")
+
+SRCS+= atomic_add_32_cas.c atomic_add_32_nv_cas.c atomic_and_32_cas.c \
+       atomic_and_32_nv_cas.c atomic_dec_32_cas.c atomic_dec_32_nv_cas.c \
+       atomic_inc_32_cas.c atomic_inc_32_nv_cas.c atomic_or_32_cas.c \
+       atomic_or_32_nv_cas.c atomic_swap_32_cas.c membar_ops_nop.c
+
+.endif
+
+.if defined(LIB) && (${LIB} == "c" || ${LIB} == "pthread")
+
+SRCS+= atomic_init_testset.c
+
+.endif
diff --git a/common/lib/libc/arch/vax/gen/bswap16.S b/common/lib/libc/arch/vax/gen/bswap16.S
new file mode 100644 (file)
index 0000000..dc1c593
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: bswap16.S,v 1.2 2008/04/28 20:22:52 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+ENTRY(_C_LABEL(bswap16), 0)
+#else
+ALTENTRY(_C_LABEL(ntohs))
+ALTENTRY(_C_LABEL(htons))
+ENTRY(_C_LABEL(__bswap16), 0)
+#endif
+       movl    4(%ap), %r1
+       extzv   $8, $8, %r1, %r0
+       insv    %r1, $8, $8, %r0
+       ret
diff --git a/common/lib/libc/arch/vax/gen/bswap32.S b/common/lib/libc/arch/vax/gen/bswap32.S
new file mode 100644 (file)
index 0000000..91377ee
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: bswap32.S,v 1.2 2008/04/28 20:22:52 martin Exp $       */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+ENTRY(_C_LABEL(bswap32), 0)
+#else
+#if BYTE_ORDER == LITTLE_ENDIAN
+ALTENTRY(_C_LABEL(ntohl))
+ALTENTRY(_C_LABEL(htonl))
+#endif
+ENTRY(_C_LABEL(__bswap32), 0)
+#endif
+       rotl    $-8, 4(%ap), %r0  
+       insv    %r0, $16, $8, %r0
+       rotl    $8, 4(%ap), %r1
+       movb    %r1, %r0
+       ret
+
diff --git a/common/lib/libc/arch/vax/gen/bswap64.S b/common/lib/libc/arch/vax/gen/bswap64.S
new file mode 100644 (file)
index 0000000..b95bb74
--- /dev/null
@@ -0,0 +1,19 @@
+/* Written by Anders Magnusson. Public Domain */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       .asciz "$NetBSD: bswap64.S,v 1.2 2005/12/24 08:33:32 matt Exp $"
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/asm.h>
+
+ENTRY(bswap64, 0)
+        movq 4(%ap),%r3
+       rotl $-8,%r3,%r1
+       insv %r1,$16,$8,%r1
+       rotl $8,%r3,%r2
+       movb %r2,%r1
+       rotl $-8,%r4,%r0
+       insv %r0,$16,$8,%r0
+       rotl $8,%r4,%r2
+       movb %r2,%r0
+       ret
diff --git a/common/lib/libc/arch/vax/gen/udiv.S b/common/lib/libc/arch/vax/gen/udiv.S
new file mode 100644 (file)
index 0000000..e9819c6
--- /dev/null
@@ -0,0 +1,100 @@
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Donn Seeley at UUNET Technologies, 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. 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)
+       /* .asciz "@(#)udiv.s   8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: udiv.S,v 1.2 2005/12/24 08:33:32 matt Exp $"
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Unsigned division, PCC flavor.
+ * udiv() takes an ordinary dividend/divisor pair;
+ * audiv() takes a pointer to a dividend and an ordinary divisor.
+ */
+
+#include <machine/asm.h>
+
+#define        DIVIDEND        4(%ap)
+#define        DIVISOR         8(%ap)
+
+#ifdef __ELF__
+ASENTRY(__udiv,0)
+#else
+ASENTRY(udiv,0)
+#endif
+       movl    DIVISOR,%r2
+       jlss    Leasy           # big divisor: settle by comparison
+       movl    DIVIDEND,%r0
+       jlss    Lhard           # big dividend: extended division
+       divl2   %r2,%r0         # small divisor and dividend: signed division
+       ret
+Lhard:
+       clrl    %r1
+       ediv    %r2,%r0,%r0,%r1
+       ret
+Leasy:
+       cmpl    DIVIDEND,%r2
+       jgequ   Lone            # if dividend is as big or bigger, return 1
+       clrl    %r0             # else return 0
+       ret
+Lone:
+       movl    $1,%r0
+       ret
+
+#ifdef __ELF__
+ASENTRY(__audiv,0)
+#else
+ASENTRY(audiv,0)
+#endif
+       movl    DIVIDEND,%r3
+       movl    DIVISOR,%r2
+       jlss    La_easy         # big divisor: settle by comparison
+       movl    (%r3),%r0
+       jlss    La_hard         # big dividend: extended division
+       divl2   %r2,%r0         # small divisor and dividend: signed division
+       movl    %r0,(%r3)               # leave the value of the assignment in %r0
+       ret
+La_hard:
+       clrl    %r1
+       ediv    %r2,%r0,%r0,%r1
+       movl    %r0,(%r3)
+       ret
+La_easy:
+       cmpl    (%r3),%r2
+       jgequ   La_one          # if dividend is as big or bigger, return 1
+       clrl    %r0             # else return 0
+       clrl    (%r3)
+       ret
+La_one:
+       movl    $1,%r0
+       movl    %r0,(%r3)
+       ret
diff --git a/common/lib/libc/arch/vax/gen/urem.S b/common/lib/libc/arch/vax/gen/urem.S
new file mode 100644 (file)
index 0000000..ffae00c
--- /dev/null
@@ -0,0 +1,100 @@
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Donn Seeley at UUNET Technologies, 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. 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)
+       /* .asciz "@(#)urem.s   8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: urem.S,v 1.2 2005/12/24 08:33:32 matt Exp $"
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/asm.h>
+
+/*
+ * Unsigned modulus, PCC flavor.
+ * urem() takes an ordinary dividend/divisor pair;
+ * aurem() takes a pointer to a dividend and an ordinary divisor.
+ */
+
+#define        DIVIDEND        4(%ap)
+#define        DIVISOR         8(%ap)
+
+#ifdef __ELF__
+ASENTRY(__urem,0)
+#else
+ASENTRY(urem,0)
+#endif
+       movl    DIVISOR,%r2
+       jlss    Leasy           # big divisor: settle by comparison
+       movl    DIVIDEND,%r0
+       jlss    Lhard           # big dividend: need extended division
+       divl3   %r2,%r0,%r1     # small divisor and dividend: signed modulus
+       mull2   %r2,%r1
+       subl2   %r1,%r0
+       ret
+Lhard:
+       clrl    %r1
+       ediv    %r2,%r0,%r1,%r0
+       ret
+Leasy:
+       subl3   %r2,DIVIDEND,%r0
+       jcc     Ldifference     # if divisor goes in once, return difference
+       movl    DIVIDEND,%r0    # if divisor is bigger, return dividend
+Ldifference:
+       ret
+
+#ifdef __ELF__
+ASENTRY(__aurem,0)
+#else
+ASENTRY(aurem,0)
+#endif
+       movl    DIVIDEND,%r3
+       movl    DIVISOR,%r2
+       jlss    La_easy         # big divisor: settle by comparison
+       movl    (%r3),%r0
+       jlss    La_hard         # big dividend: need extended division
+       divl3   %r2,%r0,%r1     # small divisor and dividend: signed modulus
+       mull2   %r2,%r1
+       subl2   %r1,%r0
+       movl    %r0,(%r3)               # leave the value of the assignment in %r0
+       ret
+La_hard:
+       clrl    %r1
+       ediv    %r2,%r0,%r1,%r0
+       movl    %r0,(%r3)
+       ret
+La_easy:
+       subl3   %r2,(%r3),%r0
+       jcs     La_dividend     # if divisor is bigger, leave dividend alone
+       movl    %r0,(%r3)               # if divisor goes in once, store difference
+       ret
+La_dividend:
+       movl    (%r3),%r0
+       ret
diff --git a/common/lib/libc/arch/vax/string/memcpy.S b/common/lib/libc/arch/vax/string/memcpy.S
new file mode 100644 (file)
index 0000000..843451c
--- /dev/null
@@ -0,0 +1,90 @@
+/*     $NetBSD: memcpy.S,v 1.2 2005/12/24 08:33:32 matt Exp $  */
+/*-
+ * 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.
+ * 3. 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)
+       .asciz "@(#)memcpy.s    8.1 (Berkeley) 6/4/93"
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * void *memcpy(dst, src, size)
+ * returns dst
+ *
+ * This optimises the usual case (count < 65536) at the expense
+ * of some extra memory references and branches when count >= 65536.
+ */
+
+#include <machine/asm.h>
+
+ENTRY(memcpy, 0)
+       movzwl  $65535,%r0      /* %r0 = 64K (needed below) */
+       movq    8(%ap),%r1      /* %r1 = src, %r2 = length */
+       movl    4(%ap),%r3      /* %r3 = dst */
+       cmpl    %r1,%r3
+       bgtru   1f              /* normal forward case */
+       beql    2f              /* equal, nothing to do */
+       addl2   %r2,%r1         /* overlaps iff src<dst but src+len>dst */
+       cmpl    %r1,%r3
+       bgtru   4f              /* overlapping, must move backwards */
+       subl2   %r2,%r1
+
+1:     /* move forward */
+       cmpl    %r2,%r0
+       bgtru   3f              /* stupid movc3 limitation */
+       movc3   %r2,(%r1),(%r3) /* move it all */
+2:
+       movl    4(%ap),%r0      /* return original dst */
+       ret
+3:
+       subl2   %r0,12(%ap)     /* adjust length by 64K */
+       movc3   %r0,(%r1),(%r3) /* move 64K */
+       movl    12(%ap),%r2
+       decw    %r0             /* from 0 to 65535 */
+       brb     1b              /* retry */
+
+4:     /* move backward */
+       addl2   %r2,%r3
+5:
+       cmpl    %r2,%r0
+       bgtru   6f              /* stupid movc3 limitation */
+       subl2   %r2,%r1
+       subl2   %r2,%r3
+       movc3   %r2,(%r1),(%r3) /* move it all */
+       movl    4(%ap),%r0      /* return original dst */
+       ret
+6:
+       subl2   %r0,12(%ap)     /* adjust length by 64K */
+       subl2   %r0,%r1
+       subl2   %r0,%r3
+       movc3   %r0,(%r1),(%r3) /* move 64K */
+       movl    12(%ap),%r2
+       decw    %r0
+       subl2   %r0,%r1
+       subl2   %r0,%r3
+       brb     5b
diff --git a/common/lib/libc/arch/vax/string/memmove.S b/common/lib/libc/arch/vax/string/memmove.S
new file mode 100644 (file)
index 0000000..9e6516a
--- /dev/null
@@ -0,0 +1,90 @@
+/*     $NetBSD: memmove.S,v 1.2 2005/12/24 08:33:32 matt Exp $ */
+/*-
+ * 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.
+ * 3. 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)
+       .asciz "@(#)memmove.s   8.1 (Berkeley) 6/4/93"
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * void *memmove(dst, src, size)
+ * returns dst
+ *
+ * This optimises the usual case (count < 65536) at the expense
+ * of some extra memory references and branches when count >= 65536.
+ */
+
+#include <machine/asm.h>
+
+ENTRY(memmove, 0)
+       movzwl  $65535,%r0      /* %r0 = 64K (needed below) */
+       movq    8(%ap),%r1      /* %r1 = src, %r2 = length */
+       movl    4(%ap),%r3      /* %r3 = dst */
+       cmpl    %r1,%r3
+       bgtru   1f              /* normal forward case */
+       beql    2f              /* equal, nothing to do */
+       addl2   %r2,%r1         /* overlaps iff src<dst but src+len>dst */
+       cmpl    %r1,%r3
+       bgtru   4f              /* overlapping, must move backwards */
+       subl2   %r2,%r1
+
+1:     /* move forward */
+       cmpl    %r2,%r0
+       bgtru   3f              /* stupid movc3 limitation */
+       movc3   %r2,(%r1),(%r3) /* move it all */
+2:
+       movl    4(%ap),%r0      /* return original dst */
+       ret
+3:
+       subl2   %r0,12(%ap)     /* adjust length by 64K */
+       movc3   %r0,(%r1),(%r3) /* move 64K */
+       movl    12(%ap),%r2
+       decw    %r0             /* from 0 to 65535 */
+       brb     1b              /* retry */
+
+4:     /* move backward */
+       addl2   %r2,%r3
+5:
+       cmpl    %r2,%r0
+       bgtru   6f              /* stupid movc3 limitation */
+       subl2   %r2,%r1
+       subl2   %r2,%r3
+       movc3   %r2,(%r1),(%r3) /* move it all */
+       movl    4(%ap),%r0      /* return original dst */
+       ret
+6:
+       subl2   %r0,12(%ap)     /* adjust length by 64K */
+       subl2   %r0,%r1
+       subl2   %r0,%r3
+       movc3   %r0,(%r1),(%r3) /* move 64K */
+       movl    12(%ap),%r2
+       decw    %r0
+       subl2   %r0,%r1
+       subl2   %r0,%r3
+       brb     5b
diff --git a/common/lib/libc/arch/vax/string/memset.S b/common/lib/libc/arch/vax/string/memset.S
new file mode 100644 (file)
index 0000000..6709577
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: memset.S,v 1.1 2010/03/12 09:12:34 uwe Exp $   */
+/*-
+ * 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.
+ * 3. 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)
+       .asciz "@(#)memset.s    8.1 (Berkeley) 6/4/93"
+#endif /* LIBC_SCCS and not lint */
+
+/* void *memset(base, c, length) */
+
+#include <machine/asm.h>
+
+ENTRY(memset, 0)
+       movl    4(%ap),%r3
+1:
+       movzwl  $65535,%r0
+       movq    8(%ap),%r1
+       cmpl    %r2,%r0
+       jgtru   2f
+       movc5   $0,(%r3),%r1,%r2,(%r3)
+       movl    %r1,%r0
+       ret
+2:
+       subl2   %r0,12(%ap)
+       movc5   $0,(%r3),%r1,%r0,(%r3)
+       jbr     1b
diff --git a/common/lib/libc/arch/x86_64/atomic/Makefile.inc b/common/lib/libc/arch/x86_64/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..a590a2a
--- /dev/null
@@ -0,0 +1,14 @@
+#      $NetBSD: Makefile.inc,v 1.6 2009/01/04 17:54:29 pooka Exp $
+
+.if defined(LIB) && (${LIB} == "kern" || ${LIB} == "c" || ${LIB} == "pthread" \
+       || ${LIB} == "rump")
+
+SRCS+= atomic.S
+
+.endif
+
+.if defined(LIB) && (${LIB} == "c" || ${LIB} == "pthread")
+
+SRCS+= atomic_init_cas.c
+
+.endif
diff --git a/common/lib/libc/arch/x86_64/atomic/atomic.S b/common/lib/libc/arch/x86_64/atomic/atomic.S
new file mode 100644 (file)
index 0000000..797f0ee
--- /dev/null
@@ -0,0 +1,404 @@
+/*     $NetBSD: atomic.S,v 1.16 2011/01/12 23:12:10 joerg Exp $        */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe, and by Andrew Doran.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/param.h>
+#include <machine/asm.h>
+
+#ifdef _KERNEL
+#define        ALIAS(f, t)     STRONG_ALIAS(f,t)
+#else
+#define        ALIAS(f, t)     WEAK_ALIAS(f,t)
+#endif
+
+#ifdef _HARDKERNEL
+#define        LOCK(n)         .Lpatch ## n:   lock
+#define        ENDLABEL(a)     _ALIGN_TEXT; LABEL(a)
+#else
+#define        LOCK(n)         lock
+#define        ENDLABEL(a)     /* nothing */
+#endif
+
+       .text
+
+/* 32-bit */
+
+ENTRY(_atomic_add_32)
+       LOCK(1)
+       addl    %esi, (%rdi)
+       ret
+
+ENTRY(_atomic_add_32_nv)
+       movl    %esi, %eax
+       LOCK(2)
+       xaddl   %eax, (%rdi)
+       addl    %esi, %eax
+       ret
+
+ENTRY(_atomic_and_32)
+       LOCK(3)
+       andl    %esi, (%rdi)
+       ret
+
+ENTRY(_atomic_and_32_nv)
+       movl    (%rdi), %eax
+1:
+       movl    %eax, %ecx
+       andl    %esi, %ecx
+       LOCK(4)
+       cmpxchgl %ecx, (%rdi)
+       jnz     1b
+       movl    %ecx, %eax
+       ret
+
+ENTRY(_atomic_dec_32)
+       LOCK(5)
+       decl    (%rdi)
+       ret
+
+ENTRY(_atomic_dec_32_nv)
+       movl    $-1, %eax
+       LOCK(6)
+       xaddl   %eax, (%rdi)
+       decl    %eax
+       ret
+
+ENTRY(_atomic_inc_32)
+       LOCK(7)
+       incl    (%rdi)
+       ret
+
+ENTRY(_atomic_inc_32_nv)
+       movl    $1, %eax
+       LOCK(8)
+       xaddl   %eax, (%rdi)
+       incl    %eax
+       ret
+
+ENTRY(_atomic_or_32)
+       LOCK(9)
+       orl     %esi, (%rdi)
+       ret
+
+ENTRY(_atomic_or_32_nv)
+       movl    (%rdi), %eax
+1:
+       movl    %eax, %ecx
+       orl     %esi, %ecx
+       LOCK(10)
+       cmpxchgl %ecx, (%rdi)
+       jnz     1b
+       movl    %ecx, %eax
+       ret
+
+ENTRY(_atomic_swap_32)
+       movl    %esi, %eax
+       xchgl   %eax, (%rdi)
+       ret
+
+ENTRY(_atomic_cas_32)
+       movl    %esi, %eax
+       LOCK(12)
+       cmpxchgl %edx, (%rdi)
+       /* %eax now contains the old value */
+       ret
+
+ENTRY(_atomic_cas_32_ni)
+       movl    %esi, %eax
+       cmpxchgl %edx, (%rdi)
+       /* %eax now contains the old value */
+       ret
+
+/* 64-bit */
+
+ENTRY(_atomic_add_64)
+       LOCK(13)
+       addq    %rsi, (%rdi)
+       ret
+
+ENTRY(_atomic_add_64_nv)
+       movq    %rsi, %rax
+       LOCK(14)
+       xaddq   %rax, (%rdi)
+       addq    %rsi, %rax
+       ret
+
+ENTRY(_atomic_and_64)
+       LOCK(15)
+       andq    %rsi, (%rdi)
+       ret
+
+ENTRY(_atomic_and_64_nv)
+       movq    (%rdi), %rax
+1:
+       movq    %rax, %rcx
+       andq    %rsi, %rcx
+       LOCK(16)
+       cmpxchgq %rcx, (%rdi)
+       jnz     1b
+       movq    %rcx, %rax
+       ret
+
+ENTRY(_atomic_dec_64)
+       LOCK(17)
+       decq    (%rdi)
+       ret
+
+ENTRY(_atomic_dec_64_nv)
+       movq    $-1, %rax
+       LOCK(18)
+       xaddq   %rax, (%rdi)
+       decq    %rax
+       ret
+
+ENTRY(_atomic_inc_64)
+       LOCK(19)
+       incq    (%rdi)
+       ret
+
+ENTRY(_atomic_inc_64_nv)
+       movq    $1, %rax
+       LOCK(20)
+       xaddq   %rax, (%rdi)
+       incq    %rax
+       ret
+
+ENTRY(_atomic_or_64)
+       LOCK(21)
+       orq     %rsi, (%rdi)
+       ret
+
+ENTRY(_atomic_or_64_nv)
+       movq    (%rdi), %rax
+1:
+       movq    %rax, %rcx
+       orq     %rsi, %rcx
+       LOCK(22)
+       cmpxchgq %rcx, (%rdi)
+       jnz     1b
+       movq    %rcx, %rax
+       ret
+
+ENTRY(_atomic_swap_64)
+       movq    %rsi, %rax
+       xchgq   %rax, (%rdi)
+       ret
+
+ENTRY(_atomic_cas_64)
+       movq    %rsi, %rax
+       LOCK(24)
+       cmpxchgq %rdx, (%rdi)
+       /* %eax now contains the old value */
+       ret
+
+ENTRY(_atomic_cas_64_ni)
+       movq    %rsi, %rax
+       cmpxchgq %rdx, (%rdi)
+       /* %eax now contains the old value */
+       ret
+
+/* memory barriers */
+
+ENTRY(_membar_consumer)
+       LOCK(25)
+       addq    $0, -8(%rsp)
+       ret
+ENDLABEL(membar_consumer_end)
+
+ENTRY(_membar_producer)
+       /* A store is enough */
+       movq    $0, -8(%rsp)
+       ret
+ENDLABEL(membar_producer_end)
+
+ENTRY(_membar_sync)
+       LOCK(26)
+       addq    $0, -8(%rsp)
+       ret
+ENDLABEL(membar_sync_end)
+
+#ifdef _HARDKERNEL
+ENTRY(sse2_lfence)
+       lfence
+       ret
+ENDLABEL(sse2_lfence_end)
+
+ENTRY(sse2_mfence)
+       mfence
+       ret
+ENDLABEL(sse2_mfence_end)
+
+atomic_lockpatch:
+       .globl  atomic_lockpatch
+       .quad   .Lpatch1, .Lpatch2, .Lpatch3, .Lpatch4, .Lpatch5
+       .quad   .Lpatch6, .Lpatch7, .Lpatch8, .Lpatch9, .Lpatch10
+       .quad   .Lpatch12, .Lpatch13, .Lpatch14, .Lpatch15
+       .quad   .Lpatch16, .Lpatch17, .Lpatch18, .Lpatch19, .Lpatch20
+       .quad   .Lpatch21, .Lpatch22, .Lpatch24, .Lpatch25
+       .quad   .Lpatch26, 0
+#endif /* _HARDKERNEL */
+
+ALIAS(atomic_add_32,_atomic_add_32)
+ALIAS(atomic_add_64,_atomic_add_64)
+ALIAS(atomic_add_int,_atomic_add_32)
+ALIAS(atomic_add_long,_atomic_add_64)
+ALIAS(atomic_add_ptr,_atomic_add_64)
+
+ALIAS(atomic_add_32_nv,_atomic_add_32_nv)
+ALIAS(atomic_add_64_nv,_atomic_add_64_nv)
+ALIAS(atomic_add_int_nv,_atomic_add_32_nv)
+ALIAS(atomic_add_long_nv,_atomic_add_64_nv)
+ALIAS(atomic_add_ptr_nv,_atomic_add_64_nv)
+
+ALIAS(atomic_and_32,_atomic_and_32)
+ALIAS(atomic_and_64,_atomic_and_64)
+ALIAS(atomic_and_uint,_atomic_and_32)
+ALIAS(atomic_and_ulong,_atomic_and_64)
+ALIAS(atomic_and_ptr,_atomic_and_64)
+
+ALIAS(atomic_and_32_nv,_atomic_and_32_nv)
+ALIAS(atomic_and_64_nv,_atomic_and_64_nv)
+ALIAS(atomic_and_uint_nv,_atomic_and_32_nv)
+ALIAS(atomic_and_ulong_nv,_atomic_and_64_nv)
+ALIAS(atomic_and_ptr_nv,_atomic_and_64_nv)
+
+ALIAS(atomic_dec_32,_atomic_dec_32)
+ALIAS(atomic_dec_64,_atomic_dec_64)
+ALIAS(atomic_dec_uint,_atomic_dec_32)
+ALIAS(atomic_dec_ulong,_atomic_dec_64)
+ALIAS(atomic_dec_ptr,_atomic_dec_64)
+
+ALIAS(atomic_dec_32_nv,_atomic_dec_32_nv)
+ALIAS(atomic_dec_64_nv,_atomic_dec_64_nv)
+ALIAS(atomic_dec_uint_nv,_atomic_dec_32_nv)
+ALIAS(atomic_dec_ulong_nv,_atomic_dec_64_nv)
+ALIAS(atomic_dec_ptr_nv,_atomic_dec_64_nv)
+
+ALIAS(atomic_inc_32,_atomic_inc_32)
+ALIAS(atomic_inc_64,_atomic_inc_64)
+ALIAS(atomic_inc_uint,_atomic_inc_32)
+ALIAS(atomic_inc_ulong,_atomic_inc_64)
+ALIAS(atomic_inc_ptr,_atomic_inc_64)
+
+ALIAS(atomic_inc_32_nv,_atomic_inc_32_nv)
+ALIAS(atomic_inc_64_nv,_atomic_inc_64_nv)
+ALIAS(atomic_inc_uint_nv,_atomic_inc_32_nv)
+ALIAS(atomic_inc_ulong_nv,_atomic_inc_64_nv)
+ALIAS(atomic_inc_ptr_nv,_atomic_inc_64_nv)
+
+ALIAS(atomic_or_32,_atomic_or_32)
+ALIAS(atomic_or_uint,_atomic_or_32)
+ALIAS(atomic_or_ulong,_atomic_or_64)
+ALIAS(atomic_or_ptr,_atomic_or_64)
+
+ALIAS(atomic_or_32_nv,_atomic_or_32_nv)
+ALIAS(atomic_or_64_nv,_atomic_or_64_nv)
+ALIAS(atomic_or_uint_nv,_atomic_or_32_nv)
+ALIAS(atomic_or_ulong_nv,_atomic_or_64_nv)
+ALIAS(atomic_or_ptr_nv,_atomic_or_64_nv)
+
+ALIAS(atomic_swap_32,_atomic_swap_32)
+ALIAS(atomic_swap_64,_atomic_swap_64)
+ALIAS(atomic_swap_uint,_atomic_swap_32)
+ALIAS(atomic_swap_ulong,_atomic_swap_64)
+ALIAS(atomic_swap_ptr,_atomic_swap_64)
+
+ALIAS(atomic_cas_32,_atomic_cas_32)
+ALIAS(atomic_cas_64,_atomic_cas_64)
+ALIAS(atomic_cas_uint,_atomic_cas_32)
+ALIAS(atomic_cas_ulong,_atomic_cas_64)
+ALIAS(atomic_cas_ptr,_atomic_cas_64)
+
+ALIAS(atomic_cas_32_ni,_atomic_cas_32_ni)
+ALIAS(atomic_cas_64_ni,_atomic_cas_64_ni)
+ALIAS(atomic_cas_uint_ni,_atomic_cas_32_ni)
+ALIAS(atomic_cas_ulong_ni,_atomic_cas_64_ni)
+ALIAS(atomic_cas_ptr_ni,_atomic_cas_64_ni)
+
+ALIAS(membar_consumer,_membar_consumer)
+ALIAS(membar_producer,_membar_producer)
+ALIAS(membar_enter,_membar_consumer)
+ALIAS(membar_exit,_membar_producer)
+ALIAS(membar_sync,_membar_sync)
+
+STRONG_ALIAS(_atomic_add_int,_atomic_add_32)
+STRONG_ALIAS(_atomic_add_long,_atomic_add_64)
+STRONG_ALIAS(_atomic_add_ptr,_atomic_add_64)
+
+STRONG_ALIAS(_atomic_add_int_nv,_atomic_add_32_nv)
+STRONG_ALIAS(_atomic_add_long_nv,_atomic_add_64_nv)
+STRONG_ALIAS(_atomic_add_ptr_nv,_atomic_add_64_nv)
+
+STRONG_ALIAS(_atomic_and_uint,_atomic_and_32)
+STRONG_ALIAS(_atomic_and_ulong,_atomic_and_64)
+STRONG_ALIAS(_atomic_and_ptr,_atomic_and_64)
+
+STRONG_ALIAS(_atomic_and_uint_nv,_atomic_and_32_nv)
+STRONG_ALIAS(_atomic_and_ulong_nv,_atomic_and_64_nv)
+STRONG_ALIAS(_atomic_and_ptr_nv,_atomic_and_64_nv)
+
+STRONG_ALIAS(_atomic_dec_uint,_atomic_dec_32)
+STRONG_ALIAS(_atomic_dec_ulong,_atomic_dec_64)
+STRONG_ALIAS(_atomic_dec_ptr,_atomic_dec_64)
+
+STRONG_ALIAS(_atomic_dec_uint_nv,_atomic_dec_32_nv)
+STRONG_ALIAS(_atomic_dec_ulong_nv,_atomic_dec_64_nv)
+STRONG_ALIAS(_atomic_dec_ptr_nv,_atomic_dec_64_nv)
+
+STRONG_ALIAS(_atomic_inc_uint,_atomic_inc_32)
+STRONG_ALIAS(_atomic_inc_ulong,_atomic_inc_64)
+STRONG_ALIAS(_atomic_inc_ptr,_atomic_inc_64)
+
+STRONG_ALIAS(_atomic_inc_uint_nv,_atomic_inc_32_nv)
+STRONG_ALIAS(_atomic_inc_ulong_nv,_atomic_inc_64_nv)
+STRONG_ALIAS(_atomic_inc_ptr_nv,_atomic_inc_64_nv)
+
+STRONG_ALIAS(_atomic_or_uint,_atomic_or_32)
+STRONG_ALIAS(_atomic_or_ulong,_atomic_or_64)
+STRONG_ALIAS(_atomic_or_ptr,_atomic_or_64)
+
+STRONG_ALIAS(_atomic_or_uint_nv,_atomic_or_32_nv)
+STRONG_ALIAS(_atomic_or_ulong_nv,_atomic_or_64_nv)
+STRONG_ALIAS(_atomic_or_ptr_nv,_atomic_or_64_nv)
+
+STRONG_ALIAS(_atomic_swap_uint,_atomic_swap_32)
+STRONG_ALIAS(_atomic_swap_ulong,_atomic_swap_64)
+STRONG_ALIAS(_atomic_swap_ptr,_atomic_swap_64)
+
+STRONG_ALIAS(_atomic_cas_uint,_atomic_cas_32)
+STRONG_ALIAS(_atomic_cas_ulong,_atomic_cas_64)
+STRONG_ALIAS(_atomic_cas_ptr,_atomic_cas_64)
+
+STRONG_ALIAS(_atomic_cas_uint_ni,_atomic_cas_32_ni)
+STRONG_ALIAS(_atomic_cas_ulong_ni,_atomic_cas_64_ni)
+STRONG_ALIAS(_atomic_cas_ptr_ni,_atomic_cas_64_ni)
+
+STRONG_ALIAS(_membar_enter,_membar_consumer)
+STRONG_ALIAS(_membar_exit,_membar_producer)
diff --git a/common/lib/libc/arch/x86_64/gen/byte_swap_2.S b/common/lib/libc/arch/x86_64/gen/byte_swap_2.S
new file mode 100644 (file)
index 0000000..288aaf6
--- /dev/null
@@ -0,0 +1,19 @@
+/*     $NetBSD: byte_swap_2.S,v 1.2 2006/02/04 21:53:31 uwe Exp $      */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: byte_swap_2.S,v 1.2 2006/02/04 21:53:31 uwe Exp $")
+#endif
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+_ENTRY(_C_LABEL(bswap16))
+#else
+_ENTRY(_C_LABEL(__bswap16))
+#endif
+_ENTRY(_C_LABEL(ntohs))
+_ENTRY(_C_LABEL(htons))
+_PROF_PROLOGUE
+       movl    %edi,%eax
+       xchgb   %ah,%al
+       ret
diff --git a/common/lib/libc/arch/x86_64/gen/byte_swap_4.S b/common/lib/libc/arch/x86_64/gen/byte_swap_4.S
new file mode 100644 (file)
index 0000000..ee8006e
--- /dev/null
@@ -0,0 +1,18 @@
+/*     $NetBSD: byte_swap_4.S,v 1.2 2006/02/04 21:53:31 uwe Exp $      */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: byte_swap_4.S,v 1.2 2006/02/04 21:53:31 uwe Exp $")
+#endif
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+_ENTRY(_C_LABEL(bswap32))
+#else
+_ENTRY(_C_LABEL(__bswap32))
+#endif
+_ENTRY(_C_LABEL(ntohl))
+_ENTRY(_C_LABEL(htonl))
+_PROF_PROLOGUE
+       movl    %edi,%eax
+       bswapl  %eax
+       ret
diff --git a/common/lib/libc/arch/x86_64/gen/byte_swap_8.S b/common/lib/libc/arch/x86_64/gen/byte_swap_8.S
new file mode 100644 (file)
index 0000000..1ac0df2
--- /dev/null
@@ -0,0 +1,17 @@
+/*     $NetBSD: byte_swap_8.S,v 1.1 2010/01/14 02:09:46 joerg Exp $    */
+
+/*
+ * Written by Frank van der Linden (fvdl@wasabisystems.com)
+ * Public Domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: byte_swap_8.S,v 1.1 2010/01/14 02:09:46 joerg Exp $")
+#endif
+
+ENTRY(bswap64)
+       bswapq  %rdi
+       movq    %rdi,%rax
+       ret
diff --git a/common/lib/libc/arch/x86_64/string/bcmp.S b/common/lib/libc/arch/x86_64/string/bcmp.S
new file mode 100644 (file)
index 0000000..03671a8
--- /dev/null
@@ -0,0 +1,23 @@
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: bcmp.S,v 1.2 2007/11/12 18:41:59 ad Exp $")
+#endif
+
+ENTRY(bcmp)
+       xorl    %eax,%eax               /* clear return value */
+
+       movq    %rdx,%rcx               /* compare by words */
+       shrq    $3,%rcx
+       repe
+       cmpsq
+       jne     L1
+
+       movq    %rdx,%rcx               /* compare remainder by bytes */
+       andq    $7,%rcx
+       repe
+       cmpsb
+       je      L2
+
+L1:    incl    %eax
+L2:    ret
diff --git a/common/lib/libc/arch/x86_64/string/bcopy.S b/common/lib/libc/arch/x86_64/string/bcopy.S
new file mode 100644 (file)
index 0000000..8b0c4f3
--- /dev/null
@@ -0,0 +1,160 @@
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from locore.s.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: bcopy.S,v 1.4 2009/11/22 17:25:47 dsl Exp $")
+#endif
+
+       /*
+        * (ov)bcopy (src,dst,cnt)
+        *  ws@tools.de     (Wolfgang Solfrank, TooLs GmbH) +49-228-985800
+        *
+        * Hacked about by dsl@netbsd.org
+        */
+
+#ifdef MEMCOPY
+ENTRY(memcpy)
+#define NO_OVERLAP
+#else
+#ifdef MEMMOVE
+ENTRY(memmove)
+#else
+ENTRY(bcopy)
+#endif
+#endif
+       movq    %rdx,%rcx
+#if defined(MEMCOPY) || defined(MEMMOVE)
+       movq    %rdi,%rax       /* must return destination address */
+       mov     %rdi,%r11       /* for misaligned check */
+#else
+       mov     %rsi,%r11       /* for misaligned check */
+       xchgq   %rdi,%rsi       /* bcopy() has arg order reversed */
+#endif
+
+#if !defined(NO_OVERLAP)
+       movq    %rdi,%r8
+       subq    %rsi,%r8
+#endif
+
+       shrq    $3,%rcx         /* count for copy by words */
+       jz      8f              /* j if less than 8 bytes */
+
+       lea     -8(%rdi,%rdx),%r9       /* target address of last 8 */
+       mov     -8(%rsi,%rdx),%r10      /* get last word */
+#if !defined(NO_OVERLAP)
+       cmpq    %rdx,%r8        /* overlapping? */
+       jb      10f
+#endif
+
+/*
+ * Non-overlaping, copy forwards.
+ * Newer Intel cpus (Nehalem) will do 16byte read/write transfers
+ * if %ecx is more than 76.
+ * AMD might do something similar some day.
+ */
+       and     $7,%r11         /* destination misaligned ? */
+       jnz     2f
+       rep
+       movsq
+       mov     %r10,(%r9)      /* write last word */
+       ret
+
+/*
+ * Destination misaligned
+ * AMD say it is better to align the destination (not the source).
+ * This will also re-align copies if the source and dest are both
+ * misaligned by the same amount)
+ * (I think Nehalem will use its accelerated copy if the source
+ * and destination have the same alignment.)
+ */
+2:
+       lea     -9(%r11,%rdx),%rcx      /* post re-alignment count */
+       neg     %r11                    /* now -1 .. -7 */
+       mov     (%rsi),%rdx             /* get first word */
+       mov     %rdi,%r8                /* target for first word */
+       lea     8(%rsi,%r11),%rsi
+       lea     8(%rdi,%r11),%rdi
+       shr     $3,%rcx
+       rep
+       movsq
+       mov     %rdx,(%r8)              /* write first word */
+       mov     %r10,(%r9)              /* write last word */
+       ret
+
+#if !defined(NO_OVERLAP)
+/* Must copy backwards.
+ * Reverse copy is probably easy to code faster than 'rep movds'
+ * since that requires (IIRC) an extra clock every 3 iterations (AMD).
+ * However I don't suppose anything cares that much!
+ * The big cost is the std/cld pair - reputedly 50+ cycles on Netburst P4.
+ * The copy is aligned with the buffer start (more likely to
+ * be a multiple of 8 than the end).
+ */
+10:
+       lea     -8(%rsi,%rcx,8),%rsi
+       lea     -8(%rdi,%rcx,8),%rdi
+       std
+       rep
+       movsq
+       cld
+       mov     %r10,(%r9)      /* write last bytes */
+       ret
+#endif
+
+/* Less than 8 bytes to copy, copy by bytes */
+/* Intel Nehalem optimise 'rep movsb' for <= 7 bytes (9-15 clocks).
+ * For longer transfers it is 50+ !
+ */
+8:     mov     %rdx,%rcx
+
+#if !defined(NO_OVERLAP)
+       cmpq    %rdx,%r8        /* overlapping? */
+       jb      81f
+#endif
+
+       /* nope, copy forwards. */
+       rep
+       movsb
+       ret
+
+#if !defined(NO_OVERLAP)
+/* Must copy backwards */
+81:
+       lea     -1(%rsi,%rcx),%rsi
+       lea     -1(%rdi,%rcx),%rdi
+       std
+       rep
+       movsb
+       cld
+       ret
+#endif
diff --git a/common/lib/libc/arch/x86_64/string/bzero.S b/common/lib/libc/arch/x86_64/string/bzero.S
new file mode 100644 (file)
index 0000000..27c6e4a
--- /dev/null
@@ -0,0 +1,8 @@
+/*
+ * Code for bzero() is in memset.S
+ *
+ * This file is left in place so that libc.a doesn't get a duplicate
+ * symbol error on update builds.
+ *
+ * If you are reading this in 2010, delete the file!
+ */
diff --git a/common/lib/libc/arch/x86_64/string/ffs.S b/common/lib/libc/arch/x86_64/string/ffs.S
new file mode 100644 (file)
index 0000000..77934ce
--- /dev/null
@@ -0,0 +1,20 @@
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ * Adapted for NetBSD/x86_64 by Frank van der Linden <fvdl@wasabisystems.com>
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: ffs.S,v 1.4 2009/07/20 15:21:00 christos Exp $")
+#endif
+
+ENTRY(ffs)
+       bsfl    %edi,%eax
+       jz      1f                      /* ZF is set if all bits are 0 */
+       incl    %eax                    /* bits numbered from 1, not 0 */
+       ret
+
+1:     xorl    %eax,%eax               /* clear result */
+       ret
diff --git a/common/lib/libc/arch/x86_64/string/memchr.S b/common/lib/libc/arch/x86_64/string/memchr.S
new file mode 100644 (file)
index 0000000..5531a51
--- /dev/null
@@ -0,0 +1,108 @@
+/*     $NetBSD: memchr.S,v 1.5 2009/08/01 20:47:02 dsl Exp $   */
+
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by David Laight.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: memchr.S,v 1.5 2009/08/01 20:47:02 dsl Exp $")
+#endif
+
+/*
+ * The instruction sequences used try to avoid data dependencies
+ * between adjacent instructions (to allow parallel execution).
+ * The 'imul' for %r9 could be put into the delay following the
+ * memory read (ie inside the loop) at no obvious cost - except
+ * that the loop is currently exactly 32 bytes - 2 fetch blocks!.
+ *
+ * I don't think aligning any of the other branch targets is useful.
+ */
+
+ENTRY(memchr)
+       movabsq $0x0101010101010101,%r8
+       lea     (%rdi,%rdx),%r10        /* limit of buffer to scan */
+       movzbq  %sil,%rsi       /* mask high bits! */
+
+       /* 'directpath' imuls can execute 3 at a time ... (amd) */
+       imul    %r8,%rsi        /* search byte replicated in word */
+       imul    $0x80,%r8,%r9   /* 0x8080808080808080 */
+       test    $7,%dil
+       jnz     20f             /* jump if misaligned */
+       jmp     1f              /* jump to avoid 4 nops (13 bytes) in gap */
+
+       _ALIGN_TEXT             /* entire loop now in 32 aligned bytes */
+1:
+       cmpq    %r10,%rdi       /* end of buffer ? */
+       jae     30f             /* jump if so */
+
+       movq    (%rdi),%rax     /* value to check */
+       addq    $8,%rdi
+       xorq    %rsi,%rax       /* now looking for zeros */
+2:
+       mov     %rax,%rcx
+       subq    %r8,%rax        /* x - 0x01 */
+       not     %rcx
+       andq    %r9,%rax        /* (x - 0x01) & 0x80 */
+       andq    %rcx,%rax       /* ((x - 0x01) & 0x80) & ~x */
+       je      1b              /* jump if not found */
+
+/* Found byte in word, get its address */
+       bsf     %rax,%rax
+       shr     $3,%eax
+       lea     -8(%rax,%rdi),%rax
+       cmpq    %r10,%rax       /* need to check not beyond buffer */
+       jae     30f
+       rep
+       ret                     /* amd - no ret after jmp */
+
+/* Input misaligned, read aligned and make low bytes invalid */
+20:
+       mov     %dil,%cl        /* misalignment amount 1..7 (+high bits )*/
+       and     $~7,%dil        /* %rdi now start of word */
+       test    %rdx,%rdx       /* zero length, don't read */
+       jz      30f
+
+       neg     %cl             /* 7..1 (+high bits) */
+       mov     (%rdi),%rax     /* word containing first byte */
+       addq    $8,%rdi
+       and     $7,%cl          /* 7..1 */
+
+       mov     %r8,%r11        /* any value with bits in each byte */
+       shl     $3,%cl          /* 56..8 */
+       xorq    %rsi,%rax       /* now looking for zeros */
+
+       /* Set low bytes non-zero */
+       shr     %cl,%r11        /* non-zero in unwanted bytes */
+       or      %r11,%rax       /* low bytes now set */
+       jmp     2b
+
+/* Not found */
+30:    xorq    %rax,%rax
+       ret
diff --git a/common/lib/libc/arch/x86_64/string/memcmp.S b/common/lib/libc/arch/x86_64/string/memcmp.S
new file mode 100644 (file)
index 0000000..86928e5
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ * Adapted for NetBSD/x86_64 by Frank van der Linden <fvdl@wasabisystems.com>
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: memcmp.S,v 1.2 2007/11/12 18:41:59 ad Exp $")
+#endif
+
+ENTRY(memcmp)
+       movq    %rdx,%rcx               /* compare by longs */
+       shrq    $3,%rcx
+       repe
+       cmpsq
+       jne     L5                      /* do we match so far? */
+
+       movq    %rdx,%rcx               /* compare remainder by bytes */
+       andq    $7,%rcx
+       repe
+       cmpsb
+       jne     L6                      /* do we match? */
+
+       xorl    %eax,%eax               /* we match, return zero        */
+       ret
+
+L5:    movl    $8,%ecx                 /* We know that one of the next */
+       subq    %rcx,%rdi               /* eight pairs of bytes do not  */
+       subq    %rcx,%rsi               /* match.                       */
+       repe
+       cmpsb
+L6:    xorl    %eax,%eax               /* Perform unsigned comparison  */
+       movb    -1(%rdi),%al
+       xorl    %edx,%edx
+       movb    -1(%rsi),%dl
+       subl    %edx,%eax
+       ret
diff --git a/common/lib/libc/arch/x86_64/string/memcpy.S b/common/lib/libc/arch/x86_64/string/memcpy.S
new file mode 100644 (file)
index 0000000..a53243b
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: memcpy.S,v 1.1 2005/12/20 19:28:51 christos Exp $      */
+
+#define MEMCOPY
+#include "bcopy.S"
diff --git a/common/lib/libc/arch/x86_64/string/memmove.S b/common/lib/libc/arch/x86_64/string/memmove.S
new file mode 100644 (file)
index 0000000..f4b7b08
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: memmove.S,v 1.1 2005/12/20 19:28:51 christos Exp $     */
+
+#define MEMMOVE
+#include "bcopy.S"
diff --git a/common/lib/libc/arch/x86_64/string/memset.S b/common/lib/libc/arch/x86_64/string/memset.S
new file mode 100644 (file)
index 0000000..8891e7e
--- /dev/null
@@ -0,0 +1,91 @@
+/*     $NetBSD: memset.S,v 1.3 2009/08/01 20:35:45 dsl Exp $   */
+
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by David Laight.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: memset.S,v 1.3 2009/08/01 20:35:45 dsl Exp $")
+#endif
+
+#ifndef _KERNEL
+/* bzero, %rdi is buffer, %rsi length */
+
+ENTRY(bzero)
+       mov     %rsi,%rdx               /* length */
+       xor     %eax,%eax               /* value to write */
+       jmp     1f
+#endif
+
+/* memset, %rdi is buffer, %rsi char to fill, %rdx length */
+
+ENTRY(memset)
+       movzbq  %sil,%rax               /* byte value to fill */
+       mov     %rdx,%rsi               /* copy of length */
+       mov     $0x0101010101010101,%r9
+       imul    %r9,%rax                /* fill value in all bytes */
+
+1:
+       mov     %rdi,%r9                /* Need to return buffer address */
+       or      %edi,%edx               /* address | length */
+       mov     %rsi,%rcx
+       cmp     $7,%rsi
+       jbe     10f                     /* jump if short fill */
+       test    $7,%dl                  /* check for misaligned fill */
+       jnz     20f                     /* jump if misaligned */
+
+/* Target aligned and length multiple of 8 */
+2:
+       shr     $3,%rcx
+       rep     stosq
+       mov     %r9,%rax
+       ret
+
+/*
+ * Short transfer, any faffing here will generate mispredicted branches.
+ * So we keep it simple.
+ */
+10:    rep     stosb
+       mov     %r9,%rax
+       ret
+
+/*
+ * Buffer or length misaligned.
+ * Write pattern to first and last word of buffer, then fill middle.
+ * (This writes to some bytes more than once - possibly three times!.)
+ */
+20:
+       mov     %rax,(%rdi)
+       movzbq  %dil,%rdx               /* low address for alignment */
+       mov     %rax,-8(%rcx,%rdi)
+       and     $7,%dl                  /* offset in word */
+       sub     %rdx,%rcx               /* adjust length ... */
+       add     %rdx,%rdi               /* ... and target */
+       jmp     2b
diff --git a/common/lib/libc/arch/x86_64/string/strcat.S b/common/lib/libc/arch/x86_64/string/strcat.S
new file mode 100644 (file)
index 0000000..9dd99a8
--- /dev/null
@@ -0,0 +1,164 @@
+/*
+ * Written by J.T. Conklin <jtc@acorntoolworks.com>
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strcat.S,v 1.1 2005/12/20 19:28:51 christos Exp $")
+#endif
+
+ENTRY(strcat)
+       movq    %rdi,%rax
+       movabsq $0x0101010101010101,%r8
+       movabsq $0x8080808080808080,%r9
+
+       /*
+        * Align destination to word boundary.
+        * Consider unrolling loop?
+        */
+.Lscan:
+.Lscan_align:
+       testb   $7,%dil
+       je      .Lscan_aligned
+       cmpb    $0,(%rdi)
+       je      .Lcopy
+       incq    %rdi
+       jmp     .Lscan_align
+
+       _ALIGN_TEXT
+.Lscan_aligned:
+.Lscan_loop:
+       movq    (%rdi),%rdx
+       addq    $8,%rdi
+       subq    %r8,%rdx
+       testq   %r9,%rdx
+       je      .Lscan_loop
+
+       /*
+        * In rare cases, the above loop may exit prematurely. We must
+        * return to the loop if none of the bytes in the word equal 0.
+        */
+
+       cmpb    $0,-8(%rdi)     /* 1st byte == 0? */
+       jne     1f
+       subq    $8,%rdi
+       jmp     .Lcopy
+
+1:     cmpb    $0,-7(%rdi)     /* 2nd byte == 0? */
+       jne     1f
+       subq    $7,%rdi
+       jmp     .Lcopy
+
+1:     cmpb    $0,-6(%rdi)     /* 3rd byte == 0? */
+       jne     1f
+       subq    $6,%rdi
+       jmp     .Lcopy
+
+1:     cmpb    $0,-5(%rdi)     /* 4th byte == 0? */
+       jne     1f
+       subq    $5,%rdi
+       jmp     .Lcopy
+
+1:     cmpb    $0,-4(%rdi)     /* 5th byte == 0? */
+       jne     1f
+       subq    $4,%rdi
+       jmp     .Lcopy
+
+1:     cmpb    $0,-3(%rdi)     /* 6th byte == 0? */
+       jne     1f
+       subq    $3,%rdi
+       jmp     .Lcopy
+
+1:     cmpb    $0,-2(%rdi)     /* 7th byte == 0? */
+       jne     1f
+       subq    $2,%rdi
+       jmp     .Lcopy
+
+1:     cmpb    $0,-1(%rdi)     /* 8th byte == 0? */
+       jne     .Lscan_loop
+       subq    $1,%rdi
+
+       /*
+        * Align source to a word boundary.
+        * Consider unrolling loop?
+        */
+.Lcopy:
+.Lcopy_align:
+       testb   $7,%sil
+       je      .Lcopy_aligned
+       movb    (%rsi),%dl
+       incq    %rsi
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl
+       jne     .Lcopy_align
+       ret
+
+       _ALIGN_TEXT
+.Lcopy_loop:
+       movq    %rdx,(%rdi)
+       addq    $8,%rdi
+.Lcopy_aligned:
+       movq    (%rsi),%rdx
+       movq    %rdx,%rcx
+       addq    $8,%rsi
+       subq    %r8,%rcx
+       testq   %r9,%rcx
+       je      .Lcopy_loop
+
+       /*
+        * In rare cases, the above loop may exit prematurely. We must
+        * return to the loop if none of the bytes in the word equal 0.
+        */
+
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 1st byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 2nd byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 3rd byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 4th byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 5th byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 6th byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 7th byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 8th byte == 0? */
+       jne     .Lcopy_aligned
+
+.Ldone:
+       ret
diff --git a/common/lib/libc/arch/x86_64/string/strchr.S b/common/lib/libc/arch/x86_64/string/strchr.S
new file mode 100644 (file)
index 0000000..a223774
--- /dev/null
@@ -0,0 +1,153 @@
+/*     $NetBSD: strchr.S,v 1.6 2009/07/20 15:21:00 christos Exp $      */
+
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by David Laight.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/* See comments in strlen.S about checking words for byte values */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strchr.S,v 1.6 2009/07/20 15:21:00 christos Exp $")
+#endif
+
+/*
+ * On entry %rdi is the buffer and the low byte of %rsi (%sil) the
+ * character to search for.
+ *
+ * Registers %rdx, %rcx, %r8-%r11 and %rax are also usable
+ */
+
+/* Uncomment below to get regression test to run this version but
+ * have everything else use the trivial one below. */
+/* #define TEST_STRCHR */
+
+#ifdef TEST_STRCHR
+ENTRY(test_strchr)
+#else
+ENTRY(strchr)
+#endif
+       movabsq $0x0101010101010101,%r8
+
+       movzbq  %sil,%rdx       /* value to search for (c) */
+       /* These imul are 'directpath' on athlons, so are fast */
+       imul    $0x80,%r8,%r9   /* 0x8080808080808080 */
+       imul    %r8,%rdx        /* (c) copied to all bytes */
+       test    $7,%dil
+       jnz     20f             /* jump if misaligned */
+
+       _ALIGN_TEXT             /* one byte nop */
+1:
+       movq    (%rdi),%rax     /* bytes to check (x) */
+2:
+       addq    $8,%rdi
+       mov     %rax,%r10
+       mov     %rax,%r11       /* for 'char' check */
+       not     %r10            /* invert of data (~x) */
+
+       xorq    %rdx,%r11       /* convert 'char' test to one for NUL */
+       subq    %r8,%rax        /* x - 0x10 */
+       movq    %r10,%rsi       /* ~x */
+       subq    %r8,%r11        /* (x ^ c) - 0x10 */
+/*
+ * Here we could check ((x - 0x10) | ((x ^ c) - 0x10)) & 0x80
+ * and short-circuit the case where no top bits are set, and
+ * we continue the loop.
+ * However it needs 3 more clocks that are difficult to interleave
+ * in the existing dependency chain ...
+ */
+       andq    %r9,%rax        /* (x - 0x10) & 0x80 */
+       xorq    %rdx,%rsi       /* c ^ ~x == ~(c ^ x) */
+       andq    %r9,%r11        /* ((x ^ c) - 0x10) & 0x80 */
+       andq    %r10,%rax       /* (x - 0x10) & 0x80 & ~x */
+       jne     10f             /* jump if string ends */
+       andq    %rsi,%r11       /* ((x ^ c) - 0x10) & 0x80 & ~(x ^ c) */
+       je      1b              /* jump if no match */
+
+       /* Found char, since LE can use bit scan */
+       bsf     %r11,%r11       /* 7, 15, 23 ... 63 */
+8:     shr     $3,%r11         /* 0, 1, 2 .. 7 */
+       lea     -8(%r11,%rdi),%rax
+       ret
+
+/* End of string, check whether char is before NUL */
+       _ALIGN_TEXT             /* adds three byte nop */
+10:
+       bsf     %rax,%rax       /* count to NUL */
+       andq    %rsi,%r11       /* check for char in last 8 bytes */
+       je      11f
+       bsf     %r11,%r11       /* NUL and char - see which was first */
+       cmp     %r11,%rax
+       jae     8b              /* return 'found' if same - searching for NUL */
+11:    xor     %eax,%eax       /* char not found */
+       ret
+
+/* Source misaligned: read aligned word and make low bytes invalid */
+/* I (dsl) think a _ALIGN_TEXT here will slow things down! */
+20:
+       xor     %rcx,%rcx
+       sub     %dil,%cl        /* Convert low address values 1..7 ... */
+       sbb     %rsi,%rsi       /* carry was set, so %rsi now ~0u! */
+       and     $7,%cl          /* ... to 7..1 */
+       and     $~7,%dil        /* move address to start of word */
+       shl     $3,%cl          /* now 56, 48 ... 16, 8 */
+       movq    (%rdi),%rax     /* aligned word containing first data */
+       xor     %rdx,%rsi       /* invert of search pattern (~c) */
+       je      22f             /* searching for 0xff */
+21:    shr     %cl,%rsi        /* ~c in low bytes */
+       or      %rsi,%rax       /* set some bits making low bytes invalid */
+       jmp     2b
+
+/* We are searching for 0xff, so can't use ~pattern for invalid value */
+22:
+       mov     %r8,%r10        /* 0x01 pattern */
+       lea     (%r8,%r8),%rsi  /* 0x02 - bits gets set (above) */
+       not     %r10            /* now 0xfe */
+       sar     %cl,%r10        /* top bytes 0xff */
+       and     %r10,%rax       /* clear lsb from unwanted low bytes */
+       jmp     21b
+
+#ifdef TEST_STRCHR
+/* Trivial version for bug-fixing above */
+ENTRY(strchr)
+       movq    %rsi,%rdx
+       movq    %rdi,%rsi
+1:
+       lodsb
+       cmp     %al,%dl
+       je      2f
+       test    %al,%al
+       jne     1b
+       xor     %eax,%eax
+       ret
+2:     lea     -1(%rsi),%rax
+       ret
+#endif
+
+STRONG_ALIAS(index,strchr)
diff --git a/common/lib/libc/arch/x86_64/string/strcmp.S b/common/lib/libc/arch/x86_64/string/strcmp.S
new file mode 100644 (file)
index 0000000..ce05ff4
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Written by J.T. Conklin <jtc@acorntoolworks.com>
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strcmp.S,v 1.1 2005/12/20 19:28:51 christos Exp $")
+#endif
+
+ENTRY(strcmp)
+       /*
+        * Align s1 to word boundary.
+        * Consider unrolling loop?
+        */
+.Ls1align:
+       testb   $7,%dil
+       je      .Ls1aligned
+       movb    (%rdi),%al
+       incq    %rdi
+       movb    (%rsi),%dl
+       incq    %rsi
+       testb   %al,%al
+       je      .Ldone
+       cmpb    %al,%dl
+       je      .Ls1align
+       jmp     .Ldone
+
+       /*
+        * Check whether s2 is aligned to a word boundary.  If it is, we
+        * can compare by words.  Otherwise we have to compare by bytes.
+        */
+.Ls1aligned:
+       testb   $7,%sil
+       jne     .Lbyte_loop
+
+       movabsq $0x0101010101010101,%r8
+       subq    $8,%rdi
+       movabsq $0x8080808080808080,%r9
+       subq    $8,%rsi
+
+       _ALIGN_TEXT
+.Lword_loop:
+       movq    8(%rdi),%rax
+       addq    $8,%rdi
+       movq    8(%rsi),%rdx
+       addq    $8,%rsi
+       cmpq    %rax,%rdx
+       jne     .Lbyte_loop
+       subq    %r8,%rdx
+       notq    %rax
+       andq    %rax,%rdx
+       testq   %r9,%rdx
+       je      .Lword_loop
+
+       _ALIGN_TEXT
+.Lbyte_loop:
+       movb    (%rdi),%al
+       incq    %rdi
+       movb    (%rsi),%dl
+       incq    %rsi
+       testb   %al,%al
+       je      .Ldone
+       cmpb    %al,%dl
+       je      .Lbyte_loop
+
+.Ldone:
+       movzbq  %al,%rax
+       movzbq  %dl,%rdx
+       subq    %rdx,%rax
+       ret
diff --git a/common/lib/libc/arch/x86_64/string/strcpy.S b/common/lib/libc/arch/x86_64/string/strcpy.S
new file mode 100644 (file)
index 0000000..02cb408
--- /dev/null
@@ -0,0 +1,111 @@
+/*
+ * Written by J.T. Conklin <jtc@acorntoolworks.com>
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strcpy.S,v 1.1 2005/12/20 19:28:51 christos Exp $")
+#endif
+
+/*
+ * This strcpy implementation copies a byte at a time until the
+ * source pointer is aligned to a word boundary, it then copies by
+ * words until it finds a word containing a zero byte, and finally
+ * copies by bytes until the end of the string is reached.
+ *
+ * While this may result in unaligned stores if the source and
+ * destination pointers are unaligned with respect to each other,
+ * it is still faster than either byte copies or the overhead of
+ * an implementation suitable for machines with strict alignment
+ * requirements.
+ */
+
+ENTRY(strcpy)
+       movq    %rdi,%rax
+       movabsq $0x0101010101010101,%r8
+       movabsq $0x8080808080808080,%r9
+
+       /*
+        * Align source to a word boundary.
+        * Consider unrolling loop?
+        */
+       _ALIGN_TEXT
+.Lalign:
+       testb   $7,%sil
+       je      .Lword_aligned
+       movb    (%rsi),%dl
+       incq    %rsi
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl
+       jne     .Lalign
+       ret
+
+       _ALIGN_TEXT
+.Lloop:
+       movq    %rdx,(%rdi)
+       addq    $8,%rdi
+.Lword_aligned:
+       movq    (%rsi),%rdx
+       movq    %rdx,%rcx
+       addq    $8,%rsi
+       subq    %r8,%rcx
+       testq   %r9,%rcx
+       je      .Lloop
+
+       /*
+        * In rare cases, the above loop may exit prematurely. We must
+        * return to the loop if none of the bytes in the word equal 0.
+        */
+
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 1st byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 2nd byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 3rd byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 4th byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 5th byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 6th byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 7th byte == 0? */
+       je      .Ldone
+
+       shrq    $8,%rdx
+       movb    %dl,(%rdi)
+       incq    %rdi
+       testb   %dl,%dl         /* 8th byte == 0? */
+       jne     .Lword_aligned
+
+.Ldone:
+       ret
diff --git a/common/lib/libc/arch/x86_64/string/strlen.S b/common/lib/libc/arch/x86_64/string/strlen.S
new file mode 100644 (file)
index 0000000..01391d9
--- /dev/null
@@ -0,0 +1,176 @@
+/*     $NetBSD: strlen.S,v 1.5 2009/07/12 21:24:21 dsl Exp $   */
+
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by David Laight.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * Inspired by a version written by J.T. Conklin <jtc@acorntoolworks.com>
+ * (Only the long comment really remains his work!)
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strlen.S,v 1.5 2009/07/12 21:24:21 dsl Exp $")
+#endif
+
+/*
+ * There are many well known branch-free sequences which are used
+ * for determining whether a zero-byte is contained within a word.
+ * These sequences are generally much more efficent than loading
+ * and comparing each byte individually.
+ *
+ * The expression [1,2]:
+ *
+ * (1)  ~(((x & 0x7f....7f) + 0x7f....7f) | (x | 0x7f....7f))
+ *
+ * evaluates to a non-zero value if any of the bytes in the
+ * original word is zero.
+ *
+ * It also has the useful property that bytes in the result word
+ * that correspond to non-zero bytes in the original word have
+ * the value 0x00, while bytes corresponding to zero bytes have
+ * the value 0x80. This allows calculation of the first (and
+ * last) occurrence of a zero byte within the word (useful for C's
+ * str* primitives) by counting the number of leading (or
+ * trailing) zeros and dividing the result by 8.  On machines
+ * without (or with slow) clz() / ctz() instructions, testing
+ * each byte in the result word for zero is necessary.
+ *
+ * This typically takes 4 instructions (5 on machines without
+ * "not-or") not including those needed to load the constant.
+ *
+ *
+ * The expression:
+ *
+ * (2)  ((x - 0x01....01) & 0x80....80 & ~x)
+ *
+ * evaluates to a non-zero value if any of the bytes in the
+ * original word is zero.
+ *
+ * On little endian machines, the first byte in the result word
+ * that corresponds to a zero byte in the original byte is 0x80,
+ * so clz() can be used as above.  On big endian machines, and
+ * little endian machines without (or with a slow) clz() insn,
+ * testing each byte in the original for zero is necessary.
+ *
+ * This typically takes 3 instructions (4 on machines without
+ * "and with complement") not including those needed to load
+ * constants.
+ *
+ *
+ * The expression:
+ *
+ * (3)  ((x - 0x01....01) & 0x80....80)
+ *
+ * always evaluates to a non-zero value if any of the bytes in
+ * the original word is zero or has the top bit set.
+ * For strings that are likely to only contain 7-bit ascii these
+ * false positives will be rare.
+ *
+ * To account for possible false positives, each byte of the
+ * original word must be checked when the expression evaluates to
+ * a non-zero value.  However, because it is simpler than those
+ * presented above, code that uses it will be faster as long as
+ * the rate of false positives is low.
+ *
+ * This is likely, because the the false positive can only occur
+ * if the most siginificant bit of a byte within the word is set.
+ * The expression will never fail for typical 7-bit ASCII strings.
+ *
+ * This typically takes 2 instructions not including those needed
+ * to load constants.
+ *
+ *
+ * [1] Henry S. Warren Jr., "Hacker's Delight", Addison-Westley 2003
+ *
+ * [2] International Business Machines, "The PowerPC Compiler Writer's
+ *     Guide", Warthman Associates, 1996
+ */
+
+#ifdef TEST_STRLEN
+ENTRY(test_strlen)
+#else
+ENTRY(strlen)
+#endif
+       movabsq $0x0101010101010101,%r8
+
+       test    $7,%dil
+       movq    %rdi,%rax               /* Buffer, %rdi unchanged */
+       movabsq $0x8080808080808080,%r9
+       jnz     10f                     /* Jump if misaligned */
+
+       _ALIGN_TEXT
+1:
+       movq    (%rax),%rdx             /* get bytes to check */
+2:
+       addq    $8,%rax
+       mov     %rdx,%rcx               /* save for later check */
+       subq    %r8,%rdx                /* alg (3) above first */
+       not     %rcx                    /* Invert of data */
+       andq    %r9,%rdx
+       je      1b                      /* jump if all 0x01-0x80 */
+
+       /* Do check from alg (2) above - loops for 0x81..0xff bytes */
+       andq    %rcx,%rdx
+       je      1b
+
+       /* Since we are LE, use bit scan for first 0x80 byte */
+       sub     %rdi,%rax               /* length to next word */
+       bsf     %rdx,%rdx               /* 7, 15, 23 ... 63 */
+       shr     $3,%rdx                 /* 0, 1, 2 ... 7 */
+       lea     -8(%rax,%rdx),%rax
+       ret
+
+/* Misaligned, read aligned word and make low bytes non-zero */
+       _ALIGN_TEXT
+10:
+       mov     %al,%cl
+       mov     $1,%rsi
+       and     $7,%cl                  /* offset into word 1..7 */
+       and     $~7,%al                 /* start of word with buffer */
+       shl     $3,%cl                  /* bit count 8, 16 .. 56 */
+       movq    (%rax),%rdx             /* first data in high bytes */
+       shl     %cl,%rsi
+       dec     %rsi
+       or      %rsi,%rdx               /* low bytes now non-zero */
+       jmp     2b
+
+#ifdef TEST_STRLEN
+/* trivial implementation when testing above! */
+ENTRY(strlen)
+       mov     %rdi,%rax
+1:
+       cmpb    $0,(%rax)
+       jz      2f
+       inc     %rax
+       jmp     1b
+2:     sub     %rdi,%rax
+       ret
+#endif
diff --git a/common/lib/libc/arch/x86_64/string/strrchr.S b/common/lib/libc/arch/x86_64/string/strrchr.S
new file mode 100644 (file)
index 0000000..9f3ebb1
--- /dev/null
@@ -0,0 +1,124 @@
+/*
+ * Written by J.T. Conklin <jtc@acorntoolworks.com>
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strrchr.S,v 1.2 2009/07/17 19:37:57 dsl Exp $")
+#endif
+
+ENTRY(strrchr)
+       movzbq  %sil,%rcx
+
+       /* zero return value */
+       xorq    %rax,%rax
+
+       /*
+        * Align to word boundary.
+        * Consider unrolling loop?
+        */
+.Lalign:
+       testb   $7,%dil
+       je      .Lword_aligned
+       movb    (%rdi),%dl
+       cmpb    %cl,%dl
+       cmoveq  %rdi,%rax
+       incq    %rdi
+       testb   %dl,%dl
+       jne     .Lalign
+       jmp     .Ldone
+
+.Lword_aligned:
+       /* copy char to all bytes in word */
+       movb    %cl,%ch
+       movq    %rcx,%rdx
+       salq    $16,%rcx
+       orq     %rdx,%rcx
+       movq    %rcx,%rdx
+       salq    $32,%rcx
+       orq     %rdx,%rcx
+
+       movabsq $0x0101010101010101,%r8
+       movabsq $0x8080808080808080,%r9
+
+       /* Check whether any byte in the word is equal to ch or 0. */
+       _ALIGN_TEXT
+.Lloop:
+       movq    (%rdi),%rdx
+       addq    $8,%rdi
+       movq    %rdx,%rsi
+       subq    %r8,%rdx
+       xorq    %rcx,%rsi
+       subq    %r8,%rsi
+       orq     %rsi,%rdx
+       testq   %r9,%rdx
+       je      .Lloop
+
+       /*
+        * In rare cases, the above loop may exit prematurely. We must
+        * return to the loop if none of the bytes in the word match
+        * ch or are equal to 0.
+        */
+
+       movb    -8(%rdi),%dl
+       cmpb    %cl,%dl         /* 1st byte == ch? */
+       jne     1f
+       leaq    -8(%rdi),%rax
+1:     testb   %dl,%dl         /* 1st byte == 0? */
+       je      .Ldone
+
+       movb    -7(%rdi),%dl
+       cmpb    %cl,%dl         /* 2nd byte == ch? */
+       jne     1f
+       leaq    -7(%rdi),%rax
+1:     testb   %dl,%dl         /* 2nd byte == 0? */
+       je      .Ldone
+
+       movb    -6(%rdi),%dl
+       cmpb    %cl,%dl         /* 3rd byte == ch? */
+       jne     1f
+       leaq    -6(%rdi),%rax
+1:     testb   %dl,%dl         /* 3rd byte == 0? */
+       je      .Ldone
+
+       movb    -5(%rdi),%dl
+       cmpb    %cl,%dl         /* 4th byte == ch? */
+       jne     1f
+       leaq    -5(%rdi),%rax
+1:     testb   %dl,%dl         /* 4th byte == 0? */
+       je      .Ldone
+
+       movb    -4(%rdi),%dl
+       cmpb    %cl,%dl         /* 5th byte == ch? */
+       jne     1f
+       leaq    -4(%rdi),%rax
+1:     testb   %dl,%dl         /* 5th byte == 0? */
+       je      .Ldone
+
+       movb    -3(%rdi),%dl
+       cmpb    %cl,%dl         /* 6th byte == ch? */
+       jne     1f
+       leaq    -3(%rdi),%rax
+1:     testb   %dl,%dl         /* 6th byte == 0? */
+       je      .Ldone
+
+       movb    -2(%rdi),%dl
+       cmpb    %cl,%dl         /* 7th byte == ch? */
+       jne     1f
+       leaq    -2(%rdi),%rax
+1:     testb   %dl,%dl         /* 7th byte == 0? */
+       je      .Ldone
+
+       movb    -1(%rdi),%dl
+       cmpb    %cl,%dl         /* 8th byte == ch? */
+       jne     1f
+       leaq    -1(%rdi),%rax
+1:     testb   %dl,%dl         /* 8th byte == 0? */
+       jne     .Lloop
+
+.Ldone:
+       ret
+
+STRONG_ALIAS(rindex,strrchr)
diff --git a/common/lib/libc/atomic/atomic_add_32_cas.c b/common/lib/libc/atomic/atomic_add_32_cas.c
new file mode 100644 (file)
index 0000000..e94682f
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: atomic_add_32_cas.c,v 1.4 2008/04/28 20:22:52 martin Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+void
+atomic_add_32(volatile uint32_t *addr, int32_t val)
+{
+       uint32_t old, new;
+
+       do {
+               old = *addr;
+               new = old + val;
+       } while (atomic_cas_32(addr, old, new) != old);
+}
+
+#undef atomic_add_32
+atomic_op_alias(atomic_add_32,_atomic_add_32)
+
+#undef atomic_add_int
+atomic_op_alias(atomic_add_int,_atomic_add_32)
+__strong_alias(_atomic_add_int,_atomic_add_32)
+
+#if !defined(_LP64)
+#undef atomic_add_long
+atomic_op_alias(atomic_add_long,_atomic_add_32)
+__strong_alias(_atomic_add_long,_atomic_add_32)
+
+#undef atomic_add_ptr
+atomic_op_alias(atomic_add_ptr,_atomic_add_32)
+__strong_alias(_atomic_add_ptr,_atomic_add_32)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_add_32_nv_cas.c b/common/lib/libc/atomic/atomic_add_32_nv_cas.c
new file mode 100644 (file)
index 0000000..1416d97
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: atomic_add_32_nv_cas.c,v 1.4 2008/04/28 20:22:52 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+uint32_t
+atomic_add_32_nv(volatile uint32_t *addr, int32_t val)
+{
+       uint32_t old, new;
+
+       do {
+               old = *addr;
+               new = old + val;
+       } while (atomic_cas_32(addr, old, new) != old);
+
+       return (new);
+}
+
+#undef atomic_add_32_nv
+atomic_op_alias(atomic_add_32_nv,_atomic_add_32_nv)
+
+#undef atomic_add_int_nv
+atomic_op_alias(atomic_add_int_nv,_atomic_add_32_nv)
+__strong_alias(_atomic_add_int_nv,_atomic_add_32_nv)
+
+#if !defined(_LP64)
+#undef atomic_add_long_nv
+atomic_op_alias(atomic_add_long_nv,_atomic_add_32_nv)
+__strong_alias(_atomic_add_long_nv,_atomic_add_32_nv)
+
+#undef atomic_add_ptr_nv
+atomic_op_alias(atomic_add_ptr_nv,_atomic_add_32_nv)
+__strong_alias(_atomic_add_ptr_nv,_atomic_add_32_nv)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_add_64_cas.c b/common/lib/libc/atomic/atomic_add_64_cas.c
new file mode 100644 (file)
index 0000000..b99a800
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: atomic_add_64_cas.c,v 1.5 2008/04/28 20:22:52 martin Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+void
+atomic_add_64(volatile uint64_t *addr, int64_t val)
+{
+       uint64_t old, new;
+
+       do {
+               old = *addr;
+               new = old + val;
+       } while (atomic_cas_64(addr, old, new) != old);
+}
+
+#undef atomic_add_64
+atomic_op_alias(atomic_add_64,_atomic_add_64)
+
+#if defined(_LP64)
+#undef atomic_add_long
+atomic_op_alias(atomic_add_long,_atomic_add_64)
+__strong_alias(_atomic_add_long,_atomic_add_64)
+
+#undef atomic_add_ptr
+atomic_op_alias(atomic_add_ptr,_atomic_add_64)
+__strong_alias(_atomic_add_ptr,_atomic_add_64)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_add_64_nv_cas.c b/common/lib/libc/atomic/atomic_add_64_nv_cas.c
new file mode 100644 (file)
index 0000000..9dde5e9
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: atomic_add_64_nv_cas.c,v 1.5 2008/04/28 20:22:52 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+uint64_t
+atomic_add_64_nv(volatile uint64_t *addr, int64_t val)
+{
+       uint64_t old, new;
+
+       do {
+               old = *addr;
+               new = old + val;
+       } while (atomic_cas_64(addr, old, new) != old);
+
+       return (new);
+}
+
+#undef atomic_add_64_nv
+atomic_op_alias(atomic_add_64_nv,_atomic_add_64_nv)
+
+#if defined(_LP64)
+#undef atomic_add_long_nv
+atomic_op_alias(atomic_add_long_nv,_atomic_add_64_nv)
+__strong_alias(_atomic_add_long_nv,_atomic_add_64_nv)
+
+#undef atomic_add_ptr_nv
+atomic_op_alias(atomic_add_ptr_nv,_atomic_add_64_nv)
+__strong_alias(_atomic_add_ptr_nv,_atomic_add_64_nv)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_and_32_cas.c b/common/lib/libc/atomic/atomic_and_32_cas.c
new file mode 100644 (file)
index 0000000..a95fe68
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: atomic_and_32_cas.c,v 1.4 2008/04/28 20:22:52 martin Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+void
+atomic_and_32(volatile uint32_t *addr, uint32_t val)
+{
+       uint32_t old, new;
+
+       do {
+               old = *addr;
+               new = old & val;
+       } while (atomic_cas_32(addr, old, new) != old);
+}
+
+#undef atomic_and_32
+atomic_op_alias(atomic_and_32,_atomic_and_32)
+#undef atomic_and_uint
+atomic_op_alias(atomic_and_uint,_atomic_and_32)
+__strong_alias(_atomic_and_uint,_atomic_and_32)
+#if !defined(_LP64)
+#undef atomic_and_ulong
+atomic_op_alias(atomic_and_ulong,_atomic_and_32)
+__strong_alias(_atomic_and_ulong,_atomic_and_32)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_and_32_nv_cas.c b/common/lib/libc/atomic/atomic_and_32_nv_cas.c
new file mode 100644 (file)
index 0000000..9a391c9
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: atomic_and_32_nv_cas.c,v 1.4 2008/04/28 20:22:52 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+uint32_t
+atomic_and_32_nv(volatile uint32_t *addr, uint32_t val)
+{
+       uint32_t old, new;
+
+       do {
+               old = *addr;
+               new = old & val;
+       } while (atomic_cas_32(addr, old, new) != old);
+
+       return (new);
+}
+
+#undef atomic_and_32_nv
+atomic_op_alias(atomic_and_32_nv,_atomic_and_32_nv)
+#undef atomic_and_uint_nv
+atomic_op_alias(atomic_and_uint_nv,_atomic_and_32_nv)
+__strong_alias(_atomic_and_uint_nv,_atomic_and_32_nv)
+#if !defined(_LP64)
+#undef atomic_and_ulong_nv
+atomic_op_alias(atomic_and_ulong_nv,_atomic_and_32_nv)
+__strong_alias(_atomic_and_ulong_nv,_atomic_and_32_nv)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_and_64_cas.c b/common/lib/libc/atomic/atomic_and_64_cas.c
new file mode 100644 (file)
index 0000000..7c3c522
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: atomic_and_64_cas.c,v 1.5 2008/04/28 20:22:52 martin Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+void
+atomic_and_64(volatile uint64_t *addr, uint64_t val)
+{
+       uint64_t old, new;
+
+       do {
+               old = *addr;
+               new = old & val;
+       } while (atomic_cas_64(addr, old, new) != old);
+}
+
+#undef atomic_and_64
+atomic_op_alias(atomic_and_64,_atomic_and_64)
+#if defined(_LP64)
+#undef atomic_and_ulong
+atomic_op_alias(atomic_and_ulong,_atomic_and_64)
+__strong_alias(_atomic_and_ulong,_atomic_and_64)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_and_64_nv_cas.c b/common/lib/libc/atomic/atomic_and_64_nv_cas.c
new file mode 100644 (file)
index 0000000..4c9019d
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: atomic_and_64_nv_cas.c,v 1.5 2008/04/28 20:22:52 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+uint64_t
+atomic_and_64_nv(volatile uint64_t *addr, uint64_t val)
+{
+       uint64_t old, new;
+
+       do {
+               old = *addr;
+               new = old & val;
+       } while (atomic_cas_64(addr, old, new) != old);
+
+       return (new);
+}
+
+#undef atomic_and_64_nv
+atomic_op_alias(atomic_and_64_nv,_atomic_and_64_nv)
+#if defined(_LP64)
+#undef atomic_and_ulong_nv
+atomic_op_alias(atomic_and_ulong_nv,_atomic_and_64_nv)
+__strong_alias(_atomic_and_ulong_nv,_atomic_and_64_nv)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_dec_32_add.c b/common/lib/libc/atomic/atomic_dec_32_add.c
new file mode 100644 (file)
index 0000000..46285d6
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: atomic_dec_32_add.c,v 1.3 2008/04/28 20:22:52 martin Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+void
+atomic_dec_32(volatile uint32_t *addr)
+{
+
+       atomic_add_32(addr, -1);
+}
+
+#undef atomic_dec_32
+atomic_op_alias(atomic_dec_32,_atomic_dec_32)
+#undef atomic_dec_uint
+atomic_op_alias(atomic_dec_uint,_atomic_dec_32)
+__strong_alias(_atomic_dec_uint,_atomic_dec_32)
+#if !defined(_LP64)
+#undef atomic_dec_ulong
+atomic_op_alias(atomic_dec_ulong,_atomic_dec_32)
+__strong_alias(_atomic_dec_ulong,_atomic_dec_32)
+#undef atomic_dec_ptr
+atomic_op_alias(atomic_dec_ptr,_atomic_dec_32)
+__strong_alias(_atomic_dec_ptr,_atomic_dec_32)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_dec_32_cas.c b/common/lib/libc/atomic/atomic_dec_32_cas.c
new file mode 100644 (file)
index 0000000..0f977f3
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: atomic_dec_32_cas.c,v 1.3 2008/04/28 20:22:52 martin Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+void
+atomic_dec_32(volatile uint32_t *addr)
+{
+       uint32_t old, new;
+
+       do {
+               old = *addr;
+               new = old - 1;
+       } while (atomic_cas_32(addr, old, new) != old);
+}
+
+#undef atomic_dec_32
+atomic_op_alias(atomic_dec_32,_atomic_dec_32)
+
+#undef atomic_dec_uint
+atomic_op_alias(atomic_dec_uint,_atomic_dec_32)
+__strong_alias(_atomic_dec_uint,_atomic_dec_32)
+
+#if !defined(_LP64)
+#undef atomic_dec_ulong
+atomic_op_alias(atomic_dec_ulong,_atomic_dec_32)
+__strong_alias(_atomic_dec_ulong,_atomic_dec_32)
+
+#undef atomic_dec_ptr
+atomic_op_alias(atomic_dec_ptr,_atomic_dec_32)
+__strong_alias(_atomic_dec_ptr,_atomic_dec_32)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_dec_32_nv_add.c b/common/lib/libc/atomic/atomic_dec_32_nv_add.c
new file mode 100644 (file)
index 0000000..4af68c5
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: atomic_dec_32_nv_add.c,v 1.3 2008/04/28 20:22:52 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+uint32_t
+atomic_dec_32_nv(volatile uint32_t *addr)
+{
+
+       return (atomic_add_32_nv(addr, -1));
+}
+
+#undef atomic_dec_32_nv
+atomic_op_alias(atomic_dec_32_nv,_atomic_dec_32_nv)
+#undef atomic_dec_uint_nv
+atomic_op_alias(atomic_dec_uint_nv,_atomic_dec_32_nv)
+__strong_alias(_atomic_dec_uint_nv,_atomic_dec_32_nv)
+#if !defined(_LP64)
+#undef atomic_dec_ulong_nv
+atomic_op_alias(atomic_dec_ulong_nv,_atomic_dec_32_nv)
+__strong_alias(_atomic_dec_ulong_nv,_atomic_dec_32_nv)
+#undef atomic_dec_ptr_nv
+atomic_op_alias(atomic_dec_ptr_nv,_atomic_dec_32_nv)
+__strong_alias(_atomic_dec_ptr_nv,_atomic_dec_32_nv)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_dec_32_nv_cas.c b/common/lib/libc/atomic/atomic_dec_32_nv_cas.c
new file mode 100644 (file)
index 0000000..9f7d6ae
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: atomic_dec_32_nv_cas.c,v 1.3 2008/04/28 20:22:52 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+uint32_t
+atomic_dec_32_nv(volatile uint32_t *addr)
+{
+       uint32_t old, new;
+
+       do {
+               old = *addr;
+               new = old - 1;
+       } while (atomic_cas_32(addr, old, new) != old);
+
+       return (new);
+}
+
+#undef atomic_dec_32_nv
+atomic_op_alias(atomic_dec_32_nv,_atomic_dec_32_nv)
+
+#undef atomic_dec_uint_nv
+atomic_op_alias(atomic_dec_uint_nv,_atomic_dec_32_nv)
+__strong_alias(_atomic_dec_uint_nv,_atomic_dec_32_nv)
+
+#if !defined(_LP64)
+#undef atomic_dec_ulong_nv
+atomic_op_alias(atomic_dec_ulong_nv,_atomic_dec_32_nv)
+__strong_alias(_atomic_dec_ulong_nv,_atomic_dec_32_nv)
+
+#undef atomic_dec_ptr_nv
+atomic_op_alias(atomic_dec_ptr_nv,_atomic_dec_32_nv)
+__strong_alias(_atomic_dec_ptr_nv,_atomic_dec_32_nv)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_dec_64_add.c b/common/lib/libc/atomic/atomic_dec_64_add.c
new file mode 100644 (file)
index 0000000..dca0ee3
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: atomic_dec_64_add.c,v 1.4 2008/04/28 20:22:52 martin Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+void
+atomic_dec_64(volatile uint64_t *addr)
+{
+
+       atomic_add_64(addr, -1);
+}
+
+#undef atomic_dec_64
+atomic_op_alias(atomic_dec_64,_atomic_dec_64)
+#if defined(_LP64)
+#undef atomic_dec_ulong
+atomic_op_alias(atomic_dec_ulong,_atomic_dec_64)
+__strong_alias(_atomic_dec_ulong,_atomic_dec_64)
+#undef atomic_dec_ptr
+atomic_op_alias(atomic_dec_ptr,_atomic_dec_64)
+__strong_alias(_atomic_dec_ptr,_atomic_dec_64)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_dec_64_cas.c b/common/lib/libc/atomic/atomic_dec_64_cas.c
new file mode 100644 (file)
index 0000000..0c20ace
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: atomic_dec_64_cas.c,v 1.3 2008/04/28 20:22:52 martin Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+void
+atomic_dec_64(volatile uint64_t *addr)
+{
+       uint64_t old, new;
+
+       do {
+               old = *addr;
+               new = old - 1;
+       } while (atomic_cas_64(addr, old, new) != old);
+}
+
+#undef atomic_dec_64
+atomic_op_alias(atomic_dec_64,_atomic_dec_64)
+
+#if defined(_LP64)
+#undef atomic_dec_ulong
+atomic_op_alias(atomic_dec_ulong,_atomic_dec_64)
+__strong_alias(_atomic_dec_ulong,_atomic_dec_64)
+
+#undef atomic_dec_ptr
+atomic_op_alias(atomic_dec_ptr,_atomic_dec_64)
+__strong_alias(_atomic_dec_ptr,_atomic_dec_64)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_dec_64_nv_add.c b/common/lib/libc/atomic/atomic_dec_64_nv_add.c
new file mode 100644 (file)
index 0000000..02a90b0
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: atomic_dec_64_nv_add.c,v 1.4 2008/04/28 20:22:52 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+uint64_t
+atomic_dec_64_nv(volatile uint64_t *addr)
+{
+
+       return (atomic_add_64_nv(addr, -1));
+}
+
+#undef atomic_dec_64_nv
+atomic_op_alias(atomic_dec_64_nv,_atomic_dec_64_nv)
+#if defined(_LP64)
+#undef atomic_dec_ulong_nv
+atomic_op_alias(atomic_dec_ulong_nv,_atomic_dec_64_nv)
+__strong_alias(_atomic_dec_ulong_nv,_atomic_dec_64_nv)
+#undef atomic_dec_ptr_nv
+atomic_op_alias(atomic_dec_ptr_nv,_atomic_dec_64_nv)
+__strong_alias(_atomic_dec_ptr_nv,_atomic_dec_64_nv)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_dec_64_nv_cas.c b/common/lib/libc/atomic/atomic_dec_64_nv_cas.c
new file mode 100644 (file)
index 0000000..22f5c90
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: atomic_dec_64_nv_cas.c,v 1.3 2008/04/28 20:22:52 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+uint64_t
+atomic_dec_64_nv(volatile uint64_t *addr)
+{
+       uint64_t old, new;
+
+       do {
+               old = *addr;
+               new = old - 1;
+       } while (atomic_cas_64(addr, old, new) != old);
+
+       return (new);
+}
+
+#undef atomic_dec_64_nv
+atomic_op_alias(atomic_dec_64_nv,_atomic_dec_64_nv)
+
+#if defined(_LP64)
+#undef atomic_dec_ulong_nv
+atomic_op_alias(atomic_dec_ulong_nv,_atomic_dec_64_nv)
+__strong_alias(_atomic_dec_ulong_nv,_atomic_dec_64_nv)
+
+#undef atomic_dec_ptr_nv
+atomic_op_alias(atomic_dec_ptr_nv,_atomic_dec_64_nv)
+__strong_alias(_atomic_dec_ptr_nv,_atomic_dec_64_nv)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_inc_32_add.c b/common/lib/libc/atomic/atomic_inc_32_add.c
new file mode 100644 (file)
index 0000000..06aaa46
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: atomic_inc_32_add.c,v 1.3 2008/04/28 20:22:52 martin Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+void
+atomic_inc_32(volatile uint32_t *addr)
+{
+
+       atomic_add_32(addr, 1);
+}
+
+#undef atomic_inc_32
+atomic_op_alias(atomic_inc_32,_atomic_inc_32)
+#undef atomic_inc_uint
+atomic_op_alias(atomic_inc_uint,_atomic_inc_32)
+__strong_alias(_atomic_inc_uint,_atomic_inc_32)
+#if !defined(_LP64)
+#undef atomic_inc_ulong
+atomic_op_alias(atomic_inc_ulong,_atomic_inc_32)
+__strong_alias(_atomic_inc_ulong,_atomic_inc_32)
+#undef atomic_inc_ptr
+atomic_op_alias(atomic_inc_ptr,_atomic_inc_32)
+__strong_alias(_atomic_inc_ptr,_atomic_inc_32)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_inc_32_cas.c b/common/lib/libc/atomic/atomic_inc_32_cas.c
new file mode 100644 (file)
index 0000000..2f8f915
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: atomic_inc_32_cas.c,v 1.3 2008/04/28 20:22:52 martin Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+void
+atomic_inc_32(volatile uint32_t *addr)
+{
+       uint32_t old, new;
+
+       do {
+               old = *addr;
+               new = old + 1;
+       } while (atomic_cas_32(addr, old, new) != old);
+}
+
+#undef atomic_inc_32
+atomic_op_alias(atomic_inc_32,_atomic_inc_32)
+
+#undef atomic_inc_uint
+atomic_op_alias(atomic_inc_uint,_atomic_inc_32)
+__strong_alias(_atomic_inc_uint,_atomic_inc_32)
+
+#if !defined(_LP64)
+#undef atomic_inc_ulong
+atomic_op_alias(atomic_inc_ulong,_atomic_inc_32)
+__strong_alias(_atomic_inc_ulong,_atomic_inc_32)
+
+#undef atomic_inc_ptr
+atomic_op_alias(atomic_inc_ptr,_atomic_inc_32)
+__strong_alias(_atomic_inc_ptr,_atomic_inc_32)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_inc_32_nv_add.c b/common/lib/libc/atomic/atomic_inc_32_nv_add.c
new file mode 100644 (file)
index 0000000..6fc0900
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: atomic_inc_32_nv_add.c,v 1.3 2008/04/28 20:22:52 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+uint32_t
+atomic_inc_32_nv(volatile uint32_t *addr)
+{
+
+       return (atomic_add_32_nv(addr, 1));
+}
+
+#undef atomic_inc_32_nv
+atomic_op_alias(atomic_inc_32_nv,_atomic_inc_32_nv)
+#undef atomic_inc_uint_nv
+atomic_op_alias(atomic_inc_uint_nv,_atomic_inc_32_nv)
+__strong_alias(_atomic_inc_uint_nv,_atomic_inc_32_nv)
+#if !defined(_LP64)
+#undef atomic_inc_ulong_nv
+atomic_op_alias(atomic_inc_ulong_nv,_atomic_inc_32_nv)
+__strong_alias(_atomic_inc_ulong_nv,_atomic_inc_32_nv)
+#undef atomic_inc_ptr_nv
+atomic_op_alias(atomic_inc_ptr_nv,_atomic_inc_32_nv)
+__strong_alias(_atomic_inc_ptr_nv,_atomic_inc_32_nv)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_inc_32_nv_cas.c b/common/lib/libc/atomic/atomic_inc_32_nv_cas.c
new file mode 100644 (file)
index 0000000..45fdffb
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: atomic_inc_32_nv_cas.c,v 1.3 2008/04/28 20:22:52 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+uint32_t
+atomic_inc_32_nv(volatile uint32_t *addr)
+{
+       uint32_t old, new;
+
+       do {
+               old = *addr;
+               new = old + 1;
+       } while (atomic_cas_32(addr, old, new) != old);
+
+       return (new);
+}
+
+#undef atomic_inc_32_nv
+atomic_op_alias(atomic_inc_32_nv,_atomic_inc_32_nv)
+
+#undef atomic_inc_uint_nv
+atomic_op_alias(atomic_inc_uint_nv,_atomic_inc_32_nv)
+__strong_alias(_atomic_inc_uint_nv,_atomic_inc_32_nv)
+
+#if !defined(_LP64)
+#undef atomic_inc_ulong_nv
+atomic_op_alias(atomic_inc_ulong_nv,_atomic_inc_32_nv)
+__strong_alias(_atomic_inc_ulong_nv,_atomic_inc_32_nv)
+
+#undef atomic_inc_ptr_nv
+atomic_op_alias(atomic_inc_ptr_nv,_atomic_inc_32_nv)
+__strong_alias(_atomic_inc_ptr_nv,_atomic_inc_32_nv)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_inc_64_add.c b/common/lib/libc/atomic/atomic_inc_64_add.c
new file mode 100644 (file)
index 0000000..626eb1c
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: atomic_inc_64_add.c,v 1.4 2008/04/28 20:22:52 martin Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+void
+atomic_inc_64(volatile uint64_t *addr)
+{
+
+       atomic_add_64(addr, 1);
+}
+
+#undef atomic_inc_64
+atomic_op_alias(atomic_inc_64,_atomic_inc_64)
+#if defined(_LP64)
+#undef atomic_inc_ulong
+atomic_op_alias(atomic_inc_ulong,_atomic_inc_64)
+__strong_alias(_atomic_inc_ulong,_atomic_inc_64)
+#undef atomic_inc_ptr
+atomic_op_alias(atomic_inc_ptr,_atomic_inc_64)
+__strong_alias(_atomic_inc_ptr,_atomic_inc_64)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_inc_64_cas.c b/common/lib/libc/atomic/atomic_inc_64_cas.c
new file mode 100644 (file)
index 0000000..ded46ca
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: atomic_inc_64_cas.c,v 1.3 2008/04/28 20:22:52 martin Exp $     */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+void
+atomic_inc_64(volatile uint64_t *addr)
+{
+       uint64_t old, new;
+
+       do {
+               old = *addr;
+               new = old + 1;
+       } while (atomic_cas_64(addr, old, new) != old);
+}
+
+#undef atomic_inc_64
+atomic_op_alias(atomic_inc_64,_atomic_inc_64)
+
+#if defined(_LP64)
+#undef atomic_inc_ulong
+atomic_op_alias(atomic_inc_ulong,_atomic_inc_64)
+__strong_alias(_atomic_inc_ulong,_atomic_inc_64)
+
+#undef atomic_inc_ptr
+atomic_op_alias(atomic_inc_ptr,_atomic_inc_64)
+__strong_alias(_atomic_inc_ptr,_atomic_inc_64)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_inc_64_nv_add.c b/common/lib/libc/atomic/atomic_inc_64_nv_add.c
new file mode 100644 (file)
index 0000000..71bbc9a
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: atomic_inc_64_nv_add.c,v 1.4 2008/04/28 20:22:53 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+uint64_t
+atomic_inc_64_nv(volatile uint64_t *addr)
+{
+
+       return (atomic_add_64_nv(addr, 1));
+}
+
+#undef atomic_inc_64_nv
+atomic_op_alias(atomic_inc_64_nv,_atomic_inc_64_nv)
+#if defined(_LP64)
+#undef atomic_inc_ulong_nv
+atomic_op_alias(atomic_inc_ulong_nv,_atomic_inc_64_nv)
+__strong_alias(_atomic_inc_ulong_nv,_atomic_inc_64_nv)
+#undef atomic_inc_ptr_nv
+atomic_op_alias(atomic_inc_ptr_nv,_atomic_inc_64_nv)
+__strong_alias(_atomic_inc_ptr_nv,_atomic_inc_64_nv)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_inc_64_nv_cas.c b/common/lib/libc/atomic/atomic_inc_64_nv_cas.c
new file mode 100644 (file)
index 0000000..f835df5
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: atomic_inc_64_nv_cas.c,v 1.4 2008/04/28 20:22:53 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+uint64_t
+atomic_inc_64_nv(volatile uint64_t *addr)
+{
+       uint64_t old, new;
+
+       do {
+               old = *addr;
+               new = old + 1;
+       } while (atomic_cas_64(addr, old, new) != old);
+
+       return (new);
+}
+
+#undef atomic_inc_64_nv
+atomic_op_alias(atomic_inc_64_nv,_atomic_inc_64_nv)
+
+#if defined(_LP64)
+#undef atomic_add_ulong_nv
+atomic_op_alias(atomic_inc_ulong_nv,_atomic_inc_64_nv)
+__strong_alias(_atomic_inc_ulong_nv,_atomic_inc_64_nv)
+
+#undef atomic_inc_ptr_nv
+atomic_op_alias(atomic_inc_ptr_nv,_atomic_inc_64_nv)
+__strong_alias(_atomic_inc_ptr_nv,_atomic_inc_64_nv)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_init_cas.c b/common/lib/libc/atomic/atomic_init_cas.c
new file mode 100644 (file)
index 0000000..51a83d0
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: atomic_init_cas.c,v 1.3 2008/04/28 20:22:53 martin Exp $       */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * libc glue for atomic operations where the hardware _does_ provide
+ * compare-and-swap.
+ */
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: atomic_init_cas.c,v 1.3 2008/04/28 20:22:53 martin Exp $");
+
+void   __libc_atomic_init(void) __attribute__ ((visibility("hidden")));
+
+void
+__libc_atomic_init(void)
+{
+
+       /* nothing to do */
+}
diff --git a/common/lib/libc/atomic/atomic_init_testset.c b/common/lib/libc/atomic/atomic_init_testset.c
new file mode 100644 (file)
index 0000000..9769d62
--- /dev/null
@@ -0,0 +1,154 @@
+/*     $NetBSD: atomic_init_testset.c,v 1.7 2009/12/14 00:39:00 matt Exp $     */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * libc glue for atomic operations where the hardware does not provide
+ * compare-and-swap.  It's assumed that this will only be used on 32-bit
+ * platforms.
+ *
+ * This should be compiled with '-fno-reorder-blocks -fomit-frame-pointer'
+ * if using gcc.
+ */
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: atomic_init_testset.c,v 1.7 2009/12/14 00:39:00 matt Exp $");
+
+#include "atomic_op_namespace.h"
+
+#include <sys/types.h>
+#include <sys/atomic.h>
+#include <sys/lock.h>
+#include <sys/ras.h>
+#include <sys/sysctl.h>
+
+#include <string.h>
+
+#define        I2      __SIMPLELOCK_UNLOCKED, __SIMPLELOCK_UNLOCKED,
+#define        I16     I2 I2 I2 I2 I2 I2 I2 I2
+#define        I128    I16 I16 I16 I16 I16 I16 I16 I16
+
+static __cpu_simple_lock_t atomic_locks[128] = { I128 };
+
+#ifdef __HAVE_ASM_ATOMIC_CAS_UP
+extern uint32_t _atomic_cas_up(volatile uint32_t *, uint32_t, uint32_t);
+#else
+static uint32_t _atomic_cas_up(volatile uint32_t *, uint32_t, uint32_t);
+#endif
+
+static uint32_t (*_atomic_cas_fn)(volatile uint32_t *, uint32_t, uint32_t) =
+    _atomic_cas_up;
+
+void   __libc_atomic_init(void) __attribute__ ((visibility("hidden")));
+
+RAS_DECL(_atomic_cas);
+
+#ifndef        __HAVE_ASM_ATOMIC_CAS_UP
+static uint32_t
+_atomic_cas_up(volatile uint32_t *ptr, uint32_t old, uint32_t new)
+{
+       uint32_t ret;
+
+       RAS_START(_atomic_cas);
+       ret = *ptr;
+       if (__predict_false(ret != old)) {
+               return ret;
+       }
+       *ptr = new;
+       RAS_END(_atomic_cas);
+
+       return ret;
+}
+#endif
+
+static uint32_t
+_atomic_cas_mp(volatile uint32_t *ptr, uint32_t old, uint32_t new)
+{
+       __cpu_simple_lock_t *lock;
+       uint32_t ret;
+
+       lock = &atomic_locks[((uintptr_t)ptr >> 3) & 127];
+       __cpu_simple_lock(lock);
+       ret = *ptr;
+       if (__predict_true(ret == old)) {
+               *ptr = new;
+       }
+       __cpu_simple_unlock(lock);
+
+       return ret;
+}
+
+uint32_t
+_atomic_cas_32(volatile uint32_t *ptr, uint32_t old, uint32_t new)
+{
+
+       return (*_atomic_cas_fn)(ptr, old, new);
+}
+
+void
+__libc_atomic_init(void)
+{
+       int ncpu, mib[2];
+       size_t len;
+
+       _atomic_cas_fn = _atomic_cas_mp;
+
+       mib[0] = CTL_HW;
+       mib[1] = HW_NCPU; 
+       len = sizeof(ncpu);
+       if (sysctl(mib, 2, &ncpu, &len, NULL, 0) == -1)
+               return;
+       if (ncpu > 1)
+               return;
+       if (rasctl(RAS_ADDR(_atomic_cas), RAS_SIZE(_atomic_cas),
+           RAS_INSTALL) == 0) {
+               _atomic_cas_fn = _atomic_cas_up;
+               return;
+       }
+}
+
+#undef atomic_cas_32
+#undef atomic_cas_uint
+#undef atomic_cas_ulong
+#undef atomic_cas_ptr
+
+atomic_op_alias(atomic_cas_32,_atomic_cas_32)
+atomic_op_alias(atomic_cas_uint,_atomic_cas_32)
+__strong_alias(_atomic_cas_uint,_atomic_cas_32)
+atomic_op_alias(atomic_cas_ulong,_atomic_cas_32)
+__strong_alias(_atomic_cas_ulong,_atomic_cas_32)
+atomic_op_alias(atomic_cas_ptr,_atomic_cas_32)
+__strong_alias(_atomic_cas_ptr,_atomic_cas_32)
+
+atomic_op_alias(atomic_cas_32_ni,_atomic_cas_32)
+__strong_alias(_atomic_cas_32_ni,_atomic_cas_32)
+atomic_op_alias(atomic_cas_uint_ni,_atomic_cas_32)
+__strong_alias(_atomic_cas_uint_ni,_atomic_cas_32)
+atomic_op_alias(atomic_cas_ulong_ni,_atomic_cas_32)
+__strong_alias(_atomic_cas_ulong_ni,_atomic_cas_32)
+atomic_op_alias(atomic_cas_ptr_ni,_atomic_cas_32)
+__strong_alias(_atomic_cas_ptr_ni,_atomic_cas_32)
diff --git a/common/lib/libc/atomic/atomic_op_namespace.h b/common/lib/libc/atomic/atomic_op_namespace.h
new file mode 100644 (file)
index 0000000..5bf410e
--- /dev/null
@@ -0,0 +1,125 @@
+/*     $NetBSD: atomic_op_namespace.h,v 1.4 2008/06/23 10:33:52 ad Exp $       */
+
+/*-
+ * Copyright (c) 2007, 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _ATOMIC_OP_NAMESPACE_H_
+#define        _ATOMIC_OP_NAMESPACE_H_
+
+#include <sys/cdefs.h>
+
+#if !defined(__lint__)
+
+#define        atomic_add_32           _atomic_add_32
+#define        atomic_add_int          _atomic_add_int
+#define        atomic_add_long         _atomic_add_long
+#define        atomic_add_ptr          _atomic_add_ptr
+#define        atomic_add_64           _atomic_add_64
+
+#define        atomic_add_32_nv        _atomic_add_32_nv
+#define        atomic_add_int_nv       _atomic_add_int_nv
+#define        atomic_add_long_nv      _atomic_add_long_nv
+#define        atomic_add_ptr_nv       _atomic_add_ptr_nv
+#define        atomic_add_64_nv        _atomic_add_64_nv
+
+#define        atomic_and_32           _atomic_and_32
+#define        atomic_and_uint         _atomic_and_uint
+#define        atomic_and_ulong        _atomic_and_ulong
+#define        atomic_and_64           _atomic_and_64
+
+#define        atomic_and_32_nv        _atomic_and_32_nv
+#define        atomic_and_uint_nv      _atomic_and_uint_nv
+#define        atomic_and_ulong_nv     _atomic_and_ulong_nv
+#define        atomic_and_64_nv        _atomic_and_64_nv
+
+#define        atomic_or_32            _atomic_or_32
+#define        atomic_or_uint          _atomic_or_uint
+#define        atomic_or_ulong         _atomic_or_ulong
+#define        atomic_or_64            _atomic_or_64
+
+#define        atomic_or_32_nv         _atomic_or_32_nv
+#define        atomic_or_uint_nv       _atomic_or_uint_nv
+#define        atomic_or_ulong_nv      _atomic_or_ulong_nv
+#define        atomic_or_64_nv         _atomic_or_64_nv
+
+#define        atomic_cas_32           _atomic_cas_32
+#define        atomic_cas_uint         _atomic_cas_uint
+#define        atomic_cas_ulong        _atomic_cas_ulong
+#define        atomic_cas_ptr          _atomic_cas_ptr
+#define        atomic_cas_64           _atomic_cas_64
+
+#define        atomic_cas_32_ni        _atomic_cas_32_ni
+#define        atomic_cas_uint_ni      _atomic_cas_uint_ni
+#define        atomic_cas_ulong_ni     _atomic_cas_ulong_ni
+#define        atomic_cas_ptr_ni       _atomic_cas_ptr_ni
+#define        atomic_cas_64_ni        _atomic_cas_64_ni
+
+#define        atomic_swap_32          _atomic_swap_32
+#define        atomic_swap_uint        _atomic_swap_uint
+#define        atomic_swap_ulong       _atomic_swap_ulong
+#define        atomic_swap_ptr         _atomic_swap_ptr
+#define        atomic_swap_64          _atomic_swap_64
+
+#define        atomic_dec_32           _atomic_dec_32
+#define        atomic_dec_uint         _atomic_dec_uint
+#define        atomic_dec_ulong        _atomic_dec_ulong
+#define        atomic_dec_ptr          _atomic_dec_ptr
+#define        atomic_dec_64           _atomic_dec_64
+
+#define        atomic_dec_32_nv        _atomic_dec_32_nv
+#define        atomic_dec_uint_nv      _atomic_dec_uint_nv
+#define        atomic_dec_ptr_nv       _atomic_dec_ptr_nv
+#define        atomic_dec_64_nv        _atomic_dec_64_nv
+
+#define        atomic_inc_32           _atomic_inc_32
+#define        atomic_inc_uint         _atomic_inc_uint
+#define        atomic_inc_ulong        _atomic_inc_ulong
+#define        atomic_inc_ptr          _atomic_inc_ptr
+#define        atomic_inc_64           _atomic_inc_64
+
+#define        atomic_inc_32_nv        _atomic_inc_32_nv
+#define        atomic_inc_uint_nv      _atomic_inc_uint_nv
+#define        atomic_inc_ptr_nv       _atomic_inc_ptr_nv
+#define        atomic_inc_64_nv        _atomic_inc_64_nv
+
+#define        membar_enter            _membar_enter
+#define        membar_exit             _membar_exit
+#define        membar_producer         _membar_producer
+#define        membar_consumer         _membar_consumer
+#define        membar_sync             _membar_sync
+
+#endif /* __lint__ */
+
+#if defined(_KERNEL)
+#define        atomic_op_alias(a,s)    __strong_alias(a,s)
+#else
+#define        atomic_op_alias(a,s)    __weak_alias(a,s)
+#endif /* _KERNEL */
+
+#endif /* _ATOMIC_OP_NAMESPACE_H_ */
diff --git a/common/lib/libc/atomic/atomic_or_32_cas.c b/common/lib/libc/atomic/atomic_or_32_cas.c
new file mode 100644 (file)
index 0000000..6ce5768
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: atomic_or_32_cas.c,v 1.4 2008/04/28 20:22:53 martin Exp $      */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+void
+atomic_or_32(volatile uint32_t *addr, uint32_t val)
+{
+       uint32_t old, new;
+
+       do {
+               old = *addr;
+               new = old | val;
+       } while (atomic_cas_32(addr, old, new) != old);
+}
+
+#undef atomic_or_32
+atomic_op_alias(atomic_or_32,_atomic_or_32)
+#undef atomic_or_uint
+atomic_op_alias(atomic_or_uint,_atomic_or_32)
+__strong_alias(_atomic_or_uint,_atomic_or_32)
+#if !defined(_LP64)
+#undef atomic_or_ulong
+atomic_op_alias(atomic_or_ulong,_atomic_or_32)
+__strong_alias(_atomic_or_ulong,_atomic_or_32)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_or_32_nv_cas.c b/common/lib/libc/atomic/atomic_or_32_nv_cas.c
new file mode 100644 (file)
index 0000000..a812f86
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: atomic_or_32_nv_cas.c,v 1.4 2008/04/28 20:22:53 martin Exp $   */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+uint32_t
+atomic_or_32_nv(volatile uint32_t *addr, uint32_t val)
+{
+       uint32_t old, new;
+
+       do {
+               old = *addr;
+               new = old | val;
+       } while (atomic_cas_32(addr, old, new) != old);
+
+       return (new);
+}
+
+#undef atomic_or_32_nv
+atomic_op_alias(atomic_or_32_nv,_atomic_or_32_nv)
+#undef atomic_or_uint_nv
+atomic_op_alias(atomic_or_uint_nv,_atomic_or_32_nv)
+__strong_alias(_atomic_or_uint_nv,_atomic_or_32_nv)
+#if !defined(_LP64)
+#undef atomic_or_ulong_nv
+atomic_op_alias(atomic_or_ulong_nv,_atomic_or_32_nv)
+__strong_alias(_atomic_or_ulong_nv,_atomic_or_32_nv)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_or_64_cas.c b/common/lib/libc/atomic/atomic_or_64_cas.c
new file mode 100644 (file)
index 0000000..fc409b4
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: atomic_or_64_cas.c,v 1.5 2008/04/28 20:22:53 martin Exp $      */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+void
+atomic_or_64(volatile uint64_t *addr, uint64_t val)
+{
+       uint64_t old, new;
+
+       do {
+               old = *addr;
+               new = old | val;
+       } while (atomic_cas_64(addr, old, new) != old);
+}
+
+#undef atomic_or_64
+atomic_op_alias(atomic_or_64,_atomic_or_64)
+#if defined(_LP64)
+#undef atomic_or_ulong
+atomic_op_alias(atomic_or_ulong,_atomic_or_64)
+__strong_alias(_atomic_or_ulong,_atomic_or_64)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_or_64_nv_cas.c b/common/lib/libc/atomic/atomic_or_64_nv_cas.c
new file mode 100644 (file)
index 0000000..bbca59e
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: atomic_or_64_nv_cas.c,v 1.5 2008/04/28 20:22:53 martin Exp $   */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+uint64_t
+atomic_or_64_nv(volatile uint64_t *addr, uint64_t val)
+{
+       uint64_t old, new;
+
+       do {
+               old = *addr;
+               new = old | val;
+       } while (atomic_cas_64(addr, old, new) != old);
+
+       return (new);
+}
+
+#undef atomic_or_64_nv
+atomic_op_alias(atomic_or_64_nv,_atomic_or_64_nv)
+#if defined(_LP64)
+#undef atomic_or_ulong_nv
+atomic_op_alias(atomic_or_ulong_nv,_atomic_or_64_nv)
+__strong_alias(_atomic_or_ulong_nv,_atomic_or_64_nv)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/atomic_swap_32_cas.c b/common/lib/libc/atomic/atomic_swap_32_cas.c
new file mode 100644 (file)
index 0000000..6b8b6dc
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: atomic_swap_32_cas.c,v 1.4 2008/04/28 20:22:53 martin Exp $    */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+uint32_t
+atomic_swap_32(volatile uint32_t *addr, uint32_t new)
+{
+       uint32_t old;
+
+       do {
+               old = *addr;
+       } while (atomic_cas_32(addr, old, new) != old);
+
+       return (old);
+}
+
+#undef atomic_swap_32
+atomic_op_alias(atomic_swap_32,_atomic_swap_32)
+#undef atomic_swap_uint
+atomic_op_alias(atomic_swap_uint,_atomic_swap_32)
+__strong_alias(_atomic_swap_uint,_atomic_swap_32)
+#if !defined(_LP64)
+#undef atomic_swap_ulong
+atomic_op_alias(atomic_swap_ulong,_atomic_swap_32)
+__strong_alias(_atomic_swap_ulong,_atomic_swap_32)
+#undef atomic_swap_ptr
+atomic_op_alias(atomic_swap_ptr,_atomic_swap_32)
+__strong_alias(_atomic_swap_ptr,_atomic_swap_32)
+#endif /* _LP64 */
diff --git a/common/lib/libc/atomic/atomic_swap_64_cas.c b/common/lib/libc/atomic/atomic_swap_64_cas.c
new file mode 100644 (file)
index 0000000..8cf4db8
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: atomic_swap_64_cas.c,v 1.5 2008/04/28 20:22:53 martin Exp $    */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+#ifdef __HAVE_ATOMIC64_OPS
+
+uint64_t
+atomic_swap_64(volatile uint64_t *addr, uint64_t new)
+{
+       uint64_t old;
+
+       do {
+               old = *addr;
+       } while (atomic_cas_64(addr, old, new) != old);
+
+       return (old);
+}
+
+#undef atomic_swap_64
+atomic_op_alias(atomic_swap_64,_atomic_swap_64)
+#if defined(_LP64)
+#undef atomic_swap_ulong
+atomic_op_alias(atomic_swap_ulong,_atomic_swap_64)
+__strong_alias(_atomic_swap_ulong,_atomic_swap_64)
+#undef atomic_swap_ptr
+atomic_op_alias(atomic_swap_ptr,_atomic_swap_64)
+__strong_alias(_atomic_swap_ptr,_atomic_swap_64)
+#endif /* _LP64 */
+
+#endif
diff --git a/common/lib/libc/atomic/membar_ops_nop.c b/common/lib/libc/atomic/membar_ops_nop.c
new file mode 100644 (file)
index 0000000..f6791d9
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: membar_ops_nop.c,v 1.5 2009/08/21 14:31:02 skrll Exp $ */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "atomic_op_namespace.h"
+
+#include <sys/atomic.h>
+
+void
+membar_sync(void)
+{
+
+       /* nothing */
+}
+
+#undef membar_enter
+atomic_op_alias(membar_enter,_membar_sync)
+__strong_alias(_membar_enter,_membar_sync)
+#undef membar_exit
+atomic_op_alias(membar_exit,_membar_sync)
+__strong_alias(_membar_exit,_membar_sync)
+#undef membar_producer
+atomic_op_alias(membar_producer,_membar_sync)
+__strong_alias(_membar_producer,_membar_sync)
+#undef membar_consumer
+atomic_op_alias(membar_consumer,_membar_sync)
+__strong_alias(_membar_consumer,_membar_sync)
+#undef membar_sync
+atomic_op_alias(membar_sync,_membar_sync)
diff --git a/common/lib/libc/gen/bswap16.c b/common/lib/libc/gen/bswap16.c
new file mode 100644 (file)
index 0000000..54496fe
--- /dev/null
@@ -0,0 +1,23 @@
+/*  $NetBSD: bswap16.c,v 1.2 2008/02/16 17:37:13 apb Exp $    */
+
+/*
+ * Written by Manuel Bouyer <bouyer@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: bswap16.c,v 1.2 2008/02/16 17:37:13 apb Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <machine/bswap.h>
+
+#undef bswap16
+
+uint16_t
+bswap16(x)
+       uint16_t x;
+{
+       return ((x << 8) & 0xff00) | ((x >> 8) & 0x00ff);
+}
diff --git a/common/lib/libc/gen/bswap32.c b/common/lib/libc/gen/bswap32.c
new file mode 100644 (file)
index 0000000..ded9866
--- /dev/null
@@ -0,0 +1,26 @@
+/*  $NetBSD: bswap32.c,v 1.2 2008/02/16 17:37:13 apb Exp $    */
+
+/*
+ * Written by Manuel Bouyer <bouyer@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: bswap32.c,v 1.2 2008/02/16 17:37:13 apb Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <machine/bswap.h>
+
+#undef bswap32
+
+uint32_t
+bswap32(x)
+       uint32_t x;
+{
+       return  ((x << 24) & 0xff000000 ) |
+               ((x <<  8) & 0x00ff0000 ) |
+               ((x >>  8) & 0x0000ff00 ) |
+               ((x >> 24) & 0x000000ff );
+}
diff --git a/common/lib/libc/gen/bswap64.c b/common/lib/libc/gen/bswap64.c
new file mode 100644 (file)
index 0000000..b2decf9
--- /dev/null
@@ -0,0 +1,44 @@
+/*  $NetBSD: bswap64.c,v 1.3 2009/03/16 05:59:21 cegger Exp $    */
+
+/*
+ * Written by Manuel Bouyer <bouyer@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: bswap64.c,v 1.3 2009/03/16 05:59:21 cegger Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <machine/bswap.h>
+
+#undef bswap64
+
+uint64_t
+bswap64(uint64_t x)
+{
+#ifdef _LP64
+       /*
+        * Assume we have wide enough registers to do it without touching
+        * memory.
+        */
+       return  ( (x << 56) & 0xff00000000000000UL ) |
+               ( (x << 40) & 0x00ff000000000000UL ) |
+               ( (x << 24) & 0x0000ff0000000000UL ) |
+               ( (x <<  8) & 0x000000ff00000000UL ) |
+               ( (x >>  8) & 0x00000000ff000000UL ) |
+               ( (x >> 24) & 0x0000000000ff0000UL ) |
+               ( (x >> 40) & 0x000000000000ff00UL ) |
+               ( (x >> 56) & 0x00000000000000ffUL );
+#else
+       /*
+        * Split the operation in two 32bit steps.
+        */
+       uint32_t tl, th;
+
+       th = bswap32((uint32_t)(x & 0x00000000ffffffffULL));
+       tl = bswap32((uint32_t)((x >> 32) & 0x00000000ffffffffULL));
+       return ((uint64_t)th << 32) | tl;
+#endif
+}
diff --git a/common/lib/libc/gen/ptree.c b/common/lib/libc/gen/ptree.c
new file mode 100644 (file)
index 0000000..1a2b940
--- /dev/null
@@ -0,0 +1,1202 @@
+/* $NetBSD: ptree.c,v 1.5 2009/06/07 03:12:40 yamt Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+#define _PT_PRIVATE
+
+#if defined(PTCHECK) && !defined(PTDEBUG)
+#define PTDEBUG
+#endif
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/systm.h>
+#include <lib/libkern/libkern.h>
+__KERNEL_RCSID(0, "$NetBSD: ptree.c,v 1.5 2009/06/07 03:12:40 yamt Exp $");
+#else
+#include <stddef.h>
+#include <stdint.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <string.h>
+#ifdef PTDEBUG
+#include <assert.h>
+#define        KASSERT(e)      assert(e)
+#else
+#define        KASSERT(e)      do { } while (/*CONSTCOND*/ 0)
+#endif
+__RCSID("$NetBSD: ptree.c,v 1.5 2009/06/07 03:12:40 yamt Exp $");
+#endif /* _KERNEL || _STANDALONE */
+
+#ifdef _LIBC
+#include "namespace.h"
+#endif
+
+#ifdef PTTEST
+#include "ptree.h"
+#else
+#include <sys/ptree.h>
+#endif
+
+/*
+ * This is an implementation of a radix / PATRICIA tree.  As in a traditional 
+ * patricia tree, all the data is at the leaves of the tree.  An N-value
+ * tree would have N leaves, N-1 branching nodes, and a root pointer.  Each
+ * branching node would have left(0) and right(1) pointers that either point
+ * to another branching node or a leaf node.  The root pointer would also
+ * point to either the first branching node or a leaf node.  Leaf nodes
+ * have no need for pointers.
+ *
+ * However, allocation for these branching nodes is problematic since the
+ * allocation could fail.  This would cause insertions to fail for reasons  
+ * beyond the users control.  So to prevent this, in this implementation
+ * each node has two identities: its leaf identity and its branch identity.
+ * Each is separate from the other.  Every branch is tagged as to whether
+ * it points to a leaf or a branch.  This is not an attribute of the object
+ * but of the pointer to the object.  The low bit of the pointer is used as
+ * the tag to determine whether it points to a leaf or branch identity, with
+ * branch identities having the low bit set.
+ * 
+ * A node's branch identity has one rule: when traversing the tree from the
+ * root to the node's leaf identity, one of the branches traversed will be via
+ * the node's branch identity.  Of course, that has an exception: since to
+ * store N leaves, you need N-1 branches.  That one node whose branch identity
+ * isn't used is stored as "oddman"-out in the root.
+ *
+ * Branching nodes also has a bit offset and a bit length which determines
+ * which branch slot is used.  The bit length can be zero resulting in a
+ * one-way branch.  This is happens in two special cases: the root and
+ * interior mask nodes.
+ *
+ * To support longest match first lookups, when a mask node (one that only
+ * match the first N bits) has children who first N bits match the mask nodes,
+ * that mask node is converted from being a leaf node to being a one-way
+ * branch-node.  The mask becomes fixed in position in the tree.  The mask
+ * will always be the longest mask match for its descendants (unless they
+ * traverse an even longer match).
+ */
+
+#define        NODETOITEM(pt, ptn)     \
+       ((void *)((uintptr_t)(ptn) - (pt)->pt_node_offset))
+#define        NODETOKEY(pt, ptn)      \
+       ((void *)((uintptr_t)(ptn) - (pt)->pt_node_offset + pt->pt_key_offset))
+#define        ITEMTONODE(pt, ptn)     \
+       ((pt_node_t *)((uintptr_t)(ptn) + (pt)->pt_node_offset))
+
+bool ptree_check(const pt_tree_t *);
+#if PTCHECK > 1
+#define        PTREE_CHECK(pt)         ptree_check(pt)
+#else
+#define        PTREE_CHECK(pt)         do { } while (/*CONSTCOND*/ 0)
+#endif
+
+static inline bool
+ptree_matchnode(const pt_tree_t *pt, const pt_node_t *target,
+       const pt_node_t *ptn, pt_bitoff_t max_bitoff,
+       pt_bitoff_t *bitoff_p, pt_slot_t *slots_p)
+{
+       return (*pt->pt_ops->ptto_matchnode)(NODETOKEY(pt, target),
+           (ptn != NULL ? NODETOKEY(pt, ptn) : NULL), max_bitoff,
+           bitoff_p, slots_p);
+}
+
+static inline pt_slot_t
+ptree_testnode(const pt_tree_t *pt, const pt_node_t *target,
+       const pt_node_t *ptn)
+{
+       const pt_bitlen_t bitlen = PTN_BRANCH_BITLEN(ptn);
+       if (bitlen == 0)
+               return PT_SLOT_ROOT;
+       return (*pt->pt_ops->ptto_testnode)(NODETOKEY(pt, target),
+            PTN_BRANCH_BITOFF(ptn),
+            bitlen);
+}
+
+static inline bool
+ptree_matchkey(const pt_tree_t *pt, const void *key,
+       const pt_node_t *ptn, pt_bitoff_t bitoff, pt_bitlen_t bitlen)
+{
+       return (*pt->pt_ops->ptto_matchkey)(key, NODETOKEY(pt, ptn),
+           bitoff, bitlen);
+}
+
+static inline pt_slot_t
+ptree_testkey(const pt_tree_t *pt, const void *key, const pt_node_t *ptn)
+{
+       return (*pt->pt_ops->ptto_testkey)(key,
+           PTN_BRANCH_BITOFF(ptn),
+           PTN_BRANCH_BITLEN(ptn));
+}
+
+static inline void
+ptree_set_position(uintptr_t node, pt_slot_t position)
+{
+       if (PT_LEAF_P(node))
+               PTN_SET_LEAF_POSITION(PT_NODE(node), position);
+       else
+               PTN_SET_BRANCH_POSITION(PT_NODE(node), position);
+}
+
+void
+ptree_init(pt_tree_t *pt, const pt_tree_ops_t *ops, size_t node_offset,
+       size_t key_offset)
+{
+       memset(pt, 0, sizeof(*pt));
+       pt->pt_node_offset = node_offset;
+       pt->pt_key_offset = key_offset;
+       pt->pt_ops = ops;
+}
+
+typedef struct {
+       uintptr_t *id_insertp;
+       pt_node_t *id_parent;
+       uintptr_t id_node;
+       pt_slot_t id_parent_slot;
+       pt_bitoff_t id_bitoff;
+       pt_slot_t id_slot;
+} pt_insertdata_t;
+
+typedef bool (*pt_insertfunc_t)(pt_tree_t *, pt_node_t *, pt_insertdata_t *);
+
+/*
+ * Move a branch identify from src to dst.  The leaves don't care since 
+ * nothing for them has changed.
+ */
+/*ARGSUSED*/
+static uintptr_t
+ptree_move_branch(pt_tree_t * const pt, pt_node_t * const dst,
+       const pt_node_t * const src)
+{
+       KASSERT(PTN_BRANCH_BITLEN(src) == 1);
+       /* set branch bitlen and bitoff in one step.  */
+       dst->ptn_branchdata = src->ptn_branchdata;
+       PTN_SET_BRANCH_POSITION(dst, PTN_BRANCH_POSITION(src));
+       PTN_COPY_BRANCH_SLOTS(dst, src);
+       return PTN_BRANCH(dst);
+}
+
+#ifndef PTNOMASK
+static inline uintptr_t *
+ptree_find_branch(pt_tree_t * const pt, uintptr_t branch_node)
+{
+       pt_node_t * const branch = PT_NODE(branch_node);
+       pt_node_t *parent;
+
+       for (parent = &pt->pt_rootnode;;) {
+               uintptr_t *nodep =
+                   &PTN_BRANCH_SLOT(parent, ptree_testnode(pt, branch, parent));
+               if (*nodep == branch_node)
+                       return nodep;
+               if (PT_LEAF_P(*nodep))
+                       return NULL;
+               parent = PT_NODE(*nodep);
+       }
+}
+
+static bool
+ptree_insert_leaf_after_mask(pt_tree_t * const pt, pt_node_t * const target,
+       pt_insertdata_t * const id)
+{
+       const uintptr_t target_node = PTN_LEAF(target);
+       const uintptr_t mask_node = id->id_node;
+       pt_node_t * const mask = PT_NODE(mask_node);
+       const pt_bitlen_t mask_len = PTN_MASK_BITLEN(mask);
+
+       KASSERT(PT_LEAF_P(mask_node));
+       KASSERT(PTN_LEAF_POSITION(mask) == id->id_parent_slot);
+       KASSERT(mask_len <= id->id_bitoff);
+       KASSERT(PTN_ISMASK_P(mask));
+       KASSERT(!PTN_ISMASK_P(target) || mask_len < PTN_MASK_BITLEN(target));
+
+       if (mask_node == PTN_BRANCH_ODDMAN_SLOT(&pt->pt_rootnode)) {
+               KASSERT(id->id_parent != mask);
+               /*
+                * Nice, mask was an oddman.  So just set the oddman to target.
+                */
+               PTN_BRANCH_ODDMAN_SLOT(&pt->pt_rootnode) = target_node;
+       } else {
+               /*
+                * We need to find out who's pointing to mask's branch
+                * identity.  We know that between root and the leaf identity,
+                * we must traverse the node's branch identity.
+                */
+               uintptr_t * const mask_nodep = ptree_find_branch(pt, PTN_BRANCH(mask));
+               KASSERT(mask_nodep != NULL);
+               KASSERT(*mask_nodep == PTN_BRANCH(mask));
+               KASSERT(PTN_BRANCH_BITLEN(mask) == 1);
+
+               /*
+                * Alas, mask was used as a branch.  Since the mask is becoming
+                * a one-way branch, we need make target take over mask's
+                * branching responsibilities.  Only then can we change it.
+                */
+               *mask_nodep = ptree_move_branch(pt, target, mask);
+
+               /*
+                * However, it's possible that mask's parent is itself.  If
+                * that's true, update the insert point to use target since it
+                * has taken over mask's branching duties.
+                */
+               if (id->id_parent == mask)
+                       id->id_insertp = &PTN_BRANCH_SLOT(target,
+                           id->id_parent_slot);
+       }
+
+       PTN_SET_BRANCH_BITLEN(mask, 0);
+       PTN_SET_BRANCH_BITOFF(mask, mask_len);
+
+       PTN_BRANCH_ROOT_SLOT(mask) = target_node;
+       PTN_BRANCH_ODDMAN_SLOT(mask) = PT_NULL;
+       PTN_SET_LEAF_POSITION(target, PT_SLOT_ROOT);
+       PTN_SET_BRANCH_POSITION(mask, id->id_parent_slot);
+
+       /*
+        * Now that everything is done, to make target visible we need to
+        * change mask from a leaf to a branch.
+        */
+       *id->id_insertp = PTN_BRANCH(mask);
+       PTREE_CHECK(pt);
+       return true;
+}
+
+/*ARGSUSED*/
+static bool
+ptree_insert_mask_before_node(pt_tree_t * const pt, pt_node_t * const target,
+       pt_insertdata_t * const id)
+{
+       const uintptr_t node = id->id_node;
+       pt_node_t * const ptn = PT_NODE(node);
+       const pt_slot_t mask_len = PTN_MASK_BITLEN(target);
+       const pt_bitlen_t node_mask_len = PTN_MASK_BITLEN(ptn);
+
+       KASSERT(PT_LEAF_P(node) || id->id_parent_slot == PTN_BRANCH_POSITION(ptn));
+       KASSERT(PT_BRANCH_P(node) || id->id_parent_slot == PTN_LEAF_POSITION(ptn));
+       KASSERT(PTN_ISMASK_P(target));
+
+       /*
+        * If the node we are placing ourself in front is a mask with the
+        * same mask length as us, return failure.
+        */
+       if (PTN_ISMASK_P(ptn) && node_mask_len == mask_len)
+               return false;
+
+       PTN_SET_BRANCH_BITLEN(target, 0);
+       PTN_SET_BRANCH_BITOFF(target, mask_len);
+
+       PTN_BRANCH_SLOT(target, PT_SLOT_ROOT) = node;
+       *id->id_insertp = PTN_BRANCH(target);
+
+       PTN_SET_BRANCH_POSITION(target, id->id_parent_slot);
+       ptree_set_position(node, PT_SLOT_ROOT);
+
+       PTREE_CHECK(pt);
+       return true;
+}
+#endif /* !PTNOMASK */
+
+/*ARGSUSED*/
+static bool
+ptree_insert_branch_at_node(pt_tree_t * const pt, pt_node_t * const target,
+       pt_insertdata_t * const id)
+{
+       const uintptr_t target_node = PTN_LEAF(target);
+       const uintptr_t node = id->id_node;
+       const pt_slot_t other_slot = id->id_slot ^ PT_SLOT_OTHER;
+
+       KASSERT(PT_BRANCH_P(node) || id->id_parent_slot == PTN_LEAF_POSITION(PT_NODE(node)));
+       KASSERT(PT_LEAF_P(node) || id->id_parent_slot == PTN_BRANCH_POSITION(PT_NODE(node)));
+       KASSERT((node == pt->pt_root) == (id->id_parent == &pt->pt_rootnode));
+#ifndef PTNOMASK
+       KASSERT(!PTN_ISMASK_P(target) || id->id_bitoff <= PTN_MASK_BITLEN(target));
+#endif
+       KASSERT(node == pt->pt_root || PTN_BRANCH_BITOFF(id->id_parent) + PTN_BRANCH_BITLEN(id->id_parent) <= id->id_bitoff);
+
+       PTN_SET_BRANCH_BITOFF(target, id->id_bitoff);
+       PTN_SET_BRANCH_BITLEN(target, 1);
+
+       PTN_BRANCH_SLOT(target, id->id_slot) = target_node;
+       PTN_BRANCH_SLOT(target, other_slot) = node;
+       *id->id_insertp = PTN_BRANCH(target);
+
+       PTN_SET_LEAF_POSITION(target, id->id_slot);
+       ptree_set_position(node, other_slot);
+
+       PTN_SET_BRANCH_POSITION(target, id->id_parent_slot);
+       PTREE_CHECK(pt);
+       return true;
+}
+
+static bool
+ptree_insert_leaf(pt_tree_t * const pt, pt_node_t * const target,
+       pt_insertdata_t * const id)
+{
+       const uintptr_t leaf_node = id->id_node;
+       pt_node_t * const leaf = PT_NODE(leaf_node);
+#ifdef PTNOMASK
+       const bool inserting_mask = false;
+       const bool at_mask = false;
+#else
+       const bool inserting_mask = PTN_ISMASK_P(target);
+       const bool at_mask = PTN_ISMASK_P(leaf);
+       const pt_bitlen_t leaf_masklen = PTN_MASK_BITLEN(leaf);
+       const pt_bitlen_t target_masklen = PTN_MASK_BITLEN(target);
+#endif
+       pt_insertfunc_t insertfunc = ptree_insert_branch_at_node;
+       bool matched;
+
+       /*
+        * In all likelyhood we are going simply going to insert a branch
+        * where this leaf is which will point to the old and new leaves.
+        */
+       KASSERT(PT_LEAF_P(leaf_node));
+       KASSERT(PTN_LEAF_POSITION(leaf) == id->id_parent_slot);
+       matched = ptree_matchnode(pt, target, leaf, UINT_MAX,
+           &id->id_bitoff, &id->id_slot);
+       if (__predict_false(!inserting_mask)) {
+               /*
+                * We aren't inserting a mask nor is the leaf a mask, which
+                * means we are trying to insert a duplicate leaf.  Can't do
+                * that.
+                */
+               if (!at_mask && matched)
+                       return false;
+
+#ifndef PTNOMASK
+               /*
+                * We are at a mask and the leaf we are about to insert
+                * is at or beyond the mask, we need to convert the mask
+                * from a leaf to a one-way branch interior mask.
+                */
+               if (at_mask && id->id_bitoff >= leaf_masklen)
+                       insertfunc = ptree_insert_leaf_after_mask;
+#endif /* PTNOMASK */
+       }
+#ifndef PTNOMASK
+       else {
+               /*
+                * We are inserting a mask.
+                */
+               if (matched) {
+                       /*
+                        * If the leaf isn't a mask, we obviously have to
+                        * insert the new mask before non-mask leaf.  If the
+                        * leaf is a mask, and the new node has a LEQ mask
+                        * length it too needs to inserted before leaf (*).
+                        *
+                        * In other cases, we place the new mask as leaf after
+                        * leaf mask.  Which mask comes first will be a one-way
+                        * branch interior mask node which has the other mask
+                        * node as a child.
+                        *
+                        * (*) ptree_insert_mask_before_node can detect a
+                        * duplicate mask and return failure if needed.
+                        */
+                       if (!at_mask || target_masklen <= leaf_masklen)
+                               insertfunc = ptree_insert_mask_before_node;
+                       else
+                               insertfunc = ptree_insert_leaf_after_mask;
+               } else if (at_mask && id->id_bitoff >= leaf_masklen) {
+                       /*
+                        * If the new mask has a bit offset GEQ than the leaf's
+                        * mask length, convert the left to a one-way branch
+                        * interior mask and make that point to the new [leaf]
+                        * mask.
+                        */
+                       insertfunc = ptree_insert_leaf_after_mask;
+               } else {
+                       /*
+                        * The new mask has a bit offset less than the leaf's
+                        * mask length or if the leaf isn't a mask at all, the
+                        * new mask deserves to be its own leaf so we use the
+                        * default insertfunc to do that.
+                        */
+               }
+       }
+#endif /* PTNOMASK */
+
+       return (*insertfunc)(pt, target, id);
+}
+
+static bool
+ptree_insert_node_common(pt_tree_t *pt, void *item)
+{
+       pt_node_t * const target = ITEMTONODE(pt, item);
+#ifndef PTNOMASK
+       const bool inserting_mask = PTN_ISMASK_P(target);
+       const pt_bitlen_t target_masklen = PTN_MASK_BITLEN(target);
+#endif
+       pt_insertfunc_t insertfunc;
+       pt_insertdata_t id;
+
+       /*
+        * We need a leaf so we can match against.  Until we get a leaf
+        * we having nothing to test against.
+        */
+       if (__predict_false(PT_NULL_P(pt->pt_root))) {
+               PTN_BRANCH_ROOT_SLOT(&pt->pt_rootnode) = PTN_LEAF(target);
+               PTN_BRANCH_ODDMAN_SLOT(&pt->pt_rootnode) = PTN_LEAF(target);
+               PTN_SET_LEAF_POSITION(target, PT_SLOT_ROOT);
+               PTREE_CHECK(pt);
+               return true;
+       }
+
+       id.id_bitoff = 0;
+       id.id_parent = &pt->pt_rootnode;
+       id.id_parent_slot = PT_SLOT_ROOT;
+       id.id_insertp = &PTN_BRANCH_ROOT_SLOT(id.id_parent);
+       for (;;) {
+               pt_bitoff_t branch_bitoff;
+               pt_node_t * const ptn = PT_NODE(*id.id_insertp);
+               id.id_node = *id.id_insertp;
+
+               /*
+                * If we hit a leaf, try to insert target at leaf.  We could
+                * have inlined ptree_insert_leaf here but that would have
+                * made this routine much harder to understand.  Trust the
+                * compiler to optimize this properly.
+                */
+               if (PT_LEAF_P(id.id_node)) {
+                       KASSERT(PTN_LEAF_POSITION(ptn) == id.id_parent_slot);
+                       insertfunc = ptree_insert_leaf;
+                       break;
+               }
+
+               /*
+                * If we aren't a leaf, we must be a branch.  Make sure we are
+                * in the slot we think we are.
+                */
+               KASSERT(PT_BRANCH_P(id.id_node));
+               KASSERT(PTN_BRANCH_POSITION(ptn) == id.id_parent_slot);
+
+               /*
+                * Where is this branch?
+                */
+               branch_bitoff = PTN_BRANCH_BITOFF(ptn);
+
+#ifndef PTNOMASK
+               /*
+                * If this is a one-way mask node, its offset must equal
+                * its mask's bitlen.
+                */
+               KASSERT(!(PTN_ISMASK_P(ptn) && PTN_BRANCH_BITLEN(ptn) == 0) || PTN_MASK_BITLEN(ptn) == branch_bitoff);
+
+               /*
+                * If we are inserting a mask, and we know that at this point
+                * all bits before the current bit offset match both the target
+                * and the branch.  If the target's mask length is LEQ than
+                * this branch's bit offset, then this is where the mask needs
+                * to added to the tree.
+                */
+               if (__predict_false(inserting_mask)
+                   && (PTN_ISROOT_P(pt, id.id_parent)
+                       || id.id_bitoff < target_masklen)
+                   && target_masklen <= branch_bitoff) {
+                       /*
+                        * We don't know about the bits (if any) between
+                        * id.id_bitoff and the target's mask length match
+                        * both the target and the branch.  If the target's
+                        * mask length is greater than the current bit offset
+                        * make sure the untested bits match both the target
+                        * and the branch.
+                        */
+                       if (target_masklen == id.id_bitoff
+                           || ptree_matchnode(pt, target, ptn, target_masklen,
+                                   &id.id_bitoff, &id.id_slot)) {
+                               /*
+                                * The bits matched, so insert the mask as a
+                                * one-way branch.
+                                */
+                               insertfunc = ptree_insert_mask_before_node;
+                               break;
+                       } else if (id.id_bitoff < branch_bitoff) {
+                               /*
+                                * They didn't match, so create a normal branch
+                                * because this mask needs to a be a new leaf.
+                                */
+                               insertfunc = ptree_insert_branch_at_node;
+                               break;
+                       }
+               }
+#endif /* PTNOMASK */
+
+               /*
+                * If we are skipping some bits, verify they match the node.
+                * If they don't match, it means we have a leaf to insert.
+                * Note that if we are advancing bit by bit, we'll skip
+                * doing matchnode and walk the tree bit by bit via testnode.
+                */
+               if (id.id_bitoff < branch_bitoff
+                   && !ptree_matchnode(pt, target, ptn, branch_bitoff,
+                                       &id.id_bitoff, &id.id_slot)) {
+                       KASSERT(id.id_bitoff < branch_bitoff);
+                       insertfunc = ptree_insert_branch_at_node;
+                       break;
+               }
+
+               /*
+                * At this point, all bits before branch_bitoff are known
+                * to match the target.
+                */
+               KASSERT(id.id_bitoff >= branch_bitoff);
+
+               /*
+                * Decend the tree one level.
+                */
+               id.id_parent = ptn;
+               id.id_parent_slot = ptree_testnode(pt, target, id.id_parent);
+               id.id_bitoff += PTN_BRANCH_BITLEN(id.id_parent);
+               id.id_insertp = &PTN_BRANCH_SLOT(id.id_parent, id.id_parent_slot);
+       }
+
+       /*
+        * Do the actual insertion.
+        */
+       return (*insertfunc)(pt, target, &id);
+}
+
+bool
+ptree_insert_node(pt_tree_t *pt, void *item)
+{
+       pt_node_t * const target = ITEMTONODE(pt, item);
+
+       memset(target, 0, sizeof(*target));
+       return ptree_insert_node_common(pt, target);
+}
+
+#ifndef PTNOMASK
+bool
+ptree_insert_mask_node(pt_tree_t *pt, void *item, pt_bitlen_t mask_len)
+{
+       pt_node_t * const target = ITEMTONODE(pt, item);
+       pt_bitoff_t bitoff = mask_len;
+       pt_slot_t slot;
+
+       memset(target, 0, sizeof(*target));
+       KASSERT(mask_len == 0 || (~PT__MASK(PTN_MASK_BITLEN) & mask_len) == 0);
+       /*
+        * Only the first <mask_len> bits can be non-zero.
+        * All other bits must be 0.
+        */
+       if (!ptree_matchnode(pt, target, NULL, UINT_MAX, &bitoff, &slot))
+               return false;
+       PTN_SET_MASK_BITLEN(target, mask_len);
+       PTN_MARK_MASK(target);
+       return ptree_insert_node_common(pt, target);
+}
+#endif /* !PTNOMASH */
+
+void *
+ptree_find_filtered_node(pt_tree_t *pt, void *key, pt_filter_t filter,
+       void *filter_arg)
+{
+#ifndef PTNOMASK
+       pt_node_t *mask = NULL;
+#endif
+       bool at_mask = false;
+       pt_node_t *ptn, *parent;
+       pt_bitoff_t bitoff;
+       pt_slot_t parent_slot;
+
+       if (PT_NULL_P(PTN_BRANCH_ROOT_SLOT(&pt->pt_rootnode)))
+               return NULL;
+
+       bitoff = 0;
+       parent = &pt->pt_rootnode;
+       parent_slot = PT_SLOT_ROOT;
+       for (;;) {
+               const uintptr_t node = PTN_BRANCH_SLOT(parent, parent_slot);
+               const pt_slot_t branch_bitoff = PTN_BRANCH_BITOFF(PT_NODE(node));
+               ptn = PT_NODE(node);
+
+               if (PT_LEAF_P(node)) {
+#ifndef PTNOMASK
+                       at_mask = PTN_ISMASK_P(ptn);
+#endif
+                       break;
+               }
+
+               if (bitoff < branch_bitoff) {
+                       if (!ptree_matchkey(pt, key, ptn, bitoff, branch_bitoff - bitoff)) {
+#ifndef PTNOMASK
+                               if (mask != NULL)
+                                       return NODETOITEM(pt, mask);
+#endif
+                               return NULL;
+                       }
+                       bitoff = branch_bitoff;
+               }
+
+#ifndef PTNOMASK
+               if (PTN_ISMASK_P(ptn) && PTN_BRANCH_BITLEN(ptn) == 0
+                   && (!filter
+                       || (*filter)(filter_arg, NODETOITEM(pt, ptn),
+                                    PT_FILTER_MASK)))
+                       mask = ptn;
+#endif
+
+               parent = ptn;
+               parent_slot = ptree_testkey(pt, key, parent);
+               bitoff += PTN_BRANCH_BITLEN(parent);
+       }
+
+       KASSERT(PTN_ISROOT_P(pt, parent) || PTN_BRANCH_BITOFF(parent) + PTN_BRANCH_BITLEN(parent) == bitoff);
+       if (!filter || (*filter)(filter_arg, NODETOITEM(pt, ptn), at_mask ? PT_FILTER_MASK : 0)) {
+#ifndef PTNOMASK
+               if (PTN_ISMASK_P(ptn)) {
+                       const pt_bitlen_t mask_len = PTN_MASK_BITLEN(ptn);
+                       if (bitoff == PTN_MASK_BITLEN(ptn))
+                               return NODETOITEM(pt, ptn);
+                       if (ptree_matchkey(pt, key, ptn, bitoff, mask_len - bitoff))
+                               return NODETOITEM(pt, ptn);
+               } else
+#endif /* !PTNOMASK */
+               if (ptree_matchkey(pt, key, ptn, bitoff, UINT_MAX))
+                       return NODETOITEM(pt, ptn);
+       }
+
+#ifndef PTNOMASK
+       /*
+        * By virtue of how the mask was placed in the tree,
+        * all nodes descended from it will match it.  But the bits
+        * before the mask still need to be checked and since the
+        * mask was a branch, that was done implicitly.
+        */
+       if (mask != NULL) {
+               KASSERT(ptree_matchkey(pt, key, mask, 0, PTN_MASK_BITLEN(mask)));
+               return NODETOITEM(pt, mask);
+       }
+#endif /* !PTNOMASK */
+
+       /*
+        * Nothing matched.
+        */
+       return NULL;
+}
+
+void *
+ptree_iterate(pt_tree_t *pt, const void *item, pt_direction_t direction)
+{
+       const pt_node_t * const target = ITEMTONODE(pt, item);
+       uintptr_t node, next_node;
+
+       if (direction != PT_ASCENDING && direction != PT_DESCENDING)
+               return NULL;
+
+       node = PTN_BRANCH_ROOT_SLOT(&pt->pt_rootnode);
+       if (PT_NULL_P(node))
+               return NULL;
+
+       if (item == NULL) {
+               pt_node_t * const ptn = PT_NODE(node);
+               if (direction == PT_ASCENDING
+                   && PTN_ISMASK_P(ptn) && PTN_BRANCH_BITLEN(ptn) == 0)
+                       return NODETOITEM(pt, ptn);
+               next_node = node;
+       } else {
+#ifndef PTNOMASK
+               uintptr_t mask_node = PT_NULL;
+#endif /* !PTNOMASK */
+               next_node = PT_NULL;
+               while (!PT_LEAF_P(node)) { 
+                       pt_node_t * const ptn = PT_NODE(node);
+                       pt_slot_t slot;
+#ifndef PTNOMASK
+                       if (PTN_ISMASK_P(ptn) && PTN_BRANCH_BITLEN(ptn) == 0) {
+                               if (ptn == target)
+                                       break;
+                               if (direction == PT_DESCENDING) {
+                                       mask_node = node;
+                                       next_node = PT_NULL;
+                               }
+                       }
+#endif /* !PTNOMASK */
+                       slot = ptree_testnode(pt, target, ptn);
+                       node = PTN_BRANCH_SLOT(ptn, slot);
+                       if (direction == PT_ASCENDING) {
+                               if (slot != (pt_slot_t)((1 << PTN_BRANCH_BITLEN(ptn)) - 1))
+                                       next_node = PTN_BRANCH_SLOT(ptn, slot + 1);
+                       } else {
+                               if (slot > 0) {
+#ifndef PTNOMASK
+                                       mask_node = PT_NULL;
+#endif /* !PTNOMASK */
+                                       next_node = PTN_BRANCH_SLOT(ptn, slot - 1);
+                               }
+                       }
+               }
+               if (PT_NODE(node) != target)
+                       return NULL;
+#ifndef PTNOMASK
+               if (PT_BRANCH_P(node)) {
+                       pt_node_t *ptn = PT_NODE(node);
+                       KASSERT(PTN_ISMASK_P(PT_NODE(node)) && PTN_BRANCH_BITLEN(PT_NODE(node)) == 0);
+                       if (direction == PT_ASCENDING) {
+                               next_node = PTN_BRANCH_ROOT_SLOT(ptn);
+                               ptn = PT_NODE(next_node);
+                       }
+               }
+               /*
+                * When descending, if we countered a mask node then that's
+                * we want to return.
+                */
+               if (direction == PT_DESCENDING && !PT_NULL_P(mask_node)) {
+                       KASSERT(PT_NULL_P(next_node));
+                       return NODETOITEM(pt, PT_NODE(mask_node));
+               }
+#endif /* !PTNOMASK */
+       }
+
+       node = next_node;
+       if (PT_NULL_P(node))
+               return NULL;
+
+       while (!PT_LEAF_P(node)) {
+               pt_node_t * const ptn = PT_NODE(node);
+               pt_slot_t slot;
+               if (direction == PT_ASCENDING) {
+#ifndef PTNOMASK
+                       if (PT_BRANCH_P(node)
+                           && PTN_ISMASK_P(ptn)
+                           && PTN_BRANCH_BITLEN(ptn) == 0)
+                               return NODETOITEM(pt, ptn);
+#endif /* !PTNOMASK */
+                       slot = PT_SLOT_LEFT;
+               } else {
+                       slot = (1 << PTN_BRANCH_BITLEN(ptn)) - 1;
+               }
+               node = PTN_BRANCH_SLOT(ptn, slot);
+       }
+       return NODETOITEM(pt, PT_NODE(node));
+}
+
+void
+ptree_remove_node(pt_tree_t *pt, void *item)
+{
+       pt_node_t * const target = ITEMTONODE(pt, item);
+       const pt_slot_t leaf_slot = PTN_LEAF_POSITION(target);
+       const pt_slot_t branch_slot = PTN_BRANCH_POSITION(target);
+       pt_node_t *ptn, *parent;
+       uintptr_t node;
+       uintptr_t *removep;
+       uintptr_t *nodep;
+       pt_bitoff_t bitoff;
+       pt_slot_t parent_slot;
+#ifndef PTNOMASK
+       bool at_mask;
+#endif
+
+       if (PT_NULL_P(PTN_BRANCH_ROOT_SLOT(&pt->pt_rootnode))) {
+               KASSERT(!PT_NULL_P(PTN_BRANCH_ROOT_SLOT(&pt->pt_rootnode)));
+               return;
+       }
+
+       bitoff = 0;
+       removep = NULL;
+       nodep = NULL;
+       parent = &pt->pt_rootnode;
+       parent_slot = PT_SLOT_ROOT;
+       for (;;) {
+               node = PTN_BRANCH_SLOT(parent, parent_slot);
+               ptn = PT_NODE(node);
+#ifndef PTNOMASK
+               at_mask = PTN_ISMASK_P(ptn);
+#endif
+
+               if (PT_LEAF_P(node))
+                       break;
+
+               /*
+                * If we are at the target, then we are looking at its branch
+                * identity.  We need to remember who's pointing at it so we
+                * stop them from doing that.
+                */
+               if (__predict_false(ptn == target)) {
+                       KASSERT(nodep == NULL);
+#ifndef PTNOMASK
+                       /*
+                        * Interior mask nodes are trivial to get rid of.
+                        */
+                       if (at_mask && PTN_BRANCH_BITLEN(ptn) == 0) {
+                               PTN_BRANCH_SLOT(parent, parent_slot) =
+                                   PTN_BRANCH_ROOT_SLOT(ptn);
+                               KASSERT(PT_NULL_P(PTN_BRANCH_ODDMAN_SLOT(ptn)));
+                               PTREE_CHECK(pt);
+                               return;
+                       }
+#endif /* !PTNOMASK */
+                       nodep = &PTN_BRANCH_SLOT(parent, parent_slot);
+                       KASSERT(*nodep == PTN_BRANCH(target));
+               }
+               /*
+                * We need also need to know who's pointing at our parent.
+                * After we remove ourselves from our parent, he'll only
+                * have one child and that's unacceptable.  So we replace
+                * the pointer to the parent with our abadoned sibling.
+                */
+               removep = &PTN_BRANCH_SLOT(parent, parent_slot);
+
+               /*
+                * Descend into the tree.
+                */
+               parent = ptn;
+               parent_slot = ptree_testnode(pt, target, parent);
+               bitoff += PTN_BRANCH_BITLEN(parent);
+       }
+
+       /*
+        * We better have found that the leaf we are looking for is target.
+        */
+       if (target != ptn) {
+               KASSERT(target == ptn);
+               return;
+       }
+
+       /*
+        * If we didn't encounter target as branch, then target must be the
+        * oddman-out.
+        */
+       if (nodep == NULL) {
+               KASSERT(PTN_BRANCH_ODDMAN_SLOT(&pt->pt_rootnode) == PTN_LEAF(target));
+               KASSERT(nodep == NULL);
+               nodep = &PTN_BRANCH_ODDMAN_SLOT(&pt->pt_rootnode);
+       }
+
+       KASSERT((removep == NULL) == (parent == &pt->pt_rootnode));
+
+       /*
+        * We have to special remove the last leaf from the root since
+        * the only time the tree can a PT_NULL node is when it's empty.
+        */
+       if (__predict_false(PTN_ISROOT_P(pt, parent))) {
+               KASSERT(removep == NULL);
+               KASSERT(parent == &pt->pt_rootnode);
+               KASSERT(nodep == &PTN_BRANCH_ODDMAN_SLOT(&pt->pt_rootnode));
+               KASSERT(*nodep == PTN_LEAF(target));
+               PTN_BRANCH_ROOT_SLOT(&pt->pt_rootnode) = PT_NULL;
+               PTN_BRANCH_ODDMAN_SLOT(&pt->pt_rootnode) = PT_NULL;
+               return;
+       }
+
+       KASSERT((parent == target) == (removep == nodep));
+       if (PTN_BRANCH(parent) == PTN_BRANCH_SLOT(target, PTN_BRANCH_POSITION(parent))) {
+               /*
+                * The pointer to the parent actually lives in the target's
+                * branch identity.  We can't just move the target's branch
+                * identity since that would result in the parent pointing
+                * to its own branch identity and that's fobidden.
+                */
+               const pt_slot_t slot = PTN_BRANCH_POSITION(parent);
+               const pt_slot_t other_slot = slot ^ PT_SLOT_OTHER;
+               const pt_bitlen_t parent_bitlen = PTN_BRANCH_BITLEN(parent);
+
+               KASSERT(PTN_BRANCH_BITOFF(target) < PTN_BRANCH_BITOFF(parent));
+
+               /*
+                * This gets so confusing.  The target's branch identity
+                * points to the branch identity of the parent of the target's
+                * leaf identity:
+                *
+                *      TB = { X, PB = { TL, Y } }
+                *   or TB = { X, PB = { TL } }
+                *
+                * So we can't move the target's branch identity to the parent
+                * because that would corrupt the tree.
+                */
+               if (__predict_true(parent_bitlen > 0)) {
+                       /*
+                        * The parent is a two-way branch.  We have to have
+                        * do to this chang in two steps to keep internally
+                        * consistent.  First step is to copy our sibling from
+                        * our parent to where we are pointing to parent's
+                        * branch identiy.  This remove all references to his
+                        * branch identity from the tree.  We then simply make
+                        * the parent assume the target's branching duties.
+                        *
+                        *   TB = { X, PB = { Y, TL } } --> PB = { X, Y }.
+                        *   TB = { X, PB = { TL, Y } } --> PB = { X, Y }.
+                        *   TB = { PB = { Y, TL }, X } --> PB = { Y, X }.
+                        *   TB = { PB = { TL, Y }, X } --> PB = { Y, X }.
+                        */
+                       PTN_BRANCH_SLOT(target, slot) =
+                           PTN_BRANCH_SLOT(parent, parent_slot ^ PT_SLOT_OTHER);
+                       *nodep = ptree_move_branch(pt, parent, target);
+                       PTREE_CHECK(pt);
+                       return;
+               } else {
+                       /*
+                        * If parent was a one-way branch, it must have been
+                        * mask which pointed to a single leaf which we are
+                        * removing.  This means we have to convert the
+                        * parent back to a leaf node.  So in the same
+                        * position that target pointed to parent, we place
+                        * leaf pointer to parent.  In the other position,
+                        * we just put the other node from target.
+                        *
+                        *   TB = { X, PB = { TL } } --> PB = { X, PL }
+                        */
+                       KASSERT(PTN_ISMASK_P(parent));
+                       KASSERT(slot == ptree_testnode(pt, parent, target));
+                       PTN_BRANCH_SLOT(parent, slot) = PTN_LEAF(parent);
+                       PTN_BRANCH_SLOT(parent, other_slot) =
+                          PTN_BRANCH_SLOT(target, other_slot);
+                       PTN_SET_LEAF_POSITION(parent,slot);
+                       PTN_SET_BRANCH_BITLEN(parent, 1);
+               }
+               PTN_SET_BRANCH_BITOFF(parent, PTN_BRANCH_BITOFF(target));
+               PTN_SET_BRANCH_POSITION(parent, PTN_BRANCH_POSITION(target));
+
+               *nodep = PTN_BRANCH(parent);
+               PTREE_CHECK(pt);
+               return;
+       }
+
+#ifndef PTNOMASK
+       if (__predict_false(PTN_BRANCH_BITLEN(parent) == 0)) {
+               /*
+                * Parent was a one-way branch which is changing back to a leaf.
+                * Since parent is no longer a one-way branch, it can take over
+                * target's branching duties.
+                *
+                *  GB = { PB = { TL } }        --> GB = { PL }
+                *  TB = { X, Y }               --> PB = { X, Y }
+                */
+               KASSERT(PTN_ISMASK_P(parent));
+               KASSERT(parent != target);
+               *removep = PTN_LEAF(parent);
+       } else
+#endif /* !PTNOMASK */
+       {
+               /*
+                * Now we are the normal removal case.  Since after the
+                * target's leaf identity is removed from the its parent,
+                * that parent will only have one decendent.  So we can
+                * just as easily replace the node that has the parent's
+                * branch identity with the surviving node.  This freeing
+                * parent from its branching duties which means it can
+                * take over target's branching duties.
+                *
+                *  GB = { PB = { X, TL } }     --> GB = { X }
+                *  TB = { V, W }               --> PB = { V, W }
+                */
+               const pt_slot_t other_slot = parent_slot ^ PT_SLOT_OTHER;
+               uintptr_t other_node = PTN_BRANCH_SLOT(parent, other_slot);
+               const pt_slot_t target_slot = (parent == target ? branch_slot : leaf_slot);
+
+               *removep = other_node;
+               
+               ptree_set_position(other_node, target_slot);
+
+               /*
+                * If target's branch identity contained its leaf identity, we
+                * have nothing left to do.  We've already moved 'X' so there
+                * is no longer anything in the target's branch identiy that 
+                * has to be preserved.
+                */
+               if (parent == target) {
+                       /*
+                        *  GB = { TB = { X, TL } }     --> GB = { X }
+                        *  TB = { X, TL }              --> don't care
+                        */
+                       PTREE_CHECK(pt);
+                       return;
+               }
+       }
+
+       /*
+        * If target wasn't used as a branch, then it must have been the
+        * oddman-out of the tree (the one node that doesn't have a branch
+        * identity).  This makes parent the new oddman-out.
+        */
+       if (*nodep == PTN_LEAF(target)) {
+               KASSERT(nodep == &PTN_BRANCH_ODDMAN_SLOT(&pt->pt_rootnode));
+               PTN_BRANCH_ODDMAN_SLOT(&pt->pt_rootnode) = PTN_LEAF(parent);
+               PTREE_CHECK(pt);
+               return;
+       }
+
+       /*
+        * Finally move the target's branching duties to the parent.
+        */
+       KASSERT(PTN_BRANCH_BITOFF(parent) > PTN_BRANCH_BITOFF(target));
+       *nodep = ptree_move_branch(pt, parent, target);
+       PTREE_CHECK(pt);
+}
+
+#ifdef PTCHECK
+static const pt_node_t *
+ptree_check_find_node2(const pt_tree_t *pt, const pt_node_t *parent,
+       uintptr_t target)
+{
+       const pt_bitlen_t slots = 1 << PTN_BRANCH_BITLEN(parent);
+       pt_slot_t slot;
+
+       for (slot = 0; slot < slots; slot++) {
+               const uintptr_t node = PTN_BRANCH_SLOT(parent, slot);
+               if (PTN_BRANCH_SLOT(parent, slot) == node)
+                       return parent;
+       }
+       for (slot = 0; slot < slots; slot++) {
+               const uintptr_t node = PTN_BRANCH_SLOT(parent, slot);
+               const pt_node_t *branch;
+               if (!PT_BRANCH_P(node))
+                       continue;
+               branch = ptree_check_find_node2(pt, PT_NODE(node), target);
+               if (branch != NULL)
+                       return branch;
+       }
+
+       return NULL;
+}
+
+static bool
+ptree_check_leaf(const pt_tree_t *pt, const pt_node_t *parent,
+       const pt_node_t *ptn)
+{
+       const pt_bitoff_t leaf_position = PTN_LEAF_POSITION(ptn);
+       const pt_bitlen_t bitlen = PTN_BRANCH_BITLEN(ptn);
+       const pt_bitlen_t mask_len = PTN_MASK_BITLEN(ptn);
+       const uintptr_t leaf_node = PTN_LEAF(ptn);
+       const bool is_parent_root = (parent == &pt->pt_rootnode);
+       const bool is_mask = PTN_ISMASK_P(ptn);
+       bool ok = true;
+
+       if (is_parent_root) {
+               ok = ok && PTN_BRANCH_ODDMAN_SLOT(parent) == leaf_node;
+               KASSERT(ok);
+               return ok;
+       }
+
+       if (is_mask && PTN_ISMASK_P(parent) && PTN_BRANCH_BITLEN(parent) == 0) {
+               ok = ok && PTN_MASK_BITLEN(parent) < mask_len;
+               KASSERT(ok);
+               ok = ok && PTN_BRANCH_BITOFF(parent) < mask_len;
+               KASSERT(ok);
+       }
+       ok = ok && PTN_BRANCH_SLOT(parent, leaf_position) == leaf_node;
+       KASSERT(ok);
+       ok = ok && leaf_position == ptree_testnode(pt, ptn, parent);
+       KASSERT(ok);
+       if (PTN_BRANCH_ODDMAN_SLOT(&pt->pt_rootnode) != leaf_node) {
+               ok = ok && bitlen > 0;
+               KASSERT(ok);
+               ok = ok && ptn == ptree_check_find_node2(pt, ptn, PTN_LEAF(ptn));
+               KASSERT(ok);
+       }
+       return ok;
+}
+
+static bool
+ptree_check_branch(const pt_tree_t *pt, const pt_node_t *parent,
+       const pt_node_t *ptn)
+{
+       const bool is_parent_root = (parent == &pt->pt_rootnode);
+       const pt_slot_t branch_slot = PTN_BRANCH_POSITION(ptn);
+       const pt_bitoff_t bitoff = PTN_BRANCH_BITOFF(ptn);
+       const pt_bitoff_t bitlen = PTN_BRANCH_BITLEN(ptn);
+       const pt_bitoff_t parent_bitoff = PTN_BRANCH_BITOFF(parent);
+       const pt_bitoff_t parent_bitlen = PTN_BRANCH_BITLEN(parent);
+       const bool is_parent_mask = PTN_ISMASK_P(parent) && parent_bitlen == 0;
+       const bool is_mask = PTN_ISMASK_P(ptn) && bitlen == 0;
+       const pt_bitoff_t parent_mask_len = PTN_MASK_BITLEN(parent);
+       const pt_bitoff_t mask_len = PTN_MASK_BITLEN(ptn);
+       const pt_bitlen_t slots = 1 << bitlen;
+       pt_slot_t slot;
+       bool ok = true;
+
+       ok = ok && PTN_BRANCH_SLOT(parent, branch_slot) == PTN_BRANCH(ptn);
+       KASSERT(ok);
+       ok = ok && branch_slot == ptree_testnode(pt, ptn, parent);
+       KASSERT(ok);
+
+       if (is_mask) {
+               ok = ok && bitoff == mask_len;
+               KASSERT(ok);
+               if (is_parent_mask) {
+                       ok = ok && parent_mask_len < mask_len;
+                       KASSERT(ok);
+                       ok = ok && parent_bitoff < bitoff;
+                       KASSERT(ok);
+               }
+       } else {
+               if (is_parent_mask) {
+                       ok = ok && parent_bitoff <= bitoff;
+               } else if (!is_parent_root) {
+                       ok = ok && parent_bitoff < bitoff;
+               }
+               KASSERT(ok);
+       }
+
+       for (slot = 0; slot < slots; slot++) {
+               const uintptr_t node = PTN_BRANCH_SLOT(ptn, slot);
+               pt_bitoff_t tmp_bitoff = 0;
+               pt_slot_t tmp_slot;
+               ok = ok && node != PTN_BRANCH(ptn);
+               KASSERT(ok);
+               if (bitlen > 0) {
+                       ok = ok && ptree_matchnode(pt, PT_NODE(node), ptn, bitoff, &tmp_bitoff, &tmp_slot);
+                       KASSERT(ok);
+                       tmp_slot = ptree_testnode(pt, PT_NODE(node), ptn);
+                       ok = ok && slot == tmp_slot;
+                       KASSERT(ok);
+               }
+               if (PT_LEAF_P(node))
+                       ok = ok && ptree_check_leaf(pt, ptn, PT_NODE(node));
+               else
+                       ok = ok && ptree_check_branch(pt, ptn, PT_NODE(node));
+       }
+
+       return ok;
+}
+#endif /* PTCHECK */
+
+/*ARGSUSED*/
+bool
+ptree_check(const pt_tree_t *pt)
+{
+       bool ok = true;
+#ifdef PTCHECK
+       const pt_node_t * const parent = &pt->pt_rootnode;
+       const uintptr_t node = pt->pt_root;
+       const pt_node_t * const ptn = PT_NODE(node);
+
+       ok = ok && PTN_BRANCH_BITOFF(parent) == 0;
+       ok = ok && !PTN_ISMASK_P(parent);
+
+       if (PT_NULL_P(node))
+               return ok;
+
+       if (PT_LEAF_P(node))
+               ok = ok && ptree_check_leaf(pt, parent, ptn);
+       else
+               ok = ok && ptree_check_branch(pt, parent, ptn);
+#endif
+       return ok;
+}
diff --git a/common/lib/libc/gen/rb.c b/common/lib/libc/gen/rb.c
new file mode 100644 (file)
index 0000000..a277c28
--- /dev/null
@@ -0,0 +1,1335 @@
+/*     $NetBSD: rb.c,v 1.9 2010/11/17 13:19:32 tron Exp $      */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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(_KERNEL) && !defined(_STANDALONE)
+#include <sys/types.h>
+#include <stddef.h>
+#include <assert.h>
+#include <stdbool.h>
+#ifdef RBDEBUG
+#define        KASSERT(s)      assert(s)
+#else
+#define KASSERT(s)     do { } while (/*CONSTCOND*/ 0)
+#endif
+#else
+#include <lib/libkern/libkern.h>
+#endif
+
+#ifdef _LIBC
+__weak_alias(rb_tree_init, _rb_tree_init)
+__weak_alias(rb_tree_find_node, _rb_tree_find_node)
+__weak_alias(rb_tree_find_node_geq, _rb_tree_find_node_geq)
+__weak_alias(rb_tree_find_node_leq, _rb_tree_find_node_leq)
+__weak_alias(rb_tree_insert_node, _rb_tree_insert_node)
+__weak_alias(rb_tree_remove_node, _rb_tree_remove_node)
+__weak_alias(rb_tree_iterate, _rb_tree_iterate)
+#ifdef RBDEBUG
+__weak_alias(rb_tree_check, _rb_tree_check)
+__weak_alias(rb_tree_depths, _rb_tree_depths)
+#endif
+
+#include "namespace.h"
+#endif
+
+#ifdef RBTEST
+#include "rbtree.h"
+#else
+#include <sys/rbtree.h>
+#endif
+
+static void rb_tree_insert_rebalance(struct rb_tree *, struct rb_node *);
+static void rb_tree_removal_rebalance(struct rb_tree *, struct rb_node *,
+       unsigned int);
+#ifdef RBDEBUG
+static const struct rb_node *rb_tree_iterate_const(const struct rb_tree *,
+       const struct rb_node *, const unsigned int);
+static bool rb_tree_check_node(const struct rb_tree *, const struct rb_node *,
+       const struct rb_node *, bool);
+#else
+#define        rb_tree_check_node(a, b, c, d)  true
+#endif
+
+#define        RB_NODETOITEM(rbto, rbn)        \
+    ((void *)((uintptr_t)(rbn) - (rbto)->rbto_node_offset))
+#define        RB_ITEMTONODE(rbto, rbn)        \
+    ((rb_node_t *)((uintptr_t)(rbn) + (rbto)->rbto_node_offset))
+
+#define        RB_SENTINEL_NODE        NULL
+
+void
+rb_tree_init(struct rb_tree *rbt, const rb_tree_ops_t *ops)
+{
+
+       rbt->rbt_ops = ops;
+       *((const struct rb_node **)&rbt->rbt_root) = RB_SENTINEL_NODE;
+       RB_TAILQ_INIT(&rbt->rbt_nodes);
+#ifndef RBSMALL
+       rbt->rbt_minmax[RB_DIR_LEFT] = rbt->rbt_root;   /* minimum node */
+       rbt->rbt_minmax[RB_DIR_RIGHT] = rbt->rbt_root;  /* maximum node */
+#endif
+#ifdef RBSTATS
+       rbt->rbt_count = 0;
+       rbt->rbt_insertions = 0;
+       rbt->rbt_removals = 0;
+       rbt->rbt_insertion_rebalance_calls = 0;
+       rbt->rbt_insertion_rebalance_passes = 0;
+       rbt->rbt_removal_rebalance_calls = 0;
+       rbt->rbt_removal_rebalance_passes = 0;
+#endif
+}
+
+void *
+rb_tree_find_node(struct rb_tree *rbt, const void *key)
+{
+       const rb_tree_ops_t *rbto = rbt->rbt_ops;
+       rbto_compare_key_fn compare_key = rbto->rbto_compare_key;
+       struct rb_node *parent = rbt->rbt_root;
+
+       while (!RB_SENTINEL_P(parent)) {
+               void *pobj = RB_NODETOITEM(rbto, parent);
+               const signed int diff = (*compare_key)(rbto->rbto_context,
+                   pobj, key);
+               if (diff == 0)
+                       return pobj;
+               parent = parent->rb_nodes[diff < 0];
+       }
+
+       return NULL;
+}
+
+void *
+rb_tree_find_node_geq(struct rb_tree *rbt, const void *key)
+{
+       const rb_tree_ops_t *rbto = rbt->rbt_ops;
+       rbto_compare_key_fn compare_key = rbto->rbto_compare_key;
+       struct rb_node *parent = rbt->rbt_root, *last = NULL;
+
+       while (!RB_SENTINEL_P(parent)) {
+               void *pobj = RB_NODETOITEM(rbto, parent);
+               const signed int diff = (*compare_key)(rbto->rbto_context,
+                   pobj, key);
+               if (diff == 0)
+                       return pobj;
+               if (diff > 0)
+                       last = parent;
+               parent = parent->rb_nodes[diff < 0];
+       }
+
+       return RB_NODETOITEM(rbto, last);
+}
+
+void *
+rb_tree_find_node_leq(struct rb_tree *rbt, const void *key)
+{
+       const rb_tree_ops_t *rbto = rbt->rbt_ops;
+       rbto_compare_key_fn compare_key = rbto->rbto_compare_key;
+       struct rb_node *parent = rbt->rbt_root, *last = NULL;
+
+       while (!RB_SENTINEL_P(parent)) {
+               void *pobj = RB_NODETOITEM(rbto, parent);
+               const signed int diff = (*compare_key)(rbto->rbto_context,
+                   pobj, key);
+               if (diff == 0)
+                       return pobj;
+               if (diff < 0)
+                       last = parent;
+               parent = parent->rb_nodes[diff < 0];
+       }
+
+       return RB_NODETOITEM(rbto, last);
+}
+
+void *
+rb_tree_insert_node(struct rb_tree *rbt, void *object)
+{
+       const rb_tree_ops_t *rbto = rbt->rbt_ops;
+       rbto_compare_nodes_fn compare_nodes = rbto->rbto_compare_nodes;
+       struct rb_node *parent, *tmp, *self = RB_ITEMTONODE(rbto, object);
+       unsigned int position;
+       bool rebalance;
+
+       RBSTAT_INC(rbt->rbt_insertions);
+
+       tmp = rbt->rbt_root;
+       /*
+        * This is a hack.  Because rbt->rbt_root is just a struct rb_node *,
+        * just like rb_node->rb_nodes[RB_DIR_LEFT], we can use this fact to
+        * avoid a lot of tests for root and know that even at root,
+        * updating RB_FATHER(rb_node)->rb_nodes[RB_POSITION(rb_node)] will
+        * update rbt->rbt_root.
+        */
+       parent = (struct rb_node *)(void *)&rbt->rbt_root;
+       position = RB_DIR_LEFT;
+
+       /*
+        * Find out where to place this new leaf.
+        */
+       while (!RB_SENTINEL_P(tmp)) {
+               void *tobj = RB_NODETOITEM(rbto, tmp);
+               const signed int diff = (*compare_nodes)(rbto->rbto_context,
+                   tobj, object);
+               if (__predict_false(diff == 0)) {
+                       /*
+                        * Node already exists; return it.
+                        */
+                       return tobj;
+               }
+               parent = tmp;
+               position = (diff < 0);
+               tmp = parent->rb_nodes[position];
+       }
+
+#ifdef RBDEBUG
+       {
+               struct rb_node *prev = NULL, *next = NULL;
+
+               if (position == RB_DIR_RIGHT)
+                       prev = parent;
+               else if (tmp != rbt->rbt_root)
+                       next = parent;
+
+               /*
+                * Verify our sequential position
+                */
+               KASSERT(prev == NULL || !RB_SENTINEL_P(prev));
+               KASSERT(next == NULL || !RB_SENTINEL_P(next));
+               if (prev != NULL && next == NULL)
+                       next = TAILQ_NEXT(prev, rb_link);
+               if (prev == NULL && next != NULL)
+                       prev = TAILQ_PREV(next, rb_node_qh, rb_link);
+               KASSERT(prev == NULL || !RB_SENTINEL_P(prev));
+               KASSERT(next == NULL || !RB_SENTINEL_P(next));
+               KASSERT(prev == NULL || (*compare_nodes)(rbto->rbto_context,
+                   RB_NODETOITEM(rbto, prev), RB_NODETOITEM(rbto, self)) < 0);
+               KASSERT(next == NULL || (*compare_nodes)(rbto->rbto_context,
+                   RB_NODETOITEM(rbto, self), RB_NODETOITEM(rbto, next)) < 0);
+       }
+#endif
+
+       /*
+        * Initialize the node and insert as a leaf into the tree.
+        */
+       RB_SET_FATHER(self, parent);
+       RB_SET_POSITION(self, position);
+       if (__predict_false(parent == (struct rb_node *)(void *)&rbt->rbt_root)) {
+               RB_MARK_BLACK(self);            /* root is always black */
+#ifndef RBSMALL
+               rbt->rbt_minmax[RB_DIR_LEFT] = self;
+               rbt->rbt_minmax[RB_DIR_RIGHT] = self;
+#endif
+               rebalance = false;
+       } else {
+               KASSERT(position == RB_DIR_LEFT || position == RB_DIR_RIGHT);
+#ifndef RBSMALL
+               /*
+                * Keep track of the minimum and maximum nodes.  If our
+                * parent is a minmax node and we on their min/max side,
+                * we must be the new min/max node.
+                */
+               if (parent == rbt->rbt_minmax[position])
+                       rbt->rbt_minmax[position] = self;
+#endif /* !RBSMALL */
+               /*
+                * All new nodes are colored red.  We only need to rebalance
+                * if our parent is also red.
+                */
+               RB_MARK_RED(self);
+               rebalance = RB_RED_P(parent);
+       }
+       KASSERT(RB_SENTINEL_P(parent->rb_nodes[position]));
+       self->rb_left = parent->rb_nodes[position];
+       self->rb_right = parent->rb_nodes[position];
+       parent->rb_nodes[position] = self;
+       KASSERT(RB_CHILDLESS_P(self));
+
+       /*
+        * Insert the new node into a sorted list for easy sequential access
+        */
+       RBSTAT_INC(rbt->rbt_count);
+#ifdef RBDEBUG
+       if (RB_ROOT_P(rbt, self)) {
+               RB_TAILQ_INSERT_HEAD(&rbt->rbt_nodes, self, rb_link);
+       } else if (position == RB_DIR_LEFT) {
+               KASSERT((*compare_nodes)(rbto->rbto_context,
+                   RB_NODETOITEM(rbto, self),
+                   RB_NODETOITEM(rbto, RB_FATHER(self))) < 0);
+               RB_TAILQ_INSERT_BEFORE(RB_FATHER(self), self, rb_link);
+       } else {
+               KASSERT((*compare_nodes)(rbto->rbto_context,
+                   RB_NODETOITEM(rbto, RB_FATHER(self)),
+                   RB_NODETOITEM(rbto, self)) < 0);
+               RB_TAILQ_INSERT_AFTER(&rbt->rbt_nodes, RB_FATHER(self),
+                   self, rb_link);
+       }
+#endif
+       KASSERT(rb_tree_check_node(rbt, self, NULL, !rebalance));
+
+       /*
+        * Rebalance tree after insertion
+        */
+       if (rebalance) {
+               rb_tree_insert_rebalance(rbt, self);
+               KASSERT(rb_tree_check_node(rbt, self, NULL, true));
+       }
+
+       /* Succesfully inserted, return our node pointer. */
+       return object;
+}
+
+/*
+ * Swap the location and colors of 'self' and its child @ which.  The child
+ * can not be a sentinel node.  This is our rotation function.  However,
+ * since it preserves coloring, it great simplifies both insertion and
+ * removal since rotation almost always involves the exchanging of colors
+ * as a separate step.
+ */
+/*ARGSUSED*/
+static void
+rb_tree_reparent_nodes(struct rb_tree *rbt, struct rb_node *old_father,
+       const unsigned int which)
+{
+       const unsigned int other = which ^ RB_DIR_OTHER;
+       struct rb_node * const grandpa = RB_FATHER(old_father);
+       struct rb_node * const old_child = old_father->rb_nodes[which];
+       struct rb_node * const new_father = old_child;
+       struct rb_node * const new_child = old_father;
+
+       KASSERT(which == RB_DIR_LEFT || which == RB_DIR_RIGHT);
+
+       KASSERT(!RB_SENTINEL_P(old_child));
+       KASSERT(RB_FATHER(old_child) == old_father);
+
+       KASSERT(rb_tree_check_node(rbt, old_father, NULL, false));
+       KASSERT(rb_tree_check_node(rbt, old_child, NULL, false));
+       KASSERT(RB_ROOT_P(rbt, old_father) ||
+           rb_tree_check_node(rbt, grandpa, NULL, false));
+
+       /*
+        * Exchange descendant linkages.
+        */
+       grandpa->rb_nodes[RB_POSITION(old_father)] = new_father;
+       new_child->rb_nodes[which] = old_child->rb_nodes[other];
+       new_father->rb_nodes[other] = new_child;
+
+       /*
+        * Update ancestor linkages
+        */
+       RB_SET_FATHER(new_father, grandpa);
+       RB_SET_FATHER(new_child, new_father);
+
+       /*
+        * Exchange properties between new_father and new_child.  The only
+        * change is that new_child's position is now on the other side.
+        */
+#if 0
+       {
+               struct rb_node tmp;
+               tmp.rb_info = 0;
+               RB_COPY_PROPERTIES(&tmp, old_child);
+               RB_COPY_PROPERTIES(new_father, old_father);
+               RB_COPY_PROPERTIES(new_child, &tmp);
+       }
+#else
+       RB_SWAP_PROPERTIES(new_father, new_child);
+#endif
+       RB_SET_POSITION(new_child, other);
+
+       /*
+        * Make sure to reparent the new child to ourself.
+        */
+       if (!RB_SENTINEL_P(new_child->rb_nodes[which])) {
+               RB_SET_FATHER(new_child->rb_nodes[which], new_child);
+               RB_SET_POSITION(new_child->rb_nodes[which], which);
+       }
+
+       KASSERT(rb_tree_check_node(rbt, new_father, NULL, false));
+       KASSERT(rb_tree_check_node(rbt, new_child, NULL, false));
+       KASSERT(RB_ROOT_P(rbt, new_father) ||
+           rb_tree_check_node(rbt, grandpa, NULL, false));
+}
+
+static void
+rb_tree_insert_rebalance(struct rb_tree *rbt, struct rb_node *self)
+{
+       struct rb_node * father = RB_FATHER(self);
+       struct rb_node * grandpa = RB_FATHER(father);
+       struct rb_node * uncle;
+       unsigned int which;
+       unsigned int other;
+
+       KASSERT(!RB_ROOT_P(rbt, self));
+       KASSERT(RB_RED_P(self));
+       KASSERT(RB_RED_P(father));
+       RBSTAT_INC(rbt->rbt_insertion_rebalance_calls);
+
+       for (;;) {
+               KASSERT(!RB_SENTINEL_P(self));
+
+               KASSERT(RB_RED_P(self));
+               KASSERT(RB_RED_P(father));
+               /*
+                * We are red and our parent is red, therefore we must have a
+                * grandfather and he must be black.
+                */
+               grandpa = RB_FATHER(father);
+               KASSERT(RB_BLACK_P(grandpa));
+               KASSERT(RB_DIR_RIGHT == 1 && RB_DIR_LEFT == 0);
+               which = (father == grandpa->rb_right);
+               other = which ^ RB_DIR_OTHER;
+               uncle = grandpa->rb_nodes[other];
+
+               if (RB_BLACK_P(uncle))
+                       break;
+
+               RBSTAT_INC(rbt->rbt_insertion_rebalance_passes);
+               /*
+                * Case 1: our uncle is red
+                *   Simply invert the colors of our parent and
+                *   uncle and make our grandparent red.  And
+                *   then solve the problem up at his level.
+                */
+               RB_MARK_BLACK(uncle);
+               RB_MARK_BLACK(father);
+               if (__predict_false(RB_ROOT_P(rbt, grandpa))) {
+                       /*
+                        * If our grandpa is root, don't bother
+                        * setting him to red, just return.
+                        */
+                       KASSERT(RB_BLACK_P(grandpa));
+                       return;
+               }
+               RB_MARK_RED(grandpa);
+               self = grandpa;
+               father = RB_FATHER(self);
+               KASSERT(RB_RED_P(self));
+               if (RB_BLACK_P(father)) {
+                       /*
+                        * If our greatgrandpa is black, we're done.
+                        */
+                       KASSERT(RB_BLACK_P(rbt->rbt_root));
+                       return;
+               }
+       }
+
+       KASSERT(!RB_ROOT_P(rbt, self));
+       KASSERT(RB_RED_P(self));
+       KASSERT(RB_RED_P(father));
+       KASSERT(RB_BLACK_P(uncle));
+       KASSERT(RB_BLACK_P(grandpa));
+       /*
+        * Case 2&3: our uncle is black.
+        */
+       if (self == father->rb_nodes[other]) {
+               /*
+                * Case 2: we are on the same side as our uncle
+                *   Swap ourselves with our parent so this case
+                *   becomes case 3.  Basically our parent becomes our
+                *   child.
+                */
+               rb_tree_reparent_nodes(rbt, father, other);
+               KASSERT(RB_FATHER(father) == self);
+               KASSERT(self->rb_nodes[which] == father);
+               KASSERT(RB_FATHER(self) == grandpa);
+               self = father;
+               father = RB_FATHER(self);
+       }
+       KASSERT(RB_RED_P(self) && RB_RED_P(father));
+       KASSERT(grandpa->rb_nodes[which] == father);
+       /*
+        * Case 3: we are opposite a child of a black uncle.
+        *   Swap our parent and grandparent.  Since our grandfather
+        *   is black, our father will become black and our new sibling
+        *   (former grandparent) will become red.
+        */
+       rb_tree_reparent_nodes(rbt, grandpa, which);
+       KASSERT(RB_FATHER(self) == father);
+       KASSERT(RB_FATHER(self)->rb_nodes[RB_POSITION(self) ^ RB_DIR_OTHER] == grandpa);
+       KASSERT(RB_RED_P(self));
+       KASSERT(RB_BLACK_P(father));
+       KASSERT(RB_RED_P(grandpa));
+
+       /*
+        * Final step: Set the root to black.
+        */
+       RB_MARK_BLACK(rbt->rbt_root);
+}
+
+static void
+rb_tree_prune_node(struct rb_tree *rbt, struct rb_node *self, bool rebalance)
+{
+       const unsigned int which = RB_POSITION(self);
+       struct rb_node *father = RB_FATHER(self);
+#ifndef RBSMALL
+       const bool was_root = RB_ROOT_P(rbt, self);
+#endif
+
+       KASSERT(rebalance || (RB_ROOT_P(rbt, self) || RB_RED_P(self)));
+       KASSERT(!rebalance || RB_BLACK_P(self));
+       KASSERT(RB_CHILDLESS_P(self));
+       KASSERT(rb_tree_check_node(rbt, self, NULL, false));
+
+       /*
+        * Since we are childless, we know that self->rb_left is pointing
+        * to the sentinel node.
+        */
+       father->rb_nodes[which] = self->rb_left;
+
+       /*
+        * Remove ourselves from the node list, decrement the count,
+        * and update min/max.
+        */
+       RB_TAILQ_REMOVE(&rbt->rbt_nodes, self, rb_link);
+       RBSTAT_DEC(rbt->rbt_count);
+#ifndef RBSMALL
+       if (__predict_false(rbt->rbt_minmax[RB_POSITION(self)] == self)) {
+               rbt->rbt_minmax[RB_POSITION(self)] = father;
+               /*
+                * When removing the root, rbt->rbt_minmax[RB_DIR_LEFT] is
+                * updated automatically, but we also need to update 
+                * rbt->rbt_minmax[RB_DIR_RIGHT];
+                */
+               if (__predict_false(was_root)) {
+                       rbt->rbt_minmax[RB_DIR_RIGHT] = father;
+               }
+       }
+       RB_SET_FATHER(self, NULL);
+#endif
+
+       /*
+        * Rebalance if requested.
+        */
+       if (rebalance)
+               rb_tree_removal_rebalance(rbt, father, which);
+       KASSERT(was_root || rb_tree_check_node(rbt, father, NULL, true));
+}
+
+/*
+ * When deleting an interior node
+ */
+static void
+rb_tree_swap_prune_and_rebalance(struct rb_tree *rbt, struct rb_node *self,
+       struct rb_node *standin)
+{
+       const unsigned int standin_which = RB_POSITION(standin);
+       unsigned int standin_other = standin_which ^ RB_DIR_OTHER;
+       struct rb_node *standin_son;
+       struct rb_node *standin_father = RB_FATHER(standin);
+       bool rebalance = RB_BLACK_P(standin);
+
+       if (standin_father == self) {
+               /*
+                * As a child of self, any childen would be opposite of
+                * our parent.
+                */
+               KASSERT(RB_SENTINEL_P(standin->rb_nodes[standin_other]));
+               standin_son = standin->rb_nodes[standin_which];
+       } else {
+               /*
+                * Since we aren't a child of self, any childen would be
+                * on the same side as our parent.
+                */
+               KASSERT(RB_SENTINEL_P(standin->rb_nodes[standin_which]));
+               standin_son = standin->rb_nodes[standin_other];
+       }
+
+       /*
+        * the node we are removing must have two children.
+        */
+       KASSERT(RB_TWOCHILDREN_P(self));
+       /*
+        * If standin has a child, it must be red.
+        */
+       KASSERT(RB_SENTINEL_P(standin_son) || RB_RED_P(standin_son));
+
+       /*
+        * Verify things are sane.
+        */
+       KASSERT(rb_tree_check_node(rbt, self, NULL, false));
+       KASSERT(rb_tree_check_node(rbt, standin, NULL, false));
+
+       if (__predict_false(RB_RED_P(standin_son))) {
+               /*
+                * We know we have a red child so if we flip it to black
+                * we don't have to rebalance.
+                */
+               KASSERT(rb_tree_check_node(rbt, standin_son, NULL, true));
+               RB_MARK_BLACK(standin_son);
+               rebalance = false;
+
+               if (standin_father == self) {
+                       KASSERT(RB_POSITION(standin_son) == standin_which);
+               } else {
+                       KASSERT(RB_POSITION(standin_son) == standin_other);
+                       /*
+                        * Change the son's parentage to point to his grandpa.
+                        */
+                       RB_SET_FATHER(standin_son, standin_father);
+                       RB_SET_POSITION(standin_son, standin_which);
+               }
+       }
+
+       if (standin_father == self) {
+               /*
+                * If we are about to delete the standin's father, then when
+                * we call rebalance, we need to use ourselves as our father.
+                * Otherwise remember our original father.  Also, sincef we are
+                * our standin's father we only need to reparent the standin's
+                * brother.
+                *
+                * |    R      -->     S    |
+                * |  Q   S    -->   Q   T  |
+                * |        t  -->          |
+                */
+               KASSERT(RB_SENTINEL_P(standin->rb_nodes[standin_other]));
+               KASSERT(!RB_SENTINEL_P(self->rb_nodes[standin_other]));
+               KASSERT(self->rb_nodes[standin_which] == standin);
+               /*
+                * Have our son/standin adopt his brother as his new son.
+                */
+               standin_father = standin;
+       } else {
+               /*
+                * |    R          -->    S       .  |
+                * |   / \  |   T  -->   / \  |  /   |
+                * |  ..... | S    -->  ..... | T    |
+                *
+                * Sever standin's connection to his father.
+                */
+               standin_father->rb_nodes[standin_which] = standin_son;
+               /*
+                * Adopt the far son.
+                */
+               standin->rb_nodes[standin_other] = self->rb_nodes[standin_other];
+               RB_SET_FATHER(standin->rb_nodes[standin_other], standin);
+               KASSERT(RB_POSITION(self->rb_nodes[standin_other]) == standin_other);
+               /*
+                * Use standin_other because we need to preserve standin_which
+                * for the removal_rebalance.
+                */
+               standin_other = standin_which;
+       }
+
+       /*
+        * Move the only remaining son to our standin.  If our standin is our
+        * son, this will be the only son needed to be moved.
+        */
+       KASSERT(standin->rb_nodes[standin_other] != self->rb_nodes[standin_other]);
+       standin->rb_nodes[standin_other] = self->rb_nodes[standin_other];
+       RB_SET_FATHER(standin->rb_nodes[standin_other], standin);
+
+       /*
+        * Now copy the result of self to standin and then replace
+        * self with standin in the tree.
+        */
+       RB_COPY_PROPERTIES(standin, self);
+       RB_SET_FATHER(standin, RB_FATHER(self));
+       RB_FATHER(standin)->rb_nodes[RB_POSITION(standin)] = standin;
+
+       /*
+        * Remove ourselves from the node list, decrement the count,
+        * and update min/max.
+        */
+       RB_TAILQ_REMOVE(&rbt->rbt_nodes, self, rb_link);
+       RBSTAT_DEC(rbt->rbt_count);
+#ifndef RBSMALL
+       if (__predict_false(rbt->rbt_minmax[RB_POSITION(self)] == self))
+               rbt->rbt_minmax[RB_POSITION(self)] = RB_FATHER(self);
+       RB_SET_FATHER(self, NULL);
+#endif
+
+       KASSERT(rb_tree_check_node(rbt, standin, NULL, false));
+       KASSERT(RB_FATHER_SENTINEL_P(standin)
+               || rb_tree_check_node(rbt, standin_father, NULL, false));
+       KASSERT(RB_LEFT_SENTINEL_P(standin)
+               || rb_tree_check_node(rbt, standin->rb_left, NULL, false));
+       KASSERT(RB_RIGHT_SENTINEL_P(standin)
+               || rb_tree_check_node(rbt, standin->rb_right, NULL, false));
+
+       if (!rebalance)
+               return;
+
+       rb_tree_removal_rebalance(rbt, standin_father, standin_which);
+       KASSERT(rb_tree_check_node(rbt, standin, NULL, true));
+}
+
+/*
+ * We could do this by doing
+ *     rb_tree_node_swap(rbt, self, which);
+ *     rb_tree_prune_node(rbt, self, false);
+ *
+ * But it's more efficient to just evalate and recolor the child.
+ */
+static void
+rb_tree_prune_blackred_branch(struct rb_tree *rbt, struct rb_node *self,
+       unsigned int which)
+{
+       struct rb_node *father = RB_FATHER(self);
+       struct rb_node *son = self->rb_nodes[which];
+#ifndef RBSMALL
+       const bool was_root = RB_ROOT_P(rbt, self);
+#endif
+
+       KASSERT(which == RB_DIR_LEFT || which == RB_DIR_RIGHT);
+       KASSERT(RB_BLACK_P(self) && RB_RED_P(son));
+       KASSERT(!RB_TWOCHILDREN_P(son));
+       KASSERT(RB_CHILDLESS_P(son));
+       KASSERT(rb_tree_check_node(rbt, self, NULL, false));
+       KASSERT(rb_tree_check_node(rbt, son, NULL, false));
+
+       /*
+        * Remove ourselves from the tree and give our former child our
+        * properties (position, color, root).
+        */
+       RB_COPY_PROPERTIES(son, self);
+       father->rb_nodes[RB_POSITION(son)] = son;
+       RB_SET_FATHER(son, father);
+
+       /*
+        * Remove ourselves from the node list, decrement the count,
+        * and update minmax.
+        */
+       RB_TAILQ_REMOVE(&rbt->rbt_nodes, self, rb_link);
+       RBSTAT_DEC(rbt->rbt_count);
+#ifndef RBSMALL
+       if (__predict_false(was_root)) {
+               KASSERT(rbt->rbt_minmax[which] == son);
+               rbt->rbt_minmax[which ^ RB_DIR_OTHER] = son;
+       } else if (rbt->rbt_minmax[RB_POSITION(self)] == self) {
+               rbt->rbt_minmax[RB_POSITION(self)] = son;
+       }
+       RB_SET_FATHER(self, NULL);
+#endif
+
+       KASSERT(was_root || rb_tree_check_node(rbt, father, NULL, true));
+       KASSERT(rb_tree_check_node(rbt, son, NULL, true));
+}
+
+void
+rb_tree_remove_node(struct rb_tree *rbt, void *object)
+{
+       const rb_tree_ops_t *rbto = rbt->rbt_ops;
+       struct rb_node *standin, *self = RB_ITEMTONODE(rbto, object);
+       unsigned int which;
+
+       KASSERT(!RB_SENTINEL_P(self));
+       RBSTAT_INC(rbt->rbt_removals);
+
+       /*
+        * In the following diagrams, we (the node to be removed) are S.  Red
+        * nodes are lowercase.  T could be either red or black.
+        *
+        * Remember the major axiom of the red-black tree: the number of
+        * black nodes from the root to each leaf is constant across all
+        * leaves, only the number of red nodes varies.
+        *
+        * Thus removing a red leaf doesn't require any other changes to a
+        * red-black tree.  So if we must remove a node, attempt to rearrange
+        * the tree so we can remove a red node.
+        *
+        * The simpliest case is a childless red node or a childless root node:
+        *
+        * |    T  -->    T  |    or    |  R  -->  *  |
+        * |  s    -->  *    |
+        */
+       if (RB_CHILDLESS_P(self)) {
+               const bool rebalance = RB_BLACK_P(self) && !RB_ROOT_P(rbt, self);
+               rb_tree_prune_node(rbt, self, rebalance);
+               return;
+       }
+       KASSERT(!RB_CHILDLESS_P(self));
+       if (!RB_TWOCHILDREN_P(self)) {
+               /*
+                * The next simpliest case is the node we are deleting is
+                * black and has one red child.
+                *
+                * |      T  -->      T  -->      T  |
+                * |    S    -->  R      -->  R      |
+                * |  r      -->    s    -->    *    |
+                */
+               which = RB_LEFT_SENTINEL_P(self) ? RB_DIR_RIGHT : RB_DIR_LEFT;
+               KASSERT(RB_BLACK_P(self));
+               KASSERT(RB_RED_P(self->rb_nodes[which]));
+               KASSERT(RB_CHILDLESS_P(self->rb_nodes[which]));
+               rb_tree_prune_blackred_branch(rbt, self, which);
+               return;
+       }
+       KASSERT(RB_TWOCHILDREN_P(self));
+
+       /*
+        * We invert these because we prefer to remove from the inside of
+        * the tree.
+        */
+       which = RB_POSITION(self) ^ RB_DIR_OTHER;
+
+       /*
+        * Let's find the node closes to us opposite of our parent
+        * Now swap it with ourself, "prune" it, and rebalance, if needed.
+        */
+       standin = RB_ITEMTONODE(rbto, rb_tree_iterate(rbt, object, which));
+       rb_tree_swap_prune_and_rebalance(rbt, self, standin);
+}
+
+static void
+rb_tree_removal_rebalance(struct rb_tree *rbt, struct rb_node *parent,
+       unsigned int which)
+{
+       KASSERT(!RB_SENTINEL_P(parent));
+       KASSERT(RB_SENTINEL_P(parent->rb_nodes[which]));
+       KASSERT(which == RB_DIR_LEFT || which == RB_DIR_RIGHT);
+       RBSTAT_INC(rbt->rbt_removal_rebalance_calls);
+
+       while (RB_BLACK_P(parent->rb_nodes[which])) {
+               unsigned int other = which ^ RB_DIR_OTHER;
+               struct rb_node *brother = parent->rb_nodes[other];
+
+               RBSTAT_INC(rbt->rbt_removal_rebalance_passes);
+
+               KASSERT(!RB_SENTINEL_P(brother));
+               /*
+                * For cases 1, 2a, and 2b, our brother's children must
+                * be black and our father must be black
+                */
+               if (RB_BLACK_P(parent)
+                   && RB_BLACK_P(brother->rb_left)
+                   && RB_BLACK_P(brother->rb_right)) {
+                       if (RB_RED_P(brother)) {
+                               /*
+                                * Case 1: Our brother is red, swap its
+                                * position (and colors) with our parent. 
+                                * This should now be case 2b (unless C or E
+                                * has a red child which is case 3; thus no
+                                * explicit branch to case 2b).
+                                *
+                                *    B         ->        D
+                                *  A     d     ->    b     E
+                                *      C   E   ->  A   C
+                                */
+                               KASSERT(RB_BLACK_P(parent));
+                               rb_tree_reparent_nodes(rbt, parent, other);
+                               brother = parent->rb_nodes[other];
+                               KASSERT(!RB_SENTINEL_P(brother));
+                               KASSERT(RB_RED_P(parent));
+                               KASSERT(RB_BLACK_P(brother));
+                               KASSERT(rb_tree_check_node(rbt, brother, NULL, false));
+                               KASSERT(rb_tree_check_node(rbt, parent, NULL, false));
+                       } else {
+                               /*
+                                * Both our parent and brother are black.
+                                * Change our brother to red, advance up rank
+                                * and go through the loop again.
+                                *
+                                *    B         ->   *B
+                                * *A     D     ->  A     d
+                                *      C   E   ->      C   E
+                                */
+                               RB_MARK_RED(brother);
+                               KASSERT(RB_BLACK_P(brother->rb_left));
+                               KASSERT(RB_BLACK_P(brother->rb_right));
+                               if (RB_ROOT_P(rbt, parent))
+                                       return; /* root == parent == black */
+                               KASSERT(rb_tree_check_node(rbt, brother, NULL, false));
+                               KASSERT(rb_tree_check_node(rbt, parent, NULL, false));
+                               which = RB_POSITION(parent);
+                               parent = RB_FATHER(parent);
+                               continue;
+                       }
+               }
+               /*
+                * Avoid an else here so that case 2a above can hit either
+                * case 2b, 3, or 4.
+                */
+               if (RB_RED_P(parent)
+                   && RB_BLACK_P(brother)
+                   && RB_BLACK_P(brother->rb_left)
+                   && RB_BLACK_P(brother->rb_right)) {
+                       KASSERT(RB_RED_P(parent));
+                       KASSERT(RB_BLACK_P(brother));
+                       KASSERT(RB_BLACK_P(brother->rb_left));
+                       KASSERT(RB_BLACK_P(brother->rb_right));
+                       /*
+                        * We are black, our father is red, our brother and
+                        * both nephews are black.  Simply invert/exchange the
+                        * colors of our father and brother (to black and red
+                        * respectively).
+                        *
+                        *      |    f        -->    F        |
+                        *      |  *     B    -->  *     b    |
+                        *      |      N   N  -->      N   N  |
+                        */
+                       RB_MARK_BLACK(parent);
+                       RB_MARK_RED(brother);
+                       KASSERT(rb_tree_check_node(rbt, brother, NULL, true));
+                       break;          /* We're done! */
+               } else {
+                       /*
+                        * Our brother must be black and have at least one
+                        * red child (it may have two).
+                        */
+                       KASSERT(RB_BLACK_P(brother));
+                       KASSERT(RB_RED_P(brother->rb_nodes[which]) ||
+                               RB_RED_P(brother->rb_nodes[other]));
+                       if (RB_BLACK_P(brother->rb_nodes[other])) {
+                               /*
+                                * Case 3: our brother is black, our near
+                                * nephew is red, and our far nephew is black.
+                                * Swap our brother with our near nephew.  
+                                * This result in a tree that matches case 4.
+                                * (Our father could be red or black).
+                                *
+                                *      |    F      -->    F      |
+                                *      |  x     B  -->  x   B    |
+                                *      |      n    -->        n  |
+                                */
+                               KASSERT(RB_RED_P(brother->rb_nodes[which]));
+                               rb_tree_reparent_nodes(rbt, brother, which);
+                               KASSERT(RB_FATHER(brother) == parent->rb_nodes[other]);
+                               brother = parent->rb_nodes[other];
+                               KASSERT(RB_RED_P(brother->rb_nodes[other]));
+                       }
+                       /*
+                        * Case 4: our brother is black and our far nephew
+                        * is red.  Swap our father and brother locations and
+                        * change our far nephew to black.  (these can be
+                        * done in either order so we change the color first).
+                        * The result is a valid red-black tree and is a
+                        * terminal case.  (again we don't care about the
+                        * father's color)
+                        *
+                        * If the father is red, we will get a red-black-black
+                        * tree:
+                        *      |  f      ->  f      -->    b    |
+                        *      |    B    ->    B    -->  F   N  |
+                        *      |      n  ->      N  -->         |
+                        *
+                        * If the father is black, we will get an all black
+                        * tree:
+                        *      |  F      ->  F      -->    B    |
+                        *      |    B    ->    B    -->  F   N  |
+                        *      |      n  ->      N  -->         |
+                        *
+                        * If we had two red nephews, then after the swap,
+                        * our former father would have a red grandson. 
+                        */
+                       KASSERT(RB_BLACK_P(brother));
+                       KASSERT(RB_RED_P(brother->rb_nodes[other]));
+                       RB_MARK_BLACK(brother->rb_nodes[other]);
+                       rb_tree_reparent_nodes(rbt, parent, other);
+                       break;          /* We're done! */
+               }
+       }
+       KASSERT(rb_tree_check_node(rbt, parent, NULL, true));
+}
+
+void *
+rb_tree_iterate(struct rb_tree *rbt, void *object, const unsigned int direction)
+{
+       const rb_tree_ops_t *rbto = rbt->rbt_ops;
+       const unsigned int other = direction ^ RB_DIR_OTHER;
+       struct rb_node *self;
+
+       KASSERT(direction == RB_DIR_LEFT || direction == RB_DIR_RIGHT);
+
+       if (object == NULL) {
+#ifndef RBSMALL
+               if (RB_SENTINEL_P(rbt->rbt_root))
+                       return NULL;
+               return RB_NODETOITEM(rbto, rbt->rbt_minmax[direction]);
+#else
+               self = rbt->rbt_root;
+               if (RB_SENTINEL_P(self))
+                       return NULL;
+               while (!RB_SENTINEL_P(self->rb_nodes[direction]))
+                       self = self->rb_nodes[direction];
+               return RB_NODETOITEM(rbto, self);
+#endif /* !RBSMALL */
+       }
+       self = RB_ITEMTONODE(rbto, object);
+       KASSERT(!RB_SENTINEL_P(self));
+       /*
+        * We can't go any further in this direction.  We proceed up in the
+        * opposite direction until our parent is in direction we want to go.
+        */
+       if (RB_SENTINEL_P(self->rb_nodes[direction])) {
+               while (!RB_ROOT_P(rbt, self)) {
+                       if (other == RB_POSITION(self))
+                               return RB_NODETOITEM(rbto, RB_FATHER(self));
+                       self = RB_FATHER(self);
+               }
+               return NULL;
+       }
+
+       /*
+        * Advance down one in current direction and go down as far as possible
+        * in the opposite direction.
+        */
+       self = self->rb_nodes[direction];
+       KASSERT(!RB_SENTINEL_P(self));
+       while (!RB_SENTINEL_P(self->rb_nodes[other]))
+               self = self->rb_nodes[other];
+       return RB_NODETOITEM(rbto, self);
+}
+
+#ifdef RBDEBUG
+static const struct rb_node *
+rb_tree_iterate_const(const struct rb_tree *rbt, const struct rb_node *self,
+       const unsigned int direction)
+{
+       const unsigned int other = direction ^ RB_DIR_OTHER;
+       KASSERT(direction == RB_DIR_LEFT || direction == RB_DIR_RIGHT);
+
+       if (self == NULL) {
+#ifndef RBSMALL
+               if (RB_SENTINEL_P(rbt->rbt_root))
+                       return NULL;
+               return rbt->rbt_minmax[direction];
+#else
+               self = rbt->rbt_root;
+               if (RB_SENTINEL_P(self))
+                       return NULL;
+               while (!RB_SENTINEL_P(self->rb_nodes[direction]))
+                       self = self->rb_nodes[direction];
+               return self;
+#endif /* !RBSMALL */
+       }
+       KASSERT(!RB_SENTINEL_P(self));
+       /*
+        * We can't go any further in this direction.  We proceed up in the
+        * opposite direction until our parent is in direction we want to go.
+        */
+       if (RB_SENTINEL_P(self->rb_nodes[direction])) {
+               while (!RB_ROOT_P(rbt, self)) {
+                       if (other == RB_POSITION(self))
+                               return RB_FATHER(self);
+                       self = RB_FATHER(self);
+               }
+               return NULL;
+       }
+
+       /*
+        * Advance down one in current direction and go down as far as possible
+        * in the opposite direction.
+        */
+       self = self->rb_nodes[direction];
+       KASSERT(!RB_SENTINEL_P(self));
+       while (!RB_SENTINEL_P(self->rb_nodes[other]))
+               self = self->rb_nodes[other];
+       return self;
+}
+
+static unsigned int
+rb_tree_count_black(const struct rb_node *self)
+{
+       unsigned int left, right;
+
+       if (RB_SENTINEL_P(self))
+               return 0;
+
+       left = rb_tree_count_black(self->rb_left);
+       right = rb_tree_count_black(self->rb_right);
+
+       KASSERT(left == right);
+
+       return left + RB_BLACK_P(self);
+}
+
+static bool
+rb_tree_check_node(const struct rb_tree *rbt, const struct rb_node *self,
+       const struct rb_node *prev, bool red_check)
+{
+       const rb_tree_ops_t *rbto = rbt->rbt_ops;
+       rbto_compare_nodes_fn compare_nodes = rbto->rbto_compare_nodes;
+
+       KASSERT(!RB_SENTINEL_P(self));
+       KASSERT(prev == NULL || (*compare_nodes)(rbto->rbto_context,
+           RB_NODETOITEM(rbto, prev), RB_NODETOITEM(rbto, self)) < 0);
+
+       /*
+        * Verify our relationship to our parent.
+        */
+       if (RB_ROOT_P(rbt, self)) {
+               KASSERT(self == rbt->rbt_root);
+               KASSERT(RB_POSITION(self) == RB_DIR_LEFT);
+               KASSERT(RB_FATHER(self)->rb_nodes[RB_DIR_LEFT] == self);
+               KASSERT(RB_FATHER(self) == (const struct rb_node *) &rbt->rbt_root);
+       } else {
+               int diff = (*compare_nodes)(rbto->rbto_context,
+                   RB_NODETOITEM(rbto, self),
+                   RB_NODETOITEM(rbto, RB_FATHER(self)));
+
+               KASSERT(self != rbt->rbt_root);
+               KASSERT(!RB_FATHER_SENTINEL_P(self));
+               if (RB_POSITION(self) == RB_DIR_LEFT) {
+                       KASSERT(diff < 0);
+                       KASSERT(RB_FATHER(self)->rb_nodes[RB_DIR_LEFT] == self);
+               } else {
+                       KASSERT(diff > 0);
+                       KASSERT(RB_FATHER(self)->rb_nodes[RB_DIR_RIGHT] == self);
+               }
+       }
+
+       /*
+        * Verify our position in the linked list against the tree itself.
+        */
+       {
+               const struct rb_node *prev0 = rb_tree_iterate_const(rbt, self, RB_DIR_LEFT);
+               const struct rb_node *next0 = rb_tree_iterate_const(rbt, self, RB_DIR_RIGHT);
+               KASSERT(prev0 == TAILQ_PREV(self, rb_node_qh, rb_link));
+               KASSERT(next0 == TAILQ_NEXT(self, rb_link));
+#ifndef RBSMALL
+               KASSERT(prev0 != NULL || self == rbt->rbt_minmax[RB_DIR_LEFT]);
+               KASSERT(next0 != NULL || self == rbt->rbt_minmax[RB_DIR_RIGHT]);
+#endif
+       }
+
+       /*
+        * The root must be black.
+        * There can never be two adjacent red nodes. 
+        */
+       if (red_check) {
+               KASSERT(!RB_ROOT_P(rbt, self) || RB_BLACK_P(self));
+               (void) rb_tree_count_black(self);
+               if (RB_RED_P(self)) {
+                       const struct rb_node *brother;
+                       KASSERT(!RB_ROOT_P(rbt, self));
+                       brother = RB_FATHER(self)->rb_nodes[RB_POSITION(self) ^ RB_DIR_OTHER];
+                       KASSERT(RB_BLACK_P(RB_FATHER(self)));
+                       /* 
+                        * I'm red and have no children, then I must either
+                        * have no brother or my brother also be red and
+                        * also have no children.  (black count == 0)
+                        */
+                       KASSERT(!RB_CHILDLESS_P(self)
+                               || RB_SENTINEL_P(brother)
+                               || RB_RED_P(brother)
+                               || RB_CHILDLESS_P(brother));
+                       /*
+                        * If I'm not childless, I must have two children
+                        * and they must be both be black.
+                        */
+                       KASSERT(RB_CHILDLESS_P(self)
+                               || (RB_TWOCHILDREN_P(self)
+                                   && RB_BLACK_P(self->rb_left)
+                                   && RB_BLACK_P(self->rb_right)));
+                       /*
+                        * If I'm not childless, thus I have black children,
+                        * then my brother must either be black or have two
+                        * black children.
+                        */
+                       KASSERT(RB_CHILDLESS_P(self)
+                               || RB_BLACK_P(brother)
+                               || (RB_TWOCHILDREN_P(brother)
+                                   && RB_BLACK_P(brother->rb_left)
+                                   && RB_BLACK_P(brother->rb_right)));
+               } else {
+                       /*
+                        * If I'm black and have one child, that child must
+                        * be red and childless.
+                        */
+                       KASSERT(RB_CHILDLESS_P(self)
+                               || RB_TWOCHILDREN_P(self)
+                               || (!RB_LEFT_SENTINEL_P(self)
+                                   && RB_RIGHT_SENTINEL_P(self)
+                                   && RB_RED_P(self->rb_left)
+                                   && RB_CHILDLESS_P(self->rb_left))
+                               || (!RB_RIGHT_SENTINEL_P(self)
+                                   && RB_LEFT_SENTINEL_P(self)
+                                   && RB_RED_P(self->rb_right)
+                                   && RB_CHILDLESS_P(self->rb_right)));
+
+                       /*
+                        * If I'm a childless black node and my parent is
+                        * black, my 2nd closet relative away from my parent
+                        * is either red or has a red parent or red children.
+                        */
+                       if (!RB_ROOT_P(rbt, self)
+                           && RB_CHILDLESS_P(self)
+                           && RB_BLACK_P(RB_FATHER(self))) {
+                               const unsigned int which = RB_POSITION(self);
+                               const unsigned int other = which ^ RB_DIR_OTHER;
+                               const struct rb_node *relative0, *relative;
+
+                               relative0 = rb_tree_iterate_const(rbt,
+                                   self, other);
+                               KASSERT(relative0 != NULL);
+                               relative = rb_tree_iterate_const(rbt,
+                                   relative0, other);
+                               KASSERT(relative != NULL);
+                               KASSERT(RB_SENTINEL_P(relative->rb_nodes[which]));
+#if 0
+                               KASSERT(RB_RED_P(relative)
+                                       || RB_RED_P(relative->rb_left)
+                                       || RB_RED_P(relative->rb_right)
+                                       || RB_RED_P(RB_FATHER(relative)));
+#endif
+                       }
+               }
+               /*
+                * A grandparent's children must be real nodes and not
+                * sentinels.  First check out grandparent.
+                */
+               KASSERT(RB_ROOT_P(rbt, self)
+                       || RB_ROOT_P(rbt, RB_FATHER(self))
+                       || RB_TWOCHILDREN_P(RB_FATHER(RB_FATHER(self))));
+               /*
+                * If we are have grandchildren on our left, then
+                * we must have a child on our right.
+                */
+               KASSERT(RB_LEFT_SENTINEL_P(self)
+                       || RB_CHILDLESS_P(self->rb_left)
+                       || !RB_RIGHT_SENTINEL_P(self));
+               /*
+                * If we are have grandchildren on our right, then
+                * we must have a child on our left.
+                */
+               KASSERT(RB_RIGHT_SENTINEL_P(self)
+                       || RB_CHILDLESS_P(self->rb_right)
+                       || !RB_LEFT_SENTINEL_P(self));
+
+               /*
+                * If we have a child on the left and it doesn't have two
+                * children make sure we don't have great-great-grandchildren on
+                * the right.
+                */
+               KASSERT(RB_TWOCHILDREN_P(self->rb_left)
+                       || RB_CHILDLESS_P(self->rb_right)
+                       || RB_CHILDLESS_P(self->rb_right->rb_left)
+                       || RB_CHILDLESS_P(self->rb_right->rb_left->rb_left)
+                       || RB_CHILDLESS_P(self->rb_right->rb_left->rb_right)
+                       || RB_CHILDLESS_P(self->rb_right->rb_right)
+                       || RB_CHILDLESS_P(self->rb_right->rb_right->rb_left)
+                       || RB_CHILDLESS_P(self->rb_right->rb_right->rb_right));
+
+               /*
+                * If we have a child on the right and it doesn't have two
+                * children make sure we don't have great-great-grandchildren on
+                * the left.
+                */
+               KASSERT(RB_TWOCHILDREN_P(self->rb_right)
+                       || RB_CHILDLESS_P(self->rb_left)
+                       || RB_CHILDLESS_P(self->rb_left->rb_left)
+                       || RB_CHILDLESS_P(self->rb_left->rb_left->rb_left)
+                       || RB_CHILDLESS_P(self->rb_left->rb_left->rb_right)
+                       || RB_CHILDLESS_P(self->rb_left->rb_right)
+                       || RB_CHILDLESS_P(self->rb_left->rb_right->rb_left)
+                       || RB_CHILDLESS_P(self->rb_left->rb_right->rb_right));
+
+               /*
+                * If we are fully interior node, then our predecessors and
+                * successors must have no children in our direction.
+                */
+               if (RB_TWOCHILDREN_P(self)) {
+                       const struct rb_node *prev0;
+                       const struct rb_node *next0;
+
+                       prev0 = rb_tree_iterate_const(rbt, self, RB_DIR_LEFT);
+                       KASSERT(prev0 != NULL);
+                       KASSERT(RB_RIGHT_SENTINEL_P(prev0));
+
+                       next0 = rb_tree_iterate_const(rbt, self, RB_DIR_RIGHT);
+                       KASSERT(next0 != NULL);
+                       KASSERT(RB_LEFT_SENTINEL_P(next0));
+               }
+       }
+
+       return true;
+}
+
+void
+rb_tree_check(const struct rb_tree *rbt, bool red_check)
+{
+       const struct rb_node *self;
+       const struct rb_node *prev;
+#ifdef RBSTATS
+       unsigned int count = 0;
+#endif
+
+       KASSERT(rbt->rbt_root != NULL);
+       KASSERT(RB_LEFT_P(rbt->rbt_root));
+
+#if defined(RBSTATS) && !defined(RBSMALL)
+       KASSERT(rbt->rbt_count > 1
+           || rbt->rbt_minmax[RB_DIR_LEFT] == rbt->rbt_minmax[RB_DIR_RIGHT]);
+#endif
+
+       prev = NULL;
+       TAILQ_FOREACH(self, &rbt->rbt_nodes, rb_link) {
+               rb_tree_check_node(rbt, self, prev, false);
+#ifdef RBSTATS
+               count++;
+#endif
+       }
+#ifdef RBSTATS
+       KASSERT(rbt->rbt_count == count);
+#endif
+       if (red_check) {
+               KASSERT(RB_BLACK_P(rbt->rbt_root));
+               KASSERT(RB_SENTINEL_P(rbt->rbt_root)
+                       || rb_tree_count_black(rbt->rbt_root));
+
+               /*
+                * The root must be black.
+                * There can never be two adjacent red nodes. 
+                */
+               TAILQ_FOREACH(self, &rbt->rbt_nodes, rb_link) {
+                       rb_tree_check_node(rbt, self, NULL, true);
+               }
+       }
+}
+#endif /* RBDEBUG */
+
+#ifdef RBSTATS
+static void
+rb_tree_mark_depth(const struct rb_tree *rbt, const struct rb_node *self,
+       size_t *depths, size_t depth)
+{
+       if (RB_SENTINEL_P(self))
+               return;
+
+       if (RB_TWOCHILDREN_P(self)) {
+               rb_tree_mark_depth(rbt, self->rb_left, depths, depth + 1);
+               rb_tree_mark_depth(rbt, self->rb_right, depths, depth + 1);
+               return;
+       }
+       depths[depth]++;
+       if (!RB_LEFT_SENTINEL_P(self)) {
+               rb_tree_mark_depth(rbt, self->rb_left, depths, depth + 1);
+       }
+       if (!RB_RIGHT_SENTINEL_P(self)) {
+               rb_tree_mark_depth(rbt, self->rb_right, depths, depth + 1);
+       }
+}
+
+void
+rb_tree_depths(const struct rb_tree *rbt, size_t *depths)
+{
+       rb_tree_mark_depth(rbt, rbt->rbt_root, depths, 1);
+}
+#endif /* RBSTATS */
diff --git a/common/lib/libc/gen/rpst.c b/common/lib/libc/gen/rpst.c
new file mode 100644 (file)
index 0000000..753e992
--- /dev/null
@@ -0,0 +1,712 @@
+/*     $NetBSD: rpst.c,v 1.9 2009/05/26 22:39:15 yamt Exp $    */
+
+/*-
+ * Copyright (c)2009 YAMAMOTO Takashi,
+ * 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.
+ */
+
+/*
+ * radix priority search tree
+ *
+ * described in:
+ *     SIAM J. COMPUT.
+ *     Vol. 14, No. 2, May 1985
+ *     PRIORITY SEARCH TREES
+ *     EDWARD M. McCREIGHT
+ *
+ * ideas from linux:
+ *     - grow tree height on-demand.
+ *     - allow duplicated X values.  in that case, we act as a heap.
+ */
+
+#include <sys/cdefs.h>
+
+#if defined(_KERNEL)
+__KERNEL_RCSID(0, "$NetBSD: rpst.c,v 1.9 2009/05/26 22:39:15 yamt Exp $");
+#include <sys/param.h>
+#else /* defined(_KERNEL) */
+__RCSID("$NetBSD: rpst.c,v 1.9 2009/05/26 22:39:15 yamt Exp $");
+#include <assert.h>
+#include <stdbool.h>
+#include <string.h>
+#if 1
+#define        KASSERT assert
+#else
+#define        KASSERT(a)
+#endif
+#endif /* defined(_KERNEL) */
+
+#include <sys/rpst.h>
+
+/*
+ * rpst_init_tree: initialize a tree.
+ */
+
+void
+rpst_init_tree(struct rpst_tree *t)
+{
+
+       t->t_root = NULL;
+       t->t_height = 0;
+}
+
+/*
+ * rpst_height2max: calculate the maximum index which can be handled by
+ * a tree with the given height.
+ *
+ * 0  ... 0x0000000000000001
+ * 1  ... 0x0000000000000003
+ * 2  ... 0x0000000000000007
+ * 3  ... 0x000000000000000f
+ *
+ * 31 ... 0x00000000ffffffff
+ *
+ * 63 ... 0xffffffffffffffff
+ */
+
+static uint64_t
+rpst_height2max(unsigned int height)
+{
+
+       KASSERT(height < 64);
+       if (height == 63) {
+               return UINT64_MAX;
+       }
+       return (UINT64_C(1) << (height + 1)) - 1;
+}
+
+/*
+ * rpst_level2mask: calculate the mask for the given level in the tree.
+ *
+ * the mask used to index root's children is level 0.
+ */
+
+static uint64_t
+rpst_level2mask(const struct rpst_tree *t, unsigned int level)
+{
+       uint64_t mask;
+
+       if (t->t_height < level) {
+               mask = 0;
+       } else {
+               mask = UINT64_C(1) << (t->t_height - level);
+       }
+       return mask;
+}
+
+/*
+ * rpst_startmask: calculate the mask for the start of a search.
+ * (ie. the mask for the top-most bit)
+ */
+
+static uint64_t
+rpst_startmask(const struct rpst_tree *t)
+{
+       const uint64_t mask = rpst_level2mask(t, 0);
+
+       KASSERT((mask | (mask - 1)) == rpst_height2max(t->t_height));
+       return mask;
+}
+
+/*
+ * rpst_update_parents: update n_parent of children
+ */
+
+static inline void
+rpst_update_parents(struct rpst_node *n)
+{
+       int i;
+
+       for (i = 0; i < 2; i++) {
+               if (n->n_children[i] != NULL) {
+                       n->n_children[i]->n_parent = n;
+               }
+       }
+}
+
+/*
+ * rpst_enlarge_tree: enlarge tree so that 'idx' can be stored
+ */
+
+static void
+rpst_enlarge_tree(struct rpst_tree *t, uint64_t idx)
+{
+
+       while (idx > rpst_height2max(t->t_height)) {
+               struct rpst_node *n = t->t_root;
+
+               if (n != NULL) {
+                       rpst_remove_node(t, n);
+                       memset(&n->n_children, 0, sizeof(n->n_children));
+                       n->n_children[0] = t->t_root;
+                       t->t_root->n_parent = n;
+                       t->t_root = n;
+                       n->n_parent = NULL;
+               }
+               t->t_height++;
+       }
+}
+
+/*
+ * rpst_insert_node1: a helper for rpst_insert_node.
+ */
+
+static struct rpst_node *
+rpst_insert_node1(struct rpst_node **where, struct rpst_node *n, uint64_t mask)
+{
+       struct rpst_node *parent;
+       struct rpst_node *cur;
+       unsigned int idx;
+
+       KASSERT((n->n_x & ((-mask) << 1)) == 0);
+       parent = NULL;
+next:
+       cur = *where;
+       if (cur == NULL) {
+               n->n_parent = parent;
+               memset(&n->n_children, 0, sizeof(n->n_children));
+               *where = n;
+               return NULL;
+       }
+       KASSERT(cur->n_parent == parent);
+       if (n->n_y == cur->n_y && n->n_x == cur->n_x) {
+               return cur;
+       }
+       if (n->n_y < cur->n_y) {
+               /*
+                * swap cur and n.
+                * note that n is not in tree.
+                */
+               memcpy(n->n_children, cur->n_children, sizeof(n->n_children));
+               n->n_parent = cur->n_parent;
+               rpst_update_parents(n);
+               *where = n;
+               n = cur;
+               cur = *where;
+       }
+       KASSERT(*where == cur);
+       idx = (n->n_x & mask) != 0;
+       where = &cur->n_children[idx];
+       parent = cur;
+       KASSERT((*where) == NULL || ((((*where)->n_x & mask) != 0) == idx));
+       KASSERT((*where) == NULL || (*where)->n_y >= cur->n_y);
+       mask >>= 1;
+       goto next;
+}
+
+/*
+ * rpst_insert_node: insert a node into the tree.
+ *
+ * => return NULL on success.
+ * => if a duplicated node (a node with the same X,Y pair as ours) is found,
+ *    return the node.  in that case, the tree is intact.
+ */
+
+struct rpst_node *
+rpst_insert_node(struct rpst_tree *t, struct rpst_node *n)
+{
+
+       rpst_enlarge_tree(t, n->n_x);
+       return rpst_insert_node1(&t->t_root, n, rpst_startmask(t));
+}
+
+/*
+ * rpst_find_pptr: find a pointer to the given node.
+ *
+ * also, return the parent node via parentp.  (NULL for the root node.)
+ */
+
+static inline struct rpst_node **
+rpst_find_pptr(struct rpst_tree *t, struct rpst_node *n,
+    struct rpst_node **parentp)
+{
+       struct rpst_node * const parent = n->n_parent;
+       unsigned int i;
+
+       *parentp = parent;
+       if (parent == NULL) {
+               return &t->t_root;
+       }
+       for (i = 0; i < 2 - 1; i++) {
+               if (parent->n_children[i] == n) {
+                       break;
+               }
+       }
+       KASSERT(parent->n_children[i] == n);
+       return &parent->n_children[i];
+}
+
+/*
+ * rpst_remove_node_at: remove a node at *where.
+ */
+
+static void
+rpst_remove_node_at(struct rpst_node *parent, struct rpst_node **where,
+    struct rpst_node *cur)
+{
+       struct rpst_node *tmp[2];
+       struct rpst_node *selected;
+       unsigned int selected_idx = 0; /* XXX gcc */
+       unsigned int i;
+
+       KASSERT(cur != NULL);
+       KASSERT(parent == cur->n_parent);
+next:
+       selected = NULL;
+       for (i = 0; i < 2; i++) {
+               struct rpst_node *c;
+
+               c = cur->n_children[i];
+               KASSERT(c == NULL || c->n_parent == cur);
+               if (selected == NULL || (c != NULL && c->n_y < selected->n_y)) {
+                       selected = c;
+                       selected_idx = i;
+               }
+       }
+       /*
+        * now we have:
+        *
+        *      parent
+        *          \ <- where
+        *           cur
+        *           / \
+        *          A  selected
+        *              / \
+        *             B   C
+        */
+       *where = selected;
+       if (selected == NULL) {
+               return;
+       }
+       /*
+        * swap selected->n_children and cur->n_children.
+        */
+       memcpy(tmp, selected->n_children, sizeof(tmp));
+       memcpy(selected->n_children, cur->n_children, sizeof(tmp));
+       memcpy(cur->n_children, tmp, sizeof(tmp));
+       rpst_update_parents(cur);
+       rpst_update_parents(selected);
+       selected->n_parent = parent;
+       /*
+        *      parent
+        *          \ <- where
+        *          selected
+        *           / \
+        *          A  selected
+        *
+        *              cur
+        *              / \
+        *             B   C
+        */
+       where = &selected->n_children[selected_idx];
+       /*
+        *      parent
+        *          \
+        *          selected
+        *           / \ <- where
+        *          A  selected (*)
+        *
+        *              cur (**)
+        *              / \
+        *             B   C
+        *
+        * (*) this 'selected' will be overwritten in the next iteration.
+        * (**) cur->n_parent is bogus.
+        */
+       parent = selected;
+       goto next;
+}
+
+/*
+ * rpst_remove_node: remove a node from the tree.
+ */
+
+void
+rpst_remove_node(struct rpst_tree *t, struct rpst_node *n)
+{
+       struct rpst_node *parent;
+       struct rpst_node **where;
+
+       where = rpst_find_pptr(t, n, &parent);
+       rpst_remove_node_at(parent, where, n);
+}
+
+static bool __unused
+rpst_iterator_match_p(const struct rpst_node *n, const struct rpst_iterator *it)
+{
+
+       if (n->n_y > it->it_max_y) {
+               return false;
+       }
+       if (n->n_x < it->it_min_x) {
+               return false;
+       }
+       if (n->n_x > it->it_max_x) {
+               return false;
+       }
+       return true;
+}
+
+struct rpst_node *
+rpst_iterate_first(struct rpst_tree *t, uint64_t max_y, uint64_t min_x,
+    uint64_t max_x, struct rpst_iterator *it)
+{
+       struct rpst_node *n;
+
+       KASSERT(min_x <= max_x);
+       n = t->t_root;
+       if (n == NULL || n->n_y > max_y) {
+               return NULL;
+       }
+       if (rpst_height2max(t->t_height) < min_x) {
+               return NULL;
+       }
+       it->it_tree = t;
+       it->it_cur = n;
+       it->it_idx = (min_x & rpst_startmask(t)) != 0;
+       it->it_level = 0;
+       it->it_max_y = max_y;
+       it->it_min_x = min_x;
+       it->it_max_x = max_x;
+       return rpst_iterate_next(it);
+}
+
+static inline unsigned int
+rpst_node_on_edge_p(const struct rpst_node *n, uint64_t val, uint64_t mask)
+{
+
+       return ((n->n_x ^ val) & ((-mask) << 1)) == 0;
+}
+
+static inline uint64_t
+rpst_maxidx(const struct rpst_node *n, uint64_t max_x, uint64_t mask)
+{
+
+       if (rpst_node_on_edge_p(n, max_x, mask)) {
+               return (max_x & mask) != 0;
+       } else {
+               return 1;
+       }
+}
+
+static inline uint64_t
+rpst_minidx(const struct rpst_node *n, uint64_t min_x, uint64_t mask)
+{
+
+       if (rpst_node_on_edge_p(n, min_x, mask)) {
+               return (min_x & mask) != 0;
+       } else {
+               return 0;
+       }
+}
+
+struct rpst_node *
+rpst_iterate_next(struct rpst_iterator *it)
+{
+       struct rpst_tree *t;
+       struct rpst_node *n;
+       struct rpst_node *next;
+       const uint64_t max_y = it->it_max_y;
+       const uint64_t min_x = it->it_min_x;
+       const uint64_t max_x = it->it_max_x;
+       unsigned int idx;
+       unsigned int maxidx;
+       unsigned int level;
+       uint64_t mask;
+
+       t = it->it_tree;
+       n = it->it_cur;
+       idx = it->it_idx;
+       level = it->it_level;
+       mask = rpst_level2mask(t, level);
+       maxidx = rpst_maxidx(n, max_x, mask);
+       KASSERT(n == t->t_root || rpst_iterator_match_p(n, it));
+next:
+       KASSERT(mask == rpst_level2mask(t, level));
+       KASSERT(idx >= rpst_minidx(n, min_x, mask));
+       KASSERT(maxidx == rpst_maxidx(n, max_x, mask));
+       KASSERT(idx <= maxidx + 2);
+       KASSERT(n != NULL);
+#if 0
+       printf("%s: cur=%p, idx=%u maxidx=%u level=%u mask=%" PRIx64 "\n",
+           __func__, (void *)n, idx, maxidx, level, mask);
+#endif
+       if (idx == maxidx + 1) { /* visit the current node */
+               idx++;
+               if (min_x <= n->n_x && n->n_x <= max_x) {
+                       it->it_cur = n;
+                       it->it_idx = idx;
+                       it->it_level = level;
+                       KASSERT(rpst_iterator_match_p(n, it));
+                       return n; /* report */
+               }
+               goto next;
+       } else if (idx == maxidx + 2) { /* back to the parent */
+               struct rpst_node **where;
+
+               where = rpst_find_pptr(t, n, &next);
+               if (next == NULL) {
+                       KASSERT(level == 0);
+                       KASSERT(t->t_root == n);
+                       KASSERT(&t->t_root == where);
+                       return NULL; /* done */
+               }
+               KASSERT(level > 0);
+               level--;
+               n = next;
+               mask = rpst_level2mask(t, level);
+               maxidx = rpst_maxidx(n, max_x, mask);
+               idx = where - n->n_children + 1;
+               KASSERT(idx < 2 + 1);
+               goto next;
+       }
+       /* go to a child */
+       KASSERT(idx < 2);
+       next = n->n_children[idx];
+       if (next == NULL || next->n_y > max_y) {
+               idx++;
+               goto next;
+       }
+       KASSERT(next->n_parent == n);
+       KASSERT(next->n_y >= n->n_y);
+       level++;
+       mask >>= 1;
+       n = next;
+       idx = rpst_minidx(n, min_x, mask);
+       maxidx = rpst_maxidx(n, max_x, mask);
+#if 0
+       printf("%s: visit %p idx=%u level=%u mask=%llx\n",
+           __func__, n, idx, level, mask);
+#endif
+       goto next;
+}
+
+#if defined(UNITTEST)
+#include <sys/time.h>
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+static void
+rpst_dump_node(const struct rpst_node *n, unsigned int depth)
+{
+       unsigned int i;
+
+       for (i = 0; i < depth; i++) {
+               printf("  ");
+       }
+       printf("[%u]", depth);
+       if (n == NULL) {
+               printf("NULL\n");
+               return;
+       }
+       printf("%p x=%" PRIx64 "(%" PRIu64 ") y=%" PRIx64 "(%" PRIu64 ")\n",
+           (const void *)n, n->n_x, n->n_x, n->n_y, n->n_y);
+       for (i = 0; i < 2; i++) {
+               rpst_dump_node(n->n_children[i], depth + 1);
+       }
+}
+
+static void
+rpst_dump_tree(const struct rpst_tree *t)
+{
+
+       printf("pst %p height=%u\n", (const void *)t, t->t_height);
+       rpst_dump_node(t->t_root, 0);
+}
+
+struct testnode {
+       struct rpst_node n;
+       struct testnode *next;
+       bool failed;
+       bool found;
+};
+
+struct rpst_tree t;
+struct testnode *h = NULL;
+
+static uintmax_t
+tvdiff(const struct timeval *tv1, const struct timeval *tv2)
+{
+
+       return (uintmax_t)tv1->tv_sec * 1000000 + tv1->tv_usec -
+           tv2->tv_sec * 1000000 - tv2->tv_usec;
+}
+
+static unsigned int
+query(uint64_t max_y, uint64_t min_x, uint64_t max_x)
+{
+       struct testnode *n;
+       struct rpst_node *rn;
+       struct rpst_iterator it;
+       struct timeval start;
+       struct timeval end;
+       unsigned int done;
+
+       printf("quering max_y=%" PRIu64 " min_x=%" PRIu64 " max_x=%" PRIu64
+           "\n",
+           max_y, min_x, max_x);
+       done = 0;
+       gettimeofday(&start, NULL);
+       for (rn = rpst_iterate_first(&t, max_y, min_x, max_x, &it);
+           rn != NULL;
+           rn = rpst_iterate_next(&it)) {
+               done++;
+#if 0
+               printf("found %p x=%" PRIu64 " y=%" PRIu64 "\n",
+                   (void *)rn, rn->n_x, rn->n_y);
+#endif
+               n = (void *)rn;
+               assert(!n->found);
+               n->found = true;
+       }
+       gettimeofday(&end, NULL);
+       printf("%u nodes found in %ju usecs\n", done,
+           tvdiff(&end, &start));
+
+       gettimeofday(&start, NULL);
+       for (n = h; n != NULL; n = n->next) {
+               assert(n->failed ||
+                   n->found == rpst_iterator_match_p(&n->n, &it));
+               n->found = false;
+       }
+       gettimeofday(&end, NULL);
+       printf("(linear search took %ju usecs)\n", tvdiff(&end, &start));
+       return done;
+}
+
+int
+main(int argc, char *argv[])
+{
+       struct testnode *n;
+       unsigned int i;
+       struct rpst_iterator it;
+       struct timeval start;
+       struct timeval end;
+       uint64_t min_y = UINT64_MAX;
+       uint64_t max_y = 0;
+       uint64_t min_x = UINT64_MAX;
+       uint64_t max_x = 0;
+       uint64_t w;
+       unsigned int done;
+       unsigned int fail;
+       unsigned int num = 500000;
+
+       rpst_init_tree(&t);
+       rpst_dump_tree(&t);
+       assert(NULL == rpst_iterate_first(&t, UINT64_MAX, 0, UINT64_MAX, &it));
+
+       for (i = 0; i < num; i++) {
+               n = malloc(sizeof(*n));
+               if (i > 499000) {
+                       n->n.n_x = 10;
+                       n->n.n_y = random();
+               } else if (i > 400000) {
+                       n->n.n_x = i;
+                       n->n.n_y = random();
+               } else {
+                       n->n.n_x = random();
+                       n->n.n_y = random();
+               }
+               if (n->n.n_y < min_y) {
+                       min_y = n->n.n_y;
+               }
+               if (n->n.n_y > max_y) {
+                       max_y = n->n.n_y;
+               }
+               if (n->n.n_x < min_x) {
+                       min_x = n->n.n_x;
+               }
+               if (n->n.n_x > max_x) {
+                       max_x = n->n.n_x;
+               }
+               n->found = false;
+               n->failed = false;
+               n->next = h;
+               h = n;
+       }
+
+       done = 0;
+       fail = 0;
+       gettimeofday(&start, NULL);
+       for (n = h; n != NULL; n = n->next) {
+               struct rpst_node *o;
+#if 0
+               printf("insert %p x=%" PRIu64 " y=%" PRIu64 "\n",
+                   n, n->n.n_x, n->n.n_y);
+#endif
+               o = rpst_insert_node(&t, &n->n);
+               if (o == NULL) {
+                       done++;
+               } else {
+                       n->failed = true;
+                       fail++;
+               }
+       }
+       gettimeofday(&end, NULL);
+       printf("%u nodes inserted and %u insertion failed in %ju usecs\n",
+           done, fail,
+           tvdiff(&end, &start));
+
+       assert(min_y == 0 || 0 == query(min_y - 1, 0, UINT64_MAX));
+       assert(max_x == UINT64_MAX ||
+           0 == query(UINT64_MAX, max_x + 1, UINT64_MAX));
+       assert(min_x == 0 || 0 == query(UINT64_MAX, 0, min_x - 1));
+
+       done = query(max_y, min_x, max_x);
+       assert(done == num - fail);
+
+       done = query(UINT64_MAX, 0, UINT64_MAX);
+       assert(done == num - fail);
+
+       w = max_x - min_x;
+       query(max_y / 2, min_x, max_x);
+       query(max_y, min_x + w / 2, max_x);
+       query(max_y / 2, min_x + w / 2, max_x);
+       query(max_y / 2, min_x, max_x - w / 2);
+       query(max_y / 2, min_x + w / 3, max_x - w / 3);
+       query(max_y - 1, min_x + 1, max_x - 1);
+       query(UINT64_MAX, 10, 10);
+
+       done = 0;
+       gettimeofday(&start, NULL);
+       for (n = h; n != NULL; n = n->next) {
+               if (n->failed) {
+                       continue;
+               }
+#if 0
+               printf("remove %p x=%" PRIu64 " y=%" PRIu64 "\n",
+                   n, n->n.n_x, n->n.n_y);
+#endif
+               rpst_remove_node(&t, &n->n);
+               done++;
+       }
+       gettimeofday(&end, NULL);
+       printf("%u nodes removed in %ju usecs\n", done,
+           tvdiff(&end, &start));
+
+       rpst_dump_tree(&t);
+}
+#endif /* defined(UNITTEST) */
diff --git a/common/lib/libc/gmon/mcount.c b/common/lib/libc/gmon/mcount.c
new file mode 100644 (file)
index 0000000..0a0c716
--- /dev/null
@@ -0,0 +1,270 @@
+/*     $NetBSD: mcount.c,v 1.8 2009/01/05 18:06:57 pooka Exp $ */
+
+/*
+ * Copyright (c) 2003, 2004 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Nathan J. Williams for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed for the NetBSD Project by
+ *     Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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.
+ */
+
+/*-
+ * Copyright (c) 1983, 1992, 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.
+ * 3. 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 building a standalone libkern, don't include mcount. */
+#if (!defined(_KERNEL) || defined(GPROF)) && !defined(_STANDALONE)
+
+#ifdef _KERNEL_OPT
+#include "opt_multiprocessor.h"
+#endif
+
+#include <sys/cdefs.h>
+#if !defined(lint) && !defined(_KERNEL) && defined(LIBC_SCCS)
+#if 0
+static char sccsid[] = "@(#)mcount.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: mcount.c,v 1.8 2009/01/05 18:06:57 pooka Exp $");
+#endif
+#endif
+
+#include <sys/param.h>
+#include <sys/gmon.h>
+
+#ifndef _KERNEL
+#include "reentrant.h"
+#endif
+
+#ifdef _REENTRANT
+extern thread_key_t _gmonkey;
+extern struct gmonparam _gmondummy;
+struct gmonparam *_m_gmon_alloc(void);
+#endif
+
+_MCOUNT_DECL __P((u_long, u_long))
+#ifdef _KERNEL
+    __attribute__((__no_instrument_function__))
+#endif
+    __used;
+
+/* XXX: make these interfaces */
+#ifdef _RUMPKERNEL
+#undef MCOUNT_ENTER
+#define MCOUNT_ENTER
+#undef MCOUNT_EXIT
+#define MCOUNT_EXIT
+#undef MCOUNT
+#define MCOUNT
+#endif
+
+/*
+ * mcount is called on entry to each function compiled with the profiling
+ * switch set.  _mcount(), which is declared in a machine-dependent way
+ * with _MCOUNT_DECL, does the actual work and is either inlined into a
+ * C routine or called by an assembly stub.  In any case, this magic is
+ * taken care of by the MCOUNT definition in <machine/profile.h>.
+ *
+ * _mcount updates data structures that represent traversals of the
+ * program's call graph edges.  frompc and selfpc are the return
+ * address and function address that represents the given call graph edge.
+ * 
+ * Note: the original BSD code used the same variable (frompcindex) for
+ * both frompcindex and frompc.  Any reasonable, modern compiler will
+ * perform this optimization.
+ */
+_MCOUNT_DECL(frompc, selfpc)   /* _mcount; may be static, inline, etc */
+       u_long frompc, selfpc;
+{
+       u_short *frompcindex;
+       struct tostruct *top, *prevtop;
+       struct gmonparam *p;
+       long toindex;
+#if defined(_KERNEL) && !defined(_RUMPKERNEL)
+       int s;
+#endif
+
+#if defined(_REENTRANT) && !defined(_KERNEL)
+       if (__isthreaded) {
+               p = thr_getspecific(_gmonkey);
+               if (p == NULL) {
+                       /* Prevent recursive calls while allocating */
+                       thr_setspecific(_gmonkey, &_gmondummy);
+                       p = _m_gmon_alloc();
+               }
+       } else
+#endif
+               p = &_gmonparam;
+       /*
+        * check that we are profiling
+        * and that we aren't recursively invoked.
+        */
+       if (p->state != GMON_PROF_ON)
+               return;
+#ifdef _KERNEL
+       MCOUNT_ENTER;
+#endif
+       p->state = GMON_PROF_BUSY;
+       /*
+        * check that frompcindex is a reasonable pc value.
+        * for example: signal catchers get called from the stack,
+        *              not from text space.  too bad.
+        */
+       frompc -= p->lowpc;
+       if (frompc > p->textsize)
+               goto done;
+
+#if (HASHFRACTION & (HASHFRACTION - 1)) == 0
+       if (p->hashfraction == HASHFRACTION)
+               frompcindex =
+                   &p->froms[
+                   (size_t)(frompc / (HASHFRACTION * sizeof(*p->froms)))];
+       else
+#endif
+               frompcindex =
+                   &p->froms[
+                   (size_t)(frompc / (p->hashfraction * sizeof(*p->froms)))];
+       toindex = *frompcindex;
+       if (toindex == 0) {
+               /*
+                *      first time traversing this arc
+                */
+               toindex = ++p->tos[0].link;
+               if (toindex >= p->tolimit)
+                       /* halt further profiling */
+                       goto overflow;
+
+               *frompcindex = (u_short)toindex;
+               top = &p->tos[(size_t)toindex];
+               top->selfpc = selfpc;
+               top->count = 1;
+               top->link = 0;
+               goto done;
+       }
+       top = &p->tos[(size_t)toindex];
+       if (top->selfpc == selfpc) {
+               /*
+                * arc at front of chain; usual case.
+                */
+               top->count++;
+               goto done;
+       }
+       /*
+        * have to go looking down chain for it.
+        * top points to what we are looking at,
+        * prevtop points to previous top.
+        * we know it is not at the head of the chain.
+        */
+       for (; /* goto done */; ) {
+               if (top->link == 0) {
+                       /*
+                        * top is end of the chain and none of the chain
+                        * had top->selfpc == selfpc.
+                        * so we allocate a new tostruct
+                        * and link it to the head of the chain.
+                        */
+                       toindex = ++p->tos[0].link;
+                       if (toindex >= p->tolimit)
+                               goto overflow;
+
+                       top = &p->tos[(size_t)toindex];
+                       top->selfpc = selfpc;
+                       top->count = 1;
+                       top->link = *frompcindex;
+                       *frompcindex = (u_short)toindex;
+                       goto done;
+               }
+               /*
+                * otherwise, check the next arc on the chain.
+                */
+               prevtop = top;
+               top = &p->tos[top->link];
+               if (top->selfpc == selfpc) {
+                       /*
+                        * there it is.
+                        * increment its count
+                        * move it to the head of the chain.
+                        */
+                       top->count++;
+                       toindex = prevtop->link;
+                       prevtop->link = top->link;
+                       top->link = *frompcindex;
+                       *frompcindex = (u_short)toindex;
+                       goto done;
+               }
+               
+       }
+done:
+       p->state = GMON_PROF_ON;
+#ifdef _KERNEL
+       MCOUNT_EXIT;
+#endif
+       return;
+overflow:
+       p->state = GMON_PROF_ERROR;
+#ifdef _KERNEL
+       MCOUNT_EXIT;
+#endif
+       return;
+}
+
+#ifdef MCOUNT
+/*
+ * Actual definition of mcount function.  Defined in <machine/profile.h>,
+ * which is included by <sys/gmon.h>.
+ */
+MCOUNT
+#endif
+
+#endif /* (!_KERNEL || GPROF) && !_STANDALONE */
diff --git a/common/lib/libc/hash/rmd160/rmd160.c b/common/lib/libc/hash/rmd160/rmd160.c
new file mode 100644 (file)
index 0000000..ea107e3
--- /dev/null
@@ -0,0 +1,393 @@
+/*     $NetBSD: rmd160.c,v 1.5 2009/08/21 09:40:51 skrll Exp $ */
+/*     $KAME: rmd160.c,v 1.2 2003/07/25 09:37:55 itojun Exp $  */
+/*     $OpenBSD: rmd160.c,v 1.3 2001/09/26 21:40:13 markus Exp $       */
+/*
+ * Copyright (c) 2001 Markus Friedl.  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 ``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 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.
+ */
+/*
+ * Preneel, Bosselaers, Dobbertin, "The Cryptographic Hash Function RIPEMD-160",
+ * RSA Laboratories, CryptoBytes, Volume 3, Number 2, Autumn 1997,
+ * ftp://ftp.rsasecurity.com/pub/cryptobytes/crypto3n2.pdf
+ */
+
+#include <sys/cdefs.h>
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+__KERNEL_RCSID(0, "$NetBSD: rmd160.c,v 1.5 2009/08/21 09:40:51 skrll Exp $");
+
+#include <lib/libkern/libkern.h>
+
+#else
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: rmd160.c,v 1.5 2009/08/21 09:40:51 skrll Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <string.h>
+
+#endif
+
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/rmd160.h>
+
+
+#define PUT_64BIT_LE(cp, value) do { \
+       (cp)[7] = (u_char)((value) >> 56); \
+       (cp)[6] = (u_char)((value) >> 48); \
+       (cp)[5] = (u_char)((value) >> 40); \
+       (cp)[4] = (u_char)((value) >> 32); \
+       (cp)[3] = (u_char)((value) >> 24); \
+       (cp)[2] = (u_char)((value) >> 16); \
+       (cp)[1] = (u_char)((value) >> 8); \
+       (cp)[0] = (u_char)((value)); } while (/*CONSTCOND*/0)
+
+#define PUT_32BIT_LE(cp, value) do { \
+       (cp)[3] = (value) >> 24; \
+       (cp)[2] = (value) >> 16; \
+       (cp)[1] = (value) >> 8; \
+       (cp)[0] = (value); } while (/*CONSTCOND*/0)
+
+#define        H0      0x67452301U
+#define        H1      0xEFCDAB89U
+#define        H2      0x98BADCFEU
+#define        H3      0x10325476U
+#define        H4      0xC3D2E1F0U
+
+#define        K0      0x00000000U
+#define        K1      0x5A827999U
+#define        K2      0x6ED9EBA1U
+#define        K3      0x8F1BBCDCU
+#define        K4      0xA953FD4EU
+
+#define        KK0     0x50A28BE6U
+#define        KK1     0x5C4DD124U
+#define        KK2     0x6D703EF3U
+#define        KK3     0x7A6D76E9U
+#define        KK4     0x00000000U
+
+/* rotate x left n bits.  */
+#define ROL(n, x) (((x) << (n)) | ((x) >> (32-(n))))
+
+#define F0(x, y, z) ((x) ^ (y) ^ (z))
+#define F1(x, y, z) (((x) & (y)) | ((~x) & (z)))
+#define F2(x, y, z) (((x) | (~y)) ^ (z))
+#define F3(x, y, z) (((x) & (z)) | ((y) & (~z)))
+#define F4(x, y, z) ((x) ^ ((y) | (~z)))
+
+#define R(a, b, c, d, e, Fj, Kj, sj, rj) \
+       do { \
+               a = ROL(sj, a + Fj(b,c,d) + X(rj) + Kj) + e; \
+               c = ROL(10, c); \
+       } while(/*CONSTCOND*/0)
+
+#define X(i)   x[i]
+
+static const u_char PADDING[64] = {
+       0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#if defined(__weak_alias)
+__weak_alias(RMD160Init,_RMD160Init) 
+__weak_alias(RMD160Update,_RMD160Update)
+__weak_alias(RMD160Final,_RMD160Final)
+__weak_alias(RMD160Transform,_RMD160Transform)
+#endif
+#endif
+
+void
+RMD160Init(RMD160_CTX *ctx)
+{
+       ctx->count = 0;
+       ctx->state[0] = H0;
+       ctx->state[1] = H1;
+       ctx->state[2] = H2;
+       ctx->state[3] = H3;
+       ctx->state[4] = H4;
+}
+
+void
+RMD160Update(RMD160_CTX *ctx, const u_char *input, uint32_t len)
+{
+       uint32_t have, off, need;
+
+       have = (uint32_t)((ctx->count/8) % 64);
+       need = 64 - have;
+       ctx->count += 8 * len;
+       off = 0;
+
+       if (len >= need) {
+               if (have) {
+                       memcpy(ctx->buffer + have, input, (size_t)need);
+                       RMD160Transform(ctx->state, ctx->buffer);
+                       off = need;
+                       have = 0;
+               }
+               /* now the buffer is empty */
+               while (off + 64 <= len) {
+                       RMD160Transform(ctx->state, input+off);
+                       off += 64;
+               }
+       }
+       if (off < len)
+               memcpy(ctx->buffer + have, input+off, (size_t)len-off);
+}
+
+void
+RMD160Final(u_char digest[20], RMD160_CTX *ctx)
+{
+       int i;
+       u_char size[8];
+       uint32_t padlen;
+
+       PUT_64BIT_LE(size, ctx->count);
+
+       /*
+        * pad to 64 byte blocks, at least one byte from PADDING plus 8 bytes
+        * for the size
+        */
+       padlen = (uint32_t)(64 - ((ctx->count/8) % 64));
+       if (padlen < 1 + 8)
+               padlen += 64;
+       RMD160Update(ctx, PADDING, padlen - 8);         /* padlen - 8 <= 64 */
+       RMD160Update(ctx, size, 8);
+
+       if (digest != NULL)
+               for (i = 0; i < 5; i++)
+                       PUT_32BIT_LE(digest + i*4, ctx->state[i]);
+
+       memset(ctx, 0, sizeof (*ctx));
+}
+
+void
+RMD160Transform(uint32_t state[5], const u_char block[64])
+{
+       uint32_t a, b, c, d, e, aa, bb, cc, dd, ee, t, x[16];
+
+#if BYTE_ORDER == LITTLE_ENDIAN
+       memcpy(x, block, (size_t)64);
+#else
+       int i;
+
+       for (i = 0; i < 16; i++)
+               x[i] = le32dec(block+i*4);
+#endif
+
+       a = state[0];
+       b = state[1];
+       c = state[2];
+       d = state[3];
+       e = state[4];
+
+       /* Round 1 */
+       R(a, b, c, d, e, F0, K0, 11,  0);
+       R(e, a, b, c, d, F0, K0, 14,  1);
+       R(d, e, a, b, c, F0, K0, 15,  2);
+       R(c, d, e, a, b, F0, K0, 12,  3);
+       R(b, c, d, e, a, F0, K0,  5,  4);
+       R(a, b, c, d, e, F0, K0,  8,  5);
+       R(e, a, b, c, d, F0, K0,  7,  6);
+       R(d, e, a, b, c, F0, K0,  9,  7);
+       R(c, d, e, a, b, F0, K0, 11,  8);
+       R(b, c, d, e, a, F0, K0, 13,  9);
+       R(a, b, c, d, e, F0, K0, 14, 10);
+       R(e, a, b, c, d, F0, K0, 15, 11);
+       R(d, e, a, b, c, F0, K0,  6, 12);
+       R(c, d, e, a, b, F0, K0,  7, 13);
+       R(b, c, d, e, a, F0, K0,  9, 14);
+       R(a, b, c, d, e, F0, K0,  8, 15); /* #15 */
+       /* Round 2 */
+       R(e, a, b, c, d, F1, K1,  7,  7);
+       R(d, e, a, b, c, F1, K1,  6,  4);
+       R(c, d, e, a, b, F1, K1,  8, 13);
+       R(b, c, d, e, a, F1, K1, 13,  1);
+       R(a, b, c, d, e, F1, K1, 11, 10);
+       R(e, a, b, c, d, F1, K1,  9,  6);
+       R(d, e, a, b, c, F1, K1,  7, 15);
+       R(c, d, e, a, b, F1, K1, 15,  3);
+       R(b, c, d, e, a, F1, K1,  7, 12);
+       R(a, b, c, d, e, F1, K1, 12,  0);
+       R(e, a, b, c, d, F1, K1, 15,  9);
+       R(d, e, a, b, c, F1, K1,  9,  5);
+       R(c, d, e, a, b, F1, K1, 11,  2);
+       R(b, c, d, e, a, F1, K1,  7, 14);
+       R(a, b, c, d, e, F1, K1, 13, 11);
+       R(e, a, b, c, d, F1, K1, 12,  8); /* #31 */
+       /* Round 3 */
+       R(d, e, a, b, c, F2, K2, 11,  3);
+       R(c, d, e, a, b, F2, K2, 13, 10);
+       R(b, c, d, e, a, F2, K2,  6, 14);
+       R(a, b, c, d, e, F2, K2,  7,  4);
+       R(e, a, b, c, d, F2, K2, 14,  9);
+       R(d, e, a, b, c, F2, K2,  9, 15);
+       R(c, d, e, a, b, F2, K2, 13,  8);
+       R(b, c, d, e, a, F2, K2, 15,  1);
+       R(a, b, c, d, e, F2, K2, 14,  2);
+       R(e, a, b, c, d, F2, K2,  8,  7);
+       R(d, e, a, b, c, F2, K2, 13,  0);
+       R(c, d, e, a, b, F2, K2,  6,  6);
+       R(b, c, d, e, a, F2, K2,  5, 13);
+       R(a, b, c, d, e, F2, K2, 12, 11);
+       R(e, a, b, c, d, F2, K2,  7,  5);
+       R(d, e, a, b, c, F2, K2,  5, 12); /* #47 */
+       /* Round 4 */
+       R(c, d, e, a, b, F3, K3, 11,  1);
+       R(b, c, d, e, a, F3, K3, 12,  9);
+       R(a, b, c, d, e, F3, K3, 14, 11);
+       R(e, a, b, c, d, F3, K3, 15, 10);
+       R(d, e, a, b, c, F3, K3, 14,  0);
+       R(c, d, e, a, b, F3, K3, 15,  8);
+       R(b, c, d, e, a, F3, K3,  9, 12);
+       R(a, b, c, d, e, F3, K3,  8,  4);
+       R(e, a, b, c, d, F3, K3,  9, 13);
+       R(d, e, a, b, c, F3, K3, 14,  3);
+       R(c, d, e, a, b, F3, K3,  5,  7);
+       R(b, c, d, e, a, F3, K3,  6, 15);
+       R(a, b, c, d, e, F3, K3,  8, 14);
+       R(e, a, b, c, d, F3, K3,  6,  5);
+       R(d, e, a, b, c, F3, K3,  5,  6);
+       R(c, d, e, a, b, F3, K3, 12,  2); /* #63 */
+       /* Round 5 */
+       R(b, c, d, e, a, F4, K4,  9,  4);
+       R(a, b, c, d, e, F4, K4, 15,  0);
+       R(e, a, b, c, d, F4, K4,  5,  5);
+       R(d, e, a, b, c, F4, K4, 11,  9);
+       R(c, d, e, a, b, F4, K4,  6,  7);
+       R(b, c, d, e, a, F4, K4,  8, 12);
+       R(a, b, c, d, e, F4, K4, 13,  2);
+       R(e, a, b, c, d, F4, K4, 12, 10);
+       R(d, e, a, b, c, F4, K4,  5, 14);
+       R(c, d, e, a, b, F4, K4, 12,  1);
+       R(b, c, d, e, a, F4, K4, 13,  3);
+       R(a, b, c, d, e, F4, K4, 14,  8);
+       R(e, a, b, c, d, F4, K4, 11, 11);
+       R(d, e, a, b, c, F4, K4,  8,  6);
+       R(c, d, e, a, b, F4, K4,  5, 15);
+       R(b, c, d, e, a, F4, K4,  6, 13); /* #79 */
+
+       aa = a ; bb = b; cc = c; dd = d; ee = e;
+
+       a = state[0];
+       b = state[1];
+       c = state[2];
+       d = state[3];
+       e = state[4];
+
+       /* Parallel round 1 */
+       R(a, b, c, d, e, F4, KK0,  8,  5);
+       R(e, a, b, c, d, F4, KK0,  9, 14);
+       R(d, e, a, b, c, F4, KK0,  9,  7);
+       R(c, d, e, a, b, F4, KK0, 11,  0);
+       R(b, c, d, e, a, F4, KK0, 13,  9);
+       R(a, b, c, d, e, F4, KK0, 15,  2);
+       R(e, a, b, c, d, F4, KK0, 15, 11);
+       R(d, e, a, b, c, F4, KK0,  5,  4);
+       R(c, d, e, a, b, F4, KK0,  7, 13);
+       R(b, c, d, e, a, F4, KK0,  7,  6);
+       R(a, b, c, d, e, F4, KK0,  8, 15);
+       R(e, a, b, c, d, F4, KK0, 11,  8);
+       R(d, e, a, b, c, F4, KK0, 14,  1);
+       R(c, d, e, a, b, F4, KK0, 14, 10);
+       R(b, c, d, e, a, F4, KK0, 12,  3);
+       R(a, b, c, d, e, F4, KK0,  6, 12); /* #15 */
+       /* Parallel round 2 */
+       R(e, a, b, c, d, F3, KK1,  9,  6);
+       R(d, e, a, b, c, F3, KK1, 13, 11);
+       R(c, d, e, a, b, F3, KK1, 15,  3);
+       R(b, c, d, e, a, F3, KK1,  7,  7);
+       R(a, b, c, d, e, F3, KK1, 12,  0);
+       R(e, a, b, c, d, F3, KK1,  8, 13);
+       R(d, e, a, b, c, F3, KK1,  9,  5);
+       R(c, d, e, a, b, F3, KK1, 11, 10);
+       R(b, c, d, e, a, F3, KK1,  7, 14);
+       R(a, b, c, d, e, F3, KK1,  7, 15);
+       R(e, a, b, c, d, F3, KK1, 12,  8);
+       R(d, e, a, b, c, F3, KK1,  7, 12);
+       R(c, d, e, a, b, F3, KK1,  6,  4);
+       R(b, c, d, e, a, F3, KK1, 15,  9);
+       R(a, b, c, d, e, F3, KK1, 13,  1);
+       R(e, a, b, c, d, F3, KK1, 11,  2); /* #31 */
+       /* Parallel round 3 */
+       R(d, e, a, b, c, F2, KK2,  9, 15);
+       R(c, d, e, a, b, F2, KK2,  7,  5);
+       R(b, c, d, e, a, F2, KK2, 15,  1);
+       R(a, b, c, d, e, F2, KK2, 11,  3);
+       R(e, a, b, c, d, F2, KK2,  8,  7);
+       R(d, e, a, b, c, F2, KK2,  6, 14);
+       R(c, d, e, a, b, F2, KK2,  6,  6);
+       R(b, c, d, e, a, F2, KK2, 14,  9);
+       R(a, b, c, d, e, F2, KK2, 12, 11);
+       R(e, a, b, c, d, F2, KK2, 13,  8);
+       R(d, e, a, b, c, F2, KK2,  5, 12);
+       R(c, d, e, a, b, F2, KK2, 14,  2);
+       R(b, c, d, e, a, F2, KK2, 13, 10);
+       R(a, b, c, d, e, F2, KK2, 13,  0);
+       R(e, a, b, c, d, F2, KK2,  7,  4);
+       R(d, e, a, b, c, F2, KK2,  5, 13); /* #47 */
+       /* Parallel round 4 */
+       R(c, d, e, a, b, F1, KK3, 15,  8);
+       R(b, c, d, e, a, F1, KK3,  5,  6);
+       R(a, b, c, d, e, F1, KK3,  8,  4);
+       R(e, a, b, c, d, F1, KK3, 11,  1);
+       R(d, e, a, b, c, F1, KK3, 14,  3);
+       R(c, d, e, a, b, F1, KK3, 14, 11);
+       R(b, c, d, e, a, F1, KK3,  6, 15);
+       R(a, b, c, d, e, F1, KK3, 14,  0);
+       R(e, a, b, c, d, F1, KK3,  6,  5);
+       R(d, e, a, b, c, F1, KK3,  9, 12);
+       R(c, d, e, a, b, F1, KK3, 12,  2);
+       R(b, c, d, e, a, F1, KK3,  9, 13);
+       R(a, b, c, d, e, F1, KK3, 12,  9);
+       R(e, a, b, c, d, F1, KK3,  5,  7);
+       R(d, e, a, b, c, F1, KK3, 15, 10);
+       R(c, d, e, a, b, F1, KK3,  8, 14); /* #63 */
+       /* Parallel round 5 */
+       R(b, c, d, e, a, F0, KK4,  8, 12);
+       R(a, b, c, d, e, F0, KK4,  5, 15);
+       R(e, a, b, c, d, F0, KK4, 12, 10);
+       R(d, e, a, b, c, F0, KK4,  9,  4);
+       R(c, d, e, a, b, F0, KK4, 12,  1);
+       R(b, c, d, e, a, F0, KK4,  5,  5);
+       R(a, b, c, d, e, F0, KK4, 14,  8);
+       R(e, a, b, c, d, F0, KK4,  6,  7);
+       R(d, e, a, b, c, F0, KK4,  8,  6);
+       R(c, d, e, a, b, F0, KK4, 13,  2);
+       R(b, c, d, e, a, F0, KK4,  6, 13);
+       R(a, b, c, d, e, F0, KK4,  5, 14);
+       R(e, a, b, c, d, F0, KK4, 15,  0);
+       R(d, e, a, b, c, F0, KK4, 13,  3);
+       R(c, d, e, a, b, F0, KK4, 11,  9);
+       R(b, c, d, e, a, F0, KK4, 11, 11); /* #79 */
+
+       t =        state[1] + cc + d;
+       state[1] = state[2] + dd + e;
+       state[2] = state[3] + ee + a;
+       state[3] = state[4] + aa + b;
+       state[4] = state[0] + bb + c;
+       state[0] = t;
+}
diff --git a/common/lib/libc/hash/sha1/sha1.c b/common/lib/libc/hash/sha1/sha1.c
new file mode 100644 (file)
index 0000000..cbd60fc
--- /dev/null
@@ -0,0 +1,289 @@
+/*     $NetBSD: sha1.c,v 1.6 2009/11/06 20:31:18 joerg Exp $   */
+/*     $OpenBSD: sha1.c,v 1.9 1997/07/23 21:12:32 kstailey Exp $       */
+
+/*
+ * SHA-1 in C
+ * By Steve Reid <steve@edmweb.com>
+ * 100% Public Domain
+ *
+ * Test Vectors (from FIPS PUB 180-1)
+ * "abc"
+ *   A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
+ * "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
+ *   84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
+ * A million repetitions of "a"
+ *   34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
+ */
+
+#define SHA1HANDSOFF           /* Copies data before messing with it. */
+
+#include <sys/cdefs.h>
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+__KERNEL_RCSID(0, "$NetBSD: sha1.c,v 1.6 2009/11/06 20:31:18 joerg Exp $");
+
+#include <lib/libkern/libkern.h>
+
+#else
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sha1.c,v 1.6 2009/11/06 20:31:18 joerg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <string.h>
+
+#endif
+
+#include <sys/types.h>
+#include <sys/sha1.h>
+
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#if !HAVE_SHA1_H
+
+#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
+
+/*
+ * blk0() and blk() perform the initial expand.
+ * I got the idea of expanding during the round function from SSLeay
+ */
+#if BYTE_ORDER == LITTLE_ENDIAN
+# define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
+    |(rol(block->l[i],8)&0x00FF00FF))
+#else
+# define blk0(i) block->l[i]
+#endif
+#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
+    ^block->l[(i+2)&15]^block->l[i&15],1))
+
+/*
+ * (R0+R1), R2, R3, R4 are the different operations (rounds) used in SHA1
+ */
+#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
+#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
+#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
+#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
+#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
+
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#if defined(__weak_alias)
+__weak_alias(SHA1Transform,_SHA1Transform)
+__weak_alias(SHA1Init,_SHA1Init)
+__weak_alias(SHA1Update,_SHA1Update)
+__weak_alias(SHA1Final,_SHA1Final)
+#endif
+#endif
+
+typedef union {
+    uint8_t c[64];
+    uint32_t l[16];
+} CHAR64LONG16;
+
+/* old sparc64 gcc could not compile this */
+#undef SPARC64_GCC_WORKAROUND
+#if defined(__sparc64__) && defined(__GNUC__) && __GNUC__ < 3
+#define SPARC64_GCC_WORKAROUND
+#endif
+
+#ifdef SPARC64_GCC_WORKAROUND
+void do_R01(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *);
+void do_R2(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *);
+void do_R3(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *);
+void do_R4(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *);
+
+#define nR0(v,w,x,y,z,i) R0(*v,*w,*x,*y,*z,i)
+#define nR1(v,w,x,y,z,i) R1(*v,*w,*x,*y,*z,i)
+#define nR2(v,w,x,y,z,i) R2(*v,*w,*x,*y,*z,i)
+#define nR3(v,w,x,y,z,i) R3(*v,*w,*x,*y,*z,i)
+#define nR4(v,w,x,y,z,i) R4(*v,*w,*x,*y,*z,i)
+
+void
+do_R01(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block)
+{
+    nR0(a,b,c,d,e, 0); nR0(e,a,b,c,d, 1); nR0(d,e,a,b,c, 2); nR0(c,d,e,a,b, 3);
+    nR0(b,c,d,e,a, 4); nR0(a,b,c,d,e, 5); nR0(e,a,b,c,d, 6); nR0(d,e,a,b,c, 7);
+    nR0(c,d,e,a,b, 8); nR0(b,c,d,e,a, 9); nR0(a,b,c,d,e,10); nR0(e,a,b,c,d,11);
+    nR0(d,e,a,b,c,12); nR0(c,d,e,a,b,13); nR0(b,c,d,e,a,14); nR0(a,b,c,d,e,15);
+    nR1(e,a,b,c,d,16); nR1(d,e,a,b,c,17); nR1(c,d,e,a,b,18); nR1(b,c,d,e,a,19);
+}
+
+void
+do_R2(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block)
+{
+    nR2(a,b,c,d,e,20); nR2(e,a,b,c,d,21); nR2(d,e,a,b,c,22); nR2(c,d,e,a,b,23);
+    nR2(b,c,d,e,a,24); nR2(a,b,c,d,e,25); nR2(e,a,b,c,d,26); nR2(d,e,a,b,c,27);
+    nR2(c,d,e,a,b,28); nR2(b,c,d,e,a,29); nR2(a,b,c,d,e,30); nR2(e,a,b,c,d,31);
+    nR2(d,e,a,b,c,32); nR2(c,d,e,a,b,33); nR2(b,c,d,e,a,34); nR2(a,b,c,d,e,35);
+    nR2(e,a,b,c,d,36); nR2(d,e,a,b,c,37); nR2(c,d,e,a,b,38); nR2(b,c,d,e,a,39);
+}
+
+void
+do_R3(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block)
+{
+    nR3(a,b,c,d,e,40); nR3(e,a,b,c,d,41); nR3(d,e,a,b,c,42); nR3(c,d,e,a,b,43);
+    nR3(b,c,d,e,a,44); nR3(a,b,c,d,e,45); nR3(e,a,b,c,d,46); nR3(d,e,a,b,c,47);
+    nR3(c,d,e,a,b,48); nR3(b,c,d,e,a,49); nR3(a,b,c,d,e,50); nR3(e,a,b,c,d,51);
+    nR3(d,e,a,b,c,52); nR3(c,d,e,a,b,53); nR3(b,c,d,e,a,54); nR3(a,b,c,d,e,55);
+    nR3(e,a,b,c,d,56); nR3(d,e,a,b,c,57); nR3(c,d,e,a,b,58); nR3(b,c,d,e,a,59);
+}
+
+void
+do_R4(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block)
+{
+    nR4(a,b,c,d,e,60); nR4(e,a,b,c,d,61); nR4(d,e,a,b,c,62); nR4(c,d,e,a,b,63);
+    nR4(b,c,d,e,a,64); nR4(a,b,c,d,e,65); nR4(e,a,b,c,d,66); nR4(d,e,a,b,c,67);
+    nR4(c,d,e,a,b,68); nR4(b,c,d,e,a,69); nR4(a,b,c,d,e,70); nR4(e,a,b,c,d,71);
+    nR4(d,e,a,b,c,72); nR4(c,d,e,a,b,73); nR4(b,c,d,e,a,74); nR4(a,b,c,d,e,75);
+    nR4(e,a,b,c,d,76); nR4(d,e,a,b,c,77); nR4(c,d,e,a,b,78); nR4(b,c,d,e,a,79);
+}
+#endif
+
+/*
+ * Hash a single 512-bit block. This is the core of the algorithm.
+ */
+void SHA1Transform(uint32_t state[5], const uint8_t buffer[64])
+{
+    uint32_t a, b, c, d, e;
+    CHAR64LONG16 *block;
+
+#ifdef SHA1HANDSOFF
+    CHAR64LONG16 workspace;
+#endif
+
+    _DIAGASSERT(buffer != 0);
+    _DIAGASSERT(state != 0);
+
+#ifdef SHA1HANDSOFF
+    block = &workspace;
+    (void)memcpy(block, buffer, 64);
+#else
+    block = (CHAR64LONG16 *)(void *)buffer;
+#endif
+
+    /* Copy context->state[] to working vars */
+    a = state[0];
+    b = state[1];
+    c = state[2];
+    d = state[3];
+    e = state[4];
+
+#ifdef SPARC64_GCC_WORKAROUND
+    do_R01(&a, &b, &c, &d, &e, block);
+    do_R2(&a, &b, &c, &d, &e, block);
+    do_R3(&a, &b, &c, &d, &e, block);
+    do_R4(&a, &b, &c, &d, &e, block);
+#else
+    /* 4 rounds of 20 operations each. Loop unrolled. */
+    R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
+    R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
+    R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
+    R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
+    R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
+    R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
+    R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
+    R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
+    R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
+    R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
+    R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
+    R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
+    R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
+    R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
+    R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
+    R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
+    R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
+    R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
+    R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
+    R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
+#endif
+
+    /* Add the working vars back into context.state[] */
+    state[0] += a;
+    state[1] += b;
+    state[2] += c;
+    state[3] += d;
+    state[4] += e;
+
+    /* Wipe variables */
+    a = b = c = d = e = 0;
+}
+
+
+/*
+ * SHA1Init - Initialize new context
+ */
+void SHA1Init(SHA1_CTX *context)
+{
+
+    _DIAGASSERT(context != 0);
+
+    /* SHA1 initialization constants */
+    context->state[0] = 0x67452301;
+    context->state[1] = 0xEFCDAB89;
+    context->state[2] = 0x98BADCFE;
+    context->state[3] = 0x10325476;
+    context->state[4] = 0xC3D2E1F0;
+    context->count[0] = context->count[1] = 0;
+}
+
+
+/*
+ * Run your data through this.
+ */
+void SHA1Update(SHA1_CTX *context, const uint8_t *data, unsigned int len)
+{
+    unsigned int i, j;
+
+    _DIAGASSERT(context != 0);
+    _DIAGASSERT(data != 0);
+
+    j = context->count[0];
+    if ((context->count[0] += len << 3) < j)
+       context->count[1] += (len>>29)+1;
+    j = (j >> 3) & 63;
+    if ((j + len) > 63) {
+       (void)memcpy(&context->buffer[j], data, (i = 64-j));
+       SHA1Transform(context->state, context->buffer);
+       for ( ; i + 63 < len; i += 64)
+           SHA1Transform(context->state, &data[i]);
+       j = 0;
+    } else {
+       i = 0;
+    }
+    (void)memcpy(&context->buffer[j], &data[i], len - i);
+}
+
+
+/*
+ * Add padding and return the message digest.
+ */
+void SHA1Final(uint8_t digest[20], SHA1_CTX *context)
+{
+    unsigned int i;
+    uint8_t finalcount[8];
+
+    _DIAGASSERT(digest != 0);
+    _DIAGASSERT(context != 0);
+
+    for (i = 0; i < 8; i++) {
+       finalcount[i] = (uint8_t)((context->count[(i >= 4 ? 0 : 1)]
+        >> ((3-(i & 3)) * 8) ) & 255);  /* Endian independent */
+    }
+    SHA1Update(context, (const uint8_t *)"\200", 1);
+    while ((context->count[0] & 504) != 448)
+       SHA1Update(context, (const uint8_t *)"\0", 1);
+    SHA1Update(context, finalcount, 8);  /* Should cause a SHA1Transform() */
+
+    if (digest) {
+       for (i = 0; i < 20; i++)
+           digest[i] = (uint8_t)
+               ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
+    }
+}
+
+#endif /* HAVE_SHA1_H */
diff --git a/common/lib/libc/hash/sha2/sha2.c b/common/lib/libc/hash/sha2/sha2.c
new file mode 100644 (file)
index 0000000..55fd47d
--- /dev/null
@@ -0,0 +1,1007 @@
+/* $NetBSD: sha2.c,v 1.21 2010/01/24 21:11:18 joerg Exp $ */
+/*     $KAME: sha2.c,v 1.9 2003/07/20 00:28:38 itojun Exp $    */
+
+/*
+ * sha2.c
+ *
+ * Version 1.0.0beta1
+ *
+ * Written by Aaron D. Gifford <me@aarongifford.com>
+ *
+ * Copyright 2000 Aaron D. Gifford.  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.
+ * 3. Neither the name of the copyright holder nor the names of contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTOR(S) ``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(S) OR CONTRIBUTOR(S) 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+__KERNEL_RCSID(0, "$NetBSD: sha2.c,v 1.21 2010/01/24 21:11:18 joerg Exp $");
+
+#include <sys/param.h> /* XXX: to pull <machine/macros.h> for vax memset(9) */
+#include <lib/libkern/libkern.h>
+
+#else
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sha2.c,v 1.21 2010/01/24 21:11:18 joerg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <string.h>
+
+#endif
+
+#include <sys/types.h>
+#include <sys/sha2.h>
+
+#if HAVE_NBTOOL_CONFIG_H
+#  if HAVE_SYS_ENDIAN_H
+#    include <sys/endian.h>
+#  else
+#   undef htobe32
+#   undef htobe64
+#   undef be32toh
+#   undef be64toh
+
+static uint32_t
+htobe32(uint32_t x)
+{
+       uint8_t p[4];
+       memcpy(p, &x, 4);
+
+       return ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
+}
+
+static uint64_t
+htobe64(uint64_t x)
+{
+       uint8_t p[8];
+       uint32_t u, v;
+       memcpy(p, &x, 8);
+
+       u = ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
+       v = ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]);
+
+       return ((((uint64_t)u) << 32) | v);
+}
+
+static uint32_t
+be32toh(uint32_t x)
+{
+       return htobe32(x);
+}
+
+static uint64_t
+be64toh(uint64_t x)
+{
+       return htobe64(x);
+}
+#  endif
+#endif
+
+/*** SHA-256/384/512 Various Length Definitions ***********************/
+/* NOTE: Most of these are in sha2.h */
+#define SHA256_SHORT_BLOCK_LENGTH      (SHA256_BLOCK_LENGTH - 8)
+#define SHA384_SHORT_BLOCK_LENGTH      (SHA384_BLOCK_LENGTH - 16)
+#define SHA512_SHORT_BLOCK_LENGTH      (SHA512_BLOCK_LENGTH - 16)
+
+/*
+ * Macro for incrementally adding the unsigned 64-bit integer n to the
+ * unsigned 128-bit integer (represented using a two-element array of
+ * 64-bit words):
+ */
+#define ADDINC128(w,n) { \
+       (w)[0] += (uint64_t)(n); \
+       if ((w)[0] < (n)) { \
+               (w)[1]++; \
+       } \
+}
+
+/*** THE SIX LOGICAL FUNCTIONS ****************************************/
+/*
+ * Bit shifting and rotation (used by the six SHA-XYZ logical functions:
+ *
+ *   NOTE:  The naming of R and S appears backwards here (R is a SHIFT and
+ *   S is a ROTATION) because the SHA-256/384/512 description document
+ *   (see http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf) uses this
+ *   same "backwards" definition.
+ */
+/* Shift-right (used in SHA-256, SHA-384, and SHA-512): */
+#define R(b,x)                 ((x) >> (b))
+/* 32-bit Rotate-right (used in SHA-256): */
+#define S32(b,x)       (((x) >> (b)) | ((x) << (32 - (b))))
+/* 64-bit Rotate-right (used in SHA-384 and SHA-512): */
+#define S64(b,x)       (((x) >> (b)) | ((x) << (64 - (b))))
+
+/* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */
+#define Ch(x,y,z)      (((x) & (y)) ^ ((~(x)) & (z)))
+#define Maj(x,y,z)     (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
+
+/* Four of six logical functions used in SHA-256: */
+#define Sigma0_256(x)  (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))
+#define Sigma1_256(x)  (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
+#define sigma0_256(x)  (S32(7,  (x)) ^ S32(18, (x)) ^ R(3 ,   (x)))
+#define sigma1_256(x)  (S32(17, (x)) ^ S32(19, (x)) ^ R(10,   (x)))
+
+/* Four of six logical functions used in SHA-384 and SHA-512: */
+#define Sigma0_512(x)  (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x)))
+#define Sigma1_512(x)  (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x)))
+#define sigma0_512(x)  (S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7,   (x)))
+#define sigma1_512(x)  (S64(19, (x)) ^ S64(61, (x)) ^ R( 6,   (x)))
+
+/*** INTERNAL FUNCTION PROTOTYPES *************************************/
+/* NOTE: These should not be accessed directly from outside this
+ * library -- they are intended for private internal visibility/use
+ * only.
+ */
+static void SHA512_Last(SHA512_CTX *);
+void SHA224_Transform(SHA224_CTX *, const uint32_t*);
+void SHA256_Transform(SHA256_CTX *, const uint32_t*);
+void SHA384_Transform(SHA384_CTX *, const uint64_t*);
+void SHA512_Transform(SHA512_CTX *, const uint64_t*);
+
+
+/*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/
+/* Hash constant words K for SHA-256: */
+static const uint32_t K256[64] = {
+       0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL,
+       0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL,
+       0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL,
+       0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL,
+       0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
+       0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL,
+       0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL,
+       0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL,
+       0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL,
+       0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
+       0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL,
+       0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL,
+       0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL,
+       0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL,
+       0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
+       0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
+};
+
+/* Initial hash value H for SHA-224: */
+static const uint32_t sha224_initial_hash_value[8] = {
+       0xc1059ed8UL,
+       0x367cd507UL,
+       0x3070dd17UL,
+       0xf70e5939UL,
+       0xffc00b31UL,
+       0x68581511UL,
+       0x64f98fa7UL,
+       0xbefa4fa4UL
+};
+
+/* Initial hash value H for SHA-256: */
+static const uint32_t sha256_initial_hash_value[8] = {
+       0x6a09e667UL,
+       0xbb67ae85UL,
+       0x3c6ef372UL,
+       0xa54ff53aUL,
+       0x510e527fUL,
+       0x9b05688cUL,
+       0x1f83d9abUL,
+       0x5be0cd19UL
+};
+
+/* Hash constant words K for SHA-384 and SHA-512: */
+static const uint64_t K512[80] = {
+       0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
+       0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
+       0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
+       0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
+       0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
+       0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
+       0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
+       0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
+       0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
+       0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
+       0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
+       0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
+       0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
+       0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
+       0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
+       0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
+       0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
+       0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
+       0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
+       0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
+       0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
+       0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
+       0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
+       0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
+       0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
+       0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
+       0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
+       0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
+       0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
+       0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
+       0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
+       0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
+       0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
+       0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
+       0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
+       0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
+       0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
+       0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
+       0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
+       0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL
+};
+
+/* Initial hash value H for SHA-384 */
+static const uint64_t sha384_initial_hash_value[8] = {
+       0xcbbb9d5dc1059ed8ULL,
+       0x629a292a367cd507ULL,
+       0x9159015a3070dd17ULL,
+       0x152fecd8f70e5939ULL,
+       0x67332667ffc00b31ULL,
+       0x8eb44a8768581511ULL,
+       0xdb0c2e0d64f98fa7ULL,
+       0x47b5481dbefa4fa4ULL
+};
+
+/* Initial hash value H for SHA-512 */
+static const uint64_t sha512_initial_hash_value[8] = {
+       0x6a09e667f3bcc908ULL,
+       0xbb67ae8584caa73bULL,
+       0x3c6ef372fe94f82bULL,
+       0xa54ff53a5f1d36f1ULL,
+       0x510e527fade682d1ULL,
+       0x9b05688c2b3e6c1fULL,
+       0x1f83d9abfb41bd6bULL,
+       0x5be0cd19137e2179ULL
+};
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#if defined(__weak_alias)
+__weak_alias(SHA224_Init,_SHA224_Init) 
+__weak_alias(SHA224_Update,_SHA224_Update)
+__weak_alias(SHA224_Final,_SHA224_Final)
+__weak_alias(SHA224_Transform,_SHA224_Transform)
+
+__weak_alias(SHA256_Init,_SHA256_Init) 
+__weak_alias(SHA256_Update,_SHA256_Update)
+__weak_alias(SHA256_Final,_SHA256_Final)
+__weak_alias(SHA256_Transform,_SHA256_Transform)
+
+__weak_alias(SHA384_Init,_SHA384_Init) 
+__weak_alias(SHA384_Update,_SHA384_Update)
+__weak_alias(SHA384_Final,_SHA384_Final)
+__weak_alias(SHA384_Transform,_SHA384_Transform)
+
+__weak_alias(SHA512_Init,_SHA512_Init) 
+__weak_alias(SHA512_Update,_SHA512_Update)
+__weak_alias(SHA512_Final,_SHA512_Final)
+__weak_alias(SHA512_Transform,_SHA512_Transform)
+#endif
+#endif
+
+/*** SHA-256: *********************************************************/
+int
+SHA256_Init(SHA256_CTX *context)
+{
+       if (context == NULL)
+               return 1;
+
+       memcpy(context->state, sha256_initial_hash_value,
+           (size_t)(SHA256_DIGEST_LENGTH));
+       memset(context->buffer, 0, (size_t)(SHA256_BLOCK_LENGTH));
+       context->bitcount = 0;
+
+       return 1;
+}
+
+#ifdef SHA2_UNROLL_TRANSFORM
+
+/* Unrolled SHA-256 round macros: */
+
+#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h)      \
+       W256[j] = be32toh(*data);               \
+       ++data;                                 \
+       T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
+             K256[j] + W256[j]; \
+       (d) += T1; \
+       (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
+       j++
+
+#define ROUND256(a,b,c,d,e,f,g,h)      \
+       s0 = W256[(j+1)&0x0f]; \
+       s0 = sigma0_256(s0); \
+       s1 = W256[(j+14)&0x0f]; \
+       s1 = sigma1_256(s1); \
+       T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \
+            (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \
+       (d) += T1; \
+       (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
+       j++
+
+void 
+SHA256_Transform(SHA256_CTX *context, const uint32_t *data)
+{
+       uint32_t        a, b, c, d, e, f, g, h, s0, s1;
+       uint32_t        T1, *W256;
+       int             j;
+
+       W256 = (uint32_t *)context->buffer;
+
+       /* Initialize registers with the prev. intermediate value */
+       a = context->state[0];
+       b = context->state[1];
+       c = context->state[2];
+       d = context->state[3];
+       e = context->state[4];
+       f = context->state[5];
+       g = context->state[6];
+       h = context->state[7];
+
+       j = 0;
+       do {
+               /* Rounds 0 to 15 (unrolled): */
+               ROUND256_0_TO_15(a,b,c,d,e,f,g,h);
+               ROUND256_0_TO_15(h,a,b,c,d,e,f,g);
+               ROUND256_0_TO_15(g,h,a,b,c,d,e,f);
+               ROUND256_0_TO_15(f,g,h,a,b,c,d,e);
+               ROUND256_0_TO_15(e,f,g,h,a,b,c,d);
+               ROUND256_0_TO_15(d,e,f,g,h,a,b,c);
+               ROUND256_0_TO_15(c,d,e,f,g,h,a,b);
+               ROUND256_0_TO_15(b,c,d,e,f,g,h,a);
+       } while (j < 16);
+
+       /* Now for the remaining rounds to 64: */
+       do {
+               ROUND256(a,b,c,d,e,f,g,h);
+               ROUND256(h,a,b,c,d,e,f,g);
+               ROUND256(g,h,a,b,c,d,e,f);
+               ROUND256(f,g,h,a,b,c,d,e);
+               ROUND256(e,f,g,h,a,b,c,d);
+               ROUND256(d,e,f,g,h,a,b,c);
+               ROUND256(c,d,e,f,g,h,a,b);
+               ROUND256(b,c,d,e,f,g,h,a);
+       } while (j < 64);
+
+       /* Compute the current intermediate hash value */
+       context->state[0] += a;
+       context->state[1] += b;
+       context->state[2] += c;
+       context->state[3] += d;
+       context->state[4] += e;
+       context->state[5] += f;
+       context->state[6] += g;
+       context->state[7] += h;
+
+       /* Clean up */
+       a = b = c = d = e = f = g = h = T1 = 0;
+}
+
+#else /* SHA2_UNROLL_TRANSFORM */
+
+void
+SHA256_Transform(SHA256_CTX *context, const uint32_t *data)
+{
+       uint32_t        a, b, c, d, e, f, g, h, s0, s1;
+       uint32_t        T1, T2, *W256;
+       int             j;
+
+       W256 = (uint32_t *)(void *)context->buffer;
+
+       /* Initialize registers with the prev. intermediate value */
+       a = context->state[0];
+       b = context->state[1];
+       c = context->state[2];
+       d = context->state[3];
+       e = context->state[4];
+       f = context->state[5];
+       g = context->state[6];
+       h = context->state[7];
+
+       j = 0;
+       do {
+               W256[j] = be32toh(*data);
+               ++data;
+               /* Apply the SHA-256 compression function to update a..h */
+               T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j];
+               T2 = Sigma0_256(a) + Maj(a, b, c);
+               h = g;
+               g = f;
+               f = e;
+               e = d + T1;
+               d = c;
+               c = b;
+               b = a;
+               a = T1 + T2;
+
+               j++;
+       } while (j < 16);
+
+       do {
+               /* Part of the message block expansion: */
+               s0 = W256[(j+1)&0x0f];
+               s0 = sigma0_256(s0);
+               s1 = W256[(j+14)&0x0f];
+               s1 = sigma1_256(s1);
+
+               /* Apply the SHA-256 compression function to update a..h */
+               T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] +
+                    (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0);
+               T2 = Sigma0_256(a) + Maj(a, b, c);
+               h = g;
+               g = f;
+               f = e;
+               e = d + T1;
+               d = c;
+               c = b;
+               b = a;
+               a = T1 + T2;
+
+               j++;
+       } while (j < 64);
+
+       /* Compute the current intermediate hash value */
+       context->state[0] += a;
+       context->state[1] += b;
+       context->state[2] += c;
+       context->state[3] += d;
+       context->state[4] += e;
+       context->state[5] += f;
+       context->state[6] += g;
+       context->state[7] += h;
+
+       /* Clean up */
+       a = b = c = d = e = f = g = h = T1 = T2 = 0;
+}
+
+#endif /* SHA2_UNROLL_TRANSFORM */
+
+int
+SHA256_Update(SHA256_CTX *context, const uint8_t *data, size_t len)
+{
+       unsigned int    freespace, usedspace;
+
+       if (len == 0) {
+               /* Calling with no data is valid - we do nothing */
+               return 1;
+       }
+
+       usedspace = (unsigned int)((context->bitcount >> 3) %
+                                   SHA256_BLOCK_LENGTH);
+       if (usedspace > 0) {
+               /* Calculate how much free space is available in the buffer */
+               freespace = SHA256_BLOCK_LENGTH - usedspace;
+
+               if (len >= freespace) {
+                       /* Fill the buffer completely and process it */
+                       memcpy(&context->buffer[usedspace], data,
+                           (size_t)(freespace));
+                       context->bitcount += freespace << 3;
+                       len -= freespace;
+                       data += freespace;
+                       SHA256_Transform(context,
+                           (uint32_t *)(void *)context->buffer);
+               } else {
+                       /* The buffer is not yet full */
+                       memcpy(&context->buffer[usedspace], data, len);
+                       context->bitcount += len << 3;
+                       /* Clean up: */
+                       usedspace = freespace = 0;
+                       return 1;
+               }
+       }
+       /*
+        * Process as many complete blocks as possible.
+        *
+        * Check alignment of the data pointer. If it is 32bit aligned,
+        * SHA256_Transform can be called directly on the data stream,
+        * otherwise enforce the alignment by copy into the buffer.
+        */
+       if ((uintptr_t)data % 4 == 0) {
+               while (len >= SHA256_BLOCK_LENGTH) {
+                       SHA256_Transform(context,
+                           (const uint32_t *)(const void *)data);
+                       context->bitcount += SHA256_BLOCK_LENGTH << 3;
+                       len -= SHA256_BLOCK_LENGTH;
+                       data += SHA256_BLOCK_LENGTH;
+               }
+       } else {
+               while (len >= SHA256_BLOCK_LENGTH) {
+                       memcpy(context->buffer, data, SHA256_BLOCK_LENGTH);
+                       SHA256_Transform(context,
+                           (const uint32_t *)(const void *)context->buffer);
+                       context->bitcount += SHA256_BLOCK_LENGTH << 3;
+                       len -= SHA256_BLOCK_LENGTH;
+                       data += SHA256_BLOCK_LENGTH;
+               }
+       }
+       if (len > 0) {
+               /* There's left-overs, so save 'em */
+               memcpy(context->buffer, data, len);
+               context->bitcount += len << 3;
+       }
+       /* Clean up: */
+       usedspace = freespace = 0;
+
+       return 1;
+}
+
+static int
+SHA224_256_Final(uint8_t digest[], SHA256_CTX *context, size_t len)
+{
+       unsigned int    usedspace;
+       size_t i;
+
+       /* If no digest buffer is passed, we don't bother doing this: */
+       if (digest != NULL) {
+               usedspace = (unsigned int)((context->bitcount >> 3) %
+                   SHA256_BLOCK_LENGTH);
+               context->bitcount = htobe64(context->bitcount);
+               if (usedspace > 0) {
+                       /* Begin padding with a 1 bit: */
+                       context->buffer[usedspace++] = 0x80;
+
+                       if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) {
+                               /* Set-up for the last transform: */
+                               memset(&context->buffer[usedspace], 0,
+                                   (size_t)(SHA256_SHORT_BLOCK_LENGTH -
+                                   usedspace));
+                       } else {
+                               if (usedspace < SHA256_BLOCK_LENGTH) {
+                                       memset(&context->buffer[usedspace], 0,
+                                           (size_t)(SHA256_BLOCK_LENGTH -
+                                           usedspace));
+                               }
+                               /* Do second-to-last transform: */
+                               SHA256_Transform(context,
+                                   (uint32_t *)(void *)context->buffer);
+
+                               /* And set-up for the last transform: */
+                               memset(context->buffer, 0,
+                                   (size_t)(SHA256_SHORT_BLOCK_LENGTH));
+                       }
+               } else {
+                       /* Set-up for the last transform: */
+                       memset(context->buffer, 0,
+                           (size_t)(SHA256_SHORT_BLOCK_LENGTH));
+
+                       /* Begin padding with a 1 bit: */
+                       *context->buffer = 0x80;
+               }
+               /* Set the bit count: */
+               memcpy(&context->buffer[SHA256_SHORT_BLOCK_LENGTH],
+                   &context->bitcount, sizeof(context->bitcount));
+
+               /* Final transform: */
+               SHA256_Transform(context, (uint32_t *)(void *)context->buffer);
+
+               for (i = 0; i < len / 4; i++)
+                       be32enc(digest + 4 * i, context->state[i]);
+       }
+
+       /* Clean up state data: */
+       memset(context, 0, sizeof(*context));
+       usedspace = 0;
+
+       return 1;
+}
+
+int
+SHA256_Final(uint8_t digest[], SHA256_CTX *context)
+{
+       return SHA224_256_Final(digest, context, SHA256_DIGEST_LENGTH);
+}
+
+/*** SHA-224: *********************************************************/
+int 
+SHA224_Init(SHA224_CTX *context)
+{
+       if (context == NULL)
+               return 1;
+
+       /* The state and buffer size are driven by SHA256, not by SHA224. */
+       memcpy(context->state, sha224_initial_hash_value,
+           (size_t)(SHA256_DIGEST_LENGTH));
+       memset(context->buffer, 0, (size_t)(SHA256_BLOCK_LENGTH));
+       context->bitcount = 0;
+
+       return 1;
+}
+
+int
+SHA224_Update(SHA224_CTX *context, const uint8_t *data, size_t len)
+{
+       return SHA256_Update((SHA256_CTX *)context, data, len);
+}
+
+void
+SHA224_Transform(SHA224_CTX *context, const uint32_t *data)
+{
+       SHA256_Transform((SHA256_CTX *)context, data);
+}
+
+int
+SHA224_Final(uint8_t digest[], SHA224_CTX *context)
+{
+       return SHA224_256_Final(digest, (SHA256_CTX *)context,
+           SHA224_DIGEST_LENGTH);
+}
+
+/*** SHA-512: *********************************************************/
+int
+SHA512_Init(SHA512_CTX *context)
+{
+       if (context == NULL)
+               return 1;
+
+       memcpy(context->state, sha512_initial_hash_value,
+           (size_t)(SHA512_DIGEST_LENGTH));
+       memset(context->buffer, 0, (size_t)(SHA512_BLOCK_LENGTH));
+       context->bitcount[0] = context->bitcount[1] =  0;
+
+       return 1;
+}
+
+#ifdef SHA2_UNROLL_TRANSFORM
+
+/* Unrolled SHA-512 round macros: */
+#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h)      \
+       W512[j] = be64toh(*data);               \
+       ++data;                                 \
+       T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \
+             K512[j] + W512[j]; \
+       (d) += T1, \
+       (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \
+       j++
+
+#define ROUND512(a,b,c,d,e,f,g,h)      \
+       s0 = W512[(j+1)&0x0f]; \
+       s0 = sigma0_512(s0); \
+       s1 = W512[(j+14)&0x0f]; \
+       s1 = sigma1_512(s1); \
+       T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \
+             (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \
+       (d) += T1; \
+       (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
+       j++
+
+void
+SHA512_Transform(SHA512_CTX *context, const uint64_t *data)
+{
+       uint64_t        a, b, c, d, e, f, g, h, s0, s1;
+       uint64_t        T1, *W512 = (uint64_t *)context->buffer;
+       int             j;
+
+       /* Initialize registers with the prev. intermediate value */
+       a = context->state[0];
+       b = context->state[1];
+       c = context->state[2];
+       d = context->state[3];
+       e = context->state[4];
+       f = context->state[5];
+       g = context->state[6];
+       h = context->state[7];
+
+       j = 0;
+       do {
+               ROUND512_0_TO_15(a,b,c,d,e,f,g,h);
+               ROUND512_0_TO_15(h,a,b,c,d,e,f,g);
+               ROUND512_0_TO_15(g,h,a,b,c,d,e,f);
+               ROUND512_0_TO_15(f,g,h,a,b,c,d,e);
+               ROUND512_0_TO_15(e,f,g,h,a,b,c,d);
+               ROUND512_0_TO_15(d,e,f,g,h,a,b,c);
+               ROUND512_0_TO_15(c,d,e,f,g,h,a,b);
+               ROUND512_0_TO_15(b,c,d,e,f,g,h,a);
+       } while (j < 16);
+
+       /* Now for the remaining rounds up to 79: */
+       do {
+               ROUND512(a,b,c,d,e,f,g,h);
+               ROUND512(h,a,b,c,d,e,f,g);
+               ROUND512(g,h,a,b,c,d,e,f);
+               ROUND512(f,g,h,a,b,c,d,e);
+               ROUND512(e,f,g,h,a,b,c,d);
+               ROUND512(d,e,f,g,h,a,b,c);
+               ROUND512(c,d,e,f,g,h,a,b);
+               ROUND512(b,c,d,e,f,g,h,a);
+       } while (j < 80);
+
+       /* Compute the current intermediate hash value */
+       context->state[0] += a;
+       context->state[1] += b;
+       context->state[2] += c;
+       context->state[3] += d;
+       context->state[4] += e;
+       context->state[5] += f;
+       context->state[6] += g;
+       context->state[7] += h;
+
+       /* Clean up */
+       a = b = c = d = e = f = g = h = T1 = 0;
+}
+
+#else /* SHA2_UNROLL_TRANSFORM */
+
+void
+SHA512_Transform(SHA512_CTX *context, const uint64_t *data)
+{
+       uint64_t        a, b, c, d, e, f, g, h, s0, s1;
+       uint64_t        T1, T2, *W512 = (void *)context->buffer;
+       int             j;
+
+       /* Initialize registers with the prev. intermediate value */
+       a = context->state[0];
+       b = context->state[1];
+       c = context->state[2];
+       d = context->state[3];
+       e = context->state[4];
+       f = context->state[5];
+       g = context->state[6];
+       h = context->state[7];
+
+       j = 0;
+       do {
+               W512[j] = be64toh(*data);
+               ++data;
+               /* Apply the SHA-512 compression function to update a..h */
+               T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j];
+               T2 = Sigma0_512(a) + Maj(a, b, c);
+               h = g;
+               g = f;
+               f = e;
+               e = d + T1;
+               d = c;
+               c = b;
+               b = a;
+               a = T1 + T2;
+
+               j++;
+       } while (j < 16);
+
+       do {
+               /* Part of the message block expansion: */
+               s0 = W512[(j+1)&0x0f];
+               s0 = sigma0_512(s0);
+               s1 = W512[(j+14)&0x0f];
+               s1 =  sigma1_512(s1);
+
+               /* Apply the SHA-512 compression function to update a..h */
+               T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] +
+                    (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0);
+               T2 = Sigma0_512(a) + Maj(a, b, c);
+               h = g;
+               g = f;
+               f = e;
+               e = d + T1;
+               d = c;
+               c = b;
+               b = a;
+               a = T1 + T2;
+
+               j++;
+       } while (j < 80);
+
+       /* Compute the current intermediate hash value */
+       context->state[0] += a;
+       context->state[1] += b;
+       context->state[2] += c;
+       context->state[3] += d;
+       context->state[4] += e;
+       context->state[5] += f;
+       context->state[6] += g;
+       context->state[7] += h;
+
+       /* Clean up */
+       a = b = c = d = e = f = g = h = T1 = T2 = 0;
+}
+
+#endif /* SHA2_UNROLL_TRANSFORM */
+
+int
+SHA512_Update(SHA512_CTX *context, const uint8_t *data, size_t len)
+{
+       unsigned int    freespace, usedspace;
+
+       if (len == 0) {
+               /* Calling with no data is valid - we do nothing */
+               return 1;
+       }
+
+       usedspace = (unsigned int)((context->bitcount[0] >> 3) %
+           SHA512_BLOCK_LENGTH);
+       if (usedspace > 0) {
+               /* Calculate how much free space is available in the buffer */
+               freespace = SHA512_BLOCK_LENGTH - usedspace;
+
+               if (len >= freespace) {
+                       /* Fill the buffer completely and process it */
+                       memcpy(&context->buffer[usedspace], data,
+                           (size_t)(freespace));
+                       ADDINC128(context->bitcount, freespace << 3);
+                       len -= freespace;
+                       data += freespace;
+                       SHA512_Transform(context,
+                           (uint64_t *)(void *)context->buffer);
+               } else {
+                       /* The buffer is not yet full */
+                       memcpy(&context->buffer[usedspace], data, len);
+                       ADDINC128(context->bitcount, len << 3);
+                       /* Clean up: */
+                       usedspace = freespace = 0;
+                       return 1;
+               }
+       }
+       /*
+        * Process as many complete blocks as possible.
+        *
+        * Check alignment of the data pointer. If it is 64bit aligned,
+        * SHA512_Transform can be called directly on the data stream,
+        * otherwise enforce the alignment by copy into the buffer.
+        */
+       if ((uintptr_t)data % 8 == 0) {
+               while (len >= SHA512_BLOCK_LENGTH) {
+                       SHA512_Transform(context,
+                           (const uint64_t*)(const void *)data);
+                       ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3);
+                       len -= SHA512_BLOCK_LENGTH;
+                       data += SHA512_BLOCK_LENGTH;
+               }
+       } else {
+               while (len >= SHA512_BLOCK_LENGTH) {
+                       memcpy(context->buffer, data, SHA512_BLOCK_LENGTH);
+                       SHA512_Transform(context,
+                           (const void *)context->buffer);
+                       ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3);
+                       len -= SHA512_BLOCK_LENGTH;
+                       data += SHA512_BLOCK_LENGTH;
+               }
+       }
+       if (len > 0) {
+               /* There's left-overs, so save 'em */
+               memcpy(context->buffer, data, len);
+               ADDINC128(context->bitcount, len << 3);
+       }
+       /* Clean up: */
+       usedspace = freespace = 0;
+
+       return 1;
+}
+
+static void
+SHA512_Last(SHA512_CTX *context)
+{
+       unsigned int    usedspace;
+
+       usedspace = (unsigned int)((context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH);
+       context->bitcount[0] = htobe64(context->bitcount[0]);
+       context->bitcount[1] = htobe64(context->bitcount[1]);
+       if (usedspace > 0) {
+               /* Begin padding with a 1 bit: */
+               context->buffer[usedspace++] = 0x80;
+
+               if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) {
+                       /* Set-up for the last transform: */
+                       memset(&context->buffer[usedspace], 0,
+                           (size_t)(SHA512_SHORT_BLOCK_LENGTH - usedspace));
+               } else {
+                       if (usedspace < SHA512_BLOCK_LENGTH) {
+                               memset(&context->buffer[usedspace], 0,
+                                   (size_t)(SHA512_BLOCK_LENGTH - usedspace));
+                       }
+                       /* Do second-to-last transform: */
+                       SHA512_Transform(context,
+                           (uint64_t *)(void *)context->buffer);
+
+                       /* And set-up for the last transform: */
+                       memset(context->buffer, 0,
+                           (size_t)(SHA512_BLOCK_LENGTH - 2));
+               }
+       } else {
+               /* Prepare for final transform: */
+               memset(context->buffer, 0, (size_t)(SHA512_SHORT_BLOCK_LENGTH));
+
+               /* Begin padding with a 1 bit: */
+               *context->buffer = 0x80;
+       }
+       /* Store the length of input data (in bits): */
+       memcpy(&context->buffer[SHA512_SHORT_BLOCK_LENGTH],
+           &context->bitcount[1], sizeof(context->bitcount[1]));
+       memcpy(&context->buffer[SHA512_SHORT_BLOCK_LENGTH + 8],
+           &context->bitcount[0], sizeof(context->bitcount[0]));
+
+       /* Final transform: */
+       SHA512_Transform(context, (uint64_t *)(void *)context->buffer);
+}
+
+int
+SHA512_Final(uint8_t digest[], SHA512_CTX *context)
+{
+       size_t i;
+
+       /* If no digest buffer is passed, we don't bother doing this: */
+       if (digest != NULL) {
+               SHA512_Last(context);
+
+               /* Save the hash data for output: */
+               for (i = 0; i < 8; ++i)
+                       be64enc(digest + 8 * i, context->state[i]);
+       }
+
+       /* Zero out state data */
+       memset(context, 0, sizeof(*context));
+
+       return 1;
+}
+
+/*** SHA-384: *********************************************************/
+int
+SHA384_Init(SHA384_CTX *context)
+{
+       if (context == NULL)
+               return 1;
+
+       memcpy(context->state, sha384_initial_hash_value,
+           (size_t)(SHA512_DIGEST_LENGTH));
+       memset(context->buffer, 0, (size_t)(SHA384_BLOCK_LENGTH));
+       context->bitcount[0] = context->bitcount[1] = 0;
+
+       return 1;
+}
+
+int
+SHA384_Update(SHA384_CTX *context, const uint8_t *data, size_t len)
+{
+       return SHA512_Update((SHA512_CTX *)context, data, len);
+}
+
+void
+SHA384_Transform(SHA512_CTX *context, const uint64_t *data)
+{
+       SHA512_Transform((SHA512_CTX *)context, data);
+}
+
+int
+SHA384_Final(uint8_t digest[], SHA384_CTX *context)
+{
+       size_t i;
+
+       /* If no digest buffer is passed, we don't bother doing this: */
+       if (digest != NULL) {
+               SHA512_Last((SHA512_CTX *)context);
+
+               /* Save the hash data for output: */
+               for (i = 0; i < 6; ++i)
+                       be64enc(digest + 8 * i, context->state[i]);
+       }
+
+       /* Zero out state data */
+       memset(context, 0, sizeof(*context));
+
+       return 1;
+}
diff --git a/common/lib/libc/inet/inet_addr.c b/common/lib/libc/inet/inet_addr.c
new file mode 100644 (file)
index 0000000..551ba17
--- /dev/null
@@ -0,0 +1,223 @@
+/*     $NetBSD: inet_addr.c,v 1.2 2008/02/16 17:37:13 apb Exp $        */
+
+/*
+ * Copyright (c) 1983, 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+/*
+ * Portions Copyright (c) 1993 by Digital Equipment Corporation.
+ * 
+ * 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, and that
+ * the name of Digital Equipment Corporation not be used in advertising or
+ * publicity pertaining to distribution of the document or software without
+ * specific, written prior permission.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
+ * CORPORATION 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.
+ */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static const char sccsid[] = "@(#)inet_addr.c  8.1 (Berkeley) 6/17/93";
+static const char rcsid[] = "Id: inet_addr.c,v 1.2.206.2 2004/03/17 00:29:45 marka Exp";
+#else
+__RCSID("$NetBSD: inet_addr.c,v 1.2 2008/02/16 17:37:13 apb Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include <ctype.h>
+
+#include "port_after.h"
+
+#ifdef __weak_alias
+__weak_alias(inet_aton,_inet_aton)
+#endif
+#else
+#include <lib/libkern/libkern.h>
+#include <netinet/in.h>
+#endif
+
+/*
+ * Ascii internet address interpretation routine.
+ * The value returned is in network order.
+ */
+uint32_t
+inet_addr(const char *cp) {
+       struct in_addr val;
+
+       if (inet_aton(cp, &val))
+               return (val.s_addr);
+       return (INADDR_NONE);
+}
+
+/* 
+ * Check whether "cp" is a valid ascii representation
+ * of an Internet address and convert to a binary address.
+ * Returns 1 if the address is valid, 0 if not.
+ * This replaces inet_addr, the return value from which
+ * cannot distinguish between failure and a local broadcast address.
+ */
+int
+inet_aton(const char *cp, struct in_addr *addr) {
+       uint32_t val;
+       int base, n;
+       char c;
+       uint8_t parts[4];
+       uint8_t *pp = parts;
+       int digit;
+
+       c = *cp;
+       for (;;) {
+               /*
+                * Collect number up to ``.''.
+                * Values are specified as for C:
+                * 0x=hex, 0=octal, isdigit=decimal.
+                */
+               if (!isdigit((unsigned char)c))
+                       return (0);
+               val = 0; base = 10; digit = 0;
+               if (c == '0') {
+                       c = *++cp;
+                       if (c == 'x' || c == 'X')
+                               base = 16, c = *++cp;
+                       else {
+                               base = 8;
+                               digit = 1 ;
+                       }
+               }
+               for (;;) {
+                       if (isascii(c) && isdigit((unsigned char)c)) {
+                               if (base == 8 && (c == '8' || c == '9'))
+                                       return (0);
+                               val = (val * base) + (c - '0');
+                               c = *++cp;
+                               digit = 1;
+                       } else if (base == 16 && isascii(c) && 
+                                  isxdigit((unsigned char)c)) {
+                               val = (val << 4) |
+                                       (c + 10 - (islower((unsigned char)c) ? 'a' : 'A'));
+                               c = *++cp;
+                               digit = 1;
+                       } else
+                               break;
+               }
+               if (c == '.') {
+                       /*
+                        * Internet format:
+                        *      a.b.c.d
+                        *      a.b.c   (with c treated as 16 bits)
+                        *      a.b     (with b treated as 24 bits)
+                        */
+                       if (pp >= parts + 3 || val > 0xffU)
+                               return (0);
+                       *pp++ = val;
+                       c = *++cp;
+               } else
+                       break;
+       }
+       /*
+        * Check for trailing characters.
+        */
+       if (c != '\0' && (!isascii(c) || !isspace((unsigned char)c)))
+               return (0);
+       /*
+        * Did we get a valid digit?
+        */
+       if (!digit)
+               return (0);
+       /*
+        * Concoct the address according to
+        * the number of parts specified.
+        */
+       n = pp - parts + 1;
+       switch (n) {
+       case 1:                         /* a -- 32 bits */
+               break;
+
+       case 2:                         /* a.b -- 8.24 bits */
+               if (val > 0xffffffU)
+                       return (0);
+               val |= parts[0] << 24;
+               break;
+
+       case 3:                         /* a.b.c -- 8.8.16 bits */
+               if (val > 0xffffU)
+                       return (0);
+               val |= (parts[0] << 24) | (parts[1] << 16);
+               break;
+
+       case 4:                         /* a.b.c.d -- 8.8.8.8 bits */
+               if (val > 0xffU)
+                       return (0);
+               val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
+               break;
+       }
+       if (addr != NULL)
+               addr->s_addr = htonl(val);
+       return (1);
+}
diff --git a/common/lib/libc/md/md4c.c b/common/lib/libc/md/md4c.c
new file mode 100644 (file)
index 0000000..ee7a697
--- /dev/null
@@ -0,0 +1,324 @@
+/*     $NetBSD: md4c.c,v 1.4 2009/03/16 05:59:21 cegger Exp $  */
+
+/*
+ * This file is derived from the RSA Data Security, Inc. MD4 Message-Digest
+ * Algorithm and has been modified by Jason R. Thorpe <thorpej@NetBSD.org>
+ * for portability and formatting.
+ */
+
+/*
+ * Copyright (C) 1990-2, RSA Data Security, Inc. All rights reserved.
+ *
+ * License to copy and use this software is granted provided that it
+ * is identified as the "RSA Data Security, Inc. MD4 Message-Digest
+ * Algorithm" in all material mentioning or referencing this software
+ * or this function.
+ *
+ * License is also granted to make and use derivative works provided
+ * that such works are identified as "derived from the RSA Data
+ * Security, Inc. MD4 Message-Digest Algorithm" in all material
+ * mentioning or referencing the derived work.
+ *
+ * RSA Data Security, Inc. makes no representations concerning either
+ * the merchantability of this software or the suitability of this
+ * software for any particular purpose. It is provided "as is"
+ * without express or implied warranty of any kind.
+ *
+ * These notices must be retained in any copies of any part of this
+ * documentation and/or software.
+ */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: md4c.c,v 1.4 2009/03/16 05:59:21 cegger Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+
+#include <assert.h>
+#include <md4.h>
+#include <string.h>
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#else
+
+#include <sys/param.h>
+#include <sys/md4.h>
+#include <lib/libkern/libkern.h>
+
+#endif /* !_KERNEL && !_STANDALONE */
+
+#if !HAVE_MD4_H
+
+typedef unsigned char *POINTER;
+typedef uint16_t UINT2;
+typedef uint32_t UINT4;
+
+/*
+ * Constants for MD4Transform routine.
+ */
+#define S11 3
+#define S12 7
+#define S13 11
+#define S14 19
+#define S21 3
+#define S22 5
+#define S23 9
+#define S24 13
+#define S31 3
+#define S32 9
+#define S33 11
+#define S34 15
+
+static void MD4Transform __P((UINT4 [4], const unsigned char [64]));
+
+static void Encode __P((unsigned char *, UINT4 *, unsigned int));
+static void Decode __P((UINT4 *, const unsigned char *, unsigned int));
+
+static const unsigned char PADDING[64] = {
+       0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+/*
+ * F, G and H are basic MD4 functions.
+ */
+#define F(x, y, z)     (((x) & (y)) | ((~x) & (z)))
+#define G(x, y, z)     (((x) & (y)) | ((x) & (z)) | ((y) & (z)))
+#define H(x, y, z)     ((x) ^ (y) ^ (z))
+
+/*
+ * ROTATE_LEFT rotates x left n bits.
+ */
+#define ROTATE_LEFT(x, n)      (((x) << (n)) | ((x) >> (32-(n))))
+
+/*
+ * FF, GG and HH are transformations for rounds 1, 2 and 3.
+ * Rotation is separate from addition to prevent recomputation.
+ */
+#define FF(a, b, c, d, x, s) { \
+       (a) += F ((b), (c), (d)) + (x); \
+       (a) = ROTATE_LEFT ((a), (s)); \
+}
+
+#define GG(a, b, c, d, x, s) { \
+       (a) += G ((b), (c), (d)) + (x) + (UINT4)0x5a827999; \
+       (a) = ROTATE_LEFT ((a), (s)); \
+}
+
+#define HH(a, b, c, d, x, s) { \
+       (a) += H ((b), (c), (d)) + (x) + (UINT4)0x6ed9eba1; \
+       (a) = ROTATE_LEFT ((a), (s)); \
+}
+
+#if !defined(_KERNEL) && !defined(_STANDALONE) && defined(__weak_alias)
+__weak_alias(MD4Init,_MD4Init)
+__weak_alias(MD4Update,_MD4Update)
+__weak_alias(MD4Final,_MD4Final)
+__weak_alias(MD4Transform,_MD4Transform)
+#endif
+
+/*
+ * MD4 initialization. Begins an MD4 operation, writing a new context.
+ */
+void
+MD4Init(MD4_CTX *context)              /* context */
+{
+
+       _DIAGASSERT(context != 0);
+
+       context->count[0] = context->count[1] = 0;
+
+       /* Load magic initialization constants. */
+       context->state[0] = 0x67452301;
+       context->state[1] = 0xefcdab89;
+       context->state[2] = 0x98badcfe;
+       context->state[3] = 0x10325476;
+}
+
+/*
+ * MD4 block update operation.  Continues an MD4 message-digest
+ * operation, processing another message block, and updating the
+ * context.
+ */
+void
+MD4Update (MD4_CTX *context,           /* context */
+       const unsigned char *input,     /* input block */
+       unsigned int inputLen)          /* length of input block */
+{
+       unsigned int i, idx, partLen;
+
+       _DIAGASSERT(context != 0);
+       _DIAGASSERT(input != 0);
+
+       /* Compute number of bytes mod 64 */
+       idx = (unsigned int)((context->count[0] >> 3) & 0x3F);
+
+       /* Update number of bits */
+       if ((context->count[0] += ((UINT4)inputLen << 3))
+           < ((UINT4)inputLen << 3))
+               context->count[1]++;
+       context->count[1] += ((UINT4)inputLen >> 29);
+
+       partLen = 64 - idx;
+
+       /* Transform as many times as possible. */
+       if (inputLen >= partLen) {
+               memcpy(&context->buffer[idx], input, partLen);
+               MD4Transform(context->state, context->buffer);
+
+               for (i = partLen; i + 63 < inputLen; i += 64)
+                       MD4Transform(context->state, &input[i]);
+
+               idx = 0;
+       } else
+               i = 0;
+
+       /* Buffer remaining input */
+       memcpy(&context->buffer[idx], &input[i], inputLen - i);
+}
+
+/*
+ * MD4 finalization.  Ends an MD4 message-digest operation, writing the
+ * message digest and zeroing the context.
+ */
+void
+MD4Final (unsigned char digest[16],    /* message digest */
+       MD4_CTX *context)               /* context */
+{
+       unsigned char bits[8];
+       unsigned int idx, padLen;
+
+       _DIAGASSERT(digest != 0);
+       _DIAGASSERT(context != 0);
+
+       /* Save number of bits */
+       Encode(bits, context->count, 8);
+
+       /* Pad out to 56 mod 64. */
+       idx = (unsigned int)((context->count[0] >> 3) & 0x3f);
+       padLen = (idx < 56) ? (56 - idx) : (120 - idx);
+       MD4Update(context, PADDING, padLen);
+
+       /* Append length (before padding) */
+       MD4Update(context, bits, 8);
+
+       /* Store state in digest */
+       Encode(digest, context->state, 16);
+
+       /* Zeroize sensitive information. */
+       memset(context, 0, sizeof(*context));
+}
+
+/*
+ * MD4 basic transformation.  Transforms state based on block.
+ */
+static void
+MD4Transform (UINT4 state[4], const unsigned char block[64])
+{
+       UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
+
+       Decode(x, block, 64);
+
+       /* Round 1 */
+       FF (a, b, c, d, x[ 0], S11); /* 1 */
+       FF (d, a, b, c, x[ 1], S12); /* 2 */
+       FF (c, d, a, b, x[ 2], S13); /* 3 */
+       FF (b, c, d, a, x[ 3], S14); /* 4 */
+       FF (a, b, c, d, x[ 4], S11); /* 5 */
+       FF (d, a, b, c, x[ 5], S12); /* 6 */
+       FF (c, d, a, b, x[ 6], S13); /* 7 */
+       FF (b, c, d, a, x[ 7], S14); /* 8 */
+       FF (a, b, c, d, x[ 8], S11); /* 9 */
+       FF (d, a, b, c, x[ 9], S12); /* 10 */
+       FF (c, d, a, b, x[10], S13); /* 11 */
+       FF (b, c, d, a, x[11], S14); /* 12 */
+       FF (a, b, c, d, x[12], S11); /* 13 */
+       FF (d, a, b, c, x[13], S12); /* 14 */
+       FF (c, d, a, b, x[14], S13); /* 15 */
+       FF (b, c, d, a, x[15], S14); /* 16 */
+
+       /* Round 2 */
+       GG (a, b, c, d, x[ 0], S21); /* 17 */
+       GG (d, a, b, c, x[ 4], S22); /* 18 */
+       GG (c, d, a, b, x[ 8], S23); /* 19 */
+       GG (b, c, d, a, x[12], S24); /* 20 */
+       GG (a, b, c, d, x[ 1], S21); /* 21 */
+       GG (d, a, b, c, x[ 5], S22); /* 22 */
+       GG (c, d, a, b, x[ 9], S23); /* 23 */
+       GG (b, c, d, a, x[13], S24); /* 24 */
+       GG (a, b, c, d, x[ 2], S21); /* 25 */
+       GG (d, a, b, c, x[ 6], S22); /* 26 */
+       GG (c, d, a, b, x[10], S23); /* 27 */
+       GG (b, c, d, a, x[14], S24); /* 28 */
+       GG (a, b, c, d, x[ 3], S21); /* 29 */
+       GG (d, a, b, c, x[ 7], S22); /* 30 */
+       GG (c, d, a, b, x[11], S23); /* 31 */
+       GG (b, c, d, a, x[15], S24); /* 32 */
+
+       /* Round 3 */
+       HH (a, b, c, d, x[ 0], S31); /* 33 */
+       HH (d, a, b, c, x[ 8], S32); /* 34 */
+       HH (c, d, a, b, x[ 4], S33); /* 35 */
+       HH (b, c, d, a, x[12], S34); /* 36 */
+       HH (a, b, c, d, x[ 2], S31); /* 37 */
+       HH (d, a, b, c, x[10], S32); /* 38 */
+       HH (c, d, a, b, x[ 6], S33); /* 39 */
+       HH (b, c, d, a, x[14], S34); /* 40 */
+       HH (a, b, c, d, x[ 1], S31); /* 41 */
+       HH (d, a, b, c, x[ 9], S32); /* 42 */
+       HH (c, d, a, b, x[ 5], S33); /* 43 */
+       HH (b, c, d, a, x[13], S34); /* 44 */
+       HH (a, b, c, d, x[ 3], S31); /* 45 */
+       HH (d, a, b, c, x[11], S32); /* 46 */
+       HH (c, d, a, b, x[ 7], S33); /* 47 */
+       HH (b, c, d, a, x[15], S34); /* 48 */
+
+       state[0] += a;
+       state[1] += b;
+       state[2] += c;
+       state[3] += d;
+
+       /* Zeroize sensitive information. */
+       memset(x, 0, sizeof (x));
+}
+
+/*
+ * Encodes input (UINT4) into output (unsigned char). Assumes len is
+ * a multiple of 4.
+ */
+static void
+Encode(unsigned char *output, UINT4 *input, unsigned int len)
+{
+       unsigned int i, j;
+
+       for (i = 0, j = 0; j < len; i++, j += 4) {
+               output[j] = (unsigned char)(input[i] & 0xff);
+               output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
+               output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
+               output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
+       }
+}
+
+/*
+ * Decodes input (unsigned char) into output (UINT4). Assumes len is
+ * a multiple of 4.
+ */
+static void
+Decode(UINT4 *output, const unsigned char *input, unsigned int len)
+{
+       unsigned int i, j;
+
+       for (i = 0, j = 0; j < len; i++, j += 4)
+               output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) |
+                   (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
+}
+
+#endif /* HAVE_MD4_H */
diff --git a/common/lib/libc/md/md5c.c b/common/lib/libc/md/md5c.c
new file mode 100644 (file)
index 0000000..e15548d
--- /dev/null
@@ -0,0 +1,357 @@
+/*     $NetBSD: md5c.c,v 1.4 2009/03/16 05:59:21 cegger Exp $  */
+
+/*
+ * This file is derived from the RSA Data Security, Inc. MD5 Message-Digest
+ * Algorithm and has been modified by Jason R. Thorpe <thorpej@NetBSD.org>
+ * for portability and formatting.
+ */
+
+/*
+ * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
+ * rights reserved.
+ *
+ * License to copy and use this software is granted provided that it
+ * is identified as the "RSA Data Security, Inc. MD5 Message-Digest
+ * Algorithm" in all material mentioning or referencing this software
+ * or this function.
+ *
+ * License is also granted to make and use derivative works provided
+ * that such works are identified as "derived from the RSA Data
+ * Security, Inc. MD5 Message-Digest Algorithm" in all material
+ * mentioning or referencing the derived work.
+ *
+ * RSA Data Security, Inc. makes no representations concerning either
+ * the merchantability of this software or the suitability of this
+ * software for any particular purpose. It is provided "as is"
+ * without express or implied warranty of any kind.
+ *
+ * These notices must be retained in any copies of any part of this
+ * documentation and/or software.
+ */
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+#include <sys/param.h>
+#include <sys/md5.h>
+#include <lib/libkern/libkern.h>
+#else
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: md5c.c,v 1.4 2009/03/16 05:59:21 cegger Exp $");
+#endif /* LIBC_SCCS and not lint */
+#include "namespace.h"
+#include <sys/types.h>
+#include <assert.h>
+#include <string.h>
+#include <md5.h>
+#endif /* _KERNEL || _STANDALONE */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#if !HAVE_MD5_H
+
+#define        ZEROIZE(d, l)           memset((d), 0, (l))
+
+typedef unsigned char *POINTER;
+typedef uint16_t UINT2;
+typedef uint32_t UINT4;
+
+/*
+ * Constants for MD5Transform routine.
+ */
+#define S11 7
+#define S12 12
+#define S13 17
+#define S14 22
+#define S21 5
+#define S22 9
+#define S23 14
+#define S24 20
+#define S31 4
+#define S32 11
+#define S33 16
+#define S34 23
+#define S41 6
+#define S42 10
+#define S43 15
+#define S44 21
+
+#if !defined(_KERNEL) && !defined(_STANDALONE) && defined(__weak_alias)
+__weak_alias(MD5Init,_MD5Init)
+__weak_alias(MD5Update,_MD5Update)
+__weak_alias(MD5Final,_MD5Final)
+__weak_alias(MD5Transform,_MD5Transform)
+#endif
+
+static void MD5Transform __P((UINT4 [4], const unsigned char [64]));
+
+static void Encode __P((unsigned char *, UINT4 *, unsigned int));
+static void Decode __P((UINT4 *, const unsigned char *, unsigned int));
+
+/*
+ * Encodes input (UINT4) into output (unsigned char).  Assumes len is
+ * a multiple of 4.
+ */
+static void
+Encode (unsigned char *output,
+       UINT4 *input,
+       unsigned int len)
+{
+       unsigned int i, j;
+
+       for (i = 0, j = 0; j < len; i++, j += 4) {
+               output[j] = (unsigned char)(input[i] & 0xff);
+               output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
+               output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
+               output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
+       }
+}
+
+/*
+ * Decodes input (unsigned char) into output (UINT4).  Assumes len is
+ * a multiple of 4.
+ */
+static void
+Decode (UINT4 *output,
+       const unsigned char *input,
+       unsigned int len)
+{
+       unsigned int i, j;
+
+       for (i = 0, j = 0; j < len; i++, j += 4)
+               output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) |
+                   (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
+}
+
+static const unsigned char PADDING[64] = {
+       0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+/*
+ * F, G, H and I are basic MD5 functions.
+ */
+#define F(x, y, z)     (((x) & (y)) | ((~x) & (z)))
+#define G(x, y, z)     (((x) & (z)) | ((y) & (~z)))
+#define H(x, y, z)     ((x) ^ (y) ^ (z))
+#define I(x, y, z)     ((y) ^ ((x) | (~z)))
+
+/*
+ * ROTATE_LEFT rotates x left n bits.
+ */
+#define ROTATE_LEFT(x, n)      (((x) << (n)) | ((x) >> (32-(n))))
+
+/*
+ * FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
+ * Rotation is separate from addition to prevent recomputation.
+ */
+#define FF(a, b, c, d, x, s, ac) { \
+       (a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \
+       (a) = ROTATE_LEFT ((a), (s)); \
+       (a) += (b); \
+}
+
+#define GG(a, b, c, d, x, s, ac) { \
+       (a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \
+       (a) = ROTATE_LEFT ((a), (s)); \
+       (a) += (b); \
+}
+
+#define HH(a, b, c, d, x, s, ac) { \
+       (a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \
+       (a) = ROTATE_LEFT ((a), (s)); \
+       (a) += (b); \
+}
+
+#define II(a, b, c, d, x, s, ac) { \
+       (a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \
+       (a) = ROTATE_LEFT ((a), (s)); \
+       (a) += (b); \
+}
+
+/*
+ * MD5 initialization. Begins an MD5 operation, writing a new context.
+ */
+void
+MD5Init(MD5_CTX *context)
+{
+
+       _DIAGASSERT(context != 0);
+
+       context->count[0] = context->count[1] = 0;
+
+       /* Load magic initialization constants. */
+       context->state[0] = 0x67452301;
+       context->state[1] = 0xefcdab89;
+       context->state[2] = 0x98badcfe;
+       context->state[3] = 0x10325476;
+}
+
+/*
+ * MD5 block update operation.  Continues an MD5 message-digest
+ * operation, processing another message block, and updating the
+ * context.
+ */
+void
+MD5Update(MD5_CTX *context,
+       const unsigned char *input,     /* input block */
+       unsigned int inputLen)          /* length of input block */
+{
+       unsigned int i, idx, partLen;
+
+       _DIAGASSERT(context != 0);
+       _DIAGASSERT(input != 0);
+
+       /* Compute number of bytes mod 64 */
+       idx = (unsigned int)((context->count[0] >> 3) & 0x3F);
+
+       /* Update number of bits */
+       if ((context->count[0] += ((UINT4)inputLen << 3))
+           < ((UINT4)inputLen << 3))
+               context->count[1]++;
+       context->count[1] += ((UINT4)inputLen >> 29);
+
+       partLen = 64 - idx;
+
+       /* Transform as many times as possible. */
+       if (inputLen >= partLen) {
+               memcpy((POINTER)&context->buffer[idx], input, partLen);
+               MD5Transform(context->state, context->buffer);
+
+               for (i = partLen; i + 63 < inputLen; i += 64)
+                       MD5Transform(context->state, &input[i]);
+
+               idx = 0;
+       } else
+               i = 0;
+
+       /* Buffer remaining input */
+       memcpy(&context->buffer[idx], &input[i], inputLen - i);
+}
+
+/*
+ * MD5 finalization.  Ends an MD5 message-digest operation, writing the
+ * message digest and zeroing the context.
+ */
+void
+MD5Final(unsigned char digest[16],     /* message digest */
+       MD5_CTX *context)               /* context */
+{
+       unsigned char bits[8];
+       unsigned int idx, padLen;
+
+       _DIAGASSERT(digest != 0);
+       _DIAGASSERT(context != 0);
+
+       /* Save number of bits */
+       Encode(bits, context->count, 8);
+
+       /* Pad out to 56 mod 64. */
+       idx = (unsigned int)((context->count[0] >> 3) & 0x3f);
+       padLen = (idx < 56) ? (56 - idx) : (120 - idx);
+       MD5Update (context, PADDING, padLen);
+
+       /* Append length (before padding) */
+       MD5Update(context, bits, 8);
+
+       /* Store state in digest */
+       Encode(digest, context->state, 16);
+
+       /* Zeroize sensitive information. */
+       ZEROIZE((POINTER)(void *)context, sizeof(*context));
+}
+
+/*
+ * MD5 basic transformation. Transforms state based on block.
+ */
+static void
+MD5Transform(UINT4 state[4], const unsigned char block[64])
+{
+       UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
+
+       Decode(x, block, 64);
+
+       /* Round 1 */
+       FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
+       FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
+       FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
+       FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
+       FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
+       FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
+       FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
+       FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
+       FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
+       FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
+       FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
+       FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
+       FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
+       FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
+       FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
+       FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
+
+       /* Round 2 */
+       GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
+       GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
+       GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
+       GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
+       GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
+       GG (d, a, b, c, x[10], S22,  0x2441453); /* 22 */
+       GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
+       GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
+       GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
+       GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
+       GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
+       GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
+       GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
+       GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
+       GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
+       GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
+
+       /* Round 3 */
+       HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
+       HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
+       HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
+       HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
+       HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
+       HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
+       HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
+       HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
+       HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
+       HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
+       HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
+       HH (b, c, d, a, x[ 6], S34,  0x4881d05); /* 44 */
+       HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
+       HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
+       HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
+       HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
+
+       /* Round 4 */
+       II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
+       II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
+       II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
+       II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
+       II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
+       II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
+       II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
+       II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
+       II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
+       II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
+       II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
+       II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
+       II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
+       II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
+       II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
+       II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
+
+       state[0] += a;
+       state[1] += b;
+       state[2] += c;
+       state[3] += d;
+
+       /* Zeroize sensitive information. */
+       ZEROIZE((POINTER)(void *)x, sizeof (x));
+}
+
+#endif /* HAVE_MD5_H */
diff --git a/common/lib/libc/net/__cmsg_alignbytes.c b/common/lib/libc/net/__cmsg_alignbytes.c
new file mode 100644 (file)
index 0000000..726ff56
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: __cmsg_alignbytes.c,v 1.3 2009/03/16 05:59:21 cegger Exp $     */
+
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jun-ichiro Hagino.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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(_KERNEL) && !defined(_STANDALONE)
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __cmsg_alignbytes.c,v 1.3 2009/03/16 05:59:21 cegger Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/sysctl.h>
+#include <sys/socket.h>
+#else
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#endif
+
+int
+__cmsg_alignbytes(void)
+{
+       static int alignbytes = -1;
+#ifdef HW_ALIGNBYTES
+       int mib[2];
+       size_t len;
+       int ret;
+#endif
+
+       if (alignbytes > 0)
+               return alignbytes;
+
+#ifdef HW_ALIGNBYTES
+       mib[0] = CTL_HW;
+       mib[1] = HW_ALIGNBYTES;
+       len = sizeof(alignbytes);
+       ret = sysctl(mib, (u_int) (sizeof(mib) / sizeof(mib[0])),
+           (void *)&alignbytes, &len, NULL, (size_t)0);
+       if (ret >= 0 && alignbytes >= 0)
+               return alignbytes;
+#endif
+       /* last resort */
+       alignbytes = ALIGNBYTES;
+       return alignbytes;
+}
diff --git a/common/lib/libc/net/htonl.c b/common/lib/libc/net/htonl.c
new file mode 100644 (file)
index 0000000..7edc4f8
--- /dev/null
@@ -0,0 +1,27 @@
+/*     $NetBSD: htonl.c,v 1.1 2005/12/20 19:28:51 christos Exp $       */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: htonl.c,v 1.1 2005/12/20 19:28:51 christos Exp $");
+#endif
+
+#include <sys/types.h>
+
+#undef htonl
+
+uint32_t 
+htonl(x)
+       uint32_t x;
+{
+#if BYTE_ORDER == LITTLE_ENDIAN
+       u_char *s = (u_char *)&x;
+       return (uint32_t)(s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]);
+#else
+       return x;
+#endif
+}
diff --git a/common/lib/libc/net/htons.c b/common/lib/libc/net/htons.c
new file mode 100644 (file)
index 0000000..830db0f
--- /dev/null
@@ -0,0 +1,27 @@
+/*     $NetBSD: htons.c,v 1.1 2005/12/20 19:28:51 christos Exp $       */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: htons.c,v 1.1 2005/12/20 19:28:51 christos Exp $");
+#endif
+
+#include <sys/types.h>
+
+#undef htons
+
+uint16_t
+htons(x)
+       uint16_t x;
+{
+#if BYTE_ORDER == LITTLE_ENDIAN
+       u_char *s = (u_char *) &x;
+       return (uint16_t)(s[0] << 8 | s[1]);
+#else
+       return x;
+#endif
+}
diff --git a/common/lib/libc/net/ntohl.c b/common/lib/libc/net/ntohl.c
new file mode 100644 (file)
index 0000000..dc0ca9a
--- /dev/null
@@ -0,0 +1,27 @@
+/*     $NetBSD: ntohl.c,v 1.1 2005/12/20 19:28:51 christos Exp $       */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ntohl.c,v 1.1 2005/12/20 19:28:51 christos Exp $");
+#endif
+
+#include <sys/types.h>
+
+#undef ntohl
+
+uint32_t
+ntohl(x)
+       uint32_t x;
+{
+#if BYTE_ORDER == LITTLE_ENDIAN
+       u_char *s = (u_char *)&x;
+       return (uint32_t)(s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]);
+#else
+       return x;
+#endif
+}
diff --git a/common/lib/libc/net/ntohs.c b/common/lib/libc/net/ntohs.c
new file mode 100644 (file)
index 0000000..eb4e841
--- /dev/null
@@ -0,0 +1,27 @@
+/*     $NetBSD: ntohs.c,v 1.1 2005/12/20 19:28:51 christos Exp $       */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ntohs.c,v 1.1 2005/12/20 19:28:51 christos Exp $");
+#endif
+
+#include <sys/types.h>
+
+#undef ntohs
+
+uint16_t
+ntohs(x)
+       uint16_t x;
+{
+#if BYTE_ORDER == LITTLE_ENDIAN
+       u_char *s = (u_char *) &x;
+       return (uint16_t)(s[0] << 8 | s[1]);
+#else
+       return x;
+#endif
+}
diff --git a/common/lib/libc/quad/adddi3.c b/common/lib/libc/quad/adddi3.c
new file mode 100644 (file)
index 0000000..81eaede
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: adddi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)adddi3.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: adddi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Add two quads.  This is trivial since a one-bit carry from a single
+ * u_int addition x+y occurs if and only if the sum x+y is less than
+ * either x or y (the choice to compare with x or y is arbitrary).
+ */
+quad_t
+__adddi3(quad_t a, quad_t b)
+{
+       union uu aa, bb, sum;
+
+       aa.q = a;
+       bb.q = b;
+       sum.ul[L] = aa.ul[L] + bb.ul[L];
+       sum.ul[H] = aa.ul[H] + bb.ul[H] + (sum.ul[L] < bb.ul[L]);
+       return (sum.q);
+}
diff --git a/common/lib/libc/quad/anddi3.c b/common/lib/libc/quad/anddi3.c
new file mode 100644 (file)
index 0000000..4a5605a
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: anddi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)anddi3.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: anddi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Return a & b, in quad.
+ */
+quad_t
+__anddi3(quad_t a, quad_t b)
+{
+       union uu aa, bb;
+
+       aa.q = a;
+       bb.q = b;
+       aa.ul[0] &= bb.ul[0];
+       aa.ul[1] &= bb.ul[1];
+       return (aa.q);
+}
diff --git a/common/lib/libc/quad/ashldi3.c b/common/lib/libc/quad/ashldi3.c
new file mode 100644 (file)
index 0000000..d242614
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: ashldi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $       */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ashldi3.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: ashldi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Shift a (signed) quad value left (arithmetic shift left).
+ * This is the same as logical shift left!
+ */
+quad_t
+__ashldi3(quad_t a, qshift_t shift)
+{
+       union uu aa;
+
+       if (shift == 0)
+               return(a);
+       aa.q = a;
+       if (shift >= INT_BITS) {
+               aa.ul[H] = aa.ul[L] << (shift - INT_BITS);
+               aa.ul[L] = 0;
+       } else {
+               aa.ul[H] = (aa.ul[H] << shift) |
+                   (aa.ul[L] >> (INT_BITS - shift));
+               aa.ul[L] <<= shift;
+       }
+       return (aa.q);
+}
diff --git a/common/lib/libc/quad/ashrdi3.c b/common/lib/libc/quad/ashrdi3.c
new file mode 100644 (file)
index 0000000..c064b57
--- /dev/null
@@ -0,0 +1,80 @@
+/*     $NetBSD: ashrdi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $       */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ashrdi3.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: ashrdi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Shift a (signed) quad value right (arithmetic shift right).
+ */
+quad_t
+__ashrdi3(quad_t a, qshift_t shift)
+{
+       union uu aa;
+
+       if (shift == 0)
+               return(a);
+       aa.q = a;
+       if (shift >= INT_BITS) {
+               int s;
+
+               /*
+                * Smear bits rightward using the machine's right-shift
+                * method, whether that is sign extension or zero fill,
+                * to get the `sign word' s.  Note that shifting by
+                * INT_BITS is undefined, so we shift (INT_BITS-1),
+                * then 1 more, to get our answer.
+                */
+               /* LINTED inherits machine dependency */
+               s = (aa.sl[H] >> (INT_BITS - 1)) >> 1;
+               /* LINTED inherits machine dependency*/
+               aa.ul[L] = aa.sl[H] >> (shift - INT_BITS);
+               aa.ul[H] = s;
+       } else {
+               aa.ul[L] = (aa.ul[L] >> shift) |
+                   (aa.ul[H] << (INT_BITS - shift));
+               /* LINTED inherits machine dependency */
+               aa.sl[H] >>= shift;
+       }
+       return (aa.q);
+}
diff --git a/common/lib/libc/quad/cmpdi2.c b/common/lib/libc/quad/cmpdi2.c
new file mode 100644 (file)
index 0000000..e1b3c42
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: cmpdi2.c,v 1.2 2009/03/15 22:31:12 cegger Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)cmpdi2.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: cmpdi2.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Return 0, 1, or 2 as a <, =, > b respectively.
+ * Both a and b are considered signed---which means only the high word is
+ * signed.
+ */
+int
+__cmpdi2(quad_t a, quad_t b)
+{
+       union uu aa, bb;
+
+       aa.q = a;
+       bb.q = b;
+       return (aa.sl[H] < bb.sl[H] ? 0 : aa.sl[H] > bb.sl[H] ? 2 :
+           aa.ul[L] < bb.ul[L] ? 0 : aa.ul[L] > bb.ul[L] ? 2 : 1);
+}
diff --git a/common/lib/libc/quad/divdi3.c b/common/lib/libc/quad/divdi3.c
new file mode 100644 (file)
index 0000000..b241ed1
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: divdi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)divdi3.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: divdi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Divide two signed quads.
+ * ??? if -1/2 should produce -1 on this machine, this code is wrong
+ */
+quad_t
+__divdi3(quad_t a, quad_t b)
+{
+       u_quad_t ua, ub, uq;
+       int neg = 0;
+
+       ua = a;
+       ub = b;
+
+       if (a < 0)
+               ua = -ua, neg ^= 1;
+       if (b < 0)
+               ub = -ub, neg ^= 1;
+
+       uq = __qdivrem(ua, ub, (u_quad_t *)0);
+       if (neg)
+               uq = - uq;
+       return uq;
+}
diff --git a/common/lib/libc/quad/iordi3.c b/common/lib/libc/quad/iordi3.c
new file mode 100644 (file)
index 0000000..300bdca
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: iordi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)iordi3.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: iordi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Return a | b, in quad.
+ */
+quad_t
+__iordi3(quad_t a, quad_t b)
+{
+       union uu aa, bb;
+
+       aa.q = a;
+       bb.q = b;
+       aa.ul[0] |= bb.ul[0];
+       aa.ul[1] |= bb.ul[1];
+       return (aa.q);
+}
diff --git a/common/lib/libc/quad/lshldi3.c b/common/lib/libc/quad/lshldi3.c
new file mode 100644 (file)
index 0000000..6525524
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: lshldi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $       */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)lshldi3.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: lshldi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Shift an (unsigned) quad value left (logical shift left).
+ * This is the same as arithmetic shift left!
+ */
+quad_t
+__lshldi3(quad_t a, qshift_t shift)
+{
+       union uu aa;
+
+       if (shift == 0)
+               return(a);
+       aa.q = a;
+       if (shift >= INT_BITS) {
+               aa.ul[H] = aa.ul[L] << (shift - INT_BITS);
+               aa.ul[L] = 0;
+       } else {
+               aa.ul[H] = (aa.ul[H] << shift) |
+                   (aa.ul[L] >> (INT_BITS - shift));
+               aa.ul[L] <<= shift;
+       }
+       return (aa.q);
+}
diff --git a/common/lib/libc/quad/lshrdi3.c b/common/lib/libc/quad/lshrdi3.c
new file mode 100644 (file)
index 0000000..80a4b6d
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: lshrdi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $       */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)lshrdi3.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: lshrdi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Shift an (unsigned) quad value right (logical shift right).
+ */
+quad_t
+__lshrdi3(quad_t a, qshift_t shift)
+{
+       union uu aa;
+
+       if (shift == 0)
+               return(a);
+       aa.q = a;
+       if (shift >= INT_BITS) {
+               aa.ul[L] = aa.ul[H] >> (shift - INT_BITS);
+               aa.ul[H] = 0;
+       } else {
+               aa.ul[L] = (aa.ul[L] >> shift) |
+                   (aa.ul[H] << (INT_BITS - shift));
+               aa.ul[H] >>= shift;
+       }
+       return (aa.q);
+}
diff --git a/common/lib/libc/quad/moddi3.c b/common/lib/libc/quad/moddi3.c
new file mode 100644 (file)
index 0000000..74333b9
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: moddi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)moddi3.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: moddi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Return remainder after dividing two signed quads.
+ *
+ * XXX we assume a % b < 0 iff a < 0, but this is actually machine-dependent.
+ */
+quad_t
+__moddi3(quad_t a, quad_t b)
+{
+       u_quad_t ua, ub, ur;
+       int neg = 0;
+
+       ua = a;
+       ub = b;
+
+       if (a < 0)
+               ua = -ua, neg ^= 1;
+       if (b < 0)
+               ub = -ub;
+       (void)__qdivrem(ua, ub, &ur);
+       if (neg)
+               ur = -ur;
+       return (ur);
+}
diff --git a/common/lib/libc/quad/muldi3.c b/common/lib/libc/quad/muldi3.c
new file mode 100644 (file)
index 0000000..bf3b5bd
--- /dev/null
@@ -0,0 +1,248 @@
+/*     $NetBSD: muldi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)muldi3.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: muldi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Multiply two quads.
+ *
+ * Our algorithm is based on the following.  Split incoming quad values
+ * u and v (where u,v >= 0) into
+ *
+ *     u = 2^n u1  *  u0       (n = number of bits in `u_int', usu. 32)
+ *
+ * and 
+ *
+ *     v = 2^n v1  *  v0
+ *
+ * Then
+ *
+ *     uv = 2^2n u1 v1  +  2^n u1 v0  +  2^n v1 u0  +  u0 v0
+ *        = 2^2n u1 v1  +     2^n (u1 v0 + v1 u0)   +  u0 v0
+ *
+ * Now add 2^n u1 v1 to the first term and subtract it from the middle,
+ * and add 2^n u0 v0 to the last term and subtract it from the middle.
+ * This gives:
+ *
+ *     uv = (2^2n + 2^n) (u1 v1)  +
+ *              (2^n)    (u1 v0 - u1 v1 + u0 v1 - u0 v0)  +
+ *            (2^n + 1)  (u0 v0)
+ *
+ * Factoring the middle a bit gives us:
+ *
+ *     uv = (2^2n + 2^n) (u1 v1)  +                    [u1v1 = high]
+ *              (2^n)    (u1 - u0) (v0 - v1)  +        [(u1-u0)... = mid]
+ *            (2^n + 1)  (u0 v0)                       [u0v0 = low]
+ *
+ * The terms (u1 v1), (u1 - u0) (v0 - v1), and (u0 v0) can all be done
+ * in just half the precision of the original.  (Note that either or both
+ * of (u1 - u0) or (v0 - v1) may be negative.)
+ *
+ * This algorithm is from Knuth vol. 2 (2nd ed), section 4.3.3, p. 278.
+ *
+ * Since C does not give us a `int * int = quad' operator, we split
+ * our input quads into two ints, then split the two ints into two
+ * shorts.  We can then calculate `short * short = int' in native
+ * arithmetic.
+ *
+ * Our product should, strictly speaking, be a `long quad', with 128
+ * bits, but we are going to discard the upper 64.  In other words,
+ * we are not interested in uv, but rather in (uv mod 2^2n).  This
+ * makes some of the terms above vanish, and we get:
+ *
+ *     (2^n)(high) + (2^n)(mid) + (2^n + 1)(low)
+ *
+ * or
+ *
+ *     (2^n)(high + mid + low) + low
+ *
+ * Furthermore, `high' and `mid' can be computed mod 2^n, as any factor
+ * of 2^n in either one will also vanish.  Only `low' need be computed
+ * mod 2^2n, and only because of the final term above.
+ */
+static quad_t __lmulq(u_int, u_int);
+
+quad_t
+__muldi3(quad_t a, quad_t b)
+{
+       union uu u, v, low, prod;
+       u_int high, mid, udiff, vdiff;
+       int negall, negmid;
+#define        u1      u.ul[H]
+#define        u0      u.ul[L]
+#define        v1      v.ul[H]
+#define        v0      v.ul[L]
+
+       /*
+        * Get u and v such that u, v >= 0.  When this is finished,
+        * u1, u0, v1, and v0 will be directly accessible through the
+        * int fields.
+        */
+       if (a >= 0)
+               u.q = a, negall = 0;
+       else
+               u.q = -a, negall = 1;
+       if (b >= 0)
+               v.q = b;
+       else
+               v.q = -b, negall ^= 1;
+
+       if (u1 == 0 && v1 == 0) {
+               /*
+                * An (I hope) important optimization occurs when u1 and v1
+                * are both 0.  This should be common since most numbers
+                * are small.  Here the product is just u0*v0.
+                */
+               prod.q = __lmulq(u0, v0);
+       } else {
+               /*
+                * Compute the three intermediate products, remembering
+                * whether the middle term is negative.  We can discard
+                * any upper bits in high and mid, so we can use native
+                * u_int * u_int => u_int arithmetic.
+                */
+               low.q = __lmulq(u0, v0);
+
+               if (u1 >= u0)
+                       negmid = 0, udiff = u1 - u0;
+               else
+                       negmid = 1, udiff = u0 - u1;
+               if (v0 >= v1)
+                       vdiff = v0 - v1;
+               else
+                       vdiff = v1 - v0, negmid ^= 1;
+               mid = udiff * vdiff;
+
+               high = u1 * v1;
+
+               /*
+                * Assemble the final product.
+                */
+               prod.ul[H] = high + (negmid ? -mid : mid) + low.ul[L] +
+                   low.ul[H];
+               prod.ul[L] = low.ul[L];
+       }
+       return (negall ? -prod.q : prod.q);
+#undef u1
+#undef u0
+#undef v1
+#undef v0
+}
+
+/*
+ * Multiply two 2N-bit ints to produce a 4N-bit quad, where N is half
+ * the number of bits in an int (whatever that is---the code below
+ * does not care as long as quad.h does its part of the bargain---but
+ * typically N==16).
+ *
+ * We use the same algorithm from Knuth, but this time the modulo refinement
+ * does not apply.  On the other hand, since N is half the size of an int,
+ * we can get away with native multiplication---none of our input terms
+ * exceeds (UINT_MAX >> 1).
+ *
+ * Note that, for u_int l, the quad-precision result
+ *
+ *     l << N
+ *
+ * splits into high and low ints as HHALF(l) and LHUP(l) respectively.
+ */
+static quad_t
+__lmulq(u_int u, u_int v)
+{
+       u_int u1, u0, v1, v0, udiff, vdiff, high, mid, low;
+       u_int prodh, prodl, was;
+       union uu prod;
+       int neg;
+
+       u1 = HHALF(u);
+       u0 = LHALF(u);
+       v1 = HHALF(v);
+       v0 = LHALF(v);
+
+       low = u0 * v0;
+
+       /* This is the same small-number optimization as before. */
+       if (u1 == 0 && v1 == 0)
+               return (low);
+
+       if (u1 >= u0)
+               udiff = u1 - u0, neg = 0;
+       else
+               udiff = u0 - u1, neg = 1;
+       if (v0 >= v1)
+               vdiff = v0 - v1;
+       else
+               vdiff = v1 - v0, neg ^= 1;
+       mid = udiff * vdiff;
+
+       high = u1 * v1;
+
+       /* prod = (high << 2N) + (high << N); */
+       prodh = high + HHALF(high);
+       prodl = LHUP(high);
+
+       /* if (neg) prod -= mid << N; else prod += mid << N; */
+       if (neg) {
+               was = prodl;
+               prodl -= LHUP(mid);
+               prodh -= HHALF(mid) + (prodl > was);
+       } else {
+               was = prodl;
+               prodl += LHUP(mid);
+               prodh += HHALF(mid) + (prodl < was);
+       }
+
+       /* prod += low << N */
+       was = prodl;
+       prodl += LHUP(low);
+       prodh += HHALF(low) + (prodl < was);
+       /* ... + low; */
+       if ((prodl += low) < low)
+               prodh++;
+
+       /* return 4N-bit product */
+       prod.ul[H] = prodh;
+       prod.ul[L] = prodl;
+       return (prod.q);
+}
diff --git a/common/lib/libc/quad/negdi2.c b/common/lib/libc/quad/negdi2.c
new file mode 100644 (file)
index 0000000..000889a
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: negdi2.c,v 1.2 2009/03/15 22:31:12 cegger Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)negdi2.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: negdi2.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Return -a (or, equivalently, 0 - a), in quad.  See subdi3.c.
+ */
+quad_t
+__negdi2(quad_t a)
+{
+       union uu aa, res;
+
+       aa.q = a;
+       res.ul[L] = -aa.ul[L];
+       res.ul[H] = -aa.ul[H] - (res.ul[L] > 0);
+       return (res.q);
+}
diff --git a/common/lib/libc/quad/notdi2.c b/common/lib/libc/quad/notdi2.c
new file mode 100644 (file)
index 0000000..1706b6d
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: notdi2.c,v 1.2 2009/03/15 22:31:12 cegger Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)notdi2.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: notdi2.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Return ~a.  For some reason gcc calls this `one's complement' rather
+ * than `not'.
+ */
+quad_t
+__one_cmpldi2(quad_t a)
+{
+       union uu aa;
+
+       aa.q = a;
+       aa.ul[0] = ~aa.ul[0];
+       aa.ul[1] = ~aa.ul[1];
+       return (aa.q);
+}
diff --git a/common/lib/libc/quad/qdivrem.c b/common/lib/libc/quad/qdivrem.c
new file mode 100644 (file)
index 0000000..84b7781
--- /dev/null
@@ -0,0 +1,284 @@
+/*     $NetBSD: qdivrem.c,v 1.2 2009/03/15 22:31:12 cegger Exp $       */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)qdivrem.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: qdivrem.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Multiprecision divide.  This algorithm is from Knuth vol. 2 (2nd ed),
+ * section 4.3.1, pp. 257--259.
+ */
+
+#include "quad.h"
+
+#define        B       ((int)1 << HALF_BITS)   /* digit base */
+
+/* Combine two `digits' to make a single two-digit number. */
+#define        COMBINE(a, b) (((u_int)(a) << HALF_BITS) | (b))
+
+/* select a type for digits in base B: use unsigned short if they fit */
+#if UINT_MAX == 0xffffffffU && USHRT_MAX >= 0xffff
+typedef unsigned short digit;
+#else
+typedef u_int digit;
+#endif
+
+static void shl __P((digit *p, int len, int sh));
+
+/*
+ * __qdivrem(u, v, rem) returns u/v and, optionally, sets *rem to u%v.
+ *
+ * We do this in base 2-sup-HALF_BITS, so that all intermediate products
+ * fit within u_int.  As a consequence, the maximum length dividend and
+ * divisor are 4 `digits' in this base (they are shorter if they have
+ * leading zeros).
+ */
+u_quad_t
+__qdivrem(u_quad_t uq, u_quad_t vq, u_quad_t *arq)
+{
+       union uu tmp;
+       digit *u, *v, *q;
+       digit v1, v2;
+       u_int qhat, rhat, t;
+       int m, n, d, j, i;
+       digit uspace[5], vspace[5], qspace[5];
+
+       /*
+        * Take care of special cases: divide by zero, and u < v.
+        */
+       if (vq == 0) {
+               /* divide by zero. */
+               static volatile const unsigned int zero = 0;
+
+               tmp.ul[H] = tmp.ul[L] = 1 / zero;
+               if (arq)
+                       *arq = uq;
+               return (tmp.q);
+       }
+       if (uq < vq) {
+               if (arq)
+                       *arq = uq;
+               return (0);
+       }
+       u = &uspace[0];
+       v = &vspace[0];
+       q = &qspace[0];
+
+       /*
+        * Break dividend and divisor into digits in base B, then
+        * count leading zeros to determine m and n.  When done, we
+        * will have:
+        *      u = (u[1]u[2]...u[m+n]) sub B
+        *      v = (v[1]v[2]...v[n]) sub B
+        *      v[1] != 0
+        *      1 < n <= 4 (if n = 1, we use a different division algorithm)
+        *      m >= 0 (otherwise u < v, which we already checked)
+        *      m + n = 4
+        * and thus
+        *      m = 4 - n <= 2
+        */
+       tmp.uq = uq;
+       u[0] = 0;
+       u[1] = (digit)HHALF(tmp.ul[H]);
+       u[2] = (digit)LHALF(tmp.ul[H]);
+       u[3] = (digit)HHALF(tmp.ul[L]);
+       u[4] = (digit)LHALF(tmp.ul[L]);
+       tmp.uq = vq;
+       v[1] = (digit)HHALF(tmp.ul[H]);
+       v[2] = (digit)LHALF(tmp.ul[H]);
+       v[3] = (digit)HHALF(tmp.ul[L]);
+       v[4] = (digit)LHALF(tmp.ul[L]);
+       for (n = 4; v[1] == 0; v++) {
+               if (--n == 1) {
+                       u_int rbj;      /* r*B+u[j] (not root boy jim) */
+                       digit q1, q2, q3, q4;
+
+                       /*
+                        * Change of plan, per exercise 16.
+                        *      r = 0;
+                        *      for j = 1..4:
+                        *              q[j] = floor((r*B + u[j]) / v),
+                        *              r = (r*B + u[j]) % v;
+                        * We unroll this completely here.
+                        */
+                       t = v[2];       /* nonzero, by definition */
+                       q1 = (digit)(u[1] / t);
+                       rbj = COMBINE(u[1] % t, u[2]);
+                       q2 = (digit)(rbj / t);
+                       rbj = COMBINE(rbj % t, u[3]);
+                       q3 = (digit)(rbj / t);
+                       rbj = COMBINE(rbj % t, u[4]);
+                       q4 = (digit)(rbj / t);
+                       if (arq)
+                               *arq = rbj % t;
+                       tmp.ul[H] = COMBINE(q1, q2);
+                       tmp.ul[L] = COMBINE(q3, q4);
+                       return (tmp.q);
+               }
+       }
+
+       /*
+        * By adjusting q once we determine m, we can guarantee that
+        * there is a complete four-digit quotient at &qspace[1] when
+        * we finally stop.
+        */
+       for (m = 4 - n; u[1] == 0; u++)
+               m--;
+       for (i = 4 - m; --i >= 0;)
+               q[i] = 0;
+       q += 4 - m;
+
+       /*
+        * Here we run Program D, translated from MIX to C and acquiring
+        * a few minor changes.
+        *
+        * D1: choose multiplier 1 << d to ensure v[1] >= B/2.
+        */
+       d = 0;
+       for (t = v[1]; t < B / 2; t <<= 1)
+               d++;
+       if (d > 0) {
+               shl(&u[0], m + n, d);           /* u <<= d */
+               shl(&v[1], n - 1, d);           /* v <<= d */
+       }
+       /*
+        * D2: j = 0.
+        */
+       j = 0;
+       v1 = v[1];      /* for D3 -- note that v[1..n] are constant */
+       v2 = v[2];      /* for D3 */
+       do {
+               digit uj0, uj1, uj2;
+               
+               /*
+                * D3: Calculate qhat (\^q, in TeX notation).
+                * Let qhat = min((u[j]*B + u[j+1])/v[1], B-1), and
+                * let rhat = (u[j]*B + u[j+1]) mod v[1].
+                * While rhat < B and v[2]*qhat > rhat*B+u[j+2],
+                * decrement qhat and increase rhat correspondingly.
+                * Note that if rhat >= B, v[2]*qhat < rhat*B.
+                */
+               uj0 = u[j + 0]; /* for D3 only -- note that u[j+...] change */
+               uj1 = u[j + 1]; /* for D3 only */
+               uj2 = u[j + 2]; /* for D3 only */
+               if (uj0 == v1) {
+                       qhat = B;
+                       rhat = uj1;
+                       goto qhat_too_big;
+               } else {
+                       u_int nn = COMBINE(uj0, uj1);
+                       qhat = nn / v1;
+                       rhat = nn % v1;
+               }
+               while (v2 * qhat > COMBINE(rhat, uj2)) {
+       qhat_too_big:
+                       qhat--;
+                       if ((rhat += v1) >= B)
+                               break;
+               }
+               /*
+                * D4: Multiply and subtract.
+                * The variable `t' holds any borrows across the loop.
+                * We split this up so that we do not require v[0] = 0,
+                * and to eliminate a final special case.
+                */
+               for (t = 0, i = n; i > 0; i--) {
+                       t = u[i + j] - v[i] * qhat - t;
+                       u[i + j] = (digit)LHALF(t);
+                       t = (B - HHALF(t)) & (B - 1);
+               }
+               t = u[j] - t;
+               u[j] = (digit)LHALF(t);
+               /*
+                * D5: test remainder.
+                * There is a borrow if and only if HHALF(t) is nonzero;
+                * in that (rare) case, qhat was too large (by exactly 1).
+                * Fix it by adding v[1..n] to u[j..j+n].
+                */
+               if (HHALF(t)) {
+                       qhat--;
+                       for (t = 0, i = n; i > 0; i--) { /* D6: add back. */
+                               t += u[i + j] + v[i];
+                               u[i + j] = (digit)LHALF(t);
+                               t = HHALF(t);
+                       }
+                       u[j] = (digit)LHALF(u[j] + t);
+               }
+               q[j] = (digit)qhat;
+       } while (++j <= m);             /* D7: loop on j. */
+
+       /*
+        * If caller wants the remainder, we have to calculate it as
+        * u[m..m+n] >> d (this is at most n digits and thus fits in
+        * u[m+1..m+n], but we may need more source digits).
+        */
+       if (arq) {
+               if (d) {
+                       for (i = m + n; i > m; --i)
+                               u[i] = (digit)(((u_int)u[i] >> d) |
+                                   LHALF((u_int)u[i - 1] << (HALF_BITS - d)));
+                       u[i] = 0;
+               }
+               tmp.ul[H] = COMBINE(uspace[1], uspace[2]);
+               tmp.ul[L] = COMBINE(uspace[3], uspace[4]);
+               *arq = tmp.q;
+       }
+
+       tmp.ul[H] = COMBINE(qspace[1], qspace[2]);
+       tmp.ul[L] = COMBINE(qspace[3], qspace[4]);
+       return (tmp.q);
+}
+
+/*
+ * Shift p[0]..p[len] left `sh' bits, ignoring any bits that
+ * `fall out' the left (there never will be any such anyway).
+ * We may assume len >= 0.  NOTE THAT THIS WRITES len+1 DIGITS.
+ */
+static void
+shl(digit *p, int len, int sh)
+{
+       int i;
+
+       for (i = 0; i < len; i++)
+               p[i] = (digit)(LHALF((u_int)p[i] << sh) |
+                   ((u_int)p[i + 1] >> (HALF_BITS - sh)));
+       p[i] = (digit)(LHALF((u_int)p[i] << sh));
+}
diff --git a/common/lib/libc/quad/quad.h b/common/lib/libc/quad/quad.h
new file mode 100644 (file)
index 0000000..c509640
--- /dev/null
@@ -0,0 +1,139 @@
+/*     $NetBSD: quad.h,v 1.1 2005/12/20 20:29:40 christos Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ *     @(#)quad.h      8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * Quad arithmetic.
+ *
+ * This library makes the following assumptions:
+ *
+ *  - The type long long (aka quad_t) exists.
+ *
+ *  - A quad variable is exactly twice as long as `int'.
+ *
+ *  - The machine's arithmetic is two's complement.
+ *
+ * This library can provide 128-bit arithmetic on a machine with 128-bit
+ * quads and 64-bit ints, for instance, or 96-bit arithmetic on machines
+ * with 48-bit ints.
+ */
+
+#include <sys/types.h>
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <limits.h>
+#else
+#include <machine/limits.h>
+#endif
+
+/*
+ * Depending on the desired operation, we view a `long long' (aka quad_t) in
+ * one or more of the following formats.
+ */
+union uu {
+       quad_t  q;              /* as a (signed) quad */
+       u_quad_t uq;            /* as an unsigned quad */
+       int     sl[2];          /* as two signed ints */
+       u_int   ul[2];          /* as two unsigned ints */
+};
+
+/*
+ * Define high and low parts of a quad_t.
+ */
+#define        H               _QUAD_HIGHWORD
+#define        L               _QUAD_LOWWORD
+
+/*
+ * Total number of bits in a quad_t and in the pieces that make it up.
+ * These are used for shifting, and also below for halfword extraction
+ * and assembly.
+ */
+#define        QUAD_BITS       (sizeof(quad_t) * CHAR_BIT)
+#define        INT_BITS        (sizeof(int) * CHAR_BIT)
+#define        HALF_BITS       (sizeof(int) * CHAR_BIT / 2)
+
+/*
+ * Extract high and low shortwords from longword, and move low shortword of
+ * longword to upper half of long, i.e., produce the upper longword of
+ * ((quad_t)(x) << (number_of_bits_in_int/2)).  (`x' must actually be u_int.)
+ *
+ * These are used in the multiply code, to split a longword into upper
+ * and lower halves, and to reassemble a product as a quad_t, shifted left
+ * (sizeof(int)*CHAR_BIT/2).
+ */
+#define        HHALF(x)        ((u_int)(x) >> HALF_BITS)
+#define        LHALF(x)        ((u_int)(x) & (((int)1 << HALF_BITS) - 1))
+#define        LHUP(x)         ((u_int)(x) << HALF_BITS)
+
+/*
+ * XXX
+ * Compensate for gcc 1 vs gcc 2.  Gcc 1 defines ?sh?di3's second argument
+ * as u_quad_t, while gcc 2 correctly uses int.  Unfortunately, we still use
+ * both compilers.
+ */
+#if __GNUC_PREREQ__(2, 0) || defined(lint)
+typedef unsigned int   qshift_t;
+#else
+typedef u_quad_t       qshift_t;
+#endif
+
+__BEGIN_DECLS
+quad_t __adddi3 __P((quad_t, quad_t));
+quad_t __anddi3 __P((quad_t, quad_t));
+quad_t __ashldi3 __P((quad_t, qshift_t));
+quad_t __ashrdi3 __P((quad_t, qshift_t));
+int __cmpdi2 __P((quad_t, quad_t));
+quad_t __divdi3 __P((quad_t, quad_t));
+quad_t __fixdfdi __P((double));
+quad_t __fixsfdi __P((float));
+u_quad_t __fixunsdfdi __P((double));
+u_quad_t __fixunssfdi __P((float));
+double __floatdidf __P((quad_t));
+float __floatdisf __P((quad_t));
+double __floatunsdidf __P((u_quad_t));
+quad_t __iordi3 __P((quad_t, quad_t));
+quad_t __lshldi3 __P((quad_t, qshift_t));
+quad_t __lshrdi3 __P((quad_t, qshift_t));
+quad_t __moddi3 __P((quad_t, quad_t));
+quad_t __muldi3 __P((quad_t, quad_t));
+quad_t __negdi2 __P((quad_t));
+quad_t __one_cmpldi2 __P((quad_t));
+u_quad_t __qdivrem __P((u_quad_t, u_quad_t, u_quad_t *));
+quad_t __subdi3 __P((quad_t, quad_t));
+int __ucmpdi2 __P((u_quad_t, u_quad_t));
+u_quad_t __udivdi3 __P((u_quad_t, u_quad_t ));
+u_quad_t __umoddi3 __P((u_quad_t, u_quad_t ));
+quad_t __xordi3 __P((quad_t, quad_t));
+__END_DECLS
diff --git a/common/lib/libc/quad/subdi3.c b/common/lib/libc/quad/subdi3.c
new file mode 100644 (file)
index 0000000..b84ef05
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: subdi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)subdi3.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: subdi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Subtract two quad values.  This is trivial since a one-bit carry
+ * from a single u_int difference x-y occurs if and only if (x-y) > x.
+ */
+quad_t
+__subdi3(quad_t a, quad_t b)
+{
+       union uu aa, bb, diff;
+
+       aa.q = a;
+       bb.q = b;
+       diff.ul[L] = aa.ul[L] - bb.ul[L];
+       diff.ul[H] = aa.ul[H] - bb.ul[H] - (diff.ul[L] > aa.ul[L]);
+       return (diff.q);
+}
diff --git a/common/lib/libc/quad/ucmpdi2.c b/common/lib/libc/quad/ucmpdi2.c
new file mode 100644 (file)
index 0000000..04e7133
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: ucmpdi2.c,v 1.2 2009/03/15 22:31:12 cegger Exp $       */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ucmpdi2.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: ucmpdi2.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Return 0, 1, or 2 as a <, =, > b respectively.
+ * Neither a nor b are considered signed.
+ */
+int
+__ucmpdi2(u_quad_t a, u_quad_t b)
+{
+       union uu aa, bb;
+
+       aa.uq = a;
+       bb.uq = b;
+       return (aa.ul[H] < bb.ul[H] ? 0 : aa.ul[H] > bb.ul[H] ? 2 :
+           aa.ul[L] < bb.ul[L] ? 0 : aa.ul[L] > bb.ul[L] ? 2 : 1);
+}
diff --git a/common/lib/libc/quad/udivdi3.c b/common/lib/libc/quad/udivdi3.c
new file mode 100644 (file)
index 0000000..72a95c7
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: udivdi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $       */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)udivdi3.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: udivdi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Divide two unsigned quads.
+ */
+u_quad_t
+__udivdi3(u_quad_t a, u_quad_t b)
+{
+
+       return (__qdivrem(a, b, (u_quad_t *)0));
+}
diff --git a/common/lib/libc/quad/umoddi3.c b/common/lib/libc/quad/umoddi3.c
new file mode 100644 (file)
index 0000000..2fef61e
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: umoddi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $       */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)umoddi3.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: umoddi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Return remainder after dividing two unsigned quads.
+ */
+u_quad_t
+__umoddi3(u_quad_t a, u_quad_t b)
+{
+       u_quad_t r;
+
+       (void)__qdivrem(a, b, &r);
+       return (r);
+}
diff --git a/common/lib/libc/quad/xordi3.c b/common/lib/libc/quad/xordi3.c
new file mode 100644 (file)
index 0000000..1a1fa4f
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: xordi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)xordi3.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: xordi3.c,v 1.2 2009/03/15 22:31:12 cegger Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Return a ^ b, in quad.
+ */
+quad_t
+__xordi3(quad_t a, quad_t b)
+{
+       union uu aa, bb;
+
+       aa.q = a;
+       bb.q = b;
+       aa.ul[0] ^= bb.ul[0];
+       aa.ul[1] ^= bb.ul[1];
+       return (aa.q);
+}
diff --git a/common/lib/libc/stdlib/_strtol.h b/common/lib/libc/stdlib/_strtol.h
new file mode 100644 (file)
index 0000000..8f7ec49
--- /dev/null
@@ -0,0 +1,169 @@
+/* $NetBSD: _strtol.h,v 1.2 2009/05/20 22:03:29 christos Exp $ */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ * Original version ID:
+ * NetBSD: src/lib/libc/locale/_wcstol.h,v 1.2 2003/08/07 16:43:03 agc Exp
+ */
+
+/*
+ * function template for strtol, strtoll and strtoimax.
+ *
+ * parameters:
+ *     _FUNCNAME : function name
+ *      __INT     : return type
+ *      __INT_MIN : lower limit of the return type
+ *      __INT_MAX : upper limit of the return type
+ */
+
+__INT
+_FUNCNAME(const char *nptr, char **endptr, int base)
+{
+       const char *s;
+       __INT acc, cutoff;
+       unsigned char c;
+       int i, neg, any, cutlim;
+
+       _DIAGASSERT(nptr != NULL);
+       /* endptr may be NULL */
+
+       /* check base value */
+       if (base && (base < 2 || base > 36)) {
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+               errno = EINVAL;
+               if (endptr != NULL)
+                       /* LINTED interface specification */
+                       *endptr = __UNCONST(nptr);
+               return 0;
+#else
+               panic("%s: invalid base %d", __func__, base);
+#endif
+       }
+
+       /*
+        * Skip white space and pick up leading +/- sign if any.
+        * If base is 0, allow 0x for hex and 0 for octal, else
+        * assume decimal; if base is already 16, allow 0x.
+        */
+       s = nptr;
+       do {
+               c = *s++;
+       } while (isspace(c));
+       if (c == '-') {
+               neg = 1;
+               c = *s++;
+       } else {
+               neg = 0;
+               if (c == '+')
+                       c = *s++;
+       }
+       if ((base == 0 || base == 16) &&
+           c == '0' && (*s == 'x' || *s == 'X')) {
+               c = s[1];
+               s += 2;
+               base = 16;
+       }
+       if (base == 0)
+               base = (c == '0' ? 8 : 10);
+
+       /*
+        * Compute the cutoff value between legal numbers and illegal
+        * numbers.  That is the largest legal value, divided by the
+        * base.  An input number that is greater than this value, if
+        * followed by a legal input character, is too big.  One that
+        * is equal to this value may be valid or not; the limit
+        * between valid and invalid numbers is then based on the last
+        * digit.  For instance, if the range for longs is
+        * [-2147483648..2147483647] and the input base is 10,
+        * cutoff will be set to 214748364 and cutlim to either
+        * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
+        * a value > 214748364, or equal but the next digit is > 7 (or 8),
+        * the number is too big, and we will return a range error.
+        *
+        * Set any if any `digits' consumed; make it negative to indicate
+        * overflow.
+        */
+       cutoff = (neg ? __INT_MIN : __INT_MAX);
+       cutlim = (int)(cutoff % base);
+       cutoff /= base;
+       if (neg) {
+               if (cutlim > 0) {
+                       cutlim -= base;
+                       cutoff += 1;
+               }
+               cutlim = -cutlim;
+       }
+       for (acc = 0, any = 0;; c = *s++) {
+               if (isdigit(c))
+                       i = c - '0';
+               else if (isalpha(c))
+                       i = c - (isupper(c) ? 'A' - 10 : 'a' - 10);
+               else
+                       break;
+               if (i >= base)
+                       break;
+               if (any < 0)
+                       continue;
+               if (neg) {
+                       if (acc < cutoff || (acc == cutoff && i > cutlim)) {
+                               acc = __INT_MIN;
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+                               any = -1;
+                               errno = ERANGE;
+#else
+                               any = 0;
+                               break;
+#endif
+                       } else {
+                               any = 1;
+                               acc *= base;
+                               acc -= i;
+                       }
+               } else {
+                       if (acc > cutoff || (acc == cutoff && i > cutlim)) {
+                               acc = __INT_MAX;
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+                               any = -1;
+                               errno = ERANGE;
+#else
+                               any = 0;
+                               break;
+#endif
+                       } else {
+                               any = 1;
+                               acc *= base;
+                               acc += i;
+                       }
+               }
+       }
+       if (endptr != NULL)
+               /* LINTED interface specification */
+               *endptr = __UNCONST(any ? s - 1 : nptr);
+       return(acc);
+}
diff --git a/common/lib/libc/stdlib/_strtoul.h b/common/lib/libc/stdlib/_strtoul.h
new file mode 100644 (file)
index 0000000..a9519f9
--- /dev/null
@@ -0,0 +1,128 @@
+/* $NetBSD: _strtoul.h,v 1.1 2008/08/20 12:42:26 joerg Exp $ */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ * Original version ID:
+ * NetBSD: src/lib/libc/locale/_wcstoul.h,v 1.2 2003/08/07 16:43:03 agc Exp
+ */
+
+/*
+ * function template for strtoul, strtoull and strtoumax.
+ *
+ * parameters:
+ *     _FUNCNAME  : function name
+ *      __UINT     : return type
+ *      __UINT_MAX : upper limit of the return type
+ */
+
+__UINT
+_FUNCNAME(const char *nptr, char **endptr, int base)
+{
+       const char *s;
+       __UINT acc, cutoff;
+       unsigned char c;
+       int i, neg, any, cutlim;
+
+       _DIAGASSERT(nptr != NULL);
+       /* endptr may be NULL */
+
+       /* check base value */
+       if (base && (base < 2 || base > 36)) {
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+               errno = EINVAL;
+               return(0);
+#else
+               panic("%s: invalid base %d", __func__, base);
+#endif
+       }
+
+       /*
+        * Skip white space and pick up leading +/- sign if any.
+        * If base is 0, allow 0x for hex and 0 for octal, else
+        * assume decimal; if base is already 16, allow 0x.
+        */
+       s = nptr;
+       do {
+               c = *s++;
+       } while (isspace(c));
+       if (c == '-') {
+               neg = 1;
+               c = *s++;
+       } else {
+               neg = 0;
+               if (c == '+')
+                       c = *s++;
+       }
+       if ((base == 0 || base == 16) &&
+           c == '0' && (*s == 'x' || *s == 'X')) {
+               c = s[1];
+               s += 2;
+               base = 16;
+       }
+       if (base == 0)
+               base = (c == '0' ? 8 : 10);
+
+       /*
+        * See strtol for comments as to the logic used.
+        */
+       cutoff = __UINT_MAX / (__UINT)base;
+       cutlim = (int)(__UINT_MAX % (__UINT)base);
+       for (acc = 0, any = 0;; c = *s++) {
+               if (isdigit(c))
+                       i = c - '0';
+               else if (isalpha(c))
+                       i = c - (isupper(c) ? 'A' - 10 : 'a' - 10);
+               else
+                       break;
+               if (i >= base)
+                       break;
+               if (any < 0)
+                       continue;
+               if (acc > cutoff || (acc == cutoff && i > cutlim)) {
+                       acc = __UINT_MAX;
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+                       any = -1;
+                       errno = ERANGE;
+#else
+                       any = 0;
+                       break;
+#endif
+               } else {
+                       any = 1;
+                       acc *= (__UINT)base;
+                       acc += i;
+               }
+       }
+       if (neg && any > 0)
+               acc = -acc;
+       if (endptr != NULL)
+               /* LINTED interface specification */
+               *endptr = __UNCONST(any ? s - 1 : nptr);
+       return(acc);
+}
diff --git a/common/lib/libc/stdlib/heapsort.c b/common/lib/libc/stdlib/heapsort.c
new file mode 100644 (file)
index 0000000..d0c74c5
--- /dev/null
@@ -0,0 +1,229 @@
+/*     $NetBSD: heapsort.c,v 1.3 2008/11/17 10:21:30 jnemeth Exp $     */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ronnie Kon at Mindcraft Inc., Kevin Lew and Elmer Yglesias.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+/*
+ * XXX Undefine the renames of these functions so that we don't
+ * XXX rename the versions found in the host's headers by mistake!
+ */
+#undef heapsort
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "from: @(#)heapsort.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: heapsort.c,v 1.3 2008/11/17 10:21:30 jnemeth Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+#include <sys/types.h>
+
+#include <lib/libkern/libkern.h>
+#else  /* _KERNEL || _STANDALONE */
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+
+#if HAVE_NBTOOL_CONFIG_H
+/* XXX Now, re-apply the renaming that we undid above. */
+#define heapsort       __nbcompat_heapsort
+#endif
+
+#ifdef __weak_alias
+__weak_alias(heapsort,_heapsort)
+#endif
+#endif /* _KERNEL || _STANDALONE */
+
+/*
+ * Swap two areas of size number of bytes.  Although qsort(3) permits random
+ * blocks of memory to be sorted, sorting pointers is almost certainly the
+ * common case (and, were it not, could easily be made so).  Regardless, it
+ * isn't worth optimizing; the SWAP's get sped up by the cache, and pointer
+ * arithmetic gets lost in the time required for comparison function calls.
+ */
+#define        SWAP(a, b, count, size, tmp) { \
+       count = size; \
+       do { \
+               tmp = *a; \
+               *a++ = *b; \
+               *b++ = tmp; \
+       } while (--count); \
+}
+
+/* Copy one block of size size to another. */
+#define COPY(a, b, count, size, tmp1, tmp2) { \
+       count = size; \
+       tmp1 = a; \
+       tmp2 = b; \
+       do { \
+               *tmp1++ = *tmp2++; \
+       } while (--count); \
+}
+
+/*
+ * Build the list into a heap, where a heap is defined such that for
+ * the records K1 ... KN, Kj/2 >= Kj for 1 <= j/2 <= j <= N.
+ *
+ * There are two cases.  If j == nmemb, select largest of Ki and Kj.  If
+ * j < nmemb, select largest of Ki, Kj and Kj+1.
+ */
+#define CREATE(initval, nmemb, par_i, child_i, par, child, size, count, tmp) { \
+       for (par_i = initval; (child_i = par_i * 2) <= nmemb; \
+           par_i = child_i) { \
+               child = base + child_i * size; \
+               if (child_i < nmemb && compar(child, child + size) < 0) { \
+                       child += size; \
+                       ++child_i; \
+               } \
+               par = base + par_i * size; \
+               if (compar(child, par) <= 0) \
+                       break; \
+               SWAP(par, child, count, size, tmp); \
+       } \
+}
+
+/*
+ * Select the top of the heap and 'heapify'.  Since by far the most expensive
+ * action is the call to the compar function, a considerable optimization
+ * in the average case can be achieved due to the fact that k, the displaced
+ * element, is usually quite small, so it would be preferable to first
+ * heapify, always maintaining the invariant that the larger child is copied
+ * over its parent's record.
+ *
+ * Then, starting from the *bottom* of the heap, finding k's correct place,
+ * again maintaining the invariant.  As a result of the invariant no element
+ * is 'lost' when k is assigned its correct place in the heap.
+ *
+ * The time savings from this optimization are on the order of 15-20% for the
+ * average case. See Knuth, Vol. 3, page 158, problem 18.
+ *
+ * XXX Don't break the #define SELECT line, below.  Reiser cpp gets upset.
+ */
+#define SELECT(par_i, child_i, nmemb, par, child, size, k, count, tmp1, tmp2) { \
+       for (par_i = 1; (child_i = par_i * 2) <= nmemb; par_i = child_i) { \
+               child = base + child_i * size; \
+               if (child_i < nmemb && compar(child, child + size) < 0) { \
+                       child += size; \
+                       ++child_i; \
+               } \
+               par = base + par_i * size; \
+               COPY(par, child, count, size, tmp1, tmp2); \
+       } \
+       for (;;) { \
+               child_i = par_i; \
+               par_i = child_i / 2; \
+               child = base + child_i * size; \
+               par = base + par_i * size; \
+               if (child_i == 1 || compar(k, par) < 0) { \
+                       COPY(child, k, count, size, tmp1, tmp2); \
+                       break; \
+               } \
+               COPY(child, par, count, size, tmp1, tmp2); \
+       } \
+}
+
+/*
+ * Heapsort -- Knuth, Vol. 3, page 145.  Runs in O (N lg N), both average
+ * and worst.  While heapsort is faster than the worst case of quicksort,
+ * the BSD quicksort does median selection so that the chance of finding
+ * a data set that will trigger the worst case is nonexistent.  Heapsort's
+ * only advantage over quicksort is that it requires little additional memory.
+ */
+#if defined(_KERNEL) || defined(_STANDALONE)
+int
+kheapsort(void *vbase, size_t nmemb, size_t size,
+    int (*compar)(const void *, const void *), void *k)
+#else
+int
+heapsort(void *vbase, size_t nmemb, size_t size,
+    int (*compar)(const void *, const void *))
+#endif
+{
+       size_t cnt, i, j, l;
+       char tmp, *tmp1, *tmp2;
+       char *base, *p, *t;
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+       char *k;
+#endif
+
+       _DIAGASSERT(vbase != NULL);
+       _DIAGASSERT(compar != NULL);
+
+       if (nmemb <= 1)
+               return (0);
+
+       if (!size) {
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+               errno = EINVAL;
+#endif
+               return (-1);
+       }
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+       if ((k = malloc(size)) == NULL)
+               return (-1);
+#endif
+
+       /*
+        * Items are numbered from 1 to nmemb, so offset from size bytes
+        * below the starting address.
+        */
+       base = (char *)vbase - size;
+
+       for (l = nmemb / 2 + 1; --l;)
+               CREATE(l, nmemb, i, j, t, p, size, cnt, tmp);
+
+       /*
+        * For each element of the heap, save the largest element into its
+        * final slot, save the displaced element (k), then recreate the
+        * heap.
+        */
+       while (nmemb > 1) {
+               COPY(k, base + nmemb * size, cnt, size, tmp1, tmp2);
+               COPY(base + nmemb * size, base + size, cnt, size, tmp1, tmp2);
+               --nmemb;
+               SELECT(i, j, nmemb, t, p, size, k, cnt, tmp1, tmp2);
+       }
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+       free(k);
+#endif
+       return (0);
+}
diff --git a/common/lib/libc/stdlib/random.c b/common/lib/libc/stdlib/random.c
new file mode 100644 (file)
index 0000000..85a50da
--- /dev/null
@@ -0,0 +1,530 @@
+/*     $NetBSD: random.c,v 1.3 2005/12/21 14:23:58 christos Exp $      */
+
+/*
+ * 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.
+ * 3. 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(_KERNEL) && !defined(_STANDALONE)
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)random.c   8.2 (Berkeley) 5/19/95";
+#else
+__RCSID("$NetBSD: random.c,v 1.3 2005/12/21 14:23:58 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include "reentrant.h"
+
+#ifdef __weak_alias
+__weak_alias(initstate,_initstate)
+__weak_alias(random,_random)
+__weak_alias(setstate,_setstate)
+__weak_alias(srandom,_srandom)
+#endif
+
+
+#ifdef _REENTRANT
+static mutex_t random_mutex = MUTEX_INITIALIZER;
+#endif
+#else
+#include <lib/libkern/libkern.h>
+#define mutex_lock(a)  (void)0
+#define mutex_unlock(a) (void)0
+#endif
+
+#ifndef SMALL_RANDOM
+static void srandom_unlocked(unsigned int);
+static long random_unlocked(void);
+
+#define USE_BETTER_RANDOM
+
+/*
+ * 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 ints; 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 register 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.
+ *
+ * Modified 07 January 2002 by Jason R. Thorpe.
+ * The following changes have been made:
+ * All the references to "long" have been changed back to "int".  This
+ * fixes memory corruption problems on LP64 platforms.
+ */
+
+/*
+ * 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 */
+
+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.
+ */
+
+/* LINTED */
+static int randtbl[DEG_3 + 1] = {
+       TYPE_3,
+#ifdef USE_BETTER_RANDOM
+       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,
+#else
+       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,
+#endif /* USE_BETTER_RANDOM */
+};
+
+/*
+ * 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 int *fptr = &randtbl[SEP_3 + 1];
+static int *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 int *state = &randtbl[1];
+static int rand_type = TYPE_3;
+static int rand_deg = DEG_3;
+static int rand_sep = SEP_3;
+static int *end_ptr = &randtbl[DEG_3 + 1];
+
+/*
+ * 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.
+ */
+static void
+srandom_unlocked(unsigned int x)
+{
+       int i;
+
+       if (rand_type == TYPE_0)
+               state[0] = x;
+       else {
+               state[0] = x;
+               for (i = 1; i < rand_deg; i++) {
+#ifdef USE_BETTER_RANDOM
+                       int x1, hi, lo, t;
+
+                       /*
+                        * Compute x[n + 1] = (7^5 * x[n]) mod (2^31 - 1).
+                        * 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.
+                        */
+                       x1 = state[i - 1];
+                       hi = x1 / 127773;
+                       lo = x1 % 127773;
+                       t = 16807 * lo - 2836 * hi;
+                       if (t <= 0)
+                               t += 0x7fffffff;
+                       state[i] = t;
+#else
+                       state[i] = 1103515245 * state[i - 1] + 12345;
+#endif /* USE_BETTER_RANDOM */
+               }
+               fptr = &state[rand_sep];
+               rptr = &state[0];
+               for (i = 0; i < 10 * rand_deg; i++)
+                       (void)random_unlocked();
+       }
+}
+
+void
+srandom(unsigned long x)
+{
+
+       mutex_lock(&random_mutex);
+       srandom_unlocked((unsigned int) x);
+       mutex_unlock(&random_mutex);
+}
+
+/*
+ * 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(
+       unsigned long seed,             /* seed for R.N.G. */
+       char *arg_state,                /* pointer to state array */
+       size_t n)                       /* # bytes of state info */
+{
+       void *ostate = (void *)(&state[-1]);
+       int *int_arg_state;
+
+       _DIAGASSERT(arg_state != NULL);
+
+       int_arg_state = (int *)(void *)arg_state;
+
+       mutex_lock(&random_mutex);
+       if (rand_type == TYPE_0)
+               state[-1] = rand_type;
+       else
+               state[-1] = MAX_TYPES * (int)(rptr - state) + rand_type;
+       if (n < BREAK_0) {
+               mutex_unlock(&random_mutex);
+               return (NULL);
+       } else 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 *) (int_arg_state + 1); /* first location */
+       end_ptr = &state[rand_deg];     /* must set end_ptr before srandom */
+       srandom_unlocked((unsigned int) seed);
+       if (rand_type == TYPE_0)
+               int_arg_state[0] = rand_type;
+       else
+               int_arg_state[0] = MAX_TYPES * (int)(rptr - state) + rand_type;
+       mutex_unlock(&random_mutex);
+       return((char *)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 a long
+ * word boundary; otherwise a bus error will occur. Even so, lint will
+ * complain about mis-alignment, but you should disregard these messages.
+ */
+char *
+setstate(char *arg_state)              /* pointer to state array */
+{
+       int *new_state;
+       int type;
+       int rear;
+       void *ostate = (void *)(&state[-1]);
+
+       _DIAGASSERT(arg_state != NULL);
+
+       new_state = (int *)(void *)arg_state;
+       type = (int)(new_state[0] % MAX_TYPES);
+       rear = (int)(new_state[0] / MAX_TYPES);
+
+       mutex_lock(&random_mutex);
+       if (rand_type == TYPE_0)
+               state[-1] = rand_type;
+       else
+               state[-1] = MAX_TYPES * (int)(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:
+               mutex_unlock(&random_mutex);
+               return (NULL);
+       }
+       state = (int *) (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 */
+       mutex_unlock(&random_mutex);
+       return((char *)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.
+ */
+static long
+random_unlocked(void)
+{
+       int i;
+       int *f, *r;
+
+       if (rand_type == TYPE_0) {
+               i = state[0];
+               state[0] = i = (i * 1103515245 + 12345) & 0x7fffffff;
+       } else {
+               /*
+                * Use local variables rather than static variables for speed.
+                */
+               f = fptr; r = rptr;
+               *f += *r;
+               /* chucking least random bit */
+               i = ((unsigned int)*f >> 1) & 0x7fffffff;
+               if (++f >= end_ptr) {
+                       f = state;
+                       ++r;
+               }
+               else if (++r >= end_ptr) {
+                       r = state;
+               }
+
+               fptr = f; rptr = r;
+       }
+       return(i);
+}
+
+long
+random(void)
+{
+       long r;
+
+       mutex_lock(&random_mutex);
+       r = random_unlocked();
+       mutex_unlock(&random_mutex);
+       return (r);
+}
+#else
+long
+random(void)
+{
+       static u_long randseed = 1;
+       long x, hi, lo, t;
+       /*
+        * Compute x[n + 1] = (7^5 * x[n]) mod (2^31 - 1).
+        * 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.
+        */
+       x = randseed;
+       hi = x / 127773;
+       lo = x % 127773;
+       t = 16807 * lo - 2836 * hi;
+       if (t <= 0)
+               t += 0x7fffffff;
+       randseed = t;
+       return (t);
+}
+#endif /* SMALL_RANDOM */
diff --git a/common/lib/libc/stdlib/strtoll.c b/common/lib/libc/stdlib/strtoll.c
new file mode 100644 (file)
index 0000000..184f92c
--- /dev/null
@@ -0,0 +1,66 @@
+/* $NetBSD: strtoll.c,v 1.6 2008/08/22 03:00:02 matt Exp $ */
+
+/*-
+ * Copyright (c) 2005 The DragonFly Project.  All rights reserved.
+ * Copyright (c) 2003 Citrus Project,
+ * 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.
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: strtoll.c,v 1.6 2008/08/22 03:00:02 matt Exp $");
+
+#ifdef _LIBC
+#include "namespace.h"
+#endif
+
+#if defined(_KERNEL)
+#include <sys/param.h>
+#include <lib/libkern/libkern.h>
+#elif defined(_STANDALONE)
+#include <sys/param.h>
+#include <lib/libkern/libkern.h>
+#include <lib/libsa/stand.h>
+#else
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdint.h>
+#include <stdlib.h>
+#endif
+
+#define        _FUNCNAME       strtoll
+#define        __INT           long long
+#define        __INT_MIN       LLONG_MIN
+#define        __INT_MAX       LLONG_MAX
+
+#include "_strtol.h"
+
+#ifdef _LIBC
+__weak_alias(strtoll, _strtoll)
+#endif
diff --git a/common/lib/libc/stdlib/strtoul.c b/common/lib/libc/stdlib/strtoul.c
new file mode 100644 (file)
index 0000000..764b091
--- /dev/null
@@ -0,0 +1,53 @@
+/* $NetBSD: strtoul.c,v 1.3 2008/08/20 19:58:34 oster Exp $ */
+
+/*-
+ * Copyright (c) 2005 The DragonFly Project.  All rights reserved.
+ * Copyright (c) 2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: strtoul.c,v 1.3 2008/08/20 19:58:34 oster Exp $");
+
+#if defined(_KERNEL)
+#include <sys/param.h>
+#include <lib/libkern/libkern.h>
+#elif defined(_STANDALONE)
+#include <sys/param.h>
+#include <lib/libkern/libkern.h>
+#include <lib/libsa/stand.h>
+#else
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdint.h>
+#include <stdlib.h>
+#endif
+
+#define        _FUNCNAME       strtoul
+#define        __UINT          unsigned long int
+#define        __UINT_MAX      ULONG_MAX
+
+#include "_strtoul.h"
diff --git a/common/lib/libc/stdlib/strtoull.c b/common/lib/libc/stdlib/strtoull.c
new file mode 100644 (file)
index 0000000..72efd4a
--- /dev/null
@@ -0,0 +1,65 @@
+/* $NetBSD: strtoull.c,v 1.5 2008/09/10 18:08:58 joerg Exp $ */
+
+/*-
+ * Copyright (c) 2005 The DragonFly Project.  All rights reserved.
+ * Copyright (c) 2003 Citrus Project,
+ * 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.
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: strtoull.c,v 1.5 2008/09/10 18:08:58 joerg Exp $");
+
+#ifdef _LIBC
+#include "namespace.h"
+#endif
+
+#if defined(_KERNEL)
+#include <sys/param.h>
+#include <lib/libkern/libkern.h>
+#elif defined(_STANDALONE)
+#include <sys/param.h>
+#include <lib/libkern/libkern.h>
+#include <lib/libsa/stand.h>
+#else
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdint.h>
+#include <stdlib.h>
+#endif
+
+#define        _FUNCNAME       strtoull
+#define        __UINT          unsigned long long int
+#define        __UINT_MAX      ULLONG_MAX
+
+#include "_strtoul.h"
+
+#ifdef _LIBC
+__weak_alias(strtoull, _strtoull)
+#endif
diff --git a/common/lib/libc/stdlib/strtoumax.c b/common/lib/libc/stdlib/strtoumax.c
new file mode 100644 (file)
index 0000000..d8356e0
--- /dev/null
@@ -0,0 +1,66 @@
+/* $NetBSD: strtoumax.c,v 1.5 2008/09/10 18:08:58 joerg Exp $ */
+
+/*-
+ * Copyright (c) 2005 The DragonFly Project.  All rights reserved.
+ * Copyright (c) 2003 Citrus Project,
+ * 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.
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: strtoumax.c,v 1.5 2008/09/10 18:08:58 joerg Exp $");
+
+#ifdef _LIBC
+#include "namespace.h"
+#endif
+
+#if defined(_KERNEL)
+#include <sys/param.h>
+#include <lib/libkern/libkern.h>
+#elif defined(_STANDALONE)
+#include <sys/param.h>
+#include <lib/libkern/libkern.h>
+#include <lib/libsa/stand.h>
+#else
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <stdint.h>
+#include <stdlib.h>
+#endif
+
+#define        _FUNCNAME       strtoumax
+#define        __UINT          uintmax_t
+#define        __UINT_MAX      UINTMAX_MAX
+
+#include "_strtoul.h"
+
+#ifdef _LIBC
+__weak_alias(strtoumax, _strtoumax)
+#endif
diff --git a/common/lib/libc/string/bcmp.c b/common/lib/libc/string/bcmp.c
new file mode 100644 (file)
index 0000000..724658d
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: bcmp.c,v 1.6 2009/04/25 12:20:48 skrll Exp $   */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)bcmp.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: bcmp.c,v 1.6 2009/04/25 12:20:48 skrll Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+
+#if defined(_KERNEL) || defined(_STANDALONE)
+#include <lib/libkern/libkern.h>
+#if defined(_STANDALONE)
+#include <lib/libsa/stand.h>
+#endif
+#else
+#include <assert.h>
+#include <string.h>
+#endif
+
+/*
+ * bcmp -- vax cmpc3 instruction
+ */
+int
+bcmp(const void *b1, const void *b2, size_t length)
+{
+       const char *p1 = b1, *p2 = b2;
+
+       _DIAGASSERT(b1 != 0);
+       _DIAGASSERT(b2 != 0);
+
+       if (length == 0)
+               return(0);
+       do
+               if (*p1++ != *p2++)
+                       break;
+       while (--length);
+       return(length);
+}
diff --git a/common/lib/libc/string/bcopy.c b/common/lib/libc/string/bcopy.c
new file mode 100644 (file)
index 0000000..6d379ff
--- /dev/null
@@ -0,0 +1,210 @@
+/*     $NetBSD: bcopy.c,v 1.9 2009/03/18 12:25:06 tsutsui Exp $        */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)bcopy.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: bcopy.c,v 1.9 2009/03/18 12:25:06 tsutsui Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#if !defined(MEMCOPY) && defined(_STANDALONE)
+#include <lib/libsa/stand.h>
+#endif
+#endif
+
+#ifdef _FORTIFY_SOURCE
+#undef bcopy
+#undef memcpy
+#undef memmove
+#endif
+
+#ifndef __OPTIMIZE_SIZE__
+/*
+ * sizeof(word) MUST BE A POWER OF TWO
+ * SO THAT wmask BELOW IS ALL ONES
+ */
+typedef        long word;              /* "word" used for optimal copy speed */
+
+#define        wsize   sizeof(word)
+#define        wmask   (wsize - 1)
+
+/*
+ * Copy a block of memory, handling overlap.
+ * This is the routine that actually implements
+ * (the portable versions of) bcopy, memcpy, and memmove.
+ */
+#if defined(MEMCOPY)
+void *
+memcpy(void *dst0, const void *src0, size_t length)
+#elif defined(MEMMOVE)
+void *
+memmove(void *dst0, const void *src0, size_t length)
+#else
+void
+bcopy(const void *src0, void *dst0, size_t length)
+#endif
+{
+       char *dst = dst0;
+       const char *src = src0;
+       size_t t;
+       unsigned long u;
+
+#if !defined(_KERNEL)
+       _DIAGASSERT(dst0 != 0);
+       _DIAGASSERT(src0 != 0);
+#endif
+
+       if (length == 0 || dst == src)          /* nothing to do */
+               goto done;
+
+       /*
+        * Macros: loop-t-times; and loop-t-times, t>0
+        */
+#define        TLOOP(s) if (t) TLOOP1(s)
+#define        TLOOP1(s) do { s; } while (--t)
+
+       if ((unsigned long)dst < (unsigned long)src) {
+               /*
+                * Copy forward.
+                */
+               u = (unsigned long)src; /* only need low bits */
+               if ((u | (unsigned long)dst) & wmask) {
+                       /*
+                        * Try to align operands.  This cannot be done
+                        * unless the low bits match.
+                        */
+                       if ((u ^ (unsigned long)dst) & wmask || length < wsize)
+                               t = length;
+                       else
+                               t = wsize - (size_t)(u & wmask);
+                       length -= t;
+                       TLOOP1(*dst++ = *src++);
+               }
+               /*
+                * Copy whole words, then mop up any trailing bytes.
+                */
+               t = length / wsize;
+               TLOOP(*(word *)(void *)dst = *(const word *)(const void *)src; src += wsize; dst += wsize);
+               t = length & wmask;
+               TLOOP(*dst++ = *src++);
+       } else {
+               /*
+                * Copy backwards.  Otherwise essentially the same.
+                * Alignment works as before, except that it takes
+                * (t&wmask) bytes to align, not wsize-(t&wmask).
+                */
+               src += length;
+               dst += length;
+               _DIAGASSERT((unsigned long)dst >= (unsigned long)dst0);
+               _DIAGASSERT((unsigned long)src >= (unsigned long)src0);
+               u = (unsigned long)src;
+               if ((u | (unsigned long)dst) & wmask) {
+                       if ((u ^ (unsigned long)dst) & wmask || length <= wsize)
+                               t = length;
+                       else
+                               t = (size_t)(u & wmask);
+                       length -= t;
+                       TLOOP1(*--dst = *--src);
+               }
+               t = length / wsize;
+               TLOOP(src -= wsize; dst -= wsize; *(word *)(void *)dst = *(const word *)(const void *)src);
+               t = length & wmask;
+               TLOOP(*--dst = *--src);
+       }
+done:
+#if defined(MEMCOPY) || defined(MEMMOVE)
+       return (dst0);
+#else
+       return;
+#endif
+}
+#else /* __OPTIMIZE_SIZE__ */
+#if defined(MEMCOPY)
+/*
+ * This is designed to be small, not fast.
+ */
+void *
+memcpy(void *s1, const void *s2, size_t n)
+{
+       const char *f = s2;
+       char *t = s1;
+
+       while (n-- > 0)
+               *t++ = *f++;
+       return s1;
+}
+#elif defined(MEMMOVE)
+/*
+ * This is designed to be small, not fast.
+ */
+void *
+memmove(void *s1, const void *s2, size_t n)
+{
+       const char *f = s2;
+       char *t = s1;
+
+       if (f < t) {
+               f += n;
+               t += n;
+               while (n-- > 0)
+                       *--t = *--f;
+       } else {
+               while (n-- > 0)
+                       *t++ = *f++;
+       }
+       return s1;
+}
+#else
+/*
+ * This is designed to be small, not fast.
+ */
+void
+bcopy(const void *s2, void *s1, size_t n)
+{
+       const char *f = s2;
+       char *t = s1;
+
+       while (n-- > 0)
+               *t++ = *f++;
+}
+#endif
+#endif /* __OPTIMIZE_SIZE__ */
diff --git a/common/lib/libc/string/bzero.c b/common/lib/libc/string/bzero.c
new file mode 100644 (file)
index 0000000..8db58bb
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: bzero.c,v 1.1 2005/12/20 19:28:52 christos Exp $       */
+
+#define BZERO
+#include "memset.c"
diff --git a/common/lib/libc/string/bzero2.c b/common/lib/libc/string/bzero2.c
new file mode 100644 (file)
index 0000000..0522034
--- /dev/null
@@ -0,0 +1,36 @@
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+#define        BZERO
+
+#include "memset2.c"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: bzero2.c,v 1.2 2009/12/14 00:39:01 matt Exp $");
+#endif /* LIBC_SCCS and not lint */
diff --git a/common/lib/libc/string/ffs.c b/common/lib/libc/string/ffs.c
new file mode 100644 (file)
index 0000000..0217f5e
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: ffs.c,v 1.3 2007/11/02 21:05:06 christos Exp $ */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ffs.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: ffs.c,v 1.3 2007/11/02 21:05:06 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/bitops.h>
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#endif
+
+/* #undef ffs() - might be defined as macro to __builtin_ffs() */
+#undef ffs
+
+/*
+ * ffs -- vax ffs instruction
+ */
+int
+ffs(int mask)
+{
+       return ffs32((uint32_t)mask);
+}
diff --git a/common/lib/libc/string/memchr.c b/common/lib/libc/string/memchr.c
new file mode 100644 (file)
index 0000000..93d11cd
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: memchr.c,v 1.3 2008/01/08 21:57:06 martin Exp $        */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)memchr.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: memchr.c,v 1.3 2008/01/08 21:57:06 martin Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#endif
+
+void *
+memchr(const void *s, int c, size_t n)
+{
+       _DIAGASSERT(s != NULL);
+
+       if (n != 0) {
+               const unsigned char *p = s;
+               const unsigned char cmp = c;
+
+               do {
+                       if (*p++ == cmp)
+                               return __UNCONST(p - 1);
+               } while (--n != 0);
+       }
+       return NULL;
+}
diff --git a/common/lib/libc/string/memcmp.c b/common/lib/libc/string/memcmp.c
new file mode 100644 (file)
index 0000000..1288048
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: memcmp.c,v 1.2 2007/06/04 18:19:27 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)memcmp.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: memcmp.c,v 1.2 2007/06/04 18:19:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#endif 
+
+/*
+ * Compare memory regions.
+ */
+int
+memcmp(const void *s1, const void *s2, size_t n)
+{
+       _DIAGASSERT(s1 != 0);
+       _DIAGASSERT(s2 != 0);
+
+       if (n != 0) {
+               const unsigned char *p1 = s1, *p2 = s2;
+
+               do {
+                       if (*p1++ != *p2++)
+                               return (*--p1 - *--p2);
+               } while (--n != 0);
+       }
+       return (0);
+}
diff --git a/common/lib/libc/string/memcpy.c b/common/lib/libc/string/memcpy.c
new file mode 100644 (file)
index 0000000..38792bb
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: memcpy.c,v 1.1 2005/12/20 19:28:52 christos Exp $      */
+
+#define MEMCOPY
+#include "bcopy.c"
diff --git a/common/lib/libc/string/memmove.c b/common/lib/libc/string/memmove.c
new file mode 100644 (file)
index 0000000..a3af3b7
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: memmove.c,v 1.1 2005/12/20 19:28:52 christos Exp $     */
+
+#define MEMMOVE
+#include "bcopy.c"
diff --git a/common/lib/libc/string/memset.c b/common/lib/libc/string/memset.c
new file mode 100644 (file)
index 0000000..ed2ccb4
--- /dev/null
@@ -0,0 +1,167 @@
+/*     $NetBSD: memset.c,v 1.8 2009/03/18 12:25:06 tsutsui Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Hibler and Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)memset.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: memset.c,v 1.8 2009/03/18 12:25:06 tsutsui Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <limits.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#if defined(BZERO) && defined(_STANDALONE)
+#include <lib/libsa/stand.h>
+#endif
+#include <machine/limits.h>
+#endif 
+
+#define        wsize   sizeof(u_int)
+#define        wmask   (wsize - 1)
+
+#ifdef _FORTIFY_SOURCE
+#undef bzero
+#undef memset
+#endif
+
+#ifndef __OPTIMIZE_SIZE__
+#ifdef BZERO
+#define        RETURN  return
+#define        VAL     0
+#define        WIDEVAL 0
+
+void
+bzero(void *dst0, size_t length)
+#else
+#define        RETURN  return (dst0)
+#define        VAL     c0
+#define        WIDEVAL c
+
+void *
+memset(void *dst0, int c0, size_t length)
+#endif
+{
+       size_t t;
+#ifndef BZERO
+       u_int c;
+#endif
+       u_char *dst;
+
+       _DIAGASSERT(dst0 != 0);
+
+       dst = dst0;
+       /*
+        * If not enough words, just fill bytes.  A length >= 2 words
+        * guarantees that at least one of them is `complete' after
+        * any necessary alignment.  For instance:
+        *
+        *      |-----------|-----------|-----------|
+        *      |00|01|02|03|04|05|06|07|08|09|0A|00|
+        *                ^---------------------^
+        *               dst             dst+length-1
+        *
+        * but we use a minimum of 3 here since the overhead of the code
+        * to do word writes is substantial.
+        */ 
+       if (length < 3 * wsize) {
+               while (length != 0) {
+                       *dst++ = VAL;
+                       --length;
+               }
+               RETURN;
+       }
+
+#ifndef BZERO
+       if ((c = (u_char)c0) != 0) {    /* Fill the word. */
+               c = (c << 8) | c;       /* u_int is 16 bits. */
+#if UINT_MAX > 0xffff
+               c = (c << 16) | c;      /* u_int is 32 bits. */
+#endif
+#if UINT_MAX > 0xffffffff
+               c = (c << 32) | c;      /* u_int is 64 bits. */
+#endif
+       }
+#endif
+       /* Align destination by filling in bytes. */
+       if ((t = (size_t)((u_long)dst & wmask)) != 0) {
+               t = wsize - t;
+               length -= t;
+               do {
+                       *dst++ = VAL;
+               } while (--t != 0);
+       }
+
+       /* Fill words.  Length was >= 2*words so we know t >= 1 here. */
+       t = length / wsize;
+       do {
+               *(u_int *)(void *)dst = WIDEVAL;
+               dst += wsize;
+       } while (--t != 0);
+
+       /* Mop up trailing bytes, if any. */
+       t = length & wmask;
+       if (t != 0)
+               do {
+                       *dst++ = VAL;
+               } while (--t != 0);
+       RETURN;
+}
+#else /* __OPTIMIZE_SIZE__ */
+#ifdef BZERO
+void
+bzero(void *dstv, size_t length)
+{
+       u_char *dst = dstv;
+       while (length-- > 0)
+               *dst++ = 0;
+}
+#else
+void *
+memset(void *dstv, int c, size_t length)
+{
+       u_char *dst = dstv;
+       while (length-- > 0)
+               *dst++ = c;
+       return dstv;
+}
+#endif /* BZERO */
+#endif /* __OPTIMIZE_SIZE__ */
diff --git a/common/lib/libc/string/memset2.c b/common/lib/libc/string/memset2.c
new file mode 100644 (file)
index 0000000..7009f48
--- /dev/null
@@ -0,0 +1,277 @@
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/types.h>
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <limits.h>
+#include <string.h>
+#include <inttypes.h>
+#else
+#include <lib/libkern/libkern.h>
+#include <machine/limits.h>
+#endif 
+
+#include <sys/endian.h>
+#include <machine/types.h>
+
+#ifdef TEST
+#include <assert.h>
+#define _DIAGASSERT(a)         assert(a)
+#endif
+
+#ifdef _FORTIFY_SOURCE
+#undef bzero
+#undef memset
+#endif
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: memset2.c,v 1.2 2009/12/14 00:39:01 matt Exp $");    
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Assume uregister_t is the widest non-synthetic unsigned type.
+ */
+typedef uregister_t memword_t;
+
+#ifdef BZERO
+static inline
+#define        memset memset0
+#endif
+
+#ifdef TEST
+static
+#define memset test_memset
+#endif
+
+#ifdef CTASSERT
+CTASSERT((~(memword_t)0U >> 1) != ~(memword_t)0U);
+#endif
+
+void *
+memset(void *addr, int c, size_t len)
+{
+       memword_t *dstp = addr;
+       memword_t *edstp;
+       memword_t fill;
+#ifndef __OPTIMIZE_SIZE__
+       memword_t keep_mask = 0;
+#endif
+       size_t fill_count;
+
+       _DIAGASSERT(addr != 0);
+
+       if (__predict_false(len == 0))
+               return addr;
+
+       /*
+        * Pad out the fill byte (v) across a memword_t.
+        * The conditional at the end prevents GCC from complaing about
+        * shift count >= width of type 
+        */
+       fill = c;
+       fill |= fill << 8;
+       fill |= fill << 16;
+       fill |= fill << (sizeof(c) < sizeof(fill) ? 32 : 0);
+
+       /*
+        * Get the number of unaligned bytes to fill in the first word.
+        */
+       fill_count = -(uintptr_t)addr & (sizeof(memword_t) - 1);
+
+       if (__predict_false(fill_count != 0)) {
+#ifndef __OPTIMIZE_SIZE__
+               /*
+                * We want to clear <fill_count> trailing bytes in the word.
+                * On big/little endian, these are the least/most significant,
+                * bits respectively.  So as we shift, the keep_mask will only
+                * have bits set for the bytes we won't be filling.
+                */
+#if BYTE_ORDER == BIG_ENDIAN
+               keep_mask = ~(memword_t)0U << (fill_count * 8);
+#endif
+#if BYTE_ORDER == LITTLE_ENDIAN
+               keep_mask = ~(memword_t)0U >> (fill_count * 8);
+#endif
+               /*
+                * Make sure dstp is aligned to a memword_t boundary.
+                */
+               dstp = (memword_t *)((uintptr_t)addr & -sizeof(memword_t));
+               if (len >= fill_count) {
+                       /*
+                        * If we can fill the rest of this word, then we mask
+                        * off the bytes we are filling and then fill in those
+                        * bytes with the new fill value.
+                        */
+                       *dstp = (*dstp & keep_mask) | (fill & ~keep_mask);
+                       len -= fill_count;
+                       if (__predict_false(len == 0))
+                               return addr;
+                       /*
+                        * Since we were able to fill the rest of this word,
+                        * we will advance to the next word and thus have no
+                        * bytes to preserve.
+                        *
+                        * If we don't have enough to fill the rest of this
+                        * word, we will fall through the following loop
+                        * (since there are no full words to fill).  Then we
+                        * use the keep_mask above to preserve the leading
+                        * bytes of word.
+                        */
+                       dstp++;
+                       keep_mask = 0;
+               } else {
+                       len += (uintptr_t)addr & (sizeof(memword_t) - 1);
+               }
+#else /* __OPTIMIZE_SIZE__ */
+               uint8_t *dp, *ep;
+               if (len < fill_count)
+                       fill_count = len;
+               for (dp = (uint8_t *)dstp, ep = dp + fill_count;
+                    dp != ep; dp++)
+                       *dp = fill;
+               if ((len -= fill_count) == 0)
+                       return addr;
+               dstp = (memword_t *)ep;
+#endif /* __OPTIMIZE_SIZE__ */
+       }
+
+       /*
+        * Simply fill memory one word at time (for as many full words we have
+        * to write).
+        */
+       for (edstp = dstp + len / sizeof(memword_t); dstp != edstp; dstp++)
+               *dstp = fill;
+
+       /*
+        * We didn't subtract out the full words we just filled since we know
+        * by the time we get here we will have less than a words worth to
+        * write.  So we can concern ourselves with only the subword len bits.
+        */
+       len &= sizeof(memword_t)-1;
+       if (len > 0) {
+#ifndef __OPTIMIZE_SIZE__
+               /*
+                * We want to clear <len> leading bytes in the word.
+                * On big/little endian, these are the most/least significant
+                * bits, respectively,  But as we want the mask of the bytes to
+                * keep, we have to complement the mask.  So after we shift,
+                * the keep_mask will only have bits set for the bytes we won't
+                * be filling.
+                *
+                * But the keep_mask could already have bytes to preserve
+                * if the amount to fill was less than the amount of traiing
+                * space in the first word.
+                */
+#if BYTE_ORDER == BIG_ENDIAN
+               keep_mask |= ~(memword_t)0U >> (len * 8);
+#endif
+#if BYTE_ORDER == LITTLE_ENDIAN
+               keep_mask |= ~(memword_t)0U << (len * 8);
+#endif
+               /*
+                * Now we mask off the bytes we are filling and then fill in
+                * those bytes with the new fill value.
+                */
+               *dstp = (*dstp & keep_mask) | (fill & ~keep_mask);
+#else /* __OPTIMIZE_SIZE__ */
+               uint8_t *dp, *ep;
+               for (dp = (uint8_t *)dstp, ep = dp + len;
+                    dp != ep; dp++)
+                       *dp = fill;
+#endif /* __OPTIMIZE_SIZE__ */
+       }
+
+       /*
+        * Return the initial addr
+        */
+       return addr;
+}
+
+#ifdef BZERO
+/*
+ * For bzero, simply inline memset and let the compiler optimize things away.
+ */
+void
+bzero(void *addr, size_t len)
+{
+       memset(addr, 0, len);
+}
+#endif
+
+#ifdef TEST
+#include <stdbool.h>
+#include <stdio.h>
+
+#undef memset
+
+static union {
+       uint8_t bytes[sizeof(memword_t) * 4];
+       memword_t words[4];
+} testmem;
+
+int
+main(int argc, char **argv)
+{
+       size_t start;
+       size_t len;
+       bool failed = false;
+
+       for (start = 1; start < sizeof(testmem) - 1; start++) {
+               for (len = 1; start + len < sizeof(testmem) - 1; len++) {
+                       bool ok = true;
+                       size_t i;
+                       uint8_t check_value;
+                       memset(testmem.bytes, 0xff, sizeof(testmem));
+                       test_memset(testmem.bytes + start, 0x00, len);
+                       for (i = 0; i < sizeof(testmem); i++) {
+                               if (i == 0 || i == start + len)
+                                       check_value = 0xff;
+                               else if (i == start)
+                                       check_value = 0x00;
+                               if (testmem.bytes[i] != check_value) {
+                                       if (ok)
+                                               printf("pass @ %zu .. %zu failed",
+                                                   start, start + len - 1);
+                                       ok = false;
+                                       printf(" [%zu]=0x%02x(!0x%02x)",
+                                           i, testmem.bytes[i], check_value);
+                               }
+                       }
+                       if (!ok) {
+                               printf("\n");
+                               failed = 1;
+                       }
+               }
+       }
+
+       return failed ? 1 : 0;
+}
+#endif /* TEST */
diff --git a/common/lib/libc/string/popcount32.c b/common/lib/libc/string/popcount32.c
new file mode 100644 (file)
index 0000000..bc5058d
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: popcount32.c,v 1.3 2009/07/21 19:56:55 drochner Exp $  */
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Joerg Sonnenberger.
+ *
+ * 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 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 HOLDERS 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 <sys/cdefs.h>
+__RCSID("$NetBSD: popcount32.c,v 1.3 2009/07/21 19:56:55 drochner Exp $");
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <limits.h>
+#include <strings.h>
+#else
+#include <lib/libkern/libkern.h>
+#include <machine/limits.h>
+#endif
+
+/*
+ * This a hybrid algorithm for bit counting between parallel counting and
+ * using multiplication.  The idea is to sum up the bits in each Byte, so
+ * that the final accumulation can be done with a single multiplication.
+ * If the platform has a slow multiplication instruction, it can be replaced
+ * by the commented out version below.
+ */
+
+unsigned int
+popcount32(uint32_t v)
+{
+       unsigned int c;
+
+       v = v - ((v >> 1) & 0x55555555U);
+       v = (v & 0x33333333U) + ((v >> 2) & 0x33333333U);
+       v = (v + (v >> 4)) & 0x0f0f0f0fU;
+       c = (v * 0x01010101U) >> 24;
+       /*
+        * v = (v >> 16) + v;
+        * v = (v >> 8) + v;
+        * c = v & 255;
+        */
+
+       return c;
+}
+
+#if UINT_MAX == 0xffffffffU
+__strong_alias(popcount, popcount32)
+#endif
+
+#if ULONG_MAX == 0xffffffffU
+__strong_alias(popcountl, popcount32)
+#endif
diff --git a/common/lib/libc/string/popcount64.c b/common/lib/libc/string/popcount64.c
new file mode 100644 (file)
index 0000000..51a1c19
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: popcount64.c,v 1.5 2009/08/05 15:04:15 joerg Exp $     */
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Joerg Sonnenberger.
+ *
+ * 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 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 HOLDERS 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 <sys/cdefs.h>
+__RCSID("$NetBSD: popcount64.c,v 1.5 2009/08/05 15:04:15 joerg Exp $");
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <limits.h>
+#include <strings.h>
+#else
+#include <lib/libkern/libkern.h>
+#include <machine/limits.h>
+#endif
+
+/*
+ * If uint64_t is larger than size_t, the follow assumes that
+ * splitting into 32bit halfes is faster.
+ *
+ * The native pocount64 version is based on the same ideas as popcount32(3),
+ * see popcount32.c for comments.
+ */
+
+#if SIZE_MAX < 0xffffffffffffffffULL
+unsigned int
+popcount64(uint64_t v)
+{
+       return popcount32((uint32_t)(v >> 32)) +
+           popcount32((uint32_t)(v & 0xffffffffULL));
+}
+#else
+unsigned int
+popcount64(uint64_t v)
+{
+       unsigned int c;
+
+       v = v - ((v >> 1) & 0x5555555555555555ULL);
+       v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
+       v = ((v + (v >> 4)) & 0x0f0f0f0f0f0f0f0fULL) * 0x0101010101010101ULL;
+       c = v >> 56;
+
+       return c;
+}
+#endif
+
+#if ULONG_MAX == 0xffffffffffffffffULL
+__strong_alias(popcountl, popcount64)
+#endif
+
+#if ULLONG_MAX == 0xffffffffffffffffULL
+__strong_alias(popcountll, popcount64)
+#endif
+
diff --git a/common/lib/libc/string/strcasecmp.c b/common/lib/libc/string/strcasecmp.c
new file mode 100644 (file)
index 0000000..ad4e78e
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: strcasecmp.c,v 1.2 2007/06/04 18:19:27 christos Exp $  */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strcasecmp.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strcasecmp.c,v 1.2 2007/06/04 18:19:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include "namespace.h"
+#include <assert.h>
+#include <ctype.h>
+#include <string.h>
+#ifdef __weak_alias
+__weak_alias(strcasecmp,_strcasecmp)
+__weak_alias(strncasecmp,_strncasecmp)
+#endif
+#else
+#include <lib/libkern/libkern.h>
+#include <machine/limits.h>
+#endif 
+
+int
+strcasecmp(const char *s1, const char *s2)
+{
+       const unsigned char *us1 = (const unsigned char *)s1,
+                       *us2 = (const unsigned char *)s2;
+
+       _DIAGASSERT(s1 != NULL);
+       _DIAGASSERT(s2 != NULL);
+
+       while (tolower(*us1) == tolower(*us2++))
+               if (*us1++ == '\0')
+                       return (0);
+       return (tolower(*us1) - tolower(*--us2));
+}
diff --git a/common/lib/libc/string/strcat.c b/common/lib/libc/string/strcat.c
new file mode 100644 (file)
index 0000000..0d83d45
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: strcat.c,v 1.2 2007/06/04 18:19:27 christos Exp $      */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strcat.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strcat.c,v 1.2 2007/06/04 18:19:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#endif
+
+#ifdef _FORTIFY_SOURCE
+#undef strcat
+#endif
+
+char *
+strcat(char *s, const char *append)
+{
+       char    *t = s;
+
+       _DIAGASSERT(t != NULL);
+       _DIAGASSERT(append != NULL);
+
+       for (; *t; ++t)
+               ;
+       while ((*t++ = *append++) != '\0')
+               ;
+       return (s);
+}
diff --git a/common/lib/libc/string/strchr.c b/common/lib/libc/string/strchr.c
new file mode 100644 (file)
index 0000000..01c8946
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: strchr.c,v 1.4 2009/07/17 19:37:57 dsl Exp $   */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)index.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strchr.c,v 1.4 2009/07/17 19:37:57 dsl Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include "namespace.h"
+#include <assert.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#endif
+
+__strong_alias(index, strchr)
+char *
+strchr(const char *p, int ch)
+{
+       const char cmp = ch;
+       _DIAGASSERT(p != NULL);
+
+       for (;; ++p) {
+               if (*p == cmp) {
+                       /* LINTED const cast-away */
+                       return(__UNCONST(p));
+               }
+               if (!*p)
+                       return((char *)NULL);
+       }
+       /* NOTREACHED */
+}
diff --git a/common/lib/libc/string/strcmp.c b/common/lib/libc/string/strcmp.c
new file mode 100644 (file)
index 0000000..e17aab2
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: strcmp.c,v 1.2 2007/06/04 18:19:27 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strcmp.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strcmp.c,v 1.2 2007/06/04 18:19:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#endif
+
+/*
+ * Compare strings.
+ */
+int
+strcmp(const char *s1, const char *s2)
+{
+
+       _DIAGASSERT(s1 != NULL);
+       _DIAGASSERT(s2 != NULL);
+
+       while (*s1 == *s2++)
+               if (*s1++ == 0)
+                       return (0);
+       return (*(const unsigned char *)s1 - *(const unsigned char *)--s2);
+}
diff --git a/common/lib/libc/string/strcpy.c b/common/lib/libc/string/strcpy.c
new file mode 100644 (file)
index 0000000..f7dfb58
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: strcpy.c,v 1.2 2007/06/04 18:19:27 christos Exp $      */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strcpy.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strcpy.c,v 1.2 2007/06/04 18:19:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#endif
+
+#ifdef _FORTIFY_SOURCE
+#undef strcpy
+#endif
+
+char *
+strcpy(char *to, const char *from)
+{
+       char *save = to;
+
+       _DIAGASSERT(to != NULL);
+       _DIAGASSERT(from != NULL);
+
+       for (; (*to = *from) != '\0'; ++from, ++to);
+       return(save);
+}
diff --git a/common/lib/libc/string/strlcat.c b/common/lib/libc/string/strlcat.c
new file mode 100644 (file)
index 0000000..d4a8d7e
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: strlcat.c,v 1.3 2007/06/04 18:19:27 christos Exp $     */
+/*     $OpenBSD: strlcat.c,v 1.10 2003/04/12 21:56:39 millert Exp $    */
+
+/*
+ * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
+ *
+ * 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 TODD C. MILLER DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL TODD C. MILLER 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.
+ */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: strlcat.c,v 1.3 2007/06/04 18:19:27 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef _LIBC
+#include "namespace.h"
+#endif
+#include <sys/types.h>
+#include <assert.h>
+#include <string.h>
+
+#ifdef _LIBC
+# ifdef __weak_alias
+__weak_alias(strlcat, _strlcat)
+# endif
+#endif
+
+#else
+#include <lib/libkern/libkern.h>
+#endif /* !_KERNEL && !_STANDALONE */
+
+#if !HAVE_STRLCAT
+/*
+ * 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
+ * will be copied.  Always NUL terminates (unless siz <= strlen(dst)).
+ * Returns strlen(src) + MIN(siz, strlen(initial dst)).
+ * If retval >= siz, truncation occurred.
+ */
+size_t
+strlcat(char *dst, const char *src, size_t siz)
+{
+       char *d = dst;
+       const char *s = src;
+       size_t n = siz;
+       size_t dlen;
+
+       _DIAGASSERT(dst != NULL);
+       _DIAGASSERT(src != NULL);
+
+       /* Find the end of dst and adjust bytes left but don't go past end */
+       while (n-- != 0 && *d != '\0')
+               d++;
+       dlen = d - dst;
+       n = siz - dlen;
+
+       if (n == 0)
+               return(dlen + strlen(s));
+       while (*s != '\0') {
+               if (n != 1) {
+                       *d++ = *s;
+                       n--;
+               }
+               s++;
+       }
+       *d = '\0';
+
+       return(dlen + (s - src));       /* count does not include NUL */
+}
+#endif
diff --git a/common/lib/libc/string/strlcpy.c b/common/lib/libc/string/strlcpy.c
new file mode 100644 (file)
index 0000000..fbb5f4d
--- /dev/null
@@ -0,0 +1,81 @@
+/*     $NetBSD: strlcpy.c,v 1.3 2007/06/04 18:19:27 christos Exp $     */
+/*     $OpenBSD: strlcpy.c,v 1.7 2003/04/12 21:56:39 millert Exp $     */
+
+/*
+ * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
+ *
+ * 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 TODD C. MILLER DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL TODD C. MILLER 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.
+ */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: strlcpy.c,v 1.3 2007/06/04 18:19:27 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef _LIBC
+#include "namespace.h"
+#endif
+#include <sys/types.h>
+#include <assert.h>
+#include <string.h>
+
+#ifdef _LIBC
+# ifdef __weak_alias
+__weak_alias(strlcpy, _strlcpy)
+# endif
+#endif
+#else
+#include <lib/libkern/libkern.h>
+#endif /* !_KERNEL && !_STANDALONE */
+
+
+#if !HAVE_STRLCPY
+/*
+ * Copy src to string dst of size siz.  At most siz-1 characters
+ * will be copied.  Always NUL terminates (unless siz == 0).
+ * Returns strlen(src); if retval >= siz, truncation occurred.
+ */
+size_t
+strlcpy(char *dst, const char *src, size_t siz)
+{
+       char *d = dst;
+       const char *s = src;
+       size_t n = siz;
+
+       _DIAGASSERT(dst != NULL);
+       _DIAGASSERT(src != NULL);
+
+       /* Copy as many bytes as will fit */
+       if (n != 0 && --n != 0) {
+               do {
+                       if ((*d++ = *s++) == 0)
+                               break;
+               } while (--n != 0);
+       }
+
+       /* Not enough room in dst, add NUL and traverse rest of src */
+       if (n == 0) {
+               if (siz != 0)
+                       *d = '\0';              /* NUL-terminate dst */
+               while (*s++)
+                       ;
+       }
+
+       return(s - src - 1);    /* count does not include NUL */
+}
+#endif
diff --git a/common/lib/libc/string/strlen.c b/common/lib/libc/string/strlen.c
new file mode 100644 (file)
index 0000000..84195a3
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: strlen.c,v 1.2 2007/06/04 18:19:27 christos Exp $      */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strlen.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strlen.c,v 1.2 2007/06/04 18:19:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#endif
+
+size_t
+strlen(const char *str)
+{
+       const char *s;
+
+       _DIAGASSERT(str != NULL);
+
+       for (s = str; *s; ++s)
+               continue;
+       return(s - str);
+}
diff --git a/common/lib/libc/string/strncasecmp.c b/common/lib/libc/string/strncasecmp.c
new file mode 100644 (file)
index 0000000..e58a5da
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: strncasecmp.c,v 1.2 2007/06/04 18:19:27 christos Exp $ */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strcasecmp.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strncasecmp.c,v 1.2 2007/06/04 18:19:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include "namespace.h"
+#include <assert.h>
+#include <ctype.h>
+#include <string.h>
+#ifdef __weak_alias
+__weak_alias(strcasecmp,_strcasecmp)
+__weak_alias(strncasecmp,_strncasecmp)
+#endif
+#else
+#include <lib/libkern/libkern.h>
+#include <machine/limits.h>
+#endif 
+
+int
+strncasecmp(const char *s1, const char *s2, size_t n)
+{
+
+       _DIAGASSERT(s1 != NULL);
+       _DIAGASSERT(s2 != NULL);
+
+       if (n != 0) {
+               const unsigned char *us1 = (const unsigned char *)s1,
+                               *us2 = (const unsigned char *)s2;
+
+               do {
+                       if (tolower(*us1) != tolower(*us2++))
+                               return (tolower(*us1) - tolower(*--us2));
+                       if (*us1++ == '\0')
+                               break;
+               } while (--n != 0);
+       }
+       return (0);
+}
diff --git a/common/lib/libc/string/strncmp.c b/common/lib/libc/string/strncmp.c
new file mode 100644 (file)
index 0000000..105e914
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: strncmp.c,v 1.2 2007/06/04 18:19:27 christos Exp $     */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strncmp.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strncmp.c,v 1.2 2007/06/04 18:19:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#endif
+
+int
+strncmp(const char *s1, const char *s2, size_t n)
+{
+
+       _DIAGASSERT(s1 != NULL);
+       _DIAGASSERT(s2 != NULL);
+
+       if (n == 0)
+               return (0);
+       do {
+               if (*s1 != *s2++)
+                       return (*(const unsigned char *)s1 -
+                           *(const unsigned char *)--s2);
+               if (*s1++ == 0)
+                       break;
+       } while (--n != 0);
+       return (0);
+}
diff --git a/common/lib/libc/string/strncpy.c b/common/lib/libc/string/strncpy.c
new file mode 100644 (file)
index 0000000..afed6c0
--- /dev/null
@@ -0,0 +1,80 @@
+/*     $NetBSD: strncpy.c,v 1.3 2007/06/04 18:19:28 christos Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strncpy.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strncpy.c,v 1.3 2007/06/04 18:19:28 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#endif
+
+#ifdef _FORTIFY_SOURCE
+#undef strncpy
+#endif
+
+/*
+ * Copy src to dst, truncating or null-padding to always copy n bytes.
+ * Return dst.
+ */
+char *
+strncpy(char *dst, const char *src, size_t n)
+{
+
+       _DIAGASSERT(dst != NULL);
+       _DIAGASSERT(src != NULL);
+
+       if (n != 0) {
+               char *d = dst;
+               const char *s = src;
+
+               do {
+                       if ((*d++ = *s++) == 0) {
+                               /* NUL pad the remaining n-1 bytes */
+                               while (--n != 0)
+                                       *d++ = 0;
+                               break;
+                       }
+               } while (--n != 0);
+       }
+       return (dst);
+}
diff --git a/common/lib/libc/string/strrchr.c b/common/lib/libc/string/strrchr.c
new file mode 100644 (file)
index 0000000..c3ddb64
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: strrchr.c,v 1.5 2009/07/17 19:37:57 dsl Exp $  */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)rindex.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strrchr.c,v 1.5 2009/07/17 19:37:57 dsl Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#endif
+
+__strong_alias(rindex, strrchr)
+char *
+strrchr(const char *p, int ch)
+{
+       char *save;
+       const char c = ch;
+
+       _DIAGASSERT(p != NULL);
+
+       for (save = NULL;; ++p) {
+               if (*p == c) {
+                       /* LINTED const cast-away */
+                       save = __UNCONST(p);
+               }
+               if (!*p)
+                       return(save);
+       }
+       /* NOTREACHED */
+}
diff --git a/common/lib/libc/string/strsep.c b/common/lib/libc/string/strsep.c
new file mode 100644 (file)
index 0000000..7972b32
--- /dev/null
@@ -0,0 +1,97 @@
+/*     $NetBSD: strsep.c,v 1.3 2007/06/04 18:19:28 christos Exp $      */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strsep.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strsep.c,v 1.3 2007/06/04 18:19:28 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include "namespace.h"
+
+#include <assert.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(strsep,_strsep)
+#endif
+
+#else
+#include <sys/param.h>
+#include <lib/libkern/libkern.h>
+#endif /* !_KERNEL && !_STANDALONE */
+
+#if !HAVE_STRSEP
+/*
+ * Get next token from string *stringp, where tokens are possibly-empty
+ * strings separated by characters from delim.  
+ *
+ * Writes NULs into the string at *stringp to end tokens.
+ * delim need not remain constant from call to call.
+ * On return, *stringp points past the last NUL written (if there might
+ * be further tokens), or is NULL (if there are definitely no more tokens).
+ *
+ * If *stringp is NULL, strsep returns NULL.
+ */
+char *
+strsep(char **stringp, const char *delim)
+{
+       char *s;
+       const char *spanp;
+       int c, sc;
+       char *tok;
+
+       _DIAGASSERT(stringp != NULL);
+       _DIAGASSERT(delim != NULL);
+
+       if ((s = *stringp) == NULL)
+               return (NULL);
+       for (tok = s;;) {
+               c = *s++;
+               spanp = delim;
+               do {
+                       if ((sc = *spanp++) == c) {
+                               if (c == 0)
+                                       s = NULL;
+                               else
+                                       s[-1] = 0;
+                               *stringp = s;
+                               return (tok);
+                       }
+               } while (sc != 0);
+       }
+       /* NOTREACHED */
+}
+#endif
diff --git a/common/lib/libc/string/strstr.c b/common/lib/libc/string/strstr.c
new file mode 100644 (file)
index 0000000..c2fa47d
--- /dev/null
@@ -0,0 +1,75 @@
+/*     $NetBSD: strstr.c,v 1.2 2007/06/04 18:19:28 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strstr.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strstr.c,v 1.2 2007/06/04 18:19:28 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <string.h>
+#else
+#include <sys/param.h>
+#include <lib/libkern/libkern.h>
+#endif
+
+/*
+ * Find the first occurrence of find in s.
+ */
+char *
+strstr(const char *s, const char *find)
+{
+       char c, sc;
+       size_t len;
+
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(find != NULL);
+
+       if ((c = *find++) != 0) {
+               len = strlen(find);
+               do {
+                       do {
+                               if ((sc = *s++) == 0)
+                                       return (NULL);
+                       } while (sc != c);
+               } while (strncmp(s, find, len) != 0);
+               s--;
+       }
+       return __UNCONST(s);
+}
diff --git a/common/lib/libc/sys/cpuset.c b/common/lib/libc/sys/cpuset.c
new file mode 100644 (file)
index 0000000..66b3320
--- /dev/null
@@ -0,0 +1,310 @@
+/*     $NetBSD: cpuset.c,v 1.16 2010/09/21 02:03:29 rmind Exp $        */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _STANDALONE
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: cpuset.c,v 1.16 2010/09/21 02:03:29 rmind Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/param.h>
+#include <sys/sched.h>
+#ifdef _KERNEL
+#include <sys/kmem.h>
+#include <lib/libkern/libkern.h>
+#include <sys/atomic.h>
+#else
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <sys/sysctl.h>
+#endif
+
+#define        CPUSET_SHIFT    5
+#define        CPUSET_MASK     31
+#define CPUSET_NENTRIES(nc)    ((nc) > 32 ? ((nc) >> CPUSET_SHIFT) : 1)
+#ifndef __lint__
+#define CPUSET_SIZE(n) (sizeof( \
+       struct {  \
+               uint32_t bits[0]; \
+       }) + sizeof(uint32_t) * (n))
+#else
+#define CPUSET_SIZE(n) 0
+#endif
+
+struct _cpuset {
+       uint32_t        bits[0];
+};
+
+#ifdef _KERNEL
+struct _kcpuset {
+       unsigned int    nused;
+       struct _kcpuset *next;
+       uint32_t        bits[0];
+};
+#define KCPUSET_SIZE(n)        (sizeof( \
+       struct {  \
+               unsigned int nused; \
+               struct _kcpuset *next; \
+               uint32_t bits[0]; \
+       }) + sizeof(uint32_t) * (n))
+#endif
+
+static size_t cpuset_size = 0;
+static size_t cpuset_nentries = 0;
+
+#ifndef _KERNEL
+size_t
+/*ARGSUSED*/
+_cpuset_size(const cpuset_t *c)
+{
+
+       return cpuset_size;
+}
+
+void
+_cpuset_zero(cpuset_t *c)
+{
+
+       memset(c->bits, 0, cpuset_nentries * sizeof(c->bits[0]));
+}
+
+int
+_cpuset_isset(cpuid_t i, const cpuset_t *c)
+{
+       const unsigned long j = i >> CPUSET_SHIFT;
+
+       if (j >= cpuset_nentries) {
+               errno = EINVAL;
+               return -1;
+       }
+       return ((1 << (i & CPUSET_MASK)) & c->bits[j]) != 0;
+}
+
+int
+_cpuset_set(cpuid_t i, cpuset_t *c)
+{
+       const unsigned long j = i >> CPUSET_SHIFT;
+
+       if (j >= cpuset_nentries) {
+               errno = EINVAL;
+               return -1;
+       }
+       c->bits[j] |= 1 << (i & CPUSET_MASK);
+       return 0;
+}
+
+int
+_cpuset_clr(cpuid_t i, cpuset_t *c)
+{
+       const unsigned long j = i >> CPUSET_SHIFT;
+
+       if (j >= cpuset_nentries) {
+               errno = EINVAL;
+               return -1;
+       }
+       c->bits[j] &= ~(1 << (i & CPUSET_MASK));
+       return 0;
+}
+
+cpuset_t *
+_cpuset_create(void)
+{
+
+       if (cpuset_size == 0) {
+               static int mib[2] = { CTL_HW, HW_NCPU };
+               size_t len;
+               u_int nc;
+
+               len = sizeof(nc);
+               if (sysctl(mib, __arraycount(mib), &nc, &len, NULL, 0) == -1)
+                       return NULL;
+
+               cpuset_nentries = CPUSET_NENTRIES(nc);
+               cpuset_size = CPUSET_SIZE(cpuset_nentries);
+       }
+       return calloc(1, cpuset_size);
+}
+
+void
+_cpuset_destroy(cpuset_t *c)
+{
+
+       free(c);
+}
+
+#else
+
+kcpuset_t *
+kcpuset_create(void)
+{
+       kcpuset_t *c;
+
+       if (cpuset_size == 0) {
+               cpuset_nentries = CPUSET_NENTRIES(MAXCPUS);
+               cpuset_size = KCPUSET_SIZE(cpuset_nentries);
+       }
+       c = kmem_zalloc(cpuset_size, KM_SLEEP);
+       c->next = NULL;
+       c->nused = 1;
+       return c;
+}
+
+void
+kcpuset_destroy(kcpuset_t *c)
+{
+       kcpuset_t *nc;
+
+       while (c) {
+               KASSERT(c->nused == 0);
+               nc = c->next;
+               kmem_free(c, cpuset_size);
+               c = nc;
+       }
+}
+
+void
+kcpuset_copy(kcpuset_t *d, const kcpuset_t *s)
+{
+
+       KASSERT(d->nused == 1);
+       memcpy(d->bits, s->bits, cpuset_nentries * sizeof(s->bits[0]));
+}
+
+void
+kcpuset_use(kcpuset_t *c)
+{
+
+       atomic_inc_uint(&c->nused);
+}
+
+void
+kcpuset_unuse(kcpuset_t *c, kcpuset_t **lst)
+{
+
+       if (atomic_dec_uint_nv(&c->nused) != 0)
+               return;
+       KASSERT(c->nused == 0);
+       KASSERT(c->next == NULL);
+       if (lst == NULL) {
+               kcpuset_destroy(c);
+               return;
+       }
+       c->next = *lst;
+       *lst = c;
+}
+
+int
+kcpuset_copyin(const cpuset_t *u, kcpuset_t *k, size_t len)
+{
+
+       KASSERT(k->nused > 0);
+       KASSERT(k->next == NULL);
+       if (len != CPUSET_SIZE(cpuset_nentries))
+               return EINVAL;
+       return copyin(u->bits, k->bits, cpuset_nentries * sizeof(k->bits[0]));
+}
+
+int
+kcpuset_copyout(const kcpuset_t *k, cpuset_t *u, size_t len)
+{
+
+       KASSERT(k->nused > 0);
+       KASSERT(k->next == NULL);
+       if (len != CPUSET_SIZE(cpuset_nentries))
+               return EINVAL;
+       return copyout(k->bits, u->bits, cpuset_nentries * sizeof(u->bits[0]));
+}
+
+void
+kcpuset_zero(kcpuset_t *c)
+{
+
+       KASSERT(c->nused > 0);
+       KASSERT(c->next == NULL);
+       memset(c->bits, 0, cpuset_nentries * sizeof(c->bits[0]));
+}
+
+void
+kcpuset_fill(kcpuset_t *c)
+{
+
+       KASSERT(c->nused > 0);
+       KASSERT(c->next == NULL);
+       memset(c->bits, ~0, cpuset_nentries * sizeof(c->bits[0]));
+}
+
+void
+kcpuset_set(cpuid_t i, kcpuset_t *c)
+{
+       const unsigned long j = i >> CPUSET_SHIFT;
+
+       KASSERT(c->next == NULL);
+       KASSERT(j < cpuset_nentries);
+       c->bits[j] |= 1 << (i & CPUSET_MASK);
+}
+
+int
+kcpuset_isset(cpuid_t i, const kcpuset_t *c)
+{
+       const unsigned long j = i >> CPUSET_SHIFT;
+
+       KASSERT(c != NULL);
+       KASSERT(c->nused > 0);
+       KASSERT(c->next == NULL);
+       KASSERT(j < cpuset_nentries);
+       return ((1 << (i & CPUSET_MASK)) & c->bits[j]) != 0;
+}
+
+bool
+kcpuset_iszero(const kcpuset_t *c)
+{
+       unsigned long j;
+
+       for (j = 0; j < cpuset_nentries; j++)
+               if (c->bits[j] != 0)
+                       return false;
+       return true;
+}
+
+bool
+kcpuset_match(const kcpuset_t *c1, const kcpuset_t *c2)
+{
+       unsigned long j;
+
+       for (j = 0; j < cpuset_nentries; j++)
+               if ((c1->bits[j] & c2->bits[j]) != c2->bits[j])
+                       return false;
+       return true;
+}
+
+#endif
+#endif
diff --git a/lib/nbsd_libc/Makefile b/lib/nbsd_libc/Makefile
new file mode 100644 (file)
index 0000000..2bce0bb
--- /dev/null
@@ -0,0 +1,149 @@
+#      $NetBSD: Makefile,v 1.143 2010/09/04 12:17:58 ahoka Exp $
+#      @(#)Makefile    8.2 (Berkeley) 2/3/94
+#
+# All library objects contain sccsid strings by default; they may be
+# excluded as a space-saving measure.  To produce a library that does
+# not contain these strings, delete -DLIBC_SCCS and -DSYSLIBC_SCCS
+# from CPPFLAGS below.  To remove these strings from just the system call
+# stubs, remove just -DSYSLIBC_SCCS from CPPFLAGS.
+#
+# The NLS (message catalog) functions are always in libc.  To choose that
+# strerror(), perror(), strsignal(), psignal(), etc. actually call the NLS
+# functions, put -DNLS on the CPPFLAGS line below.
+#
+# The YP functions are always in libc. To choose that getpwent() and friends
+# actually call the YP functions, put -DYP on the CPPFLAGS line below.
+#
+# The Hesiod functions are always in libc. To choose that getpwent() and friends
+# actually call the Hesiod functions, put -DHESIOD on the CPPFLAGS line below.
+
+.include "Makefile.inc"
+
+LIB=           c
+CPPFLAGS+=     -I${.CURDIR}/include -I${.CURDIR}
+
+LIBCDIR=       ${.CURDIR}
+
+.if exists (${ARCHDIR}/Makefile.inc)
+.PATH: ${ARCHDIR}
+.include "${ARCHDIR}/Makefile.inc"
+.endif
+
+.if exists (${ARCHDIR}/genassym.cf)
+DPSRCS+=       assym.h
+CLEANFILES+=   assym.h assym.h.tmp
+
+assym.h: ${ARCHDIR}/genassym.cf
+       ${_MKTARGET_CREATE}
+       ${TOOL_GENASSYM} -- ${CC} ${CFLAGS} \
+               ${CPPFLAGS} ${CPPFLAGS.assym.h} ${PROF} \
+               < ${ARCHDIR}/genassym.cf > assym.h.tmp && \
+       mv -f assym.h.tmp assym.h
+.endif
+
+# The following controls how to build compatibility code for old NetBSD
+# binaries. If BUILDCOLD is yes, then we build a separate library; otherwise
+# we include the code in libc.
+BUILDCOLD?= no
+.if "${BUILDCOLD}" == "yes"
+SUBDIR=compat
+.include <bsd.subdir.mk>
+.else
+COMPATDIR=${.CURDIR}/compat
+.include "${.CURDIR}/compat/Makefile.inc"
+.endif
+
+.include "${.CURDIR}/../../common/lib/libc/Makefile.inc"
+.include "${.CURDIR}/atomic/Makefile.inc"
+.include "${.CURDIR}/cdb/Makefile.inc"
+.include "${.CURDIR}/db/Makefile.inc"
+.if (${CITRUS} == "yes")
+.include "${.CURDIR}/citrus/Makefile.inc"
+.endif
+.include "${.CURDIR}/compat-43/Makefile.inc"
+.include "${.CURDIR}/dlfcn/Makefile.inc"
+.include "${.CURDIR}/gdtoa/Makefile.inc"
+.include "${.CURDIR}/gen/Makefile.inc"
+.include "${.CURDIR}/gmon/Makefile.inc"
+.include "${.CURDIR}/hash/Makefile.inc"
+.include "${.CURDIR}/iconv/Makefile.inc"
+.include "${.CURDIR}/inet/Makefile.inc"
+.include "${.CURDIR}/isc/Makefile.inc"
+.include "${.CURDIR}/locale/Makefile.inc"
+.include "${.CURDIR}/md/Makefile.inc"
+.include "${.CURDIR}/misc/Makefile.inc"
+.include "${.CURDIR}/net/Makefile.inc"
+.include "${.CURDIR}/nameser/Makefile.inc"
+.include "${.CURDIR}/nls/Makefile.inc"
+.if (${MACHINE_ARCH} != "alpha") && (${MACHINE_ARCH} != "sparc64")
+.include "${.CURDIR}/quad/Makefile.inc"
+.endif
+.if (${USE_LIBTRE} == "yes")
+.include "${NETBSDSRCDIR}/external/bsd/tre/Makefile.inc"
+.else
+.include "${.CURDIR}/regex/Makefile.inc"
+.endif
+.include "${.CURDIR}/resolv/Makefile.inc"
+.include "${.CURDIR}/rpc/Makefile.inc"
+.include "${.CURDIR}/ssp/Makefile.inc"
+.include "${.CURDIR}/stdio/Makefile.inc"
+.include "${.CURDIR}/stdlib/Makefile.inc"
+.include "${.CURDIR}/string/Makefile.inc"
+.include "${.CURDIR}/termios/Makefile.inc"
+.include "${.CURDIR}/thread-stub/Makefile.inc"
+.include "${.CURDIR}/time/Makefile.inc"
+.include "${.CURDIR}/sys/Makefile.inc"
+.include "${.CURDIR}/uuid/Makefile.inc"
+.if (${MKYP} != "no")
+.include "${.CURDIR}/yp/Makefile.inc"
+.endif
+
+# Remove from SRCS the .c files for any .S files added by the MD makefiles,
+# also remove from SRCS the .c files for the .S and .c files in NO_SRCS.
+# Add the .c file for .S files (in both variables) to LSRCS so that the
+# 'normal' .c file for assembly files is used for the lint librray.
+#
+# Usage:
+# Add .S files to NO_SRSC when another .S file provides the entry points.
+# Add .c files to NO_SRSC when another .c file provides the entry points.
+# (lint is run on all .c files in SRCS)
+
+.for check_file in ${SRCS:M*.S} ${NO_SRCS}
+unwanted_file := ${SRCS:M${check_file:.S=.c}}
+.if "${unwanted_file}" != ""
+SRCS := ${SRCS:N${unwanted_file}}
+.if "${unwanted_file}" != "${check_file}"
+LSRCS := ${LSRCS} ${unwanted_file}
+.endif
+.endif
+.endfor
+
+NLS=   C.msg Pig.msg ca.msg cs.msg de.msg es.msg fi.msg fr.msg nl.msg \
+       no.msg pl.msg sk.msg sv.msg
+
+realall: tags
+tags: ${.OBJDIR}/tags
+${.OBJDIR}/tags: ${SRCS}
+       ${_MKTARGET_CREATE}
+       -${TOOL_CTAGS} -w ${.ALLSRC:M*.c}
+       -egrep "^ENTRY(.*)|^FUNC(.*)|^SYSCALL(.*)" /dev/null ${.ALLSRC:M*.S} | \
+           sed "s;\([^:]*\):\([^(]*\)(\([^, )]*\)\(.*\);\3 \1 /^\2(\3\4$$/;" \
+           >> ${.TARGET}; sort -o ${.TARGET} ${.TARGET}
+
+FILES=         ${.OBJDIR}/tags
+FILESNAME=     libc.tags
+FILESDIR=      /var/db
+
+
+# workaround for I18N stuffs: build singlebyte setlocale() for libc.a,
+# multibyte for libc.so.  the quirk should be removed when we support
+# dlopen() from within statically linked binaries.
+.if (${CITRUS} == "yes")
+CSHLIBFLAGS+=  -D_I18N_DYNAMIC
+.endif
+
+.include <bsd.lib.mk>
+
+# force the dynamic linker to initialize libc first
+SHLIB_SHFLAGS+=        -Wl,-z,initfirst
+
diff --git a/lib/nbsd_libc/Makefile.inc b/lib/nbsd_libc/Makefile.inc
new file mode 100644 (file)
index 0000000..6837e02
--- /dev/null
@@ -0,0 +1,64 @@
+#      $NetBSD: Makefile.inc,v 1.6 2010/05/30 08:28:53 tnozaki Exp $
+#      @(#)Makefile    8.2 (Berkeley) 2/3/94
+#
+# All library objects contain sccsid strings by default; they may be
+# excluded as a space-saving measure.  To produce a library that does
+# not contain these strings, delete -DLIBC_SCCS and -DSYSLIBC_SCCS
+# from CPPFLAGS below.  To remove these strings from just the system call
+# stubs, remove just -DSYSLIBC_SCCS from CPPFLAGS.
+#
+# The NLS (message catalog) functions are always in libc.  To choose that
+# strerror(), perror(), strsignal(), psignal(), etc. actually call the NLS
+# functions, put -DNLS on the CPPFLAGS line below.
+#
+# The YP functions are always in libc. To choose that getpwent() and friends
+# actually call the YP functions, put -DYP on the CPPFLAGS line below.
+#
+# The Hesiod functions are always in libc. To choose that getpwent() and friends
+# actually call the Hesiod functions, put -DHESIOD on the CPPFLAGS line below.
+
+USE_FORT?=     yes
+
+USE_SHLIBDIR=  yes
+
+CITRUS?=       yes
+
+.include <bsd.own.mk>
+
+WARNS=4
+CPPFLAGS+=     -D_LIBC -DLIBC_SCCS -DSYSLIBC_SCCS -D_REENTRANT
+
+.if (${USE_HESIOD} != "no")
+CPPFLAGS+=     -DHESIOD
+.endif
+
+.if (${USE_INET6} != "no")
+CPPFLAGS+=     -DINET6
+.endif
+
+CPPFLAGS+=     -DNLS
+
+.if (${USE_YP} != "no")
+CPPFLAGS+=     -DYP
+.endif
+
+.if ${MACHINE_ARCH} == "i386"
+# Set lint to exit on warnings
+LINTFLAGS+=    -w
+.endif
+# ignore 'empty translation unit' warnings.
+LINTFLAGS+=    -X 272
+
+.include "libcincludes.mk"
+
+ARCHDIR=       ${.CURDIR}/arch/${ARCHSUBDIR}
+AFLAGS+=       -I${ARCHDIR}
+.if defined(DESTDIR)
+AFLAGS+=       -nostdinc -isystem ${DESTDIR}/usr/include
+.endif
+CLEANFILES+=   tags
+
+# Don't try to lint the C library against itself when creating llib-lc.ln
+LLIBS=
+
+INCSDIR=       /usr/include
diff --git a/lib/nbsd_libc/arch/alpha/Makefile.inc b/lib/nbsd_libc/arch/alpha/Makefile.inc
new file mode 100644 (file)
index 0000000..a897682
--- /dev/null
@@ -0,0 +1,44 @@
+#      $NetBSD: Makefile.inc,v 1.20 2008/10/26 07:43:07 mrg Exp $
+
+SRCS+= __longjmp14.c
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S
+
+# `source' files built from m4 source
+SRCS+= __divqu.S __divq.S __divlu.S __divl.S
+SRCS+= __remqu.S __remq.S __remlu.S __reml.S
+CLEANFILES+=   __divqu.S __divq.S __divlu.S __divl.S
+CLEANFILES+=   __remqu.S __remq.S __remlu.S __reml.S
+
+__divqu.S: ${LIBCDIR}/arch/alpha/gen/divrem.m4
+       ${TOOL_M4} -DNAME=__divqu -DOP=div -DS=false -DWORDSIZE=64 \
+               ${.ALLSRC} > ${.TARGET}
+
+__divq.S: ${LIBCDIR}/arch/alpha/gen/divrem.m4
+       ${TOOL_M4} -DNAME=__divq -DOP=div -DS=true -DWORDSIZE=64 \
+               ${.ALLSRC} > ${.TARGET}
+
+__divlu.S: ${LIBCDIR}/arch/alpha/gen/divrem.m4
+       ${TOOL_M4} -DNAME=__divlu -DOP=div -DS=false -DWORDSIZE=32 \
+               ${.ALLSRC} > ${.TARGET}
+
+__divl.S: ${LIBCDIR}/arch/alpha/gen/divrem.m4
+       ${TOOL_M4} -DNAME=__divl -DOP=div -DS=true -DWORDSIZE=32 \
+               ${.ALLSRC} > ${.TARGET}
+
+__remqu.S: ${LIBCDIR}/arch/alpha/gen/divrem.m4
+       ${TOOL_M4} -DNAME=__remqu -DOP=rem -DS=false -DWORDSIZE=64 \
+               ${.ALLSRC} > ${.TARGET}
+
+__remq.S: ${LIBCDIR}/arch/alpha/gen/divrem.m4
+       ${TOOL_M4} -DNAME=__remq -DOP=rem -DS=true -DWORDSIZE=64 \
+               ${.ALLSRC} > ${.TARGET}
+
+__remlu.S: ${LIBCDIR}/arch/alpha/gen/divrem.m4
+       ${TOOL_M4} -DNAME=__remlu -DOP=rem -DS=false -DWORDSIZE=32 \
+               ${.ALLSRC} > ${.TARGET}
+
+__reml.S: ${LIBCDIR}/arch/alpha/gen/divrem.m4
+       ${TOOL_M4} -DNAME=__reml -DOP=rem -DS=true -DWORDSIZE=32 \
+               ${.ALLSRC} > ${.TARGET}
+
+CPPFLAGS+= -I.
diff --git a/lib/nbsd_libc/arch/alpha/SYS.h b/lib/nbsd_libc/arch/alpha/SYS.h
new file mode 100644 (file)
index 0000000..2cd4839
--- /dev/null
@@ -0,0 +1,76 @@
+/* $NetBSD: SYS.h,v 1.8 2002/01/14 00:55:55 thorpej Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+#include <sys/syscall.h>
+
+
+#define        CALLSYS_ERROR(name)                                     \
+       CALLSYS_NOERROR(name);                                  \
+       br      gp, LLABEL(name,0);                             \
+LLABEL(name,0):                                                        \
+       LDGP(gp);                                               \
+       beq     a3, LLABEL(name,1);                             \
+       jmp     zero, __cerror;                                 \
+LLABEL(name,1):
+
+
+#define        SYSCALL(name)                                           \
+LEAF(name,0);                          /* XXX # of args? */    \
+       CALLSYS_ERROR(name)
+
+#define        SYSCALL_NOERROR(name)                                   \
+LEAF(name,0);                          /* XXX # of args? */    \
+       CALLSYS_NOERROR(name)
+
+#define        PSEUDO(label,name)                                      \
+LEAF(label,0);                         /* XXX # of args? */    \
+       CALLSYS_ERROR(name);                                    \
+       RET;                                                    \
+END(label);
+
+#define        PSEUDO_NOERROR(label,name)                              \
+LEAF(label,0);                         /* XXX # of args? */    \
+       CALLSYS_NOERROR(name);                                  \
+       RET;                                                    \
+END(label);
+
+#define RSYSCALL(name)                                         \
+       SYSCALL(name);                                          \
+       RET;                                                    \
+END(name)
+
+#define RSYSCALL_NOERROR(name)                                 \
+       SYSCALL_NOERROR(name);                                  \
+       RET;                                                    \
+END(name)
+
+#define        WSYSCALL(weak,strong)                                   \
+       WEAK_ALIAS(weak,strong);                                \
+       PSEUDO(strong,weak)
diff --git a/lib/nbsd_libc/arch/alpha/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/alpha/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..1d786e0
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/15 17:35:18 kleink Exp $
+
+SRCS+= strtof.c
diff --git a/lib/nbsd_libc/arch/alpha/gdtoa/arith.h b/lib/nbsd_libc/arch/alpha/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..650a936
--- /dev/null
@@ -0,0 +1,6 @@
+/* $NetBSD: arith.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define IEEE_LITTLE_ENDIAN
+#ifndef _IEEE_FP
+#define Sudden_Underflow
+#endif
diff --git a/lib/nbsd_libc/arch/alpha/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/alpha/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..36cb4af
--- /dev/null
@@ -0,0 +1,5 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define f_QNAN 0x7fc00000
+#define d_QNAN0 0x0
+#define d_QNAN1 0x7ff80000
diff --git a/lib/nbsd_libc/arch/alpha/gen/Makefile.inc b/lib/nbsd_libc/arch/alpha/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..c3f59d9
--- /dev/null
@@ -0,0 +1,28 @@
+#      $NetBSD: Makefile.inc,v 1.22 2009/12/06 07:12:17 uebayasi Exp $
+
+SRCS+= fabs.S 
+
+# Common ieee754 constants and functions
+SRCS+= infinityf_ieee754.c infinity_ieee754.c infinityl_dbl_ieee754.c
+SRCS+= fpclassifyf_ieee754.c fpclassifyd_ieee754.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c
+SRCS+= isfinitef_ieee754.c isfinited_ieee754.c
+SRCS+= signbitf_ieee754.c signbitd_ieee754.c
+
+SRCS+= nanf.c
+
+SRCS+= flt_rounds.c fpgetmask.c fpgetround.c fpgetsticky.c fpsetmask.c \
+       fpsetround.c fpsetsticky.c
+SRCS+= __setjmp14.S
+SRCS+= __sigsetjmp14.S
+SRCS+= byte_swap_2.S byte_swap_4.S bswap64.c
+SRCS+= _resumecontext.S
+
+LSRCS.alpha.gen=       Lint_bswap16.c Lint_bswap32.c Lint_swapcontext.c
+LSRCS+=                ${LSRCS.alpha.gen}
+DPSRCS+=       ${LSRCS.alpha.gen}
+CLEANFILES+=   ${LSRCS.alpha.gen}
+
+SRCS+= makecontext.c resumecontext.c swapcontext.S _lwp.c
+
diff --git a/lib/nbsd_libc/arch/alpha/gen/__longjmp14.c b/lib/nbsd_libc/arch/alpha/gen/__longjmp14.c
new file mode 100644 (file)
index 0000000..af70b73
--- /dev/null
@@ -0,0 +1,99 @@
+/*     $NetBSD: __longjmp14.c,v 1.5 2008/04/28 20:22:55 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christian Limpach and Matt Thomas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+#include <machine/reg.h>
+#include <machine/alpha_cpu.h>
+
+#define __LIBC12_SOURCE__
+#include <setjmp.h>
+#include <compat/include/setjmp.h>
+
+void
+__longjmp14(jmp_buf env, int val)
+{
+       struct sigcontext *sc = (void *)env;
+       ucontext_t uc;
+
+       /* Ensure non-zero SP */
+       if (sc->sc_sp == 0 || sc->sc_regs[R_ZERO] != 0xacedbade)
+               goto err;
+
+       /* Ensure non-zero return value */
+       if (val == 0)
+               val = -1;
+
+       /* Set _UC_SIGMASK and _UC_CPU */
+       uc.uc_flags = _UC_SIGMASK | _UC_CPU;
+
+       /* Clear uc_link */
+       uc.uc_link = 0;
+
+       /* Save return value in context */
+       uc.uc_mcontext.__gregs[_REG_V0] = val;
+
+       /* Copy saved registers */
+       uc.uc_mcontext.__gregs[_REG_S0] = sc->sc_regs[R_S0];
+       uc.uc_mcontext.__gregs[_REG_S1] = sc->sc_regs[R_S1];
+       uc.uc_mcontext.__gregs[_REG_S2] = sc->sc_regs[R_S2];
+       uc.uc_mcontext.__gregs[_REG_S3] = sc->sc_regs[R_S3];
+       uc.uc_mcontext.__gregs[_REG_S4] = sc->sc_regs[R_S4];
+       uc.uc_mcontext.__gregs[_REG_S5] = sc->sc_regs[R_S5];
+       uc.uc_mcontext.__gregs[_REG_S6] = sc->sc_regs[R_S6];
+       uc.uc_mcontext.__gregs[_REG_RA] = sc->sc_regs[R_RA];
+       uc.uc_mcontext.__gregs[_REG_SP] = sc->sc_sp;
+       uc.uc_mcontext.__gregs[_REG_PC] = sc->sc_pc;
+       uc.uc_mcontext.__gregs[_REG_PS] =
+          (sc->sc_ps | ALPHA_PSL_USERSET) & ~ALPHA_PSL_USERCLR;
+
+       /* Copy FP state */
+       if (sc->sc_ownedfp) {
+               memcpy(&uc.uc_mcontext.__fpregs.__fp_fr,
+                   &sc->sc_fpregs, 31 * sizeof(unsigned long));
+               uc.uc_mcontext.__fpregs.__fp_fpcr = sc->sc_fpcr;
+               /* XXX sc_fp_control */
+               uc.uc_flags |= _UC_FPU;
+       }
+
+       /* Copy signal mask */
+       uc.uc_sigmask = sc->sc_mask;
+
+       setcontext(&uc);
+ err:
+       longjmperror();
+       abort();
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/alpha/gen/__setjmp14.S b/lib/nbsd_libc/arch/alpha/gen/__setjmp14.S
new file mode 100644 (file)
index 0000000..4e59a7b
--- /dev/null
@@ -0,0 +1,118 @@
+/* $NetBSD: __setjmp14.S,v 1.4 2004/03/21 18:04:27 matt Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+#include "assym.h"
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and the previous signal state.
+ */
+
+       .set    noreorder
+
+LEAF(__setjmp14, 1)
+       LDGP(pv)
+       stq     ra, SC_PC(a0)                   /* sc_pc = return address */
+       stq     s0, (SC_REGS+_REG_S0)(a0)       /* saved bits of sc_regs */
+       stq     s1, (SC_REGS+_REG_S1)(a0)
+       stq     s2, (SC_REGS+_REG_S2)(a0)
+       stq     s3, (SC_REGS+_REG_S3)(a0)
+       stq     s4, (SC_REGS+_REG_S4)(a0)
+       stq     s5, (SC_REGS+_REG_S5)(a0)
+       stq     s6, (SC_REGS+_REG_S6)(a0)
+       stq     ra, (SC_REGS+_REG_RA)(a0)
+       stq     sp, (SC_REGS+_REG_SP)(a0)
+
+       /*
+        * get signal information
+        */
+       mov     a0, s0                          /* squirrel away ptr to sc */
+
+       /* see what's blocked */
+       mov     zero, a0                        /* how (insignificant) */
+       mov     zero, a1                        /* set (NULL) */
+       lda     a2, SC_MASK(s0)                 /* point to mask in sc */
+       CALL(__sigprocmask14)
+
+       lda     sp, -24(sp)                     /* sizeof struct sigaltstack */
+       mov     zero, a0
+       mov     sp, a1
+       CALL(__sigaltstack14)
+       ldl     t0, 16(sp)                      /* offset of ss_flags */
+       lda     sp, 24(sp)                      /* sizeof struct sigaltstack */
+       ldq     ra, (SC_REGS+_REG_RA)(s0)       /* restore return address */
+       blt     v0, botch                       /* check for error */
+       and     t0, 0x1, t0                     /* get SA_ONSTACK flag */
+       stq     t0, SC_ONSTACK(s0)              /* and save it in sc_onstack */
+       /*
+        * Restore old s0 and a0, and continue saving registers
+        */
+       mov     s0, a0
+       ldq     s0, (SC_REGS+_REG_S0)(a0)
+
+       ldiq    t0, 0xacedbade                  /* sigcontext magic number */
+       stq     t0, (SC_REGS+_REG_UNIQUE)(a0)   /* magic in sc_regs[31] */
+       /* Too bad we can't check if we actually used FP */
+       ldiq    t0, 1
+       stq     t0, SC_OWNEDFP(a0)              /* say we've used FP.  */
+       stt     fs0, (2*8 + SC_FPREGS)(a0)      /* saved bits of sc_fpregs */
+       stt     fs1, (3*8 + SC_FPREGS)(a0)
+       stt     fs2, (4*8 + SC_FPREGS)(a0)
+       stt     fs3, (5*8 + SC_FPREGS)(a0)
+       stt     fs4, (6*8 + SC_FPREGS)(a0)
+       stt     fs5, (7*8 + SC_FPREGS)(a0)
+       stt     fs6, (8*8 + SC_FPREGS)(a0)
+       stt     fs7, (9*8 + SC_FPREGS)(a0)
+       mf_fpcr ft0                             /* get FP control reg */
+       stt     ft0, SC_FPCR(a0)                /* and store it in sc_fpcr */
+       stq     zero, SC_FP_CONTROL(a0)         /* FP software control XXX */
+       stq     zero, (SC_RESERVED + 0*8)(a0)   /* sc_reserved[0] */
+       stq     zero, (SC_RESERVED + 1*8)(a0)   /* sc_reserved[1] */
+       stq     zero, (SC_XXX + 0*8)(a0)        /* sc_xxx[0] */
+       stq     zero, (SC_XXX + 1*8)(a0)        /* sc_xxx[1] */
+       stq     zero, (SC_XXX + 2*8)(a0)        /* sc_xxx[2] */
+       stq     zero, (SC_XXX + 3*8)(a0)        /* sc_xxx[3] */
+       stq     zero, (SC_XXX + 4*8)(a0)        /* sc_xxx[4] */
+       stq     zero, (SC_XXX + 5*8)(a0)        /* sc_xxx[5] */
+       stq     zero, (SC_XXX + 6*8)(a0)        /* sc_xxx[6] */
+       stq     zero, (SC_XXX + 7*8)(a0)        /* sc_xxx[7] */
+
+       mov     zero, v0                        /* return zero */
+       RET
+botch:
+       CALL(abort)
+       RET                                     /* "can't" get here... */
+END(__setjmp14)
diff --git a/lib/nbsd_libc/arch/alpha/gen/__sigsetjmp14.S b/lib/nbsd_libc/arch/alpha/gen/__sigsetjmp14.S
new file mode 100644 (file)
index 0000000..4460f7e
--- /dev/null
@@ -0,0 +1,62 @@
+/* $NetBSD: __sigsetjmp14.S,v 1.2 2000/06/14 06:49:01 cgd Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+
+/*
+ * C library -- sigsetjmp, siglongjmp
+ *
+ *     siglongjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     sigsetjmp(a, mask)
+ * by restoring registers from the stack.
+ * If `mask' is non-zero, the previous signal
+ * state will be restored.
+ */
+
+       .set    noreorder
+
+LEAF(__sigsetjmp14, 2)
+       LDGP(pv)
+       stq     a1, (83 * 8)(a0)                /* save the mask */
+       bne     a1, Lsavesig                    /* if !zero, save signals */
+       jmp     zero, _setjmp                           /* else don't. */
+Lsavesig:
+       jmp     zero, __setjmp14
+END(__sigsetjmp14)
+
+LEAF(__siglongjmp14, 2)
+       LDGP(pv)
+       ldq     t0, (83 * 8)(a0)                /* get the mask */
+       bne     t0, Lrestoresig                 /* if !zero, restore signals */
+       jmp     zero, _longjmp
+Lrestoresig:
+       jmp     zero, __longjmp14
+END(__siglongjmp14)
diff --git a/lib/nbsd_libc/arch/alpha/gen/_lwp.c b/lib/nbsd_libc/arch/alpha/gen/_lwp.c
new file mode 100644 (file)
index 0000000..2121368
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: _lwp.c,v 1.5 2008/04/28 20:22:55 martin Exp $  */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Nathan J. Williams.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.5 2008/04/28 20:22:55 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+
+void
+_lwp_makecontext(ucontext_t *u, void (*start)(void *),
+    void *arg, void *private, caddr_t stack_base, size_t stack_size)
+{
+       __greg_t *gr;
+
+       getcontext(u);
+       gr = u->uc_mcontext.__gregs;
+
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+
+       gr[_REG_PC] = (unsigned long)start;
+       gr[_REG_T12] = (unsigned long) start;
+       gr[_REG_RA] = (unsigned long) _lwp_exit;
+       gr[_REG_A0] = (unsigned long) arg;
+       gr[_REG_SP] = ((unsigned long) (stack_base + stack_size)) & ~0x7;
+       gr[_REG_S6] = 0;
+}
diff --git a/lib/nbsd_libc/arch/alpha/gen/_resumecontext.S b/lib/nbsd_libc/arch/alpha/gen/_resumecontext.S
new file mode 100644 (file)
index 0000000..8babf15
--- /dev/null
@@ -0,0 +1,35 @@
+/* $NetBSD: _resumecontext.S,v 1.3 2008/04/22 04:47:44 dogcow Exp $ */
+       
+/*
+ * Copyright (c) 2004
+ *     Matthias Drochner. 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.
+ */
+
+#include <machine/asm.h>
+
+LEAF_NOPROFILE(__resumecontext, 0)
+       LDGP(ra)
+       CALL(_resumecontext)
+END(__resumecontext)
+
diff --git a/lib/nbsd_libc/arch/alpha/gen/divrem.m4 b/lib/nbsd_libc/arch/alpha/gen/divrem.m4
new file mode 100644 (file)
index 0000000..d8a1d2b
--- /dev/null
@@ -0,0 +1,197 @@
+/* $NetBSD: divrem.m4,v 1.9 2002/01/21 23:40:41 ross Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+/*
+ * Division and remainder.
+ *
+ * The use of m4 is modeled after the sparc code, but the algorithm is
+ * simple binary long division.
+ *
+ * Note that the loops could probably benefit from unrolling.
+ */
+
+/*
+ * M4 Parameters
+ * NAME                name of function to generate
+ * OP          OP=div: t10 / t11 -> t12; OP=rem: t10 % t11 -> t12
+ * S           S=true: signed; S=false: unsigned
+ * WORDSIZE    total number of bits
+ */
+
+define(A, `t10')
+define(B, `t11')
+define(RESULT, `t12')
+
+define(BIT, `t0')
+define(I, `t1')
+define(CC, `t2')
+define(T_0, `t3')
+ifelse(S, `true', `define(NEG, `t4')')
+
+#include <machine/asm.h>
+
+LEAF(NAME, 0)                                  /* XXX */
+       lda     sp, -64(sp)
+       stq     BIT, 0(sp)
+       stq     I, 8(sp)
+       stq     CC, 16(sp)
+       stq     T_0, 24(sp)
+ifelse(S, `true',
+`      stq     NEG, 32(sp)')
+       stq     A, 40(sp)
+       stq     B, 48(sp)
+       mov     zero, RESULT                    /* Initialize result to zero */
+
+ifelse(S, `true',
+`
+       /* Compute sign of result.  If either is negative, this is easy.  */
+       or      A, B, NEG                       /* not the sign, but... */
+       srl     NEG, WORDSIZE - 1, NEG          /* rather, or of high bits */
+       blbc    NEG, Ldoit                      /* neither negative? do it! */
+
+ifelse(OP, `div',
+`      xor     A, B, NEG                       /* THIS is the sign! */
+', `   mov     A, NEG                          /* sign follows A. */
+')
+       srl     NEG, WORDSIZE - 1, NEG          /* make negation the low bit. */
+
+       srl     A, WORDSIZE - 1, I              /* is A negative? */
+       blbc    I, LnegB                        /* no. */
+       /* A is negative; flip it. */
+ifelse(WORDSIZE, `32', `
+       /* top 32 bits may be random junk */
+       zap     A, 0xf0, A
+')
+       subq    zero, A, A
+       srl     B, WORDSIZE - 1, I              /* is B negative? */
+       blbc    I, Ldoit                        /* no. */
+LnegB:
+       /* B is definitely negative, no matter how we got here. */
+ifelse(WORDSIZE, `32', `
+       /* top 32 bits may be random junk */
+       zap     B, 0xf0, B
+')
+       subq    zero, B, B
+Ldoit:
+')
+ifelse(WORDSIZE, `32', `
+       /*
+        * Clear the top 32 bits of each operand, as they may
+        * sign extension (if negated above), or random junk.
+        */
+       zap     A, 0xf0, A
+       zap     B, 0xf0, B
+')
+
+       /* kill the special cases. */
+       beq     B, Ldotrap                      /* division by zero! */
+
+       cmpult  A, B, CC                        /* A < B? */
+       /* RESULT is already zero, from above.  A is untouched. */
+       bne     CC, Lret_result
+
+       cmpeq   A, B, CC                        /* A == B? */
+       cmovne  CC, 1, RESULT
+       cmovne  CC, zero, A
+       bne     CC, Lret_result
+
+       /*
+        * Find out how many bits of zeros are at the beginning of the divisor.
+        */
+LBbits:
+       ldiq    T_0, 1                          /* I = 0; BIT = 1<<WORDSIZE-1 */
+       mov     zero, I
+       sll     T_0, WORDSIZE-1, BIT
+LBloop:
+       and     B, BIT, CC                      /* if bit in B is set, done. */
+       bne     CC, LAbits
+       addq    I, 1, I                         /* increment I, shift bit */
+       srl     BIT, 1, BIT
+       cmplt   I, WORDSIZE-1, CC               /* if I leaves one bit, done. */
+       bne     CC, LBloop
+
+LAbits:
+       beq     I, Ldodiv                       /* If I = 0, divide now.  */
+       ldiq    T_0, 1                          /* BIT = 1<<WORDSIZE-1 */
+       sll     T_0, WORDSIZE-1, BIT
+
+LAloop:
+       and     A, BIT, CC                      /* if bit in A is set, done. */
+       bne     CC, Ldodiv
+       subq    I, 1, I                         /* decrement I, shift bit */
+       srl     BIT, 1, BIT 
+       bne     I, LAloop                       /* If I != 0, loop again */
+
+Ldodiv:
+       sll     B, I, B                         /* B <<= i */
+       ldiq    T_0, 1
+       sll     T_0, I, BIT
+
+Ldivloop:
+       cmpult  A, B, CC
+       or      RESULT, BIT, T_0
+       cmoveq  CC, T_0, RESULT
+       subq    A, B, T_0
+       cmoveq  CC, T_0, A
+       srl     BIT, 1, BIT     
+       srl     B, 1, B
+       beq     A, Lret_result
+       bne     BIT, Ldivloop
+
+Lret_result:
+ifelse(OP, `div',
+`', `  mov     A, RESULT
+')
+ifelse(S, `true',
+`
+       /* Check to see if we should negate it. */
+       subq    zero, RESULT, T_0
+       cmovlbs NEG, T_0, RESULT
+')
+
+       ldq     BIT, 0(sp)
+       ldq     I, 8(sp)
+       ldq     CC, 16(sp)
+       ldq     T_0, 24(sp)
+ifelse(S, `true',
+`      ldq     NEG, 32(sp)')
+       ldq     A, 40(sp)
+       ldq     B, 48(sp)
+       lda     sp, 64(sp)
+       ret     zero, (t9), 1
+
+Ldotrap:
+       ldiq    a0, -2                  /* This is the signal to SIGFPE! */
+       call_pal PAL_gentrap
+ifelse(OP, `div',
+`', `  mov     zero, A                 /* so that zero will be returned */
+')
+       br      zero, Lret_result
+
+END(NAME)
diff --git a/lib/nbsd_libc/arch/alpha/gen/fabs.S b/lib/nbsd_libc/arch/alpha/gen/fabs.S
new file mode 100644 (file)
index 0000000..8ba84ba
--- /dev/null
@@ -0,0 +1,35 @@
+/* $NetBSD: fabs.S,v 1.3 2000/06/14 06:49:02 cgd Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+
+LEAF(fabs, 1)
+       cpys    fzero, fa0, fv0
+       RET
+END(fabs)
diff --git a/lib/nbsd_libc/arch/alpha/gen/flt_rounds.c b/lib/nbsd_libc/arch/alpha/gen/flt_rounds.c
new file mode 100644 (file)
index 0000000..ef06c6c
--- /dev/null
@@ -0,0 +1,64 @@
+/* $NetBSD: flt_rounds.c,v 1.8 2005/12/24 23:10:08 perry Exp $ */
+
+/*
+ * Copyright (c) 1995 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: flt_rounds.c,v 1.8 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <machine/float.h>
+
+static const int map[] = {
+       0,      /* round to zero */
+       3,      /* round to negative infinity */
+       1,      /* round to nearest */
+       2       /* round to positive infinity */
+};
+
+int
+__flt_rounds()
+{
+       double fpcrval;
+       u_int64_t old;
+
+       __asm("trapb");
+       __asm("mf_fpcr %0" : "=f" (fpcrval));
+       __asm("trapb");
+       old = *(u_int64_t *)(void *)&fpcrval;
+
+       return map[(old >> 58) & 0x3];
+}
diff --git a/lib/nbsd_libc/arch/alpha/gen/fpgetmask.c b/lib/nbsd_libc/arch/alpha/gen/fpgetmask.c
new file mode 100644 (file)
index 0000000..b0fd56b
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: fpgetmask.c,v 1.5 2005/06/12 05:21:25 lukem Exp $      */
+
+/*
+ * Copyright (c) 1999 Ross Harvey
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Ross Harvey
+ *     for the NetBSD Project.
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetmask.c,v 1.5 2005/06/12 05:21:25 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+#include <machine/sysarch.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetmask,_fpgetmask)
+#endif
+
+fp_except
+fpgetmask __P((void))
+{
+       return sysarch(ALPHA_FPGETMASK, 0L);
+}
diff --git a/lib/nbsd_libc/arch/alpha/gen/fpgetround.c b/lib/nbsd_libc/arch/alpha/gen/fpgetround.c
new file mode 100644 (file)
index 0000000..1bee9b6
--- /dev/null
@@ -0,0 +1,61 @@
+/* $NetBSD: fpgetround.c,v 1.9 2005/12/24 23:10:08 perry Exp $ */
+
+/*
+ * Copyright (c) 1995 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetround.c,v 1.9 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetround,_fpgetround)
+#endif
+
+fp_rnd
+fpgetround()
+{
+       double fpcrval;
+       u_int64_t old;
+
+       __asm("mf_fpcr %0" : "=f" (fpcrval));
+       old = *(u_int64_t *)(void *)&fpcrval;
+
+       return ((old >> 58) & 0x3);
+}
diff --git a/lib/nbsd_libc/arch/alpha/gen/fpgetsticky.c b/lib/nbsd_libc/arch/alpha/gen/fpgetsticky.c
new file mode 100644 (file)
index 0000000..55d7e66
--- /dev/null
@@ -0,0 +1,54 @@
+/* $NetBSD: fpgetsticky.c,v 1.9 2008/05/10 15:31:04 martin Exp $ */
+
+/*-
+ * Copyright (c) 2001 Ross Harvey
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the NetBSD
+ *     Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetsticky.c,v 1.9 2008/05/10 15:31:04 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+#include <machine/sysarch.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetsticky,_fpgetsticky)
+#endif
+
+fp_except
+fpgetsticky(void)
+{
+       return sysarch(ALPHA_FPGETSTICKY, 0L);
+}
diff --git a/lib/nbsd_libc/arch/alpha/gen/fpsetmask.c b/lib/nbsd_libc/arch/alpha/gen/fpsetmask.c
new file mode 100644 (file)
index 0000000..55d6dc1
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: fpsetmask.c,v 1.4 2005/06/12 05:21:25 lukem Exp $      */
+
+/*
+ * Copyright (c) 1995 Ross Harvey
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Ross Harvey
+ *     for the NetBSD Project.
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetmask.c,v 1.4 2005/06/12 05:21:25 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+#include <machine/sysarch.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetmask,_fpsetmask)
+#endif
+
+fp_except
+fpsetmask(mask)
+       fp_except mask;
+{
+       struct alpha_fp_except_args a;
+
+       a.mask = mask;
+       return sysarch(ALPHA_FPSETMASK, &a);
+}
diff --git a/lib/nbsd_libc/arch/alpha/gen/fpsetround.c b/lib/nbsd_libc/arch/alpha/gen/fpsetround.c
new file mode 100644 (file)
index 0000000..b3cb5a5
--- /dev/null
@@ -0,0 +1,70 @@
+/* $NetBSD: fpsetround.c,v 1.10 2005/12/24 23:10:08 perry Exp $ */
+
+/*
+ * Copyright (c) 1995 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetround.c,v 1.10 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetround,_fpsetround)
+#endif
+
+fp_rnd
+fpsetround(rnd_dir)
+       fp_rnd rnd_dir;
+{
+       double fpcrval;
+       u_int64_t old, new;
+
+       __asm("excb");
+       __asm("mf_fpcr %0" : "=f" (fpcrval));
+       old = *(u_int64_t *)(void *)&fpcrval;
+
+       new = old & ~(long)0x0c00000000000000;
+       new = (long)rnd_dir << 58;
+       *(u_int64_t *)(void *)&fpcrval = new;
+
+       __asm("mt_fpcr %0" : : "f" (fpcrval));
+       __asm("excb");
+
+       return ((old >> 58) & 0x3);
+}
diff --git a/lib/nbsd_libc/arch/alpha/gen/fpsetsticky.c b/lib/nbsd_libc/arch/alpha/gen/fpsetsticky.c
new file mode 100644 (file)
index 0000000..8306834
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: fpsetsticky.c,v 1.4 2005/06/12 05:21:25 lukem Exp $    */
+
+/*
+ * Copyright (c) 1999 Ross Harvey
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Ross Harvey
+ *     for the NetBSD Project.
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetsticky.c,v 1.4 2005/06/12 05:21:25 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+#include <machine/sysarch.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetsticky,_fpsetsticky)
+#endif
+
+fp_except
+fpsetsticky(sticky)
+       fp_except sticky;
+{
+       struct alpha_fp_except_args a;
+
+       a.mask = sticky;
+       return sysarch(ALPHA_FPSETSTICKY, &a);
+}
diff --git a/lib/nbsd_libc/arch/alpha/gen/makecontext.c b/lib/nbsd_libc/arch/alpha/gen/makecontext.c
new file mode 100644 (file)
index 0000000..3554eb3
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: makecontext.c,v 1.4 2008/04/28 20:22:55 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.4 2008/04/28 20:22:55 martin Exp $");
+#endif
+
+#include <stddef.h>
+#include <inttypes.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#include <stdarg.h>
+
+void
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+{
+       __greg_t *gr = ucp->uc_mcontext.__gregs;
+       int i;
+       unsigned long *sp;
+       va_list ap;
+
+       void __resumecontext(void);
+
+       /* Compute and align stack pointer. */
+       sp = (unsigned long *)
+           (((uintptr_t)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size) & ~0x7);
+       /* Allocate necessary stack space for arguments exceeding a0-5. */
+       if (argc > 6)
+               sp -= (argc - 6);
+       gr[_REG_SP] = (__greg_t)sp;
+       /* Arrange for return via the trampoline code. */
+       gr[_REG_RA] = (__greg_t)__resumecontext;
+       gr[_REG_PC] = (__greg_t)func;
+       gr[_REG_PV] = (__greg_t)func;
+
+       va_start(ap, argc);
+       /* Pass up to six arguments in a0-5. */
+       for (i = 0; i < argc && i < 6; i++)
+               gr[_REG_A0 + i] = va_arg(ap, unsigned long);
+       /* Pass any additional arguments on the stack. */
+       for (argc -= i; argc > 0; argc--)
+               *sp++ = va_arg(ap, unsigned long);
+       va_end(ap);
+}
diff --git a/lib/nbsd_libc/arch/alpha/gen/nanf.c b/lib/nbsd_libc/arch/alpha/gen/nanf.c
new file mode 100644 (file)
index 0000000..7a5b3a2
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: nanf.c,v 1.5 2009/02/22 01:34:01 martin Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nanf.c,v 1.5 2009/02/22 01:34:01 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+/* bytes for quiet NaN (IEEE single precision) */
+const union __float_u __nanf =
+               { {    0,    0, 0xc0, 0x7f } };
+
+__warn_references(__nanf, "warning: <math.h> defines NAN incorrectly for your compiler.")
diff --git a/lib/nbsd_libc/arch/alpha/gen/resumecontext.c b/lib/nbsd_libc/arch/alpha/gen/resumecontext.c
new file mode 100644 (file)
index 0000000..cd1795b
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:55 martin Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:55 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <ucontext.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include "extern.h"
+
+void
+_resumecontext()
+{
+       ucontext_t uct;
+
+       (void)getcontext(&uct);
+       if (!uct.uc_link) {
+               exit(0);
+               /* NOTREACHED */
+       }
+
+       (void)setcontext(uct.uc_link);
+       /* NOTREACHED */
+
+       /* something is wrong, pull the brake */
+       _exit(-1);
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/alpha/gen/swapcontext.S b/lib/nbsd_libc/arch/alpha/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..2a91164
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: swapcontext.S,v 1.3 2008/04/28 20:22:55 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+NESTED(swapcontext, 2, 24, ra, IM_RA|IM_A0|IM_A1, 0)
+       LDGP(pv)
+       lda     sp, -24(sp)
+       stq     ra, (24- 8)(sp)         /* must save ra, oucp, ucp */
+       stq     a0, (24-16)(sp)
+       stq     a1, (24-24)(sp)
+       CALL(_getcontext)               /* getcontext(oucp) */
+       ldq     t0, (24-16)(sp)
+       bne     v0, Lerr
+       ldq     t1, (24- 8)(sp)
+       stq     t1, (56 + 26 * 8)(t0)   /* Adjust saved RA */
+       stq     t1, (56 + 32 * 8)(t0)   /* Adjust saved PC */
+       lda     t1, 24(sp)
+       stq     t1, (56 + 30 * 8)(t0)   /* Adjust saved SP */
+
+       ldq     a0, (24-24)(sp)
+       CALL(setcontext)                /* setcontext(ucp) */
+Lerr:
+       ldq     ra, (24- 8)(sp)
+       lda     sp, 24(sp)
+       RET
+END(swapcontext)
diff --git a/lib/nbsd_libc/arch/alpha/genassym.cf b/lib/nbsd_libc/arch/alpha/genassym.cf
new file mode 100644 (file)
index 0000000..64d4ed0
--- /dev/null
@@ -0,0 +1,84 @@
+#      $NetBSD: genassym.cf,v 1.2 2008/04/28 20:22:55 martin Exp $
+
+#
+# Copyright (c) 2001 The NetBSD Foundation, Inc.
+# All rights reserved.
+#
+# This code is derived from software contributed to The NetBSD Foundation
+# by Matt Thomas <matt@3am-sfotware.com>.
+#
+# 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/types.h>
+include <machine/reg.h>
+include <ucontext.h>
+include <signal.h>
+
+define _REG_V0         8*_REG_V0       /* 0 */
+define _REG_T0         8*_REG_T0       /* 1 */
+define _REG_T1         8*_REG_T1       /* 2 */
+define _REG_T2         8*_REG_T2       /* 3 */
+define _REG_T3         8*_REG_T3       /* 4 */
+define _REG_T4         8*_REG_T4       /* 5 */
+define _REG_T5         8*_REG_T5       /* 6 */
+define _REG_T6         8*_REG_T6       /* 7 */
+define _REG_T7         8*_REG_T7       /* 8 */
+define _REG_S0         8*_REG_S0       /* 9 */
+define _REG_S1         8*_REG_S1       /* 10 */
+define _REG_S2         8*_REG_S2       /* 11 */
+define _REG_S3         8*_REG_S3       /* 12 */
+define _REG_S4         8*_REG_S4       /* 13 */
+define _REG_S5         8*_REG_S5       /* 14 */
+define _REG_S6         8*_REG_S6       /* 15 */
+define _REG_A0         8*_REG_A0       /* 16 */
+define _REG_A1         8*_REG_A1       /* 17 */
+define _REG_A2         8*_REG_A2       /* 18 */
+define _REG_A3         8*_REG_A3       /* 19 */
+define _REG_A4         8*_REG_A4       /* 20 */
+define _REG_A5         8*_REG_A5       /* 21 */
+define _REG_T8         8*_REG_T8       /* 22 */
+define _REG_T9         8*_REG_T9       /* 23 */
+define _REG_T10                8*_REG_T10      /* 24 */
+define _REG_T11                8*_REG_T11      /* 25 */
+define _REG_RA         8*_REG_RA       /* 26 */
+define _REG_T12                8*_REG_T12      /* 27 */
+define _REG_PV         8*_REG_PV       /* 27 */
+define _REG_AT         8*_REG_AT       /* 28 */
+define _REG_GP         8*_REG_GP       /* 29 */
+define _REG_SP         8*_REG_SP       /* 30 */
+define _REG_UNIQUE     8*_REG_UNIQUE   /* 31 */
+define _REG_PC         8*_REG_PC       /* 32 */
+define _REG_PS         8*_REG_PS       /* 33 */
+
+define SC_ONSTACK      offsetof(struct sigcontext, sc_onstack)
+define SC_SP           offsetof(struct sigcontext, sc_sp)
+define SC_PC           offsetof(struct sigcontext, sc_pc)
+define SC_PS           offsetof(struct sigcontext, sc_ps)
+define SC_REGS         offsetof(struct sigcontext, sc_regs)
+define SC_OWNEDFP      offsetof(struct sigcontext, sc_regs)
+define SC_FPREGS       offsetof(struct sigcontext, sc_fpregs)
+define SC_FPCR         offsetof(struct sigcontext, sc_fpcr)
+define SC_FP_CONTROL   offsetof(struct sigcontext, sc_fp_control)
+define SC_MASK         offsetof(struct sigcontext, sc_mask)
+define SC_RESERVED     offsetof(struct sigcontext, sc_reserved)
+define SC_XXX          offsetof(struct sigcontext, sc_xxx)
diff --git a/lib/nbsd_libc/arch/alpha/gmon/Makefile.inc b/lib/nbsd_libc/arch/alpha/gmon/Makefile.inc
new file mode 100644 (file)
index 0000000..35d0bfd
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 2000/09/05 16:28:31 thorpej Exp $
+
+SRCS+= _mcount.S
diff --git a/lib/nbsd_libc/arch/alpha/net/Makefile.inc b/lib/nbsd_libc/arch/alpha/net/Makefile.inc
new file mode 100644 (file)
index 0000000..9f1a438
--- /dev/null
@@ -0,0 +1,10 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/12/06 07:12:17 uebayasi Exp $
+
+# objects built from assembler sources (need lint stubs)
+# hton* and nto* functions provided by ../gen/byte_swap_*.S
+SRCS+=  
+
+LSRCS.alpha.net=       Lint_htonl.c Lint_htons.c Lint_ntohl.c Lint_ntohs.c
+LSRCS+=                ${LSRCS.alpha.net}
+DPSRCS+=       ${LSRCS.alpha.net}
+CLEANFILES+=   ${LSRCS.alpha.net}
diff --git a/lib/nbsd_libc/arch/alpha/stdlib/Makefile.inc b/lib/nbsd_libc/arch/alpha/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..0dbbca4
--- /dev/null
@@ -0,0 +1 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/07/31 20:39:59 dsl Exp $
diff --git a/lib/nbsd_libc/arch/alpha/string/Makefile.inc b/lib/nbsd_libc/arch/alpha/string/Makefile.inc
new file mode 100644 (file)
index 0000000..d7c4794
--- /dev/null
@@ -0,0 +1,5 @@
+#      $NetBSD: Makefile.inc,v 1.6 2009/07/30 20:57:15 dsl Exp $
+
+SRCS+= bcopy.S bzero.S ffs.S 
+
+SRCS+= memcpy.S memmove.S
diff --git a/lib/nbsd_libc/arch/alpha/sys/__clone.S b/lib/nbsd_libc/arch/alpha/sys/__clone.S
new file mode 100644 (file)
index 0000000..824d1c9
--- /dev/null
@@ -0,0 +1,91 @@
+/*     $NetBSD: __clone.S,v 1.3 2008/04/28 20:22:55 martin Exp $       */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(clone, __clone)
+#endif
+
+/*
+ * int __clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+LEAF(__clone, 4)
+       br      pv, 1f
+1:     LDGP(pv)
+       
+       /*
+        * Sanity checks: func and stack may not be NULL.
+        */
+       beq     a0, 9f
+       beq     a1, 9f
+
+       /*
+        * We need to be able to get at the func and arg arguments
+        * in the child.  Luckily, we have a convenient place to
+        * do this; the child's stack.
+        */
+       subq    a1, 16, a1
+       stq     a0, 0(a1)
+       stq     a3, 8(a1)
+
+       /*
+        * The system call expects (flags, stack).
+        */
+       mov     a2, a0
+       CALLSYS_ERROR(__clone)
+
+       beq     a4, 8f          /* a4 (rv[1]) == 0, parent, child pid in v0 */
+
+       /*
+        * Fetch the function and argument from the new stack, and
+        * pop it back.
+        */
+       ldq     pv, 0(sp)
+       ldq     a0, 8(sp)
+       addq    sp, 16, sp
+
+       /* Call the clone's entry point. */
+       CALL((pv))
+
+       /* Pass return value to _exit(). */
+       mov     v0, a0
+       CALL(_exit)
+
+       /* NOTREACHED */
+
+8:     RET
+
+9:     ldiq    v0, EINVAL
+       jmp     zero, __cerror
+       END(__clone)
diff --git a/lib/nbsd_libc/arch/alpha/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/alpha/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..77d0896
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.7 2008/04/28 20:22:55 martin Exp $        */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/types.h>
+#include <stddef.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern const int __sigtramp_siginfo_2[];
+
+       /*
+        * If no sigaction, use the "default" trampoline since it won't
+        * be used.
+        */
+       if (act == NULL)
+               return  __sigaction_sigtramp(sig, act, oact, NULL, 0);
+
+#ifdef __LIBC12_SOURCE__
+       /*
+        * We select the non-SA_SIGINFO trampoline if SA_SIGINFO is not
+        * set in the sigaction.
+        */
+       if ((act->sa_flags & SA_SIGINFO) == 0) {
+               extern const int __sigtramp_sigcontext_1[];
+               int sav = errno;
+               int rv =  __sigaction_sigtramp(sig, act, oact,
+                   __sigtramp_sigcontext_1, 1);
+               if (rv >= 0 || errno != EINVAL)
+                       return rv;
+               errno = sav;
+       }
+#endif
+
+       /*
+        * If SA_SIGINFO was specified or the compatibility trampolines
+        * can't be used, use the siginfo trampoline.
+        */
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_2, 2);
+}
diff --git a/lib/nbsd_libc/arch/alpha/sys/__sigtramp2.S b/lib/nbsd_libc/arch/alpha/sys/__sigtramp2.S
new file mode 100644 (file)
index 0000000..4c94fb2
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: __sigtramp2.S,v 1.2 2006/11/08 21:16:40 drochner Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995, 1996 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ *
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ *
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ *
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+/*
+ * The Alpha signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ *
+ * On entry, the stack looks like:
+ *
+ *             ucontext structure      [128] == sp + sizeof(siginfo_t)]
+ *     sp->    siginfo structure       [0]
+ */
+NESTED_NOPROFILE(__sigtramp_siginfo_2,0,0,ra,0,0)
+       ldgp    gp,0(ra)
+       lda     a0,(128)(sp)            /* get pointer to ucontext */
+       CALLSYS_NOERROR(setcontext)     /* and call setcontext() with it */
+       ldiq    a0,-1                   /* if that failed, set an exit code */
+       CALLSYS_NOERROR(exit)           /* and call exit() */
+END(__sigtramp_siginfo_2)
diff --git a/lib/nbsd_libc/arch/alpha/sys/__syscall.S b/lib/nbsd_libc/arch/alpha/sys/__syscall.S
new file mode 100644 (file)
index 0000000..ca2b600
--- /dev/null
@@ -0,0 +1,32 @@
+/* $NetBSD: __syscall.S,v 1.1 2000/12/13 07:49:17 mycroft Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+RSYSCALL(__syscall)
diff --git a/lib/nbsd_libc/arch/alpha/sys/__vfork14.S b/lib/nbsd_libc/arch/alpha/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..2b4022c
--- /dev/null
@@ -0,0 +1,35 @@
+/* $NetBSD: __vfork14.S,v 1.2 2000/06/14 06:49:03 cgd Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+SYSCALL(__vfork14)
+       cmovne  a4, zero, v0            /* a4 (rv[1]) != 0, child */
+       RET
+END(__vfork14)
diff --git a/lib/nbsd_libc/arch/alpha/sys/brk.S b/lib/nbsd_libc/arch/alpha/sys/brk.S
new file mode 100644 (file)
index 0000000..032640f
--- /dev/null
@@ -0,0 +1,54 @@
+/* $NetBSD: brk.S,v 1.9 2001/05/07 17:19:17 kleink Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+       .globl  _end
+IMPORT(__curbrk, 8)
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(brk, _brk)
+#endif
+
+       .data
+EXPORT(__minbrk)
+       .quad   _end
+
+       .text
+LEAF(_brk, 1)
+       br      pv, L1                          /* XXX profiling */
+L1:    LDGP(pv)
+       ldq     v0, __minbrk
+       cmpult  a0, v0, t0
+       cmovne  t0, v0, a0
+       CALLSYS_ERROR(break)
+       stq     a0, __curbrk
+       mov     zero, v0
+       RET
+END(_brk)
diff --git a/lib/nbsd_libc/arch/alpha/sys/cerror.S b/lib/nbsd_libc/arch/alpha/sys/cerror.S
new file mode 100644 (file)
index 0000000..1878863
--- /dev/null
@@ -0,0 +1,65 @@
+/* $NetBSD: cerror.S,v 1.6 2000/06/14 06:49:03 cgd Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+#ifdef _REENTRANT
+#define        FRAME_SIZE              16
+#define        FRAME_RA_OFFSET         0
+#define        FRAME_V0_OFFSET         8
+#endif
+
+#ifdef _REENTRANT
+NESTED(__cerror, 0, FRAME_SIZE, ra, IM_RA|IM_V0, 0)
+#else
+LEAF(__cerror, 0)
+#endif
+       br      t0, L1
+L1:    LDGP(t0)
+
+#ifdef _REENTRANT
+       lda     sp, -FRAME_SIZE(sp)
+       stq     ra, FRAME_RA_OFFSET(sp)
+       stq     v0, FRAME_V0_OFFSET(sp)
+
+       CALL(__errno)
+
+       ldq     t0, FRAME_V0_OFFSET(sp)
+       stl     t0, 0(v0)
+#else
+       stl     v0, errno
+#endif
+
+       ldiq    v0, -1
+#ifdef _REENTRANT
+       ldq     ra, FRAME_RA_OFFSET(sp)
+       lda     sp, FRAME_SIZE(sp)
+#endif
+       RET
+END(__cerror)
diff --git a/lib/nbsd_libc/arch/alpha/sys/exect.S b/lib/nbsd_libc/arch/alpha/sys/exect.S
new file mode 100644 (file)
index 0000000..57db0fa
--- /dev/null
@@ -0,0 +1,35 @@
+/* $NetBSD: exect.S,v 1.3 2000/06/14 06:49:03 cgd Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+LEAF(exect, 3)
+       CALLSYS_ERROR(execve)
+       RET
+END(exect)
diff --git a/lib/nbsd_libc/arch/alpha/sys/fork.S b/lib/nbsd_libc/arch/alpha/sys/fork.S
new file mode 100644 (file)
index 0000000..2b93d7b
--- /dev/null
@@ -0,0 +1,36 @@
+/* $NetBSD: fork.S,v 1.5 2003/02/13 02:50:48 nathanw Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+LEAF(__fork, 0)
+       CALLSYS_ERROR(fork)
+       cmovne  a4, zero, v0            /* a4 (rv[1]) != 0, child */
+       RET
+END(__fork)
diff --git a/lib/nbsd_libc/arch/alpha/sys/getcontext.S b/lib/nbsd_libc/arch/alpha/sys/getcontext.S
new file mode 100644 (file)
index 0000000..b973957
--- /dev/null
@@ -0,0 +1,43 @@
+/*     $NetBSD: getcontext.S,v 1.3 2008/04/28 20:22:55 martin Exp $    */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext, _getcontext)
+#endif
+
+LEAF(_getcontext, 1)
+       CALLSYS_ERROR(getcontext)
+       stq     ra, (56 + 32 * 8)(a0)   /* Adjust saved PC */
+       stq     zero, (56 + 0 * 8)(a0)  /* Arrange for a return value of 0 */
+       RET
+END(_getcontext)
diff --git a/lib/nbsd_libc/arch/alpha/sys/pipe.S b/lib/nbsd_libc/arch/alpha/sys/pipe.S
new file mode 100644 (file)
index 0000000..cddc812
--- /dev/null
@@ -0,0 +1,42 @@
+/* $NetBSD: pipe.S,v 1.4 2001/05/07 17:19:18 kleink Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe, _pipe)
+#endif
+
+LEAF(_pipe, 0)
+       CALLSYS_ERROR(pipe)
+       stl     v0, 0(a0)
+       stl     a4, 4(a0)
+       mov     zero, v0
+       RET
+END(_pipe)
diff --git a/lib/nbsd_libc/arch/alpha/sys/ptrace.S b/lib/nbsd_libc/arch/alpha/sys/ptrace.S
new file mode 100644 (file)
index 0000000..46eff5b
--- /dev/null
@@ -0,0 +1,37 @@
+/* $NetBSD: ptrace.S,v 1.5 2000/06/14 06:49:03 cgd Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+LEAF(ptrace, 4)
+       LDGP(pv)
+       stl     zero, errno
+       CALLSYS_ERROR(ptrace)
+       RET
+END(ptrace)
diff --git a/lib/nbsd_libc/arch/alpha/sys/sbrk.S b/lib/nbsd_libc/arch/alpha/sys/sbrk.S
new file mode 100644 (file)
index 0000000..afd80c4
--- /dev/null
@@ -0,0 +1,52 @@
+/* $NetBSD: sbrk.S,v 1.9 2001/05/07 17:19:18 kleink Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+       .globl  _end
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(sbrk, _sbrk)
+#endif
+
+       .data
+EXPORT(__curbrk)
+       .quad   _end
+
+       .text
+LEAF(_sbrk, 1)
+       br      pv, L1                          /* XXX profiling */
+L1:    LDGP(pv)
+       ldq     a1, __curbrk
+       addq    a0, a1, a0
+       CALLSYS_ERROR(break)
+       stq     a0, __curbrk
+       mov     a1, v0
+       RET
+END(_sbrk)
diff --git a/lib/nbsd_libc/arch/alpha/sys/shmat.S b/lib/nbsd_libc/arch/alpha/sys/shmat.S
new file mode 100644 (file)
index 0000000..90e3185
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: shmat.S,v 1.1 2000/07/07 08:20:51 itohy Exp $  */
+
+#include "SYS.h"
+
+RSYSCALL(shmat)
diff --git a/lib/nbsd_libc/arch/alpha/sys/syscall.S b/lib/nbsd_libc/arch/alpha/sys/syscall.S
new file mode 100644 (file)
index 0000000..b97ef3f
--- /dev/null
@@ -0,0 +1,32 @@
+/* $NetBSD: syscall.S,v 1.2 2000/06/14 06:49:03 cgd Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+RSYSCALL(syscall)
diff --git a/lib/nbsd_libc/arch/arm/Makefile.inc b/lib/nbsd_libc/arch/arm/Makefile.inc
new file mode 100644 (file)
index 0000000..7f0313b
--- /dev/null
@@ -0,0 +1,10 @@
+# $NetBSD: Makefile.inc,v 1.9 2010/07/06 05:59:52 mrg Exp $
+
+.include <bsd.own.mk>
+
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S
+
+CPPFLAGS += -DSOFTFLOAT
+
+SOFTFLOAT_BITS=32
+.include <softfloat/Makefile.inc>
diff --git a/lib/nbsd_libc/arch/arm/SYS.h b/lib/nbsd_libc/arch/arm/SYS.h
new file mode 100644 (file)
index 0000000..d4f2e5d
--- /dev/null
@@ -0,0 +1,94 @@
+/*     $NetBSD: SYS.h,v 1.10 2011/01/14 06:12:16 matt Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)SYS.h 5.5 (Berkeley) 5/7/91
+ */
+
+#include <machine/asm.h>
+#include <sys/syscall.h>
+#include <arm/swi.h>
+
+#ifdef __STDC__
+#define SYSTRAP(x)     swi SWI_OS_NETBSD | SYS_ ## x
+#else
+#define SYSTRAP(x)     swi SWI_OS_NETBSD | SYS_/**/x
+#endif
+
+#ifdef __ELF__
+#define        CERROR          _C_LABEL(__cerror)
+#define        CURBRK          _C_LABEL(__curbrk)
+#else
+#define        CERROR          _ASM_LABEL(cerror)
+#define        CURBRK          _ASM_LABEL(curbrk)
+#endif
+
+#define _SYSCALL_NOERROR(x,y)                                          \
+       ENTRY(x);                                                       \
+       SYSTRAP(y)
+
+#define _SYSCALL(x, y)                                                 \
+       _SYSCALL_NOERROR(x,y);                                          \
+       bcs CERROR
+
+#define SYSCALL_NOERROR(x)                                             \
+       _SYSCALL_NOERROR(x,x)
+
+#define SYSCALL(x)                                                     \
+       _SYSCALL(x,x)
+
+
+#define PSEUDO_NOERROR(x,y)                                            \
+       _SYSCALL_NOERROR(x,y);                                          \
+       RET
+
+#define PSEUDO(x,y)                                                    \
+       _SYSCALL(x,y);                                                  \
+       RET
+
+
+#define RSYSCALL_NOERROR(x)                                            \
+       PSEUDO_NOERROR(x,x)
+
+#define RSYSCALL(x)                                                    \
+       PSEUDO(x,x)
+
+#ifdef WEAK_ALIAS
+#define        WSYSCALL(weak,strong)                                           \
+       WEAK_ALIAS(weak,strong);                                        \
+       PSEUDO(strong,weak)
+#else
+#define        WSYSCALL(weak,strong)                                           \
+       PSEUDO(weak,weak)
+#endif
+
+       .globl  CERROR
diff --git a/lib/nbsd_libc/arch/arm/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/arm/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..1d786e0
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/15 17:35:18 kleink Exp $
+
+SRCS+= strtof.c
diff --git a/lib/nbsd_libc/arch/arm/gdtoa/arith.h b/lib/nbsd_libc/arch/arm/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..40d3ed1
--- /dev/null
@@ -0,0 +1,9 @@
+/* $NetBSD: arith.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#include <machine/endian.h>
+
+#if BYTE_ORDER == BIG_ENDIAN
+#define IEEE_BIG_ENDIAN
+#else
+#define IEEE_LITTLE_ENDIAN
+#endif
diff --git a/lib/nbsd_libc/arch/arm/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/arm/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..9554f49
--- /dev/null
@@ -0,0 +1,12 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#include <machine/endian.h>
+
+#define f_QNAN 0x7fc00000
+#if BYTE_ORDER == BIG_ENDIAN
+#define d_QNAN0 0x7ff80000
+#define d_QNAN1 0x0
+#else
+#define d_QNAN0 0x0
+#define d_QNAN1 0x7ff80000
+#endif
diff --git a/lib/nbsd_libc/arch/arm/gen/Makefile.inc b/lib/nbsd_libc/arch/arm/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..d9aa365
--- /dev/null
@@ -0,0 +1,27 @@
+# $NetBSD: Makefile.inc,v 1.16 2009/12/06 07:12:17 uebayasi Exp $
+
+SRCS+= alloca.S byte_swap_2.S byte_swap_4.S bswap64.c divsi3.S \
+       fabs.c flt_rounds.c
+
+# Common ieee754 constants and functions
+SRCS+= infinityf_ieee754.c infinity_ieee754.c infinityl_dbl_ieee754.c
+SRCS+= fpclassifyf_ieee754.c fpclassifyd_ieee754.c
+SRCS+= isfinitef_ieee754.c isfinited_ieee754.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c
+SRCS+= signbitf_ieee754.c signbitd_ieee754.c
+
+SRCS+= nanf.c
+
+SRCS+= setjmp.S
+SRCS+= _setjmp.S
+SRCS+= sigsetjmp.S
+
+SRCS+= makecontext.c resumecontext.c swapcontext.S
+
+SRCS+= _lwp.c
+
+LSRCS.arm.gen= Lint_bswap16.c Lint_bswap32.c Lint_swapcontext.c
+LSRCS+=                ${LSRCS.arm.gen}
+DPSRCS+=       ${LSRCS.arm.gen}
+CLEANFILES+=   ${LSRCS.arm.gen}
diff --git a/lib/nbsd_libc/arch/arm/gen/_lwp.c b/lib/nbsd_libc/arch/arm/gen/_lwp.c
new file mode 100644 (file)
index 0000000..fcc78bd
--- /dev/null
@@ -0,0 +1,71 @@
+/*     $NetBSD: _lwp.c,v 1.4 2005/06/12 05:21:25 lukem Exp $   */
+
+/*
+ * Copyright (c) 2001 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Jason R. Thorpe for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed for the NetBSD Project by
+ *     Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.4 2005/06/12 05:21:25 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+
+void
+_lwp_makecontext(ucontext_t *u, void (*start)(void *),
+    void *arg, void *private, caddr_t stack_base, size_t stack_size)
+{
+       void **sp;
+
+       getcontext(u);
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+
+       sp = (void **) (stack_base + stack_size);
+
+       /*
+        * Note: We make sure the stack is 8-byte aligned, here.
+        */
+
+       u->uc_mcontext.__gregs[_REG_R0] = (__greg_t) arg;
+       u->uc_mcontext.__gregs[_REG_SP] = ((__greg_t) sp) & ~7;
+       u->uc_mcontext.__gregs[_REG_LR] = (__greg_t) _lwp_exit;
+       u->uc_mcontext.__gregs[_REG_PC] = (__greg_t) start;
+}
diff --git a/lib/nbsd_libc/arch/arm/gen/_setjmp.S b/lib/nbsd_libc/arch/arm/gen/_setjmp.S
new file mode 100644 (file)
index 0000000..559d9b3
--- /dev/null
@@ -0,0 +1,105 @@
+/*     $NetBSD: _setjmp.S,v 1.6 2004/08/21 11:20:10 rearnsha Exp $     */
+
+/*
+ * Copyright (c) 1997 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe
+ * 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 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 <machine/asm.h>
+#include <machine/setjmp.h>
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     _longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     _setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is NOT restored.
+ *
+ * Note: r0 is the return value
+ *       r1-r3 are scratch registers in functions
+ */
+
+ENTRY(_setjmp)
+       ldr     r1, .L_setjmp_magic
+       str     r1, [r0], #4
+#ifdef SOFTFLOAT
+       add     r0, r0, #52
+#else
+       /* Store fp registers */
+       sfm     f4, 4, [r0], #48
+       /* Store fpsr */
+       rfs     r1
+       str     r1, [r0], #0x0004
+#endif /* SOFTFLOAT */
+       /* Store integer registers */
+        stmia  r0, {r4-r14}
+
+        mov    r0, #0x00000000
+        RET
+
+.L_setjmp_magic:
+       .word   _JB_MAGIC__SETJMP
+
+ENTRY(_longjmp)
+       ldr     r2, .L_setjmp_magic
+       ldr     r3, [r0], #4
+       teq     r2, r3
+       bne     botch
+
+#ifdef SOFTFLOAT
+       add     r0, r0, #52
+#else
+       /* Restore fp registers */
+       lfm     f4, 4, [r0], #48
+       /* Restore fpsr */
+       ldr     r4, [r0], #0x0004
+       wfs     r4
+#endif /* SOFTFLOAT */
+               /* Restore integer registers */
+        ldmia  r0, {r4-r14}
+
+       /* Validate sp and r14 */
+       teq     sp, #0
+       teqne   r14, #0
+       beq     botch
+
+       /* Set return value */
+       mov     r0, r1
+       teq     r0, #0x00000000
+       moveq   r0, #0x00000001
+       RET
+
+       /* validation failed, die die die. */
+botch:
+       bl      PIC_SYM(_C_LABEL(longjmperror), PLT)
+       bl      PIC_SYM(_C_LABEL(abort), PLT)
+       b       . - 8           /* Cannot get here */
diff --git a/lib/nbsd_libc/arch/arm/gen/alloca.S b/lib/nbsd_libc/arch/arm/gen/alloca.S
new file mode 100644 (file)
index 0000000..694c2a9
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: alloca.S,v 1.4 2004/08/21 11:20:10 rearnsha Exp $      */
+
+/*
+ * Copyright (c) 1995 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe
+ * 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 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.
+ */
+
+/* like alloc, but automatic automatic free in return */
+
+#include <machine/asm.h>
+
+ENTRY(alloca)
+       add     r0, r0, #0x00000007     /* round up to next 8 byte alignment */
+       bic     r0, r0, #0x00000007
+       sub     sp, sp, r0              /* Adjust the stack pointer */
+       mov     r0, sp                  /* r0 = base of new space */
+       RET
diff --git a/lib/nbsd_libc/arch/arm/gen/fabs.c b/lib/nbsd_libc/arch/arm/gen/fabs.c
new file mode 100644 (file)
index 0000000..64cbeba
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: fabs.c,v 1.3 2006/05/16 05:29:16 mrg Exp $     */
+
+/*
+ * Copyright (c) 1996 Mark Brinicombe
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe
+ * 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 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.
+ */
+
+/*
+ * fabs(x) returns the absolute value of x.
+ */
+
+double fabs(double x);
+
+double
+fabs(double x)
+{
+       if (x < 0)
+               x = -x;
+       return(x);
+}
diff --git a/lib/nbsd_libc/arch/arm/gen/flt_rounds.c b/lib/nbsd_libc/arch/arm/gen/flt_rounds.c
new file mode 100644 (file)
index 0000000..a341e6e
--- /dev/null
@@ -0,0 +1,81 @@
+/*     $NetBSD: flt_rounds.c,v 1.3 2006/02/25 00:58:35 wiz Exp $       */
+
+/*
+ * Copyright (c) 1996 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Mark Brinicombe
+ *     for the NetBSD Project.
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: flt_rounds.c,v 1.3 2006/02/25 00:58:35 wiz Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+static const int map[] = {
+       1,      /* round to nearest */
+       2,      /* round to positive infinity */
+       3,      /* round to negative infinity */
+       0       /* round to zero */
+};
+
+/*
+ * Return the current FP rounding mode
+ *
+ * Returns:
+ *     0 - round to zero
+ *     1 - round to nearest
+ *     2 - round to postive infinity
+ *     3 - round to negative infinity
+ *
+ * ok all we need to do is get the current FP rounding mode
+ * index our map table and return the appropriate value.
+ *
+ * HOWEVER:
+ * The ARM FPA codes the rounding mode into the actual FP instructions
+ * so there is no such thing as a global rounding mode.
+ * The default is round to nearest if rounding is not explicitly specified.
+ * FP instructions generated by GCC will not explicitly specify a rounding
+ * mode.
+ *
+ * So the best we can do it to return the rounding mode FP instructions
+ * use if rounding is not specified which is round to nearest.
+ *
+ * This could change in the future with new floating point emulators or
+ * soft float FP libraries.
+ */
+
+int __flt_rounds(void);
+
+int
+__flt_rounds()
+{
+       return(map[fpgetround()]);
+}
diff --git a/lib/nbsd_libc/arch/arm/gen/makecontext.c b/lib/nbsd_libc/arch/arm/gen/makecontext.c
new file mode 100644 (file)
index 0000000..cf9bfea
--- /dev/null
@@ -0,0 +1,73 @@
+/*     $NetBSD: makecontext.c,v 1.3 2008/04/28 20:22:55 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.3 2008/04/28 20:22:55 martin Exp $");
+#endif
+
+#include <stddef.h>
+#include <inttypes.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#include <stdarg.h>
+
+void
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+{
+       __greg_t *gr = ucp->uc_mcontext.__gregs;
+       int i;
+       unsigned int *sp;
+       va_list ap;
+
+       /* Compute and align stack pointer. */
+       sp = (unsigned int *)
+           (((uintptr_t)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size) & ~7);
+       /* Allocate necessary stack space for arguments exceeding r0-3. */
+       if (argc > 4)
+               sp -= argc - 4;
+       gr[_REG_SP] = (__greg_t)sp;
+       /* Wipe out frame pointer. */
+       gr[_REG_FP] = 0;
+       /* Arrange for return via the trampoline code. */
+       gr[_REG_LR] = (__greg_t)_resumecontext;
+       gr[_REG_PC] = (__greg_t)func;
+
+       va_start(ap, argc);
+       /* Pass up to four arguments in r0-3. */
+       for (i = 0; i < argc && i < 4; i++)
+               gr[_REG_R0 + i] = va_arg(ap, int);
+       /* Pass any additional arguments on the stack. */
+       for (argc -= i; argc > 0; argc--)
+               *sp++ = va_arg(ap, int);
+       va_end(ap);
+}
diff --git a/lib/nbsd_libc/arch/arm/gen/nanf.c b/lib/nbsd_libc/arch/arm/gen/nanf.c
new file mode 100644 (file)
index 0000000..0be7edd
--- /dev/null
@@ -0,0 +1,19 @@
+/*     $NetBSD: nanf.c,v 1.4 2009/02/22 01:34:01 martin Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nanf.c,v 1.4 2009/02/22 01:34:01 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+/* bytes for quiet NaN (IEEE single precision) */
+const union __float_u __nanf =
+#if BYTE_ORDER == BIG_ENDIAN
+               { { 0x7f, 0xc0,    0,    0 } };
+#else
+               { {    0,    0, 0xc0, 0x7f } };
+#endif
+
+__warn_references(__nanf, "warning: <math.h> defines NAN incorrectly for your compiler.")
diff --git a/lib/nbsd_libc/arch/arm/gen/resumecontext.c b/lib/nbsd_libc/arch/arm/gen/resumecontext.c
new file mode 100644 (file)
index 0000000..7cb6a42
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:55 martin Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:55 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "extern.h"
+
+void
+_resumecontext()
+{
+       ucontext_t uct;
+
+       (void)getcontext(&uct);
+       if (uct.uc_link == NULL) 
+               exit(0);
+       (void)setcontext(uct.uc_link);
+       _exit(-1);
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/arm/gen/setjmp.S b/lib/nbsd_libc/arch/arm/gen/setjmp.S
new file mode 100644 (file)
index 0000000..b3f5a62
--- /dev/null
@@ -0,0 +1,121 @@
+/*     $NetBSD: setjmp.S,v 1.8 2005/10/16 17:26:24 christos Exp $      */
+
+/*
+ * Copyright (c) 1997 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe
+ * 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 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 <machine/asm.h>
+#include <machine/setjmp.h>
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(__setjmp14)
+       /* Get the signal mask. */
+       stmfd   sp!, {r0-r2, r14}
+       add     r2, r0, #(_JB_SIGMASK * 4)
+       mov     r1, #0x00000000
+       mov     r0, #0x00000000
+       bl      PIC_SYM(_C_LABEL(__sigprocmask14), PLT)
+       ldmfd   sp!, {r0-r2, r14}
+
+       ldr     r1, .Lsetjmp_magic
+       str     r1, [r0], #4
+
+#ifdef SOFTFLOAT
+       add     r0, r0, #52
+#else
+       /* Store fp registers */
+       sfm     f4, 4, [r0], #48
+       /* Store fpsr */
+       rfs     r1
+       str     r1, [r0], #0x0004
+#endif /*SOFTFLOAT*/
+       /* Store integer registers */
+        stmia  r0, {r4-r14}
+        mov    r0, #0x00000000
+        RET
+
+.Lsetjmp_magic:
+       .word   _JB_MAGIC_SETJMP
+
+
+ENTRY(__longjmp14)
+       ldr     r2, .Lsetjmp_magic
+       ldr     r3, [r0]
+       teq     r2, r3
+       bne     .Lbotch
+
+       /* Restore the signal mask. */
+       stmfd   sp!, {r0-r2, r14}
+       mov     r2, #0x00000000
+       add     r1, r0, #(_JB_SIGMASK * 4)
+       mov     r0, #3                          /* SIG_SETMASK */
+       bl      PIC_SYM(_C_LABEL(__sigprocmask14), PLT)
+       ldmfd   sp!, {r0-r2, r14}
+
+       add     r0, r0, #4
+#ifdef SOFTFLOAT
+       add     r0, r0, #52
+#else
+       /* Restore fp registers */
+       lfm     f4, 4, [r0], #48
+       /* Restore FPSR */
+       ldr     r4, [r0], #0x0004
+       wfs     r4
+#endif /* SOFTFLOAT */
+       /* Restore integer registers */
+        ldmia  r0, {r4-r14}
+
+       /* Validate sp and r14 */
+       teq     sp, #0
+       teqne   r14, #0
+       beq     .Lbotch
+
+       /* Set return value */
+
+       mov     r0, r1
+       teq     r0, #0x00000000
+       moveq   r0, #0x00000001
+       RET
+
+       /* validation failed, die die die. */
+.Lbotch:
+       bl      PIC_SYM(_C_LABEL(longjmperror), PLT)
+       bl      PIC_SYM(_C_LABEL(abort), PLT)
+       b       . - 8           /* Cannot get here */
diff --git a/lib/nbsd_libc/arch/arm/gen/sigsetjmp.S b/lib/nbsd_libc/arch/arm/gen/sigsetjmp.S
new file mode 100644 (file)
index 0000000..58afe0b
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: sigsetjmp.S,v 1.5 2005/10/16 17:26:24 christos Exp $   */
+
+/*
+ * Copyright (c) 1997 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe
+ * 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 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 <machine/asm.h>
+#include <machine/setjmp.h>
+
+/*
+ * C library -- sigsetjmp, siglongjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     setjmp(a, m)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(__sigsetjmp14)
+       teq     r1, #0
+       beq     PIC_SYM(_C_LABEL(_setjmp), PLT)
+       b       PIC_SYM(_C_LABEL(__setjmp14), PLT)
+
+.L_setjmp_magic:
+       .word   _JB_MAGIC__SETJMP
+
+ENTRY(__siglongjmp14)
+       ldr     r2, .L_setjmp_magic
+       ldr     r3, [r0]
+       teq     r2, r3
+       beq     PIC_SYM(_C_LABEL(_longjmp), PLT)
+       b       PIC_SYM(_C_LABEL(__longjmp14), PLT)
diff --git a/lib/nbsd_libc/arch/arm/gen/swapcontext.S b/lib/nbsd_libc/arch/arm/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..a193733
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: swapcontext.S,v 1.5 2008/04/28 20:22:55 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+        RCSID("$NetBSD: swapcontext.S,v 1.5 2008/04/28 20:22:55 martin Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+ENTRY(swapcontext)
+       stmfd   sp!, {r0-r1, lr}        /* Must save oucp, ucp, lr. */
+       bl      PIC_SYM(_C_LABEL(_getcontext), PLT)  /* getcontext(oucp) */
+       cmp     r0, #0
+       ldmfd   sp!, {r0-r1, lr}
+       RETc(ne)
+       str     lr, [r0, #(36 + 15*4)]  /* Adjust saved PC. */
+#ifdef SOFTFLOAT
+       /* Ahem. */
+#endif
+       mov     r0, r1
+       bl      PIC_SYM(_C_LABEL(setcontext), PLT)
+       RET
diff --git a/lib/nbsd_libc/arch/arm/hardfloat/fpgetmask.S b/lib/nbsd_libc/arch/arm/hardfloat/fpgetmask.S
new file mode 100644 (file)
index 0000000..7064608
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: fpgetmask.S,v 1.4 2004/08/21 11:21:00 rearnsha Exp $   */
+
+/*
+ * Copyright (c) 1996 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe
+ *     for the NetBSD project.
+ * 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 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 <machine/asm.h>
+
+/*
+ * Return the current FP exception enable mask
+ */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpgetmask, _fpgetmask)
+ENTRY(_fpgetmask)
+#else
+ENTRY(fpgetmask)
+#endif
+       rfs     r0
+       mov     r0, r0, lsr #16
+       and     r0, r0, #0x1f
+       RET
diff --git a/lib/nbsd_libc/arch/arm/hardfloat/fpgetround.c b/lib/nbsd_libc/arch/arm/hardfloat/fpgetround.c
new file mode 100644 (file)
index 0000000..e333bcd
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: fpgetround.c,v 1.4 2006/02/25 02:28:55 wiz Exp $       */
+
+/*
+ * Copyright (c) 1996 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Mark Brinicombe
+ *     for the NetBSD Project.
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetround.c,v 1.4 2006/02/25 02:28:55 wiz Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetround,_fpgetround)
+#endif
+
+/*
+ * Return the current FP rounding mode
+ *
+ * ok all we need to do is return the current FP rounding mode
+ *
+ * HOWEVER:
+ * The ARM FPA codes the rounding mode into the actual FP instructions
+ * so there is no such thing as a global rounding mode.
+ * The default is round to nearest if rounding is not explicitly specified.
+ * FP instructions generated by GCC will not explicitly specify a rounding
+ * mode.
+ *
+ * So the best we can do it to return the rounding mode FP instructions
+ * use if rounding is not specified which is round to nearest.
+ *
+ * This could change in the future with new floating point emulators or
+ * soft float FP libraries.
+ */
+
+fp_rnd
+fpgetround()
+{
+
+       return(FP_RN);
+}
diff --git a/lib/nbsd_libc/arch/arm/hardfloat/fpgetsticky.S b/lib/nbsd_libc/arch/arm/hardfloat/fpgetsticky.S
new file mode 100644 (file)
index 0000000..f7ee580
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: fpgetsticky.S,v 1.4 2004/08/21 11:21:00 rearnsha Exp $ */
+
+/*
+ * Copyright (c) 1996 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe
+ *     for the NetBSD project.
+ * 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 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 <machine/asm.h>
+
+/*
+ * Return the current FP cumulative flags
+ */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpgetsticky, _fpgetsticky)
+ENTRY(_fpgetsticky)
+#else
+ENTRY(fpgetsticky)
+#endif
+       rfs     r0
+       and     r0, r0, #0x1f
+       RET
diff --git a/lib/nbsd_libc/arch/arm/hardfloat/fpsetmask.S b/lib/nbsd_libc/arch/arm/hardfloat/fpsetmask.S
new file mode 100644 (file)
index 0000000..1c956cf
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: fpsetmask.S,v 1.4 2004/08/21 11:21:00 rearnsha Exp $   */
+
+/*
+ * Copyright (c) 1996 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe
+ *     for the NetBSD project.
+ * 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 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 <machine/asm.h>
+
+/*
+ * Set the current FP exception enable mask
+ */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpsetmask, _fpsetmask)
+ENTRY(_fpsetmask)
+#else
+ENTRY(fpsetmask)
+#endif
+       rfs     r1
+       bic     r1, r1, #0x001f0000
+       and     r0, r0, #0x0000001f
+       orr     r0, r1, r0, lsl #16
+       wfs     r0
+       mov     r0, r1, lsr #16         /* Return old mask */
+       RET
diff --git a/lib/nbsd_libc/arch/arm/hardfloat/fpsetround.c b/lib/nbsd_libc/arch/arm/hardfloat/fpsetround.c
new file mode 100644 (file)
index 0000000..ffb0a1d
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: fpsetround.c,v 1.6 2006/02/25 02:28:55 wiz Exp $       */
+
+/*
+ * Copyright (c) 1996 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Mark Brinicombe
+ *     for the NetBSD Project.
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetround.c,v 1.6 2006/02/25 02:28:55 wiz Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetround,_fpsetround)
+#endif
+
+/*
+ * Return the current FP rounding mode
+ *
+ * ok all we need to do is return the current FP rounding mode
+ *
+ * HOWEVER:
+ * The ARM FPA codes the rounding mode into the actual FP instructions
+ * so there is no such thing as a global rounding mode.
+ * The default is round to nearest if rounding is not explicitly specified.
+ * FP instructions generated by GCC will not explicitly specify a rounding
+ * mode.
+ *
+ * All we can do is abort if they ask for anything else.
+ */
+
+fp_rnd
+fpsetround(fp_rnd rnd_dir)
+{
+
+       if (rnd_dir != FP_RN)
+               abort();
+       return (FP_RN);
+}
diff --git a/lib/nbsd_libc/arch/arm/hardfloat/fpsetsticky.S b/lib/nbsd_libc/arch/arm/hardfloat/fpsetsticky.S
new file mode 100644 (file)
index 0000000..dd81e89
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: fpsetsticky.S,v 1.4 2004/08/21 11:21:00 rearnsha Exp $ */
+
+/*
+ * Copyright (c) 1996 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe
+ *     for the NetBSD project.
+ * 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 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 <machine/asm.h>
+
+/*
+ * Set the current FP cumulative flags
+ */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpsetsticky, _fpsetsticky)
+ENTRY(_fpsetsticky)
+#else
+ENTRY(fpsetsticky)
+#endif
+       rfs     r1
+       bic     r1, r1, #0x1f
+       and     r0, r0, #0x1f
+       orr     r0, r1, r0
+       wfs     r0
+       mov     r0, r1                  /* Return old mask */
+       RET
diff --git a/lib/nbsd_libc/arch/arm/net/Makefile.inc b/lib/nbsd_libc/arch/arm/net/Makefile.inc
new file mode 100644 (file)
index 0000000..10fabd3
--- /dev/null
@@ -0,0 +1,4 @@
+# $NetBSD: Makefile.inc,v 1.1 2000/12/29 20:13:53 bjh21 Exp $
+
+# hton* and nto* functions provided by ../gen/byte_swap_*.S
+SRCS+= 
diff --git a/lib/nbsd_libc/arch/arm/softfloat/arm-gcc.h b/lib/nbsd_libc/arch/arm/softfloat/arm-gcc.h
new file mode 100644 (file)
index 0000000..c92086a
--- /dev/null
@@ -0,0 +1,100 @@
+/* $NetBSD: arm-gcc.h,v 1.3 2005/12/24 21:11:16 perry Exp $ */
+
+/*
+-------------------------------------------------------------------------------
+One of the macros `BIGENDIAN' or `LITTLEENDIAN' must be defined.
+-------------------------------------------------------------------------------
+*/
+#ifdef __ARMEB__
+#define BIGENDIAN
+#else
+#define LITTLEENDIAN
+#endif
+
+/*
+-------------------------------------------------------------------------------
+The macro `BITS64' can be defined to indicate that 64-bit integer types are
+supported by the compiler.
+-------------------------------------------------------------------------------
+*/
+#define BITS64
+
+/*
+-------------------------------------------------------------------------------
+Each of the following `typedef's defines the most convenient type that holds
+integers of at least as many bits as specified.  For example, `uint8' should
+be the most convenient type that can hold unsigned integers of as many as
+8 bits.  The `flag' type must be able to hold either a 0 or 1.  For most
+implementations of C, `flag', `uint8', and `int8' should all be `typedef'ed
+to the same as `int'.
+-------------------------------------------------------------------------------
+*/
+typedef int flag;
+typedef int uint8;
+typedef int int8;
+typedef int uint16;
+typedef int int16;
+typedef unsigned int uint32;
+typedef signed int int32;
+#ifdef BITS64
+typedef unsigned long long int uint64;
+typedef signed long long int int64;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Each of the following `typedef's defines a type that holds integers
+of _exactly_ the number of bits specified.  For instance, for most
+implementation of C, `bits16' and `sbits16' should be `typedef'ed to
+`unsigned short int' and `signed short int' (or `short int'), respectively.
+-------------------------------------------------------------------------------
+*/
+typedef unsigned char bits8;
+typedef signed char sbits8;
+typedef unsigned short int bits16;
+typedef signed short int sbits16;
+typedef unsigned int bits32;
+typedef signed int sbits32;
+#ifdef BITS64
+typedef unsigned long long int bits64;
+typedef signed long long int sbits64;
+#endif
+
+#ifdef BITS64
+/*
+-------------------------------------------------------------------------------
+The `LIT64' macro takes as its argument a textual integer literal and
+if necessary ``marks'' the literal as having a 64-bit integer type.
+For example, the GNU C Compiler (`gcc') requires that 64-bit literals be
+appended with the letters `LL' standing for `long long', which is `gcc's
+name for the 64-bit integer type.  Some compilers may allow `LIT64' to be
+defined as the identity macro:  `#define LIT64( a ) a'.
+-------------------------------------------------------------------------------
+*/
+#define LIT64( a ) a##LL
+#endif
+
+/*
+-------------------------------------------------------------------------------
+The macro `INLINE' can be used before functions that should be inlined.  If
+a compiler does not support explicit inlining, this macro should be defined
+to be `static'.
+-------------------------------------------------------------------------------
+*/
+#define INLINE static inline
+
+/*
+-------------------------------------------------------------------------------
+The ARM FPA is odd in that it stores doubles high-order word first, no matter
+what the endianness of the CPU.  VFP is sane.
+-------------------------------------------------------------------------------
+*/
+#if defined(SOFTFLOAT_FOR_GCC)
+#if defined(__VFP_FP__) || defined(__ARMEB__)
+#define FLOAT64_DEMANGLE(a)    (a)
+#define FLOAT64_MANGLE(a)      (a)
+#else
+#define FLOAT64_DEMANGLE(a)    (((a) << 32) | ((a) >> 32))
+#define FLOAT64_MANGLE(a)      FLOAT64_DEMANGLE(a)
+#endif
+#endif
diff --git a/lib/nbsd_libc/arch/arm/softfloat/milieu.h b/lib/nbsd_libc/arch/arm/softfloat/milieu.h
new file mode 100644 (file)
index 0000000..a3f829c
--- /dev/null
@@ -0,0 +1,48 @@
+/* $NetBSD: milieu.h,v 1.1 2000/12/29 20:13:54 bjh21 Exp $ */
+
+/*
+===============================================================================
+
+This C header file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+Include common integer types and flags.
+-------------------------------------------------------------------------------
+*/
+#include "arm-gcc.h"
+
+/*
+-------------------------------------------------------------------------------
+Symbolic Boolean literals.
+-------------------------------------------------------------------------------
+*/
+enum {
+    FALSE = 0,
+    TRUE  = 1
+};
diff --git a/lib/nbsd_libc/arch/arm/softfloat/softfloat.h b/lib/nbsd_libc/arch/arm/softfloat/softfloat.h
new file mode 100644 (file)
index 0000000..f424abe
--- /dev/null
@@ -0,0 +1,314 @@
+/*     $NetBSD: softfloat.h,v 1.7 2006/05/16 20:55:51 mrg Exp $        */
+
+/* This is a derivative work. */
+
+/*
+===============================================================================
+
+This C header file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+The macro `FLOATX80' must be defined to enable the extended double-precision
+floating-point format `floatx80'.  If this macro is not defined, the
+`floatx80' type will not be defined, and none of the functions that either
+input or output the `floatx80' type will be defined.  The same applies to
+the `FLOAT128' macro and the quadruple-precision format `float128'.
+-------------------------------------------------------------------------------
+*/
+/* #define FLOATX80 */
+/* #define FLOAT128 */
+
+#include <machine/ieeefp.h>
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point types.
+-------------------------------------------------------------------------------
+*/
+typedef unsigned int float32;
+typedef unsigned long long float64;
+#ifdef FLOATX80
+typedef struct {
+    unsigned short high;
+    unsigned long long low;
+} floatx80;
+#endif
+#ifdef FLOAT128
+typedef struct {
+    unsigned long long high, low;
+} float128;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point underflow tininess-detection mode.
+-------------------------------------------------------------------------------
+*/
+#ifndef SOFTFLOAT_FOR_GCC
+extern int float_detect_tininess;
+#endif
+enum {
+    float_tininess_after_rounding  = 0,
+    float_tininess_before_rounding = 1
+};
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point rounding mode.
+-------------------------------------------------------------------------------
+*/
+extern fp_rnd float_rounding_mode;
+enum {
+    float_round_nearest_even = FP_RN,
+    float_round_to_zero      = FP_RZ,
+    float_round_down         = FP_RM,
+    float_round_up           = FP_RP
+};
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point exception flags.
+-------------------------------------------------------------------------------
+*/
+extern fp_except float_exception_flags;
+extern fp_except float_exception_mask;
+enum {
+    float_flag_inexact   = FP_X_IMP,
+    float_flag_underflow = FP_X_UFL,
+    float_flag_overflow  = FP_X_OFL,
+    float_flag_divbyzero = FP_X_DZ,
+    float_flag_invalid   = FP_X_INV
+};
+
+/*
+-------------------------------------------------------------------------------
+Routine to raise any or all of the software IEC/IEEE floating-point
+exception flags.
+-------------------------------------------------------------------------------
+*/
+void float_raise( fp_except );
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE integer-to-floating-point conversion routines.
+-------------------------------------------------------------------------------
+*/
+float32 int32_to_float32( int );
+float64 int32_to_float64( int );
+#ifdef FLOATX80
+floatx80 int32_to_floatx80( int );
+#endif
+#ifdef FLOAT128
+float128 int32_to_float128( int );
+#endif
+#ifndef SOFTFLOAT_FOR_GCC /* __floatdi?f is in libgcc2.c */
+float32 int64_to_float32( long long );
+float64 int64_to_float64( long long );
+#ifdef FLOATX80
+floatx80 int64_to_floatx80( long long );
+#endif
+#ifdef FLOAT128
+float128 int64_to_float128( long long );
+#endif
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE single-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float32_to_int32( float32 );
+int float32_to_int32_round_to_zero( float32 );
+#if defined(SOFTFLOAT_FOR_GCC) && defined(SOFTFLOAT_NEED_FIXUNS)
+unsigned int float32_to_uint32_round_to_zero( float32 );
+#endif
+#ifndef SOFTFLOAT_FOR_GCC /* __fix?fdi provided by libgcc2.c */
+long long float32_to_int64( float32 );
+long long float32_to_int64_round_to_zero( float32 );
+#endif
+float64 float32_to_float64( float32 );
+#ifdef FLOATX80
+floatx80 float32_to_floatx80( float32 );
+#endif
+#ifdef FLOAT128
+float128 float32_to_float128( float32 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE single-precision operations.
+-------------------------------------------------------------------------------
+*/
+float32 float32_round_to_int( float32 );
+float32 float32_add( float32, float32 );
+float32 float32_sub( float32, float32 );
+float32 float32_mul( float32, float32 );
+float32 float32_div( float32, float32 );
+float32 float32_rem( float32, float32 );
+float32 float32_sqrt( float32 );
+int float32_eq( float32, float32 );
+int float32_le( float32, float32 );
+int float32_lt( float32, float32 );
+int float32_eq_signaling( float32, float32 );
+int float32_le_quiet( float32, float32 );
+int float32_lt_quiet( float32, float32 );
+#ifndef SOFTFLOAT_FOR_GCC
+int float32_is_signaling_nan( float32 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE double-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float64_to_int32( float64 );
+int float64_to_int32_round_to_zero( float64 );
+#if defined(SOFTFLOAT_FOR_GCC) && defined(SOFTFLOAT_NEED_FIXUNS)
+unsigned int float64_to_uint32_round_to_zero( float64 );
+#endif
+#ifndef SOFTFLOAT_FOR_GCC /* __fix?fdi provided by libgcc2.c */
+long long float64_to_int64( float64 );
+long long float64_to_int64_round_to_zero( float64 );
+#endif
+float32 float64_to_float32( float64 );
+#ifdef FLOATX80
+floatx80 float64_to_floatx80( float64 );
+#endif
+#ifdef FLOAT128
+float128 float64_to_float128( float64 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE double-precision operations.
+-------------------------------------------------------------------------------
+*/
+float64 float64_round_to_int( float64 );
+float64 float64_add( float64, float64 );
+float64 float64_sub( float64, float64 );
+float64 float64_mul( float64, float64 );
+float64 float64_div( float64, float64 );
+float64 float64_rem( float64, float64 );
+float64 float64_sqrt( float64 );
+int float64_eq( float64, float64 );
+int float64_le( float64, float64 );
+int float64_lt( float64, float64 );
+int float64_eq_signaling( float64, float64 );
+int float64_le_quiet( float64, float64 );
+int float64_lt_quiet( float64, float64 );
+#ifndef SOFTFLOAT_FOR_GCC
+int float64_is_signaling_nan( float64 );
+#endif
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int floatx80_to_int32( floatx80 );
+int floatx80_to_int32_round_to_zero( floatx80 );
+long long floatx80_to_int64( floatx80 );
+long long floatx80_to_int64_round_to_zero( floatx80 );
+float32 floatx80_to_float32( floatx80 );
+float64 floatx80_to_float64( floatx80 );
+#ifdef FLOAT128
+float128 floatx80_to_float128( floatx80 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision rounding precision.  Valid
+values are 32, 64, and 80.
+-------------------------------------------------------------------------------
+*/
+extern int floatx80_rounding_precision;
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision operations.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_round_to_int( floatx80 );
+floatx80 floatx80_add( floatx80, floatx80 );
+floatx80 floatx80_sub( floatx80, floatx80 );
+floatx80 floatx80_mul( floatx80, floatx80 );
+floatx80 floatx80_div( floatx80, floatx80 );
+floatx80 floatx80_rem( floatx80, floatx80 );
+floatx80 floatx80_sqrt( floatx80 );
+int floatx80_eq( floatx80, floatx80 );
+int floatx80_le( floatx80, floatx80 );
+int floatx80_lt( floatx80, floatx80 );
+int floatx80_eq_signaling( floatx80, floatx80 );
+int floatx80_le_quiet( floatx80, floatx80 );
+int floatx80_lt_quiet( floatx80, floatx80 );
+int floatx80_is_signaling_nan( floatx80 );
+
+#endif
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE quadruple-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float128_to_int32( float128 );
+int float128_to_int32_round_to_zero( float128 );
+long long float128_to_int64( float128 );
+long long float128_to_int64_round_to_zero( float128 );
+float32 float128_to_float32( float128 );
+float64 float128_to_float64( float128 );
+#ifdef FLOATX80
+floatx80 float128_to_floatx80( float128 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE quadruple-precision operations.
+-------------------------------------------------------------------------------
+*/
+float128 float128_round_to_int( float128 );
+float128 float128_add( float128, float128 );
+float128 float128_sub( float128, float128 );
+float128 float128_mul( float128, float128 );
+float128 float128_div( float128, float128 );
+float128 float128_rem( float128, float128 );
+float128 float128_sqrt( float128 );
+int float128_eq( float128, float128 );
+int float128_le( float128, float128 );
+int float128_lt( float128, float128 );
+int float128_eq_signaling( float128, float128 );
+int float128_le_quiet( float128, float128 );
+int float128_lt_quiet( float128, float128 );
+int float128_is_signaling_nan( float128 );
+
+#endif
+
diff --git a/lib/nbsd_libc/arch/arm/stdlib/Makefile.inc b/lib/nbsd_libc/arch/arm/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..d1dda02
--- /dev/null
@@ -0,0 +1 @@
+#      $NetBSD: Makefile.inc,v 1.4 2009/07/31 20:39:59 dsl Exp $
diff --git a/lib/nbsd_libc/arch/arm/string/Makefile.inc b/lib/nbsd_libc/arch/arm/string/Makefile.inc
new file mode 100644 (file)
index 0000000..ca90544
--- /dev/null
@@ -0,0 +1,5 @@
+# $NetBSD: Makefile.inc,v 1.8 2009/07/30 20:57:15 dsl Exp $
+
+SRCS+=  memcpy.S bcopy.S memmove.S memset.S bzero.S ffs.S strcmp.S
+SRCS+= strncmp.S memcmp.S
+
diff --git a/lib/nbsd_libc/arch/arm/string/bcopy.S b/lib/nbsd_libc/arch/arm/string/bcopy.S
new file mode 100644 (file)
index 0000000..71fb909
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: bcopy.S,v 1.3 2003/10/14 07:51:45 scw Exp $    */
+
+#define _BCOPY
+#include "memmove.S"
diff --git a/lib/nbsd_libc/arch/arm/string/bzero.S b/lib/nbsd_libc/arch/arm/string/bzero.S
new file mode 100644 (file)
index 0000000..1c9d390
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: bzero.S,v 1.4 2008/04/28 20:22:55 martin Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Neil A. Carson and Mark Brinicombe
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#define _BZERO
+#include "memset.S"
diff --git a/lib/nbsd_libc/arch/arm/sys/__clone.S b/lib/nbsd_libc/arch/arm/sys/__clone.S
new file mode 100644 (file)
index 0000000..f5b329a
--- /dev/null
@@ -0,0 +1,93 @@
+/* $NetBSD: __clone.S,v 1.6 2006/04/24 19:00:30 snj Exp $ */
+
+/*
+ * Copyright (c) 2001 Christopher Gilbert
+ * All rights reserved.
+ *
+ * 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 company nor the name of the author may be used to
+ *    endorse or promote products derived from this software without specific
+ *    prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 <machine/asm.h>
+#include <sys/errno.h>
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(clone, __clone)
+#endif
+
+/*
+ * int __clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+ENTRY(__clone)
+
+       /* test stack and function are not null */
+       teq     r0, #0x00
+       teqne   r1, #0x00
+       beq     .Leinval
+
+       /* place the func and its arg onto the child's stack */
+       stmfd   r1!, {r0, r3} 
+       
+       /* syscall expects (flags, stack) */
+       mov     r0, r2
+
+       SYSTRAP(__clone)
+       bcs     PIC_SYM(CERROR, PLT)
+
+       /*
+        * r1 and r0 are the same as from fork:
+        * r1 == 0 in parent process, r1 == 1 in child process.
+        * r0 == pid of child in parent, r0 == pid of parent in child.
+        */
+       teq     r1, #0x00
+
+       /* if this is the parent then just return the pid */
+       RETc(eq)
+       /*
+        * This is the child
+        * load the function and arg off the stack
+        */
+       ldmfd   sp!, {r1, r2}
+
+       /* setup return address */
+       add     lr, pc, #.Lreturnhere - . - 8
+
+       /* place arg in r0 */
+       mov     r0, r2
+
+       /* call the function */
+#ifdef _ARM_ARCH_4T
+       bx      r1
+#else
+       mov     pc, r1
+#endif
+
+.Lreturnhere:
+       /* call _exit with the returned value */
+       b       PIC_SYM(_C_LABEL(_exit), PLT)
+
+       /* NOTREACHED */
+
+       /* error handler if func or stack is NULL */
+.Leinval:
+       mov     R0, #EINVAL
+       b       PIC_SYM(CERROR, PLT)
diff --git a/lib/nbsd_libc/arch/arm/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/arm/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..615ebe8
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.7 2008/04/28 20:22:55 martin Exp $        */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigaction14_sigtramp.c,v 1.7 2008/04/28 20:22:55 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern const int __sigtramp_siginfo_2[];
+
+       /*
+        * If no sigaction, use the "default" trampoline since it won't
+        * be used.
+        */
+       if (act == NULL)
+               return  __sigaction_sigtramp(sig, act, oact, NULL, 0);
+
+#ifdef __LIBC12_SOURCE__
+       /*
+        * We select the non-SA_SIGINFO trampoline if SA_SIGINFO is not
+        * set in the sigaction.
+        */
+       if ((act->sa_flags & SA_SIGINFO) == 0) {
+               extern const int __sigtramp_sigcontext_1[];
+               int sav = errno;
+               int rv =  __sigaction_sigtramp(sig, act, oact,
+                   __sigtramp_sigcontext_1, 1);
+               if (rv >= 0 || errno != EINVAL)
+                       return rv;
+               errno = sav;
+       }
+#endif
+
+       /*
+        * If SA_SIGINFO was specificed or the compatibility trampolines
+        * can't be used, use the siginfo trampoline.
+        */
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_2, 2);
+}
diff --git a/lib/nbsd_libc/arch/arm/sys/__sigtramp2.S b/lib/nbsd_libc/arch/arm/sys/__sigtramp2.S
new file mode 100755 (executable)
index 0000000..4bc72f4
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: __sigtramp2.S,v 1.2 2008/04/28 20:22:55 martin Exp $   */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+/*
+ * The ARM signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ *
+ * On entry, the stack looks like:
+ *
+ *             ucontext structure
+ *     sp->    siginfo structure
+ * and  r5 points to the ucontext
+ */
+ENTRY_NP(__sigtramp_siginfo_2)
+       mov r0, r5                              /* set the arg         */
+       SYSTRAP(setcontext)                     /* and call setcontext */
+
+       /* If that failed, exit with the error code. */
+       SYSTRAP(exit)
diff --git a/lib/nbsd_libc/arch/arm/sys/__syscall.S b/lib/nbsd_libc/arch/arm/sys/__syscall.S
new file mode 100644 (file)
index 0000000..563aaad
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: __syscall.S,v 1.4 2003/08/07 16:42:03 agc Exp $        */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)syscall.s     5.1 (Berkeley) 4/23/90
+ */
+
+#include "SYS.h"
+
+RSYSCALL(__syscall)
diff --git a/lib/nbsd_libc/arch/arm/sys/__vfork14.S b/lib/nbsd_libc/arch/arm/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..f2710a9
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: __vfork14.S,v 1.7 2004/08/21 11:30:17 rearnsha Exp $   */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)Ovfork.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include "SYS.h"
+
+/*
+ * pid = vfork();
+ *
+ * On return from the SWI:
+ * r1 == 0 in parent process, r1 == 1 in child process.
+ * r0 == pid of child in parent, r0 == pid of parent in child.
+ */
+       .text
+       .align  0
+
+ENTRY(__vfork14)
+       mov     r2, r14
+       SYSTRAP(__vfork14)
+       bcs     PIC_SYM(CERROR, PLT)
+       mov     r14, r2
+       sub     r1, r1, #1      /* r1 == 0xffffffff if parent, 0 if child */
+       and     r0, r0, r1      /* r0 == 0 if child, else unchanged */
+       RET
diff --git a/lib/nbsd_libc/arch/arm/sys/brk.S b/lib/nbsd_libc/arch/arm/sys/brk.S
new file mode 100644 (file)
index 0000000..b5cbbd4
--- /dev/null
@@ -0,0 +1,98 @@
+/*     $NetBSD: brk.S,v 1.8 2004/08/21 11:30:17 rearnsha Exp $ */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)brk.s 5.2 (Berkeley) 12/17/90
+ */
+
+#include "SYS.h"
+
+       .globl  _C_LABEL(end)
+       .globl  CURBRK
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(brk, _brk)
+#endif
+
+       .data
+       .align  0
+       .globl  _C_LABEL(__minbrk)
+       .type   _C_LABEL(__minbrk),#object
+_C_LABEL(__minbrk):
+       .word   _C_LABEL(end)
+
+/*
+ * Change the data segment size
+ */
+ENTRY(_brk)
+#ifdef PIC
+       /* Setup the GOT */
+       ldr     r3, .Lgot
+       add     r3, pc, r3
+.L1:
+       ldr     r1, .Lminbrk
+       ldr     r1, [r3, r1]
+#else
+       ldr     r1, .Lminbrk
+#endif
+       /* Get the minimum allowable brk address */
+       ldr     r1, [r1]
+
+       /*
+        * Valid the address specified and set to the minimum
+        * if the address is below minbrk.
+        */
+       cmp     r0, r1
+       movcc   r0, r1
+       mov     r2, r0
+       SYSTRAP(break)
+       bcs     PIC_SYM(CERROR, PLT)
+
+#ifdef PIC
+       ldr     r1, .Lcurbrk
+       ldr     r1, [r3, r1]
+#else
+       ldr     r1, .Lcurbrk
+#endif
+       /* Store the new address in curbrk */
+       str     r2, [r1]
+
+       /* Return 0 for success */
+       mov     r0, #0x00000000
+       RET
+
+       .align  2
+#ifdef PIC
+.Lgot:
+       .word   _C_LABEL(_GLOBAL_OFFSET_TABLE_) + (. - (.L1+4))
+#endif
+.Lminbrk:
+       .word   PIC_SYM(_C_LABEL(__minbrk), GOT)
+.Lcurbrk:
+       .word   PIC_SYM(CURBRK, GOT)
diff --git a/lib/nbsd_libc/arch/arm/sys/cerror.S b/lib/nbsd_libc/arch/arm/sys/cerror.S
new file mode 100644 (file)
index 0000000..f05cd69
--- /dev/null
@@ -0,0 +1,75 @@
+/*     $NetBSD: cerror.S,v 1.7 2011/01/14 06:12:17 matt Exp $  */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)cerror.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include "SYS.h"
+
+#ifdef PIC
+       .hidden CERROR
+#endif
+
+ASENTRY(CERROR)
+#ifdef _REENTRANT
+       stmfd   sp!, {r4, lr}
+       mov     r4, r0
+       bl      PIC_SYM(_C_LABEL(__errno), PLT)
+       str     r4, [r0]
+       mvn     r0, #0x00000000
+       mvn     r1, #0x00000000
+       ldmfd   sp!, {r4, pc}
+#else
+#ifdef PIC
+       /* Setup the GOT */
+       ldr     r3, .Lgot
+       add     r3, pc, r3
+.L1:
+       ldr     r1, .Lerrno
+       ldr     r1, [r3, r1]
+#else
+       ldr     r1, .Lerrno
+#endif /* PIC */
+       str     r0, [r1]
+       mvn     r0, #0x00000000
+       mvn     r1, #0x00000000
+       RET
+
+#ifdef PIC
+       .align  0
+.Lgot:
+       .word   _C_LABEL(_GLOBAL_OFFSET_TABLE_) + (. - (.L1+4))
+#endif /* PIC */
+
+       .globl  _C_LABEL(errno)
+
+.Lerrno:
+       .word   PIC_SYM(_C_LABEL(errno), GOT)
+#endif /* _REENTRANT */
diff --git a/lib/nbsd_libc/arch/arm/sys/exect.S b/lib/nbsd_libc/arch/arm/sys/exect.S
new file mode 100644 (file)
index 0000000..07d9c5d
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: exect.S,v 1.4 2003/08/07 16:42:04 agc Exp $    */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)exect.s       5.1 (Berkeley) 4/23/90
+ */
+
+#include "SYS.h"
+
+PSEUDO(exect,execve)
diff --git a/lib/nbsd_libc/arch/arm/sys/fork.S b/lib/nbsd_libc/arch/arm/sys/fork.S
new file mode 100644 (file)
index 0000000..41dac49
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: fork.S,v 1.6 2004/08/21 11:30:17 rearnsha Exp $        */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)fork.s        5.1 (Berkeley) 4/23/90
+ */
+
+#include "SYS.h"
+
+/*
+ * pid = fork();
+ *
+ * On return from the SWI:
+ * r1 == 0 in parent process, r1 == 1 in child process.
+ * r0 == pid of child in parent, r0 == pid of parent in child.
+ */
+
+_SYSCALL(__fork,fork)
+       sub     r1, r1, #1      /* r1 == 0xffffffff if parent, 0 if child */
+       and     r0, r0, r1      /* r0 == 0 if child, else unchanged */
+       RET
diff --git a/lib/nbsd_libc/arch/arm/sys/getcontext.S b/lib/nbsd_libc/arch/arm/sys/getcontext.S
new file mode 100644 (file)
index 0000000..79ff1e6
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: getcontext.S,v 1.6 2008/04/28 20:22:55 martin Exp $    */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: getcontext.S,v 1.6 2008/04/28 20:22:55 martin Exp $")
+#endif /* SYSLIBC_SCCS && !lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext, _getcontext)
+#endif
+
+ENTRY(_getcontext)
+       mov     r2, r0                  /* Must save argument pointer. */
+       SYSTRAP (getcontext)
+       bcs     PIC_SYM(CERROR, PLT)
+       str     lr, [r2, #(36 + 15*4)]  /* Adjust PC. */
+#ifdef SOFTFLOAT
+       /* Ahem. */
+       /* Judging from the softfloat code we should at least save
+          the exception codes and rounding mode here. */
+#endif
+       mov     r0, #0
+       str     r0, [r2, #(36 + 0*4)]   /* Return 0. */
+       RET
diff --git a/lib/nbsd_libc/arch/arm/sys/pipe.S b/lib/nbsd_libc/arch/arm/sys/pipe.S
new file mode 100644 (file)
index 0000000..8dc1492
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: pipe.S,v 1.6 2004/08/21 11:30:17 rearnsha Exp $        */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)pipe.s        5.1 (Berkeley) 4/23/90
+ */
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe, _pipe)
+#endif
+
+ENTRY(_pipe)
+       mov     r2, r0
+       SYSTRAP(pipe)
+       bcs     PIC_SYM(CERROR, PLT)
+       str     r0, [r2, #0x0000]
+       str     r1, [r2, #0x0004]
+       mov     r0, #0x00000000
+       RET
diff --git a/lib/nbsd_libc/arch/arm/sys/ptrace.S b/lib/nbsd_libc/arch/arm/sys/ptrace.S
new file mode 100644 (file)
index 0000000..1a91c0d
--- /dev/null
@@ -0,0 +1,75 @@
+/*     $NetBSD: ptrace.S,v 1.8 2004/08/21 11:30:17 rearnsha Exp $ */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)ptrace.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include "SYS.h"
+
+ENTRY(ptrace)
+#ifdef _REENTRANT
+       stmfd   sp!, {r0-r3, lr}
+       sub     sp, sp, #4      /* align stack */
+       bl      PIC_SYM(_C_LABEL(__errno), PLT)
+       add     sp, sp, #4      /* unalign stack */
+       mov     r1, #0x00000000
+       str     r1, [r0]
+       ldmfd   sp!, {r0-r3, lr}
+#else
+       stmfd   sp!, {r0, r1}
+#ifdef PIC
+       /* Setup the GOT */
+       ldr     r0, .Lgot
+       add     r0, pc, r0
+.L1:
+       ldr     r1, .Lerrno
+       ldr     r1, [r0, r1]
+#else
+       ldr     r1, .Lerrno
+#endif /* PIC */
+       mov     r0, #0x00000000
+       str     r0, [r1]
+       ldmfd   sp!, {r0, r1}
+#endif /* _REENTRANT */
+
+       SYSTRAP(ptrace)
+       bcs     PIC_SYM(CERROR, PLT)
+       RET
+
+#ifndef _REENTRANT
+#ifdef PIC
+       .align  0
+.Lgot:
+       .word   _C_LABEL(_GLOBAL_OFFSET_TABLE_) + (. - (.L1+4))
+#endif /* PIC */
+
+.Lerrno:
+       .word   PIC_SYM(_C_LABEL(errno), GOT)
+#endif /* !_REENTRANT */
diff --git a/lib/nbsd_libc/arch/arm/sys/sbrk.S b/lib/nbsd_libc/arch/arm/sys/sbrk.S
new file mode 100644 (file)
index 0000000..6ad1619
--- /dev/null
@@ -0,0 +1,86 @@
+/*     $NetBSD: sbrk.S,v 1.8 2004/08/21 11:30:17 rearnsha Exp $        */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)sbrk.s        5.1 (Berkeley) 4/23/90
+ */
+
+#include "SYS.h"
+
+       .globl  _C_LABEL(end)
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(sbrk, _sbrk)
+#endif
+
+       .data
+       .align  0
+       .globl  CURBRK
+       .type   CURBRK,#object
+CURBRK:
+       .word   _C_LABEL(end)
+
+/*
+ * Change the data segment size
+ */
+ENTRY(_sbrk)
+#ifdef PIC
+       /* Setup the GOT */
+       ldr     r3, .Lgot
+       add     r3, pc, r3
+.L1:
+       ldr     r2, .Lcurbrk
+       ldr     r2, [r3, r2]
+#else
+       ldr     r2, .Lcurbrk
+#endif
+       /* Get the current brk address */
+       ldr     r1, [r2]
+
+       /* Calculate new value */
+       mov     r3, r0
+       add     r0, r0, r1
+       SYSTRAP(break)
+       bcs     PIC_SYM(CERROR, PLT)
+
+       /* Store new curbrk value */
+       ldr     r0, [r2]
+       add     r1, r0, r3
+       str     r1, [r2]
+
+       /* Return old curbrk value */
+       RET
+
+       .align  0
+#ifdef PIC
+.Lgot:
+       .word   _C_LABEL(_GLOBAL_OFFSET_TABLE_) + (. - (.L1+4))
+#endif
+.Lcurbrk:
+       .word   PIC_SYM(CURBRK, GOT)
diff --git a/lib/nbsd_libc/arch/arm/sys/shmat.S b/lib/nbsd_libc/arch/arm/sys/shmat.S
new file mode 100644 (file)
index 0000000..13bdd0d
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: shmat.S,v 1.1 2000/12/29 20:14:04 bjh21 Exp $  */
+
+#include "SYS.h"
+
+RSYSCALL(shmat)
diff --git a/lib/nbsd_libc/arch/arm/sys/syscall.S b/lib/nbsd_libc/arch/arm/sys/syscall.S
new file mode 100644 (file)
index 0000000..43c8261
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: syscall.S,v 1.4 2003/08/07 16:42:05 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)syscall.s     5.1 (Berkeley) 4/23/90
+ */
+
+#include "SYS.h"
+
+RSYSCALL(syscall)
diff --git a/lib/nbsd_libc/arch/hppa/DEFS.h b/lib/nbsd_libc/arch/hppa/DEFS.h
new file mode 100644 (file)
index 0000000..6e01259
--- /dev/null
@@ -0,0 +1,3 @@
+/*     $NetBSD: DEFS.h,v 1.1 2002/06/06 20:31:20 fredette Exp $        */
+
+#include <machine/asm.h>
diff --git a/lib/nbsd_libc/arch/hppa/Makefile.inc b/lib/nbsd_libc/arch/hppa/Makefile.inc
new file mode 100644 (file)
index 0000000..432cdb2
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.9 2009/10/21 19:30:46 skrll Exp $
+
+#      $OpenBSD: Makefile.inc,v 1.3 1999/12/25 06:02:10 mickey Exp $
+
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S
+
+SRCS+= bcopy.c
diff --git a/lib/nbsd_libc/arch/hppa/SYS.h b/lib/nbsd_libc/arch/hppa/SYS.h
new file mode 100644 (file)
index 0000000..5e50844
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: SYS.h,v 1.7 2009/11/03 05:07:25 snj Exp $      */
+
+/*     $OpenBSD: SYS.h,v 1.9 2001/09/20 20:52:09 millert Exp $ */
+
+/*
+ * Copyright (c) 1998-2002 Michael Shalayeff
+ * 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 ``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 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 MIND
+ * 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 <sys/syscall.h>
+#include <machine/asm.h>
+#include <machine/vmparam.h>
+#undef _LOCORE
+#define _LOCORE
+#include <machine/frame.h>
+
+#define        SYSENTRY(x)     LEAF_ENTRY(x)
+#define        SYSEXIT(x)      EXIT(x)
+
+#define        SYSCALL(x)                              !\
+       stw     %rp, HPPA_FRAME_ERP(%sr0,%sp)   !\
+       ldil    L%SYSCALLGATE, %r1              !\
+       ble     4(%sr7, %r1)                    !\
+       ldi     __CONCAT(SYS_,x), %t1           !\
+       .import __cerror, code                  !\
+       comb,<> %r0, %t1, __cerror              !\
+       ldw     HPPA_FRAME_ERP(%sr0,%sp), %rp   
+
+#define        PSEUDO(x,y)                             !\
+SYSENTRY(x)                                    !\
+       SYSCALL(y)                              !\
+       bv      %r0(%rp)                        !\
+       nop                                     !\
+SYSEXIT(x)
+
+#define        PSEUDO_NOERROR(x,y)                     !\
+SYSENTRY(x)                                    !\
+       stw     %rp, HPPA_FRAME_ERP(%sr0,%sp)   !\
+       ldil    L%SYSCALLGATE, %r1              !\
+       ble     4(%sr7, %r1)                    !\
+       ldi     __CONCAT(SYS_,y), %t1           !\
+       ldw     HPPA_FRAME_ERP(%sr0,%sp), %rp   !\
+       bv      %r0(%rp)                        !\
+       nop                                     !\
+SYSEXIT(x)
+
+#define RSYSCALL(x)            PSEUDO(x,x)
+#define        RSYSCALL_NOERROR(x)     PSEUDO_NOERROR(x,x)     
+
+#ifdef WEAK_ALIAS
+#define WSYSCALL(weak,strong)          !\
+       WEAK_ALIAS(weak,strong)         !\
+       PSEUDO(strong,weak)
+#else
+#define WSYSCALL(weak,strong)          !\
+       PSEUDO(weak,weak)
+#endif
diff --git a/lib/nbsd_libc/arch/hppa/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/hppa/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..1d786e0
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/15 17:35:18 kleink Exp $
+
+SRCS+= strtof.c
diff --git a/lib/nbsd_libc/arch/hppa/gdtoa/arith.h b/lib/nbsd_libc/arch/hppa/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..4674f62
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: arith.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define IEEE_BIG_ENDIAN
diff --git a/lib/nbsd_libc/arch/hppa/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/hppa/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..b9e91e7
--- /dev/null
@@ -0,0 +1,11 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define f_QNAN 0x7fa00000
+#define d_QNAN0 0x7ff40000
+#define d_QNAN1 0x0
+#ifdef _LP64
+#define ld_QNAN0 0x7fff4000
+#define ld_QNAN1 0x0
+#define ld_QNAN2 0x0
+#define ld_QNAN3 0x0
+#endif
diff --git a/lib/nbsd_libc/arch/hppa/gen/Makefile.inc b/lib/nbsd_libc/arch/hppa/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..24ab0e5
--- /dev/null
@@ -0,0 +1,20 @@
+#      $NetBSD: Makefile.inc,v 1.15 2006/06/28 14:46:32 drochner Exp $
+
+SRCS+= bswap16.c bswap32.c bswap64.c
+SRCS+= fabs.c
+SRCS+= __sigsetjmp14.S __setjmp14.S _setjmp.S __longjmp14.c
+
+# Common ieee754 constants and functions
+SRCS+= infinityf_ieee754.c infinity_ieee754.c infinityl_dbl_ieee754.c
+SRCS+= fpclassifyf_ieee754.c fpclassifyd_ieee754.c
+SRCS+= isfinitef_ieee754.c isfinited_ieee754.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c
+SRCS+= signbitf_ieee754.c signbitd_ieee754.c
+
+SRCS+= nanf.c
+
+SRCS+= makecontext.c resumecontext.c _resumecontext.S swapcontext.S _lwp.c
+
+SRCS+= flt_rounds.c fpgetmask.c fpgetround.c fpgetsticky.c fpsetmask.c \
+       fpsetround.c fpsetsticky.c
diff --git a/lib/nbsd_libc/arch/hppa/gen/__longjmp14.c b/lib/nbsd_libc/arch/hppa/gen/__longjmp14.c
new file mode 100644 (file)
index 0000000..bb14fd6
--- /dev/null
@@ -0,0 +1,118 @@
+/*     $NetBSD: __longjmp14.c,v 1.4 2008/04/28 20:22:55 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christian Limpach.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define __LIBC12_SOURCE__
+#include <setjmp.h>
+#include <compat/include/setjmp.h>
+
+#include <stdio.h>
+#include <unistd.h>
+
+ssize_t _sys_write(int, void *, size_t);
+
+void
+__longjmp14(jmp_buf env, int val)
+{
+       ucontext_t uc;
+       struct sigcontext *sc = (void *)env;
+       register_t *regs = (void *)(sc + 1);
+       register register_t dp __asm("r27");
+
+       /* Ensure non-zero SP */
+       if (sc->sc_sp == 0)
+               goto err;
+
+       /* Make return value non-zero */
+       if (val == 0)
+               val = 1;
+
+       /* Copy callee-saved regs */
+       regs -= 3;
+       uc.uc_mcontext.__gregs[3] = regs[3];
+       uc.uc_mcontext.__gregs[4] = regs[4];
+       uc.uc_mcontext.__gregs[5] = regs[5];
+       uc.uc_mcontext.__gregs[6] = regs[6];
+       uc.uc_mcontext.__gregs[7] = regs[7];
+       uc.uc_mcontext.__gregs[8] = regs[8];
+       uc.uc_mcontext.__gregs[9] = regs[9];
+       uc.uc_mcontext.__gregs[10] = regs[10];
+       uc.uc_mcontext.__gregs[11] = regs[11];
+       uc.uc_mcontext.__gregs[12] = regs[12];
+       uc.uc_mcontext.__gregs[13] = regs[13];
+       uc.uc_mcontext.__gregs[14] = regs[14];
+       uc.uc_mcontext.__gregs[15] = regs[15];
+       uc.uc_mcontext.__gregs[16] = regs[16];
+       uc.uc_mcontext.__gregs[17] = regs[17];
+       uc.uc_mcontext.__gregs[18] = regs[18];
+
+       /* Preserve the current value of DP */
+       uc.uc_mcontext.__gregs[27] = dp;
+
+       /* Set the desired return value. */
+       uc.uc_mcontext.__gregs[_REG_RET0] = val;
+
+       /*
+        * Set _UC_{SET,CLR}STACK according to SS_ONSTACK.
+        *
+        * Restore the signal mask with sigprocmask() instead of _UC_SIGMASK,
+        * since libpthread may want to interpose on signal handling.
+        */
+       uc.uc_flags = _UC_CPU | (sc->sc_onstack ? _UC_SETSTACK : _UC_CLRSTACK);
+
+       sigprocmask(SIG_SETMASK, &sc->sc_mask, NULL);
+
+       /* Clear uc_link */
+       uc.uc_link = 0;
+
+       /* Copy signal mask */
+       uc.uc_sigmask = sc->sc_mask;
+
+       /* Copy special regs */
+       uc.uc_mcontext.__gregs[_REG_PSW] = sc->sc_ps;
+       uc.uc_mcontext.__gregs[_REG_SP] = sc->sc_sp;
+       uc.uc_mcontext.__gregs[_REG_PCSQH] = sc->sc_pcsqh;
+       uc.uc_mcontext.__gregs[_REG_PCOQH] = sc->sc_pcoqh;
+       uc.uc_mcontext.__gregs[_REG_PCSQT] = sc->sc_pcsqt;
+       uc.uc_mcontext.__gregs[_REG_PCOQT] = sc->sc_pcoqt;
+
+       setcontext(&uc);
+ err:
+       longjmperror();
+       abort();
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/hppa/gen/__setjmp14.S b/lib/nbsd_libc/arch/hppa/gen/__setjmp14.S
new file mode 100644 (file)
index 0000000..4777b21
--- /dev/null
@@ -0,0 +1,131 @@
+/*     $NetBSD: __setjmp14.S,v 1.5 2008/04/28 20:22:55 martin Exp $    */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matthew Fredette.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+/* XXX fredette - this is awful */
+#define _LOCORE
+#include <machine/frame.h>
+#undef _LOCORE
+#include <machine/psl.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __setjmp14.S,v 1.5 2008/04/28 20:22:55 martin Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and a struct sigcontext, see <signal.h>
+ */
+
+ENTRY(__setjmp14,0)
+       /* Finish our stack frame. */
+       stw     %rp, HPPA_FRAME_CRP(%sp)
+       stw     %arg0, HPPA_FRAME_ARG(0)(%sp)
+
+       /* A sigcontext is at the beginning of our jmp_buf. */
+       stw     %r0, 4(%arg0)           ; unused word (old style signal mask)
+       stw     %sp, 8(%arg0)           ; sc.sc_sp = %sp
+       stw     %r0, 16(%arg0)          ; sc.sc_ap = NULL
+       mfsp    %sr0, %r1
+       stw     %r1, 20(%arg0)          ; sc.sc_pcsqh = %sr0
+       stw     %rp, 24(%arg0)          ; sc.sc_pcoqh = %rp
+       stw     %r1, 28(%arg0)          ; sc.sc_pcsqh = %sr0
+       ldo     4(%rp), %r1
+       stw     %r1, 32(%arg0)          ; sc.sc_pcoqt = %rp + 4
+#define PSW_MBS (PSW_C|PSW_Q|PSW_P|PSW_D|PSW_I)
+       ldil    L%PSW_MBS, %r1
+       ldo     R%PSW_MBS(%r1), %r1
+       stw     %r1, 36(%arg0)          ; set sc.sc_ps
+
+       /* We store all callee-saved registers after the sigcontext. */
+       ldo     56(%arg0), %r1
+       stwm    %r3, 4(%r1)
+       stwm    %r4, 4(%r1)
+       stwm    %r5, 4(%r1)
+       stwm    %r6, 4(%r1)
+       stwm    %r7, 4(%r1)
+       stwm    %r8, 4(%r1)
+       stwm    %r9, 4(%r1)
+       stwm    %r10, 4(%r1)
+       stwm    %r11, 4(%r1)
+       stwm    %r12, 4(%r1)
+       stwm    %r13, 4(%r1)
+       stwm    %r14, 4(%r1)
+       stwm    %r15, 4(%r1)
+       stwm    %r16, 4(%r1)
+       stwm    %r17, 4(%r1)
+       stwm    %r18, 4(%r1)
+
+       /*
+        * Start the stack frame for the calls we will make.
+        * The minimum frame is 48 bytes, but the stack must
+        * always be 64-byte aligned; we use the top 4 bytes
+        * to save our caller's %r3, and the following 12 bytes
+        * as the stack_t for our sigaltstack call.
+        * XXX - this assumes that sizeof(stack_t) <= 12
+        */
+       copy    %r3, %r1
+       copy    %sp, %r3
+       stwm    %r1, HPPA_FRAME_SIZE(%sp)
+
+       /* Get signal stack info. */
+       ldo     4(%r3), %arg1           ; set up oss
+       bl      __sigaltstack14, %rp
+       copy    %r0, %arg0              ; set up ss
+
+       /* Recover our jmp_buf and extract SS_ONSTACK */
+       ldw     HPPA_FRAME_ARG(0)(%r3), %arg0
+       ldw     12(%r3), %r1            ; get ss_flags
+       ldi     1, %r20                 ; SS_ONSTACK
+       and     %r1, %r20, %r1
+       stw     %r1, 0(%arg0)           ; sc.sc_onstack
+       
+       /* Get the signal mask. */
+       ldo     40(%arg0), %arg2        ; oset = &sc.sc_mask    
+       copy    %r0, %arg1              ; set = NULL
+       bl      __sigprocmask14, %rp
+       copy    %r0, %arg0              ; action = 0 <ignored>
+
+       /* Return 0. */
+       ldo     HPPA_FRAME_SIZE(%r3),%sp
+       ldwm    -HPPA_FRAME_SIZE(%sp),%r3
+       ldw     HPPA_FRAME_CRP(%sp), %rp
+       bv      %r0(%rp)
+       copy    %r0, %ret0
+EXIT(__setjmp14)
+
+       .end
diff --git a/lib/nbsd_libc/arch/hppa/gen/__sigsetjmp14.S b/lib/nbsd_libc/arch/hppa/gen/__sigsetjmp14.S
new file mode 100644 (file)
index 0000000..6e1f154
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: __sigsetjmp14.S,v 1.2 2008/04/28 20:22:55 martin Exp $ */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matthew Fredette.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __sigsetjmp14.S,v 1.2 2008/04/28 20:22:55 martin Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- sigsetjmp, siglongjmp
+ *
+ *     siglongjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     sigsetjmp(a,m)
+ * by restoring registers from the stack,
+ * The previous signal state is restored if 'm' was non-zero.
+ */
+
+/* grab _JBLEN */
+#include <machine/setjmp.h>
+
+ENTRY(__sigsetjmp14,0)
+       stw     %arg1, (_JBLEN * 4)(%arg0)      ; save mask at end of area
+       add,<>  %r0, %arg0, %r0
+       b,n     _setjmp
+       b,n     __setjmp14
+EXIT(__sigsetjmp14)
+
+
+ENTRY(__siglongjmp14,0)
+       ldw     (_JBLEN * 4)(%arg0), %r1
+       add,<>  %r0, %r1, %r0
+       b,n     _longjmp
+       b,n     __longjmp14
+EXIT(__siglongjmp14)
+
+       .end
diff --git a/lib/nbsd_libc/arch/hppa/gen/_lwp.c b/lib/nbsd_libc/arch/hppa/gen/_lwp.c
new file mode 100644 (file)
index 0000000..4e8cc16
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: _lwp.c,v 1.4 2010/01/07 12:31:10 skrll Exp $   */
+
+/*
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Wayne Knowles
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.4 2010/01/07 12:31:10 skrll Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+#include <machine/frame.h>
+
+void
+_lwp_makecontext(ucontext_t *u, void (*start)(void *),
+       void *arg, void *private, caddr_t stack_base, size_t stack_size)
+{
+       caddr_t sp;
+       __greg_t *gr;
+       __greg_t *gp;
+       __greg_t fp;
+
+       getcontext(u);
+       gr = u->uc_mcontext.__gregs;
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+       sp = stack_base + HPPA_FRAME_SIZE;
+
+       fp = (__greg_t)start;
+       if (fp & 2) {
+               gp = (__greg_t *)(fp & ~3);
+               fp = gp[0];
+               gr[_REG_R19] = gp[1];
+       }
+       gr[_REG_PCOQH] = fp | HPPA_PC_PRIV_USER;
+       gr[_REG_PCOQT] = (fp + 4) | HPPA_PC_PRIV_USER;
+       gr[_REG_RP] = (__greg_t) _lwp_exit;
+       gr[_REG_ARG0] = (__greg_t) arg;
+       gr[_REG_SP] = (__greg_t) sp;
+}
diff --git a/lib/nbsd_libc/arch/hppa/gen/_resumecontext.S b/lib/nbsd_libc/arch/hppa/gen/_resumecontext.S
new file mode 100644 (file)
index 0000000..5bf827a
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: _resumecontext.S,v 1.3 2008/04/28 20:22:56 martin Exp $        */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Wayne Knowles.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#include <machine/asm.h>
+#include <machine/mcontext.h>
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: _resumecontext.S,v 1.3 2008/04/28 20:22:56 martin Exp $")
+#endif /* SYSLIBC_SCCS && !lint */
+
+       .import _resumecontext, code
+
+LEAF_ENTRY_NOPROFILE(__resumecontext)
+#ifdef PIC
+       ldw     HPPA_FRAME_EDP(%sp), %r19
+       addil   LT%_C_LABEL(_resumecontext), %r19
+       ldw     RT%_C_LABEL(_resumecontext)(%r1), %r1
+#else
+       ldil    L%_C_LABEL(_resumecontext), %r1
+       ldo     R%_C_LABEL(_resumecontext)(%r1), %r1
+#endif
+       bv,n    %r0(%r1)
+EXIT(__resumecontext)
+       .end
diff --git a/lib/nbsd_libc/arch/hppa/gen/_setjmp.S b/lib/nbsd_libc/arch/hppa/gen/_setjmp.S
new file mode 100644 (file)
index 0000000..9d7c74c
--- /dev/null
@@ -0,0 +1,128 @@
+/*     $NetBSD: _setjmp.S,v 1.4 2008/04/28 20:22:56 martin Exp $       */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matthew Fredette.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+/* XXX fredette - this is awful */
+#define _LOCORE
+#include <machine/frame.h>
+#undef _LOCORE
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: _setjmp.S,v 1.4 2008/04/28 20:22:56 martin Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and a struct sigcontext, see <signal.h>
+ */
+
+ENTRY(_setjmp,0)
+       /* A sigcontext is at the beginning of our jmp_buf. */
+       stw     %r0, 0(%arg0)           ; no onstack
+       stw     %r0, 4(%arg0)           ; unused word (old style signal mask)
+       stw     %sp, 8(%arg0)           ; sc.sc_sp = %sp
+       stw     %r0, 16(%arg0)          ; sc.sc_ap = NULL
+       mfsp    %sr0, %r1
+       stw     %r1, 20(%arg0)          ; sc.sc_pcsqh = %sr0
+       stw     %rp, 24(%arg0)          ; sc.sc_pcoqh = %rp
+       stw     %r1, 28(%arg0)          ; sc.sc_pcsqh = %sr0
+       ldo     4(%rp), %r1
+       stw     %r1, 32(%arg0)          ; sc.sc_pcoqt = %rp + 4
+       stw     %r0, 36(%arg0)          ; set sc.sc_ps
+
+       /* We store all callee-saved registers after the sigcontext. */
+       ldo     56(%arg0), %r1
+       stwm    %r3, 4(%r1)
+       stwm    %r4, 4(%r1)
+       stwm    %r5, 4(%r1)
+       stwm    %r6, 4(%r1)
+       stwm    %r7, 4(%r1)
+       stwm    %r8, 4(%r1)
+       stwm    %r9, 4(%r1)
+       stwm    %r10, 4(%r1)
+       stwm    %r11, 4(%r1)
+       stwm    %r12, 4(%r1)
+       stwm    %r13, 4(%r1)
+       stwm    %r14, 4(%r1)
+       stwm    %r15, 4(%r1)
+       stwm    %r16, 4(%r1)
+       stwm    %r17, 4(%r1)
+       stwm    %r18, 4(%r1)
+
+       /* Return 0. */
+       bv      %r0(%rp)
+       copy    %r0, %ret0
+EXIT(_setjmp)
+
+ENTRY(_longjmp,0)
+       ldw     8(%arg0), %r1           ; ensure non-zero SP
+       combt,=,n       %r0, %r1, botch ; oops!
+       add,<>  %r0, %arg1, %ret0       ; ensure return value non-zero
+       ldi     1, %ret0
+
+       /* restore callee-saved registers */
+       ldo     56(%arg0), %r1
+       ldwm    4(%r1), %r3
+       ldwm    4(%r1), %r4
+       ldwm    4(%r1), %r5
+       ldwm    4(%r1), %r6
+       ldwm    4(%r1), %r7
+       ldwm    4(%r1), %r8
+       ldwm    4(%r1), %r9
+       ldwm    4(%r1), %r10
+       ldwm    4(%r1), %r11
+       ldwm    4(%r1), %r12
+       ldwm    4(%r1), %r13
+       ldwm    4(%r1), %r14
+       ldwm    4(%r1), %r15
+       ldwm    4(%r1), %r16
+       ldwm    4(%r1), %r17
+       ldwm    4(%r1), %r18
+
+       /* restore the rest */
+       ldw     8(%arg0), %sp
+       ldw     24(%arg0), %rp
+       bv      %r0(%rp)
+       nop
+botch:
+       bl      longjmperror, %rp
+       nop
+       bl      abort, %rp
+       nop
+EXIT(_longjmp)
+
+       .end
diff --git a/lib/nbsd_libc/arch/hppa/gen/fabs.c b/lib/nbsd_libc/arch/hppa/gen/fabs.c
new file mode 100644 (file)
index 0000000..f08f504
--- /dev/null
@@ -0,0 +1,17 @@
+/*     $NetBSD: fabs.c,v 1.4 2005/12/24 21:42:32 perry Exp $   */
+
+/*     $OpenBSD: fabs.c,v 1.3 2002/10/21 18:41:05 mickey Exp $ */
+
+/*
+ * Written by Miodrag Vallat.  Public domain
+ */
+
+#include <math.h>
+
+double
+fabs(double val)
+{
+
+       __asm volatile("fabs,dbl %0,%0" : "+f" (val));
+       return (val);
+}
diff --git a/lib/nbsd_libc/arch/hppa/gen/flt_rounds.c b/lib/nbsd_libc/arch/hppa/gen/flt_rounds.c
new file mode 100644 (file)
index 0000000..e043d2b
--- /dev/null
@@ -0,0 +1,31 @@
+/*     $NetBSD: flt_rounds.c,v 1.4 2005/12/24 21:42:32 perry Exp $     */
+
+/*     $OpenBSD: flt_rounds.c,v 1.3 2002/10/21 18:41:05 mickey Exp $   */
+
+/*
+ * Written by Miodrag Vallat.  Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: flt_rounds.c,v 1.4 2005/12/24 21:42:32 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <machine/float.h>
+
+static const int map[] = {
+       1,      /* round to nearest */
+       0,      /* round to zero */
+       2,      /* round to positive infinity */
+       3       /* round to negative infinity */
+};
+
+int
+__flt_rounds(void)
+{
+       uint64_t fpsr;
+
+       __asm volatile("fstd %%fr0,0(%1)" : "=m" (fpsr) : "r" (&fpsr));
+       return map[(fpsr >> 41) & 0x03];
+}
diff --git a/lib/nbsd_libc/arch/hppa/gen/fpgetmask.c b/lib/nbsd_libc/arch/hppa/gen/fpgetmask.c
new file mode 100644 (file)
index 0000000..4ef451c
--- /dev/null
@@ -0,0 +1,24 @@
+/*     $NetBSD: fpgetmask.c,v 1.4 2005/12/24 21:42:32 perry Exp $      */
+
+/*     $OpenBSD: fpgetmask.c,v 1.3 2002/10/21 18:41:05 mickey Exp $    */
+
+/*
+ * Written by Miodrag Vallat.  Public domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetmask.c,v 1.4 2005/12/24 21:42:32 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+fp_except
+fpgetmask(void)
+{
+       uint64_t fpsr;
+
+       __asm volatile("fstd %%fr0,0(%1)" : "=m" (fpsr) : "r" (&fpsr));
+       return ((fpsr >> 32) & 0x1f);
+}
diff --git a/lib/nbsd_libc/arch/hppa/gen/fpgetround.c b/lib/nbsd_libc/arch/hppa/gen/fpgetround.c
new file mode 100644 (file)
index 0000000..1629b64
--- /dev/null
@@ -0,0 +1,24 @@
+/*     $NetBSD: fpgetround.c,v 1.4 2005/12/24 21:42:32 perry Exp $     */
+
+/*     $OpenBSD: fpgetround.c,v 1.3 2002/10/21 18:41:05 mickey Exp $   */
+
+/*
+ * Written by Miodrag Vallat.  Public domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetround.c,v 1.4 2005/12/24 21:42:32 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+fp_rnd
+fpgetround(void)
+{
+       uint64_t fpsr;
+
+       __asm volatile("fstd %%fr0,0(%1)" : "=m" (fpsr) : "r" (&fpsr));
+       return ((fpsr >> 41) & 0x3);
+}
diff --git a/lib/nbsd_libc/arch/hppa/gen/fpgetsticky.c b/lib/nbsd_libc/arch/hppa/gen/fpgetsticky.c
new file mode 100644 (file)
index 0000000..29ea34a
--- /dev/null
@@ -0,0 +1,24 @@
+/*     $NetBSD: fpgetsticky.c,v 1.4 2005/12/24 21:42:32 perry Exp $    */
+
+/*     $OpenBSD: fpgetsticky.c,v 1.3 2002/10/21 18:41:05 mickey Exp $  */
+
+/*
+ * Written by Miodrag Vallat.  Public domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetsticky.c,v 1.4 2005/12/24 21:42:32 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+fp_except
+fpgetsticky(void)
+{
+       uint64_t fpsr;
+
+       __asm volatile("fstd %%fr0,0(%1)" : "=m" (fpsr) : "r" (&fpsr));
+       return ((fpsr >> 59) & 0x1f);
+}
diff --git a/lib/nbsd_libc/arch/hppa/gen/fpsetmask.c b/lib/nbsd_libc/arch/hppa/gen/fpsetmask.c
new file mode 100644 (file)
index 0000000..1633f61
--- /dev/null
@@ -0,0 +1,28 @@
+/*     $NetBSD: fpsetmask.c,v 1.5 2009/01/25 16:44:41 skrll Exp $      */
+
+/*     $OpenBSD: fpsetmask.c,v 1.4 2004/01/05 06:06:16 otto Exp $      */
+
+/*
+ * Written by Miodrag Vallat.  Public domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetmask.c,v 1.5 2009/01/25 16:44:41 skrll Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+fp_except
+fpsetmask(fp_except mask)
+{
+       uint64_t fpsr;
+       fp_except old;
+
+       __asm volatile("fstd %%fr0,0(%1)" : "=m"(fpsr) : "r"(&fpsr) : "memory");
+       old = (fpsr >> 32) & 0x1f;
+       fpsr = (fpsr & 0xffffffe000000000LL) | ((uint64_t)(mask & 0x1f) << 32);
+       __asm volatile("fldd 0(%0),%%fr0" : : "r"(&fpsr) : "memory");
+       return (old);
+}
diff --git a/lib/nbsd_libc/arch/hppa/gen/fpsetround.c b/lib/nbsd_libc/arch/hppa/gen/fpsetround.c
new file mode 100644 (file)
index 0000000..d947462
--- /dev/null
@@ -0,0 +1,29 @@
+/*     $NetBSD: fpsetround.c,v 1.5 2009/01/25 16:44:41 skrll Exp $     */
+
+/*     $OpenBSD: fpsetround.c,v 1.3 2002/10/21 18:41:05 mickey Exp $   */
+
+/*
+ * Written by Miodrag Vallat.  Public domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetround.c,v 1.5 2009/01/25 16:44:41 skrll Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+fp_rnd
+fpsetround(fp_rnd rnd_dir)
+{
+       uint64_t fpsr;
+       fp_rnd old;
+
+       __asm volatile("fstd %%fr0,0(%1)" : "=m" (fpsr) : "r" (&fpsr) : "memory");
+       old = (fpsr >> 41) & 0x03;
+       fpsr = (fpsr & 0xfffff9ff00000000LL) |
+           ((uint64_t)(rnd_dir & 0x03) << 41);
+       __asm volatile("fldd 0(%0),%%fr0" : : "r" (&fpsr) : "memory");
+       return (old);
+}
diff --git a/lib/nbsd_libc/arch/hppa/gen/fpsetsticky.c b/lib/nbsd_libc/arch/hppa/gen/fpsetsticky.c
new file mode 100644 (file)
index 0000000..4721609
--- /dev/null
@@ -0,0 +1,29 @@
+/*     $NetBSD: fpsetsticky.c,v 1.5 2009/01/25 16:44:41 skrll Exp $    */
+
+/*     $OpenBSD: fpsetsticky.c,v 1.4 2004/01/05 06:06:16 otto Exp $    */
+
+/*
+ * Written by Miodrag Vallat.  Public domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetsticky.c,v 1.5 2009/01/25 16:44:41 skrll Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+fp_except
+fpsetsticky(fp_except mask)
+{
+       uint64_t fpsr;
+       fp_except old;
+
+       __asm volatile("fstd %%fr0,0(%1)" : "=m" (fpsr) : "r" (&fpsr) : "memory");
+       old = (fpsr >> 59) & 0x1f;
+       fpsr = (fpsr & 0x07ffffff00000000LL) | ((uint64_t)(mask & 0x1f) << 59);
+       __asm volatile("fldd 0(%0),%%fr0" : : "r" (&fpsr) : "memory");
+
+       return (old);
+}
diff --git a/lib/nbsd_libc/arch/hppa/gen/makecontext.c b/lib/nbsd_libc/arch/hppa/gen/makecontext.c
new file mode 100644 (file)
index 0000000..c7cb50d
--- /dev/null
@@ -0,0 +1,99 @@
+/*     $NetBSD: makecontext.c,v 1.3 2008/04/28 20:22:56 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.3 2008/04/28 20:22:56 martin Exp $");
+#endif
+
+#include <inttypes.h>
+#include <stddef.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#include <stdarg.h>
+
+#include <sys/types.h>
+#include <machine/frame.h>
+
+void
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+{
+       __greg_t *gr = ucp->uc_mcontext.__gregs;
+       __greg_t *gp, rp, fp;
+       register __greg_t dp __asm("r27");
+       uintptr_t *sp;
+       int i;
+       va_list ap;
+
+       void __resumecontext(void);
+
+       /* LINTED uintptr_t is safe */
+       sp  = (uintptr_t *)ucp->uc_stack.ss_sp;
+       /* LINTED uintptr_t is safe */
+       sp += 16;                       /* standard frame */
+       sp += (argc >= 4 ? argc : 4);   /* Make room for >=4 arguments. */
+       sp  = (uintptr_t *)
+             ((uintptr_t)(sp + 16) & ~0x3f);   /* Align on 64-byte boundary. */
+
+       /* Save away the registers that we'll need. */
+       gr[_REG_SP] = (__greg_t)sp;
+       rp = (__greg_t)__resumecontext;
+       if (rp & 2) {
+               gp = (__greg_t *)(rp & ~3);
+               rp = gp[0];
+               sp[-8] = gp[1];
+       }
+       gr[_REG_RP] = rp;
+       fp = (__greg_t)func;
+       if (fp & 2) {
+               gp = (__greg_t *)(fp & ~3);
+               fp = gp[0];
+               gr[_REG_R19] = gp[1];
+       }
+       gr[_REG_PCOQH] = fp | HPPA_PC_PRIV_USER;
+       gr[_REG_PCOQT] = (fp + 4) | HPPA_PC_PRIV_USER;
+       gr[_REG_DP] = dp;
+
+       /* Construct argument list. */
+       va_start(ap, argc);
+       /* Up to the first four arguments are passed in %arg0-3. */
+       for (i = 0; i < argc && i < 4; i++) {
+               /* LINTED uintptr_t is safe */
+               gr[_REG_ARG0 - i] = va_arg(ap, uintptr_t);
+       }
+       /* Pass remaining arguments on the stack below the %arg0-3 gap. */
+       for (; i < argc; i++) {
+               /* LINTED uintptr_t is safe */
+               sp[-9 - i] = va_arg(ap, uintptr_t);
+       }
+       va_end(ap);
+}
diff --git a/lib/nbsd_libc/arch/hppa/gen/nanf.c b/lib/nbsd_libc/arch/hppa/gen/nanf.c
new file mode 100644 (file)
index 0000000..b95319b
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: nanf.c,v 1.2 2009/02/22 01:34:01 martin Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nanf.c,v 1.2 2009/02/22 01:34:01 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+/* bytes for quiet NaN (IEEE single precision) */
+const union __float_u __nanf =
+               { { 0x7f, 0xa0,    0,    0 } };
+
+__warn_references(__nanf, "warning: <math.h> defines NAN incorrectly for your compiler.")
diff --git a/lib/nbsd_libc/arch/hppa/gen/resumecontext.c b/lib/nbsd_libc/arch/hppa/gen/resumecontext.c
new file mode 100644 (file)
index 0000000..03443a3
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: resumecontext.c,v 1.3 2008/04/28 20:22:56 martin Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: resumecontext.c,v 1.3 2008/04/28 20:22:56 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "extern.h"
+
+void
+_resumecontext()
+{
+       ucontext_t uct;
+
+       (void)getcontext(&uct);
+       if (uct.uc_link == NULL) 
+               exit(0);
+       (void)setcontext(uct.uc_link);
+       _exit(-1);
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/hppa/gen/swapcontext.S b/lib/nbsd_libc/arch/hppa/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..7e5601c
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: swapcontext.S,v 1.4 2008/04/28 20:22:56 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+#include <machine/mcontext.h>
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: swapcontext.S,v 1.4 2008/04/28 20:22:56 martin Exp $")
+#endif /* SYSLIBC_SCCS && !lint */
+
+LEAF_ENTRY(swapcontext)
+       stw     %rp, HPPA_FRAME_CRP(%sp)
+       stw     %arg0, HPPA_FRAME_ARG(0)(%sp)
+       stw     %arg1, HPPA_FRAME_ARG(1)(%sp)
+       SYSCALL(getcontext)
+
+       ldw     HPPA_FRAME_ARG(0)(%sp), %arg1
+       ldw     HPPA_FRAME_ARG(1)(%sp), %arg0
+       stw     %r0, (_OFFSETOF_UC_GREGS + _REG_RET0 * SZREG)(%arg1)
+       ldo     4(%rp), %r1
+       stw     %r1, (_OFFSETOF_UC_GREGS + _REG_PCOQT * SZREG)(%arg1)
+       stw     %rp, (_OFFSETOF_UC_GREGS + _REG_PCOQH * SZREG)(%arg1)
+       SYSCALL(setcontext)
+EXIT(swapcontext)
+       .end
diff --git a/lib/nbsd_libc/arch/hppa/net/Makefile.inc b/lib/nbsd_libc/arch/hppa/net/Makefile.inc
new file mode 100644 (file)
index 0000000..e3e9f67
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.1 2002/06/06 20:31:21 fredette Exp $
+
+SRCS += ntohl.c ntohs.c htons.c htonl.c
+
diff --git a/lib/nbsd_libc/arch/hppa/stdlib/Makefile.inc b/lib/nbsd_libc/arch/hppa/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..d1dda02
--- /dev/null
@@ -0,0 +1 @@
+#      $NetBSD: Makefile.inc,v 1.4 2009/07/31 20:39:59 dsl Exp $
diff --git a/lib/nbsd_libc/arch/hppa/string/Makefile.inc b/lib/nbsd_libc/arch/hppa/string/Makefile.inc
new file mode 100644 (file)
index 0000000..f00669a
--- /dev/null
@@ -0,0 +1,10 @@
+#      $NetBSD: Makefile.inc,v 1.3 2009/07/30 20:57:16 dsl Exp $
+
+#      $OpenBSD: Makefile.inc,v 1.4 1999/09/14 00:46:18 mickey Exp $
+
+SRCS+= bcmp.S bzero.S ffs.S
+
+# NetBSD doesn't currently let archs supply a strlcpy.S.
+# plus, the one that fredette made is untested.
+#SRCS+=        strlcpy.S
+
diff --git a/lib/nbsd_libc/arch/hppa/string/bcmp.S b/lib/nbsd_libc/arch/hppa/string/bcmp.S
new file mode 100644 (file)
index 0000000..6e2263f
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: bcmp.S,v 1.2 2003/10/06 05:30:21 matt Exp $    */
+
+/*     $OpenBSD: bcmp.S,v 1.3 2001/06/04 23:14:02 mickey Exp $ */
+
+/*
+ * Copyright 1996 1995 by Open Software Foundation, Inc.   
+ *              All Rights Reserved 
+ *  
+ * Permission to use, copy, modify, and distribute this software and 
+ * its documentation for any purpose and without fee is hereby granted, 
+ * provided that the above copyright notice appears in all copies and 
+ * that both the copyright notice and this permission notice appear in 
+ * supporting documentation. 
+ *  
+ * OSF DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE 
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
+ * FOR A PARTICULAR PURPOSE. 
+ *  
+ * IN NO EVENT SHALL OSF BE LIABLE FOR ANY SPECIAL, INDIRECT, OR 
+ * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 
+ * LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT, 
+ * NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION 
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 
+ */
+/*
+ *  (c) Copyright 1988 HEWLETT-PACKARD COMPANY
+ *
+ *  To anyone who acknowledges that this file is provided "AS IS"
+ *  without any express or implied warranty:
+ *      permission to use, copy, modify, and distribute this file
+ *  for any purpose is hereby granted without fee, provided that
+ *  the above copyright notice and this notice appears in all
+ *  copies, and that the name of Hewlett-Packard Company not be
+ *  used in advertising or publicity pertaining to distribution
+ *  of the software without specific, written prior permission.
+ *  Hewlett-Packard Company makes no representations about the
+ *  suitability of this software for any purpose.
+ */
+/*
+ * Copyright (c) 1990,1991,1994 The University of Utah and
+ * the Computer Systems Laboratory (CSL).  All rights reserved.
+ *
+ * THE UNIVERSITY OF UTAH AND CSL PROVIDE THIS SOFTWARE IN ITS "AS IS"
+ * CONDITION, AND DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM ITS USE.
+ *
+ * CSL requests users of this software to return to csl-dist@cs.utah.edu any
+ * improvements that they make and grant CSL redistribution rights.
+ *
+ *     Utah Hdr: movc.s 1.26 94/12/14
+ */
+
+#include <machine/asm.h>
+
+#ifdef SYSLIBC_SCCS
+       .text
+       .asciz "$OpenBSD: bcmp.S,v 1.3 2001/06/04 23:14:02 mickey Exp $"
+       .align  4
+#endif
+
+/*
+ * int
+ * bcmp(src, dst, count)
+ *     vaddr_t src;
+ *     vaddr_t dst;
+ *     size_t  count;
+ */
+LEAF_ENTRY(bcmp)
+        comb,>= %r0,%arg2,$bcmp_exit
+       copy    %t1,%t2
+
+$bcmp_loop:
+       ldbs,ma 1(%arg0),%t1
+       ldbs,ma 1(%arg1),%t2
+       comb,<>,n %t1,%t2,$bcmp_exit
+       addib,<> -1,%arg2,$bcmp_loop
+       nop
+
+$bcmp_exit:
+       bv      0(%r2)
+       sub     %t1,%t2,%ret0
+
+EXIT(bcmp)
+
diff --git a/lib/nbsd_libc/arch/hppa/string/bzero.S b/lib/nbsd_libc/arch/hppa/string/bzero.S
new file mode 100644 (file)
index 0000000..c14de62
--- /dev/null
@@ -0,0 +1,119 @@
+/*     $NetBSD: bzero.S,v 1.2 2003/10/06 05:30:21 matt Exp $   */
+
+/*     $OpenBSD: bzero.S,v 1.3 2001/06/04 23:14:02 mickey Exp $        */
+
+/*
+ *  (c) Copyright 1988 HEWLETT-PACKARD COMPANY
+ *
+ *  To anyone who acknowledges that this file is provided "AS IS"
+ *  without any express or implied warranty:
+ *      permission to use, copy, modify, and distribute this file
+ *  for any purpose is hereby granted without fee, provided that
+ *  the above copyright notice and this notice appears in all
+ *  copies, and that the name of Hewlett-Packard Company not be
+ *  used in advertising or publicity pertaining to distribution
+ *  of the software without specific, written prior permission.
+ *  Hewlett-Packard Company makes no representations about the
+ *  suitability of this software for any purpose.
+ */
+/*
+ * Copyright (c) 1990,1994 The University of Utah and
+ * the Computer Systems Laboratory (CSL).  All rights reserved.
+ *
+ * THE UNIVERSITY OF UTAH AND CSL PROVIDE THIS SOFTWARE IN ITS "AS IS"
+ * CONDITION, AND DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM ITS USE.
+ *
+ * CSL requests users of this software to return to csl-dist@cs.utah.edu any
+ * improvements that they make and grant CSL redistribution rights.
+ *
+ *     Utah $Hdr: bzero.s 1.9 94/12/14$
+ *     Author: Bob Wheeler, University of Utah CSL
+ */
+
+#include <machine/asm.h>
+
+#ifdef SYSLIBC_SCCS
+       .text
+       .asciz "$OpenBSD: bzero.S,v 1.3 2001/06/04 23:14:02 mickey Exp $"
+       .align  4
+#endif
+
+/*
+ * void 
+ * bzero(dst, count)
+ *     void *dst;
+ *     size_t count;
+ */
+LEAF_ENTRY(bzero)
+        comb,>=,n %r0,%arg1,$bzero_exit
+
+       /*
+        * If we need to clear less than a word do it a byte at a time
+        */
+
+       comib,>>,n 4,%arg1,$bzero_bytes
+
+       /*
+        * Since we are only clearing memory the alignment restrictions 
+        * are simplified. Figure out how many "extra" bytes we need to
+        * store with stbys.
+        */
+
+        extru   %arg0,31,2,%t1
+        add     %arg1,%t1,%arg1
+
+       /*
+        * We will zero the destination in blocks of 16 bytes as long as we 
+        * can and then we'll go to the 4 byte moves.
+        */
+
+       comib,>>=       15, %arg1, $bzero_word
+       addi            -16, %arg1, %arg1
+
+$bzero_loop_16:
+        stbys,b,m %r0,4(%arg0)
+        stwm    %r0,4(%arg0)
+        stwm    %r0,4(%arg0)
+        stwm    %r0,4(%arg0)
+       comib,<<        15, %arg1, $bzero_loop_16
+       addi            -16, %arg1, %arg1
+
+       /*
+        * see if there is anything left that needs to be zeroed in a word 
+        * move. Since the count was decremented by 16, add 12 to test if 
+        * there are any full word moves left to do.
+        */
+
+$bzero_word:
+        addib,<,n 12,%arg1,$bzero_cleanup
+
+$bzero_loop_4:
+        addib,>= -4,%arg1,$bzero_loop_4
+        stbys,b,m %r0,4(%arg0)
+
+       /*
+        * zero the last bytes that may be unaligned on a word boundary
+        */
+
+$bzero_cleanup:
+        addib,=,n 4,%arg1,$bzero_exit
+        add    %arg0,%arg1,%arg0
+        b       $bzero_exit
+        stbys,e %r0,0(%arg0)
+       b,n     $bzero_exit
+
+
+       /*
+        * zero by bytes
+        */
+
+$bzero_bytes:
+        addib,> -1,%arg1,$bzero_bytes
+        stbs,ma %r0,1(%arg0) 
+
+$bzero_exit:
+       bv,n    %r0(%rp)
+EXIT(bzero)
+
+       .end
diff --git a/lib/nbsd_libc/arch/hppa/string/ffs.S b/lib/nbsd_libc/arch/hppa/string/ffs.S
new file mode 100644 (file)
index 0000000..a4754a7
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: ffs.S,v 1.3 2004/07/18 20:30:04 chs Exp $      */
+
+/*     $OpenBSD: ffs.S,v 1.3 2001/06/04 23:14:02 mickey Exp $  */
+
+/* 
+ * Copyright (c) 1990, 1991, 1992, 1994, The University of Utah and
+ * the Computer Systems Laboratory at the University of Utah (CSL).
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify and distribute this software and its
+ * documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ *
+ * THE UNIVERSITY OF UTAH AND CSL ALLOW FREE USE OF THIS SOFTWARE IN ITS "AS
+ * IS" CONDITION.  THE UNIVERSITY OF UTAH AND CSL DISCLAIM ANY LIABILITY OF
+ * ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ *
+ * CSL requests users of this software to return to csl-dist@cs.utah.edu any
+ * improvements that they make and grant CSL redistribution rights.
+ *
+ */
+
+#include <machine/asm.h>
+
+#ifdef SYSLIBC_SCCS
+       .text
+       .asciz "$OpenBSD: ffs.S,v 1.3 2001/06/04 23:14:02 mickey Exp $"
+       .align  4
+#endif
+
+/*
+ * ffs(bitmask)
+ *
+ * Return the position of the "most significant" bit in `bitmask'.
+ * Since this is similar to the VAX ffs instruction, bits in a word
+ * are numbered as "32, 31, ... 1", 0 is returned if no bits are set.
+ */
+
+LEAF_ENTRY(ffs)
+       comb,=  %arg0,%r0,ffsdone       ; If arg0 is 0
+       or      %r0,%r0,%ret0           ;   return 0
+       ldi     32,%ret0                ; Set return to high bit
+       extru,= %arg0,31,16,%r0         ; If low 16 bits are non-zero
+       addi,tr -16,%ret0,%ret0         ;   subtract 16 from bitpos
+       shd     %r0,%arg0,16,%arg0      ; else shift right 16 bits
+       extru,= %arg0,31,8,%r0          ; If low 8 bits are non-zero
+       addi,tr -8,%ret0,%ret0          ;   subtract 8 from bitpos
+       shd     %r0,%arg0,8,%arg0       ; else shift right 8 bits
+       extru,= %arg0,31,4,%r0          ; If low 4 bits are non-zero
+       addi,tr -4,%ret0,%ret0          ;   subtract 4 from bitpos
+       shd     %r0,%arg0,4,%arg0       ; else shift right 4 bits
+       extru,= %arg0,31,2,%r0          ; If low 2 bits are non-zero
+       addi,tr -2,%ret0,%ret0          ;   subtract 2 from bitpos
+       shd     %r0,%arg0,2,%arg0       ; else shift right 2 bits
+       extru,= %arg0,31,1,%r0          ; If low bit is non-zero
+       addi    -1,%ret0,%ret0          ;   subtract 1 from bitpos
+ffsdone:
+       bv,n    %r0(%rp)
+EXIT(ffs)
+
+       .end
diff --git a/lib/nbsd_libc/arch/hppa/string/strlcpy.S b/lib/nbsd_libc/arch/hppa/string/strlcpy.S
new file mode 100644 (file)
index 0000000..ec199b1
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: strlcpy.S,v 1.3 2008/04/28 20:22:56 martin Exp $       */
+
+/*
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matthew Fredette.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint) 
+        RCSID("$NetBSD: strlcpy.S,v 1.3 2008/04/28 20:22:56 martin Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * size_t strlcpy(char *dst, const char *src, size_t size);
+ */
+LEAF_ENTRY(_strlcpy)
+       .weak strlcpy
+       strlcpy = _strlcpy
+
+       /* Always load the first byte of the source string. */
+       ldbs,ma         1(%arg1), %r1
+
+       /*
+        * If our dst buffer is zero bytes, branch immediately
+        * to the code that counts the (remaining) length
+        * of the src string.
+        */
+       comb,=          %r0, %arg2, $strlcpy_dst_done
+       copy            %arg1, %ret0
+
+       /*
+        * If our dst buffer is one byte, branch immediately 
+        * to the code that NUL-terminates the dst buffer and
+        * counts the (remaining) length of the src string.
+        */
+       addib,=,n       -1, %arg2, $strlcpy_dst_full
+
+       /*
+        * Loop copying bytes.  At the top of this loop,
+        * %arg2 is always the number of bytes we can still 
+        * store, and %r1 holds the next byte to store.
+        */
+$strlcpy_loop:
+       comb,=          %r0, %r1, $strlcpy_exit
+       stbs,ma         %r1, 1(%arg0)
+       addib,<>        -1, %arg2, $strlcpy_loop
+       ldbs,ma         1(%arg1), %r1
+
+$strlcpy_dst_full:
+       stbs,ma         %r0, 1(%arg0)
+
+$strlcpy_dst_done:
+       comb,<>,n       %r0, %r1, $strlcpy_dst_done
+       ldbs,ma         1(%arg1), %r1
+       
+$strlcpy_exit:
+       bv              %r0(%rp)
+       sub             %arg1, %ret0, %ret0
+EXIT(strlcpy)
diff --git a/lib/nbsd_libc/arch/hppa/sys/__clone.S b/lib/nbsd_libc/arch/hppa/sys/__clone.S
new file mode 100644 (file)
index 0000000..b3ee7a2
--- /dev/null
@@ -0,0 +1,87 @@
+/*     $NetBSD: __clone.S,v 1.6 2008/04/28 20:22:56 martin Exp $       */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Fredette.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+       WEAK_ALIAS(clone, __clone)
+#endif
+
+       .import __cerror, code
+
+/*
+ * int clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+ENTRY(__clone, 0)
+
+       /*
+        * Sanity checks: func and stack may not be NULL.
+        */
+       ldi     EINVAL, %t1
+       comb,=  %r0, %arg0, __cerror
+       nop
+       comb,=  %r0, %arg1, __cerror
+       nop
+
+       /*
+        * Put the func and arg arguments into a frame in the child's stack.
+        */
+       ldo     (HPPA_FRAME_SIZE * 2)(%arg1), %arg1
+       stw     %arg0, HPPA_FRAME_ARG(0)(%arg1)
+       stw     %arg3, HPPA_FRAME_ARG(1)(%arg1)
+
+       /*
+        * The system call expects (flags, stack).
+        */
+       copy    %arg2, %arg0
+       SYSCALL(__clone)
+       comb,<>,n %r0, %ret1, 9f
+       bv,n    %r0(%rp)
+
+9:     /*
+        * Child: Reload the function and argument from the new stack.
+        */
+       ldw     HPPA_FRAME_ARG(0)(%sp), %r22
+       ldw     HPPA_FRAME_ARG(1)(%sp), %arg0
+
+       /* Call the clone's entry point. */
+       stw     %r19, HPPA_FRAME_ARG(2)(%sp)
+       bl      $$dyncall, %r31
+       copy    %r31, %rp
+       ldw     HPPA_FRAME_ARG(2)(%sp), %r19
+
+       /* Pass the return value to _exit(). */
+       copy    %ret0, %arg0
+       PIC_CALL(_exit)
+
+       /* NOTREACHED */
+EXIT(__clone)
diff --git a/lib/nbsd_libc/arch/hppa/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/hppa/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..dbfb300
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.4 2008/04/28 20:22:56 martin Exp $        */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigaction14_sigtramp.c,v 1.4 2008/04/28 20:22:56 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define        __LIBC12_SOURCE__
+
+#include <sys/types.h>
+#include <signal.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern int __sigtramp_siginfo_2[];
+
+       return (__sigaction_sigtramp(sig, act, oact,
+                                    __sigtramp_siginfo_2, 2));
+}
diff --git a/lib/nbsd_libc/arch/hppa/sys/__sigtramp2.S b/lib/nbsd_libc/arch/hppa/sys/__sigtramp2.S
new file mode 100644 (file)
index 0000000..7c047ba
--- /dev/null
@@ -0,0 +1,133 @@
+/*     $NetBSD: __sigtramp2.S,v 1.4 2009/11/03 05:07:25 snj Exp $      */
+
+/*
+ * Copyright (c) 1998-2001 Michael Shalayeff
+ * 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 ``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 HIS RELATIVES 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 MIND, 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.
+ *
+ * Portitions of this file are derived from other sources, see
+ * the copyrights and acknowledgements below.
+ */
+/*
+ * Copyright (c) 1990,1991,1992,1994 The University of Utah and
+ * the Computer Systems Laboratory (CSL).  All rights reserved.
+ *
+ * THE UNIVERSITY OF UTAH AND CSL PROVIDE THIS SOFTWARE IN ITS "AS IS"
+ * CONDITION, AND DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM ITS USE.
+ *
+ * CSL requests users of this software to return to csl-dist@cs.utah.edu any
+ * improvements that they make and grant CSL redistribution rights.
+ *
+ *     Utah $Hdr: locore.s 1.62 94/12/15$
+ */
+/*
+ *  (c) Copyright 1988 HEWLETT-PACKARD COMPANY
+ *
+ *  To anyone who acknowledges that this file is provided "AS IS"
+ *  without any express or implied warranty:
+ *      permission to use, copy, modify, and distribute this file
+ *  for any purpose is hereby granted without fee, provided that
+ *  the above copyright notice and this notice appears in all
+ *  copies, and that the name of Hewlett-Packard Company not be
+ *  used in advertising or publicity pertaining to distribution
+ *  of the software without specific, written prior permission.
+ *  Hewlett-Packard Company makes no representations about the
+ *  suitability of this software for any purpose.
+ */
+
+#include "SYS.h"
+
+/*
+ * The hppa signal trampoline is required to call the handler
+ * possibily via a PLABEL.
+ *
+ * On entry, stack looks like:
+ *
+ *     sp->                                    [x]
+ * r3,arg2->   ucontext structure
+ *    arg1->   siginfo structure               [0]
+ *
+ * where
+ *     x = HPPA_FRAME_ROUND(sizeof(sigframe_siginfo))
+ *
+ * and
+ *     struct sigframe_siginfo {
+ *             siginfo_t sf_si;
+ *             ucontext_t sf_uc;
+ *     };
+ */
+
+ENTRY_NOPROFILE(__sigtramp_siginfo_2, 0)
+       .call
+
+       /*
+        * Our sendsig() places the address of the signal handler in %arg3.
+        * It may actually be a PLABEL.
+        */
+       bb,>=,n %arg3, 30, L$sigcode_bounce     ; branch if not a PLABEL
+       depi    0, 31, 2, %arg3                 ; zero L bit in PLABEL pointer
+       ldw     4(%arg3), %r19                  ; load shared library linkage
+       ldw     0(%arg3), %arg3                 ; load real catcher address
+
+L$sigcode_bounce:
+
+       /*
+        * This blr puts the address of the following nop in rp.
+        * It also schedules the nop for execution, which is why
+        * that instruction has to be a nop, or, rather, not any
+        * instruction only meant to execute once the signal handler
+        * returns.
+        */
+       blr     %r0, %rp
+
+       /*
+        * This bv schedules the instruction pointed to by arg3
+        * for execution.  So, arg3 is the address of the signal
+        * handler.
+        */
+       bv,n    %r0(%arg3)
+       nop
+
+       /*
+        * The signal handler has returned.  Since r3 is on the list
+        * of callee-saved registers, it's whatever the sendsig
+        * code wanted it set to.  Since we copy it into arg0,
+        * it looks like sendsig leaves r3 holding the desired
+        * single argument to sys_setcontext, i.e., the ucontext_t *.
+        */
+
+       /* Make a SYS_setcontext system call. */
+       copy    %r3, %arg0
+       ldil    L%SYSCALLGATE, %r1
+       .call
+       ble     4(%sr7, %r1)
+       ldi     SYS_setcontext, %t1
+
+       /* Make a SYS_exit system call. */
+       copy    %ret0, %arg0
+       ldil    L%SYSCALLGATE, %r1
+       .call
+       ble     4(%sr7, %r1)
+       ldi     SYS_exit, %t1
+EXIT(__sigtramp_siginfo_2)
diff --git a/lib/nbsd_libc/arch/hppa/sys/__syscall.S b/lib/nbsd_libc/arch/hppa/sys/__syscall.S
new file mode 100644 (file)
index 0000000..bdef76f
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: __syscall.S,v 1.1 2002/06/06 20:31:23 fredette Exp $   */
+
+#include "SYS.h"
+RSYSCALL(__syscall)
diff --git a/lib/nbsd_libc/arch/hppa/sys/__vfork14.S b/lib/nbsd_libc/arch/hppa/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..770ccf9
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: __vfork14.S,v 1.5 2008/04/28 20:22:56 martin Exp $     */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Fredette.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+#include "SYS.h"
+
+ENTRY(__vfork14, 0)
+       /*
+        * NB: __vfork14 is a tricky syscall.  We can't save
+        * any values on the stack, because the stack will be 
+        * trashed by the child, leaving garbage for when the
+        * parent returns.
+        *
+        * So we must save values in registers, specifically,
+        * registers that the kernel is willing to preserve
+        * across the syscall.  Normally, this would be callee-
+        * saved registers, with the kernel being the callee,
+        * but the problem is that we, too, are a callee, and
+        * would have to save that very same register somewhere,
+        * because *our* caller is counting on us to do so.
+        *
+        * What we need is a normally caller-saved register,
+        * that the kernel is willing to save for us.  The 
+        * syscall entry code in locore.S has been modified 
+        * to do just this for the t4 register.
+        */
+       .import __cerror, code
+
+       copy    %rp, %t4
+       ldil    L%SYSCALLGATE, %r1
+       ble     4(%sr7, %r1)
+       ldi     SYS___vfork14, %t1
+       comb,<> %r0, %t1, __cerror
+       copy    %t4, %rp
+       addi    -1, %ret1, %ret1
+       bv      %r0(%rp)
+       and     %ret0, %ret1, %ret0
+EXIT(__vfork14)
diff --git a/lib/nbsd_libc/arch/hppa/sys/brk.S b/lib/nbsd_libc/arch/hppa/sys/brk.S
new file mode 100644 (file)
index 0000000..61ce625
--- /dev/null
@@ -0,0 +1,78 @@
+/*     $NetBSD: brk.S,v 1.4 2009/11/03 05:07:25 snj Exp $      */
+
+/*     $OpenBSD: brk.S,v 1.7 2001/06/04 23:14:04 mickey Exp $  */
+
+/*
+ * Copyright (c) 1999 Michael Shalayeff
+ * 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 ``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 HIS RELATIVES 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 MIND, 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: brk.S,v 1.4 2009/11/03 05:07:25 snj Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+       .import curbrk, data
+       .import end, data
+
+#ifdef WEAK_ALIAS
+       WEAK_ALIAS(brk, _brk) 
+#endif
+
+       .data
+       .export __minbrk, data
+__minbrk:
+       .long   end
+
+ENTRY(_brk,0)
+#ifdef PIC
+       addil   LT%__minbrk, %r19
+       ldw     RT%__minbrk(%r1), %r1
+       ldw     0(%r1), %t2
+#else  /* !PIC */
+       ldil    L%__minbrk, %t1
+       ldw     R%__minbrk(%t1), %t2
+#endif /* !PIC */
+       sub,<<  %t2, %arg0, %r0
+       copy    %t2, %arg0
+       stw     %arg0, HPPA_FRAME_ARG(0)(%sp)
+
+       SYSCALL(break)
+
+       ldw     HPPA_FRAME_ARG(0)(%sp), %arg0
+#ifdef PIC
+       addil   LT%curbrk, %r19
+       ldw     RT%curbrk(%r1), %r1
+       bv      %r0(%rp)
+       stw     %arg0, 0(%r1)
+#else  /* !PIC */
+       ldil    L%curbrk, %t1
+       bv      %r0(%rp)
+       stw     %arg0, R%curbrk(%t1)
+#endif /* !PIC */
+EXIT(brk)
+
+       .end
+
diff --git a/lib/nbsd_libc/arch/hppa/sys/cerror.S b/lib/nbsd_libc/arch/hppa/sys/cerror.S
new file mode 100644 (file)
index 0000000..f55b042
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: cerror.S,v 1.4 2008/04/28 20:22:56 martin Exp $        */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Nick Hudson
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#ifdef _REENTRANT
+ENTRY(__cerror,HPPA_FRAME_SIZE)
+#else
+LEAF_ENTRY(__cerror)
+#endif
+#ifdef _REENTRANT
+       stw     %rp, HPPA_FRAME_CRP(%sp)
+       stw     %t1, HPPA_FRAME_ARG(0)(%sp)
+       ldo     HPPA_FRAME_SIZE(%sp),%sp
+       bl      __errno, %rp
+       nop
+       ldo     -HPPA_FRAME_SIZE(%sp), %sp
+       ldw     HPPA_FRAME_ARG(0)(%sp), %t1
+       ldw     HPPA_FRAME_CRP(%sp), %rp
+       stw     %t1, 0(%ret0)
+#else
+#ifdef PIC
+       addil   LT%errno, %r19
+       ldw     RT%errno(%r1), %r1
+       stw     %t1, 0(%r1)
+#else
+       ldil    L%errno, %r1
+       stw     %t1, R%errno(%r1)
+#endif
+#endif
+       ldi     -1, %ret0
+       bv      %r0(%rp)
+       ldi     -1, %ret1
+EXIT(__cerror)
diff --git a/lib/nbsd_libc/arch/hppa/sys/exect.S b/lib/nbsd_libc/arch/hppa/sys/exect.S
new file mode 100644 (file)
index 0000000..5bb0ce1
--- /dev/null
@@ -0,0 +1,40 @@
+/*     $NetBSD: exect.S,v 1.2 2009/11/03 05:07:25 snj Exp $    */
+
+/*     $OpenBSD: exect.S,v 1.5 2001/03/29 01:43:52 mickey Exp $        */
+
+/*
+ * Copyright (c) 1999 Michael Shalayeff
+ * 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 ``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 HIS RELATIVES 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 MIND, 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: exect.S,v 1.2 2009/11/03 05:07:25 snj Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+/* we do no tracing yet */
+PSEUDO(exect,execve)
+
+       .end
diff --git a/lib/nbsd_libc/arch/hppa/sys/fork.S b/lib/nbsd_libc/arch/hppa/sys/fork.S
new file mode 100644 (file)
index 0000000..0ee7ddf
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: fork.S,v 1.4 2009/11/03 05:07:25 snj Exp $     */
+
+/*     $OpenBSD: fork.S,v 1.7 2001/06/04 23:14:04 mickey Exp $ */
+
+/*
+ * Copyright (c) 1999 Michael Shalayeff
+ * 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 ``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 HIS RELATIVES 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 MIND, 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: fork.S,v 1.4 2009/11/03 05:07:25 snj Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(__fork,0)
+       SYSCALL(fork)
+       addi    -1, %ret1, %ret1
+       bv      %r0(%rp)
+       and     %ret0, %ret1, %ret0
+EXIT(__fork)
+
+       .end
diff --git a/lib/nbsd_libc/arch/hppa/sys/getcontext.S b/lib/nbsd_libc/arch/hppa/sys/getcontext.S
new file mode 100644 (file)
index 0000000..e1a6aa6
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: getcontext.S,v 1.4 2008/04/28 20:22:56 martin Exp $    */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Fredette.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+#include <machine/mcontext.h>
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext, _getcontext)
+#endif
+
+#define _OFFSETOF_UC_GREGS (10 * 4)
+#define SZREG 4
+
+ENTRY(_getcontext, 0)
+       SYSCALL(getcontext)
+       stw     %rp, (_OFFSETOF_UC_GREGS + _REG_PCOQH * SZREG)(%arg0)
+       ldo     4(%rp), %r1
+       stw     %r1, (_OFFSETOF_UC_GREGS + _REG_PCOQT * SZREG)(%arg0)
+       bv      %r0(%rp)
+       stw     %r0, (_OFFSETOF_UC_GREGS + _REG_RET0 * SZREG)(%arg0)
+EXIT(_getcontext)
diff --git a/lib/nbsd_libc/arch/hppa/sys/pipe.S b/lib/nbsd_libc/arch/hppa/sys/pipe.S
new file mode 100644 (file)
index 0000000..00970ae
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: pipe.S,v 1.3 2003/10/06 05:30:21 matt Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)pipe.s 5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: pipe.S,v 1.3 2003/10/06 05:30:21 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef WEAK_ALIAS
+       WEAK_ALIAS(pipe, _pipe)
+#endif
+
+ENTRY(_pipe,0)
+       stw     %arg0, HPPA_FRAME_ARG(0)(%sp)
+       SYSCALL(pipe)
+       ldw     HPPA_FRAME_ARG(0)(%sp), %arg0
+       stw     %ret0, 0(%arg0)
+       stw     %ret1, 4(%arg0)
+       bv      %r0(%rp)
+       copy    %r0, %ret0
+EXIT(_pipe)
diff --git a/lib/nbsd_libc/arch/hppa/sys/ptrace.S b/lib/nbsd_libc/arch/hppa/sys/ptrace.S
new file mode 100644 (file)
index 0000000..6235259
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: ptrace.S,v 1.6 2008/04/28 20:22:56 martin Exp $        */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Fredette.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+#include "SYS.h"
+
+       .import __cerror, code
+
+/*
+ * int ptrace(int request, pid_t pid, void * addr, int data);
+ */
+
+ENTRY(ptrace, HPPA_FRAME_SIZE)
+       stw     %rp, HPPA_FRAME_CRP(%sp)
+       stw     %arg0, HPPA_FRAME_ARG(0)(%sp)
+       stw     %arg1, HPPA_FRAME_ARG(1)(%sp)
+       stw     %arg2, HPPA_FRAME_ARG(2)(%sp)
+       stw     %arg3, HPPA_FRAME_ARG(3)(%sp)
+       ldo     HPPA_FRAME_SIZE(%sp),%sp
+       bl      __cerror, %rp
+        copy   %r0, %t1
+       ldo     -HPPA_FRAME_SIZE(%sp), %sp
+       ldw     HPPA_FRAME_ARG(0)(%sp), %arg0
+       ldw     HPPA_FRAME_ARG(1)(%sp), %arg1
+       ldw     HPPA_FRAME_ARG(2)(%sp), %arg2
+       ldw     HPPA_FRAME_ARG(3)(%sp), %arg3
+       ldw     HPPA_FRAME_CRP(%sp), %rp
+
+       SYSCALL(ptrace)
+       bv,n    %r0(%rp)
+EXIT(ptrace)
diff --git a/lib/nbsd_libc/arch/hppa/sys/sbrk.S b/lib/nbsd_libc/arch/hppa/sys/sbrk.S
new file mode 100644 (file)
index 0000000..963d251
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: sbrk.S,v 1.4 2009/11/03 05:07:25 snj Exp $     */
+
+/*     $OpenBSD: sbrk.S,v 1.7 2001/06/04 23:14:04 mickey Exp $ */
+
+/*
+ * Copyright (c) 1999 Michael Shalayeff
+ * 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 ``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 HIS RELATIVES 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 MIND, 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: sbrk.S,v 1.4 2009/11/03 05:07:25 snj Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+       .import end, data
+
+#ifdef WEAK_ALIAS
+       WEAK_ALIAS(sbrk, _sbrk)
+#endif
+
+       .data
+       .export curbrk, data
+curbrk:
+       .long   end
+
+ENTRY(_sbrk,0)
+#ifdef PIC
+       addil   LT%curbrk, %r19
+       ldw     RT%curbrk(%r1), %r1
+       ldw     0(%r1), %t2
+#else  /* !PIC */
+       ldil    L%curbrk, %t1
+       ldw     R%curbrk(%t1), %t2
+#endif /* !PIC */
+       add     %arg0, %t2, %arg0
+       stw     %arg0, HPPA_FRAME_ARG(0)(%sp)
+
+       SYSCALL(break)
+
+#ifdef PIC
+       addil   LT%curbrk, %r19
+       ldw     RT%curbrk(%r1), %r1
+#else  /* !PIC */
+       ldil    L%curbrk, %t1
+       ldo     R%curbrk(%t1), %r1
+#endif /* !PIC */
+       ldw     0(%r1), %ret0
+       ldw     HPPA_FRAME_ARG(0)(%sp), %arg0
+       bv      %r0(%rp)
+       stw     %arg0, 0(%r1)
+
+EXIT(sbrk)
+
+       .end
diff --git a/lib/nbsd_libc/arch/hppa/sys/shmat.S b/lib/nbsd_libc/arch/hppa/sys/shmat.S
new file mode 100644 (file)
index 0000000..0eaf832
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: shmat.S,v 1.3 2004/07/18 20:48:04 chs Exp $    */
+
+#include "SYS.h"
+
+RSYSCALL(shmat)
diff --git a/lib/nbsd_libc/arch/hppa/sys/syscall.S b/lib/nbsd_libc/arch/hppa/sys/syscall.S
new file mode 100644 (file)
index 0000000..fbf8ee4
--- /dev/null
@@ -0,0 +1,39 @@
+/*     $NetBSD: syscall.S,v 1.2 2009/11/03 05:07:25 snj Exp $  */
+
+/*     $OpenBSD: syscall.S,v 1.4 2001/03/29 01:43:53 mickey Exp $      */
+
+/*
+ * Copyright (c) 1999 Michael Shalayeff
+ * 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 ``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 HIS RELATIVES 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 MIND, 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: syscall.S,v 1.2 2009/11/03 05:07:25 snj Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+RSYSCALL(syscall)
+
+       .end
diff --git a/lib/nbsd_libc/arch/i386/Makefile.inc b/lib/nbsd_libc/arch/i386/Makefile.inc
new file mode 100644 (file)
index 0000000..6b78a3b
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.20 2006/06/17 18:04:23 uwe Exp $
+
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S
diff --git a/lib/nbsd_libc/arch/i386/SYS.h b/lib/nbsd_libc/arch/i386/SYS.h
new file mode 100644 (file)
index 0000000..11e06ab
--- /dev/null
@@ -0,0 +1,152 @@
+/*     $NetBSD: SYS.h,v 1.23 2008/04/28 20:22:56 martin Exp $  */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Andrew Doran.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)SYS.h 5.5 (Berkeley) 5/7/91
+ */
+
+#include <machine/asm.h>
+#include <sys/syscall.h>
+
+#ifdef __STDC__
+#define _SYSNAM(x)     $(SYS_ ## x)
+#else
+#define        _SYSNAM(x)      $(SYS_/**/x)
+#endif
+
+#define OSYSTRAP(x)                    \
+       movl _SYSNAM(x),%eax            ;\
+       int $0x80
+
+#ifdef I686_LIBC
+#define SYSTRAP(x)                     \
+       pushl   %ebx                    ;\
+       movl    _SYSNAM(x),%eax         ;\
+       movl    $123f,%edx              ;\
+       movl    %esp,%ecx               ;\
+       sysenter                        ;\
+123:   movl    %ebx,%edx               ;\
+       popl    %ebx
+#else  /* I686_LIBC */
+#define SYSTRAP(x)     OSYSTRAP(x)
+#endif /* I686_LIBC */
+
+#ifdef __ELF__
+#define CERROR         _C_LABEL(__cerror)
+#define CURBRK         _C_LABEL(__curbrk)
+#else
+#define CERROR         _ASM_LABEL(cerror)
+#define CURBRK         _ASM_LABEL(curbrk)
+#endif
+
+#define _SYSCALL_NOERROR(x,y)                                          \
+       ENTRY(x);                                                       \
+       SYSTRAP(y)
+
+#ifdef PIC
+#define _SYSCALL_ERR                                                   \
+       PIC_PROLOGUE;                                                   \
+       mov PIC_GOT(CERROR), %ecx;                                      \
+       PIC_EPILOGUE;                                                   \
+       jmp *%ecx
+#else
+#define _SYSCALL_ERR                                                   \
+       jmp CERROR
+#endif
+
+#define _SYSCALL(x,y)                                                  \
+       .text; _ALIGN_TEXT;                                             \
+       2: _SYSCALL_ERR;                                                \
+       _SYSCALL_NOERROR(x,y);                                          \
+       jc 2b
+
+#define SYSCALL_NOERROR(x)                                             \
+       _SYSCALL_NOERROR(x,x)
+
+#define SYSCALL(x)                                                     \
+       _SYSCALL(x,x)
+
+#define PSEUDO_NOERROR(x,y)                                            \
+       _SYSCALL_NOERROR(x,y);                                          \
+       ret
+
+#define PSEUDO(x,y)                                                    \
+       _SYSCALL_NOERROR(x,y);                                          \
+       jc 2f;                                                          \
+       ret;                                                            \
+       2: _SYSCALL_ERR
+
+#define RSYSCALL_NOERROR(x)                                            \
+       PSEUDO_NOERROR(x,x)
+
+#define RSYSCALL(x)                                                    \
+       PSEUDO(x,x)
+
+#ifdef WEAK_ALIAS
+#define        WSYSCALL(weak,strong)                                           \
+       WEAK_ALIAS(weak,strong);                                        \
+       PSEUDO(strong,weak)
+#else
+#define        WSYSCALL(weak,strong)                                           \
+       PSEUDO(weak,weak)
+#endif
+
+       .globl  CERROR
diff --git a/lib/nbsd_libc/arch/i386/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/i386/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..ce2f485
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/15 17:35:18 kleink Exp $
+
+SRCS+= strtof.c strtold_px.c
+SRCS+= strtopx.c
diff --git a/lib/nbsd_libc/arch/i386/gdtoa/arith.h b/lib/nbsd_libc/arch/i386/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..1513f1f
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: arith.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define IEEE_LITTLE_ENDIAN
diff --git a/lib/nbsd_libc/arch/i386/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/i386/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..b316779
--- /dev/null
@@ -0,0 +1,11 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define f_QNAN 0x7fc00000
+#define d_QNAN0 0x0
+#define d_QNAN1 0x7ff80000
+#define ldus_QNAN0 0x0
+#define ldus_QNAN1 0x0
+#define ldus_QNAN2 0x0
+#define ldus_QNAN3 0x4000
+#define ldus_QNAN4 0x7fff
+/* 2 bytes of tail padding follow, per i386 ABI */
diff --git a/lib/nbsd_libc/arch/i386/gen/Makefile.inc b/lib/nbsd_libc/arch/i386/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..4c845e7
--- /dev/null
@@ -0,0 +1,38 @@
+#      $NetBSD: Makefile.inc,v 1.26 2009/12/06 07:12:17 uebayasi Exp $
+
+# objects built from assembler sources (need lint stubs)
+SRCS+= alloca.S byte_swap_2.S byte_swap_4.S fabs.S \
+       flt_rounds.S fpgetmask.S fpgetround.S fpgetsticky.S \
+       fpsetmask.S fpsetround.S fpsetsticky.S 
+
+SRCS+= setjmp.S _setjmp.S sigsetjmp.S
+
+SRCS+= resumecontext.S swapcontext.S
+
+# objects built from C sources
+SRCS+= bswap64.c _lwp.c makecontext.c
+
+# Common ieee754 constants and functions
+SRCS+= infinityf_ieee754.c infinity_ieee754.c
+SRCS+= fpclassifyf_ieee754.c fpclassifyd_ieee754.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c
+SRCS+= isfinitef_ieee754.c isfinited_ieee754.c
+SRCS+= signbitf_ieee754.c signbitd_ieee754.c
+
+SRCS+= nanf.c infinityl.c
+SRCS+= fpclassifyl.c isfinitel.c isinfl.c isnanl.c signbitl.c
+
+# "internal" objects (don't provide part of the user-visible API)
+SRCS+= divsi3.S fixdfsi.S fixunsdfsi.S udivsi3.S
+
+LSRCS.i386.gen=\
+       Lint__setjmp.c Lint_alloca.c Lint_bswap16.c Lint_bswap32.c \
+       Lint_fabs.c \
+       Lint___setjmp14.c Lint___sigsetjmp14.c Lint_flt_rounds.c \
+       Lint_fpgetmask.c Lint_fpgetround.c Lint_fpgetsticky.c \
+       Lint_fpsetmask.c Lint_fpsetround.c Lint_fpsetsticky.c \
+       Lint_resumecontext.c Lint_swapcontext.c Lint__setjmp.c
+LSRCS+=                ${LSRCS.i386.gen}
+DPSRCS+=       ${LSRCS.i386.gen}
+CLEANFILES+=   ${LSRCS.i386.gen}
diff --git a/lib/nbsd_libc/arch/i386/gen/_lwp.c b/lib/nbsd_libc/arch/i386/gen/_lwp.c
new file mode 100644 (file)
index 0000000..0837709
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: _lwp.c,v 1.6 2008/04/28 20:22:56 martin Exp $  */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Nathan J. Williams.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.6 2008/04/28 20:22:56 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <inttypes.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+
+void
+_lwp_makecontext(ucontext_t *u, void (*start)(void *),
+    void *arg, void *private, caddr_t stack_base, size_t stack_size)
+{
+       void **sp;
+
+       getcontext(u);
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+
+       /* LINTED uintptr_t is safe */
+       u->uc_mcontext.__gregs[_REG_EIP] = (uintptr_t)start;
+       
+       /* Align to a word */
+       /* LINTED uintptr_t is safe */
+       sp = (void **) ((uintptr_t)(stack_base + stack_size) & ~0x3);
+       
+       *--sp = arg;
+       *--sp = (void *) _lwp_exit;
+       
+       /* LINTED uintptr_t is safe */
+       u->uc_mcontext.__gregs[_REG_UESP] = (uintptr_t) sp;
+
+       /* LINTED private is currently unused */
+}
diff --git a/lib/nbsd_libc/arch/i386/gen/_setjmp.S b/lib/nbsd_libc/arch/i386/gen/_setjmp.S
new file mode 100644 (file)
index 0000000..1fb2366
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: _setjmp.S,v 1.8 2005/10/05 20:18:12 christos Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)_setjmp.s     5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: _setjmp.S,v 1.8 2005/10/05 20:18:12 christos Exp $")
+#endif
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     _longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     _setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is NOT restored.
+ */
+
+ENTRY(_setjmp)
+       movl    4(%esp),%eax
+       movl    0(%esp),%edx
+       movl    %edx, 0(%eax)           /* rta */
+       movl    %ebx, 4(%eax)
+       movl    %esp, 8(%eax)
+       movl    %ebp,12(%eax)
+       movl    %esi,16(%eax)
+       movl    %edi,20(%eax)
+       xorl    %eax,%eax
+       ret
+
+ENTRY(_longjmp)
+       movl    4(%esp),%edx
+       movl    8(%esp),%eax
+       movl    0(%edx),%ecx
+       movl    4(%edx),%ebx
+       movl    8(%edx),%esp
+       movl    12(%edx),%ebp
+       movl    16(%edx),%esi
+       movl    20(%edx),%edi
+       testl   %eax,%eax
+       jnz     1f
+       incl    %eax
+1:     movl    %ecx,0(%esp)
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/alloca.S b/lib/nbsd_libc/arch/i386/gen/alloca.S
new file mode 100644 (file)
index 0000000..1ceb457
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: alloca.S,v 1.8 2003/08/07 16:42:06 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)alloca.s      5.2 (Berkeley) 5/14/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: alloca.S,v 1.8 2003/08/07 16:42:06 agc Exp $")
+#endif
+
+/* like alloc, but automatic free in return */
+
+ENTRY(alloca)
+       popl    %edx            /*  pop return addr */
+       popl    %eax            /*  pop amount to allocate */
+       movl    %esp,%ecx
+       addl    $3,%eax         /*  round up to next word */
+       andl    $-4,%eax
+       subl    %eax,%esp
+       movl    %esp,%eax       /* base of newly allocated space */
+       pushl   8(%ecx)         /* copy possible saved registers */
+       pushl   4(%ecx)
+       pushl   0(%ecx)
+       pushl   %eax            /* dummy to pop at callsite */
+       jmp     *%edx           /* "return" */
diff --git a/lib/nbsd_libc/arch/i386/gen/divsi3.S b/lib/nbsd_libc/arch/i386/gen/divsi3.S
new file mode 100644 (file)
index 0000000..61d6b34
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: divsi3.S,v 1.6 2003/08/07 16:42:07 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)divsi3.s      5.1 (Berkeley) 5/15/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: divsi3.S,v 1.6 2003/08/07 16:42:07 agc Exp $")
+#endif
+
+ENTRY(__divsi3)
+       movl 4(%esp),%eax
+       cltd
+       idivl 8(%esp)
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/fabs.S b/lib/nbsd_libc/arch/i386/gen/fabs.S
new file mode 100644 (file)
index 0000000..76c3f3e
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: fabs.S,v 1.5 2003/08/07 16:42:07 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)fabs.s        5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: fabs.S,v 1.5 2003/08/07 16:42:07 agc Exp $")
+#endif
+
+ENTRY(fabs)
+       fldl    4(%esp)
+       fabs
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/fixdfsi.S b/lib/nbsd_libc/arch/i386/gen/fixdfsi.S
new file mode 100644 (file)
index 0000000..6bcf500
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: fixdfsi.S,v 1.6 2003/08/07 16:42:07 agc Exp $  */
+
+/*-
+ * Copyright (c) 1991 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)fixdfsi.s     5.4 (Berkeley) 4/12/91
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: fixdfsi.S,v 1.6 2003/08/07 16:42:07 agc Exp $")
+#endif
+
+ENTRY(__fixdfsi)
+       fldl    4(%esp)
+       fistpl  4(%esp)
+       movl    4(%esp),%eax
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/fixunsdfsi.S b/lib/nbsd_libc/arch/i386/gen/fixunsdfsi.S
new file mode 100644 (file)
index 0000000..e9c2e67
--- /dev/null
@@ -0,0 +1,75 @@
+/*     $NetBSD: fixunsdfsi.S,v 1.11 2003/08/07 16:42:07 agc Exp $      */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)fixunsdfsi.s  5.1     12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: fixunsdfsi.S,v 1.11 2003/08/07 16:42:07 agc Exp $")
+#endif
+
+ENTRY(__fixunsdfsi)
+       fldl    4(%esp)         /* argument double to accum stack */
+       frndint                 /* create integer */
+#ifdef PIC
+       PIC_PROLOGUE
+       leal    PIC_GOTOFF(fbiggestsigned),%eax
+       PIC_EPILOGUE
+       fcoml   (%eax)
+#else
+       fcoml   fbiggestsigned  /* bigger than biggest signed? */
+#endif
+       fstsw   %ax
+       sahf
+       jnb     2f
+
+       fistpl  4(%esp)
+       movl    4(%esp),%eax
+       ret
+
+2:
+#ifdef PIC
+       PIC_PROLOGUE
+       leal    PIC_GOTOFF(fbiggestsigned),%eax
+       PIC_EPILOGUE
+       fsubl   (%eax)
+#else
+       fsubl   fbiggestsigned  /* reduce for proper conversion */
+#endif
+       fistpl  4(%esp)         /* convert */
+       movl    4(%esp),%eax
+       orl     $0x80000000,%eax        /* restore bias */
+       ret
+
+fbiggestsigned:        .double 0r2147483648.0
diff --git a/lib/nbsd_libc/arch/i386/gen/flt_rounds.S b/lib/nbsd_libc/arch/i386/gen/flt_rounds.S
new file mode 100644 (file)
index 0000000..4b21327
--- /dev/null
@@ -0,0 +1,33 @@
+/*     $NetBSD: flt_rounds.S,v 1.6 1999/08/23 08:45:09 kleink Exp $    */
+
+/*
+ * Written by J.T. Conklin, Apr 4, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+       .text
+       _ALIGN_TEXT
+_map:
+       .byte 1         /* round to nearest */
+       .byte 3         /* round to negative infinity */
+       .byte 2         /* round to positive infinity */
+       .byte 0         /* round to zero */
+
+ENTRY(__flt_rounds)
+       subl $4,%esp
+       fnstcw (%esp)
+       movl (%esp),%eax
+       shrl $10,%eax
+       andl $3,%eax
+#ifdef PIC
+       PIC_PROLOGUE
+       leal PIC_GOTOFF(_map),%ecx
+       PIC_EPILOGUE
+       movb (%ecx,%eax,1),%al
+#else
+       movb _map(,%eax,1),%al
+#endif
+       addl $4,%esp
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/fpclassifyl.c b/lib/nbsd_libc/arch/i386/gen/fpclassifyl.c
new file mode 100644 (file)
index 0000000..185ee0c
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: fpclassifyl.c,v 1.3 2008/04/28 20:22:56 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpclassifyl.c,v 1.3 2008/04/28 20:22:56 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <assert.h>
+#include <math.h>
+
+/*
+ * 7.12.3.1 fpclassify - classify real floating type
+ *          IEEE 754 compatible 80-bit extended-precision Intel 386 version
+ */
+int
+__fpclassifyl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       _DIAGASSERT(u.extu_ext.ext_exp == 0 ||
+           (u.extu_ext.ext_frach & 0x80000000));
+
+       if (u.extu_ext.ext_exp == 0) {
+               if ((u.extu_ext.ext_frach & 0x7fffffff) == 0 &&
+                   u.extu_ext.ext_fracl == 0)
+                       return FP_ZERO;
+               else
+                       return FP_SUBNORMAL;
+       } else if (u.extu_ext.ext_exp == EXT_EXP_INFNAN) {
+               if ((u.extu_ext.ext_frach & 0x7fffffff) == 0 &&
+                   u.extu_ext.ext_fracl == 0)
+                       return FP_INFINITE;
+               else
+                       return FP_NAN;
+       }
+
+       return FP_NORMAL;
+}
diff --git a/lib/nbsd_libc/arch/i386/gen/fpgetmask.S b/lib/nbsd_libc/arch/i386/gen/fpgetmask.S
new file mode 100644 (file)
index 0000000..e3e2953
--- /dev/null
@@ -0,0 +1,22 @@
+/*     $NetBSD: fpgetmask.S,v 1.4 2002/01/13 21:45:42 thorpej Exp $    */
+
+/*
+ * Written by J.T. Conklin, Apr 4, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpgetmask, _fpgetmask)
+ENTRY(_fpgetmask)
+#else
+ENTRY(fpgetmask)
+#endif
+       subl $4,%esp
+       fnstcw (%esp)
+       movl (%esp),%eax
+       notl %eax
+       andl $63,%eax
+       addl $4,%esp
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/fpgetround.S b/lib/nbsd_libc/arch/i386/gen/fpgetround.S
new file mode 100644 (file)
index 0000000..093c115
--- /dev/null
@@ -0,0 +1,22 @@
+/*     $NetBSD: fpgetround.S,v 1.5 2002/01/13 21:45:43 thorpej Exp $   */
+
+/*
+ * Written by J.T. Conklin, Apr 4, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpgetround, _fpgetround)
+ENTRY(_fpgetround)
+#else
+ENTRY(fpgetround)
+#endif
+       subl $4,%esp
+       fnstcw (%esp)
+       movl (%esp),%eax
+       rorl $10,%eax
+       andl $3,%eax
+       addl $4,%esp
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/fpgetsticky.S b/lib/nbsd_libc/arch/i386/gen/fpgetsticky.S
new file mode 100644 (file)
index 0000000..5f54f94
--- /dev/null
@@ -0,0 +1,21 @@
+/*     $NetBSD: fpgetsticky.S,v 1.6 2002/01/13 21:45:43 thorpej Exp $  */
+
+/*
+ * Written by J.T. Conklin, Apr 4, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpgetsticky, _fpgetsticky)
+ENTRY(_fpgetsticky)
+#else
+ENTRY(fpgetsticky)
+#endif
+       subl $4,%esp
+       fnstsw (%esp)
+       movl (%esp),%eax
+       andl $63,%eax
+       addl $4,%esp
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/fpsetmask.S b/lib/nbsd_libc/arch/i386/gen/fpsetmask.S
new file mode 100644 (file)
index 0000000..7e010cc
--- /dev/null
@@ -0,0 +1,33 @@
+/*     $NetBSD: fpsetmask.S,v 1.4 2002/01/13 21:45:43 thorpej Exp $    */
+
+/*
+ * Written by Charles M. Hannum, Apr 9, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpsetmask, _fpsetmask)
+ENTRY(_fpsetmask)
+#else
+ENTRY(fpsetmask)
+#endif
+       subl $4,%esp
+
+       fnstcw (%esp)
+       movl (%esp),%eax
+       movl %eax,%edx
+
+       notl %eax
+       andl $63,%eax
+
+       addl %eax,%edx
+       movl 8(%esp),%ecx
+       andl $63,%ecx
+       subl %ecx,%edx
+       movl %edx,(%esp)
+       fldcw (%esp)
+
+       addl $4,%esp
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/fpsetround.S b/lib/nbsd_libc/arch/i386/gen/fpsetround.S
new file mode 100644 (file)
index 0000000..6e00f87
--- /dev/null
@@ -0,0 +1,34 @@
+/*     $NetBSD: fpsetround.S,v 1.3 2002/01/13 21:45:43 thorpej Exp $   */
+
+/*
+ * Written by Charles M. Hannum, Apr 9, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpsetround, _fpsetround)
+ENTRY(_fpsetround)
+#else
+ENTRY(fpsetround)
+#endif
+       subl $4,%esp
+
+       fnstcw (%esp)
+       movl (%esp),%eax
+
+       rorl $10,%eax
+       movl %eax,%edx
+       andl $3,%eax
+
+       subl %eax,%edx
+       movl 8(%esp),%ecx
+       andl $3,%ecx
+       orl %ecx,%edx
+       roll $10,%edx
+       movl %edx,(%esp)
+       fldcw (%esp)
+
+       addl $4,%esp
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/fpsetsticky.S b/lib/nbsd_libc/arch/i386/gen/fpsetsticky.S
new file mode 100644 (file)
index 0000000..76389d3
--- /dev/null
@@ -0,0 +1,32 @@
+/*     $NetBSD: fpsetsticky.S,v 1.6 2002/01/13 21:45:43 thorpej Exp $  */
+
+/*
+ * Written by Charles M. Hannum, Apr 9, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpsetsticky, _fpsetsticky)
+ENTRY(_fpsetsticky)
+#else
+ENTRY(fpsetsticky)
+#endif
+       subl $28,%esp
+
+       fnstenv (%esp)
+       movl 4(%esp),%eax
+       movl %eax,%edx
+
+       andl $63,%eax
+
+       subl %eax,%edx
+       movl 32(%esp),%ecx
+       andl $63,%ecx
+       addl %ecx,%edx
+       movl %edx,4(%esp)
+       fldenv (%esp)
+
+       addl $28,%esp
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/infinityl.c b/lib/nbsd_libc/arch/i386/gen/infinityl.c
new file mode 100644 (file)
index 0000000..3e7f543
--- /dev/null
@@ -0,0 +1,16 @@
+/*     $NetBSD: infinityl.c,v 1.2 2005/06/12 05:21:26 lukem Exp $      */
+
+/*
+ * IEEE-compatible infinityl.c for little-endian 80-bit format -- public domain.
+ * Note that the representation includes 16 bits of tail padding per i386 ABI.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: infinityl.c,v 1.2 2005/06/12 05:21:26 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+
+const union __long_double_u __infinityl =
+       { { 0, 0, 0, 0, 0, 0, 0, 0x80, 0xff, 0x7f, 0, 0 } };
diff --git a/lib/nbsd_libc/arch/i386/gen/isfinitel.c b/lib/nbsd_libc/arch/i386/gen/isfinitel.c
new file mode 100644 (file)
index 0000000..8b0c8a7
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: isfinitel.c,v 1.3 2008/04/28 20:22:56 martin Exp $     */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: isfinitel.c,v 1.3 2008/04/28 20:22:56 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <assert.h>
+#include <math.h>
+
+/*
+ * 7.12.3.2 isfinite - determine whether an argument has finite value
+ *          IEEE 754 compatible 80-bit extended-precision Intel 386 version
+ */
+int
+__isfinitel(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       _DIAGASSERT(u.extu_ext.ext_exp == 0 ||
+           (u.extu_ext.ext_frach & 0x80000000));
+
+       if (u.extu_ext.ext_exp == EXT_EXP_INFNAN)
+               return 0;
+
+       return 1;
+}
diff --git a/lib/nbsd_libc/arch/i386/gen/isinfl.c b/lib/nbsd_libc/arch/i386/gen/isinfl.c
new file mode 100644 (file)
index 0000000..b1675e9
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: isinfl.c,v 1.6 2007/02/02 23:14:09 christos Exp $      */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isinfl.c,v 1.6 2007/02/02 23:14:09 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.3 isinf - test for infinity
+ *          IEEE 754 compatible 80-bit extended-precision Intel 386 version
+ */
+int
+__isinfl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return (u.extu_ext.ext_exp == EXT_EXP_INFNAN &&
+            u.extu_ext.ext_frach == 0x80000000 && u.extu_ext.ext_fracl == 0);
+}
diff --git a/lib/nbsd_libc/arch/i386/gen/isnanl.c b/lib/nbsd_libc/arch/i386/gen/isnanl.c
new file mode 100644 (file)
index 0000000..a85fdc6
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: isnanl.c,v 1.6 2007/02/02 23:14:09 christos Exp $      */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isnanl.c,v 1.6 2007/02/02 23:14:09 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.4 isnan - test for a NaN
+ *          IEEE 754 compatible 80-bit extended-precision Intel 386 version
+ */
+int
+__isnanl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return (u.extu_ext.ext_exp == EXT_EXP_INFNAN &&
+           (u.extu_ext.ext_frach & 0x80000000) != 0 &&
+           (u.extu_ext.ext_frach != 0x80000000 || u.extu_ext.ext_fracl != 0));
+}
diff --git a/lib/nbsd_libc/arch/i386/gen/makecontext.c b/lib/nbsd_libc/arch/i386/gen/makecontext.c
new file mode 100644 (file)
index 0000000..11e8ec7
--- /dev/null
@@ -0,0 +1,93 @@
+/*     $NetBSD: makecontext.c,v 1.4 2008/04/28 20:22:56 martin Exp $   */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.4 2008/04/28 20:22:56 martin Exp $");
+#endif
+
+#include <inttypes.h>
+#include <stddef.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#if __STDC__
+#include <stdarg.h>
+#else
+#include <varargs.h>
+#endif
+
+
+void
+#if __STDC__
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+#else
+makecontext(ucp, func, argc, va_alist)
+       ucontext_t *ucp;
+       void (*func)();
+       int argc;
+       va_dcl
+#endif
+{
+       __greg_t *gr = ucp->uc_mcontext.__gregs;
+       unsigned int *sp;
+       va_list ap;
+
+       /* LINTED __greg_t is safe */
+       gr[_REG_EIP] = (__greg_t)func;
+
+       /* LINTED uintptr_t is safe */
+       sp  = (unsigned int *)((uintptr_t)ucp->uc_stack.ss_sp +
+           ucp->uc_stack.ss_size);
+       /* Align on word boundary. */
+       /* LINTED uintptr_t is safe */
+       sp  = (unsigned int *)((uintptr_t)sp & ~0x3);
+       sp -= argc + 1;                 /* Make room for ret and args. */
+       /* LINTED __greg_t is safe */
+       gr[_REG_UESP] = (__greg_t)sp;
+       gr[_REG_EBP] = (__greg_t)0;     /* Wipe out frame pointer. */
+
+       /* Put return address on top of stack. */
+       /* LINTED uintptr_t is safe */
+       *sp++ = (uintptr_t)_resumecontext;
+
+       /* Construct argument list. */
+#if __STDC__
+       va_start(ap, argc);
+#else
+       va_start(ap);
+#endif
+       while (argc-- > 0) {
+               /* LINTED uintptr_t is safe */
+               *sp++ = va_arg(ap, uintptr_t);
+       }
+       va_end(ap);
+}
diff --git a/lib/nbsd_libc/arch/i386/gen/nanf.c b/lib/nbsd_libc/arch/i386/gen/nanf.c
new file mode 100644 (file)
index 0000000..ac1fde3
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: nanf.c,v 1.4 2009/02/22 01:34:01 martin Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nanf.c,v 1.4 2009/02/22 01:34:01 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+/* bytes for quiet NaN (IEEE single precision) */
+const union __float_u __nanf =
+               { {    0,    0, 0xc0, 0x7f } };
+
+__warn_references(__nanf, "warning: <math.h> defines NAN incorrectly for your compiler.")
diff --git a/lib/nbsd_libc/arch/i386/gen/resumecontext.S b/lib/nbsd_libc/arch/i386/gen/resumecontext.S
new file mode 100644 (file)
index 0000000..629a09f
--- /dev/null
@@ -0,0 +1,83 @@
+/*     $NetBSD: resumecontext.S,v 1.6 2008/04/28 20:22:56 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: resumecontext.S,v 1.6 2008/04/28 20:22:56 martin Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+/*
+ * This assembly-language implementation differs from the (obvious)
+ * C-language implementation only in not clobbering the previous
+ * function's return address (us), which is the point of the exercise.
+ */
+
+NENTRY(_resumecontext) /* profiling prologue would clobber TOS */
+       leal    -(4 + 776)(%esp),%ecx   /* retaddr + sizeof (ucontext_t) */
+       andl    $~(0xf),%ecx            /* align on _UC_UCONTEXT_ALIGN */
+       movl    %ecx,%esp
+       PIC_PROLOGUE
+       pushl   %ecx
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(_getcontext))
+#else
+       call    _C_LABEL(_getcontext)
+#endif
+       addl    $4,%esp
+       PIC_EPILOGUE
+       movl    4(%esp),%ecx            /* uc_link */
+       PIC_PROLOGUE
+       pushl   %ecx    /* argument for exit() or setcontext() */
+       testl   %ecx,%ecx               /* link end? */
+       jnz     9f      /* watch out for local label use in PIC_* */
+
+       /* normal exit */
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(exit))
+#else
+       call    _C_LABEL(exit)
+#endif
+       /* NOTREACHED */
+
+9:
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(setcontext))
+#else
+       call    _C_LABEL(setcontext)
+#endif
+       /* NOTREACHED */
+
+       /* something is wrong, pull the brake */
+       pushl   $-1
+       pushl   %eax    /* unused return address */
+       SYSTRAP(exit)
diff --git a/lib/nbsd_libc/arch/i386/gen/setjmp.S b/lib/nbsd_libc/arch/i386/gen/setjmp.S
new file mode 100644 (file)
index 0000000..4d2a5b5
--- /dev/null
@@ -0,0 +1,109 @@
+/*     $NetBSD: setjmp.S,v 1.14 2005/09/13 01:44:08 christos Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)setjmp.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: setjmp.S,v 1.14 2005/09/13 01:44:08 christos Exp $")
+#endif
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(__setjmp14)
+       movl    4(%esp),%ecx
+       movl    0(%esp),%edx
+       movl    %edx, 0(%ecx)
+       movl    %ebx, 4(%ecx)
+       movl    %esp, 8(%ecx)
+       movl    %ebp,12(%ecx)
+       movl    %esi,16(%ecx)
+       movl    %edi,20(%ecx)
+
+       /* Get the signal mask. */
+       leal    24(%ecx),%edx
+
+       PIC_PROLOGUE
+       pushl   %edx
+       pushl   $0
+       pushl   $0
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(__sigprocmask14))
+#else
+       call    _C_LABEL(__sigprocmask14)
+#endif
+       addl    $12,%esp
+       PIC_EPILOGUE
+
+       xorl    %eax,%eax
+       ret
+
+ENTRY(__longjmp14)
+       /* Restore the signal mask. */
+       movl    4(%esp),%ecx
+       leal    24(%ecx),%edx
+
+       PIC_PROLOGUE
+       pushl   $0
+       pushl   %edx
+       pushl   $3                      /* SIG_SETMASK */
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(__sigprocmask14))
+#else
+       call    _C_LABEL(__sigprocmask14)
+#endif
+       addl    $12,%esp
+       PIC_EPILOGUE
+
+       movl    4(%esp),%edx
+       movl    8(%esp),%eax
+       movl    0(%edx),%ecx
+       movl    4(%edx),%ebx
+       movl    8(%edx),%esp
+       movl    12(%edx),%ebp
+       movl    16(%edx),%esi
+       movl    20(%edx),%edi
+       testl   %eax,%eax
+       jnz     1f
+       incl    %eax
+1:     movl    %ecx,0(%esp)
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/signbitl.c b/lib/nbsd_libc/arch/i386/gen/signbitl.c
new file mode 100644 (file)
index 0000000..8ea9a1f
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: signbitl.c,v 1.2 2008/04/28 20:22:56 martin Exp $      */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: signbitl.c,v 1.2 2008/04/28 20:22:56 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.6 signbit - determine whether the sign of an argument is negative
+ *          IEEE 754 compatible 80-bit extended-precision Intel 386 version
+ */
+int
+__signbitl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return (u.extu_ext.ext_sign == 1);
+}
diff --git a/lib/nbsd_libc/arch/i386/gen/sigsetjmp.S b/lib/nbsd_libc/arch/i386/gen/sigsetjmp.S
new file mode 100644 (file)
index 0000000..63fbb0d
--- /dev/null
@@ -0,0 +1,109 @@
+/*     $NetBSD: sigsetjmp.S,v 1.16 2005/09/13 01:44:08 christos Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)setjmp.s      5.1 (Berkeley) 4/23/90"
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: sigsetjmp.S,v 1.16 2005/09/13 01:44:08 christos Exp $")
+#endif
+
+ENTRY(__sigsetjmp14)
+       movl    4(%esp),%ecx
+       movl    0(%esp),%edx
+       movl    %edx, 0(%ecx)
+       movl    %ebx, 4(%ecx)
+       movl    %esp, 8(%ecx)
+       movl    %ebp,12(%ecx)
+       movl    %esi,16(%ecx)
+       movl    %edi,20(%ecx)
+
+       /* Check if we should save the signal mask, and remember it. */
+       movl    8(%esp),%eax
+       movl    %eax,40(%ecx)
+       testl   %eax,%eax
+       jz      2f                      /* no, skip */
+
+       /* Get the signal mask. */
+       leal    24(%ecx),%edx
+
+       PIC_PROLOGUE
+       pushl   %edx
+       pushl   $0
+       pushl   $0
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(__sigprocmask14))
+#else
+       call    _C_LABEL(__sigprocmask14)
+#endif
+       addl    $12,%esp
+       PIC_EPILOGUE
+
+2:     xorl    %eax,%eax
+       ret
+
+ENTRY(__siglongjmp14)
+       /* Check to see if we need to restore the signal mask. */
+       movl    4(%esp),%ecx
+       cmpl    $0,40(%ecx)
+       jz      2f                      /* no, skip */
+
+       /* Restore the signal mask. */
+       leal    24(%ecx),%edx
+
+       PIC_PROLOGUE
+       pushl   $0
+       pushl   %edx
+       pushl   $3                      /* SIG_SETMASK */
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(__sigprocmask14))
+#else
+       call    _C_LABEL(__sigprocmask14)
+#endif
+       addl    $12,%esp
+       PIC_EPILOGUE
+
+2:     movl    4(%esp),%edx
+       movl    8(%esp),%eax
+       movl    0(%edx),%ecx
+       movl    4(%edx),%ebx
+       movl    8(%edx),%esp
+       movl    12(%edx),%ebp
+       movl    16(%edx),%esi
+       movl    20(%edx),%edi
+       testl   %eax,%eax
+       jnz     3f
+       incl    %eax
+3:     movl    %ecx,0(%esp)
+       ret
diff --git a/lib/nbsd_libc/arch/i386/gen/swapcontext.S b/lib/nbsd_libc/arch/i386/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..a140c99
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: swapcontext.S,v 1.6 2008/04/28 20:22:56 martin Exp $   */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: swapcontext.S,v 1.6 2008/04/28 20:22:56 martin Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+ENTRY(swapcontext)
+       movl    4(%esp),%ecx
+       PIC_PROLOGUE
+       pushl   %ecx                    /* push oucp */
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(_getcontext))
+#else
+       call    _C_LABEL(_getcontext)
+#endif
+       addl    $4,%esp                 /* pop oucp */
+       PIC_EPILOGUE
+       testl   %eax,%eax
+       jnz     2f
+       movl    4(%esp),%ecx
+       movl    0(%esp),%edx
+       movl    %edx,(36 + 14 * 4)(%ecx)        /*  Adjust saved %eip ... */
+#ifdef PIC
+       movl    %ebx,(36 +  8 * 4)(%ecx)        /* ... clobbered PIC reg ... */
+#endif
+       leal    4(%esp),%edx
+       movl    %edx,(36 + 17 * 4)(%ecx)        /* ... and %esp. */
+       /* Note: oucp->%eax has been cleared by getcontext(). */
+       movl    8(%esp),%ecx
+       PIC_PROLOGUE
+       pushl   %ecx                    /* push ucp */
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(setcontext))
+#else
+       call    _C_LABEL(setcontext)
+#endif
+       addl    $4,%esp                 /* pop ucp */
+       PIC_EPILOGUE
+       /* No need to error-check: setcontext() must have failed. */
+2:     ret     
diff --git a/lib/nbsd_libc/arch/i386/gen/udivsi3.S b/lib/nbsd_libc/arch/i386/gen/udivsi3.S
new file mode 100644 (file)
index 0000000..0cb51af
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: udivsi3.S,v 1.6 2003/08/07 16:42:07 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)udivsi3.s     5.1 (Berkeley) 5/15/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: udivsi3.S,v 1.6 2003/08/07 16:42:07 agc Exp $")
+#endif
+
+ENTRY(__udivsi3)
+       movl 4(%esp),%eax
+       xorl %edx,%edx
+       divl 8(%esp)
+       ret
diff --git a/lib/nbsd_libc/arch/i386/net/Makefile.inc b/lib/nbsd_libc/arch/i386/net/Makefile.inc
new file mode 100644 (file)
index 0000000..0185ca6
--- /dev/null
@@ -0,0 +1,10 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/12/06 07:12:17 uebayasi Exp $
+
+# objects built from assembler sources (need lint stubs)
+# hton* and nto* functions provided by ../gen/byte_swap_*.S
+SRCS+=  
+
+LSRCS.i386.net=        Lint_htonl.c Lint_htons.c Lint_ntohl.c Lint_ntohs.c
+LSRCS+=                ${LSRCS.i386.net}
+DPSRCS+=       ${LSRCS.i386.net}
+CLEANFILES+=   ${LSRCS.i386.net}
diff --git a/lib/nbsd_libc/arch/i386/stdlib/Makefile.inc b/lib/nbsd_libc/arch/i386/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..189f574
--- /dev/null
@@ -0,0 +1,5 @@
+#      $NetBSD: Makefile.inc,v 1.9 2009/08/11 17:30:43 dsl Exp $
+
+# objects built from assembler sources
+SRCS+= abs.S div.S labs.S ldiv.S llabs.S
+NO_SRCS+= imaxabs.S
diff --git a/lib/nbsd_libc/arch/i386/stdlib/abs.S b/lib/nbsd_libc/arch/i386/stdlib/abs.S
new file mode 100644 (file)
index 0000000..74e9625
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: abs.S,v 1.7 2003/08/07 16:42:07 agc Exp $      */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)abs.s 5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: abs.S,v 1.7 2003/08/07 16:42:07 agc Exp $")
+#endif
+
+ENTRY(abs)
+       movl    4(%esp),%eax
+       testl   %eax,%eax
+       jns     1f
+       negl    %eax
+1:     ret
diff --git a/lib/nbsd_libc/arch/i386/stdlib/div.S b/lib/nbsd_libc/arch/i386/stdlib/div.S
new file mode 100644 (file)
index 0000000..66f3351
--- /dev/null
@@ -0,0 +1,23 @@
+/*     $NetBSD: div.S,v 1.8 2003/07/26 19:24:33 salo Exp $     */
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+RCSID("$NetBSD: div.S,v 1.8 2003/07/26 19:24:33 salo Exp $")
+#endif
+
+ENTRY(div)
+       pushl   %ebx
+       movl    8(%esp),%ebx
+       movl    12(%esp),%eax
+       movl    16(%esp),%ecx
+       cdq
+       idiv    %ecx
+       movl    %eax,(%ebx)
+       movl    %edx,4(%ebx)
+       popl    %ebx
+       ret     $4
diff --git a/lib/nbsd_libc/arch/i386/stdlib/labs.S b/lib/nbsd_libc/arch/i386/stdlib/labs.S
new file mode 100644 (file)
index 0000000..3b3414d
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: labs.S,v 1.7 2003/08/07 16:42:07 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)abs.s 5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: labs.S,v 1.7 2003/08/07 16:42:07 agc Exp $")
+#endif
+
+ENTRY(labs)
+       movl    4(%esp),%eax
+       testl   %eax,%eax
+       jns     1f
+       negl    %eax
+1:     ret
diff --git a/lib/nbsd_libc/arch/i386/stdlib/ldiv.S b/lib/nbsd_libc/arch/i386/stdlib/ldiv.S
new file mode 100644 (file)
index 0000000..d9acd25
--- /dev/null
@@ -0,0 +1,23 @@
+/*     $NetBSD: ldiv.S,v 1.8 2003/07/26 19:24:33 salo Exp $    */
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+RCSID("$NetBSD: ldiv.S,v 1.8 2003/07/26 19:24:33 salo Exp $")
+#endif
+
+ENTRY(ldiv)
+       pushl   %ebx
+       movl    8(%esp),%ebx
+       movl    12(%esp),%eax
+       movl    16(%esp),%ecx
+       cdq
+       idiv    %ecx
+       movl    %eax,(%ebx)
+       movl    %edx,4(%ebx)
+       popl    %ebx
+       ret     $4
diff --git a/lib/nbsd_libc/arch/i386/stdlib/llabs.S b/lib/nbsd_libc/arch/i386/stdlib/llabs.S
new file mode 100644 (file)
index 0000000..bc740ff
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: llabs.S,v 1.5 2008/08/04 21:29:28 matt Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)abs.s 5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: llabs.S,v 1.5 2008/08/04 21:29:28 matt Exp $")
+#endif
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(llabs, _llabs)
+WEAK_ALIAS(imaxabs, _llabs)
+#endif
+
+#ifdef WEAK_ALIAS
+ENTRY(_llabs)
+#else
+STRONG_ALIAS(imaxabs, llabs)
+ENTRY(llabs)
+#endif
+       movl    8(%esp),%edx
+       movl    4(%esp),%eax
+       testl   %edx,%edx
+       jns     1f
+       negl    %eax
+       adcl    $0,%edx
+       negl    %edx
+1:     ret
diff --git a/lib/nbsd_libc/arch/i386/string/Makefile.inc b/lib/nbsd_libc/arch/i386/string/Makefile.inc
new file mode 100644 (file)
index 0000000..c161174
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/07/30 20:57:16 dsl Exp $
+
+# objects built from assembler sources
+SRCS+= bcmp.S bcopy.S bzero.S ffs.S memchr.S memcmp.S \
+       memcpy.S memmove.S memset.S strcat.S strchr.S \
+       strcmp.S strcpy.S strlen.S strncmp.S strrchr.S swab.S
diff --git a/lib/nbsd_libc/arch/i386/string/bcmp.S b/lib/nbsd_libc/arch/i386/string/bcmp.S
new file mode 100644 (file)
index 0000000..3ea341e
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: bcmp.S,v 1.9 2007/11/12 18:41:59 ad Exp $")
+#endif
+
+ENTRY(bcmp)
+       pushl   %edi
+       pushl   %esi
+       movl    12(%esp),%edi
+       movl    16(%esp),%esi
+       xorl    %eax,%eax               /* clear return value */
+
+       movl    20(%esp),%ecx           /* compare by words */
+       shrl    $2,%ecx
+       repe
+       cmpsl
+       jne     L1
+
+       movl    20(%esp),%ecx           /* compare remainder by bytes */
+       andl    $3,%ecx
+       repe
+       cmpsb
+       je      L2
+
+L1:    incl    %eax
+L2:    popl    %esi
+       popl    %edi
+       ret
diff --git a/lib/nbsd_libc/arch/i386/string/bcopy.S b/lib/nbsd_libc/arch/i386/string/bcopy.S
new file mode 100644 (file)
index 0000000..35fb1df
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: bcopy.S,v 1.15 2005/02/09 18:15:16 christos Exp $      */
+
+#define BCOPY
+#include "memcpy.S"
diff --git a/lib/nbsd_libc/arch/i386/string/bzero.S b/lib/nbsd_libc/arch/i386/string/bzero.S
new file mode 100644 (file)
index 0000000..f837447
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: bzero.S,v 1.12 2005/02/09 18:15:16 christos Exp $      */
+
+#define BZERO
+#include "memset.S"
diff --git a/lib/nbsd_libc/arch/i386/string/index.S b/lib/nbsd_libc/arch/i386/string/index.S
new file mode 100644 (file)
index 0000000..bda26bb
--- /dev/null
@@ -0,0 +1,4 @@
+/* $NetBSD: index.S,v 1.14 2005/02/09 18:15:16 christos Exp $ */
+
+#define INDEX
+#include "strchr.S"
diff --git a/lib/nbsd_libc/arch/i386/string/rindex.S b/lib/nbsd_libc/arch/i386/string/rindex.S
new file mode 100644 (file)
index 0000000..f39cc2c
--- /dev/null
@@ -0,0 +1,4 @@
+/* $NetBSD: rindex.S,v 1.14 2005/02/09 18:15:16 christos Exp $ */
+
+#define RINDEX
+#include "strrchr.S"
diff --git a/lib/nbsd_libc/arch/i386/string/strncmp.S b/lib/nbsd_libc/arch/i386/string/strncmp.S
new file mode 100644 (file)
index 0000000..45b1ce2
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: strncmp.S,v 1.14 2005/08/03 22:59:50 rpaulo Exp $")
+#endif
+
+/*
+ * NOTE: I've unrolled the loop eight times: large enough to make a
+ * significant difference, and small enough not to totally trash the
+ * cache.
+ */
+
+ENTRY(strncmp)
+       pushl   %ebx
+       movl    8(%esp),%eax
+       movl    12(%esp),%ecx
+       movl    16(%esp),%edx
+       testl   %edx,%edx
+       jmp     L2                      /* Jump into the loop! */
+
+       _ALIGN_TEXT,0x90
+L1:    incl    %eax
+       incl    %ecx
+       decl    %edx
+L2:    jz      L4                      /* strings are equal */
+       movb    (%eax),%bl
+       testb   %bl,%bl
+       jz      L3
+       cmpb    %bl,(%ecx)
+       jne     L3
+
+       incl    %eax
+       incl    %ecx
+       decl    %edx
+       jz      L4
+       movb    (%eax),%bl
+       testb   %bl,%bl
+       jz      L3
+       cmpb    %bl,(%ecx)
+       jne     L3
+
+       incl    %eax
+       incl    %ecx
+       decl    %edx
+       jz      L4
+       movb    (%eax),%bl
+       testb   %bl,%bl
+       jz      L3
+       cmpb    %bl,(%ecx)
+       jne     L3
+
+       incl    %eax
+       incl    %ecx
+       decl    %edx
+       jz      L4
+       movb    (%eax),%bl
+       testb   %bl,%bl
+       jz      L3
+       cmpb    %bl,(%ecx)
+       jne     L3
+
+       incl    %eax
+       incl    %ecx
+       decl    %edx
+       jz      L4
+       movb    (%eax),%bl
+       testb   %bl,%bl
+       jz      L3
+       cmpb    %bl,(%ecx)
+       jne     L3
+
+       incl    %eax
+       incl    %ecx
+       decl    %edx
+       jz      L4
+       movb    (%eax),%bl
+       testb   %bl,%bl
+       jz      L3
+       cmpb    %bl,(%ecx)
+       jne     L3
+
+       incl    %eax
+       incl    %ecx
+       decl    %edx
+       jz      L4
+       movb    (%eax),%bl
+       testb   %bl,%bl
+       jz      L3
+       cmpb    %bl,(%ecx)
+       jne     L3
+
+       incl    %eax
+       incl    %ecx
+       decl    %edx
+       jz      L4
+       movb    (%eax),%bl
+       testb   %bl,%bl
+       jz      L3
+       cmpb    %bl,(%ecx)
+       je      L1
+
+       _ALIGN_TEXT,0x90
+L3:    movzbl  (%eax),%eax             /* unsigned comparison */
+       movzbl  (%ecx),%ecx
+       subl    %ecx,%eax
+       popl    %ebx
+       ret
+       _ALIGN_TEXT,0x90
+L4:    xorl    %eax,%eax
+       popl    %ebx
+       ret
diff --git a/lib/nbsd_libc/arch/i386/string/swab.S b/lib/nbsd_libc/arch/i386/string/swab.S
new file mode 100644 (file)
index 0000000..65f7903
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: swab.S,v 1.13 2007/11/12 18:42:00 ad Exp $")
+#endif
+
+/*
+ * On the i486, this code is negligibly faster than the code generated
+ * by gcc at about half the size.  If my i386 databook is correct, it
+ * should be considerably faster than the gcc code on a i386.
+ */
+
+ENTRY(swab)
+       pushl   %esi
+       pushl   %edi
+       movl    12(%esp),%esi
+       movl    16(%esp),%edi
+       movl    20(%esp),%ecx
+
+       shrl    $1,%ecx
+       testl   $7,%ecx                 # copy first group of 1 to 7 words
+       jz      L2                      # while swapping alternate bytes.
+       _ALIGN_TEXT,0x90
+L1:    lodsw
+       rorw    $8,%ax
+       stosw
+       decl    %ecx
+       testl   $7,%ecx
+       jnz     L1
+
+L2:    shrl    $3,%ecx                 # copy remainder 8 words at a time
+       jz      L4                      # while swapping alternate bytes.
+       _ALIGN_TEXT,0x90
+L3:    lodsw
+       rorw    $8,%ax
+       stosw
+       lodsw
+       rorw    $8,%ax
+       stosw
+       lodsw
+       rorw    $8,%ax
+       stosw
+       lodsw
+       rorw    $8,%ax
+       stosw
+       lodsw
+       rorw    $8,%ax
+       stosw
+       lodsw
+       rorw    $8,%ax
+       stosw
+       lodsw
+       rorw    $8,%ax
+       stosw
+       lodsw
+       rorw    $8,%ax
+       stosw
+       decl    %ecx
+       jnz     L3
+
+L4:    popl    %edi
+       popl    %esi
+       ret
diff --git a/lib/nbsd_libc/arch/i386/sys/__clone.S b/lib/nbsd_libc/arch/i386/sys/__clone.S
new file mode 100644 (file)
index 0000000..ef27f46
--- /dev/null
@@ -0,0 +1,110 @@
+/*     $NetBSD: __clone.S,v 1.3 2001/07/18 12:24:53 fvdl Exp $ */
+
+/*
+ * Copyright (c) 2001 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Frank van der Linden for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 <machine/asm.h>
+#include <sys/errno.h>
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(clone, __clone)
+#endif
+       .text
+
+/*
+ * int clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+ENTRY(__clone)
+       pushl   %ebp
+
+       /*
+        * Sanity checks: func and stack may not be NULL.
+        */
+       movl    8(%esp), %ebp
+       cmpl    $0,%ebp         /* function */
+       je      3f
+       movl    12(%esp),%eax   /* stack */
+       cmpl    $0,%eax
+       je      3f
+
+       /*
+        * Set up the stack for the clone.
+        */
+       movl    20(%esp),%ecx
+       movl    %ecx,-4(%eax)   /* argument */
+       leal    -4(%eax),%eax   /* sp points to arg */
+
+       pushl   %eax            /* stack */
+       pushl   20(%esp)        /* flags */
+       pushl   $0              /* dummy return address */
+
+       SYSTRAP(__clone)
+       jc      4f
+       cmpl    $0,%eax
+       jne     2f              /* we're the parent */
+       call    *%ebp           /* this is the clone, call the function */
+
+#ifdef PIC
+       PIC_PROLOGUE
+       pushl   %eax            /* clone does _exit(func(arg)); */
+       call    PIC_PLT(_C_LABEL(_exit))
+       addl    $4,%esp
+       PIC_EPILOGUE
+#else
+       pushl   %eax
+       call    _C_LABEL(_exit)
+       addl    $4,%esp
+#endif
+
+2:
+       addl    $12,%esp
+       popl    %ebp
+       ret
+3:
+       movl    $EINVAL,%eax
+       jmp     5f
+4:
+       addl    $12,%esp
+5:
+       popl    %ebp
+#ifdef PIC
+       PIC_PROLOGUE
+       movl    PIC_GOT(CERROR),%edx
+       PIC_EPILOGUE
+       jmp     *%edx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/i386/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/i386/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..dab72d1
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.12 2008/04/28 20:22:56 martin Exp $       */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigaction14_sigtramp.c,v 1.12 2008/04/28 20:22:56 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern const int __sigtramp_siginfo_2[];
+
+       /*
+        * If no sigaction, use the "default" trampoline since it won't
+        * be used.
+        */
+       if (act == NULL)
+               return  __sigaction_sigtramp(sig, act, oact, NULL, 0);
+
+#ifdef __LIBC12_SOURCE__
+       /*
+        * We select the non-SA_SIGINFO trampoline if SA_SIGINFO is not
+        * set in the sigaction.
+        */
+       if ((act->sa_flags & SA_SIGINFO) == 0) {
+               extern const int __sigtramp_sigcontext_1[];
+               int sav = errno;
+               int rv =  __sigaction_sigtramp(sig, act, oact,
+                   __sigtramp_sigcontext_1, 1);
+               if (rv >= 0 || errno != EINVAL)
+                       return rv;
+               errno = sav;
+       }
+#endif
+
+       /*
+        * If SA_SIGINFO was specified or the compatibility trampolines
+        * can't be used, use the siginfo trampoline.
+        */
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_2, 2);
+}
diff --git a/lib/nbsd_libc/arch/i386/sys/__sigtramp2.S b/lib/nbsd_libc/arch/i386/sys/__sigtramp2.S
new file mode 100644 (file)
index 0000000..c530bcd
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: __sigtramp2.S,v 1.4 2008/04/28 20:22:56 martin Exp $   */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+/*
+ * The i386 signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ *
+ * On entry, stack looks like:
+ *
+ *             ucontext structure                      [12+sizeof(siginfo_t)]
+ *             siginfo structure                       [12]
+ *             pointer to ucontext structure           [8]
+ *             pointer to siginfo structure            [4]
+ *     sp->    signal number                           [0]
+ */
+NENTRY(__sigtramp_siginfo_2)
+       leal    12+128(%esp),%eax       /* get address of ucontext */
+       movl    %eax,4(%esp)    /* put it in the argument slot */
+                               /* fake return address already there */
+       SYSTRAP(setcontext)     /* do setcontext */
+       movl    $-1,4(%esp)     /* if we return here, something is wrong */
+       SYSTRAP(exit)           /* exit */
diff --git a/lib/nbsd_libc/arch/i386/sys/__syscall.S b/lib/nbsd_libc/arch/i386/sys/__syscall.S
new file mode 100644 (file)
index 0000000..cb5db51
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: __syscall.S,v 1.3 2003/08/07 16:42:08 agc Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)syscall.s     5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __syscall.S,v 1.3 2003/08/07 16:42:08 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+ENTRY(__syscall)
+       pop     %ecx    /* rta */
+       pop     %eax    /* syscall number */
+       pop     %edx    /* junk */
+       push    %ecx
+       int     $0x80
+       push    %ecx    /* Keep stack frame consistant */
+       push    %ecx    /* Keep stack frame consistant */
+       jc      err
+       ret
+err:
+#ifdef PIC
+       PIC_PROLOGUE
+       mov     PIC_GOT(CERROR), %ecx
+       PIC_EPILOGUE
+       jmp     *%ecx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/i386/sys/__vfork14.S b/lib/nbsd_libc/arch/i386/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..2dc085d
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: __vfork14.S,v 1.8 2007/03/09 14:30:48 ad Exp $ */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)Ovfork.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __vfork14.S,v 1.8 2007/03/09 14:30:48 ad Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+/*
+ * pid = vfork();
+ *
+ * %edx == 0 in parent process, %edx == 1 in child process.
+ * %eax == pid of child in parent, %eax == pid of parent in child.
+ *
+ */
+ENTRY(__vfork14)
+       popl    %ecx            /* my rta into %ecx */
+       OSYSTRAP(__vfork14)     /* don't clobber %ecx */
+       jc      err
+       decl    %edx
+       andl    %edx,%eax
+       jmp     *%ecx
+err:
+       pushl   %ecx
+#ifdef PIC
+       PIC_PROLOGUE
+       mov     PIC_GOT(CERROR), %ecx
+       PIC_EPILOGUE
+       jmp     *%ecx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/i386/sys/brk.S b/lib/nbsd_libc/arch/i386/sys/brk.S
new file mode 100644 (file)
index 0000000..73e363c
--- /dev/null
@@ -0,0 +1,95 @@
+/*     $NetBSD: brk.S,v 1.21 2007/03/09 14:30:56 ad Exp $      */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)brk.s 5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: brk.S,v 1.21 2007/03/09 14:30:56 ad Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _end
+       .globl  _C_LABEL(__minbrk)
+       .globl  CURBRK
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(brk, _brk)
+#endif
+
+       .data
+_C_LABEL(__minbrk):
+       .long   _end
+       .text
+
+ENTRY(_brk)
+#ifdef PIC
+       movl    4(%esp),%ecx
+       PIC_PROLOGUE
+       movl    PIC_GOT(_C_LABEL(__minbrk)),%edx
+       PIC_EPILOGUE
+       cmpl    %ecx,(%edx)
+       jb      1f
+       movl    (%edx),%ecx
+       movl    %ecx,4(%esp)
+1:
+       OSYSTRAP(break) /* don't clobber %ecx */
+       jc      err
+       PIC_PROLOGUE
+       movl    PIC_GOT(CURBRK),%edx    # set up GOT addressing
+       PIC_EPILOGUE
+       movl    %ecx,(%edx)
+       xorl    %eax,%eax
+       ret
+err:
+       PIC_PROLOGUE
+       mov     PIC_GOT(CERROR),%edx
+       PIC_EPILOGUE
+       jmp     *%edx
+#else
+       movl    4(%esp),%ecx
+       cmpl    %ecx,_C_LABEL(__minbrk)
+       jb      1f
+       movl    _C_LABEL(__minbrk),%ecx
+       movl    %ecx,4(%esp)
+1:
+       OSYSTRAP(break) /* don't clobber %ecx */
+       jc      err
+       movl    %ecx,CURBRK
+       xorl    %eax,%eax
+       ret
+err:
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/i386/sys/cerror.S b/lib/nbsd_libc/arch/i386/sys/cerror.S
new file mode 100644 (file)
index 0000000..3a0c722
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: cerror.S,v 1.14 2003/08/07 16:42:08 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)cerror.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: cerror.S,v 1.14 2003/08/07 16:42:08 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _C_LABEL(__errno)
+
+_ENTRY(CERROR)
+       pushl   %eax
+#ifdef PIC
+       PIC_PROLOGUE
+       call    PIC_PLT(_C_LABEL(__errno))
+       PIC_EPILOGUE
+#else
+       call    _C_LABEL(__errno)
+#endif /* PIC */
+       popl    (%eax)
+       movl    $-1,%eax
+       movl    $-1,%edx
+       ret
diff --git a/lib/nbsd_libc/arch/i386/sys/exect.S b/lib/nbsd_libc/arch/i386/sys/exect.S
new file mode 100644 (file)
index 0000000..dacc450
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: exect.S,v 1.13 2003/08/07 16:42:08 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)exect.s       5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: exect.S,v 1.13 2003/08/07 16:42:08 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+#include <machine/psl.h>
+
+ENTRY(exect)
+       pushfl
+       orb     $(PSL_T>>8),1(%esp)
+       popfl
+       SYSTRAP(execve)
+#ifdef PIC
+       PIC_PROLOGUE
+       mov     PIC_GOT(CERROR), %ecx
+       PIC_EPILOGUE
+       jmp     *%ecx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/i386/sys/fork.S b/lib/nbsd_libc/arch/i386/sys/fork.S
new file mode 100644 (file)
index 0000000..9b96f9e
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: fork.S,v 1.9 2003/08/07 16:42:09 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)fork.s        5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: fork.S,v 1.9 2003/08/07 16:42:09 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+_SYSCALL(__fork,fork)
+       decl    %edx    /* from 1 to 0 in child, 0 to -1 in parent */
+       andl    %edx,%eax
+       ret             /* pid = fork(); */
diff --git a/lib/nbsd_libc/arch/i386/sys/getcontext.S b/lib/nbsd_libc/arch/i386/sys/getcontext.S
new file mode 100644 (file)
index 0000000..dc00027
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: getcontext.S,v 1.3 2008/04/28 20:22:56 martin Exp $    */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: getcontext.S,v 1.3 2008/04/28 20:22:56 martin Exp $")
+#endif /* SYSLIBC_SCCS && !lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext, _getcontext)
+#endif
+
+_SYSCALL(_getcontext,getcontext)
+       movl    4(%esp),%ecx
+       movl    0(%esp),%edx
+       movl    %edx,(36 + 14 * 4)(%ecx)        /* Adjust saved %eip ... */
+       leal    4(%esp),%edx
+       movl    %edx,(36 + 17 * 4)(%ecx)        /* ... and %esp. */
+       movl    $0,(36 + 11 * 4)(%ecx)          /* Arrange for return of 0. */
+       xorl    %eax,%eax
+       ret
diff --git a/lib/nbsd_libc/arch/i386/sys/pipe.S b/lib/nbsd_libc/arch/i386/sys/pipe.S
new file mode 100644 (file)
index 0000000..2b4d321
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: pipe.S,v 1.6 2003/08/07 16:42:09 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)pipe.s        5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: pipe.S,v 1.6 2003/08/07 16:42:09 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe, _pipe)
+#endif
+
+_SYSCALL(_pipe,pipe)
+       movl    4(%esp),%ecx
+       movl    %eax,(%ecx)
+       movl    %edx,4(%ecx)
+       xorl    %eax,%eax
+       ret
diff --git a/lib/nbsd_libc/arch/i386/sys/ptrace.S b/lib/nbsd_libc/arch/i386/sys/ptrace.S
new file mode 100644 (file)
index 0000000..1fd7acf
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: ptrace.S,v 1.16 2003/08/07 16:42:09 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)ptrace.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: ptrace.S,v 1.16 2003/08/07 16:42:09 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _C_LABEL(__errno)
+
+ENTRY(ptrace)
+#ifdef PIC
+       PIC_PROLOGUE
+       call    PIC_PLT(_C_LABEL(__errno))
+       PIC_EPILOGUE
+#else
+       call    _C_LABEL(__errno)
+#endif /* PIC */
+       xorl    %edx,%edx
+       movl    %edx,(%eax)
+       SYSTRAP(ptrace)
+       jc      err
+       ret
+err:
+#ifdef PIC
+       PIC_PROLOGUE
+       mov     PIC_GOT(CERROR), %ecx
+       PIC_EPILOGUE
+       jmp     *%ecx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/i386/sys/sbrk.S b/lib/nbsd_libc/arch/i386/sys/sbrk.S
new file mode 100644 (file)
index 0000000..359e500
--- /dev/null
@@ -0,0 +1,94 @@
+/*     $NetBSD: sbrk.S,v 1.19 2008/07/02 20:07:43 rmind Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sbrk.s        5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: sbrk.S,v 1.19 2008/07/02 20:07:43 rmind Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _end
+       .globl  CURBRK
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(sbrk, _sbrk)
+#endif
+
+       .data
+CURBRK:        .long   _end
+       .text
+
+ENTRY(_sbrk)
+#ifdef PIC
+       movl    4(%esp),%ecx
+       PIC_PROLOGUE
+       movl    PIC_GOT(CURBRK),%edx
+       PIC_EPILOGUE
+       movl    (%edx),%eax
+       test    %ecx,%ecx
+       jz      out
+       addl    %eax,%ecx
+       movl    %ecx,4(%esp)
+       OSYSTRAP(break) /* don't clobber %ecx */
+       jc      err
+       PIC_PROLOGUE
+       movl    PIC_GOT(CURBRK),%edx
+       PIC_EPILOGUE
+       movl    (%edx),%eax
+       movl    %ecx,(%edx)
+out:
+       ret
+err:
+       PIC_PROLOGUE
+       mov     PIC_GOT(CERROR),%edx
+       PIC_EPILOGUE
+       jmp     *%edx
+#else
+       movl    4(%esp),%ecx
+       movl    CURBRK,%eax
+       test    %ecx,%ecx
+       jz      out
+       addl    %eax,4(%esp)
+       OSYSTRAP(break) /* don't clobber %ecx */
+       jc      err
+       movl    CURBRK,%eax
+       addl    %ecx,CURBRK
+out:
+       ret
+err:
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/i386/sys/shmat.S b/lib/nbsd_libc/arch/i386/sys/shmat.S
new file mode 100644 (file)
index 0000000..0e78422
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: shmat.S,v 1.1 2000/07/07 08:20:52 itohy Exp $  */
+
+#include "SYS.h"
+
+RSYSCALL(shmat)
diff --git a/lib/nbsd_libc/arch/i386/sys/syscall.S b/lib/nbsd_libc/arch/i386/sys/syscall.S
new file mode 100644 (file)
index 0000000..3fe3f72
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: syscall.S,v 1.11 2003/08/07 16:42:09 agc Exp $ */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)syscall.s     5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: syscall.S,v 1.11 2003/08/07 16:42:09 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+ENTRY(syscall)
+       pop     %ecx    /* rta */
+       pop     %eax    /* syscall number */
+       push    %ecx
+       int     $0x80
+       push    %ecx    /* Keep stack frame consistant */
+       jc      err
+       ret
+err:
+#ifdef PIC
+       PIC_PROLOGUE
+       mov     PIC_GOT(CERROR), %ecx
+       PIC_EPILOGUE
+       jmp     *%ecx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/ia64/Makefile.inc b/lib/nbsd_libc/arch/ia64/Makefile.inc
new file mode 100644 (file)
index 0000000..6c135b1
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.3 2006/09/23 17:39:34 cherry Exp $
+
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S
diff --git a/lib/nbsd_libc/arch/ia64/SYS.h b/lib/nbsd_libc/arch/ia64/SYS.h
new file mode 100644 (file)
index 0000000..8ee7fb4
--- /dev/null
@@ -0,0 +1,74 @@
+/* $NetBSD: SYS.h,v 1.1 2006/09/10 21:22:33 cherry Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <sys/cdefs.h>
+
+#include <machine/asm.h>
+#include <sys/syscall.h>
+
+#define RET { br.ret.sptk.few rp;; }
+
+#define CALLSYS_ERROR(name)                                    \
+       CALLSYS_NOERROR(name)                                   \
+{      cmp.ne  p6,p0=r0,r10;                                   \
+(p6)    br.cond.sptk.few __cerror ;; }
+
+#define        SYSCALL(name)                                           \
+ENTRY(name,0);                         /* XXX # of args? */    \
+       CALLSYS_ERROR(name)
+
+#define        SYSCALL_NOERROR(name)                                   \
+ENTRY(name,0);                         /* XXX # of args? */    \
+       CALLSYS_NOERROR(name)
+
+#define        PSEUDO(label,name)                                      \
+ENTRY(label,0);                                /* XXX # of args? */    \
+       CALLSYS_ERROR(name);                                    \
+       RET;                                                    \
+END(label);
+
+#define        PSEUDO_NOERROR(label,name)                              \
+ENTRY(label,0);                                /* XXX # of args? */    \
+       CALLSYS_NOERROR(name);                                  \
+       RET;                                                    \
+END(label);
+
+#define RSYSCALL(name)                                         \
+       SYSCALL(name);                                          \
+       RET;                                                    \
+END(name)
+
+#define RSYSCALL_NOERROR(name)                                 \
+       SYSCALL_NOERROR(name);                                  \
+       RET;                                                    \
+END(name)
+
+#define        WSYSCALL(weak,strong)                                   \
+       WEAK_ALIAS(weak,strong);                                \
+       PSEUDO(strong,weak)
diff --git a/lib/nbsd_libc/arch/ia64/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/ia64/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..43505ea
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/09/22 12:09:24 cherry Exp $
+
+SRCS+= strtof.c
diff --git a/lib/nbsd_libc/arch/ia64/gdtoa/arith.h b/lib/nbsd_libc/arch/ia64/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..4fb91e5
--- /dev/null
@@ -0,0 +1,6 @@
+/*     $NetBSD: arith.h,v 1.1 2006/09/10 21:22:33 cherry Exp $ */
+
+#define IEEE_LITTLE_ENDIAN
+#ifndef _IEEE_FP
+#define Sudden_Underflow
+#endif
diff --git a/lib/nbsd_libc/arch/ia64/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/ia64/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..92b0734
--- /dev/null
@@ -0,0 +1,5 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/09/10 21:22:33 cherry Exp $ */
+
+#define f_QNAN 0x7fc00000
+#define d_QNAN0 0x0
+#define d_QNAN1 0x7ff80000
diff --git a/lib/nbsd_libc/arch/ia64/gen/Makefile.inc b/lib/nbsd_libc/arch/ia64/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..03edc59
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.4 2006/09/23 17:39:34 cherry Exp $
+
+SRCS+= bswap16.c bswap32.c bswap64.c
+
+SRCS+= flt_rounds.c fpgetround.c fpsetround.c fpgetmask.c fpsetmask.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c
diff --git a/lib/nbsd_libc/arch/ia64/gen/flt_rounds.c b/lib/nbsd_libc/arch/ia64/gen/flt_rounds.c
new file mode 100644 (file)
index 0000000..a48a423
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+/* __FBSDID("$FreeBSD: src/lib/libc/ia64/gen/flt_rounds.c,v 1.1 2004/07/19 08:17:24 das Exp $"); */
+
+#include <float.h>
+
+static const int map[] = {
+       1,      /* round to nearest */
+       3,      /* round to zero */
+       2,      /* round to negative infinity */
+       0       /* round to positive infinity */
+};
+
+int
+__flt_rounds(void)
+{
+       int x;
+
+       __asm("mov %0=ar.fpsr" : "=r" (x));
+        return (map[(x >> 10) & 0x03]);
+}
diff --git a/lib/nbsd_libc/arch/ia64/gen/fpgetmask.c b/lib/nbsd_libc/arch/ia64/gen/fpgetmask.c
new file mode 100644 (file)
index 0000000..6bf750c
--- /dev/null
@@ -0,0 +1,41 @@
+/*-
+ * Copyright (c) 2001 Doug Rabson
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+/* __FBSDID("$FreeBSD: src/lib/libc/ia64/gen/fpgetmask.c,v 1.4 2003/10/22 09:00:07 marcel Exp $"); */
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+/* XXX: Move to sysarchs() */
+fp_except
+fpgetmask(void)
+{
+       uint64_t fpsr;
+
+       __asm __volatile("mov %0=ar.fpsr" : "=r" (fpsr));
+       return (~fpsr & 0x3d);
+}
diff --git a/lib/nbsd_libc/arch/ia64/gen/fpgetround.c b/lib/nbsd_libc/arch/ia64/gen/fpgetround.c
new file mode 100644 (file)
index 0000000..407edce
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2003 Marcel Moolenaar
+ * 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 ``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 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.
+ *
+ * $FreeBSD: src/lib/libc/ia64/gen/fpgetround.c,v 1.1 2003/01/11 07:24:54 marcel Exp $
+ */
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+fp_rnd
+fpgetround(void)
+{
+       uint64_t fpsr;
+
+       __asm __volatile("mov %0=ar.fpsr" : "=r"(fpsr));
+       return ((fp_rnd)((fpsr >> 10) & 3));
+}
diff --git a/lib/nbsd_libc/arch/ia64/gen/fpsetmask.c b/lib/nbsd_libc/arch/ia64/gen/fpsetmask.c
new file mode 100644 (file)
index 0000000..ea87938
--- /dev/null
@@ -0,0 +1,44 @@
+/*-
+ * Copyright (c) 2001 Doug Rabson
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+/* __FBSDID("$FreeBSD: src/lib/libc/ia64/gen/fpsetmask.c,v 1.4 2003/10/22 09:00:07 marcel Exp $"); */
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+fp_except
+fpsetmask(fp_except mask)
+{
+       int64_t fpsr;
+       int64_t oldmask;
+
+       __asm __volatile("mov %0=ar.fpsr" : "=r" (fpsr));
+       oldmask = ~fpsr & 0x3d;
+       fpsr = (fpsr & ~0x3d) | (~mask & 0x3d);
+       __asm __volatile("mov ar.fpsr=%0" :: "r" (fpsr));
+       return (oldmask);
+}
diff --git a/lib/nbsd_libc/arch/ia64/gen/fpsetround.c b/lib/nbsd_libc/arch/ia64/gen/fpsetround.c
new file mode 100644 (file)
index 0000000..6955406
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2003 Marcel Moolenaar
+ * 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 ``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 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.
+ *
+ * $FreeBSD: src/lib/libc/ia64/gen/fpsetround.c,v 1.1 2003/01/11 07:24:54 marcel Exp $
+ */
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+fp_rnd
+fpsetround(fp_rnd rnd)
+{
+       uint64_t fpsr;
+       fp_rnd prev;
+
+       __asm __volatile("mov %0=ar.fpsr" : "=r"(fpsr));
+       prev = (fp_rnd)((fpsr >> 10) & 3);
+       fpsr = (fpsr & ~0xC00ULL) | ((unsigned int)rnd << 10);
+       __asm __volatile("mov ar.fpsr=%0" :: "r"(fpsr));
+       return (prev);
+}
diff --git a/lib/nbsd_libc/arch/ia64/net/Makefile.inc b/lib/nbsd_libc/arch/ia64/net/Makefile.inc
new file mode 100644 (file)
index 0000000..fa364cf
--- /dev/null
@@ -0,0 +1,2 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/09/10 21:22:33 cherry Exp $
+#      XXX: Stub
diff --git a/lib/nbsd_libc/arch/ia64/stdlib/Makefile.inc b/lib/nbsd_libc/arch/ia64/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..d1dda02
--- /dev/null
@@ -0,0 +1 @@
+#      $NetBSD: Makefile.inc,v 1.4 2009/07/31 20:39:59 dsl Exp $
diff --git a/lib/nbsd_libc/arch/ia64/string/Makefile.inc b/lib/nbsd_libc/arch/ia64/string/Makefile.inc
new file mode 100644 (file)
index 0000000..eebf40a
--- /dev/null
@@ -0,0 +1,2 @@
+#      $NetBSD: Makefile.inc,v 1.4 2009/07/30 20:57:16 dsl Exp $
+
diff --git a/lib/nbsd_libc/arch/ia64/sys/__clone.S b/lib/nbsd_libc/arch/ia64/sys/__clone.S
new file mode 100644 (file)
index 0000000..a62702e
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: __clone.S,v 1.1 2006/09/10 21:22:34 cherry Exp $ */
+       
+/* XXX:         Stub */
\ No newline at end of file
diff --git a/lib/nbsd_libc/arch/ia64/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/ia64/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..77451d0
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.2 2008/04/28 20:22:56 martin Exp $        */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/types.h>
+#include <stddef.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern const int __sigtramp_siginfo_2[];
+
+       /*
+        * If no sigaction, use the "default" trampoline since it won't
+        * be used.
+        */
+       if (act == NULL)
+               return  __sigaction_sigtramp(sig, act, oact, NULL, 0);
+
+#ifdef __LIBC12_SOURCE__
+       /*
+        * We select the non-SA_SIGINFO trampoline if SA_SIGINFO is not
+        * set in the sigaction.
+        */
+       if ((act->sa_flags & SA_SIGINFO) == 0) {
+               extern const int __sigtramp_sigcontext_1[];
+               int sav = errno;
+               int rv =  __sigaction_sigtramp(sig, act, oact,
+                   __sigtramp_sigcontext_1, 1);
+               if (rv >= 0 || errno != EINVAL)
+                       return rv;
+               errno = sav;
+       }
+#endif
+
+       /*
+        * If SA_SIGINFO was specified or the compatibility trampolines
+        * can't be used, use the siginfo trampoline.
+        */
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_2, 2);
+}
diff --git a/lib/nbsd_libc/arch/ia64/sys/__sigtramp2.S b/lib/nbsd_libc/arch/ia64/sys/__sigtramp2.S
new file mode 100644 (file)
index 0000000..a305ed4
--- /dev/null
@@ -0,0 +1,12 @@
+/*     $NetBSD: __sigtramp2.S,v 1.1 2006/09/23 17:39:34 cherry Exp $   */
+
+#include "SYS.h"
+
+/* XXX:         Fix this when we look at signal handling */
+       
+ENTRY(__sigtramp_siginfo_2, 2)
+       /* XXX:  get pointer to ucontext */
+       /* setcontext() ie. CALLSYS_NOERROR(setcontext)  */ 
+       /* get error code */
+       CALLSYS_NOERROR(exit) /* exit */
+END(__sigtramp_siginfo_2)
\ No newline at end of file
diff --git a/lib/nbsd_libc/arch/ia64/sys/__syscall.S b/lib/nbsd_libc/arch/ia64/sys/__syscall.S
new file mode 100644 (file)
index 0000000..e3312db
--- /dev/null
@@ -0,0 +1,7 @@
+/*     $NetBSD: __syscall.S,v 1.2 2006/09/22 12:09:25 cherry Exp $     */
+
+#include "SYS.h"
+
+       
+RSYSCALL(__syscall)
+
diff --git a/lib/nbsd_libc/arch/ia64/sys/__vfork14.S b/lib/nbsd_libc/arch/ia64/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..324396f
--- /dev/null
@@ -0,0 +1,8 @@
+/* $NetBSD: __vfork14.S,v 1.2 2006/09/22 17:59:47 cherry Exp $ */
+
+#include "SYS.h"
+
+SYSCALL(__vfork14)
+       /* XXX: watchout for return values for child/parent */ 
+       RET
+END(__vfork14) 
diff --git a/lib/nbsd_libc/arch/ia64/sys/brk.S b/lib/nbsd_libc/arch/ia64/sys/brk.S
new file mode 100644 (file)
index 0000000..8be7e90
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: brk.S,v 1.2 2006/09/23 17:39:34 cherry Exp $   */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+/* __FBSDID("$FreeBSD: src/lib/libc/ia64/sys/brk.S,v 1.4 2003/05/16 21:26:39 marcel Exp $"); */
+
+#include "SYS.h"
+
+       .globl  _end
+IMPORT(__curbrk, 8)
+
+       .data
+EXPORT(__minbrk)
+       .quad   _end
+
+       .text
+ENTRY(_brk, 1)
+       add     r14=@ltoff(__minbrk),gp ;;
+       ld8     r14=[r14] ;;
+       ld8     r14=[r14] ;;
+       cmp.ltu p6,p0=r32,r14 ;;
+(p6)   mov     r32=r14 ;;
+       st8     [sp]=r32
+       CALLSYS_ERROR(break)
+       ld8     r15=[sp]
+       add     r14=@ltoff(__curbrk),gp ;;
+       ld8     r14=[r14] ;;
+       st8     [r14]=r15
+       mov     ret0=0
+       br.ret.sptk.few rp
+END(_brk)
diff --git a/lib/nbsd_libc/arch/ia64/sys/cerror.S b/lib/nbsd_libc/arch/ia64/sys/cerror.S
new file mode 100644 (file)
index 0000000..7698241
--- /dev/null
@@ -0,0 +1,48 @@
+/* $NetBSD: cerror.S,v 1.2 2006/09/22 17:59:47 cherry Exp $ */
+       
+/*-
+ * Copyright (c) 2000 Doug Rabson
+ * 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.
+ */
+
+#include <machine/asm.h>
+/* __FBSDID("$FreeBSD: src/lib/libc/ia64/sys/cerror.S,v 1.2 2003/03/03 01:09:46 obrien Exp $"); */
+
+
+ENTRY(__cerror, 0)
+       alloc   loc0=ar.pfs,0,3,1,0
+       ;;
+       mov     loc1=rp
+       mov     loc2=ret0
+       mov     out0=ret0
+       ;;
+       br.call.sptk.few rp=__errno
+       st4     [ret0]=loc2
+       ;;
+       mov     ret0=-1
+       mov     ar.pfs=loc0
+       mov     rp=loc1
+       ;;
+       br.ret.sptk.few rp
+END(__cerror)
diff --git a/lib/nbsd_libc/arch/ia64/sys/exect.S b/lib/nbsd_libc/arch/ia64/sys/exect.S
new file mode 100644 (file)
index 0000000..5a78ec0
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: exect.S,v 1.1 2006/09/10 21:22:34 cherry Exp $ */
+       
+/* XXX:         Stub */
\ No newline at end of file
diff --git a/lib/nbsd_libc/arch/ia64/sys/fork.S b/lib/nbsd_libc/arch/ia64/sys/fork.S
new file mode 100644 (file)
index 0000000..c0df388
--- /dev/null
@@ -0,0 +1,9 @@
+/* $NetBSD: fork.S,v 1.2 2006/09/23 17:39:34 cherry Exp $ */
+       
+#include "SYS.h"
+
+ENTRY(__fork, 0)
+       CALLSYS_ERROR(fork)
+       /* XXX:  get return value for child */
+       RET
+END(__fork)
\ No newline at end of file
diff --git a/lib/nbsd_libc/arch/ia64/sys/getcontext.S b/lib/nbsd_libc/arch/ia64/sys/getcontext.S
new file mode 100644 (file)
index 0000000..ea491ab
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: getcontext.S,v 1.1 2006/09/10 21:22:34 cherry Exp $ */
+       
+/* XXX:         Stub */
\ No newline at end of file
diff --git a/lib/nbsd_libc/arch/ia64/sys/pipe.S b/lib/nbsd_libc/arch/ia64/sys/pipe.S
new file mode 100644 (file)
index 0000000..e545e5a
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: pipe.S,v 1.2 2006/09/23 17:39:34 cherry Exp $  */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+/* __FBSDID("$FreeBSD: src/lib/libc/ia64/sys/pipe.S,v 1.4 2003/05/16 21:26:39 marcel Exp $"); */
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe, _pipe)
+#endif
+/* XXX:         Relook  param passing  */
+       
+ENTRY(_pipe, 1)
+       st8             [sp]=r32
+       CALLSYS_ERROR(pipe)
+       ld8             r14=[sp]
+       ;;
+       st4             [r14]=ret0,4
+       ;;
+       st4             [r14]=ret1
+       mov             ret0=0
+       br.ret.sptk.few rp
+END(_pipe)
diff --git a/lib/nbsd_libc/arch/ia64/sys/ptrace.S b/lib/nbsd_libc/arch/ia64/sys/ptrace.S
new file mode 100644 (file)
index 0000000..bea78b2
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: ptrace.S,v 1.1 2006/09/10 21:22:34 cherry Exp $ */
+       
+/* XXX:         Stub */
\ No newline at end of file
diff --git a/lib/nbsd_libc/arch/ia64/sys/sbrk.S b/lib/nbsd_libc/arch/ia64/sys/sbrk.S
new file mode 100644 (file)
index 0000000..2340e2f
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: sbrk.S,v 1.2 2006/09/23 17:39:34 cherry Exp $  */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+/* __FBSDID("$FreeBSD: src/lib/libc/ia64/sys/sbrk.S,v 1.5 2003/05/16 21:26:39 marcel Exp $"); */
+
+#include "SYS.h"
+
+       .globl  _end
+
+       .data
+EXPORT(__curbrk)
+       .quad   _end
+
+       .text
+ENTRY(_sbrk, 1)
+       add     r14 = @ltoff(__curbrk), gp
+       ;;
+       ld8     r14 = [r14]
+       cmp.eq  p6, p0 = r32, r0
+       ;;
+       ld8     ret0 = [r14]
+(p6)   br.ret.sptk.few rp
+       ;;
+       add     r32 = ret0, r32
+       ;;
+       st8     [sp] = r32
+       CALLSYS_ERROR(break)
+       ld8     r15 = [sp]
+       add     r14 = @ltoff(__curbrk), gp
+       ;;
+       ld8     r14 = [r14]
+       ;;
+       ld8     ret0 = [r14]
+       st8     [r14] = r15
+       br.ret.sptk.few rp
+END(_sbrk)
diff --git a/lib/nbsd_libc/arch/ia64/sys/shmat.S b/lib/nbsd_libc/arch/ia64/sys/shmat.S
new file mode 100644 (file)
index 0000000..cacc700
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: shmat.S,v 1.1 2006/09/10 21:22:34 cherry Exp $ */
+       
+/* XXX:         Stub */
\ No newline at end of file
diff --git a/lib/nbsd_libc/arch/ia64/sys/syscall.S b/lib/nbsd_libc/arch/ia64/sys/syscall.S
new file mode 100644 (file)
index 0000000..21359c5
--- /dev/null
@@ -0,0 +1,7 @@
+/* $NetBSD: syscall.S,v 1.2 2006/09/22 12:09:25 cherry Exp $ */
+       
+#include "SYS.h"
+
+       
+RSYSCALL(syscall)
+
diff --git a/lib/nbsd_libc/arch/m68k/DEFS.h b/lib/nbsd_libc/arch/m68k/DEFS.h
new file mode 100644 (file)
index 0000000..1abc2d6
--- /dev/null
@@ -0,0 +1,3 @@
+/*     $NetBSD: DEFS.h,v 1.3 1995/12/13 22:21:23 thorpej Exp $ */
+
+#include <machine/asm.h>
diff --git a/lib/nbsd_libc/arch/m68k/Makefile.inc b/lib/nbsd_libc/arch/m68k/Makefile.inc
new file mode 100644 (file)
index 0000000..abe01f4
--- /dev/null
@@ -0,0 +1,10 @@
+#      $NetBSD: Makefile.inc,v 1.13 2008/02/09 02:41:06 mrg Exp $
+
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S __mmap.S
+
+ASM+=  _lwp_getprivate.S mremap.S
+
+.if ${MKSOFTFLOAT} != "no"
+CPPFLAGS+= -DSOFTLOFLOAT_NEED_FIXUNS -DSOFTFLOAT -DSOFTFLOATM68K_FOR_GCC
+.  include <softfloat/Makefile.inc>
+.endif
diff --git a/lib/nbsd_libc/arch/m68k/SYS.h b/lib/nbsd_libc/arch/m68k/SYS.h
new file mode 100644 (file)
index 0000000..cf70998
--- /dev/null
@@ -0,0 +1,97 @@
+/*     $NetBSD: SYS.h,v 1.16 2003/08/07 16:42:09 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)SYS.h 5.5 (Berkeley) 5/7/91
+ */
+
+#include <sys/syscall.h>
+#include <machine/asm.h>
+
+#ifdef __STDC__
+#define        IMMEDIATE       #
+#define SYSTRAP(x)     movl IMMEDIATE SYS_ ## x ## ,%d0; trap IMMEDIATE 0
+#else
+#define SYSTRAP(x)     movl #SYS_/**/x,%d0; trap #0
+#endif
+
+#ifdef __ELF__
+#define CERROR         _C_LABEL(__cerror)
+#define CURBRK         _C_LABEL(__curbrk)
+#else
+#define CERROR         _ASM_LABEL(cerror)
+#define CURBRK         _ASM_LABEL(curbrk)
+#endif
+
+#define _SYSCALL_NOERROR(x,y)                                          \
+       ENTRY(x);                                                       \
+       SYSTRAP(y)
+
+#define _SYSCALL(x,y)                                                  \
+       .even;                                                          \
+       err: jra PIC_PLT(CERROR);                                       \
+       _SYSCALL_NOERROR(x,y);                                          \
+       jcs err
+
+#define SYSCALL_NOERROR(x)                                             \
+       _SYSCALL_NOERROR(x,x)
+
+#define SYSCALL(x)                                                     \
+       _SYSCALL(x,x)
+
+#define PSEUDO_NOERROR(x,y)                                            \
+       _SYSCALL_NOERROR(x,y);                                          \
+       rts
+
+#define PSEUDO(x,y)                                                    \
+       _SYSCALL(x,y);                                                  \
+       rts
+
+#define RSYSCALL_NOERROR(x)                                            \
+       PSEUDO_NOERROR(x,x)
+
+#define RSYSCALL(x)                                                    \
+       PSEUDO(x,x)
+
+#ifdef WEAK_ALIAS
+#define        WSYSCALL(weak,strong)                                           \
+       WEAK_ALIAS(weak,strong);                                        \
+       PSEUDO(strong,weak)
+#else
+#define        WSYSCALL(weak,strong)                                           \
+       PSEUDO(weak,weak)
+#endif
+
+#define        ASMSTR          .asciz
+
+       .globl  CERROR
diff --git a/lib/nbsd_libc/arch/m68k/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/m68k/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..66da1e5
--- /dev/null
@@ -0,0 +1,8 @@
+#      $NetBSD: Makefile.inc,v 1.3 2006/03/21 22:50:13 he Exp $
+
+SRCS+= strtof.c
+
+.if ${MACHINE_ARCH} != "m68000"
+SRCS+= strtold_pxL.c
+SRCS+= strtopxL.c
+.endif
diff --git a/lib/nbsd_libc/arch/m68k/gdtoa/arith.h b/lib/nbsd_libc/arch/m68k/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..4674f62
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: arith.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define IEEE_BIG_ENDIAN
diff --git a/lib/nbsd_libc/arch/m68k/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/m68k/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..eb22e0b
--- /dev/null
@@ -0,0 +1,10 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define f_QNAN 0x7fc00000
+#define d_QNAN0 0x7ff80000
+#define d_QNAN1 0x0
+#ifndef __mc68010__
+#define ld_QNAN0 0x7fff0000
+#define ld_QNAN1 0x40000000
+#define ld_QNAN2 0x0
+#endif
diff --git a/lib/nbsd_libc/arch/m68k/gen/Makefile.inc b/lib/nbsd_libc/arch/m68k/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..f1ed046
--- /dev/null
@@ -0,0 +1,72 @@
+#      $NetBSD: Makefile.inc,v 1.30 2009/12/06 07:12:17 uebayasi Exp $
+
+SRCS+= alloca.S fabs.S
+
+# Common ieee754 constants and functions
+SRCS+= infinityf_ieee754.c infinity_ieee754.c
+SRCS+= fpclassifyf_ieee754.c fpclassifyd_ieee754.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c
+SRCS+= isfinitef_ieee754.c isfinited_ieee754.c
+SRCS+= signbitf_ieee754.c signbitd_ieee754.c
+
+SRCS+= nanf.c
+
+# 68000-based machines use a double-extended `long double' type
+# for which the generic ieee754 versions can be used
+.if    ${MACHINE_ARCH} == "m68000"
+SRCS+= infinityl_dbl_ieee754.c
+.else
+SRCS+= infinityl.c
+SRCS+= fpclassifyl.c isfinitel.c isinfl.c isnanl.c signbitl.c
+.endif
+
+SRCS+= ashlsi3.S ashrsi3.S \
+       lshlsi3.S lshrsi3.S \
+       negdf2.S negsf2.S
+SRCS+= bswap16.S bswap32.S bswap64.S
+SRCS+= _lwp.c
+
+# 68000-based machines build with a libgcc that includes
+# much of the (soft)float and integer support that would 
+# otherwise be compiled here.
+.if    (${MACHINE_ARCH} == "m68000" || ${MKSOFTFLOAT} == "yes")
+SRCS+= modf_ieee754.c                  # generic ieee754 version
+SRCS+= flt_rounds_softfloat.S
+.if ${MKSOFTFLOAT} != "yes"
+SRCS+= fpfake.c
+.endif
+.else
+SRCS+= modf.S
+SRCS+= flt_rounds.S fpgetmask.S fpgetround.S fpgetsticky.S fpsetmask.S \
+       fpsetround.S fpsetsticky.S
+SRCS+= adddf3.S addsf3.S cmpdf2.S cmpsf2.S divdf3.S \
+       divsf3.S divsi3.S extendsfdf2.S fixdfsi.S fixunsdfsi.S \
+       floatsidf.S modsi3.S muldf3.S mulsf3.S mulsi3.S \
+       subdf3.S subsf3.S truncdfsf2.S udivsi3.S \
+       umodsi3.S umulsi3.S
+.endif
+
+SRCS+= setjmp.S longjmp.c
+SRCS+= _setjmp.S
+SRCS+= sigsetjmp.S
+
+SRCS+= makecontext.c resumecontext.S swapcontext.S
+
+.ifdef M68040
+SRCS+= ldexp_ieee754.c                 # generic ieee754 version
+.elifdef MKSOFTFLOAT
+SRCS+= ldexp_ieee754.c                 # generic ieee754 version
+.elifdef M68060
+SRCS+= ldexp_ieee754.c                 # generic ieee754 version
+.elif  ${MACHINE_ARCH} == "m68000"
+SRCS+= ldexp_ieee754.c                 # generic ieee754 version
+.else
+SRCS+= ldexp_881.c
+.endif
+
+LSRCS.m68k.gen=        Lint_bswap16.c Lint_bswap32.c Lint_bswap64.c \
+               Lint_resumecontext.c Lint_swapcontext.c
+LSRCS+=                ${LSRCS.m68k.gen}
+DPSRCS+=       ${LSRCS.m68k.gen}
+CLEANFILES+=   ${LSRCS.m68k.gen}
diff --git a/lib/nbsd_libc/arch/m68k/gen/_lwp.c b/lib/nbsd_libc/arch/m68k/gen/_lwp.c
new file mode 100644 (file)
index 0000000..6d6e093
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: _lwp.c,v 1.5 2008/04/28 20:22:56 martin Exp $  */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Nathan J. Williams and Steve C. Woodford.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.5 2008/04/28 20:22:56 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+
+void
+_lwp_makecontext(ucontext_t *u, void (*start)(void *),
+    void *arg, void *private, caddr_t stack_base, size_t stack_size)
+{
+       void **sp;
+
+       getcontext(u);
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+
+       u->uc_mcontext.__gregs[_REG_PC] = (int)start;
+       
+       sp = (void **) (stack_base + stack_size);
+       
+       *--sp = arg;
+       *--sp = (void *) _lwp_exit;
+
+       u->uc_mcontext.__gregs[_REG_A7] = (int) sp;
+}
diff --git a/lib/nbsd_libc/arch/m68k/gen/_setjmp.S b/lib/nbsd_libc/arch/m68k/gen/_setjmp.S
new file mode 100644 (file)
index 0000000..4efad38
--- /dev/null
@@ -0,0 +1,88 @@
+/*     $NetBSD: _setjmp.S,v 1.7 2003/08/07 16:42:10 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)_setjmp.s      5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: _setjmp.S,v 1.7 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     _longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     _setjmp(a)
+ * by restoring registers from the stack,
+ * The previous signal state is NOT restored.
+ */
+
+ENTRY(_setjmp)
+       movl    %sp@(4),%a0     /* save area pointer */
+       clrl    %a0@+           /* no old onstack */
+       clrl    %a0@+           /* no old sigmask */
+       movl    %sp,%a0@+       /* save old SP */
+       movl    %a6,%a0@+       /* save old FP */
+       clrl    %a0@+           /* no old AP */
+       movl    %sp@,%a0@+      /* save old PC */
+       clrl    %a0@+           /* clear PS */
+       moveml  #0x3CFC,%a0@    /* save other non-scratch regs */
+       clrl    %d0             /* return zero */
+       rts
+
+ENTRY(_longjmp)
+       movl    %sp@(4),%a0     /* save area pointer */
+       addql   #8,%a0          /* skip onstack/sigmask */
+       tstl    %a0@            /* ensure non-zero SP */
+       jeq     botch           /* oops! */
+       movl    %sp@(8),%d0     /* grab return value */
+       jne     ok              /* non-zero ok */
+       moveq   #1,%d0          /* else make non-zero */
+ok:
+       movl    %a0@+,%sp       /* restore SP */
+       movl    %a0@+,%a6       /* restore FP */
+       addql   #4,%a0          /* skip AP */
+       movl    %a0@+,%sp@      /* restore PC */
+       moveml  %a0@(4),#0x3CFC /* restore non-scratch regs */
+       rts
+
+botch:
+       jbsr    PIC_PLT(_C_LABEL(longjmperror))
+       stop    #0
diff --git a/lib/nbsd_libc/arch/m68k/gen/adddf3.S b/lib/nbsd_libc/arch/m68k/gen/adddf3.S
new file mode 100644 (file)
index 0000000..da3aa18
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: adddf3.S,v 1.6 2003/08/07 16:42:10 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)adddf3.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: adddf3.S,v 1.6 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* double + double */
+ENTRY(__adddf3)
+       fmoved  %sp@(4),%fp0
+       faddd   %sp@(12),%fp0
+#ifndef __SVR4_ABI__
+       fmoved  %fp0,%sp@-
+       movel   %sp@+,%d0
+       movel   %sp@+,%d1
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/addsf3.S b/lib/nbsd_libc/arch/m68k/gen/addsf3.S
new file mode 100644 (file)
index 0000000..3c243db
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: addsf3.S,v 1.6 2003/08/07 16:42:10 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)addsf3.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: addsf3.S,v 1.6 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* single + single */
+ENTRY(__addsf3)
+       fmoves  %sp@(4),%fp0
+       fadds   %sp@(8),%fp0
+#ifndef __SVR4_ABI__
+       fmoves  %fp0,%d0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/alloca.S b/lib/nbsd_libc/arch/m68k/gen/alloca.S
new file mode 100644 (file)
index 0000000..1c305c5
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: alloca.S,v 1.6 2003/08/07 16:42:10 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)alloca.s       5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: alloca.S,v 1.6 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* like alloc, but automatic free in return */
+
+ENTRY(alloca)
+       movl    %sp@,%a1        /* save return addr */
+       movl    %sp,%d0         /* get current SP value */
+       subl    %sp@(4),%d0     /* allocate requested space */
+       andb    #~3,%d0         /* longword align for efficiency */
+       addql   #8,%d0          /* reuse space of call frame */
+       movl    %d0,%sp         /* set new SP value */
+       lea     %sp@(-4),%sp    /* account for argument pop in caller */
+#ifdef __SVR4_ABI__
+       moveal  %d0,%a0
+#endif
+       jmp     %a1@            /* funny return */
diff --git a/lib/nbsd_libc/arch/m68k/gen/ashlsi3.S b/lib/nbsd_libc/arch/m68k/gen/ashlsi3.S
new file mode 100644 (file)
index 0000000..dc56771
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: ashlsi3.S,v 1.5 2003/08/07 16:42:10 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)ashlsi3.s      5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: ashlsi3.S,v 1.5 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* int << int */
+ENTRY(__ashlsi3)
+       movel   %sp@(8),%d1
+       movel   %sp@(4),%d0
+       asll    %d1,%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/ashrsi3.S b/lib/nbsd_libc/arch/m68k/gen/ashrsi3.S
new file mode 100644 (file)
index 0000000..9ea73ce
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: ashrsi3.S,v 1.5 2003/08/07 16:42:10 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)ashrsi3.s      5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: ashrsi3.S,v 1.5 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* int >> int */
+ENTRY(__ashrsi3)
+       movel   %sp@(8),%d1
+       movel   %sp@(4),%d0
+       asrl    %d1,%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/cmpdf2.S b/lib/nbsd_libc/arch/m68k/gen/cmpdf2.S
new file mode 100644 (file)
index 0000000..3322c11
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: cmpdf2.S,v 1.5 2003/08/07 16:42:10 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)cmpdf2.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: cmpdf2.S,v 1.5 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* double > double: 1 */
+/* double < double: -1 */
+/* double == double: 0 */
+ENTRY(__cmpdf2)
+       fmoved  %sp@(4),%fp0
+       fcmpd   %sp@(12),%fp0
+       fbgt    Lagtb
+       fslt    %d0
+       extbl   %d0
+       rts
+Lagtb:
+       moveq   #1,%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/cmpsf2.S b/lib/nbsd_libc/arch/m68k/gen/cmpsf2.S
new file mode 100644 (file)
index 0000000..d42dd84
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: cmpsf2.S,v 1.5 2003/08/07 16:42:10 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)cmpsf2.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: cmpsf2.S,v 1.5 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* single > single: 1 */
+/* single < single: -1 */
+/* single == single: 0 */
+ENTRY(__cmpsf2)
+       fmoves  %sp@(4),%fp0
+       fcmps   %sp@(8),%fp0
+       fbgt    Lagtb
+       fslt    %d0
+       extbl   %d0
+       rts
+Lagtb:
+       moveq   #1,%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/divdf3.S b/lib/nbsd_libc/arch/m68k/gen/divdf3.S
new file mode 100644 (file)
index 0000000..3611290
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: divdf3.S,v 1.6 2003/08/07 16:42:10 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)divdf3.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: divdf3.S,v 1.6 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* double / double */
+ENTRY(__divdf3)
+       fmoved  %sp@(4),%fp0
+       fdivd   %sp@(12),%fp0
+#ifndef __SVR4_ABI__
+       fmoved  %fp0,%sp@-
+       movel   %sp@+,%d0
+       movel   %sp@+,%d1
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/divsf3.S b/lib/nbsd_libc/arch/m68k/gen/divsf3.S
new file mode 100644 (file)
index 0000000..219f223
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: divsf3.S,v 1.6 2003/08/07 16:42:10 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)divsf3.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: divsf3.S,v 1.6 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* single / single */
+ENTRY(__divsf3)
+       fmoves  %sp@(4),%fp0
+       fdivs   %sp@(8),%fp0
+#ifndef __SVR4_ABI__
+       fmoves  %fp0,%d0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/extendsfdf2.S b/lib/nbsd_libc/arch/m68k/gen/extendsfdf2.S
new file mode 100644 (file)
index 0000000..2ba6178
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: extendsfdf2.S,v 1.6 2003/08/07 16:42:10 agc Exp $      */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)extendsfdf2.s  5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: extendsfdf2.S,v 1.6 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* (double) float */
+ENTRY(__extendsfdf2)
+       fmoves  %sp@(4),%fp0
+#ifndef __SVR4_ABI__
+       fmoved  %fp0,%sp@-
+       movel   %sp@+,%d0
+       movel   %sp@+,%d1
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/fabs.S b/lib/nbsd_libc/arch/m68k/gen/fabs.S
new file mode 100644 (file)
index 0000000..b88bcdc
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: fabs.S,v 1.8 2008/04/28 20:22:56 martin Exp $  */
+
+/*-
+ * Copyright (c) 1996 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by 
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+RCSID("$NetBSD: fabs.S,v 1.8 2008/04/28 20:22:56 martin Exp $")
+
+ENTRY(fabs)
+#if defined(__SVR4_ABI__) && defined(__HAVE_68881__)
+       bclr    #31,%sp@(4)
+       fmoved  %sp@(4),%fp0
+#else
+       movl    %sp@(4),%d0
+       movl    %sp@(8),%d1
+       bclr    #31,%d0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/fixdfsi.S b/lib/nbsd_libc/arch/m68k/gen/fixdfsi.S
new file mode 100644 (file)
index 0000000..6ef5b56
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: fixdfsi.S,v 1.5 2003/08/07 16:42:10 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)fixdfsi.s      5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: fixdfsi.S,v 1.5 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* (int) double */
+ENTRY(__fixdfsi)
+       fintrzd %sp@(4),%fp0
+       fmovel  %fp0,%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/fixunsdfsi.S b/lib/nbsd_libc/arch/m68k/gen/fixunsdfsi.S
new file mode 100644 (file)
index 0000000..57669d6
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: fixunsdfsi.S,v 1.5 2003/08/07 16:42:10 agc Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)fixunsdfsi.s   5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: fixunsdfsi.S,v 1.5 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* (unsigned) double */
+ENTRY(__fixunsdfsi)
+       fintrzd %sp@(4),%fp0
+       fcmpd   #0r2147483648.0,%fp0
+       fbge    Lwaybig
+       fmovel  %fp0,%d0
+       rts
+Lwaybig:
+       fsubd   #0r2147483648.0,%fp0
+       fmovel  %fp0,%d0
+       bset    #31,%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/floatsidf.S b/lib/nbsd_libc/arch/m68k/gen/floatsidf.S
new file mode 100644 (file)
index 0000000..d4fe49a
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: floatsidf.S,v 1.6 2003/08/07 16:42:10 agc Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)floatsidf.s    5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: floatsidf.S,v 1.6 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* (double) int */
+ENTRY(__floatsidf)
+       fmovel  %sp@(4),%fp0
+#ifndef __SVR4_ABI__
+       fmoved  %fp0,%sp@-
+       movel   %sp@+,%d0
+       movel   %sp@+,%d1
+#endif
+       rts
+
diff --git a/lib/nbsd_libc/arch/m68k/gen/flt_rounds.S b/lib/nbsd_libc/arch/m68k/gen/flt_rounds.S
new file mode 100644 (file)
index 0000000..051e710
--- /dev/null
@@ -0,0 +1,25 @@
+/*     $NetBSD: flt_rounds.S,v 1.9 2000/12/04 12:02:08 is Exp $        */
+
+/*
+ * Written by J.T. Conklin, Apr 6, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+       .text
+       .even
+#if 0
+/* XXX This is, effectively, an exclusive-or with 1 operation. */
+_map:
+       .byte 1         /* round to nearest */
+       .byte 0         /* round to zero */
+       .byte 3         /* round to negative infinity */
+       .byte 2         /* round to positive infinity */
+#endif
+
+ENTRY(__flt_rounds)
+       fmovel %fpcr,%d0
+       bfextu %d0{#26:#2},%d0
+       eorib #1,%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/flt_rounds_softfloat.S b/lib/nbsd_libc/arch/m68k/gen/flt_rounds_softfloat.S
new file mode 100644 (file)
index 0000000..f271b24
--- /dev/null
@@ -0,0 +1,32 @@
+/*     $NetBSD: flt_rounds_softfloat.S,v 1.2 2004/09/26 21:13:27 jmmv Exp $    */
+
+/*
+ * Written by J.T. Conklin, Apr 6, 1995
+ * Public domain.
+
+ * Broken by Bruce O'Neel Aug 4 2003
+       gcc no longer seems to export fpCCR so this fails.
+       for now just return 0.
+ */
+
+#include <machine/asm.h>
+
+       .text
+       .even
+
+       /* NB: this is tied to the gcc-2.95 lb1sf68.asm: */
+_map:
+       .byte 1         /* round to nearest */
+       .byte 0         /* round to zero */
+       .byte 2         /* round to positive infinity */
+       .byte 3         /* round to negative infinity */
+
+ENTRY(__flt_rounds)
+       /* lea  _C_LABEL(_fpCCR),%a0    | check the rounding mode */
+       /* movew        %a0@(6),%d0     | rounding mode in d0 */
+       /* lea  _map,%a0 */
+       moveb   #0,%d0
+       rts
+
+
+               
diff --git a/lib/nbsd_libc/arch/m68k/gen/fpclassifyl.c b/lib/nbsd_libc/arch/m68k/gen/fpclassifyl.c
new file mode 100644 (file)
index 0000000..5caeebf
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: fpclassifyl.c,v 1.3 2008/04/28 20:22:56 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpclassifyl.c,v 1.3 2008/04/28 20:22:56 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <assert.h>
+#include <math.h>
+
+/*
+ * 7.12.3.1 fpclassify - classify real floating type
+ *          IEEE 754 compatible 80-bit extended-precision Motorola 68k version
+ */
+int
+__fpclassifyl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       _DIAGASSERT(u.extu_ext.ext_zero == 0);
+
+       if (u.extu_ext.ext_exp == 0 &&
+           (u.extu_ext.ext_frach & 0x80000000) == 0) {
+               if ((u.extu_ext.ext_frach & 0x7fffffff) == 0 &&
+                   u.extu_ext.ext_fracl == 0)
+                       return FP_ZERO;
+               else
+                       return FP_SUBNORMAL;
+       } else if (u.extu_ext.ext_exp == EXT_EXP_INFNAN) {
+               if ((u.extu_ext.ext_frach & 0x7fffffff) == 0 &&
+                   u.extu_ext.ext_fracl == 0)
+                       return FP_INFINITE;
+               else
+                       return FP_NAN;
+       }
+
+       return FP_NORMAL;
+}
diff --git a/lib/nbsd_libc/arch/m68k/gen/fpfake.c b/lib/nbsd_libc/arch/m68k/gen/fpfake.c
new file mode 100644 (file)
index 0000000..b2835d4
--- /dev/null
@@ -0,0 +1,37 @@
+#include <ieeefp.h>
+
+fp_except
+fpgetmask(void)
+{
+       return 0;
+}
+
+fp_rnd
+fpgetround(void)
+{
+       return 0;
+}
+
+fp_except
+fpgetsticky(void)
+{
+       return 0;
+}
+
+fp_except
+fpsetmask(fp_except mask)
+{
+       return 0;
+}
+
+fp_rnd
+fpsetround(fp_rnd rnd_dir)
+{
+       return 0;
+}
+
+fp_except
+fpsetsticky(fp_except sticky)
+{
+       return 0;
+}
diff --git a/lib/nbsd_libc/arch/m68k/gen/fpgetmask.S b/lib/nbsd_libc/arch/m68k/gen/fpgetmask.S
new file mode 100644 (file)
index 0000000..3410585
--- /dev/null
@@ -0,0 +1,18 @@
+/*     $NetBSD: fpgetmask.S,v 1.7 2002/01/13 21:45:44 thorpej Exp $    */
+
+/*
+ * Written by Charles M. Hannum, Apr 9, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpgetmask, _fpgetmask)
+ENTRY(_fpgetmask)
+#else
+ENTRY(fpgetmask)
+#endif
+       fmovel %fpcr,%d0
+       bfextu %d0{#18:#5},%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/fpgetround.S b/lib/nbsd_libc/arch/m68k/gen/fpgetround.S
new file mode 100644 (file)
index 0000000..29c3729
--- /dev/null
@@ -0,0 +1,18 @@
+/*     $NetBSD: fpgetround.S,v 1.8 2002/01/13 21:45:44 thorpej Exp $   */
+
+/*
+ * Written by J.T. Conklin, Apr 6, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpgetround, _fpgetround)
+ENTRY(_fpgetround)
+#else
+ENTRY(fpgetround)
+#endif
+       fmovel %fpcr,%d0
+       bfextu %d0{#26:#2},%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/fpgetsticky.S b/lib/nbsd_libc/arch/m68k/gen/fpgetsticky.S
new file mode 100644 (file)
index 0000000..9e482eb
--- /dev/null
@@ -0,0 +1,18 @@
+/*     $NetBSD: fpgetsticky.S,v 1.7 2002/01/13 21:45:44 thorpej Exp $  */
+
+/*
+ * Written by Charles M. Hannum, Apr 9, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpgetsticky, _fpgetsticky)
+ENTRY(_fpgetsticky)
+#else
+ENTRY(fpgetsticky)
+#endif
+       fmovel %fpsr,%d0
+       bfextu %d0{#24:#5},%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/fpsetmask.S b/lib/nbsd_libc/arch/m68k/gen/fpsetmask.S
new file mode 100644 (file)
index 0000000..65a5572
--- /dev/null
@@ -0,0 +1,23 @@
+/*     $NetBSD: fpsetmask.S,v 1.7 2002/01/13 21:45:44 thorpej Exp $    */
+
+/*
+ * Written by Charles M. Hannum, Apr 9, 1995
+ * Public Domain.
+ */
+
+#include <machine/asm.h>
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpsetmask, _fpsetmask)
+ENTRY(_fpsetmask)
+#else
+ENTRY(fpsetmask)
+#endif
+       movel %d2,%sp@-
+       fmovel %fpcr,%d1
+       movel %sp@(8),%d2
+       bfextu %d1{#18:#5},%d0
+       bfins %d2,%d1{#18:#5}
+       movel %sp@+,%d2
+       fmovel %d1,%fpcr
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/fpsetround.S b/lib/nbsd_libc/arch/m68k/gen/fpsetround.S
new file mode 100644 (file)
index 0000000..b02e669
--- /dev/null
@@ -0,0 +1,23 @@
+/*     $NetBSD: fpsetround.S,v 1.8 2002/01/13 21:45:44 thorpej Exp $   */
+
+/*
+ * Written by J.T. Conklin, Apr 6, 1995
+ * Public Domain.
+ */
+
+#include <machine/asm.h>
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpsetround, _fpsetround)
+ENTRY(_fpsetround)
+#else
+ENTRY(fpsetround)
+#endif
+       movel %d2,%sp@-
+       fmovel %fpcr,%d1
+       movel %sp@(8),%d2
+       bfextu %d1{#26,#2},%d0
+       bfins %d2,%d1{#26:#2}
+       movel %sp@+,%d2
+       fmovel %d1,%fpcr
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/fpsetsticky.S b/lib/nbsd_libc/arch/m68k/gen/fpsetsticky.S
new file mode 100644 (file)
index 0000000..f0d7db2
--- /dev/null
@@ -0,0 +1,23 @@
+/*     $NetBSD: fpsetsticky.S,v 1.7 2002/01/13 21:45:45 thorpej Exp $  */
+
+/*
+ * Written by Charles M. Hannum, Apr 9, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpsetsticky, _fpsetsticky)
+ENTRY(_fpsetsticky)
+#else
+ENTRY(fpsetsticky)
+#endif
+       movel %d2,%sp@-
+       fmovel %fpsr,%d1
+       movel %sp@(8),%d2
+       bfextu %d1{#24:#5},%d0
+       bfins %d2,%d1{#24:#5}
+       movel %sp@+,%d2
+       fmovel %d1,%fpsr
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/infinityl.c b/lib/nbsd_libc/arch/m68k/gen/infinityl.c
new file mode 100644 (file)
index 0000000..775388c
--- /dev/null
@@ -0,0 +1,17 @@
+/*     $NetBSD: infinityl.c,v 1.2 2005/06/12 05:21:26 lukem Exp $      */
+
+/*
+ * IEEE-compatible infinityl.c for Motorola 68k 80-bit format -- public domain.
+ * Note that the representation includes 16 bits of padding between exponent
+ * and mantissa.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: infinityl.c,v 1.2 2005/06/12 05:21:26 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+
+const union __long_double_u __infinityl =
+       { { 0x7f, 0xff, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0 } };
diff --git a/lib/nbsd_libc/arch/m68k/gen/isfinitel.c b/lib/nbsd_libc/arch/m68k/gen/isfinitel.c
new file mode 100644 (file)
index 0000000..8b1fd97
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: isfinitel.c,v 1.2 2008/04/28 20:22:56 martin Exp $     */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: isfinitel.c,v 1.2 2008/04/28 20:22:56 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <assert.h>
+#include <math.h>
+
+/*
+ * 7.12.3.2 isfinite - determine whether an argument has finite value
+ *          IEEE 754 compatible 80-bit extended-precision Motorola 68k version
+ */
+int
+__isfinitel(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       _DIAGASSERT(u.extu_ext.ext_zero == 0);
+
+       if (u.extu_ext.ext_exp == EXT_EXP_INFNAN)
+               return 0;
+
+       return 1;
+}
diff --git a/lib/nbsd_libc/arch/m68k/gen/isinfl.c b/lib/nbsd_libc/arch/m68k/gen/isinfl.c
new file mode 100644 (file)
index 0000000..b67676f
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: isinfl.c,v 1.6 2009/01/30 07:00:45 mhitch Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isinfl.c,v 1.6 2009/01/30 07:00:45 mhitch Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.3 isinf - test for infinity
+ *          IEEE 754 compatible 80-bit extended-precision Motorola 68k version
+ */
+int
+__isinfl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       /* Note: the explicit integer bit is "don't care". */
+       return (u.extu_ext.ext_exp == EXT_EXP_INFNAN &&
+           ((u.extu_ext.ext_frach & 0x7fffffff) == 0 && u.extu_ext.ext_fracl == 0));
+}
diff --git a/lib/nbsd_libc/arch/m68k/gen/isnanl.c b/lib/nbsd_libc/arch/m68k/gen/isnanl.c
new file mode 100644 (file)
index 0000000..d046f7d
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: isnanl.c,v 1.5 2004/03/04 23:42:38 kleink Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isnanl.c,v 1.5 2004/03/04 23:42:38 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.4 isnan - test for a NaN
+ *          IEEE 754 compatible 80-bit extended-precision Motorola 68k version
+ */
+int
+__isnanl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       /* Note: the explicit integer bit is "don't care". */
+       return (u.extu_ext.ext_exp == EXT_EXP_INFNAN &&
+           (u.extu_ext.ext_frach != 0 || u.extu_ext.ext_fracl != 0));
+}
diff --git a/lib/nbsd_libc/arch/m68k/gen/ldexp_881.c b/lib/nbsd_libc/arch/m68k/gen/ldexp_881.c
new file mode 100644 (file)
index 0000000..ab4a0a4
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: ldexp_881.c,v 1.3 2008/04/28 20:22:56 martin Exp $     */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Charles M. Hannum.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ldexp_881.c,v 1.3 2008/04/28 20:22:56 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * ldexp(value, exp): return value * (2 ** exp).
+ */
+double
+ldexp(value, exp2)
+       double value;
+       int exp2;
+{
+       double temp;
+
+       __asm ("fscalel %2,%1"
+               : "=f" (temp)
+               : "0" (value), "g" (exp2));
+       return (temp);
+}
diff --git a/lib/nbsd_libc/arch/m68k/gen/longjmp.c b/lib/nbsd_libc/arch/m68k/gen/longjmp.c
new file mode 100644 (file)
index 0000000..e8d5d03
--- /dev/null
@@ -0,0 +1,96 @@
+/*     $NetBSD: longjmp.c,v 1.2 2008/04/28 20:22:56 martin Exp $       */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christian Limpach.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define __LIBC12_SOURCE__
+#include <setjmp.h>
+#include <compat/include/setjmp.h>
+
+typedef struct {
+       __greg_t        __data[6];
+       __greg_t        __addr[4];
+} __jmp_buf_regs_t;
+
+void
+__longjmp14(jmp_buf env, int val)
+{
+       struct sigcontext *sc = (void *)env;
+       __jmp_buf_regs_t *r = (void *)&sc[1];
+       ucontext_t uc;
+
+       /* Ensure non-zero SP */
+       if (sc->sc_sp == 0)
+               goto err;
+
+       /* Make return value non-zero */
+       if (val == 0)
+               val = 1;
+
+       /* Save return value in context */
+       uc.uc_mcontext.__gregs[_REG_D0] = val;
+
+       /*
+        * Set _UC_SIGMASK, _UC_CPU and _UC_M68K_UC_USER
+        * Set _UC_{SET,CLR}STACK according to SS_ONSTACK
+        */
+       uc.uc_flags = _UC_SIGMASK | _UC_CPU | _UC_M68K_UC_USER |
+               (sc->sc_onstack ? _UC_SETSTACK : _UC_CLRSTACK);
+
+       /* Clear uc_link */
+       uc.uc_link = 0;
+
+       /* Copy signal mask */
+       uc.uc_sigmask = sc->sc_mask;
+
+       /* Copy SP/PC/PS/FP */
+       uc.uc_mcontext.__gregs[_REG_A7] = sc->sc_sp;
+       uc.uc_mcontext.__gregs[_REG_PC] = sc->sc_pc;
+       uc.uc_mcontext.__gregs[_REG_PS] = sc->sc_ps;
+       uc.uc_mcontext.__gregs[_REG_A6] = sc->sc_fp;
+
+       /* Copy remaining non-scratch regs. */
+       memcpy(&uc.uc_mcontext.__gregs[_REG_D2],
+           &r->__data, sizeof(r->__data));
+       memcpy(&uc.uc_mcontext.__gregs[_REG_A2],
+           &r->__addr, sizeof(r->__addr));
+
+       setcontext(&uc);
+ err:
+       longjmperror();
+       abort();
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/m68k/gen/lshlsi3.S b/lib/nbsd_libc/arch/m68k/gen/lshlsi3.S
new file mode 100644 (file)
index 0000000..2d2e592
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: lshlsi3.S,v 1.5 2003/08/07 16:42:10 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)lshlsi3.s      5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: lshlsi3.S,v 1.5 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* unsigned << unsigned */
+ENTRY(__lshlsi3)
+       movel   %sp@(8),%d1
+       movel   %sp@(4),%d0
+       lsll    %d1,%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/lshrsi3.S b/lib/nbsd_libc/arch/m68k/gen/lshrsi3.S
new file mode 100644 (file)
index 0000000..0f13039
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: lshrsi3.S,v 1.5 2003/08/07 16:42:10 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)lshrsi3.s      5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: lshrsi3.S,v 1.5 2003/08/07 16:42:10 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* unsigned >> unsigned */
+ENTRY(__lshrsi3)
+       movel   %sp@(8),%d1
+       movel   %sp@(4),%d0
+       lsrl    %d1,%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/makecontext.c b/lib/nbsd_libc/arch/m68k/gen/makecontext.c
new file mode 100644 (file)
index 0000000..173904e
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: makecontext.c,v 1.3 2008/04/28 20:22:56 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.3 2008/04/28 20:22:56 martin Exp $");
+#endif
+
+#include <sys/types.h>
+#include <inttypes.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#include <stdarg.h>
+
+void
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+{
+       mcontext_t *mcp = &ucp->uc_mcontext;
+       int *sp;
+       va_list ap;
+
+       mcp->__gregs[_REG_PC] = (__greg_t)func;
+
+       sp  = (int *)((uintptr_t)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size);
+       sp  = (int *)((uintptr_t)sp & ~0x3);    /* Align on word boundary. */
+       sp -= (argc + 1);               /* Make room for retaddr and args. */
+       mcp->__gregs[_REG_A7] = (__greg_t)sp;
+       mcp->__gregs[_REG_A6] = 0;              /* Wipe out frame pointer. */
+
+       *sp++ = (int)_resumecontext;
+
+       va_start(ap, argc);
+       while (argc-- > 0)
+               *sp++ = va_arg(ap, int);
+       va_end(ap);
+}
diff --git a/lib/nbsd_libc/arch/m68k/gen/modf.S b/lib/nbsd_libc/arch/m68k/gen/modf.S
new file mode 100644 (file)
index 0000000..57f2369
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: modf.S,v 1.6 2003/08/07 16:42:11 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)modf.s 5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: modf.S,v 1.6 2003/08/07 16:42:11 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * double modf(val, iptr)
+ * returns: xxx and n (in *iptr) where val == n.xxx
+ */
+ENTRY(modf)
+       fmoved  %sp@(4),%fp0
+       movel   %sp@(12),%a0
+       fintrzx %fp0,%fp1
+       fmoved  %fp1,%a0@
+       fsubx   %fp1,%fp0
+#ifndef __SVR4_ABI__
+       fmoved  %fp0,%sp@-
+       movel   %sp@+,%d0
+       movel   %sp@+,%d1
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/muldf3.S b/lib/nbsd_libc/arch/m68k/gen/muldf3.S
new file mode 100644 (file)
index 0000000..e637ebf
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: muldf3.S,v 1.7 2003/08/07 16:42:11 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)muldf3.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: muldf3.S,v 1.7 2003/08/07 16:42:11 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* double * double */
+ENTRY(__muldf3)
+       fmoved  %sp@(4),%fp0
+       fmuld   %sp@(12),%fp0
+#ifndef __SVR4_ABI__
+       fmoved  %fp0,%sp@-
+       movel   %sp@+,%d0
+       movel   %sp@+,%d1
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/mulsf3.S b/lib/nbsd_libc/arch/m68k/gen/mulsf3.S
new file mode 100644 (file)
index 0000000..61bf7a3
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: mulsf3.S,v 1.6 2003/08/07 16:42:11 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)mulsf3.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: mulsf3.S,v 1.6 2003/08/07 16:42:11 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* single * single */
+ENTRY(__mulsf3)
+       fmoves  %sp@(4),%fp0
+       fmuls   %sp@(8),%fp0
+#ifndef __SVR4_ABI__
+       fmoves  %fp0,%d0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/nanf.c b/lib/nbsd_libc/arch/m68k/gen/nanf.c
new file mode 100644 (file)
index 0000000..8516c1b
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: nanf.c,v 1.4 2009/02/22 01:34:01 martin Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nanf.c,v 1.4 2009/02/22 01:34:01 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+/* bytes for quiet NaN (IEEE single precision) */
+const union __float_u __nanf =
+               { { 0x7f, 0xc0,    0,    0 } };
+
+__warn_references(__nanf, "warning: <math.h> defines NAN incorrectly for your compiler.")
diff --git a/lib/nbsd_libc/arch/m68k/gen/negdf2.S b/lib/nbsd_libc/arch/m68k/gen/negdf2.S
new file mode 100644 (file)
index 0000000..805412a
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: negdf2.S,v 1.7 2003/08/07 16:42:11 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)negdf2.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: negdf2.S,v 1.7 2003/08/07 16:42:11 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* -double */
+ENTRY(__negdf2)
+#if defined(__SVR4_ABI__) && defined(__HAVE_68881__)
+       fnegd   %sp@(4),%fp0
+#else
+       movel   %sp@(4),%d0
+       movel   %sp@(8),%d1
+       bchg    #31,%d0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/negsf2.S b/lib/nbsd_libc/arch/m68k/gen/negsf2.S
new file mode 100644 (file)
index 0000000..3ff73c4
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: negsf2.S,v 1.7 2003/08/07 16:42:11 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID"from: @(#)negsf2.s        5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: negsf2.S,v 1.7 2003/08/07 16:42:11 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* -single */
+ENTRY(__negsf2)
+#if defined(__SVR4_ABI__) && defined(__HAVE_68881__)
+       fnegs   %sp@(4),%fp0
+#else
+       movel   %sp@(4),%d0
+       bchg    #31,%d0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/resumecontext.S b/lib/nbsd_libc/arch/m68k/gen/resumecontext.S
new file mode 100644 (file)
index 0000000..078d55f
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: resumecontext.S,v 1.5 2008/04/28 20:22:56 martin Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: resumecontext.S,v 1.5 2008/04/28 20:22:56 martin Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+/*
+ * This assembly-language implementation differs from the (obvious)
+ * C-language implementation only in not clobbering the previous
+ * function's return address (us), which is the point of the exercise.
+ */
+
+ENTRY(_resumecontext)
+       subl    #(4 + 1024),%sp         /* retaddr preservation + ucontext_t */
+       lea     %sp@,%a0
+       movl    %a0,%sp@-
+       jbsr    PIC_PLT(_C_LABEL(_getcontext))
+       movl    %sp@(4 + 4),%sp@        /* uc_link */
+       tstl    %sp@                    /* check for NULL */
+       jne     1f
+       jbsr    PIC_PLT(_C_LABEL(exit)) /* cleanly exit(0) */
+       jmp     2f
+1:     jbsr    PIC_PLT(_C_LABEL(setcontext))
+       /* NOTREACHED */
+       /* But just in case... */
+2:     movl    #-1,%sp@
+       jbsr    PIC_PLT(_C_LABEL(_exit))
+       /* NOTREACHED */
diff --git a/lib/nbsd_libc/arch/m68k/gen/setjmp.S b/lib/nbsd_libc/arch/m68k/gen/setjmp.S
new file mode 100644 (file)
index 0000000..945eb7e
--- /dev/null
@@ -0,0 +1,93 @@
+/*     $NetBSD: setjmp.S,v 1.12 2006/03/09 16:20:27 christos Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)setjmp.s       5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: setjmp.S,v 1.12 2006/03/09 16:20:27 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and a struct sigcontext, see <signal.h>
+ */
+
+ENTRY(__setjmp14)
+       /* Get signal stack info.  Note overlay of ss_sp and ss_size! */
+       lea     %sp@(-12),%sp   /* sizeof(stack_t) */
+       clrl    %sp@            /* ss = NULL */
+       movl    %sp,%sp@(4)     /* oss = stack_t on stack */
+       jbsr    PIC_PLT(_C_LABEL(__sigaltstack14))
+
+       movl    %sp@(8),%d0     /* ss_flags */
+       andl    #1,%d0          /* extract SS_ONSTACK */
+       lea     %sp@(12),%sp    /* pop stack_t */
+
+       /* Get pointer to jmp_buf; a sigcontext is at the beginning. */
+       movl    %sp@(4),%a0
+       movl    %d0,%a0@        /* store onstack */
+       clrl    %a0@(4)         /* unused word (old style signal mask) */
+
+       /* Get the signal mask. */
+       pea     %a0@(28)        /* oset = &sc.sc_mask */
+       movl    #0,%sp@-        /* set = NULL */
+       movl    #0,%sp@-        /* action = 0 <ignored> */
+       jbsr    PIC_PLT(_C_LABEL(__sigprocmask14))
+       addl    #12,%sp
+
+       movl    %sp@(4),%a0     /* get jmp_buf pointer again */
+       lea     %sp@(4),%a1     /* adjust SP since we won't rts */
+       movl    %a1,%a0@(8)     /* save SP */
+       movl    %a6,%a0@(12)    /* save FP */
+       clrl    %a0@(16)        /* no AP */
+       movl    %sp@,%a0@(20)   /* save return PC */
+       clrl    %a0@(24)        /* clear PS */
+
+       /* Save remaining non-scratch regs after signal mask. */
+       moveml  #0x3CFC,%a0@(44)
+
+       clrl    %d0             /* return 0 */
+       rts
+
diff --git a/lib/nbsd_libc/arch/m68k/gen/signbitl.c b/lib/nbsd_libc/arch/m68k/gen/signbitl.c
new file mode 100644 (file)
index 0000000..1574716
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: signbitl.c,v 1.2 2008/04/28 20:22:56 martin Exp $      */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: signbitl.c,v 1.2 2008/04/28 20:22:56 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.6 signbit - determine whether the sign of an argument is negative
+ *          IEEE 754 compatible 80-bit extended-precision Motorola 68k version
+ */
+int
+__signbitl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return (u.extu_ext.ext_sign == 1);
+}
diff --git a/lib/nbsd_libc/arch/m68k/gen/sigsetjmp.S b/lib/nbsd_libc/arch/m68k/gen/sigsetjmp.S
new file mode 100644 (file)
index 0000000..d64865f
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: sigsetjmp.S,v 1.8 2006/03/09 16:20:27 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)_setjmp.s      5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: sigsetjmp.S,v 1.8 2006/03/09 16:20:27 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- sigsetjmp, siglongjmp
+ *
+ *     siglongjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     sigsetjmp(a,m)
+ * by restoring registers from the stack,
+ * The previous signal state is restored if 'm' was non-zero.
+ */
+
+/* grab _JBLEN */
+#include <m68k/setjmp.h>
+
+ENTRY(__sigsetjmp14)
+       movl    %sp@(8),%d1     /* grab the mask */
+        movl   %sp@(4),%a0     /* grab the area pointer */
+       movl    %d1,%a0@(_JBLEN * 4)    /* save at end of area */
+       tstl    %d1
+       bne     dosig
+       jra     PIC_PLT(_C_LABEL(_setjmp))
+dosig:
+       jra     PIC_PLT(_C_LABEL(__setjmp14))
+
+
+ENTRY(__siglongjmp14)
+       movl    %sp@(4),%a0     /* save area pointer */
+       tstl    %a0@(_JBLEN * 4) /* check mask... */
+       bne     didsig
+       jra     PIC_PLT(_C_LABEL(_longjmp))
+didsig:
+       jra     PIC_PLT(_C_LABEL(__longjmp14))
diff --git a/lib/nbsd_libc/arch/m68k/gen/subdf3.S b/lib/nbsd_libc/arch/m68k/gen/subdf3.S
new file mode 100644 (file)
index 0000000..beba955
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: subdf3.S,v 1.6 2003/08/07 16:42:11 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)subdf3.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: subdf3.S,v 1.6 2003/08/07 16:42:11 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* double - double */
+ENTRY(__subdf3)
+       fmoved  %sp@(4),%fp0
+       fsubd   %sp@(12),%fp0
+#ifndef __SVR4_ABI__
+       fmoved  %fp0,%sp@-
+       movel   %sp@+,%d0
+       movel   %sp@+,%d1
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/subsf3.S b/lib/nbsd_libc/arch/m68k/gen/subsf3.S
new file mode 100644 (file)
index 0000000..ab3a852
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: subsf3.S,v 1.6 2003/08/07 16:42:11 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)subsf3.s       5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: subsf3.S,v 1.6 2003/08/07 16:42:11 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* single - single */
+ENTRY(__subsf3)
+       fmoves  %sp@(4),%fp0
+       fsubs   %sp@(8),%fp0
+#ifndef __SVR4_ABI__
+       fmoves  %fp0,%d0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/swapcontext.S b/lib/nbsd_libc/arch/m68k/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..5cb0aa2
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: swapcontext.S,v 1.3 2008/04/28 20:22:56 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: swapcontext.S,v 1.3 2008/04/28 20:22:56 martin Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+ENTRY(swapcontext)
+       movl    %sp@(4),%sp@-           | push oucp on stack
+       jbsr    PIC_PLT(_C_LABEL(_getcontext))  | getcontext(oucp)
+       tstl    %d0                     | OK?
+       jne     L1
+       movl    %sp@,%a0
+       addql   #8,%a0@(96)             | adjust saved stack pointer (again)
+       movl    %sp@(4),%a0@(100)       | adjust saved program counter (again)
+       movl    %sp@(12),%sp@           | push ucp on stack
+       jbsr    PIC_PLT(_C_LABEL(setcontext))   | setcontext(ucp)
+L1:    addql   #4,%sp                  | pop ucp
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/truncdfsf2.S b/lib/nbsd_libc/arch/m68k/gen/truncdfsf2.S
new file mode 100644 (file)
index 0000000..7a3e173
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: truncdfsf2.S,v 1.6 2003/08/07 16:42:11 agc Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)truncdfsf2.s   5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: truncdfsf2.S,v 1.6 2003/08/07 16:42:11 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* (float) double */
+ENTRY(__truncdfsf2)
+       fmoved  %sp@(4),%fp0
+#ifndef __SVR4_ABI__
+       fmoves  %fp0,%d0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/gen/umulsi3.S b/lib/nbsd_libc/arch/m68k/gen/umulsi3.S
new file mode 100644 (file)
index 0000000..c6d6fb2
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: umulsi3.S,v 1.5 2003/08/07 16:42:12 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)umulsi3.s      5.1 (Berkeley) 6/7/90")
+#else
+       RCSID("$NetBSD: umulsi3.S,v 1.5 2003/08/07 16:42:12 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* unsigned * unsigned */
+ENTRY(__umulsi3)
+       movel   %sp@(4),%d0
+       mulul   %sp@(8),%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/net/Makefile.inc b/lib/nbsd_libc/arch/m68k/net/Makefile.inc
new file mode 100644 (file)
index 0000000..dc2ddf3
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 1995/02/25 14:58:55 cgd Exp $
+
+SRCS+=  htonl.S htons.S ntohl.S ntohs.S
diff --git a/lib/nbsd_libc/arch/m68k/quad/ashldi3.S b/lib/nbsd_libc/arch/m68k/quad/ashldi3.S
new file mode 100644 (file)
index 0000000..22e527d
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: ashldi3.S,v 1.4 2008/04/28 20:22:56 martin Exp $       */
+
+/*-
+ * Copyright (c) 1996 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+| d0 msw
+| d1 lsw
+| d2 shift
+| d3 offset (32 - shift)
+
+ENTRY(__ashldi3)
+       link    %a6,#0
+       moveml  %d2-%d4,%sp@-
+       movel   %a6@(8),%d0
+       movel   %a6@(12),%d1
+       movel   %a6@(16),%d2
+       moveq   #32,%d3
+       subl    %d2,%d3
+       jgt     L2
+       negl    %d3
+       movel   %d1,%d0
+       asll    %d3,%d0
+       clrl    %d1
+       jra     L3
+L2:    asll    %d2,%d0
+       movel   %d1,%d4
+       lsrl    %d3,%d4
+       orl     %d4,%d0
+       asll    %d2,%d1
+L3:    moveml  %a6@(-12),%d2-%d4
+       unlk    %a6
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/quad/ashrdi3.S b/lib/nbsd_libc/arch/m68k/quad/ashrdi3.S
new file mode 100644 (file)
index 0000000..5289ec9
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: ashrdi3.S,v 1.4 2008/04/28 20:22:56 martin Exp $       */
+
+/*-
+ * Copyright (c) 1996 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+| d0 msw
+| d1 lsw
+| d2 shift
+| d3 offset (32 - shift)
+
+ENTRY(__ashrdi3)
+       link    %a6,#0
+       moveml  %d2-%d4,%sp@-
+       movel   %a6@(8),%d0
+       movel   %a6@(12),%d1
+       movel   %a6@(16),%d2
+       moveq   #32,%d3
+       subl    %d2,%d3
+       jgt     L2
+       negl    %d3
+       movel   %d0,%d1
+       asrl    %d3,%d1
+       smi     %d0
+       extbl   %d0
+       jra     L3
+L2:    lsrl    %d2,%d1
+       movel   %d0,%d4
+       asll    %d3,%d4
+       orl     %d4,%d1
+       asrl    %d2,%d0
+L3:    moveml  %a6@(-12),%d2-%d4
+       unlk    %a6
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/quad/lshrdi3.S b/lib/nbsd_libc/arch/m68k/quad/lshrdi3.S
new file mode 100644 (file)
index 0000000..cf3794d
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: lshrdi3.S,v 1.5 2008/04/28 20:22:56 martin Exp $       */
+
+/*-
+ * Copyright (c) 1996 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+| d0 msw
+| d1 lsw
+| d2 shift
+| d3 offset (32 - shift)
+
+ENTRY(__lshrdi3)
+       link    %a6,#0
+       moveml  %d2-%d4,%sp@-
+       movel   %a6@(8),%d0
+       movel   %a6@(12),%d1
+       movel   %a6@(16),%d2
+       moveq   #32,%d3
+       subl    %d2,%d3
+       jgt     L2
+       negl    %d3
+       movel   %d0,%d1
+       lsrl    %d3,%d1
+       clrl    %d0
+       jra     L3
+L2:    lsrl    %d2,%d1
+       movel   %d0,%d4
+       asll    %d3,%d4
+       orl     %d4,%d1
+       lsrl    %d2,%d0
+L3:    moveml  %a6@(-12),%d2-%d4
+       unlk    %a6
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/softfloat/m68k-gcc.h b/lib/nbsd_libc/arch/m68k/softfloat/m68k-gcc.h
new file mode 100644 (file)
index 0000000..07bd45b
--- /dev/null
@@ -0,0 +1,89 @@
+/*     $NetBSD: m68k-gcc.h,v 1.2 2005/12/24 21:11:16 perry Exp $       */
+
+/*
+-------------------------------------------------------------------------------
+One of the macros `BIGENDIAN' or `LITTLEENDIAN' must be defined.
+-------------------------------------------------------------------------------
+*/
+#include <machine/endian.h>
+#if _BYTE_ORDER == _BIG_ENDIAN
+#define BIGENDIAN
+#endif
+#if _BYTE_ORDER == _LITTLE_ENDIAN
+#define LITTLEENDIAN
+#endif
+
+/*
+-------------------------------------------------------------------------------
+The macro `BITS64' can be defined to indicate that 64-bit integer types are
+supported by the compiler.
+-------------------------------------------------------------------------------
+*/
+#define BITS64
+
+/*
+-------------------------------------------------------------------------------
+Each of the following `typedef's defines the most convenient type that holds
+integers of at least as many bits as specified.  For example, `uint8' should
+be the most convenient type that can hold unsigned integers of as many as
+8 bits.  The `flag' type must be able to hold either a 0 or 1.  For most
+implementations of C, `flag', `uint8', and `int8' should all be `typedef'ed
+to the same as `int'.
+-------------------------------------------------------------------------------
+*/
+typedef int flag;
+typedef int uint8;
+typedef int int8;
+typedef int uint16;
+typedef int int16;
+typedef unsigned int uint32;
+typedef signed int int32;
+#ifdef BITS64
+typedef unsigned long long int uint64;
+typedef signed long long int int64;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Each of the following `typedef's defines a type that holds integers
+of _exactly_ the number of bits specified.  For instance, for most
+implementation of C, `bits16' and `sbits16' should be `typedef'ed to
+`unsigned short int' and `signed short int' (or `short int'), respectively.
+-------------------------------------------------------------------------------
+*/
+typedef unsigned char bits8;
+typedef signed char sbits8;
+typedef unsigned short int bits16;
+typedef signed short int sbits16;
+typedef unsigned int bits32;
+typedef signed int sbits32;
+#ifdef BITS64
+typedef unsigned long long int bits64;
+typedef signed long long int sbits64;
+#endif
+
+#ifdef BITS64
+/*
+-------------------------------------------------------------------------------
+The `LIT64' macro takes as its argument a textual integer literal and
+if necessary ``marks'' the literal as having a 64-bit integer type.
+For example, the GNU C Compiler (`gcc') requires that 64-bit literals be
+appended with the letters `LL' standing for `long long', which is `gcc's
+name for the 64-bit integer type.  Some compilers may allow `LIT64' to be
+defined as the identity macro:  `#define LIT64( a ) a'.
+-------------------------------------------------------------------------------
+*/
+#define LIT64( a ) a##LL
+#endif
+
+/*
+-------------------------------------------------------------------------------
+The macro `INLINE' can be used before functions that should be inlined.  If
+a compiler does not support explicit inlining, this macro should be defined
+to be `static'.
+-------------------------------------------------------------------------------
+*/
+#define INLINE static inline
+
+#define FLOAT64_DEMANGLE(a)    (a)
+#define FLOAT64_MANGLE(a)      (a)
diff --git a/lib/nbsd_libc/arch/m68k/softfloat/milieu.h b/lib/nbsd_libc/arch/m68k/softfloat/milieu.h
new file mode 100644 (file)
index 0000000..462472b
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: milieu.h,v 1.1 2004/09/26 21:13:27 jmmv Exp $  */
+
+/*
+===============================================================================
+
+This C header file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+Include common integer types and flags.
+-------------------------------------------------------------------------------
+*/
+#include "m68k-gcc.h"
+
+/*
+-------------------------------------------------------------------------------
+Symbolic Boolean literals.
+-------------------------------------------------------------------------------
+*/
+enum {
+    FALSE = 0,
+    TRUE  = 1
+};
diff --git a/lib/nbsd_libc/arch/m68k/softfloat/softfloat.h b/lib/nbsd_libc/arch/m68k/softfloat/softfloat.h
new file mode 100644 (file)
index 0000000..1c4c153
--- /dev/null
@@ -0,0 +1,302 @@
+/*     $NetBSD: softfloat.h,v 1.2 2006/05/16 20:55:51 mrg Exp $        */
+
+/* This is a derivative work. */
+
+/*
+===============================================================================
+
+This C header file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+The macro `FLOATX80' must be defined to enable the extended double-precision
+floating-point format `floatx80'.  If this macro is not defined, the
+`floatx80' type will not be defined, and none of the functions that either
+input or output the `floatx80' type will be defined.  The same applies to
+the `FLOAT128' macro and the quadruple-precision format `float128'.
+-------------------------------------------------------------------------------
+*/
+#define FLOATX80
+/* #define FLOAT128 */
+
+#include <machine/ieeefp.h>
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point types.
+-------------------------------------------------------------------------------
+*/
+typedef unsigned int float32;
+typedef unsigned long long float64;
+#ifdef FLOATX80
+typedef struct {
+    unsigned short high;
+    unsigned long long low;
+} floatx80;
+#endif
+#ifdef FLOAT128
+typedef struct {
+    unsigned long long high, low;
+} float128;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point underflow tininess-detection mode.
+-------------------------------------------------------------------------------
+*/
+#ifndef SOFTFLOAT_FOR_GCC
+extern int8 float_detect_tininess;
+#endif
+enum {
+    float_tininess_after_rounding  = 0,
+    float_tininess_before_rounding = 1
+};
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point rounding mode.
+-------------------------------------------------------------------------------
+*/
+extern fp_rnd float_rounding_mode;
+enum {
+    float_round_nearest_even = FP_RN,
+    float_round_to_zero      = FP_RZ,
+    float_round_down         = FP_RM,
+    float_round_up           = FP_RP
+};
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point exception flags.
+-------------------------------------------------------------------------------
+*/
+extern fp_except float_exception_flags;
+extern fp_except float_exception_mask;
+enum {
+    float_flag_inexact   = FP_X_IMP,
+    float_flag_underflow = FP_X_UFL,
+    float_flag_overflow  = FP_X_OFL,
+    float_flag_divbyzero = FP_X_DZ,
+    float_flag_invalid   = FP_X_INV
+};
+
+/*
+-------------------------------------------------------------------------------
+Routine to raise any or all of the software IEC/IEEE floating-point
+exception flags.
+-------------------------------------------------------------------------------
+*/
+void float_raise( fp_except );
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE integer-to-floating-point conversion routines.
+-------------------------------------------------------------------------------
+*/
+float32 int32_to_float32( int );
+float64 int32_to_float64( int );
+#ifdef FLOATX80
+floatx80 int32_to_floatx80( int );
+#endif
+#ifdef FLOAT128
+float128 int32_to_float128( int );
+#endif
+float32 int64_to_float32( long long );
+float64 int64_to_float64( long long );
+#ifdef FLOATX80
+floatx80 int64_to_floatx80( long long );
+#endif
+#ifdef FLOAT128
+float128 int64_to_float128( long long );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE single-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float32_to_int32( float32 );
+int float32_to_int32_round_to_zero( float32 );
+unsigned int float32_to_uint32_round_to_zero( float32 );
+long long float32_to_int64( float32 );
+long long float32_to_int64_round_to_zero( float32 );
+float64 float32_to_float64( float32 );
+#ifdef FLOATX80
+floatx80 float32_to_floatx80( float32 );
+#endif
+#ifdef FLOAT128
+float128 float32_to_float128( float32 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE single-precision operations.
+-------------------------------------------------------------------------------
+*/
+float32 float32_round_to_int( float32 );
+float32 float32_add( float32, float32 );
+float32 float32_sub( float32, float32 );
+float32 float32_mul( float32, float32 );
+float32 float32_div( float32, float32 );
+float32 float32_rem( float32, float32 );
+float32 float32_sqrt( float32 );
+flag float32_eq( float32, float32 );
+flag float32_le( float32, float32 );
+flag float32_lt( float32, float32 );
+flag float32_eq_signaling( float32, float32 );
+flag float32_le_quiet( float32, float32 );
+flag float32_lt_quiet( float32, float32 );
+#ifndef SOFTFLOAT_FOR_GCC
+flag float32_is_signaling_nan( float32 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE double-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float64_to_int32( float64 );
+int float64_to_int32_round_to_zero( float64 );
+unsigned int float64_to_uint32_round_to_zero( float64 );
+long long float64_to_int64( float64 );
+long long float64_to_int64_round_to_zero( float64 );
+float32 float64_to_float32( float64 );
+#ifdef FLOATX80
+floatx80 float64_to_floatx80( float64 );
+#endif
+#ifdef FLOAT128
+float128 float64_to_float128( float64 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE double-precision operations.
+-------------------------------------------------------------------------------
+*/
+float64 float64_round_to_int( float64 );
+float64 float64_add( float64, float64 );
+float64 float64_sub( float64, float64 );
+float64 float64_mul( float64, float64 );
+float64 float64_div( float64, float64 );
+float64 float64_rem( float64, float64 );
+float64 float64_sqrt( float64 );
+flag float64_eq( float64, float64 );
+flag float64_le( float64, float64 );
+flag float64_lt( float64, float64 );
+flag float64_eq_signaling( float64, float64 );
+flag float64_le_quiet( float64, float64 );
+flag float64_lt_quiet( float64, float64 );
+flag float64_is_signaling_nan( float64 );
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int floatx80_to_int32( floatx80 );
+int floatx80_to_int32_round_to_zero( floatx80 );
+long long floatx80_to_int64( floatx80 );
+long long floatx80_to_int64_round_to_zero( floatx80 );
+float32 floatx80_to_float32( floatx80 );
+float64 floatx80_to_float64( floatx80 );
+#ifdef FLOAT128
+float128 floatx80_to_float128( floatx80 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision rounding precision.  Valid
+values are 32, 64, and 80.
+-------------------------------------------------------------------------------
+*/
+extern int floatx80_rounding_precision;
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision operations.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_round_to_int( floatx80 );
+floatx80 floatx80_add( floatx80, floatx80 );
+floatx80 floatx80_sub( floatx80, floatx80 );
+floatx80 floatx80_mul( floatx80, floatx80 );
+floatx80 floatx80_div( floatx80, floatx80 );
+floatx80 floatx80_rem( floatx80, floatx80 );
+floatx80 floatx80_sqrt( floatx80 );
+flag floatx80_eq( floatx80, floatx80 );
+flag floatx80_le( floatx80, floatx80 );
+flag floatx80_lt( floatx80, floatx80 );
+flag floatx80_eq_signaling( floatx80, floatx80 );
+flag floatx80_le_quiet( floatx80, floatx80 );
+flag floatx80_lt_quiet( floatx80, floatx80 );
+flag floatx80_is_signaling_nan( floatx80 );
+flag floatx80_is_nan( floatx80 );
+
+#endif
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE quadruple-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float128_to_int32( float128 );
+int float128_to_int32_round_to_zero( float128 );
+long long float128_to_int64( float128 );
+long long float128_to_int64_round_to_zero( float128 );
+float32 float128_to_float32( float128 );
+float64 float128_to_float64( float128 );
+#ifdef FLOATX80
+floatx80 float128_to_floatx80( float128 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE quadruple-precision operations.
+-------------------------------------------------------------------------------
+*/
+float128 float128_round_to_int( float128 );
+float128 float128_add( float128, float128 );
+float128 float128_sub( float128, float128 );
+float128 float128_mul( float128, float128 );
+float128 float128_div( float128, float128 );
+float128 float128_rem( float128, float128 );
+float128 float128_sqrt( float128 );
+flag float128_eq( float128, float128 );
+flag float128_le( float128, float128 );
+flag float128_lt( float128, float128 );
+flag float128_eq_signaling( float128, float128 );
+flag float128_le_quiet( float128, float128 );
+flag float128_lt_quiet( float128, float128 );
+flag float128_is_signaling_nan( float128 );
+
+#endif
diff --git a/lib/nbsd_libc/arch/m68k/stdlib/Makefile.inc b/lib/nbsd_libc/arch/m68k/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..4945ed9
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.7 2009/08/11 17:30:43 dsl Exp $
+
+SRCS+= abs.S llabs.S
+NO_SRCS+= labs.S imaxabs.S
diff --git a/lib/nbsd_libc/arch/m68k/stdlib/abs.S b/lib/nbsd_libc/arch/m68k/stdlib/abs.S
new file mode 100644 (file)
index 0000000..261136d
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: abs.S,v 1.6 2003/08/07 16:42:12 agc Exp $      */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)abs.s  5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: abs.S,v 1.6 2003/08/07 16:42:12 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* labs - long int absolute value */
+
+ENTRY_NOPROFILE(labs)
+/* fall through to: */
+
+/* abs - int absolute value */
+
+ENTRY(abs)
+       movl    %sp@(4),%d0
+       jge     L1
+       negl    %d0
+L1:
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/stdlib/llabs.S b/lib/nbsd_libc/arch/m68k/stdlib/llabs.S
new file mode 100644 (file)
index 0000000..b565ded
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: llabs.S,v 1.4 2008/08/04 21:29:28 matt Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)abs.s  5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: llabs.S,v 1.4 2008/08/04 21:29:28 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(llabs, _llabs)
+WEAK_ALIAS(imaxabs, _llabs)
+#endif
+/* llabs - long long int absolute value */
+
+#ifdef WEAK_ALIAS
+ENTRY(_llabs)
+#else
+ENTRY(llabs)
+#endif
+       movl    %sp@(8),%d1
+       movl    %sp@(4),%d0
+       jge     L1
+       negl    %d1
+       negxl   %d0
+L1:
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/string/Makefile.inc b/lib/nbsd_libc/arch/m68k/string/Makefile.inc
new file mode 100644 (file)
index 0000000..239dce2
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/07/30 20:57:16 dsl Exp $
+
+SRCS+= bcmp.S bcopy.S bzero.S ffs.S memcmp.S memset.S \
+       strcat.S strcmp.S strcpy.S strlen.S \
+       strncmp.S strncpy.S \
+       swab.S
+SRCS+= memcpy.S memccpy.S memmove.S strchr.S strrchr.S
diff --git a/lib/nbsd_libc/arch/m68k/string/memccpy.S b/lib/nbsd_libc/arch/m68k/string/memccpy.S
new file mode 100644 (file)
index 0000000..4a88a9c
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: memccpy.S,v 1.1 2001/02/05 00:17:22 scottr Exp $       */
+
+/*
+ * Copyright (C) 1999 Scott Reynolds.  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.
+ * 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 ``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 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 <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: memccpy.S,v 1.1 2001/02/05 00:17:22 scottr Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(memccpy)
+       movl    %sp@(16),%d0            | count
+       jeq     Lmcbail                 | nothing to do
+
+       movl    %sp@(4),%a0             | a0 = toaddr
+       subql   #1,%d0                  |   prepare count for DBcc loop
+       movl    %sp@(8),%a1             | a1 = fromaddr
+       movl    %sp@(12),%d1            | d1 = terminator
+       jeq     Lmcloop                 |   handle ASCII NUL specially
+
+       movl    %d2,%sp@-               | save scratch register
+Lmcnzloop:
+       movb    %a1@+,%d2               | move a byte
+       movb    %d2,%a0@+
+       cmpb    %d2,%d1                 | found the terminator?
+       dbeq    %d0,Lmcnzloop           | if not, keep transferring,
+       jeq     Lmcnzdone               |   otherwise done
+       clrw    %d0                     | check to see if more to do
+       subql   #1,%d0
+       jcc     Lmcnzloop               | yes, keep going...
+
+       movl    %sp@+,%d2               | restore scratch register
+       movql   #0,%d0                  | no terminator found, return NULL
+#ifdef __SVR4_ABI__
+       movl    %d0,%a0                 | XXX maybe use lea to avoid stall?
+#endif
+       rts
+
+Lmcloop:
+       movb    %a1@+,%a0@+             | move a byte; was it NUL?
+       dbeq    %d0,Lmcloop             | if not, keep transferring,
+       jeq     Lmcdone                 |   otherwise done
+       clrw    %d0                     | check to see if more to do
+       subql   #1,%d0
+       jcc     Lmcloop                 | yes, keep going...
+                                       | Note: %d0 is now -1!
+       movql   #0,%d0                  | no terminator found, return NULL
+Lmcbail:
+#ifdef __SVR4_ABI__
+       movl    %d0,%a0                 | XXX maybe use lea to avoid stall?
+#endif
+       rts
+
+Lmcnzdone:
+       movl    %sp@+,%d2               | restore scratch register
+Lmcdone:
+       movl    %a0,%d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/string/swab.S b/lib/nbsd_libc/arch/m68k/string/swab.S
new file mode 100644 (file)
index 0000000..91fea3f
--- /dev/null
@@ -0,0 +1,20 @@
+/*     $NetBSD: swab.S,v 1.7 1999/10/25 23:48:16 thorpej Exp $ */
+
+#include <machine/asm.h>
+
+ENTRY(swab)
+       movl    %sp@(4),%a0             | source
+       movl    %sp@(8),%a1             | destination
+       movl    %sp@(12),%d0            | count
+       lsrl    #1,%d0                  | count is in bytes; we need words
+       jeq     swdone
+
+swloop:
+       movw    %a0@+,%d1
+       rorw    #8,%d1
+       movw    %d1,%a1@+
+       subql   #1,%d0
+       jne     swloop
+
+swdone:
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/sys/__clone.S b/lib/nbsd_libc/arch/m68k/sys/__clone.S
new file mode 100644 (file)
index 0000000..d51788b
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: __clone.S,v 1.3 2008/04/28 20:22:56 martin Exp $       */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Steve C. Woodford.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(clone, __clone)
+#endif
+
+/*
+ * int clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+ENTRY(__clone)
+       movl    %sp@(4),%d0     /* NULL function pointer? */
+       jeq     2f              /* Yup, bomb out */
+       movl    %d0,%a1
+       movl    %sp@(8),%d0     /* NULL stack? */
+       jeq     2f              /* Yup, bomb out */
+       movl    %d0,%a0
+       movl    %sp@(16),%a0@-  /* Push clone's `arg' on its new stack */
+       lea     %a0@(-12),%a0   /* Fake syscall args for the clone */
+       movl    %a0,%sp@-       /* Syscall arg: stack */
+       movl    %sp@(16),%sp@-  /* Syscall arg: flags */
+       clrl    %sp@-           /* Fake return address */
+       SYSTRAP(__clone)        /* Note: `fn' in a1@ is preserved */
+       lea     %sp@(12),%sp    /* Zap syscall args */
+       jcs     3f              /* Punt if syscall failed */
+       tstl    %d0
+       jne     1f              /* We're the parent, just return. */
+       jsr     %a1@            /* We're the clone, call the function */
+       movl    %d0,%sp@-       /* If clone returns, invoke _exit(3) */
+       jbsr    PIC_PLT(_C_LABEL(_exit))
+       /* NOTREACHED */
+1:     rts
+2:     movl    #EINVAL,%d0
+3:     jra     PIC_PLT(CERROR)
diff --git a/lib/nbsd_libc/arch/m68k/sys/__mmap.S b/lib/nbsd_libc/arch/m68k/sys/__mmap.S
new file mode 100644 (file)
index 0000000..0780a99
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: __mmap.S,v 1.2 2008/04/28 20:22:56 martin Exp $        */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+_SYSCALL(__mmap,mmap)
+#ifdef __SVR4_ABI__
+       movl    %d0,%a0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/m68k/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..256a990
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.9 2008/04/28 20:22:56 martin Exp $        */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigaction14_sigtramp.c,v 1.9 2008/04/28 20:22:56 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+#ifdef __LIBC12_SOURCE__
+extern const int __sigtramp_sigcontext_1[]
+    __weak_reference(__sigtramp_sigcontext_1);
+#endif
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern const int __sigtramp_siginfo_2[];
+
+       /*
+        * If no sigaction, use the "default" trampoline since it won't
+        * be used.
+        */
+       if (act == NULL)
+               return  __sigaction_sigtramp(sig, act, oact, NULL, 0);
+
+#ifdef __LIBC12_SOURCE__
+       /*
+        * We select the non-SA_SIGINFO trampoline if SA_SIGINFO is not
+        * set in the sigaction.
+        */
+       if ((act->sa_flags & SA_SIGINFO) == 0) {
+               int sav = errno;
+               int rv =  __sigaction_sigtramp(sig, act, oact,
+                   __sigtramp_sigcontext_1, 1);
+               if (rv >= 0 || errno != EINVAL)
+                       return rv;
+               errno = sav;
+       }
+#endif
+
+       /*
+        * If SA_SIGINFO was specified or the compatibility trampolines
+        * can't be used, use the siginfo trampoline.
+        */
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_2, 2);
+}
diff --git a/lib/nbsd_libc/arch/m68k/sys/__sigtramp2.S b/lib/nbsd_libc/arch/m68k/sys/__sigtramp2.S
new file mode 100755 (executable)
index 0000000..3885afe
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: __sigtramp2.S,v 1.2 2008/05/02 18:34:17 martin Exp $ */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+/*
+ * The m68k signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ *
+ * On entry, stack looks like:
+ *
+ *             ucontext structure                      [12+sizeof(siginfo_t)]
+ *             siginfo structure                       [12]
+ *             pointer to ucontext structure           [8]
+ *             pointer to siginfo structure            [4]
+ *     sp->    signal number                           [0]
+ */
+ENTRY_NOPROFILE(__sigtramp_siginfo_2)
+       movl    %sp@(8),%a0     /* get pointer to ucontext */
+       movl    %a0,%sp@(4)     /* put it in the argument slot */
+                               /* fake return address already there */
+        movl    #SYS_setcontext,%d0
+        trap    #0
+       movl    %d0,%sp@(4)     /* error code */
+       SYSTRAP(exit)           /* exit */
diff --git a/lib/nbsd_libc/arch/m68k/sys/__syscall.S b/lib/nbsd_libc/arch/m68k/sys/__syscall.S
new file mode 100644 (file)
index 0000000..8c4174e
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: __syscall.S,v 1.1 2000/12/13 21:46:23 scw Exp $        */
+
+#include "SYS.h"
+RSYSCALL(__syscall)
diff --git a/lib/nbsd_libc/arch/m68k/sys/__vfork14.S b/lib/nbsd_libc/arch/m68k/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..ed27d41
--- /dev/null
@@ -0,0 +1,107 @@
+/*     $NetBSD: __vfork14.S,v 1.9 2003/08/07 16:42:14 agc Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)Ovfork.s       5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: __vfork14.S,v 1.9 2003/08/07 16:42:14 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * @(#)vfork.s 4.1 (Berkeley) 12/21/80
+ * C library -- vfork
+ */
+
+/*
+ * pid = vfork();
+ *
+ * d1 == 0 in parent process, d1 == 1 in child process.
+ * d0 == pid of child in parent, d0 == pid of parent in child.
+ *
+ * trickery here, due to keith sklower, uses ret to clear the stack,
+ * and then returns with a jump indirect, since only one person can return
+ * with a ret off this stack... we do the ret before we vfork!
+ */
+
+ENTRY(__vfork14)
+       movl    %sp@+,%a1
+       movl    #SYS___vfork14,%d0
+       trap    #0
+       jcs     err
+       subql   #1,%d1  /* from 1 to 0 in child, 0 to -1 in parent */
+       andl    %d1,%d0
+       jmp     %a1@
+err:
+#ifdef _REENTRANT
+       .globl  _C_LABEL(__errno)
+       movl    %a1,%sp@-
+       movl    %d0,%sp@-
+#if defined(PIC) && !defined(__ELF__)
+       movl    #_C_LABEL(_GLOBAL_OFFSET_TABLE_),%a1
+       lea     %pc@(0,a1:l),%a1
+       movl    %a1@(_C_LABEL(__errno):l),%a1
+       jsr     %a1@
+#else
+       jbsr    PIC_PLT(_C_LABEL(__errno))
+#endif /* PIC */
+#ifdef __SVR4_ABI__
+       movl    %sp@+,%a0@
+#else
+       movl    %d0,%a1
+       movl    %sp@+,%a1@
+#endif
+       movl    %sp@+,%a1
+#else
+       .globl  _C_LABEL(errno)
+#ifdef PIC
+#ifdef __ELF__
+       lea     %pc@(_GLOBAL_OFFSET_TABLE_@GOTPC),%a0
+       movl    %a0@(_C_LABEL(errno)@GOT:w),%a0
+#else
+       movl    #_C_LABEL(_GLOBAL_OFFSET_TABLE_),%a0
+       lea     %pc@(0,a0:l),%a0
+       movl    %a0@(_C_LABEL(errno):w),%a0
+#endif
+       movl    %d0,%a0@
+#else
+       movl    %d0,_C_LABEL(errno)
+#endif /* PIC */
+#endif /* _REENTRANT */
+       moveq   #-1,%d0
+       jmp     %a1@
diff --git a/lib/nbsd_libc/arch/m68k/sys/_lwp_getprivate.S b/lib/nbsd_libc/arch/m68k/sys/_lwp_getprivate.S
new file mode 100644 (file)
index 0000000..df907b5
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: _lwp_getprivate.S,v 1.2 2008/04/28 20:22:56 martin Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+SYSCALL(_lwp_getprivate)
+#ifdef __SVR4_ABI__
+       movl    %d0,%a0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/sys/brk.S b/lib/nbsd_libc/arch/m68k/sys/brk.S
new file mode 100644 (file)
index 0000000..be026f8
--- /dev/null
@@ -0,0 +1,94 @@
+/*     $NetBSD: brk.S,v 1.15 2003/12/26 11:21:48 martin Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)brk.s  5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: brk.S,v 1.15 2003/12/26 11:21:48 martin Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+       .globl  _end
+       .globl  _C_LABEL(__minbrk)
+       .globl  CURBRK
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(brk, _brk)
+#endif
+
+       .data
+_C_LABEL(__minbrk):
+       .long   _end
+
+       .text
+
+ENTRY(_brk)
+#ifdef PIC
+#ifdef __ELF__
+       lea     %pc@(_GLOBAL_OFFSET_TABLE_@GOTPC),%a1
+       movl    %a1@(_C_LABEL(__minbrk)@GOT:w),%a0
+#else
+       movl    #_C_LABEL(_GLOBAL_OFFSET_TABLE_),%a1
+       lea     %pc@(0,a1:l),%a1
+       movl    %a1@(_C_LABEL(__minbrk):w),%a0
+#endif
+       movl    %a0@,%d0
+#else
+       movl    _C_LABEL(__minbrk),%d0
+#endif
+       cmpl    %sp@(4),%d0
+       jls     ok
+       movl    %d0,%sp@(4)
+ok:
+       movl    #SYS_break,%d0
+       trap    #0
+       jcs     err
+#ifdef PIC
+#ifdef __ELF__
+       movl    %a1@(CURBRK@GOT:w),%a0
+#else
+       movl    %a1@(CURBRK:w),%a0
+#endif
+       movl    %sp@(4),%a0@
+#else
+       movl    %sp@(4),CURBRK
+#endif
+       clrl    %d0
+       rts
+err:
+       jra     PIC_PLT(CERROR)
diff --git a/lib/nbsd_libc/arch/m68k/sys/cerror.S b/lib/nbsd_libc/arch/m68k/sys/cerror.S
new file mode 100644 (file)
index 0000000..40d2be2
--- /dev/null
@@ -0,0 +1,86 @@
+/*     $NetBSD: cerror.S,v 1.15 2009/10/03 22:28:33 phx Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)cerror.s       5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: cerror.S,v 1.15 2009/10/03 22:28:33 phx Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef _REENTRANT
+       .globl  _C_LABEL(__errno)
+#else
+       .globl  _C_LABEL(errno)
+#endif
+_ENTRY(CERROR)
+#ifdef _REENTRANT
+       movl    %d0,%sp@-
+#if defined(PIC) && !defined(__ELF__)
+       movl    #_C_LABEL(_GLOBAL_OFFSET_TABLE_),%a0
+       lea     %pc@(0,%a0:l),%a0
+       movl    %a0@(_C_LABEL(__errno):l),%a0
+       jsr     %a0@
+#else
+       jbsr    PIC_PLT(_C_LABEL(__errno))
+#endif
+#ifndef        __SVR4_ABI__
+       movl    %d0,%a0
+#endif
+       movl    %sp@+,%a0@
+#else
+#ifdef PIC
+#ifdef __ELF__
+       lea     %pc@(_GLOBAL_OFFSET_TABLE_@GOTPC),%a0
+       movl    %a0@(_C_LABEL(errno)@GOT:w),%a0
+#else
+       movl    #_C_LABEL(_GLOBAL_OFFSET_TABLE_),%a0
+       lea     %pc@(0,a0:l),%a0
+       movl    %a0@(_C_LABEL(errno):w),%a0
+#endif
+       movl    %d0,%a0@
+#else
+       movl    %d0,_C_LABEL(errno)
+#endif
+#endif /* _REENTRANT */
+       movl    #-1,%d0
+       movl    #-1,%d1
+#ifdef __SVR4_ABI__
+       movl    %d0,%a0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/sys/exect.S b/lib/nbsd_libc/arch/m68k/sys/exect.S
new file mode 100644 (file)
index 0000000..5be1a0a
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: exect.S,v 1.7 2003/08/07 16:42:14 agc Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+#include <machine/psl.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)exect.s        5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: exect.S,v 1.7 2003/08/07 16:42:14 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(exect)
+       movl    #SYS_execve,%d0
+       trap    #0
+       jra     PIC_PLT(CERROR) /* exect(file, argv, env) */
diff --git a/lib/nbsd_libc/arch/m68k/sys/fork.S b/lib/nbsd_libc/arch/m68k/sys/fork.S
new file mode 100644 (file)
index 0000000..84a957a
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: fork.S,v 1.7 2003/08/07 16:42:14 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)fork.s 5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: fork.S,v 1.7 2003/08/07 16:42:14 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+_SYSCALL(__fork,fork)
+       subql   #1,%d1  /* from 1 to 0 in child, 0 to -1 in parent */
+       andl    %d1,%d0
+       rts             /* pid = fork() */
diff --git a/lib/nbsd_libc/arch/m68k/sys/getcontext.S b/lib/nbsd_libc/arch/m68k/sys/getcontext.S
new file mode 100644 (file)
index 0000000..d29104a
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: getcontext.S,v 1.3 2008/04/28 20:22:56 martin Exp $    */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: getcontext.S,v 1.3 2008/04/28 20:22:56 martin Exp $")
+#endif /* SYSLIBC_SCCS && !lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext, _getcontext)
+#endif
+
+_SYSCALL(_getcontext,getcontext)
+       movl    %sp@(4),%a0
+       addql   #4,%a0@(96)             | adjust saved stack pointer
+       movl    %sp@,%a0@(100)          | adjust saved program counter
+       clrl    %a0@(36)                | arrange for return value of 0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/sys/mremap.S b/lib/nbsd_libc/arch/m68k/sys/mremap.S
new file mode 100644 (file)
index 0000000..624be03
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: mremap.S,v 1.2 2008/04/28 20:22:56 martin Exp $        */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+SYSCALL(mremap)
+#ifdef __SVR4_ABI__
+       movl    %d0,%a0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/sys/pipe.S b/lib/nbsd_libc/arch/m68k/sys/pipe.S
new file mode 100644 (file)
index 0000000..860252b
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: pipe.S,v 1.6 2003/08/07 16:42:14 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)pipe.s 5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: pipe.S,v 1.6 2003/08/07 16:42:14 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe, _pipe)
+#endif
+
+_SYSCALL(_pipe,pipe)
+       movl    %sp@(4),%a0
+       movl    %d0,%a0@+
+       movl    %d1,%a0@
+       clrl    %d0
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/sys/ptrace.S b/lib/nbsd_libc/arch/m68k/sys/ptrace.S
new file mode 100644 (file)
index 0000000..58c27d3
--- /dev/null
@@ -0,0 +1,86 @@
+/*     $NetBSD: ptrace.S,v 1.11 2003/08/07 16:42:14 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)ptrace.s       5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: ptrace.S,v 1.11 2003/08/07 16:42:14 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef _REENTRANT
+       .globl  _C_LABEL(__errno)
+#else
+       .globl  _C_LABEL(errno)
+#endif
+
+ENTRY(ptrace)
+#ifdef _REENTRANT
+#if defined(PIC) && !defined(__ELF__)
+       movl    #_C_LABEL(_GLOBAL_OFFSET_TABLE_),%a0
+       lea     %pc@(0,%a0:l),%a0
+       movl    %a0@(_C_LABEL(__errno):l),%a0
+       jsr     %a0@
+#else
+       jbsr    PIC_PLT(_C_LABEL(__errno))
+#endif /* PIC */
+#ifndef        __SVR4_ABI__
+       movl    %d0,%a0
+#endif
+       clrl    %a0@
+#else
+#ifdef PIC
+#ifdef __ELF__
+       lea     %pc@(_GLOBAL_OFFSET_TABLE_@GOTPC),%a0
+       movl    %a0@(_C_LABEL(errno)@GOT:w),%a0
+#else
+       movl    #_C_LABEL(_GLOBAL_OFFSET_TABLE_),%a0
+       lea     %pc@(0,%a0:l),%a0
+       movl    %a0@(_C_LABEL(errno):w),%a0
+#endif
+       clrl    %a0@
+#else
+       clrl    _C_LABEL(errno)
+#endif /* PIC */
+#endif /* _REENTRANT */
+       movl    #SYS_ptrace,%d0
+       trap    #0
+       jcs     err
+       rts
+err:
+       jra     PIC_PLT(CERROR)
diff --git a/lib/nbsd_libc/arch/m68k/sys/sbrk.S b/lib/nbsd_libc/arch/m68k/sys/sbrk.S
new file mode 100644 (file)
index 0000000..2ea3333
--- /dev/null
@@ -0,0 +1,88 @@
+/*     $NetBSD: sbrk.S,v 1.14 2003/08/07 16:42:14 agc Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)sbrk.s 5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: sbrk.S,v 1.14 2003/08/07 16:42:14 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+       .globl  _end
+       .globl  CURBRK
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(sbrk, _sbrk)
+#endif
+
+       .data
+CURBRK:        .long   _end
+
+       .text
+
+ENTRY(_sbrk)
+#ifdef PIC
+#ifdef __ELF__
+       lea     %pc@(_GLOBAL_OFFSET_TABLE_@GOTPC),%a1
+       movl    %a1@(CURBRK@GOT:w),%a1
+#else
+       movl    #_C_LABEL(_GLOBAL_OFFSET_TABLE_),%a1
+       lea     %pc@(0,%a1:l),%a1
+       movl    %a1@(CURBRK:w),%a1
+#endif
+       movl    %a1@,%d0
+#else
+       movl    CURBRK,%d0
+#endif
+       addl    %d0,%sp@(4)
+       movl    #SYS_break,%d0
+       trap    #0
+       jcs     err
+#ifdef PIC
+       movl    %a1@,%d0
+       movl    %sp@(4),%a1@
+#else
+       movl    CURBRK,%d0
+       movl    %sp@(4),CURBRK
+#endif
+#ifdef __SVR4_ABI__
+       movl    %d0,%a0
+#endif
+       rts
+err:
+       jra     PIC_PLT(CERROR)
diff --git a/lib/nbsd_libc/arch/m68k/sys/shmat.S b/lib/nbsd_libc/arch/m68k/sys/shmat.S
new file mode 100644 (file)
index 0000000..3a65ab4
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: shmat.S,v 1.2 2008/04/28 20:22:56 martin Exp $ */
+
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+SYSCALL(shmat)
+#ifdef __SVR4_ABI__
+       movl    %d0,%a0
+#endif
+       rts
diff --git a/lib/nbsd_libc/arch/m68k/sys/syscall.S b/lib/nbsd_libc/arch/m68k/sys/syscall.S
new file mode 100644 (file)
index 0000000..a06ae29
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: syscall.S,v 1.7 2003/08/07 16:42:14 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)syscall.s      5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: syscall.S,v 1.7 2003/08/07 16:42:14 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(syscall)
+       clrl    %d0
+       trap    #0
+       jcs     err
+       rts
+err:
+       jra     PIC_PLT(CERROR)
diff --git a/lib/nbsd_libc/arch/mips/Makefile.inc b/lib/nbsd_libc/arch/mips/Makefile.inc
new file mode 100644 (file)
index 0000000..032d3d9
--- /dev/null
@@ -0,0 +1,11 @@
+#      $NetBSD: Makefile.inc,v 1.9 2009/12/14 01:07:41 matt Exp $
+
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S
+
+CPPFLAGS+= -I.
+CPPFLAGS.assym.h+=-D__LIBC12_SOURCE__
+
+.if ${MKSOFTFLOAT} != "no"
+.include <softfloat/Makefile.inc>
+CPPFLAGS+= -DSOFTFLOAT_NEED_FIXUNS
+.endif
diff --git a/lib/nbsd_libc/arch/mips/SYS.h b/lib/nbsd_libc/arch/mips/SYS.h
new file mode 100644 (file)
index 0000000..2bafcc0
--- /dev/null
@@ -0,0 +1,141 @@
+/*     $NetBSD: SYS.h,v 1.19 2009/12/14 01:07:41 matt Exp $ */
+
+/*-
+ * Copyright (c) 1996 Jonathan Stone
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Jonathan Stone for
+ *      the NetBSD Project.
+ * 4. 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 ``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 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.
+ */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)SYS.h 8.1 (Berkeley) 6/4/93
+ */
+
+#include <sys/syscall.h>
+#include <mips/asm.h>
+
+
+/*
+ * If compiling for shared libs, Emit sysV ABI PIC segment pseudo-ops.
+ *
+ * i)  Emit .abicalls before .LEAF entrypoint, and .cpload/.cprestore after.
+ * ii) Do interprocedure jumps indirectly via t9, with the side-effect of
+ *     preserving the callee's entry address in t9.
+ */
+#ifdef __ABICALLS__
+       .abicalls
+# if defined(__mips_o32) || defined(__mips_o64)
+#  define PIC_PROLOGUE(x)      SETUP_GP
+#  define PIC_TAILCALL(l)      PTR_LA t9, _C_LABEL(l); jr t9
+#  define PIC_RETURN()         j ra
+# else
+#  define PIC_PROLOGUE(x)      SETUP_GP64(t3, x)
+#  define PIC_TAILCALL(l)      PTR_LA t9, _C_LABEL(l); RESTORE_GP64; jr t9
+#  define PIC_RETURN()         RESTORE_GP64; j ra
+# endif
+#else
+# define PIC_PROLOGUE(x)
+# define PIC_TAILCALL(l)       j  _C_LABEL(l)
+# define PIC_RETURN()
+#endif /* __ABICALLS__ */
+
+
+#ifdef __STDC__
+# define SYSTRAP(x)    li v0,SYS_ ## x; syscall;
+#else
+# define SYSTRAP(x)    li v0,SYS_/**/x; syscall;
+#endif
+
+
+/*
+ * Do a syscall that cannot fail (sync, get{p,u,g,eu,eg)id)
+ */
+#define RSYSCALL_NOERROR(x)                                            \
+       PSEUDO_NOERROR(x,x)
+
+/*
+ * Do a normal syscall.
+ */
+#define RSYSCALL(x)                                                    \
+       PSEUDO(x,x)
+
+/*
+ * Do a syscall that has an internal name and a weak external alias.
+ */
+#define        WSYSCALL(weak,strong)                                           \
+       WEAK_ALIAS(weak,strong);                                        \
+       PSEUDO(strong,weak)
+
+/*
+ * Do a renamed or pseudo syscall (e.g., _exit()), where the entrypoint
+ * and syscall name are not the same.
+ */
+#define PSEUDO_NOERROR(x,y)                                            \
+LEAF(x);                                                               \
+       SYSTRAP(y);                                                     \
+       j ra;                                                           \
+       END(x)
+
+#define PSEUDO(x,y)                                                    \
+LEAF(x);                                                               \
+       PIC_PROLOGUE(x);                                                \
+       SYSTRAP(y);                                                     \
+       bne a3,zero,err;                                                \
+       PIC_RETURN();                                                   \
+err:                                                                   \
+       PIC_TAILCALL(__cerror);                                         \
+END(x)
diff --git a/lib/nbsd_libc/arch/mips/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/mips/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..51535fa
--- /dev/null
@@ -0,0 +1,9 @@
+#      $NetBSD: Makefile.inc,v 1.4 2011/01/20 18:41:39 matt Exp $
+
+SRCS+= strtof.c
+.if (${MACHINE_ARCH} == "mips64eb" || ${MACHINE_ARCH} == "mips64el")
+.if !defined(CPUFLAGS) || empty(CPUFLAGS:M-mabi=32)
+SRCS+= strtold_pQ.c
+SRCS+= strtopQ.c
+.endif
+.endif
diff --git a/lib/nbsd_libc/arch/mips/gdtoa/arith.h b/lib/nbsd_libc/arch/mips/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..40d3ed1
--- /dev/null
@@ -0,0 +1,9 @@
+/* $NetBSD: arith.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#include <machine/endian.h>
+
+#if BYTE_ORDER == BIG_ENDIAN
+#define IEEE_BIG_ENDIAN
+#else
+#define IEEE_LITTLE_ENDIAN
+#endif
diff --git a/lib/nbsd_libc/arch/mips/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/mips/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..7fcafc0
--- /dev/null
@@ -0,0 +1,20 @@
+/* $NetBSD: gd_qnan.h,v 1.2 2011/01/17 23:53:03 matt Exp $ */
+
+#include <machine/endian.h>
+
+#define f_QNAN 0x7fa00000
+#if BYTE_ORDER == BIG_ENDIAN
+#define d_QNAN0 0x7ff40000
+#define d_QNAN1 0x0
+#define ld_QNAN0 0x7fff8000
+#define ld_QNAN1 0x0
+#define ld_QNAN2 0x0
+#define ld_QNAN3 0x0
+#else
+#define d_QNAN0 0x0
+#define d_QNAN1 0x7ff40000
+#define ld_QNAN0 0x0
+#define ld_QNAN1 0x0
+#define ld_QNAN2 0x0
+#define ld_QNAN3 0x7fff8000
+#endif
diff --git a/lib/nbsd_libc/arch/mips/gen/Makefile.inc b/lib/nbsd_libc/arch/mips/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..08d2e37
--- /dev/null
@@ -0,0 +1,38 @@
+#      $NetBSD: Makefile.inc,v 1.32 2011/01/17 23:53:03 matt Exp $
+
+.if ${MKSOFTFLOAT} == "no"
+SRCS+= fabs.S ldexp.S modf.S
+.else
+SRCS+= fabs_ieee754.c ldexp_ieee754.c modf_ieee754.c
+.endif
+
+# Common ieee754 constants and functions
+SRCS+= infinityf_ieee754.c infinity_ieee754.c infinityl_ieee754.c
+SRCS+= fpclassifyf_ieee754.c fpclassifyd_ieee754.c fpclassifyl_ieee754.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c isinfl_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c isnanl_ieee754.c
+SRCS+= isfinitef_ieee754.c isfinited_ieee754.c isfinitel_ieee754.c
+SRCS+= signbitf_ieee754.c signbitd_ieee754.c signbitl_ieee754.c
+
+SRCS+= nanf.c
+SRCS+= flt_rounds.c
+
+.if ${MKSOFTFLOAT} == "no"
+SRCS+= fpgetmask.c fpgetround.c fpgetsticky.c fpsetmask.c \
+       fpsetround.c fpsetsticky.c
+.endif
+
+SRCS+= setjmp.S longjmp.c
+SRCS+= _setjmp.S
+SRCS+= sigsetjmp.S
+SRCS+= byte_swap_2.S byte_swap_4.S byte_swap_8.S
+
+SRCS+= makecontext.c resumecontext.c _resumecontext.S swapcontext.S _lwp.c
+
+# mips abi builtin extensions (used by GCC for lexical-closure trampoline)
+SRCS+= cacheflush.c
+
+LSRCS.mips.gen=        Lint__setjmp.c Lint_bswap16.c Lint_bswap32.c Lint_swapcontext.c
+LSRCS+=                ${LSRCS.mips.gen}
+DPSRCS+=       ${LSRCS.mips.gen}
+CLEANFILES+=   ${LSRCS.mips.gen}
diff --git a/lib/nbsd_libc/arch/mips/gen/_lwp.c b/lib/nbsd_libc/arch/mips/gen/_lwp.c
new file mode 100644 (file)
index 0000000..4082402
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: _lwp.c,v 1.5 2008/04/28 20:22:56 martin Exp $  */
+
+/*
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Wayne Knowles
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.5 2008/04/28 20:22:56 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+
+#define CALLFRAME_SIZ  24
+
+void _lwp_makecontext(ucontext_t *u, void (*start)(void *),
+       void *arg, void *private, caddr_t stack_base, size_t stack_size)
+{
+       caddr_t sp;
+       __greg_t *gr;
+
+       getcontext(u);
+       gr = u->uc_mcontext.__gregs;
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+       sp = stack_base + stack_size - CALLFRAME_SIZ;
+
+       gr[_REG_EPC] = (unsigned long) start;
+       gr[_REG_T9] = (unsigned long) start; /* required for .abicalls */
+       gr[_REG_RA] = (unsigned long) _lwp_exit;
+       gr[_REG_A0] = (unsigned long) arg;
+       gr[_REG_SP] = (unsigned long) sp;
+}
diff --git a/lib/nbsd_libc/arch/mips/gen/_resumecontext.S b/lib/nbsd_libc/arch/mips/gen/_resumecontext.S
new file mode 100644 (file)
index 0000000..2631070
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: _resumecontext.S,v 1.6 2009/12/14 01:07:42 matt Exp $  */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Wayne Knowles.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+
+#include "SYS.h"
+#include "assym.h"
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: _resumecontext.S,v 1.6 2009/12/14 01:07:42 matt Exp $")
+#endif /* SYSLIBC_SCCS && !lint */
+
+       .set    reorder
+       .hidden _C_LABEL(__resumecontext)
+       
+LEAF_NOPROFILE(__resumecontext)
+       /*
+        * We get here not by a call through $t9 but thru $ra after the
+        * function passed to makecontext returns.
+        */
+       PTR_SUBU        sp, sp, UCONTEXT_SIZE           # get space for ucontext
+       move            a0, sp                          # arg0 for getcontext
+       PTR_S           zero, _OFFSETOF_UC_LINK(a0)     # make sure uc_link is 0
+       SYSTRAP(getcontext)                             # get context
+       PTR_L           a0, _OFFSETOF_UC_LINK(a0)       # linked context?
+       beq             a0, zero, 1f                    #   nope, exit process
+       nop
+       SYSTRAP(setcontext)                             #   yes, become it.
+       /* NOTREACHED (in theory) */
+       li              a0, -1                          # failure, 
+1:
+       SYSTRAP(exit)                                   # all hope is lost.
+       /* NOTREACHED */
+END(__resumecontext)
diff --git a/lib/nbsd_libc/arch/mips/gen/_setjmp.S b/lib/nbsd_libc/arch/mips/gen/_setjmp.S
new file mode 100644 (file)
index 0000000..3d2f91f
--- /dev/null
@@ -0,0 +1,188 @@
+/*     $NetBSD: _setjmp.S,v 1.22 2010/09/03 17:22:51 matt Exp $        */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <machine/cdefs.h>
+#include <mips/regnum.h>
+#include <mips/asm.h>
+#include <machine/setjmp.h>
+#include <machine/signal.h>            /* XXX */
+
+#include "assym.h"
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)_setjmp.s      8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: _setjmp.S,v 1.22 2010/09/03 17:22:51 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     _longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     _setjmp(a)
+ * by restoring registers from the stack,
+ * The previous signal state is NOT restored.
+ */
+
+       .set    noreorder
+
+LEAF(_setjmp)
+       REG_PROLOGUE
+       REG_LI  v0, 0xACEDBADE                  # sigcontext magic number
+       REG_S   ra, _OFFSETOF_SC_PC(a0)         # sc_pc = return address
+       REG_S   v0, _OFFSETOF_SC_REGS(a0)       #   saved in sc_regs[0]
+       REG_S   s0, _OFFSETOF_SC_REGS_S0(a0)
+       REG_S   s1, _OFFSETOF_SC_REGS_S1(a0)
+       REG_S   s2, _OFFSETOF_SC_REGS_S2(a0)
+       REG_S   s3, _OFFSETOF_SC_REGS_S3(a0)
+       REG_S   s4, _OFFSETOF_SC_REGS_S4(a0)
+       REG_S   s5, _OFFSETOF_SC_REGS_S5(a0)
+       REG_S   s6, _OFFSETOF_SC_REGS_S6(a0)
+       REG_S   s7, _OFFSETOF_SC_REGS_S7(a0)
+       REG_S   sp, _OFFSETOF_SC_REGS_SP(a0)
+       REG_S   s8, _OFFSETOF_SC_REGS_S8(a0)
+#if defined(__mips_n32) || defined(__mips_n64)
+       REG_S   gp, _OFFSETOF_SC_REGS_GP(a0)    # newabi gp is callee-saved
+#endif
+       /*
+        * In N32, FP registers F20, F22, F24, F26, F28, F30 are callee-saved.
+        * In N64, FP registers F23 .. F31 are callee-saved.
+        * In O32, FP registers F20 .. F23 are callee-saved.
+        */
+#ifndef SOFTFLOAT_FOR_GCC
+       cfc1    v0, $31                         # too bad cant check if FP used
+       INT_S   v0, _OFFSETOF_SC_FPREGS_FCSR(a0)
+#if defined(__mips_n64) || defined(__mips_n32)
+       FP_S    $f30, _OFFSETOF_SC_FPREGS_F30(a0)
+       FP_S    $f28, _OFFSETOF_SC_FPREGS_F28(a0)
+       FP_S    $f26, _OFFSETOF_SC_FPREGS_F26(a0)
+       FP_S    $f24, _OFFSETOF_SC_FPREGS_F24(a0)
+#endif
+#if defined(__mips_n32) || defined(__mips_o32) || defined(__mips_o64)
+       FP_S    $f22, _OFFSETOF_SC_FPREGS_F22(a0)
+       FP_S    $f20, _OFFSETOF_SC_FPREGS_F20(a0)
+#endif
+#if defined(__mips_o32) || defined(__mips_o64)
+       FP_S    $f21, _OFFSETOF_SC_FPREGS_F21(a0)
+       FP_S    $f23, _OFFSETOF_SC_FPREGS_F23(a0)
+#endif
+#if defined(__mips_n64)
+       FP_S    $f25, _OFFSETOF_SC_FPREGS_F25(a0)
+       FP_S    $f27, _OFFSETOF_SC_FPREGS_F27(a0)
+       FP_S    $f29, _OFFSETOF_SC_FPREGS_F29(a0)
+       FP_S    $f31, _OFFSETOF_SC_FPREGS_F31(a0)
+#endif
+#endif /* SOFTFLOAT_FOR_GCC */
+       REG_EPILOGUE
+
+       j       ra
+       move    v0, zero
+END(_setjmp)
+
+LEAF(_longjmp)
+       PIC_PROLOGUE(_longjmp)
+       PTR_SUBU        sp, sp, CALLFRAME_SIZ
+       SAVE_GP(CALLFRAME_GP)
+
+       REG_PROLOGUE
+       REG_L           v0, _OFFSETOF_SC_REGS(a0)       # get magic number
+       REG_L           ra, _OFFSETOF_SC_PC(a0)
+       REG_LI          t0, 0xACEDBADE
+       bne             v0, t0, botch           # jump if error
+       PTR_ADDU        sp, sp, CALLFRAME_SIZ   # does not matter, sanity
+       REG_S           a1, _OFFSETOF_SC_REGS_V0(a0)    # save return value
+       REG_L           s0, _OFFSETOF_SC_REGS_S0(a0)
+       REG_L           s1, _OFFSETOF_SC_REGS_S1(a0)
+       REG_L           s2, _OFFSETOF_SC_REGS_S2(a0)
+       REG_L           s3, _OFFSETOF_SC_REGS_S3(a0)
+       REG_L           s4, _OFFSETOF_SC_REGS_S4(a0)
+       REG_L           s5, _OFFSETOF_SC_REGS_S5(a0)
+       REG_L           s6, _OFFSETOF_SC_REGS_S6(a0)
+       REG_L           s7, _OFFSETOF_SC_REGS_S7(a0)
+#if defined(__mips_n32) || defined(__mips_n64)
+       REG_L           gp, _OFFSETOF_SC_REGS_GP(a0)
+#endif
+       # get fpu status
+       REG_L           sp, _OFFSETOF_SC_REGS_SP(a0)
+       REG_L           s8, _OFFSETOF_SC_REGS_S8(a0)
+#ifndef SOFTFLOAT_FOR_GCC
+       INT_L           v0, _OFFSETOF_SC_FPREGS_FCSR(a0)
+       ctc1            v0, $31
+       /*
+        * In N32, FP registers F20, F22, F24, F26, F28, F30 are callee-saved.
+        * In N64, FP registers F23 .. F31 are callee-saved.
+        * In O32, FP registers F20 .. F23 are callee-saved.
+        */
+#if defined(__mips_n64) || defined(__mips_n32)
+       FP_L    $f30, _OFFSETOF_SC_FPREGS_F30(a0)
+       FP_L    $f28, _OFFSETOF_SC_FPREGS_F28(a0)
+       FP_L    $f26, _OFFSETOF_SC_FPREGS_F26(a0)
+       FP_L    $f24, _OFFSETOF_SC_FPREGS_F24(a0)
+#endif
+#if defined(__mips_n32) || defined(__mips_o32) || defined(__mips_o64)
+       FP_L    $f22, _OFFSETOF_SC_FPREGS_F22(a0)
+       FP_L    $f20, _OFFSETOF_SC_FPREGS_F20(a0)
+#endif
+#if defined(__mips_o32) || defined(__mips_o64)
+       FP_L    $f21, _OFFSETOF_SC_FPREGS_F21(a0)
+       FP_L    $f23, _OFFSETOF_SC_FPREGS_F23(a0)
+#endif
+#if defined(__mips_n64)
+       FP_L    $f25, _OFFSETOF_SC_FPREGS_F25(a0)
+       FP_L    $f27, _OFFSETOF_SC_FPREGS_F27(a0)
+       FP_L    $f29, _OFFSETOF_SC_FPREGS_F29(a0)
+       FP_L    $f31, _OFFSETOF_SC_FPREGS_F31(a0)
+#endif
+#endif /* SOFTFLOAT_FOR_GCC */
+
+       REG_EPILOGUE
+       move    v0, a1                  # get return value in 1st arg
+       j       ra
+       nop
+
+botch:
+       /*
+        * We know we aren't returning so we don't care about restoring
+        * our caller's GP.
+        */
+       jal     _C_LABEL(longjmperror)
+       
+       PIC_TAILCALL(abort)
+END(_longjmp)
diff --git a/lib/nbsd_libc/arch/mips/gen/cacheflush.c b/lib/nbsd_libc/arch/mips/gen/cacheflush.c
new file mode 100644 (file)
index 0000000..45a9aef
--- /dev/null
@@ -0,0 +1,47 @@
+/* $NetBSD: cacheflush.c,v 1.4 2008/04/28 20:22:56 martin Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jonathan Stone.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/types.h>
+#include <mips/cachectl.h>
+#include <mips/sysarch.h>
+
+int
+_cacheflush(addr, nbytes, whichcache)
+       void * addr;
+       int nbytes, whichcache;
+{
+       struct mips_cacheflush_args cfa;
+
+       cfa.va = (vaddr_t) addr;
+       cfa.nbytes = nbytes;
+       cfa.whichcache = whichcache;
+       return (sysarch(MIPS_CACHEFLUSH, (void *)&cfa));
+}
diff --git a/lib/nbsd_libc/arch/mips/gen/fabs.S b/lib/nbsd_libc/arch/mips/gen/fabs.S
new file mode 100644 (file)
index 0000000..812b70e
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: fabs.S,v 1.8 2009/12/14 01:07:42 matt Exp $    */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)fabs.s 8.1 (Berkeley) 2/16/94")
+#else
+       RCSID("$NetBSD: fabs.S,v 1.8 2009/12/14 01:07:42 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+
+       .set    noreorder
+
+/*
+ * fabs(x)
+ *     double x;
+ *
+ * Return absolute value of x.
+ */
+LEAF(fabs)
+       j       ra
+       abs.d   $f0, $f12               # compute absolute value of x
+END(fabs)
diff --git a/lib/nbsd_libc/arch/mips/gen/flt_rounds.c b/lib/nbsd_libc/arch/mips/gen/flt_rounds.c
new file mode 100644 (file)
index 0000000..ab8a5cd
--- /dev/null
@@ -0,0 +1,34 @@
+/*     $NetBSD: flt_rounds.c,v 1.6 2010/09/03 17:22:51 matt Exp $      */
+
+/*
+ * Written by J.T. Conklin, Apr 11, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: flt_rounds.c,v 1.6 2010/09/03 17:22:51 matt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/float.h>
+#include <ieeefp.h>
+
+static const int map[] = {
+       1,      /* round to nearest */
+       0,      /* round to zero */
+       2,      /* round to positive infinity */
+       3       /* round to negative infinity */
+};
+
+int
+__flt_rounds()
+{
+#ifdef SOFTFLOAT_FOR_GCC
+       return map[fpgetround()];
+#else
+       int x;
+
+       __asm("cfc1\t%0,$31" : "=r" (x));
+       return map[x & 0x03];
+#endif
+}
diff --git a/lib/nbsd_libc/arch/mips/gen/fpgetmask.c b/lib/nbsd_libc/arch/mips/gen/fpgetmask.c
new file mode 100644 (file)
index 0000000..1e62810
--- /dev/null
@@ -0,0 +1,28 @@
+/*     $NetBSD: fpgetmask.c,v 1.5 2005/12/24 23:10:08 perry Exp $      */
+
+/*
+ * Written by J.T. Conklin, Apr 11, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetmask.c,v 1.5 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetmask,_fpgetmask)
+#endif
+
+fp_except
+fpgetmask()
+{
+       int x;
+
+       __asm("cfc1 %0,$31" : "=r" (x));
+       return (x >> 7) & 0x1f;
+}
diff --git a/lib/nbsd_libc/arch/mips/gen/fpgetround.c b/lib/nbsd_libc/arch/mips/gen/fpgetround.c
new file mode 100644 (file)
index 0000000..e05bdc8
--- /dev/null
@@ -0,0 +1,28 @@
+/*     $NetBSD: fpgetround.c,v 1.5 2005/12/24 23:10:08 perry Exp $     */
+
+/*
+ * Written by J.T. Conklin, Apr 11, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetround.c,v 1.5 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetround,_fpgetround)
+#endif
+
+fp_rnd
+fpgetround()
+{
+       int x;
+
+       __asm("cfc1 %0,$31" : "=r" (x));
+       return x & 0x03;
+}
diff --git a/lib/nbsd_libc/arch/mips/gen/fpgetsticky.c b/lib/nbsd_libc/arch/mips/gen/fpgetsticky.c
new file mode 100644 (file)
index 0000000..d72d234
--- /dev/null
@@ -0,0 +1,28 @@
+/*     $NetBSD: fpgetsticky.c,v 1.5 2005/12/24 23:10:08 perry Exp $    */
+
+/*
+ * Written by J.T. Conklin, Apr 11, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetsticky.c,v 1.5 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetsticky,_fpgetsticky)
+#endif
+
+fp_except
+fpgetsticky()
+{
+       int x;
+
+       __asm("cfc1 %0,$31" : "=r" (x));
+       return (x >> 2) & 0x1f;
+}
diff --git a/lib/nbsd_libc/arch/mips/gen/fpsetmask.c b/lib/nbsd_libc/arch/mips/gen/fpsetmask.c
new file mode 100644 (file)
index 0000000..f3710ab
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: fpsetmask.c,v 1.5 2005/12/24 23:10:08 perry Exp $      */
+
+/*
+ * Written by J.T. Conklin, Apr 11, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetmask.c,v 1.5 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetmask,_fpsetmask)
+#endif
+
+fp_except
+fpsetmask(mask)
+       fp_except mask;
+{
+       fp_except old;
+       fp_except new;
+
+       __asm("cfc1 %0,$31" : "=r" (old));
+
+       new = old;
+       new &= ~(0x1f << 7); 
+       new |= ((mask & 0x1f) << 7);
+
+       __asm("ctc1 %0,$31" : : "r" (new));
+
+       return (old >> 7) & 0x1f;
+}
diff --git a/lib/nbsd_libc/arch/mips/gen/fpsetround.c b/lib/nbsd_libc/arch/mips/gen/fpsetround.c
new file mode 100644 (file)
index 0000000..7741b84
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: fpsetround.c,v 1.5 2005/12/24 23:10:08 perry Exp $     */
+
+/*
+ * Written by J.T. Conklin, Apr 11, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetround.c,v 1.5 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetround,_fpsetround)
+#endif
+
+fp_rnd
+fpsetround(rnd_dir)
+       fp_rnd rnd_dir;
+{
+       fp_rnd old;
+       fp_rnd new;
+
+       __asm("cfc1 %0,$31" : "=r" (old));
+
+       new = old;
+       new &= ~0x03;
+       new |= (rnd_dir & 0x03);
+
+       __asm("ctc1 %0,$31" : : "r" (new));
+
+       return old & 0x03;
+}
diff --git a/lib/nbsd_libc/arch/mips/gen/fpsetsticky.c b/lib/nbsd_libc/arch/mips/gen/fpsetsticky.c
new file mode 100644 (file)
index 0000000..c86f595
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: fpsetsticky.c,v 1.5 2005/12/24 23:10:08 perry Exp $    */
+
+/*
+ * Written by J.T. Conklin, Apr 11, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetsticky.c,v 1.5 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetsticky,_fpsetsticky)
+#endif
+
+fp_except
+fpsetsticky(sticky)
+       fp_except sticky;
+{
+       fp_except old;
+       fp_except new;
+
+       __asm("cfc1 %0,$31" : "=r" (old));
+
+       new = old;
+       new &= ~(0x1f << 2); 
+       new |= ((sticky & 0x1f) << 2);
+
+       __asm("ctc1 %0,$31" : : "r" (new));
+
+       return (old >> 2) & 0x1f;
+}
diff --git a/lib/nbsd_libc/arch/mips/gen/ldexp.S b/lib/nbsd_libc/arch/mips/gen/ldexp.S
new file mode 100644 (file)
index 0000000..2c8fca3
--- /dev/null
@@ -0,0 +1,217 @@
+/*     $NetBSD: ldexp.S,v 1.9 2009/12/14 01:07:42 matt Exp $   */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)ldexp.s        8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: ldexp.S,v 1.9 2009/12/14 01:07:42 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#define DEXP_INF       0x7ff
+#define DEXP_BIAS      1023
+#define DEXP_MIN       -1022
+#define DEXP_MAX       1023
+#define DFRAC_BITS     52
+#define DIMPL_ONE      0x00100000
+#define DLEAD_ZEROS    31 - 20
+#define STICKYBIT      1
+#define GUARDBIT       0x80000000
+#define DSIGNAL_NAN    0x00040000
+#define DQUIET_NAN0    0x0007ffff
+#define DQUIET_NAN1    0xffffffff
+
+/*
+ * double ldexp(x, N)
+ *     double x; int N;
+ *
+ * Return x * (2**N), for integer values N.
+ */
+LEAF(ldexp)
+       mfc1    v1, $f13                # get MSW of x
+       mfc1    t3, $f12                # get LSW of x
+       sll     t1, v1, 1               # get x exponent
+       srl     t1, t1, 32 - 11
+       beq     t1, DEXP_INF, 9f        # is it a NAN or infinity?
+       beq     t1, zero, 1f            # zero or denormalized number?
+       addu    t1, t1, a2              # scale exponent
+       sll     v0, a2, 20              # position N for addition
+       bge     t1, DEXP_INF, 8f        # overflow?
+       addu    v0, v0, v1              # multiply by (2**N)
+       ble     t1, zero, 4f            # underflow?
+       mtc1    v0, $f1                 # save MSW of result
+       mtc1    t3, $f0                 # save LSW of result
+       j       ra
+1:
+       sll     t2, v1, 32 - 20         # get x fraction
+       srl     t2, t2, 32 - 20
+       srl     t0, v1, 31              # get x sign
+       bne     t2, zero, 1f
+       beq     t3, zero, 9f            # result is zero
+1:
+/*
+ * Find out how many leading zero bits are in t2,t3 and put in t9.
+ */
+       move    v0, t2
+       move    t9, zero
+       bne     t2, zero, 1f
+       move    v0, t3
+       addu    t9, 32
+1:
+       srl     ta0, v0, 16
+       bne     ta0, zero, 1f
+       addu    t9, 16
+       sll     v0, 16
+1:
+       srl     ta0, v0, 24
+       bne     ta0, zero, 1f
+       addu    t9, 8
+       sll     v0, 8
+1:
+       srl     ta0, v0, 28
+       bne     ta0, zero, 1f
+       addu    t9, 4
+       sll     v0, 4
+1:
+       srl     ta0, v0, 30
+       bne     ta0, zero, 1f
+       addu    t9, 2
+       sll     v0, 2
+1:
+       srl     ta0, v0, 31
+       bne     ta0, zero, 1f
+       addu    t9, 1
+/*
+ * Now shift t2,t3 the correct number of bits.
+ */
+1:
+       subu    t9, t9, DLEAD_ZEROS     # dont count normal leading zeros
+       li      t1, DEXP_MIN + DEXP_BIAS
+       subu    t1, t1, t9              # adjust exponent
+       addu    t1, t1, a2              # scale exponent
+       li      v0, 32
+       blt     t9, v0, 1f
+       subu    t9, t9, v0              # shift fraction left >= 32 bits
+       sll     t2, t3, t9
+       move    t3, zero
+       b       2f
+1:
+       subu    v0, v0, t9              # shift fraction left < 32 bits
+       sll     t2, t2, t9
+       srl     ta0, t3, v0
+       or      t2, t2, ta0
+       sll     t3, t3, t9
+2:
+       bge     t1, DEXP_INF, 8f        # overflow?
+       ble     t1, zero, 4f            # underflow?
+       sll     t2, t2, 32 - 20         # clear implied one bit
+       srl     t2, t2, 32 - 20
+3:
+       sll     t1, t1, 31 - 11         # reposition exponent
+       sll     t0, t0, 31              # reposition sign
+       or      t0, t0, t1              # put result back together
+       or      t0, t0, t2
+       mtc1    t0, $f1                 # save MSW of result
+       mtc1    t3, $f0                 # save LSW of result
+       j       ra
+4:
+       li      v0, 0x80000000
+       ble     t1, -52, 7f             # is result too small for denorm?
+       sll     t2, v1, 31 - 20         # clear exponent, extract fraction
+       or      t2, t2, v0              # set implied one bit
+       blt     t1, -30, 2f             # will all bits in t3 be shifted out?
+       srl     t2, t2, 31 - 20         # shift fraction back to normal position
+       subu    t1, t1, 1
+       sll     ta0, t2, t1             # shift right t2,t3 based on exponent
+       srl     t8, t3, t1              # save bits shifted out
+       negu    t1
+       srl     t3, t3, t1
+       or      t3, t3, ta0
+       srl     t2, t2, t1
+       bge     t8, zero, 1f            # does result need to be rounded?
+       addu    t3, t3, 1               # round result
+       sltu    ta0, t3, 1
+       sll     t8, t8, 1
+       addu    t2, t2, ta0
+       bne     t8, zero, 1f            # round result to nearest
+       and     t3, t3, ~1
+1:
+       mtc1    t3, $f0                 # save denormalized result (LSW)
+       mtc1    t2, $f1                 # save denormalized result (MSW)
+       bge     v1, zero, 1f            # should result be negative?
+       neg.d   $f0, $f0                # negate result
+1:
+       j       ra
+2:
+       mtc1    zero, $f1               # exponent and upper fraction
+       addu    t1, t1, 20              # compute amount to shift right by
+       sll     t8, t2, t1              # save bits shifted out
+       negu    t1
+       srl     t3, t2, t1
+       bge     t8, zero, 1f            # does result need to be rounded?
+       addu    t3, t3, 1               # round result
+       sltu    ta0, t3, 1
+       sll     t8, t8, 1
+       mtc1    ta0, $f1                        # exponent and upper fraction
+       bne     t8, zero, 1f            # round result to nearest
+       and     t3, t3, ~1
+1:
+       mtc1    t3, $f0
+       bge     v1, zero, 1f            # is result negative?
+       neg.d   $f0, $f0                # negate result
+1:
+       j       ra
+7:
+       mtc1    zero, $f0               # result is zero
+       mtc1    zero, $f1
+       beq     t0, zero, 1f            # is result positive?
+       neg.d   $f0, $f0                # negate result
+1:
+       j       ra
+8:
+       li      t1, 0x7ff00000          # result is infinity (MSW)
+       mtc1    t1, $f1 
+       mtc1    zero, $f0               # result is infinity (LSW)
+       bge     v1, zero, 1f            # should result be negative infinity?
+       neg.d   $f0, $f0                # result is negative infinity
+1:
+       add.d   $f0, $f0                # cause overflow faults if enabled
+       j       ra
+9:
+       mov.d   $f0, $f12               # yes, result is just x
+       j       ra
+END(ldexp)
diff --git a/lib/nbsd_libc/arch/mips/gen/longjmp.c b/lib/nbsd_libc/arch/mips/gen/longjmp.c
new file mode 100644 (file)
index 0000000..8a70721
--- /dev/null
@@ -0,0 +1,108 @@
+/*     $NetBSD: longjmp.c,v 1.4 2010/09/03 17:22:51 matt Exp $ */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christian Limpach and Matt Thomas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <machine/regnum.h>
+
+#define __LIBC12_SOURCE__
+#include <setjmp.h>
+#include <compat/include/setjmp.h>
+
+void
+__longjmp14(jmp_buf env, int val)
+{
+       struct sigcontext *sc = (void *)env;
+       ucontext_t uc;
+
+       /* Ensure non-zero SP and sigcontext magic number is present */
+       if (sc->sc_regs[_R_SP] == 0 || sc->sc_regs[_R_ZERO] != (mips_reg_t)0xACEDBADE)
+               goto err;
+
+       /* Ensure non-zero return value */
+       if (val == 0)
+               val = 1;
+
+       /*
+        * Set _UC_{SET,CLR}STACK according to SS_ONSTACK.
+        *
+        * Restore the signal mask with sigprocmask() instead of _UC_SIGMASK,
+        * since libpthread may want to interpose on signal handling.
+        */
+       uc.uc_flags = _UC_CPU | (sc->sc_onstack ? _UC_SETSTACK : _UC_CLRSTACK);
+
+       sigprocmask(SIG_SETMASK, &sc->sc_mask, NULL);
+
+       /* Clear uc_link */
+       uc.uc_link = 0;
+
+       /* Save return value in context */
+       uc.uc_mcontext.__gregs[_REG_V0] = val;
+
+       /* Copy saved registers */
+       uc.uc_mcontext.__gregs[_REG_S0] = sc->sc_regs[_R_S0];
+       uc.uc_mcontext.__gregs[_REG_S1] = sc->sc_regs[_R_S1];
+       uc.uc_mcontext.__gregs[_REG_S2] = sc->sc_regs[_R_S2];
+       uc.uc_mcontext.__gregs[_REG_S3] = sc->sc_regs[_R_S3];
+       uc.uc_mcontext.__gregs[_REG_S4] = sc->sc_regs[_R_S4];
+       uc.uc_mcontext.__gregs[_REG_S5] = sc->sc_regs[_R_S5];
+       uc.uc_mcontext.__gregs[_REG_S6] = sc->sc_regs[_R_S6];
+       uc.uc_mcontext.__gregs[_REG_S7] = sc->sc_regs[_R_S7];
+       uc.uc_mcontext.__gregs[_REG_S8] = sc->sc_regs[_R_S8];
+#if defined(__mips_n32) || defined(__mips_n64)
+       uc.uc_mcontext.__gregs[_REG_GP] = sc->sc_regs[_R_GP];
+#endif
+       uc.uc_mcontext.__gregs[_REG_SP] = sc->sc_regs[_R_SP];
+       uc.uc_mcontext.__gregs[_REG_RA] = sc->sc_regs[_R_RA];
+       uc.uc_mcontext.__gregs[_REG_EPC] = sc->sc_pc;
+
+       /* Copy FP state */
+       if (sc->sc_fpused) {
+               /* FP saved regs are $f20 .. $f31 */
+               memcpy(&uc.uc_mcontext.__fpregs.__fp_r.__fp_regs[20],
+                   &sc->sc_fpregs[20], 32 - 20);
+               uc.uc_mcontext.__fpregs.__fp_csr =
+                   sc->sc_fpregs[_R_FSR - _FPBASE];
+               /* XXX sc_fp_control */
+               uc.uc_flags |= _UC_FPU;
+       }
+
+       setcontext(&uc);
+ err:
+       longjmperror();
+       abort();
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/mips/gen/makecontext.c b/lib/nbsd_libc/arch/mips/gen/makecontext.c
new file mode 100644 (file)
index 0000000..7aa4298
--- /dev/null
@@ -0,0 +1,95 @@
+/*     $NetBSD: makecontext.c,v 1.5 2009/12/14 01:07:42 matt Exp $     */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.5 2009/12/14 01:07:42 matt Exp $");
+#endif
+
+#include <inttypes.h>
+#include <stddef.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#include <stdarg.h>
+
+void
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+{
+       __greg_t *gr = ucp->uc_mcontext.__gregs;
+       __greg_t *sp;
+       int i;
+       va_list ap;
+
+       void __resumecontext(void);
+
+       /* LINTED uintptr_t is safe */
+       sp  = (__greg_t *)
+           ((uintptr_t)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size);
+       /* LINTED uintptr_t is safe */
+#if defined(__mips_o32) || defined(__mips_o64)
+       sp -= (argc >= 4 ? argc : 4);   /* Make room for >=4 arguments. */
+       sp  = (__greg_t *)
+             ((uintptr_t)sp & ~0x7);   /* Align on double-word boundary. */
+#elif defined(__mips_n32) || defined(__mips_n64)
+       sp -= (argc > 8 ? argc - 8 : 0); /* Make room for > 8 arguments. */
+       sp  = (__greg_t *)
+             ((uintptr_t)sp & ~0xf);   /* Align on quad-word boundary. */
+#endif
+
+       gr[_REG_SP]  = (intptr_t)sp;
+       gr[_REG_RA]  = (intptr_t)__resumecontext;
+       gr[_REG_T9]  = (intptr_t)func;          /* required for .abicalls */
+       gr[_REG_EPC] = (intptr_t)func;
+
+       /* Construct argument list. */
+       va_start(ap, argc);
+#if defined(__mips_o32) || defined(__mips_o64)
+       /* Up to the first four arguments are passed in $a0-3. */
+       for (i = 0; i < argc && i < 4; i++)
+               /* LINTED __greg_t is safe */
+               gr[_REG_A0 + i] = va_arg(ap, __greg_t);
+       /* Pass remaining arguments on the stack above the $a0-3 gap. */
+       sp += i;
+#endif
+#if defined(__mips_n32) || defined(__mips_n64)
+       /* Up to the first 8 arguments are passed in $a0-7. */
+       for (i = 0; i < argc && i < 8; i++)
+               /* LINTED __greg_t is safe */
+               gr[_REG_A0 + i] = va_arg(ap, __greg_t);
+       /* Pass remaining arguments on the stack above the $a0-3 gap. */
+#endif
+       /* Pass remaining arguments on the stack above the $a0-3 gap. */
+       for (; i < argc; i++)
+               /* LINTED uintptr_t is safe */
+               *sp++ = va_arg(ap, __greg_t);
+       va_end(ap);
+}
diff --git a/lib/nbsd_libc/arch/mips/gen/modf.S b/lib/nbsd_libc/arch/mips/gen/modf.S
new file mode 100644 (file)
index 0000000..7e523af
--- /dev/null
@@ -0,0 +1,75 @@
+/*     $NetBSD: modf.S,v 1.11 2009/12/14 01:07:42 matt Exp $   */
+
+/*-
+ * Copyright (c) 1991, 1993, 1995
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)modf.s 8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: modf.S,v 1.11 2009/12/14 01:07:42 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * double modf(val, iptr)
+ *     double val, *iptr;
+ * returns: xxx and n (in *iptr) where val == n.xxx
+ */
+LEAF(modf)
+       cfc1    t0, $31                 # get the control register
+       li.d    $f2, 4503599627370496e0 # f2 <- 2^52
+
+       or      t1, t0, 0x3             # set rounding mode to round to zero
+       xor     t1, t1, 0x2             #  (i.e., 01)
+       ctc1    t1, $31
+
+       mov.d   $f0, $f12               # f0 <- f12
+       abs.d   $f4, $f12               # f4 <- |f12|
+       c.olt.d $f4, $f2                # f4 ? < f2 
+       bc1f    1f                      # leave f0 alone if Nan, infinity 
+                                       # or >=2^52
+       c.eq.d  $f12,$f4                # was f12 positive ?
+       add.d   $f4,$f2,$f4             # round off to integer
+       bc1f    2f                      # No -> will have to negate result
+       sub.d   $f0,$f4,$f2             # Remove fudge factor
+       j       1f                      # integer fraction got
+2:     
+       sub.d   $f0,$f2,$f4             # Remove fudge factor and negate
+1:     
+       ctc1    t0, $31                 # restore old rounding mode
+       s.d     $f0, 0(a2)              # save the integer part
+       sub.d   $f0, $f12, $f0          # subtract val - integer part
+       j       ra
+END(modf)
diff --git a/lib/nbsd_libc/arch/mips/gen/nanf.c b/lib/nbsd_libc/arch/mips/gen/nanf.c
new file mode 100644 (file)
index 0000000..6fbda28
--- /dev/null
@@ -0,0 +1,19 @@
+/*     $NetBSD: nanf.c,v 1.4 2009/02/22 01:34:02 martin Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nanf.c,v 1.4 2009/02/22 01:34:02 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+/* bytes for quiet NaN (IEEE single precision) */
+const union __float_u __nanf =
+#if BYTE_ORDER == BIG_ENDIAN
+               { { 0x7f, 0xa0,    0,    0 } };
+#else
+               { {    0,    0, 0xa0, 0x7f } };
+#endif
+
+__warn_references(__nanf, "warning: <math.h> defines NAN incorrectly for your compiler.")
diff --git a/lib/nbsd_libc/arch/mips/gen/resumecontext.c b/lib/nbsd_libc/arch/mips/gen/resumecontext.c
new file mode 100644 (file)
index 0000000..08362ec
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:56 martin Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:56 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "extern.h"
+
+void
+_resumecontext()
+{
+       ucontext_t uct;
+
+       (void)getcontext(&uct);
+       if (uct.uc_link == NULL) 
+               exit(0);
+       (void)setcontext(uct.uc_link);
+       _exit(-1);
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/mips/gen/setjmp.S b/lib/nbsd_libc/arch/mips/gen/setjmp.S
new file mode 100644 (file)
index 0000000..c75325b
--- /dev/null
@@ -0,0 +1,148 @@
+/*     $NetBSD: setjmp.S,v 1.19 2010/09/03 17:22:51 matt Exp $ */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <sys/syscall.h>
+#include <mips/asm.h>
+
+#include "assym.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)setjmp.s       8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: setjmp.S,v 1.19 2010/09/03 17:22:51 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and a struct sigcontext, see <signal.h>
+ */
+
+#define SETJMP_FRAME_SIZE      (CALLFRAME_SIZ + STACK_T_SIZE)
+
+NON_LEAF(__setjmp14, SETJMP_FRAME_SIZE, ra)
+       .mask   0x80010000, (CALLFRAME_RA - CALLFRAME_SIZ)
+       SETUP_GP
+       PTR_SUBU        sp, sp, SETJMP_FRAME_SIZE       # allocate stack frame
+       SAVE_GP(CALLFRAME_GP)
+       SETUP_GP64(CALLFRAME_GP, __setjmp14)
+
+       REG_S           ra, CALLFRAME_RA(sp)            # save RA
+       REG_S           s0, CALLFRAME_S0(sp)            # save S0
+       move            s0, a0                          # save sigcontext
+
+       /* Get the signal mask. */
+       PTR_ADDU        a2, a0, _OFFSETOF_SC_MASK       # &sc.sc_mask
+       move            a1, zero
+       jal             _C_LABEL(__sigprocmask14)       # get current signal mask
+
+       /* Get the signal stack. */
+       move            a0, zero
+       PTR_ADDU        a1, sp, CALLFRAME_SIZ           # pointer to stack_t
+       jal             _C_LABEL(__sigaltstack14)
+
+       move            a0, s0                          # restore jmpbuf
+       INT_L           v1, CALLFRAME_SIZ+_OFFSETOF_STACK_T_FLAGS(sp)
+                                                       # get old ss_onstack
+       and             v1, v1, SS_ONSTACK              # extract onstack flag
+       INT_S           v1, _OFFSETOF_SC_ONSTACK(a0)    # save it in sc_onstack
+
+       REG_L           s0, CALLFRAME_S0(sp)            # restore S0
+       REG_L           ra, CALLFRAME_RA(sp)            # restore RA
+       blt             v0, zero, botch         # check for sigaltstack() error
+       nop
+       /*
+        * We know we won't need this routine's GP anymore.
+        */
+       RESTORE_GP64
+       PTR_ADDU        sp, sp, SETJMP_FRAME_SIZE       # pop stack frame
+
+
+       REG_PROLOGUE
+       REG_S   ra, _OFFSETOF_SC_PC(a0)         # sc_pc = return address
+       REG_LI  v0, 0xACEDBADE                  # sigcontext magic number
+       REG_S   v0, _OFFSETOF_SC_REGS(a0)       #   saved in sc_regs[0]
+       REG_S   s0, _OFFSETOF_SC_REGS_S0(a0)
+       REG_S   s1, _OFFSETOF_SC_REGS_S1(a0)
+       REG_S   s2, _OFFSETOF_SC_REGS_S2(a0)
+       REG_S   s3, _OFFSETOF_SC_REGS_S3(a0)
+       REG_S   s4, _OFFSETOF_SC_REGS_S4(a0)
+       REG_S   s5, _OFFSETOF_SC_REGS_S5(a0)
+       REG_S   s6, _OFFSETOF_SC_REGS_S6(a0)
+       REG_S   s7, _OFFSETOF_SC_REGS_S7(a0)
+       REG_S   gp, _OFFSETOF_SC_REGS_GP(a0)
+       REG_S   sp, _OFFSETOF_SC_REGS_SP(a0)
+       REG_S   s8, _OFFSETOF_SC_REGS_S8(a0)
+#ifdef SOFTFLOAT_FOR_GCC
+       INT_S   zero, _OFFSETOF_SC_FPUSED(a0)   # sc_fpused = 0
+#else
+       li      v0, 1                           # be nice if we could tell
+       INT_S   v0, _OFFSETOF_SC_FPUSED(a0)     # sc_fpused = 1
+       cfc1    v0, $31
+       INT_S   v0, _OFFSETOF_SC_FPREGS_FCSR(a0)
+#if defined(__mips_o32) || defined(__mips_o64) || defined(__mips_n32)
+       FP_S    $f20, _OFFSETOF_SC_FPREGS_F20(a0)
+       FP_S    $f22, _OFFSETOF_SC_FPREGS_F22(a0)
+#endif
+#if defined(__mips_o32) || defined(__mips_o64)
+       FP_S    $f21, _OFFSETOF_SC_FPREGS_F21(a0)
+       FP_S    $f23, _OFFSETOF_SC_FPREGS_F23(a0)
+#endif
+#if defined(__mips_n32) || defined(__mips_n64)
+       FP_S    $f24, _OFFSETOF_SC_FPREGS_F24(a0)
+       FP_S    $f26, _OFFSETOF_SC_FPREGS_F26(a0)
+       FP_S    $f28, _OFFSETOF_SC_FPREGS_F28(a0)
+       FP_S    $f30, _OFFSETOF_SC_FPREGS_F30(a0)
+#endif
+#if defined(__mips_n64)
+       FP_S    $f25, _OFFSETOF_SC_FPREGS_F25(a0)
+       FP_S    $f27, _OFFSETOF_SC_FPREGS_F27(a0)
+       FP_S    $f29, _OFFSETOF_SC_FPREGS_F29(a0)
+       FP_S    $f31, _OFFSETOF_SC_FPREGS_F31(a0)
+#endif
+#endif /* SOFTFLOAT_FOR_GCC */
+       REG_EPILOGUE
+       move    v0, zero
+       j       ra
+
+botch:
+       jal     _C_LABEL(abort)
+END(__setjmp14)
diff --git a/lib/nbsd_libc/arch/mips/gen/sigsetjmp.S b/lib/nbsd_libc/arch/mips/gen/sigsetjmp.S
new file mode 100644 (file)
index 0000000..5cbe82d
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: sigsetjmp.S,v 1.9 2009/12/14 01:07:42 matt Exp $       */
+
+/*-
+ * Copyright (c) 1991, 1993, 1995,
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Havard Eidnes.
+ *
+ * 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. 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.
+ */
+
+#include <sys/syscall.h>
+#include <mips/regnum.h>
+#include <mips/asm.h>
+#include <machine/setjmp.h>
+
+#include "assym.h"
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)setjmp.s       8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: sigsetjmp.S,v 1.9 2009/12/14 01:07:42 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- sigsetjmp, siglongjmp
+ *
+ *     siglongjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     sigsetjmp(a, savemask)
+ * by restoring registers from the stack,
+ * and dependent on savemask restores the
+ * signal mask.
+ */
+
+LEAF(__sigsetjmp14)
+       PIC_PROLOGUE(__sigsetjmp14)
+       REG_S   a1, _JBLEN*SZREG(a0)            # save "savemask"
+       bne     a1, 0x0, 1f                     # do saving of signal mask?
+       PIC_TAILCALL(_setjmp)
+
+1:     PIC_TAILCALL(__setjmp14)
+END(__sigsetjmp14)
+
+LEAF(__siglongjmp14)
+       PIC_PROLOGUE(__siglongjmp14)
+       REG_L   t0, _JBLEN*SZREG(a0)            # get "savemask"
+       bne     t0, 0x0, 1f                     # restore signal mask?
+       PIC_TAILCALL(_longjmp)
+
+1:     PIC_TAILCALL(__longjmp14)
+END(__siglongjmp14)
diff --git a/lib/nbsd_libc/arch/mips/gen/swapcontext.S b/lib/nbsd_libc/arch/mips/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..9f19534
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: swapcontext.S,v 1.4 2009/12/14 01:07:42 matt Exp $     */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+#include "assym.h"
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: swapcontext.S,v 1.4 2009/12/14 01:07:42 matt Exp $")
+#endif /* SYSLIBC_SCCS && !lint */
+
+       .set    reorder
+       
+NESTED(swapcontext, CALLFRAME_SIZ, ra)
+       .mask   0x80000030, (CALLFRAME_RA - CALLFRAME_SIZ)
+       PTR_SUBU        sp, sp, CALLFRAME_SIZ
+       PTR_S           ra, CALLFRAME_RA(sp)    # save ra
+       PTR_S           a0, 0(sp)               # stash away oucp
+       PTR_S           a1, SZREG(sp)           # stash away ucp
+       SYSTRAP(getcontext)
+       PTR_L           ra, CALLFRAME_RA(sp)
+       bne             a3, zero, 1f
+
+       PTR_L           v1, 0(sp)               # load oucp again for adjustment
+       PTR_L           a0, SZREG(sp)           # load ucp
+       PTR_ADDIU       v0, sp, CALLFRAME_SIZ
+       REG_PROLOGUE
+       REG_S           zero, _OFFSETOF_UC_GREGS_V0(v1)
+       REG_S           ra, _OFFSETOF_UC_GREGS_EPC(v1)
+       REG_S           v0, _OFFSETOF_UC_GREGS_SP(v1)
+       REG_EPILOGUE
+
+       SYSTRAP(setcontext)
+       /* NOTREACHED */
+1:
+       PTR_ADDU        sp, sp, CALLFRAME_SIZ
+       SETUP_GPX(t0);
+       SETUP_GP64(t3,swapcontext);
+       PIC_TAILCALL(__cerror)
+END(swapcontext)
diff --git a/lib/nbsd_libc/arch/mips/genassym.cf b/lib/nbsd_libc/arch/mips/genassym.cf
new file mode 100644 (file)
index 0000000..512d3f9
--- /dev/null
@@ -0,0 +1,86 @@
+#      $NetBSD: genassym.cf,v 1.2 2009/12/14 01:07:41 matt Exp $
+
+#
+# Copyright (c) 2001 The NetBSD Foundation, Inc.
+# All rights reserved.
+#
+# This code is derived from software contributed to The NetBSD Foundation
+# by Matt Thomas <matt@3am-sfotware.com>.
+#
+# 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/types.h>
+include <machine/reg.h>
+include <machine/regnum.h>
+include <ucontext.h>
+include <signal.h>
+include <sys/siginfo.h>
+
+define _OFFSETOF_UC_GREGS      offsetof(ucontext_t, uc_mcontext.__gregs[0])
+define _OFFSETOF_UC_GREGS_V0   offsetof(ucontext_t, uc_mcontext.__gregs[_REG_V0])
+define _OFFSETOF_UC_GREGS_SP   offsetof(ucontext_t, uc_mcontext.__gregs[_REG_SP])
+define _OFFSETOF_UC_GREGS_EPC  offsetof(ucontext_t, uc_mcontext.__gregs[_REG_EPC])
+define _OFFSETOF_UC_LINK       offsetof(ucontext_t, uc_link)
+define UCONTEXT_SIZE           sizeof(ucontext_t)
+
+define _OFFSETOF_SC_REGS       offsetof(struct sigcontext, sc_regs[0])
+define _OFFSETOF_SC_REGS_V0    offsetof(struct sigcontext, sc_regs[_R_V0])
+define _OFFSETOF_SC_REGS_S0    offsetof(struct sigcontext, sc_regs[_R_S0])
+define _OFFSETOF_SC_REGS_S1    offsetof(struct sigcontext, sc_regs[_R_S1])
+define _OFFSETOF_SC_REGS_S2    offsetof(struct sigcontext, sc_regs[_R_S2])
+define _OFFSETOF_SC_REGS_S3    offsetof(struct sigcontext, sc_regs[_R_S3])
+define _OFFSETOF_SC_REGS_S4    offsetof(struct sigcontext, sc_regs[_R_S4])
+define _OFFSETOF_SC_REGS_S5    offsetof(struct sigcontext, sc_regs[_R_S5])
+define _OFFSETOF_SC_REGS_S6    offsetof(struct sigcontext, sc_regs[_R_S6])
+define _OFFSETOF_SC_REGS_S7    offsetof(struct sigcontext, sc_regs[_R_S7])
+define _OFFSETOF_SC_REGS_S8    offsetof(struct sigcontext, sc_regs[_R_S8])
+define _OFFSETOF_SC_REGS_SP    offsetof(struct sigcontext, sc_regs[_R_SP])
+define _OFFSETOF_SC_REGS_GP    offsetof(struct sigcontext, sc_regs[_R_GP])
+define _OFFSETOF_SC_FPREGS     offsetof(struct sigcontext, sc_fpregs[0])
+define _OFFSETOF_SC_FPREGS_F20 offsetof(struct sigcontext, sc_fpregs[20])
+define _OFFSETOF_SC_FPREGS_F21 offsetof(struct sigcontext, sc_fpregs[21])
+define _OFFSETOF_SC_FPREGS_F22 offsetof(struct sigcontext, sc_fpregs[22])
+define _OFFSETOF_SC_FPREGS_F23 offsetof(struct sigcontext, sc_fpregs[23])
+define _OFFSETOF_SC_FPREGS_F24 offsetof(struct sigcontext, sc_fpregs[24])
+define _OFFSETOF_SC_FPREGS_F25 offsetof(struct sigcontext, sc_fpregs[25])
+define _OFFSETOF_SC_FPREGS_F26 offsetof(struct sigcontext, sc_fpregs[26])
+define _OFFSETOF_SC_FPREGS_F27 offsetof(struct sigcontext, sc_fpregs[27])
+define _OFFSETOF_SC_FPREGS_F28 offsetof(struct sigcontext, sc_fpregs[28])
+define _OFFSETOF_SC_FPREGS_F29 offsetof(struct sigcontext, sc_fpregs[29])
+define _OFFSETOF_SC_FPREGS_F30 offsetof(struct sigcontext, sc_fpregs[30])
+define _OFFSETOF_SC_FPREGS_F31 offsetof(struct sigcontext, sc_fpregs[31])
+define _OFFSETOF_SC_FPREGS_FCSR        offsetof(struct sigcontext, sc_fpregs[32])
+define _OFFSETOF_SC_PC         offsetof(struct sigcontext, sc_pc)
+define _OFFSETOF_SC_MASK       offsetof(struct sigcontext, sc_mask)
+define _OFFSETOF_SC_MASK13     offsetof(struct sigcontext, __sc_mask13)
+define _OFFSETOF_SC_ONSTACK    offsetof(struct sigcontext, sc_onstack)
+define _OFFSETOF_SC_FPUSED     offsetof(struct sigcontext, sc_fpused)
+
+define SIGINFO_SIZE            sizeof(siginfo_t)
+
+define STACK_T_SIZE            ((sizeof(stack_t) + 2 * sizeof(register_t) - 1) & -(2 * sizeof(register_t)))
+define _OFFSETOF_STACK_T_SP    offsetof(stack_t, ss_sp)
+define _OFFSETOF_STACK_T_SIZE  offsetof(stack_t, ss_size)
+define _OFFSETOF_STACK_T_FLAGS offsetof(stack_t, ss_flags)
+
+define SS_ONSTACK              SS_ONSTACK
diff --git a/lib/nbsd_libc/arch/mips/net/Makefile.inc b/lib/nbsd_libc/arch/mips/net/Makefile.inc
new file mode 100644 (file)
index 0000000..a760829
--- /dev/null
@@ -0,0 +1,10 @@
+#      $NetBSD: Makefile.inc,v 1.4 2009/12/06 07:12:17 uebayasi Exp $
+
+# objects built from assembler sources (need lint stubs)
+# hton* and nto* functions provided by ../gen/byte_swap_*.S
+SRCS+=  
+
+LSRCS.mips.net=        Lint_htonl.c Lint_htons.c Lint_ntohl.c Lint_ntohs.c
+LSRCS+=                ${LSRCS.mips.net}
+DPSRCS+=       ${LSRCS.mips.net}
+CLEANFILES+=   ${LSRCS.mips.net}
diff --git a/lib/nbsd_libc/arch/mips/softfloat/milieu.h b/lib/nbsd_libc/arch/mips/softfloat/milieu.h
new file mode 100644 (file)
index 0000000..e66eb2e
--- /dev/null
@@ -0,0 +1,48 @@
+/* $NetBSD: milieu.h,v 1.2 2009/12/14 01:07:42 matt Exp $ */
+
+/*
+===============================================================================
+
+This C header file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+Include common integer types and flags.
+-------------------------------------------------------------------------------
+*/
+#include "mips-gcc.h"
+
+/*
+-------------------------------------------------------------------------------
+Symbolic Boolean literals.
+-------------------------------------------------------------------------------
+*/
+enum {
+    FALSE = 0,
+    TRUE  = 1
+};
diff --git a/lib/nbsd_libc/arch/mips/softfloat/mips-gcc.h b/lib/nbsd_libc/arch/mips/softfloat/mips-gcc.h
new file mode 100644 (file)
index 0000000..6ed3c22
--- /dev/null
@@ -0,0 +1,95 @@
+/* $NetBSD: mips-gcc.h,v 1.2 2009/12/14 01:07:42 matt Exp $ */
+
+/*
+-------------------------------------------------------------------------------
+One of the macros `BIGENDIAN' or `LITTLEENDIAN' must be defined.
+-------------------------------------------------------------------------------
+*/
+#ifdef __MIPSEB__
+#define BIGENDIAN
+#else
+#define LITTLEENDIAN
+#endif
+
+/*
+-------------------------------------------------------------------------------
+The macro `BITS64' can be defined to indicate that 64-bit integer types are
+supported by the compiler.
+-------------------------------------------------------------------------------
+*/
+#define BITS64
+
+/*
+-------------------------------------------------------------------------------
+Each of the following `typedef's defines the most convenient type that holds
+integers of at least as many bits as specified.  For example, `uint8' should
+be the most convenient type that can hold unsigned integers of as many as
+8 bits.  The `flag' type must be able to hold either a 0 or 1.  For most
+implementations of C, `flag', `uint8', and `int8' should all be `typedef'ed
+to the same as `int'.
+-------------------------------------------------------------------------------
+*/
+typedef int flag;
+typedef int uint8;
+typedef int int8;
+typedef int uint16;
+typedef int int16;
+typedef unsigned int uint32;
+typedef signed int int32;
+#ifdef BITS64
+typedef unsigned long long int uint64;
+typedef signed long long int int64;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Each of the following `typedef's defines a type that holds integers
+of _exactly_ the number of bits specified.  For instance, for most
+implementation of C, `bits16' and `sbits16' should be `typedef'ed to
+`unsigned short int' and `signed short int' (or `short int'), respectively.
+-------------------------------------------------------------------------------
+*/
+typedef unsigned char bits8;
+typedef signed char sbits8;
+typedef unsigned short int bits16;
+typedef signed short int sbits16;
+typedef unsigned int bits32;
+typedef signed int sbits32;
+#ifdef BITS64
+typedef unsigned long long int bits64;
+typedef signed long long int sbits64;
+#endif
+
+#ifdef BITS64
+/*
+-------------------------------------------------------------------------------
+The `LIT64' macro takes as its argument a textual integer literal and
+if necessary ``marks'' the literal as having a 64-bit integer type.
+For example, the GNU C Compiler (`gcc') requires that 64-bit literals be
+appended with the letters `LL' standing for `long long', which is `gcc's
+name for the 64-bit integer type.  Some compilers may allow `LIT64' to be
+defined as the identity macro:  `#define LIT64( a ) a'.
+-------------------------------------------------------------------------------
+*/
+#define LIT64( a ) a##LL
+#endif
+
+/*
+-------------------------------------------------------------------------------
+The macro `INLINE' can be used before functions that should be inlined.  If
+a compiler does not support explicit inlining, this macro should be defined
+to be `static'.
+-------------------------------------------------------------------------------
+*/
+#define INLINE static inline
+
+/*
+-------------------------------------------------------------------------------
+The ARM FPA is odd in that it stores doubles high-order word first, no matter
+what the endianness of the CPU.  VFP is sane.
+-------------------------------------------------------------------------------
+*/
+#if defined(SOFTFLOAT_FOR_GCC)
+#define FLOAT64_DEMANGLE(a)    (a)
+#define FLOAT64_MANGLE(a)      (a)
+#endif
diff --git a/lib/nbsd_libc/arch/mips/softfloat/softfloat.h b/lib/nbsd_libc/arch/mips/softfloat/softfloat.h
new file mode 100644 (file)
index 0000000..ab2ae05
--- /dev/null
@@ -0,0 +1,323 @@
+/*     $NetBSD: softfloat.h,v 1.3 2011/01/17 23:53:04 matt Exp $       */
+
+/* This is a derivative work. */
+
+/*
+===============================================================================
+
+This C header file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+The macro `FLOATX80' must be defined to enable the extended double-precision
+floating-point format `floatx80'.  If this macro is not defined, the
+`floatx80' type will not be defined, and none of the functions that either
+input or output the `floatx80' type will be defined.  The same applies to
+the `FLOAT128' macro and the quadruple-precision format `float128'.
+-------------------------------------------------------------------------------
+*/
+/* #define FLOATX80 */
+#if defined(__mips_n32) || defined(__mips_n64)
+#define FLOAT128
+#endif
+
+#include <machine/ieeefp.h>
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point types.
+-------------------------------------------------------------------------------
+*/
+typedef unsigned int float32;
+typedef unsigned long long float64;
+#ifdef FLOATX80
+typedef struct {
+    unsigned short high;
+    unsigned long long low;
+} floatx80;
+#endif
+#ifdef FLOAT128
+typedef struct {
+    unsigned long long high, low;
+} float128;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point underflow tininess-detection mode.
+-------------------------------------------------------------------------------
+*/
+#ifndef SOFTFLOAT_FOR_GCC
+extern int float_detect_tininess;
+#endif
+enum {
+    float_tininess_after_rounding  = 0,
+    float_tininess_before_rounding = 1
+};
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point rounding mode.
+-------------------------------------------------------------------------------
+*/
+extern fp_rnd float_rounding_mode;
+enum {
+    float_round_nearest_even = FP_RN,
+    float_round_to_zero      = FP_RZ,
+    float_round_down         = FP_RM,
+    float_round_up           = FP_RP
+};
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point exception flags.
+-------------------------------------------------------------------------------
+*/
+extern fp_except float_exception_flags;
+extern fp_except float_exception_mask;
+enum {
+    float_flag_inexact   = FP_X_IMP,
+    float_flag_underflow = FP_X_UFL,
+    float_flag_overflow  = FP_X_OFL,
+    float_flag_divbyzero = FP_X_DZ,
+    float_flag_invalid   = FP_X_INV
+};
+
+/*
+-------------------------------------------------------------------------------
+Routine to raise any or all of the software IEC/IEEE floating-point
+exception flags.
+-------------------------------------------------------------------------------
+*/
+void float_raise( fp_except );
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE integer-to-floating-point conversion routines.
+-------------------------------------------------------------------------------
+*/
+float32 int32_to_float32( int );
+float64 int32_to_float64( int );
+#ifdef FLOATX80
+floatx80 int32_to_floatx80( int );
+#endif
+#ifdef FLOAT128
+float128 int32_to_float128( int );
+#endif
+#ifndef SOFTFLOAT_FOR_GCC /* __floatdi?f is in libgcc2.c */
+float32 int64_to_float32( long long );
+float64 int64_to_float64( long long );
+#ifdef FLOATX80
+floatx80 int64_to_floatx80( long long );
+#endif
+#endif
+#ifdef FLOAT128
+float128 int64_to_float128( long long );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE single-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float32_to_int32( float32 );
+int float32_to_int32_round_to_zero( float32 );
+#if defined(SOFTFLOAT_FOR_GCC) && defined(SOFTFLOAT_NEED_FIXUNS)
+unsigned int float32_to_uint32_round_to_zero( float32 );
+#endif
+#ifndef SOFTFLOAT_FOR_GCC /* __fix?fdi provided by libgcc2.c */
+long long float32_to_int64( float32 );
+long long float32_to_int64_round_to_zero( float32 );
+#endif
+float64 float32_to_float64( float32 );
+#ifdef FLOATX80
+floatx80 float32_to_floatx80( float32 );
+#endif
+#ifdef FLOAT128
+float128 float32_to_float128( float32 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE single-precision operations.
+-------------------------------------------------------------------------------
+*/
+float32 float32_round_to_int( float32 );
+float32 float32_add( float32, float32 );
+float32 float32_sub( float32, float32 );
+float32 float32_mul( float32, float32 );
+float32 float32_div( float32, float32 );
+float32 float32_rem( float32, float32 );
+float32 float32_sqrt( float32 );
+int float32_eq( float32, float32 );
+int float32_le( float32, float32 );
+int float32_lt( float32, float32 );
+int float32_eq_signaling( float32, float32 );
+int float32_le_quiet( float32, float32 );
+int float32_lt_quiet( float32, float32 );
+#ifndef SOFTFLOAT_FOR_GCC
+int float32_is_signaling_nan( float32 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE double-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float64_to_int32( float64 );
+int float64_to_int32_round_to_zero( float64 );
+#if defined(SOFTFLOAT_FOR_GCC) && defined(SOFTFLOAT_NEED_FIXUNS)
+unsigned int float64_to_uint32_round_to_zero( float64 );
+#endif
+#ifndef SOFTFLOAT_FOR_GCC /* __fix?fdi provided by libgcc2.c */
+long long float64_to_int64( float64 );
+long long float64_to_int64_round_to_zero( float64 );
+#endif
+float32 float64_to_float32( float64 );
+#ifdef FLOATX80
+floatx80 float64_to_floatx80( float64 );
+#endif
+#ifdef FLOAT128
+float128 float64_to_float128( float64 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE double-precision operations.
+-------------------------------------------------------------------------------
+*/
+float64 float64_round_to_int( float64 );
+float64 float64_add( float64, float64 );
+float64 float64_sub( float64, float64 );
+float64 float64_mul( float64, float64 );
+float64 float64_div( float64, float64 );
+float64 float64_rem( float64, float64 );
+float64 float64_sqrt( float64 );
+int float64_eq( float64, float64 );
+int float64_le( float64, float64 );
+int float64_lt( float64, float64 );
+int float64_eq_signaling( float64, float64 );
+int float64_le_quiet( float64, float64 );
+int float64_lt_quiet( float64, float64 );
+#ifndef SOFTFLOAT_FOR_GCC
+int float64_is_signaling_nan( float64 );
+#endif
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int floatx80_to_int32( floatx80 );
+int floatx80_to_int32_round_to_zero( floatx80 );
+long long floatx80_to_int64( floatx80 );
+long long floatx80_to_int64_round_to_zero( floatx80 );
+float32 floatx80_to_float32( floatx80 );
+float64 floatx80_to_float64( floatx80 );
+#ifdef FLOAT128
+float128 floatx80_to_float128( floatx80 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision rounding precision.  Valid
+values are 32, 64, and 80.
+-------------------------------------------------------------------------------
+*/
+extern int floatx80_rounding_precision;
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision operations.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_round_to_int( floatx80 );
+floatx80 floatx80_add( floatx80, floatx80 );
+floatx80 floatx80_sub( floatx80, floatx80 );
+floatx80 floatx80_mul( floatx80, floatx80 );
+floatx80 floatx80_div( floatx80, floatx80 );
+floatx80 floatx80_rem( floatx80, floatx80 );
+floatx80 floatx80_sqrt( floatx80 );
+int floatx80_eq( floatx80, floatx80 );
+int floatx80_le( floatx80, floatx80 );
+int floatx80_lt( floatx80, floatx80 );
+int floatx80_eq_signaling( floatx80, floatx80 );
+int floatx80_le_quiet( floatx80, floatx80 );
+int floatx80_lt_quiet( floatx80, floatx80 );
+int floatx80_is_signaling_nan( floatx80 );
+
+#endif
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE quadruple-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float128_to_int32( float128 );
+int float128_to_int32_round_to_zero( float128 );
+#if defined(SOFTFLOAT_FOR_GCC) && defined(SOFTFLOAT_NEED_FIXUNS)
+unsigned int float128_to_uint32_round_to_zero( float64 );
+#endif
+long long float128_to_int64( float128 );
+long long float128_to_int64_round_to_zero( float128 );
+#if defined(SOFTFLOAT_FOR_GCC) && defined(SOFTFLOAT_NEED_FIXUNS)
+unsigned long long float128_to_uint64_round_to_zero( float128 );
+#endif
+float32 float128_to_float32( float128 );
+float64 float128_to_float64( float128 );
+#ifdef FLOATX80
+floatx80 float128_to_floatx80( float128 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE quadruple-precision operations.
+-------------------------------------------------------------------------------
+*/
+float128 float128_round_to_int( float128 );
+float128 float128_add( float128, float128 );
+float128 float128_sub( float128, float128 );
+float128 float128_mul( float128, float128 );
+float128 float128_div( float128, float128 );
+float128 float128_rem( float128, float128 );
+float128 float128_sqrt( float128 );
+int float128_eq( float128, float128 );
+int float128_le( float128, float128 );
+int float128_lt( float128, float128 );
+int float128_eq_signaling( float128, float128 );
+int float128_le_quiet( float128, float128 );
+int float128_lt_quiet( float128, float128 );
+int float128_is_signaling_nan( float128 );
+flag float128_is_nan( float128 );
+
+#endif
+
diff --git a/lib/nbsd_libc/arch/mips/stdlib/Makefile.inc b/lib/nbsd_libc/arch/mips/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..2f91b99
--- /dev/null
@@ -0,0 +1 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/07/31 20:40:00 dsl Exp $
diff --git a/lib/nbsd_libc/arch/mips/string/Makefile.inc b/lib/nbsd_libc/arch/mips/string/Makefile.inc
new file mode 100644 (file)
index 0000000..0213864
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/12/14 01:07:42 matt Exp $
+
+SRCS+= bcmp.S bcopy.S bzero.S \
+       ffs.S \
+       memcpy.S memmove.S \
+       strchr.S strrchr.S \
+       strcmp.S strlen.S
diff --git a/lib/nbsd_libc/arch/mips/string/bcmp.S b/lib/nbsd_libc/arch/mips/string/bcmp.S
new file mode 100644 (file)
index 0000000..c90fa2c
--- /dev/null
@@ -0,0 +1,124 @@
+/*     $NetBSD: bcmp.S,v 1.9 2009/12/14 01:07:42 matt Exp $    */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+#define _LOCORE                /* XXX not really, just assembly-code source */
+#include <machine/endian.h>    /* LWLO/LWHI, SWLO/SWHI */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)bcmp.s 8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: bcmp.S,v 1.9 2009/12/14 01:07:42 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* bcmp(s1, s2, n) */
+
+
+LEAF(bcmp)
+       .set    noreorder
+       blt             a2, 16, small   # is it worth any trouble?
+       xor             v0, a0, a1      # compare low two bits of addresses
+       and             v0, v0, 3
+       PTR_SUBU        a3, zero, a1    # compute # bytes to word align address
+       bne             v0, zero, unaligned # not possible to align addresses
+       and             a3, a3, 3
+
+       beq             a3, zero, 1f
+       PTR_SUBU        a2, a2, a3      # subtract from remaining count
+       move            v0, v1          # init v0,v1 so unmodified bytes match
+       LWHI            v0, 0(a0)       # read 1, 2, or 3 bytes
+       LWHI            v1, 0(a1)
+       PTR_ADDU        a1, a1, a3
+       bne             v0, v1, nomatch
+       PTR_ADDU        a0, a0, a3
+1:
+       and             a3, a2, ~3      # compute number of whole words left
+       PTR_SUBU        a2, a2, a3      #   which has to be >= (16-3) & ~3
+       PTR_ADDU        a3, a3, a0      # compute ending address
+2:
+       lw              v0, 0(a0)       # compare words
+       lw              v1, 0(a1)
+       PTR_ADDU        a0, a0, 4
+       bne             v0, v1, nomatch
+       PTR_ADDU        a1, a1, 4
+       bne             a0, a3, 2b
+       nop
+       b               small           # finish remainder
+       nop
+unaligned:
+       beq             a3, zero, 2f
+       PTR_SUBU        a2, a2, a3      # subtract from remaining count
+       PTR_ADDU        a3, a3, a0      # compute ending address
+1:
+       lbu             v0, 0(a0)       # compare bytes until a1 word aligned
+       lbu             v1, 0(a1)
+       PTR_ADDU        a0, a0, 1
+       bne             v0, v1, nomatch
+       PTR_ADDU        a1, a1, 1
+       bne             a0, a3, 1b
+       nop
+2:
+       and             a3, a2, ~3      # compute number of whole words left
+       PTR_SUBU        a2, a2, a3      #   which has to be >= (16-3) & ~3
+       PTR_ADDU        a3, a3, a0      # compute ending address
+3:
+       LWHI            v0, 0(a0)       # compare words a0 unaligned, a1 aligned
+       LWLO            v0, 3(a0)
+       lw              v1, 0(a1)
+       PTR_ADDU        a0, a0, 4
+       bne             v0, v1, nomatch
+       PTR_ADDU        a1, a1, 4
+       bne             a0, a3, 3b
+       nop
+small:
+       ble             a2, zero, match
+       PTR_ADDU        a3, a2, a0              # compute ending address
+1:
+       lbu             v0, 0(a0)
+       lbu             v1, 0(a1)
+       PTR_ADDU        a0, a0, 1
+       bne             v0, v1, nomatch
+       PTR_ADDU        a1, a1, 1
+       bne             a0, a3, 1b
+       nop
+match:
+       j               ra
+       move            v0, zero
+nomatch:
+       j               ra
+       li              v0, 1
+       .set    reorder
+END(bcmp)
diff --git a/lib/nbsd_libc/arch/mips/string/bzero.S b/lib/nbsd_libc/arch/mips/string/bzero.S
new file mode 100644 (file)
index 0000000..f25c020
--- /dev/null
@@ -0,0 +1,97 @@
+/*     $NetBSD: bzero.S,v 1.10 2009/12/14 02:53:52 matt Exp $  */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <mips/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)bzero.s        8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: bzero.S,v 1.10 2009/12/14 02:53:52 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+
+#define _LOCORE                /* XXX not really, just assembly-code source */
+#include <machine/endian.h>
+
+/* bzero(s1, n) */
+
+LEAF(bzero)
+       .set    noreorder
+       blt             a1, 3*SZREG, smallclr # small amount to clear?
+       PTR_SUBU        a3, zero, a0    # compute # bytes to word align address
+       and             a3, a3, SZREG-1
+       beq             a3, zero, 1f    # skip if word aligned
+#if SZREG == 4
+       PTR_SUBU        a1, a1, a3      # subtract from remaining count
+       SWHI            zero, 0(a0)     # clear 1, 2, or 3 bytes to align
+       PTR_ADDU        a0, a0, a3
+#endif
+#if SZREG == 8
+       PTR_SUBU        a1, a1, a3      # subtract from remaining count
+       PTR_ADDU        a0, a0, a3      # align dst to next word
+       sll             a3, a3, 3       # bits to bytes
+       li              a2, -1          # make a mask
+#if _BYTE_ORDER == _BIG_ENDIAN
+       REG_SRLV        a2, a2, a3      # we want to keep the MSB bytes
+#endif
+#if _BYTE_ORDER == _LITTLE_ENDIAN
+       REG_SLLV        a2, a2, a3      # we want to keep the LSB bytes
+#endif
+       nor             a2, zero, a2    # complement the mask
+       REG_L           v0, -SZREG(a0)  # load the word to partially clear
+       and             v0, v0, a2      # clear the bytes
+       REG_S           v0, -SZREG(a0)  # store it back
+#endif
+1:
+       and             v0, a1, SZREG-1 # compute number of words left
+       PTR_SUBU        a3, a1, v0
+       move            a1, v0
+       PTR_ADDU        a3, a3, a0      # compute ending address
+2:
+       PTR_ADDU        a0, a0, SZREG   # clear words
+       bne             a0, a3, 2b      #  unrolling loop doesnt help
+       REG_S           zero, -SZREG(a0) # since we are limited by memory speed
+smallclr:
+       ble             a1, zero, 2f
+       PTR_ADDU        a3, a1, a0      # compute ending address
+1:
+       PTR_ADDU        a0, a0, 1       # clear bytes
+       bne             a0, a3, 1b
+       sb              zero, -1(a0)
+2:
+       j               ra
+       nop
+END(bzero)
diff --git a/lib/nbsd_libc/arch/mips/sys/__clone.S b/lib/nbsd_libc/arch/mips/sys/__clone.S
new file mode 100644 (file)
index 0000000..de7ef47
--- /dev/null
@@ -0,0 +1,103 @@
+/*     $NetBSD: __clone.S,v 1.8 2009/12/14 01:07:42 matt Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+
+#include "SYS.h"
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __clone.S,v 1.8 2009/12/14 01:07:42 matt Exp $");
+#endif /* SYSLIBC_SCCS and not lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(clone, __clone)
+#endif
+
+/*
+ * int __clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+LEAF(__clone)
+       PIC_PROLOGUE(__clone)
+
+       /*
+        * Sanity checks: func and stack may not be NULL.
+        */
+       li              v0, EINVAL
+       beq             a0, zero, 8f
+       beq             a1, zero, 8f
+
+       /*
+        * We need to be able to get at the func and arg arguments
+        * in the child.  Luckily, we have a convenient place to
+        * do this: the child's stack.
+        */
+       PTR_SUBU        a1, a1, CALLFRAME_SIZ
+       REG_S           a0, 0(a1)
+       REG_S           a3, SZREG(a1)
+
+       /*
+        * The system call expects (flags, stack).
+        */
+       move            a0, a2
+       SYSTRAP(__clone)
+       bne             a3, zero, 8f
+
+       bne             v1, zero, 9f    # v1 (rv[1]) == 0, parent, child pid in v0
+
+       PIC_RETURN()                    # parent return
+
+8:     PIC_TAILCALL(__cerror)
+       /* NOTREACHED */
+
+9:     /*
+        * Child: Fetch the function and argument from the new stack and create
+        a frame so that the child can be safely called.
+        *
+        * There are already register slots on the stack from above.
+        * They already include the o32 argument save area.  The
+        * highest is unused.  a1 should equal sp now.
+        */
+
+       REG_L           t9, 0(sp)
+       REG_L           a0, SZREG(sp)
+
+       REG_S           zero, CALLFRAME_RA(sp)  /* make sure stack frame ends */
+
+       /* Call the clone's entry point. */
+       SAVE_GP(CALLFRAME_GP)
+       jal             t9
+
+       /* Pass the return value to _exit. */
+       move            a0, v0
+       PIC_TAILCALL(_exit)
+
+       /* NOTREACHED */
+END(__clone)
diff --git a/lib/nbsd_libc/arch/mips/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/mips/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..929edac
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.7 2008/04/28 20:22:56 martin Exp $        */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigaction14_sigtramp.c,v 1.7 2008/04/28 20:22:56 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern const int __sigtramp_siginfo_2[];
+
+       /*
+        * If no sigaction, use the "default" trampoline since it won't
+        * be used.
+        */
+       if (act == NULL)
+               return  __sigaction_sigtramp(sig, act, oact, NULL, 0);
+
+#ifdef __LIBC12_SOURCE__
+       /*
+        * We select the non-SA_SIGINFO trampoline if SA_SIGINFO is not
+        * set in the sigaction.
+        */
+       if ((act->sa_flags & SA_SIGINFO) == 0) {
+               extern const int __sigtramp_sigcontext_1[];
+               int sav = errno;
+               int rv =  __sigaction_sigtramp(sig, act, oact,
+                   __sigtramp_sigcontext_1, 1);
+               if (rv >= 0 || errno != EINVAL)
+                       return rv;
+               errno = sav;
+       }
+#endif
+
+       /*
+        * If SA_SIGINFO was specified or the compatibility trampolines
+        * can't be used, use the siginfo trampoline.
+        */
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_2, 2);
+}
diff --git a/lib/nbsd_libc/arch/mips/sys/__sigtramp2.S b/lib/nbsd_libc/arch/mips/sys/__sigtramp2.S
new file mode 100644 (file)
index 0000000..63b0661
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: __sigtramp2.S,v 1.3 2009/12/14 01:07:42 matt Exp $     */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+#include "assym.h"
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __sigtramp2.S,v 1.3 2009/12/14 01:07:42 matt Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+
+/*
+ * The MIPS signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ *
+ * On entry, stack looks like:
+ *
+ *     sp                      ->      siginfo_t structure
+ *     sp + SIGINFO_SIZE       ->      ucontext_t structure
+ */
+LEAF_NOPROFILE(__sigtramp_siginfo_2)
+       PTR_ADDU        a0, sp, SIGINFO_SIZE    /* address of ucontext */
+       SYSTRAP(setcontext)                     /* and do setcontext */
+       move            a0, v0                  /* exit with errno */
+       SYSTRAP(exit)                           /* if sigreturn fails */
+END(__sigtramp_siginfo_2)
diff --git a/lib/nbsd_libc/arch/mips/sys/__syscall.S b/lib/nbsd_libc/arch/mips/sys/__syscall.S
new file mode 100644 (file)
index 0000000..653a954
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: __syscall.S,v 1.1 2000/12/13 23:18:40 simonb Exp $     */
+
+#include "SYS.h"
+
+RSYSCALL(__syscall)
diff --git a/lib/nbsd_libc/arch/mips/sys/__vfork14.S b/lib/nbsd_libc/arch/mips/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..dcb309f
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: __vfork14.S,v 1.6 2009/12/14 01:07:42 matt Exp $       */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)Ovfork.s       8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: __vfork14.S,v 1.6 2009/12/14 01:07:42 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * pid = vfork();
+ *
+ * v1 == 0 in parent process, v1 == 1 in child process.
+ * v0 == pid of child in parent, v0 == pid of parent in child.
+ */
+
+LEAF(__vfork14)
+       PIC_PROLOGUE(__vfork14)
+       li      v0, SYS___vfork14       # system call number for vfork
+       syscall
+       beq     a3, zero, 1f            # jump if no errors
+       PIC_TAILCALL(__cerror)
+1:
+       beq     v1, zero, 2f            # parent process ?
+       move    v0, zero                # return zero in child
+2:
+       PIC_RETURN()
+END(__vfork14)
diff --git a/lib/nbsd_libc/arch/mips/sys/brk.S b/lib/nbsd_libc/arch/mips/sys/brk.S
new file mode 100644 (file)
index 0000000..f0571d0
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: brk.S,v 1.18 2010/12/12 09:00:37 tsutsui Exp $ */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)brk.s  8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: brk.S,v 1.18 2010/12/12 09:00:37 tsutsui Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+       .globl  _C_LABEL(__minbrk)
+       .globl  _C_LABEL(__curbrk)
+       .globl  _C_LABEL(_end)
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(brk, _brk)
+#endif
+
+       .data
+_C_LABEL(__minbrk):
+       PTR_WORD        _C_LABEL(_end)
+       .text
+
+LEAF(_brk)
+       PIC_PROLOGUE(_brk)
+       PTR_LA          t0, _C_LABEL(__minbrk)
+       PTR_L           v0, 0(t0)
+       bgeu            a0, v0, 1f
+       move            a0, v0          # dont allow break < minbrk
+1:
+       li              v0, SYS_break
+       syscall
+       bne             a3, zero, 2f
+       PTR_LA          t0, _C_LABEL(__curbrk)
+       PTR_S           a0, 0(t0)
+       move            v0, zero
+       PIC_RETURN()
+2:
+       PIC_TAILCALL(__cerror)
+END(_brk)
diff --git a/lib/nbsd_libc/arch/mips/sys/cerror.S b/lib/nbsd_libc/arch/mips/sys/cerror.S
new file mode 100644 (file)
index 0000000..059c3d3
--- /dev/null
@@ -0,0 +1,81 @@
+/*     $NetBSD: cerror.S,v 1.16 2011/01/17 23:34:44 matt Exp $ */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)cerror.s       8.1 (Berkeley) 6/16/93")
+#else
+       RCSID("$NetBSD: cerror.S,v 1.16 2011/01/17 23:34:44 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef PIC
+       .hidden __cerror
+#endif
+
+#ifdef _REENTRANT
+       .globl  _C_LABEL(__errno)
+NESTED_NOPROFILE(__cerror, CALLFRAME_SIZ, ra)
+       .mask   0x80000000, (CALLFRAME_RA - CALLFRAME_SIZ)
+       PIC_PROLOGUE(__cerror)
+       PTR_SUBU        sp, CALLFRAME_SIZ
+       PTR_S           ra, CALLFRAME_RA(sp)
+       INT_S           v0, CALLFRAME_S0(sp)    # save errno value
+
+       SAVE_GP(CALLFRAME_GP)
+
+       PTR_LA          t9, _C_LABEL(__errno)   # locate address of errno
+       RESTORE_GP64                            # restore GP (from t3)
+       jalr            t9                      # __errno()
+
+       INT_L           t0, CALLFRAME_S0(sp)
+       PTR_L           ra, CALLFRAME_RA(sp)
+       INT_S           t0, 0(v0)               # update errno value
+       PTR_ADDU        sp, CALLFRAME_SIZ
+       li              v0, -1
+       li              v1, -1
+       j               ra                      # GP has been restored.
+END(__cerror)
+#else          
+       .globl  _C_LABEL(errno)
+LEAF_NOPROFILE(__cerror)
+       PIC_PROLOGUE(__cerror)
+       INT_S           v0, _C_LABEL(errno)
+       li              v0, -1
+       li              v1, -1
+       PIC_RETURN()
+END(__cerror)
+#endif /* _REENTRANT */
diff --git a/lib/nbsd_libc/arch/mips/sys/exect.S b/lib/nbsd_libc/arch/mips/sys/exect.S
new file mode 100644 (file)
index 0000000..4f69e12
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: exect.S,v 1.10 2009/12/14 01:07:42 matt Exp $  */
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)exect.s        8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: exect.S,v 1.10 2009/12/14 01:07:42 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+LEAF(exect)
+       PIC_PROLOGUE(exect)
+       li      v0, SYS_execve
+       syscall
+       bne     a3, zero, 1f
+       PIC_RETURN()
+1:
+       PIC_TAILCALL(__cerror)
+END(exect)
diff --git a/lib/nbsd_libc/arch/mips/sys/fork.S b/lib/nbsd_libc/arch/mips/sys/fork.S
new file mode 100644 (file)
index 0000000..1a532fc
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: fork.S,v 1.12 2009/12/14 01:07:42 matt Exp $   */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)fork.s 8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: fork.S,v 1.12 2009/12/14 01:07:42 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+LEAF(__fork)
+       PIC_PROLOGUE(__fork)
+
+       SYSTRAP(fork)           # pid = fork()
+       bne     a3, zero, 2f
+       beq     v1, zero, 1f    # v1 == 0 in parent, 1 in child
+       move    v0, zero
+1:
+       PIC_RETURN()
+2:
+       PIC_TAILCALL(__cerror)
+END(__fork)
diff --git a/lib/nbsd_libc/arch/mips/sys/getcontext.S b/lib/nbsd_libc/arch/mips/sys/getcontext.S
new file mode 100644 (file)
index 0000000..34743c6
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: getcontext.S,v 1.4 2009/12/14 01:07:42 matt Exp $      */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+#include "assym.h"
+#include <machine/mcontext.h>
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: getcontext.S,v 1.4 2009/12/14 01:07:42 matt Exp $")
+#endif /* SYSLIBC_SCCS && !lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext, _getcontext)
+#endif
+       .set reorder
+
+LEAF(_getcontext)
+       PIC_PROLOGUE(_getcontext)
+       SYSTRAP(getcontext)
+       bne             a3, zero, 1f
+       REG_PROLOGUE
+       REG_S           zero, (_OFFSETOF_UC_GREGS + _REG_V0 * SZREG)(a0)
+       REG_S           ra, (_OFFSETOF_UC_GREGS + _REG_EPC * SZREG)(a0)
+       REG_EPILOGUE
+       PIC_RETURN()
+1:
+       PIC_TAILCALL(__cerror)
+END(_getcontext)
diff --git a/lib/nbsd_libc/arch/mips/sys/pipe.S b/lib/nbsd_libc/arch/mips/sys/pipe.S
new file mode 100644 (file)
index 0000000..d4047e2
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: pipe.S,v 1.12 2009/12/14 01:07:42 matt Exp $   */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)pipe.s 8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: pipe.S,v 1.12 2009/12/14 01:07:42 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe, _pipe)
+#endif
+
+LEAF(_pipe)
+       PIC_PROLOGUE(_pipe);
+       
+       SYSTRAP(pipe)   # pipe(fildes) int fildes[2];
+
+       bne     a3, zero, 1f
+       INT_S   v0, 0(a0)       # store the two file descriptors
+       INT_S   v1, 4(a0)
+       move    v0, zero
+       PIC_RETURN()
+1:
+       PIC_TAILCALL(__cerror)
+END(_pipe)
diff --git a/lib/nbsd_libc/arch/mips/sys/ptrace.S b/lib/nbsd_libc/arch/mips/sys/ptrace.S
new file mode 100644 (file)
index 0000000..a1817e3
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: ptrace.S,v 1.10 2009/12/14 01:07:42 matt Exp $ */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)ptrace.s       8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: ptrace.S,v 1.10 2009/12/14 01:07:42 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+LEAF(ptrace)
+       PIC_PROLOGUE(ptrace)
+       INT_S   zero, _C_LABEL(errno)   /* BOGUS */
+
+       SYSTRAP(ptrace)
+       bne     a3, zero, 1f
+       PIC_RETURN()
+1:
+       PIC_TAILCALL(__cerror)
+END(ptrace)
diff --git a/lib/nbsd_libc/arch/mips/sys/sbrk.S b/lib/nbsd_libc/arch/mips/sys/sbrk.S
new file mode 100644 (file)
index 0000000..f8b9b52
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: sbrk.S,v 1.18 2010/12/12 09:03:06 tsutsui Exp $        */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)sbrk.s 8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: sbrk.S,v 1.18 2010/12/12 09:03:06 tsutsui Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+       .globl  _C_LABEL(__curbrk)
+       .globl  _C_LABEL(_end)
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(sbrk, _sbrk)
+#endif
+
+       .data
+_C_LABEL(__curbrk):
+       PTR_WORD        _C_LABEL(_end)
+       .text
+
+LEAF(_sbrk)
+       PIC_PROLOGUE(_sbrk)
+       PTR_LA          t0, _C_LABEL(__curbrk)
+       PTR_L           v1, 0(t0)
+       PTR_ADDU        a0, a0, v1      # compute current break
+       SYSTRAP(break)
+       bne             a3, zero, 1f
+       move            v0, v1          # return old val of curbrk from above
+       PTR_LA          t0, _C_LABEL(__curbrk)
+       PTR_S           a0, 0(t0)       # save current val of curbrk from above
+       PIC_RETURN()
+1:
+       PIC_TAILCALL(__cerror)
+END(_sbrk)
diff --git a/lib/nbsd_libc/arch/mips/sys/shmat.S b/lib/nbsd_libc/arch/mips/sys/shmat.S
new file mode 100644 (file)
index 0000000..0e78422
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: shmat.S,v 1.1 2000/07/07 08:20:52 itohy Exp $  */
+
+#include "SYS.h"
+
+RSYSCALL(shmat)
diff --git a/lib/nbsd_libc/arch/mips/sys/syscall.S b/lib/nbsd_libc/arch/mips/sys/syscall.S
new file mode 100644 (file)
index 0000000..9d90f0b
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: syscall.S,v 1.6 2009/12/14 01:07:42 matt Exp $ */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)syscall.s      8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: syscall.S,v 1.6 2009/12/14 01:07:42 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+RSYSCALL(syscall)
diff --git a/lib/nbsd_libc/arch/powerpc/Makefile.inc b/lib/nbsd_libc/arch/powerpc/Makefile.inc
new file mode 100644 (file)
index 0000000..5190904
--- /dev/null
@@ -0,0 +1,9 @@
+#      $NetBSD: Makefile.inc,v 1.13 2011/01/17 08:23:53 matt Exp $
+
+SRCS+=         __sigaction14_sigtramp.c __sigtramp2.S
+
+CPPFLAGS+=     -I.
+
+.if defined(MKSOFTFLOAT) && (${MKSOFTFLOAT} != "no")
+.include <softfloat/Makefile.inc>
+.endif
diff --git a/lib/nbsd_libc/arch/powerpc/SYS.h b/lib/nbsd_libc/arch/powerpc/SYS.h
new file mode 100644 (file)
index 0000000..e6d1ac4
--- /dev/null
@@ -0,0 +1,43 @@
+/*     $NetBSD: SYS.h,v 1.12 2011/01/15 07:31:12 matt Exp $    */
+
+#include <machine/asm.h>
+#include <sys/syscall.h>
+
+#ifdef __STDC__
+#define        _DOSYSCALL(x)           li      %r0,(SYS_ ## x)         ;\
+                               sc
+#else
+#define        _DOSYSCALL(x)           li      %r0,(SYS_/**/x)         ;\
+                               sc
+#endif /* __STDC__ */
+
+#define        _SYSCALL_NOERROR(x,y)   .text                           ;\
+                               .align  2                       ;\
+                       ENTRY(x)                                ;\
+                               _DOSYSCALL(y)
+
+#define _SYSCALL(x,y)          .text                           ;\
+                               .align  2                       ;\
+                       2:      b       _C_LABEL(__cerror)      ;\
+                               _SYSCALL_NOERROR(x,y)           ;\
+                               bso     2b
+
+#define SYSCALL_NOERROR(x)     _SYSCALL_NOERROR(x,x)
+
+#define SYSCALL(x)             _SYSCALL(x,x)
+
+#define PSEUDO_NOERROR(x,y)    _SYSCALL_NOERROR(x,y)           ;\
+                               blr                             ;\
+                               END(x)
+
+#define PSEUDO(x,y)            _SYSCALL_NOERROR(x,y)           ;\
+                               bnslr                           ;\
+                               b       _C_LABEL(__cerror)      ;\
+                               END(x)
+
+#define RSYSCALL_NOERROR(x)    PSEUDO_NOERROR(x,x)
+
+#define RSYSCALL(x)            PSEUDO(x,x)
+
+#define        WSYSCALL(weak,strong)   WEAK_ALIAS(weak,strong)         ;\
+                               PSEUDO(strong,weak)
diff --git a/lib/nbsd_libc/arch/powerpc/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/powerpc/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..1d786e0
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/15 17:35:18 kleink Exp $
+
+SRCS+= strtof.c
diff --git a/lib/nbsd_libc/arch/powerpc/gdtoa/arith.h b/lib/nbsd_libc/arch/powerpc/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..4674f62
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: arith.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define IEEE_BIG_ENDIAN
diff --git a/lib/nbsd_libc/arch/powerpc/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/powerpc/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..75f636b
--- /dev/null
@@ -0,0 +1,5 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define f_QNAN 0x7fc00000
+#define d_QNAN0 0x7ff80000
+#define d_QNAN1 0x0
diff --git a/lib/nbsd_libc/arch/powerpc/gen/Makefile.inc b/lib/nbsd_libc/arch/powerpc/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..a0d1799
--- /dev/null
@@ -0,0 +1,27 @@
+#      $NetBSD: Makefile.inc,v 1.24 2009/12/06 07:12:17 uebayasi Exp $
+
+SRCS+= __setjmp14.S __sigsetjmp14.S _setjmp.S
+SRCS+= bswap16.c bswap32.c bswap64.c
+SRCS+= fabs.c flt_rounds.c
+SRCS+= syncicache.c
+SRCS+=  _lwp.c makecontext.c resumecontext.c swapcontext.S
+
+# Common ieee754 constants and functions
+SRCS+= infinityf_ieee754.c infinity_ieee754.c infinityl_dbl_ieee754.c
+SRCS+= fpclassifyf_ieee754.c fpclassifyd_ieee754.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c
+SRCS+= isfinitef_ieee754.c isfinited_ieee754.c
+SRCS+= signbitf_ieee754.c signbitd_ieee754.c
+
+SRCS+= nanf.c
+
+.if (${MKSOFTFLOAT} == "no")
+SRCS+= fpgetround.c fpsetround.c fpgetmask.c fpsetmask.c
+SRCS+= fpgetsticky.c fpsetsticky.c
+.endif
+
+LSRCS.powerpc.gen=Lint_swapcontext.c
+LSRCS+=                ${LSRCS.powerpc.gen}
+DPSRCS+=       ${LSRCS.powerpc.gen}
+CLEANFILES+=   ${LSRCS.powerpc.gen}
diff --git a/lib/nbsd_libc/arch/powerpc/gen/__setjmp14.S b/lib/nbsd_libc/arch/powerpc/gen/__setjmp14.S
new file mode 100644 (file)
index 0000000..f8cf955
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: __setjmp14.S,v 1.5 2011/01/15 07:31:12 matt Exp $      */
+
+#include "SYS.h"
+#include "assym.h"
+
+#if defined(LIBC_SCCS)
+__RCSID("$NetBSD: __setjmp14.S,v 1.5 2011/01/15 07:31:12 matt Exp $")
+#endif
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v?v:1)" from the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(__setjmp14)
+       mr      %r6,%r3
+       li      %r3,SIG_BLOCK
+       li      %r4,0
+       addi    %r5,%r6,4*(1+24)        # &sigmask
+       _DOSYSCALL(__sigprocmask14)     # assume no error       XXX
+       mflr    %r11
+       mfcr    %r12
+       mr      %r10,%r1
+       mr      %r9,%r2
+       stmw    %r8,4(%r6)              # save r8-r31
+       li      %r3,0
+       blr
+END(__setjmp14)
+
+ENTRY(__longjmp14)
+       lmw     %r8,4(%r3)              # load r8-r31
+       mr      %r6,%r4
+       mtlr    %r11
+       mtcr    %r12
+       mr      %r2,%r9
+       mr      %r1,%r10
+       addi    %r4,%r3,4*(1+24)        # &sigmask
+       li      %r3,SIG_SETMASK
+       li      %r5,0
+       _DOSYSCALL(__sigprocmask14)     # assume no error       XXX
+       or.     %r3,%r6,%r6
+       bnelr
+       li      %r3,1
+       blr
+END(__longjmp14)
diff --git a/lib/nbsd_libc/arch/powerpc/gen/__sigsetjmp14.S b/lib/nbsd_libc/arch/powerpc/gen/__sigsetjmp14.S
new file mode 100644 (file)
index 0000000..e026982
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: __sigsetjmp14.S,v 1.5 2011/01/15 07:31:12 matt Exp $   */
+
+#include "SYS.h"
+#include "assym.h"
+
+#if defined(LIBC_SCCS)
+__RCSID("$NetBSD: __sigsetjmp14.S,v 1.5 2011/01/15 07:31:12 matt Exp $")
+#endif
+
+ENTRY(__sigsetjmp14)
+       mr      %r6,%r3
+       or.     %r7,%r4,%r4
+       beq     1f
+       li      %r3,SIG_BLOCK
+       li      %r4,0
+       addi    %r5,%r6,4*(1+24)        # &sigmask
+       _DOSYSCALL(__sigprocmask14)     # assume no error       XXX
+1:
+       mflr    %r11
+       mfcr    %r12
+       mr      %r10,%r1
+       mr      %r9,%r2
+       stmw    %r7,0(%r6)              # save r7-r31
+       li      %r3,0
+       blr
+END(__sigsetjmp14)
+
+ENTRY(__siglongjmp14)
+       lmw     %r7,0(%r3)              # load r7-r31
+       mr      %r6,%r4
+       mtlr    %r11
+       mtcr    %r12
+       mr      %r2,%r9
+       mr      %r1,%r10
+       or.     %r7,%r7,%r7
+       beq     1f
+       addi    %r4,%r3,4*(1+24)        # &sigmask
+       li      %r3,SIG_SETMASK
+       li      %r5,0
+       _DOSYSCALL(__sigprocmask14)     # assume no error       XXX
+1:
+       or.     %r3,%r6,%r6
+       bnelr
+       li      %r3,1
+       blr
+END(__siglongjmp14)
diff --git a/lib/nbsd_libc/arch/powerpc/gen/_lwp.c b/lib/nbsd_libc/arch/powerpc/gen/_lwp.c
new file mode 100644 (file)
index 0000000..4a55970
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: _lwp.c,v 1.4 2005/06/12 05:21:26 lukem Exp $   */
+
+/*
+ * Copyright (c) 2001 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Allen Briggs for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.4 2005/06/12 05:21:26 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+
+void
+_lwp_makecontext(ucontext_t *u, void (*start)(void *), void *arg,
+       void *private, caddr_t stack_base, size_t stack_size)
+{
+       void    **sp;
+
+       getcontext(u);
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+
+       sp = (void **) (stack_base + stack_size);
+
+       u->uc_mcontext.__gregs[3] = (int) arg;          /* arg1 */
+       u->uc_mcontext.__gregs[1] = ((int) sp) - 12;    /* stack */
+       u->uc_mcontext.__gregs[33] = (int) _lwp_exit;   /* LR */
+       u->uc_mcontext.__gregs[34] = (int) start;       /* PC */
+}
diff --git a/lib/nbsd_libc/arch/powerpc/gen/_setjmp.S b/lib/nbsd_libc/arch/powerpc/gen/_setjmp.S
new file mode 100644 (file)
index 0000000..44f2a57
--- /dev/null
@@ -0,0 +1,39 @@
+/*     $NetBSD: _setjmp.S,v 1.3 2011/01/15 07:31:12 matt Exp $ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+__RCSID("$NetBSD: _setjmp.S,v 1.3 2011/01/15 07:31:12 matt Exp $")
+#endif
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     _longjmp(a,v)
+ * will generate a "return(v?v:1)" from the last call to
+ *     _setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is NOT restored.
+ */
+
+ENTRY(_setjmp)
+       mflr    %r11                    /* save return address */
+       mfcr    %r12                    /* save condition register */
+       mr      %r10,%r1                /* save stack pointer */
+       mr      %r9,%r2                 /* save GPR2 (not needed) */
+       stmw    %r9,8(%r3)              /* save r9..r31 */
+       li      %r3,0                   /* indicate success */
+       blr                             /* return */
+END(_setjmp)
+
+ENTRY(_longjmp)
+       lmw     %r9,8(%r3)              /* save r9..r31 */
+       mtlr    %r11                    /* restore LR */
+       mtcr    %r12                    /* restore CR */
+       mr      %r2,%r9                 /* restore GPR2 (not needed) */
+       mr      %r1,%r10                /* restore stack */
+       or.     %r3,%r4,%r4             /* get return value */
+       bnelr                           /* return if not 0 */
+       li      %r3,1                   /* what's the point? */
+       blr                             /* return */
+END(_longjmp)
diff --git a/lib/nbsd_libc/arch/powerpc/gen/fabs.c b/lib/nbsd_libc/arch/powerpc/gen/fabs.c
new file mode 100644 (file)
index 0000000..25d28db
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: fabs.c,v 1.4 2005/12/24 23:10:08 perry Exp $   */
+
+#include <math.h>
+
+double
+fabs(double x)
+{
+#ifdef _SOFT_FLOAT
+       if (x < 0)
+               x = -x;
+#else
+       __asm volatile("fabs %0,%1" : "=f"(x) : "f"(x));
+#endif
+       return (x);
+}
diff --git a/lib/nbsd_libc/arch/powerpc/gen/flt_rounds.c b/lib/nbsd_libc/arch/powerpc/gen/flt_rounds.c
new file mode 100644 (file)
index 0000000..d0b14f4
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: flt_rounds.c,v 1.10 2005/12/24 23:10:08 perry Exp $    */
+
+/*
+ * Copyright (c) 1996 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Mark Brinicombe
+ *     for the NetBSD Project.
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: flt_rounds.c,v 1.10 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <ieeefp.h>
+#include <float.h>
+#include <stdint.h>
+#include <powerpc/fpu.h>
+
+static const int map[] = {
+       1,      /* round to nearest */
+       0,      /* round to zero */
+       2,      /* round to positive infinity */
+       3       /* round to negative infinity */
+};
+
+int
+__flt_rounds(void)
+{
+#ifdef _SOFT_FLOAT
+       return map[fpgetround()];
+#else
+       uint64_t fpscr;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       return map[((uint32_t)fpscr & FPSCR_RN)];
+#endif
+}
diff --git a/lib/nbsd_libc/arch/powerpc/gen/fpgetmask.c b/lib/nbsd_libc/arch/powerpc/gen/fpgetmask.c
new file mode 100644 (file)
index 0000000..278411b
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: fpgetmask.c,v 1.9 2008/04/28 20:22:56 martin Exp $     */
+
+/*
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dan Winship.
+ * 
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetmask.c,v 1.9 2008/04/28 20:22:56 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+#include <powerpc/fpu.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetmask,_fpgetmask)
+#endif
+
+#define        MASKBITS        (FPSCR_VE|FPSCR_OE|FPSCR_UE|FPSCR_ZE|FPSCR_XE)
+#define        MASKSHFT        3
+
+fp_except
+fpgetmask(void)
+{
+       uint64_t fpscr;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       return (((uint32_t)fpscr & MASKBITS) >> MASKSHFT);
+}
diff --git a/lib/nbsd_libc/arch/powerpc/gen/fpgetround.c b/lib/nbsd_libc/arch/powerpc/gen/fpgetround.c
new file mode 100644 (file)
index 0000000..65c19eb
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: fpgetround.c,v 1.9 2008/04/28 20:22:56 martin Exp $    */
+
+/*
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dan Winship.
+ * 
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetround.c,v 1.9 2008/04/28 20:22:56 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+#include <powerpc/fpu.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetround,_fpgetround)
+#endif
+
+#define        ROUNDBITS       FPSCR_RN
+#define        ROUNDSHFT       0
+
+fp_rnd
+fpgetround(void)
+{
+       uint64_t fpscr;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       return (((uint32_t)fpscr & ROUNDBITS) >> ROUNDSHFT);
+}
diff --git a/lib/nbsd_libc/arch/powerpc/gen/fpgetsticky.c b/lib/nbsd_libc/arch/powerpc/gen/fpgetsticky.c
new file mode 100644 (file)
index 0000000..7fba344
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: fpgetsticky.c,v 1.9 2008/04/28 20:22:56 martin Exp $   */
+
+/*
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dan Winship.
+ * 
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetsticky.c,v 1.9 2008/04/28 20:22:56 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+#include <powerpc/fpu.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetsticky,_fpgetsticky)
+#endif
+
+#define        STICKYBITS      (FPSCR_XX|FPSCR_ZX|FPSCR_UX|FPSCR_OX|FPSCR_VX)
+#define        STICKYSHFT      25
+
+fp_except
+fpgetsticky(void)
+{
+       uint64_t fpscr;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       return (((uint32_t)fpscr & STICKYBITS) >> STICKYSHFT);
+}
diff --git a/lib/nbsd_libc/arch/powerpc/gen/fpsetmask.c b/lib/nbsd_libc/arch/powerpc/gen/fpsetmask.c
new file mode 100644 (file)
index 0000000..8e6f079
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: fpsetmask.c,v 1.9 2008/04/28 20:22:56 martin Exp $     */
+
+/*
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dan Winship.
+ * 
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetmask.c,v 1.9 2008/04/28 20:22:56 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+#include <powerpc/fpu.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetmask,_fpsetmask)
+#endif
+
+#define        MASKBITS        (FPSCR_XE|FPSCR_ZE|FPSCR_UE|FPSCR_OE|FPSCR_VE)
+#define        MASKSHFT        3
+
+fp_except
+fpsetmask(fp_except mask)
+{
+       uint64_t fpscr;
+       fp_except old;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       old = ((uint32_t)fpscr & MASKBITS) >> MASKSHFT;
+       fpscr &= ~MASKBITS;
+       fpscr |= ((uint32_t)mask << MASKSHFT) & MASKBITS;
+       __asm volatile("mtfsf 0xff,%0" :: "f"(fpscr));
+       return (old);
+}
diff --git a/lib/nbsd_libc/arch/powerpc/gen/fpsetround.c b/lib/nbsd_libc/arch/powerpc/gen/fpsetround.c
new file mode 100644 (file)
index 0000000..d451241
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: fpsetround.c,v 1.9 2008/04/28 20:22:57 martin Exp $    */
+
+/*
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dan Winship.
+ * 
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetround.c,v 1.9 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+#include <powerpc/fpu.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetround,_fpsetround)
+#endif
+
+#define        ROUNDBITS       FPSCR_RN
+
+fp_rnd
+fpsetround(fp_rnd rnd_dir)
+{
+       uint64_t fpscr;
+       fp_rnd old;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       old = (uint32_t)fpscr & ROUNDBITS;
+       fpscr &= ~ROUNDBITS;
+       fpscr |= rnd_dir & ROUNDBITS;
+       __asm volatile("mtfsf 0xff,%0" :: "f"(fpscr));
+       return (old);
+}
diff --git a/lib/nbsd_libc/arch/powerpc/gen/fpsetsticky.c b/lib/nbsd_libc/arch/powerpc/gen/fpsetsticky.c
new file mode 100644 (file)
index 0000000..2ce3f7d
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: fpsetsticky.c,v 1.10 2008/04/28 20:22:57 martin Exp $  */
+
+/*
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dan Winship.
+ * 
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetsticky.c,v 1.10 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+#include <powerpc/fpu.h>
+
+#define        STICKYBITS      (FPSCR_XX|FPSCR_ZX|FPSCR_UX|FPSCR_OX|FPSCR_VX)
+#define        INVBITS         (FPSCR_VXCVI|FPSCR_VXSQRT|FPSCR_VXSOFT|FPSCR_VXVC|\
+                        FPSCR_VXIMZ|FPSCR_VXZDZ|FPSCR_VXIDI|FPSCR_VXISI|\
+                        FPSCR_VXSNAN)
+#define        STICKYSHFT      25
+
+#ifdef __weak_alias
+__weak_alias(fpsetsticky,_fpsetsticky)
+#endif
+
+fp_except
+fpsetsticky(fp_except mask)
+{
+       uint64_t fpscr;
+       fp_except old;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       old = ((uint32_t)fpscr & STICKYBITS) >> STICKYSHFT;
+       /*
+        * FPSCR_VX (aka FP_X_INV) is not a sticky bit but a summary of the
+        * all the FPSCR_VX* sticky bits.  So when FP_X_INV is cleared then
+        * clear all of those bits, likewise when it's set, set them all.
+        */
+       if ((mask & FP_X_INV) == 0)
+               fpscr &= ~INVBITS;
+       else 
+               fpscr |= INVBITS;
+       fpscr &= ~STICKYBITS;
+       fpscr |= ((uint32_t)mask << STICKYSHFT) & STICKYBITS;
+       /*
+        * Make FPSCR_FX reflect the presence of a set sticky bit (or not).
+        */
+       if (fpscr & (STICKYBITS|INVBITS))
+               fpscr |= FPSCR_FX;
+       else
+               fpscr &= ~FPSCR_FX;
+       /*
+        * Write back the fpscr.
+        */
+       __asm volatile("mtfsf 0xff,%0" :: "f"(fpscr));
+       return (old);
+}
diff --git a/lib/nbsd_libc/arch/powerpc/gen/makecontext.c b/lib/nbsd_libc/arch/powerpc/gen/makecontext.c
new file mode 100644 (file)
index 0000000..3d8f763
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: makecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include <inttypes.h>
+#include <stddef.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#if __STDC__
+#include <stdarg.h>
+#else
+#include <varargs.h>
+#endif
+
+void
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+{
+       __greg_t *gr = ucp->uc_mcontext.__gregs;
+       int *sp;
+       int i;
+       va_list ap;
+
+       /* LINTED uintptr_t is safe */
+       sp  = (int *)
+           ((uintptr_t)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size);
+       /* LINTED uintptr_t is safe */
+       sp -= 2 + (argc > 8 ? argc - 8: 0); /* Make room for call frame. */
+       sp  = (int *)
+           ((uintptr_t)sp & ~0xf);     /* Align on quad-word boundary. */
+
+       /*
+        * Start executing at <func> -- when <func> completes, return to
+        * <_resumecontext>.
+        */
+       gr[_REG_R1]  = (__greg_t)sp;
+       gr[_REG_LR] = (__greg_t)_resumecontext;
+       gr[_REG_PC] = (__greg_t)func;
+
+       /* Wipe out stack frame backchain pointer. */
+       *sp = 0;
+
+       /* Construct argument list. */
+       va_start(ap, argc);
+       /* Up to the first eight arguments are passed in r3-10. */
+       for (i = 0; i < argc && i < 8; i++)
+               gr[_REG_R3 + i] = va_arg(ap, int);
+       /* Pass remaining arguments on the stack above the backchain/lr gap. */
+       for (sp += 2; i < argc; i++)
+               *sp++ = va_arg(ap, int);
+       va_end(ap);
+}
diff --git a/lib/nbsd_libc/arch/powerpc/gen/nanf.c b/lib/nbsd_libc/arch/powerpc/gen/nanf.c
new file mode 100644 (file)
index 0000000..1688d0e
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: nanf.c,v 1.4 2009/02/22 01:34:02 martin Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nanf.c,v 1.4 2009/02/22 01:34:02 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+/* bytes for quiet NaN (IEEE single precision) */
+const union __float_u __nanf =
+               { { 0x7f, 0xc0,    0,    0 } };
+
+__warn_references(__nanf, "warning: <math.h> defines NAN incorrectly for your compiler.")
diff --git a/lib/nbsd_libc/arch/powerpc/gen/resumecontext.c b/lib/nbsd_libc/arch/powerpc/gen/resumecontext.c
new file mode 100644 (file)
index 0000000..1a7c4c5
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "extern.h"
+
+void
+_resumecontext()
+{
+       ucontext_t uct;
+
+       (void)getcontext(&uct);
+       if (uct.uc_link == NULL) 
+               exit(0);
+       (void)setcontext(uct.uc_link);
+       _exit(-1);
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/powerpc/gen/swapcontext.S b/lib/nbsd_libc/arch/powerpc/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..d5db5d1
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: swapcontext.S,v 1.6 2011/01/16 02:43:10 matt Exp $     */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+#include "assym.h"
+
+__RCSID("$NetBSD: swapcontext.S,v 1.6 2011/01/16 02:43:10 matt Exp $")
+
+#define        XCALLFRAMELEN   (((2+3)*SZREG + CALLFRAMELEN - 1) & -CALLFRAMELEN)
+#define        XCALLFRAME_R30  (XCALLFRAMELEN-1*SZREG)
+#define        XCALLFRAME_UCP  (XCALLFRAMELEN-2*SZREG)
+#define        XCALLFRAME_OUCP (XCALLFRAMELEN-3*SZREG)
+
+ENTRY(swapcontext)
+       stwu    %r1,-XCALLFRAMELEN(%r1)         # set up new stack frame
+       mflr    %r0
+       stw     %r0,XCALLFRAMELEN+CALLFRAME_LR(%r1)     # save link register
+       stw     %r3,XCALLFRAME_OUCP(%r1)        # must save oucp
+       stw     %r4,XCALLFRAME_UCP(%r1)         # must save ucp
+#ifdef PIC
+       stw     %r30,XCALLFRAME_R30(%r1)        # must save r30
+       PIC_TOCSETUP(swapcontext,%r30)          # setup toc pointer
+#endif
+       bl      PIC_PLT(_C_LABEL(_getcontext))  # getcontext(oucp)
+       cmpwi   %r3,0
+       bne     1f
+       lwz     %r11,XCALLFRAME_OUCP(%r1)       # load oucp for adjustment
+       lwz     %r0,XCALLFRAMELEN+CALLFRAME_LR(%r1)
+       stw     %r0,UC_GREGS_PC(%r11)           # pc <- lr
+       addi    %r0,%r1,XCALLFRAMELEN
+       stw     %r0,UC_GREGS_R1(%r11)           # adjust sp
+       lwz     %r3,XCALLFRAME_UCP(%r1)         # load ucp
+       bl      PIC_PLT(_C_LABEL(setcontext))   # setcontext(ucp)
+1:
+       lwz     %r0,XCALLFRAMELEN+CALLFRAME_LR(%r1)
+#ifdef PIC
+       lwz     %r30,XCALLFRAME_R30(%r1)
+#endif
+       mtlr    %r0
+       addi    %r1,%r1,XCALLFRAMELEN
+       blr
+END(swapcontext)
diff --git a/lib/nbsd_libc/arch/powerpc/gen/syncicache.c b/lib/nbsd_libc/arch/powerpc/gen/syncicache.c
new file mode 100644 (file)
index 0000000..2c16406
--- /dev/null
@@ -0,0 +1,140 @@
+/*     $NetBSD: syncicache.c,v 1.15 2008/03/18 20:11:43 he Exp $       */
+
+/*
+ * Copyright (C) 1995-1997, 1999 Wolfgang Solfrank.
+ * Copyright (C) 1995-1997, 1999 TooLs GmbH.
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by TooLs GmbH.
+ * 4. The name of TooLs GmbH may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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 <sys/param.h>
+#if    defined(_KERNEL)
+#include <sys/time.h>
+#include <sys/proc.h>
+#include <uvm/uvm_extern.h>
+#endif
+#if    !defined(_STANDALONE)
+#include <sys/sysctl.h>
+#endif
+
+#include <machine/cpu.h>
+
+
+#if defined(_STANDALONE)
+#ifndef        CACHELINESIZE
+#error "Must know the size of a cache line"
+#endif
+static struct cache_info _cache_info = {
+       CACHELINESIZE,
+       CACHELINESIZE,
+       CACHELINESIZE,
+       CACHELINESIZE
+};
+#define CACHEINFO      _cache_info
+#elif defined(_KERNEL)
+#define        CACHEINFO       (curcpu()->ci_ci)
+#else
+#include <stdlib.h>
+
+size_t __getcachelinesize (void);
+
+static int _cachelinesize = 0;
+
+static struct cache_info _cache_info;
+#define CACHEINFO      _cache_info
+
+size_t
+__getcachelinesize(void)
+{
+       static int cachemib[] = { CTL_MACHDEP, CPU_CACHELINE };
+       static int cacheinfomib[] = { CTL_MACHDEP, CPU_CACHEINFO };
+       size_t clen = sizeof(_cache_info);
+
+       if (_cachelinesize)
+               return _cachelinesize;
+
+       if (sysctl(cacheinfomib, sizeof(cacheinfomib) / sizeof(cacheinfomib[0]),
+               &_cache_info, &clen, NULL, 0) == 0) {
+               _cachelinesize = _cache_info.dcache_line_size;
+               return _cachelinesize;
+       }
+
+       /* Try older deprecated sysctl */
+       clen = sizeof(_cachelinesize);
+       if (sysctl(cachemib, sizeof(cachemib) / sizeof(cachemib[0]),
+                  &_cachelinesize, &clen, NULL, 0) < 0
+           || !_cachelinesize)
+               abort();
+
+       _cache_info.dcache_size = _cachelinesize;
+       _cache_info.dcache_line_size = _cachelinesize;
+       _cache_info.icache_size = _cachelinesize;
+       _cache_info.icache_line_size = _cachelinesize;
+
+       /* If there is no cache, indicate we have issued the sysctl. */
+       if (!_cachelinesize)
+               _cachelinesize = 1;
+
+       return _cachelinesize;
+}
+#endif
+
+void
+__syncicache(void *from, size_t len)
+{
+       size_t l, off;
+       size_t linesz;
+       char *p;
+
+#if    !defined(_KERNEL) && !defined(_STANDALONE)
+       if (!_cachelinesize)
+               __getcachelinesize();
+#endif 
+
+       if (CACHEINFO.dcache_size > 0) {
+               linesz = CACHEINFO.dcache_line_size;
+               off = (uintptr_t)from & (linesz - 1);
+               l = (len + off + linesz - 1) & ~(linesz - 1);
+               p = (char *)from - off;
+               do {
+                       __asm volatile ("dcbst 0,%0" :: "r"(p));
+                       p += linesz;
+               } while ((l -= linesz) != 0);
+       }
+       __asm volatile ("sync");
+
+       if (CACHEINFO.icache_size > 0 ) {
+               linesz = CACHEINFO.icache_line_size;
+               off = (uintptr_t)from & (linesz - 1);
+               l = (len + off + linesz - 1) & ~(linesz - 1);
+               p = (char *)from - off;
+               do {
+                       __asm volatile ("icbi 0,%0" :: "r"(p));
+                       p += linesz;
+               } while ((l -= linesz) != 0);
+       }
+       __asm volatile ("sync; isync");
+}
diff --git a/lib/nbsd_libc/arch/powerpc/genassym.cf b/lib/nbsd_libc/arch/powerpc/genassym.cf
new file mode 100644 (file)
index 0000000..5fb2277
--- /dev/null
@@ -0,0 +1,48 @@
+#      $NetBSD: genassym.cf,v 1.3 2011/01/18 01:23:24 matt Exp $
+
+#
+# Copyright (c) 2001 The NetBSD Foundation, Inc.
+# All rights reserved.
+#
+# This code is derived from software contributed to The NetBSD Foundation
+# by Matt Thomas <matt@3am-sfotware.com>.
+#
+# 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/types.h>
+include <sys/signal.h>
+include <sys/ucontext.h>
+
+include <machine/frame.h>
+
+define CALLFRAMELEN    sizeof(struct callframe)
+define CALLFRAME_LR    offsetof(struct callframe, cf_lr)
+define CALLFRAME_R30   offsetof(struct callframe, cf_r30)
+define CALLFRAME_R31   offsetof(struct callframe, cf_r31)
+
+define UC_GREGS_R1     offsetof(ucontext_t, uc_mcontext.__gregs[_REG_R1])
+define UC_GREGS_R3     offsetof(ucontext_t, uc_mcontext.__gregs[_REG_R3])
+define UC_GREGS_PC     offsetof(ucontext_t, uc_mcontext.__gregs[_REG_PC])
+
+define SIG_BLOCK       SIG_BLOCK
+define SIG_SETMASK     SIG_SETMASK
diff --git a/lib/nbsd_libc/arch/powerpc/net/Makefile.inc b/lib/nbsd_libc/arch/powerpc/net/Makefile.inc
new file mode 100644 (file)
index 0000000..80be363
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.2 2003/05/12 09:32:10 kleink Exp $
+
+SRCS+= htonl.c htons.c ntohl.c ntohs.c
diff --git a/lib/nbsd_libc/arch/powerpc/softfloat/milieu.h b/lib/nbsd_libc/arch/powerpc/softfloat/milieu.h
new file mode 100644 (file)
index 0000000..52c2bc3
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: milieu.h,v 1.1 2001/05/25 11:38:57 simonb Exp $        */
+
+/*
+===============================================================================
+
+This C header file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+Include common integer types and flags.
+-------------------------------------------------------------------------------
+*/
+#include "powerpc-gcc.h"
+
+/*
+-------------------------------------------------------------------------------
+Symbolic Boolean literals.
+-------------------------------------------------------------------------------
+*/
+enum {
+    FALSE = 0,
+    TRUE  = 1
+};
diff --git a/lib/nbsd_libc/arch/powerpc/softfloat/powerpc-gcc.h b/lib/nbsd_libc/arch/powerpc/softfloat/powerpc-gcc.h
new file mode 100644 (file)
index 0000000..9a17842
--- /dev/null
@@ -0,0 +1,89 @@
+/*     $NetBSD: powerpc-gcc.h,v 1.2 2005/12/24 21:11:16 perry Exp $    */
+
+/*
+-------------------------------------------------------------------------------
+One of the macros `BIGENDIAN' or `LITTLEENDIAN' must be defined.
+-------------------------------------------------------------------------------
+*/
+#include <machine/endian.h>
+#if _BYTE_ORDER == _BIG_ENDIAN
+#define BIGENDIAN
+#endif
+#if _BYTE_ORDER == _LITTLE_ENDIAN
+#define LITTLEENDIAN
+#endif
+
+/*
+-------------------------------------------------------------------------------
+The macro `BITS64' can be defined to indicate that 64-bit integer types are
+supported by the compiler.
+-------------------------------------------------------------------------------
+*/
+#define BITS64
+
+/*
+-------------------------------------------------------------------------------
+Each of the following `typedef's defines the most convenient type that holds
+integers of at least as many bits as specified.  For example, `uint8' should
+be the most convenient type that can hold unsigned integers of as many as
+8 bits.  The `flag' type must be able to hold either a 0 or 1.  For most
+implementations of C, `flag', `uint8', and `int8' should all be `typedef'ed
+to the same as `int'.
+-------------------------------------------------------------------------------
+*/
+typedef int flag;
+typedef int uint8;
+typedef int int8;
+typedef int uint16;
+typedef int int16;
+typedef unsigned int uint32;
+typedef signed int int32;
+#ifdef BITS64
+typedef unsigned long long int uint64;
+typedef signed long long int int64;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Each of the following `typedef's defines a type that holds integers
+of _exactly_ the number of bits specified.  For instance, for most
+implementation of C, `bits16' and `sbits16' should be `typedef'ed to
+`unsigned short int' and `signed short int' (or `short int'), respectively.
+-------------------------------------------------------------------------------
+*/
+typedef unsigned char bits8;
+typedef signed char sbits8;
+typedef unsigned short int bits16;
+typedef signed short int sbits16;
+typedef unsigned int bits32;
+typedef signed int sbits32;
+#ifdef BITS64
+typedef unsigned long long int bits64;
+typedef signed long long int sbits64;
+#endif
+
+#ifdef BITS64
+/*
+-------------------------------------------------------------------------------
+The `LIT64' macro takes as its argument a textual integer literal and
+if necessary ``marks'' the literal as having a 64-bit integer type.
+For example, the GNU C Compiler (`gcc') requires that 64-bit literals be
+appended with the letters `LL' standing for `long long', which is `gcc's
+name for the 64-bit integer type.  Some compilers may allow `LIT64' to be
+defined as the identity macro:  `#define LIT64( a ) a'.
+-------------------------------------------------------------------------------
+*/
+#define LIT64( a ) a##LL
+#endif
+
+/*
+-------------------------------------------------------------------------------
+The macro `INLINE' can be used before functions that should be inlined.  If
+a compiler does not support explicit inlining, this macro should be defined
+to be `static'.
+-------------------------------------------------------------------------------
+*/
+#define INLINE static inline
+
+#define FLOAT64_DEMANGLE(a)    (a)
+#define FLOAT64_MANGLE(a)      (a)
diff --git a/lib/nbsd_libc/arch/powerpc/softfloat/softfloat.h b/lib/nbsd_libc/arch/powerpc/softfloat/softfloat.h
new file mode 100644 (file)
index 0000000..d9c095b
--- /dev/null
@@ -0,0 +1,303 @@
+/*     $NetBSD: softfloat.h,v 1.5 2006/05/16 20:55:51 mrg Exp $        */
+
+/* This is a derivative work. */
+
+/*
+===============================================================================
+
+This C header file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+The macro `FLOATX80' must be defined to enable the extended double-precision
+floating-point format `floatx80'.  If this macro is not defined, the
+`floatx80' type will not be defined, and none of the functions that either
+input or output the `floatx80' type will be defined.  The same applies to
+the `FLOAT128' macro and the quadruple-precision format `float128'.
+-------------------------------------------------------------------------------
+*/
+/* #define FLOATX80 */
+/* #define FLOAT128 */
+
+#include <machine/ieeefp.h>
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point types.
+-------------------------------------------------------------------------------
+*/
+typedef unsigned int float32;
+typedef unsigned long long float64;
+#ifdef FLOATX80
+typedef struct {
+    unsigned short high;
+    unsigned long long low;
+} floatx80;
+#endif
+#ifdef FLOAT128
+typedef struct {
+    unsigned long long high, low;
+} float128;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point underflow tininess-detection mode.
+-------------------------------------------------------------------------------
+*/
+#ifndef SOFTFLOAT_FOR_GCC
+extern int8 float_detect_tininess;
+#endif
+enum {
+    float_tininess_after_rounding  = 0,
+    float_tininess_before_rounding = 1
+};
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point rounding mode.
+-------------------------------------------------------------------------------
+*/
+extern fp_rnd float_rounding_mode;
+enum {
+    float_round_nearest_even = FP_RN,
+    float_round_to_zero      = FP_RZ,
+    float_round_down         = FP_RM,
+    float_round_up           = FP_RP
+};
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point exception flags.
+-------------------------------------------------------------------------------
+*/
+extern fp_except float_exception_flags;
+extern fp_except float_exception_mask;
+enum {
+    float_flag_inexact   = FP_X_IMP,
+    float_flag_underflow = FP_X_UFL,
+    float_flag_overflow  = FP_X_OFL,
+    float_flag_divbyzero = FP_X_DZ,
+    float_flag_invalid   = FP_X_INV
+};
+
+/*
+-------------------------------------------------------------------------------
+Routine to raise any or all of the software IEC/IEEE floating-point
+exception flags.
+-------------------------------------------------------------------------------
+*/
+void float_raise( fp_except );
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE integer-to-floating-point conversion routines.
+-------------------------------------------------------------------------------
+*/
+float32 int32_to_float32( int );
+float64 int32_to_float64( int );
+#ifdef FLOATX80
+floatx80 int32_to_floatx80( int );
+#endif
+#ifdef FLOAT128
+float128 int32_to_float128( int );
+#endif
+float32 int64_to_float32( long long );
+float64 int64_to_float64( long long );
+#ifdef FLOATX80
+floatx80 int64_to_floatx80( long long );
+#endif
+#ifdef FLOAT128
+float128 int64_to_float128( long long );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE single-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float32_to_int32( float32 );
+int float32_to_int32_round_to_zero( float32 );
+unsigned int float32_to_uint32_round_to_zero( float32 );
+long long float32_to_int64( float32 );
+long long float32_to_int64_round_to_zero( float32 );
+float64 float32_to_float64( float32 );
+#ifdef FLOATX80
+floatx80 float32_to_floatx80( float32 );
+#endif
+#ifdef FLOAT128
+float128 float32_to_float128( float32 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE single-precision operations.
+-------------------------------------------------------------------------------
+*/
+float32 float32_round_to_int( float32 );
+float32 float32_add( float32, float32 );
+float32 float32_sub( float32, float32 );
+float32 float32_mul( float32, float32 );
+float32 float32_div( float32, float32 );
+float32 float32_rem( float32, float32 );
+float32 float32_sqrt( float32 );
+flag float32_eq( float32, float32 );
+flag float32_le( float32, float32 );
+flag float32_lt( float32, float32 );
+flag float32_eq_signaling( float32, float32 );
+flag float32_le_quiet( float32, float32 );
+flag float32_lt_quiet( float32, float32 );
+#ifndef SOFTFLOAT_FOR_GCC
+flag float32_is_signaling_nan( float32 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE double-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float64_to_int32( float64 );
+int float64_to_int32_round_to_zero( float64 );
+unsigned int float64_to_uint32_round_to_zero( float64 );
+long long float64_to_int64( float64 );
+long long float64_to_int64_round_to_zero( float64 );
+float32 float64_to_float32( float64 );
+#ifdef FLOATX80
+floatx80 float64_to_floatx80( float64 );
+#endif
+#ifdef FLOAT128
+float128 float64_to_float128( float64 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE double-precision operations.
+-------------------------------------------------------------------------------
+*/
+float64 float64_round_to_int( float64 );
+float64 float64_add( float64, float64 );
+float64 float64_sub( float64, float64 );
+float64 float64_mul( float64, float64 );
+float64 float64_div( float64, float64 );
+float64 float64_rem( float64, float64 );
+float64 float64_sqrt( float64 );
+flag float64_eq( float64, float64 );
+flag float64_le( float64, float64 );
+flag float64_lt( float64, float64 );
+flag float64_eq_signaling( float64, float64 );
+flag float64_le_quiet( float64, float64 );
+flag float64_lt_quiet( float64, float64 );
+#ifndef SOFTFLOAT_FOR_GCC
+flag float64_is_signaling_nan( float64 );
+#endif
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int floatx80_to_int32( floatx80 );
+int floatx80_to_int32_round_to_zero( floatx80 );
+long long floatx80_to_int64( floatx80 );
+long long floatx80_to_int64_round_to_zero( floatx80 );
+float32 floatx80_to_float32( floatx80 );
+float64 floatx80_to_float64( floatx80 );
+#ifdef FLOAT128
+float128 floatx80_to_float128( floatx80 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision rounding precision.  Valid
+values are 32, 64, and 80.
+-------------------------------------------------------------------------------
+*/
+extern int floatx80_rounding_precision;
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision operations.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_round_to_int( floatx80 );
+floatx80 floatx80_add( floatx80, floatx80 );
+floatx80 floatx80_sub( floatx80, floatx80 );
+floatx80 floatx80_mul( floatx80, floatx80 );
+floatx80 floatx80_div( floatx80, floatx80 );
+floatx80 floatx80_rem( floatx80, floatx80 );
+floatx80 floatx80_sqrt( floatx80 );
+flag floatx80_eq( floatx80, floatx80 );
+flag floatx80_le( floatx80, floatx80 );
+flag floatx80_lt( floatx80, floatx80 );
+flag floatx80_eq_signaling( floatx80, floatx80 );
+flag floatx80_le_quiet( floatx80, floatx80 );
+flag floatx80_lt_quiet( floatx80, floatx80 );
+flag floatx80_is_signaling_nan( floatx80 );
+
+#endif
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE quadruple-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float128_to_int32( float128 );
+int float128_to_int32_round_to_zero( float128 );
+long long float128_to_int64( float128 );
+long long float128_to_int64_round_to_zero( float128 );
+float32 float128_to_float32( float128 );
+float64 float128_to_float64( float128 );
+#ifdef FLOATX80
+floatx80 float128_to_floatx80( float128 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE quadruple-precision operations.
+-------------------------------------------------------------------------------
+*/
+float128 float128_round_to_int( float128 );
+float128 float128_add( float128, float128 );
+float128 float128_sub( float128, float128 );
+float128 float128_mul( float128, float128 );
+float128 float128_div( float128, float128 );
+float128 float128_rem( float128, float128 );
+float128 float128_sqrt( float128 );
+flag float128_eq( float128, float128 );
+flag float128_le( float128, float128 );
+flag float128_lt( float128, float128 );
+flag float128_eq_signaling( float128, float128 );
+flag float128_le_quiet( float128, float128 );
+flag float128_lt_quiet( float128, float128 );
+flag float128_is_signaling_nan( float128 );
+
+#endif
diff --git a/lib/nbsd_libc/arch/powerpc/stdlib/Makefile.inc b/lib/nbsd_libc/arch/powerpc/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..2f91b99
--- /dev/null
@@ -0,0 +1 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/07/31 20:40:00 dsl Exp $
diff --git a/lib/nbsd_libc/arch/powerpc/string/Makefile.inc b/lib/nbsd_libc/arch/powerpc/string/Makefile.inc
new file mode 100644 (file)
index 0000000..5814c9a
--- /dev/null
@@ -0,0 +1,24 @@
+#      $NetBSD: Makefile.inc,v 1.13 2010/03/14 00:26:10 mrg Exp $
+
+SRCS+=  bzero.S ffs.S strlen.S
+NO_SRCS+= memset.S
+
+# disable the asm versions of these because they break the explora.
+# the special rules here are to override the suffix rules which seem
+# to prefer .S files over .c
+.if ${MACHINE} == "evbppc"
+bcopy.o: bcopy.c
+bcopy.po: bcopy.c
+bcopy.pico: bcopy.c
+memcpy.o: memcpy.c
+memcpy.po: memcpy.c
+memcpy.pico: memcpy.c
+memcmp.o: memcmp.c
+memcmp.po: memcmp.c
+memcmp.pico: memcmp.c
+memmove.o: memmove.c
+memmove.po: memmove.c
+memmove.pico: memmove.c
+.else
+SRCS+= memcmp.S bcopy.S memcpy.S memmove.S
+.endif
diff --git a/lib/nbsd_libc/arch/powerpc/string/bzero.S b/lib/nbsd_libc/arch/powerpc/string/bzero.S
new file mode 100644 (file)
index 0000000..3e441e1
--- /dev/null
@@ -0,0 +1,378 @@
+/*     $NetBSD: bzero.S,v 1.10 2011/01/19 02:47:01 matt Exp $ */
+
+/*-
+ * Copyright (C) 2001  Martin J. Laubach <mjl@NetBSD.org>
+ * 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.
+ * 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 ``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 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 <machine/asm.h>
+
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: bzero.S,v 1.10 2011/01/19 02:47:01 matt Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+#ifdef _KERNEL
+#include <assym.h>
+#endif
+
+#define USE_STSWX 0    /* don't. slower than trivial copy loop */
+
+/*----------------------------------------------------------------------*/
+/*
+     void bzero(void *b %r3, size_t len %r4);
+     void * memset(void *b %r3, int c %r4, size_t len %r5);
+*/
+/*----------------------------------------------------------------------*/
+
+#define r_dst  %r3
+#define r_len  %r4
+#define r_val  %r0
+
+               .text
+               .align 4
+ENTRY(bzero)
+               li      r_val, 0                /* Value to stuff in */
+               b       cb_memset
+END(bzero)
+
+ENTRY(memset)
+               cmplwi  cr1, %r5, 0
+               mr.     %r0, %r4
+               mr      %r8, %r3
+               beqlr-  cr1                     /* Nothing to do */
+
+               rlwimi  %r0, %r4, 8, 16, 23     /* word extend fill value */
+               rlwimi  %r0, %r0, 16, 0, 15
+               mr      %r4, %r5
+               bne-    simple_fill             /* =! 0, use trivial fill */
+cb_memset:
+
+/*----------------------------------------------------------------------*/
+#ifndef _KERNEL
+               /* First find out cache line size */
+               mflr    %r9
+#ifdef PIC
+               PIC_GOTSETUP(%r10)
+               mtlr    %r9
+               lwz     %r5,cache_info@got(%r10)
+#else
+               lis     %r5,cache_info@h
+               ori     %r5,%r5,cache_info@l
+#endif
+               lwz     %r6, 4(%r5)
+               cmpwi   %r6, -1
+               bne+    cb_cacheline_known
+
+/*----------------------------------------------------------------------*/
+#define CTL_MACHDEP    7
+#define CPU_CACHELINE  1
+#define        CPU_CACHEINFO   5
+
+#define STKFRAME_SZ    64
+#define MIB            8
+#define OLDPLEN                16
+#define R3_SAVE                20
+#define R4_SAVE                24
+#define R0_SAVE                28
+#define R8_SAVE                32
+#define R31_SAVE       36
+#ifdef PIC
+#define R30_SAVE       40
+#endif
+
+               stw     %r9, 4(%r1)
+               stwu    %r1, -STKFRAME_SZ(%r1)
+
+               stw     %r31, R31_SAVE(%r1)
+               mr      %r31, %r5               /* cache info */
+
+#ifdef PIC
+               stw     %r30, R30_SAVE(%r1)
+               PIC_TOCSETUP(cb_memset,%r30)
+#endif
+
+               stw     %r8, R8_SAVE(%r1)
+               stw     %r3, R3_SAVE(%r1)
+               stw     %r4, R4_SAVE(%r1)
+               stw     %r0, R0_SAVE(%r1)
+
+               li      %r0, CTL_MACHDEP                /* Construct MIB */
+               stw     %r0, MIB(%r1)
+               li      %r0, CPU_CACHEINFO
+               stw     %r0, MIB+4(%r1)
+
+               li      %r0, 4*4                        /* Oldlenp := 4*4 */
+               stw     %r0, OLDPLEN(%r1)
+
+               addi    %r3, %r1, MIB
+               li      %r4, 2                  /* namelen */
+               /* %r5 already contains &cache_info */
+               addi    %r6, %r1, OLDPLEN
+               li      %r7, 0
+               li      %r8, 0
+               bl      PIC_PLT(_C_LABEL(sysctl))
+       
+               cmpwi   %r3, 0                  /* Check result */
+               beq     1f
+
+               /* Failure, try older sysctl */
+       
+               li      %r0, CTL_MACHDEP        /* Construct MIB */
+               stw     %r0, MIB(%r1)
+               li      %r0, CPU_CACHELINE
+               stw     %r0, MIB+4(%r1)
+
+               li      %r0, 4                  /* Oldlenp := 4 */
+               stw     %r0, OLDPLEN(%r1)
+
+               addi    %r3, %r1, MIB
+               li      %r4, 2                  /* namelen */
+               addi    %r5, %r31, 4
+               addi    %r6, %r1, OLDPLEN
+               li      %r7, 0
+               li      %r8, 0
+               bl      PIC_PLT(_C_LABEL(sysctl))
+1:
+               lwz     %r3, R3_SAVE(%r1)
+               lwz     %r4, R4_SAVE(%r1)
+               lwz     %r8, R8_SAVE(%r1)
+               lwz     %r0, R0_SAVE(%r1)
+               lwz     %r9, 4(%r31)
+               lwz     %r31, R31_SAVE(%r1)
+#ifdef PIC
+               lwz     %r30, R30_SAVE(%r1)
+#endif
+               addi    %r1, %r1, STKFRAME_SZ
+               lwz     %r0, 4(%r1)
+               mtlr    %r0
+
+               cntlzw  %r6, %r9                        /* compute shift value */
+               li      %r5, 31
+               subf    %r5, %r6, %r5
+
+#ifdef PIC
+               mflr    %r9
+               PIC_GOTSETUP(%r10)
+               mtlr    %r9
+               lwz     %r6, cache_sh@got(%r10)
+               stw     %r5, 0(%r6)
+#else
+               lis     %r6, cache_sh@ha
+               stw     %r5, cache_sh@l(%r6)
+#endif
+/*----------------------------------------------------------------------*/
+/* Okay, we know the cache line size (%r9) and shift value (%r10) */
+cb_cacheline_known:
+#ifdef PIC
+               lwz     %r5, cache_info@got(%r10)
+               lwz     %r9, 4(%r5)
+               lwz     %r5, cache_sh@got(%r10)
+               lwz     %r10, 0(%r5)
+#else
+               lis     %r9, cache_info+4@ha
+               lwz     %r9, cache_info+4@l(%r9)
+               lis     %r10, cache_sh@ha
+               lwz     %r10, cache_sh@l(%r10)
+#endif
+
+#else /* _KERNEL */
+#ifdef MULTIPROCESSOR
+               mfsprg  %r10, 0                 /* Get cpu_info pointer */
+#else
+               lis     %r10, cpu_info_store@ha
+               addi    %r10, %r10, cpu_info_store@l
+#endif
+               lwz     %r9, CPU_CI+4(%r10)     /* Load D$ line size */
+               cntlzw  %r10, %r9                       /* Calculate shift.. */
+               li      %r6, 31
+               subf    %r10, %r10, %r6
+#endif /* _KERNEL */
+               /* Back in memory filling business */
+               
+               cmplwi  cr1, r_len, 0           /* Nothing to do? */
+               add     %r5, %r9, %r9
+               cmplw   r_len, %r5              /* <= 2*CL bytes to move? */
+               beqlr-  cr1                     /* then do nothing */
+
+               blt+    simple_fill             /* a trivial fill routine */
+
+               /* Word align the block, fill bytewise until dst even*/
+               
+               andi.   %r5, r_dst, 0x03        
+               li      %r6, 4
+               beq+    cb_aligned_w            /* already aligned to word? */
+
+               subf    %r5, %r5, %r6           /* bytes to fill to align4 */
+#if USE_STSWX
+               mtxer   %r5
+               stswx   %r0, 0, r_dst
+               add     r_dst, %r5, r_dst
+#else
+               mtctr   %r5
+
+               subi    r_dst, r_dst, 1
+1:             stbu    r_val, 1(r_dst)         /* Fill bytewise */
+               bdnz    1b
+
+               addi    r_dst, r_dst, 1
+#endif
+               subf    r_len, %r5, r_len
+
+cb_aligned_w:  /* Cache block align, fill wordwise until dst aligned */
+
+               /* I know I have something to do since we had > 2*CL initially */
+               /* so no need to check for r_len = 0 */
+
+               subi    %r6, %r9, 1             /* CL mask */
+               and.    %r5, r_dst, %r6
+               srwi    %r5, %r5, 2
+               srwi    %r6, %r9, 2
+               beq     cb_aligned_cb           /* already on CL boundary? */
+
+               subf    %r5, %r5, %r6           /* words to fill to alignment */
+               mtctr   %r5
+               slwi    %r5, %r5, 2
+               subf    r_len, %r5, r_len
+
+               subi    r_dst, r_dst, 4
+1:             stwu    r_val, 4(r_dst)         /* Fill wordwise */
+               bdnz    1b
+               addi    r_dst, r_dst, 4
+
+cb_aligned_cb: /* no need to check r_len, see above */
+               
+               srw.    %r5, r_len, %r10                /* Number of cache blocks */
+               mtctr   %r5
+               beq     cblocks_done
+
+               slw     %r5, %r5, %r10
+               subf    r_len, %r5, r_len
+
+1:             dcbz    0, r_dst                /* Clear blockwise */
+               add     r_dst, r_dst, %r9
+               bdnz    1b
+
+cblocks_done:  /* still CL aligned, but less than CL bytes left */
+               cmplwi  cr1, r_len, 0
+               cmplwi  r_len, 8
+               beq-    cr1, sf_return
+
+               blt-    sf_bytewise             /* <8 remaining? */
+               b       sf_aligned_w
+
+/*----------------------------------------------------------------------*/
+wbzero:                li      r_val, 0
+
+               cmplwi  r_len, 0
+               beqlr-                          /* Nothing to do */
+
+simple_fill:
+#if USE_STSWX
+               cmplwi  cr1, r_len, 12          /* < 12 bytes to move? */
+#else
+               cmplwi  cr1, r_len, 8           /* < 8 bytes to move? */
+#endif
+               andi.   %r5, r_dst, 0x03                /* bytes to fill to align4 */
+               blt     cr1, sf_bytewise        /* trivial byte mover */
+
+               li      %r6, 4
+               subf    %r5, %r5, %r6
+               beq+    sf_aligned_w            /* dest is word aligned */
+
+#if USE_STSWX
+               mtxer   %r5
+               stswx   %r0, 0, r_dst
+               add     r_dst, %r5, r_dst
+#else
+               mtctr   %r5                     /* nope, then fill bytewise */
+               subi    r_dst, r_dst, 1         /* until it is */
+1:             stbu    r_val, 1(r_dst)         
+               bdnz    1b
+
+               addi    r_dst, r_dst, 1
+#endif
+               subf    r_len, %r5, r_len
+
+sf_aligned_w:  /* no need to check r_len since it were >= 8 bytes initially */
+#if USE_STSWX
+               mr      %r6, %r0
+               mr      %r7, %r0
+
+               srwi    %r5, r_len, 3
+               mtctr   %r5
+               
+               slwi    %r5, %r5, 3             /* adjust len */
+               subf.   r_len, %r5, r_len
+               
+1:             stswi   %r6, r_dst, 8
+               addi    r_dst, r_dst, 8
+               bdnz    1b
+#else
+               srwi    %r5, r_len, 2           /* words to fill */
+               mtctr   %r5
+
+               slwi    %r5, %r5, 2
+               subf.   r_len, %r5, r_len       /* adjust len for fill */
+
+               subi    r_dst, r_dst, 4
+1:             stwu    r_val, 4(r_dst)
+               bdnz    1b
+               addi    r_dst, r_dst, 4
+#endif
+
+sf_word_done:  bne-    sf_bytewise
+
+sf_return:     mr      %r3, %r8                        /* restore orig ptr */
+               blr                             /* for memset functionality */
+
+sf_bytewise:
+#if USE_STSWX
+               mr      %r5, %r0
+               mr      %r6, %r0
+               mr      %r7, %r0
+               
+               mtxer   r_len
+               stswx   %r5, 0, r_dst
+#else
+               mtctr   r_len
+
+               subi    r_dst, r_dst, 1
+1:             stbu    r_val, 1(r_dst)
+               bdnz    1b
+#endif
+               mr      %r3, %r8                        /* restore orig ptr */
+               blr                             /* for memset functionality */
+END(memset)
+
+/*----------------------------------------------------------------------*/
+#ifndef _KERNEL
+               .data
+cache_info:    .long   -1, -1, -1, -1
+cache_sh:      .long   0
+
+#endif
+/*----------------------------------------------------------------------*/
diff --git a/lib/nbsd_libc/arch/powerpc/sys/__clone.S b/lib/nbsd_libc/arch/powerpc/sys/__clone.S
new file mode 100644 (file)
index 0000000..3ede8dc
--- /dev/null
@@ -0,0 +1,73 @@
+/*     $NetBSD: __clone.S,v 1.4 2011/01/16 02:43:10 matt Exp $ */
+
+/*-
+ * Copyright (c) 2001 Tsubai Masanari.  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.
+ * 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 ``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 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 <sys/errno.h>
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __clone.S,v 1.4 2011/01/16 02:43:10 matt Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(clone, __clone)
+#endif
+
+/*
+ * int __clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+ENTRY(__clone)
+       /*
+        * Sanity checks: func and stack may not be NULL.
+        */
+       cmpwi   %r3,0
+       beq     1f
+       cmpwi   %r4,0
+       beq     1f
+
+       mr      %r7,%r3         /* Save fn in r7. */
+       mr      %r3,%r5
+       _DOSYSCALL(__clone)     /* (flags, stack) */
+       bso     2f              /* error... */
+
+       cmpwi   %r3,0
+       bnelr                   /* We're the parent, just return. */
+
+       mtlr    %r7             /* fn */
+       mr      %r3,%r6         /* arg */
+       blrl                    /* Call the clone's entry point. */
+
+#ifdef PIC
+       PIC_TOCSETUP(__clone, %r30)     /* exit won't return so blow away r30 */
+#endif
+       bl      PIC_PLT(_C_LABEL(_exit))
+
+1:
+       li      %r3,EINVAL
+2:
+       b       _C_LABEL(__cerror)
+END(__clone)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/powerpc/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..71f9740
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.9 2008/04/28 20:22:57 martin Exp $        */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigaction14_sigtramp.c,v 1.9 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+#ifdef __LIBC12_SOURCE__
+extern const int __sigtramp_sigcontext_1[]
+    __weak_reference(__sigtramp_sigcontext_1);
+#endif
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern const int __sigtramp_siginfo_2[];
+
+       /*
+        * If no sigaction, use the "default" trampoline since it won't
+        * be used.
+        */
+       if (act == NULL)
+               return  __sigaction_sigtramp(sig, act, oact, NULL, 0);
+
+#ifdef __LIBC12_SOURCE__
+       /*
+        * We select the non-SA_SIGINFO trampoline if SA_SIGINFO is not
+        * set in the sigaction.
+        */
+       if ((act->sa_flags & SA_SIGINFO) == 0) {
+               int sav = errno;
+               int rv =  __sigaction_sigtramp(sig, act, oact,
+                   __sigtramp_sigcontext_1, 1);
+               if (rv >= 0 || errno != EINVAL)
+                       return rv;
+               errno = sav;
+       }
+#endif
+
+       /*
+        * If SA_SIGINFO was specificed or the compatibility trampolines
+        * can't be used, use the siginfo trampoline.
+        */
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_2, 2);
+}
diff --git a/lib/nbsd_libc/arch/powerpc/sys/__sigtramp2.S b/lib/nbsd_libc/arch/powerpc/sys/__sigtramp2.S
new file mode 100644 (file)
index 0000000..132b347
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: __sigtramp2.S,v 1.3 2011/01/15 07:31:12 matt Exp $     */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigtramp2.S,v 1.3 2011/01/15 07:31:12 matt Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+/*
+ * On entry to user space, stack and registers look like:
+ *
+ *     r3      signal number
+ *     r4      pointer to siginfo structure
+ *     r5      pointer to ucontext structure
+ *     r30     pointer to ucontext structure
+ *     srr0    address of handler
+ *     lr      address of this trampoline
+ *
+ */
+ENTRY_NOPROFILE(__sigtramp_siginfo_2)
+       mr      %r3,%r30                /* restore ucontext pointer */
+       _DOSYSCALL(setcontext)          /* restore machine state */
+       _DOSYSCALL(exit)                /* or exit with errno if failed */
+END(__sigtramp_siginfo_2)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/__syscall.S b/lib/nbsd_libc/arch/powerpc/sys/__syscall.S
new file mode 100644 (file)
index 0000000..d5ac447
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: __syscall.S,v 1.1 2000/12/13 07:50:48 matt Exp $       */
+
+#include "SYS.h"
+
+RSYSCALL(__syscall)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/__vfork14.S b/lib/nbsd_libc/arch/powerpc/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..c2894d0
--- /dev/null
@@ -0,0 +1,16 @@
+/*     $NetBSD: __vfork14.S,v 1.4 2011/01/15 07:31:12 matt Exp $       */
+
+/*
+ * pid = vfork();
+ *
+ * r4 == 0 in parent process, 1 in child process.
+ * r3 == pid of child in parent, pid of parent in child.
+ */
+
+#include "SYS.h"
+
+SYSCALL(__vfork14)
+       addi    %r4,%r4,-1      # from 1 to 0 in child, 0 to -1 in parent
+       and     %r3,%r3,%r4     # return 0 in child, pid in parent
+       blr
+END(__vfork14)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/brk.S b/lib/nbsd_libc/arch/powerpc/sys/brk.S
new file mode 100644 (file)
index 0000000..fff9dd0
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: brk.S,v 1.12 2011/01/16 02:43:10 matt Exp $    */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: brk.S,v 1.12 2011/01/16 02:43:10 matt Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+       .globl  _C_LABEL(__curbrk)
+       .globl  _C_LABEL(__minbrk)
+       .globl  _C_LABEL(_end)
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(brk, _brk)
+#endif
+
+       .data
+_C_LABEL(__minbrk):
+       .long   _C_LABEL(_end)          # XXX not used yet
+
+       .text
+ENTRY(_brk)
+#if defined(PIC)
+       mflr    %r10
+       PIC_GOTSETUP(%r9)
+       mtlr    %r10
+       lwz     %r5,_C_LABEL(_end)@got(%r9)
+#else
+       lis     %r5,_C_LABEL(_end)@ha   # r5 = &_end
+       addi    %r5,%r5,_C_LABEL(_end)@l
+#endif
+       cmplw   %r5,%r3                 # if (&_end <= r3)
+       bgt     0f
+       mr      %r5,%r3                 # r5 = r3
+0:
+       mr      %r3,%r5                 # new break value
+       _DOSYSCALL(break)               # assume, that r5 is kept
+       bso     1f
+#ifdef PIC
+       lwz     %r6,_C_LABEL(__curbrk)@got(%r9)
+       stw     %r5,0(%r6)
+#else
+       lis     %r6,_C_LABEL(__curbrk)@ha       # record new break
+       stw     %r5,_C_LABEL(__curbrk)@l(%r6)
+#endif
+       blr                             # return 0
+
+1:
+       b       _C_LABEL(__cerror)
+END(_brk)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/cerror.S b/lib/nbsd_libc/arch/powerpc/sys/cerror.S
new file mode 100644 (file)
index 0000000..9e86f75
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: cerror.S,v 1.8 2011/01/16 02:43:10 matt Exp $  */
+
+#include "SYS.h"
+#include "assym.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: cerror.S,v 1.8 2011/01/16 02:43:10 matt Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+#ifndef _REENTRANT
+       .globl  _C_LABEL(errno)
+#endif
+#ifdef PIC
+       .hidden _C_LABEL(__cerror)
+#endif
+
+ENTRY(__cerror)
+#ifdef _REENTRANT
+       mflr    %r0
+       stwu    %r1,-CALLFRAMELEN(%r1)          # allocate new stack frame
+       stw     %r0,CALLFRAMELEN+CALLFRAME_LR(%r1)
+#ifdef PIC
+       stw     %r30,CALLFRAME_R30(%r1)
+       PIC_TOCSETUP(__cerror, %r30)
+#endif
+       stw     %r31,CALLFRAME_R31(%r1)
+       mr      %r31,%r3                # stash away in callee-saved register
+       bl      PIC_PLT(_C_LABEL(__errno))
+       stw     %r31,0(%r3)
+       lwz     %r0,CALLFRAMELEN+CALLFRAME_LR(%r1)
+       lwz     %r31,CALLFRAME_R31(%r1)
+#ifdef PIC
+       lwz     %r30,CALLFRAME_R30(%r1)
+#endif
+       mtlr    %r0
+       addi    %r1,%r1,CALLFRAMELEN
+#else
+#ifdef PIC
+       mflr    %r10
+       PIC_GOTSETUP(%r4)
+       lwz     %r4,_C_LABEL(errno)@got(%r4)
+       stw     %r3,0(%r4)
+       mtlr    %r10
+#else
+       lis     %r4,_C_LABEL(errno)@ha
+       stw     %r3,_C_LABEL(errno)@l(%r4)
+#endif /* PIC */
+#endif /* _REENTRANT */
+       li      %r3,-1
+       li      %r4,-1
+       blr
+END(__cerror)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/exect.S b/lib/nbsd_libc/arch/powerpc/sys/exect.S
new file mode 100644 (file)
index 0000000..362cbf6
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: exect.S,v 1.3 1998/05/25 15:28:03 ws Exp $     */
+
+#include "SYS.h"
+
+PSEUDO(exect,execve)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/fork.S b/lib/nbsd_libc/arch/powerpc/sys/fork.S
new file mode 100644 (file)
index 0000000..c442b82
--- /dev/null
@@ -0,0 +1,16 @@
+/*     $NetBSD: fork.S,v 1.6 2011/01/15 07:31:13 matt Exp $    */
+
+/*
+ * pid = fork();
+ *
+ * r4 == 0 in parent process, 1 in child process.
+ * r3 == pid of child in parent, pid of parent in child.
+ */
+
+#include "SYS.h"
+
+_SYSCALL(__fork,fork)
+       addi    %r4,%r4,-1      # from 1 to 0 in child, 0 to -1 in parent
+       and     %r3,%r3,%r4     # return 0 in child, pid in parent
+       blr
+END(__fork)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/getcontext.S b/lib/nbsd_libc/arch/powerpc/sys/getcontext.S
new file mode 100644 (file)
index 0000000..9ebd65b
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: getcontext.S,v 1.5 2011/01/15 07:31:13 matt Exp $      */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+#include "assym.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getcontext.S,v 1.5 2011/01/15 07:31:13 matt Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext, _getcontext)
+#endif
+
+ENTRY(_getcontext)
+       mr      %r5,%r3                         # must save pointer
+       _DOSYSCALL(getcontext)
+       bso     1f
+       mflr    %r4
+       stw     %r4,UC_GREGS_PC(%r5)            # saved pc <- lr
+       stw     %r3,UC_GREGS_R3(%r5)            # arrange for return value 0
+       blr
+1:
+       b       _C_LABEL(__cerror)
+END(_getcontext)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/pipe.S b/lib/nbsd_libc/arch/powerpc/sys/pipe.S
new file mode 100644 (file)
index 0000000..7bce8c7
--- /dev/null
@@ -0,0 +1,23 @@
+/*     $NetBSD: pipe.S,v 1.8 2011/01/15 07:31:13 matt Exp $    */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: pipe.S,v 1.8 2011/01/15 07:31:13 matt Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe, _pipe)
+#endif
+
+ENTRY(_pipe)
+       mr      %r5,%r3         # save pointer
+       _DOSYSCALL(pipe)        # assume, that r5 is kept
+       bso     1f
+       stw     %r3,0(%r5)      # success, store fds
+       stw     %r4,4(%r5)
+       li      %r3,0
+       blr                     # and return 0
+1:
+       b       _C_LABEL(__cerror)
+END(_pipe)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/ptrace.S b/lib/nbsd_libc/arch/powerpc/sys/ptrace.S
new file mode 100644 (file)
index 0000000..3b9571d
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: ptrace.S,v 1.6 2011/01/16 02:43:10 matt Exp $  */
+
+#include "SYS.h"
+#include "assym.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ptrace.S,v 1.6 2011/01/16 02:43:10 matt Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+#define        XCALLFRAMELEN           ((((2+5)*SZREG) + CALLFRAMELEN - 1) & -CALLFRAMELEN)
+#define        XCALLFRAME_DATA         (XCALLFRAMELEN - 1*SZREG)
+#define        XCALLFRAME_ADDR         (XCALLFRAMELEN - 2*SZREG)
+#define        XCALLFRAME_PID          (XCALLFRAMELEN - 3*SZREG)
+#define        XCALLFRAME_REQUEST      (XCALLFRAMELEN - 4*SZREG)
+#define        XCALLFRAME_R30          (XCALLFRAMELEN - 5*SZREG)
+
+ENTRY(ptrace)
+#ifdef _REENTRANT
+       mflr    %r0
+       stw     %r0,CALLFRAME_LR(%r1)
+       stwu    %r1,-XCALLFRAMELEN(%r1)
+       stw     %r3,XCALLFRAME_REQUEST(%r1)
+       stw     %r4,XCALLFRAME_PID(%r1)
+       stw     %r5,XCALLFRAME_ADDR(%r1)
+       stw     %r6,XCALLFRAME_DATA(%r1)
+#ifdef PIC
+       stw     %r30,XCALLFRAME_R30(%r1)
+       PIC_TOCSETUP(ptrace, %r30)
+#endif
+
+       bl      PIC_PLT(_C_LABEL(__errno))
+       li      %r7,0
+       stw     %r7,0(%r3)
+
+#ifdef PIC
+       lwz     %r30,XCALLFRAME_R30(%r1)
+#endif
+       lwz     %r6,XCALLFRAME_DATA(%r1)
+       lwz     %r4,XCALLFRAME_PID(%r1)
+       lwz     %r5,XCALLFRAME_ADDR(%r1)
+       lwz     %r3,XCALLFRAME_REQUEST(%r1)
+       addi    %r1,%r1,XCALLFRAMELEN
+       lwz     %r0,CALLFRAME_LR(%r1)
+       mtlr    %r0
+#else
+#ifdef PIC
+       mflr    %r0
+       PIC_GOTSETUP(%r7)
+       lwz     %r7,_C_LABEL(errno)@got(%r7)
+       li      %r8,0
+       stw     %r8,0(%r7)
+       mtlr    0
+#else
+       lis     %r7,_C_LABEL(errno)@ha
+       li      %r8,0
+       stw     %r8,_C_LABEL(errno)@l(%r7)
+#endif /* PIC */
+#endif /* _REENTRANT */
+       _DOSYSCALL(ptrace)
+       bnslr
+       b       _C_LABEL(__cerror)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/sbrk.S b/lib/nbsd_libc/arch/powerpc/sys/sbrk.S
new file mode 100644 (file)
index 0000000..ad2e257
--- /dev/null
@@ -0,0 +1,41 @@
+/*     $NetBSD: sbrk.S,v 1.11 2011/01/16 02:43:10 matt Exp $   */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sbrk.S,v 1.11 2011/01/16 02:43:10 matt Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+       .globl  _C_LABEL(__curbrk)
+       .globl  _C_LABEL(_end)
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(sbrk, _sbrk)
+#endif
+
+       .data
+_C_LABEL(__curbrk):
+       .long   _C_LABEL(_end)
+       .text
+
+ENTRY(_sbrk)
+#ifdef PIC
+       mflr    %r10
+       PIC_GOTSETUP(%r5)
+       mtlr    %r10
+       lwz     %r5,_C_LABEL(__curbrk)@got(%r5)
+       lwz     %r6,0(%r5)
+#else
+       lis     %r5,_C_LABEL(__curbrk)@ha
+       lwzu    %r6,_C_LABEL(__curbrk)@l(%r5)   # r6 = old break, r5 = &curbrk
+#endif
+       add     %r3,%r3,%r6
+       mr      %r7,%r3                         # r7 = new break
+       _DOSYSCALL(break)                       # break(new_break)
+       bso     1f
+       mr      %r3,%r6                         # set return value
+       stw     %r7,0(%r5)                      # record new break
+       blr
+1:
+       b       _C_LABEL(__cerror)
+END(_sbrk)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/shmat.S b/lib/nbsd_libc/arch/powerpc/sys/shmat.S
new file mode 100644 (file)
index 0000000..b72046b
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: shmat.S,v 1.1 2000/07/07 08:20:53 itohy Exp $  */
+
+#include "SYS.h"
+
+RSYSCALL(shmat)
diff --git a/lib/nbsd_libc/arch/powerpc/sys/syscall.S b/lib/nbsd_libc/arch/powerpc/sys/syscall.S
new file mode 100644 (file)
index 0000000..ffc2259
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: syscall.S,v 1.2 1998/05/25 15:28:04 ws Exp $   */
+
+#include "SYS.h"
+
+RSYSCALL(syscall)
diff --git a/lib/nbsd_libc/arch/powerpc64/Makefile.inc b/lib/nbsd_libc/arch/powerpc64/Makefile.inc
new file mode 100644 (file)
index 0000000..4cf8f63
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/07/07 06:56:34 ross Exp $
+
+KMINCLUDES=
+KMSRCS=        
+
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S
diff --git a/lib/nbsd_libc/arch/powerpc64/SYS.h b/lib/nbsd_libc/arch/powerpc64/SYS.h
new file mode 100644 (file)
index 0000000..7b7c8c1
--- /dev/null
@@ -0,0 +1,43 @@
+/*     $NetBSD: SYS.h,v 1.2 2010/03/22 02:17:23 mrg Exp $      */
+
+#include <machine/asm.h>
+#include <sys/syscall.h>
+
+#ifdef __STDC__
+#define        _DOSYSCALL(x)           li      %r0,(SYS_ ## x)         ;\
+                               sc
+#else
+#define        _DOSYSCALL(x)           li      %r0,(SYS_/**/x)         ;\
+                               sc
+#endif /* __STDC__ */
+
+#define        _SYSCALL_NOERROR(x,y)   .text                           ;\
+                               .align  2                       ;\
+                       ENTRY(x)                                ;\
+                               _DOSYSCALL(y)
+
+#define _SYSCALL(x,y)          .text                           ;\
+                               .align  2                       ;\
+                       2:      b       PIC_PLT(_C_LABEL(__cerror));\
+                               nop                             ;\
+                               _SYSCALL_NOERROR(x,y)           ;\
+                               bso     2b
+
+#define SYSCALL_NOERROR(x)     _SYSCALL_NOERROR(x,x)
+
+#define SYSCALL(x)             _SYSCALL(x,x)
+
+#define PSEUDO_NOERROR(x,y)    _SYSCALL_NOERROR(x,y)           ;\
+                               blr
+
+#define PSEUDO(x,y)            _SYSCALL_NOERROR(x,y)           ;\
+                               bnslr                           ;\
+                               b       PIC_PLT(_C_LABEL(__cerror));\
+                               nop
+
+#define RSYSCALL_NOERROR(x)    PSEUDO_NOERROR(x,x)
+
+#define RSYSCALL(x)            PSEUDO(x,x)
+
+#define        WSYSCALL(weak,strong)   WEAK_ALIAS(weak,strong)         ;\
+                               PSEUDO(strong,weak)
diff --git a/lib/nbsd_libc/arch/powerpc64/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/powerpc64/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..98cc03a
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/07/01 16:37:20 ross Exp $
+
+SRCS+= strtof.c
diff --git a/lib/nbsd_libc/arch/powerpc64/gdtoa/arith.h b/lib/nbsd_libc/arch/powerpc64/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..6ea59e9
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: arith.h,v 1.1 2006/07/01 16:37:20 ross Exp $ */
+
+#define IEEE_BIG_ENDIAN
diff --git a/lib/nbsd_libc/arch/powerpc64/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/powerpc64/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..a37738f
--- /dev/null
@@ -0,0 +1,5 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/07/01 16:37:20 ross Exp $ */
+
+#define f_QNAN 0x7fc00000
+#define d_QNAN0 0x7ff80000
+#define d_QNAN1 0x0
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/Makefile.inc b/lib/nbsd_libc/arch/powerpc64/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..36713d3
--- /dev/null
@@ -0,0 +1,27 @@
+#      $NetBSD: Makefile.inc,v 1.4 2009/12/06 07:12:17 uebayasi Exp $
+
+SRCS+= __setjmp14.S __sigsetjmp14.S _setjmp.S
+SRCS+= bswap16.c bswap32.c bswap64.c
+SRCS+= fabs.c flt_rounds.c
+SRCS+= syncicache.c
+SRCS+=  _lwp.c makecontext.c resumecontext.c swapcontext.S
+
+# Common ieee754 constants and functions
+SRCS+= infinityf_ieee754.c infinity_ieee754.c infinityl_dbl_ieee754.c
+SRCS+= fpclassifyf_ieee754.c fpclassifyd_ieee754.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c
+SRCS+= isfinitef_ieee754.c isfinited_ieee754.c
+SRCS+= signbitf_ieee754.c signbitd_ieee754.c
+
+SRCS+= nanf.c
+
+.if (${MKSOFTFLOAT} == "no")
+SRCS+= fpgetround.c fpsetround.c fpgetmask.c fpsetmask.c
+SRCS+= fpgetsticky.c fpsetsticky.c
+.endif
+
+LSRCS.powerpc.gen=Lint_swapcontext.c
+LSRCS+=                ${LSRCS.powerpc.gen}
+DPSRCS+=       ${LSRCS.powerpc.gen}
+CLEANFILES+=   ${LSRCS.powerpc.gen}
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/__setjmp14.S b/lib/nbsd_libc/arch/powerpc64/gen/__setjmp14.S
new file mode 100644 (file)
index 0000000..f4b6af1
--- /dev/null
@@ -0,0 +1,101 @@
+/*     $NetBSD: __setjmp14.S,v 1.2 2009/03/08 18:57:12 he Exp $        */
+
+#include <sys/syscall.h>
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       .text
+       .asciz "$NetBSD: __setjmp14.S,v 1.2 2009/03/08 18:57:12 he Exp $"
+#endif
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v?v:1)" from the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(__setjmp14)
+       mr      %r6,%r3
+       li      %r3,1                   # SIG_BLOCK
+       li      %r4,0
+       addi    %r5,%r6,100             # &sigmask
+       li      %r0,SYS___sigprocmask14
+       sc                              # assume no error       XXX
+       mflr    %r11
+       mfcr    %r12
+       mr      %r10,%r1
+       mr      %r9,%r2
+
+       std     %r8,8(%r6)              # save r8-r31
+       std     %r9,16(%r6)
+       std     %r10,24(%r6)
+       std     %r11,32(%r6)
+       std     %r12,40(%r6)
+       std     %r13,48(%r6)
+       std     %r14,56(%r6)
+       std     %r15,64(%r6)
+       std     %r16,72(%r6)
+       std     %r17,80(%r6)
+       std     %r18,88(%r6)
+       std     %r19,96(%r6)
+       std     %r20,104(%r6)
+       std     %r21,112(%r6)
+       std     %r22,120(%r6)
+       std     %r23,128(%r6)
+       std     %r24,136(%r6)
+       std     %r25,144(%r6)
+       std     %r26,152(%r6)
+       std     %r27,160(%r6)
+       std     %r28,168(%r6)
+       std     %r29,176(%r6)
+       std     %r30,184(%r6)
+       std     %r31,192(%r6)
+
+       li      %r3,0
+       blr
+
+ENTRY(__longjmp14)
+       ld      %r8,8(%r6)              # load r8-r31
+       ld      %r9,16(%r6)
+       ld      %r10,24(%r6)
+       ld      %r11,32(%r6)
+       ld      %r12,40(%r6)
+       ld      %r13,48(%r6)
+       ld      %r14,56(%r6)
+       ld      %r15,64(%r6)
+       ld      %r16,72(%r6)
+       ld      %r17,80(%r6)
+       ld      %r18,88(%r6)
+       ld      %r19,96(%r6)                               
+       ld      %r20,104(%r6)
+       ld      %r21,112(%r6)
+       ld      %r22,120(%r6)
+       ld      %r23,128(%r6)
+       ld      %r24,136(%r6)
+       ld      %r25,144(%r6)
+       ld      %r26,152(%r6)
+       ld      %r27,160(%r6)
+       ld      %r28,168(%r6)
+       ld      %r29,176(%r6)
+       ld      %r30,184(%r6)
+       ld      %r31,192(%r6)
+
+       mr      %r6,%r4
+       mtlr    %r11
+       mtcr    %r12
+       mr      %r2,%r9
+       mr      %r1,%r10
+       addi    %r4,%r3,100             # &sigmask
+       li      %r3,3                   # SIG_SETMASK
+       li      %r5,0
+       li      %r0,SYS___sigprocmask14
+       sc                              # assume no error       XXX
+       or.     %r3,%r6,%r6
+       bnelr
+       li      %r3,1
+       blr
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/__sigsetjmp14.S b/lib/nbsd_libc/arch/powerpc64/gen/__sigsetjmp14.S
new file mode 100644 (file)
index 0000000..cb6d974
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: __sigsetjmp14.S,v 1.2 2010/03/22 01:39:11 mrg Exp $    */
+
+#include <sys/syscall.h>
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       .text
+       .asciz "$NetBSD: __sigsetjmp14.S,v 1.2 2010/03/22 01:39:11 mrg Exp $"
+#endif
+
+ENTRY(__sigsetjmp14)
+       mr      %r6,%r3
+       or.     %r7,%r4,%r4
+       beq     1f
+       li      %r3,1                   # SIG_BLOCK
+       li      %r4,0
+       addi    %r5,%r6,100             # &sigmask
+       li      %r0,SYS___sigprocmask14
+       sc                              # assume no error       XXX
+1:
+       mflr    %r11
+       mfcr    %r12
+       mr      %r10,%r1
+       mr      %r9,%r2
+       i = 0
+       .rept   32-7
+       std     7+i,i*8(%r6)            # save r7-r31
+       i = i + 1
+       .endr
+       li      %r3,0
+       blr
+
+ENTRY(__siglongjmp14)
+       i = 0
+       .rept   32-7
+       ld      7+i,i*8(%r3)            # load r7-r31
+       i = i + 1
+       .endr
+       mr      %r6,%r4
+       mtlr    %r11
+       mtcr    %r12
+       mr      %r2,%r9
+       mr      %r1,%r10
+       or.     %r7,%r7,%r7
+       beq     1f
+       addi    %r4,%r3,100             # &sigmask
+       li      %r3,3                   # SIG_SETMASK
+       li      %r5,0
+       li      %r0,SYS___sigprocmask14
+       sc                              # assume no error       XXX
+1:
+       or.     %r3,%r6,%r6
+       bnelr
+       li      %r3,1
+       blr
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/_lwp.c b/lib/nbsd_libc/arch/powerpc64/gen/_lwp.c
new file mode 100644 (file)
index 0000000..406f743
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: _lwp.c,v 1.2 2006/07/05 18:05:45 ross Exp $    */
+
+/*
+ * Copyright (c) 2001 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Allen Briggs for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.2 2006/07/05 18:05:45 ross Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+
+void
+_lwp_makecontext(ucontext_t *u, void (*start)(void *), void *arg,
+       void *private, caddr_t stack_base, size_t stack_size)
+{
+       void    **sp;
+
+       getcontext(u);
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+
+       sp = (void **) (stack_base + stack_size);
+
+       u->uc_mcontext.__gregs[3] = (__greg_t) arg;             /* arg1 */
+       u->uc_mcontext.__gregs[1] = ((__greg_t) sp) - 112;      /* stack */
+       u->uc_mcontext.__gregs[33] = (__greg_t) _lwp_exit;      /* LR */
+       u->uc_mcontext.__gregs[34] = (__greg_t) start;  /* PC */
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/_setjmp.S b/lib/nbsd_libc/arch/powerpc64/gen/_setjmp.S
new file mode 100644 (file)
index 0000000..3d8da04
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: _setjmp.S,v 1.2 2006/07/05 18:06:47 ross Exp $ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       .text
+       .asciz "$NetBSD: _setjmp.S,v 1.2 2006/07/05 18:06:47 ross Exp $"
+#endif
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     _longjmp(a,v)
+ * will generate a "return(v?v:1)" from the last call to
+ *     _setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is NOT restored.
+ */
+
+ENTRY(_setjmp)
+       mflr    %r11                    /* save return address */
+       mfcr    %r12                    /* save condition register */
+       mr      %r10,%r1                /* save stack pointer */
+       mr      %r9,%r2                 /* save GPR2 (not needed) */
+       i = 0
+       .rept   32-9
+       std     9+i,i*8+16(%r3)
+       i = i + 1
+       .endr
+       li      %r3,0                   /* indicate success */
+       blr                             /* return */
+
+ENTRY(_longjmp)
+       i = 0
+       .rept   32-9
+       ld      9+i,i*8+16(%r3)
+       i = i + 1
+       .endr
+       mtlr    %r11                    /* restore LR */
+       mtcr    %r12                    /* restore CR */
+       mr      %r2,%r9                 /* restore GPR2 (not needed) */
+       mr      %r1,%r10                /* restore stack */
+       or.     %r3,%r4,%r4             /* get return value */
+       bnelr                           /* return if not 0 */
+       li      %r3,1                   /* what's the point? */
+       blr                             /* return */
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/fabs.c b/lib/nbsd_libc/arch/powerpc64/gen/fabs.c
new file mode 100644 (file)
index 0000000..4cc21a9
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: fabs.c,v 1.2 2006/07/05 18:07:22 ross Exp $    */
+
+#include <math.h>
+
+double
+fabs(double x)
+{
+#ifdef _SOFT_FLOAT
+       if (x < 0)
+               x = -x;
+#else
+       __asm volatile("fabs %0,%1" : "=f"(x) : "f"(x));
+#endif
+       return (x);
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/flt_rounds.c b/lib/nbsd_libc/arch/powerpc64/gen/flt_rounds.c
new file mode 100644 (file)
index 0000000..13834cb
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: flt_rounds.c,v 1.1 2006/07/01 16:37:20 ross Exp $      */
+
+/*
+ * Copyright (c) 1996 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Mark Brinicombe
+ *     for the NetBSD Project.
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: flt_rounds.c,v 1.1 2006/07/01 16:37:20 ross Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <ieeefp.h>
+#include <float.h>
+#include <stdint.h>
+#include <powerpc/fpu.h>
+
+static const int map[] = {
+       1,      /* round to nearest */
+       0,      /* round to zero */
+       2,      /* round to positive infinity */
+       3       /* round to negative infinity */
+};
+
+int
+__flt_rounds(void)
+{
+#ifdef _SOFT_FLOAT
+       return map[fpgetround()];
+#else
+       uint64_t fpscr;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       return map[((uint32_t)fpscr & FPSCR_RN)];
+#endif
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/fpgetmask.c b/lib/nbsd_libc/arch/powerpc64/gen/fpgetmask.c
new file mode 100644 (file)
index 0000000..5e44e33
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: fpgetmask.c,v 1.2 2008/04/28 20:22:57 martin Exp $     */
+
+/*
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dan Winship.
+ * 
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetmask.c,v 1.2 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+#include <powerpc/fpu.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetmask,_fpgetmask)
+#endif
+
+#define        MASKBITS        (FPSCR_VE|FPSCR_OE|FPSCR_UE|FPSCR_ZE|FPSCR_XE)
+#define        MASKSHFT        3
+
+fp_except
+fpgetmask(void)
+{
+       uint64_t fpscr;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       return (((uint32_t)fpscr & MASKBITS) >> MASKSHFT);
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/fpgetround.c b/lib/nbsd_libc/arch/powerpc64/gen/fpgetround.c
new file mode 100644 (file)
index 0000000..8cc346e
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: fpgetround.c,v 1.2 2008/04/28 20:22:57 martin Exp $    */
+
+/*
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dan Winship.
+ * 
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetround.c,v 1.2 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+#include <powerpc/fpu.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetround,_fpgetround)
+#endif
+
+#define        ROUNDBITS       FPSCR_RN
+#define        ROUNDSHFT       0
+
+fp_rnd
+fpgetround(void)
+{
+       uint64_t fpscr;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       return (((uint32_t)fpscr & ROUNDBITS) >> ROUNDSHFT);
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/fpgetsticky.c b/lib/nbsd_libc/arch/powerpc64/gen/fpgetsticky.c
new file mode 100644 (file)
index 0000000..f46aa83
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: fpgetsticky.c,v 1.2 2008/04/28 20:22:57 martin Exp $   */
+
+/*
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dan Winship.
+ * 
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetsticky.c,v 1.2 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+#include <powerpc/fpu.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetsticky,_fpgetsticky)
+#endif
+
+#define        STICKYBITS      (FPSCR_XX|FPSCR_ZX|FPSCR_UX|FPSCR_OX|FPSCR_VX)
+#define        STICKYSHFT      25
+
+fp_except
+fpgetsticky(void)
+{
+       uint64_t fpscr;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       return (((uint32_t)fpscr & STICKYBITS) >> STICKYSHFT);
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/fpsetmask.c b/lib/nbsd_libc/arch/powerpc64/gen/fpsetmask.c
new file mode 100644 (file)
index 0000000..0ede254
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: fpsetmask.c,v 1.2 2008/04/28 20:22:57 martin Exp $     */
+
+/*
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dan Winship.
+ * 
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetmask.c,v 1.2 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+#include <powerpc/fpu.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetmask,_fpsetmask)
+#endif
+
+#define        MASKBITS        (FPSCR_XE|FPSCR_ZE|FPSCR_UE|FPSCR_OE|FPSCR_VE)
+#define        MASKSHFT        3
+
+fp_except
+fpsetmask(fp_except mask)
+{
+       uint64_t fpscr;
+       fp_except old;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       old = ((uint32_t)fpscr & MASKBITS) >> MASKSHFT;
+       fpscr &= ~MASKBITS;
+       fpscr |= ((uint32_t)mask << MASKSHFT) & MASKBITS;
+       __asm volatile("mtfsf 0xff,%0" :: "f"(fpscr));
+       return (old);
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/fpsetround.c b/lib/nbsd_libc/arch/powerpc64/gen/fpsetround.c
new file mode 100644 (file)
index 0000000..90fe829
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: fpsetround.c,v 1.2 2008/04/28 20:22:57 martin Exp $    */
+
+/*
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dan Winship.
+ * 
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetround.c,v 1.2 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+#include <powerpc/fpu.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetround,_fpsetround)
+#endif
+
+#define        ROUNDBITS       FPSCR_RN
+
+fp_rnd
+fpsetround(fp_rnd rnd_dir)
+{
+       uint64_t fpscr;
+       fp_rnd old;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       old = (uint32_t)fpscr & ROUNDBITS;
+       fpscr &= ~ROUNDBITS;
+       fpscr |= rnd_dir & ROUNDBITS;
+       __asm volatile("mtfsf 0xff,%0" :: "f"(fpscr));
+       return (old);
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/fpsetsticky.c b/lib/nbsd_libc/arch/powerpc64/gen/fpsetsticky.c
new file mode 100644 (file)
index 0000000..30e1bd8
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: fpsetsticky.c,v 1.2 2008/04/28 20:22:57 martin Exp $   */
+
+/*
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dan Winship.
+ * 
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetsticky.c,v 1.2 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <ieeefp.h>
+#include <powerpc/fpu.h>
+
+#define        STICKYBITS      (FPSCR_XX|FPSCR_ZX|FPSCR_UX|FPSCR_OX|FPSCR_VX)
+#define        INVBITS         (FPSCR_VXCVI|FPSCR_VXSQRT|FPSCR_VXSOFT|FPSCR_VXVC|\
+                        FPSCR_VXIMZ|FPSCR_VXZDZ|FPSCR_VXIDI|FPSCR_VXISI|\
+                        FPSCR_VXSNAN)
+#define        STICKYSHFT      25
+
+#ifdef __weak_alias
+__weak_alias(fpsetsticky,_fpsetsticky)
+#endif
+
+fp_except
+fpsetsticky(fp_except mask)
+{
+       uint64_t fpscr;
+       fp_except old;
+
+       __asm volatile("mffs %0" : "=f"(fpscr));
+       old = ((uint32_t)fpscr & STICKYBITS) >> STICKYSHFT;
+       /*
+        * FPSCR_VX (aka FP_X_INV) is not a sticky bit but a summary of the
+        * all the FPSCR_VX* sticky bits.  So when FP_X_INV is cleared then
+        * clear all of those bits, likewise when it's set, set them all.
+        */
+       if ((mask & FP_X_INV) == 0)
+               fpscr &= ~INVBITS;
+       else 
+               fpscr |= INVBITS;
+       fpscr &= ~STICKYBITS;
+       fpscr |= ((uint32_t)mask << STICKYSHFT) & STICKYBITS;
+       /*
+        * Make FPSCR_FX reflect the presence of a set sticky bit (or not).
+        */
+       if (fpscr & (STICKYBITS|INVBITS))
+               fpscr |= FPSCR_FX;
+       else
+               fpscr &= ~FPSCR_FX;
+       /*
+        * Write back the fpscr.
+        */
+       __asm volatile("mtfsf 0xff,%0" :: "f"(fpscr));
+       return (old);
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/makecontext.c b/lib/nbsd_libc/arch/powerpc64/gen/makecontext.c
new file mode 100644 (file)
index 0000000..fbfe1ec
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: makecontext.c,v 1.3 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.3 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include <inttypes.h>
+#include <stddef.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#if __STDC__
+#include <stdarg.h>
+#else
+#include <varargs.h>
+#endif
+
+void
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+{
+       __greg_t *gr = ucp->uc_mcontext.__gregs;
+       __greg_t sp, *spp;
+       int i;
+       va_list ap;
+
+       sp  = (__greg_t) ((uintptr_t)ucp->uc_stack.ss_sp
+           + ucp->uc_stack.ss_size);
+       sp -= 2 + (argc > 8 ? argc - 8: 0); /* Make room for call frame. */
+       sp  = (__greg_t) ((uintptr_t)sp & ~0xf);
+
+       /*
+        * Start executing at <func> -- when <func> completes, return to
+        * <_resumecontext>.
+        */
+       gr[_REG_R1]  = sp;
+       gr[_REG_LR] = (__greg_t)_resumecontext;
+       gr[_REG_PC] = (__greg_t)func; // XXX -- this is the descriptor address!
+
+       /* Wipe out stack frame backchain pointer. */
+       spp = (__greg_t *)sp;
+       *spp = 0;
+
+       /* Construct argument list. */
+       va_start(ap, argc);
+       /* Up to the first eight arguments are passed in r3-10. */
+       for (i = 0; i < argc && i < 8; i++)
+               gr[_REG_R3 + i] = va_arg(ap, long);
+       /* Pass remaining arguments on the stack above the backchain/lr gap. */
+       for (spp += 2; i < argc; i++)
+               *spp++ = va_arg(ap, long);
+       va_end(ap);
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/nanf.c b/lib/nbsd_libc/arch/powerpc64/gen/nanf.c
new file mode 100644 (file)
index 0000000..5007de7
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: nanf.c,v 1.2 2009/02/22 01:34:02 martin Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nanf.c,v 1.2 2009/02/22 01:34:02 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+/* bytes for quiet NaN (IEEE single precision) */
+const union __float_u __nanf =
+               { { 0x7f, 0xc0,    0,    0 } };
+
+__warn_references(__nanf, "warning: <math.h> defines NAN incorrectly for your compiler.")
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/resumecontext.c b/lib/nbsd_libc/arch/powerpc64/gen/resumecontext.c
new file mode 100644 (file)
index 0000000..7baafea
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: resumecontext.c,v 1.3 2008/04/28 20:22:57 martin Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: resumecontext.c,v 1.3 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "extern.h"
+
+void
+_resumecontext()
+{
+       ucontext_t uct;
+
+       (void)getcontext(&uct);
+       if (uct.uc_link == NULL) 
+               exit(0);
+       (void)setcontext(uct.uc_link);
+       _exit(-1);
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/swapcontext.S b/lib/nbsd_libc/arch/powerpc64/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..a3d7b9c
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: swapcontext.S,v 1.3 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       .text
+       .asciz "$NetBSD: swapcontext.S,v 1.3 2008/04/28 20:22:57 martin Exp $"
+#endif /* LIBC_SCCS && !lint */
+
+ENTRY(swapcontext)
+       mc_off  = 56                            # offset of uc_mcontext
+       stdu    %r1,-SF_SZ(%r1)                 # set up new stack frame
+       mflr    %r0
+       std     %r0,[SF_SZ+SF_LR](%r1)          # save link register
+       std     %r3,SF_PARAM(%r1)               # must save oucp (was 8)
+       std     %r4,SF_PARAM+8(%r1)             # must save ucp (was 12)
+       bl      ._getcontext                    # getcontext(oucp)
+       nop
+       cmpdi   %r3,0
+       bne     1f
+       ld      %r11,SF_PARAM(%r1)              # load oucp for adjustment
+       ld      %r0,SF_SZ+SF_LR(%r1)            # get LR back
+       std     %r0,mc_off+34*8(%r11)   #       pc <- lr
+       la      %r0,16(%r1)
+       std     %r0,mc_off+1*8(%r11)            # adjust sp
+       ld      %r3,SF_PARAM+8(%r1)                     # load ucp
+       bl      .setcontext                     # setcontext(ucp)
+       nop
+1:
+       ld      %r0,SF_SZ+SF_LR(%r1)
+       mtlr    %r0
+       la      %r1,SF_SZ(%r1)
+       blr
diff --git a/lib/nbsd_libc/arch/powerpc64/gen/syncicache.c b/lib/nbsd_libc/arch/powerpc64/gen/syncicache.c
new file mode 100644 (file)
index 0000000..2e73ae7
--- /dev/null
@@ -0,0 +1,138 @@
+/*     $NetBSD: syncicache.c,v 1.1 2006/07/01 16:37:20 ross Exp $      */
+
+/*
+ * Copyright (C) 1995-1997, 1999 Wolfgang Solfrank.
+ * Copyright (C) 1995-1997, 1999 TooLs GmbH.
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by TooLs GmbH.
+ * 4. The name of TooLs GmbH may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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 <sys/param.h>
+#if    defined(_KERNEL) || defined(_STANDALONE)
+#include <sys/time.h>
+#include <sys/proc.h>
+#include <uvm/uvm_extern.h>
+#endif
+#include <sys/sysctl.h>
+
+#include <machine/cpu.h>
+
+
+#if defined(_STANDALONE)
+#ifndef        CACHELINESIZE
+#error "Must know the size of a cache line"
+#endif
+static struct cache_info _cache_info = {
+       CACHELINESIZE,
+       CACHELINESIZE,
+       CACHELINESIZE,
+       CACHELINESIZE
+};
+#define CACHEINFO      _cache_info
+#elif defined(_KERNEL)
+#define        CACHEINFO       (curcpu()->ci_ci)
+#else
+#include <stdlib.h>
+
+size_t __getcachelinesize (void);
+
+static int _cachelinesize = 0;
+
+static struct cache_info _cache_info;
+#define CACHEINFO      _cache_info
+
+size_t
+__getcachelinesize(void)
+{
+       static int cachemib[] = { CTL_MACHDEP, CPU_CACHELINE };
+       static int cacheinfomib[] = { CTL_MACHDEP, CPU_CACHEINFO };
+       size_t clen = sizeof(_cache_info);
+
+       if (_cachelinesize)
+               return _cachelinesize;
+
+       if (sysctl(cacheinfomib, sizeof(cacheinfomib) / sizeof(cacheinfomib[0]),
+               &_cache_info, &clen, NULL, 0) == 0) {
+               _cachelinesize = _cache_info.dcache_line_size;
+               return _cachelinesize;
+       }
+
+       /* Try older deprecated sysctl */
+       clen = sizeof(_cachelinesize);
+       if (sysctl(cachemib, sizeof(cachemib) / sizeof(cachemib[0]),
+                  &_cachelinesize, &clen, NULL, 0) < 0
+           || !_cachelinesize)
+               abort();
+
+       _cache_info.dcache_size = _cachelinesize;
+       _cache_info.dcache_line_size = _cachelinesize;
+       _cache_info.icache_size = _cachelinesize;
+       _cache_info.icache_line_size = _cachelinesize;
+
+       /* If there is no cache, indicate we have issued the sysctl. */
+       if (!_cachelinesize)
+               _cachelinesize = 1;
+
+       return _cachelinesize;
+}
+#endif
+
+void
+__syncicache(void *from, size_t len)
+{
+       size_t l, off;
+       size_t linesz;
+       char *p;
+
+#if    !defined(_KERNEL) && !defined(_STANDALONE)
+       if (!_cachelinesize)
+               __getcachelinesize();
+#endif 
+
+       if (CACHEINFO.dcache_size > 0) {
+               linesz = CACHEINFO.dcache_line_size;
+               off = (uintptr_t)from & (linesz - 1);
+               l = (len + off + linesz - 1) & ~(linesz - 1);
+               p = (char *)from - off;
+               do {
+                       __asm volatile ("dcbst 0,%0" :: "r"(p));
+                       p += linesz;
+               } while ((l -= linesz) != 0);
+       }
+       __asm volatile ("sync");
+
+       if (CACHEINFO.icache_size > 0 ) {
+               linesz = CACHEINFO.icache_line_size;
+               off = (uintptr_t)from & (linesz - 1);
+               l = (len + off + linesz - 1) & ~(linesz - 1);
+               p = (char *)from - off;
+               do {
+                       __asm volatile ("icbi 0,%0" :: "r"(p));
+                       p += linesz;
+               } while ((l -= linesz) != 0);
+       }
+       __asm volatile ("sync; isync");
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/net/Makefile.inc b/lib/nbsd_libc/arch/powerpc64/net/Makefile.inc
new file mode 100644 (file)
index 0000000..74baf83
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/07/01 16:37:20 ross Exp $
+
+SRCS+= htonl.c htons.c ntohl.c ntohs.c
diff --git a/lib/nbsd_libc/arch/powerpc64/stdlib/Makefile.inc b/lib/nbsd_libc/arch/powerpc64/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..f12f78d
--- /dev/null
@@ -0,0 +1 @@
+#      $NetBSD: Makefile.inc,v 1.3 2009/07/31 20:40:00 dsl Exp $
diff --git a/lib/nbsd_libc/arch/powerpc64/string/Makefile.inc b/lib/nbsd_libc/arch/powerpc64/string/Makefile.inc
new file mode 100644 (file)
index 0000000..b724ef5
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.6 2009/08/11 17:30:43 dsl Exp $
+
+SRCS+= bzero.S ffs.S strlen.S
+NO_SRCS+= memset.S
diff --git a/lib/nbsd_libc/arch/powerpc64/string/bzero.S b/lib/nbsd_libc/arch/powerpc64/string/bzero.S
new file mode 100644 (file)
index 0000000..096725f
--- /dev/null
@@ -0,0 +1,100 @@
+/*     $NetBSD: bzero.S,v 1.4 2008/04/28 20:22:57 martin Exp $ */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Ross Harvey.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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       <machine/asm.h>
+
+       .file   "bzero.c"
+ENTRY(bzero)
+       mr      5, 4            # translate to memcpy signature
+       li      4, 0            # add missing memcpy param
+ENTRY(memset)
+       cmpldi  7, 5, 7         # only optimize if len >= 8
+       mr      9, 3
+       ble     7, 2f
+       rldicl. 0, 3, 0, 61     # only optimize if aligned
+       beq     0, 4f
+2:
+       cmpdi   7, 5, 0 
+       beqlr   7
+3:
+       mtctr   5
+       rldicl  0, 4, 0, 56
+       .p2align 4,, 15
+2:
+       stb     0, 0(9)         # byte-at-a-time loop
+       addi    9, 9, 1
+       bdnz    2b
+       blr                     # done
+4:
+       rldicl  4, 4, 0, 56     # construct parallel store
+       cmpldi  7, 5, 31
+       mr      10, 3
+       sldi    0, 4, 8
+       or      0, 0, 4
+       sldi    9, 0, 16
+       or      0, 0, 9
+       sldi    11, 0, 32
+       or      0, 0, 11
+       ble     7, 5f
+       addi    9, 5, -32
+       srdi    9, 9, 5
+       addi    9, 9, 1
+       mtctr   9
+       .p2align 4,, 15
+2:
+       std     0, 0(10)        # 8-way + unrolled store loop
+       std     0, 8(10)
+       addi    5, 5, -32       # schedule count decrement
+       std     0, 16(10)
+       std     0, 24(10)
+       addi    10, 10, 32
+       bdnz    2b
+       cmpldi  7, 5, 7
+       ble     7, 8f
+5:
+       addi    9, 5, -8
+       srdi    9, 9, 3
+       addi    9, 9, 1
+       mtctr   9
+       .p2align 4,, 15
+14:
+       std     0, 0(10)        # 8-way not-unrolled loop
+       addi    5, 5, -8
+       addi    10, 10, 8
+       bdnz    14b
+8:
+       cmpdi   7, 5, 0
+       mr      9, 10
+       bne     7, 3b
+       blr
+       .long   0
+       .byte   0, 0, 0, 0, 0, 0, 0, 0
+       .size   .memset, .-.memset
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/Makefile.inc b/lib/nbsd_libc/arch/powerpc64/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..7d5f094
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/07/07 06:40:45 ross Exp $
+
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/__clone.S b/lib/nbsd_libc/arch/powerpc64/sys/__clone.S
new file mode 100644 (file)
index 0000000..46e9806
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: __clone.S,v 1.1 2006/07/01 16:37:20 ross Exp $ */
+
+/*-
+ * Copyright (c) 2001 Tsubai Masanari.  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.
+ * 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 ``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 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 <sys/errno.h>
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(clone, __clone)
+#endif
+
+/*
+ * int __clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+ENTRY(__clone)
+       /*
+        * Sanity checks: func and stack may not be NULL.
+        */
+       cmpdi   %r3,0
+       beq     1f
+       cmpdi   %r4,0
+       beq     1f
+
+       mr      %r7,%r3         /* Save fn in r7. */
+       mr      %r3,%r5
+       li      %r0,SYS___clone /* (flags, stack) */
+       sc
+       bso     2f              /* error... */
+
+       cmpdi   %r3,0
+       bnelr                   /* We're the parent, just return. */
+
+       mtlr    %r7             /* fn */
+       mr      %r3,%r6         /* arg */
+       blrl                    /* Call the clone's entry point. */
+
+       bl      PIC_PLT(_C_LABEL(_exit))
+
+1:
+       li      %r3,EINVAL
+2:
+       b       PIC_PLT(_C_LABEL(__cerror))
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/powerpc64/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..092c2bc
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.2 2008/04/28 20:22:57 martin Exp $        */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigaction14_sigtramp.c,v 1.2 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+#ifdef __LIBC12_SOURCE__
+extern const int __sigtramp_sigcontext_1[]
+    __weak_reference(__sigtramp_sigcontext_1);
+#endif
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern const int __sigtramp_siginfo_2[];
+
+       /*
+        * If no sigaction, use the "default" trampoline since it won't
+        * be used.
+        */
+       if (act == NULL)
+               return  __sigaction_sigtramp(sig, act, oact, NULL, 0);
+
+#ifdef __LIBC12_SOURCE__
+       /*
+        * We select the non-SA_SIGINFO trampoline if SA_SIGINFO is not
+        * set in the sigaction.
+        */
+       if ((act->sa_flags & SA_SIGINFO) == 0) {
+               int sav = errno;
+               int rv =  __sigaction_sigtramp(sig, act, oact,
+                   __sigtramp_sigcontext_1, 1);
+               if (rv >= 0 || errno != EINVAL)
+                       return rv;
+               errno = sav;
+       }
+#endif
+
+       /*
+        * If SA_SIGINFO was specificed or the compatibility trampolines
+        * can't be used, use the siginfo trampoline.
+        */
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_2, 2);
+}
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/__sigtramp2.S b/lib/nbsd_libc/arch/powerpc64/sys/__sigtramp2.S
new file mode 100644 (file)
index 0000000..e43c4d4
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: __sigtramp2.S,v 1.3 2011/01/17 08:23:54 matt Exp $     */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+/*
+ * On entry to user space, stack and registers look like:
+ *
+ *     r3      signal number
+ *     r4      pointer to siginfo structure
+ *     r5      pointer to ucontext structure
+ *     r30     pointer to ucontext structure
+ *     srr0    address of handler
+ *     lr      address of this trampoline
+ *
+ */
+ENTRY_NOPROFILE(__sigtramp_siginfo_2)
+       mr      %r3,%r30                /* restore ucontext pointer */
+       _DOSYSCALL(setcontext)          /* restore machine state */
+       _DOSYSCALL(exit)                /* or exit with errno if failed */
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/__syscall.S b/lib/nbsd_libc/arch/powerpc64/sys/__syscall.S
new file mode 100644 (file)
index 0000000..076066d
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: __syscall.S,v 1.1 2006/07/01 16:37:20 ross Exp $       */
+
+#include "SYS.h"
+
+RSYSCALL(__syscall)
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/__vfork14.S b/lib/nbsd_libc/arch/powerpc64/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..1b1469f
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: __vfork14.S,v 1.1 2006/07/06 17:04:22 ross Exp $       */
+
+/*
+ * pid = vfork();
+ *
+ * r4 == 0 in parent process, 1 in child process.
+ * r3 == pid of child in parent, pid of parent in child.
+ */
+
+#include "SYS.h"
+
+SYSCALL(__vfork14)
+       addi    %r4,%r4,-1      # from 1 to 0 in child, 0 to -1 in parent
+       and     %r3,%r3,%r4     # return 0 in child, pid in parent
+       blr
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/brk.S b/lib/nbsd_libc/arch/powerpc64/sys/brk.S
new file mode 100644 (file)
index 0000000..6eb574d
--- /dev/null
@@ -0,0 +1,40 @@
+/*     $NetBSD: brk.S,v 1.3 2006/07/07 06:50:06 ross Exp $     */
+
+#include "SYS.h"
+
+       .globl  _C_LABEL(__curbrk)
+       .globl  _C_LABEL(__minbrk)
+       .globl  _C_LABEL(_end)
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(brk, _brk)
+#endif
+
+       .macro  LdAddr  r,sym
+       .pushsection    ".toc","aw"
+100:   .tc \sym[TC],\sym
+       .popsection
+       ld      \r,100b@toc(2)
+       .endm
+
+        .data
+_C_LABEL(__minbrk):
+       .long   _C_LABEL(_end)      
+       .text
+
+ENTRY(_brk)
+       LdAddr  %r5,_end
+       cmpld   %r5,%r3                 # if (&_end <= r3)
+       bgt     0f
+       mr      %r5,%r3                 # r5 = r3
+0:
+       mr      %r3,%r5                 # new break value
+       li      %r0,SYS_break
+       sc                              # assume, that r5 is kept
+       bso     1f
+       LdAddr  %r6,__curbrk
+       std     %r5,0(%r6)
+       blr                             # return 0
+
+1:
+       b       .__cerror
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/cerror.S b/lib/nbsd_libc/arch/powerpc64/sys/cerror.S
new file mode 100644 (file)
index 0000000..e360b69
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: cerror.S,v 1.1 2006/07/01 16:37:20 ross Exp $  */
+
+#include <machine/asm.h>
+#include "SYS.h"
+
+#ifndef _REENTRANT
+       .globl  _C_LABEL(errno)
+#endif
+
+ENTRY(__cerror)
+#ifdef _REENTRANT
+       mflr    %r0
+       stwu    %r1,-16(%r1)            # allocate new stack frame
+       stw     %r0,20(%r1)
+       stw     %r31,8(%r1)
+       mr      %r31,%r3                # stash away in callee-saved register
+       bl      PIC_PLT(_C_LABEL(__errno))
+       stw     %r31,0(%r3)
+       lwz     %r0,20(%r1)
+       lwz     %r31,8(%r1)
+       mtlr    %r0
+       la      %r1,16(%r1)
+#else
+#ifdef PIC
+       mflr    %r10
+       bl      _GLOBAL_OFFSET_TABLE_@local-4
+       mflr    %r4
+       lwz     %r4,_C_LABEL(errno)@got(%r4)
+       stw     %r3,0(%r4)
+       mtlr    %r10
+#else
+       lis     %r4,_C_LABEL(errno)@ha
+       stw     %r3,_C_LABEL(errno)@l(%r4)
+#endif /* PIC */
+#endif /* _REENTRANT */
+       li      %r3,-1
+       li      %r4,-1
+       blr
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/exect.S b/lib/nbsd_libc/arch/powerpc64/sys/exect.S
new file mode 100644 (file)
index 0000000..1972309
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: exect.S,v 1.1 2006/07/01 16:37:20 ross Exp $   */
+
+#include "SYS.h"
+
+PSEUDO(exect,execve)
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/fork.S b/lib/nbsd_libc/arch/powerpc64/sys/fork.S
new file mode 100644 (file)
index 0000000..0e1b658
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: fork.S,v 1.1 2006/07/01 16:37:20 ross Exp $    */
+
+/*
+ * pid = fork();
+ *
+ * r4 == 0 in parent process, 1 in child process.
+ * r3 == pid of child in parent, pid of parent in child.
+ */
+
+#include "SYS.h"
+
+_SYSCALL(__fork,fork)
+       addi    %r4,%r4,-1      # from 1 to 0 in child, 0 to -1 in parent
+       and     %r3,%r3,%r4     # return 0 in child, pid in parent
+       blr
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/getcontext.S b/lib/nbsd_libc/arch/powerpc64/sys/getcontext.S
new file mode 100644 (file)
index 0000000..a718dc5
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: getcontext.S,v 1.3 2008/04/28 20:22:57 martin Exp $    */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       .text
+       .asciz "$NetBSD: getcontext.S,v 1.3 2008/04/28 20:22:57 martin Exp $"
+#endif /* SYSLIBC_SCCS && !lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext, _getcontext)
+#endif
+
+ENTRY(_getcontext)
+       mr      %r5,%r3                         # must save pointer
+       li      %r0,SYS_getcontext
+       sc
+       bso     1f
+       mflr    %r4
+       stw     %r4,(48 + 34 * 4)(%r5)          # saved pc <- lr
+       stw     %r3,(48 +  3 * 4)(%r5)          # arrange for return value 0
+       blr
+1:
+       b       .__cerror
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/pipe.S b/lib/nbsd_libc/arch/powerpc64/sys/pipe.S
new file mode 100644 (file)
index 0000000..224453a
--- /dev/null
@@ -0,0 +1,19 @@
+/*     $NetBSD: pipe.S,v 1.1 2006/07/01 16:37:20 ross Exp $    */
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe, _pipe)
+#endif
+
+ENTRY(_pipe)
+       mr      %r5,%r3         # save pointer
+       li      %r0,SYS_pipe
+       sc                      # assume, that r5 is kept
+       bso     1f
+       stw     %r3,0(%r5)      # success, store fds
+       stw     %r4,4(%r5)
+       li      %r3,0
+       blr                     # and return 0
+1:
+       b       PIC_PLT(_C_LABEL(__cerror))
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/ptrace.S b/lib/nbsd_libc/arch/powerpc64/sys/ptrace.S
new file mode 100644 (file)
index 0000000..161535d
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: ptrace.S,v 1.1 2006/07/01 16:37:20 ross Exp $  */
+
+#include "SYS.h"
+
+ENTRY(ptrace)
+#ifdef _REENTRANT
+       mflr    %r0
+       stwu    %r1,-32(%r1)
+       stw     %r0,36(%r1)
+       stw     %r3,8(%r1)
+       stw     %r4,12(%r1)
+       stw     %r5,16(%r1)
+       stw     %r6,20(%r1)
+
+       bl      PIC_PLT(_C_LABEL(__errno))
+       li      %r7,0
+       stw     %r7,0(%r3)
+
+       lwz     %r3,8(%r1)
+       lwz     %r4,12(%r1)
+       lwz     %r5,16(%r1)
+       lwz     %r0,36(%r1)
+       lwz     %r6,20(%r1)
+       mtlr    %r0
+       la      %r1,32(%r1)
+#else
+#ifdef PIC
+       mflr    %r0
+       bl      _GLOBAL_OFFSET_TABLE_@local-4
+       mflr    %r7
+       lwz     %r7,_C_LABEL(errno)@got(%r7)
+       li      %r8,0
+       stw     %r8,0(%r7)
+       mtlr    0
+#else
+       lis     %r7,_C_LABEL(errno)@ha
+       li      %r8,0
+       stw     %r8,_C_LABEL(errno)@l(%r7)
+#endif /* PIC */
+#endif /* _REENTRANT */
+       li      %r0,SYS_ptrace
+       sc
+       bso     1f
+       blr
+1:
+       b       PIC_PLT(_C_LABEL(__cerror))
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/sbrk.S b/lib/nbsd_libc/arch/powerpc64/sys/sbrk.S
new file mode 100644 (file)
index 0000000..75d9b2e
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: sbrk.S,v 1.3 2006/07/07 06:50:06 ross Exp $    */
+
+#include "SYS.h"
+
+       .globl  _C_LABEL(__curbrk)
+       .globl  _C_LABEL(_end)
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(sbrk, _sbrk)
+#endif
+
+
+       .data
+_C_LABEL(__curbrk):
+       .long   _C_LABEL(_end)
+       .text
+
+       .macro  LdAddr  r,sym
+       .pushsection    ".toc","aw"
+100:   .tc \sym[TC],\sym
+       .popsection
+       ld      \r,100b@toc(2)
+       .endm
+
+ENTRY(_sbrk)
+       ldAddr  %r6,__curbrk
+       add     %r3,%r3,%r6
+       mr      %r7,%r3                         # r7 = new break
+       li      %r0,SYS_break
+       sc                                      # break(new_break)
+       bso     1f
+       mr      %r3,%r6                         # set return value
+       LdAddr  %r6,__curbrk
+       std     %r7,0(%r6)
+       blr
+1:
+       b       PIC_PLT(_C_LABEL(__cerror))
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/shmat.S b/lib/nbsd_libc/arch/powerpc64/sys/shmat.S
new file mode 100644 (file)
index 0000000..92f9bec
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: shmat.S,v 1.1 2006/07/01 16:37:20 ross Exp $   */
+
+#include "SYS.h"
+
+RSYSCALL(shmat)
diff --git a/lib/nbsd_libc/arch/powerpc64/sys/syscall.S b/lib/nbsd_libc/arch/powerpc64/sys/syscall.S
new file mode 100644 (file)
index 0000000..f30fb7c
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: syscall.S,v 1.1 2006/07/01 16:37:20 ross Exp $ */
+
+#include "SYS.h"
+
+RSYSCALL(syscall)
diff --git a/lib/nbsd_libc/arch/sh3/Makefile.inc b/lib/nbsd_libc/arch/sh3/Makefile.inc
new file mode 100644 (file)
index 0000000..e97ee97
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.6 2006/06/17 18:04:23 uwe Exp $
+
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S
+
+CPPFLAGS+=      -DSOFTFLOAT # -DSOFTFLOAT_NEED_FIXUNS
+.include <softfloat/Makefile.inc>
diff --git a/lib/nbsd_libc/arch/sh3/SYS.h b/lib/nbsd_libc/arch/sh3/SYS.h
new file mode 100644 (file)
index 0000000..91e856c
--- /dev/null
@@ -0,0 +1,126 @@
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)SYS.h 5.5 (Berkeley) 5/7/91
+ *     $NetBSD: SYS.h,v 1.9 2006/01/06 06:19:20 uwe Exp $
+ */
+
+#include <machine/asm.h>
+#include <sys/syscall.h>
+
+#ifdef __STDC__
+#define SYSTRAP(x)                                     \
+               mov.l   903f, r0;                       \
+               .long   0xc380; /* trapa #0x80 */       \
+               bra     904f;                           \
+                nop;                                   \
+               .align  2;                              \
+       903:    .long   (SYS_ ## x);                    \
+       904:
+#else
+#define SYSTRAP(x)                                     \
+               mov.l   903f, r0;                       \
+               trapa   #0x80;                          \
+               bra     904f;                           \
+                nop;                                   \
+               .align  2;                              \
+       903:    .long   (SYS_/**/x);                    \
+       904:
+#endif
+
+#define _SYSCALL_NOERROR(x,y)                          \
+               ENTRY(x);                               \
+               SYSTRAP(y)
+
+#ifdef PIC
+
+#define JUMP_CERROR                                    \
+               mov     r0, r4;                         \
+               mov.l   912f, r1;                       \
+               mova    912f, r0;                       \
+               mov.l   913f, r2;                       \
+               add     r1, r0;                         \
+               mov.l   @(r0, r2), r3;                  \
+               jmp     @r3;                            \
+                nop;                                   \
+               .align  2;                              \
+       912:    .long   _GLOBAL_OFFSET_TABLE_;          \
+       913:    .long   PIC_GOT(cerror)
+
+#else  /* !PIC */
+
+#define JUMP_CERROR                                    \
+               mov.l   912f, r3;                       \
+               jmp     @r3;                            \
+                mov    r0, r4;                         \
+               .align  2;                              \
+       912:    .long   cerror
+
+#endif /* !PIC */
+
+#define _SYSCALL(x,y)                                  \
+               .text;                                  \
+       911:    JUMP_CERROR;                            \
+               _SYSCALL_NOERROR(x,y);                  \
+               bf      911b
+
+#define SYSCALL_NOERROR(x)                             \
+               _SYSCALL_NOERROR(x,x)
+
+#define SYSCALL(x)                                     \
+               _SYSCALL(x,x)
+
+#define PSEUDO_NOERROR(x,y)                            \
+               _SYSCALL_NOERROR(x,y);                  \
+               rts;                                    \
+                nop
+
+#define PSEUDO(x,y)                                    \
+               _SYSCALL(x,y);                          \
+               rts;                                    \
+                nop
+
+#define RSYSCALL_NOERROR(x)                            \
+               PSEUDO_NOERROR(x,x)
+
+#define RSYSCALL(x)                                    \
+               PSEUDO(x,x)
+
+#ifdef WEAK_ALIAS
+#define        WSYSCALL(weak,strong)                           \
+               WEAK_ALIAS(weak,strong);                \
+               PSEUDO(strong,weak)
+#else
+#define        WSYSCALL(weak,strong)                           \
+               PSEUDO(weak,weak)
+#endif
+
+       .globl  cerror
diff --git a/lib/nbsd_libc/arch/sh3/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/sh3/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..1d786e0
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/15 17:35:18 kleink Exp $
+
+SRCS+= strtof.c
diff --git a/lib/nbsd_libc/arch/sh3/gdtoa/arith.h b/lib/nbsd_libc/arch/sh3/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..40d3ed1
--- /dev/null
@@ -0,0 +1,9 @@
+/* $NetBSD: arith.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#include <machine/endian.h>
+
+#if BYTE_ORDER == BIG_ENDIAN
+#define IEEE_BIG_ENDIAN
+#else
+#define IEEE_LITTLE_ENDIAN
+#endif
diff --git a/lib/nbsd_libc/arch/sh3/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/sh3/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..a7b54a2
--- /dev/null
@@ -0,0 +1,12 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#include <machine/endian.h>
+
+#define f_QNAN 0x7fa00000
+#if BYTE_ORDER == BIG_ENDIAN
+#define d_QNAN0 0x7ff40000
+#define d_QNAN1 0x0
+#else
+#define d_QNAN0 0x0
+#define d_QNAN1 0x7ff40000
+#endif
diff --git a/lib/nbsd_libc/arch/sh3/gen/Makefile.inc b/lib/nbsd_libc/arch/sh3/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..651ada0
--- /dev/null
@@ -0,0 +1,26 @@
+#      $NetBSD: Makefile.inc,v 1.25 2009/12/06 07:12:17 uebayasi Exp $
+
+SRCS+= setjmp.S _setjmp.S sigsetjmp.S
+
+SRCS+= makecontext.c resumecontext.c swapcontext.S
+
+SRCS+= _lwp.c
+
+SRCS+= fabs.c flt_rounds.c bswap16.c bswap32.c bswap64.c
+
+# Common ieee754 constants and functions
+SRCS+= infinityf_ieee754.c infinity_ieee754.c infinityl_dbl_ieee754.c
+SRCS+= fpclassifyf_ieee754.c fpclassifyd_ieee754.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c
+SRCS+= isfinitef_ieee754.c isfinited_ieee754.c
+SRCS+= signbitf_ieee754.c signbitd_ieee754.c
+
+SRCS+= nanf.c
+
+LSRCS.sh3.gen= Lint__setjmp.c Lint___setjmp14.c Lint___sigsetjmp14.c \
+               Lint_swapcontext.c
+
+LSRCS+=                ${LSRCS.sh3.gen}
+DPSRCS+=       ${LSRCS.sh3.gen}
+CLEANFILES+=   ${LSRCS.sh3.gen}
diff --git a/lib/nbsd_libc/arch/sh3/gen/_lwp.c b/lib/nbsd_libc/arch/sh3/gen/_lwp.c
new file mode 100644 (file)
index 0000000..84d1647
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: _lwp.c,v 1.4 2005/06/12 05:21:26 lukem Exp $   */
+
+/*
+ * Copyright (c) 2002 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Jason R. Thorpe for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed for the NetBSD Project by
+ *     Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.4 2005/06/12 05:21:26 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+
+void
+_lwp_makecontext(ucontext_t *u, void (*start)(void *),
+    void *arg, void *private, caddr_t stack_base, size_t stack_size)
+{
+       void **sp;
+
+       getcontext(u);
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+
+       sp = (void **) (stack_base + stack_size);
+
+       u->uc_mcontext.__gregs[_REG_R4] = (__greg_t) arg;
+       u->uc_mcontext.__gregs[_REG_SP] = ((__greg_t) sp) & ~3;
+       u->uc_mcontext.__gregs[_REG_PR] = (__greg_t) _lwp_exit;
+       u->uc_mcontext.__gregs[_REG_PC] = (__greg_t) start;
+}
diff --git a/lib/nbsd_libc/arch/sh3/gen/_setjmp.S b/lib/nbsd_libc/arch/sh3/gen/_setjmp.S
new file mode 100644 (file)
index 0000000..81a022d
--- /dev/null
@@ -0,0 +1,89 @@
+/*     $NetBSD: _setjmp.S,v 1.7 2006/01/05 02:04:41 uwe Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)_setjmp.s     5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#include <machine/setjmp.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: _setjmp.S,v 1.7 2006/01/05 02:04:41 uwe Exp $")
+#endif
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     _longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     _setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is NOT restored.
+ */
+
+ENTRY(_setjmp)
+       add     #((_JB_HAS_MASK + 1) * 4), r4
+       mov     #0, r0
+       mov.l   r0, @-r4                /* no saved signal mask */
+       mov.l   r15, @-r4
+       mov.l   r14, @-r4
+       mov.l   r13, @-r4
+       mov.l   r12, @-r4
+       mov.l   r11, @-r4
+       mov.l   r10, @-r4
+       mov.l   r9, @-r4
+       mov.l   r8, @-r4
+       sts.l   pr, @-r4
+       rts
+        xor    r0, r0
+       SET_ENTRY_SIZE(_setjmp)
+
+ENTRY(_longjmp)
+       lds.l   @r4+, pr
+       mov.l   @r4+, r8
+       mov.l   @r4+, r9
+       mov.l   @r4+, r10
+       mov.l   @r4+, r11
+       mov.l   @r4+, r12
+       mov.l   @r4+, r13
+       mov.l   @r4+, r14
+       mov.l   @r4+, r15
+
+       mov     r5, r0
+       tst     r0, r0
+       bf      .L0
+       add     #1, r0
+.L0:
+       rts
+        nop
+       SET_ENTRY_SIZE(_longjmp)
diff --git a/lib/nbsd_libc/arch/sh3/gen/fabs.c b/lib/nbsd_libc/arch/sh3/gen/fabs.c
new file mode 100644 (file)
index 0000000..f0738d4
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: fabs.c,v 1.3 2006/05/21 02:51:15 mrg Exp $     */
+
+/*
+ * Copyright (c) 1996 Mark Brinicombe
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe
+ * 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 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.
+ */
+
+/*
+ * fabs(x) returns the absolute value of x.
+ */
+
+double fabs(double x);
+
+double
+fabs(double x)
+{
+       if (x < 0)
+               x = -x;
+       return(x);
+}
diff --git a/lib/nbsd_libc/arch/sh3/gen/flt_rounds.c b/lib/nbsd_libc/arch/sh3/gen/flt_rounds.c
new file mode 100644 (file)
index 0000000..936d8f4
--- /dev/null
@@ -0,0 +1,81 @@
+/*     $NetBSD: flt_rounds.c,v 1.4 2007/01/17 23:24:22 hubertf Exp $   */
+
+/*
+ * Copyright (c) 1996 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Mark Brinicombe
+ *     for the NetBSD Project.
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: flt_rounds.c,v 1.4 2007/01/17 23:24:22 hubertf Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <ieeefp.h>
+
+static const int map[] = {
+       1,      /* round to nearest */
+       2,      /* round to positive infinity */
+       3,      /* round to negative infinity */
+       0       /* round to zero */
+};
+
+/*
+ * Return the current FP rounding mode
+ *
+ * Returns:
+ *     0 - round to zero
+ *     1 - round to nearest
+ *     2 - round to postive infinity
+ *     3 - round to negative infinity
+ *
+ * ok all we need to do is get the current FP rounding mode
+ * index our map table and return the appropriate value.
+ *
+ * HOWEVER:
+ * The ARM FPA codes the rounding mode into the actual FP instructions
+ * so there is no such thing as a global rounding mode.
+ * The default is round to nearest if rounding is not explicitly specified.
+ * FP instructions generated by GCC will not explicitly specify a rounding
+ * mode.
+ *
+ * So the best we can do it to return the rounding mode FP instructions
+ * use if rounding is not specified which is round to nearest.
+ *
+ * This could change in the future with new floating point emulators or
+ * soft float FP libraries.
+ */
+
+extern int __flt_rounds __P((void));
+
+int
+__flt_rounds()
+{
+       return(map[fpgetround()]);
+}
diff --git a/lib/nbsd_libc/arch/sh3/gen/makecontext.c b/lib/nbsd_libc/arch/sh3/gen/makecontext.c
new file mode 100644 (file)
index 0000000..1c55e45
--- /dev/null
@@ -0,0 +1,71 @@
+/*     $NetBSD: makecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include <stddef.h>
+#include <inttypes.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#include <stdarg.h>
+
+void
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+{
+       __greg_t *gr = ucp->uc_mcontext.__gregs;
+       int i;
+       unsigned int *sp;
+       va_list ap;
+
+       /* Compute and align stack pointer. */
+       sp = (unsigned int *)
+           (((uintptr_t)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size) & ~3);
+       /* Allocate necessary stack space for arguments exceeding r4-7. */
+       if (argc > 4) 
+               sp -= argc - 4;
+       gr[_REG_SP] = (__greg_t)sp;
+       /* Arrange for return via the trampoline code. */
+       gr[_REG_PR] = (__greg_t)_resumecontext;
+       gr[_REG_PC] = (__greg_t)func; 
+
+       va_start(ap, argc);
+       /* Pass up to four arguments in r4-7. */
+       for (i = 0; i < argc && i < 4; i++)
+               gr[_REG_R4 - i] = va_arg(ap, int); /* sic!  see mcontext.h */
+       /* Pass any additional arguments on the stack. */
+       for (argc -= i; argc > 0; argc--)
+               *sp++ = va_arg(ap, int);
+       va_end(ap); 
+}
diff --git a/lib/nbsd_libc/arch/sh3/gen/nanf.c b/lib/nbsd_libc/arch/sh3/gen/nanf.c
new file mode 100644 (file)
index 0000000..6fbda28
--- /dev/null
@@ -0,0 +1,19 @@
+/*     $NetBSD: nanf.c,v 1.4 2009/02/22 01:34:02 martin Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nanf.c,v 1.4 2009/02/22 01:34:02 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+/* bytes for quiet NaN (IEEE single precision) */
+const union __float_u __nanf =
+#if BYTE_ORDER == BIG_ENDIAN
+               { { 0x7f, 0xa0,    0,    0 } };
+#else
+               { {    0,    0, 0xa0, 0x7f } };
+#endif
+
+__warn_references(__nanf, "warning: <math.h> defines NAN incorrectly for your compiler.")
diff --git a/lib/nbsd_libc/arch/sh3/gen/resumecontext.c b/lib/nbsd_libc/arch/sh3/gen/resumecontext.c
new file mode 100644 (file)
index 0000000..1a7c4c5
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "extern.h"
+
+void
+_resumecontext()
+{
+       ucontext_t uct;
+
+       (void)getcontext(&uct);
+       if (uct.uc_link == NULL) 
+               exit(0);
+       (void)setcontext(uct.uc_link);
+       _exit(-1);
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/sh3/gen/setjmp.S b/lib/nbsd_libc/arch/sh3/gen/setjmp.S
new file mode 100644 (file)
index 0000000..5ad5da2
--- /dev/null
@@ -0,0 +1,130 @@
+/*     $NetBSD: setjmp.S,v 1.10 2006/01/05 19:21:37 uwe Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)setjmp.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#include <machine/setjmp.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: setjmp.S,v 1.10 2006/01/05 19:21:37 uwe Exp $")
+#endif
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(__setjmp14)
+       PIC_PROLOGUE(.L_got_1)
+       sts.l   pr, @-sp
+       mov.l   r4, @-sp
+
+       mov.l   .L___sigprocmask14_1, r0
+       mov     r4, r6
+       mov     #1, r4                  /* how = SIG_BLOCK */
+       mov     #0, r5                  /* new = NULL */
+1:     CALL    r0
+        add    #(_JB_SIGMASK * 4), r6  /* old = &sigmask */
+
+       mov.l   @sp+, r4
+       lds.l   @sp+, pr
+       PIC_EPILOGUE
+
+       /* identical to _setjmp except that _JB_HAS_MASK is non-zero */
+       add     #((_JB_HAS_MASK + 1) * 4), r4
+       mov     #1, r0
+       mov.l   r0, @-r4                /* has signal mask */
+       mov.l   r15, @-r4
+       mov.l   r14, @-r4
+       mov.l   r13, @-r4
+       mov.l   r12, @-r4
+       mov.l   r11, @-r4
+       mov.l   r10, @-r4
+       mov.l   r9, @-r4
+       mov.l   r8, @-r4
+       sts.l   pr, @-r4
+       rts
+        xor    r0, r0
+
+       .align  2
+.L_got_1:              PIC_GOT_DATUM
+.L___sigprocmask14_1:  CALL_DATUM(_C_LABEL(__sigprocmask14), 1b)
+       SET_ENTRY_SIZE(__setjmp14)
+
+
+ENTRY(__longjmp14)
+       /* we won't return here, so we don't need to save pr and r12 */
+       PIC_PROLOGUE_NOSAVE(.L_got_2)
+       mov.l   r5, @-sp
+       mov.l   r4, @-sp
+
+       mov.l   .L___sigprocmask14_2, r0
+       mov     r4, r5
+       mov     #3, r4                  /* how = SIG_SETMASK */
+       add     #(_JB_SIGMASK * 4), r5  /* new = &sigmask */
+1:     CALL    r0
+        mov    #0, r6                  /* old = NULL */
+
+       mov.l   @sp+, r4
+       mov.l   @sp+, r5
+
+       /* identical to _longjmp */
+       lds.l   @r4+, pr
+       mov.l   @r4+, r8
+       mov.l   @r4+, r9
+       mov.l   @r4+, r10
+       mov.l   @r4+, r11
+       mov.l   @r4+, r12
+       mov.l   @r4+, r13
+       mov.l   @r4+, r14
+       mov.l   @r4+, r15
+
+       mov     r5, r0
+       tst     r0, r0  /* make sure return value is non-zero */
+       bf      .L0
+       add     #1, r0
+.L0:
+       rts
+        nop
+
+       .align  2
+.L_got_2:              PIC_GOT_DATUM
+.L___sigprocmask14_2:  CALL_DATUM(_C_LABEL(__sigprocmask14), 1b)
+       SET_ENTRY_SIZE(__longjmp14)
diff --git a/lib/nbsd_libc/arch/sh3/gen/sigsetjmp.S b/lib/nbsd_libc/arch/sh3/gen/sigsetjmp.S
new file mode 100644 (file)
index 0000000..2c7d7b1
--- /dev/null
@@ -0,0 +1,130 @@
+/*     $NetBSD: sigsetjmp.S,v 1.9 2006/01/05 19:21:37 uwe Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)setjmp.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#include <machine/setjmp.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: sigsetjmp.S,v 1.9 2006/01/05 19:21:37 uwe Exp $")
+#endif
+
+ENTRY(__sigsetjmp14)
+       tst     r5, r5
+       bt      2f                      /* if (savemask == 0) */
+
+       /* identical to longjmp except that _JB_HAS_MASK is in the argument */
+       PIC_PROLOGUE(.L_got_1)
+       sts.l   pr, @-sp
+       mov.l   r4, @-sp
+       mov.l   r5, @-sp
+
+       mov.l   .L___sigprocmask14_1, r0
+       mov     r4, r6
+       mov     #1, r4                  /* how = SIG_BLOCK */
+       mov     #0, r5                  /* new = NULL */
+1:     CALL    r0
+        add    #(_JB_SIGMASK * 4), r6  /* old = &sigmask */
+
+       mov.l   @sp+, r5
+       mov.l   @sp+, r4
+       lds.l   @sp+, pr
+       PIC_EPILOGUE
+
+2:     /* identical to _setjmp except that _JB_HAS_MASK is in the argument */
+       add     #((_JB_HAS_MASK + 1) * 4), r4
+       mov.l   r5, @-r4                /* has signal mask? */
+       mov.l   r15, @-r4
+       mov.l   r14, @-r4
+       mov.l   r13, @-r4
+       mov.l   r12, @-r4
+       mov.l   r11, @-r4
+       mov.l   r10, @-r4
+       mov.l   r9, @-r4
+       mov.l   r8, @-r4
+       sts.l   pr, @-r4
+       rts
+        xor    r0, r0
+
+       .align  2
+.L_got_1:              PIC_GOT_DATUM
+.L___sigprocmask14_1:  CALL_DATUM(_C_LABEL(__sigprocmask14), 1b)
+       SET_ENTRY_SIZE(__sigsetjmp14)
+
+
+ENTRY(__siglongjmp14)
+       mov.l   @(_JB_HAS_MASK * 4, r4), r0
+       tst     r0, r0
+       bt      2f                      /* if no mask */
+
+       /* identical to longjmp */
+       /* we won't return here, so we don't need to save pr and r12 */
+       PIC_PROLOGUE_NOSAVE(.L_got_2)
+       mov.l   r5, @-sp
+       mov.l   r4, @-sp
+
+       mov.l   .L___sigprocmask14_2, r0
+       mov     r4, r5
+       mov     #3, r4                  /* how = SIG_SETMASK */
+       add     #(_JB_SIGMASK * 4), r5  /* new = &sigmask */
+1:     CALL    r0
+        mov    #0, r6                  /* old = NULL */
+
+       mov.l   @sp+, r4
+       mov.l   @sp+, r5
+
+2:     /* identical to _longjmp */
+       lds.l   @r4+, pr
+       mov.l   @r4+, r8
+       mov.l   @r4+, r9
+       mov.l   @r4+, r10
+       mov.l   @r4+, r11
+       mov.l   @r4+, r12
+       mov.l   @r4+, r13
+       mov.l   @r4+, r14
+       mov.l   @r4+, r15
+
+       mov     r5, r0
+       tst     r0, r0  /* make sure return value is non-zero */
+       bf      .L0
+       add     #1, r0
+.L0:
+       rts
+        nop
+
+       .align  2
+.L_got_2:              PIC_GOT_DATUM
+.L___sigprocmask14_2:  CALL_DATUM(_C_LABEL(__sigprocmask14), 1b)
+       SET_ENTRY_SIZE(__siglongjmp14)
diff --git a/lib/nbsd_libc/arch/sh3/gen/swapcontext.S b/lib/nbsd_libc/arch/sh3/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..841a842
--- /dev/null
@@ -0,0 +1,75 @@
+/*     $NetBSD: swapcontext.S,v 1.9 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: swapcontext.S,v 1.9 2008/04/28 20:22:57 martin Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+/*
+ * int
+ * swapcontext(ucontext_t * restrict oucp, ucontext_t * restrict ucp);
+ */
+ENTRY(swapcontext)
+       PIC_PROLOGUE(.L_got)
+       mov.l   r5, @-sp
+       sts.l   pr, @-sp
+
+       mov.l   .L__getcontext, r0
+1:     CALL    r0                      /* _getcontext(oucp) */
+        mov.l  r4, @-sp
+       mov.l   @sp+, r1
+       tst     r0, r0
+       bf      3f                      /* return error from getcontext */
+
+       /* Note: getcontext does _UC_MACHINE_INTRV(oucp) = 0 for us */
+       mov.l   @sp, r0
+       mov.l   r0, @(36 + 1 * 4, r1)   /* _UC_MACHINE_SET_PC(oucp, pr) */
+       mov.l   .L_setcontext, r2
+2:     CALL    r2                      /* setcontext(ucp) */
+        mov.l  @(4, sp), r4
+       /* if we get here, return error from setcontext */
+3:
+       lds.l   @sp+, pr
+#ifdef PIC
+       add     #4, sp
+       rts
+        PIC_EPILOGUE
+#else
+       rts
+        add    #4, sp
+#endif
+
+       .align  2
+.L_got:                        PIC_GOT_DATUM
+.L__getcontext:                CALL_DATUM(_C_LABEL(_getcontext), 1b)
+.L_setcontext:         CALL_DATUM(_C_LABEL(setcontext), 2b)
+       SET_ENTRY_SIZE(swapcontext)
diff --git a/lib/nbsd_libc/arch/sh3/net/Makefile.inc b/lib/nbsd_libc/arch/sh3/net/Makefile.inc
new file mode 100644 (file)
index 0000000..02c67cf
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 2000/01/05 14:07:36 msaitoh Exp $
+
+SRCS+= htonl.c htons.c ntohl.c ntohs.c
diff --git a/lib/nbsd_libc/arch/sh3/net/htonl.c b/lib/nbsd_libc/arch/sh3/net/htonl.c
new file mode 100644 (file)
index 0000000..6735628
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: htonl.c,v 1.3 2005/12/24 23:10:08 perry Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)htonl.s       5.2 (Berkeley) 12/17/90
+ */
+
+#include <sys/types.h>
+#include <machine/endian.h>
+#if defined(LIBC_SCCS)
+       __RCSID("$NetBSD: htonl.c,v 1.3 2005/12/24 23:10:08 perry Exp $");
+#endif
+
+/* hostorder = htonl(netorder) */
+#if BYTE_ORDER == LITTLE_ENDIAN
+u_int32_t
+htonl(x)
+       u_int32_t x;
+{
+       u_int32_t y = 0;
+
+       __asm("swap.b %1, %0" : "=r" (y) : "r" (x));
+       __asm("swap.w %1, %0" : "=r" (y) : "r" (y));
+       __asm("swap.b %1, %0" : "=r" (y) : "r" (y));
+       return y;
+}
+#endif
diff --git a/lib/nbsd_libc/arch/sh3/net/htons.c b/lib/nbsd_libc/arch/sh3/net/htons.c
new file mode 100644 (file)
index 0000000..544f9fc
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: htons.c,v 1.3 2005/12/24 23:10:08 perry Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)htonl.s       5.2 (Berkeley) 12/17/90
+ */
+
+#include <sys/types.h>
+#include <machine/endian.h>
+#if defined(LIBC_SCCS)
+       __RCSID("$NetBSD: htons.c,v 1.3 2005/12/24 23:10:08 perry Exp $");
+#endif
+
+/* netorder = htons(hostorder) */
+#if BYTE_ORDER == LITTLE_ENDIAN
+u_int16_t
+htons(x)
+       u_int16_t x;
+{
+       __asm("swap.b %1, %0" : "=r" (x) :  "r" (x));
+       return x;
+}
+#endif
diff --git a/lib/nbsd_libc/arch/sh3/net/ntohl.c b/lib/nbsd_libc/arch/sh3/net/ntohl.c
new file mode 100644 (file)
index 0000000..364656b
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: ntohl.c,v 1.3 2005/12/24 23:10:08 perry Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)ntohl.s       5.2 (Berkeley) 12/17/90
+ */
+
+#include <sys/types.h>
+#include <machine/endian.h>
+#if defined(LIBC_SCCS)
+       __RCSID("$NetBSD: ntohl.c,v 1.3 2005/12/24 23:10:08 perry Exp $");
+#endif
+
+/* netorder = ntohl(hostorder) */
+#if BYTE_ORDER == LITTLE_ENDIAN
+u_int32_t
+ntohl(x)
+       u_int32_t x;
+{
+       u_int32_t y = 0;
+
+       __asm("swap.b %1, %0" : "=r" (y) : "r" (x));
+       __asm("swap.w %1, %0" : "=r" (y) : "r" (y));
+       __asm("swap.b %1, %0" : "=r" (y) : "r" (y));
+       return y;
+}
+#endif
diff --git a/lib/nbsd_libc/arch/sh3/net/ntohs.c b/lib/nbsd_libc/arch/sh3/net/ntohs.c
new file mode 100644 (file)
index 0000000..174a64d
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: ntohs.c,v 1.3 2005/12/24 23:10:08 perry Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)ntohl.s       5.2 (Berkeley) 12/17/90
+ */
+
+#include <sys/types.h>
+#include <machine/endian.h>
+#if defined(LIBC_SCCS)
+       __RCSID("$NetBSD: ntohs.c,v 1.3 2005/12/24 23:10:08 perry Exp $");
+#endif
+
+/* hostorder = ntohs(netorder) */
+#if BYTE_ORDER == LITTLE_ENDIAN
+u_int16_t
+ntohs(x)
+       u_int16_t x;
+{
+       __asm("swap.b %1, %0" : "=r" (x) :  "r" (x));
+       return x;
+}
+#endif
diff --git a/lib/nbsd_libc/arch/sh3/softfloat/milieu.h b/lib/nbsd_libc/arch/sh3/softfloat/milieu.h
new file mode 100644 (file)
index 0000000..64429ca
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: milieu.h,v 1.1 2000/06/06 17:28:42 tsubai Exp $        */
+
+/*
+===============================================================================
+
+This C header file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+Include common integer types and flags.
+-------------------------------------------------------------------------------
+*/
+#include "sh3-gcc.h"
+
+/*
+-------------------------------------------------------------------------------
+Symbolic Boolean literals.
+-------------------------------------------------------------------------------
+*/
+enum {
+    FALSE = 0,
+    TRUE  = 1
+};
diff --git a/lib/nbsd_libc/arch/sh3/softfloat/sh3-gcc.h b/lib/nbsd_libc/arch/sh3/softfloat/sh3-gcc.h
new file mode 100644 (file)
index 0000000..15c168a
--- /dev/null
@@ -0,0 +1,89 @@
+/*     $NetBSD: sh3-gcc.h,v 1.2 2005/12/24 21:11:16 perry Exp $        */
+
+/*
+-------------------------------------------------------------------------------
+One of the macros `BIGENDIAN' or `LITTLEENDIAN' must be defined.
+-------------------------------------------------------------------------------
+*/
+#include <machine/endian.h>
+#if _BYTE_ORDER == _BIG_ENDIAN
+#define BIGENDIAN
+#endif
+#if _BYTE_ORDER == _LITTLE_ENDIAN
+#define LITTLEENDIAN
+#endif
+
+/*
+-------------------------------------------------------------------------------
+The macro `BITS64' can be defined to indicate that 64-bit integer types are
+supported by the compiler.
+-------------------------------------------------------------------------------
+*/
+#define BITS64
+
+/*
+-------------------------------------------------------------------------------
+Each of the following `typedef's defines the most convenient type that holds
+integers of at least as many bits as specified.  For example, `uint8' should
+be the most convenient type that can hold unsigned integers of as many as
+8 bits.  The `flag' type must be able to hold either a 0 or 1.  For most
+implementations of C, `flag', `uint8', and `int8' should all be `typedef'ed
+to the same as `int'.
+-------------------------------------------------------------------------------
+*/
+typedef int flag;
+typedef unsigned char uint8;
+typedef signed char int8;
+typedef int uint16;
+typedef int int16;
+typedef unsigned int uint32;
+typedef signed int int32;
+#ifdef BITS64
+typedef unsigned long long int uint64;
+typedef signed long long int int64;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Each of the following `typedef's defines a type that holds integers
+of _exactly_ the number of bits specified.  For instance, for most
+implementation of C, `bits16' and `sbits16' should be `typedef'ed to
+`unsigned short int' and `signed short int' (or `short int'), respectively.
+-------------------------------------------------------------------------------
+*/
+typedef unsigned char bits8;
+typedef signed char sbits8;
+typedef unsigned short int bits16;
+typedef signed short int sbits16;
+typedef unsigned int bits32;
+typedef signed int sbits32;
+#ifdef BITS64
+typedef unsigned long long int bits64;
+typedef signed long long int sbits64;
+#endif
+
+#ifdef BITS64
+/*
+-------------------------------------------------------------------------------
+The `LIT64' macro takes as its argument a textual integer literal and
+if necessary ``marks'' the literal as having a 64-bit integer type.
+For example, the GNU C Compiler (`gcc') requires that 64-bit literals be
+appended with the letters `LL' standing for `long long', which is `gcc's
+name for the 64-bit integer type.  Some compilers may allow `LIT64' to be
+defined as the identity macro:  `#define LIT64( a ) a'.
+-------------------------------------------------------------------------------
+*/
+#define LIT64(a) a##LL
+#endif
+
+/*
+-------------------------------------------------------------------------------
+The macro `INLINE' can be used before functions that should be inlined.  If
+a compiler does not support explicit inlining, this macro should be defined
+to be `static'.
+-------------------------------------------------------------------------------
+*/
+#define INLINE static inline
+
+#define FLOAT64_DEMANGLE(a)    (a)
+#define FLOAT64_MANGLE(a)      (a)
diff --git a/lib/nbsd_libc/arch/sh3/softfloat/softfloat.h b/lib/nbsd_libc/arch/sh3/softfloat/softfloat.h
new file mode 100644 (file)
index 0000000..a1f9b1a
--- /dev/null
@@ -0,0 +1,314 @@
+/*     $NetBSD: softfloat.h,v 1.9 2006/05/16 20:55:51 mrg Exp $        */
+
+/* This is a derivative work. */
+
+/*
+===============================================================================
+
+This C header file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+The macro `FLOATX80' must be defined to enable the extended double-precision
+floating-point format `floatx80'.  If this macro is not defined, the
+`floatx80' type will not be defined, and none of the functions that either
+input or output the `floatx80' type will be defined.  The same applies to
+the `FLOAT128' macro and the quadruple-precision format `float128'.
+-------------------------------------------------------------------------------
+*/
+/* #define FLOATX80 */
+/* #define FLOAT128 */
+
+#include <machine/ieeefp.h>
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point types.
+-------------------------------------------------------------------------------
+*/
+typedef unsigned int float32;
+typedef unsigned long long float64;
+#ifdef FLOATX80
+typedef struct {
+    unsigned short high;
+    unsigned long long low;
+} floatx80;
+#endif
+#ifdef FLOAT128
+typedef struct {
+    unsigned long long high, low;
+} float128;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point underflow tininess-detection mode.
+-------------------------------------------------------------------------------
+*/
+#ifndef SOFTFLOAT_FOR_GCC
+extern int8 float_detect_tininess;
+#endif
+enum {
+    float_tininess_after_rounding  = 0,
+    float_tininess_before_rounding = 1
+};
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point rounding mode.
+-------------------------------------------------------------------------------
+*/
+extern fp_rnd float_rounding_mode;
+enum {
+    float_round_nearest_even = FP_RN,
+    float_round_to_zero      = FP_RZ,
+    float_round_down         = FP_RM,
+    float_round_up           = FP_RP
+};
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point exception flags.
+-------------------------------------------------------------------------------
+*/
+extern fp_except float_exception_flags;
+extern fp_except float_exception_mask;
+enum {
+    float_flag_inexact   = FP_X_IMP,
+    float_flag_underflow = FP_X_UFL,
+    float_flag_overflow  = FP_X_OFL,
+    float_flag_divbyzero = FP_X_DZ,
+    float_flag_invalid   = FP_X_INV
+};
+
+/*
+-------------------------------------------------------------------------------
+Routine to raise any or all of the software IEC/IEEE floating-point
+exception flags.
+-------------------------------------------------------------------------------
+*/
+void float_raise( fp_except );
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE integer-to-floating-point conversion routines.
+-------------------------------------------------------------------------------
+*/
+float32 int32_to_float32( int );
+float64 int32_to_float64( int );
+#ifdef FLOATX80
+floatx80 int32_to_floatx80( int );
+#endif
+#ifdef FLOAT128
+float128 int32_to_float128( int );
+#endif
+#ifndef SOFTFLOAT_FOR_GCC /* __floatdi?f is in libgcc2.c */
+float32 int64_to_float32( long long );
+float64 int64_to_float64( long long );
+#ifdef FLOATX80
+floatx80 int64_to_floatx80( long long );
+#endif
+#ifdef FLOAT128
+float128 int64_to_float128( long long );
+#endif
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE single-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float32_to_int32( float32 );
+int float32_to_int32_round_to_zero( float32 );
+#if defined(SOFTFLOAT_FOR_GCC) && defined(SOFTFLOAT_NEED_FIXUNS)
+unsigned int float32_to_uint32_round_to_zero( float32 );
+#endif
+#ifndef SOFTFLOAT_FOR_GCC /* __fix?fdi provided by libgcc2.c */
+long long float32_to_int64( float32 );
+long long float32_to_int64_round_to_zero( float32 );
+#endif
+float64 float32_to_float64( float32 );
+#ifdef FLOATX80
+floatx80 float32_to_floatx80( float32 );
+#endif
+#ifdef FLOAT128
+float128 float32_to_float128( float32 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE single-precision operations.
+-------------------------------------------------------------------------------
+*/
+float32 float32_round_to_int( float32 );
+float32 float32_add( float32, float32 );
+float32 float32_sub( float32, float32 );
+float32 float32_mul( float32, float32 );
+float32 float32_div( float32, float32 );
+float32 float32_rem( float32, float32 );
+float32 float32_sqrt( float32 );
+flag float32_eq( float32, float32 );
+flag float32_le( float32, float32 );
+flag float32_lt( float32, float32 );
+flag float32_eq_signaling( float32, float32 );
+flag float32_le_quiet( float32, float32 );
+flag float32_lt_quiet( float32, float32 );
+#ifndef SOFTFLOAT_FOR_GCC
+flag float32_is_signaling_nan( float32 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE double-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float64_to_int32( float64 );
+int float64_to_int32_round_to_zero( float64 );
+#if defined(SOFTFLOAT_FOR_GCC) && defined(SOFTFLOAT_NEED_FIXUNS)
+unsigned int float64_to_uint32_round_to_zero( float64 );
+#endif
+#ifndef SOFTFLOAT_FOR_GCC /* __fix?fdi provided by libgcc2.c */
+long long float64_to_int64( float64 );
+long long float64_to_int64_round_to_zero( float64 );
+#endif
+float32 float64_to_float32( float64 );
+#ifdef FLOATX80
+floatx80 float64_to_floatx80( float64 );
+#endif
+#ifdef FLOAT128
+float128 float64_to_float128( float64 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE double-precision operations.
+-------------------------------------------------------------------------------
+*/
+float64 float64_round_to_int( float64 );
+float64 float64_add( float64, float64 );
+float64 float64_sub( float64, float64 );
+float64 float64_mul( float64, float64 );
+float64 float64_div( float64, float64 );
+float64 float64_rem( float64, float64 );
+float64 float64_sqrt( float64 );
+flag float64_eq( float64, float64 );
+flag float64_le( float64, float64 );
+flag float64_lt( float64, float64 );
+flag float64_eq_signaling( float64, float64 );
+flag float64_le_quiet( float64, float64 );
+flag float64_lt_quiet( float64, float64 );
+#ifndef SOFTFLOAT_FOR_GCC
+flag float64_is_signaling_nan( float64 );
+#endif
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int floatx80_to_int32( floatx80 );
+int floatx80_to_int32_round_to_zero( floatx80 );
+long long floatx80_to_int64( floatx80 );
+long long floatx80_to_int64_round_to_zero( floatx80 );
+float32 floatx80_to_float32( floatx80 );
+float64 floatx80_to_float64( floatx80 );
+#ifdef FLOAT128
+float128 floatx80_to_float128( floatx80 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision rounding precision.  Valid
+values are 32, 64, and 80.
+-------------------------------------------------------------------------------
+*/
+extern int floatx80_rounding_precision;
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision operations.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_round_to_int( floatx80 );
+floatx80 floatx80_add( floatx80, floatx80 );
+floatx80 floatx80_sub( floatx80, floatx80 );
+floatx80 floatx80_mul( floatx80, floatx80 );
+floatx80 floatx80_div( floatx80, floatx80 );
+floatx80 floatx80_rem( floatx80, floatx80 );
+floatx80 floatx80_sqrt( floatx80 );
+flag floatx80_eq( floatx80, floatx80 );
+flag floatx80_le( floatx80, floatx80 );
+flag floatx80_lt( floatx80, floatx80 );
+flag floatx80_eq_signaling( floatx80, floatx80 );
+flag floatx80_le_quiet( floatx80, floatx80 );
+flag floatx80_lt_quiet( floatx80, floatx80 );
+flag floatx80_is_signaling_nan( floatx80 );
+
+#endif
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE quadruple-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float128_to_int32( float128 );
+int float128_to_int32_round_to_zero( float128 );
+long long float128_to_int64( float128 );
+long long float128_to_int64_round_to_zero( float128 );
+float32 float128_to_float32( float128 );
+float64 float128_to_float64( float128 );
+#ifdef FLOATX80
+floatx80 float128_to_floatx80( float128 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE quadruple-precision operations.
+-------------------------------------------------------------------------------
+*/
+float128 float128_round_to_int( float128 );
+float128 float128_add( float128, float128 );
+float128 float128_sub( float128, float128 );
+float128 float128_mul( float128, float128 );
+float128 float128_div( float128, float128 );
+float128 float128_rem( float128, float128 );
+float128 float128_sqrt( float128 );
+flag float128_eq( float128, float128 );
+flag float128_le( float128, float128 );
+flag float128_lt( float128, float128 );
+flag float128_eq_signaling( float128, float128 );
+flag float128_le_quiet( float128, float128 );
+flag float128_lt_quiet( float128, float128 );
+flag float128_is_signaling_nan( float128 );
+
+#endif
+
diff --git a/lib/nbsd_libc/arch/sh3/stdlib/Makefile.inc b/lib/nbsd_libc/arch/sh3/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..2f91b99
--- /dev/null
@@ -0,0 +1 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/07/31 20:40:00 dsl Exp $
diff --git a/lib/nbsd_libc/arch/sh3/string/Makefile.inc b/lib/nbsd_libc/arch/sh3/string/Makefile.inc
new file mode 100644 (file)
index 0000000..2aced0d
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/07/30 20:57:16 dsl Exp $
+
+SRCS+= bcopy.S bzero.S ffs.S memset.S
+SRCS+= memcpy.S memmove.S
diff --git a/lib/nbsd_libc/arch/sh3/string/bcopy.S b/lib/nbsd_libc/arch/sh3/string/bcopy.S
new file mode 100644 (file)
index 0000000..b32725a
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: bcopy.S,v 1.3 2006/04/23 00:08:18 uwe Exp $    */
+
+#define BCOPY
+#include "memcpy.S"
diff --git a/lib/nbsd_libc/arch/sh3/string/bzero.S b/lib/nbsd_libc/arch/sh3/string/bzero.S
new file mode 100644 (file)
index 0000000..2d5ceca
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: bzero.S,v 1.1 2002/11/20 14:23:54 itohy Exp $  */
+
+#define BZERO
+#include "memset.S"
+
diff --git a/lib/nbsd_libc/arch/sh3/sys/__clone.S b/lib/nbsd_libc/arch/sh3/sys/__clone.S
new file mode 100644 (file)
index 0000000..7e8b808
--- /dev/null
@@ -0,0 +1,88 @@
+/*     $NetBSD: __clone.S,v 1.6 2006/01/06 03:58:31 uwe Exp $  */
+
+/*-
+ * Copyright (c) 2001 Tsubai Masanari.  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.
+ * 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 ``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 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 <sys/errno.h>
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(clone,__clone)
+#endif
+
+/*
+ * int __clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+ENTRY(__clone)
+       /*
+        * Sanity checks: func and stack may not be NULL.
+        */
+       tst     r4, r4
+       bt      inval
+       tst     r5, r5
+       bt      inval
+
+       mov     r4, r2          /* save entry point for later */
+
+       mov     r6, r4          /* r4 = flags, r5 = stack (already) */
+       mov.l   .L_SYS___clone, r0
+       trapa   #0x80
+       bf      err
+
+       tst     r0, r0
+       bf      3f              /* we're the parent, just return */
+
+       jsr     @r2             /* clone does _exit((*fn)(arg)); */
+        mov    r7, r4
+
+       mov.l   .L__exit, r1
+#ifdef PIC
+       mov     r0, r4
+       mov.l   .L_got, r12     /* PIC_PROLOGUE_NOSAVE(.L_got) */
+       mova    .L_got, r0      /*  expanded to fill the delay slot */
+1:     JUMP    r1
+        add    r0, r12
+#else
+       JUMP    r1
+        mov    r0, r4
+#endif
+       /* NOTREACHED */
+
+inval:
+       mov     #EINVAL, r0
+err:
+       JUMP_CERROR
+       /* NOTREACHED */
+
+3:     rts
+        nop
+
+       .align  2
+.L_SYS___clone:        .long   SYS___clone
+
+.L_got:                PIC_GOT_DATUM
+.L__exit:      CALL_DATUM(_C_LABEL(_exit), 1b)
+       SET_ENTRY_SIZE(__clone)
diff --git a/lib/nbsd_libc/arch/sh3/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/sh3/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..73b8fd8
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.8 2008/04/28 20:22:57 martin Exp $        */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigaction14_sigtramp.c,v 1.8 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+#ifdef __LIBC12_SOURCE__
+extern const int __sigtramp_sigcontext_1[]
+    __weak_reference(__sigtramp_sigcontext_1);
+#endif
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern int __sigtramp_siginfo_2[];
+
+#ifdef __LIBC12_SOURCE__
+       /*
+        * We select the compatibility SIGCONTEXT trampoline if SA_SIGINFO
+        * is not set in the sigaction.
+        */
+       if (act && (act->sa_flags & SA_SIGINFO) == 0) {
+               extern int __sigtramp_sigcontext_1[];
+               int sav = errno;
+               int rv =  __sigaction_sigtramp(sig, act, oact,
+                                          __sigtramp_sigcontext_1, 1);
+               /*
+                * EINVAL might indicate that trampoline version 1 is
+                * not supported by the kernel; fall back on native
+                * SIGINFO trampoline.
+                */
+               if (rv >= 0 || errno != EINVAL)
+                       return rv;
+               errno = sav;
+       }
+#endif
+
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_2, 2);
+}
diff --git a/lib/nbsd_libc/arch/sh3/sys/__sigtramp2.S b/lib/nbsd_libc/arch/sh3/sys/__sigtramp2.S
new file mode 100644 (file)
index 0000000..930a999
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: __sigtramp2.S,v 1.3 2008/04/28 20:22:57 martin Exp $ */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+/*
+ * The SH signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ *
+ * On entry, stack looks like:
+ *
+ *             siginfo structure
+ *     sp->    ucontext structure
+ *
+ * NB: This order is different from what other ports use (siginfo at
+ * the top of the stack), because we want to avoid wasting two
+ * instructions to skip to the ucontext.  Not that this order really
+ * matters, but I think this inconsistency deserves an explanation.    
+ */
+NENTRY(__sigtramp_siginfo_2)
+       mov     r15, r4                 /* get pointer to ucontext */
+       SYSTRAP(setcontext)             /* and call setcontext() */
+       mov     r0, r4                  /* exit with errno */
+       SYSTRAP(exit)                   /* if sigreturn fails */
+
+       SET_ENTRY_SIZE(__sigtramp_siginfo_2)
diff --git a/lib/nbsd_libc/arch/sh3/sys/__syscall.S b/lib/nbsd_libc/arch/sh3/sys/__syscall.S
new file mode 100644 (file)
index 0000000..0da9394
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: __syscall.S,v 1.6 2006/01/06 01:57:38 uwe Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)syscall.s     5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __syscall.S,v 1.6 2006/01/06 01:57:38 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+RSYSCALL(__syscall)
diff --git a/lib/nbsd_libc/arch/sh3/sys/__vfork14.S b/lib/nbsd_libc/arch/sh3/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..0d2a296
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: __vfork14.S,v 1.6 2006/01/06 07:07:34 uwe Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)Ovfork.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __vfork14.S,v 1.6 2006/01/06 07:07:34 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+/*
+ * pid = vfork();
+ *
+ * r1 == 0 in parent process, r1 == 1 in child process.
+ * r0 == pid of child in parent, r0 == pid of parent in child.
+ *
+ */
+ENTRY(__vfork14)
+       mov.l   .L_SYS___vfork14, r0
+       trapa   #0x80
+       bf      err
+
+       add     #0xff, r1       /* from 1 to 0 in child, 0 to -1 in parent */
+       rts
+        and    r1, r0          /* 0 in child, child pid in parent */
+
+err:
+       JUMP_CERROR
+
+       .align  2
+.L_SYS___vfork14:
+       .long   SYS___vfork14
+
+       SET_ENTRY_SIZE(__vfork14)
diff --git a/lib/nbsd_libc/arch/sh3/sys/brk.S b/lib/nbsd_libc/arch/sh3/sys/brk.S
new file mode 100644 (file)
index 0000000..b6f26c1
--- /dev/null
@@ -0,0 +1,98 @@
+/*     $NetBSD: brk.S,v 1.10 2006/01/06 03:58:31 uwe Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)brk.s 5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: brk.S,v 1.10 2006/01/06 03:58:31 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(brk,_brk)
+#endif
+
+       .data
+       .globl  _C_LABEL(__minbrk)
+       .align  2
+_C_LABEL(__minbrk):
+       .long   _end
+
+       .text
+
+ENTRY(_brk)
+#ifdef PIC
+       mova    L_GOT, r0
+       mov.l   L_GOT, r2
+       add     r0, r2
+       mov.l   Lminbrk, r0
+       mov.l   @(r0, r2), r0
+       mov.l   @r0, r0
+#else
+       mov.l   Lminbrk, r0
+       mov.l   @r0, r0
+#endif
+       cmp/hs  r4, r0
+       bf      1f
+       mov     r0, r4
+1:
+       mov.l   LSYS_break, r0
+       trapa   #0x80
+       bf      err
+#ifdef PIC
+       mov.l   Lcurbrk, r0
+       mov.l   @(r0, r2), r1
+       xor     r0, r0
+#else
+       xor     r0, r0
+       mov.l   Lcurbrk, r1
+#endif
+       rts
+       mov.l   r4, @r1
+err:
+       JUMP_CERROR
+
+       .align  2
+LSYS_break:    .long   SYS_break
+#ifdef PIC
+L_GOT:         .long   _GLOBAL_OFFSET_TABLE_
+Lminbrk:       .long   _C_LABEL(__minbrk)@GOT
+Lcurbrk:       .long   curbrk@GOT
+#else
+Lminbrk:       .long   _C_LABEL(__minbrk)
+Lcurbrk:       .long   curbrk
+#endif
+       SET_ENTRY_SIZE(_brk)
diff --git a/lib/nbsd_libc/arch/sh3/sys/cerror.S b/lib/nbsd_libc/arch/sh3/sys/cerror.S
new file mode 100644 (file)
index 0000000..9d8c552
--- /dev/null
@@ -0,0 +1,99 @@
+/*     $NetBSD: cerror.S,v 1.10 2006/01/06 05:14:39 uwe Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)cerror.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: cerror.S,v 1.10 2006/01/06 05:14:39 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+#ifdef _REENTRANT
+
+
+       .globl  _C_LABEL(__errno)
+
+       .align  2
+cerror:
+       mov.l   .L___errno, r1
+       PIC_PROLOGUE(.L_got)
+       sts.l   pr, @-sp
+1:     CALL    r1
+        mov.l  r4, @-sp        ! save error code
+       mov.l   @sp+, r4
+       lds.l   @sp+, pr
+       PIC_EPILOGUE
+       mov.l   r4, @r0
+       mov     #-1, r1
+       rts
+        mov    #-1, r0
+
+       .align  2
+.L_got:                PIC_GOT_DATUM
+.L___errno:    CALL_DATUM(_C_LABEL(__errno), 1b)
+       SET_ASENTRY_SIZE(cerror)
+
+#else /* !_REENTRANT */
+
+
+       .globl  _C_LABEL(errno)
+
+       .align  2
+cerror:
+#ifdef PIC
+       mova    L_GOT, r0
+       mov.l   L_GOT, r1
+       add     r0, r1
+       mov.l   L_errno, r0
+       mov.l   @(r0, r1), r1
+       mov.l   r4, @r1
+#else
+       mov.l   L_errno, r1
+       mov.l   r4, @r1
+#endif
+       mov     #-1, r0
+       rts
+        mov    #-1, r1
+
+       .align  2
+#ifdef PIC
+L_GOT:         .long   _GLOBAL_OFFSET_TABLE_
+L_errno:       .long   _C_LABEL(errno)@GOT
+#else
+L_errno:       .long   _C_LABEL(errno)
+#endif
+
+#endif /* !_REENTRANT */
diff --git a/lib/nbsd_libc/arch/sh3/sys/exect.S b/lib/nbsd_libc/arch/sh3/sys/exect.S
new file mode 100644 (file)
index 0000000..a4f2a9e
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: exect.S,v 1.5 2006/01/06 01:53:30 uwe Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)exect.s       5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: exect.S,v 1.5 2006/01/06 01:53:30 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+PSEUDO(exect,execve)
diff --git a/lib/nbsd_libc/arch/sh3/sys/fork.S b/lib/nbsd_libc/arch/sh3/sys/fork.S
new file mode 100644 (file)
index 0000000..5448955
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: fork.S,v 1.10 2006/01/06 05:11:29 uwe Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)fork.s        5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: fork.S,v 1.10 2006/01/06 05:11:29 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+/*
+ * pid = fork();
+ *
+ * r1 == 0 in parent process, r1 == 1 in child process.
+ * r0 == pid of child in parent, r0 == pid of parent in child.
+ *
+ */
+ENTRY(__fork)
+       mov     #SYS_fork, r0
+       trapa   #0x80
+       bf      err
+
+       add     #0xff, r1       /* from 1 to 0 in child, 0 to -1 in parent */
+       rts
+        and    r1, r0          /* 0 in child, child pid in parent */
+
+err:
+       JUMP_CERROR
+
+       SET_ENTRY_SIZE(__fork)
diff --git a/lib/nbsd_libc/arch/sh3/sys/getcontext.S b/lib/nbsd_libc/arch/sh3/sys/getcontext.S
new file mode 100644 (file)
index 0000000..91ca4a9
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: getcontext.S,v 1.3 2008/04/28 20:22:57 martin Exp $    */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: getcontext.S,v 1.3 2008/04/28 20:22:57 martin Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h" 
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext,_getcontext)
+#endif
+
+_SYSCALL(_getcontext,getcontext) 
+       sts     pr, r2
+       mov.l   r2, @(36 + 1 * 4, r4)   /* saved pc <- pr */
+       add     #36 + 20 * 4, r4
+       rts
+        mov.l  r0, @r4                 /* arrange for return value 0 */
diff --git a/lib/nbsd_libc/arch/sh3/sys/pipe.S b/lib/nbsd_libc/arch/sh3/sys/pipe.S
new file mode 100644 (file)
index 0000000..11c6b95
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: pipe.S,v 1.7 2006/01/06 05:23:46 uwe Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)pipe.s        5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: pipe.S,v 1.7 2006/01/06 05:23:46 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe,_pipe)
+#endif
+
+_SYSCALL(_pipe,pipe)
+       mov.l   r0, @r4
+       mov.l   r1, @(4, r4)
+       rts
+        mov    #0, r0
diff --git a/lib/nbsd_libc/arch/sh3/sys/ptrace.S b/lib/nbsd_libc/arch/sh3/sys/ptrace.S
new file mode 100644 (file)
index 0000000..be78d6c
--- /dev/null
@@ -0,0 +1,111 @@
+/*     $NetBSD: ptrace.S,v 1.8 2006/01/06 20:38:01 uwe Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)ptrace.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: ptrace.S,v 1.8 2006/01/06 20:38:01 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+/*
+ * int
+ * ptrace(int request, pid_t pid, caddr_t addr, int data);
+ */
+ENTRY(ptrace)
+#ifdef _REENTRANT
+
+       mov.l   .L___errno, r1
+       PIC_PROLOGUE(.L_GOT)
+       sts.l   pr, @-sp
+       mov.l   r7, @-sp
+       mov.l   r6, @-sp
+       mov.l   r5, @-sp
+1:     CALL    r1
+        mov.l  r4, @-sp
+       mov.l   @sp+, r4
+       mov.l   @sp+, r5
+       mov.l   @sp+, r6
+       mov.l   @sp+, r7
+       lds.l   @sp+, pr
+       PIC_EPILOGUE
+
+#else  /* ! _REENTRANT */
+
+#ifdef PIC
+       mova    .L_GOT, r0
+       mov.l   .L_GOT, r1
+       add     r0, r1
+       mov.l   .L_errno, r0
+       mov.l   @(r0, r1), r0
+#else
+       mov.l   .L_errno, r0
+#endif
+
+#endif /* ! _REENTRANT */
+
+       mov     #0, r1
+       mov.l   r1, @r0                 /* errno = 0; */
+
+       mov     #SYS_ptrace, r0
+       trapa   #0x80
+       bf      err
+       rts
+        nop
+err:
+       JUMP_CERROR
+
+       .align  2
+.L_GOT:
+       PIC_GOT_DATUM
+
+#ifdef _REENTRANT
+       .global _C_LABEL(__errno)
+.L___errno:
+       CALL_DATUM(_C_LABEL(__errno), 1b)
+
+#else  /* ! _REENTRANT */
+       .global _C_LABEL(errno)
+.L_errno:
+#ifdef PIC
+       .long   PIC_GOT(_C_LABEL(errno))
+#else
+       .long   _C_LABEL(errno)
+#endif
+
+#endif /* ! _REENTRANT */
+
+       SET_ENTRY_SIZE(ptrace)
diff --git a/lib/nbsd_libc/arch/sh3/sys/sbrk.S b/lib/nbsd_libc/arch/sh3/sys/sbrk.S
new file mode 100644 (file)
index 0000000..75351c7
--- /dev/null
@@ -0,0 +1,92 @@
+/*     $NetBSD: sbrk.S,v 1.9 2006/01/06 03:58:31 uwe Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sbrk.s        5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: sbrk.S,v 1.9 2006/01/06 03:58:31 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _end
+       .globl  curbrk
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(sbrk,_sbrk)
+#endif
+
+       .data
+curbrk:        .long   _end
+       .text
+
+ENTRY(_sbrk)
+       mov     r4, r2
+#ifdef PIC
+       mova    L_GOT, r0
+       mov.l   L_GOT, r3
+       add     r0, r3
+       mov.l   Lcurbrk, r0
+       mov.l   @(r0, r3), r0
+#else
+       mov.l   Lcurbrk, r0
+#endif
+       mov.l   @r0, r0
+       add     r0, r4
+       mov.l   LSYS_break, r0
+       trapa   #0x80
+       bf      err
+#ifdef PIC
+       mov.l   Lcurbrk, r0
+       mov.l   @(r0, r3), r1
+#else
+       mov.l   Lcurbrk, r1
+#endif
+       mov.l   @r1, r0
+       add     r0, r2
+       rts
+       mov.l   r2, @r1
+err:
+       JUMP_CERROR
+
+       .align  2
+LSYS_break:    .long   SYS_break
+#ifdef PIC
+L_GOT:         .long   _GLOBAL_OFFSET_TABLE_
+Lcurbrk:       .long   curbrk@GOT
+#else
+Lcurbrk:       .long   curbrk
+#endif
+       SET_ENTRY_SIZE(_sbrk)
diff --git a/lib/nbsd_libc/arch/sh3/sys/shmat.S b/lib/nbsd_libc/arch/sh3/sys/shmat.S
new file mode 100644 (file)
index 0000000..7f57fad
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: shmat.S,v 1.1 2000/07/07 08:20:54 itohy Exp $  */
+
+#include "SYS.h"
+
+RSYSCALL(shmat)
diff --git a/lib/nbsd_libc/arch/sh3/sys/syscall.S b/lib/nbsd_libc/arch/sh3/sys/syscall.S
new file mode 100644 (file)
index 0000000..979ef83
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: syscall.S,v 1.6 2006/01/06 01:27:23 uwe Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)syscall.s     5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: syscall.S,v 1.6 2006/01/06 01:27:23 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+RSYSCALL(syscall)
diff --git a/lib/nbsd_libc/arch/sparc/Makefile.inc b/lib/nbsd_libc/arch/sparc/Makefile.inc
new file mode 100644 (file)
index 0000000..cc99fbe
--- /dev/null
@@ -0,0 +1,32 @@
+#      $NetBSD: Makefile.inc,v 1.13 2008/10/26 07:43:07 mrg Exp $
+
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S
+
+# `source' files built from m4 source
+# the name `div.o' is taken for the ANSI C `div' function, hence sdiv here
+SRCS+= rem.S sdiv.S udiv.S urem.S
+CLEANFILES+=rem.S sdiv.S udiv.S urem.S
+
+sdiv.S: ${LIBCDIR}/arch/sparc/gen/divrem.m4
+       @echo 'building ${.TARGET} from ${.ALLSRC}'
+       @(echo "define(NAME,\`.div')define(OP,\`div')define(S,\`true')"; \
+        cat ${.ALLSRC}) | ${TOOL_M4} > ${.TARGET}
+       @chmod 444 ${.TARGET}
+
+udiv.S: ${LIBCDIR}/arch/sparc/gen/divrem.m4
+       @echo 'building ${.TARGET} from ${.ALLSRC}'
+       @(echo "define(NAME,\`.udiv')define(OP,\`div')define(S,\`false')"; \
+        cat ${.ALLSRC}) | ${TOOL_M4} > ${.TARGET}
+       @chmod 444 ${.TARGET}
+
+rem.S: ${LIBCDIR}/arch/sparc/gen/divrem.m4
+       @echo 'building ${.TARGET} from ${.ALLSRC}'
+       @(echo "define(NAME,\`.rem')define(OP,\`rem')define(S,\`true')"; \
+        cat ${.ALLSRC}) | ${TOOL_M4} > ${.TARGET}
+       @chmod 444 ${.TARGET}
+
+urem.S: ${LIBCDIR}/arch/sparc/gen/divrem.m4
+       @echo 'building ${.TARGET} from ${.ALLSRC}'
+       @(echo "define(NAME,\`.urem')define(OP,\`rem')define(S,\`false')"; \
+        cat ${.ALLSRC}) | ${TOOL_M4} > ${.TARGET}
+       @chmod 444 ${.TARGET}
diff --git a/lib/nbsd_libc/arch/sparc/SYS.h b/lib/nbsd_libc/arch/sparc/SYS.h
new file mode 100644 (file)
index 0000000..5f8f3a4
--- /dev/null
@@ -0,0 +1,151 @@
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ *     @(#)SYS.h       8.1 (Berkeley) 6/4/93
+ *
+ *     from: Header: SYS.h,v 1.2 92/07/03 18:57:00 torek Exp
+ *     $NetBSD: SYS.h,v 1.17 2007/10/08 13:06:00 uwe Exp $
+ */
+
+#include <machine/asm.h>
+#include <sys/syscall.h>
+#include <machine/trap.h>
+
+#ifdef __STDC__
+#define _CAT(x,y) x##y
+#else
+#define _CAT(x,y) x/**/y
+#endif
+
+#ifdef __ELF__
+#define CERROR         _C_LABEL(__cerror)
+#define CURBRK         _C_LABEL(__curbrk)
+#else
+#define CERROR         _ASM_LABEL(cerror)
+#define CURBRK         _ASM_LABEL(curbrk)
+#endif
+
+/*
+ * ERROR branches to cerror.
+ */
+#ifdef PIC
+#define CALL(name)                             \
+       PIC_PROLOGUE(%g1, %g2);                 \
+       set     name, %g2;                      \
+       ld      [%g1 + %g2], %g2;               \
+       jmp     %g2;                            \
+        nop
+#else
+#define        CALL(name)                              \
+       set     name, %g1;                      \
+       jmp     %g1;                            \
+        nop
+#endif
+#define        ERROR() CALL(CERROR)
+
+/*
+ * SYSCALL is used when further action must be taken before returning.
+ * Note that it adds a `nop' over what we could do, if we only knew
+ * what came at label 1....
+ */
+#define        _SYSCALL(x,y)                           \
+ENTRY(x);                                      \
+       mov     _CAT(SYS_,y), %g1;              \
+       t       ST_SYSCALL;                     \
+       bcc     1f;                             \
+        nop;                                   \
+       ERROR();                                \
+1:     /* next insn */
+
+#define        SYSCALL(x)                              \
+       _SYSCALL(x,x)
+
+/*
+ * RSYSCALL is used when the system call should just return.  Here we
+ * use the SYSCALL_G2RFLAG to put the `success' return address in %g2
+ * and avoid a branch.
+ *
+ * PSEUDO(x,y) is like RSYSCALL(y), except that the name is x.
+ */
+#define        _RSYSCALL(x,y)                                  \
+ENTRY(x);                                              \
+       mov     (_CAT(SYS_,y)) | SYSCALL_G2RFLAG, %g1;  \
+       add     %o7, 8, %g2;                            \
+       t       ST_SYSCALL;                             \
+       ERROR()
+
+#define        RSYSCALL(x)     _RSYSCALL(x,x)
+#define        PSEUDO(x,y)     _RSYSCALL(x,y)
+
+/*
+ * WSYSCALL(weak,strong) is like RSYSCALL(weak),
+ * except that weak is a weak internal alias for the strong symbol.
+ */
+#ifdef WEAK_ALIAS
+#define        WSYSCALL(weak,strong)                   \
+       WEAK_ALIAS(weak,strong);                \
+       PSEUDO(strong,weak)
+#else
+#define        WSYSCALL(weak,strong)                   \
+       RSYSCALL(weak)
+#endif
+
+/*
+ * SYSCALL_NOERROR is like SYSCALL, except it's used for syscalls that
+ * never fail.
+ *
+ * XXX - This should be optimized.
+ */
+#define SYSCALL_NOERROR(x)                     \
+ENTRY(x);                                      \
+       mov     _CAT(SYS_,x), %g1;              \
+       t       ST_SYSCALL
+
+/*
+ * RSYSCALL_NOERROR is like RSYSCALL, except it's used for syscalls
+ * that never fail.
+ *
+ * PSEUDO_NOERROR(x,y) is like RSYSCALL_NOERROR(y), except that the
+ * name is x.
+ *
+ * XXX - This should be optimized.
+ */
+#define _RSYSCALL_NOERROR(x,y)                         \
+ENTRY(x);                                              \
+       mov     (_CAT(SYS_,y)) | SYSCALL_G2RFLAG, %g1;  \
+       add     %o7, 8, %g2;                            \
+       t       ST_SYSCALL
+
+#define RSYSCALL_NOERROR(x)    _RSYSCALL_NOERROR(x,x)
+#define PSEUDO_NOERROR(x,y)    _RSYSCALL_NOERROR(x,y)
+
+       .globl  CERROR
diff --git a/lib/nbsd_libc/arch/sparc/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/sparc/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..1d786e0
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/15 17:35:18 kleink Exp $
+
+SRCS+= strtof.c
diff --git a/lib/nbsd_libc/arch/sparc/gdtoa/arith.h b/lib/nbsd_libc/arch/sparc/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..4674f62
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: arith.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define IEEE_BIG_ENDIAN
diff --git a/lib/nbsd_libc/arch/sparc/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/sparc/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..75f636b
--- /dev/null
@@ -0,0 +1,5 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define f_QNAN 0x7fc00000
+#define d_QNAN0 0x7ff80000
+#define d_QNAN1 0x0
diff --git a/lib/nbsd_libc/arch/sparc/gen/Makefile.inc b/lib/nbsd_libc/arch/sparc/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..dae1231
--- /dev/null
@@ -0,0 +1,29 @@
+#      $NetBSD: Makefile.inc,v 1.22 2009/12/06 07:12:17 uebayasi Exp $
+
+SRCS+= fabs.S modf.S
+SRCS+= flt_rounds.c fpgetmask.c fpgetround.c fpgetsticky.c fpsetmask.c \
+       fpsetround.c fpsetsticky.c
+
+# Common ieee754 constants and functions
+SRCS+= infinityf_ieee754.c infinity_ieee754.c infinityl_dbl_ieee754.c
+SRCS+= fpclassifyf_ieee754.c fpclassifyd_ieee754.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c
+SRCS+= isfinitef_ieee754.c isfinited_ieee754.c
+SRCS+= signbitf_ieee754.c signbitd_ieee754.c
+
+SRCS+= nanf.c
+
+SRCS+= setjmp.S longjmp.c
+SRCS+= _setjmp.S
+SRCS+= sigsetjmp.S
+
+SRCS+= makecontext.c resumecontext.c _lwp.c swapcontext.S
+
+SRCS+= fixunsdfsi.S mul.S umul.S saveregs.S
+SRCS+= bswap16.c bswap32.c bswap64.c
+
+LSRCS.sparc.gen=       Lint_swapcontext.c
+LSRCS+=                ${LSRCS.sparc.gen}
+DPSRCS+=       ${LSRCS.sparc.gen}
+CLEANFILES+=   ${LSRCS.sparc.gen}
diff --git a/lib/nbsd_libc/arch/sparc/gen/_lwp.c b/lib/nbsd_libc/arch/sparc/gen/_lwp.c
new file mode 100644 (file)
index 0000000..a8a91e8
--- /dev/null
@@ -0,0 +1,73 @@
+/*     $NetBSD: _lwp.c,v 1.5 2008/04/28 20:22:57 martin Exp $  */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.5 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+
+void
+_lwp_makecontext(ucontext_t *u, void (*start)(void *), void *arg,
+                void *private, caddr_t stack_base, size_t stack_size)
+{
+       __greg_t *gr;
+       unsigned long *sp;
+
+       getcontext(u);
+       gr = u->uc_mcontext.__gregs;
+
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+
+
+       sp = (ulong *)(stack_base + stack_size);
+       sp = (ulong *)((ulong)sp & ~0x07);
+
+       /* Make room for the fake caller stack frame (CCFSZ, only in words) */
+       sp -= 8 + 8 + 1 + 6 + 1;
+
+       /* Entering (*start)(arg), return is to _lwp_exit */
+       gr[_REG_PC] = (ulong) start;
+       gr[_REG_nPC] = (ulong) start + 4;
+       gr[_REG_O0] = (ulong)arg;
+       gr[_REG_O6] = (ulong)sp;
+       gr[_REG_O7] = (ulong)_lwp_exit - 8;
+
+       /* XXX: uwe: why do we need this? */
+       /* create loopback in the window save area on the stack? */
+       sp[8+6] = (ulong)sp;            /* %i6 */
+       sp[8+7] = (ulong)_lwp_exit - 8; /* %i7 */
+}
diff --git a/lib/nbsd_libc/arch/sparc/gen/_setjmp.S b/lib/nbsd_libc/arch/sparc/gen/_setjmp.S
new file mode 100644 (file)
index 0000000..3c593f4
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: _setjmp.S,v 1.8 2008/04/28 20:22:57 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Paul Kranenburg.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+#include <machine/trap.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+RCSID("$NetBSD: _setjmp.S,v 1.8 2008/04/28 20:22:57 martin Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     _longjmp(a,v)
+ * will generate a "return(v?v:1)" from
+ * the last call to
+ *     _setjmp(a)
+ * The previous signal state is NOT restored.
+ */
+
+ENTRY(_setjmp)
+       st      %sp, [%o0+0]    /* store caller's stack pointer */
+       st      %o7, [%o0+4]    /* and the return pc */
+       retl
+        clr    %o0             ! return 0
+
+ENTRY(_longjmp)
+       sub     %sp, 64, %sp    ! set up a local stack frame
+       tst     %o1             ! compute v ? v : 1
+       be,a    0f
+        mov    1, %o1
+0:
+       t       ST_FLUSHWIN     ! flush register windows out to the stack
+
+       /*
+        * We restore the saved stack pointer to %fp, then issue
+        * a `restore' instruction which will reload the register
+        * window from the stack.
+        */
+       ld      [%o0+4], %o7    /* restore return pc */
+       ld      [%o0+0], %fp    /* and stack pointer */
+
+       retl                    ! success, return %o1
+        restore        %o1, 0, %o0
diff --git a/lib/nbsd_libc/arch/sparc/gen/divrem.m4 b/lib/nbsd_libc/arch/sparc/gen/divrem.m4
new file mode 100644 (file)
index 0000000..601fd9c
--- /dev/null
@@ -0,0 +1,272 @@
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: divrem.m4,v 1.4 92/06/25 13:23:57 torek Exp
+ * $NetBSD: divrem.m4,v 1.5 2003/08/07 16:42:23 agc Exp $
+ */
+
+/*
+ * Division and remainder, from Appendix E of the Sparc Version 8
+ * Architecture Manual, with fixes from Gordon Irlam.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       .asciz "@(#)divrem.m4   8.1 (Berkeley) 6/4/93"
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Input: dividend and divisor in %o0 and %o1 respectively.
+ *
+ * m4 parameters:
+ *  NAME       name of function to generate
+ *  OP         OP=div => %o0 / %o1; OP=rem => %o0 % %o1
+ *  S          S=true => signed; S=false => unsigned
+ *
+ * Algorithm parameters:
+ *  N          how many bits per iteration we try to get (4)
+ *  WORDSIZE   total number of bits (32)
+ *
+ * Derived constants:
+ *  TWOSUPN    2^N, for label generation (m4 exponentiation currently broken)
+ *  TOPBITS    number of bits in the top `decade' of a number
+ *
+ * Important variables:
+ *  Q          the partial quotient under development (initially 0)
+ *  R          the remainder so far, initially the dividend
+ *  ITER       number of main division loop iterations required;
+ *             equal to ceil(log2(quotient) / N).  Note that this
+ *             is the log base (2^N) of the quotient.
+ *  V          the current comparand, initially divisor*2^(ITER*N-1)
+ *
+ * Cost:
+ *  Current estimate for non-large dividend is
+ *     ceil(log2(quotient) / N) * (10 + 7N/2) + C
+ *  A large dividend is one greater than 2^(31-TOPBITS) and takes a
+ *  different path, as the upper bits of the quotient must be developed
+ *  one bit at a time.
+ */
+
+define(N, `4')
+define(TWOSUPN, `16')
+define(WORDSIZE, `32')
+define(TOPBITS, eval(WORDSIZE - N*((WORDSIZE-1)/N)))
+
+define(dividend, `%o0')
+define(divisor, `%o1')
+define(Q, `%o2')
+define(R, `%o3')
+define(ITER, `%o4')
+define(V, `%o5')
+
+/* m4 reminder: ifelse(a,b,c,d) => if a is b, then c, else d */
+define(T, `%g1')
+define(SC, `%g7')
+ifelse(S, `true', `define(SIGN, `%g6')')
+
+/*
+ * This is the recursive definition for developing quotient digits.
+ *
+ * Parameters:
+ *  $1 the current depth, 1 <= $1 <= N
+ *  $2 the current accumulation of quotient bits
+ *  N  max depth
+ *
+ * We add a new bit to $2 and either recurse or insert the bits in
+ * the quotient.  R, Q, and V are inputs and outputs as defined above;
+ * the condition codes are expected to reflect the input R, and are
+ * modified to reflect the output R.
+ */
+define(DEVELOP_QUOTIENT_BITS,
+`      ! depth $1, accumulated bits $2
+       bl      L.$1.eval(TWOSUPN+$2)
+       srl     V,1,V
+       ! remainder is positive
+       subcc   R,V,R
+       ifelse($1, N,
+       `       b       9f
+               add     Q, ($2*2+1), Q
+       ', `    DEVELOP_QUOTIENT_BITS(incr($1), `eval(2*$2+1)')')
+L.$1.eval(TWOSUPN+$2):
+       ! remainder is negative
+       addcc   R,V,R
+       ifelse($1, N,
+       `       b       9f
+               add     Q, ($2*2-1), Q
+       ', `    DEVELOP_QUOTIENT_BITS(incr($1), `eval(2*$2-1)')')
+       ifelse($1, 1, `9:')')
+
+#include <machine/asm.h>
+#include <machine/trap.h>
+
+FUNC(NAME)
+ifelse(S, `true',
+`      ! compute sign of result; if neither is negative, no problem
+       orcc    divisor, dividend, %g0  ! either negative?
+       bge     2f                      ! no, go do the divide
+       ifelse(OP, `div',
+               `xor    divisor, dividend, SIGN',
+               `mov    dividend, SIGN')        ! compute sign in any case
+       tst     divisor
+       bge     1f
+       tst     dividend
+       ! divisor is definitely negative; dividend might also be negative
+       bge     2f                      ! if dividend not negative...
+       neg     divisor                 ! in any case, make divisor nonneg
+1:     ! dividend is negative, divisor is nonnegative
+       neg     dividend                ! make dividend nonnegative
+2:
+')
+       ! Ready to divide.  Compute size of quotient; scale comparand.
+       orcc    divisor, %g0, V
+       bnz     1f
+       mov     dividend, R
+
+               ! Divide by zero trap.  If it returns, return 0 (about as
+               ! wrong as possible, but that is what SunOS does...).
+               t       ST_DIV0
+               retl
+               clr     %o0
+
+1:
+       cmp     R, V                    ! if divisor exceeds dividend, done
+       blu     Lgot_result             ! (and algorithm fails otherwise)
+       clr     Q
+       sethi   %hi(1 << (WORDSIZE - TOPBITS - 1)), T
+       cmp     R, T
+       blu     Lnot_really_big
+       clr     ITER
+
+       ! `Here the dividend is >= 2^(31-N) or so.  We must be careful here,
+       ! as our usual N-at-a-shot divide step will cause overflow and havoc.
+       ! The number of bits in the result here is N*ITER+SC, where SC <= N.
+       ! Compute ITER in an unorthodox manner: know we need to shift V into
+       ! the top decade: so do not even bother to compare to R.'
+       1:
+               cmp     V, T
+               bgeu    3f
+               mov     1, SC
+               sll     V, N, V
+               b       1b
+               inc     ITER
+
+       ! Now compute SC.
+       2:      addcc   V, V, V
+               bcc     Lnot_too_big
+               inc     SC
+
+               ! We get here if the divisor overflowed while shifting.
+               ! This means that R has the high-order bit set.
+               ! Restore V and subtract from R.
+               sll     T, TOPBITS, T   ! high order bit
+               srl     V, 1, V         ! rest of V
+               add     V, T, V
+               b       Ldo_single_div
+               dec     SC
+
+       Lnot_too_big:
+       3:      cmp     V, R
+               blu     2b
+               nop
+               be      Ldo_single_div
+               nop
+       /* NB: these are commented out in the V8-Sparc manual as well */
+       /* (I do not understand this) */
+       ! V > R: went too far: back up 1 step
+       !       srl     V, 1, V
+       !       dec     SC
+       ! do single-bit divide steps
+       !
+       ! We have to be careful here.  We know that R >= V, so we can do the
+       ! first divide step without thinking.  BUT, the others are conditional,
+       ! and are only done if R >= 0.  Because both R and V may have the high-
+       ! order bit set in the first step, just falling into the regular
+       ! division loop will mess up the first time around.
+       ! So we unroll slightly...
+       Ldo_single_div:
+               deccc   SC
+               bl      Lend_regular_divide
+               nop
+               sub     R, V, R
+               mov     1, Q
+               b       Lend_single_divloop
+               nop
+       Lsingle_divloop:
+               sll     Q, 1, Q
+               bl      1f
+               srl     V, 1, V
+               ! R >= 0
+               sub     R, V, R
+               b       2f
+               inc     Q
+       1:      ! R < 0
+               add     R, V, R
+               dec     Q
+       2:
+       Lend_single_divloop:
+               deccc   SC
+               bge     Lsingle_divloop
+               tst     R
+               b,a     Lend_regular_divide
+
+Lnot_really_big:
+1:
+       sll     V, N, V
+       cmp     V, R
+       bleu    1b
+       inccc   ITER
+       be      Lgot_result
+       dec     ITER
+
+       tst     R       ! set up for initial iteration
+Ldivloop:
+       sll     Q, N, Q
+       DEVELOP_QUOTIENT_BITS(1, 0)
+Lend_regular_divide:
+       deccc   ITER
+       bge     Ldivloop
+       tst     R
+       bl,a    Lgot_result
+       ! non-restoring fixup here (one instruction only!)
+ifelse(OP, `div',
+`      dec     Q
+', `   add     R, divisor, R
+')
+
+Lgot_result:
+ifelse(S, `true',
+`      ! check to see if answer should be < 0
+       tst     SIGN
+       bl,a    1f
+       ifelse(OP, `div', `neg Q', `neg R')
+1:')
+       retl
+       ifelse(OP, `div', `mov Q, %o0', `mov R, %o0')
diff --git a/lib/nbsd_libc/arch/sparc/gen/fabs.S b/lib/nbsd_libc/arch/sparc/gen/fabs.S
new file mode 100644 (file)
index 0000000..ef7dafa
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: fabs.S,v 1.4 2003/08/07 16:42:23 agc Exp $     */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: fabs.s,v 1.4 91/10/07 23:59:05 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)fabs.s      8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: fabs.S,v 1.4 2003/08/07 16:42:23 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* fabs - floating absolute value */
+
+
+ENTRY(fabs)
+       std     %o0, [%sp + 32]         ! return value => %f0:f1
+       ldd     [%sp + 32], %f0         ! (via kernel %o0/%o1 slot)
+       retl
+        fabss  %f0, %f0                ! return absolute value
diff --git a/lib/nbsd_libc/arch/sparc/gen/fixunsdfsi.S b/lib/nbsd_libc/arch/sparc/gen/fixunsdfsi.S
new file mode 100644 (file)
index 0000000..504917f
--- /dev/null
@@ -0,0 +1,93 @@
+/*     $NetBSD: fixunsdfsi.S,v 1.5 2003/08/07 16:42:23 agc Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: fixunsdfsi.s,v 1.3 91/10/08 00:03:15 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)fixunsdfsi.s        8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: fixunsdfsi.S,v 1.5 2003/08/07 16:42:23 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Convert double to unsigned integer (for gcc).
+ *
+ * I have made the output for NaN agree with the Sun compiler, not
+ * that it really matters, by using `fbul,a'.
+ */
+
+
+       .align  8
+Lbig:
+       .word   0x41e00000              ! .double 0r2147483648.0e+00
+       .word   0                       ! (who me, not trust the assembler?)
+
+ENTRY(__fixunsdfsi)
+       sub     %sp, 8, %sp
+       std     %o0, [%sp + 64]         ! get argument into fpu reg
+       ldd     [%sp + 64], %f0
+#ifdef PIC
+       PICCY_SET(Lbig, %g1, %o0)
+       ldd     [%g1], %f2
+#else
+       sethi   %hi(Lbig), %g1
+       ldd     [%g1 + %lo(Lbig)], %f2
+#endif
+       fcmped  %f0, %f2                ! d < 2^31, or NaN, or -Inf?
+       nop                             ! (fpop2 delay)
+       fbul,a  1f                      ! if so, use fdtoi to convert to int
+       fdtoi   %f0, %f0                !        (this includes negatives!)
+
+       ! d does not fit in an int, so subtract 2^31, convert,
+       ! and add 2^31 again (sigh).  Just hope the intermediate
+       ! fits (if not, the result is undefined anyway).
+
+       fsubd   %f0, %f2, %f0           ! d -= 2^31
+       fdtoi   %f0, %f0                ! convert to int
+       st      %f0, [%sp + 64]         ! move into return reg
+       ld      [%sp + 64], %o0
+       sethi   %hi(0x80000000), %o1
+       add     %o0, %o1, %o0           ! add 2^31
+       retl
+       add     %sp, 8, %sp
+
+1:
+       st      %f0, [%sp + 64]         ! return result
+       ld      [%sp + 64], %o0
+       retl
+       add     %sp, 8, %sp
diff --git a/lib/nbsd_libc/arch/sparc/gen/flt_rounds.c b/lib/nbsd_libc/arch/sparc/gen/flt_rounds.c
new file mode 100644 (file)
index 0000000..7f67483
--- /dev/null
@@ -0,0 +1,30 @@
+/*     $NetBSD: flt_rounds.c,v 1.6 2005/12/24 23:10:08 perry Exp $     */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: flt_rounds.c,v 1.6 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <machine/float.h>
+
+static const int map[] = {
+       1,      /* round to nearest */
+       0,      /* round to zero */
+       2,      /* round to positive infinity */
+       3       /* round to negative infinity */
+};
+
+int
+__flt_rounds()
+{
+       int x;
+
+       __asm("st %%fsr,%0" : "=m" (*&x));
+       return map[(x >> 30) & 0x03];
+}
diff --git a/lib/nbsd_libc/arch/sparc/gen/fpgetmask.c b/lib/nbsd_libc/arch/sparc/gen/fpgetmask.c
new file mode 100644 (file)
index 0000000..0639cb8
--- /dev/null
@@ -0,0 +1,28 @@
+/*     $NetBSD: fpgetmask.c,v 1.5 2005/12/24 23:10:08 perry Exp $      */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetmask.c,v 1.5 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetmask,_fpgetmask)
+#endif
+
+fp_except
+fpgetmask()
+{
+       int x;
+
+       __asm("st %%fsr,%0" : "=m" (*&x));
+       return (x >> 23) & 0x1f;
+}
diff --git a/lib/nbsd_libc/arch/sparc/gen/fpgetround.c b/lib/nbsd_libc/arch/sparc/gen/fpgetround.c
new file mode 100644 (file)
index 0000000..2dffecf
--- /dev/null
@@ -0,0 +1,28 @@
+/*     $NetBSD: fpgetround.c,v 1.5 2005/12/24 23:10:08 perry Exp $     */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetround.c,v 1.5 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetround,_fpgetround)
+#endif
+
+fp_rnd
+fpgetround()
+{
+       int x;
+
+       __asm("st %%fsr,%0" : "=m" (*&x));
+       return (x >> 30) & 0x03;
+}
diff --git a/lib/nbsd_libc/arch/sparc/gen/fpgetsticky.c b/lib/nbsd_libc/arch/sparc/gen/fpgetsticky.c
new file mode 100644 (file)
index 0000000..ebff93f
--- /dev/null
@@ -0,0 +1,28 @@
+/*     $NetBSD: fpgetsticky.c,v 1.5 2005/12/24 23:10:08 perry Exp $    */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetsticky.c,v 1.5 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetsticky,_fpgetsticky)
+#endif
+
+fp_except
+fpgetsticky()
+{
+       int x;
+
+       __asm("st %%fsr,%0" : "=m" (*&x));
+       return (x >> 5) & 0x1f;
+}
diff --git a/lib/nbsd_libc/arch/sparc/gen/fpsetmask.c b/lib/nbsd_libc/arch/sparc/gen/fpsetmask.c
new file mode 100644 (file)
index 0000000..99ca472
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: fpsetmask.c,v 1.5 2005/12/24 23:10:08 perry Exp $      */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetmask.c,v 1.5 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetmask,_fpsetmask)
+#endif
+
+fp_except
+fpsetmask(mask)
+       fp_except mask;
+{
+       fp_except old;
+       fp_except new;
+
+       __asm("st %%fsr,%0" : "=m" (*&old));
+
+       new = old;
+       new &= ~(0x1f << 23); 
+       new |= ((mask & 0x1f) << 23);
+
+       __asm("ld %0,%%fsr" : : "m" (*&new));
+
+       return (old >> 23) & 0x1f;
+}
diff --git a/lib/nbsd_libc/arch/sparc/gen/fpsetround.c b/lib/nbsd_libc/arch/sparc/gen/fpsetround.c
new file mode 100644 (file)
index 0000000..122feb2
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: fpsetround.c,v 1.5 2005/12/24 23:10:08 perry Exp $     */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetround.c,v 1.5 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetround,_fpsetround)
+#endif
+
+fp_rnd
+fpsetround(rnd_dir)
+       fp_rnd rnd_dir;
+{
+       fp_rnd old;
+       fp_rnd new;
+
+       __asm("st %%fsr,%0" : "=m" (*&old));
+
+       new = old;
+       new &= ~(0x03 << 30); 
+       new |= ((rnd_dir & 0x03) << 30);
+
+       __asm("ld %0,%%fsr" : : "m" (*&new));
+
+       return (old >> 30) & 0x03;
+}
diff --git a/lib/nbsd_libc/arch/sparc/gen/fpsetsticky.c b/lib/nbsd_libc/arch/sparc/gen/fpsetsticky.c
new file mode 100644 (file)
index 0000000..d070690
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: fpsetsticky.c,v 1.5 2005/12/24 23:10:08 perry Exp $    */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetsticky.c,v 1.5 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetsticky,_fpsetsticky)
+#endif
+
+fp_except
+fpsetsticky(sticky)
+       fp_except sticky;
+{
+       fp_except old;
+       fp_except new;
+
+       __asm("st %%fsr,%0" : "=m" (*&old));
+
+       new = old;
+       new &= ~(0x1f << 5); 
+       new |= ((sticky & 0x1f) << 5);
+
+       __asm("ld %0,%%fsr" : : "m" (*&new));
+
+       return (old >> 5) & 0x1f;
+}
diff --git a/lib/nbsd_libc/arch/sparc/gen/longjmp.c b/lib/nbsd_libc/arch/sparc/gen/longjmp.c
new file mode 100644 (file)
index 0000000..825e023
--- /dev/null
@@ -0,0 +1,86 @@
+/*     $NetBSD: longjmp.c,v 1.2 2008/04/28 20:22:57 martin Exp $       */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christian Limpach.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define __LIBC12_SOURCE__
+#include <setjmp.h>
+#include <compat/include/setjmp.h>
+
+/*
+ * Use setcontext to reload the stack pointer, program counter <pc,npc>, and
+ * set the return value in %o0.  The %i and %l registers will be reloaded
+ * from the place to which %sp points.
+ */
+void
+__longjmp14(jmp_buf env, int val)
+{
+       struct sigcontext *sc = (void *)env;
+       ucontext_t uc;
+
+       /* Ensure non-zero SP */
+       if (sc->sc_sp == 0)
+               goto err;
+
+       /* Initialise the fields we're going to use */
+       uc.uc_link = 0;
+
+       /*
+        * Set _UC_{SET,CLR}STACK according to SS_ONSTACK.
+        *
+        * Restore the signal mask with sigprocmask() instead of _UC_SIGMASK,
+        * since libpthread may want to interpose on signal handling.
+        */
+       uc.uc_flags = _UC_CPU | (sc->sc_onstack ? _UC_SETSTACK : _UC_CLRSTACK);
+
+       sigprocmask(SIG_SETMASK, &sc->sc_mask, NULL);
+
+       /* Extract PSR, PC, NPC and SP from jmp_buf */
+       uc.uc_mcontext.__gregs[_REG_PSR] = sc->sc_psr;
+       uc.uc_mcontext.__gregs[_REG_PC] = sc->sc_pc;
+       uc.uc_mcontext.__gregs[_REG_nPC] = sc->sc_npc;
+       uc.uc_mcontext.__gregs[_REG_O6] = sc->sc_sp;
+
+       /* Set the return value; make sure it's non-zero */
+       uc.uc_mcontext.__gregs[_REG_O0] = (val != 0 ? val : 1);
+
+       setcontext(&uc);
+
+err:
+       longjmperror();
+       abort();
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/sparc/gen/makecontext.c b/lib/nbsd_libc/arch/sparc/gen/makecontext.c
new file mode 100644 (file)
index 0000000..1742bfb
--- /dev/null
@@ -0,0 +1,75 @@
+/*     $NetBSD: makecontext.c,v 1.3 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.3 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include <inttypes.h>
+#include <stddef.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#include <stdarg.h>
+
+void
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+{
+       __greg_t *gr = ucp->uc_mcontext.__gregs;
+       int i;
+       unsigned long *sp;
+       va_list ap;
+
+       sp = (unsigned long *)
+           ((unsigned long)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size);
+       /* Make room for: rwindow, struct return pointer, argd, argx */
+       sp -= 8 + 8 + 1 + 6 + 1; /* CCFSZ, only in words */
+       /* CCFSZ provides space for up to 7 arguments, add more if necessary */
+       if (argc > 7)
+               sp -= argc - 7;
+       /* Align on double-word boundary. */
+       sp = (unsigned long *)((unsigned long)sp & ~0x7);
+
+       gr[_REG_O6] = (__greg_t)sp;
+       gr[_REG_PC] = (__greg_t)func;
+       gr[_REG_nPC] = (__greg_t)func + 4;
+       gr[_REG_O7] = (__greg_t)_resumecontext - 8;
+
+       va_start(ap, argc);
+       /* Pass up to 6 arguments in %o0..%o5. */
+       for (i = 0; i < argc && i < 6; i++)
+               gr[_REG_O0 + i] = va_arg(ap, unsigned long);
+       /* Pass any additional arguments on the stack. */
+       for (/* i = 6 */; i < argc; i++)
+               sp[8 + 8 + 1 + 6 + (i - 6)] = va_arg(ap, unsigned long);
+       va_end(ap);
+}
diff --git a/lib/nbsd_libc/arch/sparc/gen/modf.S b/lib/nbsd_libc/arch/sparc/gen/modf.S
new file mode 100644 (file)
index 0000000..f7cce29
--- /dev/null
@@ -0,0 +1,197 @@
+/*     $NetBSD: modf.S,v 1.6 2003/08/07 16:42:23 agc Exp $     */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: modf.s,v 1.3 92/06/20 00:00:54 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)modf.s      8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: modf.S,v 1.6 2003/08/07 16:42:23 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/fsr.h>
+
+/*
+ * double modf(double val, double *iptr)
+ *
+ * Returns the fractional part of `val', storing the integer part of
+ * `val' in *iptr.  Both *iptr and the return value have the same sign
+ * as `val'.
+ *
+ * Method:
+ *
+ * We use the fpu's normalization hardware to compute the integer portion
+ * of the double precision argument.  Sun IEEE double precision numbers
+ * have 52 bits of mantissa, 11 bits of exponent, and one bit of sign,
+ * with the sign occupying bit 31 of word 0, and the exponent bits 30:20
+ * of word 0.  Thus, values >= 2^52 are by definition integers.
+ *
+ * If we take a value that is in the range [+0..2^52) and add 2^52, all
+ * of the fractional bits fall out and all of the integer bits are summed
+ * with 2^52.  If we then subtract 2^52, we get those integer bits back.
+ * This must be done with rounding set to `towards 0' or `towards -inf'.
+ * `Toward -inf' fails when the value is 0 (we get -0 back)....
+ *
+ * Note that this method will work anywhere, but is machine dependent in
+ * various aspects.
+ *
+ * Stack usage:
+ *     4@[%fp - 4]     saved %fsr
+ *     4@[%fp - 8]     new %fsr with rounding set to `towards 0'
+ *     8@[%fp - 16]    space for moving between %i and %f registers
+ * Register usage:
+ *     %i0%i1          double val;
+ *     %l0             scratch
+ *     %l1             sign bit (0x80000000)
+ *     %i2             double *iptr;
+ *     %f2:f3          `magic number' 2^52, in fpu registers
+ *     %f4:f5          double v, in fpu registers
+ */
+
+       .align  8
+Lmagic:
+       .word   0x43300000      ! sign = 0, exponent = 52 + 1023, mantissa = 0
+       .word   0               ! (i.e., .double 0r4503599627370496e+00)
+
+L0:
+       .word   0               ! 0.0
+       .word   0
+
+ENTRY(modf)
+       save    %sp, -64-16, %sp
+
+       /*
+        * First, compute v = abs(val) by clearing sign bit,
+        * and then set up the fpu registers.  This would be
+        * much easier if we could do alu operations on fpu registers!
+        */
+       sethi   %hi(0x80000000), %l1    ! sign bit
+       andn    %i0, %l1, %l0
+       st      %l0, [%fp - 16]
+#ifdef PIC
+       PICCY_SET(Lmagic, %l0, %o7)
+       ldd     [%l0], %f2
+#else
+       sethi   %hi(Lmagic), %l0
+       ldd     [%l0 + %lo(Lmagic)], %f2
+#endif
+       st      %i1, [%fp - 12]
+       ldd     [%fp - 16], %f4         ! %f4:f5 = v
+
+       /*
+        * Is %f4:f5 >= %f2:f3 ?  If so, it is all integer bits.
+        * It is probably less, though.
+        */
+       fcmped  %f4, %f2
+       nop                             ! fpop2 delay
+       fbuge   Lbig                    ! if >= (or unordered), go out
+       nop
+
+       /*
+        * v < 2^52, so add 2^52, then subtract 2^52, but do it all
+        * with rounding set towards zero.  We leave any enabled
+        * traps enabled, but change the rounding mode.  This might
+        * not be so good.  Oh well....
+        */
+       st      %fsr, [%fp - 4]         ! %l5 = current FSR mode
+       set     FSR_RD, %l3             ! %l3 = rounding direction mask
+       ld      [%fp - 4], %l5
+       set     FSR_RD_RZ << FSR_RD_SHIFT, %l4
+       andn    %l5, %l3, %l6
+       or      %l6, %l4, %l6           ! round towards zero, please
+       and     %l5, %l3, %l5           ! save original rounding mode
+       st      %l6, [%fp - 8]
+       ld      [%fp - 8], %fsr
+
+       faddd   %f4, %f2, %f4           ! %f4:f5 += 2^52
+       fsubd   %f4, %f2, %f4           ! %f4:f5 -= 2^52
+
+       /*
+        * Restore %fsr, but leave exceptions accrued.
+        */
+       st      %fsr, [%fp - 4]
+       ld      [%fp - 4], %l6
+       andn    %l6, %l3, %l6           ! %l6 = %fsr & ~FSR_RD;
+       or      %l5, %l6, %l5           ! %l5 |= %l6;
+       st      %l5, [%fp - 4]
+       ld      [%fp - 4], %fsr         ! restore %fsr, leaving accrued stuff
+
+       /*
+        * Now insert the original sign in %f4:f5.
+        * This is a lot of work, so it is conditional here.
+        */
+       btst    %l1, %i0
+       be      1f
+       nop
+       st      %f4, [%fp - 16]
+       ld      [%fp - 16], %g1
+       or      %l1, %g1, %g1
+       st      %g1, [%fp - 16]
+       ld      [%fp - 16], %f4
+1:
+
+       /*
+        * The value in %f4:f5 is now the integer portion of the original
+        * argument.  We need to store this in *ival (%i2), subtract it
+        * from the original value argument (%i0:i1), and return the result.
+        */
+       std     %f4, [%i2]              ! *ival = %f4:f5;
+       std     %i0, [%fp - 16]
+       ldd     [%fp - 16], %f0         ! %f0:f1 = val;
+       fsubd   %f0, %f4, %f0           ! %f0:f1 -= %f4:f5;
+       ret
+       restore
+
+Lbig:
+       /*
+        * We get here if the original comparison of %f4:f5 (v) to
+        * %f2:f3 (2^52) came out `greater or unordered'.  In this
+        * case the integer part is the original value, and the
+        * fractional part is 0.
+        */
+#ifdef PIC
+       PICCY_SET(L0, %l0, %o7)
+       std     %f0, [%i2]              ! *ival = val;
+       ldd     [%l0], %f0              ! return 0.0;
+#else
+       sethi   %hi(L0), %l0
+       std     %f0, [%i2]              ! *ival = val;
+       ldd     [%l0 + %lo(L0)], %f0    ! return 0.0;
+#endif
+       ret
+       restore
diff --git a/lib/nbsd_libc/arch/sparc/gen/nanf.c b/lib/nbsd_libc/arch/sparc/gen/nanf.c
new file mode 100644 (file)
index 0000000..1688d0e
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: nanf.c,v 1.4 2009/02/22 01:34:02 martin Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nanf.c,v 1.4 2009/02/22 01:34:02 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+/* bytes for quiet NaN (IEEE single precision) */
+const union __float_u __nanf =
+               { { 0x7f, 0xc0,    0,    0 } };
+
+__warn_references(__nanf, "warning: <math.h> defines NAN incorrectly for your compiler.")
diff --git a/lib/nbsd_libc/arch/sparc/gen/resumecontext.c b/lib/nbsd_libc/arch/sparc/gen/resumecontext.c
new file mode 100644 (file)
index 0000000..1a7c4c5
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "extern.h"
+
+void
+_resumecontext()
+{
+       ucontext_t uct;
+
+       (void)getcontext(&uct);
+       if (uct.uc_link == NULL) 
+               exit(0);
+       (void)setcontext(uct.uc_link);
+       _exit(-1);
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/sparc/gen/setjmp.S b/lib/nbsd_libc/arch/sparc/gen/setjmp.S
new file mode 100644 (file)
index 0000000..993b927
--- /dev/null
@@ -0,0 +1,86 @@
+/*     $NetBSD: setjmp.S,v 1.11 2007/10/08 13:06:00 uwe Exp $  */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: setjmp.s,v 1.2 92/06/25 03:18:43 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)setjmp.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: setjmp.S,v 1.11 2007/10/08 13:06:00 uwe Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and a struct sigcontext, see <signal.h>
+ */
+
+#include "SYS.h"
+
+ENTRY(__setjmp14)
+       save    %sp, -CCFSZ, %sp
+       /*
+        * local vars on stack: struct sigstack foo @ offset 0x48
+        * Note: sc_g1 is not used; sc_o0 is set in longjmp()
+        */
+       mov     1, %o0          /* SIG_BLOCK */
+       add     %i0, 32, %o2    /* build sigcontext sc.sc_mask */
+       call    _C_LABEL(__sigprocmask14)
+        clr    %o1             /* sigprocmask(SIG_BLOCK, NULL, &sc.sc_mask) */
+
+       add     %sp, 0x48, %o1  /* (foo being in arg dump area) */
+       call    _C_LABEL(__sigaltstack14)
+        clr    %o0             /* sigstack(NULL, &foo) */
+
+       ld      [%sp + 0x48 + 8], %o0   /* foo.ss_flags */
+       and     %o0, 1, %o1     /* onstack = foo.ss_flags & 1; */
+       st      %o1, [%i0 + 0]  /* sc.sc_onstack = current onstack; */
+       st      %fp, [%i0 + 8]  /* sc.sc_sp = (caller's) sp */
+       add     %i7, 8, %o0
+       st      %o0, [%i0 + 12] /* sc.sc_pc = return_pc */
+       add     %i7, 12, %o0
+       st      %o0, [%i0 + 16] /* sc.sc_npc = return_pc + 4 */
+       st      %g0, [%i0 + 20] /* sc.sc_psr = (clean psr) */
+       ret                     /* return 0 */
+        restore        %g0, %g0, %o0
+
diff --git a/lib/nbsd_libc/arch/sparc/gen/sigsetjmp.S b/lib/nbsd_libc/arch/sparc/gen/sigsetjmp.S
new file mode 100644 (file)
index 0000000..44958e6
--- /dev/null
@@ -0,0 +1,93 @@
+/*     $NetBSD: sigsetjmp.S,v 1.6 2007/10/08 13:06:00 uwe Exp $        */
+/*
+ * Copyright (c) 1995 Paul Kranenburg
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Paul Kranenburg.
+ * 4. 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 ``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 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 "SYS.h"
+
+#ifdef PIC
+
+ENTRY(__sigsetjmp14)
+       PIC_PROLOGUE(%g1, %g2)          ! %g1 = _GLOBAL_OFFSET_TABLE
+       tst     %o1
+       bnz     1f
+        st     %o1, [%o0 + 56]         ! jmpbuf[JBLEN] = savemask
+
+       !! if (savemask == 0) goto _setjmp
+       set     _C_LABEL(_setjmp), %g2
+       ld      [%g1 + %g2], %g1
+       jmp %g1
+        nop
+
+       !! if (savemask != 0) goto setjmp
+1:     set     _C_LABEL(__setjmp14), %g2
+       ld      [%g1 + %g2], %g1
+       jmp %g1
+        nop
+
+
+ENTRY(__siglongjmp14)
+       PIC_PROLOGUE(%g1, %g2)          ! %g1 = _GLOBAL_OFFSET_TABLE
+       ld      [%o0 + 56], %g2         ! restoremask = jmpbuf[JBLEN]
+       tst     %g2
+       bnz     1f
+        nop
+
+       !! if (restoremask == 0) goto _longjmp
+       set     _C_LABEL(_longjmp), %g2
+       ld      [%g1 + %g2], %g1
+       jmp %g1
+        nop
+
+       !! if (restoremask != 0) goto longjmp
+1:     set     _C_LABEL(__longjmp14), %g2
+       ld      [%g1 + %g2], %g1
+       jmp %g1
+        nop
+
+#else /* !PIC */
+
+ENTRY(__sigsetjmp14)
+       cmp %o1,0
+       be _C_LABEL(_setjmp)
+       st %o1,[%o0+56]         ! jmpbuf[JBLEN]
+       nop
+       ba,a _C_LABEL(__setjmp14)
+       unimp 0
+
+ENTRY(__siglongjmp14)
+       ld [%o0+56],%g1
+       cmp %g1,0
+       be _C_LABEL(_longjmp)
+       nop
+       ba,a _C_LABEL(__longjmp14)
+       unimp 0
+
+#endif /* !PIC */
diff --git a/lib/nbsd_libc/arch/sparc/gen/swapcontext.S b/lib/nbsd_libc/arch/sparc/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..8b88d29
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: swapcontext.S,v 1.3 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: swapcontext.S,v 1.3 2008/04/28 20:22:57 martin Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+ENTRY(swapcontext)
+       mov     %o0, %o2                        ! must save pointer
+       mov     %o1, %o3                        ! must save pointer
+       mov     SYS_getcontext, %g1
+       t       ST_SYSCALL
+       bcc,a   1f
+        st     %g0, [%o2 + 40 + 11 * 4]        ! gr[_REG_O0] = 0
+       ERROR()
+1:
+       add     %o7, 12, %o1
+       st      %o1, [%o2 + 40 + 2 * 4]         ! gr[_REG_nPC] = retaddr + 4
+       add     %o7, 8, %o1
+       st      %o1, [%o2 + 40 + 1 * 4]         ! gr[_REG_PC] = retaddr
+
+       mov     %o3, %o0
+       mov     %o1, %g2                        ! optimize `return'
+       mov     SYS_setcontext|SYSCALL_G2RFLAG, %g1
+       t       ST_SYSCALL
+       ERROR()
diff --git a/lib/nbsd_libc/arch/sparc/net/Makefile.inc b/lib/nbsd_libc/arch/sparc/net/Makefile.inc
new file mode 100644 (file)
index 0000000..0279aaa
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 1995/02/25 14:59:11 cgd Exp $
+
+SRCS+=  htonl.S htons.S ntohl.S ntohs.S
diff --git a/lib/nbsd_libc/arch/sparc/stdlib/Makefile.inc b/lib/nbsd_libc/arch/sparc/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..102817f
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/08/11 17:30:43 dsl Exp $
+
+SRCS+= llabs.S
+NO_SRCS+= imaxabs.S
diff --git a/lib/nbsd_libc/arch/sparc/stdlib/llabs.S b/lib/nbsd_libc/arch/sparc/stdlib/llabs.S
new file mode 100644 (file)
index 0000000..ab81609
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: llabs.S,v 1.4 2008/08/04 21:29:28 matt Exp $   */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: abs.s,v 1.1 91/07/06 18:01:57 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "from: @(#)abs.s 8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: llabs.S,v 1.4 2008/08/04 21:29:28 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(llabs, _llabs)
+WEAK_ALIAS(imaxabs, _llabs)
+#endif
+
+/* llabs - long long int absolute value */
+/* imaxabs - intmax_t absolute value */
+
+
+#ifdef WEAK_ALIAS
+ENTRY(_llabs)
+#else
+ENTRY(llabs)
+#endif
+       tst     %o0
+       bge     1f
+        nop
+       subcc   %g0, %o1, %o1
+       subx    %g0, %o0, %o0
+1:     retl
+        nop
diff --git a/lib/nbsd_libc/arch/sparc/string/Makefile.inc b/lib/nbsd_libc/arch/sparc/string/Makefile.inc
new file mode 100644 (file)
index 0000000..ed9c5d3
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.4 2009/07/30 20:57:17 dsl Exp $
+
+SRCS+= bzero.S ffs.S memset.S strlen.S
diff --git a/lib/nbsd_libc/arch/sparc/sys/__clone.S b/lib/nbsd_libc/arch/sparc/sys/__clone.S
new file mode 100644 (file)
index 0000000..c420ded
--- /dev/null
@@ -0,0 +1,93 @@
+/*     $NetBSD: __clone.S,v 1.6 2008/04/28 20:22:57 martin Exp $       */
+
+/*-     
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *      
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(clone, __clone)
+#endif
+
+/*
+ * int __clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+ENTRY(__clone)
+       save    %sp, -CCFSZ, %sp
+
+       /*
+        * Sanity checks: func and stack may not be NULL.
+        */
+       tst     %i0
+       be      8f              ! func == NULL, bail
+        orcc   %i1, %g0, %o1   ! setup stack arg for syscall, test
+       be      8f              ! stack == NULL, bail
+        mov    %i2, %o0        ! setup flags arg for syscall
+
+       /*
+        * Allocate "caller's" frame in the child stack as ABI
+        * requires.
+        *
+        * We pass the function and the argument to the child by
+        * stashing them at the bottom of the frame.  There they are
+        * safe from window spill would we need to take one as it's
+        * below the window save area.
+        */
+       sub     %o1, CCFSZ, %o1 ! make space on the child's stack
+       st      %i0, [%o1+CCFSZ-8]      ! save func
+       st      %i3, [%o1+CCFSZ-4]      ! save arg
+
+       /*
+        * Args are now set up for system call as (flags, stack).
+        */
+       mov     SYS___clone, %g1
+       t       ST_SYSCALL
+       bcs     9f
+        tst    %o1             ! %o1 (rv[1]) == 0 in parent
+
+1:     bz      2f              ! yes, parent
+        ld     [%sp+CCFSZ-8], %l0      ! grab the function...
+       call    %l0             ! Call the clone's entry point.
+        ld     [%sp+CCFSZ-4], %o0      ! ...and the argument from the stack
+
+       CALL(_C_LABEL(_exit))
+       /* NOTREACHED */
+
+2:     ret
+        restore %g0, %o0, %o0
+
+8:     restore %g0, EINVAL, %o0
+       ERROR()
+       /* NOTREACHED */
+
+9:     restore %g0, %o0, %o0
+       ERROR()
+       /* NOTREACHED */
diff --git a/lib/nbsd_libc/arch/sparc/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/sparc/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..2632964
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.7 2008/04/28 20:22:57 martin Exp $        */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigaction14_sigtramp.c,v 1.7 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern void __sigtramp_siginfo_2(void);
+
+#ifdef __LIBC12_SOURCE__
+       /*
+        * We select the compatibility SIGCONTEXT trampoline if SA_SIGINFO
+        * is not set in the sigaction.
+        */
+       if (act && (act->sa_flags & SA_SIGINFO) == 0) {
+               extern void __sigtramp_sigcontext_1(void);
+               int sav = errno;
+               int rv =  __sigaction_sigtramp(sig, act, oact,
+                                          __sigtramp_sigcontext_1, 1);
+               /*
+                * EINVAL might indicate that trampoline version 1 is
+                * not supported by the kernel; fall back on native
+                * SIGINFO trampoline.
+                */
+               if (rv >= 0 || errno != EINVAL)
+                       return rv;
+               errno = sav;
+       }
+#endif
+
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_2, 2);
+}
diff --git a/lib/nbsd_libc/arch/sparc/sys/__sigtramp2.S b/lib/nbsd_libc/arch/sparc/sys/__sigtramp2.S
new file mode 100644 (file)
index 0000000..3cb90da
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: __sigtramp2.S,v 1.2 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Paul Kranenburg.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __sigtramp2.S,v 1.2 2008/04/28 20:22:57 martin Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+/*
+ * When this code is run, the stack looks like:
+ *     [%sp]                   struct frame
+ *     [%sp + 96]              siginfo_t
+ *     [%sp + 96 + 128]        ucontext_t
+ *         .
+ *         .
+ */
+ENTRY_NOPROFILE(__sigtramp_siginfo_2)
+       add     %sp, 96 + 128, %o0      /* get pointer to ucontext */
+       mov     SYS_setcontext, %g1
+       t       ST_SYSCALL              /* call setcontext */
+       mov     SYS_exit, %g1           /* exit with errno */
+       t       ST_SYSCALL              /* if sigreturn fails */
diff --git a/lib/nbsd_libc/arch/sparc/sys/__syscall.S b/lib/nbsd_libc/arch/sparc/sys/__syscall.S
new file mode 100644 (file)
index 0000000..1e00e42
--- /dev/null
@@ -0,0 +1,39 @@
+/*     $NetBSD: __syscall.S,v 1.2 2008/04/28 20:22:57 martin Exp $     */
+
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Paul Kranenburg.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __syscall.S,v 1.2 2008/04/28 20:22:57 martin Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+RSYSCALL(__syscall)
diff --git a/lib/nbsd_libc/arch/sparc/sys/__vfork14.S b/lib/nbsd_libc/arch/sparc/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..74cc932
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: __vfork14.S,v 1.2 2003/08/07 16:42:25 agc Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: Ovfork.s,v 1.1 91/07/06 13:05:56 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)Ovfork.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: __vfork14.S,v 1.2 2003/08/07 16:42:25 agc Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+/*
+ * pid = vfork();
+ *
+ * %o1 == 0 in parent process, 1 in child process.
+ * %o0 == pid of child in parent, pid of parent in child.
+ */
+
+#include "SYS.h"
+
+SYSCALL(__vfork14)
+       dec     %o1             ! from 1 to 0 in child, 0 to -1 in parent
+       retl
+       and     %o0, %o1, %o0   ! return 0 in child, pid in parent
diff --git a/lib/nbsd_libc/arch/sparc/sys/brk.S b/lib/nbsd_libc/arch/sparc/sys/brk.S
new file mode 100644 (file)
index 0000000..20f9969
--- /dev/null
@@ -0,0 +1,98 @@
+/*     $NetBSD: brk.S,v 1.15 2008/11/06 13:42:55 nakayama Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: brk.s,v 1.3 92/06/25 12:56:05 mccanne Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)brk.s       8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: brk.S,v 1.15 2008/11/06 13:42:55 nakayama Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  CURBRK
+       .globl  _C_LABEL(__minbrk)
+       .globl  _end
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(brk, _brk)
+#endif
+
+       .data
+_C_LABEL(__minbrk):
+       .long   _end                    ! lower brk limit; also for gmon code
+       .text
+
+ENTRY(_brk)
+#ifdef PIC
+       PIC_PROLOGUE(%o5,%o4)
+       set     _C_LABEL(__minbrk), %o4
+       ld      [%o5 + %o4], %o4
+       ld      [%o4], %o1              ! %o1 = minbrk
+       cmp     %o1, %o0                ! if (minbrk > %o0)
+       bgu,a   0f
+        mov    %o1, %o0                !       %o0 = minbrk
+0:
+       mov     %o0, %o2                ! save argument to syscall
+       mov     SYS_break, %g1
+       t       ST_SYSCALL
+       set     CURBRK, %o3
+       bcc,a   1f
+        ld     [%o5 + %o3], %o4
+       ERROR()
+1:
+       retl                            ! success, return 0 & record new break
+        st     %o2, [%o4]
+#else
+       sethi   %hi(_C_LABEL(__minbrk)), %o1    ! %o1 = minbrk
+       ld      [%o1 + %lo(_C_LABEL(__minbrk))], %o1
+       cmp     %o1, %o0                ! if (minbrk > %o0)
+       bgu,a   0f
+        mov    %o1, %o0                !       %o0 = minbrk
+0:
+       mov     %o0, %o2                ! save argument to syscall
+       mov     SYS_break, %g1
+       t       ST_SYSCALL
+       bcc,a   1f
+        sethi  %hi(CURBRK), %g1
+       ERROR()
+1:
+       retl                            ! success, return 0 & record new break
+        st     %o2, [%g1 + %lo(CURBRK)]
+#endif
diff --git a/lib/nbsd_libc/arch/sparc/sys/cerror.S b/lib/nbsd_libc/arch/sparc/sys/cerror.S
new file mode 100644 (file)
index 0000000..ee02e04
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: cerror.S,v 1.10 2007/10/08 13:06:00 uwe Exp $  */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: cerror.s,v 1.3 92/07/02 04:17:59 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)cerror.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: cerror.S,v 1.10 2007/10/08 13:06:00 uwe Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+#ifdef _REENTRANT
+FUNC(CERROR)
+       save    %sp, -CCFSZ, %sp
+       call    _C_LABEL(__errno)
+        nop
+       st      %i0, [%o0]
+       mov     -1, %i0
+       ret
+        restore %g0, -1, %o1
+#else
+       .globl  _C_LABEL(errno)
+#ifdef PIC
+FUNC(CERROR)
+       set     _C_LABEL(errno), %g2
+       ld      [%g1 + %g2], %g1
+       st      %o0, [%g1]
+       mov     -1, %o0
+       retl
+        mov    -1, %o1
+#else
+FUNC(CERROR)
+       sethi   %hi(_C_LABEL(errno)), %g1
+       st      %o0, [%g1 + %lo(_C_LABEL(errno))]
+       mov     -1, %o0
+       retl
+        mov    -1, %o1
+#endif
+#endif /* _REENTRANT */
diff --git a/lib/nbsd_libc/arch/sparc/sys/exect.S b/lib/nbsd_libc/arch/sparc/sys/exect.S
new file mode 100644 (file)
index 0000000..208cef9
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: exect.S,v 1.3 2003/08/07 16:42:25 agc Exp $    */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: exect.s,v 1.1 91/07/06 13:05:57 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)exect.s     8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: exect.S,v 1.3 2003/08/07 16:42:25 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+ENTRY(exect)
+       mov     SYS_execve, %g1 /* execve(file, argv, env) */
+       t       ST_SYSCALL
+       ERROR()
diff --git a/lib/nbsd_libc/arch/sparc/sys/fork.S b/lib/nbsd_libc/arch/sparc/sys/fork.S
new file mode 100644 (file)
index 0000000..1ffb190
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: fork.S,v 1.5 2003/08/07 16:42:25 agc Exp $     */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: fork.s,v 1.1 91/07/06 13:05:58 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)fork.s      8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: fork.S,v 1.5 2003/08/07 16:42:25 agc Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+_SYSCALL(__fork,fork)
+       dec     %o1             ! from 1 to 0 in child, 0 to -1 in parent
+       retl
+        and    %o0, %o1, %o0   ! return 0 in child, pid in parent
diff --git a/lib/nbsd_libc/arch/sparc/sys/getcontext.S b/lib/nbsd_libc/arch/sparc/sys/getcontext.S
new file mode 100644 (file)
index 0000000..d5788bb
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: getcontext.S,v 1.2 2008/04/28 20:22:57 martin Exp $    */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: getcontext.S,v 1.2 2008/04/28 20:22:57 martin Exp $")
+#endif /* SYSLIBC_SCCS && !lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext, _getcontext)
+#endif
+
+ENTRY(_getcontext)
+       mov     %o0, %o2                        ! must save pointer
+       mov     SYS_getcontext, %g1
+       t       ST_SYSCALL
+       bcc,a   1f
+        clr    [%o2 + 40 + 11 * 4]             ! gr[_REG_O0] = 0
+       ERROR()
+1:
+       add     %o7, 8, %o1
+       st      %o1, [%o2 + 40 + 1 * 4]         ! gr[_REG_PC] = retaddr
+       add     %o7, 12, %o1
+       retl
+        st     %o1, [%o2 + 40 + 2 * 4]         ! gr[_REG_nPC] = retaddr + 4
diff --git a/lib/nbsd_libc/arch/sparc/sys/pipe.S b/lib/nbsd_libc/arch/sparc/sys/pipe.S
new file mode 100644 (file)
index 0000000..457c713
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: pipe.S,v 1.4 2003/08/07 16:42:25 agc Exp $     */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: pipe.s,v 1.1 91/07/06 13:05:58 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)pipe.s      8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: pipe.S,v 1.4 2003/08/07 16:42:25 agc Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe, _pipe)
+#endif
+
+ENTRY(_pipe)
+       mov     %o0, %o2        ! save pointer
+       mov     SYS_pipe, %g1
+       t       ST_SYSCALL      ! pipe()
+       bcc,a   1f
+        st     %o0, [%o2]      ! success, store fds
+       ERROR()
+1:
+       st      %o1, [%o2 + 4]
+       retl                    ! and return 0
+        clr    %o0
diff --git a/lib/nbsd_libc/arch/sparc/sys/ptrace.S b/lib/nbsd_libc/arch/sparc/sys/ptrace.S
new file mode 100644 (file)
index 0000000..e5507bb
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: ptrace.S,v 1.8 2007/10/08 13:06:00 uwe Exp $   */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: ptrace.s,v 1.2 91/12/20 01:59:00 leres Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)ptrace.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: ptrace.S,v 1.8 2007/10/08 13:06:00 uwe Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+ENTRY(ptrace)
+#ifdef _REENTRANT
+       save    %sp, -CCFSZ, %sp
+       call    _C_LABEL(__errno)
+        nop
+       st      %g0, [%o0]
+       restore
+#else
+#ifdef PIC
+       PIC_PROLOGUE(%g1,%g2)
+       set     _C_LABEL(errno), %g2
+       ld      [%g1 + %g2], %g1
+       st      %g0, [%g1]
+#else
+       sethi   %hi(_C_LABEL(errno)), %g1
+       st      %g0, [%g1 + %lo(_C_LABEL(errno))]
+#endif
+#endif /* !_REENTRANT */
+       mov     SYS_ptrace, %g1
+       t       ST_SYSCALL
+       bcc     1f
+        nop
+       ERROR()
+1:
+       retl
+        nop
diff --git a/lib/nbsd_libc/arch/sparc/sys/sbrk.S b/lib/nbsd_libc/arch/sparc/sys/sbrk.S
new file mode 100644 (file)
index 0000000..5eebf90
--- /dev/null
@@ -0,0 +1,89 @@
+/*     $NetBSD: sbrk.S,v 1.10 2007/10/08 13:06:00 uwe Exp $    */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: sbrk.s,v 1.3 92/07/02 00:56:49 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)sbrk.s      8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: sbrk.S,v 1.10 2007/10/08 13:06:00 uwe Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _end
+       .globl  CURBRK
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(sbrk, _sbrk)
+#endif
+
+       .data
+CURBRK:        .long   _end
+       .text
+
+ENTRY(_sbrk)
+#ifdef PIC
+       PIC_PROLOGUE(%o5,%o4)
+       set     CURBRK, %o2
+       ld      [%o5 + %o2], %o2
+       ld      [%o2], %o3                      ! %o3 = old break
+       add     %o3, %o0, %o4                   ! %o4 = new break
+       mov     %o4, %o0                        ! copy for syscall
+       mov     SYS_break, %g1
+       t       ST_SYSCALL                      ! break(new_break)
+       bcc,a   1f                              ! if success,
+        mov    %o3, %o0                        !    set return value
+       ERROR()
+1:
+       retl                                    ! and update curbrk
+        st     %o4, [%o2]
+#else
+       sethi   %hi(CURBRK), %o2
+       ld      [%o2 + %lo(CURBRK)], %o3        ! %o3 = old break
+       add     %o3, %o0, %o4                   ! %o4 = new break
+       mov     %o4, %o0                        ! copy for syscall
+       mov     SYS_break, %g1
+       t       ST_SYSCALL                      ! break(new_break)
+       bcc,a   1f                              ! if success,
+        mov    %o3, %o0                        !    set return value
+       ERROR()
+1:
+       retl                                    ! and update curbrk
+        st     %o4, [%o2 + %lo(CURBRK)]
+#endif
diff --git a/lib/nbsd_libc/arch/sparc/sys/shmat.S b/lib/nbsd_libc/arch/sparc/sys/shmat.S
new file mode 100644 (file)
index 0000000..7f57fad
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: shmat.S,v 1.1 2000/07/07 08:20:54 itohy Exp $  */
+
+#include "SYS.h"
+
+RSYSCALL(shmat)
diff --git a/lib/nbsd_libc/arch/sparc/sys/syscall.S b/lib/nbsd_libc/arch/sparc/sys/syscall.S
new file mode 100644 (file)
index 0000000..b824c43
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: syscall.S,v 1.4 2003/08/07 16:42:26 agc Exp $  */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: syscall.s,v 1.1 91/07/06 13:06:02 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)syscall.s   8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: syscall.S,v 1.4 2003/08/07 16:42:26 agc Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+RSYSCALL(syscall)
diff --git a/lib/nbsd_libc/arch/sparc64/Makefile.inc b/lib/nbsd_libc/arch/sparc64/Makefile.inc
new file mode 100644 (file)
index 0000000..a3a651b
--- /dev/null
@@ -0,0 +1,50 @@
+#      $NetBSD: Makefile.inc,v 1.13 2009/12/06 07:05:50 uebayasi Exp $
+
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S
+
+# Some assembler files use v9a extensions.
+AFLAGS+= -Wa,-Av9a
+
+# `source' files built from m4 source
+# the name `div.o' is taken for the ANSI C `div' function, hence sdiv here
+SRCS+= rem.S sdiv.S udiv.S urem.S
+CLEANFILES+=rem.S sdiv.S udiv.S urem.S
+
+sdiv.S: ${LIBCDIR}/arch/sparc64/gen/divrem.m4
+       @echo 'building ${.TARGET} from ${.ALLSRC}'
+       @(echo "define(NAME,\`.div')define(OP,\`div')define(S,\`true')"; \
+        cat ${.ALLSRC}) | ${TOOL_M4} > ${.TARGET}
+       @chmod 444 ${.TARGET}
+
+udiv.S: ${LIBCDIR}/arch/sparc64/gen/divrem.m4
+       @echo 'building ${.TARGET} from ${.ALLSRC}'
+       @(echo "define(NAME,\`.udiv')define(OP,\`div')define(S,\`false')"; \
+        cat ${.ALLSRC}) | ${TOOL_M4} > ${.TARGET}
+       @chmod 444 ${.TARGET}
+
+rem.S: ${LIBCDIR}/arch/sparc64/gen/divrem.m4
+       @echo 'building ${.TARGET} from ${.ALLSRC}'
+       @(echo "define(NAME,\`.rem')define(OP,\`rem')define(S,\`true')"; \
+        cat ${.ALLSRC}) | ${TOOL_M4} > ${.TARGET}
+       @chmod 444 ${.TARGET}
+
+urem.S: ${LIBCDIR}/arch/sparc64/gen/divrem.m4
+       @echo 'building ${.TARGET} from ${.ALLSRC}'
+       @(echo "define(NAME,\`.urem')define(OP,\`rem')define(S,\`false')"; \
+        cat ${.ALLSRC}) | ${TOOL_M4} > ${.TARGET}
+       @chmod 444 ${.TARGET}
+
+.PATH: ${ARCHDIR}/softfloat
+SRCS+= qp.c
+CPPFLAGS+=     -DSOFTFLOATSPARC64_FOR_GCC
+.if ${MKSOFTFLOAT} != "no"
+.include <softfloat/Makefile.inc>
+.else
+#
+# Can't directly use softfloat.c due to .PATH issues with the other source
+# in softfloat. Just provide a wrapper which pulls it in via a #include
+SRCS.softfloat= softfloat-wrapper.c
+SRCS+= ${SRCS.softfloat}
+CPPFLAGS+=      -I${ARCHDIR}/softfloat -I${.CURDIR}/softfloat \
+               -I${.CURDIR}/softfloat/bits64
+.endif
diff --git a/lib/nbsd_libc/arch/sparc64/SYS.h b/lib/nbsd_libc/arch/sparc64/SYS.h
new file mode 100644 (file)
index 0000000..ede6a3e
--- /dev/null
@@ -0,0 +1,135 @@
+/*     $NetBSD: SYS.h,v 1.13 2003/08/07 16:42:26 agc Exp $     */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ *     @(#)SYS.h       8.1 (Berkeley) 6/4/93
+ *
+ *     from: Header: SYS.h,v 1.2 92/07/03 18:57:00 torek Exp
+ */
+
+#include <machine/asm.h>
+#include <sys/syscall.h>
+#include <machine/trap.h>
+
+#ifdef __STDC__
+#define _CAT(x,y) x##y
+#else
+#define _CAT(x,y) x/**/y
+#endif
+
+/*
+ * ERROR branches to cerror.  This is done with a macro so that I can
+ * change it to be position independent later, if need be.
+ */
+#ifdef PIC
+#ifdef BIGPIC
+#define        JUMP(name) \
+       PIC_PROLOGUE(%g1,%g5); \
+       sethi %hi(_C_LABEL(name)),%g5; \
+       or %g5,%lo(_C_LABEL(name)),%g5; \
+       ldx [%g1+%g5],%g5; \
+       jmp %g5; \
+       nop
+#else
+#define        JUMP(name) \
+       PIC_PROLOGUE(%g1,%g5); \
+       ldx [%g1+_C_LABEL(name)],%g5; jmp %g5; nop
+#endif
+#else
+#define        JUMP(name)      set _C_LABEL(name),%g1; jmp %g1; nop
+#endif
+#define        ERROR()         JUMP(__cerror)
+/*
+ * SYSCALL is used when further action must be taken before returning.
+ * Note that it adds a `nop' over what we could do, if we only knew what
+ * came at label 1....
+ */
+#define        _SYSCALL(x,y) \
+       ENTRY(x); mov _CAT(SYS_,y),%g1; t ST_SYSCALL; bcc 1f; nop; ERROR(); 1:
+
+#define        SYSCALL(x) \
+       _SYSCALL(x,x)
+
+/*
+ * RSYSCALL is used when the system call should just return.  Here
+ * we use the SYSCALL_G7RFLAG to put the `success' return address in %g7
+ * and avoid a branch.
+ */
+#define        RSYSCALL(x) \
+       ENTRY(x); mov (_CAT(SYS_,x))|SYSCALL_G7RFLAG,%g1; add %o7,8,%g7; \
+       t ST_SYSCALL; ERROR()
+
+/*
+ * PSEUDO(x,y) is like RSYSCALL(y) except that the name is x.
+ */
+#define        PSEUDO(x,y) \
+       ENTRY(x); mov (_CAT(SYS_,y))|SYSCALL_G7RFLAG,%g1; add %o7,8,%g7; \
+       t ST_SYSCALL; ERROR()
+
+/*
+ * WSYSCALL(weak,strong) is like RSYSCALL(weak), except that weak is
+ * a weak internal alias for the strong symbol.
+ */
+#define        WSYSCALL(weak,strong) \
+       WEAK_ALIAS(weak,strong); \
+       PSEUDO(strong,weak)
+
+/*
+ * SYSCALL_NOERROR is like SYSCALL, except it's used for syscalls 
+ * that never fail.
+ *
+ * XXX - This should be optimized.
+ */
+#define SYSCALL_NOERROR(x) \
+       ENTRY(x); mov _CAT(SYS_,x),%g1; t ST_SYSCALL
+
+/*
+ * RSYSCALL_NOERROR is like RSYSCALL, except it's used for syscalls 
+ * that never fail.
+ *
+ * XXX - This should be optimized.
+ */
+#define RSYSCALL_NOERROR(x) \
+       ENTRY(x); mov (_CAT(SYS_,x))|SYSCALL_G7RFLAG,%g1; add %o7,8,%g7; \
+       t ST_SYSCALL
+
+/*
+ * PSEUDO_NOERROR(x,y) is like RSYSCALL_NOERROR(y) except that the name is x.
+ */
+#define PSEUDO_NOERROR(x,y) \
+       ENTRY(x); mov (_CAT(SYS_,y))|SYSCALL_G7RFLAG,%g1; add %o7,8,%g7; \
+       t ST_SYSCALL
+
+       .register       %g7,#scratch
+
+       .globl  _C_LABEL(__cerror)
diff --git a/lib/nbsd_libc/arch/sparc64/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/sparc64/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..c13f9a7
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/15 17:35:18 kleink Exp $
+
+SRCS+= strtof.c strtold_pQ.c
+SRCS+= strtopQ.c
diff --git a/lib/nbsd_libc/arch/sparc64/gdtoa/arith.h b/lib/nbsd_libc/arch/sparc64/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..4674f62
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: arith.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define IEEE_BIG_ENDIAN
diff --git a/lib/nbsd_libc/arch/sparc64/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/sparc64/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..860e1b0
--- /dev/null
@@ -0,0 +1,9 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define f_QNAN 0x7fc00000
+#define d_QNAN0 0x7ff80000
+#define d_QNAN1 0x0
+#define ld_QNAN0 0x7fff8000
+#define ld_QNAN1 0x0
+#define ld_QNAN2 0x0
+#define ld_QNAN3 0x0
diff --git a/lib/nbsd_libc/arch/sparc64/gen/Makefile.inc b/lib/nbsd_libc/arch/sparc64/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..3753cba
--- /dev/null
@@ -0,0 +1,30 @@
+#      $NetBSD: Makefile.inc,v 1.19 2009/12/06 07:12:17 uebayasi Exp $
+
+SRCS+= fabs.S modf.S
+SRCS+= flt_rounds.c fpgetmask.c fpgetround.c fpgetsticky.c fpsetmask.c \
+       fpsetround.c fpsetsticky.c
+
+# Common ieee754 constants and functions
+SRCS+= infinityf_ieee754.c infinity_ieee754.c
+SRCS+= fpclassifyf_ieee754.c fpclassifyd_ieee754.c
+SRCS+= isfinitef_ieee754.c isfinited_ieee754.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c
+SRCS+= signbitf_ieee754.c signbitd_ieee754.c
+
+SRCS+= nanf.c infinityl.c
+SRCS+= fpclassifyl.c isfinitel.c isinfl.c isnanl.c signbitl.c
+
+SRCS+= bswap16.c bswap32.c bswap64.c
+SRCS+= setjmp.S
+SRCS+= _setjmp.S
+SRCS+= sigsetjmp.S longjmp.c
+
+SRCS+= makecontext.c resumecontext.c _lwp.c swapcontext.S
+
+SRCS+= fixunsdfsi.S mul.S umul.S saveregs.S
+
+LSRCS.sparc64.gen=Lint_swapcontext.c
+LSRCS+=                ${LSRCS.sparc64.gen}
+DPSRCS+=       ${LSRCS.sparc64.gen}
+CLEANFILES+=   ${LSRCS.sparc64.gen}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/_lwp.c b/lib/nbsd_libc/arch/sparc64/gen/_lwp.c
new file mode 100644 (file)
index 0000000..b217d28
--- /dev/null
@@ -0,0 +1,73 @@
+/*     $NetBSD: _lwp.c,v 1.5 2008/04/28 20:22:57 martin Exp $  */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.5 2008/04/28 20:22:57 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+
+void
+_lwp_makecontext(ucontext_t *u, void (*start)(void *),
+                     void *arg, void *private,
+                     caddr_t stack_base, size_t stack_size)
+{
+       __greg_t *gr;
+       unsigned long *sp;
+
+       getcontext(u);
+       gr = u->uc_mcontext.__gregs;
+
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+
+       sp = (ulong *)(stack_base + stack_size);
+       sp = (ulong *)((ulong)sp & ~0x0f);
+
+       sp -= 8 + 8 + 6;
+
+       sp[8]  = (ulong)arg;
+       sp[14] = (ulong)sp - 2047;
+       sp[15] = (ulong)_lwp_exit - 8;
+
+       sp = (ulong *)((caddr_t)sp - 2047);
+
+       gr[_REG_PC] = (ulong) start;
+       gr[_REG_nPC] = (ulong) start + 4;
+
+       gr[_REG_O0] = (ulong) arg;
+       gr[_REG_O6] = (ulong) sp;
+       gr[_REG_O7] = (ulong)_lwp_exit - 8;
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/_setjmp.S b/lib/nbsd_libc/arch/sparc64/gen/_setjmp.S
new file mode 100644 (file)
index 0000000..4990bb5
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: _setjmp.S,v 1.6 2004/12/07 08:20:07 martin Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: _setjmp.s,v 1.1 91/07/06 16:45:53 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)_setjmp.s   8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: _setjmp.S,v 1.6 2004/12/07 08:20:07 martin Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     _longjmp(a,v)
+ * will generate a "return(v?v:1)" from
+ * the last call to
+ *     _setjmp(a)
+ * The previous signal state is NOT restored.
+ */
+
+ENTRY(_setjmp)
+       stx     %sp, [%o0+0]    /* store caller's stack pointer */
+       stx     %o7, [%o0+8]    /* and return pc */
+       retl
+        clr    %o0             ! return 0
+
+ENTRY(_longjmp)
+       save    %sp, -CC64FSZ, %sp
+       flushw
+       /*
+        * We restore the saved stack pointer to %fp, then issue
+        * a `restore' instruction which will reload the register
+        * window from the stack.
+        */
+       ldx     [%i0+8], %i7
+       ldx     [%i0+0], %fp
+       mov     1, %i0
+       movrnz  %i1, %i1, %i0   ! compute v ? v : 1
+       ret
+        restore
diff --git a/lib/nbsd_libc/arch/sparc64/gen/divrem.m4 b/lib/nbsd_libc/arch/sparc64/gen/divrem.m4
new file mode 100644 (file)
index 0000000..108918e
--- /dev/null
@@ -0,0 +1,273 @@
+/*     $NetBSD: divrem.m4,v 1.4 2003/08/07 16:42:27 agc Exp $  */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: divrem.m4,v 1.4 92/06/25 13:23:57 torek Exp
+ */
+
+#include <machine/asm.h>
+#include <machine/trap.h>
+
+/*
+ * Division and remainder, from Appendix E of the Sparc Version 8
+ * Architecture Manual, with fixes from Gordon Irlam.
+ */
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: divrem.m4,v 1.4 2003/08/07 16:42:27 agc Exp $")
+#endif
+
+/*
+ * Input: dividend and divisor in %o0 and %o1 respectively.
+ *
+ * m4 parameters:
+ *  NAME       name of function to generate
+ *  OP         OP=div => %o0 / %o1; OP=rem => %o0 % %o1
+ *  S          S=true => signed; S=false => unsigned
+ *
+ * Algorithm parameters:
+ *  N          how many bits per iteration we try to get (4)
+ *  WORDSIZE   total number of bits (32)
+ *
+ * Derived constants:
+ *  TWOSUPN    2^N, for label generation (m4 exponentiation currently broken)
+ *  TOPBITS    number of bits in the top `decade' of a number
+ *
+ * Important variables:
+ *  Q          the partial quotient under development (initially 0)
+ *  R          the remainder so far, initially the dividend
+ *  ITER       number of main division loop iterations required;
+ *             equal to ceil(log2(quotient) / N).  Note that this
+ *             is the log base (2^N) of the quotient.
+ *  V          the current comparand, initially divisor*2^(ITER*N-1)
+ *
+ * Cost:
+ *  Current estimate for non-large dividend is
+ *     ceil(log2(quotient) / N) * (10 + 7N/2) + C
+ *  A large dividend is one greater than 2^(31-TOPBITS) and takes a
+ *  different path, as the upper bits of the quotient must be developed
+ *  one bit at a time.
+ */
+
+define(N, `4')
+define(TWOSUPN, `16')
+define(WORDSIZE, `32')
+define(TOPBITS, eval(WORDSIZE - N*((WORDSIZE-1)/N)))
+
+define(dividend, `%o0')
+define(divisor, `%o1')
+define(Q, `%o2')
+define(R, `%o3')
+define(ITER, `%o4')
+define(V, `%o5')
+
+/* m4 reminder: ifelse(a,b,c,d) => if a is b, then c, else d */
+define(T, `%g1')
+define(SC, `%g5')
+ifelse(S, `true', `define(SIGN, `%g6')')
+
+/*
+ * This is the recursive definition for developing quotient digits.
+ *
+ * Parameters:
+ *  $1 the current depth, 1 <= $1 <= N
+ *  $2 the current accumulation of quotient bits
+ *  N  max depth
+ *
+ * We add a new bit to $2 and either recurse or insert the bits in
+ * the quotient.  R, Q, and V are inputs and outputs as defined above;
+ * the condition codes are expected to reflect the input R, and are
+ * modified to reflect the output R.
+ */
+define(DEVELOP_QUOTIENT_BITS,
+`      ! depth $1, accumulated bits $2
+       bl      L.$1.eval(TWOSUPN+$2)
+       srl     V,1,V
+       ! remainder is positive
+       subcc   R,V,R
+       ifelse($1, N,
+       `       b       9f
+               add     Q, ($2*2+1), Q
+       ', `    DEVELOP_QUOTIENT_BITS(incr($1), `eval(2*$2+1)')')
+L.$1.eval(TWOSUPN+$2):
+       ! remainder is negative
+       addcc   R,V,R
+       ifelse($1, N,
+       `       b       9f
+               add     Q, ($2*2-1), Q
+       ', `    DEVELOP_QUOTIENT_BITS(incr($1), `eval(2*$2-1)')')
+       ifelse($1, 1, `9:')')
+
+FUNC(NAME)
+ifelse(S, `true',
+`      ! compute sign of result; if neither is negative, no problem
+       orcc    divisor, dividend, %g0  ! either negative?
+       bge     2f                      ! no, go do the divide
+       ifelse(OP, `div',
+               `xor    divisor, dividend, SIGN',
+               `mov    dividend, SIGN')        ! compute sign in any case
+       tst     divisor
+       bge     1f
+       tst     dividend
+       ! divisor is definitely negative; dividend might also be negative
+       bge     2f                      ! if dividend not negative...
+       neg     divisor                 ! in any case, make divisor nonneg
+1:     ! dividend is negative, divisor is nonnegative
+       neg     dividend                ! make dividend nonnegative
+2:
+')
+       ! Ready to divide.  Compute size of quotient; scale comparand.
+       orcc    divisor, %g0, V
+       bnz     1f
+       mov     dividend, R
+
+               ! Divide by zero trap.  If it returns, return 0 (about as
+               ! wrong as possible, but that is what SunOS does...).
+               t       ST_DIV0
+               retl
+               clr     %o0
+
+1:
+       cmp     R, V                    ! if divisor exceeds dividend, done
+       blu     Lgot_result             ! (and algorithm fails otherwise)
+       clr     Q
+       sethi   %hi(1 << (WORDSIZE - TOPBITS - 1)), T
+       cmp     R, T
+       blu     Lnot_really_big
+       clr     ITER
+
+       ! `Here the dividend is >= 2^(31-N) or so.  We must be careful here,
+       ! as our usual N-at-a-shot divide step will cause overflow and havoc.
+       ! The number of bits in the result here is N*ITER+SC, where SC <= N.
+       ! Compute ITER in an unorthodox manner: know we need to shift V into
+       ! the top decade: so do not even bother to compare to R.'
+       1:
+               cmp     V, T
+               bgeu    3f
+               mov     1, SC
+               sll     V, N, V
+               b       1b
+               inc     ITER
+
+       ! Now compute SC.
+       2:      addcc   V, V, V
+               bcc     Lnot_too_big
+               inc     SC
+
+               ! We get here if the divisor overflowed while shifting.
+               ! This means that R has the high-order bit set.
+               ! Restore V and subtract from R.
+               sll     T, TOPBITS, T   ! high order bit
+               srl     V, 1, V         ! rest of V
+               add     V, T, V
+               b       Ldo_single_div
+               dec     SC
+
+       Lnot_too_big:
+       3:      cmp     V, R
+               blu     2b
+               nop
+               be      Ldo_single_div
+               nop
+       /* NB: these are commented out in the V8-Sparc manual as well */
+       /* (I do not understand this) */
+       ! V > R: went too far: back up 1 step
+       !       srl     V, 1, V
+       !       dec     SC
+       ! do single-bit divide steps
+       !
+       ! We have to be careful here.  We know that R >= V, so we can do the
+       ! first divide step without thinking.  BUT, the others are conditional,
+       ! and are only done if R >= 0.  Because both R and V may have the high-
+       ! order bit set in the first step, just falling into the regular
+       ! division loop will mess up the first time around.
+       ! So we unroll slightly...
+       Ldo_single_div:
+               deccc   SC
+               bl      Lend_regular_divide
+               nop
+               sub     R, V, R
+               mov     1, Q
+               b       Lend_single_divloop
+               nop
+       Lsingle_divloop:
+               sll     Q, 1, Q
+               bl      1f
+               srl     V, 1, V
+               ! R >= 0
+               sub     R, V, R
+               b       2f
+               inc     Q
+       1:      ! R < 0
+               add     R, V, R
+               dec     Q
+       2:
+       Lend_single_divloop:
+               deccc   SC
+               bge     Lsingle_divloop
+               tst     R
+               b,a     Lend_regular_divide
+
+Lnot_really_big:
+1:
+       sll     V, N, V
+       cmp     V, R
+       bleu    1b
+       inccc   ITER
+       be      Lgot_result
+       dec     ITER
+
+       tst     R       ! set up for initial iteration
+Ldivloop:
+       sll     Q, N, Q
+       DEVELOP_QUOTIENT_BITS(1, 0)
+Lend_regular_divide:
+       deccc   ITER
+       bge     Ldivloop
+       tst     R
+       bl,a    Lgot_result
+       ! non-restoring fixup here (one instruction only!)
+ifelse(OP, `div',
+`      dec     Q
+', `   add     R, divisor, R
+')
+
+Lgot_result:
+ifelse(S, `true',
+`      ! check to see if answer should be < 0
+       tst     SIGN
+       bl,a    1f
+       ifelse(OP, `div', `neg Q', `neg R')
+1:')
+       retl
+       ifelse(OP, `div', `mov Q, %o0', `mov R, %o0')
diff --git a/lib/nbsd_libc/arch/sparc64/gen/fabs.S b/lib/nbsd_libc/arch/sparc64/gen/fabs.S
new file mode 100644 (file)
index 0000000..bb7ac9f
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: fabs.S,v 1.5 2003/08/07 16:42:27 agc Exp $     */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: fabs.s,v 1.4 91/10/07 23:59:05 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)fabs.s      8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: fabs.S,v 1.5 2003/08/07 16:42:27 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* fabs - floating absolute value */
+
+ENTRY(fabs)
+       retl
+        fabss  %f0, %f0                ! return absolute value
+
diff --git a/lib/nbsd_libc/arch/sparc64/gen/fixunsdfsi.S b/lib/nbsd_libc/arch/sparc64/gen/fixunsdfsi.S
new file mode 100644 (file)
index 0000000..bc67fd0
--- /dev/null
@@ -0,0 +1,100 @@
+/*     $NetBSD: fixunsdfsi.S,v 1.4 2003/08/07 16:42:27 agc Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: fixunsdfsi.s,v 1.3 91/10/08 00:03:15 torek Exp
+ */
+
+#include <machine/asm.h>
+#define _LOCORE
+#include <machine/frame.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)fixunsdfsi.s        8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: fixunsdfsi.S,v 1.4 2003/08/07 16:42:27 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Convert double to unsigned integer (for gcc).
+ *
+ * I have made the output for NaN agree with the Sun compiler, not
+ * that it really matters, by using `fbul,a'.
+ */
+
+
+       .align  8
+Lbig:
+       .word   0x43e00000              ! .double 2^63
+       .word   0                       ! (who me, not trust the assembler?)
+
+/*
+ * Same as above but to unsigned long
+ */
+ENTRY(__dtoul)
+       sub     %sp, 16, %sp
+       std     %f2, [%sp + 64 + BIAS + 8]
+#ifdef PIC
+       PICCY_SET(Lbig, %g1, %o0)
+       ldd     [%g1], %f2
+#else
+       sethi   %hi(Lbig), %g1
+       ldd     [%g1 + %lo(Lbig)], %f2
+#endif
+       fcmped  %f0, %f2                ! d < 2^63, or NaN, or -Inf?
+       nop                             ! (fpop2 delay)
+       fbul,a  1f                      ! if so, use fdtoi to convert to int
+        fdtox  %f0, %f0                !        (this includes negatives!)
+
+       ! d does not fit in an int, so subtract 2^63, convert,
+       ! and add 2^63 again (sigh).  Just hope the intermediate
+       ! fits (if not, the result is undefined anyway).
+
+       fsubd   %f0, %f2, %f0           ! d -= 2^63
+       fdtox   %f0, %f0                ! convert to int
+       std     %f0, [%sp + 64 + BIAS]  ! move into return reg
+       ldx     [%sp + 64 + BIAS], %o0
+       sethi   %hi(0x80000000), %o1
+       sllx    %o1, 32, %o1
+       add     %o0, %o1, %o0           ! add 2^63
+       ldd     [%sp + 64 + BIAS + 8], %f2
+       retl
+        add    %sp, 16, %sp
+
+1:
+       std     %f0, [%sp + 64 + BIAS]  ! return result
+       ldx     [%sp + 64 + BIAS], %o0
+       ldd     [%sp + 64 + BIAS + 8], %f2
+       retl
+        add    %sp, 16, %sp
diff --git a/lib/nbsd_libc/arch/sparc64/gen/flt_rounds.c b/lib/nbsd_libc/arch/sparc64/gen/flt_rounds.c
new file mode 100644 (file)
index 0000000..5e70b74
--- /dev/null
@@ -0,0 +1,30 @@
+/*     $NetBSD: flt_rounds.c,v 1.4 2005/12/24 23:10:08 perry Exp $     */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: flt_rounds.c,v 1.4 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <machine/float.h>
+
+static const int map[] = {
+       1,      /* round to nearest */
+       0,      /* round to zero */
+       2,      /* round to positive infinity */
+       3       /* round to negative infinity */
+};
+
+int
+__flt_rounds()
+{
+       int x;
+
+       __asm("st %%fsr,%0" : "=m" (*&x));
+       return map[(x >> 30) & 0x03];
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/fpclassifyl.c b/lib/nbsd_libc/arch/sparc64/gen/fpclassifyl.c
new file mode 100644 (file)
index 0000000..613798a
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: fpclassifyl.c,v 1.2 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpclassifyl.c,v 1.2 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.1 fpclassify - classify real floating type
+ *          IEEE 754 compatible 128-bit extended-precision version
+ */
+int
+__fpclassifyl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       if (u.extu_ext.ext_exp == 0) {
+               if (u.extu_ext.ext_frach  == 0 && u.extu_ext.ext_frachm == 0 &&
+                   u.extu_ext.ext_fraclm == 0 && u.extu_ext.ext_fracl  == 0)
+                       return FP_ZERO;
+               else
+                       return FP_SUBNORMAL;
+       } else if (u.extu_ext.ext_exp == EXT_EXP_INFNAN) {
+               if (u.extu_ext.ext_frach  == 0 && u.extu_ext.ext_frachm == 0 &&
+                   u.extu_ext.ext_fraclm == 0 && u.extu_ext.ext_fracl  == 0)
+                       return FP_INFINITE;
+               else
+                       return FP_NAN;
+       }
+
+       return FP_NORMAL;
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/fpgetmask.c b/lib/nbsd_libc/arch/sparc64/gen/fpgetmask.c
new file mode 100644 (file)
index 0000000..b0cadda
--- /dev/null
@@ -0,0 +1,28 @@
+/*     $NetBSD: fpgetmask.c,v 1.4 2005/12/24 23:10:08 perry Exp $      */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetmask.c,v 1.4 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetmask,_fpgetmask)
+#endif
+
+fp_except
+fpgetmask()
+{
+       int x;
+
+       __asm("st %%fsr,%0" : "=m" (*&x));
+       return (x >> 23) & 0x1f;
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/fpgetround.c b/lib/nbsd_libc/arch/sparc64/gen/fpgetround.c
new file mode 100644 (file)
index 0000000..c449910
--- /dev/null
@@ -0,0 +1,28 @@
+/*     $NetBSD: fpgetround.c,v 1.4 2005/12/24 23:10:08 perry Exp $     */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetround.c,v 1.4 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetround,_fpgetround)
+#endif
+
+fp_rnd
+fpgetround()
+{
+       int x;
+
+       __asm("st %%fsr,%0" : "=m" (*&x));
+       return (x >> 30) & 0x03;
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/fpgetsticky.c b/lib/nbsd_libc/arch/sparc64/gen/fpgetsticky.c
new file mode 100644 (file)
index 0000000..bd0484d
--- /dev/null
@@ -0,0 +1,28 @@
+/*     $NetBSD: fpgetsticky.c,v 1.4 2005/12/24 23:10:08 perry Exp $    */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetsticky.c,v 1.4 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpgetsticky,_fpgetsticky)
+#endif
+
+fp_except
+fpgetsticky()
+{
+       int x;
+
+       __asm("st %%fsr,%0" : "=m" (*&x));
+       return (x >> 5) & 0x1f;
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/fpsetmask.c b/lib/nbsd_libc/arch/sparc64/gen/fpsetmask.c
new file mode 100644 (file)
index 0000000..65e7a79
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: fpsetmask.c,v 1.4 2005/12/24 23:10:08 perry Exp $      */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetmask.c,v 1.4 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetmask,_fpsetmask)
+#endif
+
+fp_except
+fpsetmask(mask)
+       fp_except mask;
+{
+       fp_except old;
+       fp_except new;
+
+       __asm("st %%fsr,%0" : "=m" (*&old));
+
+       new = old;
+       new &= ~(0x1f << 23); 
+       new |= ((mask & 0x1f) << 23);
+
+       __asm("ld %0,%%fsr" : : "m" (*&new));
+
+       return (old >> 23) & 0x1f;
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/fpsetround.c b/lib/nbsd_libc/arch/sparc64/gen/fpsetround.c
new file mode 100644 (file)
index 0000000..9e21dc7
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: fpsetround.c,v 1.4 2005/12/24 23:10:08 perry Exp $     */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetround.c,v 1.4 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetround,_fpsetround)
+#endif
+
+fp_rnd
+fpsetround(rnd_dir)
+       fp_rnd rnd_dir;
+{
+       fp_rnd old;
+       fp_rnd new;
+
+       __asm("st %%fsr,%0" : "=m" (*&old));
+
+       new = old;
+       new &= ~(0x03 << 30); 
+       new |= ((rnd_dir & 0x03) << 30);
+
+       __asm("ld %0,%%fsr" : : "m" (*&new));
+
+       return (old >> 30) & 0x03;
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/fpsetsticky.c b/lib/nbsd_libc/arch/sparc64/gen/fpsetsticky.c
new file mode 100644 (file)
index 0000000..10e98ed
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: fpsetsticky.c,v 1.4 2005/12/24 23:10:08 perry Exp $    */
+
+/*
+ * Written by J.T. Conklin, Apr 10, 1995
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetsticky.c,v 1.4 2005/12/24 23:10:08 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+
+#ifdef __weak_alias
+__weak_alias(fpsetsticky,_fpsetsticky)
+#endif
+
+fp_except
+fpsetsticky(sticky)
+       fp_except sticky;
+{
+       fp_except old;
+       fp_except new;
+
+       __asm("st %%fsr,%0" : "=m" (*&old));
+
+       new = old;
+       new &= ~(0x1f << 5); 
+       new |= ((sticky & 0x1f) << 5);
+
+       __asm("ld %0,%%fsr" : : "m" (*&new));
+
+       return (old >> 5) & 0x1f;
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/infinityl.c b/lib/nbsd_libc/arch/sparc64/gen/infinityl.c
new file mode 100644 (file)
index 0000000..ebd8f2d
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: infinityl.c,v 1.2 2005/06/12 05:21:27 lukem Exp $      */
+
+/*
+ * IEEE-compatible infinityl.c for big-endian 128-bit format -- public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: infinityl.c,v 1.2 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+
+const union __long_double_u __infinityl =
+       { { 0x7f, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };
diff --git a/lib/nbsd_libc/arch/sparc64/gen/isfinitel.c b/lib/nbsd_libc/arch/sparc64/gen/isfinitel.c
new file mode 100644 (file)
index 0000000..b569512
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: isfinitel.c,v 1.2 2008/04/28 20:22:57 martin Exp $     */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: isfinitel.c,v 1.2 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.2 isfinite - determine whether an argument has finite value
+ *          IEEE 754 compatible 128-bit extended-precision version
+ */
+int
+__isfinitel(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       if (u.extu_ext.ext_exp == EXT_EXP_INFNAN)
+               return 0;
+
+       return 1;
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/isinfl.c b/lib/nbsd_libc/arch/sparc64/gen/isinfl.c
new file mode 100644 (file)
index 0000000..8d7acc6
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: isinfl.c,v 1.4 2004/03/04 23:42:39 kleink Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isinfl.c,v 1.4 2004/03/04 23:42:39 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.3 isinf - test for infinity
+ *          IEEE 754 compatible 128-bit extended-precision version
+ */
+int
+__isinfl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return (u.extu_ext.ext_exp == EXT_EXP_INFNAN &&
+           (u.extu_ext.ext_frach  == 0 && u.extu_ext.ext_frachm == 0 &&
+            u.extu_ext.ext_fraclm == 0 && u.extu_ext.ext_fracl  == 0));
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/isnanl.c b/lib/nbsd_libc/arch/sparc64/gen/isnanl.c
new file mode 100644 (file)
index 0000000..2b67f08
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: isnanl.c,v 1.4 2004/03/04 23:42:39 kleink Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isnanl.c,v 1.4 2004/03/04 23:42:39 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.4 isnan - test for a NaN
+ *          IEEE 754 compatible 128-bit extended-precision version
+ */
+int
+__isnanl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return (u.extu_ext.ext_exp == EXT_EXP_INFNAN &&
+           (u.extu_ext.ext_frach  != 0 || u.extu_ext.ext_frachm != 0 ||
+            u.extu_ext.ext_fraclm != 0 || u.extu_ext.ext_fracl  != 0));
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/longjmp.c b/lib/nbsd_libc/arch/sparc64/gen/longjmp.c
new file mode 100644 (file)
index 0000000..54f54ac
--- /dev/null
@@ -0,0 +1,98 @@
+/*     $NetBSD: longjmp.c,v 1.2 2008/04/28 20:22:57 martin Exp $       */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christian Limpach.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+#define __LIBC12_SOURCE__
+#include <setjmp.h>
+#include <compat/include/setjmp.h>
+
+typedef struct {
+       __greg_t        __glob[5];
+} __jmp_buf_regs_t;
+
+void
+__longjmp14(jmp_buf env, int val)
+{
+       struct sigcontext *sc = (void *)env;
+       __jmp_buf_regs_t *r = (void *)&sc[1];
+       ucontext_t uc;
+
+       /* Ensure non-zero SP */
+       if (sc->sc_sp == 0)
+               goto err;
+
+       /*
+        * Set _UC_CPU. No FPU data saved, so we can't restore
+        * that. Set _UC_{SET,CLR}STACK according to SS_ONSTACK
+        */
+       memset(&uc, 0, sizeof(uc));
+       uc.uc_flags = _UC_CPU | (sc->sc_onstack ? _UC_SETSTACK : _UC_CLRSTACK);
+
+       /*
+        * Set the signal mask - this is a weak symbol, so don't use
+        * _UC_SIGMASK in the mcontext, libpthread might override sigprocmask.
+        */
+       sigprocmask(SIG_SETMASK, &sc->sc_mask, NULL);
+
+       /* Fill other registers */
+       uc.uc_mcontext.__gregs[_REG_CCR] = sc->sc_tstate;
+       uc.uc_mcontext.__gregs[_REG_PC] = sc->sc_pc;
+       uc.uc_mcontext.__gregs[_REG_nPC] = sc->sc_npc;
+       uc.uc_mcontext.__gregs[_REG_G1] = sc->sc_g1;
+       uc.uc_mcontext.__gregs[_REG_G2] = sc->sc_o0;
+       uc.uc_mcontext.__gregs[_REG_G3] = r->__glob[0];
+       uc.uc_mcontext.__gregs[_REG_G4] = r->__glob[1];
+       uc.uc_mcontext.__gregs[_REG_G5] = r->__glob[2];
+       uc.uc_mcontext.__gregs[_REG_G6] = r->__glob[3];
+       uc.uc_mcontext.__gregs[_REG_G7] = r->__glob[4];
+       uc.uc_mcontext.__gregs[_REG_O6] = sc->sc_sp;
+
+       /* Make return value non-zero */
+       if (val == 0)
+               val = 1;
+
+       /* Save return value in context */
+       uc.uc_mcontext.__gregs[_REG_O0] = val;
+
+       setcontext(&uc);
+
+ err:
+       longjmperror();
+       abort();
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/makecontext.c b/lib/nbsd_libc/arch/sparc64/gen/makecontext.c
new file mode 100644 (file)
index 0000000..64fa3c6
--- /dev/null
@@ -0,0 +1,81 @@
+/*     $NetBSD: makecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include <inttypes.h>
+#include <stddef.h>
+#include <sys/types.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#include <stdarg.h>
+
+void
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+{
+       __greg_t *gr = ucp->uc_mcontext.__gregs;
+       int i;
+       ulong *sp;
+       va_list ap;
+
+       sp = (ulong *)((caddr_t)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size);
+       /* Align on quad-word boundary. */
+       sp = (ulong *)((ulong)sp & ~0xf);
+
+       /* Make room for: argx, argd, struct return pointer(?), rwindow. */
+       sp -= (argc > 6 ? argc - 6 : 0) + 6 + 8 + 8;
+
+       va_start(ap, argc);
+
+       /* Pass up to 6 arguments in %o0-5. */
+       for (i = 0; i < argc && i < 6; i++)
+               gr[_REG_O0 + i] = sp[i + 16] = va_arg(ap, unsigned long);
+
+       /* Pass any additional arguments on the stack. */
+       for (; i < argc; i++)
+               sp[i + 16] = va_arg(ap, unsigned long);
+       va_end(ap);
+
+       sp[14] = (ulong)sp - 2047;
+       sp[15] = (ulong)_resumecontext - 8;
+
+       sp = (ulong *)((caddr_t)sp - 2047);
+
+       gr[_REG_O6] = (__greg_t)sp;
+       gr[_REG_PC] = (__greg_t)func;
+       gr[_REG_nPC] = (__greg_t)func + 4;
+       gr[_REG_O7] = (__greg_t)_resumecontext - 8;
+
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/modf.S b/lib/nbsd_libc/arch/sparc64/gen/modf.S
new file mode 100644 (file)
index 0000000..624a2f3
--- /dev/null
@@ -0,0 +1,189 @@
+/*     $NetBSD: modf.S,v 1.4 2003/08/07 16:42:27 agc Exp $     */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: modf.s,v 1.3 92/06/20 00:00:54 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)modf.s      8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: modf.S,v 1.4 2003/08/07 16:42:27 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/fsr.h>
+
+/*
+ * double modf(double val, double *iptr)
+ *
+ * Returns the fractional part of `val', storing the integer part of
+ * `val' in *iptr.  Both *iptr and the return value have the same sign
+ * as `val'.
+ *
+ * Method:
+ *
+ * We use the fpu's normalization hardware to compute the integer portion
+ * of the double precision argument.  Sun IEEE double precision numbers
+ * have 52 bits of mantissa, 11 bits of exponent, and one bit of sign,
+ * with the sign occupying bit 31 of word 0, and the exponent bits 30:20
+ * of word 0.  Thus, values >= 2^52 are by definition integers.
+ *
+ * If we take a value that is in the range [+0..2^52) and add 2^52, all
+ * of the fractional bits fall out and all of the integer bits are summed
+ * with 2^52.  If we then subtract 2^52, we get those integer bits back.
+ * This must be done with rounding set to `towards 0' or `towards -inf'.
+ * `Toward -inf' fails when the value is 0 (we get -0 back)....
+ *
+ * Note that this method will work anywhere, but is machine dependent in
+ * various aspects.
+ *
+ * Stack usage:
+ *     4@[%fp + BIAS - 4]      saved %fsr
+ *     4@[%fp + BIAS - 8]      new %fsr with rounding set to `towards 0'
+ *     8@[%fp + BIAS - 16]     space for moving between %i and %f registers
+ * Register usage:
+ *     %f0:f1          double val;
+ *     %l0             scratch
+ *     %l1             sign bit (0x80000000)
+ *     %i1             double *iptr;
+ *     %f2:f3          `magic number' 2^52, in fpu registers
+ *     %f4:f5          double v, in fpu registers
+ *     %f6:f7          double temp.
+ */
+
+       .align  8
+Lmagic:
+       .word   0x43300000      ! sign = 0, exponent = 52 + 1023, mantissa = 0
+       .word   0               ! (i.e., .double 0r4503599627370496e+00)
+
+L0:
+       .word   0               ! 0.0
+       .word   0
+
+ENTRY(modf)
+       save    %sp, -CC64FSZ-16, %sp
+
+       /*
+        * First, compute v = abs(val)
+        */
+       fabsd   %f0, %f4                ! %f4:f5 = v
+       fcmped  %fcc1, %f0, %f4         ! %fcc1 = (val == abs(val))
+#ifdef PIC
+       PICCY_SET(Lmagic, %l0, %o7)
+       ldd     [%l0], %f2
+#else
+       sethi   %hi(Lmagic), %l0
+       ldd     [%l0 + %lo(Lmagic)], %f2
+#endif
+
+       /*
+        * Is %f4:f5 >= %f2:f3 ?  If so, it is all integer bits.
+        * It is probably less, though.
+        */
+       fcmped  %f4, %f2
+       fbuge   Lbig                    ! if >= (or unordered), go out
+       nop
+
+       /*
+        * v < 2^52, so add 2^52, then subtract 2^52, but do it all
+        * with rounding set towards zero.  We leave any enabled
+        * traps enabled, but change the rounding mode.  This might
+        * not be so good.  Oh well....
+        */
+       st      %fsr, [%fp + BIAS - 4]  ! %l5 = current FSR mode
+       set     FSR_RD, %l3             ! %l3 = rounding direction mask
+       ld      [%fp + BIAS - 4], %l5
+       set     FSR_RD_RZ << FSR_RD_SHIFT, %l4
+       andn    %l5, %l3, %l6
+       or      %l6, %l4, %l6           ! round towards zero, please
+       and     %l5, %l3, %l5           ! save original rounding mode
+       st      %l6, [%fp + BIAS - 8]
+       ld      [%fp + BIAS - 8], %fsr
+
+       faddd   %f4, %f2, %f4           ! %f4:f5 += 2^52
+       fsubd   %f4, %f2, %f4           ! %f4:f5 -= 2^52
+
+       /*
+        * Restore %fsr, but leave exceptions accrued.
+        */
+       st      %fsr, [%fp + BIAS - 4]
+       ld      [%fp + BIAS - 4], %l6
+       andn    %l6, %l3, %l6           ! %l6 = %fsr & ~FSR_RD;
+       or      %l5, %l6, %l5           ! %l5 |= %l6;
+       st      %l5, [%fp + BIAS - 4]
+       ld      [%fp + BIAS - 4], %fsr  ! restore %fsr, leaving accrued stuff
+
+       /*
+        * Now insert the original sign in %f4:f5.
+        * %fcc1 should still have the reults of (val == abs(val))
+        * from above, so we use a conditional move on %fcc1 to: 
+        *
+        *      %f4 = (val == abs(val)) ? %f4 : -%f4
+        *
+        */
+       fnegd   %f4, %f6
+       fmovdnz %fcc1, %f6, %f4
+1:
+
+       /*
+        * The value in %f4:f5 is now the integer portion of the original
+        * argument.  We need to store this in *ival (%i1), subtract it
+        * from the original value argument (%d0), and return the result.
+        */
+       std     %f4, [%i1]              ! *ival = %f4:f5;
+       fsubd   %f0, %f4, %f0           ! %f0:f1 -= %f4:f5;
+       ret
+       restore
+
+Lbig:
+       /*
+        * We get here if the original comparison of %f4:f5 (v) to
+        * %f2:f3 (2^52) came out `greater or unordered'.  In this
+        * case the integer part is the original value, and the
+        * fractional part is 0.
+        */
+#ifdef PIC
+       PICCY_SET(L0, %l0, %o7)
+       std     %f0, [%i1]              ! *ival = val;
+       ldd     [%l0], %f0              ! return 0.0;
+#else
+       sethi   %hi(L0), %l0
+       std     %f0, [%i1]              ! *ival = val;
+       ldd     [%l0 + %lo(L0)], %f0    ! return 0.0;
+#endif
+       ret
+       restore
+
diff --git a/lib/nbsd_libc/arch/sparc64/gen/nanf.c b/lib/nbsd_libc/arch/sparc64/gen/nanf.c
new file mode 100644 (file)
index 0000000..1688d0e
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: nanf.c,v 1.4 2009/02/22 01:34:02 martin Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nanf.c,v 1.4 2009/02/22 01:34:02 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+/* bytes for quiet NaN (IEEE single precision) */
+const union __float_u __nanf =
+               { { 0x7f, 0xc0,    0,    0 } };
+
+__warn_references(__nanf, "warning: <math.h> defines NAN incorrectly for your compiler.")
diff --git a/lib/nbsd_libc/arch/sparc64/gen/resumecontext.c b/lib/nbsd_libc/arch/sparc64/gen/resumecontext.c
new file mode 100644 (file)
index 0000000..1a7c4c5
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: resumecontext.c,v 1.4 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "extern.h"
+
+void
+_resumecontext()
+{
+       ucontext_t uct;
+
+       (void)getcontext(&uct);
+       if (uct.uc_link == NULL) 
+               exit(0);
+       (void)setcontext(uct.uc_link);
+       _exit(-1);
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/setjmp.S b/lib/nbsd_libc/arch/sparc64/gen/setjmp.S
new file mode 100644 (file)
index 0000000..e12e04a
--- /dev/null
@@ -0,0 +1,136 @@
+/*     $NetBSD: setjmp.S,v 1.7 2005/10/16 17:15:38 christos Exp $      */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: setjmp.s,v 1.2 92/06/25 03:18:43 torek Exp
+ */
+
+#define _LOCORE
+#include <machine/asm.h>
+#include <machine/frame.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)setjmp.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: setjmp.S,v 1.7 2005/10/16 17:15:38 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- setjmp
+ *
+ *     __longjmp14(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and a struct sigcontext, see <signal.h>
+ */
+
+#include "SYS.h"
+
+       .register %g2,#ignore
+       .register %g3,#ignore
+       .register %g6,#ignore
+
+ENTRY(__setjmp14)
+       save    %sp, -CC64FSZ, %sp
+
+       /* save globals into locals */
+       mov     %g1, %l1
+       mov     %g2, %l2
+       mov     %g3, %l3
+       mov     %g4, %l4
+       mov     %g5, %l5
+       mov     %g6, %l6
+       mov     %g7, %l7
+
+#ifdef PIC
+       PIC_PROLOGUE(%i1, %o4)
+#endif
+
+       /* now get sigmask and onstack flag */
+       add     %i0, 0x38, %o2          /* build sigcontext in [%o2]->sc.sc_mask */
+       mov     1, %o0                  /* SIG_BLOCK */
+                                       /* sigprocmask(SIG_BLOCK, (sigset_t *)NULL, (sigset_t *)a) */
+#ifdef PIC
+#ifdef BIGPIC
+       set     _C_LABEL(__sigprocmask14), %o4
+       ldx     [%i1 + %o4], %g2
+#else
+       ldx     [%i1 + _C_LABEL(__sigprocmask14)], %g2
+#endif
+       call    %g2
+#else
+       call    _C_LABEL(__sigprocmask14)
+#endif
+        clr    %o1
+
+       clr     %o0                     /* sigstack(NULL, &foo) */
+#ifdef PIC
+#ifdef BIGPIC
+       set     _C_LABEL(__sigaltstack14), %o4
+       ldx     [%i1 + %o4], %g2
+#else
+       ldx     [%i1 + _C_LABEL(__sigaltstack14)], %g2
+#endif
+       call    %g2
+#else
+       call    _C_LABEL(__sigaltstack14)
+#endif
+        add    %i0, 8, %o1             /* (foo being part of the sigcontext we're overwriting) */
+       
+       lduw    [%i0 + 8 + 0x10], %o0   /* foo.ss_flags */
+       and     %o0, 1, %o1             /* onstack = foo.ss_flags & SS_ONSTACK; */
+       st      %o1, [%i0 + 0x00]       /* sc.sc_onstack = current onstack; */
+
+       /* store essential state */
+       stx     %fp, [%i0 + 0x08]       /* sc.sc_sp = sp */
+       add     %i7, 8, %o0
+       stx     %o0, [%i0 + 0x10]       /* sc.sc_pc = return_pc */
+       add     %i7, 12, %o0
+       stx     %o0, [%i0 + 0x18]       /* sc.sc_npc = return_pc + 4 */
+       stx     %g0, [%i0 + 0x20]       /* sc.sc_tstate = (clean ccr) */
+       stx     %l1, [%i0 + 0x28]       /* sc.sc_g1 */
+       stx     %l2, [%i0 + 0x30]       /* sc.sc_o0, set in longjmp, use as %g2 */
+       /* 0x38 */                      /* sc.sc_mask was already saved above */
+
+       /* save additional registers needed to fill a complete mcontext */
+       stx     %l3, [%i0 + 0x40]
+       stx     %l4, [%i0 + 0x48]
+       stx     %l5, [%i0 + 0x50]
+       stx     %l6, [%i0 + 0x58]
+       stx     %l7, [%i0 + 0x60]
+
+       ret                             /* return 0 */
+        restore %g0, 0, %o0
diff --git a/lib/nbsd_libc/arch/sparc64/gen/signbitl.c b/lib/nbsd_libc/arch/sparc64/gen/signbitl.c
new file mode 100644 (file)
index 0000000..0328c9f
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: signbitl.c,v 1.2 2008/04/28 20:22:57 martin Exp $      */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.6 signbit - determine whether the sign of an argument is negative
+ *          IEEE 754 compatible 128-bit extended-precision version
+ */
+int
+__signbitl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return (u.extu_ext.ext_sign == 1);
+}
diff --git a/lib/nbsd_libc/arch/sparc64/gen/sigsetjmp.S b/lib/nbsd_libc/arch/sparc64/gen/sigsetjmp.S
new file mode 100644 (file)
index 0000000..fedbc70
--- /dev/null
@@ -0,0 +1,108 @@
+/*     $NetBSD: sigsetjmp.S,v 1.8 2005/10/16 17:15:38 christos Exp $   */
+/*
+ * Copyright (c) 1995 Paul Kranenburg
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Paul Kranenburg.
+ * 4. 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 ``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 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 "SYS.h"
+
+#ifdef PIC
+#ifdef BIGPIC
+       
+ENTRY(__sigsetjmp14)
+       PIC_PROLOGUE(%g1,%o2)           ! %g1 = _GLOBAL_OFFSET_TABLE
+       st      %o1,[%o0+0x68]          ! jmpbuf[JBLEN]
+       sethi   %hi(_C_LABEL(__setjmp14)), %o2
+       sethi   %hi(_C_LABEL(_setjmp)), %o3
+       or      %o2, %lo(_C_LABEL(__setjmp14)), %o2
+       or      %o3, %lo(_C_LABEL(_setjmp)), %o3
+       brz     %o1, 1f 
+        ldx    [%g1+%o3], %o3          ! if (%o1 == 0) goto _setjmp;
+       ldx     [%g1+%o2], %o3          ! else goto __setjmp;
+1:
+       jmp     %o3
+        nop
+       
+ENTRY(__siglongjmp14)
+       PIC_PROLOGUE(%g1,%o2)           ! %g1 = _GLOBAL_OFFSET_TABLE
+       ld      [%o0+0x68], %o2         ! jmpbuf[JBLEN]
+       sethi   %hi(_C_LABEL(__longjmp14)), %o3 
+       sethi   %hi(_C_LABEL(_longjmp)), %o4
+       or      %o3, %lo(_C_LABEL(__longjmp14)), %o3
+       or      %o4, %lo(_C_LABEL(_longjmp)), %o4
+       brz,a   %o2, 1f 
+        ldx    [%g1+%o4], %o4          ! if (%o2 == 0) goto _longjmp;
+       ldx     [%g1+%o3], %o4          ! else goto __longjmp;
+1:
+       jmp     %o4     
+        nop
+       unimp 0
+#else
+
+ENTRY(__sigsetjmp14)
+       PIC_PROLOGUE(%g1,%o2)                   ! %g1 = _GLOBAL_OFFSET_TABLE
+       cmp     %o1,0
+       st      %o1,[%o0+0x68]                  ! jmpbuf[JBLEN]
+       bne,a   1f
+        ldx    [%g1+_C_LABEL(__setjmp14)], %g1 ! if (%o1 != 0) goto __setjmp;
+       ldx     [%g1+_C_LABEL(_setjmp)], %g1    ! else goto _setjmp;
+1:
+       jmp %g1
+        nop
+
+ENTRY(__siglongjmp14)
+       PIC_PROLOGUE(%g1,%o2)                   ! %g1 = _GLOBAL_OFFSET_TABLE
+       ld      [%o0+0x68],%o2                  ! jmpbuf[JBLEN]
+       cmp     %o2,0
+       bne,a   1f
+        ldx    [%g1+_C_LABEL(__longjmp14)], %g1 ! if (%o2 != 0) goto __longjmp;
+       ldx     [%g1+_C_LABEL(_longjmp)], %g1   ! else goto _longjmp;
+1:
+       jmp %g1
+        nop
+       unimp 0
+#endif /* BIGPIC */
+#else /* PIC */
+
+ENTRY(__sigsetjmp14)
+       cmp     %o1,0
+       be      _C_LABEL(_setjmp)
+        st     %o1,[%o0+0x68]          ! jmpbuf[JBLEN]
+       ba,a    _C_LABEL(__setjmp14)
+       unimp 0
+
+ENTRY(__siglongjmp14)
+       ld      [%o0+0x68],%g1
+       cmp     %g1,0
+       be      _C_LABEL(_longjmp)
+        nop
+       ba,a    _C_LABEL(__longjmp14)
+       unimp 0
+
+#endif /* PIC */
diff --git a/lib/nbsd_libc/arch/sparc64/gen/swapcontext.S b/lib/nbsd_libc/arch/sparc64/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..972d5a3
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: swapcontext.S,v 1.4 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: swapcontext.S,v 1.4 2008/04/28 20:22:57 martin Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+       .register       %g2,#scratch
+
+ENTRY(swapcontext)
+       mov     %o0, %o2                        /* must save pointer */
+       mov     %o1, %o3                        /* must save pointer */
+       mov     SYS_getcontext, %g1
+       t       ST_SYSCALL
+       bcc,a   1f
+        stx    %g0, [%o2 + 64 + 11 * 8]        /* gr[_REG_O0] = 0 */
+       ERROR()
+1:
+       add     %o7, 12, %o1
+       stx     %o1, [%o2 + 64 + 2 * 8]         /* gr[_REG_nPC] = retaddr + 4 */
+       add     %o7, 8, %o1
+       stx     %o1, [%o2 + 64 + 1 * 8]         /* gr[_REG_PC] = retaddr */
+
+       mov     %o3, %o0
+       mov     %o1, %g2                        /* optimize `return' */
+       mov     SYS_setcontext|SYSCALL_G2RFLAG, %g1
+       t       ST_SYSCALL
+       ERROR()
diff --git a/lib/nbsd_libc/arch/sparc64/net/Makefile.inc b/lib/nbsd_libc/arch/sparc64/net/Makefile.inc
new file mode 100644 (file)
index 0000000..f515535
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 1998/09/11 04:56:30 eeh Exp $
+
+SRCS+=  htonl.S htons.S ntohl.S ntohs.S
diff --git a/lib/nbsd_libc/arch/sparc64/softfloat/milieu.h b/lib/nbsd_libc/arch/sparc64/softfloat/milieu.h
new file mode 100644 (file)
index 0000000..ef43336
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: milieu.h,v 1.1 2002/02/05 07:53:05 jmc Exp $   */
+
+/*
+===============================================================================
+
+This C header file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+Include common integer types and flags.
+-------------------------------------------------------------------------------
+*/
+#include "sparc64-gcc.h"
+
+/*
+-------------------------------------------------------------------------------
+Symbolic Boolean literals.
+-------------------------------------------------------------------------------
+*/
+enum {
+    FALSE = 0,
+    TRUE  = 1
+};
diff --git a/lib/nbsd_libc/arch/sparc64/softfloat/qp.c b/lib/nbsd_libc/arch/sparc64/softfloat/qp.c
new file mode 100644 (file)
index 0000000..40bf845
--- /dev/null
@@ -0,0 +1,285 @@
+/* $NetBSD: qp.c,v 1.7 2008/04/28 20:22:57 martin Exp $ */
+
+/*-
+ * Copyright (c) 2002, 2003 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#include <memory.h>
+
+#include "milieu.h"
+#include "softfloat.h"
+
+
+void _Qp_add(float128 *c, float128 *a, float128 *b);
+int  _Qp_cmp(float128 *a, float128 *b);
+int  _Qp_cmpe(float128 *a, float128 *b);
+void _Qp_div(float128 *c, float128 *a, float128 *b);
+void _Qp_dtoq(float128 *c, double a);
+int  _Qp_feq(float128 *a, float128 *b);
+int  _Qp_fge(float128 *a, float128 *b);
+int  _Qp_fgt(float128 *a, float128 *b);
+int  _Qp_fle(float128 *a, float128 *b);
+int  _Qp_flt(float128 *a, float128 *b);
+int  _Qp_fne(float128 *a, float128 *b);
+void _Qp_itoq(float128 *c, int a);
+void _Qp_mul(float128 *c, float128 *a, float128 *b);
+void _Qp_neg(float128 *c, float128 *a);
+double _Qp_qtod(float128 *a);
+int _Qp_qtoi(float128 *a);
+float _Qp_qtos(float128 *a);
+unsigned int _Qp_qtoui(float128 *a);
+unsigned long _Qp_qtoux(float128 *a);
+long _Qp_qtox(float128 *a);
+void _Qp_sqrt(float128 *c, float128 *a);
+void _Qp_stoq(float128 *c, float a);
+void _Qp_sub(float128 *c, float128 *a, float128 *b);
+void _Qp_uitoq(float128 *c, unsigned int a);
+void _Qp_uxtoq(float128 *c, unsigned long a);
+void _Qp_xtoq(float128 *c, long a);
+
+
+void
+_Qp_add(float128 *c, float128 *a, float128 *b)
+{
+        *c =  float128_add(*a, *b);
+}
+
+
+int
+_Qp_cmp(float128 *a, float128 *b)
+{
+
+       if (float128_eq(*a, *b))
+               return 0;
+
+       if (float128_le(*a, *b))
+               return 1;
+
+       return 2;
+}
+
+
+/*
+ * XXX 
+ */
+int
+_Qp_cmpe(float128 *a, float128 *b)
+{
+       return _Qp_cmp(a, b);
+}
+
+
+void
+_Qp_div(float128 *c, float128 *a, float128 *b)
+{
+       *c = float128_div(*a, *b);
+}
+
+
+void
+_Qp_dtoq(float128 *c, double a)
+{
+       float64 _b;
+
+       memcpy (&_b, &a, sizeof(float64));
+       *c = float64_to_float128(_b);
+}
+
+
+int
+_Qp_feq(float128 *a, float128 *b)
+{
+       return float128_eq(*a, *b);
+}
+
+
+int
+_Qp_fge(float128 *a, float128 *b)
+{
+       return float128_le(*b, *a);
+}
+
+
+int
+_Qp_fgt(float128 *a, float128 *b)
+{
+       return float128_lt(*b, *a);
+}
+
+
+int
+_Qp_fle(float128 *a, float128 *b)
+{
+       return float128_le(*a, *b);
+}
+
+
+int
+_Qp_flt(float128 *a, float128 *b)
+{
+       return float128_lt(*a, *b);
+}
+
+
+int
+_Qp_fne(float128 *a, float128 *b)
+{
+       return !float128_eq(*a, *b);
+}
+
+
+void
+_Qp_itoq(float128 *c, int a)
+{
+       *c = int32_to_float128(a);
+}
+
+
+void
+_Qp_mul(float128 *c, float128 *a, float128 *b)
+{
+       *c = float128_mul(*a, *b);
+}
+
+
+/*
+ * XXX need corresponding softfloat function
+ */
+static float128 __zero = {0x4034000000000000, 0x00000000};
+
+void
+_Qp_neg(float128 *c, float128 *a)
+{
+       *c = float128_sub(__zero, *a);
+}
+
+
+double
+_Qp_qtod(float128 *a)
+{
+       float64 _c;
+       double c;
+
+       _c = float128_to_float64(*a);
+
+       memcpy(&c, &_c, sizeof(double));
+
+       return c;
+}
+
+
+int
+_Qp_qtoi(float128 *a)
+{
+       return float128_to_int32(*a);
+}
+
+
+float
+ _Qp_qtos(float128 *a)
+{
+       float c;
+       float32 _c;
+
+       _c = float128_to_float32(*a);
+
+       memcpy(&c, &_c, sizeof(_c));
+
+       return c; 
+}
+
+
+unsigned int
+_Qp_qtoui(float128 *a)
+{
+       return (unsigned int)float128_to_int64(*a);
+}
+
+
+unsigned long
+_Qp_qtoux(float128 *a)
+{
+       return (unsigned long)float128_to_uint64_round_to_zero(*a);
+}
+
+
+long
+_Qp_qtox(float128 *a)
+{
+       return (long)float128_to_int64_round_to_zero(*a);
+}
+
+
+void
+_Qp_sqrt(float128 *c, float128 *a)
+{
+       *c = float128_sqrt(*a);
+}
+
+
+void
+_Qp_stoq(float128 *c, float a)
+{
+       float32 _a;
+
+       memcpy(&_a, &a, sizeof(a));
+
+       *c = float32_to_float128(_a);
+}
+
+
+void
+_Qp_sub(float128 *c, float128 *a, float128 *b)
+{
+       *c = float128_sub(*a, *b);
+}
+
+
+void
+_Qp_uitoq(float128 *c, unsigned int a)
+{
+       *c = int64_to_float128(a);
+}
+
+
+void
+_Qp_uxtoq(float128 *c, unsigned long a)
+{
+
+       if (a & 0x8000000000000000ULL) {
+               a = (a >> 1) | (a & 1);
+               *c = int64_to_float128(a);
+               *c = float128_add(*c, *c);
+       } else
+               *c = int64_to_float128(a);
+}
+
+
+void
+_Qp_xtoq(float128 *c, long a)
+{
+       *c = int64_to_float128(a);
+}
diff --git a/lib/nbsd_libc/arch/sparc64/softfloat/softfloat-qp.h b/lib/nbsd_libc/arch/sparc64/softfloat/softfloat-qp.h
new file mode 100644 (file)
index 0000000..1fda880
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * Get everything SOFTFLOAT_FOR_GCC normally would rename out of the users
+ * namespace. Much of this isn't used but to avoid dissecting softloat.c
+ * all of it is pulled in even for just the _Qp* case
+ */
+
+#if defined(SOFTFLOATSPARC64_FOR_GCC) && !defined(SOFTFLOAT_FOR_GCC)
+#define float_exception_flags   _softfloat_float_exception_flags
+#define float_rounding_mode     _softfloat_float_rounding_mode
+#define float_raise             _softfloat_float_raise
+
+#define float32_eq              _softfloat_float32_eq
+#define float32_le              _softfloat_float32_le
+#define float32_lt              _softfloat_float32_lt
+#define float64_eq              _softfloat_float64_eq
+#define float64_le              _softfloat_float64_le
+#define float64_lt              _softfloat_float64_lt
+
+#define float32_add                    _softfloat_float32_add
+#define float64_add                    _softfloat_float64_add
+#define float32_sub                    _softfloat_float32_sub
+#define float64_sub                    _softfloat_float64_sub
+#define float32_mul                    _softfloat_float32_mul
+#define float64_mul                    _softfloat_float64_mul
+#define float32_div                    _softfloat_float32_div
+#define float64_div                    _softfloat_float64_div
+#define int32_to_float32               _softfloat_int32_to_float32
+#define int32_to_float64               _softfloat_int32_to_float64
+#define int64_to_float32               _softfloat_int64_to_float32
+#define int64_to_float64               _softfloat_int64_to_float64
+#define float32_to_int32_round_to_zero _softfloat_float32_to_int32_round_to_zero
+#define float64_to_int32_round_to_zero _softfloat_float64_to_int32_round_to_zero
+#define float32_to_int64_round_to_zero _softfloat_float32_to_int64_round_to_zero
+#define float64_to_int64_round_to_zero _softfloat_float64_to_int64_round_to_zero
+#define float32_to_uint32_round_to_zero        _softfloat_float32_to_uint32_round_to_zero
+#define float64_to_uint32_round_to_zero        _softfloat_float64_to_uint32_round_to_zero
+#define float32_to_float64             _softfloat_float32_to_float64
+#define float64_to_float32             _softfloat_float64_to_float32
+#define float32_is_signaling_nan       _softfloat_float32_is_signaling_nan
+#define float64_is_signaling_nan       _softfloat_float64_is_signaling_nan
+
+#endif /* SOFTFLOATSPARC64_FOR_GCC and !SOFTFLOAT_FOR_GCC */
+
+/*
+ * The following will always end up in the namespace if FLOAT128 is
+ * defined and SOFTFLOAT_FOR_GCC isn't. So rename them out of the user's
+ * namespace.
+ */
+
+#ifdef SOFTFLOATSPARC64_FOR_GCC
+#define        float128_add                    _softfloat_float128_add
+#define        float128_div                    _softfloat_float128_div
+#define        float128_eq                     _softfloat_float128_eq
+#define        float128_eq_signaling           _softfloat_float128_eq_signaling
+#define        float128_is_nan                 _softfloat_float128_is_nan
+#define        float128_is_signaling_nan       _softfloat_float128_is_signaling_nan
+#define        float128_le                     _softfloat_float128_le
+#define        float128_le_quiet               _softfloat_float128_le_quiet
+#define        float128_lt                     _softfloat_float128_lt
+#define        float128_lt_quiet               _softfloat_float128_lt_quiet
+#define        float128_mul                    _softfloat_float128_mul
+#define        float128_rem                    _softfloat_float128_rem
+#define        float128_round_to_int           _softfloat_float128_round_to_int
+#define        float128_sqrt                   _softfloat_float128_sqrt
+#define        float128_sub                    _softfloat_float128_sub
+#define        float128_to_float32             _softfloat_float128_to_float32
+#define        float128_to_float64             _softfloat_float128_to_float64
+#define        float128_to_int32               _softfloat_float128_to_int32
+#define        float128_to_int32_round_to_zero _softfloat_float128_to_int32_round_to_zero
+#define        float128_to_int64               _softfloat_float128_to_int64
+#define        float128_to_int64_round_to_zero _softfloat_float128_to_int64_round_to_zero
+#define        float128_to_uint64_round_to_zero        _softfloat_float128_to_uint64_round_to_zero
+#define        float32_to_float128             _softfloat_float32_to_float128
+#define        float64_to_float128             _softfloat_float64_to_float128
+#define        int32_to_float128               _softfloat_int32_to_float128
+#define        int64_to_float128               _softfloat_int64_to_float128
+
+/*
+ * If this isn't defined go ahead and set it now since this is now past
+ * anywhere define's are happening and this will conditionally compile out
+ * a lot of extraneous code in softfloat.c
+ */
+
+#ifndef SOFTFLOAT_FOR_GCC
+#define SOFTFLOAT_FOR_GCC
+#endif
+
+#endif /* SOFTFLOATSPARC64_FOR_GCC */
diff --git a/lib/nbsd_libc/arch/sparc64/softfloat/softfloat-wrapper.c b/lib/nbsd_libc/arch/sparc64/softfloat/softfloat-wrapper.c
new file mode 100644 (file)
index 0000000..ac5582a
--- /dev/null
@@ -0,0 +1 @@
+#include <softfloat.c>
diff --git a/lib/nbsd_libc/arch/sparc64/softfloat/softfloat.h b/lib/nbsd_libc/arch/sparc64/softfloat/softfloat.h
new file mode 100644 (file)
index 0000000..069c0e5
--- /dev/null
@@ -0,0 +1,303 @@
+/*     $NetBSD: softfloat.h,v 1.6 2007/11/08 15:50:23 martin Exp $     */
+
+/* This is a derivative work. */
+
+/*
+===============================================================================
+
+This C header file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+The macro `FLOATX80' must be defined to enable the extended double-precision
+floating-point format `floatx80'.  If this macro is not defined, the
+`floatx80' type will not be defined, and none of the functions that either
+input or output the `floatx80' type will be defined.  The same applies to
+the `FLOAT128' macro and the quadruple-precision format `float128'.
+-------------------------------------------------------------------------------
+*/
+/* #define FLOATX80 */
+#define FLOAT128
+
+#include "softfloat-qp.h"
+
+#include <machine/ieeefp.h>
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point types.
+-------------------------------------------------------------------------------
+*/
+typedef unsigned int float32;
+typedef unsigned long long float64;
+#ifdef FLOATX80
+typedef struct {
+    unsigned short high;
+    unsigned long long low;
+} floatx80;
+#endif
+#ifdef FLOAT128
+typedef struct {
+    unsigned long long high, low;
+} float128;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point underflow tininess-detection mode.
+-------------------------------------------------------------------------------
+*/
+#ifndef SOFTFLOAT_FOR_GCC
+extern int8 float_detect_tininess;
+#endif
+enum {
+    float_tininess_after_rounding  = 0,
+    float_tininess_before_rounding = 1
+};
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point rounding mode.
+-------------------------------------------------------------------------------
+*/
+extern fp_rnd float_rounding_mode;
+enum {
+    float_round_nearest_even = FP_RN,
+    float_round_to_zero      = FP_RZ,
+    float_round_down         = FP_RM,
+    float_round_up           = FP_RP
+};
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE floating-point exception flags.
+-------------------------------------------------------------------------------
+*/
+extern fp_except float_exception_flags;
+extern fp_except float_exception_mask;
+enum {
+    float_flag_inexact   = FP_X_IMP,
+    float_flag_underflow = FP_X_UFL,
+    float_flag_overflow  = FP_X_OFL,
+    float_flag_divbyzero = FP_X_DZ,
+    float_flag_invalid   = FP_X_INV
+};
+
+/*
+-------------------------------------------------------------------------------
+Routine to raise any or all of the software IEC/IEEE floating-point
+exception flags.
+-------------------------------------------------------------------------------
+*/
+void float_raise( fp_except );
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE integer-to-floating-point conversion routines.
+-------------------------------------------------------------------------------
+*/
+float32 int32_to_float32( int );
+float64 int32_to_float64( int );
+#ifdef FLOATX80
+floatx80 int32_to_floatx80( int );
+#endif
+#ifdef FLOAT128
+float128 int32_to_float128( int );
+#endif
+float32 int64_to_float32( long long );
+float64 int64_to_float64( long long );
+#ifdef FLOATX80
+floatx80 int64_to_floatx80( long long );
+#endif
+#ifdef FLOAT128
+float128 int64_to_float128( long long );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE single-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float32_to_int32( float32 );
+int float32_to_int32_round_to_zero( float32 );
+unsigned int float32_to_uint32_round_to_zero( float32 );
+long long float32_to_int64( float32 );
+long long float32_to_int64_round_to_zero( float32 );
+float64 float32_to_float64( float32 );
+#ifdef FLOATX80
+floatx80 float32_to_floatx80( float32 );
+#endif
+#ifdef FLOAT128
+float128 float32_to_float128( float32 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE single-precision operations.
+-------------------------------------------------------------------------------
+*/
+float32 float32_round_to_int( float32 );
+float32 float32_add( float32, float32 );
+float32 float32_sub( float32, float32 );
+float32 float32_mul( float32, float32 );
+float32 float32_div( float32, float32 );
+float32 float32_rem( float32, float32 );
+float32 float32_sqrt( float32 );
+flag float32_eq( float32, float32 );
+flag float32_le( float32, float32 );
+flag float32_lt( float32, float32 );
+flag float32_eq_signaling( float32, float32 );
+flag float32_le_quiet( float32, float32 );
+flag float32_lt_quiet( float32, float32 );
+flag float32_is_signaling_nan( float32 );
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE double-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float64_to_int32( float64 );
+int float64_to_int32_round_to_zero( float64 );
+unsigned int float64_to_uint32_round_to_zero( float64 );
+long long float64_to_int64( float64 );
+long long float64_to_int64_round_to_zero( float64 );
+float32 float64_to_float32( float64 );
+#ifdef FLOATX80
+floatx80 float64_to_floatx80( float64 );
+#endif
+#ifdef FLOAT128
+float128 float64_to_float128( float64 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE double-precision operations.
+-------------------------------------------------------------------------------
+*/
+float64 float64_round_to_int( float64 );
+float64 float64_add( float64, float64 );
+float64 float64_sub( float64, float64 );
+float64 float64_mul( float64, float64 );
+float64 float64_div( float64, float64 );
+float64 float64_rem( float64, float64 );
+float64 float64_sqrt( float64 );
+flag float64_eq( float64, float64 );
+flag float64_le( float64, float64 );
+flag float64_lt( float64, float64 );
+flag float64_eq_signaling( float64, float64 );
+flag float64_le_quiet( float64, float64 );
+flag float64_lt_quiet( float64, float64 );
+flag float64_is_signaling_nan( float64 );
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int floatx80_to_int32( floatx80 );
+int floatx80_to_int32_round_to_zero( floatx80 );
+long long floatx80_to_int64( floatx80 );
+long long floatx80_to_int64_round_to_zero( floatx80 );
+float32 floatx80_to_float32( floatx80 );
+float64 floatx80_to_float64( floatx80 );
+#ifdef FLOAT128
+float128 floatx80_to_float128( floatx80 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision rounding precision.  Valid
+values are 32, 64, and 80.
+-------------------------------------------------------------------------------
+*/
+extern int floatx80_rounding_precision;
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE extended double-precision operations.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_round_to_int( floatx80 );
+floatx80 floatx80_add( floatx80, floatx80 );
+floatx80 floatx80_sub( floatx80, floatx80 );
+floatx80 floatx80_mul( floatx80, floatx80 );
+floatx80 floatx80_div( floatx80, floatx80 );
+floatx80 floatx80_rem( floatx80, floatx80 );
+floatx80 floatx80_sqrt( floatx80 );
+flag floatx80_eq( floatx80, floatx80 );
+flag floatx80_le( floatx80, floatx80 );
+flag floatx80_lt( floatx80, floatx80 );
+flag floatx80_eq_signaling( floatx80, floatx80 );
+flag floatx80_le_quiet( floatx80, floatx80 );
+flag floatx80_lt_quiet( floatx80, floatx80 );
+flag floatx80_is_signaling_nan( floatx80 );
+
+#endif
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE quadruple-precision conversion routines.
+-------------------------------------------------------------------------------
+*/
+int float128_to_int32( float128 );
+int float128_to_int32_round_to_zero( float128 );
+long long float128_to_int64( float128 );
+long long float128_to_int64_round_to_zero( float128 );
+unsigned long long float128_to_uint64_round_to_zero( float128 );
+float32 float128_to_float32( float128 );
+float64 float128_to_float64( float128 );
+#ifdef FLOATX80
+floatx80 float128_to_floatx80( float128 );
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Software IEC/IEEE quadruple-precision operations.
+-------------------------------------------------------------------------------
+*/
+float128 float128_round_to_int( float128 );
+float128 float128_add( float128, float128 );
+float128 float128_sub( float128, float128 );
+float128 float128_mul( float128, float128 );
+float128 float128_div( float128, float128 );
+float128 float128_rem( float128, float128 );
+float128 float128_sqrt( float128 );
+flag float128_eq( float128, float128 );
+flag float128_le( float128, float128 );
+flag float128_lt( float128, float128 );
+flag float128_eq_signaling( float128, float128 );
+flag float128_le_quiet( float128, float128 );
+flag float128_lt_quiet( float128, float128 );
+flag float128_is_signaling_nan( float128 );
+flag float128_is_nan( float128 );
+
+#endif
diff --git a/lib/nbsd_libc/arch/sparc64/softfloat/sparc64-gcc.h b/lib/nbsd_libc/arch/sparc64/softfloat/sparc64-gcc.h
new file mode 100644 (file)
index 0000000..778e9d0
--- /dev/null
@@ -0,0 +1,89 @@
+/*     $NetBSD: sparc64-gcc.h,v 1.2 2005/12/24 21:11:16 perry Exp $    */
+
+/*
+-------------------------------------------------------------------------------
+One of the macros `BIGENDIAN' or `LITTLEENDIAN' must be defined.
+-------------------------------------------------------------------------------
+*/
+#include <machine/endian.h>
+#if _BYTE_ORDER == _BIG_ENDIAN
+#define BIGENDIAN
+#endif
+#if _BYTE_ORDER == _LITTLE_ENDIAN
+#define LITTLEENDIAN
+#endif
+
+/*
+-------------------------------------------------------------------------------
+The macro `BITS64' can be defined to indicate that 64-bit integer types are
+supported by the compiler.
+-------------------------------------------------------------------------------
+*/
+#define BITS64
+
+/*
+-------------------------------------------------------------------------------
+Each of the following `typedef's defines the most convenient type that holds
+integers of at least as many bits as specified.  For example, `uint8' should
+be the most convenient type that can hold unsigned integers of as many as
+8 bits.  The `flag' type must be able to hold either a 0 or 1.  For most
+implementations of C, `flag', `uint8', and `int8' should all be `typedef'ed
+to the same as `int'.
+-------------------------------------------------------------------------------
+*/
+typedef int flag;
+typedef int uint8;
+typedef int int8;
+typedef int uint16;
+typedef int int16;
+typedef unsigned int uint32;
+typedef signed int int32;
+#ifdef BITS64
+typedef unsigned long long int uint64;
+typedef signed long long int int64;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Each of the following `typedef's defines a type that holds integers
+of _exactly_ the number of bits specified.  For instance, for most
+implementation of C, `bits16' and `sbits16' should be `typedef'ed to
+`unsigned short int' and `signed short int' (or `short int'), respectively.
+-------------------------------------------------------------------------------
+*/
+typedef unsigned char bits8;
+typedef signed char sbits8;
+typedef unsigned short int bits16;
+typedef signed short int sbits16;
+typedef unsigned int bits32;
+typedef signed int sbits32;
+#ifdef BITS64
+typedef unsigned long long int bits64;
+typedef signed long long int sbits64;
+#endif
+
+#ifdef BITS64
+/*
+-------------------------------------------------------------------------------
+The `LIT64' macro takes as its argument a textual integer literal and
+if necessary ``marks'' the literal as having a 64-bit integer type.
+For example, the GNU C Compiler (`gcc') requires that 64-bit literals be
+appended with the letters `LL' standing for `long long', which is `gcc's
+name for the 64-bit integer type.  Some compilers may allow `LIT64' to be
+defined as the identity macro:  `#define LIT64( a ) a'.
+-------------------------------------------------------------------------------
+*/
+#define LIT64( a ) a##LL
+#endif
+
+/*
+-------------------------------------------------------------------------------
+The macro `INLINE' can be used before functions that should be inlined.  If
+a compiler does not support explicit inlining, this macro should be defined
+to be `static'.
+-------------------------------------------------------------------------------
+*/
+#define INLINE static inline
+
+#define FLOAT64_DEMANGLE(a)    (a)
+#define FLOAT64_MANGLE(a)      (a)
diff --git a/lib/nbsd_libc/arch/sparc64/stdlib/Makefile.inc b/lib/nbsd_libc/arch/sparc64/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..2f91b99
--- /dev/null
@@ -0,0 +1 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/07/31 20:40:00 dsl Exp $
diff --git a/lib/nbsd_libc/arch/sparc64/stdlib/abs.S b/lib/nbsd_libc/arch/sparc64/stdlib/abs.S
new file mode 100644 (file)
index 0000000..379b26e
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: abs.S,v 1.2 2003/08/07 16:42:28 agc Exp $      */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: abs.s,v 1.1 91/07/06 18:01:57 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)abs.s       8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: abs.S,v 1.2 2003/08/07 16:42:28 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/* abs - int absolute value */
+
+
+ENTRY(abs)
+       neg     %o0, %o1
+       retl
+        movrlz %o0, %o1, %o0
diff --git a/lib/nbsd_libc/arch/sparc64/string/Makefile.inc b/lib/nbsd_libc/arch/sparc64/string/Makefile.inc
new file mode 100644 (file)
index 0000000..3d197b8
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.8 2009/08/11 17:30:43 dsl Exp $
+
+SRCS+= ffs.S memcpy.S memset.S strlen.S
+NO_SRCS+= bcopy.S bzero.S
diff --git a/lib/nbsd_libc/arch/sparc64/string/memcpy.S b/lib/nbsd_libc/arch/sparc64/string/memcpy.S
new file mode 100644 (file)
index 0000000..7d677f4
--- /dev/null
@@ -0,0 +1,1958 @@
+/*     $NetBSD: memcpy.S,v 1.2 2001/08/01 05:52:12 eeh Exp $   */
+
+/*
+ * Copyright (c) 2001  Eduardo E. Horvath
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ */
+
+#include <machine/asm.h>
+#ifndef _LOCORE
+#define _LOCORE
+#endif
+#include <machine/ctlreg.h>
+#include <machine/frame.h>
+#include <machine/psl.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: memcpy.S,v 1.2 2001/08/01 05:52:12 eeh Exp $")
+#endif  /* LIBC_SCCS and not lint */
+
+#define        EMPTY   nop
+#define        NOTREACHED      ta      1
+
+#define        BCOPY_SMALL     16
+#define        BLOCK_SIZE      64
+
+#if 0
+#define ASI_STORE      ASI_BLK_COMMIT_P
+#else
+#define ASI_STORE      ASI_BLK_P
+#endif
+
+#if 1
+/*
+ * kernel bcopy/memcpy
+ * Assumes regions do not overlap; has no useful return value.
+ *
+ * Must not use %g7 (see copyin/copyout above).
+ */
+ENTRY(memcpy) /* dest, src, size */
+       /*
+        * Swap args for bcopy.  Gcc generates calls to memcpy for
+        * structure assignments.
+        */
+       mov     %o0, %o3
+       mov     %o1, %o0
+       mov     %o3, %o1
+#endif
+ENTRY(bcopy) /* src, dest, size */
+#ifdef DEBUG
+       set     pmapdebug, %o4
+       ld      [%o4], %o4
+       btst    0x80, %o4       ! PDB_COPY
+       bz,pt   %icc, 3f
+        nop
+       save    %sp, -CC64FSZ, %sp
+       mov     %i0, %o1
+       set     2f, %o0
+       mov     %i1, %o2
+       call    printf
+        mov    %i2, %o3
+!      ta      1; nop
+       restore
+       .data
+2:     .asciz  "bcopy(%p->%p,%x)\n"
+       _ALIGN
+       .text
+3:
+#endif
+       /*
+        * Check for overlaps and punt.
+        *
+        * If src <= dest <= src+len we have a problem.
+        */
+
+       sub     %o1, %o0, %o3
+
+       cmp     %o3, %o2
+       blu,pn  %xcc, Lovbcopy
+        cmp    %o2, BCOPY_SMALL
+Lbcopy_start:
+       bge,pt  %xcc, 2f        ! if >= this many, go be fancy.
+        cmp    %o2, 256
+
+       mov     %o1, %o5        ! Save memcpy return value
+       /*
+        * Not much to copy, just do it a byte at a time.
+        */
+       deccc   %o2             ! while (--len >= 0)
+       bl      1f
+        EMPTY
+0:
+       inc     %o0
+       ldsb    [%o0 - 1], %o4  !       (++dst)[-1] = *src++;
+       stb     %o4, [%o1]
+       deccc   %o2
+       bge     0b
+        inc    %o1
+1:
+       retl
+        mov    %o5, %o0
+       NOTREACHED
+
+       /*
+        * Overlapping bcopies -- punt.
+        */
+Lovbcopy:
+
+       /*
+        * Since src comes before dst, and the regions might overlap,
+        * we have to do the copy starting at the end and working backwards.
+        *
+        * We could optimize this, but it almost never happens.
+        */
+       mov     %o1, %o5        ! Retval
+       add     %o2, %o0, %o0   ! src += len
+       add     %o2, %o1, %o1   ! dst += len
+       
+       deccc   %o2
+       bl,pn   %xcc, 1f
+        dec    %o0
+0:
+       dec     %o1
+       ldsb    [%o0], %o4
+       dec     %o0
+       
+       deccc   %o2
+       bge,pt  %xcc, 0b
+        stb    %o4, [%o1]
+1:
+       retl
+        mov    %o5, %o0
+
+       /*
+        * Plenty of data to copy, so try to do it optimally.
+        */
+2:
+#if 1
+       ! If it is big enough, use VIS instructions
+       bge     Lbcopy_block
+        nop
+#endif
+Lbcopy_fancy:
+
+       !!
+       !! First align the output to a 8-byte entity
+       !! 
+
+       save    %sp, -CC64FSZ, %sp
+       
+       mov     %i0, %o0
+       mov     %i1, %o1
+       
+       mov     %i2, %o2
+       btst    1, %o1
+       
+       bz,pt   %icc, 4f
+        btst   2, %o1
+       ldub    [%o0], %o4                              ! Load 1st byte
+       
+       deccc   1, %o2
+       ble,pn  %xcc, Lbcopy_finish                     ! XXXX
+        inc    1, %o0
+       
+       stb     %o4, [%o1]                              ! Store 1st byte
+       inc     1, %o1                                  ! Update address
+       btst    2, %o1
+4:     
+       bz,pt   %icc, 4f
+       
+        btst   1, %o0
+       bz,a    1f
+        lduh   [%o0], %o4                              ! Load short
+
+       ldub    [%o0], %o4                              ! Load bytes
+       
+       ldub    [%o0+1], %o3
+       sllx    %o4, 8, %o4
+       or      %o3, %o4, %o4
+       
+1:     
+       deccc   2, %o2
+       ble,pn  %xcc, Lbcopy_finish                     ! XXXX
+        inc    2, %o0
+       sth     %o4, [%o1]                              ! Store 1st short
+       
+       inc     2, %o1
+4:
+       btst    4, %o1
+       bz,pt   %xcc, 4f
+       
+        btst   3, %o0
+       bz,a,pt %xcc, 1f
+        lduw   [%o0], %o4                              ! Load word -1
+
+       btst    1, %o0
+       bz,a,pt %icc, 2f
+        lduh   [%o0], %o4
+       
+       ldub    [%o0], %o4
+       
+       lduh    [%o0+1], %o3
+       sllx    %o4, 16, %o4
+       or      %o4, %o3, %o4
+       
+       ldub    [%o0+3], %o3
+       sllx    %o4, 8, %o4
+       ba,pt   %icc, 1f
+        or     %o4, %o3, %o4
+       
+2:
+       lduh    [%o0+2], %o3
+       sllx    %o4, 16, %o4
+       or      %o4, %o3, %o4
+       
+1:     
+       deccc   4, %o2
+       ble,pn  %xcc, Lbcopy_finish             ! XXXX
+        inc    4, %o0
+       
+       st      %o4, [%o1]                              ! Store word
+       inc     4, %o1
+4:
+       !!
+       !! We are now 32-bit aligned in the dest.
+       !!
+Lbcopy__common:        
+
+       and     %o0, 7, %o4                             ! Shift amount
+       andn    %o0, 7, %o0                             ! Source addr
+       
+       brz,pt  %o4, Lbcopy_noshift8                    ! No shift version...
+
+        sllx   %o4, 3, %o4                             ! In bits
+       mov     8<<3, %o3
+       
+       ldx     [%o0], %l0                              ! Load word -1
+       sub     %o3, %o4, %o3                           ! Reverse shift
+       deccc   16*8, %o2                               ! Have enough room?
+       
+       sllx    %l0, %o4, %l0
+       bl,pn   %xcc, 2f
+        and    %o3, 0x38, %o3
+Lbcopy_unrolled8:
+
+       /*
+        * This is about as close to optimal as you can get, since
+        * the shifts require EU0 and cannot be paired, and you have
+        * 3 dependent operations on the data.
+        */ 
+
+!      ldx     [%o0+0*8], %l0                          ! Already done
+!      sllx    %l0, %o4, %l0                           ! Already done
+       ldx     [%o0+1*8], %l1
+       ldx     [%o0+2*8], %l2
+       ldx     [%o0+3*8], %l3
+       ldx     [%o0+4*8], %l4
+       ldx     [%o0+5*8], %l5
+       ldx     [%o0+6*8], %l6
+#if 1
+       ba,pt   %icc, 1f
+        ldx    [%o0+7*8], %l7
+       .align  8
+1:
+       srlx    %l1, %o3, %g1
+       inc     8*8, %o0
+       
+       sllx    %l1, %o4, %l1
+       or      %g1, %l0, %o5
+       ldx     [%o0+0*8], %l0
+       
+       stx     %o5, [%o1+0*8]
+       srlx    %l2, %o3, %g1
+
+       sllx    %l2, %o4, %l2
+       or      %g1, %l1, %o5
+       ldx     [%o0+1*8], %l1
+       
+       stx     %o5, [%o1+1*8]
+       srlx    %l3, %o3, %g1
+       
+       sllx    %l3, %o4, %l3
+       or      %g1, %l2, %o5
+       ldx     [%o0+2*8], %l2
+       
+       stx     %o5, [%o1+2*8]
+       srlx    %l4, %o3, %g1
+       
+       sllx    %l4, %o4, %l4   
+       or      %g1, %l3, %o5
+       ldx     [%o0+3*8], %l3
+       
+       stx     %o5, [%o1+3*8]
+       srlx    %l5, %o3, %g1
+       
+       sllx    %l5, %o4, %l5
+       or      %g1, %l4, %o5
+       ldx     [%o0+4*8], %l4
+       
+       stx     %o5, [%o1+4*8]
+       srlx    %l6, %o3, %g1
+       
+       sllx    %l6, %o4, %l6
+       or      %g1, %l5, %o5
+       ldx     [%o0+5*8], %l5
+       
+       stx     %o5, [%o1+5*8]
+       srlx    %l7, %o3, %g1
+       
+       sllx    %l7, %o4, %l7
+       or      %g1, %l6, %o5
+       ldx     [%o0+6*8], %l6
+       
+       stx     %o5, [%o1+6*8]
+       srlx    %l0, %o3, %g1
+       deccc   8*8, %o2                                ! Have enough room?
+       
+       sllx    %l0, %o4, %l0                           ! Next loop
+       or      %g1, %l7, %o5
+       ldx     [%o0+7*8], %l7
+       
+       stx     %o5, [%o1+7*8]
+       bge,pt  %xcc, 1b
+        inc    8*8, %o1
+
+Lbcopy_unrolled8_cleanup:      
+       !!
+       !! Finished 8 byte block, unload the regs.
+       !! 
+       srlx    %l1, %o3, %g1
+       inc     7*8, %o0
+       
+       sllx    %l1, %o4, %l1
+       or      %g1, %l0, %o5
+               
+       stx     %o5, [%o1+0*8]
+       srlx    %l2, %o3, %g1
+       
+       sllx    %l2, %o4, %l2
+       or      %g1, %l1, %o5
+               
+       stx     %o5, [%o1+1*8]
+       srlx    %l3, %o3, %g1
+       
+       sllx    %l3, %o4, %l3
+       or      %g1, %l2, %o5
+               
+       stx     %o5, [%o1+2*8]
+       srlx    %l4, %o3, %g1
+       
+       sllx    %l4, %o4, %l4   
+       or      %g1, %l3, %o5
+               
+       stx     %o5, [%o1+3*8]
+       srlx    %l5, %o3, %g1
+       
+       sllx    %l5, %o4, %l5
+       or      %g1, %l4, %o5
+               
+       stx     %o5, [%o1+4*8]
+       srlx    %l6, %o3, %g1
+       
+       sllx    %l6, %o4, %l6
+       or      %g1, %l5, %o5
+               
+       stx     %o5, [%o1+5*8]
+       srlx    %l7, %o3, %g1
+       
+       sllx    %l7, %o4, %l7
+       or      %g1, %l6, %o5
+               
+       stx     %o5, [%o1+6*8]
+       inc     7*8, %o1
+       
+       mov     %l7, %l0                                ! Save our unused data
+       dec     7*8, %o2
+#else
+       /*
+        * This version also handles aligned copies at almost the
+        * same speed.  It should take the same number of cycles
+        * as the previous version, but is slightly slower, probably
+        * due to i$ issues.
+        */
+       ldx     [%o0+7*8], %l7
+       ba,pt   %icc, 1f
+        clr    %g1
+       .align 32
+1:
+       srlx    %l1, %o3, %g1
+       bz,pn   %xcc, 3f
+        inc    8*8, %o0
+
+       sllx    %l1, %o4, %l1
+       or      %g1, %l0, %o5
+       ba,pt   %icc, 4f
+       ldx     [%o0+0*8], %l0
+       
+       nop
+3:
+       mov     %l0, %o5
+       ldx     [%o0+0*8], %l0
+       
+4:     
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+0*8]
+       srlx    %l2, %o3, %g1
+
+       sllx    %l2, %o4, %l2
+3:     
+       or      %g1, %l1, %o5
+       ldx     [%o0+1*8], %l1
+       
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+1*8]
+       srlx    %l3, %o3, %g1
+       
+       sllx    %l3, %o4, %l3
+3:     
+       or      %g1, %l2, %o5
+       ldx     [%o0+2*8], %l2
+       
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+2*8]
+       srlx    %l4, %o3, %g1
+       
+       sllx    %l4, %o4, %l4
+3:     
+       or      %g1, %l3, %o5
+       ldx     [%o0+3*8], %l3
+       
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+3*8]
+       srlx    %l5, %o3, %g1
+       
+       sllx    %l5, %o4, %l5
+3:     
+       or      %g1, %l4, %o5
+       ldx     [%o0+4*8], %l4
+       
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+4*8]
+       srlx    %l6, %o3, %g1
+       
+       sllx    %l6, %o4, %l6
+3:     
+       or      %g1, %l5, %o5
+       ldx     [%o0+5*8], %l5
+       
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+5*8]
+       srlx    %l7, %o3, %g1
+       
+       sllx    %l7, %o4, %l7
+3:     
+       or      %g1, %l6, %o5
+       ldx     [%o0+6*8], %l6
+       
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+6*8]
+       srlx    %l0, %o3, %g1
+       
+       sllx    %l0, %o4, %l0                           ! Next loop
+3:     
+       or      %g1, %l7, %o5
+       ldx     [%o0+7*8], %l7
+       deccc   8*8, %o2                                ! Have enough room?
+       
+       stx     %o5, [%o1+7*8]
+       inc     8*8, %o1
+       bge,pt  %xcc, 1b
+        tst    %o4
+
+
+       !!
+       !! Now unload all those regs
+       !! 
+Lbcopy_unrolled8_cleanup:      
+       srlx    %l1, %o3, %g1
+       bz,pn   %xcc, 3f
+        inc    7*8, %o0                                ! Point at the last load
+
+       sllx    %l1, %o4, %l1
+       ba,pt   %icc, 4f
+        or     %g1, %l0, %o5
+       
+3:
+       mov     %l0, %o5
+       
+4:     
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+0*8]
+       srlx    %l2, %o3, %g1
+
+       sllx    %l2, %o4, %l2
+3:     
+       or      %g1, %l1, %o5
+       
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+1*8]
+       srlx    %l3, %o3, %g1
+       
+       sllx    %l3, %o4, %l3
+3:     
+       or      %g1, %l2, %o5
+       
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+2*8]
+       srlx    %l4, %o3, %g1
+       
+       sllx    %l4, %o4, %l4
+3:     
+       or      %g1, %l3, %o5
+       
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+3*8]
+       srlx    %l5, %o3, %g1
+       
+       sllx    %l5, %o4, %l5
+3:     
+       or      %g1, %l4, %o5
+       
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+4*8]
+       srlx    %l6, %o3, %g1
+       
+       sllx    %l6, %o4, %l6
+3:     
+       or      %g1, %l5, %o5
+       
+       bz,pn   %icc, 3f
+       stx     %o5, [%o1+5*8]
+       srlx    %l7, %o3, %g1
+       
+       sllx    %l7, %o4, %l7
+3:     
+       or      %g1, %l6, %o5
+       mov     %l7, %l0                                ! Shuffle to %l0
+       
+       stx     %o5, [%o1+6*8]
+       or      %g1, %l7, %o5
+       dec     7*8, %o2
+       
+       inc     7*8, %o1                                ! Point at last store
+#endif
+2:
+       inccc   16*8, %o2
+       bz,pn   %icc, Lbcopy_complete
+       
+       !! Unrolled 8 times
+Lbcopy_aligned8:       
+!      ldx     [%o0], %l0                              ! Already done
+!      sllx    %l0, %o4, %l0                           ! Shift high word
+       
+        deccc  8, %o2                                  ! Pre-decrement
+       bl,pn   %xcc, Lbcopy_finish
+1:
+       ldx     [%o0+8], %l1                            ! Load word 0
+       inc     8, %o0
+       
+       srlx    %l1, %o3, %o5
+       or      %o5, %l0, %o5                           ! Combine
+       
+       stx     %o5, [%o1]                              ! Store result
+        inc    8, %o1
+       
+       deccc   8, %o2
+       bge,pn  %xcc, 1b
+        sllx   %l1, %o4, %l0   
+
+       btst    7, %o2                                  ! Done?
+       bz,pt   %xcc, Lbcopy_complete
+
+       !!
+       !! Loadup the last dregs into %l0 and shift it into place
+       !! 
+        srlx   %o3, 3, %o5                             ! # bytes in %l0
+       dec     8, %o5                                  !  - 8
+       !! n-8 - (by - 8) -> n - by
+       subcc   %o2, %o5, %g0                           ! # bytes we need
+       ble,pt  %icc, Lbcopy_finish
+        nop
+       ldx     [%o0+8], %l1                            ! Need another word
+       srlx    %l1, %o3, %l1
+       ba,pt   %icc, Lbcopy_finish
+        or     %l0, %l1, %l0                           ! All loaded up.
+       
+Lbcopy_noshift8:
+       deccc   8*8, %o2                                ! Have enough room?
+       bl,pn   %xcc, 2f
+        nop
+       ba,pt   %icc, 1f
+        nop
+       .align  32
+1:     
+       ldx     [%o0+0*8], %l0
+       ldx     [%o0+1*8], %l1
+       ldx     [%o0+2*8], %l2
+       ldx     [%o0+3*8], %l3
+       stx     %l0, [%o1+0*8]
+       stx     %l1, [%o1+1*8]
+       stx     %l2, [%o1+2*8]
+       stx     %l3, [%o1+3*8]
+
+       
+       ldx     [%o0+4*8], %l4
+       ldx     [%o0+5*8], %l5
+       ldx     [%o0+6*8], %l6
+       ldx     [%o0+7*8], %l7
+       inc     8*8, %o0
+       stx     %l4, [%o1+4*8]
+       stx     %l5, [%o1+5*8]
+       deccc   8*8, %o2
+       stx     %l6, [%o1+6*8]
+       stx     %l7, [%o1+7*8]
+       stx     %l2, [%o1+2*8]
+       bge,pt  %xcc, 1b
+        inc    8*8, %o1
+2:
+       inc     8*8, %o2
+1:     
+       deccc   8, %o2
+       bl,pn   %icc, 1f                                ! < 0 --> sub word
+        nop
+       ldx     [%o0], %o5
+       inc     8, %o0
+       stx     %o5, [%o1]
+       bg,pt   %icc, 1b                                ! Exactly 0 --> done
+        inc    8, %o1
+1:
+       btst    7, %o2                                  ! Done?
+       bz,pt   %xcc, Lbcopy_complete
+        clr    %o4
+       ldx     [%o0], %l0
+Lbcopy_finish:
+       
+       brz,pn  %o2, 2f                                 ! 100% complete?
+        cmp    %o2, 8                                  ! Exactly 8 bytes?
+       bz,a,pn %xcc, 2f
+        stx    %l0, [%o1]
+
+       btst    4, %o2                                  ! Word store?
+       bz      %xcc, 1f
+        srlx   %l0, 32, %o5                            ! Shift high word down
+       stw     %o5, [%o1]
+       inc     4, %o1
+       mov     %l0, %o5                                ! Operate on the low bits
+1:
+       btst    2, %o2
+       mov     %o5, %l0
+       bz      1f
+        srlx   %l0, 16, %o5
+       
+       sth     %o5, [%o1]                              ! Store short
+       inc     2, %o1
+       mov     %l0, %o5                                ! Operate on low bytes
+1:
+       mov     %o5, %l0
+       btst    1, %o2                                  ! Byte aligned?
+       bz      2f
+        srlx   %l0, 8, %o5
+
+       stb     %o5, [%o1]                              ! Store last byte
+       inc     1, %o1                                  ! Update address
+2:     
+Lbcopy_complete:
+#if 0
+       !!
+       !! verify copy success.
+       !! 
+
+       mov     %i0, %o2
+       mov     %i1, %o4
+       mov     %i2, %l4
+0:     
+       ldub    [%o2], %o1
+       inc     %o2
+       ldub    [%o4], %o3
+       inc     %o4
+       cmp     %o3, %o1
+       bnz     1f
+        dec    %l4
+       brnz    %l4, 0b
+        nop
+       ba      2f
+        nop
+
+1:
+       set     0f, %o0
+       call    printf
+        sub    %i2, %l4, %o5
+       set     1f, %o0
+       mov     %i0, %o1
+       mov     %i1, %o2
+       call    printf
+        mov    %i2, %o3
+       ta      1
+       .data
+0:     .asciz  "bcopy failed: %x@%p != %x@%p byte %d\n"
+1:     .asciz  "bcopy(%p, %p, %lx)\n"
+       .align 8
+       .text
+2:     
+#endif
+       ret
+        restore %i1, %g0, %o0
+
+#if 1
+
+/*
+ * Block copy.  Useful for >256 byte copies.
+ *
+ * Benchmarking has shown this always seems to be slower than
+ * the integer version, so this is disabled.  Maybe someone will
+ * figure out why sometime.
+ */
+       
+Lbcopy_block:
+#ifdef _KERNEL
+/*
+ * Kernel:
+ *
+ * Here we use VIS instructions to do a block clear of a page.
+ * But before we can do that we need to save and enable the FPU.
+ * The last owner of the FPU registers is fpproc, and
+ * fpproc->p_md.md_fpstate is the current fpstate.  If that's not
+ * null, call savefpstate() with it to store our current fp state.
+ *
+ * Next, allocate an aligned fpstate on the stack.  We will properly
+ * nest calls on a particular stack so this should not be a problem.
+ *
+ * Now we grab either curproc (or if we're on the interrupt stack
+ * proc0).  We stash its existing fpstate in a local register and
+ * put our new fpstate in curproc->p_md.md_fpstate.  We point
+ * fpproc at curproc (or proc0) and enable the FPU.
+ *
+ * If we are ever preempted, our FPU state will be saved in our
+ * fpstate.  Then, when we're resumed and we take an FPDISABLED
+ * trap, the trap handler will be able to fish our FPU state out
+ * of curproc (or proc0).
+ *
+ * On exiting this routine we undo the damage: restore the original
+ * pointer to curproc->p_md.md_fpstate, clear our fpproc, and disable
+ * the MMU.
+ *
+ *
+ * Register usage, Kernel only (after save):
+ *
+ * %i0         src
+ * %i1         dest
+ * %i2         size
+ *
+ * %l0         XXXX DEBUG old fpstate
+ * %l1         fpproc (hi bits only)
+ * %l2         orig fpproc
+ * %l3         orig fpstate
+ * %l5         curproc
+ * %l6         old fpstate
+ *
+ * Register ussage, Kernel and user:
+ *
+ * %g1         src (retval for memcpy)
+ *
+ * %o0         src
+ * %o1         dest
+ * %o2         end dest
+ * %o5         last safe fetchable address
+ */
+
+#if 1
+       ENABLE_FPU(0)
+#else
+       save    %sp, -(CC64FSZ+FS_SIZE+BLOCK_SIZE), %sp ! Allocate an fpstate
+       sethi   %hi(FPPROC), %l1
+       LDPTR   [%l1 + %lo(FPPROC)], %l2                ! Load fpproc
+       add     %sp, (CC64FSZ+STKB+BLOCK_SIZE-1), %l0   ! Calculate pointer to fpstate
+       brz,pt  %l2, 1f                                 ! fpproc == NULL?
+        andn   %l0, BLOCK_ALIGN, %l0                   ! And make it block aligned
+       LDPTR   [%l2 + P_FPSTATE], %l3
+       brz,pn  %l3, 1f                                 ! Make sure we have an fpstate
+        mov    %l3, %o0
+       call    _C_LABEL(savefpstate)                   ! Save the old fpstate
+        set    EINTSTACK-STKB, %l4                     ! Are we on intr stack?
+       cmp     %sp, %l4
+       bgu,pt  %xcc, 1f
+        set    INTSTACK-STKB, %l4
+       cmp     %sp, %l4
+       blu     %xcc, 1f
+0:
+        sethi  %hi(_C_LABEL(proc0)), %l4               ! Yes, use proc0
+       ba,pt   %xcc, 2f                                ! XXXX needs to change to CPUs idle proc
+        or     %l4, %lo(_C_LABEL(proc0)), %l5
+1:
+       sethi   %hi(CURPROC), %l4                       ! Use curproc
+       LDPTR   [%l4 + %lo(CURPROC)], %l5
+       brz,pn  %l5, 0b                                 ! If curproc is NULL need to use proc0
+        nop
+2:
+       LDPTR   [%l5 + P_FPSTATE], %l6                  ! Save old fpstate
+       STPTR   %l0, [%l5 + P_FPSTATE]                  ! Insert new fpstate
+       STPTR   %l5, [%l1 + %lo(FPPROC)]                ! Set new fpproc
+       wr      %g0, FPRS_FEF, %fprs                    ! Enable FPU
+#endif
+       mov     %i0, %o0                                ! Src addr.
+       mov     %i1, %o1                                ! Store our dest ptr here.
+       mov     %i2, %o2                                ! Len counter
+#endif
+
+       !!
+       !! First align the output to a 64-bit entity
+       !! 
+
+       mov     %o1, %g1                                ! memcpy retval
+       add     %o0, %o2, %o5                           ! End of source block
+
+       andn    %o0, 7, %o3                             ! Start of block
+       dec     %o5
+       fzero   %f0
+
+       andn    %o5, BLOCK_ALIGN, %o5                   ! Last safe addr.
+       ldd     [%o3], %f2                              ! Load 1st word
+
+       dec     8, %o3                                  ! Move %o3 1 word back
+       btst    1, %o1
+       bz      4f
+       
+        mov    -7, %o4                                 ! Lowest src addr possible
+       alignaddr %o0, %o4, %o4                         ! Base addr for load.
+
+       cmp     %o3, %o4
+       be,pt   %xcc, 1f                                ! Already loaded?
+        mov    %o4, %o3
+       fmovd   %f2, %f0                                ! No. Shift
+       ldd     [%o3+8], %f2                            ! And load
+1:     
+
+       faligndata      %f0, %f2, %f4                   ! Isolate 1st byte
+
+       stda    %f4, [%o1] ASI_FL8_P                    ! Store 1st byte
+       inc     1, %o1                                  ! Update address
+       inc     1, %o0
+       dec     1, %o2
+4:     
+       btst    2, %o1
+       bz      4f
+
+        mov    -6, %o4                                 ! Calculate src - 6
+       alignaddr %o0, %o4, %o4                         ! calculate shift mask and dest.
+
+       cmp     %o3, %o4                                ! Addresses same?
+       be,pt   %xcc, 1f
+        mov    %o4, %o3
+       fmovd   %f2, %f0                                ! Shuffle data
+       ldd     [%o3+8], %f2                            ! Load word 0
+1:     
+       faligndata %f0, %f2, %f4                        ! Move 1st short low part of f8
+
+       stda    %f4, [%o1] ASI_FL16_P                   ! Store 1st short
+       dec     2, %o2
+       inc     2, %o1
+       inc     2, %o0
+4:
+       brz,pn  %o2, Lbcopy_blockfinish                 ! XXXX
+
+        btst   4, %o1
+       bz      4f
+
+       mov     -4, %o4
+       alignaddr %o0, %o4, %o4                         ! calculate shift mask and dest.
+
+       cmp     %o3, %o4                                ! Addresses same?
+       beq,pt  %xcc, 1f
+        mov    %o4, %o3
+       fmovd   %f2, %f0                                ! Shuffle data
+       ldd     [%o3+8], %f2                            ! Load word 0
+1:     
+       faligndata %f0, %f2, %f4                        ! Move 1st short low part of f8
+
+       st      %f5, [%o1]                              ! Store word
+       dec     4, %o2
+       inc     4, %o1
+       inc     4, %o0
+4:
+       brz,pn  %o2, Lbcopy_blockfinish                 ! XXXX
+       !!
+       !! We are now 32-bit aligned in the dest.
+       !!
+Lbcopy_block_common:   
+
+        mov    -0, %o4
+       alignaddr %o0, %o4, %o4                         ! base - shift
+
+       cmp     %o3, %o4                                ! Addresses same?
+       beq,pt  %xcc, 1f
+        mov    %o4, %o3
+       fmovd   %f2, %f0                                ! Shuffle data
+       ldd     [%o3+8], %f2                            ! Load word 0
+1:     
+       add     %o3, 8, %o0                             ! now use %o0 for src
+       
+       !!
+       !! Continue until our dest is block aligned
+       !! 
+Lbcopy_block_aligned8: 
+1:
+       brz     %o2, Lbcopy_blockfinish
+        btst   BLOCK_ALIGN, %o1                        ! Block aligned?
+       bz      1f
+       
+        faligndata %f0, %f2, %f4                       ! Generate result
+       deccc   8, %o2
+       ble,pn  %icc, Lbcopy_blockfinish                ! Should never happen
+        fmovd  %f4, %f48
+       
+       std     %f4, [%o1]                              ! Store result
+       inc     8, %o1
+       
+       fmovd   %f2, %f0
+       inc     8, %o0
+       ba,pt   %xcc, 1b                                ! Not yet.
+        ldd    [%o0], %f2                              ! Load next part
+Lbcopy_block_aligned64:        
+1:
+
+/*
+ * 64-byte aligned -- ready for block operations.
+ *
+ * Here we have the destination block aligned, but the
+ * source pointer may not be.  Sub-word alignment will
+ * be handled by faligndata instructions.  But the source
+ * can still be potentially aligned to 8 different words
+ * in our 64-bit block, so we have 8 different copy routines.
+ *
+ * Once we figure out our source alignment, we branch
+ * to the appropriate copy routine, which sets up the
+ * alignment for faligndata and loads (sets) the values
+ * into the source registers and does the copy loop.
+ *
+ * When were down to less than 1 block to store, we
+ * exit the copy loop and execute cleanup code.
+ *
+ * Block loads and stores are not properly interlocked.
+ * Stores save one reg/cycle, so you can start overwriting
+ * registers the cycle after the store is issued.  
+ * 
+ * Block loads require a block load to a different register
+ * block or a membar #Sync before accessing the loaded
+ * data.
+ *     
+ * Since the faligndata instructions may be offset as far
+ * as 7 registers into a block (if you are shifting source 
+ * 7 -> dest 0), you need 3 source register blocks for full 
+ * performance: one you are copying, one you are loading, 
+ * and one for interlocking.  Otherwise, we would need to
+ * sprinkle the code with membar #Sync and lose the advantage
+ * of running faligndata in parallel with block stores.  This 
+ * means we are fetching a full 128 bytes ahead of the stores.  
+ * We need to make sure the prefetch does not inadvertently 
+ * cross a page boundary and fault on data that we will never 
+ * store.
+ *
+ */
+#if 1
+       and     %o0, BLOCK_ALIGN, %o3
+       srax    %o3, 3, %o3                             ! Isolate the offset
+
+       brz     %o3, L100                               ! 0->0
+        btst   4, %o3
+       bnz     %xcc, 4f
+        btst   2, %o3
+       bnz     %xcc, 2f
+        btst   1, %o3
+       ba,pt   %xcc, L101                              ! 0->1
+        nop    /* XXX spitfire bug */
+2:
+       bz      %xcc, L102                              ! 0->2
+        nop
+       ba,pt   %xcc, L103                              ! 0->3
+        nop    /* XXX spitfire bug */
+4:     
+       bnz     %xcc, 2f
+        btst   1, %o3
+       bz      %xcc, L104                              ! 0->4
+        nop
+       ba,pt   %xcc, L105                              ! 0->5
+        nop    /* XXX spitfire bug */
+2:
+       bz      %xcc, L106                              ! 0->6
+        nop
+       ba,pt   %xcc, L107                              ! 0->7
+        nop    /* XXX spitfire bug */
+#else
+
+       !!
+       !! Isolate the word offset, which just happens to be
+       !! the slot in our jump table.
+       !!
+       !! This is 6 insns, most of which cannot be paired,
+       !! which is about the same as the above version.
+       !!
+       rd      %pc, %o4
+1:     
+       and     %o0, 0x31, %o3
+       add     %o3, (Lbcopy_block_jmp - 1b), %o3
+       jmpl    %o4 + %o3, %g0
+        nop
+
+       !!
+       !! Jump table
+       !!
+       
+Lbcopy_block_jmp:
+       ba,a,pt %xcc, L100
+        nop
+       ba,a,pt %xcc, L101
+        nop
+       ba,a,pt %xcc, L102
+        nop
+       ba,a,pt %xcc, L103
+        nop
+       ba,a,pt %xcc, L104
+        nop
+       ba,a,pt %xcc, L105
+        nop
+       ba,a,pt %xcc, L106
+        nop
+       ba,a,pt %xcc, L107
+        nop
+#endif
+
+       !!
+       !! Source is block aligned.
+       !!
+       !! Just load a block and go.
+       !!
+L100:
+#ifdef RETURN_NAME
+       sethi   %hi(1f), %g1
+       ba,pt   %icc, 2f
+        or     %g1, %lo(1f), %g1
+1:     
+       .asciz  "L100"
+       .align  8
+2:     
+#endif
+       fmovd   %f0 , %f62
+       ldda    [%o0] ASI_BLK_P, %f0
+       inc     BLOCK_SIZE, %o0
+       cmp     %o0, %o5
+       bleu,a,pn       %icc, 3f
+        ldda   [%o0] ASI_BLK_P, %f16
+       ba,pt   %icc, 3f
+        membar #Sync
+       
+       .align  32                                      ! ICache align.
+3:
+       faligndata      %f62, %f0, %f32
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f0, %f2, %f34
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f2, %f4, %f36
+       cmp     %o0, %o5
+       faligndata      %f4, %f6, %f38
+       faligndata      %f6, %f8, %f40
+       faligndata      %f8, %f10, %f42
+       faligndata      %f10, %f12, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f12, %f14, %f46
+       
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f48
+       membar  #Sync
+2:     
+       stda    %f32, [%o1] ASI_STORE
+       faligndata      %f14, %f16, %f32
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f16, %f18, %f34
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f18, %f20, %f36
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f20, %f22, %f38
+       cmp     %o0, %o5
+       faligndata      %f22, %f24, %f40
+       faligndata      %f24, %f26, %f42
+       faligndata      %f26, %f28, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f28, %f30, %f46
+       
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f0
+       membar  #Sync
+2:
+       stda    %f32, [%o1] ASI_STORE
+       faligndata      %f30, %f48, %f32
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f48, %f50, %f34
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f50, %f52, %f36
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f52, %f54, %f38
+       cmp     %o0, %o5
+       faligndata      %f54, %f56, %f40
+       faligndata      %f56, %f58, %f42
+       faligndata      %f58, %f60, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f60, %f62, %f46
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16                   ! Increment is at top
+       membar  #Sync
+2:     
+       stda    %f32, [%o1] ASI_STORE
+       ba      3b
+        inc    BLOCK_SIZE, %o1
+       
+       !!
+       !! Source at BLOCK_ALIGN+8
+       !!
+       !! We need to load almost 1 complete block by hand.
+       !! 
+L101:
+#ifdef RETURN_NAME
+       sethi   %hi(1f), %g1
+       ba,pt   %icc, 2f
+        or     %g1, %lo(1f), %g1
+1:     
+       .asciz  "L101"
+       .align  8
+2:     
+#endif
+!      fmovd   %f0, %f0                                ! Hoist fmovd
+       ldd     [%o0], %f2
+       inc     8, %o0
+       ldd     [%o0], %f4
+       inc     8, %o0
+       ldd     [%o0], %f6
+       inc     8, %o0
+       ldd     [%o0], %f8
+       inc     8, %o0
+       ldd     [%o0], %f10
+       inc     8, %o0
+       ldd     [%o0], %f12
+       inc     8, %o0
+       ldd     [%o0], %f14
+       inc     8, %o0
+       
+       cmp     %o0, %o5
+       bleu,a,pn       %icc, 3f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar #Sync
+3:     
+       faligndata      %f0, %f2, %f32
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f2, %f4, %f34
+       cmp     %o0, %o5
+       faligndata      %f4, %f6, %f36
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f6, %f8, %f38
+       faligndata      %f8, %f10, %f40
+       faligndata      %f10, %f12, %f42
+       faligndata      %f12, %f14, %f44
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f48
+       membar  #Sync
+2:
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f14, %f16, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+       
+       faligndata      %f16, %f18, %f32
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f18, %f20, %f34
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f20, %f22, %f36
+       cmp     %o0, %o5
+       faligndata      %f22, %f24, %f38
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f24, %f26, %f40
+       faligndata      %f26, %f28, %f42
+       faligndata      %f28, %f30, %f44
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f0
+       membar  #Sync
+2:     
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f30, %f48, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f48, %f50, %f32
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f50, %f52, %f34
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f52, %f54, %f36
+       cmp     %o0, %o5
+       faligndata      %f54, %f56, %f38
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f56, %f58, %f40
+       faligndata      %f58, %f60, %f42
+       faligndata      %f60, %f62, %f44
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar  #Sync
+2:     
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f62, %f0, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+       ba      3b
+        inc    BLOCK_SIZE, %o1
+
+       !!
+       !! Source at BLOCK_ALIGN+16
+       !!
+       !! We need to load 6 doubles by hand.
+       !! 
+L102:
+#ifdef RETURN_NAME
+       sethi   %hi(1f), %g1
+       ba,pt   %icc, 2f
+        or     %g1, %lo(1f), %g1
+1:     
+       .asciz  "L102"
+       .align  8
+2:     
+#endif
+       ldd     [%o0], %f4
+       inc     8, %o0
+       fmovd   %f0, %f2                                ! Hoist fmovd
+       ldd     [%o0], %f6
+       inc     8, %o0
+       
+       ldd     [%o0], %f8
+       inc     8, %o0
+       ldd     [%o0], %f10
+       inc     8, %o0
+       ldd     [%o0], %f12
+       inc     8, %o0
+       ldd     [%o0], %f14
+       inc     8, %o0
+       
+       cmp     %o0, %o5
+       bleu,a,pn       %icc, 3f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar #Sync
+3:     
+       faligndata      %f2, %f4, %f32
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f4, %f6, %f34
+       cmp     %o0, %o5
+       faligndata      %f6, %f8, %f36
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f8, %f10, %f38
+       faligndata      %f10, %f12, %f40
+       faligndata      %f12, %f14, %f42
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f48
+       membar  #Sync
+2:
+       faligndata      %f14, %f16, %f44
+
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f16, %f18, %f46
+       
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f18, %f20, %f32
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f20, %f22, %f34
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f22, %f24, %f36
+       cmp     %o0, %o5
+       faligndata      %f24, %f26, %f38
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f26, %f28, %f40
+       faligndata      %f28, %f30, %f42
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f0
+       membar  #Sync
+2:     
+       faligndata      %f30, %f48, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f48, %f50, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f50, %f52, %f32
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f52, %f54, %f34
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f54, %f56, %f36
+       cmp     %o0, %o5
+       faligndata      %f56, %f58, %f38
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f58, %f60, %f40
+       faligndata      %f60, %f62, %f42
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar  #Sync
+2:     
+       faligndata      %f62, %f0, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f0, %f2, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+       ba      3b
+        inc    BLOCK_SIZE, %o1
+       
+       !!
+       !! Source at BLOCK_ALIGN+24
+       !!
+       !! We need to load 5 doubles by hand.
+       !! 
+L103:
+#ifdef RETURN_NAME
+       sethi   %hi(1f), %g1
+       ba,pt   %icc, 2f
+        or     %g1, %lo(1f), %g1
+1:     
+       .asciz  "L103"
+       .align  8
+2:     
+#endif
+       fmovd   %f0, %f4
+       ldd     [%o0], %f6
+       inc     8, %o0
+       ldd     [%o0], %f8
+       inc     8, %o0
+       ldd     [%o0], %f10
+       inc     8, %o0
+       ldd     [%o0], %f12
+       inc     8, %o0
+       ldd     [%o0], %f14
+       inc     8, %o0
+
+       cmp     %o0, %o5
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar #Sync
+2:     
+       inc     BLOCK_SIZE, %o0
+3:     
+       faligndata      %f4, %f6, %f32
+       cmp     %o0, %o5
+       faligndata      %f6, %f8, %f34
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f8, %f10, %f36
+       faligndata      %f10, %f12, %f38
+       faligndata      %f12, %f14, %f40
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f48
+       membar  #Sync
+2:
+       faligndata      %f14, %f16, %f42
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f16, %f18, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f18, %f20, %f46
+       
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f20, %f22, %f32
+       cmp     %o0, %o5
+       faligndata      %f22, %f24, %f34
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f24, %f26, %f36
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f26, %f28, %f38
+       faligndata      %f28, %f30, %f40
+       ble,a,pn        %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f0
+       membar  #Sync
+2:     
+       faligndata      %f30, %f48, %f42
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f48, %f50, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f50, %f52, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f52, %f54, %f32
+       cmp     %o0, %o5
+       faligndata      %f54, %f56, %f34
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f56, %f58, %f36
+       faligndata      %f58, %f60, %f38
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f60, %f62, %f40
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar  #Sync
+2:     
+       faligndata      %f62, %f0, %f42
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f0, %f2, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f2, %f4, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+       ba      3b
+        inc    BLOCK_SIZE, %o1
+
+       !!
+       !! Source at BLOCK_ALIGN+32
+       !!
+       !! We need to load 4 doubles by hand.
+       !! 
+L104:
+#ifdef RETURN_NAME
+       sethi   %hi(1f), %g1
+       ba,pt   %icc, 2f
+        or     %g1, %lo(1f), %g1
+1:     
+       .asciz  "L104"
+       .align  8
+2:     
+#endif
+       fmovd   %f0, %f6
+       ldd     [%o0], %f8
+       inc     8, %o0
+       ldd     [%o0], %f10
+       inc     8, %o0
+       ldd     [%o0], %f12
+       inc     8, %o0
+       ldd     [%o0], %f14
+       inc     8, %o0
+       
+       cmp     %o0, %o5
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar #Sync
+2:     
+       inc     BLOCK_SIZE, %o0
+3:     
+       faligndata      %f6, %f8, %f32
+       cmp     %o0, %o5
+       faligndata      %f8, %f10, %f34
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f10, %f12, %f36
+       faligndata      %f12, %f14, %f38
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f48
+       membar  #Sync
+2:
+       faligndata      %f14, %f16, %f40
+       faligndata      %f16, %f18, %f42
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f18, %f20, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f20, %f22, %f46
+       
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f22, %f24, %f32
+       cmp     %o0, %o5
+       faligndata      %f24, %f26, %f34
+       faligndata      %f26, %f28, %f36
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f28, %f30, %f38
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f0
+       membar  #Sync
+2:     
+       faligndata      %f30, %f48, %f40
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f48, %f50, %f42
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f50, %f52, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f52, %f54, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f54, %f56, %f32
+       cmp     %o0, %o5
+       faligndata      %f56, %f58, %f34
+       faligndata      %f58, %f60, %f36
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f60, %f62, %f38
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar  #Sync
+2:     
+       faligndata      %f62, %f0, %f40
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f0, %f2, %f42
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f2, %f4, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f4, %f6, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+       ba      3b
+        inc    BLOCK_SIZE, %o1
+
+       !!
+       !! Source at BLOCK_ALIGN+40
+       !!
+       !! We need to load 3 doubles by hand.
+       !! 
+L105:
+#ifdef RETURN_NAME
+       sethi   %hi(1f), %g1
+       ba,pt   %icc, 2f
+        or     %g1, %lo(1f), %g1
+1:     
+       .asciz  "L105"
+       .align  8
+2:     
+#endif
+       fmovd   %f0, %f8
+       ldd     [%o0], %f10
+       inc     8, %o0
+       ldd     [%o0], %f12
+       inc     8, %o0
+       ldd     [%o0], %f14
+       inc     8, %o0
+       
+       cmp     %o0, %o5
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar #Sync
+2:     
+       inc     BLOCK_SIZE, %o0
+3:     
+       faligndata      %f8, %f10, %f32
+       cmp     %o0, %o5
+       faligndata      %f10, %f12, %f34
+       faligndata      %f12, %f14, %f36
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f48
+       membar  #Sync
+2:
+       faligndata      %f14, %f16, %f38
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f16, %f18, %f40
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f18, %f20, %f42
+       faligndata      %f20, %f22, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f22, %f24, %f46
+       
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f24, %f26, %f32
+       cmp     %o0, %o5
+       faligndata      %f26, %f28, %f34
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f28, %f30, %f36
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f0
+       membar  #Sync
+2:
+       faligndata      %f30, %f48, %f38
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f48, %f50, %f40
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f50, %f52, %f42
+       faligndata      %f52, %f54, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f54, %f56, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f56, %f58, %f32
+       cmp     %o0, %o5
+       faligndata      %f58, %f60, %f34
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f60, %f62, %f36
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar  #Sync
+2:
+       faligndata      %f62, %f0, %f38
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f0, %f2, %f40
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f2, %f4, %f42
+       faligndata      %f4, %f6, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f6, %f8, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+       ba      3b
+        inc    BLOCK_SIZE, %o1
+
+
+       !!
+       !! Source at BLOCK_ALIGN+48
+       !!
+       !! We need to load 2 doubles by hand.
+       !! 
+L106:
+#ifdef RETURN_NAME
+       sethi   %hi(1f), %g1
+       ba,pt   %icc, 2f
+        or     %g1, %lo(1f), %g1
+1:     
+       .asciz  "L106"
+       .align  8
+2:     
+#endif
+       fmovd   %f0, %f10
+       ldd     [%o0], %f12
+       inc     8, %o0
+       ldd     [%o0], %f14
+       inc     8, %o0
+       
+       cmp     %o0, %o5
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar #Sync
+2:     
+       inc     BLOCK_SIZE, %o0
+3:     
+       faligndata      %f10, %f12, %f32
+       cmp     %o0, %o5
+       faligndata      %f12, %f14, %f34
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f48
+       membar  #Sync
+2:
+       faligndata      %f14, %f16, %f36
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f16, %f18, %f38
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f18, %f20, %f40
+       faligndata      %f20, %f22, %f42
+       faligndata      %f22, %f24, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f24, %f26, %f46
+       
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f26, %f28, %f32
+       cmp     %o0, %o5
+       faligndata      %f28, %f30, %f34
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f0
+       membar  #Sync
+2:
+       faligndata      %f30, %f48, %f36
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f48, %f50, %f38
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f50, %f52, %f40
+       faligndata      %f52, %f54, %f42
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f54, %f56, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f56, %f58, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f58, %f60, %f32
+       cmp     %o0, %o5
+       faligndata      %f60, %f62, %f34
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar  #Sync
+2:
+       faligndata      %f62, %f0, %f36
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f0, %f2, %f38
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f2, %f4, %f40
+       faligndata      %f4, %f6, %f42
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f6, %f8, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f8, %f10, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+       ba      3b
+        inc    BLOCK_SIZE, %o1
+
+
+       !!
+       !! Source at BLOCK_ALIGN+56
+       !!
+       !! We need to load 1 double by hand.
+       !! 
+L107:
+#ifdef RETURN_NAME
+       sethi   %hi(1f), %g1
+       ba,pt   %icc, 2f
+        or     %g1, %lo(1f), %g1
+1:     
+       .asciz  "L107"
+       .align  8
+2:     
+#endif
+       fmovd   %f0, %f12
+       ldd     [%o0], %f14
+       inc     8, %o0
+
+       cmp     %o0, %o5
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar #Sync
+2:     
+       inc     BLOCK_SIZE, %o0
+3:     
+       faligndata      %f12, %f14, %f32
+       cmp     %o0, %o5
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f48
+       membar  #Sync
+2:
+       faligndata      %f14, %f16, %f34
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f16, %f18, %f36
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f18, %f20, %f38
+       faligndata      %f20, %f22, %f40
+       faligndata      %f22, %f24, %f42
+       faligndata      %f24, %f26, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f26, %f28, %f46
+       
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f28, %f30, %f32
+       cmp     %o0, %o5
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f0
+       membar  #Sync
+2:
+       faligndata      %f30, %f48, %f34
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f48, %f50, %f36
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f50, %f52, %f38
+       faligndata      %f52, %f54, %f40
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f54, %f56, %f42
+       faligndata      %f56, %f58, %f44
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f58, %f60, %f46
+       
+       stda    %f32, [%o1] ASI_STORE
+
+       faligndata      %f60, %f62, %f32
+       cmp     %o0, %o5
+       bleu,a,pn       %icc, 2f
+        ldda   [%o0] ASI_BLK_P, %f16
+       membar  #Sync
+2:
+       faligndata      %f62, %f0, %f34
+       dec     BLOCK_SIZE, %o2
+       faligndata      %f0, %f2, %f36
+       inc     BLOCK_SIZE, %o1
+       faligndata      %f2, %f4, %f38
+       faligndata      %f4, %f6, %f40
+       inc     BLOCK_SIZE, %o0
+       faligndata      %f6, %f8, %f42
+       faligndata      %f8, %f10, %f44
+
+       brlez,pn        %o2, Lbcopy_blockdone
+        faligndata     %f10, %f12, %f46
+
+       stda    %f32, [%o1] ASI_STORE
+       ba      3b
+        inc    BLOCK_SIZE, %o1
+       
+Lbcopy_blockdone:
+       inc     BLOCK_SIZE, %o2                         ! Fixup our overcommit
+       membar  #Sync                                   ! Finish any pending loads
+#define        FINISH_REG(f)                           \
+       deccc   8, %o2;                         \
+       bl,a    Lbcopy_blockfinish;             \
+        fmovd  f, %f48;                        \
+       std     f, [%o1];                       \
+       inc     8, %o1
+
+       FINISH_REG(%f32)
+       FINISH_REG(%f34)
+       FINISH_REG(%f36)
+       FINISH_REG(%f38)
+       FINISH_REG(%f40)
+       FINISH_REG(%f42)
+       FINISH_REG(%f44)
+       FINISH_REG(%f46)
+       FINISH_REG(%f48)
+#undef FINISH_REG
+       !! 
+       !! The low 3 bits have the sub-word bits needed to be
+       !! stored [because (x-8)&0x7 == x].
+       !!
+Lbcopy_blockfinish:
+       brz,pn  %o2, 2f                                 ! 100% complete?
+        fmovd  %f48, %f4
+       cmp     %o2, 8                                  ! Exactly 8 bytes?
+       bz,a,pn %xcc, 2f
+        std    %f4, [%o1]
+
+       btst    4, %o2                                  ! Word store?
+       bz      %xcc, 1f
+        nop
+       st      %f4, [%o1]
+       inc     4, %o1
+1:
+       btst    2, %o2
+       fzero   %f0
+       bz      1f
+
+        mov    -6, %o4
+       alignaddr %o1, %o4, %g0
+
+       faligndata %f0, %f4, %f8
+       
+       stda    %f8, [%o1] ASI_FL16_P                   ! Store short
+       inc     2, %o1
+1:
+       btst    1, %o2                                  ! Byte aligned?
+       bz      2f
+
+        mov    -7, %o0                                 ! Calculate dest - 7
+       alignaddr %o1, %o0, %g0                         ! Calculate shift mask and dest.
+
+       faligndata %f0, %f4, %f8                        ! Move 1st byte to low part of f8
+
+       stda    %f8, [%o1] ASI_FL8_P                    ! Store 1st byte
+       inc     1, %o1                                  ! Update address
+2:
+       membar  #Sync
+#if 0
+       !!
+       !! verify copy success.
+       !! 
+
+       mov     %i0, %o2
+       mov     %i1, %o4
+       mov     %i2, %l4
+0:     
+       ldub    [%o2], %o1
+       inc     %o2
+       ldub    [%o4], %o3
+       inc     %o4
+       cmp     %o3, %o1
+       bnz     1f
+        dec    %l4
+       brnz    %l4, 0b
+        nop
+       ba      2f
+        nop
+
+1:
+       set     block_disable, %o0
+       stx     %o0, [%o0]
+       
+       set     0f, %o0
+       call    prom_printf
+        sub    %i2, %l4, %o5
+       set     1f, %o0
+       mov     %i0, %o1
+       mov     %i1, %o2
+       call    prom_printf
+        mov    %i2, %o3
+       ta      1
+       .data
+       _ALIGN
+block_disable: .xword  0
+0:     .asciz  "bcopy failed: %x@%p != %x@%p byte %d\r\n"
+1:     .asciz  "bcopy(%p, %p, %lx)\r\n"
+       _ALIGN
+       .text
+2:     
+#endif
+#ifdef _KERNEL         
+
+       set 1f, %o0
+       mov     %i0, %o1
+       mov     %i1, %o2
+       call    printf
+       mov     %i2, %o3
+       
+       .data
+       _ALIGN
+1:     .asciz "block exit (%p, %p, %d)\n"
+       _ALIGN
+       .text
+/*
+ * Weve saved our possible fpstate, now disable the fpu
+ * and continue with life.
+ */
+#if 1
+       RESTORE_FPU
+#else
+#ifdef DEBUG
+       LDPTR   [%l1 + %lo(FPPROC)], %l7
+       cmp     %l7, %l5
+!      tnz     1               ! fpproc has changed!
+       LDPTR   [%l5 + P_FPSTATE], %l7
+       cmp     %l7, %l0
+       tnz     1               ! fpstate has changed!
+#endif
+       andcc   %l2, %l3, %g0                           ! If (fpproc && fpstate)
+       STPTR   %l2, [%l1 + %lo(FPPROC)]                ! Restore old fproc
+       bz,pt   %xcc, 1f                                ! Skip if no fpstate
+        STPTR  %l6, [%l5 + P_FPSTATE]                  ! Restore old fpstate
+       
+       call    _C_LABEL(loadfpstate)                   ! Re-load orig fpstate
+        mov    %l3, %o0
+1:
+#endif
+       set 1f, %o0
+       mov     %i0, %o1
+       mov     %i1, %o2
+       call    printf
+       mov     %i2, %o3
+       
+       .data
+       _ALIGN
+1:     .asciz "block done (%p, %p, %d)\n"
+       _ALIGN
+       .text
+
+       
+       ret
+        restore        %g1, 0, %o0                     ! Return DEST for memcpy
+#endif
+       retl
+        mov    %g1, %o0
+#endif
+
+
diff --git a/lib/nbsd_libc/arch/sparc64/string/memset.S b/lib/nbsd_libc/arch/sparc64/string/memset.S
new file mode 100644 (file)
index 0000000..ca10dc7
--- /dev/null
@@ -0,0 +1,196 @@
+/*     $NetBSD: memset.S,v 1.4 2001/08/02 01:17:28 eeh Exp $   */
+
+/*
+ * Copyright (c) 2001, Eduardo E. Horvath
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ * from: Header: bzero.s,v 1.1 92/06/25 12:52:46 torek Exp
+ */
+
+#include <machine/asm.h>
+#ifndef _LOCORE
+#define _LOCORE
+#endif
+#include <machine/ctlreg.h>
+#include <machine/frame.h>
+#include <machine/psl.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: memset.S,v 1.4 2001/08/02 01:17:28 eeh Exp $")
+#endif  /* LIBC_SCCS and not lint */
+
+/*
+ * bzero(addr, len)
+ *
+ * We want to use VIS instructions if we're clearing out more than
+ * 256 bytes, but to do that we need to properly save and restore the
+ * FP registers.  Unfortunately the code to do that in the kernel needs
+ * to keep track of the current owner of the FPU, hence the different
+ * code.
+ *
+ * XXXXX To produce more efficient code, we do not allow lengths
+ * greater than 0x80000000000000000, which are negative numbers.
+ * This should not really be an issue since the VA hole should
+ * cause any such ranges to fail anyway.
+ */
+ENTRY(bzero)
+       ! %o0 = addr, %o1 = len
+       mov     %o1, %o2
+       clr     %o1                     ! Initialize our pattern
+/*
+ * memset(addr, c, len)
+ *
+ */
+ENTRY(memset)
+       ! %o0 = addr, %o1 = pattern, %o2 = len
+       mov     %o0, %o4                ! Save original pointer
+
+Lbzero_internal:
+       btst    7, %o0                  ! Word aligned?
+       bz,pn   %xcc, 0f
+        nop
+       inc     %o0
+       deccc   %o2                     ! Store up to 7 bytes
+       bge,a,pt        %xcc, Lbzero_internal
+        stb    %o1, [%o0 - 1]
+
+       retl                            ! Duplicate Lbzero_done
+        mov    %o4, %o0
+0:
+       /*
+        * Duplicate the pattern so it fills 64-bits.
+        */
+       andcc   %o1, 0x0ff, %o1         ! No need to extend zero
+       bz,pt   %icc, 1f
+        sllx   %o1, 8, %o3             ! sigh.  all dependent insns.
+       or      %o1, %o3, %o1
+       sllx    %o1, 16, %o3
+       or      %o1, %o3, %o1
+       sllx    %o1, 32, %o3
+        or     %o1, %o3, %o1
+1:     
+#if 1
+       !! Now we are 64-bit aligned
+       cmp     %o2, 256                ! Use block clear if len > 256
+       bge,pt  %xcc, Lbzero_block      ! use block store insns
+#endif 
+        deccc  8, %o2
+Lbzero_longs:
+       bl,pn   %xcc, Lbzero_cleanup    ! Less than 8 bytes left
+        nop
+3:     
+       inc     8, %o0
+       deccc   8, %o2
+       bge,pt  %xcc, 3b
+        stx    %o1, [%o0 - 8]          ! Do 1 longword at a time
+
+       /*
+        * Len is in [-8..-1] where -8 => done, -7 => 1 byte to zero,
+        * -6 => two bytes, etc.  Mop up this remainder, if any.
+        */
+Lbzero_cleanup:        
+       btst    4, %o2
+       bz,pt   %xcc, 5f                ! if (len & 4) {
+        nop
+       stw     %o1, [%o0]              !       *(int *)addr = 0;
+       inc     4, %o0                  !       addr += 4;
+5:     
+       btst    2, %o2
+       bz,pt   %xcc, 7f                ! if (len & 2) {
+        nop
+       sth     %o1, [%o0]              !       *(short *)addr = 0;
+       inc     2, %o0                  !       addr += 2;
+7:     
+       btst    1, %o2
+       bnz,a   %icc, Lbzero_done       ! if (len & 1)
+        stb    %o1, [%o0]              !       *addr = 0;
+Lbzero_done:
+       retl
+        mov    %o4, %o0                ! Restore ponter for memset (ugh)
+
+#if 1  
+Lbzero_block:
+/*
+ * Userland:
+ *
+ * Floating point registers are volatile.  What luck.
+ *
+ * See locore.s for the kernel version.
+ *
+ */    
+!      wr      %g0, FPRS_FEF, %fprs                    ! Enable FPU
+
+       !! We are now 8-byte aligned.  We need to become 64-byte aligned.
+       btst    63, %o0
+       bz,pt   %xcc, 2f
+        nop
+1:     
+       stx     %o1, [%o0]
+       inc     8, %o0
+       btst    63, %o0
+       bnz,pt  %xcc, 1b
+        dec    8, %o2
+
+2:
+       brz     %o1, 3f                                 ! Skip the memory op
+        fzero  %f0                                     ! for bzero
+       
+       stx     %o1, [%o0]                              ! Flush this puppy to RAM
+       membar  #StoreLoad
+       ldd     [%o0], %f0
+3:     
+       fmovd   %f0, %f2                                ! Duplicate the pattern
+       fmovd   %f0, %f4
+       fmovd   %f0, %f6
+       fmovd   %f0, %f8
+       fmovd   %f0, %f10
+       fmovd   %f0, %f12
+       fmovd   %f0, %f14
+       
+       !! Remember: we were 8 bytes too far
+       dec     56, %o2                                 ! Go one iteration too far
+5:
+       stda    %f0, [%o0] ASI_BLK_P                    ! Store 64 bytes
+       deccc   64, %o2
+       bg,pn   %xcc, 5b
+        inc    64, %o0
+       
+       membar  #Sync
+/*
+ * Now we're done we need to load the FPU state from where
+ * we put it.
+ */
+       ba,pt   %xcc, Lbzero_longs      ! Finish up the remainder
+        inccc  56, %o2         ! Restore the count
+#endif
diff --git a/lib/nbsd_libc/arch/sparc64/sys/__clone.S b/lib/nbsd_libc/arch/sparc64/sys/__clone.S
new file mode 100644 (file)
index 0000000..3d36d7d
--- /dev/null
@@ -0,0 +1,91 @@
+/*     $NetBSD: __clone.S,v 1.7 2008/04/28 20:22:57 martin Exp $       */
+
+/*-     
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *      
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(clone, __clone)
+#endif
+
+/*
+ * int __clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+ENTRY(__clone)
+       save    %sp, -CC64FSZ, %sp
+
+       /*
+        * Sanity checks: func and stack may not be NULL.
+        */
+       brz,pn  %i0,8f          ! func == NULL, bail
+        orcc   %i1, %g0, %o1   ! setup stack arg for syscall, test
+       bz,pn   %xcc, 8f        ! stack == NULL, bail
+        mov    %i2, %o0        ! setup flags arg for syscall
+
+       /*
+        * Allocate "caller's" frame in the child stack as ABI
+        * requires.  Subtract BIAS - it will be 64-bit code.
+        *
+        * We pass the function and the argument to the child by
+        * stashing them at the bottom of the frame.  There they are
+        * safe from window spill would we need to take one as it's
+        * below the window save area.
+        */
+       sub     %o1, CC64FSZ+BIAS, %o1          ! make space
+       stx     %i0, [%o1+CC64FSZ-16+BIAS]      ! save func
+       stx     %i3, [%o1+CC64FSZ-8+BIAS]       ! save arg
+
+       /*
+        * Args are now set up for system call as (flags, stack).
+        */
+       mov     SYS___clone, %g1
+       t       ST_SYSCALL
+       bcs,pn  %xcc, 9f
+        tst    %o1             ! %o1 (rv[1]) == 0 in parent
+       bz      %xcc, 2f        ! yes, parent
+        ldx    [%sp+CC64FSZ-16+BIAS], %l0      ! grab the function...
+       call    %l0             ! Call the clone's entry point.
+        ldx    [%sp+CC64FSZ-8+BIAS], %o0       ! ...and the argument
+
+       JUMP(_exit)
+       /* NOTREACHED */
+
+2:     ret
+        restore %g0, %o0, %o0
+
+8:     restore %g0, EINVAL, %o0
+       ERROR()
+       /* NOTREACHED */
+
+9:     restore %o0, %g0, %o0
+       ERROR()
+       /* NOTREACHED */
diff --git a/lib/nbsd_libc/arch/sparc64/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/sparc64/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..62833a6
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.9 2009/01/11 02:46:24 christos Exp $      */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigaction14_sigtramp.c,v 1.9 2009/01/11 02:46:24 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern void __sigtramp_siginfo_2(void);
+
+#ifdef __LIBC12_SOURCE__
+       /*
+        * We select the compatibility SIGCONTEXT trampoline if SA_SIGINFO
+        * is not set in the sigaction.
+        */
+       if (act && (act->sa_flags & SA_SIGINFO) == 0) {
+               extern void __sigtramp_sigcontext_1(void);
+               int sav = errno;
+               int rv =  __sigaction_sigtramp(sig, act, oact,
+                                          __sigtramp_sigcontext_1, 1);
+               /*
+                * EINVAL might indicate that trampoline version 1 is
+                * not supported by the kernel; fall back on native
+                * SIGINFO trampoline.
+                */
+               if (rv >= 0 || errno != EINVAL)
+                       return rv;
+               errno = sav;
+       }
+#endif
+
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_2, 2);
+}
diff --git a/lib/nbsd_libc/arch/sparc64/sys/__sigtramp2.S b/lib/nbsd_libc/arch/sparc64/sys/__sigtramp2.S
new file mode 100644 (file)
index 0000000..9f93571
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: __sigtramp2.S,v 1.3 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Paul Kranenburg.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __sigtramp2.S,v 1.3 2008/04/28 20:22:57 martin Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+#define _LOCORE
+#include <sparc/frame.h>       /* BIAS, CC64FSZ */
+
+/*
+ * When this code is run, the stack looks like:
+ *     [%sp + BIAS]                    struct frame
+ *     [%sp + BIAS + CC64FSZ]          siginfo_t
+ *     [%sp + BIAS + CC64FSZ + 128]    ucontext_t
+ *         .
+ *         .
+ */
+ENTRY_NOPROFILE(__sigtramp_siginfo_2)
+       add     %sp, BIAS + CC64FSZ + 128, %o0  /* get pointer to ucontext */
+       mov     SYS_setcontext, %g1
+       t       ST_SYSCALL              /* call setcontext */
+       mov     SYS_exit, %g1           /* exit with errno */
+       t       ST_SYSCALL              /* if sigreturn fails */
diff --git a/lib/nbsd_libc/arch/sparc64/sys/__syscall.S b/lib/nbsd_libc/arch/sparc64/sys/__syscall.S
new file mode 100644 (file)
index 0000000..5d55ec7
--- /dev/null
@@ -0,0 +1,6 @@
+/*     $NetBSD: __syscall.S,v 1.1 2000/12/13 20:25:04 martin Exp $     */
+
+#include <machine/asm.h>
+#include "SYS.h"
+
+RSYSCALL(__syscall)
diff --git a/lib/nbsd_libc/arch/sparc64/sys/__vfork14.S b/lib/nbsd_libc/arch/sparc64/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..1ffd4d6
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: __vfork14.S,v 1.3 2003/08/07 16:42:29 agc Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: Ovfork.s,v 1.1 91/07/06 13:05:56 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)Ovfork.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: __vfork14.S,v 1.3 2003/08/07 16:42:29 agc Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+/*
+ * pid = vfork();
+ *
+ * %o1 == 0 in parent process, 1 in child process.
+ * %o0 == pid of child in parent, pid of parent in child.
+ */
+
+#include "SYS.h"
+
+SYSCALL(__vfork14)
+       dec     %o1             /* from 1 to 0 in child, 0 to -1 in parent */
+       retl
+        and    %o0, %o1, %o0   /* return 0 in child, pid in parent */
diff --git a/lib/nbsd_libc/arch/sparc64/sys/brk.S b/lib/nbsd_libc/arch/sparc64/sys/brk.S
new file mode 100644 (file)
index 0000000..7813b5b
--- /dev/null
@@ -0,0 +1,112 @@
+/*     $NetBSD: brk.S,v 1.12 2003/12/26 11:21:48 martin Exp $  */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: brk.s,v 1.3 92/06/25 12:56:05 mccanne Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)brk.s       8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: brk.S,v 1.12 2003/12/26 11:21:48 martin Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _C_LABEL(__curbrk)
+       .globl  _C_LABEL(__minbrk)
+       .globl  _C_LABEL(_end)
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(brk, _brk)
+#endif
+
+       .data
+       .align  8
+_C_LABEL(__minbrk):
+       .xword  _C_LABEL(_end)          /* lower brk limit; also for gmon code */
+       .text
+
+ENTRY(_brk)
+#ifdef PIC
+#ifdef BIGPIC
+       PIC_PROLOGUE(%o5,%o4)
+       set     _C_LABEL(__minbrk), %o4
+       ldx     [%o5 + %o4], %o4
+       ldx     [%o4], %o1              /* %o1 = minbrk */
+       cmp     %o1, %o0                /* if (minbrk > %o0) */
+       movgu   %xcc, %o1, %o0          /*      %o0 = minbrk */
+       mov     %o0, %o2                /* save argument to syscall */
+       mov     SYS_break, %g1
+       t       ST_SYSCALL
+       set     _C_LABEL(__curbrk), %o3
+       bcc,a,pt        %icc, 1f
+        ldx    [%o5 + %o3], %o4
+       ERROR()
+1:
+       retl                            /* success, return 0 & record new break */
+        stx    %o2, [%o4]
+#else
+       PIC_PROLOGUE(%o5,%o4)
+       ldx     [%o5 + _C_LABEL(__minbrk)], %o4
+       ldx     [%o4], %o1              /* %o1 = minbrk */
+       cmp     %o1, %o0                /* if (minbrk > %o0) */
+       movgu   %xcc, %o1, %o0          /*      %o0 = minbrk */
+       mov     %o0, %o2                /* save argument to syscall */
+       mov     SYS_break, %g1
+       t       ST_SYSCALL
+       bcc,a,pt        %icc, 1f
+        ldx    [%o5 + _C_LABEL(__curbrk)], %o4
+       ERROR()
+1:
+       retl                            /* success, return 0 & record new break */
+        stx    %o2, [%o4]
+#endif
+#else
+       sethi   %hi(_C_LABEL(__minbrk)), %o1    /* %o1 = minbrk */
+       ldx     [%o1 + %lo(_C_LABEL(__minbrk))], %o1
+       cmp     %o1, %o0                /* if (minbrk > %o0) */
+       movgu   %xcc, %o1, %o0          /*      %o0 = minbrk */
+       mov     %o0, %o2                /* save argument to syscall */
+       mov     SYS_break, %g1
+       t       ST_SYSCALL
+       bcc,a,pt        %icc,1f
+        sethi  %hi(_C_LABEL(__curbrk)), %g1
+       ERROR()
+1:
+       retl                            /* success, return 0 & record new break */
+        stx    %o2, [%g1 + %lo(_C_LABEL(__curbrk))]
+#endif
diff --git a/lib/nbsd_libc/arch/sparc64/sys/cerror.S b/lib/nbsd_libc/arch/sparc64/sys/cerror.S
new file mode 100644 (file)
index 0000000..3cd2acf
--- /dev/null
@@ -0,0 +1,87 @@
+/*     $NetBSD: cerror.S,v 1.6 2003/08/07 16:42:29 agc Exp $   */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: cerror.s,v 1.3 92/07/02 04:17:59 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)cerror.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: cerror.S,v 1.6 2003/08/07 16:42:29 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+#ifdef _REENTRANT
+FUNC(__cerror)
+       save    %sp, -CC64FSZ, %sp
+       call    _C_LABEL(__errno)
+        nop
+       st      %i0, [%o0]
+       mov     -1, %i0
+       ret
+        restore %g0, -1, %o1
+#else
+       .globl  _C_LABEL(errno)
+#ifdef PIC
+#ifdef BIGPIC
+FUNC(__cerror)
+       PIC_PROLOGUE(%g1, %o3)
+       set     _C_LABEL(errno),%o1
+       ldx     [%g1 + %o1], %g1
+       st      %o0, [%g1]
+       mov     -1, %o0
+       retl
+        mov    -1, %o1
+#else
+FUNC(__cerror)
+       PIC_PROLOGUE(%g1, %o3)
+       ldx     [%g1 + _C_LABEL(errno)], %g1
+       st      %o0, [%g1]
+       mov     -1, %o0
+       retl
+        mov    -1, %o1
+#endif
+#else
+FUNC(__cerror)
+       sethi   %hi(_C_LABEL(errno)), %g1
+       st      %o0, [%g1 + %lo(_C_LABEL(errno))]
+       mov     -1, %o0
+       retl
+        mov    -1, %o1
+#endif
+#endif /* _REENTRANT */
diff --git a/lib/nbsd_libc/arch/sparc64/sys/exect.S b/lib/nbsd_libc/arch/sparc64/sys/exect.S
new file mode 100644 (file)
index 0000000..5c88698
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: exect.S,v 1.2 2003/08/07 16:42:29 agc Exp $    */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: exect.s,v 1.1 91/07/06 13:05:57 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)exect.s     8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: exect.S,v 1.2 2003/08/07 16:42:29 agc Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+ENTRY(exect)
+       mov     SYS_execve, %g1 /* execve(file, argv, env) */
+       t       ST_SYSCALL
+       ERROR()
diff --git a/lib/nbsd_libc/arch/sparc64/sys/fork.S b/lib/nbsd_libc/arch/sparc64/sys/fork.S
new file mode 100644 (file)
index 0000000..e83affa
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: fork.S,v 1.5 2003/08/07 16:42:30 agc Exp $     */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: fork.s,v 1.1 91/07/06 13:05:58 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)fork.s      8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: fork.S,v 1.5 2003/08/07 16:42:30 agc Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+_SYSCALL(__fork,fork)
+       dec     %o1             /* from 1 to 0 in child, 0 to -1 in parent */
+       retl
+        and    %o0, %o1, %o0   /* return 0 in child, pid in parent */
diff --git a/lib/nbsd_libc/arch/sparc64/sys/getcontext.S b/lib/nbsd_libc/arch/sparc64/sys/getcontext.S
new file mode 100644 (file)
index 0000000..29f0c84
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: getcontext.S,v 1.3 2008/04/28 20:22:57 martin Exp $    */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: getcontext.S,v 1.3 2008/04/28 20:22:57 martin Exp $")
+#endif /* SYSLIBC_SCCS && !lint */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext, _getcontext)
+#endif
+
+ENTRY(_getcontext)
+       mov     %o0, %o2                        /* must save pointer */
+       mov     SYS_getcontext, %g1
+       t       ST_SYSCALL
+       bcc,a   1f
+        stx    %g0, [%o2 + 64 + 11 * 8]        /* gr[_REG_O0] = 0 */
+       ERROR()
+1:
+       add     %o7, 8, %o1
+       stx     %o1, [%o2 + 64 + 1 * 8]         /* gr[_REG_PC] = retaddr */
+       add     %o7, 12, %o1
+       retl
+        stx    %o1, [%o2 + 64 + 2 * 8]         /* gr[_REG_nPC] = retaddr + 4 */
diff --git a/lib/nbsd_libc/arch/sparc64/sys/pipe.S b/lib/nbsd_libc/arch/sparc64/sys/pipe.S
new file mode 100644 (file)
index 0000000..c0c6ecf
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: pipe.S,v 1.4 2003/08/07 16:42:30 agc Exp $     */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: pipe.s,v 1.1 91/07/06 13:05:58 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)pipe.s      8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: pipe.S,v 1.4 2003/08/07 16:42:30 agc Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe, _pipe)
+#endif
+
+ENTRY(_pipe)
+       mov     %o0, %o2        /* save pointer */
+       mov     SYS_pipe, %g1
+       t       ST_SYSCALL      /* pipe() */
+       bcc,a   1f
+        st     %o0, [%o2]      /* success, store fds */
+       ERROR()
+1:
+       st      %o1, [%o2 + 4]
+       retl                    /* and return 0 */
+        clr    %o0
diff --git a/lib/nbsd_libc/arch/sparc64/sys/ptrace.S b/lib/nbsd_libc/arch/sparc64/sys/ptrace.S
new file mode 100644 (file)
index 0000000..ecf2c9c
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: ptrace.S,v 1.5 2003/08/07 16:42:30 agc Exp $   */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: ptrace.s,v 1.2 91/12/20 01:59:00 leres Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)ptrace.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: ptrace.S,v 1.5 2003/08/07 16:42:30 agc Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+ENTRY(ptrace)
+       save    %sp, -CC64FSZ, %sp
+       call    _C_LABEL(__errno)
+        nop
+       st      %g0, [%o0]
+       restore
+       mov     SYS_ptrace, %g1
+       t       ST_SYSCALL
+       bcc     1f
+       nop
+       ERROR()
+1:
+       retl
+       nop
diff --git a/lib/nbsd_libc/arch/sparc64/sys/sbrk.S b/lib/nbsd_libc/arch/sparc64/sys/sbrk.S
new file mode 100644 (file)
index 0000000..e420e5e
--- /dev/null
@@ -0,0 +1,107 @@
+/*     $NetBSD: sbrk.S,v 1.9 2003/08/07 16:42:30 agc Exp $     */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: sbrk.s,v 1.3 92/07/02 00:56:49 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)sbrk.s      8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: sbrk.S,v 1.9 2003/08/07 16:42:30 agc Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _C_LABEL(__curbrk)
+       .globl  _C_LABEL(_end)
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(sbrk, _sbrk)
+#endif
+
+       .data
+       .align  8
+_C_LABEL(__curbrk):
+       .xword  _C_LABEL(_end)
+       .text
+
+ENTRY(_sbrk)
+#ifdef PIC
+#ifdef BIGPIC
+       PIC_PROLOGUE(%o5,%o4)
+       set     _C_LABEL(__curbrk), %o3
+       ldx     [%o5 + %o3], %o2
+       ldx     [%o2], %o3                      /* %o3 = old break */
+       add     %o3, %o0, %o4                   /* %o4 = new break */
+       mov     %o4, %o0                        /* copy for syscall */
+       mov     SYS_break, %g1
+       t       ST_SYSCALL                      /* break(new_break) */
+       bcc,a   1f                              /* if success, */
+        mov    %o3, %o0                        /*    set return value */
+       ERROR()
+1:
+       retl                                    /* and update curbrk */
+        stx    %o4, [%o2]
+#else
+       PIC_PROLOGUE(%o5,%o4)
+       ldx     [%o5 + _C_LABEL(__curbrk)], %o2
+       ldx     [%o2], %o3                      /* %o3 = old break */
+       add     %o3, %o0, %o4                   /* %o4 = new break */
+       mov     %o4, %o0                        /* copy for syscall */
+       mov     SYS_break, %g1
+       t       ST_SYSCALL                      /* break(new_break) */
+       bcc,a   1f                              /* if success, */
+        mov    %o3, %o0                        /*    set return value */
+       ERROR()
+1:
+       retl                                    /* and update curbrk */
+        stx    %o4, [%o2]
+#endif
+#else
+       sethi   %hi(_C_LABEL(__curbrk)), %o2
+       ldx     [%o2 + %lo(_C_LABEL(__curbrk))], %o3    /* %o3 = old break */
+       add     %o3, %o0, %o4                   /* %o4 = new break */
+       mov     %o4, %o0                        /* copy for syscall */
+       mov     SYS_break, %g1
+       t       ST_SYSCALL                      /* break(new_break) */
+       bcc,a   1f                              /* if success, */
+        mov    %o3, %o0                        /*    set return value */
+       ERROR()
+1:
+       retl                                    /* and update curbrk */
+        stx    %o4, [%o2 + %lo(_C_LABEL(__curbrk))]
+#endif
diff --git a/lib/nbsd_libc/arch/sparc64/sys/shmat.S b/lib/nbsd_libc/arch/sparc64/sys/shmat.S
new file mode 100644 (file)
index 0000000..216dbd8
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: shmat.S,v 1.1 2000/07/07 08:20:55 itohy Exp $  */
+
+#include "SYS.h"
+
+RSYSCALL(shmat)
diff --git a/lib/nbsd_libc/arch/sparc64/sys/syscall.S b/lib/nbsd_libc/arch/sparc64/sys/syscall.S
new file mode 100644 (file)
index 0000000..f49bf2d
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: syscall.S,v 1.2 2003/08/07 16:42:30 agc Exp $  */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: syscall.s,v 1.1 91/07/06 13:06:02 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)syscall.s   8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: syscall.S,v 1.2 2003/08/07 16:42:30 agc Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+RSYSCALL(syscall)
diff --git a/lib/nbsd_libc/arch/vax/DEFS.h b/lib/nbsd_libc/arch/vax/DEFS.h
new file mode 100644 (file)
index 0000000..9e26197
--- /dev/null
@@ -0,0 +1,4 @@
+/*     $NetBSD: DEFS.h,v 1.3 1996/01/06 18:34:59 ragge Exp $ */
+
+#include <machine/asm.h>
+
diff --git a/lib/nbsd_libc/arch/vax/Makefile.inc b/lib/nbsd_libc/arch/vax/Makefile.inc
new file mode 100644 (file)
index 0000000..592be93
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.9 2010/07/06 05:59:52 mrg Exp $
+
+SRCS+= __longjmp14.c
+SRCS+= __sigaction14_sigtramp.c __sigtramp3.S
+
+CPPFLAGS+= -I.
+CPPFLAGS.assym.h+=-D__LIBC12_SOURCE__
diff --git a/lib/nbsd_libc/arch/vax/SYS.h b/lib/nbsd_libc/arch/vax/SYS.h
new file mode 100644 (file)
index 0000000..7bc4513
--- /dev/null
@@ -0,0 +1,90 @@
+/*     $NetBSD: SYS.h,v 1.10 2003/08/07 16:42:30 agc Exp $ */
+/*
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)SYS.h       8.1 (Berkeley) 6/4/93
+ */
+
+#include <machine/asm.h>
+#include <sys/syscall.h>
+
+#ifdef __STDC__
+#define SYSTRAP(x)     chmk $ SYS_ ## x
+#else
+#define SYSTRAP(x)     chmk $ SYS_/**/x
+#endif
+
+#define _SYSCALL_NOERROR(x,y)                                          \
+       ENTRY(x,0);                                                     \
+       SYSTRAP(y)
+
+#define _SYSCALL(x,y)                                                  \
+       err: nop; nop; jmp CERROR+2;                                    \
+       _SYSCALL_NOERROR(x,y);                                          \
+       jcs err+2
+
+#define SYSCALL_NOERROR(x)                                             \
+       _SYSCALL_NOERROR(x,x)
+
+#define SYSCALL(x)                                                     \
+       _SYSCALL(x,x)
+
+#define PSEUDO_NOERROR(x,y)                                            \
+       _SYSCALL_NOERROR(x,y);                                          \
+       ret
+
+#define PSEUDO(x,y)                                                    \
+       _SYSCALL(x,y);                                                  \
+       ret
+
+#define RSYSCALL_NOERROR(x)                                            \
+       PSEUDO_NOERROR(x,x)
+
+#define RSYSCALL(x)                                                    \
+       PSEUDO(x,x)
+
+#ifdef WEAK_ALIAS
+#define        WSYSCALL(weak,strong)                                           \
+       WEAK_ALIAS(weak,strong);                                        \
+       PSEUDO(strong,weak)
+#else
+#define        WSYSCALL(weak,strong)                                           \
+       PSEUDO(weak,weak)
+#endif
+
+#define        ASMSTR          .asciz
+
+#ifdef __ELF__
+#define        CERROR  _C_LABEL(__cerror)
+#define        CURBRK  _C_LABEL(__curbrk)
+#else
+#define        CERROR  _ASM_LABEL(cerror)
+#define        CURBRK  _ASM_LABEL(curbrk)
+#endif
+
+       .globl  CERROR
diff --git a/lib/nbsd_libc/arch/vax/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/vax/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..bae804d
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/15 17:35:18 kleink Exp $
+
+SRCS+= strtof_vaxf.c
diff --git a/lib/nbsd_libc/arch/vax/gdtoa/arith.h b/lib/nbsd_libc/arch/vax/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..66e57a0
--- /dev/null
@@ -0,0 +1,4 @@
+/* $NetBSD: arith.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define VAX
+#define NO_HEX_FP      /* XXX */
diff --git a/lib/nbsd_libc/arch/vax/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/vax/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..86a5f8d
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+/* No NaN in VAX FP. */
diff --git a/lib/nbsd_libc/arch/vax/gen/Makefile.inc b/lib/nbsd_libc/arch/vax/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..224cb0f
--- /dev/null
@@ -0,0 +1,22 @@
+#      $NetBSD: Makefile.inc,v 1.17 2010/07/06 05:59:52 mrg Exp $
+
+SRCS+= byte_swap_2.S byte_swap_4.S bswap64.S \
+       fabs.S frexp.c \
+       fpclassifyf.c fpclassifyd.c \
+       infinityf.c infinity.c infinityl.c \
+       isfinitef.c isfinited.c \
+       ldexp.S \
+       makecontext.c modf.S \
+       resumecontext.c \
+       signbitf.c signbitd.c \
+       swapcontext.S \
+       udiv.S urem.S \
+       __setjmp14.S __sigsetjmp14.S _lwp.c _setjmp.S 
+
+# ABI compatibility for libc.so.12
+SRCS+= isinf.c isnan.c
+
+LSRCS.vax.gen= Lint_bswap16.c Lint_bswap32.c Lint_bswap64.c
+LSRCS+=                ${LSRCS.vax.gen}
+DPSRCS+=       ${LSRCS.vax.gen}
+CLEANFILES+=   ${LSRCS.vax.gen}
diff --git a/lib/nbsd_libc/arch/vax/gen/__longjmp14.c b/lib/nbsd_libc/arch/vax/gen/__longjmp14.c
new file mode 100644 (file)
index 0000000..c5d1aaf
--- /dev/null
@@ -0,0 +1,94 @@
+/*     $NetBSD: __longjmp14.c,v 1.4 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christian Limpach and Matt Thomas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "namespace.h"
+#include <sys/types.h>
+#include <ucontext.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+#include <machine/reg.h>
+
+#define __LIBC12_SOURCE__
+#include <setjmp.h>
+#include <compat/include/setjmp.h>
+
+struct _jmp_buf {
+       struct sigcontext jb_sc;
+       register_t jb_regs[6];
+};
+
+void
+__longjmp14(jmp_buf env, int val)
+{
+       struct _jmp_buf *jb = (void *)env;
+       ucontext_t uc;
+
+       /* Ensure non-zero SP */
+       if (jb->jb_sc.sc_sp == 0)
+               goto err;
+
+       /* Ensure non-zero return value */
+       if (val == 0)
+               val = -1;
+
+       /* Set _UC_SIGMASK and _UC_CPU */
+       uc.uc_flags = _UC_SIGMASK | _UC_CPU;
+
+       /* Clear uc_link */
+       uc.uc_link = 0;
+
+       /* Save return value in context */
+       uc.uc_mcontext.__gregs[_REG_R0] = val;
+
+       /* Copy saved registers */
+       uc.uc_mcontext.__gregs[_REG_AP] = jb->jb_sc.sc_ap;
+       uc.uc_mcontext.__gregs[_REG_SP] = jb->jb_sc.sc_sp;
+       uc.uc_mcontext.__gregs[_REG_FP] = jb->jb_sc.sc_fp;
+       uc.uc_mcontext.__gregs[_REG_PC] = jb->jb_sc.sc_pc;
+       uc.uc_mcontext.__gregs[_REG_PSL] = jb->jb_sc.sc_ps;
+
+       uc.uc_mcontext.__gregs[_REG_R6] = jb->jb_regs[0];
+       uc.uc_mcontext.__gregs[_REG_R7] = jb->jb_regs[1];
+       uc.uc_mcontext.__gregs[_REG_R8] = jb->jb_regs[2];
+       uc.uc_mcontext.__gregs[_REG_R9] = jb->jb_regs[3];
+       uc.uc_mcontext.__gregs[_REG_R10] = jb->jb_regs[4];
+       uc.uc_mcontext.__gregs[_REG_R11] = jb->jb_regs[5];
+
+       /* Copy signal mask */
+       uc.uc_sigmask = jb->jb_sc.sc_mask;
+
+       setcontext(&uc);
+ err:
+       longjmperror();
+       abort();
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/__setjmp14.S b/lib/nbsd_libc/arch/vax/gen/__setjmp14.S
new file mode 100644 (file)
index 0000000..69726b1
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * 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.
+ * 3. 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)
+       /* .asciz "@(#)setjmp.s 8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: __setjmp14.S,v 1.10 2005/05/03 04:37:33 matt Exp $"
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and a struct sigcontext, see <signal.h>
+ */
+
+#include "DEFS.h"
+#include "assym.h"
+
+ENTRY(__setjmp14, R6)
+       movl    4(%ap),%r2              # construct sigcontext
+       subl2   $12,%sp                 # space for current struct sigstack
+       pushl   %sp                     # get current values
+       pushl   $0                      # no new values
+       calls   $4,_C_LABEL(__sigaltstack14) # pop args plus signal stack value
+       movl    4(%ap),%r2              # construct sigcontext
+       movl    (%sp)+,(%r2)            # save onsigstack status of caller
+       pushal  28(%r2)
+       pushl   $0
+       pushl   $0
+       calls   $3,_C_LABEL(__sigprocmask14) # get signal mask
+       addl3   $8,4(%ap),%r2           # point to sp in signal context
+       clrl    %r0                     # assume no stack arguments
+       bbc     $13,6(%fp),1f           # handle callg
+       addl3   $1,(%ap),%r0            # get argument count +1 if calls
+1:     moval   24(%fp)[%r0],(%r2)+     # save sp of caller
+       movl    12(%fp),(%r2)+          # save frame pointer of caller
+       movl    8(%fp),(%r2)+           # save argument pointer of caller
+       movl    16(%fp),(%r2)+          # save pc of caller
+       movpsl  (%r2)                   # save current psl
+       movw    4(%fp),(%r2)            # save psw of caller
+#ifdef __ELF__
+       addl3   $SC_LEN,4(%ap),%r2      # point to past signal context
+       movq    %r6,(%r2)+              # save r6/r7
+       movq    %r8,(%r2)+              # save r8/r9
+       movq    %r10,(%r2)+             # save r10/r11
+#endif
+       clrl    %r0
+       ret
+
+#ifndef __ELF__
+ENTRY(__longjmp14, 0)
+       movl    8(%ap),%r0              # return(v)
+       movl    4(%ap),%r1              # fetch buffer
+       tstl    12(%r1)                 # is fp non-null?
+       beql    botch
+
+#ifdef __ELF__
+       moval   $SC_LEN(%r1),%r2        # get ptr to saved registers
+       movq    (%r2)+,%r6              # restore r6/r7
+       movq    (%r2)+,%r8              # restore r8/r9
+       movq    (%r2)+,%r10             # restore r10/r11
+#else
+loop:
+       cmpl    12(%r1),%fp             # are we there yet?
+       beql    done
+       blssu   botch
+       moval   20(%fp),%r2
+       blbc    6(%fp),1f               # was %r0 saved?
+       movl    %r0,(%r2)+
+1:
+       bbc     $1,6(%fp),2f            # was %r1 saved?
+       movl    %r1,(%r2)
+2:
+       movab   loop,16(%fp)
+       ret                             # pop another frame
+
+done:
+#endif /* !__ELF__ */
+       pushl   %r1                     # pointer to sigcontext
+       calls   $1,_C_LABEL(__sigreturn14) # restore previous context
+                                       # we should never return
+botch:
+       calls   $0,_C_LABEL(longjmperror)
+       halt
+#endif
diff --git a/lib/nbsd_libc/arch/vax/gen/__sigsetjmp14.S b/lib/nbsd_libc/arch/vax/gen/__sigsetjmp14.S
new file mode 100644 (file)
index 0000000..b5ada46
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 1983, 1993, 1995
+ *     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.
+ * 3. 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)
+       .asciz "$NetBSD: __sigsetjmp14.S,v 1.4 2003/08/07 16:42:31 agc Exp $"
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- sigsetjmp, siglongjmp
+ *
+ *      siglongjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *      sigsetjmp(a, savemask)
+ * by restoring registers from the stack,
+ * and dependent on savemask restores the
+ * signal mask.
+ */
+
+#include "DEFS.h"
+#include <machine/setjmp.h>
+
+ENTRY(__sigsetjmp14, R6)
+       movl    4(%ap),%r0              # get env pointer
+       movl    8(%ap),(_JBLEN*4)(%r0)  # save "savemask"
+       tstl    8(%ap)                  # do saving of signal mask?
+       beql    L1
+       jmp     _C_LABEL(__setjmp14)+2  # yep, do full setjmp
+L1:    jmp     _C_LABEL(_setjmp)+2     # nope, skip to _setjmp
+
+ENTRY(__siglongjmp14, 0)
+       movl    4(%ap),%r0              # get env pointer
+       tstl    (_JBLEN*4)(%r0)         # test if "savemask" was set
+       beql    L2
+       jmp     _C_LABEL(__longjmp14)+2 # yep, do full longjmp
+L2:    jmp     _C_LABEL(_longjmp)+2    # nope, skip to _longjmp
+
+
diff --git a/lib/nbsd_libc/arch/vax/gen/_lwp.c b/lib/nbsd_libc/arch/vax/gen/_lwp.c
new file mode 100644 (file)
index 0000000..d48b6cd
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: _lwp.c,v 1.1 2009/06/03 01:02:28 christos Exp $        */
+
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.1 2009/06/03 01:02:28 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <inttypes.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+
+void
+_lwp_makecontext(ucontext_t *u, void (*start)(void *),
+    void *arg, void *private, caddr_t stack_base, size_t stack_size)
+{
+       __greg_t *gr = u->uc_mcontext.__gregs;
+       int *sp;
+
+       getcontext(u);
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+
+       /* Align to a word */
+       /* LINTED uintptr_t is safe */
+       sp = (int *)((uintptr_t)(stack_base + stack_size) & ~0x3);
+       
+       /*
+        * Allocate necessary stack space for arguments including arg count
+        * and call frame
+        */
+       sp -= 1 + 1 + 5;
+
+       sp[0] = 0;                      /* condition handler is null */
+       sp[1] = 0x20000000;             /* make this a CALLS frame */
+       sp[2] = 0;                      /* saved argument pointer */
+       sp[3] = 0;                      /* saved frame pointer */
+       sp[4] = (intptr_t)_lwp_exit + 2;/* return via _lwp_exit */
+       sp[5] = 1;                      /* argc */
+       sp[6] = (intptr_t)arg;          /* argv */
+       
+       gr[_REG_AP] = (__greg_t)(sp + 5);
+       gr[_REG_SP] = (__greg_t)sp;
+       gr[_REG_FP] = (__greg_t)sp;
+       gr[_REG_PC] = (__greg_t)start + 2;
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/_setjmp.S b/lib/nbsd_libc/arch/vax/gen/_setjmp.S
new file mode 100644 (file)
index 0000000..4cd0fca
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 1980, 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.
+ * 3. 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)
+       /* .asciz "@(#)_setjmp.s        8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: _setjmp.S,v 1.9 2003/08/07 16:42:31 agc Exp $"
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     _longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     _setjmp(a)
+ * by restoring registers from the stack,
+ * The previous signal state is NOT restored.
+ *
+ * Even though we don't use sigreturn14, we still store things in a sigcontext
+ * in order to be consistent.
+ */
+
+#include "DEFS.h"
+
+ENTRY(_setjmp, R6)
+       movl    4(%ap),%r0
+       movl    12(%fp),12(%r0)         # save frame pointer of caller
+       movl    16(%fp),20(%r0)         # save pc of caller
+#ifdef __ELF__
+       movl    8(%fp),16(%r0)          # save ap of caller
+       clrl    %r1                     # clear arg count
+       bbc     $13,6(%fp),1f           # was this a callg?
+       addl3   $1,(%ap),%r1            # get real arg count+1 for calls
+1:     moval   24(%fp)[%r1],8(%r0)     # save sp of caller
+       movpsl  24(%r0)                 # save current psl
+       movw    4(%fp),24(%r0)          # save psw of caller
+       movq    %r6,44(%r0)             # save r6/r7
+       movq    %r8,52(%r0)             # save r8/r9
+       movq    %r10,60(%r0)            # save r10/r11
+#endif
+       clrl    %r0
+       ret
+
+ENTRY(_longjmp, 0)
+       movl    8(%ap),%r0              # return(v)
+       movl    4(%ap),%r1              # fetch buffer
+       tstl    12(%r1)                 # is fp null
+       beql    botch
+#ifdef __ELF__
+       movq    44(%r1),%r6             # restore r6/r7
+       movq    52(%r1),%r8             # restore r8/r9
+       movq    60(%r1),%r10            # restore r10/r11
+       movl    16(%r1),%ap             # restore ap
+       movl    8(%r1),%sp              # restore sp
+       movl    12(%r1),%fp             # restore fp
+       movq    20(%r1),-(%sp)          # save pc/psl to new stack
+       rei                             # and go back to saved pc/psl
+#else
+loop:
+       bitw    $1,6(%fp)               # %r0 saved?
+       beql    1f
+       movl    %r0,20(%fp)
+       bitw    $2,6(%fp)               # was %r1 saved?
+       beql    2f
+       movl    %r1,24(%fp)
+       brb     2f
+1:
+       bitw    $2,6(%fp)               # was %r1 saved?
+       beql    2f
+       movl    %r1,20(%fp)
+2:
+       cmpl    12(%r1),12(%fp)
+       beql    done
+       blssu   botch
+       movab   loop,16(%fp)
+       ret                             # pop another frame
+
+done:
+       cmpb    *16(%fp),$2             # returning to an "rei"?
+       bneq    1f
+       movab   3f,16(%fp)              # do return w/ psl-pc pop
+       brw     2f
+1:
+       movab   4f,16(%fp)              # do standard return
+2:
+       ret                             # unwind stack before signals enabled
+3:
+       addl2   $8,%sp                  # compensate for PSL-PC push
+4:
+       jmp     *20(%r1)                # done, return....
+#endif /* !__ELF__ */
+
+botch:
+       calls   $0,_C_LABEL(longjmperror)
+       halt
diff --git a/lib/nbsd_libc/arch/vax/gen/alloca.S b/lib/nbsd_libc/arch/vax/gen/alloca.S
new file mode 100644 (file)
index 0000000..d70bf24
--- /dev/null
@@ -0,0 +1,46 @@
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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)
+       /* .asciz "@(#)alloca.s 8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: alloca.S,v 1.3 2003/08/07 16:42:31 agc Exp $"
+#endif /* LIBC_SCCS and not lint */
+
+#include "DEFS.h"
+
+ENTRY(alloca, 0)
+       movl    4(%ap),%r0      # get allocation size
+       movl    16(%fp),%r2     # save return address before we smash it
+       movab   here,16(%fp)
+       ret
+here:
+       subl2   %r0,%sp         # create stack space
+       bicl2   $3,%sp          # align to longword boundary
+       movl    %sp,%r0
+       jmp     (%r2)
diff --git a/lib/nbsd_libc/arch/vax/gen/byte_swap_2.S b/lib/nbsd_libc/arch/vax/gen/byte_swap_2.S
new file mode 100644 (file)
index 0000000..6a94404
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ * 3. 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)
+       /* .asciz "@(#)htons.s  8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: byte_swap_2.S,v 1.3 2003/08/07 16:42:31 agc Exp $"
+#endif /* LIBC_SCCS and not lint */
+
+#include "DEFS.h"
+
+ALTENTRY(ntohs)
+ALTENTRY(htons)
+ENTRY(__bswap16, 0)
+       rotl    $8,4(%ap),%r0
+       movb    5(%ap),%r0
+       movzwl  %r0,%r0
+       ret
diff --git a/lib/nbsd_libc/arch/vax/gen/byte_swap_4.S b/lib/nbsd_libc/arch/vax/gen/byte_swap_4.S
new file mode 100644 (file)
index 0000000..13cb051
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ * 3. 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)
+       /* .asciz "@(#)htonl.s  8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: byte_swap_4.S,v 1.4 2003/08/07 16:42:31 agc Exp $"
+#endif /* LIBC_SCCS and not lint */
+
+#include "DEFS.h"
+
+ALTENTRY(ntohl)
+ALTENTRY(htonl)
+ENTRY(__bswap32, 0)
+       rotl    $-8,4(%ap),%r0
+       insv    %r0,$16,$8,%r0
+       movb    7(%ap),%r0
+       ret
diff --git a/lib/nbsd_libc/arch/vax/gen/fabs.S b/lib/nbsd_libc/arch/vax/gen/fabs.S
new file mode 100644 (file)
index 0000000..a31bb9b
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ * 3. 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)
+       /* .asciz "@(#)fabs.s   8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: fabs.S,v 1.3 2003/08/07 16:42:31 agc Exp $"
+#endif /* LIBC_SCCS and not lint */
+
+/* fabs - floating absolute value */
+
+#include "DEFS.h"
+
+ENTRY(fabs, 0)
+       movd    4(%ap),%r0
+       bgeq    1f
+       mnegd   %r0,%r0
+1:
+       ret
diff --git a/lib/nbsd_libc/arch/vax/gen/fpclassifyd.c b/lib/nbsd_libc/arch/vax/gen/fpclassifyd.c
new file mode 100644 (file)
index 0000000..d7814de
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: fpclassifyd.c,v 1.3 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpclassifyd.c,v 1.3 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include <machine/vaxfp.h>
+#include <math.h>
+
+/*
+ * 7.12.3.1 fpclassify - classify real floating type
+ *          VAX D_floating version
+ *
+ *          Implementation notes:
+ *          Reserved operand -> FP_ROP
+ *          True zero        -> FP_ZERO
+ *          Dirty zero       -> FP_DIRTY_ZERO
+ *          Finite           -> FP_NORMAL
+ */
+int
+__fpclassifyd(double x)
+{
+       union vax_dfloating_u u;
+
+       u.dfltu_d = x;
+
+       if (u.dfltu_dflt.dflt_exp == 0) {
+               if (u.dfltu_dflt.dflt_sign != 0)
+                       return FP_ROP;
+               else if (u.dfltu_dflt.dflt_frach != 0 ||
+                        u.dfltu_dflt.dflt_fracm != 0 ||
+                        u.dfltu_dflt.dflt_fracl != 0) 
+                       return FP_DIRTYZERO;
+               else
+                       return FP_ZERO;
+       } else {
+               return FP_NORMAL;
+       }
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/fpclassifyf.c b/lib/nbsd_libc/arch/vax/gen/fpclassifyf.c
new file mode 100644 (file)
index 0000000..20145ad
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: fpclassifyf.c,v 1.3 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpclassifyf.c,v 1.3 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include <machine/vaxfp.h>
+#include <math.h>
+
+/*
+ * 7.12.3.1 fpclassify - classify real floating type
+ *          VAX F_floating version
+ *
+ *          Implementation notes:
+ *          Reserved operand -> FP_ROP
+ *          True zero        -> FP_ZERO
+ *          Dirty zero       -> FP_DIRTY_ZERO
+ *          Finite           -> FP_NORMAL
+ */
+int
+__fpclassifyf(float x)
+{
+       union vax_ffloating_u u;
+
+       u.ffltu_f = x;
+
+       if (u.ffltu_fflt.fflt_exp == 0) {
+               if (u.ffltu_fflt.fflt_sign != 0)
+                       return FP_ROP;
+               else if (u.ffltu_fflt.fflt_frach != 0 ||
+                        u.ffltu_fflt.fflt_fracl != 0) 
+                       return FP_DIRTYZERO;
+               else
+                       return FP_ZERO;
+       } else {
+               return FP_NORMAL;
+       }
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/frexp.c b/lib/nbsd_libc/arch/vax/gen/frexp.c
new file mode 100644 (file)
index 0000000..66db249
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: frexp.c,v 1.4 2003/08/07 16:42:31 agc Exp $    */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)frexp.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: frexp.c,v 1.4 2003/08/07 16:42:31 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <math.h>
+
+double
+frexp(value, eptr)
+       double value;
+       int *eptr;
+{
+       union {
+                double v;
+                struct {
+                       u_int u_mant1 :  7;
+                       u_int   u_exp :  8;
+                       u_int  u_sign :  1;
+                       u_int u_mant2 : 16;
+                       u_int u_mant3 : 32;
+                } s;
+        } u;
+
+       if (value) {
+               u.v = value;
+               *eptr = u.s.u_exp - 128;
+               u.s.u_exp = 128;
+               return (u.v);
+       } else {
+               *eptr = 0;
+               return (0.0);
+       }
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/infinity.c b/lib/nbsd_libc/arch/vax/gen/infinity.c
new file mode 100644 (file)
index 0000000..fb0d41f
--- /dev/null
@@ -0,0 +1,17 @@
+/*     $NetBSD: infinity.c,v 1.8 2002/02/19 21:50:01 thorpej Exp $     */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: infinity.c,v 1.8 2002/02/19 21:50:01 thorpej Exp $");
+#endif /* LIBC_SCCS and not lint */
+/*
+ * XXX - This is not correct, but what can we do about it???
+ */
+
+/* infinity.c */
+
+#include <math.h>
+
+/* The highest D float on a vax. */
+const union __double_u __infinity =
+       { { 0xff, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
diff --git a/lib/nbsd_libc/arch/vax/gen/infinityf.c b/lib/nbsd_libc/arch/vax/gen/infinityf.c
new file mode 100644 (file)
index 0000000..49a2704
--- /dev/null
@@ -0,0 +1,11 @@
+/*     $NetBSD: infinityf.c,v 1.1 2003/10/25 22:31:20 kleink Exp $     */
+
+/*
+ * infinityf.c - max. value representable in VAX F_floating  -- public domain.
+ * This is _not_ infinity.
+ */
+
+#include <math.h>
+
+const union __float_u __infinityf =
+       { { 0xff, 0x7f, 0xff, 0xff } };
diff --git a/lib/nbsd_libc/arch/vax/gen/infinityl.c b/lib/nbsd_libc/arch/vax/gen/infinityl.c
new file mode 100644 (file)
index 0000000..8c613b9
--- /dev/null
@@ -0,0 +1,16 @@
+/*     $NetBSD: infinityl.c,v 1.2 2005/06/12 05:21:27 lukem Exp $      */
+
+/*
+ * infinityl.c - max. value representable in VAX D_floating  -- public domain.
+ * This is _not_ infinity.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: infinityl.c,v 1.2 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+
+const union __long_double_u __infinityl =
+       { { 0xff, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
diff --git a/lib/nbsd_libc/arch/vax/gen/isfinited.c b/lib/nbsd_libc/arch/vax/gen/isfinited.c
new file mode 100644 (file)
index 0000000..778cf81
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: isfinited.c,v 1.5 2008/04/28 20:22:57 martin Exp $     */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: isfinited.c,v 1.5 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include <machine/vaxfp.h>
+#include <math.h>
+
+/*
+ * 7.12.3.2 isfinite - determine whether an argument has finite value
+ *          VAX D_floating version
+ */
+int
+__isfinited(double x)
+{
+       union vax_dfloating_u u;
+
+       u.dfltu_d = x;
+
+       if (u.dfltu_dflt.dflt_exp == 0 &&
+           ((u.dfltu_dflt.dflt_frach != 0 ||
+             u.dfltu_dflt.dflt_fracm != 0 ||
+             u.dfltu_dflt.dflt_fracl != 0) ||
+            (u.dfltu_dflt.dflt_sign != 0)))
+               return 0;
+
+       return 1;
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/isfinitef.c b/lib/nbsd_libc/arch/vax/gen/isfinitef.c
new file mode 100644 (file)
index 0000000..3bdfc22
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: isfinitef.c,v 1.4 2008/04/28 20:22:57 martin Exp $     */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: isfinitef.c,v 1.4 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include <machine/vaxfp.h>
+#include <math.h>
+
+/*
+ * 7.12.3.2 isfinite - determine whether an argument has finite value
+ *          VAX F_floating version
+ */
+int
+__isfinitef(float x)
+{
+       union vax_ffloating_u u;
+
+       u.ffltu_f = x;
+
+       if (u.ffltu_fflt.fflt_exp == 0 &&
+           ((u.ffltu_fflt.fflt_frach != 0 ||
+             u.ffltu_fflt.fflt_fracl != 0) ||
+            (u.ffltu_fflt.fflt_sign != 0)))
+               return 0;
+
+       return 1;
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/isinf.c b/lib/nbsd_libc/arch/vax/gen/isinf.c
new file mode 100644 (file)
index 0000000..8478a4c
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: isinf.c,v 1.8 2004/03/04 23:42:39 kleink Exp $ */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isinf.c,v 1.8 2004/03/04 23:42:39 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+
+#undef isinf
+int isinf __P((double));
+
+/* ARGSUSED */
+int
+isinf(double d)
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/isnan.c b/lib/nbsd_libc/arch/vax/gen/isnan.c
new file mode 100644 (file)
index 0000000..d46615e
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: isnan.c,v 1.3 2004/03/04 23:42:39 kleink Exp $ */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isnan.c,v 1.3 2004/03/04 23:42:39 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <math.h>
+
+#undef isnan
+int isnan __P((double));
+
+/* ARGSUSED */
+int
+isnan(double d)
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/ldexp.S b/lib/nbsd_libc/arch/vax/gen/ldexp.S
new file mode 100644 (file)
index 0000000..ef36ccf
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ * 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.
+ * 3. 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)
+       /*.asciz "@(#)ldexp.s   8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: ldexp.S,v 1.6 2003/08/07 16:42:31 agc Exp $"
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * double ldexp (value, exp)
+ * double value;
+ * int exp;
+ *
+ * Ldexp returns value*2**exp, if that result is in range.
+ * If underflow occurs, it returns zero.  If overflow occurs,
+ * it returns a value of appropriate sign and largest
+ * possible magnitude.  In case of either overflow or underflow,
+ * errno is set to ERANGE.  Note that errno is not modified if
+ * no error occurs.
+ */
+
+#include "DEFS.h"
+
+/*
+ * don't include errno.h, ANSI C says it defines errno.
+ *
+ * #include <errno.h>
+ */
+#define        ERANGE  34
+
+       .globl  _C_LABEL(errno)
+
+ENTRY(ldexp, 0)
+       movd    4(%ap),%r0      /* fetch "value" */
+       extzv   $7,$8,%r0,%r2   /* %r2 := biased exponent */
+       jeql    1f              /* if zero, done */
+
+       addl2   12(%ap),%r2     /* %r2 := new biased exponent */
+       jleq    2f              /* if <= 0, underflow */
+       cmpl    %r2,$256                /* otherwise check if too big */
+       jgeq    3f              /* jump if overflow */
+       insv    %r2,$7,$8,%r0   /* put exponent back in result */
+1:
+       ret
+2:
+       clrd    %r0
+       jbr     1f
+3:
+       movd    huge,%r0                /* largest possible floating magnitude */
+       jbc     $15,4(%ap),1f   /* jump if argument was positive */
+       mnegd   %r0,%r0         /* if arg < 0, make result negative */
+1:
+#ifdef _REENTRANT
+       pushl   %r0
+       calls   $0,_C_LABEL(__errno)
+       movl    $ ERANGE,(%r0)
+       movl    (%sp)+,%r0
+#else
+       movl    $ ERANGE,_C_LABEL(errno)
+#endif
+       ret
+
+       .data
+huge:  .word   0x7fff          /* the largest number that can */
+       .word   0xffff          /*   be represented in a long floating */
+       .word   0xffff          /*   number.  This is given in hex in order */
+       .word   0xffff          /*   to avoid floating conversions */
diff --git a/lib/nbsd_libc/arch/vax/gen/makecontext.c b/lib/nbsd_libc/arch/vax/gen/makecontext.c
new file mode 100644 (file)
index 0000000..87ee3bf
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: makecontext.c,v 1.3 2008/04/28 20:22:57 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.3 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include <stddef.h>
+#include <inttypes.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#include <stdarg.h>
+
+void
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+{
+       __greg_t *gr = ucp->uc_mcontext.__gregs;
+       va_list ap;
+       int *sp;
+       int i;
+
+       /* Compute and align stack pointer. */
+       sp = (int *)
+           (((uintptr_t)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size) & ~0x3);
+
+       /*
+        * Allocate necessary stack space for arguments including arg count
+        * and call frame
+        */
+       sp -= argc + 1 + 5;
+
+       va_start(ap, argc);
+       sp[5] = argc;
+       for (i = 1; argc > 0; argc--, i++)
+               sp[5 + i] = va_arg(ap, int);
+       va_end(ap);
+
+       sp[0] = 0;                      /* condition handler is null */
+       sp[1] = 0x20000000;             /* make this a CALLS frame */
+       sp[2] = 0;                      /* saved argument pointer */
+       sp[3] = 0;                      /* saved frame pointer */
+       sp[4] = (int)_resumecontext+2;  /* return via trampoline code */
+
+       gr[_REG_AP] = (__greg_t)(sp + 5);
+       gr[_REG_SP] = (__greg_t)sp;
+       gr[_REG_FP] = (__greg_t)sp;
+       gr[_REG_PC] = (__greg_t)func+2;
+
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/modf.S b/lib/nbsd_libc/arch/vax/gen/modf.S
new file mode 100644 (file)
index 0000000..e175705
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ * 3. 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)
+       /* .asciz "@(#)modf.s   8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: modf.S,v 1.4 2003/08/07 16:42:31 agc Exp $"
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * double modf (value, iptr)
+ * double value, *iptr;
+ *
+ * Modf returns the fractional part of "value",
+ * and stores the integer part indirectly through "iptr".
+ */
+
+#include "DEFS.h"
+
+ENTRY(modf, 0)
+       emodd   4(%ap),$0,$0f1.0,%r2,%r0
+       jvs     1f                      # integer overflow
+       cvtld   %r2,*12(%ap)
+       ret
+1:
+       subd3   %r0,4(%ap),*12(%ap)
+       ret
+
+ENTRY(modff, 0)
+       emodf   4(%ap),$0,$0f1.0,%r2,%r0
+       jvs     1f                      # integer overflow
+       cvtlf   %r2,*8(%ap)
+       ret
+1:
+       subf3   %r0,4(%ap),*8(%ap)
+       ret
diff --git a/lib/nbsd_libc/arch/vax/gen/resumecontext.c b/lib/nbsd_libc/arch/vax/gen/resumecontext.c
new file mode 100644 (file)
index 0000000..7baafea
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: resumecontext.c,v 1.3 2008/04/28 20:22:57 martin Exp $ */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: resumecontext.c,v 1.3 2008/04/28 20:22:57 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "extern.h"
+
+void
+_resumecontext()
+{
+       ucontext_t uct;
+
+       (void)getcontext(&uct);
+       if (uct.uc_link == NULL) 
+               exit(0);
+       (void)setcontext(uct.uc_link);
+       _exit(-1);
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/signbitd.c b/lib/nbsd_libc/arch/vax/gen/signbitd.c
new file mode 100644 (file)
index 0000000..7f313e1
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: signbitd.c,v 1.2 2008/04/28 20:22:58 martin Exp $      */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: signbitd.c,v 1.2 2008/04/28 20:22:58 martin Exp $");
+#endif
+
+#include <machine/vaxfp.h>
+#include <math.h>
+
+/*
+ * 7.12.3.6 signbit - determine whether the sign of an argument is negative
+ *          VAX D_floating version
+ */
+int
+__signbitd(double x)
+{
+       union vax_dfloating_u u;
+
+       u.dfltu_d = x;
+
+       return (u.dfltu_dflt.dflt_sign == 1);
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/signbitf.c b/lib/nbsd_libc/arch/vax/gen/signbitf.c
new file mode 100644 (file)
index 0000000..02cedaa
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: signbitf.c,v 1.2 2008/04/28 20:22:58 martin Exp $      */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: signbitf.c,v 1.2 2008/04/28 20:22:58 martin Exp $");
+#endif
+
+#include <machine/vaxfp.h>
+#include <math.h>
+
+/*
+ * 7.12.3.6 signbit - determine whether the sign of an argument is negative
+ *          VAX F_floating version
+ */
+int
+__signbitf(float x)
+{
+       union vax_ffloating_u u;
+
+       u.ffltu_f = x;
+
+       return (u.ffltu_fflt.fflt_sign == 1);
+}
diff --git a/lib/nbsd_libc/arch/vax/gen/swapcontext.S b/lib/nbsd_libc/arch/vax/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..45f5afb
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: swapcontext.S,v 1.3 2008/04/28 20:22:58 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+ENTRY(swapcontext, 0)
+       clrl    %r0                     /* assume getcontext succeeds */
+       chmk    $SYS_getcontext         /* getcontext(oucp) */
+       jcc     1f
+       jmp     CERROR+2                /* something bad happened */
+
+1:     movl    4(%ap),%r0              /* get oucp */
+       addl3   (%ap),$(5+1),%r1        /* size of callframe + arglist (LW) */
+       bbs     $13,6(%fp),2f           /* was this a CALLG? */
+       movl    $5,%r1                  /* size of callframe (in LW) */
+2:     movl    8(%fp),(36+12*4)(%r0)           /* restore AP */
+       moval   (%sp)[%r1],(36+13*4)(%r0)       /* restore SP */
+       movq    12(%fp),(36+14*4)(%r0)          /* restore FP + PC */
+
+       pushl   8(%ap)
+       calls   $1,_C_LABEL(setcontext) /* setcontext(ucp) */
+       ret
diff --git a/lib/nbsd_libc/arch/vax/genassym.cf b/lib/nbsd_libc/arch/vax/genassym.cf
new file mode 100644 (file)
index 0000000..ddb2b08
--- /dev/null
@@ -0,0 +1,83 @@
+#      $NetBSD: genassym.cf,v 1.4 2008/04/28 20:22:57 martin Exp $
+
+#
+# Copyright (c) 2001 The NetBSD Foundation, Inc.
+# All rights reserved.
+#
+# This code is derived from software contributed to The NetBSD Foundation
+# by Matt Thomas <matt@3am-sfotware.com>.
+#
+# 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <ucontext.h>
+include <signal.h>
+
+define UC_LEN          sizeof(ucontext_t)
+define UC_FLAGS                offsetof(ucontext_t, uc_flags)
+define UC_LINK         offsetof(ucontext_t, uc_link)
+define UC_STACK                offsetof(ucontext_t, uc_stack)
+define UC_SIGMASK      offsetof(ucontext_t, uc_sigmask)
+define UC_GREGS                offsetof(ucontext_t, uc_mcontext.__gregs)
+define _UC_SIGMASK     _UC_SIGMASK
+define _UC_STACK       _UC_STACK
+define _UC_CPU         _UC_CPU
+
+define _REG_R0         4*_REG_R0
+define _REG_R1         4*_REG_R1
+define _REG_R2         4*_REG_R2
+define _REG_R4         4*_REG_R4
+define _REG_R6         4*_REG_R6
+define _REG_R8         4*_REG_R8
+define _REG_R10                4*_REG_R10
+define _REG_AP         4*_REG_AP
+define _REG_SP         4*_REG_SP
+define _REG_FP         4*_REG_FP
+define _REG_PC         4*_REG_PC
+define _REG_PSL                4*_REG_PSL
+
+define SS_SP           offsetof(stack_t, ss_sp)
+define SS_SIZE         offsetof(stack_t, ss_size)
+define SS_FLAGS        offsetof(stack_t, ss_flags)
+define SS_ONSTACK      SS_ONSTACK
+
+define SC13_LEN        sizeof(struct sigcontext13)
+define SC13_ONSTACK    offsetof(struct sigcontext13, sc_onstack)
+define SC13_MASK       offsetof(struct sigcontext13, sc_mask)
+define SC13_SP         offsetof(struct sigcontext13, sc_sp)
+define SC13_FP         offsetof(struct sigcontext13, sc_fp)
+define SC13_AP         offsetof(struct sigcontext13, sc_ap)
+define SC13_PC         offsetof(struct sigcontext13, sc_pc)
+define SC13_PS         offsetof(struct sigcontext13, sc_ps)
+
+define SC_LEN          sizeof(struct sigcontext)
+define SC_ONSTACK      offsetof(struct sigcontext, sc_onstack)
+define SC_MASK13       offsetof(struct sigcontext, __sc_mask13)
+define SC_SP           offsetof(struct sigcontext, sc_sp)
+define SC_FP           offsetof(struct sigcontext, sc_fp)
+define SC_AP           offsetof(struct sigcontext, sc_ap)
+define SC_PC           offsetof(struct sigcontext, sc_pc)
+define SC_PS           offsetof(struct sigcontext, sc_ps)
+define SC_MASK         offsetof(struct sigcontext, sc_mask)
+
+define SIG_BLOCK       SIG_BLOCK
+define SS_LEN          sizeof(sigset_t)
diff --git a/lib/nbsd_libc/arch/vax/net/Makefile.inc b/lib/nbsd_libc/arch/vax/net/Makefile.inc
new file mode 100644 (file)
index 0000000..db4492c
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.4 2004/06/06 17:09:48 he Exp $
+
+# ntoh* and htn* are in ../gen/byte_swap_*
+SRCS+= 
diff --git a/lib/nbsd_libc/arch/vax/stdlib/Makefile.inc b/lib/nbsd_libc/arch/vax/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..6057423
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.5 2009/07/31 20:40:00 dsl Exp $
+
+SRCS+= erand48.c
+NO_SRCS+= erand48_ieee754.c
diff --git a/lib/nbsd_libc/arch/vax/string/Makefile.inc b/lib/nbsd_libc/arch/vax/string/Makefile.inc
new file mode 100644 (file)
index 0000000..57d25c5
--- /dev/null
@@ -0,0 +1,4 @@
+#       $NetBSD: Makefile.inc,v 1.5 2010/03/12 09:12:35 uwe Exp $
+
+SRCS+=  bcmp.S bcopy.S bzero.S ffs.S memcmp.S
+SRCS+= memcpy.S memmove.S memset.S
diff --git a/lib/nbsd_libc/arch/vax/string/bcmp.S b/lib/nbsd_libc/arch/vax/string/bcmp.S
new file mode 100644 (file)
index 0000000..e032c29
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: bcmp.S,v 1.3 2003/08/07 16:42:32 agc Exp $     */
+/*
+ * 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.
+ * 3. 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.
+ */
+
+/* bcmp(s1, s2, n) */
+
+#include "DEFS.h"
+
+/* Since "cmpc3" is not portable across VAXen, do it the hard way */
+/*  still, this is four times faster than the generic C version on a uvax2 */
+
+ENTRY(bcmp, 0)
+       movl    12(%ap),%r0     # %r0 = n
+       jeql    9f
+       movq    4(%ap),%r1      # %r1 = s1, %r2 = s2
+       ashl    $-2,%r0,%r3     # convert len to # of long words
+       jeql    2f
+1:
+       cmpl    (%r1)+,(%r2)+   # no "cmpq" alas, so four bytes at a time
+       jneq    9f
+       sobgtr  %r3,1b
+2:
+       bicl3   $-4,%r0,%r3     # handle at most 3 extra bytes
+       jeql    8f
+3:
+       cmpb    (%r1)+,(%r2)+
+       jneq    9f
+       sobgtr  %r3,3b
+8:
+       clrl    %r0             # we have a match!
+9:
+       ret
diff --git a/lib/nbsd_libc/arch/vax/string/bcopy.S b/lib/nbsd_libc/arch/vax/string/bcopy.S
new file mode 100644 (file)
index 0000000..6a9c8fe
--- /dev/null
@@ -0,0 +1,75 @@
+/*     $NetBSD: bcopy.S,v 1.3 2003/08/07 16:42:32 agc Exp $    */
+/*
+ * 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.
+ * 3. 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)
+       .asciz "@(#)bcopy.s     8.1 (Berkeley) 6/4/93"
+#endif /* LIBC_SCCS and not lint */
+
+/* bcopy(from, to, size) */
+
+#include "DEFS.h"
+
+ENTRY(bcopy, R6)
+       movl    4(%ap),%r1
+       movl    8(%ap),%r3
+       movl    12(%ap),%r6
+       cmpl    %r1,%r3
+       bgtr    2f              # normal forward case
+       blss    3f              # overlapping, must do backwards
+       ret                     # equal, nothing to do
+1:
+       subl2   %r0,%r6
+       movc3   %r0,(%r1),(%r3)
+2:
+       movzwl  $65535,%r0
+       cmpl    %r6,%r0
+       jgtr    1b
+       movc3   %r6,(%r1),(%r3)
+       ret
+3:
+       addl2   %r6,%r1
+       addl2   %r6,%r3
+       movzwl  $65535,%r0
+       jbr     5f
+4:
+       subl2   %r0,%r6
+       subl2   %r0,%r1
+       subl2   %r0,%r3
+       movc3   %r0,(%r1),(%r3)
+       movzwl  $65535,%r0
+       subl2   %r0,%r1
+       subl2   %r0,%r3
+5:
+       cmpl    %r6,%r0
+       jgtr    4b
+       subl2   %r6,%r1
+       subl2   %r6,%r3
+       movc3   %r6,(%r1),(%r3)
+       ret
diff --git a/lib/nbsd_libc/arch/vax/string/bzero.S b/lib/nbsd_libc/arch/vax/string/bzero.S
new file mode 100644 (file)
index 0000000..291bdf8
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: bzero.S,v 1.3 2003/08/07 16:42:32 agc Exp $    */
+/*
+ * 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.
+ * 3. 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)
+       .asciz "@(#)bzero.s     8.1 (Berkeley) 6/4/93"
+#endif /* LIBC_SCCS and not lint */
+
+/* bzero(base, length) */
+
+#include "DEFS.h"
+
+ENTRY(bzero, 0)
+       movl    4(%ap),%r3
+       jbr     2f
+1:
+       subl2   %r0,8(%ap)
+       movc5   $0,(%r3),$0,%r0,(%r3)
+2:
+       movzwl  $65535,%r0
+       cmpl    8(%ap),%r0
+       jgtr    1b
+       movc5   $0,(%r3),$0,8(%ap),(%r3)
+       ret
diff --git a/lib/nbsd_libc/arch/vax/string/ffs.S b/lib/nbsd_libc/arch/vax/string/ffs.S
new file mode 100644 (file)
index 0000000..04d78bf
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: ffs.S,v 1.3 2003/08/07 16:42:32 agc Exp $      */
+/*
+ * 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.
+ * 3. 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)
+       .asciz "@(#)ffs.s       8.1 (Berkeley) 6/4/93"
+#endif /* LIBC_SCCS and not lint */
+
+/* bit = ffs(value) */
+
+#include "DEFS.h"
+
+ENTRY(ffs, 0)
+       ffs     $0,$32,4(%ap),%r0
+       bneq    1f
+       mnegl   $1,%r0
+1:
+       incl    %r0
+       ret
diff --git a/lib/nbsd_libc/arch/vax/string/index.S b/lib/nbsd_libc/arch/vax/string/index.S
new file mode 100644 (file)
index 0000000..097f35c
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: index.S,v 1.3 2003/08/07 16:42:32 agc Exp $    */
+/*
+ * Copyright (c) 1980, 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.
+ * 3. 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.
+ */
+
+/*
+ * Find the first occurence of c in the string cp.
+ * Return pointer to match or null pointer.
+ *
+ * char *
+ * index(cp, c)
+ *     char *cp, c;
+ */
+#include "DEFS.h"
+
+/* Alas not quite twice as fast as the generic C version on a uvax2 */
+
+ENTRY(index, 0)
+       movq    4(%ap),%r0      # %r0 = cp; %r1 = c
+       tstb    %r1             # special case, looking for '\0'
+       jeql    3f
+1:
+       cmpb    (%r0),%r1
+       jeql    2f
+       tstb    (%r0)+
+       jneq    1b
+       clrl    %r0             # return NULL if no match
+2:
+       ret
+3:
+       tstb    (%r0)+
+       jneq    3b
+       decl    %r0
+       jbr     2b
diff --git a/lib/nbsd_libc/arch/vax/string/memcmp.S b/lib/nbsd_libc/arch/vax/string/memcmp.S
new file mode 100644 (file)
index 0000000..a129fb4
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: memcmp.S,v 1.3 2003/08/07 16:42:32 agc Exp $   */
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+/* int memcmp(s1, s2, n) */
+
+#include "DEFS.h"
+
+ENTRY(memcmp, 0)
+       movl    12(%ap),%r0
+       jeql    9f
+       movq    4(%ap),%r1
+       ashl    $-2,%r0,%r3     # convert len to long words
+       jeql    2f
+1:
+       cmpl    (%r1)+,(%r2)+   # no "cmpq" alas
+       jneq    7f
+       sobgtr  %r3,1b
+2:
+       bicl3   $-4,%r0,%r3     # handle at most 3 extra bytes
+       jeql    4f
+3:
+       cmpb    (%r1)+,(%r2)+
+       jneq    8f
+       sobgtr  %r3,3b
+4:
+       clrl    %r0             # we had a match
+       ret
+7:                             # backup, and do a byte compare
+       tstl    -(%r1)
+       tstl    -(%r2)
+       movl    $4,%r3
+       jbr     3b
+8:
+       movzbl  -(%r1),%r3
+       movzbl  -(%r2),%r4
+       subl3   %r4,%r3,%r0
+9:
+       ret
diff --git a/lib/nbsd_libc/arch/vax/sys/__clone.S b/lib/nbsd_libc/arch/vax/sys/__clone.S
new file mode 100644 (file)
index 0000000..53dec10
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: __clone.S,v 1.3 2008/04/28 20:22:58 martin Exp $       */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(clone, __clone)
+#endif
+
+/*
+ * int __clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+ENTRY(__clone, 0)
+       
+       /*
+        * Sanity checks: func and stack may not be NULL.
+        */
+       movl    4(%ap),%r2      /* check and save function */
+       beql    9f
+       tstl    8(%ap)          /* check stack */
+       beql    9f
+
+       /*
+        * The system call expects (flags, stack).
+        */
+       movl    12(%ap),4(%ap)  /* XXX this doesn't work for
+                                  callg with a RO arglist */
+       movl    $2,(%ap)
+       SYSTRAP(__clone)        /* only %r0/%r1 munged */
+
+       blbc    %r1,8f          /* %r1<0>:   0=parent  1=child */
+
+       /* Call the clone's entry point. */
+       pushl   16(%ap)
+       calls   $1,(%r2)
+
+       /* Pass return value to _exit(). */
+       pushl   %r0
+       calls   $1,_C_LABEL(_exit)
+
+       /* NOTREACHED */
+
+8:     ret
+
+9:     movl    $EINVAL,%r0
+       jmp     CERROR+2
diff --git a/lib/nbsd_libc/arch/vax/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/vax/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..8c06955
--- /dev/null
@@ -0,0 +1,81 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.10 2008/04/28 20:22:58 martin Exp $       */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigaction14_sigtramp.c,v 1.10 2008/04/28 20:22:58 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/signal.h>
+#include <stddef.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+__weak_alias(__sigaction14, __libc_sigaction14)
+
+extern const int __sigtramp_siginfo_3[];
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+
+       /*
+        * If no sigaction, use the "default" trampoline since it won't
+        * be used.
+        */
+       if (act == NULL)
+               return  __sigaction_sigtramp(sig, act, oact, NULL, 0);
+
+#ifdef __LIBC12_SOURCE__
+       /*
+        * We select the non-SA_SIGINFO trampoline if SA_SIGINFO is not
+        * set in the sigaction.
+        */
+       if ((act->sa_flags & SA_SIGINFO) == 0) {
+               extern const int __sigtramp_sigcontext_2[];
+               int sav = errno;
+               int rv =  __sigaction_sigtramp(sig, act, oact,
+                   __sigtramp_sigcontext_2, 2);
+               if (rv >= 0 || errno != EINVAL)
+                       return rv;
+               errno = sav;
+       }
+#endif
+
+       /*
+        * If SA_SIGINFO was specificed or the compatibility trampolines
+        * can't be used, use the siginfo trampoline.
+        */
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_3, 3);
+}
diff --git a/lib/nbsd_libc/arch/vax/sys/__sigtramp3.S b/lib/nbsd_libc/arch/vax/sys/__sigtramp3.S
new file mode 100644 (file)
index 0000000..e4703a2
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: __sigtramp3.S,v 1.1 2003/09/30 19:05:41 matt Exp $     */
+
+/*
+ * Copyright (c) 2003 Matt Thomas <matt@3am-software.com>
+ * 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.
+ * 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 ``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 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.
+ */
+
+/*
+ * Signal trampoline; registers when called:
+ *     pc, psl - obvious
+ *     sp, ap - points to argument list
+ *         4(ap) -- signo
+ *         8(ap) -- pointer to siginfo
+ *        12(ap) -- pointer to ucontext
+ *     fp - address of signal handler
+ */
+
+#include "SYS.h"
+
+       .text
+       _ALIGN_TEXT
+
+       .globl  _C_LABEL(__sigtramp_siginfo_3)
+_C_LABEL(__sigtramp_siginfo_3):
+       callg (%ap),(%fp)               # use global arg list
+       addl2 $8,%ap                    # arg is pointer to ucontext
+       SYSTRAP(setcontext)             # exit from here
+       halt                            # illegal insn
diff --git a/lib/nbsd_libc/arch/vax/sys/__syscall.S b/lib/nbsd_libc/arch/vax/sys/__syscall.S
new file mode 100644 (file)
index 0000000..4ceb9bb
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 1983, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)syscall.s        8.2 (Berkeley) 1/21/94" */
+       .asciz "$NetBSD: __syscall.S,v 1.3 2003/08/07 16:42:33 agc Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+ENTRY(__syscall, 0)
+       movl    4(%ap),%r0      # syscall number
+       addl2   $8,%ap          # skip the first argument
+       subl3   $2,-8(%ap),(%ap)        # two fewer arguments
+       chmk    %r0
+       jcs     1f
+       ret
+1:
+       jmp     CERROR+2
diff --git a/lib/nbsd_libc/arch/vax/sys/__vfork14.S b/lib/nbsd_libc/arch/vax/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..d9bdabd
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)Ovfork.s 8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: __vfork14.S,v 1.5 2003/08/07 16:42:33 agc Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+/*
+ * @(#)vfork.s 4.1 (Berkeley) 12/21/80
+ * C library -- vfork
+ */
+
+#include "SYS.h"
+
+/*
+ * pid = vfork();
+ *
+ * %r1 == 0 in parent process, %r1 == 1 in child process.
+ * %r0 == pid of child in parent, %r0 == pid of parent in child.
+ *
+ * trickery here, due to keith sklower, uses ret to clear the stack,
+ * and then returns with a jump indirect, since only one person can return
+ * with a ret off this stack... we do the ret before we vfork!
+ */
+
+ENTRY(__vfork14, 0)
+       movl    16(%fp),%r2     # save return address before we smash it
+       movab   here,16(%fp)
+       ret
+here:
+       chmk    $ SYS___vfork14
+       bcs     err             # if failed, set errno and return -1
+       /* this next trick is Chris Torek's fault */
+       mnegl   %r1,%r1         # %r1 = 0xffffffff if child, 0 if parent
+       bicl2   %r1,%r0         # %r0 &= ~%r1, i.e., 0 if child, else unchanged
+       jmp     (%r2)
+
+err:
+#ifdef _REENTRANT
+       pushr   $0x5
+       calls   $0,_C_LABEL(__errno)
+       movl    (%sp)+,(%r0)
+       mnegl   $1,%r0
+       rsb
+#else
+       movl    %r0,_C_LABEL(errno)
+       mnegl   $1,%r0
+       jmp     (%r2)
+#endif
diff --git a/lib/nbsd_libc/arch/vax/sys/brk.S b/lib/nbsd_libc/arch/vax/sys/brk.S
new file mode 100644 (file)
index 0000000..63be221
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)brk.s    8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: brk.S,v 1.12 2003/12/26 11:21:48 martin Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  CURBRK
+       .globl  _C_LABEL(__minbrk)
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(brk, _brk)
+#endif
+
+ENTRY(_brk, 0)
+       cmpl    _C_LABEL(__minbrk),4(%ap)       # gtr > _end 
+       blequ   1f                              #   is fine
+       movl    _C_LABEL(__minbrk),4(%ap)       # shrink back to _end
+1:     chmk    $ SYS_break                     # do it
+       jcs     err
+       movl    4(%ap),CURBRK
+       clrl    %r0
+       ret
+err:
+       jmp     CERROR+2
diff --git a/lib/nbsd_libc/arch/vax/sys/cerror.S b/lib/nbsd_libc/arch/vax/sys/cerror.S
new file mode 100644 (file)
index 0000000..f943031
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)cerror.s 8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: cerror.S,v 1.8 2003/08/07 16:42:33 agc Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _C_LABEL(errno)
+CERROR: .word 0
+#ifdef _REENTRANT
+       pushl   %r0
+       calls   $0,_C_LABEL(__errno)
+       movl    (%sp)+,(%r0)
+#else
+       movl    %r0,_C_LABEL(errno)
+#endif
+       mnegl   $1,%r0
+       movl    %r0,%r1
+       ret
diff --git a/lib/nbsd_libc/arch/vax/sys/execl.S b/lib/nbsd_libc/arch/vax/sys/execl.S
new file mode 100644 (file)
index 0000000..b1262f0
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: execl.S,v 1.3 2003/08/24 21:04:53 ragge Exp $  */
+/*
+ * Copyright (c) 2001 Ludd, University of Lule}, Sweden. 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed at Ludd, University of
+ *      Lule}, Sweden and its contributors.
+ * 4. 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 ``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 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 "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(execl, _execl)
+#endif
+
+ENTRY(_execl, 0)
+       pushal  8(%ap)  # Push pointer to argv vector
+       pushl   4(%ap)  # Push path
+       calls   $2,_C_LABEL(execv)
+       ret
diff --git a/lib/nbsd_libc/arch/vax/sys/execle.S b/lib/nbsd_libc/arch/vax/sys/execle.S
new file mode 100644 (file)
index 0000000..6c8c9ff
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: execle.S,v 1.4 2003/08/24 21:04:53 ragge Exp $ */
+/*
+ * Copyright (c) 2001 Ludd, University of Lule}, Sweden. 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed at Ludd, University of
+ *      Lule}, Sweden and its contributors.
+ * 4. 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 ``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 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 "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(execle, _execle)
+#endif
+
+ENTRY(_execle, 0)
+       movl    (%ap),%r0               # Get number of args
+       pushl   (%ap)[%r0]      # Push last arg (envp)
+       pushal  8(%ap)          # Push pointer to argv vector
+       pushl   4(%ap)          # Push path
+       calls   $3,_C_LABEL(execve)
+       ret
diff --git a/lib/nbsd_libc/arch/vax/sys/execlp.S b/lib/nbsd_libc/arch/vax/sys/execlp.S
new file mode 100644 (file)
index 0000000..fd275ce
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: execlp.S,v 1.3 2003/08/24 21:04:53 ragge Exp $ */
+/*
+ * Copyright (c) 2001 Ludd, University of Lule}, Sweden. 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed at Ludd, University of
+ *      Lule}, Sweden and its contributors.
+ * 4. 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 ``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 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 "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(execlp, _execlp)
+#endif
+
+ENTRY(_execlp, 0)
+       pushal  8(%ap)  # Push pointer to argv vector
+       pushl   4(%ap)  # Push path
+       calls   $2,_C_LABEL(execvp)
+       ret
diff --git a/lib/nbsd_libc/arch/vax/sys/exect.S b/lib/nbsd_libc/arch/vax/sys/exect.S
new file mode 100644 (file)
index 0000000..3061c6f
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)exect.s  8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: exect.S,v 1.5 2003/08/07 16:42:33 agc Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+#include <machine/psl.h>
+
+ENTRY(exect, 0)
+       bispsw  $PSL_T
+       chmk    $ SYS_execve
+       jmp     CERROR+2                # exect(file, argv, env)
diff --git a/lib/nbsd_libc/arch/vax/sys/fork.S b/lib/nbsd_libc/arch/vax/sys/fork.S
new file mode 100644 (file)
index 0000000..72ddf58
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)fork.s   8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: fork.S,v 1.5 2003/08/07 16:42:33 agc Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+_SYSCALL(__fork,fork)
+       jlbc    %r1,1f  # parent, since %r1 == 0 in parent, 1 in child
+       clrl    %r0
+1:
+       ret             # pid = fork()
diff --git a/lib/nbsd_libc/arch/vax/sys/getcontext.S b/lib/nbsd_libc/arch/vax/sys/getcontext.S
new file mode 100644 (file)
index 0000000..b0d78e1
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: getcontext.S,v 1.4 2008/04/28 20:22:58 martin Exp $    */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext, _getcontext)
+#endif
+
+/*
+ * Can't use R4 or R5 since those needed by the phread_switch code.
+ */
+ENTRY(_getcontext, 0)
+       clrl    %r0                     /* assume success */
+       chmk    $SYS_getcontext         /* getcontext(oucp) */
+       jcc     1f
+       jmp     CERROR+2                /* badness happened */
+
+1:     movl    4(%ap),%r2              /* ptr to ucontext */
+       movl    16(%fp),%r3             /* PC to return to */
+       movab   2f,16(%fp)              /* let's return early */
+       ret
+       /*
+        * Now we have the blown away the callframe and argument
+        * list so it's as if we've return from the function except
+        * we aren't executing the caller's code (yet).  So it's
+        * the callers state but we still have control.
+        */
+       _ALIGN_TEXT
+2:     movq    %ap,(36+12*4)(%r2)      /* adjust AP + SP */
+       movl    %fp,(36+14*4)(%r2)      /* adjust FP */
+       movl    %r3,(36+15*4)(%r2)      /* adjust PC */
+       jmp     (%r3)                   /* and return */
diff --git a/lib/nbsd_libc/arch/vax/sys/pipe.S b/lib/nbsd_libc/arch/vax/sys/pipe.S
new file mode 100644 (file)
index 0000000..9163d1f
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)pipe.s   8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: pipe.S,v 1.4 2003/08/07 16:42:33 agc Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe, _pipe)
+#endif
+
+_SYSCALL(_pipe,pipe)
+       movl    4(%ap),%r2
+       movl    %r0,(%r2)+
+       movl    %r1,(%r2)
+       clrl    %r0
+       ret
diff --git a/lib/nbsd_libc/arch/vax/sys/ptrace.S b/lib/nbsd_libc/arch/vax/sys/ptrace.S
new file mode 100644 (file)
index 0000000..0aa93b1
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)ptrace.s 8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: ptrace.S,v 1.7 2003/08/07 16:42:33 agc Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+ENTRY(ptrace, 0)
+#ifdef _REENTRANT
+       calls   $0,_C_LABEL(__errno)
+       clrl    (%r0)
+#else
+       clrl    _C_LABEL(errno)
+#endif
+       chmk    $ SYS_ptrace
+       jcs     err
+       ret
+err:
+       jmp     CERROR+2
diff --git a/lib/nbsd_libc/arch/vax/sys/sbrk.S b/lib/nbsd_libc/arch/vax/sys/sbrk.S
new file mode 100644 (file)
index 0000000..19fad3a
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)sbrk.s   8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: sbrk.S,v 1.10 2003/08/07 16:42:33 agc Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _end
+       .globl  _C_LABEL(__minbrk)
+       .globl  CURBRK
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(sbrk, _sbrk)
+#endif
+
+       .data
+_C_LABEL(__minbrk):
+       .long   _end
+CURBRK:
+       .long   _end
+       .text
+
+ENTRY(_sbrk, 0)
+       addl3   CURBRK,4(%ap),-(%sp)
+       pushl   $1
+       movl    %ap,%r3
+       movl    %sp,%ap
+       chmk    $ SYS_break
+       jcs     err
+       movl    CURBRK,%r0
+       addl2   4(%r3),CURBRK
+       ret
+err:
+       jmp     CERROR+2
diff --git a/lib/nbsd_libc/arch/vax/sys/shmat.S b/lib/nbsd_libc/arch/vax/sys/shmat.S
new file mode 100644 (file)
index 0000000..216dbd8
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: shmat.S,v 1.1 2000/07/07 08:20:55 itohy Exp $  */
+
+#include "SYS.h"
+
+RSYSCALL(shmat)
diff --git a/lib/nbsd_libc/arch/vax/sys/syscall.S b/lib/nbsd_libc/arch/vax/sys/syscall.S
new file mode 100644 (file)
index 0000000..b55c600
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 1983, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)syscall.s        8.2 (Berkeley) 1/21/94" */
+       .asciz "$NetBSD: syscall.S,v 1.6 2003/08/07 16:42:34 agc Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+ENTRY(syscall, 0)
+       movl    4(%ap),%r0      # syscall number
+       subl3   $1,(%ap)+,(%ap) # one fewer arguments
+       chmk    %r0
+       jcs     1f
+       ret
+1:
+       jmp     CERROR+2
diff --git a/lib/nbsd_libc/arch/x86_64/Makefile.inc b/lib/nbsd_libc/arch/x86_64/Makefile.inc
new file mode 100644 (file)
index 0000000..b4b415e
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.5 2006/06/17 18:04:24 uwe Exp $
+
+SRCS+= __sigaction14_sigtramp.c __sigtramp2.S
diff --git a/lib/nbsd_libc/arch/x86_64/SYS.h b/lib/nbsd_libc/arch/x86_64/SYS.h
new file mode 100644 (file)
index 0000000..2b02603
--- /dev/null
@@ -0,0 +1,93 @@
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)SYS.h 5.5 (Berkeley) 5/7/91
+ *     $NetBSD: SYS.h,v 1.10 2007/11/23 07:36:05 dsl Exp $
+ */
+
+#include <machine/asm.h>
+#include <sys/syscall.h>
+
+#ifdef __STDC__
+#define SYSTRAP(x)     movl $(SYS_ ## x),%eax; movq %rcx, %r10; syscall
+#else
+#define SYSTRAP(x)     movl $(SYS_/**/x),%eax; movq %rcx, %r10; syscall
+#endif
+
+#define CERROR         _C_LABEL(__cerror)
+#define CURBRK         _C_LABEL(__curbrk)
+
+#define _SYSCALL_NOERROR(x,y)                                          \
+       ENTRY(x);                                                       \
+       SYSTRAP(y)
+
+#ifdef PIC
+#define _SYSCALL_ERR                                                   \
+       mov PIC_GOT(CERROR), %rcx;                                      \
+       jmp *%rcx
+#else
+#define _SYSCALL_ERR                                                   \
+       jmp CERROR
+#endif
+
+#define _SYSCALL(x,y)                                                  \
+       .text; _ALIGN_TEXT;                                             \
+       2: _SYSCALL_ERR;                                                \
+       _SYSCALL_NOERROR(x,y);                                          \
+       jc 2b
+
+#define SYSCALL_NOERROR(x)                                             \
+       _SYSCALL_NOERROR(x,x)
+
+#define SYSCALL(x)                                                     \
+       _SYSCALL(x,x)
+
+#define PSEUDO_NOERROR(x,y)                                            \
+       _SYSCALL_NOERROR(x,y);                                          \
+       ret
+
+#define PSEUDO(x,y)                                                    \
+       _SYSCALL_NOERROR(x,y);                                          \
+       jc 2f;                                                          \
+       ret;                                                            \
+       2: _SYSCALL_ERR
+
+#define RSYSCALL_NOERROR(x)                                            \
+       PSEUDO_NOERROR(x,x)
+
+#define RSYSCALL(x)                                                    \
+       PSEUDO(x,x)
+
+#define        WSYSCALL(weak,strong)                                           \
+       WEAK_ALIAS(weak,strong);                                        \
+       PSEUDO(strong,weak)
+
+       .globl  CERROR
diff --git a/lib/nbsd_libc/arch/x86_64/gdtoa/Makefile.inc b/lib/nbsd_libc/arch/x86_64/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..ce2f485
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/15 17:35:18 kleink Exp $
+
+SRCS+= strtof.c strtold_px.c
+SRCS+= strtopx.c
diff --git a/lib/nbsd_libc/arch/x86_64/gdtoa/arith.h b/lib/nbsd_libc/arch/x86_64/gdtoa/arith.h
new file mode 100644 (file)
index 0000000..1513f1f
--- /dev/null
@@ -0,0 +1,3 @@
+/* $NetBSD: arith.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define IEEE_LITTLE_ENDIAN
diff --git a/lib/nbsd_libc/arch/x86_64/gdtoa/gd_qnan.h b/lib/nbsd_libc/arch/x86_64/gdtoa/gd_qnan.h
new file mode 100644 (file)
index 0000000..98638cc
--- /dev/null
@@ -0,0 +1,11 @@
+/* $NetBSD: gd_qnan.h,v 1.1 2006/01/25 15:33:28 kleink Exp $ */
+
+#define f_QNAN 0x7fc00000
+#define d_QNAN0 0x0
+#define d_QNAN1 0x7ff80000
+#define ldus_QNAN0 0x0
+#define ldus_QNAN1 0x0
+#define ldus_QNAN2 0x0
+#define ldus_QNAN3 0x4000
+#define ldus_QNAN4 0x7fff
+/* 6 bytes of tail padding follow, per AMD64 ABI */
diff --git a/lib/nbsd_libc/arch/x86_64/gen/Makefile.inc b/lib/nbsd_libc/arch/x86_64/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..3f79456
--- /dev/null
@@ -0,0 +1,36 @@
+#      $NetBSD: Makefile.inc,v 1.15 2010/01/14 02:09:46 joerg Exp $
+
+# objects built from assembler sources (need lint stubs)
+SRCS+= alloca.S byte_swap_2.S byte_swap_4.S byte_swap_8.S fabs.S \
+       flt_rounds.S fpgetmask.S fpgetround.S fpgetsticky.S \
+       fpsetmask.S fpsetround.S fpsetsticky.S 
+
+SRCS+= __setjmp14.S
+SRCS+= _setjmp.S
+SRCS+= __sigsetjmp14.S
+
+SRCS+= resumecontext.S swapcontext.S
+
+# objects built from C sources
+SRCS+= _lwp.c makecontext.c
+
+# Common ieee754 constants and functions
+SRCS+= infinityf_ieee754.c infinity_ieee754.c
+SRCS+= fpclassifyf_ieee754.c fpclassifyd_ieee754.c
+SRCS+= isfinitef_ieee754.c isfinited_ieee754.c
+SRCS+= isinff_ieee754.c isinfd_ieee754.c
+SRCS+= isnanf_ieee754.c isnand_ieee754.c
+SRCS+= signbitf_ieee754.c signbitd_ieee754.c
+
+SRCS+= nanf.c infinityl.c
+SRCS+= fpclassifyl.c isfinitel.c isinfl.c isnanl.c signbitl.c
+
+LSRCS.x86_64.gen=\
+       Lint__setjmp.c Lint_alloca.c Lint_bswap16.c Lint_bswap32.c \
+       Lint_bswap64.c Lint_fabs.c \
+       Lint___setjmp14.c Lint___sigsetjmp14.c Lint_flt_rounds.c \
+       Lint_fpgetmask.c Lint_fpgetround.c Lint_fpgetsticky.c \
+       Lint_fpsetmask.c Lint_fpsetround.c Lint_fpsetsticky.c
+LSRCS+=                ${LSRCS.x86_64.gen}
+DPSRCS+=       ${LSRCS.x86_64.gen}
+CLEANFILES+=   ${LSRCS.x86_64.gen}
diff --git a/lib/nbsd_libc/arch/x86_64/gen/__setjmp14.S b/lib/nbsd_libc/arch/x86_64/gen/__setjmp14.S
new file mode 100644 (file)
index 0000000..c5541cb
--- /dev/null
@@ -0,0 +1,108 @@
+/*     $NetBSD: __setjmp14.S,v 1.1 2001/06/19 00:25:02 fvdl Exp $      */
+
+/*
+ * Copyright (c) 2001 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Frank van der Linden for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 <machine/asm.h>
+#include <machine/setjmp.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: __setjmp14.S,v 1.1 2001/06/19 00:25:02 fvdl Exp $")
+#endif
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(__setjmp14)
+       movq    (%rsp),%r11
+       movq    %rbx,(_JB_RBX * 8)(%rdi)
+       movq    %rbp,(_JB_RBP * 8)(%rdi)
+       movq    %r12,(_JB_R12 * 8)(%rdi)
+       movq    %r13,(_JB_R13 * 8)(%rdi)
+       movq    %r14,(_JB_R14 * 8)(%rdi)
+       movq    %r15,(_JB_R15 * 8)(%rdi)
+       movq    %rsp,(_JB_RSP * 8)(%rdi)
+       movq    %r11,(_JB_PC  * 8)(%rdi)
+
+       leaq    (_JB_SIGMASK * 8)(%rdi),%rdx
+       xorl    %edi,%edi
+       xorq    %rsi,%rsi
+
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(__sigprocmask14))
+#else
+       call    _C_LABEL(__sigprocmask14)
+#endif
+2:     xorl    %eax,%eax
+       ret
+
+ENTRY(__longjmp14)
+       movq    %rdi,%r12
+       movl    %esi,%r8d
+
+       leaq    (_JB_SIGMASK * 8)(%rdi),%rsi
+       movl    $3,%edi         /* SIG_SETMASK */
+       xorq    %rdx,%rdx
+
+       pushq   %r8
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(__sigprocmask14))
+#else
+       call    _C_LABEL(__sigprocmask14)
+#endif
+       popq    %r8
+       movq    (_JB_RBX * 8)(%r12),%rbx
+       movq    (_JB_RBP * 8)(%r12),%rbp
+       movq    (_JB_R13 * 8)(%r12),%r13
+       movq    (_JB_R14 * 8)(%r12),%r14
+       movq    (_JB_R15 * 8)(%r12),%r15
+       movq    (_JB_RSP * 8)(%r12),%rsp
+       movq    (_JB_PC  * 8)(%r12),%r11
+       movq    (_JB_R12 * 8)(%r12),%r12
+
+       movl    %r8d,%eax
+       testl   %eax,%eax
+       jnz     1f
+       incl    %eax
+1:     movq    %r11,0(%rsp)
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/gen/__sigsetjmp14.S b/lib/nbsd_libc/arch/x86_64/gen/__sigsetjmp14.S
new file mode 100644 (file)
index 0000000..07b3db6
--- /dev/null
@@ -0,0 +1,112 @@
+/*     $NetBSD: __sigsetjmp14.S,v 1.1 2001/06/19 00:25:02 fvdl Exp $   */
+
+/*
+ * Copyright (c) 2001 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Frank van der Linden for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 <machine/asm.h>
+#include <machine/setjmp.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: __sigsetjmp14.S,v 1.1 2001/06/19 00:25:02 fvdl Exp $")
+#endif
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(__sigsetjmp14)
+       movq    (%rsp),%r11
+       movq    %rbx,(_JB_RBX * 8)(%rdi)
+       movq    %rbp,(_JB_RBP * 8)(%rdi)
+       movq    %r12,(_JB_R12 * 8)(%rdi)
+       movq    %r13,(_JB_R13 * 8)(%rdi)
+       movq    %r14,(_JB_R14 * 8)(%rdi)
+       movq    %r15,(_JB_R15 * 8)(%rdi)
+       movq    %rsp,(_JB_RSP * 8)(%rdi)
+       movq    %r11,(_JB_PC  * 8)(%rdi)
+
+       movq    %rsi,(_JB_SIGFLAG  * 8)(%rdi)
+       testl   %esi,%esi
+       jz      2f
+
+       leaq    (_JB_SIGMASK * 8)(%rdi),%rdx
+       xorl    %edi,%edi
+       xorq    %rsi,%rsi
+
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(__sigprocmask14))
+#else
+       call    _C_LABEL(__sigprocmask14)
+#endif
+2:     xorl    %eax,%eax
+       ret
+
+ENTRY(__siglongjmp14)
+       movq    %rdi,%r12
+       pushq   %rsi
+       cmpl    $0, (_JB_SIGFLAG * 8)(%rdi)
+
+       jz      2f
+       leaq    (_JB_SIGMASK * 8)(%rdi),%rsi
+       movl    $3,%edi         /* SIG_SETMASK */
+       xorq    %rdx,%rdx
+
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(__sigprocmask14))
+#else
+       call    _C_LABEL(__sigprocmask14)
+#endif
+2:     popq    %rax
+       movq    (_JB_RBX * 8)(%r12),%rbx
+       movq    (_JB_RBP * 8)(%r12),%rbp
+       movq    (_JB_R13 * 8)(%r12),%r13
+       movq    (_JB_R14 * 8)(%r12),%r14
+       movq    (_JB_R15 * 8)(%r12),%r15
+       movq    (_JB_RSP * 8)(%r12),%rsp
+       movq    (_JB_PC  * 8)(%r12),%r11
+       movq    (_JB_R12 * 8)(%r12),%r12
+
+       testl   %eax,%eax
+       jnz     1f
+       incl    %eax
+1:     movq    %r11,0(%rsp)
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/gen/_lwp.c b/lib/nbsd_libc/arch/x86_64/gen/_lwp.c
new file mode 100644 (file)
index 0000000..511c126
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: _lwp.c,v 1.6 2009/07/02 09:57:09 joerg Exp $   */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Nathan J. Williams.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _lwp.c,v 1.6 2009/07/02 09:57:09 joerg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <inttypes.h>
+#include <ucontext.h>
+#include <lwp.h>
+#include <stdlib.h>
+
+void
+_lwp_makecontext(ucontext_t *u, void (*start)(void *),
+    void *arg, void *private, caddr_t stack_base, size_t stack_size)
+{
+       __greg_t *gr = u->uc_mcontext.__gregs;
+       void **sp;
+
+       getcontext(u);
+       u->uc_link = NULL;
+
+       u->uc_stack.ss_sp = stack_base;
+       u->uc_stack.ss_size = stack_size;
+
+       /* LINTED uintptr_t is safe */
+       gr[_REG_RIP] = (uintptr_t)start;
+       
+       sp = (void **) (((uintptr_t)(stack_base + stack_size) & ~15));
+
+       /* LINTED __greg_t is safe */
+       gr[_REG_RDI] = (__greg_t)arg;
+       *--sp = (void *) _lwp_exit;
+       
+       /* LINTED uintptr_t is safe */
+       gr[_REG_URSP] = (uintptr_t) sp;
+
+       /* LINTED private is currently unused */
+}
diff --git a/lib/nbsd_libc/arch/x86_64/gen/_setjmp.S b/lib/nbsd_libc/arch/x86_64/gen/_setjmp.S
new file mode 100644 (file)
index 0000000..fb95430
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: _setjmp.S,v 1.1 2001/06/19 00:25:02 fvdl Exp $ */
+
+/*
+ * Copyright (c) 2001 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Frank van der Linden for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 <machine/asm.h>
+#include <machine/setjmp.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: _setjmp.S,v 1.1 2001/06/19 00:25:02 fvdl Exp $")
+#endif
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     _longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     _setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is NOT restored.
+ */
+
+ENTRY(_setjmp)
+       movq    (%rsp),%r11
+       movq    %rbx,(_JB_RBX * 8)(%rdi)
+       movq    %rbp,(_JB_RBP * 8)(%rdi)
+       movq    %r12,(_JB_R12 * 8)(%rdi)
+       movq    %r13,(_JB_R13 * 8)(%rdi)
+       movq    %r14,(_JB_R14 * 8)(%rdi)
+       movq    %r15,(_JB_R15 * 8)(%rdi)
+       movq    %rsp,(_JB_RSP * 8)(%rdi)
+       movq    %r11,(_JB_PC  * 8)(%rdi)
+
+       xorl    %eax,%eax
+       ret
+
+ENTRY(_longjmp)
+       movq    (_JB_RBX * 8)(%rdi),%rbx
+       movq    (_JB_RBP * 8)(%rdi),%rbp
+       movq    (_JB_R12 * 8)(%rdi),%r12
+       movq    (_JB_R13 * 8)(%rdi),%r13
+       movq    (_JB_R14 * 8)(%rdi),%r14
+       movq    (_JB_R15 * 8)(%rdi),%r15
+       movq    (_JB_RSP * 8)(%rdi),%rsp
+       movq    (_JB_PC  * 8)(%rdi),%r11
+
+       movl    %esi,%eax
+       testl   %eax,%eax
+       jnz     1f
+       incl    %eax
+1:     movq    %r11,0(%rsp)
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/gen/alloca.S b/lib/nbsd_libc/arch/x86_64/gen/alloca.S
new file mode 100644 (file)
index 0000000..ab232f6
--- /dev/null
@@ -0,0 +1,16 @@
+/*     $NetBSD: alloca.S,v 1.1 2001/06/19 00:25:02 fvdl Exp $  */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: alloca.S,v 1.1 2001/06/19 00:25:02 fvdl Exp $")
+#endif
+
+ENTRY(alloca)
+       popq    %rdx
+       movq    %rsp,%rcx
+       addq    $15,%rdi        /*  round up to 16 bytes */
+       andq    $~15,%rdi
+       subq    %rdi,%rsp
+       movq    %rsp,%rax
+       jmp     *%rdx
diff --git a/lib/nbsd_libc/arch/x86_64/gen/fabs.S b/lib/nbsd_libc/arch/x86_64/gen/fabs.S
new file mode 100644 (file)
index 0000000..69d577c
--- /dev/null
@@ -0,0 +1,17 @@
+/*     $NetBSD: fabs.S,v 1.3 2004/03/23 17:11:35 drochner Exp $        */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: fabs.S,v 1.3 2004/03/23 17:11:35 drochner Exp $")
+#endif
+
+       .section .rodata
+       .align 8
+__signmask:
+       .long 0xffffffff
+       .long 0x7fffffff
+
+ENTRY(fabs)
+       movsd   __signmask(%rip),%xmm1
+       andpd   %xmm1,%xmm0
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/gen/flt_rounds.S b/lib/nbsd_libc/arch/x86_64/gen/flt_rounds.S
new file mode 100644 (file)
index 0000000..1b23501
--- /dev/null
@@ -0,0 +1,29 @@
+/*     $NetBSD: flt_rounds.S,v 1.2 2002/06/06 23:04:35 fvdl Exp $      */
+
+/*
+ * Written by J.T. Conklin, Apr 4, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+       .text
+       _ALIGN_TEXT
+_map:
+       .byte 1         /* round to nearest */
+       .byte 3         /* round to negative infinity */
+       .byte 2         /* round to positive infinity */
+       .byte 0         /* round to zero */
+
+ENTRY(__flt_rounds)
+       fnstcw -4(%rsp)
+       movl -4(%rsp),%eax
+       shrl $10,%eax
+       andl $3,%eax
+#ifdef PIC
+       leaq PIC_GOT(_map),%rcx
+       movb (%rcx,%rax,1),%al
+#else
+       movb _map(,%rax,1),%al
+#endif
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/gen/fpclassifyl.c b/lib/nbsd_libc/arch/x86_64/gen/fpclassifyl.c
new file mode 100644 (file)
index 0000000..edaf283
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: fpclassifyl.c,v 1.4 2008/04/28 20:22:58 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpclassifyl.c,v 1.4 2008/04/28 20:22:58 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <assert.h>
+#include <math.h>
+
+/*
+ * 7.12.3.1 fpclassify - classify real floating type
+ *          IEEE 754 compatible 80-bit extended-precision Intel 386 version
+ */
+int
+__fpclassifyl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       _DIAGASSERT(u.extu_ext.ext_exp == 0 ||
+           (u.extu_ext.ext_frach & 0x80000000));
+
+       if (u.extu_ext.ext_exp == 0) {
+               if ((u.extu_ext.ext_frach & 0x7fffffff) == 0 &&
+                   u.extu_ext.ext_fracl == 0)
+                       return FP_ZERO;
+               else
+                       return FP_SUBNORMAL;
+       } else if (u.extu_ext.ext_exp == EXT_EXP_INFNAN) {
+               if ((u.extu_ext.ext_frach & 0x7fffffff) == 0 &&
+                   u.extu_ext.ext_fracl == 0)
+                       return FP_INFINITE;
+               else
+                       return FP_NAN;
+       }
+
+       return FP_NORMAL;
+}
diff --git a/lib/nbsd_libc/arch/x86_64/gen/fpgetmask.S b/lib/nbsd_libc/arch/x86_64/gen/fpgetmask.S
new file mode 100644 (file)
index 0000000..2b367a9
--- /dev/null
@@ -0,0 +1,26 @@
+/*     $NetBSD: fpgetmask.S,v 1.3 2002/06/12 19:17:22 fvdl Exp $       */
+
+/*
+ * Written by J.T. Conklin, Apr 4, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+/*
+ * XXX only read x87 control word here. If an application only
+ * uses the fp* interface to manipulate FP bits, it should
+ * always remain in sync with the SSE mxcsr register.
+ */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpgetmask, _fpgetmask)
+ENTRY(_fpgetmask)
+#else
+ENTRY(fpgetmask)
+#endif
+       fnstcw -4(%rsp)
+       movl -4(%rsp),%eax
+       notl %eax
+       andl $63,%eax
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/gen/fpgetround.S b/lib/nbsd_libc/arch/x86_64/gen/fpgetround.S
new file mode 100644 (file)
index 0000000..2693c27
--- /dev/null
@@ -0,0 +1,25 @@
+/*     $NetBSD: fpgetround.S,v 1.3 2002/06/12 19:17:22 fvdl Exp $      */
+
+/*
+ * Written by J.T. Conklin, Apr 4, 1995
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+/*
+ * XXX store only x87 state. If an application only uses the fp*
+ * interface, this should be in sync with the SSE mxcsr register.
+ */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpgetround, _fpgetround)
+ENTRY(_fpgetround)
+#else
+ENTRY(fpgetround)
+#endif
+       fnstcw -4(%rsp)
+       movl -4(%rsp),%eax
+       rorl $10,%eax
+       andl $3,%eax
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/gen/fpgetsticky.S b/lib/nbsd_libc/arch/x86_64/gen/fpgetsticky.S
new file mode 100644 (file)
index 0000000..f715864
--- /dev/null
@@ -0,0 +1,27 @@
+/*     $NetBSD: fpgetsticky.S,v 1.3 2002/06/12 19:17:22 fvdl Exp $     */
+
+/*
+ * Written by Frank van der Linden at Wasabi Systems for NetBSD.
+ * Public domain.
+ *
+ */
+
+#include <machine/asm.h>
+
+/*
+ * XXX read both the x87 and SSE status words here, and OR
+ * them to get a complete picture of exceptions.
+ */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpgetsticky, _fpgetsticky)
+ENTRY(_fpgetsticky)
+#else
+ENTRY(fpgetsticky)
+#endif
+       fnstsw  -4(%rsp)
+       stmxcsr -8(%rsp)
+       movl    -4(%rsp),%eax
+       orl     -8(%rsp),%eax
+       andl    $63,%eax
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/gen/fpsetmask.S b/lib/nbsd_libc/arch/x86_64/gen/fpsetmask.S
new file mode 100644 (file)
index 0000000..0e18099
--- /dev/null
@@ -0,0 +1,41 @@
+/*     $NetBSD: fpsetmask.S,v 1.3 2002/06/12 19:17:22 fvdl Exp $       */
+
+/*
+ * Written by Frank van der Linden at Wasabi Systems for NetBSD.
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+/*
+ * XXX set both the x87 control word and the SSE mxcsr register.
+ * Applications should only set exception and round flags
+ * via the fp*() interface, otherwise the status words
+ * will get our of sync.
+ */
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpsetmask, _fpsetmask)
+ENTRY(_fpsetmask)
+#else
+ENTRY(fpsetmask)
+#endif
+       fnstcw  -4(%rsp)
+       stmxcsr -8(%rsp)
+       andl    $63,%edi
+       notl    %edi
+
+       movl    -4(%rsp),%edx
+       movl    %edx,%eax
+       andl    %edi,%edx
+       movl    %edx,-4(%rsp)
+
+       movl    -8(%rsp),%edx
+       roll    $7,%edi
+       andl    %edi,%edx
+       movl    %edx,-8(%rsp)
+
+       fldcw   -4(%rsp)
+       ldmxcsr -8(%rsp)
+       andl    $63,%eax
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/gen/fpsetround.S b/lib/nbsd_libc/arch/x86_64/gen/fpsetround.S
new file mode 100644 (file)
index 0000000..68e275f
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: fpsetround.S,v 1.3 2002/06/12 19:17:22 fvdl Exp $      */
+
+/*
+ * Written by Frank van der Linden at Wasabi Systems for NetBSD.
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+/*
+ * XXX set both the x87 control word and the SSE mxcsr register.
+ * Applications should only set exception and round flags
+ * via the fp*() interface, otherwise the status words
+ * will get our of sync.
+ */ 
+
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpsetround, _fpsetround)
+ENTRY(_fpsetround)
+#else
+ENTRY(fpsetround)
+#endif
+       fnstcw  -4(%rsp)
+       stmxcsr -8(%rsp)
+
+       andl    $3,%edi
+
+       movl    -4(%rsp),%edx
+       rorl    $10,%edx
+       movl    %edx,%eax
+       andl    $3,%eax
+
+       andl    $~3,%edx
+       orl     %edi,%edx
+       roll    $10,%edx
+       movl    %edx,-4(%rsp)
+
+       movl    -8(%rsp),%edx
+       rorl    $13,%edx
+       andl    $~3,%edx
+       orl     %edi,%edx
+       roll    $13,%edx
+       movl    %edx,-8(%rsp)
+
+       ldmxcsr -8(%rsp)
+       fldcw   -4(%rsp)
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/gen/fpsetsticky.S b/lib/nbsd_libc/arch/x86_64/gen/fpsetsticky.S
new file mode 100644 (file)
index 0000000..71c29cf
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: fpsetsticky.S,v 1.5 2004/03/09 17:16:13 drochner Exp $ */
+
+/*
+ * Written by Frank van der Linden at Wasabi Systems for NetBSD
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+/*
+ * XXX set both the x87 status word and the SSE mxcsr register.
+ * Applications should only set exception and round flags
+ * via the fp*() interface, otherwise the status words
+ * will get our of sync.
+ */ 
+
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(fpsetsticky, _fpsetsticky)
+ENTRY(_fpsetsticky)
+#else
+ENTRY(fpsetsticky)
+#endif
+       fnstenv -28(%rsp)
+       stmxcsr -32(%rsp)
+
+       andl    $63,%edi
+
+       movl    -24(%rsp),%eax
+       movl    %eax,%edx
+       andb    $0xc0,%dl
+
+       orl     %edi,%edx
+       movl    %edx,-24(%rsp)
+
+       movl    -32(%rsp),%edx
+       orl     %edx,%eax
+       andl    $63,%eax
+       andb    $0xc0,%dl
+       orl     %edi,%edx
+       movl    %edx,-32(%rsp)
+
+       ldmxcsr -32(%rsp)
+       fldenv  -28(%rsp)
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/gen/infinityl.c b/lib/nbsd_libc/arch/x86_64/gen/infinityl.c
new file mode 100644 (file)
index 0000000..d931768
--- /dev/null
@@ -0,0 +1,16 @@
+/*     $NetBSD: infinityl.c,v 1.2 2005/06/12 05:21:27 lukem Exp $      */
+
+/*
+ * IEEE-compatible infinityl.c for little-endian 80-bit format -- public domain.
+ * Note that the representation includes 48 bits of tail padding per amd64 ABI.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: infinityl.c,v 1.2 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+
+const union __long_double_u __infinityl =
+       { { 0, 0, 0, 0, 0, 0, 0, 0x80, 0xff, 0x7f, 0, 0, 0, 0, 0, 0 } };
diff --git a/lib/nbsd_libc/arch/x86_64/gen/isfinitel.c b/lib/nbsd_libc/arch/x86_64/gen/isfinitel.c
new file mode 100644 (file)
index 0000000..d0f960a
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: isfinitel.c,v 1.3 2008/04/28 20:22:58 martin Exp $     */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: isfinitel.c,v 1.3 2008/04/28 20:22:58 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <assert.h>
+#include <math.h>
+
+/*
+ * 7.12.3.2 isfinite - determine whether an argument has finite value
+ *          IEEE 754 compatible 80-bit extended-precision Intel 386 version
+ */
+int
+__isfinitel(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       _DIAGASSERT(u.extu_ext.ext_exp == 0 ||
+           (u.extu_ext.ext_frach & 0x80000000));
+
+       if (u.extu_ext.ext_exp == EXT_EXP_INFNAN)
+               return 0;
+
+       return 1;
+}
diff --git a/lib/nbsd_libc/arch/x86_64/gen/isinfl.c b/lib/nbsd_libc/arch/x86_64/gen/isinfl.c
new file mode 100644 (file)
index 0000000..3304511
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: isinfl.c,v 1.6 2007/02/02 23:19:25 christos Exp $      */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isinfl.c,v 1.6 2007/02/02 23:19:25 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.3 isinf - test for infinity
+ *          IEEE 754 compatible 80-bit extended-precision Intel 386 version
+ */
+int
+__isinfl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return (u.extu_ext.ext_exp == EXT_EXP_INFNAN &&
+            u.extu_ext.ext_frach == 0x80000000 && u.extu_ext.ext_fracl == 0);
+}
diff --git a/lib/nbsd_libc/arch/x86_64/gen/isnanl.c b/lib/nbsd_libc/arch/x86_64/gen/isnanl.c
new file mode 100644 (file)
index 0000000..8694ec8
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: isnanl.c,v 1.6 2007/02/02 23:19:25 christos Exp $      */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isnanl.c,v 1.6 2007/02/02 23:19:25 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.4 isnan - test for a NaN
+ *          IEEE 754 compatible 80-bit extended-precision Intel 386 version
+ */
+int
+__isnanl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return (u.extu_ext.ext_exp == EXT_EXP_INFNAN &&
+           (u.extu_ext.ext_frach & 0x80000000) != 0 &&
+           (u.extu_ext.ext_frach != 0x80000000 || u.extu_ext.ext_fracl != 0));
+}
diff --git a/lib/nbsd_libc/arch/x86_64/gen/makecontext.c b/lib/nbsd_libc/arch/x86_64/gen/makecontext.c
new file mode 100644 (file)
index 0000000..e689761
--- /dev/null
@@ -0,0 +1,97 @@
+/*     $NetBSD: makecontext.c,v 1.4 2009/07/30 20:57:17 dsl Exp $      */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ *
+ * Modified from the i386 version for x86_64 by fvdl@wasabisystems.com.
+ *
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: makecontext.c,v 1.4 2009/07/30 20:57:17 dsl Exp $");
+#endif
+
+#include <inttypes.h>
+#include <stddef.h>
+#include <ucontext.h>
+#include "extern.h"
+
+#include <stdarg.h>
+
+void
+makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
+{
+       __greg_t *gr = ucp->uc_mcontext.__gregs;
+       uintptr_t *sp;
+       va_list ap;
+       int stackargs, i;
+
+       stackargs = argc - 6;
+
+       /* LINTED __greg_t is safe */
+       gr[_REG_RIP] = (__greg_t)func;
+
+       /* LINTED uintptr_t is safe */
+       sp  = (uintptr_t *)
+           ((uintptr_t)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size);
+
+       /* LINTED uintptr_t is safe */
+       sp  = (uintptr_t *)(((uintptr_t)sp & ~15));
+       sp--;
+       if (stackargs > 0)
+               sp -= stackargs;
+       /* LINTED __greg_t is safe */
+       gr[_REG_RSP] = (__greg_t)sp;
+       gr[_REG_RBP] = (__greg_t)0;     /* Wipe out frame pointer. */
+
+       /* Put return address on top of stack. */
+       /* LINTED uintptr_t is safe */
+       *sp++ = (uintptr_t)_resumecontext;
+
+       /*
+        * Construct argument list.
+        * The registers used to pass the first 6 arguments
+        * (rdi, rsi, rdx, rcx, r8, r9) are the first 6 in gregs,
+        * in that order, so those arguments can just be copied to
+        * the gregs array.
+        */
+       va_start(ap, argc);
+       for (i = 0; i < 6 && argc > 0; i++) {
+               argc--;
+               /* LINTED __greg_t is safe */
+               gr[i] = va_arg(ap, __greg_t);
+       }
+
+       while (stackargs-- > 0) {
+               /* LINTED uintptr_t is safe */
+               *sp++ = va_arg(ap, uintptr_t);
+       }
+
+       va_end(ap);
+}
diff --git a/lib/nbsd_libc/arch/x86_64/gen/nanf.c b/lib/nbsd_libc/arch/x86_64/gen/nanf.c
new file mode 100644 (file)
index 0000000..ffc388e
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: nanf.c,v 1.4 2009/02/22 01:34:02 martin Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nanf.c,v 1.4 2009/02/22 01:34:02 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+/* bytes for quiet NaN (IEEE single precision) */
+const union __float_u __nanf =
+               { {    0,    0, 0xc0, 0x7f } };
+
+__warn_references(__nanf, "warning: <math.h> defines NAN incorrectly for your compiler.")
diff --git a/lib/nbsd_libc/arch/x86_64/gen/resumecontext.S b/lib/nbsd_libc/arch/x86_64/gen/resumecontext.S
new file mode 100644 (file)
index 0000000..693169f
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: resumecontext.S,v 1.4 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ *
+ * Modified for x86-64 by fvdl@wasabisystems.com
+ */
+
+#include <machine/asm.h>
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: resumecontext.S,v 1.4 2008/04/28 20:22:58 martin Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+/*
+ * This assembly-language implementation differs from the (obvious)
+ * C-language implementation only in not clobbering the previous
+ * function's return address (us), which is the point of the exercise.
+ */
+
+NENTRY(_resumecontext) /* profiling prologue would clobber TOS */
+       leaq    -(8 + 784)(%rsp),%rdi   /* retaddr + sizeof (ucontext_t) */
+       andq    $~15,%rdi               /* align on _UC_UCONTEXT_ALIGN */
+       movq    %rdi,%rsp
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(_getcontext))
+#else
+       call    _C_LABEL(_getcontext)
+#endif
+       movq    8(%rsp),%rdi    /* uc_link */
+       testq   %rdi,%rdi       /* link end? */
+       jnz     9f
+
+       /* normal exit */
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(exit))
+#else
+       call    _C_LABEL(exit)
+#endif
+
+9:
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(setcontext))
+#else
+       call    _C_LABEL(setcontext)
+#endif
+       /* NOTREACHED */
+
+       /* something is wrong, pull the brake */
+       movq    $-1,%rdi
+       movq    $SYS_exit,%rax
+       syscall
+       /* NOTREACHED */
diff --git a/lib/nbsd_libc/arch/x86_64/gen/signbitl.c b/lib/nbsd_libc/arch/x86_64/gen/signbitl.c
new file mode 100644 (file)
index 0000000..7f9f2ed
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: signbitl.c,v 1.2 2008/04/28 20:22:58 martin Exp $      */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: signbitl.c,v 1.2 2008/04/28 20:22:58 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.6 signbit - determine whether the sign of an argument is negative
+ *          IEEE 754 compatible 80-bit extended-precision Intel 386 version
+ */
+int
+__signbitl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return (u.extu_ext.ext_sign == 1);
+}
diff --git a/lib/nbsd_libc/arch/x86_64/gen/swapcontext.S b/lib/nbsd_libc/arch/x86_64/gen/swapcontext.S
new file mode 100644 (file)
index 0000000..49744bf
--- /dev/null
@@ -0,0 +1,73 @@
+/*     $NetBSD: swapcontext.S,v 1.4 2007/04/12 12:33:26 pooka Exp $    */
+
+/*
+ * Copyright (c) 2003 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Frank van der Linden for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: swapcontext.S,v 1.4 2007/04/12 12:33:26 pooka Exp $")
+#endif /* LIBC_SCCS && !lint */
+
+/*
+ * 56 == offsetof(ucontext_t, uc_mcontext)
+ * 21 == _REG_RIP
+ * 24 == _REG_URSP
+ */
+
+ENTRY(swapcontext)
+       pushq   %rdi                            /* preserve oucp */
+       pushq   %rsi                            /* preserve ucp */
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(_getcontext))
+#else
+       call    _C_LABEL(_getcontext)
+#endif
+       popq    %rsi
+       popq    %rdi
+       testl   %eax,%eax
+       jnz     2f
+       movq    0(%rsp),%r11
+       movq    %r11,(56 + 21 * 8)(%rdi)
+       leaq    8(%rsp),%r11
+       movq    %r11,(56 + 24 * 8)(%rdi)
+       movq    %rsi,%rdi
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(setcontext))
+#else
+       call    _C_LABEL(setcontext)
+#endif
+2:
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/net/Makefile.inc b/lib/nbsd_libc/arch/x86_64/net/Makefile.inc
new file mode 100644 (file)
index 0000000..6c0eeab
--- /dev/null
@@ -0,0 +1,10 @@
+#      $NetBSD: Makefile.inc,v 1.3 2009/12/06 07:12:18 uebayasi Exp $
+
+# objects built from assembler sources (need lint stubs)
+# hton* and nto* functions provided by ../gen/byte_swap_*.S
+SRCS+=  
+
+LSRCS.x86_64.net=Lint_htonl.c Lint_htons.c Lint_ntohl.c Lint_ntohs.c
+LSRCS+=                ${LSRCS.x86_64.net}
+DPSRCS+=       ${LSRCS.x86_64.net}
+CLEANFILES+=   ${LSRCS.x86_64.net}
diff --git a/lib/nbsd_libc/arch/x86_64/stdlib/Makefile.inc b/lib/nbsd_libc/arch/x86_64/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..8737f1b
--- /dev/null
@@ -0,0 +1,5 @@
+#      $NetBSD: Makefile.inc,v 1.6 2009/08/11 17:30:43 dsl Exp $
+
+# objects built from assembler sources
+SRCS+= abs.S div.S labs.S ldiv.S
+NO_SRCS+= llabs.S imaxabs.S imaxdiv.S
diff --git a/lib/nbsd_libc/arch/x86_64/stdlib/abs.S b/lib/nbsd_libc/arch/x86_64/stdlib/abs.S
new file mode 100644 (file)
index 0000000..8a454dc
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: abs.S,v 1.2 2003/08/07 16:42:36 agc Exp $      */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)abs.s 5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: abs.S,v 1.2 2003/08/07 16:42:36 agc Exp $")
+#endif
+
+ENTRY(abs)
+       movl    %edi,%eax
+       testl   %eax,%eax
+       jns     1f
+       negl    %eax
+1:     ret
diff --git a/lib/nbsd_libc/arch/x86_64/stdlib/div.S b/lib/nbsd_libc/arch/x86_64/stdlib/div.S
new file mode 100644 (file)
index 0000000..5e98cc5
--- /dev/null
@@ -0,0 +1,19 @@
+/*     $NetBSD: div.S,v 1.1 2001/06/19 00:25:04 fvdl Exp $     */
+/*
+ * Written by Frank van der Linden (fvdl@wasabisystems.com)
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+RCSID("$NetBSD: div.S,v 1.1 2001/06/19 00:25:04 fvdl Exp $")
+#endif
+
+ENTRY(div)
+       movl    %edi, %eax
+       cltd
+       idivl   %esi
+       salq    $32, %rdx
+       orq     %rdx,%rax
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/stdlib/labs.S b/lib/nbsd_libc/arch/x86_64/stdlib/labs.S
new file mode 100644 (file)
index 0000000..ffc8f2b
--- /dev/null
@@ -0,0 +1,31 @@
+/*     $NetBSD: labs.S,v 1.2 2008/08/04 20:21:26 matt Exp $    */
+
+/*
+ * Written by Frank van der Linden (fvdl@wasabisystems.com)
+ * Public Domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: labs.S,v 1.2 2008/08/04 20:21:26 matt Exp $")
+#endif
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(imaxabs, _llabs)
+WEAK_ALIAS(llabs, _llabs)
+WEAK_ALIAS(labs, _labs)
+#endif
+
+#ifdef WEAK_ALIAS
+ENTRY(_llabs)
+ENTRY(_labs)
+#else
+ENTRY(llabs)
+ENTRY(labs)
+#endif
+        movq    %rdi,%rax
+        testq   %rax,%rax
+        jns     1f
+        negq    %rax
+1:      ret
diff --git a/lib/nbsd_libc/arch/x86_64/stdlib/ldiv.S b/lib/nbsd_libc/arch/x86_64/stdlib/ldiv.S
new file mode 100644 (file)
index 0000000..ba62fdf
--- /dev/null
@@ -0,0 +1,26 @@
+/*     $NetBSD: ldiv.S,v 1.2 2008/08/04 20:26:38 matt Exp $    */
+
+/*
+ * Written by gcc 3.0.
+ * Copy/pasted by Frank van der Linden (fvdl@wasabisystems.com)
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: ldiv.S,v 1.2 2008/08/04 20:26:38 matt Exp $")
+#endif
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(ldiv, _ldiv)
+#endif
+
+#ifdef WEAK_ALIAS
+ENTRY(_ldiv)
+#else
+ENTRY(ldiv)
+#endif
+       movq    %rdi, %rax
+       cqto
+       idivq   %rsi
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/string/Makefile.inc b/lib/nbsd_libc/arch/x86_64/string/Makefile.inc
new file mode 100644 (file)
index 0000000..ba5d077
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.4 2009/07/30 20:57:17 dsl Exp $
+
+# objects built from assembler sources
+SRCS+= bcmp.S bcopy.S bzero.S ffs.S memchr.S memcmp.S \
+       memcpy.S memmove.S memset.S strcat.S strchr.S \
+       strcmp.S strcpy.S strlen.S strncmp.S strrchr.S swab.S
diff --git a/lib/nbsd_libc/arch/x86_64/string/strncmp.S b/lib/nbsd_libc/arch/x86_64/string/strncmp.S
new file mode 100644 (file)
index 0000000..7e1db10
--- /dev/null
@@ -0,0 +1,107 @@
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+        RCSID("$NetBSD: strncmp.S,v 1.3 2005/08/03 22:59:50 rpaulo Exp $")
+#endif
+
+/*
+ * NOTE: I've unrolled the loop eight times: large enough to make a
+ * significant difference, and small enough not to totally trash the
+ * cache.
+ */
+
+ENTRY(strncmp)
+       testq   %rdx,%rdx
+       jmp     L2                      /* Jump into the loop! */
+
+L1:    incq    %rdi
+       incq    %rsi
+       decq    %rdx
+L2:    jz      L4                      /* strings are equal */
+       movb    (%rdi),%al
+       testb   %al,%al
+       jz      L3
+       cmpb    %al,(%rsi)
+       jne     L3
+
+       incq    %rdi
+       incq    %rsi
+       decq    %rdx
+       jz      L4
+       movb    (%rdi),%al
+       testb   %al,%al
+       jz      L3
+       cmpb    %al,(%rsi)
+       jne     L3
+
+       incq    %rdi
+       incq    %rsi
+       decq    %rdx
+       jz      L4
+       movb    (%rdi),%al
+       testb   %al,%al
+       jz      L3
+       cmpb    %al,(%rsi)
+       jne     L3
+
+       incq    %rdi
+       incq    %rsi
+       decq    %rdx
+       jz      L4
+       movb    (%rdi),%al
+       testb   %al,%al
+       jz      L3
+       cmpb    %al,(%rsi)
+       jne     L3
+
+       incq    %rdi
+       incq    %rsi
+       decq    %rdx
+       jz      L4
+       movb    (%rdi),%al
+       testb   %al,%al
+       jz      L3
+       cmpb    %al,(%rsi)
+       jne     L3
+
+       incq    %rdi
+       incq    %rsi
+       decq    %rdx
+       jz      L4
+       movb    (%rdi),%al
+       testb   %al,%al
+       jz      L3
+       cmpb    %al,(%rsi)
+       jne     L3
+
+       incq    %rdi
+       incq    %rsi
+       decq    %rdx
+       jz      L4
+       movb    (%rdi),%al
+       testb   %al,%al
+       jz      L3
+       cmpb    %al,(%rsi)
+       jne     L3
+
+       incq    %rdi
+       incq    %rsi
+       decq    %rdx
+       jz      L4
+       movb    (%rdi),%al
+       testb   %al,%al
+       jz      L3
+       cmpb    %al,(%rsi)
+       je      L1
+
+L3:    movzbl  (%rdi),%eax             /* unsigned comparison */
+       movzbl  (%rsi),%ecx
+       subl    %ecx,%eax
+       ret
+L4:    xorl    %eax,%eax
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/string/swab.S b/lib/nbsd_libc/arch/x86_64/string/swab.S
new file mode 100644 (file)
index 0000000..a9012d8
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: swab.S,v 1.3 2005/08/02 14:20:49 rpaulo Exp $")
+#endif
+
+#define LOAD_SWAP_STORE_WORD \
+       lodsw   ; \
+       xchgb   %al,%ah ; \
+       stosw
+
+ENTRY(swab)
+       xchgq   %rdi,%rsi
+       cld                             # set direction forward
+
+       shrq    $1,%rdx
+       testq   $7,%rdx                 # copy first group of 1 to 7 words
+       jz      L2                      # while swapping alternate bytes.
+L1:    lodsw
+       rorw    $8,%ax
+       stosw
+       decq    %rdx
+       testq   $7,%rdx
+       jnz     L1
+
+L2:    shrq    $3,%rdx                 # copy remainder 8 words at a time
+       jz      L4                      # while swapping alternate bytes.
+L3:
+       LOAD_SWAP_STORE_WORD
+       LOAD_SWAP_STORE_WORD
+       LOAD_SWAP_STORE_WORD
+       LOAD_SWAP_STORE_WORD
+       LOAD_SWAP_STORE_WORD
+       LOAD_SWAP_STORE_WORD
+       LOAD_SWAP_STORE_WORD
+       LOAD_SWAP_STORE_WORD
+
+       decq    %rdx
+       jnz     L3
+L4:
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/sys/__clone.S b/lib/nbsd_libc/arch/x86_64/sys/__clone.S
new file mode 100644 (file)
index 0000000..76d6874
--- /dev/null
@@ -0,0 +1,101 @@
+/*     $NetBSD: __clone.S,v 1.2 2002/06/06 20:51:17 fvdl Exp $ */
+
+/*
+ * Copyright (c) 2002 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Frank van der Linden for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 <machine/asm.h>
+#include <sys/errno.h>
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(clone, __clone)
+#endif
+       .text
+
+/*
+ * int clone(int (*fn)(void *), void *stack, int flags, void *arg);
+ */
+ENTRY(__clone)
+       pushq   %r12
+       pushq   %r13
+       /*
+        * Sanity checks: func and stack may not be NULL.
+        */
+       testq   %rdi,%rdi
+       je      3f
+       testq   %rsi,%rsi
+       je      3f
+
+
+       movq    %rdi,%r12
+       movq    %rcx,%r13
+
+       movq    %rdx,%rdi
+
+       pushq   $0              /* dummy return address */
+
+       SYSTRAP(__clone)
+       jc      4f
+       cmpl    $0,%eax
+       jne     2f              /* we're the parent */
+       movq    %r13,%rdi       /* restore argument */
+       call    *%r12           /* this is the clone, call the function */
+
+       movq    %rax,%rdi
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(_exit))
+#else
+       call    _C_LABEL(_exit)
+#endif
+
+2:
+       addq    $8,%rsp
+       popq    %r13
+       popq    %r12
+       ret
+3:
+       movl    $EINVAL,%eax
+       jmp     5f
+4:
+       addq    $8,%rsp
+5:
+       popq    %r13
+       popq    %r12
+#ifdef PIC
+       movq    PIC_GOT(CERROR),%rdx
+       jmp     *%rdx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/x86_64/sys/__sigaction14_sigtramp.c b/lib/nbsd_libc/arch/x86_64/sys/__sigaction14_sigtramp.c
new file mode 100644 (file)
index 0000000..fc022ff
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: __sigaction14_sigtramp.c,v 1.10 2008/04/28 20:22:58 martin Exp $       */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __sigaction14_sigtramp.c,v 1.10 2008/04/28 20:22:58 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "extern.h"
+
+ __weak_alias(__sigaction14, __libc_sigaction14)
+
+int
+__libc_sigaction14(int sig, const struct sigaction *act, struct sigaction *oact)
+{
+       extern const int __sigtramp_siginfo_2[];
+
+#if 0
+       /*
+        * If no sigaction, use the "default" trampoline since it won't
+        * be used.
+        */
+       if (act == NULL)
+               return  __sigaction_sigtramp(sig, act, oact, NULL, 0);
+#endif
+
+       /*
+        * Don't provide sigcontext compatibility,
+        * always use the siginfo trampoline.
+        */
+       return __sigaction_sigtramp(sig, act, oact, __sigtramp_siginfo_2, 2);
+}
diff --git a/lib/nbsd_libc/arch/x86_64/sys/__sigtramp2.S b/lib/nbsd_libc/arch/x86_64/sys/__sigtramp2.S
new file mode 100644 (file)
index 0000000..e0489cc
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: __sigtramp2.S,v 1.5 2006/11/08 21:16:40 drochner Exp $ */
+
+/*
+ * Copyright (c) 2001 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Frank van der Linden for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 "SYS.h"
+
+/*
+ * The x86-64 signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ */
+NENTRY(__sigtramp_siginfo_2)
+       movq    %r15,%rdi
+       movq    $SYS_setcontext, %rax
+       syscall
+       movq    $-1,%rdi /* if we return here, something is wrong */
+       movq    $SYS_exit, %rax
+       syscall
diff --git a/lib/nbsd_libc/arch/x86_64/sys/__syscall.S b/lib/nbsd_libc/arch/x86_64/sys/__syscall.S
new file mode 100644 (file)
index 0000000..9550377
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: __syscall.S,v 1.2 2003/08/07 16:42:37 agc Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)syscall.s     5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __syscall.S,v 1.2 2003/08/07 16:42:37 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+RSYSCALL(__syscall)
diff --git a/lib/nbsd_libc/arch/x86_64/sys/__vfork14.S b/lib/nbsd_libc/arch/x86_64/sys/__vfork14.S
new file mode 100644 (file)
index 0000000..bbd6821
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: __vfork14.S,v 1.3 2003/08/07 16:42:37 agc Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)Ovfork.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: __vfork14.S,v 1.3 2003/08/07 16:42:37 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+/*
+ * pid = vfork();
+ *
+ * %edx == 0 in parent process, %edx == 1 in child process.
+ * %eax == pid of child in parent, %eax == pid of parent in child.
+ *
+ */
+ENTRY(__vfork14)
+       popq    %r9             /* my rta into r9 */
+       SYSTRAP(__vfork14)
+       jc      err
+       decl    %edx
+       andl    %edx,%eax
+       jmp     *%r9
+err:
+       pushq   %r9
+#ifdef PIC
+       movq    PIC_GOT(CERROR), %rcx
+       jmp     *%rcx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/x86_64/sys/brk.S b/lib/nbsd_libc/arch/x86_64/sys/brk.S
new file mode 100644 (file)
index 0000000..7d969e9
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: brk.S,v 1.3 2003/08/07 16:42:37 agc Exp $      */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)brk.s 5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: brk.S,v 1.3 2003/08/07 16:42:37 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _end
+       .globl  _C_LABEL(__minbrk)
+       .globl  CURBRK
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(brk, _brk)
+#endif
+
+       .data
+_C_LABEL(__minbrk):
+       .quad   _end
+       .text
+
+ENTRY(_brk)
+#ifdef PIC
+       movq    PIC_GOT(_C_LABEL(__minbrk)),%rdx
+       cmpq    %rdi,(%rdx)
+       jb      1f
+       movq    (%rdx),%rdi
+1:
+       SYSTRAP(break)
+       jc      err
+       movq    PIC_GOT(CURBRK),%rdx    # set up GOT addressing
+       movq    %rdi,(%rdx)
+       xorl    %eax,%eax
+       ret
+err:
+       movq    PIC_GOT(CERROR),%rdx
+       jmp     *%rdx
+#else
+       cmpq    %rdi,_C_LABEL(__minbrk)(%rip)
+       jb      1f
+       movq    _C_LABEL(__minbrk)(%rip),%rdi
+1:
+       SYSTRAP(break)
+       jc      err
+       movq    %rdi,CURBRK(%rip)
+       xorl    %eax,%eax
+       ret
+err:
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/x86_64/sys/cerror.S b/lib/nbsd_libc/arch/x86_64/sys/cerror.S
new file mode 100644 (file)
index 0000000..6c06fa4
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: cerror.S,v 1.3 2003/08/07 16:42:37 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)cerror.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: cerror.S,v 1.3 2003/08/07 16:42:37 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _C_LABEL(__errno)
+
+_ENTRY(CERROR)
+       pushq   %r12
+       movl    %eax,%edi
+       movl    %eax,%r12d
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(__errno))
+#else
+       call    _C_LABEL(__errno)
+#endif /* PIC */
+       movl    %r12d,(%rax)
+       movq    $-1,%rax
+       popq    %r12
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/sys/exect.S b/lib/nbsd_libc/arch/x86_64/sys/exect.S
new file mode 100644 (file)
index 0000000..9f32e5e
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: exect.S,v 1.2 2003/08/07 16:42:37 agc Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)exect.s       5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: exect.S,v 1.2 2003/08/07 16:42:37 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+#include <machine/psl.h>
+
+ENTRY(exect)
+       pushfq
+       orb     $(PSL_T>>8),1(%rsp)
+       popfq
+       SYSTRAP(execve)
+#ifdef PIC
+       movq    PIC_GOT(CERROR), %rcx
+       jmp     *%rcx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/x86_64/sys/fork.S b/lib/nbsd_libc/arch/x86_64/sys/fork.S
new file mode 100644 (file)
index 0000000..00a64c4
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: fork.S,v 1.3 2003/08/07 16:42:37 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)fork.s        5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: fork.S,v 1.3 2003/08/07 16:42:37 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+_SYSCALL(__fork,fork)
+       decl    %edx    /* from 1 to 0 in child, 0 to -1 in parent */
+       andl    %edx,%eax
+       ret             /* pid = fork(); */
diff --git a/lib/nbsd_libc/arch/x86_64/sys/getcontext.S b/lib/nbsd_libc/arch/x86_64/sys/getcontext.S
new file mode 100644 (file)
index 0000000..bb5ea32
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: getcontext.S,v 1.3 2004/03/09 20:21:22 drochner Exp $  */
+
+/*
+ * Copyright (c) 2003 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Frank van der Linden for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project by
+ *      Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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 "SYS.h"
+
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: getcontext.S,v 1.3 2004/03/09 20:21:22 drochner Exp $")
+#endif
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(getcontext, _getcontext)
+#endif
+
+/*
+ * 56 == offsetof(ucontext_t, uc_mcontext)
+ * 14 == _REG_RAX
+ * 21 == _REG_RIP
+ * 24 == _REG_URSP
+ */
+
+_SYSCALL(_getcontext,getcontext)
+       movq    (%rsp),%r11
+       movq    %r11,(56 + 21 * 8)(%rdi)
+       leaq    8(%rsp),%r11
+       movq    %r11,(56 + 24 * 8)(%rdi)
+       movq    $0,(56 + 14 * 8)(%rdi)
+       xorl    %eax,%eax
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/sys/pipe.S b/lib/nbsd_libc/arch/x86_64/sys/pipe.S
new file mode 100644 (file)
index 0000000..0d21c4e
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: pipe.S,v 1.2 2003/08/07 16:42:37 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)pipe.s        5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: pipe.S,v 1.2 2003/08/07 16:42:37 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(pipe, _pipe)
+#endif
+
+_SYSCALL(_pipe,pipe)
+       movl    %eax,(%rdi)
+       movl    %edx,4(%rdi)
+       xorl    %eax,%eax
+       ret
diff --git a/lib/nbsd_libc/arch/x86_64/sys/ptrace.S b/lib/nbsd_libc/arch/x86_64/sys/ptrace.S
new file mode 100644 (file)
index 0000000..8b7cc33
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: ptrace.S,v 1.2 2003/08/07 16:42:37 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)ptrace.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: ptrace.S,v 1.2 2003/08/07 16:42:37 agc Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _C_LABEL(__errno)
+
+ENTRY(ptrace)
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(__errno))
+#else
+       call    _C_LABEL(__errno)
+#endif /* PIC */
+       movl    $0,(%rax)
+       SYSTRAP(ptrace)
+       jc      err
+       ret
+err:
+#ifdef PIC
+       movq    PIC_GOT(CERROR), %rcx
+       jmp     *%rcx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/x86_64/sys/sbrk.S b/lib/nbsd_libc/arch/x86_64/sys/sbrk.S
new file mode 100644 (file)
index 0000000..65c3362
--- /dev/null
@@ -0,0 +1,86 @@
+/*     $NetBSD: sbrk.S,v 1.3 2008/07/02 20:07:43 rmind Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sbrk.s        5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: sbrk.S,v 1.3 2008/07/02 20:07:43 rmind Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+       .globl  _end
+       .globl  CURBRK
+
+#ifdef WEAK_ALIAS
+WEAK_ALIAS(sbrk, _sbrk)
+#endif
+
+       .data
+CURBRK:        .quad   _end
+       .text
+
+ENTRY(_sbrk)
+#ifdef PIC
+       movq    PIC_GOT(CURBRK),%rdx
+       movq    (%rdx),%rax
+       test    %rdi,%rdi
+       jz      out
+       addq    %rax,%rdi
+       SYSTRAP(break)
+       jc      err
+       movq    PIC_GOT(CURBRK),%rdx
+       movq    (%rdx),%rax
+       movq    %rdi,(%rdx)
+out:
+       ret
+err:
+       mov     PIC_GOT(CERROR),%rdx
+       jmp     *%rdx
+#else
+       movq    CURBRK(%rip),%rax
+       test    %rdi,%rdi
+       jz      out
+       movq    %rdi,%rsi
+       addq    %rax,%rdi
+       SYSTRAP(break)
+       jc      err
+       movq    CURBRK(%rip),%rax
+       addq    %rsi,CURBRK(%rip)
+out:
+       ret
+err:
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/arch/x86_64/sys/shmat.S b/lib/nbsd_libc/arch/x86_64/sys/shmat.S
new file mode 100644 (file)
index 0000000..2c81105
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: shmat.S,v 1.1 2001/06/19 00:25:06 fvdl Exp $   */
+
+#include "SYS.h"
+
+RSYSCALL(shmat)
diff --git a/lib/nbsd_libc/arch/x86_64/sys/syscall.S b/lib/nbsd_libc/arch/x86_64/sys/syscall.S
new file mode 100644 (file)
index 0000000..e802b61
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: syscall.S,v 1.4 2007/11/05 20:30:07 dsl Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)syscall.s     5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: syscall.S,v 1.4 2007/11/05 20:30:07 dsl Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+RSYSCALL(syscall)
diff --git a/lib/nbsd_libc/atomic/Makefile.inc b/lib/nbsd_libc/atomic/Makefile.inc
new file mode 100644 (file)
index 0000000..80951a7
--- /dev/null
@@ -0,0 +1,76 @@
+#      $NetBSD: Makefile.inc,v 1.2 2010/02/12 22:34:38 dyoung Exp $
+#      from: @(#)Makefile.inc  8.6 (Berkeley) 5/4/95
+
+# gen sources
+.PATH: ${.CURDIR}/atomic
+
+MAN+=  atomic_add.3 atomic_and.3 atomic_cas.3 atomic_dec.3 \
+       atomic_inc.3 atomic_ops.3 atomic_or.3 atomic_swap.3 \
+       membar_ops.3
+
+MLINKS+=atomic_add.3 atomic_add_32.3 \
+       atomic_add.3 atomic_add_int.3 \
+       atomic_add.3 atomic_add_long.3 \
+       atomic_add.3 atomic_add_ptr.3 \
+       atomic_add.3 atomic_add_64.3 \
+       atomic_add.3 atomic_add_32_nv.3 \
+       atomic_add.3 atomic_add_int_nv.3 \
+       atomic_add.3 atomic_add_long_nv.3 \
+       atomic_add.3 atomic_add_ptr_nv.3 \
+       atomic_add.3 atomic_add_64_nv.3 \
+       atomic_and.3 atomic_and_32.3 \
+       atomic_and.3 atomic_and_uint.3 \
+       atomic_and.3 atomic_and_ulong.3 \
+       atomic_and.3 atomic_and_64.3 \
+       atomic_and.3 atomic_and_32_nv.3 \
+       atomic_and.3 atomic_and_uint_nv.3 \
+       atomic_and.3 atomic_and_ulong_nv.3 \
+       atomic_and.3 atomic_and_64_nv.3 \
+       atomic_cas.3 atomic_cas_32.3 \
+       atomic_cas.3 atomic_cas_uint.3 \
+       atomic_cas.3 atomic_cas_ulong.3 \
+       atomic_cas.3 atomic_cas_ptr.3 \
+       atomic_cas.3 atomic_cas_64.3 \
+       atomic_cas.3 atomic_cas_32_ni.3 \
+       atomic_cas.3 atomic_cas_uint_ni.3 \
+       atomic_cas.3 atomic_cas_ulong_ni.3 \
+       atomic_cas.3 atomic_cas_ptr_ni.3 \
+       atomic_cas.3 atomic_cas_64_ni.3 \
+       atomic_dec.3 atomic_dec_32.3 \
+       atomic_dec.3 atomic_dec_uint.3 \
+       atomic_dec.3 atomic_dec_ulong.3 \
+       atomic_dec.3 atomic_dec_ptr.3 \
+       atomic_dec.3 atomic_dec_64.3 \
+       atomic_dec.3 atomic_dec_32_nv.3 \
+       atomic_dec.3 atomic_dec_uint_nv.3 \
+       atomic_dec.3 atomic_dec_ulong_nv.3 \
+       atomic_dec.3 atomic_dec_ptr_nv.3 \
+       atomic_dec.3 atomic_dec_64_nv.3 \
+       atomic_inc.3 atomic_inc_32.3 \
+       atomic_inc.3 atomic_inc_uint.3 \
+       atomic_inc.3 atomic_inc_ulong.3 \
+       atomic_inc.3 atomic_inc_ptr.3 \
+       atomic_inc.3 atomic_inc_64.3 \
+       atomic_inc.3 atomic_inc_32_nv.3 \
+       atomic_inc.3 atomic_inc_uint_nv.3 \
+       atomic_inc.3 atomic_inc_ulong_nv.3 \
+       atomic_inc.3 atomic_inc_ptr_nv.3 \
+       atomic_inc.3 atomic_inc_64_nv.3 \
+       atomic_or.3 atomic_or_32.3 \
+       atomic_or.3 atomic_or_uint.3 \
+       atomic_or.3 atomic_or_ulong.3 \
+       atomic_or.3 atomic_or_64.3 \
+       atomic_or.3 atomic_or_32_nv.3 \
+       atomic_or.3 atomic_or_uint_nv.3 \
+       atomic_or.3 atomic_or_ulong_nv.3 \
+       atomic_or.3 atomic_or_64_nv.3 \
+       atomic_swap.3 atomic_swap_32.3 \
+       atomic_swap.3 atomic_swap_uint.3 \
+       atomic_swap.3 atomic_swap_ulong.3 \
+       atomic_swap.3 atomic_swap_ptr.3 \
+       atomic_swap.3 atomic_swap_64.3 \
+       membar_ops.3 membar_enter.3 \
+       membar_ops.3 membar_exit.3 \
+       membar_ops.3 membar_producer.3 \
+       membar_ops.3 membar_consumer.3 \
+       membar_ops.3 membar_sync.3
diff --git a/lib/nbsd_libc/atomic/atomic_add.3 b/lib/nbsd_libc/atomic/atomic_add.3
new file mode 100644 (file)
index 0000000..b6f8adb
--- /dev/null
@@ -0,0 +1,95 @@
+.\"    $NetBSD: atomic_add.3,v 1.1 2008/06/23 10:22:40 ad Exp $
+.\"
+.\" Copyright (c) 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 11, 2007
+.Dt ATOMIC_ADD 3
+.Os
+.Sh NAME
+.Nm atomic_add ,
+.Nm atomic_add_32 ,
+.Nm atomic_add_int ,
+.Nm atomic_add_long ,
+.Nm atomic_add_ptr ,
+.Nm atomic_add_64 ,
+.Nm atomic_add_32_nv ,
+.Nm atomic_add_int_nv ,
+.Nm atomic_add_long_nv ,
+.Nm atomic_add_ptr_nv ,
+.Nm atomic_add_64_nv
+.Nd atomic add operations
+.\" .Sh LIBRARY
+.\" .Lb libc
+.Sh SYNOPSIS
+.In sys/atomic.h
+.Ft void
+.Fn atomic_add_32 "volatile uint32_t *ptr" "int32_t delta"
+.Ft void
+.Fn atomic_add_int "volatile unsigned int *ptr" "int delta"
+.Ft void
+.Fn atomic_add_long "volatile unsigned long *ptr" "long delta"
+.Ft void
+.Fn atomic_add_ptr "volatile void *ptr" "ssize_t delta"
+.Ft void
+.Fn atomic_add_64 "volatile uint64_t *ptr" "int64_t delta"
+.Ft uint32_t
+.Fn atomic_add_32_nv "volatile uint32_t *ptr" "int32_t delta"
+.Ft unsigned int
+.Fn atomic_add_int_nv "volatile unsigned int *ptr" "int delta"
+.Ft unsigned long
+.Fn atomic_add_long_nv "volatile unsigned long *ptr" "long delta"
+.Ft void *
+.Fn atomic_add_ptr_nv "volatile void *ptr" "ssize_t delta"
+.Ft uint64_t
+.Fn atomic_add_64_nv "volatile uint64_t *ptr" "int64_t delta"
+.Sh DESCRIPTION
+The
+.Nm atomic_add
+family of functions add a signed value
+.Fa delta
+to the variable referenced by
+.Fa ptr
+in an atomic fashion.
+.Pp
+The
+.Fn *_nv
+variants of these functions return the new value.
+.Pp
+The 64-bit variants of these functions are available only on platforms
+that can support atomic 64-bit memory access.
+Applications can check for the availability of 64-bit atomic memory
+operations by testing if the pre-processor macro
+.Dv __HAVE_ATOMIC64_OPS
+is defined.
+.Sh SEE ALSO
+.Xr atomic_ops 3
+.Sh HISTORY
+The
+.Nm atomic_add
+functions first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/atomic/atomic_and.3 b/lib/nbsd_libc/atomic/atomic_and.3
new file mode 100644 (file)
index 0000000..7f5ed50
--- /dev/null
@@ -0,0 +1,95 @@
+.\"    $NetBSD: atomic_and.3,v 1.1 2008/06/23 10:22:40 ad Exp $
+.\"
+.\" Copyright (c) 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 11, 2007
+.Dt ATOMIC_AND 3
+.Os
+.Sh NAME
+.Nm atomic_and ,
+.Nm atomic_and_32 ,
+.Nm atomic_and_uint ,
+.Nm atomic_and_ulong ,
+.Nm atomic_and_64 ,
+.Nm atomic_and_32_nv ,
+.Nm atomic_and_uint_nv ,
+.Nm atomic_and_ulong_nv ,
+.Nm atomic_and_64_nv
+.Nd atomic logical
+.Sq and
+operations
+.\" .Sh LIBRARY
+.\" .Lb libc
+.Sh SYNOPSIS
+.In sys/atomic.h
+.Ft void
+.Fn atomic_and_32 "volatile uint32_t *ptr" "uint32_t bits"
+.Ft void
+.Fn atomic_and_uint "volatile unsigned int *ptr" "unsigned int bits"
+.Ft void
+.Fn atomic_and_ulong "volatile unsigned long *ptr" "unsigned long bits"
+.Ft void
+.Fn atomic_and_64 "volatile uint64_t *ptr" "uint64_t bits"
+.Ft uint32_t
+.Fn atomic_and_32_nv "volatile uint32_t *ptr" "uint32_t bits"
+.Ft unsigned int
+.Fn atomic_and_uint_nv "volatile unsigned int *ptr" "unsigned int bits"
+.Ft unsigned long
+.Fn atomic_and_ulong_nv "volatile unsigned long *ptr" "unsigned long bits"
+.Ft uint64_t
+.Fn atomic_and_64_nv "volatile uint64_t *ptr" "uint64_t bits"
+.Sh DESCRIPTION
+The
+.Nm atomic_and
+family of functions load the value of the variable referenced by
+.Fa ptr ,
+perform a logical
+.Sq and
+with the value
+.Fa bits ,
+and store the result back to the variable referenced by
+.Fa ptr
+in an atomic fashion.
+.Pp
+The
+.Fn *_nv
+variants of these functions return the new value.
+.Pp
+The 64-bit variants of these functions are available only on platforms
+that can support atomic 64-bit memory access.
+Applications can check for the availability of 64-bit atomic memory
+operations by testing if the pre-processor macro
+.Dv __HAVE_ATOMIC64_OPS
+is defined.
+.Sh SEE ALSO
+.Xr atomic_ops 3
+.Sh HISTORY
+The
+.Nm atomic_and
+functions first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/atomic/atomic_cas.3 b/lib/nbsd_libc/atomic/atomic_cas.3
new file mode 100644 (file)
index 0000000..06804b7
--- /dev/null
@@ -0,0 +1,129 @@
+.\"    $NetBSD: atomic_cas.3,v 1.2 2010/02/12 22:23:17 dyoung Exp $
+.\"
+.\" Copyright (c) 2007, 2010 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd February 11, 2010
+.Dt ATOMIC_CAS 3
+.Os
+.Sh NAME
+.Nm atomic_cas ,
+.Nm atomic_cas_32 ,
+.Nm atomic_cas_uint ,
+.Nm atomic_cas_ulong ,
+.Nm atomic_cas_ptr ,
+.Nm atomic_cas_64 ,
+.Nm atomic_cas_32_ni ,
+.Nm atomic_cas_uint_ni ,
+.Nm atomic_cas_ulong_ni ,
+.Nm atomic_cas_ptr_ni ,
+.Nm atomic_cas_64_ni
+.Nd atomic compare-and-swap operations
+.\" .Sh LIBRARY
+.\" .Lb libc
+.Sh SYNOPSIS
+.In sys/atomic.h
+.Ft uint32_t
+.Fn atomic_cas_32 "volatile uint32_t *ptr" "uint32_t old" "uint32_t new"
+.Ft unsigned int
+.Fn atomic_cas_uint "volatile unsigned int *ptr" "unsigned int old" \
+    "unsigned int new"
+.Ft unsigned long
+.Fn atomic_cas_ulong "volatile unsigned long *ptr" "unsigned long old" \
+    "unsigned long new"
+.Ft void *
+.Fn atomic_cas_ptr "volatile void *ptr" "void *old" "void *new"
+.Ft uint64_t
+.Fn atomic_cas_64 "volatile uint64_t *ptr" "uint64_t old" "uint64_t new"
+.Ft uint32_t
+.Fn atomic_cas_32_ni "volatile uint32_t *ptr" "uint32_t old" "uint32_t new"
+.Ft unsigned int
+.Fn atomic_cas_uint_ni "volatile unsigned int *ptr" "unsigned int old" \
+    "unsigned int new"
+.Ft unsigned long
+.Fn atomic_cas_ulong_ni "volatile unsigned long *ptr" "unsigned long old" \
+    "unsigned long new"
+.Ft void *
+.Fn atomic_cas_ptr_ni "volatile void *ptr" "void *old" "void *new"
+.Ft uint64_t
+.Fn atomic_cas_64_ni "volatile uint64_t *ptr" "uint64_t old" "uint64_t new"
+.Sh DESCRIPTION
+The
+.Nm atomic_cas
+family of functions perform a compare-and-swap operation in an atomic fashion.
+The value of the variable referenced by
+.Fa ptr
+is compared against
+.Fa old .
+If the values are equal,
+.Fa new
+is stored in the variable referenced by
+.Fa ptr .
+.Pp
+The old value of the variable referenced by
+.Fa ptr
+is always returned regardless of whether or not the new value was stored.
+Applications can test for success of the operation by comparing the
+return value to the value passed as
+.Fa old ;
+if they are equal then the new value was stored.
+.Pp
+The non-interlocked variants,
+.Fn *_ni ,
+guarantee atomicity within the same CPU with respect to
+interrupts and preemption.
+For example, they are suitable for synchronizing compare-and-swap
+operations on a variable shared by a thread and an interrupt
+that are bound to the same CPU.
+The
+.Fn *_ni
+variants are not atomic with respect to different CPUs.
+.Fn *_ni
+variants should avoid the interprocessor synchronization overhead
+of the standard compare-and-swap operations.
+.Pp
+The 64-bit variants of these functions are available only on platforms
+that can support atomic 64-bit memory access.
+Applications can check for the availability of 64-bit atomic memory
+operations by testing if the pre-processor macro
+.Dv __HAVE_ATOMIC64_OPS
+is defined.
+.Sh SEE ALSO
+.Xr atomic_ops 3
+.Sh HISTORY
+The
+.Nm atomic_cas
+functions first appeared in
+.Nx 5.0 .
+.Sh NOTES
+On some architectures, a
+.Fn *_ni
+variant is merely an alias for the corresponding standard
+compare-and-swap operation.
+While the non-interlocked variant behaves correctly on those
+architectures, it does not avoid the interprocessor synchronization
+overhead.
diff --git a/lib/nbsd_libc/atomic/atomic_dec.3 b/lib/nbsd_libc/atomic/atomic_dec.3
new file mode 100644 (file)
index 0000000..654ed24
--- /dev/null
@@ -0,0 +1,95 @@
+.\"    $NetBSD: atomic_dec.3,v 1.1 2008/06/23 10:22:40 ad Exp $
+.\"
+.\" Copyright (c) 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 11, 2007
+.Dt ATOMIC_DEC 3
+.Os
+.Sh NAME
+.Nm atomic_dec ,
+.Nm atomic_dec_32 ,
+.Nm atomic_dec_uint ,
+.Nm atomic_dec_ulong ,
+.Nm atomic_dec_ptr ,
+.Nm atomic_dec_64 ,
+.Nm atomic_dec_32_nv ,
+.Nm atomic_dec_uint_nv ,
+.Nm atomic_dec_ulong_nv ,
+.Nm atomic_dec_ptr_nv ,
+.Nm atomic_dec_64_nv
+.Nd atomic decrement operations
+.\" .Sh LIBRARY
+.\" .Lb libc
+.Sh SYNOPSIS
+.In sys/atomic.h
+.Ft void
+.Fn atomic_dec_32 "volatile uint32_t *ptr"
+.Ft void
+.Fn atomic_dec_uint "volatile unsigned int *ptr"
+.Ft void
+.Fn atomic_dec_ulong "volatile unsigned long *ptr"
+.Ft void
+.Fn atomic_dec_ptr "volatile void *ptr"
+.Ft void
+.Fn atomic_dec_64 "volatile uint64_t *ptr"
+.Ft uint32_t
+.Fn atomic_dec_32_nv "volatile uint32_t *ptr"
+.Ft unsigned int
+.Fn atomic_dec_uint_nv "volatile unsigned int *ptr"
+.Ft unsigned long
+.Fn atomic_dec_ulong_nv "volatile unsigned long *ptr"
+.Ft void *
+.Fn atomic_dec_ptr_nv "volatile void *ptr"
+.Ft uint64_t
+.Fn atomic_dec_64_nv "volatile uint64_t *ptr"
+.Sh DESCRIPTION
+The
+.Nm atomic_dec
+family of functions decrement
+.Pq by one
+the variable referenced by
+.Fa ptr
+in an atomic fashion.
+.Pp
+The
+.Fn *_nv
+variants of these functions return the new value.
+.Pp
+The 64-bit variants of these functions are available only on platforms
+that can support atomic 64-bit memory access.
+Applications can check for the availability of 64-bit atomic memory
+operations by testing if the pre-processor macro
+.Dv __HAVE_ATOMIC64_OPS
+is defined.
+.Sh SEE ALSO
+.Xr atomic_ops 3
+.Sh HISTORY
+The
+.Nm atomic_dec
+functions first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/atomic/atomic_inc.3 b/lib/nbsd_libc/atomic/atomic_inc.3
new file mode 100644 (file)
index 0000000..a03429e
--- /dev/null
@@ -0,0 +1,95 @@
+.\"    $NetBSD: atomic_inc.3,v 1.1 2008/06/23 10:22:40 ad Exp $
+.\"
+.\" Copyright (c) 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 11, 2007
+.Dt ATOMIC_INC 3
+.Os
+.Sh NAME
+.Nm atomic_inc ,
+.Nm atomic_inc_32 ,
+.Nm atomic_inc_uint ,
+.Nm atomic_inc_ulong ,
+.Nm atomic_inc_ptr ,
+.Nm atomic_inc_64 ,
+.Nm atomic_inc_32_nv ,
+.Nm atomic_inc_uint_nv ,
+.Nm atomic_inc_ulong_nv ,
+.Nm atomic_inc_ptr_nv ,
+.Nm atomic_inc_64_nv
+.Nd atomic increment operations
+.\" .Sh LIBRARY
+.\" .Lb libc
+.Sh SYNOPSIS
+.In sys/atomic.h
+.Ft void
+.Fn atomic_inc_32 "volatile uint32_t *ptr"
+.Ft void
+.Fn atomic_inc_uint "volatile unsigned int *ptr"
+.Ft void
+.Fn atomic_inc_ulong "volatile unsigned long *ptr"
+.Ft void
+.Fn atomic_inc_ptr "volatile void *ptr"
+.Ft void
+.Fn atomic_inc_64 "volatile uint64_t *ptr"
+.Ft uint32_t
+.Fn atomic_inc_32_nv "volatile uint32_t *ptr"
+.Ft unsigned int
+.Fn atomic_inc_uint_nv "volatile unsigned int *ptr"
+.Ft unsigned long
+.Fn atomic_inc_ulong_nv "volatile unsigned long *ptr"
+.Ft void *
+.Fn atomic_inc_ptr_nv "volatile void *ptr"
+.Ft uint64_t
+.Fn atomic_inc_64_nv "volatile uint64_t *ptr"
+.Sh DESCRIPTION
+The
+.Nm atomic_inc
+family of functions increment
+.Pq by one
+the variable referenced by
+.Fa ptr
+in an atomic fashion.
+.Pp
+The
+.Fn *_nv
+variants of these functions return the new value.
+.Pp
+The 64-bit variants of these functions are available only on platforms
+that can support atomic 64-bit memory access.
+Applications can check for the availability of 64-bit atomic memory
+operations by testing if the pre-processor macro
+.Dv __HAVE_ATOMIC64_OPS
+is defined.
+.Sh SEE ALSO
+.Xr atomic_ops 3
+.Sh HISTORY
+The
+.Nm atomic_inc
+functions first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/atomic/atomic_ops.3 b/lib/nbsd_libc/atomic/atomic_ops.3
new file mode 100644 (file)
index 0000000..77f6c72
--- /dev/null
@@ -0,0 +1,129 @@
+.\"    $NetBSD: atomic_ops.3,v 1.5 2010/04/14 08:49:49 jruoho Exp $
+.\"
+.\" Copyright (c) 2007, 2008 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 14, 2010
+.Dt ATOMIC_OPS 3
+.Os
+.Sh NAME
+.Nm atomic_ops
+.Nd atomic memory operations
+.\" .Sh LIBRARY
+.\" .Lb libc
+.Sh SYNOPSIS
+.In sys/atomic.h
+.Sh DESCRIPTION
+The
+.Nm atomic_ops
+family of functions provide atomic memory operations.
+There are 7 classes of atomic memory operations available:
+.Pp
+.Bl -tag -width "atomic_swap(3)" -offset indent
+.It Xr atomic_add 3
+These functions perform atomic addition.
+.It Xr atomic_and 3
+These functions perform atomic logical
+.Dq and .
+.It Xr atomic_cas 3
+These functions perform atomic compare-and-swap.
+.It Xr atomic_dec 3
+These functions perform atomic decrement.
+.It Xr atomic_inc 3
+These functions perform atomic increment.
+.It Xr atomic_or 3
+These functions perform atomic logical
+.Dq or .
+.It Xr atomic_swap 3
+These functions perform atomic swap.
+.El
+.Ss Synchronization Mechanisms
+Where the architecture does not provide hardware support for atomic compare
+and swap (CAS), atomicity is provided by a restartable sequence or by a
+spinlock.
+The chosen method is not ordinarily distinguishable by or visible to users
+of the interface.
+The following architectures can be assumed to provide CAS in hardware:
+alpha, amd64, i386, powerpc, powerpc64, sparc64.
+.Ss Scope and Restrictions
+If hardware CAS is available, the atomic operations are globally atomic:
+operations within a memory region shared between processes are
+guaranteed to be performed atomically.
+If hardware CAS is not available, it may only be assumed that the operations
+are atomic with respect to threads in the same process.
+Additionally, if hardware CAS is not available, the atomic operations must
+not be used within a signal handler.
+.Pp
+Users of atomic memory operations should not make assumptions about how
+the memory access is performed
+.Pq specifically, the width of the memory access .
+For this reason, applications making use of atomic memory operations should
+limit their use to regular memory.
+The results of using atomic memory operations on anything other than
+regular memory are undefined.
+.Pp
+Users of atomic memory operations should take care to modify any given
+memory location either entirely with atomic operations or entirely with
+some other synchronization mechanism.
+Intermixing of atomic operations with other synchronization mechanisms
+for the same memory location results in undefined behavior.
+.Ss Visibility and Ordering of Memory Accesses
+If hardware CAS is available, stores to the target memory location by an
+atomic operation will reach global visibility before the operation
+completes.
+If hardware CAS is not available, the store may not reach global visibility
+until some time after the atomic operation has completed.
+However, in all cases a subsequent atomic operation on the same memory cell
+will be delayed until the result of any preceeding operation has reached
+global visibility.
+.Pp
+Atomic operations are strongly ordered with respect to each other.
+The global visibility of other loads and stores before and after an atomic
+operation is undefined.
+Applications that require synchronization of loads and stores with respect
+to an atomic operation must use memory barriers.
+See
+.Xr membar_ops 3 .
+.Ss Performance
+Because atomic memory operations require expensive synchronization at the
+hardware level, applications should take care to minimize their use.
+In certain cases, it may be more appropriate to use a mutex, especially
+if more than one memory location will be modified.
+.Sh SEE ALSO
+.Xr atomic_add 3 ,
+.Xr atomic_and 3 ,
+.Xr atomic_cas 3 ,
+.Xr atomic_dec 3 ,
+.Xr atomic_inc 3 ,
+.Xr atomic_or 3 ,
+.Xr atomic_swap 3 ,
+.Xr membar_ops 3
+.Sh HISTORY
+The
+.Nm atomic_ops
+functions first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/atomic/atomic_or.3 b/lib/nbsd_libc/atomic/atomic_or.3
new file mode 100644 (file)
index 0000000..903f5b0
--- /dev/null
@@ -0,0 +1,95 @@
+.\"    $NetBSD: atomic_or.3,v 1.1 2008/06/23 10:22:40 ad Exp $
+.\"
+.\" Copyright (c) 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 11, 2007
+.Dt ATOMIC_OR 3
+.Os
+.Sh NAME
+.Nm atomic_or ,
+.Nm atomic_or_32 ,
+.Nm atomic_or_uint ,
+.Nm atomic_or_ulong ,
+.Nm atomic_or_64 ,
+.Nm atomic_or_32_nv ,
+.Nm atomic_or_uint_nv ,
+.Nm atomic_or_ulong_nv ,
+.Nm atomic_or_64_nv
+.Nd atomic logical
+.Sq or
+operations
+.\" .Sh LIBRARY
+.\" .Lb libc
+.Sh SYNOPSIS
+.In sys/atomic.h
+.Ft void
+.Fn atomic_or_32 "volatile uint32_t *ptr" "uint32_t bits"
+.Ft void
+.Fn atomic_or_uint "volatile unsigned int *ptr" "unsigned int bits"
+.Ft void
+.Fn atomic_or_ulong "volatile unsigned long *ptr" "unsigned long bits"
+.Ft void
+.Fn atomic_or_64 "volatile uint64_t *ptr" "uint64_t bits"
+.Ft uint32_t
+.Fn atomic_or_32_nv "volatile uint32_t *ptr" "uint32_t bits"
+.Ft unsigned int
+.Fn atomic_or_uint_nv "volatile unsigned int *ptr" "unsigned int bits"
+.Ft unsigned long
+.Fn atomic_or_ulong_nv "volatile unsigned long *ptr" "unsigned long bits"
+.Ft uint64_t
+.Fn atomic_or_64_nv "volatile uint64_t *ptr" "uint64_t bits"
+.Sh DESCRIPTION
+The
+.Nm atomic_or
+family of functions load the value of the variable referenced by
+.Fa ptr ,
+perform a logical
+.Sq or
+with the value
+.Fa bits ,
+and store the result back to the variable referenced by
+.Fa ptr
+in an atomic fashion.
+.Pp
+The
+.Fn *_nv
+variants of these functions return the new value.
+.Pp
+The 64-bit variants of these functions are available only on platforms
+that can support atomic 64-bit memory access.
+Applications can check for the availability of 64-bit atomic memory
+operations by testing if the pre-processor macro
+.Dv __HAVE_ATOMIC64_OPS
+is defined.
+.Sh SEE ALSO
+.Xr atomic_ops 3
+.Sh HISTORY
+The
+.Nm atomic_or
+functions first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/atomic/atomic_swap.3 b/lib/nbsd_libc/atomic/atomic_swap.3
new file mode 100644 (file)
index 0000000..2743652
--- /dev/null
@@ -0,0 +1,77 @@
+.\"    $NetBSD: atomic_swap.3,v 1.1 2008/06/23 10:22:40 ad Exp $
+.\"
+.\" Copyright (c) 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 11, 2007
+.Dt ATOMIC_SWAP 3
+.Os
+.Sh NAME
+.Nm atomic_swap ,
+.Nm atomic_swap_32 ,
+.Nm atomic_swap_uint ,
+.Nm atomic_swap_ulong ,
+.Nm atomic_swap_ptr ,
+.Nm atomic_swap_64
+.Nd atomic swap operations
+.\" .Sh LIBRARY
+.\" .Lb libc
+.Sh SYNOPSIS
+.In sys/atomic.h
+.Ft uint32_t
+.Fn atomic_swap_32 "volatile uint32_t *ptr" "uint32_t new"
+.Ft unsigned int
+.Fn atomic_swap_uint "volatile unsigned int *ptr" "unsigned int new"
+.Ft unsigned long
+.Fn atomic_swap_ulong "volatile unsigned long *ptr" "unsigned long new"
+.Ft void *
+.Fn atomic_swap_ptr "volatile void *ptr" "void *new"
+.Ft uint64_t
+.Fn atomic_swap_64 "volatile uint64_t *ptr" "uint64_t new"
+.Sh DESCRIPTION
+The
+.Nm atomic_swap
+family of functions perform a swap operation in an atomic fashion.
+The value of the variable referenced by
+.Fa ptr
+is replaced by
+.Fa new
+and the old value returned.
+.Pp
+The 64-bit variants of these functions are available only on platforms
+that can support atomic 64-bit memory access.
+Applications can check for the availability of 64-bit atomic memory
+operations by testing if the pre-processor macro
+.Dv __HAVE_ATOMIC64_OPS
+is defined.
+.Sh SEE ALSO
+.Xr atomic_ops 3
+.Sh HISTORY
+The
+.Nm atomic_swap
+functions first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/atomic/membar_ops.3 b/lib/nbsd_libc/atomic/membar_ops.3
new file mode 100644 (file)
index 0000000..125d696
--- /dev/null
@@ -0,0 +1,97 @@
+.\"    $NetBSD: membar_ops.3,v 1.2 2009/05/18 12:39:17 wiz Exp $
+.\"
+.\" Copyright (c) 2007, 2008 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd February 11, 2007
+.Dt MEMBAR_OPS 3
+.Os
+.Sh NAME
+.Nm membar_ops ,
+.Nm membar_enter ,
+.Nm membar_exit ,
+.Nm membar_producer ,
+.Nm membar_consumer ,
+.Nm membar_sync
+.Nd memory access barrier operations
+.\" .Sh LIBRARY
+.\" .Lb libc
+.Sh SYNOPSIS
+.In sys/atomic.h
+.\"
+.Ft void
+.Fn membar_enter "void"
+.Ft void
+.Fn membar_exit "void"
+.Ft void
+.Fn membar_producer "void"
+.Ft void
+.Fn membar_consumer "void"
+.Ft void
+.Fn membar_sync "void"
+.Sh DESCRIPTION
+The
+.Nm membar_ops
+family of functions provide memory access barrier operations necessary
+for synchronization in multiprocessor execution environments that have
+relaxed load and store order.
+.Pp
+.Bl -tag -width "mem"
+.It Fn membar_enter
+Any store preceeding
+.Fn membar_enter
+will reach global visibility before all loads and stores following it.
+.Pp
+.Fn membar_enter
+is typically used in code that implements locking primitives to ensure
+that a lock protects its data.
+.It Fn membar_exit
+All loads and stores preceding
+.Fn membar_exit
+will reach global visibility before any store that follows it.
+.Pp
+.Fn membar_exit
+is typically used in code that implements locking primitives to ensure
+that a lock protects its data.
+.It Fn membar_producer
+All stores preceding the memory barrier will reach global visibility
+before any stores after the memory barrier reach global visibility.
+.It Fn membar_consumer
+All loads preceding the memory barrier will complete before any loads
+after the memory barrier complete.
+.It Fn membar_sync
+All loads and stores preceding the memory barrier will complete and
+reach global visibility before any loads and stores after the memory
+barrier complete and reach global visibility.
+.El
+.Sh SEE ALSO
+.Xr atomic_ops 3
+.Sh HISTORY
+The
+.Nm membar_ops
+functions first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/cdb/Makefile.inc b/lib/nbsd_libc/cdb/Makefile.inc
new file mode 100644 (file)
index 0000000..2fb9d05
--- /dev/null
@@ -0,0 +1,21 @@
+#      $NetBSD: Makefile.inc,v 1.1 2010/04/25 00:54:46 joerg Exp $
+
+# Constant database reader/writer
+
+.PATH: ${.CURDIR}/cdb
+
+SRCS+=         cdbr.c cdbw.c
+
+MAN+=          cdbr.3 cdbw.3 cdb.5
+
+MLINKS+=       cdbr.3 cdbr_open.3
+MLINKS+=       cdbr.3 cdbr_entries.3
+MLINKS+=       cdbr.3 cdbr_get.3
+MLINKS+=       cdbr.3 cdbr_find.3
+MLINKS+=       cdbr.3 cdbr_close.3
+MLINKS+=       cdbw.3 cdbw_open.3
+MLINKS+=       cdbw.3 cdbw_put.3
+MLINKS+=       cdbw.3 cdbw_put_data.3
+MLINKS+=       cdbw.3 cdbw_put_key.3
+MLINKS+=       cdbw.3 cdbw_output.3
+MLINKS+=       cdbw.3 cdbw_close.3
diff --git a/lib/nbsd_libc/cdb/cdb.5 b/lib/nbsd_libc/cdb/cdb.5
new file mode 100644 (file)
index 0000000..0c1ec86
--- /dev/null
@@ -0,0 +1,104 @@
+.\"    $NetBSD: cdb.5,v 1.3 2010/04/27 14:26:52 jruoho Exp $
+.\"
+.\" Copyright (c) 2010 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Joerg Sonnenberger.
+.\" 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 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 HOLDERS 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.
+.Dd April 27, 2010
+.Dt CDB 5
+.Os
+.Sh NAME
+.Nm cdb
+.Nd format of the constant database
+.Sh DESCRIPTION
+The
+.Nm
+database format provides a space-efficient (key,value) database.
+The format doesn't allow updates in any convenient form.
+The file overhead is around 5 bytes per key and 5 bytes per entry.
+Keys are not stored and it is the responsibility of the caller
+to validate matches.
+The index structure is based on a minimal perfect hash table, so exactly
+one entry has to be checked for a match.
+.Ss General Format
+The header record of a
+.Nm
+database consists of the following:
+.Bd -literal -offset indent
+struct header_cdb {
+       uint8_t magic[7];
+       uint8_t version;
+       uint8_t description[16];
+       uint32_t data_size;
+       uint32_t entries;
+       uint32_t entries_index;
+       uint32_t seed;
+};
+.Ed
+.Pp
+All fields are in Little Endian byte order.
+.Pp
+This is followed by a description of the hash function of
+.Va entries_index
+records.
+The size of each index entry is the logarithm of
+.Va entries
+to base 256, rounded up.
+.Pp
+The index records are followed by the start offsets of the entries,
+followed by
+.Va data_size .
+The offsets are relative to the end of the offset record table and are
+monotically increasing.
+The size of each offset record is the logarithm of
+.Va data_size
+to base 256, rounded up.
+.Pp
+The offset table is followed by the entries in order.
+No separation or padding is added.
+.Ss Limitations
+The
+.Nm
+file format is by design intended for a database that can be
+mapped into memory.
+The hard limit for the number of entries and keys is 3435973836.
+The total size of all values must be smaller than 4GiB.
+.Sh SEE ALSO
+.Xr cdbr 3 ,
+.Xr cdbw 3
+.Sh HISTORY
+Support for the
+.Nm cdb
+format first appeared in
+.Nx 6.0 .
+.Sh AUTHORS
+The
+.Nm cdbr
+and
+.Nm cdbw
+functions have been written by
+.An Joerg Sonnenberger Aq joerg@NetBSD.org .
diff --git a/lib/nbsd_libc/cdb/cdbr.3 b/lib/nbsd_libc/cdb/cdbr.3
new file mode 100644 (file)
index 0000000..7b93ebe
--- /dev/null
@@ -0,0 +1,119 @@
+.\"    $NetBSD: cdbr.3,v 1.2 2010/04/25 10:32:44 wiz Exp $
+.\"
+.\" Copyright (c) 2010 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Joerg Sonnenberger.
+.\" 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 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 HOLDERS 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.
+.Dd March 3, 2010
+.Dt CDBR 3
+.Os
+.Sh NAME
+.Nm cdbr
+.Nm cdbr_open ,
+.Nm cdbr_entries ,
+.Nm cdbr_get ,
+.Nm cdbr_find ,
+.Nm cdbr_close ,
+.Nm cdbr_write
+.Nd constant database access methods
+.Sh SYNOPSIS
+.Ft "struct cdbr *"
+.Fn cdbr_open "const char *path" "int flags"
+.Ft uint32_t
+.Fn cdbr_entries "struct cdbr *cdbr"
+.Ft int
+.Fn cdbr_get "struct cdbr *cdbr" "uint32_t index" "const void **data" "size_t *datalen"
+.Ft int
+.Fo cdbr_find
+.Fa "struct cdbr *cdbr"
+.Fa "const void *key"
+.Fa "size_t keylen"
+.Fa "const void **data"
+.Fa "size_t *datalen"
+.Fc
+.Ft void
+.Fn cdbr_close "struct cdbr *cdbr"
+.Sh DESCRIPTION
+The
+.Nm
+library provides a space efficient (key,value) database based
+on perfect hashing.
+.Pp
+A cdb database is opened for reading by calling
+.Fn cdbr_open .
+The only supported value for
+.Va flags
+is
+.Dv CDBR_DEFAULT .
+The function returns a handle to pass to the other functions.
+The database is closed by invoking
+.Fn cdbr_close .
+All resources associated with the handle are freed and the memory
+returned by
+.Fn cdbr_get
+and
+.Fn cdbr_find
+is invalidated.
+.Pp
+The number of records in the database can be obtained by calling
+.Fn cdbr_entries .
+Records can be obtained by record number using
+.Fn cdbr_get
+or by key using
+.Fn cdbr_find .
+Both functions return 0 on success and update
+.Va data
+and
+.Va datalen
+accordingly.
+The location
+.Va *data
+remains valid until
+.Fn cdbr_close
+is called.
+It is the responsibility of the caller of
+.Fn cdbr_find
+to ensure that the key matches the returned data.
+The function returns the only possible match, but the database doesn't store
+the keys to minimize overhead.
+.Sh SEE ALSO
+.Xr nbperf 1 ,
+.Xr cdbw 3 ,
+.Xr db 3 ,
+.Xr cdb 5
+.Sh HISTORY
+Support for the
+.Nm cdb
+format first appeared in
+.Nx 6.0 .
+.Sh AUTHORS
+The
+.Nm cdbr
+and
+.Nm cdbw
+functions have been written by
+.An Joerg Sonnenberger Aq joerg@NetBSD.org .
diff --git a/lib/nbsd_libc/cdb/cdbr.c b/lib/nbsd_libc/cdb/cdbr.c
new file mode 100644 (file)
index 0000000..a71ac42
--- /dev/null
@@ -0,0 +1,246 @@
+/*     $NetBSD: cdbr.c,v 1.2 2010/06/03 12:40:52 veego Exp $   */
+/*-
+ * Copyright (c) 2010 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Joerg Sonnenberger.
+ *
+ * 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 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 HOLDERS 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: cdbr.c,v 1.2 2010/06/03 12:40:52 veego Exp $");
+
+#include "namespace.h"
+
+#include <sys/bitops.h>
+#include <sys/endian.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <cdbr.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(cdbr_close,_cdbr_close)
+__weak_alias(cdbr_find,_cdbr_find)
+__weak_alias(cdbr_get,_cdbr_get)
+__weak_alias(cdbr_open,_cdbr_open)
+#endif
+
+struct cdbr {
+       uint8_t *mmap_base;
+       size_t mmap_size;
+
+       uint8_t *hash_base;
+       uint8_t *offset_base;
+       uint8_t *data_base;
+
+       uint32_t data_size;
+       uint32_t entries;
+       uint32_t entries_index;
+       uint32_t seed;
+
+       uint8_t offset_size;
+       uint8_t index_size;
+
+       uint32_t entries_m;
+       uint32_t entries_index_m;
+       uint8_t entries_s1, entries_s2;
+       uint8_t entries_index_s1, entries_index_s2;
+};
+
+/* ARGSUSED */
+struct cdbr *
+cdbr_open(const char *path, int flags)
+{
+       uint8_t buf[40];
+       int fd;
+       struct cdbr *cdbr;
+       struct stat sb;
+
+       if ((fd = open(path, O_RDONLY)) == -1)
+               return NULL;
+
+       errno = EINVAL;
+       if (fstat(fd, &sb) == -1 ||
+           read(fd, buf, sizeof(buf)) != sizeof(buf) ||
+           memcmp(buf, "NBCDB\n\0\001", 8) ||
+           (cdbr = malloc(sizeof(*cdbr))) == NULL) {
+               close(fd);
+               return NULL;
+       }
+
+       cdbr->data_size = le32dec(buf + 24);
+       cdbr->entries = le32dec(buf + 28);
+       cdbr->entries_index = le32dec(buf + 32);
+       cdbr->seed = le32dec(buf + 36);
+
+       if (cdbr->data_size < 0x100)
+               cdbr->offset_size = 1;
+       else if (cdbr->data_size < 0x10000)
+               cdbr->offset_size = 2;
+       else
+               cdbr->offset_size = 4;
+
+       if (cdbr->entries_index < 0x100)
+               cdbr->index_size = 1;
+       else if (cdbr->entries_index < 0x10000)
+               cdbr->index_size = 2;
+       else
+               cdbr->index_size = 4;
+
+       cdbr->mmap_size = (size_t)sb.st_size;
+       cdbr->mmap_base = mmap(NULL, cdbr->mmap_size, PROT_READ, MAP_FILE|MAP_SHARED, fd, 0);
+       close(fd);
+
+       if (cdbr->mmap_base == MAP_FAILED) {
+               free(cdbr);
+               return NULL;
+       }
+
+       cdbr->hash_base = cdbr->mmap_base + 40;
+       cdbr->offset_base = cdbr->hash_base + cdbr->entries_index * cdbr->index_size;
+       if (cdbr->entries_index * cdbr->index_size % cdbr->offset_size)
+               cdbr->offset_base += cdbr->offset_size -
+                   cdbr->entries_index * cdbr->index_size % cdbr->offset_size;
+       cdbr->data_base = cdbr->offset_base + (cdbr->entries + 1) * cdbr->offset_size;
+
+       if (cdbr->hash_base < cdbr->mmap_base ||
+           cdbr->offset_base < cdbr->mmap_base ||
+           cdbr->data_base < cdbr->mmap_base ||
+           cdbr->data_base + cdbr->data_size < cdbr->mmap_base ||
+           cdbr->data_base + cdbr->data_size >
+           cdbr->mmap_base + cdbr->mmap_size ||
+           cdbr->entries == 0 || cdbr->entries_index == 0) {
+               errno = EINVAL;
+               cdbr_close(cdbr);
+               return NULL;
+       }
+
+       fast_divide32_prepare(cdbr->entries, &cdbr->entries_m,
+           &cdbr->entries_s1, &cdbr->entries_s2);
+       fast_divide32_prepare(cdbr->entries_index, &cdbr->entries_index_m,
+           &cdbr->entries_index_s1, &cdbr->entries_index_s2);
+
+       return cdbr;
+}
+
+static inline uint32_t
+get_uintX(const uint8_t *addr, uint32_t idx, int size)
+{
+       addr += idx * size;
+
+       if (size == 4)
+               return /* LINTED */le32toh(*(const uint32_t *)addr);
+       else if (size == 2)
+               return /* LINTED */le16toh(*(const uint16_t *)addr);
+       else
+               return *addr;
+}
+
+uint32_t
+cdbr_entries(struct cdbr *cdbr)
+{
+
+       return cdbr->entries;
+}
+
+int
+cdbr_get(struct cdbr *cdbr, uint32_t idx, const void **data, size_t *data_len)
+{
+       uint32_t start, end;
+
+       if (idx >= cdbr->entries) {
+               errno = EINVAL;
+               return -1;
+       }
+
+       start = get_uintX(cdbr->offset_base, idx, cdbr->offset_size);
+       end = get_uintX(cdbr->offset_base, idx + 1, cdbr->offset_size);
+
+       if (start > end) {
+               errno = EIO;
+               return -1;
+       }
+
+       if (end > cdbr->data_size) {
+               errno = EIO;
+               return -1;
+       }
+
+       *data = cdbr->data_base + start;
+       *data_len = end - start;
+
+       return 0;
+}
+
+int
+cdbr_find(struct cdbr *cdbr, const void *key, size_t key_len,
+    const void **data, size_t *data_len)
+{
+       uint32_t hashes[3], idx;
+
+       if (cdbr->entries_index == 0) {
+               errno = EINVAL;
+               return -1;
+       }
+
+       mi_vector_hash(key, key_len, cdbr->seed, hashes);
+
+       hashes[0] = fast_remainder32(hashes[0], cdbr->entries_index,
+           cdbr->entries_index_m, cdbr->entries_index_s1,
+           cdbr->entries_index_s2);
+       hashes[1] = fast_remainder32(hashes[1], cdbr->entries_index,
+           cdbr->entries_index_m, cdbr->entries_index_s1,
+           cdbr->entries_index_s2);
+       hashes[2] = fast_remainder32(hashes[2], cdbr->entries_index,
+           cdbr->entries_index_m, cdbr->entries_index_s1,
+           cdbr->entries_index_s2);
+
+       idx = get_uintX(cdbr->hash_base, hashes[0], cdbr->index_size);
+       idx += get_uintX(cdbr->hash_base, hashes[1], cdbr->index_size);
+       idx += get_uintX(cdbr->hash_base, hashes[2], cdbr->index_size);
+
+       return cdbr_get(cdbr, fast_remainder32(idx, cdbr->entries,
+           cdbr->entries_m, cdbr->entries_s1, cdbr->entries_s2), data,
+           data_len);
+}
+
+void
+cdbr_close(struct cdbr *cdbr)
+{
+       munmap(cdbr->mmap_base, cdbr->mmap_size);
+       free(cdbr);
+}
diff --git a/lib/nbsd_libc/cdb/cdbw.3 b/lib/nbsd_libc/cdb/cdbw.3
new file mode 100644 (file)
index 0000000..bd6e152
--- /dev/null
@@ -0,0 +1,130 @@
+.\"    $NetBSD: cdbw.3,v 1.3 2010/11/03 16:17:48 plunky Exp $
+.\"
+.\" Copyright (c) 2010 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Joerg Sonnenberger.
+.\" 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 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 HOLDERS 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.
+.Dd November 3, 2010
+.Dt CDBW 3
+.Os
+.Sh NAME
+.Nm cdbw_open ,
+.Nm cdbw_put ,
+.Nm cdbw_put_data ,
+.Nm cdbw_put_key ,
+.Nm cdbw_close
+.Nd create constant databases
+.Sh SYNOPSIS
+.In archive_entry.h
+.Ft "struct cdbw *"
+.Fn cdbw_open "void"
+.Ft int
+.Fo cdbw_put
+.Fa "struct cdbw *cdbw"
+.Fa "const void *key"
+.Fa "size_t keylen"
+.Fa "const void *data"
+.Fa "size_t datalen"
+.Fc
+.Ft int
+.Fo cdbw_put_data
+.Fa "struct cdbw *cdbw"
+.Fa "const void *data"
+.Fa "size_t datalen"
+.Fa "uint32_t *index"
+.Fc
+.Ft int
+.Fo cdbw_put_key
+.Fa "struct cdbw *cdbw"
+.Fa "const void *key"
+.Fa "size_t keylen"
+.Fa "uint32_t index"
+.Fc
+.Ft int
+.Fo cdbw_output
+.Fa "struct cdbw *cdbw"
+.Fa "int output"
+.Fa "const char descr[16]"
+.Fa "uint32_t (*seedgen)(void)"
+.Fc
+.Ft void
+.Fn cdbw_close "struct cdbw *cdbw"
+.Sh DESCRIPTION
+The
+.Nm cdbw
+functions are used to create a constant databases for use with
+.Xr cdbr 3 .
+Details about the file format, including overhead and limitations,
+can be found in
+.Xr cdb 5 .
+.Pp
+.Fn cdbw_open
+prepares a new
+.Nm cdb
+writer.
+The function returns a handle to pass to the other functions.
+.Pp
+.Fn cdbw_close
+frees all resources associated with the handle.
+.Pp
+.Fn cdbw_put
+adds the given (key,value) pair after checking for a duplicate key.
+.Fn cdbw_put_data
+adds the given value to the writer without adding a key reference.
+The returned index can be used in subsequent calls to
+.Fn cdbw_put_key
+to add one or more keys pointing to this value.
+.Fn cdbw_put_key
+checks for duplicate keys and valid index arguments.
+On success it adds the given key.
+.Pp
+.Fn cdbw_output
+computes the database file and writes it to the given descriptor.
+The function returns an error if the file cannot be written correctly.
+The
+.Fn descr
+parameter provides a human readable description of the database content.
+The
+.Fn seedgen
+parameter can be used to override the default PRNG.
+The function should return a different value for each invokation.
+The bitwise layout of the output depends on the chosen seed.
+.Sh SEE ALSO
+.Xr cdbr 3 ,
+.Xr cdb 5
+.Sh HISTORY
+Support for the
+.Nm cdb
+format first appeared in
+.Nx 6.0 .
+.Sh AUTHORS
+The
+.Nm cdbr
+and
+.Nm cdbw
+functions have been written by
+.An Joerg Sonnenberger Aq joerg@NetBSD.org .
diff --git a/lib/nbsd_libc/cdb/cdbw.c b/lib/nbsd_libc/cdb/cdbw.c
new file mode 100644 (file)
index 0000000..d670740
--- /dev/null
@@ -0,0 +1,599 @@
+/*     $NetBSD: cdbw.c,v 1.1 2010/04/25 00:54:46 joerg Exp $   */
+/*-
+ * Copyright (c) 2009, 2010 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Joerg Sonnenberger.
+ *
+ * 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 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 HOLDERS 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: cdbw.c,v 1.1 2010/04/25 00:54:46 joerg Exp $");
+
+#include "namespace.h"
+
+#include <sys/endian.h>
+#include <sys/queue.h>
+#include <cdbw.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(cdbw_close,_cdbw_close)
+__weak_alias(cdbw_open,_cdbw_open)
+__weak_alias(cdbw_output,_cdbw_output)
+__weak_alias(cdbw_put,_cdbw_put)
+__weak_alias(cdbw_put_data,_cdbw_put_data)
+__weak_alias(cdbw_put_key,_cdbw_put_key)
+#endif
+
+struct key_hash {
+       SLIST_ENTRY(key_hash) link;
+       uint32_t hashes[3];
+       uint32_t idx;
+       void *key;
+       size_t keylen;
+};
+
+SLIST_HEAD(key_hash_head, key_hash);
+
+struct cdbw {
+       size_t data_counter;
+       size_t data_allocated;
+       size_t data_size;
+       size_t *data_len;
+       void **data_ptr;
+
+       size_t hash_size;
+       struct key_hash_head *hash;
+       size_t key_counter;
+};
+
+ /* Max. data counter that allows the index size to be 32bit. */
+static const uint32_t max_data_counter = 0xccccccccU;
+
+struct cdbw *
+cdbw_open(void)
+{
+       struct cdbw *cdbw;
+       size_t i;
+
+       cdbw = calloc(sizeof(*cdbw), 1);
+       if (cdbw == NULL)
+               return NULL;
+
+       cdbw->hash_size = 1024;
+       cdbw->hash = calloc(cdbw->hash_size, sizeof(*cdbw->hash));
+       if (cdbw->hash == NULL) {
+               free(cdbw);
+               return NULL;
+       }
+
+       for (i = 0; i < cdbw->hash_size; ++i)
+               SLIST_INIT(cdbw->hash + i);
+
+       return cdbw;
+}
+
+int
+cdbw_put(struct cdbw *cdbw, const void *key, size_t keylen,
+    const void *data, size_t datalen)
+{
+       uint32_t idx;
+       int rv;
+
+       rv = cdbw_put_data(cdbw, data, datalen, &idx);
+       if (rv)
+               return rv;
+       rv = cdbw_put_key(cdbw, key, keylen, idx);
+       if (rv) {
+               --cdbw->data_counter;
+               free(cdbw->data_ptr[cdbw->data_counter]);
+               cdbw->data_size -= datalen;
+               return rv;
+       }
+       return 0;
+}
+
+int
+cdbw_put_data(struct cdbw *cdbw, const void *data, size_t datalen,
+    uint32_t *idx)
+{
+
+       if (cdbw->data_counter == max_data_counter)
+               return -1;
+
+       if (cdbw->data_size + datalen < cdbw->data_size ||
+           cdbw->data_size + datalen > 0xffffffffU)
+               return -1; /* Overflow */
+
+       if (cdbw->data_allocated == cdbw->data_counter) {
+               void **new_data_ptr;
+               size_t *new_data_len;
+               size_t new_allocated;
+
+               if (cdbw->data_allocated == 0)
+                       new_allocated = 256;
+               else
+                       new_allocated = cdbw->data_allocated * 2;
+
+               new_data_ptr = realloc(cdbw->data_ptr,
+                   sizeof(*cdbw->data_ptr) * new_allocated);
+               if (new_data_ptr == NULL)
+                       return -1;
+               cdbw->data_ptr = new_data_ptr;
+
+               new_data_len = realloc(cdbw->data_len,
+                   sizeof(*cdbw->data_len) * new_allocated);
+               if (new_data_len == NULL)
+                       return -1;
+               cdbw->data_len = new_data_len;
+
+               cdbw->data_allocated = new_allocated;
+       }
+
+       cdbw->data_ptr[cdbw->data_counter] = malloc(datalen);
+       if (cdbw->data_ptr[cdbw->data_counter] == NULL)
+               return -1;
+       memcpy(cdbw->data_ptr[cdbw->data_counter], data, datalen);
+       cdbw->data_len[cdbw->data_counter] = datalen;
+       cdbw->data_size += datalen;
+       *idx = cdbw->data_counter++;
+       return 0;
+}
+
+int
+cdbw_put_key(struct cdbw *cdbw, const void *key, size_t keylen, uint32_t idx)
+{
+       uint32_t hashes[3];
+       struct key_hash_head *head, *head2, *new_head;
+       struct key_hash *key_hash;
+       size_t new_hash_size, i;
+
+       if (idx >= cdbw->data_counter ||
+           cdbw->key_counter == max_data_counter)
+               return -1;
+
+       mi_vector_hash(key, keylen, 0, hashes);
+
+       head = cdbw->hash + (hashes[0] & (cdbw->hash_size - 1));
+       SLIST_FOREACH(key_hash, head, link) {
+               if (key_hash->keylen != keylen)
+                       continue;
+               if (key_hash->hashes[0] != hashes[0])
+                       continue;
+               if (key_hash->hashes[1] != hashes[1])
+                       continue;
+               if (key_hash->hashes[2] != hashes[2])
+                       continue;
+               if (memcmp(key, key_hash->key, keylen))
+                       continue;
+               return -1;
+       }
+       key_hash = malloc(sizeof(*key_hash));
+       if (key_hash == NULL)
+               return -1;
+       key_hash->key = malloc(keylen);
+       if (key_hash->key == NULL) {
+               free(key_hash);
+               return -1;
+       }
+       memcpy(key_hash->key, key, keylen);
+       key_hash->hashes[0] = hashes[0];
+       key_hash->hashes[1] = hashes[1];
+       key_hash->hashes[2] = hashes[2];
+       key_hash->keylen = keylen;
+       key_hash->idx = idx;
+       SLIST_INSERT_HEAD(head, key_hash, link);
+       ++cdbw->key_counter;
+
+       if (cdbw->key_counter <= cdbw->hash_size)
+               return 0;
+
+       /* Try to resize the hash table, but ignore errors. */
+       new_hash_size = cdbw->hash_size * 2;
+       new_head = calloc(sizeof(*new_head), new_hash_size);
+       if (new_head == NULL)
+               return 0;
+
+       head = &cdbw->hash[hashes[0] & (cdbw->hash_size - 1)];
+       for (i = 0; i < new_hash_size; ++i)
+               SLIST_INIT(new_head + i);
+
+       for (i = 0; i < cdbw->hash_size; ++i) {
+               head = cdbw->hash + i;
+
+               while ((key_hash = SLIST_FIRST(head)) != NULL) {
+                       SLIST_REMOVE_HEAD(head, link);
+                       head2 = new_head +
+                           (key_hash->hashes[0] & (new_hash_size - 1));
+                       SLIST_INSERT_HEAD(head2, key_hash, link);
+               }
+       }
+       free(cdbw->hash);
+       cdbw->hash_size = new_hash_size;
+       cdbw->hash = new_head;
+
+       return 0;
+}
+
+void
+cdbw_close(struct cdbw *cdbw)
+{
+       struct key_hash_head *head;
+       struct key_hash *key_hash;
+       size_t i;
+
+       for (i = 0; i < cdbw->hash_size; ++i) {
+               head = cdbw->hash + i;
+               while ((key_hash = SLIST_FIRST(head)) != NULL) {
+                       SLIST_REMOVE_HEAD(head, link);
+                       free(key_hash->key);
+                       free(key_hash);
+               }
+       }
+
+       for (i = 0; i < cdbw->data_counter; ++i)
+               free(cdbw->data_ptr[i]);
+       free(cdbw->data_ptr);
+       free(cdbw->data_len);
+       free(cdbw->hash);
+       free(cdbw);
+}
+
+#define unused 0xffffffffU
+
+struct vertex {
+       uint32_t l_edge, m_edge, r_edge;
+};
+
+struct edge {
+       uint32_t idx;
+
+       uint32_t left, middle, right;
+       uint32_t l_prev, m_prev, l_next;
+       uint32_t r_prev, m_next, r_next;
+};
+
+struct state {
+       uint32_t data_entries;
+       uint32_t entries;
+       uint32_t keys;
+       uint32_t seed;
+
+       uint32_t *g;
+       char *visited;
+
+       struct vertex *verts;
+       struct edge *edges;
+       uint32_t output_index;
+       uint32_t *output_order;
+};
+
+static void
+remove_vertex(struct state *state, struct vertex *v)
+{
+       struct edge *e;
+       struct vertex *vl, *vm, *vr;
+
+       if (v->l_edge != unused && v->m_edge != unused)
+               return;
+       if (v->l_edge != unused && v->r_edge != unused)
+               return;
+       if (v->m_edge != unused && v->r_edge != unused)
+               return;
+       if (v->l_edge == unused && v->m_edge == unused && v->r_edge == unused)
+               return;
+
+       if (v->l_edge != unused) {
+               e = &state->edges[v->l_edge];
+               if (e->l_next != unused)
+                       return;
+       } else if (v->m_edge != unused) {
+               e = &state->edges[v->m_edge];
+               if (e->m_next != unused)
+                       return;
+       } else {
+               if (v->r_edge == unused)
+                       abort();
+               e = &state->edges[v->r_edge];
+               if (e->r_next != unused)
+                       return;
+       }
+
+       state->output_order[--state->output_index] = e - state->edges;
+
+       vl = &state->verts[e->left];
+       vm = &state->verts[e->middle];
+       vr = &state->verts[e->right];
+
+       if (e->l_prev == unused)
+               vl->l_edge = e->l_next;
+       else
+               state->edges[e->l_prev].l_next = e->l_next;
+       if (e->l_next != unused)
+               state->edges[e->l_next].l_prev = e->l_prev;
+
+       if (e->m_prev == unused)
+               vm->m_edge = e->m_next;
+       else
+               state->edges[e->m_prev].m_next = e->m_next;
+       if (e->m_next != unused)
+               state->edges[e->m_next].m_prev = e->m_prev;
+
+       if (e->r_prev == unused)
+               vr->r_edge = e->r_next;
+       else
+               state->edges[e->r_prev].r_next = e->r_next;
+       if (e->r_next != unused)
+               state->edges[e->r_next].r_prev = e->r_prev;
+}
+
+static int
+build_graph(struct cdbw *cdbw, struct state *state)
+{
+       struct key_hash_head *head;
+       struct key_hash *key_hash;
+       struct vertex *v;
+       struct edge *e;
+       uint32_t hashes[3];
+       size_t i;
+
+       e = state->edges;
+       for (i = 0; i < cdbw->hash_size; ++i) {
+               head = &cdbw->hash[i];
+               SLIST_FOREACH(key_hash, head, link) {
+                       e->idx = key_hash->idx;
+                       mi_vector_hash(key_hash->key, key_hash->keylen,
+                           state->seed, hashes);
+                       e->left = hashes[0] % state->entries;
+                       e->middle = hashes[1] % state->entries;
+                       e->right = hashes[2] % state->entries;
+
+                       ++e;
+               }
+       }
+
+       for (i = 0; i < state->entries; ++i) {
+               v = state->verts + i;
+               v->l_edge = unused;
+               v->m_edge = unused;
+               v->r_edge = unused;
+       }
+
+       for (i = 0; i < state->keys; ++i) {
+               e = state->edges + i;
+               v = state->verts + e->left;
+               if (v->l_edge != unused)
+                       state->edges[v->l_edge].l_prev = i;
+               e->l_next = v->l_edge;
+               e->l_prev = unused;
+               v->l_edge = i;
+
+               v = &state->verts[e->middle];
+               if (v->m_edge != unused)
+                       state->edges[v->m_edge].m_prev = i;
+               e->m_next = v->m_edge;
+               e->m_prev = unused;
+               v->m_edge = i;
+
+               v = &state->verts[e->right];
+               if (v->r_edge != unused)
+                       state->edges[v->r_edge].r_prev = i;
+               e->r_next = v->r_edge;
+               e->r_prev = unused;
+               v->r_edge = i;
+       }
+
+       state->output_index = state->keys;
+       for (i = 0; i < state->entries; ++i)
+               remove_vertex(state, state->verts + i);
+
+       i = state->keys;
+       while (i > 0 && i > state->output_index) {
+               --i;
+               e = state->edges + state->output_order[i];
+               remove_vertex(state, state->verts + e->left);
+               remove_vertex(state, state->verts + e->middle);
+               remove_vertex(state, state->verts + e->right);
+       }
+
+       return state->output_index == 0 ? 0 : -1;
+}
+
+static void
+assign_nodes(struct state *state)
+{
+       struct edge *e;
+       size_t i;
+
+       for (i = 0; i < state->keys; ++i) {
+               e = state->edges + state->output_order[i];
+
+               if (!state->visited[e->left]) {
+                       state->g[e->left] =
+                           (2 * state->data_entries + e->idx
+                           - state->g[e->middle] - state->g[e->right])
+                           % state->data_entries;
+               } else if (!state->visited[e->middle]) {
+                       state->g[e->middle] =
+                           (2 * state->data_entries + e->idx
+                           - state->g[e->left] - state->g[e->right])
+                           % state->data_entries;
+               } else {
+                       state->g[e->right] =
+                           (2 * state->data_entries + e->idx
+                           - state->g[e->left] - state->g[e->middle])
+                           % state->data_entries;
+               }
+               state->visited[e->left] = 1;
+               state->visited[e->middle] = 1;
+               state->visited[e->right] = 1;
+       }
+}
+
+static size_t
+compute_size(uint32_t size)
+{
+       if (size < 0x100)
+               return 1;
+       else if (size < 0x10000)
+               return 2;
+       else
+               return 4;
+}
+
+#define COND_FLUSH_BUFFER(n) do {                              \
+       if (__predict_false(cur_pos + (n) >= sizeof(buf))) {    \
+               ret = write(fd, buf, cur_pos);                  \
+               if (ret == -1 || (size_t)ret != cur_pos)        \
+                       return -1;                              \
+               cur_pos = 0;                                    \
+       }                                                       \
+} while (/* CONSTCOND */ 0)
+
+static int
+print_hash(struct cdbw *cdbw, struct state *state, int fd, const char *descr)
+{
+       uint32_t data_size;
+       uint8_t buf[90000];
+       size_t i, size, size2, cur_pos;
+       ssize_t ret;
+
+       memcpy(buf, "NBCDB\n\0", 7);
+       buf[7] = 1;
+       strncpy((char *)buf + 8, descr, 16);
+       le32enc(buf + 24, cdbw->data_size);
+       le32enc(buf + 28, cdbw->data_counter);
+       le32enc(buf + 32, state->entries);
+       le32enc(buf + 36, state->seed);
+       cur_pos = 40;
+
+       size = compute_size(state->entries);
+       for (i = 0; i < state->entries; ++i) {
+               COND_FLUSH_BUFFER(4);
+               le32enc(buf + cur_pos, state->g[i]);
+               cur_pos += size;
+       }
+       size2 = compute_size(cdbw->data_size);
+       size = size * state->entries % size2;
+       if (size != 0) {
+               size = size2 - size;
+               COND_FLUSH_BUFFER(4);
+               le32enc(buf + cur_pos, 0);
+               cur_pos += size;
+       }
+       for (data_size = 0, i = 0; i < cdbw->data_counter; ++i) {
+               COND_FLUSH_BUFFER(4);
+               le32enc(buf + cur_pos, data_size);
+               cur_pos += size2;
+               data_size += cdbw->data_len[i];
+       }
+       COND_FLUSH_BUFFER(4);
+       le32enc(buf + cur_pos, data_size);
+       cur_pos += size2;
+
+       for (i = 0; i < cdbw->data_counter; ++i) {
+               COND_FLUSH_BUFFER(cdbw->data_len[i]);
+               if (cdbw->data_len[i] < sizeof(buf)) {
+                       memcpy(buf + cur_pos, cdbw->data_ptr[i],
+                           cdbw->data_len[i]);
+                       cur_pos += cdbw->data_len[i];
+               } else {
+                       ret = write(fd, cdbw->data_ptr[i], cdbw->data_len[i]);
+                       if (ret == -1 || (size_t)ret != cdbw->data_len[i])
+                               return -1;
+               }
+       }
+       if (cur_pos != 0) {
+               ret = write(fd, buf, cur_pos);
+               if (ret == -1 || (size_t)ret != cur_pos)
+                       return -1;
+       }
+       return 0;
+}
+
+int
+cdbw_output(struct cdbw *cdbw, int fd, const char descr[16],
+    uint32_t (*seedgen)(void))
+{
+       struct state state;
+       int rv;
+
+       if (cdbw->data_counter == 0 || cdbw->key_counter == 0) {
+               state.entries = 0;
+               state.seed = 0;
+               print_hash(cdbw, &state, fd, descr);
+               return 0;
+       }
+
+       if (seedgen == NULL)
+               seedgen = arc4random;
+
+       rv = 0;
+
+       state.keys = cdbw->key_counter;
+       state.data_entries = cdbw->data_counter;
+       state.entries = state.keys + (state.keys + 3) / 4;
+       if (state.entries < 10)
+               state.entries = 10;
+
+#define        NALLOC(var, n)  var = calloc(sizeof(*var), n)
+       NALLOC(state.g, state.entries);
+       NALLOC(state.visited, state.entries);
+       NALLOC(state.verts, state.entries);
+       NALLOC(state.edges, state.entries);
+       NALLOC(state.output_order, state.keys);
+#undef NALLOC
+
+       if (state.g == NULL || state.visited == NULL || state.verts == NULL ||
+           state.edges == NULL || state.output_order == NULL) {
+               rv = -1;
+               goto release;
+       }
+
+       do {
+               state.seed = (*seedgen)();
+       } while (build_graph(cdbw, &state));
+
+       assign_nodes(&state);
+       rv = print_hash(cdbw, &state, fd, descr);
+
+release:
+       free(state.g);
+       free(state.visited);
+       free(state.verts);
+       free(state.edges);
+       free(state.output_order);
+
+       return rv;
+}
diff --git a/lib/nbsd_libc/citrus/Makefile.inc b/lib/nbsd_libc/citrus/Makefile.inc
new file mode 100644 (file)
index 0000000..abab175
--- /dev/null
@@ -0,0 +1,25 @@
+#      $NetBSD: Makefile.inc,v 1.8 2010/05/30 08:28:53 tnozaki Exp $
+
+# sources
+.PATH: ${ARCHDIR}/citrus ${.CURDIR}/citrus
+
+MODULE_SHLIB_MAJOR!= . ${NETBSDSRCDIR}/lib/i18n_module/shlib_version ; echo $$major
+CPPFLAGS.citrus_module.c+=-DI18NMODULE_MAJOR=${MODULE_SHLIB_MAJOR}
+SRCS+= citrus_bcs.c citrus_bcs_strtol.c citrus_bcs_strtoul.c \
+       citrus_csmapper.c citrus_ctype.c citrus_ctype_fallback.c \
+       citrus_db.c citrus_db_hash.c citrus_esdb.c citrus_hash.c \
+       citrus_iconv.c citrus_lookup.c \
+       citrus_mapper.c citrus_memstream.c citrus_mmap.c citrus_module.c \
+       citrus_none.c citrus_stdenc.c
+SRCS+= citrus_lc_ctype.c \
+       citrus_lc_monetary.c \
+       citrus_lc_numeric.c \
+       citrus_lc_time.c \
+       citrus_lc_messages.c
+CPPFLAGS.citrus_bcs_strtol.c+= -I${LIBCDIR}/../../common/lib/libc/stdlib
+CPPFLAGS.citrus_bcs_strtoul.c+=        -I${LIBCDIR}/../../common/lib/libc/stdlib
+CPPFLAGS.citrus_lc_ctype.c+=   -I${LIBCDIR}/locale
+CPPFLAGS.citrus_lc_monetary.c+=        -I${LIBCDIR}/locale
+CPPFLAGS.citrus_lc_numeric.c+= -I${LIBCDIR}/locale
+CPPFLAGS.citrus_lc_time.c+=    -I${LIBCDIR}/locale
+CPPFLAGS.citrus_lc_messages.c+=        -I${LIBCDIR}/locale
diff --git a/lib/nbsd_libc/citrus/citrus_aliasname_local.h b/lib/nbsd_libc/citrus/citrus_aliasname_local.h
new file mode 100644 (file)
index 0000000..d76cb41
--- /dev/null
@@ -0,0 +1,48 @@
+/* $NetBSD: citrus_aliasname_local.h,v 1.2 2009/01/11 02:46:24 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_ALIASNAME_LOCAL_H_
+#define _CITRUS_ALIASNAME_LOCAL_H_
+
+static __inline const char *
+__unaliasname(const char *dbname, const char *alias,
+    void *buf, size_t bufsize)
+{
+       return _lookup_simple(dbname, alias,
+           buf, bufsize, _LOOKUP_CASE_SENSITIVE);
+}
+
+static __inline int
+__isforcemapping(const char *name)
+{
+       _DIAGASSERT(name != NULL);
+
+       return _bcs_strcasecmp("/force", name);
+}
+
+#endif /*_CITRUS_ALIASNAME_LOCAL_H_*/
diff --git a/lib/nbsd_libc/citrus/citrus_bcs.c b/lib/nbsd_libc/citrus/citrus_bcs.c
new file mode 100644 (file)
index 0000000..b14186d
--- /dev/null
@@ -0,0 +1,171 @@
+/*     $NetBSD: citrus_bcs.c,v 1.5 2005/05/14 17:55:42 tshiozak Exp $  */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_bcs.c,v 1.5 2005/05/14 17:55:42 tshiozak Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifndef HOSTPROG
+#include "namespace.h"
+#endif
+#include <assert.h>
+#include <stdlib.h>
+
+#include "citrus_namespace.h"
+#include "citrus_bcs.h"
+
+/*
+ * case insensitive comparison between two C strings.
+ */
+int
+_citrus_bcs_strcasecmp(const char * __restrict str1,
+                      const char * __restrict str2)
+{
+       int c1 = 1, c2 = 1;
+
+       while (c1 && c2 && c1 == c2) {
+               c1 = _bcs_toupper(*str1++);
+               c2 = _bcs_toupper(*str2++);
+       }
+
+       return ((c1 == c2) ? 0 : ((c1 > c2) ? 1 : -1));
+}
+
+/*
+ * case insensitive comparison between two C strings with limitation of length.
+ */
+int
+_citrus_bcs_strncasecmp(const char * __restrict str1,
+                       const char * __restrict str2, size_t sz)
+{
+       int c1 = 1, c2 = 1;
+
+       while (c1 && c2 && c1 == c2 && sz != 0) {
+               c1 = _bcs_toupper(*str1++);
+               c2 = _bcs_toupper(*str2++);
+               sz--;
+       }
+
+       return ((c1 == c2) ? 0 : ((c1 > c2) ? 1 : -1));
+}
+
+/*
+ * skip white space characters.
+ */
+const char *
+_citrus_bcs_skip_ws(const char *p)
+{
+
+       while (*p && _bcs_isspace(*p))
+               p++;
+
+       return (p);
+}
+
+/*
+ * skip non white space characters.
+ */
+const char *
+_citrus_bcs_skip_nonws(const char *p)
+{
+
+       while (*p && !_bcs_isspace(*p))
+               p++;
+
+       return (p);
+}
+
+/*
+ * skip white space characters with limitation of length.
+ */
+const char *
+_citrus_bcs_skip_ws_len(const char * __restrict p, size_t * __restrict len)
+{
+
+       while (*p && *len > 0 && _bcs_isspace(*p)) {
+               p++;
+               (*len)--;
+       }
+
+       return (p);
+}
+
+/*
+ * skip non white space characters with limitation of length.
+ */
+const char *
+_citrus_bcs_skip_nonws_len(const char * __restrict p, size_t * __restrict len)
+{
+
+       while (*p && *len > 0 && !_bcs_isspace(*p)) {
+               p++;
+               (*len)--;
+       }
+
+       return (p);
+}
+
+/*
+ * truncate trailing white space characters.
+ */
+void
+_citrus_bcs_trunc_rws_len(const char * __restrict p, size_t * __restrict len)
+{
+
+       while (*len > 0 && _bcs_isspace(p[*len - 1]))
+               (*len)--;
+}
+
+/*
+ * destructive transliterate to lowercase.
+ */
+void
+_citrus_bcs_convert_to_lower(char *s)
+{
+       while (*s) {
+               *s = _bcs_tolower(*s);
+               s++;
+       }
+}
+
+/*
+ * destructive transliterate to uppercase.
+ */
+void
+_citrus_bcs_convert_to_upper(char *s)
+{
+       while (*s) {
+               *s = _bcs_toupper(*s);
+               s++;
+       }
+}
diff --git a/lib/nbsd_libc/citrus/citrus_bcs.h b/lib/nbsd_libc/citrus/citrus_bcs.h
new file mode 100644 (file)
index 0000000..784da76
--- /dev/null
@@ -0,0 +1,98 @@
+/*     $NetBSD: citrus_bcs.h,v 1.6 2009/01/11 02:46:24 christos Exp $  */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_BCS_H_
+#define _CITRUS_BCS_H_
+
+/*
+ * predicate/conversion for basic character set.
+ *
+ * `Basic character set' is a term defined in the ISO C standard.
+ * Citrus bcs is, if anything, close to `portable character set'
+ * defined in the POSIX.
+ */
+
+#define _CITRUS_BCS_PRED(_name_, _cond_) \
+static __inline int _citrus_bcs_##_name_(uint8_t c) { return (_cond_); }
+
+/*
+ * predicates.
+ * Unlike predicates defined in ctype.h, these do not accept EOF.
+ */
+_CITRUS_BCS_PRED(isblank, c == ' ' || c == '\t')
+_CITRUS_BCS_PRED(iseol, c == '\n' || c == '\r')
+_CITRUS_BCS_PRED(isspace,
+                _citrus_bcs_isblank(c) || _citrus_bcs_iseol(c) ||
+                c == '\f' || c == '\v')
+_CITRUS_BCS_PRED(isdigit, c >= '0' && c <= '9')
+_CITRUS_BCS_PRED(isupper, c >= 'A' && c <= 'Z')
+_CITRUS_BCS_PRED(islower, c >= 'a' && c <= 'z')
+_CITRUS_BCS_PRED(isalpha, _citrus_bcs_isupper(c) || _citrus_bcs_islower(c))
+_CITRUS_BCS_PRED(isalnum, _citrus_bcs_isdigit(c) || _citrus_bcs_isalpha(c))
+_CITRUS_BCS_PRED(isxdigit,
+                _citrus_bcs_isdigit(c) ||
+                (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))
+
+/*
+ * transliterate between uppercase and lowercase.
+ * Unlike transliterator defined in ctype.h, these do not accept EOF.
+ */
+static __inline uint8_t
+_citrus_bcs_toupper(uint8_t c)
+{
+       return (_citrus_bcs_islower(c) ? (c - 'a' + 'A') : c);
+}
+
+static __inline uint8_t
+_citrus_bcs_tolower(uint8_t c)
+{
+       return (_citrus_bcs_isupper(c) ? (c - 'A' + 'a') : c);
+}
+
+__BEGIN_DECLS
+int _citrus_bcs_strcasecmp(const char * __restrict, const char * __restrict);
+int _citrus_bcs_strncasecmp(const char * __restrict, const char * __restrict,
+                           size_t);
+const char *_citrus_bcs_skip_ws(const char * __restrict);
+const char *_citrus_bcs_skip_nonws(const char * __restrict);
+const char *_citrus_bcs_skip_ws_len(const char * __restrict,
+                                      size_t * __restrict);
+const char *_citrus_bcs_skip_nonws_len(const char * __restrict,
+                                      size_t * __restrict);
+void _citrus_bcs_trunc_rws_len(const char * __restrict, size_t * __restrict);
+void _citrus_bcs_convert_to_lower(char *);
+void _citrus_bcs_convert_to_upper(char *);
+
+long int _citrus_bcs_strtol(
+    const char * __restrict, char ** __restrict, int);
+unsigned long int _citrus_bcs_strtoul(
+    const char * __restrict, char ** __restrict, int);
+
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_bcs_strtol.c b/lib/nbsd_libc/citrus/citrus_bcs_strtol.c
new file mode 100644 (file)
index 0000000..4a30bc8
--- /dev/null
@@ -0,0 +1,59 @@
+/* $NetBSD: citrus_bcs_strtol.c,v 1.2 2009/01/11 02:46:24 christos Exp $ */
+
+/*-
+ * Copyright (c) 2005 The DragonFly Project.  All rights reserved.
+ * Copyright (c) 2003, 2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: citrus_bcs_strtol.c,v 1.2 2009/01/11 02:46:24 christos Exp $");
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#include "citrus_namespace.h"
+#include "citrus_bcs.h"
+
+#define        _FUNCNAME       _bcs_strtol
+#define        __INT           long int
+#define        __INT_MIN       LONG_MIN
+#define        __INT_MAX       LONG_MAX
+
+#undef isspace
+#define isspace(c)     _bcs_isspace(c)
+
+#undef isdigit
+#define isdigit(c)     _bcs_isdigit(c)
+
+#undef isalpha
+#define isalpha(c)     _bcs_isalpha(c)
+
+#undef isupper
+#define isupper(c)     _bcs_isupper(c)
+
+#include "_strtol.h"
diff --git a/lib/nbsd_libc/citrus/citrus_bcs_strtoul.c b/lib/nbsd_libc/citrus/citrus_bcs_strtoul.c
new file mode 100644 (file)
index 0000000..984030f
--- /dev/null
@@ -0,0 +1,64 @@
+/* $NetBSD: citrus_bcs_strtoul.c,v 1.3 2009/01/11 02:46:24 christos Exp $ */
+
+/*-
+ * Copyright (c) 2005 The DragonFly Project.  All rights reserved.
+ * Copyright (c) 2003, 2008 Citrus Project,
+ * 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.
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if !defined(lint)
+__RCSID("$NetBSD: citrus_bcs_strtoul.c,v 1.3 2009/01/11 02:46:24 christos Exp $");
+#endif /* not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#include "citrus_namespace.h"
+#include "citrus_bcs.h"
+
+#define        _FUNCNAME       _bcs_strtoul
+#define        __UINT          unsigned long int
+#define        __UINT_MAX      ULONG_MAX
+
+#undef isspace
+#define isspace(c)     _bcs_isspace(c)
+
+#undef isdigit
+#define isdigit(c)     _bcs_isdigit(c)
+
+#undef isalpha
+#define isalpha(c)     _bcs_isalpha(c)
+
+#undef isupper
+#define isupper(c)     _bcs_isupper(c)
+
+#include "_strtoul.h"
diff --git a/lib/nbsd_libc/citrus/citrus_csmapper.c b/lib/nbsd_libc/citrus/citrus_csmapper.c
new file mode 100644 (file)
index 0000000..bcbc977
--- /dev/null
@@ -0,0 +1,387 @@
+/*     $NetBSD: citrus_csmapper.c,v 1.10 2009/01/11 02:46:24 christos Exp $    */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_csmapper.c,v 1.10 2009/01/11 02:46:24 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+#include <paths.h>
+#include <sys/types.h>
+#include <sys/queue.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_memstream.h"
+#include "citrus_mmap.h"
+#include "citrus_module.h"
+#include "citrus_hash.h"
+#include "citrus_mapper.h"
+#include "citrus_csmapper.h"
+#include "citrus_pivot_file.h"
+#include "citrus_db.h"
+#include "citrus_db_hash.h"
+#include "citrus_lookup.h"
+
+#ifdef _REENTRANT
+static rwlock_t lock = RWLOCK_INITIALIZER;
+#endif
+static struct _citrus_mapper_area *maparea = NULL;
+
+#define CS_ALIAS       _PATH_CSMAPPER "/charset.alias"
+#define CS_PIVOT       _PATH_CSMAPPER "/charset.pivot"
+
+
+/* ---------------------------------------------------------------------- */
+
+static int
+get32(struct _region *r, uint32_t *rval)
+{
+       if (_region_size(r) != 4)
+               return EFTYPE;
+
+       memcpy(rval, _region_head(r), (size_t)4);
+       *rval = be32toh(*rval);
+
+       return 0;
+}
+
+static int
+open_subdb(struct _citrus_db **subdb, struct _citrus_db *db, const char *src)
+{
+       int ret;
+       struct _region r;
+
+       ret = _db_lookup_by_s(db, src, &r, NULL);
+       if (ret)
+               return ret;
+       ret = _db_open(subdb, &r, _CITRUS_PIVOT_SUB_MAGIC, _db_hash_std, NULL);
+       if (ret)
+               return ret;
+
+       return 0;
+}
+
+
+#define NO_SUCH_FILE   EOPNOTSUPP
+static int
+find_best_pivot_pvdb(const char *src, const char *dst, char *pivot,
+                    size_t pvlen, unsigned long *rnorm)
+{
+       int ret, num, i;
+       struct _region fr, r1, r2;
+       struct _citrus_db *db1, *db2, *db3;
+       char buf[LINE_MAX];
+       unsigned long norm;
+       uint32_t val32;
+
+       ret = _map_file(&fr, CS_PIVOT ".pvdb");
+       if (ret) {
+               if (ret == ENOENT)
+                       ret = NO_SUCH_FILE;
+               return ret;
+       }
+       ret = _db_open(&db1, &fr, _CITRUS_PIVOT_MAGIC, _db_hash_std, NULL);
+       if (ret)
+               goto quit1;
+       ret = open_subdb(&db2, db1, src);
+       if (ret)
+               goto quit2;
+
+       num = _db_get_num_entries(db2);
+       *rnorm = ULONG_MAX;
+       for (i = 0; i < num; i++) {
+               /* iterate each pivot */
+               ret = _db_get_entry(db2, i, &r1, &r2);
+               if (ret)
+                       goto quit3;
+               /* r1:pivot name, r2:norm among src and pivot */
+               ret = get32(&r2, &val32);
+               if (ret)
+                       goto quit3;
+               norm = val32;
+               snprintf(buf, sizeof(buf), "%.*s",
+                        (int)_region_size(&r1), (char *)_region_head(&r1));
+               /* buf: pivot name */
+               ret = open_subdb(&db3, db1, buf);
+               if (ret)
+                       goto quit3;
+               if (_db_lookup_by_s(db3, dst, &r2, NULL) != 0)
+                       goto quit4;
+               /* r2: norm among pivot and dst */
+               ret = get32(&r2, &val32);
+               if (ret)
+                       goto quit4;
+               norm += val32;
+               /* judge minimum norm */
+               if (norm < *rnorm) {
+                       *rnorm = norm;
+                       strlcpy(pivot, buf, pvlen);
+               }
+quit4:
+               _db_close(db3);
+               if (ret)
+                       goto quit3;
+       }
+quit3:
+       _db_close(db2);
+quit2:
+       _db_close(db1);
+quit1:
+       _unmap_file(&fr);
+       if (ret)
+               return ret;
+
+       if (*rnorm == ULONG_MAX)
+               return ENOENT;
+
+       return 0;
+}
+
+/* ---------------------------------------------------------------------- */
+
+struct zone {
+       const char *begin, *end;
+};
+
+struct parse_arg {
+       char dst[PATH_MAX];
+       unsigned long norm;
+};
+
+static int
+parse_line(struct parse_arg *pa, struct _region *r)
+{
+       char buf[20];
+       struct zone z1, z2;
+       size_t len;
+
+       len = _region_size(r);
+       z1.begin = _bcs_skip_ws_len(_region_head(r), &len);
+       if (len == 0)
+               return EFTYPE;
+       z1.end = _bcs_skip_nonws_len(z1.begin, &len);
+       if (len == 0)
+               return EFTYPE;
+       z2.begin = _bcs_skip_ws_len(z1.end, &len);
+       if (len == 0)
+               return EFTYPE;
+       z2.end = _bcs_skip_nonws_len(z2.begin, &len);
+
+       /* z1 : dst name, z2 : norm */
+       snprintf(pa->dst, sizeof(pa->dst),
+                "%.*s", (int)(z1.end-z1.begin), z1.begin);
+       snprintf(buf, sizeof(buf),
+                "%.*s", (int)(z2.end-z2.begin), z2.begin);
+       pa->norm = _bcs_strtoul(buf, NULL, 0);
+
+       return 0;
+}
+
+static int
+find_dst(struct parse_arg *pasrc, const char *dst)
+{
+       int ret;
+       struct parse_arg padst;
+       struct _lookup *cl;
+       struct _region data;
+
+       ret = _lookup_seq_open(&cl, CS_PIVOT, _LOOKUP_CASE_IGNORE);
+       if (ret)
+               return ret;
+
+       ret = _lookup_seq_lookup(cl, pasrc->dst, &data);
+       while (ret == 0) {
+               ret = parse_line(&padst, &data);
+               if (ret)
+                       break;
+               if (strcmp(dst, padst.dst) == 0) {
+                       pasrc->norm += padst.norm;
+                       break;
+               }
+               ret = _lookup_seq_next(cl, NULL, &data);
+       }
+       _lookup_seq_close(cl);
+
+       return ret;
+}
+
+static int
+find_best_pivot_lookup(const char *src, const char *dst, char *pivot,
+                      size_t pvlen, unsigned long *rnorm)
+{
+       int ret;
+       struct _lookup *cl;
+       struct _region data;
+       struct parse_arg pa;
+       unsigned long norm_min;
+       char pivot_min[PATH_MAX];
+
+       ret = _lookup_seq_open(&cl, CS_PIVOT, _LOOKUP_CASE_IGNORE);
+       if (ret)
+               return ret;
+
+       norm_min = ULONG_MAX;
+
+       /* find pivot code */
+       ret = _lookup_seq_lookup(cl, src, &data);
+       while (ret == 0) {
+               ret = parse_line(&pa, &data);
+               if (ret)
+                       break;
+               ret = find_dst(&pa, dst);
+               if (ret)
+                       break;
+               if (pa.norm < norm_min) {
+                       norm_min = pa.norm;
+                       strlcpy(pivot_min, pa.dst, sizeof(pivot_min));
+               }
+               ret = _lookup_seq_next(cl, NULL, &data);
+       }
+       _lookup_seq_close(cl);
+
+       if (ret != ENOENT)
+               return ret;
+       if (norm_min == ULONG_MAX)
+               return ENOENT;
+       strlcpy(pivot, pivot_min, pvlen);
+       if (rnorm)
+               *rnorm = norm_min;
+
+       return 0;
+}
+
+static int
+find_best_pivot(const char *src, const char *dst, char *pivot, size_t pvlen,
+               unsigned long *rnorm)
+{
+       int ret;
+
+       ret = find_best_pivot_pvdb(src, dst, pivot, pvlen, rnorm);
+       if (ret == NO_SUCH_FILE)
+               ret = find_best_pivot_lookup(src, dst, pivot, pvlen, rnorm);
+
+       return ret;
+}
+
+static __inline int
+open_serial_mapper(struct _citrus_mapper_area *__restrict ma,
+                  struct _citrus_mapper * __restrict * __restrict rcm,
+                  const char *src, const char *pivot, const char *dst)
+{
+       char buf[PATH_MAX];
+
+       snprintf(buf, sizeof(buf), "%s/%s,%s/%s", src, pivot, pivot, dst);
+
+       return _mapper_open_direct(ma, rcm, "mapper_serial", buf);
+}
+
+static struct _citrus_csmapper *csm_none = NULL;
+static int
+get_none(struct _citrus_mapper_area *__restrict ma,
+        struct _citrus_csmapper *__restrict *__restrict rcsm)
+{
+       int ret;
+
+       rwlock_wrlock(&lock);
+       if (csm_none) {
+               *rcsm = csm_none;
+               ret = 0;
+               goto quit;
+       }
+
+       ret = _mapper_open_direct(ma, &csm_none, "mapper_none", "");
+       if (ret)
+               goto quit;
+       _mapper_set_persistent(csm_none);
+
+       *rcsm = csm_none;
+       ret = 0;
+quit:
+       rwlock_unlock(&lock);
+       return ret;
+}
+
+int
+_citrus_csmapper_open(struct _citrus_csmapper * __restrict * __restrict rcsm,
+                     const char * __restrict src, const char * __restrict dst,
+                     uint32_t flags, unsigned long *rnorm)
+{
+       int ret;
+       char buf1[PATH_MAX], buf2[PATH_MAX], key[PATH_MAX], pivot[PATH_MAX];
+       const char *realsrc, *realdst;
+       unsigned long norm;
+
+       norm = 0;       /* XXX gcc */
+
+       ret = _citrus_mapper_create_area(&maparea, _PATH_CSMAPPER);
+       if (ret)
+               return ret;
+
+       realsrc = _lookup_alias(CS_ALIAS, src, buf1, sizeof(buf1),
+                               _LOOKUP_CASE_IGNORE);
+       realdst = _lookup_alias(CS_ALIAS, dst, buf2, sizeof(buf2),
+                               _LOOKUP_CASE_IGNORE);
+       if (!strcmp(realsrc, realdst)) {
+               ret = get_none(maparea, rcsm);
+               if (ret == 0 && rnorm != NULL)
+                       *rnorm = 0;
+               return ret;
+       }
+
+       snprintf(key, sizeof(key), "%s/%s", realsrc, realdst);
+
+       ret = _mapper_open(maparea, rcsm, key);
+       if (ret == 0) {
+               if (rnorm != NULL)
+                       *rnorm = 0;
+               return 0;
+       }
+       if (ret != ENOENT || (flags & _CSMAPPER_F_PREVENT_PIVOT)!=0)
+               return ret;
+
+       ret = find_best_pivot(realsrc, realdst, pivot, sizeof(pivot), &norm);
+       if (ret)
+               return ret;
+
+       ret = open_serial_mapper(maparea, rcsm, realsrc, pivot, realdst);
+       if (ret == 0 && rnorm != NULL)
+               *rnorm = norm;
+
+       return ret;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_csmapper.h b/lib/nbsd_libc/citrus/citrus_csmapper.h
new file mode 100644 (file)
index 0000000..31b06e4
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: citrus_csmapper.h,v 1.2 2008/02/09 14:56:20 junyoung Exp $     */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_CSMAPPER_H_
+#define _CITRUS_CSMAPPER_H
+
+#define _citrus_csmapper               _citrus_mapper
+#define _citrus_csmapper_close         _citrus_mapper_close
+#define _citrus_csmapper_convert       _citrus_mapper_convert
+#define _citrus_csmapper_init_state    _citrus_mapper_init_state
+#define _citrus_csmapper_get_state_size        _citrus_mapper_get_state_size
+#define _citrus_csmapper_get_src_max   _citrus_mapper_get_src_max
+#define _citrus_csmapper_get_dst_max   _citrus_mapper_get_dst_max
+
+#define _CITRUS_CSMAPPER_F_PREVENT_PIVOT       0x00000001
+__BEGIN_DECLS
+int    _citrus_csmapper_open(struct _citrus_csmapper *__restrict *__restrict,
+                             const char *__restrict,
+                             const char *__restrict, uint32_t,
+                             unsigned long *);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_ctype.c b/lib/nbsd_libc/citrus/citrus_ctype.c
new file mode 100644 (file)
index 0000000..d661c2a
--- /dev/null
@@ -0,0 +1,210 @@
+/*     $NetBSD: citrus_ctype.c,v 1.5 2008/06/14 16:01:07 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)1999, 2000, 2001, 2002 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_ctype.c,v 1.5 2008/06/14 16:01:07 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <stddef.h>
+#include <wchar.h>
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_ctype_fallback.h"
+#include "citrus_none.h"
+#include _CITRUS_DEFAULT_CTYPE_HEADER
+
+_citrus_ctype_rec_t _citrus_ctype_default = {
+       &_CITRUS_DEFAULT_CTYPE_OPS,     /* cc_ops */
+       NULL,                           /* cc_closure */
+       NULL                            /* cc_module */
+};
+
+#ifdef _I18N_DYNAMIC
+
+static int _initctypemodule(_citrus_ctype_t, char const *, _citrus_module_t,
+                           void *, size_t, size_t);
+
+static int
+_initctypemodule(_citrus_ctype_t cc, char const *modname,
+                _citrus_module_t handle, void *variable, size_t lenvar,
+                size_t szpriv)
+{
+       int ret;
+       _citrus_ctype_getops_t getops;
+
+       _DIAGASSERT(cc != NULL);
+
+       cc->cc_module = handle;
+
+       getops = (_citrus_ctype_getops_t)_citrus_find_getops(cc->cc_module,
+                                                            modname,
+                                                            "ctype");
+       if (getops == NULL)
+               return (EINVAL);
+
+       cc->cc_ops = (_citrus_ctype_ops_rec_t *)malloc(sizeof(*cc->cc_ops));
+       if (cc->cc_ops == NULL)
+               return (ENOMEM);
+
+       ret = (*getops)(cc->cc_ops, sizeof(*cc->cc_ops),
+                       _CITRUS_CTYPE_ABI_VERSION);
+       if (ret)
+               goto bad;
+
+       /* If return ABI version is not expected, fixup it here*/
+       switch (cc->cc_ops->co_abi_version) {
+       case 0x00000001:
+               cc->cc_ops->co_btowc = &_citrus_ctype_btowc_fallback;
+               cc->cc_ops->co_wctob = &_citrus_ctype_wctob_fallback;
+               /* FALLTHROUGH */
+       case 0x00000002:
+               /* FALLTHROUGH */
+       default:
+               break;
+       }
+
+       /* validation check */
+       if (cc->cc_ops->co_init == NULL ||
+           cc->cc_ops->co_uninit == NULL ||
+           cc->cc_ops->co_get_mb_cur_max == NULL ||
+           cc->cc_ops->co_mblen == NULL ||
+           cc->cc_ops->co_mbrlen == NULL ||
+           cc->cc_ops->co_mbrtowc == NULL ||
+           cc->cc_ops->co_mbsinit == NULL ||
+           cc->cc_ops->co_mbsrtowcs == NULL ||
+           cc->cc_ops->co_mbstowcs == NULL ||
+           cc->cc_ops->co_mbtowc == NULL ||
+           cc->cc_ops->co_wcrtomb == NULL ||
+           cc->cc_ops->co_wcsrtombs == NULL ||
+           cc->cc_ops->co_wcstombs == NULL ||
+           cc->cc_ops->co_wctomb == NULL ||
+           cc->cc_ops->co_btowc == NULL ||
+           cc->cc_ops->co_wctob == NULL)
+               goto bad;
+
+       /* init and get closure */
+       ret = (*cc->cc_ops->co_init)(
+               &cc->cc_closure, variable, lenvar, szpriv);
+       if (ret)
+               goto bad;
+
+       return (0);
+
+bad:
+       if (cc->cc_ops)
+               free(cc->cc_ops);
+       cc->cc_ops = NULL;
+
+       return (ret);
+}
+
+int
+_citrus_ctype_open(_citrus_ctype_t *rcc,
+                  char const *encname, void *variable, size_t lenvar,
+                  size_t szpriv)
+{
+       int ret;
+       _citrus_module_t handle;
+       _citrus_ctype_t cc;
+
+       _DIAGASSERT(encname != NULL);
+       _DIAGASSERT(!lenvar || variable!=NULL);
+       _DIAGASSERT(rcc != NULL);
+
+       if (!strcmp(encname, _CITRUS_DEFAULT_CTYPE_NAME)) {
+               *rcc = &_citrus_ctype_default;
+               return (0);
+       }
+       ret = _citrus_load_module(&handle, encname);
+       if (ret)
+               return (ret);
+
+       cc = calloc(1, sizeof(*cc));
+       if (!cc) {
+               _citrus_unload_module(handle);
+               return (errno);
+       }
+
+       ret = _initctypemodule(cc, encname, handle, variable, lenvar, szpriv);
+       if (ret) {
+               _citrus_unload_module(cc->cc_module);
+               free(cc);
+               return (ret);
+       }
+
+       *rcc = cc;
+
+       return (0);
+}
+
+void
+_citrus_ctype_close(_citrus_ctype_t cc)
+{
+
+       _DIAGASSERT(cc != NULL);
+
+       if (cc == &_citrus_ctype_default)
+               return;
+       (*cc->cc_ops->co_uninit)(cc->cc_closure);
+       free(cc->cc_ops);
+       _citrus_unload_module(cc->cc_module);
+       free(cc);
+}
+
+#else
+/* !_I18N_DYNAMIC */
+
+int
+/*ARGSUSED*/
+_citrus_ctype_open(_citrus_ctype_t *rcc,
+                  char const *encname, void *variable, size_t lenvar,
+                  size_t szpriv)
+{
+       if (!strcmp(encname, _CITRUS_DEFAULT_CTYPE_NAME)) {
+               *rcc = &_citrus_ctype_default;
+               return (0);
+       }
+       return (EINVAL);
+}
+
+void
+/*ARGSUSED*/
+_citrus_ctype_close(_citrus_ctype_t cc)
+{
+}
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_ctype.h b/lib/nbsd_libc/citrus/citrus_ctype.h
new file mode 100644 (file)
index 0000000..aeb0a2b
--- /dev/null
@@ -0,0 +1,170 @@
+/*     $NetBSD: citrus_ctype.h,v 1.2 2003/03/05 20:18:15 tshiozak Exp $        */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ *
+ */
+
+#ifndef _CITRUS_CTYPE_H_
+#define _CITRUS_CTYPE_H_
+
+#include "citrus_ctype_local.h"
+
+typedef struct _citrus_ctype_rec *_citrus_ctype_t;
+
+__BEGIN_DECLS
+int _citrus_ctype_open(_citrus_ctype_t * __restrict,
+                      char const * __restrict, void * __restrict,
+                      size_t, size_t);
+void _citrus_ctype_close(_citrus_ctype_t);
+__END_DECLS
+
+static __inline unsigned
+_citrus_ctype_get_mb_cur_max(_citrus_ctype_t cc)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops);
+       return (*cc->cc_ops->co_get_mb_cur_max)(cc->cc_closure);
+}
+
+static __inline int
+_citrus_ctype_mblen(_citrus_ctype_t cc, const char *s, size_t n, int *nresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_mblen && nresult);
+       return (*cc->cc_ops->co_mblen)(cc->cc_closure, s, n, nresult);
+}
+
+static __inline int
+_citrus_ctype_mbrlen(_citrus_ctype_t cc, const char *s, size_t n,
+                    void *pspriv, size_t *nresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_mbrlen && nresult);
+       return (*cc->cc_ops->co_mbrlen)(cc->cc_closure, s, n, pspriv, nresult);
+}
+
+static __inline int
+_citrus_ctype_mbrtowc(_citrus_ctype_t cc, wchar_t *pwc, const char *s,
+                     size_t n, void *pspriv, size_t *nresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_mbrtowc);
+       return (*cc->cc_ops->co_mbrtowc)(cc->cc_closure, pwc, s, n, pspriv,
+                                        nresult);
+}
+
+static __inline int
+_citrus_ctype_mbsinit(_citrus_ctype_t cc, void const *pspriv, int *nresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_mbsinit && nresult);
+       return (*cc->cc_ops->co_mbsinit)(cc->cc_closure, pspriv, nresult);
+}
+
+static __inline int
+_citrus_ctype_mbsrtowcs(_citrus_ctype_t cc, wchar_t *pwcs, const char **s,
+                       size_t n, void *pspriv, size_t *nresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_mbsrtowcs && nresult);
+       return (*cc->cc_ops->co_mbsrtowcs)(cc->cc_closure, pwcs, s, n, pspriv,
+                                          nresult);
+}
+
+static __inline int
+_citrus_ctype_mbstowcs(_citrus_ctype_t cc, wchar_t *pwcs, const char *s,
+                      size_t n, size_t *nresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_mbstowcs && nresult);
+       return (*cc->cc_ops->co_mbstowcs)(cc->cc_closure, pwcs, s, n, nresult);
+}
+
+static __inline int
+_citrus_ctype_mbtowc(_citrus_ctype_t cc, wchar_t *pw, const char *s, size_t n,
+                    int *nresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_mbtowc && nresult);
+       return (*cc->cc_ops->co_mbtowc)(cc->cc_closure, pw, s, n, nresult);
+}
+
+static __inline int
+_citrus_ctype_wcrtomb(_citrus_ctype_t cc, char *s, wchar_t wc,
+                     void *pspriv, size_t *nresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_wcrtomb && nresult);
+       return (*cc->cc_ops->co_wcrtomb)(cc->cc_closure, s, wc, pspriv,
+                                        nresult);
+}
+
+static __inline int
+_citrus_ctype_wcsrtombs(_citrus_ctype_t cc, char *s, const wchar_t **ppwcs,
+                       size_t n, void *pspriv, size_t *nresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_wcsrtombs && nresult);
+       return (*cc->cc_ops->co_wcsrtombs)(cc->cc_closure, s, ppwcs, n,
+                                          pspriv, nresult);
+}
+
+static __inline int
+_citrus_ctype_wcstombs(_citrus_ctype_t cc, char *s, const wchar_t *wcs,
+                      size_t n, size_t *nresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_wcstombs && nresult);
+       return (*cc->cc_ops->co_wcstombs)(cc->cc_closure, s, wcs, n, nresult);
+}
+
+static __inline int
+_citrus_ctype_wctomb(_citrus_ctype_t cc, char *s, wchar_t wc, int *nresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_wctomb && nresult);
+       return (*cc->cc_ops->co_wctomb)(cc->cc_closure, s, wc, nresult);
+}
+
+static __inline int
+_citrus_ctype_btowc(_citrus_ctype_t cc, int c, wint_t *wcresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_btowc && wcresult);
+       return (*cc->cc_ops->co_btowc)(cc, c, wcresult);
+}
+
+static __inline int
+_citrus_ctype_wctob(_citrus_ctype_t cc, wint_t c, int *cresult)
+{
+
+       _DIAGASSERT(cc && cc->cc_ops && cc->cc_ops->co_wctob && cresult);
+       return (*cc->cc_ops->co_wctob)(cc, c, cresult);
+}
+
+extern _citrus_ctype_rec_t _citrus_ctype_default;
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_ctype_fallback.c b/lib/nbsd_libc/citrus/citrus_ctype_fallback.c
new file mode 100644 (file)
index 0000000..2adbb8b
--- /dev/null
@@ -0,0 +1,110 @@
+/*     $NetBSD: citrus_ctype_fallback.c,v 1.2 2003/06/27 14:52:25 yamt Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_ctype_fallback.c,v 1.2 2003/06/27 14:52:25 yamt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <assert.h>
+#include <wchar.h>
+#include <stdio.h>
+#include <string.h>
+#include <limits.h>
+
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_ctype_fallback.h"
+
+/*
+ * for ABI version >= 0x00000002
+ */ 
+
+int
+_citrus_ctype_btowc_fallback(_citrus_ctype_rec_t * __restrict cc,
+                            int c, wint_t * __restrict wcresult)
+{
+       char mb;
+       /*
+        * what we need is _PRIVSIZE
+        * and we know that it's smaller than sizeof(mbstate_t).
+        */
+       char pspriv[sizeof(mbstate_t)];
+       wchar_t wc;
+       size_t nr;
+       int err;
+
+       _DIAGASSERT(cc != NULL && cc->cc_closure != NULL);
+
+       if (c == EOF) {
+               *wcresult = WEOF;
+               return 0;
+       }
+
+       memset(&pspriv, 0, sizeof(pspriv));
+       mb = (char)(unsigned)c;
+       err = _citrus_ctype_mbrtowc(cc, &wc, &mb, 1, (void *)&pspriv, &nr);
+       if (!err && (nr == 0 || nr == 1))
+               *wcresult = wc;
+       else
+               *wcresult = WEOF;
+
+       return 0;
+}
+
+int
+_citrus_ctype_wctob_fallback(_citrus_ctype_rec_t * __restrict cc,
+                            wint_t wc, int * __restrict cresult)
+{
+       /*
+        * what we need is _PRIVSIZE
+        * and we know that it's smaller than sizeof(mbstate_t).
+        */
+       char pspriv[sizeof(mbstate_t)];
+       char buf[MB_LEN_MAX];
+       size_t nr;
+       int err;
+
+       _DIAGASSERT(cc != NULL && cc->cc_closure != NULL);
+
+       if (wc == WEOF) {
+               *cresult = EOF;
+               return 0;
+       }
+       memset(&pspriv, 0, sizeof(pspriv));
+       err = _citrus_ctype_wcrtomb(cc, buf, (wchar_t)wc, (void *)&pspriv, &nr);
+       if (!err && nr == 1)
+               *cresult = buf[0];
+       else
+               *cresult = EOF;
+
+       return 0;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_ctype_fallback.h b/lib/nbsd_libc/citrus/citrus_ctype_fallback.h
new file mode 100644 (file)
index 0000000..81a20c7
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: citrus_ctype_fallback.h,v 1.1 2003/03/05 20:18:15 tshiozak Exp $       */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_CTYPE_FALLBACK_H_
+#define _CITRUS_CTYPE_FALLBACK_H_
+
+/* fallback functions for 0x00000002 */
+int _citrus_ctype_btowc_fallback(_citrus_ctype_rec_t * __restrict,
+                                int, wint_t * __restrict);
+int _citrus_ctype_wctob_fallback(_citrus_ctype_rec_t * __restrict,
+                                wint_t, int * __restrict);
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_ctype_local.h b/lib/nbsd_libc/citrus/citrus_ctype_local.h
new file mode 100644 (file)
index 0000000..4969946
--- /dev/null
@@ -0,0 +1,198 @@
+/*     $NetBSD: citrus_ctype_local.h,v 1.3 2008/02/09 14:56:20 junyoung Exp $  */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ *
+ */
+
+#ifndef _CITRUS_CTYPE_LOCAL_H_
+#define _CITRUS_CTYPE_LOCAL_H_
+
+#define _CITRUS_CTYPE_GETOPS_FUNC_BASE(_n_)                            \
+int _n_(_citrus_ctype_ops_rec_t *, size_t, uint32_t)
+#define _CITRUS_CTYPE_GETOPS_FUNC(_n_)                                 \
+_CITRUS_CTYPE_GETOPS_FUNC_BASE(_citrus_##_n_##_ctype_getops)
+
+#define _CITRUS_CTYPE_DECLS(_e_)                                             \
+static int     _citrus_##_e_##_ctype_init                                    \
+       (void ** __restrict, void * __restrict, size_t, size_t);              \
+static void    _citrus_##_e_##_ctype_uninit(void *);                         \
+static unsigned        _citrus_##_e_##_ctype_get_mb_cur_max(void *);                 \
+static int     _citrus_##_e_##_ctype_mblen(void * __restrict,                \
+                                    const char * __restrict,                 \
+                                    size_t, int * __restrict);               \
+static int     _citrus_##_e_##_ctype_mbrlen(void * __restrict,               \
+                                     const char * __restrict,                \
+                                     size_t, void * __restrict,              \
+                                     size_t * __restrict);                   \
+static int     _citrus_##_e_##_ctype_mbrtowc(void * __restrict,              \
+                                      wchar_t * __restrict,                  \
+                                      const char * __restrict, size_t,       \
+                                      void * __restrict,                     \
+                                      size_t * __restrict);                  \
+static int     _citrus_##_e_##_ctype_mbsinit(void * __restrict,              \
+                                      void const * __restrict,               \
+                                      int * __restrict);                     \
+static int     _citrus_##_e_##_ctype_mbsrtowcs(void * __restrict,            \
+                                        wchar_t * __restrict,                \
+                                        const char ** __restrict,            \
+                                        size_t, void * __restrict,           \
+                                        size_t * __restrict);                \
+static int     _citrus_##_e_##_ctype_mbstowcs(void * __restrict,             \
+                                       wchar_t * __restrict,                 \
+                                       const char * __restrict,              \
+                                       size_t, size_t * __restrict);         \
+static int     _citrus_##_e_##_ctype_mbtowc(void * __restrict,               \
+                                     wchar_t * __restrict,                   \
+                                     const char * __restrict,                \
+                                     size_t, int * __restrict);              \
+static int     _citrus_##_e_##_ctype_wcrtomb(void * __restrict,              \
+                                      char * __restrict, wchar_t,            \
+                                      void * __restrict,                     \
+                                      size_t * __restrict);                  \
+static int     _citrus_##_e_##_ctype_wcsrtombs(void * __restrict,            \
+                                        char * __restrict,                   \
+                                        const wchar_t ** __restrict,         \
+                                        size_t, void * __restrict,           \
+                                        size_t * __restrict);                \
+static int     _citrus_##_e_##_ctype_wcstombs(void * __restrict,             \
+                                       char * __restrict,                    \
+                                       const wchar_t * __restrict,           \
+                                       size_t, size_t * __restrict);         \
+static int     _citrus_##_e_##_ctype_wctomb(void * __restrict,               \
+                                     char * __restrict,                      \
+                                     wchar_t, int * __restrict);             \
+static int     _citrus_##_e_##_ctype_btowc(_citrus_ctype_rec_t * __restrict, \
+                                     int, wint_t * __restrict);              \
+static int     _citrus_##_e_##_ctype_wctob(_citrus_ctype_rec_t * __restrict, \
+                                     wint_t, int * __restrict)
+
+#define _CITRUS_CTYPE_DEF_OPS(_e_)                                     \
+_citrus_ctype_ops_rec_t _citrus_##_e_##_ctype_ops = {                  \
+       /* co_abi_version */    _CITRUS_CTYPE_ABI_VERSION,              \
+       /* co_init */           &_citrus_##_e_##_ctype_init,            \
+       /* co_uninit */         &_citrus_##_e_##_ctype_uninit,          \
+       /* co_get_mb_cur_max */ &_citrus_##_e_##_ctype_get_mb_cur_max,  \
+       /* co_mblen */          &_citrus_##_e_##_ctype_mblen,           \
+       /* co_mbrlen */         &_citrus_##_e_##_ctype_mbrlen,          \
+       /* co_mbrtowc */        &_citrus_##_e_##_ctype_mbrtowc,         \
+       /* co_mbsinit */        &_citrus_##_e_##_ctype_mbsinit,         \
+       /* co_mbsrtowcs */      &_citrus_##_e_##_ctype_mbsrtowcs,       \
+       /* co_mbstowcs */       &_citrus_##_e_##_ctype_mbstowcs,        \
+       /* co_mbtowc */         &_citrus_##_e_##_ctype_mbtowc,          \
+       /* co_wcrtomb */        &_citrus_##_e_##_ctype_wcrtomb,         \
+       /* co_wcsrtombs */      &_citrus_##_e_##_ctype_wcsrtombs,       \
+       /* co_wcstombs */       &_citrus_##_e_##_ctype_wcstombs,        \
+       /* co_wctomb */         &_citrus_##_e_##_ctype_wctomb,          \
+       /* co_btowc */          &_citrus_##_e_##_ctype_btowc,           \
+       /* co_wctob */          &_citrus_##_e_##_ctype_wctob            \
+}
+
+typedef struct _citrus_ctype_ops_rec   _citrus_ctype_ops_rec_t;
+typedef struct _citrus_ctype_rec       _citrus_ctype_rec_t;
+
+typedef int    (*_citrus_ctype_init_t)
+       (void ** __restrict, void * __restrict, size_t, size_t);
+typedef void   (*_citrus_ctype_uninit_t)(void *);
+typedef unsigned (*_citrus_ctype_get_mb_cur_max_t)(void *);
+typedef int    (*_citrus_ctype_mblen_t)
+       (void * __restrict, const char * __restrict, size_t, int * __restrict);
+typedef int    (*_citrus_ctype_mbrlen_t)
+       (void * __restrict, const char * __restrict, size_t,
+        void * __restrict, size_t * __restrict);
+typedef int    (*_citrus_ctype_mbrtowc_t)
+       (void * __restrict, wchar_t * __restrict, const char * __restrict,
+        size_t, void * __restrict, size_t * __restrict);
+typedef int    (*_citrus_ctype_mbsinit_t)
+       (void * __restrict, const void * __restrict, int * __restrict);
+typedef int    (*_citrus_ctype_mbsrtowcs_t)
+       (void * __restrict, wchar_t * __restrict, const char ** __restrict,
+        size_t, void * __restrict,
+        size_t * __restrict);
+typedef int    (*_citrus_ctype_mbstowcs_t)
+       (void * __restrict, wchar_t * __restrict, const char * __restrict,
+        size_t, size_t * __restrict);
+typedef int    (*_citrus_ctype_mbtowc_t)
+       (void * __restrict, wchar_t * __restrict, const char * __restrict,
+        size_t, int * __restrict);
+typedef int    (*_citrus_ctype_wcrtomb_t)
+       (void * __restrict, char * __restrict, wchar_t, void * __restrict,
+        size_t * __restrict);
+typedef int    (*_citrus_ctype_wcsrtombs_t)
+       (void * __restrict, char * __restrict, const wchar_t ** __restrict,
+        size_t, void * __restrict, size_t * __restrict);
+typedef int    (*_citrus_ctype_wcstombs_t)
+       (void * __restrict, char * __restrict, const wchar_t * __restrict,
+        size_t, size_t * __restrict);
+typedef int    (*_citrus_ctype_wctomb_t)
+       (void * __restrict, char * __restrict, wchar_t, int * __restrict);
+typedef int    (*_citrus_ctype_btowc_t)
+       (_citrus_ctype_rec_t * __restrict, int, wint_t * __restrict);
+typedef int    (*_citrus_ctype_wctob_t)
+       (_citrus_ctype_rec_t * __restrict, wint_t, int * __restrict);
+
+/*
+ * ABI Version change log:
+ *   0x00000001
+ *     initial version
+ *   0x00000002
+ *     ops record:     btowc and wctob are added.
+ *     ctype record:   unchanged.
+ */
+#define _CITRUS_CTYPE_ABI_VERSION      0x00000002
+struct _citrus_ctype_ops_rec {
+       uint32_t                        co_abi_version;
+       /* version 0x00000001 */
+       _citrus_ctype_init_t            co_init;
+       _citrus_ctype_uninit_t          co_uninit;
+       _citrus_ctype_get_mb_cur_max_t  co_get_mb_cur_max;
+       _citrus_ctype_mblen_t           co_mblen;
+       _citrus_ctype_mbrlen_t          co_mbrlen;
+       _citrus_ctype_mbrtowc_t         co_mbrtowc;
+       _citrus_ctype_mbsinit_t         co_mbsinit;
+       _citrus_ctype_mbsrtowcs_t       co_mbsrtowcs;
+       _citrus_ctype_mbstowcs_t        co_mbstowcs;
+       _citrus_ctype_mbtowc_t          co_mbtowc;
+       _citrus_ctype_wcrtomb_t         co_wcrtomb;
+       _citrus_ctype_wcsrtombs_t       co_wcsrtombs;
+       _citrus_ctype_wcstombs_t        co_wcstombs;
+       _citrus_ctype_wctomb_t          co_wctomb;
+       /* version 0x00000002 */
+       _citrus_ctype_btowc_t           co_btowc;
+       _citrus_ctype_wctob_t           co_wctob;
+};
+
+#define _CITRUS_DEFAULT_CTYPE_NAME     "NONE"
+#define _CITRUS_DEFAULT_CTYPE_OPS      _citrus_NONE_ctype_ops
+#define _CITRUS_DEFAULT_CTYPE_HEADER   "citrus_none.h"
+
+typedef _CITRUS_CTYPE_GETOPS_FUNC_BASE((*_citrus_ctype_getops_t));
+struct _citrus_ctype_rec {
+       _citrus_ctype_ops_rec_t *cc_ops;
+       void                    *cc_closure;
+       _citrus_module_t        cc_module;
+};
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_ctype_template.h b/lib/nbsd_libc/citrus/citrus_ctype_template.h
new file mode 100644 (file)
index 0000000..c61dedf
--- /dev/null
@@ -0,0 +1,767 @@
+/*     $NetBSD: citrus_ctype_template.h,v 1.35 2008/02/09 14:56:20 junyoung Exp $      */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Borman at Krystal Technologies.
+ *
+ * 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. 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.
+ */
+
+
+/*
+ * CAUTION: THIS IS NOT STANDALONE FILE
+ *
+ * function templates of ctype encoding handler for each encodings.
+ *
+ * you need to define the macros below:
+ *
+ *   _FUNCNAME(method) :
+ *     It should convine the real function name for the method.
+ *      e.g. _FUNCNAME(mbrtowc) should be expanded to
+ *             _EUC_ctype_mbrtowc
+ *           for EUC locale.
+ *
+ *   _CEI_TO_STATE(cei, method) :
+ *     It should be expanded to the pointer of the method-internal state
+ *     structures.
+ *     e.g. _CEI_TO_STATE(cei, mbrtowc) might be expanded to
+ *             (cei)->states.s_mbrtowc
+ *     This structure may use if the function is called as
+ *           mbrtowc(&wc, s, n, NULL);
+ *     Such individual structures are needed by:
+ *           mblen
+ *           mbrlen
+ *           mbrtowc
+ *           mbtowc
+ *           mbsrtowcs
+ *           wcrtomb
+ *           wcsrtombs
+ *           wctomb
+ *     These need to be keeped in the ctype encoding information structure,
+ *     pointed by "cei".
+ *
+ *   _ENCODING_INFO :
+ *     It should be expanded to the name of the encoding information structure.
+ *     e.g. For EUC encoding, this macro is expanded to _EUCInfo.
+ *     Encoding information structure need to contain the common informations
+ *     for the codeset.
+ *
+ *   _ENCODING_STATE :
+ *     It should be expanded to the name of the encoding state structure.
+ *     e.g. For EUC encoding, this macro is expanded to _EUCState.
+ *     Encoding state structure need to contain the context-dependent states,
+ *     which are "unpacked-form" of mbstate_t type and keeped during sequent
+ *     calls of mb/wc functions,
+ *
+ *   _ENCODING_IS_STATE_DEPENDENT :
+ *     If the encoding is state dependent, this should be expanded to
+ *     non-zero integral value.  Otherwise, 0.
+ *
+ *   _STATE_NEEDS_EXPLICIT_INIT(ps) :
+ *     some encodings, states needs some explicit initialization.
+ *     (ie. initialization with memset isn't enough.)
+ *     If the encoding state pointed by "ps" needs to be initialized
+ *     explicitly, return non-zero. Otherwize, 0.
+ *
+ */
+
+
+/* prototypes */
+
+__BEGIN_DECLS
+static void _FUNCNAME(init_state)(_ENCODING_INFO * __restrict,
+                                 _ENCODING_STATE * __restrict);
+static void _FUNCNAME(pack_state)(_ENCODING_INFO * __restrict,
+                                 void * __restrict,
+                                 const _ENCODING_STATE * __restrict);
+static void _FUNCNAME(unpack_state)(_ENCODING_INFO * __restrict,
+                                   _ENCODING_STATE * __restrict,
+                                   const void * __restrict);
+#if _ENCODING_IS_STATE_DEPENDENT
+static int _FUNCNAME(put_state_reset)(_ENCODING_INFO * __restrict,
+                                     char * __restrict, size_t,
+                                     _ENCODING_STATE * __restrict,
+                                     size_t * __restrict);
+#endif
+
+/*
+ * standard form of mbrtowc_priv.
+ *
+ * note (differences from real mbrtowc):
+ *   - 3rd parameter is not "const char *s" but "const char **s".
+ *     after the call of the function, *s will point the first byte of
+ *     the next character.
+ *   - additional 4th parameter is the size of src buffer.
+ *   - 5th parameter is unpacked encoding-dependent state structure.
+ *   - additional 6th parameter is the storage to be stored
+ *     the return value in the real mbrtowc context.
+ *   - return value means "errno" in the real mbrtowc context.
+ */
+
+static int _FUNCNAME(mbrtowc_priv)(_ENCODING_INFO * __restrict,
+                                  wchar_t * __restrict,
+                                  const char ** __restrict,
+                                  size_t, _ENCODING_STATE * __restrict,
+                                  size_t * __restrict);
+
+/*
+ * standard form of wcrtomb_priv.
+ *
+ * note (differences from real wcrtomb):
+ *   - additional 3th parameter is the size of src buffer.
+ *   - 5th parameter is unpacked encoding-dependent state structure.
+ *   - additional 6th parameter is the storage to be stored
+ *     the return value in the real mbrtowc context.
+ *   - return value means "errno" in the real wcrtomb context.
+ *   - caller should ensure that 2nd parameter isn't NULL.
+ *     (XXX inconsist with mbrtowc_priv)
+ */
+
+static int _FUNCNAME(wcrtomb_priv)(_ENCODING_INFO * __restrict,
+                                  char * __restrict, size_t, wchar_t,
+                                  _ENCODING_STATE * __restrict,
+                                  size_t * __restrict);
+__END_DECLS
+
+
+/*
+ * macros
+ */
+
+#define _TO_CEI(_cl_)  ((_CTYPE_INFO*)(_cl_))
+
+
+/*
+ * templates
+ */
+
+/* internal routines */
+
+static __inline int
+_FUNCNAME(mbtowc_priv)(_ENCODING_INFO * __restrict ei,
+                      wchar_t * __restrict pwc,  const char * __restrict s,
+                      size_t n, _ENCODING_STATE * __restrict psenc,
+                      int * __restrict nresult)
+{
+       _ENCODING_STATE state;
+       size_t nr;
+       int err = 0;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       if (s == NULL) {
+               _FUNCNAME(init_state)(ei, psenc);
+               *nresult = _ENCODING_IS_STATE_DEPENDENT;
+               return (0);
+       }
+
+       state = *psenc;
+       err = _FUNCNAME(mbrtowc_priv)(ei, pwc, (const char **)&s, n, psenc, &nr);
+       if (nr == (size_t)-2)
+               err = EILSEQ;
+       if (err) {
+               /* In error case, we should restore the state. */
+               *psenc = state;
+               *nresult = -1;
+               return (err);
+       }
+
+       *nresult = (int)nr;
+
+       return (0);
+}
+
+static int
+_FUNCNAME(mbsrtowcs_priv)(_ENCODING_INFO * __restrict ei,
+                         wchar_t * __restrict pwcs,
+                         const char ** __restrict s,
+                         size_t n, _ENCODING_STATE * __restrict psenc,
+                         size_t * __restrict nresult)
+{
+       int err, cnt;
+       size_t siz;
+       const char *s0;
+       size_t mbcurmax;
+
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(s == NULL);
+       _DIAGASSERT(*s == NULL);
+
+       /* if pwcs is NULL, ignore n */
+       if (pwcs == NULL)
+               n = 1; /* arbitrary >0 value */
+
+       err = cnt = 0;
+       s0 = *s; /* to keep *s unchanged for now, use copy instead. */
+       mbcurmax = _ENCODING_MB_CUR_MAX(ei);
+       while (n > 0) {
+               err = _FUNCNAME(mbrtowc_priv)(ei, pwcs, &s0, mbcurmax,
+                                             psenc, &siz);
+               if (siz == (size_t)-2)
+                       err = EILSEQ;
+               if (err) {
+                       cnt = -1;
+                       goto bye;
+               }
+               switch (siz) {
+               case 0:
+                       if (pwcs) {
+                               _FUNCNAME(init_state)(ei, psenc);
+                       }
+                       s0 = 0;
+                       goto bye;
+               default:
+                       if (pwcs) {
+                               pwcs++;
+                               n--;
+                       }
+                       cnt++;
+                       break;
+               }
+       }
+bye:
+       if (pwcs)
+               *s = s0;
+
+       *nresult = (size_t)cnt;
+
+       return err;
+}
+
+
+static int
+_FUNCNAME(wcsrtombs_priv)(_ENCODING_INFO * __restrict ei, char * __restrict s,
+                         const wchar_t ** __restrict pwcs,
+                         size_t n, _ENCODING_STATE * __restrict psenc,
+                         size_t * __restrict nresult)
+{
+       int cnt = 0, err;
+       char buf[MB_LEN_MAX];
+       size_t siz;
+       const wchar_t* pwcs0;
+#if _ENCODING_IS_STATE_DEPENDENT
+       _ENCODING_STATE state;
+#endif
+
+       pwcs0 = *pwcs;
+
+       if (!s)
+               n = 1;
+
+       while (n > 0) {
+#if _ENCODING_IS_STATE_DEPENDENT
+               state = *psenc;
+#endif
+               err = _FUNCNAME(wcrtomb_priv)(ei, buf, sizeof(buf),
+                                             *pwcs0, psenc, &siz);
+               if (siz == (size_t)-1) {
+                       *nresult = siz;
+                       return (err);
+               }
+
+               if (s) {
+                       if (n < siz) {
+#if _ENCODING_IS_STATE_DEPENDENT
+                               *psenc = state;
+#endif
+                               break;
+                       }
+                       memcpy(s, buf, siz);
+                       s += siz;
+                       n -= siz;
+               }
+               cnt += siz;
+               if (!*pwcs0) {
+                       if (s) {
+                               _FUNCNAME(init_state)(ei, psenc);
+                       }
+                       pwcs0 = 0;
+                       cnt--; /* don't include terminating null */
+                       break;
+               }
+               pwcs0++;
+       }
+       if (s)
+               *pwcs = pwcs0;
+
+       *nresult = (size_t)cnt;
+       return (0);
+}
+
+
+/* ----------------------------------------------------------------------
+ * templates for public functions
+ */
+
+#define _RESTART_BEGIN(_func_, _cei_, _pspriv_, _pse_)                 \
+do {                                                                   \
+       _ENCODING_STATE _state;                                         \
+       do {                                                            \
+               if (_pspriv_ == NULL) {                                 \
+                       _pse_ = &_CEI_TO_STATE(_cei_, _func_);          \
+                       if (_STATE_NEEDS_EXPLICIT_INIT(_pse_))          \
+                           _FUNCNAME(init_state)(_CEI_TO_EI(_cei_),    \
+                                                       (_pse_));       \
+               } else {                                                \
+                       _pse_ = &_state;                                \
+                       _FUNCNAME(unpack_state)(_CEI_TO_EI(_cei_),      \
+                                               _pse_, _pspriv_);       \
+               }                                                       \
+       } while (/*CONSTCOND*/0)
+
+#define _RESTART_END(_func_, _cei_, _pspriv_, _pse_)                   \
+       if (_pspriv_ != NULL) {                                         \
+               _FUNCNAME(pack_state)(_CEI_TO_EI(_cei_), _pspriv_,      \
+                                     _pse_);                           \
+       }                                                               \
+} while (/*CONSTCOND*/0)
+
+int
+_FUNCNAME(ctype_getops)(_citrus_ctype_ops_rec_t *ops, size_t lenops,
+                       uint32_t expected_version)
+{
+       if (expected_version<_CITRUS_CTYPE_ABI_VERSION || lenops<sizeof(*ops))
+               return (EINVAL);
+
+       memcpy(ops, &_FUNCNAME(ctype_ops), sizeof(_FUNCNAME(ctype_ops)));
+
+       return (0);
+}
+
+static int
+_FUNCNAME(ctype_init)(void ** __restrict cl,
+                     void * __restrict var, size_t lenvar, size_t lenps)
+{
+       _CTYPE_INFO *cei;
+
+       _DIAGASSERT(cl != NULL);
+
+       /* sanity check to avoid overruns */
+       if (sizeof(_ENCODING_STATE) > lenps)
+               return (EINVAL);
+
+       cei = calloc(1, sizeof(_CTYPE_INFO));
+       if (cei == NULL)
+               return (ENOMEM);
+
+       *cl = (void *)cei;
+
+       return _FUNCNAME(encoding_module_init)(_CEI_TO_EI(cei), var, lenvar);
+}
+
+static void
+_FUNCNAME(ctype_uninit)(void *cl)
+{
+       if (cl) {
+               _FUNCNAME(encoding_module_uninit)(_CEI_TO_EI(_TO_CEI(cl)));
+               free(cl);
+       }
+}
+
+static unsigned
+/*ARGSUSED*/
+_FUNCNAME(ctype_get_mb_cur_max)(void *cl)
+{
+       return _ENCODING_MB_CUR_MAX(_CEI_TO_EI(_TO_CEI(cl)));
+}
+
+static int
+_FUNCNAME(ctype_mblen)(void * __restrict cl,
+                      const char * __restrict s, size_t n,
+                      int * __restrict nresult)
+{
+       _ENCODING_STATE *psenc;
+       _ENCODING_INFO *ei;
+
+       _DIAGASSERT(cl != NULL);
+
+       psenc = &_CEI_TO_STATE(_TO_CEI(cl), mblen);
+       ei = _CEI_TO_EI(_TO_CEI(cl));
+       if (_STATE_NEEDS_EXPLICIT_INIT(psenc))
+               _FUNCNAME(init_state)(ei, psenc);
+       return _FUNCNAME(mbtowc_priv)(ei, NULL, s, n, psenc, nresult);
+}
+
+static int
+_FUNCNAME(ctype_mbrlen)(void * __restrict cl, const char * __restrict s,
+                       size_t n, void * __restrict pspriv,
+                       size_t * __restrict nresult)
+{
+       _ENCODING_STATE *psenc;
+       _ENCODING_INFO *ei;
+       int err = 0;
+
+       _DIAGASSERT(cl != NULL);
+
+       ei = _CEI_TO_EI(_TO_CEI(cl));
+       _RESTART_BEGIN(mbrlen, _TO_CEI(cl), pspriv, psenc);
+       if (s == NULL) {
+               _FUNCNAME(init_state)(ei, psenc);
+               *nresult = 0;
+       } else {
+               err = _FUNCNAME(mbrtowc_priv)(ei, NULL, (const char **)&s, n,
+                   (void *)psenc, nresult);
+       }
+       _RESTART_END(mbrlen, _TO_CEI(cl), pspriv, psenc);
+
+       return (err);
+}
+
+static int
+_FUNCNAME(ctype_mbrtowc)(void * __restrict cl, wchar_t * __restrict pwc,
+                        const char * __restrict s, size_t n,
+                        void * __restrict pspriv, size_t * __restrict nresult)
+{
+       _ENCODING_STATE *psenc;
+       _ENCODING_INFO *ei;
+       int err = 0;
+
+       _DIAGASSERT(cl != NULL);
+
+       ei = _CEI_TO_EI(_TO_CEI(cl));
+       _RESTART_BEGIN(mbrtowc, _TO_CEI(cl), pspriv, psenc);
+       if (s == NULL) {
+               _FUNCNAME(init_state)(ei, psenc);
+               *nresult = 0;
+       } else {
+               err = _FUNCNAME(mbrtowc_priv)(ei, pwc, (const char **)&s, n,
+                   (void *)psenc, nresult);
+       }
+       _RESTART_END(mbrtowc, _TO_CEI(cl), pspriv, psenc);
+
+       return (err);
+}
+
+static int
+/*ARGSUSED*/
+_FUNCNAME(ctype_mbsinit)(void * __restrict cl, const void * __restrict pspriv,
+                        int * __restrict nresult)
+{
+       _ENCODING_STATE state;
+
+       if (pspriv == NULL) {
+               *nresult = 1;
+               return (0);
+       }
+
+       _FUNCNAME(unpack_state)(_CEI_TO_EI(_TO_CEI(cl)), &state, pspriv);
+
+       *nresult = (state.chlen == 0); /* XXX: FIXME */
+
+       return (0);
+}
+
+static int
+_FUNCNAME(ctype_mbsrtowcs)(void * __restrict cl, wchar_t * __restrict pwcs,
+                          const char ** __restrict s, size_t n,
+                          void * __restrict pspriv,
+                          size_t * __restrict nresult)
+{
+       _ENCODING_STATE *psenc;
+       _ENCODING_INFO *ei;
+       int err = 0;
+
+       _DIAGASSERT(cl != NULL);
+
+       ei = _CEI_TO_EI(_TO_CEI(cl));
+       _RESTART_BEGIN(mbsrtowcs, _TO_CEI(cl), pspriv, psenc);
+       err = _FUNCNAME(mbsrtowcs_priv)(ei, pwcs, s, n, psenc, nresult);
+       _RESTART_END(mbsrtowcs, _TO_CEI(cl), pspriv, psenc);
+
+       return (err);
+}
+
+static int
+_FUNCNAME(ctype_mbstowcs)(void * __restrict cl, wchar_t * __restrict pwcs,
+                         const char * __restrict s, size_t n,
+                         size_t * __restrict nresult)
+{
+       int err;
+       _ENCODING_STATE state;
+       _ENCODING_INFO *ei;
+
+       _DIAGASSERT(cl != NULL);
+
+       ei = _CEI_TO_EI(_TO_CEI(cl));
+       _FUNCNAME(init_state)(ei, &state);
+       err = _FUNCNAME(mbsrtowcs_priv)(ei, pwcs, (const char **)&s, n,
+                                       &state, nresult);
+       if (*nresult == (size_t)-2) {
+               err = EILSEQ;
+               *nresult = (size_t)-1;
+       }
+
+       return (err);
+}
+
+static int
+_FUNCNAME(ctype_mbtowc)(void * __restrict cl, wchar_t * __restrict pwc,
+                       const char * __restrict s, size_t n,
+                       int * __restrict nresult)
+{
+       _ENCODING_STATE *psenc;
+       _ENCODING_INFO *ei;
+
+       _DIAGASSERT(cl != NULL);
+
+       psenc = &_CEI_TO_STATE(_TO_CEI(cl), mbtowc);
+       ei = _CEI_TO_EI(_TO_CEI(cl));
+       if (_STATE_NEEDS_EXPLICIT_INIT(psenc))
+               _FUNCNAME(init_state)(ei, psenc);
+       return _FUNCNAME(mbtowc_priv)(ei, pwc, s, n, psenc, nresult);
+}
+
+static int
+_FUNCNAME(ctype_wcrtomb)(void * __restrict cl, char * __restrict s, wchar_t wc,
+                        void * __restrict pspriv, size_t * __restrict nresult)
+{
+       _ENCODING_STATE *psenc;
+       char buf[MB_LEN_MAX];
+       int err = 0;
+       size_t sz;
+#if _ENCODING_IS_STATE_DEPENDENT
+       size_t rsz = 0;
+#endif
+
+       _DIAGASSERT(cl != NULL);
+
+       if (s == NULL) {
+               /*
+                * use internal buffer.
+                */
+               s = buf;
+               wc = L'\0'; /* SUSv3 */
+       }
+
+       _RESTART_BEGIN(wcrtomb, _TO_CEI(cl), pspriv, psenc);
+       sz = _ENCODING_MB_CUR_MAX(_CEI_TO_EI(_TO_CEI(cl)));
+#if _ENCODING_IS_STATE_DEPENDENT
+       if (wc == L'\0') {
+               /* reset state */
+               err = _FUNCNAME(put_state_reset)(_CEI_TO_EI(_TO_CEI(cl)), s,
+                                                sz, psenc, &rsz);
+               if (err) {
+                       *nresult = -1;
+                       goto quit;
+               }
+               s += rsz;
+               sz -= rsz;
+       }
+#endif
+       err = _FUNCNAME(wcrtomb_priv)(_CEI_TO_EI(_TO_CEI(cl)), s, sz,
+                                     wc, psenc, nresult);
+#if _ENCODING_IS_STATE_DEPENDENT
+       if (err == 0)
+               *nresult += rsz;
+quit:
+#endif
+       if (err == E2BIG)
+               err = EINVAL;
+       _RESTART_END(wcrtomb, _TO_CEI(cl), pspriv, psenc);
+
+       return err;
+}
+
+static int
+/*ARGSUSED*/
+_FUNCNAME(ctype_wcsrtombs)(void * __restrict cl, char * __restrict s,
+                          const wchar_t ** __restrict pwcs, size_t n,
+                          void * __restrict pspriv,
+                          size_t * __restrict nresult)
+{
+       _ENCODING_STATE *psenc;
+       _ENCODING_INFO *ei;
+       int err = 0;
+
+       _DIAGASSERT(cl != NULL);
+
+       ei = _CEI_TO_EI(_TO_CEI(cl));
+       _RESTART_BEGIN(wcsrtombs, _TO_CEI(cl), pspriv, psenc);
+       err = _FUNCNAME(wcsrtombs_priv)(ei, s, pwcs, n, psenc, nresult);
+       _RESTART_END(wcsrtombs, _TO_CEI(cl), pspriv, psenc);
+
+       return err;
+}
+
+static int
+/*ARGSUSED*/
+_FUNCNAME(ctype_wcstombs)(void * __restrict cl, char * __restrict s,
+                         const wchar_t * __restrict pwcs, size_t n,
+                         size_t * __restrict nresult)
+{
+       _ENCODING_STATE state;
+       _ENCODING_INFO *ei;
+       int err;
+
+       _DIAGASSERT(cl != NULL);
+
+       ei = _CEI_TO_EI(_TO_CEI(cl));
+       _FUNCNAME(init_state)(ei, &state);
+       err = _FUNCNAME(wcsrtombs_priv)(ei, s, (const wchar_t **)&pwcs, n,
+                                       &state, nresult);
+
+       return err;
+}
+
+static int
+_FUNCNAME(ctype_wctomb)(void * __restrict cl, char * __restrict s, wchar_t wc,
+                       int * __restrict nresult)
+{
+       _ENCODING_STATE *psenc;
+       _ENCODING_INFO *ei;
+       size_t nr, sz;
+#if _ENCODING_IS_STATE_DEPENDENT
+       size_t rsz = 0;
+#endif
+       int err = 0;
+
+       _DIAGASSERT(cl != NULL);
+
+       ei = _CEI_TO_EI(_TO_CEI(cl));
+       psenc = &_CEI_TO_STATE(_TO_CEI(cl), wctomb);
+       if (_STATE_NEEDS_EXPLICIT_INIT(psenc))
+               _FUNCNAME(init_state)(ei, psenc);
+       if (s == NULL) {
+               _FUNCNAME(init_state)(ei, psenc);
+               *nresult = _ENCODING_IS_STATE_DEPENDENT;
+               return 0;
+       }
+       sz = _ENCODING_MB_CUR_MAX(_CEI_TO_EI(_TO_CEI(cl)));
+#if _ENCODING_IS_STATE_DEPENDENT
+       if (wc == L'\0') {
+               /* reset state */
+               err = _FUNCNAME(put_state_reset)(_CEI_TO_EI(_TO_CEI(cl)), s,
+                                                sz, psenc, &rsz);
+               if (err) {
+                       *nresult = -1; /* XXX */
+                       return 0;
+               }
+               s += rsz;
+               sz -= rsz;
+       }
+#endif
+       err = _FUNCNAME(wcrtomb_priv)(ei, s, sz, wc, psenc, &nr);
+#if _ENCODING_IS_STATE_DEPENDENT
+       if (err == 0)
+               *nresult = (int)(nr + rsz);
+       else
+#endif
+       *nresult = (int)nr;
+
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_FUNCNAME(ctype_btowc)(_citrus_ctype_rec_t * __restrict cc,
+                      int c, wint_t * __restrict wcresult)
+{
+       _ENCODING_STATE state;
+       _ENCODING_INFO *ei;
+       char mb;
+       char const *s;
+       wchar_t wc;
+       size_t nr;
+       int err;
+
+       _DIAGASSERT(cc != NULL && cc->cc_closure != NULL);
+
+       if (c == EOF) {
+               *wcresult = WEOF;
+               return 0;
+       }
+       ei = _CEI_TO_EI(_TO_CEI(cc->cc_closure));
+       _FUNCNAME(init_state)(ei, &state);
+       mb = (char)(unsigned)c;
+       s = &mb;
+       err = _FUNCNAME(mbrtowc_priv)(ei, &wc, &s, 1, &state, &nr);
+       if (!err && (nr == 0 || nr == 1))
+               *wcresult = (wint_t)wc;
+       else
+               *wcresult = WEOF;
+
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_FUNCNAME(ctype_wctob)(_citrus_ctype_rec_t * __restrict cc,
+                      wint_t wc, int * __restrict cresult)
+{
+       _ENCODING_STATE state;
+       _ENCODING_INFO *ei;
+       char buf[MB_LEN_MAX];
+       size_t nr;
+       int err;
+
+       _DIAGASSERT(cc != NULL && cc->cc_closure != NULL);
+
+       if (wc == WEOF) {
+               *cresult = EOF;
+               return 0;
+       }
+       ei = _CEI_TO_EI(_TO_CEI(cc->cc_closure));
+       _FUNCNAME(init_state)(ei, &state);
+       err = _FUNCNAME(wcrtomb_priv)(ei, buf, _ENCODING_MB_CUR_MAX(ei),
+                                     (wchar_t)wc, &state, &nr);
+       if (!err && nr == 1)
+               *cresult = buf[0];
+       else
+               *cresult = EOF;
+
+       return 0;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_db.c b/lib/nbsd_libc/citrus/citrus_db.c
new file mode 100644 (file)
index 0000000..fc7e014
--- /dev/null
@@ -0,0 +1,340 @@
+/*     $NetBSD: citrus_db.c,v 1.5 2008/02/09 14:56:20 junyoung Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_db.c,v 1.5 2008/02/09 14:56:20 junyoung Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+#include <sys/types.h>
+
+#include "citrus_namespace.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_memstream.h"
+#include "citrus_mmap.h"
+#include "citrus_db.h"
+#include "citrus_db_file.h"
+
+struct _citrus_db {
+       /* private */
+       struct _region db_region;
+       uint32_t (*db_hashfunc)(void *, struct _citrus_region *);
+       void *db_hashfunc_closure;
+};
+
+int
+_citrus_db_open(struct _citrus_db **rdb, struct _region *r, const char *magic,
+               uint32_t (*hashfunc)(void *, struct _citrus_region *),
+               void *hashfunc_closure)
+{
+       struct _memstream ms;
+       struct _citrus_db *db;
+       struct _citrus_db_header_x *dhx;
+
+       _memstream_bind(&ms, r);
+
+       /* sanity check */
+       dhx = _memstream_getregion(&ms, NULL, sizeof(*dhx));
+       if (dhx == NULL)
+               return EFTYPE;
+       if (strncmp(dhx->dhx_magic, magic, _CITRUS_DB_MAGIC_SIZE) != 0)
+               return EFTYPE;
+       if (_memstream_seek(&ms, be32toh(dhx->dhx_entry_offset), SEEK_SET))
+               return EFTYPE;
+
+       if (be32toh(dhx->dhx_num_entries)*_CITRUS_DB_ENTRY_SIZE >
+           _memstream_remainder(&ms))
+               return EFTYPE;
+
+       db = malloc(sizeof(*db));
+       if (db==NULL)
+               return errno;
+       db->db_region = *r;
+       db->db_hashfunc = hashfunc;
+       db->db_hashfunc_closure = hashfunc_closure;
+       *rdb = db;
+
+       return 0;
+}
+
+void
+_citrus_db_close(struct _citrus_db *db)
+{
+       free(db);
+}
+
+int
+_citrus_db_lookup(struct _citrus_db *db, struct _citrus_region *key,
+                 struct _citrus_region *data, struct _citrus_db_locator *dl)
+{
+       uint32_t hashval, num_entries;
+       size_t offset;
+       struct _memstream ms;
+       struct _citrus_db_header_x *dhx;
+       struct _citrus_db_entry_x *dex;
+       struct _citrus_region r;
+
+       _memstream_bind(&ms, &db->db_region);
+
+       dhx = _memstream_getregion(&ms, NULL, sizeof(*dhx));
+       _DIAGASSERT(dhx);
+       num_entries = be32toh(dhx->dhx_num_entries);
+       if (num_entries == 0)
+               return ENOENT;
+
+       if (dl != NULL && dl->dl_offset>0) {
+               hashval = dl->dl_hashval;
+               offset = dl->dl_offset;
+               if (offset >= _region_size(&db->db_region))
+                       return ENOENT;
+       } else {
+               hashval =
+                   db->db_hashfunc(db->db_hashfunc_closure, key)%num_entries;
+               offset =
+                   be32toh(dhx->dhx_entry_offset) +
+                   hashval * _CITRUS_DB_ENTRY_SIZE;
+               if (dl)
+                       dl->dl_hashval = hashval;
+       }
+       do {
+               /* seek to the next entry */
+               if (_citrus_memory_stream_seek(&ms, offset, SEEK_SET))
+                       return EFTYPE;
+               /* get the entry record */
+               dex = _memstream_getregion(&ms, NULL, _CITRUS_DB_ENTRY_SIZE);
+               if (dex == NULL)
+                       return EFTYPE;
+
+               /* jump to next entry having the same hash value. */
+               offset = be32toh(dex->dex_next_offset);
+
+               /* save the current position */
+               if (dl) {
+                       dl->dl_offset = offset;
+                       if (offset==0)
+                               dl->dl_offset = _region_size(&db->db_region);
+               }
+
+               /* compare hash value. */
+               if (be32toh(dex->dex_hash_value) != hashval)
+                       /* not found */
+                       break;
+               /* compare key length */
+               if (be32toh(dex->dex_key_size) == _region_size(key)) {
+                       /* seek to the head of the key. */
+                       if (_memstream_seek(&ms, be32toh(dex->dex_key_offset),
+                                           SEEK_SET))
+                               return EFTYPE;
+                       /* get the region of the key */
+                       if (_memstream_getregion(&ms, &r,
+                                                _region_size(key)) == NULL)
+                               return EFTYPE;
+                       /* compare key byte stream */
+                       if (memcmp(_region_head(&r), _region_head(key),
+                                  _region_size(key)) == 0) {
+                               /* match */
+                               if (_memstream_seek(
+                                       &ms, be32toh(dex->dex_data_offset),
+                                       SEEK_SET))
+                                       return EFTYPE;
+                               if (_memstream_getregion(
+                                       &ms, data,
+                                       be32toh(dex->dex_data_size)) == NULL)
+                                       return EFTYPE;
+                               return 0;
+                       }
+               }
+       } while (offset != 0);
+
+       return ENOENT;
+}
+
+int
+_citrus_db_lookup_by_string(struct _citrus_db *db, const char *key,
+                           struct _citrus_region *data,
+                           struct _citrus_db_locator *dl)
+{
+       struct _region r;
+
+       _region_init(&r, __UNCONST(key), strlen(key));
+
+       return _citrus_db_lookup(db, &r, data, dl);
+}
+
+int
+_citrus_db_lookup8_by_string(struct _citrus_db *db, const char *key,
+                            uint8_t *rval, struct _citrus_db_locator *dl)
+{
+       int ret;
+       struct _region r;
+
+       ret = _citrus_db_lookup_by_string(db, key, &r, dl);
+       if (ret)
+               return ret;
+
+       if (_region_size(&r) != 1)
+               return EFTYPE;
+
+       if (rval)
+               memcpy(rval, _region_head(&r), 1);
+
+       return 0;
+}
+
+int
+_citrus_db_lookup16_by_string(struct _citrus_db *db, const char *key,
+                             uint16_t *rval, struct _citrus_db_locator *dl)
+{
+       int ret;
+       struct _region r;
+       uint16_t val;
+
+       ret = _citrus_db_lookup_by_string(db, key, &r, dl);
+       if (ret)
+               return ret;
+
+       if (_region_size(&r) != 2)
+               return EFTYPE;
+
+       if (rval) {
+               memcpy(&val, _region_head(&r), 2);
+               *rval = be16toh(val);
+       }
+
+       return 0;
+}
+
+int
+_citrus_db_lookup32_by_string(struct _citrus_db *db, const char *key,
+                             uint32_t *rval, struct _citrus_db_locator *dl)
+{
+       int ret;
+       struct _region r;
+       uint32_t val;
+
+       ret = _citrus_db_lookup_by_string(db, key, &r, dl);
+       if (ret)
+               return ret;
+
+       if (_region_size(&r) != 4)
+               return EFTYPE;
+
+       if (rval) {
+               memcpy(&val, _region_head(&r), 4);
+               *rval = be32toh(val);
+       }
+
+       return 0;
+}
+
+int
+_citrus_db_lookup_string_by_string(struct _citrus_db *db, const char *key,
+                                  const char **rdata,
+                                  struct _citrus_db_locator *dl)
+{
+       int ret;
+       struct _region r;
+
+       ret = _citrus_db_lookup_by_string(db, key, &r, dl);
+       if (ret)
+               return ret;
+
+       /* check whether the string is null terminated */
+       if (_region_size(&r) == 0)
+               return EFTYPE;
+       if (*((const char*)_region_head(&r)+_region_size(&r)-1) != '\0')
+               return EFTYPE;
+
+       if (rdata)
+               *rdata = _region_head(&r);
+
+       return 0;
+}
+
+int
+_citrus_db_get_number_of_entries(struct _citrus_db *db)
+{
+       struct _memstream ms;
+       struct _citrus_db_header_x *dhx;
+
+       _memstream_bind(&ms, &db->db_region);
+
+       dhx = _memstream_getregion(&ms, NULL, sizeof(*dhx));
+       _DIAGASSERT(dhx);
+       return (int)be32toh(dhx->dhx_num_entries);
+}
+
+int
+_citrus_db_get_entry(struct _citrus_db *db, int idx,
+                    struct _region *key, struct _region *data)
+{
+       uint32_t num_entries;
+       size_t offset;
+       struct _memstream ms;
+       struct _citrus_db_header_x *dhx;
+       struct _citrus_db_entry_x *dex;
+
+       _memstream_bind(&ms, &db->db_region);
+
+       dhx = _memstream_getregion(&ms, NULL, sizeof(*dhx));
+       _DIAGASSERT(dhx);
+       num_entries = be32toh(dhx->dhx_num_entries);
+       if (idx < 0 || (uint32_t)idx >= num_entries)
+               return EINVAL;
+
+       /* seek to the next entry */
+       offset = be32toh(dhx->dhx_entry_offset) + idx * _CITRUS_DB_ENTRY_SIZE;
+       if (_citrus_memory_stream_seek(&ms, offset, SEEK_SET))
+               return EFTYPE;
+       /* get the entry record */
+       dex = _memstream_getregion(&ms, NULL, _CITRUS_DB_ENTRY_SIZE);
+       if (dex == NULL)
+               return EFTYPE;
+       /* seek to the head of the key. */
+       if (_memstream_seek(&ms, be32toh(dex->dex_key_offset), SEEK_SET))
+               return EFTYPE;
+       /* get the region of the key. */
+       if (_memstream_getregion(&ms, key, be32toh(dex->dex_key_size))==NULL)
+               return EFTYPE;
+       /* seek to the head of the data. */
+       if (_memstream_seek(&ms, be32toh(dex->dex_data_offset), SEEK_SET))
+               return EFTYPE;
+       /* get the region of the data. */
+       if (_memstream_getregion(&ms, data, be32toh(dex->dex_data_size))==NULL)
+               return EFTYPE;
+
+       return 0;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_db.h b/lib/nbsd_libc/citrus/citrus_db.h
new file mode 100644 (file)
index 0000000..239e1cd
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: citrus_db.h,v 1.2 2008/02/09 14:56:20 junyoung Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_DB_H_
+#define _CITRUS_DB_H_
+
+struct _citrus_db;
+struct _citrus_db_locator {
+       uint32_t        dl_hashval;
+       size_t          dl_offset;
+};
+
+__BEGIN_DECLS
+int    _citrus_db_open(struct _citrus_db **, struct _citrus_region *,
+                       const char *,
+                       uint32_t (*)(void *, struct _citrus_region *),
+                       void *);
+void   _citrus_db_close(struct _citrus_db *);
+int    _citrus_db_lookup(struct _citrus_db *, struct _citrus_region *,
+                         struct _citrus_region *,
+                         struct _citrus_db_locator *);
+int    _citrus_db_lookup_by_string(struct _citrus_db *, const char *,
+                                   struct _citrus_region *,
+                                   struct _citrus_db_locator *);
+int    _citrus_db_lookup8_by_string(struct _citrus_db *, const char *,
+                                    uint8_t *,
+                                    struct _citrus_db_locator *);
+int    _citrus_db_lookup16_by_string(struct _citrus_db *, const char *,
+                                     uint16_t *,
+                                     struct _citrus_db_locator *);
+int    _citrus_db_lookup32_by_string(struct _citrus_db *, const char *,
+                                     uint32_t *,
+                                     struct _citrus_db_locator *);
+int    _citrus_db_lookup_string_by_string(struct _citrus_db *, const char *,
+                                          const char **,
+                                          struct _citrus_db_locator *);
+int    _citrus_db_get_number_of_entries(struct _citrus_db *);
+int    _citrus_db_get_entry(struct _citrus_db *, int,
+                            struct _citrus_region *, struct _citrus_region *);
+__END_DECLS
+
+static __inline void
+_citrus_db_locator_init(struct _citrus_db_locator *dl)
+{
+       dl->dl_hashval = 0;
+       dl->dl_offset = 0;
+}
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_db_factory.c b/lib/nbsd_libc/citrus/citrus_db_factory.c
new file mode 100644 (file)
index 0000000..44475af
--- /dev/null
@@ -0,0 +1,353 @@
+/*     $NetBSD: citrus_db_factory.c,v 1.9 2008/02/09 14:56:20 junyoung Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_db_factory.c,v 1.9 2008/02/09 14:56:20 junyoung Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <arpa/inet.h>
+#include <sys/types.h>
+#include <sys/queue.h>
+
+#include "citrus_namespace.h"
+#include "citrus_region.h"
+#include "citrus_db_file.h"
+#include "citrus_db_factory.h"
+
+struct _citrus_db_factory_entry {
+       SIMPLEQ_ENTRY(_citrus_db_factory_entry) de_entry;
+       struct _citrus_db_factory_entry *de_next;
+       uint32_t de_hashvalue;
+       struct _region de_key;
+       int de_key_free;
+       struct _region de_data;
+       int de_data_free;
+       int de_idx;
+};
+
+struct _citrus_db_factory {
+       size_t df_num_entries;
+       SIMPLEQ_HEAD(, _citrus_db_factory_entry) df_entries;
+       size_t df_total_key_size;
+       size_t df_total_data_size;
+       uint32_t (*df_hashfunc)(void *, struct _citrus_region *);
+       void *df_hashfunc_closure;
+};
+
+#define DB_ALIGN 16
+
+int
+_citrus_db_factory_create(struct _citrus_db_factory **rdf,
+                         _citrus_db_hash_func_t hashfunc,
+                         void *hashfunc_closure)
+{
+       struct _citrus_db_factory *df;
+
+       df = malloc(sizeof(*df));
+       if (df == NULL)
+               return errno;
+       df->df_num_entries = 0;
+       df->df_total_key_size = df->df_total_data_size = 0;
+       SIMPLEQ_INIT(&df->df_entries);
+       df->df_hashfunc = hashfunc;
+       df->df_hashfunc_closure = hashfunc_closure;
+
+       *rdf = df;
+
+       return 0;
+}
+
+void
+_citrus_db_factory_free(struct _citrus_db_factory *df)
+{
+       struct _citrus_db_factory_entry *de;
+
+       while ((de = SIMPLEQ_FIRST(&df->df_entries)) != NULL) {
+               SIMPLEQ_REMOVE_HEAD(&df->df_entries, de_entry);
+               if (de->de_key_free)
+                       free(_region_head(&de->de_key));
+               if (de->de_data_free)
+                       free(_region_head(&de->de_data));
+               free(de);
+       }
+       free(df);
+}
+
+static __inline size_t
+ceilto(size_t sz)
+{
+       return (sz+DB_ALIGN-1) & ~(DB_ALIGN-1);
+}
+
+int
+_citrus_db_factory_add(struct _citrus_db_factory *df,
+                      struct _region *key, int keyfree,
+                      struct _region *data, int datafree)
+{
+       struct _citrus_db_factory_entry *de;
+
+       de = malloc(sizeof(*de));
+       if (de == NULL)
+               return -1;
+
+       de->de_hashvalue = df->df_hashfunc(df->df_hashfunc_closure, key);
+       de->de_key = *key;
+       de->de_key_free = keyfree;
+       de->de_data = *data;
+       de->de_data_free = datafree;
+       de->de_idx = -1;
+
+       SIMPLEQ_INSERT_TAIL(&df->df_entries, de, de_entry);
+       df->df_total_key_size += _region_size(key);
+       df->df_total_data_size += ceilto(_region_size(data));
+       df->df_num_entries++;
+
+       return 0;
+
+}
+
+int
+_citrus_db_factory_add_by_string(struct _citrus_db_factory *df,
+                                const char *key,
+                                struct _citrus_region *data, int datafree)
+{
+       struct _region r;
+       char *tmp;
+       tmp = strdup(key);
+       if (tmp == NULL)
+               return errno;
+       _region_init(&r, tmp, strlen(key));
+       return _citrus_db_factory_add(df, &r, 1, data, datafree);
+}
+
+int
+_citrus_db_factory_add8_by_string(struct _citrus_db_factory *df,
+                                 const char *key, uint8_t val)
+{
+       struct _region r;
+       uint8_t *p;
+
+       p = malloc(sizeof(*p));
+       if (p == NULL)
+               return errno;
+       *p = val;
+       _region_init(&r, p, 1);
+       return _citrus_db_factory_add_by_string(df, key, &r, 1);
+}
+
+int
+_citrus_db_factory_add16_by_string(struct _citrus_db_factory *df,
+                                  const char *key, uint16_t val)
+{
+       struct _region r;
+       uint16_t *p;
+
+       p = malloc(sizeof(*p));
+       if (p == NULL)
+               return errno;
+       *p = htons(val);
+       _region_init(&r, p, 2);
+       return _citrus_db_factory_add_by_string(df, key, &r, 1);
+}
+
+int
+_citrus_db_factory_add32_by_string(struct _citrus_db_factory *df,
+                                  const char *key, uint32_t val)
+{
+       struct _region r;
+       uint32_t *p;
+
+       p = malloc(sizeof(*p));
+       if (p == NULL)
+               return errno;
+       *p = htonl(val);
+       _region_init(&r, p, 4);
+       return _citrus_db_factory_add_by_string(df, key, &r, 1);
+}
+
+int
+_citrus_db_factory_add_string_by_string(struct _citrus_db_factory *df,
+                                       const char *key, const char *data)
+{
+       char *p;
+       struct _region r;
+
+       p = strdup(data);
+       if (p == NULL)
+               return errno;
+       _region_init(&r, p, strlen(p)+1);
+       return _citrus_db_factory_add_by_string(df, key, &r, 1);
+}
+
+size_t
+_citrus_db_factory_calc_size(struct _citrus_db_factory *df)
+{
+       size_t sz;
+
+       sz = ceilto(_CITRUS_DB_HEADER_SIZE);
+       sz += ceilto(_CITRUS_DB_ENTRY_SIZE * df->df_num_entries);
+       sz += ceilto(df->df_total_key_size);
+       sz += df->df_total_data_size;
+
+       return sz;
+}
+
+static __inline void
+put8(struct _region *r, size_t *rofs, uint8_t val)
+{
+       *(uint8_t *)_region_offset(r, *rofs) = val;
+       *rofs += 1;
+}
+
+static __inline void
+put16(struct _region *r, size_t *rofs, uint16_t val)
+{
+       val = htons(val);
+       memcpy(_region_offset(r, *rofs), &val, 2);
+       *rofs += 2;
+}
+
+static __inline void
+put32(struct _region *r, size_t *rofs, uint32_t val)
+{
+       val = htonl(val);
+       memcpy(_region_offset(r, *rofs), &val, 4);
+       *rofs += 4;
+}
+
+static __inline void
+putpad(struct _region *r, size_t *rofs)
+{
+       size_t i;
+       for (i = ceilto(*rofs) - *rofs; i > 0; i--)
+               put8(r, rofs, 0);
+}
+
+static __inline void
+dump_header(struct _region *r, const char *magic, size_t *rofs,
+           size_t num_entries)
+{
+       while (*rofs<_CITRUS_DB_MAGIC_SIZE)
+               put8(r, rofs, *magic++);
+       put32(r, rofs, num_entries);
+       put32(r, rofs, _CITRUS_DB_HEADER_SIZE);
+}
+
+int
+_citrus_db_factory_serialize(struct _citrus_db_factory *df, const char *magic,
+                            struct _region *r)
+{
+       size_t i, ofs, keyofs, dataofs, nextofs;
+       struct _citrus_db_factory_entry *de, **depp, *det;
+
+       ofs = 0;
+       /* check whether more than 0 entries exist */
+       if (df->df_num_entries == 0) {
+               dump_header(r, magic, &ofs, 0);
+               return 0;
+       }
+       /* allocate hash table */
+       depp = malloc(sizeof(*depp) * df->df_num_entries);
+       if (depp == NULL)
+               return -1;
+       for (i = 0; i < df->df_num_entries; i++)
+               depp[i] = NULL;
+
+       /* step1: store the entries which are not conflicting */
+       SIMPLEQ_FOREACH(de, &df->df_entries, de_entry) {
+               de->de_hashvalue %= df->df_num_entries;
+               de->de_idx = -1;
+               de->de_next = NULL;
+               if (depp[de->de_hashvalue] == NULL) {
+                       depp[de->de_hashvalue] = de;
+                       de->de_idx = (int)de->de_hashvalue;
+               }
+       }
+
+       /* step2: resolve conflicts */
+       i = 0;
+       SIMPLEQ_FOREACH(de, &df->df_entries, de_entry) {
+               if (de->de_idx == -1) {
+                       det = depp[de->de_hashvalue];
+                       while (det->de_next != NULL)
+                               det = det->de_next;
+                       det->de_next = de;
+                       while (depp[i] != NULL)
+                               i++;
+                       depp[i] = de;
+                       de->de_idx = (int)i;
+               }
+       }
+
+       keyofs =
+           _CITRUS_DB_HEADER_SIZE +
+           ceilto(df->df_num_entries*_CITRUS_DB_ENTRY_SIZE);
+       dataofs = keyofs + ceilto(df->df_total_key_size);
+
+       /* dump header */
+       dump_header(r, magic, &ofs, df->df_num_entries);
+
+       /* dump entries */
+       for (i = 0; i < df->df_num_entries; i++) {
+               de = depp[i];
+               nextofs = 0;
+               if (de->de_next) {
+                       nextofs =
+                           _CITRUS_DB_HEADER_SIZE +
+                           de->de_next->de_idx * _CITRUS_DB_ENTRY_SIZE;
+               }
+               put32(r, &ofs, de->de_hashvalue);
+               put32(r, &ofs, nextofs);
+               put32(r, &ofs, keyofs);
+               put32(r, &ofs, _region_size(&de->de_key));
+               put32(r, &ofs, dataofs);
+               put32(r, &ofs, _region_size(&de->de_data));
+               memcpy(_region_offset(r, keyofs),
+                      _region_head(&de->de_key), _region_size(&de->de_key));
+               keyofs += _region_size(&de->de_key);
+               memcpy(_region_offset(r, dataofs),
+                      _region_head(&de->de_data), _region_size(&de->de_data));
+               dataofs += _region_size(&de->de_data);
+               putpad(r, &dataofs);
+       }
+       putpad(r, &ofs);
+       putpad(r, &keyofs);
+       free(depp);
+
+       return 0;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_db_factory.h b/lib/nbsd_libc/citrus/citrus_db_factory.h
new file mode 100644 (file)
index 0000000..8b2f994
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: citrus_db_factory.h,v 1.3 2008/02/09 14:56:20 junyoung Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_DB_FACTORY_H_
+#define _CITRUS_DB_FACTORY_H_
+
+struct _citrus_db_factory;
+typedef uint32_t (*_citrus_db_hash_func_t)(void *, struct _citrus_region *);
+
+__BEGIN_DECLS
+int    _citrus_db_factory_create(struct _citrus_db_factory **,
+                                 _citrus_db_hash_func_t, void *);
+void   _citrus_db_factory_free(struct _citrus_db_factory *);
+int    _citrus_db_factory_add(struct _citrus_db_factory *,
+                              struct _citrus_region *, int,
+                              struct _citrus_region *, int);
+int    _citrus_db_factory_add_by_string(struct _citrus_db_factory *,
+                                        const char *,
+                                        struct _citrus_region *, int);
+int    _citrus_db_factory_add8_by_string(struct _citrus_db_factory *,
+                                         const char *, uint8_t);
+int    _citrus_db_factory_add16_by_string(struct _citrus_db_factory *,
+                                          const char *, uint16_t);
+int    _citrus_db_factory_add32_by_string(struct _citrus_db_factory *,
+                                         const char *, uint32_t);
+int    _citrus_db_factory_add_string_by_string(struct _citrus_db_factory *,
+                                               const char *, const char *);
+size_t _citrus_db_factory_calc_size(struct _citrus_db_factory *);
+int    _citrus_db_factory_serialize(struct _citrus_db_factory *,
+                                    const char *, struct _citrus_region *);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_db_file.h b/lib/nbsd_libc/citrus/citrus_db_file.h
new file mode 100644 (file)
index 0000000..4e52957
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: citrus_db_file.h,v 1.4 2008/02/10 05:58:22 junyoung Exp $      */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_DB_FILE_H_
+#define _CITRUS_DB_FILE_H_
+
+/*
+ * db format:
+ *  +---
+ *  | header
+ *  |  - magic
+ *  |  - num entries
+ *  +---
+ *  | entry directory
+ *  |  +------------
+ *  |  | entry0
+ *  |  |  - hash value
+ *  |  |  - next entry
+ *  |  |  - key offset
+ *  |  |  - key len
+ *  |  |  - data offset
+ *  |  |  - data size
+ *  |  |---
+ *  |  | entry1
+ *  |  | ..
+ *  |  | entryN
+ *  |  +---
+ *  +---
+ *  | key table
+ *  |  - key0
+ *  |   ...
+ *  |  - keyN
+ *  +---
+ *  | data table
+ *  |  - data0
+ *  |   ...
+ *  |  - dataN
+ *  +---
+ */
+
+#define _CITRUS_DB_MAGIC_SIZE  8
+#define _CITRUS_DB_HEADER_SIZE 16
+struct _citrus_db_header_x {
+       char            dhx_magic[_CITRUS_DB_MAGIC_SIZE];
+       uint32_t        dhx_num_entries;
+       uint32_t        dhx_entry_offset;
+} __packed;
+
+struct _citrus_db_entry_x {
+       uint32_t        dex_hash_value;
+       uint32_t        dex_next_offset;
+       uint32_t        dex_key_offset;
+       uint32_t        dex_key_size;
+       uint32_t        dex_data_offset;
+       uint32_t        dex_data_size;
+} __packed;
+#define _CITRUS_DB_ENTRY_SIZE  24
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_db_hash.c b/lib/nbsd_libc/citrus/citrus_db_hash.c
new file mode 100644 (file)
index 0000000..9702391
--- /dev/null
@@ -0,0 +1,71 @@
+/*     $NetBSD: citrus_db_hash.c,v 1.5 2008/02/09 14:56:20 junyoung Exp $      */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_db_hash.c,v 1.5 2008/02/09 14:56:20 junyoung Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifndef HOSTPROG
+#include "namespace.h"
+#endif
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/types.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_db_hash.h"
+
+uint32_t
+/*ARGSUSED*/
+_citrus_db_hash_std(void *closure, struct _region *r)
+{
+       const uint8_t *p = _region_head(r);
+       uint32_t hash = 0, tmp;
+       size_t i;
+
+       for (i = _region_size(r); i > 0; i--) {
+               hash <<= 4;
+               hash += _bcs_tolower(*p);
+               tmp = hash & 0xF0000000;
+               if (tmp != 0) {
+                       hash ^= tmp;
+                       hash ^= tmp >> 24;
+               }
+               p++;
+       }
+       return hash;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_db_hash.h b/lib/nbsd_libc/citrus/citrus_db_hash.h
new file mode 100644 (file)
index 0000000..55ee45e
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: citrus_db_hash.h,v 1.2 2008/02/09 14:56:20 junyoung Exp $      */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_DB_HASH_H_
+#define _CITRUS_DB_HASH_H_
+
+__BEGIN_DECLS
+uint32_t       _citrus_db_hash_std(void *, struct _citrus_region *);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_esdb.c b/lib/nbsd_libc/citrus/citrus_esdb.c
new file mode 100644 (file)
index 0000000..4934007
--- /dev/null
@@ -0,0 +1,355 @@
+/*     $NetBSD: citrus_esdb.c,v 1.5 2008/02/09 14:56:20 junyoung Exp $ */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_esdb.c,v 1.5 2008/02/09 14:56:20 junyoung Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+#include <paths.h>
+#include <sys/types.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_memstream.h"
+#include "citrus_mmap.h"
+#include "citrus_lookup.h"
+#include "citrus_db.h"
+#include "citrus_db_hash.h"
+#include "citrus_esdb.h"
+#include "citrus_esdb_file.h"
+
+#define ESDB_DIR       "esdb.dir"
+#define ESDB_ALIAS     "esdb.alias"
+
+/*
+ * _citrus_esdb_alias:
+ *     resolve encoding scheme name aliases.
+ */
+const char *
+_citrus_esdb_alias(const char *esname, char *buf, size_t bufsize)
+{
+       return _lookup_alias(_PATH_ESDB "/" ESDB_ALIAS, esname, buf, bufsize,
+                            _LOOKUP_CASE_IGNORE);
+}
+
+
+/*
+ * conv_esdb:
+ *     external representation -> local structure.
+ */
+static int
+conv_esdb(struct _citrus_esdb *esdb, struct _region *fr)
+{
+       int ret;
+       struct _citrus_db *db;
+       uint32_t version, num_charsets, csid, i, tmp;
+       char buf[100];
+       const char *str;
+
+       /* open db */
+       ret = _db_open(&db, fr, _CITRUS_ESDB_MAGIC, &_db_hash_std, NULL);
+       if (ret)
+               goto err0;
+
+       /* check version */
+       ret = _db_lookup32_by_s(db, _CITRUS_ESDB_SYM_VERSION, &version, NULL);
+       if (ret)
+               goto err1;
+       switch (version) {
+       case 0x00000001:
+               /* current version */
+               /* initial version */
+               break;
+       default:
+               ret = EFTYPE;
+               goto err1;
+       }
+
+       /* get encoding/variable */
+       ret = _db_lookupstr_by_s(db, _CITRUS_ESDB_SYM_ENCODING, &str, NULL);
+       if (ret)
+               goto err1;
+       esdb->db_encname = strdup(str);
+       if (esdb->db_encname == NULL) {
+               ret = errno;
+               goto err1;
+       }
+
+       esdb->db_len_variable = 0;
+       esdb->db_variable = NULL;
+       ret = _db_lookupstr_by_s(db, _CITRUS_ESDB_SYM_VARIABLE, &str, NULL);
+       if (ret == 0) {
+               esdb->db_len_variable = strlen(str)+1;
+               esdb->db_variable = strdup(str);
+               if (esdb->db_variable == NULL) {
+                       ret = errno;
+                       goto err2;
+               }
+       } else if (ret != ENOENT)
+               goto err2;
+
+       /* get number of charsets */
+       ret = _db_lookup32_by_s(db, _CITRUS_ESDB_SYM_NUM_CHARSETS,
+                               &num_charsets, NULL);
+       if (ret)
+               goto err3;
+       esdb->db_num_charsets = num_charsets;
+
+       /* get invalid character */
+       ret = _db_lookup32_by_s(db, _CITRUS_ESDB_SYM_INVALID, &tmp, NULL);
+       if (ret == 0) {
+               esdb->db_use_invalid = 1;
+               esdb->db_invalid = tmp;
+       } else if (ret == ENOENT)
+               esdb->db_use_invalid = 0;
+       else
+               goto err3;
+
+       /* get charsets */
+       esdb->db_charsets = malloc(num_charsets * sizeof(*esdb->db_charsets));
+       if (esdb->db_charsets == NULL) {
+               ret = errno;
+               goto err3;
+       }
+       for (i = 0; i < num_charsets; i++) {
+               snprintf(buf, sizeof(buf),
+                   _CITRUS_ESDB_SYM_CSID_PREFIX "%d", i);
+               ret = _db_lookup32_by_s(db, buf, &csid, NULL);
+               if (ret)
+                       goto err4;
+               esdb->db_charsets[i].ec_csid = csid;
+
+               snprintf(buf, sizeof(buf),
+                   _CITRUS_ESDB_SYM_CSNAME_PREFIX "%d", i);
+               ret = _db_lookupstr_by_s(db, buf, &str, NULL);
+               if (ret)
+                       goto err4;
+               esdb->db_charsets[i].ec_csname = strdup(str);
+               if (esdb->db_charsets[i].ec_csname == NULL) {
+                       ret = errno;
+                       goto err4;
+               }
+       }
+
+       _db_close(db);
+       return 0;
+
+err4:
+       for (; i > 0; i--)
+               free(esdb->db_charsets[i - 1].ec_csname);
+       free(esdb->db_charsets);
+err3:
+       free(esdb->db_variable);
+err2:
+       free(esdb->db_encname);
+err1:
+       _db_close(db);
+       if (ret == ENOENT)
+               ret = EFTYPE;
+err0:
+       return ret;
+}
+
+/*
+ * _citrus_esdb_open:
+ *     open an ESDB file.
+ */
+int
+_citrus_esdb_open(struct _citrus_esdb *db, const char *esname)
+{
+       int ret;
+       const char *realname, *encfile;
+       char buf1[PATH_MAX], buf2[PATH_MAX], path[PATH_MAX];
+       struct _region fr;
+
+       _DIAGASSERT(esname != NULL);
+
+       snprintf(path, sizeof(path), "%s/%s", _PATH_ESDB, ESDB_ALIAS);
+       realname = _lookup_alias(path, esname, buf1, sizeof(buf1),
+                                _LOOKUP_CASE_IGNORE);
+
+       snprintf(path, sizeof(path), "%s/%s", _PATH_ESDB, ESDB_DIR);
+       encfile = _lookup_simple(path, realname, buf2, sizeof(buf2),
+                                _LOOKUP_CASE_IGNORE);
+       if (encfile==NULL)
+               return ENOENT;
+
+       /* open file */
+       snprintf(path, sizeof(path), "%s/%s", _PATH_ESDB, encfile);
+       ret = _map_file(&fr, path);
+       if (ret)
+               return ret;
+
+       ret = conv_esdb(db, &fr);
+
+       _unmap_file(&fr);
+
+       return ret;
+}
+
+/*
+ * _citrus_esdb_close:
+ *     free an ESDB.
+ */
+void
+_citrus_esdb_close(struct _citrus_esdb *db)
+{
+       int i;
+
+       _DIAGASSERT(db != NULL);
+       _DIAGASSERT(db->db_num_charsets == 0 || db->db_charsets != NULL);
+
+       for (i = 0; i < db->db_num_charsets; i++)
+               free(db->db_charsets[i].ec_csname);
+       db->db_num_charsets = 0;
+       free(db->db_charsets); db->db_charsets = NULL;
+       free(db->db_encname); db->db_encname = NULL;
+       db->db_len_variable = 0;
+       free(db->db_variable); db->db_variable = NULL;
+}
+
+/*
+ * _citrus_esdb_free_list:
+ *     free the list.
+ */
+void
+_citrus_esdb_free_list(char **list, size_t num)
+{
+       size_t i;
+
+       for (i = 0; i < num; i++)
+               free(list[i]);
+       free(list);
+}
+
+/*
+ * _citrus_esdb_get_list:
+ *     get esdb entries.
+ */
+int
+_citrus_esdb_get_list(char ***rlist, size_t *rnum)
+{
+       int ret;
+       struct _region key;
+       size_t num;
+       struct _citrus_lookup *cla, *cld;
+       char **list, **q;
+       char buf[PATH_MAX];
+
+       num = 0;
+
+       ret = _lookup_seq_open(&cla, _PATH_ESDB "/" ESDB_ALIAS,
+                              _LOOKUP_CASE_IGNORE);
+       if (ret)
+               goto quit0;
+
+       ret = _lookup_seq_open(&cld, _PATH_ESDB "/" ESDB_DIR,
+                              _LOOKUP_CASE_IGNORE);
+       if (ret)
+               goto quit1;
+
+       /* count number of entries */
+       num = _lookup_get_num_entries(cla) + _lookup_get_num_entries(cld);
+
+       _lookup_seq_rewind(cla);
+       _lookup_seq_rewind(cld);
+
+       /* allocate list pointer space */
+       list = malloc(num * sizeof(char *));
+       num = 0;
+       if (list == NULL) {
+               ret = errno;
+               goto quit3;
+       }
+
+       /* get alias entries */
+       while ((ret = _lookup_seq_next(cla, &key, NULL)) == 0) {
+               snprintf(buf, sizeof(buf), "%.*s",
+                        (int)_region_size(&key),
+                        (const char *)_region_head(&key));
+               _bcs_convert_to_lower(buf);
+               list[num] = strdup(buf);
+               if (list[num] == NULL) {
+                       ret = errno;
+                       goto quit3;
+               }
+               num++;
+       }
+       if (ret != ENOENT)
+               goto quit3;
+       /* get dir entries */
+       while ((ret = _lookup_seq_next(cld, &key, NULL)) == 0) {
+               /* check duplicated entry */
+               snprintf(buf, sizeof(buf), "%.*s",
+                        (int)_region_size(&key),
+                        (const char *)_region_head(&key));
+               _bcs_convert_to_lower(buf);
+               ret = _lookup_seq_lookup(cla, buf, NULL);
+               if (ret) {
+                       if (ret != ENOENT)
+                               goto quit3;
+                       /* not duplicated */
+                       list[num] = strdup(buf);
+                       if (list[num] == NULL) {
+                               ret = errno;
+                               goto quit3;
+                       }
+                       num++;
+               }
+       }
+       if (ret != ENOENT)
+               goto quit3;
+
+       ret = 0;
+       q = realloc(list, num * sizeof(char *));
+       if (!q) {
+               ret = ENOMEM;
+               goto quit3;
+       }
+       list = q;
+       *rlist = list;
+       *rnum = num;
+quit3:
+       if (ret)
+               _citrus_esdb_free_list(list, num);
+       _lookup_seq_close(cld);
+quit1:
+       _lookup_seq_close(cla);
+quit0:
+       return ret;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_esdb.h b/lib/nbsd_libc/citrus/citrus_esdb.h
new file mode 100644 (file)
index 0000000..dce973d
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: citrus_esdb.h,v 1.1 2003/06/25 09:51:32 tshiozak Exp $ */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_ESDB_H_
+#define _CITRUS_ESDB_H_
+
+struct _citrus_esdb_charset {
+       _citrus_csid_t                  ec_csid;
+       char                            *ec_csname;
+};
+
+struct _citrus_esdb {
+       char                            *db_encname;
+       void                            *db_variable;
+       size_t                          db_len_variable;
+       int                             db_num_charsets;
+       struct  _citrus_esdb_charset    *db_charsets;
+       int                             db_use_invalid;
+       _citrus_wc_t                    db_invalid;
+};
+
+__BEGIN_DECLS
+const char     *_citrus_esdb_alias(const char *, char *, size_t);
+int            _citrus_esdb_open(struct _citrus_esdb *, const char *);
+void           _citrus_esdb_close(struct _citrus_esdb *);
+void           _citrus_esdb_free_list(char **, size_t);
+int            _citrus_esdb_get_list(char ***, size_t *);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_esdb_file.h b/lib/nbsd_libc/citrus/citrus_esdb_file.h
new file mode 100644 (file)
index 0000000..5bb05a2
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: citrus_esdb_file.h,v 1.1 2003/06/25 09:51:32 tshiozak Exp $    */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_ESDB_FILE_H_
+#define _CITRUS_ESDB_FILE_H_
+
+#define _CITRUS_ESDB_MAGIC     "ESDB\0\0\0\0"
+
+#define _CITRUS_ESDB_SYM_VERSION       "version"
+#define _CITRUS_ESDB_SYM_ENCODING      "encoding"
+#define _CITRUS_ESDB_SYM_VARIABLE      "variable"
+#define _CITRUS_ESDB_SYM_NUM_CHARSETS  "num_charsets"
+#define _CITRUS_ESDB_SYM_INVALID       "invalid"
+#define _CITRUS_ESDB_SYM_CSNAME_PREFIX "csname_"
+#define _CITRUS_ESDB_SYM_CSID_PREFIX   "csid_"
+
+#define _CITRUS_ESDB_VERSION 0x00000001
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_fix_grouping.h b/lib/nbsd_libc/citrus/citrus_fix_grouping.h
new file mode 100644 (file)
index 0000000..f4e85e5
--- /dev/null
@@ -0,0 +1,55 @@
+/* $NetBSD: citrus_fix_grouping.h,v 1.2 2009/01/11 02:46:24 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_FIX_GROUPING_H_
+#define _CITRUS_FIX_GROUPING_H_
+
+#define _CITRUS_LC_GROUPING_VALUE_MIN          0
+#define _CITRUS_LC_GROUPING_VALUE_MAX          126
+#define _CITRUS_LC_GROUPING_VALUE_NO_FUTHER    127
+
+#if CHAR_MAX != _CITRUS_LC_GROUPING_VALUE_NO_FUTHER
+static __inline void
+_citrus_fixup_char_max_md(char *grouping)
+{
+       char *p;
+
+       _DIAGASSERT(grouping != NULL);
+
+       for (p = grouping; *p != '\0'; ++p) {
+               if (*p == _CITRUS_LC_GROUPING_VALUE_NO_FUTHER)
+                       *p = (char)CHAR_MAX;
+       }
+}
+#define _CITRUS_FIXUP_CHAR_MAX_MD(grouping) \
+    _citrus_fixup_char_max_md(__UNCONST(grouping))
+#else
+#define _CITRUS_FIXUP_CHAR_MAX_MD(grouping)    /* nothing to do */
+#endif
+
+#endif /*_CITRUS_FIX_GROUPING_H_*/
diff --git a/lib/nbsd_libc/citrus/citrus_hash.c b/lib/nbsd_libc/citrus/citrus_hash.c
new file mode 100644 (file)
index 0000000..954ce21
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: citrus_hash.c,v 1.3 2008/02/09 14:56:20 junyoung Exp $ */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_hash.c,v 1.3 2008/02/09 14:56:20 junyoung Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/types.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_region.h"
+#include "citrus_hash.h"
+#include "citrus_db_hash.h"
+
+int
+_citrus_string_hash_func(const char *key, int hashsize)
+{
+       struct _region r;
+
+       _region_init(&r, __UNCONST(key), strlen(key));
+
+       return (int)(_db_hash_std(NULL, &r) % (uint32_t)hashsize);
+}
diff --git a/lib/nbsd_libc/citrus/citrus_hash.h b/lib/nbsd_libc/citrus/citrus_hash.h
new file mode 100644 (file)
index 0000000..2e677a1
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: citrus_hash.h,v 1.3 2004/01/02 21:49:35 itojun Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_HASH_H_
+#define _CITRUS_HASH_H_
+
+#define _CITRUS_HASH_ENTRY(type) LIST_ENTRY(type)
+#define _CITRUS_HASH_HEAD(headname, type, hashsize)    \
+struct headname {                                      \
+       LIST_HEAD(, type)       chh_table[hashsize];    \
+}
+#define _CITRUS_HASH_INIT(head, hashsize)                      \
+do {                                                           \
+       int _ch_loop;                                           \
+       for (_ch_loop = 0; _ch_loop < hashsize; _ch_loop++)     \
+               LIST_INIT(&(head)->chh_table[_ch_loop]);        \
+} while (/*CONSTCOND*/0)
+#define _CITRUS_HASH_REMOVE(elm, field) LIST_REMOVE(elm, field)
+#define _CITRUS_HASH_INSERT(head, elm, field, hashval)         \
+LIST_INSERT_HEAD(&(head)->chh_table[hashval], elm, field)
+#define _CITRUS_HASH_SEARCH(head, elm, field, matchfunc, key, hashval) \
+do {                                                                   \
+       LIST_FOREACH((elm), &(head)->chh_table[hashval], field) {       \
+               if (matchfunc((elm), key)==0)                           \
+                       break;                                          \
+       }                                                               \
+} while (/*CONSTCOND*/0)
+
+__BEGIN_DECLS
+int    _citrus_string_hash_func(const char *, int);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_iconv.c b/lib/nbsd_libc/citrus/citrus_iconv.c
new file mode 100644 (file)
index 0000000..585b285
--- /dev/null
@@ -0,0 +1,387 @@
+/*     $NetBSD: citrus_iconv.c,v 1.8 2009/09/05 06:44:27 dholland Exp $        */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_iconv.c,v 1.8 2009/09/05 06:44:27 dholland Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+#include <unistd.h>
+#include <paths.h>
+#include <dirent.h>
+#include <sys/types.h>
+#include <sys/queue.h>
+
+#include "citrus_namespace.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_memstream.h"
+#include "citrus_mmap.h"
+#include "citrus_module.h"
+#include "citrus_lookup.h"
+#include "citrus_hash.h"
+#include "citrus_iconv.h"
+
+#define _CITRUS_ICONV_DIR      "iconv.dir"
+#define _CITRUS_ICONV_ALIAS    "iconv.alias"
+
+#define CI_HASH_SIZE 101
+#define CI_INITIAL_MAX_REUSE   5
+#define CI_ENV_MAX_REUSE       "ICONV_MAX_REUSE"
+
+#ifdef _REENTRANT
+static rwlock_t lock = RWLOCK_INITIALIZER;
+#endif
+static int isinit = 0;
+static _CITRUS_HASH_HEAD(, _citrus_iconv_shared, CI_HASH_SIZE) shared_pool;
+static TAILQ_HEAD(, _citrus_iconv_shared) shared_unused;
+static int shared_num_unused, shared_max_reuse;
+
+static __inline void
+init_cache(void)
+{
+       rwlock_wrlock(&lock);
+       if (!isinit) {
+               _CITRUS_HASH_INIT(&shared_pool, CI_HASH_SIZE);
+               TAILQ_INIT(&shared_unused);
+               shared_max_reuse = -1;
+               if (!issetugid() && getenv(CI_ENV_MAX_REUSE))
+                       shared_max_reuse = atoi(getenv(CI_ENV_MAX_REUSE));
+               if (shared_max_reuse < 0)
+                       shared_max_reuse = CI_INITIAL_MAX_REUSE;
+               isinit = 1;
+       }
+       rwlock_unlock(&lock);
+}
+
+/*
+ * lookup_iconv_entry:
+ *     lookup iconv.dir entry in the specified directory.
+ *
+ * line format of iconv.dir file:
+ *     key  module  arg
+ * key    : lookup key.
+ * module : iconv module name.
+ * arg    : argument for the module (generally, description file name)
+ *
+ */
+static __inline int
+lookup_iconv_entry(const char *curdir, const char *key,
+                  char *linebuf, size_t linebufsize,
+                  const char **module, const char **variable)
+{
+       const char *cp, *cq;
+       char *p, path[PATH_MAX];
+
+       /* iconv.dir path */
+       snprintf(path, (size_t)PATH_MAX, ("%s/" _CITRUS_ICONV_DIR), curdir);
+
+       /* lookup db */
+       cp = p = _lookup_simple(path, key, linebuf, linebufsize,
+                               _LOOKUP_CASE_IGNORE);
+       if (p == NULL)
+               return ENOENT;
+
+       /* get module name */
+       *module = p;
+       cq = _bcs_skip_nonws(cp);
+       p[cq-cp] = '\0';
+       p += cq-cp+1;
+       cq++;
+
+       /* get variable */
+       cp = _bcs_skip_ws(cq);
+       *variable = p += cp - cq;
+       cq = _bcs_skip_nonws(cp);
+       p[cq-cp] = '\0';
+
+       return 0;
+}
+
+static __inline void
+close_shared(struct _citrus_iconv_shared *ci)
+{
+       if (ci) {
+               if (ci->ci_module) {
+                       if (ci->ci_ops) {
+                               if (ci->ci_closure)
+                                       (*ci->ci_ops->io_uninit_shared)(ci);
+                               free(ci->ci_ops);
+                       }
+                       _citrus_unload_module(ci->ci_module);
+               }
+               free(ci);
+       }
+}
+
+static __inline int
+open_shared(struct _citrus_iconv_shared * __restrict * __restrict rci,
+           const char * __restrict basedir, const char * __restrict convname,
+           const char * __restrict src, const char * __restrict dst)
+{
+       int ret;
+       struct _citrus_iconv_shared *ci;
+       _citrus_iconv_getops_t getops;
+       char linebuf[LINE_MAX];
+       const char *module, *variable;
+       size_t len_convname;
+
+       /* search converter entry */
+       ret = lookup_iconv_entry(basedir, convname, linebuf, sizeof(linebuf),
+                                &module, &variable);
+       if (ret) {
+               if (ret == ENOENT)
+                       /* fallback */
+                       ret = lookup_iconv_entry(basedir, "*",
+                                                linebuf, sizeof(linebuf),
+                                                &module, &variable);
+               if (ret)
+                       return ret;
+       }
+
+       /* initialize iconv handle */
+       len_convname = strlen(convname);
+       ci = malloc(sizeof(*ci)+len_convname+1);
+       if (!ci) {
+               ret = errno;
+               goto err;
+       }
+       ci->ci_module = NULL;
+       ci->ci_ops = NULL;
+       ci->ci_closure = NULL;
+       ci->ci_convname = (void *)&ci[1];
+       memcpy(ci->ci_convname, convname, len_convname+1);
+
+       /* load module */
+       ret = _citrus_load_module(&ci->ci_module, module);
+       if (ret)
+               goto err;
+
+       /* get operators */
+       getops = (_citrus_iconv_getops_t)
+           _citrus_find_getops(ci->ci_module, module, "iconv");
+       if (!getops) {
+               ret = EOPNOTSUPP;
+               goto err;
+       }
+       ci->ci_ops = malloc(sizeof(*ci->ci_ops));
+       if (!ci->ci_ops) {
+               ret = errno;
+               goto err;
+       }
+       ret = (*getops)(ci->ci_ops, sizeof(*ci->ci_ops),
+                       _CITRUS_ICONV_ABI_VERSION);
+       if (ret)
+               goto err;
+
+       /* version check */
+       if (ci->ci_ops->io_abi_version == 1) {
+               /* binary compatibility broken at ver.2 */
+               ret = EINVAL;
+               goto err;
+       }
+
+       if (ci->ci_ops->io_init_shared == NULL ||
+           ci->ci_ops->io_uninit_shared == NULL ||
+           ci->ci_ops->io_init_context == NULL ||
+           ci->ci_ops->io_uninit_context == NULL ||
+           ci->ci_ops->io_convert == NULL)
+               goto err;
+
+       /* initialize the converter */
+       ret = (*ci->ci_ops->io_init_shared)(ci, basedir, src, dst,
+                                           (const void *)variable,
+                                           strlen(variable)+1);
+       if (ret)
+               goto err;
+
+       *rci = ci;
+
+       return 0;
+err:
+       close_shared(ci);
+       return ret;
+}
+
+static __inline int
+hash_func(const char *key)
+{
+       return _string_hash_func(key, CI_HASH_SIZE);
+}
+
+static __inline int
+match_func(struct _citrus_iconv_shared * __restrict ci,
+          const char * __restrict key)
+{
+       return strcmp(ci->ci_convname, key);
+}
+
+static int
+get_shared(struct _citrus_iconv_shared * __restrict * __restrict rci,
+          const char *basedir, const char *src, const char *dst)
+{
+       int ret = 0;
+       int hashval;
+       struct _citrus_iconv_shared * ci;
+       char convname[PATH_MAX];
+
+       snprintf(convname, sizeof(convname), "%s/%s", src, dst);
+
+       rwlock_wrlock(&lock);
+
+       /* lookup alread existing entry */
+       hashval = hash_func(convname);
+       _CITRUS_HASH_SEARCH(&shared_pool, ci, ci_hash_entry, match_func,
+                           convname, hashval);
+       if (ci != NULL) {
+               /* found */
+               if (ci->ci_used_count == 0) {
+                       TAILQ_REMOVE(&shared_unused, ci, ci_tailq_entry);
+                       shared_num_unused--;
+               }
+               ci->ci_used_count++;
+               *rci = ci;
+               goto quit;
+       }
+
+       /* create new entry */
+       ret = open_shared(&ci, basedir, convname, src, dst);
+       if (ret)
+               goto quit;
+
+       _CITRUS_HASH_INSERT(&shared_pool, ci, ci_hash_entry, hashval);
+       ci->ci_used_count = 1;
+       *rci = ci;
+
+quit:
+       rwlock_unlock(&lock);
+
+       return ret;
+}
+
+static void
+release_shared(struct _citrus_iconv_shared * __restrict ci)
+{
+       rwlock_wrlock(&lock);
+
+       ci->ci_used_count--;
+       if (ci->ci_used_count == 0) {
+               /* put it into unused list */
+               shared_num_unused++;
+               TAILQ_INSERT_TAIL(&shared_unused, ci, ci_tailq_entry);
+               /* flood out */
+               while (shared_num_unused > shared_max_reuse) {
+                       ci = TAILQ_FIRST(&shared_unused);
+                       _DIAGASSERT(ci != NULL);
+                       TAILQ_REMOVE(&shared_unused, ci, ci_tailq_entry);
+                       _CITRUS_HASH_REMOVE(ci, ci_hash_entry);
+                       shared_num_unused--;
+                       close_shared(ci);
+               }
+       }
+
+       rwlock_unlock(&lock);
+}
+
+/*
+ * _citrus_iconv_open:
+ *     open a converter for the specified in/out codes.
+ */
+int
+_citrus_iconv_open(struct _citrus_iconv * __restrict * __restrict rcv,
+                  const char * __restrict basedir,
+                  const char * __restrict src, const char * __restrict dst)
+{
+       int ret;
+       struct _citrus_iconv_shared *ci = NULL;
+       struct _citrus_iconv *cv;
+       char realsrc[PATH_MAX], realdst[PATH_MAX];
+       char buf[PATH_MAX], path[PATH_MAX];
+
+       init_cache();
+
+       /* resolve codeset name aliases */
+       snprintf(path, sizeof(path), "%s/%s", basedir, _CITRUS_ICONV_ALIAS);
+       strlcpy(realsrc,
+               _lookup_alias(path, src, buf, (size_t)PATH_MAX,
+               _LOOKUP_CASE_IGNORE),
+               (size_t)PATH_MAX);
+       strlcpy(realdst,
+               _lookup_alias(path, dst, buf, (size_t)PATH_MAX,
+               _LOOKUP_CASE_IGNORE),
+               (size_t)PATH_MAX);
+
+       /* sanity check */
+       if (strchr(realsrc, '/') != NULL || strchr(realdst, '/'))
+               return EINVAL;
+
+       /* get shared record */
+       ret = get_shared(&ci, basedir, realsrc, realdst);
+       if (ret)
+               return ret;
+
+       /* create/init context */
+       cv = malloc(sizeof(*cv));
+       if (cv == NULL) {
+               ret = errno;
+               release_shared(ci);
+               return ret;
+       }
+       cv->cv_shared = ci;
+       ret = (*ci->ci_ops->io_init_context)(cv);
+       if (ret) {
+               release_shared(ci);
+               free(cv);
+               return ret;
+       }
+       *rcv = cv;
+
+       return 0;
+}
+
+/*
+ * _citrus_iconv_close:
+ *     close the specified converter.
+ */
+void
+_citrus_iconv_close(struct _citrus_iconv *cv)
+{
+       if (cv) {
+               (*cv->cv_shared->ci_ops->io_uninit_context)(cv);
+               release_shared(cv->cv_shared);
+               free(cv);
+       }
+}
diff --git a/lib/nbsd_libc/citrus/citrus_iconv.h b/lib/nbsd_libc/citrus/citrus_iconv.h
new file mode 100644 (file)
index 0000000..3719260
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: citrus_iconv.h,v 1.5 2008/02/09 14:56:20 junyoung Exp $        */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_ICONV_H_
+#define _CITRUS_ICONV_H_
+
+struct _citrus_iconv_shared;
+struct _citrus_iconv_ops;
+struct _citrus_iconv;
+
+__BEGIN_DECLS
+int    _citrus_iconv_open(struct _citrus_iconv * __restrict * __restrict,
+                          const char * __restrict,
+                          const char * __restrict, const char * __restrict);
+void   _citrus_iconv_close(struct _citrus_iconv *);
+__END_DECLS
+
+
+#include "citrus_iconv_local.h"
+
+#define _CITRUS_ICONV_F_HIDE_INVALID   0x0001
+
+/*
+ * _citrus_iconv_convert:
+ *     convert a string.
+ */
+static __inline int
+_citrus_iconv_convert(struct _citrus_iconv * __restrict cv,
+                     const char * __restrict * __restrict in,
+                     size_t * __restrict inbytes,
+                     char * __restrict * __restrict out,
+                     size_t * __restrict outbytes, uint32_t flags,
+                     size_t * __restrict nresults)
+{
+
+       _DIAGASSERT(cv && cv->cv_shared && cv->cv_shared->ci_ops &&
+           cv->cv_shared->ci_ops->io_convert);
+       _DIAGASSERT(out || outbytes == 0);
+
+       return (*cv->cv_shared->ci_ops->io_convert)(cv, in, inbytes, out,
+                                                   outbytes, flags, nresults);
+}
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_iconv_local.h b/lib/nbsd_libc/citrus/citrus_iconv_local.h
new file mode 100644 (file)
index 0000000..fd42e84
--- /dev/null
@@ -0,0 +1,107 @@
+/*     $NetBSD: citrus_iconv_local.h,v 1.3 2008/02/09 14:56:20 junyoung Exp $  */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_ICONV_LOCAL_H_
+#define _CITRUS_ICONV_LOCAL_H_
+
+#define _CITRUS_ICONV_GETOPS_FUNC_BASE(_n_)                            \
+int _n_(struct _citrus_iconv_ops *, size_t, uint32_t)
+#define _CITRUS_ICONV_GETOPS_FUNC(_n_)                                 \
+_CITRUS_ICONV_GETOPS_FUNC_BASE(_citrus_##_n_##_iconv_getops)
+
+#define _CITRUS_ICONV_DECLS(_m_)                                       \
+static int     _citrus_##_m_##_iconv_init_shared                       \
+       (struct _citrus_iconv_shared * __restrict,                      \
+        const char * __restrict,                                       \
+        const char * __restrict, const char * __restrict,              \
+        const void * __restrict, size_t);                              \
+static void    _citrus_##_m_##_iconv_uninit_shared                     \
+       (struct _citrus_iconv_shared *);                                \
+static int     _citrus_##_m_##_iconv_convert                           \
+       (struct _citrus_iconv * __restrict,                             \
+        const char * __restrict * __restrict, size_t * __restrict,     \
+        char * __restrict * __restrict, size_t * __restrict outbytes,  \
+        uint32_t, size_t * __restrict);                                \
+static int     _citrus_##_m_##_iconv_init_context                      \
+       (struct _citrus_iconv *);                                       \
+static void    _citrus_##_m_##_iconv_uninit_context                    \
+       (struct _citrus_iconv *)
+
+
+#define _CITRUS_ICONV_DEF_OPS(_m_)                                     \
+struct _citrus_iconv_ops _citrus_##_m_##_iconv_ops = {                 \
+       /* io_abi_version */    _CITRUS_ICONV_ABI_VERSION,              \
+       /* io_init_shared */    &_citrus_##_m_##_iconv_init_shared,     \
+       /* io_uninit_shared */  &_citrus_##_m_##_iconv_uninit_shared,   \
+       /* io_init_context */   &_citrus_##_m_##_iconv_init_context,    \
+       /* io_uninit_context */ &_citrus_##_m_##_iconv_uninit_context,  \
+       /* io_convert */        &_citrus_##_m_##_iconv_convert          \
+}
+
+typedef _CITRUS_ICONV_GETOPS_FUNC_BASE((*_citrus_iconv_getops_t));
+typedef        int     (*_citrus_iconv_init_shared_t)
+       (struct _citrus_iconv_shared * __restrict,
+        const char * __restrict, const char * __restrict,
+        const char * __restrict, const void * __restrict, size_t);
+typedef void   (*_citrus_iconv_uninit_shared_t)
+       (struct _citrus_iconv_shared *);
+typedef int    (*_citrus_iconv_convert_t)
+       (struct _citrus_iconv * __restrict,
+        const char *__restrict* __restrict, size_t * __restrict,
+        char * __restrict * __restrict, size_t * __restrict, uint32_t,
+        size_t * __restrict);
+typedef int    (*_citrus_iconv_init_context_t)(struct _citrus_iconv *);
+typedef void   (*_citrus_iconv_uninit_context_t)(struct _citrus_iconv *);
+
+struct _citrus_iconv_ops {
+       uint32_t                        io_abi_version;
+       _citrus_iconv_init_shared_t     io_init_shared;
+       _citrus_iconv_uninit_shared_t   io_uninit_shared;
+       _citrus_iconv_init_context_t    io_init_context;
+       _citrus_iconv_uninit_context_t  io_uninit_context;
+       _citrus_iconv_convert_t         io_convert;
+};
+#define _CITRUS_ICONV_ABI_VERSION      2
+
+struct _citrus_iconv_shared {
+       struct _citrus_iconv_ops                        *ci_ops;
+       void                                            *ci_closure;
+       /* private */
+       _CITRUS_HASH_ENTRY(_citrus_iconv_shared)        ci_hash_entry;
+       TAILQ_ENTRY(_citrus_iconv_shared)               ci_tailq_entry;
+       _citrus_module_t                                ci_module;
+       unsigned int                                    ci_used_count;
+       char                                            *ci_convname;
+};
+
+struct _citrus_iconv {
+       struct _citrus_iconv_shared     *cv_shared;
+       void                            *cv_closure;
+};
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_lc_ctype.c b/lib/nbsd_libc/citrus/citrus_lc_ctype.c
new file mode 100644 (file)
index 0000000..e6d55e7
--- /dev/null
@@ -0,0 +1,133 @@
+/* $NetBSD: citrus_lc_ctype.c,v 1.9 2010/06/19 13:26:51 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_lc_ctype.c,v 1.9 2010/06/19 13:26:51 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/ctype_bits.h>
+#include <sys/queue.h>
+#include <assert.h>
+#include <errno.h>
+#include <langinfo.h>
+#include <limits.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <wchar.h>
+
+#include "setlocale_local.h"
+
+#include "citrus_namespace.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_lookup.h"
+#include "citrus_aliasname_local.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_mmap.h"
+
+#include "runetype_local.h"
+#include "multibyte.h"
+
+/*
+ * macro required by all template headers
+ */
+#define _PREFIX(name)          __CONCAT(_citrus_LC_CTYPE_, name)
+
+/*
+ * macro required by nb_lc_template(_decl).h
+ */
+#define _CATEGORY_TYPE          _RuneLocale
+
+#include "nb_lc_template_decl.h"
+
+static int
+_citrus_LC_CTYPE_create_impl(const char * __restrict root,
+    const char * __restrict name, _RuneLocale ** __restrict pdata)
+{
+       char path[PATH_MAX + 1];
+       int ret;
+       struct _region r;
+
+       _DIAGASSERT(root != NULL);
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(pdata != NULL);
+
+       snprintf(path, sizeof(path),
+           "%s/%s/LC_CTYPE", root, name);
+       ret = _citrus_map_file(&r, path);
+       if (!ret) {
+               ret = _rune_load((const char *)r.r_head, r.r_size, pdata);
+               _citrus_unmap_file(&r);
+       }
+       return ret;
+}
+
+static __inline void
+_PREFIX(build_cache)(struct _locale_cache_t * __restrict cache,
+    _RuneLocale * __restrict data)
+{
+       _DIAGASSERT(cache != NULL);
+       _DIAGASSERT(cache->items != NULL);
+       _DIAGASSERT(data != NULL);
+
+       cache->ctype_tab = data->rl_ctype_tab;
+       cache->tolower_tab = data->rl_tolower_tab;
+       cache->toupper_tab = data->rl_toupper_tab;
+       cache->mb_cur_max = _citrus_ctype_get_mb_cur_max(data->rl_citrus_ctype);
+       cache->items[(size_t)CODESET] = data->rl_codeset;
+}
+
+static __inline void
+_PREFIX(fixup)(_RuneLocale *data)
+{
+       _DIAGASSERT(data != NULL);
+
+       __mb_cur_max = _citrus_ctype_get_mb_cur_max(data->rl_citrus_ctype);
+       _ctype_ = data->rl_ctype_tab;
+       _tolower_tab_ = data->rl_tolower_tab;
+       _toupper_tab_ = data->rl_toupper_tab;
+       _CurrentRuneLocale = data;
+}
+
+/*
+ * macro required by nb_lc_template.h
+ */
+#define _CATEGORY_ID           LC_CTYPE
+#define _CATEGORY_NAME         "LC_CTYPE"
+#define _CATEGORY_DEFAULT      _DefaultRuneLocale
+
+#include "nb_lc_template.h"
+_LOCALE_CATEGORY_ENTRY(_citrus_LC_CTYPE_);
diff --git a/lib/nbsd_libc/citrus/citrus_lc_messages.c b/lib/nbsd_libc/citrus/citrus_lc_messages.c
new file mode 100644 (file)
index 0000000..6e62db5
--- /dev/null
@@ -0,0 +1,163 @@
+/* $NetBSD: citrus_lc_messages.c,v 1.4 2010/06/13 04:14:57 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_lc_messages.c,v 1.4 2010/06/13 04:14:57 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/localedef.h>
+#include <sys/queue.h>
+#include <assert.h>
+#include <errno.h>
+#include <langinfo.h>
+#include <limits.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "setlocale_local.h"
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_lookup.h"
+#include "citrus_aliasname_local.h"
+#include "citrus_module.h"
+#include "citrus_mmap.h"
+#include "citrus_hash.h"
+#include "citrus_db.h"
+#include "citrus_db_hash.h"
+#include "citrus_memstream.h"
+#include "runetype_local.h"
+
+/*
+ * macro required by all template headers
+ */
+#define _PREFIX(name)          __CONCAT(_citrus_LC_MESSAGES_, name)
+
+#include "nb_lc_messages_misc.h"
+#include "citrus_lc_template_decl.h"
+
+static __inline void
+_citrus_LC_MESSAGES_uninit(_MessagesLocale *data)
+{
+       free(__UNCONST(data->yesexpr));
+       free(__UNCONST(data->noexpr));
+       free(__UNCONST(data->yesstr));
+       free(__UNCONST(data->nostr));
+}
+
+#include "citrus_lc_messages.h"
+
+struct _citrus_LC_MESSAGES_key {
+       const char *name;
+       size_t offset;
+};
+
+#define OFFSET(field) (offsetof(_MessagesLocale, field))
+static const struct _citrus_LC_MESSAGES_key keys[] = {
+  { _CITRUS_LC_MESSAGES_SYM_YESEXPR, OFFSET(yesexpr) },
+  { _CITRUS_LC_MESSAGES_SYM_NOEXPR,  OFFSET(noexpr ) },
+  { _CITRUS_LC_MESSAGES_SYM_YESSTR,  OFFSET(yesstr ) },
+  { _CITRUS_LC_MESSAGES_SYM_NOSTR,   OFFSET(nostr  ) },
+  { NULL, 0 }
+};
+
+static __inline int
+_citrus_LC_MESSAGES_init_normal(_MessagesLocale * __restrict data,
+    struct _citrus_db * __restrict db)
+{
+       const struct _citrus_LC_MESSAGES_key *key;
+       char **p;
+       const char *s;
+
+       _DIAGASSERT(data != NULL);
+       _DIAGASSERT(db != NULL);
+
+       memset(data, 0, sizeof(*data));
+       for (key = &keys[0]; key->name != NULL; ++key) {
+               if (_db_lookupstr_by_s(db, key->name, &s, NULL))
+                       goto fatal;
+               p = (char **)(void *)
+                   (((char *)(void *)data) + key->offset);
+               *p = strdup(s);
+               if (*p == NULL)
+                       goto fatal;
+       }
+       return 0;
+
+fatal:
+       _citrus_LC_MESSAGES_uninit(data);
+       return EFTYPE;
+}
+
+static __inline int
+_citrus_LC_MESSAGES_init_fallback(_MessagesLocale * __restrict data,
+    struct _memstream * __restrict ms)
+{
+       const struct _citrus_LC_MESSAGES_key *key;
+       char **p;
+       const char *s;
+       size_t n;
+
+       _DIAGASSERT(data != NULL);
+       _DIAGASSERT(ms != NULL);
+
+       memset(data, 0, sizeof(*data));
+       for (key = &keys[0]; key->name != NULL; ++key) {
+               if ((s = _memstream_getln(ms, &n)) == NULL)
+                       goto fatal;
+               p = (char **)(void *)
+                   (((char *)(void *)data) + key->offset);
+               *p = strndup(s, n - 1);
+               if (*p == NULL)
+                       goto fatal;
+       }
+       return 0;
+
+fatal:
+       _citrus_LC_MESSAGES_uninit(data);
+       return EFTYPE;
+}
+
+/*
+ * macro required by citrus_lc_template.h
+ */
+#define _CATEGORY_DB           "LC_MESSAGES/SYS_LC_MESSAGES"
+#define _CATEGORY_MAGIC                _CITRUS_LC_MESSAGES_MAGIC_1
+
+#include "citrus_lc_template.h"
+_LOCALE_CATEGORY_ENTRY(_citrus_LC_MESSAGES_);
diff --git a/lib/nbsd_libc/citrus/citrus_lc_messages.h b/lib/nbsd_libc/citrus/citrus_lc_messages.h
new file mode 100644 (file)
index 0000000..cdf7d39
--- /dev/null
@@ -0,0 +1,47 @@
+/* $NetBSD: citrus_lc_messages.h,v 1.2 2009/01/11 02:46:24 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_LC_MESSAGES_H_
+#define _CITRUS_LC_MESSAGES_H_
+
+/*
+ *
+ */
+#define _CITRUS_LC_MESSAGES_MAGIC_1            "CtrsME10"
+#define _CITRUS_LC_MESSAGES_SYM_VERSION                "version"
+#define _CITRUS_LC_MESSAGES_VERSION            0x00000001
+
+/*
+ *
+ */
+#define _CITRUS_LC_MESSAGES_SYM_YESEXPR                        "yesexpr"
+#define _CITRUS_LC_MESSAGES_SYM_NOEXPR                 "noexpr"
+#define _CITRUS_LC_MESSAGES_SYM_YESSTR                 "yesstr"
+#define _CITRUS_LC_MESSAGES_SYM_NOSTR                  "nostr"
+
+#endif /*_CITRUS_LC_MESSAGES_H_*/
diff --git a/lib/nbsd_libc/citrus/citrus_lc_monetary.c b/lib/nbsd_libc/citrus/citrus_lc_monetary.c
new file mode 100644 (file)
index 0000000..833a5a1
--- /dev/null
@@ -0,0 +1,220 @@
+/* $NetBSD: citrus_lc_monetary.c,v 1.4 2010/06/13 04:14:57 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_lc_monetary.c,v 1.4 2010/06/13 04:14:57 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/localedef.h>
+#include <sys/queue.h>
+#include <assert.h>
+#include <errno.h>
+#include <langinfo.h>
+#include <limits.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "setlocale_local.h"
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_lookup.h"
+#include "citrus_aliasname_local.h"
+#include "citrus_module.h"
+#include "citrus_mmap.h"
+#include "citrus_hash.h"
+#include "citrus_db.h"
+#include "citrus_db_hash.h"
+#include "citrus_memstream.h"
+#include "runetype_local.h"
+
+#include "fix_grouping.h"
+#include "citrus_fix_grouping.h"
+
+/*
+ * macro required by all template headers
+ */
+#define _PREFIX(name)          __CONCAT(_citrus_LC_MONETARY_, name)
+
+#include "nb_lc_monetary_misc.h"
+#include "citrus_lc_template_decl.h"
+
+static __inline void
+_citrus_LC_MONETARY_uninit(_MonetaryLocale *data)
+{
+       _DIAGASSERT(data != NULL);
+
+       free(__UNCONST(data->int_curr_symbol));
+       free(__UNCONST(data->currency_symbol));
+       free(__UNCONST(data->mon_decimal_point));
+       free(__UNCONST(data->mon_thousands_sep));
+       free(__UNCONST(data->mon_grouping));
+       free(__UNCONST(data->positive_sign));
+       free(__UNCONST(data->negative_sign));
+}
+
+#include "citrus_lc_monetary.h"
+
+struct _citrus_LC_MONETARY_key {
+       const char *name;
+       size_t offset;
+};
+
+#define OFFSET(field) (offsetof(_MonetaryLocale, field))
+static const struct _citrus_LC_MONETARY_key keys_string[] = {
+  { _CITRUS_LC_MONETARY_SYM_INT_CURR_SYMBOL,    OFFSET(int_curr_symbol   ) },
+  { _CITRUS_LC_MONETARY_SYM_CURRENCY_SYMBOL,    OFFSET(currency_symbol   ) },
+  { _CITRUS_LC_MONETARY_SYM_MON_DECIMAL_POINT,  OFFSET(mon_decimal_point ) },
+  { _CITRUS_LC_MONETARY_SYM_MON_THOUSANDS_SEP,  OFFSET(mon_thousands_sep ) },
+  { _CITRUS_LC_MONETARY_SYM_MON_GROUPING,       OFFSET(mon_grouping      ) },
+  { _CITRUS_LC_MONETARY_SYM_POSITIVE_SIGN,      OFFSET(positive_sign     ) },
+  { _CITRUS_LC_MONETARY_SYM_NEGATIVE_SIGN,      OFFSET(negative_sign     ) },
+  { NULL, (size_t)0 }
+};
+static const struct _citrus_LC_MONETARY_key keys_char[] = {
+  { _CITRUS_LC_MONETARY_SYM_INT_FRAC_DIGITS,    OFFSET(int_frac_digits   ) },
+  { _CITRUS_LC_MONETARY_SYM_FRAC_DIGITS,        OFFSET(frac_digits       ) },
+  { _CITRUS_LC_MONETARY_SYM_P_CS_PRECEDES,      OFFSET(p_cs_precedes     ) },
+  { _CITRUS_LC_MONETARY_SYM_P_SEP_BY_SPACE,     OFFSET(p_sep_by_space    ) },
+  { _CITRUS_LC_MONETARY_SYM_N_CS_PRECEDES,      OFFSET(n_cs_precedes     ) },
+  { _CITRUS_LC_MONETARY_SYM_N_SEP_BY_SPACE,     OFFSET(n_sep_by_space    ) },
+  { _CITRUS_LC_MONETARY_SYM_P_SIGN_POSN,        OFFSET(p_sign_posn       ) },
+  { _CITRUS_LC_MONETARY_SYM_N_SIGN_POSN,        OFFSET(n_sign_posn       ) },
+  { _CITRUS_LC_MONETARY_SYM_INT_P_CS_PRECEDES,  OFFSET(int_p_cs_precedes ) },
+  { _CITRUS_LC_MONETARY_SYM_INT_N_CS_PRECEDES,  OFFSET(int_n_cs_precedes ) },
+  { _CITRUS_LC_MONETARY_SYM_INT_P_SEP_BY_SPACE, OFFSET(int_p_sep_by_space) },
+  { _CITRUS_LC_MONETARY_SYM_INT_N_SEP_BY_SPACE, OFFSET(int_n_sep_by_space) },
+  { _CITRUS_LC_MONETARY_SYM_INT_P_SIGN_POSN,    OFFSET(int_p_sign_posn   ) },
+  { _CITRUS_LC_MONETARY_SYM_INT_N_SIGN_POSN,    OFFSET(int_n_sign_posn   ) },
+  { NULL, (size_t)0 }
+};
+
+static __inline int
+_citrus_LC_MONETARY_init_normal(_MonetaryLocale * __restrict data,
+    struct _citrus_db * __restrict db)
+{
+       const struct _citrus_LC_MONETARY_key *key;
+       char **p_string, *p_char;
+       const char *s;
+       uint8_t u8;
+
+       _DIAGASSERT(data != NULL);
+       _DIAGASSERT(db != NULL);
+
+       memset(data, 0, sizeof(*data));
+       for (key = &keys_string[0]; key->name != NULL; ++key) {
+               if (_db_lookupstr_by_s(db, key->name, &s, NULL))
+                       goto fatal;
+               p_string = (char **)(void *)
+                   (((char *)(void *)data) + key->offset);
+               *p_string = strdup(s);
+               if (*p_string == NULL)
+                       goto fatal;
+       }
+       for (key = &keys_char[0]; key->name != NULL; ++key) {
+               if (_db_lookup8_by_s(db, key->name, &u8, NULL))
+                       goto fatal;
+               p_char = ((char *)(void *)data) + key->offset;
+               *p_char = (char)(unsigned char)u8;
+       }
+       _CITRUS_FIXUP_CHAR_MAX_MD(data->mon_grouping);
+
+       return 0;
+
+fatal:
+       _citrus_LC_MONETARY_uninit(data);
+       return EFTYPE;
+}
+
+static __inline int
+_citrus_LC_MONETARY_init_fallback(_MonetaryLocale * __restrict data,
+    struct _memstream * __restrict ms)
+{
+       const struct _citrus_LC_MONETARY_key *key;
+       char **p_string, *p_char;
+       const char *s;
+       size_t n;
+       char *t;
+       long int l;
+
+       _DIAGASSERT(data != NULL);
+       _DIAGASSERT(ms != NULL);
+
+       memset(data, 0, sizeof(*data));
+       for (key = &keys_string[0]; key->name != NULL; ++key) {
+               if ((s = _memstream_getln(ms, &n)) == NULL)
+                       goto fatal;
+               p_string = (char **)(void *)
+                   (((char *)(void *)data) + key->offset);
+               *p_string = strndup(s, n - 1);
+               if (*p_string == NULL)
+                       goto fatal;
+       }
+       for (key = &keys_char[0]; key->name != NULL; ++key) {
+               if ((s = _memstream_getln(ms, &n)) == NULL)
+                       goto fatal;
+               t = strndup(s, n - 1);
+               if (t == NULL)
+                       goto fatal;
+               s = (const char *)t;
+               l = _bcs_strtol(s, &t, 0);
+               if (s == t || l < 0 || l > 0x7fL) {
+                       free(t);
+                       goto fatal;
+               }
+               free(t);
+               p_char = ((char *)(void *)data) + key->offset;
+               *p_char = (char)(l & 0x7fL);
+       }
+        data->mon_grouping =
+           __fix_locale_grouping_str(data->mon_grouping);
+       return 0;
+
+fatal:
+       _citrus_LC_MONETARY_uninit(data);
+       return EFTYPE;
+}
+
+/*
+ * macro required by citrus_lc_template.h
+ */
+#define _CATEGORY_DB           "LC_MONETARY"
+#define _CATEGORY_MAGIC                _CITRUS_LC_MONETARY_MAGIC_1
+
+#include "citrus_lc_template.h"
+_LOCALE_CATEGORY_ENTRY(_citrus_LC_MONETARY_);
diff --git a/lib/nbsd_libc/citrus/citrus_lc_monetary.h b/lib/nbsd_libc/citrus/citrus_lc_monetary.h
new file mode 100644 (file)
index 0000000..0ef146c
--- /dev/null
@@ -0,0 +1,64 @@
+/* $NetBSD: citrus_lc_monetary.h,v 1.2 2009/01/11 02:46:24 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_LC_MONETARY_H_
+#define _CITRUS_LC_MONETARY_H_
+
+/*
+ *
+ */
+#define _CITRUS_LC_MONETARY_MAGIC_1            "CtrsMO10"
+#define _CITRUS_LC_MONETARY_SYM_VERSION                "version"
+#define _CITRUS_LC_MONETARY_VERSION            0x00000001
+
+/*
+ *
+ */
+#define _CITRUS_LC_MONETARY_SYM_INT_CURR_SYMBOL                "int_curr_symbol"
+#define _CITRUS_LC_MONETARY_SYM_CURRENCY_SYMBOL                "currency_symbol"
+#define _CITRUS_LC_MONETARY_SYM_MON_DECIMAL_POINT      "mon_decimal_point"
+#define _CITRUS_LC_MONETARY_SYM_MON_THOUSANDS_SEP      "mon_thousands_sep"
+#define _CITRUS_LC_MONETARY_SYM_MON_GROUPING           "mon_grouping"
+#define _CITRUS_LC_MONETARY_SYM_POSITIVE_SIGN          "positive_sign"
+#define _CITRUS_LC_MONETARY_SYM_NEGATIVE_SIGN          "negative_sign"
+#define _CITRUS_LC_MONETARY_SYM_INT_FRAC_DIGITS                "int_frac_digits"
+#define _CITRUS_LC_MONETARY_SYM_FRAC_DIGITS            "frac_digits"
+#define _CITRUS_LC_MONETARY_SYM_P_CS_PRECEDES          "p_cs_precedes"
+#define _CITRUS_LC_MONETARY_SYM_P_SEP_BY_SPACE         "p_sep_by_space"
+#define _CITRUS_LC_MONETARY_SYM_N_CS_PRECEDES          "n_cs_precedes"
+#define _CITRUS_LC_MONETARY_SYM_N_SEP_BY_SPACE         "n_sep_by_space"
+#define _CITRUS_LC_MONETARY_SYM_P_SIGN_POSN            "p_sign_posn"
+#define _CITRUS_LC_MONETARY_SYM_N_SIGN_POSN            "n_sign_posn"
+#define _CITRUS_LC_MONETARY_SYM_INT_P_CS_PRECEDES      "int_p_cs_precedes"
+#define _CITRUS_LC_MONETARY_SYM_INT_N_CS_PRECEDES      "int_n_cs_precedes"
+#define _CITRUS_LC_MONETARY_SYM_INT_P_SEP_BY_SPACE     "int_p_sep_by_space"
+#define _CITRUS_LC_MONETARY_SYM_INT_N_SEP_BY_SPACE     "int_n_sep_by_space"
+#define _CITRUS_LC_MONETARY_SYM_INT_P_SIGN_POSN                "int_p_sign_posn"
+#define _CITRUS_LC_MONETARY_SYM_INT_N_SIGN_POSN                "int_n_sign_posn"
+
+#endif /*_CITRUS_LC_MONETARY_H_*/
diff --git a/lib/nbsd_libc/citrus/citrus_lc_numeric.c b/lib/nbsd_libc/citrus/citrus_lc_numeric.c
new file mode 100644 (file)
index 0000000..65616ee
--- /dev/null
@@ -0,0 +1,169 @@
+/* $NetBSD: citrus_lc_numeric.c,v 1.4 2010/06/13 04:14:57 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_lc_numeric.c,v 1.4 2010/06/13 04:14:57 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/localedef.h>
+#include <sys/queue.h>
+#include <assert.h>
+#include <errno.h>
+#include <langinfo.h>
+#include <limits.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "setlocale_local.h"
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_lookup.h"
+#include "citrus_aliasname_local.h"
+#include "citrus_module.h"
+#include "citrus_mmap.h"
+#include "citrus_hash.h"
+#include "citrus_db.h"
+#include "citrus_db_hash.h"
+#include "citrus_memstream.h"
+#include "runetype_local.h"
+
+#include "fix_grouping.h"
+#include "citrus_fix_grouping.h"
+
+/*
+ * macro required by all template headers
+ */
+#define _PREFIX(name)          __CONCAT(_citrus_LC_NUMERIC_, name)
+
+#include "nb_lc_numeric_misc.h"
+#include "citrus_lc_template_decl.h"
+
+static __inline void
+_citrus_LC_NUMERIC_uninit(_NumericLocale *data)
+{
+       free(__UNCONST(data->decimal_point));
+       free(__UNCONST(data->thousands_sep));
+       free(__UNCONST(data->grouping));
+}
+
+#include "citrus_lc_numeric.h"
+
+struct _citrus_LC_NUMERIC_key {
+       const char *name;
+       size_t offset;
+};
+
+#define OFFSET(field) (offsetof(_NumericLocale, field))
+static const struct _citrus_LC_NUMERIC_key keys[] = {
+  { _CITRUS_LC_NUMERIC_SYM_DECIMAL_POINT, OFFSET(decimal_point) },
+  { _CITRUS_LC_NUMERIC_SYM_THOUSANDS_SEP, OFFSET(thousands_sep) },
+  { _CITRUS_LC_NUMERIC_SYM_GROUPING,      OFFSET(grouping     ) },
+  { NULL, 0 }
+};
+
+static __inline int
+_citrus_LC_NUMERIC_init_normal(_NumericLocale * __restrict data,
+    struct _citrus_db * __restrict db)
+{
+       const struct _citrus_LC_NUMERIC_key *key;
+       char **p;
+       const char *s;
+
+       _DIAGASSERT(data != NULL);
+       _DIAGASSERT(db != NULL);
+
+       memset(data, 0, sizeof(*data));
+       for (key = &keys[0]; key->name != NULL; ++key) {
+               if (_db_lookupstr_by_s(db, key->name, &s, NULL))
+                       goto fatal;
+               p = (char **)(void *)
+                   (((char *)(void *)data) + key->offset);
+               *p = strdup(s);
+               if (*p == NULL)
+                       goto fatal;
+       }
+       _CITRUS_FIXUP_CHAR_MAX_MD(data->grouping);
+
+       return 0;
+
+fatal:
+       _citrus_LC_NUMERIC_uninit(data);
+       return EFTYPE;
+}
+
+static __inline int
+_citrus_LC_NUMERIC_init_fallback(_NumericLocale * __restrict data,
+    struct _memstream * __restrict ms)
+{
+       const struct _citrus_LC_NUMERIC_key *key;
+       char **p;
+       const char *s;
+       size_t n;
+
+       _DIAGASSERT(data != NULL);
+       _DIAGASSERT(ms != NULL);
+
+       memset(data, 0, sizeof(*data));
+       for (key = &keys[0]; key->name != NULL; ++key) {
+               if ((s = _memstream_getln(ms, &n)) == NULL)
+                       goto fatal;
+               p = (char **)(void *)
+                   (((char *)(void *)data) + key->offset);
+               *p = strndup(s, n - 1);
+               if (*p == NULL)
+                       goto fatal;
+       }
+       data->grouping =
+           __fix_locale_grouping_str(data->grouping);
+
+       return 0;
+
+fatal:
+       _citrus_LC_NUMERIC_uninit(data);
+       return EFTYPE;
+}
+
+/*
+ * macro required by citrus_lc_template.h
+ */
+#define _CATEGORY_DB           "LC_NUMERIC"
+#define _CATEGORY_MAGIC                _CITRUS_LC_NUMERIC_MAGIC_1
+
+#include "citrus_lc_template.h"
+_LOCALE_CATEGORY_ENTRY(_citrus_LC_NUMERIC_);
diff --git a/lib/nbsd_libc/citrus/citrus_lc_numeric.h b/lib/nbsd_libc/citrus/citrus_lc_numeric.h
new file mode 100644 (file)
index 0000000..cf9bdd8
--- /dev/null
@@ -0,0 +1,46 @@
+/* $NetBSD: citrus_lc_numeric.h,v 1.2 2009/01/11 02:46:24 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_LC_NUMERIC_H_
+#define _CITRUS_LC_NUMERIC_H_
+
+/*
+ *
+ */
+#define _CITRUS_LC_NUMERIC_MAGIC_1     "CtrsNU10"
+#define _CITRUS_LC_NUMERIC_SYM_VERSION "version"
+#define _CITRUS_LC_NUMERIC_VERSION     0x00000001
+
+/*
+ *
+ */
+#define _CITRUS_LC_NUMERIC_SYM_DECIMAL_POINT           "decimal_point"
+#define _CITRUS_LC_NUMERIC_SYM_THOUSANDS_SEP           "thousands_sep"
+#define _CITRUS_LC_NUMERIC_SYM_GROUPING                        "grouping"
+
+#endif /*_CITRUS_LC_NUMERIC_H_*/
diff --git a/lib/nbsd_libc/citrus/citrus_lc_template.h b/lib/nbsd_libc/citrus/citrus_lc_template.h
new file mode 100644 (file)
index 0000000..42b2c22
--- /dev/null
@@ -0,0 +1,74 @@
+/* $NetBSD: citrus_lc_template.h,v 1.2 2009/01/11 02:46:24 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_LC_TEMPLATE_H_
+#define _CITRUS_LC_TEMPLATE_H_
+
+static __inline int
+_PREFIX(create_impl)(const char * __restrict root,
+    const char * __restrict name, _CATEGORY_TYPE ** __restrict pdata)
+{
+       char path[PATH_MAX + 1];
+       int ret;
+       struct _region file;
+       struct _citrus_db *db;
+       struct _memstream ms;
+       _CATEGORY_TYPE *data;
+
+       snprintf(path, sizeof(path),
+           "%s/%s/" _CATEGORY_DB, root, name);
+       ret = _map_file(&file, path);
+       if (ret) {
+               ret = ENOENT;
+       } else {
+               data = malloc(sizeof(*data));
+               if (!data) {
+                       ret = ENOMEM;
+               } else {
+                       ret = _db_open(&db, &file, _CATEGORY_MAGIC,
+                           &_db_hash_std, NULL);
+                       if (!ret) {
+                               ret = _PREFIX(init_normal)(data, db);
+                               _db_close(db);
+                       } else {
+                               _memstream_bind(&ms, &file);
+                               ret = _PREFIX(init_fallback)(data, &ms);
+                       }
+                       if (!ret)
+                               *pdata = data;
+                       else
+                               free(data);
+               }
+               _unmap_file(&file);
+       }
+       return ret;
+}
+
+#include "nb_lc_template.h"
+
+#endif /* _CITRUS_LC_TEMPLATE_H_ */
diff --git a/lib/nbsd_libc/citrus/citrus_lc_template_decl.h b/lib/nbsd_libc/citrus/citrus_lc_template_decl.h
new file mode 100644 (file)
index 0000000..e83c691
--- /dev/null
@@ -0,0 +1,42 @@
+/* $NetBSD: citrus_lc_template_decl.h,v 1.2 2009/01/11 02:46:24 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_LC_TEMPLATE_DECL_H_
+#define _CITRUS_LC_TEMPLATE_DECL_H_
+
+#include "nb_lc_template_decl.h"
+
+static __inline int
+_PREFIX(init_normal)(_CATEGORY_TYPE * __restrict,
+    struct _citrus_db * __restrict db);
+
+static __inline int
+_PREFIX(init_fallback)(_CATEGORY_TYPE * __restrict,
+    struct _memstream * __restrict);
+
+#endif /*_CITRUS_LC_TEMPLATE_DECL_H_*/
diff --git a/lib/nbsd_libc/citrus/citrus_lc_time.c b/lib/nbsd_libc/citrus/citrus_lc_time.c
new file mode 100644 (file)
index 0000000..e2100af
--- /dev/null
@@ -0,0 +1,214 @@
+/* $NetBSD: citrus_lc_time.c,v 1.5 2010/06/13 04:14:57 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_lc_time.c,v 1.5 2010/06/13 04:14:57 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/localedef.h>
+#include <sys/queue.h>
+#include <assert.h>
+#include <errno.h>
+#include <langinfo.h>
+#include <limits.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "setlocale_local.h"
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_lookup.h"
+#include "citrus_aliasname_local.h"
+#include "citrus_module.h"
+#include "citrus_mmap.h"
+#include "citrus_hash.h"
+#include "citrus_db.h"
+#include "citrus_db_hash.h"
+#include "citrus_memstream.h"
+#include "runetype_local.h"
+
+/*
+ * macro required by all template headers
+ */
+#define _PREFIX(name)          __CONCAT(_citrus_LC_TIME_, name)
+
+#include "nb_lc_time_misc.h"
+#include "citrus_lc_template_decl.h"
+
+static __inline void
+_citrus_LC_TIME_uninit(_TimeLocale *data)
+{
+       size_t i, j;
+
+       _DIAGASSERT(data != NULL);
+
+       for (i = ABDAY_IDX(ABDAY_1), j = ABDAY_IDX(ABDAY_7);  i <= j; ++i)
+               free(__UNCONST(data->abday[i]));
+       for (i = DAY_IDX(DAY_1),     j = DAY_IDX(DAY_7);      i <= j; ++i)
+               free(__UNCONST(data->day[i]));
+       for (i = ABMON_IDX(ABMON_1), j = ABMON_IDX(ABMON_12); i <= j; ++i)
+               free(__UNCONST(data->abmon[i]));
+       for (i = MON_IDX(MON_1),     j = MON_IDX(MON_12);     i <= j; ++i)
+               free(__UNCONST(data->mon[i]));
+       for (i = AM_PM_IDX(AM_STR),  j = AM_PM_IDX(PM_STR);   i <= j; ++i)
+               free(__UNCONST(data->am_pm[i]));
+       free(__UNCONST(data->d_t_fmt));
+       free(__UNCONST(data->d_fmt));
+       free(__UNCONST(data->t_fmt));
+       free(__UNCONST(data->t_fmt_ampm));
+}
+
+#include "citrus_lc_time.h"
+
+struct _citrus_LC_TIME_key {
+       const char *name;
+       size_t offset;
+};
+
+#define OFFSET(field) offsetof(_TimeLocale, field)
+static const struct _citrus_LC_TIME_key keys[] = {
+  { _CITRUS_LC_TIME_SYM_ABDAY_1,  OFFSET(abday[ABDAY_IDX(ABDAY_1)] ) },
+  { _CITRUS_LC_TIME_SYM_ABDAY_2,  OFFSET(abday[ABDAY_IDX(ABDAY_2)] ) },
+  { _CITRUS_LC_TIME_SYM_ABDAY_3,  OFFSET(abday[ABDAY_IDX(ABDAY_3)] ) },
+  { _CITRUS_LC_TIME_SYM_ABDAY_4,  OFFSET(abday[ABDAY_IDX(ABDAY_4)] ) },
+  { _CITRUS_LC_TIME_SYM_ABDAY_5,  OFFSET(abday[ABDAY_IDX(ABDAY_5)] ) },
+  { _CITRUS_LC_TIME_SYM_ABDAY_6,  OFFSET(abday[ABDAY_IDX(ABDAY_6)] ) },
+  { _CITRUS_LC_TIME_SYM_ABDAY_7,  OFFSET(abday[ABDAY_IDX(ABDAY_7)] ) },
+  { _CITRUS_LC_TIME_SYM_DAY_1,    OFFSET(day[DAY_IDX(DAY_1)]       ) },
+  { _CITRUS_LC_TIME_SYM_DAY_2,    OFFSET(day[DAY_IDX(DAY_2)]       ) },
+  { _CITRUS_LC_TIME_SYM_DAY_3,    OFFSET(day[DAY_IDX(DAY_3)]       ) },
+  { _CITRUS_LC_TIME_SYM_DAY_4,    OFFSET(day[DAY_IDX(DAY_4)]       ) },
+  { _CITRUS_LC_TIME_SYM_DAY_5,    OFFSET(day[DAY_IDX(DAY_5)]       ) },
+  { _CITRUS_LC_TIME_SYM_DAY_6,    OFFSET(day[DAY_IDX(DAY_6)]       ) },
+  { _CITRUS_LC_TIME_SYM_DAY_7,    OFFSET(day[DAY_IDX(DAY_7)]       ) },
+  { _CITRUS_LC_TIME_SYM_ABMON_1,  OFFSET(abmon[ABMON_IDX(ABMON_1)] ) },
+  { _CITRUS_LC_TIME_SYM_ABMON_2,  OFFSET(abmon[ABMON_IDX(ABMON_2)] ) },
+  { _CITRUS_LC_TIME_SYM_ABMON_3,  OFFSET(abmon[ABMON_IDX(ABMON_3)] ) },
+  { _CITRUS_LC_TIME_SYM_ABMON_4,  OFFSET(abmon[ABMON_IDX(ABMON_4)] ) },
+  { _CITRUS_LC_TIME_SYM_ABMON_5,  OFFSET(abmon[ABMON_IDX(ABMON_5)] ) },
+  { _CITRUS_LC_TIME_SYM_ABMON_6,  OFFSET(abmon[ABMON_IDX(ABMON_6)] ) },
+  { _CITRUS_LC_TIME_SYM_ABMON_7,  OFFSET(abmon[ABMON_IDX(ABMON_7)] ) },
+  { _CITRUS_LC_TIME_SYM_ABMON_8,  OFFSET(abmon[ABMON_IDX(ABMON_8)] ) },
+  { _CITRUS_LC_TIME_SYM_ABMON_9,  OFFSET(abmon[ABMON_IDX(ABMON_9)] ) },
+  { _CITRUS_LC_TIME_SYM_ABMON_10, OFFSET(abmon[ABMON_IDX(ABMON_10)]) },
+  { _CITRUS_LC_TIME_SYM_ABMON_11, OFFSET(abmon[ABMON_IDX(ABMON_11)]) },
+  { _CITRUS_LC_TIME_SYM_ABMON_12, OFFSET(abmon[ABMON_IDX(ABMON_12)]) },
+  { _CITRUS_LC_TIME_SYM_MON_1,    OFFSET(mon[MON_IDX(MON_1)]       ) },
+  { _CITRUS_LC_TIME_SYM_MON_2,    OFFSET(mon[MON_IDX(MON_2)]       ) },
+  { _CITRUS_LC_TIME_SYM_MON_3,    OFFSET(mon[MON_IDX(MON_3)]       ) },
+  { _CITRUS_LC_TIME_SYM_MON_4,    OFFSET(mon[MON_IDX(MON_4)]       ) },
+  { _CITRUS_LC_TIME_SYM_MON_5,    OFFSET(mon[MON_IDX(MON_5)]       ) },
+  { _CITRUS_LC_TIME_SYM_MON_6,    OFFSET(mon[MON_IDX(MON_6)]       ) },
+  { _CITRUS_LC_TIME_SYM_MON_7,    OFFSET(mon[MON_IDX(MON_7)]       ) },
+  { _CITRUS_LC_TIME_SYM_MON_8,    OFFSET(mon[MON_IDX(MON_8)]       ) },
+  { _CITRUS_LC_TIME_SYM_MON_9,    OFFSET(mon[MON_IDX(MON_9)]       ) },
+  { _CITRUS_LC_TIME_SYM_MON_10,   OFFSET(mon[MON_IDX(MON_10)]      ) },
+  { _CITRUS_LC_TIME_SYM_MON_11,   OFFSET(mon[MON_IDX(MON_11)]      ) },
+  { _CITRUS_LC_TIME_SYM_MON_12,   OFFSET(mon[MON_IDX(MON_12)]      ) },
+  { _CITRUS_LC_TIME_SYM_AM_STR,   OFFSET(am_pm[AM_PM_IDX(AM_STR)]  ) },
+  { _CITRUS_LC_TIME_SYM_PM_STR,   OFFSET(am_pm[AM_PM_IDX(PM_STR)]  ) },
+  { _CITRUS_LC_TIME_SYM_D_T_FMT,  OFFSET(d_t_fmt                   ) },
+  { _CITRUS_LC_TIME_SYM_D_FMT,    OFFSET(d_fmt                     ) },
+  { _CITRUS_LC_TIME_SYM_T_FMT,    OFFSET(t_fmt                     ) },
+  { _CITRUS_LC_TIME_SYM_T_FMT_AMPM, OFFSET(t_fmt_ampm                ) },
+  { NULL, 0 }
+};
+
+static __inline int
+_citrus_LC_TIME_init_normal(_TimeLocale * __restrict data,
+    struct _citrus_db * __restrict db)
+{
+        const struct _citrus_LC_TIME_key *key;
+       char **p;
+       const char *s;
+
+       _DIAGASSERT(data != NULL);
+       _DIAGASSERT(db != NULL);
+
+       memset(data, 0, sizeof(*data));
+       for (key = &keys[0]; key->name != NULL; ++key) {
+               if (_db_lookupstr_by_s(db, key->name, &s, NULL))
+                       goto fatal;
+               p = (char **)(void *)
+                   (((char *)(void *)data) + key->offset);
+               *p = strdup(s);
+               if (*p == NULL)
+                       goto fatal;
+       }
+       return 0;
+
+fatal:
+       _citrus_LC_TIME_uninit(data);
+       return EFTYPE;
+}
+
+static __inline int
+_citrus_LC_TIME_init_fallback(_TimeLocale * __restrict data,
+    struct _memstream * __restrict ms)
+{
+        const struct _citrus_LC_TIME_key *key;
+       char **p;
+       const char *s;
+       size_t n;
+
+       memset(data, 0, sizeof(*data));
+       for (key = &keys[0]; key->name != NULL; ++key) {
+               if ((s = _memstream_getln(ms, &n)) == NULL)
+                       goto fatal;
+               p = (char **)(void *)
+                   (((char *)(void *)data) + key->offset);
+               *p = strndup(s, n - 1);
+               if (*p == NULL)
+                       goto fatal;
+       }
+       return 0;
+
+fatal:
+       _citrus_LC_TIME_uninit(data);
+       return EFTYPE;
+}
+
+/*
+ * macro required by citrus_lc_template.h
+ */
+#define _CATEGORY_DB           "LC_TIME"
+#define _CATEGORY_MAGIC                _CITRUS_LC_TIME_MAGIC_1
+
+#include "citrus_lc_template.h"
+_LOCALE_CATEGORY_ENTRY(_citrus_LC_TIME_);
diff --git a/lib/nbsd_libc/citrus/citrus_lc_time.h b/lib/nbsd_libc/citrus/citrus_lc_time.h
new file mode 100644 (file)
index 0000000..3b9616f
--- /dev/null
@@ -0,0 +1,87 @@
+/* $NetBSD: citrus_lc_time.h,v 1.2 2009/01/11 02:46:24 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_LC_TIME_H_
+#define _CITRUS_LC_TIME_H_
+
+/*
+ *
+ */
+#define _CITRUS_LC_TIME_MAGIC_1                "CtrsTI10"
+#define _CITRUS_LC_TIME_SYM_VERSION    "version"
+#define _CITRUS_LC_TIME_VERSION                0x00000001
+
+/*
+ *
+ */
+#define _CITRUS_LC_TIME_SYM_ABDAY_1                    "abday1"
+#define _CITRUS_LC_TIME_SYM_ABDAY_2                    "abday2"
+#define _CITRUS_LC_TIME_SYM_ABDAY_3                    "abday3"
+#define _CITRUS_LC_TIME_SYM_ABDAY_4                    "abday4"
+#define _CITRUS_LC_TIME_SYM_ABDAY_5                    "abday5"
+#define _CITRUS_LC_TIME_SYM_ABDAY_6                    "abday6"
+#define _CITRUS_LC_TIME_SYM_ABDAY_7                    "abday7"
+#define _CITRUS_LC_TIME_SYM_DAY_1                      "day1"
+#define _CITRUS_LC_TIME_SYM_DAY_2                      "day2"
+#define _CITRUS_LC_TIME_SYM_DAY_3                      "day3"
+#define _CITRUS_LC_TIME_SYM_DAY_4                      "day4"
+#define _CITRUS_LC_TIME_SYM_DAY_5                      "day5"
+#define _CITRUS_LC_TIME_SYM_DAY_6                      "day6"
+#define _CITRUS_LC_TIME_SYM_DAY_7                      "day7"
+#define _CITRUS_LC_TIME_SYM_ABMON_1                    "abmon_1"
+#define _CITRUS_LC_TIME_SYM_ABMON_2                    "abmon_2"
+#define _CITRUS_LC_TIME_SYM_ABMON_3                    "abmon_3"
+#define _CITRUS_LC_TIME_SYM_ABMON_4                    "abmon_4"
+#define _CITRUS_LC_TIME_SYM_ABMON_5                    "abmon_5"
+#define _CITRUS_LC_TIME_SYM_ABMON_6                    "abmon_6"
+#define _CITRUS_LC_TIME_SYM_ABMON_7                    "abmon_7"
+#define _CITRUS_LC_TIME_SYM_ABMON_8                    "abmon_8"
+#define _CITRUS_LC_TIME_SYM_ABMON_9                    "abmon_9"
+#define _CITRUS_LC_TIME_SYM_ABMON_10                   "abmon_10"
+#define _CITRUS_LC_TIME_SYM_ABMON_11                   "abmon_11"
+#define _CITRUS_LC_TIME_SYM_ABMON_12                   "abmon_12"
+#define _CITRUS_LC_TIME_SYM_MON_1                      "mon_1"
+#define _CITRUS_LC_TIME_SYM_MON_2                      "mon_2"
+#define _CITRUS_LC_TIME_SYM_MON_3                      "mon_3"
+#define _CITRUS_LC_TIME_SYM_MON_4                      "mon_4"
+#define _CITRUS_LC_TIME_SYM_MON_5                      "mon_5"
+#define _CITRUS_LC_TIME_SYM_MON_6                      "mon_6"
+#define _CITRUS_LC_TIME_SYM_MON_7                      "mon_7"
+#define _CITRUS_LC_TIME_SYM_MON_8                      "mon_8"
+#define _CITRUS_LC_TIME_SYM_MON_9                      "mon_9"
+#define _CITRUS_LC_TIME_SYM_MON_10                     "mon_10"
+#define _CITRUS_LC_TIME_SYM_MON_11                     "mon_11"
+#define _CITRUS_LC_TIME_SYM_MON_12                     "mon_12"
+#define _CITRUS_LC_TIME_SYM_AM_STR                     "am_str"
+#define _CITRUS_LC_TIME_SYM_PM_STR                     "pm_str"
+#define _CITRUS_LC_TIME_SYM_D_T_FMT                    "d_t_fmt"
+#define _CITRUS_LC_TIME_SYM_D_FMT                      "d_fmt"
+#define _CITRUS_LC_TIME_SYM_T_FMT                      "t_fmt"
+#define _CITRUS_LC_TIME_SYM_T_FMT_AMPM                 "t_fmt_ampm"
+
+#endif /*_CITRUS_LC_TIME_H_*/
diff --git a/lib/nbsd_libc/citrus/citrus_lookup.c b/lib/nbsd_libc/citrus/citrus_lookup.c
new file mode 100644 (file)
index 0000000..95adc58
--- /dev/null
@@ -0,0 +1,356 @@
+/*     $NetBSD: citrus_lookup.c,v 1.6 2009/02/03 04:58:38 lukem Exp $  */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_lookup.c,v 1.6 2009/02/03 04:58:38 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <paths.h>
+#include <dirent.h>
+#include <sys/types.h>
+
+#include "citrus_namespace.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_memstream.h"
+#include "citrus_mmap.h"
+#include "citrus_db.h"
+#include "citrus_db_hash.h"
+#include "citrus_lookup.h"
+#include "citrus_lookup_file.h"
+
+struct _citrus_lookup {
+       union {
+               struct {
+                       struct _citrus_db *db;
+                       struct _citrus_region file;
+                       int num, idx;
+                       struct _db_locator locator;
+               } db;
+               struct {
+                       struct _region r;
+                       struct _memstream ms;
+               } plain;
+       } u;
+#define cl_db          u.db.db
+#define cl_dbidx       u.db.idx
+#define cl_dbfile      u.db.file
+#define cl_dbnum       u.db.num
+#define cl_dblocator   u.db.locator
+#define cl_plainr      u.plain.r
+#define cl_plainms     u.plain.ms
+       int cl_ignore_case;
+       int cl_rewind;
+       char *cl_key;
+       size_t cl_keylen;
+       int (*cl_next)(struct _citrus_lookup *, struct _region *,
+                      struct _region *);
+       int (*cl_lookup)(struct _citrus_lookup *, const char *,
+                        struct _region *);
+       int (*cl_num_entries)(struct _citrus_lookup *);
+       void (*cl_close)(struct _citrus_lookup *);
+};
+
+static int
+seq_get_num_entries_db(struct _citrus_lookup *cl)
+{
+       return cl->cl_dbnum;
+}
+
+static int
+seq_next_db(struct _citrus_lookup *cl,
+           struct _region *key, struct _region *data)
+{
+
+       if (cl->cl_key) {
+               if (key)
+                       _region_init(key, cl->cl_key, cl->cl_keylen);
+               return _db_lookup_by_s(cl->cl_db, cl->cl_key, data,
+                                      &cl->cl_dblocator);
+       }
+
+       if (cl->cl_rewind) {
+               cl->cl_dbidx = 0;
+       }
+       cl->cl_rewind = 0;
+       if (cl->cl_dbidx >= cl->cl_dbnum)
+               return ENOENT;
+
+       return _db_get_entry(cl->cl_db, cl->cl_dbidx++, key, data);
+}
+
+static int
+seq_lookup_db(struct _citrus_lookup *cl, const char *key,
+             struct _region *data)
+{
+       cl->cl_rewind = 0;
+       free(cl->cl_key);
+       cl->cl_key = strdup(key);
+       if (cl->cl_ignore_case)
+               _bcs_convert_to_lower(cl->cl_key);
+       cl->cl_keylen = strlen(cl->cl_key);
+       _db_locator_init(&cl->cl_dblocator);
+       return _db_lookup_by_s(cl->cl_db, cl->cl_key, data, &cl->cl_dblocator);
+}
+
+static void
+seq_close_db(struct _citrus_lookup *cl)
+{
+       _db_close(cl->cl_db);
+       _unmap_file(&cl->cl_dbfile);
+}
+
+static int
+seq_open_db(struct _citrus_lookup *cl, const char *name)
+{
+       int ret;
+       struct _region r;
+       char path[PATH_MAX];
+
+       snprintf(path, sizeof(path), "%s.db", name);
+       ret = _map_file(&r, path);
+       if (ret)
+               return ret;
+
+       ret = _db_open(&cl->cl_db, &r, _CITRUS_LOOKUP_MAGIC,
+                      _db_hash_std, NULL);
+       if (ret) {
+               _unmap_file(&r);
+               return ret;
+       }
+
+       cl->cl_dbfile = r;
+       cl->cl_dbnum = _db_get_num_entries(cl->cl_db);
+       cl->cl_dbidx = 0;
+       cl->cl_rewind = 1;
+       cl->cl_lookup = &seq_lookup_db;
+       cl->cl_next = &seq_next_db;
+       cl->cl_num_entries = &seq_get_num_entries_db;
+       cl->cl_close = &seq_close_db;
+
+       return 0;
+}
+
+#define T_COMM '#'
+static int
+seq_next_plain(struct _citrus_lookup *cl, struct _region *key,
+              struct _region *data)
+{
+       const char *p, *q;
+       size_t len;
+
+       if (cl->cl_rewind)
+               _memstream_bind(&cl->cl_plainms, &cl->cl_plainr);
+       cl->cl_rewind = 0;
+
+retry:
+       p = _memstream_getln(&cl->cl_plainms, &len);
+       if (p == NULL)
+               return ENOENT;
+       /* ignore comment */
+       q = memchr(p, T_COMM, len);
+       if (q) {
+               len = q-p;
+       }
+       /* ignore trailing spaces */
+       _bcs_trunc_rws_len(p, &len);
+       p = _bcs_skip_ws_len(p, &len);
+       q = _bcs_skip_nonws_len(p, &len);
+       if (p==q)
+               goto retry;
+       if (cl->cl_key && ((size_t)(q-p) != cl->cl_keylen ||
+                          memcmp(p, cl->cl_key, (size_t)(q-p)) != 0))
+               goto retry;
+
+       /* found a entry */
+       if (key)
+               _region_init(key, __UNCONST(p), (size_t)(q-p));
+       p = _bcs_skip_ws_len(q, &len);
+       if (data)
+               _region_init(data, len ? __UNCONST(p) : NULL, len);
+
+       return 0;
+}
+
+static int
+seq_get_num_entries_plain(struct _citrus_lookup *cl)
+{
+       int num;
+
+       num = 0;
+       while (seq_next_plain(cl, NULL, NULL) == 0)
+               num++;
+
+       return num;
+}
+
+static int
+seq_lookup_plain(struct _citrus_lookup *cl, const char *key,
+                struct _region *data)
+{
+       size_t len;
+       const char *p;
+
+       cl->cl_rewind = 0;
+       free(cl->cl_key);
+       cl->cl_key = strdup(key);
+       if (cl->cl_ignore_case)
+               _bcs_convert_to_lower(cl->cl_key);
+       cl->cl_keylen = strlen(cl->cl_key);
+       _memstream_bind(&cl->cl_plainms, &cl->cl_plainr);
+       p = _memstream_matchline(&cl->cl_plainms, cl->cl_key, &len, 0);
+       if (p == NULL)
+               return ENOENT;
+       if (data)
+               _region_init(data, __UNCONST(p), len);
+
+       return 0;
+}
+
+static void
+seq_close_plain(struct _citrus_lookup *cl)
+{
+       _unmap_file(&cl->cl_plainr);
+}
+
+static int
+seq_open_plain(struct _citrus_lookup *cl, const char *name)
+{
+       int ret;
+
+       /* open read stream */
+       ret = _map_file(&cl->cl_plainr, name);
+       if (ret)
+               return ret;
+
+       cl->cl_rewind = 1;
+       cl->cl_next = &seq_next_plain;
+       cl->cl_lookup = &seq_lookup_plain;
+       cl->cl_num_entries = &seq_get_num_entries_plain;
+       cl->cl_close = &seq_close_plain;
+
+       return 0;
+}
+
+int
+_citrus_lookup_seq_open(struct _citrus_lookup **rcl, const char *name,
+                       int ignore_case)
+{
+       int ret;
+       struct _citrus_lookup *cl;
+
+       cl = malloc(sizeof(*cl));
+       if (cl == NULL)
+               return errno;
+
+       cl->cl_key = NULL;
+       cl->cl_keylen = 0;
+       cl->cl_ignore_case = ignore_case;
+       ret = seq_open_db(cl, name);
+       if (ret == ENOENT)
+               ret = seq_open_plain(cl, name);
+       if (!ret)
+               *rcl = cl;
+       else
+               free(cl);
+
+       return ret;
+}
+
+void
+_citrus_lookup_seq_rewind(struct _citrus_lookup *cl)
+{
+       cl->cl_rewind = 1;
+       free(cl->cl_key);
+       cl->cl_key = NULL;
+       cl->cl_keylen = 0;
+}
+
+int
+_citrus_lookup_seq_next(struct _citrus_lookup *cl,
+                       struct _region *key, struct _region *data)
+{
+       return (*cl->cl_next)(cl, key, data);
+}
+
+int
+_citrus_lookup_seq_lookup(struct _citrus_lookup *cl, const char *key,
+                         struct _region *data)
+{
+       return (*cl->cl_lookup)(cl, key, data);
+}
+
+int
+_citrus_lookup_get_number_of_entries(struct _citrus_lookup *cl)
+{
+       return (*cl->cl_num_entries)(cl);
+}
+
+void
+_citrus_lookup_seq_close(struct _citrus_lookup *cl)
+{
+       free(cl->cl_key);
+       (*cl->cl_close)(cl);
+       free(cl);
+}
+
+char *
+_citrus_lookup_simple(const char *name, const char *key,
+                     char *linebuf, size_t linebufsize, int ignore_case)
+{
+       int ret;
+       struct _citrus_lookup *cl;
+       struct _region data;
+
+       ret = _citrus_lookup_seq_open(&cl, name, ignore_case);
+       if (ret)
+               return NULL;
+
+       ret = _citrus_lookup_seq_lookup(cl, key, &data);
+       if (ret) {
+               _citrus_lookup_seq_close(cl);
+               return NULL;
+       }
+
+       snprintf(linebuf, linebufsize, "%.*s",
+                (int)_region_size(&data), (const char *)_region_head(&data));
+
+       _citrus_lookup_seq_close(cl);
+
+       return linebuf;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_lookup.h b/lib/nbsd_libc/citrus/citrus_lookup.h
new file mode 100644 (file)
index 0000000..92b721f
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: citrus_lookup.h,v 1.2 2004/07/21 14:16:34 tshiozak Exp $       */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_LOOKUP_H_
+#define _CITRUS_LOOKUP_H_
+
+#define _CITRUS_LOOKUP_CASE_SENSITIVE  0
+#define _CITRUS_LOOKUP_CASE_IGNORE     1
+
+struct _citrus_lookup;
+__BEGIN_DECLS
+char *_citrus_lookup_simple(const char *, const char *, char *, size_t, int);
+int _citrus_lookup_seq_open(struct _citrus_lookup **, const char *, int);
+void _citrus_lookup_seq_rewind(struct _citrus_lookup *);
+int _citrus_lookup_seq_next(struct _citrus_lookup *,
+                           struct _region *, struct _region *);
+int _citrus_lookup_seq_lookup(struct _citrus_lookup *, const char *,
+                             struct _region *);
+int _citrus_lookup_get_number_of_entries(struct _citrus_lookup *);
+void _citrus_lookup_seq_close(struct _citrus_lookup *);
+__END_DECLS
+
+static __inline const char *
+_citrus_lookup_alias(const char *path, const char *key, char *buf, size_t n,
+                    int ignore_case)
+{
+       const char *ret;
+
+       ret = _citrus_lookup_simple(path, key, buf, n, ignore_case);
+       if (ret == NULL)
+               ret = key;
+
+       return ret;
+}
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_lookup_factory.c b/lib/nbsd_libc/citrus/citrus_lookup_factory.c
new file mode 100644 (file)
index 0000000..7d14b51
--- /dev/null
@@ -0,0 +1,127 @@
+/*     $NetBSD: citrus_lookup_factory.c,v 1.4 2003/10/27 00:12:42 lukem Exp $  */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_lookup_factory.c,v 1.4 2003/10/27 00:12:42 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <ctype.h>
+#include <limits.h>
+
+#include "citrus_namespace.h"
+#include "citrus_region.h"
+#include "citrus_bcs.h"
+#include "citrus_db_factory.h"
+#include "citrus_db_hash.h"
+#include "citrus_lookup_factory.h"
+#include "citrus_lookup_file.h"
+
+#define T_COMM '#'
+static int
+convert_line(struct _citrus_db_factory *df, const char *line, size_t len)
+{
+       const char *p;
+       char key[LINE_MAX], data[LINE_MAX];
+
+       /* cut off trailing comment */
+       p = memchr(line, T_COMM, len);
+       if (p)
+               len = p - line;
+
+       /* key */
+       line = _bcs_skip_ws_len(line, &len);
+       if (len == 0)
+               return 0;
+       p = _bcs_skip_nonws_len(line, &len);
+       if (p==line)
+               return 0;
+       snprintf(key, sizeof(key), "%.*s", (int)(p-line), line);
+       _bcs_convert_to_lower(key);
+
+       /* data */
+       line = _bcs_skip_ws_len(p, &len);
+       _bcs_trunc_rws_len(line, &len);
+       snprintf(data, sizeof(data), "%.*s", (int)len, line);
+
+       return _db_factory_addstr_by_s(df, key, data);
+}
+
+static int
+dump_db(struct _citrus_db_factory *df, struct _region *r)
+{
+       size_t size;
+       void *ptr;
+
+       size = _db_factory_calc_size(df);
+       ptr = malloc(size);
+       if (ptr == NULL)
+               return errno;
+       _region_init(r, ptr, size);
+
+       return _db_factory_serialize(df, _CITRUS_LOOKUP_MAGIC, r);
+}
+
+int
+_citrus_lookup_factory_convert(FILE *out, FILE *in)
+{
+       struct _citrus_db_factory *df;
+       struct _region r;
+       char *line;
+       size_t size;
+       int ret;
+
+       ret = _db_factory_create(&df, &_db_hash_std, NULL);
+       if (ret)
+               return ret;
+
+       while ((line = fgetln(in, &size)) != NULL)
+               if ((ret = convert_line(df, line, size))) {
+                       _db_factory_free(df);
+                       return ret;
+               }
+
+       ret = dump_db(df, &r);
+       _db_factory_free(df);
+       if (ret)
+               return ret;
+
+       if (fwrite(_region_head(&r), _region_size(&r), 1, out) != 1)
+               return errno;
+
+       return 0;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_lookup_factory.h b/lib/nbsd_libc/citrus/citrus_lookup_factory.h
new file mode 100644 (file)
index 0000000..d50a1e8
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: citrus_lookup_factory.h,v 1.1 2003/06/25 09:51:35 tshiozak Exp $       */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_LOOKUP_FACTORY_H_
+#define _CITRUS_LOOKUP_FACTORY_H_
+
+__BEGIN_DECLS
+int    _citrus_lookup_factory_convert(FILE *, FILE *);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_lookup_file.h b/lib/nbsd_libc/citrus/citrus_lookup_file.h
new file mode 100644 (file)
index 0000000..0c56b61
--- /dev/null
@@ -0,0 +1,34 @@
+/*     $NetBSD: citrus_lookup_file.h,v 1.1 2003/06/25 09:51:36 tshiozak Exp $  */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_LOOKUP_FILE_H_
+#define _CITRUS_LOOKUP_FILE_H_
+
+#define _CITRUS_LOOKUP_MAGIC   "LOOKUP\0\0"
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_mapper.c b/lib/nbsd_libc/citrus/citrus_mapper.c
new file mode 100644 (file)
index 0000000..cef71ba
--- /dev/null
@@ -0,0 +1,404 @@
+/*     $NetBSD: citrus_mapper.c,v 1.7 2008/07/25 14:05:25 christos Exp $       */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_mapper.c,v 1.7 2008/07/25 14:05:25 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/queue.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_region.h"
+#include "citrus_memstream.h"
+#include "citrus_bcs.h"
+#include "citrus_mmap.h"
+#include "citrus_module.h"
+#include "citrus_hash.h"
+#include "citrus_mapper.h"
+
+#define _CITRUS_MAPPER_DIR     "mapper.dir"
+
+#define CM_HASH_SIZE 101
+#define REFCOUNT_PERSISTENT    -1
+
+#ifdef _REENTRANT
+static rwlock_t lock = RWLOCK_INITIALIZER;
+#endif
+
+struct _citrus_mapper_area {
+       _CITRUS_HASH_HEAD(, _citrus_mapper, CM_HASH_SIZE)       ma_cache;
+       char                                                    *ma_dir;
+};
+
+/*
+ * _citrus_mapper_create_area:
+ *     create mapper area
+ */
+
+int
+_citrus_mapper_create_area(
+       struct _citrus_mapper_area *__restrict *__restrict rma,
+       const char *__restrict area)
+{
+       struct stat st;
+       int ret;
+       char path[PATH_MAX];
+       struct _citrus_mapper_area *ma;
+
+       rwlock_wrlock(&lock);
+
+       if (*rma != NULL) {
+               ret = 0;
+               goto quit;
+       }
+
+       snprintf(path, (size_t)PATH_MAX, "%s/%s", area, _CITRUS_MAPPER_DIR);
+
+       ret = stat(path, &st);
+       if (ret)
+               goto quit;
+
+       ma = malloc(sizeof(*ma));
+       if (ma == NULL) {
+               ret = errno;
+               goto quit;
+       }
+       ma->ma_dir = strdup(area);
+       if (ma->ma_dir == NULL) {
+               ret = errno;
+               free(ma->ma_dir);
+               goto quit;
+       }
+       _CITRUS_HASH_INIT(&ma->ma_cache, CM_HASH_SIZE);
+
+       *rma = ma;
+       ret = 0;
+quit:
+       rwlock_unlock(&lock);
+
+       return ret;
+}
+
+
+/*
+ * lookup_mapper_entry:
+ *     lookup mapper.dir entry in the specified directory.
+ *
+ * line format of iconv.dir file:
+ *     mapper  module  arg
+ * mapper : mapper name.
+ * module : mapper module name.
+ * arg    : argument for the module (generally, description file name)
+ */
+
+static int
+lookup_mapper_entry(const char *dir, const char *mapname,
+                   void *linebuf, size_t linebufsize,
+                   const char **module, const char **variable)
+{
+       struct _region r;
+       struct _memstream ms;
+       int ret;
+       const char *cp, *cq;
+       char *p;
+       size_t len;
+       char path[PATH_MAX];
+
+       /* create mapper.dir path */
+       snprintf(path, (size_t)PATH_MAX, "%s/%s", dir, _CITRUS_MAPPER_DIR);
+
+       /* open read stream */
+       ret = _map_file(&r, path);
+       if (ret)
+               return ret;
+
+       _memstream_bind(&ms, &r);
+
+       /* search the line matching to the map name */
+       cp = _memstream_matchline(&ms, mapname, &len, 0);
+       if (!cp) {
+               ret = ENOENT;
+               goto quit;
+       }
+       if (!len || len>linebufsize-1) {
+               ret = EINVAL;
+               goto quit;
+       }
+
+       p = linebuf;
+       /* get module name */
+       *module = p;
+       cq = _bcs_skip_nonws_len(cp, &len);
+       strlcpy(p, cp, (size_t)(cq-cp+1));
+       p += cq-cp+1;
+
+       /* get variable */
+       *variable = p;
+       cp = _bcs_skip_ws_len(cq, &len);
+       strlcpy(p, cp, len+1);
+
+       ret = 0;
+
+quit:
+       _unmap_file(&r);
+       return ret;
+}
+
+/*
+ * mapper_close:
+ *     simply close a mapper. (without handling hash)
+ */
+static void
+mapper_close(struct _citrus_mapper *cm)
+{
+       if (cm->cm_module) {
+               if (cm->cm_ops) {
+                       if (cm->cm_closure)
+                               (*cm->cm_ops->mo_uninit)(cm);
+                       free(cm->cm_ops);
+               }
+               _citrus_unload_module(cm->cm_module);
+       }
+       free(cm->cm_traits);
+       free(cm);
+}
+
+/*
+ * mapper_open:
+ *     simply open a mapper. (without handling hash)
+ */
+static int
+mapper_open(struct _citrus_mapper_area *__restrict ma,
+           struct _citrus_mapper * __restrict * __restrict rcm,
+           const char * __restrict module,
+           const char * __restrict variable)
+{
+       int ret;
+       struct _citrus_mapper *cm;
+       _citrus_mapper_getops_t getops;
+
+       /* initialize mapper handle */
+       cm = malloc(sizeof(*cm));
+       if (!cm)
+               return errno;
+
+       cm->cm_module = NULL;
+       cm->cm_ops = NULL;
+       cm->cm_closure = NULL;
+       cm->cm_traits = NULL;
+       cm->cm_refcount = 0;
+       cm->cm_key = NULL;
+
+       /* load module */
+       ret = _citrus_load_module(&cm->cm_module, module);
+       if (ret)
+               goto err;
+
+       /* get operators */
+       getops = (_citrus_mapper_getops_t)
+           _citrus_find_getops(cm->cm_module, module, "mapper");
+       if (!getops) {
+               ret = EOPNOTSUPP;
+               goto err;
+       }
+       cm->cm_ops = malloc(sizeof(*cm->cm_ops));
+       if (!cm->cm_ops) {
+               ret = errno;
+               goto err;
+       }
+       ret = (*getops)(cm->cm_ops, sizeof(*cm->cm_ops),
+                       _CITRUS_MAPPER_ABI_VERSION);
+       if (ret)
+               goto err;
+
+       if (!cm->cm_ops->mo_init ||
+           !cm->cm_ops->mo_uninit ||
+           !cm->cm_ops->mo_convert ||
+           !cm->cm_ops->mo_init_state)
+               goto err;
+
+       /* allocate traits structure */
+       cm->cm_traits = malloc(sizeof(*cm->cm_traits));
+       if (cm->cm_traits == NULL) {
+               ret = errno;
+               goto err;
+       }
+       /* initialize the mapper */
+       ret = (*cm->cm_ops->mo_init)(ma, cm, ma->ma_dir,
+                                    (const void *)variable,
+                                    strlen(variable)+1,
+                                    cm->cm_traits, sizeof(*cm->cm_traits));
+       if (ret)
+               goto err;
+
+       *rcm = cm;
+
+       return 0;
+
+err:
+       mapper_close(cm);
+       return ret;
+}
+
+/*
+ * _citrus_mapper_open_direct:
+ *     open a mapper.
+ */
+int
+_citrus_mapper_open_direct(struct _citrus_mapper_area *__restrict ma,
+                          struct _citrus_mapper * __restrict * __restrict rcm,
+                          const char * __restrict module,
+                          const char * __restrict variable)
+{
+       return mapper_open(ma, rcm, module, variable);
+}
+
+/*
+ * hash_func
+ */
+static __inline int
+hash_func(const char *key)
+{
+       return _string_hash_func(key, CM_HASH_SIZE);
+}
+
+/*
+ * match_func
+ */
+static __inline int
+match_func(struct _citrus_mapper *cm, const char *key)
+{
+       return strcmp(cm->cm_key, key);
+}
+
+/*
+ * _citrus_mapper_open:
+ *     open a mapper with looking up "mapper.dir".
+ */
+int
+_citrus_mapper_open(struct _citrus_mapper_area *__restrict ma,
+                   struct _citrus_mapper * __restrict * __restrict rcm,
+                   const char * __restrict mapname)
+{
+       int ret;
+       char linebuf[PATH_MAX];
+       const char *module, *variable = NULL;
+       struct _citrus_mapper *cm;
+       int hashval;
+
+       rwlock_wrlock(&lock);
+
+       /* search in the cache */
+       hashval = hash_func(mapname);
+       _CITRUS_HASH_SEARCH(&ma->ma_cache, cm, cm_entry, match_func, mapname,
+                           hashval);
+       if (cm) {
+               /* found */
+               cm->cm_refcount++;
+               *rcm = cm;
+               ret = 0;
+               goto quit;
+       }
+
+       /* search mapper entry */
+       ret = lookup_mapper_entry(ma->ma_dir, mapname, linebuf,
+           (size_t)PATH_MAX, &module, &variable);
+       if (ret)
+               goto quit;
+
+       /* open mapper */
+       ret = mapper_open(ma, &cm, module, variable);
+       if (ret)
+               goto quit;
+       cm->cm_key = strdup(mapname);
+       if (cm->cm_key == NULL) {
+               ret = errno;
+               rwlock_unlock(&lock);
+               _mapper_close(cm);
+               return ret;
+       }
+
+       /* insert to the cache */
+       cm->cm_refcount = 1;
+       _CITRUS_HASH_INSERT(&ma->ma_cache, cm, cm_entry, hashval);
+
+       *rcm = cm;
+       ret = 0;
+quit:
+       rwlock_unlock(&lock);
+       return ret;
+}
+
+/*
+ * _citrus_mapper_close:
+ *     close the specified mapper.
+ */
+void
+_citrus_mapper_close(struct _citrus_mapper *cm)
+{
+       if (cm) {
+               rwlock_wrlock(&lock);
+               if (cm->cm_refcount == REFCOUNT_PERSISTENT)
+                       goto quit;
+               if (cm->cm_refcount > 0) {
+                       if (--cm->cm_refcount > 0)
+                               goto quit;
+                       _CITRUS_HASH_REMOVE(cm, cm_entry);
+                       free(cm->cm_key);
+               }
+               rwlock_unlock(&lock);
+               mapper_close(cm);
+               return;
+quit:
+               rwlock_unlock(&lock);
+       }
+}
+
+/*
+ * _citrus_mapper_set_persistent:
+ *     set persistent count.
+ */
+void
+_citrus_mapper_set_persistent(struct _citrus_mapper * __restrict cm)
+{
+       rwlock_wrlock(&lock);
+       cm->cm_refcount = REFCOUNT_PERSISTENT;
+       rwlock_unlock(&lock);
+}
diff --git a/lib/nbsd_libc/citrus/citrus_mapper.h b/lib/nbsd_libc/citrus/citrus_mapper.h
new file mode 100644 (file)
index 0000000..2eb1d22
--- /dev/null
@@ -0,0 +1,142 @@
+/*     $NetBSD: citrus_mapper.h,v 1.3 2003/07/12 15:39:19 tshiozak Exp $       */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_MAPPER_H_
+#define _CITRUS_MAPPER_H_
+
+struct _citrus_mapper_area;
+struct _citrus_mapper;
+struct _citrus_mapper_ops;
+struct _citrus_mapper_traits;
+
+__BEGIN_DECLS
+int    _citrus_mapper_create_area(
+               struct _citrus_mapper_area *__restrict *__restrict,
+               const char *__restrict);
+int    _citrus_mapper_open(struct _citrus_mapper_area *__restrict,
+                           struct _citrus_mapper *__restrict *__restrict,
+                           const char *__restrict);
+int    _citrus_mapper_open_direct(
+               struct _citrus_mapper_area *__restrict,
+               struct _citrus_mapper *__restrict *__restrict,
+               const char *__restrict, const char *__restrict);
+void   _citrus_mapper_close(struct _citrus_mapper *);
+void   _citrus_mapper_set_persistent(struct _citrus_mapper * __restrict);
+__END_DECLS
+
+#include "citrus_mapper_local.h"
+
+/* return values of _citrus_mapper_convert */
+#define _CITRUS_MAPPER_CONVERT_SUCCESS         (0)
+#define _CITRUS_MAPPER_CONVERT_NONIDENTICAL    (1)
+#define _CITRUS_MAPPER_CONVERT_SRC_MORE                (2)
+#define _CITRUS_MAPPER_CONVERT_DST_MORE                (3)
+#define _CITRUS_MAPPER_CONVERT_ILSEQ           (4)
+#define _CITRUS_MAPPER_CONVERT_FATAL           (5)
+
+/*
+ * _citrus_mapper_convert:
+ *     convert an index.
+ *     - if the converter supports M:1 converter, the function may return
+ *       _CITRUS_MAPPER_CONVERT_SRC_MORE and the storage pointed by dst
+ *       may be unchanged in this case, although the internal status of
+ *       the mapper is affected.
+ *     - if the converter supports 1:N converter, the function may return
+ *       _CITRUS_MAPPER_CONVERT_DST_MORE. In this case, the contiguous
+ *       call of this function ignores src and changes the storage pointed
+ *       by dst.
+ *     - if the converter supports M:N converter, the function may behave
+ *       the combination of the above.
+ *
+ */
+static __inline int
+_citrus_mapper_convert(struct _citrus_mapper * __restrict cm,
+                      _citrus_index_t * __restrict dst,
+                      _citrus_index_t src,
+                      void * __restrict ps)
+{
+
+       _DIAGASSERT(cm && cm->cm_ops && cm->cm_ops->mo_convert && dst);
+
+       return (*cm->cm_ops->mo_convert)(cm, dst, src, ps);
+}
+
+/*
+ * _citrus_mapper_init_state:
+ *     initialize the state.
+ */
+static __inline void
+_citrus_mapper_init_state(struct _citrus_mapper * __restrict cm,
+                         void * __restrict ps)
+{
+
+       _DIAGASSERT(cm && cm->cm_ops && cm->cm_ops->mo_init_state);
+
+       (*cm->cm_ops->mo_init_state)(cm, ps);
+}
+
+/*
+ * _citrus_mapper_get_state_size:
+ *     get the size of state storage.
+ */
+static __inline size_t
+_citrus_mapper_get_state_size(struct _citrus_mapper * __restrict cm)
+{
+
+       _DIAGASSERT(cm && cm->cm_traits);
+
+       return cm->cm_traits->mt_state_size;
+}
+
+/*
+ * _citrus_mapper_get_src_max:
+ *     get the maximum number of suspended sources.
+ */
+static __inline size_t
+_citrus_mapper_get_src_max(struct _citrus_mapper * __restrict cm)
+{
+
+       _DIAGASSERT(cm && cm->cm_traits);
+
+       return cm->cm_traits->mt_src_max;
+}
+
+/*
+ * _citrus_mapper_get_dst_max:
+ *     get the maximum number of suspended destinations.
+ */
+static __inline size_t
+_citrus_mapper_get_dst_max(struct _citrus_mapper * __restrict cm)
+{
+
+       _DIAGASSERT(cm && cm->cm_traits);
+
+       return cm->cm_traits->mt_dst_max;
+}
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_mapper_local.h b/lib/nbsd_libc/citrus/citrus_mapper_local.h
new file mode 100644 (file)
index 0000000..4861e66
--- /dev/null
@@ -0,0 +1,105 @@
+/*     $NetBSD: citrus_mapper_local.h,v 1.2 2008/02/09 14:56:20 junyoung Exp $ */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_MAPPER_LOCAL_H_
+#define _CITRUS_MAPPER_LOCAL_H_
+
+#define _CITRUS_MAPPER_GETOPS_FUNC_BASE(_n_)                           \
+int _n_(struct _citrus_mapper_ops *, size_t, uint32_t)
+#define _CITRUS_MAPPER_GETOPS_FUNC(_n_)                                        \
+_CITRUS_MAPPER_GETOPS_FUNC_BASE(_citrus_##_n_##_mapper_getops)
+
+#define _CITRUS_MAPPER_DECLS(_m_)                                      \
+static int     _citrus_##_m_##_mapper_init                             \
+       (struct _citrus_mapper_area *__restrict,                        \
+        struct _citrus_mapper * __restrict, const char * __restrict,   \
+        const void * __restrict, size_t,                               \
+        struct _citrus_mapper_traits * __restrict, size_t);            \
+static void    _citrus_##_m_##_mapper_uninit(struct _citrus_mapper *); \
+static int     _citrus_##_m_##_mapper_convert                          \
+       (struct _citrus_mapper * __restrict,                            \
+        _citrus_index_t * __restrict, _citrus_index_t,                 \
+        void * __restrict);                                            \
+static void    _citrus_##_m_##_mapper_init_state                       \
+       (struct _citrus_mapper * __restrict, void * __restrict);
+
+#define _CITRUS_MAPPER_DEF_OPS(_m_)                                    \
+struct _citrus_mapper_ops _citrus_##_m_##_mapper_ops = {               \
+       /* mo_abi_version */    _CITRUS_MAPPER_ABI_VERSION,             \
+       /* mo_init */           &_citrus_##_m_##_mapper_init,           \
+       /* mo_uninit */         &_citrus_##_m_##_mapper_uninit,         \
+       /* mo_convert */        &_citrus_##_m_##_mapper_convert,        \
+       /* mo_init_state */     &_citrus_##_m_##_mapper_init_state      \
+}
+
+typedef _CITRUS_MAPPER_GETOPS_FUNC_BASE((*_citrus_mapper_getops_t));
+typedef        int     (*_citrus_mapper_init_t)(
+       struct _citrus_mapper_area *__restrict,
+       struct _citrus_mapper *__restrict, const char *__restrict,
+       const void *__restrict, size_t,
+       struct _citrus_mapper_traits * __restrict, size_t);
+typedef void   (*_citrus_mapper_uninit_t)(struct _citrus_mapper *);
+typedef int    (*_citrus_mapper_convert_t)(struct _citrus_mapper * __restrict,
+                                           _citrus_index_t * __restrict,
+                                           _citrus_index_t,
+                                           void * __restrict);
+typedef void   (*_citrus_mapper_init_state_t)(
+       struct _citrus_mapper * __restrict, void * __restrict);
+
+/*
+ * ABI version change log
+ *   0x00000001
+ *     initial version
+ */
+#define _CITRUS_MAPPER_ABI_VERSION     0x00000001
+struct _citrus_mapper_ops {
+       uint32_t                        mo_abi_version;
+       /* version 0x00000001 */
+       _citrus_mapper_init_t           mo_init;
+       _citrus_mapper_uninit_t         mo_uninit;
+       _citrus_mapper_convert_t        mo_convert;
+       _citrus_mapper_init_state_t     mo_init_state;
+};
+
+struct _citrus_mapper_traits {
+       /* version 0x00000001 */
+       size_t                          mt_state_size;
+       size_t                          mt_src_max;
+       size_t                          mt_dst_max;
+};
+
+struct _citrus_mapper {
+       struct _citrus_mapper_ops               *cm_ops;
+       void                                    *cm_closure;
+       _citrus_module_t                        cm_module;
+       struct _citrus_mapper_traits            *cm_traits;
+       _CITRUS_HASH_ENTRY(_citrus_mapper)      cm_entry;
+       int                                     cm_refcount;
+       char                                    *cm_key;
+};
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_memstream.c b/lib/nbsd_libc/citrus/citrus_memstream.c
new file mode 100644 (file)
index 0000000..e32a97c
--- /dev/null
@@ -0,0 +1,153 @@
+/*     $NetBSD: citrus_memstream.c,v 1.4 2009/02/03 05:02:12 lukem Exp $       */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_memstream.c,v 1.4 2009/02/03 05:02:12 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "citrus_namespace.h"
+#include "citrus_region.h"
+#include "citrus_memstream.h"
+#include "citrus_bcs.h"
+
+const char *
+_citrus_memory_stream_getln(struct _citrus_memory_stream * __restrict ms,
+                           size_t * __restrict rlen)
+{
+       int i;
+       const uint8_t *h, *p;
+       size_t ret;
+
+       if (ms->ms_pos>=_region_size(&ms->ms_region))
+               return (NULL);
+
+       h = p = (uint8_t *)_region_offset(&ms->ms_region, ms->ms_pos);
+       ret = 0;
+       for (i = _region_size(&ms->ms_region) - ms->ms_pos; i > 0; i--) {
+               ret++;
+               if (_bcs_iseol(*p))
+                       break;
+               p++;
+       }
+
+       ms->ms_pos += ret;
+       *rlen = ret;
+       return ((const char *)h);
+}
+
+#define T_COMM '#'
+
+const char *
+_citrus_memory_stream_matchline(struct _citrus_memory_stream * __restrict ms,
+                               const char * __restrict key,
+                               size_t * __restrict rlen,
+                               int iscasesensitive)
+{
+       const char *p, *q;
+       size_t len, keylen;
+
+       keylen = strlen(key);
+       while (/*CONSTCOND*/ 1) {
+               p = _citrus_memory_stream_getln(ms, &len);
+               if (p == NULL)
+                       return (NULL);
+
+               /* ignore comment */
+               q = memchr(p, T_COMM, len);
+               if (q) {
+                       len = q-p;
+               }
+               /* ignore trailing white space and newline */
+               _bcs_trunc_rws_len(p, &len);
+               if (len == 0)
+                       continue; /* ignore null line */
+
+               /* skip white spaces at the head of the line */
+               p = _bcs_skip_ws_len(p, &len);
+               q = _bcs_skip_nonws_len(p, &len);
+
+               if ((size_t)(q-p) == keylen) {
+                       if (iscasesensitive) {
+                               if (memcmp(key, p, keylen) == 0)
+                                       break; /* match */
+                       } else {
+                               if (_bcs_strncasecmp(key, p, keylen) == 0)
+                                       break; /* match */
+                       }
+               }
+       }
+
+       p = _bcs_skip_ws_len(q, &len);
+       *rlen = len;
+
+       return (p);
+}
+
+void *
+_citrus_memory_stream_chr(struct _citrus_memory_stream *ms,
+                         struct _citrus_region *r, char ch)
+{
+       void *head, *chr;
+       size_t sz;
+
+       if (ms->ms_pos >= _region_size(&ms->ms_region))
+               return NULL;
+
+       head = _region_offset(&ms->ms_region, ms->ms_pos);
+       chr = memchr(head, ch, _memstream_remainder(ms));
+       if (chr == NULL) {
+               _region_init(r, head, _memstream_remainder(ms));
+               ms->ms_pos = _region_size(&ms->ms_region);
+               return NULL;
+       }
+       sz = (char *)chr - (char *)head;
+
+       _region_init(r, head, sz);
+       ms->ms_pos += sz+1;
+
+       return chr;
+}
+
+void
+_citrus_memory_stream_skip_ws(struct _citrus_memory_stream *ms)
+{
+       int ch;
+
+       while ((ch = _memstream_peek(ms)) != EOF) {
+               if (!_bcs_isspace(ch))
+                       break;
+               _memstream_getc(ms);
+       }
+}
diff --git a/lib/nbsd_libc/citrus/citrus_memstream.h b/lib/nbsd_libc/citrus/citrus_memstream.h
new file mode 100644 (file)
index 0000000..baeb14b
--- /dev/null
@@ -0,0 +1,213 @@
+/*     $NetBSD: citrus_memstream.h,v 1.3 2005/05/14 17:55:42 tshiozak Exp $    */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ *
+ */
+
+#ifndef _CITRUS_MEMSTREAM_H_
+#define _CITRUS_MEMSTREAM_H_
+
+struct _citrus_memory_stream {
+       struct _citrus_region   ms_region;
+       size_t                  ms_pos;
+};
+
+__BEGIN_DECLS
+const char *   _citrus_memory_stream_getln(
+       struct _citrus_memory_stream * __restrict, size_t * __restrict);
+const char *   _citrus_memory_stream_matchline(
+       struct _citrus_memory_stream * __restrict, const char * __restrict,
+       size_t * __restrict, int);
+void *         _citrus_memory_stream_chr(struct _citrus_memory_stream *,
+                                         struct _citrus_region *, char);
+void           _citrus_memory_stream_skip_ws(struct _citrus_memory_stream *);
+__END_DECLS
+
+static __inline int
+_citrus_memory_stream_iseof(struct _citrus_memory_stream *ms)
+{
+       return ms->ms_pos >= _citrus_region_size(&ms->ms_region);
+}
+
+static __inline void
+_citrus_memory_stream_bind(struct _citrus_memory_stream * __restrict ms,
+                          const struct _citrus_region * __restrict r)
+{
+       ms->ms_region = *r;
+       ms->ms_pos = 0;
+}
+
+static __inline void
+_citrus_memory_stream_bind_ptr(struct _citrus_memory_stream * __restrict ms,
+                              void *ptr, size_t sz)
+{
+       struct _citrus_region r;
+
+       _citrus_region_init(&r, ptr, sz);
+       _citrus_memory_stream_bind(ms, &r);
+}
+
+static __inline void
+_citrus_memory_stream_rewind(struct _citrus_memory_stream *ms)
+{
+       ms->ms_pos = 0;
+}
+
+static __inline size_t
+_citrus_memory_stream_tell(struct _citrus_memory_stream *ms)
+{
+       return ms->ms_pos;
+}
+
+static __inline size_t
+_citrus_memory_stream_remainder(struct _citrus_memory_stream *ms)
+{
+       size_t sz;
+       sz = _citrus_region_size(&ms->ms_region);
+       if (ms->ms_pos>sz)
+               return 0;
+       return sz-ms->ms_pos;
+}
+
+static __inline int
+_citrus_memory_stream_seek(struct _citrus_memory_stream *ms, size_t pos, int w)
+{
+       size_t sz = _citrus_region_size(&ms->ms_region);
+       switch (w) {
+       case SEEK_SET:
+               if (pos>=sz)
+                       return -1;
+               ms->ms_pos = pos;
+               break;
+       case SEEK_CUR:
+               pos += (ssize_t)ms->ms_pos;
+               if (pos>=sz)
+                       return -1;
+               ms->ms_pos = pos;
+               break;
+       case SEEK_END:
+               if (sz<pos)
+                       return -1;
+               ms->ms_pos = sz - pos;
+               break;
+       }
+       return 0;
+}
+
+static __inline int
+_citrus_memory_stream_getc(struct _citrus_memory_stream *ms)
+{
+       if (_citrus_memory_stream_iseof(ms))
+               return (EOF);
+       return _citrus_region_peek8(&ms->ms_region, ms->ms_pos++);
+}
+
+static __inline void
+_citrus_memory_stream_ungetc(struct _citrus_memory_stream *ms, int ch)
+{
+       if (ch != EOF && ms->ms_pos > 0)
+               ms->ms_pos--;
+}
+
+static __inline int
+_citrus_memory_stream_peek(struct _citrus_memory_stream *ms)
+{
+       if (_citrus_memory_stream_iseof(ms))
+               return (EOF);
+       return _citrus_region_peek8(&ms->ms_region, ms->ms_pos);
+}
+
+static __inline void *
+_citrus_memory_stream_getregion(struct _citrus_memory_stream *ms,
+                               struct _citrus_region *r, size_t sz)
+{
+       void *ret;
+
+       if (ms->ms_pos + sz > _citrus_region_size(&ms->ms_region))
+               return NULL;
+
+       ret = _citrus_region_offset(&ms->ms_region, ms->ms_pos);
+       ms->ms_pos += sz;
+       if (r)
+               _citrus_region_init(r, ret, sz);
+
+       return ret;
+}
+
+static __inline int
+_citrus_memory_stream_get8(struct _citrus_memory_stream *ms, uint8_t *rval)
+{
+
+       if (ms->ms_pos + 1 > _citrus_region_size(&ms->ms_region))
+               return -1;
+
+       *rval = _citrus_region_peek8(&ms->ms_region, ms->ms_pos);
+       ms->ms_pos += 2;
+
+       return 0;
+}
+
+static __inline int
+_citrus_memory_stream_get16(struct _citrus_memory_stream *ms, uint16_t *rval)
+{
+
+       if (ms->ms_pos + 2 > _citrus_region_size(&ms->ms_region))
+               return -1;
+
+       *rval = _citrus_region_peek16(&ms->ms_region, ms->ms_pos);
+       ms->ms_pos += 2;
+
+       return 0;
+}
+
+static __inline int
+_citrus_memory_stream_get32(struct _citrus_memory_stream *ms, uint32_t *rval)
+{
+
+       if (ms->ms_pos + 4 > _citrus_region_size(&ms->ms_region))
+               return -1;
+
+       *rval = _citrus_region_peek32(&ms->ms_region, ms->ms_pos);
+       ms->ms_pos += 4;
+
+       return 0;
+}
+
+static __inline int
+_citrus_memory_stream_getln_region(struct _citrus_memory_stream *ms,
+                                  struct _citrus_region *r)
+{
+       const char *ptr;
+       size_t sz;
+
+       ptr = _citrus_memory_stream_getln(ms, &sz);
+       if (ptr)
+               _citrus_region_init(r, __UNCONST(ptr), sz);
+
+       return ptr == NULL;
+}
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_mmap.c b/lib/nbsd_libc/citrus/citrus_mmap.c
new file mode 100644 (file)
index 0000000..7bbc518
--- /dev/null
@@ -0,0 +1,100 @@
+/*     $NetBSD: citrus_mmap.c,v 1.3 2005/01/19 00:52:37 mycroft Exp $  */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_mmap.c,v 1.3 2005/01/19 00:52:37 mycroft Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <sys/mman.h>
+
+#include "citrus_namespace.h"
+#include "citrus_region.h"
+#include "citrus_mmap.h"
+
+int
+_citrus_map_file(struct _citrus_region * __restrict r,
+    const char * __restrict path)
+{
+       int fd, ret = 0;
+       struct stat st;
+       void *head;
+
+       _DIAGASSERT(r != NULL);
+
+       _region_init(r, NULL, 0);
+
+       if ((fd = open(path, O_RDONLY)) == -1)
+               return errno;
+       if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
+               ret = errno;
+               goto error;
+       }
+
+       if (fstat(fd, &st)  == -1) {
+               ret = errno;
+               goto error;
+       }
+       if (!S_ISREG(st.st_mode)) {
+               ret = EOPNOTSUPP;
+               goto error;
+       }
+
+       head = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_FILE|MAP_PRIVATE,
+           fd, (off_t)0);
+       if (head == MAP_FAILED) {
+               ret = errno;
+               goto error;
+       }
+       _region_init(r, head, (size_t)st.st_size);
+
+error:
+       (void)close(fd);
+       return ret;
+}
+
+void
+_citrus_unmap_file(struct _citrus_region *r)
+{
+
+       _DIAGASSERT(r != NULL);
+
+       if (_region_head(r) != NULL) {
+               (void)munmap(_region_head(r), _region_size(r));
+               _region_init(r, NULL, 0);
+       }
+}
diff --git a/lib/nbsd_libc/citrus/citrus_mmap.h b/lib/nbsd_libc/citrus/citrus_mmap.h
new file mode 100644 (file)
index 0000000..1a968a4
--- /dev/null
@@ -0,0 +1,39 @@
+/*     $NetBSD: citrus_mmap.h,v 1.1 2003/06/25 09:51:38 tshiozak Exp $ */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ *
+ */
+
+#ifndef _CITRUS_MMAP_H_
+#define _CITRUS_MMAP_H_
+
+__BEGIN_DECLS
+int _citrus_map_file(struct _citrus_region * __restrict,
+                    const char * __restrict);
+void _citrus_unmap_file(struct _citrus_region *);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_module.c b/lib/nbsd_libc/citrus/citrus_module.c
new file mode 100644 (file)
index 0000000..e0f542c
--- /dev/null
@@ -0,0 +1,357 @@
+/*     $NetBSD: citrus_module.c,v 1.9 2009/01/11 02:46:24 christos Exp $       */
+
+/*-
+ * Copyright (c)1999, 2000, 2001, 2002 Citrus Project,
+ * 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.
+ */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Paul Kranenburg.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Borman at Krystal Technologies.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_module.c,v 1.9 2009/01/11 02:46:24 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <stddef.h>
+#include <paths.h>
+#include "citrus_namespace.h"
+#include "citrus_bcs.h"
+#include "citrus_module.h"
+
+#include <sys/types.h>
+#include <dirent.h>
+#include <dlfcn.h>
+
+#ifdef _I18N_DYNAMIC
+
+static int _getdewey(int [], char *);
+static int _cmpndewey(int [], int, int [], int);
+static const char *_findshlib(char *, int *, int *);
+
+static const char *_pathI18nModule = NULL;
+
+/* from libexec/ld.aout_so/shlib.c */
+#undef major
+#undef minor
+#define MAXDEWEY       3       /*ELF*/
+
+static int
+_getdewey(int dewey[], char *cp)
+{
+       int     i, n;
+
+       _DIAGASSERT(dewey != NULL);
+       _DIAGASSERT(cp != NULL);
+
+       for (n = 0, i = 0; i < MAXDEWEY; i++) {
+               if (*cp == '\0')
+                       break;
+
+               if (*cp == '.') cp++;
+               if (*cp < '0' || '9' < *cp)
+                       return 0;
+
+               dewey[n++] = (int)_bcs_strtol(cp, &cp, 10);
+       }
+
+       return n;
+}
+
+/*
+ * Compare two dewey arrays.
+ * Return -1 if `d1' represents a smaller value than `d2'.
+ * Return  1 if `d1' represents a greater value than `d2'.
+ * Return  0 if equal.
+ */
+static int
+_cmpndewey(int d1[], int n1, int d2[], int n2)
+{
+       register int    i;
+
+       _DIAGASSERT(d1 != NULL);
+       _DIAGASSERT(d2 != NULL);
+
+       for (i = 0; i < n1 && i < n2; i++) {
+               if (d1[i] < d2[i])
+                       return -1;
+               if (d1[i] > d2[i])
+                       return 1;
+       }
+
+       if (n1 == n2)
+               return 0;
+
+       if (i == n1)
+               return -1;
+
+       if (i == n2)
+               return 1;
+
+       /* XXX cannot happen */
+       return 0;
+}
+
+static const char *
+_findshlib(char *name, int *majorp, int *minorp)
+{
+       int             dewey[MAXDEWEY];
+       int             ndewey;
+       int             tmp[MAXDEWEY];
+       int             i;
+       int             len;
+       char            *lname;
+       static char     path[PATH_MAX];
+       int             major, minor;
+       const char      *search_dirs[1];
+       const int       n_search_dirs = 1;
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(majorp != NULL);
+       _DIAGASSERT(minorp != NULL);
+
+       major = *majorp;
+       minor = *minorp;
+       path[0] = '\0';
+       search_dirs[0] = _pathI18nModule;
+       len = strlen(name);
+       lname = name;
+
+       ndewey = 0;
+
+       for (i = 0; i < n_search_dirs; i++) {
+               DIR             *dd = opendir(search_dirs[i]);
+               struct dirent   *dp;
+               int             found_dot_a = 0;
+               int             found_dot_so = 0;
+
+               if (dd == NULL)
+                       continue;
+
+               while ((dp = readdir(dd)) != NULL) {
+                       int     n;
+
+                       if (dp->d_namlen < len + 4)
+                               continue;
+                       if (strncmp(dp->d_name, lname, (size_t)len) != 0)
+                               continue;
+                       if (strncmp(dp->d_name+len, ".so.", 4) != 0)
+                               continue;
+
+                       if ((n = _getdewey(tmp, dp->d_name+len+4)) == 0)
+                               continue;
+
+                       if (major != -1 && found_dot_a)
+                               found_dot_a = 0;
+
+                       /* XXX should verify the library is a.out/ELF? */
+
+                       if (major == -1 && minor == -1) {
+                               goto compare_version;
+                       } else if (major != -1 && minor == -1) {
+                               if (tmp[0] == major)
+                                       goto compare_version;
+                       } else if (major != -1 && minor != -1) {
+                               if (tmp[0] == major) {
+                                       if (n == 1 || tmp[1] >= minor)
+                                               goto compare_version;
+                               }
+                       }
+
+                       /* else, this file does not qualify */
+                       continue;
+
+               compare_version:
+                       if (_cmpndewey(tmp, n, dewey, ndewey) <= 0)
+                               continue;
+
+                       /* We have a better version */
+                       found_dot_so = 1;
+                       snprintf(path, sizeof(path), "%s/%s", search_dirs[i],
+                           dp->d_name);
+                       found_dot_a = 0;
+                       bcopy(tmp, dewey, sizeof(dewey));
+                       ndewey = n;
+                       *majorp = dewey[0];
+                       *minorp = dewey[1];
+               }
+               closedir(dd);
+
+               if (found_dot_a || found_dot_so)
+                       /*
+                        * There's a lib in this dir; take it.
+                        */
+                       return path[0] ? path : NULL;
+       }
+
+       return path[0] ? path : NULL;
+}
+
+void *
+_citrus_find_getops(_citrus_module_t handle, const char *modname,
+                   const char *ifname)
+{
+       char name[PATH_MAX];
+       void *p;
+
+       _DIAGASSERT(handle != NULL);
+       _DIAGASSERT(modname != NULL);
+       _DIAGASSERT(ifname != NULL);
+
+       snprintf(name, sizeof(name), _C_LABEL_STRING("_citrus_%s_%s_getops"),
+           modname, ifname);
+       p = dlsym((void *)handle, name);
+       return p;
+}
+
+int
+_citrus_load_module(_citrus_module_t *rhandle, const char *encname)
+{
+       const char *p;
+       char path[PATH_MAX];
+       int maj, min;
+       void *handle;
+
+       _DIAGASSERT(rhandle != NULL);
+
+       if (_pathI18nModule == NULL) {
+               p = getenv("PATH_I18NMODULE");
+               if (p != NULL && !issetugid()) {
+                       _pathI18nModule = strdup(p);
+                       if (_pathI18nModule == NULL)
+                               return ENOMEM;
+               } else
+                       _pathI18nModule = _PATH_I18NMODULE;
+       }
+
+       (void)snprintf(path, sizeof(path), "lib%s", encname);
+       maj = I18NMODULE_MAJOR;
+       min = -1;
+       p = _findshlib(path, &maj, &min);
+       if (!p)
+               return (EINVAL);
+       handle = dlopen(p, RTLD_LAZY);
+       if (!handle)
+               return (EINVAL);
+
+       *rhandle = (_citrus_module_t)handle;
+
+       return (0);
+}
+
+void
+_citrus_unload_module(_citrus_module_t handle)
+{
+       if (handle)
+               dlclose((void *)handle);
+}
+#else
+/* !_I18N_DYNAMIC */
+
+void *
+/*ARGSUSED*/
+_citrus_find_getops(_citrus_module_t handle, const char *modname,
+                   const char *ifname)
+{
+       return (NULL);
+}
+
+int
+/*ARGSUSED*/
+_citrus_load_module(_citrus_module_t *rhandle, char const *modname)
+{
+       return (EINVAL);
+}
+
+void
+/*ARGSUSED*/
+_citrus_unload_module(_citrus_module_t handle)
+{
+}
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_module.h b/lib/nbsd_libc/citrus/citrus_module.h
new file mode 100644 (file)
index 0000000..d7e68b8
--- /dev/null
@@ -0,0 +1,43 @@
+/*     $NetBSD: citrus_module.h,v 1.1 2002/03/17 22:14:20 tshiozak Exp $       */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ *
+ */
+
+#ifndef _CITRUS_MODULE_H_
+#define _CITRUS_MODULE_H_
+
+typedef struct _citrus_module_rec *_citrus_module_t;
+
+__BEGIN_DECLS
+void *_citrus_find_getops(_citrus_module_t __restrict,
+                         const char * __restrict, const char * __restrict);
+int _citrus_load_module(_citrus_module_t * __restrict,
+                       const char * __restrict);
+void _citrus_unload_module(_citrus_module_t);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_namespace.h b/lib/nbsd_libc/citrus/citrus_namespace.h
new file mode 100644 (file)
index 0000000..bb0937d
--- /dev/null
@@ -0,0 +1,238 @@
+/*     $NetBSD: citrus_namespace.h,v 1.8 2009/01/11 02:46:24 christos Exp $    */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_NAMESPACE_H_
+#define _CITRUS_NAMESPACE_H_
+
+/* citrus_alias */
+#ifndef _CITRUS_ALIAS_NO_NAMESPACE
+#define _alias_lookup          _citrus_alias_lookup
+#endif /* _CITRUS_ALIAS_NO_NAMESPACE */
+
+/* citrus_bcs */
+#ifndef _CITRUS_BCS_NO_NAMESPACE
+#define _bcs_isalnum           _citrus_bcs_isalnum
+#define _bcs_isalpha           _citrus_bcs_isalpha
+#define _bcs_isblank           _citrus_bcs_isblank
+#define _bcs_isdigit           _citrus_bcs_isdigit
+#define _bcs_islower           _citrus_bcs_islower
+#define _bcs_iseol             _citrus_bcs_iseol
+#define _bcs_isspace           _citrus_bcs_isspace
+#define _bcs_isupper           _citrus_bcs_isupper
+#define _bcs_isxdigit          _citrus_bcs_isxdigit
+#define _bcs_skip_nonws                _citrus_bcs_skip_nonws
+#define _bcs_skip_nonws_len    _citrus_bcs_skip_nonws_len
+#define _bcs_skip_ws           _citrus_bcs_skip_ws
+#define _bcs_skip_ws_len       _citrus_bcs_skip_ws_len
+#define _bcs_strcasecmp                _citrus_bcs_strcasecmp
+#define _bcs_strncasecmp       _citrus_bcs_strncasecmp
+#define _bcs_tolower           _citrus_bcs_tolower
+#define _bcs_toupper           _citrus_bcs_toupper
+#define _bcs_trunc_rws_len     _citrus_bcs_trunc_rws_len
+#define _bcs_convert_to_lower  _citrus_bcs_convert_to_lower
+#define _bcs_convert_to_upper  _citrus_bcs_convert_to_upper
+#define _bcs_strtol            _citrus_bcs_strtol
+#define _bcs_strtoul           _citrus_bcs_strtoul
+#endif /* _CITRUS_BCS_NO_NAMESPACE */
+
+/* citrus_csmapper */
+#ifndef _CITRUS_CSMAPPER_NO_NAMESPACE
+#define _csmapper              _citrus_csmapper
+#define _csmapper_open         _citrus_csmapper_open
+#define _csmapper_close                _citrus_csmapper_close
+#define _csmapper_convert      _citrus_csmapper_convert
+#define _csmapper_init_state   _citrus_csmapper_init_state
+#define _csmapper_get_state_size _citrus_csmapper_get_state_size
+#define _csmapper_get_src_max  _citrus_csmapper_get_src_max
+#define _csmapper_get_dst_max  _citrus_csmapper_get_dst_max
+#define _CSMAPPER_F_PREVENT_PIVOT _CITRUS_CSMAPPER_F_PREVENT_PIVOT
+#endif /* _CITRUS_CSMAPPER_NO_NAMESPACE */
+
+/* citrus_db */
+#ifndef _CITRUS_DB_NO_NAMESPACE
+#define _db_open               _citrus_db_open
+#define _db_close              _citrus_db_close
+#define _db_lookup             _citrus_db_lookup
+#define _db_lookup_by_s                _citrus_db_lookup_by_string
+#define _db_lookup8_by_s       _citrus_db_lookup8_by_string
+#define _db_lookup16_by_s      _citrus_db_lookup16_by_string
+#define _db_lookup32_by_s      _citrus_db_lookup32_by_string
+#define _db_lookupstr_by_s     _citrus_db_lookup_string_by_string
+#define _db_hash_std           _citrus_db_hash_std
+#define _db_get_num_entries    _citrus_db_get_number_of_entries
+#define _db_get_entry          _citrus_db_get_entry
+#define _db_locator            _citrus_db_locator
+#define _db_locator_init       _citrus_db_locator_init
+#endif /* _CITRUS_DB_NO_NAMESPACE */
+
+/* citrus_db_factory */
+#ifndef _CITRUS_DB_FACTORY_NO_NAMESPACE
+#define _db_factory            _citrus_db_factory
+#define _db_factory_create     _citrus_db_factory_create
+#define _db_factory_free       _citrus_db_factory_free
+#define _db_factory_add                _citrus_db_factory_add
+#define _db_factory_add_by_s   _citrus_db_factory_add_by_string
+#define _db_factory_add8_by_s  _citrus_db_factory_add8_by_string
+#define _db_factory_add16_by_s _citrus_db_factory_add16_by_string
+#define _db_factory_add32_by_s _citrus_db_factory_add32_by_string
+#define _db_factory_addstr_by_s        _citrus_db_factory_add_string_by_string
+#define _db_factory_calc_size  _citrus_db_factory_calc_size
+#define _db_factory_serialize  _citrus_db_factory_serialize
+#endif /* _CITRUS_DB_FACTORY_NO_NAMESPACE */
+
+/* citrus_lookup */
+#ifndef _CITRUS_DB_NO_NAMESPACE
+#define _LOOKUP_CASE_SENSITIVE _CITRUS_LOOKUP_CASE_SENSITIVE
+#define _LOOKUP_CASE_IGNORE    _CITRUS_LOOKUP_CASE_IGNORE
+#define _lookup                        _citrus_lookup
+#define _lookup_simple         _citrus_lookup_simple
+#define _lookup_alias          _citrus_lookup_alias
+#define _lookup_seq_open       _citrus_lookup_seq_open
+#define _lookup_seq_rewind     _citrus_lookup_seq_rewind
+#define _lookup_seq_next       _citrus_lookup_seq_next
+#define _lookup_seq_lookup     _citrus_lookup_seq_lookup
+#define _lookup_get_num_entries        _citrus_lookup_get_number_of_entries
+#define _lookup_seq_close      _citrus_lookup_seq_close
+#define _lookup_factory_convert        _citrus_lookup_factory_convert
+#endif /* _CITRUS_DB_NO_NAMESPACE */
+
+/* citrus_esdb */
+#ifndef _CITRUS_ESDB_NO_NAMESPACE
+#define _esdb                  _citrus_esdb
+#define _esdb_charset          _citrus_esdb_charset
+#define _esdb_open             _citrus_esdb_open
+#define _esdb_close            _citrus_esdb_close
+#define _esdb_get_list         _citrus_esdb_get_list
+#define _esdb_free_list                _citrus_esdb_free_list
+#endif /* _CITRUS_ESDB_NO_NAMESPACE */
+
+/* citrus_hash */
+#ifndef _CITRUS_HASH_NO_NAMESPACE
+#define _citrus_string_hash_func _string_hash_func
+#endif /* _CITRUS_HASH_NO_NAMESPACE */
+
+/* citrus_mapper */
+#ifndef _CITRUS_MAPPER_NO_NAMESPACE
+#define _mapper                        _citrus_mapper
+#define _mapper_ops            _citrus_mapper_ops
+#define _mapper_traits         _citrus_mapper_traits
+#define _mapper_open           _citrus_mapper_open
+#define _mapper_open_direct    _citrus_mapper_open_direct
+#define _mapper_close          _citrus_mapper_close
+#define _MAPPER_CONVERT_SUCCESS        _CITRUS_MAPPER_CONVERT_SUCCESS
+#define _MAPPER_CONVERT_NONIDENTICAL _CITRUS_MAPPER_CONVERT_NONIDENTICAL
+#define _MAPPER_CONVERT_SRC_MORE _CITRUS_MAPPER_CONVERT_SRC_MORE
+#define _MAPPER_CONVERT_DST_MORE _CITRUS_MAPPER_CONVERT_DST_MORE
+#define _MAPPER_CONVERT_ILSEQ  _CITRUS_MAPPER_CONVERT_ILSEQ
+#define _MAPPER_CONVERT_FATAL  _CITRUS_MAPPER_CONVERT_FATAL
+#define _mapper_convert                _citrus_mapper_convert
+#define _mapper_init_state     _citrus_mapper_init_state
+#define _mapper_get_state_size _citrus_mapper_get_state_size
+#define _mapper_get_src_max    _citrus_mapper_get_src_max
+#define _mapper_get_dst_max    _citrus_mapper_get_dst_max
+#define _mapper_set_persistent _citrus_mapper_set_persistent
+#endif /* _CITRUS_MAPPER_NO_NAMESPACE */
+
+/* citrus_memstream */
+#ifndef _CITRUS_MEMSTREAM_NO_NAMESPACE
+#define _memstream             _citrus_memory_stream
+#define _memstream_getln       _citrus_memory_stream_getln
+#define _memstream_matchline   _citrus_memory_stream_matchline
+#define _memstream_chr         _citrus_memory_stream_chr
+#define _memstream_skip_ws     _citrus_memory_stream_skip_ws
+#define _memstream_iseof       _citrus_memory_stream_iseof
+#define _memstream_bind                _citrus_memory_stream_bind
+#define _memstream_bind_ptr    _citrus_memory_stream_bind_ptr
+#define _memstream_seek                _citrus_memory_stream_seek
+#define _memstream_rewind      _citrus_memory_stream_rewind
+#define _memstream_tell                _citrus_memory_stream_tell
+#define _memstream_remainder   _citrus_memory_stream_remainder
+#define _memstream_getc                _citrus_memory_stream_getc
+#define _memstream_ungetc      _citrus_memory_stream_ungetc
+#define _memstream_peek                _citrus_memory_stream_peek
+#define _memstream_getregion   _citrus_memory_stream_getregion
+#define _memstream_getln_region        _citrus_memory_stream_getln_region
+#endif /* _CITRUS_MEMSTREAM_NO_NAMESPACE */
+
+/* citrus_mmap */
+#ifndef _CITRUS_MMAP_NO_NAMESPACE
+#define _map_file              _citrus_map_file
+#define _unmap_file            _citrus_unmap_file
+#endif /* _CITRUS_MMAP_NO_NAMESPACE */
+
+#ifndef _CITRUS_PIVOT_NO_NAMESPACE
+#define _pivot_factory_convert _citrus_pivot_factory_convert
+#endif /* _CITRUS_PIVOT_NO_NAMESPACE */
+
+/* citrus_region.h */
+#ifndef _CITRUS_REGION_NO_NAMESPACE
+#define _region                        _citrus_region
+#define _region_init           _citrus_region_init
+#define _region_head           _citrus_region_head
+#define _region_size           _citrus_region_size
+#define _region_check          _citrus_region_check
+#define _region_offset         _citrus_region_offset
+#define _region_peek8          _citrus_region_peek8
+#define _region_peek16         _citrus_region_peek16
+#define _region_peek32         _citrus_region_peek32
+#define _region_get_subregion  _citrus_region_get_subregion
+#endif /* _CITRUS_REGION_NO_NAMESPACE */
+
+/* citrus_stdenc.h */
+#ifndef _CITRUS_STDENC_NO_NAMESPACE
+#define _stdenc                        _citrus_stdenc
+#define _stdenc_ops            _citrus_stdenc_ops
+#define _stdenc_traits         _citrus_stdenc_traits
+#define _stdenc_state_desc     _citrus_stdenc_state_desc
+#define _stdenc_open           _citrus_stdenc_open
+#define _stdenc_close          _citrus_stdenc_close
+#define _stdenc_init_state     _citrus_stdenc_init_state
+#define _stdenc_mbtocs         _citrus_stdenc_mbtocs
+#define _stdenc_cstomb         _citrus_stdenc_cstomb
+#define _stdenc_mbtowc         _citrus_stdenc_mbtowc
+#define _stdenc_wctomb         _citrus_stdenc_wctomb
+#define _stdenc_put_state_reset        _citrus_stdenc_put_state_reset
+#define _stdenc_get_state_size _citrus_stdenc_get_state_size
+#define _stdenc_get_mb_cur_max _citrus_stdenc_get_mb_cur_max
+#define _stdenc_get_state_desc _citrus_stdenc_get_state_desc
+#define _STDENC_SDID_GENERIC   _CITRUS_STDENC_SDID_GENERIC
+#define _STDENC_SDGEN_UNKNOWN  _CITRUS_STDENC_SDGEN_UNKNOWN
+#define _STDENC_SDGEN_INITIAL  _CITRUS_STDENC_SDGEN_INITIAL
+#define _STDENC_SDGEN_STABLE   _CITRUS_STDENC_SDGEN_STABLE
+#define _STDENC_SDGEN_INCOMPLETE_CHAR _CITRUS_STDENC_SDGEN_INCOMPLETE_CHAR
+#define _STDENC_SDGEN_INCOMPLETE_SHIFT _CITRUS_STDENC_SDGEN_INCOMPLETE_SHIFT
+#endif /* _CITRUS_STDENC_NO_NAMESPACE */
+
+/* citrus_types.h */
+#ifndef _CITRUS_TYPES_NO_NAMESPACE
+#define _index_t               _citrus_index_t
+#define _csid_t                        _citrus_csid_t
+#define _wc_t                  _citrus_wc_t
+#endif /* _CITRUS_TYPES_NO_NAMESPACE */
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_none.c b/lib/nbsd_libc/citrus/citrus_none.c
new file mode 100644 (file)
index 0000000..0472197
--- /dev/null
@@ -0,0 +1,503 @@
+/*     $NetBSD: citrus_none.c,v 1.18 2008/06/14 16:01:07 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_none.c,v 1.18 2008/06/14 16:01:07 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <wchar.h>
+#include <sys/types.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_none.h"
+#include "citrus_stdenc.h"
+
+/* ---------------------------------------------------------------------- */
+
+_CITRUS_CTYPE_DECLS(NONE);
+_CITRUS_CTYPE_DEF_OPS(NONE);
+
+
+/* ---------------------------------------------------------------------- */
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_ctype_init(void ** __restrict cl, void * __restrict var,
+                       size_t lenvar, size_t lenps)
+{
+       *cl = NULL;
+       return (0);
+}
+
+static void
+/*ARGSUSED*/
+_citrus_NONE_ctype_uninit(void *cl)
+{
+}
+
+static unsigned
+/*ARGSUSED*/
+_citrus_NONE_ctype_get_mb_cur_max(void *cl)
+{
+       return (1);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_ctype_mblen(void * __restrict cl, const char * __restrict s,
+                        size_t n, int * __restrict nresult)
+{
+       if (!s) {
+               *nresult = 0; /* state independent */
+               return (0);
+       }
+       if (n==0) {
+               *nresult = -1;
+               return (EILSEQ);
+       }
+       *nresult = (*s == 0) ? 0 : 1;
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_ctype_mbrlen(void * __restrict cl, const char * __restrict s,
+                         size_t n, void * __restrict pspriv,
+                         size_t * __restrict nresult)
+{
+       if (!s) {
+               *nresult = 0;
+               return (0);
+       }
+       if (n==0) {
+               *nresult = (size_t)-2;
+               return (0);
+       }
+       *nresult = (*s == 0) ? 0 : 1;
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_ctype_mbrtowc(void * __restrict cl, wchar_t * __restrict pwc,
+                          const char * __restrict s, size_t n,
+                          void * __restrict pspriv,
+                          size_t * __restrict nresult)
+{
+       if (s == NULL) {
+               *nresult = 0;
+               return (0);
+       }
+       if (n == 0) {
+               *nresult = (size_t)-2;
+               return (0);
+       }
+
+       if (pwc != NULL)
+               *pwc = (wchar_t)(unsigned char) *s;
+
+       *nresult = *s == '\0' ? 0 : 1;
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_ctype_mbsinit(void * __restrict cl,
+                          const void * __restrict pspriv,
+                          int * __restrict nresult)
+{
+       *nresult = 1;  /* always initial state */
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_ctype_mbsrtowcs(void * __restrict cl, wchar_t * __restrict pwcs,
+                            const char ** __restrict s, size_t n,
+                            void * __restrict pspriv,
+                            size_t * __restrict nresult)
+{
+       int cnt;
+       const char *s0;
+
+       /* if pwcs is NULL, ignore n */
+       if (pwcs == NULL)
+               n = 1; /* arbitrary >0 value */
+
+       cnt = 0;
+       s0 = *s; /* to keep *s unchanged for now, use copy instead. */
+       while (n > 0) {
+               if (pwcs != NULL) {
+                       *pwcs = (wchar_t)(unsigned char)*s0;
+               }
+               if (*s0 == '\0') {
+                       s0 = NULL;
+                       break;
+               }
+               s0++;
+               if (pwcs != NULL) {
+                       pwcs++;
+                       n--;
+               }
+               cnt++;
+       }
+       if (pwcs)
+               *s = s0;
+
+       *nresult = (size_t)cnt;
+
+       return (0);
+}
+
+static int
+_citrus_NONE_ctype_mbstowcs(void * __restrict cl, wchar_t * __restrict wcs,
+                           const char * __restrict s, size_t n,
+                           size_t * __restrict nresult)
+{
+       const char *rs = s;
+
+       return (_citrus_NONE_ctype_mbsrtowcs(cl, wcs, &rs, n, NULL, nresult));
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_ctype_mbtowc(void * __restrict cl, wchar_t * __restrict pwc,
+                         const char * __restrict s, size_t n,
+                         int * __restrict nresult)
+{
+
+       if (s == NULL) {
+               *nresult = 0; /* state independent */
+               return (0);
+       }
+       if (n == 0) {
+               return (EILSEQ);
+       }
+       if (pwc == NULL) {
+               if (*s == '\0') {
+                       *nresult = 0;
+               } else {
+                       *nresult = 1;
+               }
+               return (0);
+       }
+
+       *pwc = (wchar_t)(unsigned char)*s;
+       *nresult = *s == '\0' ? 0 : 1;
+
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_ctype_wcrtomb(void * __restrict cl, char * __restrict s,
+                          wchar_t wc, void * __restrict pspriv,
+                          size_t * __restrict nresult)
+{
+       if ((wc&~0xFFU) != 0) {
+               *nresult = (size_t)-1;
+               return (EILSEQ);
+       }
+
+       *nresult = 1;
+       if (s!=NULL)
+               *s = (char)wc;
+
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_ctype_wcsrtombs(void * __restrict cl, char * __restrict s,
+                            const wchar_t ** __restrict pwcs, size_t n,
+                            void * __restrict pspriv,
+                            size_t * __restrict nresult)
+{
+       size_t count;
+       const wchar_t *pwcs0;
+
+       pwcs0 = *pwcs;
+       count = 0;
+
+       if (s == NULL)
+               n = 1;
+
+       while (n > 0) {
+               if ((*pwcs0 & ~0xFFU) != 0) {
+                       *nresult = (size_t)-1;
+                       return (EILSEQ);
+               }
+               if (s != NULL) {
+                       *s++ = (char)*pwcs0;
+                       n--;
+               }
+               if (*pwcs0 == L'\0') {
+                       pwcs0 = NULL;
+                       break;
+               }
+               count++;
+               pwcs0++;
+       }
+       if (s != NULL)
+               *pwcs = pwcs0;
+
+       *nresult = count;
+
+       return (0);
+}
+
+static int
+_citrus_NONE_ctype_wcstombs(void * __restrict cl, char * __restrict s,
+                           const wchar_t * __restrict pwcs, size_t n,
+                           size_t * __restrict nresult)
+{
+       const wchar_t *rpwcs = pwcs;
+
+       return (_citrus_NONE_ctype_wcsrtombs(cl, s, &rpwcs, n, NULL, nresult));
+}
+
+static int
+_citrus_NONE_ctype_wctomb(void * __restrict cl, char * __restrict s,
+                         wchar_t wc, int * __restrict nresult)
+{
+       int ret;
+       size_t nr;
+
+       if (s == 0) {
+               /*
+                * initialize state here.
+                * (nothing to do for us.)
+                */
+               *nresult = 0; /* we're state independent */
+               return (0);
+       }
+
+       ret = _citrus_NONE_ctype_wcrtomb(cl, s, wc, NULL, &nr);
+       *nresult = (int)nr;
+
+       return (ret);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_ctype_btowc(_citrus_ctype_rec_t * __restrict cc,
+                        int c, wint_t * __restrict wcresult)
+{
+       if (c == EOF || c & ~0xFF)
+               *wcresult = WEOF;
+       else
+               *wcresult = (wint_t)c;
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_ctype_wctob(_citrus_ctype_rec_t * __restrict cc,
+                        wint_t wc, int * __restrict cresult)
+{
+       if (wc == WEOF || wc & ~0xFF)
+               *cresult = EOF;
+       else
+               *cresult = (int)wc;
+       return (0);
+}
+
+/* ---------------------------------------------------------------------- */
+
+_CITRUS_STDENC_DECLS(NONE);
+_CITRUS_STDENC_DEF_OPS(NONE);
+struct _citrus_stdenc_traits _citrus_NONE_stdenc_traits = {
+       0,      /* et_state_size */
+       1,      /* mb_cur_max */
+};
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_stdenc_init(struct _citrus_stdenc * __restrict ce,
+                        const void *var, size_t lenvar,
+                        struct _citrus_stdenc_traits * __restrict et)
+{
+
+       et->et_state_size = 0;
+       et->et_mb_cur_max = 1;
+
+       ce->ce_closure = NULL;
+
+       return (0);
+}
+
+static void
+/*ARGSUSED*/
+_citrus_NONE_stdenc_uninit(struct _citrus_stdenc *ce)
+{
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_stdenc_init_state(struct _citrus_stdenc * __restrict ce,
+                              void * __restrict ps)
+{
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_stdenc_mbtocs(struct _citrus_stdenc * __restrict ce,
+                          _csid_t *csid, _index_t *idx,
+                          const char **s, size_t n,
+                          void *ps, size_t *nresult)
+{
+
+       _DIAGASSERT(csid != NULL && idx != NULL);
+
+       if (n<1) {
+               *nresult = (size_t)-2;
+               return (0);
+       }
+
+       *csid = 0;
+       *idx = (_index_t)(unsigned char)*(*s)++;
+       *nresult = *idx == 0 ? 0 : 1;
+
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_stdenc_cstomb(struct _citrus_stdenc * __restrict ce,
+                          char *s, size_t n,
+                          _csid_t csid, _index_t idx,
+                          void *ps, size_t *nresult)
+{
+
+       if (csid == _CITRUS_CSID_INVALID) {
+               *nresult = 0;
+               return (0);
+       }
+       if (n<1) {
+               *nresult = (size_t)-1;
+               return (E2BIG);
+       }
+       if (csid != 0 || (idx&0xFF) != idx)
+               return (EILSEQ);
+
+       *s = (char)idx;
+       *nresult = 1;
+
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_stdenc_mbtowc(struct _citrus_stdenc * __restrict ce,
+                          _wc_t * __restrict pwc,
+                          const char ** __restrict s, size_t n,
+                          void * __restrict pspriv,
+                          size_t * __restrict nresult)
+{
+       if (s == NULL) {
+               *nresult = 0;
+               return (0);
+       }
+       if (n == 0) {
+               *nresult = (size_t)-2;
+               return (0);
+       }
+
+       if (pwc != NULL)
+               *pwc = (_wc_t)(unsigned char) **s;
+
+       *nresult = *s == '\0' ? 0 : 1;
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_stdenc_wctomb(struct _citrus_stdenc * __restrict ce,
+                          char * __restrict s, size_t n,
+                          _wc_t wc, void * __restrict pspriv,
+                          size_t * __restrict nresult)
+{
+       if ((wc&~0xFFU) != 0) {
+               *nresult = (size_t)-1;
+               return (EILSEQ);
+       }
+       if (n==0) {
+               *nresult = (size_t)-1;
+               return (E2BIG);
+       }
+
+       *nresult = 1;
+       if (s!=NULL && n>0)
+               *s = (char)wc;
+
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_stdenc_put_state_reset(struct _citrus_stdenc * __restrict ce,
+                                   char * __restrict s, size_t n,
+                                   void * __restrict pspriv,
+                                   size_t * __restrict nresult)
+{
+
+       *nresult = 0;
+
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_NONE_stdenc_get_state_desc(struct _stdenc * __restrict ce,
+                                  void * __restrict ps,
+                                  int id,
+                                  struct _stdenc_state_desc * __restrict d)
+{
+       int ret = 0;
+
+       switch (id) {
+       case _STDENC_SDID_GENERIC:
+               d->u.generic.state = _STDENC_SDGEN_INITIAL;
+               break;
+       default:
+               ret = EOPNOTSUPP;
+       }
+
+       return ret;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_none.h b/lib/nbsd_libc/citrus/citrus_none.h
new file mode 100644 (file)
index 0000000..1a75f2c
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: citrus_none.h,v 1.3 2003/06/25 09:51:38 tshiozak Exp $ */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_NONE_H_
+#define _CITRUS_NONE_H_
+
+extern struct _citrus_ctype_ops_rec    _citrus_NONE_ctype_ops;
+extern struct _citrus_stdenc_ops       _citrus_NONE_stdenc_ops;
+extern struct _citrus_stdenc_traits    _citrus_NONE_stdenc_traits;
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_pivot_factory.c b/lib/nbsd_libc/citrus/citrus_pivot_factory.c
new file mode 100644 (file)
index 0000000..54369ca
--- /dev/null
@@ -0,0 +1,231 @@
+/*     $NetBSD: citrus_pivot_factory.c,v 1.7 2009/04/12 14:20:19 lukem Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_pivot_factory.c,v 1.7 2009/04/12 14:20:19 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <ctype.h>
+#include <limits.h>
+#include <sys/queue.h>
+
+#include "citrus_namespace.h"
+#include "citrus_region.h"
+#include "citrus_bcs.h"
+#include "citrus_db_factory.h"
+#include "citrus_db_hash.h"
+#include "citrus_pivot_file.h"
+#include "citrus_pivot_factory.h"
+
+struct src_entry {
+       char *se_name;
+       struct _citrus_db_factory *se_df;
+       SIMPLEQ_ENTRY(src_entry) se_entry;
+};
+SIMPLEQ_HEAD(src_head, src_entry);
+
+static int
+find_src(struct src_head *sh, struct src_entry **rse, const char *name)
+{
+       int ret;
+       struct src_entry *se;
+
+       SIMPLEQ_FOREACH(se, sh, se_entry) {
+               if (_bcs_strcasecmp(se->se_name, name) == 0) {
+                       *rse = se;
+                       return 0;
+               }
+       }
+       se = malloc(sizeof(*se));
+       if (se == NULL)
+               return errno;
+       se->se_name = strdup(name);
+       if (se->se_name == NULL) {
+               ret = errno;
+               free(se);
+               return ret;
+       }
+       ret = _db_factory_create(&se->se_df, &_db_hash_std, NULL);
+       if (ret) {
+               free(se->se_name);
+               free(se);
+               return ret;
+       }
+       SIMPLEQ_INSERT_TAIL(sh, se, se_entry);
+       *rse = se;
+
+       return 0;
+}
+
+static void
+free_src(struct src_head *sh)
+{
+       struct src_entry *se;
+
+       while ((se = SIMPLEQ_FIRST(sh)) != NULL) {
+               SIMPLEQ_REMOVE_HEAD(sh, se_entry);
+               _db_factory_free(se->se_df);
+               free(se->se_name);
+               free(se);
+       }
+}
+
+
+#define T_COMM '#'
+static int
+convert_line(struct src_head *sh, const char *line, size_t len)
+{
+       int ret;
+       struct src_entry *se;
+       const char *p;
+       char key1[LINE_MAX], key2[LINE_MAX], data[LINE_MAX];
+       char *ep;
+       uint32_t val;
+
+       se = NULL; /* XXX gcc */
+
+       /* cut off trailing comment */
+       p = memchr(line, T_COMM, len);
+       if (p)
+               len = p - line;
+
+       /* key1 */
+       line = _bcs_skip_ws_len(line, &len);
+       if (len == 0)
+               return 0;
+       p = _bcs_skip_nonws_len(line, &len);
+       if (p==line)
+               return 0;
+       snprintf(key1, sizeof(key1), "%.*s", (int)(p-line), line);
+
+       /* key2 */
+       line = _bcs_skip_ws_len(p, &len);
+       if (len == 0)
+               return 0;
+       p = _bcs_skip_nonws_len(line, &len);
+       if (p==line)
+               return 0;
+       snprintf(key2, sizeof(key2), "%.*s", (int)(p-line), line);
+
+       /* data */
+       line = _bcs_skip_ws_len(p, &len);
+       _bcs_trunc_rws_len(line, &len);
+       snprintf(data, sizeof(data), "%.*s", (int)len, line);
+       val = strtoul(data, &ep, 0);
+       if (*ep != '\0')
+               return EFTYPE;
+
+       /* insert to DB */
+       ret = find_src(sh, &se, key1);
+       if (ret)
+               return ret;
+
+       return _db_factory_add32_by_s(se->se_df, key2, val);
+}
+
+static int
+dump_db(struct src_head *sh, struct _region *r)
+{
+       int ret;
+       struct _db_factory *df;
+       struct src_entry *se;
+       size_t size;
+       void *ptr;
+       struct _region subr;
+
+       ret = _db_factory_create(&df, &_db_hash_std, NULL);
+       if (ret)
+               return ret;
+
+       SIMPLEQ_FOREACH(se, sh, se_entry) {
+               size = _db_factory_calc_size(se->se_df);
+               ptr = malloc(size);
+               if (ptr == NULL)
+                       goto quit;
+               _region_init(&subr, ptr, size);
+               ret = _db_factory_serialize(se->se_df, _CITRUS_PIVOT_SUB_MAGIC,
+                                           &subr);
+               if (ret)
+                       goto quit;
+               ret = _db_factory_add_by_s(df, se->se_name, &subr, 1);
+               if (ret)
+                       goto quit;
+       }
+
+       size = _db_factory_calc_size(df);
+       ptr = malloc(size);
+       if (ptr == NULL)
+               goto quit;
+       _region_init(r, ptr, size);
+
+       ret = _db_factory_serialize(df, _CITRUS_PIVOT_MAGIC, r);
+       ptr = NULL;
+
+quit:
+       free(ptr);
+       _db_factory_free(df);
+       return ret;
+}
+
+int
+_citrus_pivot_factory_convert(FILE *out, FILE *in)
+{
+       struct src_head sh;
+       struct _region r;
+       char *line;
+       size_t size;
+       int ret;
+
+       SIMPLEQ_INIT(&sh);
+
+       while ((line = fgetln(in, &size)) != NULL)
+               if ((ret = convert_line(&sh, line, size))) {
+                       free_src(&sh);
+                       return ret;
+               }
+
+       ret = dump_db(&sh, &r);
+       free_src(&sh);
+       if (ret)
+               return ret;
+
+       if (fwrite(_region_head(&r), _region_size(&r), 1, out) != 1)
+               return errno;
+
+       return 0;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_pivot_factory.h b/lib/nbsd_libc/citrus/citrus_pivot_factory.h
new file mode 100644 (file)
index 0000000..dd5d804
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: citrus_pivot_factory.h,v 1.1 2003/06/25 09:51:39 tshiozak Exp $        */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_PIVOT_FACTORY_H_
+#define _CITRUS_PIVOT_FACTORY_H_
+
+__BEGIN_DECLS
+int    _citrus_pivot_factory_convert(FILE *, FILE *);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_pivot_file.h b/lib/nbsd_libc/citrus/citrus_pivot_file.h
new file mode 100644 (file)
index 0000000..eb50645
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: citrus_pivot_file.h,v 1.1 2003/06/25 09:51:39 tshiozak Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_PIVOT_FILE_H_
+#define _CITRUS_PIVOT_FILE_H_
+
+#define _CITRUS_PIVOT_MAGIC    "CSPIVOT\0"
+#define _CITRUS_PIVOT_SUB_MAGIC        "CSPIVSUB"
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_prop.c b/lib/nbsd_libc/citrus/citrus_prop.c
new file mode 100644 (file)
index 0000000..0b23628
--- /dev/null
@@ -0,0 +1,452 @@
+/* $NetBSD: citrus_prop.c,v 1.3 2006/11/22 23:47:21 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2006 Citrus Project,
+ * 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.
+ *
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_prop.c,v 1.3 2006/11/22 23:47:21 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <limits.h>
+#include <errno.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "citrus_namespace.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_memstream.h"
+#include "citrus_prop.h"
+
+typedef struct {
+       _citrus_prop_type_t type;
+       union {
+               const char *str;
+               int bool, chr;
+               uint64_t num;
+       } u;
+} _citrus_prop_object_t;
+
+static __inline void
+_citrus_prop_object_init(_citrus_prop_object_t *obj, _citrus_prop_type_t type)
+{
+       _DIAGASSERT(obj != NULL);
+
+       obj->type = type;
+       memset(&obj->u, 0, sizeof(obj->u));
+}
+
+static __inline void
+_citrus_prop_object_uninit(_citrus_prop_object_t *obj)
+{
+       _DIAGASSERT(obj != NULL);
+
+       if (obj->type == _CITRUS_PROP_STR)
+               free(__UNCONST(obj->u.str));
+}
+
+static const char *xdigit = "0123456789ABCDEF";
+
+#define _CITRUS_PROP_READ_UINT_COMMON(_func_, _type_, _max_)           \
+static int                                                             \
+_citrus_prop_read_##_func_##_common(struct _memstream * __restrict ms, \
+       _type_ * __restrict result, int base)                           \
+{                                                                      \
+       _type_ acc, cutoff;                                             \
+       int n, ch, cutlim;                                              \
+       char *p;                                                        \
+                                                                       \
+       _DIAGASSERT(ms != NULL);                                        \
+       _DIAGASSERT(result != NULL);                                    \
+                                                                       \
+       acc = (_type_)0;                                                \
+       cutoff = _max_ / base;                                          \
+       cutlim = _max_ % base;                                          \
+       for (;;) {                                                      \
+               ch = _memstream_getc(ms);                               \
+               p = strchr(xdigit, _bcs_toupper(ch));                   \
+               if (p == NULL || (n = (p - xdigit)) >= base)            \
+                       break;                                          \
+               if (acc > cutoff || (acc == cutoff && n > cutlim))      \
+                       break;                                          \
+               acc *= base;                                            \
+               acc += n;                                               \
+       }                                                               \
+       _memstream_ungetc(ms, ch);                                      \
+       *result = acc;                                                  \
+       return 0;                                                       \
+}
+_CITRUS_PROP_READ_UINT_COMMON(chr, int, UCHAR_MAX)
+_CITRUS_PROP_READ_UINT_COMMON(num, uint64_t, UINT64_MAX)
+#undef _CITRUS_PROP_READ_UINT_COMMON
+
+#define _CITRUS_PROP_READ_INT(_func_, _type_)                  \
+static int                                                     \
+_citrus_prop_read_##_func_(struct _memstream * __restrict ms,  \
+       _citrus_prop_object_t * __restrict obj)                 \
+{                                                              \
+       int ch, neg, base;                                      \
+                                                               \
+       _DIAGASSERT(ms != NULL);                                \
+       _DIAGASSERT(obj != NULL);                               \
+                                                               \
+       _memstream_skip_ws(ms);                                 \
+       ch = _memstream_getc(ms);                               \
+       neg = 0;                                                \
+       switch (ch) {                                           \
+       case '-':                                               \
+               neg = 1;                                        \
+       case '+':                                               \
+               ch = _memstream_getc(ms);                       \
+       }                                                       \
+       base = 10;                                              \
+       if (ch == '0') {                                        \
+               base -= 2;                                      \
+               ch = _memstream_getc(ms);                       \
+               if (ch == 'x' || ch == 'X') {                   \
+                       ch = _memstream_getc(ms);               \
+                       if (_bcs_isxdigit(ch) == 0) {           \
+                               _memstream_ungetc(ms, ch);      \
+                               obj->u._func_ = 0;              \
+                               return 0;                       \
+                       }                                       \
+                       base += 8;                              \
+               }                                               \
+       } else if (_bcs_isdigit(ch) == 0)                       \
+               return EINVAL;                                  \
+       _memstream_ungetc(ms, ch);                              \
+       return _citrus_prop_read_##_func_##_common              \
+           (ms, &obj->u._func_, base);                         \
+}
+_CITRUS_PROP_READ_INT(chr, int)
+_CITRUS_PROP_READ_INT(num, uint64_t)
+#undef _CITRUS_PROP_READ_INT
+
+static int
+_citrus_prop_read_character_common(struct _memstream * __restrict ms,
+       int * __restrict result)
+{
+       int ch, base;
+
+       _DIAGASSERT(ms != NULL);
+       _DIAGASSERT(result != NULL);
+
+       ch = _memstream_getc(ms);
+       if (ch != '\\') {
+               *result = ch;
+       } else {
+               ch = _memstream_getc(ms);
+               base = 16;
+               switch (ch) {
+               case 'a': *result = '\a'; break;
+               case 'b': *result = '\b'; break;
+               case 'f': *result = '\f'; break;
+               case 'n': *result = '\n'; break;
+               case 'r': *result = '\r'; break;
+               case 't': *result = '\t'; break;
+               case 'v': *result = '\v'; break;
+               /*FALLTHROUGH*/
+               case '0': case '1': case '2': case '3':
+               case '4': case '5': case '6': case '7':
+                       _memstream_ungetc(ms, ch);
+                       base -= 8;
+               case 'x':
+                       return _citrus_prop_read_chr_common(ms, result, base);
+                       
+               default:
+                       /* unknown escape */
+                       *result = ch;
+               }
+       }
+       return 0;
+}
+
+static int
+_citrus_prop_read_character(struct _memstream * __restrict ms,
+       _citrus_prop_object_t * __restrict obj)
+{
+       int ch, errnum;
+
+       _DIAGASSERT(ms != NULL);
+       _DIAGASSERT(obj != NULL);
+
+       _memstream_skip_ws(ms);
+       ch = _memstream_getc(ms);
+       if (ch != '\'') {
+               _memstream_ungetc(ms, ch);
+               return _citrus_prop_read_chr(ms, obj);
+       }
+       errnum = _citrus_prop_read_character_common(ms, &ch);
+       if (errnum != 0)
+               return errnum;
+       obj->u.chr = ch;
+       ch = _memstream_getc(ms);
+       if (ch != '\'')
+               return EINVAL;
+       return 0;
+}
+
+static int
+_citrus_prop_read_bool(struct _memstream * __restrict ms,
+       _citrus_prop_object_t * __restrict obj)
+{
+       _DIAGASSERT(ms != NULL);
+       _DIAGASSERT(obj != NULL);
+
+       _memstream_skip_ws(ms);
+       switch (_bcs_tolower(_memstream_getc(ms))) {
+       case 't':
+               if (_bcs_tolower(_memstream_getc(ms)) == 'r' &&
+                   _bcs_tolower(_memstream_getc(ms)) == 'u' &&
+                   _bcs_tolower(_memstream_getc(ms)) == 'e') {
+                       obj->u.bool = 1;
+                       return 0;
+               }
+               break;
+       case 'f':
+               if (_bcs_tolower(_memstream_getc(ms)) == 'a' &&
+                   _bcs_tolower(_memstream_getc(ms)) == 'l' &&
+                   _bcs_tolower(_memstream_getc(ms)) == 's' &&
+                   _bcs_tolower(_memstream_getc(ms)) == 'e') {
+                       obj->u.bool = 0;
+                       return 0;
+               }
+       }
+       return EINVAL;
+}
+
+static int
+_citrus_prop_read_str(struct _memstream * __restrict ms,
+       _citrus_prop_object_t * __restrict obj)
+{
+       int errnum, quot, ch;
+       char *s, *t;
+#define _CITRUS_PROP_STR_BUFSIZ        512
+       size_t n, m;
+
+       _DIAGASSERT(ms != NULL);
+       _DIAGASSERT(obj != NULL);
+
+       m = _CITRUS_PROP_STR_BUFSIZ;
+       s = malloc(m);
+       if (s == NULL)
+               return ENOMEM;
+       n = 0;
+       _memstream_skip_ws(ms);
+       quot = _memstream_getc(ms);
+       switch (quot) {
+       case EOF:
+               goto done;
+       case '\\':
+               _memstream_ungetc(ms, quot);
+               quot = EOF;
+       /*FALLTHROUGH*/
+       case '\"': case '\'':
+               break;
+       default:
+               s[n] = quot;
+               ++n, --m;
+               quot = EOF;
+       }
+       for (;;) {
+               if (m < 1) {
+                       m = _CITRUS_PROP_STR_BUFSIZ;
+                       t = realloc(s, n + m);
+                       if (t == NULL) {
+                               free(s);
+                               return ENOMEM;
+                       }
+                       s = t;
+               }
+               ch = _memstream_getc(ms);
+               if (quot == ch || (quot == EOF &&
+                   (ch == ';' || _bcs_isspace(ch)))) {
+done:
+                       s[n] = '\0';
+                       obj->u.str = (const char *)s;
+                       return 0;
+               }
+               _memstream_ungetc(ms, ch);
+               errnum = _citrus_prop_read_character_common(ms, &ch);
+               if (errnum != 0)
+                       return errnum;
+               s[n] = ch;
+               ++n, --m;
+       }
+       free(s);
+       return EINVAL;
+#undef _CITRUS_PROP_STR_BUFSIZ
+}
+
+typedef int (*_citrus_prop_read_type_t)(struct _memstream * __restrict,
+       _citrus_prop_object_t * __restrict);
+
+static const _citrus_prop_read_type_t readers[] = {
+       _citrus_prop_read_bool,
+       _citrus_prop_read_str,
+       _citrus_prop_read_character,
+       _citrus_prop_read_num,
+};
+
+static __inline int
+_citrus_prop_read_symbol(struct _memstream * __restrict ms,
+       char * __restrict s, size_t n)
+{
+       int ch;
+       size_t m;
+
+       _DIAGASSERT(ms != NULL);
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(n > 0);
+
+       for (m = 0; m < n; ++m) {
+               ch = _memstream_getc(ms);
+               if (ch != '_' && _bcs_isalnum(ch) == 0)
+                       goto name_found;
+               s[m] = ch;
+       }
+       ch = _memstream_getc(ms);
+       if (ch == '_' || _bcs_isalnum(ch) != 0)
+               return EINVAL;
+
+name_found:
+       _memstream_ungetc(ms, ch);
+       s[m] = '\0';
+
+       return 0;
+}
+
+static int
+_citrus_prop_parse_element(struct _memstream * __restrict ms,
+       const _citrus_prop_hint_t * __restrict hints,
+       void ** __restrict context)
+{
+       int ch, errnum;
+#define _CITRUS_PROP_HINT_NAME_LEN_MAX 255
+       char name[_CITRUS_PROP_HINT_NAME_LEN_MAX + 1];
+       const _citrus_prop_hint_t *hint;
+       _citrus_prop_object_t ostart, oend;
+
+       _DIAGASSERT(ms != NULL);
+       _DIAGASSERT(hints != NULL);
+
+       errnum = _citrus_prop_read_symbol(ms, name, sizeof(name));
+       if (errnum != 0)
+               return errnum;
+       for (hint = hints; hint->name != NULL; ++hint) {
+               if (_citrus_bcs_strcasecmp(name, hint->name) == 0)
+                       goto hint_found;
+       }
+       return EINVAL;
+
+hint_found:
+       _memstream_skip_ws(ms);
+       ch = _memstream_getc(ms);
+       if (ch != '=' && ch != ':')
+               _memstream_ungetc(ms, ch);
+       do {
+               _citrus_prop_object_init(&ostart, hint->type);
+               _citrus_prop_object_init(&oend, hint->type);
+               errnum = (*readers[hint->type])(ms, &ostart);
+               if (errnum != 0)
+                       return errnum;
+               _memstream_skip_ws(ms);
+               ch = _memstream_getc(ms);
+               switch (hint->type) {
+               case _CITRUS_PROP_BOOL:
+               case _CITRUS_PROP_STR:
+                       break;
+               default:
+                       if (ch != '-')
+                               break;
+                       errnum = (*readers[hint->type])(ms, &oend);
+                       if (errnum != 0)
+                               return errnum;
+                       _memstream_skip_ws(ms);
+                       ch = _memstream_getc(ms);
+               }
+#define CALL0(_func_)                                  \
+do {                                                   \
+       _DIAGASSERT(hint->cb._func_.func != NULL);      \
+       errnum = (*hint->cb._func_.func)(context,       \
+           hint->name, ostart.u._func_);               \
+} while (/*CONSTCOND*/0)
+#define CALL1(_func_)                                  \
+do {                                                   \
+       _DIAGASSERT(hint->cb._func_.func != NULL);      \
+       errnum = (*hint->cb._func_.func)(context,       \
+           hint->name, ostart.u._func_, oend.u._func_);\
+} while (/*CONSTCOND*/0)
+               switch (hint->type) {
+               case _CITRUS_PROP_BOOL: CALL0(bool); break;
+               case _CITRUS_PROP_STR : CALL0( str); break;
+               case _CITRUS_PROP_CHR : CALL1( chr); break;
+               case _CITRUS_PROP_NUM : CALL1( num); break;
+               default:
+                       abort();
+                       /*NOTREACHED*/
+               }
+#undef CALL0
+#undef CALL1
+               _citrus_prop_object_uninit(&ostart);
+               _citrus_prop_object_uninit(&oend);
+               if (errnum != 0)
+                       return errnum;
+       } while (ch == ',');
+       if (ch != ';')
+               _memstream_ungetc(ms, ch);
+       return 0;
+}
+
+int
+_citrus_prop_parse_variable(const _citrus_prop_hint_t * __restrict hints,
+       void * __restrict context, const void *var, size_t lenvar)
+{
+       struct _memstream ms;
+       int errnum, ch;
+
+       _DIAGASSERT(hints != NULL);
+
+       _memstream_bind_ptr(&ms, __UNCONST(var), lenvar);
+       for (;;) {
+               _memstream_skip_ws(&ms);
+               ch = _memstream_getc(&ms);
+               if (ch == EOF || ch == '\0')
+                       break;
+               _memstream_ungetc(&ms, ch);
+               errnum = _citrus_prop_parse_element(
+                   &ms, hints, (void **)&context);
+               if (errnum != 0)
+                       return errnum;
+       }
+       return 0;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_prop.h b/lib/nbsd_libc/citrus/citrus_prop.h
new file mode 100644 (file)
index 0000000..86d3ed1
--- /dev/null
@@ -0,0 +1,91 @@
+/* $NetBSD: citrus_prop.h,v 1.3 2006/11/23 13:59:03 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2006 Citrus Project,
+ * 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.
+ *
+ */
+
+#ifndef _CITRUS_PROP_H_
+#define _CITRUS_PROP_H_
+
+typedef enum {
+       _CITRUS_PROP_BOOL = 0,
+       _CITRUS_PROP_STR  = 1,
+       _CITRUS_PROP_CHR  = 2,
+       _CITRUS_PROP_NUM  = 3,
+} _citrus_prop_type_t;
+
+typedef struct _citrus_prop_hint_t _citrus_prop_hint_t;
+
+#define _CITRUS_PROP_CB0_T(_func_, _type_) \
+typedef int (*_citrus_prop_##_func_##_cb_func_t) \
+       (void ** __restrict, const char *, _type_); \
+typedef struct { \
+       _citrus_prop_##_func_##_cb_func_t func; \
+} _citrus_prop_##_func_##_cb_t;
+_CITRUS_PROP_CB0_T(bool, int)
+_CITRUS_PROP_CB0_T(str, const char *)
+#undef _CITRUS_PROP_CB0_T
+
+#define _CITRUS_PROP_CB1_T(_func_, _type_) \
+typedef int (*_citrus_prop_##_func_##_cb_func_t) \
+       (void ** __restrict, const char *, _type_, _type_); \
+typedef struct { \
+       _citrus_prop_##_func_##_cb_func_t func; \
+} _citrus_prop_##_func_##_cb_t;
+_CITRUS_PROP_CB1_T(chr, int)
+_CITRUS_PROP_CB1_T(num, uint64_t)
+#undef _CITRUS_PROP_CB1_T
+
+struct _citrus_prop_hint_t {
+       const char *name;
+       _citrus_prop_type_t type;
+#define _CITRUS_PROP_CB_T_OPS(_name_) \
+       _citrus_prop_##_name_##_cb_t _name_
+       union {
+               _CITRUS_PROP_CB_T_OPS(bool);
+               _CITRUS_PROP_CB_T_OPS(str);
+               _CITRUS_PROP_CB_T_OPS(chr);
+               _CITRUS_PROP_CB_T_OPS(num);
+       } cb;
+};
+
+#define _CITRUS_PROP_HINT_BOOL(name, cb) \
+       { name, _CITRUS_PROP_BOOL, { .bool = { cb } } }
+#define _CITRUS_PROP_HINT_STR(name, cb) \
+       { name, _CITRUS_PROP_STR, { .str = { cb } } }
+#define _CITRUS_PROP_HINT_CHR(name, cb) \
+       { name, _CITRUS_PROP_CHR, { .chr = { cb } } }
+#define _CITRUS_PROP_HINT_NUM(name, cb) \
+       { name, _CITRUS_PROP_NUM, { .num = { cb } } }
+#define _CITRUS_PROP_HINT_END \
+       { NULL }
+
+__BEGIN_DECLS
+int _citrus_prop_parse_variable(const _citrus_prop_hint_t * __restrict,
+       void * __restrict, const void *, size_t);
+__END_DECLS
+
+#endif /* !_CITRUS_PROP_H_ */
diff --git a/lib/nbsd_libc/citrus/citrus_region.h b/lib/nbsd_libc/citrus/citrus_region.h
new file mode 100644 (file)
index 0000000..18c9db7
--- /dev/null
@@ -0,0 +1,108 @@
+/*     $NetBSD: citrus_region.h,v 1.7 2008/02/09 14:56:20 junyoung Exp $       */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ *
+ */
+
+#ifndef _CITRUS_REGION_H_
+#define _CITRUS_REGION_H_
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+struct _citrus_region {
+/* private: */
+       void    *r_head;
+       size_t  r_size;
+};
+
+static __inline void
+_citrus_region_init(struct _citrus_region *r, void *h, size_t sz)
+{
+       _DIAGASSERT(r);
+       r->r_head = h;
+       r->r_size = sz;
+}
+
+static __inline void *
+_citrus_region_head(const struct _citrus_region *r)
+{
+       return r->r_head;
+}
+
+static __inline size_t
+_citrus_region_size(const struct _citrus_region *r)
+{
+       return r->r_size;
+}
+
+static __inline int
+_citrus_region_check(const struct _citrus_region *r, size_t ofs, size_t sz)
+{
+       return r->r_size >= ofs + sz ? 0 : -1;
+}
+
+static __inline void *
+_citrus_region_offset(const struct _citrus_region *r, size_t pos)
+{
+       return (void *)((uint8_t *)r->r_head + pos);
+}
+
+static __inline uint8_t
+_citrus_region_peek8(const struct _citrus_region *r, size_t pos)
+{
+       return *(uint8_t *)_citrus_region_offset(r, pos);
+}
+
+static __inline uint16_t
+_citrus_region_peek16(const struct _citrus_region *r, size_t pos)
+{
+       uint16_t val;
+       memcpy(&val, _citrus_region_offset(r, pos), (size_t)2);
+       return val;
+}
+
+static __inline uint32_t
+_citrus_region_peek32(const struct _citrus_region *r, size_t pos)
+{
+       uint32_t val;
+       memcpy(&val, _citrus_region_offset(r, pos), (size_t)4);
+       return val;
+}
+
+static __inline int
+_citrus_region_get_subregion(struct _citrus_region *subr,
+                            const struct _citrus_region *r,
+                            size_t ofs, size_t sz)
+{
+       if (_citrus_region_check(r, ofs, sz))
+               return -1;
+       _citrus_region_init(subr, _citrus_region_offset(r, ofs), sz);
+       return 0;
+}
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_stdenc.c b/lib/nbsd_libc/citrus/citrus_stdenc.c
new file mode 100644 (file)
index 0000000..d784075
--- /dev/null
@@ -0,0 +1,197 @@
+/*     $NetBSD: citrus_stdenc.c,v 1.3 2005/10/29 18:02:04 tshiozak Exp $       */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_stdenc.c,v 1.3 2005/10/29 18:02:04 tshiozak Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_stdenc.h"
+#include "citrus_none.h"
+
+struct _citrus_stdenc _citrus_stdenc_default = {
+       &_citrus_NONE_stdenc_ops,       /* ce_ops */
+       NULL,                           /* ce_closure */
+       NULL,                           /* ce_module */
+       &_citrus_NONE_stdenc_traits,    /* ce_traits */
+};
+
+#ifdef _I18N_DYNAMIC
+
+static int
+/*ARGSUSED*/
+get_state_desc_default(struct _citrus_stdenc * __restrict ce,
+                      void * __restrict ps,
+                      int id,
+                      struct _citrus_stdenc_state_desc * __restrict d)
+{
+       return EOPNOTSUPP;
+}
+
+int
+_citrus_stdenc_open(struct _citrus_stdenc * __restrict * __restrict rce,
+                   char const * __restrict encname,
+                   const void * __restrict variable, size_t lenvar)
+{
+       int ret;
+       _citrus_module_t handle;
+       struct _citrus_stdenc *ce;
+       _citrus_stdenc_getops_t getops;
+
+       _DIAGASSERT(encname != NULL);
+       _DIAGASSERT(!lenvar || variable!=NULL);
+       _DIAGASSERT(rce != NULL);
+
+       if (!strcmp(encname, _CITRUS_DEFAULT_STDENC_NAME)) {
+               *rce = &_citrus_stdenc_default;
+               return (0);
+       }
+       ce = malloc(sizeof(*ce));
+       if (ce==NULL) {
+               ret = errno;
+               goto bad;
+       }
+       ce->ce_ops = NULL;
+       ce->ce_closure = NULL;
+       ce->ce_module = NULL;
+       ce->ce_traits = NULL;
+
+       ret = _citrus_load_module(&handle, encname);
+       if (ret)
+               goto bad;
+
+       ce->ce_module = handle;
+
+       getops =
+           (_citrus_stdenc_getops_t)_citrus_find_getops(ce->ce_module,
+                                                        encname, "stdenc");
+       if (getops == NULL) {
+               ret = EINVAL;
+               goto bad;
+       }
+
+       ce->ce_ops = (struct _citrus_stdenc_ops *)malloc(sizeof(*ce->ce_ops));
+       if (ce->ce_ops == NULL) {
+               ret = errno;
+               goto bad;
+       }
+
+       ret = (*getops)(ce->ce_ops, sizeof(*ce->ce_ops),
+                       _CITRUS_STDENC_ABI_VERSION);
+       if (ret)
+               goto bad;
+
+       /* If return ABI version is not expected, should fixup it */
+       if (ce->ce_ops->eo_abi_version < 0x00000002) {
+               ce->ce_ops->eo_get_state_desc = &get_state_desc_default;
+       }
+
+       /* validation check */
+       if (ce->ce_ops->eo_init == NULL ||
+           ce->ce_ops->eo_uninit == NULL ||
+           ce->ce_ops->eo_init_state == NULL ||
+           ce->ce_ops->eo_mbtocs == NULL ||
+           ce->ce_ops->eo_cstomb == NULL ||
+           ce->ce_ops->eo_mbtowc == NULL ||
+           ce->ce_ops->eo_wctomb == NULL ||
+           ce->ce_ops->eo_get_state_desc == NULL)
+               goto bad;
+
+       /* allocate traits */
+       ce->ce_traits = malloc(sizeof(*ce->ce_traits));
+       if (ce->ce_traits == NULL) {
+               ret = errno;
+               goto bad;
+       }
+       /* init and get closure */
+       ret = (*ce->ce_ops->eo_init)(ce, variable, lenvar, ce->ce_traits);
+       if (ret)
+               goto bad;
+
+       *rce = ce;
+
+       return (0);
+
+bad:
+       _citrus_stdenc_close(ce);
+       return (ret);
+}
+
+void
+_citrus_stdenc_close(struct _citrus_stdenc *ce)
+{
+
+       _DIAGASSERT(ce != NULL);
+
+       if (ce == &_citrus_stdenc_default)
+               return;
+
+       if (ce->ce_module) {
+               if (ce->ce_ops) {
+                       if (ce->ce_closure && ce->ce_ops->eo_uninit)
+                               (*ce->ce_ops->eo_uninit)(ce);
+                       free(ce->ce_ops);
+               }
+               free(ce->ce_traits);
+               _citrus_unload_module(ce->ce_module);
+       }
+       free(ce);
+}
+
+#else
+/* !_I18N_DYNAMIC */
+
+int
+/*ARGSUSED*/
+_citrus_stdenc_open(struct _citrus_stdenc * __restrict * __restrict rce,
+                   char const * __restrict encname,
+                   const void * __restrict variable, size_t lenvar)
+{
+       if (!strcmp(encname, _CITRUS_DEFAULT_STDENC_NAME)) {
+               *rce = &_citrus_stdenc_default;
+               return (0);
+       }
+       return (EINVAL);
+}
+
+void
+/*ARGSUSED*/
+_citrus_stdenc_close(struct _citrus_stdenc *ce)
+{
+}
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_stdenc.h b/lib/nbsd_libc/citrus/citrus_stdenc.h
new file mode 100644 (file)
index 0000000..ce198db
--- /dev/null
@@ -0,0 +1,145 @@
+/*     $NetBSD: citrus_stdenc.h,v 1.4 2005/10/29 18:02:04 tshiozak Exp $       */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ *
+ */
+
+#ifndef _CITRUS_STDENC_H_
+#define _CITRUS_STDENC_H_
+
+struct _citrus_stdenc;
+struct _citrus_stdenc_ops;
+struct _citrus_stdenc_traits;
+
+#define _CITRUS_STDENC_SDID_GENERIC            0
+struct _citrus_stdenc_state_desc
+{
+       union {
+               struct {
+                       int     state;
+#define _CITRUS_STDENC_SDGEN_UNKNOWN           0
+#define _CITRUS_STDENC_SDGEN_INITIAL           1
+#define _CITRUS_STDENC_SDGEN_STABLE            2
+#define _CITRUS_STDENC_SDGEN_INCOMPLETE_CHAR   3
+#define _CITRUS_STDENC_SDGEN_INCOMPLETE_SHIFT  4
+               } generic;
+       } u;
+};
+
+#include "citrus_stdenc_local.h"
+
+__BEGIN_DECLS
+int _citrus_stdenc_open(struct _citrus_stdenc * __restrict * __restrict,
+                       char const * __restrict,
+                       const void * __restrict, size_t);
+void _citrus_stdenc_close(struct _citrus_stdenc *);
+__END_DECLS
+
+static __inline int
+_citrus_stdenc_init_state(struct _citrus_stdenc * __restrict ce,
+                         void * __restrict ps)
+{
+       _DIAGASSERT(ce && ce->ce_ops && ce->ce_ops->eo_init_state);
+       return (*ce->ce_ops->eo_init_state)(ce, ps);
+}
+
+static __inline int
+_citrus_stdenc_mbtocs(struct _citrus_stdenc * __restrict ce,
+                     _citrus_csid_t * __restrict csid,
+                     _citrus_index_t * __restrict idx,
+                     const char ** __restrict s, size_t n,
+                     void * __restrict ps, size_t * __restrict nresult)
+{
+       _DIAGASSERT(ce && ce->ce_ops && ce->ce_ops->eo_mbtocs);
+       return (*ce->ce_ops->eo_mbtocs)(ce, csid, idx, s, n, ps, nresult);
+}
+
+static __inline int
+_citrus_stdenc_cstomb(struct _citrus_stdenc * __restrict ce,
+                     char * __restrict s, size_t n,
+                     _citrus_csid_t csid, _citrus_index_t idx,
+                     void * __restrict ps, size_t * __restrict nresult)
+{
+       _DIAGASSERT(ce && ce->ce_ops && ce->ce_ops->eo_cstomb);
+       return (*ce->ce_ops->eo_cstomb)(ce, s, n, csid, idx, ps, nresult);
+}
+
+static __inline int
+_citrus_stdenc_mbtowc(struct _citrus_stdenc * __restrict ce,
+                     _citrus_wc_t * __restrict wc,
+                     const char ** __restrict s, size_t n,
+                     void * __restrict ps, size_t * __restrict nresult)
+{
+       _DIAGASSERT(ce && ce->ce_ops && ce->ce_ops->eo_mbtocs);
+       return (*ce->ce_ops->eo_mbtowc)(ce, wc, s, n, ps, nresult);
+}
+
+static __inline int
+_citrus_stdenc_wctomb(struct _citrus_stdenc * __restrict ce,
+                     char * __restrict s, size_t n, _citrus_wc_t wc,
+                     void * __restrict ps, size_t * __restrict nresult)
+{
+       _DIAGASSERT(ce && ce->ce_ops && ce->ce_ops->eo_cstomb);
+       return (*ce->ce_ops->eo_wctomb)(ce, s, n, wc, ps, nresult);
+}
+
+static __inline int
+_citrus_stdenc_put_state_reset(struct _citrus_stdenc * __restrict ce,
+                              char * __restrict s, size_t n,
+                              void * __restrict ps,
+                              size_t * __restrict nresult)
+{
+       _DIAGASSERT(ce && ce->ce_ops && ce->ce_ops->eo_put_state_reset);
+       return (*ce->ce_ops->eo_put_state_reset)(ce, s, n, ps, nresult);
+}
+
+static __inline size_t
+_citrus_stdenc_get_state_size(struct _citrus_stdenc *ce)
+{
+       _DIAGASSERT(ce && ce->ce_traits);
+       return ce->ce_traits->et_state_size;
+}
+
+static __inline size_t
+_citrus_stdenc_get_mb_cur_max(struct _citrus_stdenc *ce)
+{
+       _DIAGASSERT(ce && ce->ce_traits);
+       return ce->ce_traits->et_mb_cur_max;
+}
+
+static __inline int
+_citrus_stdenc_get_state_desc(struct _citrus_stdenc * __restrict ce,
+                             void * __restrict ps,
+                             int id,
+                             struct _citrus_stdenc_state_desc * __restrict d)
+{
+
+       _DIAGASSERT(ce && ce->ce_ops && ce->ce_ops->eo_get_state_desc);
+
+       return (*ce->ce_ops->eo_get_state_desc)(ce, ps, id, d);
+}
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_stdenc_local.h b/lib/nbsd_libc/citrus/citrus_stdenc_local.h
new file mode 100644 (file)
index 0000000..bac89c6
--- /dev/null
@@ -0,0 +1,153 @@
+/*     $NetBSD: citrus_stdenc_local.h,v 1.4 2008/02/09 14:56:20 junyoung Exp $ */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ *
+ */
+
+#ifndef _CITRUS_STDENC_LOCAL_H_
+#define _CITRUS_STDENC_LOCAL_H_
+
+#define _CITRUS_STDENC_GETOPS_FUNC_BASE(n)                     \
+int n(struct _citrus_stdenc_ops *, size_t, uint32_t)
+#define _CITRUS_STDENC_GETOPS_FUNC(_e_)                                        \
+_CITRUS_STDENC_GETOPS_FUNC_BASE(_citrus_##_e_##_stdenc_getops)
+typedef _CITRUS_STDENC_GETOPS_FUNC_BASE((*_citrus_stdenc_getops_t));
+
+
+#define _CITRUS_STDENC_DECLS(_e_)                                      \
+static int     _citrus_##_e_##_stdenc_init                             \
+       (struct _citrus_stdenc * __restrict, const void * __restrict,   \
+        size_t, struct _citrus_stdenc_traits * __restrict);            \
+static void    _citrus_##_e_##_stdenc_uninit(struct _citrus_stdenc *); \
+static int     _citrus_##_e_##_stdenc_init_state                       \
+       (struct _citrus_stdenc * __restrict, void * __restrict);        \
+static int     _citrus_##_e_##_stdenc_mbtocs                           \
+       (struct _citrus_stdenc * __restrict,                            \
+        _citrus_csid_t * __restrict, _citrus_index_t * __restrict,     \
+        const char ** __restrict, size_t,                              \
+        void * __restrict, size_t * __restrict);                       \
+static int     _citrus_##_e_##_stdenc_cstomb                           \
+       (struct _citrus_stdenc * __restrict, char * __restrict,         \
+        size_t, _citrus_csid_t, _citrus_index_t,                       \
+        void * __restrict, size_t * __restrict);                       \
+static int     _citrus_##_e_##_stdenc_mbtowc                           \
+       (struct _citrus_stdenc * __restrict,                            \
+        _citrus_wc_t * __restrict,                                     \
+        const char ** __restrict, size_t,                              \
+        void * __restrict, size_t * __restrict);                       \
+static int     _citrus_##_e_##_stdenc_wctomb                           \
+       (struct _citrus_stdenc * __restrict, char * __restrict, size_t, \
+        _citrus_wc_t, void * __restrict, size_t * __restrict);         \
+static int     _citrus_##_e_##_stdenc_put_state_reset                  \
+       (struct _citrus_stdenc * __restrict, char * __restrict, size_t, \
+        void * __restrict, size_t * __restrict);                       \
+static int     _citrus_##_e_##_stdenc_get_state_desc                   \
+       (struct _citrus_stdenc * __restrict, void * __restrict, int,    \
+        struct _citrus_stdenc_state_desc * __restrict)
+
+#define _CITRUS_STDENC_DEF_OPS(_e_)                                    \
+struct _citrus_stdenc_ops _citrus_##_e_##_stdenc_ops = {               \
+       /* eo_abi_version */    _CITRUS_STDENC_ABI_VERSION,             \
+       /* eo_init */           &_citrus_##_e_##_stdenc_init,           \
+       /* eo_uninit */         &_citrus_##_e_##_stdenc_uninit,         \
+       /* eo_init_state */     &_citrus_##_e_##_stdenc_init_state,     \
+       /* eo_mbtocs */         &_citrus_##_e_##_stdenc_mbtocs,         \
+       /* eo_cstomb */         &_citrus_##_e_##_stdenc_cstomb,         \
+       /* eo_mbtowc */         &_citrus_##_e_##_stdenc_mbtowc,         \
+       /* eo_wctomb */         &_citrus_##_e_##_stdenc_wctomb,         \
+       /* eo_put_state_reset */&_citrus_##_e_##_stdenc_put_state_reset,\
+       /* eo_get_state_desc */ &_citrus_##_e_##_stdenc_get_state_desc  \
+}
+
+typedef int    (*_citrus_stdenc_init_t)
+       (struct _citrus_stdenc * __reatrict, const void * __restrict , size_t,
+        struct _citrus_stdenc_traits * __restrict);
+typedef void   (*_citrus_stdenc_uninit_t)(struct _citrus_stdenc * __restrict);
+typedef int    (*_citrus_stdenc_init_state_t)
+       (struct _citrus_stdenc * __restrict, void * __restrict);
+typedef int    (*_citrus_stdenc_mbtocs_t)
+       (struct _citrus_stdenc * __restrict,
+        _citrus_csid_t * __restrict, _citrus_index_t * __restrict,
+        const char ** __restrict, size_t,
+        void * __restrict, size_t * __restrict);
+typedef int    (*_citrus_stdenc_cstomb_t)
+       (struct _citrus_stdenc *__restrict, char * __restrict, size_t,
+        _citrus_csid_t, _citrus_index_t, void * __restrict,
+        size_t * __restrict);
+typedef int    (*_citrus_stdenc_mbtowc_t)
+       (struct _citrus_stdenc * __restrict,
+        _citrus_wc_t * __restrict,
+        const char ** __restrict, size_t,
+        void * __restrict, size_t * __restrict);
+typedef int    (*_citrus_stdenc_wctomb_t)
+       (struct _citrus_stdenc *__restrict, char * __restrict, size_t,
+        _citrus_wc_t, void * __restrict, size_t * __restrict);
+typedef int    (*_citrus_stdenc_put_state_reset_t)
+       (struct _citrus_stdenc *__restrict, char * __restrict, size_t,
+        void * __restrict, size_t * __restrict);
+typedef int    (*_citrus_stdenc_get_state_desc_t)
+       (struct _citrus_stdenc * __restrict, void * __restrict, int,
+        struct _citrus_stdenc_state_desc * __restrict);
+/*
+ * ABI version change log
+ *   0x00000001
+ *     initial version
+ */
+#define _CITRUS_STDENC_ABI_VERSION     0x00000002
+struct _citrus_stdenc_ops {
+       uint32_t                        eo_abi_version;
+       /* version 0x00000001 */
+       _citrus_stdenc_init_t           eo_init;
+       _citrus_stdenc_uninit_t         eo_uninit;
+       _citrus_stdenc_init_state_t     eo_init_state;
+       _citrus_stdenc_mbtocs_t         eo_mbtocs;
+       _citrus_stdenc_cstomb_t         eo_cstomb;
+       _citrus_stdenc_mbtowc_t         eo_mbtowc;
+       _citrus_stdenc_wctomb_t         eo_wctomb;
+       _citrus_stdenc_put_state_reset_t eo_put_state_reset;
+       /* version 0x00000002 */
+       _citrus_stdenc_get_state_desc_t eo_get_state_desc;
+};
+
+struct _citrus_stdenc_traits {
+       /* version 0x00000001 */
+       size_t                          et_state_size;
+       size_t                          et_mb_cur_max;
+};
+
+struct _citrus_stdenc {
+       /* public */
+       /* version 0x00000001 */
+       struct _citrus_stdenc_ops       *ce_ops;
+       void                            *ce_closure;
+       /* private */
+       _citrus_module_t                ce_module;
+       struct _citrus_stdenc_traits    *ce_traits;
+};
+
+#define _CITRUS_DEFAULT_STDENC_NAME            "NONE"
+
+#endif
diff --git a/lib/nbsd_libc/citrus/citrus_stdenc_template.h b/lib/nbsd_libc/citrus/citrus_stdenc_template.h
new file mode 100644 (file)
index 0000000..54088cd
--- /dev/null
@@ -0,0 +1,206 @@
+/*     $NetBSD: citrus_stdenc_template.h,v 1.4 2008/02/09 14:56:20 junyoung Exp $      */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+/*
+ * CAUTION: THIS IS NOT STANDALONE FILE
+ *
+ * function templates of iconv standard encoding handler for each encodings.
+ *
+ */
+
+/*
+ * macros
+ */
+
+#undef _TO_EI
+#undef _CE_TO_EI
+#undef _TO_STATE
+#define _TO_EI(_cl_)   ((_ENCODING_INFO*)(_cl_))
+#define _CE_TO_EI(_ce_)        (_TO_EI((_ce_)->ce_closure))
+#define _TO_STATE(_ps_)        ((_ENCODING_STATE*)(_ps_))
+
+/* ----------------------------------------------------------------------
+ * templates for public functions
+ */
+
+int
+_FUNCNAME(stdenc_getops)(struct _citrus_stdenc_ops *ops, size_t lenops,
+                        uint32_t expected_version)
+{
+       if (expected_version<_CITRUS_STDENC_ABI_VERSION || lenops<sizeof(*ops))
+               return (EINVAL);
+
+       memcpy(ops, &_FUNCNAME(stdenc_ops), sizeof(_FUNCNAME(stdenc_ops)));
+
+       return (0);
+}
+
+static int
+_FUNCNAME(stdenc_init)(struct _citrus_stdenc * __restrict ce,
+                      const void * __restrict var, size_t lenvar,
+                      struct _citrus_stdenc_traits * __restrict et)
+{
+       int ret;
+       _ENCODING_INFO *ei;
+
+       ei = NULL;
+       if (sizeof(_ENCODING_INFO) > 0) {
+               ei = calloc(1, sizeof(_ENCODING_INFO));
+               if (ei == NULL) {
+                       return errno;
+               }
+       }
+
+       ret = _FUNCNAME(encoding_module_init)(ei, var, lenvar);
+       if (ret) {
+               free((void *)ei);
+               return ret;
+       }
+
+       ce->ce_closure = ei;
+       et->et_state_size = sizeof(_ENCODING_STATE);
+       et->et_mb_cur_max = _ENCODING_MB_CUR_MAX(_CE_TO_EI(ce));
+
+       return 0;
+}
+
+static void
+_FUNCNAME(stdenc_uninit)(struct _citrus_stdenc * __restrict ce)
+{
+       if (ce) {
+               _FUNCNAME(encoding_module_uninit)(_CE_TO_EI(ce));
+               free(ce->ce_closure);
+       }
+}
+
+static int
+_FUNCNAME(stdenc_init_state)(struct _citrus_stdenc * __restrict ce,
+                            void * __restrict ps)
+{
+       _FUNCNAME(init_state)(_CE_TO_EI(ce), _TO_STATE(ps));
+
+       return 0;
+}
+
+static int
+_FUNCNAME(stdenc_mbtocs)(struct _citrus_stdenc * __restrict ce,
+                        _citrus_csid_t * __restrict csid,
+                        _citrus_index_t * __restrict idx,
+                        const char ** __restrict s, size_t n,
+                        void * __restrict ps, size_t * __restrict nresult)
+{
+       int ret;
+       wchar_t wc;
+
+       _DIAGASSERT(nresult != NULL);
+
+       ret = _FUNCNAME(mbrtowc_priv)(_CE_TO_EI(ce), &wc, s, n,
+                                     _TO_STATE(ps), nresult);
+
+       if (!ret && *nresult != (size_t)-2)
+               _FUNCNAME(stdenc_wctocs)(_CE_TO_EI(ce), csid, idx, wc);
+
+       return ret;
+}
+
+static int
+_FUNCNAME(stdenc_cstomb)(struct _citrus_stdenc * __restrict ce,
+                        char * __restrict s, size_t n,
+                        _citrus_csid_t csid, _citrus_index_t idx,
+                        void * __restrict ps, size_t * __restrict nresult)
+{
+       int ret;
+       wchar_t wc;
+
+       _DIAGASSERT(nresult != NULL);
+
+       wc = 0;
+
+       if (csid != _CITRUS_CSID_INVALID) {
+               ret = _FUNCNAME(stdenc_cstowc)(_CE_TO_EI(ce), &wc, csid, idx);
+               if (ret)
+                       return ret;
+       }
+
+       return _FUNCNAME(wcrtomb_priv)(_CE_TO_EI(ce), s, n, wc, _TO_STATE(ps),
+                                      nresult);
+}
+
+static int
+_FUNCNAME(stdenc_mbtowc)(struct _citrus_stdenc * __restrict ce,
+                        _citrus_wc_t * __restrict wc,
+                        const char ** __restrict s, size_t n,
+                        void * __restrict ps, size_t * __restrict nresult)
+{
+       return _FUNCNAME(mbrtowc_priv)(_CE_TO_EI(ce), wc, s, n,
+                                      _TO_STATE(ps), nresult);
+}
+
+static int
+_FUNCNAME(stdenc_wctomb)(struct _citrus_stdenc * __restrict ce,
+                         char * __restrict s, size_t n, _citrus_wc_t wc,
+                         void * __restrict ps, size_t * __restrict nresult)
+{
+       return _FUNCNAME(wcrtomb_priv)(_CE_TO_EI(ce), s, n, wc, _TO_STATE(ps),
+                                      nresult);
+}
+
+static int
+_FUNCNAME(stdenc_put_state_reset)(struct _citrus_stdenc * __restrict ce,
+                                 char * __restrict s, size_t n,
+                                 void * __restrict ps,
+                                 size_t * __restrict nresult)
+{
+#if _ENCODING_IS_STATE_DEPENDENT
+       return _FUNCNAME(put_state_reset)(_CE_TO_EI(ce), s, n, _TO_STATE(ps),
+                                         nresult);
+#else
+       *nresult = 0;
+       return 0;
+#endif
+}
+
+static int
+_FUNCNAME(stdenc_get_state_desc)(struct _citrus_stdenc * __restrict ce,
+                                void * __restrict ps,
+                                int id,
+                                struct _citrus_stdenc_state_desc * __restrict d)
+{
+       int ret;
+
+       switch (id) {
+       case _STDENC_SDID_GENERIC:
+               ret = _FUNCNAME(stdenc_get_state_desc_generic)(
+                       _CE_TO_EI(ce), _TO_STATE(ps), &d->u.generic.state);
+               break;
+       default:
+               ret = EOPNOTSUPP;
+       }
+
+       return ret;
+}
diff --git a/lib/nbsd_libc/citrus/citrus_types.h b/lib/nbsd_libc/citrus/citrus_types.h
new file mode 100644 (file)
index 0000000..6692fd3
--- /dev/null
@@ -0,0 +1,41 @@
+/*     $NetBSD: citrus_types.h,v 1.3 2003/10/27 00:12:42 lukem Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_TYPES_H_
+#define _CITRUS_TYPES_H_
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+typedef uint32_t       _citrus_wc_t;
+typedef uint32_t       _citrus_index_t;
+typedef uint32_t       _citrus_csid_t;
+#define _CITRUS_CSID_INVALID   ((_citrus_csid_t)-1)
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_big5.c b/lib/nbsd_libc/citrus/modules/citrus_big5.c
new file mode 100644 (file)
index 0000000..eda3a71
--- /dev/null
@@ -0,0 +1,512 @@
+/*     $NetBSD: citrus_big5.c,v 1.12 2008/06/14 16:01:07 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2002, 2006 Citrus Project,
+ * 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.
+ */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Borman at Krystal Technologies.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_big5.c,v 1.12 2008/06/14 16:01:07 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/queue.h>
+#include <sys/types.h>
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <wchar.h>
+#include <limits.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_big5.h"
+
+#include "citrus_prop.h"
+
+/* ----------------------------------------------------------------------
+ * private stuffs used by templates
+ */
+
+typedef struct {
+       char ch[2];
+       int chlen;
+} _BIG5State;
+
+typedef struct _BIG5Exclude {
+       TAILQ_ENTRY(_BIG5Exclude) entry;
+       wint_t start, end;
+} _BIG5Exclude;
+
+typedef TAILQ_HEAD(_BIG5ExcludeList, _BIG5Exclude) _BIG5ExcludeList;
+
+typedef struct {
+       int cell[0x100];
+       _BIG5ExcludeList excludes;
+} _BIG5EncodingInfo;
+
+typedef struct {
+       _BIG5EncodingInfo       ei;
+       struct {
+               /* for future multi-locale facility */
+               _BIG5State      s_mblen;
+               _BIG5State      s_mbrlen;
+               _BIG5State      s_mbrtowc;
+               _BIG5State      s_mbtowc;
+               _BIG5State      s_mbsrtowcs;
+               _BIG5State      s_wcrtomb;
+               _BIG5State      s_wcsrtombs;
+               _BIG5State      s_wctomb;
+       } states;
+} _BIG5CTypeInfo;
+
+#define _CEI_TO_EI(_cei_)              (&(_cei_)->ei)
+#define _CEI_TO_STATE(_cei_, _func_)   (_cei_)->states.s_##_func_
+
+#define _FUNCNAME(m)                   _citrus_BIG5_##m
+#define _ENCODING_INFO                 _BIG5EncodingInfo
+#define _CTYPE_INFO                    _BIG5CTypeInfo
+#define _ENCODING_STATE                        _BIG5State
+#define _ENCODING_MB_CUR_MAX(_ei_)     2
+#define _ENCODING_IS_STATE_DEPENDENT   0
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       0
+
+
+static __inline void
+/*ARGSUSED*/
+_citrus_BIG5_init_state(_BIG5EncodingInfo * __restrict ei,
+                       _BIG5State * __restrict s)
+{
+       memset(s, 0, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_BIG5_pack_state(_BIG5EncodingInfo * __restrict ei,
+                       void * __restrict pspriv,
+                       const _BIG5State * __restrict s)
+{
+       memcpy(pspriv, (const void *)s, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_BIG5_unpack_state(_BIG5EncodingInfo * __restrict ei,
+                         _BIG5State * __restrict s,
+                         const void * __restrict pspriv)
+{
+       memcpy((void *)s, pspriv, sizeof(*s));
+}
+
+static __inline int
+_citrus_BIG5_check(_BIG5EncodingInfo *ei, u_int c)
+{
+       _DIAGASSERT(ei != NULL);
+
+       return (ei->cell[c & 0xFF] & 0x1) ? 2 : 1;
+}
+
+static __inline int
+_citrus_BIG5_check2(_BIG5EncodingInfo *ei, u_int c)
+{
+       _DIAGASSERT(ei != NULL);
+
+       return (ei->cell[c & 0xFF] & 0x2) ? 1 : 0;
+}
+
+static __inline int
+_citrus_BIG5_check_excludes(_BIG5EncodingInfo *ei, wint_t c)
+{
+       _BIG5Exclude *exclude;
+
+       _DIAGASSERT(ei != NULL);
+
+       TAILQ_FOREACH(exclude, &ei->excludes, entry) {
+               if (c >= exclude->start && c <= exclude->end)
+                       return EILSEQ;
+       }
+       return 0;
+}
+
+static int
+_citrus_BIG5_fill_rowcol(void ** __restrict ctx, const char * __restrict s,
+       uint64_t start, uint64_t end)
+{
+       _BIG5EncodingInfo *ei;
+       int i;
+       uint64_t n;
+
+       _DIAGASSERT(ctx != NULL && *ctx != NULL);
+
+       if (start > 0xFF || end > 0xFF)
+               return EINVAL;
+       ei = (_BIG5EncodingInfo *)*ctx;
+       i = strcmp("row", s) ? 1 : 0;
+       i = 1 << i;
+       for (n = start; n <= end; ++n)
+               ei->cell[n & 0xFF] |= i;
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_BIG5_fill_excludes(void ** __restrict ctx, const char * __restrict s,
+       uint64_t start, uint64_t end)
+{
+       _BIG5EncodingInfo *ei;
+       _BIG5Exclude *exclude;
+
+       _DIAGASSERT(ctx != NULL && *ctx != NULL);
+
+       if (start > 0xFFFF || end > 0xFFFF)
+               return EINVAL;
+       ei = (_BIG5EncodingInfo *)*ctx;
+       exclude = TAILQ_LAST(&ei->excludes, _BIG5ExcludeList);
+       if (exclude != NULL && (wint_t)start <= exclude->end)
+               return EINVAL;
+       exclude = (void *)malloc(sizeof(*exclude));
+       if (exclude == NULL)
+               return ENOMEM;
+       exclude->start = (wint_t)start;
+       exclude->end = (wint_t)end;
+       TAILQ_INSERT_TAIL(&ei->excludes, exclude, entry);
+
+       return 0;
+}
+
+static const _citrus_prop_hint_t root_hints[] = {
+    _CITRUS_PROP_HINT_NUM("row", &_citrus_BIG5_fill_rowcol),
+    _CITRUS_PROP_HINT_NUM("col", &_citrus_BIG5_fill_rowcol),
+    _CITRUS_PROP_HINT_NUM("excludes", &_citrus_BIG5_fill_excludes),
+    _CITRUS_PROP_HINT_END
+};
+
+static void
+/*ARGSUSED*/
+_citrus_BIG5_encoding_module_uninit(_BIG5EncodingInfo *ei)
+{
+       _BIG5Exclude *exclude;
+
+       _DIAGASSERT(ei != NULL);
+
+       while ((exclude = TAILQ_FIRST(&ei->excludes)) != NULL) {
+               TAILQ_REMOVE(&ei->excludes, exclude, entry);
+               free(exclude);
+       }
+}
+
+static int
+/*ARGSUSED*/
+_citrus_BIG5_encoding_module_init(_BIG5EncodingInfo * __restrict ei,
+                                 const void * __restrict var, size_t lenvar)
+{
+       int err;
+       const char *s;
+
+       _DIAGASSERT(ei != NULL);
+
+       memset((void *)ei, 0, sizeof(*ei));
+       TAILQ_INIT(&ei->excludes);
+
+       if (lenvar > 0 && var != NULL) {
+               s = _bcs_skip_ws_len((const char *)var, &lenvar);
+               if (lenvar > 0 && *s != '\0') {
+                       err = _citrus_prop_parse_variable(
+                           root_hints, (void *)ei, s, lenvar);
+                       if (err == 0)
+                               return 0;
+
+                       _citrus_BIG5_encoding_module_uninit(ei);
+                       memset((void *)ei, 0, sizeof(*ei));
+                       TAILQ_INIT(&ei->excludes);
+               }
+       }
+
+       /* fallback Big5-1984, for backward compatibility. */
+       _citrus_BIG5_fill_rowcol((void **)&ei, "row", 0xA1, 0xFE);
+       _citrus_BIG5_fill_rowcol((void **)&ei, "col", 0x40, 0x7E);
+       _citrus_BIG5_fill_rowcol((void **)&ei, "col", 0xA1, 0xFE);
+
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_BIG5_mbrtowc_priv(_BIG5EncodingInfo * __restrict ei,
+                         wchar_t * __restrict pwc,
+                         const char ** __restrict s, size_t n,
+                         _BIG5State * __restrict psenc,
+                         size_t * __restrict nresult)
+{
+       wchar_t wchar;
+       int c;
+       int chlenbak;
+       const char *s0;
+
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(s != NULL && *s != NULL);
+
+       s0 = *s;
+
+       if (s0 == NULL) {
+               _citrus_BIG5_init_state(ei, psenc);
+               *nresult = 0;
+               return (0);
+       }
+
+       chlenbak = psenc->chlen;
+
+       /* make sure we have the first byte in the buffer */
+       switch (psenc->chlen) {
+       case 0:
+               if (n < 1)
+                       goto restart;
+               psenc->ch[0] = *s0++;
+               psenc->chlen = 1;
+               n--;
+               break;
+       case 1:
+               break;
+       default:
+               /* illegal state */
+               goto ilseq;
+       }
+
+       c = _citrus_BIG5_check(ei, psenc->ch[0] & 0xff);
+       if (c == 0)
+               goto ilseq;
+       while (psenc->chlen < c) {
+               if (n < 1) {
+                       goto restart;
+               }
+               psenc->ch[psenc->chlen] = *s0++;
+               psenc->chlen++;
+               n--;
+       }
+
+       switch (c) {
+       case 1:
+               wchar = psenc->ch[0] & 0xff;
+               break;
+       case 2:
+               if (!_citrus_BIG5_check2(ei, psenc->ch[1] & 0xff))
+                       goto ilseq;
+               wchar = ((psenc->ch[0] & 0xff) << 8) | (psenc->ch[1] & 0xff);
+               break;
+       default:
+               /* illegal state */
+               goto ilseq;
+       }
+
+       if (_citrus_BIG5_check_excludes(ei, (wint_t)wchar) != 0)
+               goto ilseq;
+
+       *s = s0;
+       psenc->chlen = 0;
+       if (pwc)
+               *pwc = wchar;
+       if (!wchar)
+               *nresult = 0;
+       else
+               *nresult = c - chlenbak;
+
+       return (0);
+
+ilseq:
+       psenc->chlen = 0;
+       *nresult = (size_t)-1;
+       return (EILSEQ);
+
+restart:
+       *s = s0;
+       *nresult = (size_t)-2;
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_BIG5_wcrtomb_priv(_BIG5EncodingInfo * __restrict ei,
+                         char * __restrict s,
+                         size_t n, wchar_t wc, _BIG5State * __restrict psenc,
+                         size_t * __restrict nresult)
+{
+       int l, ret;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(s != NULL);
+
+       /* check invalid sequence */
+       if (wc & ~0xffff ||
+           _citrus_BIG5_check_excludes(ei, (wint_t)wc) != 0) {
+               ret = EILSEQ;
+               goto err;
+       }
+
+       if (wc & 0x8000) {
+               if (_citrus_BIG5_check(ei, (wc >> 8) & 0xff) != 2 ||
+                   !_citrus_BIG5_check2(ei, wc & 0xff)) {
+                       ret = EILSEQ;
+                       goto err;
+               }
+               l = 2;
+       } else {
+               if (wc & ~0xff || !_citrus_BIG5_check(ei, wc & 0xff)) {
+                       ret = EILSEQ;
+                       goto err;
+               }
+               l = 1;
+       }
+
+       if (n < l) {
+               /* bound check failure */
+               ret = E2BIG;
+               goto err;
+       }
+
+       if (l == 2) {
+               s[0] = (wc >> 8) & 0xff;
+               s[1] = wc & 0xff;
+       } else
+               s[0] = wc & 0xff;
+
+       *nresult = l;
+
+       return 0;
+
+err:
+       *nresult = (size_t)-1;
+       return ret;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_BIG5_stdenc_wctocs(_BIG5EncodingInfo * __restrict ei,
+                          _csid_t * __restrict csid,
+                          _index_t * __restrict idx, wchar_t wc)
+{
+
+       _DIAGASSERT(csid != NULL && idx != NULL);
+
+       *csid = (wc < 0x100) ? 0 : 1;
+       *idx = (_index_t)wc;
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_BIG5_stdenc_cstowc(_BIG5EncodingInfo * __restrict ei,
+                          wchar_t * __restrict wc,
+                          _csid_t csid, _index_t idx)
+{
+       _DIAGASSERT(wc != NULL);
+
+       switch (csid) {
+       case 0:
+       case 1:
+               *wc = (wchar_t)idx;
+               break;
+       default:
+               return EILSEQ;
+       }
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_BIG5_stdenc_get_state_desc_generic(_BIG5EncodingInfo * __restrict ei,
+                                          _BIG5State * __restrict psenc,
+                                          int * __restrict rstate)
+{
+
+       if (psenc->chlen == 0)
+               *rstate = _STDENC_SDGEN_INITIAL;
+       else
+               *rstate = _STDENC_SDGEN_INCOMPLETE_CHAR;
+
+       return 0;
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(BIG5);
+_CITRUS_CTYPE_DEF_OPS(BIG5);
+
+#include "citrus_ctype_template.h"
+
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(BIG5);
+_CITRUS_STDENC_DEF_OPS(BIG5);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_big5.h b/lib/nbsd_libc/citrus/modules/citrus_big5.h
new file mode 100644 (file)
index 0000000..60a0f59
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: citrus_big5.h,v 1.2 2003/06/25 09:51:41 tshiozak Exp $ */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_BIG5_H_
+#define _CITRUS_BIG5_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(BIG5);
+_CITRUS_STDENC_GETOPS_FUNC(BIG5);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_dechanyu.c b/lib/nbsd_libc/citrus/modules/citrus_dechanyu.c
new file mode 100644 (file)
index 0000000..09c40f9
--- /dev/null
@@ -0,0 +1,441 @@
+/* $NetBSD: citrus_dechanyu.c,v 1.3 2008/06/14 16:01:07 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2007 Citrus Project,
+ * 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.
+ */
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_dechanyu.c,v 1.3 2008/06/14 16:01:07 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <wchar.h>
+#include <limits.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_dechanyu.h"
+
+/* ----------------------------------------------------------------------
+ * private stuffs used by templates
+ */
+
+typedef struct {
+       int chlen;
+       char ch[4];
+} _DECHanyuState;
+
+typedef struct {
+       int dummy;
+} _DECHanyuEncodingInfo;
+
+typedef struct {
+       _DECHanyuEncodingInfo   ei;
+       struct {
+               /* for future multi-locale facility */
+               _DECHanyuState  s_mblen;
+               _DECHanyuState  s_mbrlen;
+               _DECHanyuState  s_mbrtowc;
+               _DECHanyuState  s_mbtowc;
+               _DECHanyuState  s_mbsrtowcs;
+               _DECHanyuState  s_wcrtomb;
+               _DECHanyuState  s_wcsrtombs;
+               _DECHanyuState  s_wctomb;
+       } states;
+} _DECHanyuCTypeInfo;
+
+#define _CEI_TO_EI(_cei_)              (&(_cei_)->ei)
+#define _CEI_TO_STATE(_cei_, _func_)   (_cei_)->states.__CONCAT(s_,_func_)
+
+#define _FUNCNAME(m)                   __CONCAT(_citrus_DECHanyu_,m)
+#define _ENCODING_INFO                 _DECHanyuEncodingInfo
+#define _CTYPE_INFO                    _DECHanyuCTypeInfo
+#define _ENCODING_STATE                        _DECHanyuState
+#define _ENCODING_MB_CUR_MAX(_ei_)             4
+#define _ENCODING_IS_STATE_DEPENDENT           0
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       0
+
+static __inline void
+/*ARGSUSED*/
+_citrus_DECHanyu_init_state(_DECHanyuEncodingInfo * __restrict ei,
+       _DECHanyuState * __restrict psenc)
+{
+       /* ei may be null */
+       _DIAGASSERT(psenc != NULL);
+
+       psenc->chlen = 0;
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_DECHanyu_pack_state(_DECHanyuEncodingInfo * __restrict ei,
+       void * __restrict pspriv,
+       const _DECHanyuState * __restrict psenc)
+{
+       /* ei may be null */
+       _DIAGASSERT(pspriv != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       memcpy(pspriv, (const void *)psenc, sizeof(*psenc));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_DECHanyu_unpack_state(_DECHanyuEncodingInfo * __restrict ei,
+       _DECHanyuState * __restrict psenc,
+       const void * __restrict pspriv)
+{
+       /* ei may be null */
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(pspriv != NULL);
+
+       memcpy((void *)psenc, pspriv, sizeof(*psenc));
+}
+
+static void
+/*ARGSUSED*/
+_citrus_DECHanyu_encoding_module_uninit(_DECHanyuEncodingInfo *ei)
+{
+       /* ei may be null */
+}
+
+static int
+/*ARGSUSED*/
+_citrus_DECHanyu_encoding_module_init(_DECHanyuEncodingInfo * __restrict ei,
+       const void * __restrict var, size_t lenvar)
+{
+       /* ei may be null */
+       return 0;
+}
+
+static __inline int
+is_singlebyte(int c)
+{
+       return c <= 0x7F;
+}
+
+static __inline int
+is_leadbyte(int c)
+{
+       return c >= 0xA1 && c <= 0xFE;
+}
+
+static __inline int
+is_trailbyte(int c)
+{
+       c &= ~0x80;
+       return c >= 0x21 && c <= 0x7E;
+}
+
+static __inline int
+is_hanyu1(int c)
+{
+       return c == 0xC2;
+}
+
+static __inline int
+is_hanyu2(int c)
+{
+       return c == 0xCB;
+}
+
+#define HANYUBIT       0xC2CB0000
+
+static __inline int
+is_94charset(int c)
+{
+       return c >= 0x21 && c <= 0x7E;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_DECHanyu_mbrtowc_priv(_DECHanyuEncodingInfo * __restrict ei,
+       wchar_t * __restrict pwc, const char ** __restrict s, size_t n,
+       _DECHanyuState * __restrict psenc, size_t * __restrict nresult)
+{
+       const char *s0;
+       int ch, i;
+       wchar_t wc;
+
+       /* ei may be unused */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (*s == NULL) {
+               _citrus_DECHanyu_init_state(ei, psenc);
+               *nresult = _ENCODING_IS_STATE_DEPENDENT;
+               return 0;
+       } 
+       s0 = *s;
+
+       wc = (wchar_t)0;
+       switch (psenc->chlen) {
+       case 0:
+               if (n-- < 1)
+                       goto restart;
+               ch = *s0++ & 0xFF;
+               if (is_singlebyte(ch) != 0) {
+                       if (pwc != NULL)
+                               *pwc = (wchar_t)ch;
+                       *nresult = (size_t)((ch == 0) ? 0 : 1);
+                       *s = s0;
+                       return 0;
+               }
+               if (is_leadbyte(ch) == 0)
+                       goto ilseq;
+               psenc->ch[psenc->chlen++] = ch;
+               break;
+       case 1:
+               ch = psenc->ch[0] & 0xFF;
+               if (is_leadbyte(ch) == 0)
+                       return EINVAL;
+               break;
+       case 2: case 3:
+               ch = psenc->ch[0] & 0xFF;
+               if (is_hanyu1(ch) != 0) {
+                       ch = psenc->ch[1] & 0xFF;
+                       if (is_hanyu2(ch) != 0) {
+                               wc |= (wchar_t)HANYUBIT;
+                               break;
+                       }
+               }
+       /*FALLTHROUGH*/
+       default:
+               return EINVAL;
+       }
+
+       switch (psenc->chlen) {
+       case 1:
+               if (is_hanyu1(ch) != 0) {
+                       if (n-- < 1)
+                               goto restart;
+                       ch = *s0++ & 0xFF;
+                       if (is_hanyu2(ch) == 0)
+                               goto ilseq;
+                       psenc->ch[psenc->chlen++] = ch;
+                       wc |= (wchar_t)HANYUBIT;
+                       if (n-- < 1)
+                               goto restart;
+                       ch = *s0++ & 0xFF;
+                       if (is_leadbyte(ch) == 0)
+                               goto ilseq;
+                       psenc->ch[psenc->chlen++] = ch;
+               }
+               break;
+       case 2:
+               if (n-- < 1)
+                       goto restart;
+               ch = *s0++ & 0xFF;
+               if (is_leadbyte(ch) == 0)
+                       goto ilseq;
+               psenc->ch[psenc->chlen++] = ch;
+               break;
+       case 3:
+               ch = psenc->ch[2] & 0xFF;
+               if (is_leadbyte(ch) == 0)
+                       return EINVAL;
+       }
+       if (n-- < 1)
+               goto restart;
+       wc |= (wchar_t)(ch << 8);
+       ch = *s0++ & 0xFF;
+       if (is_trailbyte(ch) == 0)
+               goto ilseq;
+       wc |= (wchar_t)ch;
+       if (pwc != NULL)
+               *pwc = wc;
+       *nresult = (size_t)(s0 - *s);
+       *s = s0;
+       psenc->chlen = 0;
+
+       return 0;
+
+restart:
+       *nresult = (size_t)-2;
+       *s = s0;
+       return 0;
+
+ilseq:
+       *nresult = (size_t)-1;
+       return EILSEQ;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_DECHanyu_wcrtomb_priv(_DECHanyuEncodingInfo * __restrict ei,
+       char * __restrict s, size_t n, wchar_t wc,
+       _DECHanyuState * __restrict psenc, size_t * __restrict nresult)
+{
+       int ch;
+
+       /* ei may be unused */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (psenc->chlen != 0)
+               return EINVAL;
+
+       /* XXX: assume wchar_t as int */
+       if ((uint32_t)wc <= 0x7F) {
+               ch = wc & 0xFF;
+       } else {
+               if ((uint32_t)wc > 0xFFFF) {
+                       if ((wc & ~0xFFFF) != HANYUBIT)
+                               goto ilseq;
+                       psenc->ch[psenc->chlen++] = (wc >> 24) & 0xFF;
+                       psenc->ch[psenc->chlen++] = (wc >> 16) & 0xFF;
+                       wc &= 0xFFFF;
+               }
+               ch = (wc >> 8) & 0xFF;
+               if (!is_leadbyte(ch))
+                       goto ilseq;
+               psenc->ch[psenc->chlen++] = ch;
+               ch = wc & 0xFF;
+               if (is_trailbyte(ch) == 0)
+                       goto ilseq;
+       }
+       psenc->ch[psenc->chlen++] = ch;
+       if (n < psenc->chlen) {
+               *nresult = (size_t)-1;
+               return E2BIG;
+       }
+       memcpy(s, psenc->ch, psenc->chlen);
+       *nresult = psenc->chlen;
+       psenc->chlen = 0;
+
+       return 0;
+
+ilseq:
+       *nresult = (size_t)-1;
+       return EILSEQ;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_DECHanyu_stdenc_wctocs(_DECHanyuEncodingInfo * __restrict ei,
+       _csid_t * __restrict csid, _index_t * __restrict idx, wchar_t wc)
+{
+       int plane;
+       wchar_t mask;
+
+       /* ei may be unused */
+       _DIAGASSERT(csid != NULL);
+       _DIAGASSERT(idx != NULL);
+
+       plane = 0;
+       mask = 0x7F;
+       /* XXX: assume wchar_t as int */
+       if ((uint32_t)wc > 0x7F) {
+               if ((uint32_t)wc > 0xFFFF) {
+                       if ((wc & ~0xFFFF) != HANYUBIT)
+                               return EILSEQ;
+                       plane += 2;
+               }
+               if (is_leadbyte((wc >> 8) & 0xFF) == 0 ||
+                   is_trailbyte(wc & 0xFF) == 0)
+                       return EILSEQ;
+               plane += (wc & 0x80) ? 1 : 2;
+               mask |= 0x7F00;
+       }
+       *csid = plane;
+       *idx = (_index_t)(wc & mask);
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_DECHanyu_stdenc_cstowc(_DECHanyuEncodingInfo * __restrict ei,
+       wchar_t * __restrict wc, _csid_t csid, _index_t idx)
+{
+       /* ei may be unused */
+       _DIAGASSERT(wc != NULL);
+
+       if (csid == 0) {
+               if (idx > 0x7F)
+                       return EILSEQ;
+       } else if (csid <= 4) {
+               if (is_94charset(idx >> 8) == 0)
+                       return EILSEQ;
+               if (is_94charset(idx & 0xFF) == 0)
+                       return EILSEQ;
+               if (csid % 2)
+                       idx |= 0x80;
+               idx |= 0x8000;
+               if (csid > 2)
+                       idx |= HANYUBIT;
+       } else
+               return EILSEQ;
+       *wc = (wchar_t)idx;
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_DECHanyu_stdenc_get_state_desc_generic(
+       _DECHanyuEncodingInfo * __restrict ei,
+       _DECHanyuState * __restrict psenc, int * __restrict rstate)
+{
+       /* ei may be unused */
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(rstate != NULL);
+
+       *rstate = (psenc->chlen == 0)
+           ? _STDENC_SDGEN_INITIAL
+           : _STDENC_SDGEN_INCOMPLETE_CHAR;
+       return 0;
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(DECHanyu);
+_CITRUS_CTYPE_DEF_OPS(DECHanyu);
+
+#include "citrus_ctype_template.h"
+
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(DECHanyu);
+_CITRUS_STDENC_DEF_OPS(DECHanyu);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_dechanyu.h b/lib/nbsd_libc/citrus/modules/citrus_dechanyu.h
new file mode 100644 (file)
index 0000000..ed774bc
--- /dev/null
@@ -0,0 +1,37 @@
+/* $NetBSD: citrus_dechanyu.h,v 1.1 2007/04/01 18:52:32 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2006 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_DECHANYU_H_
+#define _CITRUS_DECHANYU_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(DECHanyu);
+_CITRUS_STDENC_GETOPS_FUNC(DECHanyu);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_euc.c b/lib/nbsd_libc/citrus/modules/citrus_euc.c
new file mode 100644 (file)
index 0000000..32292f8
--- /dev/null
@@ -0,0 +1,435 @@
+/*     $NetBSD: citrus_euc.c,v 1.14 2009/01/11 02:46:24 christos Exp $ */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Borman at Krystal Technologies.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_euc.c,v 1.14 2009/01/11 02:46:24 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <wchar.h>
+#include <sys/types.h>
+#include <limits.h>
+
+#include "citrus_namespace.h"
+#include "citrus_bcs.h"
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_euc.h"
+
+
+/* ----------------------------------------------------------------------
+ * private stuffs used by templates
+ */
+
+typedef struct {
+       char ch[3];
+       int chlen;
+} _EUCState;
+
+typedef struct {
+       unsigned        count[4];
+       wchar_t         bits[4];
+       wchar_t         mask;
+       unsigned        mb_cur_max;
+} _EUCEncodingInfo;
+
+typedef struct {
+       _EUCEncodingInfo        ei;
+       struct {
+               /* for future multi-locale facility */
+               _EUCState       s_mblen;
+               _EUCState       s_mbrlen;
+               _EUCState       s_mbrtowc;
+               _EUCState       s_mbtowc;
+               _EUCState       s_mbsrtowcs;
+               _EUCState       s_wcrtomb;
+               _EUCState       s_wcsrtombs;
+               _EUCState       s_wctomb;
+       } states;
+} _EUCCTypeInfo;
+
+#define        _SS2    0x008e
+#define        _SS3    0x008f
+
+#define _CEI_TO_EI(_cei_)              (&(_cei_)->ei)
+#define _CEI_TO_STATE(_cei_, _func_)   (_cei_)->states.s_##_func_
+
+#define _FUNCNAME(m)                   _citrus_EUC_##m
+#define _ENCODING_INFO                 _EUCEncodingInfo
+#define _CTYPE_INFO                    _EUCCTypeInfo
+#define _ENCODING_STATE                        _EUCState
+#define _ENCODING_MB_CUR_MAX(_ei_)     (_ei_)->mb_cur_max
+#define _ENCODING_IS_STATE_DEPENDENT   0
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       0
+
+
+static __inline int
+_citrus_EUC_cs(unsigned int c)
+{
+       c &= 0xff;
+
+       return ((c & 0x80) ? c == _SS3 ? 3 : c == _SS2 ? 2 : 1 : 0);
+}
+
+static __inline int
+_citrus_EUC_parse_variable(_EUCEncodingInfo *ei,
+                          const void *var, size_t lenvar)
+{
+       const char *v, *e;
+       int x;
+
+       /* parse variable string */
+       if (!var)
+               return (EFTYPE);
+
+       v = (const char *) var;
+
+       while (*v == ' ' || *v == '\t')
+               ++v;
+
+       ei->mb_cur_max = 1;
+       for (x = 0; x < 4; ++x) {
+               ei->count[x] = (int)_bcs_strtol(v, (char **)&e, 0);
+               if (v == e || !(v = e) || ei->count[x]<1 || ei->count[x]>4) {
+                       return (EFTYPE);
+               }
+               if (ei->mb_cur_max < ei->count[x])
+                       ei->mb_cur_max = ei->count[x];
+               while (*v == ' ' || *v == '\t')
+                       ++v;
+               ei->bits[x] = (int)_bcs_strtol(v, (char **)&e, 0);
+               if (v == e || !(v = e)) {
+                       return (EFTYPE);
+               }
+               while (*v == ' ' || *v == '\t')
+                       ++v;
+       }
+       ei->mask = (int)_bcs_strtol(v, (char **)&e, 0);
+       if (v == e || !(v = e)) {
+               return (EFTYPE);
+       }
+
+       return 0;
+}
+
+
+static __inline void
+/*ARGSUSED*/
+_citrus_EUC_init_state(_EUCEncodingInfo *ei, _EUCState *s)
+{
+       memset(s, 0, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_EUC_pack_state(_EUCEncodingInfo *ei, void *pspriv, const _EUCState *s)
+{
+       memcpy(pspriv, (const void *)s, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_EUC_unpack_state(_EUCEncodingInfo *ei, _EUCState *s,
+                        const void *pspriv)
+{
+       memcpy((void *)s, pspriv, sizeof(*s));
+}
+
+static int
+_citrus_EUC_mbrtowc_priv(_EUCEncodingInfo *ei, wchar_t *pwc, const char **s,
+                        size_t n, _EUCState *psenc, size_t *nresult)
+{
+       wchar_t wchar;
+       int c, cs, len;
+       int chlenbak;
+       const char *s0, *s1 = NULL;
+
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(s != NULL);
+
+       s0 = *s;
+
+       if (s0 == NULL) {
+               _citrus_EUC_init_state(ei, psenc);
+               *nresult = 0; /* state independent */
+               return (0);
+       }
+
+       chlenbak = psenc->chlen;
+
+       /* make sure we have the first byte in the buffer */
+       switch (psenc->chlen) {
+       case 0:
+               if (n < 1)
+                       goto restart;
+               psenc->ch[0] = *s0++;
+               psenc->chlen = 1;
+               n--;
+               break;
+       case 1:
+       case 2:
+               break;
+       default:
+               /* illgeal state */
+               goto encoding_error;
+       }
+
+       c = ei->count[cs = _citrus_EUC_cs(psenc->ch[0] & 0xff)];
+       if (c == 0)
+               goto encoding_error;
+       while (psenc->chlen < c) {
+               if (n < 1)
+                       goto restart;
+               psenc->ch[psenc->chlen] = *s0++;
+               psenc->chlen++;
+               n--;
+       }
+       *s = s0;
+
+       switch (cs) {
+       case 3:
+       case 2:
+               /* skip SS2/SS3 */
+               len = c - 1;
+               s1 = &psenc->ch[1];
+               break;
+       case 1:
+       case 0:
+               len = c;
+               s1 = &psenc->ch[0];
+               break;
+       default:
+               goto encoding_error;
+       }
+       wchar = 0;
+       while (len-- > 0)
+               wchar = (wchar << 8) | (*s1++ & 0xff);
+       wchar = (wchar & ~ei->mask) | ei->bits[cs];
+
+       psenc->chlen = 0;
+       if (pwc)
+               *pwc = wchar;
+
+       if (!wchar) {
+               *nresult = 0;
+       } else {
+               *nresult = (size_t)(c - chlenbak);
+       }
+
+       return 0;
+
+encoding_error:
+       psenc->chlen = 0;
+       *nresult = (size_t)-1;
+       return (EILSEQ);
+
+restart:
+       *nresult = (size_t)-2;
+       *s = s0;
+       return (0);
+}
+
+static int
+_citrus_EUC_wcrtomb_priv(_EUCEncodingInfo *ei, char *s, size_t n, wchar_t wc,
+                        _EUCState *psenc, size_t *nresult)
+{
+       wchar_t m, nm;
+       int cs, i, ret;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(s != NULL);
+
+       m = wc & ei->mask;
+       nm = wc & ~m;
+
+       for (cs = 0;
+            cs < sizeof(ei->count)/sizeof(ei->count[0]);
+            cs++) {
+               if (m == ei->bits[cs])
+                       break;
+       }
+       /* fallback case - not sure if it is necessary */
+       if (cs == sizeof(ei->count)/sizeof(ei->count[0]))
+               cs = 1;
+
+       i = ei->count[cs];
+       if (n < i) {
+               ret = E2BIG;
+               goto err;
+       }
+       m = (cs) ? 0x80 : 0x00;
+       switch (cs) {
+       case 2:
+               *s++ = _SS2;
+               i--;
+               break;
+       case 3:
+               *s++ = _SS3;
+               i--;
+               break;
+       }
+
+       while (i-- > 0)
+               *s++ = ((nm >> (i << 3)) & 0xff) | m;
+
+       *nresult = (size_t)ei->count[cs];
+       return 0;
+
+err:
+       *nresult = (size_t)-1;
+       return ret;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_EUC_stdenc_wctocs(_EUCEncodingInfo * __restrict ei,
+                         _csid_t * __restrict csid,
+                         _index_t * __restrict idx, wchar_t wc)
+{
+       wchar_t m, nm;
+
+       _DIAGASSERT(ei != NULL && csid != NULL && idx != NULL);
+
+       m = wc & ei->mask;
+       nm = wc & ~m;
+
+       *csid = (_citrus_csid_t)m;
+       *idx  = (_citrus_index_t)nm;
+
+       return (0);
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_EUC_stdenc_cstowc(_EUCEncodingInfo * __restrict ei,
+                         wchar_t * __restrict wc,
+                         _csid_t csid, _index_t idx)
+{
+
+       _DIAGASSERT(ei != NULL && wc != NULL);
+
+       if ((csid & ~ei->mask) != 0 || (idx & ei->mask) != 0)
+               return (EINVAL);
+
+       *wc = (wchar_t)csid | (wchar_t)idx;
+
+       return (0);
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_EUC_stdenc_get_state_desc_generic(_EUCEncodingInfo * __restrict ei,
+                                         _EUCState * __restrict psenc,
+                                         int * __restrict rstate)
+{
+
+       if (psenc->chlen == 0)
+               *rstate = _STDENC_SDGEN_INITIAL;
+       else
+               *rstate = _STDENC_SDGEN_INCOMPLETE_CHAR;
+
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_EUC_encoding_module_init(_EUCEncodingInfo * __restrict ei,
+                                const void * __restrict var, size_t lenvar)
+{
+
+       _DIAGASSERT(ei != NULL);
+
+       return (_citrus_EUC_parse_variable(ei, var, lenvar));
+}
+
+static void
+/*ARGSUSED*/
+_citrus_EUC_encoding_module_uninit(_EUCEncodingInfo * __restrict ei)
+{
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(EUC);
+_CITRUS_CTYPE_DEF_OPS(EUC);
+
+#include "citrus_ctype_template.h"
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(EUC);
+_CITRUS_STDENC_DEF_OPS(EUC);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_euc.h b/lib/nbsd_libc/citrus/modules/citrus_euc.h
new file mode 100644 (file)
index 0000000..9f67756
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: citrus_euc.h,v 1.2 2003/06/25 09:51:42 tshiozak Exp $  */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_EUC_H_
+#define _CITRUS_EUC_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(EUC);
+_CITRUS_STDENC_GETOPS_FUNC(EUC);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_euctw.c b/lib/nbsd_libc/citrus/modules/citrus_euctw.c
new file mode 100644 (file)
index 0000000..7ab35e8
--- /dev/null
@@ -0,0 +1,428 @@
+/*     $NetBSD: citrus_euctw.c,v 1.11 2008/06/14 16:01:07 tnozaki Exp $        */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     $Citrus: xpg4dl/FreeBSD/lib/libc/locale/euctw.c,v 1.13 2001/06/21 01:51:44 yamt Exp $
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_euctw.c,v 1.11 2008/06/14 16:01:07 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <wchar.h>
+#include <sys/types.h>
+#include <limits.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_euctw.h"
+
+
+/* ----------------------------------------------------------------------
+ * private stuffs used by templates
+ */
+
+typedef struct {
+       char ch[4];
+       int chlen;
+} _EUCTWState;
+
+typedef struct {
+       int dummy;
+} _EUCTWEncodingInfo;
+typedef struct {
+       _EUCTWEncodingInfo      ei;
+       struct {
+               /* for future multi-locale facility */
+               _EUCTWState     s_mblen;
+               _EUCTWState     s_mbrlen;
+               _EUCTWState     s_mbrtowc;
+               _EUCTWState     s_mbtowc;
+               _EUCTWState     s_mbsrtowcs;
+               _EUCTWState     s_wcrtomb;
+               _EUCTWState     s_wcsrtombs;
+               _EUCTWState     s_wctomb;
+       } states;
+} _EUCTWCTypeInfo;
+
+#define        _SS2    0x008e
+#define        _SS3    0x008f
+
+#define _CEI_TO_EI(_cei_)              (&(_cei_)->ei)
+#define _CEI_TO_STATE(_cei_, _func_)   (_cei_)->states.s_##_func_
+
+#define _FUNCNAME(m)                   _citrus_EUCTW_##m
+#define _ENCODING_INFO                 _EUCTWEncodingInfo
+#define _CTYPE_INFO                    _EUCTWCTypeInfo
+#define _ENCODING_STATE                        _EUCTWState
+#define _ENCODING_MB_CUR_MAX(_ei_)     4
+#define _ENCODING_IS_STATE_DEPENDENT   0
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       0
+
+static __inline int
+_citrus_EUCTW_cs(u_int c)
+{
+       c &= 0xff;
+
+       return ((c & 0x80) ? (c == _SS2 ? 2 : 1) : 0);
+}
+
+static __inline int
+_citrus_EUCTW_count(int cs)
+{
+       switch (cs) {
+       case 0:
+               return 1;
+       case 1:
+               return 2;
+       case 2:
+               return 4;
+       case 3:
+               abort();
+               /*NOTREACHED*/
+       }
+       return 0;
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_EUCTW_init_state(_EUCTWEncodingInfo * __restrict ei,
+                        _EUCTWState * __restrict s)
+{
+       memset(s, 0, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_EUCTW_pack_state(_EUCTWEncodingInfo * __restrict ei,
+                        void * __restrict pspriv,
+                        const _EUCTWState * __restrict s)
+{
+       memcpy(pspriv, (const void *)s, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_EUCTW_unpack_state(_EUCTWEncodingInfo * __restrict ei,
+                          _EUCTWState * __restrict s,
+                          const void * __restrict pspriv)
+{
+       memcpy((void *)s, pspriv, sizeof(*s));
+}
+
+static int
+/*ARGSUSED*/
+_citrus_EUCTW_encoding_module_init(_EUCTWEncodingInfo * __restrict ei,
+                                  const void * __restrict var, size_t lenvar)
+{
+
+       _DIAGASSERT(ei != NULL);
+
+       memset((void *)ei, 0, sizeof(*ei));
+
+       return 0;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_EUCTW_encoding_module_uninit(_EUCTWEncodingInfo *ei)
+{
+}
+
+static int
+_citrus_EUCTW_mbrtowc_priv(_EUCTWEncodingInfo * __restrict ei,
+                          wchar_t * __restrict pwc,
+                          const char ** __restrict s,
+                          size_t n, _EUCTWState * __restrict psenc,
+                          size_t * __restrict nresult)
+{
+       wchar_t wchar;
+       int c, cs;
+       int chlenbak;
+       const char *s0;
+
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(s != NULL);
+
+       s0 = *s;
+
+       if (s0 == NULL) {
+               _citrus_EUCTW_init_state(ei, psenc);
+               *nresult = 0; /* state independent */
+               return (0);
+       }
+
+       chlenbak = psenc->chlen;
+
+       /* make sure we have the first byte in the buffer */
+       switch (psenc->chlen) {
+       case 0:
+               if (n < 1)
+                       goto restart;
+               psenc->ch[0] = *s0++;
+               psenc->chlen = 1;
+               n--;
+               break;
+       case 1:
+       case 2:
+               break;
+       default:
+               /* illgeal state */
+               goto ilseq;
+       }
+
+       c = _citrus_EUCTW_count(cs = _citrus_EUCTW_cs(psenc->ch[0] & 0xff));
+       if (c == 0)
+               goto ilseq;
+       while (psenc->chlen < c) {
+               if (n < 1)
+                       goto ilseq;
+               psenc->ch[psenc->chlen] = *s0++;
+               psenc->chlen++;
+               n--;
+       }
+
+       wchar = 0;
+       switch (cs) {
+       case 0:
+               if (psenc->ch[0] & 0x80)
+                       goto ilseq;
+               wchar = psenc->ch[0] & 0xff;
+               break;
+       case 1:
+               if (!(psenc->ch[0] & 0x80) || !(psenc->ch[1] & 0x80))
+                       goto ilseq;
+               wchar = ((psenc->ch[0] & 0xff) << 8) | (psenc->ch[1] & 0xff);
+               wchar |= 'G' << 24;
+               break;
+       case 2:
+               if ((u_char)psenc->ch[1] < 0xa1 || 0xa7 < (u_char)psenc->ch[1])
+                       goto ilseq;
+               if (!(psenc->ch[2] & 0x80) || !(psenc->ch[3] & 0x80))
+                       goto ilseq;
+               wchar = ((psenc->ch[2] & 0xff) << 8) | (psenc->ch[3] & 0xff);
+               wchar |= ('G' + psenc->ch[1] - 0xa1) << 24;
+               break;
+       default:
+               goto ilseq;
+       }
+
+       *s = s0;
+       psenc->chlen = 0;
+
+       if (pwc)
+               *pwc = wchar;
+
+       if (!wchar)
+               *nresult = 0;
+       else
+               *nresult = c - chlenbak;
+
+       return (0);
+
+ilseq:
+       psenc->chlen = 0;
+       *nresult = (size_t)-1;
+       return (EILSEQ);
+
+restart:
+       *s = s0;
+       *nresult = (size_t)-1;
+       return (0);
+}
+
+static int
+_citrus_EUCTW_wcrtomb_priv(_EUCTWEncodingInfo * __restrict ei,
+                          char * __restrict s, size_t n, wchar_t wc,
+                          _EUCTWState * __restrict psenc,
+                          size_t * __restrict nresult)
+{
+       wchar_t cs = wc & 0x7f000080;
+       wchar_t v;
+       int i, len, clen, ret;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(s != NULL);
+
+       clen = 1;
+       if (wc & 0x00007f00)
+               clen = 2;
+       if ((wc & 0x007f0000) && !(wc & 0x00800000))
+               clen = 3;
+
+       if (clen == 1 && cs == 0x00000000) {
+               /* ASCII */
+               len = 1;
+               if (n < len) {
+                       ret = E2BIG;
+                       goto err;
+               }
+               v = wc & 0x0000007f;
+       } else if (clen == 2 && cs == ('G' << 24)) {
+               /* CNS-11643-1 */
+               len = 2;
+               if (n < len) {
+                       ret = E2BIG;
+                       goto err;
+               }
+               v = wc & 0x00007f7f;
+               v |= 0x00008080;
+       } else if (clen == 2 && 'H' <= (cs >> 24) && (cs >> 24) <= 'M') {
+               /* CNS-11643-[2-7] */
+               len = 4;
+               if (n < len) {
+                       ret = E2BIG;
+                       goto err;
+               }
+               *s++ = _SS2;
+               *s++ = (cs >> 24) - 'H' + 0xa2;
+               v = wc & 0x00007f7f;
+               v |= 0x00008080;
+       } else {
+               ret = EILSEQ;
+               goto err;
+       }
+
+       i = clen;
+       while (i-- > 0)
+               *s++ = (v >> (i << 3)) & 0xff;
+
+       *nresult = len;
+       return 0;
+
+err:
+       *nresult = (size_t)-1;
+       return ret;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_EUCTW_stdenc_wctocs(_EUCTWEncodingInfo * __restrict ei,
+                           _csid_t * __restrict csid,
+                           _index_t * __restrict idx, wchar_t wc)
+{
+
+       _DIAGASSERT(ei != NULL && csid != NULL && idx != NULL);
+
+       *csid = (_csid_t)(wc >> 24) & 0xFF;
+       *idx  = (_index_t)(wc & 0x7F7F);
+
+       return (0);
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_EUCTW_stdenc_cstowc(_EUCTWEncodingInfo * __restrict ei,
+                           wchar_t * __restrict wc,
+                           _csid_t csid, _index_t idx)
+{
+
+       _DIAGASSERT(ei != NULL && wc != NULL);
+
+       if (csid==0) {
+               if ((idx & ~0x7F) != 0)
+                       return (EINVAL);
+               *wc = (wchar_t)idx;
+       } else {
+               if (csid < 'G' || csid > 'M' || (idx & ~0x7F7F) != 0)
+                       return (EINVAL);
+               *wc = (wchar_t)idx | ((wchar_t)csid<<24);
+       }
+
+       return (0);
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_EUCTW_stdenc_get_state_desc_generic(_EUCTWEncodingInfo * __restrict ei,
+                                           _EUCTWState * __restrict psenc,
+                                           int * __restrict rstate)
+{
+
+       if (psenc->chlen == 0)
+               *rstate = _STDENC_SDGEN_INITIAL;
+       else
+               *rstate = _STDENC_SDGEN_INCOMPLETE_CHAR;
+
+       return 0;
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(EUCTW);
+_CITRUS_CTYPE_DEF_OPS(EUCTW);
+
+#include "citrus_ctype_template.h"
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(EUCTW);
+_CITRUS_STDENC_DEF_OPS(EUCTW);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_euctw.h b/lib/nbsd_libc/citrus/modules/citrus_euctw.h
new file mode 100644 (file)
index 0000000..dc01412
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: citrus_euctw.h,v 1.2 2003/06/25 09:51:42 tshiozak Exp $        */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_EUCTW_H_
+#define _CITRUS_EUCTW_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(EUCTW);
+_CITRUS_STDENC_GETOPS_FUNC(EUCTW);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_gbk2k.c b/lib/nbsd_libc/citrus/modules/citrus_gbk2k.c
new file mode 100644 (file)
index 0000000..77d7dd2
--- /dev/null
@@ -0,0 +1,474 @@
+/* $NetBSD: citrus_gbk2k.c,v 1.7 2008/06/14 16:01:07 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_gbk2k.c,v 1.7 2008/06/14 16:01:07 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <wchar.h>
+#include <sys/types.h>
+#include <limits.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_gbk2k.h"
+
+
+/* ----------------------------------------------------------------------
+ * private stuffs used by templates
+ */
+
+typedef struct _GBK2KState {
+       char ch[4];
+       int chlen;
+} _GBK2KState;
+
+typedef struct {
+       int mb_cur_max;
+} _GBK2KEncodingInfo;
+
+typedef struct {
+       _GBK2KEncodingInfo      ei;
+       struct {
+               /* for future multi-locale facility */
+               _GBK2KState     s_mblen;
+               _GBK2KState     s_mbrlen;
+               _GBK2KState     s_mbrtowc;
+               _GBK2KState     s_mbtowc;
+               _GBK2KState     s_mbsrtowcs;
+               _GBK2KState     s_wcrtomb;
+               _GBK2KState     s_wcsrtombs;
+               _GBK2KState     s_wctomb;
+       } states;
+} _GBK2KCTypeInfo;
+
+#define _CEI_TO_EI(_cei_)              (&(_cei_)->ei)
+#define _CEI_TO_STATE(_cei_, _func_)   (_cei_)->states.s_##_func_
+
+#define _FUNCNAME(m)                   _citrus_GBK2K_##m
+#define _ENCODING_INFO                 _GBK2KEncodingInfo
+#define _CTYPE_INFO                    _GBK2KCTypeInfo
+#define _ENCODING_STATE                        _GBK2KState
+#define _ENCODING_MB_CUR_MAX(_ei_)     (_ei_)->mb_cur_max
+#define _ENCODING_IS_STATE_DEPENDENT   0
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       0
+
+static __inline void
+/*ARGSUSED*/
+_citrus_GBK2K_init_state(_GBK2KEncodingInfo * __restrict ei,
+                        _GBK2KState * __restrict s)
+{
+       memset(s, 0, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_GBK2K_pack_state(_GBK2KEncodingInfo * __restrict ei,
+                        void * __restrict pspriv,
+                        const _GBK2KState * __restrict s)
+{
+       memcpy(pspriv, (const void *)s, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_GBK2K_unpack_state(_GBK2KEncodingInfo * __restrict ei,
+                          _GBK2KState * __restrict s,
+                          const void * __restrict pspriv)
+{
+       memcpy((void *)s, pspriv, sizeof(*s));
+}
+
+static  __inline int
+_mb_singlebyte(int c)
+{
+       c &= 0xff;
+       return (c <= 0x7f);
+}
+
+static __inline int
+_mb_leadbyte(int c)
+{
+       c &= 0xff;
+       return (0x81 <= c && c <= 0xfe);
+}
+
+static __inline int
+_mb_trailbyte(int c)
+{
+       c &= 0xff;
+       return ((0x40 <= c && c <= 0x7e) || (0x80 <= c && c <= 0xfe));
+}
+
+static __inline int
+_mb_surrogate(int c)
+{
+       c &= 0xff;
+       return (0x30 <= c && c <= 0x39);
+}
+
+static __inline int
+_mb_count(wchar_t v)
+{
+       u_int32_t c;
+
+       c = (u_int32_t)v; /* XXX */
+       if (!(c & 0xffffff00))
+               return (1);
+       if (!(c & 0xffff0000))
+               return (2);
+       return (4);
+}
+
+#define        _PSENC          (psenc->ch[psenc->chlen - 1])
+#define        _PUSH_PSENC(c)  (psenc->ch[psenc->chlen++] = (c))
+
+static int
+_citrus_GBK2K_mbrtowc_priv(_GBK2KEncodingInfo * __restrict ei,
+                          wchar_t * __restrict pwc,
+                          const char ** __restrict s, size_t n,
+                          _GBK2KState * __restrict psenc,
+                          size_t * __restrict nresult)
+{
+       int chlenbak, len;
+       const char *s0, *s1;
+       wchar_t wc;
+
+       _DIAGASSERT(ei != NULL);
+       /* pwc may be NULL */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       s0 = *s;
+
+       if (s0 == NULL) {
+               /* _citrus_GBK2K_init_state(ei, psenc); */
+               psenc->chlen = 0;
+               *nresult = 0;
+               return (0);
+       }
+
+       chlenbak = psenc->chlen;
+
+       switch (psenc->chlen) {
+       case 3:
+               if (!_mb_leadbyte (_PSENC))
+                       goto invalid;
+       /* FALLTHROUGH */
+       case 2:
+               if (!_mb_surrogate(_PSENC) || _mb_trailbyte(_PSENC))
+                       goto invalid;
+       /* FALLTHROUGH */
+       case 1:
+               if (!_mb_leadbyte (_PSENC))
+                       goto invalid;
+       /* FALLTHOROUGH */
+       case 0:
+               break;
+       default:
+               goto invalid;
+       }
+
+       for (;;) {
+               if (n-- < 1)
+                       goto restart;
+
+               _PUSH_PSENC(*s0++);
+
+               switch (psenc->chlen) {
+               case 1:
+                       if (_mb_singlebyte(_PSENC))
+                               goto convert;
+                       if (_mb_leadbyte  (_PSENC))
+                               continue;
+                       goto ilseq;
+               case 2:
+                       if (_mb_trailbyte (_PSENC))
+                               goto convert;
+                       if (ei->mb_cur_max == 4 &&
+                           _mb_surrogate (_PSENC))
+                               continue;
+                       goto ilseq;
+               case 3:
+                       if (_mb_leadbyte  (_PSENC))
+                               continue;
+                       goto ilseq;
+               case 4:
+                       if (_mb_surrogate (_PSENC))
+                               goto convert;
+                       goto ilseq;
+               }
+       }
+
+convert:
+       len = psenc->chlen;
+       s1  = &psenc->ch[0];
+       wc  = 0;
+       while (len-- > 0)
+               wc = (wc << 8) | (*s1++ & 0xff);
+
+       if (pwc != NULL)
+               *pwc = wc;
+       *s = s0;
+       *nresult = (wc == 0) ? 0 : psenc->chlen - chlenbak; 
+       /* _citrus_GBK2K_init_state(ei, psenc); */
+       psenc->chlen = 0;
+
+       return (0);
+
+restart:
+       *s = s0;
+       *nresult = (size_t)-2;
+
+       return (0);
+
+invalid:
+       return (EINVAL);
+
+ilseq:
+       *nresult = (size_t)-1;
+       return (EILSEQ);
+}
+
+static int
+_citrus_GBK2K_wcrtomb_priv(_GBK2KEncodingInfo * __restrict ei,
+                          char * __restrict s, size_t n, wchar_t wc,
+                          _GBK2KState * __restrict psenc,
+                          size_t * __restrict nresult)
+{
+       int len, ret;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       if (psenc->chlen != 0) {
+               ret = EINVAL;
+               goto err;
+       }
+
+       len = _mb_count(wc);
+       if (n < len) {
+               ret = E2BIG;
+               goto err;
+       }
+
+       switch (len) {
+       case 1:
+               if (!_mb_singlebyte(_PUSH_PSENC(wc     ))) {
+                       ret = EILSEQ;
+                       goto err;
+               }
+               break;
+       case 2:
+               if (!_mb_leadbyte  (_PUSH_PSENC(wc >> 8)) ||
+                   !_mb_trailbyte (_PUSH_PSENC(wc     ))) {
+                       ret = EILSEQ;
+                       goto err;
+               }
+               break;
+       case 4:
+               if (ei->mb_cur_max != 4 ||
+                   !_mb_leadbyte  (_PUSH_PSENC(wc >> 24)) ||
+                   !_mb_surrogate (_PUSH_PSENC(wc >> 16)) ||
+                   !_mb_leadbyte  (_PUSH_PSENC(wc >>  8)) ||
+                   !_mb_surrogate (_PUSH_PSENC(wc      ))) {
+                       ret = EILSEQ;
+                       goto err;
+               }
+               break;
+       }
+
+       _DIAGASSERT(len == psenc->chlen);
+
+       memcpy(s, psenc->ch, psenc->chlen);
+       *nresult = psenc->chlen;
+       /* _citrus_GBK2K_init_state(ei, psenc); */
+       psenc->chlen = 0;
+
+       return (0);
+
+err:
+       *nresult = (size_t)-1;
+       return ret;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_GBK2K_stdenc_wctocs(_GBK2KEncodingInfo * __restrict ei,
+                           _csid_t * __restrict csid,
+                           _index_t * __restrict idx, wchar_t wc)
+{
+       u_int8_t ch, cl;
+
+       _DIAGASSERT(csid != NULL && idx != NULL);
+
+       if ((u_int32_t)wc<0x80) {
+               /* ISO646 */
+               *csid = 0;
+               *idx = (_index_t)wc;
+       } else if ((u_int32_t)wc>=0x10000) {
+               /* GBKUCS : XXX */
+               *csid = 3;
+               *idx = (_index_t)wc;
+       } else {
+               ch = (u_int8_t)(wc >> 8);
+               cl = (u_int8_t)wc;
+               if (ch>=0xA1 && cl>=0xA1) {
+                       /* EUC G1 */
+                       *csid = 1;
+                       *idx = (_index_t)wc & 0x7F7FU;
+               } else {
+                       /* extended area (0x8140-) */
+                       *csid = 2;
+                       *idx = (_index_t)wc;
+               }
+       }
+               
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_GBK2K_stdenc_cstowc(_GBK2KEncodingInfo * __restrict ei,
+                           wchar_t * __restrict wc,
+                           _csid_t csid, _index_t idx)
+{
+
+       _DIAGASSERT(wc != NULL);
+
+       switch (csid) {
+       case 0:
+               /* ISO646 */
+               *wc = (wchar_t)idx;
+               break;
+       case 1:
+               /* EUC G1 */
+               *wc = (wchar_t)idx | 0x8080U;
+               break;
+       case 2:
+               /* extended area */
+               *wc = (wchar_t)idx;
+               break;
+       case 3:
+               /* GBKUCS : XXX */
+               if (ei->mb_cur_max != 4)
+                       return EINVAL;
+               *wc = (wchar_t)idx;
+               break;
+       default:
+               return EILSEQ;
+       }
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_GBK2K_stdenc_get_state_desc_generic(_GBK2KEncodingInfo * __restrict ei,
+                                           _GBK2KState * __restrict psenc,
+                                           int * __restrict rstate)
+{
+
+       if (psenc->chlen == 0)
+               *rstate = _STDENC_SDGEN_INITIAL;
+       else
+               *rstate = _STDENC_SDGEN_INCOMPLETE_CHAR;
+
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_GBK2K_encoding_module_init(_GBK2KEncodingInfo * __restrict ei,
+                                  const void * __restrict var, size_t lenvar)
+{
+       const char *p;
+
+       _DIAGASSERT(ei != NULL);
+
+       p = var;
+#define MATCH(x, act)                                           \
+do {                                                            \
+        if (lenvar >= (sizeof(#x)-1) &&                         \
+            _bcs_strncasecmp(p, #x, sizeof(#x)-1) == 0) {       \
+                act;                                            \
+                lenvar -= sizeof(#x)-1;                         \
+                p += sizeof(#x)-1;                              \
+        }                                                       \
+} while (/*CONSTCOND*/0)
+       memset((void *)ei, 0, sizeof(*ei));
+       ei->mb_cur_max = 4;
+       while (lenvar>0) {
+               switch (_bcs_tolower(*p)) {
+               case '2':
+                       MATCH("2byte", ei->mb_cur_max = 2);
+                       break;
+               }
+               p++;
+               lenvar--;
+       }
+
+       return (0);
+}
+
+static void
+/*ARGSUSED*/
+_citrus_GBK2K_encoding_module_uninit(_GBK2KEncodingInfo *ei)
+{
+}
+
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(GBK2K);
+_CITRUS_CTYPE_DEF_OPS(GBK2K);
+
+#include "citrus_ctype_template.h"
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(GBK2K);
+_CITRUS_STDENC_DEF_OPS(GBK2K);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_gbk2k.h b/lib/nbsd_libc/citrus/modules/citrus_gbk2k.h
new file mode 100644 (file)
index 0000000..d0ea491
--- /dev/null
@@ -0,0 +1,37 @@
+/* $NetBSD: citrus_gbk2k.h,v 1.2 2003/06/25 09:51:43 tshiozak Exp $ */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_GBK2K_H_
+#define _CITRUS_GBK2K_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(GBK2K);
+_CITRUS_STDENC_GETOPS_FUNC(GBK2K);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_hz.c b/lib/nbsd_libc/citrus/modules/citrus_hz.c
new file mode 100644 (file)
index 0000000..caebd2f
--- /dev/null
@@ -0,0 +1,726 @@
+/* $NetBSD: citrus_hz.c,v 1.2 2008/06/14 16:01:07 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2004, 2006 Citrus Project,
+ * 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.
+ *
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_hz.c,v 1.2 2008/06/14 16:01:07 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/queue.h>
+#include <sys/types.h>
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <limits.h>
+#include <wchar.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+
+#include "citrus_hz.h"
+#include "citrus_prop.h"
+
+/*
+ * wchar_t mapping:
+ *
+ * CTRL/ASCII  00000000 00000000 00000000 gxxxxxxx
+ * GB2312      00000000 00000000 0xxxxxxx gxxxxxxx
+ * 94/96*n (~M)        0mmmmmmm 0xxxxxxx 0xxxxxxx gxxxxxxx
+ */
+
+#define ESCAPE_CHAR    '~'
+
+typedef enum {
+       CTRL = 0, ASCII = 1, GB2312 = 2, CS94 = 3, CS96 = 4
+} charset_t;
+
+typedef struct {
+       int start, end, width;
+} range_t;
+
+static const range_t ranges[] = {
+#define RANGE(start, end) { start, end, (end - start) + 1 }
+/* CTRL   */ RANGE(0x00, 0x1F),
+/* ASCII  */ RANGE(0x20, 0x7F),
+/* GB2312 */ RANGE(0x21, 0x7E),
+/* CS94   */ RANGE(0x21, 0x7E),
+/* CS96   */ RANGE(0x20, 0x7F),
+#undef RANGE
+};
+
+typedef struct escape_t escape_t;
+typedef struct {
+       charset_t charset;
+       size_t length;
+#define ROWCOL_MAX     3
+       escape_t *escape;
+} graphic_t;
+
+typedef TAILQ_HEAD(escape_list, escape_t) escape_list;
+struct escape_t {
+       TAILQ_ENTRY(escape_t) entry;
+       int ch;
+       graphic_t *left, *right;
+       escape_list *set;
+};
+
+#define GL(escape)     ((escape)->left)
+#define GR(escape)     ((escape)->right)
+#define SET(escape)    ((escape)->set)
+#define ESC(escape)    ((escape)->ch)
+#define INIT(escape)   (TAILQ_FIRST(SET(escape)))
+
+static __inline escape_t *
+find_escape(escape_list *set, int ch)
+{
+       escape_t *escape;
+
+       _DIAGASSERT(set != NULL);
+
+       TAILQ_FOREACH(escape, set, entry) {
+               if (ESC(escape) == ch)
+                       break;
+       }
+
+       return escape;
+}
+
+typedef struct {
+       escape_list e0, e1;
+       graphic_t *ascii, *gb2312;
+} _HZEncodingInfo;
+
+#define E0SET(ei)      (&(ei)->e0)
+#define E1SET(ei)      (&(ei)->e1)
+#define INIT0(ei)      (TAILQ_FIRST(E0SET(ei)))
+#define INIT1(ei)      (TAILQ_FIRST(E1SET(ei)))
+
+typedef struct {
+       int chlen;
+       char ch[ROWCOL_MAX];
+       escape_t *inuse;
+} _HZState;
+
+typedef struct {
+       _HZEncodingInfo         ei;
+       struct {
+               /* for future multi-locale facility */
+               _HZState        s_mblen;
+               _HZState        s_mbrlen;
+               _HZState        s_mbrtowc;
+               _HZState        s_mbtowc;
+               _HZState        s_mbsrtowcs;
+               _HZState        s_wcrtomb;
+               _HZState        s_wcsrtombs;
+               _HZState        s_wctomb;
+       } states;
+} _HZCTypeInfo;
+
+#define _CEI_TO_EI(_cei_)              (&(_cei_)->ei)
+#define _CEI_TO_STATE(_cei_, _func_)   (_cei_)->states.s_##_func_
+
+#define _FUNCNAME(m)                   _citrus_HZ_##m
+#define _ENCODING_INFO                 _HZEncodingInfo
+#define _CTYPE_INFO                    _HZCTypeInfo
+#define _ENCODING_STATE                        _HZState
+#define _ENCODING_MB_CUR_MAX(_ei_)     MB_LEN_MAX
+#define _ENCODING_IS_STATE_DEPENDENT           1
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       ((_ps_)->inuse == NULL)
+
+static __inline void
+_citrus_HZ_init_state(_HZEncodingInfo * __restrict ei,
+       _HZState * __restrict psenc)
+{
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       psenc->chlen = 0;
+       psenc->inuse = INIT0(ei);
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_HZ_pack_state(_HZEncodingInfo * __restrict ei,
+       void *__restrict pspriv, const _HZState * __restrict psenc)
+{
+       /* ei may be unused */
+       _DIAGASSERT(pspriv != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       memcpy(pspriv, (const void *)psenc, sizeof(*psenc));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_HZ_unpack_state(_HZEncodingInfo * __restrict ei,
+       _HZState * __restrict psenc, const void * __restrict pspriv)
+{
+       /* ei may be unused */
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(pspriv != NULL);
+
+       memcpy((void *)psenc, pspriv, sizeof(*psenc));
+}
+
+static int
+_citrus_HZ_mbrtowc_priv(_HZEncodingInfo * __restrict ei,
+       wchar_t * __restrict pwc, const char ** __restrict s, size_t n,
+       _HZState * __restrict psenc, size_t * __restrict nresult)
+{
+       const char *s0;
+       wchar_t wc;
+       int bit, head, tail, len, ch;
+       graphic_t *graphic;
+       escape_t *candidate, *init;
+       const range_t *range;
+
+       _DIAGASSERT(ei != NULL);
+       /* pwc may be null */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (*s == NULL) {
+               _citrus_HZ_init_state(ei, psenc);
+               *nresult = 1;
+               return 0;
+       }
+       s0 = *s;
+       if (psenc->chlen < 0 || psenc->inuse == NULL)
+               return EINVAL;
+
+       wc = (wchar_t)0;
+       bit = head = tail = 0;
+       graphic = NULL;
+       for (len = 0; len <= MB_LEN_MAX; /**/) {
+               if (psenc->chlen == tail) {
+                       if (n-- < 1) {
+                               *s = s0;
+                               *nresult = (size_t)-2;
+                               return 0;
+                       }
+                       psenc->ch[psenc->chlen++] = *s0++;
+                       ++len;
+               }
+               ch = (unsigned char)psenc->ch[tail++];
+               if (tail == 1) {
+                       if ((ch & ~0x80) <= 0x1F) {
+                               if (psenc->inuse != INIT0(ei))
+                                       break;
+                               wc = (wchar_t)ch;
+                               goto done;
+                       }
+                       if (ch & 0x80) {
+                               graphic = GR(psenc->inuse);
+                               bit = 0x80;
+                               ch &= ~0x80;
+                       } else {
+                               graphic = GL(psenc->inuse);
+                               if (ch == ESCAPE_CHAR)
+                                       continue;
+                               bit = 0x0;
+                       }
+                       if (graphic == NULL)
+                               break;
+               } else if (tail == 2 && psenc->ch[0] == ESCAPE_CHAR) {
+                       if (tail < psenc->chlen)
+                               return EINVAL;
+                       if (ch == ESCAPE_CHAR) {
+                               ++head;
+                       } else if (ch == '\n') {
+                               if (psenc->inuse != INIT0(ei))
+                                       break;
+                               tail = psenc->chlen = 0;
+                               continue;
+                       } else {
+                               candidate = NULL;
+                               init = INIT0(ei);
+                               _DIAGASSERT(init != NULL);
+                               if (psenc->inuse == init) {
+                                       init = INIT1(ei);
+                               } else if (INIT(psenc->inuse) == init) {
+                                       if (ESC(init) != ch)
+                                               break;
+                                       candidate = init;
+                               }
+                               if (candidate == NULL) {
+                                       candidate = find_escape(
+                                           SET(psenc->inuse), ch);
+                                       if (candidate == NULL) {
+                                               if (init == NULL ||
+                                                   ESC(init) != ch)
+                                                       break;
+                                               candidate = init;
+                                       }
+                               }
+                               psenc->inuse = candidate;
+                               tail = psenc->chlen = 0;
+                               continue;
+                       }
+               } else if (ch & 0x80) {
+                       if (graphic != GR(psenc->inuse))
+                               break;
+                       ch &= ~0x80;
+               } else {
+                       if (graphic != GL(psenc->inuse))
+                               break;
+               }
+               _DIAGASSERT(graphic != NULL);
+               range = &ranges[(size_t)graphic->charset];
+               if (range->start > ch || range->end < ch)
+                       break;
+               wc <<= 8;
+               wc |= ch;
+               if (graphic->length == (tail - head)) {
+                       if (graphic->charset > GB2312)
+                               bit |= ESC(psenc->inuse) << 24;
+                       wc |= bit;
+                       goto done;
+               }
+       }
+       *nresult = (size_t)-1;
+       return EILSEQ;
+done:
+       if (tail < psenc->chlen)
+               return EINVAL;
+       *s = s0;
+       if (pwc != NULL)
+               *pwc = wc;
+       psenc->chlen = 0;
+       *nresult = (wc == 0) ? 0 : len;
+
+       return 0;
+}
+
+static int
+_citrus_HZ_wcrtomb_priv(_HZEncodingInfo * __restrict ei,
+       char * __restrict s, size_t n, wchar_t wc,
+       _HZState * __restrict psenc, size_t * __restrict nresult)
+{
+       int bit, ch;
+       escape_t *candidate, *init;
+       graphic_t *graphic;
+       size_t len;
+       const range_t *range;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (psenc->chlen != 0 || psenc->inuse == NULL)
+               return EINVAL;
+       if (wc & 0x80) {
+               bit = 0x80;
+               wc &= ~0x80;
+       } else {
+               bit = 0x0;
+       }
+       if ((uint32_t)wc <= 0x1F) {
+               candidate = INIT0(ei);
+               graphic = (bit == 0)
+                   ? candidate->left : candidate->right;
+               if (graphic == NULL)
+                       goto ilseq;
+               range = &ranges[(size_t)CTRL];
+               len = 1;
+       } else if ((uint32_t)wc <= 0x7F) {
+               graphic = ei->ascii;
+               if (graphic == NULL)
+                       goto ilseq;
+               candidate = graphic->escape;
+               range = &ranges[(size_t)graphic->charset];
+               len = graphic->length;
+       } else if ((uint32_t)wc <= 0x7F7F) {
+               graphic = ei->gb2312;
+               if (graphic == NULL)
+                       goto ilseq;
+               candidate = graphic->escape;
+               range = &ranges[(size_t)graphic->charset];
+               len = graphic->length;
+       } else {
+               ch = (wc >> 24) & 0xFF;
+               candidate = find_escape(E0SET(ei), ch);
+               if (candidate == NULL) {
+                       candidate = find_escape(E1SET(ei), ch);
+                       if (candidate == NULL)
+                               goto ilseq;
+               }
+               wc &= ~0xFF000000;
+               graphic = (bit == 0)
+                   ? candidate->left : candidate->right;
+               if (graphic == NULL)
+                       goto ilseq;
+               range = &ranges[(size_t)graphic->charset];
+               len = graphic->length;
+       }
+       if (psenc->inuse != candidate) {
+               init = INIT0(ei);
+               if (SET(psenc->inuse) == SET(candidate)) {
+                       if (INIT(psenc->inuse) != init ||
+                           psenc->inuse == init || candidate == init)
+                               init = NULL;
+               } else if (candidate == (init = INIT(candidate))) {
+                       init = NULL;
+               }
+               if (init != NULL) {
+                       if (n < 2)
+                               return E2BIG;
+                       n -= 2;
+                       psenc->ch[psenc->chlen++] = ESCAPE_CHAR;
+                       psenc->ch[psenc->chlen++] = ESC(init);
+               }
+               if (n < 2)
+                       return E2BIG;
+               n -= 2;
+               psenc->ch[psenc->chlen++] = ESCAPE_CHAR;
+               psenc->ch[psenc->chlen++] = ESC(candidate);
+               psenc->inuse = candidate;
+       }
+       if (n < len)
+               return E2BIG;
+       while (len-- > 0) {
+               ch = (wc >> (len * 8)) & 0xFF;
+               if (range->start > ch || range->end < ch)
+                       goto ilseq;
+               psenc->ch[psenc->chlen++] = ch | bit;
+       }
+       memcpy(s, psenc->ch, psenc->chlen);
+       *nresult = psenc->chlen;
+       psenc->chlen = 0;
+
+       return 0;
+
+ilseq:
+       *nresult = (size_t)-1;
+       return EILSEQ;
+}
+
+static __inline int
+_citrus_HZ_put_state_reset(_HZEncodingInfo * __restrict ei,
+       char * __restrict s, size_t n, _HZState * __restrict psenc,
+       size_t * __restrict nresult)
+{
+       escape_t *candidate;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (psenc->chlen != 0 || psenc->inuse == NULL)
+               return EINVAL;
+       candidate = INIT0(ei);
+       if (psenc->inuse != candidate) {
+               if (n < 2)
+                       return E2BIG;
+               n -= 2;
+               psenc->ch[psenc->chlen++] = ESCAPE_CHAR;
+               psenc->ch[psenc->chlen++] = ESC(candidate);
+       }
+       if (n < 1)
+               return E2BIG;
+       if (psenc->chlen > 0)
+               memcpy(s, psenc->ch, psenc->chlen);
+       *nresult = psenc->chlen;
+       _citrus_HZ_init_state(ei, psenc);
+
+       return 0;
+}
+
+static __inline int
+_citrus_HZ_stdenc_get_state_desc_generic(_HZEncodingInfo * __restrict ei,
+       _HZState * __restrict psenc, int * __restrict rstate)
+{
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(rstate != NULL);
+
+       if (psenc->chlen < 0 || psenc->inuse == NULL)
+               return EINVAL;
+       *rstate = (psenc->chlen == 0)
+           ? ((psenc->inuse == INIT0(ei))
+               ? _STDENC_SDGEN_INITIAL
+               : _STDENC_SDGEN_STABLE)
+           : ((psenc->ch[0] == ESCAPE_CHAR)
+               ? _STDENC_SDGEN_INCOMPLETE_SHIFT
+               : _STDENC_SDGEN_INCOMPLETE_CHAR);
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_HZ_stdenc_wctocs(_HZEncodingInfo * __restrict ei,
+       _csid_t * __restrict csid, _index_t * __restrict idx, wchar_t wc)
+{
+       int bit;
+
+       _DIAGASSERT(csid != NULL);
+       _DIAGASSERT(idx != NULL);
+
+       if (wc & 0x80) {
+               bit = 0x80;
+               wc &= ~0x80;
+       } else {
+               bit = 0x0;
+       }
+       if ((uint32_t)wc <= 0x7F) {
+               *csid = (_csid_t)bit;
+               *idx = (_index_t)wc;
+       } else if ((uint32_t)wc <= 0x7F7F) {
+               *csid = (_csid_t)(bit | 0x8000);
+               *idx = (_index_t)wc;
+       } else {
+               *csid = (_index_t)(wc & ~0x00FFFF7F);
+               *idx = (_csid_t)(wc & 0x00FFFF7F);
+       }
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_HZ_stdenc_cstowc(_HZEncodingInfo * __restrict ei,
+       wchar_t * __restrict wc, _csid_t csid, _index_t idx)
+{
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(wc != NULL);
+
+       *wc = (wchar_t)idx;
+       switch (csid) {
+       case 0x80:
+       case 0x8080:
+               *wc |= (wchar_t)0x80;
+       /*FALLTHROUGH*/
+       case 0x0:
+       case 0x8000:
+               break;
+       default:
+               *wc |= (wchar_t)csid;
+       }
+
+       return 0;
+}
+
+static void
+_citrus_HZ_encoding_module_uninit(_HZEncodingInfo *ei)
+{
+       escape_t *escape;
+
+       _DIAGASSERT(ei != NULL);
+       while ((escape = TAILQ_FIRST(E0SET(ei))) != NULL) {
+               TAILQ_REMOVE(E0SET(ei), escape, entry);
+               free(GL(escape));
+               free(GR(escape));
+               free(escape);
+       }
+       while ((escape = TAILQ_FIRST(E1SET(ei))) != NULL) {
+               TAILQ_REMOVE(E1SET(ei), escape, entry);
+               free(GL(escape));
+               free(GR(escape));
+               free(escape);
+       }
+}
+
+static int
+_citrus_HZ_parse_char(void **context, const char *name, const char *s)
+{
+       void **p;
+       escape_t *escape;
+
+       _DIAGASSERT(context != NULL && *context != NULL);
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(s != NULL);
+
+       p = (void **)*context;
+       escape = (escape_t *)p[0];
+       if (escape->ch != '\0')
+               return EINVAL;
+       escape->ch = *s++;
+       if (escape->ch == ESCAPE_CHAR || *s != '\0')
+               return EINVAL;
+
+       return 0;
+}
+
+static int
+_citrus_HZ_parse_graphic(void **context, const char *name, const char *s)
+{
+       void **p;
+       _HZEncodingInfo *ei;
+       escape_t *escape;
+       graphic_t *graphic;
+
+       _DIAGASSERT(context != NULL && *context != NULL);
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(s != NULL);
+
+       p = (void **)*context;
+       escape = (escape_t *)p[0];
+       ei = (_HZEncodingInfo *)p[1];
+       graphic = malloc(sizeof(*graphic));
+       if (graphic == NULL)
+               return ENOMEM;
+       memset(graphic, 0, sizeof(*graphic));
+       if (strcmp("GL", name) == 0) {
+               if (GL(escape) != NULL)
+                       goto release;
+               GL(escape) = graphic;
+       } else if (strcmp("GR", name) == 0) {
+               if (GR(escape) != NULL)
+                       goto release;
+               GR(escape) = graphic;
+       } else {
+release:
+               free(graphic);
+               return EINVAL;
+       }
+       graphic->escape = escape;
+       if (_bcs_strncasecmp("ASCII", s, 5) == 0) {
+               if (s[5] != '\0')
+                       return EINVAL;
+               graphic->charset = ASCII;
+               graphic->length = 1;
+               ei->ascii = graphic;
+               return 0;
+       } else if (_bcs_strncasecmp("GB2312", s, 6) == 0) {
+               if (s[6] != '\0')
+                       return EINVAL;
+               graphic->charset = GB2312;
+               graphic->length = 2;
+               ei->gb2312 = graphic;
+               return 0;
+       } else if (strncmp("94*", s, 3) == 0) {
+               graphic->charset = CS94;
+       } else if (strncmp("96*", s, 3) == 0) {
+               graphic->charset = CS96;
+       } else {
+               return EINVAL;
+       }
+       s += 3;
+       switch(*s) {
+       case '1': case '2': case '3':
+               graphic->length = (size_t)(*s - '0');
+               if (*++s == '\0')
+                       break;
+       /*FALLTHROUGH*/
+       default:
+               return EINVAL;
+       }
+       return 0;
+}
+
+static const _citrus_prop_hint_t escape_hints[] = {
+_CITRUS_PROP_HINT_STR("CH", &_citrus_HZ_parse_char),
+_CITRUS_PROP_HINT_STR("GL", &_citrus_HZ_parse_graphic),
+_CITRUS_PROP_HINT_STR("GR", &_citrus_HZ_parse_graphic),
+_CITRUS_PROP_HINT_END
+};
+
+static int
+_citrus_HZ_parse_escape(void **context, const char *name, const char *s)
+{
+       _HZEncodingInfo *ei;
+       escape_t *escape;
+       void *p[2];
+
+       _DIAGASSERT(context != NULL);
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(s != NULL);
+
+       ei = (_HZEncodingInfo *)*context;
+       escape = malloc(sizeof(*escape));
+       if (escape == NULL)
+               return EINVAL;
+       memset(escape, 0, sizeof(*escape));
+       if (strcmp("0", name) == 0) {
+               escape->set = E0SET(ei);
+               TAILQ_INSERT_TAIL(E0SET(ei), escape, entry);
+       } else if (strcmp("1", name) == 0) {
+               escape->set = E1SET(ei);
+               TAILQ_INSERT_TAIL(E1SET(ei), escape, entry);
+       } else {
+               free(escape);
+               return EINVAL;
+       }
+       p[0] = (void *)escape;
+       p[1] = (void *)ei;
+       return _citrus_prop_parse_variable(
+           escape_hints, (void *)&p[0], s, strlen(s));
+}
+
+static const _citrus_prop_hint_t root_hints[] = {
+_CITRUS_PROP_HINT_STR("0", &_citrus_HZ_parse_escape),
+_CITRUS_PROP_HINT_STR("1", &_citrus_HZ_parse_escape),
+_CITRUS_PROP_HINT_END
+};
+
+static int
+_citrus_HZ_encoding_module_init(_HZEncodingInfo * __restrict ei,
+       const void * __restrict var, size_t lenvar)
+{
+       int errnum;
+
+       _DIAGASSERT(ei != NULL);
+
+       memset(ei, 0, sizeof(*ei));
+       TAILQ_INIT(E0SET(ei));
+       TAILQ_INIT(E1SET(ei));
+       errnum = _citrus_prop_parse_variable(
+           root_hints, (void *)ei, var, lenvar);
+       if (errnum != 0)
+               _citrus_HZ_encoding_module_uninit(ei);
+       return errnum;
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(HZ);
+_CITRUS_CTYPE_DEF_OPS(HZ);
+
+#include "citrus_ctype_template.h"
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(HZ);
+_CITRUS_STDENC_DEF_OPS(HZ);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_hz.h b/lib/nbsd_libc/citrus/modules/citrus_hz.h
new file mode 100644 (file)
index 0000000..5543521
--- /dev/null
@@ -0,0 +1,37 @@
+/* $NetBSD: citrus_hz.h,v 1.1 2006/11/22 23:38:27 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2004, 2006 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_HZ_H_
+#define _CITRUS_HZ_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(HZ);
+_CITRUS_STDENC_GETOPS_FUNC(HZ);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_iconv_none.c b/lib/nbsd_libc/citrus/modules/citrus_iconv_none.c
new file mode 100644 (file)
index 0000000..45cc2b1
--- /dev/null
@@ -0,0 +1,127 @@
+/*     $NetBSD: citrus_iconv_none.c,v 1.2 2003/07/01 09:42:16 tshiozak Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_iconv_none.c,v 1.2 2003/07/01 09:42:16 tshiozak Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/queue.h>
+
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_hash.h"
+#include "citrus_iconv.h"
+#include "citrus_iconv_none.h"
+
+/* ---------------------------------------------------------------------- */
+
+_CITRUS_ICONV_DECLS(iconv_none);
+_CITRUS_ICONV_DEF_OPS(iconv_none);
+
+
+/* ---------------------------------------------------------------------- */
+
+int
+_citrus_iconv_none_iconv_getops(struct _citrus_iconv_ops *ops, size_t lenops,
+                               uint32_t expected_version)
+{
+       if (expected_version<_CITRUS_ICONV_ABI_VERSION || lenops<sizeof(*ops))
+               return (EINVAL);
+
+       memcpy(ops, &_citrus_iconv_none_iconv_ops,
+              sizeof(_citrus_iconv_none_iconv_ops));
+
+       return (0);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_iconv_none_iconv_init_shared(
+       struct _citrus_iconv_shared * __restrict ci,
+       const char * __restrict curdir,
+       const char * __restrict in, const char * __restrict out,
+       const void * __restrict var, size_t lenvar)
+{
+       ci->ci_closure = NULL;
+       return 0;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_iconv_none_iconv_uninit_shared(struct _citrus_iconv_shared *ci)
+{
+}
+
+static int
+/*ARGSUSED*/
+_citrus_iconv_none_iconv_init_context(struct _citrus_iconv *cv)
+{
+       cv->cv_closure = NULL;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_iconv_none_iconv_uninit_context(struct _citrus_iconv *cv)
+{
+}
+
+static int
+/*ARGSUSED*/
+_citrus_iconv_none_iconv_convert(struct _citrus_iconv * __restrict ci,
+                                const char * __restrict * __restrict in,
+                                size_t * __restrict inbytes,
+                                char * __restrict * __restrict out,
+                                size_t * __restrict outbytes,
+                                u_int32_t flags, size_t * __restrict invalids)
+{
+       int e2big;
+       size_t len;
+
+       len = *inbytes;
+       e2big = 0;
+       if (*outbytes<len) {
+               e2big = 1;
+               len = *outbytes;
+       }
+       memcpy(*out, *in, len);
+       in += len;
+       *inbytes -= len;
+       out+=len;
+       *outbytes -= len;
+       *invalids = 0;
+       if (e2big) {
+               return (E2BIG);
+       }
+
+       return (0);
+}
diff --git a/lib/nbsd_libc/citrus/modules/citrus_iconv_none.h b/lib/nbsd_libc/citrus/modules/citrus_iconv_none.h
new file mode 100644 (file)
index 0000000..f162d4e
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: citrus_iconv_none.h,v 1.1 2003/06/25 09:51:43 tshiozak Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_ICONV_NONE_H_
+#define _CITRUS_ICONV_NONE_H_
+
+__BEGIN_DECLS
+_CITRUS_ICONV_GETOPS_FUNC(iconv_none);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_iconv_std.c b/lib/nbsd_libc/citrus/modules/citrus_iconv_std.c
new file mode 100644 (file)
index 0000000..59929d8
--- /dev/null
@@ -0,0 +1,586 @@
+/*     $NetBSD: citrus_iconv_std.c,v 1.15 2006/11/13 19:08:19 tnozaki Exp $    */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_iconv_std.c,v 1.15 2006/11/13 19:08:19 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <machine/endian.h>
+#include <sys/queue.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_region.h"
+#include "citrus_mmap.h"
+#include "citrus_hash.h"
+#include "citrus_iconv.h"
+#include "citrus_stdenc.h"
+#include "citrus_mapper.h"
+#include "citrus_csmapper.h"
+#include "citrus_memstream.h"
+#include "citrus_iconv_std.h"
+#include "citrus_esdb.h"
+
+/* ---------------------------------------------------------------------- */
+
+_CITRUS_ICONV_DECLS(iconv_std);
+_CITRUS_ICONV_DEF_OPS(iconv_std);
+
+
+/* ---------------------------------------------------------------------- */
+
+int
+_citrus_iconv_std_iconv_getops(struct _citrus_iconv_ops *ops, size_t lenops,
+                              u_int32_t expected_version)
+{
+       if (expected_version<_CITRUS_ICONV_ABI_VERSION || lenops<sizeof(*ops))
+               return (EINVAL);
+
+       memcpy(ops, &_citrus_iconv_std_iconv_ops,
+              sizeof(_citrus_iconv_std_iconv_ops));
+
+       return (0);
+}
+
+/* ---------------------------------------------------------------------- */
+
+/*
+ * convenience routines for stdenc.
+ */
+static __inline void
+save_encoding_state(struct _citrus_iconv_std_encoding *se)
+{
+       if (se->se_ps)
+               memcpy(se->se_pssaved, se->se_ps,
+                      _stdenc_get_state_size(se->se_handle));
+}
+
+static __inline void
+restore_encoding_state(struct _citrus_iconv_std_encoding *se)
+{
+       if (se->se_ps)
+               memcpy(se->se_ps, se->se_pssaved,
+                      _stdenc_get_state_size(se->se_handle));
+}
+
+static __inline void
+init_encoding_state(struct _citrus_iconv_std_encoding *se)
+{
+       if (se->se_ps)
+               _stdenc_init_state(se->se_handle, se->se_ps);
+}
+
+static __inline int
+mbtocsx(struct _citrus_iconv_std_encoding *se,
+       _csid_t *csid, _index_t *idx, const char **s, size_t n,
+       size_t *nresult)
+{
+       return _stdenc_mbtocs(se->se_handle, csid, idx, s, n, se->se_ps,
+                             nresult);
+}
+
+static __inline int
+cstombx(struct _citrus_iconv_std_encoding *se,
+       char *s, size_t n, _csid_t csid, _index_t idx, size_t *nresult)
+{
+       return _stdenc_cstomb(se->se_handle, s, n, csid, idx, se->se_ps,
+                             nresult);
+}
+
+static __inline int
+wctombx(struct _citrus_iconv_std_encoding *se,
+       char *s, size_t n, _wc_t wc, size_t *nresult)
+{
+       return _stdenc_wctomb(se->se_handle, s, n, wc, se->se_ps, nresult);
+}
+
+static __inline int
+put_state_resetx(struct _citrus_iconv_std_encoding *se,
+                char *s, size_t n, size_t *nresult)
+{
+       return _stdenc_put_state_reset(se->se_handle, s, n, se->se_ps, nresult);
+}
+
+static __inline int
+get_state_desc_gen(struct _citrus_iconv_std_encoding *se, int *rstate)
+{
+       int ret;
+       struct _stdenc_state_desc ssd;
+
+       ret = _stdenc_get_state_desc(se->se_handle, se->se_ps,
+                                    _STDENC_SDID_GENERIC, &ssd);
+       if (!ret)
+               *rstate = ssd.u.generic.state;
+
+       return ret;
+}
+
+/*
+ * init encoding context
+ */
+static int
+init_encoding(struct _citrus_iconv_std_encoding *se, struct _stdenc *cs,
+             void *ps1, void *ps2)
+{
+       int ret = -1;
+
+       se->se_handle = cs;
+       se->se_ps = ps1;
+       se->se_pssaved = ps2;
+
+       if (se->se_ps)
+               ret = _stdenc_init_state(cs, se->se_ps);
+       if (!ret && se->se_pssaved)
+               ret = _stdenc_init_state(cs, se->se_pssaved);
+
+       return ret;
+}
+
+static int
+open_csmapper(struct _csmapper **rcm, const char *src, const char *dst,
+             unsigned long *rnorm)
+{
+       int ret;
+       struct _csmapper *cm;
+
+       ret = _csmapper_open(&cm, src, dst, 0, rnorm);
+       if (ret)
+               return ret;
+       if (_csmapper_get_src_max(cm) != 1 || _csmapper_get_dst_max(cm) != 1 ||
+           _csmapper_get_state_size(cm) != 0) {
+               _csmapper_close(cm);
+               return EINVAL;
+       }
+
+       *rcm = cm;
+
+       return 0;
+}
+
+static void
+close_dsts(struct _citrus_iconv_std_dst_list *dl)
+{
+       struct _citrus_iconv_std_dst *sd;
+
+       while ((sd=TAILQ_FIRST(dl)) != NULL) {
+               TAILQ_REMOVE(dl, sd, sd_entry);
+               _csmapper_close(sd->sd_mapper);
+               free(sd);
+       }
+}
+
+static int
+open_dsts(struct _citrus_iconv_std_dst_list *dl,
+         const struct _esdb_charset *ec, const struct _esdb *dbdst)
+{
+       int i, ret;
+       struct _citrus_iconv_std_dst *sd, *sdtmp;
+       unsigned long norm;
+
+       sd = malloc(sizeof(*sd));
+       if (sd == NULL)
+               return errno;
+
+       for (i=0; i<dbdst->db_num_charsets; i++) {
+               ret = open_csmapper(&sd->sd_mapper, ec->ec_csname,
+                                   dbdst->db_charsets[i].ec_csname, &norm);
+               if (ret == 0) {
+                       sd->sd_csid = dbdst->db_charsets[i].ec_csid;
+                       sd->sd_norm = norm;
+                       /* insert this mapper by sorted order. */
+                       TAILQ_FOREACH(sdtmp, dl, sd_entry) {
+                               if (sdtmp->sd_norm > norm) {
+                                       TAILQ_INSERT_BEFORE(sdtmp, sd,
+                                                           sd_entry);
+                                       sd = NULL;
+                                       break;
+                               }
+                       }
+                       if (sd)
+                               TAILQ_INSERT_TAIL(dl, sd, sd_entry);
+                       sd = malloc(sizeof(*sd));
+                       if (sd == NULL) {
+                               ret = errno;
+                               close_dsts(dl);
+                               return ret;
+                       }
+               } else if (ret != ENOENT) {
+                       close_dsts(dl);
+                       free(sd);
+                       return ret;
+               }
+       }
+       free(sd);
+       return 0;
+}
+
+static void
+close_srcs(struct _citrus_iconv_std_src_list *sl)
+{
+       struct _citrus_iconv_std_src *ss;
+
+       while ((ss=TAILQ_FIRST(sl)) != NULL) {
+               TAILQ_REMOVE(sl, ss, ss_entry);
+               close_dsts(&ss->ss_dsts);
+               free(ss);
+       }
+}
+
+static int
+open_srcs(struct _citrus_iconv_std_src_list *sl,
+         const struct _esdb *dbsrc, const struct _esdb *dbdst)
+{
+       int i, ret, count = 0;
+       struct _citrus_iconv_std_src *ss;
+
+       ss = malloc(sizeof(*ss));
+       if (ss == NULL)
+               return errno;
+
+       TAILQ_INIT(&ss->ss_dsts);
+
+       for (i=0; i<dbsrc->db_num_charsets; i++) {
+               ret = open_dsts(&ss->ss_dsts, &dbsrc->db_charsets[i], dbdst);
+               if (ret)
+                       goto err;
+               if (!TAILQ_EMPTY(&ss->ss_dsts)) {
+                       ss->ss_csid = dbsrc->db_charsets[i].ec_csid;
+                       TAILQ_INSERT_TAIL(sl, ss, ss_entry);
+                       ss = malloc(sizeof(*ss));
+                       if (ss == NULL) {
+                               ret = errno;
+                               goto err;
+                       }
+                       count++;
+                       TAILQ_INIT(&ss->ss_dsts);
+               }
+       }
+       free(ss);
+
+       return count ? 0 : ENOENT;
+
+err:
+       free(ss);
+       close_srcs(sl);
+       return ret;
+}
+
+/* do convert a character */
+#define E_NO_CORRESPONDING_CHAR ENOENT /* XXX */
+static int
+/*ARGSUSED*/
+do_conv(const struct _citrus_iconv_std_shared *is,
+       struct _citrus_iconv_std_context *sc, _csid_t *csid, _index_t *idx)
+{
+       _index_t tmpidx;
+       int ret;
+       struct _citrus_iconv_std_src *ss;
+       struct _citrus_iconv_std_dst *sd;
+
+       TAILQ_FOREACH(ss, &is->is_srcs, ss_entry) {
+               if (ss->ss_csid == *csid) {
+                       TAILQ_FOREACH(sd, &ss->ss_dsts, sd_entry) {
+                               ret = _csmapper_convert(sd->sd_mapper,
+                                                       &tmpidx, *idx, NULL);
+                               switch (ret) {
+                               case _MAPPER_CONVERT_SUCCESS:
+                                       *csid = sd->sd_csid;
+                                       *idx = tmpidx;
+                                       return 0;
+                               case _MAPPER_CONVERT_NONIDENTICAL:
+                                       break;
+                               case _MAPPER_CONVERT_SRC_MORE:
+                                       /*FALLTHROUGH*/
+                               case _MAPPER_CONVERT_DST_MORE:
+                                       /*FALLTHROUGH*/
+                               case _MAPPER_CONVERT_FATAL:
+                                       return EINVAL;
+                               case _MAPPER_CONVERT_ILSEQ:
+                                       return EILSEQ;
+                               }
+                       }
+                       break;
+               }
+       }
+
+       return E_NO_CORRESPONDING_CHAR;
+}
+/* ---------------------------------------------------------------------- */
+
+static int
+/*ARGSUSED*/
+_citrus_iconv_std_iconv_init_shared(struct _citrus_iconv_shared *ci,
+                                   const char * __restrict curdir,
+                                   const char * __restrict src,
+                                   const char * __restrict dst,
+                                   const void * __restrict var, size_t lenvar)
+{
+       int ret;
+       struct _citrus_iconv_std_shared *is;
+       struct _citrus_esdb esdbsrc, esdbdst;
+
+       is = malloc(sizeof(*is));
+       if (is==NULL) {
+               ret = errno;
+               goto err0;
+       }
+       ret = _citrus_esdb_open(&esdbsrc, src);
+       if (ret)
+               goto err1;
+       ret = _citrus_esdb_open(&esdbdst, dst);
+       if (ret)
+               goto err2;
+       ret = _stdenc_open(&is->is_src_encoding, esdbsrc.db_encname,
+                          esdbsrc.db_variable, esdbsrc.db_len_variable);
+       if (ret)
+               goto err3;
+       ret = _stdenc_open(&is->is_dst_encoding, esdbdst.db_encname,
+                          esdbdst.db_variable, esdbdst.db_len_variable);
+       if (ret)
+               goto err4;
+       is->is_use_invalid = esdbdst.db_use_invalid;
+       is->is_invalid = esdbdst.db_invalid;
+
+       TAILQ_INIT(&is->is_srcs);
+       ret = open_srcs(&is->is_srcs, &esdbsrc, &esdbdst);
+       if (ret)
+               goto err5;
+
+       _esdb_close(&esdbsrc);
+       _esdb_close(&esdbdst);
+       ci->ci_closure = is;
+
+       return 0;
+
+err5:
+       _stdenc_close(is->is_dst_encoding);
+err4:
+       _stdenc_close(is->is_src_encoding);
+err3:
+       _esdb_close(&esdbdst);
+err2:
+       _esdb_close(&esdbsrc);
+err1:
+       free(is);
+err0:
+       return ret;
+}
+
+static void
+_citrus_iconv_std_iconv_uninit_shared(struct _citrus_iconv_shared *ci)
+{
+       struct _citrus_iconv_std_shared *is = ci->ci_closure;
+
+       if (is == NULL)
+               return;
+
+       _stdenc_close(is->is_src_encoding);
+       _stdenc_close(is->is_dst_encoding);
+       close_srcs(&is->is_srcs);
+       free(is);
+}
+
+static int
+_citrus_iconv_std_iconv_init_context(struct _citrus_iconv *cv)
+{
+       const struct _citrus_iconv_std_shared *is = cv->cv_shared->ci_closure;
+       struct _citrus_iconv_std_context *sc;
+       int ret;
+       size_t szpssrc, szpsdst, sz;
+       char *ptr;
+
+       szpssrc = _stdenc_get_state_size(is->is_src_encoding);
+       szpsdst = _stdenc_get_state_size(is->is_dst_encoding);
+
+       sz = (szpssrc + szpsdst)*2 + sizeof(struct _citrus_iconv_std_context);
+       sc = malloc(sz);
+       if (sc == NULL)
+               return errno;
+
+       ptr = (char *)&sc[1];
+       if (szpssrc)
+               init_encoding(&sc->sc_src_encoding, is->is_src_encoding,
+                             ptr, ptr+szpssrc);
+       else
+               init_encoding(&sc->sc_src_encoding, is->is_src_encoding,
+                             NULL, NULL);
+       ptr += szpssrc*2;
+       if (szpsdst)
+               init_encoding(&sc->sc_dst_encoding, is->is_dst_encoding,
+                             ptr, ptr+szpsdst);
+       else
+               init_encoding(&sc->sc_dst_encoding, is->is_dst_encoding,
+                             NULL, NULL);
+
+       cv->cv_closure = (void *)sc;
+
+       return 0;
+}
+
+static void
+_citrus_iconv_std_iconv_uninit_context(struct _citrus_iconv *cv)
+{
+       free(cv->cv_closure);
+}
+
+static int
+_citrus_iconv_std_iconv_convert(struct _citrus_iconv * __restrict cv,
+                               const char * __restrict * __restrict in,
+                               size_t * __restrict inbytes,
+                               char * __restrict * __restrict out,
+                               size_t * __restrict outbytes, u_int32_t flags,
+                               size_t * __restrict invalids)
+{
+       const struct _citrus_iconv_std_shared *is = cv->cv_shared->ci_closure;
+       struct _citrus_iconv_std_context *sc = cv->cv_closure;
+       _index_t idx;
+       _csid_t csid;
+       int ret, state;
+       size_t szrin, szrout;
+       size_t inval;
+       const char *tmpin;
+
+       inval = 0;
+       if (in==NULL || *in==NULL) {
+               /* special cases */
+               if (out!=NULL && *out!=NULL) {
+                       /* init output state and store the shift sequence */
+                       save_encoding_state(&sc->sc_src_encoding);
+                       save_encoding_state(&sc->sc_dst_encoding);
+                       szrout = 0;
+
+                       ret = put_state_resetx(&sc->sc_dst_encoding,
+                                              *out, *outbytes,
+                                              &szrout);
+                       if (ret)
+                               goto err;
+
+                       if (szrout == (size_t)-2) {
+                               /* too small to store the character */
+                               ret = EINVAL;
+                               goto err;
+                       }
+                       *out += szrout;
+                       *outbytes -= szrout;
+               } else
+                       /* otherwise, discard the shift sequence */
+                       init_encoding_state(&sc->sc_dst_encoding);
+               init_encoding_state(&sc->sc_src_encoding);
+               *invalids = 0;
+               return 0;
+       }
+
+       /* normal case */
+       for (;;) {
+               if (*inbytes==0) {
+                       ret = get_state_desc_gen(&sc->sc_src_encoding, &state);
+                       if (state == _STDENC_SDGEN_INITIAL ||
+                           state == _STDENC_SDGEN_STABLE)
+                               break;
+               }
+
+               /* save the encoding states for the error recovery */
+               save_encoding_state(&sc->sc_src_encoding);
+               save_encoding_state(&sc->sc_dst_encoding);
+
+               /* mb -> csid/index */
+               tmpin = *in;
+               szrin = szrout = 0;
+               ret = mbtocsx(&sc->sc_src_encoding, &csid, &idx,
+                             &tmpin, *inbytes, &szrin);
+               if (ret)
+                       goto err;
+
+               if (szrin == (size_t)-2) {
+                       /* incompleted character */
+                       ret = get_state_desc_gen(&sc->sc_src_encoding, &state);
+                       if (ret) {
+                               ret = EINVAL;
+                               goto err;
+                       }
+                       switch (state) {
+                       case _STDENC_SDGEN_INITIAL:
+                       case _STDENC_SDGEN_STABLE:
+                               /* fetch shift sequences only. */
+                               goto next;
+                       }
+                       ret = EINVAL;
+                       goto err;
+               }
+               /* convert the character */
+               ret = do_conv(is, sc, &csid, &idx);
+               if (ret) {
+                       if (ret == E_NO_CORRESPONDING_CHAR) {
+                               inval++;
+                               szrout = 0;
+                               if ((flags&_CITRUS_ICONV_F_HIDE_INVALID)==0 &&
+                                   is->is_use_invalid) {
+                                       ret = wctombx(&sc->sc_dst_encoding,
+                                                     *out, *outbytes,
+                                                     is->is_invalid,
+                                                     &szrout);
+                                       if (ret)
+                                               goto err;
+                               }
+                               goto next;
+                       } else {
+                               goto err;
+                       }
+               }
+               /* csid/index -> mb */
+               ret = cstombx(&sc->sc_dst_encoding,
+                             *out, *outbytes, csid, idx, &szrout);
+               if (ret)
+                       goto err;
+next:
+               _DIAGASSERT(*inbytes>=szrin && *outbytes>=szrout);
+               *inbytes -= tmpin-*in; /* szrin is insufficient on \0. */
+               *in = tmpin;
+               *outbytes -= szrout;
+               *out += szrout;
+       }
+       *invalids = inval;
+
+       return 0;
+
+err:
+       restore_encoding_state(&sc->sc_src_encoding);
+       restore_encoding_state(&sc->sc_dst_encoding);
+err_norestore:
+       *invalids = inval;
+
+       return ret;
+}
diff --git a/lib/nbsd_libc/citrus/modules/citrus_iconv_std.h b/lib/nbsd_libc/citrus/modules/citrus_iconv_std.h
new file mode 100644 (file)
index 0000000..c1d4301
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: citrus_iconv_std.h,v 1.1 2003/06/25 09:51:44 tshiozak Exp $    */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_ICONV_STD_H_
+#define _CITRUS_ICONV_STD_H_
+
+#include "citrus_iconv_std_local.h"
+
+_CITRUS_ICONV_GETOPS_FUNC(iconv_std);
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_iconv_std_local.h b/lib/nbsd_libc/citrus/modules/citrus_iconv_std_local.h
new file mode 100644 (file)
index 0000000..4b0f583
--- /dev/null
@@ -0,0 +1,81 @@
+/*     $NetBSD: citrus_iconv_std_local.h,v 1.2 2003/07/01 09:42:16 tshiozak Exp $      */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_ICONV_STD_LOCAL_H_
+#define _CITRUS_ICONV_STD_LOCAL_H_
+
+/*
+ * encoding
+ */
+struct _citrus_iconv_std_encoding {
+       struct _citrus_stdenc   *se_handle;
+       void                    *se_ps;
+       void                    *se_pssaved;
+};
+
+/*
+ * dst
+ */
+struct _citrus_iconv_std_dst {
+       TAILQ_ENTRY(_citrus_iconv_std_dst)      sd_entry;
+       _citrus_csid_t                          sd_csid;
+       unsigned long                           sd_norm;
+       struct _citrus_csmapper                 *sd_mapper;
+};
+TAILQ_HEAD(_citrus_iconv_std_dst_list, _citrus_iconv_std_dst);
+
+/*
+ * src
+ */
+struct _citrus_iconv_std_src {
+       TAILQ_ENTRY(_citrus_iconv_std_src)      ss_entry;
+       _citrus_csid_t                          ss_csid;
+       struct _citrus_iconv_std_dst_list       ss_dsts;
+};
+TAILQ_HEAD(_citrus_iconv_std_src_list, _citrus_iconv_std_src);
+
+/*
+ * iconv_std handle
+ */
+struct _citrus_iconv_std_shared {
+       struct _citrus_stdenc                   *is_src_encoding;
+       struct _citrus_stdenc                   *is_dst_encoding;
+       struct _citrus_iconv_std_src_list       is_srcs;
+       int                                     is_use_invalid;
+       _citrus_wc_t                            is_invalid;
+};
+
+/*
+ * iconv_std context
+ */
+struct _citrus_iconv_std_context {
+       struct _citrus_iconv_std_encoding       sc_src_encoding;
+       struct _citrus_iconv_std_encoding       sc_dst_encoding;
+};
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_iso2022.c b/lib/nbsd_libc/citrus/modules/citrus_iso2022.c
new file mode 100644 (file)
index 0000000..3f0eec6
--- /dev/null
@@ -0,0 +1,1347 @@
+/*     $NetBSD: citrus_iso2022.c,v 1.20 2010/12/07 22:01:45 joerg Exp $        */
+
+/*-
+ * Copyright (c)1999, 2002 Citrus Project,
+ * 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.
+ *
+ *     $Citrus: xpg4dl/FreeBSD/lib/libc/locale/iso2022.c,v 1.23 2001/06/21 01:51:44 yamt Exp $
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_iso2022.c,v 1.20 2010/12/07 22:01:45 joerg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <wchar.h>
+#include <sys/types.h>
+#include <limits.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_iso2022.h"
+
+
+/* ----------------------------------------------------------------------
+ * private stuffs used by templates
+ */
+
+
+/*
+ * wchar_t mappings:
+ * ASCII (ESC ( B)             00000000 00000000 00000000 0xxxxxxx
+ * iso-8859-1 (ESC , A)                00000000 00000000 00000000 1xxxxxxx
+ * 94 charset (ESC ( F)                0fffffff 00000000 00000000 0xxxxxxx
+ * 94 charset (ESC ( M F)      0fffffff 1mmmmmmm 00000000 0xxxxxxx
+ * 96 charset (ESC , F)                0fffffff 00000000 00000000 1xxxxxxx
+ * 96 charset (ESC , M F)      0fffffff 1mmmmmmm 00000000 1xxxxxxx
+ * 94x94 charset (ESC $ ( F)   0fffffff 00000000 0xxxxxxx 0xxxxxxx
+ * 96x96 charset (ESC $ , F)   0fffffff 00000000 0xxxxxxx 1xxxxxxx
+ * 94x94 charset (ESC & V ESC $ ( F)
+ *                             0fffffff 1vvvvvvv 0xxxxxxx 0xxxxxxx
+ * 94x94x94 charset (ESC $ ( F)        0fffffff 0xxxxxxx 0xxxxxxx 0xxxxxxx
+ * 96x96x96 charset (ESC $ , F)        0fffffff 0xxxxxxx 0xxxxxxx 1xxxxxxx
+ * reserved for UCS4 co-existence (UCS4 is 31bit encoding thanks to mohta bit)
+ *                             1xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
+ */
+
+typedef struct {
+       u_char  type;
+#define        CS94            (0U)
+#define        CS96            (1U)
+#define        CS94MULTI       (2U)
+#define        CS96MULTI       (3U)
+
+       u_char  final;
+       u_char  interm;
+       u_char  vers;
+} _ISO2022Charset;
+
+static const _ISO2022Charset ascii    = { CS94, 'B', '\0', '\0' };
+static const _ISO2022Charset iso88591 = { CS96, 'A', '\0', '\0' };
+
+typedef struct {
+       _ISO2022Charset g[4];
+       /* need 3 bits to hold -1, 0, ..., 3 */
+       int     gl:3,
+               gr:3,
+               singlegl:3,
+               singlegr:3;
+       char ch[7];     /* longest escape sequence (ESC & V ESC $ ( F) */
+       int chlen;
+       int flags;
+#define _ISO2022STATE_FLAG_INITIALIZED 1
+} _ISO2022State;
+
+typedef struct {
+       _ISO2022Charset *recommend[4];
+       size_t  recommendsize[4];
+       _ISO2022Charset initg[4];
+       int     maxcharset;
+       int     flags;
+#define        F_8BIT  0x0001
+#define        F_NOOLD 0x0002
+#define        F_SI    0x0010  /*0F*/
+#define        F_SO    0x0020  /*0E*/
+#define        F_LS0   0x0010  /*0F*/
+#define        F_LS1   0x0020  /*0E*/
+#define        F_LS2   0x0040  /*ESC n*/
+#define        F_LS3   0x0080  /*ESC o*/
+#define        F_LS1R  0x0100  /*ESC ~*/
+#define        F_LS2R  0x0200  /*ESC }*/
+#define        F_LS3R  0x0400  /*ESC |*/
+#define        F_SS2   0x0800  /*ESC N*/
+#define        F_SS3   0x1000  /*ESC O*/
+#define        F_SS2R  0x2000  /*8E*/
+#define        F_SS3R  0x4000  /*8F*/
+} _ISO2022EncodingInfo;
+typedef struct {
+       _ISO2022EncodingInfo ei;
+       struct {
+               /* for future multi-locale facility */
+               _ISO2022State   s_mblen;
+               _ISO2022State   s_mbrlen;
+               _ISO2022State   s_mbrtowc;
+               _ISO2022State   s_mbtowc;
+               _ISO2022State   s_mbsrtowcs;
+               _ISO2022State   s_wcrtomb;
+               _ISO2022State   s_wcsrtombs;
+               _ISO2022State   s_wctomb;
+       } states;
+} _ISO2022CTypeInfo;
+
+#define _CEI_TO_EI(_cei_)              (&(_cei_)->ei)
+#define _CEI_TO_STATE(_cei_, _func_)   (_cei_)->states.s_##_func_
+
+#define _FUNCNAME(m)                   _citrus_ISO2022_##m
+#define _ENCODING_INFO                 _ISO2022EncodingInfo
+#define _CTYPE_INFO                    _ISO2022CTypeInfo
+#define _ENCODING_STATE                        _ISO2022State
+#define _ENCODING_MB_CUR_MAX(_ei_)     MB_LEN_MAX
+#define _ENCODING_IS_STATE_DEPENDENT   1
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       \
+    (!((_ps_)->flags & _ISO2022STATE_FLAG_INITIALIZED))
+
+
+#define _ISO2022INVALID (wchar_t)-1
+
+static __inline int isc0(__uint8_t x) { return ((x & 0x1f) == x); }
+static __inline int isc1(__uint8_t x) { return (0x80 <= x && x <= 0x9f); }
+static __inline int iscntl(__uint8_t x) { return (isc0(x) || isc1(x) || x == 0x7f); }
+static __inline int is94(__uint8_t x) { return (0x21 <= x && x <= 0x7e); }
+static __inline int is96(__uint8_t x) { return (0x20 <= x && x <= 0x7f); }
+static __inline int isecma(__uint8_t x) { return (0x30 <= x && x <= 0x7f); }
+static __inline int isinterm(__uint8_t x) { return (0x20 <= x && x <= 0x2f); }
+static __inline int isthree(__uint8_t x) { return (0x60 <= x && x <= 0x6f); }
+
+static __inline int
+getcs(const char * __restrict p, _ISO2022Charset * __restrict cs)
+{
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(cs != NULL);
+
+       if (!strncmp(p, "94$", 3) && p[3] && !p[4]) {
+               cs->final = (u_char)(p[3] & 0xff);
+               cs->interm = '\0';
+               cs->vers = '\0';
+               cs->type = CS94MULTI;
+       } else if (!strncmp(p, "96$", 3) && p[3] && !p[4]) {
+               cs->final = (u_char)(p[3] & 0xff);
+               cs->interm = '\0';
+               cs->vers = '\0';
+               cs->type = CS96MULTI;
+       } else if (!strncmp(p, "94", 2) && p[2] && !p[3]) {
+               cs->final = (u_char)(p[2] & 0xff);
+               cs->interm = '\0';
+               cs->vers = '\0';
+               cs->type = CS94;
+       } else if (!strncmp(p, "96", 2) && p[2] && !p[3]) {
+               cs->final = (u_char )(p[2] & 0xff);
+               cs->interm = '\0';
+               cs->vers = '\0';
+               cs->type = CS96;
+       } else {
+               return 1;
+       }
+
+       return 0;
+}
+
+
+#define _NOTMATCH      0
+#define _MATCH         1
+#define _PARSEFAIL     2
+
+static __inline int
+get_recommend(_ISO2022EncodingInfo * __restrict ei,
+             const char * __restrict token)
+{
+       int i;
+       _ISO2022Charset cs, *p;
+
+       if (!strchr("0123", token[0]) || token[1] != '=')
+               return (_NOTMATCH);
+
+       if (getcs(&token[2], &cs) == 0)
+               ;
+       else if (!strcmp(&token[2], "94")) {
+               cs.final = (u_char)(token[4]);
+               cs.interm = '\0';
+               cs.vers = '\0';
+               cs.type = CS94;
+       } else if (!strcmp(&token[2], "96")) {
+               cs.final = (u_char)(token[4]);
+               cs.interm = '\0';
+               cs.vers = '\0';
+               cs.type = CS96;
+       } else if (!strcmp(&token[2], "94$")) {
+               cs.final = (u_char)(token[5]);
+               cs.interm = '\0';
+               cs.vers = '\0';
+               cs.type = CS94MULTI;
+       } else if (!strcmp(&token[2], "96$")) {
+               cs.final = (u_char)(token[5]);
+               cs.interm = '\0';
+               cs.vers = '\0';
+               cs.type = CS96MULTI;
+       } else {
+               return (_PARSEFAIL);
+       }
+
+       i = token[0] - '0';
+       if (!ei->recommend[i]) {
+               ei->recommend[i] = malloc(sizeof(_ISO2022Charset));
+       } else {
+               p = realloc(ei->recommend[i],
+                   sizeof(_ISO2022Charset) * (ei->recommendsize[i] + 1));
+               if (!p)
+                       return (_PARSEFAIL);
+               ei->recommend[i] = p;
+       }
+       if (!ei->recommend[i])
+               return (_PARSEFAIL);
+       ei->recommendsize[i]++;
+
+       (ei->recommend[i] + (ei->recommendsize[i] - 1))->final = cs.final;
+       (ei->recommend[i] + (ei->recommendsize[i] - 1))->interm = cs.interm;
+       (ei->recommend[i] + (ei->recommendsize[i] - 1))->vers = cs.vers;
+       (ei->recommend[i] + (ei->recommendsize[i] - 1))->type = cs.type;
+
+       return (_MATCH);
+}
+
+static __inline int
+get_initg(_ISO2022EncodingInfo * __restrict ei,
+         const char * __restrict token)
+{
+       _ISO2022Charset cs;
+
+       if (strncmp("INIT", &token[0], 4) ||
+           !strchr("0123", token[4]) ||
+           token[5] != '=')
+               return (_NOTMATCH);
+
+       if (getcs(&token[6], &cs) != 0)
+               return (_PARSEFAIL);
+
+       ei->initg[token[4] - '0'].type = cs.type;
+       ei->initg[token[4] - '0'].final = cs.final;
+       ei->initg[token[4] - '0'].interm = cs.interm;
+       ei->initg[token[4] - '0'].vers = cs.vers;
+
+       return (_MATCH);
+}
+
+static __inline int
+get_max(_ISO2022EncodingInfo * __restrict ei,
+       const char * __restrict token)
+{
+       if (!strcmp(token, "MAX1")) {
+               ei->maxcharset = 1;
+       } else if (!strcmp(token, "MAX2")) {
+               ei->maxcharset = 2;
+       } else if (!strcmp(token, "MAX3")) {
+               ei->maxcharset = 3;
+       } else
+               return (_NOTMATCH);
+
+       return (_MATCH);
+}
+
+
+static __inline int
+get_flags(_ISO2022EncodingInfo * __restrict ei,
+         const char * __restrict token)
+{
+       int i;
+       static struct {
+               const char      *tag;
+               int             flag;
+       } const tags[] = {
+               { "DUMMY",      0       },
+               { "8BIT",       F_8BIT  },
+               { "NOOLD",      F_NOOLD },
+               { "SI",         F_SI    },
+               { "SO",         F_SO    },
+               { "LS0",        F_LS0   },
+               { "LS1",        F_LS1   },
+               { "LS2",        F_LS2   },
+               { "LS3",        F_LS3   },
+               { "LS1R",       F_LS1R  },
+               { "LS2R",       F_LS2R  },
+               { "LS3R",       F_LS3R  },
+               { "SS2",        F_SS2   },
+               { "SS3",        F_SS3   },
+               { "SS2R",       F_SS2R  },
+               { "SS3R",       F_SS3R  },
+               { NULL,         0 }
+       };
+
+       for (i = 0; tags[i].tag; i++) {
+               if (!strcmp(token, tags[i].tag)) {
+                       ei->flags |= tags[i].flag;
+                       return (_MATCH);
+               }
+       }
+
+       return (_NOTMATCH);
+}
+
+
+static __inline int
+_citrus_ISO2022_parse_variable(_ISO2022EncodingInfo * __restrict ei,
+                              const void * __restrict var, size_t lenvar)
+{
+       char const *v, *e;
+       char buf[20];
+       int i, len, ret;
+
+       _DIAGASSERT(ei != NULL);
+
+
+       /*
+        * parse VARIABLE section.
+        */
+
+       if (!var)
+               return (EFTYPE);
+
+       v = (const char *) var;
+
+       /* initialize structure */
+       ei->maxcharset = 0;
+       for (i = 0; i < 4; i++) {
+               ei->recommend[i] = NULL;
+               ei->recommendsize[i] = 0;
+       }
+       ei->flags = 0;
+
+       while (*v) {
+               while (*v == ' ' || *v == '\t')
+                       ++v;
+
+               /* find the token */
+               e = v;
+               while (*e && *e != ' ' && *e != '\t')
+                       ++e;
+
+               len = e-v;
+               if (len == 0)
+                       break;
+               if (len>=sizeof(buf))
+                       goto parsefail;
+               snprintf(buf, sizeof(buf), "%.*s", len, v);
+
+               if ((ret = get_recommend(ei, buf)) != _NOTMATCH)
+                       ;
+               else if ((ret = get_initg(ei, buf)) != _NOTMATCH)
+                       ;
+               else if ((ret = get_max(ei, buf)) != _NOTMATCH)
+                       ;
+               else if ((ret = get_flags(ei, buf)) != _NOTMATCH)
+                       ;
+               else
+                       ret = _PARSEFAIL;
+               if (ret==_PARSEFAIL)
+                       goto parsefail;
+               v = e;
+
+       }
+
+       return (0);
+
+parsefail:
+       free(ei->recommend[0]);
+       free(ei->recommend[1]);
+       free(ei->recommend[2]);
+       free(ei->recommend[3]);
+
+       return (EFTYPE);
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_ISO2022_init_state(_ISO2022EncodingInfo * __restrict ei,
+                          _ISO2022State * __restrict s)
+{
+       int i;
+
+       memset(s, 0, sizeof(*s));
+       s->gl = 0;
+       s->gr = (ei->flags & F_8BIT) ? 1 : -1;
+
+       for (i = 0; i < 4; i++) {
+               if (ei->initg[i].final) {
+                       s->g[i].type = ei->initg[i].type;
+                       s->g[i].final = ei->initg[i].final;
+                       s->g[i].interm = ei->initg[i].interm;
+               }
+       }
+       s->singlegl = s->singlegr = -1;
+       s->flags |= _ISO2022STATE_FLAG_INITIALIZED;
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_ISO2022_pack_state(_ISO2022EncodingInfo * __restrict ei,
+                          void * __restrict pspriv,
+                          const _ISO2022State * __restrict s)
+{
+       memcpy(pspriv, (const void *)s, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_ISO2022_unpack_state(_ISO2022EncodingInfo * __restrict ei,
+                            _ISO2022State * __restrict s,
+                            const void * __restrict pspriv)
+{
+       memcpy((void *)s, pspriv, sizeof(*s));
+}
+
+static int
+/*ARGSUSED*/
+_citrus_ISO2022_encoding_module_init(_ISO2022EncodingInfo * __restrict ei,
+                                    const void * __restrict var,
+                                    size_t lenvar)
+{
+
+       _DIAGASSERT(ei != NULL);
+
+       return _citrus_ISO2022_parse_variable(ei, var, lenvar);
+}
+
+static void
+/*ARGSUSED*/
+_citrus_ISO2022_encoding_module_uninit(_ISO2022EncodingInfo *ei)
+{
+}
+
+#define        ESC     '\033'
+#define        ECMA    -1
+#define        INTERM  -2
+#define        OECMA   -3
+static const struct seqtable {
+       int type;
+       int csoff;
+       int finaloff;
+       int intermoff;
+       int versoff;
+       int len;
+       int chars[10];
+} seqtable[] = {
+       /* G0 94MULTI special */
+       { CS94MULTI, -1, 2, -1, -1,     3, { ESC, '$', OECMA }, },
+       /* G0 94MULTI special with version identification */
+       { CS94MULTI, -1, 5, -1, 2,      6, { ESC, '&', ECMA, ESC, '$', OECMA }, },
+       /* G? 94 */
+       { CS94, 1, 2, -1, -1,           3, { ESC, CS94, ECMA, }, },
+       /* G? 94 with 2nd intermediate char */
+       { CS94, 1, 3, 2, -1,            4, { ESC, CS94, INTERM, ECMA, }, },
+       /* G? 96 */
+       { CS96, 1, 2, -1, -1,           3, { ESC, CS96, ECMA, }, },
+       /* G? 96 with 2nd intermediate char */
+       { CS96, 1, 3, 2, -1,            4, { ESC, CS96, INTERM, ECMA, }, },
+       /* G? 94MULTI */
+       { CS94MULTI, 2, 3, -1, -1,      4, { ESC, '$', CS94, ECMA, }, },
+       /* G? 96MULTI */
+       { CS96MULTI, 2, 3, -1, -1,      4, { ESC, '$', CS96, ECMA, }, },
+       /* G? 94MULTI with version specification */
+       { CS94MULTI, 5, 6, -1, 2,       7, { ESC, '&', ECMA, ESC, '$', CS94, ECMA, }, },
+       /* LS2/3 */
+       { -1, -1, -1, -1, -1,           2, { ESC, 'n', }, },
+       { -1, -1, -1, -1, -1,           2, { ESC, 'o', }, },
+       /* LS1/2/3R */
+       { -1, -1, -1, -1, -1,           2, { ESC, '~', }, },
+       { -1, -1, -1, -1, -1,           2, { ESC, /*{*/ '}', }, },
+       { -1, -1, -1, -1, -1,           2, { ESC, '|', }, },
+       /* SS2/3 */
+       { -1, -1, -1, -1, -1,           2, { ESC, 'N', }, },
+       { -1, -1, -1, -1, -1,           2, { ESC, 'O', }, },
+       /* end of records */
+       { 0, }
+};
+
+static int
+seqmatch(const char * __restrict s, size_t n,
+        const struct seqtable * __restrict sp)
+{
+       const int *p;
+
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(sp != NULL);
+
+       p = sp->chars;
+       while (p - sp->chars < n && p - sp->chars < sp->len) {
+               switch (*p) {
+               case ECMA:
+                       if (!isecma(*s))
+                               goto terminate;
+                       break;
+               case OECMA:
+                       if (*s && strchr("@AB", *s))
+                               break;
+                       else
+                               goto terminate;
+               case INTERM:
+                       if (!isinterm(*s))
+                               goto terminate;
+                       break;
+               case CS94:
+                       if (*s && strchr("()*+", *s))
+                               break;
+                       else
+                               goto terminate;
+               case CS96:
+                       if (*s && strchr(",-./", *s))
+                               break;
+                       else
+                               goto terminate;
+               default:
+                       if (*s != *p)
+                               goto terminate;
+                       break;
+               }
+
+               p++;
+               s++;
+       }
+
+terminate:
+       return p - sp->chars;
+}
+
+static wchar_t
+_ISO2022_sgetwchar(_ISO2022EncodingInfo * __restrict ei,
+               const char * __restrict string, size_t n,
+               const char ** __restrict result,
+               _ISO2022State * __restrict psenc)
+{
+       wchar_t wchar = 0;
+       int cur;
+       const struct seqtable *sp;
+       int nmatch;
+       int i;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(string != NULL);
+       /* result may be NULL */
+
+       while (1) {
+               /* SI/SO */
+               if (1 <= n && string[0] == '\017') {
+                       psenc->gl = 0;
+                       string++;
+                       n--;
+                       continue;
+               }
+               if (1 <= n && string[0] == '\016') {
+                       psenc->gl = 1;
+                       string++;
+                       n--;
+                       continue;
+               }
+
+               /* SS2/3R */
+               if (1 <= n && string[0] && strchr("\217\216", string[0])) {
+                       psenc->singlegl = psenc->singlegr =
+                           (string[0] - '\216') + 2;
+                       string++;
+                       n--;
+                       continue;
+               }
+
+               /* eat the letter if this is not ESC */
+               if (1 <= n && string[0] != '\033')
+                       break;
+
+               /* look for a perfect match from escape sequences */
+               for (sp = &seqtable[0]; sp->len; sp++) {
+                       nmatch = seqmatch(string, n, sp);
+                       if (sp->len == nmatch && n >= sp->len)
+                               break;
+               }
+
+               if (!sp->len)
+                       goto notseq;
+
+               if (sp->type != -1) {
+                       if (sp->csoff == -1)
+                               i = 0;
+                       else {
+                               switch (sp->type) {
+                               case CS94:
+                               case CS94MULTI:
+                                       i = string[sp->csoff] - '(';
+                                       break;
+                               case CS96:
+                               case CS96MULTI:
+                                       i = string[sp->csoff] - ',';
+                                       break;
+                               default:
+                                       return (_ISO2022INVALID);
+                               }
+                       }
+                       psenc->g[i].type = sp->type;
+                       psenc->g[i].final = '\0';
+                       psenc->g[i].interm = '\0';
+                       psenc->g[i].vers = '\0';
+                       /* sp->finaloff must not be -1 */
+                       if (sp->finaloff != -1)
+                               psenc->g[i].final = string[sp->finaloff];
+                       if (sp->intermoff != -1)
+                               psenc->g[i].interm = string[sp->intermoff];
+                       if (sp->versoff != -1)
+                               psenc->g[i].vers = string[sp->versoff];
+
+                       string += sp->len;
+                       n -= sp->len;
+                       continue;
+               }
+
+               /* LS2/3 */
+               if (2 <= n && string[0] == '\033'
+                && string[1] && strchr("no", string[1])) {
+                       psenc->gl = string[1] - 'n' + 2;
+                       string += 2;
+                       n -= 2;
+                       continue;
+               }
+
+               /* LS1/2/3R */
+                       /* XXX: { for vi showmatch */
+               if (2 <= n && string[0] == '\033'
+                && string[1] && strchr("~}|", string[1])) {
+                       psenc->gr = 3 - (string[1] - '|');
+                       string += 2;
+                       n -= 2;
+                       continue;
+               }
+
+               /* SS2/3 */
+               if (2 <= n && string[0] == '\033'
+                && string[1] && strchr("NO", string[1])) {
+                       psenc->singlegl = (string[1] - 'N') + 2;
+                       string += 2;
+                       n -= 2;
+                       continue;
+               }
+
+       notseq:
+               /*
+                * if we've got an unknown escape sequence, eat the ESC at the
+                * head.  otherwise, wait till full escape sequence comes.
+                */
+               for (sp = &seqtable[0]; sp->len; sp++) {
+                       nmatch = seqmatch(string, n, sp);
+                       if (!nmatch)
+                               continue;
+
+                       /*
+                        * if we are in the middle of escape sequence,
+                        * we still need to wait for more characters to come
+                        */
+                       if (n < sp->len) {
+                               if (nmatch == n) {
+                                       if (result)
+                                               *result = string;
+                                       return (_ISO2022INVALID);
+                               }
+                       } else {
+                               if (nmatch == sp->len) {
+                                       /* this case should not happen */
+                                       goto eat;
+                               }
+                       }
+               }
+
+               break;
+       }
+
+eat:
+       /* no letter to eat */
+       if (n < 1) {
+               if (result)
+                       *result = string;
+               return (_ISO2022INVALID);
+       }
+
+       /* normal chars.  always eat C0/C1 as is. */
+       if (iscntl(*string & 0xff))
+               cur = -1;
+       else if (*string & 0x80) {
+               cur = (psenc->singlegr == -1)
+                       ? psenc->gr : psenc->singlegr;
+       } else {
+               cur = (psenc->singlegl == -1)
+                       ? psenc->gl : psenc->singlegl;
+       }
+
+       if (cur == -1) {
+asis:
+               wchar = *string++ & 0xff;
+               if (result)
+                       *result = string;
+               /* reset single shift state */
+               psenc->singlegr = psenc->singlegl = -1;
+               return wchar;
+       }
+
+       /* length error check */
+       switch (psenc->g[cur].type) {
+       case CS94MULTI:
+       case CS96MULTI:
+               if (!isthree(psenc->g[cur].final)) {
+                       if (2 <= n
+                        && (string[0] & 0x80) == (string[1] & 0x80))
+                               break;
+               } else {
+                       if (3 <= n
+                        && (string[0] & 0x80) == (string[1] & 0x80)
+                        && (string[0] & 0x80) == (string[2] & 0x80))
+                               break;
+               }
+
+               /* we still need to wait for more characters to come */
+               if (result)
+                       *result = string;
+               return (_ISO2022INVALID);
+
+       case CS94:
+       case CS96:
+               if (1 <= n)
+                       break;
+
+               /* we still need to wait for more characters to come */
+               if (result)
+                       *result = string;
+               return (_ISO2022INVALID);
+       }
+
+       /* range check */
+       switch (psenc->g[cur].type) {
+       case CS94:
+               if (!(is94(string[0] & 0x7f)))
+                       goto asis;
+       case CS96:
+               if (!(is96(string[0] & 0x7f)))
+                       goto asis;
+               break;
+       case CS94MULTI:
+               if (!(is94(string[0] & 0x7f) && is94(string[1] & 0x7f)))
+                       goto asis;
+               break;
+       case CS96MULTI:
+               if (!(is96(string[0] & 0x7f) && is96(string[1] & 0x7f)))
+                       goto asis;
+               break;
+       }
+
+       /* extract the character. */
+       switch (psenc->g[cur].type) {
+       case CS94:
+               /* special case for ASCII. */
+               if (psenc->g[cur].final == 'B' && !psenc->g[cur].interm) {
+                       wchar = *string++;
+                       wchar &= 0x7f;
+                       break;
+               }
+               wchar = psenc->g[cur].final;
+               wchar = (wchar << 8);
+               wchar |= (psenc->g[cur].interm ? (0x80 | psenc->g[cur].interm) : 0);
+               wchar = (wchar << 8);
+               wchar = (wchar << 8) | (*string++ & 0x7f);
+               break;
+       case CS96:
+               /* special case for ISO-8859-1. */
+               if (psenc->g[cur].final == 'A' && !psenc->g[cur].interm) {
+                       wchar = *string++;
+                       wchar &= 0x7f;
+                       wchar |= 0x80;
+                       break;
+               }
+               wchar = psenc->g[cur].final;
+               wchar = (wchar << 8);
+               wchar |= (psenc->g[cur].interm ? (0x80 | psenc->g[cur].interm) : 0);
+               wchar = (wchar << 8);
+               wchar = (wchar << 8) | (*string++ & 0x7f);
+               wchar |= 0x80;
+               break;
+       case CS94MULTI:
+       case CS96MULTI:
+               wchar = psenc->g[cur].final;
+               wchar = (wchar << 8);
+               if (isthree(psenc->g[cur].final))
+                       wchar |= (*string++ & 0x7f);
+               wchar = (wchar << 8) | (*string++ & 0x7f);
+               wchar = (wchar << 8) | (*string++ & 0x7f);
+               if (psenc->g[cur].type == CS96MULTI)
+                       wchar |= 0x80;
+               break;
+       }
+
+       if (result)
+               *result = string;
+       /* reset single shift state */
+       psenc->singlegr = psenc->singlegl = -1;
+       return wchar;
+}
+
+
+
+static int
+_citrus_ISO2022_mbrtowc_priv(_ISO2022EncodingInfo * __restrict ei,
+                            wchar_t * __restrict pwc,
+                            const char ** __restrict s,
+                            size_t n, _ISO2022State * __restrict psenc,
+                            size_t * __restrict nresult)
+{
+       wchar_t wchar;
+       const char *s0, *p, *result;
+       int c;
+       int chlenbak;
+
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(s != NULL);
+
+       if (*s == NULL) {
+               _citrus_ISO2022_init_state(ei, psenc);
+               *nresult = _ENCODING_IS_STATE_DEPENDENT;
+               return 0;
+       }
+       s0 = *s;
+       c = 0;
+       chlenbak = psenc->chlen;
+
+       /*
+        * if we have something in buffer, use that.
+        * otherwise, skip here
+        */
+       if (psenc->chlen < 0 || psenc->chlen > sizeof(psenc->ch)) {
+               /* illgeal state */
+               _citrus_ISO2022_init_state(ei, psenc);
+               goto encoding_error;
+       }
+       if (psenc->chlen == 0)
+               goto emptybuf;
+
+       /* buffer is not empty */
+       p = psenc->ch;
+       while (psenc->chlen < sizeof(psenc->ch)) {
+               if (n > 0) {
+                       psenc->ch[psenc->chlen++] = *s0++;
+                       n--;
+               }
+
+               wchar = _ISO2022_sgetwchar(ei, p, psenc->chlen - (p-psenc->ch),
+                                          &result, psenc);
+               c += result - p;
+               if (wchar != _ISO2022INVALID) {
+                       if (psenc->chlen > c)
+                               memmove(psenc->ch, result, psenc->chlen - c);
+                       if (psenc->chlen < c)
+                               psenc->chlen = 0;
+                       else
+                               psenc->chlen -= c;
+                       goto output;
+               }
+
+               if (n == 0) {
+                       if ((result - p) == psenc->chlen)
+                               /* complete shift sequence. */
+                               psenc->chlen = 0;
+                       goto restart;
+               }
+
+               p = result;
+       }
+
+       /* escape sequence too long? */
+       goto encoding_error;
+
+emptybuf:
+       wchar = _ISO2022_sgetwchar(ei, s0, n, &result, psenc);
+       if (wchar != _ISO2022INVALID) {
+               c += result - s0;
+               psenc->chlen = 0;
+               s0 = result;
+               goto output;
+       }
+       if (result > s0) {
+               c += (result - s0);
+               n -= (result - s0);
+               s0 = result;
+               if (n>0)
+                       goto emptybuf;
+               /* complete shift sequence. */
+               goto restart;
+       }
+       n += c;
+       if (n < sizeof(psenc->ch)) {
+               memcpy(psenc->ch, s0 - c, n);
+               psenc->chlen = n;
+               s0 = result;
+               goto restart;
+       }
+
+       /* escape sequence too long? */
+
+encoding_error:
+       psenc->chlen = 0;
+       *nresult = (size_t)-1;
+       return (EILSEQ);
+
+output:
+       *s = s0;
+       if (pwc)
+               *pwc = wchar;
+
+       if (!wchar)
+               *nresult = 0;
+       else
+               *nresult = c - chlenbak;
+
+       return (0);
+
+restart:
+       *s = s0;
+       *nresult = (size_t)-2;
+
+       return (0);
+}
+
+static int
+recommendation(_ISO2022EncodingInfo * __restrict ei,
+              _ISO2022Charset * __restrict cs)
+{
+       int i, j;
+       _ISO2022Charset *recommend;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(cs != NULL);
+
+       /* first, try a exact match. */
+       for (i = 0; i < 4; i++) {
+               recommend = ei->recommend[i];
+               for (j = 0; j < ei->recommendsize[i]; j++) {
+                       if (cs->type != recommend[j].type)
+                               continue;
+                       if (cs->final != recommend[j].final)
+                               continue;
+                       if (cs->interm != recommend[j].interm)
+                               continue;
+
+                       return i;
+               }
+       }
+
+       /* then, try a wildcard match over final char. */
+       for (i = 0; i < 4; i++) {
+               recommend = ei->recommend[i];
+               for (j = 0; j < ei->recommendsize[i]; j++) {
+                       if (cs->type != recommend[j].type)
+                               continue;
+                       if (cs->final && (cs->final != recommend[j].final))
+                               continue;
+                       if (cs->interm && (cs->interm != recommend[j].interm))
+                               continue;
+
+                       return i;
+               }
+       }
+
+       /* there's no recommendation. make a guess. */
+       if (ei->maxcharset == 0) {
+               return 0;
+       } else {
+               switch (cs->type) {
+               case CS94:
+               case CS94MULTI:
+                       return 0;
+               case CS96:
+               case CS96MULTI:
+                       return 1;
+               }
+       }
+       return 0;
+}
+
+static int
+_ISO2022_sputwchar(_ISO2022EncodingInfo * __restrict ei, wchar_t wc,
+                  char * __restrict string, size_t n,
+                  char ** __restrict result,
+                  _ISO2022State * __restrict psenc,
+                  size_t * __restrict nresult)
+{
+       int i = 0;
+       size_t len;
+       _ISO2022Charset cs;
+       char *p;
+       char tmp[MB_LEN_MAX];
+       int target;
+       u_char mask;
+       int bit8;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(string != NULL);
+       /* result may be NULL */
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (isc0(wc & 0xff)) {
+               /* go back to INIT0 or ASCII on control chars */
+               cs = ei->initg[0].final ? ei->initg[0] : ascii;
+       } else if (isc1(wc & 0xff)) {
+               /* go back to INIT1 or ISO-8859-1 on control chars */
+               cs = ei->initg[1].final ? ei->initg[1] : iso88591;
+       } else if (!(wc & ~0xff)) {
+               if (wc & 0x80) {
+                       /* special treatment for ISO-8859-1 */
+                       cs = iso88591;
+               } else {
+                       /* special treatment for ASCII */
+                       cs = ascii;
+               }
+       } else {
+               cs.final = (wc >> 24) & 0x7f;
+               if ((wc >> 16) & 0x80)
+                       cs.interm = (wc >> 16) & 0x7f;
+               else
+                       cs.interm = '\0';
+               if (wc & 0x80)
+                       cs.type = (wc & 0x00007f00) ? CS96MULTI : CS96;
+               else
+                       cs.type = (wc & 0x00007f00) ? CS94MULTI : CS94;
+       }
+       target = recommendation(ei, &cs);
+       p = tmp;
+       bit8 = ei->flags & F_8BIT;
+
+       /* designate the charset onto the target plane(G0/1/2/3). */
+       if (psenc->g[target].type == cs.type
+        && psenc->g[target].final == cs.final
+        && psenc->g[target].interm == cs.interm)
+               goto planeok;
+
+       *p++ = '\033';
+       if (cs.type == CS94MULTI || cs.type == CS96MULTI)
+               *p++ = '$';
+       if (target == 0 && cs.type == CS94MULTI && strchr("@AB", cs.final)
+        && !cs.interm && !(ei->flags & F_NOOLD))
+               ;
+       else if (cs.type == CS94 || cs.type == CS94MULTI)
+               *p++ = "()*+"[target];
+       else
+               *p++ = ",-./"[target];
+       if (cs.interm)
+               *p++ = cs.interm;
+       *p++ = cs.final;
+
+       psenc->g[target].type = cs.type;
+       psenc->g[target].final = cs.final;
+       psenc->g[target].interm = cs.interm;
+
+planeok:
+       /* invoke the plane onto GL or GR. */
+       if (psenc->gl == target)
+               goto sideok;
+       if (bit8 && psenc->gr == target)
+               goto sideok;
+
+       if (target == 0 && (ei->flags & F_LS0)) {
+               *p++ = '\017';
+               psenc->gl = 0;
+       } else if (target == 1 && (ei->flags & F_LS1)) {
+               *p++ = '\016';
+               psenc->gl = 1;
+       } else if (target == 2 && (ei->flags & F_LS2)) {
+               *p++ = '\033';
+               *p++ = 'n';
+               psenc->gl = 2;
+       } else if (target == 3 && (ei->flags & F_LS3)) {
+               *p++ = '\033';
+               *p++ = 'o';
+               psenc->gl = 3;
+       } else if (bit8 && target == 1 && (ei->flags & F_LS1R)) {
+               *p++ = '\033';
+               *p++ = '~';
+               psenc->gr = 1;
+       } else if (bit8 && target == 2 && (ei->flags & F_LS2R)) {
+               *p++ = '\033';
+               /*{*/
+               *p++ = '}';
+               psenc->gr = 2;
+       } else if (bit8 && target == 3 && (ei->flags & F_LS3R)) {
+               *p++ = '\033';
+               *p++ = '|';
+               psenc->gr = 3;
+       } else if (target == 2 && (ei->flags & F_SS2)) {
+               *p++ = '\033';
+               *p++ = 'N';
+               psenc->singlegl = 2;
+       } else if (target == 3 && (ei->flags & F_SS3)) {
+               *p++ = '\033';
+               *p++ = 'O';
+               psenc->singlegl = 3;
+       } else if (bit8 && target == 2 && (ei->flags & F_SS2R)) {
+               *p++ = '\216';
+               *p++ = 'N';
+               psenc->singlegl = psenc->singlegr = 2;
+       } else if (bit8 && target == 3 && (ei->flags & F_SS3R)) {
+               *p++ = '\217';
+               *p++ = 'O';
+               psenc->singlegl = psenc->singlegr = 3;
+       } else
+               goto ilseq;
+
+sideok:
+       if (psenc->singlegl == target)
+               mask = 0x00;
+       else if (psenc->singlegr == target)
+               mask = 0x80;
+       else if (psenc->gl == target)
+               mask = 0x00;
+       else if ((ei->flags & F_8BIT) && psenc->gr == target)
+               mask = 0x80;
+       else
+               goto ilseq;
+
+       switch (cs.type) {
+       case CS94:
+       case CS96:
+               i = 1;
+               break;
+       case CS94MULTI:
+       case CS96MULTI:
+               i = !iscntl(wc & 0xff) ?
+                   (isthree(cs.final) ? 3 : 2) : 1;
+               break;
+       }
+       while (i-- > 0)
+               *p++ = ((wc >> (i << 3)) & 0x7f) | mask;
+
+       /* reset single shift state */
+       psenc->singlegl = psenc->singlegr = -1;
+
+       len = (size_t)(p - tmp);
+       if (n < len) {
+               if (result)
+                       *result = (char *)0;
+               *nresult = (size_t)-1;
+               return E2BIG;
+       }
+       if (result)
+               *result = string + len;
+       memcpy(string, tmp, len);
+       *nresult = len;
+
+       return 0;
+
+ilseq:
+       *nresult = (size_t)-1;
+       return EILSEQ;
+}
+
+static int
+_citrus_ISO2022_put_state_reset(_ISO2022EncodingInfo * __restrict ei,
+                               char * __restrict s, size_t n,
+                               _ISO2022State * __restrict psenc,
+                               size_t * __restrict nresult)
+{
+       char buf[MB_LEN_MAX];
+       char *result;
+       int ret;
+       size_t len;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(s != NULL);
+
+       /* XXX state will be modified after this operation... */
+       ret = _ISO2022_sputwchar(ei, L'\0', buf, sizeof(buf), &result, psenc,
+           &len);
+       if (ret) {
+               *nresult = len;
+               return ret;
+       }
+
+       if (sizeof(buf) < len || n < len-1) {
+               /* XXX should recover state? */
+               *nresult = (size_t)-1;
+               return E2BIG;
+       }
+
+       memcpy(s, buf, len-1);
+       *nresult = len-1;
+       return (0);
+}
+
+static int
+_citrus_ISO2022_wcrtomb_priv(_ISO2022EncodingInfo * __restrict ei,
+                            char * __restrict s, size_t n, wchar_t wc,
+                            _ISO2022State * __restrict psenc,
+                            size_t * __restrict nresult)
+{
+       char buf[MB_LEN_MAX];
+       char *result;
+       int ret;
+       size_t len;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != 0);
+
+       /* XXX state will be modified after this operation... */
+       ret = _ISO2022_sputwchar(ei, wc, buf, sizeof(buf), &result, psenc,
+           &len);
+       if (ret) {
+               *nresult = len;
+               return ret;
+       }
+
+       if (sizeof(buf) < len || n < len) {
+               /* XXX should recover state? */
+               *nresult = (size_t)-1;
+               return E2BIG;
+       }
+
+       memcpy(s, buf, len);
+       *nresult = len;
+       return (0);
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_ISO2022_stdenc_wctocs(_ISO2022EncodingInfo * __restrict ei,
+                             _csid_t * __restrict csid,
+                             _index_t * __restrict idx, wchar_t wc)
+{
+       wchar_t m, nm;
+
+       _DIAGASSERT(csid != NULL && idx != NULL);
+
+       m = wc & 0x7FFF8080;
+       nm = wc & 0x007F7F7F;
+       if (m & 0x00800000) {
+               nm &= 0x00007F7F;
+       } else {
+               m &= 0x7F008080;
+       }
+       if (nm & 0x007F0000) {
+               /* ^3 mark */
+               m |= 0x007F0000;
+       } else if (nm & 0x00007F00) {
+               /* ^2 mark */
+               m |= 0x00007F00;
+       }
+       *csid = (_csid_t)m;
+       *idx  = (_index_t)nm;
+
+       return (0);
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_ISO2022_stdenc_cstowc(_ISO2022EncodingInfo * __restrict ei,
+                             wchar_t * __restrict wc,
+                             _csid_t csid, _index_t idx)
+{
+
+       _DIAGASSERT(ei != NULL && wc != NULL);
+
+       *wc = (wchar_t)(csid & 0x7F808080) | (wchar_t)idx;
+
+       return (0);
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_ISO2022_stdenc_get_state_desc_generic(_ISO2022EncodingInfo * __restrict ei,
+                                             _ISO2022State * __restrict psenc,
+                                             int * __restrict rstate)
+{
+
+       if (psenc->chlen == 0) {
+               /* XXX: it should distinguish initial and stable. */
+               *rstate = _STDENC_SDGEN_STABLE;
+       } else {
+               if (psenc->ch[0] == '\033')
+                       *rstate = _STDENC_SDGEN_INCOMPLETE_SHIFT;
+               else
+                       *rstate = _STDENC_SDGEN_INCOMPLETE_CHAR;
+       }
+
+       return 0;
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(ISO2022);
+_CITRUS_CTYPE_DEF_OPS(ISO2022);
+
+#include "citrus_ctype_template.h"
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(ISO2022);
+_CITRUS_STDENC_DEF_OPS(ISO2022);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_iso2022.h b/lib/nbsd_libc/citrus/modules/citrus_iso2022.h
new file mode 100644 (file)
index 0000000..e82e0b3
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: citrus_iso2022.h,v 1.2 2003/06/25 09:51:44 tshiozak Exp $      */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_ISO2022_H_
+#define _CITRUS_ISO2022_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(ISO2022);
+_CITRUS_STDENC_GETOPS_FUNC(ISO2022);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_johab.c b/lib/nbsd_libc/citrus/modules/citrus_johab.c
new file mode 100644 (file)
index 0000000..bebf939
--- /dev/null
@@ -0,0 +1,392 @@
+/* $NetBSD: citrus_johab.c,v 1.4 2008/06/14 16:01:07 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2006 Citrus Project,
+ * 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.
+ */
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_johab.c,v 1.4 2008/06/14 16:01:07 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <wchar.h>
+#include <limits.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_johab.h"
+
+/* ----------------------------------------------------------------------
+ * private stuffs used by templates
+ */
+
+typedef struct {
+       int chlen;
+       char ch[2];
+} _JOHABState;
+
+typedef struct {
+       int dummy;
+} _JOHABEncodingInfo;
+
+typedef struct {
+       _JOHABEncodingInfo      ei;
+       struct {
+               /* for future multi-locale facility */
+               _JOHABState     s_mblen;
+               _JOHABState     s_mbrlen;
+               _JOHABState     s_mbrtowc;
+               _JOHABState     s_mbtowc;
+               _JOHABState     s_mbsrtowcs;
+               _JOHABState     s_wcrtomb;
+               _JOHABState     s_wcsrtombs;
+               _JOHABState     s_wctomb;
+       } states;
+} _JOHABCTypeInfo;
+
+#define _CEI_TO_EI(_cei_)              (&(_cei_)->ei)
+#define _CEI_TO_STATE(_cei_, _func_)   (_cei_)->states.s_##_func_
+
+#define _FUNCNAME(m)                   _citrus_JOHAB_##m
+#define _ENCODING_INFO                 _JOHABEncodingInfo
+#define _CTYPE_INFO                    _JOHABCTypeInfo
+#define _ENCODING_STATE                        _JOHABState
+#define _ENCODING_MB_CUR_MAX(_ei_)             2
+#define _ENCODING_IS_STATE_DEPENDENT           0
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       0
+
+
+static __inline void
+/*ARGSUSED*/
+_citrus_JOHAB_init_state(_JOHABEncodingInfo * __restrict ei,
+       _JOHABState * __restrict psenc)
+{
+       /* ei may be null */
+       _DIAGASSERT(psenc != NULL);
+
+       psenc->chlen = 0;
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_JOHAB_pack_state(_JOHABEncodingInfo * __restrict ei,
+       void * __restrict pspriv,
+       const _JOHABState * __restrict psenc)
+{
+       /* ei may be null */
+       _DIAGASSERT(pspriv != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       memcpy(pspriv, (const void *)psenc, sizeof(*psenc));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_JOHAB_unpack_state(_JOHABEncodingInfo * __restrict ei,
+       _JOHABState * __restrict psenc,
+       const void * __restrict pspriv)
+{
+       /* ei may be null */
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(pspriv != NULL);
+
+       memcpy((void *)psenc, pspriv, sizeof(*psenc));
+}
+
+static void
+/*ARGSUSED*/
+_citrus_JOHAB_encoding_module_uninit(_JOHABEncodingInfo *ei)
+{
+       /* ei may be null */
+}
+
+static int
+/*ARGSUSED*/
+_citrus_JOHAB_encoding_module_init(_JOHABEncodingInfo * __restrict ei,
+       const void * __restrict var, size_t lenvar)
+{
+       /* ei may be null */
+       return 0;
+}
+
+static __inline int
+ishangul(int l, int t)
+{
+
+       return (l >= 0x84 && l <= 0xD3) &&
+             ((t >= 0x41 && t <= 0x7E) || (t >= 0x81 && t <= 0xFE));
+}
+
+static __inline int
+isuda(int l, int t)
+{
+       return (l == 0xD8) &&
+              ((t >= 0x31 && t <= 0x7E) || (t >= 0x91 && t <= 0xFE));
+}
+
+static __inline int
+ishanja(int l, int t)
+{
+       return ((l >= 0xD9 && l <= 0xDE) || (l >= 0xE0 && l <= 0xF9)) &&
+              ((t >= 0x31 && t <= 0x7E) || (t >= 0x91 && t <= 0xFE));
+}
+
+static int
+/*ARGSUSED*/
+_citrus_JOHAB_mbrtowc_priv(_JOHABEncodingInfo * __restrict ei,
+       wchar_t * __restrict pwc, const char ** __restrict s, size_t n,
+       _JOHABState * __restrict psenc, size_t * __restrict nresult)
+{
+       const char *s0;
+       int l, t;
+
+       /* ei may be unused */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != 0);
+
+       if (*s == NULL) {
+               _citrus_JOHAB_init_state(ei, psenc);
+               *nresult = _ENCODING_IS_STATE_DEPENDENT;
+               return 0;
+       } 
+       s0 = *s;
+
+       switch (psenc->chlen) {
+       case 0:
+               if (n-- < 1)
+                       goto restart;
+               l = *s0++ & 0xFF;
+               if (l <= 0x7F) {
+                       if (pwc != NULL)
+                               *pwc = (wchar_t)l;
+                       *nresult = (l == 0) ? 0 : 1;
+                       *s = s0;
+                       return 0;
+               }
+               psenc->ch[psenc->chlen++] = l;
+               break;
+       case 1:
+               l = psenc->ch[0] & 0xFF;
+               break;
+       default:
+               return EINVAL;
+       }
+       if (n-- < 1) {
+restart:
+               *nresult = (size_t)-2;
+               *s = s0;
+               return 0;
+       }
+       t = *s0++ & 0xFF;
+       if (!ishangul(l, t) && !isuda(l, t) && !ishanja(l, t)) {
+               *nresult = (size_t)-1;
+               return EILSEQ;
+       }
+       if (pwc != NULL)
+               *pwc = (wchar_t)(l << 8 | t);
+       *nresult = s0 - *s;
+       *s = s0;
+       psenc->chlen = 0;
+
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_JOHAB_wcrtomb_priv(_JOHABEncodingInfo * __restrict ei,
+       char * __restrict s, size_t n, wchar_t wc,
+       _JOHABState * __restrict psenc, size_t * __restrict nresult)
+{
+       int l, t;
+
+       /* ei may be unused */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (psenc->chlen != 0)
+               return EINVAL;
+
+       /* XXX assume wchar_t as int */
+       if ((uint32_t)wc <= 0x7F) {
+               if (n < 1)
+                       goto e2big;
+               *s = wc & 0xFF;
+               *nresult = 1;
+       } else if ((uint32_t)wc <= 0xFFFF) {
+               if (n < 2) {
+e2big:
+                       *nresult = (size_t)-1;
+                       return E2BIG;
+               }
+               l = (wc >> 8) & 0xFF;
+               t = wc & 0xFF;
+               if (!ishangul(l, t) && !isuda(l, t) && !ishanja(l, t))
+                       goto ilseq;
+               *s++ = l;
+               *s = t;
+               *nresult = 2;
+       } else {
+ilseq:
+               *nresult = (size_t)-1;
+               return EILSEQ;
+       }
+       return 0;
+
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_JOHAB_stdenc_wctocs(_JOHABEncodingInfo * __restrict ei,
+       _csid_t * __restrict csid, _index_t * __restrict idx, wchar_t wc)
+{
+       int m, l, t, linear;
+
+       /* ei may be unused */
+       _DIAGASSERT(csid != NULL);
+       _DIAGASSERT(idx != NULL);
+
+       /* XXX assume wchar_t as int */
+       if ((uint32_t)wc <= 0x7F) {
+               *idx = (_index_t)wc;
+               *csid = 0;
+       } else if ((uint32_t)wc <= 0xFFFF) {
+               l = (wc >> 8) & 0xFF;
+               t = wc & 0xFF;
+               if (ishangul(l, t) || isuda(l, t)) {
+                       *idx = (_index_t)wc;
+                       *csid = 1;
+               } else {
+                       if (l >= 0xD9 && l <= 0xDE) {
+                               linear = l - 0xD9;
+                               m = 0x21;
+                       } else if (l >= 0xE0 && l <= 0xF9) {
+                               linear = l - 0xE0;
+                               m = 0x4A;
+                       } else {
+                               return EILSEQ;
+                       }
+                       linear *= 188;
+                       if (t >= 0x31 && t <= 0x7E) {
+                               linear += t - 0x31;
+                       } else if (t >= 0x91 && t <= 0xFE) {
+                               linear += t - 0x43;
+                       } else {
+                               return EILSEQ;
+                       }
+                       l = (linear / 94) + m;
+                       t = (linear % 94) + 0x21;
+                       *idx = (_index_t)((l << 8) | t);
+                       *csid = 2;
+               }
+       } else {
+               return EILSEQ;
+       }
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_JOHAB_stdenc_cstowc(_JOHABEncodingInfo * __restrict ei,
+       wchar_t * __restrict wc, _csid_t csid, _index_t idx)
+{
+       int m, n, l, t, linear;
+
+       /* ei may be unused */
+       _DIAGASSERT(wc != NULL);
+
+       switch (csid) {
+       case 0:
+       case 1:
+               *wc = (wchar_t)idx;
+               break;
+       case 2:
+               if (idx >= 0x2121 && idx <= 0x2C71) {
+                       m = 0xD9;
+                       n = 0x21;
+               } else if (idx >= 0x4A21 && idx <= 0x7D7E) {
+                       m = 0xE0;
+                       n = 0x4A;
+               } else {
+                       return EILSEQ;
+               }
+               l = ((idx >> 8) & 0xFF) - n;
+               t = (idx & 0xFF) - 0x21;
+               linear = (l * 94) + t;
+               l = (linear / 188) + m;
+               t = linear % 188;
+               t += (t <= 0x4D) ? 0x31 : 0x43;
+               break;
+       default:
+               return EILSEQ;
+       }
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_JOHAB_stdenc_get_state_desc_generic(_JOHABEncodingInfo * __restrict ei,
+       _JOHABState * __restrict psenc, int * __restrict rstate)
+{
+       /* ei may be unused */
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(rstate != NULL);
+
+       *rstate = (psenc->chlen == 0)
+           ? _STDENC_SDGEN_INITIAL
+           : _STDENC_SDGEN_INCOMPLETE_CHAR;
+       return 0;
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(JOHAB);
+_CITRUS_CTYPE_DEF_OPS(JOHAB);
+
+#include "citrus_ctype_template.h"
+
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(JOHAB);
+_CITRUS_STDENC_DEF_OPS(JOHAB);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_johab.h b/lib/nbsd_libc/citrus/modules/citrus_johab.h
new file mode 100644 (file)
index 0000000..f3878ad
--- /dev/null
@@ -0,0 +1,37 @@
+/* $NetBSD: citrus_johab.h,v 1.1 2006/10/18 17:54:55 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2006 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_JOHAB_H_
+#define _CITRUS_JOHAB_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(JOHAB);
+_CITRUS_STDENC_GETOPS_FUNC(JOHAB);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mapper_646.c b/lib/nbsd_libc/citrus/modules/citrus_mapper_646.c
new file mode 100644 (file)
index 0000000..14e6fd2
--- /dev/null
@@ -0,0 +1,259 @@
+/*     $NetBSD: citrus_mapper_646.c,v 1.4 2003/07/14 11:37:49 tshiozak Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_mapper_646.c,v 1.4 2003/07/14 11:37:49 tshiozak Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <sys/queue.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_module.h"
+#include "citrus_region.h"
+#include "citrus_memstream.h"
+#include "citrus_mmap.h"
+#include "citrus_hash.h"
+#include "citrus_mapper.h"
+#include "citrus_mapper_646.h"
+
+/* ---------------------------------------------------------------------- */
+
+_CITRUS_MAPPER_DECLS(mapper_646);
+_CITRUS_MAPPER_DEF_OPS(mapper_646);
+
+/* ---------------------------------------------------------------------- */
+
+#define ILSEQ  0xFFFFFFFE
+#define INVALID        0xFFFFFFFF
+#define SPECIALS(x)                            \
+       x(0x23)                                 \
+       x(0x24)                                 \
+       x(0x40)                                 \
+       x(0x5B)                                 \
+       x(0x5C)                                 \
+       x(0x5D)                                 \
+       x(0x5E)                                 \
+       x(0x60)                                 \
+       x(0x7B)                                 \
+       x(0x7C)                                 \
+       x(0x7D)                                 \
+       x(0x7E)
+
+#define INDEX(x) INDEX_##x,
+
+enum {
+       SPECIALS(INDEX)
+       NUM_OF_SPECIALS
+};
+struct _citrus_mapper_646 {
+       int             m6_forward;
+       _index_t        m6_map[NUM_OF_SPECIALS];
+};
+
+int
+_citrus_mapper_646_mapper_getops(struct _citrus_mapper_ops *ops,
+                                size_t lenops, uint32_t expected_version)
+{
+       if (expected_version<_CITRUS_MAPPER_ABI_VERSION || lenops<sizeof(*ops))
+               return EINVAL;
+
+       memcpy(ops, &_citrus_mapper_646_mapper_ops,
+              sizeof(_citrus_mapper_646_mapper_ops));
+
+       return 0;
+}
+
+#define T_COMM '#'
+static int
+parse_file(struct _citrus_mapper_646 *m6, const char *path)
+{
+       int ret, i;
+       struct _region r;
+       struct _memstream ms;
+       const char *p;
+       size_t len;
+       char buf[PATH_MAX];
+
+       ret = _map_file(&r, path);
+       if (ret)
+               return ret;
+       _memstream_bind(&ms, &r);
+       for (i=0; i<NUM_OF_SPECIALS; i++) {
+retry:
+               p = _memstream_getln(&ms, &len);
+               if (p==NULL) {
+                       ret = EINVAL;
+                       break;
+               }
+               p = _bcs_skip_ws_len(p, &len);
+               if (*p == T_COMM || len==0)
+                       goto retry;
+               if (!_bcs_isdigit(*p)) {
+                       ret = EINVAL;
+                       break;
+               }
+               snprintf(buf, sizeof(buf), "%.*s", (int)len, p);
+               m6->m6_map[i] = strtoul(buf, (char **)&p, 0);
+               p = _bcs_skip_ws(buf);
+               if (*p != T_COMM && !*p) {
+                       ret = EINVAL;
+                       break;
+               }
+       }
+       _unmap_file(&r);
+
+       return ret;
+};
+
+static int
+parse_var(struct _citrus_mapper_646 *m6, struct _memstream *ms,
+         const char *dir)
+{
+       struct _region r;
+       char path[PATH_MAX];
+
+       m6->m6_forward = 1;
+       _memstream_skip_ws(ms);
+       /* whether backward */
+       if (_memstream_peek(ms) == '!') {
+               _memstream_getc(ms);
+               m6->m6_forward = 0;
+       }
+       /* get description file path */
+       _memstream_getregion(ms, &r, _memstream_remainder(ms));
+       snprintf(path, sizeof(path), "%s/%.*s",
+                dir, (int)_region_size(&r), (char *)_region_head(&r));
+       /* remove trailing white spaces */
+       path[_bcs_skip_nonws(path)-path] = '\0';
+       return parse_file(m6, path);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_mapper_646_mapper_init(struct _citrus_mapper_area *__restrict ma,
+                              struct _citrus_mapper * __restrict cm,
+                              const char * __restrict dir,
+                              const void * __restrict var, size_t lenvar,
+                              struct _citrus_mapper_traits * __restrict mt,
+                              size_t lenmt)
+{
+       struct _citrus_mapper_646 *m6;
+       struct _memstream ms;
+       struct _region r;
+       int ret;
+
+       _DIAGASSERT(cm && dir && mt);
+
+       if (lenmt<sizeof(*mt))
+               return EINVAL;
+
+       m6 = malloc(sizeof(*m6));
+       if (m6 == NULL)
+               return errno;
+
+       _region_init(&r, (void *)var, lenvar);
+       _memstream_bind(&ms, &r);
+       ret = parse_var(m6, &ms, dir);
+       if (ret) {
+               free(m6);
+               return ret;
+       }
+
+       cm->cm_closure = m6;
+       mt->mt_src_max = mt->mt_dst_max = 1;    /* 1:1 converter */
+       mt->mt_state_size = 0;                  /* stateless */
+
+       return 0;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_mapper_646_mapper_uninit(struct _citrus_mapper *cm)
+{
+       if (cm && cm->cm_closure) {
+               free(cm->cm_closure);
+       }
+}
+
+static int
+/*ARGSUSED*/
+_citrus_mapper_646_mapper_convert(struct _citrus_mapper * __restrict cm,
+                                 _index_t * __restrict dst, _index_t src,
+                                 void * __restrict ps)
+{
+       struct _citrus_mapper_646 *m6;
+
+       _DIAGASSERT(cm && cm->cm_closure);
+
+       m6 = cm->cm_closure;
+       if (m6->m6_forward) {
+               /* forward */
+               if (src>=0x80)
+                       return _MAPPER_CONVERT_ILSEQ;
+#define FORWARD(x)                                     \
+if (src==(x)) {                                                \
+       if (m6->m6_map[INDEX_##x]==INVALID)             \
+               return _MAPPER_CONVERT_NONIDENTICAL;    \
+       *dst = m6->m6_map[INDEX_##x];                   \
+       return 0;                                       \
+} else
+               SPECIALS(FORWARD);
+               *dst = src;
+       } else {
+               /* backward */
+#define BACKWARD(x)                                                    \
+if (m6->m6_map[INDEX_##x]!=INVALID && src==m6->m6_map[INDEX_##x]) {    \
+       *dst = (x);                                                     \
+       return 0;                                                       \
+} else if (src==(x))                                                   \
+       return _MAPPER_CONVERT_ILSEQ;                                   \
+else
+               SPECIALS(BACKWARD);
+               if (src>=0x80)
+                       return _MAPPER_CONVERT_NONIDENTICAL;
+               *dst = src;
+       }
+
+       return _MAPPER_CONVERT_SUCCESS;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_mapper_646_mapper_init_state(struct _citrus_mapper * __restrict cm,
+                                    void * __restrict ps)
+{
+}
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mapper_646.h b/lib/nbsd_libc/citrus/modules/citrus_mapper_646.h
new file mode 100644 (file)
index 0000000..cdacae0
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: citrus_mapper_646.h,v 1.1 2003/06/25 09:51:45 tshiozak Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_MAPPER_646_H_
+#define _CITRUS_MAPPER_646_H_
+
+__BEGIN_DECLS
+_CITRUS_MAPPER_GETOPS_FUNC(mapper_646);
+_CITRUS_MAPPER_GETOPS_FUNC(mapper_646);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mapper_none.c b/lib/nbsd_libc/citrus/modules/citrus_mapper_none.c
new file mode 100644 (file)
index 0000000..12b3141
--- /dev/null
@@ -0,0 +1,111 @@
+/*     $NetBSD: citrus_mapper_none.c,v 1.2 2003/06/27 17:53:31 tshiozak Exp $  */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_mapper_none.c,v 1.2 2003/06/27 17:53:31 tshiozak Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/queue.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_hash.h"
+#include "citrus_mapper.h"
+#include "citrus_mapper_none.h"
+
+/* ---------------------------------------------------------------------- */
+
+_CITRUS_MAPPER_DECLS(mapper_none);
+_CITRUS_MAPPER_DEF_OPS(mapper_none);
+
+
+/* ---------------------------------------------------------------------- */
+
+int
+_citrus_mapper_none_mapper_getops(struct _citrus_mapper_ops *ops,
+                                 size_t lenops, uint32_t expected_version)
+{
+       if (expected_version<_CITRUS_MAPPER_ABI_VERSION || lenops<sizeof(*ops))
+               return (EINVAL);
+
+       memcpy(ops, &_citrus_mapper_none_mapper_ops,
+              sizeof(_citrus_mapper_none_mapper_ops));
+
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_mapper_none_mapper_init(struct _citrus_mapper_area *__restrict ma,
+                               struct _citrus_mapper * __restrict cm,
+                               const char * __restrict dir,
+                               const void * __restrict var, size_t lenvar,
+                               struct _citrus_mapper_traits * __restrict mt,
+                               size_t lenmt)
+{
+
+       _DIAGASSERT(cm && dir && mt);
+
+       if (lenmt<sizeof(*mt))
+               return (EINVAL);
+
+       cm->cm_closure = NULL;
+       mt->mt_src_max = mt->mt_dst_max = 1;    /* 1:1 converter */
+       mt->mt_state_size = 0;                  /* stateless */
+
+       return 0;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_mapper_none_mapper_uninit(struct _citrus_mapper *cm)
+{
+}
+
+static int
+/*ARGSUSED*/
+_citrus_mapper_none_mapper_convert(struct _citrus_mapper * __restrict cm,
+                                  _citrus_index_t * __restrict dst,
+                                  _citrus_index_t src, void * __restrict ps)
+{
+       *dst = src;
+       return _CITRUS_MAPPER_CONVERT_SUCCESS;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_mapper_none_mapper_init_state(struct _citrus_mapper * __restrict cm,
+                                     void * __restrict ps)
+{
+}
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mapper_none.h b/lib/nbsd_libc/citrus/modules/citrus_mapper_none.h
new file mode 100644 (file)
index 0000000..c0d6a71
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: citrus_mapper_none.h,v 1.1 2003/06/25 09:51:45 tshiozak Exp $  */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_MAPPER_NONE_H_
+#define _CITRUS_MAPPER_NONE_H_
+
+__BEGIN_DECLS
+_CITRUS_MAPPER_GETOPS_FUNC(mapper_none);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mapper_serial.c b/lib/nbsd_libc/citrus/modules/citrus_mapper_serial.c
new file mode 100644 (file)
index 0000000..be006b5
--- /dev/null
@@ -0,0 +1,263 @@
+/*     $NetBSD: citrus_mapper_serial.c,v 1.2 2003/07/12 15:39:20 tshiozak Exp $        */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_mapper_serial.c,v 1.2 2003/07/12 15:39:20 tshiozak Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <sys/queue.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_module.h"
+#include "citrus_region.h"
+#include "citrus_memstream.h"
+#include "citrus_mmap.h"
+#include "citrus_hash.h"
+#include "citrus_mapper.h"
+#include "citrus_mapper_serial.h"
+
+/* ---------------------------------------------------------------------- */
+
+_CITRUS_MAPPER_DECLS(mapper_serial);
+_CITRUS_MAPPER_DEF_OPS(mapper_serial);
+
+#define _citrus_mapper_parallel_mapper_init            \
+       _citrus_mapper_serial_mapper_init
+#define _citrus_mapper_parallel_mapper_uninit          \
+       _citrus_mapper_serial_mapper_uninit
+#define _citrus_mapper_parallel_mapper_init_state      \
+       _citrus_mapper_serial_mapper_init_state
+static int     _citrus_mapper_parallel_mapper_convert(
+       struct _citrus_mapper * __restrict, _index_t * __restrict, _index_t,
+       void * __restrict);
+_CITRUS_MAPPER_DEF_OPS(mapper_parallel);
+#undef _citrus_mapper_parallel_mapper_init
+#undef _citrus_mapper_parallel_mapper_uninit
+#undef _citrus_mapper_parallel_mapper_init_state
+
+
+/* ---------------------------------------------------------------------- */
+
+struct maplink {
+       SIMPLEQ_ENTRY(maplink)  ml_entry;
+       struct _mapper          *ml_mapper;
+};
+SIMPLEQ_HEAD(maplist, maplink);
+
+struct _citrus_mapper_serial {
+       struct maplist  sr_mappers;
+};
+
+int
+_citrus_mapper_serial_mapper_getops(struct _citrus_mapper_ops *ops,
+                                   size_t lenops, uint32_t expected_version)
+{
+       if (expected_version<_CITRUS_MAPPER_ABI_VERSION || lenops<sizeof(*ops))
+               return EINVAL;
+
+       memcpy(ops, &_citrus_mapper_serial_mapper_ops,
+              sizeof(_citrus_mapper_serial_mapper_ops));
+
+       return 0;
+}
+
+int
+_citrus_mapper_parallel_mapper_getops(struct _citrus_mapper_ops *ops,
+                                     size_t lenops, uint32_t expected_version)
+{
+       if (expected_version<_CITRUS_MAPPER_ABI_VERSION || lenops<sizeof(*ops))
+               return EINVAL;
+
+       memcpy(ops, &_citrus_mapper_parallel_mapper_ops,
+              sizeof(_citrus_mapper_parallel_mapper_ops));
+
+       return 0;
+}
+
+static void
+uninit(struct _citrus_mapper_serial *sr)
+{
+       struct maplink *ml;
+
+       while ((ml = SIMPLEQ_FIRST(&sr->sr_mappers)) != NULL) {
+               SIMPLEQ_REMOVE_HEAD(&sr->sr_mappers, ml_entry);
+               _mapper_close(ml->ml_mapper);
+               free(ml);
+       }
+}
+
+static int
+parse_var(struct _citrus_mapper_area *__restrict ma,
+         struct _citrus_mapper_serial *sr, struct _memstream *ms)
+{
+       int ret;
+       struct _region r;
+       char mapname[PATH_MAX];
+       struct maplink *ml;
+
+       SIMPLEQ_INIT(&sr->sr_mappers);
+       while (1) {
+               /* remove beginning white spaces */
+               _memstream_skip_ws(ms);
+               if (_memstream_iseof(ms))
+                       break;
+               /* cut down a mapper name */
+               _memstream_chr(ms, &r, ',');
+               snprintf(mapname, sizeof(mapname), "%.*s",
+                        (int)_region_size(&r), (char *)_region_head(&r));
+               /* remove trailing white spaces */
+               mapname[_bcs_skip_nonws(mapname)-mapname] = '\0';
+               /* create a new mapper record */
+               ml = malloc(sizeof(*ml));
+               if (ml == NULL)
+                       return errno;
+               ret = _mapper_open(ma, &ml->ml_mapper, mapname);
+               if (ret) {
+                       free(ml);
+                       return ret;
+               }
+               /* support only 1:1 and stateless converter */
+               if (_mapper_get_src_max(ml->ml_mapper) != 1 ||
+                   _mapper_get_dst_max(ml->ml_mapper) != 1 ||
+                   _mapper_get_state_size(ml->ml_mapper) != 0) {
+                       free(ml);
+                       return EINVAL;
+               }
+               SIMPLEQ_INSERT_TAIL(&sr->sr_mappers, ml, ml_entry);
+       }
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_mapper_serial_mapper_init(struct _citrus_mapper_area *__restrict ma,
+                                 struct _citrus_mapper * __restrict cm,
+                                 const char * __restrict dir,
+                                 const void * __restrict var, size_t lenvar,
+                                 struct _citrus_mapper_traits * __restrict mt,
+                                 size_t lenmt)
+{
+       struct _citrus_mapper_serial *sr;
+       struct _memstream ms;
+       struct _region r;
+
+       _DIAGASSERT(cm && dir && mt);
+
+       if (lenmt<sizeof(*mt))
+               return EINVAL;
+
+       sr = malloc(sizeof(*sr));
+       if (sr == NULL)
+               return errno;
+
+       _region_init(&r, (void *)var, lenvar);
+       _memstream_bind(&ms, &r);
+       if (parse_var(ma, sr, &ms)) {
+               uninit(sr);
+               free(sr);
+               return EINVAL;
+       }
+       cm->cm_closure = sr;
+       mt->mt_src_max = mt->mt_dst_max = 1;    /* 1:1 converter */
+       mt->mt_state_size = 0;                  /* stateless */
+
+       return 0;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_mapper_serial_mapper_uninit(struct _citrus_mapper *cm)
+{
+       if (cm && cm->cm_closure) {
+               uninit(cm->cm_closure);
+               free(cm->cm_closure);
+       }
+}
+
+static int
+/*ARGSUSED*/
+_citrus_mapper_serial_mapper_convert(struct _citrus_mapper * __restrict cm,
+                                    _index_t * __restrict dst, _index_t src,
+                                    void * __restrict ps)
+{
+       int ret;
+       struct _citrus_mapper_serial *sr;
+       struct maplink *ml;
+
+       _DIAGASSERT(cm && cm->cm_closure);
+
+       sr = cm->cm_closure;
+       SIMPLEQ_FOREACH(ml, &sr->sr_mappers, ml_entry) {
+               ret = _mapper_convert(ml->ml_mapper, &src, src, NULL);
+               if (ret != _MAPPER_CONVERT_SUCCESS)
+                       return ret;
+       }
+       *dst = src;
+       return _MAPPER_CONVERT_SUCCESS;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_mapper_parallel_mapper_convert(struct _citrus_mapper * __restrict cm,
+                                      _index_t * __restrict dst, _index_t src,
+                                      void * __restrict ps)
+{
+       int ret;
+       struct _citrus_mapper_serial *sr;
+       struct maplink *ml;
+       _index_t tmp;
+
+       _DIAGASSERT(cm && cm->cm_closure);
+
+       sr = cm->cm_closure;
+       SIMPLEQ_FOREACH(ml, &sr->sr_mappers, ml_entry) {
+               ret = _mapper_convert(ml->ml_mapper, &tmp, src, NULL);
+               if (ret == _MAPPER_CONVERT_SUCCESS) {
+                       *dst = tmp;
+                       return _MAPPER_CONVERT_SUCCESS;
+               } else if (ret == _MAPPER_CONVERT_ILSEQ)
+                       return _MAPPER_CONVERT_ILSEQ;
+       }
+       return _MAPPER_CONVERT_NONIDENTICAL;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_mapper_serial_mapper_init_state(struct _citrus_mapper * __restrict cm,
+                                       void * __restrict ps)
+{
+}
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mapper_serial.h b/lib/nbsd_libc/citrus/modules/citrus_mapper_serial.h
new file mode 100644 (file)
index 0000000..107f0ed
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: citrus_mapper_serial.h,v 1.1 2003/06/25 09:51:46 tshiozak Exp $        */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_MAPPER_SERIAL_H_
+#define _CITRUS_MAPPER_SERIAL_H_
+
+__BEGIN_DECLS
+_CITRUS_MAPPER_GETOPS_FUNC(mapper_serial);
+_CITRUS_MAPPER_GETOPS_FUNC(mapper_parallel);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mapper_std.c b/lib/nbsd_libc/citrus/modules/citrus_mapper_std.c
new file mode 100644 (file)
index 0000000..7d49f5f
--- /dev/null
@@ -0,0 +1,461 @@
+/*     $NetBSD: citrus_mapper_std.c,v 1.8 2006/09/11 13:06:33 tnozaki Exp $    */
+
+/*-
+ * Copyright (c)2003, 2006 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_mapper_std.c,v 1.8 2006/09/11 13:06:33 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#include <machine/endian.h>
+#include <sys/queue.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_mmap.h"
+#include "citrus_module.h"
+#include "citrus_hash.h"
+#include "citrus_mapper.h"
+#include "citrus_db.h"
+#include "citrus_db_hash.h"
+
+#include "citrus_mapper_std.h"
+#include "citrus_mapper_std_file.h"
+
+/* ---------------------------------------------------------------------- */
+
+_CITRUS_MAPPER_DECLS(mapper_std);
+_CITRUS_MAPPER_DEF_OPS(mapper_std);
+
+
+/* ---------------------------------------------------------------------- */
+
+int
+_citrus_mapper_std_mapper_getops(struct _citrus_mapper_ops *ops, size_t lenops,
+                                u_int32_t expected_version)
+{
+       if (expected_version<_CITRUS_MAPPER_ABI_VERSION || lenops<sizeof(*ops))
+               return (EINVAL);
+
+       memcpy(ops, &_citrus_mapper_std_mapper_ops,
+              sizeof(_citrus_mapper_std_mapper_ops));
+
+       return (0);
+}
+
+/* ---------------------------------------------------------------------- */
+
+static int
+/*ARGSUSED*/
+rowcol_convert(struct _citrus_mapper_std * __restrict ms,
+              _index_t * __restrict dst, _index_t src,
+              void * __restrict ps)
+{
+       struct _citrus_mapper_std_rowcol *rc;
+       size_t i;
+       struct _citrus_mapper_std_linear_zone *lz;
+       _index_t n, idx = 0;
+       u_int32_t conv;
+
+       _DIAGASSERT(ms != NULL);
+       _DIAGASSERT(dst != NULL);
+       /* ps may be unused */
+       rc = &ms->ms_rowcol;
+
+       for (i = rc->rc_src_rowcol_len * rc->rc_src_rowcol_bits,
+            lz = &rc->rc_src_rowcol[0]; i > 0; ++lz) {
+               i -= rc->rc_src_rowcol_bits;
+               n = (src >> i) & rc->rc_src_rowcol_mask;
+               if (n < lz->begin || n > lz->end) {
+                       switch (rc->rc_oob_mode) {
+                       case _CITRUS_MAPPER_STD_OOB_NONIDENTICAL:
+                               *dst = rc->rc_dst_invalid;
+                               return _MAPPER_CONVERT_NONIDENTICAL;
+                       case _CITRUS_MAPPER_STD_OOB_ILSEQ:
+                               return _MAPPER_CONVERT_ILSEQ;
+                       default:
+                               return _MAPPER_CONVERT_FATAL;
+                       }
+               }
+               idx = idx * lz->width + n - lz->begin;
+       }
+       switch (rc->rc_dst_unit_bits) {
+       case 8:
+               conv = _region_peek8(&rc->rc_table, idx);
+               break;
+       case 16:
+               conv = be16toh(_region_peek16(&rc->rc_table, idx*2));
+               break;
+       case 32:
+               conv = be32toh(_region_peek32(&rc->rc_table, idx*4));
+               break;
+       default:
+               return _MAPPER_CONVERT_FATAL;
+       }
+
+       if (conv == rc->rc_dst_invalid) {
+               *dst = rc->rc_dst_invalid;
+               return _MAPPER_CONVERT_NONIDENTICAL;
+       }
+       if (conv == rc->rc_dst_ilseq)
+               return _MAPPER_CONVERT_ILSEQ;
+
+       *dst = conv;
+
+       return _MAPPER_CONVERT_SUCCESS;
+}
+
+static __inline int
+set_linear_zone(struct _citrus_mapper_std_linear_zone *lz,
+       u_int32_t begin, u_int32_t end)
+{
+       _DIAGASSERT(lz != NULL);
+
+       if (begin > end)
+               return EFTYPE;
+
+       lz->begin = begin;
+       lz->end = end;
+       lz->width= end - begin + 1;
+
+       return 0;
+}
+
+static __inline int
+rowcol_parse_variable_compat(struct _citrus_mapper_std_rowcol *rc,
+       struct _region *r)
+{
+       const struct _citrus_mapper_std_rowcol_info_compat_x *rcx;
+       struct _citrus_mapper_std_linear_zone *lz;
+       u_int32_t m, n;
+       int ret;
+
+       _DIAGASSERT(rc != NULL);
+       _DIAGASSERT(r != NULL && _region_size(r) == sizeof(*rcx));
+       rcx = _region_head(r);
+
+       rc->rc_dst_invalid = be32toh(rcx->rcx_dst_invalid);
+       rc->rc_dst_unit_bits = be32toh(rcx->rcx_dst_unit_bits);
+       m = be32toh(rcx->rcx_src_col_bits);
+       n = 1 << (m - 1);
+       n |= n - 1;
+       rc->rc_src_rowcol_bits = m;
+       rc->rc_src_rowcol_mask = n;
+
+       rc->rc_src_rowcol = malloc(2 *
+           sizeof(*rc->rc_src_rowcol));
+       if (rc->rc_src_rowcol == NULL)
+               return ENOMEM;
+       lz = rc->rc_src_rowcol;
+       rc->rc_src_rowcol_len = 1;
+       m = be32toh(rcx->rcx_src_row_begin);
+       n = be32toh(rcx->rcx_src_row_end);
+       if (m + n > 0) {
+               ret = set_linear_zone(lz, m, n);
+               if (ret != 0)
+                       return ret;
+               ++rc->rc_src_rowcol_len, ++lz;
+       }
+       m = be32toh(rcx->rcx_src_col_begin);
+       n = be32toh(rcx->rcx_src_col_end);
+
+       return set_linear_zone(lz, m, n);
+}
+
+static __inline int
+rowcol_parse_variable(struct _citrus_mapper_std_rowcol *rc,
+       struct _region *r)
+{
+       const struct _citrus_mapper_std_rowcol_info_x *rcx;
+       struct _citrus_mapper_std_linear_zone *lz;
+       u_int32_t m, n;
+       size_t i;
+       int ret;
+
+       _DIAGASSERT(rc != NULL);
+       _DIAGASSERT(r != NULL && _region_size(r) == sizeof(*rcx));
+       rcx = _region_head(r);
+
+       rc->rc_dst_invalid = be32toh(rcx->rcx_dst_invalid);
+       rc->rc_dst_unit_bits = be32toh(rcx->rcx_dst_unit_bits);
+
+       m = be32toh(rcx->rcx_src_rowcol_bits);
+       n = 1 << (m - 1);
+       n |= n - 1;
+       rc->rc_src_rowcol_bits = m;
+       rc->rc_src_rowcol_mask = n;
+
+       rc->rc_src_rowcol_len = be32toh(rcx->rcx_src_rowcol_len);
+       if (rc->rc_src_rowcol_len > _CITRUS_MAPPER_STD_ROWCOL_MAX)
+               return EFTYPE;
+       rc->rc_src_rowcol = malloc(rc->rc_src_rowcol_len *
+           sizeof(*rc->rc_src_rowcol));
+       if (rc->rc_src_rowcol == NULL)
+               return ENOMEM;
+       for (i = 0, lz = rc->rc_src_rowcol;
+            i < rc->rc_src_rowcol_len; ++i, ++lz) {
+               m = be32toh(rcx->rcx_src_rowcol[i].begin),
+               n = be32toh(rcx->rcx_src_rowcol[i].end);
+               ret = set_linear_zone(lz, m, n);
+               if (ret != 0) {
+                       free(rc->rc_src_rowcol);
+                       rc->rc_src_rowcol = NULL;
+                       return ret;
+               }
+       }
+       return 0;
+}
+
+static void
+rowcol_uninit(struct _citrus_mapper_std *ms)
+{
+       struct _citrus_mapper_std_rowcol *rc;
+       _DIAGASSERT(ms != NULL);
+
+       rc = &ms->ms_rowcol;
+       free(rc->rc_src_rowcol);
+}
+
+static int
+rowcol_init(struct _citrus_mapper_std *ms)
+{
+       int ret;
+       struct _citrus_mapper_std_rowcol *rc;
+       const struct _citrus_mapper_std_rowcol_ext_ilseq_info_x *eix;
+       struct _region r;
+       u_int64_t table_size;
+       size_t i;
+       struct _citrus_mapper_std_linear_zone *lz;
+
+       _DIAGASSERT(ms != NULL);
+       ms->ms_convert = &rowcol_convert;
+       ms->ms_uninit = &rowcol_uninit;
+       rc = &ms->ms_rowcol;
+
+       /* get table region */
+       ret = _db_lookup_by_s(ms->ms_db, _CITRUS_MAPPER_STD_SYM_TABLE,
+                             &rc->rc_table, NULL);
+       if (ret) {
+               if (ret==ENOENT)
+                       ret = EFTYPE;
+               return ret;
+       }
+
+       /* get table information */
+       ret = _db_lookup_by_s(ms->ms_db, _CITRUS_MAPPER_STD_SYM_INFO, &r, NULL);
+       if (ret) {
+               if (ret==ENOENT)
+                       ret = EFTYPE;
+               return ret;
+       }
+       switch (_region_size(&r)) {
+       case _CITRUS_MAPPER_STD_ROWCOL_INFO_COMPAT_SIZE:
+               ret = rowcol_parse_variable_compat(rc, &r);
+               break;
+       case _CITRUS_MAPPER_STD_ROWCOL_INFO_SIZE:
+               ret = rowcol_parse_variable(rc, &r);
+               break;
+       default:
+               return EFTYPE;
+       }
+       if (ret != 0)
+               return ret;
+       /* sanity check */
+       switch (rc->rc_src_rowcol_bits) {
+       case 8: case 16: case 32:
+               if (rc->rc_src_rowcol_len <= 32 / rc->rc_src_rowcol_bits)
+                       break;
+       /*FALLTHROUGH*/
+       default:
+               return EFTYPE;
+       }
+
+       /* ilseq extension */
+       rc->rc_oob_mode = _CITRUS_MAPPER_STD_OOB_NONIDENTICAL;
+       rc->rc_dst_ilseq = rc->rc_dst_invalid;
+       ret = _db_lookup_by_s(ms->ms_db,
+                             _CITRUS_MAPPER_STD_SYM_ROWCOL_EXT_ILSEQ,
+                             &r, NULL);
+       if (ret && ret != ENOENT)
+               return ret;
+       if (_region_size(&r) < sizeof(*eix))
+               return EFTYPE;
+       if (ret == 0) {
+               eix = _region_head(&r);
+               rc->rc_oob_mode = be32toh(eix->eix_oob_mode);
+               rc->rc_dst_ilseq = be32toh(eix->eix_dst_ilseq);
+       }
+
+       /* calcurate expected table size */
+       i = rc->rc_src_rowcol_len;
+       lz = &rc->rc_src_rowcol[--i];
+       table_size = lz->width;
+       while (i > 0) {
+               lz = &rc->rc_src_rowcol[--i];
+               table_size *= lz->width;
+       }
+       table_size *= rc->rc_dst_unit_bits/8;
+
+       if (table_size > UINT32_MAX ||
+           _region_size(&rc->rc_table) < table_size)
+               return EFTYPE;
+
+       return 0;
+}
+
+typedef int (*initfunc_t)(struct _citrus_mapper_std *);
+static const struct {
+       const char                      *t_name;
+       initfunc_t                      t_init;
+} types[] = {
+       { _CITRUS_MAPPER_STD_TYPE_ROWCOL, &rowcol_init },
+};
+#define NUM_OF_TYPES ((int)(sizeof(types)/sizeof(types[0])))
+
+static int
+/*ARGSUSED*/
+_citrus_mapper_std_mapper_init(struct _citrus_mapper_area *__restrict ma,
+                              struct _citrus_mapper * __restrict cm,
+                              const char * __restrict curdir,
+                              const void * __restrict var, size_t lenvar,
+                              struct _citrus_mapper_traits * __restrict mt,
+                              size_t lenmt)
+{
+       char path[PATH_MAX];
+       const char *type;
+       int ret, id;
+       struct _citrus_mapper_std *ms;
+
+       /* set traits */
+       if (lenmt<sizeof(*mt)) {
+               ret = EINVAL;
+               goto err0;
+       }
+       mt->mt_src_max = mt->mt_dst_max = 1;    /* 1:1 converter */
+       mt->mt_state_size = 0;                  /* stateless */
+
+       /* alloc mapper std structure */
+       ms = malloc(sizeof(*ms));
+       if (ms==NULL) {
+               ret = errno;
+               goto err0;
+       }
+
+       /* open mapper file */
+       snprintf(path, sizeof(path),
+                "%s/%.*s", curdir, (int)lenvar, (const char *)var);
+       ret = _map_file(&ms->ms_file, path);
+       if (ret)
+               goto err1;
+
+       ret = _db_open(&ms->ms_db, &ms->ms_file, _CITRUS_MAPPER_STD_MAGIC,
+                      &_db_hash_std, NULL);
+       if (ret)
+               goto err2;
+
+       /* get mapper type */
+       ret = _db_lookupstr_by_s(ms->ms_db, _CITRUS_MAPPER_STD_SYM_TYPE,
+                                &type, NULL);
+       if (ret) {
+               if (ret==ENOENT)
+                       ret = EFTYPE;
+               goto err3;
+       }
+       for (id=0; id<NUM_OF_TYPES; id++)
+               if (_bcs_strcasecmp(type, types[id].t_name) == 0)
+                       break;
+
+       if (id == NUM_OF_TYPES)
+               goto err3;
+
+       /* init the per-type structure */
+       ret = (*types[id].t_init)(ms);
+       if (ret)
+               goto err3;
+
+       cm->cm_closure = ms;
+
+       return 0;
+
+err3:
+       _db_close(ms->ms_db);
+err2:
+       _unmap_file(&ms->ms_file);
+err1:
+       free(ms);
+err0:
+       return ret;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_mapper_std_mapper_uninit(struct _citrus_mapper *cm)
+{
+       struct _citrus_mapper_std *ms;
+
+       _DIAGASSERT(cm!=NULL & cm->cm_closure!=NULL);
+
+       ms = cm->cm_closure;
+       if (ms->ms_uninit)
+               (*ms->ms_uninit)(ms);
+       _db_close(ms->ms_db);
+       _unmap_file(&ms->ms_file);
+       free(ms);
+}
+
+static void
+/*ARGSUSED*/
+_citrus_mapper_std_mapper_init_state(struct _citrus_mapper * __restrict cm,
+                                    void * __restrict ps)
+{
+}
+
+static int
+/*ARGSUSED*/
+_citrus_mapper_std_mapper_convert(struct _citrus_mapper * __restrict cm,
+                                 _index_t * __restrict dst, _index_t src,
+                                 void * __restrict ps)
+{
+       struct _citrus_mapper_std *ms;
+
+       _DIAGASSERT(cm!=NULL && cm->cm_closure!=NULL);
+
+       ms = cm->cm_closure;
+
+       _DIAGASSERT(ms->ms_convert != NULL);
+
+       return (*ms->ms_convert)(ms, dst, src, ps);
+}
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mapper_std.h b/lib/nbsd_libc/citrus/modules/citrus_mapper_std.h
new file mode 100644 (file)
index 0000000..83eae82
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: citrus_mapper_std.h,v 1.1 2003/06/25 09:51:47 tshiozak Exp $   */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_MAPPER_STD_H_
+#define _CITRUS_MAPPER_STD_H_
+
+#include "citrus_mapper_std_local.h"
+
+__BEGIN_DECLS
+_CITRUS_MAPPER_GETOPS_FUNC(mapper_std);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mapper_std_file.h b/lib/nbsd_libc/citrus/modules/citrus_mapper_std_file.h
new file mode 100644 (file)
index 0000000..c9d17ca
--- /dev/null
@@ -0,0 +1,75 @@
+/*     $NetBSD: citrus_mapper_std_file.h,v 1.3 2006/09/09 14:35:17 tnozaki Exp $       */
+
+/*-
+ * Copyright (c)2003, 2006 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_MAPPER_STD_FILE_H_
+#define _CITRUS_MAPPER_STD_FILE_H_
+
+#define _CITRUS_MAPPER_STD_MAGIC               "MAPPER\0\0"
+
+#define _CITRUS_MAPPER_STD_SYM_TYPE            "type"
+#define _CITRUS_MAPPER_STD_SYM_INFO            "info"
+#define _CITRUS_MAPPER_STD_SYM_TABLE           "table"
+
+#define _CITRUS_MAPPER_STD_TYPE_ROWCOL         "rowcol"
+struct _citrus_mapper_std_rowcol_info_x {
+       u_int32_t               rcx_src_rowcol_bits;
+       u_int32_t               rcx_dst_invalid;
+#define _CITRUS_MAPPER_STD_ROWCOL_MAX                  4
+       struct {
+               u_int32_t               begin;
+               u_int32_t               end;
+       } __packed              rcx_src_rowcol[_CITRUS_MAPPER_STD_ROWCOL_MAX];
+       u_int32_t               rcx_dst_unit_bits;
+       u_int32_t               rcx_src_rowcol_len;
+} __packed;
+#define _CITRUS_MAPPER_STD_ROWCOL_INFO_SIZE            48
+
+/* old file layout */
+struct _citrus_mapper_std_rowcol_info_compat_x {
+       u_int32_t               rcx_src_col_bits;
+       u_int32_t               rcx_dst_invalid;
+       u_int32_t               rcx_src_row_begin;
+       u_int32_t               rcx_src_row_end;
+       u_int32_t               rcx_src_col_begin;
+       u_int32_t               rcx_src_col_end;
+       u_int32_t               rcx_dst_unit_bits;
+       u_int32_t               rcx_pad;
+} __packed;
+#define _CITRUS_MAPPER_STD_ROWCOL_INFO_COMPAT_SIZE     32
+
+/* rowcol oob extension info */
+#define _CITRUS_MAPPER_STD_SYM_ROWCOL_EXT_ILSEQ                "rowcol_ext_ilseq"
+struct _citrus_mapper_std_rowcol_ext_ilseq_info_x {
+#define _CITRUS_MAPPER_STD_OOB_NONIDENTICAL    0
+#define _CITRUS_MAPPER_STD_OOB_ILSEQ           1
+       u_int32_t               eix_oob_mode;
+       u_int32_t               eix_dst_ilseq;
+} __packed;
+#define _CITRUS_MAPPER_STD_ROWCOL_EXT_ILSEQ_SIZE       8
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mapper_std_local.h b/lib/nbsd_libc/citrus/modules/citrus_mapper_std_local.h
new file mode 100644 (file)
index 0000000..631a296
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: citrus_mapper_std_local.h,v 1.3 2006/09/09 14:35:17 tnozaki Exp $      */
+
+/*-
+ * Copyright (c)2003, 2006 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_MAPPER_STD_LOCAL_H_
+#define _CITRUS_MAPPER_STD_LOCAL_H_
+
+typedef u_int32_t (*_citrus_mapper_std_getvalfunc_t)(const void *, u_int32_t);
+
+struct _citrus_mapper_std_linear_zone {
+       _citrus_index_t         begin;
+       _citrus_index_t         end;
+       _citrus_index_t         width;
+};
+struct _citrus_mapper_std_rowcol {
+       struct _citrus_region   rc_table;
+       size_t                  rc_src_rowcol_len;
+       struct _citrus_mapper_std_linear_zone
+                               *rc_src_rowcol;
+       _citrus_index_t         rc_src_rowcol_bits;
+       _citrus_index_t         rc_src_rowcol_mask;
+       _citrus_index_t         rc_dst_invalid;
+       _citrus_index_t         rc_dst_unit_bits;
+       int                     rc_oob_mode;
+       _citrus_index_t         rc_dst_ilseq;
+};
+
+struct _citrus_mapper_std;
+
+typedef int (*_citrus_mapper_std_convert_t)(
+       struct _citrus_mapper_std *__restrict,
+       _index_t *__restrict, _index_t, void *__restrict);
+typedef void (*_citrus_mapper_std_uninit_t)(struct _citrus_mapper_std *);
+
+struct _citrus_mapper_std {
+       struct _citrus_region           ms_file;
+       struct _citrus_db               *ms_db;
+       _citrus_mapper_std_convert_t    ms_convert;
+       _citrus_mapper_std_uninit_t     ms_uninit;
+       union {
+               struct _citrus_mapper_std_rowcol        rowcol;
+       } u;
+#define ms_rowcol      u.rowcol
+};
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mapper_zone.c b/lib/nbsd_libc/citrus/modules/citrus_mapper_zone.c
new file mode 100644 (file)
index 0000000..8eddefa
--- /dev/null
@@ -0,0 +1,401 @@
+/*     $NetBSD: citrus_mapper_zone.c,v 1.4 2003/07/12 15:39:21 tshiozak Exp $  */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_mapper_zone.c,v 1.4 2003/07/12 15:39:21 tshiozak Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/queue.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_module.h"
+#include "citrus_region.h"
+#include "citrus_memstream.h"
+#include "citrus_mmap.h"
+#include "citrus_hash.h"
+#include "citrus_mapper.h"
+#include "citrus_mapper_zone.h"
+
+/* ---------------------------------------------------------------------- */
+
+_CITRUS_MAPPER_DECLS(mapper_zone);
+_CITRUS_MAPPER_DEF_OPS(mapper_zone);
+
+
+/* ---------------------------------------------------------------------- */
+
+struct _zone {
+       u_int32_t z_begin;
+       u_int32_t z_end;
+};
+
+struct _citrus_mapper_zone {
+       struct _zone    mz_row;
+       struct _zone    mz_col;
+       int             mz_col_bits;
+       int32_t         mz_row_offset;
+       int32_t         mz_col_offset;
+};
+
+struct _parse_state {
+       enum { S_BEGIN, S_OFFSET }      ps_state;
+       union {
+               u_int32_t       u_imm;
+               int32_t         s_imm;
+               struct _zone    zone;
+       } u;
+#define ps_u_imm       u.u_imm
+#define ps_s_imm       u.s_imm
+#define ps_zone                u.zone
+       int ps_top;
+};
+
+int
+_citrus_mapper_zone_mapper_getops(struct _citrus_mapper_ops *ops,
+                                 size_t lenops, uint32_t expected_version)
+{
+       if (expected_version<_CITRUS_MAPPER_ABI_VERSION || lenops<sizeof(*ops))
+               return EINVAL;
+
+       memcpy(ops, &_citrus_mapper_zone_mapper_ops,
+              sizeof(_citrus_mapper_zone_mapper_ops));
+
+       return 0;
+}
+
+#define BUFSIZE 20
+#define T_ERR  0x100
+#define T_IMM  0x101
+
+static int
+get_imm(struct _memstream *ms, struct _parse_state *ps)
+{
+       int sign = 0;
+       int c, i;
+       char buf[BUFSIZE+1], *p;
+
+       for (i=0; i<BUFSIZE; i++) {
+retry:
+               c = _memstream_peek(ms);
+               if (i==0) {
+                       if (sign == 0 && (c == '+' || c == '-')) {
+                               sign = c;
+                               _memstream_getc(ms);
+                               goto retry;
+                       } else if (!_bcs_isdigit(c))
+                               break;
+               } else if (!_bcs_isxdigit(c))
+                       if (!(i==1 && c == 'x'))
+                               break;
+               buf[i] = _memstream_getc(ms);
+       }
+       buf[i] = '\0';
+       ps->ps_u_imm = strtoul(buf, &p, 0);
+       if ((p-buf) != i)
+               return T_ERR;
+       if (sign == '-')
+               ps->ps_u_imm = (unsigned long)-(long)ps->ps_u_imm;
+       return T_IMM;
+}
+
+static int
+get_tok(struct _memstream *ms, struct _parse_state *ps)
+{
+       int c;
+
+loop:
+       c = _memstream_peek(ms);
+       if (c==0x00)
+               return EOF;
+       if (_bcs_isspace(c)) {
+               _memstream_getc(ms);
+               goto loop;
+       }
+
+       switch (ps->ps_state) {
+       case S_BEGIN:
+               switch (c) {
+               case ':':
+               case '-':
+               case '/':
+                       _memstream_getc(ms);
+                       return c;
+               case '0':
+               case '1':
+               case '2':
+               case '3':
+               case '4':
+               case '5':
+               case '6':
+               case '7':
+               case '8':
+               case '9':
+                       return get_imm(ms, ps);
+               }
+               break;
+       case S_OFFSET:
+               switch (c) {
+               case '/':
+                       _memstream_getc(ms);
+                       return c;
+               case '+': 
+               case '-': 
+               case '0':
+               case '1':
+               case '2':
+               case '3':
+               case '4':
+               case '5':
+               case '6':
+               case '7':
+               case '8':
+               case '9':
+                       return get_imm(ms, ps);
+               }
+               break;
+       }
+       return T_ERR;
+}
+
+static int
+parse_zone(struct _memstream *ms, struct _parse_state *ps, struct _zone *z)
+{
+       if (get_tok(ms, ps) != T_IMM)
+               return -1;
+       z->z_begin = ps->ps_u_imm;
+       if (get_tok(ms, ps) != '-')
+               return -1;
+       if (get_tok(ms, ps) != T_IMM)
+               return -1;
+       z->z_end = ps->ps_u_imm;
+
+       if (z->z_begin > z->z_end)
+               return -1;
+
+       return 0;
+}
+
+static int
+check_rowcol(struct _zone *z, int32_t ofs, uint32_t maxval)
+{
+       u_int32_t remain;
+
+       if (maxval != 0 && z->z_end >= maxval)
+               return -1;
+
+       if (ofs > 0) {
+               if (maxval == 0) {
+                       /* this should 0x100000000 - z->z_end */
+                       if (z->z_end == 0) {
+                               remain = 0xFFFFFFFF;
+                       } else {
+                               remain = 0xFFFFFFFF - z->z_end + 1;
+                       }
+               } else
+                       remain = maxval - z->z_end;
+               if ((u_int32_t)ofs > remain)
+                       return -1;
+       } else if (ofs < 0) {
+               if (z->z_begin < (u_int32_t)-ofs)
+                       return -1;
+       }
+
+       return 0;
+}
+
+static int
+parse_var(struct _citrus_mapper_zone *mz, struct _memstream *ms)
+{
+       struct _parse_state ps;
+       int ret, isrc;
+       uint32_t rowmax, colmax;
+
+       ps.ps_state = S_BEGIN;
+
+       if (parse_zone(ms, &ps, &mz->mz_col))
+               return -1;
+
+       ret = get_tok(ms, &ps);
+       if (ret == '/') {
+               /* rowzone / colzone / bits */
+               isrc = 1;
+               mz->mz_row = mz->mz_col;
+
+               if (parse_zone(ms, &ps, &mz->mz_col))
+                       return -1;
+               if (get_tok(ms, &ps) != '/')
+                       return -1;
+               if (get_tok(ms, &ps) != T_IMM)
+                       return -1;
+               mz->mz_col_bits = ps.ps_u_imm;
+               if (mz->mz_col_bits<0 || mz->mz_col_bits>32)
+                       return -1;
+               ret = get_tok(ms, &ps);
+       } else {
+               /* colzone */
+               isrc = 0;
+               mz->mz_col_bits = 32;
+               mz->mz_row.z_begin = mz->mz_row.z_end = 0;
+       }
+       if (ret == ':') {
+               /* offset */
+               ps.ps_state = S_OFFSET;
+               if (get_tok(ms, &ps) != T_IMM)
+                       return -1;
+               mz->mz_col_offset = ps.ps_s_imm;
+               if (isrc) {
+                       /* row/col */
+                       mz->mz_row_offset = mz->mz_col_offset;
+                       if (get_tok(ms, &ps) != '/')
+                               return -1;
+                       if (get_tok(ms, &ps) != T_IMM)
+                               return -1;
+                       mz->mz_col_offset = ps.ps_s_imm;
+               } else
+                       mz->mz_row_offset = 0;
+               ret = get_tok(ms, &ps);
+       }
+       if (ret != EOF)
+               return -1;
+
+       /* sanity check */
+       if (mz->mz_col_bits==32)
+               colmax = 0;
+       else
+               colmax = 1 << mz->mz_col_bits;
+       if (mz->mz_col_bits==0)
+               rowmax = 0;
+       else
+               rowmax = 1 << (32-mz->mz_col_bits);
+       if (check_rowcol(&mz->mz_col, mz->mz_col_offset, colmax))
+               return -1;
+       if (check_rowcol(&mz->mz_row, mz->mz_row_offset, rowmax))
+               return -1;
+
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_mapper_zone_mapper_init(struct _citrus_mapper_area *__restrict ma,
+                               struct _citrus_mapper * __restrict cm,
+                               const char * __restrict dir,
+                               const void * __restrict var, size_t lenvar,
+                               struct _citrus_mapper_traits * __restrict mt,
+                               size_t lenmt)
+{
+       struct _citrus_mapper_zone *mz;
+       struct _memstream ms;
+       struct _region r;
+
+       _DIAGASSERT(cm && dir && mt);
+
+       if (lenmt<sizeof(*mt))
+               return EINVAL;
+
+       mz = malloc(sizeof(*mz));
+       if (mz == NULL)
+               return errno;
+
+       mz->mz_col.z_begin = mz->mz_col.z_end = 0;
+       mz->mz_row.z_begin = mz->mz_row.z_end = 0;
+       mz->mz_col_bits = 0;
+       mz->mz_row_offset = 0;
+       mz->mz_col_offset = 0;
+
+       _region_init(&r, (void *)var, lenvar);
+       _memstream_bind(&ms, &r);
+       if (parse_var(mz, &ms)) {
+               free(mz);
+               return EINVAL;
+       }
+       cm->cm_closure = mz;
+       mt->mt_src_max = mt->mt_dst_max = 1;    /* 1:1 converter */
+       mt->mt_state_size = 0;                  /* stateless */
+
+       return 0;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_mapper_zone_mapper_uninit(struct _citrus_mapper *cm)
+{
+}
+
+static int
+/*ARGSUSED*/
+_citrus_mapper_zone_mapper_convert(struct _citrus_mapper * __restrict cm,
+                                  _citrus_index_t * __restrict dst,
+                                  _citrus_index_t src, void * __restrict ps)
+{
+       u_int32_t row, col;
+       struct _citrus_mapper_zone *mz = cm->cm_closure;
+
+       if (mz->mz_col_bits == 32) {
+               col = src;
+               row = 0;
+               if (col < mz->mz_col.z_begin || col > mz->mz_col.z_end)
+                       return _CITRUS_MAPPER_CONVERT_NONIDENTICAL;
+               if (mz->mz_col_offset>0)
+                       col += (u_int32_t)mz->mz_col_offset;
+               else
+                       col -= (u_int32_t)-mz->mz_col_offset;
+               *dst = col;
+       } else {
+               col = src & (((u_int32_t)1<<mz->mz_col_bits)-1);
+               row = src >> mz->mz_col_bits;
+               if (row < mz->mz_row.z_begin || row > mz->mz_row.z_end ||
+                   col < mz->mz_col.z_begin || col > mz->mz_col.z_end)
+                       return _CITRUS_MAPPER_CONVERT_NONIDENTICAL;
+               if (mz->mz_col_offset>0)
+                       col += (u_int32_t)mz->mz_col_offset;
+               else
+                       col -= (u_int32_t)-mz->mz_col_offset;
+               if (mz->mz_row_offset>0)
+                       row += (u_int32_t)mz->mz_row_offset;
+               else
+                       row -= (u_int32_t)-mz->mz_row_offset;
+               *dst = col | (row << mz->mz_col_bits);
+       }
+       return _CITRUS_MAPPER_CONVERT_SUCCESS;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_mapper_zone_mapper_init_state(struct _citrus_mapper * __restrict cm,
+                                     void * __restrict ps)
+{
+}
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mapper_zone.h b/lib/nbsd_libc/citrus/modules/citrus_mapper_zone.h
new file mode 100644 (file)
index 0000000..d975dd1
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: citrus_mapper_zone.h,v 1.1 2003/06/25 09:51:48 tshiozak Exp $  */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_MAPPER_ZONE_H_
+#define _CITRUS_MAPPER_ZONE_H_
+
+__BEGIN_DECLS
+_CITRUS_MAPPER_GETOPS_FUNC(mapper_zone);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mskanji.c b/lib/nbsd_libc/citrus/modules/citrus_mskanji.c
new file mode 100644 (file)
index 0000000..c6011c4
--- /dev/null
@@ -0,0 +1,544 @@
+/*     $NetBSD: citrus_mskanji.c,v 1.13 2008/06/14 16:01:08 tnozaki Exp $      */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+/*
+ *    ja_JP.SJIS locale table for BSD4.4/rune
+ *    version 1.0
+ *    (C) Sin'ichiro MIYATANI / Phase One, Inc
+ *    May 12, 1995
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Phase One, Inc.
+ * 4. The name of Phase One, Inc. 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.  
+ */  
+
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_mskanji.c,v 1.13 2008/06/14 16:01:08 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <wchar.h>
+#include <sys/types.h>
+#include <limits.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_mskanji.h"
+
+
+/* ----------------------------------------------------------------------
+ * private stuffs used by templates
+ */
+
+typedef struct _MSKanjiState {
+       char ch[2];
+       int chlen;
+} _MSKanjiState;
+
+typedef struct {
+       int mode;
+#define MODE_JIS2004   1
+} _MSKanjiEncodingInfo;
+
+typedef struct {
+       _MSKanjiEncodingInfo    ei;
+       struct {
+               /* for future multi-locale facility */
+               _MSKanjiState   s_mblen;
+               _MSKanjiState   s_mbrlen;
+               _MSKanjiState   s_mbrtowc;
+               _MSKanjiState   s_mbtowc;
+               _MSKanjiState   s_mbsrtowcs;
+               _MSKanjiState   s_wcrtomb;
+               _MSKanjiState   s_wcsrtombs;
+               _MSKanjiState   s_wctomb;
+       } states;
+} _MSKanjiCTypeInfo;
+
+#define _CEI_TO_EI(_cei_)              (&(_cei_)->ei)
+#define _CEI_TO_STATE(_cei_, _func_)   (_cei_)->states.s_##_func_
+
+#define _FUNCNAME(m)                   _citrus_MSKanji_##m
+#define _ENCODING_INFO                 _MSKanjiEncodingInfo
+#define _CTYPE_INFO                    _MSKanjiCTypeInfo
+#define _ENCODING_STATE                        _MSKanjiState
+#define _ENCODING_MB_CUR_MAX(_ei_)     2
+#define _ENCODING_IS_STATE_DEPENDENT   0
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       0
+
+
+static int
+_mskanji1(int c)
+{
+
+       if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc))
+               return 1;
+       else
+               return 0;
+}
+
+static int
+_mskanji2(int c)
+{
+
+       if ((c >= 0x40 && c <= 0x7e) || (c >= 0x80 && c <= 0xfc))
+               return 1;
+       else
+               return 0;
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_MSKanji_init_state(_MSKanjiEncodingInfo * __restrict ei,
+                          _MSKanjiState * __restrict s)
+{
+       s->chlen = 0;
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_MSKanji_pack_state(_MSKanjiEncodingInfo * __restrict ei,
+                          void * __restrict pspriv,
+                          const _MSKanjiState * __restrict s)
+{
+       memcpy(pspriv, (const void *)s, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_MSKanji_unpack_state(_MSKanjiEncodingInfo * __restrict ei,
+                            _MSKanjiState * __restrict s,
+                            const void * __restrict pspriv)
+{
+       memcpy((void *)s, pspriv, sizeof(*s));
+}
+
+static int
+/*ARGSUSED*/
+_citrus_MSKanji_mbrtowc_priv(_MSKanjiEncodingInfo * __restrict ei,
+                            wchar_t * __restrict pwc,
+                            const char ** __restrict s, size_t n,
+                            _MSKanjiState * __restrict psenc,
+                            size_t * __restrict nresult)
+{
+       wchar_t wchar;
+       int len;
+       int chlenbak;
+       const char *s0;
+
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       s0 = *s;
+
+       if (s0 == NULL) {
+               _citrus_MSKanji_init_state(ei, psenc);
+               *nresult = 0; /* state independent */
+               return (0);
+       }
+
+       chlenbak = psenc->chlen;
+
+       /* make sure we have the first byte in the buffer */
+       switch (psenc->chlen) {
+       case 0:
+               if (n < 1)
+                       goto restart;
+               psenc->ch[0] = *s0++;
+               psenc->chlen = 1;
+               n--;
+               break;
+       case 1:
+               break;
+       default:
+               /* illegal state */
+               goto encoding_error;
+       }
+
+       len = _mskanji1(psenc->ch[0] & 0xff) ? 2 : 1;
+       while (psenc->chlen < len) {
+               if (n < 1)
+                       goto restart;
+               psenc->ch[psenc->chlen] = *s0++;
+               psenc->chlen++;
+               n--;
+       }
+
+       *s = s0;
+
+       switch (len) {
+       case 1:
+               wchar = psenc->ch[0] & 0xff;
+               break;
+       case 2:
+               if (!_mskanji2(psenc->ch[1] & 0xff))
+                       goto encoding_error;
+               wchar = ((psenc->ch[0] & 0xff) << 8) | (psenc->ch[1] & 0xff);
+               break;
+       default:
+               /* illegal state */
+               goto encoding_error;
+       }
+
+       psenc->chlen = 0;
+
+       if (pwc)
+               *pwc = wchar;
+
+       if (!wchar)
+               *nresult = 0;
+       else
+               *nresult = len - chlenbak;
+
+       return (0);
+
+encoding_error:
+       psenc->chlen = 0;
+       *nresult = (size_t)-1;
+       return (EILSEQ);
+
+restart:
+       *nresult = (size_t)-2;
+       *s = s0;
+       return (0);
+}
+
+
+static int
+_citrus_MSKanji_wcrtomb_priv(_MSKanjiEncodingInfo * __restrict ei,
+                            char * __restrict s, size_t n, wchar_t wc,
+                            _MSKanjiState * __restrict psenc,
+                            size_t * __restrict nresult)
+{
+       int ret;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(s != NULL);
+
+       /* check invalid sequence */
+       if (wc & ~0xffff) {
+               ret = EILSEQ;
+               goto err;
+       }
+
+       if (wc & 0xff00) {
+               if (n < 2) {
+                       ret = E2BIG;
+                       goto err;
+               }
+
+               s[0] = (wc >> 8) & 0xff;
+               s[1] = wc & 0xff;
+               if (!_mskanji1(s[0] & 0xff) || !_mskanji2(s[1] & 0xff)) {
+                       ret = EILSEQ;
+                       goto err;
+               }
+
+               *nresult = 2;
+               return 0;
+       } else {
+               if (n < 1) {
+                       ret = E2BIG;
+                       goto err;
+               }
+
+               s[0] = wc & 0xff;
+               if (_mskanji1(s[0] & 0xff)) {
+                       ret = EILSEQ;
+                       goto err;
+               }
+
+               *nresult = 1;
+               return 0;
+       }
+
+err:
+       *nresult = (size_t)-1;
+       return ret;
+}
+
+
+static __inline int
+/*ARGSUSED*/
+_citrus_MSKanji_stdenc_wctocs(_MSKanjiEncodingInfo * __restrict ei,
+                             _csid_t * __restrict csid,
+                             _index_t * __restrict idx, wchar_t wc)
+{
+       _index_t row, col;
+       int offset;
+
+       _DIAGASSERT(csid != NULL && idx != NULL);
+
+       if ((_wc_t)wc < 0x80) {
+               /* ISO-646 */
+               *csid = 0;
+               *idx = (_index_t)wc;
+       } else if ((_wc_t)wc < 0x100) {
+               /* KANA */
+               *csid = 1;
+               *idx = (_index_t)wc & 0x7F;
+       } else {
+               /* Kanji (containing Gaiji zone) */
+               /*
+                * 94^2 zone (contains a part of Gaiji (0xED40 - 0xEEFC)):
+                * 0x8140 - 0x817E -> 0x2121 - 0x215F
+                * 0x8180 - 0x819E -> 0x2160 - 0x217E
+                * 0x819F - 0x81FC -> 0x2221 - 0x227E
+                *
+                * 0x8240 - 0x827E -> 0x2321 - 0x235F
+                *  ...
+                * 0x9F9F - 0x9FFc -> 0x5E21 - 0x5E7E
+                *
+                * 0xE040 - 0xE07E -> 0x5F21 - 0x5F5F
+                *  ...
+                * 0xEF9F - 0xEFFC -> 0x7E21 - 0x7E7E
+                *
+                * extended Gaiji zone:
+                * 0xF040 - 0xFCFC
+                *
+                * JIS X0213-plane2:
+                * 0xF040 - 0xF09E -> 0x2121 - 0x217E
+                * 0xF140 - 0xF19E -> 0x2321 - 0x237E
+                * ...
+                * 0xF240 - 0xF29E -> 0x2521 - 0x257E
+                *
+                * 0xF09F - 0xF0FC -> 0x2821 - 0x287E
+                * 0xF29F - 0xF2FC -> 0x2C21 - 0x2C7E
+                * ...
+                * 0xF44F - 0xF49E -> 0x2F21 - 0x2F7E
+                *
+                * 0xF49F - 0xF4FC -> 0x6E21 - 0x6E7E
+                * ...
+                * 0xFC9F - 0xFCFC -> 0x7E21 - 0x7E7E
+                */
+               row = ((_wc_t)wc >> 8) & 0xFF;
+               col = (_wc_t)wc & 0xFF;
+               if (!_mskanji1(row) || !_mskanji2(col))
+                       return EILSEQ;
+               if ((ei->mode & MODE_JIS2004) == 0 || row < 0xF0) {
+                       *csid = 2;
+                       offset = 0x81;
+               } else {
+                       *csid = 3;
+                       if ((_wc_t)wc <= 0xF49E) {
+                               offset = (_wc_t)wc >= 0xF29F ||
+                                 ((_wc_t)wc >= 0xF09F && (_wc_t)wc <= 0xF0FC)
+                                   ? 0xED : 0xF0;
+                       } else
+                               offset = 0xCE;
+               }
+               row -= offset;
+               if (row >= 0x5F)
+                       row -= 0x40;
+               row = row * 2 + 0x21;
+               col -= 0x1F;
+               if (col >= 0x61)
+                       col -= 1;
+               if (col > 0x7E) {
+                       row += 1;
+                       col -= 0x5E;
+               }
+               *idx = ((_index_t)row << 8) | col;
+       }
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_MSKanji_stdenc_cstowc(_MSKanjiEncodingInfo * __restrict ei,
+                             wchar_t * __restrict wc,
+                             _csid_t csid, _index_t idx)
+{
+       u_int32_t row, col;
+       int offset;
+
+       _DIAGASSERT(wc != NULL);
+
+       switch (csid) {
+       case 0:
+               /* ISO-646 */
+               if (idx >= 0x80)
+                       return EILSEQ;
+               *wc = (wchar_t)idx;
+               break;
+       case 1:
+               /* kana */
+               if (idx >= 0x80)
+                       return EILSEQ;
+               *wc = (wchar_t)idx + 0x80;
+               break;
+       case 3:
+               if ((ei->mode & MODE_JIS2004) == 0)
+                       return EILSEQ;
+       /*FALLTHROUGH*/
+       case 2:
+               /* kanji */
+               row = (idx >> 8);
+               if (row < 0x21)
+                       return EILSEQ;
+               if (csid == 3) {
+                       if (row <= 0x2F)
+                               offset = (row == 0x22 || row >= 0x26)
+                                   ? 0xED : 0xF0;
+                       else if (row >= 0x4D && row <= 0x7E)
+                               offset = 0xCE;
+                       else
+                               return EILSEQ;
+               } else {
+                       if (row > 0x97)
+                               return EILSEQ;
+                       offset = (row < 0x5F) ? 0x81 : 0xC1;
+               }
+               col = idx & 0xFF;
+               if (col < 0x21 || col > 0x7E)
+                       return EILSEQ;
+               row -= 0x21; col -= 0x21;
+               if ((row & 1) == 0) {
+                       col += 0x40;
+                       if (col >= 0x7F)
+                               col += 1;
+               } else
+                       col += 0x9F;
+               row = row / 2 + offset;
+               *wc = ((wchar_t)row << 8) | col;
+               break;
+       default:
+               return EILSEQ;
+       }
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_MSKanji_stdenc_get_state_desc_generic(_MSKanjiEncodingInfo * __restrict ei,
+                                             _MSKanjiState * __restrict psenc,
+                                             int * __restrict rstate)
+{
+
+       if (psenc->chlen == 0)
+               *rstate = _STDENC_SDGEN_INITIAL;
+       else
+               *rstate = _STDENC_SDGEN_INCOMPLETE_CHAR;
+
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_MSKanji_encoding_module_init(_MSKanjiEncodingInfo *  __restrict ei,
+                                    const void * __restrict var,
+                                    size_t lenvar)
+{
+       const char *p;
+
+       _DIAGASSERT(ei != NULL);
+
+       p = var;
+#define MATCH(x, act)                                          \
+do {                                                           \
+       if (lenvar >= (sizeof(#x)-1) &&                         \
+           _bcs_strncasecmp(p, #x, sizeof(#x)-1) == 0) {       \
+               act;                                            \
+               lenvar -= sizeof(#x)-1;                         \
+               p += sizeof(#x)-1;                              \
+       }                                                       \
+} while (/*CONSTCOND*/0)
+       memset((void *)ei, 0, sizeof(*ei));
+       while (lenvar > 0) {
+               switch (_bcs_toupper(*p)) {
+               case 'J':
+                       MATCH(JIS2004, ei->mode |= MODE_JIS2004);
+                       break;
+               }
+               ++p;
+               --lenvar;
+       }
+
+       return 0;
+}
+
+static void
+_citrus_MSKanji_encoding_module_uninit(_MSKanjiEncodingInfo *ei)
+{
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(MSKanji);
+_CITRUS_CTYPE_DEF_OPS(MSKanji);
+
+#include "citrus_ctype_template.h"
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(MSKanji);
+_CITRUS_STDENC_DEF_OPS(MSKanji);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_mskanji.h b/lib/nbsd_libc/citrus/modules/citrus_mskanji.h
new file mode 100644 (file)
index 0000000..90aebe1
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: citrus_mskanji.h,v 1.2 2003/06/25 09:51:48 tshiozak Exp $      */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_MSKANJI_H_
+#define _CITRUS_MSKANJI_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(MSKanji);
+_CITRUS_STDENC_GETOPS_FUNC(MSKanji);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_ues.c b/lib/nbsd_libc/citrus/modules/citrus_ues.c
new file mode 100644 (file)
index 0000000..08b23d5
--- /dev/null
@@ -0,0 +1,472 @@
+/* $NetBSD: citrus_ues.c,v 1.2 2010/12/07 22:01:22 joerg Exp $ */
+
+/*-
+ * Copyright (c)2006 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_ues.c,v 1.2 2010/12/07 22:01:22 joerg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <wchar.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_ues.h"
+
+typedef struct {
+       int mode;
+#define MODE_C99       1
+       size_t mb_cur_max;
+} _UESEncodingInfo;
+
+typedef struct {
+       int chlen;
+       char ch[12];
+} _UESState;
+
+typedef struct {
+       _UESEncodingInfo        ei;
+       struct {
+               /* for future multi-locale facility */
+               _UESState       s_mblen;
+               _UESState       s_mbrlen;
+               _UESState       s_mbrtowc;
+               _UESState       s_mbtowc;
+               _UESState       s_mbsrtowcs;
+               _UESState       s_wcrtomb;
+               _UESState       s_wcsrtombs;
+               _UESState       s_wctomb;
+       } states;
+} _UESCTypeInfo;
+
+#define _CEI_TO_EI(_cei_)               (&(_cei_)->ei)
+#define _CEI_TO_STATE(_cei_, _func_)    (_cei_)->states.s_##_func_
+
+#define _FUNCNAME(m)                   _citrus_UES_##m
+#define _ENCODING_INFO                 _UESEncodingInfo
+#define _CTYPE_INFO                    _UESCTypeInfo
+#define _ENCODING_STATE                        _UESState
+#define _ENCODING_MB_CUR_MAX(_ei_)     (_ei_)->mb_cur_max
+#define _ENCODING_IS_STATE_DEPENDENT           0
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       0
+
+static __inline void
+/*ARGSUSED*/
+_citrus_UES_init_state(_UESEncodingInfo * __restrict ei,
+       _UESState * __restrict psenc)
+{
+       psenc->chlen = 0;
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_UES_pack_state(_UESEncodingInfo * __restrict ei,
+       void *__restrict pspriv, const _UESState * __restrict psenc)
+{
+       /* ei seem to be unused */
+       _DIAGASSERT(pspriv != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       memcpy(pspriv, (const void *)psenc, sizeof(*psenc));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_UES_unpack_state(_UESEncodingInfo * __restrict ei,
+       _UESState * __restrict psenc, const void * __restrict pspriv)
+{
+       /* ei seem to be unused */
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(pspriv != NULL);
+
+       memcpy((void *)psenc, pspriv, sizeof(*psenc));
+}
+
+static __inline int
+to_int(int ch)
+{
+       if (ch >= '0' && ch <= '9')
+               return ch - '0';
+       else if (ch >= 'A' && ch <= 'F')
+               return (ch - 'A') + 10;
+       else if (ch >= 'a' && ch <= 'f')
+               return (ch - 'a') + 10;
+       return -1;
+}
+
+#define ESCAPE         '\\'
+#define UCS2_ESC       'u'
+#define UCS4_ESC       'U'
+
+#define UCS2_BIT       16
+#define UCS4_BIT       32
+#define BMP_MAX                UINT32_C(0xFFFF)
+#define UCS2_MAX       UINT32_C(0x10FFFF)
+#define UCS4_MAX       UINT32_C(0x7FFFFFFF)
+
+static const char *xdig = "0123456789abcdef";
+
+static __inline int
+to_str(char *s, wchar_t wc, int bit)
+{
+       char *p;
+
+       p = s;
+       *p++ = ESCAPE;
+       switch (bit) {
+       case UCS2_BIT:
+               *p++ = UCS2_ESC;
+               break;
+       case UCS4_BIT:
+               *p++ = UCS4_ESC;
+               break;
+       default:
+               abort();
+       }
+       do {
+               *p++ = xdig[(wc >> (bit -= 4)) & 0xF];
+       } while (bit > 0);
+       return p - s;
+}
+
+static __inline int
+is_hi_surrogate(wchar_t wc)
+{
+       return wc >= 0xD800 && wc <= 0xDBFF;
+}
+
+static __inline int
+is_lo_surrogate(wchar_t wc)
+{
+       return wc >= 0xDC00 && wc <= 0xDFFF;
+}
+
+static __inline wchar_t
+surrogate_to_ucs(wchar_t hi, wchar_t lo)
+{
+       _DIAGASSERT(is_hi_surrogate(hi));
+       _DIAGASSERT(is_lo_surrogate(lo));
+
+       hi -= 0xD800;
+       lo -= 0xDC00;
+       return (hi << 10 | lo) + 0x10000;
+}
+
+static __inline void
+ucs_to_surrogate(wchar_t wc, wchar_t * __restrict hi, wchar_t * __restrict lo)
+{
+       _DIAGASSERT(hi != NULL);
+       _DIAGASSERT(lo != NULL);
+       _DIAGASSERT(wc >= 0x10000);
+
+       wc -= 0x10000;
+       *hi = (wc >> 10) + 0xD800;
+       *lo = (wc & 0x3FF) + 0xDC00;
+}
+
+static __inline int
+is_basic(wchar_t wc)
+{
+       return (uint32_t)wc <= 0x9F &&
+           wc != 0x24 && wc != 0x40 && wc != 0x60;
+}
+
+static int
+_citrus_UES_mbrtowc_priv(_UESEncodingInfo * __restrict ei,
+       wchar_t * __restrict pwc, const char ** __restrict s, size_t n,
+       _UESState * __restrict psenc, size_t * __restrict nresult)
+{
+       const char *s0;
+       int ch, head, tail, i, num;
+       wchar_t hi, wc;
+
+       _DIAGASSERT(ei != NULL);
+       /* pwc may be null */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (*s == NULL) {
+               _citrus_UES_init_state(ei, psenc);
+               *nresult = 0;
+               return 0;
+       }
+       s0 = *s;
+
+       hi = (wchar_t)0;
+       tail = 0;
+
+surrogate:
+       wc = (wchar_t)0;
+       head = tail;
+       if (psenc->chlen == head) {
+               if (n-- < 1)
+                       goto restart;
+               psenc->ch[psenc->chlen++] = *s0++;
+       }
+       ch = (unsigned char)psenc->ch[head++];
+       if (ch == ESCAPE) {
+               if (psenc->chlen == head) {
+                       if (n-- < 1)
+                               goto restart;
+                       psenc->ch[psenc->chlen++] = *s0++;
+               }
+               switch (psenc->ch[head]) {
+               case UCS2_ESC:
+                       tail += 6;
+                       break;
+               case UCS4_ESC:
+                       if (ei->mode & MODE_C99) {
+                               tail = 10;
+                               break;
+                       }
+               /*FALLTHROUGH*/
+               default:
+                       tail = 0;
+               }
+               ++head;
+       }
+       for (; head < tail; ++head) {
+               if (psenc->chlen == head) {
+                       if (n-- < 1) {
+restart:
+                               *s = s0;
+                               *nresult = (size_t)-2;
+                               return 0;
+                       }
+                       psenc->ch[psenc->chlen++] = *s0++;
+               }
+               num = to_int((int)(unsigned char)psenc->ch[head]);
+               if (num < 0) {
+                       tail = 0;
+                       break;
+               }
+               wc = (wc << 4) | num;
+       }
+       head = 0;
+       switch (tail) {
+       case 0:
+               break;
+       case 6:
+               if (hi != (wchar_t)0)
+                       break;
+               if ((ei->mode & MODE_C99) == 0) {
+                       if (is_hi_surrogate(wc) != 0) {
+                               hi = wc;
+                               goto surrogate;
+                       }
+                       if ((uint32_t)wc <= 0x7F /* XXX */ ||
+                           is_lo_surrogate(wc) != 0)
+                               break;
+                       goto done;
+               }
+       /*FALLTHROUGH*/
+       case 10:
+               if (is_basic(wc) == 0 && (uint32_t)wc <= UCS4_MAX &&
+                   is_hi_surrogate(wc) == 0 && is_lo_surrogate(wc) == 0)
+                       goto done;
+               *nresult = (size_t)-1;
+               return EILSEQ;
+       case 12:
+               if (is_lo_surrogate(wc) == 0)
+                       break;
+               wc = surrogate_to_ucs(hi, wc);
+               goto done;
+       }
+       ch = (unsigned char)psenc->ch[0];
+       head = psenc->chlen;
+       if (--head > 0)
+               memmove(&psenc->ch[0], &psenc->ch[1], head);
+       wc = (wchar_t)ch;
+done:
+       psenc->chlen = head;
+       if (pwc != NULL)
+               *pwc = wc;
+       *nresult = (size_t)((wc == 0) ? 0 : (s0 - *s));
+       *s = s0;
+
+       return 0;
+}
+
+static int
+_citrus_UES_wcrtomb_priv(_UESEncodingInfo * __restrict ei,
+       char * __restrict s, size_t n, wchar_t wc,
+       _UESState * __restrict psenc, size_t * __restrict nresult)
+{
+       wchar_t hi, lo;
+
+       if (psenc->chlen != 0)
+               return EINVAL;
+
+       if ((ei->mode & MODE_C99) ? is_basic(wc) : (uint32_t)wc <= 0x7F) {
+               if (n-- < 1)
+                       goto e2big;
+               psenc->ch[psenc->chlen++] = (char)wc;
+       } else if ((uint32_t)wc <= BMP_MAX) {
+               if (n < 6)
+                       goto e2big;
+               psenc->chlen = to_str(&psenc->ch[0], wc, UCS2_BIT);
+       } else if ((ei->mode & MODE_C99) == 0 && (uint32_t)wc <= UCS2_MAX) {
+               if (n < 12)
+                       goto e2big;
+               ucs_to_surrogate(wc, &hi, &lo);
+               psenc->chlen += to_str(&psenc->ch[0], hi, UCS2_BIT);
+               psenc->chlen += to_str(&psenc->ch[6], lo, UCS2_BIT);
+       } else if ((ei->mode & MODE_C99) && (uint32_t)wc <= UCS4_MAX) {
+               if (n < 10)
+                       goto e2big;
+               psenc->chlen = to_str(&psenc->ch[0], wc, UCS4_BIT);
+       } else {
+               *nresult = (size_t)-1;
+               return EILSEQ;
+       }
+       memcpy(s, psenc->ch, psenc->chlen);
+       *nresult = psenc->chlen;
+       psenc->chlen = 0;
+
+       return 0;
+
+e2big:
+       *nresult = (size_t)-1;
+       return E2BIG;
+}
+
+/*ARGSUSED*/
+static int
+_citrus_UES_stdenc_wctocs(_UESEncodingInfo * __restrict ei,
+       _csid_t * __restrict csid, _index_t * __restrict idx, wchar_t wc)
+{
+       /* ei seem to be unused */
+       _DIAGASSERT(csid != NULL);
+       _DIAGASSERT(idx != NULL);
+
+       *csid = 0;
+       *idx = (_index_t)wc;
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_UES_stdenc_cstowc(_UESEncodingInfo * __restrict ei,
+       wchar_t * __restrict wc, _csid_t csid, _index_t idx)
+{
+       /* ei seem to be unused */
+       _DIAGASSERT(wc != NULL);
+
+       if (csid != 0)
+               return EILSEQ;
+       *wc = (wchar_t)idx;
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_UES_stdenc_get_state_desc_generic(_UESEncodingInfo * __restrict ei,
+       _UESState * __restrict psenc, int * __restrict rstate)
+{
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(rstate != NULL);
+
+       if (psenc->chlen == 0)
+               *rstate = _STDENC_SDGEN_INITIAL;
+       else
+               *rstate = _STDENC_SDGEN_INCOMPLETE_CHAR; /* XXX */
+       return 0;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_UES_encoding_module_uninit(_UESEncodingInfo *ei)
+{
+       /* ei seems to be unused */
+}
+
+static int
+/*ARGSUSED*/
+_citrus_UES_encoding_module_init(_UESEncodingInfo * __restrict ei,
+       const void * __restrict var, size_t lenvar)
+{
+       const char *p;
+
+       _DIAGASSERT(ei != NULL);
+
+       p = var;
+#define MATCH(x, act)                                          \
+do {                                                           \
+        if (lenvar >= (sizeof(#x)-1) &&                                \
+            _bcs_strncasecmp(p, #x, sizeof(#x)-1) == 0) {      \
+                act;                                           \
+                lenvar -= sizeof(#x)-1;                                \
+                p += sizeof(#x)-1;                             \
+        }                                                      \
+} while (/*CONSTCOND*/0)
+       memset((void *)ei, 0, sizeof(*ei));
+       while (lenvar > 0) {
+               switch (_bcs_toupper(*p)) {
+               case 'C':
+                       MATCH(C99, ei->mode |= MODE_C99);
+                       break;
+               }
+               ++p;
+               --lenvar;
+       }
+       ei->mb_cur_max = (ei->mode & MODE_C99) ? 10 : 12;
+
+       return 0;
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(UES);
+_CITRUS_CTYPE_DEF_OPS(UES);
+
+#include "citrus_ctype_template.h"
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(UES);
+_CITRUS_STDENC_DEF_OPS(UES);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_ues.h b/lib/nbsd_libc/citrus/modules/citrus_ues.h
new file mode 100644 (file)
index 0000000..0df7f27
--- /dev/null
@@ -0,0 +1,37 @@
+/* $NetBSD: citrus_ues.h,v 1.1 2006/11/13 15:16:31 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2004, 2006 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_UES_H_
+#define _CITRUS_UES_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(UES);
+_CITRUS_STDENC_GETOPS_FUNC(UES);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_utf1632.c b/lib/nbsd_libc/citrus/modules/citrus_utf1632.c
new file mode 100644 (file)
index 0000000..e582fd6
--- /dev/null
@@ -0,0 +1,486 @@
+/*     $NetBSD: citrus_utf1632.c,v 1.11 2010/03/20 18:15:32 tnozaki Exp $      */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_utf1632.c,v 1.11 2010/03/20 18:15:32 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <limits.h>
+#include <wchar.h>
+#include <sys/types.h>
+#include <machine/endian.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_stdenc.h"
+#include "citrus_bcs.h"
+
+#include "citrus_utf1632.h"
+
+
+/* ----------------------------------------------------------------------
+ * private stuffs used by templates
+ */
+
+typedef struct {
+       u_int8_t                ch[4];
+       int                     chlen;
+       int                     current_endian;
+} _UTF1632State;
+
+typedef struct {
+       int             preffered_endian;
+       unsigned int    cur_max;
+#define _ENDIAN_UNKNOWN        0
+#define _ENDIAN_BIG    1
+#define _ENDIAN_LITTLE 2
+       u_int32_t       mode;
+#define _MODE_UTF32            0x00000001U
+#define _MODE_FORCE_ENDIAN     0x00000002U
+} _UTF1632EncodingInfo;
+
+#define _FUNCNAME(m)                   _citrus_UTF1632_##m
+#define _ENCODING_INFO                 _UTF1632EncodingInfo
+#define _ENCODING_STATE                        _UTF1632State
+#define _ENCODING_MB_CUR_MAX(_ei_)     ((_ei_)->cur_max)
+#define _ENCODING_IS_STATE_DEPENDENT   0
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       0
+
+
+static __inline void
+/*ARGSUSED*/
+_citrus_UTF1632_init_state(_UTF1632EncodingInfo *ei, _UTF1632State *s)
+{
+       memset(s, 0, sizeof(*s));
+}
+
+static int
+_citrus_UTF1632_mbrtowc_priv(_UTF1632EncodingInfo *ei, wchar_t *pwc,
+                            const char **s, size_t n, _UTF1632State *psenc,
+                            size_t *nresult)
+{
+       int chlenbak, endian, needlen;
+       wchar_t wc;
+       size_t result;
+       const char *s0;
+
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       s0 = *s;
+
+       if (s0 == NULL) {
+               _citrus_UTF1632_init_state(ei, psenc);
+               *nresult = 0; /* state independent */
+               return (0);
+       }
+
+       result = 0;
+       chlenbak = psenc->chlen;
+
+refetch:
+       if ((ei->mode & _MODE_UTF32) != 0 || chlenbak>=2)
+               needlen = 4;
+       else
+               needlen = 2;
+
+       while (chlenbak < needlen) {
+               if (n==0)
+                       goto restart;
+               psenc->ch[chlenbak++] = *s0++;
+               n--;
+               result++;
+       }
+
+       if (psenc->current_endian == _ENDIAN_UNKNOWN) {
+               if ((ei->mode & _MODE_FORCE_ENDIAN) == 0) {
+                       /* judge endian marker */
+                       if ((ei->mode & _MODE_UTF32) == 0) {
+                               /* UTF16 */
+                               if (psenc->ch[0]==0xFE && psenc->ch[1]==0xFF) {
+                                       psenc->current_endian = _ENDIAN_BIG;
+                                       chlenbak = 0;
+                                       goto refetch;
+                               } else if (psenc->ch[0]==0xFF && psenc->ch[1]==0xFE) {
+                                       psenc->current_endian = _ENDIAN_LITTLE;
+                                       chlenbak = 0;
+                                       goto refetch;
+                               }
+                       } else {
+                               /* UTF32 */
+                               if (psenc->ch[0]==0x00 && psenc->ch[1]==0x00 &&
+                                   psenc->ch[2]==0xFE && psenc->ch[3]==0xFF) {
+                                       psenc->current_endian = _ENDIAN_BIG;
+                                       chlenbak = 0;
+                                       goto refetch;
+                               } else if (psenc->ch[0]==0xFF && psenc->ch[1]==0xFE &&
+                                          psenc->ch[2]==0x00 && psenc->ch[3]==0x00) {
+                                       psenc->current_endian = _ENDIAN_LITTLE;
+                                       chlenbak = 0;
+                                       goto refetch;
+                               }
+                       }
+               }
+               psenc->current_endian = ei->preffered_endian;
+       }
+       endian = psenc->current_endian;
+
+       /* get wc */
+       if ((ei->mode & _MODE_UTF32) == 0) {
+               /* UTF16 */
+               if (needlen==2) {
+                       switch (endian) {
+                       case _ENDIAN_LITTLE:
+                               wc = (psenc->ch[0] |
+                                     ((wchar_t)psenc->ch[1] << 8));
+                               break;
+                       case _ENDIAN_BIG:
+                               wc = (psenc->ch[1] |
+                                     ((wchar_t)psenc->ch[0] << 8));
+                               break;
+                       default:
+                               goto ilseq;
+                       }
+                       if (wc >= 0xD800 && wc <= 0xDBFF) {
+                               /* surrogate high */
+                               needlen=4;
+                               goto refetch;
+                       }
+               } else {
+                       /* surrogate low */
+                       wc -= 0xD800; /* wc : surrogate high (see above) */
+                       wc <<= 10;
+                       switch (endian) {
+                       case _ENDIAN_LITTLE:
+                               if (psenc->ch[3]<0xDC || psenc->ch[3]>0xDF)
+                                       goto ilseq;
+                               wc |= psenc->ch[2];
+                               wc |= (wchar_t)(psenc->ch[3] & 3) << 8;
+                               break;
+                       case _ENDIAN_BIG:
+                               if (psenc->ch[2]<0xDC || psenc->ch[2]>0xDF)
+                                       goto ilseq;
+                               wc |= psenc->ch[3];
+                               wc |= (wchar_t)(psenc->ch[2] & 3) << 8;
+                               break;
+                       default:
+                               goto ilseq;
+                       }
+                       wc += 0x10000;
+               }
+       } else {
+               /* UTF32 */
+               switch (endian) {
+               case _ENDIAN_LITTLE:
+                       wc = (psenc->ch[0] |
+                             ((wchar_t)psenc->ch[1] << 8) |
+                             ((wchar_t)psenc->ch[2] << 16) |
+                             ((wchar_t)psenc->ch[3] << 24));
+                       break;
+               case _ENDIAN_BIG:
+                       wc = (psenc->ch[3] |
+                             ((wchar_t)psenc->ch[2] << 8) |
+                             ((wchar_t)psenc->ch[1] << 16) |
+                             ((wchar_t)psenc->ch[0] << 24));
+                       break;
+               default:
+                       goto ilseq;
+               }
+               if (wc >= 0xD800 && wc <= 0xDFFF)
+                       goto ilseq;
+       }
+
+
+       *pwc = wc;
+       psenc->chlen = 0;
+       *nresult = result;
+       *s = s0;
+
+       return (0);
+
+ilseq:
+       *nresult = (size_t)-1;
+       psenc->chlen = 0;
+       return (EILSEQ);
+
+restart:
+       *nresult = (size_t)-2;
+       psenc->chlen = chlenbak;
+       *s = s0;
+       return (0);
+}
+
+static int
+_citrus_UTF1632_wcrtomb_priv(_UTF1632EncodingInfo *ei, char *s, size_t n,
+                            wchar_t wc, _UTF1632State *psenc,
+                            size_t *nresult)
+{
+       int ret;
+       wchar_t wc2;
+       static const char _bom[4] = {
+#if BYTE_ORDER == BIG_ENDIAN
+           0x00, 0x00, 0xFE, 0xFF,
+#else
+           0xFF, 0xFE, 0x00, 0x00,
+#endif
+       };
+       const char *bom = &_bom[0];
+       size_t cnt;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(s != NULL);
+
+       cnt = (size_t)0;
+       if (psenc->current_endian == _ENDIAN_UNKNOWN) {
+               if ((ei->mode & _MODE_FORCE_ENDIAN) == 0) {
+                       if (ei->mode & _MODE_UTF32) {
+                               cnt = 4;
+                       } else {
+                               cnt = 2;
+#if BYTE_ORDER == BIG_ENDIAN
+                               bom += 2;
+#endif
+                       }
+                       if (n < cnt)
+                               goto e2big;
+                       memcpy(s, bom, cnt);
+                       s += cnt, n -= cnt;
+               }
+               psenc->current_endian = ei->preffered_endian;
+       }
+
+       wc2 = 0;
+       if ((ei->mode & _MODE_UTF32)==0) {
+               /* UTF16 */
+               if (wc>0xFFFF) {
+                       /* surrogate */
+                       if (wc>0x10FFFF)
+                               goto ilseq;
+                       if (n < 4)
+                               goto e2big;
+                       cnt += 4;
+                       wc -= 0x10000;
+                       wc2 = (wc & 0x3FF) | 0xDC00;
+                       wc = (wc>>10) | 0xD800;
+               } else {
+                       if (n < 2)
+                               goto e2big;
+                       cnt += 2;
+               }
+
+surrogate:
+               switch (psenc->current_endian) {
+               case _ENDIAN_BIG:
+                       s[1] = wc;
+                       s[0] = (wc >>= 8);
+                       break;
+               case _ENDIAN_LITTLE:
+                       s[0] = wc;
+                       s[1] = (wc >>= 8);
+                       break;
+               }
+               if (wc2!=0) {
+                       wc = wc2;
+                       wc2 = 0;
+                       s += 2;
+                       goto surrogate;
+               }
+       } else {
+               /* UTF32 */
+               if (wc >= 0xD800 && wc <= 0xDFFF)
+                       goto ilseq;
+               if (n < 4)
+                       goto e2big;
+               cnt += 4;
+               switch (psenc->current_endian) {
+               case _ENDIAN_BIG:
+                       s[3] = wc;
+                       s[2] = (wc >>= 8);
+                       s[1] = (wc >>= 8);
+                       s[0] = (wc >>= 8);
+                       break;
+               case _ENDIAN_LITTLE:
+                       s[0] = wc;
+                       s[1] = (wc >>= 8);
+                       s[2] = (wc >>= 8);
+                       s[3] = (wc >>= 8);
+                       break;
+               }
+       }
+       *nresult = cnt;
+
+       return 0;
+
+ilseq:
+       *nresult = (size_t)-1;
+       return EILSEQ;
+e2big:
+       *nresult = (size_t)-1;
+       return E2BIG;
+}
+
+static void
+parse_variable(_UTF1632EncodingInfo * __restrict ei,
+              const void * __restrict var, size_t lenvar)
+{
+#define MATCH(x, act)                                          \
+do {                                                           \
+       if (lenvar >= (sizeof(#x)-1) &&                         \
+           _bcs_strncasecmp(p, #x, sizeof(#x)-1) == 0) {       \
+               act;                                            \
+               lenvar -= sizeof(#x)-1;                         \
+               p += sizeof(#x)-1;                              \
+       }                                                       \
+} while (/*CONSTCOND*/0)
+       const char *p;
+       p = var;
+       while (lenvar>0) {
+               switch (*p) {
+               case 'B':
+               case 'b':
+                       MATCH(big, ei->preffered_endian = _ENDIAN_BIG);
+                       break;
+               case 'L':
+               case 'l':
+                       MATCH(little, ei->preffered_endian = _ENDIAN_LITTLE);
+                       break;
+               case 'F':
+               case 'f':
+                       MATCH(force, ei->mode |= _MODE_FORCE_ENDIAN);
+                       break;
+               case 'U':
+               case 'u':
+                       MATCH(utf32, ei->mode |= _MODE_UTF32);
+                       break;
+               }
+               p++;
+               lenvar--;
+       }
+}
+
+static int
+/*ARGSUSED*/
+_citrus_UTF1632_encoding_module_init(_UTF1632EncodingInfo * __restrict ei,
+                                    const void * __restrict var,
+                                    size_t lenvar)
+{
+       _DIAGASSERT(ei != NULL);
+
+       memset((void *)ei, 0, sizeof(*ei));
+
+       parse_variable(ei, var, lenvar);
+
+       if ((ei->mode&_MODE_UTF32)==0)
+               ei->cur_max = 6; /* endian + surrogate */
+       else
+               ei->cur_max = 8; /* endian + normal */
+
+       if (ei->preffered_endian == _ENDIAN_UNKNOWN) {
+#if BYTE_ORDER == BIG_ENDIAN
+               ei->preffered_endian = _ENDIAN_BIG;
+#else
+               ei->preffered_endian = _ENDIAN_LITTLE;
+#endif
+       }
+
+       return (0);
+}
+
+static void
+/*ARGSUSED*/
+_citrus_UTF1632_encoding_module_uninit(_UTF1632EncodingInfo *ei)
+{
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_UTF1632_stdenc_wctocs(_UTF1632EncodingInfo * __restrict ei,
+                             _csid_t * __restrict csid,
+                             _index_t * __restrict idx,
+                             _wc_t wc)
+{
+
+       _DIAGASSERT(csid != NULL && idx != NULL);
+
+       *csid = 0;
+       *idx = (_index_t)wc;
+
+       return (0);
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_UTF1632_stdenc_cstowc(_UTF1632EncodingInfo * __restrict ei,
+                             _wc_t * __restrict wc,
+                             _csid_t csid, _index_t idx)
+{
+
+       _DIAGASSERT(wc != NULL);
+
+       if (csid != 0)
+               return (EILSEQ);
+
+       *wc = (_wc_t)idx;
+
+       return (0);
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_UTF1632_stdenc_get_state_desc_generic(_UTF1632EncodingInfo * __restrict ei,
+                                             _UTF1632State * __restrict psenc,
+                                             int * __restrict rstate)
+{
+
+       if (psenc->chlen == 0)
+               *rstate = _STDENC_SDGEN_INITIAL;
+       else
+               *rstate = _STDENC_SDGEN_INCOMPLETE_CHAR;
+
+       return 0;
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(UTF1632);
+_CITRUS_STDENC_DEF_OPS(UTF1632);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_utf1632.h b/lib/nbsd_libc/citrus/modules/citrus_utf1632.h
new file mode 100644 (file)
index 0000000..0fac6f3
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: citrus_utf1632.h,v 1.1 2003/06/25 09:51:49 tshiozak Exp $      */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_UTF1632_H_
+#define _CITRUS_UTF1632_H_
+
+__BEGIN_DECLS
+_CITRUS_STDENC_GETOPS_FUNC(UTF1632);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_utf7.c b/lib/nbsd_libc/citrus/modules/citrus_utf7.c
new file mode 100644 (file)
index 0000000..fabb048
--- /dev/null
@@ -0,0 +1,571 @@
+/*     $NetBSD: citrus_utf7.c,v 1.5 2006/08/23 12:57:24 tnozaki Exp $  */
+
+/*-
+ * Copyright (c)2004, 2005 Citrus Project,
+ * 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.
+ *
+ */
+#include <sys/cdefs.h>
+#if defined(LIB_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_utf7.c,v 1.5 2006/08/23 12:57:24 tnozaki Exp $");
+#endif /* LIB_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <wchar.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_utf7.h"
+
+/* ----------------------------------------------------------------------
+ * private stuffs used by templates
+ */
+
+typedef struct {
+       uint16_t        cell[0x80];
+#define        EI_MASK         UINT16_C(0xff)
+#define EI_DIRECT      UINT16_C(0x100)
+#define EI_OPTION      UINT16_C(0x200)
+#define EI_SPACE       UINT16_C(0x400)
+} _UTF7EncodingInfo;
+
+typedef struct {
+       unsigned int
+               mode: 1,        /* whether base64 mode */
+               bits: 4,        /* need to hold 0 - 15 */
+               cache: 22,      /* 22 = BASE64_BIT + UTF16_BIT */
+               surrogate: 1;   /* whether surrogate pair or not */
+       int chlen;
+       char ch[4]; /* BASE64_IN, 3 * 6 = 18, most closed to UTF16_BIT */
+} _UTF7State;
+
+typedef struct {
+       _UTF7EncodingInfo       ei;
+       struct {
+               /* for future multi-locale facility */
+               _UTF7State      s_mblen;
+               _UTF7State      s_mbrlen;
+               _UTF7State      s_mbrtowc;
+               _UTF7State      s_mbtowc;
+               _UTF7State      s_mbsrtowcs;
+               _UTF7State      s_wcrtomb;
+               _UTF7State      s_wcsrtombs;
+               _UTF7State      s_wctomb;
+       } states;
+} _UTF7CTypeInfo;
+
+#define        _CEI_TO_EI(_cei_)               (&(_cei_)->ei)
+#define        _CEI_TO_STATE(_cei_, _func_)    (_cei_)->states.s_##_func_
+
+#define        _FUNCNAME(m)                    _citrus_UTF7_##m
+#define        _ENCODING_INFO                  _UTF7EncodingInfo
+#define        _CTYPE_INFO                     _UTF7CTypeInfo
+#define        _ENCODING_STATE                 _UTF7State
+#define        _ENCODING_MB_CUR_MAX(_ei_)              4
+#define        _ENCODING_IS_STATE_DEPENDENT            1
+#define        _STATE_NEEDS_EXPLICIT_INIT(_ps_)        0
+
+static __inline void
+/*ARGSUSED*/
+_citrus_UTF7_init_state(_UTF7EncodingInfo * __restrict ei,
+       _UTF7State * __restrict s)
+{
+       /* ei appears to be unused */
+       _DIAGASSERT(s != NULL);
+
+       memset((void *)s, 0, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_UTF7_pack_state(_UTF7EncodingInfo * __restrict ei,
+       void *__restrict pspriv, const _UTF7State * __restrict s)
+{
+       /* ei seem to be unused */
+       _DIAGASSERT(pspriv != NULL);
+       _DIAGASSERT(s != NULL);
+
+       memcpy(pspriv, (const void *)s, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_UTF7_unpack_state(_UTF7EncodingInfo * __restrict ei,
+       _UTF7State * __restrict s, const void * __restrict pspriv)
+{
+       /* ei seem to be unused */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(pspriv != NULL);
+
+       memcpy((void *)s, pspriv, sizeof(*s));
+}
+
+static const char base64[] =
+       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+       "abcdefghijklmnopqrstuvwxyz"
+       "0123456789+/";
+
+static const char direct[] =
+       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+       "abcdefghijklmnopqrstuvwxyz"
+       "0123456789(),-./:?";
+
+static const char option[] = "!\"#$%&';<=>@[]^_`{|}";
+static const char spaces[] = " \t\r\n";
+
+#define        BASE64_BIT      6
+#define        UTF16_BIT       16
+
+#define        BASE64_MAX      0x3f
+#define        UTF16_MAX       UINT16_C(0xffff)
+#define        UTF32_MAX       UINT32_C(0x10ffff)
+
+#define        BASE64_IN       '+'
+#define        BASE64_OUT      '-'
+
+#define        SHIFT7BIT(c)    ((c) >> 7)
+#define        ISSPECIAL(c)    ((c) == '\0' || (c) == BASE64_IN)
+
+#define        FINDLEN(ei, c) \
+       (SHIFT7BIT((c)) ? -1 : (((ei)->cell[(c)] & EI_MASK) - 1))
+
+#define        ISDIRECT(ei, c) (!SHIFT7BIT((c)) && (ISSPECIAL((c)) || \
+       ei->cell[(c)] & (EI_DIRECT | EI_OPTION | EI_SPACE)))
+
+#define        ISSAFE(ei, c)   (!SHIFT7BIT((c)) && (ISSPECIAL((c)) || \
+       (c < 0x80 && ei->cell[(c)] & (EI_DIRECT | EI_SPACE))))
+
+/* surrogate pair */
+#define        SRG_BASE        UINT32_C(0x10000)
+#define        HISRG_MIN       UINT16_C(0xd800)
+#define        HISRG_MAX       UINT16_C(0xdbff)
+#define        LOSRG_MIN       UINT16_C(0xdc00)
+#define        LOSRG_MAX       UINT16_C(0xdfff)
+
+static int
+_citrus_UTF7_mbtoutf16(_UTF7EncodingInfo * __restrict ei,
+       uint16_t * __restrict u16, const char ** __restrict s, size_t n,
+       _UTF7State * __restrict psenc, size_t * __restrict nresult)
+{
+       _UTF7State sv;
+       const char *s0;
+       int i, done, len;
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(s != NULL && *s != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       s0 = *s;
+       sv = *psenc;
+
+       for (i = 0, done = 0; done == 0; i++) {
+               _DIAGASSERT(i <= psenc->chlen);
+               if (i == psenc->chlen) {
+                       if (n-- < 1) {
+                               *nresult = (size_t)-2;
+                               *s = s0;
+                               sv.chlen = psenc->chlen;
+                               *psenc = sv;
+                               return 0;
+                       }
+                       psenc->ch[psenc->chlen++] = *s0++;
+               }
+               if (SHIFT7BIT((int)psenc->ch[i]))
+                       goto ilseq;
+               if (!psenc->mode) {
+                       if (psenc->bits > 0 || psenc->cache > 0)
+                               return EINVAL;
+                       if (psenc->ch[i] == BASE64_IN) {
+                               psenc->mode = 1;
+                       } else {
+                               if (!ISDIRECT(ei, (int)psenc->ch[i]))
+                                       goto ilseq;
+                               *u16 = (uint16_t)psenc->ch[i];
+                               done = 1;
+                               continue;
+                       }
+               } else {
+                       if (psenc->ch[i] == BASE64_OUT && psenc->cache == 0) {
+                               psenc->mode = 0;
+                               *u16 = (uint16_t)BASE64_IN;
+                               done = 1;
+                               continue;
+                       }
+                       len = FINDLEN(ei, (int)psenc->ch[i]);
+                       if (len < 0) {
+                               if (psenc->bits >= BASE64_BIT)
+                                       return EINVAL;
+                               psenc->mode = 0;
+                               psenc->bits = psenc->cache = 0;
+                               if (psenc->ch[i] != BASE64_OUT) {
+                                       if (!ISDIRECT(ei, (int)psenc->ch[i]))
+                                               goto ilseq;
+                                       *u16 = (uint16_t)psenc->ch[i];
+                                       done = 1;
+                               }
+                       } else {
+                               psenc->cache =
+                                   (psenc->cache << BASE64_BIT) | len;
+                               switch (psenc->bits) {
+                               case 0: case 2: case 4: case 6: case 8:
+                                       psenc->bits += BASE64_BIT;
+                                       break;
+                               case 10: case 12: case 14:
+                                       psenc->bits -= (UTF16_BIT - BASE64_BIT);
+                                       *u16 = (psenc->cache >> psenc->bits)
+                                           & UTF16_MAX;
+                                       done = 1;
+                                       break;
+                               default:
+                                       return EINVAL;
+                               }
+                       }
+               }
+       }
+
+       if (psenc->chlen > i)
+               return EINVAL;
+       psenc->chlen = 0;
+       *nresult = (size_t)((*u16 == 0) ? 0 : s0 - *s);
+       *s = s0;
+
+       return 0;
+
+ilseq:
+       *nresult = (size_t)-1;
+       return EILSEQ;
+}
+
+static int
+_citrus_UTF7_mbrtowc_priv(_UTF7EncodingInfo * __restrict ei,
+       wchar_t * __restrict pwc, const char ** __restrict s, size_t n,
+       _UTF7State * __restrict psenc, size_t * __restrict nresult)
+{
+       const char *s0;
+       uint32_t u32;
+       uint16_t hi, lo;
+       size_t siz, nr;
+       int err;
+
+       _DIAGASSERT(ei != NULL);
+       /* pwc may be null */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       if (*s == NULL) {
+               _citrus_UTF7_init_state(ei, psenc);
+               *nresult = (size_t)_ENCODING_IS_STATE_DEPENDENT;
+               return 0;
+       }
+       s0 = *s;
+       if (psenc->surrogate) {
+               hi = (psenc->cache >> 2) & UTF16_MAX;
+               if (hi < HISRG_MIN || hi > HISRG_MAX)
+                       return EINVAL;
+               siz = 0;
+       } else {
+               err = _citrus_UTF7_mbtoutf16(ei, &hi, &s0, n, psenc, &nr);
+               if (nr == (size_t)-1 || nr == (size_t)-2) {
+                       *nresult = nr;
+                       return err;
+               }
+               if (err != 0)
+                       return err;
+               n -= nr;
+               siz = nr;
+               if (hi < HISRG_MIN || hi > HISRG_MAX) {
+                       u32 = (uint32_t)hi;
+                       goto done;
+               }
+               psenc->surrogate = 1;
+       }
+       err = _citrus_UTF7_mbtoutf16(ei, &lo, &s0, n, psenc, &nr);
+       if (nr == (size_t)-1 || nr == (size_t)-2) {
+               *nresult = nr;
+               return err;
+       }
+       if (err != 0)
+               return err;
+       hi -= HISRG_MIN;
+       lo -= LOSRG_MIN;
+       u32 = (hi << 10 | lo) + SRG_BASE;
+       siz += nr;
+done:
+       *s = s0;
+       if (pwc != NULL)
+               *pwc = (wchar_t)u32;
+       if (u32 == (uint32_t)0) {
+               *nresult = (size_t)0;
+               _citrus_UTF7_init_state(ei, psenc);
+       } else {
+               *nresult = siz;
+               psenc->surrogate = 0;
+       }
+       return err;
+}
+
+static int
+_citrus_UTF7_utf16tomb(_UTF7EncodingInfo * __restrict ei,
+       char * __restrict s, size_t n, uint16_t u16,
+       _UTF7State * __restrict psenc, size_t * __restrict nresult)
+{
+       int bits, i;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       if (psenc->chlen != 0 || psenc->bits > BASE64_BIT)
+               return EINVAL;
+
+       if (ISSAFE(ei, u16)) {
+               if (psenc->mode) {
+                       if (psenc->bits > 0) {
+                               bits = BASE64_BIT - psenc->bits;
+                               i = (psenc->cache << bits) & BASE64_MAX;
+                               psenc->ch[psenc->chlen++] = base64[i];
+                               psenc->bits = psenc->cache = 0;
+                       }
+                       if (u16 == BASE64_OUT || FINDLEN(ei, u16) >= 0)
+                               psenc->ch[psenc->chlen++] = BASE64_OUT;
+                       psenc->mode = 0;
+               }
+               if (psenc->bits != 0)
+                       return EINVAL;
+               psenc->ch[psenc->chlen++] = (char)u16;
+               if (u16 == BASE64_IN)
+                       psenc->ch[psenc->chlen++] = BASE64_OUT;
+       } else {
+               if (!psenc->mode) {
+                       if (psenc->bits > 0)
+                               return EINVAL;
+                       psenc->ch[psenc->chlen++] = BASE64_IN;
+                       psenc->mode = 1;
+               }
+               psenc->cache = (psenc->cache << UTF16_BIT) | u16;
+               bits = UTF16_BIT + psenc->bits;
+               psenc->bits = bits % BASE64_BIT;
+               while ((bits -= BASE64_BIT) >= 0) {
+                       i = (psenc->cache >> bits) & BASE64_MAX;
+                       psenc->ch[psenc->chlen++] = base64[i];
+               }
+       }
+       memcpy(s, psenc->ch, psenc->chlen);
+       *nresult = psenc->chlen;
+       psenc->chlen = 0;
+
+       return 0;
+}
+
+static int
+_citrus_UTF7_wcrtomb_priv(_UTF7EncodingInfo * __restrict ei,
+       char * __restrict s, size_t n, wchar_t wchar,
+       _UTF7State * __restrict psenc, size_t * __restrict nresult)
+{
+       uint32_t u32;
+       uint16_t u16[2];
+       int err, len, i;
+       size_t siz, nr;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       u32 = (uint32_t)wchar;
+       if (u32 <= UTF16_MAX) {
+               u16[0] = (uint16_t)u32;
+               len = 1;
+       } else if (u32 <= UTF32_MAX) {
+               u32 -= SRG_BASE;
+               u16[0] = (u32 >> 10) + HISRG_MIN;
+               u16[1] = ((uint16_t)(u32 & UINT32_C(0x3ff))) + LOSRG_MIN;
+               len = 2;
+       } else {
+               *nresult = (size_t)-1;
+               return EILSEQ;
+       }
+       siz = 0;
+       for (i = 0; i < len; ++i) {
+               err = _citrus_UTF7_utf16tomb(ei, s, n, u16[i], psenc, &nr);
+               if (err != 0)
+                       return err; /* XXX: state has been modified */
+               s += nr;
+               n -= nr;
+               siz += nr;
+       }
+       *nresult = siz;
+
+       return 0;
+}
+
+static int
+/* ARGSUSED */
+_citrus_UTF7_put_state_reset(_UTF7EncodingInfo * __restrict ei,
+       char * __restrict s, size_t n, _UTF7State * __restrict psenc,
+       size_t * __restrict nresult)
+{
+       int bits, pos;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (psenc->chlen != 0 || psenc->bits > BASE64_BIT || psenc->surrogate)
+               return EINVAL;
+
+       if (psenc->mode) {
+               if (psenc->bits > 0) {
+                       if (n-- < 1)
+                               return E2BIG;
+                       bits = BASE64_BIT - psenc->bits;
+                       pos = (psenc->cache << bits) & BASE64_MAX;
+                       psenc->ch[psenc->chlen++] = base64[pos];
+                       psenc->ch[psenc->chlen++] = BASE64_OUT;
+                       psenc->bits = psenc->cache = 0;
+               }
+               psenc->mode = 0;
+       }
+       if (psenc->bits != 0)
+               return EINVAL;
+       if (n-- < 1)
+               return E2BIG;
+
+       _DIAGASSERT(n >= psenc->chlen);
+       *nresult = (size_t)psenc->chlen;
+       if (psenc->chlen > 0) {
+               memcpy(s, psenc->ch, psenc->chlen);
+               psenc->chlen = 0;
+       }
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_UTF7_stdenc_wctocs(_UTF7EncodingInfo * __restrict ei,
+                          _csid_t * __restrict csid,
+                          _index_t * __restrict idx, wchar_t wc)
+{
+       /* ei seem to be unused */
+       _DIAGASSERT(csid != NULL);
+       _DIAGASSERT(idx != NULL);
+
+       *csid = 0;
+       *idx = (_index_t)wc;
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_UTF7_stdenc_cstowc(_UTF7EncodingInfo * __restrict ei,
+                          wchar_t * __restrict wc,
+                          _csid_t csid, _index_t idx)
+{
+       /* ei seem to be unused */
+       _DIAGASSERT(wc != NULL);
+
+       if (csid != 0)
+               return EILSEQ;
+       *wc = (wchar_t)idx;
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_UTF7_stdenc_get_state_desc_generic(_UTF7EncodingInfo * __restrict ei,
+                                          _UTF7State * __restrict psenc,
+                                          int * __restrict rstate)
+{
+
+       if (psenc->chlen == 0)
+               *rstate = _STDENC_SDGEN_INITIAL;
+       else
+               *rstate = _STDENC_SDGEN_INCOMPLETE_CHAR;
+
+       return 0;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_UTF7_encoding_module_uninit(_UTF7EncodingInfo *ei)
+{
+       /* ei seems to be unused */
+}
+
+static int
+/*ARGSUSED*/
+_citrus_UTF7_encoding_module_init(_UTF7EncodingInfo * __restrict ei,
+                                 const void * __restrict var, size_t lenvar)
+{
+       const char *s;
+
+       _DIAGASSERT(ei != NULL);
+       /* var may be null */
+
+       memset(ei, 0, sizeof(*ei));
+
+#define FILL(str, flag)                                \
+do {                                           \
+       for (s = str; *s != '\0'; s++)          \
+               ei->cell[*s & 0x7f] |= flag;    \
+} while (/*CONSTCOND*/0)
+
+       FILL(base64, (s - base64) + 1);
+       FILL(direct, EI_DIRECT);
+       FILL(option, EI_OPTION);
+       FILL(spaces, EI_SPACE);
+
+       return 0;
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(UTF7);
+_CITRUS_CTYPE_DEF_OPS(UTF7);
+
+#include "citrus_ctype_template.h"
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(UTF7);
+_CITRUS_STDENC_DEF_OPS(UTF7);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_utf7.h b/lib/nbsd_libc/citrus/modules/citrus_utf7.h
new file mode 100644 (file)
index 0000000..8502ace
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: citrus_utf7.h,v 1.1 2005/03/05 18:05:15 tnozaki Exp $  */
+
+/*-
+ * Copyright (c)2004,2005 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_UTF7_H_
+#define _CITRUS_UTF7_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(UTF7);
+_CITRUS_STDENC_GETOPS_FUNC(UTF7);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_utf8.c b/lib/nbsd_libc/citrus/modules/citrus_utf8.c
new file mode 100644 (file)
index 0000000..de22fae
--- /dev/null
@@ -0,0 +1,395 @@
+/*     $NetBSD: citrus_utf8.c,v 1.17 2008/06/14 16:01:08 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Borman at Krystal Technologies.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_utf8.c,v 1.17 2008/06/14 16:01:08 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <wchar.h>
+#include <sys/types.h>
+#include <limits.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_utf8.h"
+
+
+/* ----------------------------------------------------------------------
+ * private stuffs used by templates
+ */
+
+static int _UTF8_count_array[256];
+static int const *_UTF8_count = NULL;
+
+static const u_int32_t _UTF8_range[] = {
+       0,      /*dummy*/
+       0x00000000, 0x00000080, 0x00000800, 0x00010000, 
+       0x00200000, 0x04000000, 0x80000000,
+};
+
+typedef struct {
+       char ch[6];
+       int chlen;
+} _UTF8State;
+
+typedef struct {
+} _UTF8EncodingInfo;
+
+typedef struct {
+       _UTF8EncodingInfo       ei;
+       struct {
+               /* for future multi-locale facility */
+               _UTF8State      s_mblen;
+               _UTF8State      s_mbrlen;
+               _UTF8State      s_mbrtowc;
+               _UTF8State      s_mbtowc;
+               _UTF8State      s_mbsrtowcs;
+               _UTF8State      s_wcrtomb;
+               _UTF8State      s_wcsrtombs;
+               _UTF8State      s_wctomb;
+       } states;
+} _UTF8CTypeInfo;
+
+#define _CEI_TO_EI(_cei_)              (&(_cei_)->ei)
+#define _CEI_TO_STATE(_ei_, _func_)    (_ei_)->states.s_##_func_
+
+#define _FUNCNAME(m)                   _citrus_UTF8_##m
+#define _ENCODING_INFO                 _UTF8EncodingInfo
+#define _CTYPE_INFO                    _UTF8CTypeInfo
+#define _ENCODING_STATE                        _UTF8State
+#define _ENCODING_MB_CUR_MAX(_ei_)     6
+#define _ENCODING_IS_STATE_DEPENDENT   0
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       0
+
+
+static __inline void
+_UTF8_init_count(void)
+{
+       int i;
+       if (!_UTF8_count) {
+               memset(_UTF8_count_array, 0, sizeof(_UTF8_count_array));
+               for (i = 0; i <= 0x7f; i++)
+                       _UTF8_count_array[i] = 1;
+               for (i = 0xc0; i <= 0xdf; i++)
+                       _UTF8_count_array[i] = 2;
+               for (i = 0xe0; i <= 0xef; i++)
+                       _UTF8_count_array[i] = 3;
+               for (i = 0xf0; i <= 0xf7; i++)
+                       _UTF8_count_array[i] = 4;
+               for (i = 0xf8; i <= 0xfb; i++)
+                       _UTF8_count_array[i] = 5;
+               for (i = 0xfc; i <= 0xfd; i++)
+                       _UTF8_count_array[i] = 6;
+               _UTF8_count = _UTF8_count_array;
+       }
+}
+
+static int
+_UTF8_findlen(wchar_t v)
+{
+       int i;
+       u_int32_t c;
+
+       c = (u_int32_t)v;       /*XXX*/
+       for (i = 1; i < sizeof(_UTF8_range) / sizeof(_UTF8_range[0]) - 1; i++)
+               if (c >= _UTF8_range[i] && c < _UTF8_range[i + 1])
+                       return i;
+
+       return -1;      /*out of range*/
+}
+
+static __inline int
+_UTF8_surrogate(wchar_t wc)
+{
+       return wc >= 0xd800 && wc <= 0xdfff;
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_UTF8_init_state(_UTF8EncodingInfo *ei, _UTF8State *s)
+{
+       s->chlen = 0;
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_UTF8_pack_state(_UTF8EncodingInfo *ei, void *pspriv,
+                       const _UTF8State *s)
+{
+       memcpy(pspriv, (const void *)s, sizeof(*s));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_UTF8_unpack_state(_UTF8EncodingInfo *ei, _UTF8State *s,
+                         const void *pspriv)
+{
+       memcpy((void *)s, pspriv, sizeof(*s));
+}
+
+static int
+_citrus_UTF8_mbrtowc_priv(_UTF8EncodingInfo *ei, wchar_t *pwc, const char **s,
+                         size_t n, _UTF8State *psenc, size_t *nresult)
+{
+       wchar_t wchar;
+       const char *s0;
+       int c;
+       int i;
+
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       s0 = *s;
+
+       if (s0 == NULL) {
+               _citrus_UTF8_init_state(ei, psenc);
+               *nresult = 0; /* state independent */
+               return 0;
+       }
+
+       /* make sure we have the first byte in the buffer */
+       if (psenc->chlen == 0) {
+               if (n-- < 1)
+                       goto restart;
+               psenc->ch[psenc->chlen++] = *s0++;
+       }
+
+       c = _UTF8_count[psenc->ch[0] & 0xff];
+       if (c < 1 || c < psenc->chlen)
+               goto ilseq;
+
+       if (c == 1)
+               wchar = psenc->ch[0] & 0xff;
+       else {
+               while (psenc->chlen < c) {
+                       if (n-- < 1)
+                               goto restart;
+                       psenc->ch[psenc->chlen++] = *s0++;
+               }
+               wchar = psenc->ch[0] & (0x7f >> c);
+               for (i = 1; i < c; i++) {
+                       if ((psenc->ch[i] & 0xc0) != 0x80)
+                               goto ilseq;
+                       wchar <<= 6;
+                       wchar |= (psenc->ch[i] & 0x3f);
+               }
+               if (_UTF8_surrogate(wchar) || _UTF8_findlen(wchar) != c)
+                       goto ilseq;
+       }
+       if (pwc != NULL)
+               *pwc = wchar;
+       *nresult = (wchar == 0) ? 0 : s0 - *s;
+       *s = s0;
+       psenc->chlen = 0;
+
+       return 0;
+
+ilseq:
+       *nresult = (size_t)-1;
+       return EILSEQ;
+
+restart:
+       *s = s0;
+       *nresult = (size_t)-2;
+       return 0;
+}
+
+static int
+_citrus_UTF8_wcrtomb_priv(_UTF8EncodingInfo *ei, char *s, size_t n, wchar_t wc,
+                         _UTF8State *psenc, size_t *nresult)
+{
+       int cnt, i, ret;
+       wchar_t c;
+
+       _DIAGASSERT(nresult != 0);
+       _DIAGASSERT(s != NULL);
+
+       if (_UTF8_surrogate(wc)) {
+               ret = EILSEQ;
+               goto err;
+       }
+       cnt = _UTF8_findlen(wc);
+       if (cnt <= 0 || cnt > 6) {
+               /* invalid UCS4 value */
+               ret = EILSEQ;
+               goto err;
+       }
+       if (n < cnt) {
+               /* bound check failure */
+               ret = E2BIG;
+               goto err;
+       }
+
+       c = wc;
+       if (s) {
+               for (i = cnt - 1; i > 0; i--) {
+                       s[i] = 0x80 | (c & 0x3f);
+                       c >>= 6;
+               }
+               s[0] = c;
+               if (cnt == 1)
+                       s[0] &= 0x7f;
+               else {
+                       s[0] &= (0x7f >> cnt);
+                       s[0] |= ((0xff00 >> cnt) & 0xff);
+               }
+       }
+
+       *nresult = (size_t)cnt;
+       return 0;
+
+err:
+       *nresult = (size_t)-1;
+       return ret;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_UTF8_stdenc_wctocs(_UTF8EncodingInfo * __restrict ei,
+                          _csid_t * __restrict csid,
+                          _index_t * __restrict idx,
+                          wchar_t wc)
+{
+
+       _DIAGASSERT(csid != NULL && idx != NULL);
+
+       *csid = 0;
+       *idx = (_citrus_index_t)wc;
+
+       return (0);
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_UTF8_stdenc_cstowc(_UTF8EncodingInfo * __restrict ei,
+                          wchar_t * __restrict wc,
+                          _csid_t csid, _index_t idx)
+{
+
+       _DIAGASSERT(wc != NULL);
+
+       if (csid != 0)
+               return (EILSEQ);
+
+       *wc = (wchar_t)idx;
+
+       return (0);
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_UTF8_stdenc_get_state_desc_generic(_UTF8EncodingInfo * __restrict ei,
+                                          _UTF8State * __restrict psenc,
+                                          int * __restrict rstate)
+{
+
+       if (psenc->chlen == 0)
+               *rstate = _STDENC_SDGEN_INITIAL;
+       else
+               *rstate = _STDENC_SDGEN_INCOMPLETE_CHAR;
+
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_UTF8_encoding_module_init(_UTF8EncodingInfo * __restrict ei,
+                                 const void * __restrict var, size_t lenvar)
+{
+       _UTF8_init_count();
+
+       return 0;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_UTF8_encoding_module_uninit(_UTF8EncodingInfo *ei)
+{
+}
+
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(UTF8);
+_CITRUS_CTYPE_DEF_OPS(UTF8);
+
+#include "citrus_ctype_template.h"
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(UTF8);
+_CITRUS_STDENC_DEF_OPS(UTF8);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_utf8.h b/lib/nbsd_libc/citrus/modules/citrus_utf8.h
new file mode 100644 (file)
index 0000000..9e57b6b
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: citrus_utf8.h,v 1.2 2003/06/25 09:51:49 tshiozak Exp $ */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_UTF8_H_
+#define _CITRUS_UTF8_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(UTF8);
+_CITRUS_STDENC_GETOPS_FUNC(UTF8);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_viqr.c b/lib/nbsd_libc/citrus/modules/citrus_viqr.c
new file mode 100644 (file)
index 0000000..f27c6cf
--- /dev/null
@@ -0,0 +1,572 @@
+/* $NetBSD: citrus_viqr.c,v 1.4 2008/06/14 16:01:08 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2006 Citrus Project,
+ * 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.
+ *
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_viqr.c,v 1.4 2008/06/14 16:01:08 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/queue.h>
+#include <sys/types.h>
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <wchar.h>
+#include <limits.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_bcs.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_viqr.h"
+
+#define ESCAPE '\\'
+
+/*
+ * this table generated from RFC 1456.
+ */
+static const char *mnemonic_rfc1456[0x100] = {
+  NULL , NULL , "A(?", NULL , NULL , "A(~", "A^~", NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  NULL , NULL , NULL , NULL , "Y?" , NULL , NULL , NULL ,
+  NULL , "Y~" , NULL , NULL , NULL , NULL , "Y." , NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL ,
+  "A." , "A('", "A(`", "A(.", "A^'", "A^`", "A^?", "A^.",
+  "E~" , "E." , "E^'", "E^`", "E^?", "E^~", "E^.", "O^'",
+  "O^`", "O^?", "O^~", "O^.", "O+.", "O+'", "O+`", "O+?",
+  "I." , "O?" , "O." , "I?" , "U?" , "U~" , "U." , "Y`" ,
+  "O~" , "a('", "a(`", "a(.", "a^'", "a^`", "a^?", "a^.",
+  "e~" , "e." , "e^'", "e^`", "e^?", "e^~", "e^.", "o^'",
+  "o^`", "o^?", "o^~", "O+~", "O+" , "o^.", "o+`", "o+?",
+  "i." , "U+.", "U+'", "U+`", "U+?", "o+" , "o+'", "U+" ,
+  "A`" , "A'" , "A^" , "A~" , "A?" , "A(" , "a(?", "a(~",
+  "E`" , "E'" , "E^" , "E?" , "I`" , "I'" , "I~" , "y`" ,
+  "DD" , "u+'", "O`" , "O'" , "O^" , "a." , "y?" , "u+`",
+  "u+?", "U`" , "U'" , "y~" , "y." , "Y'" , "o+~", "u+" ,
+  "a`" , "a'" , "a^" , "a~" , "a?" , "a(" , "u+~", "a^~",
+  "e`" , "e'" , "e^" , "e?" , "i`" , "i'" , "i~" , "i?" ,
+  "dd" , "u+.", "o`" , "o'" , "o^" , "o~" , "o?" , "o." ,
+  "u." , "u`" , "u'" , "u~" , "u?" , "y'" , "o+.", "U+~",
+};
+
+typedef struct {
+       const char *name;
+       wchar_t value;
+} mnemonic_def_t;
+
+static const mnemonic_def_t mnemonic_ext[] = {
+/* add extra mnemonic here (should be sorted by wchar_t order). */
+};
+static const size_t mnemonic_ext_size =
+       sizeof(mnemonic_ext) / sizeof(mnemonic_def_t);
+
+static const char *
+mnemonic_ext_find(wchar_t wc, const mnemonic_def_t *head, size_t n)
+{
+       const mnemonic_def_t *mid;
+
+       _DIAGASSERT(head != NULL);
+
+       for (; n > 0; n >>= 1) {
+               mid = head + (n >> 1);
+               if (mid->value == wc) {
+                       return mid->name;
+               } else if (mid->value < wc) {
+                       head = mid + 1;
+                       --n;
+               }
+       }
+       return NULL;
+}
+
+struct mnemonic_t;
+typedef TAILQ_HEAD(mnemonic_list_t, mnemonic_t) mnemonic_list_t;
+typedef struct mnemonic_t {
+       TAILQ_ENTRY(mnemonic_t) entry;
+       int ascii;
+       struct mnemonic_t *parent;
+       mnemonic_list_t child;
+       wchar_t value;
+} mnemonic_t;
+
+static mnemonic_t *
+mnemonic_list_find(mnemonic_list_t *ml, int ch)
+{
+       mnemonic_t *m;
+
+       _DIAGASSERT(ml != NULL);
+
+       TAILQ_FOREACH(m, ml, entry) {
+               if (m->ascii == ch)
+                       return m;
+       }
+
+       return NULL;
+}
+
+static mnemonic_t *
+mnemonic_create(mnemonic_t *parent, int ascii, wchar_t value)
+{
+       mnemonic_t *m;
+
+       _DIAGASSERT(parent != NULL);
+
+       m = malloc(sizeof(*m));
+       if (m != NULL) {
+               m->parent = parent;
+               m->ascii = ascii;
+               m->value = value;
+               TAILQ_INIT(&m->child);
+       }
+
+       return m;
+}
+
+static int
+mnemonic_append_child(mnemonic_t *m, const char *s,
+       wchar_t value, wchar_t invalid)
+{
+       int ch;
+       mnemonic_t *m0;
+
+       _DIAGASSERT(m != NULL);
+       _DIAGASSERT(s != NULL);
+
+       ch = (unsigned char)*s++;
+       if (ch == '\0')
+               return EINVAL;
+       m0 = mnemonic_list_find(&m->child, ch);
+       if (m0 == NULL) {
+               m0 = mnemonic_create(m, ch, (wchar_t)ch);
+               if (m0 == NULL)
+                       return ENOMEM;
+               TAILQ_INSERT_TAIL(&m->child, m0, entry);
+       }
+       m = m0;
+       for (m0 = NULL; (ch = (unsigned char)*s) != '\0'; ++s) {
+               m0 = mnemonic_list_find(&m->child, ch);
+               if (m0 == NULL) {
+                       m0 = mnemonic_create(m, ch, invalid);
+                       if (m0 == NULL)
+                               return ENOMEM;
+                       TAILQ_INSERT_TAIL(&m->child, m0, entry);
+               }
+               m = m0;
+       }
+       if (m0 == NULL)
+               return EINVAL;
+       m0->value = value;
+
+       return 0;
+}
+
+static void
+mnemonic_destroy(mnemonic_t *m)
+{
+       mnemonic_t *m0;
+
+       _DIAGASSERT(m != NULL);
+
+       TAILQ_FOREACH(m0, &m->child, entry)
+               mnemonic_destroy(m0);
+       free(m);
+}
+
+typedef struct {
+       size_t mb_cur_max;
+       wchar_t invalid;
+       mnemonic_t *mroot;
+} _VIQREncodingInfo;
+
+typedef struct {
+       int chlen;
+       char ch[MB_LEN_MAX];
+} _VIQRState;
+
+typedef struct {
+       _VIQREncodingInfo       ei;
+       struct {
+               /* for future multi-locale facility */
+               _VIQRState      s_mblen;
+               _VIQRState      s_mbrlen;
+               _VIQRState      s_mbrtowc;
+               _VIQRState      s_mbtowc;
+               _VIQRState      s_mbsrtowcs;
+               _VIQRState      s_wcrtomb;
+               _VIQRState      s_wcsrtombs;
+               _VIQRState      s_wctomb;
+       } states;
+} _VIQRCTypeInfo;
+
+#define _CEI_TO_EI(_cei_)              (&(_cei_)->ei)
+#define _CEI_TO_STATE(_cei_, _func_)   (_cei_)->states.s_##_func_
+
+#define _FUNCNAME(m)                   _citrus_VIQR_##m
+#define _ENCODING_INFO                 _VIQREncodingInfo
+#define _CTYPE_INFO                    _VIQRCTypeInfo
+#define _ENCODING_STATE                        _VIQRState
+#define _ENCODING_MB_CUR_MAX(_ei_)     (_ei_)->mb_cur_max
+#define _ENCODING_IS_STATE_DEPENDENT           1
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       0
+
+static __inline void
+/*ARGSUSED*/
+_citrus_VIQR_init_state(_VIQREncodingInfo * __restrict ei,
+       _VIQRState * __restrict psenc)
+{
+       /* ei may be unused */
+       _DIAGASSERT(psenc != NULL);
+
+       psenc->chlen = 0;
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_VIQR_pack_state(_VIQREncodingInfo * __restrict ei,
+       void *__restrict pspriv, const _VIQRState * __restrict psenc)
+{
+       /* ei may be unused */
+       _DIAGASSERT(pspriv != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       memcpy(pspriv, (const void *)psenc, sizeof(*psenc));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_VIQR_unpack_state(_VIQREncodingInfo * __restrict ei,
+       _VIQRState * __restrict psenc, const void * __restrict pspriv)
+{
+       /* ei may be unused */
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(pspriv != NULL);
+
+       memcpy((void *)psenc, pspriv, sizeof(*psenc));
+}
+
+static int
+_citrus_VIQR_mbrtowc_priv(_VIQREncodingInfo * __restrict ei,
+       wchar_t * __restrict pwc, const char ** __restrict s, size_t n,
+       _VIQRState * __restrict psenc, size_t * __restrict nresult)
+{
+       const char *s0;
+       wchar_t wc;
+       mnemonic_t *m, *m0;
+       size_t i;
+       int ch, escape;
+
+       _DIAGASSERT(ei != NULL);
+       /* pwc may be null */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (*s == NULL) {
+               _citrus_VIQR_init_state(ei, psenc);
+               *nresult = (size_t)_ENCODING_IS_STATE_DEPENDENT;
+               return 0;
+       }
+       s0 = *s;
+
+       i = 0;
+       m = ei->mroot;
+       for (escape = 0;;) {
+               if (psenc->chlen == i) {
+                       if (n-- < 1) {
+                               *s = s0;
+                               *nresult = (size_t)-2;
+                               return 0;
+                       }
+                       psenc->ch[psenc->chlen++] = *s0++;
+               }
+               ch = (unsigned char)psenc->ch[i++];
+               if (ch == ESCAPE) {
+                       if (m != ei->mroot)
+                               break;
+                       escape = 1;
+                       continue;
+               }
+               if (escape != 0)
+                       break;
+               m0 = mnemonic_list_find(&m->child, ch);
+               if (m0 == NULL)
+                       break;
+               m = m0;
+       }
+       while (m != ei->mroot) {
+               --i;
+               if (m->value != ei->invalid)
+                       break;
+               m = m->parent;
+       }
+       if (ch == ESCAPE && m != ei->mroot)
+               ++i;
+       psenc->chlen -= i;
+       memmove(&psenc->ch[0], &psenc->ch[i], psenc->chlen);
+       wc = (m == ei->mroot) ? (wchar_t)ch : m->value;
+       if (pwc != NULL)
+               *pwc = wc;
+       *nresult = (size_t)(wc == 0 ? 0 : s0 - *s);
+       *s = s0;
+
+       return 0;
+}
+
+static int
+_citrus_VIQR_wcrtomb_priv(_VIQREncodingInfo * __restrict ei,
+       char * __restrict s, size_t n, wchar_t wc,
+       _VIQRState * __restrict psenc, size_t * __restrict nresult)
+{
+       mnemonic_t *m;
+       int ch, escape;
+       const char *p;
+
+       _DIAGASSERT(ei != NULL);
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       switch (psenc->chlen) {
+       case 0: case 1:
+               break;
+       default:
+               return EINVAL;
+       }
+       m = NULL;
+       if ((uint32_t)wc <= 0xFF) {
+               p = mnemonic_rfc1456[wc & 0xFF];
+               if (p != NULL)
+                       goto mnemonic_found;
+               if (n-- < 1)
+                       goto e2big;
+               ch = (unsigned int)wc;
+               m = ei->mroot;
+               if (psenc->chlen > 0) {
+                       m = mnemonic_list_find(&m->child, psenc->ch[0]);
+                       if (m == NULL)
+                               return EINVAL;
+                       psenc->ch[0] = ESCAPE;
+               }
+               if (mnemonic_list_find(&m->child, ch) == NULL) {
+                       psenc->chlen = 0;
+                       m = NULL;
+               }
+               psenc->ch[psenc->chlen++] = ch;
+       } else {
+               p = mnemonic_ext_find(wc, &mnemonic_ext[0], mnemonic_ext_size);
+               if (p == NULL) {
+                       *nresult = (size_t)-1;
+                       return EILSEQ;
+               } else {
+mnemonic_found:
+                       psenc->chlen = 0;
+                       while (*p != '\0') {
+                               if (n-- < 1)
+                                       goto e2big;
+                               psenc->ch[psenc->chlen++] = *p++;
+                       }
+               }
+       }
+       memcpy(s, psenc->ch, psenc->chlen);
+       *nresult = psenc->chlen;
+       if (m == ei->mroot) {
+               psenc->ch[0] = ch;
+               psenc->chlen = 1;
+       } else {
+               psenc->chlen = 0;
+       }
+
+       return 0;
+
+e2big:
+       *nresult = (size_t)-1;
+       return E2BIG;
+}
+
+static int
+/* ARGSUSED */
+_citrus_VIQR_put_state_reset(_VIQREncodingInfo * __restrict ei,
+       char * __restrict s, size_t n, _VIQRState * __restrict psenc,
+       size_t * __restrict nresult)
+{
+       /* ei may be unused */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       switch (psenc->chlen) {
+       case 0: case 1:
+               break;
+       default:
+               return EINVAL;
+       }
+       *nresult = 0;
+       psenc->chlen = 0;
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_VIQR_stdenc_wctocs(_VIQREncodingInfo * __restrict ei,
+       _csid_t * __restrict csid, _index_t * __restrict idx, wchar_t wc)
+{
+       /* ei may be unused */
+       _DIAGASSERT(csid != NULL);
+       _DIAGASSERT(idx != NULL);
+
+       *csid = 0;
+       *idx = (_index_t)wc;
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_VIQR_stdenc_cstowc(_VIQREncodingInfo * __restrict ei,
+       wchar_t * __restrict pwc, _csid_t csid, _index_t idx)
+{
+       /* ei may be unused */
+       _DIAGASSERT(pwc != NULL);
+
+       if (csid != 0)
+               return EILSEQ;
+       *pwc = (wchar_t)idx;
+
+       return 0;
+}
+
+static void
+_citrus_VIQR_encoding_module_uninit(_VIQREncodingInfo *ei)
+{
+       _DIAGASSERT(ei != NULL);
+
+       mnemonic_destroy(ei->mroot);
+}
+
+static int
+/*ARGSUSED*/
+_citrus_VIQR_encoding_module_init(_VIQREncodingInfo * __restrict ei,
+       const void * __restrict var, size_t lenvar)
+{
+       int errnum;
+       const char *s;
+       size_t i, n;
+       const mnemonic_def_t *p;
+
+       _DIAGASSERT(ei != NULL);
+       /* var may be unused */
+
+       ei->mb_cur_max = 1;
+       ei->invalid = (wchar_t)-1;
+       ei->mroot = mnemonic_create(NULL, '\0', ei->invalid);
+       if (ei->mroot == NULL)
+               return ENOMEM;
+       for (i = 0; i < sizeof(mnemonic_rfc1456) / sizeof(const char *); ++i) {
+               s = mnemonic_rfc1456[i];
+               if (s == NULL)
+                       continue;
+               n = strlen(s);
+               _DIAGASSERT(n <= MB_LEN_MAX);
+               if (ei->mb_cur_max < n)
+                       ei->mb_cur_max = n;
+               errnum = mnemonic_append_child(ei->mroot,
+                   s, (wchar_t)i, ei->invalid);
+               if (errnum != 0) {
+                       _citrus_VIQR_encoding_module_uninit(ei);
+                       return errnum;
+               }
+       }
+       for (i = 0; i < mnemonic_ext_size; ++i) {
+               p = &mnemonic_ext[i];
+               _DIAGASSERT(p != NULL && p->name != NULL);
+               n = strlen(p->name);
+               _DIAGASSERT(n <= MB_LEN_MAX);
+               if (ei->mb_cur_max < n)
+                       ei->mb_cur_max = n;
+               errnum = mnemonic_append_child(ei->mroot,
+                   p->name, p->value, ei->invalid);
+               if (errnum != 0) {
+                       _citrus_VIQR_encoding_module_uninit(ei);
+                       return errnum;
+               }
+       }
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_VIQR_stdenc_get_state_desc_generic(_VIQREncodingInfo * __restrict ei,
+       _VIQRState * __restrict psenc, int * __restrict rstate)
+{
+       /* ei may be unused */
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(rstate != NULL);
+
+       *rstate = (psenc->chlen == 0)
+           ? _STDENC_SDGEN_INITIAL
+           : _STDENC_SDGEN_INCOMPLETE_CHAR;
+
+       return 0;
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(VIQR);
+_CITRUS_CTYPE_DEF_OPS(VIQR);
+
+#include "citrus_ctype_template.h"
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(VIQR);
+_CITRUS_STDENC_DEF_OPS(VIQR);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_viqr.h b/lib/nbsd_libc/citrus/modules/citrus_viqr.h
new file mode 100644 (file)
index 0000000..9315429
--- /dev/null
@@ -0,0 +1,37 @@
+/* $NetBSD: citrus_viqr.h,v 1.1 2006/11/13 15:16:31 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2006 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_VIQR_H_
+#define _CITRUS_VIQR_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(VIQR);
+_CITRUS_STDENC_GETOPS_FUNC(VIQR);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/citrus/modules/citrus_zw.c b/lib/nbsd_libc/citrus/modules/citrus_zw.c
new file mode 100644 (file)
index 0000000..485d53a
--- /dev/null
@@ -0,0 +1,512 @@
+/* $NetBSD: citrus_zw.c,v 1.4 2008/06/14 16:01:08 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2004, 2006 Citrus Project,
+ * 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.
+ *
+ */
+#include <sys/cdefs.h>
+#if defined(LIB_SCCS) && !defined(lint)
+__RCSID("$NetBSD: citrus_zw.c,v 1.4 2008/06/14 16:01:08 tnozaki Exp $");
+#endif /* LIB_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <wchar.h>
+#include <limits.h>
+
+#include "citrus_namespace.h"
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "citrus_stdenc.h"
+#include "citrus_zw.h"
+
+/* ----------------------------------------------------------------------
+ * private stuffs used by templates
+ */
+
+typedef struct {
+       int dummy;
+} _ZWEncodingInfo;
+
+typedef enum {
+       NONE, AMBIGIOUS, ASCII, GB2312
+} _ZWCharset;
+
+typedef struct {
+       int             chlen;
+       char            ch[4];
+       _ZWCharset      charset;
+} _ZWState;
+
+typedef struct {
+       _ZWEncodingInfo ei;
+       struct {
+               /* for future multi-locale facility */
+               _ZWState        s_mblen;
+               _ZWState        s_mbrlen;
+               _ZWState        s_mbrtowc;
+               _ZWState        s_mbtowc;
+               _ZWState        s_mbsrtowcs;
+               _ZWState        s_wcrtomb;
+               _ZWState        s_wcsrtombs;
+               _ZWState        s_wctomb;
+       } states;
+} _ZWCTypeInfo;
+
+#define _CEI_TO_EI(_cei_)              (&(_cei_)->ei)
+#define _CEI_TO_STATE(_cei_, _func_)   (_cei_)->states.s_##_func_
+
+#define _FUNCNAME(m)                   _citrus_ZW_##m
+#define _ENCODING_INFO                 _ZWEncodingInfo
+#define _CTYPE_INFO                    _ZWCTypeInfo
+#define _ENCODING_STATE                        _ZWState
+#define _ENCODING_MB_CUR_MAX(_ei_)     MB_LEN_MAX
+#define _ENCODING_IS_STATE_DEPENDENT           1
+#define _STATE_NEEDS_EXPLICIT_INIT(_ps_)       ((_ps_)->charset != NONE)
+
+static __inline void
+/*ARGSUSED*/
+_citrus_ZW_init_state(_ZWEncodingInfo * __restrict ei,
+       _ZWState * __restrict psenc)
+{
+       /* ei my be unused */
+       _DIAGASSERT(psenc != NULL);
+
+       psenc->chlen = 0;
+       psenc->charset = NONE;
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_ZW_pack_state(_ZWEncodingInfo * __restrict ei,
+       void *__restrict pspriv, const _ZWState * __restrict psenc)
+{
+       /* ei may be unused */
+       _DIAGASSERT(pspriv != NULL);
+       _DIAGASSERT(psenc != NULL);
+
+       memcpy(pspriv, (const void *)psenc, sizeof(*psenc));
+}
+
+static __inline void
+/*ARGSUSED*/
+_citrus_ZW_unpack_state(_ZWEncodingInfo * __restrict ei,
+       _ZWState * __restrict psenc, const void * __restrict pspriv)
+{
+       /* ei may be unused */
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(pspriv != NULL);
+
+       memcpy((void *)psenc, pspriv, sizeof(*psenc));
+}
+
+static int
+_citrus_ZW_mbrtowc_priv(_ZWEncodingInfo * __restrict ei,
+       wchar_t * __restrict pwc, const char **__restrict s, size_t n,
+       _ZWState * __restrict psenc, size_t * __restrict nresult)
+{
+       const char *s0;
+       int ch, len;
+       wchar_t  wc;
+
+       /* ei may be unused */
+       /* pwc may be null */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (*s == NULL) {
+               _citrus_ZW_init_state(ei, psenc);
+               *nresult = (size_t)_ENCODING_IS_STATE_DEPENDENT;
+               return 0;
+       }
+       s0 = *s;
+       len = 0;
+
+#define        STORE                           \
+do {                                   \
+       if (n-- < 1) {                  \
+               *nresult = (size_t)-2;  \
+               *s = s0;                \
+               return 0;               \
+       }                               \
+       ch = (unsigned char)*s0++;      \
+       if (len++ > MB_LEN_MAX || ch > 0x7F)\
+               goto ilseq;             \
+       psenc->ch[psenc->chlen++] = ch; \
+} while (/*CONSTCOND*/0)
+
+loop:
+       switch (psenc->charset) {
+       case ASCII:
+               switch (psenc->chlen) {
+               case 0:
+                       STORE;
+                       switch (psenc->ch[0]) {
+                       case '\0': case '\n':
+                               psenc->charset = NONE;
+                       }
+               /*FALLTHROUGH*/
+               case 1:
+                       break;
+               default:
+                       return EINVAL;
+               }
+               ch = (unsigned char)psenc->ch[0];
+               if (ch > 0x7F)
+                       goto ilseq;
+               wc = (wchar_t)ch;
+               psenc->chlen = 0;
+               break;
+       case NONE:
+               if (psenc->chlen != 0)
+                       return EINVAL;
+               STORE;
+               ch = (unsigned char)psenc->ch[0];
+               if (ch != 'z') {
+                       if (ch != '\n' && ch != '\0')
+                               psenc->charset = ASCII;
+                       wc = (wchar_t)ch;
+                       psenc->chlen = 0;
+                       break;
+               }
+               psenc->charset = AMBIGIOUS;
+               psenc->chlen = 0;
+       /* FALLTHROUGH */
+       case AMBIGIOUS:
+               if (psenc->chlen != 0)
+                       return EINVAL;
+               STORE;
+               if (psenc->ch[0] != 'W') {
+                       psenc->charset = ASCII;
+                       wc = L'z';
+                       break;
+               }
+               psenc->charset = GB2312;
+               psenc->chlen = 0;
+       /* FALLTHROUGH */
+       case GB2312:
+               switch (psenc->chlen) {
+               case 0:
+                       STORE;
+                       ch = (unsigned char)psenc->ch[0];
+                       if (ch == '\0') {
+                               psenc->charset = NONE;
+                               wc = (wchar_t)ch;
+                               psenc->chlen = 0;
+                               break;
+                       } else if (ch == '\n') {
+                               psenc->charset = NONE;
+                               psenc->chlen = 0;
+                               goto loop;
+                       }
+               /*FALLTHROUGH*/
+               case 1:
+                       STORE;
+                       if (psenc->ch[0] == ' ') {
+                               ch = (unsigned char)psenc->ch[1];
+                               wc = (wchar_t)ch;
+                               psenc->chlen = 0;
+                               break;
+                       } else if (psenc->ch[0] == '#') {
+                               ch = (unsigned char)psenc->ch[1];
+                               if (ch == '\n') {
+                                       psenc->charset = NONE;
+                                       wc = (wchar_t)ch;
+                                       psenc->chlen = 0;
+                                       break;
+                               } else if (ch == ' ') {
+                                       wc = (wchar_t)ch;
+                                       psenc->chlen = 0;
+                                       break;
+                               }
+                       }
+                       ch = (unsigned char)psenc->ch[0];
+                       if (ch < 0x21 || ch > 0x7E)
+                               goto ilseq;
+                       wc = (wchar_t)(ch << 8);
+                       ch = (unsigned char)psenc->ch[1];
+                       if (ch < 0x21 || ch > 0x7E) {
+ilseq:
+                               *nresult = (size_t)-1;
+                               return EILSEQ;
+                       }
+                       wc |= (wchar_t)ch;
+                       psenc->chlen = 0;
+                       break;
+               default:
+                       return EINVAL;
+               }
+               break;
+       default:
+               return EINVAL;
+       }
+       if (pwc != NULL)
+               *pwc = wc;
+
+       *nresult = (size_t)(wc == 0 ? 0 : len);
+       *s = s0;
+
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_ZW_wcrtomb_priv(_ZWEncodingInfo * __restrict ei,
+       char *__restrict s, size_t n, wchar_t wc,
+       _ZWState * __restrict psenc, size_t * __restrict nresult)
+{
+       int ch;
+
+       /* ei may be null */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (psenc->chlen != 0)
+               return EINVAL;
+       if ((uint32_t)wc <= 0x7F) {
+               ch = (unsigned char)wc;
+               switch (psenc->charset) {
+               case NONE:
+                       if (ch == '\0' || ch == '\n') {
+                               psenc->ch[psenc->chlen++] = ch;
+                       } else {
+                               if (n < 4)
+                                       return E2BIG;
+                               n -= 4;
+                               psenc->ch[psenc->chlen++] = 'z';
+                               psenc->ch[psenc->chlen++] = 'W';
+                               psenc->ch[psenc->chlen++] = ' ';
+                               psenc->ch[psenc->chlen++] = ch;
+                               psenc->charset = GB2312;
+                       }
+                       break;
+               case GB2312:
+                       if (n < 2)
+                               return E2BIG;
+                       n -= 2;
+                       if (ch == '\0') {
+                               psenc->ch[psenc->chlen++] = '\n';
+                               psenc->ch[psenc->chlen++] = '\0';
+                               psenc->charset = NONE;
+                       } else if (ch == '\n') {
+                               psenc->ch[psenc->chlen++] = '#';
+                               psenc->ch[psenc->chlen++] = '\n';
+                               psenc->charset = NONE;
+                       } else {
+                               psenc->ch[psenc->chlen++] = ' ';
+                               psenc->ch[psenc->chlen++] = ch;
+                       }
+                       break;
+               default:
+                       return EINVAL;
+               }
+       } else if ((uint32_t)wc <= 0x7E7E) {
+               switch (psenc->charset) {
+               case NONE:
+                       if (n < 2)
+                               return E2BIG;
+                       n -= 2;
+                       psenc->ch[psenc->chlen++] = 'z';
+                       psenc->ch[psenc->chlen++] = 'W';
+                       psenc->charset = GB2312;
+               /* FALLTHROUGH*/
+               case GB2312:
+                       if (n < 2)
+                               return E2BIG;
+                       n -= 2;
+                       ch = (wc >> 8) & 0xFF;
+                       if (ch < 0x21 || ch > 0x7E)
+                               goto ilseq;
+                       psenc->ch[psenc->chlen++] = ch;
+                       ch = wc & 0xFF;
+                       if (ch < 0x21 || ch > 0x7E)
+                               goto ilseq;
+                       psenc->ch[psenc->chlen++] = ch;
+                       break;
+               default:
+                       return EINVAL;
+               }
+       } else {
+ilseq:
+               *nresult = (size_t)-1;
+               return EILSEQ;
+       }
+       memcpy(s, psenc->ch, psenc->chlen);
+       *nresult = psenc->chlen;
+       psenc->chlen = 0;
+
+       return 0;
+}
+
+static int
+/*ARGSUSED*/
+_citrus_ZW_put_state_reset(_ZWEncodingInfo * __restrict ei,
+       char * __restrict s, size_t n,
+       _ZWState * __restrict psenc, size_t * __restrict nresult)
+{
+       /* ei may be unused */
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(nresult != NULL);
+
+       if (psenc->chlen != 0)
+               return EINVAL;
+       switch (psenc->charset) {
+       case GB2312:
+               if (n-- < 1)
+                       return E2BIG;
+               psenc->ch[psenc->chlen++] = '\n';
+               psenc->charset = NONE;
+       /*FALLTHROUGH*/
+       case NONE:
+               *nresult = psenc->chlen;
+               if (psenc->chlen > 0) {
+                       memcpy(s, psenc->ch, psenc->chlen);
+                       psenc->chlen = 0;
+               }
+               break;
+       default:
+               return EINVAL;
+       }
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_ZW_stdenc_get_state_desc_generic(_ZWEncodingInfo * __restrict ei,
+       _ZWState * __restrict psenc, int * __restrict rstate)
+{
+       /* ei may be unused */
+       _DIAGASSERT(psenc != NULL);
+       _DIAGASSERT(rstate != NULL);
+
+       switch (psenc->charset) {
+       case NONE:
+               if (psenc->chlen != 0)
+                       return EINVAL;
+               *rstate = _STDENC_SDGEN_INITIAL;
+               break;
+       case AMBIGIOUS:
+               if (psenc->chlen != 0)
+                       return EINVAL;
+               *rstate = _STDENC_SDGEN_INCOMPLETE_SHIFT;
+               break;
+       case ASCII:
+       case GB2312:
+               switch (psenc->chlen) {
+               case 0:
+                       *rstate = _STDENC_SDGEN_STABLE;
+                       break;
+               case 1:
+                       *rstate = (psenc->ch[0] == '#')
+                           ? _STDENC_SDGEN_INCOMPLETE_SHIFT
+                           : _STDENC_SDGEN_INCOMPLETE_CHAR;
+                       break;
+               default:
+                       return EINVAL;
+               }
+               break;
+       default:
+               return EINVAL;
+       }
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_ZW_stdenc_wctocs(_ZWEncodingInfo * __restrict ei,
+       _csid_t * __restrict csid, _index_t * __restrict idx, wchar_t wc)
+{
+       /* ei seems to be unused */
+       _DIAGASSERT(csid != NULL);
+       _DIAGASSERT(idx != NULL);
+
+       *csid = (_csid_t)(wc <= 0x7FU) ? 0 : 1;
+       *idx = (_index_t)wc;
+
+       return 0;
+}
+
+static __inline int
+/*ARGSUSED*/
+_citrus_ZW_stdenc_cstowc(_ZWEncodingInfo * __restrict ei,
+        wchar_t * __restrict wc, _csid_t csid, _index_t idx)
+{
+       /* ei seems to be unused */
+       _DIAGASSERT(wc != NULL);
+
+       switch (csid) {
+       case 0: case 1:
+               break;
+       default:
+               return EINVAL;
+       }
+       *wc = (wchar_t)idx;
+
+       return 0;
+}
+
+static void
+/*ARGSUSED*/
+_citrus_ZW_encoding_module_uninit(_ZWEncodingInfo *ei)
+{
+}
+
+static int
+/*ARGSUSED*/
+_citrus_ZW_encoding_module_init(_ZWEncodingInfo * __restrict ei,
+       const void *__restrict var, size_t lenvar)
+{
+       return 0;
+}
+
+/* ----------------------------------------------------------------------
+ * public interface for ctype
+ */
+
+_CITRUS_CTYPE_DECLS(ZW);
+_CITRUS_CTYPE_DEF_OPS(ZW);
+
+#include "citrus_ctype_template.h"
+
+/* ----------------------------------------------------------------------
+ * public interface for stdenc
+ */
+
+_CITRUS_STDENC_DECLS(ZW);
+_CITRUS_STDENC_DEF_OPS(ZW);
+
+#include "citrus_stdenc_template.h"
diff --git a/lib/nbsd_libc/citrus/modules/citrus_zw.h b/lib/nbsd_libc/citrus/modules/citrus_zw.h
new file mode 100644 (file)
index 0000000..9f7a20d
--- /dev/null
@@ -0,0 +1,37 @@
+/* $NetBSD: citrus_zw.h,v 1.1 2006/11/22 23:38:27 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2004,2006 Citrus Project,
+ * 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.
+ */
+
+#ifndef _CITRUS_ZW_H_
+#define _CITRUS_ZW_H_
+
+__BEGIN_DECLS
+_CITRUS_CTYPE_GETOPS_FUNC(ZW);
+_CITRUS_STDENC_GETOPS_FUNC(ZW);
+__END_DECLS
+
+#endif
diff --git a/lib/nbsd_libc/compat-43/Makefile.inc b/lib/nbsd_libc/compat-43/Makefile.inc
new file mode 100644 (file)
index 0000000..98e5390
--- /dev/null
@@ -0,0 +1,21 @@
+#      $NetBSD: Makefile.inc,v 1.16 2006/04/24 17:15:06 drochner Exp $
+#      from: @(#)Makefile.inc  8.1 (Berkeley) 6/2/93
+
+# compat-43 sources
+.PATH: ${ARCHDIR}/compat-43 ${.CURDIR}/compat-43
+
+SRCS+= creat.c getdtablesize.c gethostid.c \
+       killpg.c sethostid.c setpgrp.c \
+       setrgid.c setruid.c sigcompat.c
+.if !defined(AUDIT)
+SRCS+= getwd.c
+.endif
+
+# XXX this is to get <compat/sys/signal.h>
+CPPFLAGS.sigcompat.c+= -I${NETBSDSRCDIR}/sys
+
+MAN+=  creat.3 getdtablesize.3 gethostid.3 killpg.3 \
+       setruid.3 sigblock.3 sigpause.3 sigsetmask.3 sigvec.3
+
+MLINKS+=setruid.3 setrgid.3
+MLINKS+=gethostid.3 sethostid.3
diff --git a/lib/nbsd_libc/compat-43/creat.3 b/lib/nbsd_libc/compat-43/creat.3
new file mode 100644 (file)
index 0000000..a5905b4
--- /dev/null
@@ -0,0 +1,65 @@
+.\" Copyright (c) 1989, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)creat.2      8.1 (Berkeley) 6/2/93
+.\"    $NetBSD: creat.3,v 1.16 2003/08/07 16:42:39 agc Exp $
+.\"
+.Dd June 2, 1993
+.Dt CREAT 3
+.Os
+.Sh NAME
+.Nm creat
+.Nd create a new file
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In fcntl.h
+.Ft int
+.Fn creat "const char *path" "mode_t mode"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is made obsolete by:
+.Ef
+.Xr open 2 .
+.Pp
+.Fn creat
+is the same as:
+.Bd -literal -offset indent
+open(path, O_CREAT | O_TRUNC | O_WRONLY, mode);
+.Ed
+.Sh SEE ALSO
+.Xr open 2
+.Sh STANDARDS
+The
+.Fn creat
+function call conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+The
+.Fn creat
+function call appeared in
+.At v6 .
diff --git a/lib/nbsd_libc/compat-43/creat.c b/lib/nbsd_libc/compat-43/creat.c
new file mode 100644 (file)
index 0000000..9560bea
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: creat.c,v 1.10 2003/08/07 16:42:39 agc Exp $   */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)creat.c    8.1 (Berkeley) 6/2/93";
+#else
+__RCSID("$NetBSD: creat.c,v 1.10 2003/08/07 16:42:39 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+
+int
+creat(const char *path, mode_t mode)
+{
+
+       _DIAGASSERT(path != NULL);
+
+       return(open(path, O_WRONLY|O_CREAT|O_TRUNC, mode));
+}
diff --git a/lib/nbsd_libc/compat-43/getdtablesize.3 b/lib/nbsd_libc/compat-43/getdtablesize.3
new file mode 100644 (file)
index 0000000..5f19f7f
--- /dev/null
@@ -0,0 +1,62 @@
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)getdtablesize.2      8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: getdtablesize.3,v 1.13 2003/08/07 16:42:39 agc Exp $
+.\"
+.Dd June 4, 1993
+.Dt GETDTABLESIZE 3
+.Os
+.Sh NAME
+.Nm getdtablesize
+.Nd get descriptor table size
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn getdtablesize void
+.Sh DESCRIPTION
+Each process has a fixed size descriptor table,
+which is guaranteed to have at least 20 slots.
+The entries in
+the descriptor table are numbered with small integers starting at 0.
+The call
+.Fn getdtablesize
+returns the size of this table.
+.Sh SEE ALSO
+.Xr close 2 ,
+.Xr dup 2 ,
+.Xr getrlimit 2 ,
+.Xr open 2 ,
+.Xr select 2 ,
+.Xr sysconf 3
+.Sh HISTORY
+The
+.Fn getdtablesize
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/compat-43/getdtablesize.c b/lib/nbsd_libc/compat-43/getdtablesize.c
new file mode 100644 (file)
index 0000000..eff7c18
--- /dev/null
@@ -0,0 +1,20 @@
+/*     $NetBSD: getdtablesize.c,v 1.9 2003/07/26 19:24:41 salo Exp $   */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getdtablesize.c,v 1.9 2003/07/26 19:24:41 salo Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <unistd.h>
+
+int
+getdtablesize()
+{
+       return ((int)sysconf(_SC_OPEN_MAX));
+}
diff --git a/lib/nbsd_libc/compat-43/gethostid.3 b/lib/nbsd_libc/compat-43/gethostid.3
new file mode 100644 (file)
index 0000000..a9f4ab2
--- /dev/null
@@ -0,0 +1,77 @@
+.\"    $NetBSD: gethostid.3,v 1.12 2003/08/07 16:42:39 agc Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)gethostid.3        8.1 (Berkeley) 6/2/93
+.\"
+.Dd June 2, 1993
+.Dt GETHOSTID 3
+.Os
+.Sh NAME
+.Nm gethostid ,
+.Nm sethostid
+.Nd get/set unique identifier of current host
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft long
+.Fn gethostid void
+.Ft int
+.Fn sethostid "long hostid"
+.Sh DESCRIPTION
+.Fn sethostid
+establishes a 32-bit identifier for the current processor that is
+intended to be unique among all
+.Ux
+systems in existence.
+This is normally a DARPA Internet address for the local machine.
+This call is allowed only to the super-user and is normally performed
+at boot time.
+.Pp
+.Fn gethostid
+returns the 32-bit identifier for the current processor.
+.Pp
+This function has been deprecated.
+The hostid should be set or retrieved by use of
+.Xr sysctl 3 .
+.Sh SEE ALSO
+.Xr gethostname 3 ,
+.Xr sysctl 3 ,
+.Xr sysctl 8
+.Sh HISTORY
+The
+.Fn gethostid
+and
+.Fn sethostid
+syscalls appeared in
+.Bx 4.2
+and were dropped in
+.Bx 4.4 .
+.Sh BUGS
+32 bits for the identifier is too small.
diff --git a/lib/nbsd_libc/compat-43/gethostid.c b/lib/nbsd_libc/compat-43/gethostid.c
new file mode 100644 (file)
index 0000000..b95f598
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: gethostid.c,v 1.6 2004/04/19 13:16:42 atatat Exp $     */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)gethostid.c        8.1 (Berkeley) 6/2/93";
+#else
+__RCSID("$NetBSD: gethostid.c,v 1.6 2004/04/19 13:16:42 atatat Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <unistd.h>
+#include <sys/param.h>
+#include <sys/sysctl.h>
+
+long
+gethostid(void)
+{
+       int mib[2], value;
+       size_t size;
+
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_HOSTID;
+       size = sizeof(value);
+       if (sysctl(mib, 2, &value, &size, NULL, (size_t)0) == -1)
+               return (-1);
+       return (value);
+}
diff --git a/lib/nbsd_libc/compat-43/getwd.c b/lib/nbsd_libc/compat-43/getwd.c
new file mode 100644 (file)
index 0000000..98b72c1
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: getwd.c,v 1.14 2003/08/07 16:42:39 agc Exp $   */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getwd.c    8.1 (Berkeley) 6/2/93";
+#else
+__RCSID("$NetBSD: getwd.c,v 1.14 2003/08/07 16:42:39 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+__warn_references(getwd,
+    "warning: getwd() possibly used unsafely, consider using getcwd()")
+
+char *
+getwd(buf)
+       char *buf;
+{
+       char *p;
+
+       _DIAGASSERT(buf != NULL);
+
+       if ((p = getcwd(buf, MAXPATHLEN)) != NULL)
+               return(p);
+       (void)strlcpy(buf, strerror(errno), MAXPATHLEN);
+       return((char *)NULL);
+}
diff --git a/lib/nbsd_libc/compat-43/killpg.3 b/lib/nbsd_libc/compat-43/killpg.3
new file mode 100644 (file)
index 0000000..d3afef0
--- /dev/null
@@ -0,0 +1,94 @@
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)killpg.2     8.1 (Berkeley) 6/2/93
+.\"    $NetBSD: killpg.3,v 1.16 2003/08/07 16:42:39 agc Exp $
+.\"
+.Dd June 2, 1993
+.Dt KILLPG 3
+.Os
+.Sh NAME
+.Nm killpg
+.Nd send signal to a process group
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn killpg "pid_t pgrp" "int sig"
+.Sh DESCRIPTION
+.Fn killpg
+sends the signal
+.Fa sig
+to the process group
+.Fa pgrp .
+See
+.Xr sigaction 2
+for a list of signals.
+If
+.Fa pgrp
+is 0,
+.Fn killpg
+sends the signal to the sending process's process group.
+.Pp
+The sending process and members of the process group must
+have the same effective user ID, or
+the sender must be the super-user.
+As a single special case the continue signal SIGCONT may be sent
+to any process that is a descendant of the current process.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn killpg
+will fail and no signal will be sent if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+.Fa sig
+is not a valid signal number.
+.It Bq Er ESRCH
+No process can be found in the process group specified by
+.Fa pgrp .
+.It Bq Er ESRCH
+The process group was given as 0
+but the sending process does not have a process group.
+.It Bq Er EPERM
+The sending process is not the super-user and one or more
+of the target processes has an effective user ID different from that
+of the sending process.
+.El
+.Sh SEE ALSO
+.Xr getpgrp 2 ,
+.Xr kill 2 ,
+.Xr sigaction 2
+.Sh HISTORY
+The
+.Fn killpg
+function call appeared in
+.Bx 4.0 .
diff --git a/lib/nbsd_libc/compat-43/killpg.c b/lib/nbsd_libc/compat-43/killpg.c
new file mode 100644 (file)
index 0000000..ceac3f4
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: killpg.c,v 1.8 2003/08/07 16:42:39 agc Exp $   */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)killpg.c   8.1 (Berkeley) 6/2/93";
+#else
+__RCSID("$NetBSD: killpg.c,v 1.8 2003/08/07 16:42:39 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <signal.h>
+#include <errno.h>
+
+/*
+ * Backwards-compatible killpg().
+ */
+int
+killpg(pid_t pgid, int sig)
+{
+       if (pgid == 1) {
+               errno = ESRCH;
+               return (-1);
+       }
+       return (kill(-pgid, sig));
+}
diff --git a/lib/nbsd_libc/compat-43/sethostid.c b/lib/nbsd_libc/compat-43/sethostid.c
new file mode 100644 (file)
index 0000000..b38bf8a
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: sethostid.c,v 1.7 2004/04/19 13:16:42 atatat Exp $     */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)sethostid.c        8.1 (Berkeley) 6/2/93";
+#else
+__RCSID("$NetBSD: sethostid.c,v 1.7 2004/04/19 13:16:42 atatat Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/sysctl.h>
+#include <unistd.h>
+
+int
+sethostid(long hostid)
+{
+       int mib[2], value;
+
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_HOSTID;
+       value = (int)hostid;
+       if (sysctl(mib, 2, NULL, NULL, &value, sizeof(value)) == -1)
+               return (-1);
+       return (0);
+}
diff --git a/lib/nbsd_libc/compat-43/setpgrp.c b/lib/nbsd_libc/compat-43/setpgrp.c
new file mode 100644 (file)
index 0000000..3c031cc
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: setpgrp.c,v 1.8 2003/08/07 16:42:40 agc Exp $  */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)setpgrp.c  8.1 (Berkeley) 6/2/93";
+#else
+__RCSID("$NetBSD: setpgrp.c,v 1.8 2003/08/07 16:42:40 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <unistd.h>
+
+int
+setpgrp(pid_t pid, pid_t pgid)
+{
+       return(setpgid(pid, pgid));
+}
diff --git a/lib/nbsd_libc/compat-43/setrgid.c b/lib/nbsd_libc/compat-43/setrgid.c
new file mode 100644 (file)
index 0000000..a0f9334
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: setrgid.c,v 1.12 2003/08/07 16:42:40 agc Exp $ */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)setrgid.c  8.1 (Berkeley) 6/2/93";
+#else
+__RCSID("$NetBSD: setrgid.c,v 1.12 2003/08/07 16:42:40 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <unistd.h>
+
+__warn_references(setrgid, "warning: this program uses setrgid(), which is deprecated.")
+
+int
+setrgid(gid_t rgid)
+{
+       return (setregid(rgid, (gid_t)-1));
+}
diff --git a/lib/nbsd_libc/compat-43/setruid.3 b/lib/nbsd_libc/compat-43/setruid.3
new file mode 100644 (file)
index 0000000..8a557b1
--- /dev/null
@@ -0,0 +1,78 @@
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)setruid.3    8.1 (Berkeley) 6/2/93
+.\"    $NetBSD: setruid.3,v 1.10 2003/08/07 16:42:40 agc Exp $
+.\"
+.Dd June 2, 1993
+.Dt SETRUID 3
+.Os
+.Sh NAME
+.Nm setruid ,
+.Nm setrgid
+.Nd set user and group ID
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.Ft int
+.Fn setruid "uid_t ruid"
+.Ft int
+.Fn setrgid "gid_t rgid"
+.Sh DESCRIPTION
+The
+.Fn setruid
+function
+.Pq Fn setrgid
+sets the real user ID (group ID) of the
+current process.
+.Sh RETURN VALUES
+Upon success, these functions return 0;
+otherwise \-1 is returned.
+.Pp
+If the user is not the super user, or the uid
+specified is not the real or effective ID, these
+functions return \-1.
+.Pp
+The use of these calls is not portable.
+Their use is discouraged; they will be removed in the future.
+.Sh SEE ALSO
+.Xr getgid 2 ,
+.Xr getuid 2 ,
+.Xr setegid 2 ,
+.Xr seteuid 2 ,
+.Xr setgid 2 ,
+.Xr setuid 2
+.Sh HISTORY
+The
+.Fn setruid
+and
+.Fn setrgid
+syscalls appeared in
+.Bx 4.2
+and were dropped in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/compat-43/setruid.c b/lib/nbsd_libc/compat-43/setruid.c
new file mode 100644 (file)
index 0000000..64b8433
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: setruid.c,v 1.13 2003/08/07 16:42:40 agc Exp $ */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)setruid.c  8.1 (Berkeley) 6/2/93";
+#else
+__RCSID("$NetBSD: setruid.c,v 1.13 2003/08/07 16:42:40 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <unistd.h>
+
+__warn_references(setruid, "warning: this program uses setruid(), which is deprecated.")
+
+int
+setruid(uid_t ruid)
+{
+       return (setreuid(ruid, (uid_t)-1));
+}
diff --git a/lib/nbsd_libc/compat-43/sigblock.3 b/lib/nbsd_libc/compat-43/sigblock.3
new file mode 100644 (file)
index 0000000..86c8dff
--- /dev/null
@@ -0,0 +1,119 @@
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)sigblock.2   8.1 (Berkeley) 6/2/93
+.\"    $NetBSD: sigblock.3,v 1.17 2003/08/07 16:42:40 agc Exp $
+.\"
+.Dd August 10, 2002
+.Dt SIGBLOCK 3
+.Os
+.Sh NAME
+.Nm sigblock
+.Nd block signals
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigblock "int mask"
+.Ft int
+.Fn sigmask signum
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is made obsolete by:
+.Xr sigprocmask 2 .
+.Ef
+.Pp
+.Fn sigblock
+adds the signals specified in
+.Fa mask
+to the set of signals currently
+being blocked from delivery.
+Signals are blocked if the
+corresponding bit in
+.Fa mask
+is a 1; the macro
+.Fn sigmask
+is provided to construct the mask for a given
+.Fa signum .
+.Pp
+It is not possible to block
+.Dv SIGKILL
+or
+.Dv SIGSTOP ;
+this restriction is silently
+imposed by the system.
+.Sh RETURN VALUES
+The previous set of masked signals is returned.
+.Sh EXAMPLES
+The following example using
+.Fn sigblock :
+.Bd -literal -offset indent
+int omask;
+
+omask = sigblock(sigmask(SIGINT) | sigmask(SIGHUP));
+.Ed
+.Pp
+Becomes:
+.Bd -literal -offset indent
+sigset_t set, oset;
+
+sigemptyset(&set);
+sigaddset(&set, SIGINT);
+sigaddset(&set, SIGHUP);
+sigprocmask(SIG_BLOCK, &set, &oset);
+.Ed
+.Pp
+Another use of
+.Fn sigblock
+is to get the current set of masked signals without changing what
+is actually blocked.
+Instead of:
+.Bd -literal -offset indent
+int set;
+
+set = sigblock(0);
+.Ed
+.Pp
+Use the following:
+.Bd -literal -offset indent
+sigset_t set;
+
+sigprocmask(SIG_BLOCK, NULL, &set);
+.Ed
+.Sh SEE ALSO
+.Xr kill 2 ,
+.Xr sigaction 2 ,
+.Xr sigprocmask 2 ,
+.Xr sigsetmask 3 ,
+.Xr sigsetops 3
+.Sh HISTORY
+The
+.Fn sigblock
+function call appeared in
+.Bx 4.2
+and has been deprecated.
diff --git a/lib/nbsd_libc/compat-43/sigcompat.c b/lib/nbsd_libc/compat-43/sigcompat.c
new file mode 100644 (file)
index 0000000..a8ae696
--- /dev/null
@@ -0,0 +1,120 @@
+/*     $NetBSD: sigcompat.c,v 1.13 2005/12/24 21:11:16 perry Exp $     */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)sigcompat.c        8.1 (Berkeley) 6/2/93";
+#else
+__RCSID("$NetBSD: sigcompat.c,v 1.13 2005/12/24 21:11:16 perry Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/param.h>
+#include <signal.h>
+#include <compat/sys/signal.h>
+
+static inline void sv2sa(struct sigaction *, const struct sigvec *);
+static inline void sa2sv(struct sigvec *, const struct sigaction *);
+
+static inline void
+sv2sa(struct sigaction *sa, const struct sigvec *sv)
+{
+       sigemptyset(&sa->sa_mask);
+       sa->sa_mask.__bits[0] = sv->sv_mask;
+       sa->sa_handler = sv->sv_handler;
+       sa->sa_flags = sv->sv_flags ^ SV_INTERRUPT; /* !SA_INTERRUPT */
+}
+
+static inline void
+sa2sv(struct sigvec *sv, const struct sigaction *sa)
+{
+       sv->sv_mask = sa->sa_mask.__bits[0];
+       sv->sv_handler = sa->sa_handler;
+       sv->sv_flags = sa->sa_flags ^ SV_INTERRUPT; /* !SA_INTERRUPT */
+}
+       
+int
+sigvec(int signo, struct sigvec *nsv, struct sigvec *osv)
+{
+       int ret;
+       struct sigaction osa, nsa;
+
+       if (nsv)
+               sv2sa(&nsa, nsv);
+
+       ret = sigaction(signo, nsv ? &nsa : NULL, osv ? &osa : NULL);
+
+       if (ret == 0 && osv)
+               sa2sv(osv, &osa);
+
+       return (ret);
+}
+
+int
+sigsetmask(int mask)
+{
+       sigset_t nmask, omask;
+       int n;
+
+       sigemptyset(&nmask);
+       nmask.__bits[0] = mask;
+
+       n = sigprocmask(SIG_SETMASK, &nmask, &omask);
+       if (n)
+               return (n);
+       return (omask.__bits[0]);
+}
+
+int
+sigblock(int mask)
+{
+       sigset_t nmask, omask;
+       int n;
+
+       sigemptyset(&nmask);
+       nmask.__bits[0] = mask;
+
+       n = sigprocmask(SIG_BLOCK, &nmask, &omask);
+       if (n)
+               return (n);
+       return (omask.__bits[0]);
+}
+
+int
+sigpause(int mask)
+{
+       sigset_t nmask;
+
+       sigemptyset(&nmask);
+       nmask.__bits[0] = mask;
+       return (sigsuspend(&nmask));
+}
diff --git a/lib/nbsd_libc/compat-43/sigpause.3 b/lib/nbsd_libc/compat-43/sigpause.3
new file mode 100644 (file)
index 0000000..431ad50
--- /dev/null
@@ -0,0 +1,75 @@
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)sigpause.2   8.1 (Berkeley) 6/2/93
+.\"    $NetBSD: sigpause.3,v 1.15 2003/08/07 16:42:40 agc Exp $
+.\"
+.Dd June 2, 1993
+.Dt SIGPAUSE 3
+.Os
+.Sh NAME
+.Nm sigpause
+.Nd atomically release blocked signals and wait for interrupt
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigpause "int sigmask"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is made obsolete by
+.Xr sigsuspend 2 .
+.Ef
+.Pp
+.Fn sigpause
+assigns
+.Fa sigmask
+to the set of masked signals
+and then waits for a signal to arrive;
+on return the set of masked signals is restored.
+.Fa sigmask
+is usually 0 to indicate that no
+signals are to be blocked.
+.Fn sigpause
+always terminates by being interrupted, returning -1 with
+.Va errno
+set to
+.Dv EINTR .
+.Sh SEE ALSO
+.Xr kill 2 ,
+.Xr sigaction 2 ,
+.Xr sigprocmask 2 ,
+.Xr sigsuspend 2 ,
+.Xr sigblock 3 ,
+.Xr sigvec 3
+.Sh HISTORY
+The
+.Fn sigpause
+function call appeared in
+.Bx 4.2
+and has been deprecated.
diff --git a/lib/nbsd_libc/compat-43/sigsetmask.3 b/lib/nbsd_libc/compat-43/sigsetmask.3
new file mode 100644 (file)
index 0000000..3b36b0c
--- /dev/null
@@ -0,0 +1,140 @@
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)sigsetmask.2 8.1 (Berkeley) 6/2/93
+.\"    $NetBSD: sigsetmask.3,v 1.18 2003/08/07 16:42:40 agc Exp $
+.\"
+.Dd August 10, 2002
+.Dt SIGSETMASK 3
+.Os
+.Sh NAME
+.Nm sigsetmask
+.Nd set current signal mask
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigsetmask "int mask"
+.Fn sigmask signum
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is made obsolete by:
+.Ef
+.Xr sigprocmask 2 .
+.Pp
+.Fn sigsetmask
+sets the current signal mask
+Signals are blocked from delivery if the
+corresponding bit in
+.Fa mask
+is a 1; the macro
+.Fn sigmask
+is provided to construct the mask for a given
+.Fa signum .
+.Pp
+The system
+quietly disallows
+.Dv SIGKILL
+or
+.Dv SIGSTOP
+to be blocked.
+.Sh RETURN VALUES
+The previous set of masked signals is returned.
+.Sh EXAMPLES
+The following example using
+.Fn sigsetmask :
+.Bd -literal -offset indent
+int omask;
+
+omask = sigblock(sigmask(SIGINT) | sigmask(SIGHUP));
+
+\&...
+
+sigsetmask(omask & ~(sigmask(SIGINT) | sigmask(SIGHUP)));
+.Ed
+.Pp
+Could be converted literally to:
+.Bd -literal -offset indent
+sigset_t set, oset;
+
+sigemptyset(&set);
+sigaddset(&set, SIGINT);
+sigaddset(&set, SIGHUP);
+sigprocmask(SIG_BLOCK, &set, &oset);
+
+\&...
+
+sigdelset(&oset, SIGINT);
+sigdelset(&oset, SIGHUP);
+sigprocmask(SIG_SETMASK, &oset, NULL);
+.Ed
+.Pp
+Another, clearer, alternative is:
+.Bd -literal -offset indent
+sigset_t set;
+
+sigemptyset(&set);
+sigaddset(&set, SIGINT);
+sigaddset(&set, SIGHUP);
+sigprocmask(SIG_BLOCK, &set, NULL);
+
+\&...
+
+sigprocmask(SIG_UNBLOCK, &set, NULL);
+.Ed
+.Pp
+To completely clear the signal mask using
+.Fn sigsetmask
+one can do:
+.Bd -literal -offset indent
+(void) sigsetmask(0);
+.Ed
+.Pp
+Which can be expressed via
+.Xr sigprocmask 2
+as:
+.Bd -literal -offset indent
+sigset_t eset;
+
+sigemptyset(&eset);
+(void) sigprocmask(SIG_SETMASK, &eset, NULL);
+.Ed
+.Sh SEE ALSO
+.Xr kill 2 ,
+.Xr sigaction 2 ,
+.Xr sigprocmask 2 ,
+.Xr sigsuspend 2 ,
+.Xr sigblock 3 ,
+.Xr sigsetops 3 ,
+.Xr sigvec 3
+.Sh HISTORY
+The
+.Fn sigsetmask
+function call appeared in
+.Bx 4.2
+and has been deprecated.
diff --git a/lib/nbsd_libc/compat-43/sigvec.3 b/lib/nbsd_libc/compat-43/sigvec.3
new file mode 100644 (file)
index 0000000..18c2a4c
--- /dev/null
@@ -0,0 +1,313 @@
+.\"    $NetBSD: sigvec.3,v 1.26 2010/03/22 19:30:53 joerg Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)sigvec.2     8.2 (Berkeley) 4/19/94
+.\"
+.Dd December 3, 2005
+.Dt SIGVEC 3
+.Os
+.Sh NAME
+.Nm sigvec
+.Nd software signal facilities
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Bd -literal
+struct sigvec {
+       void    (*sv_handler)();
+       int     sv_mask;
+       int     sv_flags;
+};
+.Ed
+.Ft int
+.Fn sigvec "int sig" "struct sigvec *vec" "struct sigvec *ovec"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is made obsolete by
+.Xr sigaction 2 .
+The structure, flags, and function declaration have been removed from
+the header files but the function is kept in the c library for binary
+compatibility.
+.Ef
+.Pp
+The system defines a set of signals that may be delivered to a process.
+Signal delivery resembles the occurrence of a hardware interrupt:
+the signal is blocked from further occurrence, the current process
+context is saved, and a new one is built.
+A process may specify a
+.Em handler
+to which a signal is delivered, or specify that a signal is to be
+.Em ignored .
+A process may also specify that a default action is to be taken
+by the system when a signal occurs.
+A signal may also be
+.Em blocked ,
+in which case its delivery is postponed until it is
+.Em unblocked .
+The action to be taken on delivery is determined at the time
+of delivery.
+Normally, signal handlers execute on the current stack
+of the process.
+This may be changed, on a per-handler basis, so that signals are
+taken on a special
+.Em "signal stack" .
+.Pp
+Signal routines execute with the signal that caused their
+invocation
+.Em blocked ,
+but other signals may yet occur.
+A global
+.Em "signal mask"
+defines the set of signals currently blocked from delivery
+to a process.
+The signal mask for a process is initialized from that of its parent
+(normally 0).
+It may be changed with a
+.Xr sigblock 3
+or
+.Xr sigsetmask 3
+call, or when a signal is delivered to the process.
+.Pp
+When a signal
+condition arises for a process, the signal is added to a set of
+signals pending for the process.
+If the signal is not currently
+.Em blocked
+by the process then it is delivered to the process.
+When a caught signal
+is delivered, the current state of the process is saved,
+a new signal mask is calculated (as described below),
+and the signal handler is invoked.
+The call to the handler is arranged so that if the signal handling
+routine returns normally the process will resume execution in the
+context from before the signal's delivery.
+If the process wishes to resume in a different context, then it
+must arrange to restore the previous context itself.
+.Pp
+When a signal is delivered to a process a new signal mask is
+installed for the duration of the process' signal handler
+(or until a
+.Xr sigblock 3
+or
+.Xr sigsetmask 3
+call is made).
+This mask is formed by taking the union of the current signal mask,
+the signal to be delivered, and
+the signal mask associated with the handler to be invoked.
+.Pp
+.Fn sigvec
+assigns a handler for a specific signal.
+If
+.Fa vec
+is non-zero, it
+specifies an action
+.Pf ( Dv SIG_DFL ,
+.Dv SIG_IGN ,
+or a handler routine) and mask
+to be used when delivering the specified signal.
+Further, if the
+.Dv SV_ONSTACK
+bit is set in
+.Fa sv_flags ,
+the system will deliver the signal to the process on a
+.Em "signal stack" ,
+specified with
+.Xr sigaltstack 2 .
+If
+.Fa ovec
+is non-zero, the previous handling information for the signal
+is returned to the user.
+.Pp
+Once a signal handler is installed, it remains installed
+until another
+.Fn sigvec
+call is made, or an
+.Xr execve 2
+is performed.
+A signal-specific default action may be reset by
+setting
+.Fa sv_handler
+to
+.Dv SIG_DFL .
+The defaults are process termination, possibly with core dump;
+no action; stopping the process; or continuing the process.
+See the signal list below for each signal's default action.
+If
+.Fa sv_handler
+is set to
+.Dv SIG_DFL ,
+the default action for the signal is to discard the signal,
+and if a signal is pending,
+the pending signal is discarded even if the signal is masked.
+If
+.Fa sv_handler
+is set to
+.Dv SIG_IGN ,
+current and pending instances
+of the signal are ignored and discarded.
+.Pp
+Options may be specified by setting
+.Em sv_flags .
+If the
+.Dv SV_ONSTACK
+bit is set in
+.Fa sv_flags ,
+the system will deliver the signal to the process on a
+.Em "signal stack" ,
+specified with
+.Xr sigstack 2 .
+.Pp
+If a signal is caught during the system calls listed below,
+the call may be restarted,
+the call may return with a data transfer shorter than requested,
+or the call may be forced to terminate
+with the error
+.Dv EINTR .
+Interrupting of pending calls is requested
+by setting the
+.Dv SV_INTERRUPT
+bit in
+.Ar sv_flags .
+The affected system calls include
+.Xr open 2 ,
+.Xr read 2 ,
+.Xr write 2 ,
+.Xr sendto 2 ,
+.Xr recvfrom 2 ,
+.Xr sendmsg 2
+and
+.Xr recvmsg 2
+on a communications channel or a slow device (such as a terminal,
+but not a regular file)
+and during a
+.Xr wait 2
+or
+.Xr ioctl 2 .
+However, calls that have already committed are not restarted,
+but instead return a partial success (for example, a short read count).
+.Pp
+After a
+.Xr fork 2
+or
+.Xr vfork 2
+all signals, the signal mask, the signal stack,
+and the interrupt/restart flags are inherited by the child.
+.Pp
+The
+.Xr execve 2
+system call reinstates the default action for all signals which
+were caught and resets all signals to be caught on the user stack.
+Ignored signals remain ignored;
+the signal mask remains the same;
+signals that interrupt pending system calls continue to do so.
+.Pp
+See
+.Xr signal 7
+for comprehensive list of supported signals.
+.Sh NOTES
+The mask specified in
+.Fa vec
+is not allowed to block
+.Dv SIGKILL
+or
+.Dv SIGSTOP .
+This is enforced silently by the system.
+.Pp
+The
+.Dv SV_INTERRUPT
+flag is not available in
+.Bx 4.2 ,
+hence it should not be used if backward compatibility is needed.
+.Sh RETURN VALUES
+A 0 value indicated that the call succeeded.
+A \-1 return value indicates an error occurred and
+.Va errno
+is set to indicated the reason.
+.Sh EXAMPLES
+The handler routine can be declared:
+.Bd -literal -offset indent
+void
+handler(sig, code, scp)
+       int sig, code;
+       struct sigcontext *scp;
+.Ed
+.Pp
+Here
+.Fa sig
+is the signal number, into which the hardware faults and traps are
+mapped as defined below.
+.Fa code
+is a parameter that is either a constant
+or the code provided by the hardware.
+.Fa scp
+is a pointer to the
+.Fa sigcontext
+structure (defined in
+.In signal.h ) ,
+used to restore the context from before the signal.
+.Sh ERRORS
+.Fn sigvec
+will fail and no new signal handler will be installed if one
+of the following occurs:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+Either
+.Fa vec
+or
+.Fa ovec
+points to memory that is not a valid part of the process
+address space.
+.It Bq Er EINVAL
+.Fa sig
+is not a valid signal number.
+.It Bq Er EINVAL
+An attempt is made to ignore or supply a handler for
+.Dv SIGKILL
+or
+.Dv SIGSTOP .
+.El
+.Sh SEE ALSO
+.Xr kill 1 ,
+.Xr kill 2 ,
+.Xr ptrace 2 ,
+.Xr sigaction 2 ,
+.Xr sigaltstack 2 ,
+.Xr sigprocmask 2 ,
+.Xr sigstack 2 ,
+.Xr sigsuspend 2 ,
+.Xr setjmp 3 ,
+.Xr sigblock 3 ,
+.Xr siginterrupt 3 ,
+.Xr signal 3 ,
+.Xr sigpause 3 ,
+.Xr sigsetmask 3 ,
+.Xr sigsetops 3 ,
+.Xr tty 4 ,
+.Xr signal 7
diff --git a/lib/nbsd_libc/compat/Makefile b/lib/nbsd_libc/compat/Makefile
new file mode 100644 (file)
index 0000000..d9eec76
--- /dev/null
@@ -0,0 +1,26 @@
+#      $NetBSD: Makefile,v 1.5 2010/06/07 13:52:29 tnozaki Exp $
+#      @(#)Makefile    8.2 (Berkeley) 2/3/94
+#
+
+.include "${.CURDIR}/../Makefile.inc"
+
+LIB=           cold
+CPPFLAGS+=     -I${.CURDIR}/../include -I${.CURDIR}/..
+CPPFLAGS+=     -I${.CURDIR}/../arch/${ARCHSUBDIR}
+
+COMPATDIR=${.CURDIR}
+
+.include "${.CURDIR}/Makefile.inc"
+
+.include "${.CURDIR}/db/Makefile.inc"
+.include "${.CURDIR}/gen/Makefile.inc"
+.include "${.CURDIR}/locale/Makefile.inc"
+.include "${.CURDIR}/net/Makefile.inc"
+.include "${.CURDIR}/rpc/Makefile.inc"
+.include "${.CURDIR}/stdlib/Makefile.inc"
+.include "${.CURDIR}/sys/Makefile.inc"
+
+COMPATARCHDIR=${.CURDIR}/arch/${ARCHSUBDIR}
+.PATH: ${COMPATARCHDIR}/gen ${COMPATARCHDIR}/sys
+
+.include <bsd.lib.mk>
diff --git a/lib/nbsd_libc/compat/Makefile.inc b/lib/nbsd_libc/compat/Makefile.inc
new file mode 100644 (file)
index 0000000..e6a6478
--- /dev/null
@@ -0,0 +1,16 @@
+#      $NetBSD: Makefile.inc,v 1.6 2010/06/07 13:52:29 tnozaki Exp $
+
+CPPFLAGS+=     -I${NETBSDSRCDIR}/sys
+
+COMPATARCHDIR=${COMPATDIR}/arch/${ARCHSUBDIR}
+.PATH: ${COMPATARCHDIR}/gen ${COMPATARCHDIR}/sys
+
+.include "${COMPATDIR}/db/Makefile.inc"
+.include "${COMPATDIR}/locale/Makefile.inc"
+.include "${COMPATDIR}/gen/Makefile.inc"
+.include "${COMPATDIR}/net/Makefile.inc"
+.include "${COMPATDIR}/rpc/Makefile.inc"
+.include "${COMPATDIR}/stdlib/Makefile.inc"
+.include "${COMPATDIR}/sys/Makefile.inc"
+.include "${COMPATDIR}/time/Makefile.inc"
+.include "${COMPATARCHDIR}/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/alpha/Makefile.inc b/lib/nbsd_libc/compat/arch/alpha/Makefile.inc
new file mode 100644 (file)
index 0000000..aa2ae66
--- /dev/null
@@ -0,0 +1,4 @@
+# $NetBSD: Makefile.inc,v 1.2 2006/03/11 23:04:03 christos Exp $
+
+.include "${COMPATARCHDIR}/gen/Makefile.inc"
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/alpha/gen/Makefile.inc b/lib/nbsd_libc/compat/arch/alpha/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..4fc8c9a
--- /dev/null
@@ -0,0 +1,7 @@
+# $NetBSD: Makefile.inc,v 1.2 2006/06/28 14:22:15 drochner Exp $
+
+# objects built from assembler sources
+SRCS+=  compat_setjmp.S compat__setjmp.S compat_sigsetjmp.S
+
+# objects built from C sources in compat/gen
+SRCS+=  compat_frexp_ieee754.c compat_ldexp_ieee754.c compat_modf_ieee754.c
diff --git a/lib/nbsd_libc/compat/arch/alpha/gen/compat__setjmp.S b/lib/nbsd_libc/compat/arch/alpha/gen/compat__setjmp.S
new file mode 100644 (file)
index 0000000..40b4b2b
--- /dev/null
@@ -0,0 +1,123 @@
+/* $NetBSD: compat__setjmp.S,v 1.1 2005/09/16 18:21:19 drochner Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     _longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     _setjmp(a)
+ * by restoring registers from the stack,
+ * The previous signal state is NOT restored.
+ */
+
+       .set    noreorder
+
+LEAF(_setjmp, 1)
+       LDGP(pv)
+       stq     ra, (2 * 8)(a0)                 /* sc_pc = return address */
+       stq     s0, (( 9 + 4) * 8)(a0)          /* saved bits of sc_regs */
+       stq     s1, ((10 + 4) * 8)(a0)
+       stq     s2, ((11 + 4) * 8)(a0)
+       stq     s3, ((12 + 4) * 8)(a0)
+       stq     s4, ((13 + 4) * 8)(a0)
+       stq     s5, ((14 + 4) * 8)(a0)
+       stq     s6, ((15 + 4) * 8)(a0)
+       stq     ra, ((26 + 4) * 8)(a0)
+       stq     sp, ((30 + 4) * 8)(a0)
+       ldiq    t0, 0xacedbadd                  /* sigcontext magic number */
+       stq     t0, ((31 + 4) * 8)(a0)          /* magic in sc_regs[31] */
+       /* Too bad we can't check if we actually used FP */
+       ldiq    t0, 1
+       stq     t0, (36 * 8)(a0)                /* say we've used FP.  */
+       stt     fs0, ((2 + 37) * 8)(a0)         /* saved bits of sc_fpregs */
+       stt     fs1, ((3 + 37) * 8)(a0)
+       stt     fs2, ((4 + 37) * 8)(a0)
+       stt     fs3, ((5 + 37) * 8)(a0)
+       stt     fs4, ((6 + 37) * 8)(a0)
+       stt     fs5, ((7 + 37) * 8)(a0)
+       stt     fs6, ((8 + 37) * 8)(a0)
+       stt     fs7, ((9 + 37) * 8)(a0)
+       mf_fpcr ft0                             /* get FP control reg */
+       stt     ft0, (69 * 8)(a0)               /* and store it in sc_fpcr */
+       stq     zero, (70 * 8)(a0)              /* FP software control XXX */
+       stq     zero, (71 * 8)(a0)              /* sc_reserved[0] */
+       stq     zero, (72 * 8)(a0)              /* sc_reserved[1] */
+       stq     zero, (73 * 8)(a0)              /* sc_xxx[0] */
+       stq     zero, (74 * 8)(a0)              /* sc_xxx[1] */
+       stq     zero, (75 * 8)(a0)              /* sc_xxx[2] */
+       stq     zero, (76 * 8)(a0)              /* sc_xxx[3] */
+       stq     zero, (77 * 8)(a0)              /* sc_xxx[4] */
+       stq     zero, (78 * 8)(a0)              /* sc_xxx[5] */
+       stq     zero, (79 * 8)(a0)              /* sc_xxx[6] */
+       stq     zero, (80 * 8)(a0)              /* sc_xxx[7] */
+
+       mov     zero, v0                        /* return zero */
+       RET
+END(_setjmp)
+
+LEAF(_longjmp, 2)
+       LDGP(pv)
+       ldq     t0, ((31 + 4) * 8)(a0)          /* magic in sc_regs[31] */
+       ldiq    t1, 0xacedbadd
+       cmpeq   t0, t1, t0
+       beq     t0, botch                       /* If the magic was bad, punt */
+
+       ldq     ra, (2 * 8)(a0)                 /* sc_pc = return address */
+       ldq     s0, (( 9 + 4) * 8)(a0)          /* saved bits of sc_regs */
+       ldq     s1, ((10 + 4) * 8)(a0)
+       ldq     s2, ((11 + 4) * 8)(a0)
+       ldq     s3, ((12 + 4) * 8)(a0)
+       ldq     s4, ((13 + 4) * 8)(a0)
+       ldq     s5, ((14 + 4) * 8)(a0)
+       ldq     s6, ((15 + 4) * 8)(a0)
+       /* ldq  ra, ((26 + 4) * 8)(a0)          set above */
+       ldq     sp, ((30 + 4) * 8)(a0)
+       ldt     fs0, ((2 + 37) * 8)(a0)         /* saved bits of sc_fpregs */
+       ldt     fs1, ((3 + 37) * 8)(a0)
+       ldt     fs2, ((4 + 37) * 8)(a0)
+       ldt     fs3, ((5 + 37) * 8)(a0)
+       ldt     fs4, ((6 + 37) * 8)(a0)
+       ldt     fs5, ((7 + 37) * 8)(a0)
+       ldt     fs6, ((8 + 37) * 8)(a0)
+       ldt     fs7, ((9 + 37) * 8)(a0)
+       ldt     ft0, (69 * 8)(a0)               /* get sc_fpcr */
+       mt_fpcr ft0                             /* and restore it. */
+
+       mov     a1, v0                          /* return second arg */
+       RET
+
+botch:
+       CALL(longjmperror)
+       CALL(abort)
+       RET                                     /* "can't" get here... */
+END(_longjmp)
diff --git a/lib/nbsd_libc/compat/arch/alpha/gen/compat_setjmp.S b/lib/nbsd_libc/compat/arch/alpha/gen/compat_setjmp.S
new file mode 100644 (file)
index 0000000..29781cd
--- /dev/null
@@ -0,0 +1,124 @@
+/* $NetBSD: compat_setjmp.S,v 1.1 2005/09/16 18:21:19 drochner Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and the previous signal state.
+ */
+
+       .set    noreorder
+
+LEAF(setjmp, 1)
+       LDGP(pv)
+       stq     ra, (2 * 8)(a0)                 /* sc_pc = return address */
+       stq     s0, (( 9 + 4) * 8)(a0)          /* saved bits of sc_regs */
+       stq     s1, ((10 + 4) * 8)(a0)
+       stq     s2, ((11 + 4) * 8)(a0)
+       stq     s3, ((12 + 4) * 8)(a0)
+       stq     s4, ((13 + 4) * 8)(a0)
+       stq     s5, ((14 + 4) * 8)(a0)
+       stq     s6, ((15 + 4) * 8)(a0)
+       stq     ra, ((26 + 4) * 8)(a0)
+       stq     sp, ((30 + 4) * 8)(a0)
+
+       /*
+        * get signal information
+        */
+       mov     a0, s0                          /* squirrel away ptr to sc */
+
+       /* see what's blocked */
+       mov     zero, a0
+       CALL(sigblock)                          /* see what's blocked */
+       stq     v0, (1 * 8)(s0)                 /* and remember it in sc_mask */
+
+       lda     sp, -24(sp)                     /* sizeof struct sigaltstack */
+       mov     zero, a0
+       mov     sp, a1
+       CALL(__sigaltstack14)
+       ldl     t0, 16(sp)                      /* offset of ss_flags */
+       lda     sp, 24(sp)                      /* sizeof struct sigaltstack */
+       ldq     ra, ((26 + 4) * 8)(s0)          /* restore return address */
+       blt     v0, botch                       /* check for error */
+       and     t0, 0x1, t0                     /* get SA_ONSTACK flag */
+       stq     t0, (0 * 8)(s0)                 /* and save it in sc_onstack */
+       /*
+        * Restore old s0 and a0, and continue saving registers
+        */
+       mov     s0, a0
+       ldq     s0, (( 9 + 4) * 8)(a0)
+
+       ldiq    t0, 0xacedbade                  /* sigcontext magic number */
+       stq     t0, ((31 + 4) * 8)(a0)          /* magic in sc_regs[31] */
+       /* Too bad we can't check if we actually used FP */
+       ldiq    t0, 1
+       stq     t0, (36 * 8)(a0)                /* say we've used FP.  */
+       stt     fs0, ((2 + 37) * 8)(a0)         /* saved bits of sc_fpregs */
+       stt     fs1, ((3 + 37) * 8)(a0)
+       stt     fs2, ((4 + 37) * 8)(a0)
+       stt     fs3, ((5 + 37) * 8)(a0)
+       stt     fs4, ((6 + 37) * 8)(a0)
+       stt     fs5, ((7 + 37) * 8)(a0)
+       stt     fs6, ((8 + 37) * 8)(a0)
+       stt     fs7, ((9 + 37) * 8)(a0)
+       mf_fpcr ft0                             /* get FP control reg */
+       stt     ft0, (69 * 8)(a0)               /* and store it in sc_fpcr */
+       stq     zero, (70 * 8)(a0)              /* FP software control XXX */
+       stq     zero, (71 * 8)(a0)              /* sc_reserved[0] */
+       stq     zero, (72 * 8)(a0)              /* sc_reserved[1] */
+       stq     zero, (73 * 8)(a0)              /* sc_xxx[0] */
+       stq     zero, (74 * 8)(a0)              /* sc_xxx[1] */
+       stq     zero, (75 * 8)(a0)              /* sc_xxx[2] */
+       stq     zero, (76 * 8)(a0)              /* sc_xxx[3] */
+       stq     zero, (77 * 8)(a0)              /* sc_xxx[4] */
+       stq     zero, (78 * 8)(a0)              /* sc_xxx[5] */
+       stq     zero, (79 * 8)(a0)              /* sc_xxx[6] */
+       stq     zero, (80 * 8)(a0)              /* sc_xxx[7] */
+
+       mov     zero, v0                        /* return zero */
+       RET
+END(setjmp)
+
+LEAF(longjmp, 2)
+       LDGP(pv)
+       stq     a1, (( 0 + 4) * 8)(a0)          /* save return value */
+       CALL(sigreturn)                         /* use sigreturn to return */
+
+botch:
+       CALL(longjmperror)
+       CALL(abort)
+       RET                                     /* "can't" get here... */
+END(longjmp)
diff --git a/lib/nbsd_libc/compat/arch/alpha/gen/compat_sigsetjmp.S b/lib/nbsd_libc/compat/arch/alpha/gen/compat_sigsetjmp.S
new file mode 100644 (file)
index 0000000..dba6f64
--- /dev/null
@@ -0,0 +1,62 @@
+/* $NetBSD: compat_sigsetjmp.S,v 1.1 2005/09/16 18:21:19 drochner Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <machine/asm.h>
+
+/*
+ * C library -- sigsetjmp, siglongjmp
+ *
+ *     siglongjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     sigsetjmp(a, mask)
+ * by restoring registers from the stack.
+ * If `mask' is non-zero, the previous signal
+ * state will be restored.
+ */
+
+       .set    noreorder
+
+LEAF(sigsetjmp, 2)
+       LDGP(pv)
+       stq     a1, (81 * 8)(a0)                /* save the mask */
+       bne     a1, Lsavesig                    /* if !zero, save signals */
+       jmp     zero, _setjmp                           /* else don't. */
+Lsavesig:
+       jmp     zero, setjmp
+END(sigsetjmp)
+
+LEAF(siglongjmp, 2)
+       LDGP(pv)
+       ldq     t0, (81 * 8)(a0)                /* get the mask */
+       bne     t0, Lrestoresig                 /* if !zero, restore signals */
+       jmp     zero, _longjmp
+Lrestoresig:
+       jmp     zero, longjmp
+END(siglongjmp)
diff --git a/lib/nbsd_libc/compat/arch/alpha/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/alpha/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..1786884
--- /dev/null
@@ -0,0 +1,6 @@
+# $NetBSD: Makefile.inc,v 1.1 2005/09/16 18:21:19 drochner Exp $
+
+SRCS+=compat_Ovfork.S compat___semctl.S compat___sigreturn14.S \
+    compat___sigtramp1.S compat_msgctl.S compat_shmctl.S compat_sigaction.S \
+    compat_sigpending.S compat_sigprocmask.S compat_sigreturn.S \
+    compat_sigsuspend.S
diff --git a/lib/nbsd_libc/compat/arch/alpha/sys/compat_Ovfork.S b/lib/nbsd_libc/compat/arch/alpha/sys/compat_Ovfork.S
new file mode 100644 (file)
index 0000000..b061d6d
--- /dev/null
@@ -0,0 +1,38 @@
+/* $NetBSD: compat_Ovfork.S,v 1.1 2005/09/16 18:21:19 drochner Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+WARN_REFERENCES(vfork, \
+    "warning: reference to compatibility vfork(); include <unistd.h> for correct reference")
+
+SYSCALL(vfork)
+       cmovne  a4, zero, v0            /* a4 (rv[1]) != 0, child */
+       RET
+END(vfork)
diff --git a/lib/nbsd_libc/compat/arch/alpha/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/alpha/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..8050310
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/alpha/sys/compat___sigreturn14.S b/lib/nbsd_libc/compat/arch/alpha/sys/compat___sigreturn14.S
new file mode 100644 (file)
index 0000000..708ef2f
--- /dev/null
@@ -0,0 +1,38 @@
+/* $NetBSD: compat___sigreturn14.S,v 1.1 2005/09/16 18:21:19 drochner Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ * However, that doesn't involve any special work on the Alpha.
+ * (XXX PROFILING)
+ */
+
+PSEUDO(__sigreturn14,compat_16___sigreturn14)
diff --git a/lib/nbsd_libc/compat/arch/alpha/sys/compat___sigtramp1.S b/lib/nbsd_libc/compat/arch/alpha/sys/compat___sigtramp1.S
new file mode 100644 (file)
index 0000000..df48f30
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: compat___sigtramp1.S,v 1.1 2005/09/16 18:21:19 drochner Exp $  */
+
+/*
+ * Copyright (c) 1994, 1995, 1996 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ *
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ *
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ *
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+/*
+ * The Alpha signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ *
+ * On entry, the stack looks like:
+ *
+ *     sp->    sigcontext structure
+ */
+NESTED_NOPROFILE(__sigtramp_sigcontext_1,0,0,ra,0,0)
+       mov     sp, a0                  /* get pointer to sigcontext */
+       CALLSYS_NOERROR(compat_16___sigreturn14)        /* and call sigreturn() with it */
+       mov     v0, a0                  /* if that failed, get error code */
+       CALLSYS_NOERROR(exit)           /* and call exit() with it */
+END(__sigtramp_sigcontext_1)
diff --git a/lib/nbsd_libc/compat/arch/alpha/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/alpha/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..cc08d76
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_msgctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/alpha/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/alpha/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..10d43f7
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_shmctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/alpha/sys/compat_sigaction.S b/lib/nbsd_libc/compat/arch/alpha/sys/compat_sigaction.S
new file mode 100644 (file)
index 0000000..a5f8ad8
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_sigaction.S,v 1.2 2008/04/28 20:22:58 martin Exp $      */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(sigaction, \
+    "warning: reference to compatibility sigaction(); include <signal.h> for correct reference")
+
+PSEUDO(sigaction,compat_13_sigaction13)
diff --git a/lib/nbsd_libc/compat/arch/alpha/sys/compat_sigpending.S b/lib/nbsd_libc/compat/arch/alpha/sys/compat_sigpending.S
new file mode 100644 (file)
index 0000000..7ecf6a3
--- /dev/null
@@ -0,0 +1,40 @@
+/* $NetBSD: compat_sigpending.S,v 1.1 2005/09/16 18:21:20 drochner Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigpending, \
+    "warning: reference to compatibility sigpending(); include <signal.h> for correct reference")
+
+LEAF(sigpending,0)                     /* XXX # of args? */
+       CALLSYS_ERROR(compat_13_sigpending13)
+       stl     v0, 0(a0)
+       mov     zero, v0
+       RET
+END(sigpending)
diff --git a/lib/nbsd_libc/compat/arch/alpha/sys/compat_sigprocmask.S b/lib/nbsd_libc/compat/arch/alpha/sys/compat_sigprocmask.S
new file mode 100644 (file)
index 0000000..316a80a
--- /dev/null
@@ -0,0 +1,47 @@
+/* $NetBSD: compat_sigprocmask.S,v 1.1 2005/09/16 18:21:20 drochner Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigprocmask, \
+    "warning: reference to compatibility sigprocmask(); include <signal.h> for correct reference")
+
+LEAF(sigprocmask, 3)
+       mov     a2, a5                  /* safe */
+       cmoveq  a1, 1, a0               /* if set == NULL, how = SIG_BLOCK */
+       beq     a1, Ldoit               /* and set = 0, and do it. */
+       ldl     a1, 0(a1)               /* load the set from *set */
+Ldoit: CALLSYS_ERROR(compat_13_sigprocmask13)
+       beq     a5, Lret                /* if they don't want old mask, done */ 
+       stl     v0, 0(a5)               /* otherwise, give it to them. */
+Lret:  mov     zero, v0
+       RET
+
+       END(sigprocmask)
+
diff --git a/lib/nbsd_libc/compat/arch/alpha/sys/compat_sigreturn.S b/lib/nbsd_libc/compat/arch/alpha/sys/compat_sigreturn.S
new file mode 100644 (file)
index 0000000..76983d0
--- /dev/null
@@ -0,0 +1,41 @@
+/* $NetBSD: compat_sigreturn.S,v 1.1 2005/09/16 18:21:20 drochner Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ * However, that doesn't involve any special work on the Alpha.
+ * (XXX PROFILING)
+ */
+
+WARN_REFERENCES(sigreturn, \
+    "warning: reference to compatibility sigreturn()")
+
+PSEUDO(sigreturn,compat_13_sigreturn13)
diff --git a/lib/nbsd_libc/compat/arch/alpha/sys/compat_sigsuspend.S b/lib/nbsd_libc/compat/arch/alpha/sys/compat_sigsuspend.S
new file mode 100644 (file)
index 0000000..b8f3b57
--- /dev/null
@@ -0,0 +1,40 @@
+/* $NetBSD: compat_sigsuspend.S,v 1.1 2005/09/16 18:21:20 drochner Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigsuspend, \
+    "warning: reference to compatibility sigsuspend(); include <signal.h> for correct reference")
+
+LEAF(sigsuspend, 1)
+       ldl     a0, 0(a0)               /* pass *mask instead of mask */
+       CALLSYS_ERROR(compat_13_sigsuspend13)
+       mov     zero, v0                /* shouldn't need; just in case... */
+       RET
+END(sigsuspend)
diff --git a/lib/nbsd_libc/compat/arch/arm/Makefile.inc b/lib/nbsd_libc/compat/arch/arm/Makefile.inc
new file mode 100644 (file)
index 0000000..78ab575
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/03/11 23:04:03 christos Exp $
+
+.include "${COMPATARCHDIR}/gen/Makefile.inc"
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/arm/gen/Makefile.inc b/lib/nbsd_libc/compat/arch/arm/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..81b2b91
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/06/28 14:46:33 drochner Exp $
+
+SRCS+= compat_setjmp.S compat_sigsetjmp.S
+
+# objects built from C sources in compat/gen
+SRCS+= compat_frexp_ieee754.c compat_ldexp_ieee754.c compat_modf_ieee754.c
diff --git a/lib/nbsd_libc/compat/arch/arm/gen/compat_setjmp.S b/lib/nbsd_libc/compat/arch/arm/gen/compat_setjmp.S
new file mode 100644 (file)
index 0000000..1514ef4
--- /dev/null
@@ -0,0 +1,130 @@
+/*     $NetBSD: compat_setjmp.S,v 1.1 2005/10/16 17:27:50 christos Exp $       */
+
+/*
+ * Copyright (c) 1997 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe
+ * 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 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 <machine/asm.h>
+#include <machine/setjmp.h>
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(setjmp)
+       /* Block all signals and retrieve the old signal mask */
+       stmfd   sp!, {r0, r14}
+       mov     r0, #0x00000000
+
+       bl      PIC_SYM(_C_LABEL(sigblock), PLT)
+       mov     r1, r0
+
+       ldmfd   sp!, {r0, r14}
+
+       /* Store signal mask */
+       str     r1, [r0, #(25 * 4)]
+
+       ldr     r1, .Lsetjmp_magic
+       str     r1, [r0], #4
+
+#ifdef SOFTFLOAT
+       add     r0, r0, #52
+#else
+       /* Store fp registers */
+       sfm     f4, 4, [r0], #48
+       /* Store fpsr */
+       rfs     r1
+       str     r1, [r0], #0x0004
+#endif /*SOFTFLOAT*/
+       /* Store integer registers */
+        stmia  r0, {r4-r14}
+        mov    r0, #0x00000000
+        RET
+
+.Lsetjmp_magic:
+       .word   _JB_MAGIC_SETJMP
+
+
+ENTRY(longjmp)
+       ldr     r2, .Lsetjmp_magic
+       ldr     r3, [r0]
+       teq     r2, r3
+       bne     botch
+
+       /* Fetch signal mask */
+       ldr     r2, [r0, #(25 * 4)]
+
+       /* Set signal mask */
+       stmfd   sp!, {r0, r1, r14}
+       sub     sp, sp, #4      /* align the stack */
+
+       mov     r0, r2
+       bl      PIC_SYM(_C_LABEL(sigsetmask), PLT)
+
+       add     sp, sp, #4      /* unalign the stack */
+       ldmfd   sp!, {r0, r1, r14} 
+
+       add     r0, r0, #4
+#ifdef SOFTFLOAT
+       add     r0, r0, #52
+#else
+       /* Restore fp registers */
+       lfm     f4, 4, [r0], #48
+       /* Restore FPSR */
+       ldr     r4, [r0], #0x0004
+       wfs     r4
+#endif /* SOFTFLOAT */
+       /* Restore integer registers */
+        ldmia  r0, {r4-r14}
+
+       /* Validate sp and r14 */
+       teq     sp, #0
+       teqne   r14, #0
+       beq     botch
+
+       /* Set return value */
+
+       mov     r0, r1
+       teq     r0, #0x00000000
+       moveq   r0, #0x00000001
+       RET
+
+       /* validation failed, die die die. */
+botch:
+       bl      PIC_SYM(_C_LABEL(longjmperror), PLT)
+       bl      PIC_SYM(_C_LABEL(abort), PLT)
+       b       . - 8           /* Cannot get here */
diff --git a/lib/nbsd_libc/compat/arch/arm/gen/compat_sigsetjmp.S b/lib/nbsd_libc/compat/arch/arm/gen/compat_sigsetjmp.S
new file mode 100644 (file)
index 0000000..8ad14fb
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: compat_sigsetjmp.S,v 1.1 2005/10/16 17:27:50 christos Exp $    */
+
+/*
+ * Copyright (c) 1997 Mark Brinicombe
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Mark Brinicombe
+ * 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 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 <machine/asm.h>
+#include <machine/setjmp.h>
+
+/*
+ * C library -- sigsetjmp, siglongjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     setjmp(a, m)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(sigsetjmp)
+       teq     r1, #0
+       beq     PIC_SYM(_C_LABEL(_setjmp), PLT)
+       b       PIC_SYM(_C_LABEL(setjmp), PLT)
+
+.L_setjmp_magic:
+       .word   _JB_MAGIC__SETJMP
+
+ENTRY(siglongjmp)
+       ldr     r2, .L_setjmp_magic
+       ldr     r3, [r0]
+       teq     r2, r3
+       beq     PIC_SYM(_C_LABEL(_longjmp), PLT)
+       b       PIC_SYM(_C_LABEL(longjmp), PLT)
diff --git a/lib/nbsd_libc/compat/arch/arm/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/arm/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..64c5246
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.1 2005/10/16 17:27:50 christos Exp $
+
+SRCS+=compat_Ovfork.S compat___semctl.S compat___sigreturn14.S \
+    compat___sigtramp1.S compat_msgctl.S compat_shmctl.S compat_sigaction.S \
+    compat_sigpending.S compat_sigprocmask.S compat_sigreturn.S \
+    compat_sigsuspend.S 
diff --git a/lib/nbsd_libc/compat/arch/arm/sys/compat_Ovfork.S b/lib/nbsd_libc/compat/arch/arm/sys/compat_Ovfork.S
new file mode 100644 (file)
index 0000000..317094e
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: compat_Ovfork.S,v 1.1 2005/10/16 17:27:50 christos Exp $       */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)Ovfork.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include "SYS.h"
+
+WARN_REFERENCES(vfork, \
+    "warning: reference to compatibility vfork(); include <unistd.h> for correct reference")
+
+/*
+ * pid = vfork();
+ *
+ * On return from the SWI:
+ * r1 == 0 in parent process, r1 == 1 in child process.
+ * r0 == pid of child in parent, r0 == pid of parent in child.
+ */
+       .text
+       .align  0
+
+ENTRY(vfork)
+       mov     r2, r14
+       SYSTRAP(vfork)
+       bcs     PIC_SYM(CERROR, PLT)
+       mov     r14, r2
+       sub     r1, r1, #1      /* r1 == 0xffffffff if parent, 0 if child */
+       and     r0, r0, r1      /* r0 == 0 if child, else unchanged */
+       RET
diff --git a/lib/nbsd_libc/compat/arch/arm/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/arm/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..8050310
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/arm/sys/compat___sigreturn14.S b/lib/nbsd_libc/compat/arch/arm/sys/compat___sigreturn14.S
new file mode 100644 (file)
index 0000000..72f0c1d
--- /dev/null
@@ -0,0 +1,40 @@
+/*     $NetBSD: compat___sigreturn14.S,v 1.1 2005/10/16 17:27:50 christos Exp $        */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)sigreturn.s   5.2 (Berkeley) 12/17/90"
+ */
+
+#include "SYS.h"
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ */
+
+PSEUDO(__sigreturn14,compat_16___sigreturn14)
diff --git a/lib/nbsd_libc/compat/arch/arm/sys/compat___sigtramp1.S b/lib/nbsd_libc/compat/arch/arm/sys/compat___sigtramp1.S
new file mode 100644 (file)
index 0000000..8404824
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: compat___sigtramp1.S,v 1.2 2008/04/28 20:22:58 martin Exp $    */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+/*
+ * The ARM signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ *
+ * On entry, the stack looks like:
+ *
+ *     sp->    sigcontext structure
+ */
+ENTRY_NP(__sigtramp_sigcontext_1)
+       mov     r0, sp                  /* get pointer to sigcontext */
+       SYSTRAP(compat_16___sigreturn14) /* and call sigreturn */
+
+       /* If that failed, exit with the error code. */
+       SYSTRAP(exit)
diff --git a/lib/nbsd_libc/compat/arch/arm/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/arm/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..cc08d76
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_msgctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/arm/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/arm/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..10d43f7
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_shmctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/arm/sys/compat_sigaction.S b/lib/nbsd_libc/compat/arch/arm/sys/compat_sigaction.S
new file mode 100644 (file)
index 0000000..a5f8ad8
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_sigaction.S,v 1.2 2008/04/28 20:22:58 martin Exp $      */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(sigaction, \
+    "warning: reference to compatibility sigaction(); include <signal.h> for correct reference")
+
+PSEUDO(sigaction,compat_13_sigaction13)
diff --git a/lib/nbsd_libc/compat/arch/arm/sys/compat_sigpending.S b/lib/nbsd_libc/compat/arch/arm/sys/compat_sigpending.S
new file mode 100644 (file)
index 0000000..7449a52
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: compat_sigpending.S,v 1.1 2005/10/16 17:27:50 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)sigpending.s  5.1 (Berkeley) 7/1/90
+ */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigpending, \
+    "warning: reference to compatibility sigpending(); include <signal.h> for correct reference")
+
+ENTRY(sigpending)
+       mov     r2, r0
+       SYSTRAP(compat_13_sigpending13)
+       bcs     PIC_SYM(CERROR, PLT)
+       str     r0, [r2]
+       mov     r0, #0x00000000
+       RET
diff --git a/lib/nbsd_libc/compat/arch/arm/sys/compat_sigprocmask.S b/lib/nbsd_libc/compat/arch/arm/sys/compat_sigprocmask.S
new file mode 100644 (file)
index 0000000..9e73bd1
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: compat_sigprocmask.S,v 1.1 2005/10/16 17:27:50 christos Exp $  */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)sigprocmask.s 5.2 (Berkeley) 12/17/90
+ */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigprocmask, \
+    "warning: reference to compatibility sigprocmask(); include <signal.h> for correct reference")
+
+ENTRY(sigprocmask)
+       teq     r1, #0x00000000
+       moveq   r0, #0x00000001
+       moveq   r1, #0x00000000
+       ldrne   r1, [r1]
+       SYSTRAP(compat_13_sigprocmask13)
+       bcs     PIC_SYM(CERROR, PLT)
+       teq     r2, #0x00000000
+       strne   r0, [r2]
+       mov     r0, #0x00000000
+       RET
diff --git a/lib/nbsd_libc/compat/arch/arm/sys/compat_sigreturn.S b/lib/nbsd_libc/compat/arch/arm/sys/compat_sigreturn.S
new file mode 100644 (file)
index 0000000..6428869
--- /dev/null
@@ -0,0 +1,43 @@
+/*     $NetBSD: compat_sigreturn.S,v 1.2 2005/10/16 22:16:05 christos Exp $    */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)sigreturn.s   5.2 (Berkeley) 12/17/90"
+ */
+
+#include "SYS.h"
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ */
+
+WARN_REFERENCES(sigreturn, \
+    "warning: reference to compatibility sigreturn()")
+
+PSEUDO(sigreturn,compat_13_sigreturn13)
diff --git a/lib/nbsd_libc/compat/arch/arm/sys/compat_sigsuspend.S b/lib/nbsd_libc/compat/arch/arm/sys/compat_sigsuspend.S
new file mode 100644 (file)
index 0000000..2b22059
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: compat_sigsuspend.S,v 1.1 2005/10/16 17:27:50 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ *
+ *     from: @(#)sigsuspend.s  5.2 (Berkeley) 12/17/90
+ */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigsuspend, \
+    "warning: reference to compatibility sigsuspend(); include <signal.h> for correct reference")
+
+ENTRY(sigsuspend)
+       ldr     r0, [r0]
+       SYSTRAP(compat_13_sigsuspend13)
+       bcs     PIC_SYM(CERROR, PLT)
+       mov     r0, #0x00000000
+       RET
diff --git a/lib/nbsd_libc/compat/arch/hppa/Makefile.inc b/lib/nbsd_libc/compat/arch/hppa/Makefile.inc
new file mode 100644 (file)
index 0000000..e9f6ca5
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.3 2006/06/28 14:46:33 drochner Exp $
+
+.include "${COMPATARCHDIR}/gen/Makefile.inc"
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/hppa/gen/Makefile.inc b/lib/nbsd_libc/compat/arch/hppa/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..a9e9667
--- /dev/null
@@ -0,0 +1,4 @@
+# $NetBSD: Makefile.inc,v 1.1 2006/06/28 14:46:33 drochner Exp $
+
+# objects built from C sources in compat/gen
+SRCS+= compat_frexp_ieee754.c compat_ldexp_ieee754.c compat_modf_ieee754.c
diff --git a/lib/nbsd_libc/compat/arch/hppa/locale/compat_setlocale32.c b/lib/nbsd_libc/compat/arch/hppa/locale/compat_setlocale32.c
new file mode 100644 (file)
index 0000000..dc035cd
--- /dev/null
@@ -0,0 +1,53 @@
+/* $NetBSD: compat_setlocale32.c,v 1.1 2010/06/07 13:52:29 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ * NetBSD: setlocale32.c,v 1.6 2010/05/22 13:50:02 tnozaki Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_setlocale32.c,v 1.1 2010/06/07 13:52:29 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <compat/include/locale.h>
+
+#include "setlocale_local.h"
+
+__warn_references(__setlocale_mb_len_max_32,
+    "warning: reference to compatibility __setlocale_mb_len_max_32();"
+    "include <locale.h> for correct reference")
+
+char *
+__setlocale_mb_len_max_32(int category, const char *locale)
+{
+
+       /* locale may be NULL */
+
+       __mb_len_max_runtime = 6;
+       return __setlocale(category, locale);
+}
diff --git a/lib/nbsd_libc/compat/arch/hppa/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/hppa/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..a38ba11
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/11 19:54:56 christos Exp $
+
+SRCS+=compat_Ovfork.S compat___semctl.S compat___sigreturn14.S \
+    compat_msgctl.S compat_shmctl.S compat_sigaction.S \
+    compat_sigpending.S compat_sigprocmask.S compat_sigreturn.S \
+    compat_sigsuspend.S 
diff --git a/lib/nbsd_libc/compat/arch/hppa/sys/compat_Ovfork.S b/lib/nbsd_libc/compat/arch/hppa/sys/compat_Ovfork.S
new file mode 100644 (file)
index 0000000..bf0f9a2
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: compat_Ovfork.S,v 1.2 2009/11/03 05:07:25 snj Exp $    */
+
+/*     $OpenBSD: Ovfork.S,v 1.7 2001/06/04 23:14:04 mickey Exp $       */
+
+/*
+ * Copyright (c) 1999,2002 Michael Shalayeff
+ * 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 ``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 HIS RELATIVES 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 MIND, 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_Ovfork.S,v 1.2 2009/11/03 05:07:25 snj Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+ENTRY(vfork,0)
+       SYSCALL(vfork)
+       addi    -1, %ret1, %ret1
+       bv      %r0(%rp)
+       and     %ret1, %ret0, %ret0
+EXIT(vfork)
+
+       .end
diff --git a/lib/nbsd_libc/compat/arch/hppa/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/hppa/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..8050310
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/hppa/sys/compat___sigreturn14.S b/lib/nbsd_libc/compat/arch/hppa/sys/compat___sigreturn14.S
new file mode 100644 (file)
index 0000000..515a888
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: compat___sigreturn14.S,v 1.1 2006/03/11 19:54:56 christos Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat___sigreturn14.S,v 1.1 2006/03/11 19:54:56 christos Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+PSEUDO(__sigreturn14,compat_16___sigreturn14)
diff --git a/lib/nbsd_libc/compat/arch/hppa/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/hppa/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..cc08d76
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_msgctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/hppa/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/hppa/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..10d43f7
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_shmctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/hppa/sys/compat_sigaction.S b/lib/nbsd_libc/compat/arch/hppa/sys/compat_sigaction.S
new file mode 100644 (file)
index 0000000..a5f8ad8
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_sigaction.S,v 1.2 2008/04/28 20:22:58 martin Exp $      */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(sigaction, \
+    "warning: reference to compatibility sigaction(); include <signal.h> for correct reference")
+
+PSEUDO(sigaction,compat_13_sigaction13)
diff --git a/lib/nbsd_libc/compat/arch/hppa/sys/compat_sigpending.S b/lib/nbsd_libc/compat/arch/hppa/sys/compat_sigpending.S
new file mode 100644 (file)
index 0000000..0ed8d51
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: compat_sigpending.S,v 1.2 2008/04/28 20:22:58 martin Exp $     */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Fredette.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+#include "SYS.h"
+
+       .import __cerror, code
+
+WARN_REFERENCES(sigpending, \
+    "warning: reference to compatibility sigpending(); include <signal.h> for correct reference")
+
+ENTRY(sigpending, 0)
+       /*
+        * AFAICT, since the hppa port came after __sigpending14, 
+        * we shouldn't have to supply the compatability sigpending.
+        */
+       ldi     EINVAL, %t1
+       b,n     __cerror
+EXIT(sigpending)
diff --git a/lib/nbsd_libc/compat/arch/hppa/sys/compat_sigprocmask.S b/lib/nbsd_libc/compat/arch/hppa/sys/compat_sigprocmask.S
new file mode 100644 (file)
index 0000000..99c0093
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: compat_sigprocmask.S,v 1.2 2008/04/28 20:22:58 martin Exp $    */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Fredette.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+#include "SYS.h"
+
+       .import __cerror, code
+
+WARN_REFERENCES(sigprocmask, \
+    "warning: reference to compatibility sigprocmask(); include <signal.h> for correct reference")
+
+ENTRY(sigprocmask, 0)
+       /*
+        * AFAICT, since the hppa port came after __sigprocmask14, 
+        * we shouldn't have to supply the compatability sigprocmask.
+        */
+       ldi     EINVAL, %t1
+       b,n     __cerror
+EXIT(sigprocmask)
diff --git a/lib/nbsd_libc/compat/arch/hppa/sys/compat_sigreturn.S b/lib/nbsd_libc/compat/arch/hppa/sys/compat_sigreturn.S
new file mode 100644 (file)
index 0000000..d02624b
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: compat_sigreturn.S,v 1.2 2008/04/28 20:22:58 martin Exp $      */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Fredette.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+#include "SYS.h"
+
+       .import __cerror, code
+
+WARN_REFERENCES(sigreturn, \
+    "warning: reference to compatibility sigreturn(); include <signal.h> for correct reference")
+
+ENTRY(sigreturn, 0)
+       /*
+        * AFAICT, since the hppa port came after __sigreturn14, 
+        * we shouldn't have to supply the compatability sigreturn.
+        */
+       ldi     EINVAL, %t1
+       b,n     __cerror
+EXIT(sigreturn)
diff --git a/lib/nbsd_libc/compat/arch/hppa/sys/compat_sigsuspend.S b/lib/nbsd_libc/compat/arch/hppa/sys/compat_sigsuspend.S
new file mode 100644 (file)
index 0000000..2cdbb3e
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: compat_sigsuspend.S,v 1.2 2008/04/28 20:22:58 martin Exp $     */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Fredette.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/errno.h>
+#include "SYS.h"
+
+       .import __cerror, code
+
+WARN_REFERENCES(sigsuspend, \
+    "warning: reference to compatibility sigsuspend(); include <signal.h> for correct reference")
+
+ENTRY(sigsuspend, 0)
+       /*
+        * AFAICT, since the hppa port came after __sigsuspend14, 
+        * we shouldn't have to supply the compatability sigsuspend.
+        */
+       ldi     EINVAL, %t1
+       b,n     __cerror
+EXIT(sigsuspend)
diff --git a/lib/nbsd_libc/compat/arch/i386/Makefile.inc b/lib/nbsd_libc/compat/arch/i386/Makefile.inc
new file mode 100644 (file)
index 0000000..78ab575
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/03/11 23:04:03 christos Exp $
+
+.include "${COMPATARCHDIR}/gen/Makefile.inc"
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/i386/gen/Makefile.inc b/lib/nbsd_libc/compat/arch/i386/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..81d6059
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.3 2006/06/27 18:19:57 drochner Exp $
+
+# objects built from assembler sources (need lint stubs)
+SRCS+= compat_setjmp.S compat_sigsetjmp.S
+
+# objects built from C sources in compat/gen
+SRCS+=  compat_frexp_ieee754.c compat_ldexp_ieee754.c compat_modf_ieee754.c
diff --git a/lib/nbsd_libc/compat/arch/i386/gen/compat_setjmp.S b/lib/nbsd_libc/compat/arch/i386/gen/compat_setjmp.S
new file mode 100644 (file)
index 0000000..67e7f72
--- /dev/null
@@ -0,0 +1,101 @@
+/*     $NetBSD: compat_setjmp.S,v 1.1 2005/09/13 01:44:08 christos Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)setjmp.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: compat_setjmp.S,v 1.1 2005/09/13 01:44:08 christos Exp $")
+#endif
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(setjmp)
+
+       PIC_PROLOGUE
+       pushl   $0
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(sigblock))
+#else
+       call    _C_LABEL(sigblock)
+#endif
+       addl    $4,%esp
+       PIC_EPILOGUE
+
+       movl    4(%esp),%ecx
+       movl    0(%esp),%edx
+       movl    %edx, 0(%ecx)
+       movl    %ebx, 4(%ecx)
+       movl    %esp, 8(%ecx)
+       movl    %ebp,12(%ecx)
+       movl    %esi,16(%ecx)
+       movl    %edi,20(%ecx)
+       movl    %eax,24(%ecx)
+       xorl    %eax,%eax
+       ret
+
+ENTRY(longjmp)
+       movl    4(%esp),%edx
+
+       PIC_PROLOGUE
+       pushl   24(%edx)
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(sigsetmask))
+#else
+       call    _C_LABEL(sigsetmask)
+#endif
+       addl    $4,%esp
+       PIC_EPILOGUE
+
+       movl    4(%esp),%edx
+       movl    8(%esp),%eax
+       movl    0(%edx),%ecx
+       movl    4(%edx),%ebx
+       movl    8(%edx),%esp
+       movl    12(%edx),%ebp
+       movl    16(%edx),%esi
+       movl    20(%edx),%edi
+       testl   %eax,%eax
+       jnz     1f
+       incl    %eax
+1:     movl    %ecx,0(%esp)
+       ret
diff --git a/lib/nbsd_libc/compat/arch/i386/gen/compat_sigsetjmp.S b/lib/nbsd_libc/compat/arch/i386/gen/compat_sigsetjmp.S
new file mode 100644 (file)
index 0000000..f9cc9e9
--- /dev/null
@@ -0,0 +1,98 @@
+/*     $NetBSD: compat_sigsetjmp.S,v 1.1 2005/09/13 01:44:08 christos Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)setjmp.s      5.1 (Berkeley) 4/23/90"
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: compat_sigsetjmp.S,v 1.1 2005/09/13 01:44:08 christos Exp $")
+#endif
+
+ENTRY(sigsetjmp)
+       movl    4(%esp),%ecx
+       movl    8(%esp),%eax
+       movl    %eax,28(%ecx)
+       testl   %eax,%eax
+       jz      2f
+
+       PIC_PROLOGUE
+       pushl   $0
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(sigblock))
+#else
+       call    _C_LABEL(sigblock)
+#endif
+       addl    $4,%esp
+       PIC_EPILOGUE
+
+       movl    4(%esp),%ecx
+       movl    %eax,24(%ecx)
+2:     movl    0(%esp),%edx
+       movl    %edx, 0(%ecx)
+       movl    %ebx, 4(%ecx)
+       movl    %esp, 8(%ecx)
+       movl    %ebp,12(%ecx)
+       movl    %esi,16(%ecx)
+       movl    %edi,20(%ecx)
+       xorl    %eax,%eax
+       ret
+
+ENTRY(siglongjmp)
+       movl    4(%esp),%edx
+       cmpl    $0,28(%edx)
+       jz      2f
+
+       PIC_PROLOGUE
+       pushl   24(%edx)
+#ifdef PIC
+       call    PIC_PLT(_C_LABEL(sigsetmask))
+#else
+       call    _C_LABEL(sigsetmask)
+#endif
+       addl    $4,%esp
+       PIC_EPILOGUE
+
+2:     movl    4(%esp),%edx
+       movl    8(%esp),%eax
+       movl    0(%edx),%ecx
+       movl    4(%edx),%ebx
+       movl    8(%edx),%esp
+       movl    12(%edx),%ebp
+       movl    16(%edx),%esi
+       movl    20(%edx),%edi
+       testl   %eax,%eax
+       jnz     3f
+       incl    %eax
+3:     movl    %ecx,0(%esp)
+       ret
diff --git a/lib/nbsd_libc/compat/arch/i386/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/i386/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..60a6c2d
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.1 2005/09/13 01:44:08 christos Exp $
+
+SRCS+=compat_Ovfork.S compat___semctl.S compat___sigreturn14.S \
+    compat___sigtramp1.S compat_msgctl.S compat_shmctl.S compat_sigaction.S \
+    compat_sigpending.S compat_sigprocmask.S compat_sigreturn.S \
+    compat_sigsuspend.S 
diff --git a/lib/nbsd_libc/compat/arch/i386/sys/compat_Ovfork.S b/lib/nbsd_libc/compat/arch/i386/sys/compat_Ovfork.S
new file mode 100644 (file)
index 0000000..385d075
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: compat_Ovfork.S,v 1.1 2005/09/13 01:44:08 christos Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)Ovfork.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_Ovfork.S,v 1.1 2005/09/13 01:44:08 christos Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(vfork, \
+    "warning: reference to compatibility vfork(); include <unistd.h> for correct reference")
+
+/*
+ * pid = vfork();
+ *
+ * %edx == 0 in parent process, %edx == 1 in child process.
+ * %eax == pid of child in parent, %eax == pid of parent in child.
+ *
+ */
+ENTRY(vfork)
+       popl    %ecx            /* my rta into ecx */
+       SYSTRAP(vfork)
+       jc      err
+       decl    %edx
+       andl    %edx,%eax
+       jmp     *%ecx
+err:
+       pushl   %ecx
+#ifdef PIC
+       PIC_PROLOGUE
+       mov     PIC_GOT(CERROR), %ecx
+       PIC_EPILOGUE
+       jmp     *%ecx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/compat/arch/i386/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/i386/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..8050310
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/i386/sys/compat___sigreturn14.S b/lib/nbsd_libc/compat/arch/i386/sys/compat___sigreturn14.S
new file mode 100644 (file)
index 0000000..08fdc51
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: compat___sigreturn14.S,v 1.2 2011/01/12 23:12:11 joerg Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigreturn.s   5.2 (Berkeley) 12/17/90"
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat___sigreturn14.S,v 1.2 2011/01/12 23:12:11 joerg Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ */
+#ifdef GPROF
+#undef ENTRY
+#ifdef __ELF__
+#define MCOUNT_SYMBOL  __mcount
+#else
+#define MCOUNT_SYMBOL  mcount
+#endif
+#define        ENTRY(x) \
+       .globl _ ## x; _ALIGN_TEXT; _ ## x:  pusha ; \
+       .data; 1:; .long 0; .text; movl $1b,%eax; call MCOUNT_SYMBOL; popa ; nop
+#endif /* GPROF */
+
+PSEUDO(__sigreturn14,compat_16___sigreturn14)
diff --git a/lib/nbsd_libc/compat/arch/i386/sys/compat___sigtramp1.S b/lib/nbsd_libc/compat/arch/i386/sys/compat___sigtramp1.S
new file mode 100644 (file)
index 0000000..4ae7546
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: compat___sigtramp1.S,v 1.2 2008/04/28 20:22:58 martin Exp $    */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+/*
+ * The i386 signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ *
+ * On entry, stack looks like:
+ *
+ *             sigcontext structure                    [12]
+ *             pointer to sigcontext structure         [8]
+ *             signal specific code                    [4]
+ *     sp->    signal number                           [0]
+ */
+NENTRY(__sigtramp_sigcontext_1)
+       leal    12(%esp),%eax   /* get pointer to sigcontext */
+       movl    %eax,4(%esp)    /* put it in the argument slot */
+                               /* fake return address already there */
+       SYSTRAP(compat_16___sigreturn14) /* do sigreturn */
+       movl    %eax,4(%esp)    /* error code */
+       SYSTRAP(exit)           /* exit */
diff --git a/lib/nbsd_libc/compat/arch/i386/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/i386/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..cc08d76
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_msgctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/i386/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/i386/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..10d43f7
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_shmctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/i386/sys/compat_sigaction.S b/lib/nbsd_libc/compat/arch/i386/sys/compat_sigaction.S
new file mode 100644 (file)
index 0000000..a5f8ad8
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_sigaction.S,v 1.2 2008/04/28 20:22:58 martin Exp $      */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(sigaction, \
+    "warning: reference to compatibility sigaction(); include <signal.h> for correct reference")
+
+PSEUDO(sigaction,compat_13_sigaction13)
diff --git a/lib/nbsd_libc/compat/arch/i386/sys/compat_sigpending.S b/lib/nbsd_libc/compat/arch/i386/sys/compat_sigpending.S
new file mode 100644 (file)
index 0000000..55ad1b7
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: compat_sigpending.S,v 1.1 2005/09/13 01:44:08 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigpending.s  5.1 (Berkeley) 7/1/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigpending.S,v 1.1 2005/09/13 01:44:08 christos Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigpending, \
+    "warning: reference to compatibility sigpending(); include <signal.h> for correct reference")
+
+_SYSCALL(sigpending,compat_13_sigpending13)
+       movl    4(%esp),%ecx            # fetch pointer to...
+       movl    %eax,(%ecx)             # store old mask
+       xorl    %eax,%eax
+       ret
diff --git a/lib/nbsd_libc/compat/arch/i386/sys/compat_sigprocmask.S b/lib/nbsd_libc/compat/arch/i386/sys/compat_sigprocmask.S
new file mode 100644 (file)
index 0000000..246cf69
--- /dev/null
@@ -0,0 +1,73 @@
+/*     $NetBSD: compat_sigprocmask.S,v 1.1 2005/09/13 01:44:08 christos Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigprocmask.s 5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigprocmask.S,v 1.1 2005/09/13 01:44:08 christos Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigprocmask, \
+    "warning: reference to compatibility sigprocmask(); include <signal.h> for correct reference")
+
+ENTRY(sigprocmask)
+       movl    8(%esp),%ecx            # fetch new sigset pointer
+       testl   %ecx,%ecx               # check new sigset pointer
+       jnz     1f                      # if not null, indirect
+/*     movl    $0,8(%esp)              # null mask pointer: block empty set */
+       movl    $1,4(%esp)              # SIG_BLOCK
+       jmp     2f
+1:     movl    (%ecx),%ecx             # fetch indirect  ...
+       movl    %ecx,8(%esp)            # to new mask arg
+2:     SYSTRAP(compat_13_sigprocmask13)
+       jc      err
+       movl    12(%esp),%ecx           # fetch old mask requested
+       testl   %ecx,%ecx               # test if old mask requested
+       jz      out
+       movl    %eax,(%ecx)             # store old mask
+out:
+       xorl    %eax,%eax
+       ret
+err:
+#ifdef PIC
+       PIC_PROLOGUE
+       mov     PIC_GOT(CERROR), %ecx
+       PIC_EPILOGUE
+       jmp     *%ecx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/compat/arch/i386/sys/compat_sigreturn.S b/lib/nbsd_libc/compat/arch/i386/sys/compat_sigreturn.S
new file mode 100644 (file)
index 0000000..c3da3cb
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: compat_sigreturn.S,v 1.2 2011/01/12 23:12:11 joerg Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigreturn.s   5.2 (Berkeley) 12/17/90"
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigreturn.S,v 1.2 2011/01/12 23:12:11 joerg Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ */
+#ifdef GPROF
+#undef ENTRY
+#ifdef __ELF__
+#define MCOUNT_SYMBOL  __mcount
+#else
+#define MCOUNT_SYMBOL  mcount
+#endif
+#define        ENTRY(x) \
+       .globl _ ## x; _ALIGN_TEXT; _ ## x:  pusha ; \
+       .data; 1:; .long 0; .text; movl $1b,%eax; call MCOUNT_SYMBOL; popa ; nop
+#endif /* GPROF */
+
+WARN_REFERENCES(sigreturn, \
+    "warning: reference to compatibility sigreturn()")
+
+PSEUDO(sigreturn,compat_13_sigreturn13)
diff --git a/lib/nbsd_libc/compat/arch/i386/sys/compat_sigsuspend.S b/lib/nbsd_libc/compat/arch/i386/sys/compat_sigsuspend.S
new file mode 100644 (file)
index 0000000..b1bdb2a
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: compat_sigsuspend.S,v 1.1 2005/09/13 01:44:08 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigsuspend.s  5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigsuspend.S,v 1.1 2005/09/13 01:44:08 christos Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigsuspend, \
+    "warning: reference to compatibility sigsuspend(); include <signal.h> for correct reference")
+
+ENTRY(sigsuspend)
+       movl    4(%esp),%eax            # fetch mask arg
+       movl    (%eax),%eax             # indirect to mask arg
+       movl    %eax,4(%esp)
+       SYSTRAP(compat_13_sigsuspend13)
+       jc      err
+       xorl    %eax,%eax               # shouldn t happen
+       ret
+err:
+#ifdef PIC
+       PIC_PROLOGUE
+       mov     PIC_GOT(CERROR), %ecx
+       PIC_EPILOGUE
+       jmp     *%ecx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/compat/arch/ia64/Makefile.inc b/lib/nbsd_libc/compat/arch/ia64/Makefile.inc
new file mode 100644 (file)
index 0000000..81c5297
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/09/23 17:38:03 cherry Exp $
+
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
+
diff --git a/lib/nbsd_libc/compat/arch/ia64/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/ia64/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..f7d1a2c
--- /dev/null
@@ -0,0 +1,3 @@
+# $NetBSD: Makefile.inc,v 1.1 2006/09/23 17:38:03 cherry Exp $
+
+SRCS+= compat___semctl.S
diff --git a/lib/nbsd_libc/compat/arch/ia64/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/ia64/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..8050310
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/m68k/Makefile.inc b/lib/nbsd_libc/compat/arch/m68k/Makefile.inc
new file mode 100644 (file)
index 0000000..78ab575
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/03/11 23:04:03 christos Exp $
+
+.include "${COMPATARCHDIR}/gen/Makefile.inc"
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/m68k/gen/Makefile.inc b/lib/nbsd_libc/compat/arch/m68k/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..260fd9c
--- /dev/null
@@ -0,0 +1,8 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/07/03 12:54:34 drochner Exp $
+
+# objects built from assembler sources (need lint stubs)
+SRCS+= compat_setjmp.S compat_sigsetjmp.S
+
+# objects built from C sources in compat/gen
+SRCS+= compat_frexp_ieee754.c
+#SRCS+=        compat_ldexp_ieee754.c compat_modf_ieee754.c
diff --git a/lib/nbsd_libc/compat/arch/m68k/gen/compat_setjmp.S b/lib/nbsd_libc/compat/arch/m68k/gen/compat_setjmp.S
new file mode 100644 (file)
index 0000000..49045e0
--- /dev/null
@@ -0,0 +1,95 @@
+/*     $NetBSD: compat_setjmp.S,v 1.1 2006/03/09 16:20:55 christos Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)setjmp.s       5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: compat_setjmp.S,v 1.1 2006/03/09 16:20:55 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and a struct sigcontext, see <signal.h>
+ */
+
+ENTRY(setjmp)
+       lea     %sp@(-12),%sp   /* space for sigstack args/rvals */
+       clrl    %sp@            /* don't change it... */
+       movl    %sp,%sp@(4)     /* ...but return the current val */
+       jbsr    PIC_PLT(_C_LABEL(__sigaltstack14))
+                               /* note: flags returned in sp@(8) */
+       clrl    %sp@            /* don't change mask, just return */
+       jbsr    PIC_PLT(_C_LABEL(sigblock)) /*  old value */
+       movl    %sp@(8),%d1     /* old flags value */
+       andl    #1,%d1          /* extract onstack flag */
+       lea     %sp@(12),%sp
+       movl    %sp@(4),%a0     /* save area pointer */
+       movl    %d1,%a0@+       /* save old onstack value */
+       movl    %d0,%a0@+       /* save old signal mask */
+       lea     %sp@(4),%a1     /* adjust saved SP since we won't rts */
+       movl    %a1,%a0@+       /* save old SP */
+       movl    %a6,%a0@+       /* save old FP */
+       clrl    %a0@+           /* no AP */
+       movl    %sp@,%a0@+      /* save old PC */
+       clrl    %a0@+           /* clean PS */
+       moveml  #0x3CFC,%a0@    /* save remaining non-scratch regs */
+       clrl    %d0             /* return 0 */
+       rts
+
+ENTRY(longjmp)
+       movl    %sp@(4),%a0     /* save area pointer */
+       tstl    %a0@(8)         /* ensure non-zero SP */
+       jeq     botch           /* oops! */
+       movl    %sp@(8),%d0     /* grab return value */
+       jne     ok              /* non-zero ok */
+       moveq   #1,%d0          /* else make non-zero */
+ok:
+       moveml  %a0@(28),#0x3CFC /* restore non-scratch regs */
+       movl    %a0,%sp@-        /* let sigreturn */
+       jbsr    PIC_PLT(_C_LABEL(sigreturn)) /*  finish for us */
+
+botch:
+       jbsr    PIC_PLT(_C_LABEL(longjmperror))
+       stop    #0
diff --git a/lib/nbsd_libc/compat/arch/m68k/gen/compat_sigsetjmp.S b/lib/nbsd_libc/compat/arch/m68k/gen/compat_sigsetjmp.S
new file mode 100644 (file)
index 0000000..4c57960
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: compat_sigsetjmp.S,v 1.1 2006/03/09 16:20:55 christos Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include <machine/asm.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)_setjmp.s      5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: compat_sigsetjmp.S,v 1.1 2006/03/09 16:20:55 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- sigsetjmp, siglongjmp
+ *
+ *     siglongjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     sigsetjmp(a,m)
+ * by restoring registers from the stack,
+ * The previous signal state is restored if 'm' was non-zero.
+ */
+
+/* grab _JBLEN */
+#include <m68k/setjmp.h>
+
+ENTRY(sigsetjmp)
+       movl    %sp@(8),%d1     /* grab the mask */
+        movl   %sp@(4),%a0     /* grab the area pointer */
+       movl    %d1,%a0@(_JBLEN * 4 )   /* save at end of area */
+       tstl    %d1
+       bne     dosig
+       jra     PIC_PLT(_C_LABEL(_setjmp))
+dosig:
+       jra     PIC_PLT(_C_LABEL(setjmp))
+
+
+ENTRY(siglongjmp)
+       movl    %sp@(4),%a0     /* save area pointer */
+       tstl    %a0@(_JBLEN * 4) /* check mask... */
+       bne     didsig
+       jra     PIC_PLT(_C_LABEL(_longjmp))
+didsig:
+       jra     PIC_PLT(_C_LABEL(longjmp))
diff --git a/lib/nbsd_libc/compat/arch/m68k/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/m68k/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..768d04c
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/09 16:20:55 christos Exp $
+
+SRCS+=compat_Ovfork.S compat___semctl.S compat___sigreturn14.S \
+    compat___sigtramp1.S compat_msgctl.S compat_shmctl.S compat_sigaction.S \
+    compat_sigpending.S compat_sigprocmask.S compat_sigreturn.S \
+    compat_sigsuspend.S 
diff --git a/lib/nbsd_libc/compat/arch/m68k/sys/compat_Ovfork.S b/lib/nbsd_libc/compat/arch/m68k/sys/compat_Ovfork.S
new file mode 100644 (file)
index 0000000..4935ec9
--- /dev/null
@@ -0,0 +1,110 @@
+/*     $NetBSD: compat_Ovfork.S,v 1.1 2006/03/09 16:20:55 christos Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)Ovfork.s       5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: compat_Ovfork.S,v 1.1 2006/03/09 16:20:55 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * @(#)vfork.s 4.1 (Berkeley) 12/21/80
+ * C library -- vfork
+ */
+
+WARN_REFERENCES(vfork, \
+    "warning: reference to compatibility vfork(); include <unistd.h> for correct reference")
+
+/*
+ * pid = vfork();
+ *
+ * d1 == 0 in parent process, d1 == 1 in child process.
+ * d0 == pid of child in parent, d0 == pid of parent in child.
+ *
+ * trickery here, due to keith sklower, uses ret to clear the stack,
+ * and then returns with a jump indirect, since only one person can return
+ * with a ret off this stack... we do the ret before we vfork!
+ */
+
+ENTRY(vfork)
+       movl    %sp@+,%a1
+       movl    #SYS_vfork,%d0
+       trap    #0
+       jcs     err
+       subql   #1,%d1  /* from 1 to 0 in child, 0 to -1 in parent */
+       andl    %d1,%d0
+       jmp     %a1@
+err:
+#ifdef _REENTRANT
+       .globl  _C_LABEL(__errno)
+       movl    %a1,%sp@-
+       movl    %d0,%sp@-
+#if defined(PIC) && !defined(__ELF__)
+       movl    #_C_LABEL(_GLOBAL_OFFSET_TABLE_),%a1
+       lea     %pc@(0,a1:l),%a1
+       movl    %a1@(_C_LABEL(__errno):l),%a1
+       jsr     %a1@
+#else
+       jbsr    PIC_PLT(_C_LABEL(__errno))
+#endif /* PIC */
+#ifdef __SVR4_ABI__
+       movl    %sp@+,%a0@
+#else
+       movl    %d0,%a1
+       movl    %sp@+,%a1@
+#endif /* __SVR4_ABI__ */
+       movl    %sp@+,%a1
+#else
+       .globl  _C_LABEL(errno)
+#ifdef PIC
+#ifdef __ELF__
+       lea     %pc@(_GLOBAL_OFFSET_TABLE_@GOTPC),%a0
+       movl    %a0@(_C_LABEL(errno)@GOT:w),%a0
+#else
+       movl    #_C_LABEL(_GLOBAL_OFFSET_TABLE_),%a0
+       lea     %pc@(0,a0:l),%a0
+       movl    %a0@(_C_LABEL(errno):w),%a0
+#endif
+       movl    %d0,%a0@
+#else
+       movl    %d0,_C_LABEL(errno)
+#endif /* PIC */
+#endif /* _REENTRANT */
+       moveq   #-1,%d0
+       jmp     %a1@
diff --git a/lib/nbsd_libc/compat/arch/m68k/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/m68k/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..8050310
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/m68k/sys/compat___sigreturn14.S b/lib/nbsd_libc/compat/arch/m68k/sys/compat___sigreturn14.S
new file mode 100644 (file)
index 0000000..8a97da0
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: compat___sigreturn14.S,v 1.1 2006/03/09 16:20:55 christos Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)sigreturn.s    5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: compat___sigreturn14.S,v 1.1 2006/03/09 16:20:55 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ */
+#ifdef GPROF
+#undef ENTRY
+#ifdef __STDC__
+#define ENTRY(x) \
+       .globl _C_LABEL(x); .even; _C_LABEL(x):; moveml #0xC0C0,%sp@-; .data; \
+       PROF ## x:; .long 0; .text; lea PROF ## x,%a0; jbsr MCOUNT_ENTRY; \
+       moveml %sp@+,#0x0303
+#else
+#define        ENTRY(x) \
+       .globl _C_LABEL(x); .even; _C_LABEL(x):; moveml #0xC0C0,%sp@-; .data; \
+       PROF/**/x:; .long 0; .text; lea PROF/**/x,%a0; jbsr MCOUNT_ENTRY; \
+       moveml %sp@+,#0x0303
+#endif /* __STDC__ */
+#endif /* GPROF */
+
+ENTRY(__sigreturn14)
+       trap    #3              /* special sigreturn syscall entry point */
+       jra     PIC_PLT(CERROR)
diff --git a/lib/nbsd_libc/compat/arch/m68k/sys/compat___sigtramp1.S b/lib/nbsd_libc/compat/arch/m68k/sys/compat___sigtramp1.S
new file mode 100644 (file)
index 0000000..8c3162b
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: compat___sigtramp1.S,v 1.2 2008/04/28 20:22:58 martin Exp $    */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+/*
+ * The m68k signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ *
+ * On entry, stack looks like:
+ *
+ *             sigcontext structure                    [12]
+ *             pointer to sigcontext structure         [8]
+ *             signal specific code                    [4]
+ *     sp->    signal number                           [0]
+ */
+ENTRY_NOPROFILE(__sigtramp_sigcontext_1)
+       leal    %sp@(12),%a0    /* get pointer to sigcontext */
+       movl    %a0,%sp@(4)     /* put it in the argument slot */
+                               /* fake return address already there */
+       trap    #3              /* special sigreturn trap */
+       movl    %d0,%sp@(4)     /* failed, exit with errno */
+       SYSTRAP(exit)
diff --git a/lib/nbsd_libc/compat/arch/m68k/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/m68k/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..cc08d76
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_msgctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/m68k/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/m68k/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..10d43f7
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_shmctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/m68k/sys/compat_sigaction.S b/lib/nbsd_libc/compat/arch/m68k/sys/compat_sigaction.S
new file mode 100644 (file)
index 0000000..a5f8ad8
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_sigaction.S,v 1.2 2008/04/28 20:22:58 martin Exp $      */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(sigaction, \
+    "warning: reference to compatibility sigaction(); include <signal.h> for correct reference")
+
+PSEUDO(sigaction,compat_13_sigaction13)
diff --git a/lib/nbsd_libc/compat/arch/m68k/sys/compat_sigpending.S b/lib/nbsd_libc/compat/arch/m68k/sys/compat_sigpending.S
new file mode 100644 (file)
index 0000000..4202f3a
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: compat_sigpending.S,v 1.1 2006/03/09 16:20:55 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)sigpending.s   5.2 (Berkeley) 8/6/90")
+#else
+       RCSID("$NetBSD: compat_sigpending.S,v 1.1 2006/03/09 16:20:55 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+WARN_REFERENCES(sigpending, \
+    "warning: reference to compatibility sigpending(); include <signal.h> for correct reference")
+
+_SYSCALL(sigpending,compat_13_sigpending13)
+       movl    %sp@(4),%a0
+       movl    %d0,%a0@
+       clrl    %d0
+       rts
diff --git a/lib/nbsd_libc/compat/arch/m68k/sys/compat_sigprocmask.S b/lib/nbsd_libc/compat/arch/m68k/sys/compat_sigprocmask.S
new file mode 100644 (file)
index 0000000..485ae33
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: compat_sigprocmask.S,v 1.1 2006/03/09 16:20:55 christos Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)sigprocmask.s  5.2 (Berkeley) 6/6/90")
+#else
+       RCSID("$NetBSD: compat_sigprocmask.S,v 1.1 2006/03/09 16:20:55 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+WARN_REFERENCES(sigprocmask, \
+    "warning: reference to compatibility sigprocmask(); include <signal.h> for correct reference")
+
+ENTRY(sigprocmask)
+       tstl    %sp@(8)                 /* check new sigset pointer */
+       jne     gotptr                  /* if not null, indirect */
+/*     movl    #0,%sp@(8)              /* null mask pointer: block empty set */
+       movl    #1,%sp@(4)              /* SIG_BLOCK */
+       jra     doit
+gotptr:
+       movl    %sp@(8),%a0
+       movl    %a0@,%sp@(8)            /* indirect to new mask arg */
+doit:
+       movl    #SYS_compat_13_sigprocmask13,%d0
+       trap    #0
+       jcs     err
+       tstl    %sp@(12)                /* test if old mask requested */
+       jeq     out
+       movl    %sp@(12),%a0
+       movl    %d0,%a0@                /* store old mask */
+out:
+       clrl    %d0
+       rts
+err:
+       jra     PIC_PLT(CERROR)
diff --git a/lib/nbsd_libc/compat/arch/m68k/sys/compat_sigreturn.S b/lib/nbsd_libc/compat/arch/m68k/sys/compat_sigreturn.S
new file mode 100644 (file)
index 0000000..33357ed
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: compat_sigreturn.S,v 1.1 2006/03/09 16:20:55 christos Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)sigreturn.s    5.1 (Berkeley) 5/12/90")
+#else
+       RCSID("$NetBSD: compat_sigreturn.S,v 1.1 2006/03/09 16:20:55 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ */
+#ifdef GPROF
+#undef ENTRY
+#ifdef __STDC__
+#define        ENTRY(x) \
+       .globl _C_LABEL(x); .even; _C_LABEL(x):; moveml #0xC0C0,%sp@-; .data; \
+       PROF ## x:; .long 0; .text; lea PROF ## x,%a0; jbsr MCOUNT_ENTRY; \
+       moveml %sp@+,#0x0303
+#else
+#define        ENTRY(x) \
+       .globl _C_LABEL(x); .even; _C_LABEL(x):; moveml #0xC0C0,%sp@-; .data; \
+       PROF/**/x:; .long 0; .text; lea PROF/**/x,%a0; jbsr MCOUNT_ENTRY; \
+       moveml %sp@+,#0x0303
+#endif /* __STDC__ */
+#endif /* GPROF */
+
+WARN_REFERENCES(sigreturn, \
+    "warning: reference to compatibility sigreturn()")
+
+/*
+ * NOTE: Trap #1 is used for compat_13_sigreturn13 on the m68k!
+ */
+ENTRY(sigreturn)
+       trap    #1              /* signals compat_13_sigreturn13() */
+       jra     PIC_PLT(CERROR)
diff --git a/lib/nbsd_libc/compat/arch/m68k/sys/compat_sigsuspend.S b/lib/nbsd_libc/compat/arch/m68k/sys/compat_sigsuspend.S
new file mode 100644 (file)
index 0000000..af7c3ed
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: compat_sigsuspend.S,v 1.1 2006/03/09 16:20:55 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * the Systems Programming Group of the University of Utah Computer
+ * Science Department.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)sigsuspend.s   5.2 (Berkeley) 6/6/90")
+#else
+       RCSID("$NetBSD: compat_sigsuspend.S,v 1.1 2006/03/09 16:20:55 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+WARN_REFERENCES(sigsuspend, \
+    "warning: reference to compatibility sigsuspend(); include <signal.h> for correct reference")
+
+ENTRY(sigsuspend)
+       movl    %sp@(4),%a0
+       movl    %a0@,%sp@(4)            /* indirect to mask arg */
+       movl    #SYS_compat_13_sigsuspend13,%d0
+       trap    #0
+       jcs     err
+       clrl    %d0                     /* shouldn't happen */
+       rts
+err:
+       jra     PIC_PLT(CERROR)
diff --git a/lib/nbsd_libc/compat/arch/mips/Makefile.inc b/lib/nbsd_libc/compat/arch/mips/Makefile.inc
new file mode 100644 (file)
index 0000000..78ab575
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/03/11 23:04:03 christos Exp $
+
+.include "${COMPATARCHDIR}/gen/Makefile.inc"
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/mips/gen/Makefile.inc b/lib/nbsd_libc/compat/arch/mips/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..3aa7a90
--- /dev/null
@@ -0,0 +1,8 @@
+#      $NetBSD: Makefile.inc,v 1.3 2006/07/03 12:58:55 drochner Exp $
+
+# objects built from assembler sources (need lint stubs)
+SRCS+= compat_setjmp.S compat_sigsetjmp.S
+
+# objects built from C sources in compat/gen
+SRCS+= compat_frexp_ieee754.c
+#SRCS+=        compat_ldexp_ieee754.c compat_modf_ieee754.c
diff --git a/lib/nbsd_libc/compat/arch/mips/gen/compat_setjmp.S b/lib/nbsd_libc/compat/arch/mips/gen/compat_setjmp.S
new file mode 100644 (file)
index 0000000..a3028f7
--- /dev/null
@@ -0,0 +1,162 @@
+/*     $NetBSD: compat_setjmp.S,v 1.2 2009/12/14 03:04:33 matt Exp $   */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include <sys/syscall.h>
+#include <mips/asm.h>
+
+#include "assym.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)setjmp.s       8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: compat_setjmp.S,v 1.2 2009/12/14 03:04:33 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and a struct sigcontext, see <signal.h>
+ */
+
+#define SETJMP_FRAME_SIZE      (CALLFRAME_SIZ + STACK_T_SIZE)
+
+NON_LEAF(setjmp, SETJMP_FRAME_SIZE, ra)
+       .mask   0x80010000, (CALLFRAME_RA - CALLFRAME_SIZ)
+       SETUP_GP
+       PTR_SUBU        sp, sp, SETJMP_FRAME_SIZE       # allocate stack frame
+       SAVE_GP(CALLFRAME_GP)
+       SETUP_GP64(CALLFRAME_GP, setjmp)
+
+       REG_S           ra, CALLFRAME_RA(sp)            # save RA
+       REG_S           s0, CALLFRAME_S0(sp)            # save S0
+       move            s0, a0                          # save sigcontext
+
+       /* Get the signal mask. */
+       move            a0, zero                        # get current sigmask
+       jal             _C_LABEL(sigblock)
+       nop
+       INT_S           v0, _OFFSETOF_SC_MASK13(s0)     # save sc_mask13
+
+       /* Get the signal stack. */
+       move            a0, zero
+       PTR_ADDU        a1, sp, CALLFRAME_SIZ           # pointer to stack_t
+       jal             _C_LABEL(__sigaltstack14)
+
+       move            a0, s0                          # restore jmpbuf
+       INT_L           v1, CALLFRAME_SIZ+_OFFSETOF_STACK_T_FLAGS(sp)
+                                                       # get old ss_onstack
+       and             v1, v1, SS_ONSTACK              # extract onstack flag
+       INT_S           v1, _OFFSETOF_SC_ONSTACK(a0)    # save it in sc_onstack
+
+       REG_L           s0, CALLFRAME_S0(sp)            # restore S0
+       REG_L           ra, CALLFRAME_RA(sp)            # restore RA
+       blt             v0, zero, botch         # check for sigaltstack() error
+       nop
+       /*
+        * We know we won't need this routine's GP anymore.
+        */
+       RESTORE_GP64
+       PTR_ADDU        sp, sp, SETJMP_FRAME_SIZE       # pop stack frame
+
+       REG_PROLOGUE
+       REG_S   ra, _OFFSETOF_SC_PC(a0)         # sc_pc = return address
+       REG_LI  v0, 0xACEDBADE                  # sigcontext magic number
+       REG_S   v0, _OFFSETOF_SC_REGS(a0)       #   saved in sc_regs[0]
+       REG_S   s0, _OFFSETOF_SC_REGS_S0(a0)
+       REG_S   s1, _OFFSETOF_SC_REGS_S1(a0)
+       REG_S   s2, _OFFSETOF_SC_REGS_S2(a0)
+       REG_S   s3, _OFFSETOF_SC_REGS_S3(a0)
+       REG_S   s4, _OFFSETOF_SC_REGS_S4(a0)
+       REG_S   s5, _OFFSETOF_SC_REGS_S5(a0)
+       REG_S   s6, _OFFSETOF_SC_REGS_S6(a0)
+       REG_S   s7, _OFFSETOF_SC_REGS_S7(a0)
+       REG_S   gp, _OFFSETOF_SC_REGS_GP(a0)
+       REG_S   sp, _OFFSETOF_SC_REGS_SP(a0)
+       REG_S   s8, _OFFSETOF_SC_REGS_S8(a0)
+       li      v0, 1                           # be nice if we could tell
+       INT_S   v0, _OFFSETOF_SC_FPUSED(a0)     # sc_fpused = 1
+       cfc1    v0, $31
+       INT_S   v0, _OFFSETOF_SC_FPREGS_FCSR(a0)
+#if defined(__mips_o32) || defined(__mips_o64) || defined(__mips_n32)
+       FP_S    $f20, _OFFSETOF_SC_FPREGS_F20(a0)
+       FP_S    $f22, _OFFSETOF_SC_FPREGS_F22(a0)
+#endif
+#if defined(__mips_o32) || defined(__mips_o64)
+       FP_S    $f21, _OFFSETOF_SC_FPREGS_F21(a0)
+       FP_S    $f23, _OFFSETOF_SC_FPREGS_F23(a0)
+#endif
+#if defined(__mips_n32) || defined(__mips_n64)
+       FP_S    $f24, _OFFSETOF_SC_FPREGS_F24(a0)
+       FP_S    $f26, _OFFSETOF_SC_FPREGS_F26(a0)
+       FP_S    $f28, _OFFSETOF_SC_FPREGS_F28(a0)
+       FP_S    $f30, _OFFSETOF_SC_FPREGS_F30(a0)
+#endif
+#if defined(__mips_n64)
+       FP_S    $f25, _OFFSETOF_SC_FPREGS_F25(a0)
+       FP_S    $f27, _OFFSETOF_SC_FPREGS_F27(a0)
+       FP_S    $f29, _OFFSETOF_SC_FPREGS_F29(a0)
+       FP_S    $f31, _OFFSETOF_SC_FPREGS_F31(a0)
+#endif
+       REG_EPILOGUE
+       j       ra
+       move    v0, zero
+
+botch:
+       jal     _C_LABEL(abort)
+END(setjmp)
+
+LEAF(longjmp)
+       SETUP_GP
+       PTR_SUBU        sp, sp, CALLFRAME_SIZ
+       SAVE_GP(CALLFRAME_S0)
+       SETUP_GP64(s0, longjmp)
+
+       REG_PROLOGUE
+       /* save return value in sc_regs[_R_V0] */
+       REG_S           a1, _OFFSETOF_SC_REGS_V0(a0)
+       REG_EPILOGUE
+
+       li              v0, SYS_compat_13_sigreturn13
+       syscall
+
+       jal             _C_LABEL(longjmperror)
+       jal             _C_LABEL(abort)
+END(longjmp)
diff --git a/lib/nbsd_libc/compat/arch/mips/gen/compat_sigsetjmp.S b/lib/nbsd_libc/compat/arch/mips/gen/compat_sigsetjmp.S
new file mode 100644 (file)
index 0000000..e7c8b96
--- /dev/null
@@ -0,0 +1,83 @@
+/*     $NetBSD: compat_sigsetjmp.S,v 1.2 2009/12/14 03:04:33 matt Exp $        */
+
+/*-
+ * Copyright (c) 1991, 1993, 1995,
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Havard Eidnes.
+ *
+ * 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. 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.
+ */
+
+#include <sys/syscall.h>
+#include <mips/asm.h>
+#include <mips/regdef.h>
+
+#include "assym.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       ASMSTR("from: @(#)setjmp.s      8.1 (Berkeley) 6/4/93")
+#else
+       ASMSTR("$NetBSD: compat_sigsetjmp.S,v 1.2 2009/12/14 03:04:33 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- sigsetjmp, siglongjmp
+ *
+ *     siglongjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     sigsetjmp(a, savemask)
+ * by restoring registers from the stack,
+ * and dependent on savemask restores the
+ * signal mask.
+ */
+
+LEAF(sigsetjmp)
+       SETUP_GP
+       SETUP_GP64(t0, sigsetjmp)
+       INT_S   a1, _OFFSETOF_SC_MASK13(a0)     # save "savemask"
+       bne     a1, 0x0, 1f                     # do saving of signal mask?
+       PTR_LA  t9, _C_LABEL(_setjmp)
+       jr      t9
+
+1:     PTR_LA  t9, _C_LABEL(setjmp)
+       jr      t9
+END(sigsetjmp)
+
+LEAF(siglongjmp)
+       SETUP_GP
+       SETUP_GP64(t0, siglongjmp)
+       INT_L   t1, _OFFSETOF_SC_MASK13(a0)     # get "savemask"
+       bne     t1, 0x0, 1f                     # restore signal mask?
+       PTR_LA  t9, _C_LABEL(_longjmp)
+       jr      t9
+
+1:     PTR_LA  t9, _C_LABEL(longjmp)
+       jr      t9
+END(siglongjmp)
diff --git a/lib/nbsd_libc/compat/arch/mips/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/mips/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..73e76cc
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.1 2005/09/17 11:49:39 tsutsui Exp $
+
+SRCS+=compat_Ovfork.S compat___semctl.S compat___sigreturn14.S \
+    compat___sigtramp1.S compat_msgctl.S compat_shmctl.S compat_sigaction.S \
+    compat_sigpending.S compat_sigprocmask.S compat_sigreturn.S \
+    compat_sigsuspend.S 
diff --git a/lib/nbsd_libc/compat/arch/mips/sys/compat_Ovfork.S b/lib/nbsd_libc/compat/arch/mips/sys/compat_Ovfork.S
new file mode 100644 (file)
index 0000000..758f9ac
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: compat_Ovfork.S,v 1.2 2009/12/14 03:04:33 matt Exp $   */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)Ovfork.s       8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: compat_Ovfork.S,v 1.2 2009/12/14 03:04:33 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+WARN_REFERENCES(vfork, \
+    "warning: reference to compatibility vfork(); include <unistd.h> for correct reference")
+
+/*
+ * pid = vfork();
+ *
+ * v1 == 0 in parent process, v1 == 1 in child process.
+ * v0 == pid of child in parent, v0 == pid of parent in child.
+ */
+
+LEAF(vfork)
+       PIC_PROLOGUE(vfork)
+
+       SYSTRAP(vfork)                  # system call number for vfork
+       beq     a3, zero, 1f            # jump if no errors
+
+       PIC_TAILCALL(__cerror)
+
+1:
+       beq     v1, zero, 2f            # parent process ?
+       move    v0, zero                # return zero in child
+2:
+       PIC_RETURN()
+END(vfork)
diff --git a/lib/nbsd_libc/compat/arch/mips/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/mips/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..53f21ef
--- /dev/null
@@ -0,0 +1,39 @@
+/*     $NetBSD: compat___semctl.S,v 1.4 2009/12/14 03:04:33 matt Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat___semctl.S,v 1.4 2009/12/14 03:04:33 matt Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/mips/sys/compat___sigreturn14.S b/lib/nbsd_libc/compat/arch/mips/sys/compat___sigreturn14.S
new file mode 100644 (file)
index 0000000..b2536af
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: compat___sigreturn14.S,v 1.2 2009/12/14 03:04:33 matt Exp $    */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)sigreturn.s    8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: compat___sigreturn14.S,v 1.2 2009/12/14 03:04:33 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ */
+
+PSEUDO(__sigreturn14,compat_16___sigreturn14)
diff --git a/lib/nbsd_libc/compat/arch/mips/sys/compat___sigtramp1.S b/lib/nbsd_libc/compat/arch/mips/sys/compat___sigtramp1.S
new file mode 100644 (file)
index 0000000..71680d0
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: compat___sigtramp1.S,v 1.4 2009/12/14 03:04:33 matt Exp $      */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat___sigtramp1.S,v 1.4 2009/12/14 03:04:33 matt Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * The MIPS signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ *
+ * On entry, stack looks like:
+ *
+ *     sp->    sigcontext structure
+ */
+LEAF_NOPROFILE(__sigtramp_sigcontext_1)
+       move    a0, sp                  /* address of sigcontext */
+       SYSTRAP(compat_16___sigreturn14) /* and do sigreturn */
+       move    a0, v0                  /* exit with errno */
+       SYSTRAP(exit)                   /* if sigreturn fails */
+END(__sigtramp_sigcontext_1)
diff --git a/lib/nbsd_libc/compat/arch/mips/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/mips/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..5457c6c
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: compat_msgctl.S,v 1.3 2009/12/14 01:07:42 matt Exp $   */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_msgctl.S,v 1.3 2009/12/14 01:07:42 matt Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/mips/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/mips/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..57c8421
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: compat_shmctl.S,v 1.3 2009/12/14 01:07:42 matt Exp $   */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_shmctl.S,v 1.3 2009/12/14 01:07:42 matt Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/mips/sys/compat_sigaction.S b/lib/nbsd_libc/compat/arch/mips/sys/compat_sigaction.S
new file mode 100644 (file)
index 0000000..b2506ac
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: compat_sigaction.S,v 1.3 2009/12/14 01:07:42 matt Exp $        */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigaction.S,v 1.3 2009/12/14 01:07:42 matt Exp $")
+#endif /* LIBC_SCCS and not lint */
+
+WARN_REFERENCES(sigaction, \
+    "warning: reference to compatibility sigaction(); include <signal.h> for correct reference")
+
+PSEUDO(sigaction,compat_13_sigaction13)
diff --git a/lib/nbsd_libc/compat/arch/mips/sys/compat_sigpending.S b/lib/nbsd_libc/compat/arch/mips/sys/compat_sigpending.S
new file mode 100644 (file)
index 0000000..93c99e8
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: compat_sigpending.S,v 1.2 2009/12/14 03:04:33 matt Exp $       */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+#include "assym.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)sigpending.s   8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: compat_sigpending.S,v 1.2 2009/12/14 03:04:33 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+WARN_REFERENCES(sigpending, \
+    "warning: reference to compatibility sigpending(); include <signal.h> for correct reference")
+
+LEAF(sigpending)
+       PIC_PROLOGUE(sigpending)
+
+       SYSTRAP(compat_13_sigpending13)
+       bne     a3, zero, 1f
+       INT_S   v0, _OFFSETOF_SC_ONSTACK(a0)
+       move    v0, zero
+       PIC_RETURN()
+
+1:
+       PIC_TAILCALL(__cerror)
+END(sigpending)
diff --git a/lib/nbsd_libc/compat/arch/mips/sys/compat_sigprocmask.S b/lib/nbsd_libc/compat/arch/mips/sys/compat_sigprocmask.S
new file mode 100644 (file)
index 0000000..913a139
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: compat_sigprocmask.S,v 1.2 2009/12/14 03:04:33 matt Exp $      */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)sigprocmask.s  8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: compat_sigprocmask.S,v 1.2 2009/12/14 03:04:33 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+WARN_REFERENCES(sigprocmask, \
+    "warning: reference to compatibility sigprocmask(); include <signal.h> for correct reference")
+
+LEAF(sigprocmask)      # sigprocmask(how, new, old) sigset_t *new, *old;
+       PIC_PROLOGUE(sigprocmask)
+       bne     a1, zero, gotptr        # if new sigset pointer not null
+       li      a0, 1                   # how = SIG_BLOCK
+       b       doit                    # mask = zero
+gotptr:
+       INT_L   a1, 0(a1)               # indirect to new mask arg
+doit:
+       SYSTRAP(compat_13_sigprocmask13)
+
+       bne     a3, zero, err
+       beq     a2, zero, out           # test if old mask requested
+       INT_S   v0, 0(a2)               # store old mask
+out:
+       move    v0, zero
+       PIC_RETURN()
+err:
+       PIC_TAILCALL(__cerror)
+END(sigprocmask)
diff --git a/lib/nbsd_libc/compat/arch/mips/sys/compat_sigreturn.S b/lib/nbsd_libc/compat/arch/mips/sys/compat_sigreturn.S
new file mode 100644 (file)
index 0000000..ac5df9d
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: compat_sigreturn.S,v 1.2 2009/12/14 03:04:33 matt Exp $        */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)sigreturn.s    8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: compat_sigreturn.S,v 1.2 2009/12/14 03:04:33 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ */
+
+WARN_REFERENCES(sigreturn, \
+    "warning: reference to compatibility sigreturn()")
+
+PSEUDO(sigreturn,compat_13_sigreturn13)
diff --git a/lib/nbsd_libc/compat/arch/mips/sys/compat_sigsuspend.S b/lib/nbsd_libc/compat/arch/mips/sys/compat_sigsuspend.S
new file mode 100644 (file)
index 0000000..8c7b7c5
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: compat_sigsuspend.S,v 1.2 2009/12/14 03:04:33 matt Exp $       */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Ralph Campbell.
+ *
+ * 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. 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.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       RCSID("from: @(#)sigsuspend.s   8.1 (Berkeley) 6/4/93")
+#else
+       RCSID("$NetBSD: compat_sigsuspend.S,v 1.2 2009/12/14 03:04:33 matt Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+WARN_REFERENCES(sigsuspend, \
+    "warning: reference to compatibility sigsuspend(); include <signal.h> for correct reference")
+
+LEAF(sigsuspend)
+       PIC_PROLOGUE(sigsuspend)
+
+       INT_L   a0, 0(a0)               # indirect to mask arg
+       SYSTRAP(compat_13_sigsuspend13)
+       bne     a3, zero, 1f
+       move    v0, zero                # should not happen
+       PIC_RETURN()
+1:
+       PIC_TAILCALL(__cerror)
+END(sigsuspend)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/Makefile.inc b/lib/nbsd_libc/compat/arch/powerpc/Makefile.inc
new file mode 100644 (file)
index 0000000..2f234ec
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.3 2011/01/15 07:31:13 matt Exp $
+
+.include "${COMPATARCHDIR}/gen/Makefile.inc"
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
+
+CPPFLAGS+=     -I.
diff --git a/lib/nbsd_libc/compat/arch/powerpc/gen/Makefile.inc b/lib/nbsd_libc/compat/arch/powerpc/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..0018c2b
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.3 2006/06/28 14:46:33 drochner Exp $
+
+# objects built from assembler sources (need lint stubs)
+SRCS+= compat_setjmp.S compat_sigsetjmp.S
+
+# objects built from C sources in compat/gen
+SRCS+= compat_frexp_ieee754.c compat_ldexp_ieee754.c compat_modf_ieee754.c
diff --git a/lib/nbsd_libc/compat/arch/powerpc/gen/compat_setjmp.S b/lib/nbsd_libc/compat/arch/powerpc/gen/compat_setjmp.S
new file mode 100644 (file)
index 0000000..49d9283
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: compat_setjmp.S,v 1.2 2011/01/15 07:31:13 matt Exp $   */
+
+#include "SYS.h"
+#include "assym.h"
+
+#if defined(LIBC_SCCS)
+__RCSID("$NetBSD: compat_setjmp.S,v 1.2 2011/01/15 07:31:13 matt Exp $")
+#endif
+
+/*
+ * C library -- _setjmp, _longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v?v:1)" from the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(setjmp)
+       mr      %r6,%r3
+       li      %r3,SIG_BLOCK
+       li      %r4,0
+       _DOSYSCALL(compat_13_sigprocmask13) # assume no error   XXX
+       mflr    %r11
+       mfcr    %r12
+       mr      %r10,%r1
+       mr      %r9,%r2
+       mr      %r8,%r3
+       stmw    %r8,4(%r6)
+       li      %r3,0
+       blr
+END(setjmp)
+
+ENTRY(longjmp)
+       lmw     %r8,4(%r3)
+       mr      %r6,%r4
+       mtlr    %r11
+       mtcr    %r12
+       mr      %r2,%r9
+       mr      %r1,%r10
+       mr      %r4,%r8
+       li      %r3,SIG_SETMASK
+       _DOSYSCALL(compat_13_sigprocmask13) # assume no error   XXX
+       or.     %r3,%r6,%r6
+       bnelr
+       li      %r3,1
+       blr
+END(longjmp)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/gen/compat_sigsetjmp.S b/lib/nbsd_libc/compat/arch/powerpc/gen/compat_sigsetjmp.S
new file mode 100644 (file)
index 0000000..9ebe269
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: compat_sigsetjmp.S,v 1.2 2011/01/15 07:31:13 matt Exp $        */
+
+#include "SYS.h"
+#include "assym.h"
+
+#if defined(LIBC_SCCS)
+__RCSID("$NetBSD: compat_sigsetjmp.S,v 1.2 2011/01/15 07:31:13 matt Exp $")
+#endif
+
+ENTRY(sigsetjmp)
+       mr      %r6,%r3
+       or.     %r7,%r4,%r4
+       beq     1f
+       li      %r3,SIG_BLOCK
+       li      %r4,0
+       _DOSYSCALL(compat_13_sigprocmask13) # assume no error   XXX
+1:
+       mflr    %r11
+       mfcr    %r12
+       mr      %r10,%r1
+       mr      %r9,%r2
+       mr      %r8,%r3
+       stmw    %r7,0(%r6)
+       li      %r3,0
+       blr
+END(sigsetjmp)
+
+ENTRY(siglongjmp)
+       lmw     %r7,0(%r3)
+       mr      %r6,%r4
+       mtlr    %r11
+       mtcr    %r12
+       mr      %r2,%r9
+       mr      %r1,%r10
+       or.     %r7,%r7,%r7
+       beq     1f
+       mr      %r4,%r8
+       li      %r3,SIG_SETMASK
+       _DOSYSCALL(compat_13_sigprocmask13) # assume no error   XXX
+1:
+       or.     %r3,%r6,%r6
+       bnelr
+       li      %r3,1
+       blr
+END(siglongjmp)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/powerpc/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..425cfc4
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/02/18 00:21:28 matt Exp $
+
+SRCS+= compat_Ovfork.S \
+       compat___sigreturn14.S compat___sigtramp1.S \
+       compat_msgctl.S compat___semctl.S compat_shmctl.S \
+       compat_sigaction13.S compat_sigpending13.S compat_sigprocmask13.S \
+       compat_sigreturn13.S compat_sigsuspend13.S 
diff --git a/lib/nbsd_libc/compat/arch/powerpc/sys/compat_Ovfork.S b/lib/nbsd_libc/compat/arch/powerpc/sys/compat_Ovfork.S
new file mode 100644 (file)
index 0000000..4c39ceb
--- /dev/null
@@ -0,0 +1,23 @@
+/*     $NetBSD: compat_Ovfork.S,v 1.2 2011/01/15 07:31:13 matt Exp $   */
+
+/*
+ * pid = vfork();
+ *
+ * r4 == 0 in parent process, 1 in child process.
+ * r3 == pid of child in parent, pid of parent in child.
+ */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS)
+__RCSID("$NetBSD: compat_Ovfork.S,v 1.2 2011/01/15 07:31:13 matt Exp $")
+#endif
+
+WARN_REFERENCES(vfork, \
+    "warning: reference to compatibility vfork(); include <unistd.h> for correct reference")
+
+SYSCALL(vfork)
+       addi    %r4,%r4,-1      # from 1 to 0 in child, 0 to -1 in parent
+       and     %r3,%r3,%r4     # return 0 in child, pid in parent
+       blr
+END(vfork)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/powerpc/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..8050310
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/sys/compat___sigreturn14.S b/lib/nbsd_libc/compat/arch/powerpc/sys/compat___sigreturn14.S
new file mode 100644 (file)
index 0000000..b075c31
--- /dev/null
@@ -0,0 +1,5 @@
+/*     $NetBSD: compat___sigreturn14.S,v 1.1 2006/02/18 00:21:28 matt Exp $    */
+
+#include "SYS.h"
+
+PSEUDO(__sigreturn14,compat_16___sigreturn14)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/sys/compat___sigtramp1.S b/lib/nbsd_libc/compat/arch/powerpc/sys/compat___sigtramp1.S
new file mode 100644 (file)
index 0000000..ff6e30a
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: compat___sigtramp1.S,v 1.3 2011/01/15 07:31:13 matt Exp $      */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+#include "assym.h"
+
+#if defined(LIBC_SCCS)
+__RCSID("$NetBSD: compat___sigtramp1.S,v 1.3 2011/01/15 07:31:13 matt Exp $")
+#endif
+
+/*
+ * On entry, stack and registers look like:
+ *
+ *     r3      signal number
+ *     r4      signal specific code
+ *     r5      pointer to sigcontext structure
+ *     lr      address of handler
+ *
+ *     sp->    sigcontext structure
+ */
+ENTRY_NOPROFILE(__sigtramp_sigcontext_1)
+       addi    %r1,%r1,-CALLFRAMELEN   /* space for callee */
+       blrl                            /* call handler */
+       addi    %r3,%r1,CALLFRAMELEN    /* compute address of sigcontext */
+       _DOSYSCALL(compat_16___sigreturn14)     /* and call sigreturn */
+       _DOSYSCALL(exit)                /* or exit with errno if failed */
+END(__sigtramp_sigcontext_1)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/powerpc/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..26ccc3c
--- /dev/null
@@ -0,0 +1,8 @@
+/*     $NetBSD: compat_msgctl.S,v 1.1 2006/02/18 00:21:28 matt Exp $   */
+
+#include "SYS.h"
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/powerpc/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..10d43f7
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_shmctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigaction13.S b/lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigaction13.S
new file mode 100644 (file)
index 0000000..42c5ed6
--- /dev/null
@@ -0,0 +1,8 @@
+/*     $NetBSD: compat_sigaction13.S,v 1.1 2006/02/18 00:21:28 matt Exp $      */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigaction, \
+    "warning: reference to compatibility sigaction(); include <signal.h> for correct reference")
+
+PSEUDO(sigaction,compat_13_sigaction13)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigpending13.S b/lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigpending13.S
new file mode 100644 (file)
index 0000000..27867cc
--- /dev/null
@@ -0,0 +1,21 @@
+/*     $NetBSD: compat_sigpending13.S,v 1.3 2011/01/16 02:45:48 matt Exp $     */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS)
+__RCSID("$NetBSD: compat_sigpending13.S,v 1.3 2011/01/16 02:45:48 matt Exp $")
+#endif
+
+WARN_REFERENCES(sigpending, \
+    "warning: reference to compatibility sigpending(); include <signal.h> for correct reference")
+
+ENTRY(sigpending)
+       mr      %r5,%r3                         # save pointer
+       _DOSYSCALL(compat_13_sigpending13)      # sigpending()
+       bso     1f
+       stw     %r3,0(%r5)                      # store return value
+       li      %r3,0                           # and return 0
+       blr
+1:
+       b       _C_LABEL(__cerror)
+END(sigpending)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigprocmask13.S b/lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigprocmask13.S
new file mode 100644 (file)
index 0000000..08ee8bf
--- /dev/null
@@ -0,0 +1,34 @@
+/*     $NetBSD: compat_sigprocmask13.S,v 1.2 2011/01/15 07:31:13 matt Exp $    */
+
+#include "SYS.h"
+#include "assym.h"
+
+#if defined(LIBC_SCCS)
+__RCSID("$NetBSD: compat_sigprocmask13.S,v 1.2 2011/01/15 07:31:13 matt Exp $")
+#endif
+
+WARN_REFERENCES(sigprocmask, \
+    "warning: reference to compatibility sigprocmask(); include <signal.h> for correct reference")
+
+/*
+ * sigprocmask(int how, sigset_t *set, sigset_t *oset)
+ */
+ENTRY(sigprocmask)
+       or.     %r4,%r4,%r4     # set == NULL?
+       li      %r6,SIG_BLOCK
+       beq     1f
+       lwz     %r4,0(%r4)      # if not, replace it in r4 with *set
+       mr      %r6,%r3
+1:
+       mr      %r3,%r6         # ... using sigprocmask(SIG_BLOCK)
+       _DOSYSCALL(compat_13_sigprocmask13)
+       bso     3f
+       or.     %r5,%r5,%r5     # check to see of oset requested
+       beq     2f              # if oset != NULL,
+       stw     %r3,0(%r5)      #    *oset = oldmask
+2:
+       li      %r3,0
+       blr                     # in any case, return 0
+3:
+       b       _C_LABEL(__cerror)
+END(sigprocmask)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigreturn13.S b/lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigreturn13.S
new file mode 100644 (file)
index 0000000..0c50209
--- /dev/null
@@ -0,0 +1,8 @@
+/*     $NetBSD: compat_sigreturn13.S,v 1.1 2006/02/18 00:21:28 matt Exp $      */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigreturn, \
+    "warning: reference to compatibility sigreturn()")
+
+PSEUDO(sigreturn,compat_13_sigreturn13)
diff --git a/lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigsuspend13.S b/lib/nbsd_libc/compat/arch/powerpc/sys/compat_sigsuspend13.S
new file mode 100644 (file)
index 0000000..fa0374a
--- /dev/null
@@ -0,0 +1,16 @@
+/*     $NetBSD: compat_sigsuspend13.S,v 1.2 2011/01/15 07:31:13 matt Exp $     */
+
+#include "SYS.h"
+
+#if defined(LIBC_SCCS)
+__RCSID("$NetBSD: compat_sigsuspend13.S,v 1.2 2011/01/15 07:31:13 matt Exp $")
+#endif
+
+WARN_REFERENCES(sigsuspend, \
+    "warning: reference to compatibility sigsuspend(); include <signal.h> for correct reference")
+
+ENTRY(sigsuspend)
+       lwz     %r3,0(%r3)                      # indirect to mask arg
+       _DOSYSCALL(compat_13_sigsuspend13)
+       b       _C_LABEL(__cerror)              # always terminates with EINTR
+END(sigsuspend)
diff --git a/lib/nbsd_libc/compat/arch/powerpc64/Makefile.inc b/lib/nbsd_libc/compat/arch/powerpc64/Makefile.inc
new file mode 100644 (file)
index 0000000..edf1a86
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/07/01 19:14:49 ross Exp $
+
+.include "${COMPATARCHDIR}/gen/Makefile.inc"
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/powerpc64/gen/Makefile.inc b/lib/nbsd_libc/compat/arch/powerpc64/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..91d77fb
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/07/01 19:17:32 ross Exp $
+
+# objects built from assembler sources (need lint stubs)
+SRCS+= 
+
+# objects built from C sources in compat/gen
+SRCS+=
diff --git a/lib/nbsd_libc/compat/arch/powerpc64/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/powerpc64/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..2b441c4
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/07/07 06:59:04 ross Exp $
+
+SRCS+= compat_msgctl.S compat___semctl.S compat_shmctl.S
diff --git a/lib/nbsd_libc/compat/arch/powerpc64/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/powerpc64/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..8050310
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/powerpc64/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/powerpc64/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..1e3309a
--- /dev/null
@@ -0,0 +1,8 @@
+/*     $NetBSD: compat_msgctl.S,v 1.1 2006/07/07 06:59:04 ross Exp $   */
+
+#include "SYS.h"
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/powerpc64/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/powerpc64/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..10d43f7
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_shmctl.S,v 1.2 2008/04/28 20:22:58 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/sh3/Makefile.inc b/lib/nbsd_libc/compat/arch/sh3/Makefile.inc
new file mode 100644 (file)
index 0000000..30de512
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.3 2006/03/11 23:04:04 christos Exp $
+
+.include "${COMPATARCHDIR}/gen/Makefile.inc"
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/sh3/gen/Makefile.inc b/lib/nbsd_libc/compat/arch/sh3/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..4faa8a2
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.3 2006/06/28 14:46:33 drochner Exp $
+
+SRCS+= compat_setjmp.S compat_sigsetjmp.S
+
+# objects built from C sources in compat/gen
+SRCS+= compat_frexp_ieee754.c compat_ldexp_ieee754.c compat_modf_ieee754.c
diff --git a/lib/nbsd_libc/compat/arch/sh3/gen/compat_setjmp.S b/lib/nbsd_libc/compat/arch/sh3/gen/compat_setjmp.S
new file mode 100644 (file)
index 0000000..ce296fd
--- /dev/null
@@ -0,0 +1,125 @@
+/*     $NetBSD: compat_setjmp.S,v 1.3 2006/01/05 19:21:37 uwe Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)setjmp.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#include <machine/setjmp.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: compat_setjmp.S,v 1.3 2006/01/05 19:21:37 uwe Exp $")
+#endif
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack.
+ * The previous signal state is restored.
+ */
+
+ENTRY(setjmp)
+       PIC_PROLOGUE(.L_got_1)
+       sts.l   pr, @-sp
+       mov.l   r4, @-sp
+
+       mov.l   .L_sigblock, r0
+1:     CALL    r0                      /* int mask = sigblock(0); */
+        mov    #0, r4
+
+       mov.l   @sp+, r4
+       lds.l   @sp+, pr
+       PIC_EPILOGUE
+
+       /* identical to _setjmp except that mask is present */
+       add     #((_JB_SIGMASK + 1) * 4), r4
+       mov.l   r0, @-r4                /* current mask returned by sigblock */
+       mov     #1, r0
+       mov.l   r0, @-r4                /* has signal mask */
+       mov.l   r15, @-r4
+       mov.l   r14, @-r4
+       mov.l   r13, @-r4
+       mov.l   r12, @-r4
+       mov.l   r11, @-r4
+       mov.l   r10, @-r4
+       mov.l   r9, @-r4
+       mov.l   r8, @-r4
+       sts.l   pr, @-r4
+       rts
+        xor    r0, r0
+
+       .align  2
+.L_got_1:      PIC_GOT_DATUM
+.L_sigblock:   CALL_DATUM(_C_LABEL(sigblock), 1b)
+       SET_ENTRY_SIZE(setjmp)
+
+
+ENTRY(longjmp)
+       /* we won't return here, so we don't need to save pr and r12 */
+       PIC_PROLOGUE_NOSAVE(.L_got_2)
+       mov.l   r5, @-sp
+       mov.l   r4, @-sp
+
+       mov.l   .L_sigsetmask, r0
+1:     CALL    r0                      /* sigsetmask(saved mask) */
+        mov.l  @(_JB_SIGMASK * 4, r4), r4
+
+       mov.l   @sp+, r4
+       mov.l   @sp+, r5
+
+       /* identical to _longjmp */
+       lds.l   @r4+, pr
+       mov.l   @r4+, r8
+       mov.l   @r4+, r9
+       mov.l   @r4+, r10
+       mov.l   @r4+, r11
+       mov.l   @r4+, r12
+       mov.l   @r4+, r13
+       mov.l   @r4+, r14
+       mov.l   @r4+, r15
+
+       mov     r5, r0
+       tst     r0, r0  /* make sure return value is non-zero */
+       bf      .L0
+       add     #1, r0
+.L0:
+       rts
+        nop
+
+       .align  2
+.L_got_2:      PIC_GOT_DATUM
+.L_sigsetmask: CALL_DATUM(_C_LABEL(sigsetmask), 1b)
+       SET_ENTRY_SIZE(longjmp)
diff --git a/lib/nbsd_libc/compat/arch/sh3/gen/compat_sigsetjmp.S b/lib/nbsd_libc/compat/arch/sh3/gen/compat_sigsetjmp.S
new file mode 100644 (file)
index 0000000..5260f7b
--- /dev/null
@@ -0,0 +1,122 @@
+/*     $NetBSD: compat_sigsetjmp.S,v 1.5 2006/01/05 19:21:37 uwe Exp $ */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)setjmp.s      5.1 (Berkeley) 4/23/90"
+ */
+
+#include <machine/asm.h>
+#include <machine/setjmp.h>
+
+#if defined(LIBC_SCCS)
+       RCSID("$NetBSD: compat_sigsetjmp.S,v 1.5 2006/01/05 19:21:37 uwe Exp $")
+#endif
+
+ENTRY(sigsetjmp)
+       tst     r5, r5
+       mov.l   r5, @(_JB_HAS_MASK * 4, r4)
+       bt      2f                      /* if (savemask == 0) */
+
+       PIC_PROLOGUE(.L_got_1)
+       sts.l   pr, @-sp
+       mov.l   r4, @-sp
+
+       mov.l   .L_sigblock, r0
+1:     CALL    r0                      /* int mask = sigblock(0); */
+        mov    #0, r4
+
+       mov.l   @sp+, r4
+       lds.l   @sp+, pr
+       PIC_EPILOGUE
+
+       mov.l   r0, @(_JB_SIGMASK * 4, r4)
+
+2:     /* identical to _setjmp sans mask */
+       add     #((_JB_REG_R15 + 1) * 4), r4
+       mov.l   r15, @-r4
+       mov.l   r14, @-r4
+       mov.l   r13, @-r4
+       mov.l   r12, @-r4
+       mov.l   r11, @-r4
+       mov.l   r10, @-r4
+       mov.l   r9, @-r4
+       mov.l   r8, @-r4
+       sts.l   pr, @-r4
+       rts
+        xor    r0, r0
+
+       .align  2
+.L_got_1:      PIC_GOT_DATUM
+.L_sigblock:   CALL_DATUM(_C_LABEL(sigblock), 1b)
+       SET_ENTRY_SIZE(sigsetjmp)
+
+
+ENTRY(siglongjmp)
+       mov.l   @(_JB_HAS_MASK * 4, r4), r0
+       tst     r0, r0
+       bt      2f                      /* if no mask */
+
+       /* we won't return here, so we don't need to save pr and r12 */
+       PIC_PROLOGUE_NOSAVE(.L_got_2)
+       mov.l   r5, @-sp
+       mov.l   r4, @-sp
+
+       mov.l   .L_sigsetmask, r0
+1:     CALL    r0                      /* sigsetmask(saved mask) */
+        mov.l  @(_JB_SIGMASK * 4, r4), r4
+
+       mov.l   @sp+, r4
+       mov.l   @sp+, r5
+
+2:     /* identical to _longjmp */
+       lds.l   @r4+, pr
+       mov.l   @r4+, r8
+       mov.l   @r4+, r9
+       mov.l   @r4+, r10
+       mov.l   @r4+, r11
+       mov.l   @r4+, r12
+       mov.l   @r4+, r13
+       mov.l   @r4+, r14
+       mov.l   @r4+, r15
+
+       mov     r5, r0
+       tst     r0, r0  /* make sure return value is non-zero */
+       bf      .L0
+       add     #1, r0
+.L0:
+       rts
+        nop
+
+       .align  2
+.L_got_2:      PIC_GOT_DATUM
+.L_sigsetmask: CALL_DATUM(_C_LABEL(sigsetmask), 1b)
+       SET_ENTRY_SIZE(siglongjmp)
diff --git a/lib/nbsd_libc/compat/arch/sh3/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/sh3/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..44f3740
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.1 2005/09/15 21:39:16 uwe Exp $
+
+SRCS+=compat_Ovfork.S compat___semctl.S compat___sigreturn14.S \
+    compat___sigtramp1.S compat_msgctl.S compat_shmctl.S compat_sigaction.S \
+    compat_sigpending.S compat_sigprocmask.S compat_sigreturn.S \
+    compat_sigsuspend.S 
diff --git a/lib/nbsd_libc/compat/arch/sh3/sys/compat_Ovfork.S b/lib/nbsd_libc/compat/arch/sh3/sys/compat_Ovfork.S
new file mode 100644 (file)
index 0000000..7ed4d04
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: compat_Ovfork.S,v 1.2 2006/01/06 04:30:33 uwe Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)Ovfork.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_Ovfork.S,v 1.2 2006/01/06 04:30:33 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(vfork, \
+    "warning: reference to compatibility vfork(); include <unistd.h> for correct reference")
+
+/*
+ * pid = vfork();
+ *
+ * r1 == 0 in parent process, r1 == 1 in child process.
+ * r0 == pid of child in parent, r0 == pid of parent in child.
+ *
+ */
+ENTRY(vfork)
+       mov     #SYS_vfork, r0
+       trapa   #0x80
+       bf      err
+
+       add     #0xff, r1       /* from 1 to 0 in child, 0 to -1 in parent */
+       rts
+        and    r1, r0          /* 0 in child, child pid in parent */
+
+err:
+       JUMP_CERROR
+
+       SET_ENTRY_SIZE(vfork)
diff --git a/lib/nbsd_libc/compat/arch/sh3/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/sh3/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..c64b6d3
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/sh3/sys/compat___sigreturn14.S b/lib/nbsd_libc/compat/arch/sh3/sys/compat___sigreturn14.S
new file mode 100644 (file)
index 0000000..b151804
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: compat___sigreturn14.S,v 1.1 2005/09/15 21:39:16 uwe Exp $     */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigreturn.s   5.2 (Berkeley) 12/17/90"
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat___sigreturn14.S,v 1.1 2005/09/15 21:39:16 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ */
+
+PSEUDO(__sigreturn14,compat_16___sigreturn14)
diff --git a/lib/nbsd_libc/compat/arch/sh3/sys/compat___sigtramp1.S b/lib/nbsd_libc/compat/arch/sh3/sys/compat___sigtramp1.S
new file mode 100644 (file)
index 0000000..671b5cc
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: compat___sigtramp1.S,v 1.2 2008/04/28 20:22:59 martin Exp $    */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+/*
+ * The SH signal trampoline is invoked only to return from
+ * the signal; the kernel calls the signal handler directly.
+ *
+ * On entry, stack looks like:
+ *
+ *     sp->    sigcontext structure
+ */
+NENTRY(__sigtramp_sigcontext_1)
+       mov     r15, r4                 /* get pointer to sigcontext */
+       SYSTRAP(compat_16___sigreturn14) /* and call sigreturn() */
+       mov     r0, r4                  /* exit with errno */
+       SYSTRAP(exit)                   /* if sigreturn fails */
diff --git a/lib/nbsd_libc/compat/arch/sh3/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/sh3/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..a5598b0
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_msgctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/sh3/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/sh3/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..a9f938c
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_shmctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/sh3/sys/compat_sigaction.S b/lib/nbsd_libc/compat/arch/sh3/sys/compat_sigaction.S
new file mode 100644 (file)
index 0000000..7d77843
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_sigaction.S,v 1.2 2008/04/28 20:22:59 martin Exp $      */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(sigaction, \
+    "warning: reference to compatibility sigaction(); include <signal.h> for correct reference")
+
+PSEUDO(sigaction,compat_13_sigaction13)
diff --git a/lib/nbsd_libc/compat/arch/sh3/sys/compat_sigpending.S b/lib/nbsd_libc/compat/arch/sh3/sys/compat_sigpending.S
new file mode 100644 (file)
index 0000000..39f2e62
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: compat_sigpending.S,v 1.2 2006/01/06 04:14:35 uwe Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigpending.s  5.1 (Berkeley) 7/1/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigpending.S,v 1.2 2006/01/06 04:14:35 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigpending, \
+    "warning: reference to compatibility sigpending(); include <signal.h> for correct reference")
+
+/*
+ * int
+ * sigpending(sigset_t *set);
+ */
+_SYSCALL(sigpending,compat_13_sigpending13)
+       mov.l   r0, @r4                 /* store returned mask */
+       rts
+        mov    #0, r0
diff --git a/lib/nbsd_libc/compat/arch/sh3/sys/compat_sigprocmask.S b/lib/nbsd_libc/compat/arch/sh3/sys/compat_sigprocmask.S
new file mode 100644 (file)
index 0000000..f67a414
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: compat_sigprocmask.S,v 1.3 2006/01/06 04:08:47 uwe Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigprocmask.s 5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigprocmask.S,v 1.3 2006/01/06 04:08:47 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigprocmask, \
+    "warning: reference to compatibility sigprocmask(); include <signal.h> for correct reference")
+
+/*
+ * int
+ * sigprocmask(int how, const sigset_t * restrict set,
+ *     sigset_t * restrict oset);
+ */
+ENTRY(sigprocmask)
+       tst     r5, r5                  /* set == NULL? */
+       bf      1f
+
+       bra     2f                      /* r5 (new mask) is already zero */
+        mov    #1, r4                  /* how = SIG_BLOCK */
+
+1:     mov.l   @r5, r5                 /* fetch new mask */
+
+2:     mov     #SYS_compat_13_sigprocmask13, r0
+       trapa   #0x80
+       bf      err
+
+       tst     r6, r6                  /* oset == NULL? */
+       bt      3f
+       mov.l   r0, @r6                 /* store old mask */
+3:     rts
+        mov    #0, r0
+
+err:
+       JUMP_CERROR
+
+       SET_ENTRY_SIZE(sigprocmask)
diff --git a/lib/nbsd_libc/compat/arch/sh3/sys/compat_sigreturn.S b/lib/nbsd_libc/compat/arch/sh3/sys/compat_sigreturn.S
new file mode 100644 (file)
index 0000000..9376a7a
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: compat_sigreturn.S,v 1.1 2005/09/15 21:39:16 uwe Exp $ */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigreturn.s   5.2 (Berkeley) 12/17/90"
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigreturn.S,v 1.1 2005/09/15 21:39:16 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ */
+
+WARN_REFERENCES(sigreturn, \
+    "warning: reference to compatibility sigreturn()")
+
+PSEUDO(sigreturn,compat_13_sigreturn13)
diff --git a/lib/nbsd_libc/compat/arch/sh3/sys/compat_sigsuspend.S b/lib/nbsd_libc/compat/arch/sh3/sys/compat_sigsuspend.S
new file mode 100644 (file)
index 0000000..3f6fdf2
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: compat_sigsuspend.S,v 1.3 2006/01/06 04:05:55 uwe Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigsuspend.s  5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigsuspend.S,v 1.3 2006/01/06 04:05:55 uwe Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigsuspend, \
+    "warning: reference to compatibility sigsuspend(); include <signal.h> for correct reference")
+
+/*
+ * int sigsuspend(const sigset_t *sigmask);
+ */
+ENTRY(sigsuspend)
+       mov.l   @r4, r4         /* syscall expects mask as the argument */
+       mov     #SYS_compat_13_sigsuspend13, r0
+       trapa   #0x80
+       bf      err
+       rts                     /* shouldn t happen */
+        mov    #0, r0
+err:
+       JUMP_CERROR
+
+       SET_ENTRY_SIZE(sigsuspend)
diff --git a/lib/nbsd_libc/compat/arch/sparc/Makefile.inc b/lib/nbsd_libc/compat/arch/sparc/Makefile.inc
new file mode 100644 (file)
index 0000000..fc44d31
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/03/11 23:04:04 christos Exp $
+
+.include "${COMPATARCHDIR}/gen/Makefile.inc"
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/sparc/gen/Makefile.inc b/lib/nbsd_libc/compat/arch/sparc/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..ec25fc1
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/07/03 13:06:12 drochner Exp $
+
+SRCS+= compat_setjmp.S compat_sigsetjmp.S
+
+# objects built from C sources in compat/gen
+SRCS+= compat_frexp_ieee754.c compat_ldexp_ieee754.c
+#SRCS+=        compat_modf_ieee754.c
diff --git a/lib/nbsd_libc/compat/arch/sparc/gen/compat_setjmp.S b/lib/nbsd_libc/compat/arch/sparc/gen/compat_setjmp.S
new file mode 100644 (file)
index 0000000..dc56cef
--- /dev/null
@@ -0,0 +1,116 @@
+/*     $NetBSD: compat_setjmp.S,v 1.1 2005/10/15 22:11:22 uwe Exp $    */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: setjmp.s,v 1.2 92/06/25 03:18:43 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)setjmp.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat_setjmp.S,v 1.1 2005/10/15 22:11:22 uwe Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and a struct sigcontext, see <signal.h>
+ */
+
+#include "SYS.h"
+
+ENTRY(setjmp)
+       /*
+        * We use the caller's `arg dump' area (%sp+0x44; there are 6 ints
+        * reserved there for us) to avoid having to allocate stack space
+        * here.
+        */
+       mov     %o0, %o2        /* build sigcontext in [%o2] */
+       mov     1, %o0          /* SIG_BLOCK */
+       mov     SYS_compat_13_sigprocmask13, %g1
+       clr     %o1             /* sigprocmask(SIG_BLOCK, (sigset_t *)NULL) */
+       t       ST_SYSCALL
+       st      %o0, [%o2 + 4]  /* sc.sc_mask = current mask; */
+       mov     SYS___sigaltstack14, %g1
+       clr     %o0             /* sigaltstack(NULL, &foo) */
+       add     %sp, 0x48, %o1  /* (foo being in arg dump area) */
+       t       ST_SYSCALL
+       ld      [%sp + 0x50], %o0       /* foo.ss_flags */
+       and     %o0, 1, %o1     /* onstack = foo.ss_flags & 1; */
+       st      %o0, [%o2 + 0]  /* sc.sc_onstack = current onstack; */
+       st      %sp, [%o2 + 8]  /* sc.sc_sp = sp (both ours and caller's) */
+       add     %o7, 8, %o0
+       st      %o0, [%o2 + 12] /* sc.sc_pc = return_pc */
+       add     %o7, 12, %o0
+       st      %o0, [%o2 + 16] /* sc.sc_npc = return_pc + 4 */
+       st      %g0, [%o2 + 20] /* sc.sc_psr = (clean psr) */
+       st      %fp, [%o2 + 24] /* sc.sc_g1 = %fp (misuse, but what the heck) */
+                               /* sc.sc_o0 = random(), set in longjmp */
+       retl                    /* return 0 */
+        clr    %o0
+
+/*
+ * All we need to do here is force sigreturn to load a new stack pointer,
+ * new <pc,npc>, and appropriate %o0 return value from the sigcontext built
+ * in setjmp.  The %i and %l registers will be reloaded from the place to
+ * which %sp points, due to sigreturn() semantics (sigreturn does not modify
+ * the window pointer in the psr, hence it must force all windows to reload).
+ */
+ENTRY(longjmp)
+       save    %sp, -96, %sp
+       ld      [%i0 + 8], %o2  /* make sure sc->sc_sp, sc->sc_fp nonzero */
+       ld      [%i0 + 24], %o3
+       orcc    %o2, %o3, %g0
+       bz      Lbotch
+        tst    %i1             /* if (v == 0) v = 1; */
+       bz,a    1f
+        mov    1, %i1
+1:
+       st      %i1, [%i0 + 28] /* sc.sc_o0 = v; */
+       mov     SYS_compat_13_sigreturn13, %g1
+       mov     %i0, %o0
+       t       ST_SYSCALL      /* sigreturn(scp); */
+
+Lbotch:
+       /* oops, caller botched it */
+       call    _C_LABEL(longjmperror)
+        nop
+       unimp   0
diff --git a/lib/nbsd_libc/compat/arch/sparc/gen/compat_sigsetjmp.S b/lib/nbsd_libc/compat/arch/sparc/gen/compat_sigsetjmp.S
new file mode 100644 (file)
index 0000000..5b1060d
--- /dev/null
@@ -0,0 +1,93 @@
+/*     $NetBSD: compat_sigsetjmp.S,v 1.2 2007/10/08 13:06:00 uwe Exp $ */
+/*
+ * Copyright (c) 1995 Paul Kranenburg
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Paul Kranenburg.
+ * 4. 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 ``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 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 "SYS.h"
+
+#ifdef PIC
+
+ENTRY(sigsetjmp)
+       PIC_PROLOGUE(%g1, %g2)          ! %g1 = _GLOBAL_OFFSET_TABLE
+       tst     %o1
+       bnz     1f
+        st     %o1, [%o0 + 56]         ! jmpbuf[JBLEN] = savemask
+
+       !! if (savemask == 0) goto _setjmp
+       set     _C_LABEL(_setjmp), %g2
+       ld      [%g1 + %g2], %g1
+       jmp %g1
+        nop
+
+       !! if (savemask != 0) goto setjmp
+1:     set     _C_LABEL(setjmp), %g2
+       ld      [%g1 + %g2], %g1
+       jmp %g1
+        nop
+
+
+ENTRY(siglongjmp)
+       PIC_PROLOGUE(%g1, %g2)          ! %g1 = _GLOBAL_OFFSET_TABLE
+       ld      [%o0 + 56], %g2         ! restoremask = jmpbuf[JBLEN]
+       tst     %g2
+       bnz     1f
+        nop
+
+       !! if (restoremask == 0) goto _longjmp
+       set     _C_LABEL(_longjmp), %g2
+       ld      [%g1 + %g2], %g1
+       jmp %g1
+        nop
+
+       !! if (restoremask != 0) goto longjmp
+1:     set     _C_LABEL(longjmp), %g2
+       ld      [%g1 + %g2], %g1
+       jmp %g1
+        nop
+
+#else /* !PIC */
+
+ENTRY(sigsetjmp)
+       cmp %o1,0
+       be _C_LABEL(_setjmp)
+       st %o1,[%o0+40]         ! jmpbuf[JBLEN]
+       nop
+       ba,a _C_LABEL(setjmp)
+       unimp 0
+
+ENTRY(siglongjmp)
+       ld [%o0+40],%g1
+       cmp %g1,0
+       be _C_LABEL(_longjmp)
+       nop
+       ba,a _C_LABEL(longjmp)
+       unimp 0
+
+#endif /* !PIC */
diff --git a/lib/nbsd_libc/compat/arch/sparc/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/sparc/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..0a7475a
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.1 2005/10/15 22:11:22 uwe Exp $
+
+SRCS+=compat_Ovfork.S compat___semctl.S compat___sigreturn14.S \
+    compat___sigtramp1.S compat_msgctl.S compat_shmctl.S compat_sigaction.S \
+    compat_sigpending.S compat_sigprocmask.S compat_sigreturn.S \
+    compat_sigsuspend.S 
diff --git a/lib/nbsd_libc/compat/arch/sparc/sys/compat_Ovfork.S b/lib/nbsd_libc/compat/arch/sparc/sys/compat_Ovfork.S
new file mode 100644 (file)
index 0000000..e56f145
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: compat_Ovfork.S,v 1.1 2005/10/15 22:11:22 uwe Exp $    */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: Ovfork.s,v 1.1 91/07/06 13:05:56 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)Ovfork.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat_Ovfork.S,v 1.1 2005/10/15 22:11:22 uwe Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+/*
+ * pid = vfork();
+ *
+ * %o1 == 0 in parent process, 1 in child process.
+ * %o0 == pid of child in parent, pid of parent in child.
+ */
+
+#include "SYS.h"
+
+WARN_REFERENCES(vfork, \
+    "warning: reference to compatibility vfork(); include <unistd.h> for correct reference")
+
+SYSCALL(vfork)
+       dec     %o1             ! from 1 to 0 in child, 0 to -1 in parent
+       retl
+       and     %o0, %o1, %o0   ! return 0 in child, pid in parent
diff --git a/lib/nbsd_libc/compat/arch/sparc/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/sparc/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..c64b6d3
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/sparc/sys/compat___sigreturn14.S b/lib/nbsd_libc/compat/arch/sparc/sys/compat___sigreturn14.S
new file mode 100644 (file)
index 0000000..d6620e7
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: compat___sigreturn14.S,v 1.1 2005/10/15 22:11:22 uwe Exp $     */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: sigreturn.s,v 1.1 91/07/06 13:06:01 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)sigreturn.s 8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat___sigreturn14.S,v 1.1 2005/10/15 22:11:22 uwe Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+ENTRY(__sigreturn14)
+       mov     SYS_compat_16___sigreturn14, %g1
+       t       ST_SYSCALL
+       ERROR()
diff --git a/lib/nbsd_libc/compat/arch/sparc/sys/compat___sigtramp1.S b/lib/nbsd_libc/compat/arch/sparc/sys/compat___sigtramp1.S
new file mode 100644 (file)
index 0000000..12385b1
--- /dev/null
@@ -0,0 +1,170 @@
+/*     $NetBSD: compat___sigtramp1.S,v 1.1 2005/10/15 22:11:22 uwe Exp $       */
+
+/*
+ * Copyright (c) 1996 Paul Kranenburg
+ * Copyright (c) 1996
+ *     The President and Fellows of Harvard College. All rights reserved.
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * All advertising materials mentioning features or use of this software
+ * must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Lawrence Berkeley Laboratory.
+ *     This product includes software developed by Harvard University.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Harvard University.
+ *     This product includes software developed by Paul Kranenburg.
+ * 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.
+ */
+
+#include "SYS.h"
+
+#define _LOCORE
+#include <machine/frame.h>
+#include <machine/psl.h>
+#include <machine/signal.h>
+
+/*
+ * When this code is run, the stack looks like:
+ *     [%sp]           64 bytes to which registers can be dumped
+ *     [%sp + 64]      signal number (goes in %o0)
+ *     [%sp + 64 + 4]  signal code (goes in %o1)
+ *     [%sp + 64 + 8]  placeholder
+ *     [%sp + 64 + 12] argument for %o3, currently unsupported (always 0)
+ *     [%sp + 64 + 16] first word of saved state (sigcontext)
+ *         .
+ *         .
+ *         .
+ *     [%sp + NNN]     last word of saved state
+ * (followed by previous stack contents or top of signal stack).
+ * The address of the function to call is in %g1; the old %g1 and %o0
+ * have already been saved in the sigcontext.  We are running in a clean
+ * window, all previous windows now being saved to the stack.
+ *
+ * Note that [%sp + 64 + 8] == %sp + 64 + 16.  The copy at %sp+64+8
+ * will eventually be removed, with a hole left in its place, if things
+ * work out.
+ */
+#define SAVE_STATE \
+       /* \
+        * XXX  the `save' and `restore' below are unnecessary: should \
+        *      replace with simple arithmetic on %sp \
+        * \
+        * Make room on the stack for 32 %f registers + %fsr.  This comes \
+        * out to 33*4 or 132 bytes, but this must be aligned to a multiple \
+        * of 8, or 136 bytes. \
+        */ \
+       save    %sp, -CCFSZ - 136, %sp; \
+       mov     %g2, %l2;               /* save globals in %l registers */ \
+       mov     %g3, %l3; \
+       mov     %g4, %l4; \
+       mov     %g5, %l5; \
+       mov     %g6, %l6; \
+       mov     %g7, %l7; \
+       /* \
+        * Saving the fpu registers is expensive, so do it iff the fsr \
+        * stored in the sigcontext shows that the fpu is enabled. \
+        */ \
+       ld      [%fp + 64 + 16 + SC_PSR_OFFSET], %l0; \
+       sethi   %hi(PSR_EF), %l1;       /* FPU enable is too high for andcc */ \
+       andcc   %l0, %l1, %l0;          /* %l0 = fpu enable bit */ \
+       be      1f;                     /* if not set, skip the saves */ \
+        rd     %y, %l1;                /* in any case, save %y */ \
+       /* fpu is enabled, oh well */ \
+       st      %fsr, [%sp + CCFSZ + 0]; \
+       std     %f0, [%sp + CCFSZ + 8]; \
+       std     %f2, [%sp + CCFSZ + 16]; \
+       std     %f4, [%sp + CCFSZ + 24]; \
+       std     %f6, [%sp + CCFSZ + 32]; \
+       std     %f8, [%sp + CCFSZ + 40]; \
+       std     %f10, [%sp + CCFSZ + 48]; \
+       std     %f12, [%sp + CCFSZ + 56]; \
+       std     %f14, [%sp + CCFSZ + 64]; \
+       std     %f16, [%sp + CCFSZ + 72]; \
+       std     %f18, [%sp + CCFSZ + 80]; \
+       std     %f20, [%sp + CCFSZ + 88]; \
+       std     %f22, [%sp + CCFSZ + 96]; \
+       std     %f24, [%sp + CCFSZ + 104]; \
+       std     %f26, [%sp + CCFSZ + 112]; \
+       std     %f28, [%sp + CCFSZ + 120]; \
+       std     %f30, [%sp + CCFSZ + 128]; \
+1:
+
+#define RESTORE_STATE \
+       /* \
+        * Now that the handler has returned, re-establish all the state \
+        * we just saved above, then do a sigreturn. \
+        */ \
+       tst     %l0;                    /* reload fpu registers? */ \
+       be      1f;                     /* if not, skip the loads */ \
+        wr     %l1, %g0, %y;           /* in any case, restore %y */ \
+       ld      [%sp + CCFSZ + 0], %fsr; \
+       ldd     [%sp + CCFSZ + 8], %f0; \
+       ldd     [%sp + CCFSZ + 16], %f2; \
+       ldd     [%sp + CCFSZ + 24], %f4; \
+       ldd     [%sp + CCFSZ + 32], %f6; \
+       ldd     [%sp + CCFSZ + 40], %f8; \
+       ldd     [%sp + CCFSZ + 48], %f10; \
+       ldd     [%sp + CCFSZ + 56], %f12; \
+       ldd     [%sp + CCFSZ + 64], %f14; \
+       ldd     [%sp + CCFSZ + 72], %f16; \
+       ldd     [%sp + CCFSZ + 80], %f18; \
+       ldd     [%sp + CCFSZ + 88], %f20; \
+       ldd     [%sp + CCFSZ + 96], %f22; \
+       ldd     [%sp + CCFSZ + 104], %f24; \
+       ldd     [%sp + CCFSZ + 112], %f26; \
+       ldd     [%sp + CCFSZ + 120], %f28; \
+       ldd     [%sp + CCFSZ + 128], %f30; \
+1: \
+       mov     %l2, %g2; \
+       mov     %l3, %g3; \
+       mov     %l4, %g4; \
+       mov     %l5, %g5; \
+       mov     %l6, %g6; \
+       mov     %l7, %g7
+
+ENTRY_NOPROFILE(__sigtramp_sigcontext_1)
+       SAVE_STATE
+
+       ldd     [%fp + 64], %o0         /* sig, code */
+       ld      [%fp + 76], %o3         /* arg3 */
+       call    %g1                     /* call handler */
+        add    %fp, 64 + 16, %o2       /* pointer to sigcontext */
+
+       RESTORE_STATE
+
+       /* Get registers back and set syscall # */
+       restore %g0, SYS_compat_16___sigreturn14, %g1
+       add     %sp, 64 + 16, %o0       /* compute scp */
+       t       ST_SYSCALL              /* call sigreturn */
+       mov     SYS_exit, %g1           /* exit with errno */
+       t       ST_SYSCALL              /* if sigreturn fails */
diff --git a/lib/nbsd_libc/compat/arch/sparc/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/sparc/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..a5598b0
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_msgctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/sparc/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/sparc/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..a9f938c
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_shmctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/sparc/sys/compat_sigaction.S b/lib/nbsd_libc/compat/arch/sparc/sys/compat_sigaction.S
new file mode 100644 (file)
index 0000000..7d77843
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_sigaction.S,v 1.2 2008/04/28 20:22:59 martin Exp $      */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(sigaction, \
+    "warning: reference to compatibility sigaction(); include <signal.h> for correct reference")
+
+PSEUDO(sigaction,compat_13_sigaction13)
diff --git a/lib/nbsd_libc/compat/arch/sparc/sys/compat_sigpending.S b/lib/nbsd_libc/compat/arch/sparc/sys/compat_sigpending.S
new file mode 100644 (file)
index 0000000..c589159
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: compat_sigpending.S,v 1.1 2005/10/15 22:11:22 uwe Exp $        */
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: sigpending.s,v 1.1 91/07/06 13:06:00 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)sigpending.s        8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat_sigpending.S,v 1.1 2005/10/15 22:11:22 uwe Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigpending, \
+    "warning: reference to compatibility sigpending(); include <signal.h> for correct reference")
+
+ENTRY(sigpending)
+       mov     %o0, %o2                ! save pointer
+       mov     SYS_compat_13_sigpending13, %g1
+       t       ST_SYSCALL              ! sigpending()
+       bcc,a   1f                      ! if success,
+        st     %o0, [%o2]              !    store return value
+       ERROR()
+1:
+       retl                            ! and return 0
+        clr    %o0
diff --git a/lib/nbsd_libc/compat/arch/sparc/sys/compat_sigprocmask.S b/lib/nbsd_libc/compat/arch/sparc/sys/compat_sigprocmask.S
new file mode 100644 (file)
index 0000000..d38d787
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: compat_sigprocmask.S,v 1.1 2005/10/15 22:11:22 uwe Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: sigprocmask.s,v 1.1 91/07/06 13:06:01 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)sigprocmask.s       8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat_sigprocmask.S,v 1.1 2005/10/15 22:11:22 uwe Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigprocmask, \
+    "warning: reference to compatibility sigprocmask(); include <signal.h> for correct reference")
+
+/*
+ * sigprocmask(int how, sigset_t *set, sigset_t *oset)
+ */
+ENTRY(sigprocmask)
+       tst     %o1             ! set == NULL?
+       bne,a   1f              ! if not,
+        ld     [%o1], %o1      !    replace it in %o1 with *set
+!      clr     %o1             ! else block no signals ...
+       mov     1, %o0          ! ... using sigprocmask(SIG_BLOCK)
+1:
+       mov     SYS_compat_13_sigprocmask13, %g1
+       t       ST_SYSCALL
+       bcc     2f              ! if success,
+        tst    %o2             !    check to see if oset requested
+       ERROR()
+2:
+       bne,a   3f              ! if oset != NULL,
+        st     %o0, [%o2]      !    *oset = oldmask
+3:
+       retl                    ! in any case, return 0
+        clr    %o0
diff --git a/lib/nbsd_libc/compat/arch/sparc/sys/compat_sigreturn.S b/lib/nbsd_libc/compat/arch/sparc/sys/compat_sigreturn.S
new file mode 100644 (file)
index 0000000..041392b
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: compat_sigreturn.S,v 1.1 2005/10/15 22:11:22 uwe Exp $ */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: sigreturn.s,v 1.1 91/07/06 13:06:01 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)sigreturn.s 8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat_sigreturn.S,v 1.1 2005/10/15 22:11:22 uwe Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigreturn, \
+    "warning: reference to compatibility sigreturn()")
+
+ENTRY(sigreturn)
+       mov     SYS_compat_13_sigreturn13, %g1
+       t       ST_SYSCALL
+       ERROR()
diff --git a/lib/nbsd_libc/compat/arch/sparc/sys/compat_sigsuspend.S b/lib/nbsd_libc/compat/arch/sparc/sys/compat_sigsuspend.S
new file mode 100644 (file)
index 0000000..a50ff71
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: compat_sigsuspend.S,v 1.1 2005/10/15 22:11:22 uwe Exp $        */
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: sigsuspend.s,v 1.1 91/07/06 13:06:01 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)sigsuspend.s        8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat_sigsuspend.S,v 1.1 2005/10/15 22:11:22 uwe Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigsuspend, \
+    "warning: reference to compatibility sigsuspend(); include <signal.h> for correct reference")
+
+ENTRY(sigsuspend)
+       ld      [%o0], %o0              ! indirect to mask argument
+       mov     SYS_compat_13_sigsuspend13, %g1
+       t       ST_SYSCALL
+       ERROR()                         ! always terminates with EINTR
diff --git a/lib/nbsd_libc/compat/arch/sparc64/Makefile.inc b/lib/nbsd_libc/compat/arch/sparc64/Makefile.inc
new file mode 100644 (file)
index 0000000..fc44d31
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/03/11 23:04:04 christos Exp $
+
+.include "${COMPATARCHDIR}/gen/Makefile.inc"
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/sparc64/gen/Makefile.inc b/lib/nbsd_libc/compat/arch/sparc64/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..ec25fc1
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/07/03 13:06:12 drochner Exp $
+
+SRCS+= compat_setjmp.S compat_sigsetjmp.S
+
+# objects built from C sources in compat/gen
+SRCS+= compat_frexp_ieee754.c compat_ldexp_ieee754.c
+#SRCS+=        compat_modf_ieee754.c
diff --git a/lib/nbsd_libc/compat/arch/sparc64/gen/compat_setjmp.S b/lib/nbsd_libc/compat/arch/sparc64/gen/compat_setjmp.S
new file mode 100644 (file)
index 0000000..628a5e0
--- /dev/null
@@ -0,0 +1,119 @@
+/*     $NetBSD: compat_setjmp.S,v 1.1 2005/10/16 04:41:34 christos Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: setjmp.s,v 1.2 92/06/25 03:18:43 torek Exp
+ */
+
+#define _LOCORE
+#include <machine/asm.h>
+#include <machine/frame.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)setjmp.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat_setjmp.S,v 1.1 2005/10/16 04:41:34 christos Exp $")
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * C library -- setjmp, longjmp
+ *
+ *     longjmp(a,v)
+ * will generate a "return(v)" from
+ * the last call to
+ *     setjmp(a)
+ * by restoring registers from the stack,
+ * and a struct sigcontext, see <signal.h>
+ */
+
+#include "SYS.h"
+
+#define STACK_T_SZ
+ENTRY(setjmp)
+       /*
+        * We use the part of the sigcontext structure, the sp, pc, and npc fields,
+        * for the sigstack call so we don't need to get our own stackframe.  It 
+        * won't be filled out till later anyway.
+        */
+       mov     %o0, %o3                /* Save our jmp_buf in %o3 */
+       mov     %o0, %o2                /* build sigcontext in [%o2] */
+       mov     1, %o0                  /* SIG_BLOCK */
+       mov     SYS_compat_13_sigprocmask13, %g1
+       clr     %o1                     /* sigprocmask(SIG_BLOCK, (sigset_t *)NULL, (sigset_t *)a) */
+       t       ST_SYSCALL
+       
+       st      %o0, [%o3 + 0x04]       /* sc.sc_mask = current mask; */
+       mov     SYS___sigaltstack14, %g1
+       clr     %o0                     /* sigstack(NULL, &foo) */
+       add     %o3, 0x38, %o1          /* (foo being the sigcontext14 sc_mask) */
+       t       ST_SYSCALL
+       
+       lduw    [%o3 + 0x38+0x10], %o0  /* foo.ss_flags */
+       and     %o0, 1, %o1             /* onstack = foo.ss_flags & 1; */
+       st      %o0, [%o3 + 0x00]       /* sc.sc_onstack = current onstack; */
+       stx     %sp, [%o3 + 0x08]       /* sc.sc_sp = sp (both ours and caller's) */
+       add     %o7, 8, %o0
+       stx     %o0, [%o3 + 0x10]       /* sc.sc_pc = return_pc */
+       add     %o7, 12, %o0
+       stx     %o0, [%o3 + 0x18]       /* sc.sc_npc = return_pc + 4 */
+       stx     %g0, [%o3 + 0x20]       /* sc.sc_psr = (clean psr) */
+       stx     %fp, [%o3 + 0x28]       /* sc.sc_g1 = %fp (misuse, but what the heck) */
+                                       /* sc.sc_o0 = random(), set in longjmp */
+       retl                            /* return 0 */
+        clr    %o0
+
+/*
+ * All we need to do here is force sigreturn to load a new stack pointer,
+ * new <pc,npc>, and appropriate %o0 return value from the sigcontext built
+ * in setjmp.  The %i and %l registers will be reloaded from the place to
+ * which %sp points, due to sigreturn() semantics (sigreturn does not modify
+ * the window pointer in the psr, hence it must force all windows to reload).
+ */
+ENTRY(longjmp)
+       save    %sp, -CC64FSZ, %sp
+       ldx     [%i0 + 0x08], %o2       /* make sure sc->sc_sp, sc->sc_fp nonzero */
+       ldx     [%i0 + 0x28], %o3
+       orcc    %o2, %o3, %g0
+       bz,pn   %xcc, Lbotch
+        movrz  %i1, 1, %i1             /* if (v == 0) v = 1; */
+       st      %i1, [%i0 + 0x30]       /* sc.sc_o0 = v; */
+       mov     SYS_compat_13_sigreturn13, %g1
+       mov     %i0, %o0
+       t       ST_SYSCALL              /* sigreturn(scp); */
+
+Lbotch:
+       /* oops, caller botched it */
+       call    _C_LABEL(longjmperror)
+        nop
+       unimp   0
diff --git a/lib/nbsd_libc/compat/arch/sparc64/gen/compat_sigsetjmp.S b/lib/nbsd_libc/compat/arch/sparc64/gen/compat_sigsetjmp.S
new file mode 100644 (file)
index 0000000..9d85159
--- /dev/null
@@ -0,0 +1,101 @@
+/*     $NetBSD: compat_sigsetjmp.S,v 1.1 2005/10/16 04:41:34 christos Exp $    */
+/*
+ * Copyright (c) 1995 Paul Kranenburg
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Paul Kranenburg.
+ * 4. 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 ``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 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 "SYS.h"
+
+#ifdef PIC
+#ifdef BIGPIC
+       
+ENTRY(sigsetjmp)
+       PIC_PROLOGUE(%g1,%o2)           ! %g1 = _GLOBAL_OFFSET_TABLE
+       set     _C_LABEL(setjmp), %o2   ! if (%o1 != 0) goto _setjmp;
+       set     _C_LABEL(_setjmp), %o3  ! else goto __setjmp;
+       movrnz  %o1, %o2, %o3
+       ldx [%g1+%o3], %g1
+       jmp %g1
+        st     %o1,[%o0+0x48]          ! jmpbuf[JBLEN]
+
+
+ENTRY(siglongjmp)
+       PIC_PROLOGUE(%g1,%o2)           ! %g1 = _GLOBAL_OFFSET_TABLE
+       ld      [%o0 + 0x48],%o2        ! jmpbuf[JBLEN]
+       set     _C_LABEL(longjmp), %o3  ! if (%o2 != 0) goto _longjmp;
+       set     _C_LABEL(_longjmp), %o4 ! else goto __longjmp;
+       movrnz  %o2, %o3, %o4 
+       ldx     [%g1 + %o4], %g1
+       jmp %g1
+        nop
+       unimp 0
+
+#else
+       
+ENTRY(sigsetjmp)
+       PIC_PROLOGUE(%g1,%o2)           ! %g1 = _GLOBAL_OFFSET_TABLE
+       cmp     %o1, 0
+       bne,a   1f
+        ldx    [%g1 + _C_LABEL(setjmp)], %g1   ! if (%o1 != 0) goto _setjmp;
+       ldx     [%g1 + _C_LABEL(_setjmp)], %g1  ! else goto __setjmp;
+1:     
+       jmp %g1
+        st     %o1,[%o0+0x48]          ! jmpbuf[JBLEN]
+
+
+ENTRY(siglongjmp)
+       PIC_PROLOGUE(%g1,%o2)           ! %g1 = _GLOBAL_OFFSET_TABLE
+       cmp     %o2, 0
+       ld      [%o0 + 0x48],%o2        ! jmpbuf[JBLEN]
+       bne,a   1f
+        ldx    [%g1 + _C_LABEL(longjmp)], %g1  ! if (%o2 != 0) goto _longjmp;
+       ldx     [%g1 + _C_LABEL(_longjmp)], %g1 ! else goto __longjmp;
+1:     
+       jmp %g1
+        nop
+       unimp 0
+
+#endif /* BIGPIC */
+#else /* PIC */
+
+ENTRY(sigsetjmp)
+       brz,pt  %o1,_C_LABEL(_setjmp)
+        st     %o1,[%o0+0x48]          ! jmpbuf[JBLEN]
+       ba,a,pt %icc,_C_LABEL(setjmp)
+        nop                            ! spitfire bug
+       unimp 0
+
+ENTRY(siglongjmp)
+       ld      [%o0 + 0x48], %g1
+       brz,pt  %g1, _C_LABEL(_longjmp)
+        nop
+       ba,a,pt %icc, _C_LABEL(longjmp)
+       unimp 0
+
+#endif /* PIC */
diff --git a/lib/nbsd_libc/compat/arch/sparc64/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/sparc64/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..f45e2b8
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.1 2005/10/16 04:41:34 christos Exp $
+
+SRCS+=compat_Ovfork.S compat___semctl.S compat___sigreturn14.S \
+    compat___sigtramp1.S compat_msgctl.S compat_shmctl.S compat_sigaction.S \
+    compat_sigpending.S compat_sigprocmask.S compat_sigreturn.S \
+    compat_sigsuspend.S 
diff --git a/lib/nbsd_libc/compat/arch/sparc64/sys/compat_Ovfork.S b/lib/nbsd_libc/compat/arch/sparc64/sys/compat_Ovfork.S
new file mode 100644 (file)
index 0000000..e11a6aa
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: compat_Ovfork.S,v 1.1 2005/10/16 04:41:34 christos Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: Ovfork.s,v 1.1 91/07/06 13:05:56 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)Ovfork.s    8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat_Ovfork.S,v 1.1 2005/10/16 04:41:34 christos Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+/*
+ * pid = vfork();
+ *
+ * %o1 == 0 in parent process, 1 in child process.
+ * %o0 == pid of child in parent, pid of parent in child.
+ */
+
+#include "SYS.h"
+
+WARN_REFERENCES(vfork, \
+    "warning: reference to compatibility vfork(); include <unistd.h> for correct reference")
+
+SYSCALL(vfork)
+       dec     %o1             /* from 1 to 0 in child, 0 to -1 in parent */
+       retl
+        and    %o0, %o1, %o0   /* return 0 in child, pid in parent */
diff --git a/lib/nbsd_libc/compat/arch/sparc64/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/sparc64/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..c64b6d3
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/sparc64/sys/compat___sigreturn14.S b/lib/nbsd_libc/compat/arch/sparc64/sys/compat___sigreturn14.S
new file mode 100644 (file)
index 0000000..b65b839
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: compat___sigreturn14.S,v 1.1 2005/10/16 04:41:34 christos Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: sigreturn.s,v 1.1 91/07/06 13:06:01 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)sigreturn.s 8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat___sigreturn14.S,v 1.1 2005/10/16 04:41:34 christos Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+ENTRY(__sigreturn14)
+       mov     SYS_compat_16___sigreturn14, %g1
+       t       ST_SYSCALL
+       ERROR()
diff --git a/lib/nbsd_libc/compat/arch/sparc64/sys/compat___sigtramp1.S b/lib/nbsd_libc/compat/arch/sparc64/sys/compat___sigtramp1.S
new file mode 100644 (file)
index 0000000..38810fb
--- /dev/null
@@ -0,0 +1,169 @@
+/*     $NetBSD: compat___sigtramp1.S,v 1.1 2005/10/16 04:41:34 christos Exp $  */
+
+/*
+ * Copyright (c) 1996-2002 Eduardo Horvath
+ * Copyright (c) 1996 Paul Kranenburg
+ * Copyright (c) 1996
+ *     The President and Fellows of Harvard College. All rights reserved.
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * All advertising materials mentioning features or use of this software
+ * must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Lawrence Berkeley Laboratory.
+ *     This product includes software developed by Harvard University.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Harvard University.
+ *     This product includes software developed by Paul Kranenburg.
+ * 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.
+ */
+
+#include "SYS.h"
+
+#define _LOCORE
+#include <machine/frame.h>
+#include <machine/fsr.h>
+#include <machine/ctlreg.h>
+#include <machine/psl.h>
+
+       .register       %g2,#ignore
+       .register       %g3,#ignore
+
+/*
+ * When this code is run, the stack looks like:
+ *     [%sp]                   128 bytes to which registers can be dumped
+ *     [%sp + 128]             signal number (goes in %o0)
+ *     [%sp + 128 + 4]         signal code (goes in %o1)
+ *     [%sp + 128 + 8]         first word of saved state (sigcontext)
+ *         .
+ *         .
+ *         .
+ *     [%sp + NNN]     last word of saved state
+ * (followed by previous stack contents or top of signal stack).
+ * The address of the function to call is in %g1; the old %g1 and %o0
+ * have already been saved in the sigcontext.  We are running in a clean
+ * window, all previous windows now being saved to the stack.
+ *
+ * Note that [%sp + 128 + 8] == %sp + 128 + 16.  The copy at %sp+128+8
+ * will eventually be removed, with a hole left in its place, if things
+ * work out.
+ */
+ENTRY_NOPROFILE(__sigtramp_sigcontext_1)
+       /*
+        * XXX  the `save' and `restore' below are unnecessary: should
+        *      replace with simple arithmetic on %sp
+        *
+        * Make room on the stack for 64 %f registers + %fsr.  This comes
+        * out to 64*4+8 or 264 bytes, but this must be aligned to a multiple
+        * of 64, or 320 bytes.
+        */
+       save    %sp, -CC64FSZ - 320, %sp
+       mov     %g2, %l2                /* save globals in %l registers */
+       mov     %g3, %l3
+       mov     %g4, %l4
+       mov     %g5, %l5
+       mov     %g6, %l6
+       mov     %g7, %l7
+       /*
+        * Saving the fpu registers is expensive, so do it iff it is
+        * enabled and dirty.
+        */
+       rd      %fprs, %l0
+       btst    FPRS_DL|FPRS_DU, %l0    /* All clean? */
+       bz,pt   %icc, 2f
+        btst   FPRS_DL, %l0            /* test dl */
+       bz,pt   %icc, 1f
+        btst   FPRS_DU, %l0            /* test du */
+
+       /* fpu is enabled, oh well */
+       stx     %fsr, [%sp + CC64FSZ + BIAS + 0]
+       add     %sp, BIAS+CC64FSZ+BLOCK_SIZE, %l0 /* Generate a pointer so */
+       andn    %l0, BLOCK_ALIGN, %l0             /* we can do a block store */
+       stda    %f0, [%l0] ASI_BLK_P
+       inc     BLOCK_SIZE, %l0
+       stda    %f16, [%l0] ASI_BLK_P
+1:
+       bz,pt   %icc, 2f
+        add    %sp, BIAS+CC64FSZ+BLOCK_SIZE, %l0 /* Generate a pointer so */
+       andn    %l0, BLOCK_ALIGN, %l0             /* we can do a block store */
+       add     %l0, 2*BLOCK_SIZE, %l0  /* and skip what we already stored */
+       stda    %f32, [%l0] ASI_BLK_P
+       inc     BLOCK_SIZE, %l0
+       stda    %f48, [%l0] ASI_BLK_P
+2:
+       membar  #Sync
+       rd      %y, %l1                         /* in any case, save %y */
+       lduw    [%fp + BIAS + 128], %o0         /* sig */
+       lduw    [%fp + BIAS + 128 + 4], %o1     /* code */
+       call    %g1                             /* call handler */
+        add    %fp, BIAS + 128 + 8, %o2        /* scp */
+
+       /*
+        * Now that the handler has returned, re-establish all the state
+        * we just saved above, then do a sigreturn.
+        */
+       btst    3, %l0                  /* All clean? */
+       bz,pt   %icc, 2f
+        btst   1, %l0                  /* test dl */
+       bz,pt   %icc, 1f
+        btst   2, %l0                  /* test du */
+
+       ldx     [%sp + CC64FSZ + BIAS + 0], %fsr
+       add     %sp, BIAS+CC64FSZ+BLOCK_SIZE, %l0 /* Generate a pointer so */
+       andn    %l0, BLOCK_ALIGN, %l0             /* we can do a block load */
+       ldda    [%l0] ASI_BLK_P, %f0
+       inc     BLOCK_SIZE, %l0
+       ldda    [%l0] ASI_BLK_P, %f16
+1:
+       bz,pt   %icc, 2f
+        wr     %l1, %g0, %y            /* in any case, restore %y */
+       add     %sp, BIAS+CC64FSZ+BLOCK_SIZE, %l0 /* Generate a pointer so */
+       andn    %l0, BLOCK_ALIGN, %l0             /* we can do a block load */
+       inc     2*BLOCK_SIZE, %l0       /* and skip what we already loaded */
+       ldda    [%l0] ASI_BLK_P, %f32
+       inc     BLOCK_SIZE, %l0
+       ldda    [%l0] ASI_BLK_P, %f48
+2:
+       mov     %l2, %g2
+       mov     %l3, %g3
+       mov     %l4, %g4
+       mov     %l5, %g5
+       mov     %l6, %g6
+       mov     %l7, %g7
+       membar  #Sync
+
+       /* get registers back and set syscall # */
+       restore %g0, SYS_compat_16___sigreturn14, %g1
+       add     %sp, BIAS + 128 + 8, %o0        /* compute scp */
+       t       ST_SYSCALL                      /* call sigreturn */
+       mov     SYS_exit, %g1                   /* exit with errno */
+       t       ST_SYSCALL                      /* if sigreturn fails */
diff --git a/lib/nbsd_libc/compat/arch/sparc64/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/sparc64/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..a5598b0
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_msgctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/sparc64/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/sparc64/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..a9f938c
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_shmctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigaction.S b/lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigaction.S
new file mode 100644 (file)
index 0000000..7d77843
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_sigaction.S,v 1.2 2008/04/28 20:22:59 martin Exp $      */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(sigaction, \
+    "warning: reference to compatibility sigaction(); include <signal.h> for correct reference")
+
+PSEUDO(sigaction,compat_13_sigaction13)
diff --git a/lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigpending.S b/lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigpending.S
new file mode 100644 (file)
index 0000000..21d6290
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: compat_sigpending.S,v 1.1 2005/10/16 04:41:34 christos Exp $   */
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: sigpending.s,v 1.1 91/07/06 13:06:00 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)sigpending.s        8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat_sigpending.S,v 1.1 2005/10/16 04:41:34 christos Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigpending, \
+    "warning: reference to compatibility sigpending(); include <signal.h> for correct reference")
+
+ENTRY(sigpending)
+       mov     %o0, %o2                /* save pointer */
+       mov     SYS_compat_13_sigpending13, %g1
+       t       ST_SYSCALL              /* sigpending() */
+       bcc,a   1f                      /* if success, */
+        st     %o0, [%o2]              /*    store return value */
+       ERROR()
+1:
+       retl                            /* and return 0 */
+        clr    %o0
diff --git a/lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigprocmask.S b/lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigprocmask.S
new file mode 100644 (file)
index 0000000..bbdd339
--- /dev/null
@@ -0,0 +1,73 @@
+/*     $NetBSD: compat_sigprocmask.S,v 1.1 2005/10/16 04:41:34 christos Exp $  */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: sigprocmask.s,v 1.1 91/07/06 13:06:01 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)sigprocmask.s       8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat_sigprocmask.S,v 1.1 2005/10/16 04:41:34 christos Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigprocmask, \
+    "warning: reference to compatibility sigprocmask(); include <signal.h> for correct reference")
+
+/*
+ * sigprocmask(int how, sigset_t *set, sigset_t *oset)
+ */
+ENTRY(sigprocmask)
+       brnz,a  %o1, 1f         /* if (set != NULL) */
+        ld     [%o1], %o1      /*    replace it in %o1 with *set */
+#if 0
+       clr     %o1             /* else block no signals ... */
+#endif
+       mov     1, %o0          /* ... using sigprocmask(SIG_BLOCK) */
+1:
+       mov     SYS_compat_13_sigprocmask13, %g1
+       t       ST_SYSCALL
+       bcc     2f              /* if success, */
+        tst    %o2             /*    check to see if oset requested */
+       ERROR()
+2:
+       bne,a   3f              /* if oset != NULL, */
+        st     %o0, [%o2]      /*    *oset = oldmask */
+3:
+       retl                    /* in any case, return 0 */
+        clr    %o0
diff --git a/lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigreturn.S b/lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigreturn.S
new file mode 100644 (file)
index 0000000..2bb980e
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: compat_sigreturn.S,v 1.1 2005/10/16 04:41:34 christos Exp $    */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: sigreturn.s,v 1.1 91/07/06 13:06:01 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)sigreturn.s 8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat_sigreturn.S,v 1.1 2005/10/16 04:41:34 christos Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigreturn, \
+    "warning: reference to compatibility sigreturn()")
+
+ENTRY(sigreturn)
+       mov     SYS_compat_13_sigreturn13, %g1
+       t       ST_SYSCALL
+       ERROR()
diff --git a/lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigsuspend.S b/lib/nbsd_libc/compat/arch/sparc64/sys/compat_sigsuspend.S
new file mode 100644 (file)
index 0000000..0fefb34
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: compat_sigsuspend.S,v 1.1 2005/10/16 04:41:34 christos Exp $   */
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: sigsuspend.s,v 1.1 91/07/06 13:06:01 torek Exp
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+#if 0
+       .asciz "@(#)sigsuspend.s        8.1 (Berkeley) 6/4/93"
+#else
+       RCSID("$NetBSD: compat_sigsuspend.S,v 1.1 2005/10/16 04:41:34 christos Exp $")
+#endif
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigsuspend, \
+    "warning: reference to compatibility sigsuspend(); include <signal.h> for correct reference")
+
+ENTRY(sigsuspend)
+       ld      [%o0], %o0              /* indirect to mask argument */
+       mov     SYS_compat_13_sigsuspend13, %g1
+       t       ST_SYSCALL
+       ERROR()                         /* always terminates with EINTR */
diff --git a/lib/nbsd_libc/compat/arch/vax/Makefile.inc b/lib/nbsd_libc/compat/arch/vax/Makefile.inc
new file mode 100644 (file)
index 0000000..04c44bf
--- /dev/null
@@ -0,0 +1,3 @@
+#      $NetBSD: Makefile.inc,v 1.3 2010/07/06 05:59:52 mrg Exp $
+
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/vax/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/vax/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..add5297
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/02/18 22:54:51 matt Exp $
+
+SRCS+= compat_Ovfork.S \
+       compat___sigreturn14.S compat___sigtramp2.S \
+       compat_msgctl.S compat___semctl.S compat_shmctl.S \
+       compat_sigaction13.S compat_sigpending13.S compat_sigprocmask13.S \
+       compat_sigreturn13.S compat_sigsuspend13.S 
diff --git a/lib/nbsd_libc/compat/arch/vax/sys/compat_Ovfork.S b/lib/nbsd_libc/compat/arch/vax/sys/compat_Ovfork.S
new file mode 100644 (file)
index 0000000..0fdda43
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)Ovfork.s 8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: compat_Ovfork.S,v 1.1 2006/02/18 22:54:51 matt Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+/*
+ * @(#)vfork.s 4.1 (Berkeley) 12/21/80
+ * C library -- vfork
+ */
+
+#include "SYS.h"
+
+WARN_REFERENCES(vfork, \
+    "warning: reference to compatibility vfork(); include <unistd.h> for correct reference")
+
+/*
+ * pid = vfork();
+ *
+ * %r1 == 0 in parent process, %r1 == 1 in child process.
+ * %r0 == pid of child in parent, %r0 == pid of parent in child.
+ *
+ * trickery here, due to keith sklower, uses ret to clear the stack,
+ * and then returns with a jump indirect, since only one person can return
+ * with a ret off this stack... we do the ret before we vfork!
+ */
+
+ENTRY(vfork, 0)
+       movl    16(%fp),%r2     # save return address before we smash it
+       movab   here,16(%fp)
+       ret
+here:
+       chmk    $ SYS_vfork
+       bcs     err             # if failed, set errno and return -1
+       /* this next trick is Chris Torek's fault */
+       mnegl   %r1,%r1         # %r1 = 0xffffffff if child, 0 if parent
+       bicl2   %r1,%r0         # %r0 &= ~%r1, i.e., 0 if child, else unchanged
+       jmp     (%r2)
+
+err:
+#ifdef _REENTRANT
+       pushr   $0x5
+       calls   $0,_C_LABEL(__errno)
+       movl    (%sp)+,(%r0)
+       mnegl   $1,%r0
+       rsb
+#else
+       movl    %r0,_C_LABEL(errno)
+       mnegl   $1,%r0
+       jmp     (%r2)
+#endif
diff --git a/lib/nbsd_libc/compat/arch/vax/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/vax/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..c64b6d3
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/vax/sys/compat___sigreturn14.S b/lib/nbsd_libc/compat/arch/vax/sys/compat___sigreturn14.S
new file mode 100644 (file)
index 0000000..4a530aa
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)sigreturn.s      8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: compat___sigreturn14.S,v 1.1 2006/02/18 22:54:51 matt Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ */
+#ifdef GPROF
+#undef ENTRY
+#define        ENTRY(x, y)     _ENTRY(x, y); pushr $0x3f; _PROF_PROLOGUE; popr $0x3f
+#endif /* GPROF */
+
+PSEUDO(__sigreturn14,compat_16___sigreturn14)
diff --git a/lib/nbsd_libc/compat/arch/vax/sys/compat___sigtramp2.S b/lib/nbsd_libc/compat/arch/vax/sys/compat___sigtramp2.S
new file mode 100644 (file)
index 0000000..7f0b688
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: compat___sigtramp2.S,v 1.1 2006/02/18 22:54:51 matt Exp $      */
+
+/*
+ * Copyright (c) 2002 Anders Magnusson, (ragge@NetBSD.org).
+ * 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.
+ * 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 ``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 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.
+ */
+
+/*
+ * Signal trampoline; registers when called:
+ *     sp, pc, psl - obvious
+ *     ap - points to argument list, see machdep.c:sendsig()
+ *     fp - address of signal handler
+ */
+
+#include "SYS.h"
+
+       .text
+       _ALIGN_TEXT
+
+       .globl  _C_LABEL(__sigtramp_sigcontext_2)
+_C_LABEL(__sigtramp_sigcontext_2):
+       pushr $(R0|R1|R2|R3|R4|R5)      # save scratch registers
+       callg (%ap),(%fp)               # use global arg list
+       popr $(R0|R1|R2|R3|R4|R5)       # restore regs
+       movab 8(%ap),%ap                # arg is pointer to sigctx
+       SYSTRAP(compat_16___sigreturn14) # exit from here
+       halt                            # illegal insn
diff --git a/lib/nbsd_libc/compat/arch/vax/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/vax/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..a5598b0
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_msgctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/vax/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/vax/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..a9f938c
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_shmctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/vax/sys/compat_sigaction13.S b/lib/nbsd_libc/compat/arch/vax/sys/compat_sigaction13.S
new file mode 100644 (file)
index 0000000..19d9860
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_sigaction13.S,v 1.2 2008/04/28 20:22:59 martin Exp $    */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(sigaction, \
+    "warning: reference to compatibility sigaction(); include <signal.h> for correct reference")
+
+PSEUDO(sigaction,compat_13_sigaction13)
diff --git a/lib/nbsd_libc/compat/arch/vax/sys/compat_sigpending13.S b/lib/nbsd_libc/compat/arch/vax/sys/compat_sigpending13.S
new file mode 100644 (file)
index 0000000..fa423f8
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)sigpending.s     8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: compat_sigpending13.S,v 1.1 2006/02/18 22:54:51 matt Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigpending, \
+    "warning: reference to compatibility sigpending(); include <signal.h> for correct reference")
+
+_SYSCALL(sigpending,compat_13_sigpending13)
+       movl    %r0,*4(%ap)             # store old mask
+       clrl    %r0
+       ret
diff --git a/lib/nbsd_libc/compat/arch/vax/sys/compat_sigprocmask13.S b/lib/nbsd_libc/compat/arch/vax/sys/compat_sigprocmask13.S
new file mode 100644 (file)
index 0000000..14df4fa
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)sigprocmask.s    8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: compat_sigprocmask13.S,v 1.1 2006/02/18 22:54:51 matt Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigprocmask, \
+    "warning: reference to compatibility sigprocmask(); include <signal.h> for correct reference")
+
+ENTRY(sigprocmask, 0)
+       tstl    8(%ap)                  # check new sigset pointer
+       bneq    1f                      # if not null, indirect
+/*     movl    $0,8(%ap)               # null mask pointer: block empty set */
+       movl    $1,4(%ap)               # SIG_BLOCK
+       jbr     2f
+1:     movl    *8(%ap),8(%ap)          # indirect to new mask arg
+2:     chmk    $ SYS_compat_13_sigprocmask13
+       jcc     3f
+       jmp     CERROR+2
+
+3:     tstl    12(%ap)                 # test if old mask requested
+       beql    out
+       movl    %r0,*12(%ap)            # store old mask
+out:
+       clrl    %r0
+       ret
diff --git a/lib/nbsd_libc/compat/arch/vax/sys/compat_sigreturn13.S b/lib/nbsd_libc/compat/arch/vax/sys/compat_sigreturn13.S
new file mode 100644 (file)
index 0000000..f66856d
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)sigreturn.s      8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: compat_sigreturn13.S,v 1.1 2006/02/18 22:54:51 matt Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+/*
+ * We must preserve the state of the registers as the user has set them up.
+ */
+#ifdef GPROF
+#undef ENTRY
+#define        ENTRY(x, y) \
+       _ENTRY(x, y); pushr $0x3f; _PROF_PROLOGUE; popr $0x3f;
+#endif /* GPROF */
+
+WARN_REFERENCES(sigreturn, \
+    "warning: reference to compatibility sigreturn()")
+
+PSEUDO(sigreturn,compat_13_sigreturn13)
diff --git a/lib/nbsd_libc/compat/arch/vax/sys/compat_sigsuspend13.S b/lib/nbsd_libc/compat/arch/vax/sys/compat_sigsuspend13.S
new file mode 100644 (file)
index 0000000..057ce40
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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(SYSLIBC_SCCS) && !defined(lint)
+       /* .asciz "@(#)sigsuspend.s     8.1 (Berkeley) 6/4/93" */
+       .asciz "$NetBSD: compat_sigsuspend13.S,v 1.1 2006/02/18 22:54:51 matt Exp $"
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigsuspend, \
+    "warning: reference to compatibility sigsuspend(); include <signal.h> for correct reference")
+
+ENTRY(sigsuspend, 0)
+       movl    *4(%ap),4(%ap)          # indirect to mask arg
+       chmk    $ SYS_compat_13_sigsuspend13
+       jcc     1f
+       jmp     CERROR+2
+1:     clrl    %r0                     # shouldnt happen
+       ret
diff --git a/lib/nbsd_libc/compat/arch/x86_64/Makefile.inc b/lib/nbsd_libc/compat/arch/x86_64/Makefile.inc
new file mode 100644 (file)
index 0000000..ccf4c07
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.4 2006/07/03 13:13:53 drochner Exp $
+
+.include "${COMPATARCHDIR}/gen/Makefile.inc"
+.include "${COMPATARCHDIR}/sys/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/arch/x86_64/gen/Makefile.inc b/lib/nbsd_libc/compat/arch/x86_64/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..e06093e
--- /dev/null
@@ -0,0 +1,4 @@
+# $NetBSD: Makefile.inc,v 1.1 2006/07/03 13:13:53 drochner Exp $
+
+# objects built from C sources in compat/gen
+SRCS+= compat_frexp_ieee754.c compat_ldexp_ieee754.c compat_modf_ieee754.c
diff --git a/lib/nbsd_libc/compat/arch/x86_64/sys/Makefile.inc b/lib/nbsd_libc/compat/arch/x86_64/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..28fe055
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/03/11 18:59:21 christos Exp $
+
+SRCS+=compat_Ovfork.S compat___semctl.S compat___sigreturn14.S \
+    compat_msgctl.S compat_shmctl.S compat_sigaction.S \
+    compat_sigpending.S compat_sigprocmask.S compat_sigreturn.S \
+    compat_sigsuspend.S 
diff --git a/lib/nbsd_libc/compat/arch/x86_64/sys/compat_Ovfork.S b/lib/nbsd_libc/compat/arch/x86_64/sys/compat_Ovfork.S
new file mode 100644 (file)
index 0000000..bd6afd9
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: compat_Ovfork.S,v 1.1 2006/03/11 18:59:21 christos Exp $       */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)Ovfork.s      5.1 (Berkeley) 4/23/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_Ovfork.S,v 1.1 2006/03/11 18:59:21 christos Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(vfork, \
+    "warning: reference to compatibility vfork(); include <unistd.h> for correct reference")
+
+/*
+ * pid = vfork();
+ *
+ * %edx == 0 in parent process, %edx == 1 in child process.
+ * %eax == pid of child in parent, %eax == pid of parent in child.
+ *
+ */
+ENTRY(vfork)
+       popq    %r9             /* my rta into r9 */
+       SYSTRAP(vfork)
+       jc      err
+       decl    %edx
+       andl    %edx,%eax
+       jmp     *%r9
+err:
+       pushq   %r9
+#ifdef PIC
+       movq    PIC_GOT(CERROR), %rcx
+       jmp     *%rcx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/compat/arch/x86_64/sys/compat___semctl.S b/lib/nbsd_libc/compat/arch/x86_64/sys/compat___semctl.S
new file mode 100644 (file)
index 0000000..c64b6d3
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat___semctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $       */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+PSEUDO(__semctl,compat_14___semctl)
diff --git a/lib/nbsd_libc/compat/arch/x86_64/sys/compat___sigreturn14.S b/lib/nbsd_libc/compat/arch/x86_64/sys/compat___sigreturn14.S
new file mode 100644 (file)
index 0000000..4704ae8
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: compat___sigreturn14.S,v 1.1 2006/03/11 18:59:21 christos Exp $        */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigreturn.s   5.2 (Berkeley) 12/17/90"
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat___sigreturn14.S,v 1.1 2006/03/11 18:59:21 christos Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+/* Nothing here. We don't need NetBSD-1.6 binary compatibility. */
diff --git a/lib/nbsd_libc/compat/arch/x86_64/sys/compat_msgctl.S b/lib/nbsd_libc/compat/arch/x86_64/sys/compat_msgctl.S
new file mode 100644 (file)
index 0000000..a5598b0
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_msgctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(msgctl, \
+    "warning: reference to compatibility msgctl(); include <sys/msg.h> for correct reference")
+
+PSEUDO(msgctl,compat_14_msgctl)
diff --git a/lib/nbsd_libc/compat/arch/x86_64/sys/compat_shmctl.S b/lib/nbsd_libc/compat/arch/x86_64/sys/compat_shmctl.S
new file mode 100644 (file)
index 0000000..a9f938c
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_shmctl.S,v 1.2 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(shmctl, \
+    "warning: reference to compatibility shmctl(); include <sys/shm.h> for correct reference")
+
+PSEUDO(shmctl,compat_14_shmctl)
diff --git a/lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigaction.S b/lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigaction.S
new file mode 100644 (file)
index 0000000..7d77843
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: compat_sigaction.S,v 1.2 2008/04/28 20:22:59 martin Exp $      */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "SYS.h"
+
+WARN_REFERENCES(sigaction, \
+    "warning: reference to compatibility sigaction(); include <signal.h> for correct reference")
+
+PSEUDO(sigaction,compat_13_sigaction13)
diff --git a/lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigpending.S b/lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigpending.S
new file mode 100644 (file)
index 0000000..d368146
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: compat_sigpending.S,v 1.1 2006/03/11 18:59:21 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigpending.s  5.1 (Berkeley) 7/1/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigpending.S,v 1.1 2006/03/11 18:59:21 christos Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigpending, \
+    "warning: reference to compatibility sigpending(); include <signal.h> for correct reference")
+
+_SYSCALL(sigpending,compat_13_sigpending13)
+       movl    %eax,(%rdi)             # store old mask
+       xorl    %eax,%eax
+       ret
diff --git a/lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigprocmask.S b/lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigprocmask.S
new file mode 100644 (file)
index 0000000..db21a72
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: compat_sigprocmask.S,v 1.1 2006/03/11 18:59:21 christos Exp $  */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigprocmask.s 5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigprocmask.S,v 1.1 2006/03/11 18:59:21 christos Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigprocmask, \
+    "warning: reference to compatibility sigprocmask(); include <signal.h> for correct reference")
+
+ENTRY(sigprocmask)
+       testq   %rsi,%rsi               # check new sigset pointer
+       jnz     1f                      # if not null, indirect
+       movl    $1,%edi                 # SIG_BLOCK
+       jmp     2f
+1:     movl    (%rsi),%esi             # fetch indirect  ...
+2:     SYSTRAP(compat_13_sigprocmask13)
+       jc      err
+       testq   %rdx,%rdx               # test if old mask requested
+       jz      out
+       movq    %rax,(%rdx)             # store old mask
+out:
+       xorl    %eax,%eax
+       ret
+err:
+#ifdef PIC
+       movq    PIC_GOT(CERROR), %rcx
+       jmp     *%rcx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigreturn.S b/lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigreturn.S
new file mode 100644 (file)
index 0000000..bdfb76b
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: compat_sigreturn.S,v 1.1 2006/03/11 18:59:21 christos Exp $    */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigreturn.s   5.2 (Berkeley) 12/17/90"
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigreturn.S,v 1.1 2006/03/11 18:59:21 christos Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+/* Nothing here. We don't need NetBSD-1.3 binary compatibility. */
diff --git a/lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigsuspend.S b/lib/nbsd_libc/compat/arch/x86_64/sys/compat_sigsuspend.S
new file mode 100644 (file)
index 0000000..f5ee4d6
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: compat_sigsuspend.S,v 1.1 2006/03/11 18:59:21 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * 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. 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.
+ *
+ *     from: @(#)sigsuspend.s  5.2 (Berkeley) 12/17/90
+ */
+
+#include <machine/asm.h>
+#if defined(SYSLIBC_SCCS) && !defined(lint)
+       RCSID("$NetBSD: compat_sigsuspend.S,v 1.1 2006/03/11 18:59:21 christos Exp $")
+#endif /* SYSLIBC_SCCS and not lint */
+
+#include "SYS.h"
+
+WARN_REFERENCES(sigsuspend, \
+    "warning: reference to compatibility sigsuspend(); include <signal.h> for correct reference")
+
+ENTRY(sigsuspend)
+       movl    (%rdi),%edi             # indirect to mask arg
+       SYSTRAP(compat_13_sigsuspend13)
+       jc      err
+       xorl    %eax,%eax               # shouldn t happen
+       ret
+err:
+#ifdef PIC
+       movq    PIC_GOT(CERROR), %rcx
+       jmp     *%rcx
+#else
+       jmp     CERROR
+#endif
diff --git a/lib/nbsd_libc/compat/db/Makefile.inc b/lib/nbsd_libc/compat/db/Makefile.inc
new file mode 100644 (file)
index 0000000..91236ce
--- /dev/null
@@ -0,0 +1,2 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/03/11 21:07:18 christos Exp $
+.include "${COMPATDIR}/db/hash/Makefile.inc"
diff --git a/lib/nbsd_libc/compat/db/hash/Makefile.inc b/lib/nbsd_libc/compat/db/hash/Makefile.inc
new file mode 100644 (file)
index 0000000..b801df5
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/03/11 21:07:18 christos Exp $
+
+.PATH: ${COMPATDIR}/db/hash
+SRCS+=compat_ndbmdatum.c
diff --git a/lib/nbsd_libc/compat/db/hash/compat_ndbmdatum.c b/lib/nbsd_libc/compat/db/hash/compat_ndbmdatum.c
new file mode 100644 (file)
index 0000000..098e0e8
--- /dev/null
@@ -0,0 +1,31 @@
+/*     $NetBSD: compat_ndbmdatum.c,v 1.1 2005/09/13 01:44:09 christos Exp $    */
+
+/*
+ * Written by Klaus Klein <kleink@NetBSD.org>, April 28, 2004.
+ * Public domain.
+ */
+
+#define __LIBC12_SOURCE__
+#include "namespace.h"
+#include <sys/cdefs.h>
+#include <ndbm.h>
+#include <compat/include/ndbm.h>
+
+__warn_references(dbm_delete,
+    "warning: reference to compatibility dbm_delete();"
+    " include <ndbm.h> for correct reference")
+__warn_references(dbm_fetch,
+    "warning: reference to compatibility dbm_fetch();"
+    " include <ndbm.h> for correct reference")
+__warn_references(dbm_firstkey,
+    "warning: reference to compatibility dbm_firstkey();"
+    " include <ndbm.h> for correct reference")
+__warn_references(dbm_nextkey,
+    "warning: reference to compatibility dbm_nextkey();"
+    " include <ndbm.h> for correct reference")
+__warn_references(dbm_store,
+    "warning: reference to compatibility dbm_store();"
+    " include <ndbm.h> for correct reference")
+
+#define datum datum12
+#include "db/hash/ndbmdatum.c"
diff --git a/lib/nbsd_libc/compat/gen/Makefile.inc b/lib/nbsd_libc/compat/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..501a8df
--- /dev/null
@@ -0,0 +1,11 @@
+#      $NetBSD: Makefile.inc,v 1.13 2010/04/23 19:04:54 drochner Exp $
+
+.PATH: ${COMPATDIR}/gen
+SRCS+=compat_errlist.c compat_fts.c compat___fts13.c compat___fts30.c \
+    compat___fts31.c compat_getmntinfo.c compat_glob.c compat___glob13.c \
+    compat_opendir.c compat_readdir.c compat__readdir_unlocked30.c \
+    compat_scandir.c compat_siglist.c compat_signame.c compat_sigsetops.c \
+    compat_times.c compat_timezone.c compat_unvis.c compat_utmpx.c \
+    compat__sys_errlist.c compat__sys_nerr.c compat__sys_siglist.c \
+    compat_time.c compat_utime.c compat_devname.c compat_alphasort.c \
+    compat_getpwent.c compat___fts32.c compat_utmp.c compat___fts50.c
diff --git a/lib/nbsd_libc/compat/gen/compat___fts13.c b/lib/nbsd_libc/compat/gen/compat___fts13.c
new file mode 100644 (file)
index 0000000..f39a624
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: compat___fts13.c,v 1.6 2009/10/19 17:52:01 christos Exp $      */
+
+#include "namespace.h"
+#include <sys/cdefs.h>
+#include <dirent.h>
+
+#define        __LIBC12_SOURCE__
+
+__warn_references(__fts_children13,
+    "warning: reference to compatibility __fts_children13();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_close13,
+    "warning: reference to compatibility __fts_close13();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_open13,
+    "warning: reference to compatibility __fts_open13();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_read13,
+    "warning: reference to compatibility __fts_read13();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_set13,
+    "warning: reference to compatibility __fts_set13();"
+    " include <fts.h> for correct reference")
+
+#include <sys/stat.h>
+#include <compat/sys/time.h>
+#include <compat/sys/stat.h>
+
+#define        __fts_stat_t    struct stat13
+#define        __fts_ino_t     u_int32_t
+#define        __fts_length_t  u_short
+#define        __fts_number_t  long
+#define        __fts_dev_t     uint32_t
+#define        __fts_level_t   short
+
+#define        stat            __stat13
+#define        lstat           __lstat13
+#define        fstat           __fstat13
+
+#undef fts_children
+#define        fts_children __fts_children13
+#undef fts_close
+#define        fts_close __fts_close13
+#undef fts_open
+#define        fts_open  __fts_open13
+#undef fts_read
+#define        fts_read __fts_read13
+#undef fts_set
+#define        fts_set __fts_set13
+
+#include <fts.h>
+#include <compat/include/fts.h>
+
+#define        __FTS_COMPAT_TAILINGSLASH
+#define        __FTS_COMPAT_LENGTH
+#define        __FTS_COMPAT_LEVEL
+
+#include "gen/fts.c"
diff --git a/lib/nbsd_libc/compat/gen/compat___fts30.c b/lib/nbsd_libc/compat/gen/compat___fts30.c
new file mode 100644 (file)
index 0000000..03ec5ce
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: compat___fts30.c,v 1.3 2009/10/19 17:52:04 christos Exp $      */
+
+#include "namespace.h"
+#include <sys/cdefs.h>
+#include <dirent.h>
+
+#define        __LIBC12_SOURCE__
+
+__warn_references(__fts_children30,
+    "warning: reference to compatibility __fts_children30();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_close30,
+    "warning: reference to compatibility __fts_close30();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_open30,
+    "warning: reference to compatibility __fts_open30();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_read30,
+    "warning: reference to compatibility __fts_read30();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_set30,
+    "warning: reference to compatibility __fts_set30();"
+    " include <fts.h> for correct reference")
+
+#include <sys/stat.h>
+#include <compat/sys/time.h>
+#include <compat/sys/stat.h>
+
+#define        __fts_stat_t    struct stat30
+#define        __fts_length_t  u_short
+#define        __fts_number_t  long
+#define        __fts_dev_t     uint32_t
+#define        __fts_level_t   short
+
+#define        stat            __stat30
+#define        lstat           __lstat30
+#define        fstat           __fstat30
+
+#undef fts_children
+#define        fts_children __fts_children30
+#undef fts_close
+#define        fts_close __fts_close30
+#undef fts_open
+#define        fts_open  __fts_open30
+#undef fts_read
+#define        fts_read __fts_read30
+#undef fts_set
+#define        fts_set __fts_set30
+
+#include <fts.h>
+#include <compat/include/fts.h>
+
+#define        __FTS_COMPAT_LENGTH
+#define        __FTS_COMPAT_LEVEL
+
+#include "gen/fts.c"
diff --git a/lib/nbsd_libc/compat/gen/compat___fts31.c b/lib/nbsd_libc/compat/gen/compat___fts31.c
new file mode 100644 (file)
index 0000000..ea51847
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: compat___fts31.c,v 1.2 2009/10/19 17:52:05 christos Exp $      */
+
+#include "namespace.h"
+#include <sys/cdefs.h>
+#include <dirent.h>
+
+#define        __LIBC12_SOURCE__
+
+__warn_references(__fts_children31,
+    "warning: reference to compatibility __fts_children31();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_close31,
+    "warning: reference to compatibility __fts_close31();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_open31,
+    "warning: reference to compatibility __fts_open31();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_read31,
+    "warning: reference to compatibility __fts_read31();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_set31,
+    "warning: reference to compatibility __fts_set31();"
+    " include <fts.h> for correct reference")
+
+#include <sys/stat.h>
+#include <compat/sys/time.h>
+#include <compat/sys/stat.h>
+
+#define        __fts_stat_t    struct stat30
+#define        __fts_number_t  long
+#define        __fts_dev_t     uint32_t
+#define        __fts_level_t   short
+
+#define        stat            __stat30
+#define        lstat           __lstat30
+#define        fstat           __fstat30
+
+#undef fts_children
+#define        fts_children __fts_children31
+#undef fts_close
+#define        fts_close __fts_close31
+#undef fts_open
+#define        fts_open  __fts_open31
+#undef fts_read
+#define        fts_read __fts_read31
+#undef fts_set
+#define        fts_set __fts_set31
+
+#include <fts.h>
+#include <compat/include/fts.h>
+
+#define        __FTS_COMPAT_LEVEL
+
+#include "gen/fts.c"
diff --git a/lib/nbsd_libc/compat/gen/compat___fts32.c b/lib/nbsd_libc/compat/gen/compat___fts32.c
new file mode 100644 (file)
index 0000000..99c7388
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: compat___fts32.c,v 1.3 2009/10/19 17:52:05 christos Exp $      */
+
+#include "namespace.h"
+#include <sys/cdefs.h>
+#include <dirent.h>
+
+#define        __LIBC12_SOURCE__
+__warn_references(__fts_children32,
+    "warning: reference to compatibility __fts_children32();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_close32,
+    "warning: reference to compatibility __fts_close32();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_open32,
+    "warning: reference to compatibility __fts_open32();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_read32,
+    "warning: reference to compatibility __fts_read32();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_set32,
+    "warning: reference to compatibility __fts_set32();"
+    " include <fts.h> for correct reference")
+
+#define        __fts_stat_t    struct stat30
+#define        __fts_dev_t     uint32_t
+#define        __fts_level_t   short
+
+#undef fts_children
+#define        fts_children __fts_children32
+#undef fts_close
+#define        fts_close __fts_close32
+#undef fts_open
+#define        fts_open  __fts_open32
+#undef fts_read
+#define        fts_read __fts_read32
+#undef fts_set
+#define        fts_set __fts_set32
+
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <sys/stat.h>
+#include <compat/sys/stat.h>
+
+#include <fts.h>
+#include <compat/include/fts.h>
+
+#define        __FTS_COMPAT_LEVEL
+
+#define        stat            __stat30
+#define        lstat           __lstat30
+#define        fstat           __fstat30
+
+#include "gen/fts.c"
diff --git a/lib/nbsd_libc/compat/gen/compat___fts50.c b/lib/nbsd_libc/compat/gen/compat___fts50.c
new file mode 100644 (file)
index 0000000..dbf913b
--- /dev/null
@@ -0,0 +1,43 @@
+/*     $NetBSD: compat___fts50.c,v 1.2 2009/10/19 17:52:05 christos Exp $      */
+
+#include "namespace.h"
+#include <sys/cdefs.h>
+#include <dirent.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+
+#define __LIBC12_SOURCE__
+__warn_references(__fts_children50,
+    "warning: reference to compatibility __fts_children50();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_close50,
+    "warning: reference to compatibility __fts_close50();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_open50,
+    "warning: reference to compatibility __fts_open50();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_read50,
+    "warning: reference to compatibility __fts_read50();"
+    " include <fts.h> for correct reference")
+__warn_references(__fts_set50,
+    "warning: reference to compatibility __fts_set50();"
+    " include <fts.h> for correct reference")
+
+#define        __fts_level_t   short
+#undef fts_children
+#define        fts_children __fts_children50
+#undef fts_close
+#define        fts_close __fts_close50
+#undef fts_open
+#define        fts_open  __fts_open50
+#undef fts_read
+#define        fts_read __fts_read50
+#undef fts_set
+#define        fts_set __fts_set50
+
+#include <fts.h>
+#include <compat/include/fts.h>
+
+#define        __FTS_COMPAT_LEVEL
+
+#include "gen/fts.c"
diff --git a/lib/nbsd_libc/compat/gen/compat___glob13.c b/lib/nbsd_libc/compat/gen/compat___glob13.c
new file mode 100644 (file)
index 0000000..f3ea45b
--- /dev/null
@@ -0,0 +1,27 @@
+/*     $NetBSD: compat___glob13.c,v 1.2 2009/01/11 02:46:25 christos Exp $     */
+
+/*
+ * Written by Jason R. Thorpe <thorpej@NetBSD.org>, October 21, 1997.
+ * Public domain.
+ */
+#include "namespace.h"
+#include <pwd.h>
+#include <sys/stat.h>
+#include <dirent.h>
+#define __gl_size_t int
+
+#define __LIBC12_SOURCE__
+__warn_references(__glob13,
+    "warning: reference to compatibility __glob13(); include <glob.h> for correct reference")
+__warn_references(__globfree13,
+    "warning: reference to compatibility __globfree13(); include <glob.h> for correct reference")
+
+#undef glob
+#undef globfree
+#define glob __glob13
+#define globfree __globfree13
+
+#include <glob.h>
+#include <compat/include/glob.h>
+
+#include "gen/glob.c"
diff --git a/lib/nbsd_libc/compat/gen/compat__readdir_unlocked30.c b/lib/nbsd_libc/compat/gen/compat__readdir_unlocked30.c
new file mode 100644 (file)
index 0000000..df6fe22
--- /dev/null
@@ -0,0 +1,20 @@
+/*     $NetBSD: compat__readdir_unlocked30.c,v 1.1 2008/05/04 18:53:26 tonnerre Exp $  */
+
+#define __LIBC12_SOURCE__
+#include "namespace.h"
+#include <dirent.h>
+#include <compat/include/dirent.h>
+
+#ifdef __warn_references
+__warn_references(___readdir_unlocked30,
+    "warning: reference to compatibility _readdir_unlocked(); include <dirent.h> for correct reference")
+#endif
+
+/**     
+ * Compat version of _readdir_unlocked which always skips directories
+ */
+struct dirent *
+___readdir_unlocked30(DIR *dirp)
+{
+       return ___readdir_unlocked50(dirp, 1);
+}
diff --git a/lib/nbsd_libc/compat/gen/compat__sys_errlist.c b/lib/nbsd_libc/compat/gen/compat__sys_errlist.c
new file mode 100644 (file)
index 0000000..b4b3432
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: compat__sys_errlist.c,v 1.1 2005/09/13 01:44:09 christos Exp $ */
+
+/*
+ * Written by J.T. Conklin, December 12, 1994
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat__sys_errlist.c,v 1.1 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+__warn_references(sys_errlist,
+    "warning: reference to compatibility sys_errlist[]; include <errno.h> for correct reference")
+__warn_references(__sys_errlist,
+    "warning: reference to deprecated __sys_errlist[]; include <errno.h> and use sys_errlist")
+
+__warn_references(sys_nerr,
+    "warning: reference to compatibility sys_nerr; include <errno.h> for correct reference")
+__warn_references(__sys_nerr,
+    "warning: reference to deprecated __sys_nerr; include <errno.h> and use sys_nerr")
+
+#if defined(__indr_reference)
+__indr_reference(_sys_errlist, sys_errlist)
+__indr_reference(_sys_errlist, __sys_errlist) /* Backwards compat with v.12 */
+#else
+
+#undef _sys_errlist
+#undef _sys_nerr
+#undef rcsid
+#define        _sys_errlist    sys_errlist
+#define        _sys_nerr       sys_nerr
+#define        rcsid           _rcsid
+#include "__errlist.c"
+
+#undef _sys_errlist
+#undef _sys_nerr
+#undef rcsid
+#define        _sys_errlist    __sys_errlist
+#define        _sys_nerr       __sys_nerr
+#define        rcsid           __rcsid
+#include "__errlist.c"
+
+#endif
diff --git a/lib/nbsd_libc/compat/gen/compat__sys_nerr.c b/lib/nbsd_libc/compat/gen/compat__sys_nerr.c
new file mode 100644 (file)
index 0000000..7d09586
--- /dev/null
@@ -0,0 +1,17 @@
+/*     $NetBSD: compat__sys_nerr.c,v 1.1 2005/09/13 01:44:09 christos Exp $    */
+
+/*
+ * Written by J.T. Conklin, December 12, 1994
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat__sys_nerr.c,v 1.1 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference) && !defined(__lint__)
+__indr_reference(_sys_nerr, sys_nerr)
+__indr_reference(_sys_nerr, __sys_nerr) /* Backwards compat with v.12 */
+#endif
+/* LINTED empty translation unit */
diff --git a/lib/nbsd_libc/compat/gen/compat__sys_siglist.c b/lib/nbsd_libc/compat/gen/compat__sys_siglist.c
new file mode 100644 (file)
index 0000000..54435bf
--- /dev/null
@@ -0,0 +1,35 @@
+/*     $NetBSD: compat__sys_siglist.c,v 1.1 2005/09/13 01:44:09 christos Exp $ */
+
+/*
+ * Written by J.T. Conklin, December 12, 1994
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat__sys_siglist.c,v 1.1 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+__warn_references(sys_siglist,
+    "warning: reference to compatibility sys_siglist[]; include <signal.h> or <unistd.h> for correct reference")
+__warn_references(__sys_siglist,
+    "warning: reference to deprecated __sys_siglist[]; include <signal.h> or <unistd.h> and use sys_siglist")
+
+#if defined(__indr_reference) && !defined(__lint__)
+__indr_reference(_sys_siglist, sys_siglist)
+__indr_reference(_sys_siglist, __sys_siglist) /* Backwards compat with v.12 */
+#else
+
+#undef _sys_siglist
+#undef rcsid
+#define        _sys_siglist    sys_siglist
+#define        rcsid           _rcsid
+#include "compat_siglist.c"
+
+#undef _sys_siglist
+#undef rcsid
+#define        _sys_siglist    __sys_siglist
+#define        rcsid           __rcsid
+#include "compat_siglist.c"
+
+#endif
diff --git a/lib/nbsd_libc/compat/gen/compat_alphasort.c b/lib/nbsd_libc/compat/gen/compat_alphasort.c
new file mode 100644 (file)
index 0000000..2520171
--- /dev/null
@@ -0,0 +1,20 @@
+/*     $NetBSD: compat_alphasort.c,v 1.1 2009/02/24 18:42:36 christos Exp $    */
+
+#include <sys/stat.h>
+#define __LIBC12_SOURCE__
+#include "namespace.h"
+#include <dirent.h>
+#include <compat/include/dirent.h>
+
+#ifdef __weak_alias
+__weak_alias(alphasort,_alphasort)
+#endif
+
+#ifdef __warn_references
+__warn_references(alphasort,
+    "warning: reference to compatibility alphasort(); include <dirent.h> for correct reference")
+#endif
+
+#define dirent dirent12
+
+#include "gen/alphasort.c"
diff --git a/lib/nbsd_libc/compat/gen/compat_devname.c b/lib/nbsd_libc/compat/gen/compat_devname.c
new file mode 100644 (file)
index 0000000..399c002
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: compat_devname.c,v 1.2 2009/01/11 02:46:25 christos Exp $      */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_devname.c,v 1.2 2009/01/11 02:46:25 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <stdint.h>
+#include <stdlib.h>
+#include <compat/include/stdlib.h>
+
+__warn_references(devname,
+    "warning: reference to compatibility devname(); include <stdlib.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(devname, _devname)
+#endif
+
+__aconst char *
+devname(int32_t dev, mode_t mode)
+{
+       return __devname50(dev, mode);
+}
diff --git a/lib/nbsd_libc/compat/gen/compat_errlist.c b/lib/nbsd_libc/compat/gen/compat_errlist.c
new file mode 100644 (file)
index 0000000..7c8c8cb
--- /dev/null
@@ -0,0 +1,153 @@
+/*     $NetBSD: compat_errlist.c,v 1.2 2006/10/31 00:38:07 cbiere Exp $        */
+
+/*
+ * Copyright (c) 1982, 1985, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)errlst.c   8.2 (Berkeley) 11/16/93";
+#else
+__RCSID("$NetBSD: compat_errlist.c,v 1.2 2006/10/31 00:38:07 cbiere Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#define __LIBC12_SOURCE__
+#include <errno.h>
+#ifdef __weak_alias
+__weak_alias(sys_errlist, _sys_errlist)
+__weak_alias(__sys_errlist, _sys_errlist)
+__weak_alias(sys_nerr, _sys_nerr)
+__weak_alias(__sys_nerr, _sys_nerr)
+#endif
+
+const char *const sys_errlist[] = {
+       "Undefined error: 0",                   /*  0 - ENOERROR */
+       "Operation not permitted",              /*  1 - EPERM */
+       "No such file or directory",            /*  2 - ENOENT */
+       "No such process",                      /*  3 - ESRCH */
+       "Interrupted system call",              /*  4 - EINTR */
+       "Input/output error",                   /*  5 - EIO */
+       "Device not configured",                /*  6 - ENXIO */
+       "Argument list too long",               /*  7 - E2BIG */
+       "Exec format error",                    /*  8 - ENOEXEC */
+       "Bad file descriptor",                  /*  9 - EBADF */
+       "No child processes",                   /* 10 - ECHILD */
+       "Resource deadlock avoided",            /* 11 - EDEADLK */
+       "Cannot allocate memory",               /* 12 - ENOMEM */
+       "Permission denied",                    /* 13 - EACCES */
+       "Bad address",                          /* 14 - EFAULT */
+       "Block device required",                /* 15 - ENOTBLK */
+       "Device busy",                          /* 16 - EBUSY */
+       "File exists",                          /* 17 - EEXIST */
+       "Cross-device link",                    /* 18 - EXDEV */
+       "Operation not supported by device",    /* 19 - ENODEV */
+       "Not a directory",                      /* 20 - ENOTDIR */
+       "Is a directory",                       /* 21 - EISDIR */
+       "Invalid argument",                     /* 22 - EINVAL */
+       "Too many open files in system",        /* 23 - ENFILE */
+       "Too many open files",                  /* 24 - EMFILE */
+       "Inappropriate ioctl for device",       /* 25 - ENOTTY */
+       "Text file busy",                       /* 26 - ETXTBSY */
+       "File too large",                       /* 27 - EFBIG */
+       "No space left on device",              /* 28 - ENOSPC */
+       "Illegal seek",                         /* 29 - ESPIPE */
+       "Read-only file system",                /* 30 - EROFS */
+       "Too many links",                       /* 31 - EMLINK */
+       "Broken pipe",                          /* 32 - EPIPE */
+
+/* math software */
+       "Numerical argument out of domain",     /* 33 - EDOM */
+       "Result too large or too small",        /* 34 - ERANGE */
+
+/* non-blocking and interrupt i/o */
+       "Resource temporarily unavailable",     /* 35 - EAGAIN */
+                                               /* 35 - EWOULDBLOCK */
+       "Operation now in progress",            /* 36 - EINPROGRESS */
+       "Operation already in progress",        /* 37 - EALREADY */
+
+/* ipc/network software -- argument errors */
+       "Socket operation on non-socket",       /* 38 - ENOTSOCK */
+       "Destination address required",         /* 39 - EDESTADDRREQ */
+       "Message too long",                     /* 40 - EMSGSIZE */
+       "Protocol wrong type for socket",       /* 41 - EPROTOTYPE */
+       "Protocol option not available",        /* 42 - ENOPROTOOPT */
+       "Protocol not supported",               /* 43 - EPROTONOSUPPORT */
+       "Socket type not supported",            /* 44 - ESOCKTNOSUPPORT */
+       "Operation not supported",              /* 45 - EOPNOTSUPP */
+       "Protocol family not supported",        /* 46 - EPFNOSUPPORT */
+                                               /* 47 - EAFNOSUPPORT */
+       "Address family not supported by protocol family",
+       "Address already in use",               /* 48 - EADDRINUSE */
+       "Can't assign requested address",       /* 49 - EADDRNOTAVAIL */
+
+/* ipc/network software -- operational errors */
+       "Network is down",                      /* 50 - ENETDOWN */
+       "Network is unreachable",               /* 51 - ENETUNREACH */
+       "Network dropped connection on reset",  /* 52 - ENETRESET */
+       "Software caused connection abort",     /* 53 - ECONNABORTED */
+       "Connection reset by peer",             /* 54 - ECONNRESET */
+       "No buffer space available",            /* 55 - ENOBUFS */
+       "Socket is already connected",          /* 56 - EISCONN */
+       "Socket is not connected",              /* 57 - ENOTCONN */
+       "Can't send after socket shutdown",     /* 58 - ESHUTDOWN */
+       "Too many references: can't splice",    /* 59 - ETOOMANYREFS */
+       "Operation timed out",                  /* 60 - ETIMEDOUT */
+       "Connection refused",                   /* 61 - ECONNREFUSED */
+
+       "Too many levels of symbolic links",    /* 62 - ELOOP */
+       "File name too long",                   /* 63 - ENAMETOOLONG */
+
+/* should be rearranged */
+       "Host is down",                         /* 64 - EHOSTDOWN */
+       "No route to host",                     /* 65 - EHOSTUNREACH */
+       "Directory not empty",                  /* 66 - ENOTEMPTY */
+
+/* quotas & mush */
+       "Too many processes",                   /* 67 - EPROCLIM */
+       "Too many users",                       /* 68 - EUSERS */
+       "Disc quota exceeded",                  /* 69 - EDQUOT */
+
+/* Network File System */
+       "Stale NFS file handle",                /* 70 - ESTALE */
+       "Too many levels of remote in path",    /* 71 - EREMOTE */
+       "RPC struct is bad",                    /* 72 - EBADRPC */
+       "RPC version wrong",                    /* 73 - ERPCMISMATCH */
+       "RPC prog. not avail",                  /* 74 - EPROGUNAVAIL */
+       "Program version wrong",                /* 75 - EPROGMISMATCH */
+       "Bad procedure for program",            /* 76 - EPROCUNAVAIL */
+
+       "No locks available",                   /* 77 - ENOLCK */
+       "Function not implemented",             /* 78 - ENOSYS */
+
+       "Inappropriate file type or format",    /* 79 - EFTYPE */
+};
+const int sys_nerr = { sizeof(sys_errlist) / sizeof(sys_errlist[0]) };
diff --git a/lib/nbsd_libc/compat/gen/compat_frexp_ieee754.c b/lib/nbsd_libc/compat/gen/compat_frexp_ieee754.c
new file mode 100644 (file)
index 0000000..947039b
--- /dev/null
@@ -0,0 +1,83 @@
+/* $NetBSD: compat_frexp_ieee754.c,v 1.5 2010/04/23 19:04:54 drochner Exp $ */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: frexp.c,v 1.1 91/07/07 04:45:01 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)frexp.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: compat_frexp_ieee754.c,v 1.5 2010/04/23 19:04:54 drochner Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <machine/ieee.h>
+
+double frexp(double, int *);
+
+/*
+ * Split the given value into a fraction in the range [0.5, 1.0) and
+ * an exponent, such that frac * (2^exp) == value.  If value is 0,
+ * return 0.
+ */
+double
+frexp(double value, int *eptr)
+{
+       union ieee_double_u u;
+
+       if (value) {
+               /*
+                * Fractions in [0.5..1.0) have an exponent of 2^-1.
+                * Leave Inf and NaN alone, however.
+                */
+               u.dblu_d = value;
+               if (u.dblu_dbl.dbl_exp != DBL_EXP_INFNAN) {
+                       *eptr = 0;
+                       if (u.dblu_dbl.dbl_exp == 0) {
+                               /* denormal, scale out of mantissa */
+                               *eptr = -DBL_FRACBITS;
+                               u.dblu_d *= 4.50359962737049600000e+15;
+                       }
+                       *eptr += u.dblu_dbl.dbl_exp - (DBL_EXP_BIAS - 1);
+                       u.dblu_dbl.dbl_exp = DBL_EXP_BIAS - 1;
+               }
+               return (u.dblu_d);
+       } else {
+               *eptr = 0;
+               return (value);
+       }
+}
diff --git a/lib/nbsd_libc/compat/gen/compat_fts.c b/lib/nbsd_libc/compat/gen/compat_fts.c
new file mode 100644 (file)
index 0000000..b3bfdce
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: compat_fts.c,v 1.4 2009/10/19 17:52:05 christos Exp $  */
+
+/*
+ * Written by Jason R. Thorpe <thorpej@NetBSD.org>, October 21, 1997.
+ * Public domain.
+ */
+
+#include "namespace.h"
+#include <sys/cdefs.h>
+#include <dirent.h>
+
+#define        __LIBC12_SOURCE__
+#include <sys/stat.h>
+#include <compat/sys/time.h>
+#include <compat/sys/stat.h>
+
+#define        __fts_stat_t    struct stat12
+#define        __fts_nlink_t   u_int16_t
+#define        __fts_ino_t     u_int32_t
+#define        __fts_length_t  unsigned short
+#define        __fts_number_t  long
+#define        __fts_dev_t     uint32_t
+#define        __fts_level_t   short
+
+#include <fts.h>
+#include <compat/include/fts.h>
+
+#ifdef __weak_alias
+__weak_alias(fts_children,_fts_children)
+__weak_alias(fts_close,_fts_close)
+__weak_alias(fts_open,_fts_open)
+__weak_alias(fts_read,_fts_read)
+__weak_alias(fts_set,_fts_set)
+#endif /* __weak_alias */
+
+__warn_references(fts_children,
+    "warning: reference to compatibility fts_children();"
+    " include <fts.h> for correct reference")
+__warn_references(fts_close,
+    "warning: reference to compatibility fts_close();"
+    " include <fts.h> for correct reference")
+__warn_references(fts_open,
+    "warning: reference to compatibility fts_open();"
+    " include <fts.h> for correct reference")
+__warn_references(fts_read,
+    "warning: reference to compatibility fts_read();"
+    " include <fts.h> for correct reference")
+__warn_references(fts_set,
+    "warning: reference to compatibility fts_set();"
+    " include <fts.h> for correct reference")
+
+#define        __FTS_COMPAT_TAILINGSLASH
+#define        __FTS_COMPAT_LENGTH
+#define        __FTS_COMPAT_LEVEL
+
+#include "gen/fts.c"
diff --git a/lib/nbsd_libc/compat/gen/compat_getmntinfo.c b/lib/nbsd_libc/compat/gen/compat_getmntinfo.c
new file mode 100644 (file)
index 0000000..3db1895
--- /dev/null
@@ -0,0 +1,88 @@
+/*     $NetBSD: compat_getmntinfo.c,v 1.1 2005/09/13 01:44:09 christos Exp $   */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getmntinfo.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: compat_getmntinfo.c,v 1.1 2005/09/13 01:44:09 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/ucred.h>
+#include <sys/mount.h>
+#include <compat/sys/mount.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(getmntinfo,_getmntinfo)
+#endif
+
+/*
+ * Return information about mounted filesystems.
+ */
+int
+getmntinfo(mntbufp, flags)
+       struct statfs12 **mntbufp;
+       int flags;
+{
+       static struct statfs12 *mntbuf;
+       static int mntsize;
+       static size_t bufsize;
+
+       _DIAGASSERT(mntbufp != NULL);
+
+       if (mntsize <= 0 &&
+           (mntsize = getfsstat(NULL, 0L, MNT_NOWAIT)) == -1)
+               return (0);
+       if (bufsize > 0 &&
+           (mntsize = getfsstat(mntbuf, (long)bufsize, flags)) == -1)
+               return (0);
+       while (bufsize <= mntsize * sizeof(struct statfs12)) {
+               if (mntbuf)
+                       free(mntbuf);
+               bufsize = (mntsize + 1) * sizeof(struct statfs12);
+               if ((mntbuf = malloc(bufsize)) == NULL)
+                       return (0);
+               if ((mntsize = getfsstat(mntbuf, (long)bufsize, flags)) == -1)
+                       return (0);
+       }
+       *mntbufp = mntbuf;
+       return (mntsize);
+}
diff --git a/lib/nbsd_libc/compat/gen/compat_getpwent.c b/lib/nbsd_libc/compat/gen/compat_getpwent.c
new file mode 100644 (file)
index 0000000..886f495
--- /dev/null
@@ -0,0 +1,187 @@
+/*     $NetBSD: compat_getpwent.c,v 1.3 2009/06/01 06:04:37 yamt Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_getpwent.c,v 1.3 2009/06/01 06:04:37 yamt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <stdint.h>
+#include <stdlib.h>
+#include <pwd.h>
+#include <compat/include/pwd.h>
+
+__warn_references(getpwuid,
+    "warning: reference to compatibility getpwuid(); include <pwd.h> to generate correct reference")
+__warn_references(getpwnam,
+    "warning: reference to compatibility getpwnam(); include <pwd.h> to generate correct reference")
+__warn_references(getpwnam_r,
+    "warning: reference to compatibility getpwnam_r(); include <pwd.h> to generate correct reference")
+__warn_references(getpwuid_r,
+    "warning: reference to compatibility getpwuid_r(); include <pwd.h> to generate correct reference")
+__warn_references(getpwent,
+    "warning: reference to compatibility getpwent(); include <pwd.h> to generate correct reference")
+#ifdef notdef /* for libutil */
+__warn_references(pw_scan,
+    "warning: reference to compatibility pw_scan(); include <pwd.h> to generate correct reference")
+#endif
+__warn_references(getpwent_r,
+    "warning: reference to compatibility getpwent_r(); include <pwd.h> to generate correct reference")
+__warn_references(pwcache_userdb,
+    "warning: reference to compatibility pwcache_userdb(); include <pwd.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(getpwent, _getpwent)
+__weak_alias(getpwent_r, _getpwent_r)
+__weak_alias(getpwuid, _getpwuid)
+__weak_alias(getpwuid_r, _getpwuid_r)
+__weak_alias(getpwnam, _getpwnam)
+__weak_alias(getpwnam_r, _getpwnam_r)
+__weak_alias(pwcache_userdb, _pwcache_userdb)
+#endif
+
+static struct passwd50 *
+cvt(struct passwd *p)
+{
+       struct passwd50 *q = (void *)p;
+
+       if (q == NULL) {
+               return NULL;
+       }
+       q->pw_change = (int32_t)p->pw_change;
+       q->pw_class = p->pw_class;
+       q->pw_gecos = p->pw_gecos;
+       q->pw_dir = p->pw_dir;
+       q->pw_shell = p->pw_shell;
+       q->pw_expire = (int32_t)p->pw_expire;
+       return q;
+}
+
+struct passwd50        *
+getpwuid(uid_t uid)
+{
+       return cvt(__getpwuid50(uid));
+
+}
+
+struct passwd50        *
+getpwnam(const char *name)
+{
+       return cvt(__getpwnam50(name));
+}
+
+int
+getpwnam_r(const char *name , struct passwd50 *p, char *buf, size_t len,
+    struct passwd50 **q)
+{
+       struct passwd px, *qx;
+       int rv = __getpwnam_r50(name, &px, buf, len, &qx);
+       *q = p;
+       passwd_to_passwd50(&px, p);
+       return rv;
+}
+
+int
+getpwuid_r(uid_t uid, struct passwd50 *p, char *buf, size_t len,
+    struct passwd50 **q)
+{
+       struct passwd px, *qx;
+       int rv = __getpwuid_r50(uid, &px, buf, len, &qx);
+       *q = p;
+       passwd_to_passwd50(&px, p);
+       return rv;
+}
+
+struct passwd50        *
+getpwent(void)
+{
+       return cvt(__getpwent50());
+}
+
+#ifdef notdef /* for libutil */
+int
+pw_scan(char *buf, struct passwd50 *p, int *flags)
+{
+       struct passwd px;
+       int rv = __pw_scan50(buf, &px, flags);
+       passwd_to_passwd50(&px, p);
+       return rv;
+}
+#endif
+
+int
+getpwent_r(struct passwd50 *p, char *buf, size_t len, struct passwd50 **q)
+{
+       struct passwd px, *qx;
+       int rv = __getpwent_r50(&px, buf, len, &qx);
+       *q = p;
+       passwd_to_passwd50(&px, p);
+       return rv;
+}
+
+static struct passwd50 * (*__getpwnamf)(const char *);
+static struct passwd50 * (*__getpwuidf)(uid_t);
+static struct passwd pw;
+
+static struct passwd *
+internal_getpwnam(const char *name)
+{
+       struct passwd50 *p = (*__getpwnamf)(name);
+       passwd50_to_passwd(p, &pw);
+       return &pw;
+}
+
+static struct passwd *
+internal_getpwuid(uid_t uid)
+{
+       struct passwd50 *p = (*__getpwuidf)(uid);
+       passwd50_to_passwd(p, &pw);
+       return &pw;
+}
+
+int pwcache_userdb(int (*setpassentf)(int), void (*endpwentf)(void),
+    struct passwd50 * (*getpwnamf)(const char *),
+    struct passwd50 * (*getpwuidf)(uid_t))
+{
+       __getpwnamf = getpwnamf;
+       __getpwuidf = getpwuidf;
+       return __pwcache_userdb50(setpassentf, endpwentf, internal_getpwnam,
+           internal_getpwuid);
+}
diff --git a/lib/nbsd_libc/compat/gen/compat_glob.c b/lib/nbsd_libc/compat/gen/compat_glob.c
new file mode 100644 (file)
index 0000000..222b4a4
--- /dev/null
@@ -0,0 +1,31 @@
+/*     $NetBSD: compat_glob.c,v 1.2 2009/01/11 02:46:25 christos Exp $ */
+
+/*
+ * Written by Jason R. Thorpe <thorpej@NetBSD.org>, October 21, 1997.
+ * Public domain.
+ */
+#include "namespace.h"
+#include <pwd.h>
+#define __LIBC12_SOURCE__
+
+#include <sys/stat.h>
+#include <compat/sys/time.h>
+#include <compat/sys/stat.h>
+#include <dirent.h>
+#include <compat/include/dirent.h>
+#define __gl_stat_t struct stat12
+
+#include <glob.h>
+#include <compat/include/glob.h>
+
+#ifdef __weak_alias
+__weak_alias(glob,_glob)
+__weak_alias(globfree,_globfree)
+#endif /* __weak_alias */
+
+__warn_references(glob,
+    "warning: reference to compatibility glob(); include <glob.h> for correct reference")
+__warn_references(globfree,
+    "warning: reference to compatibility globfree(); include <glob.h> for correct reference")
+
+#include "gen/glob.c"
diff --git a/lib/nbsd_libc/compat/gen/compat_lastlogx.c b/lib/nbsd_libc/compat/gen/compat_lastlogx.c
new file mode 100644 (file)
index 0000000..8d1af36
--- /dev/null
@@ -0,0 +1,91 @@
+/*     $NetBSD: compat_lastlogx.c,v 1.2 2009/01/11 02:46:25 christos Exp $      */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_lastlogx.c,v 1.2 2009/01/11 02:46:25 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+
+#include <assert.h>
+#include <db.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <utmp.h>
+/* don't define earlier, has side effects in fcntl.h */
+#define __LIBC12_SOURCE__
+#include <utmpx.h>
+#include <compat/include/utmpx.h>
+
+__warn_references(getlastlogx,
+    "warning: reference to compatibility getlastlogx(); include <utmpx.h> for correct reference")
+__warn_references(lastlogxname,
+    "warning: reference to deprecated lastlogxname()")
+
+static char llfile[MAXPATHLEN] = _PATH_LASTLOGX;
+
+int
+lastlogxname(const char *fname)
+{
+       size_t len;
+
+       _DIAGASSERT(fname != NULL);
+
+       len = strlen(fname);
+
+       if (len >= sizeof(llfile))
+               return 0;
+
+       /* must end in x! */
+       if (fname[len - 1] != 'x')
+               return 0;
+
+       (void)strlcpy(llfile, fname, sizeof(llfile));
+       return 1;
+}
+
+struct lastlogx *
+getlastlogx(uid_t uid, struct lastlogx *ll)
+{
+
+       return __getlastlogx13(llfile, uid, ll);
+}
diff --git a/lib/nbsd_libc/compat/gen/compat_ldexp_ieee754.c b/lib/nbsd_libc/compat/gen/compat_ldexp_ieee754.c
new file mode 100644 (file)
index 0000000..a21d385
--- /dev/null
@@ -0,0 +1,143 @@
+/* $NetBSD: compat_ldexp_ieee754.c,v 1.5 2010/04/23 19:04:54 drochner Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Charles M. Hannum.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_ldexp_ieee754.c,v 1.5 2010/04/23 19:04:54 drochner Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <machine/ieee.h>
+#include <errno.h>
+
+double ldexp(double, int);
+
+/*
+ * Multiply the given value by 2^expon.
+ */
+double
+ldexp(double val, int expon)
+{
+       int oldexp, newexp;
+       union ieee_double_u u, mul;
+
+       u.dblu_d = val;
+       oldexp = u.dblu_dbl.dbl_exp;
+
+       /*
+        * If input is zero, Inf or NaN, just return it.
+        */
+       if (u.dblu_d == 0.0 || oldexp == DBL_EXP_INFNAN)
+               return (val);
+
+       if (oldexp == 0) {
+               /*
+                * u.v is denormal.  We must adjust it so that the exponent
+                * arithmetic below will work.
+                */
+               if (expon <= DBL_EXP_BIAS) {
+                       /*
+                        * Optimization: if the scaling can be done in a single
+                        * multiply, or underflows, just do it now.
+                        */
+                       if (expon <= -DBL_FRACBITS) {
+                               errno = ERANGE;
+                               return (val < 0.0 ? -0.0 : 0.0);
+                       }
+                       mul.dblu_d = 0.0;
+                       mul.dblu_dbl.dbl_exp = expon + DBL_EXP_BIAS;
+                       u.dblu_d *= mul.dblu_d;
+                       if (u.dblu_d == 0.0) {
+                               errno = ERANGE;
+                               return (val < 0.0 ? -0.0 : 0.0);
+                       }
+                       return (u.dblu_d);
+               } else {
+                       /*
+                        * We know that expon is very large, and therefore the
+                        * result cannot be denormal (though it may be Inf).
+                        * Shift u.v by just enough to make it normal.
+                        */
+                       mul.dblu_d = 0.0;
+                       mul.dblu_dbl.dbl_exp = DBL_FRACBITS + DBL_EXP_BIAS;
+                       u.dblu_d *= mul.dblu_d;
+                       expon -= DBL_FRACBITS;
+                       oldexp = u.dblu_dbl.dbl_exp;
+               }
+       }
+
+       /*
+        * u.v is now normalized and oldexp has been adjusted if necessary.
+        * Calculate the new exponent and check for underflow and overflow.
+        */
+       newexp = oldexp + expon;
+
+       if (newexp <= 0) {
+               /*
+                * The output number is either denormal or underflows (see
+                * comments in machine/ieee.h).
+                */
+               if (newexp <= -DBL_FRACBITS) {
+                       errno = ERANGE;
+                       return (val < 0.0 ? -0.0 : 0.0);
+               }
+               /*
+                * Denormalize the result.  We do this with a multiply.  If
+                * expon is very large, it won't fit in a double, so we have
+                * to adjust the exponent first.  This is safe because we know
+                * that u.v is normal at this point.
+                */
+               if (expon <= -DBL_EXP_BIAS) {
+                       u.dblu_dbl.dbl_exp = 1;
+                       expon += oldexp - 1;
+               }
+               mul.dblu_d = 0.0;
+               mul.dblu_dbl.dbl_exp = expon + DBL_EXP_BIAS;
+               u.dblu_d *= mul.dblu_d;
+               return (u.dblu_d);
+       } else if (newexp >= DBL_EXP_INFNAN) {
+               /*
+                * The result overflowed; return +/-Inf.
+                */
+               u.dblu_dbl.dbl_exp = DBL_EXP_INFNAN;
+               u.dblu_dbl.dbl_frach = 0;
+               u.dblu_dbl.dbl_fracl = 0;
+               errno = ERANGE;
+               return (u.dblu_d);
+       } else {
+               /*
+                * The result is normal; just replace the old exponent with the
+                * new one.
+                */
+               u.dblu_dbl.dbl_exp = newexp;
+               return (u.dblu_d);
+       }
+}
diff --git a/lib/nbsd_libc/compat/gen/compat_modf_ieee754.c b/lib/nbsd_libc/compat/gen/compat_modf_ieee754.c
new file mode 100644 (file)
index 0000000..660697d
--- /dev/null
@@ -0,0 +1,103 @@
+/* $NetBSD: compat_modf_ieee754.c,v 1.4 2010/04/23 19:04:54 drochner Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <sys/types.h>
+#include <machine/ieee.h>
+#include <errno.h>
+
+double modf(double, double *);
+
+/*
+ * double modf(double val, double *iptr)
+ * returns: f and i such that |f| < 1.0, (f + i) = val, and
+ *     sign(f) == sign(i) == sign(val).
+ *
+ * Beware signedness when doing subtraction, and also operand size!
+ */
+double
+modf(double val, double *iptr)
+{
+       union ieee_double_u u, v;
+       u_int64_t frac;
+
+       /*
+        * If input is +/-Inf or NaN, return +/-0 or NaN.
+        */
+       u.dblu_d = val;
+       if (u.dblu_dbl.dbl_exp == DBL_EXP_INFNAN) {
+               *iptr = u.dblu_d;
+               return (0.0 / u.dblu_d);
+       }
+
+       /*
+        * If input can't have a fractional part, return
+        * (appropriately signed) zero, and make i be the input.
+        */
+       if ((int)u.dblu_dbl.dbl_exp - DBL_EXP_BIAS > DBL_FRACBITS - 1) {
+               *iptr = u.dblu_d;
+               v.dblu_d = 0.0;
+               v.dblu_dbl.dbl_sign = u.dblu_dbl.dbl_sign;
+               return (v.dblu_d);
+       }
+
+       /*
+        * If |input| < 1.0, return it, and set i to the appropriately
+        * signed zero.
+        */
+       if (u.dblu_dbl.dbl_exp < DBL_EXP_BIAS) {
+               v.dblu_d = 0.0;
+               v.dblu_dbl.dbl_sign = u.dblu_dbl.dbl_sign;
+               *iptr = v.dblu_d;
+               return (u.dblu_d);
+       }
+
+       /*
+        * There can be a fractional part of the input.
+        * If you look at the math involved for a few seconds, it's
+        * plain to see that the integral part is the input, with the
+        * low (DBL_FRACBITS - (exponent - DBL_EXP_BIAS)) bits zeroed,
+        * the fractional part is the part with the rest of the
+        * bits zeroed.  Just zeroing the high bits to get the
+        * fractional part would yield a fraction in need of
+        * normalization.  Therefore, we take the easy way out, and
+        * just use subtraction to get the fractional part.
+        */
+       v.dblu_d = u.dblu_d;
+       /* Zero the low bits of the fraction, the sleazy way. */
+       frac = ((u_int64_t)v.dblu_dbl.dbl_frach << 32) + v.dblu_dbl.dbl_fracl;
+       frac >>= DBL_FRACBITS - (u.dblu_dbl.dbl_exp - DBL_EXP_BIAS);
+       frac <<= DBL_FRACBITS - (u.dblu_dbl.dbl_exp - DBL_EXP_BIAS);
+       v.dblu_dbl.dbl_fracl = (unsigned int)frac & 0xffffffff;
+       v.dblu_dbl.dbl_frach = (unsigned int)(frac >> 32);
+       *iptr = v.dblu_d;
+
+       u.dblu_d -= v.dblu_d;
+       u.dblu_dbl.dbl_sign = v.dblu_dbl.dbl_sign;
+       return (u.dblu_d);
+}
diff --git a/lib/nbsd_libc/compat/gen/compat_opendir.c b/lib/nbsd_libc/compat/gen/compat_opendir.c
new file mode 100644 (file)
index 0000000..24eaef0
--- /dev/null
@@ -0,0 +1,24 @@
+/*     $NetBSD: compat_opendir.c,v 1.1 2005/09/13 01:44:09 christos Exp $      */
+
+#include "namespace.h"
+#include <sys/stat.h>
+#include <signal.h>
+
+#define __LIBC12_SOURCE__
+#include <dirent.h>
+#include <compat/include/dirent.h>
+
+#ifdef __weak_alias
+__weak_alias(opendir,_opendir)
+#endif
+
+#ifdef __warn_references
+__warn_references(opendir,
+    "warning: reference to compatibility opendir(); include <dirent.h> for correct reference")
+__warn_references(__opendir2,
+    "warning: reference to compatibility __opendir2(); include <dirent.h> for correct reference")
+#endif
+
+#define dirent dirent12
+
+#include "gen/opendir.c"
diff --git a/lib/nbsd_libc/compat/gen/compat_readdir.c b/lib/nbsd_libc/compat/gen/compat_readdir.c
new file mode 100644 (file)
index 0000000..0863297
--- /dev/null
@@ -0,0 +1,22 @@
+/*     $NetBSD: compat_readdir.c,v 1.1 2005/09/13 01:44:09 christos Exp $      */
+
+#define __LIBC12_SOURCE__
+#include "namespace.h"
+#include <dirent.h>
+#include <compat/include/dirent.h>
+
+#ifdef __weak_alias
+__weak_alias(readdir,_readdir)
+__weak_alias(readdir_r,_readdir_r)
+#endif
+
+#ifdef __warn_references
+__warn_references(readdir,
+    "warning: reference to compatibility readdir(); include <dirent.h> for correct reference")
+__warn_references(readdir_r,
+    "warning: reference to compatibility readdir_r(); include <dirent.h> for correct reference")
+#endif
+
+#define dirent dirent12
+
+#include "gen/readdir.c"
diff --git a/lib/nbsd_libc/compat/gen/compat_scandir.c b/lib/nbsd_libc/compat/gen/compat_scandir.c
new file mode 100644 (file)
index 0000000..7aac0f2
--- /dev/null
@@ -0,0 +1,20 @@
+/*     $NetBSD: compat_scandir.c,v 1.1 2005/09/13 01:44:09 christos Exp $      */
+
+#include <sys/stat.h>
+#define __LIBC12_SOURCE__
+#include "namespace.h"
+#include <dirent.h>
+#include <compat/include/dirent.h>
+
+#ifdef __weak_alias
+__weak_alias(scandir,_scandir)
+#endif
+
+#ifdef __warn_references
+__warn_references(scandir,
+    "warning: reference to compatibility scandir(); include <dirent.h> for correct reference")
+#endif
+
+#define dirent dirent12
+
+#include "gen/scandir.c"
diff --git a/lib/nbsd_libc/compat/gen/compat_siglist.c b/lib/nbsd_libc/compat/gen/compat_siglist.c
new file mode 100644 (file)
index 0000000..0627f44
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: compat_siglist.c,v 1.1 2005/09/13 01:44:09 christos Exp $      */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)siglist.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: compat_siglist.c,v 1.1 2005/09/13 01:44:09 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef __weak_alias
+__weak_alias(sys_siglist, _sys_siglist)
+__weak_alias(__sys_siglist, _sys_siglist)
+#endif
+
+const char *const _sys_siglist[] = {
+       "Signal 0",
+       "Hangup",                       /* SIGHUP */
+       "Interrupt",                    /* SIGINT */
+       "Quit",                         /* SIGQUIT */
+       "Illegal instruction",          /* SIGILL */
+       "Trace/BPT trap",               /* SIGTRAP */
+       "Abort trap",                   /* SIGABRT */
+       "EMT trap",                     /* SIGEMT */
+       "Floating point exception",     /* SIGFPE */
+       "Killed",                       /* SIGKILL */
+       "Bus error",                    /* SIGBUS */
+       "Segmentation fault",           /* SIGSEGV */
+       "Bad system call",              /* SIGSYS */
+       "Broken pipe",                  /* SIGPIPE */
+       "Alarm clock",                  /* SIGALRM */
+       "Terminated",                   /* SIGTERM */
+       "Urgent I/O condition",         /* SIGURG */
+       "Suspended (signal)",           /* SIGSTOP */
+       "Suspended",                    /* SIGTSTP */
+       "Continued",                    /* SIGCONT */
+       "Child exited",                 /* SIGCHLD */
+       "Stopped (tty input)",          /* SIGTTIN */
+       "Stopped (tty output)",         /* SIGTTOU */
+       "I/O possible",                 /* SIGIO */
+       "Cputime limit exceeded",       /* SIGXCPU */
+       "Filesize limit exceeded",      /* SIGXFSZ */
+       "Virtual timer expired",        /* SIGVTALRM */
+       "Profiling timer expired",      /* SIGPROF */
+       "Window size changes",          /* SIGWINCH */
+       "Information request",          /* SIGINFO */
+       "User defined signal 1",        /* SIGUSR1 */
+       "User defined signal 2"         /* SIGUSR2 */
+};
diff --git a/lib/nbsd_libc/compat/gen/compat_signame.c b/lib/nbsd_libc/compat/gen/compat_signame.c
new file mode 100644 (file)
index 0000000..b2dcddc
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: compat_signame.c,v 1.1 2005/09/13 01:44:09 christos Exp $      */
+
+/*
+ * Copyright (c) 1983 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "from: @(#)siglist.c    5.6 (Berkeley) 2/23/91";*/
+#else
+__RCSID("$NetBSD: compat_signame.c,v 1.1 2005/09/13 01:44:09 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+__warn_references(sys_signame,
+    "warning: reference to compatibility sys_signame[]; include <signal.h> for correct reference")
+
+const char *const sys_signame[] = {
+       "Signal 0",     /* 0 */
+       "HUP",          /* 1 SIGHUP */
+       "INT",          /* 2 SIGINT */
+       "QUIT",         /* 3 SIGQUIT */
+       "ILL",          /* 4 SIGILL */
+       "TRAP",         /* 5 SIGTRAP */
+       "ABRT",         /* 6 SIGABRT */
+       "EMT",          /* 7 SIGEMT */
+       "FPE",          /* 8 SIGFPE */
+       "KILL",         /* 9 SIGKILL */
+       "BUS",          /* 10 SIGBUS */
+       "SEGV",         /* 11 SIGSEGV */
+       "SYS",          /* 12 SIGSYS */
+       "PIPE",         /* 13 SIGPIPE */
+       "ALRM",         /* 14 SIGALRM */
+       "TERM",         /* 15 SIGTERM */
+       "URG",          /* 16 SIGURG */
+       "STOP",         /* 17 SIGSTOP */
+       "TSTP",         /* 18 SIGTSTP */
+       "CONT",         /* 19 SIGCONT */
+       "CHLD",         /* 20 SIGCHLD */
+       "TTIN",         /* 21 SIGTTIN */
+       "TTOU",         /* 22 SIGTTOU */
+       "IO",           /* 23 SIGIO */
+       "XCPU",         /* 24 SIGXCPU */
+       "XFSZ",         /* 25 SIGXFSZ */
+       "VTALRM",       /* 26 SIGVTALRM */
+       "PROF",         /* 27 SIGPROF */
+       "WINCH",        /* 28 SIGWINCH */
+       "INFO",         /* 29 SIGINFO */
+       "USR1",         /* 30 SIGUSR1 */
+       "USR2",         /* 31 SIGUSR2 */
+};
diff --git a/lib/nbsd_libc/compat/gen/compat_sigsetops.c b/lib/nbsd_libc/compat/gen/compat_sigsetops.c
new file mode 100644 (file)
index 0000000..dee1ec6
--- /dev/null
@@ -0,0 +1,120 @@
+/*     $NetBSD: compat_sigsetops.c,v 1.2 2009/01/11 02:46:25 christos Exp $    */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ *
+ *     @(#)sigsetops.c 8.1 (Berkeley) 6/4/93
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)sigsetops.c        8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: compat_sigsetops.c,v 1.2 2009/01/11 02:46:25 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#define        __LIBC12_SOURCE__
+
+#include <errno.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <signal.h>
+#include <compat/include/signal.h>
+
+#undef sigemptyset
+#undef sigfillset
+#undef sigaddset
+#undef sigdelset
+#undef sigismember
+
+__warn_references(sigaddset,
+    "warning: reference to compatibility sigaddset(); include <signal.h> for correct reference")
+__warn_references(sigdelset,
+    "warning: reference to compatibility sigdelset(); include <signal.h> for correct reference")
+__warn_references(sigemptyset,
+    "warning: reference to compatibility sigemptyset(); include <signal.h> for correct reference")
+__warn_references(sigfillset,
+    "warning: reference to compatibility sigfillset(); include <signal.h> for correct reference")
+__warn_references(sigismember,
+    "warning: reference to compatibility sigismember(); include <signal.h> for correct reference")
+
+int
+sigemptyset(set)
+       sigset13_t *set;
+{
+       *set = 0;
+       return (0);
+}
+
+int
+sigfillset(set)
+       sigset13_t *set;
+{
+       *set = ~(sigset13_t)0;
+       return (0);
+}
+
+int
+sigaddset(set, signo)
+       sigset13_t *set;
+       int signo;
+{
+       if (signo <= 0 || signo >= NSIG13) {
+               errno = EINVAL;
+               return -1;
+       }
+       *set |= __sigmask13(signo);
+       return (0);
+}
+
+int
+sigdelset(set, signo)
+       sigset13_t *set;
+       int signo;
+{
+       if (signo <= 0 || signo >= NSIG13) {
+               errno = EINVAL;
+               return -1;
+       }
+       *set &= ~__sigmask13(signo);
+       return (0);
+}
+
+int
+sigismember(set, signo)
+       const sigset13_t *set;
+       int signo;
+{
+       if (signo <= 0 || signo >= NSIG13) {
+               errno = EINVAL;
+               return -1;
+       }
+       return ((*set & __sigmask13(signo)) != 0);
+}
diff --git a/lib/nbsd_libc/compat/gen/compat_time.c b/lib/nbsd_libc/compat/gen/compat_time.c
new file mode 100644 (file)
index 0000000..9699490
--- /dev/null
@@ -0,0 +1,27 @@
+/*     $NetBSD: compat_time.c,v 1.2 2009/01/11 02:46:25 christos Exp $ */
+
+/*
+ * Written by Jason R. Thorpe <thorpej@NetBSD.org>, October 21, 1997.
+ * Public domain.
+ */
+
+#include "namespace.h"
+#include <sys/cdefs.h>
+
+#define __LIBC12_SOURCE__
+#include <time.h>
+#include <sys/time.h>
+#include <compat/include/time.h>
+#include <compat/sys/time.h>
+
+#ifdef __weak_alias
+__weak_alias(time,_time)
+#endif
+
+__warn_references(time,
+    "warning: reference to compatibility time();"
+    " include <time.h> for correct reference")
+
+#define timeval timeval50
+#define time_t int32_t
+#include "gen/time.c"
diff --git a/lib/nbsd_libc/compat/gen/compat_times.c b/lib/nbsd_libc/compat/gen/compat_times.c
new file mode 100644 (file)
index 0000000..8c4a7e5
--- /dev/null
@@ -0,0 +1,28 @@
+/*     $NetBSD: compat_times.c,v 1.2 2009/01/11 02:46:25 christos Exp $        */
+
+/*
+ * Ben Harris, 2002.
+ * This file is in the Public Domain.
+ */
+
+#define __LIBC12_SOURCE__
+#include "namespace.h"
+#include <sys/cdefs.h>
+#include <time.h>
+#include <compat/include/time.h>
+#include <sys/times.h>
+#include <compat/sys/times.h>
+#include <sys/resource.h>
+#include <compat/sys/resource.h>
+
+#ifdef __weak_alias
+__weak_alias(times,_times)
+#endif
+
+__warn_references(times,
+    "warning: reference to compatibility times(); include <sys/times.h> for correct reference")
+
+#define __times_rusage struct rusage50
+#define __times_timeval struct timeval50
+
+#include "gen/times.c"
diff --git a/lib/nbsd_libc/compat/gen/compat_timezone.c b/lib/nbsd_libc/compat/gen/compat_timezone.c
new file mode 100644 (file)
index 0000000..91a4f01
--- /dev/null
@@ -0,0 +1,143 @@
+/*     $NetBSD: compat_timezone.c,v 1.3 2009/01/11 02:46:25 christos Exp $     */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)timezone.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: compat_timezone.c,v 1.3 2009/01/11 02:46:25 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <time.h>
+#include <compat/include/time.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <tzfile.h>
+
+__warn_references(timezone,
+     "warning: reference to compatibility timezone; include <time.h> to generate correct reference")
+
+/*
+ * timezone --
+ *     The arguments are the number of minutes of time you are westward
+ *     from Greenwich and whether DST is in effect.  It returns a string
+ *     giving the name of the local timezone.  Should be replaced, in the
+ *     application code, by a call to localtime.
+ */
+
+char *_tztab(int, int);
+
+static char    czone[TZ_MAX_CHARS];            /* space for zone name */
+
+char *timezone(int, int);
+char *
+timezone(int zone, int dst)
+{
+       char    *beg,
+                       *end;
+
+       if ((beg = getenv("TZNAME")) != NULL) { /* set in environment */
+               if ((end = strchr(beg, ',')) != NULL) { /* "PST,PDT" */
+                       if (dst)
+                               return(++end);
+                       *end = '\0';
+                       (void)strlcpy(czone, beg, sizeof(czone));
+                       *end = ',';
+                       return(czone);
+               }
+               return(beg);
+       }
+       return(_tztab(zone,dst));       /* default: table or created zone */
+}
+
+static const struct zone {
+       int             offset;
+       const char      *stdzone;
+       const char      *dlzone;
+} zonetab[] = {
+       { -1*60,        "MET",  "MET DST" },    /* Middle European */
+       { -2*60,        "EET",  "EET DST" },    /* Eastern European */
+       { 4*60,         "AST",  "ADT" },        /* Atlantic */
+       { 5*60,         "EST",  "EDT" },        /* Eastern */
+       { 6*60,         "CST",  "CDT" },        /* Central */
+       { 7*60,         "MST",  "MDT" },        /* Mountain */
+       { 8*60,         "PST",  "PDT" },        /* Pacific */
+#ifdef notdef
+       /* there's no way to distinguish this from WET */
+       { 0,            "GMT",  0 },            /* Greenwich */
+#endif
+       { 0*60,         "WET",  "WET DST" },    /* Western European */
+       { -10*60,       "EST",  "EST" },        /* Aust: Eastern */
+       { -10*60+30,    "CST",  "CST" },        /* Aust: Central */
+       { -8*60,        "WST",  0 },            /* Aust: Western */
+       { -1,           NULL,   NULL }
+};
+
+/*
+ * _tztab --
+ *     check static tables or create a new zone name; broken out so that
+ *     we can make a guess as to what the zone is if the standard tables
+ *     aren't in place in /etc.  DO NOT USE THIS ROUTINE OUTSIDE OF THE
+ *     STANDARD LIBRARY.
+ */
+char *
+_tztab(zone,dst)
+       int     zone;
+       int     dst;
+{
+       const struct zone       *zp;
+       char    sign;
+
+       for (zp = zonetab; zp->offset != -1;++zp)       /* static tables */
+               if (zp->offset == zone) {
+                       if (dst && zp->dlzone)
+                               return __UNCONST(zp->dlzone);
+                       if (!dst && zp->stdzone)
+                               return __UNCONST(zp->stdzone);
+               }
+
+       if (zone < 0) {                                 /* create one */
+               zone = -zone;
+               sign = '+';
+       }
+       else
+               sign = '-';
+       (void)snprintf(czone, TZ_MAX_CHARS, "GMT%c%d:%02d", sign, zone / 60,
+            zone % 60);
+       return(czone);
+}
diff --git a/lib/nbsd_libc/compat/gen/compat_unvis.c b/lib/nbsd_libc/compat/gen/compat_unvis.c
new file mode 100644 (file)
index 0000000..a90512c
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: compat_unvis.c,v 1.2 2007/03/10 01:13:14 hubertf Exp $ */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)unvis.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: compat_unvis.c,v 1.2 2007/03/10 01:13:14 hubertf Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <stdio.h>
+#include <vis.h>
+#include <compat/include/vis.h>
+
+#ifdef __weak_alias
+__weak_alias(unvis,_unvis)
+#endif
+
+#ifdef __warn_references
+__warn_references(unvis,
+    "warning: reference to compatibility unvis(); include <vis.h> for correct reference")
+#endif
+
+int
+unvis(char *cp, int c, int *astate, int flag)
+{
+       return __unvis13(cp, c, astate, flag);
+}
diff --git a/lib/nbsd_libc/compat/gen/compat_utime.c b/lib/nbsd_libc/compat/gen/compat_utime.c
new file mode 100644 (file)
index 0000000..1c9c0e3
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: compat_utime.c,v 1.2 2009/01/11 02:46:25 christos Exp $        */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)utime.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: compat_utime.c,v 1.2 2009/01/11 02:46:25 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <utime.h>
+#include <compat/include/utime.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+
+__warn_references(utime,
+    "warning: reference to compatibility utime(); include <utime.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(utime, _utime)
+#endif
+
+int
+utime(const char *path, const struct utimbuf50 *times50)
+{
+       struct timeval tv[2], *tvp;
+
+       _DIAGASSERT(path != NULL);
+
+       if (times50 == NULL)
+               tvp = NULL;
+       else {
+               tv[0].tv_sec = times50->actime;
+               tv[1].tv_sec = times50->modtime;
+               tv[0].tv_usec = tv[1].tv_usec = 0;
+               tvp = tv;
+       }
+       return __utimes50(path, tvp);
+}
diff --git a/lib/nbsd_libc/compat/gen/compat_utmp.c b/lib/nbsd_libc/compat/gen/compat_utmp.c
new file mode 100644 (file)
index 0000000..be98682
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: compat_utmp.c,v 1.2 2009/01/11 02:46:25 christos Exp $  */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_utmp.c,v 1.2 2009/01/11 02:46:25 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+
+#define __LIBC12_SOURCE__
+#include <assert.h>
+#include <sys/time.h>
+#include <string.h>
+#include <compat/sys/time.h>
+#include <utmp.h>
+#include <compat/include/utmp.h>
+
+__warn_references(getutent,
+    "warning: reference to compatibility getutent(); include <utmp.h> for correct reference")
+
+static struct utmp50 *
+cvt(struct utmp *ut)
+{
+       struct utmp50 *ut50 = (void *)ut;
+       if (ut == NULL)
+               return NULL;
+       ut50->ut_time = (int32_t)ut->ut_time;
+       return ut50;
+}
+
+struct utmp50 *
+getutent(void)
+{
+       return cvt(__getutent50());
+}
diff --git a/lib/nbsd_libc/compat/gen/compat_utmpx.c b/lib/nbsd_libc/compat/gen/compat_utmpx.c
new file mode 100644 (file)
index 0000000..44784a2
--- /dev/null
@@ -0,0 +1,194 @@
+/*     $NetBSD: compat_utmpx.c,v 1.3 2009/01/11 02:46:25 christos Exp $         */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_utmpx.c,v 1.3 2009/01/11 02:46:25 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+
+#define __LIBC12_SOURCE__
+#include <assert.h>
+#include <sys/time.h>
+#include <string.h>
+#include <compat/sys/time.h>
+#include <utmpx.h>
+#include <compat/include/utmpx.h>
+
+__warn_references(getutxent,
+    "warning: reference to compatibility getutxent(); include <utmpx.h> for correct reference")
+__warn_references(getutxid,
+    "warning: reference to compatibility getutxid(); include <utmpx.h> for correct reference")
+__warn_references(getutxline,
+    "warning: reference to compatibility getutxline(); include <utmpx.h> for correct reference")
+__warn_references(pututxline,
+    "warning: reference to compatibility pututxline(); include <utmpx.h> for correct reference")
+__warn_references(updwtmpx,
+    "warning: reference to compatibility updwtmpx(); include <utmpx.h> for correct reference")
+__warn_references(getlastlogx,
+    "warning: reference to compatibility getlastlogx(); include <utmpx.h> for correct reference")
+__warn_references(updlastlogx,
+    "warning: reference to compatibility updlastlogx(); include <utmpx.h> for correct reference")
+__warn_references(getutmp,
+    "warning: reference to compatibility getutmp(); include <utmpx.h> for correct reference")
+__warn_references(getutmpx,
+    "warning: reference to compatibility getutmpx(); include <utmpx.h> for correct reference")
+
+static struct utmpx50 *
+cvt(struct utmpx *ut)
+{
+       if (ut == NULL)
+               return NULL;
+       timeval_to_timeval50(&ut->ut_tv, (void *)&ut->ut_tv);
+       return (void *)ut;
+}
+
+static void
+lastlogx50_to_lastlogx(const struct lastlogx50 *ll50, struct lastlogx *ll)
+{
+       (void)memcpy(ll->ll_line, ll50->ll_line, sizeof(ll->ll_line));
+       (void)memcpy(ll->ll_host, ll50->ll_host, sizeof(ll->ll_host));
+       (void)memcpy(&ll->ll_ss, &ll50->ll_ss, sizeof(&ll->ll_ss));
+       timeval50_to_timeval(&ll50->ll_tv, &ll->ll_tv);
+}
+
+static void
+lastlogx_to_lastlogx50(const struct lastlogx *ll, struct lastlogx50 *ll50)
+{
+       (void)memcpy(ll50->ll_line, ll->ll_line, sizeof(ll50->ll_line));
+       (void)memcpy(ll50->ll_host, ll->ll_host, sizeof(ll50->ll_host));
+       (void)memcpy(&ll50->ll_ss, &ll->ll_ss, sizeof(&ll50->ll_ss));
+       timeval_to_timeval50(&ll->ll_tv, &ll50->ll_tv);
+}
+
+struct utmpx50 *
+getutxent(void)
+{
+       return cvt(__getutxent50());
+}
+
+struct utmpx50 *
+getutxid(const struct utmpx50 *ut50)
+{
+       struct utmpx ut;
+       utmpx50_to_utmpx(ut50, &ut);
+       return cvt(__getutxid50(&ut));
+}
+
+struct utmpx50 *
+getutxline(const struct utmpx50 *ut50)
+{
+       struct utmpx ut;
+       utmpx50_to_utmpx(ut50, &ut);
+       return cvt(__getutxline50(&ut));
+}
+
+struct utmpx50 *
+pututxline(const struct utmpx50 *ut50)
+{
+       struct utmpx ut;
+       utmpx50_to_utmpx(ut50, &ut);
+       return cvt(__pututxline50(&ut));
+}
+
+int
+updwtmpx(const char *fname, const struct utmpx50 *ut50)
+{
+       struct utmpx ut;
+       utmpx50_to_utmpx(ut50, &ut);
+       return __updwtmpx50(fname, &ut);
+}
+
+struct lastlogx50 *
+__getlastlogx13(const char *fname, uid_t uid, struct lastlogx50 *ll50)
+{
+       struct lastlogx ll;
+       if (__getlastlogx50(fname, uid, &ll) == NULL)
+               return NULL;
+       lastlogx_to_lastlogx50(&ll, ll50);
+       return ll50;
+}
+
+static char llfile[MAXPATHLEN] = _PATH_LASTLOGX;
+
+int
+lastlogxname(const char *fname)
+{
+       size_t len;
+
+       _DIAGASSERT(fname != NULL);
+
+       len = strlen(fname);
+
+       if (len >= sizeof(llfile))
+               return 0;
+
+       /* must end in x! */
+       if (fname[len - 1] != 'x')
+               return 0;
+
+       (void)strlcpy(llfile, fname, sizeof(llfile));
+       return 1;
+}
+
+struct lastlogx50 *
+getlastlogx(uid_t uid, struct lastlogx50 *ll)
+{
+
+       return __getlastlogx13(llfile, uid, ll);
+}
+
+int
+updlastlogx(const char *fname, uid_t uid, struct lastlogx50 *ll50)
+{
+       struct lastlogx ll;
+       lastlogx50_to_lastlogx(ll50, &ll);
+       return __updlastlogx50(fname, uid, &ll);
+}
+
+void
+getutmp(const struct utmpx50 *utx50, struct utmp *ut)
+{
+       struct utmpx utx;
+       utmpx50_to_utmpx(utx50, &utx);
+       __getutmp50(&utx, ut);
+}
+
+void
+getutmpx(const struct utmp *ut, struct utmpx50 *utx50)
+{
+       struct utmpx utx;
+       __getutmpx50(ut, &utx);
+       utmpx_to_utmpx50(&utx, utx50);
+}
diff --git a/lib/nbsd_libc/compat/include/aio.h b/lib/nbsd_libc/compat/include/aio.h
new file mode 100644 (file)
index 0000000..60d80ee
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: aio.h,v 1.2 2009/01/11 02:46:25 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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        _COMPAT_AIO_H_
+#define        _COMPAT_AIO_H_
+
+__BEGIN_DECLS
+struct aiocb;
+struct timespec50;
+struct timespec;
+int    aio_suspend(const struct aiocb * const [], int,
+    const struct timespec50 *);
+int    __aio_suspend50(const struct aiocb * const [], int,
+    const struct timespec *);
+__END_DECLS
+
+#endif /* _COMPAT_AIO_H_ */
diff --git a/lib/nbsd_libc/compat/include/dirent.h b/lib/nbsd_libc/compat/include/dirent.h
new file mode 100644 (file)
index 0000000..f41fc32
--- /dev/null
@@ -0,0 +1,78 @@
+/*     $NetBSD: dirent.h,v 1.7 2009/02/24 18:42:36 christos Exp $      */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ *
+ *     @(#)dirent.h    8.2 (Berkeley) 7/28/94
+ */
+
+#ifndef _COMPAT_DIRENT_H_
+#define _COMPAT_DIRENT_H_
+
+#include <compat/sys/dirent.h>
+
+__BEGIN_DECLS
+
+DIR *opendir(const char *);
+DIR *__opendir30(const char *);
+
+int readdir_r(DIR *, struct dirent12 * __restrict,
+    struct dirent12 ** __restrict);
+int __readdir_r30(DIR * __restrict, struct dirent * __restrict,
+    struct dirent ** __restrict);
+
+struct dirent12 *readdir(DIR *);
+struct dirent *__readdir30(DIR *);
+
+#if defined(_NETBSD_SOURCE)
+
+struct dirent12 *_readdir_unlocked(DIR *, int);
+struct dirent *___readdir_unlocked50(DIR *, int);
+struct dirent *___readdir_unlocked30(DIR *);
+
+DIR *__opendir2(const char *, int);
+DIR *__opendir230(const char *, int);
+
+int scandir(const char *, struct dirent12 ***,
+    int (*)(const struct dirent12 *), int (*)(const void *, const void *));
+int __scandir30(const char *, struct dirent ***,
+    int (*)(const struct dirent *), int (*)(const void *, const void *));
+
+int getdents(int, char *, size_t);
+int __getdents30(int, char *, size_t);
+
+int alphasort(const void *, const void *);
+int __alphasort30(const void *, const void *);
+
+int getdirentries(int, char *, int, long *);
+
+#endif /* defined(_NETBSD_SOURCE) */
+
+__END_DECLS
+
+#endif /* !_COMPAT_DIRENT_H_ */
diff --git a/lib/nbsd_libc/compat/include/fstypes.h b/lib/nbsd_libc/compat/include/fstypes.h
new file mode 100644 (file)
index 0000000..06868b7
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: fstypes.h,v 1.4 2008/04/28 20:22:59 martin Exp $       */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Martin Husemann <martin@NetBSD.org>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _COMPAT_FSTYPES_H_
+#define _COMPAT_FSTYPES_H_
+
+#include <stddef.h>
+
+/* Old, fixed size filehandle structures (used upto (including) 3.x) */
+struct compat_30_fid {
+       unsigned short  fid30_len;
+       unsigned short  fid30_reserved;
+       char            fid30_data[16];
+};
+struct compat_30_fhandle {
+       fsid_t  fh_fsid;
+       struct compat_30_fid fh_fid;
+};
+
+#define        FHANDLE30_SIZE  sizeof(struct compat_30_fhandle) /* 28 */
+
+#endif /* _COMPAT_FSTYPES_H_ */
diff --git a/lib/nbsd_libc/compat/include/fts.h b/lib/nbsd_libc/compat/include/fts.h
new file mode 100644 (file)
index 0000000..de95bcf
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: fts.h,v 1.1 2005/09/13 01:44:09 christos Exp $ */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ *
+ *     @(#)fts.h       8.3 (Berkeley) 8/14/94
+ */
+
+#ifndef        _COMPAT_FTS_H_
+#define        _COMPAT_FTS_H_
+
+__BEGIN_DECLS
+FTSENT *fts_children(FTS *, int);
+int     fts_close(FTS *);
+FTS    *fts_open(char * const *, int,
+    int (*)(const FTSENT **, const FTSENT **));
+FTSENT *fts_read(FTS *);
+int     fts_set(FTS *, FTSENT *, int);
+__END_DECLS
+
+#endif /* !_COMPAT_FTS_H_ */
diff --git a/lib/nbsd_libc/compat/include/glob.h b/lib/nbsd_libc/compat/include/glob.h
new file mode 100644 (file)
index 0000000..cd68607
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: glob.h,v 1.1 2005/09/13 01:44:09 christos Exp $        */
+
+/*
+ * Copyright (c) 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Guido van Rossum.
+ *
+ * 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. 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.
+ *
+ *     @(#)glob.h      8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _COMPAT_GLOB_H_
+#define        _COMPAT_GLOB_H_
+
+__BEGIN_DECLS
+int    glob(const char * __restrict, int,
+    int (*)(const char *, int), glob_t * __restrict);
+void   globfree(glob_t *);
+__END_DECLS
+
+#endif /* !_COMPAT_GLOB_H_ */
diff --git a/lib/nbsd_libc/compat/include/locale.h b/lib/nbsd_libc/compat/include/locale.h
new file mode 100644 (file)
index 0000000..455be30
--- /dev/null
@@ -0,0 +1,44 @@
+/* $NetBSD: locale.h,v 1.1 2010/06/07 13:52:30 tnozaki Exp $ */
+
+/*
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ *
+ *     @(#)locale.h    8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _COMPAT_LOCALE_H_
+#define _COMPAT_LOCALE_H_
+
+#define _LC_LAST       7               /* marks end */
+
+__BEGIN_DECLS
+char *setlocale(int, const char *);
+char *__setlocale_mb_len_max_32(int, const char *);
+__END_DECLS
+
+#endif /* _COMPAT_LOCALE_H_ */
diff --git a/lib/nbsd_libc/compat/include/lwp.h b/lib/nbsd_libc/compat/include/lwp.h
new file mode 100644 (file)
index 0000000..bdad633
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: lwp.h,v 1.2 2009/01/11 02:46:25 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _COMPAT_LWP_H_
+#define _COMPAT_LWP_H_
+
+__BEGIN_DECLS
+int    _lwp_park(const struct timespec50 *, lwpid_t, const void *, const void *);
+int    ___lwp_park50(const struct timespec *, lwpid_t, const void *, const void *);
+__END_DECLS
+
+#endif /* !_COMPAT_LWP_H_ */
diff --git a/lib/nbsd_libc/compat/include/mqueue.h b/lib/nbsd_libc/compat/include/mqueue.h
new file mode 100644 (file)
index 0000000..dd0cf61
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: mqueue.h,v 1.2 2009/01/11 02:46:25 christos Exp $      */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _COMPAT_MQUEUE_H_
+#define _COMPAT_MQUEUE_H_
+
+__BEGIN_DECLS
+ssize_t        mq_timedreceive(mqd_t, char * __restrict, size_t,
+    unsigned * __restrict, const struct timespec50 * __restrict);
+int    mq_timedsend(mqd_t, const char *, size_t, unsigned,
+    const struct timespec50 *);
+ssize_t        __mq_timedreceive50(mqd_t, char * __restrict, size_t,
+    unsigned * __restrict, const struct timespec * __restrict);
+int    __mq_timedsend50(mqd_t, const char *, size_t, unsigned,
+    const struct timespec *);
+__END_DECLS
+
+#endif /* _COMPAT_MQUEUE_H_ */
diff --git a/lib/nbsd_libc/compat/include/ndbm.h b/lib/nbsd_libc/compat/include/ndbm.h
new file mode 100644 (file)
index 0000000..99a0a9b
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: ndbm.h,v 1.1 2005/09/13 01:44:09 christos Exp $        */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Margo Seltzer.
+ *
+ * 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. 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.
+ *
+ *     @(#)ndbm.h      8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _COMPAT_NDBM_H_
+#define        _COMPAT_NDBM_H_
+
+typedef struct {
+       void    *dptr;
+       int      dsize;
+} datum12;
+
+__BEGIN_DECLS
+int     dbm_delete(DBM *, datum12);
+datum12         dbm_fetch(DBM *, datum12);
+datum12         dbm_firstkey(DBM *);
+datum12         dbm_nextkey(DBM *);
+int     dbm_store(DBM *, datum12, datum12, int);
+__END_DECLS
+
+#endif /* !_COMPAT_NDBM_H_ */
diff --git a/lib/nbsd_libc/compat/include/ns.h b/lib/nbsd_libc/compat/include/ns.h
new file mode 100644 (file)
index 0000000..97d9cd4
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: ns.h,v 1.1 2006/08/26 16:07:01 matt Exp $      */
+
+/*
+ * Copyright (c) 1984, 1985, 1986, 1987, 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.
+ * 3. 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.
+ *
+ *     @(#)ns.h        8.1 (Berkeley) 6/10/93
+ */
+
+#ifndef _NETNS_NS_H_
+#define _NETNS_NS_H_
+
+/*
+ * NS addressing
+ */
+union ns_host {
+       u_int8_t        c_host[6];
+       u_int16_t       s_host[3];
+};
+
+union ns_net {
+       u_int8_t        c_net[4];
+       u_int16_t       s_net[2];
+};
+
+union ns_net_u {
+       union ns_net    net_e;
+       u_int32_t       long_e;
+};
+
+struct ns_addr {
+       union ns_net    x_net;
+       union ns_host   x_host;
+       u_int16_t       x_port;
+};
+
+__BEGIN_DECLS
+extern struct ns_addr ns_addr __P((const char *));
+extern char *ns_ntoa __P((struct ns_addr));
+__END_DECLS
+
+#endif /* !_NETNS_NS_H_ */
diff --git a/lib/nbsd_libc/compat/include/pwd.h b/lib/nbsd_libc/compat/include/pwd.h
new file mode 100644 (file)
index 0000000..b9a805a
--- /dev/null
@@ -0,0 +1,99 @@
+/*     $NetBSD: pwd.h,v 1.2 2009/01/11 02:46:25 christos Exp $ */
+
+#ifndef _COMPAT_PWD_H_
+#define        _COMPAT_PWD_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <sys/types.h>
+
+struct passwd;
+struct passwd50 {
+       __aconst char *pw_name;         /* user name */
+       __aconst char *pw_passwd;       /* encrypted password */
+       uid_t          pw_uid;          /* user uid */
+       gid_t          pw_gid;          /* user gid */
+       int32_t        pw_change;       /* password change time */
+       __aconst char *pw_class;        /* user login class */
+       __aconst char *pw_gecos;        /* general information */
+       __aconst char *pw_dir;          /* home directory */
+       __aconst char *pw_shell;        /* default shell */
+       int32_t        pw_expire;       /* account expiration */
+};
+
+__BEGIN_DECLS
+static __inline void
+passwd_to_passwd50(const struct passwd *p, struct passwd50 *q)
+{
+       q->pw_name = p->pw_name;
+       q->pw_passwd = p->pw_passwd;
+       q->pw_uid = p->pw_uid;
+       q->pw_gid = p->pw_gid;
+       q->pw_change = (int32_t)p->pw_change;
+       q->pw_class = p->pw_class;
+       q->pw_gecos = p->pw_gecos;
+       q->pw_dir = p->pw_dir;
+       q->pw_shell = p->pw_shell;
+       q->pw_expire = (int32_t)p->pw_expire;
+}
+
+static __inline void
+passwd50_to_passwd(const struct passwd50 *p, struct passwd *q)
+{
+       q->pw_name = p->pw_name;
+       q->pw_passwd = p->pw_passwd;
+       q->pw_uid = p->pw_uid;
+       q->pw_gid = p->pw_gid;
+       q->pw_change = p->pw_change;
+       q->pw_class = p->pw_class;
+       q->pw_gecos = p->pw_gecos;
+       q->pw_dir = p->pw_dir;
+       q->pw_shell = p->pw_shell;
+       q->pw_expire = p->pw_expire;
+}
+
+struct passwd50        *getpwuid(uid_t);
+struct passwd50        *getpwnam(const char *);
+#if (_POSIX_C_SOURCE - 0) >= 199506L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_REENTRANT) || defined(_NETBSD_SOURCE)
+int             getpwnam_r(const char *, struct passwd50 *, char *, size_t,
+    struct passwd50 **);
+int             getpwuid_r(uid_t, struct passwd50 *, char *, size_t,
+    struct passwd50 **);
+#endif
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+struct passwd50        *getpwent(void);
+#endif
+#if defined(_NETBSD_SOURCE)
+int             pw_scan(char *, struct passwd50 *, int *);
+int             getpwent_r(struct passwd50 *, char *, size_t, struct passwd50 **);
+#endif
+#if defined(_NETBSD_SOURCE)
+int             pwcache_userdb(int (*)(int), void (*)(void),
+    struct passwd50 * (*)(const char *), struct passwd50 * (*)(uid_t));
+#endif
+
+struct passwd  *__getpwuid50(uid_t);
+struct passwd  *__getpwnam50(const char *);
+#if (_POSIX_C_SOURCE - 0) >= 199506L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_REENTRANT) || defined(_NETBSD_SOURCE)
+int             __getpwnam_r50(const char *, struct passwd *, char *, size_t,
+    struct passwd **);
+int             __getpwuid_r50(uid_t, struct passwd *, char *, size_t,
+    struct passwd **);
+#endif
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+struct passwd  *__getpwent50(void);
+#endif
+#if defined(_NETBSD_SOURCE)
+int             __pw_scan50(char *, struct passwd *, int *);
+int             __getpwent_r50(struct passwd *, char *, size_t, struct passwd **);
+#endif
+int             setpassent(int);
+#if defined(_NETBSD_SOURCE)
+int             __pwcache_userdb50(int (*)(int), void (*)(void),
+    struct passwd * (*)(const char *), struct passwd * (*)(uid_t));
+#endif
+__END_DECLS
+
+#endif /* !_COMPAT_PWD_H_ */
diff --git a/lib/nbsd_libc/compat/include/rpc/pmap_clnt.h b/lib/nbsd_libc/compat/include/rpc/pmap_clnt.h
new file mode 100644 (file)
index 0000000..5e075c2
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: pmap_clnt.h,v 1.2 2009/01/11 03:56:22 christos Exp $   */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _COMPAT_RPC_PMAP_CLNT_H_
+#define _COMPAT_RPC_PMAP_CLNT_H_
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+extern enum clnt_stat  pmap_rmtcall(struct sockaddr_in *,
+    u_long, u_long, u_long, xdrproc_t, caddr_t, xdrproc_t, caddr_t,
+    struct timeval50, u_long *);
+extern enum clnt_stat  __pmap_rmtcall50(struct sockaddr_in *,
+    u_long, u_long, u_long, xdrproc_t, caddr_t, xdrproc_t, caddr_t,
+    struct timeval, u_long *);
+__END_DECLS
+
+#endif /* !_RPC_PMAP_CLNT_H_ */
diff --git a/lib/nbsd_libc/compat/include/rpc/rpcb_clnt.h b/lib/nbsd_libc/compat/include/rpc/rpcb_clnt.h
new file mode 100644 (file)
index 0000000..e751b65
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: rpcb_clnt.h,v 1.2 2009/01/11 03:56:22 christos Exp $   */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _COMPAT_RPC_RPCB_CLNT_H
+#define        _COMPAT_RPC_RPCB_CLNT_H
+
+__BEGIN_DECLS
+
+extern enum clnt_stat rpcb_rmtcall(const struct netconfig *,
+    const char *, const rpcprog_t, const rpcvers_t, const rpcproc_t,
+    const xdrproc_t, const char *, const xdrproc_t, caddr_t,
+    const struct timeval50, const struct netbuf *);
+extern bool_t rpcb_gettime(const char *, int32_t *);
+extern enum clnt_stat __rpcb_rmtcall50(const struct netconfig *,
+    const char *, const rpcprog_t, const rpcvers_t, const rpcproc_t,
+    const xdrproc_t, const char *, const xdrproc_t, caddr_t,
+    const struct timeval, const struct netbuf *);
+extern bool_t __rpcb_gettime50(const char *, time_t *);
+
+__END_DECLS
+
+#endif /* !_COMPAT_RPC_RPCB_CLNT_H */
diff --git a/lib/nbsd_libc/compat/include/setjmp.h b/lib/nbsd_libc/compat/include/setjmp.h
new file mode 100644 (file)
index 0000000..6160931
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: setjmp.h,v 1.1 2005/09/13 01:44:09 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     @(#)setjmp.h    8.2 (Berkeley) 1/21/94
+ */
+
+#ifndef _COMPAT_SETJMP_H_
+#define _COMPAT_SETJMP_H_
+
+__BEGIN_DECLS
+int    __setjmp14(jmp_buf);
+void   __longjmp14(jmp_buf, int) __attribute__((__noreturn__));
+
+int    __sigsetjmp14(sigjmp_buf, int);
+void   __siglongjmp14(sigjmp_buf, int) __attribute__((__noreturn__));
+__END_DECLS
+
+#endif /* !_COMPAT_SETJMP_H_ */
diff --git a/lib/nbsd_libc/compat/include/signal.h b/lib/nbsd_libc/compat/include/signal.h
new file mode 100644 (file)
index 0000000..e78a2a9
--- /dev/null
@@ -0,0 +1,83 @@
+/*     $NetBSD: signal.h,v 1.2 2009/01/11 02:46:25 christos Exp $      */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ *
+ *     @(#)signal.h    8.3 (Berkeley) 3/30/94
+ */
+
+#ifndef _COMPAT_SIGNAL_H_
+#define _COMPAT_SIGNAL_H_
+
+#include <compat/sys/signal.h>
+
+__BEGIN_DECLS
+int    sigaction(int, const struct sigaction13 * __restrict,
+    struct sigaction13 * __restrict);
+int    __sigaction14(int, const struct sigaction * __restrict,
+    struct sigaction * __restrict);
+int    sigaddset(sigset13_t *, int);
+int    __sigaddset14(sigset_t *, int);
+int    sigdelset(sigset13_t *, int);
+int    __sigdelset14(sigset_t *, int);
+int    sigemptyset(sigset13_t *);
+int    __sigemptyset14(sigset_t *);
+int    sigfillset(sigset13_t *);
+int    __sigfillset14(sigset_t *);
+int    sigismember(const sigset13_t *, int);
+int    __sigismember14(const sigset_t *, int);
+int    sigpending(sigset13_t *);
+int    __sigpending14(sigset_t *);
+int    sigprocmask(int, const sigset13_t * __restrict,
+    sigset13_t * __restrict);
+int    __sigprocmask14(int, const sigset_t * __restrict,
+    sigset_t * __restrict);
+int    sigsuspend(const sigset13_t *);
+int    __sigsuspend14(const sigset_t *);
+
+int    sigtimedwait(const sigset_t * __restrict,
+    siginfo_t * __restrict, const struct timespec50 * __restrict);
+int    __sigtimedwait(const sigset_t * __restrict,
+    siginfo_t * __restrict, struct timespec50 * __restrict);
+int    __sigtimedwait50(const sigset_t * __restrict,
+    siginfo_t * __restrict, const struct timespec * __restrict);
+int    ____sigtimedwait50(const sigset_t * __restrict,
+    siginfo_t * __restrict, struct timespec * __restrict);
+/*
+ * X/Open CAE Specification Issue 4 Version 2
+ */      
+#if (defined(_XOPEN_SOURCE) && defined(_XOPEN_SOURCE_EXTENDED)) || \
+    (_XOPEN_SOURCE - 0) >= 500 || defined(_NETBSD_SOURCE)
+int    sigaltstack(const struct sigaltstack13 * __restrict,
+    struct sigaltstack13 * __restrict);
+int    __sigaltstack14(const stack_t * __restrict, stack_t * __restrict);
+#endif /* _XOPEN_SOURCE_EXTENDED || _XOPEN_SOURCE >= 500 || _NETBSD_SOURCE */
+
+__END_DECLS
+
+#endif /* !_COMPAT_SIGNAL_H_ */
diff --git a/lib/nbsd_libc/compat/include/stdlib.h b/lib/nbsd_libc/compat/include/stdlib.h
new file mode 100644 (file)
index 0000000..1295041
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: stdlib.h,v 1.4 2009/01/26 15:05:56 drochner Exp $      */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)stdlib.h    8.5 (Berkeley) 5/19/95
+ */
+
+#ifndef _COMPAT_STDLIB_H_
+#define _COMPAT_STDLIB_H_
+
+__BEGIN_DECLS
+
+void    unsetenv(const char *);
+int     __unsetenv13(const char *);
+__aconst char *devname(int32_t, mode_t);
+__aconst char *__devname50(dev_t, mode_t);
+
+__END_DECLS
+
+#endif /* !_COMPAT_STDLIB_H_ */
diff --git a/lib/nbsd_libc/compat/include/time.h b/lib/nbsd_libc/compat/include/time.h
new file mode 100644 (file)
index 0000000..c0842f5
--- /dev/null
@@ -0,0 +1,106 @@
+/*     $NetBSD: time.h,v 1.3 2010/12/16 18:38:06 christos Exp $        */
+
+/*
+ * Copyright (c) 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     @(#)time.h      8.3 (Berkeley) 1/21/94
+ */
+
+#ifndef _COMPAT_TIME_H_
+#define        _COMPAT_TIME_H_
+
+#include <compat/sys/time.h>
+#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+#define CLK_TCK 100
+#endif
+
+__BEGIN_DECLS
+#if (_XOPEN_SOURCE - 0) >= 4 || defined(_NETBSD_SOURCE)
+char *strptime(const char * __restrict, const char * __restrict,
+    struct tm * __restrict);
+#if 0
+#if defined(_NETBSD_SOURCE)
+char *timezone(int, int);
+#endif /* _NETBSD_SOURCE */
+#endif
+
+#endif /* !_ANSI_SOURCE */
+char *ctime(const int32_t *);
+double difftime(int32_t, int32_t);
+struct tm *gmtime(const int32_t *);
+struct tm *localtime(const int32_t *);
+int32_t time(int32_t *);
+int32_t mktime(struct tm *);
+void tzset(void);
+void tzsetwall(void);
+void __tzset50(void);
+void __tzsetwall50(void);
+
+int clock_getres(clockid_t, struct timespec50 *);
+int clock_gettime(clockid_t, struct timespec50 *);
+int clock_settime(clockid_t, const struct timespec50 *);
+int __clock_getres50(clockid_t, struct timespec *);
+int __clock_gettime50(clockid_t, struct timespec *);
+int __clock_settime50(clockid_t, const struct timespec *);
+int nanosleep(const struct timespec50 *, struct timespec50 *);
+int __nanosleep50(const struct timespec *, struct timespec *);
+int timer_gettime(timer_t, struct itimerspec50 *);
+int timer_settime(timer_t, int, const struct itimerspec50 * __restrict, 
+    struct itimerspec50 * __restrict);
+int __timer_gettime50(timer_t, struct itimerspec *);
+int __timer_settime50(timer_t, int, const struct itimerspec * __restrict, 
+    struct itimerspec * __restrict);
+int __timer_getres50(timer_t, struct itimerspec *);
+char *ctime_r(const int32_t *, char *);
+struct tm *gmtime_r(const int32_t * __restrict, struct tm * __restrict);
+struct tm *localtime_r(const int32_t * __restrict, struct tm * __restrict);
+struct tm *offtime(const int32_t *, long);
+struct tm *offtime_r(const int32_t *, long, struct tm *);
+int32_t timelocal(struct tm *);
+int32_t timegm(struct tm *);
+int32_t timeoff(struct tm *, long);
+int32_t time2posix(int32_t);
+int32_t posix2time(int32_t);
+struct tm *localtime_rz(const timezone_t, const int32_t * __restrict,
+    struct tm * __restrict);
+char *ctime_rz(const timezone_t, const int32_t *, char *);
+int32_t mktime_z(const timezone_t, struct tm *);
+int32_t timelocal_z(const timezone_t, struct tm *);
+int32_t time2posix_z(const timezone_t, int32_t);
+int32_t posix2time_z(const timezone_t, int32_t);
+timezone_t tzalloc(const char *);
+void tzfree(const timezone_t);
+const char *tzgetname(const timezone_t, int);
+
+#endif /* !_COMPAT_TIME_H_ */
diff --git a/lib/nbsd_libc/compat/include/unistd.h b/lib/nbsd_libc/compat/include/unistd.h
new file mode 100644 (file)
index 0000000..d607a01
--- /dev/null
@@ -0,0 +1,71 @@
+/*     $NetBSD: unistd.h,v 1.2 2008/04/28 20:22:59 martin Exp $        */
+
+/*-
+ * Copyright (c) 1998, 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * Copyright (c) 1991, 1993, 1994
+ *     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.
+ * 3. 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.
+ *
+ *     @(#)unistd.h    8.12 (Berkeley) 4/27/95
+ */
+
+#ifndef _COMPAT_UNISTD_H_
+#define        _COMPAT_UNISTD_H_
+
+__BEGIN_DECLS
+pid_t   vfork(void);
+pid_t   __vfork14(void);
+__END_DECLS
+
+#endif /* !_COMPAT_UNISTD_H_ */
diff --git a/lib/nbsd_libc/compat/include/utime.h b/lib/nbsd_libc/compat/include/utime.h
new file mode 100644 (file)
index 0000000..33be9e9
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: utime.h,v 1.2 2009/01/11 02:46:25 christos Exp $       */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)utime.h     8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef        _COMPAT_UTIME_H_
+#define        _COMPAT_UTIME_H_
+
+#include <machine/ansi.h>
+
+struct utimbuf50 {
+       int32_t actime;         /* Access time */
+       int32_t modtime;        /* Modification time */
+};
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+int utime(const char *, const struct utimbuf50 *);
+int __utime50(const char *, const struct utimbuf *);
+__END_DECLS
+
+#endif /* !_COMPAT_UTIME_H_ */
diff --git a/lib/nbsd_libc/compat/include/utmp.h b/lib/nbsd_libc/compat/include/utmp.h
new file mode 100644 (file)
index 0000000..f6b7f13
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: utmp.h,v 1.2 2009/01/11 02:46:25 christos Exp $        */
+
+/*
+ * Copyright (c) 1988, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     @(#)utmp.h      8.2 (Berkeley) 1/21/94
+ */
+
+#ifndef        _COMPAT_UTMP_H_
+#define        _COMPAT_UTMP_H_
+
+struct utmp50 {
+       char    ut_line[UT_LINESIZE];
+       char    ut_name[UT_NAMESIZE];
+       char    ut_host[UT_HOSTSIZE];
+       int32_t ut_time;
+};
+
+__BEGIN_DECLS
+static __inline void
+utmp_to_utmp50(const struct utmp *ut, struct utmp50 *ut50)
+{
+       (void)memcpy(ut50, ut, sizeof(*ut50));
+       ut50->ut_time = (int32_t)ut->ut_time;
+}
+
+static __inline void
+utmp50_to_utmp(const struct utmp50 *ut50, struct utmp *ut)
+{
+       (void)memcpy(ut, ut50, sizeof(*ut50));
+       ut->ut_time = ut50->ut_time;
+}
+
+struct utmp50 *getutent(void);
+struct utmp *__getutent50(void);
+__END_DECLS
+
+#endif /* !_COMPAT_UTMP_H_ */
diff --git a/lib/nbsd_libc/compat/include/utmpx.h b/lib/nbsd_libc/compat/include/utmpx.h
new file mode 100644 (file)
index 0000000..ee20196
--- /dev/null
@@ -0,0 +1,101 @@
+/*     $NetBSD: utmpx.h,v 1.3 2009/01/11 02:46:25 christos Exp $        */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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        _COMPAT_UTMPX_H_
+#define        _COMPAT_UTMPX_H_
+
+#include <compat/sys/time.h>
+
+struct utmpx50 {
+       char ut_name[_UTX_USERSIZE];    /* login name */
+       char ut_id[_UTX_IDSIZE];        /* inittab id */
+       char ut_line[_UTX_LINESIZE];    /* tty name */
+       char ut_host[_UTX_HOSTSIZE];    /* host name */
+       uint16_t ut_session;            /* session id used for windowing */
+       uint16_t ut_type;               /* type of this entry */
+       pid_t ut_pid;                   /* process id creating the entry */
+       struct {
+               uint16_t e_termination; /* process termination signal */
+               uint16_t e_exit;        /* process exit status */
+       } ut_exit;
+       struct sockaddr_storage ut_ss;  /* address where entry was made from */
+       struct timeval50 ut_tv;         /* time entry was created */
+       uint32_t ut_pad[10];            /* reserved for future use */
+};
+
+struct lastlogx50 {
+       struct timeval50 ll_tv;         /* time entry was created */
+       char ll_line[_UTX_LINESIZE];    /* tty name */
+       char ll_host[_UTX_HOSTSIZE];    /* host name */
+       struct sockaddr_storage ll_ss;  /* address where entry was made from */
+};
+
+__BEGIN_DECLS
+
+static __inline void
+utmpx50_to_utmpx(const struct utmpx50 *ut50, struct utmpx *ut)
+{
+       (void)memcpy(ut, ut50, sizeof(*ut));
+       timeval50_to_timeval(&ut50->ut_tv, &ut->ut_tv);
+}
+
+static __inline void
+utmpx_to_utmpx50(const struct utmpx *ut, struct utmpx50 *ut50)
+{
+       (void)memcpy(ut50, ut, sizeof(*ut50));
+       timeval_to_timeval50(&ut->ut_tv, &ut50->ut_tv);
+}
+
+struct utmpx50 *getutxent(void);
+struct utmpx *__getutxent50(void);
+struct utmpx50 *getutxid(const struct utmpx50 *);
+struct utmpx *__getutxid50(const struct utmpx *);
+struct utmpx50 *getutxline(const struct utmpx50 *);
+struct utmpx *__getutxline50(const struct utmpx *);
+struct utmpx50 *pututxline(const struct utmpx50 *);
+struct utmpx *__pututxline50(const struct utmpx *);
+int updwtmpx(const char *, const struct utmpx50 *);
+int __updwtmpx50(const char *, const struct utmpx *);
+int updlastlogx(const char *, uid_t, struct lastlogx50 *);
+int __updlastlogx50(const char *, uid_t, struct lastlogx *);
+struct utmp;
+void getutmp(const struct utmpx50 *, struct utmp *);
+void __getutmp50(const struct utmpx *, struct utmp *);
+void getutmpx(const struct utmp *, struct utmpx50 *);
+void __getutmpx50(const struct utmp *, struct utmpx *);
+
+int lastlogxname(const char *);
+struct lastlogx50 *getlastlogx(uid_t, struct lastlogx50 *);
+struct lastlogx50 *__getlastlogx13(const char *, uid_t, struct lastlogx50 *);
+struct lastlogx *__getlastlogx50(const char *, uid_t, struct lastlogx *);
+
+__END_DECLS
+
+#endif /* !_COMPAT_UTMPX_H_ */
diff --git a/lib/nbsd_libc/compat/include/vis.h b/lib/nbsd_libc/compat/include/vis.h
new file mode 100644 (file)
index 0000000..83b17c6
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: vis.h,v 1.1 2005/09/13 01:44:09 christos Exp $ */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)vis.h       8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _COMPAT_VIS_H_
+#define        _COMPAT_VIS_H_
+
+__BEGIN_DECLS
+int    unvis(char *, int, int *, int);
+int    __unvis13(char *, int, int *, int);
+__END_DECLS
+
+#endif /* !_COMPAT_VIS_H_ */
diff --git a/lib/nbsd_libc/compat/locale/Makefile.inc b/lib/nbsd_libc/compat/locale/Makefile.inc
new file mode 100644 (file)
index 0000000..b714fcc
--- /dev/null
@@ -0,0 +1,6 @@
+# $NetBSD: Makefile.inc,v 1.1 2010/06/07 13:52:30 tnozaki Exp $
+
+.PATH: ${COMPATDIR}/arch/${MACHINE_ARCH}/locale ${COMPATDIR}/locale
+
+CPPFLAGS+=     -I${COMPATDIR}/../locale
+SRCS+=         compat_setlocale1.c compat_setlocale32.c
diff --git a/lib/nbsd_libc/compat/locale/compat_setlocale1.c b/lib/nbsd_libc/compat/locale/compat_setlocale1.c
new file mode 100644 (file)
index 0000000..bb4230d
--- /dev/null
@@ -0,0 +1,57 @@
+/* $NetBSD: compat_setlocale1.c,v 1.1 2010/06/07 13:52:30 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ * NetBSD: setlocale1.c,v 1.4 2010/05/22 13:50:02 tnozaki Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_setlocale1.c,v 1.1 2010/06/07 13:52:30 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <compat/include/locale.h>
+
+#include "setlocale_local.h"
+
+__warn_references(setlocale,
+    "warning: reference to compatibility setlocale();"
+    "include <locale.h> for correct reference")
+
+/*
+ * Preparation for the future import of multibyte locale.
+ * This function will ensure binary compatibility for old executables.
+ */
+char *
+setlocale(int category, const char *locale)
+{
+
+       /* locale may be NULL */
+
+       __mb_len_max_runtime = 1;
+       return __setlocale(category, locale);
+}
diff --git a/lib/nbsd_libc/compat/locale/compat_setlocale32.c b/lib/nbsd_libc/compat/locale/compat_setlocale32.c
new file mode 100644 (file)
index 0000000..28cd07e
--- /dev/null
@@ -0,0 +1,53 @@
+/* $NetBSD: compat_setlocale32.c,v 1.1 2010/06/07 13:52:30 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ * NetBSD: setlocale32.c,v 1.6 2010/05/22 13:50:02 tnozaki Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_setlocale32.c,v 1.1 2010/06/07 13:52:30 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <compat/include/locale.h>
+
+#include "setlocale_local.h"
+
+__warn_references(__setlocale_mb_len_max_32,
+    "warning: reference to compatibility __setlocale_mb_len_max_32();"
+    "include <locale.h> for correct reference")
+
+char *
+__setlocale_mb_len_max_32(int category, const char *locale)
+{
+
+       /* locale may be NULL */
+
+       __mb_len_max_runtime = 32;
+       return __setlocale(category, locale);
+}
diff --git a/lib/nbsd_libc/compat/net/Makefile.inc b/lib/nbsd_libc/compat/net/Makefile.inc
new file mode 100644 (file)
index 0000000..1a59b93
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.1 2006/08/26 16:07:01 matt Exp $
+
+.PATH: ${COMPATDIR}/net
+SRCS+=compat_ns_addr.c compat_ns_ntoa.c
diff --git a/lib/nbsd_libc/compat/net/compat_ns_addr.c b/lib/nbsd_libc/compat/net/compat_ns_addr.c
new file mode 100644 (file)
index 0000000..be55f3b
--- /dev/null
@@ -0,0 +1,250 @@
+/*     $NetBSD: compat_ns_addr.c,v 1.1 2006/08/26 16:07:01 matt Exp $  */
+
+/*
+ * Copyright (c) 1986, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * J.Q. Johnson.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ns_addr.c  8.1 (Berkeley) 6/7/93";
+#else
+__RCSID("$NetBSD: compat_ns_addr.c,v 1.1 2006/08/26 16:07:01 matt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <compat/include/ns.h>
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+static void Field __P((char *, u_int8_t *, int));
+static void cvtbase __P((long, int, int[], int, u_int8_t[], int));
+
+struct ns_addr 
+ns_addr(name)
+       const char *name;
+{
+       char separator;
+       char *hostname, *socketname, *cp;
+       char buf[50];
+       static struct ns_addr addr;
+
+       _DIAGASSERT(name != NULL);
+
+       (void)strlcpy(buf, name, sizeof(buf));
+
+       /*
+        * First, figure out what he intends as a field separtor.
+        * Despite the way this routine is written, the prefered
+        * form  2-272.AA001234H.01777, i.e. XDE standard.
+        * Great efforts are made to insure backward compatibility.
+        */
+       if ((hostname = strchr(buf, '#')) != NULL)
+               separator = '#';
+       else {
+               hostname = strchr(buf, '.');
+               if ((cp = strchr(buf, ':')) &&
+                   ((hostname && cp < hostname) || (hostname == 0))) {
+                       hostname = cp;
+                       separator = ':';
+               } else
+                       separator = '.';
+       }
+       if (hostname)
+               *hostname++ = 0;
+
+       memset(&addr, '\0', sizeof(addr));
+       Field(buf, addr.x_net.c_net, 4);
+       if (hostname == 0)
+               return (addr);  /* No separator means net only */
+
+       socketname = strchr(hostname, separator);
+       if (socketname) {
+               *socketname++ = 0;
+               Field(socketname, (u_int8_t *)(void *)&addr.x_port, 2);
+       }
+
+       Field(hostname, addr.x_host.c_host, 6);
+
+       return (addr);
+}
+
+static void
+Field(buf, out, len)
+       char *buf;
+       u_int8_t *out;
+       int len;
+{
+       register char *bp = buf;
+       int i, ibase, base16 = 0, base10 = 0, clen = 0;
+       int hb[6], *hp;
+
+       _DIAGASSERT(buf != NULL);
+       _DIAGASSERT(out != NULL);
+
+       /*
+        * first try 2-273#2-852-151-014#socket
+        */
+       if ((*buf != '-') &&
+           (1 < (i = sscanf(buf, "%d-%d-%d-%d-%d",
+                       &hb[0], &hb[1], &hb[2], &hb[3], &hb[4])))) {
+               cvtbase(1000L, 256, hb, i, out, len);
+               return;
+       }
+       /*
+        * try form 8E1#0.0.AA.0.5E.E6#socket
+        */
+       if (1 < (i = sscanf(buf,"%x.%x.%x.%x.%x.%x",
+                       &hb[0], &hb[1], &hb[2], &hb[3], &hb[4], &hb[5]))) {
+               cvtbase(256L, 256, hb, i, out, len);
+               return;
+       }
+       /*
+        * try form 8E1#0:0:AA:0:5E:E6#socket
+        */
+       if (1 < (i = sscanf(buf,"%x:%x:%x:%x:%x:%x",
+                       &hb[0], &hb[1], &hb[2], &hb[3], &hb[4], &hb[5]))) {
+               cvtbase(256L, 256, hb, i, out, len);
+               return;
+       }
+       /*
+        * This is REALLY stretching it but there was a
+        * comma notation separting shorts -- definitely non standard
+        */
+       if (1 < (i = sscanf(buf,"%x,%x,%x",
+                       &hb[0], &hb[1], &hb[2]))) {
+               hb[0] = htons(hb[0]); hb[1] = htons(hb[1]);
+               hb[2] = htons(hb[2]);
+               cvtbase(65536L, 256, hb, i, out, len);
+               return;
+       }
+
+       /* Need to decide if base 10, 16 or 8 */
+       while (*bp) switch (*bp++) {
+
+       case '0': case '1': case '2': case '3': case '4': case '5':
+       case '6': case '7': case '-':
+               break;
+
+       case '8': case '9':
+               base10 = 1;
+               break;
+
+       case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
+       case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
+               base16 = 1;
+               break;
+       
+       case 'x': case 'X':
+               *--bp = '0';
+               base16 = 1;
+               break;
+
+       case 'h': case 'H':
+               base16 = 1;
+               /* FALLTHROUGH */
+
+       default:
+               *--bp = 0; /* Ends Loop */
+       }
+       if (base16) {
+               ibase = 4096;
+       } else if (base10 == 0 && *buf == '0') {
+               ibase = 512;
+       } else {
+               base10 = 1;
+               ibase = 1000;
+       }
+
+       for (bp = buf; *bp++; ) clen++;
+       if (clen == 0) clen++;
+       if (clen > 18) clen = 18;
+       i = ((clen - 1) / 3) + 1;
+       bp = clen + buf - 3;
+       hp = hb + i - 1;
+
+       while (hp > hb) {
+               if (base16)
+                       (void)sscanf(bp, "%3x", hp);
+               else if (base10)
+                       (void)sscanf(bp, "%3d", hp);
+               else
+                       (void)sscanf(bp, "%3o", hp);
+
+               bp[0] = 0;
+               hp--;
+               bp -= 3;
+       }
+       if (base16)
+               (void)sscanf(buf, "%3x", hp);
+       else if (base10)
+               (void)sscanf(buf, "%3d", hp);
+       else
+               (void)sscanf(buf, "%3o", hp);
+
+       cvtbase((long)ibase, 256, hb, i, out, len);
+}
+
+static void
+cvtbase(oldbase,newbase,input,inlen,result,reslen)
+       long oldbase;
+       int newbase;
+       int input[];
+       int inlen;
+       unsigned char result[];
+       int reslen;
+{
+       int d, e;
+       long sum;
+
+       _DIAGASSERT(input != NULL);
+       _DIAGASSERT(result != NULL);
+
+       e = 1;
+       while (e > 0 && reslen > 0) {
+               d = 0; e = 0; sum = 0;
+               /* long division: input=input/newbase */
+               while (d < inlen) {
+                       sum = sum*oldbase + (long) input[d];
+                       e += (sum > 0);
+                       input[d++] = (int) (sum / newbase);
+                       sum %= newbase;
+               }
+               /* accumulate remainder */
+               result[--reslen] = (unsigned char)sum;
+       }
+       for (d=0; d < reslen; d++)
+               result[d] = 0;
+}
diff --git a/lib/nbsd_libc/compat/net/compat_ns_ntoa.c b/lib/nbsd_libc/compat/net/compat_ns_ntoa.c
new file mode 100644 (file)
index 0000000..469b2e7
--- /dev/null
@@ -0,0 +1,111 @@
+/*     $NetBSD: compat_ns_ntoa.c,v 1.1 2006/08/26 16:07:01 matt Exp $  */
+
+/*
+ * Copyright (c) 1986, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ns_ntoa.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: compat_ns_ntoa.c,v 1.1 2006/08/26 16:07:01 matt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/param.h>
+#include <compat/include/ns.h>
+
+#include <assert.h>
+#include <stdio.h>
+
+static char *spectHex __P((char *));
+
+char *
+ns_ntoa(addr)
+       struct ns_addr addr;
+{
+       static char obuf[40];
+       union { union ns_net net_e; u_int32_t long_e; } net;
+       u_int16_t port = htons(addr.x_port);
+       char *cp;
+       char *cp2;
+       u_int8_t *up = addr.x_host.c_host;
+       u_int8_t *uplim = up + 6;
+
+       net.net_e = addr.x_net;
+       sprintf(obuf, "%x", ntohl(net.long_e));
+       cp = spectHex(obuf);
+       cp2 = cp + 1;
+       while (up < uplim && *up==0)
+               up++;
+       if (up == uplim) {
+               if (port) {
+                       sprintf(cp, ".0");
+                       cp += 2;
+               }
+       } else {
+               sprintf(cp, ".%x", *up++);
+               while (up < uplim) {
+                       while (*cp) cp++;
+                       sprintf(cp, "%02x", *up++);
+               }
+               cp = spectHex(cp2);
+       }
+       if (port) {
+               sprintf(cp, ".%x", port);
+               spectHex(cp + 1);
+       }
+       return (obuf);
+}
+
+static char *
+spectHex(p0)
+       char *p0;
+{
+       int ok = 0;
+       int nonzero = 0;
+       char *p = p0;
+
+       _DIAGASSERT(p0 != NULL);
+
+       for (; *p; p++)
+               switch (*p) {
+               case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
+                       *p += ('A' - 'a');
+                       /* FALLTHROUGH */
+               case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
+                       ok = 1;
+                       /* FALLTHROUGH */
+               case '1': case '2': case '3': case '4': case '5':
+               case '6': case '7': case '8': case '9':
+                       nonzero = 1;
+               }
+       if (nonzero && !ok) { *p++ = 'H'; *p = 0; }
+       return (p);
+}
diff --git a/lib/nbsd_libc/compat/rpc/Makefile.inc b/lib/nbsd_libc/compat/rpc/Makefile.inc
new file mode 100644 (file)
index 0000000..32de61f
--- /dev/null
@@ -0,0 +1,5 @@
+#      $NetBSD: Makefile.inc,v 1.2 2009/01/11 03:41:28 christos Exp $
+
+.PATH: ${COMPATDIR}/rpc
+
+SRCS+=compat_pmap_rmtcall.c compat_rpcb.c
diff --git a/lib/nbsd_libc/compat/rpc/compat_pmap_rmtcall.c b/lib/nbsd_libc/compat/rpc/compat_pmap_rmtcall.c
new file mode 100644 (file)
index 0000000..fb82c7a
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: compat_pmap_rmtcall.c,v 1.2 2009/01/11 03:41:28 christos Exp $ */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_pmap_rmtcall.c,v 1.2 2009/01/11 03:41:28 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <rpc/rpc.h>
+#include <compat/include/rpc/pmap_clnt.h>
+
+__warn_references(pmap_rmtcall,
+    "warning: reference to compatibility pmap_rmtcall(); include <rpc/pmap_clnt.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(pmap_rmtcall, _pmap_rmtcall)
+#endif
+
+enum clnt_stat
+pmap_rmtcall(struct sockaddr_in *addr, u_long prognum, u_long versnum,
+    u_long procnum, xdrproc_t inproc, char *in, xdrproc_t outproc,
+    char *out, struct timeval50 tout50, u_long *portp)
+{
+       struct timeval tout;
+       timeval50_to_timeval(&tout50, &tout);
+       return __pmap_rmtcall50(addr, prognum, versnum, procnum, inproc, in,
+           outproc, out, tout, portp);
+}
diff --git a/lib/nbsd_libc/compat/rpc/compat_rpcb.c b/lib/nbsd_libc/compat/rpc/compat_rpcb.c
new file mode 100644 (file)
index 0000000..b547d53
--- /dev/null
@@ -0,0 +1,83 @@
+/*     $NetBSD: compat_rpcb.c,v 1.2 2009/01/11 03:41:28 christos Exp $ */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_rpcb.c,v 1.2 2009/01/11 03:41:28 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <rpc/rpcb_clnt.h>
+#include <compat/include/rpc/rpcb_clnt.h>
+
+__warn_references(rpcb_rmtcall,
+    "warning: reference to compatibility rpcb_rmtcall(); include <rpc/rpcb_clnt.h> to generate correct reference")
+__warn_references(rpcb_gettime,
+    "warning: reference to compatibility rpcb_gettime(); include <rpc/rpcb_clnt.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(rpcb_rmtcall, _rpcb_rmtcall)
+__weak_alias(rpcb_gettime, _rpcb_gettime)
+#endif
+
+enum clnt_stat
+rpcb_rmtcall(const struct netconfig *nc,
+    const char *name, const rpcprog_t prog, const rpcvers_t vers,
+    const rpcproc_t proc, const xdrproc_t inproc, const char *inbuf,
+    const xdrproc_t outproc, caddr_t outbuf,
+    const struct timeval50 tout50, const struct netbuf *nb)
+{
+       struct timeval tout;
+       timeval50_to_timeval(&tout50, &tout);
+       return __rpcb_rmtcall50(nc, name, prog, vers, proc, inproc, inbuf,
+           outproc, outbuf, tout, nb);
+}
+
+bool_t
+rpcb_gettime(const char *name, int32_t *t50)
+{
+       time_t t;
+       bool_t rv = __rpcb_gettime50(name, &t);
+       *t50 = (int32_t)t;
+       return rv;
+}
diff --git a/lib/nbsd_libc/compat/shlib_version b/lib/nbsd_libc/compat/shlib_version
new file mode 100644 (file)
index 0000000..5b1659f
--- /dev/null
@@ -0,0 +1,5 @@
+#      $NetBSD: shlib_version,v 1.1 2006/03/11 21:07:18 christos Exp $
+#      Remember to update distrib/sets/lists/base/shl.* when changing
+#
+major=0
+minor=0
diff --git a/lib/nbsd_libc/compat/stdlib/Makefile.inc b/lib/nbsd_libc/compat/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..c844080
--- /dev/null
@@ -0,0 +1,5 @@
+#      $NetBSD: Makefile.inc,v 1.2 2006/03/11 21:07:18 christos Exp $
+
+.PATH: ${COMPATDIR}/stdlib
+CPPFLAGS+=-I${COMPATDIR}/stdlib -I${COMPATDIR}/../stdlib
+SRCS+=compat_unsetenv.c 
diff --git a/lib/nbsd_libc/compat/stdlib/compat_unsetenv.c b/lib/nbsd_libc/compat/stdlib/compat_unsetenv.c
new file mode 100644 (file)
index 0000000..3c89812
--- /dev/null
@@ -0,0 +1,87 @@
+/*     $NetBSD: compat_unsetenv.c,v 1.3 2010/11/14 18:11:42 tron Exp $ */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "from: @(#)setenv.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: compat_unsetenv.c,v 1.3 2010/11/14 18:11:42 tron Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <compat/include/stdlib.h>
+#include <string.h>
+#include <bitstring.h>
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(unsetenv,_unsetenv)
+#endif
+
+#include "env.h"
+
+__warn_references(unsetenv,
+    "warning: reference to compatibility unsetenv();"
+    " include <stdlib.h> for correct reference")
+
+/*
+ * unsetenv(name) --
+ *     Delete environmental variable "name".
+ */
+void
+unsetenv(const char *name)
+{
+       size_t l_name;
+
+       _DIAGASSERT(name != NULL);
+
+       l_name = strlen(name);
+       if (__writelockenv()) {
+               ssize_t offset;
+
+               while ((offset = __getenvslot(name, l_name, false)) != -1) {
+                       char **p;               
+                       for (p = &environ[offset]; ; ++p) {
+                               if ((*p = *(p + 1)) == NULL)
+                                       break;
+                       }
+               }
+               (void)__unlockenv();
+       }
+}
diff --git a/lib/nbsd_libc/compat/sys/Lint_Ovfork.c b/lib/nbsd_libc/compat/sys/Lint_Ovfork.c
new file mode 100644 (file)
index 0000000..33cd226
--- /dev/null
@@ -0,0 +1,21 @@
+/* $NetBSD: Lint_Ovfork.c,v 1.1 2006/03/11 21:07:18 christos Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#if 0
+#include <unistd.h>
+#else
+#include <sys/cdefs.h>
+#include <sys/types.h>
+pid_t vfork __P((void));
+#endif
+
+/*ARGSUSED*/
+pid_t
+vfork()
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/compat/sys/Makefile.inc b/lib/nbsd_libc/compat/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..25031df
--- /dev/null
@@ -0,0 +1,20 @@
+#      $NetBSD: Makefile.inc,v 1.8 2009/01/11 02:46:25 christos Exp $
+
+.PATH: ${COMPATDIR}/sys
+SRCS+= compat_getdents.c compat_getdirentries.c compat_msync.c \
+    compat_ntp_gettime.c compat_sched.c \
+    compat_semctl.c compat_sigaltstack.c compat_stat.c compat___stat13.c \
+    compat_statfs.c compat_socket.c compat_getfh.c \
+    compat_fhopen.c compat___fhstat30.c compat_fhstatvfs.c compat_fhstatvfs1.c \
+    compat_mount.c compat_getrusage.c compat_gettimeofday.c compat_utimes.c \
+    compat_wait4.c compat_sigtimedwait.c compat_settimeofday.c compat_timer.c \
+    compat_clock.c compat_itimer.c compat_select.c compat_nanosleep.c \
+    compat___stat30.c compat_aio_suspend.c compat_adjtime.c compat_mknod.c \
+    compat_mqueue.c compat__lwp_park.c compat_lfs_segwait.c compat_kevent.c \
+    compat___ntp_gettime30.c compat___semctl13.c compat___shmctl13.c \
+    compat___msgctl13.c
+MAN+=  getdirentries.3
+
+.if ${MKLINT} != "no"
+LSRCS+= Lint_Ovfork.c
+.endif
diff --git a/lib/nbsd_libc/compat/sys/compat___fhstat30.c b/lib/nbsd_libc/compat/sys/compat___fhstat30.c
new file mode 100644 (file)
index 0000000..39068c9
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: compat___fhstat30.c,v 1.4 2009/01/11 02:46:25 christos Exp $   */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Martin Husemann <martin@NetBSD.org>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat___fhstat30.c,v 1.4 2009/01/11 02:46:25 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <sys/types.h>
+#include <sys/mount.h>
+#include <compat/include/fstypes.h>
+#include <compat/sys/mount.h>
+
+__warn_references(fhstat,
+    "warning: reference to compatibility __fhstat30(); include <sys/mount.h> to generate correct reference")
+
+/*
+ * Convert old fhstat() call to new calling convention
+ */
+int
+__fhstat30(const struct compat_30_fhandle *fhp, struct stat30 *sb)
+{
+       return __fhstat40(fhp, FHANDLE30_SIZE, sb);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat___msgctl13.c b/lib/nbsd_libc/compat/sys/compat___msgctl13.c
new file mode 100644 (file)
index 0000000..a69b4ad
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: compat___msgctl13.c,v 1.2 2009/01/11 02:46:25 christos Exp $   */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat___msgctl13.c,v 1.2 2009/01/11 02:46:25 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <sys/msg.h>
+#include <compat/sys/msg.h>
+
+__warn_references(__msgctl13,
+    "warning: reference to compatibility __msgctl13(); include <sys/msg.h> to generate correct reference")
+
+int
+__msgctl13(int msqid, int cmd, struct msqid_ds13 *ds13)
+{
+       struct msqid_ds ds;
+       int error;
+
+       if (cmd == IPC_SET)
+               __msqid_ds13_to_native(ds13, &ds);
+
+       error = __msgctl50(msqid, cmd, &ds);
+       if (error)
+               return error;
+       if (cmd == IPC_STAT)
+               __native_to_msqid_ds13(&ds, ds13);
+       return 0;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat___ntp_gettime30.c b/lib/nbsd_libc/compat/sys/compat___ntp_gettime30.c
new file mode 100644 (file)
index 0000000..8511ec4
--- /dev/null
@@ -0,0 +1,30 @@
+/* $NetBSD: compat___ntp_gettime30.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat___ntp_gettime30.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <sys/time.h>
+#include <sys/timex.h>
+#include <compat/sys/timex.h>
+
+__warn_references(__ntp_gettime30,
+    "warning: reference to compatibility __ntp_gettime30(); include <sys/timex.h> for correct reference")
+
+int
+__ntp_gettime30(struct ntptimeval50 *ontvp)
+{
+       struct ntptimeval ntv;
+       int res;
+
+       res = __ntp_gettime50(&ntv);
+       ontvp->time.tv_sec = (int32_t)ntv.time.tv_sec;
+       ontvp->time.tv_nsec = ntv.time.tv_nsec;
+       ontvp->maxerror = ntv.maxerror;
+       ontvp->esterror = ntv.esterror;
+
+       return (res);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat___semctl13.c b/lib/nbsd_libc/compat/sys/compat___semctl13.c
new file mode 100644 (file)
index 0000000..94ca200
--- /dev/null
@@ -0,0 +1,98 @@
+/*     $NetBSD: compat___semctl13.c,v 1.2 2009/01/11 02:46:26 christos Exp $   */
+
+/*     $NetBSD: compat___semctl13.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat___semctl13.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <stdarg.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <sys/sem.h>
+#include <compat/sys/sem.h>
+
+__warn_references(__semctl13,
+    "warning: reference to compatibility __semctl13(); include <sys/sem.h> to generate correct reference")
+
+/*
+ * Copy timeout to local variable and call the syscall.
+ */
+int
+__semctl13(int semid, int semnum, int cmd, ...)
+{
+       va_list ap;
+       union __semun semun;
+       struct semid_ds13 *ds13;
+       struct semid_ds ds;
+       int error;
+
+       va_start(ap, cmd);
+       switch (cmd) {
+       case IPC_SET:
+       case IPC_STAT:
+       case GETALL:
+       case SETVAL:
+       case SETALL:
+#ifdef __lint__
+               memcpy(&semun, &ap, sizeof(semun));
+#else
+               semun = va_arg(ap, union __semun);
+#endif
+       }
+       va_end(ap);
+
+       ds13 = (struct semid_ds13 *)(void *)semun.buf;
+       semun.buf = &ds;
+
+       if (cmd == IPC_SET)
+               __semid_ds13_to_native(ds13, &ds);
+
+       error = ____semctl50(semid, semnum, cmd, &semun);
+       if (error)
+               return error;
+
+       if (cmd == IPC_STAT)
+               __native_to_semid_ds13(&ds, ds13);
+
+       semun.buf = (struct semid_ds *)(void *)ds13;
+       return 0;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat___shmctl13.c b/lib/nbsd_libc/compat/sys/compat___shmctl13.c
new file mode 100644 (file)
index 0000000..00c3999
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: compat___shmctl13.c,v 1.2 2009/01/11 02:46:26 christos Exp $   */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat___shmctl13.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <sys/shm.h>
+#include <compat/sys/shm.h>
+
+__warn_references(__shmctl13,
+    "warning: reference to compatibility __shmctl13(); include <sys/shm.h> to generate correct reference")
+
+int
+__shmctl13(int shmid, int cmd, struct shmid_ds13 *ds13)
+{
+       struct shmid_ds ds;
+       int error;
+
+       if (cmd == IPC_SET)
+               __shmid_ds13_to_native(ds13, &ds);
+
+       error = __shmctl50(shmid, cmd, &ds);
+       if (error)
+               return error;
+       if (cmd == IPC_STAT)
+               __native_to_shmid_ds13(&ds, ds13);
+       return 0;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat___stat13.c b/lib/nbsd_libc/compat/sys/compat___stat13.c
new file mode 100644 (file)
index 0000000..e01e07d
--- /dev/null
@@ -0,0 +1,140 @@
+/*     $NetBSD: compat___stat13.c,v 1.4 2009/01/11 02:46:26 christos Exp $     */
+
+/*
+ * Copyright (c) 1997 Frank van der Linden
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project
+ *      by Frank van der Linden
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat___stat13.c,v 1.4 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/mount.h>
+#include <compat/sys/time.h>
+#include <compat/sys/stat.h>
+#include <compat/sys/mount.h>
+
+__warn_references(__stat13,
+    "warning: reference to compatibility __stat13(); include <sys/stat.h> to generate correct reference")
+
+__warn_references(__fstat13,
+    "warning: reference to compatibility __fstat13(); include <sys/stat.h> to generate correct reference")
+
+__warn_references(__lstat13,
+    "warning: reference to compatibility __lstat13(); include <sys/stat.h> to generate correct reference")
+
+__warn_references(fhstat,
+    "warning: reference to compatibility fhstat(); include <sys/mount.h> to generate correct reference")
+
+
+/*
+ * Convert from a new to an old stat structure.
+ */
+
+static void cvtstat(struct stat13 *, const struct stat *);
+
+static void
+cvtstat(struct stat13 *ost, const struct stat *st)
+{
+
+       ost->st_dev = (uint32_t)st->st_dev;
+       ost->st_ino = (uint32_t)st->st_ino;
+       ost->st_mode = st->st_mode;
+       ost->st_nlink = st->st_nlink;
+       ost->st_uid = st->st_uid;
+       ost->st_gid = st->st_gid;
+       ost->st_rdev = (uint32_t)st->st_rdev;
+       ost->st_atimespec.tv_sec = (int32_t)st->st_atimespec.tv_sec;
+       ost->st_atimespec.tv_nsec = st->st_atimespec.tv_nsec;
+       ost->st_mtimespec.tv_sec = (int32_t)st->st_mtimespec.tv_sec;
+       ost->st_mtimespec.tv_nsec = st->st_mtimespec.tv_nsec;
+       ost->st_ctimespec.tv_sec = (int32_t)st->st_ctimespec.tv_sec;
+       ost->st_ctimespec.tv_nsec = st->st_ctimespec.tv_nsec;
+       ost->st_birthtimespec.tv_sec = (int32_t)st->st_birthtimespec.tv_sec;
+       ost->st_birthtimespec.tv_nsec = st->st_birthtimespec.tv_nsec;
+       ost->st_size = st->st_size;
+       ost->st_blocks = st->st_blocks;
+       ost->st_blksize = st->st_blksize;
+       ost->st_flags = st->st_flags;
+       ost->st_gen = st->st_gen;
+}
+
+int
+__stat13(const char *file, struct stat13 *ost)
+{
+       struct stat nst;
+       int ret;
+
+       if ((ret = __stat50(file, &nst)) == -1)
+               return ret;
+       cvtstat(ost, &nst);
+       return ret;
+}
+
+int
+__fstat13(int f, struct stat13 *ost)
+{
+       struct stat nst;
+       int ret;
+
+       if ((ret = __fstat50(f, &nst)) == -1)
+               return ret;
+       cvtstat(ost, &nst);
+       return ret;
+}
+
+int
+__lstat13(const char *file, struct stat13 *ost)
+{
+       struct stat nst;
+       int ret;
+
+       if ((ret = __lstat50(file, &nst)) == -1)
+               return ret;
+       cvtstat(ost, &nst);
+       return ret;
+}
+
+int
+fhstat(const struct compat_30_fhandle *fh, struct stat13 *ost)
+{
+       struct stat nst;
+       int ret;
+
+       if ((ret = __fhstat50((const void *)fh, /* FHANDLE_SIZE_COMPAT */28, &nst)) == -1)
+               return ret;
+       cvtstat(ost, &nst);
+       return ret;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat___stat30.c b/lib/nbsd_libc/compat/sys/compat___stat30.c
new file mode 100644 (file)
index 0000000..ec6c8aa
--- /dev/null
@@ -0,0 +1,136 @@
+/*     $NetBSD: compat___stat30.c,v 1.2 2009/01/11 02:46:26 christos Exp $     */
+
+/*
+ * Copyright (c) 1997 Frank van der Linden
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project
+ *      by Frank van der Linden
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat___stat30.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/mount.h>
+#include <compat/sys/time.h>
+#include <compat/sys/stat.h>
+#include <compat/sys/mount.h>
+
+__warn_references(__stat30,
+    "warning: reference to compatibility __stat30(); include <sys/stat.h> to generate correct reference")
+
+__warn_references(__fstat30,
+    "warning: reference to compatibility __fstat30(); include <sys/stat.h> to generate correct reference")
+
+__warn_references(__lstat30,
+    "warning: reference to compatibility __lstat30(); include <sys/stat.h> to generate correct reference")
+
+__warn_references(__fhstat40,
+    "warning: reference to compatibility __fhstat40(); include <sys/mount.h> to generate correct reference")
+
+
+/*
+ * Convert from a new to an old stat structure.
+ */
+
+static void cvtstat(struct stat30 *, const struct stat *);
+
+static void
+cvtstat(struct stat30 *ost, const struct stat *st)
+{
+
+       ost->st_dev = (uint32_t)st->st_dev;
+       ost->st_ino = st->st_ino;
+       ost->st_mode = st->st_mode;
+       ost->st_nlink = st->st_nlink;
+       ost->st_uid = st->st_uid;
+       ost->st_gid = st->st_gid;
+       ost->st_rdev = (uint32_t)st->st_rdev;
+       timespec_to_timespec50(&st->st_atimespec, &ost->st_atimespec);
+       timespec_to_timespec50(&st->st_mtimespec, &ost->st_mtimespec);
+       timespec_to_timespec50(&st->st_ctimespec, &ost->st_ctimespec);
+       timespec_to_timespec50(&st->st_birthtimespec, &ost->st_birthtimespec);
+       ost->st_size = st->st_size;
+       ost->st_blocks = st->st_blocks;
+       ost->st_blksize = st->st_blksize;
+       ost->st_flags = st->st_flags;
+       ost->st_gen = st->st_gen;
+}
+
+int
+__stat30(const char *file, struct stat30 *ost)
+{
+       struct stat nst;
+       int ret;
+
+       if ((ret = __stat50(file, &nst)) == -1)
+               return ret;
+       cvtstat(ost, &nst);
+       return ret;
+}
+
+int
+__fstat30(int f, struct stat30 *ost)
+{
+       struct stat nst;
+       int ret;
+
+       if ((ret = __fstat50(f, &nst)) == -1)
+               return ret;
+       cvtstat(ost, &nst);
+       return ret;
+}
+
+int
+__lstat30(const char *file, struct stat30 *ost)
+{
+       struct stat nst;
+       int ret;
+
+       if ((ret = __lstat50(file, &nst)) == -1)
+               return ret;
+       cvtstat(ost, &nst);
+       return ret;
+}
+
+int
+__fhstat40(const void *fh, size_t fh_size, struct stat30 *ost)
+{
+       struct stat nst;
+       int ret;
+
+       if ((ret = __fhstat50(fh, fh_size, &nst)) == -1)
+               return ret;
+       cvtstat(ost, &nst);
+       return ret;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat__lwp_park.c b/lib/nbsd_libc/compat/sys/compat__lwp_park.c
new file mode 100644 (file)
index 0000000..f4f9b19
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: compat__lwp_park.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat__lwp_park.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <lwp.h>
+#include <compat/include/lwp.h>
+
+__warn_references(_lwp_park,
+    "warning: reference to compatibility _lwp_park(); include <lwp.h> to generate correct reference")
+
+/*
+ * Copy timeout to local variable and call the syscall.
+ */
+int
+_lwp_park(const struct timespec50 *ts50, lwpid_t unpark,
+    const void *hint, const void *unparkhint)
+{
+       struct timespec ts, *tsp;
+
+       if (ts50)
+               timespec50_to_timespec(ts50, tsp = &ts);
+       else
+               tsp = NULL;
+       return ___lwp_park50(tsp, unpark, hint, unparkhint);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_adjtime.c b/lib/nbsd_libc/compat/sys/compat_adjtime.c
new file mode 100644 (file)
index 0000000..b6a242f
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: compat_adjtime.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without valific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_adjtime.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <sys/time.h>
+#include <compat/sys/time.h>
+
+__warn_references(adjtime,
+    "warning: reference to compatibility adjtime(); include <time.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(adjtime, _adjtime)
+__weak_alias(__adjtime, _adjtime)
+#endif
+
+/*
+ * Copy timeout to local variable and call the syscall.
+ */
+int
+adjtime(const struct timeval50 *ts50, struct timeval50 *rts50)
+{
+       struct timeval ts, *tsp;
+       struct timeval rts, *rtsp;
+       int error;
+
+       rtsp = rts50 ? &rts : NULL;
+       if (ts50)
+               timeval50_to_timeval(ts50, tsp = &ts);
+       else
+               tsp = NULL;
+       error = __adjtime50(tsp, rtsp);
+       if (error)
+               return error;
+       if (rts50)
+               timeval_to_timeval50(rtsp, rts50);
+       return 0;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_aio_suspend.c b/lib/nbsd_libc/compat/sys/compat_aio_suspend.c
new file mode 100644 (file)
index 0000000..3639f5b
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: compat_aio_suspend.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_aio_suspend.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <time.h>
+#include <compat/include/time.h>
+#include <compat/include/aio.h>
+
+__warn_references(aio_suspend,
+    "warning: reference to compatibility aio_suspend(); include <aio.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(aio_suspend, _aio_suspend)
+__weak_alias(_sys_aio_suspend, _aio_suspend)
+#endif
+/*
+ * Copy timeout to local variable and call the syscall.
+ */
+int
+aio_suspend(const struct aiocb * const list[], int nent,
+    const struct timespec50 * ts50)
+{
+       struct timespec ts, *tsp;
+
+       if (ts50)
+               timespec50_to_timespec(ts50, tsp = &ts);
+       else
+               tsp = NULL;
+       return __aio_suspend50(list, nent, tsp);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_clock.c b/lib/nbsd_libc/compat/sys/compat_clock.c
new file mode 100644 (file)
index 0000000..c3f5645
--- /dev/null
@@ -0,0 +1,98 @@
+/*     $NetBSD: compat_clock.c,v 1.2 2009/01/11 02:46:26 christos Exp $        */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_clock.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <time.h>
+#include <compat/include/time.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+
+__warn_references(clock_gettime,
+    "warning: reference to compatibility clock_gettime(); include <time.h> to generate correct reference")
+__warn_references(clock_settime,
+    "warning: reference to compatibility clock_settime(); include <time.h> to generate correct reference")
+__warn_references(clock_getres,
+    "warning: reference to compatibility clock_getres(); include <time.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(clock_settime, _clock_settime)
+__weak_alias(__clock_settime, _clock_settime)
+__weak_alias(clock_gettime, _clock_gettime)
+__weak_alias(clock_getres, _clock_getres)
+#endif
+
+int
+clock_settime(clockid_t clockid, const struct timespec50 * tim50)
+{
+       struct timespec tim, *timp;
+       int error;
+
+       if (tim50)
+               timespec50_to_timespec(tim50, timp = &tim);
+       else
+               timp = NULL;
+       error = __clock_settime50(clockid, timp);
+       if (error)
+               return error;
+       return 0;
+}
+
+int
+clock_gettime(clockid_t clockid, struct timespec50 *tim50)
+{
+       struct timespec tim, *timp = tim50 ? &tim : NULL;
+       int error = __clock_gettime50(clockid, timp);
+       if (error)
+               return error;
+       if (tim50)
+               timespec_to_timespec50(timp, tim50);
+       return 0;
+}
+
+int
+clock_getres(clockid_t clockid, struct timespec50 *tim50)
+{
+       struct timespec tim, *timp = tim50 ? &tim : NULL;
+       int error = __clock_getres50(clockid, timp);
+       if (error)
+               return error;
+       if (tim50)
+               timespec_to_timespec50(timp, tim50);
+       return 0;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_fhopen.c b/lib/nbsd_libc/compat/sys/compat_fhopen.c
new file mode 100644 (file)
index 0000000..4382316
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: compat_fhopen.c,v 1.4 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Martin Husemann <martin@NetBSD.org>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_fhopen.c,v 1.4 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <sys/types.h>
+#include <sys/mount.h>
+#include <compat/include/fstypes.h>
+
+__warn_references(fhopen,
+    "warning: reference to compatibility fhopen(); include <sys/mount.h> to generate correct reference")
+
+
+int     __fhopen40(const void *, size_t, int);
+int    fhopen(const struct compat_30_fhandle *, int);
+
+/*
+ * Convert old fhopen() call to new calling convention
+ */
+int
+fhopen(const struct compat_30_fhandle *fhp, int flags)
+{
+       return __fhopen40(fhp, FHANDLE30_SIZE, flags);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_fhstatvfs.c b/lib/nbsd_libc/compat/sys/compat_fhstatvfs.c
new file mode 100644 (file)
index 0000000..1e2207c
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: compat_fhstatvfs.c,v 1.3 2008/04/28 20:22:59 martin Exp $      */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Martin Husemann <martin@NetBSD.org>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_fhstatvfs.c,v 1.3 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <sys/types.h>
+#include <sys/statvfs.h>
+#include <compat/include/fstypes.h>
+
+__warn_references(fhstatvfs,
+    "warning: reference to compatibility fhstatvfs(); include <sys/mount.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(fhstatvfs, _fhstatvfs)
+#endif
+
+int     _fhstatvfs(const struct compat_30_fhandle *fhp, struct statvfs *buf);
+int    __fhstatvfs140(const void *fhp, size_t fh_size, struct statvfs *buf,
+       int flags);
+
+/*
+ * Convert old fhstatvs() call to new calling convention
+ */
+int
+_fhstatvfs(const struct compat_30_fhandle *fhp, struct statvfs *buf)
+{
+       return __fhstatvfs140(fhp, FHANDLE30_SIZE, buf, ST_WAIT);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_fhstatvfs1.c b/lib/nbsd_libc/compat/sys/compat_fhstatvfs1.c
new file mode 100644 (file)
index 0000000..6eb7db3
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: compat_fhstatvfs1.c,v 1.3 2008/04/28 20:22:59 martin Exp $     */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Martin Husemann <martin@NetBSD.org>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_fhstatvfs1.c,v 1.3 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <sys/types.h>
+#include <sys/statvfs.h>
+#include <compat/include/fstypes.h>
+
+__warn_references(fhstatvfs1,
+    "warning: reference to compatibility fhstatvfs1(); include <sys/mount.h> to generate correct reference")
+
+int    fhstatvfs1(const struct compat_30_fhandle *fhp, struct statvfs *buf,
+       int flags);
+int    __fhstatvfs140(const void *fhp, size_t fh_size, struct statvfs *buf,
+       int flags);
+
+/*
+ * Convert old fhstatvs1() call to new calling convention
+ */
+int
+fhstatvfs1(const struct compat_30_fhandle *fhp, struct statvfs *buf, int flags)
+{
+       return __fhstatvfs140(fhp, FHANDLE30_SIZE, buf, flags);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_getdents.c b/lib/nbsd_libc/compat/sys/compat_getdents.c
new file mode 100644 (file)
index 0000000..20a70e4
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: compat_getdents.c,v 1.3 2008/04/28 20:22:59 martin Exp $       */
+
+/*-
+ * Copyright (c) 2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_getdents.c,v 1.3 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <dirent.h>
+#include <compat/include/dirent.h>
+#include <string.h>
+
+/*
+ * libc12 compatible getdents routine.
+ */
+int
+getdents(int fd, char *buf, size_t nbytes)
+{
+       struct dirent *ndp, *nndp, *endp;
+       struct dirent12 *odp;
+       int rv;
+
+       if ((rv = __getdents30(fd, buf, nbytes)) == -1)
+               return rv;
+
+       odp = (struct dirent12 *)(void *)buf;
+       ndp = (struct dirent *)(void *)buf;
+       endp = (struct dirent *)(void *)&buf[rv];
+
+       /*
+        * In-place conversion. This works because odp
+        * is smaller than ndp, but it has to be done
+        * in the right sequence.
+        */
+       for (; ndp < endp; ndp = nndp) {
+               nndp = _DIRENT_NEXT(ndp);
+               /* XXX: avoid unaligned 64-bit access on sparc64 */
+               odp->d_ino = ((u_int32_t *)(void *)&ndp->d_ino)[_QUAD_LOWWORD];
+               if (ndp->d_namlen >= sizeof(odp->d_name))
+                       odp->d_namlen = sizeof(odp->d_name) - 1;
+               else
+                       odp->d_namlen = (u_int8_t)ndp->d_namlen;
+               odp->d_type = ndp->d_type;
+               (void)memcpy(odp->d_name, ndp->d_name, (size_t)odp->d_namlen);
+               odp->d_name[odp->d_namlen] = '\0';
+               odp->d_reclen = _DIRENT_SIZE(odp);
+               odp = _DIRENT_NEXT(odp);
+       }
+       return ((char *)(void *)odp) - buf;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_getdirentries.c b/lib/nbsd_libc/compat/sys/compat_getdirentries.c
new file mode 100644 (file)
index 0000000..5942cc7
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: compat_getdirentries.c,v 1.2 2009/02/22 06:33:38 dholland Exp $        */
+
+/*
+ * Copyright (c) 1997 Frank van der Linden
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Frank van der Linden for
+ *      the NetBSD Project.
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_getdirentries.c,v 1.2 2009/02/22 06:33:38 dholland Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+#include "namespace.h"
+#include <sys/types.h>
+#include <dirent.h>
+#include <compat/include/dirent.h>
+#include <unistd.h>
+
+__warn_references(getdirentries,
+    "reference to compatibility-only getdirentries(); this will break; use getdents() or readdir() instead")
+
+int
+getdirentries(fd, buf, nbytes, basep)
+       int fd, nbytes;
+       char *buf;
+       long *basep;
+{
+       *basep = (long)lseek(fd, (off_t)0, SEEK_CUR);
+       return getdents(fd, buf, (size_t)nbytes);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_getfh.c b/lib/nbsd_libc/compat/sys/compat_getfh.c
new file mode 100644 (file)
index 0000000..5c76950
--- /dev/null
@@ -0,0 +1,71 @@
+/*     $NetBSD: compat_getfh.c,v 1.6 2008/04/28 20:22:59 martin Exp $  */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Martin Husemann <martin@NetBSD.org>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_getfh.c,v 1.6 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <sys/types.h>
+#include <sys/mount.h>
+#include <compat/include/fstypes.h>
+
+#include <errno.h>
+
+__warn_references(getfh,
+    "warning: reference to compatibility getfh(); include <sys/mount.h> to generate correct reference")
+
+
+int     __getfh30(const char *, void*, size_t *);
+int    getfh(const char *path, struct compat_30_fhandle *fhp);
+
+/*
+ * Convert old getfh() call to new calling convention
+ */
+int
+getfh(const char *path, struct compat_30_fhandle *fhp)
+{
+       size_t fh_size = sizeof(*fhp);
+       int ret;
+
+       ret = __getfh30(path, (void*)fhp, &fh_size);
+       if (ret != 0) {
+               return ret;
+       }
+       if (fh_size != FHANDLE30_SIZE) {
+               errno = EINVAL;
+               return -1;
+       }
+       return 0;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_getrusage.c b/lib/nbsd_libc/compat/sys/compat_getrusage.c
new file mode 100644 (file)
index 0000000..a00f0ff
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: compat_getrusage.c,v 1.2 2009/01/11 02:46:26 christos Exp $    */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_getrusage.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <string.h>
+#include <sys/types.h>
+#include <sys/resource.h>
+#include <compat/sys/resource.h>
+
+__warn_references(getrusage,
+    "warning: reference to compatibility getrusage(); include <sys/resource.h> to generate correct reference")
+
+void __rusage_to_rusage50(const struct rusage *, struct rusage50 *);
+
+void
+__rusage_to_rusage50(const struct rusage *ru, struct rusage50 *ru50)
+{
+       (void)memcpy(&ru50->ru_first, &ru->ru_first,
+           (size_t)((char *)(void *)&ru50->ru_last -
+           (char *)(void *)&ru50->ru_first));
+       ru50->ru_maxrss = ru->ru_maxrss;
+       timeval_to_timeval50(&ru->ru_utime, &ru50->ru_utime);
+       timeval_to_timeval50(&ru->ru_stime, &ru50->ru_stime);
+}
+
+/*
+ * libc12 compatible getrusage routine.
+ */
+int
+getrusage(int who, struct rusage50 *ru50)
+{
+       struct rusage ru;
+       int rv;
+
+       if ((rv = __getrusage50(who, &ru)) == -1)
+               return rv;
+       __rusage_to_rusage50(&ru, ru50);
+       return rv;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_gettimeofday.c b/lib/nbsd_libc/compat/sys/compat_gettimeofday.c
new file mode 100644 (file)
index 0000000..694cfbd
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: compat_gettimeofday.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_gettimeofday.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+
+__warn_references(gettimeofday,
+    "warning: reference to compatibility gettimeofday(); include <sys/time.h> to generate correct reference")
+
+/*
+ * libc12 compatible gettimeofday routine.
+ */
+int
+gettimeofday(struct timeval50 *tv50, void *tzp)
+{
+       struct timeval tv;
+       int rv;
+
+       if ((rv = __gettimeofday50(&tv, tzp)) == -1)
+               return rv;
+       timeval_to_timeval50(&tv, tv50);
+       return rv;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_itimer.c b/lib/nbsd_libc/compat/sys/compat_itimer.c
new file mode 100644 (file)
index 0000000..e31dec7
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: compat_itimer.c,v 1.2 2009/01/11 02:46:26 christos Exp $       */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_itimer.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <time.h>
+#include <compat/include/time.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+
+__warn_references(getitimer,
+    "warning: reference to compatibility getitimer(); include <sys/time.h> to generate correct reference")
+__warn_references(setitimer,
+    "warning: reference to compatibility setitimer(); include <sys/time.h> to generate correct reference")
+
+int
+setitimer(int timerid, const struct itimerval50 * __restrict tim50,
+    struct itimerval50 * __restrict otim50)
+{
+       struct itimerval tim, *timp;
+       struct itimerval otim, *otimp;
+       int error;
+
+       otimp = otim50 ? &otim : NULL;
+       if (tim50)
+               itimerval50_to_itimerval(tim50, timp = &tim);
+       else
+               timp = NULL;
+       error = __setitimer50(timerid, timp, otimp);
+       if (error)
+               return error;
+       if (otim50)
+               itimerval_to_itimerval50(otimp, otim50);
+       return 0;
+}
+
+int
+getitimer(int timerid, struct itimerval50 *tim50)
+{
+       struct itimerval tim, *timp = tim50 ? &tim : NULL;
+       int error = __getitimer50(timerid, timp);
+       if (error)
+               return error;
+       if (tim50)
+               itimerval_to_itimerval50(timp, tim50);
+       return 0;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_kevent.c b/lib/nbsd_libc/compat/sys/compat_kevent.c
new file mode 100644 (file)
index 0000000..c613f07
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: compat_kevent.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_kevent.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <sys/event.h>
+#include <compat/sys/event.h>
+
+__warn_references(kevent,
+    "warning: reference to compatibility kevent(); include <sys/event.h> to generate correct reference")
+
+int
+kevent(int kq, const struct kevent *changelist, size_t nchanges,
+    struct kevent *eventlist, size_t nevents, const struct timespec50 *ts50)
+{
+       struct timespec ts, *tsp;
+
+       if (ts50)
+               timespec50_to_timespec(ts50, tsp = &ts);
+       else
+               tsp = NULL;
+       return __kevent50(kq, changelist, nchanges, eventlist, nevents, tsp);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_lfs_segwait.c b/lib/nbsd_libc/compat/sys/compat_lfs_segwait.c
new file mode 100644 (file)
index 0000000..5a4cead
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: compat_lfs_segwait.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without valific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_lfs_segwait.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <sys/types.h>
+#include <sys/fstypes.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+
+__warn_references(lfs_segwait,
+    "warning: reference to compatibility lfs_segwait(); include <???.h> to generate correct reference")
+
+int lfs_segwait(fsid_t *, struct timeval50 *);
+int __lfs_segwait50(fsid_t *, struct timeval *);
+int
+lfs_segwait(fsid_t *fsid, struct timeval50 *ts50)
+{
+       struct timeval ts, *tsp;
+
+       if (ts50)
+               timeval50_to_timeval(ts50, tsp = &ts);
+       else
+               tsp = NULL;
+       return __lfs_segwait50(fsid, tsp);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_mknod.c b/lib/nbsd_libc/compat/sys/compat_mknod.c
new file mode 100644 (file)
index 0000000..eea52f4
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: compat_mknod.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_mknod.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <sys/stat.h>
+#include <compat/sys/stat.h>
+
+__warn_references(mknod,
+    "warning: reference to compatibility mknod(); include <time.h> to generate correct reference")
+
+int
+mknod(const char *path, mode_t mode, uint32_t dev)
+{
+       return __mknod50(path, mode, dev);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_mount.c b/lib/nbsd_libc/compat/sys/compat_mount.c
new file mode 100644 (file)
index 0000000..83f8f3c
--- /dev/null
@@ -0,0 +1,29 @@
+/*     $NetBSD: compat_mount.c,v 1.2 2007/07/18 20:10:47 dsl Exp $     */
+
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_mount.c,v 1.2 2007/07/18 20:10:47 dsl Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <sys/types.h>
+#include <sys/mount.h>
+
+__warn_references(mount,
+    "warning: reference to compatibility mount(); include <sys/mount.h> to generate correct reference")
+
+int    mount(const char *, const char *, int, void *);
+int    __mount50(const char *, const char *, int, void *, size_t);
+
+/*
+ * Convert old mount() call to new calling convention
+ * The kernel will treat length 0 as 'default for the fs'.
+ * We need to throw away the +ve response for MNT_GETARGS.
+ */
+int
+mount(const char *type, const char *dir, int flags, void *data)
+{
+       return __mount50(type, dir, flags, data, 0) == -1 ? -1 : 0;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_mqueue.c b/lib/nbsd_libc/compat/sys/compat_mqueue.c
new file mode 100644 (file)
index 0000000..41244f8
--- /dev/null
@@ -0,0 +1,86 @@
+/*     $NetBSD: compat_mqueue.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_mqueue.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <mqueue.h>
+#include <compat/include/mqueue.h>
+
+__warn_references(mq_timedreceive,
+    "warning: reference to compatibility mq_timedreceive(); include <mqueue.h> to generate correct reference")
+__warn_references(mq_timedsend,
+    "warning: reference to compatibility mq_timedsend(); include <mqueue.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(mq_timedreceive, _mq_timedreceive)
+__weak_alias(mq_timedsend, _mq_timedsend)
+__weak_alias(_sys_mq_timedreceive, _mq_timedreceive)
+__weak_alias(_sys_mq_timedsend, _mq_timedsend)
+#endif
+
+ssize_t
+mq_timedreceive(mqd_t mq, char * __restrict name, size_t len,
+    unsigned * __restrict buf, const struct timespec50 * __restrict ts50)
+{
+       struct timespec ts, *tsp;
+
+       if (ts50)
+               timespec50_to_timespec(ts50, tsp = &ts);
+       else
+               tsp = NULL;
+       return __mq_timedreceive50(mq, name, len, buf, tsp);
+}
+
+int
+mq_timedsend(mqd_t mq, const char *name, size_t len,
+    unsigned buf, const struct timespec50 *ts50)
+{
+       struct timespec ts, *tsp;
+
+       if (ts50)
+               timespec50_to_timespec(ts50, tsp = &ts);
+       else
+               tsp = NULL;
+       return __mq_timedsend50(mq, name, len, buf, tsp);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_msync.c b/lib/nbsd_libc/compat/sys/compat_msync.c
new file mode 100644 (file)
index 0000000..3e05ff6
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: compat_msync.c,v 1.1 2005/09/13 01:44:09 christos Exp $        */
+
+/*
+ * Copyright (c) 1997 Frank van der Linden
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project
+ *      by Frank van der Linden
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_msync.c,v 1.1 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <sys/types.h>
+#include <sys/mman.h>
+#include <compat/sys/mman.h>
+
+__warn_references(msync,
+    "warning: reference to compatibility msync(); include <sys/mman.h> for correct reference")
+
+int
+msync(addr, size)
+       void *addr;
+       size_t size;
+{
+       return __msync13(addr, size, MS_SYNC|MS_INVALIDATE);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_nanosleep.c b/lib/nbsd_libc/compat/sys/compat_nanosleep.c
new file mode 100644 (file)
index 0000000..5d76722
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: compat_nanosleep.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_nanosleep.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <time.h>
+#include <compat/include/time.h>
+
+__warn_references(nanosleep,
+    "warning: reference to compatibility nanosleep(); include <time.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(nanosleep, _nanosleep)
+__weak_alias(_sys_nanosleep, _nanosleep)
+#endif
+
+/*
+ * Copy timeout to local variable and call the syscall.
+ */
+int
+nanosleep(const struct timespec50 *ts50, struct timespec50 *rts50)
+{
+       struct timespec ts, *tsp;
+       struct timespec rts, *rtsp;
+       int error;
+
+       rtsp = rts50 ? &rts : NULL;
+       if (ts50)
+               timespec50_to_timespec(ts50, tsp = &ts);
+       else
+               tsp = NULL;
+       error = __nanosleep50(tsp, rtsp);
+       if (error)
+               return error;
+       if (rts50)
+               timespec_to_timespec50(rtsp, rts50);
+       return 0;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_ntp_gettime.c b/lib/nbsd_libc/compat/sys/compat_ntp_gettime.c
new file mode 100644 (file)
index 0000000..6fbbbbc
--- /dev/null
@@ -0,0 +1,30 @@
+/* $NetBSD: compat_ntp_gettime.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_ntp_gettime.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <sys/time.h>
+#include <sys/timex.h>
+#include <compat/sys/timex.h>
+
+__warn_references(ntp_gettime,
+    "warning: reference to compatibility ntp_gettime(); include <sys/timex.h> for correct reference")
+
+int
+ntp_gettime(struct ntptimeval30 *ontvp)
+{
+       struct ntptimeval ntv;
+       int res;
+
+       res = __ntp_gettime50(&ntv);
+       ontvp->time.tv_sec = (int32_t)ntv.time.tv_sec;
+       ontvp->time.tv_usec = ntv.time.tv_nsec / 1000;
+       ontvp->maxerror = ntv.maxerror;
+       ontvp->esterror = ntv.esterror;
+
+       return (res);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_sched.c b/lib/nbsd_libc/compat/sys/compat_sched.c
new file mode 100644 (file)
index 0000000..ceeb099
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: compat_sched.c,v 1.2 2009/01/11 02:46:26 christos Exp $        */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_sched.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <unistd.h>
+
+__warn_references(sched_rr_get_interval,
+    "warning: reference to compatibility sched_rr_get_interval(); include <sched.h> to generate correct reference")
+
+int sched_rr_get_interval(pid_t, struct timespec50 *);
+
+int
+/*ARGSUSED*/
+sched_rr_get_interval(pid_t pid, struct timespec50 *interval)
+{
+       interval->tv_sec = 0;
+       interval->tv_nsec = sysconf(_SC_SCHED_RT_TS) * 1000;
+       return 0;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_select.c b/lib/nbsd_libc/compat/sys/compat_select.c
new file mode 100644 (file)
index 0000000..c81de97
--- /dev/null
@@ -0,0 +1,102 @@
+/*     $NetBSD: compat_select.c,v 1.2 2009/01/11 02:46:26 christos Exp $       */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_select.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <sys/select.h>
+#include <compat/sys/select.h>
+#include <sys/poll.h>
+#include <compat/sys/poll.h>
+
+__warn_references(pollts,
+    "warning: reference to compatibility pollts(); include <poll.h> to generate correct reference")
+__warn_references(select,
+    "warning: reference to compatibility select(); include <sys/select.h> to generate correct reference")
+__warn_references(pselect,
+    "warning: reference to compatibility pselect(); include <sys/select.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(select, _select)
+__weak_alias(_sys_select, _select)
+__weak_alias(pselect, _pselect)
+__weak_alias(_sys_pselect, _pselect)
+__weak_alias(pollts, _pollts)
+__weak_alias(_sys_pollts, _pollts)
+#endif
+int
+pollts(struct pollfd * __restrict fds, nfds_t nfds,
+    const struct timespec50 * __restrict tim50,
+    const sigset_t * __restrict sigmask)
+{
+       struct timespec tim, *timp;
+
+       if (tim50)
+               timespec50_to_timespec(tim50, timp = &tim);
+       else
+               timp = NULL;
+       return __pollts50(fds, nfds, timp, sigmask);
+}
+
+int
+select(int nfds, fd_set * __restrict readfds, fd_set * __restrict writefds,
+    fd_set * __restrict exceptfds, struct timeval50 * __restrict tim50)
+{
+       struct timeval tim, *timp;
+
+       if (tim50)
+               timeval50_to_timeval(tim50, timp = &tim);
+       else
+               timp = NULL;
+       return __select50(nfds, readfds, writefds, exceptfds, timp);
+}
+
+int
+pselect(int nfds, fd_set * __restrict readfds, fd_set * __restrict writefds,
+    fd_set * __restrict exceptfds, const struct timespec50 *__restrict tim50,
+    const sigset_t * __restrict sigmask)
+{
+       struct timespec tim, *timp;
+
+       if (tim50)
+               timespec50_to_timespec(tim50, timp = &tim);
+       else
+               timp = NULL;
+       return __pselect50(nfds, readfds, writefds, exceptfds, timp, sigmask);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_semctl.c b/lib/nbsd_libc/compat/sys/compat_semctl.c
new file mode 100644 (file)
index 0000000..8e5f05a
--- /dev/null
@@ -0,0 +1,94 @@
+/* $NetBSD: compat_semctl.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_semctl.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+#include <sys/types.h>
+#include <sys/ipc.h>
+#include <sys/sem.h>
+#include <sys/null.h>
+#include <compat/sys/sem.h>
+#include <stdarg.h>
+
+int
+semctl(int semid, int semnum, int cmd, ...)
+{
+       va_list ap;
+       union __semun semun;
+       struct semid_ds ds;
+       struct semid_ds14 *ds14 = NULL;
+       int error;
+
+       va_start(ap, cmd);
+       switch (cmd) {
+       case IPC_SET:
+       case IPC_STAT:
+       case GETALL:
+       case SETVAL:
+       case SETALL:
+#ifdef __lint__
+               memcpy(&semun, &ap, sizeof(semun));
+#else
+               semun = va_arg(ap, union __semun);
+#endif
+       }
+       va_end(ap);
+
+       switch (cmd) {
+       case IPC_SET:
+       case IPC_STAT:
+               ds14 = (struct semid_ds14 *)(void *)semun.buf;
+               if (cmd == IPC_SET)
+                       __semid_ds14_to_native(ds14, &ds);
+               semun.buf = &ds;
+               break;
+       }
+
+       error = __semctl50(semid, semnum, cmd, &semun);
+       switch (cmd) {
+       case IPC_SET:
+       case IPC_STAT:
+               semun.buf = (struct semid_ds *)(void *)ds14;
+               if (cmd == IPC_STAT && error == 0)
+                       __native_to_semid_ds14(&ds, ds14);
+               break;
+       }
+       return error;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_settimeofday.c b/lib/nbsd_libc/compat/sys/compat_settimeofday.c
new file mode 100644 (file)
index 0000000..cafbc3f
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: compat_settimeofday.c,v 1.2 2009/01/11 02:46:26 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_settimeofday.c,v 1.2 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <time.h>
+#include <compat/include/time.h>
+
+__warn_references(settimeofday,
+    "warning: reference to compatibility settimeofday(); include <time.h> to generate correct reference")
+
+#ifdef __weak_alias
+__weak_alias(settimeofday, _settimeofday)
+__weak_alias(__settimeofday, _settimeofday)
+#endif
+/*
+ * Copy timeout to local variable and call the syscall.
+ */
+int
+settimeofday(const struct timeval50 * __restrict tv50,
+    const void * __restrict tvp)
+{
+       struct timeval tv;
+       timeval50_to_timeval(tv50, &tv);
+       return __settimeofday50(&tv, tvp);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_sigaltstack.c b/lib/nbsd_libc/compat/sys/compat_sigaltstack.c
new file mode 100644 (file)
index 0000000..909e84c
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: compat_sigaltstack.c,v 1.3 2009/01/11 02:46:26 christos Exp $  */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_sigaltstack.c,v 1.3 2009/01/11 02:46:26 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <limits.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+#include <signal.h>
+#include <compat/include/signal.h>
+#include <stddef.h>
+
+int
+sigaltstack(onss, ooss)
+       const struct sigaltstack13 *onss;
+       struct sigaltstack13 *ooss;
+{
+       stack_t nss, oss;
+       int error;
+
+       nss.ss_sp = onss->ss_sp;
+       nss.ss_size = onss->ss_size;
+       nss.ss_flags = onss->ss_flags;
+
+       error = __sigaltstack14(&nss, &oss);
+
+       if (error == 0 && ooss != NULL) {
+               ooss->ss_sp = oss.ss_sp;
+               if (oss.ss_size > INT_MAX)
+                       ooss->ss_size = INT_MAX;
+               else
+                       ooss->ss_size = oss.ss_size;
+               ooss->ss_flags = oss.ss_flags;
+       }
+
+       return (error);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_sigtimedwait.c b/lib/nbsd_libc/compat/sys/compat_sigtimedwait.c
new file mode 100644 (file)
index 0000000..1d73495
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: compat_sigtimedwait.c,v 1.2 2009/01/11 02:46:27 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_sigtimedwait.c,v 1.2 2009/01/11 02:46:27 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#define __LIBC12_SOURCE__
+#include <time.h>
+#include <compat/include/time.h>
+#include <signal.h>
+#include <compat/include/signal.h>
+
+#ifdef __weak_alias
+__weak_alias(sigtimedwait, _sigtimedwait)
+#endif
+/*
+ * Copy timeout to local variable and call the syscall.
+ */
+int
+sigtimedwait(const sigset_t * __restrict set, siginfo_t * __restrict info,
+    const struct timespec50 * __restrict timeout)
+{
+       struct timespec ts;
+
+       if (timeout) {
+               timespec50_to_timespec(timeout, &ts);
+               return ____sigtimedwait50(set, info, &ts);
+       } else
+               return ____sigtimedwait50(set, info, NULL);
+}
+
+int
+__sigtimedwait(const sigset_t * __restrict set, siginfo_t * __restrict info,
+    struct timespec50 * __restrict timeout)
+{
+       return sigtimedwait(set, info, timeout);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_socket.c b/lib/nbsd_libc/compat/sys/compat_socket.c
new file mode 100644 (file)
index 0000000..31a6dc7
--- /dev/null
@@ -0,0 +1,27 @@
+/* $NetBSD: compat_socket.c,v 1.1 2006/06/26 21:23:56 mrg Exp $ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_socket.c,v 1.1 2006/06/26 21:23:56 mrg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <compat/sys/socket.h>
+
+__warn_references(socket,
+    "warning: reference to compatibility socket(); include <sys/socket.h> for correct reference")
+
+int
+socket(int domain, int type, int protocol)
+{
+       int res;
+
+       res = __socket30(domain, type, protocol);
+       if (errno == EAFNOSUPPORT)
+               errno = EPROTONOSUPPORT;
+       return res;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_stat.c b/lib/nbsd_libc/compat/sys/compat_stat.c
new file mode 100644 (file)
index 0000000..9425edb
--- /dev/null
@@ -0,0 +1,122 @@
+/*     $NetBSD: compat_stat.c,v 1.2 2009/01/11 02:46:27 christos Exp $ */
+
+/*
+ * Copyright (c) 1997 Frank van der Linden
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed for the NetBSD Project
+ *      by Frank van der Linden
+ * 4. 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_stat.c,v 1.2 2009/01/11 02:46:27 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <compat/sys/time.h>
+#include <compat/sys/stat.h>
+
+__warn_references(stat,
+    "warning: reference to compatibility stat(); include <sys/stat.h> to generate correct reference")
+
+__warn_references(fstat,
+    "warning: reference to compatibility fstat(); include <sys/stat.h> to generate correct reference")
+
+__warn_references(lstat,
+    "warning: reference to compatibility lstat(); include <sys/stat.h> to generate correct reference")
+
+/*
+ * Convert from a new to an old stat structure.
+ */
+
+static void cvtstat(const struct stat *, struct stat12 *);
+
+static void
+cvtstat(const struct stat *st, struct stat12 *ost)
+{
+
+       ost->st_dev = (uint32_t)st->st_dev;
+       ost->st_ino = (uint32_t)st->st_ino;
+       ost->st_mode = st->st_mode;
+       if (st->st_nlink >= (1 << 15))
+               ost->st_nlink = (1 << 15) - 1;
+       else
+               ost->st_nlink = st->st_nlink;
+       ost->st_uid = st->st_uid;
+       ost->st_gid = st->st_gid;
+       ost->st_rdev = (uint32_t)st->st_rdev;
+       ost->st_atimespec.tv_sec = (int32_t)st->st_atimespec.tv_sec;
+       ost->st_atimespec.tv_nsec = st->st_atimespec.tv_nsec;
+       ost->st_mtimespec.tv_sec = (int32_t)st->st_mtimespec.tv_sec;
+       ost->st_mtimespec.tv_nsec = st->st_mtimespec.tv_nsec;
+       ost->st_ctimespec.tv_sec = (int32_t)st->st_ctimespec.tv_sec;
+       ost->st_ctimespec.tv_nsec = st->st_ctimespec.tv_nsec;
+       ost->st_size = st->st_size;
+       ost->st_blocks = st->st_blocks;
+       ost->st_blksize = st->st_blksize;
+       ost->st_flags = st->st_flags;
+       ost->st_gen = st->st_gen;
+}
+
+int
+stat(const char *file, struct stat12 *ost)
+{
+       struct stat nst;
+       int ret;
+
+       if ((ret = __stat50(file, &nst)) < 0)
+               return ret;
+       cvtstat(&nst, ost);
+       return ret;
+}
+
+int
+fstat(int f, struct stat12 *ost)
+{
+       struct stat nst;
+       int ret;
+
+       if ((ret = __fstat50(f, &nst)) < 0)
+               return ret;
+       cvtstat(&nst, ost);
+       return ret;
+}
+
+int
+lstat(const char *file, struct stat12 *ost)
+{
+       struct stat nst;
+       int ret;
+
+       if ((ret = __lstat50(file, &nst)) < 0)
+               return ret;
+       cvtstat(&nst, ost);
+       return ret;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_statfs.c b/lib/nbsd_libc/compat/sys/compat_statfs.c
new file mode 100644 (file)
index 0000000..1dfc6b5
--- /dev/null
@@ -0,0 +1,188 @@
+/*     $NetBSD: compat_statfs.c,v 1.5 2009/02/03 05:04:52 lukem Exp $  */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_statfs.c,v 1.5 2009/02/03 05:04:52 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/mount.h>
+#include <compat/sys/mount.h>
+#include <compat/include/fstypes.h>
+#include <string.h>
+#include <stdlib.h>
+
+__warn_references(statfs,
+    "warning: reference to obsolete statfs(); use statvfs()")
+
+__warn_references(fstatfs,
+    "warning: reference to obsolete fstatfs(); use fstatvfs()")
+
+__warn_references(fhstatfs,
+    "warning: reference to obsolete fhstatfs(); use fhstatvfs()")
+
+__warn_references(getfsstat,
+    "warning: reference to obsolete getfsstat(); use getvfsstat()")
+
+/*
+ * Convert from a new statvfs to an old statfs structure.
+ */
+
+static void vfs2fs(struct statfs12 *, const struct statvfs *);
+
+#define MOUNTNO_NONE   0
+#define MOUNTNO_UFS    1               /* UNIX "Fast" Filesystem */
+#define MOUNTNO_NFS    2               /* Network Filesystem */
+#define MOUNTNO_MFS    3               /* Memory Filesystem */
+#define MOUNTNO_MSDOS  4               /* MSDOS Filesystem */
+#define MOUNTNO_CD9660 5               /* iso9660 cdrom */
+#define MOUNTNO_FDESC  6               /* /dev/fd filesystem */
+#define MOUNTNO_KERNFS 7               /* kernel variable filesystem */ 
+#define MOUNTNO_DEVFS  8               /* device node filesystem */
+#define MOUNTNO_AFS    9               /* AFS 3.x */
+static const struct {
+       const char *name;
+       const int value;
+} nv[] = {
+       { MOUNT_UFS, MOUNTNO_UFS },
+       { MOUNT_NFS, MOUNTNO_NFS },
+       { MOUNT_MFS, MOUNTNO_MFS },
+       { MOUNT_MSDOS, MOUNTNO_MSDOS },
+       { MOUNT_CD9660, MOUNTNO_CD9660 },
+       { MOUNT_FDESC, MOUNTNO_FDESC },
+       { MOUNT_KERNFS, MOUNTNO_KERNFS },
+       { MOUNT_AFS, MOUNTNO_AFS },
+};
+
+static void
+vfs2fs(struct statfs12 *bfs, const struct statvfs *fs) 
+{
+       size_t i = 0;
+       bfs->f_type = 0;
+       bfs->f_oflags = (short)fs->f_flag;
+
+       for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++) {
+               if (strcmp(nv[i].name, fs->f_fstypename) == 0) {
+                       bfs->f_type = nv[i].value;
+                       break;
+               }
+       }
+#define CLAMP(a)       (long)(((a) & ~LONG_MAX) ? LONG_MAX : (a))
+       bfs->f_bsize = CLAMP(fs->f_frsize);
+       bfs->f_iosize = CLAMP(fs->f_iosize);
+       bfs->f_blocks = CLAMP(fs->f_blocks);
+       bfs->f_bfree = CLAMP(fs->f_bfree);
+       if (fs->f_bfree > fs->f_bresvd)
+               bfs->f_bavail = CLAMP(fs->f_bfree - fs->f_bresvd);
+       else
+               bfs->f_bavail = -CLAMP(fs->f_bresvd - fs->f_bfree);
+       bfs->f_files = CLAMP(fs->f_files);
+       bfs->f_ffree = CLAMP(fs->f_ffree);
+       bfs->f_fsid = fs->f_fsidx;
+       bfs->f_owner = fs->f_owner;
+       bfs->f_flags = (long)fs->f_flag;
+       bfs->f_syncwrites = CLAMP(fs->f_syncwrites);
+       bfs->f_asyncwrites = CLAMP(fs->f_asyncwrites);
+       (void)strncpy(bfs->f_fstypename, fs->f_fstypename,
+           sizeof(bfs->f_fstypename));
+       (void)strncpy(bfs->f_mntonname, fs->f_mntonname,
+           sizeof(bfs->f_mntonname));
+       (void)strncpy(bfs->f_mntfromname, fs->f_mntfromname,
+           sizeof(bfs->f_mntfromname));
+}
+
+int
+statfs(const char *file, struct statfs12 *ost)
+{
+       struct statvfs nst;
+       int ret;
+
+       if ((ret = statvfs(file, &nst)) == -1)
+               return ret;
+       vfs2fs(ost, &nst);
+       return ret;
+}
+
+int
+fstatfs(int f, struct statfs12 *ost)
+{
+       struct statvfs nst;
+       int ret;
+
+       if ((ret = fstatvfs(f, &nst)) == -1)
+               return ret;
+       vfs2fs(ost, &nst);
+       return ret;
+}
+
+int __fhstatvfs140(const void *fhp, size_t fh_size, struct statvfs *buf,
+    int flags);
+
+int
+fhstatfs(const struct compat_30_fhandle *fh, struct statfs12 *ost)
+{
+       struct statvfs nst;
+       int ret;
+
+       if ((ret = __fhstatvfs140(fh, FHANDLE30_SIZE, &nst, ST_WAIT)) == -1)
+               return ret;
+       vfs2fs(ost, &nst);
+       return ret;
+}
+
+int
+getfsstat(struct statfs12 *ost, long size, int flags)
+{
+       struct statvfs *nst;
+       int ret, i;
+       size_t bsize = (size_t)(size / sizeof(*ost)) * sizeof(*nst);
+
+       if (ost != NULL) {
+               if ((nst = malloc(bsize)) == NULL)
+                       return -1;
+       } else
+               nst = NULL;
+
+       if ((ret = getvfsstat(nst, bsize, flags)) == -1)
+               goto done;
+       if (nst)
+               for (i = 0; i < ret; i++)
+                       vfs2fs(&ost[i], &nst[i]);
+done:
+       if (nst)
+               free(nst);
+       return ret;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_timer.c b/lib/nbsd_libc/compat/sys/compat_timer.c
new file mode 100644 (file)
index 0000000..8c09a39
--- /dev/null
@@ -0,0 +1,83 @@
+/*     $NetBSD: compat_timer.c,v 1.2 2009/01/11 02:46:27 christos Exp $        */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_timer.c,v 1.2 2009/01/11 02:46:27 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <time.h>
+#include <compat/include/time.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+
+__warn_references(timer_gettime,
+    "warning: reference to compatibility timer_gettime(); include <time.h> to generate correct reference")
+__warn_references(timer_settime,
+    "warning: reference to compatibility timer_settime(); include <time.h> to generate correct reference")
+
+int
+timer_settime(timer_t timerid, int flags,
+    const struct itimerspec50 * __restrict tim50,
+    struct itimerspec50 * __restrict otim50)
+{
+       struct itimerspec tim, *timp;
+       struct itimerspec otim, *otimp;
+       int error;
+
+       otimp = otim50 ? &otim : NULL;
+       if (tim50)
+               itimerspec50_to_itimerspec(tim50, timp = &tim);
+       else
+               timp = NULL;
+       error = __timer_settime50(timerid, flags, timp, otimp);
+       if (error)
+               return error;
+       if (otim50)
+               itimerspec_to_itimerspec50(otimp, otim50);
+       return 0;
+}
+
+int
+timer_gettime(timer_t timerid, struct itimerspec50 *tim50)
+{
+       struct itimerspec tim, *timp = tim50 ? &tim : NULL;
+       int error = __timer_gettime50(timerid, timp);
+       if (error)
+               return error;
+       if (tim50)
+               itimerspec_to_itimerspec50(timp, tim50);
+       return 0;
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_utimes.c b/lib/nbsd_libc/compat/sys/compat_utimes.c
new file mode 100644 (file)
index 0000000..a566434
--- /dev/null
@@ -0,0 +1,88 @@
+/*     $NetBSD: compat_utimes.c,v 1.2 2009/01/11 02:46:27 christos Exp $       */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_utimes.c,v 1.2 2009/01/11 02:46:27 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/time.h>
+#include <compat/sys/time.h>
+
+__warn_references(utimes,
+    "warning: reference to compatibility utimes(); include <sys/time.h> to generate correct reference")
+__warn_references(lutimes,
+    "warning: reference to compatibility lutimes(); include <sys/time.h> to generate correct reference")
+__warn_references(futimes,
+    "warning: reference to compatibility futimes(); include <sys/time.h> to generate correct reference")
+
+/*
+ * libc12 compatible f,l,utimes routine.
+ */
+int
+utimes(const char *path, const struct timeval50 *tv50)
+{
+       struct timeval tv[2];
+
+       if (tv50) {
+               timeval50_to_timeval(&tv50[0], &tv[0]);
+               timeval50_to_timeval(&tv50[1], &tv[1]);
+       }
+       return __utimes50(path, tv50 ? tv : NULL);
+}
+
+int
+lutimes(const char *path, const struct timeval50 *tv50)
+{
+       struct timeval tv[2];
+
+       if (tv50) {
+               timeval50_to_timeval(&tv50[0], &tv[0]);
+               timeval50_to_timeval(&tv50[1], &tv[1]);
+       }
+       return __lutimes50(path, tv50 ? tv : NULL);
+}
+
+int
+futimes(int fd, const struct timeval50 *tv50)
+{
+       struct timeval tv[2];
+
+       if (tv50) {
+               timeval50_to_timeval(&tv50[0], &tv[0]);
+               timeval50_to_timeval(&tv50[1], &tv[1]);
+       }
+       return __futimes50(fd, tv50 ? tv : NULL);
+}
diff --git a/lib/nbsd_libc/compat/sys/compat_wait4.c b/lib/nbsd_libc/compat/sys/compat_wait4.c
new file mode 100644 (file)
index 0000000..9f1f38b
--- /dev/null
@@ -0,0 +1,86 @@
+/*     $NetBSD: compat_wait4.c,v 1.2 2009/01/11 02:46:27 christos Exp $        */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: compat_wait4.c,v 1.2 2009/01/11 02:46:27 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define __LIBC12_SOURCE__
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <compat/sys/wait.h>
+#include <sys/resource.h>
+#include <compat/sys/resource.h>
+
+__warn_references(wait3,
+    "warning: reference to compatibility wait3(); include <sys/wait.h> to generate correct reference")
+__warn_references(wait4,
+    "warning: reference to compatibility wait4(); include <sys/wait.h> to generate correct reference")
+
+extern void __rusage_to_rusage50(const struct rusage *, struct rusage50 *);
+
+#ifdef __weak_alias
+__weak_alias(wait4, _wait4)
+__weak_alias(_sys_wait4, _wait4)
+__weak_alias(wait3, _wait3)
+#endif
+
+/*
+ * libc12 compatible wait4 routine.
+ */
+int
+wait3(int *status, int options, struct rusage50 *ru50)
+{
+       struct rusage ru;
+       int rv;
+
+       if ((rv = __wait350(status, options, ru50 ? &ru : NULL)) == -1)
+               return rv;
+       if (ru50)
+               __rusage_to_rusage50(&ru, ru50);
+       return rv;
+}
+
+int
+wait4(pid_t wpid, int *status, int options, struct rusage50 *ru50)
+{
+       struct rusage ru;
+       int rv;
+
+       if ((rv = __wait450(wpid, status, options, ru50 ? &ru : NULL)) == -1)
+               return rv;
+       if (ru50)
+               __rusage_to_rusage50(&ru, ru50);
+       return rv;
+}
diff --git a/lib/nbsd_libc/compat/sys/getdirentries.3 b/lib/nbsd_libc/compat/sys/getdirentries.3
new file mode 100644 (file)
index 0000000..b1f4b6e
--- /dev/null
@@ -0,0 +1,164 @@
+.\"    $NetBSD: getdirentries.3,v 1.1 2005/09/13 01:44:09 christos Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)getdirentries.2     8.1 (Berkeley) 6/9/93
+.\"
+.Dd June 9, 1993
+.Dt GETDIRENTRIES 3
+.Os
+.Sh NAME
+.Nm getdirentries
+.Nd "get directory entries in a filesystem independent format"
+.Sh SYNOPSIS
+.In dirent.h
+.Ft int
+.Fn getdirentries "int fd" "char *buf" "int nbytes" "long *basep"
+.Sh DESCRIPTION
+.Bf -symbolic
+.\" This interface is available from the compatibility library, libcompat and
+This interface is provided for compatibility only and
+has been obsoleted by
+.Xr getdents 2 .
+.Ef
+.Pp
+.Fn getdirentries
+reads directory entries from the directory
+referenced by the file descriptor
+.Fa fd
+into the buffer pointed to by
+.Fa buf ,
+in a filesystem independent format.
+Up to
+.Fa nbytes
+of data will be transferred.
+.Fa nbytes
+must be greater than or equal to the
+block size associated with the file,
+see
+.Xr stat 2 .
+Some filesystems may not support
+.Fn getdirentries
+with buffers smaller than this size.
+.Pp
+The data in the buffer is a series of
+.Em dirent
+structures each containing the following entries:
+.Bd -literal -offset indent
+unsigned long  d_fileno;
+unsigned short d_reclen;
+unsigned short d_namlen;
+char           d_name[MAXNAMELEN + 1]; /* see below */
+.Ed
+.Pp
+The
+.Fa d_fileno
+entry is a number which is unique for each
+distinct file in the filesystem.
+Files that are linked by hard links (see
+.Xr link 2 )
+have the same
+.Fa d_fileno .
+If
+.Fa d_fileno
+is zero, the entry refers to a deleted file.
+.Pp
+The
+.Fa d_reclen
+entry is the length, in bytes, of the directory record.
+.Pp
+The
+.Fa d_namlen
+entry specifies the length of the file name excluding the null byte.
+Thus the actual size of
+.Fa d_name
+may vary from 1 to
+.Dv MAXNAMELEN
+\&+ 1.
+.Pp
+The
+.Fa d_name
+entry contains a null terminated file name.
+.Pp
+Entries may be separated by extra space.
+The
+.Fa d_reclen
+entry may be used as an offset from the start of a
+.Fa dirent
+structure to the next structure, if any.
+.Pp
+The actual number of bytes transferred is returned.
+The current position pointer associated with
+.Fa fd
+is set to point to the next block of entries.
+The pointer may not advance by the number of bytes returned by
+.Fn getdirentries .
+A value of zero is returned when
+the end of the directory has been reached.
+.Pp
+.Fn getdirentries
+writes the position of the block read into the location pointed to by
+.Fa basep .
+Alternatively, the current position pointer may be set and retrieved by
+.Xr lseek 2 .
+The current position pointer should only be set to a value returned by
+.Xr lseek 2 ,
+a value returned in the location pointed to by
+.Fa basep ,
+or zero.
+.Sh RETURN VALUES
+If successful, the number of bytes actually transferred is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn getdirentries
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa fd
+is not a valid file descriptor open for reading.
+.It Bq Er EFAULT
+Either
+.Fa buf
+or
+.Fa basep
+point outside the allocated address space.
+.It Bq Er EIO
+An
+.Tn I/O
+error occurred while reading from or writing to the file system.
+.El
+.Sh SEE ALSO
+.Xr lseek 2 ,
+.Xr open 2
+.Sh HISTORY
+The
+.Fn getdirentries
+function first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/compat/time/Makefile.inc b/lib/nbsd_libc/compat/time/Makefile.inc
new file mode 100644 (file)
index 0000000..9728ed1
--- /dev/null
@@ -0,0 +1,4 @@
+#      $NetBSD: Makefile.inc,v 1.2 2009/01/11 03:46:25 christos Exp $
+
+.PATH: ${COMPATDIR}/time
+SRCS+= compat_localtime.c compat_difftime.c
diff --git a/lib/nbsd_libc/compat/time/compat_difftime.c b/lib/nbsd_libc/compat/time/compat_difftime.c
new file mode 100644 (file)
index 0000000..30f08ff
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: compat_difftime.c,v 1.2 2009/01/11 03:46:25 christos Exp $     */
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "namespace.h"
+#include <sys/cdefs.h>
+
+#define __LIBC12_SOURCE__
+#include <time.h>
+#include <sys/time.h>
+#include <compat/include/time.h>
+#include <compat/sys/time.h>
+
+#ifdef __weak_alias
+__weak_alias(difftime,_difftime)
+#endif
+
+#define timeval timeval50
+#define timespec timespec50
+#define        time_t  int32_t
+
+#include "time/difftime.c"
diff --git a/lib/nbsd_libc/compat/time/compat_localtime.c b/lib/nbsd_libc/compat/time/compat_localtime.c
new file mode 100644 (file)
index 0000000..8a2224e
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: compat_localtime.c,v 1.2 2009/01/11 03:46:25 christos Exp $    */
+
+/*
+ * Written by Jason R. Thorpe <thorpej@NetBSD.org>, October 21, 1997.
+ * Public domain.
+ */
+
+#include "namespace.h"
+#include <sys/cdefs.h>
+
+#define __LIBC12_SOURCE__
+#include <time.h>
+#include <sys/time.h>
+#include <compat/include/time.h>
+#include <compat/sys/time.h>
+
+#ifdef __weak_alias
+__weak_alias(ctime_r,_ctime_r)
+__weak_alias(gmtime_r,_gmtime_r)
+__weak_alias(localtime_r,_localtime_r)
+__weak_alias(offtime,_offtime)
+__weak_alias(posix2time,_posix2time)
+__weak_alias(time2posix,_time2posix)
+__weak_alias(timegm,_timegm)
+__weak_alias(timelocal,_timelocal)
+__weak_alias(timeoff,_timeoff)
+__weak_alias(tzset,_tzset)
+__weak_alias(tzsetwall,_tzsetwall)
+#endif
+
+__warn_references(ctime_r,
+    "warning: reference to compatibility ctime_r();"
+    " include <time.h> for correct reference")
+__warn_references(gmtime_r,
+    "warning: reference to compatibility gmtime_r();"
+    " include <time.h> for correct reference")
+__warn_references(localtime_r,
+    "warning: reference to compatibility localtime_r();"
+    " include <time.h> for correct reference")
+__warn_references(offtime,
+    "warning: reference to compatibility offtime();"
+    " include <time.h> for correct reference")
+__warn_references(posix2time,
+    "warning: reference to compatibility posix2time();"
+    " include <time.h> for correct reference")
+__warn_references(time2posix,
+    "warning: reference to compatibility time2posix();"
+    " include <time.h> for correct reference")
+__warn_references(timegm,
+    "warning: reference to compatibility timegm();"
+    " include <time.h> for correct reference")
+__warn_references(timelocal,
+    "warning: reference to compatibility timelocal();"
+    " include <time.h> for correct reference")
+__warn_references(timeoff,
+    "warning: reference to compatibility timeoff();"
+    " include <time.h> for correct reference")
+__warn_references(tzset,
+    "warning: reference to compatibility tzset();"
+    " include <time.h> for correct reference")
+__warn_references(tzsetwall,
+    "warning: reference to compatibility tzsetwall();"
+    " include <time.h> for correct reference")
+
+#define timeval timeval50
+#define timespec timespec50
+#define        time_t  int32_t
+
+#include "time/localtime.c"
diff --git a/lib/nbsd_libc/db/Makefile.inc b/lib/nbsd_libc/db/Makefile.inc
new file mode 100644 (file)
index 0000000..224719d
--- /dev/null
@@ -0,0 +1,11 @@
+#      $NetBSD: Makefile.inc,v 1.6 1997/10/22 23:14:11 lukem Exp $
+#      @(#)Makefile.inc        8.2 (Berkeley) 2/21/94
+#
+CPPFLAGS+=-D__DBINTERFACE_PRIVATE
+
+.include "${.CURDIR}/db/btree/Makefile.inc"
+.include "${.CURDIR}/db/db/Makefile.inc"
+.include "${.CURDIR}/db/hash/Makefile.inc"
+.include "${.CURDIR}/db/man/Makefile.inc"
+.include "${.CURDIR}/db/mpool/Makefile.inc"
+.include "${.CURDIR}/db/recno/Makefile.inc"
diff --git a/lib/nbsd_libc/db/README b/lib/nbsd_libc/db/README
new file mode 100644 (file)
index 0000000..d06cdf1
--- /dev/null
@@ -0,0 +1,41 @@
+#      $NetBSD: README,v 1.3 1996/05/03 21:17:07 cgd Exp $
+#      @(#)README      8.27 (Berkeley) 9/1/94
+
+This is version 1.85 of the Berkeley DB code.
+
+For information on compiling and installing this software, see the file
+PORT/README.
+
+Newer versions of this software will periodically be made available by
+anonymous ftp from ftp.cs.berkeley.edu.  An archive in compressed format
+is in ucb/4bsd/db.tar.Z, or in gzip format in ucb/4bsd/db.tar.gz.  If
+you'd like to receive announcements of future releases of this software,
+send email to the contact address below.
+
+Email questions may be addressed to Keith Bostic at bostic@cs.berkeley.edu.
+
+============================================
+Distribution contents:
+
+Makefile.inc   Ignore this, it's the 4.4BSD subsystem Makefile.
+PORT           The per OS/architecture directories to use to build
+               libdb.a, if you're not running 4.4BSD.  See the file
+               PORT/README for more information.
+README         This file.
+btree          The B+tree routines.
+changelog      List of changes, per version.
+db             The dbopen(3) interface routine.
+docs           Various USENIX papers, and the formatted manual pages.
+hash           The extended linear hashing routines.
+man            The unformatted manual pages.
+mpool          The memory pool routines.
+recno          The fixed/variable length record routines.
+test           Test package.
+
+============================================
+Debugging:
+
+If you're running a memory checker (e.g. Purify) on DB, make sure that
+you recompile it with "-DPURIFY" in the CFLAGS, first.  By default,
+allocated pages are not initialized by the DB code, and they will show
+up as reads of uninitialized memory in the buffer write routines.
diff --git a/lib/nbsd_libc/db/btree/Makefile.inc b/lib/nbsd_libc/db/btree/Makefile.inc
new file mode 100644 (file)
index 0000000..46fbb02
--- /dev/null
@@ -0,0 +1,8 @@
+#      $NetBSD: Makefile.inc,v 1.6 1996/05/03 21:50:36 cgd Exp $
+#      @(#)Makefile.inc        8.2 (Berkeley) 7/14/94
+
+.PATH: ${.CURDIR}/db/btree
+
+SRCS+= bt_close.c bt_conv.c bt_debug.c bt_delete.c bt_get.c bt_open.c \
+       bt_overflow.c bt_page.c bt_put.c bt_search.c bt_seq.c bt_split.c \
+       bt_utils.c
diff --git a/lib/nbsd_libc/db/btree/bt_close.c b/lib/nbsd_libc/db/btree/bt_close.c
new file mode 100644 (file)
index 0000000..a085952
--- /dev/null
@@ -0,0 +1,180 @@
+/*     $NetBSD: bt_close.c,v 1.14 2008/09/11 12:58:00 joerg Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_close.c,v 1.14 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <db.h>
+#include "btree.h"
+
+static int bt_meta(BTREE *);
+
+/*
+ * BT_CLOSE -- Close a btree.
+ *
+ * Parameters:
+ *     dbp:    pointer to access method
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+int
+__bt_close(DB *dbp)
+{
+       BTREE *t;
+       int fd;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       /* Sync the tree. */
+       if (__bt_sync(dbp, 0) == RET_ERROR)
+               return (RET_ERROR);
+
+       /* Close the memory pool. */
+       if (mpool_close(t->bt_mp) == RET_ERROR)
+               return (RET_ERROR);
+
+       /* Free random memory. */
+       if (t->bt_cursor.key.data != NULL) {
+               free(t->bt_cursor.key.data);
+               t->bt_cursor.key.size = 0;
+               t->bt_cursor.key.data = NULL;
+       }
+       if (t->bt_rkey.data) {
+               free(t->bt_rkey.data);
+               t->bt_rkey.size = 0;
+               t->bt_rkey.data = NULL;
+       }
+       if (t->bt_rdata.data) {
+               free(t->bt_rdata.data);
+               t->bt_rdata.size = 0;
+               t->bt_rdata.data = NULL;
+       }
+
+       fd = t->bt_fd;
+       free(t);
+       free(dbp);
+       return (close(fd) ? RET_ERROR : RET_SUCCESS);
+}
+
+/*
+ * BT_SYNC -- sync the btree to disk.
+ *
+ * Parameters:
+ *     dbp:    pointer to access method
+ *
+ * Returns:
+ *     RET_SUCCESS, RET_ERROR.
+ */
+int
+__bt_sync(const DB *dbp, u_int flags)
+{
+       BTREE *t;
+       int status;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       /* Sync doesn't currently take any flags. */
+       if (flags != 0) {
+               errno = EINVAL;
+               return (RET_ERROR);
+       }
+
+       if (F_ISSET(t, B_INMEM | B_RDONLY) || !F_ISSET(t, B_MODIFIED))
+               return (RET_SUCCESS);
+
+       if (F_ISSET(t, B_METADIRTY) && bt_meta(t) == RET_ERROR)
+               return (RET_ERROR);
+
+       if ((status = mpool_sync(t->bt_mp)) == RET_SUCCESS)
+               F_CLR(t, B_MODIFIED);
+
+       return (status);
+}
+
+/*
+ * BT_META -- write the tree meta data to disk.
+ *
+ * Parameters:
+ *     t:      tree
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+static int
+bt_meta(BTREE *t)
+{
+       BTMETA m;
+       void *p;
+
+       if ((p = mpool_get(t->bt_mp, P_META, 0)) == NULL)
+               return (RET_ERROR);
+
+       /* Fill in metadata. */
+       m.magic = BTREEMAGIC;
+       m.version = BTREEVERSION;
+       m.psize = t->bt_psize;
+       m.free = t->bt_free;
+       m.nrecs = t->bt_nrecs;
+       m.flags = F_ISSET(t, SAVEMETA);
+
+       memmove(p, &m, sizeof(BTMETA));
+       mpool_put(t->bt_mp, p, MPOOL_DIRTY);
+       return (RET_SUCCESS);
+}
diff --git a/lib/nbsd_libc/db/btree/bt_conv.c b/lib/nbsd_libc/db/btree/bt_conv.c
new file mode 100644 (file)
index 0000000..2c5217a
--- /dev/null
@@ -0,0 +1,214 @@
+/*     $NetBSD: bt_conv.c,v 1.14 2008/09/10 17:52:35 joerg Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_conv.c,v 1.14 2008/09/10 17:52:35 joerg Exp $");
+
+#include <assert.h>
+#include <stdio.h>
+
+#include <db.h>
+#include "btree.h"
+
+static void mswap(PAGE *);
+
+/*
+ * __BT_BPGIN, __BT_BPGOUT --
+ *     Convert host-specific number layout to/from the host-independent
+ *     format stored on disk.
+ *
+ * Parameters:
+ *     t:      tree
+ *     pg:     page number
+ *     h:      page to convert
+ */
+void
+__bt_pgin(void *t, pgno_t pg, void *pp)
+{
+       PAGE *h;
+       indx_t i, top;
+       uint8_t flags;
+       char *p;
+
+       if (!F_ISSET(((BTREE *)t), B_NEEDSWAP))
+               return;
+       if (pg == P_META) {
+               mswap(pp);
+               return;
+       }
+
+       h = pp;
+       M_32_SWAP(h->pgno);
+       M_32_SWAP(h->prevpg);
+       M_32_SWAP(h->nextpg);
+       M_32_SWAP(h->flags);
+       M_16_SWAP(h->lower);
+       M_16_SWAP(h->upper);
+
+       top = NEXTINDEX(h);
+       if ((h->flags & P_TYPE) == P_BINTERNAL)
+               for (i = 0; i < top; i++) {
+                       M_16_SWAP(h->linp[i]);
+                       p = (char *)(void *)GETBINTERNAL(h, i);
+                       P_32_SWAP(p);
+                       p += sizeof(uint32_t);
+                       P_32_SWAP(p);
+                       p += sizeof(pgno_t);
+                       if (*(uint8_t *)p & P_BIGKEY) {
+                               p += sizeof(uint8_t);
+                               P_32_SWAP(p);
+                               p += sizeof(pgno_t);
+                               P_32_SWAP(p);
+                       }
+               }
+       else if ((h->flags & P_TYPE) == P_BLEAF)
+               for (i = 0; i < top; i++) {
+                       M_16_SWAP(h->linp[i]);
+                       p = (char *)(void *)GETBLEAF(h, i);
+                       P_32_SWAP(p);
+                       p += sizeof(uint32_t);
+                       P_32_SWAP(p);
+                       p += sizeof(uint32_t);
+                       flags = *(uint8_t *)p;
+                       if (flags & (P_BIGKEY | P_BIGDATA)) {
+                               p += sizeof(uint8_t);
+                               if (flags & P_BIGKEY) {
+                                       P_32_SWAP(p);
+                                       p += sizeof(pgno_t);
+                                       P_32_SWAP(p);
+                               }
+                               if (flags & P_BIGDATA) {
+                                       p += sizeof(uint32_t);
+                                       P_32_SWAP(p);
+                                       p += sizeof(pgno_t);
+                                       P_32_SWAP(p);
+                               }
+                       }
+               }
+}
+
+void
+__bt_pgout(void *t, pgno_t pg, void *pp)
+{
+       PAGE *h;
+       indx_t i, top;
+       uint8_t flags;
+       char *p;
+
+       if (!F_ISSET(((BTREE *)t), B_NEEDSWAP))
+               return;
+       if (pg == P_META) {
+               mswap(pp);
+               return;
+       }
+
+       h = pp;
+       top = NEXTINDEX(h);
+       if ((h->flags & P_TYPE) == P_BINTERNAL)
+               for (i = 0; i < top; i++) {
+                       p = (char *)(void *)GETBINTERNAL(h, i);
+                       P_32_SWAP(p);
+                       p += sizeof(uint32_t);
+                       P_32_SWAP(p);
+                       p += sizeof(pgno_t);
+                       if (*(uint8_t *)p & P_BIGKEY) {
+                               p += sizeof(uint8_t);
+                               P_32_SWAP(p);
+                               p += sizeof(pgno_t);
+                               P_32_SWAP(p);
+                       }
+                       M_16_SWAP(h->linp[i]);
+               }
+       else if ((h->flags & P_TYPE) == P_BLEAF)
+               for (i = 0; i < top; i++) {
+                       p = (char *)(void *)GETBLEAF(h, i);
+                       P_32_SWAP(p);
+                       p += sizeof(uint32_t);
+                       P_32_SWAP(p);
+                       p += sizeof(uint32_t);
+                       flags = *(uint8_t *)p;
+                       if (flags & (P_BIGKEY | P_BIGDATA)) {
+                               p += sizeof(uint8_t);
+                               if (flags & P_BIGKEY) {
+                                       P_32_SWAP(p);
+                                       p += sizeof(pgno_t);
+                                       P_32_SWAP(p);
+                               }
+                               if (flags & P_BIGDATA) {
+                                       p += sizeof(uint32_t);
+                                       P_32_SWAP(p);
+                                       p += sizeof(pgno_t);
+                                       P_32_SWAP(p);
+                               }
+                       }
+                       M_16_SWAP(h->linp[i]);
+               }
+
+       M_32_SWAP(h->pgno);
+       M_32_SWAP(h->prevpg);
+       M_32_SWAP(h->nextpg);
+       M_32_SWAP(h->flags);
+       M_16_SWAP(h->lower);
+       M_16_SWAP(h->upper);
+}
+
+/*
+ * MSWAP -- Actually swap the bytes on the meta page.
+ *
+ * Parameters:
+ *     p:      page to convert
+ */
+static void
+mswap(PAGE *pg)
+{
+       char *p;
+
+       p = (char *)(void *)pg;
+       P_32_SWAP(p);           /* magic */
+       p += sizeof(uint32_t);
+       P_32_SWAP(p);           /* version */
+       p += sizeof(uint32_t);
+       P_32_SWAP(p);           /* psize */
+       p += sizeof(uint32_t);
+       P_32_SWAP(p);           /* free */
+       p += sizeof(uint32_t);
+       P_32_SWAP(p);           /* nrecs */
+       p += sizeof(uint32_t);
+       P_32_SWAP(p);           /* flags */
+       p += sizeof(uint32_t);
+}
diff --git a/lib/nbsd_libc/db/btree/bt_debug.c b/lib/nbsd_libc/db/btree/bt_debug.c
new file mode 100644 (file)
index 0000000..590ca4a
--- /dev/null
@@ -0,0 +1,324 @@
+/*     $NetBSD: bt_debug.c,v 1.15 2008/09/10 17:52:35 joerg Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_debug.c,v 1.15 2008/09/10 17:52:35 joerg Exp $");
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <db.h>
+#include "btree.h"
+
+#ifdef DEBUG
+/*
+ * BT_DUMP -- Dump the tree
+ *
+ * Parameters:
+ *     dbp:    pointer to the DB
+ */
+void
+__bt_dump(DB *dbp)
+{
+       BTREE *t;
+       PAGE *h;
+       pgno_t i;
+       const char *sep;
+
+       t = dbp->internal;
+       (void)fprintf(stderr, "%s: pgsz %d",
+           F_ISSET(t, B_INMEM) ? "memory" : "disk", t->bt_psize);
+       if (F_ISSET(t, R_RECNO))
+               (void)fprintf(stderr, " keys %lu", (unsigned long) t->bt_nrecs);
+#undef X
+#define        X(flag, name) \
+       if (F_ISSET(t, flag)) { \
+               (void)fprintf(stderr, "%s%s", sep, name); \
+               sep = ", "; \
+       }
+       if (t->flags != 0) {
+               sep = " flags (";
+               X(R_FIXLEN,     "FIXLEN");
+               X(B_INMEM,      "INMEM");
+               X(B_NODUPS,     "NODUPS");
+               X(B_RDONLY,     "RDONLY");
+               X(R_RECNO,      "RECNO");
+               X(B_METADIRTY,"METADIRTY");
+               (void)fprintf(stderr, ")\n");
+       }
+#undef X
+
+       for (i = P_ROOT; (h = mpool_get(t->bt_mp, i, 0)) != NULL; ++i) {
+               __bt_dpage(h);
+               (void)mpool_put(t->bt_mp, h, 0);
+       }
+}
+
+/*
+ * BT_DMPAGE -- Dump the meta page
+ *
+ * Parameters:
+ *     h:      pointer to the PAGE
+ */
+void
+__bt_dmpage(PAGE *h)
+{
+       BTMETA *m;
+       const char *sep;
+
+       m = (BTMETA *)(void *)h;
+       (void)fprintf(stderr, "magic %lx\n", (unsigned long) m->magic);
+       (void)fprintf(stderr, "version %lu\n", (unsigned long) m->version);
+       (void)fprintf(stderr, "psize %lu\n", (unsigned long) m->psize);
+       (void)fprintf(stderr, "free %lu\n", (unsigned long) m->free);
+       (void)fprintf(stderr, "nrecs %lu\n", (unsigned long) m->nrecs);
+       (void)fprintf(stderr, "flags %lu", (unsigned long) m->flags);
+#undef X
+#define        X(flag, name) \
+       if (m->flags & flag) { \
+               (void)fprintf(stderr, "%s%s", sep, name); \
+               sep = ", "; \
+       }
+       if (m->flags) {
+               sep = " (";
+               X(B_NODUPS,     "NODUPS");
+               X(R_RECNO,      "RECNO");
+               (void)fprintf(stderr, ")");
+       }
+}
+
+/*
+ * BT_DNPAGE -- Dump the page
+ *
+ * Parameters:
+ *     n:      page number to dump.
+ */
+void
+__bt_dnpage(DB *dbp, pgno_t pgno)
+{
+       BTREE *t;
+       PAGE *h;
+
+       t = dbp->internal;
+       if ((h = mpool_get(t->bt_mp, pgno, 0)) != NULL) {
+               __bt_dpage(h);
+               (void)mpool_put(t->bt_mp, h, 0);
+       }
+}
+
+/*
+ * BT_DPAGE -- Dump the page
+ *
+ * Parameters:
+ *     h:      pointer to the PAGE
+ */
+void
+__bt_dpage(PAGE *h)
+{
+       BINTERNAL *bi;
+       BLEAF *bl;
+       RINTERNAL *ri;
+       RLEAF *rl;
+       indx_t cur, top;
+       const char *sep;
+
+       (void)fprintf(stderr, "    page %d: (", h->pgno);
+#undef X
+#define        X(flag, name) \
+       if (h->flags & flag) { \
+               (void)fprintf(stderr, "%s%s", sep, name); \
+               sep = ", "; \
+       }
+       sep = "";
+       X(P_BINTERNAL,  "BINTERNAL")            /* types */
+       X(P_BLEAF,      "BLEAF")
+       X(P_RINTERNAL,  "RINTERNAL")            /* types */
+       X(P_RLEAF,      "RLEAF")
+       X(P_OVERFLOW,   "OVERFLOW")
+       X(P_PRESERVE,   "PRESERVE");
+       (void)fprintf(stderr, ")\n");
+#undef X
+
+       (void)fprintf(stderr, "\tprev %2d next %2d", h->prevpg, h->nextpg);
+       if (h->flags & P_OVERFLOW)
+               return;
+
+       top = NEXTINDEX(h);
+       (void)fprintf(stderr, " lower %3d upper %3d nextind %d\n",
+           h->lower, h->upper, top);
+       for (cur = 0; cur < top; cur++) {
+               (void)fprintf(stderr, "\t[%03d] %4d ", cur, h->linp[cur]);
+               switch (h->flags & P_TYPE) {
+               case P_BINTERNAL:
+                       bi = GETBINTERNAL(h, cur);
+                       (void)fprintf(stderr,
+                           "size %03d pgno %03d", bi->ksize, bi->pgno);
+                       if (bi->flags & P_BIGKEY)
+                               (void)fprintf(stderr, " (indirect)");
+                       else if (bi->ksize)
+                               (void)fprintf(stderr,
+                                   " {%.*s}", (int)bi->ksize, bi->bytes);
+                       break;
+               case P_RINTERNAL:
+                       ri = GETRINTERNAL(h, cur);
+                       (void)fprintf(stderr, "entries %03d pgno %03d",
+                               ri->nrecs, ri->pgno);
+                       break;
+               case P_BLEAF:
+                       bl = GETBLEAF(h, cur);
+                       if (bl->flags & P_BIGKEY)
+                               (void)fprintf(stderr,
+                                   "big key page %lu size %u/",
+                                   (unsigned long) *(pgno_t *)(void *)bl->bytes,
+                                   *(uint32_t *)(void *)(bl->bytes + sizeof(pgno_t)));
+                       else if (bl->ksize)
+                               (void)fprintf(stderr, "%s/", bl->bytes);
+                       if (bl->flags & P_BIGDATA)
+                               (void)fprintf(stderr,
+                                   "big data page %lu size %u",
+                                   (unsigned long) *(pgno_t *)(void *)(bl->bytes + bl->ksize),
+                                   *(uint32_t *)(void *)(bl->bytes + bl->ksize +
+                                   sizeof(pgno_t)));
+                       else if (bl->dsize)
+                               (void)fprintf(stderr, "%.*s",
+                                   (int)bl->dsize, bl->bytes + bl->ksize);
+                       break;
+               case P_RLEAF:
+                       rl = GETRLEAF(h, cur);
+                       if (rl->flags & P_BIGDATA)
+                               (void)fprintf(stderr,
+                                   "big data page %lu size %u",
+                                   (unsigned long) *(pgno_t *)(void *)rl->bytes,
+                                   *(uint32_t *)(void *)(rl->bytes + sizeof(pgno_t)));
+                       else if (rl->dsize)
+                               (void)fprintf(stderr,
+                                   "%.*s", (int)rl->dsize, rl->bytes);
+                       break;
+               }
+               (void)fprintf(stderr, "\n");
+       }
+}
+#endif
+
+#ifdef STATISTICS
+/*
+ * BT_STAT -- Gather/print the tree statistics
+ *
+ * Parameters:
+ *     dbp:    pointer to the DB
+ */
+void
+__bt_stat(DB *dbp)
+{
+       extern unsigned long bt_cache_hit, bt_cache_miss, bt_pfxsaved, bt_rootsplit;
+       extern unsigned long bt_sortsplit, bt_split;
+       BTREE *t;
+       PAGE *h;
+       pgno_t i, pcont, pinternal, pleaf;
+       unsigned long ifree, lfree, nkeys;
+       int levels;
+
+       t = dbp->internal;
+       pcont = pinternal = pleaf = 0;
+       nkeys = ifree = lfree = 0;
+       for (i = P_ROOT; (h = mpool_get(t->bt_mp, i, 0)) != NULL; ++i) {
+               switch (h->flags & P_TYPE) {
+               case P_BINTERNAL:
+               case P_RINTERNAL:
+                       ++pinternal;
+                       ifree += h->upper - h->lower;
+                       break;
+               case P_BLEAF:
+               case P_RLEAF:
+                       ++pleaf;
+                       lfree += h->upper - h->lower;
+                       nkeys += NEXTINDEX(h);
+                       break;
+               case P_OVERFLOW:
+                       ++pcont;
+                       break;
+               }
+               (void)mpool_put(t->bt_mp, h, 0);
+       }
+
+       /* Count the levels of the tree. */
+       for (i = P_ROOT, levels = 0 ;; ++levels) {
+               h = mpool_get(t->bt_mp, i, 0);
+               if (h->flags & (P_BLEAF|P_RLEAF)) {
+                       if (levels == 0)
+                               levels = 1;
+                       (void)mpool_put(t->bt_mp, h, 0);
+                       break;
+               }
+               i = F_ISSET(t, R_RECNO) ?
+                   GETRINTERNAL(h, 0)->pgno :
+                   GETBINTERNAL(h, 0)->pgno;
+               (void)mpool_put(t->bt_mp, h, 0);
+       }
+
+       (void)fprintf(stderr, "%d level%s with %ld keys",
+           levels, levels == 1 ? "" : "s", nkeys);
+       if (F_ISSET(t, R_RECNO))
+               (void)fprintf(stderr, " (%ld header count)", (long)t->bt_nrecs);
+       (void)fprintf(stderr,
+           "\n%lu pages (leaf %ld, internal %ld, overflow %ld)\n",
+           (long)pinternal + pleaf + pcont, (long)pleaf, (long)pinternal,
+           (long)pcont);
+       (void)fprintf(stderr, "%ld cache hits, %ld cache misses\n",
+           bt_cache_hit, bt_cache_miss);
+       (void)fprintf(stderr, "%ld splits (%ld root splits, %ld sort splits)\n",
+           bt_split, bt_rootsplit, bt_sortsplit);
+       pleaf *= t->bt_psize - BTDATAOFF;
+       if (pleaf)
+               (void)fprintf(stderr,
+                   "%.0f%% leaf fill (%ld bytes used, %ld bytes free)\n",
+                   ((double)(pleaf - lfree) / pleaf) * 100,
+                   pleaf - lfree, lfree);
+       pinternal *= t->bt_psize - BTDATAOFF;
+       if (pinternal)
+               (void)fprintf(stderr,
+                   "%.0f%% internal fill (%ld bytes used, %ld bytes free\n",
+                   ((double)(pinternal - ifree) / pinternal) * 100,
+                   pinternal - ifree, ifree);
+       if (bt_pfxsaved)
+               (void)fprintf(stderr, "prefix checking removed %lu bytes.\n",
+                   bt_pfxsaved);
+}
+#endif
diff --git a/lib/nbsd_libc/db/btree/bt_delete.c b/lib/nbsd_libc/db/btree/bt_delete.c
new file mode 100644 (file)
index 0000000..701c8b2
--- /dev/null
@@ -0,0 +1,642 @@
+/*     $NetBSD: bt_delete.c,v 1.17 2009/01/29 02:02:36 lukem Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_delete.c,v 1.17 2009/01/29 02:02:36 lukem Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <db.h>
+#include "btree.h"
+
+static int __bt_bdelete(BTREE *, const DBT *);
+static int __bt_curdel(BTREE *, const DBT *, PAGE *, u_int);
+static int __bt_pdelete(BTREE *, PAGE *);
+static int __bt_relink(BTREE *, PAGE *);
+static int __bt_stkacq(BTREE *, PAGE **, CURSOR *);
+
+/*
+ * __bt_delete
+ *     Delete the item(s) referenced by a key.
+ *
+ * Return RET_SPECIAL if the key is not found.
+ */
+int
+__bt_delete(const DB *dbp, const DBT *key, u_int flags)
+{
+       BTREE *t;
+       CURSOR *c;
+       PAGE *h;
+       int status;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       /* Check for change to a read-only tree. */
+       if (F_ISSET(t, B_RDONLY)) {
+               errno = EPERM;
+               return (RET_ERROR);
+       }
+
+       switch (flags) {
+       case 0:
+               status = __bt_bdelete(t, key);
+               break;
+       case R_CURSOR:
+               /*
+                * If flags is R_CURSOR, delete the cursor.  Must already
+                * have started a scan and not have already deleted it.
+                */
+               c = &t->bt_cursor;
+               if (F_ISSET(c, CURS_INIT)) {
+                       if (F_ISSET(c, CURS_ACQUIRE | CURS_AFTER | CURS_BEFORE))
+                               return (RET_SPECIAL);
+                       if ((h = mpool_get(t->bt_mp, c->pg.pgno, 0)) == NULL)
+                               return (RET_ERROR);
+
+                       /*
+                        * If the page is about to be emptied, we'll need to
+                        * delete it, which means we have to acquire a stack.
+                        */
+                       if (NEXTINDEX(h) == 1)
+                               if (__bt_stkacq(t, &h, &t->bt_cursor))
+                                       return (RET_ERROR);
+
+                       status = __bt_dleaf(t, NULL, h, (u_int)c->pg.index);
+
+                       if (NEXTINDEX(h) == 0 && status == RET_SUCCESS) {
+                               if (__bt_pdelete(t, h))
+                                       return (RET_ERROR);
+                       } else
+                               mpool_put(t->bt_mp, h,
+                                   (u_int)(status == RET_SUCCESS ?
+                                   MPOOL_DIRTY : 0));
+                       break;
+               }
+               /* FALLTHROUGH */
+       default:
+               errno = EINVAL;
+               return (RET_ERROR);
+       }
+       if (status == RET_SUCCESS)
+               F_SET(t, B_MODIFIED);
+       return (status);
+}
+
+/*
+ * __bt_stkacq --
+ *     Acquire a stack so we can delete a cursor entry.
+ *
+ * Parameters:
+ *       t:    tree
+ *      hp:    pointer to current, pinned PAGE pointer
+ *       c:    pointer to the cursor
+ *
+ * Returns:
+ *     0 on success, 1 on failure
+ */
+static int
+__bt_stkacq(BTREE *t, PAGE **hp, CURSOR *c)
+{
+       BINTERNAL *bi;
+       EPG *e;
+       EPGNO *parent;
+       PAGE *h;
+       indx_t idx = 0; /* Pacify gcc */
+       pgno_t pgno;
+       recno_t nextpg, prevpg;
+       int exact, level;
+       
+       /*
+        * Find the first occurrence of the key in the tree.  Toss the
+        * currently locked page so we don't hit an already-locked page.
+        */
+       h = *hp;
+       mpool_put(t->bt_mp, h, 0);
+       if ((e = __bt_search(t, &c->key, &exact)) == NULL)
+               return (1);
+       h = e->page;
+
+       /* See if we got it in one shot. */
+       if (h->pgno == c->pg.pgno)
+               goto ret;
+
+       /*
+        * Move right, looking for the page.  At each move we have to move
+        * up the stack until we don't have to move to the next page.  If
+        * we have to change pages at an internal level, we have to fix the
+        * stack back up.
+        */
+       while (h->pgno != c->pg.pgno) {
+               if ((nextpg = h->nextpg) == P_INVALID)
+                       break;
+               mpool_put(t->bt_mp, h, 0);
+
+               /* Move up the stack. */
+               for (level = 0; (parent = BT_POP(t)) != NULL; ++level) {
+                       /* Get the parent page. */
+                       if ((h = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL)
+                               return (1);
+
+                       /* Move to the next index. */
+                       if (parent->index != NEXTINDEX(h) - 1) {
+                               idx = parent->index + 1;
+                               BT_PUSH(t, h->pgno, idx);
+                               break;
+                       }
+                       mpool_put(t->bt_mp, h, 0);
+               }
+
+               /* Restore the stack. */
+               while (level--) {
+                       /* Push the next level down onto the stack. */
+                       bi = GETBINTERNAL(h, idx);
+                       pgno = bi->pgno;
+                       BT_PUSH(t, pgno, 0);
+
+                       /* Lose the currently pinned page. */
+                       mpool_put(t->bt_mp, h, 0);
+
+                       /* Get the next level down. */
+                       if ((h = mpool_get(t->bt_mp, pgno, 0)) == NULL)
+                               return (1);
+                       idx = 0;
+               }
+               mpool_put(t->bt_mp, h, 0);
+               if ((h = mpool_get(t->bt_mp, nextpg, 0)) == NULL)
+                       return (1);
+       }
+
+       if (h->pgno == c->pg.pgno)
+               goto ret;
+
+       /* Reacquire the original stack. */
+       mpool_put(t->bt_mp, h, 0);
+       if ((e = __bt_search(t, &c->key, &exact)) == NULL)
+               return (1);
+       h = e->page;
+
+       /*
+        * Move left, looking for the page.  At each move we have to move
+        * up the stack until we don't have to change pages to move to the
+        * next page.  If we have to change pages at an internal level, we
+        * have to fix the stack back up.
+        */
+       while (h->pgno != c->pg.pgno) {
+               if ((prevpg = h->prevpg) == P_INVALID)
+                       break;
+               mpool_put(t->bt_mp, h, 0);
+
+               /* Move up the stack. */
+               for (level = 0; (parent = BT_POP(t)) != NULL; ++level) {
+                       /* Get the parent page. */
+                       if ((h = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL)
+                               return (1);
+
+                       /* Move to the next index. */
+                       if (parent->index != 0) {
+                               idx = parent->index - 1;
+                               BT_PUSH(t, h->pgno, idx);
+                               break;
+                       }
+                       mpool_put(t->bt_mp, h, 0);
+               }
+
+               /* Restore the stack. */
+               while (level--) {
+                       /* Push the next level down onto the stack. */
+                       bi = GETBINTERNAL(h, idx);
+                       pgno = bi->pgno;
+
+                       /* Lose the currently pinned page. */
+                       mpool_put(t->bt_mp, h, 0);
+
+                       /* Get the next level down. */
+                       if ((h = mpool_get(t->bt_mp, pgno, 0)) == NULL)
+                               return (1);
+
+                       idx = NEXTINDEX(h) - 1;
+                       BT_PUSH(t, pgno, idx);
+               }
+               mpool_put(t->bt_mp, h, 0);
+               if ((h = mpool_get(t->bt_mp, prevpg, 0)) == NULL)
+                       return (1);
+       }
+       
+
+ret:   mpool_put(t->bt_mp, h, 0);
+       return ((*hp = mpool_get(t->bt_mp, c->pg.pgno, 0)) == NULL);
+}
+
+/*
+ * __bt_bdelete --
+ *     Delete all key/data pairs matching the specified key.
+ *
+ * Parameters:
+ *       t:    tree
+ *     key:    key to delete
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key not found.
+ */
+static int
+__bt_bdelete(BTREE *t, const DBT *key)
+{
+       EPG *e;
+       PAGE *h;
+       int deleted, exact, redo;
+
+       deleted = 0;
+
+       /* Find any matching record; __bt_search pins the page. */
+loop:  if ((e = __bt_search(t, key, &exact)) == NULL)
+               return (deleted ? RET_SUCCESS : RET_ERROR);
+       if (!exact) {
+               mpool_put(t->bt_mp, e->page, 0);
+               return (deleted ? RET_SUCCESS : RET_SPECIAL);
+       }
+
+       /*
+        * Delete forward, then delete backward, from the found key.  If
+        * there are duplicates and we reach either side of the page, do
+        * the key search again, so that we get them all.
+        */
+       redo = 0;
+       h = e->page;
+       do {
+               if (__bt_dleaf(t, key, h, (u_int)e->index)) {
+                       mpool_put(t->bt_mp, h, 0);
+                       return (RET_ERROR);
+               }
+               if (F_ISSET(t, B_NODUPS)) {
+                       if (NEXTINDEX(h) == 0) {
+                               if (__bt_pdelete(t, h))
+                                       return (RET_ERROR);
+                       } else
+                               mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+                       return (RET_SUCCESS);
+               }
+               deleted = 1;
+       } while (e->index < NEXTINDEX(h) && __bt_cmp(t, key, e) == 0);
+
+       /* Check for right-hand edge of the page. */
+       if (e->index == NEXTINDEX(h))
+               redo = 1;
+
+       /* Delete from the key to the beginning of the page. */
+       while (e->index-- > 0) {
+               if (__bt_cmp(t, key, e) != 0)
+                       break;
+               if (__bt_dleaf(t, key, h, (u_int)e->index) == RET_ERROR) {
+                       mpool_put(t->bt_mp, h, 0);
+                       return (RET_ERROR);
+               }
+               if (e->index == 0)
+                       redo = 1;
+       }
+
+       /* Check for an empty page. */
+       if (NEXTINDEX(h) == 0) {
+               if (__bt_pdelete(t, h))
+                       return (RET_ERROR);
+               goto loop;
+       }
+
+       /* Put the page. */
+       mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+
+       if (redo)
+               goto loop;
+       return (RET_SUCCESS);
+}
+
+/*
+ * __bt_pdelete --
+ *     Delete a single page from the tree.
+ *
+ * Parameters:
+ *     t:      tree
+ *     h:      leaf page
+ *
+ * Returns:
+ *     RET_SUCCESS, RET_ERROR.
+ *
+ * Side-effects:
+ *     mpool_put's the page
+ */
+static int
+__bt_pdelete(BTREE *t, PAGE *h)
+{
+       BINTERNAL *bi;
+       PAGE *pg;
+       EPGNO *parent;
+       indx_t cnt, idx, *ip, offset;
+       uint32_t nksize;
+       char *from;
+
+       /*
+        * Walk the parent page stack -- a LIFO stack of the pages that were
+        * traversed when we searched for the page where the delete occurred.
+        * Each stack entry is a page number and a page index offset.  The
+        * offset is for the page traversed on the search.  We've just deleted
+        * a page, so we have to delete the key from the parent page.
+        *
+        * If the delete from the parent page makes it empty, this process may
+        * continue all the way up the tree.  We stop if we reach the root page
+        * (which is never deleted, it's just not worth the effort) or if the
+        * delete does not empty the page.
+        */
+       while ((parent = BT_POP(t)) != NULL) {
+               /* Get the parent page. */
+               if ((pg = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL)
+                       return (RET_ERROR);
+               
+               idx = parent->index;
+               bi = GETBINTERNAL(pg, idx);
+
+               /* Free any overflow pages. */
+               if (bi->flags & P_BIGKEY &&
+                   __ovfl_delete(t, bi->bytes) == RET_ERROR) {
+                       mpool_put(t->bt_mp, pg, 0);
+                       return (RET_ERROR);
+               }
+
+               /*
+                * Free the parent if it has only the one key and it's not the
+                * root page. If it's the rootpage, turn it back into an empty
+                * leaf page.
+                */
+               if (NEXTINDEX(pg) == 1) {
+                       if (pg->pgno == P_ROOT) {
+                               pg->lower = BTDATAOFF;
+                               pg->upper = t->bt_psize;
+                               pg->flags = P_BLEAF;
+                       } else {
+                               if (__bt_relink(t, pg) || __bt_free(t, pg))
+                                       return (RET_ERROR);
+                               continue;
+                       }
+               } else {
+                       /* Pack remaining key items at the end of the page. */
+                       nksize = NBINTERNAL(bi->ksize);
+                       from = (char *)(void *)pg + pg->upper;
+                       memmove(from + nksize, from,
+                       (size_t)((char *)(void *)bi - from));
+                       pg->upper += nksize;
+
+                       /* Adjust indices' offsets, shift the indices down. */
+                       offset = pg->linp[idx];
+                       for (cnt = idx, ip = &pg->linp[0]; cnt--; ++ip)
+                               if (ip[0] < offset)
+                                       ip[0] += nksize;
+                       for (cnt = NEXTINDEX(pg) - idx; --cnt; ++ip)
+                               ip[0] = ip[1] < offset ? ip[1] + nksize : ip[1];
+                       pg->lower -= sizeof(indx_t);
+               }
+
+               mpool_put(t->bt_mp, pg, MPOOL_DIRTY);
+               break;
+       }
+
+       /* Free the leaf page, as long as it wasn't the root. */
+       if (h->pgno == P_ROOT) {
+               mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+               return (RET_SUCCESS);
+       }
+       return (__bt_relink(t, h) || __bt_free(t, h));
+}
+
+/*
+ * __bt_dleaf --
+ *     Delete a single record from a leaf page.
+ *
+ * Parameters:
+ *     t:      tree
+ *    key:     referenced key
+ *     h:      page
+ *     idx:    index on page to delete
+ *
+ * Returns:
+ *     RET_SUCCESS, RET_ERROR.
+ */
+int
+__bt_dleaf(BTREE *t, const DBT *key, PAGE *h, u_int idx)
+{
+       BLEAF *bl;
+       indx_t cnt, *ip, offset;
+       uint32_t nbytes;
+       void *to;
+       char *from;
+
+       /* If this record is referenced by the cursor, delete the cursor. */
+       if (F_ISSET(&t->bt_cursor, CURS_INIT) &&
+           !F_ISSET(&t->bt_cursor, CURS_ACQUIRE) &&
+           t->bt_cursor.pg.pgno == h->pgno && t->bt_cursor.pg.index == idx &&
+           __bt_curdel(t, key, h, idx))
+               return (RET_ERROR);
+
+       /* If the entry uses overflow pages, make them available for reuse. */
+       to = bl = GETBLEAF(h, idx);
+       if (bl->flags & P_BIGKEY && __ovfl_delete(t, bl->bytes) == RET_ERROR)
+               return (RET_ERROR);
+       if (bl->flags & P_BIGDATA &&
+           __ovfl_delete(t, bl->bytes + bl->ksize) == RET_ERROR)
+               return (RET_ERROR);
+
+       /* Pack the remaining key/data items at the end of the page. */
+       nbytes = NBLEAF(bl);
+       from = (char *)(void *)h + h->upper;
+       memmove(from + nbytes, from, (size_t)((char *)(void *)to - from));
+       h->upper += nbytes;
+
+       /* Adjust the indices' offsets, shift the indices down. */
+       offset = h->linp[idx];
+       for (cnt = idx, ip = &h->linp[0]; cnt--; ++ip)
+               if (ip[0] < offset)
+                       ip[0] += nbytes;
+       for (cnt = NEXTINDEX(h) - idx; --cnt; ++ip)
+               ip[0] = ip[1] < offset ? ip[1] + nbytes : ip[1];
+       h->lower -= sizeof(indx_t);
+
+       /* If the cursor is on this page, adjust it as necessary. */
+       if (F_ISSET(&t->bt_cursor, CURS_INIT) &&
+           !F_ISSET(&t->bt_cursor, CURS_ACQUIRE) &&
+           t->bt_cursor.pg.pgno == h->pgno && t->bt_cursor.pg.index > idx)
+               --t->bt_cursor.pg.index;
+
+       return (RET_SUCCESS);
+}
+
+/*
+ * __bt_curdel --
+ *     Delete the cursor.
+ *
+ * Parameters:
+ *     t:      tree
+ *    key:     referenced key (or NULL)
+ *     h:      page
+ *  idx:       index on page to delete
+ *
+ * Returns:
+ *     RET_SUCCESS, RET_ERROR.
+ */
+static int
+__bt_curdel(BTREE *t, const DBT *key, PAGE *h, u_int idx)
+{
+       CURSOR *c;
+       EPG e;
+       PAGE *pg;
+       int curcopy, status;
+
+       /*
+        * If there are duplicates, move forward or backward to one.
+        * Otherwise, copy the key into the cursor area.
+        */
+       c = &t->bt_cursor;
+       F_CLR(c, CURS_AFTER | CURS_BEFORE | CURS_ACQUIRE);
+
+       curcopy = 0;
+       if (!F_ISSET(t, B_NODUPS)) {
+               /*
+                * We're going to have to do comparisons.  If we weren't
+                * provided a copy of the key, i.e. the user is deleting
+                * the current cursor position, get one.
+                */
+               if (key == NULL) {
+                       e.page = h;
+                       e.index = idx;
+                       if ((status = __bt_ret(t, &e,
+                           &c->key, &c->key, NULL, NULL, 1)) != RET_SUCCESS)
+                               return (status);
+                       curcopy = 1;
+                       key = &c->key;
+               }
+               /* Check previous key, if not at the beginning of the page. */
+               if (idx > 0) { 
+                       e.page = h;
+                       e.index = idx - 1;
+                       if (__bt_cmp(t, key, &e) == 0) {
+                               F_SET(c, CURS_BEFORE);
+                               goto dup2;
+                       }
+               }
+               /* Check next key, if not at the end of the page. */
+               if (idx < (unsigned)(NEXTINDEX(h) - 1)) {
+                       e.page = h;
+                       e.index = idx + 1;
+                       if (__bt_cmp(t, key, &e) == 0) {
+                               F_SET(c, CURS_AFTER);
+                               goto dup2;
+                       }
+               }
+               /* Check previous key if at the beginning of the page. */
+               if (idx == 0 && h->prevpg != P_INVALID) {
+                       if ((pg = mpool_get(t->bt_mp, h->prevpg, 0)) == NULL)
+                               return (RET_ERROR);
+                       e.page = pg;
+                       e.index = NEXTINDEX(pg) - 1;
+                       if (__bt_cmp(t, key, &e) == 0) {
+                               F_SET(c, CURS_BEFORE);
+                               goto dup1;
+                       }
+                       mpool_put(t->bt_mp, pg, 0);
+               }
+               /* Check next key if at the end of the page. */
+               if (idx == (unsigned)(NEXTINDEX(h) - 1) && h->nextpg != P_INVALID) {
+                       if ((pg = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL)
+                               return (RET_ERROR);
+                       e.page = pg;
+                       e.index = 0;
+                       if (__bt_cmp(t, key, &e) == 0) {
+                               F_SET(c, CURS_AFTER);
+dup1:                          mpool_put(t->bt_mp, pg, 0);
+dup2:                          c->pg.pgno = e.page->pgno;
+                               c->pg.index = e.index;
+                               return (RET_SUCCESS);
+                       }
+                       mpool_put(t->bt_mp, pg, 0);
+               }
+       }
+       e.page = h;
+       e.index = idx;
+       if (curcopy || (status =
+           __bt_ret(t, &e, &c->key, &c->key, NULL, NULL, 1)) == RET_SUCCESS) {
+               F_SET(c, CURS_ACQUIRE);
+               return (RET_SUCCESS);
+       }
+       return (status);
+}
+
+/*
+ * __bt_relink --
+ *     Link around a deleted page.
+ *
+ * Parameters:
+ *     t:      tree
+ *     h:      page to be deleted
+ */
+static int
+__bt_relink(BTREE *t, PAGE *h)
+{
+       PAGE *pg;
+
+       if (h->nextpg != P_INVALID) {
+               if ((pg = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL)
+                       return (RET_ERROR);
+               pg->prevpg = h->prevpg;
+               mpool_put(t->bt_mp, pg, MPOOL_DIRTY);
+       }
+       if (h->prevpg != P_INVALID) {
+               if ((pg = mpool_get(t->bt_mp, h->prevpg, 0)) == NULL)
+                       return (RET_ERROR);
+               pg->nextpg = h->nextpg;
+               mpool_put(t->bt_mp, pg, MPOOL_DIRTY);
+       }
+       return (0);
+}
diff --git a/lib/nbsd_libc/db/btree/bt_get.c b/lib/nbsd_libc/db/btree/bt_get.c
new file mode 100644 (file)
index 0000000..772210a
--- /dev/null
@@ -0,0 +1,104 @@
+/*     $NetBSD: bt_get.c,v 1.13 2008/09/11 12:58:00 joerg Exp $        */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_get.c,v 1.13 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stddef.h>
+#include <stdio.h>
+
+#include <db.h>
+#include "btree.h"
+
+/*
+ * __BT_GET -- Get a record from the btree.
+ *
+ * Parameters:
+ *     dbp:    pointer to access method
+ *     key:    key to find
+ *     data:   data to return
+ *     flag:   currently unused
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key not found.
+ */
+int
+__bt_get(const DB *dbp, const DBT *key, DBT *data, u_int flags)
+{
+       BTREE *t;
+       EPG *e;
+       int exact, status;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       /* Get currently doesn't take any flags. */
+       if (flags) {
+               errno = EINVAL;
+               return (RET_ERROR);
+       }
+
+       if ((e = __bt_search(t, key, &exact)) == NULL)
+               return (RET_ERROR);
+       if (!exact) {
+               mpool_put(t->bt_mp, e->page, 0);
+               return (RET_SPECIAL);
+       }
+
+       status = __bt_ret(t, e, NULL, NULL, data, &t->bt_rdata, 0);
+
+       /*
+        * If the user is doing concurrent access, we copied the
+        * key/data, toss the page.
+        */
+       if (F_ISSET(t, B_DB_LOCK))
+               mpool_put(t->bt_mp, e->page, 0);
+       else
+               t->bt_pinned = e->page;
+       return (status);
+}
diff --git a/lib/nbsd_libc/db/btree/bt_open.c b/lib/nbsd_libc/db/btree/bt_open.c
new file mode 100644 (file)
index 0000000..c5256d1
--- /dev/null
@@ -0,0 +1,456 @@
+/*     $NetBSD: bt_open.c,v 1.24 2008/09/11 12:58:00 joerg Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_open.c,v 1.24 2008/09/11 12:58:00 joerg Exp $");
+
+/*
+ * Implementation of btree access method for 4.4BSD.
+ *
+ * The design here was originally based on that of the btree access method
+ * used in the Postgres database system at UC Berkeley.  This implementation
+ * is wholly independent of the Postgres code.
+ */
+
+#include "namespace.h"
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <paths.h>
+
+#include <db.h>
+#include "btree.h"
+
+#ifdef DEBUG
+#undef MINPSIZE
+#define        MINPSIZE        128
+#endif
+
+static int byteorder(void);
+static int nroot(BTREE *);
+static int tmp(void);
+
+/*
+ * __BT_OPEN -- Open a btree.
+ *
+ * Creates and fills a DB struct, and calls the routine that actually
+ * opens the btree.
+ *
+ * Parameters:
+ *     fname:  filename (NULL for in-memory trees)
+ *     flags:  open flag bits
+ *     mode:   open permission bits
+ *     b:      BTREEINFO pointer
+ *
+ * Returns:
+ *     NULL on failure, pointer to DB on success.
+ *
+ */
+DB *
+__bt_open(const char *fname, int flags, mode_t mode, const BTREEINFO *openinfo,
+    int dflags)
+{
+       struct stat sb;
+       BTMETA m;
+       BTREE *t;
+       BTREEINFO b;
+       DB *dbp;
+       pgno_t ncache;
+       ssize_t nr;
+       size_t temp;
+       int machine_lorder;
+
+       t = NULL;
+
+       /*
+        * Intention is to make sure all of the user's selections are okay
+        * here and then use them without checking.  Can't be complete, since
+        * we don't know the right page size, lorder or flags until the backing
+        * file is opened.  Also, the file's page size can cause the cachesize
+        * to change.
+        */
+       machine_lorder = byteorder();
+       if (openinfo) {
+               b = *openinfo;
+
+               /* Flags: R_DUP. */
+               if (b.flags & ~(R_DUP))
+                       goto einval;
+
+               /*
+                * Page size must be indx_t aligned and >= MINPSIZE.  Default
+                * page size is set farther on, based on the underlying file
+                * transfer size.
+                */
+               if (b.psize &&
+                   (b.psize < MINPSIZE || b.psize > MAX_PAGE_OFFSET + 1 ||
+                   b.psize & (sizeof(indx_t) - 1)))
+                       goto einval;
+
+               /* Minimum number of keys per page; absolute minimum is 2. */
+               if (b.minkeypage) {
+                       if (b.minkeypage < 2)
+                               goto einval;
+               } else
+                       b.minkeypage = DEFMINKEYPAGE;
+
+               /* If no comparison, use default comparison and prefix. */
+               if (b.compare == NULL) {
+                       b.compare = __bt_defcmp;
+                       if (b.prefix == NULL)
+                               b.prefix = __bt_defpfx;
+               }
+
+               if (b.lorder == 0)
+                       b.lorder = machine_lorder;
+       } else {
+               b.compare = __bt_defcmp;
+               b.cachesize = 0;
+               b.flags = 0;
+               b.lorder = machine_lorder;
+               b.minkeypage = DEFMINKEYPAGE;
+               b.prefix = __bt_defpfx;
+               b.psize = 0;
+       }
+
+       /* Check for the ubiquitous PDP-11. */
+       if (b.lorder != BIG_ENDIAN && b.lorder != LITTLE_ENDIAN)
+               goto einval;
+
+       /* Allocate and initialize DB and BTREE structures. */
+       if ((t = (BTREE *)malloc(sizeof(BTREE))) == NULL)
+               goto err;
+       memset(t, 0, sizeof(BTREE));
+       t->bt_fd = -1;                  /* Don't close unopened fd on error. */
+       t->bt_lorder = b.lorder;
+       t->bt_order = NOT;
+       t->bt_cmp = b.compare;
+       t->bt_pfx = b.prefix;
+       t->bt_rfd = -1;
+
+       if ((t->bt_dbp = dbp = (DB *)malloc(sizeof(DB))) == NULL)
+               goto err;
+       memset(t->bt_dbp, 0, sizeof(DB));
+       if (t->bt_lorder != machine_lorder)
+               F_SET(t, B_NEEDSWAP);
+
+       dbp->type = DB_BTREE;
+       dbp->internal = t;
+       dbp->close = __bt_close;
+       dbp->del = __bt_delete;
+       dbp->fd = __bt_fd;
+       dbp->get = __bt_get;
+       dbp->put = __bt_put;
+       dbp->seq = __bt_seq;
+       dbp->sync = __bt_sync;
+
+       /*
+        * If no file name was supplied, this is an in-memory btree and we
+        * open a backing temporary file.  Otherwise, it's a disk-based tree.
+        */
+       if (fname) {
+               switch (flags & O_ACCMODE) {
+               case O_RDONLY:
+                       F_SET(t, B_RDONLY);
+                       break;
+               case O_RDWR:
+                       break;
+               case O_WRONLY:
+               default:
+                       goto einval;
+               }
+               
+               if ((t->bt_fd = open(fname, flags, mode)) == -1)
+                       goto err;
+               if (fcntl(t->bt_fd, F_SETFD, FD_CLOEXEC) == -1)
+                       goto err;
+       } else {
+               if ((flags & O_ACCMODE) != O_RDWR)
+                       goto einval;
+               if ((t->bt_fd = tmp()) == -1)
+                       goto err;
+               F_SET(t, B_INMEM);
+       }
+
+       if (fcntl(t->bt_fd, F_SETFD, FD_CLOEXEC) == -1)
+               goto err;
+
+       if (fstat(t->bt_fd, &sb))
+               goto err;
+       if (sb.st_size) {
+               if ((nr = read(t->bt_fd, &m, sizeof(BTMETA))) < 0)
+                       goto err;
+               if (nr != sizeof(BTMETA))
+                       goto eftype;
+
+               /*
+                * Read in the meta-data.  This can change the notion of what
+                * the lorder, page size and flags are, and, when the page size
+                * changes, the cachesize value can change too.  If the user
+                * specified the wrong byte order for an existing database, we
+                * don't bother to return an error, we just clear the NEEDSWAP
+                * bit.
+                */
+               if (m.magic == BTREEMAGIC)
+                       F_CLR(t, B_NEEDSWAP);
+               else {
+                       F_SET(t, B_NEEDSWAP);
+                       M_32_SWAP(m.magic);
+                       M_32_SWAP(m.version);
+                       M_32_SWAP(m.psize);
+                       M_32_SWAP(m.free);
+                       M_32_SWAP(m.nrecs);
+                       M_32_SWAP(m.flags);
+               }
+               if (m.magic != BTREEMAGIC || m.version != BTREEVERSION)
+                       goto eftype;
+               if (m.psize < MINPSIZE || m.psize > MAX_PAGE_OFFSET + 1 ||
+                   m.psize & (sizeof(indx_t) - 1))
+                       goto eftype;
+               if (m.flags & ~SAVEMETA)
+                       goto eftype;
+               b.psize = m.psize;
+               F_SET(t, m.flags);
+               t->bt_free = m.free;
+               t->bt_nrecs = m.nrecs;
+       } else {
+               /*
+                * Set the page size to the best value for I/O to this file.
+                * Don't overflow the page offset type.
+                */
+               if (b.psize == 0) {
+                       b.psize = sb.st_blksize;
+                       if (b.psize < MINPSIZE)
+                               b.psize = MINPSIZE;
+                       if (b.psize > MAX_PAGE_OFFSET + 1)
+                               b.psize = MAX_PAGE_OFFSET + 1;
+               }
+
+               /* Set flag if duplicates permitted. */
+               if (!(b.flags & R_DUP))
+                       F_SET(t, B_NODUPS);
+
+               t->bt_free = P_INVALID;
+               t->bt_nrecs = 0;
+               F_SET(t, B_METADIRTY);
+       }
+
+       t->bt_psize = b.psize;
+
+       /* Set the cache size; must be a multiple of the page size. */
+       if (b.cachesize && b.cachesize & (b.psize - 1))
+               b.cachesize += (~b.cachesize & (b.psize - 1)) + 1;
+       if (b.cachesize < b.psize * MINCACHE)
+               b.cachesize = b.psize * MINCACHE;
+
+       /* Calculate number of pages to cache. */
+       ncache = (b.cachesize + t->bt_psize - 1) / t->bt_psize;
+
+       /*
+        * The btree data structure requires that at least two keys can fit on
+        * a page, but other than that there's no fixed requirement.  The user
+        * specified a minimum number per page, and we translated that into the
+        * number of bytes a key/data pair can use before being placed on an
+        * overflow page.  This calculation includes the page header, the size
+        * of the index referencing the leaf item and the size of the leaf item
+        * structure.  Also, don't let the user specify a minkeypage such that
+        * a key/data pair won't fit even if both key and data are on overflow
+        * pages.
+        */
+       temp = (t->bt_psize - BTDATAOFF) / b.minkeypage -
+           (sizeof(indx_t) + NBLEAFDBT(0, 0));
+       _DBFIT(temp, indx_t);
+       t->bt_ovflsize = (indx_t)temp;
+       if (t->bt_ovflsize < NBLEAFDBT(NOVFLSIZE, NOVFLSIZE) + sizeof(indx_t))
+               t->bt_ovflsize =
+                   NBLEAFDBT(NOVFLSIZE, NOVFLSIZE) + sizeof(indx_t);
+
+       /* Initialize the buffer pool. */
+       if ((t->bt_mp =
+           mpool_open(NULL, t->bt_fd, t->bt_psize, ncache)) == NULL)
+               goto err;
+       if (!F_ISSET(t, B_INMEM))
+               mpool_filter(t->bt_mp, __bt_pgin, __bt_pgout, t);
+
+       /* Create a root page if new tree. */
+       if (nroot(t) == RET_ERROR)
+               goto err;
+
+       /* Global flags. */
+       if (dflags & DB_LOCK)
+               F_SET(t, B_DB_LOCK);
+       if (dflags & DB_SHMEM)
+               F_SET(t, B_DB_SHMEM);
+       if (dflags & DB_TXN)
+               F_SET(t, B_DB_TXN);
+
+       return (dbp);
+
+einval:        errno = EINVAL;
+       goto err;
+
+eftype:        errno = EFTYPE;
+       goto err;
+
+err:   if (t) {
+               if (t->bt_dbp)
+                       free(t->bt_dbp);
+               if (t->bt_fd != -1)
+                       (void)close(t->bt_fd);
+               free(t);
+       }
+       return (NULL);
+}
+
+/*
+ * NROOT -- Create the root of a new tree.
+ *
+ * Parameters:
+ *     t:      tree
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+static int
+nroot(BTREE *t)
+{
+       PAGE *meta, *root;
+       pgno_t npg;
+
+       if ((meta = mpool_get(t->bt_mp, 0, 0)) != NULL) {
+               mpool_put(t->bt_mp, meta, 0);
+               return (RET_SUCCESS);
+       }
+       if (errno != EINVAL)            /* It's OK to not exist. */
+               return (RET_ERROR);
+       errno = 0;
+
+       if ((meta = mpool_new(t->bt_mp, &npg)) == NULL)
+               return (RET_ERROR);
+
+       if ((root = mpool_new(t->bt_mp, &npg)) == NULL)
+               return (RET_ERROR);
+
+       if (npg != P_ROOT)
+               return (RET_ERROR);
+       root->pgno = npg;
+       root->prevpg = root->nextpg = P_INVALID;
+       root->lower = BTDATAOFF;
+       root->upper = t->bt_psize;
+       root->flags = P_BLEAF;
+       memset(meta, 0, t->bt_psize);
+       mpool_put(t->bt_mp, meta, MPOOL_DIRTY);
+       mpool_put(t->bt_mp, root, MPOOL_DIRTY);
+       return (RET_SUCCESS);
+}
+
+static int
+tmp(void)
+{
+       sigset_t set, oset;
+       size_t len;
+       int fd;
+       char *envtmp;
+       char path[PATH_MAX];
+
+       if (issetugid())
+               envtmp = NULL;
+       else
+               envtmp = getenv("TMPDIR");
+
+       len = snprintf(path,
+           sizeof(path), "%s/bt.XXXXXX", envtmp ? envtmp : _PATH_TMP);
+       if (len >= sizeof(path))
+               return -1;
+       
+       (void)sigfillset(&set);
+       (void)sigprocmask(SIG_BLOCK, &set, &oset);
+       if ((fd = mkstemp(path)) != -1) {
+               (void)unlink(path);
+               (void)fcntl(fd, F_SETFD, FD_CLOEXEC);
+       }
+       (void)sigprocmask(SIG_SETMASK, &oset, NULL);
+       return(fd);
+}
+
+static int
+byteorder(void)
+{
+       uint32_t x;
+       uint8_t *p;
+
+       x = 0x01020304;
+       p = (uint8_t *)(void *)&x;
+       switch (*p) {
+       case 1:
+               return (BIG_ENDIAN);
+       case 4:
+               return (LITTLE_ENDIAN);
+       default:
+               return (0);
+       }
+}
+
+int
+__bt_fd(const DB *dbp)
+{
+       BTREE *t;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       /* In-memory database can't have a file descriptor. */
+       if (F_ISSET(t, B_INMEM)) {
+               errno = ENOENT;
+               return (-1);
+       }
+       return (t->bt_fd);
+}
diff --git a/lib/nbsd_libc/db/btree/bt_overflow.c b/lib/nbsd_libc/db/btree/bt_overflow.c
new file mode 100644 (file)
index 0000000..9654804
--- /dev/null
@@ -0,0 +1,232 @@
+/*     $NetBSD: bt_overflow.c,v 1.16 2008/09/11 12:58:00 joerg Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_overflow.c,v 1.16 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/param.h>
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <db.h>
+#include "btree.h"
+
+/*
+ * Big key/data code.
+ *
+ * Big key and data entries are stored on linked lists of pages.  The initial
+ * reference is byte string stored with the key or data and is the page number
+ * and size.  The actual record is stored in a chain of pages linked by the
+ * nextpg field of the PAGE header.
+ *
+ * The first page of the chain has a special property.  If the record is used
+ * by an internal page, it cannot be deleted and the P_PRESERVE bit will be set
+ * in the header.
+ *
+ * XXX
+ * A single DBT is written to each chain, so a lot of space on the last page
+ * is wasted.  This is a fairly major bug for some data sets.
+ */
+
+/*
+ * __OVFL_GET -- Get an overflow key/data item.
+ *
+ * Parameters:
+ *     t:      tree
+ *     p:      pointer to { pgno_t, uint32_t }
+ *     buf:    storage address
+ *     bufsz:  storage size
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+int
+__ovfl_get(BTREE *t, void *p, size_t *ssz, void **buf, size_t *bufsz)
+{
+       PAGE *h;
+       pgno_t pg;
+       uint32_t sz, nb, plen;
+       size_t temp;
+
+       memmove(&pg, p, sizeof(pgno_t));
+       memmove(&sz, (char *)p + sizeof(pgno_t), sizeof(uint32_t));
+       *ssz = sz;
+
+#ifdef DEBUG
+       if (pg == P_INVALID || sz == 0)
+               abort();
+#endif
+       /* Make the buffer bigger as necessary. */
+       if (*bufsz < sz) {
+               *buf = (char *)(*buf == NULL ? malloc(sz) : realloc(*buf, sz));
+               if (*buf == NULL)
+                       return (RET_ERROR);
+               *bufsz = sz;
+       }
+
+       /*
+        * Step through the linked list of pages, copying the data on each one
+        * into the buffer.  Never copy more than the data's length.
+        */
+       temp = t->bt_psize - BTDATAOFF;
+       _DBFIT(temp, uint32_t);
+       plen = (uint32_t)temp;
+       for (p = *buf;; p = (char *)p + nb, pg = h->nextpg) {
+               if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
+                       return (RET_ERROR);
+
+               nb = MIN(sz, plen);
+               memmove(p, (char *)(void *)h + BTDATAOFF, nb);
+               mpool_put(t->bt_mp, h, 0);
+
+               if ((sz -= nb) == 0)
+                       break;
+       }
+       return (RET_SUCCESS);
+}
+
+/*
+ * __OVFL_PUT -- Store an overflow key/data item.
+ *
+ * Parameters:
+ *     t:      tree
+ *     data:   DBT to store
+ *     pgno:   storage page number
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+int
+__ovfl_put(BTREE *t, const DBT *dbt, pgno_t *pg)
+{
+       PAGE *h, *last;
+       void *p;
+       pgno_t npg;
+       uint32_t sz, nb, plen;
+       size_t temp;
+
+       /*
+        * Allocate pages and copy the key/data record into them.  Store the
+        * number of the first page in the chain.
+        */
+       temp = t->bt_psize - BTDATAOFF;
+       _DBFIT(temp, uint32_t);
+       plen = (uint32_t)temp;
+       last = NULL;
+       p = dbt->data;
+       temp = dbt->size;
+       _DBFIT(temp, uint32_t);
+       sz = temp;
+       for (;; p = (char *)p + plen, last = h) {
+               if ((h = __bt_new(t, &npg)) == NULL)
+                       return (RET_ERROR);
+
+               h->pgno = npg;
+               h->nextpg = h->prevpg = P_INVALID;
+               h->flags = P_OVERFLOW;
+               h->lower = h->upper = 0;
+
+               nb = MIN(sz, plen);
+               (void)memmove((char *)(void *)h + BTDATAOFF, p, (size_t)nb);
+
+               if (last) {
+                       last->nextpg = h->pgno;
+                       mpool_put(t->bt_mp, last, MPOOL_DIRTY);
+               } else
+                       *pg = h->pgno;
+
+               if ((sz -= nb) == 0) {
+                       mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+                       break;
+               }
+       }
+       return (RET_SUCCESS);
+}
+
+/*
+ * __OVFL_DELETE -- Delete an overflow chain.
+ *
+ * Parameters:
+ *     t:      tree
+ *     p:      pointer to { pgno_t, uint32_t }
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+int
+__ovfl_delete(BTREE *t, void *p)
+{
+       PAGE *h;
+       pgno_t pg;
+       uint32_t sz, plen;
+       size_t temp;
+
+       (void)memmove(&pg, p, sizeof(pgno_t));
+       (void)memmove(&sz, (char *)p + sizeof(pgno_t), sizeof(uint32_t));
+
+#ifdef DEBUG
+       if (pg == P_INVALID || sz == 0)
+               abort();
+#endif
+       if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
+               return (RET_ERROR);
+
+       /* Don't delete chains used by internal pages. */
+       if (h->flags & P_PRESERVE) {
+               mpool_put(t->bt_mp, h, 0);
+               return (RET_SUCCESS);
+       }
+
+       /* Step through the chain, calling the free routine for each page. */
+       temp = t->bt_psize - BTDATAOFF;
+       _DBFIT(temp, uint32_t);
+       plen = (uint32_t)temp;
+       for (;; sz -= plen) {
+               pg = h->nextpg;
+               __bt_free(t, h);
+               if (sz <= plen)
+                       break;
+               if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
+                       return (RET_ERROR);
+       }
+       return (RET_SUCCESS);
+}
diff --git a/lib/nbsd_libc/db/btree/bt_page.c b/lib/nbsd_libc/db/btree/bt_page.c
new file mode 100644 (file)
index 0000000..0db4aeb
--- /dev/null
@@ -0,0 +1,99 @@
+/*     $NetBSD: bt_page.c,v 1.13 2008/09/11 12:58:00 joerg Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_page.c,v 1.13 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <stdio.h>
+
+#include <db.h>
+#include "btree.h"
+
+/*
+ * __bt_free --
+ *     Put a page on the freelist.
+ *
+ * Parameters:
+ *     t:      tree
+ *     h:      page to free
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ *
+ * Side-effect:
+ *     mpool_put's the page.
+ */
+int
+__bt_free(BTREE *t, PAGE *h)
+{
+       /* Insert the page at the head of the free list. */
+       h->prevpg = P_INVALID;
+       h->nextpg = t->bt_free;
+       t->bt_free = h->pgno;
+       F_SET(t, B_METADIRTY);
+
+       /* Make sure the page gets written back. */
+       return (mpool_put(t->bt_mp, h, MPOOL_DIRTY));
+}
+
+/*
+ * __bt_new --
+ *     Get a new page, preferably from the freelist.
+ *
+ * Parameters:
+ *     t:      tree
+ *     npg:    storage for page number.
+ *
+ * Returns:
+ *     Pointer to a page, NULL on error.
+ */
+PAGE *
+__bt_new(BTREE *t, pgno_t *npg)
+{
+       PAGE *h;
+
+       if (t->bt_free != P_INVALID &&
+           (h = mpool_get(t->bt_mp, t->bt_free, 0)) != NULL) {
+               *npg = t->bt_free;
+               t->bt_free = h->nextpg;
+               F_SET(t, B_METADIRTY);
+               return (h);
+       }
+       return (mpool_new(t->bt_mp, npg));
+}
diff --git a/lib/nbsd_libc/db/btree/bt_put.c b/lib/nbsd_libc/db/btree/bt_put.c
new file mode 100644 (file)
index 0000000..37630b8
--- /dev/null
@@ -0,0 +1,319 @@
+/*     $NetBSD: bt_put.c,v 1.19 2009/02/12 06:40:14 lukem Exp $        */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_put.c,v 1.19 2009/02/12 06:40:14 lukem Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <db.h>
+#include "btree.h"
+
+static EPG *bt_fast(BTREE *, const DBT *, const DBT *, int *);
+
+/*
+ * __BT_PUT -- Add a btree item to the tree.
+ *
+ * Parameters:
+ *     dbp:    pointer to access method
+ *     key:    key
+ *     data:   data
+ *     flag:   R_NOOVERWRITE
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key is already in the
+ *     tree and R_NOOVERWRITE specified.
+ */
+int
+__bt_put(const DB *dbp, DBT *key, const DBT *data, u_int flags)
+{
+       BTREE *t;
+       DBT tkey, tdata;
+       EPG *e = NULL; /* pacify gcc */
+       PAGE *h;
+       indx_t idx, nxtindex;
+       pgno_t pg;
+       uint32_t nbytes, temp;
+       int dflags, exact, status;
+       char *dest, db[NOVFLSIZE], kb[NOVFLSIZE];
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       /* Check for change to a read-only tree. */
+       if (F_ISSET(t, B_RDONLY)) {
+               errno = EPERM;
+               return (RET_ERROR);
+       }
+
+       switch (flags) {
+       case 0:
+       case R_NOOVERWRITE:
+               break;
+       case R_CURSOR:
+               /*
+                * If flags is R_CURSOR, put the cursor.  Must already
+                * have started a scan and not have already deleted it.
+                */
+               if (F_ISSET(&t->bt_cursor, CURS_INIT) &&
+                   !F_ISSET(&t->bt_cursor,
+                       CURS_ACQUIRE | CURS_AFTER | CURS_BEFORE))
+                       break;
+               /* FALLTHROUGH */
+       default:
+               errno = EINVAL;
+               return (RET_ERROR);
+       }
+
+       /*
+        * If the key/data pair won't fit on a page, store it on overflow
+        * pages.  Only put the key on the overflow page if the pair are
+        * still too big after moving the data to an overflow page.
+        *
+        * XXX
+        * If the insert fails later on, the overflow pages aren't recovered.
+        */
+       dflags = 0;
+       if (key->size + data->size > t->bt_ovflsize) {
+               if (key->size > t->bt_ovflsize) {
+storekey:              if (__ovfl_put(t, key, &pg) == RET_ERROR)
+                               return (RET_ERROR);
+                       tkey.data = kb;
+                       tkey.size = NOVFLSIZE;
+                       memmove(kb, &pg, sizeof(pgno_t));
+                       memmove(kb + sizeof(pgno_t),
+                           &key->size, sizeof(uint32_t));
+                       dflags |= P_BIGKEY;
+                       key = &tkey;
+               }
+               if (key->size + data->size > t->bt_ovflsize) {
+                       if (__ovfl_put(t, data, &pg) == RET_ERROR)
+                               return (RET_ERROR);
+                       tdata.data = db;
+                       tdata.size = NOVFLSIZE;
+                       memmove(db, &pg, sizeof(pgno_t));
+                       _DBFIT(data->size, uint32_t);
+                       temp = (uint32_t)data->size;
+                       (void)memmove(db + sizeof(pgno_t),
+                           &temp, sizeof(uint32_t));
+                       dflags |= P_BIGDATA;
+                       data = &tdata;
+               }
+               if (key->size + data->size > t->bt_ovflsize)
+                       goto storekey;
+       }
+
+       /* Replace the cursor. */
+       if (flags == R_CURSOR) {
+               if ((h = mpool_get(t->bt_mp, t->bt_cursor.pg.pgno, 0)) == NULL)
+                       return (RET_ERROR);
+               idx = t->bt_cursor.pg.index;
+               goto delete;
+       }
+
+       /*
+        * Find the key to delete, or, the location at which to insert.
+        * Bt_fast and __bt_search both pin the returned page.
+        */
+       if (t->bt_order == NOT || (e = bt_fast(t, key, data, &exact)) == NULL)
+               if ((e = __bt_search(t, key, &exact)) == NULL)
+                       return (RET_ERROR);
+       h = e->page;
+       idx = e->index;
+
+       /*
+        * Add the key/data pair to the tree.  If an identical key is already
+        * in the tree, and R_NOOVERWRITE is set, an error is returned.  If
+        * R_NOOVERWRITE is not set, the key is either added (if duplicates are
+        * permitted) or an error is returned.
+        */
+       switch (flags) {
+       case R_NOOVERWRITE:
+               if (!exact)
+                       break;
+               mpool_put(t->bt_mp, h, 0);
+               return (RET_SPECIAL);
+       default:
+               if (!exact || !F_ISSET(t, B_NODUPS))
+                       break;
+               /*
+                * !!!
+                * Note, the delete may empty the page, so we need to put a
+                * new entry into the page immediately.
+                */
+delete:                if (__bt_dleaf(t, key, h, (u_int)idx) == RET_ERROR) {
+                       mpool_put(t->bt_mp, h, 0);
+                       return (RET_ERROR);
+               }
+               break;
+       }
+
+       /*
+        * If not enough room, or the user has put a ceiling on the number of
+        * keys permitted in the page, split the page.  The split code will
+        * insert the key and data and unpin the current page.  If inserting
+        * into the offset array, shift the pointers up.
+        */
+       nbytes = NBLEAFDBT(key->size, data->size);
+       if ((uint32_t)h->upper - (uint32_t)h->lower < nbytes + sizeof(indx_t)) {
+               if ((status = __bt_split(t, h, key,
+                   data, dflags, nbytes, (u_int)idx)) != RET_SUCCESS)
+                       return (status);
+               goto success;
+       }
+
+       if (idx < (nxtindex = NEXTINDEX(h)))
+               memmove(h->linp + idx + 1, h->linp + idx,
+                   (nxtindex - idx) * sizeof(indx_t));
+       h->lower += sizeof(indx_t);
+
+       h->linp[idx] = h->upper -= nbytes;
+       dest = (char *)(void *)h + h->upper;
+       WR_BLEAF(dest, key, data, dflags);
+
+       /* If the cursor is on this page, adjust it as necessary. */
+       if (F_ISSET(&t->bt_cursor, CURS_INIT) &&
+           !F_ISSET(&t->bt_cursor, CURS_ACQUIRE) &&
+           t->bt_cursor.pg.pgno == h->pgno && t->bt_cursor.pg.index >= idx)
+               ++t->bt_cursor.pg.index;
+
+       if (t->bt_order == NOT) {
+               if (h->nextpg == P_INVALID) {
+                       if (idx == NEXTINDEX(h) - 1) {
+                               t->bt_order = FORWARD;
+                               t->bt_last.index = idx;
+                               t->bt_last.pgno = h->pgno;
+                       }
+               } else if (h->prevpg == P_INVALID) {
+                       if (idx == 0) {
+                               t->bt_order = BACK;
+                               t->bt_last.index = 0;
+                               t->bt_last.pgno = h->pgno;
+                       }
+               }
+       }
+
+       mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+
+success:
+       if (flags == R_SETCURSOR)
+               __bt_setcur(t, e->page->pgno, (u_int)e->index);
+
+       F_SET(t, B_MODIFIED);
+       return (RET_SUCCESS);
+}
+
+#ifdef STATISTICS
+unsigned long bt_cache_hit, bt_cache_miss;
+#endif
+
+/*
+ * BT_FAST -- Do a quick check for sorted data.
+ *
+ * Parameters:
+ *     t:      tree
+ *     key:    key to insert
+ *
+ * Returns:
+ *     EPG for new record or NULL if not found.
+ */
+static EPG *
+bt_fast(BTREE *t, const DBT *key, const DBT *data, int *exactp)
+{
+       PAGE *h;
+       uint32_t nbytes;
+       int cmp;
+
+       if ((h = mpool_get(t->bt_mp, t->bt_last.pgno, 0)) == NULL) {
+               t->bt_order = NOT;
+               return (NULL);
+       }
+       t->bt_cur.page = h;
+       t->bt_cur.index = t->bt_last.index;
+
+       /*
+        * If won't fit in this page or have too many keys in this page,
+        * have to search to get split stack.
+        */
+       nbytes = NBLEAFDBT(key->size, data->size);
+       if ((uint32_t)h->upper - (uint32_t)h->lower < nbytes + sizeof(indx_t))
+               goto miss;
+
+       if (t->bt_order == FORWARD) {
+               if (t->bt_cur.page->nextpg != P_INVALID)
+                       goto miss;
+               if (t->bt_cur.index != NEXTINDEX(h) - 1)
+                       goto miss;
+               if ((cmp = __bt_cmp(t, key, &t->bt_cur)) < 0)
+                       goto miss;
+               t->bt_last.index = cmp ? ++t->bt_cur.index : t->bt_cur.index;
+       } else {
+               if (t->bt_cur.page->prevpg != P_INVALID)
+                       goto miss;
+               if (t->bt_cur.index != 0)
+                       goto miss;
+               if ((cmp = __bt_cmp(t, key, &t->bt_cur)) > 0)
+                       goto miss;
+               t->bt_last.index = 0;
+       }
+       *exactp = cmp == 0;
+#ifdef STATISTICS
+       ++bt_cache_hit;
+#endif
+       return (&t->bt_cur);
+
+miss:
+#ifdef STATISTICS
+       ++bt_cache_miss;
+#endif
+       t->bt_order = NOT;
+       mpool_put(t->bt_mp, h, 0);
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/db/btree/bt_search.c b/lib/nbsd_libc/db/btree/bt_search.c
new file mode 100644 (file)
index 0000000..00da7c9
--- /dev/null
@@ -0,0 +1,205 @@
+/*     $NetBSD: bt_search.c,v 1.17 2008/09/11 12:58:00 joerg Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_search.c,v 1.17 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <stdio.h>
+
+#include <db.h>
+#include "btree.h"
+
+static int __bt_snext(BTREE *, PAGE *, const DBT *, int *);
+static int __bt_sprev(BTREE *, PAGE *, const DBT *, int *);
+
+/*
+ * __bt_search --
+ *     Search a btree for a key.
+ *
+ * Parameters:
+ *     t:      tree to search
+ *     key:    key to find
+ *     exactp: pointer to exact match flag
+ *
+ * Returns:
+ *     The EPG for matching record, if any, or the EPG for the location
+ *     of the key, if it were inserted into the tree, is entered into
+ *     the bt_cur field of the tree.  A pointer to the field is returned.
+ */
+EPG *
+__bt_search(BTREE *t, const DBT *key, int *exactp)
+{
+       PAGE *h;
+       indx_t base, idx, lim;
+       pgno_t pg;
+       int cmp;
+
+       BT_CLR(t);
+       for (pg = P_ROOT;;) {
+               if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
+                       return (NULL);
+
+               /* Do a binary search on the current page. */
+               t->bt_cur.page = h;
+               for (base = 0, lim = NEXTINDEX(h); lim; lim >>= 1) {
+                       t->bt_cur.index = idx = base + ((uint32_t)lim >> 1);
+                       if ((cmp = __bt_cmp(t, key, &t->bt_cur)) == 0) {
+                               if (h->flags & P_BLEAF) {
+                                       *exactp = 1;
+                                       return (&t->bt_cur);
+                               }
+                               goto next;
+                       }
+                       if (cmp > 0) {
+                               base = idx + 1;
+                               --lim;
+                       }
+               }
+
+               /*
+                * If it's a leaf page, we're almost done.  If no duplicates
+                * are allowed, or we have an exact match, we're done.  Else,
+                * it's possible that there were matching keys on this page,
+                * which later deleted, and we're on a page with no matches
+                * while there are matches on other pages.  If at the start or
+                * end of a page, check the adjacent page.
+                */
+               if (h->flags & P_BLEAF) {
+                       if (!F_ISSET(t, B_NODUPS)) {
+                               if (base == 0 &&
+                                   h->prevpg != P_INVALID &&
+                                   __bt_sprev(t, h, key, exactp))
+                                       return (&t->bt_cur);
+                               if (base == NEXTINDEX(h) &&
+                                   h->nextpg != P_INVALID &&
+                                   __bt_snext(t, h, key, exactp))
+                                       return (&t->bt_cur);
+                       }
+                       *exactp = 0;
+                       t->bt_cur.index = base;
+                       return (&t->bt_cur);
+               }
+
+               /*
+                * No match found.  Base is the smallest index greater than
+                * key and may be zero or a last + 1 index.  If it's non-zero,
+                * decrement by one, and record the internal page which should
+                * be a parent page for the key.  If a split later occurs, the
+                * inserted page will be to the right of the saved page.
+                */
+               idx = base ? base - 1 : base;
+
+next:          BT_PUSH(t, h->pgno, idx);
+               pg = GETBINTERNAL(h, idx)->pgno;
+               mpool_put(t->bt_mp, h, 0);
+       }
+}
+
+/*
+ * __bt_snext --
+ *     Check for an exact match after the key.
+ *
+ * Parameters:
+ *     t:      tree
+ *     h:      current page
+ *     key:    key
+ *     exactp: pointer to exact match flag
+ *
+ * Returns:
+ *     If an exact match found.
+ */
+static int
+__bt_snext(BTREE *t, PAGE *h, const DBT *key, int *exactp)
+{
+       EPG e;
+
+       /*
+        * Get the next page.  The key is either an exact
+        * match, or not as good as the one we already have.
+        */
+       if ((e.page = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL)
+               return (0);
+       e.index = 0;
+       if (__bt_cmp(t, key, &e) == 0) {
+               mpool_put(t->bt_mp, h, 0);
+               t->bt_cur = e;
+               *exactp = 1;
+               return (1);
+       }
+       mpool_put(t->bt_mp, e.page, 0);
+       return (0);
+}
+
+/*
+ * __bt_sprev --
+ *     Check for an exact match before the key.
+ *
+ * Parameters:
+ *     t:      tree
+ *     h:      current page
+ *     key:    key
+ *     exactp: pointer to exact match flag
+ *
+ * Returns:
+ *     If an exact match found.
+ */
+static int
+__bt_sprev(BTREE *t, PAGE *h, const DBT *key, int *exactp)
+{
+       EPG e;
+
+       /*
+        * Get the previous page.  The key is either an exact
+        * match, or not as good as the one we already have.
+        */
+       if ((e.page = mpool_get(t->bt_mp, h->prevpg, 0)) == NULL)
+               return (0);
+       e.index = NEXTINDEX(e.page) - 1;
+       if (__bt_cmp(t, key, &e) == 0) {
+               mpool_put(t->bt_mp, h, 0);
+               t->bt_cur = e;
+               *exactp = 1;
+               return (1);
+       }
+       mpool_put(t->bt_mp, e.page, 0);
+       return (0);
+}
diff --git a/lib/nbsd_libc/db/btree/bt_seq.c b/lib/nbsd_libc/db/btree/bt_seq.c
new file mode 100644 (file)
index 0000000..58f25a0
--- /dev/null
@@ -0,0 +1,442 @@
+/*     $NetBSD: bt_seq.c,v 1.17 2008/09/11 12:58:00 joerg Exp $        */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_seq.c,v 1.17 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <db.h>
+#include "btree.h"
+
+static int __bt_first(BTREE *, const DBT *, EPG *, int *);
+static int __bt_seqadv(BTREE *, EPG *, int);
+static int __bt_seqset(BTREE *, EPG *, DBT *, int);
+
+/*
+ * Sequential scan support.
+ *
+ * The tree can be scanned sequentially, starting from either end of the
+ * tree or from any specific key.  A scan request before any scanning is
+ * done is initialized as starting from the least node.
+ */
+
+/*
+ * __bt_seq --
+ *     Btree sequential scan interface.
+ *
+ * Parameters:
+ *     dbp:    pointer to access method
+ *     key:    key for positioning and return value
+ *     data:   data return value
+ *     flags:  R_CURSOR, R_FIRST, R_LAST, R_NEXT, R_PREV.
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS or RET_SPECIAL if there's no next key.
+ */
+int
+__bt_seq(const DB *dbp, DBT *key, DBT *data, u_int flags)
+{
+       BTREE *t;
+       EPG e;
+       int status;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       /*
+        * If scan unitialized as yet, or starting at a specific record, set
+        * the scan to a specific key.  Both __bt_seqset and __bt_seqadv pin
+        * the page the cursor references if they're successful.
+        */
+       switch (flags) {
+       case R_NEXT:
+       case R_PREV:
+               if (F_ISSET(&t->bt_cursor, CURS_INIT)) {
+                       status = __bt_seqadv(t, &e, (int)flags);
+                       break;
+               }
+               /* FALLTHROUGH */
+       case R_FIRST:
+       case R_LAST:
+       case R_CURSOR:
+               status = __bt_seqset(t, &e, key, (int)flags);
+               break;
+       default:
+               errno = EINVAL;
+               return (RET_ERROR);
+       }
+
+       if (status == RET_SUCCESS) {
+               __bt_setcur(t, e.page->pgno, (u_int)e.index);
+
+               status =
+                   __bt_ret(t, &e, key, &t->bt_rkey, data, &t->bt_rdata, 0);
+
+               /*
+                * If the user is doing concurrent access, we copied the
+                * key/data, toss the page.
+                */
+               if (F_ISSET(t, B_DB_LOCK))
+                       mpool_put(t->bt_mp, e.page, 0);
+               else
+                       t->bt_pinned = e.page;
+       }
+       return (status);
+}
+
+/*
+ * __bt_seqset --
+ *     Set the sequential scan to a specific key.
+ *
+ * Parameters:
+ *     t:      tree
+ *     ep:     storage for returned key
+ *     key:    key for initial scan position
+ *     flags:  R_CURSOR, R_FIRST, R_LAST, R_NEXT, R_PREV
+ *
+ * Side effects:
+ *     Pins the page the cursor references.
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS or RET_SPECIAL if there's no next key.
+ */
+static int
+__bt_seqset(BTREE *t, EPG *ep, DBT *key, int flags)
+{
+       PAGE *h;
+       pgno_t pg;
+       int exact;
+
+       /*
+        * Find the first, last or specific key in the tree and point the
+        * cursor at it.  The cursor may not be moved until a new key has
+        * been found.
+        */
+       switch (flags) {
+       case R_CURSOR:                          /* Keyed scan. */
+               /*
+                * Find the first instance of the key or the smallest key
+                * which is greater than or equal to the specified key.
+                */
+               if (key->data == NULL || key->size == 0) {
+                       errno = EINVAL;
+                       return (RET_ERROR);
+               }
+               return (__bt_first(t, key, ep, &exact));
+       case R_FIRST:                           /* First record. */
+       case R_NEXT:
+               /* Walk down the left-hand side of the tree. */
+               for (pg = P_ROOT;;) {
+                       if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
+                               return (RET_ERROR);
+
+                       /* Check for an empty tree. */
+                       if (NEXTINDEX(h) == 0) {
+                               mpool_put(t->bt_mp, h, 0);
+                               return (RET_SPECIAL);
+                       }
+
+                       if (h->flags & (P_BLEAF | P_RLEAF))
+                               break;
+                       pg = GETBINTERNAL(h, 0)->pgno;
+                       mpool_put(t->bt_mp, h, 0);
+               }
+               ep->page = h;
+               ep->index = 0;
+               break;
+       case R_LAST:                            /* Last record. */
+       case R_PREV:
+               /* Walk down the right-hand side of the tree. */
+               for (pg = P_ROOT;;) {
+                       if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
+                               return (RET_ERROR);
+
+                       /* Check for an empty tree. */
+                       if (NEXTINDEX(h) == 0) {
+                               mpool_put(t->bt_mp, h, 0);
+                               return (RET_SPECIAL);
+                       }
+
+                       if (h->flags & (P_BLEAF | P_RLEAF))
+                               break;
+                       pg = GETBINTERNAL(h, NEXTINDEX(h) - 1)->pgno;
+                       mpool_put(t->bt_mp, h, 0);
+               }
+
+               ep->page = h;
+               ep->index = NEXTINDEX(h) - 1;
+               break;
+       }
+       return (RET_SUCCESS);
+}
+
+/*
+ * __bt_seqadvance --
+ *     Advance the sequential scan.
+ *
+ * Parameters:
+ *     t:      tree
+ *     flags:  R_NEXT, R_PREV
+ *
+ * Side effects:
+ *     Pins the page the new key/data record is on.
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS or RET_SPECIAL if there's no next key.
+ */
+static int
+__bt_seqadv(BTREE *t, EPG *ep, int flags)
+{
+       CURSOR *c;
+       PAGE *h;
+       indx_t idx = 0; /* pacify gcc */
+       pgno_t pg;
+       int exact;
+
+       /*
+        * There are a couple of states that we can be in.  The cursor has
+        * been initialized by the time we get here, but that's all we know.
+        */
+       c = &t->bt_cursor;
+
+       /*
+        * The cursor was deleted where there weren't any duplicate records,
+        * so the key was saved.  Find out where that key would go in the
+        * current tree.  It doesn't matter if the returned key is an exact
+        * match or not -- if it's an exact match, the record was added after
+        * the delete so we can just return it.  If not, as long as there's
+        * a record there, return it.
+        */
+       if (F_ISSET(c, CURS_ACQUIRE))
+               return (__bt_first(t, &c->key, ep, &exact));
+
+       /* Get the page referenced by the cursor. */
+       if ((h = mpool_get(t->bt_mp, c->pg.pgno, 0)) == NULL)
+               return (RET_ERROR);
+
+       /*
+        * Find the next/previous record in the tree and point the cursor at
+        * it.  The cursor may not be moved until a new key has been found.
+        */
+       switch (flags) {
+       case R_NEXT:                    /* Next record. */
+               /*
+                * The cursor was deleted in duplicate records, and moved
+                * forward to a record that has yet to be returned.  Clear
+                * that flag, and return the record.
+                */
+               if (F_ISSET(c, CURS_AFTER))
+                       goto usecurrent;
+               idx = c->pg.index;
+               if (++idx == NEXTINDEX(h)) {
+                       pg = h->nextpg;
+                       mpool_put(t->bt_mp, h, 0);
+                       if (pg == P_INVALID)
+                               return (RET_SPECIAL);
+                       if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
+                               return (RET_ERROR);
+                       idx = 0;
+               }
+               break;
+       case R_PREV:                    /* Previous record. */
+               /*
+                * The cursor was deleted in duplicate records, and moved
+                * backward to a record that has yet to be returned.  Clear
+                * that flag, and return the record.
+                */
+               if (F_ISSET(c, CURS_BEFORE)) {
+usecurrent:            F_CLR(c, CURS_AFTER | CURS_BEFORE);
+                       ep->page = h;
+                       ep->index = c->pg.index;
+                       return (RET_SUCCESS);
+               }
+               idx = c->pg.index;
+               if (idx == 0) {
+                       pg = h->prevpg;
+                       mpool_put(t->bt_mp, h, 0);
+                       if (pg == P_INVALID)
+                               return (RET_SPECIAL);
+                       if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
+                               return (RET_ERROR);
+                       idx = NEXTINDEX(h) - 1;
+               } else
+                       --idx;
+               break;
+       }
+
+       ep->page = h;
+       ep->index = idx;
+       return (RET_SUCCESS);
+}
+
+/*
+ * __bt_first --
+ *     Find the first entry.
+ *
+ * Parameters:
+ *     t:      the tree
+ *    key:     the key
+ *  erval:     return EPG
+ * exactp:     pointer to exact match flag
+ *
+ * Returns:
+ *     The first entry in the tree greater than or equal to key,
+ *     or RET_SPECIAL if no such key exists.
+ */
+static int
+__bt_first(BTREE *t, const DBT *key, EPG *erval, int *exactp)
+{
+       PAGE *h;
+       EPG *ep, save;
+       pgno_t pg;
+
+       /*
+        * Find any matching record; __bt_search pins the page.
+        *
+        * If it's an exact match and duplicates are possible, walk backwards
+        * in the tree until we find the first one.  Otherwise, make sure it's
+        * a valid key (__bt_search may return an index just past the end of a
+        * page) and return it.
+        */
+       if ((ep = __bt_search(t, key, exactp)) == NULL)
+               return (0);
+       if (*exactp) {
+               if (F_ISSET(t, B_NODUPS)) {
+                       *erval = *ep;
+                       return (RET_SUCCESS);
+               }
+                       
+               /*
+                * Walk backwards, as long as the entry matches and there are
+                * keys left in the tree.  Save a copy of each match in case
+                * we go too far.
+                */
+               save = *ep;
+               h = ep->page;
+               do {
+                       if (save.page->pgno != ep->page->pgno) {
+                               mpool_put(t->bt_mp, save.page, 0);
+                               save = *ep;
+                       } else
+                               save.index = ep->index;
+
+                       /*
+                        * Don't unpin the page the last (or original) match
+                        * was on, but make sure it's unpinned if an error
+                        * occurs.
+                        */
+                       if (ep->index == 0) {
+                               if (h->prevpg == P_INVALID)
+                                       break;
+                               if (h->pgno != save.page->pgno)
+                                       mpool_put(t->bt_mp, h, 0);
+                               if ((h = mpool_get(t->bt_mp,
+                                   h->prevpg, 0)) == NULL)
+                                       return (RET_ERROR);
+                               ep->page = h;
+                               ep->index = NEXTINDEX(h);
+                       }
+                       --ep->index;
+               } while (__bt_cmp(t, key, ep) == 0);
+
+               /*
+                * Reach here with the last page that was looked at pinned,
+                * which may or may not be the same as the last (or original)
+                * match page.  If it's not useful, release it.
+                */
+               if (h->pgno != save.page->pgno)
+                       mpool_put(t->bt_mp, h, 0);
+
+               *erval = save;
+               return (RET_SUCCESS);
+       }
+
+       /* If at the end of a page, find the next entry. */
+       if (ep->index == NEXTINDEX(ep->page)) {
+               h = ep->page;
+               pg = h->nextpg;
+               mpool_put(t->bt_mp, h, 0);
+               if (pg == P_INVALID)
+                       return (RET_SPECIAL);
+               if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
+                       return (RET_ERROR);
+               ep->index = 0;
+               ep->page = h;
+       }
+       *erval = *ep;
+       return (RET_SUCCESS);
+}
+
+/*
+ * __bt_setcur --
+ *     Set the cursor to an entry in the tree.
+ *
+ * Parameters:
+ *     t:      the tree
+ *   pgno:     page number
+ *    idx:     page index
+ */
+void
+__bt_setcur(BTREE *t, pgno_t pgno, u_int idx)
+{
+       /* Lose any already deleted key. */
+       if (t->bt_cursor.key.data != NULL) {
+               free(t->bt_cursor.key.data);
+               t->bt_cursor.key.size = 0;
+               t->bt_cursor.key.data = NULL;
+       }
+       F_CLR(&t->bt_cursor, CURS_ACQUIRE | CURS_AFTER | CURS_BEFORE);
+
+       /* Update the cursor. */
+       t->bt_cursor.pg.pgno = pgno;
+       t->bt_cursor.pg.index = idx;
+       F_SET(&t->bt_cursor, CURS_INIT);
+}
diff --git a/lib/nbsd_libc/db/btree/bt_split.c b/lib/nbsd_libc/db/btree/bt_split.c
new file mode 100644 (file)
index 0000000..8a97501
--- /dev/null
@@ -0,0 +1,827 @@
+/*     $NetBSD: bt_split.c,v 1.19 2009/04/22 18:44:06 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_split.c,v 1.19 2009/04/22 18:44:06 christos Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <db.h>
+#include "btree.h"
+
+static int      bt_broot(BTREE *, PAGE *, PAGE *, PAGE *);
+static PAGE    *bt_page(BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t);
+static int      bt_preserve(BTREE *, pgno_t);
+static PAGE    *bt_psplit(BTREE *, PAGE *, PAGE *, PAGE *, indx_t *, size_t);
+static PAGE    *bt_root(BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t);
+static int      bt_rroot(BTREE *, PAGE *, PAGE *, PAGE *);
+static recno_t  rec_total(PAGE *);
+
+#ifdef STATISTICS
+unsigned long  bt_rootsplit, bt_split, bt_sortsplit, bt_pfxsaved;
+#endif
+
+/*
+ * __BT_SPLIT -- Split the tree.
+ *
+ * Parameters:
+ *     t:      tree
+ *     sp:     page to split
+ *     key:    key to insert
+ *     data:   data to insert
+ *     flags:  BIGKEY/BIGDATA flags
+ *     ilen:   insert length
+ *     skip:   index to leave open
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+int
+__bt_split(BTREE *t, PAGE *sp, const DBT *key, const DBT *data, int flags,
+    size_t ilen, uint32_t argskip)
+{
+       BINTERNAL *bi = NULL;   /* pacify gcc */
+       BLEAF *bl = NULL, *tbl; /* pacify gcc */
+       DBT a, b;
+       EPGNO *parent;
+       PAGE *h, *l, *r, *lchild, *rchild;
+       indx_t nxtindex;
+       uint16_t skip;
+       uint32_t n, nbytes, nksize = 0; /* pacify gcc */
+       int parentsplit;
+       char *dest;
+
+       /*
+        * Split the page into two pages, l and r.  The split routines return
+        * a pointer to the page into which the key should be inserted and with
+        * skip set to the offset which should be used.  Additionally, l and r
+        * are pinned.
+        */
+       skip = argskip;
+       h = sp->pgno == P_ROOT ?
+           bt_root(t, sp, &l, &r, &skip, ilen) :
+           bt_page(t, sp, &l, &r, &skip, ilen);
+       if (h == NULL)
+               return (RET_ERROR);
+
+       /*
+        * Insert the new key/data pair into the leaf page.  (Key inserts
+        * always cause a leaf page to split first.)
+        */
+       _DBFIT(ilen, indx_t);
+       h->upper -= (indx_t)ilen;
+       h->linp[skip] = h->upper;
+       dest = (char *)(void *)h + h->upper;
+       if (F_ISSET(t, R_RECNO))
+               WR_RLEAF(dest, data, flags);
+       else
+               WR_BLEAF(dest, key, data, flags);
+
+       /* If the root page was split, make it look right. */
+       if (sp->pgno == P_ROOT &&
+           (F_ISSET(t, R_RECNO) ?
+           bt_rroot(t, sp, l, r) : bt_broot(t, sp, l, r)) == RET_ERROR)
+               goto err2;
+
+       /*
+        * Now we walk the parent page stack -- a LIFO stack of the pages that
+        * were traversed when we searched for the page that split.  Each stack
+        * entry is a page number and a page index offset.  The offset is for
+        * the page traversed on the search.  We've just split a page, so we
+        * have to insert a new key into the parent page.
+        *
+        * If the insert into the parent page causes it to split, may have to
+        * continue splitting all the way up the tree.  We stop if the root
+        * splits or the page inserted into didn't have to split to hold the
+        * new key.  Some algorithms replace the key for the old page as well
+        * as the new page.  We don't, as there's no reason to believe that the
+        * first key on the old page is any better than the key we have, and,
+        * in the case of a key being placed at index 0 causing the split, the
+        * key is unavailable.
+        *
+        * There are a maximum of 5 pages pinned at any time.  We keep the left
+        * and right pages pinned while working on the parent.   The 5 are the
+        * two children, left parent and right parent (when the parent splits)
+        * and the root page or the overflow key page when calling bt_preserve.
+        * This code must make sure that all pins are released other than the
+        * root page or overflow page which is unlocked elsewhere.
+        */
+       while ((parent = BT_POP(t)) != NULL) {
+               lchild = l;
+               rchild = r;
+
+               /* Get the parent page. */
+               if ((h = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL)
+                       goto err2;
+
+               /*
+                * The new key goes ONE AFTER the index, because the split
+                * was to the right.
+                */
+               skip = parent->index + 1;
+
+               /*
+                * Calculate the space needed on the parent page.
+                *
+                * Prefix trees: space hack when inserting into BINTERNAL
+                * pages.  Retain only what's needed to distinguish between
+                * the new entry and the LAST entry on the page to its left.
+                * If the keys compare equal, retain the entire key.  Note,
+                * we don't touch overflow keys, and the entire key must be
+                * retained for the next-to-left most key on the leftmost
+                * page of each level, or the search will fail.  Applicable
+                * ONLY to internal pages that have leaf pages as children.
+                * Further reduction of the key between pairs of internal
+                * pages loses too much information.
+                */
+               switch (rchild->flags & P_TYPE) {
+               case P_BINTERNAL:
+                       bi = GETBINTERNAL(rchild, 0);
+                       nbytes = NBINTERNAL(bi->ksize);
+                       break;
+               case P_BLEAF:
+                       bl = GETBLEAF(rchild, 0);
+                       nbytes = NBINTERNAL(bl->ksize);
+                       if (t->bt_pfx && !(bl->flags & P_BIGKEY) &&
+                           (h->prevpg != P_INVALID || skip > 1)) {
+                               size_t temp;
+                               tbl = GETBLEAF(lchild, NEXTINDEX(lchild) - 1);
+                               a.size = tbl->ksize;
+                               a.data = tbl->bytes;
+                               b.size = bl->ksize;
+                               b.data = bl->bytes;
+                               temp = t->bt_pfx(&a, &b);
+                               _DBFIT(temp, uint32_t);
+                               nksize = (uint32_t)temp;
+                               n = NBINTERNAL(nksize);
+                               if (n < nbytes) {
+#ifdef STATISTICS
+                                       bt_pfxsaved += nbytes - n;
+#endif
+                                       nbytes = n;
+                               } else
+                                       nksize = 0;
+                       } else
+                               nksize = 0;
+                       break;
+               case P_RINTERNAL:
+               case P_RLEAF:
+                       nbytes = NRINTERNAL;
+                       break;
+               default:
+                       abort();
+               }
+
+               /* Split the parent page if necessary or shift the indices. */
+               if ((uint32_t)h->upper - (uint32_t)h->lower < nbytes + sizeof(indx_t)) {
+                       sp = h;
+                       h = h->pgno == P_ROOT ?
+                           bt_root(t, h, &l, &r, &skip, nbytes) :
+                           bt_page(t, h, &l, &r, &skip, nbytes);
+                       if (h == NULL)
+                               goto err1;
+                       parentsplit = 1;
+               } else {
+                       if (skip < (nxtindex = NEXTINDEX(h)))
+                               memmove(h->linp + skip + 1, h->linp + skip,
+                                   (nxtindex - skip) * sizeof(indx_t));
+                       h->lower += sizeof(indx_t);
+                       parentsplit = 0;
+               }
+
+               /* Insert the key into the parent page. */
+               switch (rchild->flags & P_TYPE) {
+               case P_BINTERNAL:
+                       h->linp[skip] = h->upper -= nbytes;
+                       dest = (char *)(void *)h + h->linp[skip];
+                       memmove(dest, bi, nbytes);
+                       ((BINTERNAL *)(void *)dest)->pgno = rchild->pgno;
+                       break;
+               case P_BLEAF:
+                       h->linp[skip] = h->upper -= nbytes;
+                       dest = (char *)(void *)h + h->linp[skip];
+                       WR_BINTERNAL(dest, nksize ? nksize : bl->ksize,
+                           rchild->pgno, bl->flags & P_BIGKEY);
+                       memmove(dest, bl->bytes, nksize ? nksize : bl->ksize);
+                       if (bl->flags & P_BIGKEY &&
+                           bt_preserve(t, *(pgno_t *)(void *)bl->bytes) ==
+                           RET_ERROR)
+                               goto err1;
+                       break;
+               case P_RINTERNAL:
+                       /*
+                        * Update the left page count.  If split
+                        * added at index 0, fix the correct page.
+                        */
+                       if (skip > 0)
+                               dest = (char *)(void *)h + h->linp[skip - 1];
+                       else
+                               dest = (char *)(void *)l + l->linp[NEXTINDEX(l) - 1];
+                       ((RINTERNAL *)(void *)dest)->nrecs = rec_total(lchild);
+                       ((RINTERNAL *)(void *)dest)->pgno = lchild->pgno;
+
+                       /* Update the right page count. */
+                       h->linp[skip] = h->upper -= nbytes;
+                       dest = (char *)(void *)h + h->linp[skip];
+                       ((RINTERNAL *)(void *)dest)->nrecs = rec_total(rchild);
+                       ((RINTERNAL *)(void *)dest)->pgno = rchild->pgno;
+                       break;
+               case P_RLEAF:
+                       /*
+                        * Update the left page count.  If split
+                        * added at index 0, fix the correct page.
+                        */
+                       if (skip > 0)
+                               dest = (char *)(void *)h + h->linp[skip - 1];
+                       else
+                               dest = (char *)(void *)l + l->linp[NEXTINDEX(l) - 1];
+                       ((RINTERNAL *)(void *)dest)->nrecs = NEXTINDEX(lchild);
+                       ((RINTERNAL *)(void *)dest)->pgno = lchild->pgno;
+
+                       /* Update the right page count. */
+                       h->linp[skip] = h->upper -= nbytes;
+                       dest = (char *)(void *)h + h->linp[skip];
+                       ((RINTERNAL *)(void *)dest)->nrecs = NEXTINDEX(rchild);
+                       ((RINTERNAL *)(void *)dest)->pgno = rchild->pgno;
+                       break;
+               default:
+                       abort();
+               }
+
+               /* Unpin the held pages. */
+               if (!parentsplit) {
+                       mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+                       break;
+               }
+
+               /* If the root page was split, make it look right. */
+               if (sp->pgno == P_ROOT &&
+                   (F_ISSET(t, R_RECNO) ?
+                   bt_rroot(t, sp, l, r) : bt_broot(t, sp, l, r)) == RET_ERROR)
+                       goto err1;
+
+               mpool_put(t->bt_mp, lchild, MPOOL_DIRTY);
+               mpool_put(t->bt_mp, rchild, MPOOL_DIRTY);
+       }
+
+       /* Unpin the held pages. */
+       mpool_put(t->bt_mp, l, MPOOL_DIRTY);
+       mpool_put(t->bt_mp, r, MPOOL_DIRTY);
+
+       /* Clear any pages left on the stack. */
+       return (RET_SUCCESS);
+
+       /*
+        * If something fails in the above loop we were already walking back
+        * up the tree and the tree is now inconsistent.  Nothing much we can
+        * do about it but release any memory we're holding.
+        */
+err1:  mpool_put(t->bt_mp, lchild, MPOOL_DIRTY);
+       mpool_put(t->bt_mp, rchild, MPOOL_DIRTY);
+
+err2:  mpool_put(t->bt_mp, l, 0);
+       mpool_put(t->bt_mp, r, 0);
+       __dbpanic(t->bt_dbp);
+       return (RET_ERROR);
+}
+
+/*
+ * BT_PAGE -- Split a non-root page of a btree.
+ *
+ * Parameters:
+ *     t:      tree
+ *     h:      root page
+ *     lp:     pointer to left page pointer
+ *     rp:     pointer to right page pointer
+ *     skip:   pointer to index to leave open
+ *     ilen:   insert length
+ *
+ * Returns:
+ *     Pointer to page in which to insert or NULL on error.
+ */
+static PAGE *
+bt_page(BTREE *t, PAGE *h, PAGE **lp, PAGE **rp, indx_t *skip, size_t ilen)
+{
+       PAGE *l, *r, *tp;
+       pgno_t npg;
+
+#ifdef STATISTICS
+       ++bt_split;
+#endif
+       /* Put the new right page for the split into place. */
+       if ((r = __bt_new(t, &npg)) == NULL)
+               return (NULL);
+       r->pgno = npg;
+       r->lower = BTDATAOFF;
+       r->upper = t->bt_psize;
+       r->nextpg = h->nextpg;
+       r->prevpg = h->pgno;
+       r->flags = h->flags & P_TYPE;
+
+       /*
+        * If we're splitting the last page on a level because we're appending
+        * a key to it (skip is NEXTINDEX()), it's likely that the data is
+        * sorted.  Adding an empty page on the side of the level is less work
+        * and can push the fill factor much higher than normal.  If we're
+        * wrong it's no big deal, we'll just do the split the right way next
+        * time.  It may look like it's equally easy to do a similar hack for
+        * reverse sorted data, that is, split the tree left, but it's not.
+        * Don't even try.
+        */
+       if (h->nextpg == P_INVALID && *skip == NEXTINDEX(h)) {
+#ifdef STATISTICS
+               ++bt_sortsplit;
+#endif
+               h->nextpg = r->pgno;
+               r->lower = BTDATAOFF + sizeof(indx_t);
+               *skip = 0;
+               *lp = h;
+               *rp = r;
+               return (r);
+       }
+
+       /* Put the new left page for the split into place. */
+       if ((l = calloc(1, t->bt_psize)) == NULL) {
+               mpool_put(t->bt_mp, r, 0);
+               return (NULL);
+       }
+#ifdef PURIFY
+       memset(l, 0xff, t->bt_psize);
+#endif
+       l->pgno = h->pgno;
+       l->nextpg = r->pgno;
+       l->prevpg = h->prevpg;
+       l->lower = BTDATAOFF;
+       l->upper = t->bt_psize;
+       l->flags = h->flags & P_TYPE;
+
+       /* Fix up the previous pointer of the page after the split page. */
+       if (h->nextpg != P_INVALID) {
+               if ((tp = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL) {
+                       free(l);
+                       /* XXX mpool_free(t->bt_mp, r->pgno); */
+                       return (NULL);
+               }
+               tp->prevpg = r->pgno;
+               mpool_put(t->bt_mp, tp, MPOOL_DIRTY);
+       }
+
+       /*
+        * Split right.  The key/data pairs aren't sorted in the btree page so
+        * it's simpler to copy the data from the split page onto two new pages
+        * instead of copying half the data to the right page and compacting
+        * the left page in place.  Since the left page can't change, we have
+        * to swap the original and the allocated left page after the split.
+        */
+       tp = bt_psplit(t, h, l, r, skip, ilen);
+
+       /* Move the new left page onto the old left page. */
+       memmove(h, l, t->bt_psize);
+       if (tp == l)
+               tp = h;
+       free(l);
+
+       *lp = h;
+       *rp = r;
+       return (tp);
+}
+
+/*
+ * BT_ROOT -- Split the root page of a btree.
+ *
+ * Parameters:
+ *     t:      tree
+ *     h:      root page
+ *     lp:     pointer to left page pointer
+ *     rp:     pointer to right page pointer
+ *     skip:   pointer to index to leave open
+ *     ilen:   insert length
+ *
+ * Returns:
+ *     Pointer to page in which to insert or NULL on error.
+ */
+static PAGE *
+bt_root(BTREE *t, PAGE *h, PAGE **lp, PAGE **rp, indx_t *skip, size_t ilen)
+{
+       PAGE *l, *r, *tp;
+       pgno_t lnpg, rnpg;
+
+#ifdef STATISTICS
+       ++bt_split;
+       ++bt_rootsplit;
+#endif
+       /* Put the new left and right pages for the split into place. */
+       if ((l = __bt_new(t, &lnpg)) == NULL ||
+           (r = __bt_new(t, &rnpg)) == NULL)
+               return (NULL);
+       l->pgno = lnpg;
+       r->pgno = rnpg;
+       l->nextpg = r->pgno;
+       r->prevpg = l->pgno;
+       l->prevpg = r->nextpg = P_INVALID;
+       l->lower = r->lower = BTDATAOFF;
+       l->upper = r->upper = t->bt_psize;
+       l->flags = r->flags = h->flags & P_TYPE;
+
+       /* Split the root page. */
+       tp = bt_psplit(t, h, l, r, skip, ilen);
+
+       *lp = l;
+       *rp = r;
+       return (tp);
+}
+
+/*
+ * BT_RROOT -- Fix up the recno root page after it has been split.
+ *
+ * Parameters:
+ *     t:      tree
+ *     h:      root page
+ *     l:      left page
+ *     r:      right page
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+static int
+bt_rroot(BTREE *t, PAGE *h, PAGE *l, PAGE *r)
+{
+       char *dest;
+       uint32_t sz;
+       size_t temp;
+
+       temp = t->bt_psize - NRINTERNAL;
+       _DBFIT(temp, uint32_t);
+       sz = (uint32_t)temp;
+
+       /* Insert the left and right keys, set the header information. */
+       _DBFIT(sz, indx_t);
+       h->linp[0] = h->upper = (indx_t)sz;
+       dest = (char *)(void *)h + h->upper;
+       WR_RINTERNAL(dest,
+           l->flags & P_RLEAF ? NEXTINDEX(l) : rec_total(l), l->pgno);
+
+       h->linp[1] = h->upper -= NRINTERNAL;
+       dest = (char *)(void *)h + h->upper;
+       WR_RINTERNAL(dest,
+           r->flags & P_RLEAF ? NEXTINDEX(r) : rec_total(r), r->pgno);
+
+       h->lower = BTDATAOFF + 2 * sizeof(indx_t);
+
+       /* Unpin the root page, set to recno internal page. */
+       h->flags &= ~P_TYPE;
+       h->flags |= P_RINTERNAL;
+       mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+
+       return (RET_SUCCESS);
+}
+
+/*
+ * BT_BROOT -- Fix up the btree root page after it has been split.
+ *
+ * Parameters:
+ *     t:      tree
+ *     h:      root page
+ *     l:      left page
+ *     r:      right page
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+static int
+bt_broot(BTREE *t, PAGE *h, PAGE *l, PAGE *r)
+{
+       BINTERNAL *bi = NULL;   /* pacify gcc */
+       BLEAF *bl;
+       uint32_t nbytes;
+       char *dest;
+
+       /*
+        * If the root page was a leaf page, change it into an internal page.
+        * We copy the key we split on (but not the key's data, in the case of
+        * a leaf page) to the new root page.
+        *
+        * The btree comparison code guarantees that the left-most key on any
+        * level of the tree is never used, so it doesn't need to be filled in.
+        */
+       nbytes = NBINTERNAL(0);
+       h->linp[0] = h->upper = t->bt_psize - nbytes;
+       dest = (char *)(void *)h + h->upper;
+       WR_BINTERNAL(dest, 0, l->pgno, 0);
+
+       switch (h->flags & P_TYPE) {
+       case P_BLEAF:
+               bl = GETBLEAF(r, 0);
+               nbytes = NBINTERNAL(bl->ksize);
+               h->linp[1] = h->upper -= nbytes;
+               dest = (char *)(void *)h + h->upper;
+               WR_BINTERNAL(dest, bl->ksize, r->pgno, 0);
+               memmove(dest, bl->bytes, bl->ksize);
+
+               /*
+                * If the key is on an overflow page, mark the overflow chain
+                * so it isn't deleted when the leaf copy of the key is deleted.
+                */
+               if (bl->flags & P_BIGKEY &&
+                   bt_preserve(t, *(pgno_t *)(void *)bl->bytes) == RET_ERROR)
+                       return (RET_ERROR);
+               break;
+       case P_BINTERNAL:
+               bi = GETBINTERNAL(r, 0);
+               nbytes = NBINTERNAL(bi->ksize);
+               h->linp[1] = h->upper -= nbytes;
+               dest = (char *)(void *)h + h->upper;
+               memmove(dest, bi, nbytes);
+               ((BINTERNAL *)(void *)dest)->pgno = r->pgno;
+               break;
+       default:
+               abort();
+       }
+
+       /* There are two keys on the page. */
+       h->lower = BTDATAOFF + 2 * sizeof(indx_t);
+
+       /* Unpin the root page, set to btree internal page. */
+       h->flags &= ~P_TYPE;
+       h->flags |= P_BINTERNAL;
+       mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+
+       return (RET_SUCCESS);
+}
+
+/*
+ * BT_PSPLIT -- Do the real work of splitting the page.
+ *
+ * Parameters:
+ *     t:      tree
+ *     h:      page to be split
+ *     l:      page to put lower half of data
+ *     r:      page to put upper half of data
+ *     pskip:  pointer to index to leave open
+ *     ilen:   insert length
+ *
+ * Returns:
+ *     Pointer to page in which to insert.
+ */
+static PAGE *
+bt_psplit(BTREE *t, PAGE *h, PAGE *l, PAGE *r, indx_t *pskip, size_t ilen)
+{
+       BINTERNAL *bi;
+       BLEAF *bl;
+       CURSOR *c;
+       RLEAF *rl;
+       PAGE *rval;
+       void *src = NULL;       /* pacify gcc */
+       indx_t full, half, nxt, off, skip, top, used;
+       uint32_t nbytes;
+       size_t temp;
+       int bigkeycnt, isbigkey;
+
+       /*
+        * Split the data to the left and right pages.  Leave the skip index
+        * open.  Additionally, make some effort not to split on an overflow
+        * key.  This makes internal page processing faster and can save
+        * space as overflow keys used by internal pages are never deleted.
+        */
+       bigkeycnt = 0;
+       skip = *pskip;
+       temp = t->bt_psize - BTDATAOFF;
+       _DBFIT(temp, indx_t);
+       full = (indx_t)temp;
+       half = full / 2;
+       used = 0;
+       for (nxt = off = 0, top = NEXTINDEX(h); nxt < top; ++off) {
+               if (skip == off) {
+                       _DBFIT(ilen, uint32_t);
+                       nbytes = (uint32_t)ilen;
+                       isbigkey = 0;           /* XXX: not really known. */
+               } else
+                       switch (h->flags & P_TYPE) {
+                       case P_BINTERNAL:
+                               src = bi = GETBINTERNAL(h, nxt);
+                               nbytes = NBINTERNAL(bi->ksize);
+                               isbigkey = bi->flags & P_BIGKEY;
+                               break;
+                       case P_BLEAF:
+                               src = bl = GETBLEAF(h, nxt);
+                               nbytes = NBLEAF(bl);
+                               isbigkey = bl->flags & P_BIGKEY;
+                               break;
+                       case P_RINTERNAL:
+                               src = GETRINTERNAL(h, nxt);
+                               nbytes = NRINTERNAL;
+                               isbigkey = 0;
+                               break;
+                       case P_RLEAF:
+                               src = rl = GETRLEAF(h, nxt);
+                               nbytes = NRLEAF(rl);
+                               isbigkey = 0;
+                               break;
+                       default:
+                               abort();
+                       }
+
+               /*
+                * If the key/data pairs are substantial fractions of the max
+                * possible size for the page, it's possible to get situations
+                * where we decide to try and copy too much onto the left page.
+                * Make sure that doesn't happen.
+                */
+               if ((skip <= off && used + nbytes + sizeof(indx_t) >= full) ||
+                   nxt == top - 1) {
+                       --off;
+                       break;
+               }
+
+               /* Copy the key/data pair, if not the skipped index. */
+               if (skip != off) {
+                       ++nxt;
+
+                       l->linp[off] = l->upper -= nbytes;
+                       memmove((char *)(void *)l + l->upper, src, nbytes);
+               }
+
+               temp = nbytes + sizeof(indx_t);
+               _DBFIT(temp, indx_t);
+               used += (indx_t)temp;
+               if (used >= half) {
+                       if (!isbigkey || bigkeycnt == 3)
+                               break;
+                       else
+                               ++bigkeycnt;
+               }
+       }
+
+       /*
+        * Off is the last offset that's valid for the left page.
+        * Nxt is the first offset to be placed on the right page.
+        */
+       temp = (off + 1) * sizeof(indx_t);
+       _DBFIT(temp, indx_t);
+       l->lower += (indx_t)temp;
+
+       /*
+        * If splitting the page that the cursor was on, the cursor has to be
+        * adjusted to point to the same record as before the split.  If the
+        * cursor is at or past the skipped slot, the cursor is incremented by
+        * one.  If the cursor is on the right page, it is decremented by the
+        * number of records split to the left page.
+        */
+       c = &t->bt_cursor;
+       if (F_ISSET(c, CURS_INIT) && c->pg.pgno == h->pgno) {
+               if (c->pg.index >= skip)
+                       ++c->pg.index;
+               if (c->pg.index < nxt)                  /* Left page. */
+                       c->pg.pgno = l->pgno;
+               else {                                  /* Right page. */
+                       c->pg.pgno = r->pgno;
+                       c->pg.index -= nxt;
+               }
+       }
+
+       /*
+        * If the skipped index was on the left page, just return that page.
+        * Otherwise, adjust the skip index to reflect the new position on
+        * the right page.
+        */
+       if (skip <= off) {
+               skip = MAX_PAGE_OFFSET;
+               rval = l;
+       } else {
+               rval = r;
+               *pskip -= nxt;
+       }
+
+       for (off = 0; nxt < top; ++off) {
+               if (skip == nxt) {
+                       ++off;
+                       skip = MAX_PAGE_OFFSET;
+               }
+               switch (h->flags & P_TYPE) {
+               case P_BINTERNAL:
+                       src = bi = GETBINTERNAL(h, nxt);
+                       nbytes = NBINTERNAL(bi->ksize);
+                       break;
+               case P_BLEAF:
+                       src = bl = GETBLEAF(h, nxt);
+                       nbytes = NBLEAF(bl);
+                       break;
+               case P_RINTERNAL:
+                       src = GETRINTERNAL(h, nxt);
+                       nbytes = NRINTERNAL;
+                       break;
+               case P_RLEAF:
+                       src = rl = GETRLEAF(h, nxt);
+                       nbytes = NRLEAF(rl);
+                       break;
+               default:
+                       abort();
+               }
+               ++nxt;
+               r->linp[off] = r->upper -= nbytes;
+               memmove((char *)(void *)r + r->upper, src, nbytes);
+       }
+       temp = off * sizeof(indx_t);
+       _DBFIT(temp, indx_t);
+       r->lower += (indx_t)temp;
+
+       /* If the key is being appended to the page, adjust the index. */
+       if (skip == top)
+               r->lower += sizeof(indx_t);
+
+       return (rval);
+}
+
+/*
+ * BT_PRESERVE -- Mark a chain of pages as used by an internal node.
+ *
+ * Chains of indirect blocks pointed to by leaf nodes get reclaimed when the
+ * record that references them gets deleted.  Chains pointed to by internal
+ * pages never get deleted.  This routine marks a chain as pointed to by an
+ * internal page.
+ *
+ * Parameters:
+ *     t:      tree
+ *     pg:     page number of first page in the chain.
+ *
+ * Returns:
+ *     RET_SUCCESS, RET_ERROR.
+ */
+static int
+bt_preserve(BTREE *t, pgno_t pg)
+{
+       PAGE *h;
+
+       if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
+               return (RET_ERROR);
+       h->flags |= P_PRESERVE;
+       mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+       return (RET_SUCCESS);
+}
+
+/*
+ * REC_TOTAL -- Return the number of recno entries below a page.
+ *
+ * Parameters:
+ *     h:      page
+ *
+ * Returns:
+ *     The number of recno entries below a page.
+ *
+ * XXX
+ * These values could be set by the bt_psplit routine.  The problem is that the
+ * entry has to be popped off of the stack etc. or the values have to be passed
+ * all the way back to bt_split/bt_rroot and it's not very clean.
+ */
+static recno_t
+rec_total(PAGE *h)
+{
+       recno_t recs;
+       indx_t nxt, top;
+
+       for (recs = 0, nxt = 0, top = NEXTINDEX(h); nxt < top; ++nxt)
+               recs += GETRINTERNAL(h, nxt)->nrecs;
+       return (recs);
+}
diff --git a/lib/nbsd_libc/db/btree/bt_utils.c b/lib/nbsd_libc/db/btree/bt_utils.c
new file mode 100644 (file)
index 0000000..db0d058
--- /dev/null
@@ -0,0 +1,253 @@
+/*     $NetBSD: bt_utils.c,v 1.13 2008/09/10 17:52:35 joerg Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: bt_utils.c,v 1.13 2008/09/10 17:52:35 joerg Exp $");
+
+#include <sys/param.h>
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <db.h>
+#include "btree.h"
+
+/*
+ * __bt_ret --
+ *     Build return key/data pair.
+ *
+ * Parameters:
+ *     t:      tree
+ *     e:      key/data pair to be returned
+ *     key:    user's key structure (NULL if not to be filled in)
+ *     rkey:   memory area to hold key
+ *     data:   user's data structure (NULL if not to be filled in)
+ *     rdata:  memory area to hold data
+ *       copy: always copy the key/data item
+ *
+ * Returns:
+ *     RET_SUCCESS, RET_ERROR.
+ */
+int
+__bt_ret(BTREE *t, EPG *e, DBT *key, DBT *rkey, DBT *data, DBT *rdata, int copy)
+{
+       BLEAF *bl;
+       void *p;
+
+       bl = GETBLEAF(e->page, e->index);
+
+       /*
+        * We must copy big keys/data to make them contigous.  Otherwise,
+        * leave the page pinned and don't copy unless the user specified
+        * concurrent access.
+        */
+       if (key == NULL)
+               goto dataonly;
+
+       if (bl->flags & P_BIGKEY) {
+               if (__ovfl_get(t, bl->bytes,
+                   &key->size, &rkey->data, &rkey->size))
+                       return (RET_ERROR);
+               key->data = rkey->data;
+       } else if (copy || F_ISSET(t, B_DB_LOCK)) {
+               if (bl->ksize > rkey->size) {
+                       p = (void *)(rkey->data == NULL ?
+                           malloc(bl->ksize) : realloc(rkey->data, bl->ksize));
+                       if (p == NULL)
+                               return (RET_ERROR);
+                       rkey->data = p;
+                       rkey->size = bl->ksize;
+               }
+               memmove(rkey->data, bl->bytes, bl->ksize);
+               key->size = bl->ksize;
+               key->data = rkey->data;
+       } else {
+               key->size = bl->ksize;
+               key->data = bl->bytes;
+       }
+
+dataonly:
+       if (data == NULL)
+               return (RET_SUCCESS);
+
+       if (bl->flags & P_BIGDATA) {
+               if (__ovfl_get(t, bl->bytes + bl->ksize,
+                   &data->size, &rdata->data, &rdata->size))
+                       return (RET_ERROR);
+               data->data = rdata->data;
+       } else if (copy || F_ISSET(t, B_DB_LOCK)) {
+               /* Use +1 in case the first record retrieved is 0 length. */
+               if (bl->dsize + 1 > rdata->size) {
+                       p = (void *)(rdata->data == NULL ?
+                           malloc(bl->dsize + 1) :
+                           realloc(rdata->data, bl->dsize + 1));
+                       if (p == NULL)
+                               return (RET_ERROR);
+                       rdata->data = p;
+                       rdata->size = bl->dsize + 1;
+               }
+               memmove(rdata->data, bl->bytes + bl->ksize, bl->dsize);
+               data->size = bl->dsize;
+               data->data = rdata->data;
+       } else {
+               data->size = bl->dsize;
+               data->data = bl->bytes + bl->ksize;
+       }
+
+       return (RET_SUCCESS);
+}
+
+/*
+ * __BT_CMP -- Compare a key to a given record.
+ *
+ * Parameters:
+ *     t:      tree
+ *     k1:     DBT pointer of first arg to comparison
+ *     e:      pointer to EPG for comparison
+ *
+ * Returns:
+ *     < 0 if k1 is < record
+ *     = 0 if k1 is = record
+ *     > 0 if k1 is > record
+ */
+int
+__bt_cmp(BTREE *t, const DBT *k1, EPG *e)
+{
+       BINTERNAL *bi;
+       BLEAF *bl;
+       DBT k2;
+       PAGE *h;
+       void *bigkey;
+
+       /*
+        * The left-most key on internal pages, at any level of the tree, is
+        * guaranteed by the following code to be less than any user key.
+        * This saves us from having to update the leftmost key on an internal
+        * page when the user inserts a new key in the tree smaller than
+        * anything we've yet seen.
+        */
+       h = e->page;
+       if (e->index == 0 && h->prevpg == P_INVALID && !(h->flags & P_BLEAF))
+               return (1);
+
+       bigkey = NULL;
+       if (h->flags & P_BLEAF) {
+               bl = GETBLEAF(h, e->index);
+               if (bl->flags & P_BIGKEY)
+                       bigkey = bl->bytes;
+               else {
+                       k2.data = bl->bytes;
+                       k2.size = bl->ksize;
+               }
+       } else {
+               bi = GETBINTERNAL(h, e->index);
+               if (bi->flags & P_BIGKEY)
+                       bigkey = bi->bytes;
+               else {
+                       k2.data = bi->bytes;
+                       k2.size = bi->ksize;
+               }
+       }
+
+       if (bigkey) {
+               if (__ovfl_get(t, bigkey,
+                   &k2.size, &t->bt_rdata.data, &t->bt_rdata.size))
+                       return (RET_ERROR);
+               k2.data = t->bt_rdata.data;
+       }
+       return ((*t->bt_cmp)(k1, &k2));
+}
+
+/*
+ * __BT_DEFCMP -- Default comparison routine.
+ *
+ * Parameters:
+ *     a:      DBT #1
+ *     b:      DBT #2
+ *
+ * Returns:
+ *     < 0 if a is < b
+ *     = 0 if a is = b
+ *     > 0 if a is > b
+ */
+int
+__bt_defcmp(const DBT *a, const DBT *b)
+{
+       size_t len;
+       uint8_t *p1, *p2;
+
+       /*
+        * XXX
+        * If a size_t doesn't fit in an int, this routine can lose.
+        * What we need is a integral type which is guaranteed to be
+        * larger than a size_t, and there is no such thing.
+        */
+       len = MIN(a->size, b->size);
+       for (p1 = a->data, p2 = b->data; len--; ++p1, ++p2)
+               if (*p1 != *p2)
+                       return ((int)*p1 - (int)*p2);
+       return ((int)a->size - (int)b->size);
+}
+
+/*
+ * __BT_DEFPFX -- Default prefix routine.
+ *
+ * Parameters:
+ *     a:      DBT #1
+ *     b:      DBT #2
+ *
+ * Returns:
+ *     Number of bytes needed to distinguish b from a.
+ */
+size_t
+__bt_defpfx(const DBT *a, const DBT *b)
+{
+       uint8_t *p1, *p2;
+       size_t cnt, len;
+
+       cnt = 1;
+       len = MIN(a->size, b->size);
+       for (p1 = a->data, p2 = b->data; len--; ++p1, ++p2, ++cnt)
+               if (*p1 != *p2)
+                       return (cnt);
+
+       /* a->size must be <= b->size, or they wouldn't be in this order. */
+       return (a->size < b->size ? a->size + 1 : a->size);
+}
diff --git a/lib/nbsd_libc/db/btree/btree.h b/lib/nbsd_libc/db/btree/btree.h
new file mode 100644 (file)
index 0000000..b28f082
--- /dev/null
@@ -0,0 +1,433 @@
+/*     $NetBSD: btree.h,v 1.16 2008/08/26 21:18:38 joerg Exp $ */
+
+/*-
+ * Copyright (c) 1991, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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.
+ *
+ *     @(#)btree.h     8.11 (Berkeley) 8/17/94
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+/* Macros to set/clear/test flags. */
+#define        F_SET(p, f)     (p)->flags |= (f)
+#define        F_CLR(p, f)     (p)->flags &= ~(f)
+#define        F_ISSET(p, f)   ((p)->flags & (f))
+
+#include <mpool.h>
+
+#define        DEFMINKEYPAGE   (2)             /* Minimum keys per page */
+#define        MINCACHE        (5)             /* Minimum cached pages */
+#define        MINPSIZE        (512)           /* Minimum page size */
+
+/*
+ * Page 0 of a btree file contains a copy of the meta-data.  This page is also
+ * used as an out-of-band page, i.e. page pointers that point to nowhere point
+ * to page 0.  Page 1 is the root of the btree.
+ */
+#define        P_INVALID        0              /* Invalid tree page number. */
+#define        P_META           0              /* Tree metadata page number. */
+#define        P_ROOT           1              /* Tree root page number. */
+
+/*
+ * There are five page layouts in the btree: btree internal pages (BINTERNAL),
+ * btree leaf pages (BLEAF), recno internal pages (RINTERNAL), recno leaf pages
+ * (RLEAF) and overflow pages.  All five page types have a page header (PAGE).
+ * This implementation requires that values within structures NOT be padded.
+ * (ANSI C permits random padding.)  If your compiler pads randomly you'll have
+ * to do some work to get this package to run.
+ */
+typedef struct _page {
+       pgno_t  pgno;                   /* this page's page number */
+       pgno_t  prevpg;                 /* left sibling */
+       pgno_t  nextpg;                 /* right sibling */
+
+#define        P_BINTERNAL     0x01            /* btree internal page */
+#define        P_BLEAF         0x02            /* leaf page */
+#define        P_OVERFLOW      0x04            /* overflow page */
+#define        P_RINTERNAL     0x08            /* recno internal page */
+#define        P_RLEAF         0x10            /* leaf page */
+#define P_TYPE         0x1f            /* type mask */
+#define        P_PRESERVE      0x20            /* never delete this chain of pages */
+       uint32_t flags;
+
+       indx_t  lower;                  /* lower bound of free space on page */
+       indx_t  upper;                  /* upper bound of free space on page */
+       indx_t  linp[1];                /* indx_t-aligned VAR. LENGTH DATA */
+} PAGE;
+
+/* First and next index. */
+#define        BTDATAOFF                                                       \
+       (sizeof(pgno_t) + sizeof(pgno_t) + sizeof(pgno_t) +             \
+           sizeof(uint32_t) + sizeof(indx_t) + sizeof(indx_t))
+
+#define        _NEXTINDEX(p) (((p)->lower - BTDATAOFF) / sizeof(indx_t))
+#ifdef _DIAGNOSTIC
+static __inline indx_t
+NEXTINDEX(const PAGE *p) {
+       size_t x = _NEXTINDEX(p);
+       _DBFIT(x, indx_t);
+       return (indx_t)x;
+}
+#else
+#define        NEXTINDEX(p) (indx_t)_NEXTINDEX(p)
+#endif
+
+/*
+ * For pages other than overflow pages, there is an array of offsets into the
+ * rest of the page immediately following the page header.  Each offset is to
+ * an item which is unique to the type of page.  The h_lower offset is just
+ * past the last filled-in index.  The h_upper offset is the first item on the
+ * page.  Offsets are from the beginning of the page.
+ *
+ * If an item is too big to store on a single page, a flag is set and the item
+ * is a { page, size } pair such that the page is the first page of an overflow
+ * chain with size bytes of item.  Overflow pages are simply bytes without any
+ * external structure.
+ *
+ * The page number and size fields in the items are pgno_t-aligned so they can
+ * be manipulated without copying.  (This presumes that 32 bit items can be
+ * manipulated on this system.)
+ */
+#define        BTLALIGN(n)     (((n) + sizeof(pgno_t) - 1) & ~(sizeof(pgno_t) - 1))
+#define        NOVFLSIZE       (sizeof(pgno_t) + sizeof(uint32_t))
+
+/*
+ * For the btree internal pages, the item is a key.  BINTERNALs are {key, pgno}
+ * pairs, such that the key compares less than or equal to all of the records
+ * on that page.  For a tree without duplicate keys, an internal page with two
+ * consecutive keys, a and b, will have all records greater than or equal to a
+ * and less than b stored on the page associated with a.  Duplicate keys are
+ * somewhat special and can cause duplicate internal and leaf page records and
+ * some minor modifications of the above rule.
+ */
+typedef struct _binternal {
+       uint32_t ksize;                 /* key size */
+       pgno_t  pgno;                   /* page number stored on */
+#define        P_BIGDATA       0x01            /* overflow data */
+#define        P_BIGKEY        0x02            /* overflow key */
+       uint8_t flags;
+       char    bytes[1];               /* data */
+} BINTERNAL;
+
+/* Get the page's BINTERNAL structure at index indx. */
+#define        GETBINTERNAL(pg, indx)                                          \
+       ((BINTERNAL *)(void *)((char *)(void *)(pg) + (pg)->linp[indx]))
+
+/* Get the number of bytes in the entry. */
+#define _NBINTERNAL(len)                                               \
+    BTLALIGN(sizeof(uint32_t) + sizeof(pgno_t) + sizeof(uint8_t) + (len))
+#ifdef _DIAGNOSTIC
+static __inline uint32_t
+NBINTERNAL(uint32_t len) {
+       size_t x = _NBINTERNAL(len);
+       _DBFIT(x, uint32_t);
+       return (uint32_t)x;
+}
+#else
+#define NBINTERNAL(len)        (uint32_t)_NBINTERNAL(len)
+#endif
+
+/* Copy a BINTERNAL entry to the page. */
+#define        WR_BINTERNAL(p, size, pgno, flags) do {                         \
+       _DBFIT(size, uint32_t);                                         \
+       *(uint32_t *)(void *)p = (uint32_t)size;                        \
+       p += sizeof(uint32_t);                                          \
+       *(pgno_t *)(void *)p = pgno;                                    \
+       p += sizeof(pgno_t);                                            \
+       *(uint8_t *)(void *)p = flags;                                  \
+       p += sizeof(uint8_t);                                           \
+} while (/*CONSTCOND*/0)
+
+/*
+ * For the recno internal pages, the item is a page number with the number of
+ * keys found on that page and below.
+ */
+typedef struct _rinternal {
+       recno_t nrecs;                  /* number of records */
+       pgno_t  pgno;                   /* page number stored below */
+} RINTERNAL;
+
+/* Get the page's RINTERNAL structure at index indx. */
+#define        GETRINTERNAL(pg, indx)                                          \
+       ((RINTERNAL *)(void *)((char *)(void *)(pg) + (pg)->linp[indx]))
+
+/* Get the number of bytes in the entry. */
+#define NRINTERNAL                                                     \
+       BTLALIGN(sizeof(recno_t) + sizeof(pgno_t))
+
+/* Copy a RINTERAL entry to the page. */
+#define        WR_RINTERNAL(p, nrecs, pgno) do {                               \
+       *(recno_t *)(void *)p = nrecs;                                  \
+       p += sizeof(recno_t);                                           \
+       *(pgno_t *)(void *)p = pgno;                                    \
+} while (/*CONSTCOND*/0)
+
+/* For the btree leaf pages, the item is a key and data pair. */
+typedef struct _bleaf {
+       uint32_t        ksize;          /* size of key */
+       uint32_t        dsize;          /* size of data */
+       uint8_t flags;                  /* P_BIGDATA, P_BIGKEY */
+       char    bytes[1];               /* data */
+} BLEAF;
+
+/* Get the page's BLEAF structure at index indx. */
+#define        GETBLEAF(pg, indx)                                              \
+       ((BLEAF *)(void *)((char *)(void *)(pg) + (pg)->linp[indx]))
+
+
+/* Get the number of bytes in the user's key/data pair. */
+#define _NBLEAFDBT(ksize, dsize)                                       \
+    BTLALIGN(sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint8_t) +   \
+           (ksize) + (dsize))
+#ifdef _DIAGNOSTIC
+static __inline uint32_t
+NBLEAFDBT(size_t k, size_t d) {
+       size_t x = _NBLEAFDBT(k, d);
+       _DBFIT(x, uint32_t);
+       return (uint32_t)x;
+}
+#else
+#define NBLEAFDBT(p, q)        (uint32_t)_NBLEAFDBT(p, q)
+#endif
+
+/* Get the number of bytes in the entry. */
+#define NBLEAF(p)      NBLEAFDBT((p)->ksize, (p)->dsize)
+
+/* Copy a BLEAF entry to the page. */
+#define        WR_BLEAF(p, key, data, flags) do {                              \
+       _DBFIT(key->size, uint32_t);                                    \
+       *(uint32_t *)(void *)p = (uint32_t)key->size;                   \
+       p += sizeof(uint32_t);                                          \
+       _DBFIT(data->size, uint32_t);                                   \
+       *(uint32_t *)(void *)p = (uint32_t)data->size;                  \
+       p += sizeof(uint32_t);                                          \
+       *(uint8_t *)(void *)p = flags;                                  \
+       p += sizeof(uint8_t);                                           \
+       (void)memmove(p, key->data, key->size);                         \
+       p += key->size;                                                 \
+       (void)memmove(p, data->data, data->size);                       \
+} while (/*CONSTCOND*/0)
+
+/* For the recno leaf pages, the item is a data entry. */
+typedef struct _rleaf {
+       uint32_t        dsize;          /* size of data */
+       uint8_t flags;                  /* P_BIGDATA */
+       char    bytes[1];
+} RLEAF;
+
+/* Get the page's RLEAF structure at index indx. */
+#define        GETRLEAF(pg, indx)                                              \
+       ((RLEAF *)(void *)((char *)(void *)(pg) + (pg)->linp[indx]))
+
+#define        _NRLEAFDBT(dsize)                                               \
+       BTLALIGN(sizeof(uint32_t) + sizeof(uint8_t) + (dsize))
+
+#ifdef _DIAGNOSTIC
+static __inline uint32_t
+NRLEAFDBT(size_t d) {
+       size_t x = _NRLEAFDBT(d);
+       _DBFIT(x, uint32_t);
+       return (uint32_t)x;
+}
+#else
+#define NRLEAFDBT(d)   (uint32_t)_NRLEAFDBT(d)
+#endif
+
+/* Get the number of bytes in the entry. */
+#define NRLEAF(p)      NRLEAFDBT((p)->dsize)
+
+/* Get the number of bytes from the user's data. */
+
+/* Copy a RLEAF entry to the page. */
+#define        WR_RLEAF(p, data, flags) do {                                   \
+       _DBFIT(data->size, uint32_t);                                   \
+       *(uint32_t *)(void *)p = (uint32_t)data->size;                  \
+       p += sizeof(uint32_t);                                          \
+       *(uint8_t *)(void *)p = flags;                                  \
+       p += sizeof(uint8_t);                                           \
+       memmove(p, data->data, data->size);                             \
+} while (/*CONSTCOND*/0)
+
+/*
+ * A record in the tree is either a pointer to a page and an index in the page
+ * or a page number and an index.  These structures are used as a cursor, stack
+ * entry and search returns as well as to pass records to other routines.
+ *
+ * One comment about searches.  Internal page searches must find the largest
+ * record less than key in the tree so that descents work.  Leaf page searches
+ * must find the smallest record greater than key so that the returned index
+ * is the record's correct position for insertion.
+ */
+typedef struct _epgno {
+       pgno_t  pgno;                   /* the page number */
+       indx_t  index;                  /* the index on the page */
+} EPGNO;
+
+typedef struct _epg {
+       PAGE    *page;                  /* the (pinned) page */
+       indx_t   index;                 /* the index on the page */
+} EPG;
+
+/*
+ * About cursors.  The cursor (and the page that contained the key/data pair
+ * that it referenced) can be deleted, which makes things a bit tricky.  If
+ * there are no duplicates of the cursor key in the tree (i.e. B_NODUPS is set
+ * or there simply aren't any duplicates of the key) we copy the key that it
+ * referenced when it's deleted, and reacquire a new cursor key if the cursor
+ * is used again.  If there are duplicates keys, we move to the next/previous
+ * key, and set a flag so that we know what happened.  NOTE: if duplicate (to
+ * the cursor) keys are added to the tree during this process, it is undefined
+ * if they will be returned or not in a cursor scan.
+ *
+ * The flags determine the possible states of the cursor:
+ *
+ * CURS_INIT   The cursor references *something*.
+ * CURS_ACQUIRE        The cursor was deleted, and a key has been saved so that
+ *             we can reacquire the right position in the tree.
+ * CURS_AFTER, CURS_BEFORE
+ *             The cursor was deleted, and now references a key/data pair
+ *             that has not yet been returned, either before or after the
+ *             deleted key/data pair.
+ * XXX
+ * This structure is broken out so that we can eventually offer multiple
+ * cursors as part of the DB interface.
+ */
+typedef struct _cursor {
+       EPGNO    pg;                    /* B: Saved tree reference. */
+       DBT      key;                   /* B: Saved key, or key.data == NULL. */
+       recno_t  rcursor;               /* R: recno cursor (1-based) */
+
+#define        CURS_ACQUIRE    0x01            /*  B: Cursor needs to be reacquired. */
+#define        CURS_AFTER      0x02            /*  B: Unreturned cursor after key. */
+#define        CURS_BEFORE     0x04            /*  B: Unreturned cursor before key. */
+#define        CURS_INIT       0x08            /* RB: Cursor initialized. */
+       uint8_t flags;
+} CURSOR;
+
+/*
+ * The metadata of the tree.  The nrecs field is used only by the RECNO code.
+ * This is because the btree doesn't really need it and it requires that every
+ * put or delete call modify the metadata.
+ */
+typedef struct _btmeta {
+       uint32_t        magic;          /* magic number */
+       uint32_t        version;        /* version */
+       uint32_t        psize;          /* page size */
+       uint32_t        free;           /* page number of first free page */
+       uint32_t        nrecs;          /* R: number of records */
+
+#define        SAVEMETA        (B_NODUPS | R_RECNO)
+       uint32_t        flags;          /* bt_flags & SAVEMETA */
+} BTMETA;
+
+/* The in-memory btree/recno data structure. */
+typedef struct _btree {
+       MPOOL    *bt_mp;                /* memory pool cookie */
+
+       DB       *bt_dbp;               /* pointer to enclosing DB */
+
+       EPG       bt_cur;               /* current (pinned) page */
+       PAGE     *bt_pinned;            /* page pinned across calls */
+
+       CURSOR    bt_cursor;            /* cursor */
+
+#define        BT_PUSH(t, p, i) {                                              \
+       t->bt_sp->pgno = p;                                             \
+       t->bt_sp->index = i;                                            \
+       ++t->bt_sp;                                                     \
+}
+#define        BT_POP(t)       (t->bt_sp == t->bt_stack ? NULL : --t->bt_sp)
+#define        BT_CLR(t)       (t->bt_sp = t->bt_stack)
+       EPGNO     bt_stack[50];         /* stack of parent pages */
+       EPGNO    *bt_sp;                /* current stack pointer */
+
+       DBT       bt_rkey;              /* returned key */
+       DBT       bt_rdata;             /* returned data */
+
+       int       bt_fd;                /* tree file descriptor */
+
+       pgno_t    bt_free;              /* next free page */
+       uint32_t bt_psize;              /* page size */
+       indx_t    bt_ovflsize;          /* cut-off for key/data overflow */
+       int       bt_lorder;            /* byte order */
+                                       /* sorted order */
+       enum { NOT, BACK, FORWARD } bt_order;
+       EPGNO     bt_last;              /* last insert */
+
+                                       /* B: key comparison function */
+       int     (*bt_cmp)(const DBT *, const DBT *);
+                                       /* B: prefix comparison function */
+       size_t  (*bt_pfx)(const DBT *, const DBT *);
+                                       /* R: recno input function */
+       int     (*bt_irec)(struct _btree *, recno_t);
+
+       FILE     *bt_rfp;               /* R: record FILE pointer */
+       int       bt_rfd;               /* R: record file descriptor */
+
+       caddr_t   bt_cmap;              /* R: current point in mapped space */
+       caddr_t   bt_smap;              /* R: start of mapped space */
+       caddr_t   bt_emap;              /* R: end of mapped space */
+       size_t    bt_msize;             /* R: size of mapped region. */
+
+       recno_t   bt_nrecs;             /* R: number of records */
+       size_t    bt_reclen;            /* R: fixed record length */
+       uint8_t   bt_bval;              /* R: delimiting byte/pad character */
+
+/*
+ * NB:
+ * B_NODUPS and R_RECNO are stored on disk, and may not be changed.
+ */
+#define        B_INMEM         0x00001         /* in-memory tree */
+#define        B_METADIRTY     0x00002         /* need to write metadata */
+#define        B_MODIFIED      0x00004         /* tree modified */
+#define        B_NEEDSWAP      0x00008         /* if byte order requires swapping */
+#define        B_RDONLY        0x00010         /* read-only tree */
+
+#define        B_NODUPS        0x00020         /* no duplicate keys permitted */
+#define        R_RECNO         0x00080         /* record oriented tree */
+
+#define        R_CLOSEFP       0x00040         /* opened a file pointer */
+#define        R_EOF           0x00100         /* end of input file reached. */
+#define        R_FIXLEN        0x00200         /* fixed length records */
+#define        R_MEMMAPPED     0x00400         /* memory mapped file. */
+#define        R_INMEM         0x00800         /* in-memory file */
+#define        R_MODIFIED      0x01000         /* modified file */
+#define        R_RDONLY        0x02000         /* read-only file */
+
+#define        B_DB_LOCK       0x04000         /* DB_LOCK specified. */
+#define        B_DB_SHMEM      0x08000         /* DB_SHMEM specified. */
+#define        B_DB_TXN        0x10000         /* DB_TXN specified. */
+       uint32_t flags;
+} BTREE;
+
+#include "extern.h"
diff --git a/lib/nbsd_libc/db/btree/extern.h b/lib/nbsd_libc/db/btree/extern.h
new file mode 100644 (file)
index 0000000..665f852
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: extern.h,v 1.12 2008/09/26 11:41:06 tsutsui Exp $      */
+
+/*-
+ * Copyright (c) 1991, 1993, 1994
+ *     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.
+ * 3. 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.
+ *
+ *     @(#)extern.h    8.10 (Berkeley) 7/20/94
+ */
+
+#ifndef _BTREE_EXTERN_H_
+#define _BTREE_EXTERN_H_
+int     __bt_close(DB *);
+int     __bt_cmp(BTREE *, const DBT *, EPG *);
+int     __bt_crsrdel(BTREE *, EPGNO *);
+int     __bt_defcmp(const DBT *, const DBT *);
+size_t  __bt_defpfx(const DBT *, const DBT *);
+int     __bt_delete(const DB *, const DBT *, unsigned int);
+int     __bt_dleaf(BTREE *, const DBT *, PAGE *, unsigned int);
+int     __bt_fd(const DB *);
+int     __bt_free(BTREE *, PAGE *);
+int     __bt_get(const DB *, const DBT *, DBT *, unsigned int);
+PAGE   *__bt_new(BTREE *, pgno_t *);
+void    __bt_pgin(void *, pgno_t, void *);
+void    __bt_pgout(void *, pgno_t, void *);
+int     __bt_push(BTREE *, pgno_t, int);
+int     __bt_put(const DB *dbp, DBT *, const DBT *, unsigned int);
+int     __bt_ret(BTREE *, EPG *, DBT *, DBT *, DBT *, DBT *, int);
+EPG    *__bt_search(BTREE *, const DBT *, int *);
+int     __bt_seq(const DB *, DBT *, DBT *, unsigned int);
+void    __bt_setcur(BTREE *, pgno_t, unsigned int);
+int     __bt_split(BTREE *, PAGE *,
+           const DBT *, const DBT *, int, size_t, uint32_t);
+int     __bt_sync(const DB *, unsigned int);
+
+int     __ovfl_delete(BTREE *, void *);
+int     __ovfl_get(BTREE *, void *, size_t *, void **, size_t *);
+int     __ovfl_put(BTREE *, const DBT *, pgno_t *);
+
+#ifdef DEBUG
+void    __bt_dmpage(PAGE *);
+void    __bt_dnpage(DB *, pgno_t);
+void    __bt_dpage(PAGE *);
+void    __bt_dump(DB *);
+#endif
+#ifdef STATISTICS
+void    __bt_stat(DB *);
+#endif
+#endif /* _BTREE_EXTERN_H_ */
diff --git a/lib/nbsd_libc/db/changelog b/lib/nbsd_libc/db/changelog
new file mode 100644 (file)
index 0000000..f820e56
--- /dev/null
@@ -0,0 +1,105 @@
+#      $NetBSD: changelog,v 1.2 1996/05/03 21:20:56 cgd Exp $
+
+1.84 -> 1.85
+       recno:  #ifdef out use of mmap, it's not portable enough.
+
+1.83 -> 1.84   Thu Aug 18 15:46:07 EDT 1994
+       recno:  Rework fixed-length records so that closing and reopening
+               the file now works.  Pad short records on input.  Never do
+               signed comparison in recno input reading functions.
+
+1.82 -> 1.83   Tue Jul 26 15:33:44 EDT 1994
+       btree:  Rework cursor deletion code yet again; bugs with
+               deleting empty pages that only contained the cursor
+               record.
+
+1.81 -> 1.82   Sat Jul 16 11:01:50 EDT 1994
+       btree:  Fix bugs introduced by new cursor/deletion code.
+               Replace return kbuf/dbuf with real DBT's.
+
+1.80 -> 1.81
+       btree:  Fix bugs introduced by new cursor/deletion code.
+       all:    Add #defines for Purify.
+
+1.79 -> 1.80   Wed Jul 13 22:41:54 EDT 1994
+       btree   Change deletion to coalesce empty pages.  This is a major
+               change, cursors and duplicate pages all had to be reworked.
+               Return to a fixed stack.
+       recno:  Affected by cursor changes.  New cursor structures should
+               permit multiple cursors in the future.
+
+1.78 -> 1.79   Mon Jun 20 17:36:47 EDT 1994
+       all:    Minor cleanups of 1.78 for porting reasons; only
+               major change was inlining check of NULL pointer
+               so that __fix_realloc goes away.
+
+1.77 -> 1.78   Thu Jun 16 19:06:43 EDT 1994
+       all:    Move "standard" size typedef's into db.h.
+
+1.76 -> 1.77   Thu Jun 16 16:48:38 EDT 1994
+       hash:   Delete __init_ routine, has special meaning to OSF 2.0.
+
+1.74 -> 1.76
+       all:    Finish up the port to the Alpha.
+
+1.73 -> 1.74
+       recno:  Don't put the record if rec_search fails, in rec_rdelete.
+               Create fixed-length intermediate records past "end" of DB
+               correctly.
+               Realloc bug when reading in fixed records.
+       all:    First cut at port to Alpha (64-bit architecture) using
+               4.4BSD basic integral types typedef's.
+               Cast allocation pointers to shut up old compilers.
+               Rework PORT directory into OS/machine directories.
+
+1.72 -> 1.73
+       btree:  If enough duplicate records were inserted and then deleted
+               that internal pages had references to empty pages of the
+               duplicate keys, the search function ended up on the wrong
+               page.
+
+1.7  -> 1.72   12 Oct 1993
+       hash:   Support NET/2 hash formats.
+
+1.7  -> 1.71   16 Sep 1993
+       btree/recno:
+               Fix bug in internal search routines that caused
+               return of invalid pointers.
+
+1.6  -> 1.7    07 Sep 1993
+       hash:   Fixed big key overflow bugs.
+       test:   Portability hacks, rewrite test script, Makefile.
+       btree/recno:
+               Stop copying non-overflow key/data pairs.
+       PORT:   Break PORT directory up into per architecture/OS
+               subdirectories.
+
+1.5  -> 1.6    06 Jun 1993
+       hash:   In PAIRFITS, the first comparison should look at (P)[2].
+               The hash_realloc function was walking off the end of memory.
+               The overflow page number was wrong when bumping splitpoint.
+
+1.4  -> 1.5    23 May 1993
+       hash:   Set hash default fill factor dynamically.
+       recno:  Fixed bug in sorted page splits.
+               Add page size parameter support.
+               Allow recno to specify the name of the underlying btree;
+                       used for vi recovery.
+       btree/recno:
+               Support 64K pages.
+       btree/hash/recno:
+               Provide access to an underlying file descriptor.
+               Change sync routines to take a flag argument, recno
+                       uses this to sync out the underlying btree.
+
+1.3  -> 1.4    10 May 1993
+       recno:  Delete the R_CURSORLOG flag from the recno interface.
+               Zero-length record fix for non-mmap reads.
+               Try and make SIZE_T_MAX test in open portable.
+
+1.2  -> 1.3    01 May 1993
+       btree:  Ignore user byte-order setting when reading already
+               existing database.  Fixes to byte-order conversions.
+
+1.1  -> 1.2    15 Apr 1993
+               No bug fixes, only compatibility hacks.
diff --git a/lib/nbsd_libc/db/db/Makefile.inc b/lib/nbsd_libc/db/db/Makefile.inc
new file mode 100644 (file)
index 0000000..9755e8f
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.4 1995/02/27 13:21:22 cgd Exp $
+#       @(#)Makefile.inc       8.1 (Berkeley) 6/4/93
+
+.PATH: ${.CURDIR}/db/db
+
+SRCS+= db.c
diff --git a/lib/nbsd_libc/db/db/db.c b/lib/nbsd_libc/db/db/db.c
new file mode 100644 (file)
index 0000000..0591836
--- /dev/null
@@ -0,0 +1,102 @@
+/*     $NetBSD: db.c,v 1.16 2008/09/11 12:58:00 joerg Exp $    */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: db.c,v 1.16 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stddef.h>
+#include <stdio.h>
+
+#include <db.h>
+static int __dberr(void);
+
+#ifdef __weak_alias
+__weak_alias(dbopen,_dbopen)
+#endif
+
+DB *
+dbopen(const char *fname, int flags, mode_t mode, DBTYPE type,
+    const void *openinfo)
+{
+
+#define        DB_FLAGS        (DB_LOCK | DB_SHMEM | DB_TXN)
+#define        USE_OPEN_FLAGS                                                  \
+       (O_CREAT | O_EXCL | O_EXLOCK | O_NONBLOCK | O_RDONLY |          \
+        O_RDWR | O_SHLOCK | O_TRUNC)
+
+       if ((flags & ~(USE_OPEN_FLAGS | DB_FLAGS)) == 0)
+               switch (type) {
+               case DB_BTREE:
+                       return (__bt_open(fname, flags & USE_OPEN_FLAGS,
+                           mode, openinfo, (int)(flags & DB_FLAGS)));
+               case DB_HASH:
+                       return (__hash_open(fname, flags & USE_OPEN_FLAGS,
+                           mode, openinfo, (int)(flags & DB_FLAGS)));
+               case DB_RECNO:
+                       return (__rec_open(fname, flags & USE_OPEN_FLAGS,
+                           mode, openinfo, (int)(flags & DB_FLAGS)));
+               }
+       errno = EINVAL;
+       return (NULL);
+}
+
+static int
+__dberr(void)
+{
+       return (RET_ERROR);
+}
+
+/*
+ * __DBPANIC -- Stop.
+ *
+ * Parameters:
+ *     dbp:    pointer to the DB structure.
+ */
+void
+__dbpanic(DB *dbp)
+{
+       /* The only thing that can succeed is a close. */
+       dbp->del = (int (*)(const struct __db *, const DBT*, u_int))__dberr;
+       dbp->fd = (int (*)(const struct __db *))__dberr;
+       dbp->get = (int (*)(const struct __db *, const DBT*, DBT *, u_int))__dberr;
+       dbp->put = (int (*)(const struct __db *, DBT *, const DBT *, u_int))__dberr;
+       dbp->seq = (int (*)(const struct __db *, DBT *, DBT *, u_int))__dberr;
+       dbp->sync = (int (*)(const struct __db *, u_int))__dberr;
+}
diff --git a/lib/nbsd_libc/db/db2netbsd b/lib/nbsd_libc/db/db2netbsd
new file mode 100755 (executable)
index 0000000..d5abeda
--- /dev/null
@@ -0,0 +1,31 @@
+#!/bin/sh
+#      $NetBSD: db2netbsd,v 1.2 1999/02/16 18:01:37 kleink Exp $
+
+# This version transforms a Berkeley DB distribution into something
+# which can be 'cvs import'ed into the NetBSD source repository.
+# It is to be run in the untarred Berkeley DB distribution directory
+# (e.g. the "db.1.85" directory created by tar xvf), and sets up
+# the destination tree in place.
+
+version=`basename $PWD | sed -e 's/db\.//'`
+releasetag=`basename $PWD | sed -e 's/\./-/g'`
+
+CLEANFILES="PORT docs hash/search.h test/btree.tests test/hash.tests"
+
+# clean up pieces that we never import
+/bin/rm -rf $CLEANFILES
+find . -type l -o -name tags | xargs /bin/rm -f
+
+# The include files are already in place
+
+# Put the regression tests in the right place
+mkdir -p regress/lib/libc
+mv test regress/lib/libc/db
+
+# Put the libc pieces in the right place.
+mkdir -p lib/libc/db
+mv Makefile.inc README btree changelog db hash man mpool recno lib/libc/db
+
+echo "import with:"
+echo "cvs import -m \"Import of Berkeley DB version $version\" \
+src CSRG $releasetag"
diff --git a/lib/nbsd_libc/db/hash/Makefile.inc b/lib/nbsd_libc/db/hash/Makefile.inc
new file mode 100644 (file)
index 0000000..d65b310
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.9 2005/09/13 01:44:09 christos Exp $
+#       @(#)Makefile.inc       8.1 (Berkeley) 6/4/93
+
+.PATH: ${.CURDIR}/db/hash
+
+SRCS+= hash.c hash_bigkey.c hash_buf.c hash_func.c hash_log2.c \
+       hash_page.c ndbmdatum.c ndbm.c
diff --git a/lib/nbsd_libc/db/hash/README b/lib/nbsd_libc/db/hash/README
new file mode 100644 (file)
index 0000000..02e1655
--- /dev/null
@@ -0,0 +1,69 @@
+#      $NetBSD: README,v 1.5 1999/02/16 17:59:18 kleink Exp $
+#      @(#)README      8.1 (Berkeley) 6/4/93
+
+This package implements a superset of the hsearch and dbm/ndbm libraries.
+
+Test Programs:
+       All test programs which need key/data pairs expect them entered
+       with key and data on separate lines
+
+       tcreat3.c       
+               Takes 
+                       bucketsize (bsize), 
+                       fill factor (ffactor), and
+                       initial number of elements (nelem).  
+               Creates a hash table named hashtest containing the 
+               keys/data pairs entered from standard in.
+       thash4.c
+               Takes
+                       bucketsize (bsize), 
+                       fill factor (ffactor), 
+                       initial number of elements (nelem)
+                       bytes of cache (ncached), and
+                       file from which to read data  (fname)
+               Creates a table from the key/data pairs on standard in and
+               then does a read of each key/data in fname
+       tdel.c
+               Takes
+                       bucketsize (bsize), and
+                       fill factor (ffactor).
+                       file from which to read data (fname)
+               Reads each key/data pair from fname and deletes the
+               key from the hash table hashtest
+       tseq.c
+               Reads the key/data pairs in the file hashtest and writes them
+               to standard out.
+       tread2.c
+               Takes
+                       butes of cache (ncached).
+               Reads key/data pairs from standard in and looks them up
+               in the file hashtest.
+       tverify.c
+               Reads key/data pairs from standard in, looks them up
+               in the file hashtest, and verifies that the data is
+               correct.
+
+NOTES:
+
+The man page ../man/db.3 explains the interface to the hashing system.
+The file hash.ps is a postscript copy of a paper explaining
+the history, implementation, and performance of the hash package.
+
+"bugs" or idiosyncracies
+
+If you have a lot of overflows, it is possible to run out of overflow
+pages.  Currently, this will cause a message to be printed on stderr.
+Eventually, this will be indicated by a return error code.
+
+If you are using the ndbm interface and exit without flushing or closing the
+file, you may lose updates since the package buffers all writes.  Also,
+the db interface only creates a single database file.  To avoid overwriting
+the user's original file, the suffix ".db" is appended to the file name
+passed to dbm_open.  Additionally, if your code "knows" about the historic
+.dir and .pag files, it will break.  
+
+There is a fundamental difference between this package and the old hsearch.
+Hsearch requires the user to maintain the keys and data in the application's
+allocated memory while hash takes care of all storage management.  The down
+side is that the byte strings passed in the ENTRY structure must be null
+terminated (both the keys and the data).
diff --git a/lib/nbsd_libc/db/hash/extern.h b/lib/nbsd_libc/db/hash/extern.h
new file mode 100644 (file)
index 0000000..455bf51
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: extern.h,v 1.9 2008/08/26 21:18:38 joerg Exp $ */
+
+/*-
+ * Copyright (c) 1991, 1993, 1994
+ *     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.
+ * 3. 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.
+ *
+ *     @(#)extern.h    8.4 (Berkeley) 6/16/94
+ */
+
+BUFHEAD        *__add_ovflpage(HTAB *, BUFHEAD *);
+int     __addel(HTAB *, BUFHEAD *, const DBT *, const DBT *);
+int     __big_delete(HTAB *, BUFHEAD *);
+int     __big_insert(HTAB *, BUFHEAD *, const DBT *, const DBT *);
+int     __big_keydata(HTAB *, BUFHEAD *, DBT *, DBT *, int);
+int     __big_return(HTAB *, BUFHEAD *, int, DBT *, int);
+int     __big_split(HTAB *, BUFHEAD *, BUFHEAD *, BUFHEAD *,
+               int, uint32_t, SPLIT_RETURN *);
+int     __buf_free(HTAB *, int, int);
+void    __buf_init(HTAB *, u_int);
+uint32_t        __call_hash(HTAB *, char *, int);
+int     __delpair(HTAB *, BUFHEAD *, int);
+int     __expand_table(HTAB *);
+int     __find_bigpair(HTAB *, BUFHEAD *, int, char *, int);
+uint16_t        __find_last_page(HTAB *, BUFHEAD **);
+void    __free_ovflpage(HTAB *, BUFHEAD *);
+BUFHEAD        *__get_buf(HTAB *, uint32_t, BUFHEAD *, int);
+int     __get_page(HTAB *, char *, uint32_t, int, int, int);
+int     __ibitmap(HTAB *, int, int, int);
+uint32_t        __log2(uint32_t);
+int     __put_page(HTAB *, char *, uint32_t, int, int);
+void    __reclaim_buf(HTAB *, BUFHEAD *);
+int     __split_page(HTAB *, uint32_t, uint32_t);
+
+/* Default hash routine. */
+extern uint32_t (*__default_hash)(const void *, size_t);
+
+#ifdef HASH_STATISTICS
+extern int hash_accesses, hash_collisions, hash_expansions, hash_overflows;
+#endif
diff --git a/lib/nbsd_libc/db/hash/hash.c b/lib/nbsd_libc/db/hash/hash.c
new file mode 100644 (file)
index 0000000..358a071
--- /dev/null
@@ -0,0 +1,972 @@
+/*     $NetBSD: hash.c,v 1.31 2009/02/12 06:35:54 lukem Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Margo Seltzer.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: hash.c,v 1.31 2009/02/12 06:35:54 lukem Exp $");
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/stat.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <assert.h>
+
+#include <db.h>
+#include "hash.h"
+#include "page.h"
+#include "extern.h"
+
+static int   alloc_segs(HTAB *, int);
+static int   flush_meta(HTAB *);
+static int   hash_access(HTAB *, ACTION, DBT *, DBT *);
+static int   hash_close(DB *);
+static int   hash_delete(const DB *, const DBT *, uint32_t);
+static int   hash_fd(const DB *);
+static int   hash_get(const DB *, const DBT *, DBT *, uint32_t);
+static int   hash_put(const DB *, DBT *, const DBT *, uint32_t);
+static void *hash_realloc(SEGMENT **, size_t, size_t);
+static int   hash_seq(const DB *, DBT *, DBT *, uint32_t);
+static int   hash_sync(const DB *, uint32_t);
+static int   hdestroy(HTAB *);
+static HTAB *init_hash(HTAB *, const char *, const HASHINFO *);
+static int   init_htab(HTAB *, size_t);
+#if BYTE_ORDER == LITTLE_ENDIAN
+static void  swap_header(HTAB *);
+static void  swap_header_copy(HASHHDR *, HASHHDR *);
+#endif
+
+/* Fast arithmetic, relying on powers of 2, */
+#define MOD(x, y)              ((x) & ((y) - 1))
+
+#define RETURN_ERROR(ERR, LOC) { save_errno = ERR; goto LOC; }
+
+/* Return values */
+#define        SUCCESS  (0)
+#define        ERROR   (-1)
+#define        ABNORMAL (1)
+
+#ifdef HASH_STATISTICS
+int hash_accesses, hash_collisions, hash_expansions, hash_overflows;
+#endif
+
+/************************** INTERFACE ROUTINES ***************************/
+/* OPEN/CLOSE */
+
+/* ARGSUSED */
+DB *
+__hash_open(const char *file, int flags, mode_t mode, const HASHINFO *info,
+    int dflags)
+{
+       HTAB *hashp;
+       struct stat statbuf;
+       DB *dbp;
+       int bpages, new_table, nsegs, save_errno;
+       ssize_t hdrsize;
+
+       if ((flags & O_ACCMODE) == O_WRONLY) {
+               errno = EINVAL;
+               return (NULL);
+       }
+
+       if (!(hashp = calloc(1, sizeof(HTAB))))
+               return (NULL);
+       hashp->fp = -1;
+
+       /*
+        * Even if user wants write only, we need to be able to read
+        * the actual file, so we need to open it read/write. But, the
+        * field in the hashp structure needs to be accurate so that
+        * we can check accesses.
+        */
+       hashp->flags = flags;
+
+       new_table = 0;
+       if (!file || (flags & O_TRUNC) ||
+           (stat(file, &statbuf) && (errno == ENOENT))) {
+               if (errno == ENOENT)
+                       errno = 0; /* Just in case someone looks at errno */
+               new_table = 1;
+       }
+       if (file) {
+               if ((hashp->fp = open(file, flags, mode)) == -1)
+                       RETURN_ERROR(errno, error0);
+               if (fcntl(hashp->fp, F_SETFD, FD_CLOEXEC) == -1)
+                       RETURN_ERROR(errno, error1);
+               if (fstat(hashp->fp, &statbuf) == -1)
+                       RETURN_ERROR(errno, error1);
+               new_table |= statbuf.st_size == 0;
+       }
+       if (new_table) {
+               if (!(hashp = init_hash(hashp, file, info)))
+                       RETURN_ERROR(errno, error1);
+       } else {
+               /* Table already exists */
+               if (info && info->hash)
+                       hashp->hash = info->hash;
+               else
+                       hashp->hash = __default_hash;
+
+               hdrsize = read(hashp->fp, &hashp->hdr, sizeof(HASHHDR));
+#if BYTE_ORDER == LITTLE_ENDIAN
+               swap_header(hashp);
+#endif
+               if (hdrsize == -1)
+                       RETURN_ERROR(errno, error1);
+               if (hdrsize != sizeof(HASHHDR))
+                       RETURN_ERROR(EFTYPE, error1);
+               /* Verify file type, versions and hash function */
+               if (hashp->MAGIC != HASHMAGIC)
+                       RETURN_ERROR(EFTYPE, error1);
+#define        OLDHASHVERSION  1
+               if (hashp->VERSION != HASHVERSION &&
+                   hashp->VERSION != OLDHASHVERSION)
+                       RETURN_ERROR(EFTYPE, error1);
+               if (hashp->hash(CHARKEY, sizeof(CHARKEY)) !=
+                   (uint32_t)hashp->H_CHARKEY)
+                       RETURN_ERROR(EFTYPE, error1);
+               /*
+                * Figure out how many segments we need.  Max_Bucket is the
+                * maximum bucket number, so the number of buckets is
+                * max_bucket + 1.
+                */
+               nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
+                        hashp->SGSIZE;
+               hashp->nsegs = 0;
+               if (alloc_segs(hashp, nsegs))
+                       /*
+                        * If alloc_segs fails, table will have been destroyed
+                        * and errno will have been set.
+                        */
+                       return (NULL);
+               /* Read in bitmaps */
+               bpages = (hashp->SPARES[hashp->OVFL_POINT] +
+                   (unsigned int)(hashp->BSIZE << BYTE_SHIFT) - 1) >>
+                   (hashp->BSHIFT + BYTE_SHIFT);
+
+               hashp->nmaps = bpages;
+               (void)memset(&hashp->mapp[0], 0, bpages * sizeof(uint32_t *));
+       }
+
+       /* Initialize Buffer Manager */
+       if (info && info->cachesize)
+               __buf_init(hashp, info->cachesize);
+       else
+               __buf_init(hashp, DEF_BUFSIZE);
+
+       hashp->new_file = new_table;
+       hashp->save_file = file && (hashp->flags & O_RDWR);
+       hashp->cbucket = -1;
+       if (!(dbp = malloc(sizeof(DB)))) {
+               save_errno = errno;
+               hdestroy(hashp);
+               errno = save_errno;
+               return (NULL);
+       }
+       dbp->internal = hashp;
+       dbp->close = hash_close;
+       dbp->del = hash_delete;
+       dbp->fd = hash_fd;
+       dbp->get = hash_get;
+       dbp->put = hash_put;
+       dbp->seq = hash_seq;
+       dbp->sync = hash_sync;
+       dbp->type = DB_HASH;
+
+#ifdef DEBUG
+       (void)fprintf(stderr,
+"%s\n%s%p\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%x\n%s%x\n%s%d\n%s%d\n",
+           "init_htab:",
+           "TABLE POINTER   ", hashp,
+           "BUCKET SIZE     ", hashp->BSIZE,
+           "BUCKET SHIFT    ", hashp->BSHIFT,
+           "DIRECTORY SIZE  ", hashp->DSIZE,
+           "SEGMENT SIZE    ", hashp->SGSIZE,
+           "SEGMENT SHIFT   ", hashp->SSHIFT,
+           "FILL FACTOR     ", hashp->FFACTOR,
+           "MAX BUCKET      ", hashp->MAX_BUCKET,
+           "OVFL POINT      ", hashp->OVFL_POINT,
+           "LAST FREED      ", hashp->LAST_FREED,
+           "HIGH MASK       ", hashp->HIGH_MASK,
+           "LOW  MASK       ", hashp->LOW_MASK,
+           "NSEGS           ", hashp->nsegs,
+           "NKEYS           ", hashp->NKEYS);
+#endif
+#ifdef HASH_STATISTICS
+       hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
+#endif
+       return (dbp);
+
+error1:
+       if (hashp != NULL)
+               (void)close(hashp->fp);
+
+error0:
+       free(hashp);
+       errno = save_errno;
+       return (NULL);
+}
+
+static int
+hash_close(DB *dbp)
+{
+       HTAB *hashp;
+       int retval;
+
+       if (!dbp)
+               return (ERROR);
+
+       hashp = dbp->internal;
+       retval = hdestroy(hashp);
+       free(dbp);
+       return (retval);
+}
+
+static int
+hash_fd(const DB *dbp)
+{
+       HTAB *hashp;
+
+       if (!dbp)
+               return (ERROR);
+
+       hashp = dbp->internal;
+       if (hashp->fp == -1) {
+               errno = ENOENT;
+               return (-1);
+       }
+       return (hashp->fp);
+}
+
+/************************** LOCAL CREATION ROUTINES **********************/
+static HTAB *
+init_hash(HTAB *hashp, const char *file, const HASHINFO *info)
+{
+       struct stat statbuf;
+       int nelem;
+
+       nelem = 1;
+       hashp->NKEYS = 0;
+       hashp->LORDER = BYTE_ORDER;
+       hashp->BSIZE = DEF_BUCKET_SIZE;
+       hashp->BSHIFT = DEF_BUCKET_SHIFT;
+       hashp->SGSIZE = DEF_SEGSIZE;
+       hashp->SSHIFT = DEF_SEGSIZE_SHIFT;
+       hashp->DSIZE = DEF_DIRSIZE;
+       hashp->FFACTOR = DEF_FFACTOR;
+       hashp->hash = __default_hash;
+       memset(hashp->SPARES, 0, sizeof(hashp->SPARES));
+       memset(hashp->BITMAPS, 0, sizeof (hashp->BITMAPS));
+
+       /* Fix bucket size to be optimal for file system */
+       if (file != NULL) {
+               if (stat(file, &statbuf))
+                       return (NULL);
+               hashp->BSIZE = MIN(statbuf.st_blksize, MAX_BSIZE);
+               hashp->BSHIFT = __log2((uint32_t)hashp->BSIZE);
+       }
+
+       if (info) {
+               if (info->bsize) {
+                       /* Round pagesize up to power of 2 */
+                       hashp->BSHIFT = __log2(info->bsize);
+                       hashp->BSIZE = 1 << hashp->BSHIFT;
+                       if (hashp->BSIZE > MAX_BSIZE) {
+                               errno = EINVAL;
+                               return (NULL);
+                       }
+               }
+               if (info->ffactor)
+                       hashp->FFACTOR = info->ffactor;
+               if (info->hash)
+                       hashp->hash = info->hash;
+               if (info->nelem)
+                       nelem = info->nelem;
+               if (info->lorder) {
+                       if (info->lorder != BIG_ENDIAN &&
+                           info->lorder != LITTLE_ENDIAN) {
+                               errno = EINVAL;
+                               return (NULL);
+                       }
+                       hashp->LORDER = info->lorder;
+               }
+       }
+       /* init_htab should destroy the table and set errno if it fails */
+       if (init_htab(hashp, (size_t)nelem))
+               return (NULL);
+       else
+               return (hashp);
+}
+/*
+ * This calls alloc_segs which may run out of memory.  Alloc_segs will destroy
+ * the table and set errno, so we just pass the error information along.
+ *
+ * Returns 0 on No Error
+ */
+static int
+init_htab(HTAB *hashp, size_t nelem)
+{
+       int nbuckets;
+       uint32_t nsegs;
+       int l2;
+
+       /*
+        * Divide number of elements by the fill factor and determine a
+        * desired number of buckets.  Allocate space for the next greater
+        * power of two number of buckets.
+        */
+       nelem = (nelem - 1) / hashp->FFACTOR + 1;
+
+       _DBFIT(nelem, uint32_t);
+       l2 = __log2(MAX((uint32_t)nelem, 2));
+       nbuckets = 1 << l2;
+
+       hashp->SPARES[l2] = l2 + 1;
+       hashp->SPARES[l2 + 1] = l2 + 1;
+       hashp->OVFL_POINT = l2;
+       hashp->LAST_FREED = 2;
+
+       /* First bitmap page is at: splitpoint l2 page offset 1 */
+       if (__ibitmap(hashp, (int)OADDR_OF(l2, 1), l2 + 1, 0))
+               return (-1);
+
+       hashp->MAX_BUCKET = hashp->LOW_MASK = nbuckets - 1;
+       hashp->HIGH_MASK = (nbuckets << 1) - 1;
+       /* LINTED constant in conditional context */
+       hashp->HDRPAGES = ((MAX(sizeof(HASHHDR), MINHDRSIZE) - 1) >>
+           hashp->BSHIFT) + 1;
+
+       nsegs = (nbuckets - 1) / hashp->SGSIZE + 1;
+       nsegs = 1 << __log2(nsegs);
+
+       if (nsegs > (uint32_t)hashp->DSIZE)
+               hashp->DSIZE = nsegs;
+       return (alloc_segs(hashp, (int)nsegs));
+}
+
+/********************** DESTROY/CLOSE ROUTINES ************************/
+
+/*
+ * Flushes any changes to the file if necessary and destroys the hashp
+ * structure, freeing all allocated space.
+ */
+static int
+hdestroy(HTAB *hashp)
+{
+       int i, save_errno;
+
+       save_errno = 0;
+
+#ifdef HASH_STATISTICS
+       (void)fprintf(stderr, "hdestroy: accesses %d collisions %d\n",
+           hash_accesses, hash_collisions);
+       (void)fprintf(stderr, "hdestroy: expansions %d\n",
+           hash_expansions);
+       (void)fprintf(stderr, "hdestroy: overflows %d\n",
+           hash_overflows);
+       (void)fprintf(stderr, "keys %d maxp %d segmentcount %d\n",
+           hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs);
+
+       for (i = 0; i < NCACHED; i++)
+               (void)fprintf(stderr,
+                   "spares[%d] = %d\n", i, hashp->SPARES[i]);
+#endif
+       /*
+        * Call on buffer manager to free buffers, and if required,
+        * write them to disk.
+        */
+       if (__buf_free(hashp, 1, hashp->save_file))
+               save_errno = errno;
+       if (hashp->dir) {
+               free(*hashp->dir);      /* Free initial segments */
+               /* Free extra segments */
+               while (hashp->exsegs--)
+                       free(hashp->dir[--hashp->nsegs]);
+               free(hashp->dir);
+       }
+       if (flush_meta(hashp) && !save_errno)
+               save_errno = errno;
+       /* Free Bigmaps */
+       for (i = 0; i < hashp->nmaps; i++)
+               if (hashp->mapp[i])
+                       free(hashp->mapp[i]);
+
+       if (hashp->fp != -1)
+               (void)close(hashp->fp);
+
+       free(hashp);
+
+       if (save_errno) {
+               errno = save_errno;
+               return (ERROR);
+       }
+       return (SUCCESS);
+}
+/*
+ * Write modified pages to disk
+ *
+ * Returns:
+ *      0 == OK
+ *     -1 ERROR
+ */
+static int
+hash_sync(const DB *dbp, uint32_t flags)
+{
+       HTAB *hashp;
+
+       if (flags != 0) {
+               errno = EINVAL;
+               return (ERROR);
+       }
+
+       if (!dbp)
+               return (ERROR);
+
+       hashp = dbp->internal;
+       if (!hashp->save_file)
+               return (0);
+       if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
+               return (ERROR);
+       hashp->new_file = 0;
+       return (0);
+}
+
+/*
+ * Returns:
+ *      0 == OK
+ *     -1 indicates that errno should be set
+ */
+static int
+flush_meta(HTAB *hashp)
+{
+       HASHHDR *whdrp;
+#if BYTE_ORDER == LITTLE_ENDIAN
+       HASHHDR whdr;
+#endif
+       int fp, i;
+       ssize_t wsize;
+
+       if (!hashp->save_file)
+               return (0);
+       hashp->MAGIC = HASHMAGIC;
+       hashp->VERSION = HASHVERSION;
+       hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY));
+
+       fp = hashp->fp;
+       whdrp = &hashp->hdr;
+#if BYTE_ORDER == LITTLE_ENDIAN
+       whdrp = &whdr;
+       swap_header_copy(&hashp->hdr, whdrp);
+#endif
+       if ((wsize = pwrite(fp, whdrp, sizeof(HASHHDR), (off_t)0)) == -1)
+               return (-1);
+       else
+               if (wsize != sizeof(HASHHDR)) {
+                       errno = EFTYPE;
+                       hashp->err = errno;
+                       return (-1);
+               }
+       for (i = 0; i < NCACHED; i++)
+               if (hashp->mapp[i])
+                       if (__put_page(hashp, (char *)(void *)hashp->mapp[i],
+                               (u_int)hashp->BITMAPS[i], 0, 1))
+                               return (-1);
+       return (0);
+}
+
+/*******************************SEARCH ROUTINES *****************************/
+/*
+ * All the access routines return
+ *
+ * Returns:
+ *      0 on SUCCESS
+ *      1 to indicate an external ERROR (i.e. key not found, etc)
+ *     -1 to indicate an internal ERROR (i.e. out of memory, etc)
+ */
+static int
+hash_get(const DB *dbp, const DBT *key, DBT *data, uint32_t flag)
+{
+       HTAB *hashp;
+
+       hashp = dbp->internal;
+       if (flag) {
+               hashp->err = errno = EINVAL;
+               return (ERROR);
+       }
+       return (hash_access(hashp, HASH_GET, __UNCONST(key), data));
+}
+
+static int
+hash_put(const DB *dbp, DBT *key, const DBT *data, uint32_t flag)
+{
+       HTAB *hashp;
+
+       hashp = dbp->internal;
+       if (flag && flag != R_NOOVERWRITE) {
+               hashp->err = errno = EINVAL;
+               return (ERROR);
+       }
+       if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
+               hashp->err = errno = EPERM;
+               return (ERROR);
+       }
+       /* LINTED const castaway */
+       return (hash_access(hashp, flag == R_NOOVERWRITE ?
+           HASH_PUTNEW : HASH_PUT, __UNCONST(key), __UNCONST(data)));
+}
+
+static int
+hash_delete(const DB *dbp, const DBT *key, uint32_t flag)
+{
+       HTAB *hashp;
+
+       hashp = dbp->internal;
+       if (flag && flag != R_CURSOR) {
+               hashp->err = errno = EINVAL;
+               return (ERROR);
+       }
+       if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
+               hashp->err = errno = EPERM;
+               return (ERROR);
+       }
+       return hash_access(hashp, HASH_DELETE, __UNCONST(key), NULL);
+}
+
+/*
+ * Assume that hashp has been set in wrapper routine.
+ */
+static int
+hash_access(HTAB *hashp, ACTION action, DBT *key, DBT *val)
+{
+       BUFHEAD *rbufp;
+       BUFHEAD *bufp, *save_bufp;
+       uint16_t *bp;
+       int n, ndx, off;
+       size_t size;
+       char *kp;
+       uint16_t pageno;
+
+#ifdef HASH_STATISTICS
+       hash_accesses++;
+#endif
+
+       off = hashp->BSIZE;
+       size = key->size;
+       kp = (char *)key->data;
+       rbufp = __get_buf(hashp, __call_hash(hashp, kp, (int)size), NULL, 0);
+       if (!rbufp)
+               return (ERROR);
+       save_bufp = rbufp;
+
+       /* Pin the bucket chain */
+       rbufp->flags |= BUF_PIN;
+       for (bp = (uint16_t *)(void *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
+               if (bp[1] >= REAL_KEY) {
+                       /* Real key/data pair */
+                       if (size == (size_t)(off - *bp) &&
+                           memcmp(kp, rbufp->page + *bp, size) == 0)
+                               goto found;
+                       off = bp[1];
+#ifdef HASH_STATISTICS
+                       hash_collisions++;
+#endif
+                       bp += 2;
+                       ndx += 2;
+               } else if (bp[1] == OVFLPAGE) {
+                       rbufp = __get_buf(hashp, (uint32_t)*bp, rbufp, 0);
+                       if (!rbufp) {
+                               save_bufp->flags &= ~BUF_PIN;
+                               return (ERROR);
+                       }
+                       /* FOR LOOP INIT */
+                       bp = (uint16_t *)(void *)rbufp->page;
+                       n = *bp++;
+                       ndx = 1;
+                       off = hashp->BSIZE;
+               } else if (bp[1] < REAL_KEY) {
+                       if ((ndx =
+                           __find_bigpair(hashp, rbufp, ndx, kp, (int)size)) > 0)
+                               goto found;
+                       if (ndx == -2) {
+                               bufp = rbufp;
+                               if (!(pageno =
+                                   __find_last_page(hashp, &bufp))) {
+                                       ndx = 0;
+                                       rbufp = bufp;
+                                       break;  /* FOR */
+                               }
+                               rbufp = __get_buf(hashp, (uint32_t)pageno,
+                                   bufp, 0);
+                               if (!rbufp) {
+                                       save_bufp->flags &= ~BUF_PIN;
+                                       return (ERROR);
+                               }
+                               /* FOR LOOP INIT */
+                               bp = (uint16_t *)(void *)rbufp->page;
+                               n = *bp++;
+                               ndx = 1;
+                               off = hashp->BSIZE;
+                       } else {
+                               save_bufp->flags &= ~BUF_PIN;
+                               return (ERROR);
+                       }
+               }
+
+       /* Not found */
+       switch (action) {
+       case HASH_PUT:
+       case HASH_PUTNEW:
+               if (__addel(hashp, rbufp, key, val)) {
+                       save_bufp->flags &= ~BUF_PIN;
+                       return (ERROR);
+               } else {
+                       save_bufp->flags &= ~BUF_PIN;
+                       return (SUCCESS);
+               }
+       case HASH_GET:
+       case HASH_DELETE:
+       default:
+               save_bufp->flags &= ~BUF_PIN;
+               return (ABNORMAL);
+       }
+
+found:
+       switch (action) {
+       case HASH_PUTNEW:
+               save_bufp->flags &= ~BUF_PIN;
+               return (ABNORMAL);
+       case HASH_GET:
+               bp = (uint16_t *)(void *)rbufp->page;
+               if (bp[ndx + 1] < REAL_KEY) {
+                       if (__big_return(hashp, rbufp, ndx, val, 0))
+                               return (ERROR);
+               } else {
+                       val->data = (uint8_t *)rbufp->page + (int)bp[ndx + 1];
+                       val->size = bp[ndx] - bp[ndx + 1];
+               }
+               break;
+       case HASH_PUT:
+               if ((__delpair(hashp, rbufp, ndx)) ||
+                   (__addel(hashp, rbufp, key, val))) {
+                       save_bufp->flags &= ~BUF_PIN;
+                       return (ERROR);
+               }
+               break;
+       case HASH_DELETE:
+               if (__delpair(hashp, rbufp, ndx))
+                       return (ERROR);
+               break;
+       default:
+               abort();
+       }
+       save_bufp->flags &= ~BUF_PIN;
+       return (SUCCESS);
+}
+
+static int
+hash_seq(const DB *dbp, DBT *key, DBT *data, uint32_t flag)
+{
+       uint32_t bucket;
+       BUFHEAD *bufp = NULL; /* XXX: gcc */
+       HTAB *hashp;
+       uint16_t *bp, ndx;
+
+       hashp = dbp->internal;
+       if (flag && flag != R_FIRST && flag != R_NEXT) {
+               hashp->err = errno = EINVAL;
+               return (ERROR);
+       }
+#ifdef HASH_STATISTICS
+       hash_accesses++;
+#endif
+       if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
+               hashp->cbucket = 0;
+               hashp->cndx = 1;
+               hashp->cpage = NULL;
+       }
+
+       for (bp = NULL; !bp || !bp[0]; ) {
+               if (!(bufp = hashp->cpage)) {
+                       for (bucket = hashp->cbucket;
+                           bucket <= (uint32_t)hashp->MAX_BUCKET;
+                           bucket++, hashp->cndx = 1) {
+                               bufp = __get_buf(hashp, bucket, NULL, 0);
+                               if (!bufp)
+                                       return (ERROR);
+                               hashp->cpage = bufp;
+                               bp = (uint16_t *)(void *)bufp->page;
+                               if (bp[0])
+                                       break;
+                       }
+                       hashp->cbucket = bucket;
+                       if (hashp->cbucket > hashp->MAX_BUCKET) {
+                               hashp->cbucket = -1;
+                               return (ABNORMAL);
+                       }
+               } else
+                       bp = (uint16_t *)(void *)hashp->cpage->page;
+
+               _DIAGASSERT(bp != NULL);
+               _DIAGASSERT(bufp != NULL);
+               while (bp[hashp->cndx + 1] == OVFLPAGE) {
+                       bufp = hashp->cpage =
+                           __get_buf(hashp, (uint32_t)bp[hashp->cndx], bufp,
+                               0);
+                       if (!bufp)
+                               return (ERROR);
+                       bp = (uint16_t *)(void *)(bufp->page);
+                       hashp->cndx = 1;
+               }
+               if (!bp[0]) {
+                       hashp->cpage = NULL;
+                       ++hashp->cbucket;
+               }
+       }
+       ndx = hashp->cndx;
+       if (bp[ndx + 1] < REAL_KEY) {
+               if (__big_keydata(hashp, bufp, key, data, 1))
+                       return (ERROR);
+       } else {
+               if (hashp->cpage == NULL)
+                       return (ERROR);
+               key->data = (uint8_t *)hashp->cpage->page + bp[ndx];
+               key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx];
+               data->data = (uint8_t *)hashp->cpage->page + bp[ndx + 1];
+               data->size = bp[ndx] - bp[ndx + 1];
+               ndx += 2;
+               if (ndx > bp[0]) {
+                       hashp->cpage = NULL;
+                       hashp->cbucket++;
+                       hashp->cndx = 1;
+               } else
+                       hashp->cndx = ndx;
+       }
+       return (SUCCESS);
+}
+
+/********************************* UTILITIES ************************/
+
+/*
+ * Returns:
+ *      0 ==> OK
+ *     -1 ==> Error
+ */
+int
+__expand_table(HTAB *hashp)
+{
+       uint32_t old_bucket, new_bucket;
+       int new_segnum, spare_ndx;
+       size_t dirsize;
+
+#ifdef HASH_STATISTICS
+       hash_expansions++;
+#endif
+       new_bucket = ++hashp->MAX_BUCKET;
+       old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
+
+       new_segnum = new_bucket >> hashp->SSHIFT;
+
+       /* Check if we need a new segment */
+       if (new_segnum >= hashp->nsegs) {
+               /* Check if we need to expand directory */
+               if (new_segnum >= hashp->DSIZE) {
+                       /* Reallocate directory */
+                       dirsize = hashp->DSIZE * sizeof(SEGMENT *);
+                       if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
+                               return (-1);
+                       hashp->DSIZE = dirsize << 1;
+               }
+               if ((hashp->dir[new_segnum] =
+                   calloc((size_t)hashp->SGSIZE, sizeof(SEGMENT))) == NULL)
+                       return (-1);
+               hashp->exsegs++;
+               hashp->nsegs++;
+       }
+       /*
+        * If the split point is increasing (MAX_BUCKET's log base 2
+        * * increases), we need to copy the current contents of the spare
+        * split bucket to the next bucket.
+        */
+       spare_ndx = __log2((uint32_t)(hashp->MAX_BUCKET + 1));
+       if (spare_ndx > hashp->OVFL_POINT) {
+               hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
+               hashp->OVFL_POINT = spare_ndx;
+       }
+
+       if (new_bucket > (uint32_t)hashp->HIGH_MASK) {
+               /* Starting a new doubling */
+               hashp->LOW_MASK = hashp->HIGH_MASK;
+               hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
+       }
+       /* Relocate records to the new bucket */
+       return (__split_page(hashp, old_bucket, new_bucket));
+}
+
+/*
+ * If realloc guarantees that the pointer is not destroyed if the realloc
+ * fails, then this routine can go away.
+ */
+static void *
+hash_realloc(SEGMENT **p_ptr, size_t oldsize, size_t newsize)
+{
+       void *p;
+
+       if ((p = malloc(newsize)) != NULL) {
+               memmove(p, *p_ptr, oldsize);
+               memset((char *)p + oldsize, 0, newsize - oldsize);
+               free(*p_ptr);
+               *p_ptr = p;
+       }
+       return (p);
+}
+
+uint32_t
+__call_hash(HTAB *hashp, char *k, int len)
+{
+       int n, bucket;
+
+       n = hashp->hash(k, (size_t)len);
+       bucket = n & hashp->HIGH_MASK;
+       if (bucket > hashp->MAX_BUCKET)
+               bucket = bucket & hashp->LOW_MASK;
+       return (bucket);
+}
+
+/*
+ * Allocate segment table.  On error, destroy the table and set errno.
+ *
+ * Returns 0 on success
+ */
+static int
+alloc_segs(HTAB *hashp, int nsegs)
+{
+       int i;
+       SEGMENT store;
+
+       int save_errno;
+
+       hashp->dir = calloc((size_t)hashp->DSIZE, sizeof(SEGMENT *));
+       if (hashp->dir == NULL) {
+               save_errno = errno;
+               (void)hdestroy(hashp);
+               errno = save_errno;
+               return (-1);
+       }
+       hashp->nsegs = nsegs;
+       if (nsegs == 0)
+               return 0;
+       /* Allocate segments */
+       store = calloc((size_t)(nsegs << hashp->SSHIFT), sizeof(SEGMENT));
+       if (store == NULL) {
+               save_errno = errno;
+               (void)hdestroy(hashp);
+               errno = save_errno;
+               return (-1);
+       }
+       for (i = 0; i < nsegs; i++)
+               hashp->dir[i] = &store[i << hashp->SSHIFT];
+       return (0);
+}
+
+#if BYTE_ORDER == LITTLE_ENDIAN
+/*
+ * Hashp->hdr needs to be byteswapped.
+ */
+static void
+swap_header_copy(HASHHDR *srcp, HASHHDR *destp)
+{
+       size_t i;
+
+       P_32_COPY(srcp->magic, destp->magic);
+       P_32_COPY(srcp->version, destp->version);
+       P_32_COPY(srcp->lorder, destp->lorder);
+       P_32_COPY(srcp->bsize, destp->bsize);
+       P_32_COPY(srcp->bshift, destp->bshift);
+       P_32_COPY(srcp->dsize, destp->dsize);
+       P_32_COPY(srcp->ssize, destp->ssize);
+       P_32_COPY(srcp->sshift, destp->sshift);
+       P_32_COPY(srcp->ovfl_point, destp->ovfl_point);
+       P_32_COPY(srcp->last_freed, destp->last_freed);
+       P_32_COPY(srcp->max_bucket, destp->max_bucket);
+       P_32_COPY(srcp->high_mask, destp->high_mask);
+       P_32_COPY(srcp->low_mask, destp->low_mask);
+       P_32_COPY(srcp->ffactor, destp->ffactor);
+       P_32_COPY(srcp->nkeys, destp->nkeys);
+       P_32_COPY(srcp->hdrpages, destp->hdrpages);
+       P_32_COPY(srcp->h_charkey, destp->h_charkey);
+       for (i = 0; i < NCACHED; i++) {
+               P_32_COPY(srcp->spares[i], destp->spares[i]);
+               P_16_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
+       }
+}
+
+static void
+swap_header(HTAB *hashp)
+{
+       HASHHDR *hdrp;
+       size_t i;
+
+       hdrp = &hashp->hdr;
+
+       M_32_SWAP(hdrp->magic);
+       M_32_SWAP(hdrp->version);
+       M_32_SWAP(hdrp->lorder);
+       M_32_SWAP(hdrp->bsize);
+       M_32_SWAP(hdrp->bshift);
+       M_32_SWAP(hdrp->dsize);
+       M_32_SWAP(hdrp->ssize);
+       M_32_SWAP(hdrp->sshift);
+       M_32_SWAP(hdrp->ovfl_point);
+       M_32_SWAP(hdrp->last_freed);
+       M_32_SWAP(hdrp->max_bucket);
+       M_32_SWAP(hdrp->high_mask);
+       M_32_SWAP(hdrp->low_mask);
+       M_32_SWAP(hdrp->ffactor);
+       M_32_SWAP(hdrp->nkeys);
+       M_32_SWAP(hdrp->hdrpages);
+       M_32_SWAP(hdrp->h_charkey);
+       for (i = 0; i < NCACHED; i++) {
+               M_32_SWAP(hdrp->spares[i]);
+               M_16_SWAP(hdrp->bitmaps[i]);
+       }
+}
+#endif
diff --git a/lib/nbsd_libc/db/hash/hash.h b/lib/nbsd_libc/db/hash/hash.h
new file mode 100644 (file)
index 0000000..f3c87a8
--- /dev/null
@@ -0,0 +1,295 @@
+/*     $NetBSD: hash.h,v 1.15 2008/08/26 21:18:38 joerg Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Margo Seltzer.
+ *
+ * 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. 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.
+ *
+ *     @(#)hash.h      8.3 (Berkeley) 5/31/94
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+/* Operations */
+typedef enum {
+       HASH_GET, HASH_PUT, HASH_PUTNEW, HASH_DELETE, HASH_FIRST, HASH_NEXT
+} ACTION;
+
+/* Buffer Management structures */
+typedef struct _bufhead BUFHEAD;
+
+struct _bufhead {
+       BUFHEAD         *prev;          /* LRU links */
+       BUFHEAD         *next;          /* LRU links */
+       BUFHEAD         *ovfl;          /* Overflow page buffer header */
+       uint32_t         addr;          /* Address of this page */
+       char            *page;          /* Actual page data */
+       char            flags;
+#define        BUF_MOD         0x0001
+#define BUF_DISK       0x0002
+#define        BUF_BUCKET      0x0004
+#define        BUF_PIN         0x0008
+};
+
+#define IS_BUCKET(X)   ((X) & BUF_BUCKET)
+
+typedef BUFHEAD **SEGMENT;
+
+/* Hash Table Information */
+typedef struct hashhdr {               /* Disk resident portion */
+       int32_t         magic;          /* Magic NO for hash tables */
+       int32_t         version;        /* Version ID */
+       uint32_t        lorder;         /* Byte Order */
+       int32_t         bsize;          /* Bucket/Page Size */
+       int32_t         bshift;         /* Bucket shift */
+       int32_t         dsize;          /* Directory Size */
+       int32_t         ssize;          /* Segment Size */
+       int32_t         sshift;         /* Segment shift */
+       int32_t         ovfl_point;     /* Where overflow pages are being 
+                                        * allocated */
+       int32_t         last_freed;     /* Last overflow page freed */
+       int32_t         max_bucket;     /* ID of Maximum bucket in use */
+       int32_t         high_mask;      /* Mask to modulo into entire table */
+       int32_t         low_mask;       /* Mask to modulo into lower half of 
+                                        * table */
+       int32_t         ffactor;        /* Fill factor */
+       int32_t         nkeys;          /* Number of keys in hash table */
+       int32_t         hdrpages;       /* Size of table header */
+       int32_t         h_charkey;      /* value of hash(CHARKEY) */
+#define NCACHED        32                      /* number of bit maps and spare 
+                                        * points */
+       int32_t         spares[NCACHED];/* spare pages for overflow */
+       uint16_t        bitmaps[NCACHED];       /* address of overflow page 
+                                                * bitmaps */
+} HASHHDR;
+
+typedef struct htab     {              /* Memory resident data structure */
+       HASHHDR         hdr;            /* Header */
+       int             nsegs;          /* Number of allocated segments */
+       int             exsegs;         /* Number of extra allocated 
+                                        * segments */
+       uint32_t        (*hash)(const void *, size_t);  /* Hash function */
+       int             flags;          /* Flag values */
+       int             fp;             /* File pointer */
+       char            *tmp_buf;       /* Temporary Buffer for BIG data */
+       char            *tmp_key;       /* Temporary Buffer for BIG keys */
+       BUFHEAD         *cpage;         /* Current page */
+       int             cbucket;        /* Current bucket */
+       int             cndx;           /* Index of next item on cpage */
+       int             err;            /* Error Number -- for DBM 
+                                        * compatibility */
+       int             new_file;       /* Indicates if fd is backing store 
+                                        * or no */
+       int             save_file;      /* Indicates whether we need to flush 
+                                        * file at
+                                        * exit */
+       uint32_t        *mapp[NCACHED]; /* Pointers to page maps */
+       int             nmaps;          /* Initial number of bitmaps */
+       int             nbufs;          /* Number of buffers left to 
+                                        * allocate */
+       BUFHEAD         bufhead;        /* Header of buffer lru list */
+       SEGMENT         *dir;           /* Hash Bucket directory */
+} HTAB;
+
+/*
+ * Constants
+ */
+#define        MAX_BSIZE               65536           /* 2^16 */
+#define MIN_BUFFERS            6
+#define MINHDRSIZE             512
+#define DEF_BUFSIZE            65536           /* 64 K */
+#define DEF_BUCKET_SIZE                4096
+#define DEF_BUCKET_SHIFT       12              /* log2(BUCKET) */
+#define DEF_SEGSIZE            256
+#define DEF_SEGSIZE_SHIFT      8               /* log2(SEGSIZE)         */
+#define DEF_DIRSIZE            256
+#define DEF_FFACTOR            65536
+#define MIN_FFACTOR            4
+#define SPLTMAX                        8
+#define CHARKEY                        "%$sniglet^&"
+#define NUMKEY                 1038583
+#define BYTE_SHIFT             3
+#define INT_TO_BYTE            2
+#define INT_BYTE_SHIFT         5
+#define ALL_SET                        ((uint32_t)0xFFFFFFFF)
+#define ALL_CLEAR              0
+
+#define PTROF(X)       ((BUFHEAD *)(void *)((u_long)(X)&~0x3))
+#define ISMOD(X)       ((uint32_t)(u_long)(X)&0x1)
+#define DOMOD(X)       ((X) = (char *)(void *)((u_long)(X)|0x1))
+#define ISDISK(X)      ((uint32_t)(u_long)(X)&0x2)
+#define DODISK(X)      ((X) = (char *)(void *)((u_long)(X)|0x2))
+
+#define BITS_PER_MAP   32
+
+/* Given the address of the beginning of a big map, clear/set the nth bit */
+#define CLRBIT(A, N)   ((A)[(N)/BITS_PER_MAP] &= ~(1<<((N)%BITS_PER_MAP)))
+#define SETBIT(A, N)   ((A)[(N)/BITS_PER_MAP] |= (1<<((N)%BITS_PER_MAP)))
+#define ISSET(A, N)    ((A)[(N)/BITS_PER_MAP] & (1<<((N)%BITS_PER_MAP)))
+
+/* Overflow management */
+/*
+ * Overflow page numbers are allocated per split point.  At each doubling of
+ * the table, we can allocate extra pages.  So, an overflow page number has
+ * the top 5 bits indicate which split point and the lower 11 bits indicate
+ * which page at that split point is indicated (pages within split points are
+ * numberered starting with 1).
+ */
+
+#define SPLITSHIFT     11
+#define SPLITMASK      0x7FF
+#define SPLITNUM(N)    (((uint32_t)(N)) >> SPLITSHIFT)
+#define OPAGENUM(N)    ((N) & SPLITMASK)
+#define        OADDR_OF(S,O)   ((uint32_t)((uint32_t)(S) << SPLITSHIFT) + (O))
+
+#define BUCKET_TO_PAGE(B) \
+       (B) + hashp->HDRPAGES + \
+       ((B) ? hashp->SPARES[__log2((uint32_t)((B)+1))-1] : 0)
+#define OADDR_TO_PAGE(B)       \
+       BUCKET_TO_PAGE ( (1 << SPLITNUM((B))) -1 ) + OPAGENUM((B));
+
+/*
+ * page.h contains a detailed description of the page format.
+ *
+ * Normally, keys and data are accessed from offset tables in the top of
+ * each page which point to the beginning of the key and data.  There are
+ * four flag values which may be stored in these offset tables which indicate
+ * the following:
+ *
+ *
+ * OVFLPAGE    Rather than a key data pair, this pair contains
+ *             the address of an overflow page.  The format of
+ *             the pair is:
+ *                 OVERFLOW_PAGE_NUMBER OVFLPAGE
+ *
+ * PARTIAL_KEY This must be the first key/data pair on a page
+ *             and implies that page contains only a partial key.
+ *             That is, the key is too big to fit on a single page
+ *             so it starts on this page and continues on the next.
+ *             The format of the page is:
+ *                 KEY_OFF PARTIAL_KEY OVFL_PAGENO OVFLPAGE
+ *             
+ *                 KEY_OFF -- offset of the beginning of the key
+ *                 PARTIAL_KEY -- 1
+ *                 OVFL_PAGENO - page number of the next overflow page
+ *                 OVFLPAGE -- 0
+ *
+ * FULL_KEY    This must be the first key/data pair on the page.  It
+ *             is used in two cases.
+ *
+ *             Case 1:
+ *                 There is a complete key on the page but no data
+ *                 (because it wouldn't fit).  The next page contains
+ *                 the data.
+ *
+ *                 Page format it:
+ *                 KEY_OFF FULL_KEY OVFL_PAGENO OVFL_PAGE
+ *
+ *                 KEY_OFF -- offset of the beginning of the key
+ *                 FULL_KEY -- 2
+ *                 OVFL_PAGENO - page number of the next overflow page
+ *                 OVFLPAGE -- 0
+ *
+ *             Case 2:
+ *                 This page contains no key, but part of a large
+ *                 data field, which is continued on the next page.
+ *
+ *                 Page format it:
+ *                 DATA_OFF FULL_KEY OVFL_PAGENO OVFL_PAGE
+ *
+ *                 KEY_OFF -- offset of the beginning of the data on
+ *                             this page
+ *                 FULL_KEY -- 2
+ *                 OVFL_PAGENO - page number of the next overflow page
+ *                 OVFLPAGE -- 0
+ *
+ * FULL_KEY_DATA 
+ *             This must be the first key/data pair on the page.
+ *             There are two cases:
+ *
+ *             Case 1:
+ *                 This page contains a key and the beginning of the
+ *                 data field, but the data field is continued on the
+ *                 next page.
+ *
+ *                 Page format is:
+ *                 KEY_OFF FULL_KEY_DATA OVFL_PAGENO DATA_OFF
+ *
+ *                 KEY_OFF -- offset of the beginning of the key
+ *                 FULL_KEY_DATA -- 3
+ *                 OVFL_PAGENO - page number of the next overflow page
+ *                 DATA_OFF -- offset of the beginning of the data
+ *
+ *             Case 2:
+ *                 This page contains the last page of a big data pair.
+ *                 There is no key, only the  tail end of the data
+ *                 on this page.
+ *
+ *                 Page format is:
+ *                 DATA_OFF FULL_KEY_DATA <OVFL_PAGENO> <OVFLPAGE>
+ *
+ *                 DATA_OFF -- offset of the beginning of the data on
+ *                             this page
+ *                 FULL_KEY_DATA -- 3
+ *                 OVFL_PAGENO - page number of the next overflow page
+ *                 OVFLPAGE -- 0
+ *
+ *                 OVFL_PAGENO and OVFLPAGE are optional (they are
+ *                 not present if there is no next page).
+ */
+
+#define OVFLPAGE       0
+#define PARTIAL_KEY    1
+#define FULL_KEY       2
+#define FULL_KEY_DATA  3
+#define        REAL_KEY        4
+
+/* Short hands for accessing structure */
+#define BSIZE          hdr.bsize
+#define BSHIFT         hdr.bshift
+#define DSIZE          hdr.dsize
+#define SGSIZE         hdr.ssize
+#define SSHIFT         hdr.sshift
+#define LORDER         hdr.lorder
+#define OVFL_POINT     hdr.ovfl_point
+#define        LAST_FREED      hdr.last_freed
+#define MAX_BUCKET     hdr.max_bucket
+#define FFACTOR                hdr.ffactor
+#define HIGH_MASK      hdr.high_mask
+#define LOW_MASK       hdr.low_mask
+#define NKEYS          hdr.nkeys
+#define HDRPAGES       hdr.hdrpages
+#define SPARES         hdr.spares
+#define BITMAPS                hdr.bitmaps
+#define VERSION                hdr.version
+#define MAGIC          hdr.magic
+#define NEXT_FREE      hdr.next_free
+#define H_CHARKEY      hdr.h_charkey
diff --git a/lib/nbsd_libc/db/hash/hash_bigkey.c b/lib/nbsd_libc/db/hash/hash_bigkey.c
new file mode 100644 (file)
index 0000000..5c6fc9b
--- /dev/null
@@ -0,0 +1,674 @@
+/*     $NetBSD: hash_bigkey.c,v 1.23 2009/02/12 06:33:13 lukem Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Margo Seltzer.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: hash_bigkey.c,v 1.23 2009/02/12 06:33:13 lukem Exp $");
+
+/*
+ * PACKAGE: hash
+ * DESCRIPTION:
+ *     Big key/data handling for the hashing package.
+ *
+ * ROUTINES:
+ * External
+ *     __big_keydata
+ *     __big_split
+ *     __big_insert
+ *     __big_return
+ *     __big_delete
+ *     __find_last_page
+ * Internal
+ *     collect_key
+ *     collect_data
+ */
+
+#include <sys/param.h>
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include <db.h>
+#include "hash.h"
+#include "page.h"
+#include "extern.h"
+
+static int collect_key(HTAB *, BUFHEAD *, int, DBT *, int);
+static int collect_data(HTAB *, BUFHEAD *, int, int);
+
+/*
+ * Big_insert
+ *
+ * You need to do an insert and the key/data pair is too big
+ *
+ * Returns:
+ * 0 ==> OK
+ *-1 ==> ERROR
+ */
+int
+__big_insert(HTAB *hashp, BUFHEAD *bufp, const DBT *key, const DBT *val)
+{
+       uint16_t *p, n;
+       size_t key_size, val_size;
+       uint16_t space, move_bytes, off;
+       char *cp, *key_data, *val_data;
+       size_t temp;
+
+       cp = bufp->page;                /* Character pointer of p. */
+       p = (uint16_t *)(void *)cp;
+
+       key_data = (char *)key->data;
+       _DBFIT(key->size, int);
+       key_size = key->size;
+       val_data = (char *)val->data;
+       _DBFIT(val->size, int);
+       val_size = val->size;
+
+       /* First move the Key */
+       
+       temp = FREESPACE(p) - BIGOVERHEAD;
+       _DBFIT(temp, uint16_t);
+       space = (uint16_t)temp;
+       while (key_size) {
+               move_bytes = MIN(space, key_size);
+               off = OFFSET(p) - move_bytes;
+               memmove(cp + off, key_data, (size_t)move_bytes);
+               key_size -= move_bytes;
+               key_data += move_bytes;
+               n = p[0];
+               p[++n] = off;
+               p[0] = ++n;
+               temp = off - PAGE_META(n);
+               _DBFIT(temp, uint16_t);
+               FREESPACE(p) = (uint16_t)temp;
+               OFFSET(p) = off;
+               p[n] = PARTIAL_KEY;
+               bufp = __add_ovflpage(hashp, bufp);
+               if (!bufp)
+                       return (-1);
+               n = p[0];
+               if (!key_size) {
+                       space = FREESPACE(p);
+                       if (space) {
+                               move_bytes = MIN(space, val_size);
+                               /*
+                                * If the data would fit exactly in the
+                                * remaining space, we must overflow it to the
+                                * next page; otherwise the invariant that the
+                                * data must end on a page with FREESPACE
+                                * non-zero would fail.
+                                */
+                               if (space == val_size && val_size == val->size)
+                                       goto toolarge;
+                               off = OFFSET(p) - move_bytes;
+                               memmove(cp + off, val_data, (size_t)move_bytes);
+                               val_data += move_bytes;
+                               val_size -= move_bytes;
+                               p[n] = off;
+                               p[n - 2] = FULL_KEY_DATA;
+                               FREESPACE(p) = FREESPACE(p) - move_bytes;
+                               OFFSET(p) = off;
+                       } else {
+                       toolarge:
+                               p[n - 2] = FULL_KEY;
+                       }
+               }
+               p = (uint16_t *)(void *)bufp->page;
+               cp = bufp->page;
+               bufp->flags |= BUF_MOD;
+               temp = FREESPACE(p) - BIGOVERHEAD;
+               _DBFIT(temp, uint16_t);
+               space = (uint16_t)temp;
+       }
+
+       /* Now move the data */
+       temp = FREESPACE(p) - BIGOVERHEAD;
+       _DBFIT(temp, uint16_t);
+       space = (uint16_t)temp;
+       while (val_size) {
+               move_bytes = MIN(space, val_size);
+               /*
+                * Here's the hack to make sure that if the data ends on the
+                * same page as the key ends, FREESPACE is at least one.
+                */
+               if (space == val_size && val_size == val->size)
+                       move_bytes--;
+               off = OFFSET(p) - move_bytes;
+               memmove(cp + off, val_data, (size_t)move_bytes);
+               val_size -= move_bytes;
+               val_data += move_bytes;
+               n = p[0];
+               p[++n] = off;
+               p[0] = ++n;
+               temp = off - PAGE_META(n);
+               _DBFIT(temp, uint16_t);
+               FREESPACE(p) = (uint16_t)temp;
+               OFFSET(p) = off;
+               if (val_size) {
+                       p[n] = FULL_KEY;
+                       bufp = __add_ovflpage(hashp, bufp);
+                       if (!bufp)
+                               return (-1);
+                       cp = bufp->page;
+                       p = (uint16_t *)(void *)cp;
+               } else
+                       p[n] = FULL_KEY_DATA;
+               bufp->flags |= BUF_MOD;
+               temp = FREESPACE(p) - BIGOVERHEAD;
+               _DBFIT(temp, uint16_t);
+               space = (uint16_t)temp;
+       }
+       return (0);
+}
+
+/*
+ * Called when bufp's page  contains a partial key (index should be 1)
+ *
+ * All pages in the big key/data pair except bufp are freed.  We cannot
+ * free bufp because the page pointing to it is lost and we can't get rid
+ * of its pointer.
+ *
+ * Returns:
+ * 0 => OK
+ *-1 => ERROR
+ */
+int
+__big_delete(HTAB *hashp, BUFHEAD *bufp)
+{
+       BUFHEAD *last_bfp, *rbufp;
+       uint16_t *bp, pageno;
+       int key_done, n;
+       size_t temp;
+
+       rbufp = bufp;
+       last_bfp = NULL;
+       bp = (uint16_t *)(void *)bufp->page;
+       pageno = 0;
+       key_done = 0;
+
+       while (!key_done || (bp[2] != FULL_KEY_DATA)) {
+               if (bp[2] == FULL_KEY || bp[2] == FULL_KEY_DATA)
+                       key_done = 1;
+
+               /*
+                * If there is freespace left on a FULL_KEY_DATA page, then
+                * the data is short and fits entirely on this page, and this
+                * is the last page.
+                */
+               if (bp[2] == FULL_KEY_DATA && FREESPACE(bp))
+                       break;
+               pageno = bp[bp[0] - 1];
+               rbufp->flags |= BUF_MOD;
+               rbufp = __get_buf(hashp, (uint32_t)pageno, rbufp, 0);
+               if (last_bfp)
+                       __free_ovflpage(hashp, last_bfp);
+               last_bfp = rbufp;
+               if (!rbufp)
+                       return (-1);            /* Error. */
+               bp = (uint16_t *)(void *)rbufp->page;
+       }
+
+       /*
+        * If we get here then rbufp points to the last page of the big
+        * key/data pair.  Bufp points to the first one -- it should now be
+        * empty pointing to the next page after this pair.  Can't free it
+        * because we don't have the page pointing to it.
+        */
+
+       /* This is information from the last page of the pair. */
+       n = bp[0];
+       pageno = bp[n - 1];
+
+       /* Now, bp is the first page of the pair. */
+       bp = (uint16_t *)(void *)bufp->page;
+       if (n > 2) {
+               /* There is an overflow page. */
+               bp[1] = pageno;
+               bp[2] = OVFLPAGE;
+               bufp->ovfl = rbufp->ovfl;
+       } else
+               /* This is the last page. */
+               bufp->ovfl = NULL;
+       n -= 2;
+       bp[0] = n;
+       temp = hashp->BSIZE - PAGE_META(n);
+       _DBFIT(temp, uint16_t);
+       FREESPACE(bp) = (uint16_t)temp;
+       OFFSET(bp) = hashp->BSIZE;
+
+       bufp->flags |= BUF_MOD;
+       if (rbufp)
+               __free_ovflpage(hashp, rbufp);
+       if (last_bfp && last_bfp != rbufp)
+               __free_ovflpage(hashp, last_bfp);
+
+       hashp->NKEYS--;
+       return (0);
+}
+/*
+ * Returns:
+ *  0 = key not found
+ * -1 = get next overflow page
+ * -2 means key not found and this is big key/data
+ * -3 error
+ */
+int
+__find_bigpair(HTAB *hashp, BUFHEAD *bufp, int ndx, char *key, int size)
+{
+       uint16_t *bp;
+       char *p;
+       int ksize;
+       uint16_t bytes;
+       char *kkey;
+
+       bp = (uint16_t *)(void *)bufp->page;
+       p = bufp->page;
+       ksize = size;
+       kkey = key;
+
+       for (bytes = hashp->BSIZE - bp[ndx];
+           bytes <= size && bp[ndx + 1] == PARTIAL_KEY;
+           bytes = hashp->BSIZE - bp[ndx]) {
+               if (memcmp(p + bp[ndx], kkey, (size_t)bytes))
+                       return (-2);
+               kkey += bytes;
+               ksize -= bytes;
+               bufp = __get_buf(hashp, (uint32_t)bp[ndx + 2], bufp, 0);
+               if (!bufp)
+                       return (-3);
+               p = bufp->page;
+               bp = (uint16_t *)(void *)p;
+               ndx = 1;
+       }
+
+       if (bytes != ksize || memcmp(p + bp[ndx], kkey, (size_t)bytes)) {
+#ifdef HASH_STATISTICS
+               ++hash_collisions;
+#endif
+               return (-2);
+       } else
+               return (ndx);
+}
+
+/*
+ * Given the buffer pointer of the first overflow page of a big pair,
+ * find the end of the big pair
+ *
+ * This will set bpp to the buffer header of the last page of the big pair.
+ * It will return the pageno of the overflow page following the last page
+ * of the pair; 0 if there isn't any (i.e. big pair is the last key in the
+ * bucket)
+ */
+uint16_t
+__find_last_page(HTAB *hashp, BUFHEAD **bpp)
+{
+       BUFHEAD *bufp;
+       uint16_t *bp, pageno;
+       int n;
+
+       bufp = *bpp;
+       bp = (uint16_t *)(void *)bufp->page;
+       for (;;) {
+               n = bp[0];
+
+               /*
+                * This is the last page if: the tag is FULL_KEY_DATA and
+                * either only 2 entries OVFLPAGE marker is explicit there
+                * is freespace on the page.
+                */
+               if (bp[2] == FULL_KEY_DATA &&
+                   ((n == 2) || (bp[n] == OVFLPAGE) || (FREESPACE(bp))))
+                       break;
+
+               pageno = bp[n - 1];
+               bufp = __get_buf(hashp, (uint32_t)pageno, bufp, 0);
+               if (!bufp)
+                       return (0);     /* Need to indicate an error! */
+               bp = (uint16_t *)(void *)bufp->page;
+       }
+
+       *bpp = bufp;
+       if (bp[0] > 2)
+               return (bp[3]);
+       else
+               return (0);
+}
+
+/*
+ * Return the data for the key/data pair that begins on this page at this
+ * index (index should always be 1).
+ */
+int
+__big_return(HTAB *hashp, BUFHEAD *bufp, int ndx, DBT *val, int set_current)
+{
+       BUFHEAD *save_p;
+       uint16_t *bp, len, off, save_addr;
+       char *tp;
+
+       bp = (uint16_t *)(void *)bufp->page;
+       while (bp[ndx + 1] == PARTIAL_KEY) {
+               bufp = __get_buf(hashp, (uint32_t)bp[bp[0] - 1], bufp, 0);
+               if (!bufp)
+                       return (-1);
+               bp = (uint16_t *)(void *)bufp->page;
+               ndx = 1;
+       }
+
+       if (bp[ndx + 1] == FULL_KEY) {
+               bufp = __get_buf(hashp, (uint32_t)bp[bp[0] - 1], bufp, 0);
+               if (!bufp)
+                       return (-1);
+               bp = (uint16_t *)(void *)bufp->page;
+               save_p = bufp;
+               save_addr = save_p->addr;
+               off = bp[1];
+               len = 0;
+       } else
+               if (!FREESPACE(bp)) {
+                       /*
+                        * This is a hack.  We can't distinguish between
+                        * FULL_KEY_DATA that contains complete data or
+                        * incomplete data, so we require that if the data
+                        * is complete, there is at least 1 byte of free
+                        * space left.
+                        */
+                       off = bp[bp[0]];
+                       len = bp[1] - off;
+                       save_p = bufp;
+                       save_addr = bufp->addr;
+                       bufp = __get_buf(hashp, (uint32_t)bp[bp[0] - 1], bufp,
+                           0);
+                       if (!bufp)
+                               return (-1);
+                       bp = (uint16_t *)(void *)bufp->page;
+               } else {
+                       /* The data is all on one page. */
+                       tp = (char *)(void *)bp;
+                       off = bp[bp[0]];
+                       val->data = (uint8_t *)tp + off;
+                       val->size = bp[1] - off;
+                       if (set_current) {
+                               if (bp[0] == 2) {       /* No more buckets in
+                                                        * chain */
+                                       hashp->cpage = NULL;
+                                       hashp->cbucket++;
+                                       hashp->cndx = 1;
+                               } else {
+                                       hashp->cpage = __get_buf(hashp,
+                                           (uint32_t)bp[bp[0] - 1], bufp, 0);
+                                       if (!hashp->cpage)
+                                               return (-1);
+                                       hashp->cndx = 1;
+                                       if (!((uint16_t *)(void *)
+                                           hashp->cpage->page)[0]) {
+                                               hashp->cbucket++;
+                                               hashp->cpage = NULL;
+                                       }
+                               }
+                       }
+                       return (0);
+               }
+
+       val->size = collect_data(hashp, bufp, (int)len, set_current);
+       if (val->size == (size_t)-1)
+               return (-1);
+       if (save_p->addr != save_addr) {
+               /* We are pretty short on buffers. */
+               errno = EINVAL;                 /* OUT OF BUFFERS */
+               return (-1);
+       }
+       memmove(hashp->tmp_buf, (save_p->page) + off, (size_t)len);
+       val->data = (uint8_t *)hashp->tmp_buf;
+       return (0);
+}
+/*
+ * Count how big the total datasize is by recursing through the pages.  Then
+ * allocate a buffer and copy the data as you recurse up.
+ */
+static int
+collect_data(HTAB *hashp, BUFHEAD *bufp, int len, int set)
+{
+       uint16_t *bp;
+       char *p;
+       BUFHEAD *xbp;
+       uint16_t save_addr;
+       int mylen, totlen;
+
+       p = bufp->page;
+       bp = (uint16_t *)(void *)p;
+       mylen = hashp->BSIZE - bp[1];
+       save_addr = bufp->addr;
+
+       if (bp[2] == FULL_KEY_DATA) {           /* End of Data */
+               totlen = len + mylen;
+               if (hashp->tmp_buf)
+                       free(hashp->tmp_buf);
+               if ((hashp->tmp_buf = calloc(1, (size_t)totlen)) == NULL)
+                       return (-1);
+               if (set) {
+                       hashp->cndx = 1;
+                       if (bp[0] == 2) {       /* No more buckets in chain */
+                               hashp->cpage = NULL;
+                               hashp->cbucket++;
+                       } else {
+                               hashp->cpage =
+                                   __get_buf(hashp, (uint32_t)bp[bp[0] - 1],
+                                   bufp, 0);
+                               if (!hashp->cpage)
+                                       return (-1);
+                               else if (!((uint16_t *)(void *)hashp->cpage->page)[0]) {
+                                       hashp->cbucket++;
+                                       hashp->cpage = NULL;
+                               }
+                       }
+               }
+       } else {
+               xbp = __get_buf(hashp, (uint32_t)bp[bp[0] - 1], bufp, 0);
+               if (!xbp || ((totlen =
+                   collect_data(hashp, xbp, len + mylen, set)) < 1))
+                       return (-1);
+       }
+       if (bufp->addr != save_addr) {
+               errno = EINVAL;                 /* Out of buffers. */
+               return (-1);
+       }
+       memmove(&hashp->tmp_buf[len], (bufp->page) + bp[1], (size_t)mylen);
+       return (totlen);
+}
+
+/*
+ * Fill in the key and data for this big pair.
+ */
+int
+__big_keydata(HTAB *hashp, BUFHEAD *bufp, DBT *key, DBT *val, int set)
+{
+       key->size = collect_key(hashp, bufp, 0, val, set);
+       if (key->size == (size_t)-1)
+               return (-1);
+       key->data = (uint8_t *)hashp->tmp_key;
+       return (0);
+}
+
+/*
+ * Count how big the total key size is by recursing through the pages.  Then
+ * collect the data, allocate a buffer and copy the key as you recurse up.
+ */
+static int
+collect_key(HTAB *hashp, BUFHEAD *bufp, int len, DBT *val, int set)
+{
+       BUFHEAD *xbp;
+       char *p;
+       int mylen, totlen;
+       uint16_t *bp, save_addr;
+
+       p = bufp->page;
+       bp = (uint16_t *)(void *)p;
+       mylen = hashp->BSIZE - bp[1];
+
+       save_addr = bufp->addr;
+       totlen = len + mylen;
+       if (bp[2] == FULL_KEY || bp[2] == FULL_KEY_DATA) {    /* End of Key. */
+               if (hashp->tmp_key != NULL)
+                       free(hashp->tmp_key);
+               if ((hashp->tmp_key = calloc(1, (size_t)totlen)) == NULL)
+                       return (-1);
+               if (__big_return(hashp, bufp, 1, val, set))
+                       return (-1);
+       } else {
+               xbp = __get_buf(hashp, (uint32_t)bp[bp[0] - 1], bufp, 0);
+               if (!xbp || ((totlen =
+                   collect_key(hashp, xbp, totlen, val, set)) < 1))
+                       return (-1);
+       }
+       if (bufp->addr != save_addr) {
+               errno = EINVAL;         /* MIS -- OUT OF BUFFERS */
+               return (-1);
+       }
+       memmove(&hashp->tmp_key[len], (bufp->page) + bp[1], (size_t)mylen);
+       return (totlen);
+}
+
+/*
+ * Returns:
+ *  0 => OK
+ * -1 => error
+ */
+int
+__big_split(
+       HTAB *hashp,
+       BUFHEAD *op,    /* Pointer to where to put keys that go in old bucket */
+       BUFHEAD *np,    /* Pointer to new bucket page */
+                       /* Pointer to first page containing the big key/data */
+       BUFHEAD *big_keyp,
+       int addr,       /* Address of big_keyp */
+       uint32_t   obucket,/* Old Bucket */
+       SPLIT_RETURN *ret
+)
+{
+       BUFHEAD *tmpp;
+       uint16_t *tp;
+       BUFHEAD *bp;
+       DBT key, val;
+       uint32_t change;
+       uint16_t free_space, n, off;
+       size_t temp;
+
+       bp = big_keyp;
+
+       /* Now figure out where the big key/data goes */
+       if (__big_keydata(hashp, big_keyp, &key, &val, 0))
+               return (-1);
+       change = (__call_hash(hashp, key.data, (int)key.size) != obucket);
+
+       if ((ret->next_addr = __find_last_page(hashp, &big_keyp)) != 0) {
+               if (!(ret->nextp =
+                   __get_buf(hashp, (uint32_t)ret->next_addr, big_keyp, 0)))
+                       return (-1);
+       } else
+               ret->nextp = NULL;
+
+       /* Now make one of np/op point to the big key/data pair */
+       _DIAGASSERT(np->ovfl == NULL);
+       if (change)
+               tmpp = np;
+       else
+               tmpp = op;
+
+       tmpp->flags |= BUF_MOD;
+#ifdef DEBUG1
+       (void)fprintf(stderr,
+           "BIG_SPLIT: %d->ovfl was %d is now %d\n", tmpp->addr,
+           (tmpp->ovfl ? tmpp->ovfl->addr : 0), (bp ? bp->addr : 0));
+#endif
+       tmpp->ovfl = bp;        /* one of op/np point to big_keyp */
+       tp = (uint16_t *)(void *)tmpp->page;
+       _DIAGASSERT(FREESPACE(tp) >= OVFLSIZE);
+       n = tp[0];
+       off = OFFSET(tp);
+       free_space = FREESPACE(tp);
+       tp[++n] = (uint16_t)addr;
+       tp[++n] = OVFLPAGE;
+       tp[0] = n;
+       OFFSET(tp) = off;
+       temp = free_space - OVFLSIZE;
+       _DBFIT(temp, uint16_t);
+       FREESPACE(tp) = (uint16_t)temp;
+
+       /*
+        * Finally, set the new and old return values. BIG_KEYP contains a
+        * pointer to the last page of the big key_data pair. Make sure that
+        * big_keyp has no following page (2 elements) or create an empty
+        * following page.
+        */
+
+       ret->newp = np;
+       ret->oldp = op;
+
+       tp = (uint16_t *)(void *)big_keyp->page;
+       big_keyp->flags |= BUF_MOD;
+       if (tp[0] > 2) {
+               /*
+                * There may be either one or two offsets on this page.  If
+                * there is one, then the overflow page is linked on normally
+                * and tp[4] is OVFLPAGE.  If there are two, tp[4] contains
+                * the second offset and needs to get stuffed in after the
+                * next overflow page is added.
+                */
+               n = tp[4];
+               free_space = FREESPACE(tp);
+               off = OFFSET(tp);
+               tp[0] -= 2;
+               temp = free_space + OVFLSIZE;
+               _DBFIT(temp, uint16_t);
+               FREESPACE(tp) = (uint16_t)temp;
+               OFFSET(tp) = off;
+               tmpp = __add_ovflpage(hashp, big_keyp);
+               if (!tmpp)
+                       return (-1);
+               tp[4] = n;
+       } else
+               tmpp = big_keyp;
+
+       if (change)
+               ret->newp = tmpp;
+       else
+               ret->oldp = tmpp;
+       return (0);
+}
diff --git a/lib/nbsd_libc/db/hash/hash_buf.c b/lib/nbsd_libc/db/hash/hash_buf.c
new file mode 100644 (file)
index 0000000..6469736
--- /dev/null
@@ -0,0 +1,338 @@
+/*     $NetBSD: hash_buf.c,v 1.18 2009/04/23 22:09:23 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Margo Seltzer.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: hash_buf.c,v 1.18 2009/04/23 22:09:23 christos Exp $");
+
+/*
+ * PACKAGE: hash
+ *
+ * DESCRIPTION:
+ *     Contains buffer management
+ *
+ * ROUTINES:
+ * External
+ *     __buf_init
+ *     __get_buf
+ *     __buf_free
+ *     __reclaim_buf
+ * Internal
+ *     newbuf
+ */
+
+#include <sys/param.h>
+
+#include <errno.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include <db.h>
+#include "hash.h"
+#include "page.h"
+#include "extern.h"
+
+static BUFHEAD *newbuf(HTAB *, uint32_t, BUFHEAD *);
+
+/* Unlink B from its place in the lru */
+#define BUF_REMOVE(B) { \
+       (B)->prev->next = (B)->next; \
+       (B)->next->prev = (B)->prev; \
+}
+
+/* Insert B after P */
+#define BUF_INSERT(B, P) { \
+       (B)->next = (P)->next; \
+       (B)->prev = (P); \
+       (P)->next = (B); \
+       (B)->next->prev = (B); \
+}
+
+#define        MRU     hashp->bufhead.next
+#define        LRU     hashp->bufhead.prev
+
+#define MRU_INSERT(B)  BUF_INSERT((B), &hashp->bufhead)
+#define LRU_INSERT(B)  BUF_INSERT((B), LRU)
+
+/*
+ * We are looking for a buffer with address "addr".  If prev_bp is NULL, then
+ * address is a bucket index.  If prev_bp is not NULL, then it points to the
+ * page previous to an overflow page that we are trying to find.
+ *
+ * CAVEAT:  The buffer header accessed via prev_bp's ovfl field may no longer
+ * be valid.  Therefore, you must always verify that its address matches the
+ * address you are seeking.
+ */
+BUFHEAD *
+__get_buf(
+       HTAB *hashp,
+       uint32_t addr,
+       BUFHEAD *prev_bp,
+       int newpage     /* If prev_bp set, indicates a new overflow page. */
+)
+{
+       BUFHEAD *bp;
+       uint32_t is_disk_mask;
+       int is_disk, segment_ndx = 0;   /* pacify gcc */
+       SEGMENT segp = NULL;    /* pacify gcc */
+
+       is_disk = 0;
+       is_disk_mask = 0;
+       if (prev_bp) {
+               bp = prev_bp->ovfl;
+               if (!bp || (bp->addr != addr))
+                       bp = NULL;
+               if (!newpage)
+                       is_disk = BUF_DISK;
+       } else {
+               /* Grab buffer out of directory */
+               segment_ndx = addr & (hashp->SGSIZE - 1);
+
+               /* valid segment ensured by __call_hash() */
+               segp = hashp->dir[addr >> hashp->SSHIFT];
+               _DIAGASSERT(segp != NULL);
+               bp = PTROF(segp[segment_ndx]);
+               is_disk_mask = ISDISK(segp[segment_ndx]);
+               is_disk = is_disk_mask || !hashp->new_file;
+       }
+
+       if (!bp) {
+               bp = newbuf(hashp, addr, prev_bp);
+               if (!bp ||
+                   __get_page(hashp, bp->page, addr, !prev_bp, is_disk, 0))
+                       return (NULL);
+               if (!prev_bp)
+                       segp[segment_ndx] =
+                           (BUFHEAD *)(void *)((u_long)bp | is_disk_mask);
+       } else {
+               BUF_REMOVE(bp);
+               MRU_INSERT(bp);
+       }
+       return (bp);
+}
+
+/*
+ * We need a buffer for this page. Either allocate one, or evict a resident
+ * one (if we have as many buffers as we're allowed) and put this one in.
+ *
+ * If newbuf finds an error (returning NULL), it also sets errno.
+ */
+static BUFHEAD *
+newbuf(HTAB *hashp, uint32_t addr, BUFHEAD *prev_bp)
+{
+       BUFHEAD *bp;            /* The buffer we're going to use */
+       BUFHEAD *xbp;           /* Temp pointer */
+       BUFHEAD *next_xbp;
+       SEGMENT segp;
+       int segment_ndx;
+       uint16_t oaddr, *shortp;
+
+       oaddr = 0;
+       bp = LRU;
+       /*
+        * If LRU buffer is pinned, the buffer pool is too small. We need to
+        * allocate more buffers.
+        */
+       if (hashp->nbufs || (bp->flags & BUF_PIN)) {
+               /* Allocate a new one */
+               if ((bp = calloc(1, sizeof(BUFHEAD))) == NULL)
+                       return (NULL);
+               if ((bp->page = calloc(1, (size_t)hashp->BSIZE)) == NULL) {
+                       free(bp);
+                       return (NULL);
+               }
+               if (hashp->nbufs)
+                       hashp->nbufs--;
+       } else {
+               /* Kick someone out */
+               BUF_REMOVE(bp);
+               /*
+                * If this is an overflow page with addr 0, it's already been
+                * flushed back in an overflow chain and initialized.
+                */
+               if ((bp->addr != 0) || (bp->flags & BUF_BUCKET)) {
+                       /*
+                        * Set oaddr before __put_page so that you get it
+                        * before bytes are swapped.
+                        */
+                       shortp = (uint16_t *)(void *)bp->page;
+                       if (shortp[0])
+                               oaddr = shortp[shortp[0] - 1];
+                       if ((bp->flags & BUF_MOD) && __put_page(hashp, bp->page,
+                           bp->addr, (int)IS_BUCKET(bp->flags), 0))
+                               return (NULL);
+                       /*
+                        * Update the pointer to this page (i.e. invalidate it).
+                        *
+                        * If this is a new file (i.e. we created it at open
+                        * time), make sure that we mark pages which have been
+                        * written to disk so we retrieve them from disk later,
+                        * rather than allocating new pages.
+                        */
+                       if (IS_BUCKET(bp->flags)) {
+                               segment_ndx = bp->addr & (hashp->SGSIZE - 1);
+                               segp = hashp->dir[bp->addr >> hashp->SSHIFT];
+                               _DIAGASSERT(segp != NULL);
+
+                               if (hashp->new_file &&
+                                   ((bp->flags & BUF_MOD) ||
+                                   ISDISK(segp[segment_ndx])))
+                                       segp[segment_ndx] = (BUFHEAD *)BUF_DISK;
+                               else
+                                       segp[segment_ndx] = NULL;
+                       }
+                       /*
+                        * Since overflow pages can only be access by means of
+                        * their bucket, free overflow pages associated with
+                        * this bucket.
+                        */
+                       for (xbp = bp; xbp->ovfl;) {
+                               next_xbp = xbp->ovfl;
+                               xbp->ovfl = 0;
+                               xbp = next_xbp;
+
+                               /* Check that ovfl pointer is up date. */
+                               if (IS_BUCKET(xbp->flags) ||
+                                   (oaddr != xbp->addr))
+                                       break;
+
+                               shortp = (uint16_t *)(void *)xbp->page;
+                               if (shortp[0])
+                                       /* set before __put_page */
+                                       oaddr = shortp[shortp[0] - 1];
+                               if ((xbp->flags & BUF_MOD) && __put_page(hashp,
+                                   xbp->page, xbp->addr, 0, 0))
+                                       return (NULL);
+                               xbp->addr = 0;
+                               xbp->flags = 0;
+                               BUF_REMOVE(xbp);
+                               LRU_INSERT(xbp);
+                       }
+               }
+       }
+
+       /* Now assign this buffer */
+       bp->addr = addr;
+#ifdef DEBUG1
+       (void)fprintf(stderr, "NEWBUF1: %d->ovfl was %d is now %d\n",
+           bp->addr, (bp->ovfl ? bp->ovfl->addr : 0), 0);
+#endif
+       bp->ovfl = NULL;
+       if (prev_bp) {
+               /*
+                * If prev_bp is set, this is an overflow page, hook it in to
+                * the buffer overflow links.
+                */
+#ifdef DEBUG1
+               (void)fprintf(stderr, "NEWBUF2: %d->ovfl was %d is now %d\n",
+                   prev_bp->addr, (prev_bp->ovfl ? prev_bp->ovfl->addr : 0),
+                   (bp ? bp->addr : 0));
+#endif
+               prev_bp->ovfl = bp;
+               bp->flags = 0;
+       } else
+               bp->flags = BUF_BUCKET;
+       MRU_INSERT(bp);
+       return (bp);
+}
+
+void
+__buf_init(HTAB *hashp, u_int nbytes)
+{
+       BUFHEAD *bfp;
+       int npages;
+
+       bfp = &(hashp->bufhead);
+       npages = (unsigned int)(nbytes + hashp->BSIZE - 1) >> hashp->BSHIFT;
+       npages = MAX(npages, MIN_BUFFERS);
+
+       hashp->nbufs = npages;
+       bfp->next = bfp;
+       bfp->prev = bfp;
+       /*
+        * This space is calloc'd so these are already null.
+        *
+        * bfp->ovfl = NULL;
+        * bfp->flags = 0;
+        * bfp->page = NULL;
+        * bfp->addr = 0;
+        */
+}
+
+int
+__buf_free(HTAB *hashp, int do_free, int to_disk)
+{
+       BUFHEAD *bp;
+
+       /* Need to make sure that buffer manager has been initialized */
+       if (!LRU)
+               return (0);
+       for (bp = LRU; bp != &hashp->bufhead;) {
+               /* Check that the buffer is valid */
+               if (bp->addr || IS_BUCKET(bp->flags)) {
+                       if (to_disk && (bp->flags & BUF_MOD) &&
+                           __put_page(hashp, bp->page,
+                           bp->addr, IS_BUCKET(bp->flags), 0))
+                               return (-1);
+               }
+               /* Check if we are freeing stuff */
+               if (do_free) {
+                       if (bp->page) {
+                               (void)memset(bp->page, 0, (size_t)hashp->BSIZE);
+                               free(bp->page);
+                       }
+                       BUF_REMOVE(bp);
+                       free(bp);
+                       bp = LRU;
+               } else
+                       bp = bp->prev;
+       }
+       return (0);
+}
+
+void
+__reclaim_buf(HTAB *hashp, BUFHEAD *bp)
+{
+       bp->ovfl = 0;
+       bp->addr = 0;
+       bp->flags = 0;
+       BUF_REMOVE(bp);
+       LRU_INSERT(bp);
+}
diff --git a/lib/nbsd_libc/db/hash/hash_func.c b/lib/nbsd_libc/db/hash/hash_func.c
new file mode 100644 (file)
index 0000000..6dd136d
--- /dev/null
@@ -0,0 +1,208 @@
+/*     $NetBSD: hash_func.c,v 1.13 2008/09/10 17:52:35 joerg Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Margo Seltzer.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: hash_func.c,v 1.13 2008/09/10 17:52:35 joerg Exp $");
+
+#include <sys/types.h>
+
+#include <db.h>
+#include "hash.h"
+#include "page.h"
+#include "extern.h"
+
+#if 0
+static uint32_t hash1(const void *, size_t) __attribute__((__unused__));
+static uint32_t hash2(const void *, size_t) __attribute__((__unused__));
+static uint32_t hash3(const void *, size_t) __attribute__((__unused__));
+#endif
+static uint32_t hash4(const void *, size_t) __attribute__((__unused__));
+
+/* Global default hash function */
+uint32_t (*__default_hash)(const void *, size_t) = hash4;
+#if 0
+/*
+ * HASH FUNCTIONS
+ *
+ * Assume that we've already split the bucket to which this key hashes,
+ * calculate that bucket, and check that in fact we did already split it.
+ *
+ * This came from ejb's hsearch.
+ */
+
+#define PRIME1         37
+#define PRIME2         1048583
+
+static uint32_t
+hash1(const void *keyarg, size_t len)
+{
+       const uint8_t *key;
+       uint32_t h;
+
+       /* Convert string to integer */
+       for (key = keyarg, h = 0; len--;)
+               h = h * PRIME1 ^ (*key++ - ' ');
+       h %= PRIME2;
+       return (h);
+}
+
+/*
+ * Phong's linear congruential hash
+ */
+#define dcharhash(h, c)        ((h) = 0x63c63cd9*(h) + 0x9c39c33d + (c))
+
+static uint32_t
+hash2(const void *keyarg, size_t len)
+{
+       const uint8_t *e, *key;
+       uint32_t h;
+       uint8_t c;
+
+       key = keyarg;
+       e = key + len;
+       for (h = 0; key != e;) {
+               c = *key++;
+               if (!c && key > e)
+                       break;
+               dcharhash(h, c);
+       }
+       return (h);
+}
+
+/*
+ * This is INCREDIBLY ugly, but fast.  We break the string up into 8 byte
+ * units.  On the first time through the loop we get the "leftover bytes"
+ * (strlen % 8).  On every other iteration, we perform 8 HASHC's so we handle
+ * all 8 bytes.  Essentially, this saves us 7 cmp & branch instructions.  If
+ * this routine is heavily used enough, it's worth the ugly coding.
+ *
+ * OZ's original sdbm hash
+ */
+static uint32_t
+hash3(const void *keyarg, size_t len)
+{
+       const uint8_t *key;
+       size_t loop;
+       uint32_t h;
+
+#define HASHC   h = *key++ + 65599 * h
+
+       h = 0;
+       key = keyarg;
+       if (len > 0) {
+               loop = (len + 8 - 1) >> 3;
+
+               switch (len & (8 - 1)) {
+               case 0:
+                       do {
+                               HASHC;
+                               /* FALLTHROUGH */
+               case 7:
+                               HASHC;
+                               /* FALLTHROUGH */
+               case 6:
+                               HASHC;
+                               /* FALLTHROUGH */
+               case 5:
+                               HASHC;
+                               /* FALLTHROUGH */
+               case 4:
+                               HASHC;
+                               /* FALLTHROUGH */
+               case 3:
+                               HASHC;
+                               /* FALLTHROUGH */
+               case 2:
+                               HASHC;
+                               /* FALLTHROUGH */
+               case 1:
+                               HASHC;
+                       } while (--loop);
+               }
+       }
+       return (h);
+}
+#endif
+
+/* Hash function from Chris Torek. */
+static uint32_t
+hash4(const void *keyarg, size_t len)
+{
+       const uint8_t *key;
+       size_t loop;
+       uint32_t h;
+
+#define HASH4a   h = (h << 5) - h + *key++;
+#define HASH4b   h = (h << 5) + h + *key++;
+#define HASH4 HASH4b
+
+       h = 0;
+       key = keyarg;
+       if (len > 0) {
+               loop = (len + 8 - 1) >> 3;
+
+               switch (len & (8 - 1)) {
+               case 0:
+                       do {
+                               HASH4;
+                               /* FALLTHROUGH */
+               case 7:
+                               HASH4;
+                               /* FALLTHROUGH */
+               case 6:
+                               HASH4;
+                               /* FALLTHROUGH */
+               case 5:
+                               HASH4;
+                               /* FALLTHROUGH */
+               case 4:
+                               HASH4;
+                               /* FALLTHROUGH */
+               case 3:
+                               HASH4;
+                               /* FALLTHROUGH */
+               case 2:
+                               HASH4;
+                               /* FALLTHROUGH */
+               case 1:
+                               HASH4;
+                       } while (--loop);
+               }
+       }
+       return (h);
+}
diff --git a/lib/nbsd_libc/db/hash/hash_log2.c b/lib/nbsd_libc/db/hash/hash_log2.c
new file mode 100644 (file)
index 0000000..74343da
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: hash_log2.c,v 1.13 2008/09/11 12:33:55 joerg Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Margo Seltzer.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: hash_log2.c,v 1.13 2008/09/11 12:33:55 joerg Exp $");
+
+#include <sys/types.h>
+
+#include <db.h>
+#include "hash.h"
+#include "page.h"
+#include "extern.h"
+
+uint32_t
+__log2(uint32_t num)
+{
+       uint32_t i, limit;
+
+       if (num == 0)
+               return 0;
+       --num;
+
+       limit = 0;
+       for (i = 0; limit < num; limit = limit * 2 + 1, i++)
+               continue;
+       return (i);
+}
diff --git a/lib/nbsd_libc/db/hash/hash_page.c b/lib/nbsd_libc/db/hash/hash_page.c
new file mode 100644 (file)
index 0000000..e79dfd9
--- /dev/null
@@ -0,0 +1,962 @@
+/*     $NetBSD: hash_page.c,v 1.23 2008/09/11 12:58:00 joerg Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Margo Seltzer.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: hash_page.c,v 1.23 2008/09/11 12:58:00 joerg Exp $");
+
+/*
+ * PACKAGE:  hashing
+ *
+ * DESCRIPTION:
+ *     Page manipulation for hashing package.
+ *
+ * ROUTINES:
+ *
+ * External
+ *     __get_page
+ *     __add_ovflpage
+ * Internal
+ *     overflow_page
+ *     open_temp
+ */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <paths.h>
+#include <assert.h>
+
+#include <db.h>
+#include "hash.h"
+#include "page.h"
+#include "extern.h"
+
+static uint32_t        *fetch_bitmap(HTAB *, int);
+static uint32_t         first_free(uint32_t);
+static int      open_temp(HTAB *);
+static uint16_t         overflow_page(HTAB *);
+static void     putpair(char *, const DBT *, const DBT *);
+static void     squeeze_key(uint16_t *, const DBT *, const DBT *);
+static int      ugly_split(HTAB *, uint32_t, BUFHEAD *, BUFHEAD *, int, int);
+
+#define        PAGE_INIT(P) { \
+       ((uint16_t *)(void *)(P))[0] = 0; \
+       temp = 3 * sizeof(uint16_t); \
+       _DIAGASSERT(hashp->BSIZE >= temp); \
+       ((uint16_t *)(void *)(P))[1] = (uint16_t)(hashp->BSIZE - temp); \
+       ((uint16_t *)(void *)(P))[2] = hashp->BSIZE; \
+}
+
+/*
+ * This is called AFTER we have verified that there is room on the page for
+ * the pair (PAIRFITS has returned true) so we go right ahead and start moving
+ * stuff on.
+ */
+static void
+putpair(char *p, const DBT *key, const DBT *val)
+{
+       uint16_t *bp, n, off;
+       size_t temp;
+
+       bp = (uint16_t *)(void *)p;
+
+       /* Enter the key first. */
+       n = bp[0];
+
+       temp = OFFSET(bp);
+       _DIAGASSERT(temp >= key->size);
+       off = (uint16_t)(temp - key->size);
+       memmove(p + off, key->data, key->size);
+       bp[++n] = off;
+
+       /* Now the data. */
+       _DIAGASSERT(off >= val->size);
+       off -= (uint16_t)val->size;
+       memmove(p + off, val->data, val->size);
+       bp[++n] = off;
+
+       /* Adjust page info. */
+       bp[0] = n;
+       temp = (n + 3) * sizeof(uint16_t);
+       _DIAGASSERT(off >= temp);
+       bp[n + 1] = (uint16_t)(off - temp);
+       bp[n + 2] = off;
+}
+
+/*
+ * Returns:
+ *      0 OK
+ *     -1 error
+ */
+int
+__delpair(HTAB *hashp, BUFHEAD *bufp, int ndx)
+{
+       uint16_t *bp, newoff;
+       int n;
+       uint16_t pairlen;
+       size_t temp;
+
+       bp = (uint16_t *)(void *)bufp->page;
+       n = bp[0];
+
+       if (bp[ndx + 1] < REAL_KEY)
+               return (__big_delete(hashp, bufp));
+       if (ndx != 1)
+               newoff = bp[ndx - 1];
+       else
+               newoff = hashp->BSIZE;
+       pairlen = newoff - bp[ndx + 1];
+
+       if (ndx != (n - 1)) {
+               /* Hard Case -- need to shuffle keys */
+               int i;
+               char *src = bufp->page + (int)OFFSET(bp);
+               char *dst = src + (int)pairlen;
+               memmove(dst, src, (size_t)(bp[ndx + 1] - OFFSET(bp)));
+
+               /* Now adjust the pointers */
+               for (i = ndx + 2; i <= n; i += 2) {
+                       if (bp[i + 1] == OVFLPAGE) {
+                               bp[i - 2] = bp[i];
+                               bp[i - 1] = bp[i + 1];
+                       } else {
+                               bp[i - 2] = bp[i] + pairlen;
+                               bp[i - 1] = bp[i + 1] + pairlen;
+                       }
+               }
+       }
+       /* Finally adjust the page data */
+       bp[n] = OFFSET(bp) + pairlen;
+       temp = bp[n + 1] + pairlen + 2 * sizeof(uint16_t);
+       _DIAGASSERT(temp <= 0xffff);
+       bp[n - 1] = (uint16_t)temp;
+       bp[0] = n - 2;
+       hashp->NKEYS--;
+
+       bufp->flags |= BUF_MOD;
+       return (0);
+}
+/*
+ * Returns:
+ *      0 ==> OK
+ *     -1 ==> Error
+ */
+int
+__split_page(HTAB *hashp, uint32_t obucket, uint32_t nbucket)
+{
+       BUFHEAD *new_bufp, *old_bufp;
+       uint16_t *ino;
+       char *np;
+       DBT key, val;
+       int n, ndx, retval;
+       uint16_t copyto, diff, off, moved;
+       char *op;
+       size_t temp;
+
+       copyto = (uint16_t)hashp->BSIZE;
+       off = (uint16_t)hashp->BSIZE;
+       old_bufp = __get_buf(hashp, obucket, NULL, 0);
+       if (old_bufp == NULL)
+               return (-1);
+       new_bufp = __get_buf(hashp, nbucket, NULL, 0);
+       if (new_bufp == NULL)
+               return (-1);
+
+       old_bufp->flags |= (BUF_MOD | BUF_PIN);
+       new_bufp->flags |= (BUF_MOD | BUF_PIN);
+
+       ino = (uint16_t *)(void *)(op = old_bufp->page);
+       np = new_bufp->page;
+
+       moved = 0;
+
+       for (n = 1, ndx = 1; n < ino[0]; n += 2) {
+               if (ino[n + 1] < REAL_KEY) {
+                       retval = ugly_split(hashp, obucket, old_bufp, new_bufp,
+                           (int)copyto, (int)moved);
+                       old_bufp->flags &= ~BUF_PIN;
+                       new_bufp->flags &= ~BUF_PIN;
+                       return (retval);
+
+               }
+               key.data = (uint8_t *)op + ino[n];
+               key.size = off - ino[n];
+
+               if (__call_hash(hashp, key.data, (int)key.size) == obucket) {
+                       /* Don't switch page */
+                       diff = copyto - off;
+                       if (diff) {
+                               copyto = ino[n + 1] + diff;
+                               memmove(op + copyto, op + ino[n + 1],
+                                   (size_t)(off - ino[n + 1]));
+                               ino[ndx] = copyto + ino[n] - ino[n + 1];
+                               ino[ndx + 1] = copyto;
+                       } else
+                               copyto = ino[n + 1];
+                       ndx += 2;
+               } else {
+                       /* Switch page */
+                       val.data = (uint8_t *)op + ino[n + 1];
+                       val.size = ino[n] - ino[n + 1];
+                       putpair(np, &key, &val);
+                       moved += 2;
+               }
+
+               off = ino[n + 1];
+       }
+
+       /* Now clean up the page */
+       ino[0] -= moved;
+       temp = sizeof(uint16_t) * (ino[0] + 3);
+       _DIAGASSERT(copyto >= temp);
+       FREESPACE(ino) = (uint16_t)(copyto - temp);
+       OFFSET(ino) = copyto;
+
+#ifdef DEBUG3
+       (void)fprintf(stderr, "split %d/%d\n",
+           ((uint16_t *)np)[0] / 2,
+           ((uint16_t *)op)[0] / 2);
+#endif
+       /* unpin both pages */
+       old_bufp->flags &= ~BUF_PIN;
+       new_bufp->flags &= ~BUF_PIN;
+       return (0);
+}
+
+/*
+ * Called when we encounter an overflow or big key/data page during split
+ * handling.  This is special cased since we have to begin checking whether
+ * the key/data pairs fit on their respective pages and because we may need
+ * overflow pages for both the old and new pages.
+ *
+ * The first page might be a page with regular key/data pairs in which case
+ * we have a regular overflow condition and just need to go on to the next
+ * page or it might be a big key/data pair in which case we need to fix the
+ * big key/data pair.
+ *
+ * Returns:
+ *      0 ==> success
+ *     -1 ==> failure
+ */
+static int
+ugly_split(
+       HTAB *hashp,
+       uint32_t obucket,       /* Same as __split_page. */
+       BUFHEAD *old_bufp,
+       BUFHEAD *new_bufp,
+       int copyto,     /* First byte on page which contains key/data values. */
+       int moved       /* Number of pairs moved to new page. */
+)
+{
+       BUFHEAD *bufp;  /* Buffer header for ino */
+       uint16_t *ino;  /* Page keys come off of */
+       uint16_t *np;   /* New page */
+       uint16_t *op;   /* Page keys go on to if they aren't moving */
+       size_t temp;
+
+       BUFHEAD *last_bfp;      /* Last buf header OVFL needing to be freed */
+       DBT key, val;
+       SPLIT_RETURN ret;
+       uint16_t n, off, ov_addr, scopyto;
+       char *cino;             /* Character value of ino */
+
+       bufp = old_bufp;
+       ino = (uint16_t *)(void *)old_bufp->page;
+       np = (uint16_t *)(void *)new_bufp->page;
+       op = (uint16_t *)(void *)old_bufp->page;
+       last_bfp = NULL;
+       scopyto = (uint16_t)copyto;     /* ANSI */
+
+       n = ino[0] - 1;
+       while (n < ino[0]) {
+               if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) {
+                       if (__big_split(hashp, old_bufp,
+                           new_bufp, bufp, (int)bufp->addr, obucket, &ret))
+                               return (-1);
+                       old_bufp = ret.oldp;
+                       if (!old_bufp)
+                               return (-1);
+                       op = (uint16_t *)(void *)old_bufp->page;
+                       new_bufp = ret.newp;
+                       if (!new_bufp)
+                               return (-1);
+                       np = (uint16_t *)(void *)new_bufp->page;
+                       bufp = ret.nextp;
+                       if (!bufp)
+                               return (0);
+                       cino = (char *)bufp->page;
+                       ino = (uint16_t *)(void *)cino;
+                       last_bfp = ret.nextp;
+               } else if (ino[n + 1] == OVFLPAGE) {
+                       ov_addr = ino[n];
+                       /*
+                        * Fix up the old page -- the extra 2 are the fields
+                        * which contained the overflow information.
+                        */
+                       ino[0] -= (moved + 2);
+                       temp = sizeof(uint16_t) * (ino[0] + 3);
+                       _DIAGASSERT(scopyto >= temp);
+                       FREESPACE(ino) = (uint16_t)(scopyto - temp);
+                       OFFSET(ino) = scopyto;
+
+                       bufp = __get_buf(hashp, (uint32_t)ov_addr, bufp, 0);
+                       if (!bufp)
+                               return (-1);
+
+                       ino = (uint16_t *)(void *)bufp->page;
+                       n = 1;
+                       scopyto = hashp->BSIZE;
+                       moved = 0;
+
+                       if (last_bfp)
+                               __free_ovflpage(hashp, last_bfp);
+                       last_bfp = bufp;
+               }
+               /* Move regular sized pairs of there are any */
+               off = hashp->BSIZE;
+               for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) {
+                       cino = (char *)(void *)ino;
+                       key.data = (uint8_t *)cino + ino[n];
+                       key.size = off - ino[n];
+                       val.data = (uint8_t *)cino + ino[n + 1];
+                       val.size = ino[n] - ino[n + 1];
+                       off = ino[n + 1];
+
+                       if (__call_hash(hashp, key.data, (int)key.size) == obucket) {
+                               /* Keep on old page */
+                               if (PAIRFITS(op, (&key), (&val)))
+                                       putpair((char *)(void *)op, &key, &val);
+                               else {
+                                       old_bufp =
+                                           __add_ovflpage(hashp, old_bufp);
+                                       if (!old_bufp)
+                                               return (-1);
+                                       op = (uint16_t *)(void *)old_bufp->page;
+                                       putpair((char *)(void *)op, &key, &val);
+                               }
+                               old_bufp->flags |= BUF_MOD;
+                       } else {
+                               /* Move to new page */
+                               if (PAIRFITS(np, (&key), (&val)))
+                                       putpair((char *)(void *)np, &key, &val);
+                               else {
+                                       new_bufp =
+                                           __add_ovflpage(hashp, new_bufp);
+                                       if (!new_bufp)
+                                               return (-1);
+                                       np = (uint16_t *)(void *)new_bufp->page;
+                                       putpair((char *)(void *)np, &key, &val);
+                               }
+                               new_bufp->flags |= BUF_MOD;
+                       }
+               }
+       }
+       if (last_bfp)
+               __free_ovflpage(hashp, last_bfp);
+       return (0);
+}
+
+/*
+ * Add the given pair to the page
+ *
+ * Returns:
+ *     0 ==> OK
+ *     1 ==> failure
+ */
+int
+__addel(HTAB *hashp, BUFHEAD *bufp, const DBT *key, const DBT *val)
+{
+       uint16_t *bp, *sop;
+       int do_expand;
+
+       bp = (uint16_t *)(void *)bufp->page;
+       do_expand = 0;
+       while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY))
+               /* Exception case */
+               if (bp[2] == FULL_KEY_DATA && bp[0] == 2)
+                       /* This is the last page of a big key/data pair
+                          and we need to add another page */
+                       break;
+               else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) {
+                       bufp = __get_buf(hashp, (uint32_t)bp[bp[0] - 1], bufp,
+                           0);
+                       if (!bufp)
+                               return (-1);
+                       bp = (uint16_t *)(void *)bufp->page;
+               } else if (bp[bp[0]] != OVFLPAGE) {
+                       /* Short key/data pairs, no more pages */
+                       break;
+               } else {
+                       /* Try to squeeze key on this page */
+                       if (bp[2] >= REAL_KEY &&
+                           FREESPACE(bp) >= PAIRSIZE(key, val)) {
+                               squeeze_key(bp, key, val);
+                               goto stats;
+                       } else {
+                               bufp = __get_buf(hashp,
+                                   (uint32_t)bp[bp[0] - 1], bufp, 0);
+                               if (!bufp)
+                                       return (-1);
+                               bp = (uint16_t *)(void *)bufp->page;
+                       }
+               }
+
+       if (PAIRFITS(bp, key, val))
+               putpair(bufp->page, key, val);
+       else {
+               do_expand = 1;
+               bufp = __add_ovflpage(hashp, bufp);
+               if (!bufp)
+                       return (-1);
+               sop = (uint16_t *)(void *)bufp->page;
+
+               if (PAIRFITS(sop, key, val))
+                       putpair((char *)(void *)sop, key, val);
+               else
+                       if (__big_insert(hashp, bufp, key, val))
+                               return (-1);
+       }
+stats:
+       bufp->flags |= BUF_MOD;
+       /*
+        * If the average number of keys per bucket exceeds the fill factor,
+        * expand the table.
+        */
+       hashp->NKEYS++;
+       if (do_expand ||
+           (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR))
+               return (__expand_table(hashp));
+       return (0);
+}
+
+/*
+ *
+ * Returns:
+ *     pointer on success
+ *     NULL on error
+ */
+BUFHEAD *
+__add_ovflpage(HTAB *hashp, BUFHEAD *bufp)
+{
+       uint16_t *sp;
+       uint16_t ndx, ovfl_num;
+       size_t temp;
+#ifdef DEBUG1
+       int tmp1, tmp2;
+#endif
+       sp = (uint16_t *)(void *)bufp->page;
+
+       /* Check if we are dynamically determining the fill factor */
+       if (hashp->FFACTOR == DEF_FFACTOR) {
+               hashp->FFACTOR = (uint32_t)sp[0] >> 1;
+               if (hashp->FFACTOR < MIN_FFACTOR)
+                       hashp->FFACTOR = MIN_FFACTOR;
+       }
+       bufp->flags |= BUF_MOD;
+       ovfl_num = overflow_page(hashp);
+#ifdef DEBUG1
+       tmp1 = bufp->addr;
+       tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0;
+#endif
+       if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, (uint32_t)ovfl_num,
+           bufp, 1)))
+               return (NULL);
+       bufp->ovfl->flags |= BUF_MOD;
+#ifdef DEBUG1
+       (void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n",
+           tmp1, tmp2, bufp->ovfl->addr);
+#endif
+       ndx = sp[0];
+       /*
+        * Since a pair is allocated on a page only if there's room to add
+        * an overflow page, we know that the OVFL information will fit on
+        * the page.
+        */
+       sp[ndx + 4] = OFFSET(sp);
+       temp = FREESPACE(sp);
+       _DIAGASSERT(temp >= OVFLSIZE);
+       sp[ndx + 3] = (uint16_t)(temp - OVFLSIZE);
+       sp[ndx + 1] = ovfl_num;
+       sp[ndx + 2] = OVFLPAGE;
+       sp[0] = ndx + 2;
+#ifdef HASH_STATISTICS
+       hash_overflows++;
+#endif
+       return (bufp->ovfl);
+}
+
+/*
+ * Returns:
+ *      0 indicates SUCCESS
+ *     -1 indicates FAILURE
+ */
+int
+__get_page(HTAB *hashp, char *p, uint32_t bucket, int is_bucket, int is_disk,
+    int is_bitmap)
+{
+       int fd, page, size;
+       ssize_t rsize;
+       uint16_t *bp;
+       size_t temp;
+
+       fd = hashp->fp;
+       size = hashp->BSIZE;
+
+       if ((fd == -1) || !is_disk) {
+               PAGE_INIT(p);
+               return (0);
+       }
+       if (is_bucket)
+               page = BUCKET_TO_PAGE(bucket);
+       else
+               page = OADDR_TO_PAGE(bucket);
+       if ((rsize = pread(fd, p, (size_t)size, (off_t)page << hashp->BSHIFT)) == -1)
+               return (-1);
+       bp = (uint16_t *)(void *)p;
+       if (!rsize)
+               bp[0] = 0;      /* We hit the EOF, so initialize a new page */
+       else
+               if (rsize != size) {
+                       errno = EFTYPE;
+                       return (-1);
+               }
+       if (!is_bitmap && !bp[0]) {
+               PAGE_INIT(p);
+       } else
+               if (hashp->LORDER != BYTE_ORDER) {
+                       int i, max;
+
+                       if (is_bitmap) {
+                               max = (uint32_t)hashp->BSIZE >> 2; /* divide by 4 */
+                               for (i = 0; i < max; i++)
+                                       M_32_SWAP(((int *)(void *)p)[i]);
+                       } else {
+                               M_16_SWAP(bp[0]);
+                               max = bp[0] + 2;
+                               for (i = 1; i <= max; i++)
+                                       M_16_SWAP(bp[i]);
+                       }
+               }
+       return (0);
+}
+
+/*
+ * Write page p to disk
+ *
+ * Returns:
+ *      0 ==> OK
+ *     -1 ==>failure
+ */
+int
+__put_page(HTAB *hashp, char *p, uint32_t bucket, int is_bucket, int is_bitmap)
+{
+       int fd, page, size;
+       ssize_t wsize;
+
+       size = hashp->BSIZE;
+       if ((hashp->fp == -1) && open_temp(hashp))
+               return (-1);
+       fd = hashp->fp;
+
+       if (hashp->LORDER != BYTE_ORDER) {
+               int i;
+               int max;
+
+               if (is_bitmap) {
+                       max = (uint32_t)hashp->BSIZE >> 2;      /* divide by 4 */
+                       for (i = 0; i < max; i++)
+                               M_32_SWAP(((int *)(void *)p)[i]);
+               } else {
+                       max = ((uint16_t *)(void *)p)[0] + 2;
+                       for (i = 0; i <= max; i++)
+                               M_16_SWAP(((uint16_t *)(void *)p)[i]);
+               }
+       }
+       if (is_bucket)
+               page = BUCKET_TO_PAGE(bucket);
+       else
+               page = OADDR_TO_PAGE(bucket);
+       if ((wsize = pwrite(fd, p, (size_t)size, (off_t)page << hashp->BSHIFT)) == -1)
+               /* Errno is set */
+               return (-1);
+       if (wsize != size) {
+               errno = EFTYPE;
+               return (-1);
+       }
+       return (0);
+}
+
+#define BYTE_MASK      ((1 << INT_BYTE_SHIFT) -1)
+/*
+ * Initialize a new bitmap page.  Bitmap pages are left in memory
+ * once they are read in.
+ */
+int
+__ibitmap(HTAB *hashp, int pnum, int nbits, int ndx)
+{
+       uint32_t *ip;
+       int clearbytes, clearints;
+
+       if ((ip = malloc((size_t)hashp->BSIZE)) == NULL)
+               return (1);
+       hashp->nmaps++;
+       clearints = ((uint32_t)(nbits - 1) >> INT_BYTE_SHIFT) + 1;
+       clearbytes = clearints << INT_TO_BYTE;
+       (void)memset(ip, 0, (size_t)clearbytes);
+       (void)memset(((char *)(void *)ip) + clearbytes, 0xFF,
+           (size_t)(hashp->BSIZE - clearbytes));
+       ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK);
+       SETBIT(ip, 0);
+       hashp->BITMAPS[ndx] = (uint16_t)pnum;
+       hashp->mapp[ndx] = ip;
+       return (0);
+}
+
+static uint32_t
+first_free(uint32_t map)
+{
+       uint32_t i, mask;
+
+       mask = 0x1;
+       for (i = 0; i < BITS_PER_MAP; i++) {
+               if (!(mask & map))
+                       return (i);
+               mask = mask << 1;
+       }
+       return (i);
+}
+
+static uint16_t
+overflow_page(HTAB *hashp)
+{
+       uint32_t *freep = NULL;
+       int max_free, offset, splitnum;
+       uint16_t addr;
+       int bit, first_page, free_bit, free_page, i, in_use_bits, j;
+#ifdef DEBUG2
+       int tmp1, tmp2;
+#endif
+       splitnum = hashp->OVFL_POINT;
+       max_free = hashp->SPARES[splitnum];
+
+       free_page = (uint32_t)(max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT);
+       free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1);
+
+       /* Look through all the free maps to find the first free block */
+       first_page = (uint32_t)hashp->LAST_FREED >>(hashp->BSHIFT + BYTE_SHIFT);
+       for ( i = first_page; i <= free_page; i++ ) {
+               if (!(freep = (uint32_t *)hashp->mapp[i]) &&
+                   !(freep = fetch_bitmap(hashp, i)))
+                       return (0);
+               if (i == free_page)
+                       in_use_bits = free_bit;
+               else
+                       in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1;
+               
+               if (i == first_page) {
+                       bit = hashp->LAST_FREED &
+                           ((hashp->BSIZE << BYTE_SHIFT) - 1);
+                       j = bit / BITS_PER_MAP;
+                       bit = bit & ~(BITS_PER_MAP - 1);
+               } else {
+                       bit = 0;
+                       j = 0;
+               }
+               for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP)
+                       if (freep[j] != ALL_SET)
+                               goto found;
+       }
+
+       /* No Free Page Found */
+       hashp->LAST_FREED = hashp->SPARES[splitnum];
+       hashp->SPARES[splitnum]++;
+       offset = hashp->SPARES[splitnum] -
+           (splitnum ? hashp->SPARES[splitnum - 1] : 0);
+
+#define        OVMSG   "HASH: Out of overflow pages.  Increase page size\n"
+       if (offset > SPLITMASK) {
+               if (++splitnum >= NCACHED) {
+                       (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
+                       errno = EFBIG;
+                       return (0);
+               }
+               hashp->OVFL_POINT = splitnum;
+               hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
+               hashp->SPARES[splitnum-1]--;
+               offset = 1;
+       }
+
+       /* Check if we need to allocate a new bitmap page */
+       if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) {
+               free_page++;
+               if (free_page >= NCACHED) {
+                       (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
+                       errno = EFBIG;
+                       return (0);
+               }
+               /*
+                * This is tricky.  The 1 indicates that you want the new page
+                * allocated with 1 clear bit.  Actually, you are going to
+                * allocate 2 pages from this map.  The first is going to be
+                * the map page, the second is the overflow page we were
+                * looking for.  The init_bitmap routine automatically, sets
+                * the first bit of itself to indicate that the bitmap itself
+                * is in use.  We would explicitly set the second bit, but
+                * don't have to if we tell init_bitmap not to leave it clear
+                * in the first place.
+                */
+               if (__ibitmap(hashp,
+                   (int)OADDR_OF(splitnum, offset), 1, free_page))
+                       return (0);
+               hashp->SPARES[splitnum]++;
+#ifdef DEBUG2
+               free_bit = 2;
+#endif
+               offset++;
+               if (offset > SPLITMASK) {
+                       if (++splitnum >= NCACHED) {
+                               (void)write(STDERR_FILENO, OVMSG,
+                                   sizeof(OVMSG) - 1);
+                               errno = EFBIG;
+                               return (0);
+                       }
+                       hashp->OVFL_POINT = splitnum;
+                       hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
+                       hashp->SPARES[splitnum-1]--;
+                       offset = 0;
+               }
+       } else {
+               /*
+                * Free_bit addresses the last used bit.  Bump it to address
+                * the first available bit.
+                */
+               free_bit++;
+               SETBIT(freep, free_bit);
+       }
+
+       /* Calculate address of the new overflow page */
+       addr = OADDR_OF(splitnum, offset);
+#ifdef DEBUG2
+       (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
+           addr, free_bit, free_page);
+#endif
+       return (addr);
+
+found:
+       bit = bit + first_free(freep[j]);
+       SETBIT(freep, bit);
+#ifdef DEBUG2
+       tmp1 = bit;
+       tmp2 = i;
+#endif
+       /*
+        * Bits are addressed starting with 0, but overflow pages are addressed
+        * beginning at 1. Bit is a bit addressnumber, so we need to increment
+        * it to convert it to a page number.
+        */
+       bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT));
+       if (bit >= hashp->LAST_FREED)
+               hashp->LAST_FREED = bit - 1;
+
+       /* Calculate the split number for this page */
+       for (i = 0; (i < splitnum) && (bit > hashp->SPARES[i]); i++);
+       offset = (i ? bit - hashp->SPARES[i - 1] : bit);
+       if (offset >= SPLITMASK) {
+               (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
+               errno = EFBIG;
+               return (0);     /* Out of overflow pages */
+       }
+       addr = OADDR_OF(i, offset);
+#ifdef DEBUG2
+       (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
+           addr, tmp1, tmp2);
+#endif
+
+       /* Allocate and return the overflow page */
+       return (addr);
+}
+
+/*
+ * Mark this overflow page as free.
+ */
+void
+__free_ovflpage(HTAB *hashp, BUFHEAD *obufp)
+{
+       uint16_t addr;
+       uint32_t *freep;
+       int bit_address, free_page, free_bit;
+       uint16_t ndx;
+
+       addr = obufp->addr;
+#ifdef DEBUG1
+       (void)fprintf(stderr, "Freeing %d\n", addr);
+#endif
+       ndx = (((uint32_t)addr) >> SPLITSHIFT);
+       bit_address =
+           (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1;
+        if (bit_address < hashp->LAST_FREED)
+               hashp->LAST_FREED = bit_address;
+       free_page = ((uint32_t)bit_address >> (hashp->BSHIFT + BYTE_SHIFT));
+       free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1);
+
+       if (!(freep = hashp->mapp[free_page]))
+               freep = fetch_bitmap(hashp, free_page);
+       /*
+        * This had better never happen.  It means we tried to read a bitmap
+        * that has already had overflow pages allocated off it, and we
+        * failed to read it from the file.
+        */
+       _DIAGASSERT(freep != NULL);
+       CLRBIT(freep, free_bit);
+#ifdef DEBUG2
+       (void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n",
+           obufp->addr, free_bit, free_page);
+#endif
+       __reclaim_buf(hashp, obufp);
+}
+
+/*
+ * Returns:
+ *      0 success
+ *     -1 failure
+ */
+static int
+open_temp(HTAB *hashp)
+{
+       sigset_t set, oset;
+       char *envtmp;
+       char namestr[PATH_MAX];
+
+       if (issetugid())
+               envtmp = NULL;
+       else
+               envtmp = getenv("TMPDIR");
+
+       if (-1 == snprintf(namestr, sizeof(namestr), "%s/_hashXXXXXX",
+           envtmp ? envtmp : _PATH_TMP))
+               return -1;
+
+       /* Block signals; make sure file goes away at process exit. */
+       (void)sigfillset(&set);
+       (void)sigprocmask(SIG_BLOCK, &set, &oset);
+       if ((hashp->fp = mkstemp(namestr)) != -1) {
+               (void)unlink(namestr);
+               (void)fcntl(hashp->fp, F_SETFD, FD_CLOEXEC);
+       }
+       (void)sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
+       return (hashp->fp != -1 ? 0 : -1);
+}
+
+/*
+ * We have to know that the key will fit, but the last entry on the page is
+ * an overflow pair, so we need to shift things.
+ */
+static void
+squeeze_key(uint16_t *sp, const DBT *key, const DBT *val)
+{
+       char *p;
+       uint16_t free_space, n, off, pageno;
+       size_t temp;
+
+       p = (char *)(void *)sp;
+       n = sp[0];
+       free_space = FREESPACE(sp);
+       off = OFFSET(sp);
+
+       pageno = sp[n - 1];
+       _DIAGASSERT(off >= key->size);
+       off -= (uint16_t)key->size;
+       sp[n - 1] = off;
+       memmove(p + off, key->data, key->size);
+       _DIAGASSERT(off >= val->size);
+       off -= (uint16_t)val->size;
+       sp[n] = off;
+       memmove(p + off, val->data, val->size);
+       sp[0] = n + 2;
+       sp[n + 1] = pageno;
+       sp[n + 2] = OVFLPAGE;
+       temp = PAIRSIZE(key, val);
+       _DIAGASSERT(free_space >= temp);
+       FREESPACE(sp) = (uint16_t)(free_space - temp);
+       OFFSET(sp) = off;
+}
+
+static uint32_t *
+fetch_bitmap(HTAB *hashp, int ndx)
+{
+       if (ndx >= hashp->nmaps)
+               return (NULL);
+       if ((hashp->mapp[ndx] = malloc((size_t)hashp->BSIZE)) == NULL)
+               return (NULL);
+       if (__get_page(hashp,
+           (char *)(void *)hashp->mapp[ndx], (uint32_t)hashp->BITMAPS[ndx], 0, 1, 1)) {
+               free(hashp->mapp[ndx]);
+               return (NULL);
+       }
+       return (hashp->mapp[ndx]);
+}
+
+#ifdef DEBUG4
+void print_chain(HTAB *, uint32_t);
+void
+print_chain(HTAB *hashp, uint32_t addr)
+{
+       BUFHEAD *bufp;
+       uint16_t *bp, oaddr;
+
+       (void)fprintf(stderr, "%d ", addr);
+       bufp = __get_buf(hashp, addr, NULL, 0);
+       bp = (uint16_t *)bufp->page;
+       while (bp[0] && ((bp[bp[0]] == OVFLPAGE) ||
+               ((bp[0] > 2) && bp[2] < REAL_KEY))) {
+               oaddr = bp[bp[0] - 1];
+               (void)fprintf(stderr, "%d ", (int)oaddr);
+               bufp = __get_buf(hashp, (uint32_t)oaddr, bufp, 0);
+               bp = (uint16_t *)bufp->page;
+       }
+       (void)fprintf(stderr, "\n");
+}
+#endif
diff --git a/lib/nbsd_libc/db/hash/ndbm.c b/lib/nbsd_libc/db/hash/ndbm.c
new file mode 100644 (file)
index 0000000..1aea409
--- /dev/null
@@ -0,0 +1,115 @@
+/*     $NetBSD: ndbm.c,v 1.23 2008/09/11 12:58:00 joerg Exp $  */
+/*     from: NetBSD: ndbm.c,v 1.18 2004/04/27 20:03:45 kleink Exp      */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Margo Seltzer.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: ndbm.c,v 1.23 2008/09/11 12:58:00 joerg Exp $");
+
+/*
+ * This package provides a dbm compatible interface to the new hashing
+ * package described in db(3).
+ */
+#include "namespace.h"
+#include <sys/param.h>
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <ndbm.h>
+#include "hash.h"
+
+/*
+ * Returns:
+ *     *DBM on success
+ *      NULL on failure
+ */
+DBM *
+dbm_open(const char *file, int flags, mode_t mode)
+{
+       HASHINFO info;
+       char path[MAXPATHLEN];
+
+       info.bsize = 4096;
+       info.ffactor = 40;
+       info.nelem = 1;
+       info.cachesize = 0;
+       info.hash = NULL;
+       info.lorder = 0;
+       (void)strncpy(path, file, sizeof(path) - 1);
+       (void)strncat(path, DBM_SUFFIX, sizeof(path) - strlen(path) - 1);
+       if ((flags & O_ACCMODE) == O_WRONLY) {
+               flags &= ~O_WRONLY;
+               flags |= O_RDWR;
+       }
+       return ((DBM *)__hash_open(path, flags, mode, &info, 0));
+}
+
+void
+dbm_close(DBM *db)
+{
+       (void)(db->close)(db);
+}
+
+int
+dbm_error(DBM *db)
+{
+       HTAB *hp;
+
+       hp = db->internal;
+       return (hp->err);
+}
+
+int
+dbm_clearerr(DBM *db)
+{
+       HTAB *hp;
+
+       hp = db->internal;
+       hp->err = 0;
+       return (0);
+}
+
+int
+dbm_dirfno(DBM *db)
+{
+       HTAB *hp;
+
+       hp = db->internal;
+       return hp->fp;
+}
diff --git a/lib/nbsd_libc/db/hash/ndbmdatum.c b/lib/nbsd_libc/db/hash/ndbmdatum.c
new file mode 100644 (file)
index 0000000..75c6ab8
--- /dev/null
@@ -0,0 +1,158 @@
+/*     $NetBSD: ndbmdatum.c,v 1.4 2008/09/11 12:58:00 joerg Exp $      */
+/*     from: NetBSD: ndbm.c,v 1.18 2004/04/27 20:03:45 kleink Exp      */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Margo Seltzer.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: ndbmdatum.c,v 1.4 2008/09/11 12:58:00 joerg Exp $");
+
+/*
+ * This package provides a dbm compatible interface to the new hashing
+ * package described in db(3).
+ */
+#include "namespace.h"
+#include <sys/param.h>
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <ndbm.h>
+#include "hash.h"
+
+/*
+ * Returns:
+ *     DATUM on success
+ *     NULL on failure
+ */
+datum
+dbm_fetch(DBM *db, datum key)
+{
+       datum retdata;
+       int status;
+       DBT dbtkey, dbtretdata;
+
+       dbtkey.data = key.dptr;
+       dbtkey.size = key.dsize;
+       status = (db->get)(db, &dbtkey, &dbtretdata, 0);
+       if (status) {
+               dbtretdata.data = NULL;
+               dbtretdata.size = 0;
+       }
+       retdata.dptr = dbtretdata.data;
+       retdata.dsize = dbtretdata.size;
+       return (retdata);
+}
+
+/*
+ * Returns:
+ *     DATUM on success
+ *     NULL on failure
+ */
+datum
+dbm_firstkey(DBM *db)
+{
+       int status;
+       datum retkey;
+       DBT dbtretkey, dbtretdata;
+
+       status = (db->seq)(db, &dbtretkey, &dbtretdata, R_FIRST);
+       if (status)
+               dbtretkey.data = NULL;
+       retkey.dptr = dbtretkey.data;
+       retkey.dsize = dbtretkey.size;
+       return (retkey);
+}
+
+/*
+ * Returns:
+ *     DATUM on success
+ *     NULL on failure
+ */
+datum
+dbm_nextkey(DBM *db)
+{
+       int status;
+       datum retkey;
+       DBT dbtretkey, dbtretdata;
+
+       status = (db->seq)(db, &dbtretkey, &dbtretdata, R_NEXT);
+       if (status)
+               dbtretkey.data = NULL;
+       retkey.dptr = dbtretkey.data;
+       retkey.dsize = dbtretkey.size;
+       return (retkey);
+}
+
+/*
+ * Returns:
+ *      0 on success
+ *     <0 failure
+ */
+int
+dbm_delete(DBM *db, datum key)
+{
+       int status;
+       DBT dbtkey;
+
+       dbtkey.data = key.dptr;
+       dbtkey.size = key.dsize;
+       status = (db->del)(db, &dbtkey, 0);
+       if (status)
+               return (-1);
+       else
+               return (0);
+}
+
+/*
+ * Returns:
+ *      0 on success
+ *     <0 failure
+ *      1 if DBM_INSERT and entry exists
+ */
+int
+dbm_store(DBM *db, datum key, datum data, int flags)
+{
+       DBT dbtkey, dbtdata;
+
+       dbtkey.data = key.dptr;
+       dbtkey.size = key.dsize;
+       dbtdata.data = data.dptr;
+       dbtdata.size = data.dsize;
+       return ((db->put)(db, &dbtkey, &dbtdata,
+           (u_int)((flags == DBM_INSERT) ? R_NOOVERWRITE : 0)));
+}
diff --git a/lib/nbsd_libc/db/hash/page.h b/lib/nbsd_libc/db/hash/page.h
new file mode 100644 (file)
index 0000000..40dc77d
--- /dev/null
@@ -0,0 +1,90 @@
+/*     $NetBSD: page.h,v 1.8 2008/08/26 21:18:38 joerg Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Margo Seltzer.
+ *
+ * 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. 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.
+ *
+ *     @(#)page.h      8.2 (Berkeley) 5/31/94
+ */
+
+/*
+ * Definitions for hashing page file format.
+ */
+
+/*
+ * routines dealing with a data page
+ *
+ * page format:
+ *     +------------------------------+
+ * p   | n | keyoff | datoff | keyoff |
+ *     +------------+--------+--------+
+ *     | datoff | free  |  ptr  | --> |
+ *     +--------+---------------------+
+ *     |        F R E E A R E A       |
+ *     +--------------+---------------+
+ *     |  <---- - - - | data          |
+ *     +--------+-----+----+----------+
+ *     |  key   | data     | key      |
+ *     +--------+----------+----------+
+ *
+ * Pointer to the free space is always:  p[p[0] + 2]
+ * Amount of free space on the page is:  p[p[0] + 1]
+ */
+
+/*
+ * How many bytes required for this pair?
+ *     2 shorts in the table at the top of the page + room for the
+ *     key and room for the data
+ *
+ * We prohibit entering a pair on a page unless there is also room to append
+ * an overflow page. The reason for this it that you can get in a situation
+ * where a single key/data pair fits on a page, but you can't append an
+ * overflow page and later you'd have to split the key/data and handle like
+ * a big pair.
+ * You might as well do this up front.
+ */
+
+#define        PAIRSIZE(K,D)   (2*sizeof(uint16_t) + (K)->size + (D)->size)
+#define BIGOVERHEAD    (4*sizeof(uint16_t))
+#define KEYSIZE(K)     (4*sizeof(uint16_t) + (K)->size);
+#define OVFLSIZE       (2*sizeof(uint16_t))
+#define FREESPACE(P)   ((P)[(P)[0]+1])
+#define        OFFSET(P)       ((P)[(P)[0]+2])
+#define PAIRFITS(P,K,D) \
+       (((P)[2] >= REAL_KEY) && \
+           (PAIRSIZE((K),(D)) + OVFLSIZE) <= FREESPACE((P)))
+#define PAGE_META(N)   (((N)+3) * sizeof(uint16_t))
+
+typedef struct {
+       BUFHEAD *newp;
+       BUFHEAD *oldp;
+       BUFHEAD *nextp;
+       uint16_t next_addr;
+}       SPLIT_RETURN;
diff --git a/lib/nbsd_libc/db/man/Makefile.inc b/lib/nbsd_libc/db/man/Makefile.inc
new file mode 100644 (file)
index 0000000..f45c416
--- /dev/null
@@ -0,0 +1,15 @@
+#      $NetBSD: Makefile.inc,v 1.10 2004/04/30 21:13:23 kleink Exp $
+#       @(#)Makefile.inc       8.1 (Berkeley) 6/4/93
+
+.PATH: ${.CURDIR}/db/man
+
+MAN+=  btree.3 dbm_clearerr.3 dbopen.3 hash.3 recno.3 mpool.3
+MLINKS+= dbm_clearerr.3 dbm_close.3 dbm_clearerr.3 dbm_delete.3
+MLINKS+= dbm_clearerr.3 dbm_dirfno.3 dbm_clearerr.3 dbm_error.3
+MLINKS+= dbm_clearerr.3 dbm_fetch.3 dbm_clearerr.3 dbm_firstkey.3
+MLINKS+= dbm_clearerr.3 dbm_nextkey.3 dbm_clearerr.3 dbm_open.3
+MLINKS+= dbm_clearerr.3 dbm_store.3 dbm_clearerr.3 ndbm.3
+MLINKS+= dbopen.3 db.3
+MLINKS+= mpool.3 mpool_open.3 mpool.3 mpool_filter.3 mpool.3 mpool_new.3
+MLINKS+= mpool.3 mpool_get.3 mpool.3 mpool_put.3 mpool.3 mpool_sync.3
+MLINKS+= mpool.3 mpool_close.3
diff --git a/lib/nbsd_libc/db/man/btree.3 b/lib/nbsd_libc/db/man/btree.3
new file mode 100644 (file)
index 0000000..1936386
--- /dev/null
@@ -0,0 +1,255 @@
+.\"    $NetBSD: btree.3,v 1.12 2010/03/22 19:30:53 joerg Exp $
+.\"
+.\" 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.
+.\" 3. 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.
+.\"
+.\"    @(#)btree.3     8.4 (Berkeley) 8/18/94
+.\"
+.Dd April 17, 2003
+.Dt BTREE 3
+.Os
+.Sh NAME
+.Nm btree
+.Nd btree database access method
+.Sh SYNOPSIS
+.In sys/types.h
+.In db.h
+.Sh DESCRIPTION
+The routine
+.Fn dbopen
+is the library interface to database files.
+One of the supported file formats is btree files.
+The general description of the database access methods is in
+.Xr dbopen 3 ,
+this manual page describes only the btree specific information.
+.Pp
+The btree data structure is a sorted, balanced tree structure storing
+associated key/data pairs.
+.Pp
+The btree access method specific data structure provided to
+.Fn dbopen
+is defined in the
+.In db.h
+include file as follows:
+.Bd -literal
+typedef struct {
+       u_long flags;
+       u_int cachesize;
+       int maxkeypage;
+       int minkeypage;
+       u_int psize;
+       int (*compare)(const DBT *key1, const DBT *key2);
+       size_t (*prefix)(const DBT *key1, const DBT *key2);
+       int lorder;
+} BTREEINFO;
+.Ed
+.Pp
+The elements of this structure are as follows:
+.Bl -tag -width maxkeypagex
+.It Fa flags
+The flag value is specified by or'ing any of the following values:
+.Bl -tag -width R_DUP -offset indent
+.It Dv R_DUP
+Permit duplicate keys in the tree, i.e. permit insertion if the key to
+be inserted already exists in the tree.
+The default behavior, as described in
+.Xr dbopen 3 ,
+is to overwrite a matching key when inserting a new key or to fail if
+the
+.Dv R_NOOVERWRITE
+flag is specified.
+The
+.Dv R_DUP
+flag is overridden by the
+.Dv R_NOOVERWRITE
+flag, and if the
+.Dv R_NOOVERWRITE
+flag is specified, attempts to insert duplicate keys into the tree
+will fail.
+.Pp
+If the database contains duplicate keys, the order of retrieval of
+key/data pairs is undefined if the
+.Em get
+routine is used, however,
+.Em seq
+routine calls with the
+.Dv R_CURSOR
+flag set will always return the logical
+.Dq first
+of any group of duplicate keys.
+.El
+.It Fa cachesize
+A suggested maximum size (in bytes) of the memory cache.
+This value is
+.Em only
+advisory, and the access method will allocate more memory rather than
+fail.
+Since every search examines the root page of the tree, caching the
+most recently used pages substantially improves access time.
+In addition, physical writes are delayed as long as possible, so a
+moderate cache can reduce the number of I/O operations significantly.
+Obviously, using a cache increases (but only increases) the likelihood
+of corruption or lost data if the system crashes while a tree is being
+modified.
+If
+.Fa cachesize
+is 0 (no size is specified) a default cache is used.
+.It Fa maxkeypage
+The maximum number of keys which will be stored on any single page.
+Not currently implemented.
+.\" The maximum number of keys which will be stored on any single page.
+.\" Because of the way the btree data structure works,
+.\" .Fa maxkeypage
+.\" must always be greater than or equal to 2.
+.\" If
+.\" .Fa maxkeypage
+.\" is 0 (no maximum number of keys is specified) the page fill factor is
+.\" made as large as possible (which is almost invariably what is wanted).
+.It Fa minkeypage
+The minimum number of keys which will be stored on any single page.
+This value is used to determine which keys will be stored on overflow
+pages, i.e., if a key or data item is longer than the pagesize divided
+by the
+.Fa minkeypage
+value, it will be stored on overflow pages instead of in the page
+itself.
+If
+.Fa minkeypage
+is 0 (no minimum number of keys is specified) a value of 2 is used.
+.It Fa psize
+Page size is the size (in bytes) of the pages used for nodes in the
+tree.
+The minimum page size is 512 bytes and the maximum page size is 64K.
+If
+.Fa psize
+is 0 (no page size is specified) a page size is chosen based on the
+underlying file system I/O block size.
+.It Fa compare
+Compare is the key comparison function.
+It must return an integer less than, equal to, or greater than zero if
+the first key argument is considered to be respectively less than,
+equal to, or greater than the second key argument.
+The same comparison function must be used on a given tree every time
+it is opened.
+If
+.Fa compare
+is
+.Dv NULL
+(no comparison function is specified), the keys are compared
+lexically, with shorter keys considered less than longer keys.
+.It Fa prefix
+Prefix is the prefix comparison function.
+If specified, this routine must return the number of bytes of the
+second key argument which are necessary to determine that it is
+greater than the first key argument.
+If the keys are equal, the key length should be returned.
+Note, the usefulness of this routine is very data dependent, but, in
+some data sets can produce significantly reduced tree sizes and search
+times.
+If
+.Fa prefix
+is
+.Dv NULL
+(no prefix function is specified),
+.Em and
+no comparison function is specified, a default lexical comparison
+routine is used.
+If
+.Fa prefix
+is
+.Dv NULL
+and a comparison routine is specified, no prefix comparison is done.
+.It Fa lorder
+The byte order for integers in the stored database metadata.
+The number should represent the order as an integer; for example,
+big endian order would be the number 4,321.
+If
+.Fa lorder
+is 0 (no order is specified) the current host order is used.
+.El
+.Pp
+If the file already exists (and the
+.Dv O_TRUNC
+flag is not specified), the values specified for the parameters flags,
+lorder and psize are ignored in favor of the values used when the tree
+was created.
+.Pp
+Forward sequential scans of a tree are from the least key to the
+greatest.
+.Pp
+Space freed up by deleting key/data pairs from the tree is never
+reclaimed, although it is normally made available for reuse.
+This means that the btree storage structure is grow-only.
+The only solutions are to avoid excessive deletions, or to create a
+fresh tree periodically from a scan of an existing one.
+.Pp
+Searches, insertions, and deletions in a btree will all complete in
+O lg base N where base is the average fill factor.
+Often, inserting ordered data into btrees results in a low fill
+factor.
+This implementation has been modified to make ordered insertion the
+best case, resulting in a much better than normal page fill factor.
+.Sh ERRORS
+The
+.Nm
+access method routines may fail and set
+.Va errno
+for any of the errors specified for the library routine
+.Xr dbopen 3 .
+.Sh SEE ALSO
+.Xr dbopen 3 ,
+.Xr hash 3 ,
+.Xr mpool 3 ,
+.Xr recno 3
+.Pp
+.Rs
+.%T "The Ubiquitous B-tree"
+.%A "Douglas Comer"
+.%J "ACM Comput. Surv."
+.%V 2
+.%N 11
+.%D June 1979
+.%P 121-138
+.Re
+.Rs
+.%T "Prefix B-trees"
+.%A "Bayer"
+.%A "Unterauer"
+.%J "ACM Transactions on Database Systems"
+.%V Vol. 2
+.%N 1
+.%D March 1977
+.%P 11-26
+.Re
+.Rs
+.%B "The Art of Computer Programming Vol. 3: Sorting and Searching"
+.%A "D.E. Knuth"
+.%D 1968
+.%P 471-480
+.Re
+.Sh BUGS
+Only big and little endian byte order is supported.
diff --git a/lib/nbsd_libc/db/man/dbm_clearerr.3 b/lib/nbsd_libc/db/man/dbm_clearerr.3
new file mode 100644 (file)
index 0000000..d9f0672
--- /dev/null
@@ -0,0 +1,306 @@
+.\"    $NetBSD: dbm_clearerr.3,v 1.5 2010/05/05 06:55:57 jruoho Exp $
+.\"
+.\" Copyright (c) 2004 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 5, 2010
+.Dt DBM_CLEARERR 3
+.Os
+.Sh NAME
+.Nm dbm_clearerr ,
+.Nm dbm_close ,
+.Nm dbm_delete ,
+.Nm dbm_dirfno ,
+.Nm dbm_error ,
+.Nm dbm_fetch ,
+.Nm dbm_firstkey ,
+.Nm dbm_nextkey ,
+.Nm dbm_open ,
+.Nm dbm_store ,
+.Nm ndbm
+.Nd database functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ndbm.h
+.Ft int
+.Fn dbm_clearerr "DBM *db"
+.Ft void
+.Fn dbm_close "DBM *db"
+.Ft int
+.Fn dbm_delete "DBM *db" "datum key"
+.Ft int
+.Fn dbm_dirfno "DBM *db"
+.Ft int
+.Fn dbm_error "DBM *db"
+.Ft datum
+.Fn dbm_fetch "DBM *db" "datum key"
+.Ft datum
+.Fn dbm_firstkey "DBM *db"
+.Ft datum
+.Fn dbm_nextkey "DBM *db"
+.Ft DBM *
+.Fn dbm_open "const char *file" "int open_flags" "mode_t file_mode"
+.Ft int
+.Fn dbm_store "DBM *db" "datum key" "datum content" "int store_mode"
+.Sh DESCRIPTION
+The
+.Nm ndbm
+facility provides access to hash database files.
+.Pp
+Two data types are fundamental to the
+.Nm ndbm
+facility.
+.Fa DBM
+serves as a handle to a database.
+It is an opaque type.
+.Pp
+The other data type is
+.Fa datum ,
+which is a structure type which includes the following members:
+.Bd -literal -offset indent
+void *  dptr
+size_t  dsize
+.Ed
+.Pp
+A
+.Fa datum
+is thus given by
+.Fa dptr
+pointing at an object of
+.Fa dsize
+bytes in length.
+.Pp
+The
+.Fn dbm_open
+function opens a database.
+The
+.Fa file
+argument is the pathname which the actual database file pathname
+is based on.
+This implementation uses a single file with the suffix
+.Pa .db
+appended to
+.Fa file .
+The
+.Fa open_flags
+argument has the same meaning as the
+.Fa flags
+argument to
+.Xr open 2
+except that when opening a database for write-only access the file
+is opened for read/write access, and the
+.Dv O_APPEND
+flag must not be specified.
+The
+.Fa file_mode
+argument has the same meaning as the
+.Fa mode
+argument to
+.Xr open 2 .
+.Pp
+For the following functions, the
+.Fa db
+argument is a handle previously returned by a call to
+.Fn dbm_open .
+.Pp
+The
+.Fn dbm_close
+function closes a database.
+.Pp
+The
+.Fn dbm_fetch
+function retrieves a record from the database.
+The
+.Fa key
+argument is a
+.Fa datum
+that identifies the record to be fetched.
+.Pp
+The
+.Fn dbm_store
+function stores a record into the database.
+The
+.Fa key
+argument is a
+.Fa datum
+that identifies the record to be stored.
+The
+.Fa content
+argument is a
+.Fa datum
+that specifies the value of the record to be stored.
+The
+.Fa store_mode
+argument specifies the behavior of
+.Fn dbm_store
+if a record matching
+.Fa key
+is already present in the database,
+.Fa db .
+.Fa store_mode
+must be one of the following:
+.Bl -tag -width DBM_REPLACEXX -offset indent
+.It Dv DBM_INSERT
+If a record matching
+.Fa key
+is already present, it is left unchanged.
+.It Dv DBM_REPLACE
+If a record matching
+.Fa key
+is already present, its value is replaced by
+.Fa content .
+.El
+.Pp
+If no record matching
+.Fa key
+is present, a new record is inserted regardless of
+.Fa store_mode .
+.Pp
+The
+.Fn dbm_delete
+function deletes a record from the database.
+The
+.Fa key
+argument is a
+.Fa datum
+that identifies the record to be deleted.
+.Pp
+The
+.Fn dbm_firstkey
+function returns the first key in the database.
+.Pp
+The
+.Fn dbm_nextkey
+function returns the next key in the database.
+In order to be meaningful, it must be preceded by a call to
+.Fn dbm_firstkey .
+.Pp
+The
+.Fn dbm_error
+function returns the error indicator of the database.
+.Pp
+The
+.Fn dbm_clearerr
+function clears the error indicator of the database.
+.Pp
+The
+.Fn dbm_dirfno
+function returns the file descriptor of the underlying database file.
+.Sh IMPLEMENTATION NOTES
+The
+.Nm ndbm
+facility is implemented on top of the
+.Xr hash 3
+access method of the
+.Xr db 3
+database facility.
+.Sh RETURN VALUES
+The
+.Fn dbm_open
+function returns a pointer to a
+.Fa DBM
+when successful; otherwise a null pointer is returned.
+.Pp
+The
+.Fn dbm_close
+function returns no value.
+.Pp
+The
+.Fn dbm_fetch
+function returns a content
+.Fa datum ;
+if no record matching
+.Fa key
+was found or if an error occured, its
+.Fa dptr
+member is a null pointer.
+.Pp
+The
+.Fn dbm_store
+function returns 0 when then record was successfully inserted;
+it returns 1 when called with
+.Fa store_mode
+being
+.Dv DBM_INSERT
+and a record matching
+.Fa key
+is already present;
+otherwise a negative value is returned.
+.Pp
+The
+.Fn dbm_delete
+function returns 0 when the record was successfully deleted;
+otherwise a negative value is returned.
+.Pp
+The
+.Fn dbm_firstkey
+and
+.Fn dbm_nextkey
+functions return a key
+.Fa datum .
+When the end of the database is reached or if an error occured, its
+.Fa dptr
+member is a null pointer.
+.Pp
+The
+.Fn dbm_error
+function returns 0 if the error indicator is clear;
+if the error indicator is set a non-zero value is returned.
+.Pp
+The
+.Fn dbm_clearerr
+function always returns 0.
+.Pp
+The
+.Fn dbm_dirfno
+function returns the file descriptor of the underlying database file.
+.Sh ERRORS
+No errors are defined.
+.Sh SEE ALSO
+.Xr open 2 ,
+.Xr db 3 ,
+.Xr hash 3
+.Sh STANDARDS
+The
+.Fn dbm_clearerr ,
+.Fn dbm_close ,
+.Fn dbm_delete ,
+.Fn dbm_error ,
+.Fn dbm_fetch ,
+.Fn dbm_firstkey ,
+.Fn dbm_nextkey ,
+.Fn dbm_open ,
+and
+.Fn dbm_store
+functions conform to
+.St -xpg4.2
+and
+.St -susv2 .
+The
+.Fn dbm_dirfno
+function is an extension.
diff --git a/lib/nbsd_libc/db/man/dbopen.3 b/lib/nbsd_libc/db/man/dbopen.3
new file mode 100644 (file)
index 0000000..1db9a25
--- /dev/null
@@ -0,0 +1,538 @@
+.\"    $NetBSD: dbopen.3,v 1.19 2010/12/16 12:08:16 jruoho Exp $
+.\"
+.\" 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.
+.\" 3. 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.
+.\"
+.\"    @(#)dbopen.3    8.5 (Berkeley) 1/2/94
+.\"
+.Dd December 16, 2010
+.Dt DBOPEN 3
+.Os
+.Sh NAME
+.Nm dbopen ,
+.Nm db
+.Nd database access methods
+.Sh SYNOPSIS
+.In sys/types.h
+.In limits.h
+.In db.h
+.In fcntl.h
+.Ft DB *
+.Fn dbopen "const char *file" "int flags" "mode_t mode" \
+"DBTYPE type" "const void *openinfo"
+.Sh DESCRIPTION
+.Nm
+is the library interface to database files.
+The supported file formats are btree, hashed, and UNIX file oriented.
+The btree format is a representation of a sorted, balanced tree
+structure.
+The hashed format is an extensible, dynamic hashing scheme.
+The flat-file format is a byte stream file with fixed or variable
+length records.
+The formats and file format specific information are described in
+detail in their respective manual pages
+.Xr btree 3 ,
+.Xr hash 3 ,
+and
+.Xr recno 3 .
+.Pp
+The
+.Fn dbopen
+function opens
+.Fa file
+for reading and/or writing.
+Files never intended to be preserved on disk may be created by setting
+the file parameter to
+.Dv NULL .
+.Pp
+The
+.Fa flags
+and
+.Fa mode
+arguments are as specified to the
+.Xr open 2
+routine, however, only the
+.Dv O_CREAT ,
+.Dv O_EXCL ,
+.Dv O_EXLOCK ,
+.Dv O_NONBLOCK ,
+.Dv O_RDONLY ,
+.Dv O_RDWR ,
+.Dv O_SHLOCK ,
+and
+.Dv O_TRUNC
+flags are meaningful.
+(Note, opening a database file
+.Dv O_WRONLY
+is not possible.)
+.\"Three additional options may be specified by or'ing
+.\"them into the
+.\".Fa flags
+.\"argument.
+.\".Pp
+.\".Dv DB_LOCK
+.\"Do the necessary locking in the database to support concurrent access.
+.\"If concurrent access isn't needed or the database is read-only this
+.\"flag should not be set, as it tends to have an associated performance
+.\"penalty.
+.\".Pp
+.\".Dv DB_SHMEM
+.\"Place the underlying memory pool used by the database in shared
+.\"memory.
+.\"Necessary for concurrent access.
+.\".Pp
+.\".Dv DB_TXN
+.\"Support transactions in the database.
+.\"The
+.\".Dv DB_LOCK
+.\"and
+.\".Dv DB_SHMEM
+.\"flags must be set as well.
+.Pp
+The
+.Fa type
+argument is of type
+.Vt DBTYPE
+(as defined in the
+.In db.h
+include file) and may be set to
+.Dv DB_BTREE ,
+.Dv DB_HASH ,
+or
+.Dv DB_RECNO .
+.Pp
+The
+.Fa openinfo
+argument is a pointer to an access method specific structure described
+in the access method's manual page.
+If
+.Fa openinfo
+is
+.Dv NULL ,
+each access method will use defaults appropriate for the system and
+the access method.
+.Ss The DB Structure
+The
+.Fn dbopen
+function returns a pointer to a DB structure on success and
+.Dv NULL
+on error.
+The DB structure is defined in the
+.In db.h
+include file, and contains at least the following fields:
+.Bd -literal -offset indent
+typedef struct {
+       DBTYPE type;
+       int (*close)(const DB *db);
+       int (*del)(const DB *db, const DBT *key, u_int flags);
+       int (*fd)(const DB *db);
+       int (*get)(const DB *db, DBT *key, DBT *data, u_int flags);
+       int (*put)(const DB *db, DBT *key, const DBT *data,
+           u_int flags);
+       int (*sync)(const DB *db, u_int flags);
+       int (*seq)(const DB *db, DBT *key, DBT *data, u_int flags);
+} DB;
+.Ed
+.Pp
+These elements describe a database type and a set of functions
+performing various actions.
+These functions take a pointer to a structure as returned by
+.Nm ,
+and sometimes one or more pointers to key/data structures and a flag
+value.
+.Bl -tag -width closex -offset indent
+.It Fa type
+The type of the underlying access method (and file format).
+.It Fa close
+A pointer to a routine to flush any cached information to disk, free
+any allocated resources, and close the underlying file(s).
+Since key/data pairs may be cached in memory, failing to sync the file
+with a
+.Fa close
+or
+.Fa sync
+function may result in inconsistent or lost information.
+.Fa close
+routines return \-1 on error (setting
+.Va errno )
+and 0 on success.
+.It Fa del
+A pointer to a routine to remove key/data pairs from the database.
+.Pp
+The parameter
+.Fa flag
+may be set to the following value:
+.Bl -tag -width R_CURSORX
+.It Dv R_CURSOR
+Delete the record referenced by the cursor.
+The cursor must have previously been initialized.
+.El
+.Pp
+.Fa delete
+routines return \-1 on error (setting
+.Va errno ) ,
+0 on success, and 1 if the specified
+.Fa key
+was not in the file.
+.It Fa fd
+A pointer to a routine which returns a file descriptor representative
+of the underlying database.
+A file descriptor referencing the same file will be returned to all
+processes which call
+.Nm
+with the same
+.Fa file
+name.
+This file descriptor may be safely used as an argument to the
+.Xr fcntl 2
+and
+.Xr flock 2
+locking functions.
+The file descriptor is not necessarily associated with any of the
+underlying files used by the access method.
+No file descriptor is available for in memory databases.
+.Fa fd
+routines return \-1 on error (setting
+.Va errno ) ,
+and the file descriptor on success.
+.It Fa get
+A pointer to a routine which is the interface for keyed retrieval from
+the database.
+The address and length of the data associated with the specified
+.Fa key
+are returned in the structure referenced by
+.Fa data .
+.Fa get
+routines return \-1 on error (setting
+.Va errno ) ,
+0 on success, and 1 if the
+.Fa key
+was not in the file.
+.It Fa put
+A pointer to a routine to store key/data pairs in the database.
+.Pp
+The parameter
+.Fa flag
+may be set to one of the following values:
+.Bl -tag -width R_NOOVERWRITEX
+.It Dv R_CURSOR
+Replace the key/data pair referenced by the cursor.
+The cursor must have previously been initialized.
+.It Dv R_IAFTER
+Append the data immediately after the data referenced by
+.Fa key ,
+creating a new key/data pair.
+The record number of the appended key/data pair is returned in the
+.Fa key
+structure.
+(Applicable only to the
+.Dv DB_RECNO
+access method.)
+.It Dv R_IBEFORE
+Insert the data immediately before the data referenced by
+.Fa key ,
+creating a new key/data pair.
+The record number of the inserted key/data pair is returned in the
+.Fa key
+structure.
+(Applicable only to the
+.Dv DB_RECNO
+access method.)
+.It Dv R_NOOVERWRITE
+Enter the new key/data pair only if the key does not previously
+exist.
+.It Dv R_SETCURSOR
+Store the key/data pair, setting or initializing the position of the
+cursor to reference it.
+(Applicable only to the
+.Dv DB_BTREE
+and
+.Dv DB_RECNO
+access methods.)
+.El
+.Pp
+.Dv R_SETCURSOR
+is available only for the
+.Dv DB_BTREE
+and
+.Dv DB_RECNO
+access methods because it implies that the keys have an inherent order
+which does not change.
+.Pp
+.Dv R_IAFTER
+and
+.Dv R_IBEFORE
+are available only for the
+.Dv DB_RECNO
+access method because they each imply that the access method is able
+to create new keys.
+This is only true if the keys are ordered and independent, record
+numbers for example.
+.Pp
+The default behavior of the
+.Fa put
+routines is to enter the new key/data pair, replacing any previously
+existing key.
+.Pp
+.Fa put
+routines return \-1 on error (setting
+.Va errno ) ,
+0 on success, and 1 if the
+.Dv R_NOOVERWRITE
+.Fa flag
+was set and the key already exists in the file.
+.It Fa seq
+A pointer to a routine which is the interface for sequential
+retrieval from the database.
+The address and length of the key are returned in the structure
+referenced by
+.Fa key ,
+and the address and length of the data are returned in the
+structure referenced by
+.Fa data .
+.Pp
+Sequential key/data pair retrieval may begin at any time, and the
+position of the
+.Dq cursor
+is not affected by calls to the
+.Fa del ,
+.Fa get ,
+.Fa put ,
+or
+.Fa sync
+routines.
+Modifications to the database during a sequential scan will be
+reflected in the scan, i.e., records inserted behind the cursor will
+not be returned while records inserted in front of the cursor will be
+returned.
+.Pp
+The flag value
+.Em must
+be set to one of the following values:
+.Bl -tag -width R_CURSORX
+.It Dv R_CURSOR
+The data associated with the specified key is returned.
+This differs from the
+.Fa get
+routines in that it sets or initializes the cursor to the location of
+the key as well.
+(Note, for the
+.Dv DB_BTREE
+access method, the returned key is not necessarily an exact match for
+the specified key.
+The returned key is the smallest key greater than or equal to the
+specified key, permitting partial key matches and range searches.)
+.It Dv R_FIRST
+The first key/data pair of the database is returned, and the cursor
+is set or initialized to reference it.
+.It Dv R_LAST
+The last key/data pair of the database is returned, and the cursor
+is set or initialized to reference it.
+(Applicable only to the
+.Dv DB_BTREE
+and
+.Dv DB_RECNO
+access methods.)
+.It Dv R_NEXT
+Retrieve the key/data pair immediately after the cursor.
+If the cursor is not yet set, this is the same as the
+.Dv R_FIRST
+flag.
+.It Dv R_PREV
+Retrieve the key/data pair immediately before the cursor.
+If the cursor is not yet set, this is the same as the
+.Dv R_LAST
+flag.
+(Applicable only to the
+.Dv DB_BTREE
+and
+.Dv DB_RECNO
+access methods.)
+.El
+.Pp
+.Dv R_LAST
+and
+.Dv R_PREV
+are available only for the
+.Dv DB_BTREE
+and
+.Dv DB_RECNO
+access methods because they each imply that the keys have an inherent
+order which does not change.
+.Pp
+.Fa seq
+routines return \-1 on error (setting
+.Va errno ) ,
+0 on success and 1 if there are no key/data pairs less than or greater
+than the specified or current key.
+If the
+.Dv DB_RECNO
+access method is being used, and if the database file is a character
+special file and no complete key/data pairs are currently available,
+the
+.Fa seq
+routines return 2.
+.It Fa sync
+A pointer to a routine to flush any cached information to disk.
+If the database is in memory only, the
+.Fa sync
+routine has no effect and will always succeed.
+.Pp
+The flag value may be set to the following value:
+.Bl -tag -width ".Dv R_RECNOSYNC"
+.It Dv R_RECNOSYNC
+If the
+.Dv DB_RECNO
+access method is being used, this flag causes the sync routine to
+apply to the btree file which underlies the recno file, not the recno
+file itself.
+(See the
+.Fa bfname
+field of the
+.Xr recno 3
+manual page for more information.)
+.El
+.Pp
+.Fa sync
+routines return \-1 on error (setting
+.Va errno )
+and 0 on success.
+.El
+.Ss Key/data Pairs
+Access to all file types is based on key/data pairs.
+Both keys and data are represented by the following data structure:
+.Bd -literal -offset indent
+typedef struct {
+       void *data;
+       size_t size;
+} DBT;
+.Ed
+.Pp
+The elements of the DBT structure are defined as follows:
+.Bl -tag -width datax -offset indent
+.It Fa data
+A pointer to a byte string.
+.It Fa size
+The length of the byte string.
+.El
+.Pp
+Key and data byte strings may reference strings of essentially
+unlimited length although any two of them must fit into available
+memory at the same time.
+It should be noted that the access methods provide no guarantees about
+byte string alignment.
+.Sh ERRORS
+The
+.Nm
+routine may fail and set
+.Va errno
+for any of the errors specified for the library routines
+.Xr open 2
+and
+.Xr malloc 3
+or the following:
+.Bl -tag -width Er
+.It Er EFTYPE
+A file is incorrectly formatted.
+.It Er EINVAL
+A parameter has been specified (hash function, pad byte, etc.) that is
+incompatible with the current file specification or which is not
+meaningful for the function (for example, use of the cursor without
+prior initialization) or there is a mismatch between the version
+number of file and the software.
+.It Er EFBIG
+The key could not be inserted due to limitations in the DB file format
+(e.g., a hash database was out of overflow pages).
+.El
+.Pp
+The
+.Fa close
+routines may fail and set
+.Va errno
+for any of the errors specified for the library routines
+.Xr close 2 ,
+.Xr read 2 ,
+.Xr write 2 ,
+.Xr free 3 ,
+or
+.Xr fsync 2 .
+.Pp
+The
+.Fa del ,
+.Fa get ,
+.Fa put ,
+and
+.Fa seq
+routines may fail and set
+.Va errno
+for any of the errors specified for the library routines
+.Xr read 2 ,
+.Xr write 2 ,
+.Xr free 3 ,
+or
+.Xr malloc 3 .
+.Pp
+The
+.Fa fd
+routines will fail and set
+.Va errno
+to
+.Er ENOENT
+for in memory databases.
+.Pp
+The
+.Fa sync
+routines may fail and set
+.Va errno
+for any of the errors specified for the library routine
+.Xr fsync 2 .
+.Sh SEE ALSO
+.Xr btree 3 ,
+.Xr hash 3 ,
+.Xr mpool 3 ,
+.Xr recno 3
+.Pp
+.Rs
+.%T LIBTP: Portable, Modular Transactions for UNIX
+.%A Margo Seltzer
+.%A Michael Olson
+.%I USENIX Association
+.%B Proceedings of the 1992 Winter USENIX Technical Conference
+.%D 1992
+.%P 9-25
+.Re
+.Sh BUGS
+The typedef DBT is a mnemonic for
+.Dq data base thang ,
+and was used because no one could think of a reasonable name that
+wasn't already used.
+.Pp
+The file descriptor interface is a kludge and will be deleted in a
+future version of the interface.
+.Pp
+None of the access methods provide any form of concurrent access,
+locking, or transactions.
diff --git a/lib/nbsd_libc/db/man/hash.3 b/lib/nbsd_libc/db/man/hash.3
new file mode 100644 (file)
index 0000000..eaac286
--- /dev/null
@@ -0,0 +1,172 @@
+.\"    $NetBSD: hash.3,v 1.14 2010/12/16 11:57:20 jruoho Exp $
+.\"
+.\" 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.
+.\" 3. 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.
+.\"
+.\"    @(#)hash.3      8.6 (Berkeley) 8/18/94
+.\"
+.Dd December 16, 2010
+.Dt HASH 3
+.Os
+.Sh NAME
+.Nm hash
+.Nd hash database access method
+.Sh SYNOPSIS
+.In sys/types.h
+.In db.h
+.Sh DESCRIPTION
+The routine
+.Fn dbopen
+is the library interface to database files.
+One of the supported file formats is hash files.
+The general description of the database access methods is in
+.Xr dbopen 3 ,
+this manual page describes only the hash specific information.
+.Pp
+The hash data structure is an extensible, dynamic hashing scheme.
+.Pp
+The access method specific data structure provided to
+.Fn dbopen
+is defined in the
+.In db.h
+header as follows:
+.Bd -literal -offset indent
+typedef struct {
+       u_int bsize;
+       u_int ffactor;
+       u_int nelem;
+       u_int cachesize;
+       uint32_t (*hash)(const void *, size_t);
+       int lorder;
+} HASHINFO;
+.Ed
+.Pp
+The elements of this structure are as follows:
+.Bl -tag -width cachesizex
+.It Fa bsize
+.Fa bsize
+defines the hash table bucket size, and defaults to 4096 for in-memory tables.
+If
+.Fa bsize
+is 0 (no bucket size is specified) a bucket size is chosen based on the
+underlying file system I/O block size.
+It may be preferable to increase the page size for disk-resident
+tables and tables with large data items.
+.It Fa ffactor
+.Fa ffactor
+indicates a desired density within the hash table.
+It is an approximation of the number of keys allowed to accumulate in
+any one bucket, determining when the hash table grows or shrinks.
+The default value is 8.
+.It Fa nelem
+.Fa nelem
+is an estimate of the final size of the hash table.
+If not set or set too low, hash tables will expand gracefully as keys
+are entered, although a slight performance degradation may be
+noticed.
+The default value is 1.
+.It Fa cachesize
+A suggested maximum size, in bytes, of the memory cache.
+This value is
+.Em only
+advisory, and the access method will allocate more memory rather
+than fail.
+.It Fa hash
+.Fa hash
+is a user defined hash function.
+Since no hash function performs equally well on all possible data, the
+user may find that the built-in hash function does poorly on a
+particular data set.
+User specified hash functions must take two arguments (a pointer to a
+byte string and a length) and return a 32-bit quantity to be used as
+the hash value.
+.It Fa lorder
+The byte order for integers in the stored database metadata.
+The number should represent the order as an integer; for example,
+big endian order would be the number 4,321.
+If
+.Fa lorder
+is 0 (no order is specified) the current host order is used.
+If the file already exists, the specified value is ignored and the
+value specified when the tree was created is used.
+.El
+.Pp
+If the file already exists (and the
+.Dv O_TRUNC
+flag is not specified), the values specified for the parameters
+.Fa bsize ,
+.Fa ffactor ,
+.Fa lorder ,
+and
+.Fa nelem
+are ignored and the values specified when the tree was created are
+used.
+.Pp
+If a hash function is specified,
+.Fn hash_open
+will attempt to determine if the hash function specified is the same
+as the one with which the database was created, and will fail if it is
+not.
+.\".Pp
+.\"Backward compatible interfaces to the routines described in
+.\".Xr dbm 3 ,
+.\"and
+.\".Xr ndbm 3
+.\"are provided, however these interfaces are not compatible with
+.\"previous file formats.
+.Sh ERRORS
+The
+.Nm
+access method routines may fail and set
+.Va errno
+for any of the errors specified for the library routine
+.Xr dbopen 3 .
+.Sh SEE ALSO
+.Xr btree 3 ,
+.Xr dbopen 3 ,
+.Xr mpool 3 ,
+.Xr recno 3
+.Pp
+.Rs
+.%T Dynamic Hash Tables
+.%A Per-Ake Larson
+.%J Communications of the ACM
+.%D April 1988
+.%N Issue 4
+.%V Volume 31
+.Re
+.Rs
+.%T A New Hash Package for UNIX
+.%A Margo Seltzer
+.%I USENIX Association
+.%B Proceedings of the 1991 Winter USENIX Technical Conference
+.%D January 1991
+.%P 173-184
+.%U http://www.usenix.org/publications/library/proceedings/seltzer2.pdf
+.Re
+.Sh BUGS
+Only big and little endian byte order is supported.
diff --git a/lib/nbsd_libc/db/man/mpool.3 b/lib/nbsd_libc/db/man/mpool.3
new file mode 100644 (file)
index 0000000..32673f9
--- /dev/null
@@ -0,0 +1,226 @@
+.\"    $NetBSD: mpool.3,v 1.10 2010/12/16 11:49:35 jruoho Exp $
+.\"
+.\" 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.
+.\" 3. 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.
+.\"
+.\"    @(#)mpool.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd December 16, 2010
+.Dt MPOOL 3
+.Os
+.Sh NAME
+.Nm mpool ,
+.Nm mpool_open ,
+.Nm mpool_filter ,
+.Nm mpool_new ,
+.Nm mpool_get ,
+.Nm mpool_put ,
+.Nm mpool_sync ,
+.Nm mpool_close
+.Nd shared memory buffer pool
+.Sh SYNOPSIS
+.In db.h
+.In mpool.h
+.Ft MPOOL *
+.Fn mpool_open "DBT *key" "int fd" "pgno_t pagesize" "pgno_t maxcache"
+.Ft void
+.Fn mpool_filter "MPOOL *mp" "void (*pgin)(void *, pgno_t, void *)" \
+"void (*pgout)(void *, pgno_t, void *)" "void *pgcookie"
+.Ft void *
+.Fn mpool_new "MPOOL *mp" "pgno_t *pgnoaddr"
+.Ft void *
+.Fn mpool_get "MPOOL *mp" "pgno_t pgno" "u_int flags"
+.Ft int
+.Fn mpool_put "MPOOL *mp" "void *pgaddr" "u_int flags"
+.Ft int
+.Fn mpool_sync "MPOOL *mp"
+.Ft int
+.Fn mpool_close "MPOOL *mp"
+.Sh DESCRIPTION
+.Nm
+is the library interface intended to provide page oriented buffer
+management of files.
+The buffers may be shared between processes.
+.Pp
+The function
+.Fn mpool_open
+initializes a memory pool.
+The
+.Fa key
+argument is the byte string used to negotiate between multiple
+processes wishing to share buffers.
+If the file buffers are mapped in shared memory, all processes using
+the same key will share the buffers.
+If
+.Fa key
+is
+.Dv NULL ,
+the buffers are mapped into private memory.
+The
+.Fa fd
+argument is a file descriptor for the underlying file, which must be
+seekable.
+If
+.Fa key
+is
+.No non- Ns Dv NULL
+and matches a file already being mapped, the
+.Fa fd
+argument is ignored.
+.Pp
+The
+.Fa pagesize
+argument is the size, in bytes, of the pages into which the file is
+broken up.
+The
+.Fa maxcache
+argument is the maximum number of pages from the underlying file to
+cache at any one time.
+This value is not relative to the number of processes which share a
+file's buffers, but will be the largest value specified by any of the
+processes sharing the file.
+.Pp
+The
+.Fn mpool_filter
+function is intended to make transparent input and output processing
+of the pages possible.
+If the
+.Fa pgin
+function is specified, it is called each time a buffer is read into
+the memory pool from the backing file.
+If the
+.Fa pgout
+function is specified, it is called each time a buffer is written into
+the backing file.
+Both functions are are called with the
+.Fa pgcookie
+pointer, the page number and a pointer to the page to being read or
+written.
+.Pp
+The function
+.Fn mpool_new
+takes an MPOOL pointer and an address as arguments.
+If a new page can be allocated, a pointer to the page is returned and
+the page number is stored into the
+.Fa pgnoaddr
+address.
+Otherwise,
+.Dv NULL
+is returned and errno is set.
+.Pp
+The function
+.Fn mpool_get
+takes a MPOOL pointer and a page number as arguments.
+If the page exists, a pointer to the page is returned.
+Otherwise,
+.Dv NULL
+is returned and errno is set.
+The flags parameter is not currently used.
+.Pp
+The function
+.Fn mpool_put
+unpins the page referenced by
+.Fa pgaddr .
+.Fa pgaddr
+must be an address previously returned by
+.Fn mpool_get
+or
+.Fn mpool_new .
+The flag value is specified by or'ing any of the following values:
+.Bl -tag -width MPOOL_DIRTYX -offset indent
+.It Dv MPOOL_DIRTY
+The page has been modified and needs to be written to the backing
+file.
+.El
+.Pp
+.Fn mpool_put
+returns 0 on success and \-1 if an error occurs.
+.Pp
+The function
+.Fn mpool_sync
+writes all modified pages associated with the MPOOL pointer to the
+backing file.
+.Fn mpool_sync
+returns 0 on success and \-1 if an error occurs.
+.Pp
+The
+.Fn mpool_close
+function frees up any allocated memory associated with the memory pool
+cookie.
+Modified pages are
+.Em not
+written to the backing file.
+.Fn mpool_close
+returns 0 on success and \-1 if an error occurs.
+.Sh ERRORS
+The
+.Fn mpool_open
+function may fail and set
+.Va errno
+for any of the errors specified for the library routine
+.Xr malloc 3 .
+.Pp
+The
+.Fn mpool_get
+function may fail and set
+.Va errno
+for the following:
+.Bl -tag -width Er -offset indent
+.It Er EINVAL
+The requested record doesn't exist.
+.El
+.Pp
+The
+.Fn mpool_new
+and
+.Fn mpool_get
+functions may fail and set
+.Va errno
+for any of the errors specified for the library routines
+.Xr read 2 ,
+.Xr write 2 ,
+and
+.Xr malloc 3 .
+.Pp
+The
+.Fn mpool_sync
+function may fail and set
+.Va errno
+for any of the errors specified for the library routine
+.Xr write 2 .
+.Pp
+The
+.Fn mpool_close
+function may fail and set
+.Va errno
+for any of the errors specified for the library routine
+.Xr free 3 .
+.Sh SEE ALSO
+.Xr btree 3 ,
+.Xr dbopen 3 ,
+.Xr hash 3 ,
+.Xr recno 3
diff --git a/lib/nbsd_libc/db/man/recno.3 b/lib/nbsd_libc/db/man/recno.3
new file mode 100644 (file)
index 0000000..a38871f
--- /dev/null
@@ -0,0 +1,214 @@
+.\"    $NetBSD: recno.3,v 1.11 2010/03/22 19:30:53 joerg Exp $
+.\"
+.\" 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.
+.\" 3. 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.
+.\"
+.\"    @(#)recno.3     8.5 (Berkeley) 8/18/94
+.\"
+.Dd April 17, 2003
+.Dt RECNO 3
+.Os
+.Sh NAME
+.Nm recno
+.Nd record number database access method
+.Sh SYNOPSIS
+.In sys/types.h
+.In db.h
+.Sh DESCRIPTION
+The routine
+.Fn dbopen
+is the library interface to database files.
+One of the supported file formats is record number files.
+The general description of the database access methods is in
+.Xr dbopen 3 ,
+this manual page describes only the recno specific information.
+.Pp
+The record number data structure is either variable or fixed-length
+records stored in a flat-file format, accessed by the logical record
+number.
+The existence of record number five implies the existence of records
+one through four, and the deletion of record number one causes
+record number five to be renumbered to record number four, as well
+as the cursor, if positioned after record number one, to shift down
+one record.
+.Pp
+The recno access method specific data structure provided to
+.Fn dbopen
+is defined in the
+.In db.h
+include file as follows:
+.Bd -literal
+typedef struct {
+       u_long flags;
+       u_int cachesize;
+       u_int psize;
+       int lorder;
+       size_t reclen;
+       uint8_t bval;
+       char *bfname;
+} RECNOINFO;
+.Ed
+.Pp
+The elements of this structure are defined as follows:
+.Bl -tag -width cachesizex
+.It Fa flags
+The flag value is specified by or'ing any of the following values:
+.Bl -tag -width R_FIXEDLENX -offset indent
+.It Dv R_FIXEDLEN
+The records are fixed-length, not byte delimited.
+The structure element
+.Fa reclen
+specifies the length of the record, and the structure element
+.Fa bval
+is used as the pad character.
+Any records, inserted into the database, that are less than
+.Fa reclen
+bytes long are automatically padded.
+.It Dv R_NOKEY
+In the interface specified by
+.Fn dbopen ,
+the sequential record retrieval fills in both the caller's key and
+data structures.
+If the
+.Dv R_NOKEY
+flag is specified, the cursor routines are not required to fill in the
+key structure.
+This permits applications to retrieve records at the end of files
+without reading all of the intervening records.
+.It Dv R_SNAPSHOT
+This flag requires that a snapshot of the file be taken when
+.Fn dbopen
+is called, instead of permitting any unmodified records to be read
+from the original file.
+.El
+.It Fa cachesize
+A suggested maximum size, in bytes, of the memory cache.
+This value is
+.Em only
+advisory, and the access method will allocate more memory rather than
+fail.
+If
+.Fa cachesize
+is 0 (no size is specified) a default cache is used.
+.It Fa psize
+The recno access method stores the in-memory copies of its records
+in a btree.
+This value is the size (in bytes) of the pages used for nodes in that
+tree.
+If
+.Fa psize
+is 0 (no page size is specified) a page size is chosen based on the
+underlying file system I/O block size.
+See
+.Xr btree 3
+for more information.
+.It Fa lorder
+The byte order for integers in the stored database metadata.
+The number should represent the order as an integer; for example,
+big endian order would be the number 4,321.
+If
+.Fa lorder
+is 0 (no order is specified) the current host order is used.
+.It Fa reclen
+The length of a fixed-length record.
+.It Fa bval
+The delimiting byte to be used to mark the end of a record for
+variable-length records, and the pad character for fixed-length
+records.
+If no value is specified, newlines
+.Pq Dq \en
+are used to mark the end of variable-length records and fixed-length
+records are padded with spaces.
+.It Fa bfname
+The recno access method stores the in-memory copies of its records
+in a btree.
+If bfname is
+.No non- Ns Dv NULL ,
+it specifies the name of the btree file, as if specified as the file
+name for a
+.Fn dbopen
+of a btree file.
+.El
+.Pp
+The data part of the key/data pair used by the recno access method
+is the same as other access methods.
+The key is different.
+The
+.Fa data
+field of the key should be a pointer to a memory location of type
+recno_t, as defined in the
+.In db.h
+include file.
+This type is normally the largest unsigned integral type available to
+the implementation.
+The
+.Fa size
+field of the key should be the size of that type.
+.Pp
+Because there can be no meta-data associated with the underlying
+recno access method files, any changes made to the default values
+(e.g., fixed record length or byte separator value) must be explicitly
+specified each time the file is opened.
+.Pp
+In the interface specified by
+.Fn dbopen ,
+using the
+.Fa put
+interface to create a new record will cause the creation of multiple,
+empty records if the record number is more than one greater than the
+largest record currently in the database.
+.Sh ERRORS
+The
+.Nm
+access method routines may fail and set
+.Va errno
+for any of the errors specified for the library routine
+.Xr dbopen 3
+or the following:
+.Bl -tag -width Er
+.It Er EINVAL
+An attempt was made to add a record to a fixed-length database that
+was too large to fit.
+.El
+.Sh SEE ALSO
+.Xr btree 3 ,
+.Xr dbopen 3 ,
+.Xr hash 3 ,
+.Xr mpool 3
+.Pp
+.Rs
+.%T "Document Processing in a Relational Database System"
+.%A Michael Stonebraker
+.%A Heidi Stettner
+.%A Joseph Kalash
+.%A Antonin Guttman
+.%A Nadene Lynn
+.%J Memorandum No. UCB/ERL M82/32
+.%D May 1982
+.Re
+.Sh BUGS
+Only big and little endian byte order is supported.
diff --git a/lib/nbsd_libc/db/mpool/Makefile.inc b/lib/nbsd_libc/db/mpool/Makefile.inc
new file mode 100644 (file)
index 0000000..c9320fb
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.4 1995/02/27 13:23:53 cgd Exp $
+#      @(#)Makefile.inc        8.1 (Berkeley) 6/4/93
+
+.PATH: ${.CURDIR}/db/mpool
+
+SRCS+= mpool.c
diff --git a/lib/nbsd_libc/db/mpool/README b/lib/nbsd_libc/db/mpool/README
new file mode 100644 (file)
index 0000000..13002b3
--- /dev/null
@@ -0,0 +1,8 @@
+#      $NetBSD: README,v 1.2 1995/02/27 13:24:00 cgd Exp $
+#      @(#)README      8.1 (Berkeley) 6/4/93
+
+These are the current memory pool routines.
+They aren't ready for prime time, yet, and
+the interface is expected to change.
+
+--keith
diff --git a/lib/nbsd_libc/db/mpool/mpool.c b/lib/nbsd_libc/db/mpool/mpool.c
new file mode 100644 (file)
index 0000000..a9ce4a0
--- /dev/null
@@ -0,0 +1,462 @@
+/*     $NetBSD: mpool.c,v 1.19 2009/04/22 18:44:06 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: mpool.c,v 1.19 2009/04/22 18:44:06 christos Exp $");
+
+#include "namespace.h"
+#include <sys/queue.h>
+#include <sys/stat.h>
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <db.h>
+
+#define        __MPOOLINTERFACE_PRIVATE
+#include <mpool.h>
+
+#ifdef __weak_alias
+__weak_alias(mpool_close,_mpool_close)
+__weak_alias(mpool_filter,_mpool_filter)
+__weak_alias(mpool_get,_mpool_get)
+__weak_alias(mpool_new,_mpool_new)
+__weak_alias(mpool_open,_mpool_open)
+__weak_alias(mpool_put,_mpool_put)
+__weak_alias(mpool_sync,_mpool_sync)
+#endif
+
+static BKT *mpool_bkt(MPOOL *);
+static BKT *mpool_look(MPOOL *, pgno_t);
+static int  mpool_write(MPOOL *, BKT *);
+
+/*
+ * mpool_open --
+ *     Initialize a memory pool.
+ */
+/*ARGSUSED*/
+MPOOL *
+mpool_open(void *key, int fd, pgno_t pagesize, pgno_t maxcache)
+{
+       struct stat sb;
+       MPOOL *mp;
+       int entry;
+
+       /*
+        * Get information about the file.
+        *
+        * XXX
+        * We don't currently handle pipes, although we should.
+        */
+       if (fstat(fd, &sb))
+               return (NULL);
+       if (!S_ISREG(sb.st_mode)) {
+               errno = ESPIPE;
+               return (NULL);
+       }
+
+       /* Allocate and initialize the MPOOL cookie. */
+       if ((mp = (MPOOL *)calloc(1, sizeof(MPOOL))) == NULL)
+               return (NULL);
+       CIRCLEQ_INIT(&mp->lqh);
+       for (entry = 0; entry < HASHSIZE; ++entry)
+               CIRCLEQ_INIT(&mp->hqh[entry]);
+       mp->maxcache = maxcache;
+       mp->npages = (pgno_t)(sb.st_size / pagesize);
+       mp->pagesize = pagesize;
+       mp->fd = fd;
+       return (mp);
+}
+
+/*
+ * mpool_filter --
+ *     Initialize input/output filters.
+ */
+void
+mpool_filter(MPOOL *mp, void (*pgin)(void *, pgno_t, void *),
+    void (*pgout)(void *, pgno_t, void *), void *pgcookie)
+{
+       mp->pgin = pgin;
+       mp->pgout = pgout;
+       mp->pgcookie = pgcookie;
+}
+       
+/*
+ * mpool_new --
+ *     Get a new page of memory.
+ */
+void *
+mpool_new( MPOOL *mp, pgno_t *pgnoaddr)
+{
+       struct _hqh *head;
+       BKT *bp;
+
+       if (mp->npages == MAX_PAGE_NUMBER) {
+               (void)fprintf(stderr, "mpool_new: page allocation overflow.\n");
+               abort();
+       }
+#ifdef STATISTICS
+       ++mp->pagenew;
+#endif
+       /*
+        * Get a BKT from the cache.  Assign a new page number, attach
+        * it to the head of the hash chain, the tail of the lru chain,
+        * and return.
+        */
+       if ((bp = mpool_bkt(mp)) == NULL)
+               return (NULL);
+       *pgnoaddr = bp->pgno = mp->npages++;
+       bp->flags = MPOOL_PINNED;
+
+       head = &mp->hqh[HASHKEY(bp->pgno)];
+       CIRCLEQ_INSERT_HEAD(head, bp, hq);
+       CIRCLEQ_INSERT_TAIL(&mp->lqh, bp, q);
+       return (bp->page);
+}
+
+/*
+ * mpool_get
+ *     Get a page.
+ */
+/*ARGSUSED*/
+void *
+mpool_get(MPOOL *mp, pgno_t pgno, u_int flags)
+{
+       struct _hqh *head;
+       BKT *bp;
+       off_t off;
+       ssize_t nr;
+
+       /* Check for attempt to retrieve a non-existent page. */
+       if (pgno >= mp->npages) {
+               errno = EINVAL;
+               return (NULL);
+       }
+
+#ifdef STATISTICS
+       ++mp->pageget;
+#endif
+
+       /* Check for a page that is cached. */
+       if ((bp = mpool_look(mp, pgno)) != NULL) {
+#ifdef DEBUG
+               if (bp->flags & MPOOL_PINNED) {
+                       (void)fprintf(stderr,
+                           "mpool_get: page %d already pinned\n", bp->pgno);
+                       abort();
+               }
+#endif
+               /*
+                * Move the page to the head of the hash chain and the tail
+                * of the lru chain.
+                */
+               head = &mp->hqh[HASHKEY(bp->pgno)];
+               CIRCLEQ_REMOVE(head, bp, hq);
+               CIRCLEQ_INSERT_HEAD(head, bp, hq);
+               CIRCLEQ_REMOVE(&mp->lqh, bp, q);
+               CIRCLEQ_INSERT_TAIL(&mp->lqh, bp, q);
+
+               /* Return a pinned page. */
+               bp->flags |= MPOOL_PINNED;
+               return (bp->page);
+       }
+
+       /* Get a page from the cache. */
+       if ((bp = mpool_bkt(mp)) == NULL)
+               return (NULL);
+
+       /* Read in the contents. */
+#ifdef STATISTICS
+       ++mp->pageread;
+#endif
+       off = mp->pagesize * pgno;
+       if ((nr = pread(mp->fd, bp->page, (size_t)mp->pagesize, off)) != (int)mp->pagesize) {
+               if (nr >= 0)
+                       errno = EFTYPE;
+               return (NULL);
+       }
+
+       /* Set the page number, pin the page. */
+       bp->pgno = pgno;
+       bp->flags = MPOOL_PINNED;
+
+       /*
+        * Add the page to the head of the hash chain and the tail
+        * of the lru chain.
+        */
+       head = &mp->hqh[HASHKEY(bp->pgno)];
+       CIRCLEQ_INSERT_HEAD(head, bp, hq);
+       CIRCLEQ_INSERT_TAIL(&mp->lqh, bp, q);
+
+       /* Run through the user's filter. */
+       if (mp->pgin != NULL)
+               (mp->pgin)(mp->pgcookie, bp->pgno, bp->page);
+
+       return (bp->page);
+}
+
+/*
+ * mpool_put
+ *     Return a page.
+ */
+/*ARGSUSED*/
+int
+mpool_put(MPOOL *mp, void *page, u_int flags)
+{
+       BKT *bp;
+
+#ifdef STATISTICS
+       ++mp->pageput;
+#endif
+       bp = (BKT *)(void *)((char *)page - sizeof(BKT));
+#ifdef DEBUG
+       if (!(bp->flags & MPOOL_PINNED)) {
+               (void)fprintf(stderr,
+                   "mpool_put: page %d not pinned\n", bp->pgno);
+               abort();
+       }
+#endif
+       bp->flags &= ~MPOOL_PINNED;
+       bp->flags |= flags & MPOOL_DIRTY;
+       return (RET_SUCCESS);
+}
+
+/*
+ * mpool_close
+ *     Close the buffer pool.
+ */
+int
+mpool_close(MPOOL *mp)
+{
+       BKT *bp;
+
+       /* Free up any space allocated to the lru pages. */
+       while ((bp = mp->lqh.cqh_first) != (void *)&mp->lqh) {
+               CIRCLEQ_REMOVE(&mp->lqh, mp->lqh.cqh_first, q);
+               free(bp);
+       }
+
+       /* Free the MPOOL cookie. */
+       free(mp);
+       return (RET_SUCCESS);
+}
+
+/*
+ * mpool_sync
+ *     Sync the pool to disk.
+ */
+int
+mpool_sync(MPOOL *mp)
+{
+       BKT *bp;
+
+       /* Walk the lru chain, flushing any dirty pages to disk. */
+       for (bp = mp->lqh.cqh_first;
+           bp != (void *)&mp->lqh; bp = bp->q.cqe_next)
+               if (bp->flags & MPOOL_DIRTY &&
+                   mpool_write(mp, bp) == RET_ERROR)
+                       return (RET_ERROR);
+
+       /* Sync the file descriptor. */
+       return (fsync(mp->fd) ? RET_ERROR : RET_SUCCESS);
+}
+
+/*
+ * mpool_bkt
+ *     Get a page from the cache (or create one).
+ */
+static BKT *
+mpool_bkt(MPOOL *mp)
+{
+       struct _hqh *head;
+       BKT *bp;
+
+       /* If under the max cached, always create a new page. */
+       if (mp->curcache < mp->maxcache)
+               goto new;
+
+       /*
+        * If the cache is max'd out, walk the lru list for a buffer we
+        * can flush.  If we find one, write it (if necessary) and take it
+        * off any lists.  If we don't find anything we grow the cache anyway.
+        * The cache never shrinks.
+        */
+       for (bp = mp->lqh.cqh_first;
+           bp != (void *)&mp->lqh; bp = bp->q.cqe_next)
+               if (!(bp->flags & MPOOL_PINNED)) {
+                       /* Flush if dirty. */
+                       if (bp->flags & MPOOL_DIRTY &&
+                           mpool_write(mp, bp) == RET_ERROR)
+                               return (NULL);
+#ifdef STATISTICS
+                       ++mp->pageflush;
+#endif
+                       /* Remove from the hash and lru queues. */
+                       head = &mp->hqh[HASHKEY(bp->pgno)];
+                       CIRCLEQ_REMOVE(head, bp, hq);
+                       CIRCLEQ_REMOVE(&mp->lqh, bp, q);
+#ifdef DEBUG
+                       {
+                               void *spage = bp->page;
+                               (void)memset(bp, 0xff,
+                                   (size_t)(sizeof(BKT) + mp->pagesize));
+                               bp->page = spage;
+                       }
+#endif
+                       return (bp);
+               }
+
+new:   if ((bp = calloc(1, (size_t)(sizeof(BKT) + mp->pagesize))) == NULL)
+               return (NULL);
+#ifdef STATISTICS
+       ++mp->pagealloc;
+#endif
+#if defined(DEBUG) || defined(PURIFY)
+       (void)memset(bp, 0xff, (size_t)(sizeof(BKT) + mp->pagesize));
+#endif
+       bp->page = (char *)(void *)bp + sizeof(BKT);
+       ++mp->curcache;
+       return (bp);
+}
+
+/*
+ * mpool_write
+ *     Write a page to disk.
+ */
+static int
+mpool_write(MPOOL *mp, BKT *bp)
+{
+       off_t off;
+
+#ifdef STATISTICS
+       ++mp->pagewrite;
+#endif
+
+       /* Run through the user's filter. */
+       if (mp->pgout)
+               (mp->pgout)(mp->pgcookie, bp->pgno, bp->page);
+
+       off = mp->pagesize * bp->pgno;
+       if (pwrite(mp->fd, bp->page, (size_t)mp->pagesize, off) != (int)mp->pagesize)
+               return (RET_ERROR);
+
+       /*
+        * Re-run through the input filter since this page may soon be
+        * accessed via the cache, and whatever the user's output filter
+        * did may screw things up if we don't let the input filter
+        * restore the in-core copy.
+        */
+       if (mp->pgin)
+               (mp->pgin)(mp->pgcookie, bp->pgno, bp->page);
+
+       bp->flags &= ~MPOOL_DIRTY;
+       return (RET_SUCCESS);
+}
+
+/*
+ * mpool_look
+ *     Lookup a page in the cache.
+ */
+static BKT *
+mpool_look(MPOOL *mp, pgno_t pgno)
+{
+       struct _hqh *head;
+       BKT *bp;
+
+       head = &mp->hqh[HASHKEY(pgno)];
+       for (bp = head->cqh_first; bp != (void *)head; bp = bp->hq.cqe_next)
+               if (bp->pgno == pgno) {
+#ifdef STATISTICS
+                       ++mp->cachehit;
+#endif
+                       return (bp);
+               }
+#ifdef STATISTICS
+       ++mp->cachemiss;
+#endif
+       return (NULL);
+}
+
+#ifdef STATISTICS
+/*
+ * mpool_stat
+ *     Print out cache statistics.
+ */
+void
+mpool_stat(mp)
+       MPOOL *mp;
+{
+       BKT *bp;
+       int cnt;
+       const char *sep;
+
+       (void)fprintf(stderr, "%lu pages in the file\n", (u_long)mp->npages);
+       (void)fprintf(stderr,
+           "page size %lu, cacheing %lu pages of %lu page max cache\n",
+           (u_long)mp->pagesize, (u_long)mp->curcache, (u_long)mp->maxcache);
+       (void)fprintf(stderr, "%lu page puts, %lu page gets, %lu page new\n",
+           mp->pageput, mp->pageget, mp->pagenew);
+       (void)fprintf(stderr, "%lu page allocs, %lu page flushes\n",
+           mp->pagealloc, mp->pageflush);
+       if (mp->cachehit + mp->cachemiss)
+               (void)fprintf(stderr,
+                   "%.0f%% cache hit rate (%lu hits, %lu misses)\n", 
+                   ((double)mp->cachehit / (mp->cachehit + mp->cachemiss))
+                   * 100, mp->cachehit, mp->cachemiss);
+       (void)fprintf(stderr, "%lu page reads, %lu page writes\n",
+           mp->pageread, mp->pagewrite);
+
+       sep = "";
+       cnt = 0;
+       for (bp = mp->lqh.cqh_first;
+           bp != (void *)&mp->lqh; bp = bp->q.cqe_next) {
+               (void)fprintf(stderr, "%s%d", sep, bp->pgno);
+               if (bp->flags & MPOOL_DIRTY)
+                       (void)fprintf(stderr, "d");
+               if (bp->flags & MPOOL_PINNED)
+                       (void)fprintf(stderr, "P");
+               if (++cnt == 10) {
+                       sep = "\n";
+                       cnt = 0;
+               } else
+                       sep = ", ";
+                       
+       }
+       (void)fprintf(stderr, "\n");
+}
+#endif
diff --git a/lib/nbsd_libc/db/recno/Makefile.inc b/lib/nbsd_libc/db/recno/Makefile.inc
new file mode 100644 (file)
index 0000000..e7f78f4
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.5 1996/05/03 21:38:43 cgd Exp $
+#       @(#)Makefile.inc       8.1 (Berkeley) 6/4/93
+
+.PATH: ${.CURDIR}/db/recno
+
+SRCS+= rec_close.c rec_delete.c rec_get.c rec_open.c rec_put.c rec_search.c \
+       rec_seq.c rec_utils.c
diff --git a/lib/nbsd_libc/db/recno/extern.h b/lib/nbsd_libc/db/recno/extern.h
new file mode 100644 (file)
index 0000000..f73c83d
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: extern.h,v 1.8 2008/08/26 21:18:38 joerg Exp $ */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ *
+ *     @(#)extern.h    8.3 (Berkeley) 6/4/94
+ */
+
+#include "../btree/extern.h"
+
+int     __rec_close(DB *);
+int     __rec_delete(const DB *, const DBT *, u_int);
+int     __rec_dleaf(BTREE *, PAGE *, uint32_t);
+int     __rec_fd(const DB *);
+int     __rec_fmap(BTREE *, recno_t);
+int     __rec_fout(BTREE *);
+int     __rec_fpipe(BTREE *, recno_t);
+int     __rec_get(const DB *, const DBT *, DBT *, u_int);
+int     __rec_iput(BTREE *, recno_t, const DBT *, u_int);
+int     __rec_put(const DB *dbp, DBT *, const DBT *, u_int);
+int     __rec_ret(BTREE *, EPG *, recno_t, DBT *, DBT *);
+EPG    *__rec_search(BTREE *, recno_t, enum SRCHOP);
+int     __rec_seq(const DB *, DBT *, DBT *, u_int);
+int     __rec_sync(const DB *, u_int);
+int     __rec_vmap(BTREE *, recno_t);
+int     __rec_vout(BTREE *);
+int     __rec_vpipe(BTREE *, recno_t);
diff --git a/lib/nbsd_libc/db/recno/rec_close.c b/lib/nbsd_libc/db/recno/rec_close.c
new file mode 100644 (file)
index 0000000..aa31044
--- /dev/null
@@ -0,0 +1,186 @@
+/*     $NetBSD: rec_close.c,v 1.15 2008/09/11 12:58:00 joerg Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: rec_close.c,v 1.15 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <sys/mman.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include <db.h>
+#include "recno.h"
+
+/*
+ * __REC_CLOSE -- Close a recno tree.
+ *
+ * Parameters:
+ *     dbp:    pointer to access method
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+int
+__rec_close(DB *dbp)
+{
+       BTREE *t;
+       int status;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       if (__rec_sync(dbp, 0) == RET_ERROR)
+               return (RET_ERROR);
+
+       /* Committed to closing. */
+       status = RET_SUCCESS;
+       if (F_ISSET(t, R_MEMMAPPED) && munmap(t->bt_smap, t->bt_msize))
+               status = RET_ERROR;
+
+       if (!F_ISSET(t, R_INMEM)) {
+               if (F_ISSET(t, R_CLOSEFP)) {
+                       if (fclose(t->bt_rfp))
+                               status = RET_ERROR;
+               } else {
+                       if (close(t->bt_rfd))
+                               status = RET_ERROR;
+               }
+       }
+
+       if (__bt_close(dbp) == RET_ERROR)
+               status = RET_ERROR;
+
+       return (status);
+}
+
+/*
+ * __REC_SYNC -- sync the recno tree to disk.
+ *
+ * Parameters:
+ *     dbp:    pointer to access method
+ *
+ * Returns:
+ *     RET_SUCCESS, RET_ERROR.
+ */
+int
+__rec_sync(const DB *dbp, u_int flags)
+{
+       struct iovec iov[2];
+       BTREE *t;
+       DBT data, key;
+       off_t off;
+       recno_t scursor, trec;
+       int status;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       if (flags == R_RECNOSYNC)
+               return (__bt_sync(dbp, 0));
+
+       if (F_ISSET(t, R_RDONLY | R_INMEM) || !F_ISSET(t, R_MODIFIED))
+               return (RET_SUCCESS);
+
+       /* Read any remaining records into the tree. */
+       if (!F_ISSET(t, R_EOF) && t->bt_irec(t, MAX_REC_NUMBER) == RET_ERROR)
+               return (RET_ERROR);
+
+       /* Rewind the file descriptor. */
+       if (lseek(t->bt_rfd, (off_t)0, SEEK_SET) != 0)
+               return (RET_ERROR);
+
+       /* Save the cursor. */
+       scursor = t->bt_cursor.rcursor;
+
+       key.size = sizeof(recno_t);
+       key.data = &trec;
+
+       if (F_ISSET(t, R_FIXLEN)) {
+               /*
+                * We assume that fixed length records are all fixed length.
+                * Any that aren't are either EINVAL'd or corrected by the
+                * record put code.
+                */
+               status = (dbp->seq)(dbp, &key, &data, R_FIRST);
+               while (status == RET_SUCCESS) {
+                       if (write(t->bt_rfd, data.data, data.size) !=
+                           (ssize_t) data.size)
+                               return (RET_ERROR);
+                       status = (dbp->seq)(dbp, &key, &data, R_NEXT);
+               }
+       } else {
+               iov[1].iov_base = &t->bt_bval;
+               iov[1].iov_len = 1;
+
+               status = (dbp->seq)(dbp, &key, &data, R_FIRST);
+               while (status == RET_SUCCESS) {
+                       iov[0].iov_base = data.data;
+                       iov[0].iov_len = data.size;
+                       if (writev(t->bt_rfd, iov, 2) !=
+                           (ssize_t) (data.size + 1))
+                               return (RET_ERROR);
+                       status = (dbp->seq)(dbp, &key, &data, R_NEXT);
+               }
+       }
+
+       /* Restore the cursor. */
+       t->bt_cursor.rcursor = scursor;
+
+       if (status == RET_ERROR)
+               return (RET_ERROR);
+       if ((off = lseek(t->bt_rfd, (off_t)0, SEEK_CUR)) == -1)
+               return (RET_ERROR);
+       if (ftruncate(t->bt_rfd, off))
+               return (RET_ERROR);
+       F_CLR(t, R_MODIFIED);
+       return (RET_SUCCESS);
+}
diff --git a/lib/nbsd_libc/db/recno/rec_delete.c b/lib/nbsd_libc/db/recno/rec_delete.c
new file mode 100644 (file)
index 0000000..a9dea57
--- /dev/null
@@ -0,0 +1,197 @@
+/*     $NetBSD: rec_delete.c,v 1.17 2008/09/11 12:58:00 joerg Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: rec_delete.c,v 1.17 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <db.h>
+#include "recno.h"
+
+static int rec_rdelete(BTREE *, recno_t);
+
+/*
+ * __REC_DELETE -- Delete the item(s) referenced by a key.
+ *
+ * Parameters:
+ *     dbp:    pointer to access method
+ *     key:    key to delete
+ *     flags:  R_CURSOR if deleting what the cursor references
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key not found.
+ */
+int
+__rec_delete(const DB *dbp, const DBT *key, u_int flags)
+{
+       BTREE *t;
+       recno_t nrec;
+       int status;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       switch(flags) {
+       case 0:
+               if ((nrec = *(recno_t *)key->data) == 0)
+                       goto einval;
+               if (nrec > t->bt_nrecs)
+                       return (RET_SPECIAL);
+               --nrec;
+               status = rec_rdelete(t, nrec);
+               break;
+       case R_CURSOR:
+               if (!F_ISSET(&t->bt_cursor, CURS_INIT))
+                       goto einval;
+               if (t->bt_nrecs == 0)
+                       return (RET_SPECIAL);
+               status = rec_rdelete(t, t->bt_cursor.rcursor - 1);
+               if (status == RET_SUCCESS)
+                       --t->bt_cursor.rcursor;
+               break;
+       default:
+einval:                errno = EINVAL;
+               return (RET_ERROR);
+       }
+
+       if (status == RET_SUCCESS)
+               F_SET(t, B_MODIFIED | R_MODIFIED);
+       return (status);
+}
+
+/*
+ * REC_RDELETE -- Delete the data matching the specified key.
+ *
+ * Parameters:
+ *     tree:   tree
+ *     nrec:   record to delete
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key not found.
+ */
+static int
+rec_rdelete(BTREE *t, recno_t nrec)
+{
+       EPG *e;
+       PAGE *h;
+       int status;
+
+       /* Find the record; __rec_search pins the page. */
+       if ((e = __rec_search(t, nrec, SDELETE)) == NULL)
+               return (RET_ERROR);
+
+       /* Delete the record. */
+       h = e->page;
+       status = __rec_dleaf(t, h, (uint32_t)e->index);
+       if (status != RET_SUCCESS) {
+               mpool_put(t->bt_mp, h, 0);
+               return (status);
+       }
+       mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+       return (RET_SUCCESS);
+}
+
+/*
+ * __REC_DLEAF -- Delete a single record from a recno leaf page.
+ *
+ * Parameters:
+ *     t:      tree
+ *     index:  index on current page to delete
+ *
+ * Returns:
+ *     RET_SUCCESS, RET_ERROR.
+ */
+int
+__rec_dleaf(BTREE *t, PAGE *h, uint32_t idx)
+{
+       RLEAF *rl;
+       indx_t *ip, cnt, offset;
+       uint32_t nbytes;
+       char *from;
+       void *to;
+       size_t temp;
+
+       /*
+        * Delete a record from a recno leaf page.  Internal records are never
+        * deleted from internal pages, regardless of the records that caused
+        * them to be added being deleted.  Pages made empty by deletion are
+        * not reclaimed.  They are, however, made available for reuse.
+        *
+        * Pack the remaining entries at the end of the page, shift the indices
+        * down, overwriting the deleted record and its index.  If the record
+        * uses overflow pages, make them available for reuse.
+        */
+       to = rl = GETRLEAF(h, idx);
+       if (rl->flags & P_BIGDATA && __ovfl_delete(t, rl->bytes) == RET_ERROR)
+               return (RET_ERROR);
+       nbytes = NRLEAF(rl);
+
+       /*
+        * Compress the key/data pairs.  Compress and adjust the [BR]LEAF
+        * offsets.  Reset the headers.
+        */
+       from = (char *)(void *)h + h->upper;
+       memmove(from + nbytes, from, (size_t)((char *)to - from));
+       h->upper += nbytes;
+
+       offset = h->linp[idx];
+       temp = &h->linp[idx] - (ip = &h->linp[0]);
+       _DBFIT(temp, uint16_t);
+       for (cnt = (uint16_t)temp;  cnt--; ++ip)
+               if (ip[0] < offset)
+                       ip[0] += nbytes;
+       temp = &h->linp[NEXTINDEX(h)] - ip;
+       _DBFIT(temp, uint16_t);
+       for (cnt = (uint16_t)temp;  --cnt; ++ip)
+               ip[0] = ip[1] < offset ? ip[1] + nbytes : ip[1];
+       h->lower -= sizeof(indx_t);
+       --t->bt_nrecs;
+       return (RET_SUCCESS);
+}
diff --git a/lib/nbsd_libc/db/recno/rec_get.c b/lib/nbsd_libc/db/recno/rec_get.c
new file mode 100644 (file)
index 0000000..1dc80f9
--- /dev/null
@@ -0,0 +1,302 @@
+/*     $NetBSD: rec_get.c,v 1.16 2008/09/11 12:58:00 joerg Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: rec_get.c,v 1.16 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <db.h>
+#include "recno.h"
+
+/*
+ * __REC_GET -- Get a record from the btree.
+ *
+ * Parameters:
+ *     dbp:    pointer to access method
+ *     key:    key to find
+ *     data:   data to return
+ *     flag:   currently unused
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key not found.
+ */
+int
+__rec_get(const DB *dbp, const DBT *key, DBT *data, u_int flags)
+{
+       BTREE *t;
+       EPG *e;
+       recno_t nrec;
+       int status;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       /* Get currently doesn't take any flags, and keys of 0 are illegal. */
+       if (flags || (nrec = *(recno_t *)key->data) == 0) {
+               errno = EINVAL;
+               return (RET_ERROR);
+       }
+
+       /*
+        * If we haven't seen this record yet, try to find it in the
+        * original file.
+        */
+       if (nrec > t->bt_nrecs) {
+               if (F_ISSET(t, R_EOF | R_INMEM))
+                       return (RET_SPECIAL);
+               if ((status = t->bt_irec(t, nrec)) != RET_SUCCESS)
+                       return (status);
+       }
+
+       --nrec;
+       if ((e = __rec_search(t, nrec, SEARCH)) == NULL)
+               return (RET_ERROR);
+
+       status = __rec_ret(t, e, 0, NULL, data);
+       if (F_ISSET(t, B_DB_LOCK))
+               mpool_put(t->bt_mp, e->page, 0);
+       else
+               t->bt_pinned = e->page;
+       return (status);
+}
+
+/*
+ * __REC_FPIPE -- Get fixed length records from a pipe.
+ *
+ * Parameters:
+ *     t:      tree
+ *     cnt:    records to read
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+int
+__rec_fpipe(BTREE *t, recno_t top)
+{
+       DBT data;
+       recno_t nrec;
+       size_t len;
+       int ch;
+       uint8_t *p;
+
+       if (t->bt_rdata.size < t->bt_reclen) {
+               t->bt_rdata.data = t->bt_rdata.data == NULL ?
+                   malloc(t->bt_reclen) :
+                   realloc(t->bt_rdata.data, t->bt_reclen);
+               if (t->bt_rdata.data == NULL)
+                       return (RET_ERROR);
+               t->bt_rdata.size = t->bt_reclen;
+       }
+       data.data = t->bt_rdata.data;
+       data.size = t->bt_reclen;
+
+       for (nrec = t->bt_nrecs; nrec < top;) {
+               len = t->bt_reclen;
+               for (p = t->bt_rdata.data;; *p++ = ch)
+                       if ((ch = getc(t->bt_rfp)) == EOF || !--len) {
+                               if (ch != EOF)
+                                       *p = ch;
+                               if (len != 0)
+                                       memset(p, t->bt_bval, len);
+                               if (__rec_iput(t,
+                                   nrec, &data, 0) != RET_SUCCESS)
+                                       return (RET_ERROR);
+                               ++nrec;
+                               break;
+                       }
+               if (ch == EOF)
+                       break;
+       }
+       if (nrec < top) {
+               F_SET(t, R_EOF);
+               return (RET_SPECIAL);
+       }
+       return (RET_SUCCESS);
+}
+
+/*
+ * __REC_VPIPE -- Get variable length records from a pipe.
+ *
+ * Parameters:
+ *     t:      tree
+ *     cnt:    records to read
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+int
+__rec_vpipe(BTREE *t, recno_t top)
+{
+       DBT data;
+       recno_t nrec;
+       ptrdiff_t len;
+       size_t sz;
+       int bval, ch;
+       uint8_t *p;
+
+       bval = t->bt_bval;
+       for (nrec = t->bt_nrecs; nrec < top; ++nrec) {
+               for (p = t->bt_rdata.data,
+                   sz = t->bt_rdata.size;; *p++ = ch, --sz) {
+                       if ((ch = getc(t->bt_rfp)) == EOF || ch == bval) {
+                               data.data = t->bt_rdata.data;
+                               data.size = p - (uint8_t *)t->bt_rdata.data;
+                               if (ch == EOF && data.size == 0)
+                                       break;
+                               if (__rec_iput(t, nrec, &data, 0)
+                                   != RET_SUCCESS)
+                                       return (RET_ERROR);
+                               break;
+                       }
+                       if (sz == 0) {
+                               len = p - (uint8_t *)t->bt_rdata.data;
+                               t->bt_rdata.size += (sz = 256);
+                               t->bt_rdata.data = t->bt_rdata.data == NULL ?
+                                   malloc(t->bt_rdata.size) :
+                                   realloc(t->bt_rdata.data, t->bt_rdata.size);
+                               if (t->bt_rdata.data == NULL)
+                                       return (RET_ERROR);
+                               p = (uint8_t *)t->bt_rdata.data + len;
+                       }
+               }
+               if (ch == EOF)
+                       break;
+       }
+       if (nrec < top) {
+               F_SET(t, R_EOF);
+               return (RET_SPECIAL);
+       }
+       return (RET_SUCCESS);
+}
+
+/*
+ * __REC_FMAP -- Get fixed length records from a file.
+ *
+ * Parameters:
+ *     t:      tree
+ *     cnt:    records to read
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+int
+__rec_fmap(BTREE *t, recno_t top)
+{
+       DBT data;
+       recno_t nrec;
+       uint8_t *sp, *ep, *p;
+       size_t len;
+
+       if (t->bt_rdata.size < t->bt_reclen) {
+               t->bt_rdata.data = t->bt_rdata.data == NULL ?
+                   malloc(t->bt_reclen) :
+                   realloc(t->bt_rdata.data, t->bt_reclen);
+               if (t->bt_rdata.data == NULL)
+                       return (RET_ERROR);
+               t->bt_rdata.size = t->bt_reclen;
+       }
+       data.data = t->bt_rdata.data;
+       data.size = t->bt_reclen;
+
+       sp = (uint8_t *)t->bt_cmap;
+       ep = (uint8_t *)t->bt_emap;
+       for (nrec = t->bt_nrecs; nrec < top; ++nrec) {
+               if (sp >= ep) {
+                       F_SET(t, R_EOF);
+                       return (RET_SPECIAL);
+               }
+               len = t->bt_reclen;
+               for (p = t->bt_rdata.data;
+                   sp < ep && len > 0; *p++ = *sp++, --len);
+               if (len != 0)
+                       memset(p, t->bt_bval, len);
+               if (__rec_iput(t, nrec, &data, 0) != RET_SUCCESS)
+                       return (RET_ERROR);
+       }
+       t->bt_cmap = (caddr_t)sp;
+       return (RET_SUCCESS);
+}
+
+/*
+ * __REC_VMAP -- Get variable length records from a file.
+ *
+ * Parameters:
+ *     t:      tree
+ *     cnt:    records to read
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+int
+__rec_vmap(BTREE *t, recno_t top)
+{
+       DBT data;
+       uint8_t *sp, *ep;
+       recno_t nrec;
+       int bval;
+
+       sp = (uint8_t *)t->bt_cmap;
+       ep = (uint8_t *)t->bt_emap;
+       bval = t->bt_bval;
+
+       for (nrec = t->bt_nrecs; nrec < top; ++nrec) {
+               if (sp >= ep) {
+                       F_SET(t, R_EOF);
+                       return (RET_SPECIAL);
+               }
+               for (data.data = sp; sp < ep && *sp != bval; ++sp);
+               data.size = sp - (uint8_t *)data.data;
+               if (__rec_iput(t, nrec, &data, 0) != RET_SUCCESS)
+                       return (RET_ERROR);
+               ++sp;
+       }
+       t->bt_cmap = (caddr_t)sp;
+       return (RET_SUCCESS);
+}
diff --git a/lib/nbsd_libc/db/recno/rec_open.c b/lib/nbsd_libc/db/recno/rec_open.c
new file mode 100644 (file)
index 0000000..ff1852e
--- /dev/null
@@ -0,0 +1,246 @@
+/*     $NetBSD: rec_open.c,v 1.17 2008/09/11 12:58:00 joerg Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Olson.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: rec_open.c,v 1.17 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include <db.h>
+#include "recno.h"
+
+DB *
+__rec_open(const char *fname, int flags, mode_t mode, const RECNOINFO *openinfo,
+    int dflags)
+{
+       BTREE *t;
+       BTREEINFO btopeninfo;
+       DB *dbp;
+       PAGE *h;
+       struct stat sb;
+       int rfd = -1;   /* pacify gcc */
+       int sverrno;
+
+       dbp = NULL;
+       /* Open the user's file -- if this fails, we're done. */
+       if (fname != NULL) {
+               if ((rfd = open(fname, flags, mode)) == -1)
+                       return (NULL);
+               if (fcntl(rfd, F_SETFD, FD_CLOEXEC) == -1)
+                       goto err;
+       }
+
+       /* Create a btree in memory (backed by disk). */
+       if (openinfo) {
+               if (openinfo->flags & ~(R_FIXEDLEN | R_NOKEY | R_SNAPSHOT))
+                       goto einval;
+               btopeninfo.flags = 0;
+               btopeninfo.cachesize = openinfo->cachesize;
+               btopeninfo.maxkeypage = 0;
+               btopeninfo.minkeypage = 0;
+               btopeninfo.psize = openinfo->psize;
+               btopeninfo.compare = NULL;
+               btopeninfo.prefix = NULL;
+               btopeninfo.lorder = openinfo->lorder;
+               dbp = __bt_open(openinfo->bfname,
+                   O_RDWR, S_IRUSR | S_IWUSR, &btopeninfo, dflags);
+       } else
+               dbp = __bt_open(NULL, O_RDWR, S_IRUSR | S_IWUSR, NULL, dflags);
+       if (dbp == NULL)
+               goto err;
+
+       /*
+        * Some fields in the tree structure are recno specific.  Fill them
+        * in and make the btree structure look like a recno structure.  We
+        * don't change the bt_ovflsize value, it's close enough and slightly
+        * bigger.
+        */
+       t = dbp->internal;
+       if (openinfo) {
+               if (openinfo->flags & R_FIXEDLEN) {
+                       F_SET(t, R_FIXLEN);
+                       t->bt_reclen = openinfo->reclen;
+                       if (t->bt_reclen == 0)
+                               goto einval;
+               }
+               t->bt_bval = openinfo->bval;
+       } else
+               t->bt_bval = '\n';
+
+       F_SET(t, R_RECNO);
+       if (fname == NULL)
+               F_SET(t, R_EOF | R_INMEM);
+       else
+               t->bt_rfd = rfd;
+
+       if (fname != NULL) {
+               /*
+                * In 4.4BSD, stat(2) returns true for ISSOCK on pipes.
+                * Unfortunately, that's not portable, so we use lseek
+                * and check the errno values.
+                */
+               errno = 0;
+               if (lseek(rfd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE) {
+                       switch (flags & O_ACCMODE) {
+                       case O_RDONLY:
+                               F_SET(t, R_RDONLY);
+                               break;
+                       default:
+                               goto einval;
+                       }
+slow:                  if ((t->bt_rfp = fdopen(rfd, "r")) == NULL)
+                               goto err;
+                       F_SET(t, R_CLOSEFP);
+                       t->bt_irec =
+                           F_ISSET(t, R_FIXLEN) ? __rec_fpipe : __rec_vpipe;
+               } else {
+                       switch (flags & O_ACCMODE) {
+                       case O_RDONLY:
+                               F_SET(t, R_RDONLY);
+                               break;
+                       case O_RDWR:
+                               break;
+                       default:
+                               goto einval;
+                       }
+
+                       if (fstat(rfd, &sb))
+                               goto err;
+                       /*
+                        * Kluge -- we'd like to test to see if the file is too
+                        * big to mmap.  Since, we don't know what size or type
+                        * off_t's or size_t's are, what the largest unsigned
+                        * integral type is, or what random insanity the local
+                        * C compiler will perpetrate, doing the comparison in
+                        * a portable way is flatly impossible.  Hope that mmap
+                        * fails if the file is too large.
+                        */
+                       if (sb.st_size == 0)
+                               F_SET(t, R_EOF);
+                       else {
+#ifdef MMAP_NOT_AVAILABLE
+                               /*
+                                * XXX
+                                * Mmap doesn't work correctly on many current
+                                * systems.  In particular, it can fail subtly,
+                                * with cache coherency problems.  Don't use it
+                                * for now.
+                                */
+                               t->bt_msize = sb.st_size;
+                               if ((t->bt_smap = mmap(NULL, t->bt_msize,
+                                   PROT_READ, MAP_FILE | MAP_PRIVATE, rfd,
+                                   (off_t)0)) == (caddr_t)-1)
+                                       goto slow;
+                               t->bt_cmap = t->bt_smap;
+                               t->bt_emap = t->bt_smap + sb.st_size;
+                               t->bt_irec = F_ISSET(t, R_FIXLEN) ?
+                                   __rec_fmap : __rec_vmap;
+                               F_SET(t, R_MEMMAPPED);
+#else
+                               goto slow;
+#endif
+                       }
+               }
+       }
+
+       /* Use the recno routines. */
+       dbp->close = __rec_close;
+       dbp->del = __rec_delete;
+       dbp->fd = __rec_fd;
+       dbp->get = __rec_get;
+       dbp->put = __rec_put;
+       dbp->seq = __rec_seq;
+       dbp->sync = __rec_sync;
+
+       /* If the root page was created, reset the flags. */
+       if ((h = mpool_get(t->bt_mp, P_ROOT, 0)) == NULL)
+               goto err;
+       if ((h->flags & P_TYPE) == P_BLEAF) {
+               F_CLR(h, P_TYPE);
+               F_SET(h, P_RLEAF);
+               mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+       } else
+               mpool_put(t->bt_mp, h, 0);
+
+       if (openinfo && openinfo->flags & R_SNAPSHOT &&
+           !F_ISSET(t, R_EOF | R_INMEM) &&
+           t->bt_irec(t, MAX_REC_NUMBER) == RET_ERROR)
+                goto err;
+       return (dbp);
+
+einval:        errno = EINVAL;
+err:   sverrno = errno;
+       if (dbp != NULL)
+               (void)__bt_close(dbp);
+       if (fname != NULL)
+               (void)close(rfd);
+       errno = sverrno;
+       return (NULL);
+}
+
+int
+__rec_fd(const DB *dbp)
+{
+       BTREE *t;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       /* In-memory database can't have a file descriptor. */
+       if (F_ISSET(t, R_INMEM)) {
+               errno = ENOENT;
+               return (-1);
+       }
+       return (t->bt_rfd);
+}
diff --git a/lib/nbsd_libc/db/recno/rec_put.c b/lib/nbsd_libc/db/recno/rec_put.c
new file mode 100644 (file)
index 0000000..7c1181c
--- /dev/null
@@ -0,0 +1,278 @@
+/*     $NetBSD: rec_put.c,v 1.17 2008/09/11 12:58:00 joerg Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: rec_put.c,v 1.17 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <db.h>
+#include "recno.h"
+
+/*
+ * __REC_PUT -- Add a recno item to the tree.
+ *
+ * Parameters:
+ *     dbp:    pointer to access method
+ *     key:    key
+ *     data:   data
+ *     flag:   R_CURSOR, R_IAFTER, R_IBEFORE, R_NOOVERWRITE
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key is
+ *     already in the tree and R_NOOVERWRITE specified.
+ */
+int
+__rec_put(const DB *dbp, DBT *key, const DBT *data, u_int flags)
+{
+       BTREE *t;
+       DBT fdata, tdata;
+       recno_t nrec;
+       int status;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       /*
+        * If using fixed-length records, and the record is long, return
+        * EINVAL.  If it's short, pad it out.  Use the record data return
+        * memory, it's only short-term.
+        */
+       if (F_ISSET(t, R_FIXLEN) && data->size != t->bt_reclen) {
+               if (data->size > t->bt_reclen)
+                       goto einval;
+
+               if (t->bt_rdata.size < t->bt_reclen) {
+                       t->bt_rdata.data = t->bt_rdata.data == NULL ?
+                           malloc(t->bt_reclen) :
+                           realloc(t->bt_rdata.data, t->bt_reclen);
+                       if (t->bt_rdata.data == NULL)
+                               return (RET_ERROR);
+                       t->bt_rdata.size = t->bt_reclen;
+               }
+               memmove(t->bt_rdata.data, data->data, data->size);
+               memset((char *)t->bt_rdata.data + data->size,
+                   t->bt_bval, t->bt_reclen - data->size);
+               fdata.data = t->bt_rdata.data;
+               fdata.size = t->bt_reclen;
+       } else {
+               fdata.data = data->data;
+               fdata.size = data->size;
+       }
+
+       switch (flags) {
+       case R_CURSOR:
+               if (!F_ISSET(&t->bt_cursor, CURS_INIT))
+                       goto einval;
+               nrec = t->bt_cursor.rcursor;
+               break;
+       case R_SETCURSOR:
+               if ((nrec = *(recno_t *)key->data) == 0)
+                       goto einval;
+               break;
+       case R_IAFTER:
+               if ((nrec = *(recno_t *)key->data) == 0) {
+                       nrec = 1;
+                       flags = R_IBEFORE;
+               }
+               break;
+       case 0:
+       case R_IBEFORE:
+               if ((nrec = *(recno_t *)key->data) == 0)
+                       goto einval;
+               break;
+       case R_NOOVERWRITE:
+               if ((nrec = *(recno_t *)key->data) == 0)
+                       goto einval;
+               if (nrec <= t->bt_nrecs)
+                       return (RET_SPECIAL);
+               break;
+       default:
+einval:                errno = EINVAL;
+               return (RET_ERROR);
+       }
+
+       /*
+        * Make sure that records up to and including the put record are
+        * already in the database.  If skipping records, create empty ones.
+        */
+       if (nrec > t->bt_nrecs) {
+               if (!F_ISSET(t, R_EOF | R_INMEM) &&
+                   t->bt_irec(t, nrec) == RET_ERROR)
+                       return (RET_ERROR);
+               if (nrec > t->bt_nrecs + 1) {
+                       if (F_ISSET(t, R_FIXLEN)) {
+                               if ((tdata.data =
+                                   (void *)malloc(t->bt_reclen)) == NULL)
+                                       return (RET_ERROR);
+                               tdata.size = t->bt_reclen;
+                               memset(tdata.data, t->bt_bval, tdata.size);
+                       } else {
+                               tdata.data = NULL;
+                               tdata.size = 0;
+                       }
+                       while (nrec > t->bt_nrecs + 1)
+                               if (__rec_iput(t,
+                                   t->bt_nrecs, &tdata, 0) != RET_SUCCESS)
+                                       return (RET_ERROR);
+                       if (F_ISSET(t, R_FIXLEN))
+                               free(tdata.data);
+               }
+       }
+
+       if ((status = __rec_iput(t, nrec - 1, &fdata, flags)) != RET_SUCCESS)
+               return (status);
+
+       if (flags == R_SETCURSOR)
+               t->bt_cursor.rcursor = nrec;
+       
+       F_SET(t, R_MODIFIED);
+       return (__rec_ret(t, NULL, nrec, key, NULL));
+}
+
+/*
+ * __REC_IPUT -- Add a recno item to the tree.
+ *
+ * Parameters:
+ *     t:      tree
+ *     nrec:   record number
+ *     data:   data
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS
+ */
+int
+__rec_iput(BTREE *t, recno_t nrec, const DBT *data, u_int flags)
+{
+       DBT tdata;
+       EPG *e;
+       PAGE *h;
+       indx_t idx, nxtindex;
+       pgno_t pg;
+       uint32_t nbytes;
+       int dflags, status;
+       char *dest, db[NOVFLSIZE];
+
+       /*
+        * If the data won't fit on a page, store it on indirect pages.
+        *
+        * XXX
+        * If the insert fails later on, these pages aren't recovered.
+        */
+       if (data->size > t->bt_ovflsize) {
+               if (__ovfl_put(t, data, &pg) == RET_ERROR)
+                       return (RET_ERROR);
+               tdata.data = db;
+               tdata.size = NOVFLSIZE;
+               *(pgno_t *)(void *)db = pg;
+               _DBFIT(data->size, uint32_t);
+               *(uint32_t *)(void *)(db + sizeof(pgno_t)) =
+                   (uint32_t)data->size;
+               dflags = P_BIGDATA;
+               data = &tdata;
+       } else
+               dflags = 0;
+
+       /* __rec_search pins the returned page. */
+       if ((e = __rec_search(t, nrec,
+           nrec > t->bt_nrecs || flags == R_IAFTER || flags == R_IBEFORE ?
+           SINSERT : SEARCH)) == NULL)
+               return (RET_ERROR);
+
+       h = e->page;
+       idx = e->index;
+
+       /*
+        * Add the specified key/data pair to the tree.  The R_IAFTER and
+        * R_IBEFORE flags insert the key after/before the specified key.
+        *
+        * Pages are split as required.
+        */
+       switch (flags) {
+       case R_IAFTER:
+               ++idx;
+               break;
+       case R_IBEFORE:
+               break;
+       default:
+               if (nrec < t->bt_nrecs &&
+                   __rec_dleaf(t, h, (uint32_t)idx) == RET_ERROR) {
+                       mpool_put(t->bt_mp, h, 0);
+                       return (RET_ERROR);
+               }
+               break;
+       }
+
+       /*
+        * If not enough room, split the page.  The split code will insert
+        * the key and data and unpin the current page.  If inserting into
+        * the offset array, shift the pointers up.
+        */
+       nbytes = NRLEAFDBT(data->size);
+       if ((uint32_t) (h->upper - h->lower) < nbytes + sizeof(indx_t)) {
+               status = __bt_split(t, h, NULL, data, dflags, nbytes,
+                   (uint32_t)idx);
+               if (status == RET_SUCCESS)
+                       ++t->bt_nrecs;
+               return (status);
+       }
+
+       if (idx < (nxtindex = NEXTINDEX(h)))
+               memmove(h->linp + idx + 1, h->linp + idx,
+                   (nxtindex - idx) * sizeof(indx_t));
+       h->lower += sizeof(indx_t);
+
+       h->linp[idx] = h->upper -= nbytes;
+       dest = (char *)(void *)h + h->upper;
+       WR_RLEAF(dest, data, dflags);
+
+       ++t->bt_nrecs;
+       F_SET(t, B_MODIFIED);
+       mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+
+       return (RET_SUCCESS);
+}
diff --git a/lib/nbsd_libc/db/recno/rec_search.c b/lib/nbsd_libc/db/recno/rec_search.c
new file mode 100644 (file)
index 0000000..1238c8d
--- /dev/null
@@ -0,0 +1,126 @@
+/*     $NetBSD: rec_search.c,v 1.14 2008/09/11 12:58:00 joerg Exp $    */
+
+/*-
+ * 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: rec_search.c,v 1.14 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+
+#include <db.h>
+#include "recno.h"
+
+/*
+ * __REC_SEARCH -- Search a btree for a key.
+ *
+ * Parameters:
+ *     t:      tree to search
+ *     recno:  key to find
+ *     op:     search operation
+ *
+ * Returns:
+ *     EPG for matching record, if any, or the EPG for the location of the
+ *     key, if it were inserted into the tree.
+ *
+ * Returns:
+ *     The EPG for matching record, if any, or the EPG for the location
+ *     of the key, if it were inserted into the tree, is entered into
+ *     the bt_cur field of the tree.  A pointer to the field is returned.
+ */
+EPG *
+__rec_search(BTREE *t, recno_t recno, enum SRCHOP op)
+{
+       indx_t idx;
+       PAGE *h;
+       EPGNO *parent;
+       RINTERNAL *r;
+       pgno_t pg;
+       indx_t top;
+       recno_t total;
+       int sverrno;
+
+       BT_CLR(t);
+       for (pg = P_ROOT, total = 0;;) {
+               if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
+                       goto err;
+               if (h->flags & P_RLEAF) {
+                       t->bt_cur.page = h;
+                       t->bt_cur.index = recno - total;
+                       return (&t->bt_cur);
+               }
+               for (idx = 0, top = NEXTINDEX(h);;) {
+                       r = GETRINTERNAL(h, idx);
+                       if (++idx == top || total + r->nrecs > recno)
+                               break;
+                       total += r->nrecs;
+               }
+
+               BT_PUSH(t, pg, idx - 1);
+               
+               pg = r->pgno;
+               switch (op) {
+               case SDELETE:
+                       --GETRINTERNAL(h, (idx - 1))->nrecs;
+                       mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+                       break;
+               case SINSERT:
+                       ++GETRINTERNAL(h, (idx - 1))->nrecs;
+                       mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+                       break;
+               case SEARCH:
+                       mpool_put(t->bt_mp, h, 0);
+                       break;
+               }
+
+       }
+       /* Try and recover the tree. */
+err:   sverrno = errno;
+       if (op != SEARCH)
+               while  ((parent = BT_POP(t)) != NULL) {
+                       if ((h = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL)
+                               break;
+                       if (op == SINSERT)
+                               --GETRINTERNAL(h, parent->index)->nrecs;
+                       else
+                               ++GETRINTERNAL(h, parent->index)->nrecs;
+                        mpool_put(t->bt_mp, h, MPOOL_DIRTY);
+                }
+       errno = sverrno;
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/db/recno/rec_seq.c b/lib/nbsd_libc/db/recno/rec_seq.c
new file mode 100644 (file)
index 0000000..3b1da48
--- /dev/null
@@ -0,0 +1,131 @@
+/*     $NetBSD: rec_seq.c,v 1.14 2008/09/11 12:58:00 joerg Exp $       */
+
+/*-
+ * Copyright (c) 1991, 1993, 1994
+ *     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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: rec_seq.c,v 1.14 2008/09/11 12:58:00 joerg Exp $");
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <db.h>
+#include "recno.h"
+
+/*
+ * __REC_SEQ -- Recno sequential scan interface.
+ *
+ * Parameters:
+ *     dbp:    pointer to access method
+ *     key:    key for positioning and return value
+ *     data:   data return value
+ *     flags:  R_CURSOR, R_FIRST, R_LAST, R_NEXT, R_PREV.
+ *
+ * Returns:
+ *     RET_ERROR, RET_SUCCESS or RET_SPECIAL if there's no next key.
+ */
+int
+__rec_seq(const DB *dbp, DBT *key, DBT *data, u_int flags)
+{
+       BTREE *t;
+       EPG *e;
+       recno_t nrec;
+       int status;
+
+       t = dbp->internal;
+
+       /* Toss any page pinned across calls. */
+       if (t->bt_pinned != NULL) {
+               mpool_put(t->bt_mp, t->bt_pinned, 0);
+               t->bt_pinned = NULL;
+       }
+
+       switch(flags) {
+       case R_CURSOR:
+               if ((nrec = *(recno_t *)key->data) == 0)
+                       goto einval;
+               break;
+       case R_NEXT:
+               if (F_ISSET(&t->bt_cursor, CURS_INIT)) {
+                       nrec = t->bt_cursor.rcursor + 1;
+                       break;
+               }
+               /* FALLTHROUGH */
+       case R_FIRST:
+               nrec = 1;
+               break;
+       case R_PREV:
+               if (F_ISSET(&t->bt_cursor, CURS_INIT)) {
+                       if ((nrec = t->bt_cursor.rcursor - 1) == 0)
+                               return (RET_SPECIAL);
+                       break;
+               }
+               /* FALLTHROUGH */
+       case R_LAST:
+               if (!F_ISSET(t, R_EOF | R_INMEM) &&
+                   t->bt_irec(t, MAX_REC_NUMBER) == RET_ERROR)
+                       return (RET_ERROR);
+               nrec = t->bt_nrecs;
+               break;
+       default:
+einval:                errno = EINVAL;
+               return (RET_ERROR);
+       }
+       
+       if (t->bt_nrecs == 0 || nrec > t->bt_nrecs) {
+               if (!F_ISSET(t, R_EOF | R_INMEM) &&
+                   (status = t->bt_irec(t, nrec)) != RET_SUCCESS)
+                       return (status);
+               if (t->bt_nrecs == 0 || nrec > t->bt_nrecs)
+                       return (RET_SPECIAL);
+       }
+
+       if ((e = __rec_search(t, nrec - 1, SEARCH)) == NULL)
+               return (RET_ERROR);
+
+       F_SET(&t->bt_cursor, CURS_INIT);
+       t->bt_cursor.rcursor = nrec;
+
+       status = __rec_ret(t, e, nrec, key, data);
+       if (F_ISSET(t, B_DB_LOCK))
+               mpool_put(t->bt_mp, e->page, 0);
+       else
+               t->bt_pinned = e->page;
+       return (status);
+}
diff --git a/lib/nbsd_libc/db/recno/rec_utils.c b/lib/nbsd_libc/db/recno/rec_utils.c
new file mode 100644 (file)
index 0000000..2a61c7b
--- /dev/null
@@ -0,0 +1,120 @@
+/*     $NetBSD: rec_utils.c,v 1.12 2008/09/10 17:52:36 joerg Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: rec_utils.c,v 1.12 2008/09/10 17:52:36 joerg Exp $");
+
+#include <sys/param.h>
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <db.h>
+#include "recno.h"
+
+/*
+ * __rec_ret --
+ *     Build return data.
+ *
+ * Parameters:
+ *     t:      tree
+ *     e:      key/data pair to be returned
+ *   nrec:     record number
+ *    key:     user's key structure
+ *     data:   user's data structure
+ *
+ * Returns:
+ *     RET_SUCCESS, RET_ERROR.
+ */
+int
+__rec_ret(BTREE *t, EPG *e, recno_t nrec, DBT *key, DBT *data)
+{
+       RLEAF *rl;
+       void *p;
+
+       if (key == NULL)
+               goto dataonly;
+
+       /* We have to copy the key, it's not on the page. */
+       if (sizeof(recno_t) > t->bt_rkey.size) {
+               p = (void *)(t->bt_rkey.data == NULL ?
+                   malloc(sizeof(recno_t)) :
+                   realloc(t->bt_rkey.data, sizeof(recno_t)));
+               if (p == NULL)
+                       return (RET_ERROR);
+               t->bt_rkey.data = p;
+               t->bt_rkey.size = sizeof(recno_t);
+       }
+       memmove(t->bt_rkey.data, &nrec, sizeof(recno_t));
+       key->size = sizeof(recno_t);
+       key->data = t->bt_rkey.data;
+
+dataonly:
+       if (data == NULL)
+               return (RET_SUCCESS);
+
+       /*
+        * We must copy big keys/data to make them contigous.  Otherwise,
+        * leave the page pinned and don't copy unless the user specified
+        * concurrent access.
+        */
+       rl = GETRLEAF(e->page, e->index);
+       if (rl->flags & P_BIGDATA) {
+               if (__ovfl_get(t, rl->bytes,
+                   &data->size, &t->bt_rdata.data, &t->bt_rdata.size))
+                       return (RET_ERROR);
+               data->data = t->bt_rdata.data;
+       } else if (F_ISSET(t, B_DB_LOCK)) {
+               /* Use +1 in case the first record retrieved is 0 length. */
+               if (rl->dsize + 1 > t->bt_rdata.size) {
+                       p = (void *)(t->bt_rdata.data == NULL ?
+                           malloc(rl->dsize + 1) :
+                           realloc(t->bt_rdata.data, rl->dsize + 1));
+                       if (p == NULL)
+                               return (RET_ERROR);
+                       t->bt_rdata.data = p;
+                       t->bt_rdata.size = rl->dsize + 1;
+               }
+               memmove(t->bt_rdata.data, rl->bytes, rl->dsize);
+               data->size = rl->dsize;
+               data->data = t->bt_rdata.data;
+       } else {
+               data->size = rl->dsize;
+               data->data = rl->bytes;
+       }
+       return (RET_SUCCESS);
+}
diff --git a/lib/nbsd_libc/db/recno/recno.h b/lib/nbsd_libc/db/recno/recno.h
new file mode 100644 (file)
index 0000000..7ac0d17
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: recno.h,v 1.6 2003/08/07 16:42:44 agc Exp $    */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ *
+ *     @(#)recno.h     8.1 (Berkeley) 6/4/93
+ */
+
+enum SRCHOP { SDELETE, SINSERT, SEARCH};       /* Rec_search operation. */
+
+#include "../btree/btree.h"
+#include "extern.h"
diff --git a/lib/nbsd_libc/dlfcn/Makefile.inc b/lib/nbsd_libc/dlfcn/Makefile.inc
new file mode 100644 (file)
index 0000000..f9ba7f7
--- /dev/null
@@ -0,0 +1,7 @@
+#       $NetBSD: Makefile.inc,v 1.3 2010/07/06 05:59:52 mrg Exp $
+
+.PATH: ${.CURDIR}/dlfcn
+
+CPPFLAGS+=     -I${NETBSDSRCDIR}/libexec/ld.elf_so
+CPPFLAGS+=     -I${.CURDIR}/dlfcn
+SRCS+=         dlfcn_elf.c
diff --git a/lib/nbsd_libc/dlfcn/dlfcn_elf.c b/lib/nbsd_libc/dlfcn/dlfcn_elf.c
new file mode 100644 (file)
index 0000000..1f9bb8d
--- /dev/null
@@ -0,0 +1,138 @@
+/*     $NetBSD: dlfcn_elf.c,v 1.7 2010/10/16 10:27:07 skrll Exp $      */
+
+/*
+ * Copyright (c) 2000 Takuya SHIOZAKI
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: dlfcn_elf.c,v 1.7 2010/10/16 10:27:07 skrll Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#undef dlopen
+#undef dlclose
+#undef dlsym
+#undef dlerror
+#undef dladdr
+#undef dfinfo
+
+#define        dlopen          ___dlopen
+#define        dlclose         ___dlclose
+#define        dlsym           ___dlsym
+#define        dlerror         ___dlerror
+#define        dladdr          ___dladdr
+#define        dlinfo          ___dlinfo
+#define        dl_iterate_phdr         ___dl_iterate_phdr
+
+#define ELFSIZE ARCH_ELFSIZE
+#include "rtld.h"
+
+#ifdef __weak_alias
+__weak_alias(dlopen,___dlopen)
+__weak_alias(dlclose,___dlclose)
+__weak_alias(dlsym,___dlsym)
+__weak_alias(dlerror,___dlerror)
+__weak_alias(dladdr,___dladdr)
+__weak_alias(dlinfo,___dlinfo)
+__weak_alias(dl_iterate_phdr,___dl_iterate_phdr)
+
+__weak_alias(__dlopen,___dlopen)
+__weak_alias(__dlclose,___dlclose)
+__weak_alias(__dlsym,___dlsym)
+__weak_alias(__dlerror,___dlerror)
+__weak_alias(__dladdr,___dladdr)
+__weak_alias(__dlinfo,___dlinfo)
+__weak_alias(__dl_iterate_phdr,___dl_iterate_phdr)
+#endif
+
+/*
+ * For ELF, the dynamic linker directly resolves references to its
+ * services to functions inside the dynamic linker itself.  These
+ * weak-symbol stubs are necessary so that "ld" won't complain about
+ * undefined symbols.  The stubs are executed only when the program is
+ * linked statically, or when a given service isn't implemented in the
+ * dynamic linker.  They must return an error if called, and they must
+ * be weak symbols so that the dynamic linker can override them.
+ */
+
+static char dlfcn_error[] = "Service unavailable";
+
+/*ARGSUSED*/
+void *
+dlopen(const char *name, int mode)
+{
+
+       return NULL;
+}
+
+/*ARGSUSED*/
+int
+dlclose(void *fd)
+{
+
+       return -1;
+}
+
+/*ARGSUSED*/
+void *
+dlsym(void *handle, const char *name)
+{
+
+       return NULL;
+}
+
+/*ARGSUSED*/
+__aconst char *
+dlerror()
+{
+
+       return dlfcn_error;
+}
+
+/*ARGSUSED*/
+int
+dladdr(const void *addr, Dl_info *dli)
+{
+
+       return 0;
+}
+
+/*ARGSUSED*/
+int
+dlinfo(void *handle, int req, void *v)
+{
+
+       return -1;
+}
+
+/*ARGSUSED*/
+int
+dl_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void *),
+    void *data)
+{
+
+       return 0;
+}
diff --git a/lib/nbsd_libc/gdtoa/Makefile.inc b/lib/nbsd_libc/gdtoa/Makefile.inc
new file mode 100644 (file)
index 0000000..7ca1d6b
--- /dev/null
@@ -0,0 +1,46 @@
+#      $NetBSD: Makefile.inc,v 1.8 2008/02/09 02:37:21 mrg Exp $
+
+# gdtoa sources
+.PATH: ${.CURDIR}/gdtoa
+CPPFLAGS+=-I${.CURDIR}/gdtoa
+
+CPPFLAGS+=-DNO_FENV_H
+
+# machine-dependent directory must provide the following:
+#      arith.h gd_qnan.h
+CPPFLAGS+=-I${ARCHDIR}/gdtoa
+
+# machine-dependent Makefile must define names of modules to use for
+# float conversions:
+#      strtof(): strtof{,_vaxf}.c
+# and for long double conversions on platforms with extended-precision
+# format, if supported (strtod.c will define an alias otherwise):
+#      strtold(): strtold_p{x,xL,Q}.c
+#      helpers:   strtop{x,xL,Q}.c
+.include "${ARCHDIR}/gdtoa/Makefile.inc"
+
+# public interfaces
+SRCS+= strtod.c
+
+# private interfaces interfacing to libc
+SRCS+= dtoa.c ldtoa.c hdtoa.c gdtoa.c
+
+# local locking implementation
+SRCS+= gdtoa_locks.c
+
+# private interfaces
+SRCS+= dmisc.c \
+       gethex.c gmisc.c \
+       hd_init.c hexnan.c \
+       misc.c \
+       smisc.c strtodg.c sum.c \
+       ulp.c
+
+# wrappers
+SRCS+= _strtof.c _strtold.c
+#SRCS+=        _hdtoa.c _ldtoa.c
+
+# XXX no hexadecimal floating-point string conversion for VAX FP yet
+.if ${MACHINE_ARCH} != "vax"
+SRCS+= strtord.c
+.endif
diff --git a/lib/nbsd_libc/gdtoa/README b/lib/nbsd_libc/gdtoa/README
new file mode 100644 (file)
index 0000000..0c8a8f8
--- /dev/null
@@ -0,0 +1,338 @@
+$NetBSD: README,v 1.1.1.1 2006/01/25 15:18:40 kleink Exp $
+
+This directory contains source for a library of binary -> decimal
+and decimal -> binary conversion routines, for single-, double-,
+and extended-precision IEEE binary floating-point arithmetic, and
+other IEEE-like binary floating-point, including "double double",
+as in
+
+       T. J. Dekker, "A Floating-Point Technique for Extending the
+       Available Precision", Numer. Math. 18 (1971), pp. 224-242
+
+and
+
+       "Inside Macintosh: PowerPC Numerics", Addison-Wesley, 1994
+
+The conversion routines use double-precision floating-point arithmetic
+and, where necessary, high precision integer arithmetic.  The routines
+are generalizations of the strtod and dtoa routines described in
+
+       David M. Gay, "Correctly Rounded Binary-Decimal and
+       Decimal-Binary Conversions", Numerical Analysis Manuscript
+       No. 90-10, Bell Labs, Murray Hill, 1990;
+       http://cm.bell-labs.com/cm/cs/what/ampl/REFS/rounding.ps.gz
+
+(based in part on papers by Clinger and Steele & White: see the
+references in the above paper).
+
+The present conversion routines should be able to use any of IEEE binary,
+VAX, or IBM-mainframe double-precision arithmetic internally, but I (dmg)
+have so far only had a chance to test them with IEEE double precision
+arithmetic.
+
+The core conversion routines are strtodg for decimal -> binary conversions
+and gdtoa for binary -> decimal conversions.  These routines operate
+on arrays of unsigned 32-bit integers of type ULong, a signed 32-bit
+exponent of type Long, and arithmetic characteristics described in
+struct FPI; FPI, Long, and ULong are defined in gdtoa.h.  File arith.h
+is supposed to provide #defines that cause gdtoa.h to define its
+types correctly.  File arithchk.c is source for a program that
+generates a suitable arith.h on all systems where I've been able to
+test it.
+
+The core conversion routines are meant to be called by helper routines
+that know details of the particular binary arithmetic of interest and
+convert.  The present directory provides helper routines for 5 variants
+of IEEE binary floating-point arithmetic, each indicated by one or
+two letters:
+
+       f       IEEE single precision
+       d       IEEE double precision
+       x       IEEE extended precision, as on Intel 80x87
+               and software emulations of Motorola 68xxx chips
+               that do not pad the way the 68xxx does, but
+               only store 80 bits
+       xL      IEEE extended precision, as on Motorola 68xxx chips
+       Q       quad precision, as on Sun Sparc chips
+       dd      double double, pairs of IEEE double numbers
+               whose sum is the desired value
+
+For decimal -> binary conversions, there are three families of
+helper routines: one for round-nearest:
+
+       strtof
+       strtod
+       strtodd
+       strtopd
+       strtopf
+       strtopx
+       strtopxL
+       strtopQ
+
+one with rounding direction specified:
+
+       strtorf
+       strtord
+       strtordd
+       strtorx
+       strtorxL
+       strtorQ
+
+and one for computing an interval (at most one bit wide) that contains
+the decimal number:
+
+       strtoIf
+       strtoId
+       strtoIdd
+       strtoIx
+       strtoIxL
+       strtoIQ
+
+The latter call strtoIg, which makes one call on strtodg and adjusts
+the result to provide the desired interval.  On systems where native
+arithmetic can easily make one-ulp adjustments on values in the
+desired floating-point format, it might be more efficient to use the
+native arithmetic.  Routine strtodI is a variant of strtoId that
+illustrates one way to do this for IEEE binary double-precision
+arithmetic -- but whether this is more efficient remains to be seen.
+
+Functions strtod and strtof have "natural" return types, float and
+double -- strtod is specified by the C standard, and strtof appears
+in the stdlib.h of some systems, such as (at least some) Linux systems.
+The other functions write their results to their final argument(s):
+to the final two argument for the strtoI... (interval) functions,
+and to the final argument for the others (strtop... and strtor...).
+Where possible, these arguments have "natural" return types (double*
+or float*), to permit at least some type checking.  In reality, they
+are viewed as arrays of ULong (or, for the "x" functions, UShort)
+values. On systems where long double is the appropriate type, one can
+pass long double* final argument(s) to these routines.  The int value
+that these routines return is the return value from the call they make
+on strtodg; see the enum of possible return values in gdtoa.h.
+
+Source files g_ddfmt.c, misc.c, smisc.c, strtod.c, strtodg.c, and ulp.c
+should use true IEEE double arithmetic (not, e.g., double extended),
+at least for storing (and viewing the bits of) the variables declared
+"double" within them.
+
+One detail indicated in struct FPI is whether the target binary
+arithmetic departs from the IEEE standard by flushing denormalized
+numbers to 0.  On systems that do this, the helper routines for
+conversion to double-double format (when compiled with
+Sudden_Underflow #defined) penalize the bottom of the exponent
+range so that they return a nonzero result only when the least
+significant bit of the less significant member of the pair of
+double values returned can be expressed as a normalized double
+value.  An alternative would be to drop to 53-bit precision near
+the bottom of the exponent range.  To get correct rounding, this
+would (in general) require two calls on strtodg (one specifying
+126-bit arithmetic, then, if necessary, one specifying 53-bit
+arithmetic).
+
+By default, the core routine strtodg and strtod set errno to ERANGE
+if the result overflows to +Infinity or underflows to 0.  Compile
+these routines with NO_ERRNO #defined to inhibit errno assignments.
+
+Routine strtod is based on netlib's "dtoa.c from fp", and
+(f = strtod(s,se)) is more efficient for some conversions than, say,
+strtord(s,se,1,&f).  Parts of strtod require true IEEE double
+arithmetic with the default rounding mode (round-to-nearest) and, on
+systems with IEEE extended-precision registers, double-precision
+(53-bit) rounding precision.  If the machine uses (the equivalent of)
+Intel 80x87 arithmetic, the call
+       _control87(PC_53, MCW_PC);
+does this with many compilers.  Whether this or another call is
+appropriate depends on the compiler; for this to work, it may be
+necessary to #include "float.h" or another system-dependent header
+file.
+
+Source file strtodnrp.c gives a strtod that does not require 53-bit
+rounding precision on systems (such as Intel IA32 systems) that may
+suffer double rounding due to use of extended-precision registers.
+For some conversions this variant of strtod is less efficient than the
+one in strtod.c when the latter is run with 53-bit rounding precision.
+
+The values that the strto* routines return for NaNs are determined by
+gd_qnan.h, which the makefile generates by running the program whose
+source is qnan.c.  Note that the rules for distinguishing signaling
+from quiet NaNs are system-dependent.  For cross-compilation, you need
+to determine arith.h and gd_qnan.h suitably, e.g., using the
+arithmetic of the target machine.
+
+C99's hexadecimal floating-point constants are recognized by the
+strto* routines (but this feature has not yet been heavily tested).
+Compiling with NO_HEX_FP #defined disables this feature.
+
+When compiled with -DINFNAN_CHECK, the strto* routines recognize C99's
+NaN and Infinity syntax.  Moreover, unless No_Hex_NaN is #defined, the
+strto* routines also recognize C99's NaN(...) syntax: they accept
+(case insensitively) strings of the form NaN(x), where x is a string
+of hexadecimal digits and spaces; if there is only one string of
+hexadecimal digits, it is taken for the fraction bits of the resulting
+NaN; if there are two or more strings of hexadecimal digits, each
+string is assigned to the next available sequence of 32-bit words of
+fractions bits (starting with the most significant), right-aligned in
+each sequence.
+
+For binary -> decimal conversions, I've provided just one family
+of helper routines:
+
+       g_ffmt
+       g_dfmt
+       g_ddfmt
+       g_xfmt
+       g_xLfmt
+       g_Qfmt
+
+which do a "%g" style conversion either to a specified number of decimal
+places (if their ndig argument is positive), or to the shortest
+decimal string that rounds to the given binary floating-point value
+(if ndig <= 0).  They write into a buffer supplied as an argument
+and return either a pointer to the end of the string (a null character)
+in the buffer, if the buffer was long enough, or 0.  Other forms of
+conversion are easily done with the help of gdtoa(), such as %e or %f
+style and conversions with direction of rounding specified (so that, if
+desired, the decimal value is either >= or <= the binary value).
+
+For an example of more general conversions based on dtoa(), see
+netlib's "printf.c from ampl/solvers".
+
+For double-double -> decimal, g_ddfmt() assumes IEEE-like arithmetic
+of precision max(126, #bits(input)) bits, where #bits(input) is the
+number of mantissa bits needed to represent the sum of the two double
+values in the input.
+
+The makefile creates a library, gdtoa.a.  To use the helper
+routines, a program only needs to include gdtoa.h.  All the
+source files for gdtoa.a include a more extensive gdtoaimp.h;
+among other things, gdtoaimp.h has #defines that make "internal"
+names end in _D2A.  To make a "system" library, one could modify
+these #defines to make the names start with __.
+
+Various comments about possible #defines appear in gdtoaimp.h,
+but for most purposes, arith.h should set suitable #defines.
+
+Systems with preemptive scheduling of multiple threads require some
+manual intervention.  On such systems, it's necessary to compile
+dmisc.c, dtoa.c gdota.c, and misc.c with MULTIPLE_THREADS #defined,
+and to provide (or suitably #define) two locks, acquired by
+ACQUIRE_DTOA_LOCK(n) and freed by FREE_DTOA_LOCK(n) for n = 0 or 1.
+(The second lock, accessed in pow5mult, ensures lazy evaluation of
+only one copy of high powers of 5; omitting this lock would introduce
+a small probability of wasting memory, but would otherwise be harmless.)
+Routines that call dtoa or gdtoa directly must also invoke freedtoa(s)
+to free the value s returned by dtoa or gdtoa.  It's OK to do so whether
+or not MULTIPLE_THREADS is #defined, and the helper g_*fmt routines
+listed above all do this indirectly (in gfmt_D2A(), which they all call).
+
+By default, there is a private pool of memory of length 2000 bytes
+for intermediate quantities, and MALLOC (see gdtoaimp.h) is called only
+if the private pool does not suffice.   2000 is large enough that MALLOC
+is called only under very unusual circumstances (decimal -> binary
+conversion of very long strings) for conversions to and from double
+precision.  For systems with preemptively scheduled multiple threads
+or for conversions to extended or quad, it may be appropriate to
+#define PRIVATE_MEM nnnn, where nnnn is a suitable value > 2000.
+For extended and quad precisions, -DPRIVATE_MEM=20000 is probably
+plenty even for many digits at the ends of the exponent range.
+Use of the private pool avoids some overhead.
+
+Directory test provides some test routines.  See its README.
+I've also tested this stuff (except double double conversions)
+with Vern Paxson's testbase program: see
+
+       V. Paxson and W. Kahan, "A Program for Testing IEEE Binary-Decimal
+       Conversion", manuscript, May 1991,
+       ftp://ftp.ee.lbl.gov/testbase-report.ps.Z .
+
+(The same ftp directory has source for testbase.)
+
+Some system-dependent additions to CFLAGS in the makefile:
+
+       HU-UX: -Aa -Ae
+       OSF (DEC Unix): -ieee_with_no_inexact
+       SunOS 4.1x: -DKR_headers -DBad_float_h
+
+If you want to put this stuff into a shared library and your
+operating system requires export lists for shared libraries,
+the following would be an appropriate export list:
+
+       dtoa
+       freedtoa
+       g_Qfmt
+       g_ddfmt
+       g_dfmt
+       g_ffmt
+       g_xLfmt
+       g_xfmt
+       gdtoa
+       strtoIQ
+       strtoId
+       strtoIdd
+       strtoIf
+       strtoIx
+       strtoIxL
+       strtod
+       strtodI
+       strtodg
+       strtof
+       strtopQ
+       strtopd
+       strtopdd
+       strtopf
+       strtopx
+       strtopxL
+       strtorQ
+       strtord
+       strtordd
+       strtorf
+       strtorx
+       strtorxL
+
+When time permits, I (dmg) hope to write in more detail about the
+present conversion routines; for now, this README file must suffice.
+Meanwhile, if you wish to write helper functions for other kinds of
+IEEE-like arithmetic, some explanation of struct FPI and the bits
+array may be helpful.  Both gdtoa and strtodg operate on a bits array
+described by FPI *fpi.  The bits array is of type ULong, a 32-bit
+unsigned integer type.  Floating-point numbers have fpi->nbits bits,
+with the least significant 32 bits in bits[0], the next 32 bits in
+bits[1], etc.  These numbers are regarded as integers multiplied by
+2^e (i.e., 2 to the power of the exponent e), where e is the second
+argument (be) to gdtoa and is stored in *exp by strtodg.  The minimum
+and maximum exponent values fpi->emin and fpi->emax for normalized
+floating-point numbers reflect this arrangement.  For example, the
+P754 standard for binary IEEE arithmetic specifies doubles as having
+53 bits, with normalized values of the form 1.xxxxx... times 2^(b-1023),
+with 52 bits (the x's) and the biased exponent b represented explicitly;
+b is an unsigned integer in the range 1 <= b <= 2046 for normalized
+finite doubles, b = 0 for denormals, and b = 2047 for Infinities and NaNs.
+To turn an IEEE double into the representation used by strtodg and gdtoa,
+we multiply 1.xxxx... by 2^52 (to make it an integer) and reduce the
+exponent e = (b-1023) by 52:
+
+       fpi->emin = 1 - 1023 - 52
+       fpi->emax = 1046 - 1023 - 52
+
+In various wrappers for IEEE double, we actually write -53 + 1 rather
+than -52, to emphasize that there are 53 bits including one implicit bit.
+Field fpi->rounding indicates the desired rounding direction, with
+possible values
+       FPI_Round_zero = toward 0,
+       FPI_Round_near = unbiased rounding -- the IEEE default,
+       FPI_Round_up = toward +Infinity, and
+       FPI_Round_down = toward -Infinity
+given in gdtoa.h.
+
+Field fpi->sudden_underflow indicates whether strtodg should return
+denormals or flush them to zero.  Normal floating-point numbers have
+bit fpi->nbits in the bits array on.  Denormals have it off, with
+exponent = fpi->emin.  Strtodg provides distinct return values for normals
+and denormals; see gdtoa.h.
+
+Compiling g__fmt.c, strtod.c, and strtodg.c with -DUSE_LOCALE causes
+the decimal-point character to be taken from the current locale; otherwise
+it is '.'.
+
+Please send comments to        David M. Gay (dmg at acm dot org, with " at "
+changed at "@" and " dot " changed to ".").
diff --git a/lib/nbsd_libc/gdtoa/_strtof.c b/lib/nbsd_libc/gdtoa/_strtof.c
new file mode 100644 (file)
index 0000000..7fe7a62
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: _strtof.c,v 1.2 2009/10/21 01:07:45 snj Exp $  */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _strtof.c,v 1.2 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_strtof, strtof)
+#else
+
+#include <stdlib.h>
+float  _strtof(const char * __restrict, char ** __restrict);
+
+float
+strtof(const char *nptr, char **endptr)
+{
+
+       return _strtof(nptr, endptr);
+}
+#endif
diff --git a/lib/nbsd_libc/gdtoa/_strtold.c b/lib/nbsd_libc/gdtoa/_strtold.c
new file mode 100644 (file)
index 0000000..475f8da
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: _strtold.c,v 1.2 2009/10/21 01:07:45 snj Exp $ */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _strtold.c,v 1.2 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_strtold, strtold)
+#else
+
+#include <stdlib.h>
+long double    _strtold(const char * __restrict, char ** __restrict);
+
+long double
+strtold(const char *nptr, char **endptr)
+{
+
+       return _strtold(nptr, endptr);
+}
+#endif
diff --git a/lib/nbsd_libc/gdtoa/arithchk.c b/lib/nbsd_libc/gdtoa/arithchk.c
new file mode 100644 (file)
index 0000000..e36cdbf
--- /dev/null
@@ -0,0 +1,191 @@
+/* $NetBSD: arithchk.c,v 1.3 2010/01/17 23:06:31 wiz Exp $ */
+
+/****************************************************************
+Copyright (C) 1997, 1998 Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+****************************************************************/
+
+/* Try to deduce arith.h from arithmetic properties. */
+
+#include <stdio.h>
+
+ static int dalign;
+ typedef struct
+Akind {
+       char *name;
+       int   kind;
+       } Akind;
+
+ static Akind
+IEEE_LITTLE_ENDIAN     = { "IEEE_LITTLE_ENDIAN", 1 },
+IEEE_BIG_ENDIAN                = { "IEEE_BIG_ENDIAN", 2 },
+IBM                    = { "IBM", 3 },
+VAX                    = { "VAX", 4 },
+CRAY                   = { "CRAY", 5};
+
+ static Akind *
+Lcheck()
+{
+       union {
+               double d;
+               long L[2];
+               } u;
+       struct {
+               double d;
+               long L;
+               } x[2];
+
+       if (sizeof(x) > 2*(sizeof(double) + sizeof(long)))
+               dalign = 1;
+       u.L[0] = u.L[1] = 0;
+       u.d = 1e13;
+       if (u.L[0] == 1117925532 && u.L[1] == -448790528)
+               return &IEEE_BIG_ENDIAN;
+       if (u.L[1] == 1117925532 && u.L[0] == -448790528)
+               return &IEEE_LITTLE_ENDIAN;
+       if (u.L[0] == -2065213935 && u.L[1] == 10752)
+               return &VAX;
+       if (u.L[0] == 1267827943 && u.L[1] == 704643072)
+               return &IBM;
+       return 0;
+       }
+
+ static Akind *
+icheck()
+{
+       union {
+               double d;
+               int L[2];
+               } u;
+       struct {
+               double d;
+               int L;
+               } x[2];
+
+       if (sizeof(x) > 2*(sizeof(double) + sizeof(int)))
+               dalign = 1;
+       u.L[0] = u.L[1] = 0;
+       u.d = 1e13;
+       if (u.L[0] == 1117925532 && u.L[1] == -448790528)
+               return &IEEE_BIG_ENDIAN;
+       if (u.L[1] == 1117925532 && u.L[0] == -448790528)
+               return &IEEE_LITTLE_ENDIAN;
+       if (u.L[0] == -2065213935 && u.L[1] == 10752)
+               return &VAX;
+       if (u.L[0] == 1267827943 && u.L[1] == 704643072)
+               return &IBM;
+       return 0;
+       }
+
+char *emptyfmt = "";   /* avoid possible warning message with printf("") */
+
+ static Akind *
+ccheck()
+{
+       union {
+               double d;
+               long L;
+               } u;
+       long Cray1;
+
+       /* Cray1 = 4617762693716115456 -- without overflow on non-Crays */
+       Cray1 = printf(emptyfmt) < 0 ? 0 : 4617762;
+       if (printf(emptyfmt, Cray1) >= 0)
+               Cray1 = 1000000*Cray1 + 693716;
+       if (printf(emptyfmt, Cray1) >= 0)
+               Cray1 = 1000000*Cray1 + 115456;
+       u.d = 1e13;
+       if (u.L == Cray1)
+               return &CRAY;
+       return 0;
+       }
+
+ static int
+fzcheck()
+{
+       double a, b;
+       int i;
+
+       a = 1.;
+       b = .1;
+       for(i = 155;; b *= b, i >>= 1) {
+               if (i & 1) {
+                       a *= b;
+                       if (i == 1)
+                               break;
+                       }
+               }
+       b = a * a;
+       return b == 0.;
+       }
+
+ int
+main()
+{
+       Akind *a = 0;
+       int Ldef = 0;
+       FILE *f;
+
+#ifdef WRITE_ARITH_H   /* for Symantec's buggy "make" */
+       f = fopen("arith.h", "w");
+       if (!f) {
+               printf("Cannot open arith.h\n");
+               return 1;
+               }
+#else
+       f = stdout;
+#endif
+
+       if (sizeof(double) == 2*sizeof(long))
+               a = Lcheck();
+       else if (sizeof(double) == 2*sizeof(int)) {
+               Ldef = 1;
+               a = icheck();
+               }
+       else if (sizeof(double) == sizeof(long))
+               a = ccheck();
+       if (a) {
+               fprintf(f, "#define %s\n#define Arith_Kind_ASL %d\n",
+                       a->name, a->kind);
+               if (Ldef)
+                       fprintf(f, "#define Long int\n#define Intcast (int)(long)\n");
+               if (dalign)
+                       fprintf(f, "#define Double_Align\n");
+               if (sizeof(char*) == 8)
+                       fprintf(f, "#define X64_bit_pointers\n");
+#ifndef NO_LONG_LONG
+               if (sizeof(long long) < 8)
+#endif
+                       fprintf(f, "#define NO_LONG_LONG\n");
+               if (a->kind <= 2 && fzcheck())
+                       fprintf(f, "#define Sudden_Underflow\n");
+#ifdef WRITE_ARITH_H
+               fclose(f);
+#endif
+               return 0;
+               }
+       fprintf(f, "/* Unknown arithmetic */\n");
+#ifdef WRITE_ARITH_H
+       fclose(f);
+#endif
+       return 1;
+       }
diff --git a/lib/nbsd_libc/gdtoa/dmisc.c b/lib/nbsd_libc/gdtoa/dmisc.c
new file mode 100644 (file)
index 0000000..121f8bb
--- /dev/null
@@ -0,0 +1,227 @@
+/* $NetBSD: dmisc.c,v 1.4 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#ifndef MULTIPLE_THREADS
+ char *dtoa_result;
+#endif
+
+ char *
+#ifdef KR_headers
+rv_alloc(i) size_t i;
+#else
+rv_alloc(size_t i)
+#endif
+{
+       size_t j;
+       int k, *r;
+
+       j = sizeof(ULong);
+       for(k = 0;
+               sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= i;
+               j <<= 1)
+                       k++;
+       r = (int*)(void*)Balloc(k);
+       if (r == NULL)
+               return NULL;
+       *r = k;
+       return
+#ifndef MULTIPLE_THREADS
+       dtoa_result =
+#endif
+               (char *)(void *)(r+1);
+       }
+
+ char *
+#ifdef KR_headers
+nrv_alloc(s, rve, n) CONST char *s; char **rve; size_t n;
+#else
+nrv_alloc(CONST char *s, char **rve, size_t n)
+#endif
+{
+       char *rv, *t;
+
+       t = rv = rv_alloc(n);
+       if (t == NULL)
+               return NULL;
+       while((*t = *s++) !=0)
+               t++;
+       if (rve)
+               *rve = t;
+       return rv;
+       }
+
+/* freedtoa(s) must be used to free values s returned by dtoa
+ * when MULTIPLE_THREADS is #defined.  It should be used in all cases,
+ * but for consistency with earlier versions of dtoa, it is optional
+ * when MULTIPLE_THREADS is not defined.
+ */
+
+ void
+#ifdef KR_headers
+freedtoa(s) char *s;
+#else
+freedtoa(char *s)
+#endif
+{
+       Bigint *b = (Bigint *)(void *)((int *)(void *)s - 1);
+       b->maxwds = 1 << (b->k = *(int*)(void*)b);
+       Bfree(b);
+#ifndef MULTIPLE_THREADS
+       if (s == dtoa_result)
+               dtoa_result = 0;
+#endif
+       }
+
+ int
+quorem
+#ifdef KR_headers
+       (b, S) Bigint *b, *S;
+#else
+       (Bigint *b, Bigint *S)
+#endif
+{
+       int n;
+       ULong *bx, *bxe, q, *sx, *sxe;
+#ifdef ULLong
+       ULLong borrow, carry, y, ys;
+#else
+       ULong borrow, carry, y, ys;
+#ifdef Pack_32
+       ULong si, z, zs;
+#endif
+#endif
+
+       n = S->wds;
+#ifdef DEBUG
+       /*debug*/ if (b->wds > n)
+       /*debug*/       Bug("oversize b in quorem");
+#endif
+       if (b->wds < n)
+               return 0;
+       sx = S->x;
+       sxe = sx + --n;
+       bx = b->x;
+       bxe = bx + n;
+       q = *bxe / (*sxe + 1);  /* ensure q <= true quotient */
+#ifdef DEBUG
+       /*debug*/ if (q > 9)
+       /*debug*/       Bug("oversized quotient in quorem");
+#endif
+       if (q) {
+               borrow = 0;
+               carry = 0;
+               do {
+#ifdef ULLong
+                       ys = *sx++ * (ULLong)q + carry;
+                       carry = ys >> 32;
+                       /* LINTED conversion */
+                       y = *bx - (ys & 0xffffffffUL) - borrow;
+                       borrow = y >> 32 & 1UL;
+                       /* LINTED conversion */
+                       *bx++ = y & 0xffffffffUL;
+#else
+#ifdef Pack_32
+                       si = *sx++;
+                       ys = (si & 0xffff) * q + carry;
+                       zs = (si >> 16) * q + (ys >> 16);
+                       carry = zs >> 16;
+                       y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
+                       borrow = (y & 0x10000) >> 16;
+                       z = (*bx >> 16) - (zs & 0xffff) - borrow;
+                       borrow = (z & 0x10000) >> 16;
+                       Storeinc(bx, z, y);
+#else
+                       ys = *sx++ * q + carry;
+                       carry = ys >> 16;
+                       y = *bx - (ys & 0xffff) - borrow;
+                       borrow = (y & 0x10000) >> 16;
+                       *bx++ = y & 0xffff;
+#endif
+#endif
+                       }
+                       while(sx <= sxe);
+               if (!*bxe) {
+                       bx = b->x;
+                       while(--bxe > bx && !*bxe)
+                               --n;
+                       b->wds = n;
+                       }
+               }
+       if (cmp(b, S) >= 0) {
+               q++;
+               borrow = 0;
+               carry = 0;
+               bx = b->x;
+               sx = S->x;
+               do {
+#ifdef ULLong
+                       ys = *sx++ + carry;
+                       carry = ys >> 32;
+                       /* LINTED conversion */
+                       y = *bx - (ys & 0xffffffffUL) - borrow;
+                       borrow = y >> 32 & 1UL;
+                       /* LINTED conversion */
+                       *bx++ = y & 0xffffffffUL;
+#else
+#ifdef Pack_32
+                       si = *sx++;
+                       ys = (si & 0xffff) + carry;
+                       zs = (si >> 16) + (ys >> 16);
+                       carry = zs >> 16;
+                       y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
+                       borrow = (y & 0x10000) >> 16;
+                       z = (*bx >> 16) - (zs & 0xffff) - borrow;
+                       borrow = (z & 0x10000) >> 16;
+                       Storeinc(bx, z, y);
+#else
+                       ys = *sx++ + carry;
+                       carry = ys >> 16;
+                       y = *bx - (ys & 0xffff) - borrow;
+                       borrow = (y & 0x10000) >> 16;
+                       *bx++ = y & 0xffff;
+#endif
+#endif
+                       }
+                       while(sx <= sxe);
+               bx = b->x;
+               bxe = bx + n;
+               if (!*bxe) {
+                       while(--bxe > bx && !*bxe)
+                               --n;
+                       b->wds = n;
+                       }
+               }
+       return q;
+       }
diff --git a/lib/nbsd_libc/gdtoa/dtoa.c b/lib/nbsd_libc/gdtoa/dtoa.c
new file mode 100644 (file)
index 0000000..ede9cb1
--- /dev/null
@@ -0,0 +1,815 @@
+/* $NetBSD: dtoa.c,v 1.5 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 1999 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+/* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
+ *
+ * Inspired by "How to Print Floating-Point Numbers Accurately" by
+ * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
+ *
+ * Modifications:
+ *     1. Rather than iterating, we use a simple numeric overestimate
+ *        to determine k = floor(log10(d)).  We scale relevant
+ *        quantities using O(log2(k)) rather than O(k) multiplications.
+ *     2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
+ *        try to generate digits strictly left to right.  Instead, we
+ *        compute with fewer bits and propagate the carry if necessary
+ *        when rounding the final digit up.  This is often faster.
+ *     3. Under the assumption that input will be rounded nearest,
+ *        mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
+ *        That is, we allow equality in stopping tests when the
+ *        round-nearest rule will give the same floating-point value
+ *        as would satisfaction of the stopping test with strict
+ *        inequality.
+ *     4. We remove common factors of powers of 2 from relevant
+ *        quantities.
+ *     5. When converting floating-point integers less than 1e16,
+ *        we use floating-point arithmetic rather than resorting
+ *        to multiple-precision integers.
+ *     6. When asked to produce fewer than 15 digits, we first try
+ *        to get by with floating-point arithmetic; we resort to
+ *        multiple-precision integer arithmetic only if we cannot
+ *        guarantee that the floating-point calculation has given
+ *        the correctly rounded result.  For k requested digits and
+ *        "uniformly" distributed input, the probability is
+ *        something like 10^(k-15) that we must resort to the Long
+ *        calculation.
+ */
+
+#ifdef Honor_FLT_ROUNDS
+#define Rounding rounding
+#undef Check_FLT_ROUNDS
+#define Check_FLT_ROUNDS
+#else
+#define Rounding Flt_Rounds
+#endif
+
+ char *
+dtoa
+#ifdef KR_headers
+       (d, mode, ndigits, decpt, sign, rve)
+       double d; int mode, ndigits, *decpt, *sign; char **rve;
+#else
+       (double d, int mode, int ndigits, int *decpt, int *sign, char **rve)
+#endif
+{
+ /*    Arguments ndigits, decpt, sign are similar to those
+       of ecvt and fcvt; trailing zeros are suppressed from
+       the returned string.  If not null, *rve is set to point
+       to the end of the return value.  If d is +-Infinity or NaN,
+       then *decpt is set to 9999.
+
+       mode:
+               0 ==> shortest string that yields d when read in
+                       and rounded to nearest.
+               1 ==> like 0, but with Steele & White stopping rule;
+                       e.g. with IEEE P754 arithmetic , mode 0 gives
+                       1e23 whereas mode 1 gives 9.999999999999999e22.
+               2 ==> max(1,ndigits) significant digits.  This gives a
+                       return value similar to that of ecvt, except
+                       that trailing zeros are suppressed.
+               3 ==> through ndigits past the decimal point.  This
+                       gives a return value similar to that from fcvt,
+                       except that trailing zeros are suppressed, and
+                       ndigits can be negative.
+               4,5 ==> similar to 2 and 3, respectively, but (in
+                       round-nearest mode) with the tests of mode 0 to
+                       possibly return a shorter string that rounds to d.
+                       With IEEE arithmetic and compilation with
+                       -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
+                       as modes 2 and 3 when FLT_ROUNDS != 1.
+               6-9 ==> Debugging modes similar to mode - 4:  don't try
+                       fast floating-point estimate (if applicable).
+
+               Values of mode other than 0-9 are treated as mode 0.
+
+               Sufficient space is allocated to the return value
+               to hold the suppressed trailing zeros.
+       */
+
+       int bbits, b2, b5, be, dig, i, ieps, ilim0,
+               j, jj1, k, k0, k_check, leftright, m2, m5, s2, s5,
+               spec_case, try_quick;
+       int ilim = 0, ilim1 = 0; /* pacify gcc */
+       Long L;
+#ifndef Sudden_Underflow
+       int denorm;
+       ULong x;
+#endif
+       Bigint *b, *b1, *delta, *mhi, *S;
+       Bigint *mlo = NULL; /* pacify gcc */
+       double d2, ds, eps;
+       char *s, *s0;
+#ifdef Honor_FLT_ROUNDS
+       int rounding;
+#endif
+#ifdef SET_INEXACT
+       int inexact, oldinexact;
+#endif
+
+#ifndef MULTIPLE_THREADS
+       if (dtoa_result) {
+               freedtoa(dtoa_result);
+               dtoa_result = 0;
+               }
+#endif
+
+       if (word0(d) & Sign_bit) {
+               /* set sign for everything, including 0's and NaNs */
+               *sign = 1;
+               word0(d) &= ~Sign_bit;  /* clear sign bit */
+               }
+       else
+               *sign = 0;
+
+#if defined(IEEE_Arith) + defined(VAX)
+#ifdef IEEE_Arith
+       if ((word0(d) & Exp_mask) == Exp_mask)
+#else
+       if (word0(d)  == 0x8000)
+#endif
+               {
+               /* Infinity or NaN */
+               *decpt = 9999;
+#ifdef IEEE_Arith
+               if (!word1(d) && !(word0(d) & 0xfffff))
+                       return nrv_alloc("Infinity", rve, 8);
+#endif
+               return nrv_alloc("NaN", rve, 3);
+               }
+#endif
+#ifdef IBM
+       dval(d) += 0; /* normalize */
+#endif
+       if (!dval(d)) {
+               *decpt = 1;
+               return nrv_alloc("0", rve, 1);
+               }
+
+#ifdef SET_INEXACT
+       try_quick = oldinexact = get_inexact();
+       inexact = 1;
+#endif
+#ifdef Honor_FLT_ROUNDS
+       if ((rounding = Flt_Rounds) >= 2) {
+               if (*sign)
+                       rounding = rounding == 2 ? 0 : 2;
+               else
+                       if (rounding != 2)
+                               rounding = 0;
+               }
+#endif
+
+       b = d2b(dval(d), &be, &bbits);
+       if (b == NULL)
+               return NULL;
+#ifdef Sudden_Underflow
+       i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
+#else
+       if (( i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1)) )!=0) {
+#endif
+               dval(d2) = dval(d);
+               word0(d2) &= Frac_mask1;
+               word0(d2) |= Exp_11;
+#ifdef IBM
+               if (( j = 11 - hi0bits(word0(d2) & Frac_mask) )!=0)
+                       dval(d2) /= 1 << j;
+#endif
+
+               /* log(x)       ~=~ log(1.5) + (x-1.5)/1.5
+                * log10(x)      =  log(x) / log(10)
+                *              ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
+                * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
+                *
+                * This suggests computing an approximation k to log10(d) by
+                *
+                * k = (i - Bias)*0.301029995663981
+                *      + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
+                *
+                * We want k to be too large rather than too small.
+                * The error in the first-order Taylor series approximation
+                * is in our favor, so we just round up the constant enough
+                * to compensate for any error in the multiplication of
+                * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
+                * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
+                * adding 1e-13 to the constant term more than suffices.
+                * Hence we adjust the constant term to 0.1760912590558.
+                * (We could get a more accurate k by invoking log10,
+                *  but this is probably not worthwhile.)
+                */
+
+               i -= Bias;
+#ifdef IBM
+               i <<= 2;
+               i += j;
+#endif
+#ifndef Sudden_Underflow
+               denorm = 0;
+               }
+       else {
+               /* d is denormalized */
+
+               i = bbits + be + (Bias + (P-1) - 1);
+               x = i > 32  ? word0(d) << (64 - i) | word1(d) >> (i - 32)
+                           : word1(d) << (32 - i);
+               dval(d2) = x;
+               word0(d2) -= 31*Exp_msk1; /* adjust exponent */
+               i -= (Bias + (P-1) - 1) + 1;
+               denorm = 1;
+               }
+#endif
+       ds = (dval(d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
+       k = (int)ds;
+       if (ds < 0. && ds != k)
+               k--;    /* want k = floor(ds) */
+       k_check = 1;
+       if (k >= 0 && k <= Ten_pmax) {
+               if (dval(d) < tens[k])
+                       k--;
+               k_check = 0;
+               }
+       j = bbits - i - 1;
+       if (j >= 0) {
+               b2 = 0;
+               s2 = j;
+               }
+       else {
+               b2 = -j;
+               s2 = 0;
+               }
+       if (k >= 0) {
+               b5 = 0;
+               s5 = k;
+               s2 += k;
+               }
+       else {
+               b2 -= k;
+               b5 = -k;
+               s5 = 0;
+               }
+       if (mode < 0 || mode > 9)
+               mode = 0;
+
+#ifndef SET_INEXACT
+#ifdef Check_FLT_ROUNDS
+       try_quick = Rounding == 1;
+#else
+       try_quick = 1;
+#endif
+#endif /*SET_INEXACT*/
+
+       if (mode > 5) {
+               mode -= 4;
+               try_quick = 0;
+               }
+       leftright = 1;
+       switch(mode) {
+               case 0:
+               case 1:
+                       ilim = ilim1 = -1;
+                       i = 18;
+                       ndigits = 0;
+                       break;
+               case 2:
+                       leftright = 0;
+                       /* FALLTHROUGH */
+               case 4:
+                       if (ndigits <= 0)
+                               ndigits = 1;
+                       ilim = ilim1 = i = ndigits;
+                       break;
+               case 3:
+                       leftright = 0;
+                       /* FALLTHROUGH */
+               case 5:
+                       i = ndigits + k + 1;
+                       ilim = i;
+                       ilim1 = i - 1;
+                       if (i <= 0)
+                               i = 1;
+               }
+       s = s0 = rv_alloc((size_t)i);
+       if (s == NULL)
+               return NULL;
+
+#ifdef Honor_FLT_ROUNDS
+       if (mode > 1 && rounding != 1)
+               leftright = 0;
+#endif
+
+       if (ilim >= 0 && ilim <= Quick_max && try_quick) {
+
+               /* Try to get by with floating-point arithmetic. */
+
+               i = 0;
+               dval(d2) = dval(d);
+               k0 = k;
+               ilim0 = ilim;
+               ieps = 2; /* conservative */
+               if (k > 0) {
+                       ds = tens[k&0xf];
+                       j = (unsigned int)k >> 4;
+                       if (j & Bletch) {
+                               /* prevent overflows */
+                               j &= Bletch - 1;
+                               dval(d) /= bigtens[n_bigtens-1];
+                               ieps++;
+                               }
+                       for(; j; j = (unsigned int)j >> 1, i++)
+                               if (j & 1) {
+                                       ieps++;
+                                       ds *= bigtens[i];
+                                       }
+                       dval(d) /= ds;
+                       }
+               else if (( jj1 = -k )!=0) {
+                       dval(d) *= tens[jj1 & 0xf];
+                       for(j = jj1 >> 4; j; j >>= 1, i++)
+                               if (j & 1) {
+                                       ieps++;
+                                       dval(d) *= bigtens[i];
+                                       }
+                       }
+               if (k_check && dval(d) < 1. && ilim > 0) {
+                       if (ilim1 <= 0)
+                               goto fast_failed;
+                       ilim = ilim1;
+                       k--;
+                       dval(d) *= 10.;
+                       ieps++;
+                       }
+               dval(eps) = ieps*dval(d) + 7.;
+               word0(eps) -= (P-1)*Exp_msk1;
+               if (ilim == 0) {
+                       S = mhi = 0;
+                       dval(d) -= 5.;
+                       if (dval(d) > dval(eps))
+                               goto one_digit;
+                       if (dval(d) < -dval(eps))
+                               goto no_digits;
+                       goto fast_failed;
+                       }
+#ifndef No_leftright
+               if (leftright) {
+                       /* Use Steele & White method of only
+                        * generating digits needed.
+                        */
+                       dval(eps) = 0.5/tens[ilim-1] - dval(eps);
+                       for(i = 0;;) {
+                               L = dval(d);
+                               dval(d) -= L;
+                               *s++ = '0' + (int)L;
+                               if (dval(d) < dval(eps))
+                                       goto ret1;
+                               if (1. - dval(d) < dval(eps))
+                                       goto bump_up;
+                               if (++i >= ilim)
+                                       break;
+                               dval(eps) *= 10.;
+                               dval(d) *= 10.;
+                               }
+                       }
+               else {
+#endif
+                       /* Generate ilim digits, then fix them up. */
+                       dval(eps) *= tens[ilim-1];
+                       for(i = 1;; i++, dval(d) *= 10.) {
+                               L = (Long)(dval(d));
+                               if (!(dval(d) -= L))
+                                       ilim = i;
+                               *s++ = '0' + (int)L;
+                               if (i == ilim) {
+                                       if (dval(d) > 0.5 + dval(eps))
+                                               goto bump_up;
+                                       else if (dval(d) < 0.5 - dval(eps)) {
+                                               while(*--s == '0');
+                                               s++;
+                                               goto ret1;
+                                               }
+                                       break;
+                                       }
+                               }
+#ifndef No_leftright
+                       }
+#endif
+ fast_failed:
+               s = s0;
+               dval(d) = dval(d2);
+               k = k0;
+               ilim = ilim0;
+               }
+
+       /* Do we have a "small" integer? */
+
+       if (be >= 0 && k <= Int_max) {
+               /* Yes. */
+               ds = tens[k];
+               if (ndigits < 0 && ilim <= 0) {
+                       S = mhi = 0;
+                       if (ilim < 0 || dval(d) <= 5*ds)
+                               goto no_digits;
+                       goto one_digit;
+                       }
+               for(i = 1;; i++, dval(d) *= 10.) {
+                       L = (Long)(dval(d) / ds);
+                       dval(d) -= L*ds;
+#ifdef Check_FLT_ROUNDS
+                       /* If FLT_ROUNDS == 2, L will usually be high by 1 */
+                       if (dval(d) < 0) {
+                               L--;
+                               dval(d) += ds;
+                               }
+#endif
+                       *s++ = '0' + (int)L;
+                       if (!dval(d)) {
+#ifdef SET_INEXACT
+                               inexact = 0;
+#endif
+                               break;
+                               }
+                       if (i == ilim) {
+#ifdef Honor_FLT_ROUNDS
+                               if (mode > 1)
+                               switch(rounding) {
+                                 case 0: goto ret1;
+                                 case 2: goto bump_up;
+                                 }
+#endif
+                               dval(d) += dval(d);
+                               if (dval(d) > ds || (dval(d) == ds && L & 1)) {
+ bump_up:
+                                       while(*--s == '9')
+                                               if (s == s0) {
+                                                       k++;
+                                                       *s = '0';
+                                                       break;
+                                                       }
+                                       ++*s++;
+                                       }
+                               break;
+                               }
+                       }
+               goto ret1;
+               }
+
+       m2 = b2;
+       m5 = b5;
+       mhi = mlo = 0;
+       if (leftright) {
+               i =
+#ifndef Sudden_Underflow
+                       denorm ? be + (Bias + (P-1) - 1 + 1) :
+#endif
+#ifdef IBM
+                       1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
+#else
+                       1 + P - bbits;
+#endif
+               b2 += i;
+               s2 += i;
+               mhi = i2b(1);
+               if (mhi == NULL)
+                       return NULL;
+               }
+       if (m2 > 0 && s2 > 0) {
+               i = m2 < s2 ? m2 : s2;
+               b2 -= i;
+               m2 -= i;
+               s2 -= i;
+               }
+       if (b5 > 0) {
+               if (leftright) {
+                       if (m5 > 0) {
+                               mhi = pow5mult(mhi, m5);
+                               if (mhi == NULL)
+                                       return NULL;
+                               b1 = mult(mhi, b);
+                               if (b1 == NULL)
+                                       return NULL;
+                               Bfree(b);
+                               b = b1;
+                               }
+                       if (( j = b5 - m5 )!=0)
+                               b = pow5mult(b, j);
+                               if (b == NULL)
+                                       return NULL;
+                       }
+               else
+                       b = pow5mult(b, b5);
+                       if (b == NULL)
+                               return NULL;
+               }
+       S = i2b(1);
+       if (S == NULL)
+               return NULL;
+       if (s5 > 0) {
+               S = pow5mult(S, s5);
+               if (S == NULL)
+                       return NULL;
+       }
+
+       /* Check for special case that d is a normalized power of 2. */
+
+       spec_case = 0;
+       if ((mode < 2 || leftright)
+#ifdef Honor_FLT_ROUNDS
+                       && rounding == 1
+#endif
+                               ) {
+               if (!word1(d) && !(word0(d) & Bndry_mask)
+#ifndef Sudden_Underflow
+                && word0(d) & (Exp_mask & ~Exp_msk1)
+#endif
+                               ) {
+                       /* The special case */
+                       b2 += Log2P;
+                       s2 += Log2P;
+                       spec_case = 1;
+                       }
+               }
+
+       /* Arrange for convenient computation of quotients:
+        * shift left if necessary so divisor has 4 leading 0 bits.
+        *
+        * Perhaps we should just compute leading 28 bits of S once
+        * and for all and pass them and a shift to quorem, so it
+        * can do shifts and ors to compute the numerator for q.
+        */
+#ifdef Pack_32
+       if (( i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f )!=0)
+               i = 32 - i;
+#else
+       if (( i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf )!=0)
+               i = 16 - i;
+#endif
+       if (i > 4) {
+               i -= 4;
+               b2 += i;
+               m2 += i;
+               s2 += i;
+               }
+       else if (i < 4) {
+               i += 28;
+               b2 += i;
+               m2 += i;
+               s2 += i;
+               }
+       if (b2 > 0) {
+               b = lshift(b, b2);
+               if (b == NULL)
+                       return NULL;
+       }
+       if (s2 > 0) {
+               S = lshift(S, s2);
+               if (S == NULL)
+                       return NULL;
+       }
+       if (k_check) {
+               if (cmp(b,S) < 0) {
+                       k--;
+                       b = multadd(b, 10, 0);  /* we botched the k estimate */
+                       if (b == NULL)
+                               return NULL;
+                       if (leftright) {
+                               mhi = multadd(mhi, 10, 0);
+                               if (mhi == NULL)
+                                       return NULL;
+                       }
+                       ilim = ilim1;
+                       }
+               }
+       if (ilim <= 0 && (mode == 3 || mode == 5)) {
+               if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
+                       /* no digits, fcvt style */
+ no_digits:
+                       k = -1 - ndigits;
+                       goto ret;
+                       }
+ one_digit:
+               *s++ = '1';
+               k++;
+               goto ret;
+               }
+       if (leftright) {
+               if (m2 > 0) {
+                       mhi = lshift(mhi, m2);
+                       if (mhi == NULL)
+                               return NULL;
+               }
+
+               /* Compute mlo -- check for special case
+                * that d is a normalized power of 2.
+                */
+
+               mlo = mhi;
+               if (spec_case) {
+                       mhi = Balloc(mhi->k);
+                       if (mhi == NULL)
+                               return NULL;
+                       Bcopy(mhi, mlo);
+                       mhi = lshift(mhi, Log2P);
+                       if (mhi == NULL)
+                               return NULL;
+                       }
+
+               for(i = 1;;i++) {
+                       dig = quorem(b,S) + '0';
+                       /* Do we yet have the shortest decimal string
+                        * that will round to d?
+                        */
+                       j = cmp(b, mlo);
+                       delta = diff(S, mhi);
+                       if (delta == NULL)
+                               return NULL;
+                       jj1 = delta->sign ? 1 : cmp(b, delta);
+                       Bfree(delta);
+#ifndef ROUND_BIASED
+                       if (jj1 == 0 && mode != 1 && !(word1(d) & 1)
+#ifdef Honor_FLT_ROUNDS
+                               && rounding >= 1
+#endif
+                                                                  ) {
+                               if (dig == '9')
+                                       goto round_9_up;
+                               if (j > 0)
+                                       dig++;
+#ifdef SET_INEXACT
+                               else if (!b->x[0] && b->wds <= 1)
+                                       inexact = 0;
+#endif
+                               *s++ = dig;
+                               goto ret;
+                               }
+#endif
+                       if (j < 0 || (j == 0 && mode != 1
+#ifndef ROUND_BIASED
+                                                       && !(word1(d) & 1)
+#endif
+                                       )) {
+                               if (!b->x[0] && b->wds <= 1) {
+#ifdef SET_INEXACT
+                                       inexact = 0;
+#endif
+                                       goto accept_dig;
+                                       }
+#ifdef Honor_FLT_ROUNDS
+                               if (mode > 1)
+                                switch(rounding) {
+                                 case 0: goto accept_dig;
+                                 case 2: goto keep_dig;
+                                 }
+#endif /*Honor_FLT_ROUNDS*/
+                               if (jj1 > 0) {
+                                       b = lshift(b, 1);
+                                       if (b == NULL)
+                                               return NULL;
+                                       jj1 = cmp(b, S);
+                                       if ((jj1 > 0 || (jj1 == 0 && dig & 1))
+                                       && dig++ == '9')
+                                               goto round_9_up;
+                                       }
+ accept_dig:
+                               *s++ = dig;
+                               goto ret;
+                               }
+                       if (jj1 > 0) {
+#ifdef Honor_FLT_ROUNDS
+                               if (!rounding)
+                                       goto accept_dig;
+#endif
+                               if (dig == '9') { /* possible if i == 1 */
+ round_9_up:
+                                       *s++ = '9';
+                                       goto roundoff;
+                                       }
+                               *s++ = dig + 1;
+                               goto ret;
+                               }
+#ifdef Honor_FLT_ROUNDS
+ keep_dig:
+#endif
+                       *s++ = dig;
+                       if (i == ilim)
+                               break;
+                       b = multadd(b, 10, 0);
+                       if (b == NULL)
+                               return NULL;
+                       if (mlo == mhi) {
+                               mlo = mhi = multadd(mhi, 10, 0);
+                               if (mlo == NULL)
+                                       return NULL;
+                               }
+                       else {
+                               mlo = multadd(mlo, 10, 0);
+                               if (mlo == NULL)
+                                       return NULL;
+                               mhi = multadd(mhi, 10, 0);
+                               if (mhi == NULL)
+                                       return NULL;
+                               }
+                       }
+               }
+       else
+               for(i = 1;; i++) {
+                       *s++ = dig = quorem(b,S) + '0';
+                       if (!b->x[0] && b->wds <= 1) {
+#ifdef SET_INEXACT
+                               inexact = 0;
+#endif
+                               goto ret;
+                               }
+                       if (i >= ilim)
+                               break;
+                       b = multadd(b, 10, 0);
+                       if (b == NULL)
+                               return NULL;
+                       }
+
+       /* Round off last digit */
+
+#ifdef Honor_FLT_ROUNDS
+       switch(rounding) {
+         case 0: goto trimzeros;
+         case 2: goto roundoff;
+         }
+#endif
+       b = lshift(b, 1);
+       j = cmp(b, S);
+       if (j > 0 || (j == 0 && dig & 1)) {
+ roundoff:
+               while(*--s == '9')
+                       if (s == s0) {
+                               k++;
+                               *s++ = '1';
+                               goto ret;
+                               }
+               ++*s++;
+               }
+       else {
+#ifdef Honor_FLT_ROUNDS
+ trimzeros:
+#endif
+               while(*--s == '0');
+               s++;
+               }
+ ret:
+       Bfree(S);
+       if (mhi) {
+               if (mlo && mlo != mhi)
+                       Bfree(mlo);
+               Bfree(mhi);
+               }
+ ret1:
+#ifdef SET_INEXACT
+       if (inexact) {
+               if (!oldinexact) {
+                       word0(d) = Exp_1 + (70 << Exp_shift);
+                       word1(d) = 0;
+                       dval(d) += 1.;
+                       }
+               }
+       else if (!oldinexact)
+               clear_inexact();
+#endif
+       Bfree(b);
+       if (s == s0) {                  /* don't return empty string */
+               *s++ = '0';
+               k = 0;
+       }
+       *s = 0;
+       *decpt = k + 1;
+       if (rve)
+               *rve = s;
+       return s0;
+       }
diff --git a/lib/nbsd_libc/gdtoa/g_Qfmt.c b/lib/nbsd_libc/gdtoa/g_Qfmt.c
new file mode 100644 (file)
index 0000000..83a2041
--- /dev/null
@@ -0,0 +1,118 @@
+/* $NetBSD: g_Qfmt.c,v 1.3 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#undef _0
+#undef _1
+
+/* one or the other of IEEE_BIG_ENDIAN or IEEE_LITTLE_ENDIAN should be #defined */
+
+#ifdef IEEE_BIG_ENDIAN
+#define _0 0
+#define _1 1
+#define _2 2
+#define _3 3
+#endif
+#ifdef IEEE_LITTLE_ENDIAN
+#define _0 3
+#define _1 2
+#define _2 1
+#define _3 0
+#endif
+
+ char*
+#ifdef KR_headers
+g_Qfmt(buf, V, ndig, bufsize) char *buf; char *V; int ndig; unsigned bufsize;
+#else
+g_Qfmt(char *buf, void *V, int ndig, unsigned bufsize)
+#endif
+{
+       static FPI fpi = { 113, 1-16383-113+1, 32766 - 16383 - 113 + 1, 1, 0 };
+       char *b, *s, *se;
+       ULong bits[4], *L, sign;
+       int decpt, ex, i, mode;
+
+       if (ndig < 0)
+               ndig = 0;
+       if (bufsize < ndig + 10)
+               return 0;
+
+       L = (ULong*)V;
+       sign = L[_0] & 0x80000000L;
+       bits[3] = L[_0] & 0xffff;
+       bits[2] = L[_1];
+       bits[1] = L[_2];
+       bits[0] = L[_3];
+       b = buf;
+       if ( (ex = (L[_0] & 0x7fff0000L) >> 16) !=0) {
+               if (ex == 0x7fff) {
+                       /* Infinity or NaN */
+                       if (bits[0] | bits[1] | bits[2] | bits[3])
+                               b = strcp(b, "NaN");
+                       else {
+                               b = buf;
+                               if (sign)
+                                       *b++ = '-';
+                               b = strcp(b, "Infinity");
+                               }
+                       return b;
+                       }
+               i = STRTOG_Normal;
+               bits[3] |= 0x10000;
+               }
+       else if (bits[0] | bits[1] | bits[2] | bits[3]) {
+               i = STRTOG_Denormal;
+               ex = 1;
+               }
+       else {
+#ifndef IGNORE_ZERO_SIGN
+               if (sign)
+                       *b++ = '-';
+#endif
+               *b++ = '0';
+               *b = 0;
+               return b;
+               }
+       ex -= 0x3fff + 112;
+       mode = 2;
+       if (ndig <= 0) {
+               if (bufsize < 48)
+                       return 0;
+               mode = 0;
+               }
+       s = gdtoa(&fpi, ex, bits, &i, mode, ndig, &decpt, &se);
+       if (s == NULL)
+               return NULL;
+       return g__fmt(buf, s, se, decpt, sign);
+       }
diff --git a/lib/nbsd_libc/gdtoa/g__fmt.c b/lib/nbsd_libc/gdtoa/g__fmt.c
new file mode 100644 (file)
index 0000000..de85452
--- /dev/null
@@ -0,0 +1,101 @@
+/* $NetBSD: g__fmt.c,v 1.1.1.1 2006/01/25 15:18:41 kleink Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#ifdef USE_LOCALE
+#include "locale.h"
+#endif
+
+ char *
+#ifdef KR_headers
+g__fmt(b, s, se, decpt, sign) char *b; char *s; char *se; int decpt; ULong sign;
+#else
+g__fmt(char *b, char *s, char *se, int decpt, ULong sign)
+#endif
+{
+       int i, j, k;
+       char *s0 = s;
+#ifdef USE_LOCALE
+       char decimalpoint = *localeconv()->decimal_point;
+#else
+#define decimalpoint '.'
+#endif
+       if (sign)
+               *b++ = '-';
+       if (decpt <= -4 || decpt > se - s + 5) {
+               *b++ = *s++;
+               if (*s) {
+                       *b++ = decimalpoint;
+                       while((*b = *s++) !=0)
+                               b++;
+                       }
+               *b++ = 'e';
+               /* sprintf(b, "%+.2d", decpt - 1); */
+               if (--decpt < 0) {
+                       *b++ = '-';
+                       decpt = -decpt;
+                       }
+               else
+                       *b++ = '+';
+               for(j = 2, k = 10; 10*k <= decpt; j++, k *= 10){}
+               for(;;) {
+                       i = decpt / k;
+                       *b++ = i + '0';
+                       if (--j <= 0)
+                               break;
+                       decpt -= i*k;
+                       decpt *= 10;
+                       }
+               *b = 0;
+               }
+       else if (decpt <= 0) {
+               *b++ = decimalpoint;
+               for(; decpt < 0; decpt++)
+                       *b++ = '0';
+               while((*b = *s++) !=0)
+                       b++;
+               }
+       else {
+               while((*b = *s++) !=0) {
+                       b++;
+                       if (--decpt == 0 && *s)
+                               *b++ = decimalpoint;
+                       }
+               for(; decpt > 0; decpt--)
+                       *b++ = '0';
+               *b = 0;
+               }
+       freedtoa(s0);
+       return b;
+       }
diff --git a/lib/nbsd_libc/gdtoa/g_ddfmt.c b/lib/nbsd_libc/gdtoa/g_ddfmt.c
new file mode 100644 (file)
index 0000000..9b0725d
--- /dev/null
@@ -0,0 +1,173 @@
+/* $NetBSD: g_ddfmt.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg@acm.org). */
+
+#include "gdtoaimp.h"
+#include <string.h>
+
+ char *
+#ifdef KR_headers
+g_ddfmt(buf, dd, ndig, bufsize) char *buf; double *dd; int ndig; unsigned bufsize;
+#else
+g_ddfmt(char *buf, double *dd, int ndig, unsigned bufsize)
+#endif
+{
+       FPI fpi;
+       char *b, *s, *se;
+       ULong *L, bits0[4], *bits, *zx;
+       int bx, by, decpt, ex, ey, i, j, mode;
+       Bigint *x, *y, *z;
+       double ddx[2];
+
+       if (bufsize < 10 || bufsize < ndig + 8)
+               return 0;
+
+       L = (ULong*)dd;
+       if ((L[_0] & 0x7ff00000L) == 0x7ff00000L) {
+               /* Infinity or NaN */
+               if (L[_0] & 0xfffff || L[_1]) {
+ nanret:
+                       return strcp(buf, "NaN");
+                       }
+               if ((L[2+_0] & 0x7ff00000) == 0x7ff00000) {
+                       if (L[2+_0] & 0xfffff || L[2+_1])
+                               goto nanret;
+                       if ((L[_0] ^ L[2+_0]) & 0x80000000L)
+                               goto nanret;    /* Infinity - Infinity */
+                       }
+ infret:
+               b = buf;
+               if (L[_0] & 0x80000000L)
+                       *b++ = '-';
+               return strcp(b, "Infinity");
+               }
+       if ((L[2+_0] & 0x7ff00000) == 0x7ff00000) {
+               L += 2;
+               if (L[_0] & 0xfffff || L[_1])
+                       goto nanret;
+               goto infret;
+               }
+       if (dd[0] + dd[1] == 0.) {
+               b = buf;
+#ifndef IGNORE_ZERO_SIGN
+               if (L[_0] & L[2+_0] & 0x80000000L)
+                       *b++ = '-';
+#endif
+               *b++ = '0';
+               *b = 0;
+               return b;
+               }
+       if ((L[_0] & 0x7ff00000L) < (L[2+_0] & 0x7ff00000L)) {
+               ddx[1] = dd[0];
+               ddx[0] = dd[1];
+               dd = ddx;
+               L = (ULong*)dd;
+               }
+       z = d2b(dd[0], &ex, &bx);
+       if (z == NULL)
+               return NULL;
+       if (dd[1] == 0.)
+               goto no_y;
+       x = z;
+       y = d2b(dd[1], &ey, &by);
+       if (y == NULL)
+               return NULL;
+       if ( (i = ex - ey) !=0) {
+               if (i > 0) {
+                       x = lshift(x, i);
+                       if (x == NULL)
+                               return NULL;
+                       ex = ey;
+                       }
+               else {
+                       y = lshift(y, -i);
+                       if (y == NULL)
+                               return NULL;
+                       }
+               }
+       if ((L[_0] ^ L[2+_0]) & 0x80000000L) {
+               z = diff(x, y);
+               if (z == NULL)
+                       return NULL;
+               if (L[_0] & 0x80000000L)
+                       z->sign = 1 - z->sign;
+               }
+       else {
+               z = sum(x, y);
+               if (z == NULL)
+                       return NULL;
+               if (L[_0] & 0x80000000L)
+                       z->sign = 1;
+               }
+       Bfree(x);
+       Bfree(y);
+ no_y:
+       bits = zx = z->x;
+       for(i = 0; !*zx; zx++)
+               i += 32;
+       i += lo0bits(zx);
+       if (i) {
+               rshift(z, i);
+               ex += i;
+               }
+       fpi.nbits = z->wds * 32 - hi0bits(z->x[j = z->wds-1]);
+       if (fpi.nbits < 106) {
+               fpi.nbits = 106;
+               if (j < 3) {
+                       for(i = 0; i <= j; i++)
+                               bits0[i] = bits[i];
+                       while(i < 4)
+                               bits0[i++] = 0;
+                       bits = bits0;
+                       }
+               }
+       mode = 2;
+       if (ndig <= 0) {
+               if (bufsize < (int)(fpi.nbits * .301029995664) + 10) {
+                       Bfree(z);
+                       return 0;
+                       }
+               mode = 0;
+               }
+       fpi.emin = 1-1023-53+1;
+       fpi.emax = 2046-1023-106+1;
+       fpi.rounding = FPI_Round_near;
+       fpi.sudden_underflow = 0;
+       i = STRTOG_Normal;
+       s = gdtoa(&fpi, ex, bits, &i, mode, ndig, &decpt, &se);
+       if (s == NULL)
+               return NULL;
+       b = g__fmt(buf, s, se, decpt, z->sign);
+       if (b == NULL)
+               return NULL;
+       Bfree(z);
+       return b;
+       }
diff --git a/lib/nbsd_libc/gdtoa/g_dfmt.c b/lib/nbsd_libc/gdtoa/g_dfmt.c
new file mode 100644 (file)
index 0000000..d8379f0
--- /dev/null
@@ -0,0 +1,93 @@
+/* $NetBSD: g_dfmt.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ char*
+#ifdef KR_headers
+g_dfmt(buf, d, ndig, bufsize) char *buf; double *d; int ndig; unsigned bufsize;
+#else
+g_dfmt(char *buf, double *d, int ndig, unsigned bufsize)
+#endif
+{
+       static FPI fpi = { 53, 1-1023-53+1, 2046-1023-53+1, 1, 0 };
+       char *b, *s, *se;
+       ULong bits[2], *L, sign;
+       int decpt, ex, i, mode;
+
+       if (ndig < 0)
+               ndig = 0;
+       if (bufsize < ndig + 10)
+               return 0;
+
+       L = (ULong*)d;
+       sign = L[_0] & 0x80000000L;
+       if ((L[_0] & 0x7ff00000) == 0x7ff00000) {
+               /* Infinity or NaN */
+               if (L[_0] & 0xfffff || L[_1]) {
+                       return strcp(buf, "NaN");
+                       }
+               b = buf;
+               if (sign)
+                       *b++ = '-';
+               return strcp(b, "Infinity");
+               }
+       if (L[_1] == 0 && (L[_0] ^ sign) == 0 /*d == 0.*/) {
+               b = buf;
+#ifndef IGNORE_ZERO_SIGN
+               if (L[_0] & 0x80000000L)
+                       *b++ = '-';
+#endif
+               *b++ = '0';
+               *b = 0;
+               return b;
+               }
+       bits[0] = L[_1];
+       bits[1] = L[_0] & 0xfffff;
+       if ( (ex = (L[_0] >> 20) & 0x7ff) !=0)
+               bits[1] |= 0x100000;
+       else
+               ex = 1;
+       ex -= 0x3ff + 52;
+       mode = 2;
+       if (ndig <= 0) {
+               if (bufsize < 25)
+                       return 0;
+               mode = 0;
+               }
+       i = STRTOG_Normal;
+       s = gdtoa(&fpi, ex, bits, &i, mode, ndig, &decpt, &se);
+       if (s == NULL)
+               return NULL;
+       return g__fmt(buf, s, se, decpt, sign);
+       }
diff --git a/lib/nbsd_libc/gdtoa/g_ffmt.c b/lib/nbsd_libc/gdtoa/g_ffmt.c
new file mode 100644 (file)
index 0000000..ca7f646
--- /dev/null
@@ -0,0 +1,92 @@
+/* $NetBSD: g_ffmt.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ char*
+#ifdef KR_headers
+g_ffmt(buf, f, ndig, bufsize) char *buf; float *f; int ndig; unsigned bufsize;
+#else
+g_ffmt(char *buf, float *f, int ndig, unsigned bufsize)
+#endif
+{
+       static FPI fpi = { 24, 1-127-24+1,  254-127-24+1, 1, 0 };
+       char *b, *s, *se;
+       ULong bits[1], *L, sign;
+       int decpt, ex, i, mode;
+
+       if (ndig < 0)
+               ndig = 0;
+       if (bufsize < ndig + 10)
+               return 0;
+
+       L = (ULong*)f;
+       sign = L[0] & 0x80000000L;
+       if ((L[0] & 0x7f800000) == 0x7f800000) {
+               /* Infinity or NaN */
+               if (L[0] & 0x7fffff) {
+                       return strcp(buf, "NaN");
+                       }
+               b = buf;
+               if (sign)
+                       *b++ = '-';
+               return strcp(b, "Infinity");
+               }
+       if (*f == 0.) {
+               b = buf;
+#ifndef IGNORE_ZERO_SIGN
+               if (L[0] & 0x80000000L)
+                       *b++ = '-';
+#endif
+               *b++ = '0';
+               *b = 0;
+               return b;
+               }
+       bits[0] = L[0] & 0x7fffff;
+       if ( (ex = (L[0] >> 23) & 0xff) !=0)
+               bits[0] |= 0x800000;
+       else
+               ex = 1;
+       ex -= 0x7f + 23;
+       mode = 2;
+       if (ndig <= 0) {
+               if (bufsize < 16)
+                       return 0;
+               mode = 0;
+               }
+       i = STRTOG_Normal;
+       s = gdtoa(&fpi, ex, bits, &i, mode, ndig, &decpt, &se);
+       if (s == NULL)
+               return NULL;
+       return g__fmt(buf, s, se, decpt, sign);
+       }
diff --git a/lib/nbsd_libc/gdtoa/g_xLfmt.c b/lib/nbsd_libc/gdtoa/g_xLfmt.c
new file mode 100644 (file)
index 0000000..a1126ff
--- /dev/null
@@ -0,0 +1,112 @@
+/* $NetBSD: g_xLfmt.c,v 1.3 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#undef _0
+#undef _1
+
+/* one or the other of IEEE_BIG_ENDIAN or IEEE_LITTLE_ENDIAN should be #defined */
+
+#ifdef IEEE_BIG_ENDIAN
+#define _0 0
+#define _1 1
+#define _2 2
+#endif
+#ifdef IEEE_LITTLE_ENDIAN
+#define _0 2
+#define _1 1
+#define _2 0
+#endif
+
+ char*
+#ifdef KR_headers
+g_xLfmt(buf, V, ndig, bufsize) char *buf; char *V; int ndig; unsigned bufsize;
+#else
+g_xLfmt(char *buf, void *V, int ndig, unsigned bufsize)
+#endif
+{
+       static FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, 0 };
+       char *b, *s, *se;
+       ULong bits[2], *L, sign;
+       int decpt, ex, i, mode;
+
+       if (ndig < 0)
+               ndig = 0;
+       if (bufsize < ndig + 10)
+               return 0;
+
+       L = (ULong*)V;
+       sign = L[_0] & 0x80000000L;
+       bits[1] = L[_1];
+       bits[0] = L[_2];
+       if ( (ex = (L[_0] >> 16) & 0x7fff) !=0) {
+               if (ex == 0x7fff) {
+                       /* Infinity or NaN */
+                       if (bits[0] | bits[1])
+                               b = strcp(buf, "NaN");
+                       else {
+                               b = buf;
+                               if (sign)
+                                       *b++ = '-';
+                               b = strcp(b, "Infinity");
+                               }
+                       return b;
+                       }
+               i = STRTOG_Normal;
+               }
+       else if (bits[0] | bits[1]) {
+               i = STRTOG_Denormal;
+               }
+       else {
+               b = buf;
+#ifndef IGNORE_ZERO_SIGN
+               if (sign)
+                       *b++ = '-';
+#endif
+               *b++ = '0';
+               *b = 0;
+               return b;
+               }
+       ex -= 0x3fff + 63;
+       mode = 2;
+       if (ndig <= 0) {
+               if (bufsize < 32)
+                       return 0;
+               mode = 0;
+               }
+       s = gdtoa(&fpi, ex, bits, &i, mode, ndig, &decpt, &se);
+       if (s == NULL)
+               return NULL;
+       return g__fmt(buf, s, se, decpt, sign);
+       }
diff --git a/lib/nbsd_libc/gdtoa/g_xfmt.c b/lib/nbsd_libc/gdtoa/g_xfmt.c
new file mode 100644 (file)
index 0000000..18b434e
--- /dev/null
@@ -0,0 +1,118 @@
+/* $NetBSD: g_xfmt.c,v 1.3 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#undef _0
+#undef _1
+
+/* one or the other of IEEE_BIG_ENDIAN or IEEE_LITTLE_ENDIAN should be #defined */
+
+#ifdef IEEE_BIG_ENDIAN
+#define _0 0
+#define _1 1
+#define _2 2
+#define _3 3
+#define _4 4
+#endif
+#ifdef IEEE_LITTLE_ENDIAN
+#define _0 4
+#define _1 3
+#define _2 2
+#define _3 1
+#define _4 0
+#endif
+
+ char*
+#ifdef KR_headers
+g_xfmt(buf, V, ndig, bufsize) char *buf; char *V; int ndig; unsigned bufsize;
+#else
+g_xfmt(char *buf, void *V, int ndig, unsigned bufsize)
+#endif
+{
+       static FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, 0 };
+       char *b, *s, *se;
+       ULong bits[2], sign;
+       UShort *L;
+       int decpt, ex, i, mode;
+
+       if (ndig < 0)
+               ndig = 0;
+       if (bufsize < ndig + 10)
+               return 0;
+
+       L = (UShort *)V;
+       sign = L[_0] & 0x8000;
+       bits[1] = (L[_1] << 16) | L[_2];
+       bits[0] = (L[_3] << 16) | L[_4];
+       if ( (ex = L[_0] & 0x7fff) !=0) {
+               if (ex == 0x7fff) {
+                       /* Infinity or NaN */
+                       if (bits[0] | bits[1])
+                               b = strcp(buf, "NaN");
+                       else {
+                               b = buf;
+                               if (sign)
+                                       *b++ = '-';
+                               b = strcp(b, "Infinity");
+                               }
+                       return b;
+                       }
+               i = STRTOG_Normal;
+               }
+       else if (bits[0] | bits[1]) {
+               i = STRTOG_Denormal;
+               ex = 1;
+               }
+       else {
+               b = buf;
+#ifndef IGNORE_ZERO_SIGN
+               if (sign)
+                       *b++ = '-';
+#endif
+               *b++ = '0';
+               *b = 0;
+               return b;
+               }
+       ex -= 0x3fff + 63;
+       mode = 2;
+       if (ndig <= 0) {
+               if (bufsize < 32)
+                       return 0;
+               mode = 0;
+               }
+       s = gdtoa(&fpi, ex, bits, &i, mode, ndig, &decpt, &se);
+       if (s == NULL)
+               return NULL;
+       return g__fmt(buf, s, se, decpt, sign);
+       }
diff --git a/lib/nbsd_libc/gdtoa/gdtoa.c b/lib/nbsd_libc/gdtoa/gdtoa.c
new file mode 100644 (file)
index 0000000..95f7f4f
--- /dev/null
@@ -0,0 +1,816 @@
+/* $NetBSD: gdtoa.c,v 1.4 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 1999 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ static Bigint *
+#ifdef KR_headers
+bitstob(bits, nbits, bbits) ULong *bits; int nbits; int *bbits;
+#else
+bitstob(ULong *bits, int nbits, int *bbits)
+#endif
+{
+       int i, k;
+       Bigint *b;
+       ULong *be, *x, *x0;
+
+       i = ULbits;
+       k = 0;
+       while(i < nbits) {
+               i <<= 1;
+               k++;
+               }
+#ifndef Pack_32
+       if (!k)
+               k = 1;
+#endif
+       b = Balloc(k);
+       if (b == NULL)
+               return NULL;
+       be = bits + (((unsigned int)nbits - 1) >> kshift);
+       x = x0 = b->x;
+       do {
+               *x++ = *bits & ALL_ON;
+#ifdef Pack_16
+               *x++ = (*bits >> 16) & ALL_ON;
+#endif
+               } while(++bits <= be);
+       i = x - x0;
+       while(!x0[--i])
+               if (!i) {
+                       b->wds = 0;
+                       *bbits = 0;
+                       goto ret;
+                       }
+       b->wds = i + 1;
+       *bbits = i*ULbits + 32 - hi0bits(b->x[i]);
+ ret:
+       return b;
+       }
+
+/* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
+ *
+ * Inspired by "How to Print Floating-Point Numbers Accurately" by
+ * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
+ *
+ * Modifications:
+ *     1. Rather than iterating, we use a simple numeric overestimate
+ *        to determine k = floor(log10(d)).  We scale relevant
+ *        quantities using O(log2(k)) rather than O(k) multiplications.
+ *     2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
+ *        try to generate digits strictly left to right.  Instead, we
+ *        compute with fewer bits and propagate the carry if necessary
+ *        when rounding the final digit up.  This is often faster.
+ *     3. Under the assumption that input will be rounded nearest,
+ *        mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
+ *        That is, we allow equality in stopping tests when the
+ *        round-nearest rule will give the same floating-point value
+ *        as would satisfaction of the stopping test with strict
+ *        inequality.
+ *     4. We remove common factors of powers of 2 from relevant
+ *        quantities.
+ *     5. When converting floating-point integers less than 1e16,
+ *        we use floating-point arithmetic rather than resorting
+ *        to multiple-precision integers.
+ *     6. When asked to produce fewer than 15 digits, we first try
+ *        to get by with floating-point arithmetic; we resort to
+ *        multiple-precision integer arithmetic only if we cannot
+ *        guarantee that the floating-point calculation has given
+ *        the correctly rounded result.  For k requested digits and
+ *        "uniformly" distributed input, the probability is
+ *        something like 10^(k-15) that we must resort to the Long
+ *        calculation.
+ */
+
+ char *
+gdtoa
+#ifdef KR_headers
+       (fpi, be, bits, kindp, mode, ndigits, decpt, rve)
+       FPI *fpi; int be; ULong *bits;
+       int *kindp, mode, ndigits, *decpt; char **rve;
+#else
+       (FPI *fpi, int be, ULong *bits, int *kindp, int mode, int ndigits, int *decpt, char **rve)
+#endif
+{
+ /*    Arguments ndigits and decpt are similar to the second and third
+       arguments of ecvt and fcvt; trailing zeros are suppressed from
+       the returned string.  If not null, *rve is set to point
+       to the end of the return value.  If d is +-Infinity or NaN,
+       then *decpt is set to 9999.
+
+       mode:
+               0 ==> shortest string that yields d when read in
+                       and rounded to nearest.
+               1 ==> like 0, but with Steele & White stopping rule;
+                       e.g. with IEEE P754 arithmetic , mode 0 gives
+                       1e23 whereas mode 1 gives 9.999999999999999e22.
+               2 ==> max(1,ndigits) significant digits.  This gives a
+                       return value similar to that of ecvt, except
+                       that trailing zeros are suppressed.
+               3 ==> through ndigits past the decimal point.  This
+                       gives a return value similar to that from fcvt,
+                       except that trailing zeros are suppressed, and
+                       ndigits can be negative.
+               4-9 should give the same return values as 2-3, i.e.,
+                       4 <= mode <= 9 ==> same return as mode
+                       2 + (mode & 1).  These modes are mainly for
+                       debugging; often they run slower but sometimes
+                       faster than modes 2-3.
+               4,5,8,9 ==> left-to-right digit generation.
+               6-9 ==> don't try fast floating-point estimate
+                       (if applicable).
+
+               Values of mode other than 0-9 are treated as mode 0.
+
+               Sufficient space is allocated to the return value
+               to hold the suppressed trailing zeros.
+       */
+
+       int bbits, b2, b5, be0, dig, i, ieps, ilim = 0, ilim0, ilim1 = 0, inex;
+       int j, jj1, k, k0, k_check, kind, leftright, m2, m5, nbits;
+       int rdir, s2, s5, spec_case, try_quick;
+       Long L;
+       Bigint *b, *b1, *delta, *mlo, *mhi, *mhi1, *S;
+       double d, d2, ds, eps;
+       char *s, *s0;
+
+#ifndef MULTIPLE_THREADS
+       if (dtoa_result) {
+               freedtoa(dtoa_result);
+               dtoa_result = 0;
+               }
+#endif
+       inex = 0;
+       if (*kindp & STRTOG_NoMemory)
+               return NULL;
+       kind = *kindp &= ~STRTOG_Inexact;
+       switch(kind & STRTOG_Retmask) {
+         case STRTOG_Zero:
+               goto ret_zero;
+         case STRTOG_Normal:
+         case STRTOG_Denormal:
+               break;
+         case STRTOG_Infinite:
+               *decpt = -32768;
+               return nrv_alloc("Infinity", rve, 8);
+         case STRTOG_NaN:
+               *decpt = -32768;
+               return nrv_alloc("NaN", rve, 3);
+         default:
+               return 0;
+         }
+       b = bitstob(bits, nbits = fpi->nbits, &bbits);
+       if (b == NULL)
+               return NULL;
+       be0 = be;
+       if ( (i = trailz(b)) !=0) {
+               rshift(b, i);
+               be += i;
+               bbits -= i;
+               }
+       if (!b->wds) {
+               Bfree(b);
+ ret_zero:
+               *decpt = 1;
+               return nrv_alloc("0", rve, 1);
+               }
+
+       dval(d) = b2d(b, &i);
+       i = be + bbits - 1;
+       word0(d) &= Frac_mask1;
+       word0(d) |= Exp_11;
+#ifdef IBM
+       if ( (j = 11 - hi0bits(word0(d) & Frac_mask)) !=0)
+               dval(d) /= 1 << j;
+#endif
+
+       /* log(x)       ~=~ log(1.5) + (x-1.5)/1.5
+        * log10(x)      =  log(x) / log(10)
+        *              ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
+        * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
+        *
+        * This suggests computing an approximation k to log10(d) by
+        *
+        * k = (i - Bias)*0.301029995663981
+        *      + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
+        *
+        * We want k to be too large rather than too small.
+        * The error in the first-order Taylor series approximation
+        * is in our favor, so we just round up the constant enough
+        * to compensate for any error in the multiplication of
+        * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
+        * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
+        * adding 1e-13 to the constant term more than suffices.
+        * Hence we adjust the constant term to 0.1760912590558.
+        * (We could get a more accurate k by invoking log10,
+        *  but this is probably not worthwhile.)
+        */
+#ifdef IBM
+       i <<= 2;
+       i += j;
+#endif
+       ds = (dval(d)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
+
+       /* correct assumption about exponent range */
+       if ((j = i) < 0)
+               j = -j;
+       if ((j -= 1077) > 0)
+               ds += j * 7e-17;
+
+       k = (int)ds;
+       if (ds < 0. && ds != k)
+               k--;    /* want k = floor(ds) */
+       k_check = 1;
+#ifdef IBM
+       j = be + bbits - 1;
+       if ( (jj1 = j & 3) !=0)
+               dval(d) *= 1 << jj1;
+       word0(d) += j << Exp_shift - 2 & Exp_mask;
+#else
+       word0(d) += (be + bbits - 1) << Exp_shift;
+#endif
+       if (k >= 0 && k <= Ten_pmax) {
+               if (dval(d) < tens[k])
+                       k--;
+               k_check = 0;
+               }
+       j = bbits - i - 1;
+       if (j >= 0) {
+               b2 = 0;
+               s2 = j;
+               }
+       else {
+               b2 = -j;
+               s2 = 0;
+               }
+       if (k >= 0) {
+               b5 = 0;
+               s5 = k;
+               s2 += k;
+               }
+       else {
+               b2 -= k;
+               b5 = -k;
+               s5 = 0;
+               }
+       if (mode < 0 || mode > 9)
+               mode = 0;
+       try_quick = 1;
+       if (mode > 5) {
+               mode -= 4;
+               try_quick = 0;
+               }
+       leftright = 1;
+       switch(mode) {
+               case 0:
+               case 1:
+                       ilim = ilim1 = -1;
+                       i = (int)(nbits * .30103) + 3;
+                       ndigits = 0;
+                       break;
+               case 2:
+                       leftright = 0;
+                       /*FALLTHROUGH*/
+               case 4:
+                       if (ndigits <= 0)
+                               ndigits = 1;
+                       ilim = ilim1 = i = ndigits;
+                       break;
+               case 3:
+                       leftright = 0;
+                       /*FALLTHROUGH*/
+               case 5:
+                       i = ndigits + k + 1;
+                       ilim = i;
+                       ilim1 = i - 1;
+                       if (i <= 0)
+                               i = 1;
+               }
+       s = s0 = rv_alloc((size_t)i);
+       if (s == NULL)
+               return NULL;
+
+       if ( (rdir = fpi->rounding - 1) !=0) {
+               if (rdir < 0)
+                       rdir = 2;
+               if (kind & STRTOG_Neg)
+                       rdir = 3 - rdir;
+               }
+
+       /* Now rdir = 0 ==> round near, 1 ==> round up, 2 ==> round down. */
+
+       if (ilim >= 0 && ilim <= Quick_max && try_quick && !rdir
+#ifndef IMPRECISE_INEXACT
+               && k == 0
+#endif
+                                                               ) {
+
+               /* Try to get by with floating-point arithmetic. */
+
+               i = 0;
+               d2 = dval(d);
+#ifdef IBM
+               if ( (j = 11 - hi0bits(word0(d) & Frac_mask)) !=0)
+                       dval(d) /= 1 << j;
+#endif
+               k0 = k;
+               ilim0 = ilim;
+               ieps = 2; /* conservative */
+               if (k > 0) {
+                       ds = tens[k&0xf];
+                       j = (unsigned int)k >> 4;
+                       if (j & Bletch) {
+                               /* prevent overflows */
+                               j &= Bletch - 1;
+                               dval(d) /= bigtens[n_bigtens-1];
+                               ieps++;
+                               }
+                       for(; j; j /= 2, i++)
+                               if (j & 1) {
+                                       ieps++;
+                                       ds *= bigtens[i];
+                                       }
+                       }
+               else  {
+                       ds = 1.;
+                       if ( (jj1 = -k) !=0) {
+                               dval(d) *= tens[jj1 & 0xf];
+                               for(j = jj1 >> 4; j; j >>= 1, i++)
+                                       if (j & 1) {
+                                               ieps++;
+                                               dval(d) *= bigtens[i];
+                                               }
+                               }
+                       }
+               if (k_check && dval(d) < 1. && ilim > 0) {
+                       if (ilim1 <= 0)
+                               goto fast_failed;
+                       ilim = ilim1;
+                       k--;
+                       dval(d) *= 10.;
+                       ieps++;
+                       }
+               dval(eps) = ieps*dval(d) + 7.;
+               word0(eps) -= (P-1)*Exp_msk1;
+               if (ilim == 0) {
+                       S = mhi = 0;
+                       dval(d) -= 5.;
+                       if (dval(d) > dval(eps))
+                               goto one_digit;
+                       if (dval(d) < -dval(eps))
+                               goto no_digits;
+                       goto fast_failed;
+                       }
+#ifndef No_leftright
+               if (leftright) {
+                       /* Use Steele & White method of only
+                        * generating digits needed.
+                        */
+                       dval(eps) = ds*0.5/tens[ilim-1] - dval(eps);
+                       for(i = 0;;) {
+                               L = (Long)(dval(d)/ds);
+                               dval(d) -= L*ds;
+                               *s++ = '0' + (int)L;
+                               if (dval(d) < dval(eps)) {
+                                       if (dval(d))
+                                               inex = STRTOG_Inexlo;
+                                       goto ret1;
+                                       }
+                               if (ds - dval(d) < dval(eps))
+                                       goto bump_up;
+                               if (++i >= ilim)
+                                       break;
+                               dval(eps) *= 10.;
+                               dval(d) *= 10.;
+                               }
+                       }
+               else {
+#endif
+                       /* Generate ilim digits, then fix them up. */
+                       dval(eps) *= tens[ilim-1];
+                       for(i = 1;; i++, dval(d) *= 10.) {
+                               if ( (L = (Long)(dval(d)/ds)) !=0)
+                                       dval(d) -= L*ds;
+                               *s++ = '0' + (int)L;
+                               if (i == ilim) {
+                                       ds *= 0.5;
+                                       if (dval(d) > ds + dval(eps))
+                                               goto bump_up;
+                                       else if (dval(d) < ds - dval(eps)) {
+                                               while(*--s == '0'){}
+                                               s++;
+                                               if (dval(d))
+                                                       inex = STRTOG_Inexlo;
+                                               goto ret1;
+                                               }
+                                       break;
+                                       }
+                               }
+#ifndef No_leftright
+                       }
+#endif
+ fast_failed:
+               s = s0;
+               dval(d) = d2;
+               k = k0;
+               ilim = ilim0;
+               }
+
+       /* Do we have a "small" integer? */
+
+       if (be >= 0 && k <= Int_max) {
+               /* Yes. */
+               ds = tens[k];
+               if (ndigits < 0 && ilim <= 0) {
+                       S = mhi = 0;
+                       if (ilim < 0 || dval(d) <= 5*ds)
+                               goto no_digits;
+                       goto one_digit;
+                       }
+               for(i = 1;; i++, dval(d) *= 10.) {
+                       L = dval(d) / ds;
+                       dval(d) -= L*ds;
+#ifdef Check_FLT_ROUNDS
+                       /* If FLT_ROUNDS == 2, L will usually be high by 1 */
+                       if (dval(d) < 0) {
+                               L--;
+                               dval(d) += ds;
+                               }
+#endif
+                       *s++ = '0' + (int)L;
+                       if (dval(d) == 0.)
+                               break;
+                       if (i == ilim) {
+                               if (rdir) {
+                                       if (rdir == 1)
+                                               goto bump_up;
+                                       inex = STRTOG_Inexlo;
+                                       goto ret1;
+                                       }
+                               dval(d) += dval(d);
+                               if (dval(d) > ds || (dval(d) == ds && L & 1)) {
+ bump_up:
+                                       inex = STRTOG_Inexhi;
+                                       while(*--s == '9')
+                                               if (s == s0) {
+                                                       k++;
+                                                       *s = '0';
+                                                       break;
+                                                       }
+                                       ++*s++;
+                                       }
+                               else
+                                       inex = STRTOG_Inexlo;
+                               break;
+                               }
+                       }
+               goto ret1;
+               }
+
+       m2 = b2;
+       m5 = b5;
+       mhi = mlo = 0;
+       if (leftright) {
+               if (mode < 2) {
+                       i = nbits - bbits;
+                       if (be - i++ < fpi->emin)
+                               /* denormal */
+                               i = be - fpi->emin + 1;
+                       }
+               else {
+                       j = ilim - 1;
+                       if (m5 >= j)
+                               m5 -= j;
+                       else {
+                               s5 += j -= m5;
+                               b5 += j;
+                               m5 = 0;
+                               }
+                       if ((i = ilim) < 0) {
+                               m2 -= i;
+                               i = 0;
+                               }
+                       }
+               b2 += i;
+               s2 += i;
+               mhi = i2b(1);
+               }
+       if (m2 > 0 && s2 > 0) {
+               i = m2 < s2 ? m2 : s2;
+               b2 -= i;
+               m2 -= i;
+               s2 -= i;
+               }
+       if (b5 > 0) {
+               if (leftright) {
+                       if (m5 > 0) {
+                               mhi = pow5mult(mhi, m5);
+                               if (mhi == NULL)
+                                       return NULL;
+                               b1 = mult(mhi, b);
+                               if (b1 == NULL)
+                                       return NULL;
+                               Bfree(b);
+                               b = b1;
+                               }
+                       if ( (j = b5 - m5) !=0) {
+                               b = pow5mult(b, j);
+                               if (b == NULL)
+                                       return NULL;
+                               }
+                       }
+               else {
+                       b = pow5mult(b, b5);
+                       if (b == NULL)
+                               return NULL;
+                       }
+               }
+       S = i2b(1);
+       if (S == NULL)
+               return NULL;
+       if (s5 > 0) {
+               S = pow5mult(S, s5);
+               if (S == NULL)
+                       return NULL;
+               }
+
+       /* Check for special case that d is a normalized power of 2. */
+
+       spec_case = 0;
+       if (mode < 2) {
+               if (bbits == 1 && be0 > fpi->emin + 1) {
+                       /* The special case */
+                       b2++;
+                       s2++;
+                       spec_case = 1;
+                       }
+               }
+
+       /* Arrange for convenient computation of quotients:
+        * shift left if necessary so divisor has 4 leading 0 bits.
+        *
+        * Perhaps we should just compute leading 28 bits of S once
+        * and for all and pass them and a shift to quorem, so it
+        * can do shifts and ors to compute the numerator for q.
+        */
+#ifdef Pack_32
+       if ( (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f) !=0)
+               i = 32 - i;
+#else
+       if ( (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf) !=0)
+               i = 16 - i;
+#endif
+       if (i > 4) {
+               i -= 4;
+               b2 += i;
+               m2 += i;
+               s2 += i;
+               }
+       else if (i < 4) {
+               i += 28;
+               b2 += i;
+               m2 += i;
+               s2 += i;
+               }
+       if (b2 > 0)
+               b = lshift(b, b2);
+       if (s2 > 0)
+               S = lshift(S, s2);
+       if (k_check) {
+               if (cmp(b,S) < 0) {
+                       k--;
+                       b = multadd(b, 10, 0);  /* we botched the k estimate */
+                       if (b == NULL)
+                               return NULL;
+                       if (leftright) {
+                               mhi = multadd(mhi, 10, 0);
+                               if (mhi == NULL)
+                                       return NULL;
+                               }
+                       ilim = ilim1;
+                       }
+               }
+       if (ilim <= 0 && mode > 2) {
+               if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
+                       /* no digits, fcvt style */
+ no_digits:
+                       k = -1 - ndigits;
+                       inex = STRTOG_Inexlo;
+                       goto ret;
+                       }
+ one_digit:
+               inex = STRTOG_Inexhi;
+               *s++ = '1';
+               k++;
+               goto ret;
+               }
+       if (leftright) {
+               if (m2 > 0) {
+                       mhi = lshift(mhi, m2);
+                       if (mhi == NULL)
+                               return NULL;
+                       }
+
+               /* Compute mlo -- check for special case
+                * that d is a normalized power of 2.
+                */
+
+               mlo = mhi;
+               if (spec_case) {
+                       mhi = Balloc(mhi->k);
+                       if (mhi == NULL)
+                               return NULL;
+                       Bcopy(mhi, mlo);
+                       mhi = lshift(mhi, 1);
+                       if (mhi == NULL)
+                               return NULL;
+                       }
+
+               for(i = 1;;i++) {
+                       dig = quorem(b,S) + '0';
+                       /* Do we yet have the shortest decimal string
+                        * that will round to d?
+                        */
+                       j = cmp(b, mlo);
+                       delta = diff(S, mhi);
+                       if (delta == NULL)
+                               return NULL;
+                       jj1 = delta->sign ? 1 : cmp(b, delta);
+                       Bfree(delta);
+#ifndef ROUND_BIASED
+                       if (jj1 == 0 && !mode && !(bits[0] & 1) && !rdir) {
+                               if (dig == '9')
+                                       goto round_9_up;
+                               if (j <= 0) {
+                                       if (b->wds > 1 || b->x[0])
+                                               inex = STRTOG_Inexlo;
+                                       }
+                               else {
+                                       dig++;
+                                       inex = STRTOG_Inexhi;
+                                       }
+                               *s++ = dig;
+                               goto ret;
+                               }
+#endif
+                       if (j < 0 || (j == 0 && !mode
+#ifndef ROUND_BIASED
+                                                       && !(bits[0] & 1)
+#endif
+                                       )) {
+                               if (rdir && (b->wds > 1 || b->x[0])) {
+                                       if (rdir == 2) {
+                                               inex = STRTOG_Inexlo;
+                                               goto accept;
+                                               }
+                                       while (cmp(S,mhi) > 0) {
+                                               *s++ = dig;
+                                               mhi1 = multadd(mhi, 10, 0);
+                                               if (mhi1 == NULL)
+                                                       return NULL;
+                                               if (mlo == mhi)
+                                                       mlo = mhi1;
+                                               mhi = mhi1;
+                                               b = multadd(b, 10, 0);
+                                               if (b == NULL)
+                                                       return NULL;
+                                               dig = quorem(b,S) + '0';
+                                               }
+                                       if (dig++ == '9')
+                                               goto round_9_up;
+                                       inex = STRTOG_Inexhi;
+                                       goto accept;
+                                       }
+                               if (jj1 > 0) {
+                                       b = lshift(b, 1);
+                                       if (b == NULL)
+                                               return NULL;
+                                       jj1 = cmp(b, S);
+                                       if ((jj1 > 0 || (jj1 == 0 && dig & 1))
+                                       && dig++ == '9')
+                                               goto round_9_up;
+                                       inex = STRTOG_Inexhi;
+                                       }
+                               if (b->wds > 1 || b->x[0])
+                                       inex = STRTOG_Inexlo;
+ accept:
+                               *s++ = dig;
+                               goto ret;
+                               }
+                       if (jj1 > 0 && rdir != 2) {
+                               if (dig == '9') { /* possible if i == 1 */
+ round_9_up:
+                                       *s++ = '9';
+                                       inex = STRTOG_Inexhi;
+                                       goto roundoff;
+                                       }
+                               inex = STRTOG_Inexhi;
+                               *s++ = dig + 1;
+                               goto ret;
+                               }
+                       *s++ = dig;
+                       if (i == ilim)
+                               break;
+                       b = multadd(b, 10, 0);
+                       if (b == NULL)
+                               return NULL;
+                       if (mlo == mhi) {
+                               mlo = mhi = multadd(mhi, 10, 0);
+                               if (mlo == NULL)
+                                       return NULL;
+                               }
+                       else {
+                               mlo = multadd(mlo, 10, 0);
+                               if (mlo == NULL)
+                                       return NULL;
+                               mhi = multadd(mhi, 10, 0);
+                               if (mhi == NULL)
+                                       return NULL;
+                               }
+                       }
+               }
+       else
+               for(i = 1;; i++) {
+                       *s++ = dig = quorem(b,S) + '0';
+                       if (i >= ilim)
+                               break;
+                       b = multadd(b, 10, 0);
+                       if (b == NULL)
+                               return NULL;
+                       }
+
+       /* Round off last digit */
+
+       if (rdir) {
+               if (rdir == 2 || (b->wds <= 1 && !b->x[0]))
+                       goto chopzeros;
+               goto roundoff;
+               }
+       b = lshift(b, 1);
+       if (b == NULL)
+               return NULL;
+       j = cmp(b, S);
+       if (j > 0 || (j == 0 && dig & 1)) {
+ roundoff:
+               inex = STRTOG_Inexhi;
+               while(*--s == '9')
+                       if (s == s0) {
+                               k++;
+                               *s++ = '1';
+                               goto ret;
+                               }
+               ++*s++;
+               }
+       else {
+ chopzeros:
+               if (b->wds > 1 || b->x[0])
+                       inex = STRTOG_Inexlo;
+               while(*--s == '0'){}
+               s++;
+               }
+ ret:
+       Bfree(S);
+       if (mhi) {
+               if (mlo && mlo != mhi)
+                       Bfree(mlo);
+               Bfree(mhi);
+               }
+ ret1:
+       Bfree(b);
+       *s = 0;
+       *decpt = k + 1;
+       if (rve)
+               *rve = s;
+       *kindp |= inex;
+       return s0;
+       }
diff --git a/lib/nbsd_libc/gdtoa/gdtoa.h b/lib/nbsd_libc/gdtoa/gdtoa.h
new file mode 100644 (file)
index 0000000..6384025
--- /dev/null
@@ -0,0 +1,175 @@
+/* $NetBSD: gdtoa.h,v 1.8 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#ifndef GDTOA_H_INCLUDED
+#define GDTOA_H_INCLUDED
+
+#include "arith.h"
+
+#ifndef Long
+#define Long int32_t
+#endif
+#ifndef ULong
+#define ULong uint32_t
+#endif
+#ifndef UShort
+#define UShort uint16_t
+#endif
+
+#ifndef ANSI
+#ifdef KR_headers
+#define ANSI(x) ()
+#define Void /*nothing*/
+#else
+#define ANSI(x) x
+#define Void void
+#endif
+#endif /* ANSI */
+
+#ifndef CONST
+#ifdef KR_headers
+#define CONST /* blank */
+#else
+#define CONST const
+#endif
+#endif /* CONST */
+
+ enum {        /* return values from strtodg */
+       STRTOG_Zero     = 0,
+       STRTOG_Normal   = 1,
+       STRTOG_Denormal = 2,
+       STRTOG_Infinite = 3,
+       STRTOG_NaN      = 4,
+       STRTOG_NaNbits  = 5,
+       STRTOG_NoNumber = 6,
+       STRTOG_Retmask  = 7,
+
+       /* The following may be or-ed into one of the above values. */
+
+       STRTOG_Neg      = 0x08,
+       STRTOG_Inexlo   = 0x10,
+       STRTOG_Inexhi   = 0x20,
+       STRTOG_Inexact  = 0x30,
+       STRTOG_Underflow= 0x40,
+       STRTOG_Overflow = 0x80,
+       STRTOG_NoMemory = 0x100
+       };
+
+ typedef struct
+FPI {
+       int nbits;
+       int emin;
+       int emax;
+       int rounding;
+       int sudden_underflow;
+       } FPI;
+
+enum { /* FPI.rounding values: same as FLT_ROUNDS */
+       FPI_Round_zero = 0,
+       FPI_Round_near = 1,
+       FPI_Round_up = 2,
+       FPI_Round_down = 3
+       };
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define        dtoa            __dtoa
+#define        gdtoa           __gdtoa
+#define        ldtoa           __ldtoa
+#define        hldtoa          __hldtoa
+#define        hdtoa           __hdtoa
+#define        freedtoa        __freedtoa
+#define        strtodg         __strtodg_D2A
+#define        strtopQ         __strtopQ_D2A
+#define        strtopx         __strtopx_D2A
+#define        strtopxL        __strtopxL_D2A
+#define        strtord         __strtord_D2A
+
+extern char* dtoa  ANSI((double d, int mode, int ndigits, int *decpt,
+                       int *sign, char **rve));
+extern char* hdtoa ANSI((double d, const char *xdigs, int ndigits, int *decpt,
+                       int *sign, char **rve));
+extern char* ldtoa ANSI((long double *ld, int mode, int ndigits, int *decpt,
+                       int *sign, char **rve));
+extern char* hldtoa ANSI((long double e, const char *xdigs, int ndigits,
+                       int *decpt, int *sign, char **rve));
+
+extern char* gdtoa ANSI((FPI *fpi, int be, ULong *bits, int *kindp,
+                       int mode, int ndigits, int *decpt, char **rve));
+extern void freedtoa ANSI((char*));
+extern float  strtof ANSI((CONST char *, char **));
+extern double strtod ANSI((CONST char *, char **));
+extern int strtodg ANSI((CONST char*, char**, CONST FPI*, Long*, ULong*));
+
+extern char*   g_ddfmt  ANSI((char*, double*, int, unsigned));
+extern char*   g_dfmt   ANSI((char*, double*, int, unsigned));
+extern char*   g_ffmt   ANSI((char*, float*,  int, unsigned));
+extern char*   g_Qfmt   ANSI((char*, void*,   int, unsigned));
+extern char*   g_xfmt   ANSI((char*, void*,   int, unsigned));
+extern char*   g_xLfmt  ANSI((char*, void*,   int, unsigned));
+
+extern int     strtoId  ANSI((CONST char*, char**, double*, double*));
+extern int     strtoIdd ANSI((CONST char*, char**, double*, double*));
+extern int     strtoIf  ANSI((CONST char*, char**, float*, float*));
+extern int     strtoIQ  ANSI((CONST char*, char**, void*, void*));
+extern int     strtoIx  ANSI((CONST char*, char**, void*, void*));
+extern int     strtoIxL ANSI((CONST char*, char**, void*, void*));
+extern int     strtord  ANSI((CONST char*, char**, int, double*));
+extern int     strtordd ANSI((CONST char*, char**, int, double*));
+extern int     strtorf  ANSI((CONST char*, char**, int, float*));
+extern int     strtorQ  ANSI((CONST char*, char**, int, void*));
+extern int     strtorx  ANSI((CONST char*, char**, int, void*));
+extern int     strtorxL ANSI((CONST char*, char**, int, void*));
+#if 1
+extern int     strtodI  ANSI((CONST char*, char**, double*));
+extern int     strtopd  ANSI((CONST char*, char**, double*));
+extern int     strtopdd ANSI((CONST char*, char**, double*));
+extern int     strtopf  ANSI((CONST char*, char**, float*));
+extern int     strtopQ  ANSI((CONST char*, char**, void*));
+extern int     strtopx  ANSI((CONST char*, char**, void*));
+extern int     strtopxL ANSI((CONST char*, char**, void*));
+#else
+#define strtopd(s,se,x) strtord(s,se,1,x)
+#define strtopdd(s,se,x) strtordd(s,se,1,x)
+#define strtopf(s,se,x) strtorf(s,se,1,x)
+#define strtopQ(s,se,x) strtorQ(s,se,1,x)
+#define strtopx(s,se,x) strtorx(s,se,1,x)
+#define strtopxL(s,se,x) strtorxL(s,se,1,x)
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* GDTOA_H_INCLUDED */
diff --git a/lib/nbsd_libc/gdtoa/gdtoa_locks.c b/lib/nbsd_libc/gdtoa/gdtoa_locks.c
new file mode 100644 (file)
index 0000000..81f521c
--- /dev/null
@@ -0,0 +1,10 @@
+/* $NetBSD: gdtoa_locks.c,v 1.1 2006/01/25 15:36:13 kleink Exp $ */
+
+/*
+ * Written by Klaus Klein <kleink@NetBSD.org>, November 16, 2005.
+ * Public domain.
+ */
+
+#include "gdtoaimp.h"
+
+mutex_t __gdtoa_locks[2] = { MUTEX_INITIALIZER, MUTEX_INITIALIZER };
diff --git a/lib/nbsd_libc/gdtoa/gdtoaimp.h b/lib/nbsd_libc/gdtoa/gdtoaimp.h
new file mode 100644 (file)
index 0000000..b897f00
--- /dev/null
@@ -0,0 +1,653 @@
+/* $NetBSD: gdtoaimp.h,v 1.8 2011/01/21 23:36:49 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998-2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* This is a variation on dtoa.c that converts arbitary binary
+   floating-point formats to and from decimal notation.  It uses
+   double-precision arithmetic internally, so there are still
+   various #ifdefs that adapt the calculations to the native
+   double-precision arithmetic (any of IEEE, VAX D_floating,
+   or IBM mainframe arithmetic).
+
+   Please send bug reports to David M. Gay (dmg at acm dot org,
+   with " at " changed at "@" and " dot " changed to ".").
+ */
+
+/* On a machine with IEEE extended-precision registers, it is
+ * necessary to specify double-precision (53-bit) rounding precision
+ * before invoking strtod or dtoa.  If the machine uses (the equivalent
+ * of) Intel 80x87 arithmetic, the call
+ *     _control87(PC_53, MCW_PC);
+ * does this with many compilers.  Whether this or another call is
+ * appropriate depends on the compiler; for this to work, it may be
+ * necessary to #include "float.h" or another system-dependent header
+ * file.
+ */
+
+/* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
+ *
+ * This strtod returns a nearest machine number to the input decimal
+ * string (or sets errno to ERANGE).  With IEEE arithmetic, ties are
+ * broken by the IEEE round-even rule.  Otherwise ties are broken by
+ * biased rounding (add half and chop).
+ *
+ * Inspired loosely by William D. Clinger's paper "How to Read Floating
+ * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 112-126].
+ *
+ * Modifications:
+ *
+ *     1. We only require IEEE, IBM, or VAX double-precision
+ *             arithmetic (not IEEE double-extended).
+ *     2. We get by with floating-point arithmetic in a case that
+ *             Clinger missed -- when we're computing d * 10^n
+ *             for a small integer d and the integer n is not too
+ *             much larger than 22 (the maximum integer k for which
+ *             we can represent 10^k exactly), we may be able to
+ *             compute (d*10^k) * 10^(e-k) with just one roundoff.
+ *     3. Rather than a bit-at-a-time adjustment of the binary
+ *             result in the hard case, we use floating-point
+ *             arithmetic to determine the adjustment to within
+ *             one bit; only in really hard cases do we need to
+ *             compute a second residual.
+ *     4. Because of 3., we don't need a large table of powers of 10
+ *             for ten-to-e (just some small tables, e.g. of 10^k
+ *             for 0 <= k <= 22).
+ */
+
+/*
+ * #define IEEE_LITTLE_ENDIAN for IEEE-arithmetic machines where the least
+ *     significant byte has the lowest address.
+ * #define IEEE_BIG_ENDIAN for IEEE-arithmetic machines where the most
+ *     significant byte has the lowest address.
+ * #define Long int on machines with 32-bit ints and 64-bit longs.
+ * #define Sudden_Underflow for IEEE-format machines without gradual
+ *     underflow (i.e., that flush to zero on underflow).
+ * #define IBM for IBM mainframe-style floating-point arithmetic.
+ * #define VAX for VAX-style floating-point arithmetic (D_floating).
+ * #define No_leftright to omit left-right logic in fast floating-point
+ *     computation of dtoa.
+ * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3.
+ * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
+ *     that use extended-precision instructions to compute rounded
+ *     products and quotients) with IBM.
+ * #define ROUND_BIASED for IEEE-format with biased rounding.
+ * #define Inaccurate_Divide for IEEE-format with correctly rounded
+ *     products but inaccurate quotients, e.g., for Intel i860.
+ * #define NO_LONG_LONG on machines that do not have a "long long"
+ *     integer type (of >= 64 bits).  On such machines, you can
+ *     #define Just_16 to store 16 bits per 32-bit Long when doing
+ *     high-precision integer arithmetic.  Whether this speeds things
+ *     up or slows things down depends on the machine and the number
+ *     being converted.  If long long is available and the name is
+ *     something other than "long long", #define Llong to be the name,
+ *     and if "unsigned Llong" does not work as an unsigned version of
+ *     Llong, #define #ULLong to be the corresponding unsigned type.
+ * #define KR_headers for old-style C function headers.
+ * #define Bad_float_h if your system lacks a float.h or if it does not
+ *     define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
+ *     FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
+ * #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
+ *     if memory is available and otherwise does something you deem
+ *     appropriate.  If MALLOC is undefined, malloc will be invoked
+ *     directly -- and assumed always to succeed.
+ * #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
+ *     memory allocations from a private pool of memory when possible.
+ *     When used, the private pool is PRIVATE_MEM bytes long:  2304 bytes,
+ *     unless #defined to be a different length.  This default length
+ *     suffices to get rid of MALLOC calls except for unusual cases,
+ *     such as decimal-to-binary conversion of a very long string of
+ *     digits.  When converting IEEE double precision values, the
+ *     longest string gdtoa can return is about 751 bytes long.  For
+ *     conversions by strtod of strings of 800 digits and all gdtoa
+ *     conversions of IEEE doubles in single-threaded executions with
+ *     8-byte pointers, PRIVATE_MEM >= 7400 appears to suffice; with
+ *     4-byte pointers, PRIVATE_MEM >= 7112 appears adequate.
+ * #define INFNAN_CHECK on IEEE systems to cause strtod to check for
+ *     Infinity and NaN (case insensitively).
+ *     When INFNAN_CHECK is #defined and No_Hex_NaN is not #defined,
+ *     strtodg also accepts (case insensitively) strings of the form
+ *     NaN(x), where x is a string of hexadecimal digits and spaces;
+ *     if there is only one string of hexadecimal digits, it is taken
+ *     for the fraction bits of the resulting NaN; if there are two or
+ *     more strings of hexadecimal digits, each string is assigned
+ *     to the next available sequence of 32-bit words of fractions
+ *     bits (starting with the most significant), right-aligned in
+ *     each sequence.
+ * #define MULTIPLE_THREADS if the system offers preemptively scheduled
+ *     multiple threads.  In this case, you must provide (or suitably
+ *     #define) two locks, acquired by ACQUIRE_DTOA_LOCK(n) and freed
+ *     by FREE_DTOA_LOCK(n) for n = 0 or 1.  (The second lock, accessed
+ *     in pow5mult, ensures lazy evaluation of only one copy of high
+ *     powers of 5; omitting this lock would introduce a small
+ *     probability of wasting memory, but would otherwise be harmless.)
+ *     You must also invoke freedtoa(s) to free the value s returned by
+ *     dtoa.  You may do so whether or not MULTIPLE_THREADS is #defined.
+ * #define IMPRECISE_INEXACT if you do not care about the setting of
+ *     the STRTOG_Inexact bits in the special case of doing IEEE double
+ *     precision conversions (which could also be done by the strtog in
+ *     dtoa.c).
+ * #define NO_HEX_FP to disable recognition of C9x's hexadecimal
+ *     floating-point constants.
+ * #define -DNO_ERRNO to suppress setting errno (in strtod.c and
+ *     strtodg.c).
+ * #define NO_STRING_H to use private versions of memcpy.
+ *     On some K&R systems, it may also be necessary to
+ *     #define DECLARE_SIZE_T in this case.
+ * #define YES_ALIAS to permit aliasing certain double values with
+ *     arrays of ULongs.  This leads to slightly better code with
+ *     some compilers and was always used prior to 19990916, but it
+ *     is not strictly legal and can cause trouble with aggressively
+ *     optimizing compilers (e.g., gcc 2.95.1 under -O2).
+ * #define USE_LOCALE to use the current locale's decimal_point value.
+ */
+
+/* #define IEEE_{BIG,LITTLE}_ENDIAN in ${ARCHDIR}/gdtoa/arith.h */
+
+#include <stdint.h>
+#define Short   int16_t
+#define UShort uint16_t
+#define Long    int32_t
+#define ULong  uint32_t
+#define LLong   int64_t
+#define ULLong uint64_t
+
+#define INFNAN_CHECK
+#ifdef _REENTRANT
+#define MULTIPLE_THREADS
+#endif
+#define USE_LOCALE
+
+#ifndef GDTOAIMP_H_INCLUDED
+#define GDTOAIMP_H_INCLUDED
+#include "gdtoa.h"
+#include "gd_qnan.h"
+
+#ifdef DEBUG
+#include "stdio.h"
+#define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
+#endif
+
+#include "stdlib.h"
+#include "string.h"
+
+#ifdef KR_headers
+#define Char char
+#else
+#define Char void
+#endif
+
+#ifdef MALLOC
+extern Char *MALLOC ANSI((size_t));
+#else
+#define MALLOC malloc
+#endif
+
+#undef IEEE_Arith
+#undef Avoid_Underflow
+#ifdef IEEE_BIG_ENDIAN
+#define IEEE_Arith
+#endif
+#ifdef IEEE_LITTLE_ENDIAN
+#define IEEE_Arith
+#endif
+
+#include "errno.h"
+#ifdef Bad_float_h
+
+#ifdef IEEE_Arith
+#define DBL_DIG 15
+#define DBL_MAX_10_EXP 308
+#define DBL_MAX_EXP 1024
+#define FLT_RADIX 2
+#define DBL_MAX 1.7976931348623157e+308
+#endif
+
+#ifdef IBM
+#define DBL_DIG 16
+#define DBL_MAX_10_EXP 75
+#define DBL_MAX_EXP 63
+#define FLT_RADIX 16
+#define DBL_MAX 7.2370055773322621e+75
+#endif
+
+#ifdef VAX
+#define DBL_DIG 16
+#define DBL_MAX_10_EXP 38
+#define DBL_MAX_EXP 127
+#define FLT_RADIX 2
+#define DBL_MAX 1.7014118346046923e+38
+#define n_bigtens 2
+#endif
+
+#ifndef LONG_MAX
+#define LONG_MAX 2147483647
+#endif
+
+#else /* ifndef Bad_float_h */
+#include "float.h"
+#endif /* Bad_float_h */
+
+#ifdef IEEE_Arith
+#define Scale_Bit 0x10
+#define n_bigtens 5
+#endif
+
+#ifdef IBM
+#define n_bigtens 3
+#endif
+
+#ifdef VAX
+#define n_bigtens 2
+#endif
+
+#include "math.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(IEEE_LITTLE_ENDIAN) + defined(IEEE_BIG_ENDIAN) + defined(VAX) + defined(IBM) != 1
+Exactly one of IEEE_LITTLE_ENDIAN, IEEE_BIG_ENDIAN, VAX, or IBM should be defined.
+#endif
+
+typedef union { double d; ULong L[2]; } __attribute__((__may_alias__)) U;
+
+#ifdef YES_ALIAS
+#define dval(x) x
+#ifdef IEEE_LITTLE_ENDIAN
+#define word0(x) ((ULong *)&x)[1]
+#define word1(x) ((ULong *)&x)[0]
+#else
+#define word0(x) ((ULong *)&x)[0]
+#define word1(x) ((ULong *)&x)[1]
+#endif
+#else /* !YES_ALIAS */
+#ifdef IEEE_LITTLE_ENDIAN
+#define word0(x) ( /* LINTED */ (U*)&x)->L[1]
+#define word1(x) ( /* LINTED */ (U*)&x)->L[0]
+#else
+#define word0(x) ( /* LINTED */ (U*)&x)->L[0]
+#define word1(x) ( /* LINTED */ (U*)&x)->L[1]
+#endif
+#define dval(x) ( /* LINTED */ (U*)&x)->d
+#endif /* YES_ALIAS */
+
+/* The following definition of Storeinc is appropriate for MIPS processors.
+ * An alternative that might be better on some machines is
+ * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
+ */
+#if defined(IEEE_LITTLE_ENDIAN) + defined(VAX)
+#define Storeinc(a,b,c) \
+ (((unsigned short *)(void *)a)[1] = (unsigned short)b, \
+  ((unsigned short *)(void *)a)[0] = (unsigned short)c, \
+  a++)
+#else
+#define Storeinc(a,b,c) \
+ (((unsigned short *)(void *)a)[0] = (unsigned short)b, \
+  ((unsigned short *)(void *)a)[1] = (unsigned short)c, \
+  a++)
+#endif
+
+/* #define P DBL_MANT_DIG */
+/* Ten_pmax = floor(P*log(2)/log(5)) */
+/* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
+/* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
+/* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
+
+#ifdef IEEE_Arith
+#define Exp_shift  20
+#define Exp_shift1 20
+#define Exp_msk1    0x100000
+#define Exp_msk11   0x100000
+#define Exp_mask  0x7ff00000
+#define P 53
+#define Bias 1023
+#define Emin (-1022)
+#define Exp_1  0x3ff00000
+#define Exp_11 0x3ff00000
+#define Ebits 11
+#define Frac_mask  0xfffff
+#define Frac_mask1 0xfffff
+#define Ten_pmax 22
+#define Bletch 0x10
+#define Bndry_mask  0xfffff
+#define Bndry_mask1 0xfffff
+#define LSB 1
+#define Sign_bit 0x80000000
+#define Log2P 1
+#define Tiny0 0
+#define Tiny1 1
+#define Quick_max 14
+#define Int_max 14
+
+#ifndef Flt_Rounds
+#ifdef FLT_ROUNDS
+#define Flt_Rounds FLT_ROUNDS
+#else
+#define Flt_Rounds 1
+#endif
+#endif /*Flt_Rounds*/
+
+#else /* ifndef IEEE_Arith */
+#undef  Sudden_Underflow
+#define Sudden_Underflow
+#ifdef IBM
+#undef Flt_Rounds
+#define Flt_Rounds 0
+#define Exp_shift  24
+#define Exp_shift1 24
+#define Exp_msk1   0x1000000
+#define Exp_msk11  0x1000000
+#define Exp_mask  0x7f000000
+#define P 14
+#define Bias 65
+#define Exp_1  0x41000000
+#define Exp_11 0x41000000
+#define Ebits 8        /* exponent has 7 bits, but 8 is the right value in b2d */
+#define Frac_mask  0xffffff
+#define Frac_mask1 0xffffff
+#define Bletch 4
+#define Ten_pmax 22
+#define Bndry_mask  0xefffff
+#define Bndry_mask1 0xffffff
+#define LSB 1
+#define Sign_bit 0x80000000
+#define Log2P 4
+#define Tiny0 0x100000
+#define Tiny1 0
+#define Quick_max 14
+#define Int_max 15
+#else /* VAX */
+#undef Flt_Rounds
+#define Flt_Rounds 1
+#define Exp_shift  23
+#define Exp_shift1 7
+#define Exp_msk1    0x80
+#define Exp_msk11   0x800000
+#define Exp_mask  0x7f80
+#define P 56
+#define Bias 129
+#define Exp_1  0x40800000
+#define Exp_11 0x4080
+#define Ebits 8
+#define Frac_mask  0x7fffff
+#define Frac_mask1 0xffff007f
+#define Ten_pmax 24
+#define Bletch 2
+#define Bndry_mask  0xffff007f
+#define Bndry_mask1 0xffff007f
+#define LSB 0x10000
+#define Sign_bit 0x8000
+#define Log2P 1
+#define Tiny0 0x80
+#define Tiny1 0
+#define Quick_max 15
+#define Int_max 15
+#endif /* IBM, VAX */
+#endif /* IEEE_Arith */
+
+#ifndef IEEE_Arith
+#define ROUND_BIASED
+#endif
+
+#ifdef RND_PRODQUOT
+#define rounded_product(a,b) a = rnd_prod(a, b)
+#define rounded_quotient(a,b) a = rnd_quot(a, b)
+#ifdef KR_headers
+extern double rnd_prod(), rnd_quot();
+#else
+extern double rnd_prod(double, double), rnd_quot(double, double);
+#endif
+#else
+#define rounded_product(a,b) a *= b
+#define rounded_quotient(a,b) a /= b
+#endif
+
+#define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
+#define Big1 0xffffffff
+
+#undef  Pack_16
+#ifndef Pack_32
+#define Pack_32
+#endif
+
+#ifdef NO_LONG_LONG
+#undef ULLong
+#ifdef Just_16
+#undef Pack_32
+#define Pack_16
+/* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
+ * This makes some inner loops simpler and sometimes saves work
+ * during multiplications, but it often seems to make things slightly
+ * slower.  Hence the default is now to store 32 bits per Long.
+ */
+#endif
+#else  /* long long available */
+#ifndef Llong
+#define Llong long long
+#endif
+#ifndef ULLong
+#define ULLong unsigned Llong
+#endif
+#endif /* NO_LONG_LONG */
+
+#ifdef Pack_32
+#define ULbits 32
+#define kshift 5
+#define kmask 31
+#define ALL_ON 0xffffffff
+#else
+#define ULbits 16
+#define kshift 4
+#define kmask 15
+#define ALL_ON 0xffff
+#endif
+
+#ifndef MULTIPLE_THREADS
+#define ACQUIRE_DTOA_LOCK(n)   /*nothing*/
+#define FREE_DTOA_LOCK(n)      /*nothing*/
+#else
+#include "reentrant.h"
+
+extern mutex_t __gdtoa_locks[2];
+
+#define ACQUIRE_DTOA_LOCK(n)   \
+       do {                                                    \
+               if (__isthreaded)                               \
+                       mutex_lock(&__gdtoa_locks[n]);          \
+       } while (/* CONSTCOND */ 0)
+#define FREE_DTOA_LOCK(n)      \
+       do {                                                    \
+               if (__isthreaded)                               \
+                       mutex_unlock(&__gdtoa_locks[n]);        \
+       } while (/* CONSTCOND */ 0)
+#endif
+
+#define Kmax (sizeof(size_t) << 3)
+
+ struct
+Bigint {
+       struct Bigint *next;
+       int k, maxwds, sign, wds;
+       ULong x[1];
+       };
+
+ typedef struct Bigint Bigint;
+
+#ifdef NO_STRING_H
+#ifdef DECLARE_SIZE_T
+typedef unsigned int size_t;
+#endif
+extern void memcpy_D2A ANSI((void*, const void*, size_t));
+#define Bcopy(x,y) memcpy_D2A(&x->sign,&y->sign,y->wds*sizeof(ULong) + 2*sizeof(int))
+#else /* !NO_STRING_H */
+#define Bcopy(x,y) memcpy(&x->sign,&y->sign,y->wds*sizeof(ULong) + 2*sizeof(int))
+#endif /* NO_STRING_H */
+
+#define Balloc         __Balloc_D2A
+#define Bfree          __Bfree_D2A
+#define ULtoQ          __ULtoQ_D2A
+#define ULtof          __ULtof_D2A
+#define ULtod          __ULtod_D2A
+#define ULtodd         __ULtodd_D2A
+#define ULtox          __ULtox_D2A
+#define ULtoxL         __ULtoxL_D2A
+#define any_on                 __any_on_D2A
+#define b2d            __b2d_D2A
+#define bigtens        __bigtens_D2A
+#define cmp            __cmp_D2A
+#define copybits       __copybits_D2A
+#define d2b            __d2b_D2A
+#define decrement      __decrement_D2A
+#define diff           __diff_D2A
+#define dtoa_result    __dtoa_result_D2A
+#define g__fmt                 __g__fmt_D2A
+#define gethex                 __gethex_D2A
+#define hexdig                 __hexdig_D2A
+#define hexdig_init_D2A        __hexdig_init_D2A
+#define hexnan         __hexnan_D2A
+#define hi0bits                __hi0bits_D2A
+#define hi0bits_D2A    __hi0bits_D2A
+#define i2b            __i2b_D2A
+#define increment      __increment_D2A
+#define lo0bits                __lo0bits_D2A
+#define lshift         __lshift_D2A
+#define match          __match_D2A
+#define mult           __mult_D2A
+#define multadd                __multadd_D2A
+#define nrv_alloc      __nrv_alloc_D2A
+#define pow5mult       __pow5mult_D2A
+#define quorem         __quorem_D2A
+#define ratio          __ratio_D2A
+#define rshift         __rshift_D2A
+#define rv_alloc       __rv_alloc_D2A
+#define s2b            __s2b_D2A
+#define set_ones       __set_ones_D2A
+#define strcp          __strcp_D2A
+#define strcp_D2A      __strcp_D2A
+#define strtoIg                __strtoIg_D2A
+#define sum            __sum_D2A
+#define tens           __tens_D2A
+#define tinytens       __tinytens_D2A
+#define tinytens       __tinytens_D2A
+#define trailz         __trailz_D2A
+#define ulp            __ulp_D2A
+
+ extern char *dtoa_result;
+ extern CONST double bigtens[], tens[], tinytens[];
+ extern unsigned char hexdig[];
+
+ extern Bigint *Balloc ANSI((int));
+ extern void Bfree ANSI((Bigint*));
+ extern void ULtof ANSI((ULong*, ULong*, Long, int));
+ extern void ULtod ANSI((ULong*, ULong*, Long, int));
+ extern void ULtodd ANSI((ULong*, ULong*, Long, int));
+ extern void ULtoQ ANSI((ULong*, ULong*, Long, int));
+ extern void ULtox ANSI((UShort*, ULong*, Long, int));
+ extern void ULtoxL ANSI((ULong*, ULong*, Long, int));
+ extern ULong any_on ANSI((Bigint*, int));
+ extern double b2d ANSI((Bigint*, int*));
+ extern int cmp ANSI((Bigint*, Bigint*));
+ extern void copybits ANSI((ULong*, int, Bigint*));
+ extern Bigint *d2b ANSI((double, int*, int*));
+ extern int decrement ANSI((Bigint*));
+ extern Bigint *diff ANSI((Bigint*, Bigint*));
+ extern char *dtoa ANSI((double d, int mode, int ndigits,
+                       int *decpt, int *sign, char **rve));
+ extern char *g__fmt ANSI((char*, char*, char*, int, ULong));
+ extern int gethex ANSI((CONST char**, CONST FPI*, Long*, Bigint**, int));
+ extern void hexdig_init_D2A(Void);
+ extern int hexnan ANSI((CONST char**, CONST FPI*, ULong*));
+ extern int hi0bits_D2A ANSI((ULong));
+ extern Bigint *i2b ANSI((int));
+ extern Bigint *increment ANSI((Bigint*));
+ extern int lo0bits ANSI((ULong*));
+ extern Bigint *lshift ANSI((Bigint*, int));
+ extern int match ANSI((CONST char**, CONST char*));
+ extern Bigint *mult ANSI((Bigint*, Bigint*));
+ extern Bigint *multadd ANSI((Bigint*, int, int));
+ extern char *nrv_alloc ANSI((CONST char*, char **, size_t));
+ extern Bigint *pow5mult ANSI((Bigint*, int));
+ extern int quorem ANSI((Bigint*, Bigint*));
+ extern double ratio ANSI((Bigint*, Bigint*));
+ extern void rshift ANSI((Bigint*, int));
+ extern char *rv_alloc ANSI((size_t));
+ extern Bigint *s2b ANSI((CONST char*, int, int, ULong));
+ extern Bigint *set_ones ANSI((Bigint*, int));
+ extern char *strcp ANSI((char*, const char*));
+ extern int strtoIg ANSI((CONST char*, char**, FPI*, Long*, Bigint**, int*));
+ extern double strtod ANSI((const char *s00, char **se));
+ extern Bigint *sum ANSI((Bigint*, Bigint*));
+ extern int trailz ANSI((CONST Bigint*));
+ extern double ulp ANSI((double));
+
+#ifdef __cplusplus
+}
+#endif
+/*
+ * NAN_WORD0 and NAN_WORD1 are only referenced in strtod.c.  Prior to
+ * 20050115, they used to be hard-wired here (to 0x7ff80000 and 0,
+ * respectively), but now are determined by compiling and running
+ * qnan.c to generate gd_qnan.h, which specifies d_QNAN0 and d_QNAN1.
+ * Formerly gdtoaimp.h recommended supplying suitable -DNAN_WORD0=...
+ * and -DNAN_WORD1=...  values if necessary.  This should still work.
+ * (On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
+ */
+#ifdef IEEE_Arith
+#ifdef IEEE_BIG_ENDIAN
+#define _0 0
+#define _1 1
+#ifndef NAN_WORD0
+#define NAN_WORD0 d_QNAN0
+#endif
+#ifndef NAN_WORD1
+#define NAN_WORD1 d_QNAN1
+#endif
+#else
+#define _0 1
+#define _1 0
+#ifndef NAN_WORD0
+#define NAN_WORD0 d_QNAN1
+#endif
+#ifndef NAN_WORD1
+#define NAN_WORD1 d_QNAN0
+#endif
+#endif
+#else
+#undef INFNAN_CHECK
+#endif
+
+#undef SI
+#ifdef Sudden_Underflow
+#define SI 1
+#else
+#define SI 0
+#endif
+
+#endif /* GDTOAIMP_H_INCLUDED */
diff --git a/lib/nbsd_libc/gdtoa/gethex.c b/lib/nbsd_libc/gdtoa/gethex.c
new file mode 100644 (file)
index 0000000..a63ce97
--- /dev/null
@@ -0,0 +1,253 @@
+/* $NetBSD: gethex.c,v 1.4 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#ifdef USE_LOCALE
+#include "locale.h"
+#endif
+
+ int
+#ifdef KR_headers
+gethex(sp, fpi, expt, bp, sign)
+       CONST char **sp; CONST FPI *fpi; Long *expt; Bigint **bp; int sign;
+#else
+gethex( CONST char **sp, CONST FPI *fpi, Long *expt, Bigint **bp, int sign)
+#endif
+{
+       Bigint *b;
+       CONST unsigned char *decpt, *s0, *s, *s1;
+       int esign, havedig, irv, k, n, nbits, up, zret;
+       ULong L, lostbits, *x;
+       Long e, e1;
+#ifdef USE_LOCALE
+       unsigned char decimalpoint = *localeconv()->decimal_point;
+#else
+#define decimalpoint '.'
+#endif
+
+       if (!hexdig['0'])
+               hexdig_init_D2A();
+       havedig = 0;
+       s0 = *(CONST unsigned char **)sp + 2;
+       while(s0[havedig] == '0')
+               havedig++;
+       s0 += havedig;
+       s = s0;
+       decpt = 0;
+       zret = 0;
+       e = 0;
+       if (!hexdig[*s]) {
+               zret = 1;
+               if (*s != decimalpoint)
+                       goto pcheck;
+               decpt = ++s;
+               if (!hexdig[*s])
+                       goto pcheck;
+               while(*s == '0')
+                       s++;
+               if (hexdig[*s])
+                       zret = 0;
+               havedig = 1;
+               s0 = s;
+               }
+       while(hexdig[*s])
+               s++;
+       if (*s == decimalpoint && !decpt) {
+               decpt = ++s;
+               while(hexdig[*s])
+                       s++;
+               }
+       if (decpt)
+               e = -(((Long)(s-decpt)) << 2);
+ pcheck:
+       s1 = s;
+       switch(*s) {
+         case 'p':
+         case 'P':
+               esign = 0;
+               switch(*++s) {
+                 case '-':
+                       esign = 1;
+                       /* FALLTHROUGH */
+                 case '+':
+                       s++;
+                 }
+               if ((n = hexdig[*s]) == 0 || n > 0x19) {
+                       s = s1;
+                       break;
+                       }
+               e1 = n - 0x10;
+               while((n = hexdig[*++s]) !=0 && n <= 0x19)
+                       e1 = 10*e1 + n - 0x10;
+               if (esign)
+                       e1 = -e1;
+               e += e1;
+         }
+       *sp = __UNCONST(s);
+       if (zret)
+               return havedig ? STRTOG_Zero : STRTOG_NoNumber;
+       n = s1 - s0 - 1;
+       for(k = 0; n > 7; n = (unsigned int)n >> 1)
+               k++;
+       b = Balloc(k);
+       if (b == NULL)
+               return STRTOG_NoMemory;
+       x = b->x;
+       n = 0;
+       L = 0;
+       while(s1 > s0) {
+               if (*--s1 == decimalpoint)
+                       continue;
+               if (n == 32) {
+                       *x++ = L;
+                       L = 0;
+                       n = 0;
+                       }
+               L |= (hexdig[*s1] & 0x0f) << n;
+               n += 4;
+               }
+       *x++ = L;
+       b->wds = n = x - b->x;
+       n = 32*n - hi0bits(L);
+       nbits = fpi->nbits;
+       lostbits = 0;
+       x = b->x;
+       if (n > nbits) {
+               n -= nbits;
+               if (any_on(b,n)) {
+                       lostbits = 1;
+                       k = n - 1;
+                       if (x[(unsigned int)k>>kshift] & 1 << (k & kmask)) {
+                               lostbits = 2;
+                               if (k > 1 && any_on(b,k-1))
+                                       lostbits = 3;
+                               }
+                       }
+               rshift(b, n);
+               e += n;
+               }
+       else if (n < nbits) {
+               n = nbits - n;
+               b = lshift(b, n);
+               if (b == NULL)
+                       return STRTOG_NoMemory;
+               e -= n;
+               x = b->x;
+               }
+       if (e > fpi->emax) {
+ ovfl:
+               Bfree(b);
+               *bp = 0;
+               return STRTOG_Infinite | STRTOG_Overflow | STRTOG_Inexhi;
+               }
+       irv = STRTOG_Normal;
+       if (e < fpi->emin) {
+               irv = STRTOG_Denormal;
+               n = fpi->emin - e;
+               if (n >= nbits) {
+                       switch (fpi->rounding) {
+                         case FPI_Round_near:
+                               if (n == nbits && (n < 2 || any_on(b,n-1)))
+                                       goto one_bit;
+                               break;
+                         case FPI_Round_up:
+                               if (!sign)
+                                       goto one_bit;
+                               break;
+                         case FPI_Round_down:
+                               if (sign) {
+ one_bit:
+                                       *expt = fpi->emin;
+                                       x[0] = b->wds = 1;
+                                       *bp = b;
+                                       return STRTOG_Denormal | STRTOG_Inexhi
+                                               | STRTOG_Underflow;
+                                       }
+                         }
+                       Bfree(b);
+                       *bp = 0;
+                       return STRTOG_Zero | STRTOG_Inexlo | STRTOG_Underflow;
+                       }
+               k = n - 1;
+               if (lostbits)
+                       lostbits = 1;
+               else if (k > 0)
+                       lostbits = any_on(b,k);
+               if (x[(unsigned int)k>>kshift] & 1 << (k & kmask))
+                       lostbits |= 2;
+               nbits -= n;
+               rshift(b,n);
+               e = fpi->emin;
+               }
+       if (lostbits) {
+               up = 0;
+               switch(fpi->rounding) {
+                 case FPI_Round_zero:
+                       break;
+                 case FPI_Round_near:
+                       if (lostbits & 2
+                        && (lostbits & 1) | (x[0] & 1))
+                               up = 1;
+                       break;
+                 case FPI_Round_up:
+                       up = 1 - sign;
+                       break;
+                 case FPI_Round_down:
+                       up = sign;
+                 }
+               if (up) {
+                       k = b->wds;
+                       b = increment(b);
+                       x = b->x;
+                       if (irv == STRTOG_Denormal) {
+                               if (nbits == fpi->nbits - 1
+                                && x[(unsigned int)nbits >> kshift] & 1 << (nbits & kmask))
+                                       irv =  STRTOG_Normal;
+                               }
+                       else if (b->wds > k
+                        || ((n = nbits & kmask) !=0
+                            && hi0bits(x[k-1]) < 32-n)) {
+                               rshift(b,1);
+                               if (++e > fpi->emax)
+                                       goto ovfl;
+                               }
+                       irv |= STRTOG_Inexhi;
+                       }
+               else
+                       irv |= STRTOG_Inexlo;
+               }
+       *bp = b;
+       *expt = e;
+       return irv;
+       }
diff --git a/lib/nbsd_libc/gdtoa/gmisc.c b/lib/nbsd_libc/gdtoa/gmisc.c
new file mode 100644 (file)
index 0000000..36ae1d8
--- /dev/null
@@ -0,0 +1,89 @@
+/* $NetBSD: gmisc.c,v 1.3 2006/03/11 18:38:14 kleink Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ void
+#ifdef KR_headers
+rshift(b, k) Bigint *b; int k;
+#else
+rshift(Bigint *b, int k)
+#endif
+{
+       ULong *x, *x1, *xe, y;
+       int n;
+
+       x = x1 = b->x;
+       n = (unsigned int)k >> kshift;
+       if (n < b->wds) {
+               xe = x + b->wds;
+               x += n;
+               if (k &= kmask) {
+                       n = ULbits - k;
+                       y = *x++ >> k;
+                       while(x < xe) {
+                               *x1++ = (y | (*x << n)) & ALL_ON;
+                               y = *x++ >> k;
+                               }
+                       if ((*x1 = y) !=0)
+                               x1++;
+                       }
+               else
+                       while(x < xe)
+                               *x1++ = *x++;
+               }
+       if ((b->wds = x1 - b->x) == 0)
+               b->x[0] = 0;
+       }
+
+ int
+#ifdef KR_headers
+trailz(b) CONST Bigint *b;
+#else
+trailz(CONST Bigint *b)
+#endif
+{
+       ULong L;
+       CONST ULong *x, *xe;
+       int n = 0;
+
+       x = b->x;
+       xe = x + b->wds;
+       for(n = 0; x < xe && !*x; x++)
+               n += ULbits;
+       if (x < xe) {
+               L = *x;
+               n += lo0bits(&L);
+               }
+       return n;
+       }
diff --git a/lib/nbsd_libc/gdtoa/hd_init.c b/lib/nbsd_libc/gdtoa/hd_init.c
new file mode 100644 (file)
index 0000000..55d5d42
--- /dev/null
@@ -0,0 +1,57 @@
+/* $NetBSD: hd_init.c,v 1.2 2006/01/25 15:27:42 kleink Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ unsigned char hexdig[256];
+
+ static void
+#ifdef KR_headers
+htinit(h, s, inc) unsigned char *h; CONST unsigned char *s; int inc;
+#else
+htinit(unsigned char *h, CONST unsigned char *s, int inc)
+#endif
+{
+       int i, j;
+       for(i = 0; (j = s[i]) !=0; i++)
+               h[j] = i + inc;
+       }
+
+ void
+hexdig_init_D2A(Void)
+{
+#define USC (CONST unsigned char *)
+       htinit(hexdig, USC "0123456789", 0x10);
+       htinit(hexdig, USC "abcdef", 0x10 + 10);
+       htinit(hexdig, USC "ABCDEF", 0x10 + 10);
+       }
diff --git a/lib/nbsd_libc/gdtoa/hdtoa.c b/lib/nbsd_libc/gdtoa/hdtoa.c
new file mode 100644 (file)
index 0000000..8396bbe
--- /dev/null
@@ -0,0 +1,363 @@
+/*     $NetBSD: hdtoa.c,v 1.6 2008/03/21 23:13:48 christos Exp $       */
+
+/*-
+ * Copyright (c) 2004, 2005 David Schultz <das@FreeBSD.ORG>
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/gdtoa/_hdtoa.c,v 1.4 2007/01/03 04:57:58 das Exp $");
+#else
+__RCSID("$NetBSD: hdtoa.c,v 1.6 2008/03/21 23:13:48 christos Exp $");
+#endif
+
+#include <float.h>
+#include <limits.h>
+#include <math.h>
+#ifndef __vax__
+#include <machine/ieee.h>
+#else
+#include <machine/vaxfp.h>
+#define ieee_double_u vax_dfloating_u
+#define dblu_d dfltu_d
+#define dblu_dbl dfltu_dflt
+#define dbl_sign dflt_sign
+#define dbl_exp dflt_exp
+#define dbl_frach dflt_frach
+#define dbl_fracm dflt_fracm
+#define dbl_fracl dflt_fracl
+#define DBL_FRACHBITS  DFLT_FRACHBITS
+#define DBL_FRACMBITS  DFLT_FRACMBITS
+#define DBL_FRACLBITS  DFLT_FRACLBITS
+#define DBL_EXPBITS    DFLT_EXPBITS
+#endif
+#include "gdtoaimp.h"
+
+/* Strings values used by dtoa() */
+#define        INFSTR  "Infinity"
+#define        NANSTR  "NaN"
+
+#define        DBL_ADJ         (DBL_MAX_EXP - 2 + ((DBL_MANT_DIG - 1) % 4))
+#define        LDBL_ADJ        (LDBL_MAX_EXP - 2 + ((LDBL_MANT_DIG - 1) % 4))
+
+/*
+ * Round up the given digit string.  If the digit string is fff...f,
+ * this procedure sets it to 100...0 and returns 1 to indicate that
+ * the exponent needs to be bumped.  Otherwise, 0 is returned.
+ */
+static int
+roundup(char *s0, int ndigits)
+{
+       char *s;
+
+       for (s = s0 + ndigits - 1; *s == 0xf; s--) {
+               if (s == s0) {
+                       *s = 1;
+                       return (1);
+               }
+               *s = 0;
+       }
+       ++*s;
+       return (0);
+}
+
+/*
+ * Round the given digit string to ndigits digits according to the
+ * current rounding mode.  Note that this could produce a string whose
+ * value is not representable in the corresponding floating-point
+ * type.  The exponent pointed to by decpt is adjusted if necessary.
+ */
+static void
+dorounding(char *s0, int ndigits, int sign, int *decpt)
+{
+       int adjust = 0; /* do we need to adjust the exponent? */
+
+       switch (FLT_ROUNDS) {
+       case 0:         /* toward zero */
+       default:        /* implementation-defined */
+               break;
+       case 1:         /* to nearest, halfway rounds to even */
+               if ((s0[ndigits] > 8) ||
+                   (s0[ndigits] == 8 && s0[ndigits - 1] & 1))
+                       adjust = roundup(s0, ndigits);
+               break;
+       case 2:         /* toward +inf */
+               if (sign == 0)
+                       adjust = roundup(s0, ndigits);
+               break;
+       case 3:         /* toward -inf */
+               if (sign != 0)
+                       adjust = roundup(s0, ndigits);
+               break;
+       }
+
+       if (adjust)
+               *decpt += 4;
+}
+
+/*
+ * This procedure converts a double-precision number in IEEE format
+ * into a string of hexadecimal digits and an exponent of 2.  Its
+ * behavior is bug-for-bug compatible with dtoa() in mode 2, with the
+ * following exceptions:
+ *
+ * - An ndigits < 0 causes it to use as many digits as necessary to
+ *   represent the number exactly.
+ * - The additional xdigs argument should point to either the string
+ *   "0123456789ABCDEF" or the string "0123456789abcdef", depending on
+ *   which case is desired.
+ * - This routine does not repeat dtoa's mistake of setting decpt
+ *   to 9999 in the case of an infinity or NaN.  INT_MAX is used
+ *   for this purpose instead.
+ *
+ * Note that the C99 standard does not specify what the leading digit
+ * should be for non-zero numbers.  For instance, 0x1.3p3 is the same
+ * as 0x2.6p2 is the same as 0x4.cp3.  This implementation chooses the
+ * first digit so that subsequent digits are aligned on nibble
+ * boundaries (before rounding).
+ *
+ * Inputs:     d, xdigs, ndigits
+ * Outputs:    decpt, sign, rve
+ */
+char *
+hdtoa(double d, const char *xdigs, int ndigits, int *decpt, int *sign,
+    char **rve)
+{
+       static const int sigfigs = (DBL_MANT_DIG + 3) / 4;
+       union ieee_double_u u;
+       char *s, *s0;
+       size_t bufsize;
+
+       u.dblu_d = d;
+       *sign = u.dblu_dbl.dbl_sign;
+
+       switch (fpclassify(d)) {
+       case FP_NORMAL:
+               *decpt = u.dblu_dbl.dbl_exp - DBL_ADJ;
+               break;
+       case FP_ZERO:
+               *decpt = 1;
+               return (nrv_alloc("0", rve, 1));
+       case FP_SUBNORMAL:
+               u.dblu_d *= 0x1p514;
+               *decpt = u.dblu_dbl.dbl_exp - (514 + DBL_ADJ);
+               break;
+       case FP_INFINITE:
+               *decpt = INT_MAX;
+               return (nrv_alloc(INFSTR, rve, sizeof(INFSTR) - 1));
+       case FP_NAN:
+               *decpt = INT_MAX;
+               return (nrv_alloc(NANSTR, rve, sizeof(NANSTR) - 1));
+       default:
+               abort();
+       }
+
+       /* FP_NORMAL or FP_SUBNORMAL */
+
+       if (ndigits == 0)               /* dtoa() compatibility */
+               ndigits = 1;
+
+       /*
+        * For simplicity, we generate all the digits even if the
+        * caller has requested fewer.
+        */
+       bufsize = (sigfigs > ndigits) ? sigfigs : ndigits;
+       s0 = rv_alloc(bufsize);
+       if (s0 == NULL)
+               return NULL;
+
+       /*
+        * We work from right to left, first adding any requested zero
+        * padding, then the least significant portion of the
+        * mantissa, followed by the most significant.  The buffer is
+        * filled with the byte values 0x0 through 0xf, which are
+        * converted to xdigs[0x0] through xdigs[0xf] after the
+        * rounding phase.
+        */
+       for (s = s0 + bufsize - 1; s > s0 + sigfigs - 1; s--)
+               *s = 0;
+       for (; s > s0 + sigfigs - (DBL_FRACLBITS / 4) - 1 && s > s0; s--) {
+               *s = u.dblu_dbl.dbl_fracl & 0xf;
+               u.dblu_dbl.dbl_fracl >>= 4;
+       }
+#ifdef DBL_FRACMBITS
+       for (; s > s0; s--) {
+               *s = u.dblu_dbl.dbl_fracm & 0xf;
+               u.dblu_dbl.dbl_fracm >>= 4;
+       }
+#endif
+       for (; s > s0; s--) {
+               *s = u.dblu_dbl.dbl_frach & 0xf;
+               u.dblu_dbl.dbl_frach >>= 4;
+       }
+
+       /*
+        * At this point, we have snarfed all the bits in the
+        * mantissa, with the possible exception of the highest-order
+        * (partial) nibble, which is dealt with by the next
+        * statement.  We also tack on the implicit normalization bit.
+        */
+       *s = u.dblu_dbl.dbl_frach | (1U << ((DBL_MANT_DIG - 1) % 4));
+
+       /* If ndigits < 0, we are expected to auto-size the precision. */
+       if (ndigits < 0) {
+               for (ndigits = sigfigs; s0[ndigits - 1] == 0; ndigits--)
+                       continue;
+       }
+
+       if (sigfigs > ndigits && s0[ndigits] != 0)
+               dorounding(s0, ndigits, u.dblu_dbl.dbl_sign, decpt);
+
+       s = s0 + ndigits;
+       if (rve != NULL)
+               *rve = s;
+       *s-- = '\0';
+       for (; s >= s0; s--)
+               *s = xdigs[(unsigned int)*s];
+
+       return (s0);
+}
+
+#if (LDBL_MANT_DIG > DBL_MANT_DIG)
+
+/*
+ * This is the long double version of hdtoa().
+ */
+char *
+hldtoa(long double e, const char *xdigs, int ndigits, int *decpt, int *sign,
+    char **rve)
+{
+       static const int sigfigs = (LDBL_MANT_DIG + 3) / 4;
+       union ieee_ext_u u;
+       char *s, *s0;
+       size_t bufsize;
+
+       u.extu_ld = e;
+       *sign = u.extu_ext.ext_sign;
+
+       switch (fpclassify(e)) {
+       case FP_NORMAL:
+               *decpt = u.extu_ext.ext_exp - LDBL_ADJ;
+               break;
+       case FP_ZERO:
+               *decpt = 1;
+               return (nrv_alloc("0", rve, 1));
+       case FP_SUBNORMAL:
+               u.extu_ld *= 0x1p514L;
+               *decpt = u.extu_ext.ext_exp - (514 + LDBL_ADJ);
+               break;
+       case FP_INFINITE:
+               *decpt = INT_MAX;
+               return (nrv_alloc(INFSTR, rve, sizeof(INFSTR) - 1));
+       case FP_NAN:
+               *decpt = INT_MAX;
+               return (nrv_alloc(NANSTR, rve, sizeof(NANSTR) - 1));
+       default:
+               abort();
+       }
+
+       /* FP_NORMAL or FP_SUBNORMAL */
+
+       if (ndigits == 0)               /* dtoa() compatibility */
+               ndigits = 1;
+
+       /*
+        * For simplicity, we generate all the digits even if the
+        * caller has requested fewer.
+        */
+       bufsize = (sigfigs > ndigits) ? sigfigs : ndigits;
+       s0 = rv_alloc(bufsize);
+       if (s0 == NULL)
+               return NULL;
+
+       /*
+        * We work from right to left, first adding any requested zero
+        * padding, then the least significant portion of the
+        * mantissa, followed by the most significant.  The buffer is
+        * filled with the byte values 0x0 through 0xf, which are
+        * converted to xdigs[0x0] through xdigs[0xf] after the
+        * rounding phase.
+        */
+       for (s = s0 + bufsize - 1; s > s0 + sigfigs - 1; s--)
+               *s = 0;
+       for (; s > s0 + sigfigs - (EXT_FRACLBITS / 4) - 1 && s > s0; s--) {
+               *s = u.extu_ext.ext_fracl & 0xf;
+               u.extu_ext.ext_fracl >>= 4;
+       }
+#ifdef EXT_FRACHMBITS
+       for (; s > s0; s--) {
+               *s = u.extu_ext.ext_frachm & 0xf;
+               u.extu_ext.ext_frachm >>= 4;
+       }
+#endif
+#ifdef EXT_FRACLMBITS
+       for (; s > s0; s--) {
+               *s = u.extu_ext.ext_fraclm & 0xf;
+               u.extu_ext.ext_fraclm >>= 4;
+       }
+#endif
+       for (; s > s0; s--) {
+               *s = u.extu_ext.ext_frach & 0xf;
+               u.extu_ext.ext_frach >>= 4;
+       }
+
+       /*
+        * At this point, we have snarfed all the bits in the
+        * mantissa, with the possible exception of the highest-order
+        * (partial) nibble, which is dealt with by the next
+        * statement.  We also tack on the implicit normalization bit.
+        */
+       *s = u.extu_ext.ext_frach | (1U << ((LDBL_MANT_DIG - 1) % 4));
+
+       /* If ndigits < 0, we are expected to auto-size the precision. */
+       if (ndigits < 0) {
+               for (ndigits = sigfigs; s0[ndigits - 1] == 0; ndigits--)
+                       continue;
+       }
+
+       if (sigfigs > ndigits && s0[ndigits] != 0)
+               dorounding(s0, ndigits, u.extu_ext.ext_sign, decpt);
+
+       s = s0 + ndigits;
+       if (rve != NULL)
+               *rve = s;
+       *s-- = '\0';
+       for (; s >= s0; s--)
+               *s = xdigs[(unsigned int)*s];
+
+       return (s0);
+}
+
+#else  /* (LDBL_MANT_DIG == DBL_MANT_DIG) */
+
+char *
+hldtoa(long double e, const char *xdigs, int ndigits, int *decpt, int *sign,
+    char **rve)
+{
+
+       return (hdtoa((double)e, xdigs, ndigits, decpt, sign, rve));
+}
+
+#endif /* (LDBL_MANT_DIG == DBL_MANT_DIG) */
diff --git a/lib/nbsd_libc/gdtoa/hexnan.c b/lib/nbsd_libc/gdtoa/hexnan.c
new file mode 100644 (file)
index 0000000..405328a
--- /dev/null
@@ -0,0 +1,133 @@
+/* $NetBSD: hexnan.c,v 1.3 2006/03/11 18:38:14 kleink Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ static void
+#ifdef KR_headers
+L_shift(x, x1, i) ULong *x; ULong *x1; int i;
+#else
+L_shift(ULong *x, ULong *x1, int i)
+#endif
+{
+       int j;
+
+       i = 8 - i;
+       i <<= 2;
+       j = ULbits - i;
+       do {
+               *x |= x[1] << j;
+               x[1] >>= i;
+               } while(++x < x1);
+       }
+
+ int
+#ifdef KR_headers
+hexnan(sp, fpi, x0)
+       CONST char **sp; CONST FPI *fpi; ULong *x0;
+#else
+hexnan( CONST char **sp, CONST FPI *fpi, ULong *x0)
+#endif
+{
+       ULong c, h, *x, *x1, *xe;
+       CONST char *s;
+       int havedig, hd0, i, nbits;
+
+       if (!hexdig['0'])
+               hexdig_init_D2A();
+       nbits = fpi->nbits;
+       x = x0 + ((unsigned int)nbits >> kshift);
+       if (nbits & kmask)
+               x++;
+       *--x = 0;
+       x1 = xe = x;
+       havedig = hd0 = i = 0;
+       s = *sp;
+       while((c = *(CONST unsigned char*)++s) != 0) {
+               if (!(h = hexdig[c])) {
+                       if (c <= ' ') {
+                               if (hd0 < havedig) {
+                                       if (x < x1 && i < 8)
+                                               L_shift(x, x1, i);
+                                       if (x <= x0) {
+                                               i = 8;
+                                               continue;
+                                               }
+                                       hd0 = havedig;
+                                       *--x = 0;
+                                       x1 = x;
+                                       i = 0;
+                                       }
+                               continue;
+                               }
+                       if (/*(*/ c == ')' && havedig) {
+                               *sp = s + 1;
+                               break;
+                               }
+                       return STRTOG_NaN;
+                       }
+               havedig++;
+               if (++i > 8) {
+                       if (x <= x0)
+                               continue;
+                       i = 1;
+                       *--x = 0;
+                       }
+               *x = (*x << 4) | (h & 0xf);
+               }
+       if (!havedig)
+               return STRTOG_NaN;
+       if (x < x1 && i < 8)
+               L_shift(x, x1, i);
+       if (x > x0) {
+               x1 = x0;
+               do *x1++ = *x++;
+                       while(x <= xe);
+               do *x1++ = 0;
+                       while(x1 <= xe);
+               }
+       else {
+               /* truncate high-order word if necessary */
+               if ( (i = nbits & (ULbits-1)) !=0)
+                       *xe &= ((ULong)0xffffffff) >> (ULbits - i);
+               }
+       for(x1 = xe;; --x1) {
+               if (*x1 != 0)
+                       break;
+               if (x1 == x0) {
+                       *x1 = 1;
+                       break;
+                       }
+               }
+       return STRTOG_NaNbits;
+       }
diff --git a/lib/nbsd_libc/gdtoa/ldtoa.c b/lib/nbsd_libc/gdtoa/ldtoa.c
new file mode 100644 (file)
index 0000000..de02602
--- /dev/null
@@ -0,0 +1,111 @@
+/*     $NetBSD: ldtoa.c,v 1.4 2007/02/23 17:45:59 christos Exp $       */
+
+/*-
+ * Copyright (c) 2003 David Schultz <das@FreeBSD.ORG>
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/gdtoa/_ldtoa.c,v 1.2 2004/01/18 07:53:49 das Exp $");
+#else
+__RCSID("$NetBSD: ldtoa.c,v 1.4 2007/02/23 17:45:59 christos Exp $");
+#endif
+
+#include <float.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <math.h>
+#include <stdlib.h>
+#ifndef __vax__
+#include <machine/ieee.h>
+#endif
+#include "gdtoaimp.h"
+
+/*
+ * ldtoa() is a wrapper for gdtoa() that makes it smell like dtoa(),
+ * except that the floating point argument is passed by reference.
+ * When dtoa() is passed a NaN or infinity, it sets expt to 9999.
+ * However, a long double could have a valid exponent of 9999, so we
+ * use INT_MAX in ldtoa() instead.
+ */
+char *
+ldtoa(long double *ld, int mode, int ndigits, int *decpt, int *sign, char **rve)
+{
+#ifdef EXT_EXPBITS
+       static FPI fpi = {
+               LDBL_MANT_DIG,                  /* nbits */
+               LDBL_MIN_EXP - LDBL_MANT_DIG,   /* emin */
+               LDBL_MAX_EXP - LDBL_MANT_DIG,   /* emax */
+               FPI_Round_near,                 /* rounding */
+#ifdef Sudden_Underflow        /* unused, but correct anyway */
+               1
+#else
+               0
+#endif
+       };
+       int be, kind;
+       char *ret;
+       union ieee_ext_u u;
+       uint32_t bits[(LDBL_MANT_DIG + 31) / 32];
+
+       u.extu_ld = *ld;
+       *sign = u.extu_ext.ext_sign;
+       be = u.extu_ext.ext_exp - (LDBL_MAX_EXP - 1) - (LDBL_MANT_DIG - 1);
+       EXT_TO_ARRAY32(u, bits);
+
+       switch (fpclassify(u.extu_ld)) {
+       case FP_NORMAL:
+               kind = STRTOG_Normal;
+#ifdef LDBL_IMPLICIT_NBIT
+               bits[LDBL_MANT_DIG / 32] |= 1 << ((LDBL_MANT_DIG - 1) % 32);
+#endif /* LDBL_IMPLICIT_NBIT */
+               break;
+       case FP_ZERO:
+               kind = STRTOG_Zero;
+               break;
+       case FP_SUBNORMAL:
+               kind = STRTOG_Denormal;
+#ifdef LDBL_IMPLICIT_NBIT
+               be++;
+#endif
+               break;
+       case FP_INFINITE:
+               kind = STRTOG_Infinite;
+               break;
+       case FP_NAN:
+               kind = STRTOG_NaN;
+               break;
+       default:
+               abort();
+       }
+
+       ret = gdtoa(&fpi, be, (ULong *)bits, &kind, mode, ndigits, decpt, rve);
+       if (*decpt == -32768)
+               *decpt = INT_MAX;
+       return ret;
+#else
+       return dtoa((double)*ld, mode, ndigits, decpt, sign, rve);
+#endif
+}
diff --git a/lib/nbsd_libc/gdtoa/makefile b/lib/nbsd_libc/gdtoa/makefile
new file mode 100644 (file)
index 0000000..ff33a3d
--- /dev/null
@@ -0,0 +1,76 @@
+# $NetBSD: makefile,v 1.3 2006/01/25 16:40:57 kleink Exp $
+
+# /****************************************************************
+# Copyright (C) 1998 by Lucent Technologies
+# All Rights Reserved
+#
+# Permission to use, copy, modify, and distribute this software and
+# its documentation for any purpose and without fee is hereby
+# granted, provided that the above copyright notice appear in all
+# copies and that both that the copyright notice and this
+# permission notice and warranty disclaimer appear in supporting
+# documentation, and that the name of Lucent or any of its entities
+# not be used in advertising or publicity pertaining to
+# distribution of the software without specific, written prior
+# permission.
+#
+# LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+# IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+# SPECIAL, 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.
+#
+# ****************************************************************/
+
+.SUFFIXES: .c .o
+CC = cc
+CFLAGS = -g -DINFNAN_CHECK
+
+.c.o:
+       $(CC) -c $(CFLAGS) $*.c
+
+all: arith.h gd_qnan.h gdtoa.a
+
+arith.h: arithchk.c
+       $(CC) $(CFLAGS) arithchk.c || $(CC) -DNO_LONG_LONG $(CFLAGS) arithchk.c
+       ./a.out >arith.h
+       rm -f a.out arithchk.o
+
+gd_qnan.h: arith.h qnan.c
+       $(CC) $(CFLAGS) qnan.c
+       ./a.out >gd_qnan.h
+       rm -f a.out qnan.o
+
+gdtoa.a: dmisc.c dtoa.c g_Qfmt.c g__fmt.c g_ddfmt.c g_dfmt.c g_ffmt.c\
+        g_xLfmt.c g_xfmt.c gdtoa.c gethex.c gmisc.c hd_init.c hexnan.c\
+        misc.c smisc.c strtoIQ.c strtoId.c strtoIdd.c strtoIf.c strtoIg.c\
+        strtoIx.c strtoIxL.c strtod.c strtodI.c strtodg.c strtof.c strtopQ.c\
+        strtopd.c strtopdd.c strtopf.c strtopx.c strtopxL.c strtorQ.c\
+        strtord.c strtordd.c strtorf.c strtorx.c strtorxL.c sum.c ulp.c
+       $(CC) -c $(CFLAGS) $?
+       x=`echo $? | sed 's/\.c/.o/g'` && ar ruv gdtoa.a $$x && rm $$x
+       ranlib gdtoa.a || true
+
+# If your system lacks ranlib, you do not need it.
+
+xs0 = README arithchk.c dmisc.c dtoa.c g_Qfmt.c g__fmt.c g_ddfmt.c g_dfmt.c\
+        g_ffmt.c g_xLfmt.c g_xfmt.c gdtoa.c gdtoa.h gdtoaimp.h gethex.c\
+        gmisc.c hd_init.c hexnan.c makefile misc.c qnan.c smisc.c strtoIQ.c\
+        strtoId.c strtoIdd.c strtoIf.c strtoIg.c strtoIx.c strtoIxL.c\
+        strtod.c strtodI.c strtodg.c strtodnrp.c strtof.c strtopQ.c strtopd.c\
+        strtopdd.c strtopf.c strtopx.c strtopxL.c strtorQ.c strtord.c strtordd.c\
+        strtorf.c strtorx.c strtorxL.c sum.c ulp.c
+
+# "make xsum.out" to check for transmission errors; source for xsum is
+# netlib's "xsum.c from f2c", e.g.,
+# ftp://netlib.bell-labs.com/netlib/f2c/xsum.c.gz
+
+xsum.out: xsum0.out $(xs0)
+       xsum $(xs0) >xsum1.out
+       cmp xsum0.out xsum1.out && mv xsum1.out xsum.out || diff xsum[01].out
+
+clean:
+       rm -f arith.h gd_qnan.h *.[ao] xsum.out xsum1.out
diff --git a/lib/nbsd_libc/gdtoa/misc.c b/lib/nbsd_libc/gdtoa/misc.c
new file mode 100644 (file)
index 0000000..8ae13cc
--- /dev/null
@@ -0,0 +1,903 @@
+/* $NetBSD: misc.c,v 1.5 2009/01/30 23:35:35 lukem Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 1999 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ static Bigint *freelist[Kmax+1];
+#ifndef Omit_Private_Memory
+#ifndef PRIVATE_MEM
+#define PRIVATE_MEM 2304
+#endif
+#define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
+static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
+#endif
+
+ Bigint *
+Balloc
+#ifdef KR_headers
+       (k) int k;
+#else
+       (int k)
+#endif
+{
+       int x;
+       Bigint *rv;
+#ifndef Omit_Private_Memory
+       unsigned int len;
+#endif
+
+       ACQUIRE_DTOA_LOCK(0);
+       if ( (rv = freelist[k]) !=0) {
+               freelist[k] = rv->next;
+               }
+       else {
+               x = 1 << k;
+#ifdef Omit_Private_Memory
+               rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
+#else
+               len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
+                       /sizeof(double);
+               if ((double *)(pmem_next - private_mem + len) <= (double *)PRIVATE_mem) {
+                       rv = (Bigint*)(void *)pmem_next;
+                       pmem_next += len;
+                       }
+               else
+                       rv = (Bigint*)MALLOC(len*sizeof(double));
+#endif
+               if (rv == NULL)
+                       return NULL;
+               rv->k = k;
+               rv->maxwds = x;
+               }
+       FREE_DTOA_LOCK(0);
+       rv->sign = rv->wds = 0;
+       return rv;
+       }
+
+ void
+Bfree
+#ifdef KR_headers
+       (v) Bigint *v;
+#else
+       (Bigint *v)
+#endif
+{
+       if (v) {
+               ACQUIRE_DTOA_LOCK(0);
+               v->next = freelist[v->k];
+               freelist[v->k] = v;
+               FREE_DTOA_LOCK(0);
+               }
+       }
+
+ int
+lo0bits
+#ifdef KR_headers
+       (y) ULong *y;
+#else
+       (ULong *y)
+#endif
+{
+       int k;
+       ULong x = *y;
+
+       if (x & 7) {
+               if (x & 1)
+                       return 0;
+               if (x & 2) {
+                       *y = x >> 1;
+                       return 1;
+                       }
+               *y = x >> 2;
+               return 2;
+               }
+       k = 0;
+       if (!(x & 0xffff)) {
+               k = 16;
+               x >>= 16;
+               }
+       if (!(x & 0xff)) {
+               k += 8;
+               x >>= 8;
+               }
+       if (!(x & 0xf)) {
+               k += 4;
+               x >>= 4;
+               }
+       if (!(x & 0x3)) {
+               k += 2;
+               x >>= 2;
+               }
+       if (!(x & 1)) {
+               k++;
+               x >>= 1;
+               if (!x)
+                       return 32;
+               }
+       *y = x;
+       return k;
+       }
+
+ Bigint *
+multadd
+#ifdef KR_headers
+       (b, m, a) Bigint *b; int m, a;
+#else
+       (Bigint *b, int m, int a)       /* multiply by m and add a */
+#endif
+{
+       int i, wds;
+#ifdef ULLong
+       ULong *x;
+       ULLong carry, y;
+#else
+       ULong carry, *x, y;
+#ifdef Pack_32
+       ULong xi, z;
+#endif
+#endif
+       Bigint *b1;
+
+       wds = b->wds;
+       x = b->x;
+       i = 0;
+       carry = a;
+       do {
+#ifdef ULLong
+               y = *x * (ULLong)m + carry;
+               carry = y >> 32;
+               /* LINTED conversion */
+               *x++ = y & 0xffffffffUL;
+#else
+#ifdef Pack_32
+               xi = *x;
+               y = (xi & 0xffff) * m + carry;
+               z = (xi >> 16) * m + (y >> 16);
+               carry = z >> 16;
+               *x++ = (z << 16) + (y & 0xffff);
+#else
+               y = *x * m + carry;
+               carry = y >> 16;
+               *x++ = y & 0xffff;
+#endif
+#endif
+               }
+               while(++i < wds);
+       if (carry) {
+               if (wds >= b->maxwds) {
+                       b1 = Balloc(b->k+1);
+                       if (b1 == NULL) {
+                               Bfree(b);
+                               return NULL;
+                               }
+                       Bcopy(b1, b);
+                       Bfree(b);
+                       b = b1;
+                       }
+               /* LINTED conversion */
+               b->x[wds++] = carry;
+               b->wds = wds;
+               }
+       return b;
+       }
+
+ int
+hi0bits_D2A
+#ifdef KR_headers
+       (x) ULong x;
+#else
+       (ULong x)
+#endif
+{
+       int k = 0;
+
+       if (!(x & 0xffff0000)) {
+               k = 16;
+               x <<= 16;
+               }
+       if (!(x & 0xff000000)) {
+               k += 8;
+               x <<= 8;
+               }
+       if (!(x & 0xf0000000)) {
+               k += 4;
+               x <<= 4;
+               }
+       if (!(x & 0xc0000000)) {
+               k += 2;
+               x <<= 2;
+               }
+       if (!(x & 0x80000000)) {
+               k++;
+               if (!(x & 0x40000000))
+                       return 32;
+               }
+       return k;
+       }
+
+ Bigint *
+i2b
+#ifdef KR_headers
+       (i) int i;
+#else
+       (int i)
+#endif
+{
+       Bigint *b;
+
+       b = Balloc(1);
+       if (b == NULL)
+               return NULL;
+       b->x[0] = i;
+       b->wds = 1;
+       return b;
+       }
+
+ Bigint *
+mult
+#ifdef KR_headers
+       (a, b) Bigint *a, *b;
+#else
+       (Bigint *a, Bigint *b)
+#endif
+{
+       Bigint *c;
+       int k, wa, wb, wc;
+       ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
+       ULong y;
+#ifdef ULLong
+       ULLong carry, z;
+#else
+       ULong carry, z;
+#ifdef Pack_32
+       ULong z2;
+#endif
+#endif
+
+       if (a->wds < b->wds) {
+               c = a;
+               a = b;
+               b = c;
+               }
+       k = a->k;
+       wa = a->wds;
+       wb = b->wds;
+       wc = wa + wb;
+       if (wc > a->maxwds)
+               k++;
+       c = Balloc(k);
+       if (c == NULL)
+               return NULL;
+       for(x = c->x, xa = x + wc; x < xa; x++)
+               *x = 0;
+       xa = a->x;
+       xae = xa + wa;
+       xb = b->x;
+       xbe = xb + wb;
+       xc0 = c->x;
+#ifdef ULLong
+       for(; xb < xbe; xc0++) {
+               if ( (y = *xb++) !=0) {
+                       x = xa;
+                       xc = xc0;
+                       carry = 0;
+                       do {
+                               z = *x++ * (ULLong)y + *xc + carry;
+                               carry = z >> 32;
+                               /* LINTED conversion */
+                               *xc++ = z & 0xffffffffUL;
+                               }
+                               while(x < xae);
+                       /* LINTED conversion */
+                       *xc = carry;
+                       }
+               }
+#else
+#ifdef Pack_32
+       for(; xb < xbe; xb++, xc0++) {
+               if ( (y = *xb & 0xffff) !=0) {
+                       x = xa;
+                       xc = xc0;
+                       carry = 0;
+                       do {
+                               z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
+                               carry = z >> 16;
+                               z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
+                               carry = z2 >> 16;
+                               Storeinc(xc, z2, z);
+                               }
+                               while(x < xae);
+                       *xc = carry;
+                       }
+               if ( (y = *xb >> 16) !=0) {
+                       x = xa;
+                       xc = xc0;
+                       carry = 0;
+                       z2 = *xc;
+                       do {
+                               z = (*x & 0xffff) * y + (*xc >> 16) + carry;
+                               carry = z >> 16;
+                               Storeinc(xc, z, z2);
+                               z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
+                               carry = z2 >> 16;
+                               }
+                               while(x < xae);
+                       *xc = z2;
+                       }
+               }
+#else
+       for(; xb < xbe; xc0++) {
+               if ( (y = *xb++) !=0) {
+                       x = xa;
+                       xc = xc0;
+                       carry = 0;
+                       do {
+                               z = *x++ * y + *xc + carry;
+                               carry = z >> 16;
+                               *xc++ = z & 0xffff;
+                               }
+                               while(x < xae);
+                       *xc = carry;
+                       }
+               }
+#endif
+#endif
+       for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
+       c->wds = wc;
+       return c;
+       }
+
+ static Bigint *p5s;
+
+ Bigint *
+pow5mult
+#ifdef KR_headers
+       (b, k) Bigint *b; int k;
+#else
+       (Bigint *b, int k)
+#endif
+{
+       Bigint *b1, *p5, *p51;
+       int i;
+       static CONST int p05[3] = { 5, 25, 125 };
+
+       if ( (i = k & 3) !=0) {
+               b = multadd(b, p05[i-1], 0);
+               if (b == NULL)
+                       return NULL;
+               }
+
+       if (!(k = (unsigned int)k >> 2))
+               return b;
+       if ((p5 = p5s) == 0) {
+               /* first time */
+#ifdef MULTIPLE_THREADS
+               ACQUIRE_DTOA_LOCK(1);
+               if (!(p5 = p5s)) {
+                       p5 = p5s = i2b(625);
+                       if (p5 == NULL)
+                               return NULL;
+                       p5->next = 0;
+                       }
+               FREE_DTOA_LOCK(1);
+#else
+               p5 = p5s = i2b(625);
+               if (p5 == NULL)
+                       return NULL;
+               p5->next = 0;
+#endif
+               }
+       for(;;) {
+               if (k & 1) {
+                       b1 = mult(b, p5);
+                       if (b1 == NULL)
+                               return NULL;
+                       b = b1;
+                       }
+               if (!(k = (unsigned int)k >> 1))
+                       break;
+               if ((p51 = p5->next) == 0) {
+#ifdef MULTIPLE_THREADS
+                       ACQUIRE_DTOA_LOCK(1);
+                       if (!(p51 = p5->next)) {
+                               p51 = p5->next = mult(p5,p5);
+                               if (p51 == NULL)
+                                       return NULL;
+                               p51->next = 0;
+                               }
+                       FREE_DTOA_LOCK(1);
+#else
+                       p51 = p5->next = mult(p5,p5);
+                       if (p51 == NULL)
+                               return NULL;
+                       p51->next = 0;
+#endif
+                       }
+               p5 = p51;
+               }
+       return b;
+       }
+
+ Bigint *
+lshift
+#ifdef KR_headers
+       (b, k) Bigint *b; int k;
+#else
+       (Bigint *b, int k)
+#endif
+{
+       int i, k1, n, n1;
+       Bigint *b1;
+       ULong *x, *x1, *xe, z;
+
+       n = (unsigned int)k >> kshift;
+       k1 = b->k;
+       n1 = n + b->wds + 1;
+       for(i = b->maxwds; n1 > i; i <<= 1)
+               k1++;
+       b1 = Balloc(k1);
+       if (b1 == NULL)
+               return NULL;
+       x1 = b1->x;
+       for(i = 0; i < n; i++)
+               *x1++ = 0;
+       x = b->x;
+       xe = x + b->wds;
+       if (k &= kmask) {
+#ifdef Pack_32
+               k1 = 32 - k;
+               z = 0;
+               do {
+                       *x1++ = *x << k | z;
+                       z = *x++ >> k1;
+                       }
+                       while(x < xe);
+               if ((*x1 = z) !=0)
+                       ++n1;
+#else
+               k1 = 16 - k;
+               z = 0;
+               do {
+                       *x1++ = *x << k  & 0xffff | z;
+                       z = *x++ >> k1;
+                       }
+                       while(x < xe);
+               if (*x1 = z)
+                       ++n1;
+#endif
+               }
+       else do
+               *x1++ = *x++;
+               while(x < xe);
+       b1->wds = n1 - 1;
+       Bfree(b);
+       return b1;
+       }
+
+ int
+cmp
+#ifdef KR_headers
+       (a, b) Bigint *a, *b;
+#else
+       (Bigint *a, Bigint *b)
+#endif
+{
+       ULong *xa, *xa0, *xb, *xb0;
+       int i, j;
+
+       i = a->wds;
+       j = b->wds;
+#ifdef DEBUG
+       if (i > 1 && !a->x[i-1])
+               Bug("cmp called with a->x[a->wds-1] == 0");
+       if (j > 1 && !b->x[j-1])
+               Bug("cmp called with b->x[b->wds-1] == 0");
+#endif
+       if (i -= j)
+               return i;
+       xa0 = a->x;
+       xa = xa0 + j;
+       xb0 = b->x;
+       xb = xb0 + j;
+       for(;;) {
+               if (*--xa != *--xb)
+                       return *xa < *xb ? -1 : 1;
+               if (xa <= xa0)
+                       break;
+               }
+       return 0;
+       }
+
+ Bigint *
+diff
+#ifdef KR_headers
+       (a, b) Bigint *a, *b;
+#else
+       (Bigint *a, Bigint *b)
+#endif
+{
+       Bigint *c;
+       int i, wa, wb;
+       ULong *xa, *xae, *xb, *xbe, *xc;
+#ifdef ULLong
+       ULLong borrow, y;
+#else
+       ULong borrow, y;
+#ifdef Pack_32
+       ULong z;
+#endif
+#endif
+
+       i = cmp(a,b);
+       if (!i) {
+               c = Balloc(0);
+               if (c == NULL)
+                       return NULL;
+               c->wds = 1;
+               c->x[0] = 0;
+               return c;
+               }
+       if (i < 0) {
+               c = a;
+               a = b;
+               b = c;
+               i = 1;
+               }
+       else
+               i = 0;
+       c = Balloc(a->k);
+       if (c == NULL)
+               return NULL;
+       c->sign = i;
+       wa = a->wds;
+       xa = a->x;
+       xae = xa + wa;
+       wb = b->wds;
+       xb = b->x;
+       xbe = xb + wb;
+       xc = c->x;
+       borrow = 0;
+#ifdef ULLong
+       do {
+               y = (ULLong)*xa++ - *xb++ - borrow;
+               borrow = y >> 32 & 1UL;
+               /* LINTED conversion */
+               *xc++ = y & 0xffffffffUL;
+               }
+               while(xb < xbe);
+       while(xa < xae) {
+               y = *xa++ - borrow;
+               borrow = y >> 32 & 1UL;
+               /* LINTED conversion */
+               *xc++ = y & 0xffffffffUL;
+               }
+#else
+#ifdef Pack_32
+       do {
+               y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
+               borrow = (y & 0x10000) >> 16;
+               z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
+               borrow = (z & 0x10000) >> 16;
+               Storeinc(xc, z, y);
+               }
+               while(xb < xbe);
+       while(xa < xae) {
+               y = (*xa & 0xffff) - borrow;
+               borrow = (y & 0x10000) >> 16;
+               z = (*xa++ >> 16) - borrow;
+               borrow = (z & 0x10000) >> 16;
+               Storeinc(xc, z, y);
+               }
+#else
+       do {
+               y = *xa++ - *xb++ - borrow;
+               borrow = (y & 0x10000) >> 16;
+               *xc++ = y & 0xffff;
+               }
+               while(xb < xbe);
+       while(xa < xae) {
+               y = *xa++ - borrow;
+               borrow = (y & 0x10000) >> 16;
+               *xc++ = y & 0xffff;
+               }
+#endif
+#endif
+       while(!*--xc)
+               wa--;
+       c->wds = wa;
+       return c;
+       }
+
+ double
+b2d
+#ifdef KR_headers
+       (a, e) Bigint *a; int *e;
+#else
+       (Bigint *a, int *e)
+#endif
+{
+       ULong *xa, *xa0, w, y, z;
+       int k;
+       double d;
+#ifdef VAX
+       ULong d0, d1;
+#else
+#define d0 word0(d)
+#define d1 word1(d)
+#endif
+
+       xa0 = a->x;
+       xa = xa0 + a->wds;
+       y = *--xa;
+#ifdef DEBUG
+       if (!y) Bug("zero y in b2d");
+#endif
+       k = hi0bits(y);
+       *e = 32 - k;
+#ifdef Pack_32
+       if (k < Ebits) {
+               d0 = Exp_1 | y >> (Ebits - k);
+               w = xa > xa0 ? *--xa : 0;
+               d1 = y << ((32-Ebits) + k) | w >> (Ebits - k);
+               goto ret_d;
+               }
+       z = xa > xa0 ? *--xa : 0;
+       if (k -= Ebits) {
+               d0 = Exp_1 | y << k | z >> (32 - k);
+               y = xa > xa0 ? *--xa : 0;
+               d1 = z << k | y >> (32 - k);
+               }
+       else {
+               d0 = Exp_1 | y;
+               d1 = z;
+               }
+#else
+       if (k < Ebits + 16) {
+               z = xa > xa0 ? *--xa : 0;
+               d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
+               w = xa > xa0 ? *--xa : 0;
+               y = xa > xa0 ? *--xa : 0;
+               d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
+               goto ret_d;
+               }
+       z = xa > xa0 ? *--xa : 0;
+       w = xa > xa0 ? *--xa : 0;
+       k -= Ebits + 16;
+       d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
+       y = xa > xa0 ? *--xa : 0;
+       d1 = w << k + 16 | y << k;
+#endif
+ ret_d:
+#ifdef VAX
+       word0(d) = d0 >> 16 | d0 << 16;
+       word1(d) = d1 >> 16 | d1 << 16;
+#endif
+       return dval(d);
+       }
+#undef d0
+#undef d1
+
+ Bigint *
+d2b
+#ifdef KR_headers
+       (d, e, bits) double d; int *e, *bits;
+#else
+       (double d, int *e, int *bits)
+#endif
+{
+       Bigint *b;
+#ifndef Sudden_Underflow
+       int i;
+#endif
+       int de, k;
+       ULong *x, y, z;
+#ifdef VAX
+       ULong d0, d1;
+       d0 = word0(d) >> 16 | word0(d) << 16;
+       d1 = word1(d) >> 16 | word1(d) << 16;
+#else
+#define d0 word0(d)
+#define d1 word1(d)
+#endif
+
+#ifdef Pack_32
+       b = Balloc(1);
+#else
+       b = Balloc(2);
+#endif
+       if (b == NULL)
+               return NULL;
+       x = b->x;
+
+       z = d0 & Frac_mask;
+       d0 &= 0x7fffffff;       /* clear sign bit, which we ignore */
+#ifdef Sudden_Underflow
+       de = (int)(d0 >> Exp_shift);
+#ifndef IBM
+       z |= Exp_msk11;
+#endif
+#else
+       if ( (de = (int)(d0 >> Exp_shift)) !=0)
+               z |= Exp_msk1;
+#endif
+#ifdef Pack_32
+       if ( (y = d1) !=0) {
+               if ( (k = lo0bits(&y)) !=0) {
+                       x[0] = y | z << (32 - k);
+                       z >>= k;
+                       }
+               else
+                       x[0] = y;
+#ifndef Sudden_Underflow
+               i =
+#endif
+                    b->wds = (x[1] = z) !=0 ? 2 : 1;
+               }
+       else {
+#ifdef DEBUG
+               if (!z)
+                       Bug("Zero passed to d2b");
+#endif
+               k = lo0bits(&z);
+               x[0] = z;
+#ifndef Sudden_Underflow
+               i =
+#endif
+                   b->wds = 1;
+               k += 32;
+               }
+#else
+       if ( (y = d1) !=0) {
+               if ( (k = lo0bits(&y)) !=0)
+                       if (k >= 16) {
+                               x[0] = y | z << 32 - k & 0xffff;
+                               x[1] = z >> k - 16 & 0xffff;
+                               x[2] = z >> k;
+                               i = 2;
+                               }
+                       else {
+                               x[0] = y & 0xffff;
+                               x[1] = y >> 16 | z << 16 - k & 0xffff;
+                               x[2] = z >> k & 0xffff;
+                               x[3] = z >> k+16;
+                               i = 3;
+                               }
+               else {
+                       x[0] = y & 0xffff;
+                       x[1] = y >> 16;
+                       x[2] = z & 0xffff;
+                       x[3] = z >> 16;
+                       i = 3;
+                       }
+               }
+       else {
+#ifdef DEBUG
+               if (!z)
+                       Bug("Zero passed to d2b");
+#endif
+               k = lo0bits(&z);
+               if (k >= 16) {
+                       x[0] = z;
+                       i = 0;
+                       }
+               else {
+                       x[0] = z & 0xffff;
+                       x[1] = z >> 16;
+                       i = 1;
+                       }
+               k += 32;
+               }
+       while(!x[i])
+               --i;
+       b->wds = i + 1;
+#endif
+#ifndef Sudden_Underflow
+       if (de) {
+#endif
+#ifdef IBM
+               *e = (de - Bias - (P-1) << 2) + k;
+               *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
+#else
+               *e = de - Bias - (P-1) + k;
+               *bits = P - k;
+#endif
+#ifndef Sudden_Underflow
+               }
+       else {
+               *e = de - Bias - (P-1) + 1 + k;
+#ifdef Pack_32
+               *bits = 32*i - hi0bits(x[i-1]);
+#else
+               *bits = (i+2)*16 - hi0bits(x[i]);
+#endif
+               }
+#endif
+       return b;
+       }
+#undef d0
+#undef d1
+
+ CONST double
+#ifdef IEEE_Arith
+bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
+CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128, 1e-256
+               };
+#else
+#ifdef IBM
+bigtens[] = { 1e16, 1e32, 1e64 };
+CONST double tinytens[] = { 1e-16, 1e-32, 1e-64 };
+#else
+bigtens[] = { 1e16, 1e32 };
+CONST double tinytens[] = { 1e-16, 1e-32 };
+#endif
+#endif
+
+ CONST double
+tens[] = {
+               1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
+               1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
+               1e20, 1e21, 1e22
+#ifdef VAX
+               , 1e23, 1e24
+#endif
+               };
+
+ char *
+#ifdef KR_headers
+strcp_D2A(a, b) char *a; char *b;
+#else
+strcp_D2A(char *a, CONST char *b)
+#endif
+{
+       while((*a = *b++))
+               a++;
+       return a;
+       }
+
+#ifdef NO_STRING_H
+
+ Char *
+#ifdef KR_headers
+memcpy_D2A(a, b, len) Char *a; Char *b; size_t len;
+#else
+memcpy_D2A(void *a1, void *b1, size_t len)
+#endif
+{
+       char *a = (char*)a1, *ae = a + len;
+       char *b = (char*)b1, *a0 = a;
+       while(a < ae)
+               *a++ = *b++;
+       return a0;
+       }
+
+#endif /* NO_STRING_H */
diff --git a/lib/nbsd_libc/gdtoa/qnan.c b/lib/nbsd_libc/gdtoa/qnan.c
new file mode 100644 (file)
index 0000000..2e5ce89
--- /dev/null
@@ -0,0 +1,112 @@
+/* $NetBSD: qnan.c,v 1.2 2006/01/25 15:27:42 kleink Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 2005 by David M. Gay
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appear in all copies and that
+both that the copyright notice and this permission notice and warranty
+disclaimer appear in supporting documentation, and that the name of
+the author or any of his current or former employers not be used in
+advertising or publicity pertaining to distribution of the software
+without specific, written prior permission.
+
+THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.  IN
+NO EVENT SHALL THE AUTHOR OR ANY OF HIS CURRENT OR FORMER EMPLOYERS BE
+LIABLE FOR ANY SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+/* Program to compute quiet NaNs of various precisions (float, */
+/* double, and perhaps long double) on the current system,     */
+/* provided the system uses binary IEEE (P754) arithmetic.     */
+/* Note that one system's quiet NaN may be a signaling NaN on  */
+/* another system.  The IEEE arithmetic standards (P754, P854) */
+/* do not specify how to distinguish signaling NaNs from quiet */
+/* ones, and this detail varies across systems.         The computed   */
+/* NaN values are encoded in #defines for values for an                */
+/* unsigned 32-bit integer type, called Ulong below, and       */
+/* (for long double) perhaps as unsigned short values.  Once   */
+/* upon a time, there were PC compilers for Intel CPUs that    */
+/* had sizeof(long double) = 10.  Are such compilers still     */
+/* distributed?                                                        */
+
+#include <stdio.h>
+#include "arith.h"
+
+#ifndef Long
+#define Long long
+#endif
+
+typedef unsigned Long Ulong;
+
+#undef HAVE_IEEE
+#ifdef IEEE_LITTLE_ENDIAN
+#define _0 1
+#define _1 0
+#define HAVE_IEEE
+#endif
+#ifdef IEEE_BIG_ENDIAN
+#define _0 0
+#define _1 1
+#define HAVE_IEEE
+#endif
+
+#define UL (unsigned long)
+
+ int
+main(void)
+{
+#ifdef HAVE_IEEE
+       typedef union {
+               float f;
+               double d;
+               Ulong L[4];
+#ifndef NO_LONG_LONG
+               unsigned short u[5];
+               long double D;
+#endif
+               } U;
+       U a, b, c;
+       int i;
+
+       a.L[0] = b.L[0] = 0x7f800000;
+       c.f = a.f - b.f;
+       printf("#define f_QNAN 0x%lx\n", UL c.L[0]);
+       a.L[_0] = b.L[_0] = 0x7ff00000;
+       a.L[_1] = b.L[_1] = 0;
+       c.d = a.d - b.d;        /* quiet NaN */
+       printf("#define d_QNAN0 0x%lx\n", UL c.L[0]);
+       printf("#define d_QNAN1 0x%lx\n", UL c.L[1]);
+#ifdef NO_LONG_LONG
+       for(i = 0; i < 4; i++)
+               printf("#define ld_QNAN%d 0xffffffff\n", i);
+       for(i = 0; i < 5; i++)
+               printf("#define ldus_QNAN%d 0xffff\n", i);
+#else
+       b.D = c.D = a.d;
+       if (printf("") < 0)
+               c.D = 37;       /* never executed; just defeat optimization */
+       a.L[2] = a.L[3] = 0;
+       a.D = b.D - c.D;
+       for(i = 0; i < 4; i++)
+               printf("#define ld_QNAN%d 0x%lx\n", i, UL a.L[i]);
+       for(i = 0; i < 5; i++)
+               printf("#define ldus_QNAN%d 0x%x\n", i, a.u[i]);
+#endif
+#endif /* HAVE_IEEE */
+       return 0;
+       }
diff --git a/lib/nbsd_libc/gdtoa/smisc.c b/lib/nbsd_libc/gdtoa/smisc.c
new file mode 100644 (file)
index 0000000..349ff81
--- /dev/null
@@ -0,0 +1,203 @@
+/* $NetBSD: smisc.c,v 1.3 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 1999 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ Bigint *
+s2b
+#ifdef KR_headers
+       (s, nd0, nd, y9) CONST char *s; int nd0, nd; ULong y9;
+#else
+       (CONST char *s, int nd0, int nd, ULong y9)
+#endif
+{
+       Bigint *b;
+       int i, k;
+       Long x, y;
+
+       x = (nd + 8) / 9;
+       for(k = 0, y = 1; x > y; y <<= 1, k++) ;
+#ifdef Pack_32
+       b = Balloc(k);
+       if (b == NULL)
+               return NULL;
+       b->x[0] = y9;
+       b->wds = 1;
+#else
+       b = Balloc(k+1);
+       if (b == NULL)
+               return NULL;
+       b->x[0] = y9 & 0xffff;
+       b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
+#endif
+
+       i = 9;
+       if (9 < nd0) {
+               s += 9;
+               do  {
+                       b = multadd(b, 10, *s++ - '0');
+                       if (b == NULL)
+                               return NULL;
+                       } while(++i < nd0);
+               s++;
+               }
+       else
+               s += 10;
+       for(; i < nd; i++) {
+               b = multadd(b, 10, *s++ - '0');
+               if (b == NULL)
+                       return NULL;
+               }
+       return b;
+       }
+
+ double
+ratio
+#ifdef KR_headers
+       (a, b) Bigint *a, *b;
+#else
+       (Bigint *a, Bigint *b)
+#endif
+{
+       double da, db;
+       int k, ka, kb;
+
+       dval(da) = b2d(a, &ka);
+       dval(db) = b2d(b, &kb);
+       k = ka - kb + ULbits*(a->wds - b->wds);
+#ifdef IBM
+       if (k > 0) {
+               word0(da) += (k >> 2)*Exp_msk1;
+               if (k &= 3)
+                       dval(da) *= 1 << k;
+               }
+       else {
+               k = -k;
+               word0(db) += (k >> 2)*Exp_msk1;
+               if (k &= 3)
+                       dval(db) *= 1 << k;
+               }
+#else
+       if (k > 0)
+               word0(da) += k*Exp_msk1;
+       else {
+               k = -k;
+               word0(db) += k*Exp_msk1;
+               }
+#endif
+       return dval(da) / dval(db);
+       }
+
+#ifdef INFNAN_CHECK
+
+ int
+match
+#ifdef KR_headers
+       (sp, t) CONST char **sp, *t;
+#else
+       (CONST char **sp, CONST char *t)
+#endif
+{
+       int c, d;
+       CONST char *s = *sp;
+
+       while( (d = *t++) !=0) {
+               if ((c = *++s) >= 'A' && c <= 'Z')
+                       c += 'a' - 'A';
+               if (c != d)
+                       return 0;
+               }
+       *sp = s + 1;
+       return 1;
+       }
+#endif /* INFNAN_CHECK */
+
+ void
+#ifdef KR_headers
+copybits(c, n, b) ULong *c; int n; Bigint *b;
+#else
+copybits(ULong *c, int n, Bigint *b)
+#endif
+{
+       ULong *ce, *x, *xe;
+#ifdef Pack_16
+       int nw, nw1;
+#endif
+
+       ce = c + ((unsigned int)(n-1) >> kshift) + 1;
+       x = b->x;
+#ifdef Pack_32
+       xe = x + b->wds;
+       while(x < xe)
+               *c++ = *x++;
+#else
+       nw = b->wds;
+       nw1 = nw & 1;
+       for(xe = x + (nw - nw1); x < xe; x += 2)
+               Storeinc(c, x[1], x[0]);
+       if (nw1)
+               *c++ = *x;
+#endif
+       while(c < ce)
+               *c++ = 0;
+       }
+
+ ULong
+#ifdef KR_headers
+any_on(b, k) Bigint *b; int k;
+#else
+any_on(Bigint *b, int k)
+#endif
+{
+       int n, nwds;
+       ULong *x, *x0, x1, x2;
+
+       x = b->x;
+       nwds = b->wds;
+       n = (unsigned int)k >> kshift;
+       if (n > nwds)
+               n = nwds;
+       else if (n < nwds && (k &= kmask)) {
+               x1 = x2 = x[n];
+               x1 >>= k;
+               x1 <<= k;
+               if (x1 != x2)
+                       return 1;
+               }
+       x0 = x;
+       x += n;
+       while(x > x0)
+               if (*--x)
+                       return 1;
+       return 0;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtoIQ.c b/lib/nbsd_libc/gdtoa/strtoIQ.c
new file mode 100644 (file)
index 0000000..dfb5aaf
--- /dev/null
@@ -0,0 +1,69 @@
+/* $NetBSD: strtoIQ.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ int
+#ifdef KR_headers
+strtoIQ(s, sp, a, b) CONST char *s; char **sp; void *a; void *b;
+#else
+strtoIQ(CONST char *s, char **sp, void *a, void *b)
+#endif
+{
+       static FPI fpi = { 113, 1-16383-113+1, 32766-16383-113+1, 1, SI };
+       Long exp[2];
+       Bigint *B[2];
+       int k, rv[2];
+       ULong *L = (ULong *)a, *M = (ULong *)b;
+
+       B[0] = Balloc(2);
+       if (B[0] == NULL)
+               return STRTOG_NoMemory;
+       B[0]->wds = 4;
+       k = strtoIg(s, sp, &fpi, exp, B, rv);
+       if (k == STRTOG_NoMemory)
+               return k;
+       ULtoQ(L, B[0]->x, exp[0], rv[0]);
+       Bfree(B[0]);
+       if (B[1]) {
+               ULtoQ(M, B[1]->x, exp[1], rv[1]);
+               Bfree(B[1]);
+               }
+       else {
+               M[0] = L[0];
+               M[1] = L[1];
+               M[2] = L[2];
+               M[3] = L[3];
+               }
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtoId.c b/lib/nbsd_libc/gdtoa/strtoId.c
new file mode 100644 (file)
index 0000000..7cbfca2
--- /dev/null
@@ -0,0 +1,66 @@
+/* $NetBSD: strtoId.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ int
+#ifdef KR_headers
+strtoId(s, sp, f0, f1) CONST char *s; char **sp; double *f0, *f1;
+#else
+strtoId(CONST char *s, char **sp, double *f0, double *f1)
+#endif
+{
+       static FPI fpi = { 53, 1-1023-53+1, 2046-1023-53+1, 1, SI };
+       Long exp[2];
+       Bigint *B[2];
+       int k, rv[2];
+
+       B[0] = Balloc(1);
+       if (B[0] == NULL)
+               return STRTOG_NoMemory;
+       B[0]->wds = 2;
+       k = strtoIg(s, sp, &fpi, exp, B, rv);
+       if (k == STRTOG_NoMemory)
+               return k;
+       ULtod((ULong*)f0, B[0]->x, exp[0], rv[0]);
+       Bfree(B[0]);
+       if (B[1]) {
+               ULtod((ULong*)f1, B[1]->x, exp[1], rv[1]);
+               Bfree(B[1]);
+               }
+       else {
+               ((ULong*)f1)[0] = ((ULong*)f0)[0];
+               ((ULong*)f1)[1] = ((ULong*)f0)[1];
+               }
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtoIdd.c b/lib/nbsd_libc/gdtoa/strtoIdd.c
new file mode 100644 (file)
index 0000000..cf938ea
--- /dev/null
@@ -0,0 +1,72 @@
+/* $NetBSD: strtoIdd.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ int
+#ifdef KR_headers
+strtoIdd(s, sp, f0, f1) CONST char *s; char **sp; double *f0, *f1;
+#else
+strtoIdd(CONST char *s, char **sp, double *f0, double *f1)
+#endif
+{
+#ifdef Sudden_Underflow
+       static FPI fpi = { 106, 1-1023, 2046-1023-106+1, 1, 1 };
+#else
+       static FPI fpi = { 106, 1-1023-53+1, 2046-1023-106+1, 1, 0 };
+#endif
+       Long exp[2];
+       Bigint *B[2];
+       int k, rv[2];
+
+       B[0] = Balloc(2);
+       if (B[0] == NULL)
+               return STRTOG_NoMemory;
+       B[0]->wds = 4;
+       k = strtoIg(s, sp, &fpi, exp, B, rv);
+       if (k == STRTOG_NoMemory)
+               return k;
+       ULtodd((ULong*)f0, B[0]->x, exp[0], rv[0]);
+       Bfree(B[0]);
+       if (B[1]) {
+               ULtodd((ULong*)f1, B[1]->x, exp[1], rv[1]);
+               Bfree(B[1]);
+               }
+       else {
+               ((ULong*)f1)[0] = ((ULong*)f0)[0];
+               ((ULong*)f1)[1] = ((ULong*)f0)[1];
+               ((ULong*)f1)[2] = ((ULong*)f0)[2];
+               ((ULong*)f1)[3] = ((ULong*)f0)[3];
+               }
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtoIf.c b/lib/nbsd_libc/gdtoa/strtoIf.c
new file mode 100644 (file)
index 0000000..087acdc
--- /dev/null
@@ -0,0 +1,64 @@
+/* $NetBSD: strtoIf.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ int
+#ifdef KR_headers
+strtoIf(s, sp, f0, f1) CONST char *s; char **sp; float *f0, *f1;
+#else
+strtoIf(CONST char *s, char **sp, float *f0, float *f1)
+#endif
+{
+       static FPI fpi = { 24, 1-127-24+1,  254-127-24+1, 1, SI };
+       Long exp[2];
+       Bigint *B[2];
+       int k, rv[2];
+
+       B[0] = Balloc(0);
+       if (B[0] == NULL)
+               return STRTOG_NoMemory;
+       B[0]->wds = 1;
+       k = strtoIg(s, sp, &fpi, exp, B, rv);
+       if (k == STRTOG_NoMemory)
+               return k;
+       ULtof((ULong*)f0, B[0]->x, exp[0], rv[0]);
+       Bfree(B[0]);
+       if (B[1]) {
+               ULtof((ULong*)f1, B[1]->x, exp[1], rv[1]);
+               Bfree(B[1]);
+               }
+       else
+               *(ULong*)f1 = *(ULong*)f0;
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtoIg.c b/lib/nbsd_libc/gdtoa/strtoIg.c
new file mode 100644 (file)
index 0000000..20a4c1c
--- /dev/null
@@ -0,0 +1,139 @@
+/* $NetBSD: strtoIg.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ int
+#ifdef KR_headers
+strtoIg(s00, se, fpi, exp, B, rvp) CONST char *s00; char **se; FPI *fpi; Long *exp; Bigint **B; int *rvp;
+#else
+strtoIg(CONST char *s00, char **se, FPI *fpi, Long *exp, Bigint **B, int *rvp)
+#endif
+{
+       Bigint *b, *b1;
+       int i, nb, nw, nw1, rv, rv1, swap;
+       unsigned int nb1, nb11;
+       Long e1;
+
+       b = *B;
+       rv = strtodg(s00, se, fpi, exp, b->x);
+       if (rv == STRTOG_NoMemory)
+               return rv;
+       if (!(rv & STRTOG_Inexact)) {
+               B[1] = 0;
+               return *rvp = rv;
+               }
+       e1 = exp[0];
+       rv1 = rv ^ STRTOG_Inexact;
+       b1 = Balloc(b->k);
+       if (b1 == NULL)
+               return STRTOG_NoMemory;
+       Bcopy(b1, b);
+       nb = fpi->nbits;
+       nb1 = nb & 31;
+       nb11 = (nb1 - 1) & 31;
+       nw = b->wds;
+       nw1 = nw - 1;
+       if (rv & STRTOG_Inexlo) {
+               swap = 0;
+               b1 = increment(b1);
+               if (fpi->sudden_underflow
+                && (rv & STRTOG_Retmask) == STRTOG_Zero) {
+                       b1->x[0] = 0;
+                       b1->x[nw1] = 1L << nb11;
+                       rv1 += STRTOG_Normal - STRTOG_Zero;
+                       rv1 &= ~STRTOG_Underflow;
+                       goto swapcheck;
+                       }
+               if (b1->wds > nw
+                || nb1 && b1->x[nw1] & 1L << nb1) {
+                       if (++e1 > fpi->emax)
+                               rv1 = STRTOG_Infinite | STRTOG_Inexhi;
+                       rshift(b1, 1);
+                       }
+               else if ((rv & STRTOG_Retmask) == STRTOG_Denormal) {
+                       if (b1->x[nw1] & 1L << nb11) {
+                               rv1 += STRTOG_Normal - STRTOG_Denormal;
+                               rv1 &= ~STRTOG_Underflow;
+                               }
+                       }
+               }
+       else {
+               swap = STRTOG_Neg;
+               if ((rv & STRTOG_Retmask) == STRTOG_Infinite) {
+                       b1 = set_ones(b1, nb);
+                       e1 = fpi->emax;
+                       rv1 = STRTOG_Normal | STRTOG_Inexlo;
+                       goto swapcheck;
+                       }
+               decrement(b1);
+               if ((rv & STRTOG_Retmask) == STRTOG_Denormal) {
+                       for(i = nw1; !b1->x[i]; --i)
+                               if (!i) {
+                                       rv1 = STRTOG_Zero | STRTOG_Inexlo;
+                                       break;
+                                       }
+                       goto swapcheck;
+                       }
+               if (!(b1->x[nw1] & 1L << nb11)) {
+                       if (e1 == fpi->emin) {
+                               if (fpi->sudden_underflow)
+                                       rv1 += STRTOG_Zero - STRTOG_Normal;
+                               else
+                                       rv1 += STRTOG_Denormal - STRTOG_Normal;
+                               rv1 |= STRTOG_Underflow;
+                               }
+                       else {
+                               b1 = lshift(b1, 1);
+                               b1->x[0] |= 1;
+                               --e1;
+                               }
+                       }
+               }
+ swapcheck:
+       if (swap ^ (rv & STRTOG_Neg)) {
+               rvp[0] = rv1;
+               rvp[1] = rv;
+               B[0] = b1;
+               B[1] = b;
+               exp[1] = exp[0];
+               exp[0] = e1;
+               }
+       else {
+               rvp[0] = rv;
+               rvp[1] = rv1;
+               B[1] = b1;
+               exp[1] = e1;
+               }
+       return rv;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtoIx.c b/lib/nbsd_libc/gdtoa/strtoIx.c
new file mode 100644 (file)
index 0000000..966e4e3
--- /dev/null
@@ -0,0 +1,70 @@
+/* $NetBSD: strtoIx.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ int
+#ifdef KR_headers
+strtoIx(s, sp, a, b) CONST char *s; char **sp; void *a; void *b;
+#else
+strtoIx(CONST char *s, char **sp, void *a, void *b)
+#endif
+{
+       static FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, SI };
+       Long exp[2];
+       Bigint *B[2];
+       int k, rv[2];
+       UShort *L = (UShort *)a, *M = (UShort *)b;
+
+       B[0] = Balloc(1);
+       if (B[0] == NULL)
+               return STRTOG_NoMemory;
+       B[0]->wds = 2;
+       k = strtoIg(s, sp, &fpi, exp, B, rv);
+       if (k == STRTOG_NoMemory)
+               return k;
+       ULtox(L, B[0]->x, exp[0], rv[0]);
+       Bfree(B[0]);
+       if (B[1]) {
+               ULtox(M, B[1]->x, exp[1], rv[1]);
+               Bfree(B[1]);
+               }
+       else {
+               M[0] = L[0];
+               M[1] = L[1];
+               M[2] = L[2];
+               M[3] = L[3];
+               M[4] = L[4];
+               }
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtoIxL.c b/lib/nbsd_libc/gdtoa/strtoIxL.c
new file mode 100644 (file)
index 0000000..e610696
--- /dev/null
@@ -0,0 +1,68 @@
+/* $NetBSD: strtoIxL.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ int
+#ifdef KR_headers
+strtoIxL(s, sp, a, b) CONST char *s; char **sp; void *a; void *b;
+#else
+strtoIxL(CONST char *s, char **sp, void *a, void *b)
+#endif
+{
+       static FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, SI };
+       Long exp[2];
+       Bigint *B[2];
+       int k, rv[2];
+       ULong *L = (ULong *)a, *M = (ULong *)b;
+
+       B[0] = Balloc(1);
+       if (B[0] == NULL)
+               return STRTOG_NoMemory;
+       B[0]->wds = 2;
+       k = strtoIg(s, sp, &fpi, exp, B, rv);
+       if (k == STRTOG_NoMemory)
+               return k;
+       ULtoxL(L, B[0]->x, exp[0], rv[0]);
+       Bfree(B[0]);
+       if (B[1]) {
+               ULtoxL(M, B[1]->x, exp[1], rv[1]);
+               Bfree(B[1]);
+               }
+       else {
+               M[0] = L[0];
+               M[1] = L[1];
+               M[2] = L[2];
+               }
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtod.c b/lib/nbsd_libc/gdtoa/strtod.c
new file mode 100644 (file)
index 0000000..b371193
--- /dev/null
@@ -0,0 +1,1018 @@
+/* $NetBSD: strtod.c,v 1.5 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998-2001 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+#ifndef NO_FENV_H
+#include <fenv.h>
+#endif
+
+#ifdef USE_LOCALE
+#include "locale.h"
+#endif
+
+#ifdef IEEE_Arith
+#ifndef NO_IEEE_Scale
+#define Avoid_Underflow
+#undef tinytens
+/* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
+/* flag unnecessarily.  It leads to a song and dance at the end of strtod. */
+static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
+               9007199254740992.e-256
+               };
+#endif
+#endif
+
+#ifdef Honor_FLT_ROUNDS
+#define Rounding rounding
+#undef Check_FLT_ROUNDS
+#define Check_FLT_ROUNDS
+#else
+#define Rounding Flt_Rounds
+#endif
+
+#ifndef __HAVE_LONG_DOUBLE
+__strong_alias(_strtold, strtod)
+__weak_alias(strtold, _strtold)
+#endif
+
+ double
+strtod
+#ifdef KR_headers
+       (s00, se) CONST char *s00; char **se;
+#else
+       (CONST char *s00, char **se)
+#endif
+{
+#ifdef Avoid_Underflow
+       int scale;
+#endif
+       int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, decpt, dsign,
+                e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
+       CONST char *s, *s0, *s1;
+       double aadj, aadj1, adj, rv, rv0;
+       Long L;
+       ULong y, z;
+       Bigint *bb = NULL, *bb1, *bd0;
+       Bigint *bd = NULL, *bs = NULL, *delta = NULL; /* pacify gcc */
+#ifdef SET_INEXACT
+       int inexact, oldinexact;
+#endif
+#ifdef Honor_FLT_ROUNDS
+       int rounding;
+#endif
+
+       sign = nz0 = nz = decpt = 0;
+       dval(rv) = 0.;
+       for(s = s00;;s++) switch(*s) {
+               case '-':
+                       sign = 1;
+                       /* FALLTHROUGH */
+               case '+':
+                       if (*++s)
+                               goto break2;
+                       /* FALLTHROUGH */
+               case 0:
+                       goto ret0;
+               case '\t':
+               case '\n':
+               case '\v':
+               case '\f':
+               case '\r':
+               case ' ':
+                       continue;
+               default:
+                       goto break2;
+               }
+ break2:
+       if (*s == '0') {
+#ifndef NO_HEX_FP
+               {
+               static FPI fpi = { 53, 1-1023-53+1, 2046-1023-53+1, 1, SI };
+               Long expt;
+               ULong bits[2];
+               switch(s[1]) {
+                 case 'x':
+                 case 'X':
+                       {
+#if defined(FE_DOWNWARD) && defined(FE_TONEAREST) && defined(FE_TOWARDZERO) && defined(FE_UPWARD)
+                       FPI fpi1 = fpi;
+                       switch(fegetround()) {
+                         case FE_TOWARDZERO:   fpi1.rounding = 0; break;
+                         case FE_UPWARD:       fpi1.rounding = 2; break;
+                         case FE_DOWNWARD:     fpi1.rounding = 3;
+                         }
+#else
+#define fpi1 fpi
+#endif
+                       switch((i = gethex(&s, &fpi1, &expt, &bb, sign)) & STRTOG_Retmask) {
+                         case STRTOG_NoNumber:
+                               s = s00;
+                               sign = 0;
+                               /* FALLTHROUGH */
+                         case STRTOG_Zero:
+                               break;
+                         default:
+                               if (bb) {
+                                       copybits(bits, fpi.nbits, bb);
+                                       Bfree(bb);
+                                       }
+                               ULtod((/* LINTED */(U*)&rv)->L, bits, expt, i);
+                         }}
+                       goto ret;
+                 }
+               }
+#endif
+               nz0 = 1;
+               while(*++s == '0') ;
+               if (!*s)
+                       goto ret;
+               }
+       s0 = s;
+       y = z = 0;
+       for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
+               if (nd < 9)
+                       y = 10*y + c - '0';
+               else if (nd < 16)
+                       z = 10*z + c - '0';
+       nd0 = nd;
+#ifdef USE_LOCALE
+       if (c == *localeconv()->decimal_point)
+#else
+       if (c == '.')
+#endif
+               {
+               decpt = 1;
+               c = *++s;
+               if (!nd) {
+                       for(; c == '0'; c = *++s)
+                               nz++;
+                       if (c > '0' && c <= '9') {
+                               s0 = s;
+                               nf += nz;
+                               nz = 0;
+                               goto have_dig;
+                               }
+                       goto dig_done;
+                       }
+               for(; c >= '0' && c <= '9'; c = *++s) {
+ have_dig:
+                       nz++;
+                       if (c -= '0') {
+                               nf += nz;
+                               for(i = 1; i < nz; i++)
+                                       if (nd++ < 9)
+                                               y *= 10;
+                                       else if (nd <= DBL_DIG + 1)
+                                               z *= 10;
+                               if (nd++ < 9)
+                                       y = 10*y + c;
+                               else if (nd <= DBL_DIG + 1)
+                                       z = 10*z + c;
+                               nz = 0;
+                               }
+                       }
+               }
+ dig_done:
+       e = 0;
+       if (c == 'e' || c == 'E') {
+               if (!nd && !nz && !nz0) {
+                       goto ret0;
+                       }
+               s00 = s;
+               esign = 0;
+               switch(c = *++s) {
+                       case '-':
+                               esign = 1;
+                               /* FALLTHROUGH */
+                       case '+':
+                               c = *++s;
+                       }
+               if (c >= '0' && c <= '9') {
+                       while(c == '0')
+                               c = *++s;
+                       if (c > '0' && c <= '9') {
+                               L = c - '0';
+                               s1 = s;
+                               while((c = *++s) >= '0' && c <= '9')
+                                       L = 10*L + c - '0';
+                               if (s - s1 > 8 || L > 19999)
+                                       /* Avoid confusion from exponents
+                                        * so large that e might overflow.
+                                        */
+                                       e = 19999; /* safe for 16 bit ints */
+                               else
+                                       e = (int)L;
+                               if (esign)
+                                       e = -e;
+                               }
+                       else
+                               e = 0;
+                       }
+               else
+                       s = s00;
+               }
+       if (!nd) {
+               if (!nz && !nz0) {
+#ifdef INFNAN_CHECK
+                       /* Check for Nan and Infinity */
+                       ULong bits[2];
+                       static FPI fpinan =     /* only 52 explicit bits */
+                               { 52, 1-1023-53+1, 2046-1023-53+1, 1, SI };
+                       if (!decpt)
+                        switch(c) {
+                         case 'i':
+                         case 'I':
+                               if (match(&s,"nf")) {
+                                       --s;
+                                       if (!match(&s,"inity"))
+                                               ++s;
+                                       word0(rv) = 0x7ff00000;
+                                       word1(rv) = 0;
+                                       goto ret;
+                                       }
+                               break;
+                         case 'n':
+                         case 'N':
+                               if (match(&s, "an")) {
+#ifndef No_Hex_NaN
+                                       if (*s == '(' /*)*/
+                                        && hexnan(&s, &fpinan, bits)
+                                                       == STRTOG_NaNbits) {
+                                               word0(rv) = 0x7ff00000 | bits[1];
+                                               word1(rv) = bits[0];
+                                               }
+                                       else {
+#endif
+                                               word0(rv) = NAN_WORD0;
+                                               word1(rv) = NAN_WORD1;
+#ifndef No_Hex_NaN
+                                               }
+#endif
+                                       goto ret;
+                                       }
+                         }
+#endif /* INFNAN_CHECK */
+ ret0:
+                       s = s00;
+                       sign = 0;
+                       }
+               goto ret;
+               }
+       e1 = e -= nf;
+
+       /* Now we have nd0 digits, starting at s0, followed by a
+        * decimal point, followed by nd-nd0 digits.  The number we're
+        * after is the integer represented by those digits times
+        * 10**e */
+
+       if (!nd0)
+               nd0 = nd;
+       k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
+       dval(rv) = y;
+       if (k > 9) {
+#ifdef SET_INEXACT
+               if (k > DBL_DIG)
+                       oldinexact = get_inexact();
+#endif
+               dval(rv) = tens[k - 9] * dval(rv) + z;
+               }
+       bd0 = 0;
+       if (nd <= DBL_DIG
+#ifndef RND_PRODQUOT
+#ifndef Honor_FLT_ROUNDS
+               && Flt_Rounds == 1
+#endif
+#endif
+                       ) {
+               if (!e)
+                       goto ret;
+               if (e > 0) {
+                       if (e <= Ten_pmax) {
+#ifdef VAX
+                               goto vax_ovfl_check;
+#else
+#ifdef Honor_FLT_ROUNDS
+                               /* round correctly FLT_ROUNDS = 2 or 3 */
+                               if (sign) {
+                                       rv = -rv;
+                                       sign = 0;
+                                       }
+#endif
+                               /* rv = */ rounded_product(dval(rv), tens[e]);
+                               goto ret;
+#endif
+                               }
+                       i = DBL_DIG - nd;
+                       if (e <= Ten_pmax + i) {
+                               /* A fancier test would sometimes let us do
+                                * this for larger i values.
+                                */
+#ifdef Honor_FLT_ROUNDS
+                               /* round correctly FLT_ROUNDS = 2 or 3 */
+                               if (sign) {
+                                       rv = -rv;
+                                       sign = 0;
+                                       }
+#endif
+                               e -= i;
+                               dval(rv) *= tens[i];
+#ifdef VAX
+                               /* VAX exponent range is so narrow we must
+                                * worry about overflow here...
+                                */
+ vax_ovfl_check:
+                               word0(rv) -= P*Exp_msk1;
+                               /* rv = */ rounded_product(dval(rv), tens[e]);
+                               if ((word0(rv) & Exp_mask)
+                                > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
+                                       goto ovfl;
+                               word0(rv) += P*Exp_msk1;
+#else
+                               /* rv = */ rounded_product(dval(rv), tens[e]);
+#endif
+                               goto ret;
+                               }
+                       }
+#ifndef Inaccurate_Divide
+               else if (e >= -Ten_pmax) {
+#ifdef Honor_FLT_ROUNDS
+                       /* round correctly FLT_ROUNDS = 2 or 3 */
+                       if (sign) {
+                               rv = -rv;
+                               sign = 0;
+                               }
+#endif
+                       /* rv = */ rounded_quotient(dval(rv), tens[-e]);
+                       goto ret;
+                       }
+#endif
+               }
+       e1 += nd - k;
+
+#ifdef IEEE_Arith
+#ifdef SET_INEXACT
+       inexact = 1;
+       if (k <= DBL_DIG)
+               oldinexact = get_inexact();
+#endif
+#ifdef Avoid_Underflow
+       scale = 0;
+#endif
+#ifdef Honor_FLT_ROUNDS
+       if ((rounding = Flt_Rounds) >= 2) {
+               if (sign)
+                       rounding = rounding == 2 ? 0 : 2;
+               else
+                       if (rounding != 2)
+                               rounding = 0;
+               }
+#endif
+#endif /*IEEE_Arith*/
+
+       /* Get starting approximation = rv * 10**e1 */
+
+       if (e1 > 0) {
+               if ( (i = e1 & 15) !=0)
+                       dval(rv) *= tens[i];
+               if (e1 &= ~15) {
+                       if (e1 > DBL_MAX_10_EXP) {
+ ovfl:
+#ifndef NO_ERRNO
+                               errno = ERANGE;
+#endif
+                               /* Can't trust HUGE_VAL */
+#ifdef IEEE_Arith
+#ifdef Honor_FLT_ROUNDS
+                               switch(rounding) {
+                                 case 0: /* toward 0 */
+                                 case 3: /* toward -infinity */
+                                       word0(rv) = Big0;
+                                       word1(rv) = Big1;
+                                       break;
+                                 default:
+                                       word0(rv) = Exp_mask;
+                                       word1(rv) = 0;
+                                 }
+#else /*Honor_FLT_ROUNDS*/
+                               word0(rv) = Exp_mask;
+                               word1(rv) = 0;
+#endif /*Honor_FLT_ROUNDS*/
+#ifdef SET_INEXACT
+                               /* set overflow bit */
+                               dval(rv0) = 1e300;
+                               dval(rv0) *= dval(rv0);
+#endif
+#else /*IEEE_Arith*/
+                               word0(rv) = Big0;
+                               word1(rv) = Big1;
+#endif /*IEEE_Arith*/
+                               if (bd0)
+                                       goto retfree;
+                               goto ret;
+                               }
+                       e1 = (unsigned int)e1 >> 4;
+                       for(j = 0; e1 > 1; j++, e1 = (unsigned int)e1 >> 1)
+                               if (e1 & 1)
+                                       dval(rv) *= bigtens[j];
+               /* The last multiplication could overflow. */
+                       word0(rv) -= P*Exp_msk1;
+                       dval(rv) *= bigtens[j];
+                       if ((z = word0(rv) & Exp_mask)
+                        > Exp_msk1*(DBL_MAX_EXP+Bias-P))
+                               goto ovfl;
+                       if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
+                               /* set to largest number */
+                               /* (Can't trust DBL_MAX) */
+                               word0(rv) = Big0;
+                               word1(rv) = Big1;
+                               }
+                       else
+                               word0(rv) += P*Exp_msk1;
+                       }
+               }
+       else if (e1 < 0) {
+               e1 = -e1;
+               if ( (i = e1 & 15) !=0)
+                       dval(rv) /= tens[i];
+               if (e1 >>= 4) {
+                       if (e1 >= 1 << n_bigtens)
+                               goto undfl;
+#ifdef Avoid_Underflow
+                       if (e1 & Scale_Bit)
+                               scale = 2*P;
+                       for(j = 0; e1 > 0; j++, e1 = (unsigned int)e1 >> 1)
+                               if (e1 & 1)
+                                       dval(rv) *= tinytens[j];
+                       if (scale && (j = 2*P + 1 - ((word0(rv) & Exp_mask)
+                                               >> Exp_shift)) > 0) {
+                               /* scaled rv is denormal; zap j low bits */
+                               if (j >= 32) {
+                                       word1(rv) = 0;
+                                       if (j >= 53)
+                                        word0(rv) = (P+2)*Exp_msk1;
+                                       else
+                                        word0(rv) &= 0xffffffff << (j-32);
+                                       }
+                               else
+                                       word1(rv) &= 0xffffffff << j;
+                               }
+#else
+                       for(j = 0; e1 > 1; j++, e1 >>= 1)
+                               if (e1 & 1)
+                                       dval(rv) *= tinytens[j];
+                       /* The last multiplication could underflow. */
+                       dval(rv0) = dval(rv);
+                       dval(rv) *= tinytens[j];
+                       if (!dval(rv)) {
+                               dval(rv) = 2.*dval(rv0);
+                               dval(rv) *= tinytens[j];
+#endif
+                               if (!dval(rv)) {
+ undfl:
+                                       dval(rv) = 0.;
+#ifndef NO_ERRNO
+                                       errno = ERANGE;
+#endif
+                                       if (bd0)
+                                               goto retfree;
+                                       goto ret;
+                                       }
+#ifndef Avoid_Underflow
+                               word0(rv) = Tiny0;
+                               word1(rv) = Tiny1;
+                               /* The refinement below will clean
+                                * this approximation up.
+                                */
+                               }
+#endif
+                       }
+               }
+
+       /* Now the hard part -- adjusting rv to the correct value.*/
+
+       /* Put digits into bd: true value = bd * 10^e */
+
+       bd0 = s2b(s0, nd0, nd, y);
+       if (bd0 == NULL)
+               goto ovfl;
+
+       for(;;) {
+               bd = Balloc(bd0->k);
+               if (bd == NULL)
+                       goto ovfl;
+               Bcopy(bd, bd0);
+               bb = d2b(dval(rv), &bbe, &bbbits);      /* rv = bb * 2^bbe */
+               if (bb == NULL)
+                       goto ovfl;
+               bs = i2b(1);
+               if (bs == NULL)
+                       goto ovfl;
+
+               if (e >= 0) {
+                       bb2 = bb5 = 0;
+                       bd2 = bd5 = e;
+                       }
+               else {
+                       bb2 = bb5 = -e;
+                       bd2 = bd5 = 0;
+                       }
+               if (bbe >= 0)
+                       bb2 += bbe;
+               else
+                       bd2 -= bbe;
+               bs2 = bb2;
+#ifdef Honor_FLT_ROUNDS
+               if (rounding != 1)
+                       bs2++;
+#endif
+#ifdef Avoid_Underflow
+               j = bbe - scale;
+               i = j + bbbits - 1;     /* logb(rv) */
+               if (i < Emin)   /* denormal */
+                       j += P - Emin;
+               else
+                       j = P + 1 - bbbits;
+#else /*Avoid_Underflow*/
+#ifdef Sudden_Underflow
+#ifdef IBM
+               j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
+#else
+               j = P + 1 - bbbits;
+#endif
+#else /*Sudden_Underflow*/
+               j = bbe;
+               i = j + bbbits - 1;     /* logb(rv) */
+               if (i < Emin)   /* denormal */
+                       j += P - Emin;
+               else
+                       j = P + 1 - bbbits;
+#endif /*Sudden_Underflow*/
+#endif /*Avoid_Underflow*/
+               bb2 += j;
+               bd2 += j;
+#ifdef Avoid_Underflow
+               bd2 += scale;
+#endif
+               i = bb2 < bd2 ? bb2 : bd2;
+               if (i > bs2)
+                       i = bs2;
+               if (i > 0) {
+                       bb2 -= i;
+                       bd2 -= i;
+                       bs2 -= i;
+                       }
+               if (bb5 > 0) {
+                       bs = pow5mult(bs, bb5);
+                       if (bs == NULL)
+                               goto ovfl;
+                       bb1 = mult(bs, bb);
+                       if (bb1 == NULL)
+                               goto ovfl;
+                       Bfree(bb);
+                       bb = bb1;
+                       }
+               if (bb2 > 0) {
+                       bb = lshift(bb, bb2);
+                       if (bb == NULL)
+                               goto ovfl;
+                       }
+               if (bd5 > 0) {
+                       bd = pow5mult(bd, bd5);
+                       if (bd == NULL)
+                               goto ovfl;
+                       }
+               if (bd2 > 0) {
+                       bd = lshift(bd, bd2);
+                       if (bd == NULL)
+                               goto ovfl;
+                       }
+               if (bs2 > 0) {
+                       bs = lshift(bs, bs2);
+                       if (bs == NULL)
+                               goto ovfl;
+                       }
+               delta = diff(bb, bd);
+               if (delta == NULL)
+                       goto ovfl;
+               dsign = delta->sign;
+               delta->sign = 0;
+               i = cmp(delta, bs);
+#ifdef Honor_FLT_ROUNDS
+               if (rounding != 1) {
+                       if (i < 0) {
+                               /* Error is less than an ulp */
+                               if (!delta->x[0] && delta->wds <= 1) {
+                                       /* exact */
+#ifdef SET_INEXACT
+                                       inexact = 0;
+#endif
+                                       break;
+                                       }
+                               if (rounding) {
+                                       if (dsign) {
+                                               adj = 1.;
+                                               goto apply_adj;
+                                               }
+                                       }
+                               else if (!dsign) {
+                                       adj = -1.;
+                                       if (!word1(rv)
+                                        && !(word0(rv) & Frac_mask)) {
+                                               y = word0(rv) & Exp_mask;
+#ifdef Avoid_Underflow
+                                               if (!scale || y > 2*P*Exp_msk1)
+#else
+                                               if (y)
+#endif
+                                                 {
+                                                 delta = lshift(delta,Log2P);
+                                                 if (cmp(delta, bs) <= 0)
+                                                       adj = -0.5;
+                                                 }
+                                               }
+ apply_adj:
+#ifdef Avoid_Underflow
+                                       if (scale && (y = word0(rv) & Exp_mask)
+                                               <= 2*P*Exp_msk1)
+                                         word0(adj) += (2*P+1)*Exp_msk1 - y;
+#else
+#ifdef Sudden_Underflow
+                                       if ((word0(rv) & Exp_mask) <=
+                                                       P*Exp_msk1) {
+                                               word0(rv) += P*Exp_msk1;
+                                               dval(rv) += adj*ulp(dval(rv));
+                                               word0(rv) -= P*Exp_msk1;
+                                               }
+                                       else
+#endif /*Sudden_Underflow*/
+#endif /*Avoid_Underflow*/
+                                       dval(rv) += adj*ulp(dval(rv));
+                                       }
+                               break;
+                               }
+                       adj = ratio(delta, bs);
+                       if (adj < 1.)
+                               adj = 1.;
+                       if (adj <= 0x7ffffffe) {
+                               /* adj = rounding ? ceil(adj) : floor(adj); */
+                               y = adj;
+                               if (y != adj) {
+                                       if (!((rounding>>1) ^ dsign))
+                                               y++;
+                                       adj = y;
+                                       }
+                               }
+#ifdef Avoid_Underflow
+                       if (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
+                               word0(adj) += (2*P+1)*Exp_msk1 - y;
+#else
+#ifdef Sudden_Underflow
+                       if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
+                               word0(rv) += P*Exp_msk1;
+                               adj *= ulp(dval(rv));
+                               if (dsign)
+                                       dval(rv) += adj;
+                               else
+                                       dval(rv) -= adj;
+                               word0(rv) -= P*Exp_msk1;
+                               goto cont;
+                               }
+#endif /*Sudden_Underflow*/
+#endif /*Avoid_Underflow*/
+                       adj *= ulp(dval(rv));
+                       if (dsign)
+                               dval(rv) += adj;
+                       else
+                               dval(rv) -= adj;
+                       goto cont;
+                       }
+#endif /*Honor_FLT_ROUNDS*/
+
+               if (i < 0) {
+                       /* Error is less than half an ulp -- check for
+                        * special case of mantissa a power of two.
+                        */
+                       if (dsign || word1(rv) || word0(rv) & Bndry_mask
+#ifdef IEEE_Arith
+#ifdef Avoid_Underflow
+                        || (word0(rv) & Exp_mask) <= (2*P+1)*Exp_msk1
+#else
+                        || (word0(rv) & Exp_mask) <= Exp_msk1
+#endif
+#endif
+                               ) {
+#ifdef SET_INEXACT
+                               if (!delta->x[0] && delta->wds <= 1)
+                                       inexact = 0;
+#endif
+                               break;
+                               }
+                       if (!delta->x[0] && delta->wds <= 1) {
+                               /* exact result */
+#ifdef SET_INEXACT
+                               inexact = 0;
+#endif
+                               break;
+                               }
+                       delta = lshift(delta,Log2P);
+                       if (cmp(delta, bs) > 0)
+                               goto drop_down;
+                       break;
+                       }
+               if (i == 0) {
+                       /* exactly half-way between */
+                       if (dsign) {
+                               if ((word0(rv) & Bndry_mask1) == Bndry_mask1
+                                &&  word1(rv) == (
+#ifdef Avoid_Underflow
+                       (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
+               ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
+#endif
+                                                  0xffffffff)) {
+                                       /*boundary case -- increment exponent*/
+                                       word0(rv) = (word0(rv) & Exp_mask)
+                                               + Exp_msk1
+#ifdef IBM
+                                               | Exp_msk1 >> 4
+#endif
+                                               ;
+                                       word1(rv) = 0;
+#ifdef Avoid_Underflow
+                                       dsign = 0;
+#endif
+                                       break;
+                                       }
+                               }
+                       else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
+ drop_down:
+                               /* boundary case -- decrement exponent */
+#ifdef Sudden_Underflow /*{{*/
+                               L = word0(rv) & Exp_mask;
+#ifdef IBM
+                               if (L <  Exp_msk1)
+#else
+#ifdef Avoid_Underflow
+                               if (L <= (scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
+#else
+                               if (L <= Exp_msk1)
+#endif /*Avoid_Underflow*/
+#endif /*IBM*/
+                                       goto undfl;
+                               L -= Exp_msk1;
+#else /*Sudden_Underflow}{*/
+#ifdef Avoid_Underflow
+                               if (scale) {
+                                       L = word0(rv) & Exp_mask;
+                                       if (L <= (2*P+1)*Exp_msk1) {
+                                               if (L > (P+2)*Exp_msk1)
+                                                       /* round even ==> */
+                                                       /* accept rv */
+                                                       break;
+                                               /* rv = smallest denormal */
+                                               goto undfl;
+                                               }
+                                       }
+#endif /*Avoid_Underflow*/
+                               L = (word0(rv) & Exp_mask) - Exp_msk1;
+#endif /*Sudden_Underflow}*/
+                               word0(rv) = L | Bndry_mask1;
+                               word1(rv) = 0xffffffff;
+#ifdef IBM
+                               goto cont;
+#else
+                               break;
+#endif
+                               }
+#ifndef ROUND_BIASED
+                       if (!(word1(rv) & LSB))
+                               break;
+#endif
+                       if (dsign)
+                               dval(rv) += ulp(dval(rv));
+#ifndef ROUND_BIASED
+                       else {
+                               dval(rv) -= ulp(dval(rv));
+#ifndef Sudden_Underflow
+                               if (!dval(rv))
+                                       goto undfl;
+#endif
+                               }
+#ifdef Avoid_Underflow
+                       dsign = 1 - dsign;
+#endif
+#endif
+                       break;
+                       }
+               if ((aadj = ratio(delta, bs)) <= 2.) {
+                       if (dsign)
+                               aadj = aadj1 = 1.;
+                       else if (word1(rv) || word0(rv) & Bndry_mask) {
+#ifndef Sudden_Underflow
+                               if (word1(rv) == Tiny1 && !word0(rv))
+                                       goto undfl;
+#endif
+                               aadj = 1.;
+                               aadj1 = -1.;
+                               }
+                       else {
+                               /* special case -- power of FLT_RADIX to be */
+                               /* rounded down... */
+
+                               if (aadj < 2./FLT_RADIX)
+                                       aadj = 1./FLT_RADIX;
+                               else
+                                       aadj *= 0.5;
+                               aadj1 = -aadj;
+                               }
+                       }
+               else {
+                       aadj *= 0.5;
+                       aadj1 = dsign ? aadj : -aadj;
+#ifdef Check_FLT_ROUNDS
+                       switch(Rounding) {
+                               case 2: /* towards +infinity */
+                                       aadj1 -= 0.5;
+                                       break;
+                               case 0: /* towards 0 */
+                               case 3: /* towards -infinity */
+                                       aadj1 += 0.5;
+                               }
+#else
+                       if (Flt_Rounds == 0)
+                               aadj1 += 0.5;
+#endif /*Check_FLT_ROUNDS*/
+                       }
+               y = word0(rv) & Exp_mask;
+
+               /* Check for overflow */
+
+               if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
+                       dval(rv0) = dval(rv);
+                       word0(rv) -= P*Exp_msk1;
+                       adj = aadj1 * ulp(dval(rv));
+                       dval(rv) += adj;
+                       if ((word0(rv) & Exp_mask) >=
+                                       Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
+                               if (word0(rv0) == Big0 && word1(rv0) == Big1)
+                                       goto ovfl;
+                               word0(rv) = Big0;
+                               word1(rv) = Big1;
+                               goto cont;
+                               }
+                       else
+                               word0(rv) += P*Exp_msk1;
+                       }
+               else {
+#ifdef Avoid_Underflow
+                       if (scale && y <= 2*P*Exp_msk1) {
+                               if (aadj <= 0x7fffffff) {
+                                       if ((z = aadj) == 0)
+                                               z = 1;
+                                       aadj = z;
+                                       aadj1 = dsign ? aadj : -aadj;
+                                       }
+                               word0(aadj1) += (2*P+1)*Exp_msk1 - y;
+                               }
+                       adj = aadj1 * ulp(dval(rv));
+                       dval(rv) += adj;
+#else
+#ifdef Sudden_Underflow
+                       if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
+                               dval(rv0) = dval(rv);
+                               word0(rv) += P*Exp_msk1;
+                               adj = aadj1 * ulp(dval(rv));
+                               dval(rv) += adj;
+#ifdef IBM
+                               if ((word0(rv) & Exp_mask) <  P*Exp_msk1)
+#else
+                               if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
+#endif
+                                       {
+                                       if (word0(rv0) == Tiny0
+                                        && word1(rv0) == Tiny1)
+                                               goto undfl;
+                                       word0(rv) = Tiny0;
+                                       word1(rv) = Tiny1;
+                                       goto cont;
+                                       }
+                               else
+                                       word0(rv) -= P*Exp_msk1;
+                               }
+                       else {
+                               adj = aadj1 * ulp(dval(rv));
+                               dval(rv) += adj;
+                               }
+#else /*Sudden_Underflow*/
+                       /* Compute adj so that the IEEE rounding rules will
+                        * correctly round rv + adj in some half-way cases.
+                        * If rv * ulp(rv) is denormalized (i.e.,
+                        * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
+                        * trouble from bits lost to denormalization;
+                        * example: 1.2e-307 .
+                        */
+                       if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
+                               aadj1 = (double)(int)(aadj + 0.5);
+                               if (!dsign)
+                                       aadj1 = -aadj1;
+                               }
+                       adj = aadj1 * ulp(dval(rv));
+                       dval(rv) += adj;
+#endif /*Sudden_Underflow*/
+#endif /*Avoid_Underflow*/
+                       }
+               z = word0(rv) & Exp_mask;
+#ifndef SET_INEXACT
+#ifdef Avoid_Underflow
+               if (!scale)
+#endif
+               if (y == z) {
+                       /* Can we stop now? */
+                       L = (Long)aadj;
+                       aadj -= L;
+                       /* The tolerances below are conservative. */
+                       if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
+                               if (aadj < .4999999 || aadj > .5000001)
+                                       break;
+                               }
+                       else if (aadj < .4999999/FLT_RADIX)
+                               break;
+                       }
+#endif
+ cont:
+               Bfree(bb);
+               Bfree(bd);
+               Bfree(bs);
+               Bfree(delta);
+               }
+#ifdef SET_INEXACT
+       if (inexact) {
+               if (!oldinexact) {
+                       word0(rv0) = Exp_1 + (70 << Exp_shift);
+                       word1(rv0) = 0;
+                       dval(rv0) += 1.;
+                       }
+               }
+       else if (!oldinexact)
+               clear_inexact();
+#endif
+#ifdef Avoid_Underflow
+       if (scale) {
+               word0(rv0) = Exp_1 - 2*P*Exp_msk1;
+               word1(rv0) = 0;
+               dval(rv) *= dval(rv0);
+#ifndef NO_ERRNO
+               /* try to avoid the bug of testing an 8087 register value */
+               if (word0(rv) == 0 && word1(rv) == 0)
+                       errno = ERANGE;
+#endif
+               }
+#endif /* Avoid_Underflow */
+#ifdef SET_INEXACT
+       if (inexact && !(word0(rv) & Exp_mask)) {
+               /* set underflow bit */
+               dval(rv0) = 1e-300;
+               dval(rv0) *= dval(rv0);
+               }
+#endif
+ retfree:
+       Bfree(bb);
+       Bfree(bd);
+       Bfree(bs);
+       Bfree(bd0);
+       Bfree(delta);
+ ret:
+       if (se)
+               *se = __UNCONST(s);
+       return sign ? -dval(rv) : dval(rv);
+       }
+
diff --git a/lib/nbsd_libc/gdtoa/strtodI.c b/lib/nbsd_libc/gdtoa/strtodI.c
new file mode 100644 (file)
index 0000000..2631d5c
--- /dev/null
@@ -0,0 +1,171 @@
+/* $NetBSD: strtodI.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ static double
+#ifdef KR_headers
+ulpdown(d) double *d;
+#else
+ulpdown(double *d)
+#endif
+{
+       double u;
+       ULong *L = (ULong*)d;
+
+       u = ulp(*d);
+       if (!(L[_1] | L[_0] & 0xfffff)
+        && (L[_0] & 0x7ff00000) > 0x00100000)
+               u *= 0.5;
+       return u;
+       }
+
+ int
+#ifdef KR_headers
+strtodI(s, sp, dd) CONST char *s; char **sp; double *dd;
+#else
+strtodI(CONST char *s, char **sp, double *dd)
+#endif
+{
+       static FPI fpi = { 53, 1-1023-53+1, 2046-1023-53+1, 1, SI };
+       ULong bits[2], sign;
+       Long exp;
+       int j, k;
+       typedef union {
+               double d[2];
+               ULong L[4];
+               } U;
+       U *u;
+
+       k = strtodg(s, sp, &fpi, &exp, bits);
+       if (k == STRTOG_NoMemory)
+               return k;
+       u = (U*)dd;
+       sign = k & STRTOG_Neg ? 0x80000000L : 0;
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+               u->d[0] = u->d[1] = 0.;
+               break;
+
+         case STRTOG_Zero:
+               u->d[0] = u->d[1] = 0.;
+#ifdef Sudden_Underflow
+               if (k & STRTOG_Inexact) {
+                       if (sign)
+                               u->L[_0] = 0x80100000L;
+                       else
+                               u->L[2+_0] = 0x100000L;
+                       }
+               break;
+#else
+               goto contain;
+#endif
+
+         case STRTOG_Denormal:
+               u->L[_1] = bits[0];
+               u->L[_0] = bits[1];
+               goto contain;
+
+         case STRTOG_Normal:
+               u->L[_1] = bits[0];
+               u->L[_0] = (bits[1] & ~0x100000) | ((exp + 0x3ff + 52) << 20);
+         contain:
+               j = k & STRTOG_Inexact;
+               if (sign) {
+                       u->L[_0] |= sign;
+                       j = STRTOG_Inexact - j;
+                       }
+               switch(j) {
+                 case STRTOG_Inexlo:
+#ifdef Sudden_Underflow
+                       if ((u->L[_0] & 0x7ff00000) < 0x3500000) {
+                               u->L[2+_0] = u->L[_0] + 0x3500000;
+                               u->L[2+_1] = u->L[_1];
+                               u->d[1] += ulp(u->d[1]);
+                               u->L[2+_0] -= 0x3500000;
+                               if (!(u->L[2+_0] & 0x7ff00000)) {
+                                       u->L[2+_0] = sign;
+                                       u->L[2+_1] = 0;
+                                       }
+                               }
+                       else
+#endif
+                       u->d[1] = u->d[0] + ulp(u->d[0]);
+                       break;
+                 case STRTOG_Inexhi:
+                       u->d[1] = u->d[0];
+#ifdef Sudden_Underflow
+                       if ((u->L[_0] & 0x7ff00000) < 0x3500000) {
+                               u->L[_0] += 0x3500000;
+                               u->d[0] -= ulpdown(u->d);
+                               u->L[_0] -= 0x3500000;
+                               if (!(u->L[_0] & 0x7ff00000)) {
+                                       u->L[_0] = sign;
+                                       u->L[_1] = 0;
+                                       }
+                               }
+                       else
+#endif
+                       u->d[0] -= ulpdown(u->d);
+                       break;
+                 default:
+                       u->d[1] = u->d[0];
+                 }
+               break;
+
+         case STRTOG_Infinite:
+               u->L[_0] = u->L[2+_0] = sign | 0x7ff00000;
+               u->L[_1] = u->L[2+_1] = 0;
+               if (k & STRTOG_Inexact) {
+                       if (sign) {
+                               u->L[2+_0] = 0xffefffffL;
+                               u->L[2+_1] = 0xffffffffL;
+                               }
+                       else {
+                               u->L[_0] = 0x7fefffffL;
+                               u->L[_1] = 0xffffffffL;
+                               }
+                       }
+               break;
+
+         case STRTOG_NaN:
+               u->L[0] = u->L[2] = d_QNAN0;
+               u->L[1] = u->L[3] = d_QNAN1;
+               break;
+
+         case STRTOG_NaNbits:
+               u->L[_0] = u->L[2+_0] = 0x7ff00000 | sign | bits[1];
+               u->L[_1] = u->L[2+_1] = bits[0];
+         }
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtodg.c b/lib/nbsd_libc/gdtoa/strtodg.c
new file mode 100644 (file)
index 0000000..3b3c7be
--- /dev/null
@@ -0,0 +1,1069 @@
+/* $NetBSD: strtodg.c,v 1.6 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998-2001 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#ifdef USE_LOCALE
+#include "locale.h"
+#endif
+
+ static CONST int
+fivesbits[] = {         0,  3,  5,  7, 10, 12, 14, 17, 19, 21,
+               24, 26, 28, 31, 33, 35, 38, 40, 42, 45,
+               47, 49, 52
+#ifdef VAX
+               , 54, 56
+#endif
+               };
+
+ Bigint *
+#ifdef KR_headers
+increment(b) Bigint *b;
+#else
+increment(Bigint *b)
+#endif
+{
+       ULong *x, *xe;
+       Bigint *b1;
+#ifdef Pack_16
+       ULong carry = 1, y;
+#endif
+
+       x = b->x;
+       xe = x + b->wds;
+#ifdef Pack_32
+       do {
+               if (*x < (ULong)0xffffffffL) {
+                       ++*x;
+                       return b;
+                       }
+               *x++ = 0;
+               } while(x < xe);
+#else
+       do {
+               y = *x + carry;
+               carry = y >> 16;
+               *x++ = y & 0xffff;
+               if (!carry)
+                       return b;
+               } while(x < xe);
+       if (carry)
+#endif
+       {
+               if (b->wds >= b->maxwds) {
+                       b1 = Balloc(b->k+1);
+                       if (b1 == NULL)
+                               return NULL;
+                       Bcopy(b1,b);
+                       Bfree(b);
+                       b = b1;
+                       }
+               b->x[b->wds++] = 1;
+               }
+       return b;
+       }
+
+ int
+#ifdef KR_headers
+decrement(b) Bigint *b;
+#else
+decrement(Bigint *b)
+#endif
+{
+       ULong *x, *xe;
+#ifdef Pack_16
+       ULong borrow = 1, y;
+#endif
+
+       x = b->x;
+       xe = x + b->wds;
+#ifdef Pack_32
+       do {
+               if (*x) {
+                       --*x;
+                       break;
+                       }
+               *x++ = 0xffffffffUL;
+               }
+               while(x < xe);
+#else
+       do {
+               y = *x - borrow;
+               borrow = (y & 0x10000) >> 16;
+               *x++ = y & 0xffff;
+               } while(borrow && x < xe);
+#endif
+       return STRTOG_Inexlo;
+       }
+
+ static int
+#ifdef KR_headers
+all_on(b, n) CONST Bigint *b; int n;
+#else
+all_on(CONST Bigint *b, int n)
+#endif
+{
+       CONST ULong *x, *xe;
+
+       x = b->x;
+       xe = x + ((unsigned int)n >> kshift);
+       while(x < xe)
+               if ((*x++ & ALL_ON) != ALL_ON)
+                       return 0;
+       if (n &= kmask)
+               return ((*x | (ALL_ON << n)) & ALL_ON) == ALL_ON;
+       return 1;
+       }
+
+ Bigint *
+#ifdef KR_headers
+set_ones(b, n) Bigint *b; int n;
+#else
+set_ones(Bigint *b, int n)
+#endif
+{
+       int k;
+       ULong *x, *xe;
+
+       k = (unsigned int)(n + ((1 << kshift) - 1)) >> kshift;
+       if (b->k < k) {
+               Bfree(b);
+               b = Balloc(k);
+               if (b == NULL)
+                       return NULL;
+               }
+       k = (unsigned int)n >> kshift;
+       if (n &= kmask)
+               k++;
+       b->wds = k;
+       x = b->x;
+       xe = x + k;
+       while(x < xe)
+               *x++ = ALL_ON;
+       if (n)
+               x[-1] >>= ULbits - n;
+       return b;
+       }
+
+ static int
+rvOK
+#ifdef KR_headers
+ (d, fpi, expt, bits, exact, rd, irv)
+ double d; CONST FPI *fpi; Long *expt; ULong *bits; int exact, rd, *irv;
+#else
+ (double d, CONST FPI *fpi, Long *expt, ULong *bits, int exact, int rd, int *irv)
+#endif
+{
+       Bigint *b;
+       ULong carry, inex, lostbits;
+       int bdif, e, j, k, k1, nb, rv;
+
+       carry = rv = 0;
+       b = d2b(d, &e, &bdif);
+       bdif -= nb = fpi->nbits;
+       e += bdif;
+       if (bdif <= 0) {
+               if (exact)
+                       goto trunc;
+               goto ret;
+               }
+       if (P == nb) {
+               if (
+#ifndef IMPRECISE_INEXACT
+                       exact &&
+#endif
+                       fpi->rounding ==
+#ifdef RND_PRODQUOT
+                                       FPI_Round_near
+#else
+                                       Flt_Rounds
+#endif
+                       ) goto trunc;
+               goto ret;
+               }
+       switch(rd) {
+         case 1:
+               goto trunc;
+         case 2:
+               break;
+         default: /* round near */
+               k = bdif - 1;
+               if (!k) {
+                       if (!exact)
+                               goto ret;
+                       if (b->x[0] & 2)
+                               break;
+                       goto trunc;
+                       }
+               if (b->x[(unsigned int)k>>kshift] & ((ULong)1 << (k & kmask)))
+                       break;
+               goto trunc;
+         }
+       /* "break" cases: round up 1 bit, then truncate; bdif > 0 */
+       carry = 1;
+ trunc:
+       inex = lostbits = 0;
+       if (bdif > 0) {
+               if ( (lostbits = any_on(b, bdif)) !=0)
+                       inex = STRTOG_Inexlo;
+               rshift(b, bdif);
+               if (carry) {
+                       inex = STRTOG_Inexhi;
+                       b = increment(b);
+                       if ( (j = nb & kmask) !=0)
+                               j = ULbits - j;
+                       if (hi0bits(b->x[b->wds - 1]) != j) {
+                               if (!lostbits)
+                                       lostbits = b->x[0] & 1;
+                               rshift(b, 1);
+                               e++;
+                               }
+                       }
+               }
+       else if (bdif < 0)
+               b = lshift(b, -bdif);
+       if (e < fpi->emin) {
+               k = fpi->emin - e;
+               e = fpi->emin;
+               if (k > nb || fpi->sudden_underflow) {
+                       b->wds = inex = 0;
+                       *irv = STRTOG_Underflow | STRTOG_Inexlo;
+                       }
+               else {
+                       k1 = k - 1;
+                       if (k1 > 0 && !lostbits)
+                               lostbits = any_on(b, k1);
+                       if (!lostbits && !exact)
+                               goto ret;
+                       lostbits |=
+                         carry = b->x[(unsigned int)k1>>kshift] &
+                                      (1 << (k1 & kmask));
+                       rshift(b, k);
+                       *irv = STRTOG_Denormal;
+                       if (carry) {
+                               b = increment(b);
+                               inex = STRTOG_Inexhi | STRTOG_Underflow;
+                               }
+                       else if (lostbits)
+                               inex = STRTOG_Inexlo | STRTOG_Underflow;
+                       }
+               }
+       else if (e > fpi->emax) {
+               e = fpi->emax + 1;
+               *irv = STRTOG_Infinite | STRTOG_Overflow | STRTOG_Inexhi;
+#ifndef NO_ERRNO
+               errno = ERANGE;
+#endif
+               b->wds = inex = 0;
+               }
+       *expt = e;
+       copybits(bits, nb, b);
+       *irv |= inex;
+       rv = 1;
+ ret:
+       Bfree(b);
+       return rv;
+       }
+
+#ifndef VAX
+ static int
+#ifdef KR_headers
+mantbits(d) double d;
+#else
+mantbits(double d)
+#endif
+{
+       ULong L;
+#ifdef VAX
+       L = word1(d) << 16 | word1(d) >> 16;
+       if (L)
+#else
+       if ( (L = word1(d)) !=0)
+#endif
+               return P - lo0bits(&L);
+#ifdef VAX
+       L = word0(d) << 16 | word0(d) >> 16 | Exp_msk11;
+#else
+       L = word0(d) | Exp_msk1;
+#endif
+       return P - 32 - lo0bits(&L);
+       }
+#endif /* !VAX */
+
+ int
+strtodg
+#ifdef KR_headers
+       (s00, se, fpi, expt, bits)
+       CONST char *s00; char **se; CONST FPI *fpi; Long *expt; ULong *bits;
+#else
+       (CONST char *s00, char **se, CONST FPI *fpi, Long *expt, ULong *bits)
+#endif
+{
+       int abe, abits, asub;
+       int bb0, bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, decpt, denorm;
+       int dsign, e, e1, e2, emin, esign, finished, i, inex, irv;
+       int j, k, nbits, nd, nd0, nf, nz, nz0, rd, rvbits, rve, rve1, sign;
+       int sudden_underflow = 0; /* pacify gcc */
+       CONST char *s, *s0, *s1;
+       double adj, adj0, rv, tol;
+       Long L;
+       ULong y, z;
+       Bigint *ab, *bb, *bb1, *bd, *bd0, *bs, *delta, *rvb, *rvb0;
+
+       e2 = 0; /* XXX gcc */
+
+       irv = STRTOG_Zero;
+       denorm = sign = nz0 = nz = 0;
+       dval(rv) = 0.;
+       rvb = 0;
+       nbits = fpi->nbits;
+       for(s = s00;;s++) switch(*s) {
+               case '-':
+                       sign = 1;
+                       /* FALLTHROUGH */
+               case '+':
+                       if (*++s)
+                               goto break2;
+                       /* FALLTHROUGH */
+               case 0:
+                       sign = 0;
+                       irv = STRTOG_NoNumber;
+                       s = s00;
+                       goto ret;
+               case '\t':
+               case '\n':
+               case '\v':
+               case '\f':
+               case '\r':
+               case ' ':
+                       continue;
+               default:
+                       goto break2;
+               }
+ break2:
+       if (*s == '0') {
+#ifndef NO_HEX_FP
+               switch(s[1]) {
+                 case 'x':
+                 case 'X':
+                       irv = gethex(&s, fpi, expt, &rvb, sign);
+                       if (irv == STRTOG_NoNumber) {
+                               s = s00;
+                               sign = 0;
+                               }
+                       goto ret;
+                 }
+#endif
+               nz0 = 1;
+               while(*++s == '0') ;
+               if (!*s)
+                       goto ret;
+               }
+       sudden_underflow = fpi->sudden_underflow;
+       s0 = s;
+       y = z = 0;
+       for(decpt = nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
+               if (nd < 9)
+                       y = 10*y + c - '0';
+               else if (nd < 16)
+                       z = 10*z + c - '0';
+       nd0 = nd;
+#ifdef USE_LOCALE
+       if (c == *localeconv()->decimal_point)
+#else
+       if (c == '.')
+#endif
+               {
+               decpt = 1;
+               c = *++s;
+               if (!nd) {
+                       for(; c == '0'; c = *++s)
+                               nz++;
+                       if (c > '0' && c <= '9') {
+                               s0 = s;
+                               nf += nz;
+                               nz = 0;
+                               goto have_dig;
+                               }
+                       goto dig_done;
+                       }
+               for(; c >= '0' && c <= '9'; c = *++s) {
+ have_dig:
+                       nz++;
+                       if (c -= '0') {
+                               nf += nz;
+                               for(i = 1; i < nz; i++)
+                                       if (nd++ < 9)
+                                               y *= 10;
+                                       else if (nd <= DBL_DIG + 1)
+                                               z *= 10;
+                               if (nd++ < 9)
+                                       y = 10*y + c;
+                               else if (nd <= DBL_DIG + 1)
+                                       z = 10*z + c;
+                               nz = 0;
+                               }
+                       }
+               }
+ dig_done:
+       e = 0;
+       if (c == 'e' || c == 'E') {
+               if (!nd && !nz && !nz0) {
+                       irv = STRTOG_NoNumber;
+                       s = s00;
+                       goto ret;
+                       }
+               s00 = s;
+               esign = 0;
+               switch(c = *++s) {
+                       case '-':
+                               esign = 1;
+                               /* FALLTHROUGH */
+                       case '+':
+                               c = *++s;
+                       }
+               if (c >= '0' && c <= '9') {
+                       while(c == '0')
+                               c = *++s;
+                       if (c > '0' && c <= '9') {
+                               L = c - '0';
+                               s1 = s;
+                               while((c = *++s) >= '0' && c <= '9')
+                                       L = 10*L + c - '0';
+                               if (s - s1 > 8 || L > 19999)
+                                       /* Avoid confusion from exponents
+                                        * so large that e might overflow.
+                                        */
+                                       e = 19999; /* safe for 16 bit ints */
+                               else
+                                       e = (int)L;
+                               if (esign)
+                                       e = -e;
+                               }
+                       else
+                               e = 0;
+                       }
+               else
+                       s = s00;
+               }
+       if (!nd) {
+               if (!nz && !nz0) {
+#ifdef INFNAN_CHECK
+                       /* Check for Nan and Infinity */
+                       if (!decpt)
+                        switch(c) {
+                         case 'i':
+                         case 'I':
+                               if (match(&s,"nf")) {
+                                       --s;
+                                       if (!match(&s,"inity"))
+                                               ++s;
+                                       irv = STRTOG_Infinite;
+                                       goto infnanexp;
+                                       }
+                               break;
+                         case 'n':
+                         case 'N':
+                               if (match(&s, "an")) {
+                                       irv = STRTOG_NaN;
+                                       *expt = fpi->emax + 1;
+#ifndef No_Hex_NaN
+                                       if (*s == '(') /*)*/
+                                               irv = hexnan(&s, fpi, bits);
+#endif
+                                       goto infnanexp;
+                                       }
+                         }
+#endif /* INFNAN_CHECK */
+                       irv = STRTOG_NoNumber;
+                       s = s00;
+                       }
+               goto ret;
+               }
+
+       irv = STRTOG_Normal;
+       e1 = e -= nf;
+       rd = 0;
+       switch(fpi->rounding & 3) {
+         case FPI_Round_up:
+               rd = 2 - sign;
+               break;
+         case FPI_Round_zero:
+               rd = 1;
+               break;
+         case FPI_Round_down:
+               rd = 1 + sign;
+         }
+
+       /* Now we have nd0 digits, starting at s0, followed by a
+        * decimal point, followed by nd-nd0 digits.  The number we're
+        * after is the integer represented by those digits times
+        * 10**e */
+
+       if (!nd0)
+               nd0 = nd;
+       k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
+       dval(rv) = y;
+       if (k > 9)
+               dval(rv) = tens[k - 9] * dval(rv) + z;
+       bd0 = 0;
+       if (nbits <= P && nd <= DBL_DIG) {
+               if (!e) {
+                       if (rvOK(dval(rv), fpi, expt, bits, 1, rd, &irv))
+                               goto ret;
+                       }
+               else if (e > 0) {
+                       if (e <= Ten_pmax) {
+#ifdef VAX
+                               goto vax_ovfl_check;
+#else
+                               i = fivesbits[e] + mantbits(dval(rv)) <= P;
+                               /* rv = */ rounded_product(dval(rv), tens[e]);
+                               if (rvOK(dval(rv), fpi, expt, bits, i, rd, &irv))
+                                       goto ret;
+                               e1 -= e;
+                               goto rv_notOK;
+#endif
+                               }
+                       i = DBL_DIG - nd;
+                       if (e <= Ten_pmax + i) {
+                               /* A fancier test would sometimes let us do
+                                * this for larger i values.
+                                */
+                               e2 = e - i;
+                               e1 -= i;
+                               dval(rv) *= tens[i];
+#ifdef VAX
+                               /* VAX exponent range is so narrow we must
+                                * worry about overflow here...
+                                */
+ vax_ovfl_check:
+                               dval(adj) = dval(rv);
+                               word0(adj) -= P*Exp_msk1;
+                               /* adj = */ rounded_product(dval(adj), tens[e2]);
+                               if ((word0(adj) & Exp_mask)
+                                > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
+                                       goto rv_notOK;
+                               word0(adj) += P*Exp_msk1;
+                               dval(rv) = dval(adj);
+#else
+                               /* rv = */ rounded_product(dval(rv), tens[e2]);
+#endif
+                               if (rvOK(dval(rv), fpi, expt, bits, 0, rd, &irv))
+                                       goto ret;
+                               e1 -= e2;
+                               }
+                       }
+#ifndef Inaccurate_Divide
+               else if (e >= -Ten_pmax) {
+                       /* rv = */ rounded_quotient(dval(rv), tens[-e]);
+                       if (rvOK(dval(rv), fpi, expt, bits, 0, rd, &irv))
+                               goto ret;
+                       e1 -= e;
+                       }
+#endif
+               }
+ rv_notOK:
+       e1 += nd - k;
+
+       /* Get starting approximation = rv * 10**e1 */
+
+       e2 = 0;
+       if (e1 > 0) {
+               if ( (i = e1 & 15) !=0)
+                       dval(rv) *= tens[i];
+               if (e1 &= ~15) {
+                       e1 = (unsigned int)e1 >> 4;
+                       while(e1 >= (1 << (n_bigtens-1))) {
+                               e2 += ((word0(rv) & Exp_mask)
+                                       >> Exp_shift1) - Bias;
+                               word0(rv) &= ~Exp_mask;
+                               word0(rv) |= Bias << Exp_shift1;
+                               dval(rv) *= bigtens[n_bigtens-1];
+                               e1 -= 1 << (n_bigtens-1);
+                               }
+                       e2 += ((word0(rv) & Exp_mask) >> Exp_shift1) - Bias;
+                       word0(rv) &= ~Exp_mask;
+                       word0(rv) |= Bias << Exp_shift1;
+                       for(j = 0; e1 > 0; j++, e1 = (unsigned int)e1 >> 1)
+                               if (e1 & 1)
+                                       dval(rv) *= bigtens[j];
+                       }
+               }
+       else if (e1 < 0) {
+               e1 = -e1;
+               if ( (i = e1 & 15) !=0)
+                       dval(rv) /= tens[i];
+               if (e1 &= ~15) {
+                       e1 = (unsigned int)e1 >> 4;
+                       while(e1 >= (1 << (n_bigtens-1))) {
+                               e2 += ((word0(rv) & Exp_mask)
+                                       >> Exp_shift1) - Bias;
+                               word0(rv) &= ~Exp_mask;
+                               word0(rv) |= Bias << Exp_shift1;
+                               dval(rv) *= tinytens[n_bigtens-1];
+                               e1 -= 1 << (n_bigtens-1);
+                               }
+                       e2 += ((word0(rv) & Exp_mask) >> Exp_shift1) - Bias;
+                       word0(rv) &= ~Exp_mask;
+                       word0(rv) |= Bias << Exp_shift1;
+                       for(j = 0; e1 > 0; j++, e1 = (unsigned int)e1 >> 1)
+                               if (e1 & 1)
+                                       dval(rv) *= tinytens[j];
+                       }
+               }
+#ifdef IBM
+       /* e2 is a correction to the (base 2) exponent of the return
+        * value, reflecting adjustments above to avoid overflow in the
+        * native arithmetic.  For native IBM (base 16) arithmetic, we
+        * must multiply e2 by 4 to change from base 16 to 2.
+        */
+       e2 <<= 2;
+#endif
+       rvb = d2b(dval(rv), &rve, &rvbits);     /* rv = rvb * 2^rve */
+       if (rvb == NULL)
+               return STRTOG_NoMemory;
+       rve += e2;
+       if ((j = rvbits - nbits) > 0) {
+               rshift(rvb, j);
+               rvbits = nbits;
+               rve += j;
+               }
+       bb0 = 0;        /* trailing zero bits in rvb */
+       e2 = rve + rvbits - nbits;
+       if (e2 > fpi->emax + 1)
+               goto huge;
+       rve1 = rve + rvbits - nbits;
+       if (e2 < (emin = fpi->emin)) {
+               denorm = 1;
+               j = rve - emin;
+               if (j > 0) {
+                       rvb = lshift(rvb, j);
+                       rvbits += j;
+                       }
+               else if (j < 0) {
+                       rvbits += j;
+                       if (rvbits <= 0) {
+                               if (rvbits < -1) {
+ ufl:
+                                       rvb->wds = 0;
+                                       rvb->x[0] = 0;
+                                       *expt = emin;
+                                       irv = STRTOG_Underflow | STRTOG_Inexlo;
+                                       goto ret;
+                                       }
+                               rvb->x[0] = rvb->wds = rvbits = 1;
+                               }
+                       else
+                               rshift(rvb, -j);
+                       }
+               rve = rve1 = emin;
+               if (sudden_underflow && e2 + 1 < emin)
+                       goto ufl;
+               }
+
+       /* Now the hard part -- adjusting rv to the correct value.*/
+
+       /* Put digits into bd: true value = bd * 10^e */
+
+       bd0 = s2b(s0, nd0, nd, y);
+
+       for(;;) {
+               bd = Balloc(bd0->k);
+               if (bd == NULL)
+                       return STRTOG_NoMemory;
+               Bcopy(bd, bd0);
+               bb = Balloc(rvb->k);
+               if (bb == NULL)
+                       return STRTOG_NoMemory;
+               Bcopy(bb, rvb);
+               bbbits = rvbits - bb0;
+               bbe = rve + bb0;
+               bs = i2b(1);
+               if (bs == NULL)
+                       return STRTOG_NoMemory;
+
+               if (e >= 0) {
+                       bb2 = bb5 = 0;
+                       bd2 = bd5 = e;
+                       }
+               else {
+                       bb2 = bb5 = -e;
+                       bd2 = bd5 = 0;
+                       }
+               if (bbe >= 0)
+                       bb2 += bbe;
+               else
+                       bd2 -= bbe;
+               bs2 = bb2;
+               j = nbits + 1 - bbbits;
+               i = bbe + bbbits - nbits;
+               if (i < emin)   /* denormal */
+                       j += i - emin;
+               bb2 += j;
+               bd2 += j;
+               i = bb2 < bd2 ? bb2 : bd2;
+               if (i > bs2)
+                       i = bs2;
+               if (i > 0) {
+                       bb2 -= i;
+                       bd2 -= i;
+                       bs2 -= i;
+                       }
+               if (bb5 > 0) {
+                       bs = pow5mult(bs, bb5);
+                       if (bs == NULL)
+                               return STRTOG_NoMemory;
+                       bb1 = mult(bs, bb);
+                       if (bb1 == NULL)
+                               return STRTOG_NoMemory;
+                       Bfree(bb);
+                       bb = bb1;
+                       }
+               bb2 -= bb0;
+               if (bb2 > 0) {
+                       bb = lshift(bb, bb2);
+                       if (bb == NULL)
+                               return STRTOG_NoMemory;
+                       }
+               else if (bb2 < 0)
+                       rshift(bb, -bb2);
+               if (bd5 > 0) {
+                       bd = pow5mult(bd, bd5);
+                       if (bd == NULL)
+                               return STRTOG_NoMemory;
+                       }
+               if (bd2 > 0) {
+                       bd = lshift(bd, bd2);
+                       if (bd == NULL)
+                               return STRTOG_NoMemory;
+                       }
+               if (bs2 > 0) {
+                       bs = lshift(bs, bs2);
+                       if (bs == NULL)
+                               return STRTOG_NoMemory;
+                       }
+               asub = 1;
+               inex = STRTOG_Inexhi;
+               delta = diff(bb, bd);
+               if (delta == NULL)
+                       return STRTOG_NoMemory;
+               if (delta->wds <= 1 && !delta->x[0])
+                       break;
+               dsign = delta->sign;
+               delta->sign = finished = 0;
+               L = 0;
+               i = cmp(delta, bs);
+               if (rd && i <= 0) {
+                       irv = STRTOG_Normal;
+                       if ( (finished = dsign ^ (rd&1)) !=0) {
+                               if (dsign != 0) {
+                                       irv |= STRTOG_Inexhi;
+                                       goto adj1;
+                                       }
+                               irv |= STRTOG_Inexlo;
+                               if (rve1 == emin)
+                                       goto adj1;
+                               for(i = 0, j = nbits; j >= ULbits;
+                                               i++, j -= ULbits) {
+                                       if (rvb->x[i] & ALL_ON)
+                                               goto adj1;
+                                       }
+                               if (j > 1 && lo0bits(rvb->x + i) < j - 1)
+                                       goto adj1;
+                               rve = rve1 - 1;
+                               rvb = set_ones(rvb, rvbits = nbits);
+                               if (rvb == NULL)
+                                       return STRTOG_NoMemory;
+                               break;
+                               }
+                       irv |= dsign ? STRTOG_Inexlo : STRTOG_Inexhi;
+                       break;
+                       }
+               if (i < 0) {
+                       /* Error is less than half an ulp -- check for
+                        * special case of mantissa a power of two.
+                        */
+                       irv = dsign
+                               ? STRTOG_Normal | STRTOG_Inexlo
+                               : STRTOG_Normal | STRTOG_Inexhi;
+                       if (dsign || bbbits > 1 || denorm || rve1 == emin)
+                               break;
+                       delta = lshift(delta,1);
+                       if (delta == NULL)
+                               return STRTOG_NoMemory;
+                       if (cmp(delta, bs) > 0) {
+                               irv = STRTOG_Normal | STRTOG_Inexlo;
+                               goto drop_down;
+                               }
+                       break;
+                       }
+               if (i == 0) {
+                       /* exactly half-way between */
+                       if (dsign) {
+                               if (denorm && all_on(rvb, rvbits)) {
+                                       /*boundary case -- increment exponent*/
+                                       rvb->wds = 1;
+                                       rvb->x[0] = 1;
+                                       rve = emin + nbits - (rvbits = 1);
+                                       irv = STRTOG_Normal | STRTOG_Inexhi;
+                                       denorm = 0;
+                                       break;
+                                       }
+                               irv = STRTOG_Normal | STRTOG_Inexlo;
+                               }
+                       else if (bbbits == 1) {
+                               irv = STRTOG_Normal;
+ drop_down:
+                               /* boundary case -- decrement exponent */
+                               if (rve1 == emin) {
+                                       irv = STRTOG_Normal | STRTOG_Inexhi;
+                                       if (rvb->wds == 1 && rvb->x[0] == 1)
+                                               sudden_underflow = 1;
+                                       break;
+                                       }
+                               rve -= nbits;
+                               rvb = set_ones(rvb, rvbits = nbits);
+                               if (rvb == NULL)
+                                       return STRTOG_NoMemory;
+                               break;
+                               }
+                       else
+                               irv = STRTOG_Normal | STRTOG_Inexhi;
+                       if ((bbbits < nbits && !denorm) || !(rvb->x[0] & 1))
+                               break;
+                       if (dsign) {
+                               rvb = increment(rvb);
+                               if (rvb == NULL)
+                                       return STRTOG_NoMemory;
+                               if ( (j = rvbits & kmask) !=0)
+                                       j = ULbits - j;
+                               if (hi0bits(rvb->x[(unsigned int)(rvb->wds - 1)
+                                                  >> kshift])
+                                               != j)
+                                       rvbits++;
+                               irv = STRTOG_Normal | STRTOG_Inexhi;
+                               }
+                       else {
+                               if (bbbits == 1)
+                                       goto undfl;
+                               decrement(rvb);
+                               irv = STRTOG_Normal | STRTOG_Inexlo;
+                               }
+                       break;
+                       }
+               if ((dval(adj) = ratio(delta, bs)) <= 2.) {
+ adj1:
+                       inex = STRTOG_Inexlo;
+                       if (dsign) {
+                               asub = 0;
+                               inex = STRTOG_Inexhi;
+                               }
+                       else if (denorm && bbbits <= 1) {
+ undfl:
+                               rvb->wds = 0;
+                               rve = emin;
+                               irv = STRTOG_Underflow | STRTOG_Inexlo;
+                               break;
+                               }
+                       adj0 = dval(adj) = 1.;
+                       }
+               else {
+                       adj0 = dval(adj) *= 0.5;
+                       if (dsign) {
+                               asub = 0;
+                               inex = STRTOG_Inexlo;
+                               }
+                       if (dval(adj) < 2147483647.) {
+                               L = adj0;
+                               adj0 -= L;
+                               switch(rd) {
+                                 case 0:
+                                       if (adj0 >= .5)
+                                               goto inc_L;
+                                       break;
+                                 case 1:
+                                       if (asub && adj0 > 0.)
+                                               goto inc_L;
+                                       break;
+                                 case 2:
+                                       if (!asub && adj0 > 0.) {
+ inc_L:
+                                               L++;
+                                               inex = STRTOG_Inexact - inex;
+                                               }
+                                 }
+                               dval(adj) = L;
+                               }
+                       }
+               y = rve + rvbits;
+
+               /* adj *= ulp(dval(rv)); */
+               /* if (asub) rv -= adj; else rv += adj; */
+
+               if (!denorm && rvbits < nbits) {
+                       rvb = lshift(rvb, j = nbits - rvbits);
+                       if (rvb == NULL)
+                               return STRTOG_NoMemory;
+                       rve -= j;
+                       rvbits = nbits;
+                       }
+               ab = d2b(dval(adj), &abe, &abits);
+               if (ab == NULL)
+                       return STRTOG_NoMemory;
+               if (abe < 0)
+                       rshift(ab, -abe);
+               else if (abe > 0)
+                       ab = lshift(ab, abe);
+               rvb0 = rvb;
+               if (asub) {
+                       /* rv -= adj; */
+                       j = hi0bits(rvb->x[rvb->wds-1]);
+                       rvb = diff(rvb, ab);
+                       if (rvb == NULL)
+                               return STRTOG_NoMemory;
+                       k = rvb0->wds - 1;
+                       if (denorm)
+                               /* do nothing */;
+                       else if (rvb->wds <= k
+                               || hi0bits( rvb->x[k]) >
+                                  hi0bits(rvb0->x[k])) {
+                               /* unlikely; can only have lost 1 high bit */
+                               if (rve1 == emin) {
+                                       --rvbits;
+                                       denorm = 1;
+                                       }
+                               else {
+                                       rvb = lshift(rvb, 1);
+                                       if (rvb == NULL)
+                                               return STRTOG_NoMemory;
+                                       --rve;
+                                       --rve1;
+                                       L = finished = 0;
+                                       }
+                               }
+                       }
+               else {
+                       rvb = sum(rvb, ab);
+                       if (rvb == NULL)
+                               return STRTOG_NoMemory;
+                       k = rvb->wds - 1;
+                       if (k >= rvb0->wds
+                        || hi0bits(rvb->x[k]) < hi0bits(rvb0->x[k])) {
+                               if (denorm) {
+                                       if (++rvbits == nbits)
+                                               denorm = 0;
+                                       }
+                               else {
+                                       rshift(rvb, 1);
+                                       rve++;
+                                       rve1++;
+                                       L = 0;
+                                       }
+                               }
+                       }
+               Bfree(ab);
+               Bfree(rvb0);
+               if (finished)
+                       break;
+
+               z = rve + rvbits;
+               if (y == z && L) {
+                       /* Can we stop now? */
+                       tol = dval(adj) * 5e-16; /* > max rel error */
+                       dval(adj) = adj0 - .5;
+                       if (dval(adj) < -tol) {
+                               if (adj0 > tol) {
+                                       irv |= inex;
+                                       break;
+                                       }
+                               }
+                       else if (dval(adj) > tol && adj0 < 1. - tol) {
+                               irv |= inex;
+                               break;
+                               }
+                       }
+               bb0 = denorm ? 0 : trailz(rvb);
+               Bfree(bb);
+               Bfree(bd);
+               Bfree(bs);
+               Bfree(delta);
+               }
+       if (!denorm && (j = nbits - rvbits)) {
+               if (j > 0)
+                       rvb = lshift(rvb, j);
+               else
+                       rshift(rvb, -j);
+               rve -= j;
+               }
+       *expt = rve;
+       Bfree(bb);
+       Bfree(bd);
+       Bfree(bs);
+       Bfree(bd0);
+       Bfree(delta);
+       if (rve > fpi->emax) {
+ huge:
+               rvb->wds = 0;
+               irv = STRTOG_Infinite | STRTOG_Overflow | STRTOG_Inexhi;
+#ifndef NO_ERRNO
+               errno = ERANGE;
+#endif
+#ifdef INFNAN_CHECK
+ infnanexp:
+#endif
+               *expt = fpi->emax + 1;
+               }
+ ret:
+       if (denorm) {
+               if (sudden_underflow) {
+                       rvb->wds = 0;
+                       irv = STRTOG_Underflow | STRTOG_Inexlo;
+                       }
+               else  {
+                       irv = (irv & ~STRTOG_Retmask) |
+                               (rvb->wds > 0 ? STRTOG_Denormal : STRTOG_Zero);
+                       if (irv & STRTOG_Inexact)
+                               irv |= STRTOG_Underflow;
+                       }
+               }
+       if (se)
+               *se = __UNCONST(s);
+       if (sign)
+               irv |= STRTOG_Neg;
+       if (rvb) {
+               copybits(bits, nbits, rvb);
+               Bfree(rvb);
+               }
+       return irv;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtodnrp.c b/lib/nbsd_libc/gdtoa/strtodnrp.c
new file mode 100644 (file)
index 0000000..cc448bf
--- /dev/null
@@ -0,0 +1,95 @@
+/* $NetBSD: strtodnrp.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 2004 by David M. Gay.
+All Rights Reserved
+Based on material in the rest of /netlib/fp/gdota.tar.gz,
+which is copyright (C) 1998, 2000 by Lucent Technologies.
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* This is a variant of strtod that works on Intel ia32 systems */
+/* with the default extended-precision arithmetic -- it does not */
+/* require setting the precision control to 53 bits.  */
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ double
+#ifdef KR_headers
+strtod(s, sp) CONST char *s; char **sp;
+#else
+strtod(CONST char *s, char **sp)
+#endif
+{
+       static FPI fpi = { 53, 1-1023-53+1, 2046-1023-53+1, 1, SI };
+       ULong bits[2];
+       Long exp;
+       int k;
+       union { ULong L[2]; double d; } u;
+
+       k = strtodg(s, sp, &fpi, &exp, bits);
+       if (k == STRTOG_NoMemory) {
+               errno = ERANGE;
+               u.L[0] = Big0;
+               u.L[1] = Big1;
+               return u.d;
+       }
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               u.L[0] = u.L[1] = 0;
+               break;
+
+         case STRTOG_Normal:
+               u.L[_1] = bits[0];
+               u.L[_0] = (bits[1] & ~0x100000) | ((exp + 0x3ff + 52) << 20);
+               break;
+
+         case STRTOG_Denormal:
+               u.L[_1] = bits[0];
+               u.L[_0] = bits[1];
+               break;
+
+         case STRTOG_Infinite:
+               u.L[_0] = 0x7ff00000;
+               u.L[_1] = 0;
+               break;
+
+         case STRTOG_NaN:
+               u.L[0] = d_QNAN0;
+               u.L[1] = d_QNAN1;
+               break;
+
+         case STRTOG_NaNbits:
+               u.L[_0] = 0x7ff00000 | bits[1];
+               u.L[_1] = bits[0];
+         }
+       if (k & STRTOG_Neg)
+               u.L[_0] |= 0x80000000L;
+       return u.d;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtof.c b/lib/nbsd_libc/gdtoa/strtof.c
new file mode 100644 (file)
index 0000000..fb07ff6
--- /dev/null
@@ -0,0 +1,84 @@
+/* $NetBSD: strtof.c,v 1.3 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "namespace.h"
+#include "gdtoaimp.h"
+
+#ifdef __weak_alias
+__weak_alias(strtof, _strtof)
+#endif
+
+ float
+#ifdef KR_headers
+strtof(s, sp) CONST char *s; char **sp;
+#else
+strtof(CONST char *s, char **sp)
+#endif
+{
+       static CONST FPI fpi = { 24, 1-127-24+1,  254-127-24+1, 1, SI };
+       ULong bits[1];
+       Long expt;
+       int k;
+       union { ULong L[1]; float f; } u;
+
+       k = strtodg(s, sp, &fpi, &expt, bits);
+       if (k == STRTOG_NoMemory) {
+               errno = ERANGE;
+               return HUGE_VALF;
+       }
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               u.L[0] = 0;
+               break;
+
+         case STRTOG_Normal:
+         case STRTOG_NaNbits:
+               u.L[0] = (bits[0] & 0x7fffff) | ((expt + 0x7f + 23) << 23);
+               break;
+
+         case STRTOG_Denormal:
+               u.L[0] = bits[0];
+               break;
+
+         case STRTOG_Infinite:
+               u.L[0] = 0x7f800000;
+               break;
+
+         case STRTOG_NaN:
+               u.L[0] = f_QNAN;
+         }
+       if (k & STRTOG_Neg)
+               u.L[0] |= 0x80000000L;
+       return u.f;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtof_vaxf.c b/lib/nbsd_libc/gdtoa/strtof_vaxf.c
new file mode 100644 (file)
index 0000000..3710e62
--- /dev/null
@@ -0,0 +1,83 @@
+/* $NetBSD: strtof_vaxf.c,v 1.5 2008/03/28 00:56:54 he Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+/* Adapted to VAX F_floating by Klaus Klein <kleink@netbsd.org>. */
+
+#include "namespace.h"
+#include "gdtoaimp.h"
+
+#ifdef __weak_alias
+__weak_alias(strtof, _strtof)
+#endif
+
+ float
+#ifdef KR_headers
+strtof(s, sp) CONST char *s; char **sp;
+#else
+strtof(CONST char *s, char **sp)
+#endif
+{
+       static CONST FPI fpi = { 24, 1-128-1-24+1,  255-128-1-24+1, 1, SI };
+       ULong bits[1];
+       Long expt;
+       int k;
+       union { ULong L[1]; float f; } u;
+
+       k = strtodg(s, sp, &fpi, &expt, bits);
+       if (k == STRTOG_NoMemory) {
+               errno = ERANGE;
+               u.L[0] = Big0;
+               u.L[1] = Big1;
+               return u.f;
+       }
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               u.L[0] = 0;
+               break;
+
+         case STRTOG_Normal:
+               u.L[0] = ((bits[0] & 0x0000ffff) << 16) | /* FracLo */
+                        ((bits[0] & 0x007f0000) >> 16) | /* FracHi */
+                        ((expt + 128 + 1 + 23)  <<  7);  /* Exp */
+               break;
+
+         case STRTOG_Infinite:
+               u.L[0] = 0xffff7fff;
+               break;
+
+         }
+       if (k & STRTOG_Neg)
+               u.L[0] |= 0x00008000L;
+       return u.f;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtold_pQ.c b/lib/nbsd_libc/gdtoa/strtold_pQ.c
new file mode 100644 (file)
index 0000000..630d9df
--- /dev/null
@@ -0,0 +1,4 @@
+/* $NetBSD: strtold_pQ.c,v 1.1 2006/03/15 17:35:18 kleink Exp $ */
+
+#define        GDTOA_LD_FMT    Q
+#include "strtold_subr.c"
diff --git a/lib/nbsd_libc/gdtoa/strtold_px.c b/lib/nbsd_libc/gdtoa/strtold_px.c
new file mode 100644 (file)
index 0000000..779da85
--- /dev/null
@@ -0,0 +1,4 @@
+/* $NetBSD: strtold_px.c,v 1.1 2006/03/15 17:35:18 kleink Exp $ */
+
+#define        GDTOA_LD_FMT    x
+#include "strtold_subr.c"
diff --git a/lib/nbsd_libc/gdtoa/strtold_pxL.c b/lib/nbsd_libc/gdtoa/strtold_pxL.c
new file mode 100644 (file)
index 0000000..04c0193
--- /dev/null
@@ -0,0 +1,4 @@
+/* $NetBSD: strtold_pxL.c,v 1.1 2006/03/15 17:35:18 kleink Exp $ */
+
+#define        GDTOA_LD_FMT    xL
+#include "strtold_subr.c"
diff --git a/lib/nbsd_libc/gdtoa/strtold_subr.c b/lib/nbsd_libc/gdtoa/strtold_subr.c
new file mode 100644 (file)
index 0000000..3a9059f
--- /dev/null
@@ -0,0 +1,47 @@
+/* $NetBSD: strtold_subr.c,v 1.1 2006/03/15 17:35:18 kleink Exp $ */
+
+/*
+ * Written by Klaus Klein <kleink@NetBSD.org>, November 16, 2005.
+ * Public domain.
+ */
+
+/*
+ * NOTICE: This is not a standalone file.  To use it, #include it in
+ * the format-specific strtold_*.c, like so:
+ *
+ *     #define GDTOA_LD_FMT    <gdtoa extended-precision format code>
+ *     #include "strtold_subr.c"
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: strtold_subr.c,v 1.1 2006/03/15 17:35:18 kleink Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <math.h>
+#include <stdlib.h>
+#include "gdtoa.h"
+
+#ifdef __weak_alias
+__weak_alias(strtold, _strtold)
+#endif
+
+#ifndef __HAVE_LONG_DOUBLE
+#error no extended-precision long double type
+#endif
+
+#ifndef GDTOA_LD_FMT
+#error GDTOA_LD_FMT must be defined by format-specific source file
+#endif
+
+#define        STRTOP(x)       __CONCAT(strtop, x)
+
+long double
+strtold(const char *nptr, char **endptr)
+{
+       long double ld;
+
+       (void)STRTOP(GDTOA_LD_FMT)(nptr, endptr, &ld);
+       return ld;
+}
diff --git a/lib/nbsd_libc/gdtoa/strtopQ.c b/lib/nbsd_libc/gdtoa/strtopQ.c
new file mode 100644 (file)
index 0000000..2fd7ec5
--- /dev/null
@@ -0,0 +1,105 @@
+/* $NetBSD: strtopQ.c,v 1.4 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#undef _0
+#undef _1
+
+/* one or the other of IEEE_BIG_ENDIAN or IEEE_LITTLE_ENDIAN should be #defined */
+
+#ifdef IEEE_BIG_ENDIAN
+#define _0 0
+#define _1 1
+#define _2 2
+#define _3 3
+#endif
+#ifdef IEEE_LITTLE_ENDIAN
+#define _0 3
+#define _1 2
+#define _2 1
+#define _3 0
+#endif
+
+ int
+#ifdef KR_headers
+strtopQ(s, sp, V) CONST char *s; char **sp; void *V;
+#else
+strtopQ(CONST char *s, char **sp, void *V)
+#endif
+{
+       static CONST FPI fpi = { 113, 1-16383-113+1, 32766 - 16383 - 113 + 1, 1, SI };
+       ULong bits[4];
+       Long expt;
+       int k;
+       ULong *L = (ULong*)V;
+
+       k = strtodg(s, sp, &fpi, &expt, bits);
+       if (k == STRTOG_NoMemory)
+               return k;
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               L[0] = L[1] = L[2] = L[3] = 0;
+               break;
+
+         case STRTOG_Normal:
+         case STRTOG_NaNbits:
+               L[_3] = bits[0];
+               L[_2] = bits[1];
+               L[_1] = bits[2];
+               L[_0] = (bits[3] & ~0x10000) | ((expt + 0x3fff + 112) << 16);
+               break;
+
+         case STRTOG_Denormal:
+               L[_3] = bits[0];
+               L[_2] = bits[1];
+               L[_1] = bits[2];
+               L[_0] = bits[3];
+               break;
+
+         case STRTOG_Infinite:
+               L[_0] = 0x7fff0000;
+               L[_1] = L[_2] = L[_3] = 0;
+               break;
+
+         case STRTOG_NaN:
+               L[0] = ld_QNAN0;
+               L[1] = ld_QNAN1;
+               L[2] = ld_QNAN2;
+               L[3] = ld_QNAN3;
+         }
+       if (k & STRTOG_Neg)
+               L[_0] |= 0x80000000L;
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtopd.c b/lib/nbsd_libc/gdtoa/strtopd.c
new file mode 100644 (file)
index 0000000..9fe46ab
--- /dev/null
@@ -0,0 +1,53 @@
+/* $NetBSD: strtopd.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ int
+#ifdef KR_headers
+strtopd(s, sp, d) char *s; char **sp; double *d;
+#else
+strtopd(CONST char *s, char **sp, double *d)
+#endif
+{
+       static FPI fpi0 = { 53, 1-1023-53+1, 2046-1023-53+1, 1, SI };
+       ULong bits[2];
+       Long exp;
+       int k;
+
+       k = strtodg(s, sp, &fpi0, &exp, bits);
+       if (k == STRTOG_NoMemory)
+               return k;
+       ULtod((ULong*)d, bits, exp, k);
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtopdd.c b/lib/nbsd_libc/gdtoa/strtopdd.c
new file mode 100644 (file)
index 0000000..47357b9
--- /dev/null
@@ -0,0 +1,182 @@
+/* $NetBSD: strtopdd.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ int
+#ifdef KR_headers
+strtopdd(s, sp, dd) CONST char *s; char **sp; double *dd;
+#else
+strtopdd(CONST char *s, char **sp, double *dd)
+#endif
+{
+#ifdef Sudden_Underflow
+       static FPI fpi = { 106, 1-1023, 2046-1023-106+1, 1, 1 };
+#else
+       static FPI fpi = { 106, 1-1023-53+1, 2046-1023-106+1, 1, 0 };
+#endif
+       ULong bits[4];
+       Long exp;
+       int i, j, rv;
+       typedef union {
+               double d[2];
+               ULong L[4];
+               } U;
+       U *u;
+
+       rv = strtodg(s, sp, &fpi, &exp, bits);
+       if (rv == STRTOG_NoMemory)
+               return rv;
+       u = (U*)dd;
+       switch(rv & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               u->d[0] = u->d[1] = 0.;
+               break;
+
+         case STRTOG_Normal:
+               u->L[_1] = (bits[1] >> 21 | bits[2] << 11) & 0xffffffffL;
+               u->L[_0] = bits[2] >> 21 | bits[3] << 11 & 0xfffff
+                         | exp + 0x3ff + 105 << 20;
+               exp += 0x3ff + 52;
+               if (bits[1] &= 0x1fffff) {
+                       i = hi0bits(bits[1]) - 11;
+                       if (i >= exp) {
+                               i = exp - 1;
+                               exp = 0;
+                               }
+                       else
+                               exp -= i;
+                       if (i > 0) {
+                               bits[1] = bits[1] << i | bits[0] >> 32-i;
+                               bits[0] = bits[0] << i & 0xffffffffL;
+                               }
+                       }
+               else if (bits[0]) {
+                       i = hi0bits(bits[0]) + 21;
+                       if (i >= exp) {
+                               i = exp - 1;
+                               exp = 0;
+                               }
+                       else
+                               exp -= i;
+                       if (i < 32) {
+                               bits[1] = bits[0] >> 32 - i;
+                               bits[0] = bits[0] << i & 0xffffffffL;
+                               }
+                       else {
+                               bits[1] = bits[0] << i - 32;
+                               bits[0] = 0;
+                               }
+                       }
+               else {
+                       u->L[2] = u->L[3] = 0;
+                       break;
+                       }
+               u->L[2+_1] = bits[0];
+               u->L[2+_0] = bits[1] & 0xfffff | exp << 20;
+               break;
+
+         case STRTOG_Denormal:
+               if (bits[3])
+                       goto nearly_normal;
+               if (bits[2])
+                       goto partly_normal;
+               if (bits[1] & 0xffe00000)
+                       goto hardly_normal;
+               /* completely denormal */
+               u->L[2] = u->L[3] = 0;
+               u->L[_1] = bits[0];
+               u->L[_0] = bits[1];
+               break;
+
+         nearly_normal:
+               i = hi0bits(bits[3]) - 11;      /* i >= 12 */
+               j = 32 - i;
+               u->L[_0] = (bits[3] << i | bits[2] >> j) & 0xfffff
+                       | 65 - i << 20;
+               u->L[_1] = (bits[2] << i | bits[1] >> j) & 0xffffffffL;
+               u->L[2+_0] = bits[1] & (1L << j) - 1;
+               u->L[2+_1] = bits[0];
+               break;
+
+         partly_normal:
+               i = hi0bits(bits[2]) - 11;
+               if (i < 0) {
+                       j = -i;
+                       i += 32;
+                       u->L[_0] = bits[2] >> j & 0xfffff | (33 + j) << 20;
+                       u->L[_1] = (bits[2] << i | bits[1] >> j) & 0xffffffffL;
+                       u->L[2+_0] = bits[1] & (1L << j) - 1;
+                       u->L[2+_1] = bits[0];
+                       break;
+                       }
+               if (i == 0) {
+                       u->L[_0] = bits[2] & 0xfffff | 33 << 20;
+                       u->L[_1] = bits[1];
+                       u->L[2+_0] = 0;
+                       u->L[2+_1] = bits[0];
+                       break;
+                       }
+               j = 32 - i;
+               u->L[_0] = (bits[2] << i | bits[1] >> j) & 0xfffff
+                               | j + 1 << 20;
+               u->L[_1] = (bits[1] << i | bits[0] >> j) & 0xffffffffL;
+               u->L[2+_0] = 0;
+               u->L[2+_1] = bits[0] & (1L << j) - 1;
+               break;
+
+         hardly_normal:
+               j = 11 - hi0bits(bits[1]);
+               i = 32 - j;
+               u->L[_0] = bits[1] >> j & 0xfffff | j + 1 << 20;
+               u->L[_1] = (bits[1] << i | bits[0] >> j) & 0xffffffffL;
+               u->L[2+_0] = 0;
+               u->L[2+_1] = bits[0] & (1L << j) - 1;
+               break;
+
+         case STRTOG_Infinite:
+               u->L[_0] = u->L[2+_0] = 0x7ff00000;
+               u->L[_1] = u->L[2+_1] = 0;
+               break;
+
+         case STRTOG_NaN:
+               u->L[0] = u->L[2] = d_QNAN0;
+               u->L[1] = u->L[3] = d_QNAN1;
+         }
+       if (rv & STRTOG_Neg) {
+               u->L[  _0] |= 0x80000000L;
+               u->L[2+_0] |= 0x80000000L;
+               }
+       return rv;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtopf.c b/lib/nbsd_libc/gdtoa/strtopf.c
new file mode 100644 (file)
index 0000000..3bb9d5a
--- /dev/null
@@ -0,0 +1,77 @@
+/* $NetBSD: strtopf.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ int
+#ifdef KR_headers
+strtopf(s, sp, f) CONST char *s; char **sp; float *f;
+#else
+strtopf(CONST char *s, char **sp, float *f)
+#endif
+{
+       static FPI fpi = { 24, 1-127-24+1,  254-127-24+1, 1, SI };
+       ULong bits[1], *L;
+       Long exp;
+       int k;
+
+       k = strtodg(s, sp, &fpi, &exp, bits);
+       if (k == STRTOG_NoMemory)
+               return k;
+       L = (ULong*)f;
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               L[0] = 0;
+               break;
+
+         case STRTOG_Normal:
+         case STRTOG_NaNbits:
+               L[0] = bits[0] & 0x7fffff | exp + 0x7f + 23 << 23;
+               break;
+
+         case STRTOG_Denormal:
+               L[0] = bits[0];
+               break;
+
+         case STRTOG_Infinite:
+               L[0] = 0x7f800000;
+               break;
+
+         case STRTOG_NaN:
+               L[0] = f_QNAN;
+         }
+       if (k & STRTOG_Neg)
+               L[0] |= 0x80000000L;
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtopx.c b/lib/nbsd_libc/gdtoa/strtopx.c
new file mode 100644 (file)
index 0000000..c2a1227
--- /dev/null
@@ -0,0 +1,107 @@
+/* $NetBSD: strtopx.c,v 1.4 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#undef _0
+#undef _1
+
+/* one or the other of IEEE_BIG_ENDIAN or IEEE_LITTLE_ENDIAN should be #defined */
+
+#ifdef IEEE_BIG_ENDIAN
+#define _0 0
+#define _1 1
+#define _2 2
+#define _3 3
+#define _4 4
+#endif
+#ifdef IEEE_LITTLE_ENDIAN
+#define _0 4
+#define _1 3
+#define _2 2
+#define _3 1
+#define _4 0
+#endif
+
+ int
+#ifdef KR_headers
+strtopx(s, sp, V) CONST char *s; char **sp; void *V;
+#else
+strtopx(CONST char *s, char **sp, void *V)
+#endif
+{
+       static CONST FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, SI };
+       ULong bits[2];
+       Long expt;
+       int k;
+       UShort *L = (UShort*)V;
+
+       k = strtodg(s, sp, &fpi, &expt, bits);
+       if (k == STRTOG_NoMemory)
+               return k;
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               L[0] = L[1] = L[2] = L[3] = L[4] = 0;
+               break;
+
+         case STRTOG_Denormal:
+               L[_0] = 0;
+               goto normal_bits;
+
+         case STRTOG_Normal:
+         case STRTOG_NaNbits:
+               L[_0] = expt + 0x3fff + 63;
+ normal_bits:
+               L[_4] = (UShort)bits[0];
+               L[_3] = (UShort)(bits[0] >> 16);
+               L[_2] = (UShort)bits[1];
+               L[_1] = (UShort)(bits[1] >> 16);
+               break;
+
+         case STRTOG_Infinite:
+               L[_0] = 0x7fff;
+               L[_1] = L[_2] = L[_3] = L[_4] = 0;
+               break;
+
+         case STRTOG_NaN:
+               L[0] = ldus_QNAN0;
+               L[1] = ldus_QNAN1;
+               L[2] = ldus_QNAN2;
+               L[3] = ldus_QNAN3;
+               L[4] = ldus_QNAN4;
+         }
+       if (k & STRTOG_Neg)
+               L[_0] |= 0x8000;
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtopxL.c b/lib/nbsd_libc/gdtoa/strtopxL.c
new file mode 100644 (file)
index 0000000..d0890f2
--- /dev/null
@@ -0,0 +1,95 @@
+/* $NetBSD: strtopxL.c,v 1.4 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#undef _0
+#undef _1
+
+/* one or the other of IEEE_BIG_ENDIAN or IEEE_LITTLE_ENDIAN should be #defined */
+
+#ifdef IEEE_BIG_ENDIAN
+#define _0 0
+#define _1 1
+#define _2 2
+#endif
+#ifdef IEEE_LITTLE_ENDIAN
+#define _0 2
+#define _1 1
+#define _2 0
+#endif
+
+ int
+#ifdef KR_headers
+strtopxL(s, sp, V) CONST char *s; char **sp; void *V;
+#else
+strtopxL(CONST char *s, char **sp, void *V)
+#endif
+{
+       static CONST FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, SI };
+       ULong bits[2];
+       Long expt;
+       int k;
+       ULong *L = (ULong*)V;
+
+       k = strtodg(s, sp, &fpi, &expt, bits);
+       if (k == STRTOG_NoMemory)
+               return k;
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               L[0] = L[1] = L[2] = 0;
+               break;
+
+         case STRTOG_Normal:
+         case STRTOG_Denormal:
+         case STRTOG_NaNbits:
+               L[_2] = bits[0];
+               L[_1] = bits[1];
+               L[_0] = (expt + 0x3fff + 63) << 16;
+               break;
+
+         case STRTOG_Infinite:
+               L[_0] = 0x7fff << 16;
+               L[_1] = L[_2] = 0;
+               break;
+
+         case STRTOG_NaN:
+               L[0] = ld_QNAN0;
+               L[1] = ld_QNAN1;
+               L[2] = ld_QNAN2;
+         }
+       if (k & STRTOG_Neg)
+               L[_0] |= 0x80000000L;
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtorQ.c b/lib/nbsd_libc/gdtoa/strtorQ.c
new file mode 100644 (file)
index 0000000..349ef80
--- /dev/null
@@ -0,0 +1,121 @@
+/* $NetBSD: strtorQ.c,v 1.3 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#undef _0
+#undef _1
+
+/* one or the other of IEEE_BIG_ENDIAN or IEEE_LITTLE_ENDIAN should be #defined */
+
+#ifdef IEEE_BIG_ENDIAN
+#define _0 0
+#define _1 1
+#define _2 2
+#define _3 3
+#endif
+#ifdef IEEE_LITTLE_ENDIAN
+#define _0 3
+#define _1 2
+#define _2 1
+#define _3 0
+#endif
+
+ void
+#ifdef KR_headers
+ULtoQ(L, bits, exp, k) ULong *L; ULong *bits; Long exp; int k;
+#else
+ULtoQ(ULong *L, ULong *bits, Long exp, int k)
+#endif
+{
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               L[0] = L[1] = L[2] = L[3] = 0;
+               break;
+
+         case STRTOG_Normal:
+         case STRTOG_NaNbits:
+               L[_3] = bits[0];
+               L[_2] = bits[1];
+               L[_1] = bits[2];
+               L[_0] = (bits[3] & ~0x10000) | ((exp + 0x3fff + 112) << 16);
+               break;
+
+         case STRTOG_Denormal:
+               L[_3] = bits[0];
+               L[_2] = bits[1];
+               L[_1] = bits[2];
+               L[_0] = bits[3];
+               break;
+
+         case STRTOG_Infinite:
+               L[_0] = 0x7fff0000;
+               L[_1] = L[_2] = L[_3] = 0;
+               break;
+
+         case STRTOG_NaN:
+               L[0] = ld_QNAN0;
+               L[1] = ld_QNAN1;
+               L[2] = ld_QNAN2;
+               L[3] = ld_QNAN3;
+         }
+       if (k & STRTOG_Neg)
+               L[_0] |= 0x80000000L;
+       }
+
+ int
+#ifdef KR_headers
+strtorQ(s, sp, rounding, L) CONST char *s; char **sp; int rounding; void *L;
+#else
+strtorQ(CONST char *s, char **sp, int rounding, void *L)
+#endif
+{
+       static FPI fpi0 = { 113, 1-16383-113+1, 32766-16383-113+1, 1, SI };
+       FPI *fpi, fpi1;
+       ULong bits[4];
+       Long exp;
+       int k;
+
+       fpi = &fpi0;
+       if (rounding != FPI_Round_near) {
+               fpi1 = fpi0;
+               fpi1.rounding = rounding;
+               fpi = &fpi1;
+               }
+       k = strtodg(s, sp, fpi, &exp, bits);
+       if (k == STRTOG_NoMemory)
+               return k;
+       ULtoQ((ULong*)L, bits, exp, k);
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtord.c b/lib/nbsd_libc/gdtoa/strtord.c
new file mode 100644 (file)
index 0000000..b995f26
--- /dev/null
@@ -0,0 +1,100 @@
+/* $NetBSD: strtord.c,v 1.4 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ void
+#ifdef KR_headers
+ULtod(L, bits, expt, k) ULong *L; ULong *bits; Long expt; int k;
+#else
+ULtod(ULong *L, ULong *bits, Long expt, int k)
+#endif
+{
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               L[0] = L[1] = 0;
+               break;
+
+         case STRTOG_Denormal:
+               L[_1] = bits[0];
+               L[_0] = bits[1];
+               break;
+
+         case STRTOG_Normal:
+         case STRTOG_NaNbits:
+               L[_1] = bits[0];
+               L[_0] = (bits[1] & ~0x100000) | ((expt + 0x3ff + 52) << 20);
+               break;
+
+         case STRTOG_Infinite:
+               L[_0] = 0x7ff00000;
+               L[_1] = 0;
+               break;
+
+#ifdef d_QNAN0
+         case STRTOG_NaN:
+               L[0] = d_QNAN0;
+               L[1] = d_QNAN1;
+#endif
+         }
+       if (k & STRTOG_Neg)
+               L[_0] |= 0x80000000L;
+       }
+
+ int
+#ifdef KR_headers
+strtord(s, sp, rounding, d) CONST char *s; char **sp; int rounding; double *d;
+#else
+strtord(CONST char *s, char **sp, int rounding, double *d)
+#endif
+{
+       static CONST FPI fpi0 = { 53, 1-1023-53+1, 2046-1023-53+1, 1, SI };
+       CONST FPI *fpi;
+       FPI fpi1;
+       ULong bits[2];
+       Long expt;
+       int k;
+
+       fpi = &fpi0;
+       if (rounding != FPI_Round_near) {
+               fpi1 = fpi0;
+               fpi1.rounding = rounding;
+               fpi = &fpi1;
+               }
+       k = strtodg(s, sp, fpi, &expt, bits);
+       if (k == STRTOG_NoMemory)
+               return k; 
+       ULtod((/* LINTED */(U*)d)->L, bits, expt, k);
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtordd.c b/lib/nbsd_libc/gdtoa/strtordd.c
new file mode 100644 (file)
index 0000000..3e2d1aa
--- /dev/null
@@ -0,0 +1,203 @@
+/* $NetBSD: strtordd.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ void
+#ifdef KR_headers
+ULtodd(L, bits, exp, k) ULong *L; ULong *bits; Long exp; int k;
+#else
+ULtodd(ULong *L, ULong *bits, Long exp, int k)
+#endif
+{
+       int i, j;
+
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               L[0] = L[1] = L[2] = L[3] = 0;
+               break;
+
+         case STRTOG_Normal:
+               L[_1] = (bits[1] >> 21 | bits[2] << 11) & (ULong)0xffffffffL;
+               L[_0] = bits[2] >> 21 | bits[3] << 11 & 0xfffff
+                         | exp + 0x3ff + 105 << 20;
+               exp += 0x3ff + 52;
+               if (bits[1] &= 0x1fffff) {
+                       i = hi0bits(bits[1]) - 11;
+                       if (i >= exp) {
+                               i = exp - 1;
+                               exp = 0;
+                               }
+                       else
+                               exp -= i;
+                       if (i > 0) {
+                               bits[1] = bits[1] << i | bits[0] >> 32-i;
+                               bits[0] = bits[0] << i & (ULong)0xffffffffL;
+                               }
+                       }
+               else if (bits[0]) {
+                       i = hi0bits(bits[0]) + 21;
+                       if (i >= exp) {
+                               i = exp - 1;
+                               exp = 0;
+                               }
+                       else
+                               exp -= i;
+                       if (i < 32) {
+                               bits[1] = bits[0] >> 32 - i;
+                               bits[0] = bits[0] << i & (ULong)0xffffffffL;
+                               }
+                       else {
+                               bits[1] = bits[0] << i - 32;
+                               bits[0] = 0;
+                               }
+                       }
+               else {
+                       L[2] = L[3] = 0;
+                       break;
+                       }
+               L[2+_1] = bits[0];
+               L[2+_0] = bits[1] & 0xfffff | exp << 20;
+               break;
+
+         case STRTOG_Denormal:
+               if (bits[3])
+                       goto nearly_normal;
+               if (bits[2])
+                       goto partly_normal;
+               if (bits[1] & 0xffe00000)
+                       goto hardly_normal;
+               /* completely denormal */
+               L[2] = L[3] = 0;
+               L[_1] = bits[0];
+               L[_0] = bits[1];
+               break;
+
+         nearly_normal:
+               i = hi0bits(bits[3]) - 11;      /* i >= 12 */
+               j = 32 - i;
+               L[_0] = (bits[3] << i | bits[2] >> j) & 0xfffff
+                       | 65 - i << 20;
+               L[_1] = (bits[2] << i | bits[1] >> j) & 0xffffffffL;
+               L[2+_0] = bits[1] & ((ULong)1L << j) - 1;
+               L[2+_1] = bits[0];
+               break;
+
+         partly_normal:
+               i = hi0bits(bits[2]) - 11;
+               if (i < 0) {
+                       j = -i;
+                       i += 32;
+                       L[_0] = bits[2] >> j & 0xfffff | (33 + j) << 20;
+                       L[_1] = (bits[2] << i | bits[1] >> j) & 0xffffffffL;
+                       L[2+_0] = bits[1] & ((ULong)1L << j) - 1;
+                       L[2+_1] = bits[0];
+                       break;
+                       }
+               if (i == 0) {
+                       L[_0] = bits[2] & 0xfffff | 33 << 20;
+                       L[_1] = bits[1];
+                       L[2+_0] = 0;
+                       L[2+_1] = bits[0];
+                       break;
+                       }
+               j = 32 - i;
+               L[_0] = (bits[2] << i | bits[1] >> j) & 0xfffff
+                               | j + 1 << 20;
+               L[_1] = (bits[1] << i | bits[0] >> j) & 0xffffffffL;
+               L[2+_0] = 0;
+               L[2+_1] = bits[0] & (1L << j) - 1;
+               break;
+
+         hardly_normal:
+               j = 11 - hi0bits(bits[1]);
+               i = 32 - j;
+               L[_0] = bits[1] >> j & 0xfffff | j + 1 << 20;
+               L[_1] = (bits[1] << i | bits[0] >> j) & 0xffffffffL;
+               L[2+_0] = 0;
+               L[2+_1] = bits[0] & ((ULong)1L << j) - 1;
+               break;
+
+         case STRTOG_Infinite:
+               L[_0] = L[2+_0] = 0x7ff00000;
+               L[_1] = L[2+_1] = 0;
+               break;
+
+         case STRTOG_NaN:
+               L[0] = L[2] = d_QNAN0;
+               L[1] = L[3] = d_QNAN1;
+               break;
+
+         case STRTOG_NaNbits:
+               L[_1] = (bits[1] >> 21 | bits[2] << 11) & (ULong)0xffffffffL;
+               L[_0] = bits[2] >> 21 | bits[3] << 11
+                         | (ULong)0x7ff00000L;
+               L[2+_1] = bits[0];
+               L[2+_0] = bits[1] | (ULong)0x7ff00000L;
+         }
+       if (k & STRTOG_Neg) {
+               L[_0] |= 0x80000000L;
+               L[2+_0] |= 0x80000000L;
+               }
+       }
+
+ int
+#ifdef KR_headers
+strtordd(s, sp, rounding, dd) CONST char *s; char **sp; int rounding; double *dd;
+#else
+strtordd(CONST char *s, char **sp, int rounding, double *dd)
+#endif
+{
+#ifdef Sudden_Underflow
+       static FPI fpi0 = { 106, 1-1023, 2046-1023-106+1, 1, 1 };
+#else
+       static FPI fpi0 = { 106, 1-1023-53+1, 2046-1023-106+1, 1, 0 };
+#endif
+       FPI *fpi, fpi1;
+       ULong bits[4];
+       Long exp;
+       int k;
+
+       fpi = &fpi0;
+       if (rounding != FPI_Round_near) {
+               fpi1 = fpi0;
+               fpi1.rounding = rounding;
+               fpi = &fpi1;
+               }
+       k = strtodg(s, sp, fpi, &exp, bits);
+       if (k == STRTOG_NoMemory)
+               return k;
+       ULtodd((ULong*)dd, bits, exp, k);
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtorf.c b/lib/nbsd_libc/gdtoa/strtorf.c
new file mode 100644 (file)
index 0000000..8617e40
--- /dev/null
@@ -0,0 +1,93 @@
+/* $NetBSD: strtorf.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ void
+#ifdef KR_headers
+ULtof(L, bits, exp, k) ULong *L; ULong *bits; Long exp; int k;
+#else
+ULtof(ULong *L, ULong *bits, Long exp, int k)
+#endif
+{
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               *L = 0;
+               break;
+
+         case STRTOG_Normal:
+         case STRTOG_NaNbits:
+               L[0] = bits[0] & 0x7fffff | exp + 0x7f + 23 << 23;
+               break;
+
+         case STRTOG_Denormal:
+               L[0] = bits[0];
+               break;
+
+         case STRTOG_Infinite:
+               L[0] = 0x7f800000;
+               break;
+
+         case STRTOG_NaN:
+               L[0] = f_QNAN;
+         }
+       if (k & STRTOG_Neg)
+               L[0] |= 0x80000000L;
+       }
+
+ int
+#ifdef KR_headers
+strtorf(s, sp, rounding, f) CONST char *s; char **sp; int rounding; float *f;
+#else
+strtorf(CONST char *s, char **sp, int rounding, float *f)
+#endif
+{
+       static FPI fpi0 = { 24, 1-127-24+1,  254-127-24+1, 1, SI };
+       FPI *fpi, fpi1;
+       ULong bits[1];
+       Long exp;
+       int k;
+
+       fpi = &fpi0;
+       if (rounding != FPI_Round_near) {
+               fpi1 = fpi0;
+               fpi1.rounding = rounding;
+               fpi = &fpi1;
+               }
+       k = strtodg(s, sp, fpi, &exp, bits);
+       if (k == STRTOG_NoMemory)
+               return k;
+       ULtof((ULong*)f, bits, exp, k);
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtorx.c b/lib/nbsd_libc/gdtoa/strtorx.c
new file mode 100644 (file)
index 0000000..1512486
--- /dev/null
@@ -0,0 +1,123 @@
+/* $NetBSD: strtorx.c,v 1.3 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#undef _0
+#undef _1
+
+/* one or the other of IEEE_BIG_ENDIAN or IEEE_LITTLE_ENDIAN should be #defined */
+
+#ifdef IEEE_BIG_ENDIAN
+#define _0 0
+#define _1 1
+#define _2 2
+#define _3 3
+#define _4 4
+#endif
+#ifdef IEEE_LITTLE_ENDIAN
+#define _0 4
+#define _1 3
+#define _2 2
+#define _3 1
+#define _4 0
+#endif
+
+ void
+#ifdef KR_headers
+ULtox(L, bits, exp, k) UShort *L; ULong *bits; Long exp; int k;
+#else
+ULtox(UShort *L, ULong *bits, Long exp, int k)
+#endif
+{
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               L[0] = L[1] = L[2] = L[3] = L[4] = 0;
+               break;
+
+         case STRTOG_Denormal:
+               L[_0] = 0;
+               goto normal_bits;
+
+         case STRTOG_Normal:
+         case STRTOG_NaNbits:
+               L[_0] = exp + 0x3fff + 63;
+ normal_bits:
+               L[_4] = (UShort)bits[0];
+               L[_3] = (UShort)(bits[0] >> 16);
+               L[_2] = (UShort)bits[1];
+               L[_1] = (UShort)(bits[1] >> 16);
+               break;
+
+         case STRTOG_Infinite:
+               L[_0] = 0x7fff;
+               L[_1] = L[_2] = L[_3] = L[_4] = 0;
+               break;
+
+         case STRTOG_NaN:
+               L[0] = ldus_QNAN0;
+               L[1] = ldus_QNAN1;
+               L[2] = ldus_QNAN2;
+               L[3] = ldus_QNAN3;
+               L[4] = ldus_QNAN4;
+         }
+       if (k & STRTOG_Neg)
+               L[_0] |= 0x8000;
+       }
+
+ int
+#ifdef KR_headers
+strtorx(s, sp, rounding, L) CONST char *s; char **sp; int rounding; void *L;
+#else
+strtorx(CONST char *s, char **sp, int rounding, void *L)
+#endif
+{
+       static FPI fpi0 = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, SI };
+       FPI *fpi, fpi1;
+       ULong bits[2];
+       Long exp;
+       int k;
+
+       fpi = &fpi0;
+       if (rounding != FPI_Round_near) {
+               fpi1 = fpi0;
+               fpi1.rounding = rounding;
+               fpi = &fpi1;
+               }
+       k = strtodg(s, sp, fpi, &exp, bits);
+       if (k == STRTOG_NoMemory)
+               return k;
+       ULtox((UShort*)L, bits, exp, k);
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/strtorxL.c b/lib/nbsd_libc/gdtoa/strtorxL.c
new file mode 100644 (file)
index 0000000..4f11648
--- /dev/null
@@ -0,0 +1,111 @@
+/* $NetBSD: strtorxL.c,v 1.3 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 2000 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+#undef _0
+#undef _1
+
+/* one or the other of IEEE_BIG_ENDIAN or IEEE_LITTLE_ENDIAN should be #defined */
+
+#ifdef IEEE_BIG_ENDIAN
+#define _0 0
+#define _1 1
+#define _2 2
+#endif
+#ifdef IEEE_LITTLE_ENDIAN
+#define _0 2
+#define _1 1
+#define _2 0
+#endif
+
+ void
+#ifdef KR_headers
+ULtoxL(L, bits, exp, k) ULong *L; ULong *bits; Long exp; int k;
+#else
+ULtoxL(ULong *L, ULong *bits, Long exp, int k)
+#endif
+{
+       switch(k & STRTOG_Retmask) {
+         case STRTOG_NoNumber:
+         case STRTOG_Zero:
+               L[0] = L[1] = L[2] = 0;
+               break;
+
+         case STRTOG_Normal:
+         case STRTOG_Denormal:
+         case STRTOG_NaNbits:
+               L[_0] = (exp + 0x3fff + 63) << 16;
+               L[_1] = bits[1];
+               L[_2] = bits[0];
+               break;
+
+         case STRTOG_Infinite:
+               L[_0] = 0x7fff << 16;
+               L[_1] = L[_2] = 0;
+               break;
+
+         case STRTOG_NaN:
+               L[0] = ld_QNAN0;
+               L[1] = ld_QNAN1;
+               L[2] = ld_QNAN2;
+         }
+       if (k & STRTOG_Neg)
+               L[_0] |= 0x80000000L;
+       }
+
+ int
+#ifdef KR_headers
+strtorxL(s, sp, rounding, L) CONST char *s; char **sp; int rounding; void *L;
+#else
+strtorxL(CONST char *s, char **sp, int rounding, void *L)
+#endif
+{
+       static FPI fpi0 = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, SI };
+       FPI *fpi, fpi1;
+       ULong bits[2];
+       Long exp;
+       int k;
+
+       fpi = &fpi0;
+       if (rounding != FPI_Round_near) {
+               fpi1 = fpi0;
+               fpi1.rounding = rounding;
+               fpi = &fpi1;
+               }
+       k = strtodg(s, sp, fpi, &exp, bits);
+       if (k == STRTOG_NoMemory)
+               return k;
+       ULtoxL((ULong*)L, bits, exp, k);
+       return k;
+       }
diff --git a/lib/nbsd_libc/gdtoa/sum.c b/lib/nbsd_libc/gdtoa/sum.c
new file mode 100644 (file)
index 0000000..6a987a1
--- /dev/null
@@ -0,0 +1,104 @@
+/* $NetBSD: sum.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ Bigint *
+#ifdef KR_headers
+sum(a, b) Bigint *a; Bigint *b;
+#else
+sum(Bigint *a, Bigint *b)
+#endif
+{
+       Bigint *c;
+       ULong carry, *xc, *xa, *xb, *xe, y;
+#ifdef Pack_32
+       ULong z;
+#endif
+
+       if (a->wds < b->wds) {
+               c = b; b = a; a = c;
+               }
+       c = Balloc(a->k);
+       if (c == NULL)
+               return NULL;
+       c->wds = a->wds;
+       carry = 0;
+       xa = a->x;
+       xb = b->x;
+       xc = c->x;
+       xe = xc + b->wds;
+#ifdef Pack_32
+       do {
+               y = (*xa & 0xffff) + (*xb & 0xffff) + carry;
+               carry = (y & 0x10000) >> 16;
+               z = (*xa++ >> 16) + (*xb++ >> 16) + carry;
+               carry = (z & 0x10000) >> 16;
+               Storeinc(xc, z, y);
+               }
+               while(xc < xe);
+       xe += a->wds - b->wds;
+       while(xc < xe) {
+               y = (*xa & 0xffff) + carry;
+               carry = (y & 0x10000) >> 16;
+               z = (*xa++ >> 16) + carry;
+               carry = (z & 0x10000) >> 16;
+               Storeinc(xc, z, y);
+               }
+#else
+       do {
+               y = *xa++ + *xb++ + carry;
+               carry = (y & 0x10000) >> 16;
+               *xc++ = y & 0xffff;
+               }
+               while(xc < xe);
+       xe += a->wds - b->wds;
+       while(xc < xe) {
+               y = *xa++ + carry;
+               carry = (y & 0x10000) >> 16;
+               *xc++ = y & 0xffff;
+               }
+#endif
+       if (carry) {
+               if (c->wds == c->maxwds) {
+                       b = Balloc(c->k + 1);
+                       if (b == NULL)
+                               return NULL;
+                       Bcopy(b, c);
+                       Bfree(c);
+                       c = b;
+                       }
+               c->x[c->wds++] = 1;
+               }
+       return c;
+       }
diff --git a/lib/nbsd_libc/gdtoa/ulp.c b/lib/nbsd_libc/gdtoa/ulp.c
new file mode 100644 (file)
index 0000000..ef909ae
--- /dev/null
@@ -0,0 +1,72 @@
+/* $NetBSD: ulp.c,v 1.2 2006/01/25 15:27:42 kleink Exp $ */
+
+/****************************************************************
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1998, 1999 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, 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.
+
+****************************************************************/
+
+/* Please send bug reports to David M. Gay (dmg at acm dot org,
+ * with " at " changed at "@" and " dot " changed to ".").     */
+
+#include "gdtoaimp.h"
+
+ double
+ulp
+#ifdef KR_headers
+       (x) double x;
+#else
+       (double x)
+#endif
+{
+       Long L;
+       double a;
+
+       L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
+#ifndef Sudden_Underflow
+       if (L > 0) {
+#endif
+#ifdef IBM
+               L |= Exp_msk1 >> 4;
+#endif
+               word0(a) = L;
+               word1(a) = 0;
+#ifndef Sudden_Underflow
+               }
+       else {
+               L = (unsigned int)-L >> Exp_shift;
+               if (L < Exp_shift) {
+                       word0(a) = 0x80000 >> L;
+                       word1(a) = 0;
+                       }
+               else {
+                       word0(a) = 0;
+                       L -= Exp_shift;
+                       word1(a) = L >= 31 ? 1 : 1 << (31 - L);
+                       }
+               }
+#endif
+       return a;
+       }
diff --git a/lib/nbsd_libc/gdtoa/xsum0.out b/lib/nbsd_libc/gdtoa/xsum0.out
new file mode 100644 (file)
index 0000000..701b55d
--- /dev/null
@@ -0,0 +1,48 @@
+README f2477cff        14190
+arithchk.c     ebbe5bc7        4075
+dmisc.c        c8daa18 4682
+dtoa.c 6a7b6fe 16876
+g_Qfmt.c       f791d807        2839
+g__fmt.c       14dca85 2504
+g_ddfmt.c      10eae12a        3695
+g_dfmt.c       f36c1014        2503
+g_ffmt.c       fb83cfb5        2429
+g_xLfmt.c      f216a096        2686
+g_xfmt.c       ed824bf3        2775
+gdtoa.c        e29409a6        16988
+gdtoa.h        f208c204        4780
+gdtoaimp.h     e3c2a970        19441
+gethex.c       dba1616 5201
+gmisc.c        1859d016        2084
+hd_init.c      efdbe921        1797
+hexnan.c       f7ea38f9        2958
+makefile       f890b12 2932
+misc.c 1757f7fc        14252
+qnan.c efd33d64        3417
+smisc.c        e282e715        3655
+strtoIQ.c      1809dfcf        1939
+strtoId.c      f41ddac2        1931
+strtoIdd.c     f13e3bc3        2105
+strtoIf.c      f12c6af4        1875
+strtoIg.c      ef30d392        3454
+strtoIx.c      e50f716d        1960
+strtoIxL.c     ea0b821b        1931
+strtod.c       eec1df60        20532
+strtodI.c      1c2440ce        3915
+strtodg.c      f6c3dd52        19911
+strtodnrp.c    af895e9 2538
+strtof.c       1c5192d3        2073
+strtopQ.c      f116d4f0        2563
+strtopd.c      f7681c7a        1671
+strtopdd.c     9864fba 4497
+strtopf.c      eb15b627        2067
+strtopx.c      1cafe482        2618
+strtopxL.c     1e4b77e9        2373
+strtorQ.c      9360a0b 2885
+strtord.c      af5c50e 2491
+strtordd.c     1b266865        4936
+strtorf.c      f0d86e2b        2396
+strtorx.c      f19a56af        2947
+strtorxL.c     167fe87c        2704
+sum.c  f525bad9        2494
+ulp.c  1e2e148f        1864
diff --git a/lib/nbsd_libc/gen/Lint___setjmp14.c b/lib/nbsd_libc/gen/Lint___setjmp14.c
new file mode 100644 (file)
index 0000000..1d4f47f
--- /dev/null
@@ -0,0 +1,21 @@
+/* $NetBSD: Lint___setjmp14.c,v 1.3 2005/04/09 12:48:58 dsl Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <setjmp.h>
+
+/*ARGSUSED*/
+int
+__setjmp14(jmp_buf env)
+{
+       return 0;
+}
+
+/*ARGSUSED*/
+void
+__longjmp14(jmp_buf env, int val)
+{
+}
diff --git a/lib/nbsd_libc/gen/Lint___sigsetjmp14.c b/lib/nbsd_libc/gen/Lint___sigsetjmp14.c
new file mode 100644 (file)
index 0000000..7bd3da5
--- /dev/null
@@ -0,0 +1,25 @@
+/* $NetBSD: Lint___sigsetjmp14.c,v 1.2 2000/06/14 06:49:05 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <setjmp.h>
+
+/*ARGSUSED*/
+int
+__sigsetjmp14(env, savemask)
+       sigjmp_buf env;
+       int savemask;
+{
+       return (0);
+}
+
+/*ARGSUSED*/
+void
+__siglongjmp14(env, val)
+       sigjmp_buf env;
+       int val;
+{
+}
diff --git a/lib/nbsd_libc/gen/Lint__setjmp.c b/lib/nbsd_libc/gen/Lint__setjmp.c
new file mode 100644 (file)
index 0000000..f12a441
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: Lint__setjmp.c,v 1.2 2000/06/14 06:49:05 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <setjmp.h>
+
+/*ARGSUSED*/
+int
+_setjmp(env)
+       jmp_buf env;
+{
+       return (0);
+}
+
+/*ARGSUSED*/
+void
+_longjmp(env, val)
+       jmp_buf env;
+       int val;
+{
+}
diff --git a/lib/nbsd_libc/gen/Lint_alloca.c b/lib/nbsd_libc/gen/Lint_alloca.c
new file mode 100644 (file)
index 0000000..6662441
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint_alloca.c,v 1.2 2000/06/14 06:49:05 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <stdlib.h>
+
+/*ARGSUSED*/
+void *
+alloca(size)
+       size_t size;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/gen/Lint_bswap16.c b/lib/nbsd_libc/gen/Lint_bswap16.c
new file mode 100644 (file)
index 0000000..2842e6f
--- /dev/null
@@ -0,0 +1,13 @@
+/* $NetBSD: Lint_bswap16.c,v 1.3 2001/02/27 19:04:40 cgd Exp $ */
+/* Written by Manuel Bouyer. Public Domain */
+
+#include <sys/types.h>
+
+/*ARGSUSED*/
+/*LINTED prototype mismatch */
+u_int16_t
+bswap16(b16)
+       u_int16_t b16;
+{
+       return 0;
+}
diff --git a/lib/nbsd_libc/gen/Lint_bswap32.c b/lib/nbsd_libc/gen/Lint_bswap32.c
new file mode 100644 (file)
index 0000000..3c7c421
--- /dev/null
@@ -0,0 +1,12 @@
+/* $NetBSD: Lint_bswap32.c,v 1.2 2001/02/27 19:04:40 cgd Exp $ */
+/* Written by Manuel Bouyer. Public Domain */
+
+#include <sys/types.h>
+
+/*ARGSUSED*/
+u_int32_t
+bswap32(b32)
+       u_int32_t b32;
+{
+       return 0;
+}
diff --git a/lib/nbsd_libc/gen/Lint_bswap64.c b/lib/nbsd_libc/gen/Lint_bswap64.c
new file mode 100644 (file)
index 0000000..77286d7
--- /dev/null
@@ -0,0 +1,12 @@
+/* $NetBSD: Lint_bswap64.c,v 1.2 2001/02/27 19:04:40 cgd Exp $ */
+/* Written by Manuel Bouyer. Public Domain */
+
+#include <sys/types.h>
+
+/*ARGSUSED*/
+u_int64_t
+bswap64(b64)
+       u_int64_t b64;
+{
+       return 0;
+}
diff --git a/lib/nbsd_libc/gen/Lint_fabs.c b/lib/nbsd_libc/gen/Lint_fabs.c
new file mode 100644 (file)
index 0000000..fe28e2e
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint_fabs.c,v 1.2 2000/06/14 06:49:05 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <math.h>
+
+/*ARGSUSED*/
+double
+fabs(x)
+       double x;
+{
+       return (0.0);
+}
diff --git a/lib/nbsd_libc/gen/Lint_flt_rounds.c b/lib/nbsd_libc/gen/Lint_flt_rounds.c
new file mode 100644 (file)
index 0000000..b0744ad
--- /dev/null
@@ -0,0 +1,13 @@
+/* $NetBSD: Lint_flt_rounds.c,v 1.2 2000/06/14 06:49:05 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+/*ARGSUSED*/
+int
+__flt_rounds()
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/gen/Lint_fpgetmask.c b/lib/nbsd_libc/gen/Lint_fpgetmask.c
new file mode 100644 (file)
index 0000000..8c6a12e
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_fpgetmask.c,v 1.2 2000/06/14 06:49:05 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <ieeefp.h>
+
+/*ARGSUSED*/
+fp_except
+fpgetmask()
+{
+       fp_except rv = { 0 };
+
+       return (rv);
+}
diff --git a/lib/nbsd_libc/gen/Lint_fpgetround.c b/lib/nbsd_libc/gen/Lint_fpgetround.c
new file mode 100644 (file)
index 0000000..94f5f8c
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_fpgetround.c,v 1.2 2000/06/14 06:49:05 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <ieeefp.h>
+
+/*ARGSUSED*/
+fp_rnd
+fpgetround()
+{
+       fp_rnd rv = { 0 };
+
+       return (rv);
+}
diff --git a/lib/nbsd_libc/gen/Lint_fpgetsticky.c b/lib/nbsd_libc/gen/Lint_fpgetsticky.c
new file mode 100644 (file)
index 0000000..413898c
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_fpgetsticky.c,v 1.2 2000/06/14 06:49:05 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <ieeefp.h>
+
+/*ARGSUSED*/
+fp_except
+fpgetsticky()
+{
+       fp_except rv = { 0 };
+
+       return (rv);
+}
diff --git a/lib/nbsd_libc/gen/Lint_fpsetmask.c b/lib/nbsd_libc/gen/Lint_fpsetmask.c
new file mode 100644 (file)
index 0000000..f50fbba
--- /dev/null
@@ -0,0 +1,18 @@
+/* $NetBSD: Lint_fpsetmask.c,v 1.2 2000/06/14 06:49:05 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <ieeefp.h>
+
+/*ARGSUSED*/
+fp_except
+fpsetmask(m)
+       fp_except m;
+{
+       fp_except rv = { 0 };
+
+       return (rv);
+}
diff --git a/lib/nbsd_libc/gen/Lint_fpsetround.c b/lib/nbsd_libc/gen/Lint_fpsetround.c
new file mode 100644 (file)
index 0000000..9d7d216
--- /dev/null
@@ -0,0 +1,18 @@
+/* $NetBSD: Lint_fpsetround.c,v 1.2 2000/06/14 06:49:05 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <ieeefp.h>
+
+/*ARGSUSED*/
+fp_rnd
+fpsetround(r)
+       fp_rnd r;
+{
+       fp_rnd rv = { 0 };
+
+       return (rv);
+}
diff --git a/lib/nbsd_libc/gen/Lint_fpsetsticky.c b/lib/nbsd_libc/gen/Lint_fpsetsticky.c
new file mode 100644 (file)
index 0000000..22fe096
--- /dev/null
@@ -0,0 +1,18 @@
+/* $NetBSD: Lint_fpsetsticky.c,v 1.2 2000/06/14 06:49:05 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <ieeefp.h>
+
+/*ARGSUSED*/
+fp_except
+fpsetsticky(s)
+       fp_except s;
+{
+       fp_except rv = { 0 };
+
+       return (rv);
+}
diff --git a/lib/nbsd_libc/gen/Lint_frexp.c b/lib/nbsd_libc/gen/Lint_frexp.c
new file mode 100644 (file)
index 0000000..3fb1c14
--- /dev/null
@@ -0,0 +1,17 @@
+/*     $NetBSD: Lint_frexp.c,v 1.2 1998/12/02 09:47:20 christos Exp $  */
+
+/*
+ * This file placed in the public domain.
+ * Matthias Pfaller, December 6, 1997.
+ */
+
+#include <math.h>
+
+/*ARGSUSED*/
+double
+frexp(value, eptr)
+       double value;
+       int *eptr;
+{
+       return(0);
+}
diff --git a/lib/nbsd_libc/gen/Lint_ldexp.c b/lib/nbsd_libc/gen/Lint_ldexp.c
new file mode 100644 (file)
index 0000000..3cb80c0
--- /dev/null
@@ -0,0 +1,17 @@
+/*     $NetBSD: Lint_ldexp.c,v 1.2 1998/12/02 09:47:20 christos Exp $  */
+
+/*
+ * This file placed in the public domain.
+ * Matthias Pfaller, December 6, 1997.
+ */
+
+#include <math.h>
+
+/*ARGSUSED*/
+double
+ldexp(val, exp)
+       double val;
+       int exp;
+{
+       return(0);
+}
diff --git a/lib/nbsd_libc/gen/Lint_modf.c b/lib/nbsd_libc/gen/Lint_modf.c
new file mode 100644 (file)
index 0000000..1acf0ff
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint_modf.c,v 1.2 2000/06/14 06:49:05 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <math.h>
+
+/*ARGSUSED*/
+double
+modf(value, iptr)
+       double value, *iptr;
+{
+       return (0.0);
+}
diff --git a/lib/nbsd_libc/gen/Lint_resumecontext.c b/lib/nbsd_libc/gen/Lint_resumecontext.c
new file mode 100644 (file)
index 0000000..529b96f
--- /dev/null
@@ -0,0 +1,14 @@
+/*     $NetBSD: Lint_resumecontext.c,v 1.2 2003/01/18 11:38:46 thorpej Exp $   */
+
+/*
+ * This file placed in the public domain.
+ * Klaus Klein, January 26, 1999.
+ */
+
+#include <ucontext.h>
+
+/*ARGSUSED*/
+void
+_resumecontext()
+{
+}
diff --git a/lib/nbsd_libc/gen/Lint_swapcontext.c b/lib/nbsd_libc/gen/Lint_swapcontext.c
new file mode 100644 (file)
index 0000000..0e0b45e
--- /dev/null
@@ -0,0 +1,18 @@
+/*     $NetBSD: Lint_swapcontext.c,v 1.2 2003/01/18 11:38:47 thorpej Exp $     */
+
+/*
+ * This file placed in the public domain.
+ * Klaus Klein, November 29, 1998.
+ */
+
+#include <ucontext.h>
+
+/*ARGSUSED*/
+int
+swapcontext(oucp, ucp)
+       ucontext_t *oucp;
+       const ucontext_t *ucp;
+{
+
+       return (0);
+}
diff --git a/lib/nbsd_libc/gen/Makefile.inc b/lib/nbsd_libc/gen/Makefile.inc
new file mode 100644 (file)
index 0000000..1beaad0
--- /dev/null
@@ -0,0 +1,169 @@
+#      $NetBSD: Makefile.inc,v 1.173 2010/12/12 20:22:48 christos Exp $
+#      from: @(#)Makefile.inc  8.6 (Berkeley) 5/4/95
+
+# gen sources
+.PATH: ${ARCHDIR}/gen ${.CURDIR}/gen
+
+SRCS+=         _errno.c alarm.c alphasort.c arc4random.c assert.c basename.c clock.c \
+       closedir.c closefrom.c confstr.c ctermid.c ctype_.c daemon.c \
+       dehumanize_number.c devname.c dirname.c disklabel.c err.c errx.c \
+       errlist.c errno.c execl.c execle.c execlp.c execv.c execvp.c \
+       extattr.c fmtcheck.c fmtmsg.c fnmatch.c fstab.c ftok.c \
+       fts.c ftw.c getbsize.c getcap.c getcwd.c \
+       getdevmajor.c getdomainname.c getgrent.c \
+       getgrouplist.c getgroupmembership.c gethostname.c \
+       getloadavg.c getlogin.c getmntinfo.c \
+       getnetgrent.c getpagesize.c \
+       getpass.c getprogname.c getpwent.c getttyent.c \
+       getusershell.c glob.c humanize_number.c initdir.c initgroups.c \
+       isascii.c isatty.c isctype.c lockf.c nftw.c \
+       nice.c nlist.c nlist_aout.c \
+       nlist_coff.c nlist_ecoff.c nlist_elf32.c nlist_elf64.c opendir.c \
+       pause.c popen.c psignal.c pthread_atfork.c ptree.c pwcache.c \
+       pw_scan.c raise.c randomid.c rb.c readdir.c rewinddir.c \
+       scandir.c seekdir.c setdomainname.c \
+       sethostname.c setjmperr.c setmode.c setproctitle.c setprogname.c \
+       shquote.c shquotev.c sighold.c sigignore.c siginterrupt.c \
+       siglist.c signal.c signame.c sigrelse.c \
+       sigset.c sigsetops.c sleep.c \
+       stringlist.c sysconf.c sysctl.c sysctlbyname.c sysctlgetmibinfo.c \
+       sysctlnametomib.c syslog.c telldir.c time.c \
+       times.c toascii.c tolower_.c ttyname.c ttyslot.c \
+       toupper_.c ualarm.c ulimit.c uname.c unvis.c usleep.c utime.c utmp.c \
+       utmpx.c valloc.c vis.c wait.c wait3.c waitpid.c warn.c warnx.c \
+       vwarn.c vwarnx.c verr.c verrx.c wordexp.c
+
+# indirect reference stubs, to be removed soon.
+SRCS+= _err.c _errx.c \
+       _sysconf.c _verr.c _verrx.c _vwarn.c _vwarnx.c _warn.c _warnx.c
+
+# uses alloca
+COPTS.execvp.c = -Wno-stack-protector
+COPTS.execl.c = -Wno-stack-protector
+COPTS.execle.c = -Wno-stack-protector
+COPTS.execlp.c = -Wno-stack-protector
+
+# machine-dependent gen sources
+# m-d Makefile.inc must include sources for:
+#      _setjmp() bswap16() bswap32() bswap64() fabs() infinity
+#      isinf() setjmp() sigsetjmp()
+
+.include "${ARCHDIR}/gen/Makefile.inc"
+
+MAN+=  alarm.3 arc4random.3 basename.3 bswap.3 clock.3 closefrom.3 confstr.3 \
+       cpuset.3 ctermid.3 ctype.3 daemon.3 devname.3 directory.3 dirname.3 \
+       endutxent.3 err.3 exec.3 extattr.3 \
+       fmtcheck.3 fmtmsg.3 fnmatch.3 fpclassify.3 fpgetmask.3 \
+       ftok.3 fts.3 ftw.3 \
+       getbsize.3 cgetcap.3 getcwd.3 getdevmajor.3 \
+       getdomainname.3 getdiskbyname.3 getfsent.3 \
+       getgrent.3 getgrouplist.3 gethostname.3 getlastlogx.3 getloadavg.3 \
+       getmntinfo.3 getnetgrent.3 getpagesize.3 getpass.3 \
+       getprogname.3 getpwent.3 getttyent.3 getusershell.3 glob.3 \
+       humanize_number.3 \
+       initgroups.3 isalnum.3 isalpha.3 isascii.3 isblank.3 iscntrl.3 \
+       isdigit.3 isfinite.3 isgraph.3 isgreater.3 isinf.3 islower.3 isnan.3 \
+       isnormal.3 isprint.3 ispunct.3 isspace.3 isupper.3 isxdigit.3 \
+       lockf.3 _lwp_makecontext.3 makecontext.3 \
+       nice.3 nlist.3 \
+       pause.3 popen.3 psignal.3 pwcache.3 pthread_atfork.3 \
+       raise.3 randomid.3 realpath.3 scandir.3 setjmp.3 setmode.3 \
+       setproctitle.3 shquote.3 sighold.3 sigignore.3 siginterrupt.3 \
+       signal.3 signbit.3 sigrelse.3 sigset.3 sigsetops.3 sleep.3 \
+       stringlist.3 sysconf.3 sysctl.3 syslog.3 time.3 times.3 \
+       timezone.3 toascii.3 tolower.3 toupper.3 ttyname.3 \
+       ualarm.3 ulimit.3 uname.3 unvis.3 usleep.3 utime.3 valloc.3 vis.3 \
+       wordexp.3
+
+MLINKS+=bswap.3 bswap16.3 bswap.3 bswap32.3 bswap.3 bswap64.3
+MLINKS+=cpuset.3 cpuset_create.3 cpuset.3 cpuset_destroy.3 \
+       cpuset.3 cpuset_zero.3 cpuset.3 cpuset_set.3 cpuset.3 cpuset_clr.3 \
+       cpuset.3 cpuset_isset.3 cpuset.3 cpuset_size.3
+MLINKS+=directory.3 closedir.3 directory.3 dirfd.3 directory.3 opendir.3 \
+       directory.3 readdir.3 directory.3 readdir_r.3 directory.3 \
+       rewinddir.3 directory.3 seekdir.3 directory.3 telldir.3 \
+       directory.3 fdopendir.3 
+MLINKS+=endutxent.3 getutxent.3 endutxent.3 getutxid.3 \
+       endutxent.3 getutxline.3 endutxent.3 pututxline.3 \
+       endutxent.3 setutxent.3
+MLINKS+=err.3 verr.3 err.3 errx.3 err.3 verrx.3 err.3 warn.3 err.3 vwarn.3 \
+        err.3 warnx.3 err.3 vwarnx.3
+MLINKS+=exec.3 execl.3 exec.3 execle.3 exec.3 execlp.3 exec.3 execv.3 \
+       exec.3 execvp.3 exec.3 exect.3
+MLINKS+=extattr.3 extattr_namespace_to_string.3 \
+       extattr.3 extattr_string_to_namespace.3
+MLINKS+=fpgetmask.3 fpgetround.3 fpgetmask.3 fpgetsticky.3 \
+       fpgetmask.3 fpsetmask.3  fpgetmask.3 fpsetround.3 \
+       fpgetmask.3 fpsetsticky.3
+MLINKS+=fts.3 fts_open.3 fts.3 fts_read.3 fts.3 fts_children.3 \
+       fts.3 fts_set.3 fts.3 fts_close.3
+MLINKS+=ftw.3 nftw.3
+MLINKS+=cgetcap.3 cgetclose.3 cgetcap.3 cgetent.3 \
+       cgetcap.3 cgetfirst.3 cgetcap.3 cgetmatch.3 cgetcap.3 cgetnext.3 \
+       cgetcap.3 cgetnum.3 cgetcap.3 cgetset.3 cgetcap.3 cgetstr.3 \
+       cgetcap.3 cgetustr.3
+MLINKS+=getcwd.3 getwd.3
+MLINKS+=getdiskbyname.3 setdisktab.3
+MLINKS+=getdomainname.3 setdomainname.3
+MLINKS+=getfsent.3 endfsent.3 getfsent.3 getfsfile.3 getfsent.3 getfsspec.3 \
+       getfsent.3 setfsent.3
+MLINKS+=getgrent.3 endgrent.3 getgrent.3 setgroupent.3 getgrent.3 getgrgid.3 \
+       getgrent.3 getgrnam.3 getgrent.3 setgrent.3
+MLINKS+=getgrent.3 getgrgid_r.3 getgrent.3 getgrnam_r.3 getgrent.3 getgrent_r.3
+MLINKS+=getgrouplist.3 getgroupmembership.3
+MLINKS+=gethostname.3 sethostname.3
+MLINKS+=getlastlogx.3 getutmp.3 getlastlogx.3 getutmpx.3
+MLINKS+=getlastlogx.3 updlastlogx.3 getlastlogx.3 updwtmpx.3
+MLINKS+=getlastlogx.3 utmpxname.3
+MLINKS+=getnetgrent.3 endnetgrent.3 getnetgrent.3 innetgr.3 \
+       getnetgrent.3 setnetgrent.3
+MLINKS+=getprogname.3 setprogname.3
+MLINKS+=getpwent.3 endpwent.3 getpwent.3 setpassent.3 getpwent.3 getpwnam.3 \
+       getpwent.3 getpwuid.3 getpwent.3 setpwent.3
+MLINKS+=getpwent.3 getpwnam_r.3 getpwent.3 getpwuid_r.3 getpwent.3 getpwent_r.3
+# getpwent.3 setpwfile.3 - deprecated
+MLINKS+=getttyent.3 endttyent.3 getttyent.3 getttynam.3 \
+       getttyent.3 setttyent.3 getttyent.3 setttyentpath.3
+MLINKS+=getusershell.3 endusershell.3 getusershell.3 setusershell.3
+MLINKS+=glob.3 globfree.3
+MLINKS+=glob.3 glob_pattern_p.3
+MLINKS+=humanize_number.3 dehumanize_number.3
+MLINKS+=makecontext.3 swapcontext.3
+MLINKS+=popen.3 pclose.3
+MLINKS+=psignal.3 sys_siglist.3 psignal.3 sys_signame.3 psignal.3 psiginfo.3
+MLINKS+=pwcache.3 user_from_uid.3 pwcache.3 group_from_gid.3
+MLINKS+=pwcache.3 uid_from_user.3 pwcache.3 gid_from_group.3
+MLINKS+=pwcache.3 pwcache_userdb.3 pwcache.3 pwcache_groupdb.3
+MLINKS+=randomid.3 randomid_new.3 randomid.3 randomid_delete.3
+MLINKS+=scandir.3 alphasort.3
+MLINKS+=setjmp.3 _longjmp.3 setjmp.3 _setjmp.3 setjmp.3 longjmp.3 \
+       setjmp.3 longjmperror.3 setjmp.3 sigsetjmp.3 setjmp.3 siglongjmp.3
+MLINKS+=setmode.3 getmode.3
+MLINKS+=shquote.3 shquotev.3
+MLINKS+=sigsetops.3 sigemptyset.3 sigsetops.3 sigfillset.3 \
+       sigsetops.3 sigaddset.3 sigsetops.3 sigdelset.3 \
+       sigsetops.3 sigismember.3
+MLINKS+=stringlist.3 sl_init.3 stringlist.3 sl_free.3 stringlist.3 sl_add.3 \
+       stringlist.3 sl_find.3
+MLINKS+=sysctl.3 sysctlbyname.3 sysctl.3 sysctlgetmibinfo.3 \
+       sysctl.3 sysctlnametomib.3
+MLINKS+=syslog.3 closelog.3 syslog.3 openlog.3 syslog.3 setlogmask.3 \
+       syslog.3 vsyslog.3
+MLINKS+=syslog.3 closelog_r.3 syslog.3 openlog_r.3 syslog.3 setlogmask_r.3 \
+       syslog.3 syslog_r.3 syslog.3 vsyslog_r.3
+MLINKS+=syslog.3 syslogp.3 syslog.3 syslogp_r.3 \
+       syslog.3 vsyslogp.3 syslog.3 vsyslogp_r.3
+MLINKS+=ttyname.3 isatty.3 ttyname.3 ttyslot.3 ttyname.3 ttyname_r.3
+MLINKS+=unvis.3 strunvis.3 unvis.3 strunvisx.3
+MLINKS+=vis.3 svis.3 vis.3 strvis.3 vis.3 strvisx.3 vis.3 strsvis.3 \
+       vis.3 strsvisx.3
+
+CPPFLAGS.ctype_.c+=    -I${LIBCDIR}/locale
+CPPFLAGS.isctype.c+=   -I${LIBCDIR}/locale
+CPPFLAGS.tolower_.c+=  -I${LIBCDIR}/locale
+CPPFLAGS.toupper_.c+=  -I${LIBCDIR}/locale
+
+errlist.c: errlist.awk ${NETBSDSRCDIR}/sys/sys/errno.h
+       ${TOOL_AWK} -f ${.ALLSRC} > ${.TARGET}
+
+CLEANFILES+= errlist.c
diff --git a/lib/nbsd_libc/gen/_err.c b/lib/nbsd_libc/gen/_err.c
new file mode 100644 (file)
index 0000000..ddeef68
--- /dev/null
@@ -0,0 +1,30 @@
+/*     $NetBSD: _err.c,v 1.11 2005/09/13 01:44:09 christos Exp $       */
+
+/*
+ * J.T. Conklin, December 12, 1994
+ * Public Domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _err.c,v 1.11 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_err, err)
+#else
+
+#include <stdarg.h>
+
+__dead void _verr(int eval, const char *, _BSD_VA_LIST_);
+
+__dead void
+err(int eval, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       _verr(eval, fmt, ap);
+       va_end(ap);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/_errno.c b/lib/nbsd_libc/gen/_errno.c
new file mode 100644 (file)
index 0000000..257900d
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: _errno.c,v 1.13 2008/04/28 20:22:59 martin Exp $       */
+
+/*-
+ * Copyright (c) 1996 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _errno.c,v 1.13 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "reentrant.h"
+#include <errno.h>
+#include <stdlib.h>
+
+#undef errno
+extern int errno;
+
+int *
+__errno(void)
+{
+#ifdef _REENTRANT
+       if (__isthreaded == 0)
+               return &errno;
+
+       return thr_errno();
+#else
+       return &errno;
+#endif
+}
diff --git a/lib/nbsd_libc/gen/_errx.c b/lib/nbsd_libc/gen/_errx.c
new file mode 100644 (file)
index 0000000..79b5b80
--- /dev/null
@@ -0,0 +1,30 @@
+/*     $NetBSD: _errx.c,v 1.11 2005/09/13 01:44:09 christos Exp $      */
+
+/*
+ * J.T. Conklin, December 12, 1994
+ * Public Domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _errx.c,v 1.11 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_errx, errx)
+#else
+
+#include <stdarg.h>
+
+__dead void _verrx(int eval, const char *, _BSD_VA_LIST_);
+
+__dead void
+errx(int eval, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       _verrx(eval, fmt, ap);
+       va_end(ap);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/_lwp_makecontext.3 b/lib/nbsd_libc/gen/_lwp_makecontext.3
new file mode 100644 (file)
index 0000000..9994c98
--- /dev/null
@@ -0,0 +1,74 @@
+.\"    $NetBSD: _lwp_makecontext.3,v 1.4 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, 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.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 16, 2003
+.Dt _LWP_MAKECONTEXT 3
+.Os
+.Sh NAME
+.Nm _lwp_makecontext
+.Nd create a new initial light-weight process execution context
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft void
+.Fn _lwp_makecontext "ucontext_t *context" "void (*start_routine)(void *)" \
+    "void *arg" "void *private" "caddr_t stack_base" "size_t stack_size"
+.Sh DESCRIPTION
+.Fn _lwp_makecontext
+initializes the context structure pointed to by
+.Fa context
+in a manner suitable for using with
+.Xr _lwp_create 2 .
+The LWP will begin execution at the function specified by
+.Fa start_routine
+which will be passed a single argument
+.Fa arg .
+The LWP private data pointer will be set to
+.Fa private .
+The stack region for the new LWP is specified by the
+.Fa stack_base
+and
+.Fa stack_size
+arguments.
+.Pp
+The signal mask in the context structure is not initialized by
+.Fn _lwp_makecontext .
+.Sh SEE ALSO
+.Xr _lwp_create 2 ,
+.Xr _lwp_getprivate 2
+.Sh HISTORY
+The
+.Fn _lwp_create
+system call first appeared in
+.Nx 2.0 .
+.Sh BUGS
+The LWP private data pointer is not initialized by the current
+implementation of
+.Fn _lwp_makecontext .
diff --git a/lib/nbsd_libc/gen/_sysconf.c b/lib/nbsd_libc/gen/_sysconf.c
new file mode 100644 (file)
index 0000000..b4738c1
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: _sysconf.c,v 1.5 2009/10/21 01:07:45 snj Exp $ */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _sysconf.c,v 1.5 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(__sysconf, sysconf)
+#else
+
+#include <unistd.h>
+long   __sysconf __P((int));   /* XXX */
+
+long
+sysconf(name)
+       int name;
+{
+
+       return __sysconf(name);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/_verr.c b/lib/nbsd_libc/gen/_verr.c
new file mode 100644 (file)
index 0000000..1baab51
--- /dev/null
@@ -0,0 +1,25 @@
+/*     $NetBSD: _verr.c,v 1.10 2005/09/13 01:44:09 christos Exp $      */
+
+/*
+ * J.T. Conklin, December 12, 1994
+ * Public Domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _verr.c,v 1.10 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_verr, verr)
+#else
+
+__dead void _verr(int, const char *, _BSD_VA_LIST_);
+
+void
+verr(int eval, const char *fmt, _BSD_VA_LIST_ ap)
+{
+       _verr(eval, fmt, ap);
+}
+
+#endif
diff --git a/lib/nbsd_libc/gen/_verrx.c b/lib/nbsd_libc/gen/_verrx.c
new file mode 100644 (file)
index 0000000..0c161af
--- /dev/null
@@ -0,0 +1,25 @@
+/*     $NetBSD: _verrx.c,v 1.10 2005/09/13 01:44:09 christos Exp $     */
+
+/*
+ * J.T. Conklin, December 12, 1994
+ * Public Domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _verrx.c,v 1.10 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_verrx, verrx)
+#else
+
+__dead void _verrx(int, const char *, _BSD_VA_LIST_);
+
+void
+verrx(int eval, const char *fmt, _BSD_VA_LIST_ ap)
+{
+       _verrx(eval, fmt, ap);
+}
+
+#endif
diff --git a/lib/nbsd_libc/gen/_vwarn.c b/lib/nbsd_libc/gen/_vwarn.c
new file mode 100644 (file)
index 0000000..76cef1c
--- /dev/null
@@ -0,0 +1,25 @@
+/*     $NetBSD: _vwarn.c,v 1.10 2005/09/13 01:44:09 christos Exp $     */
+
+/*
+ * J.T. Conklin, December 12, 1994
+ * Public Domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _vwarn.c,v 1.10 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_vwarn, vwarn)
+#else
+
+void _vwarn(const char *, _BSD_VA_LIST_);
+
+void
+vwarn(const char *fmt, _BSD_VA_LIST_ ap)
+{
+       _vwarn(fmt, ap);
+}
+
+#endif
diff --git a/lib/nbsd_libc/gen/_vwarnx.c b/lib/nbsd_libc/gen/_vwarnx.c
new file mode 100644 (file)
index 0000000..37cdeaa
--- /dev/null
@@ -0,0 +1,25 @@
+/*     $NetBSD: _vwarnx.c,v 1.10 2005/09/13 01:44:09 christos Exp $    */
+
+/*
+ * J.T. Conklin, December 12, 1994
+ * Public Domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _vwarnx.c,v 1.10 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_vwarnx, vwarnx)
+#else
+
+void _vwarnx(const char *, _BSD_VA_LIST_);
+
+void
+vwarnx(const char *fmt, _BSD_VA_LIST_ ap)
+{
+       _vwarnx(fmt, ap);
+}
+
+#endif
diff --git a/lib/nbsd_libc/gen/_warn.c b/lib/nbsd_libc/gen/_warn.c
new file mode 100644 (file)
index 0000000..7fbed08
--- /dev/null
@@ -0,0 +1,30 @@
+/*     $NetBSD: _warn.c,v 1.10 2005/09/13 01:44:09 christos Exp $      */
+
+/*
+ * J.T. Conklin, December 12, 1994
+ * Public Domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _warn.c,v 1.10 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_warn, warn)
+#else
+
+#include <stdarg.h>
+
+void _vwarn(const char *, _BSD_VA_LIST_);
+
+void
+warn(const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       _vwarn(eval, fmt, ap);
+       va_end(ap);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/_warnx.c b/lib/nbsd_libc/gen/_warnx.c
new file mode 100644 (file)
index 0000000..a5fec8e
--- /dev/null
@@ -0,0 +1,31 @@
+/*     $NetBSD: _warnx.c,v 1.10 2005/09/13 01:44:09 christos Exp $     */
+
+/*
+ * J.T. Conklin, December 12, 1994
+ * Public Domain
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _warnx.c,v 1.10 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_warnx, warnx)
+#else
+
+#include <stdarg.h>
+
+void _vwarnx(const char *, _BSD_VA_LIST_);
+
+void
+warnx(const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       _vwarnx(eval, fmt, ap);
+       va_end(ap);
+}
+
+#endif
diff --git a/lib/nbsd_libc/gen/alarm.3 b/lib/nbsd_libc/gen/alarm.3
new file mode 100644 (file)
index 0000000..4eba883
--- /dev/null
@@ -0,0 +1,98 @@
+.\"    $NetBSD: alarm.3,v 1.22 2003/08/07 16:42:45 agc Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 1993, 1994
+.\"    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.
+.\" 3. 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.
+.\"
+.\"     @(#)alarm.3    8.2 (Berkeley) 4/19/94
+.\"
+.Dd April 19, 1994
+.Dt ALARM 3
+.Os
+.Sh NAME
+.Nm alarm
+.Nd set signal timer alarm
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft unsigned int
+.Fn alarm "unsigned int seconds"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is made obsolete by
+.Xr setitimer 2 .
+.Ef
+.Pp
+The
+.Fn alarm
+function sets a timer to deliver the signal
+.Dv SIGALRM
+to the calling process
+.Ar seconds
+after the call to
+.Fn alarm .
+If an alarm has already been set with
+.Fn alarm
+but has not been delivered, another call to
+.Fn alarm
+will supersede the prior call.
+The request
+.Fn alarm "0"
+voids the current
+alarm and the signal SIGALRM will not be delivered.
+The maximum number of
+.Ar seconds
+allowed
+is 2147483647.
+.Pp
+The return value of
+.Fn alarm
+is the amount of time left on the timer from a previous call to
+.Fn alarm .
+If no alarm is currently set, the return value is 0.
+If there is an error setting the timer,
+.Fn alarm
+returns ((unsigned int) -1).
+.Sh SEE ALSO
+.Xr setitimer 2 ,
+.Xr sigaction 2 ,
+.Xr sigsuspend 2 ,
+.Xr signal 3 ,
+.Xr sigvec 3 ,
+.Xr sleep 3 ,
+.Xr ualarm 3 ,
+.Xr usleep 3
+.Sh STANDARDS
+The
+.Fn alarm
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+An
+.Fn alarm
+function appeared in
+.At v7 .
diff --git a/lib/nbsd_libc/gen/alarm.c b/lib/nbsd_libc/gen/alarm.c
new file mode 100644 (file)
index 0000000..5ad22c1
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: alarm.c,v 1.10 2003/08/07 16:42:45 agc Exp $   */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)alarm.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: alarm.c,v 1.10 2003/08/07 16:42:45 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Backwards compatible alarm.
+ */
+#include "namespace.h"
+#include <sys/time.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(alarm,_alarm)
+#endif
+
+unsigned int
+alarm(secs)
+       unsigned int secs;
+{
+       struct itimerval it, oitv;
+       struct itimerval *itp = &it;
+
+       timerclear(&itp->it_interval);
+       itp->it_value.tv_sec = secs;
+       itp->it_value.tv_usec = 0;
+       if (setitimer(ITIMER_REAL, itp, &oitv) == -1)
+               return (unsigned int) -1;
+       if (oitv.it_value.tv_usec)
+               oitv.it_value.tv_sec++;
+       return (unsigned int)oitv.it_value.tv_sec;
+}
diff --git a/lib/nbsd_libc/gen/alphasort.c b/lib/nbsd_libc/gen/alphasort.c
new file mode 100644 (file)
index 0000000..c8310d4
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: alphasort.c,v 1.2 2009/03/01 19:59:55 christos Exp $   */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)scandir.c  8.3 (Berkeley) 1/2/94";
+#else
+__RCSID("$NetBSD: alphasort.c,v 1.2 2009/03/01 19:59:55 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <dirent.h>
+#include <string.h>
+
+/*
+ * Alphabetic order comparison routine for those who want it.
+ */
+int
+alphasort(const void *d1, const void *d2)
+{
+
+       _DIAGASSERT(d1 != NULL);
+       _DIAGASSERT(d2 != NULL);
+
+       return (strcmp((*(const struct dirent *const *)d1)->d_name,
+           (*(const struct dirent *const *)d2)->d_name));
+}
diff --git a/lib/nbsd_libc/gen/arc4random.3 b/lib/nbsd_libc/gen/arc4random.3
new file mode 100644 (file)
index 0000000..702ad78
--- /dev/null
@@ -0,0 +1,113 @@
+.\"    $NetBSD: arc4random.3,v 1.7 2005/12/26 19:40:14 perry Exp $
+.\" $OpenBSD: arc4random.3,v 1.17 2000/12/21 14:07:41 aaron Exp $
+.\"
+.\" Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"      This product includes software developed by Niels Provos.
+.\" 4. 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 ``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 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.
+.\"
+.\" Manual page, using -mandoc macros
+.\"
+.Dd April 15, 1997
+.Dt ARC4RANDOM 3
+.Os
+.Sh NAME
+.Nm arc4random ,
+.Nm arc4random_stir ,
+.Nm arc4random_addrandom
+.Nd arc4 random number generator
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft uint32_t
+.Fn arc4random "void"
+.Ft void
+.Fn arc4random_stir "void"
+.Ft void
+.Fn arc4random_addrandom "u_char *dat" "int datlen"
+.Sh DESCRIPTION
+The
+.Fn arc4random
+function provides a high quality 32-bit pseudo-random
+number very quickly.
+.Fn arc4random
+seeds itself on a regular basis from the kernel strong random number
+subsystem described in
+.Xr rnd 4 .
+On each call, an ARC4 generator is used to generate a new result.
+The
+.Fn arc4random
+function uses the ARC4 cipher key stream generator,
+which uses 8*8 8 bit S-Boxes.
+The S-Boxes can be in about (2**1700) states.
+.Pp
+.Fn arc4random
+fits into a middle ground not covered by other subsystems such as
+the strong, slow, and resource expensive random
+devices described in
+.Xr rnd 4
+versus the fast but poor quality interfaces described in
+.Xr rand 3 ,
+.Xr random 3 ,
+and
+.Xr drand48 3 .
+.Pp
+The
+.Fn arc4random_stir
+function reads data from
+.Pa /dev/urandom
+and uses it to permute the S-Boxes via
+.Fn arc4random_addrandom .
+.Pp
+There is no need to call
+.Fn arc4random_stir
+before using
+.Fn arc4random ,
+since
+.Fn arc4random
+automatically initializes itself.
+.Sh SEE ALSO
+.Xr rand 3 ,
+.Xr rand48 3 ,
+.Xr random 3
+.Sh HISTORY
+An algorithm called
+.Pa RC4
+was designed by RSA Data Security, Inc.
+It was considered a trade secret, but not trademarked.
+Because it was a trade secret, it obviously could not be patented.
+A clone of this was posted anonymously to USENET and confirmed to
+be equivalent by several sources who had access to the original cipher.
+Because of the trade secret situation, RSA Data Security, Inc. can do
+nothing about the release of the ARC4 algorithm.
+Since
+.Pa RC4
+used to be a trade secret, the cipher is now referred to as
+.Pa ARC4 .
+.Pp
+These functions first appeared in
+.Ox 2.1 .
diff --git a/lib/nbsd_libc/gen/arc4random.c b/lib/nbsd_libc/gen/arc4random.c
new file mode 100644 (file)
index 0000000..1b9f222
--- /dev/null
@@ -0,0 +1,217 @@
+/*     $NetBSD: arc4random.c,v 1.9 2005/12/24 21:11:16 perry Exp $     */
+/*     $OpenBSD: arc4random.c,v 1.6 2001/06/05 05:05:38 pvalchev Exp $ */
+
+/*
+ * Arc4 random number generator for OpenBSD.
+ * Copyright 1996 David Mazieres <dm@lcs.mit.edu>.
+ *
+ * Modification and redistribution in source and binary forms is
+ * permitted provided that due credit is given to the author and the
+ * OpenBSD project by leaving this copyright notice intact.
+ */
+
+/*
+ * 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: arc4random.c,v 1.9 2005/12/24 21:11:16 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <fcntl.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <sys/sysctl.h>
+
+#ifdef __weak_alias
+__weak_alias(arc4random,_arc4random)
+#endif
+
+struct arc4_stream {
+       u_int8_t i;
+       u_int8_t j;
+       u_int8_t s[256];
+};
+
+static int rs_initialized;
+static struct arc4_stream rs;
+
+static inline void arc4_init(struct arc4_stream *);
+static inline void arc4_addrandom(struct arc4_stream *, u_char *, int);
+static void arc4_stir(struct arc4_stream *);
+static inline u_int8_t arc4_getbyte(struct arc4_stream *);
+static inline u_int32_t arc4_getword(struct arc4_stream *);
+
+static inline void
+arc4_init(as)
+       struct arc4_stream *as;
+{
+       int     n;
+
+       for (n = 0; n < 256; n++)
+               as->s[n] = n;
+       as->i = 0;
+       as->j = 0;
+}
+
+static inline void
+arc4_addrandom(as, dat, datlen)
+       struct arc4_stream *as;
+       u_char *dat;
+       int     datlen;
+{
+       int     n;
+       u_int8_t si;
+
+       as->i--;
+       for (n = 0; n < 256; n++) {
+               as->i = (as->i + 1);
+               si = as->s[as->i];
+               as->j = (as->j + si + dat[n % datlen]);
+               as->s[as->i] = as->s[as->j];
+               as->s[as->j] = si;
+       }
+       as->j = as->i;
+}
+
+static void
+arc4_stir(as)
+       struct arc4_stream *as;
+{
+       int     fd;
+       struct {
+               struct timeval tv;
+               u_int rnd[(128 - sizeof(struct timeval)) / sizeof(u_int)];
+       }       rdat;
+       int     n;
+
+       gettimeofday(&rdat.tv, NULL);
+       fd = open("/dev/urandom", O_RDONLY);
+       if (fd != -1) {
+               read(fd, rdat.rnd, sizeof(rdat.rnd));
+               close(fd);
+       }
+#ifdef KERN_URND
+       else {
+               int mib[2];
+               u_int i;
+               size_t len;
+
+               /* Device could not be opened, we might be chrooted, take
+                * randomness from sysctl. */
+
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_URND;
+
+               for (i = 0; i < sizeof(rdat.rnd) / sizeof(u_int); i++) {
+                       len = sizeof(u_int);
+                       if (sysctl(mib, 2, &rdat.rnd[i], &len, NULL, 0) == -1)
+                               break;
+               }
+       }
+#endif
+       /* fd < 0 or failed sysctl ?  Ah, what the heck. We'll just take
+        * whatever was on the stack... */
+
+       arc4_addrandom(as, (void *) &rdat, sizeof(rdat));
+
+       /*
+        * 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_getbyte(as);
+}
+
+static inline u_int8_t
+arc4_getbyte(as)
+       struct arc4_stream *as;
+{
+       u_int8_t si, sj;
+
+       as->i = (as->i + 1);
+       si = as->s[as->i];
+       as->j = (as->j + si);
+       sj = as->s[as->j];
+       as->s[as->i] = sj;
+       as->s[as->j] = si;
+       return (as->s[(si + sj) & 0xff]);
+}
+
+static inline u_int32_t
+arc4_getword(as)
+       struct arc4_stream *as;
+{
+       u_int32_t val;
+       val = arc4_getbyte(as) << 24;
+       val |= arc4_getbyte(as) << 16;
+       val |= arc4_getbyte(as) << 8;
+       val |= arc4_getbyte(as);
+       return val;
+}
+
+void
+arc4random_stir()
+{
+       if (!rs_initialized) {
+               arc4_init(&rs);
+               rs_initialized = 1;
+       }
+       arc4_stir(&rs);
+}
+
+void
+arc4random_addrandom(dat, datlen)
+       u_char *dat;
+       int     datlen;
+{
+       if (!rs_initialized)
+               arc4random_stir();
+       arc4_addrandom(&rs, dat, datlen);
+}
+
+u_int32_t
+arc4random()
+{
+       if (!rs_initialized)
+               arc4random_stir();
+       return arc4_getword(&rs);
+}
+
+#if 0
+/*-------- Test code for i386 --------*/
+#include <stdio.h>
+#include <machine/pctr.h>
+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
diff --git a/lib/nbsd_libc/gen/assert.c b/lib/nbsd_libc/gen/assert.c
new file mode 100644 (file)
index 0000000..7cbf555
--- /dev/null
@@ -0,0 +1,141 @@
+/*     $NetBSD: assert.c,v 1.16 2005/02/09 21:35:46 kleink Exp $       */
+
+/*-
+ * Copyright (c) 1992, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)assert.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: assert.c,v 1.16 2005/02/09 21:35:46 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <syslog.h>
+
+void
+__assert13(file, line, function, failedexpr)
+       const char *file, *function, *failedexpr;
+       int line;
+{
+
+       (void)fprintf(stderr,
+           "assertion \"%s\" failed: file \"%s\", line %d%s%s%s\n",
+           failedexpr, file, line,
+           function ? ", function \"" : "",
+           function ? function : "",
+           function ? "\"" : "");
+       abort();
+       /* NOTREACHED */
+}
+
+void
+__assert(file, line, failedexpr)
+       const char *file, *failedexpr;
+       int line;
+{
+
+       __assert13(file, line, NULL, failedexpr);
+       /* NOTREACHED */
+}
+
+
+enum {
+       DIAGASSERT_ABORT =      1<<0,
+       DIAGASSERT_STDERR =     1<<1,
+       DIAGASSERT_SYSLOG =     1<<2
+};
+
+static int     diagassert_flags = -1;
+
+void
+__diagassert13(file, line, function, failedexpr)
+       const char *file, *function, *failedexpr;
+       int line;
+{
+       char buf[1024];
+
+       if (diagassert_flags == -1) {
+               char *p;
+
+               diagassert_flags = DIAGASSERT_SYSLOG;
+
+               for (p = getenv("LIBC_DIAGASSERT"); p && *p; p++) {
+                       switch (*p) {
+                       case 'a':
+                               diagassert_flags |= DIAGASSERT_ABORT;
+                               break;
+                       case 'A':
+                               diagassert_flags &= ~DIAGASSERT_ABORT;
+                               break;
+                       case 'e':
+                               diagassert_flags |= DIAGASSERT_STDERR;
+                               break;
+                       case 'E':
+                               diagassert_flags &= ~DIAGASSERT_STDERR;
+                               break;
+                       case 'l':
+                               diagassert_flags |= DIAGASSERT_SYSLOG;
+                               break;
+                       case 'L':
+                               diagassert_flags &= ~DIAGASSERT_SYSLOG;
+                               break;
+                       }
+               }
+       }
+
+       snprintf(buf, sizeof(buf),
+           "assertion \"%s\" failed: file \"%s\", line %d%s%s%s",
+           failedexpr, file, line,
+           function ? ", function \"" : "",
+           function ? function : "",
+           function ? "\"" : "");
+       if (diagassert_flags & DIAGASSERT_STDERR)
+               (void)fprintf(stderr, "%s: %s\n", getprogname(), buf);
+       if (diagassert_flags & DIAGASSERT_SYSLOG)
+               syslog(LOG_DEBUG | LOG_USER, "%s", buf);
+       if (diagassert_flags & DIAGASSERT_ABORT)
+               abort();
+}
+
+void
+__diagassert(file, line, failedexpr)
+       const char *file, *failedexpr;
+       int line;
+{
+
+       __diagassert13(file, line, NULL, failedexpr);
+}
diff --git a/lib/nbsd_libc/gen/basename.3 b/lib/nbsd_libc/gen/basename.3
new file mode 100644 (file)
index 0000000..7fe1e96
--- /dev/null
@@ -0,0 +1,95 @@
+.\"    $NetBSD: basename.3,v 1.14 2008/05/10 22:39:40 christos Exp $
+.\"
+.\" Copyright (c) 1997, 2002 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein and Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 10, 2008
+.Dt BASENAME 3
+.Os
+.Sh NAME
+.Nm basename
+.Nd return the last component of a pathname
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In libgen.h
+.Ft char *
+.Fn basename "char *path"
+.Sh DESCRIPTION
+The
+.Fn basename
+function takes the pathname pointed to by
+.Ar path
+and returns a pointer to the final component of the pathname,
+deleting any trailing
+.Sq /
+characters.
+.Pp
+If
+.Ar path
+consists entirely of
+.Sq /
+characters,
+.Fn basename
+returns a pointer to the string
+.Dq / .
+.Pp
+If
+.Ar path
+is a null pointer or points to an empty string,
+.Fn basename
+returns a pointer to the string
+.Dq \&. .
+.Sh RETURN VALUES
+The
+.Fn basename
+function returns a pointer to the final component of
+.Ar path .
+.Sh SEE ALSO
+.Xr basename 1 ,
+.Xr dirname 3
+.Sh STANDARDS
+.Bl -bullet -compact
+.It
+.St -xpg4.2
+.It
+.St -p1003.1-2001
+.El
+.Sh BUGS
+If the length of the result is longer than
+.Dv PATH_MAX
+bytes
+.Pq including the terminating nul ,
+the result will be truncated.
+.Pp
+The
+.Fn basename
+function returns a pointer to static storage that may be overwritten
+by subsequent calls to
+.Fn basename .
+This is not strictly a bug; it is explicitly allowed by
+.St -p1003.1-2001 .
diff --git a/lib/nbsd_libc/gen/basename.c b/lib/nbsd_libc/gen/basename.c
new file mode 100644 (file)
index 0000000..be5fe8f
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: basename.c,v 1.9 2009/11/24 13:34:20 tnozaki Exp $     */
+
+/*-
+ * Copyright (c) 1997, 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein and Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: basename.c,v 1.9 2009/11/24 13:34:20 tnozaki Exp $");
+#endif /* !LIBC_SCCS && !lint */
+
+#include "namespace.h"
+#include <libgen.h>
+#include <limits.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(basename,_basename)
+#endif
+
+#if !HAVE_BASENAME
+char *
+basename(char *path)
+{
+       static char result[PATH_MAX];
+       const char *p, *lastp;
+       size_t len;
+
+       /*
+        * If `path' is a null pointer or points to an empty string,
+        * return a pointer to the string ".".
+        */
+       if ((path == NULL) || (*path == '\0')) {
+               result[0] = '.';
+               result[1] = '\0';
+
+               return (result);
+       }
+
+       /* Strip trailing slashes, if any. */
+       lastp = path + strlen(path) - 1;
+       while (lastp != path && *lastp == '/')
+               lastp--;
+
+       /* Now find the beginning of this (final) component. */
+       p = lastp;
+       while (p != path && *(p - 1) != '/')
+               p--;
+
+       /* ...and copy the result into the result buffer. */
+       len = (lastp - p) + 1 /* last char */;
+       if (len > (PATH_MAX - 1))
+               len = PATH_MAX - 1;
+
+       memcpy(result, p, len);
+       result[len] = '\0';
+
+       return (result);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/bswap.3 b/lib/nbsd_libc/gen/bswap.3
new file mode 100644 (file)
index 0000000..cb8d03f
--- /dev/null
@@ -0,0 +1,54 @@
+.\" $NetBSD: bswap.3,v 1.11 2009/10/22 21:50:01 bouyer Exp $
+.\"
+.\" Copyright (c) 1998 Manuel Bouyer.
+.\"
+.\" 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 ``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 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.
+.\"
+.Dd March 17, 1998
+.Dt BSWAP 3
+.Os
+.Sh NAME
+.Nm bswap16 ,
+.Nm bswap32 ,
+.Nm bswap64
+.Nd byte-order swapping functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In machine/bswap.h
+.Ft uint16_t
+.Fn bswap16 "uint16_t"
+.Ft uint32_t
+.Fn bswap32 "uint32_t"
+.Ft uint64_t
+.Fn bswap64 "uint64_t"
+.Sh DESCRIPTION
+The
+.Fn bswap16 ,
+.Fn bswap32 ,
+and
+.Fn bswap64
+functions return the value of their argument with the bytes inverted.
+They can be used to convert 16, 32 or 64 bits integers from little to big
+endian, or vice-versa.
+.Sh SEE ALSO
+.Xr byteorder 3
diff --git a/lib/nbsd_libc/gen/cgetcap.3 b/lib/nbsd_libc/gen/cgetcap.3
new file mode 100644 (file)
index 0000000..1a43ccc
--- /dev/null
@@ -0,0 +1,623 @@
+.\"    $NetBSD: cgetcap.3,v 1.6 2009/08/19 15:43:02 joerg Exp $
+.\"
+.\" Copyright (c) 1992, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Casey Leedom of Lawrence Livermore National Laboratory.
+.\"
+.\" 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. 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.
+.\"
+.\"    @(#)getcap.3    8.4 (Berkeley) 5/13/94
+.\"
+.Dd February 1, 2008
+.Dt CGETCAP 3
+.Os
+.Sh NAME
+.Nm cgetent ,
+.Nm cgetset ,
+.Nm cgetmatch ,
+.Nm cgetcap ,
+.Nm cgetnum ,
+.Nm cgetstr ,
+.Nm cgetustr ,
+.Nm cgetfirst ,
+.Nm cgetnext ,
+.Nm cgetclose ,
+.Nm cexpandtc
+.Nd capability database access routines
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn cgetent "char **buf" "const char * const *db_array" "const char *name"
+.Ft int
+.Fn cgetset "const char *ent"
+.Ft int
+.Fn cgetmatch "const char *buf" "const char *name"
+.Ft char *
+.Fn cgetcap "char *buf" "const char *cap" "int type"
+.Ft int
+.Fn cgetnum "char *buf" "const char *cap" "long *num"
+.Ft int
+.Fn cgetstr "char *buf" "const char *cap" "char **str"
+.Ft int
+.Fn cgetustr "char *buf" "const char *cap" "char **str"
+.Ft int
+.Fn cgetfirst "char **buf" "const char * const *db_array"
+.Ft int
+.Fn cgetnext "char **buf" "const char * const *db_array"
+.Ft int
+.Fn cgetclose "void"
+.Ft void
+.Fn csetexpandtc "int expandtc"
+.Sh DESCRIPTION
+.Fn cgetent
+extracts the capability
+.Fa name
+from the database specified by the
+.Dv NULL
+terminated file array
+.Fa db_array
+and returns a pointer to a
+.Xr malloc 3 Ap d
+copy of it in
+.Fa buf .
+.Fn cgetent
+will first look for files ending in
+.Pa .db
+(see
+.Xr cap_mkdb 1 )
+before accessing the
+.Tn ASCII
+file.
+.Pp
+.Fa buf
+must be retained through all subsequent calls to
+.Fn cgetmatch ,
+.Fn cgetcap ,
+.Fn cgetnum ,
+.Fn cgetstr ,
+and
+.Fn cgetustr ,
+but may then be
+.Xr free 3 Ap d .
+.Pp
+On success 0 is returned, 1 if the returned record contains an unresolved
+.Qq tc
+expansion, \-1 if the requested record couldn't be found, \-2 if
+a system error was encountered (couldn't open/read a file, etc.)
+also setting
+.Va errno ,
+and \-3 if a potential reference loop is detected (see
+.Qq tc=name
+comments below).
+.Pp
+.Fn cgetset
+enables the addition of a character buffer containing a single capability
+record entry to the capability database.
+Conceptually, the entry is added as the first
+.Dq file
+in the database, and
+is therefore searched first on the call to
+.Fn cgetent .
+The entry is passed in
+.Fa ent .
+If
+.Fa ent
+is
+.Dv NULL ,
+the current entry is removed from the database.
+.Pp
+.Fn cgetset
+must precede the database traversal.
+It must be called before the
+.Fn cgetent
+call.
+If a sequential access is being performed (see below), it must be called
+before the first sequential access call
+.Po
+.Fn cgetfirst
+or
+.Fn cgetnext
+.Pc ,
+or be directly preceded by a
+.Fn cgetclose
+call.
+On success 0 is returned and \-1 on failure.
+.Pp
+.Fn cgetmatch
+will return 0 if
+.Fa name
+is one of the names of the capability record
+.Fa buf ,
+\-1 if not.
+.Pp
+.Fn cgetcap
+searches the capability record
+.Fa buf
+for the capability
+.Fa cap
+with type
+.Fa type .
+A
+.Fa type
+is specified using any single character.
+If a colon
+.Pq Sq \&:
+is used, an untyped capability will be searched
+for (see below for explanation of types).
+A pointer to the value of
+.Fa cap
+in
+.Fa buf
+is returned on success,
+.Dv NULL
+if the requested capability couldn't be found.
+The end of the capability value is signaled by a
+.Sq \&:
+or
+.Tn ASCII
+.Dv NUL
+(see below for capability database syntax).
+.Pp
+.Fn cgetnum
+retrieves the value of the numeric capability
+.Fa cap
+from the capability record pointed to by
+.Fa buf .
+The numeric value is returned in the
+.Ft long
+pointed to by
+.Fa num .
+0 is returned on success,
+\-1 if the requested numeric capability couldn't be found.
+.Pp
+.Fn cgetstr
+retrieves the value of the string capability
+.Fa cap
+from the capability record pointed to by
+.Fa buf .
+A pointer to a decoded,
+.Dv NUL
+terminated,
+.Xr malloc 3 Ap d
+copy of the string is returned in the
+.Ft char *
+pointed to by
+.Fa str .
+The number of characters in the decoded string not including the trailing
+.Dv NUL
+is returned on success, \-1 if the requested string capability couldn't
+be found, \-2 if a system error was encountered (storage allocation
+failure).
+.Pp
+.Fn cgetustr
+is identical to
+.Fn cgetstr
+except that it does not expand special characters, but rather returns each
+character of the capability string literally.
+.Pp
+.Fn cgetfirst ,
+.Fn cgetnext ,
+comprise a function group that provides for sequential access of the
+.Dv NULL
+pointer terminated array of file names,
+.Fa db_array .
+.Fn cgetfirst
+returns the first record in the database and resets the access
+to the first record.
+.Fn cgetnext
+returns the next record in the database with respect to the
+record returned by the previous
+.Fn cgetfirst
+or
+.Fn cgetnext
+call.
+If there is no such previous call,
+the first record in the database is returned.
+Each record is returned in a
+.Xr malloc 3 Ap d
+copy pointed to by
+.Fa buf .
+.Qq tc
+expansion is done (see
+.Qq tc=name
+comments below).
+.Pp
+Upon completion of the database 0 is returned,  1 is returned upon successful
+return of record with possibly more remaining (we haven't reached the end of
+the database yet), 2 is returned if the record contains an unresolved
+.Qq tc
+expansion, \-1 is returned if an system error occurred, and \-2
+is returned if a potential reference loop is detected (see
+.Qq tc=name
+comments below).
+Upon completion of database (0 return) the database is closed.
+.Pp
+.Fn cgetclose
+closes the sequential access and frees any memory and file descriptors
+being used.
+Note that it does not erase the buffer pushed by a call to
+.Fn cgetset .
+.Sh CAPABILITY DATABASE SYNTAX
+Capability databases are normally
+.Tn ASCII
+and may be edited with standard text editors.
+Blank lines and lines beginning with a
+.Sq #
+are comments and are ignored.
+Lines ending with a
+.Sq \|\e
+indicate that the next line is a continuation
+of the current line; the
+.Sq \|\e
+and following newline are ignored.
+Long lines are usually continued onto several physical
+lines by ending each line except the last with a
+.Sq \|\e .
+.Pp
+Capability databases consist of a series of records, one per logical line.
+Each record contains a variable number of
+.So \&: Sc Ns -separated
+fields (capabilities).
+Empty fields consisting entirely of white space
+characters (spaces and tabs) are ignored.
+.Pp
+The first capability of each record specifies its names, separated by
+.Sq |
+characters.
+These names are used to reference records in the database.
+By convention, the last name is usually a comment and is not intended as
+a lookup tag.
+For example, the
+.Em vt100
+record from the
+.Pa termcap
+database begins:
+.Pp
+.Dl "d0\||\|vt100\||\|vt100-am\||\|vt100am\||\|dec vt100:"
+.Pp
+giving four names that can be used to access the record.
+.Pp
+The remaining non-empty capabilities describe a set of (name, value)
+bindings, consisting of a name optionally followed by a typed value:
+.Bl -column "nameTvalue"
+.It name Ta "typeless [boolean] capability"
+.Em name No "is present [true]"
+.It name Ns Em \&T Ns value Ta capability
+.Pq Em name , \&T
+has value
+.Em value
+.It name@ Ta "no capability" Em name No exists
+.It name Ns Em T Ns \&@ Ta capability
+.Pq Em name , T
+does not exist
+.El
+.Pp
+Names consist of one or more characters.
+Names may contain any character except
+.Sq \&: ,
+but it's usually best
+to restrict them to the printable characters and avoid use of
+graphics like
+.Sq # ,
+.Sq = ,
+.Sq % ,
+.Sq @ ,
+etc.
+.Pp
+Types are single characters used to separate capability names from
+their associated typed values.
+Types may be any character except a
+.Sq \&: .
+Typically, graphics like
+.Sq # ,
+.Sq = ,
+.Sq % ,
+etc. are used.
+Values may be any number of characters and may contain any character except
+.Sq \&: .
+.Sh CAPABILITY DATABASE SEMANTICS
+Capability records describe a set of (name, value) bindings.
+Names may have multiple values bound to them.
+Different values for a name are distinguished by their
+.Fa types .
+.Fn cgetcap
+will return a pointer to a value of a name given the capability name and
+the type of the value.
+.Pp
+The types
+.Sq #
+and
+.Sq =
+are conventionally used to denote numeric and
+string typed values, but no restriction on those types is enforced.
+The functions
+.Fn cgetnum
+and
+.Fn cgetstr
+can be used to implement the traditional syntax and semantics of
+.Sq #
+and
+.Sq = .
+Typeless capabilities are typically used to denote boolean objects with
+presence or absence indicating truth and false values respectively.
+This interpretation is conveniently represented by:
+.Pp
+.Dl "(getcap(buf, name, ':') != NULL)"
+.Pp
+A special capability,
+.Qq tc=name ,
+is used to indicate that the record specified by
+.Fa name
+should be substituted for the
+.Qq tc
+capability.
+.Qq tc
+capabilities may interpolate records which also contain
+.Qq tc
+capabilities and more than one
+.Qq tc
+capability may be used in a record.
+A
+.Qq tc
+expansion scope (i.e. where the argument is searched for) contains the
+file in which the
+.Qq tc
+is declared and all subsequent files in the file array.
+.Pp
+.Fn csetexpandtc
+can be used to control if
+.Qq tc
+expansion is performed or not.
+.Pp
+When a database is searched for a capability record, the first matching
+record in the search is returned.
+When a record is scanned for a capability, the first matching
+capability is returned; the capability
+.Qq :nameT@:
+will hide any following definition of a value of type
+.Em T
+for
+.Fa name ;
+and the capability
+.Qq :name@:
+will prevent any following values of
+.Fa name
+from being seen.
+.Pp
+These features combined with
+.Qq tc
+capabilities can be used to generate variations of other databases and
+records by either adding new capabilities, overriding definitions with new
+definitions, or hiding following definitions via
+.Sq @
+capabilities.
+.Sh EXAMPLES
+.Bd -unfilled -offset indent
+example\||\|an example of binding multiple values to names:\e
+       :foo%bar:foo^blah:foo@:\e
+       :abc%xyz:abc^frap:abc$@:\e
+       :tc=more:
+.Ed
+.Pp
+The capability
+.Em foo
+has two values bound to it
+.Po
+.Em bar
+of type
+.Sq %
+and
+.Em blah
+of type
+.Sq ^
+.Pc
+and any other value bindings are hidden.
+The capability
+.Em abc
+also has two values bound but only a value of type
+.Sq $
+is prevented from
+being defined in the capability record more.
+.Pp
+.Bd -unfilled -offset indent
+file1:
+       new\||\|new_record\||\|a modification of "old":\e
+               :fript=bar:who-cares@:tc=old:blah:tc=extensions:
+file2:
+       old\||\|old_record\||\|an old database record:\e
+               :fript=foo:who-cares:glork#200:
+.Ed
+.Pp
+The records are extracted by calling
+.Fn cgetent
+with
+.Fa file1
+preceding
+.Fa file2 .
+In the capability record
+.Em new
+in
+.Fa file1 ,
+.Qq fript=bar
+overrides the definition of
+.Qq fript=foo
+interpolated from the capability record
+.Em old
+in
+.Fa file2 ,
+.Qq who-cares@
+prevents the definition of any who-cares definitions in
+.Em old
+from being seen,
+.Qq glork#200
+is inherited from
+.Em old ,
+and
+.Em blah
+and anything defined by the record extensions is added to those
+definitions in
+.Em old .
+Note that the position of the
+.Qq fript=bar
+and
+.Qq who-cares@
+definitions before
+.Qq tc=old
+is important here.
+If they were after, the definitions in
+.Em old
+would take precedence.
+.Sh CGETNUM AND CGETSTR SYNTAX AND SEMANTICS
+Two types are predefined by
+.Fn cgetnum
+and
+.Fn cgetstr :
+.Bl -column "nameXnumber"
+.It Em name Ns \&# Ns Em number Ta numeric
+capability
+.Em name
+has value
+.Em number
+.It Em name Ns = Ns Em string Ta "string capability"
+.Em name
+has value
+.Em string
+.It Em name Ns \&#@ Ns Ta "the numeric capability"
+.Em name
+does not exist
+.It Em name Ns \&=@ Ns Ta "the string capability"
+.Em name
+does not exist
+.El
+.Pp
+Numeric capability values may be given in one of three numeric bases.
+If the number starts with either
+.Ql 0x
+or
+.Ql 0X
+it is interpreted as a hexadecimal number (both upper and lower case a-f
+may be used to denote the extended hexadecimal digits).
+Otherwise, if the number starts with a
+.Ql 0
+it is interpreted as an octal number.
+Otherwise the number is interpreted as a decimal number.
+.Pp
+String capability values may contain any character.
+Non-printable
+.Dv ASCII
+codes, new lines, and colons may be conveniently represented by the use
+of escape sequences:
+.Bl -column "\e\|X,X\e\|X" "(ASCII octal nnn)"
+.It ^X ('\fIX\fP' \*[Am] 037)  control-\fIX\fP
+.It \e\|b, \e\|B       (ASCII 010)     backspace
+.It \e\|t, \e\|T       (ASCII 011)     tab
+.It \e\|n, \e\|N       (ASCII 012)     line feed (newline)
+.It \e\|f, \e\|F       (ASCII 014)     form feed
+.It \e\|r, \e\|R       (ASCII 015)     carriage return
+.It \e\|e, \e\|E       (ASCII 027)     escape
+.It \e\|c, \e\|C       (:)     colon
+.It \e\|\e     (\e\|)  back slash
+.It \e\|^      (^)     caret
+.It \e\|\fInnn\fP      (ASCII octal \fInnn\fP)
+.El
+.Pp
+A
+.Sq \|\e
+followed by up to three octal digits directly specifies
+the numeric code for a character.
+The use of
+.Tn ASCII
+.Dv NUL Ns s ,
+while easily
+encoded, causes all sorts of problems and must be used with care since
+.Dv NUL Ns s
+are typically used to denote the end of strings; many applications
+use
+.Sq \e\|200
+to represent a
+.Dv NUL .
+.Sh DIAGNOSTICS
+.Fn cgetent ,
+.Fn cgetset ,
+.Fn cgetmatch ,
+.Fn cgetnum ,
+.Fn cgetstr ,
+.Fn cgetustr ,
+.Fn cgetfirst ,
+and
+.Fn cgetnext
+return a value greater than or equal to 0 on success and a value less
+than 0 on failure.
+.Fn cgetcap
+returns a character pointer on success and a
+.Dv NULL
+on failure.
+.Pp
+.Fn cgetclose ,
+.Fn cgetent ,
+.Fn cgetfirst ,
+and
+.Fn cgetnext
+may fail and set
+.Va errno
+for any of the errors specified for the library functions:
+.Xr fopen 3 ,
+.Xr fclose 3 ,
+.Xr open 2 ,
+and
+.Xr close 2 .
+.Pp
+.Fn cgetent ,
+.Fn cgetset ,
+.Fn cgetstr ,
+and
+.Fn cgetustr
+may fail and set
+.Va errno
+as follows:
+.Bl -tag -width Er
+.It Bq Er ENOMEM
+No memory to allocate.
+.El
+.Sh SEE ALSO
+.Xr cap_mkdb 1 ,
+.Xr malloc 3
+.Sh BUGS
+Colons
+.Pq Sq \&:
+can't be used in names, types, or values.
+.Pp
+There are no checks for
+.Qq tc=name
+loops in
+.Fn cgetent .
+.Pp
+The buffer added to the database by a call to
+.Fn cgetset
+is not unique to the database but is rather prepended to any database used.
diff --git a/lib/nbsd_libc/gen/clock.3 b/lib/nbsd_libc/gen/clock.3
new file mode 100644 (file)
index 0000000..678e7ac
--- /dev/null
@@ -0,0 +1,66 @@
+.\"    $NetBSD: clock.3,v 1.10 2003/08/07 16:42:46 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)clock.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt CLOCK 3
+.Os
+.Sh NAME
+.Nm clock
+.Nd determine processor time used
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Ft clock_t
+.Fn clock void
+.Sh DESCRIPTION
+The
+.Fn clock
+function
+determines the amount of processor time used since the invocation of the
+calling process, measured in
+.Dv CLOCKS_PER_SEC Ns s .
+.Sh RETURN VALUES
+The
+.Fn clock
+function returns the amount of time used unless an error occurs, in which
+case the return value is \-1.
+.Sh SEE ALSO
+.Xr getrusage 2
+.Sh STANDARDS
+The
+.Fn clock
+function conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/gen/clock.c b/lib/nbsd_libc/gen/clock.c
new file mode 100644 (file)
index 0000000..a50e9d4
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: clock.c,v 1.10 2009/01/11 02:46:27 christos Exp $      */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)clock.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: clock.c,v 1.10 2009/01/11 02:46:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/param.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+
+#include <time.h>
+
+/*
+ * This code is all rather silly because the kernel counts actual
+ * execution time (to usec accuracy) then splits it into user, system and
+ * interrupt based on when clock ticks happen.  getrusage apportions the
+ * time based on the number of ticks, and here we are trying to generate
+ * a number which was, traditionally, the number of ticks!
+ *
+ * Due to the way the time is apportioned, this code (and indeed getrusage
+ * itself) are not guaranteed monotonic.
+ */
+
+clock_t
+clock(void)
+{
+       struct rusage ru;
+       clock_t hz = CLOCKS_PER_SEC;
+
+       if (getrusage(RUSAGE_SELF, &ru))
+               return ((clock_t) -1);
+       return (clock_t)((ru.ru_utime.tv_sec + ru.ru_stime.tv_sec) * hz +
+           (ru.ru_utime.tv_usec + ru.ru_stime.tv_usec + 50)
+           / 100 * hz / 10000);
+}
diff --git a/lib/nbsd_libc/gen/closedir.c b/lib/nbsd_libc/gen/closedir.c
new file mode 100644 (file)
index 0000000..4320197
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: closedir.c,v 1.16 2010/09/26 02:26:59 yamt Exp $       */
+
+/*
+ * Copyright (c) 1983, 1993
+ *     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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)closedir.c 8.1 (Berkeley) 6/10/93";
+#else
+__RCSID("$NetBSD: closedir.c,v 1.16 2010/09/26 02:26:59 yamt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include "extern.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <dirent.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "dirent_private.h"
+
+#ifdef __weak_alias
+__weak_alias(closedir,_closedir)
+#endif
+
+/*
+ * close a directory.
+ */
+int
+closedir(DIR *dirp)
+{
+       int fd;
+
+       _DIAGASSERT(dirp != NULL);
+
+#ifdef _REENTRANT
+       if (__isthreaded)
+               mutex_lock((mutex_t *)dirp->dd_lock);
+#endif
+       fd = dirp->dd_fd;
+       dirp->dd_fd = -1;
+       _finidir(dirp);
+
+#ifdef _REENTRANT
+       if (__isthreaded) {
+               mutex_unlock((mutex_t *)dirp->dd_lock);
+               mutex_destroy((mutex_t *)dirp->dd_lock);
+               free(dirp->dd_lock);
+       }
+#endif
+       free((void *)dirp);
+       return(close(fd));
+}
diff --git a/lib/nbsd_libc/gen/closefrom.3 b/lib/nbsd_libc/gen/closefrom.3
new file mode 100644 (file)
index 0000000..82368a0
--- /dev/null
@@ -0,0 +1,61 @@
+.\"    $NetBSD: closefrom.3,v 1.5 2004/06/01 16:12:51 kleink Exp $
+.\"    $OpenBSD: closefrom.2,v 1.2 2004/01/12 20:52:09 jmc Exp $
+.\"
+.\" Copyright (c) 2004 Ted Unangst.  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.
+.Dd June 1, 2004
+.Dt CLOSEFROM 3
+.Os
+.Sh NAME
+.Nm closefrom
+.Nd delete many descriptors
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn closefrom "int fd"
+.Sh DESCRIPTION
+The
+.Fn closefrom
+call deletes all descriptors numbered
+.Fa fd
+and higher from the per-process file descriptor table.
+It is effectively the same as calling
+.Xr close 2
+on each descriptor.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn closefrom
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa fd
+is invalid.
+.It Bq Er EINTR
+An interrupt was received.
+.El
+.Sh SEE ALSO
+.Xr close 2
diff --git a/lib/nbsd_libc/gen/closefrom.c b/lib/nbsd_libc/gen/closefrom.c
new file mode 100644 (file)
index 0000000..4d84c09
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: closefrom.c,v 1.2 2004/06/22 13:49:43 atatat Exp $     */
+
+/*
+ * Copyright (C) 2004 WIDE Project.
+ * 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.
+ * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: closefrom.c,v 1.2 2004/06/22 13:49:43 atatat Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <fcntl.h>
+#include <unistd.h>
+
+int
+closefrom(int fd)
+{
+
+       return (fcntl(fd, F_CLOSEM));
+}
diff --git a/lib/nbsd_libc/gen/confstr.3 b/lib/nbsd_libc/gen/confstr.3
new file mode 100644 (file)
index 0000000..17c5a5e
--- /dev/null
@@ -0,0 +1,134 @@
+.\"    $NetBSD: confstr.3,v 1.20 2010/04/22 08:00:34 jruoho Exp $
+.\"
+.\" Copyright (c) 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.
+.\" 3. 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.
+.\"
+.\"    @(#)confstr.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 22, 2010
+.Dt CONFSTR 3
+.Os
+.Sh NAME
+.Nm confstr
+.Nd get string-valued configurable variables
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft size_t
+.Fn confstr "int name" "char *buf" "size_t len"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is obsoleted by
+.Xr sysctl 3 .
+.Ef
+.Pp
+The
+.Fn confstr
+function provides a method for applications to get configuration
+defined string values.
+.Pp
+The
+.Fa name
+argument specifies the system variable to be queried.
+Symbolic constants for each name value are found in the
+.In unistd.h
+header.
+The
+.Fa len
+argument specifies the size of the buffer referenced by the
+argument
+.Fa buf .
+If
+.Fa len
+is non-zero,
+.Fa buf
+is a non-null pointer, and
+.Fa name
+has a value, up to
+.Fa len
+\- 1 bytes of the value are copied into the buffer
+.Fa buf .
+The copied value is always null terminated.
+.Pp
+The available values are as follows:
+.Pp
+.Bl -tag -width "123456"
+.It Li _CS_PATH
+Return a value for the
+.Ev PATH
+environment variable that finds all the standard utilities.
+.El
+.Sh RETURN VALUES
+If the call to
+.Nm confstr
+is not successful, 0 is returned and
+.Va errno
+is set appropriately.
+Otherwise, if the variable does not have a configuration defined value,
+0 is returned and
+.Va errno
+is not modified.
+Otherwise, the buffer size needed to hold the entire configuration-defined
+value is returned.
+If this size is greater than the argument
+.Fa len ,
+the string in
+.Fa buf
+was truncated.
+.Sh ERRORS
+The
+.Nm confstr
+function may fail and set
+.Va error
+for any of the errors specified for the library functions
+.Xr malloc 3
+and
+.Xr sysctl 3 .
+.Pp
+In addition, the following errors may be reported:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The value of the
+.Fa name
+argument is invalid.
+.El
+.Sh SEE ALSO
+.Xr sysctl 3
+.Sh STANDARDS
+The
+.Nm confstr
+function conforms to
+.St -p1003.2-92 .
+.Sh HISTORY
+The
+.Nm confstr
+function first appeared in
+.Bx 4.4 .
+.Sh BUGS
+The standards require us to return 0 both on errors, and when the value
+is not set.
diff --git a/lib/nbsd_libc/gen/confstr.c b/lib/nbsd_libc/gen/confstr.c
new file mode 100644 (file)
index 0000000..4641e94
--- /dev/null
@@ -0,0 +1,98 @@
+/*     $NetBSD: confstr.c,v 1.12 2006/12/03 00:39:19 christos Exp $    */
+
+/*-
+ * Copyright (c) 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)confstr.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: confstr.c,v 1.12 2006/12/03 00:39:19 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/sysctl.h>
+
+#include <errno.h>
+#include <paths.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(confstr,_confstr)
+#endif
+
+size_t
+confstr(name, buf, len)
+       int name;
+       char *buf;
+       size_t len;
+{
+       size_t tlen;
+       int mib[2], sverrno;
+       char *p;
+
+       /*
+        * POSIX 1003.2 requires errors to return 0 --
+        * that is *really* useful.
+        */
+       switch (name) {
+       case _CS_PATH:
+               mib[0] = CTL_USER;
+               mib[1] = USER_CS_PATH;
+               if (sysctl(mib, 2, NULL, &tlen, NULL, 0) == -1)
+                       return 0;
+               if (len != 0 && buf != NULL) {
+                       if ((p = malloc(tlen)) == NULL)
+                               return 0;
+                       if (sysctl(mib, 2, p, &tlen, NULL, 0) == -1) {
+                               sverrno = errno;
+                               free(p);
+                               errno = sverrno;
+                               return 0;
+                       }
+                       /*
+                        * POSIX 1003.2 requires partial return of
+                        * the string -- that is even more useful.
+                        */
+                       (void)strncpy(buf, p, len - 1);
+                       buf[len - 1] = '\0';
+                       free(p);
+               }
+               return tlen + 1;
+       default:
+               errno = EINVAL;
+               return 0;
+       }
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/gen/cpuset.3 b/lib/nbsd_libc/gen/cpuset.3
new file mode 100644 (file)
index 0000000..e27ef04
--- /dev/null
@@ -0,0 +1,118 @@
+.\"    $NetBSD: cpuset.3,v 1.3 2008/09/12 13:39:04 rmind Exp $
+.\"
+.\" Copyright (c) 2008 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Mindaugas Rasiukevicius <rmind at NetBSD org>.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd September 12, 2008
+.Dt CPUSET 3
+.Os
+.Sh NAME
+.Nm cpuset_create ,
+.Nm cpuset_destroy ,
+.Nm cpuset_zero ,
+.Nm cpuset_set ,
+.Nm cpuset_clr ,
+.Nm cpuset_isset ,
+.Nm cpuset_size
+.Nd dynamic CPU sets
+.Sh SYNOPSIS
+.In sched.h
+.Ft cpuset_t
+.Fn cpuset_create "void"
+.Ft void
+.Fn cpuset_destroy "cpuset_t *set"
+.Ft void
+.Fn cpuset_zero "cpuset_t *set"
+.Ft int
+.Fn cpuset_set "cpuid_t cpu" "cpuset_t *set"
+.Ft int
+.Fn cpuset_clr "cpuid_t cpu" "cpuset_t *set"
+.Ft int
+.Fn cpuset_isset "cpuid_t cpu" "const cpuset_t *set"
+.Ft size_t
+.Fn cpuset_size "const cpuset_t *set"
+.Sh DESCRIPTION
+This section describes the functions used to create, set, use and destroy
+the dynamic CPU sets.
+.Pp
+This API can be used with the POSIX threads, see
+.Xr pthread 3
+and
+.Xr affinity 3 .
+.Pp
+The ID of the primary CPU in the system is 0.
+.Sh FUNCTIONS
+.Bl -tag -width compact
+.It Fn cpuset_create
+Allocates and initializes a clean CPU-set.
+Returns the pointer to the CPU-set, or
+.Dv NULL
+on failure.
+.It Fn cpuset_destroy set
+Destroy the CPU-set specified by
+.Fa set .
+.It Fn cpuset_zero set
+Makes the CPU-set specified by
+.Fa set
+clean, that is, memory is initialized to zero bytes, and none of
+the CPUs set.
+.It Fn cpuset_set cpu set
+Sets the CPU specified by
+.Fa cpu
+in
+.Fa set .
+Returns zero on success, and \-1 if
+.Fa cpu
+is invalid.
+.It Fn cpuset_clr cpu set
+Clears the CPU specified by
+.Fa cpu
+in the CPU-set
+.Fa set .
+Returns zero on success, and \-1 if
+.Fa cpu
+is invalid.
+.It Fn cpuset_isset cpu set
+Checks if CPU specified by
+.Fa cpu
+is set in the CPU-set
+.Fa set .
+Returns the positive number if set, zero if not set, and \-1 if
+.Fa cpu
+is invalid.
+.It Fn cpuset_size set
+Returns the size in bytes of CPU-set specified by
+.Fa set .
+.El
+.Sh SEE ALSO
+.Xr affinity 3 ,
+.Xr pset 3 ,
+.Xr sched 3 ,
+.Xr schedctl 8
+.Sh HISTORY
+The dynamic CPU sets appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/gen/ctermid.3 b/lib/nbsd_libc/gen/ctermid.3
new file mode 100644 (file)
index 0000000..b167392
--- /dev/null
@@ -0,0 +1,90 @@
+.\"    $NetBSD: ctermid.3,v 1.11 2010/03/22 19:30:53 joerg Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)ctermid.3  8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt CTERMID 3
+.Os
+.Sh NAME
+.Nm ctermid
+.Nd generate terminal pathname
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft char *
+.Fn ctermid "char *buf"
+.Sh DESCRIPTION
+The
+.Fn ctermid
+function generates a string, that, when used as a pathname, refers to
+the current controlling terminal of the calling process.
+.Pp
+If
+.Ar buf
+is the
+.Dv NULL
+pointer, a pointer to a static area is returned.
+Otherwise, the pathname is copied into the memory referenced by
+.Ar buf .
+The argument
+.Ar buf
+is assumed to point to an array at least
+.Dv L_ctermid
+bytes long (as defined in the include file
+.In stdio.h ) .
+.Pp
+The current implementation simply returns
+.Ql /dev/tty .
+.Sh RETURN VALUES
+Upon successful completion, a
+.Pf non- Dv NULL
+pointer is returned.
+Otherwise, a
+.Dv NULL
+pointer is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The current implementation detects no error conditions.
+.Sh SEE ALSO
+.Xr ttyname 3
+.Sh STANDARDS
+The
+.Fn ctermid
+function conforms to
+.St -p1003.1-90 .
+.Sh BUGS
+By default the
+.Fn ctermid
+function writes all information to an internal static object.
+Subsequent calls to
+.Fn ctermid
+will modify the same object.
diff --git a/lib/nbsd_libc/gen/ctermid.c b/lib/nbsd_libc/gen/ctermid.c
new file mode 100644 (file)
index 0000000..f0db511
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: ctermid.c,v 1.10 2003/08/07 16:42:46 agc Exp $ */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ctermid.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: ctermid.c,v 1.10 2003/08/07 16:42:46 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <stdio.h>
+#include <string.h>
+#include <paths.h>
+
+#ifdef __weak_alias
+__weak_alias(ctermid,_ctermid)
+#endif
+
+char *
+ctermid(s)
+       char *s;
+{
+       static char def[] = _PATH_TTY;
+
+       if (s) {
+               (void)strncpy(s, def, L_ctermid);
+               return (s);
+       }
+       return (def);
+}
diff --git a/lib/nbsd_libc/gen/ctype.3 b/lib/nbsd_libc/gen/ctype.3
new file mode 100644 (file)
index 0000000..dbe8d96
--- /dev/null
@@ -0,0 +1,154 @@
+.\"    $NetBSD: ctype.3,v 1.21 2010/05/06 11:46:11 jruoho Exp $
+.\"
+.\" Copyright (c) 1991 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.
+.\" 3. 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.
+.\"
+.\"     @(#)ctype.3    6.5 (Berkeley) 4/19/91
+.\"
+.Dd May 6, 2010
+.Dt CTYPE 3
+.Os
+.Sh NAME
+.Nm isalpha ,
+.Nm isupper ,
+.Nm islower ,
+.Nm isdigit ,
+.Nm isxdigit ,
+.Nm isalnum ,
+.Nm isspace ,
+.Nm ispunct ,
+.Nm isprint ,
+.Nm isgraph ,
+.Nm iscntrl ,
+.Nm isblank ,
+.Nm toupper ,
+.Nm tolower ,
+.Nd character classification and mapping functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Fn isalpha "int c"
+.Fn isupper "int c"
+.Fn islower "int c"
+.Fn isdigit "int c"
+.Fn isxdigit "int c"
+.Fn isalnum "int c"
+.Fn isspace "int c"
+.Fn ispunct "int c"
+.Fn isprint "int c"
+.Fn isgraph "int c"
+.Fn iscntrl "int c"
+.Fn isblank "int c"
+.Fn toupper "int c"
+.Fn tolower "int c"
+.Sh DESCRIPTION
+The above functions perform character tests and conversions on the integer
+.Ar c .
+.Pp
+See the specific manual pages for information about the
+test or conversion performed by each function.
+.Sh EXAMPLES
+To print an upper-case version of a string to stdout,
+the following code can be used:
+.Bd -literal -offset indent
+const char *s = "xyz";
+
+while (*s != '\e0') {
+    putchar(toupper((int)(unsigned char)*s));
+    s++;
+}
+.Ed
+.Sh SEE ALSO
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+These functions, with the exception of
+.Fn isblank ,
+conform to
+.St -ansiC .
+All described functions, including
+.Fn isblank ,
+also conform to
+.St -p1003.1-2001 .
+.Sh CAVEATS
+The first argument of these functions is of type
+.Vt int ,
+but only a very restricted subset of values are actually valid.
+The argument must either be the value of the macro
+.Dv EOF
+(which has a negative value),
+or must be a non-negative value within the range representable as
+.Vt unsigned char .
+Passing invalid values leads to undefined behavior.
+.Pp
+Values of type
+.Vt int
+that were returned by
+.Xr getc 3 ,
+.Xr fgetc 3 ,
+and similar functions or macros
+are already in the correct range, and may be safely passed to these
+.Nm ctype
+functions without any casts.
+.Pp
+Values of type
+.Vt char
+or
+.Vt signed char
+must first be cast to
+.Vt unsigned char ,
+to ensure that the values are within the correct range.
+The result should then be cast to
+.Vt int
+to avoid warnings from some compilers.
+Casting a negative-valued
+.Vt char
+or
+.Vt signed char
+directly to
+.Vt int
+will produce a negative-valued
+.Vt int ,
+which will be outside the range of allowed values
+(unless it happens to be equal to
+.Dv EOF ,
+but even that would not give the desired result).
diff --git a/lib/nbsd_libc/gen/ctype_.c b/lib/nbsd_libc/gen/ctype_.c
new file mode 100644 (file)
index 0000000..931cfb4
--- /dev/null
@@ -0,0 +1,83 @@
+/*     $NetBSD: ctype_.c,v 1.19 2010/12/14 02:28:57 joerg Exp $        */
+
+/*
+ * Copyright (c) 1989 The Regents of the University of California.
+ * All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+/*static char *sccsid = "from: @(#)ctype_.c    5.6 (Berkeley) 6/1/90";*/
+#else
+__RCSID("$NetBSD: ctype_.c,v 1.19 2010/12/14 02:28:57 joerg Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/ctype_bits.h>
+#include <stdio.h>
+#include "ctype_local.h"
+
+#if EOF != -1
+#error "EOF != -1"
+#endif
+
+#define        _U      _CTYPE_U
+#define        _L      _CTYPE_L
+#define        _N      _CTYPE_N
+#define        _S      _CTYPE_S
+#define        _P      _CTYPE_P
+#define        _C      _CTYPE_C
+#define        _X      _CTYPE_X
+#define        _B      _CTYPE_B
+
+const unsigned char _C_ctype_[1 + _CTYPE_NUM_CHARS] = {
+       0,
+       _C,     _C,     _C,     _C,     _C,     _C,     _C,     _C,
+       _C,     _C|_S,  _C|_S,  _C|_S,  _C|_S,  _C|_S,  _C,     _C,
+       _C,     _C,     _C,     _C,     _C,     _C,     _C,     _C,
+       _C,     _C,     _C,     _C,     _C,     _C,     _C,     _C,
+       _S|_B,  _P,     _P,     _P,     _P,     _P,     _P,     _P,
+       _P,     _P,     _P,     _P,     _P,     _P,     _P,     _P,
+       _N,     _N,     _N,     _N,     _N,     _N,     _N,     _N,
+       _N,     _N,     _P,     _P,     _P,     _P,     _P,     _P,
+       _P,     _U|_X,  _U|_X,  _U|_X,  _U|_X,  _U|_X,  _U|_X,  _U,
+       _U,     _U,     _U,     _U,     _U,     _U,     _U,     _U,
+       _U,     _U,     _U,     _U,     _U,     _U,     _U,     _U,
+       _U,     _U,     _U,     _P,     _P,     _P,     _P,     _P,
+       _P,     _L|_X,  _L|_X,  _L|_X,  _L|_X,  _L|_X,  _L|_X,  _L,
+       _L,     _L,     _L,     _L,     _L,     _L,     _L,     _L,
+       _L,     _L,     _L,     _L,     _L,     _L,     _L,     _L,
+       _L,     _L,     _L,     _P,     _P,     _P,     _P,     _C
+};
+
+const unsigned char *_ctype_ = &_C_ctype_[0];
diff --git a/lib/nbsd_libc/gen/daemon.3 b/lib/nbsd_libc/gen/daemon.3
new file mode 100644 (file)
index 0000000..47f3f57
--- /dev/null
@@ -0,0 +1,114 @@
+.\"    $NetBSD: daemon.3,v 1.15 2003/08/07 16:42:46 agc Exp $
+.\"
+.\" Copyright (c) 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.
+.\" 3. 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.
+.\"
+.\"    @(#)daemon.3    8.1 (Berkeley) 6/9/93
+.\"
+.Dd September 3, 1999
+.Dt DAEMON 3
+.Os
+.Sh NAME
+.Nm daemon
+.Nd run in the background
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn daemon "int nochdir" "int noclose"
+.Sh DESCRIPTION
+The
+.Fn daemon
+function is for programs wishing to detach themselves from the
+controlling terminal and run in the background as system daemons.
+.Pp
+Unless the argument
+.Fa nochdir
+is non-zero,
+.Fn daemon
+changes the current working directory to the root
+.Pq Pa / .
+.Pp
+Unless the argument
+.Fa noclose
+is non-zero,
+.Fn daemon
+will redirect standard input, standard output and standard error
+to
+.Pa /dev/null .
+.Sh RETURN VALUES
+On return 0 indicates success with \-1 indicating error.
+.Sh ERRORS
+The function
+.Fn daemon
+may fail and set
+.Va errno
+for any of the errors specified for the library functions
+.Xr fork 2
+and
+.Xr setsid 2 .
+.Sh SEE ALSO
+.Xr fork 2 ,
+.Xr setsid 2
+.Sh HISTORY
+The
+.Fn daemon
+function first appeared in
+.Bx 4.4 .
+.Sh CAVEATS
+Unless the
+.Ar noclose
+argument is non-zero,
+.Fn daemon
+will close the first three file descriptors and redirect them to
+.Pa /dev/null .
+Normally, these correspond to standard input, standard output and
+standard error.
+However, if any of those file descriptors refer to something else they
+will still be closed, resulting in incorrect behavior of the calling program.
+This can happen if any of standard input, standard output or standard error
+have been closed before the program was run.
+Programs using
+.Fn daemon
+should therefore make sure to either call
+.Fn daemon
+before opening any files or sockets or, alternately, verifying that
+any file descriptors obtained have a value greater than 2.
+.Sh BUGS
+.Fn daemon
+uses
+.Fn fork
+as part of its tty detachment mechanism.
+Consequently the process id changes when
+.Fn daemon
+is invoked.
+Processes employing
+.Fn daemon
+can not be reliably waited upon until
+.Fn daemon
+has been invoked.
diff --git a/lib/nbsd_libc/gen/daemon.c b/lib/nbsd_libc/gen/daemon.c
new file mode 100644 (file)
index 0000000..032149d
--- /dev/null
@@ -0,0 +1,80 @@
+/*     $NetBSD: daemon.c,v 1.9 2003/08/07 16:42:46 agc Exp $   */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)daemon.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: daemon.c,v 1.9 2003/08/07 16:42:46 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <fcntl.h>
+#include <paths.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(daemon,_daemon)
+#endif
+
+int
+daemon(nochdir, noclose)
+       int nochdir, noclose;
+{
+       int fd;
+
+       switch (fork()) {
+       case -1:
+               return (-1);
+       case 0:
+               break;
+       default:
+               _exit(0);
+       }
+
+       if (setsid() == -1)
+               return (-1);
+
+       if (!nochdir)
+               (void)chdir("/");
+
+       if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
+               (void)dup2(fd, STDIN_FILENO);
+               (void)dup2(fd, STDOUT_FILENO);
+               (void)dup2(fd, STDERR_FILENO);
+               if (fd > STDERR_FILENO)
+                       (void)close(fd);
+       }
+       return (0);
+}
diff --git a/lib/nbsd_libc/gen/dehumanize_number.c b/lib/nbsd_libc/gen/dehumanize_number.c
new file mode 100644 (file)
index 0000000..89afead
--- /dev/null
@@ -0,0 +1,115 @@
+/*     $NetBSD: dehumanize_number.c,v 1.3 2008/04/28 20:22:59 martin Exp $     */
+
+/*
+ * Copyright (c) 2005, 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Julio M. Merino Vidal, developed as part of Google's Summer of Code
+ * 2005 program.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: dehumanize_number.c,v 1.3 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <inttypes.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+
+/*
+ * Converts the number given in 'str', which may be given in a humanized
+ * form (as described in humanize_number(3), but with some limitations),
+ * to an int64_t without units.
+ * In case of success, 0 is returned and *size holds the value.
+ * Otherwise, -1 is returned and *size is untouched.
+ *
+ * TODO: Internationalization, SI units.
+ */
+int
+dehumanize_number(const char *str, int64_t *size)
+{
+       char *ep, unit;
+       const char *delimit;
+       long multiplier;
+       long long tmp, tmp2;
+       size_t len;
+
+       len = strlen(str);
+       if (len == 0) {
+               errno = EINVAL;
+               return -1;
+       }
+
+       multiplier = 1;
+
+       unit = str[len - 1];
+       if (isalpha((unsigned char)unit)) {
+               switch (tolower((unsigned char)unit)) {
+               case 'b':
+                       multiplier = 1;
+                       break;
+
+               case 'k':
+                       multiplier = 1024;
+                       break;
+
+               case 'm':
+                       multiplier = 1024 * 1024;
+                       break;
+
+               case 'g':
+                       multiplier = 1024 * 1024 * 1024;
+                       break;
+
+               default:
+                       errno = EINVAL;
+                       return -1; /* Invalid suffix. */
+               }
+
+               delimit = &str[len - 1];
+       } else
+               delimit = NULL;
+
+       errno = 0;
+       tmp = strtoll(str, &ep, 10);
+       if (str[0] == '\0' || (ep != delimit && *ep != '\0'))
+               return -1; /* Not a number. */
+       else if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
+               return -1; /* Out of range. */
+
+       tmp2 = tmp * multiplier;
+       tmp2 = tmp2 / multiplier;
+       if (tmp != tmp2) {
+               errno = ERANGE;
+               return -1; /* Out of range. */
+       }
+       *size = tmp * multiplier;
+
+       return 0;
+}
diff --git a/lib/nbsd_libc/gen/devname.3 b/lib/nbsd_libc/gen/devname.3
new file mode 100644 (file)
index 0000000..1c00fc5
--- /dev/null
@@ -0,0 +1,81 @@
+.\"    $NetBSD: devname.3,v 1.11 2003/08/07 16:42:46 agc Exp $
+.\"
+.\" Copyright (c) 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.
+.\" 3. 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.
+.\"
+.\"     @(#)devname.3  8.2 (Berkeley) 4/29/95
+.\"
+.Dd April 29, 1995
+.Dt DEVNAME 3
+.Os
+.Sh NAME
+.Nm devname
+.Nd get device name
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.In sys/stat.h
+.Ft char *
+.Fn devname "dev_t dev" "mode_t type"
+.Sh DESCRIPTION
+The
+.Fn devname
+function returns a pointer to the name of the block or character
+device in
+.Dq Pa /dev
+with a device number of
+.Fa dev ,
+and a file type matching the one encoded in
+.Fa type
+which must be one of S_IFBLK or S_IFCHR.
+The device name is cached so that multiple calls with the same
+.Fa dev
+and
+.Fa type
+do not require additional queries of the device database file.
+If no device matches the specified values, or no information is
+available,
+.Dv NULL
+is returned.
+.Pp
+The traditional display for applications when no device is
+found is the string
+.Dq ?? .
+.Sh FILES
+.Bl -tag -width /var/run/dev.db -compact
+.It Pa /var/run/dev.db
+Device database file.
+.El
+.Sh SEE ALSO
+.Xr stat 2 ,
+.Xr dev_mkdb 8
+.Sh HISTORY
+The
+.Nm devname
+function call appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/gen/devname.c b/lib/nbsd_libc/gen/devname.c
new file mode 100644 (file)
index 0000000..e11d11f
--- /dev/null
@@ -0,0 +1,198 @@
+/*     $NetBSD: devname.c,v 1.21 2010/03/23 20:28:59 drochner Exp $    */
+
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Simon Burge.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*-
+ * Copyright (c) 1992 Keith Muller.
+ * Copyright (c) 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Keith Muller of the University of California, San Diego.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)devname.c  8.2 (Berkeley) 4/29/95";
+#else
+__RCSID("$NetBSD: devname.c,v 1.21 2010/03/23 20:28:59 drochner Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/param.h>
+
+#include <db.h>
+#include <fcntl.h>
+#include <paths.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <err.h>
+
+#define        DEV_SZ          317     /* show be prime for best results */
+#define        VALID           1       /* entry and devname are valid */
+#define        INVALID         2       /* entry valid, devname NOT valid */
+
+typedef struct devc {
+       int valid;              /* entry valid? */
+       dev_t dev;              /* cached device */
+       mode_t type;            /* cached file type */
+       char name[NAME_MAX];    /* device name */
+} DEVC;
+
+char *
+devname(dev, type)
+       dev_t dev;
+       mode_t type;
+{
+       struct {
+               mode_t type;
+               dev_t dev;
+       } bkey;
+       struct {
+               mode_t type;
+               int32_t dev;
+       } obkey;
+       static DB *db;
+       static int failure;
+       DBT data, key;
+       DEVC *ptr, **pptr;
+       static DEVC **devtb = NULL;
+       static devmajor_t pts;
+       static int pts_valid = 0;
+
+       if (!db && !failure &&
+           !(db = dbopen(_PATH_DEVDB, O_RDONLY, 0, DB_HASH, NULL))) {
+               warn("warning: %s", _PATH_DEVDB);
+               failure = 1;
+       }
+       /* initialise dev cache */
+       if (!failure && devtb == NULL) {
+               devtb = calloc(DEV_SZ, sizeof(DEVC *));
+               if (devtb == NULL)
+                       failure= 1;
+       }
+       if (failure)
+               return (NULL);
+
+       /* see if we have this dev/type cached */
+       pptr = devtb + (size_t)((dev + type) % DEV_SZ);
+       ptr = *pptr;
+
+       if (ptr && ptr->valid > 0 && ptr->dev == dev && ptr->type == type) {
+               if (ptr->valid == VALID)
+                       return (ptr->name);
+               return (NULL);
+       }
+
+       if (ptr == NULL)
+               *pptr = ptr = malloc(sizeof(DEVC));
+
+       /*
+        * Keys are a mode_t followed by a dev_t.  The former is the type of
+        * the file (mode & S_IFMT), the latter is the st_rdev field.  Be
+        * sure to clear any padding that may be found in bkey.
+        */
+       (void)memset(&bkey, 0, sizeof(bkey));
+       bkey.dev = dev;
+       bkey.type = type;
+       key.data = &bkey;
+       key.size = sizeof(bkey);
+       if ((db->get)(db, &key, &data, 0) == 0) {
+found_it:
+               if (ptr == NULL)
+                       return (char *)data.data;
+               ptr->dev = dev;
+               ptr->type = type;
+               strncpy(ptr->name, (char *)data.data, NAME_MAX);
+               ptr->name[NAME_MAX - 1] = '\0';
+               ptr->valid = VALID;
+       } else {
+               /* Look for a 32 bit dev_t. */
+               (void)memset(&obkey, 0, sizeof(obkey));
+               obkey.dev = (int32_t)(uint32_t)dev;
+               obkey.type = type;
+               key.data = &obkey;
+               key.size = sizeof(obkey);
+               if ((db->get)(db, &key, &data, 0) == 0)
+                       goto found_it;
+
+               if (ptr == NULL)
+                       return (NULL);
+               ptr->valid = INVALID;
+               if (type == S_IFCHR) {
+                       if (!pts_valid) {
+                               pts = getdevmajor("pts", S_IFCHR);
+                               pts_valid = 1;
+                       }
+                       if (pts != NODEVMAJOR && major(dev) == pts) {
+                               (void)snprintf(ptr->name, sizeof(ptr->name),
+                                   "%s%d", _PATH_DEV_PTS +
+                                   sizeof(_PATH_DEV) - 1,
+                                   minor(dev));
+                               ptr->valid = VALID;
+                       }
+               }
+               ptr->dev = dev;
+               ptr->type = type;
+       }
+       if (ptr->valid == VALID)
+               return (ptr->name);
+       else
+               return (NULL);
+}
diff --git a/lib/nbsd_libc/gen/directory.3 b/lib/nbsd_libc/gen/directory.3
new file mode 100644 (file)
index 0000000..432cf60
--- /dev/null
@@ -0,0 +1,395 @@
+.\"    $NetBSD: directory.3,v 1.36 2010/12/17 19:20:42 njoly Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)directory.3        8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 2010
+.Dt DIRECTORY 3
+.Os
+.Sh NAME
+.Nm fdopendir ,
+.Nm opendir ,
+.Nm readdir ,
+.Nm readdir_r ,
+.Nm telldir ,
+.Nm seekdir ,
+.Nm rewinddir ,
+.Nm closedir ,
+.Nm dirfd
+.Nd directory operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In dirent.h
+.Ft DIR *
+.Fn opendir "const char *filename"
+.Ft DIR *
+.Fn fdopendir "int fd"
+.Ft struct dirent *
+.Fn readdir "DIR *dirp"
+.Ft int
+.Fn readdir_r "DIR * restrict dirp" "struct dirent * restrict entry" "struct dirent ** restrict result"
+.Ft long
+.Fn telldir "DIR *dirp"
+.Ft void
+.Fn seekdir "DIR *dirp" "long  loc"
+.Ft void
+.Fn rewinddir "DIR *dirp"
+.Ft int
+.Fn closedir "DIR *dirp"
+.Ft int
+.Fn dirfd "DIR *dirp"
+.Sh DESCRIPTION
+The type
+.Vt DIR
+represents a directory stream;
+an ordered sequence of all directory entries in a particular directory.
+The purpose of the
+.Vt DIR
+structure is similar to that of the
+.Vt FILE
+structure maintained by the
+.Xr stdio 3
+library functions.
+.Sh FUNCTIONS
+The following standard directory operations are defined.
+.Bl -tag -width XXX
+.It Fn opendir "filename"
+The
+.Fn opendir
+function opens the directory named by
+.Fa filename
+and associates a directory stream with it.
+The directory stream is positioned at the first entry.
+Upon successful completion, a pointer to
+.Vt DIR
+type is returned.
+Otherwise,
+.Fn opendir
+returns
+.Dv NULL .
+.It Fn fdopendir "fd"
+The
+.Fn fdopendir
+function associates a directory stream with the directory file descriptor
+.Fa fd .
+The file offset associated with
+.Fa fd
+at the time of the call determines which entries are returned.
+.Pp
+Upon failure,
+.Fn fdopendir
+returns
+.Dv NULL .
+Otherwise the file descriptor is under the control of the system,
+and if any attempt is made to close the file descriptor,
+or to modify the state of the associated description,
+other than by means of
+.Fn closedir ,
+.Fn readdir ,
+.Fn readdir_r ,
+.Fn rewinddir ,
+the behavior is undefined.
+The file descriptor can be closed by calling
+.Fn closedir .
+.It Fn readdir "dirp"
+The
+.Fn readdir
+function returns a pointer to the directory entry at the current position
+in the directory stream specified by
+.Fa dirp ,
+and positions the directory stream at the next entry.
+It returns
+.Dv NULL
+upon reaching the end of the directory or detecting an invalid
+.Fn seekdir
+operation.
+The returned structure is described in
+.Xr dirent 3 .
+.Pp
+The returned pointer to the
+.Em dirent
+structure points to data which may be overwritten by another call to
+.Fn readdir
+on the same directory stream.
+This data is not however overwritten by another call to
+.Fn readdir
+on a different directory stream.
+.It Fn readdir_r "dirp" "entry" "result"
+The
+.Fn readdir_r
+function
+provides the same functionality as
+.Fn readdir ,
+but the caller must provide a directory
+.Fa entry
+buffer to store the results in.
+If the read succeeds,
+.Fa result
+is pointed at the
+.Fa entry ;
+upon reaching the end of the directory
+.Fa result
+is set to
+.Dv NULL .
+The
+.Fn readdir_r
+function
+returns 0 on success or an error number to indicate failure.
+.Pp
+Like
+.Fn readdir ,
+the
+.Fn readdir_r
+function may buffer several directory entries per actual read operation.
+Both functions mark for update the
+.Em st_atime
+field (see
+.Xr stat 2 )
+of the directory each time the directory is actually read.
+.It Fn telldir "dirp"
+The
+.Fn telldir
+function returns the current location associated
+with the directory stream specified by
+.Fa dirp .
+.Pp
+If the most recent operation on the particular directory stream was a
+.Fn seekdir ,
+the directory position returned from
+.Fn telldir
+is the same as
+.Fa loc
+supplied as an argument to the
+.Fn seekdir
+call.
+.It Fn seekdir "dirp" "loc"
+The
+.Fn seekdir
+function sets the position of the next
+.Fn readdir
+operation on the directory stream specified by
+.Fa dirp .
+The value of
+.Fa loc
+should come from a previous call to
+.Fn telldir
+using the same directory stream.
+.Pp
+The new position reverts to the one associated
+with the directory stream when the
+.Fn telldir
+operation was performed.
+Values returned by
+.Fn telldir
+are good only for the lifetime of the
+.Vt DIR
+pointer,
+.Fa dirp ,
+from which they are derived.
+If the directory is closed and then reopened, the
+.Fn telldir
+value cannot be re-used.
+.It Fn rewinddir "dirp"
+The
+.Fn rewinddir
+function resets the position of the named directory
+stream to the beginning of the directory.
+It also causes the directory stream to refer to the
+current state of the corresponding directory, as if a call to
+.Fn opendir
+would have been made.
+.Pp
+If
+.Fa dirp
+does not refer to a valid directory stream, the behavior is undefined.
+.It Fn closedir "dirp"
+The
+.Fn closedir
+function closes the directory stream
+and frees the structure associated with the
+.Fa dirp
+pointer,
+returning 0 on success and \-1 on failure.
+.It Fn dirfd "dirp"
+The
+.Fn dirfd
+function returns the integer file descriptor
+associated with the directory stream specified by
+.Fa dirp .
+Upon failure,
+.Fn dirfd
+returns \-1.
+The returned file descriptor should be closed by
+.Fn closedir
+instead of
+.Xr close 2 .
+.Pp
+The rationale of
+.Fn dirfd
+is to provide a mechanism by which a file descriptor
+can be obtained for the use of the
+.Xr fchdir 2
+function.
+.El
+.Sh EXAMPLES
+Sample code which searches a directory for entry
+.Dq name
+is:
+.Bd -literal -offset indent
+len = strlen(name);
+dirp = opendir(".");
+if (dirp != NULL) {
+       while ((dp = readdir(dirp)) != NULL)
+               if (dp-\*[Gt]d_namlen == len \*[Am]\*[Am]
+                   !strcmp(dp-\*[Gt]d_name, name)) {
+                       (void)closedir(dirp);
+                       return (FOUND);
+               }
+       (void)closedir(dirp);
+}
+return (NOT_FOUND);
+.Ed
+.Sh COMPATIBILITY
+The described directory operations have traditionally been problematic
+in terms of portability.
+A good example is the semantics around
+.Sq \&.
+(dot) and
+.Sq \&..
+(dot-dot).
+Based on historical implementations,
+the rules about file descriptors apply to directory streams as well.
+The
+.St -p1003.1-2008
+standard does not however any more mandate that directory streams
+are necessarily implemented by using file descriptors.
+.Pp
+The following additional remarks can be noted from the
+.St -p1003.1-2008
+standard.
+.Bl -bullet -offset 2n
+.It
+If the type
+.Vt DIR
+is implemented using a file descriptor,
+like in
+.Nx ,
+applications should be able to open only
+.Dv OPEN_MAX
+files and directories.
+Otherwise the limit is left as unspecified.
+.It
+When a file descriptor is used to implement the directory stream, the
+.Fn closedir
+function behaves as if the
+.Dv FD_CLOEXEC
+had been set for the file descriptor.
+In another words, it is mandatory that
+.Fn closedir
+deallocates the file descriptor.
+.It
+If directory streams are not implemented by using file descriptors,
+functions such as
+.Fn dirfd
+may fail with
+.Er ENOTSUP .
+.It
+If a file is removed from or added to the directory
+after the most recent call to
+.Fn opendir
+or
+.Fn rewinddir ,
+it is unspecified whether a subsequent call to
+.Fn readdir
+returns an entry for that file.
+.It
+When using the function
+.Fn seekdir ,
+note that if the value of
+.Fa loc
+was not obtained from an earlier call to
+.Fn telldir ,
+or if a call to
+.Fn rewinddir
+occurred between the calls to
+.Fn telldir
+and
+.Fn seekdir ,
+any subsequent call to
+.Fn readdir
+is unspecified, possibly resulting undefined behavior.
+.It
+After a call to
+.Xr fork 2 ,
+either the parent or child (but not both) can continue processing the
+directory stream using
+.Fn readdir ,
+.Fn rewinddir ,
+or
+.Fn seekdir .
+However, if both the parent and child processes use these functions,
+the result is undefined.
+.El
+.Sh ERRORS
+.\"
+.\" XXX: The errors should be enumerated.
+.\"
+All described functions may set
+.Vt errno
+to indicate the error.
+.Sh SEE ALSO
+.Xr close 2 ,
+.Xr lseek 2 ,
+.Xr open 2 ,
+.Xr read 2 ,
+.Xr dirent 3
+.Sh STANDARDS
+The
+.Fn opendir ,
+.Fn readdir ,
+.Fn rewinddir
+and
+.Fn closedir
+functions conform to
+.St -p1003.1-90 .
+The other functions conform to
+.St -p1003.1-2008 .
+.Sh HISTORY
+The
+.Fn opendir ,
+.Fn readdir ,
+.Fn telldir ,
+.Fn seekdir ,
+.Fn rewinddir ,
+.Fn closedir ,
+and
+.Fn dirfd
+functions appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/gen/dirent_private.h b/lib/nbsd_libc/gen/dirent_private.h
new file mode 100644 (file)
index 0000000..77d2d56
--- /dev/null
@@ -0,0 +1,24 @@
+/*     $NetBSD: dirent_private.h,v 1.4 2010/09/26 02:26:59 yamt Exp $  */
+
+/*
+ * One struct _dirpos is malloced to describe the current directory
+ * position each time telldir is called. It records the current magic 
+ * cookie returned by getdents and the offset within the buffer associated
+ * with that return value.
+ */
+struct dirpos {
+       struct dirpos *dp_next; /* next structure in list */
+       off_t   dp_seek;        /* magic cookie returned by getdents */
+       long    dp_loc;         /* offset of entry in buffer */
+};
+
+struct _dirdesc;
+void _seekdir_unlocked(struct _dirdesc *, long);
+long _telldir_unlocked(struct _dirdesc *);
+int _initdir(DIR *, int, const char *);
+void _finidir(DIR *);
+#ifndef __LIBC12_SOURCE__
+struct dirent;
+struct dirent *_readdir_unlocked(struct _dirdesc *, int)
+    __RENAME(___readdir_unlocked50);
+#endif
diff --git a/lib/nbsd_libc/gen/dirname.3 b/lib/nbsd_libc/gen/dirname.3
new file mode 100644 (file)
index 0000000..2166318
--- /dev/null
@@ -0,0 +1,98 @@
+.\"    $NetBSD: dirname.3,v 1.14 2008/05/10 22:39:40 christos Exp $
+.\"
+.\" Copyright (c) 1997, 2002 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein and Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 10, 2008
+.Dt DIRNAME 3
+.Os
+.Sh NAME
+.Nm dirname
+.Nd report the parent directory name of a file pathname
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In libgen.h
+.Ft char *
+.Fn dirname "char *path"
+.Sh DESCRIPTION
+The
+.Fn dirname
+function takes a pointer to a character string that contains a pathname,
+.Ar path ,
+and returns a pointer to a string that is a pathname of the parent directory of
+.Ar path .
+Trailing
+.Sq /
+characters in
+.Ar path
+are not counted as part of the path.
+.Pp
+If
+.Ar path
+does not contain a
+.Sq / ,
+then
+.Fn dirname
+returns a pointer to the string
+.Dq \&. .
+.Pp
+If
+.Ar path
+is a null pointer or points to an empty string,
+.Fn dirname
+returns a pointer to the string
+.Dq \&. .
+.Sh RETURN VALUES
+The
+.Fn dirname
+function returns a pointer to a string that is the parent directory of
+.Ar path .
+.Sh SEE ALSO
+.Xr dirname 1 ,
+.Xr basename 3
+.Sh STANDARDS
+.Bl -bullet -compact
+.It
+.St -xpg4.2
+.It
+.St -p1003.1-2001
+.El
+.Sh BUGS
+If the length of the result is longer than
+.Dv PATH_MAX
+bytes
+.Pq including the terminating nul ,
+the result will be truncated.
+.Pp
+The
+.Fn dirname
+function returns a pointer to static storage that may be overwritten
+by subsequent calls to
+.Fn dirname .
+This is not strictly a bug; it is explicitly allowed by
+.St -p1003.1-2001 .
diff --git a/lib/nbsd_libc/gen/dirname.c b/lib/nbsd_libc/gen/dirname.c
new file mode 100644 (file)
index 0000000..ef2cb04
--- /dev/null
@@ -0,0 +1,93 @@
+/*     $NetBSD: dirname.c,v 1.11 2009/11/24 13:34:20 tnozaki Exp $     */
+
+/*-
+ * Copyright (c) 1997, 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein and Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: dirname.c,v 1.11 2009/11/24 13:34:20 tnozaki Exp $");
+#endif /* !LIBC_SCCS && !lint */
+
+#include "namespace.h"
+#include <libgen.h>
+#include <limits.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(dirname,_dirname)
+#endif
+
+#if !HAVE_DIRNAME
+char *
+dirname(char *path)
+{
+       static char result[PATH_MAX];
+       const char *lastp;
+       size_t len;
+
+       /*
+        * If `path' is a null pointer or points to an empty string,
+        * return a pointer to the string ".".
+        */
+       if ((path == NULL) || (*path == '\0'))
+               goto singledot;
+
+
+       /* Strip trailing slashes, if any. */
+       lastp = path + strlen(path) - 1;
+       while (lastp != path && *lastp == '/')
+               lastp--;
+
+       /* Terminate path at the last occurence of '/'. */
+       do {
+               if (*lastp == '/') {
+                       /* Strip trailing slashes, if any. */
+                       while (lastp != path && *lastp == '/')
+                               lastp--;
+
+                       /* ...and copy the result into the result buffer. */
+                       len = (lastp - path) + 1 /* last char */;
+                       if (len > (PATH_MAX - 1))
+                               len = PATH_MAX - 1;
+
+                       memcpy(result, path, len);
+                       result[len] = '\0';
+
+                       return (result);
+               }
+       } while (--lastp >= path);
+
+       /* No /'s found, return a pointer to the string ".". */
+singledot:
+       result[0] = '.';
+       result[1] = '\0';
+
+       return (result);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/disklabel.c b/lib/nbsd_libc/gen/disklabel.c
new file mode 100644 (file)
index 0000000..94a1184
--- /dev/null
@@ -0,0 +1,242 @@
+/*     $NetBSD: disklabel.c,v 1.34 2006/03/19 02:17:16 christos Exp $  */
+
+/*
+ * Copyright (c) 1983, 1987, 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)disklabel.c        8.2 (Berkeley) 5/3/95";
+#else
+__RCSID("$NetBSD: disklabel.c,v 1.34 2006/03/19 02:17:16 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#define DKTYPENAMES
+#define FSTYPENAMES
+#include <ufs/ufs/dinode.h>
+#include <ufs/ffs/fs.h>
+
+#if HAVE_NBTOOL_CONFIG_H
+#include <nbinclude/sys/disklabel.h>
+#include <nbinclude/disktab.h>
+#else
+#include <sys/disklabel.h>
+#include <disktab.h>
+#endif /* HAVE_NBTOOL_CONFIG_H */
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(getdiskbyname,_getdiskbyname)
+#endif
+
+#if 0
+static void    error __P((int));
+#endif
+static int     gettype __P((char *, const char *const *));
+
+static const char *db_array[2] = { _PATH_DISKTAB, 0 };
+
+int
+setdisktab(name)
+       const char *name;
+{
+       if (!name || !*name)
+               return -1;
+
+       db_array[0] = name;
+       return 0;
+}
+
+
+struct disklabel *
+getdiskbyname(name)
+       const char *name;
+{
+       static struct   disklabel disk;
+       struct  disklabel *dp = &disk;
+       struct partition *pp;
+       char    *buf;
+       char    *cp, *cq;       /* can't be */
+       char    p, max, psize[3], pbsize[3],
+               pfsize[3], poffset[3], ptype[3];
+       u_int32_t *dx;
+       long f;
+
+       _DIAGASSERT(name != NULL);
+
+       if (cgetent(&buf, db_array, name) < 0)
+               return NULL;
+
+       memset(&disk, 0, sizeof(disk));
+       /*
+        * typename
+        */
+       cq = dp->d_typename;
+       cp = buf;
+       while (cq < dp->d_typename + sizeof(dp->d_typename) - 1 &&
+           (*cq = *cp) && *cq != '|' && *cq != ':')
+               cq++, cp++;
+       *cq = '\0';
+       /*
+        * boot name (optional)  xxboot, bootxx
+        */
+       cgetstr(buf, "b0", &dp->d_boot0);
+       cgetstr(buf, "b1", &dp->d_boot1);
+
+       if (cgetstr(buf, "ty", &cq) >= 0) {
+               if (strcmp(cq, "removable") == 0)
+                       dp->d_flags |= D_REMOVABLE;
+               else if (strcmp(cq, "simulated") == 0)
+                       dp->d_flags |= D_RAMDISK;
+               free(cq);
+       }
+       if (cgetcap(buf, "sf", ':') != NULL)
+               dp->d_flags |= D_BADSECT;
+
+#define getnumdflt(field, dname, dflt) \
+    (field) = ((cgetnum(buf, dname, &f) == -1) ? (dflt) : (u_int32_t) f)
+#define        getnum(field, dname) \
+       if (cgetnum(buf, dname, &f) != -1) field = (u_int32_t)f
+
+       getnumdflt(dp->d_secsize, "se", DEV_BSIZE);
+       getnum(dp->d_ntracks, "nt");
+       getnum(dp->d_nsectors, "ns");
+       getnum(dp->d_ncylinders, "nc");
+
+       if (cgetstr(buf, "dt", &cq) >= 0) {
+               dp->d_type = gettype(cq, dktypenames);
+               free(cq);
+       } else
+               getnumdflt(dp->d_type, "dt", 0);
+       getnumdflt(dp->d_secpercyl, "sc", dp->d_nsectors * dp->d_ntracks);
+       getnumdflt(dp->d_secperunit, "su", dp->d_secpercyl * dp->d_ncylinders);
+       getnumdflt(dp->d_rpm, "rm", 3600);
+       getnumdflt(dp->d_interleave, "il", 1);
+       getnumdflt(dp->d_trackskew, "sk", 0);
+       getnumdflt(dp->d_cylskew, "cs", 0);
+       getnumdflt(dp->d_headswitch, "hs", 0);
+       getnumdflt(dp->d_trkseek, "ts", 0);
+       getnumdflt(dp->d_bbsize, "bs", BBSIZE);
+       getnumdflt(dp->d_sbsize, "sb", SBLOCKSIZE);
+       strcpy(psize, "px");    /* XXX: strcpy is safe */
+       strcpy(pbsize, "bx");   /* XXX: strcpy is safe */
+       strcpy(pfsize, "fx");   /* XXX: strcpy is safe */
+       strcpy(poffset, "ox");  /* XXX: strcpy is safe */
+       strcpy(ptype, "tx");    /* XXX: strcpy is safe */
+       max = 'a' - 1;
+       pp = &dp->d_partitions[0];
+       for (p = 'a'; p < 'a' + MAXPARTITIONS; p++, pp++) {
+               long ff;
+
+               psize[1] = pbsize[1] = pfsize[1] = poffset[1] = ptype[1] = p;
+               if (cgetnum(buf, psize, &ff) == -1)
+                       pp->p_size = 0;
+               else {
+                       pp->p_size = (u_int32_t)ff;
+                       getnum(pp->p_offset, poffset);
+                       getnumdflt(pp->p_fsize, pfsize, 0);
+                       if (pp->p_fsize) {
+                               long bsize;
+
+                               if (cgetnum(buf, pbsize, &bsize) == -1)
+                                       pp->p_frag = 8;
+                               else
+                                       pp->p_frag =
+                                           (u_int8_t)(bsize / pp->p_fsize);
+                       }
+                       getnumdflt(pp->p_fstype, ptype, 0);
+                       if (pp->p_fstype == 0)
+                               if (cgetstr(buf, ptype, &cq) >= 0) {
+                                       pp->p_fstype = gettype(cq, fstypenames);
+                                       free(cq);
+                               }
+                       max = p;
+               }
+       }
+       dp->d_npartitions = max + 1 - 'a';
+       strcpy(psize, "dx");    /* XXX: strcpy is safe */
+       dx = dp->d_drivedata;
+       for (p = '0'; p < '0' + NDDATA; p++, dx++) {
+               psize[1] = p;
+               getnumdflt(*dx, psize, 0);
+       }
+       dp->d_magic = DISKMAGIC;
+       dp->d_magic2 = DISKMAGIC;
+       free(buf);
+       return (dp);
+}
+
+static int
+gettype(t, names)
+       char *t;
+       const char *const *names;
+{
+       const char *const *nm;
+
+       _DIAGASSERT(t != NULL);
+       _DIAGASSERT(names != NULL);
+
+       for (nm = names; *nm; nm++)
+               if (strcasecmp(t, *nm) == 0)
+                       return (nm - names);
+       if (isdigit((unsigned char) *t))
+               return (atoi(t));
+       return (0);
+}
+
+#if 0
+static void
+error(err)
+       int err;
+{
+       char *p;
+
+       (void)write(STDERR_FILENO, "disktab: ", 9);
+       (void)write(STDERR_FILENO, _PATH_DISKTAB, sizeof(_PATH_DISKTAB) - 1);
+       (void)write(STDERR_FILENO, ": ", 2);
+       p = strerror(err);
+       (void)write(STDERR_FILENO, p, strlen(p));
+       (void)write(STDERR_FILENO, "\n", 1);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/endutxent.3 b/lib/nbsd_libc/gen/endutxent.3
new file mode 100644 (file)
index 0000000..06a4433
--- /dev/null
@@ -0,0 +1,202 @@
+.\"    $NetBSD: endutxent.3,v 1.5 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 2002 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Thomas Klausner.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd September 26, 2002
+.Dt ENDUTXENT 3
+.Os
+.Sh NAME
+.Nm endutxent ,
+.Nm getutxent ,
+.Nm getutxid ,
+.Nm getutxline ,
+.Nm pututxline ,
+.Nm setutxent
+.Nd user accounting database functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In utmpx.h
+.Ft void
+.Fn endutxent void
+.Ft struct utmpx *
+.Fn getutxent void
+.Ft struct utmpx *
+.Fn getutxid "const struct utmpx *"
+.Ft struct utmpx *
+.Fn getutxline "const struct utmpx *"
+.Ft struct utmpx *
+.Fn pututxline "const struct utmpx *"
+.Ft void
+.Fn setutxent void
+.Sh DESCRIPTION
+These functions provide access to the
+.Xr utmpx 5
+user accounting database.
+.Pp
+.Fn getutxent
+reads the next entry from the database;
+if the database was not yet open, it also opens it.
+.Fn setutxent
+resets the database, so that the next
+.Fn getutxent
+call will get the first entry.
+.Fn endutxent
+closes the database.
+.Pp
+.Fn getutxid
+returns the next entry of the type specified in its argument's
+.Va ut_type
+field, or
+.Dv NULL
+if none is found.
+.Fn getutxline
+returns the next
+.Dv LOGIN_PROCESS
+or
+.Dv USER_PROCESS
+entry which has the same name as specified in the
+.Va ut_line
+field, or
+.Dv NULL
+if no match is found.
+.Pp
+.Fn pututxline
+adds the argument
+.Xr utmpx 5
+entry line to the accounting database, replacing a previous entry for
+the same user if it exists.
+.Ss The utmpx structure
+The
+.Nm utmpx
+structure has the following definition:
+.Pp
+.Bd -literal
+struct utmpx {
+        char ut_name[_UTX_USERSIZE];    /* login name */
+        char ut_id[_UTX_IDSIZE];        /* inittab id */
+        char ut_line[_UTX_LINESIZE];    /* tty name */
+        char ut_host[_UTX_HOSTSIZE];    /* host name */
+        uint16_t ut_session;            /* session id used for windowing */
+        uint16_t ut_type;               /* type of this entry */
+        pid_t ut_pid;                   /* process id creating the entry */
+        struct {
+                uint16_t e_termination; /* process termination signal */
+                uint16_t e_exit;        /* process exit status */
+        } ut_exit;
+        struct sockaddr_storage ut_ss;  /* address where entry was made from */
+        struct timeval ut_tv;           /* time entry was created */
+        uint32_t ut_pad[10];            /* reserved for future use */
+};
+.Ed
+.Pp
+Valid entries for
+.Fa ut_type
+are:
+.Bl -tag -width LOGIN_PROCESSXX -compact -offset indent
+.It Dv BOOT_TIME
+Time of a system boot.
+.It Dv DEAD_PROCESS
+A session leader exited.
+.It Dv EMPTY
+No valid user accounting information.
+.It Dv INIT_PROCESS
+A process spawned by
+.Xr init 8 .
+.It Dv LOGIN_PROCESS
+The session leader of a logged-in user.
+.It Dv NEW_TIME
+Time after system clock change.
+.It Dv OLD_TIME
+Time before system clock change.
+.It Dv RUN_LVL
+Run level.
+Provided for compatibility, not used on
+.Nx .
+.It Dv USER_PROCESS
+A user process.
+.El
+.Sh RETURN VALUES
+.Fn getutxent
+returns the next entry, or
+.Dv NULL
+on failure (end of database or problems reading from the database).
+.Fn getutxid
+and
+.Fn getutxline
+return the matching structure on success, or
+.Dv NULL
+if no match was found.
+.Fn pututxline
+returns the structure that was successfully written, or
+.Dv NULL .
+.Sh SEE ALSO
+.Xr logwtmpx 3 ,
+.Xr utmpx 5
+.Sh STANDARDS
+The
+.Fn endutxent ,
+.Fn getutxent ,
+.Fn getutxid ,
+.Fn getutxline ,
+.Fn pututxline ,
+.Fn setutxent
+all conform to
+.St -p1003.1-2001
+(XSI extension), and previously to
+.St -xpg4.2 .
+The fields
+.Fa ut_user ,
+.Fa ut_id ,
+.Fa ut_line ,
+.Fa ut_pid ,
+.Fa ut_type ,
+and
+.Fa ut_tv
+conform to
+.St -p1003.1-2001
+(XSI extension), and previously to
+.St -xpg4.2 .
+.\" .Fa ut_host ,
+.\" .Fa ut_session ,
+.\" .Fa ut_exit ,
+.\" and
+.\" .Fa ut_ss
+.\" are from
+.\" SVR3/4?
+.\" .Dv RUN_LVL
+.\" is for compatibility with
+.\" what exactly?
+.\" .Sh HISTORY
+.\" The
+.\" .Nm utmpx ,
+.\" .Nm wtmpx ,
+.\" and
+.\" .Nm lastlogx
+.\" files first appeared in
+.\" SVR3? 4?
diff --git a/lib/nbsd_libc/gen/err.3 b/lib/nbsd_libc/gen/err.3
new file mode 100644 (file)
index 0000000..92f2629
--- /dev/null
@@ -0,0 +1,174 @@
+.\" $NetBSD: err.3,v 1.20 2010/03/22 19:30:53 joerg Exp $
+.\"
+.\" Copyright (c) 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.
+.\" 3. 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.
+.\"
+.\"    @(#)err.3       8.1 (Berkeley) 6/9/93
+.\"
+.Dd March 21, 2001
+.Dt ERR 3
+.Os
+.Sh NAME
+.Nm err ,
+.Nm verr ,
+.Nm errx ,
+.Nm verrx ,
+.Nm warn ,
+.Nm vwarn ,
+.Nm warnx ,
+.Nm vwarnx
+.Nd formatted error messages
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In err.h
+.Ft void
+.Fn err "int status" "const char *fmt" "..."
+.Ft void
+.Fn verr "int status" "const char *fmt" "va_list args"
+.Ft void
+.Fn errx "int status" "const char *fmt" "..."
+.Ft void
+.Fn verrx "int status" "const char *fmt" "va_list args"
+.Ft void
+.Fn warn "const char *fmt" "..."
+.Ft void
+.Fn vwarn "const char *fmt" "va_list args"
+.Ft void
+.Fn warnx "const char *fmt" "..."
+.Ft void
+.Fn vwarnx "const char *fmt" "va_list args"
+.Sh DESCRIPTION
+The
+.Fn err
+and
+.Fn warn
+family of functions display a formatted error message on the standard
+error output.
+In all cases, the last component of the program name, a colon character,
+and a space are output.
+If the
+.Fa fmt
+argument is not
+.Dv NULL ,
+the formatted error message is output.
+In the case of the
+.Fn err ,
+.Fn verr ,
+.Fn warn ,
+and
+.Fn vwarn
+functions, the error message string affiliated with the current value of
+the global variable
+.Va errno
+is output next, preceded by a colon character and a space if
+.Fa fmt
+is not
+.Dv NULL .
+In all cases, the output is followed by a newline character.
+The
+.Fn errx ,
+.Fn verrx ,
+.Fn warnx ,
+and
+.Fn vwarnx
+functions will not output this error message string.
+.Pp
+The
+.Fn err ,
+.Fn verr ,
+.Fn errx ,
+and
+.Fn verrx
+functions do not return, but instead cause the program to terminate
+with the status value given by the argument
+.Fa status .
+It is often appropriate to use the value
+.Dv EXIT_FAILURE ,
+defined in
+.In stdlib.h ,
+as the
+.Fa status
+argument given to these functions.
+.Sh EXAMPLES
+Display the current
+.Va errno
+information string and terminate with status indicating failure:
+.Bd -literal -offset indent
+if ((p = malloc(size)) == NULL)
+       err(EXIT_FAILURE, NULL);
+if ((fd = open(file_name, O_RDONLY, 0)) == -1)
+       err(EXIT_FAILURE, "%s", file_name);
+.Ed
+.Pp
+Display an error message and terminate with status indicating failure:
+.Bd -literal -offset indent
+if (tm.tm_hour \*[Lt] START_TIME)
+       errx(EXIT_FAILURE, "too early, wait until %s",
+           start_time_string);
+.Ed
+.Pp
+Warn of an error:
+.Bd -literal -offset indent
+if ((fd = open(raw_device, O_RDONLY, 0)) == -1)
+       warnx("%s: %s: trying the block device",
+           raw_device, strerror(errno));
+if ((fd = open(block_device, O_RDONLY, 0)) == -1)
+       warn("%s", block_device);
+.Ed
+.Sh SEE ALSO
+.Xr exit 3 ,
+.Xr getprogname 3 ,
+.Xr strerror 3
+.Sh HISTORY
+The
+.Fn err
+and
+.Fn warn
+functions first appeared in
+.Bx 4.4 .
+.Sh CAVEATS
+It is important never to pass a string with user-supplied data as a
+format without using
+.Ql %s .
+An attacker can put format specifiers in the string to mangle your stack,
+leading to a possible security hole.
+This holds true even if you have built the string
+.Dq by hand
+using a function like
+.Fn snprintf ,
+as the resulting string may still contain user-supplied conversion specifiers
+for later interpolation by the
+.Fn err
+and
+.Fn warn
+functions.
+.Pp
+Always be sure to use the proper secure idiom:
+.Bd -literal -offset indent
+err(1, "%s", string);
+.Ed
diff --git a/lib/nbsd_libc/gen/err.c b/lib/nbsd_libc/gen/err.c
new file mode 100644 (file)
index 0000000..9bd01b0
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: err.c,v 1.26 2007/06/18 14:13:54 ginsbach Exp $        */
+
+/*-
+ * Copyright (c) 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)err.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: err.c,v 1.26 2007/06/18 14:13:54 ginsbach Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <err.h>
+#include <stdarg.h>
+
+#ifdef __weak_alias
+__weak_alias(err, _err)
+#endif
+
+#if !HAVE_ERR_H
+__dead void
+err(int eval, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       verr(eval, fmt, ap);
+       va_end(ap);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/errlist.awk b/lib/nbsd_libc/gen/errlist.awk
new file mode 100644 (file)
index 0000000..81c43fc
--- /dev/null
@@ -0,0 +1,113 @@
+#! /usr/bin/awk -f
+#      $NetBSD: errlist.awk,v 1.4 2010/12/16 22:52:32 joerg Exp $
+#
+# Copyright (c) 2010 The NetBSD Foundation, Inc.
+# All rights reserved.
+#
+# This code is derived from software contributed to The NetBSD Foundation
+# by Christos Zoulas.
+#
+# 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. All advertising materials mentioning features or use of this software
+#    must display the following acknowledgement:
+#        This product includes software developed by the NetBSD
+#        Foundation, Inc. and its contributors.
+# 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+#
+function tabs(desc) {
+       l = length(desc) + 3;
+       if (concat)
+               l++
+       if (l < 16)
+               return "\t\t\t\t";
+       else if (l < 24)
+               return "\t\t\t";
+       else if (l < 32)
+               return "\t\t";
+       else if (l < 40)
+               return "\t";
+       else
+               return "";
+}
+function perror(name, number, desc)
+{
+       if (!concat) {
+               printf("\t\"%s\",%s/* %d - %s */\n", desc, tabs(desc), number, name);
+       } else {
+               offsets[number] = offset;
+               offset += length(desc) + 1;
+               printf("\t\"%s\\0\"%s/* %d - %s */\n", desc, tabs(desc), number, name);
+       }
+}
+BEGIN {
+       printf("/* Automatically generated file; do not edit */\n");
+       printf("#include <sys/cdefs.h>\n");
+       printf("__RCSID(\"$NetBSD: errlist.awk,v 1.4 2010/12/16 22:52:32 joerg Exp $\");\n");
+       printf("#include <errno.h>\n");
+       if (!concat) {
+               printf("static const char *const errlist[] = {\n");
+       } else {
+               printf("static const char concat_errlist[] = {\n");
+               offset = 0;
+       }
+       perror("ENOERROR", 0, "Undefined error: 0");
+       errno = 1;
+}
+/^#define/ {
+       name = $2;
+       if (name == "ELAST")
+               next;
+       number = $3;
+       if (number < 0 || number == "EAGAIN")
+               next;
+       desc = $0;
+       i1 = index(desc, "/*") + 3;
+       l = length(desc);
+       desc = substr(desc, i1, l - i1 - 2);
+       if (number != errno) {
+               printf("error number mismatch %d != %d\n", number, errno) > "/dev/stderr";
+               exit(1);
+       }
+       perror(name, number, desc);
+       errno++;
+}
+END {
+       printf("};\n\n");
+       if (!concat) {
+               printf("const int sys_nerr = sizeof(errlist) / sizeof(errlist[0]);\n");
+               printf("const char * const *sys_errlist = errlist;\n");
+       } else {
+               printf("static const int concat_nerr = %d;\n", errno);
+               printf("static const unsigned short concat_offset[] = {\n");
+               offsets[errno++] = offset;
+               for (j = 0; j < errno; j++) {
+                       printf("\t%d,\n", offsets[j]);
+               }
+               printf("};\n");
+               if (offset > 65535) {
+                       printf("Total errlist size doesn't fit into 16bit\n") > "/dev/stderr";
+                       exit(1);
+               }
+       }
+}
diff --git a/lib/nbsd_libc/gen/errno.c b/lib/nbsd_libc/gen/errno.c
new file mode 100644 (file)
index 0000000..ca8b2ac
--- /dev/null
@@ -0,0 +1,8 @@
+/*     $NetBSD: errno.c,v 1.5 2005/06/12 05:21:27 lukem Exp $  */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: errno.c,v 1.5 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+int errno;
diff --git a/lib/nbsd_libc/gen/errx.c b/lib/nbsd_libc/gen/errx.c
new file mode 100644 (file)
index 0000000..004fdd6
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: errx.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $       */
+
+/*-
+ * Copyright (c) 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)err.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: errx.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <err.h>
+#include <stdarg.h>
+
+#ifdef __weak_alias
+__weak_alias(errx, _errx)
+#endif
+
+#if !HAVE_ERR_H
+__dead void
+errx(int eval, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       verrx(eval, fmt, ap);
+       va_end(ap);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/exec.3 b/lib/nbsd_libc/gen/exec.3
new file mode 100644 (file)
index 0000000..ec529ba
--- /dev/null
@@ -0,0 +1,262 @@
+.\"    $NetBSD: exec.3,v 1.21 2010/03/22 19:30:53 joerg Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)exec.3     8.3 (Berkeley) 1/24/94
+.\"
+.Dd May 6, 2005
+.Dt EXEC 3
+.Os
+.Sh NAME
+.Nm execl ,
+.Nm execlp ,
+.Nm execle ,
+.Nm exect ,
+.Nm execv ,
+.Nm execvp
+.Nd execute a file
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Vt extern char **environ;
+.Ft int
+.Fn execl "const char *path" "const char *arg" ...
+.Ft int
+.Fn execlp "const char *file" "const char *arg" ...
+.Ft int
+.Fn execle "const char *path" "const char *arg" ... "char *const envp[]"
+.Ft int
+.Fn exect "const char *path" "char *const argv[]"  "char *const envp[]"
+.Ft int
+.Fn execv "const char *path" "char *const argv[]"
+.Ft int
+.Fn execvp "const char *file" "char *const argv[]"
+.Sh DESCRIPTION
+The
+.Nm exec
+family of functions replaces the current process image with a
+new process image.
+The functions described in this manual page are front-ends for the function
+.Xr execve 2 .
+(See the manual page for
+.Xr execve 2
+for detailed information about the replacement of the current process.
+The
+.Xr script 7
+manual page provides detailed information about the execution of
+interpreter scripts.)
+.Pp
+The initial argument for these functions is the pathname of a file which
+is to be executed.
+.Pp
+The
+.Fa "const char *arg"
+and subsequent ellipses in the
+.Fn execl ,
+.Fn execlp ,
+and
+.Fn execle
+functions can be thought of as
+.Em arg0 ,
+.Em arg1 ,
+\&...,
+.Em argn .
+Together they describe a list of one or more pointers to null-terminated
+strings that represent the argument list available to the executed program.
+The first argument, by convention, should point to the file name associated
+with the file being executed.
+The list of arguments
+.Em must
+be terminated by a
+.Dv NULL
+pointer.
+.Pp
+The
+.Fn exect ,
+.Fn execv ,
+and
+.Fn execvp
+functions provide an array of pointers to null-terminated strings that
+represent the argument list available to the new program.
+The first argument, by convention, should point to the file name associated
+with the file being executed.
+The array of pointers
+.Sy must
+be terminated by a
+.Dv NULL
+pointer.
+.Pp
+The
+.Fn execle
+and
+.Fn exect
+functions also specify the environment of the executed process by following
+the
+.Dv NULL
+pointer that terminates the list of arguments in the parameter list
+or the pointer to the argv array with an additional parameter.
+This additional parameter is an array of pointers to null-terminated strings
+and
+.Em must
+be terminated by a
+.Dv NULL
+pointer.
+The other functions take the environment for the new process image from the
+external variable
+.Va environ
+in the current process.
+.Pp
+Some of these functions have special semantics.
+.Pp
+The functions
+.Fn execlp
+and
+.Fn execvp
+will duplicate the actions of the shell in searching for an executable file
+if the specified file name does not contain a slash
+.Dq Li \&/
+character.
+The search path is the path specified in the environment by the
+.Ev PATH
+variable.
+If this variable isn't specified,
+.Va _PATH_DEFPATH
+from
+.In paths.h
+is used instead, its value being:
+.Pa /usr/bin:/bin:/usr/pkg/bin:/usr/local/bin .
+In addition, certain errors are treated specially.
+.Pp
+If permission is denied for a file (the attempted
+.Xr execve 2
+returned
+.Er EACCES ) ,
+these functions will continue searching the rest of
+the search path.
+If no other file is found, however, they will return with the global variable
+.Va errno
+set to
+.Er EACCES .
+.Pp
+If the header of a file isn't recognized (the attempted
+.Xr execve 2
+returned
+.Er ENOEXEC ) ,
+these functions will execute the shell with the path of
+the file as its first argument.
+(If this attempt fails, no further searching is done.)
+.Pp
+If the file is currently busy (the attempted
+.Xr execve 2
+returned
+.Er ETXTBUSY ) ,
+these functions will sleep for several seconds,
+periodically re-attempting to execute the file.
+.Pp
+The function
+.Fn exect
+executes a file with the program tracing facilities enabled (see
+.Xr ptrace 2 ) .
+.Sh RETURN VALUES
+If any of the
+.Nm exec
+functions returns, an error will have occurred.
+The return value is \-1, and the global variable
+.Va errno
+will be set to indicate the error.
+.Sh FILES
+.Bl -tag -width /bin/sh -compact
+.It Pa /bin/sh
+The shell.
+.El
+.Sh ERRORS
+.Fn execl ,
+.Fn execle ,
+.Fn execlp
+and
+.Fn execvp
+may fail and set
+.Va errno
+for any of the errors specified for the library functions
+.Xr execve 2
+and
+.Xr malloc 3 .
+.Pp
+.Fn exect
+and
+.Fn execv
+may fail and set
+.Va errno
+for any of the errors specified for the library function
+.Xr execve 2 .
+.Sh SEE ALSO
+.Xr sh 1 ,
+.Xr execve 2 ,
+.Xr fork 2 ,
+.Xr ptrace 2 ,
+.Xr environ 7 ,
+.Xr script 7
+.Sh COMPATIBILITY
+Historically, the default path for the
+.Fn execlp
+and
+.Fn execvp
+functions was
+.Dq Pa :/bin:/usr/bin .
+This was changed to improve security and behaviour.
+.Pp
+The behavior of
+.Fn execlp
+and
+.Fn execvp
+when errors occur while attempting to execute the file is historic
+practice, but has not traditionally been documented and is not specified
+by the
+.Tn POSIX
+standard.
+.Pp
+Traditionally, the functions
+.Fn execlp
+and
+.Fn execvp
+ignored all errors except for the ones described above and
+.Er ENOMEM
+and
+.Er E2BIG ,
+upon which they returned.
+They now return if any error other than the ones described above occurs.
+.Sh STANDARDS
+.Fn execl ,
+.Fn execv ,
+.Fn execle ,
+.Fn execlp
+and
+.Fn execvp
+conform to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/gen/execl.c b/lib/nbsd_libc/gen/execl.c
new file mode 100644 (file)
index 0000000..9de075c
--- /dev/null
@@ -0,0 +1,86 @@
+/*     $NetBSD: execl.c,v 1.16 2008/01/09 11:26:03 simonb Exp $        */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)exec.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: execl.c,v 1.16 2008/01/09 11:26:03 simonb Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <errno.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include "reentrant.h"
+
+#ifdef __weak_alias
+__weak_alias(execl,_execl)
+#endif
+
+
+extern char **environ;
+
+int
+execl(const char *name, const char *arg, ...)
+{
+       int r;
+#if defined(__i386__) || defined(__m68k__)
+       r = execve(name, __UNCONST(&arg), environ);
+       return r;
+#else
+       va_list ap;
+       char **argv;
+       int i;
+
+       va_start(ap, arg);
+       for (i = 2; va_arg(ap, char *) != NULL; i++)
+               continue;
+       va_end(ap);
+
+       if ((argv = alloca(i * sizeof (char *))) == NULL) {
+               errno = ENOMEM;
+               return -1;
+       }
+       
+       va_start(ap, arg);
+       argv[0] = __UNCONST(arg);
+       for (i = 1; (argv[i] = va_arg(ap, char *)) != NULL; i++) 
+               continue;
+       va_end(ap);
+       
+       r = execve(name, argv, environ);
+       return r;
+#endif
+}
diff --git a/lib/nbsd_libc/gen/execle.c b/lib/nbsd_libc/gen/execle.c
new file mode 100644 (file)
index 0000000..1d9a4a4
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: execle.c,v 1.11 2008/01/09 11:26:03 simonb Exp $       */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)exec.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: execle.c,v 1.11 2008/01/09 11:26:03 simonb Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <stdarg.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(execle,_execle)
+#endif
+
+int
+execle(const char *name, const char *arg, ...)
+{
+#if defined(__i386__) || defined(__m68k__)
+       va_list ap;
+       char **envp;
+
+       va_start(ap, arg);
+       while ((va_arg(ap, char *)) != NULL)
+               continue;
+       envp = va_arg(ap, char **);
+       va_end(ap);
+
+       return execve(name, __UNCONST(&arg), envp);
+#else
+       va_list ap;
+       char **argv, **envp;
+       int i;
+
+       va_start(ap, arg);
+       for (i = 2; va_arg(ap, char *) != NULL; i++)
+               continue;
+       va_end(ap);
+
+       argv = alloca(i * sizeof (char *));
+       
+       va_start(ap, arg);
+       argv[0] = __UNCONST(arg);
+       for (i = 1; (argv[i] = va_arg(ap, char *)) != NULL; i++) 
+               continue;
+       envp = va_arg(ap, char **);
+       va_end(ap);
+
+       return execve(name, argv, envp);
+#endif
+}
diff --git a/lib/nbsd_libc/gen/execlp.c b/lib/nbsd_libc/gen/execlp.c
new file mode 100644 (file)
index 0000000..8b84cd1
--- /dev/null
@@ -0,0 +1,75 @@
+/*     $NetBSD: execlp.c,v 1.11 2008/01/09 11:26:03 simonb Exp $       */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)exec.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: execlp.c,v 1.11 2008/01/09 11:26:03 simonb Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <stdarg.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(execlp,_execlp)
+#endif
+
+int
+execlp(const char *name, const char *arg, ...)
+{
+#if defined(__i386__) || defined(__m68k__)
+       return execvp(name, __UNCONST(&arg));
+#else
+       va_list ap;
+       char **argv;
+       int i;
+
+       va_start(ap, arg);
+       for (i = 2; va_arg(ap, char *) != NULL; i++)
+               continue;
+       va_end(ap);
+
+       argv = alloca(i * sizeof (char *));
+       
+       va_start(ap, arg);
+       argv[0] = __UNCONST(arg);
+       for (i = 1; (argv[i] = va_arg(ap, char *)) != NULL; i++) 
+               continue;
+       va_end(ap);
+       
+       return execvp(name, argv);
+#endif
+}
diff --git a/lib/nbsd_libc/gen/execv.c b/lib/nbsd_libc/gen/execv.c
new file mode 100644 (file)
index 0000000..2bfc800
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: execv.c,v 1.9 2005/11/29 13:30:49 christos Exp $       */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)exec.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: execv.c,v 1.9 2005/11/29 13:30:49 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <unistd.h>
+#include "reentrant.h"
+
+#ifdef __weak_alias
+__weak_alias(execv,_execv)
+#endif
+
+extern char **environ;
+
+int
+execv(name, argv)
+       const char *name;
+       char * const *argv;
+{
+       return execve(name, argv, environ);
+}
diff --git a/lib/nbsd_libc/gen/execvp.c b/lib/nbsd_libc/gen/execvp.c
new file mode 100644 (file)
index 0000000..4a4a3cf
--- /dev/null
@@ -0,0 +1,155 @@
+/*     $NetBSD: execvp.c,v 1.30 2007/07/20 12:41:07 yamt Exp $ */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)exec.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: execvp.c,v 1.30 2007/07/20 12:41:07 yamt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <unistd.h>
+#include <paths.h>
+#include "reentrant.h"
+
+#ifdef __weak_alias
+__weak_alias(execvp,_execvp)
+#endif
+
+extern char **environ;
+
+int
+execvp(const char *name, char * const *argv)
+{
+       const char **memp;
+       int cnt;
+       size_t lp, ln;
+       int eacces = 0;
+       unsigned int etxtbsy = 0;
+       char buf[PATH_MAX];
+       const char *bp, *path, *p;
+
+       _DIAGASSERT(name != NULL);
+
+       /* "" is not a valid filename; check this before traversing PATH. */
+       if (name[0] == '\0') {
+               errno = ENOENT;
+               goto done;
+       }
+       ln = strlen(name);
+       /* If it's an absolute or relative path name, it's easy. */
+       if (strchr(name, '/')) {
+               bp = name;
+               path = "";
+               goto retry;
+       }
+       bp = buf;
+
+       /* Get the path we're searching. */
+       if (!(path = getenv("PATH")))
+               path = _PATH_DEFPATH;
+
+       do {
+               /* Find the end of this path element. */
+               for (p = path; *path != 0 && *path != ':'; path++)
+                       continue;
+               /*
+                * It's a SHELL path -- double, leading and trailing colons
+                * mean the current directory.
+                */
+               if (p == path) {
+                       p = ".";
+                       lp = 1;
+               } else
+                       lp = path - p;
+
+               /*
+                * If the path is too long complain.  This is a possible
+                * security issue; given a way to make the path too long
+                * the user may execute the wrong program.
+                */
+               if (lp + ln + 2 > sizeof(buf)) {
+                       (void)write(STDERR_FILENO, "execvp: ", 8);
+                       (void)write(STDERR_FILENO, p, lp);
+                       (void)write(STDERR_FILENO, ": path too long\n", 16);
+                       continue;
+               }
+               memcpy(buf, p, lp);
+               buf[lp] = '/';
+               memcpy(buf + lp + 1, name, ln);
+               buf[lp + ln + 1] = '\0';
+
+retry:         (void)execve(bp, argv, environ);
+               switch (errno) {
+               case EACCES:
+                       eacces = 1;
+                       break;
+               case ENOTDIR:
+               case ENOENT:
+                       break;
+               case ENOEXEC:
+                       for (cnt = 0; argv[cnt] != NULL; ++cnt)
+                               continue;
+                       /*
+                        * we can't use malloc here because, if we are doing
+                        * vfork+exec, it leaks memory in the parent.
+                        */
+                       if ((memp = alloca((cnt + 2) * sizeof(*memp))) == NULL)
+                               goto done;
+                       memp[0] = _PATH_BSHELL;
+                       memp[1] = bp;
+                       (void)memcpy(&memp[2], &argv[1], cnt * sizeof(*memp));
+                       (void)execve(_PATH_BSHELL, __UNCONST(memp), environ);
+                       goto done;
+               case ETXTBSY:
+                       if (etxtbsy < 3)
+                               (void)sleep(++etxtbsy);
+                       goto retry;
+               default:
+                       goto done;
+               }
+       } while (*path++ == ':');       /* Otherwise, *path was NUL */
+       if (eacces)
+               errno = EACCES;
+       else if (!errno)
+               errno = ENOENT;
+done:
+       return (-1);
+}
diff --git a/lib/nbsd_libc/gen/extattr.3 b/lib/nbsd_libc/gen/extattr.3
new file mode 100644 (file)
index 0000000..3c6a97c
--- /dev/null
@@ -0,0 +1,99 @@
+.\"    $NetBSD: extattr.3,v 1.3 2005/01/02 18:25:09 wiz Exp $
+.\"
+.\" Copyright (c) 2001 Dima Dorfman <dd@FreeBSD.org>
+.\" 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.
+.\"
+.\" FreeBSD: src/lib/libc/posix1e/extattr.3,v 1.5 2002/12/12 17:25:53 ru Exp
+.\"
+.Dd January 2, 2004
+.Dt EXTATTR 3
+.Os
+.Sh NAME
+.Nm extattr_namespace_to_string ,
+.Nm extattr_string_to_namespace
+.Nd convert an extended attribute namespace identifier to a string and vice versa
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/extattr.h
+.Ft int
+.Fn extattr_namespace_to_string "int attrnamespace" "char **string"
+.Ft int
+.Fn extattr_string_to_namespace "const char *string" "int *attrnamespace"
+.Sh DESCRIPTION
+The
+.Fn extattr_namespace_to_string
+function converts a VFS extended attribute identifier to a human-readable
+string.
+The
+.Fn extattr_string_to_namespace
+converts a human-readable string representing a namespace to a
+namespace identifier.
+Although a file system may implement arbitrary namespaces,
+these functions only support the
+.Dv EXTATTR_NAMESPACE_USER
+.Pq Dq user
+and
+.Dv EXTATTR_NAMESPACE_SYSTEM
+.Pq Dq system
+namespaces,
+which are defined in
+.Xr extattr 9 .
+.Pp
+These functions are meant to be used in error reporting and other
+interactive tasks.
+For example,
+instead of printing the integer identifying an extended attribute in
+an error message,
+a program might use
+.Fn extattr_namespace_to_string
+to obtain a human-readable representation.
+Likewise,
+instead of requiring a user to enter the integer representing a namespace,
+an interactive program might ask for a name and use
+.Fn extattr_string_to_namespace
+to get the desired identifier.
+.Sh RETURN VALUES
+If any of the calls are unsuccessful, the value \-1 is returned
+and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The requested namespace could not be identified.
+.El
+.Sh SEE ALSO
+.Xr getextattr 1 ,
+.Xr extattr_get_file 2 ,
+.Xr extattr 9
+.Sh HISTORY
+Extended attribute support was developed as part of the
+.Tn TrustedBSD
+Project, and introduced in
+.Fx 5.0
+and
+.Nx 3.0 .
+It was developed to support security extensions requiring additional labels
+to be associated with each file or directory.
diff --git a/lib/nbsd_libc/gen/extattr.c b/lib/nbsd_libc/gen/extattr.c
new file mode 100644 (file)
index 0000000..90c9c5c
--- /dev/null
@@ -0,0 +1,87 @@
+/*     $NetBSD: extattr.c,v 1.2 2005/02/09 21:35:46 kleink Exp $       */
+
+/*-
+ * Copyright (c) 2001 Robert N. M. Watson
+ * 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.
+ */
+
+/*
+ * TrustedBSD: Utility functions for extended attributes.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: extattr.c,v 1.2 2005/02/09 21:35:46 kleink Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/extattr.h>
+
+#include <errno.h>
+#include <string.h>
+
+int
+extattr_namespace_to_string(int attrnamespace, char **string)
+{
+
+       switch(attrnamespace) {
+       case EXTATTR_NAMESPACE_USER:
+               if (string != NULL) {
+                       if ((*string =
+                            strdup(EXTATTR_NAMESPACE_USER_STRING)) == NULL)
+                               return (-1);
+               }
+               return (0);
+
+       case EXTATTR_NAMESPACE_SYSTEM:
+               if (string != NULL)
+                       if ((*string =
+                            strdup(EXTATTR_NAMESPACE_SYSTEM_STRING)) == NULL)
+                               return (-1);
+               return (0);
+
+       default:
+               errno = EINVAL;
+               return (-1);
+       }
+}
+
+int
+extattr_string_to_namespace(const char *string, int *attrnamespace)
+{
+
+       if (strcmp(string, EXTATTR_NAMESPACE_USER_STRING) == 0) {
+               if (attrnamespace != NULL)
+                       *attrnamespace = EXTATTR_NAMESPACE_USER;
+               return (0);
+       } else if (strcmp(string, EXTATTR_NAMESPACE_SYSTEM_STRING) == 0) {
+               if (attrnamespace != NULL)
+                       *attrnamespace = EXTATTR_NAMESPACE_SYSTEM;
+               return (0);
+       } else {
+               errno = EINVAL;
+               return (-1);
+       }
+}
diff --git a/lib/nbsd_libc/gen/fabs_ieee754.c b/lib/nbsd_libc/gen/fabs_ieee754.c
new file mode 100644 (file)
index 0000000..006004b
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: fabs_ieee754.c,v 1.2 2010/09/10 16:32:35 matt Exp $    */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fabs_ieee754.c,v 1.2 2010/09/10 16:32:35 matt Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.6 fabs - return the absolute value of the argument
+ *          IEEE 754 double-precision version
+ */
+double
+fabs(double x)
+{
+       union ieee_double_u u;
+
+       u.dblu_d = x;
+
+       u.dblu_dbl.dbl_sign = 0;
+
+       return u.dblu_d;
+}
diff --git a/lib/nbsd_libc/gen/fmtcheck.3 b/lib/nbsd_libc/gen/fmtcheck.3
new file mode 100644 (file)
index 0000000..4c3c3b5
--- /dev/null
@@ -0,0 +1,97 @@
+.\"    $NetBSD: fmtcheck.3,v 1.7 2009/03/09 19:24:26 joerg Exp $
+.\"
+.\" Copyright (c) 2000 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This file was contributed to The NetBSD Foundation by Allen Briggs.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd October 17, 2000
+.Dt FMTCHECK 3
+.Os
+.Sh NAME
+.Nm fmtcheck
+.Nd sanitizes user-supplied printf(3)-style format string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft const char *
+.Fn fmtcheck "const char *fmt_suspect" "const char *fmt_default"
+.Sh DESCRIPTION
+The
+.Nm
+function scans
+.Fa fmt_suspect
+and
+.Fa fmt_default
+to determine if
+.Fa fmt_suspect
+will consume the same argument types as
+.Fa fmt_default
+and to ensure that
+.Fa fmt_suspect
+is a valid format string.
+.Pp
+The
+.Xr printf 3
+family of functions can not verify the types of arguments that they are
+passed at run-time.
+In some cases, like
+.Xr catgets 3 ,
+it is useful or necessary to use a user-supplied format string with no
+guarantee that the format string matches the specified parameters.
+.Pp
+The
+.Nm
+function was designed to be used in these cases, as in:
+.Bd -literal -offset indent
+printf(fmtcheck(user_format, standard_format), arg1, arg2);
+.Ed
+.Pp
+In the check, field widths, fillers, precisions, etc. are ignored (unless
+the field width or precision is an asterisk
+.Ql *
+instead of a digit string).
+Also, any text other than the format specifiers is completely ignored.
+.Pp
+Note that the formats may be quite different as long as they accept the
+same parameters.
+For example, "%p %o %30s %#llx %-10.*e %n" is
+compatible with "This number %lu %d%% and string %s has %qd numbers
+and %.*g floats (%n)."
+However, "%o" is not equivalent to "%lx" because
+the first requires an integer and the second requires a long.
+.Sh RETURN VALUES
+If
+.Fa fmt_suspect
+is a valid format and consumes the same argument types as
+.Fa fmt_default ,
+then the
+.Nm
+function will return
+.Fa fmt_suspect .
+Otherwise, it will return
+.Fa fmt_default .
+.Sh SEE ALSO
+.Xr printf 3
diff --git a/lib/nbsd_libc/gen/fmtcheck.c b/lib/nbsd_libc/gen/fmtcheck.c
new file mode 100644 (file)
index 0000000..7c779be
--- /dev/null
@@ -0,0 +1,243 @@
+/*     $NetBSD: fmtcheck.c,v 1.8 2008/04/28 20:22:59 martin Exp $      */
+
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code was contributed to The NetBSD Foundation by Allen Briggs.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fmtcheck.c,v 1.8 2008/04/28 20:22:59 martin Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <stdio.h>
+#include <string.h>
+#include <ctype.h>
+
+#ifdef __weak_alias
+__weak_alias(fmtcheck,__fmtcheck)
+#endif
+
+enum __e_fmtcheck_types {
+       FMTCHECK_START,
+       FMTCHECK_SHORT,
+       FMTCHECK_INT,
+       FMTCHECK_LONG,
+       FMTCHECK_QUAD,
+       FMTCHECK_SHORTPOINTER,
+       FMTCHECK_INTPOINTER,
+       FMTCHECK_LONGPOINTER,
+       FMTCHECK_QUADPOINTER,
+       FMTCHECK_DOUBLE,
+       FMTCHECK_LONGDOUBLE,
+       FMTCHECK_STRING,
+       FMTCHECK_WIDTH,
+       FMTCHECK_PRECISION,
+       FMTCHECK_DONE,
+       FMTCHECK_UNKNOWN
+};
+typedef enum __e_fmtcheck_types EFT;
+
+#define RETURN(pf,f,r) do { \
+                       *(pf) = (f); \
+                       return r; \
+                      } /*NOTREACHED*/ /*CONSTCOND*/ while (0)
+
+static EFT
+get_next_format_from_precision(const char **pf)
+{
+       int             sh, lg, quad, longdouble;
+       const char      *f;
+
+       sh = lg = quad = longdouble = 0;
+
+       f = *pf;
+       switch (*f) {
+       case 'h':
+               f++;
+               sh = 1;
+               break;
+       case 'l':
+               f++;
+               if (!*f) RETURN(pf,f,FMTCHECK_UNKNOWN);
+               if (*f == 'l') {
+                       f++;
+                       quad = 1;
+               } else {
+                       lg = 1;
+               }
+               break;
+       case 'q':
+               f++;
+               quad = 1;
+               break;
+       case 'L':
+               f++;
+               longdouble = 1;
+               break;
+       default:
+               break;
+       }
+       if (!*f) RETURN(pf,f,FMTCHECK_UNKNOWN);
+       if (strchr("diouxX", *f)) {
+               if (longdouble)
+                       RETURN(pf,f,FMTCHECK_UNKNOWN);
+               if (lg)
+                       RETURN(pf,f,FMTCHECK_LONG);
+               if (quad)
+                       RETURN(pf,f,FMTCHECK_QUAD);
+               RETURN(pf,f,FMTCHECK_INT);
+       }
+       if (*f == 'n') {
+               if (longdouble)
+                       RETURN(pf,f,FMTCHECK_UNKNOWN);
+               if (sh)
+                       RETURN(pf,f,FMTCHECK_SHORTPOINTER);
+               if (lg)
+                       RETURN(pf,f,FMTCHECK_LONGPOINTER);
+               if (quad)
+                       RETURN(pf,f,FMTCHECK_QUADPOINTER);
+               RETURN(pf,f,FMTCHECK_INTPOINTER);
+       }
+       if (strchr("DOU", *f)) {
+               if (sh + lg + quad + longdouble)
+                       RETURN(pf,f,FMTCHECK_UNKNOWN);
+               RETURN(pf,f,FMTCHECK_LONG);
+       }
+       if (strchr("eEfg", *f)) {
+               if (longdouble)
+                       RETURN(pf,f,FMTCHECK_LONGDOUBLE);
+               if (sh + lg + quad)
+                       RETURN(pf,f,FMTCHECK_UNKNOWN);
+               RETURN(pf,f,FMTCHECK_DOUBLE);
+       }
+       if (*f == 'c') {
+               if (sh + lg + quad + longdouble)
+                       RETURN(pf,f,FMTCHECK_UNKNOWN);
+               RETURN(pf,f,FMTCHECK_INT);
+       }
+       if (*f == 's') {
+               if (sh + lg + quad + longdouble)
+                       RETURN(pf,f,FMTCHECK_UNKNOWN);
+               RETURN(pf,f,FMTCHECK_STRING);
+       }
+       if (*f == 'p') {
+               if (sh + lg + quad + longdouble)
+                       RETURN(pf,f,FMTCHECK_UNKNOWN);
+               RETURN(pf,f,FMTCHECK_LONG);
+       }
+       RETURN(pf,f,FMTCHECK_UNKNOWN);
+       /*NOTREACHED*/
+}
+
+static EFT
+get_next_format_from_width(const char **pf)
+{
+       const char      *f;
+
+       f = *pf;
+       if (*f == '.') {
+               f++;
+               if (*f == '*') {
+                       RETURN(pf,f,FMTCHECK_PRECISION);
+               }
+               /* eat any precision (empty is allowed) */
+               while (isdigit((unsigned char)*f)) f++;
+               if (!*f) RETURN(pf,f,FMTCHECK_UNKNOWN);
+       }
+       RETURN(pf,f,get_next_format_from_precision(pf));
+       /*NOTREACHED*/
+}
+
+static EFT
+get_next_format(const char **pf, EFT eft)
+{
+       int             infmt;
+       const char      *f;
+
+       if (eft == FMTCHECK_WIDTH) {
+               (*pf)++;
+               return get_next_format_from_width(pf);
+       } else if (eft == FMTCHECK_PRECISION) {
+               (*pf)++;
+               return get_next_format_from_precision(pf);
+       }
+
+       f = *pf;
+       infmt = 0;
+       while (!infmt) {
+               f = strchr(f, '%');
+               if (f == NULL)
+                       RETURN(pf,f,FMTCHECK_DONE);
+               f++;
+               if (!*f)
+                       RETURN(pf,f,FMTCHECK_UNKNOWN);
+               if (*f != '%')
+                       infmt = 1;
+               else
+                       f++;
+       }
+
+       /* Eat any of the flags */
+       while (*f && (strchr("#0- +", *f)))
+               f++;
+
+       if (*f == '*') {
+               RETURN(pf,f,FMTCHECK_WIDTH);
+       }
+       /* eat any width */
+       while (isdigit((unsigned char)*f)) f++;
+       if (!*f) {
+               RETURN(pf,f,FMTCHECK_UNKNOWN);
+       }
+
+       RETURN(pf,f,get_next_format_from_width(pf));
+       /*NOTREACHED*/
+}
+
+const char *
+fmtcheck(const char *f1, const char *f2)
+{
+       const char      *f1p, *f2p;
+       EFT             f1t, f2t;
+
+       if (!f1) return f2;
+       
+       f1p = f1;
+       f1t = FMTCHECK_START;
+       f2p = f2;
+       f2t = FMTCHECK_START;
+       while ((f1t = get_next_format(&f1p, f1t)) != FMTCHECK_DONE) {
+               if (f1t == FMTCHECK_UNKNOWN)
+                       return f2;
+               f2t = get_next_format(&f2p, f2t);
+               if (f1t != f2t)
+                       return f2;
+       }
+       return f1;
+}
diff --git a/lib/nbsd_libc/gen/fmtmsg.3 b/lib/nbsd_libc/gen/fmtmsg.3
new file mode 100644 (file)
index 0000000..3b3fb64
--- /dev/null
@@ -0,0 +1,220 @@
+.\"    $NetBSD: fmtmsg.3,v 1.6 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 1999 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd September 10, 1999
+.Dt FMTMSG 3
+.Os
+.Sh NAME
+.Nm fmtmsg
+.Nd format and display a message
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In fmtmsg.h
+.Ft int
+.Fn fmtmsg "long classification" "const char *label" "int severity" "const char *text" "const char *action" "const char *tag"
+.Sh DESCRIPTION
+The
+.Fn fmtmsg
+function can be used to display messages in the specified format.
+Messages may be written either to standard error, to the console, or both.
+.Pp
+A formatted message consists of up to five components specified in
+.Fa label ,
+.Fa severity ,
+.Fa text ,
+.Fa action
+and
+.Fa tag .
+Further information such as the origin of the message, the recoverability
+from the condition causing the message and where to display the message
+is specified in
+.Fa classification .
+.Ss classification
+The
+.Fa classification
+argument consists of a major classification and several sub-classifications.
+It has no effect on the content of the message displayed.
+With the exception of the display sub-classification, only a single identifier
+may be specified for each (sub-)classification.
+The following classifications
+are available:
+.Bl -tag -width MessageXSourceXSub-classificationsXX
+.It Major Classifications
+The source of the condition.
+Available identifiers are:
+.Dv MM_HARD
+(hardware),
+.Dv MM_SOFT
+(software), and
+.Dv MM_FIRM
+(firmware).
+.It Message Source Sub-classifications
+The type of software detecting the condition.
+Available identifiers are:
+.Dv MM_APPL
+(application),
+.Dv MM_UTIL
+(utility), and
+.Dv MM_OPSYS
+(operating system).
+.It Display Sub-classifications
+The displays the formatted messages is to be written to.
+Available identifiers are:
+.Dv MM_PRINT
+(standard error stream) and
+.Dv MM_CONSOLE
+(system console).
+.It Status Sub-classifications
+The capability of the calling software to recover from the condition.
+Available identifiers are:
+.Dv MM_RECOVER
+(recoverable) and
+.Dv MM_NRECOV
+(non-recoverable).
+.El
+.Pp
+If no
+.Fa classification
+is to be supplied,
+.Dv MM_NULLMC
+must be specified.
+.Ss label
+The
+.Fa label
+argument identifies the source of the message.
+It consists of two fields separated by a colon (:).
+The first field is up to 10 characters, the second is up to 14 characters.
+.Pp
+If no
+.Fa label
+is to be supplied,
+.Dv MM_NULLLBL
+must be specified.
+.Ss severity
+The seriousness of the condition causing the message.
+The following
+.Fa severity
+levels are available:
+.Bl -tag -width MM_WARNINGXX
+.It Dv MM_HALT
+The software has encountered a severe fault and is halting.
+.It Dv MM_ERROR
+The software has encountered a fault.
+.It Dv MM_WARNING
+The software has encountered an unusual non-fault condition.
+.It Dv MM_INFO
+The software informs about a non-error condition.
+.El
+.Pp
+If no
+.Fa severity
+level is to be supplied,
+.Dv MM_NOSEV
+must be specified.
+.Ss text
+The description of the condition the software encountered.
+The character
+string is not limited to a specific size.
+.Pp
+If no
+.Fa text
+is to be supplied,
+.Dv MM_NOTXT
+must be specified.
+.Ss action
+The first step to be taken to recover from the condition the software
+encountered; it will be preceded by the prefix
+.Dq TO FIX: .
+The character string is not limited to a specific size.
+.Pp
+If no
+.Fa action
+is to be supplied,
+.Dv MM_NOACT
+must be specified.
+.Ss tag
+The on-line documentation which provides further information about the
+condition and the message, such as
+.Dq Xr fmtmsg 3 .
+The character string is not limited to a specific size.
+.Pp
+If no
+.Fa tag
+is to be supplied,
+.Dv MM_NOTAG
+must be specified.
+.Pp
+Further effect on the formatting of the message as displayed on the
+standard error stream (but not on the system console!) may be taken by
+setting the
+.Ev MSGVERB
+environment variable, which selects the subset of message components
+to be printed.
+It consists of a colon-separated list of the optional keywords
+.Fa label ,
+.Fa severity ,
+.Fa text ,
+.Fa action ,
+and
+.Fa tag ,
+which correspond to the arguments to
+.Fn fmtmsg
+with the same names.
+If
+.Ev MSGVERB
+is either not set or malformed (containing empty or unknown keywords),
+its content is ignored an all message components will be selected.
+.Pp
+Note that displaying a message on the system console may fail due to
+inappropriate privileges or a non-permissive file mode of the console device.
+.Sh RETURN VALUES
+The
+.Fn fmtmsg
+function returns one of the following values:
+.Bl -tag -width MM_NOTOKXXX
+.It Dv MM_OK
+The function succeeded.
+.It Dv MM_NOTOK
+The function failed completely.
+.It Dv MM_NOMSG
+The function was unable to generate a message on standard error,
+but otherwise succeeded.
+.It Dv MM_NOCOM
+The function was unable to generate a message on the console,
+but otherwise succeeded.
+.El
+.Sh SEE ALSO
+.Xr printf 3 ,
+.Xr syslog 3
+.Sh STANDARDS
+The
+.Fn fmtmsg
+function conforms to
+.St -xsh5 .
diff --git a/lib/nbsd_libc/gen/fmtmsg.c b/lib/nbsd_libc/gen/fmtmsg.c
new file mode 100644 (file)
index 0000000..9ca13ac
--- /dev/null
@@ -0,0 +1,246 @@
+/*     $NetBSD: fmtmsg.c,v 1.4 2008/04/28 20:22:59 martin Exp $        */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fmtmsg.c,v 1.4 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <fmtmsg.h>
+#include <paths.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static unsigned int    msgverb __P((const char *));
+static const char *    severity2str __P((int));
+static int             writeit __P((FILE *, unsigned int, const char *,
+                           const char *, const char *, const char *,
+                           const char *));
+
+#define MM_VERBLABEL           0x01U
+#define MM_VERBSEVERITY                0x02U
+#define MM_VERBTEXT            0x04U
+#define MM_VERBACTION          0x08U
+#define MM_VERBTAG             0x10U
+#define MM_VERBALL     \
+    (MM_VERBLABEL | MM_VERBSEVERITY | MM_VERBTEXT | MM_VERBACTION | \
+     MM_VERBTAG)
+
+static const struct keyword {
+       size_t                  len;    /* strlen(keyword) */
+       const char * const      keyword;
+} keywords[] = {
+       { 5,    "label"         },      /* log2(MM_VERBLABEL) */
+       { 8,    "severity"      },      /* ... */
+       { 4,    "text"          },
+       { 6,    "action"        },
+       { 3,    "tag"           }       /* log2(MM_VERBTAG) */
+};
+
+static const size_t nkeywords = sizeof (keywords) / sizeof (keywords[0]);
+
+/*
+ * Convert a colon-separated list of known keywords to a set of MM_VERB*
+ * flags, defaulting to `all' if not set, empty, or in presence of unknown
+ * keywords.
+ */
+static unsigned int
+msgverb(str)
+       const char *str;
+{
+       u_int i;
+       unsigned int result;
+
+       if (str == NULL)
+               return (MM_VERBALL);
+
+       result = 0;
+       while (*str != '\0') {
+               for (i = 0; i < nkeywords; i++) {
+                       if (memcmp(str, keywords[i].keyword, keywords[i].len)
+                           == 0 &&
+                           (*(str + keywords[i].len) == ':' ||
+                            *(str + keywords[i].len) == '\0'))
+                               break;
+               }
+               if (i == nkeywords) {
+                       result = MM_VERBALL;
+                       break;
+               }
+
+               result |= (1 << i);
+               if (*(str += keywords[i].len) == ':')
+                       str++;  /* Advance */
+       }
+       if (result == 0)
+               result = MM_VERBALL;
+
+       return (result);
+}
+
+static const char * const severities[] = {
+       "",             /* MM_NONE */
+       "HALT",
+       "ERROR",
+       "WARNING",
+       "INFO"
+};
+
+static const size_t nseverities = sizeof (severities) / sizeof (severities[0]);
+
+/*
+ * Returns the string representation associated with the numerical severity
+ * value, defaulting to NULL for an unknown value.
+ */
+static const char *
+severity2str(severity)
+       int severity;
+{
+       const char *result;
+
+       if (severity >= 0 &&
+           (u_int) severity < nseverities)
+               result = severities[severity];
+       else
+               result = NULL;
+
+       return (result);
+}
+
+/*
+ * Format and write the message to the given stream, selecting those
+ * components displayed from msgverb, returning the number of characters
+ * written, or a negative value in case of an error.
+ */
+static int
+writeit(stream, which, label, sevstr, text, action, tag)
+       FILE *stream;
+       unsigned int which;
+       const char *label;
+       const char *sevstr;
+       const char *text;
+       const char *action;
+       const char *tag;
+{
+       int nwritten;
+
+       nwritten = fprintf(stream, "%s%s%s%s%s%s%s%s%s%s%s",
+           ((which & MM_VERBLABEL) && label != MM_NULLLBL) ?
+           label : "",
+           ((which & MM_VERBLABEL) && label != MM_NULLLBL) ?
+           ": " : "",
+           (which & MM_VERBSEVERITY) ?
+           sevstr : "",
+           (which & MM_VERBSEVERITY) ?
+           ": " : "",
+           ((which & MM_VERBTEXT) && text != MM_NULLTXT) ?
+           text : "",
+           ((which & MM_VERBLABEL) && label != MM_NULLLBL) ||
+           ((which & MM_VERBSEVERITY)) ||
+           ((which & MM_VERBTEXT) && text != MM_NULLTXT) ?
+           "\n" : "",
+           ((which & MM_VERBACTION) && action != MM_NULLACT) ?
+           "TO FIX: " : "",
+           ((which & MM_VERBACTION) && action != MM_NULLACT) ?
+           action : "",
+           ((which & MM_VERBACTION) && label != MM_NULLACT) ?
+           " " : "",
+           ((which & MM_VERBTAG) && tag != MM_NULLTAG) ?
+           tag : "",
+           ((which & MM_VERBACTION) && action != MM_NULLACT) ||
+           ((which & MM_VERBTAG) && tag != MM_NULLTAG) ?
+           "\n" : "");
+
+       return (nwritten);
+}
+
+int
+fmtmsg(classification, label, severity, text, action, tag)
+       long classification;
+       const char *label;
+       int severity;
+       const char *text;
+       const char *action;
+       const char *tag;
+{
+       FILE *console;
+       const char *p, *sevstr;
+       int result;
+
+       /* Validate label constraints, if not null. */
+       if (label != MM_NULLLBL) {
+               /*
+                * Two fields, separated by a colon.  The first field is up to
+                * 10 bytes, the second is up to 14 bytes.
+                */
+               p = strchr(label, ':');
+               if (p ==  NULL || p - label > 10 || strlen(p + 1) > 14)
+                       return (MM_NOTOK);
+       }
+       /* Validate severity argument. */
+       if ((sevstr = severity2str(severity)) == NULL)
+               return (MM_NOTOK);
+
+       /*
+        * Fact in search for a better place: XSH5 does not define any
+        * functionality for `classification' bits other than the display
+        * subclassification.
+        */
+
+       result = 0;
+
+       if (classification & MM_PRINT) {
+               if (writeit(stderr, msgverb(getenv("MSGVERB")),
+                   label, sevstr, text, action, tag) < 0)
+                       result |= MM_NOMSG;
+       }
+       /* Similar to MM_PRINT but ignoring $MSGVERB. */
+       if (classification & MM_CONSOLE) {
+               if ((console = fopen(_PATH_CONSOLE, "w")) != NULL) {
+                       if (writeit(console, MM_VERBALL,
+                           label, sevstr, text, action, tag) < 0)
+                               result |= MM_NOCON;
+                       /*
+                        * Ignore result: does not constitute ``generate a
+                        * console message.''
+                        */
+                       (void)fclose(console);
+               } else {
+                       result |= MM_NOCON;
+               }
+       }
+
+       if (result == (MM_NOMSG | MM_NOCON))
+               result = MM_NOTOK;
+
+       return (result == 0 ? MM_OK : result);
+}
diff --git a/lib/nbsd_libc/gen/fnmatch.3 b/lib/nbsd_libc/gen/fnmatch.3
new file mode 100644 (file)
index 0000000..e146886
--- /dev/null
@@ -0,0 +1,140 @@
+.\"    $NetBSD: fnmatch.3,v 1.22 2010/11/30 21:03:07 jruoho Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Guido van Rossum.
+.\" 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. 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.
+.\"
+.\"     @(#)fnmatch.3  8.3 (Berkeley) 4/28/95
+.\"
+.Dd November 30, 2010
+.Dt FNMATCH 3
+.Os
+.Sh NAME
+.Nm fnmatch
+.Nd match filename or pathname using shell glob rules
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In fnmatch.h
+.Ft int
+.Fn fnmatch "const char *pattern" "const char *string" "int flags"
+.Sh DESCRIPTION
+The
+.Fn fnmatch
+function
+matches patterns according to the globbing rules used by the shell.
+It checks the string specified by the
+.Fa string
+argument to see if it matches the pattern specified by the
+.Fa pattern
+argument.
+.Pp
+The
+.Fa flags
+argument modifies the interpretation of
+.Fa pattern
+and
+.Fa string .
+The value of
+.Fa flags
+is the bitwise inclusive
+.Tn OR
+of any of the following
+constants, which are defined in the include file
+.Pa fnmatch.h .
+.Bl -tag -width FNM_LEADING_DIRXX
+.It Dv FNM_NOESCAPE
+Normally, every occurrence of a backslash
+.Pq Ql \e
+followed by a character in
+.Fa pattern
+is replaced by that character.
+This is done to negate any special meaning for the character.
+If the
+.Dv FNM_NOESCAPE
+flag is set, a backslash character is treated as an ordinary character.
+.It Dv FNM_PATHNAME
+Slash characters in
+.Fa string
+must be explicitly matched by slashes in
+.Fa pattern .
+If this flag is not set, then slashes are treated as regular characters.
+.It Dv FNM_PERIOD
+Leading periods in strings match periods in patterns.
+The definition of ``leading'' is related to the specification of
+.Dv FNM_PATHNAME .
+A period is always ``leading'' if it is the first character in
+.Ar string .
+Additionally, if
+.Dv FNM_PATHNAME
+is set,
+a period is ``leading'' if it immediately follows a slash.
+.It Dv FNM_LEADING_DIR
+Ignore
+.Dq /*
+rest after successful
+.Fa pattern
+matching.
+.It Dv FNM_CASEFOLD
+The pattern is matched in a case-insensitive fashion.
+.El
+.Sh RETURN VALUES
+The
+.Fn fnmatch
+function returns zero if
+.Fa string
+matches the pattern specified by
+.Fa pattern ,
+otherwise, it returns the value
+.Dv FNM_NOMATCH .
+.Sh SEE ALSO
+.Xr sh 1 ,
+.Xr glob 3 ,
+.Xr regex 3 ,
+.Xr glob 7
+.Sh STANDARDS
+The
+.Fn fnmatch
+function conforms to
+.St -p1003.2-92 .
+The
+.Dv FNM_CASEFOLD
+flag is a
+.Nx
+extension.
+.Sh HISTORY
+The
+.Fn fnmatch
+function first appeared in
+.Bx 4.4 .
+.Sh BUGS
+The pattern
+.Ql *
+matches the empty string, even if
+.Dv FNM_PATHNAME
+is specified.
diff --git a/lib/nbsd_libc/gen/fnmatch.c b/lib/nbsd_libc/gen/fnmatch.c
new file mode 100644 (file)
index 0000000..556cae7
--- /dev/null
@@ -0,0 +1,204 @@
+/*     $NetBSD: fnmatch.c,v 1.21 2005/12/24 21:11:16 perry Exp $       */
+
+/*
+ * Copyright (c) 1989, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Guido van Rossum.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fnmatch.c  8.2 (Berkeley) 4/16/94";
+#else
+__RCSID("$NetBSD: fnmatch.c,v 1.21 2005/12/24 21:11:16 perry Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Function fnmatch() as specified in POSIX 1003.2-1992, section B.6.
+ * Compares a filename or pathname to a pattern.
+ */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <ctype.h>
+#include <fnmatch.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(fnmatch,_fnmatch)
+#endif
+
+#define        EOS     '\0'
+
+static const char *rangematch __P((const char *, int, int));
+
+static inline int
+foldcase(int ch, int flags)
+{
+
+       if ((flags & FNM_CASEFOLD) != 0 && isupper(ch))
+               return (tolower(ch));
+       return (ch);
+}
+
+#define        FOLDCASE(ch, flags)     foldcase((unsigned char)(ch), (flags))
+
+int
+fnmatch(pattern, string, flags)
+       const char *pattern, *string;
+       int flags;
+{
+       const char *stringstart;
+       char c, test;
+
+       _DIAGASSERT(pattern != NULL);
+       _DIAGASSERT(string != NULL);
+
+       for (stringstart = string;;)
+               switch (c = FOLDCASE(*pattern++, flags)) {
+               case EOS:
+                       if ((flags & FNM_LEADING_DIR) && *string == '/')
+                               return (0);
+                       return (*string == EOS ? 0 : FNM_NOMATCH);
+               case '?':
+                       if (*string == EOS)
+                               return (FNM_NOMATCH);
+                       if (*string == '/' && (flags & FNM_PATHNAME))
+                               return (FNM_NOMATCH);
+                       if (*string == '.' && (flags & FNM_PERIOD) &&
+                           (string == stringstart ||
+                           ((flags & FNM_PATHNAME) && *(string - 1) == '/')))
+                               return (FNM_NOMATCH);
+                       ++string;
+                       break;
+               case '*':
+                       c = FOLDCASE(*pattern, flags);
+                       /* Collapse multiple stars. */
+                       while (c == '*')
+                               c = FOLDCASE(*++pattern, flags);
+
+                       if (*string == '.' && (flags & FNM_PERIOD) &&
+                           (string == stringstart ||
+                           ((flags & FNM_PATHNAME) && *(string - 1) == '/')))
+                               return (FNM_NOMATCH);
+
+                       /* Optimize for pattern with * at end or before /. */
+                       if (c == EOS) {
+                               if (flags & FNM_PATHNAME)
+                                       return ((flags & FNM_LEADING_DIR) ||
+                                           strchr(string, '/') == NULL ?
+                                           0 : FNM_NOMATCH);
+                               else
+                                       return (0);
+                       } else if (c == '/' && flags & FNM_PATHNAME) {
+                               if ((string = strchr(string, '/')) == NULL)
+                                       return (FNM_NOMATCH);
+                               break;
+                       }
+
+                       /* General case, use recursion. */
+                       while ((test = FOLDCASE(*string, flags)) != EOS) {
+                               if (!fnmatch(pattern, string,
+                                            flags & ~FNM_PERIOD))
+                                       return (0);
+                               if (test == '/' && flags & FNM_PATHNAME)
+                                       break;
+                               ++string;
+                       }
+                       return (FNM_NOMATCH);
+               case '[':
+                       if (*string == EOS)
+                               return (FNM_NOMATCH);
+                       if (*string == '/' && flags & FNM_PATHNAME)
+                               return (FNM_NOMATCH);
+                       if ((pattern =
+                           rangematch(pattern, FOLDCASE(*string, flags),
+                                      flags)) == NULL)
+                               return (FNM_NOMATCH);
+                       ++string;
+                       break;
+               case '\\':
+                       if (!(flags & FNM_NOESCAPE)) {
+                               if ((c = FOLDCASE(*pattern++, flags)) == EOS) {
+                                       c = '\\';
+                                       --pattern;
+                               }
+                       }
+                       /* FALLTHROUGH */
+               default:
+                       if (c != FOLDCASE(*string++, flags))
+                               return (FNM_NOMATCH);
+                       break;
+               }
+       /* NOTREACHED */
+}
+
+static const char *
+rangematch(pattern, test, flags)
+       const char *pattern;
+       int test, flags;
+{
+       int negate, ok;
+       char c, c2;
+
+       _DIAGASSERT(pattern != NULL);
+
+       /*
+        * A bracket expression starting with an unquoted circumflex
+        * character produces unspecified results (IEEE 1003.2-1992,
+        * 3.13.2).  This implementation treats it like '!', for
+        * consistency with the regular expression syntax.
+        * J.T. Conklin (conklin@ngai.kaleida.com)
+        */
+       if ((negate = (*pattern == '!' || *pattern == '^')) != 0)
+               ++pattern;
+       
+       for (ok = 0; (c = FOLDCASE(*pattern++, flags)) != ']';) {
+               if (c == '\\' && !(flags & FNM_NOESCAPE))
+                       c = FOLDCASE(*pattern++, flags);
+               if (c == EOS)
+                       return (NULL);
+               if (*pattern == '-' 
+                   && (c2 = FOLDCASE(*(pattern+1), flags)) != EOS &&
+                       c2 != ']') {
+                       pattern += 2;
+                       if (c2 == '\\' && !(flags & FNM_NOESCAPE))
+                               c2 = FOLDCASE(*pattern++, flags);
+                       if (c2 == EOS)
+                               return (NULL);
+                       if (c <= test && test <= c2)
+                               ok = 1;
+               } else if (c == test)
+                       ok = 1;
+       }
+       return (ok == negate ? NULL : pattern);
+}
diff --git a/lib/nbsd_libc/gen/fpclassify.3 b/lib/nbsd_libc/gen/fpclassify.3
new file mode 100644 (file)
index 0000000..c8dcc1b
--- /dev/null
@@ -0,0 +1,94 @@
+.\"    $NetBSD: fpclassify.3,v 1.3 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 14, 2004
+.Dt FPCLASSIFY 3
+.Os
+.Sh NAME
+.Nm fpclassify
+.Nd classify real floating type
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In math.h
+.Ft int
+.Fn fpclassify "real-floating x"
+.Sh DESCRIPTION
+The
+.Fn fpclassify
+macro performs classification of its argument
+.Fa x .
+An argument represented in a format wider than its semantic type is
+converted to its semantic type first.
+The classification is then based on the type of the argument.
+.Ss IEEE 754
+.Bl -tag -width "FP_SUBNORMALXXX" -compact -offset indent
+.It Dv FP_INFINITE
+infinity, either positive or negative
+.It Dv FP_NAN
+not-a-number
+.Pq Dq NaN
+.It Dv FP_NORMAL
+normal
+.It Dv FP_SUBNORMAL
+subnormal
+.It Dv FP_ZERO
+zero
+.El
+.Ss VAX
+.Bl -tag -width "FP_DIRTYZEROXXX" -compact -offset indent
+.It Dv FP_ROP
+reserved operand
+.Pq Dq ROP
+.It Dv FP_DIRTYZERO
+dirty zero
+.It Dv FP_NORMAL
+finite
+.It Dv FP_ZERO
+true zero
+.El
+.Sh RETURN VALUES
+The
+.Fn fpclassify
+macro returns the value of the number classification macro appropriate
+to its argument
+.Fa x
+as described above.
+.Sh ERRORS
+No errors are defined.
+.Sh SEE ALSO
+.Xr isfinite 3 ,
+.Xr isnormal 3 ,
+.Xr math 3 ,
+.Xr signbit 3
+.Sh STANDARDS
+The
+.Fn fpclassify
+macro conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/gen/fpclassifyd_ieee754.c b/lib/nbsd_libc/gen/fpclassifyd_ieee754.c
new file mode 100644 (file)
index 0000000..ecce331
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: fpclassifyd_ieee754.c,v 1.2 2008/04/28 20:22:59 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpclassifyd_ieee754.c,v 1.2 2008/04/28 20:22:59 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.1 fpclassify - classify real floating type
+ *          IEEE 754 double-precision version
+ */
+int
+__fpclassifyd(double x)
+{
+       union ieee_double_u u;
+
+       u.dblu_d = x;
+
+       if (u.dblu_dbl.dbl_exp == 0) {
+               if (u.dblu_dbl.dbl_frach == 0 && u.dblu_dbl.dbl_fracl == 0)
+                       return FP_ZERO;
+               else
+                       return FP_SUBNORMAL;
+       } else if (u.dblu_dbl.dbl_exp == DBL_EXP_INFNAN) {
+               if (u.dblu_dbl.dbl_frach == 0 && u.dblu_dbl.dbl_fracl == 0)
+                       return FP_INFINITE;
+               else
+                       return FP_NAN;
+       }
+
+       return FP_NORMAL;
+}
diff --git a/lib/nbsd_libc/gen/fpclassifyf_ieee754.c b/lib/nbsd_libc/gen/fpclassifyf_ieee754.c
new file mode 100644 (file)
index 0000000..2e522d5
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: fpclassifyf_ieee754.c,v 1.3 2008/04/28 20:22:59 martin Exp $   */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpclassifyf_ieee754.c,v 1.3 2008/04/28 20:22:59 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.1 fpclassify - classify real floating type
+ *          IEEE 754 single-precision version
+ */
+int
+__fpclassifyf(float x)
+{
+       union ieee_single_u u;
+
+       u.sngu_f = x;
+
+       if (u.sngu_sng.sng_exp == 0) {
+               if (u.sngu_sng.sng_frac == 0)
+                       return FP_ZERO;
+               else
+                       return FP_SUBNORMAL;
+       } else if (u.sngu_sng.sng_exp == SNG_EXP_INFNAN) {
+               if (u.sngu_sng.sng_frac == 0)
+                       return FP_INFINITE;
+               else
+                       return FP_NAN;
+       }
+
+       return FP_NORMAL;
+}
diff --git a/lib/nbsd_libc/gen/fpclassifyl_ieee754.c b/lib/nbsd_libc/gen/fpclassifyl_ieee754.c
new file mode 100644 (file)
index 0000000..f523573
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: fpclassifyl_ieee754.c,v 1.1 2011/01/17 23:53:03 matt Exp $     */
+
+/*-
+ * Copyright (c) 2011 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpclassifyl_ieee754.c,v 1.1 2011/01/17 23:53:03 matt Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+#ifdef __HAVE_LONG_DOUBLE
+/*
+ * 7.12.3.1 fpclassify - classify real floating type
+ *          IEEE 754 compatible 128-bit extended-precision version
+ */
+int
+__fpclassifyl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       if (u.extu_ext.ext_exp == 0) {
+               if (u.extu_ext.ext_frach == 0 && u.extu_ext.ext_frachm == 0
+                   && u.extu_ext.ext_fraclm == 0 && u.extu_ext.ext_fracl == 0)
+                       return FP_ZERO;
+               else
+                       return FP_SUBNORMAL;
+       } else if (u.extu_ext.ext_exp == EXT_EXP_INFNAN) {
+               if (u.extu_ext.ext_frach == 0 && u.extu_ext.ext_frachm == 0
+                   && u.extu_ext.ext_fraclm == 0 && u.extu_ext.ext_fracl == 0)
+                       return FP_INFINITE;
+               else
+                       return FP_NAN;
+       }
+
+       return FP_NORMAL;
+}
+#endif /* __HAVE_LONG_DOUBLE */
diff --git a/lib/nbsd_libc/gen/fpgetmask.3 b/lib/nbsd_libc/gen/fpgetmask.3
new file mode 100644 (file)
index 0000000..04b27ff
--- /dev/null
@@ -0,0 +1,140 @@
+.\"    $NetBSD: fpgetmask.3,v 1.10 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 1999 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Ross Harvey.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 4, 2004
+.Dt FPGETMASK 3
+.Os
+.Sh NAME
+.Nm fpgetmask ,
+.Nm fpgetround ,
+.Nm fpgetsticky ,
+.Nm fpsetmask ,
+.Nm fpsetround ,
+.Nm fpsetsticky
+.Nd IEEE FP mode control
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ieeefp.h
+.Ft fp_except
+.Fn fpgetmask void
+.Ft fp_rnd
+.Fn fpgetround void
+.Ft fp_except
+.Fn fpgetsticky void
+.Ft fp_except
+.Fn fpsetmask fp_except\ mask
+.Ft fp_rnd
+.Fn fpsetround fp_rnd\ rnd_dir
+.Ft fp_except
+.Fn fpsetsticky fp_except\ sticky
+.Sh DESCRIPTION
+A rounding mode is one of
+.Dv FP_RZ , FP_RM , FP_RN ,
+or
+.Dv FP_RP ,
+for rounding towards zero, rounding
+.Pq Em Minus infinity
+down, rounding to
+.Em nearest ,
+and rounding
+.Pq Em Plus infinity
+up.
+The default mode is
+.Dv FP_RN .
+.Pp
+An
+.Ft fp_except
+value is a bitmask specifying an exception type and containing any of
+the values listed below.
+.Bl -column -offset indent FP_X_UFLxx
+.It Dv FP_X_INV Ta Invalid\ Operation
+.It Dv FP_X_DZ Ta Division\ by\ zero
+.It Dv FP_X_OFL Ta Overflow
+.It Dv FP_X_UFL Ta Underflow
+.It Dv FP_X_IMP Ta Imprecision (inexact)
+.It Dv FP_X_IOV Ta Integer\ Overflow
+.El
+.Pp
+The
+.Fn fpsetmask
+function will set the current exception mask, i.e., it will cause
+future operations with the specified result status to raise the
+.Dv SIGFPE
+exception.
+The
+.Fn fpgetmask
+function will return the current exception mask.
+.Pp
+The
+.Fn fpsetround
+function will cause future operations to use the specified dynamic
+rounding mode.
+The
+.Fn fpgetround
+function will return the current rounding mode.
+.Bl -tag -width Note:x
+.It Em Note :
+On some architectures, instructions can optionally specify static
+rounding modes and exception enables that will supersede the specified
+dynamic mode.
+On other architectures, these features may not be fully supported.
+.El
+.Pp
+A
+.Dq sticky
+status word may be maintained in which a bit is set every time an
+exceptional floating point condition is encountered, whether or not a
+.Dv SIGFPE
+is generated.
+The
+.Fn fpsetsticky
+function will set or clear the specified exception history bits.
+The
+.Fn fpgetsticky
+function will return the exception history bits.
+.Sh RETURN VALUES
+The
+.Fn fpgetround
+and
+.Fn fpsetround
+functions return the
+.Pq previous
+rounding mode.
+The
+.Fn fpgetmask ,
+.Fn fpsetmask ,
+.Fn fpgetsticky ,
+and
+.Fn fpsetsticky
+functions return the
+.Pq previous
+exception mask and exception history bits.
+.Sh SEE ALSO
+.Xr sigaction 2
diff --git a/lib/nbsd_libc/gen/fstab.c b/lib/nbsd_libc/gen/fstab.c
new file mode 100644 (file)
index 0000000..bd8305e
--- /dev/null
@@ -0,0 +1,233 @@
+/*     $NetBSD: fstab.c,v 1.28 2006/08/12 23:49:54 christos Exp $      */
+
+/*
+ * Copyright (c) 1980, 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fstab.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fstab.c,v 1.28 2006/08/12 23:49:54 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <err.h>
+#include <errno.h>
+#include <fstab.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(endfsent,_endfsent)
+__weak_alias(getfsent,_getfsent)
+__weak_alias(getfsfile,_getfsfile)
+__weak_alias(getfsspec,_getfsspec)
+__weak_alias(setfsent,_setfsent)
+#endif
+
+static FILE *_fs_fp;
+static size_t _fs_lineno = 0;
+static const char *_fs_file = _PATH_FSTAB;
+static struct fstab _fs_fstab;
+
+static int fstabscan __P((void));
+
+static char *nextfld(char **, const char *);
+static int fstabscan(void);
+
+
+static char *
+nextfld(char **str, const char *sep)
+{
+       char *ret;
+
+       _DIAGASSERT(str != NULL);
+       _DIAGASSERT(sep != NULL);
+
+       while ((ret = stresep(str, sep, '\\')) != NULL && *ret == '\0')
+               continue;
+       return ret;
+}
+
+
+static int
+fstabscan(void)
+{
+       char *cp, *lp, *sp;
+#define        MAXLINELENGTH   1024
+       static char line[MAXLINELENGTH];
+       char subline[MAXLINELENGTH];
+       static const char sep[] = ":\n";
+       static const char ws[] = " \t\n";
+       static const char *fstab_type[] = {
+           FSTAB_RW, FSTAB_RQ, FSTAB_RO, FSTAB_SW, FSTAB_DP, FSTAB_XX, NULL 
+       };
+
+       (void)memset(&_fs_fstab, 0, sizeof(_fs_fstab));
+       for (;;) {
+               if (!(lp = fgets(line, sizeof(line), _fs_fp)))
+                       return 0;
+               _fs_lineno++;
+/* OLD_STYLE_FSTAB */
+               if (!strpbrk(lp, " \t")) {
+                       _fs_fstab.fs_spec = nextfld(&lp, sep);
+                       if (!_fs_fstab.fs_spec || *_fs_fstab.fs_spec == '#')
+                               continue;
+                       _fs_fstab.fs_file = nextfld(&lp, sep);
+                       _fs_fstab.fs_type = nextfld(&lp, sep);
+                       if (_fs_fstab.fs_type) {
+                               if (!strcmp(_fs_fstab.fs_type, FSTAB_XX))
+                                       continue;
+                               _fs_fstab.fs_mntops = _fs_fstab.fs_type;
+                               _fs_fstab.fs_vfstype =
+                                   __UNCONST(
+                                   strcmp(_fs_fstab.fs_type, FSTAB_SW) ?
+                                   "ufs" : "swap");
+                               if ((cp = nextfld(&lp, sep)) != NULL) {
+                                       _fs_fstab.fs_freq = atoi(cp);
+                                       if ((cp = nextfld(&lp, sep)) != NULL) {
+                                               _fs_fstab.fs_passno = atoi(cp);
+                                               return 1;
+                                       }
+                               }
+                       }
+                       goto bad;
+               }
+/* OLD_STYLE_FSTAB */
+               _fs_fstab.fs_spec = nextfld(&lp, ws);
+               if (!_fs_fstab.fs_spec || *_fs_fstab.fs_spec == '#')
+                       continue;
+               _fs_fstab.fs_file = nextfld(&lp, ws);
+               _fs_fstab.fs_vfstype = nextfld(&lp, ws);
+               _fs_fstab.fs_mntops = nextfld(&lp, ws);
+               if (_fs_fstab.fs_mntops == NULL)
+                       goto bad;
+               _fs_fstab.fs_freq = 0;
+               _fs_fstab.fs_passno = 0;
+               if ((cp = nextfld(&lp, ws)) != NULL) {
+                       _fs_fstab.fs_freq = atoi(cp);
+                       if ((cp = nextfld(&lp, ws)) != NULL)
+                               _fs_fstab.fs_passno = atoi(cp);
+               }
+
+               /* subline truncated iff line truncated */
+               (void)strlcpy(subline, _fs_fstab.fs_mntops, sizeof(subline));
+               sp = subline;
+
+               while ((cp = nextfld(&sp, ",")) != NULL) {
+                       const char **tp;
+
+                       if (strlen(cp) != 2)
+                               continue;
+
+                       for (tp = fstab_type; *tp; tp++)
+                               if (strcmp(cp, *tp) == 0) {
+                                       _fs_fstab.fs_type = __UNCONST(*tp);
+                                       break;
+                               }
+                       if (*tp)
+                               break;
+               }
+               if (_fs_fstab.fs_type == NULL)
+                       goto bad;
+               if (strcmp(_fs_fstab.fs_type, FSTAB_XX) == 0)
+                       continue;
+               if (cp != NULL)
+                       return 1;
+
+bad:
+               warnx("%s, %lu: Missing fields", _fs_file, (u_long)_fs_lineno);
+       }
+       /* NOTREACHED */
+}
+
+struct fstab *
+getfsent(void)
+{
+       if ((!_fs_fp && !setfsent()) || !fstabscan())
+               return NULL;
+       return &_fs_fstab;
+}
+
+struct fstab *
+getfsspec(const char *name)
+{
+
+       _DIAGASSERT(name != NULL);
+
+       if (setfsent())
+               while (fstabscan())
+                       if (!strcmp(_fs_fstab.fs_spec, name))
+                               return &_fs_fstab;
+       return NULL;
+}
+
+struct fstab *
+getfsfile(const char *name)
+{
+
+       _DIAGASSERT(name != NULL);
+
+       if (setfsent())
+               while (fstabscan())
+                       if (!strcmp(_fs_fstab.fs_file, name))
+                               return &_fs_fstab;
+       return NULL;
+}
+
+int
+setfsent(void)
+{
+       _fs_lineno = 0;
+       if (_fs_fp) {
+               rewind(_fs_fp);
+               return 1;
+       }
+       if ((_fs_fp = fopen(_PATH_FSTAB, "r")) == NULL) {
+               warn("Cannot open `%s'", _PATH_FSTAB);
+               return 0;
+       }
+       return 1;
+}
+
+void
+endfsent(void)
+{
+       if (_fs_fp) {
+               (void)fclose(_fs_fp);
+               _fs_fp = NULL;
+       }
+}
diff --git a/lib/nbsd_libc/gen/ftok.3 b/lib/nbsd_libc/gen/ftok.3
new file mode 100644 (file)
index 0000000..8bab7b4
--- /dev/null
@@ -0,0 +1,93 @@
+.\"    $NetBSD: ftok.3,v 1.16 2010/04/27 15:26:59 jruoho Exp $
+.\"
+.\" Copyright (c) 1994 SigmaSoft, Th. Lockert <tholo@sigmasoft.com>
+.\" 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 ``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 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.
+.\"
+.Dd April 27, 2010
+.Dt FTOK 3
+.Os
+.Sh NAME
+.Nm ftok
+.Nd create IPC identifier from path name
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/ipc.h
+.Ft key_t
+.Fn ftok "const char *path" "int id"
+.Sh DESCRIPTION
+The
+.Fn ftok
+function attempts to create a unique key suitable for use with the
+.Xr msgget 2 ,
+.Xr semget 2
+and
+.Xr shmget 2
+functions given the
+.Fa path
+of an existing file and a user-selectable
+.Fa id .
+.Pp
+The specified
+.Fa path
+must specify an existing file that is accessible to the calling process
+or the call will fail.
+Also, note that links to files will return the same key, given the same
+.Fa id .
+.Pp
+Only the 8 least significant bits of
+.Fa id
+are used in the key generation; the rest of the bits are ignored.
+.Sh RETURN VALUES
+The
+.Fn ftok
+function will return ((key_t)-1) if
+.Fa path
+does not exist or if it cannot be accessed by the calling process.
+.Sh SEE ALSO
+.Xr msgget 2 ,
+.Xr semget 2 ,
+.Xr shmget 2
+.Sh STANDARDS
+The
+.Fn ftok
+function conforms to
+.St -p1003.1 .
+.Sh HISTORY
+The
+.Fn ftok
+function originated with System V and is typically used by programs
+that use the System V IPC routines.
+.Sh AUTHORS
+.An Thorsten Lockert Aq tholo@sigmasoft.com
+.Sh BUGS
+The returned key is computed based on the device and inode of the
+specified
+.Fa path
+in combination with the given
+.Fa id .
+Thus it is quite possible for the routine to return duplicate keys
+given that those fields are not 8- and 16-bit quantities like they
+were on System V based systems where this library routine's ancestor
+were originally created.
diff --git a/lib/nbsd_libc/gen/ftok.c b/lib/nbsd_libc/gen/ftok.c
new file mode 100644 (file)
index 0000000..d50acc6
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: ftok.c,v 1.10 2004/09/15 19:45:17 hubertf Exp $        */
+
+/*
+ * Copyright (c) 1994 SigmaSoft, Th. Lockert <tholo@sigmasoft.com>
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ftok.c,v 1.10 2004/09/15 19:45:17 hubertf Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/ipc.h>
+
+#include <assert.h>
+#include <errno.h>
+
+#ifdef __weak_alias
+__weak_alias(ftok,_ftok)
+#endif
+
+key_t
+ftok(path, id)
+       const char *path;
+       int id;
+{
+       struct stat st;
+
+       _DIAGASSERT(path != NULL);
+
+       if (stat(path, &st) < 0)
+               return (key_t)-1;
+
+       return (key_t)
+           (id << 24 | (st.st_dev & 0xff) << 16 | (st.st_ino & 0xffff));
+}
diff --git a/lib/nbsd_libc/gen/fts.3 b/lib/nbsd_libc/gen/fts.3
new file mode 100644 (file)
index 0000000..596c065
--- /dev/null
@@ -0,0 +1,773 @@
+.\"    $NetBSD: fts.3,v 1.29 2010/04/29 17:39:03 jruoho Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 1993, 1994
+.\"    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.
+.\" 3. 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.
+.\"
+.\"     @(#)fts.3      8.5 (Berkeley) 4/16/94
+.\"
+.Dd April 29, 2010
+.Dt FTS 3
+.Os
+.Sh NAME
+.Nm fts ,
+.Nm fts_open ,
+.Nm fts_read ,
+.Nm fts_children ,
+.Nm fts_set ,
+.Nm fts_close
+.Nd traverse a file hierarchy
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/stat.h
+.In fts.h
+.Ft FTS *
+.Fo fts_open
+.Fa "char * const *path_argv"
+.Fa "int options"
+.Fa "int (*compar)(const FTSENT **, const FTSENT **)"
+.Fc
+.Ft FTSENT *
+.Fn fts_read "FTS *ftsp"
+.Ft FTSENT *
+.Fn fts_children "FTS *ftsp" "int options"
+.Ft int
+.Fn fts_set "FTS *ftsp" "FTSENT *f" "int options"
+.Ft int
+.Fn fts_close "FTS *ftsp"
+.Sh DESCRIPTION
+The
+.Nm
+functions are provided for traversing
+.Ux
+file hierarchies.
+A simple overview is that the
+.Fn fts_open
+function returns a
+.Dq handle
+on a file hierarchy, which is then supplied to
+the other
+.Nm
+functions.
+The function
+.Fn fts_read
+returns a pointer to a structure describing one of the files in the file
+hierarchy.
+The function
+.Fn fts_children
+returns a pointer to a linked list of structures, each of which describes
+one of the files contained in a directory in the hierarchy.
+In general, directories are visited two distinguishable times; in pre-order
+(before any of their descendants are visited) and in post-order (after all
+of their descendants have been visited).
+Files are visited once.
+It is possible to walk the hierarchy
+.Dq logically
+(ignoring symbolic links)
+or physically (visiting symbolic links), order the walk of the hierarchy or
+prune and/or re-visit portions of the hierarchy.
+.Pp
+Two structures are defined (and typedef'd) in the include file
+.In fts.h .
+The first is
+.Fa FTS ,
+the structure that represents the file hierarchy itself.
+The second is
+.Fa FTSENT ,
+the structure that represents a file in the file
+hierarchy.
+Normally, an
+.Fa FTSENT
+structure is returned for every file in the file
+hierarchy.
+In this manual page,
+.Dq file
+and
+.Dq Fa FTSENT No structure
+are generally
+interchangeable.
+The
+.Fa FTSENT
+structure contains at least the following fields, which are
+described in greater detail below:
+.Bd -literal
+typedef struct _ftsent {
+       u_short fts_info;               /* flags for FTSENT structure */
+       char *fts_accpath;              /* access path */
+       char *fts_path;                 /* root path */
+       short fts_pathlen;              /* strlen(fts_path) */
+       char *fts_name;                 /* file name */
+       short fts_namelen;              /* strlen(fts_name) */
+       short fts_level;                /* depth (\-1 to N) */
+       int fts_errno;                  /* file errno */
+       long fts_number;                /* local numeric value */
+       void *fts_pointer;              /* local address value */
+       struct ftsent *fts_parent;      /* parent directory */
+       struct ftsent *fts_link;        /* next file structure */
+       struct ftsent *fts_cycle;       /* cycle structure */
+       struct stat *fts_statp;         /* stat(2) information */
+} FTSENT;
+.Ed
+.Pp
+These fields are defined as follows:
+.Bl -tag -width "fts_namelen"
+.It Fa fts_info
+One of the following flags describing the returned
+.Fa FTSENT
+structure and
+the file it represents.
+With the exception of directories without errors
+.Pq Dv FTS_D ,
+all of these
+entries are terminal, that is, they will not be revisited, nor will any
+of their descendants be visited.
+.Bl  -tag -width FTS_DEFAULT
+.It Dv FTS_D
+A directory being visited in pre-order.
+.It Dv FTS_DC
+A directory that causes a cycle in the tree.
+(The
+.Fa fts_cycle
+field of the
+.Fa FTSENT
+structure will be filled in as well).
+.It Dv FTS_DEFAULT
+Any
+.Fa FTSENT
+structure that represents a file type not explicitly described
+by one of the other
+.Fa fts_info
+values.
+.It Dv FTS_DNR
+A directory which cannot be read.
+This is an error return, and the
+.Fa fts_errno
+field will be set to indicate what caused the error.
+.It Dv FTS_DOT
+A file named
+.Ql \&.
+or
+.Ql ..
+which was not specified as a file name to
+.Fn fts_open
+(see
+.Dv FTS_SEEDOT ) .
+.It Dv FTS_DP
+A directory being visited in post-order.
+The contents of the
+.Fa FTSENT
+structure will be unchanged from when
+it was returned in pre-order, i.e., with the
+.Fa fts_info
+field set to
+.Dv FTS_D .
+.It Dv FTS_ERR
+This is an error return, and the
+.Fa fts_errno
+field will be set to indicate what caused the error.
+.It Dv FTS_F
+A regular file.
+.It Dv FTS_NS
+A file for which no
+.Xr stat 2
+information was available.
+The contents of the
+.Fa fts_statp
+field are undefined.
+This is an error return, and the
+.Fa fts_errno
+field will be set to indicate what caused the error.
+.It Dv FTS_NSOK
+A file for which no
+.Xr stat 2
+information was requested.
+The contents of the
+.Fa fts_statp
+field are undefined.
+.It Dv FTS_SL
+A symbolic link.
+.It Dv FTS_SLNONE
+A symbolic link with a non-existent target.
+The contents of the
+.Fa fts_statp
+field reference the file characteristic information for the symbolic link
+itself.
+.It Dv FTS_W
+A whiteout object.
+.El
+.It Fa fts_accpath
+A path for accessing the file from the current directory.
+.It Fa fts_path
+The path for the file relative to the root of the traversal.
+This path contains the path specified to
+.Fn fts_open
+as a prefix.
+.It Fa fts_pathlen
+The length of the string referenced by
+.Fa fts_path .
+.It Fa fts_name
+The name of the file.
+.It Fa fts_namelen
+The length of the string referenced by
+.Fa fts_name .
+.It Fa fts_level
+The depth of the traversal, numbered from \-1 to N, where this file
+was found.
+The
+.Fa FTSENT
+structure representing the parent of the starting point (or root)
+of the traversal is numbered \-1, and the
+.Fa FTSENT
+structure for the root
+itself is numbered 0.
+.It Fa fts_errno
+Upon return of a
+.Fa FTSENT
+structure from the
+.Fn fts_children
+or
+.Fn fts_read
+functions, with its
+.Fa fts_info
+field set to
+.Dv FTS_DNR ,
+.Dv FTS_ERR
+or
+.Dv FTS_NS ,
+the
+.Fa fts_errno
+field contains the value of the external variable
+.Va errno
+specifying the cause of the error.
+Otherwise, the contents of the
+.Fa fts_errno
+field are undefined.
+.It Fa fts_number
+This field is provided for the use of the application program and is
+not modified by the
+.Nm
+functions.
+It is initialized to 0.
+.It Fa fts_pointer
+This field is provided for the use of the application program and is
+not modified by the
+.Nm
+functions.
+It is initialized to
+.Dv NULL .
+.It Fa fts_parent
+A pointer to the
+.Fa FTSENT
+structure referencing the file in the hierarchy
+immediately above the current file, i.e., the directory of which this
+file is a member.
+A parent structure for the initial entry point is provided as well,
+however, only the
+.Fa fts_level ,
+.Fa fts_number
+and
+.Fa fts_pointer
+fields are guaranteed to be initialized.
+.It Fa fts_link
+Upon return from the
+.Fn fts_children
+function, the
+.Fa fts_link
+field points to the next structure in the
+.Dv NULL Ns -terminated
+linked list of directory members.
+Otherwise, the contents of the
+.Fa fts_link
+field are undefined.
+.It Fa fts_cycle
+If a directory causes a cycle in the hierarchy (see
+.Dv FTS_DC ) ,
+either because
+of a hard link between two directories, or a symbolic link pointing to a
+directory, the
+.Fa fts_cycle
+field of the structure will point to the
+.Fa FTSENT
+structure in the hierarchy that references the same file as the current
+.Fa FTSENT
+structure.
+Otherwise, the contents of the
+.Fa fts_cycle
+field are undefined.
+.It Fa fts_statp
+A pointer to
+.Xr stat 2
+information for the file.
+.El
+.Pp
+A single buffer is used for all of the paths of all of the files in the
+file hierarchy.
+Therefore, the
+.Fa fts_path
+and
+.Fa fts_accpath
+fields are guaranteed to be
+.Dv NULL Ns -terminated
+.Em only
+for the file most recently returned by
+.Fn fts_read .
+To use these fields to reference any files represented by other
+.Fa FTSENT
+structures will require that the path buffer be modified using the
+information contained in that
+.Fa FTSENT
+structure's
+.Fa fts_pathlen
+field.
+Any such modifications should be undone before further calls to
+.Fn fts_read
+are attempted.
+The
+.Fa fts_name
+field is always
+.Dv NULL Ns -terminated .
+.Sh FTS_OPEN
+The
+.Fn fts_open
+function takes a pointer to an array of character pointers naming one
+or more paths which make up a logical file hierarchy to be traversed.
+The array must be terminated by a
+.Dv NULL
+pointer.
+.Pp
+There are
+a number of options, at least one of which (either
+.Dv FTS_LOGICAL
+or
+.Dv FTS_PHYSICAL )
+must be specified.
+The options are selected by
+.Em or Ns 'ing
+the following values:
+.Bl -tag -width "FTS_PHYSICAL"
+.It Dv FTS_COMFOLLOW
+This option causes any symbolic link specified as a root path to be
+followed immediately whether or not
+.Dv FTS_LOGICAL
+is also specified.
+.It Dv FTS_LOGICAL
+This option causes the
+.Nm
+routines to return
+.Fa FTSENT
+structures for the targets of symbolic links
+instead of the symbolic links themselves.
+If this option is set, the only symbolic links for which
+.Fa FTSENT
+structures
+are returned to the application are those referencing non-existent files.
+Either
+.Dv FTS_LOGICAL
+or
+.Dv FTS_PHYSICAL
+.Em must
+be provided to the
+.Fn fts_open
+function.
+.It Dv FTS_NOCHDIR
+As a performance optimization, the
+.Nm
+functions change directories as they walk the file hierarchy.
+This has the side-effect that an application cannot rely on being
+in any particular directory during the traversal.
+The
+.Dv FTS_NOCHDIR
+option turns off this optimization, and the
+.Nm
+functions will not change the current directory.
+Note that applications should not themselves change their current directory
+and try to access files unless
+.Dv FTS_NOCHDIR
+is specified and absolute
+pathnames were provided as arguments to
+.Fn fts_open .
+.It Dv FTS_NOSTAT
+By default, returned
+.Fa FTSENT
+structures reference file characteristic information (the
+.Fa statp
+field) for each file visited.
+This option relaxes that requirement as a performance optimization,
+allowing the
+.Nm
+functions to set the
+.Fa fts_info
+field to
+.Dv FTS_NSOK
+and leave the contents of the
+.Fa statp
+field undefined.
+.It Dv FTS_PHYSICAL
+This option causes the
+.Nm
+routines to return
+.Fa FTSENT
+structures for symbolic links themselves instead
+of the target files they point to.
+If this option is set,
+.Fa FTSENT
+structures for all symbolic links in the
+hierarchy are returned to the application.
+Either
+.Dv FTS_LOGICAL
+or
+.Dv FTS_PHYSICAL
+.Em must
+be provided to the
+.Fn fts_open
+function.
+.It Dv FTS_SEEDOT
+By default, unless they are specified as path arguments to
+.Fn fts_open ,
+any files named
+.Ql \&.
+or
+.Ql ..
+encountered in the file hierarchy are ignored.
+This option causes the
+.Nm
+routines to return
+.Fa FTSENT
+structures for them.
+.It Dv FTS_WHITEOUT
+Return whiteout entries, which are normally hidden.
+.It Dv FTS_XDEV
+This option prevents
+.Nm
+from descending into directories that have a different device number
+than the file from which the descent began.
+.El
+.Pp
+The argument
+.Fn compar
+specifies a user-defined function which may be used to order the traversal
+of the hierarchy.
+It
+takes two pointers to pointers to
+.Fa FTSENT
+structures as arguments and
+should return a negative value, zero, or a positive value to indicate
+if the file referenced by its first argument comes before, in any order
+with respect to, or after, the file referenced by its second argument.
+The
+.Fa fts_accpath ,
+.Fa fts_path
+and
+.Fa fts_pathlen
+fields of the
+.Fa FTSENT
+structures may
+.Em never
+be used in this comparison.
+If the
+.Fa fts_info
+field is set to
+.Dv FTS_NS
+or
+.Dv FTS_NSOK ,
+the
+.Fa fts_statp
+field may not either.
+If the
+.Fn compar
+argument is
+.Dv NULL ,
+the directory traversal order is in the order listed in
+.Fa path_argv
+for the root paths, and in the order listed in the directory for
+everything else.
+.Sh FTS_READ
+The
+.Fn fts_read
+function returns a pointer to an
+.Fa FTSENT
+structure describing a file in
+the hierarchy.
+Directories (that are readable and do not cause cycles) are visited at
+least twice, once in pre-order and once in post-order.
+All other files are visited at least once.
+(Hard links between directories that do not cause cycles or symbolic
+links to symbolic links may cause files to be visited more than once,
+or directories more than twice.)
+.Pp
+If all the members of the hierarchy have been returned,
+.Fn fts_read
+returns
+.Dv NULL
+and sets the external variable
+.Va errno
+to 0.
+If an error unrelated to a file in the hierarchy occurs,
+.Fn fts_read
+returns
+.Dv NULL
+and sets
+.Va errno
+appropriately.
+If an error related to a returned file occurs, a pointer to an
+.Fa FTSENT
+structure is returned, and
+.Va errno
+may or may not have been set (see
+.Fa fts_info ) .
+.Pp
+The
+.Fa FTSENT
+structures returned by
+.Fn fts_read
+may be overwritten after a call to
+.Fn fts_close
+on the same file hierarchy stream, or, after a call to
+.Fn fts_read
+on the same file hierarchy stream unless they represent a file of type
+directory, in which case they will not be overwritten until after a call to
+.Fn fts_read
+after the
+.Fa FTSENT
+structure has been returned by the function
+.Fn fts_read
+in post-order.
+.Sh FTS_CHILDREN
+The
+.Fn fts_children
+function returns a pointer to an
+.Fa FTSENT
+structure describing the first entry in a
+.Dv NULL Ns -terminated
+linked list of the files in the directory represented by the
+.Fa FTSENT
+structure most recently returned by
+.Fn fts_read .
+The list is linked through the
+.Fa fts_link
+field of the
+.Fa FTSENT
+structure, and is ordered by the user-specified comparison function, if any.
+Repeated calls to
+.Fn fts_children
+will recreate this linked list.
+.Pp
+As a special case, if
+.Fn fts_read
+has not yet been called for a hierarchy,
+.Fn fts_children
+will return a pointer to the files in the logical directory specified to
+.Fn fts_open ,
+i.e., the arguments specified to
+.Fn fts_open .
+Otherwise, if the
+.Fa FTSENT
+structure most recently returned by
+.Fn fts_read
+is not a directory being visited in pre-order,
+or the directory does not contain any files,
+.Fn fts_children
+returns
+.Dv NULL
+and sets
+.Va errno
+to zero.
+If an error occurs,
+.Fn fts_children
+returns
+.Dv NULL
+and sets
+.Va errno
+appropriately.
+.Pp
+The
+.Fa FTSENT
+structures returned by
+.Fn fts_children
+may be overwritten after a call to
+.Fn fts_children ,
+.Fn fts_close
+or
+.Fn fts_read
+on the same file hierarchy stream.
+.Pp
+.Em Option
+may be set to the following value:
+.Bl -tag -width FTS_NAMEONLY
+.It Dv FTS_NAMEONLY
+Only the names of the files are needed.
+The contents of all the fields in the returned linked list of structures
+are undefined with the exception of the
+.Fa fts_name
+and
+.Fa fts_namelen
+fields.
+.El
+.Sh FTS_SET
+The function
+.Fn fts_set
+allows the user application to determine further processing for the
+file
+.Fa f
+of the stream
+.Fa ftsp .
+The
+.Fn fts_set
+function
+returns 0 on success, and \-1 if an error occurs.
+.Em Option
+must be set to one of the following values:
+.Bl -tag -width FTS_PHYSICAL
+.It Dv FTS_AGAIN
+Re-visit the file; any file type may be re-visited.
+The next call to
+.Fn fts_read
+will return the referenced file.
+The
+.Fa fts_stat
+and
+.Fa fts_info
+fields of the structure will be reinitialized at that time,
+but no other fields will have been changed.
+This option is meaningful only for the most recently returned
+file from
+.Fn fts_read .
+Normal use is for post-order directory visits, where it causes the
+directory to be re-visited (in both pre and post-order) as well as all
+of its descendants.
+.It Dv FTS_FOLLOW
+The referenced file must be a symbolic link.
+If the referenced file is the one most recently returned by
+.Fn fts_read ,
+the next call to
+.Fn fts_read
+returns the file with the
+.Fa fts_info
+and
+.Fa fts_statp
+fields reinitialized to reflect the target of the symbolic link instead
+of the symbolic link itself.
+If the file is one of those most recently returned by
+.Fn fts_children ,
+the
+.Fa fts_info
+and
+.Fa fts_statp
+fields of the structure, when returned by
+.Fn fts_read ,
+will reflect the target of the symbolic link instead of the symbolic link
+itself.
+In either case, if the target of the symbolic link does not exist the
+fields of the returned structure will be unchanged and the
+.Fa fts_info
+field will be set to
+.Dv FTS_SLNONE .
+.Pp
+If the target of the link is a directory, the pre-order return, followed
+by the return of all of its descendants, followed by a post-order return,
+is done.
+.It Dv FTS_SKIP
+No descendants of this file are visited.
+The file may be one of those most recently returned by either
+.Fn fts_children
+or
+.Fn fts_read .
+.El
+.Sh FTS_CLOSE
+The
+.Fn fts_close
+function closes a file hierarchy stream
+.Fa ftsp
+and restores the current directory to the directory from which
+.Fn fts_open
+was called to open
+.Fa ftsp .
+The
+.Fn fts_close
+function
+returns 0 on success, and \-1 if an error occurs.
+.Sh ERRORS
+The function
+.Fn fts_open
+may fail and set
+.Va errno
+for any of the errors specified for the library functions
+.Xr open 2
+and
+.Xr malloc 3 .
+.Pp
+The function
+.Fn fts_close
+may fail and set
+.Va errno
+for any of the errors specified for the library functions
+.Xr chdir 2
+and
+.Xr close 2 .
+.Pp
+The functions
+.Fn fts_read
+and
+.Fn fts_children
+may fail and set
+.Va errno
+for any of the errors specified for the library functions
+.Xr chdir 2 ,
+.Xr malloc 3 ,
+.Xr opendir 3 ,
+.Xr readdir 3
+and
+.Xr stat 2 .
+.Pp
+In addition,
+.Fn fts_children ,
+.Fn fts_open
+and
+.Fn fts_set
+may fail and set
+.Va errno
+as follows:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The options were invalid.
+.El
+.Sh SEE ALSO
+.Xr find 1 ,
+.Xr chdir 2 ,
+.Xr stat 2 ,
+.Xr qsort 3 ,
+.Xr symlink 7
+.Sh STANDARDS
+The
+.Nm
+utility was expected to be included in the
+.St -p1003.1-88
+revision.
+But twenty years later, it still was not included in the
+.St -p1003.1-2008
+revision.
diff --git a/lib/nbsd_libc/gen/fts.c b/lib/nbsd_libc/gen/fts.c
new file mode 100644 (file)
index 0000000..1c3bc73
--- /dev/null
@@ -0,0 +1,1225 @@
+/*     $NetBSD: fts.c,v 1.40 2009/11/02 17:17:34 stacktic Exp $        */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fts.c      8.6 (Berkeley) 8/14/94";
+#else
+__RCSID("$NetBSD: fts.c,v 1.40 2009/11/02 17:17:34 stacktic Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <fts.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#if ! HAVE_NBTOOL_CONFIG_H
+#define        HAVE_STRUCT_DIRENT_D_NAMLEN
+#endif
+
+static FTSENT  *fts_alloc(FTS *, const char *, size_t);
+static FTSENT  *fts_build(FTS *, int);
+static void     fts_free(FTSENT *);
+static void     fts_lfree(FTSENT *);
+static void     fts_load(FTS *, FTSENT *);
+static size_t   fts_maxarglen(char * const *);
+static size_t   fts_pow2(size_t);
+static int      fts_palloc(FTS *, size_t);
+static void     fts_padjust(FTS *, FTSENT *);
+static FTSENT  *fts_sort(FTS *, FTSENT *, size_t);
+static unsigned short fts_stat(FTS *, FTSENT *, int);
+static int      fts_safe_changedir(const FTS *, const FTSENT *, int,
+    const char *);
+
+#if defined(ALIGNBYTES) && defined(ALIGN)
+#define        FTS_ALLOC_ALIGNED       1
+#else
+#undef FTS_ALLOC_ALIGNED
+#endif
+
+#define        ISDOT(a)        (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
+
+#define        CLR(opt)        (sp->fts_options &= ~(opt))
+#define        ISSET(opt)      (sp->fts_options & (opt))
+#define        SET(opt)        (sp->fts_options |= (opt))
+
+#define        CHDIR(sp, path) (!ISSET(FTS_NOCHDIR) && chdir(path))
+#define        FCHDIR(sp, fd)  (!ISSET(FTS_NOCHDIR) && fchdir(fd))
+
+/* fts_build flags */
+#define        BCHILD          1               /* fts_children */
+#define        BNAMES          2               /* fts_children, names only */
+#define        BREAD           3               /* fts_read */
+
+#ifndef DTF_HIDEW
+#undef FTS_WHITEOUT
+#endif
+
+FTS *
+fts_open(char * const *argv, int options,
+    int (*compar)(const FTSENT **, const FTSENT **))
+{
+       FTS *sp;
+       FTSENT *p, *root;
+       size_t nitems;
+       FTSENT *parent, *tmp = NULL;    /* pacify gcc */
+       size_t len;
+
+       _DIAGASSERT(argv != NULL);
+
+       /* Options check. */
+       if (options & ~FTS_OPTIONMASK) {
+               errno = EINVAL;
+               return (NULL);
+       }
+
+       /* Allocate/initialize the stream */
+       if ((sp = malloc((unsigned int)sizeof(FTS))) == NULL)
+               return (NULL);
+       memset(sp, 0, sizeof(FTS));
+       sp->fts_compar = compar;
+       sp->fts_options = options;
+
+       /* Logical walks turn on NOCHDIR; symbolic links are too hard. */
+       if (ISSET(FTS_LOGICAL))
+               SET(FTS_NOCHDIR);
+
+       /*
+        * Start out with 1K of path space, and enough, in any case,
+        * to hold the user's paths.
+        */
+       if (fts_palloc(sp, MAX(fts_maxarglen(argv), MAXPATHLEN)))
+               goto mem1;
+
+       /* Allocate/initialize root's parent. */
+       if ((parent = fts_alloc(sp, "", 0)) == NULL)
+               goto mem2;
+       parent->fts_level = FTS_ROOTPARENTLEVEL;
+
+       /* Allocate/initialize root(s). */
+       for (root = NULL, nitems = 0; *argv; ++argv, ++nitems) {
+               /* Don't allow zero-length paths. */
+               if ((len = strlen(*argv)) == 0) {
+                       errno = ENOENT;
+                       goto mem3;
+               }
+
+               if ((p = fts_alloc(sp, *argv, len)) == NULL)
+                       goto mem3;
+               p->fts_level = FTS_ROOTLEVEL;
+               p->fts_parent = parent;
+               p->fts_accpath = p->fts_name;
+               p->fts_info = fts_stat(sp, p, ISSET(FTS_COMFOLLOW));
+
+               /* Command-line "." and ".." are real directories. */
+               if (p->fts_info == FTS_DOT)
+                       p->fts_info = FTS_D;
+
+               /*
+                * If comparison routine supplied, traverse in sorted
+                * order; otherwise traverse in the order specified.
+                */
+               if (compar) {
+                       p->fts_link = root;
+                       root = p;
+               } else {
+                       p->fts_link = NULL;
+                       if (root == NULL)
+                               tmp = root = p;
+                       else {
+                               tmp->fts_link = p;
+                               tmp = p;
+                       }
+               }
+       }
+       if (compar && nitems > 1)
+               root = fts_sort(sp, root, nitems);
+
+       /*
+        * Allocate a dummy pointer and make fts_read think that we've just
+        * finished the node before the root(s); set p->fts_info to FTS_INIT
+        * so that everything about the "current" node is ignored.
+        */
+       if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
+               goto mem3;
+       sp->fts_cur->fts_link = root;
+       sp->fts_cur->fts_info = FTS_INIT;
+
+       /*
+        * If using chdir(2), grab a file descriptor pointing to dot to insure
+        * that we can get back here; this could be avoided for some paths,
+        * but almost certainly not worth the effort.  Slashes, symbolic links,
+        * and ".." are all fairly nasty problems.  Note, if we can't get the
+        * descriptor we run anyway, just more slowly.
+        */
+       if (!ISSET(FTS_NOCHDIR)) {
+               if ((sp->fts_rfd = open(".", O_RDONLY, 0)) == -1)
+                       SET(FTS_NOCHDIR);
+               else if (fcntl(sp->fts_rfd, F_SETFD, FD_CLOEXEC) == -1) {
+                       close(sp->fts_rfd);
+                       SET(FTS_NOCHDIR);
+               }
+       }
+
+       if (nitems == 0)
+               fts_free(parent);
+
+       return (sp);
+
+mem3:  fts_lfree(root);
+       fts_free(parent);
+mem2:  free(sp->fts_path);
+mem1:  free(sp);
+       return (NULL);
+}
+
+static void
+fts_load(FTS *sp, FTSENT *p)
+{
+       size_t len;
+       char *cp;
+
+       _DIAGASSERT(sp != NULL);
+       _DIAGASSERT(p != NULL);
+
+       /*
+        * Load the stream structure for the next traversal.  Since we don't
+        * actually enter the directory until after the preorder visit, set
+        * the fts_accpath field specially so the chdir gets done to the right
+        * place and the user can access the first node.  From fts_open it's
+        * known that the path will fit.
+        */
+       len = p->fts_pathlen = p->fts_namelen;
+       memmove(sp->fts_path, p->fts_name, len + 1);
+       if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
+               len = strlen(++cp);
+               memmove(p->fts_name, cp, len + 1);
+               p->fts_namelen = len;
+       }
+       p->fts_accpath = p->fts_path = sp->fts_path;
+       sp->fts_dev = p->fts_dev;
+}
+
+int
+fts_close(FTS *sp)
+{
+       FTSENT *freep, *p;
+       int saved_errno = 0;
+
+       _DIAGASSERT(sp != NULL);
+
+       /*
+        * This still works if we haven't read anything -- the dummy structure
+        * points to the root list, so we step through to the end of the root
+        * list which has a valid parent pointer.
+        */
+       if (sp->fts_cur) {
+               if (sp->fts_cur->fts_flags & FTS_SYMFOLLOW)
+                       (void)close(sp->fts_cur->fts_symfd);
+               for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
+                       freep = p;
+                       p = p->fts_link ? p->fts_link : p->fts_parent;
+                       fts_free(freep);
+               }
+               fts_free(p);
+       }
+
+       /* Free up child linked list, sort array, path buffer. */
+       if (sp->fts_child)
+               fts_lfree(sp->fts_child);
+       if (sp->fts_array)
+               free(sp->fts_array);
+       free(sp->fts_path);
+
+       /* Return to original directory, save errno if necessary. */
+       if (!ISSET(FTS_NOCHDIR)) {
+               if (fchdir(sp->fts_rfd) == -1)
+                       saved_errno = errno;
+               (void)close(sp->fts_rfd);
+       }
+
+       /* Free up the stream pointer. */
+       free(sp);
+       if (saved_errno) {
+               errno = saved_errno;
+               return -1;
+       }
+
+       return 0;
+}
+
+#if !defined(__FTS_COMPAT_TAILINGSLASH)
+
+/*
+ * Special case of "/" at the end of the path so that slashes aren't
+ * appended which would cause paths to be written as "....//foo".
+ */
+#define        NAPPEND(p)                                                      \
+       (p->fts_path[p->fts_pathlen - 1] == '/'                         \
+           ? p->fts_pathlen - 1 : p->fts_pathlen)
+
+#else /* !defined(__FTS_COMPAT_TAILINGSLASH) */
+
+/*
+ * compatibility with the old behaviour.
+ *
+ * Special case a root of "/" so that slashes aren't appended which would
+ * cause paths to be written as "//foo".
+ */
+
+#define        NAPPEND(p)                                                      \
+       (p->fts_level == FTS_ROOTLEVEL && p->fts_pathlen == 1 &&        \
+           p->fts_path[0] == '/' ? 0 : p->fts_pathlen)
+
+#endif /* !defined(__FTS_COMPAT_TAILINGSLASH) */
+
+FTSENT *
+fts_read(FTS *sp)
+{
+       FTSENT *p, *tmp;
+       int instr;
+       char *t;
+       int saved_errno;
+
+       _DIAGASSERT(sp != NULL);
+
+       /* If finished or unrecoverable error, return NULL. */
+       if (sp->fts_cur == NULL || ISSET(FTS_STOP))
+               return (NULL);
+
+       /* Set current node pointer. */
+       p = sp->fts_cur;
+
+       /* Save and zero out user instructions. */
+       instr = p->fts_instr;
+       p->fts_instr = FTS_NOINSTR;
+
+       /* Any type of file may be re-visited; re-stat and re-turn. */
+       if (instr == FTS_AGAIN) {
+               p->fts_info = fts_stat(sp, p, 0);
+               return (p);
+       }
+
+       /*
+        * Following a symlink -- SLNONE test allows application to see
+        * SLNONE and recover.  If indirecting through a symlink, have
+        * keep a pointer to current location.  If unable to get that
+        * pointer, follow fails.
+        */
+       if (instr == FTS_FOLLOW &&
+           (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
+               p->fts_info = fts_stat(sp, p, 1);
+               if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
+                       if ((p->fts_symfd = open(".", O_RDONLY, 0)) == -1) {
+                               p->fts_errno = errno;
+                               p->fts_info = FTS_ERR;
+                       } else if (fcntl(p->fts_symfd, F_SETFD, FD_CLOEXEC) == -1) {
+                               p->fts_errno = errno;
+                               p->fts_info = FTS_ERR;
+                               close(p->fts_symfd);
+                       } else
+                               p->fts_flags |= FTS_SYMFOLLOW;
+               }
+               return (p);
+       }
+
+       /* Directory in pre-order. */
+       if (p->fts_info == FTS_D) {
+               /* If skipped or crossed mount point, do post-order visit. */
+               if (instr == FTS_SKIP ||
+                   (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
+                       if (p->fts_flags & FTS_SYMFOLLOW)
+                               (void)close(p->fts_symfd);
+                       if (sp->fts_child) {
+                               fts_lfree(sp->fts_child);
+                               sp->fts_child = NULL;
+                       }
+                       p->fts_info = FTS_DP;
+                       return (p);
+               }
+
+               /* Rebuild if only read the names and now traversing. */
+               if (sp->fts_child && ISSET(FTS_NAMEONLY)) {
+                       CLR(FTS_NAMEONLY);
+                       fts_lfree(sp->fts_child);
+                       sp->fts_child = NULL;
+               }
+
+               /*
+                * Cd to the subdirectory.
+                *
+                * If have already read and now fail to chdir, whack the list
+                * to make the names come out right, and set the parent errno
+                * so the application will eventually get an error condition.
+                * Set the FTS_DONTCHDIR flag so that when we logically change
+                * directories back to the parent we don't do a chdir.
+                *
+                * If haven't read do so.  If the read fails, fts_build sets
+                * FTS_STOP or the fts_info field of the node.
+                */
+               if (sp->fts_child) {
+                       if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
+                               p->fts_errno = errno;
+                               p->fts_flags |= FTS_DONTCHDIR;
+                               for (p = sp->fts_child; p; p = p->fts_link)
+                                       p->fts_accpath =
+                                           p->fts_parent->fts_accpath;
+                       }
+               } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
+                       if (ISSET(FTS_STOP))
+                               return (NULL);
+                       return (p);
+               }
+               p = sp->fts_child;
+               sp->fts_child = NULL;
+               goto name;
+       }
+
+       /* Move to the next node on this level. */
+next:  tmp = p;
+       if ((p = p->fts_link) != NULL) {
+               fts_free(tmp);
+
+               /*
+                * If reached the top, return to the original directory, and
+                * load the paths for the next root.
+                */
+               if (p->fts_level == FTS_ROOTLEVEL) {
+                       if (FCHDIR(sp, sp->fts_rfd)) {
+                               SET(FTS_STOP);
+                               return (NULL);
+                       }
+                       fts_load(sp, p);
+                       return (sp->fts_cur = p);
+               }
+
+               /*
+                * User may have called fts_set on the node.  If skipped,
+                * ignore.  If followed, get a file descriptor so we can
+                * get back if necessary.
+                */
+               if (p->fts_instr == FTS_SKIP)
+                       goto next;
+               if (p->fts_instr == FTS_FOLLOW) {
+                       p->fts_info = fts_stat(sp, p, 1);
+                       if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
+                               if ((p->fts_symfd =
+                                   open(".", O_RDONLY, 0)) == -1) {
+                                       p->fts_errno = errno;
+                                       p->fts_info = FTS_ERR;
+                               } else if (fcntl(p->fts_symfd, F_SETFD, FD_CLOEXEC) == -1) {
+                                       p->fts_errno = errno;
+                                       p->fts_info = FTS_ERR;
+                                       close(p->fts_symfd);
+                               } else
+                                       p->fts_flags |= FTS_SYMFOLLOW;
+                       }
+                       p->fts_instr = FTS_NOINSTR;
+               }
+
+name:          t = sp->fts_path + NAPPEND(p->fts_parent);
+               *t++ = '/';
+               memmove(t, p->fts_name, (size_t)(p->fts_namelen + 1));
+               return (sp->fts_cur = p);
+       }
+
+       /* Move up to the parent node. */
+       p = tmp->fts_parent;
+       fts_free(tmp);
+
+       if (p->fts_level == FTS_ROOTPARENTLEVEL) {
+               /*
+                * Done; free everything up and set errno to 0 so the user
+                * can distinguish between error and EOF.
+                */
+               fts_free(p);
+               errno = 0;
+               return (sp->fts_cur = NULL);
+       }
+
+       /* Nul terminate the pathname. */
+       sp->fts_path[p->fts_pathlen] = '\0';
+
+       /*
+        * Return to the parent directory.  If at a root node or came through
+        * a symlink, go back through the file descriptor.  Otherwise, cd up
+        * one directory.
+        */
+       if (p->fts_level == FTS_ROOTLEVEL) {
+               if (FCHDIR(sp, sp->fts_rfd)) {
+                       SET(FTS_STOP);
+                       return (NULL);
+               }
+       } else if (p->fts_flags & FTS_SYMFOLLOW) {
+               if (FCHDIR(sp, p->fts_symfd)) {
+                       saved_errno = errno;
+                       (void)close(p->fts_symfd);
+                       errno = saved_errno;
+                       SET(FTS_STOP);
+                       return (NULL);
+               }
+               (void)close(p->fts_symfd);
+       } else if (!(p->fts_flags & FTS_DONTCHDIR) &&
+           fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
+               SET(FTS_STOP);
+               return (NULL);
+       }
+       p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
+       return (sp->fts_cur = p);
+}
+
+/*
+ * Fts_set takes the stream as an argument although it's not used in this
+ * implementation; it would be necessary if anyone wanted to add global
+ * semantics to fts using fts_set.  An error return is allowed for similar
+ * reasons.
+ */
+/* ARGSUSED */
+int
+fts_set(FTS *sp, FTSENT *p, int instr)
+{
+
+       _DIAGASSERT(sp != NULL);
+       _DIAGASSERT(p != NULL);
+
+       if (instr && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
+           instr != FTS_NOINSTR && instr != FTS_SKIP) {
+               errno = EINVAL;
+               return (1);
+       }
+       p->fts_instr = instr;
+       return (0);
+}
+
+FTSENT *
+fts_children(FTS *sp, int instr)
+{
+       FTSENT *p;
+       int fd;
+
+       _DIAGASSERT(sp != NULL);
+
+       if (instr && instr != FTS_NAMEONLY) {
+               errno = EINVAL;
+               return (NULL);
+       }
+
+       /* Set current node pointer. */
+       p = sp->fts_cur;
+
+       /*
+        * Errno set to 0 so user can distinguish empty directory from
+        * an error.
+        */
+       errno = 0;
+
+       /* Fatal errors stop here. */
+       if (ISSET(FTS_STOP))
+               return (NULL);
+
+       /* Return logical hierarchy of user's arguments. */
+       if (p->fts_info == FTS_INIT)
+               return (p->fts_link);
+
+       /*
+        * If not a directory being visited in pre-order, stop here.  Could
+        * allow FTS_DNR, assuming the user has fixed the problem, but the
+        * same effect is available with FTS_AGAIN.
+        */
+       if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
+               return (NULL);
+
+       /* Free up any previous child list. */
+       if (sp->fts_child)
+               fts_lfree(sp->fts_child);
+
+       if (instr == FTS_NAMEONLY) {
+               SET(FTS_NAMEONLY);
+               instr = BNAMES;
+       } else
+               instr = BCHILD;
+
+       /*
+        * If using chdir on a relative path and called BEFORE fts_read does
+        * its chdir to the root of a traversal, we can lose -- we need to
+        * chdir into the subdirectory, and we don't know where the current
+        * directory is, so we can't get back so that the upcoming chdir by
+        * fts_read will work.
+        */
+       if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
+           ISSET(FTS_NOCHDIR))
+               return (sp->fts_child = fts_build(sp, instr));
+
+       if ((fd = open(".", O_RDONLY, 0)) == -1)
+               return (sp->fts_child = NULL);
+       sp->fts_child = fts_build(sp, instr);
+       if (fchdir(fd)) {
+               (void)close(fd);
+               return (NULL);
+       }
+       (void)close(fd);
+       return (sp->fts_child);
+}
+
+/*
+ * This is the tricky part -- do not casually change *anything* in here.  The
+ * idea is to build the linked list of entries that are used by fts_children
+ * and fts_read.  There are lots of special cases.
+ *
+ * The real slowdown in walking the tree is the stat calls.  If FTS_NOSTAT is
+ * set and it's a physical walk (so that symbolic links can't be directories),
+ * we can do things quickly.  First, if it's a 4.4BSD file system, the type
+ * of the file is in the directory entry.  Otherwise, we assume that the number
+ * of subdirectories in a node is equal to the number of links to the parent.
+ * The former skips all stat calls.  The latter skips stat calls in any leaf
+ * directories and for any files after the subdirectories in the directory have
+ * been found, cutting the stat calls by about 2/3.
+ */
+static FTSENT *
+fts_build(FTS *sp, int type)
+{
+       struct dirent *dp;
+       FTSENT *p, *head;
+       size_t nitems;
+       FTSENT *cur, *tail;
+       DIR *dirp;
+       void *oldaddr;
+       size_t dnamlen;
+       int cderrno, descend, level, nlinks, saved_errno, nostat, doadjust;
+       size_t len, maxlen;
+#ifdef FTS_WHITEOUT
+       int oflag;
+#endif
+       char *cp = NULL;        /* pacify gcc */
+
+       _DIAGASSERT(sp != NULL);
+
+       /* Set current node pointer. */
+       cur = sp->fts_cur;
+
+       /*
+        * Open the directory for reading.  If this fails, we're done.
+        * If being called from fts_read, set the fts_info field.
+        */
+#ifdef FTS_WHITEOUT
+       if (ISSET(FTS_WHITEOUT))
+               oflag = DTF_NODUP|DTF_REWIND;
+       else
+               oflag = DTF_HIDEW|DTF_NODUP|DTF_REWIND;
+#else
+#define        __opendir2(path, flag) opendir(path)
+#endif
+       if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) {
+               if (type == BREAD) {
+                       cur->fts_info = FTS_DNR;
+                       cur->fts_errno = errno;
+               }
+               return (NULL);
+       }
+
+       /*
+        * Nlinks is the number of possible entries of type directory in the
+        * directory if we're cheating on stat calls, 0 if we're not doing
+        * any stat calls at all, -1 if we're doing stats on everything.
+        */
+       if (type == BNAMES) {
+               nlinks = 0;
+               nostat = 1;
+       } else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) {
+               nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2);
+               nostat = 1;
+       } else {
+               nlinks = -1;
+               nostat = 0;
+       }
+
+#ifdef notdef
+       (void)printf("nlinks == %d (cur: %d)\n", nlinks, cur->fts_nlink);
+       (void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n",
+           ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT));
+#endif
+       /*
+        * If we're going to need to stat anything or we want to descend
+        * and stay in the directory, chdir.  If this fails we keep going,
+        * but set a flag so we don't chdir after the post-order visit.
+        * We won't be able to stat anything, but we can still return the
+        * names themselves.  Note, that since fts_read won't be able to
+        * chdir into the directory, it will have to return different path
+        * names than before, i.e. "a/b" instead of "b".  Since the node
+        * has already been visited in pre-order, have to wait until the
+        * post-order visit to return the error.  There is a special case
+        * here, if there was nothing to stat then it's not an error to
+        * not be able to stat.  This is all fairly nasty.  If a program
+        * needed sorted entries or stat information, they had better be
+        * checking FTS_NS on the returned nodes.
+        */
+       cderrno = 0;
+       if (nlinks || type == BREAD) {
+               if (fts_safe_changedir(sp, cur, dirfd(dirp), NULL)) {
+                       if (nlinks && type == BREAD)
+                               cur->fts_errno = errno;
+                       cur->fts_flags |= FTS_DONTCHDIR;
+                       descend = 0;
+                       cderrno = errno;
+               } else
+                       descend = 1;
+       } else
+               descend = 0;
+
+       /*
+        * Figure out the max file name length that can be stored in the
+        * current path -- the inner loop allocates more path as necessary.
+        * We really wouldn't have to do the maxlen calculations here, we
+        * could do them in fts_read before returning the path, but it's a
+        * lot easier here since the length is part of the dirent structure.
+        *
+        * If not changing directories set a pointer so that can just append
+        * each new name into the path.
+        */
+       len = NAPPEND(cur);
+       if (ISSET(FTS_NOCHDIR)) {
+               cp = sp->fts_path + len;
+               *cp++ = '/';
+       }
+       len++;
+       maxlen = sp->fts_pathlen - len;
+
+#if defined(__FTS_COMPAT_LEVEL)
+       if (cur->fts_level == SHRT_MAX) {
+               (void)closedir(dirp);
+               cur->fts_info = FTS_ERR;
+               SET(FTS_STOP);
+               errno = ENAMETOOLONG;
+               return (NULL);
+       }
+#endif
+
+       level = cur->fts_level + 1;
+
+       /* Read the directory, attaching each entry to the `link' pointer. */
+       doadjust = 0;
+       for (head = tail = NULL, nitems = 0; (dp = readdir(dirp)) != NULL;) {
+
+               if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
+                       continue;
+
+#if defined(HAVE_STRUCT_DIRENT_D_NAMLEN)
+               dnamlen = dp->d_namlen;
+#else
+               dnamlen = strlen(dp->d_name);
+#endif
+               if ((p = fts_alloc(sp, dp->d_name, dnamlen)) == NULL)
+                       goto mem1;
+               if (dnamlen >= maxlen) {        /* include space for NUL */
+                       oldaddr = sp->fts_path;
+                       if (fts_palloc(sp, dnamlen + len + 1)) {
+                               /*
+                                * No more memory for path or structures.  Save
+                                * errno, free up the current structure and the
+                                * structures already allocated.
+                                */
+mem1:                          saved_errno = errno;
+                               if (p)
+                                       fts_free(p);
+                               fts_lfree(head);
+                               (void)closedir(dirp);
+                               errno = saved_errno;
+                               cur->fts_info = FTS_ERR;
+                               SET(FTS_STOP);
+                               return (NULL);
+                       }
+                       /* Did realloc() change the pointer? */
+                       if (oldaddr != sp->fts_path) {
+                               doadjust = 1;
+                               if (ISSET(FTS_NOCHDIR))
+                                       cp = sp->fts_path + len;
+                       }
+                       maxlen = sp->fts_pathlen - len;
+               }
+
+#if defined(__FTS_COMPAT_LENGTH)
+               if (len + dnamlen >= USHRT_MAX) {
+                       /*
+                        * In an FTSENT, fts_pathlen is an unsigned short
+                        * so it is possible to wraparound here.
+                        * If we do, free up the current structure and the
+                        * structures already allocated, then error out
+                        * with ENAMETOOLONG.
+                        */
+                       fts_free(p);
+                       fts_lfree(head);
+                       (void)closedir(dirp);
+                       cur->fts_info = FTS_ERR;
+                       SET(FTS_STOP);
+                       errno = ENAMETOOLONG;
+                       return (NULL);
+               }
+#endif
+               p->fts_level = level;
+               p->fts_pathlen = len + dnamlen;
+               p->fts_parent = sp->fts_cur;
+
+#ifdef FTS_WHITEOUT
+               if (dp->d_type == DT_WHT)
+                       p->fts_flags |= FTS_ISW;
+#endif
+
+               if (cderrno) {
+                       if (nlinks) {
+                               p->fts_info = FTS_NS;
+                               p->fts_errno = cderrno;
+                       } else
+                               p->fts_info = FTS_NSOK;
+                       p->fts_accpath = cur->fts_accpath;
+               } else if (nlinks == 0
+#ifdef DT_DIR
+                   || (nostat &&
+                   dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN)
+#endif
+                   ) {
+                       p->fts_accpath =
+                           ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name;
+                       p->fts_info = FTS_NSOK;
+               } else {
+                       /* Build a file name for fts_stat to stat. */
+                       if (ISSET(FTS_NOCHDIR)) {
+                               p->fts_accpath = p->fts_path;
+                               memmove(cp, p->fts_name,
+                                       (size_t)(p->fts_namelen + 1));
+                       } else
+                               p->fts_accpath = p->fts_name;
+                       /* Stat it. */
+                       p->fts_info = fts_stat(sp, p, 0);
+
+                       /* Decrement link count if applicable. */
+                       if (nlinks > 0 && (p->fts_info == FTS_D ||
+                           p->fts_info == FTS_DC || p->fts_info == FTS_DOT))
+                               --nlinks;
+               }
+
+               /* We walk in directory order so "ls -f" doesn't get upset. */
+               p->fts_link = NULL;
+               if (head == NULL)
+                       head = tail = p;
+               else {
+                       tail->fts_link = p;
+                       tail = p;
+               }
+               ++nitems;
+       }
+       (void)closedir(dirp);
+
+       /*
+        * If had to realloc the path, adjust the addresses for the rest
+        * of the tree.
+        */
+       if (doadjust)
+               fts_padjust(sp, head);
+
+       /*
+        * If not changing directories, reset the path back to original
+        * state.
+        */
+       if (ISSET(FTS_NOCHDIR)) {
+               if (len == sp->fts_pathlen || nitems == 0)
+                       --cp;
+               *cp = '\0';
+       }
+
+       /*
+        * If descended after called from fts_children or after called from
+        * fts_read and nothing found, get back.  At the root level we use
+        * the saved fd; if one of fts_open()'s arguments is a relative path
+        * to an empty directory, we wind up here with no other way back.  If
+        * can't get back, we're done.
+        */
+       if (descend && (type == BCHILD || !nitems) &&
+           (cur->fts_level == FTS_ROOTLEVEL ?
+           FCHDIR(sp, sp->fts_rfd) :
+           fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) {
+               cur->fts_info = FTS_ERR;
+               SET(FTS_STOP);
+               return (NULL);
+       }
+
+       /* If didn't find anything, return NULL. */
+       if (!nitems) {
+               if (type == BREAD)
+                       cur->fts_info = FTS_DP;
+               return (NULL);
+       }
+
+       /* Sort the entries. */
+       if (sp->fts_compar && nitems > 1)
+               head = fts_sort(sp, head, nitems);
+       return (head);
+}
+
+static unsigned short
+fts_stat(FTS *sp, FTSENT *p, int follow)
+{
+       FTSENT *t;
+       dev_t dev;
+       __fts_ino_t ino;
+       __fts_stat_t *sbp, sb;
+       int saved_errno;
+
+       _DIAGASSERT(sp != NULL);
+       _DIAGASSERT(p != NULL);
+
+       /* If user needs stat info, stat buffer already allocated. */
+       sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp;
+
+#ifdef FTS_WHITEOUT
+       /* check for whiteout */
+       if (p->fts_flags & FTS_ISW) {
+               if (sbp != &sb) {
+                       memset(sbp, '\0', sizeof (*sbp));
+                       sbp->st_mode = S_IFWHT;
+               }
+               return (FTS_W);
+       }
+#endif
+
+       /*
+        * If doing a logical walk, or application requested FTS_FOLLOW, do
+        * a stat(2).  If that fails, check for a non-existent symlink.  If
+        * fail, set the errno from the stat call.
+        */
+       if (ISSET(FTS_LOGICAL) || follow) {
+               if (stat(p->fts_accpath, sbp)) {
+                       saved_errno = errno;
+                       if (!lstat(p->fts_accpath, sbp)) {
+                               errno = 0;
+                               return (FTS_SLNONE);
+                       }
+                       p->fts_errno = saved_errno;
+                       goto err;
+               }
+       } else if (lstat(p->fts_accpath, sbp)) {
+               p->fts_errno = errno;
+err:           memset(sbp, 0, sizeof(*sbp));
+               return (FTS_NS);
+       }
+
+       if (S_ISDIR(sbp->st_mode)) {
+               /*
+                * Set the device/inode.  Used to find cycles and check for
+                * crossing mount points.  Also remember the link count, used
+                * in fts_build to limit the number of stat calls.  It is
+                * understood that these fields are only referenced if fts_info
+                * is set to FTS_D.
+                */
+               dev = p->fts_dev = sbp->st_dev;
+               ino = p->fts_ino = sbp->st_ino;
+               p->fts_nlink = sbp->st_nlink;
+
+               if (ISDOT(p->fts_name))
+                       return (FTS_DOT);
+
+               /*
+                * Cycle detection is done by brute force when the directory
+                * is first encountered.  If the tree gets deep enough or the
+                * number of symbolic links to directories is high enough,
+                * something faster might be worthwhile.
+                */
+               for (t = p->fts_parent;
+                   t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
+                       if (ino == t->fts_ino && dev == t->fts_dev) {
+                               p->fts_cycle = t;
+                               return (FTS_DC);
+                       }
+               return (FTS_D);
+       }
+       if (S_ISLNK(sbp->st_mode))
+               return (FTS_SL);
+       if (S_ISREG(sbp->st_mode))
+               return (FTS_F);
+       return (FTS_DEFAULT);
+}
+
+static FTSENT *
+fts_sort(FTS *sp, FTSENT *head, size_t nitems)
+{
+       FTSENT **ap, *p;
+
+       _DIAGASSERT(sp != NULL);
+       _DIAGASSERT(head != NULL);
+
+       /*
+        * Construct an array of pointers to the structures and call qsort(3).
+        * Reassemble the array in the order returned by qsort.  If unable to
+        * sort for memory reasons, return the directory entries in their
+        * current order.  Allocate enough space for the current needs plus
+        * 40 so don't realloc one entry at a time.
+        */
+       if (nitems > sp->fts_nitems) {
+               FTSENT **new;
+
+               new = realloc(sp->fts_array, sizeof(FTSENT *) * (nitems + 40));
+               if (new == 0)
+                       return (head);
+               sp->fts_array = new;
+               sp->fts_nitems = nitems + 40;
+       }
+       for (ap = sp->fts_array, p = head; p; p = p->fts_link)
+               *ap++ = p;
+       qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *),
+               (int (*)(const void *, const void *))sp->fts_compar);
+       for (head = *(ap = sp->fts_array); --nitems; ++ap)
+               ap[0]->fts_link = ap[1];
+       ap[0]->fts_link = NULL;
+       return (head);
+}
+
+static FTSENT *
+fts_alloc(FTS *sp, const char *name, size_t namelen)
+{
+       FTSENT *p;
+#if defined(FTS_ALLOC_ALIGNED)
+       size_t len;
+#endif
+
+       _DIAGASSERT(sp != NULL);
+       _DIAGASSERT(name != NULL);
+
+#if defined(FTS_ALLOC_ALIGNED)
+       /*
+        * The file name is a variable length array and no stat structure is
+        * necessary if the user has set the nostat bit.  Allocate the FTSENT
+        * structure, the file name and the stat structure in one chunk, but
+        * be careful that the stat structure is reasonably aligned.  Since the
+        * fts_name field is declared to be of size 1, the fts_name pointer is
+        * namelen + 2 before the first possible address of the stat structure.
+        */
+       len = sizeof(FTSENT) + namelen;
+       if (!ISSET(FTS_NOSTAT))
+               len += sizeof(*(p->fts_statp)) + ALIGNBYTES;
+       if ((p = malloc(len)) == NULL)
+               return (NULL);
+
+       if (!ISSET(FTS_NOSTAT))
+               p->fts_statp = (__fts_stat_t *)ALIGN(
+                   (unsigned long)(p->fts_name + namelen + 2));
+#else
+       if ((p = malloc(sizeof(FTSENT) + namelen)) == NULL)
+               return (NULL);
+
+       if (!ISSET(FTS_NOSTAT))
+               if ((p->fts_statp = malloc(sizeof(*(p->fts_statp)))) == NULL) {
+                       free(p);
+                       return (NULL);
+               }
+#endif
+
+        if (ISSET(FTS_NOSTAT))
+                p->fts_statp = NULL;
+
+       /* Copy the name plus the trailing NULL. */
+       memmove(p->fts_name, name, namelen + 1);
+
+       p->fts_namelen = namelen;
+       p->fts_path = sp->fts_path;
+       p->fts_errno = 0;
+       p->fts_flags = 0;
+       p->fts_instr = FTS_NOINSTR;
+       p->fts_number = 0;
+       p->fts_pointer = NULL;
+       return (p);
+}
+
+static void
+fts_free(FTSENT *p)
+{
+#if !defined(FTS_ALLOC_ALIGNED)
+       if (p->fts_statp)
+               free(p->fts_statp);
+#endif
+       free(p);
+}
+
+static void
+fts_lfree(FTSENT *head)
+{
+       FTSENT *p;
+
+       /* XXX: head may be NULL ? */
+
+       /* Free a linked list of structures. */
+       while ((p = head) != NULL) {
+               head = head->fts_link;
+               fts_free(p);
+       }
+}
+
+static size_t
+fts_pow2(size_t x)
+{
+
+       x--;
+       x |= x>>1;
+       x |= x>>2;
+       x |= x>>4;
+       x |= x>>8;
+       x |= x>>16;
+#if LONG_BIT > 32
+       x |= x>>32;
+#endif
+#if LONG_BIT > 64
+       x |= x>>64;
+#endif
+       x++;
+       return (x);
+}
+
+/*
+ * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
+ * Most systems will allow creation of paths much longer than MAXPATHLEN, even
+ * though the kernel won't resolve them.  Round up the new size to a power of 2,
+ * so we don't realloc the path 2 bytes at a time.
+ */
+static int
+fts_palloc(FTS *sp, size_t size)
+{
+       char *new;
+
+       _DIAGASSERT(sp != NULL);
+
+#ifdef __FTS_COMPAT_LENGTH
+       /* Protect against fts_pathlen overflow. */
+       if (size > USHRT_MAX + 1) {
+               errno = ENAMETOOLONG;
+               return (1);
+       }
+#endif
+       size = fts_pow2(size);
+       new = realloc(sp->fts_path, size);
+       if (new == 0)
+               return (1);
+       sp->fts_path = new;
+       sp->fts_pathlen = size;
+       return (0);
+}
+
+/*
+ * When the path is realloc'd, have to fix all of the pointers in structures
+ * already returned.
+ */
+static void
+fts_padjust(FTS *sp, FTSENT *head)
+{
+       FTSENT *p;
+       char *addr;
+
+       _DIAGASSERT(sp != NULL);
+
+#define        ADJUST(p) do {                                                  \
+       if ((p)->fts_accpath != (p)->fts_name)                          \
+               (p)->fts_accpath =                                      \
+                   addr + ((p)->fts_accpath - (p)->fts_path);          \
+       (p)->fts_path = addr;                                           \
+} while (/*CONSTCOND*/0)
+
+       addr = sp->fts_path;
+
+       /* Adjust the current set of children. */
+       for (p = sp->fts_child; p; p = p->fts_link)
+               ADJUST(p);
+
+       /* Adjust the rest of the tree, including the current level. */
+       for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
+               ADJUST(p);
+               p = p->fts_link ? p->fts_link : p->fts_parent;
+       }
+}
+
+static size_t
+fts_maxarglen(char * const *argv)
+{
+       size_t len, max;
+
+       _DIAGASSERT(argv != NULL);
+
+       for (max = 0; *argv; ++argv)
+               if ((len = strlen(*argv)) > max)
+                       max = len;
+       return (max + 1);
+}
+
+/*
+ * Change to dir specified by fd or p->fts_accpath without getting
+ * tricked by someone changing the world out from underneath us.
+ * Assumes p->fts_dev and p->fts_ino are filled in.
+ */
+static int
+fts_safe_changedir(const FTS *sp, const FTSENT *p, int fd, const char *path)
+{
+       int oldfd = fd, ret = -1;
+       __fts_stat_t sb;
+
+       if (ISSET(FTS_NOCHDIR))
+               return 0;
+
+       if (oldfd < 0 && (fd = open(path, O_RDONLY)) == -1)
+               return -1;
+
+       if (fstat(fd, &sb) == -1)
+               goto bail;
+
+       if (sb.st_ino != p->fts_ino || sb.st_dev != p->fts_dev) {
+               errno = ENOENT;
+               goto bail;
+       }
+
+       ret = fchdir(fd);
+
+bail:
+       if (oldfd < 0) {
+               int save_errno = errno;
+               (void)close(fd);
+               errno = save_errno;
+       }
+       return ret;
+}
diff --git a/lib/nbsd_libc/gen/ftw.3 b/lib/nbsd_libc/gen/ftw.3
new file mode 100644 (file)
index 0000000..4343823
--- /dev/null
@@ -0,0 +1,214 @@
+.\"    $NetBSD: ftw.3,v 1.5 2010/04/30 04:39:16 jruoho Exp $
+.\"
+.\"    From OpenBSD: ftw.3,v 1.4 2003/10/30 18:52:58 jmc Exp
+.\"
+.\" Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
+.\"
+.\" 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.
+.\"
+.\" Sponsored in part by the Defense Advanced Research Projects
+.\" Agency (DARPA) and Air Force Research Laboratory, Air Force
+.\" Materiel Command, USAF, under agreement number F39502-99-1-0512.
+.\"
+.Dd April 30, 2010
+.Dt FTW 3
+.Os
+.Sh NAME
+.Nm ftw, nftw
+.Nd traverse (walk) a file tree
+.Sh SYNOPSIS
+.In ftw.h
+.Ft int
+.Fo ftw
+.Fa "const char *path"
+.Fa "int (*fn)(const char *, const struct stat *, int)"
+.Fa "int maxfds"
+.Fc
+.Ft int
+.Fo nftw
+.Fa "const char *path"
+.Fa "int (*fn)(const\ char\ *, const\ struct\ stat\ *, int, struct\ FTW\ *)"
+.Fa "int maxfds"
+.Fa "int flags"
+.Fc
+.Sh DESCRIPTION
+.Bf -symbolic
+These functions are provided for compatibility with legacy code.
+New code should use the
+.Xr fts 3
+functions.
+.Ef
+.Pp
+The
+.Fn ftw
+and
+.Fn nftw
+functions traverse (walk) the directory hierarchy rooted in
+.Fa path .
+For each object in the hierarchy, these functions call the function
+pointed to by
+.Fa fn .
+The
+.Fn ftw
+function passes this function a pointer to a NUL-terminated string containing
+the name of the object, a pointer to a stat structure corresponding to the
+object, and an integer flag.
+The
+.Fn nftw
+function passes the aforementioned arguments plus a pointer to a
+.Dv FTW
+structure as defined by
+.In ftw.h
+(shown below):
+.Bd -literal
+struct FTW {
+    int base;  /* offset of basename into pathname */
+    int level; /* directory depth relative to starting point */
+};
+.Ed
+.Pp
+Possible values for the flag passed to
+.Fa fn
+are:
+.Bl -tag -width FTW_DNR
+.It Dv FTW_F
+A regular file.
+.It Dv FTW_D
+A directory being visited in pre-order.
+.It Dv FTW_DNR
+A directory which cannot be read.
+The directory will not be descended into.
+.It Dv FTW_DP
+A directory being visited in post-order
+.Pq Fn nftw No only .
+.It Dv FTW_NS
+A file for which no
+.Xr stat 2
+information was available.
+The contents of the stat structure are undefined.
+.It Dv FTW_SL
+A symbolic link.
+.It Dv FTW_SLN
+A symbolic link with a non-existent target
+.Pq Fn nftw No only .
+.El
+.Pp
+The
+.Fn ftw
+function traverses the tree in pre-order.
+That is, it processes the directory before the directory's contents.
+.Pp
+The
+.Fa maxfds
+argument specifies the maximum number of file descriptors
+to keep open while traversing the tree.
+It has no effect in this implementation.
+.Pp
+The
+.Fn nftw
+function has an additional
+.Fa flags
+argument with the following possible values:
+.Bl -tag -width FTW_MOUNT
+.It Dv FTW_PHYS
+Physical walk, don't follow symbolic links.
+.It Dv FTW_MOUNT
+The walk will not cross a mount point.
+.It FTW_DEPTH
+Process directories in post-order.
+Contents of a directory are visited before the directory itself.
+By default,
+.Fn nftw
+traverses the tree in pre-order.
+.It FTW_CHDIR
+Change to a directory before reading it.
+By default,
+.Fn nftw
+will change its starting directory.
+The current working directory will be restored to its original value before
+.Fn nftw
+returns.
+.El
+.Sh RETURN VALUES
+If the tree was traversed successfully, the
+.Fn ftw
+and
+.Fn nftw
+functions return 0.
+If the function pointed to by
+.Fa fn
+returns a non-zero value,
+.Fn ftw
+and
+.Fn nftw
+will stop processing the tree and return the value from
+.Fa fn .
+Both functions return \-1 if an error is detected.
+.Sh ERRORS
+The
+.Fn ftw
+and
+.Fn nftw
+functions may fail and set
+.Va errno
+for any of the errors specified for the library functions
+.Xr close 2 ,
+.Xr open 2 ,
+.Xr stat 2 ,
+.Xr malloc 3 ,
+.Xr opendir 3 ,
+and
+.Xr readdir 3 .
+If the
+.Dv FGTW_CHDIR
+flag is set, the
+.Fn nftw
+function may fail and set
+.Va errno
+for any of the errors specified for
+.Xr chdir 2 .
+In addition, either function may fail and set
+.Va errno
+as follows:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa maxfds
+argument is less than 1 or greater than
+.Dv OPEN_MAX .
+.El
+.Sh SEE ALSO
+.Xr chdir 2 ,
+.Xr close 2 ,
+.Xr open 2 ,
+.Xr stat 2 ,
+.Xr fts 3 ,
+.Xr malloc 3 ,
+.Xr opendir 3 ,
+.Xr readdir 3
+.Sh STANDARDS
+The
+.Fn ftw
+and
+.Fn nftw
+functions conform to
+.St -p1003.1-2001 .
+The
+.St -p1003.1-2008
+revision marked the function
+.Fn ftw
+as obsolete.
+.Sh BUGS
+The
+.Fa maxfds
+argument is currently ignored.
diff --git a/lib/nbsd_libc/gen/ftw.c b/lib/nbsd_libc/gen/ftw.c
new file mode 100644 (file)
index 0000000..a7f6bbd
--- /dev/null
@@ -0,0 +1,98 @@
+/* $NetBSD: ftw.c,v 1.1 2005/12/30 23:07:32 agc Exp $ */
+
+/*     From OpenBSD: ftw.c,v 1.2 2003/07/21 21:15:32 millert Exp       */
+
+/*
+ * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
+ *
+ * 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.
+ *
+ * Sponsored in part by the Defense Advanced Research Projects
+ * Agency (DARPA) and Air Force Research Laboratory, Air Force
+ * Materiel Command, USAF, under agreement number F39502-99-1-0512.
+ */
+#include <sys/cdefs.h>
+
+#ifndef lint
+__RCSID("$NetBSD: ftw.c,v 1.1 2005/12/30 23:07:32 agc Exp $");
+#endif
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <fts.h>
+#include <ftw.h>
+#include <limits.h>
+
+int
+ftw(const char *path, int (*fn)(const char *, const struct stat *, int),
+    int nfds)
+{
+       /* LINTED */
+       char * const paths[2] = { __UNCONST(path), NULL };
+       FTSENT *cur;
+       FTS *ftsp;
+       int fnflag, error, sverrno;
+
+       /* XXX - nfds is currently unused */
+       if (nfds < 1 || nfds > OPEN_MAX) {
+               errno = EINVAL;
+               return (-1);
+       }
+
+       ftsp = fts_open(paths, FTS_COMFOLLOW | FTS_NOCHDIR, NULL);
+       if (ftsp == NULL)
+               return (-1);
+       error = 0;
+       while ((cur = fts_read(ftsp)) != NULL) {
+               switch (cur->fts_info) {
+               case FTS_D:
+                       fnflag = FTW_D;
+                       break;
+               case FTS_DNR:
+                       fnflag = FTW_DNR;
+                       break;
+               case FTS_DP:
+                       /* we only visit in preorder */
+                       continue;
+               case FTS_F:
+               case FTS_DEFAULT:
+                       fnflag = FTW_F;
+                       break;
+               case FTS_NS:
+               case FTS_NSOK:
+               case FTS_SLNONE:
+                       fnflag = FTW_NS;
+                       break;
+               case FTS_SL:
+                       fnflag = FTW_SL;
+                       break;
+               case FTS_DC:
+                       errno = ELOOP;
+                       /* FALLTHROUGH */
+               default:
+                       error = -1;
+                       goto done;
+               }
+               error = fn(cur->fts_path, cur->fts_statp, fnflag);
+               if (error != 0)
+                       break;
+       }
+done:
+       sverrno = errno;
+       if (fts_close(ftsp) != 0 && error == 0)
+               error = -1;
+       else
+               errno = sverrno;
+       return (error);
+}
diff --git a/lib/nbsd_libc/gen/getbsize.3 b/lib/nbsd_libc/gen/getbsize.3
new file mode 100644 (file)
index 0000000..b3c1002
--- /dev/null
@@ -0,0 +1,90 @@
+.\"    $NetBSD: getbsize.3,v 1.9 2003/08/07 16:42:48 agc Exp $
+.\"
+.\" Copyright (c) 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getbsize.3 8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 30, 2003
+.Dt GETBSIZE 3
+.Os
+.Sh NAME
+.Nm getbsize
+.Nd get user block size
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft char *
+.Fn getbsize "int *headerlenp" "long *blocksizep"
+.Sh DESCRIPTION
+The
+.Nm getbsize
+function determines the user's preferred block size based on the value of the
+.Dq BLOCKSIZE
+environment variable; see
+.Xr environ 7
+for details on its use and format.
+.Pp
+The
+.Nm getbsize
+function returns a pointer to a
+.Dv NUL
+terminated string describing
+the block size, something like
+.Dq 1K-blocks .
+If the
+.Fa headerlenp
+parameter is not
+.Dv NULL
+the memory referenced by
+.Fa headerlenp
+is filled in with the length of the string (not including the
+terminating
+.Dv NUL ) .
+If the
+.Fa blocksizep
+parameter is not
+.Dv NULL
+the memory referenced by
+.Fa blocksizep
+is filled in with block size, in bytes.
+.Pp
+If the user's block size is unreasonable, a warning message is
+written to standard error and the returned information reflects
+a block size of 512 bytes.
+.Sh SEE ALSO
+.Xr df 1 ,
+.Xr du 1 ,
+.Xr ls 1 ,
+.Xr systat 1 ,
+.Xr environ 7
+.Sh HISTORY
+The
+.Nm getbsize
+function first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/gen/getbsize.c b/lib/nbsd_libc/gen/getbsize.c
new file mode 100644 (file)
index 0000000..c5e4c33
--- /dev/null
@@ -0,0 +1,120 @@
+/*     $NetBSD: getbsize.c,v 1.16 2005/11/29 03:11:59 christos Exp $   */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getbsize.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getbsize.c,v 1.16 2005/11/29 03:11:59 christos Exp $");
+#endif
+#endif /* not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <err.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(getbsize,_getbsize)
+#endif
+
+char *
+getbsize(headerlenp, blocksizep)
+       int *headerlenp;
+       long *blocksizep;
+{
+       static char header[20];
+       long n, max, mul, blocksize;
+       char *ep, *p;
+       const char *form;
+
+#define        KB      (1024L)
+#define        MB      (1024L * 1024L)
+#define        GB      (1024L * 1024L * 1024L)
+#define        MAXB    GB              /* No tera, peta, nor exa. */
+       form = "";
+       if ((p = getenv("BLOCKSIZE")) != NULL && *p != '\0') {
+               if ((n = strtol(p, &ep, 10)) < 0)
+                       goto underflow;
+               if (n == 0)
+                       n = 1;
+               if (*ep && ep[1])
+                       goto fmterr;
+               switch (*ep) {
+               case 'G': case 'g':
+                       form = "G";
+                       max = MAXB / GB;
+                       mul = GB;
+                       break;
+               case 'K': case 'k':
+                       form = "K";
+                       max = MAXB / KB;
+                       mul = KB;
+                       break;
+               case 'M': case 'm':
+                       form = "M";
+                       max = MAXB / MB;
+                       mul = MB;
+                       break;
+               case '\0':
+                       max = MAXB;
+                       mul = 1;
+                       break;
+               default:
+fmterr:                        warnx("%s: unknown blocksize", p);
+                       n = 512;
+                       mul = 1;
+                       max = 0;
+                       break;
+               }
+               if (n > max) {
+                       warnx("maximum blocksize is %ldG", MAXB / GB);
+                       n = max;
+               }
+               if ((blocksize = n * mul) < 512) {
+underflow:             warnx("%s: minimum blocksize is 512", p);
+                       form = "";
+                       blocksize = n = 512;
+               }
+       } else
+               blocksize = n = 512;
+
+       if (headerlenp)
+               *headerlenp =
+                   snprintf(header, sizeof(header), "%ld%s-blocks", n, form);
+       if (blocksizep)
+               *blocksizep = blocksize;
+       return (header);
+}
diff --git a/lib/nbsd_libc/gen/getcap.c b/lib/nbsd_libc/gen/getcap.c
new file mode 100644 (file)
index 0000000..f17873e
--- /dev/null
@@ -0,0 +1,1213 @@
+/*     $NetBSD: getcap.c,v 1.48 2008/02/02 20:56:46 christos Exp $     */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Casey Leedom of Lawrence Livermore National Laboratory.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getcap.c   8.3 (Berkeley) 3/25/94";
+#else
+__RCSID("$NetBSD: getcap.c,v 1.48 2008/02/02 20:56:46 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#ifndef SMALL
+#include "namespace.h"
+#endif
+#include <sys/types.h>
+#include <sys/param.h>
+
+#include <assert.h>
+#include <ctype.h>
+#ifndef SMALL
+#include <db.h>
+#endif
+#include <errno.h>     
+#include <fcntl.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(cgetcap,_cgetcap)
+__weak_alias(cgetclose,_cgetclose)
+__weak_alias(cgetent,_cgetent)
+__weak_alias(cgetfirst,_cgetfirst)
+__weak_alias(cgetmatch,_cgetmatch)
+__weak_alias(cgetnext,_cgetnext)
+__weak_alias(cgetnum,_cgetnum)
+__weak_alias(cgetset,_cgetset)
+__weak_alias(cgetstr,_cgetstr)
+__weak_alias(cgetustr,_cgetustr)
+__weak_alias(csetexpandtc,_csetexpandtc)
+#endif
+
+#define        BFRAG           1024
+#define        BSIZE           1024
+#define        ESC             ('[' & 037)     /* ASCII ESC */
+#define        MAX_RECURSION   32              /* maximum getent recursion */
+#define        SFRAG           100             /* cgetstr mallocs in SFRAG chunks */
+
+#define RECOK  (char)0
+#define TCERR  (char)1
+#define        SHADOW  (char)2
+
+static size_t   topreclen;     /* toprec length */
+static char    *toprec;        /* Additional record specified by cgetset() */
+static int      gottoprec;     /* Flag indicating retrieval of toprecord */
+static int      expandtc = 1;  /* flag to expand tc= or not */
+
+#ifndef SMALL
+static int     cdbget(DB *, char **, const char *);
+#endif
+static int     getent(char **, size_t *, const char * const *, int,
+    const char *, int, char *);
+static int     nfcmp(char *, char *);
+
+/*
+ * Cgetset() allows the addition of a user specified buffer to be added
+ * to the database array, in effect "pushing" the buffer on top of the
+ * virtual database. 0 is returned on success, -1 on failure.
+ */
+int
+cgetset(const char *ent)
+{
+       const char *source, *check;
+       char *dest;
+
+       if (ent == NULL) {
+               if (toprec != NULL)
+                       free(toprec);
+                toprec = NULL;
+                topreclen = 0;
+                return 0;
+        }
+        topreclen = strlen(ent);
+        if ((toprec = malloc(topreclen + 1)) == NULL) {
+               errno = ENOMEM;
+                return -1;
+       }
+       gottoprec = 0;
+
+       source = ent;
+       dest = toprec;
+       while (*source != '\0') { /* Strip whitespace */
+               *dest++ = *source++; /* Do not check first field */
+               while (*source == ':') {
+                       check = source + 1;
+                       while (*check && (isspace((unsigned char)*check) ||
+                           (*check=='\\' && isspace((unsigned char)check[1]))))
+                               ++check;
+                       if (*check == ':')
+                               source = check;
+                       else
+                               break;
+
+               }
+       }
+       *dest = 0;
+
+        return 0;
+}
+
+/*
+ * Cgetcap searches the capability record buf for the capability cap with
+ * type `type'.  A pointer to the value of cap is returned on success, NULL
+ * if the requested capability couldn't be found.
+ *
+ * Specifying a type of ':' means that nothing should follow cap (:cap:).
+ * In this case a pointer to the terminating ':' or NUL will be returned if
+ * cap is found.
+ *
+ * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
+ * return NULL.
+ */
+char *
+cgetcap(buf, cap, type)
+       char *buf;
+       const char *cap;
+       int type;
+{
+       char *bp;
+       const char *cp;
+
+       _DIAGASSERT(buf != NULL);
+       _DIAGASSERT(cap != NULL);
+
+       bp = buf;
+       for (;;) {
+               /*
+                * Skip past the current capability field - it's either the
+                * name field if this is the first time through the loop, or
+                * the remainder of a field whose name failed to match cap.
+                */
+               for (;;)
+                       if (*bp == '\0')
+                               return NULL;
+                       else if (*bp++ == ':')
+                               break;
+
+               /*
+                * Try to match (cap, type) in buf.
+                */
+               for (cp = cap; *cp == *bp && *bp != '\0'; cp++, bp++)
+                       continue;
+               if (*cp != '\0')
+                       continue;
+               if (*bp == '@')
+                       return NULL;
+               if (type == ':') {
+                       if (*bp != '\0' && *bp != ':')
+                               continue;
+                       return bp;
+               }
+               if (*bp != type)
+                       continue;
+               bp++;
+               return *bp == '@' ? NULL : bp;
+       }
+       /* NOTREACHED */
+}
+
+/*
+ * Cgetent extracts the capability record name from the NULL terminated file
+ * array db_array and returns a pointer to a malloc'd copy of it in buf.
+ * Buf must be retained through all subsequent calls to cgetcap, cgetnum,
+ * cgetflag, and cgetstr, but may then be free'd.  0 is returned on success,
+ * -1 if the requested record couldn't be found, -2 if a system error was
+ * encountered (couldn't open/read a file, etc.), and -3 if a potential
+ * reference loop is detected.
+ */
+/* coverity[+alloc : arg-*0] */
+int
+cgetent(char **buf, const char * const *db_array, const char *name)
+{
+       size_t dummy;
+
+       _DIAGASSERT(buf != NULL);
+       _DIAGASSERT(db_array != NULL);
+       _DIAGASSERT(name != NULL);
+
+       return getent(buf, &dummy, db_array, -1, name, 0, NULL);
+}
+
+void
+csetexpandtc(int etc)
+{
+       expandtc = etc;
+}
+
+/*
+ * Getent implements the functions of cgetent.  If fd is non-negative,
+ * *db_array has already been opened and fd is the open file descriptor.  We
+ * do this to save time and avoid using up file descriptors for tc=
+ * recursions.
+ *
+ * Getent returns the same success/failure codes as cgetent.  On success, a
+ * pointer to a malloc'ed capability record with all tc= capabilities fully
+ * expanded and its length (not including trailing ASCII NUL) are left in
+ * *cap and *len.
+ *
+ * Basic algorithm:
+ *     + Allocate memory incrementally as needed in chunks of size BFRAG
+ *       for capability buffer.
+ *     + Recurse for each tc=name and interpolate result.  Stop when all
+ *       names interpolated, a name can't be found, or depth exceeds
+ *       MAX_RECURSION.
+ */
+/* coverity[+alloc : arg-*0] */
+static int
+getent(char **cap, size_t *len, const char * const *db_array, int fd,
+    const char *name, int depth, char *nfield)
+{
+#ifndef SMALL
+       DB *capdbp;
+       char pbuf[MAXPATHLEN];
+       char *cbuf;
+       int retval;
+       size_t clen;
+#endif
+       char *record, *newrecord;
+       char *r_end, *rp;       /* pacify gcc */
+       const char * const *db_p;
+       int myfd, eof, foundit;
+       int tc_not_resolved;
+       
+       _DIAGASSERT(cap != NULL);
+       _DIAGASSERT(len != NULL);
+       _DIAGASSERT(db_array != NULL);
+       /* fd may be -1 */
+       _DIAGASSERT(name != NULL);
+       /* nfield may be NULL */
+
+       myfd = 0;
+       rp = NULL;
+
+       /*
+        * Return with ``loop detected'' error if we've recursed more than
+        * MAX_RECURSION times.
+        */
+       if (depth > MAX_RECURSION)
+               return -3;
+
+       /*
+        * Check if we have a top record from cgetset().
+         */
+       if (depth == 0 && toprec != NULL && cgetmatch(toprec, name) == 0) {
+               if ((record = malloc(topreclen + BFRAG)) == NULL) {
+                       errno = ENOMEM;
+                       return -2;
+               }
+               (void)strcpy(record, toprec);   /* XXX: strcpy is safe */
+               db_p = db_array;
+               rp = record + topreclen + 1;
+               r_end = rp + BFRAG;
+               goto tc_exp;
+       }
+       /*
+        * Allocate first chunk of memory.
+        */
+       if ((record = malloc(BFRAG)) == NULL) {
+               errno = ENOMEM;
+               return -2;
+       }
+       r_end = record + BFRAG;
+       foundit = 0;
+       /*
+        * Loop through database array until finding the record.
+        */
+
+       for (db_p = db_array; *db_p != NULL; db_p++) {
+               eof = 0;
+
+               /*
+                * Open database if not already open.
+                */
+
+               if (fd >= 0) {
+                       (void)lseek(fd, (off_t)0, SEEK_SET);
+               } else {
+#ifndef SMALL
+                       (void)snprintf(pbuf, sizeof(pbuf), "%s.db", *db_p);
+                       if (expandtc &&
+                           (capdbp = dbopen(pbuf, O_RDONLY, 0, DB_HASH, 0))
+                            != NULL) {
+                               free(record);
+                               retval = cdbget(capdbp, &record, name);
+                               if (retval < 0) {
+                                       /* no record available */
+                                       (void)capdbp->close(capdbp);
+                                       return retval;
+                               }
+                               /* save the data; close frees it */
+                               clen = strlen(record);
+                               if ((cbuf = malloc(clen + 1)) == NULL) {
+                                       (void)capdbp->close(capdbp);
+                                       errno = ENOMEM;
+                                       return -2;
+                               }
+                               memmove(cbuf, record, clen + 1);
+                               if (capdbp->close(capdbp) < 0) {
+                                       int serrno = errno;
+
+                                       free(cbuf);
+                                       errno = serrno;
+                                       return -2;
+                               }
+                               *len = clen;
+                               *cap = cbuf;
+                               return retval;
+                       } else
+#endif
+                       {
+                               fd = open(*db_p, O_RDONLY, 0);
+                               if (fd < 0) {
+                                       /* No error on unfound file. */
+                                       continue;
+                               }
+                               myfd = 1;
+                       }
+               }
+               /*
+                * Find the requested capability record ...
+                */
+               {
+               char buf[BUFSIZ];
+               char *b_end, *bp, *cp;
+               int c, slash;
+
+               /*
+                * Loop invariants:
+                *      There is always room for one more character in record.
+                *      R_end always points just past end of record.
+                *      Rp always points just past last character in record.
+                *      B_end always points just past last character in buf.
+                *      Bp always points at next character in buf.
+                *      Cp remembers where the last colon was.
+                */
+               b_end = buf;
+               bp = buf;
+               cp = NULL;
+               slash = 0;
+               for (;;) {
+                       /*
+                        * Read in a line implementing (\, newline)
+                        * line continuation.
+                        */
+                       rp = record;
+                       for (;;) {
+                               if (bp >= b_end) {
+                                       int n;
+               
+                                       n = read(fd, buf, sizeof(buf));
+                                       if (n <= 0) {
+                                               if (myfd)
+                                                       (void)close(fd);
+                                               if (n < 0) {
+                                                       int serrno = errno;
+
+                                                       free(record);
+                                                       errno = serrno;
+                                                       return -2;
+                                               } else {
+                                                       fd = -1;
+                                                       eof = 1;
+                                                       break;
+                                               }
+                                       }
+                                       b_end = buf+n;
+                                       bp = buf;
+                               }
+       
+                               c = *bp++;
+                               if (c == '\n') {
+                                       if (slash) {
+                                               slash = 0;
+                                               rp--;
+                                               continue;
+                                       } else
+                                               break;
+                               }
+                               if (slash) {
+                                       slash = 0;
+                                       cp = 0;
+                               }
+                               if (c == ':') {
+                                       /*
+                                        * If the field was `empty' (i.e.
+                                        * contained only white space), back up
+                                        * to the colon (eliminating the
+                                        * field).
+                                        */
+                                       if (cp != NULL)
+                                               rp = cp;
+                                       else
+                                               cp = rp;
+                               } else if (c == '\\') {
+                                       slash = 1;
+                               } else if (c != ' ' && c != '\t') {
+                                       /*
+                                        * Forget where the colon was, as this
+                                        * is not an empty field.
+                                        */
+                                       cp = 0;
+                               }
+                               *rp++ = c;
+
+                               /*
+                                * Enforce loop invariant: if no room 
+                                * left in record buffer, try to get
+                                * some more.
+                                */
+                               if (rp >= r_end) {
+                                       u_int pos;
+                                       size_t newsize;
+
+                                       pos = rp - record;
+                                       newsize = r_end - record + BFRAG;
+                                       newrecord = realloc(record, newsize);
+                                       if (newrecord == NULL) {
+                                               free(record);
+                                               if (myfd)
+                                                       (void)close(fd);
+                                               errno = ENOMEM;
+                                               return -2;
+                                       }
+                                       record = newrecord;
+                                       r_end = record + newsize;
+                                       rp = record + pos;
+                               }
+                       }
+                       /* Eliminate any white space after the last colon. */
+                       if (cp)
+                               rp = cp + 1;
+                       /* Loop invariant lets us do this. */
+                       *rp++ = '\0';
+
+                       /*
+                        * If encountered eof check next file.
+                        */
+                       if (eof)
+                               break;
+                               
+                       /*
+                        * Toss blank lines and comments.
+                        */
+                       if (*record == '\0' || *record == '#')
+                               continue;
+       
+                       /*
+                        * See if this is the record we want ...
+                        */
+                       if (cgetmatch(record, name) == 0)
+                               if (nfield == NULL || !nfcmp(nfield, record)) {
+                                       foundit = 1;
+                                       break;  /* found it! */
+                               }
+               }
+               }
+               if (foundit)
+                       break;
+       }
+
+       if (!foundit)
+               return -1;
+
+       /*
+        * Got the capability record, but now we have to expand all tc=name
+        * references in it ...
+        */
+tc_exp:
+       tc_not_resolved = 0;
+       if (expandtc) {
+               char *newicap, *s;
+               size_t ilen, newilen;
+               int diff, iret, tclen;
+               char *icap, *scan, *tc, *tcstart, *tcend;
+
+               /*
+                * Loop invariants:
+                *      There is room for one more character in record.
+                *      R_end points just past end of record.
+                *      Rp points just past last character in record.
+                *      Scan points at remainder of record that needs to be
+                *      scanned for tc=name constructs.
+                */
+               scan = record;
+               for (;;) {
+                       if ((tc = cgetcap(scan, "tc", '=')) == NULL)
+                               break;
+
+                       /*
+                        * Find end of tc=name and stomp on the trailing `:'
+                        * (if present) so we can use it to call ourselves.
+                        */
+                       s = tc;
+                       for (;;)
+                               if (*s == '\0')
+                                       break;
+                               else
+                                       if (*s++ == ':') {
+                                               *(s - 1) = '\0';
+                                               break;
+                                       }
+                       tcstart = tc - 3;
+                       tclen = s - tcstart;
+                       tcend = s;
+
+                       iret = getent(&icap, &ilen, db_p, fd, tc, depth+1, 
+                                     NULL);
+                       newicap = icap;         /* Put into a register. */
+                       newilen = ilen;
+                       if (iret != 0) {
+                               /* an error */
+                               if (iret < -1) {
+                                       if (myfd)
+                                               (void)close(fd);
+                                       free(record);
+                                       return iret;
+                               }
+                               if (iret == 1)
+                                       tc_not_resolved = 1;
+                               /* couldn't resolve tc */
+                               if (iret == -1) {
+                                       *(s - 1) = ':';                 
+                                       scan = s - 1;
+                                       tc_not_resolved = 1;
+                                       continue;
+                                       
+                               }
+                       }
+                       /* not interested in name field of tc'ed record */
+                       s = newicap;
+                       for (;;)
+                               if (*s == '\0')
+                                       break;
+                               else if (*s++ == ':')
+                                       break;
+                       newilen -= s - newicap;
+                       newicap = s;
+
+                       /* make sure interpolated record is `:'-terminated */
+                       s += newilen;
+                       if (*(s - 1) != ':') {
+                               *s = ':';       /* overwrite NUL with : */
+                               newilen++;
+                       }
+
+                       /*
+                        * Make sure there's enough room to insert the
+                        * new record.
+                        */
+                       diff = newilen - tclen;
+                       if (diff >= r_end - rp) {
+                               u_int pos, tcpos, tcposend;
+                               size_t newsize;
+
+                               pos = rp - record;
+                               newsize = r_end - record + diff + BFRAG;
+                               tcpos = tcstart - record;
+                               tcposend = tcend - record;
+                               newrecord = realloc(record, newsize);
+                               if (newrecord == NULL) {
+                                       free(record);
+                                       if (myfd)
+                                               (void)close(fd);
+                                       free(icap);
+                                       errno = ENOMEM;
+                                       return -2;
+                               }
+                               record = newrecord;
+                               r_end = record + newsize;
+                               rp = record + pos;
+                               tcstart = record + tcpos;
+                               tcend = record + tcposend;
+                       }
+
+                       /*
+                        * Insert tc'ed record into our record.
+                        */
+                       s = tcstart + newilen;
+                       memmove(s, tcend,  (size_t)(rp - tcend));
+                       memmove(tcstart, newicap, newilen);
+                       rp += diff;
+                       free(icap);
+
+                       /*
+                        * Start scan on `:' so next cgetcap works properly
+                        * (cgetcap always skips first field).
+                        */
+                       scan = s - 1;
+               }
+       
+       }
+       /*
+        * Close file (if we opened it), give back any extra memory, and
+        * return capability, length and success.
+        */
+       if (myfd)
+               (void)close(fd);
+       *len = rp - record - 1; /* don't count NUL */
+       if (r_end > rp) {
+               if ((newrecord = 
+                    realloc(record, (size_t)(rp - record))) == NULL) {
+                       free(record);
+                       errno = ENOMEM;
+                       return -2;
+               }
+               record = newrecord;
+       }
+               
+       *cap = record;
+       if (tc_not_resolved)
+               return 1;
+       return 0;
+}      
+
+#ifndef SMALL
+static int
+cdbget(DB *capdbp, char **bp, const char *name)
+{
+       DBT key;
+       DBT data;
+
+       _DIAGASSERT(capdbp != NULL);
+       _DIAGASSERT(bp != NULL);
+       _DIAGASSERT(name != NULL);
+
+       key.data = __UNCONST(name);
+       key.size = strlen(name);
+
+       for (;;) {
+               /* Get the reference. */
+               switch(capdbp->get(capdbp, &key, &data, 0)) {
+               case -1:
+                       return -2;
+               case 1:
+                       return -1;
+               }
+
+               /* If not an index to another record, leave. */
+               if (((char *)data.data)[0] != SHADOW)
+                       break;
+
+               key.data = (char *)data.data + 1;
+               key.size = data.size - 1;
+       }
+       
+       *bp = (char *)data.data + 1;
+       return ((char *)(data.data))[0] == TCERR ? 1 : 0;
+}
+#endif
+
+/*
+ * Cgetmatch will return 0 if name is one of the names of the capability
+ * record buf, -1 if not.
+ */
+int
+cgetmatch(const char *buf, const char *name)
+{
+       const char *np, *bp;
+
+       _DIAGASSERT(buf != NULL);
+       _DIAGASSERT(name != NULL);
+
+       /*
+        * Start search at beginning of record.
+        */
+       bp = buf;
+       for (;;) {
+               /*
+                * Try to match a record name.
+                */
+               np = name;
+               for (;;)
+                       if (*np == '\0') {
+                               if (*bp == '|' || *bp == ':' || *bp == '\0')
+                                       return 0;
+                               else
+                                       break;
+                       } else if (*bp++ != *np++)
+                               break;
+
+               /*
+                * Match failed, skip to next name in record.
+                */
+               if (bp > buf)
+                       bp--;   /* a '|' or ':' may have stopped the match */
+               else
+                       return -1;
+               for (;;)
+                       if (*bp == '\0' || *bp == ':')
+                               return -1;      /* match failed totally */
+                       else if (*bp++ == '|')
+                               break;          /* found next name */
+       }
+}
+
+int
+cgetfirst(char **buf, const char * const *db_array)
+{
+
+       _DIAGASSERT(buf != NULL);
+       _DIAGASSERT(db_array != NULL);
+
+       (void)cgetclose();
+       return cgetnext(buf, db_array);
+}
+
+static FILE *pfp;
+static int slash;
+static const char * const *dbp;
+
+int
+cgetclose(void)
+{
+       if (pfp != NULL) {
+               (void)fclose(pfp);
+               pfp = NULL;
+       }
+       dbp = NULL;
+       gottoprec = 0;
+       slash = 0;
+       return 0;
+}
+
+/*
+ * Cgetnext() gets either the first or next entry in the logical database 
+ * specified by db_array.  It returns 0 upon completion of the database, 1
+ * upon returning an entry with more remaining, and -1 if an error occurs.
+ */
+/* coverity[+alloc : arg-*0] */
+int
+cgetnext(char **bp, const char * const *db_array)
+{
+       size_t len = 0;
+       int status, done;
+       char *cp, *line, *rp, *np, buf[BSIZE], nbuf[BSIZE];
+       size_t dummy;
+
+       _DIAGASSERT(bp != NULL);
+       _DIAGASSERT(db_array != NULL);
+
+       if (dbp == NULL)
+               dbp = db_array;
+
+       if (pfp == NULL && (pfp = fopen(*dbp, "r")) == NULL) {
+               (void)cgetclose();
+               return -1;
+       }
+       for (;;) {
+               if (toprec != NULL && !gottoprec) {
+                       gottoprec = 1;
+                       line = toprec;
+               } else {
+                       line = fgetln(pfp, &len);
+                       if (line == NULL) {
+                               if (pfp == NULL)
+                                       return -1;
+                               if (ferror(pfp)) {
+                                       (void)cgetclose();
+                                       return -1;
+                               } else {
+                                       (void)fclose(pfp);
+                                       pfp = NULL;
+                                       if (*++dbp == NULL) {
+                                               (void)cgetclose();
+                                               return 0;
+                                       } else if ((pfp =
+                                           fopen(*dbp, "r")) == NULL) {
+                                               (void)cgetclose();
+                                               return -1;
+                                       } else
+                                               continue;
+                               }
+                       } else
+                               line[len - 1] = '\0';
+                       if (len == 1) {
+                               slash = 0;
+                               continue;
+                       }
+                       if (isspace((unsigned char)*line) ||
+                           *line == ':' || *line == '#' || slash) {
+                               if (line[len - 2] == '\\')
+                                       slash = 1;
+                               else
+                                       slash = 0;
+                               continue;
+                       }
+                       if (line[len - 2] == '\\')
+                               slash = 1;
+                       else
+                               slash = 0;
+               }                       
+
+
+               /* 
+                * Line points to a name line.
+                */
+               if (len > sizeof(nbuf))
+                       return -1;
+               done = 0;
+               np = nbuf;
+               for (;;) {
+                       for (cp = line; *cp != '\0'; cp++) {
+                               if (*cp == ':') {
+                                       *np++ = ':';
+                                       done = 1;
+                                       break;
+                               }
+                               if (*cp == '\\')
+                                       break;
+                               *np++ = *cp;
+                       }
+                       if (done) {
+                               *np = '\0';
+                               break;
+                       } else { /* name field extends beyond the line */
+                               line = fgetln(pfp, &len);
+                               if (line == NULL && pfp) {
+                                       if (ferror(pfp)) {
+                                               (void)cgetclose();
+                                               return -1;
+                                       }
+                                       (void)fclose(pfp);
+                                       pfp = NULL;
+                                       *np = '\0';
+                                       break;
+                               } else
+                                       line[len - 1] = '\0';
+                       }
+               }
+               if (len > sizeof(buf))
+                       return -1;
+               rp = buf;
+               for (cp = nbuf; *cp != '\0'; cp++)
+                       if (*cp == '|' || *cp == ':')
+                               break;
+                       else
+                               *rp++ = *cp;
+
+               *rp = '\0';
+               /* 
+                * XXX 
+                * Last argument of getent here should be nbuf if we want true
+                * sequential access in the case of duplicates.  
+                * With NULL, getent will return the first entry found
+                * rather than the duplicate entry record.  This is a 
+                * matter of semantics that should be resolved.
+                */
+               status = getent(bp, &dummy, db_array, -1, buf, 0, NULL);
+               if (status == -2 || status == -3)
+                       (void)cgetclose();
+
+               return status + 1;
+       }
+       /* NOTREACHED */
+}
+
+/*
+ * Cgetstr retrieves the value of the string capability cap from the
+ * capability record pointed to by buf.  A pointer to a decoded, NUL
+ * terminated, malloc'd copy of the string is returned in the char *
+ * pointed to by str.  The length of the string not including the trailing
+ * NUL is returned on success, -1 if the requested string capability
+ * couldn't be found, -2 if a system error was encountered (storage
+ * allocation failure).
+ */
+int
+cgetstr(char *buf, const char *cap, char **str)
+{
+       u_int m_room;
+       const char *bp;
+       char *mp;
+       int len;
+       char *mem, *newmem;
+
+       _DIAGASSERT(buf != NULL);
+       _DIAGASSERT(cap != NULL);
+       _DIAGASSERT(str != NULL);
+
+       /*
+        * Find string capability cap
+        */
+       bp = cgetcap(buf, cap, '=');
+       if (bp == NULL)
+               return -1;
+
+       /*
+        * Conversion / storage allocation loop ...  Allocate memory in
+        * chunks SFRAG in size.
+        */
+       if ((mem = malloc(SFRAG)) == NULL) {
+               errno = ENOMEM;
+               return -2;      /* couldn't even allocate the first fragment */
+       }
+       m_room = SFRAG;
+       mp = mem;
+
+       while (*bp != ':' && *bp != '\0') {
+               /*
+                * Loop invariants:
+                *      There is always room for one more character in mem.
+                *      Mp always points just past last character in mem.
+                *      Bp always points at next character in buf.
+                */
+               if (*bp == '^') {
+                       bp++;
+                       if (*bp == ':' || *bp == '\0')
+                               break;  /* drop unfinished escape */
+                       *mp++ = *bp++ & 037;
+               } else if (*bp == '\\') {
+                       bp++;
+                       if (*bp == ':' || *bp == '\0')
+                               break;  /* drop unfinished escape */
+                       if ('0' <= *bp && *bp <= '7') {
+                               int n, i;
+
+                               n = 0;
+                               i = 3;  /* maximum of three octal digits */
+                               do {
+                                       n = n * 8 + (*bp++ - '0');
+                               } while (--i && '0' <= *bp && *bp <= '7');
+                               *mp++ = n;
+                       }
+                       else switch (*bp++) {
+                               case 'b': case 'B':
+                                       *mp++ = '\b';
+                                       break;
+                               case 't': case 'T':
+                                       *mp++ = '\t';
+                                       break;
+                               case 'n': case 'N':
+                                       *mp++ = '\n';
+                                       break;
+                               case 'f': case 'F':
+                                       *mp++ = '\f';
+                                       break;
+                               case 'r': case 'R':
+                                       *mp++ = '\r';
+                                       break;
+                               case 'e': case 'E':
+                                       *mp++ = ESC;
+                                       break;
+                               case 'c': case 'C':
+                                       *mp++ = ':';
+                                       break;
+                               default:
+                                       /*
+                                        * Catches '\', '^', and
+                                        *  everything else.
+                                        */
+                                       *mp++ = *(bp-1);
+                                       break;
+                       }
+               } else
+                       *mp++ = *bp++;
+               m_room--;
+
+               /*
+                * Enforce loop invariant: if no room left in current
+                * buffer, try to get some more.
+                */
+               if (m_room == 0) {
+                       size_t size = mp - mem;
+
+                       if ((newmem = realloc(mem, size + SFRAG)) == NULL) {
+                               free(mem);
+                               return -2;
+                       }
+                       mem = newmem;
+                       m_room = SFRAG;
+                       mp = mem + size;
+               }
+       }
+       *mp++ = '\0';   /* loop invariant let's us do this */
+       m_room--;
+       len = mp - mem - 1;
+
+       /*
+        * Give back any extra memory and return value and success.
+        */
+       if (m_room != 0) {
+               if ((newmem = realloc(mem, (size_t)(mp - mem))) == NULL) {
+                       free(mem);
+                       return -2;
+               }
+               mem = newmem;
+       }
+       *str = mem;
+       return len;
+}
+
+/*
+ * Cgetustr retrieves the value of the string capability cap from the
+ * capability record pointed to by buf.  The difference between cgetustr()
+ * and cgetstr() is that cgetustr does not decode escapes but rather treats
+ * all characters literally.  A pointer to a  NUL terminated malloc'd 
+ * copy of the string is returned in the char pointed to by str.  The 
+ * length of the string not including the trailing NUL is returned on success,
+ * -1 if the requested string capability couldn't be found, -2 if a system 
+ * error was encountered (storage allocation failure).
+ */
+int
+cgetustr(char *buf, const char *cap, char **str)
+{
+       u_int m_room;
+       const char *bp;
+       char *mp;
+       int len;
+       char *mem, *newmem;
+
+       _DIAGASSERT(buf != NULL);
+       _DIAGASSERT(cap != NULL);
+       _DIAGASSERT(str != NULL);
+
+       /*
+        * Find string capability cap
+        */
+       if ((bp = cgetcap(buf, cap, '=')) == NULL)
+               return -1;
+
+       /*
+        * Conversion / storage allocation loop ...  Allocate memory in
+        * chunks SFRAG in size.
+        */
+       if ((mem = malloc(SFRAG)) == NULL) {
+               errno = ENOMEM;
+               return -2;      /* couldn't even allocate the first fragment */
+       }
+       m_room = SFRAG;
+       mp = mem;
+
+       while (*bp != ':' && *bp != '\0') {
+               /*
+                * Loop invariants:
+                *      There is always room for one more character in mem.
+                *      Mp always points just past last character in mem.
+                *      Bp always points at next character in buf.
+                */
+               *mp++ = *bp++;
+               m_room--;
+
+               /*
+                * Enforce loop invariant: if no room left in current
+                * buffer, try to get some more.
+                */
+               if (m_room == 0) {
+                       size_t size = mp - mem;
+
+                       if ((newmem = realloc(mem, size + SFRAG)) == NULL) {
+                               free(mem);
+                               return -2;
+                       }
+                       mem = newmem;
+                       m_room = SFRAG;
+                       mp = mem + size;
+               }
+       }
+       *mp++ = '\0';   /* loop invariant let's us do this */
+       m_room--;
+       len = mp - mem - 1;
+
+       /*
+        * Give back any extra memory and return value and success.
+        */
+       if (m_room != 0) {
+               if ((newmem = realloc(mem, (size_t)(mp - mem))) == NULL) {
+                       free(mem);
+                       return -2;
+               }
+               mem = newmem;
+       }
+       *str = mem;
+       return len;
+}
+
+/*
+ * Cgetnum retrieves the value of the numeric capability cap from the
+ * capability record pointed to by buf.  The numeric value is returned in
+ * the long pointed to by num.  0 is returned on success, -1 if the requested
+ * numeric capability couldn't be found.
+ */
+int
+cgetnum(char *buf, const char *cap, long *num)
+{
+       long n;
+       int base, digit;
+       const char *bp;
+
+       _DIAGASSERT(buf != NULL);
+       _DIAGASSERT(cap != NULL);
+       _DIAGASSERT(num != NULL);
+
+       /*
+        * Find numeric capability cap
+        */
+       bp = cgetcap(buf, cap, '#');
+       if (bp == NULL)
+               return -1;
+
+       /*
+        * Look at value and determine numeric base:
+        *      0x... or 0X...  hexadecimal,
+        * else 0...            octal,
+        * else                 decimal.
+        */
+       if (*bp == '0') {
+               bp++;
+               if (*bp == 'x' || *bp == 'X') {
+                       bp++;
+                       base = 16;
+               } else
+                       base = 8;
+       } else
+               base = 10;
+
+       /*
+        * Conversion loop ...
+        */
+       n = 0;
+       for (;;) {
+               if ('0' <= *bp && *bp <= '9')
+                       digit = *bp - '0';
+               else if ('a' <= *bp && *bp <= 'f')
+                       digit = 10 + *bp - 'a';
+               else if ('A' <= *bp && *bp <= 'F')
+                       digit = 10 + *bp - 'A';
+               else
+                       break;
+
+               if (digit >= base)
+                       break;
+
+               n = n * base + digit;
+               bp++;
+       }
+
+       /*
+        * Return value and success.
+        */
+       *num = n;
+       return 0;
+}
+
+
+/*
+ * Compare name field of record.
+ */
+static int
+nfcmp(char *nf, char *rec)
+{
+       char *cp, tmp;
+       int ret;
+
+       _DIAGASSERT(nf != NULL);
+       _DIAGASSERT(rec != NULL);
+
+       for (cp = rec; *cp != ':'; cp++)
+               continue;
+       
+       tmp = *(cp + 1);
+       *(cp + 1) = '\0';
+       ret = strcmp(nf, rec);
+       *(cp + 1) = tmp;
+
+       return ret;
+}
diff --git a/lib/nbsd_libc/gen/getcwd.3 b/lib/nbsd_libc/gen/getcwd.3
new file mode 100644 (file)
index 0000000..712d5a9
--- /dev/null
@@ -0,0 +1,172 @@
+.\"    $NetBSD: getcwd.3,v 1.18 2010/04/29 06:54:26 jruoho Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getcwd.3   8.2 (Berkeley) 12/11/93
+.\"
+.Dd April 29, 2010
+.Dt GETCWD 3
+.Os
+.Sh NAME
+.Nm getcwd ,
+.Nm getwd
+.Nd get working directory pathname
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft char *
+.Fn getcwd "char *buf" "size_t size"
+.Ft char *
+.Fn getwd "char *buf"
+.Sh DESCRIPTION
+The
+.Fn getcwd
+function copies the absolute pathname of the current working directory
+into the memory referenced by
+.Fa buf
+and returns a pointer to
+.Fa buf .
+The
+.Fa size
+argument is the size, in bytes, of the array referenced by
+.Fa buf .
+.Pp
+If
+.Fa buf
+is
+.Dv NULL ,
+space is allocated as necessary to store the pathname.
+This space may later be
+.Xr free 3 Ns 'd .
+.Pp
+The function
+.Fn getwd
+is a compatibility routine which calls
+.Fn getcwd
+with its
+.Fa buf
+argument and a size of
+.Dv MAXPATHLEN
+(as defined in the include
+file
+.In sys/param.h ) .
+Obviously,
+.Fa buf
+should be at least
+.Dv MAXPATHLEN
+bytes in length.
+.Pp
+These routines have traditionally been used by programs to save the
+name of a working directory for the purpose of returning to it.
+A much faster and less error-prone method of accomplishing this is to
+open the current directory
+.Pq Ql \&.
+and use the
+.Xr fchdir 2
+function to return.
+.Sh RETURN VALUES
+Upon successful completion, a pointer to the pathname is returned.
+Otherwise a
+.Dv NULL
+pointer is returned and the global variable
+.Va errno
+is set to indicate the error.
+In addition,
+.Fn getwd
+copies the error message associated with
+.Va errno
+into the memory referenced by
+.Fa buf .
+.Sh ERRORS
+The
+.Fn getcwd
+function
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+Read or search permission was denied for a component of the pathname.
+.It Bq Er EINVAL
+The
+.Fa size
+argument is zero.
+.It Bq Er ENOENT
+A component of the pathname no longer exists.
+.It Bq Er ENOMEM
+Insufficient memory is available.
+.It Bq Er ERANGE
+The
+.Fa size
+argument is greater than zero but smaller than the length of the pathname
+plus 1.
+.El
+.Sh SEE ALSO
+.Xr chdir 2 ,
+.Xr fchdir 2 ,
+.Xr malloc 3 ,
+.Xr strerror 3
+.Sh STANDARDS
+The
+.Fn getwd
+and
+.Fn getcwd
+functions conform to
+.St -p1003.1-90 .
+The
+.St -p1003.1-2004
+revision marked
+.Fn getwd
+as legacy and recommended the use of
+.Fn getcwd
+instead.
+The
+.St -p1003.1-2008
+revision removed
+.Fn getwd
+from the specification.
+.Pp
+The ability to specify a
+.Dv NULL
+pointer and have
+.Fn getcwd
+allocate memory as necessary is an extension.
+.Sh HISTORY
+The
+.Fn getwd
+function appeared in
+.Bx 4.0 .
+.Sh SECURITY CONSIDERATIONS
+As
+.Fn getwd
+does not know the length of the supplied buffer, it is possible
+for a long (but valid) path to overflow the buffer and provide
+a means for an attacker to exploit the caller.
+.Fn getcwd
+should be used in place of
+.Fn getwd
+(the latter is only provided for compatibility purposes).
diff --git a/lib/nbsd_libc/gen/getcwd.c b/lib/nbsd_libc/gen/getcwd.c
new file mode 100644 (file)
index 0000000..ed12f71
--- /dev/null
@@ -0,0 +1,248 @@
+/*     $NetBSD: getcwd.c,v 1.47 2011/01/20 02:57:00 christos Exp $     */
+
+/*
+ * Copyright (c) 1989, 1991, 1993, 1995
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Jan-Simon Pendry.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getcwd.c   8.5 (Berkeley) 2/7/95";
+#else
+__RCSID("$NetBSD: getcwd.c,v 1.47 2011/01/20 02:57:00 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "extern.h"
+
+#ifdef __weak_alias
+__weak_alias(getcwd,_sys_getcwd)
+__weak_alias(_getcwd,_sys_getcwd)
+__weak_alias(realpath,_realpath)
+
+#if defined(_FORTIFY_SOURCE) && !defined(__lint__)
+#undef getcwd
+#define getcwd _sys_getcwd
+#endif
+
+#endif
+
+/*
+ * char *realpath(const char *path, char resolved[MAXPATHLEN]);
+ *
+ * Find the real name of path, by removing all ".", ".." and symlink
+ * components.  Returns (resolved) on success, or (NULL) on failure,
+ * in which case the path which caused trouble is left in (resolved).
+ */
+char *
+realpath(const char *path, char *resolved)
+{
+       struct stat sb;
+       int idx = 0, n, nlnk = 0;
+       const char *q;
+       char *p, wbuf[2][MAXPATHLEN];
+       size_t len;
+
+       _DIAGASSERT(resolved != NULL);
+
+       /* POSIX sez we must test for this */
+       if (path == NULL) {
+               errno = EINVAL;
+               return NULL;
+       }
+
+       /*
+        * Build real path one by one with paying an attention to .,
+        * .. and symbolic link.
+        */
+
+       /*
+        * `p' is where we'll put a new component with prepending
+        * a delimiter.
+        */
+       p = resolved;
+
+       if (*path == 0) {
+               *p = 0;
+               errno = ENOENT;
+               return (NULL);
+       }
+
+       /* If relative path, start from current working directory. */
+       if (*path != '/') {
+               /* check for resolved pointer to appease coverity */
+               if (resolved && getcwd(resolved, MAXPATHLEN) == NULL) {
+                       p[0] = '.';
+                       p[1] = 0;
+                       return (NULL);
+               }
+               len = strlen(resolved);
+               if (len > 1)
+                       p += len;
+       }
+
+loop:
+       /* Skip any slash. */
+       while (*path == '/')
+               path++;
+
+       if (*path == 0) {
+               if (p == resolved)
+                       *p++ = '/';
+               *p = 0;
+               return (resolved);
+       }
+
+       /* Find the end of this component. */
+       q = path;
+       do
+               q++;
+       while (*q != '/' && *q != 0);
+
+       /* Test . or .. */
+       if (path[0] == '.') {
+               if (q - path == 1) {
+                       path = q;
+                       goto loop;
+               }
+               if (path[1] == '.' && q - path == 2) {
+                       /* Trim the last component. */
+                       if (p != resolved)
+                               while (*--p != '/')
+                                       ;
+                       path = q;
+                       goto loop;
+               }
+       }
+
+       /* Append this component. */
+       if (p - resolved + 1 + q - path + 1 > MAXPATHLEN) {
+               errno = ENAMETOOLONG;
+               if (p == resolved)
+                       *p++ = '/';
+               *p = 0;
+               return (NULL);
+       }
+       p[0] = '/';
+       memcpy(&p[1], path,
+           /* LINTED We know q > path. */
+           q - path);
+       p[1 + q - path] = 0;
+
+       /*
+        * If this component is a symlink, toss it and prepend link
+        * target to unresolved path.
+        */
+       if (lstat(resolved, &sb) == -1) {
+               return (NULL);
+       }
+       if (S_ISLNK(sb.st_mode)) {
+               if (nlnk++ >= MAXSYMLINKS) {
+                       errno = ELOOP;
+                       return (NULL);
+               }
+               n = readlink(resolved, wbuf[idx], sizeof(wbuf[0]) - 1);
+               if (n < 0)
+                       return (NULL);
+               if (n == 0) {
+                       errno = ENOENT;
+                       return (NULL);
+               }
+
+               /* Append unresolved path to link target and switch to it. */
+               if (n + (len = strlen(q)) + 1 > sizeof(wbuf[0])) {
+                       errno = ENAMETOOLONG;
+                       return (NULL);
+               }
+               memcpy(&wbuf[idx][n], q, len + 1);
+               path = wbuf[idx];
+               idx ^= 1;
+
+               /* If absolute symlink, start from root. */
+               if (*path == '/')
+                       p = resolved;
+               goto loop;
+       }
+       if (*q == '/' && !S_ISDIR(sb.st_mode)) {
+               errno = ENOTDIR;
+               return (NULL);
+       }
+
+       /* Advance both resolved and unresolved path. */
+       p += 1 + q - path;
+       path = q;
+       goto loop;
+}
+
+char *
+getcwd(char *pt, size_t size)
+{
+       char *npt;
+
+       /*
+        * If a buffer is specified, the size has to be non-zero.
+        */
+       if (pt != NULL) {
+               if (size == 0) {
+                       /* __getcwd(pt, 0) results ERANGE. */
+                       errno = EINVAL;
+                       return (NULL);
+               }
+               if (__getcwd(pt, size) >= 0)
+                       return (pt);
+               return (NULL);
+       }
+
+       /*
+        * If no buffer specified by the user, allocate one as necessary.
+        */
+       size = 1024 >> 1;
+       do {
+               if ((npt = realloc(pt, size <<= 1)) == NULL)
+                       break;
+               pt = npt;
+               if (__getcwd(pt, size) >= 0)
+                       return (pt);
+       } while (size <= MAXPATHLEN * 4 && errno == ERANGE);
+
+       free(pt);
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/gen/getdevmajor.3 b/lib/nbsd_libc/gen/getdevmajor.3
new file mode 100644 (file)
index 0000000..97db9b0
--- /dev/null
@@ -0,0 +1,118 @@
+.\"    $NetBSD: getdevmajor.3,v 1.5 2009/03/24 22:34:54 drochner Exp $
+.\"
+.\" Copyright (c) 2004 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Andrew Brown.
+.\"
+.\" 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. 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.
+.\"
+.Dd January 20, 2009
+.Dt GETDEVMAJOR 3
+.Os
+.Sh NAME
+.Nm getdevmajor
+.Nd get block or character device major number
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.In sys/stat.h
+.Ft devmajor_t
+.Fn getdevmajor "const char *name" "mode_t type"
+.Sh DESCRIPTION
+The
+.Fn getdevmajor
+function returns the major device number of the block or character
+device specified by
+.Ar name
+and a file type matching the one encoded in
+.Fa type
+which must be one of
+.Dv S_IFBLK
+or
+.Dv S_IFCHR .
+.Sh RETURN VALUES
+If no device matches the specified values, no information is
+available, or an error occurs,
+.Dv NODEVMAJOR
+is returned and
+.Va errno
+is set to indicate the error.
+.Sh EXAMPLES
+To retrieve the major number for
+.Xr pty 4
+slave devices (aka pts devices):
+.Bd -literal -offset indent
+#include \*[Lt]stdlib.h\*[Gt]
+#include \*[Lt]sys/stat.h\*[Gt]
+.sp
+devmajor_t pts;
+pts = getdevmajor("pts", S_IFCHR);
+.Ed
+.Pp
+To retrieve the major numbers for the block and character
+.Xr wd 4
+devices:
+.Bd -literal -offset indent
+#include \*[Lt]stdlib.h\*[Gt]
+#include \*[Lt]sys/stat.h\*[Gt]
+.sp
+devmajor_t c, b;
+c = getdevmajor("wd", S_IFCHR);
+b = getdevmajor("wd", S_IFBLK);
+.Ed
+.Sh ERRORS
+The
+.Fn getdevmajor
+function may fail and set
+.Va errno
+for any of the errors specified for the library functions
+.Xr malloc 3
+and
+.Xr sysctlbyname 3 .
+In addition, the following errors may be reported:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The value of the
+.Fa type
+argument is not
+.Dv S_IFCHR
+or
+.Dv S_IFBLK .
+.It Bq Er ENOENT
+The named device is not found.
+.El
+.Sh SEE ALSO
+.Xr stat 2 ,
+.Xr devname 3 ,
+.Xr malloc 3 ,
+.Xr sysctlbyname 3
+.Sh HISTORY
+The
+.Fn getdevmajor
+function call appeared in
+.Nx 3.0 .
diff --git a/lib/nbsd_libc/gen/getdevmajor.c b/lib/nbsd_libc/gen/getdevmajor.c
new file mode 100644 (file)
index 0000000..b946694
--- /dev/null
@@ -0,0 +1,110 @@
+/*     $NetBSD: getdevmajor.c,v 1.5 2009/01/20 20:08:12 drochner Exp $ */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Andrew Brown.
+ *
+ * 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. 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getdevmajor.c,v 1.5 2009/01/20 20:08:12 drochner Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/param.h>
+#include <sys/sysctl.h>
+
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(getdevmajor,_getdevmajor)
+#endif
+
+/*
+ * XXX temporary alias because getdevmajor() was renamed
+ * in -current for some time
+ */
+dev_t __getdevmajor50(const char *, mode_t);
+dev_t
+__getdevmajor50(const char *name, mode_t type)
+{
+
+       return (dev_t)getdevmajor(name, type);
+}
+
+devmajor_t
+getdevmajor(const char *name, mode_t type)
+{
+       struct kinfo_drivers kd[200], *kdp = &kd[0];
+       int rc, i;
+       size_t sz = sizeof(kd);
+       devmajor_t n = NODEVMAJOR;
+
+       if (type != S_IFCHR && type != S_IFBLK) {
+               errno = EINVAL;
+               return n;
+       }
+
+       do {
+               rc = sysctlbyname("kern.drivers", kdp, &sz, NULL, 0);
+               if (rc == -1) {
+                       if (errno != ENOMEM)
+                               goto out;
+                       if (kdp != &kd[0])
+                               free(kdp);
+                       if ((kdp = malloc(sz)) == NULL)
+                               return n;
+               }
+       } while (rc == -1);
+
+       rc = sz / sizeof(*kdp);
+
+       for (i = 0; i < rc; i++) {
+               if (strcmp(name, kdp[i].d_name) == 0) {
+                       if (type == S_IFCHR)
+                               n = kdp[i].d_cmajor;
+                       else
+                               n = kdp[i].d_bmajor;
+                       break;
+               }
+       }
+       if (i >= rc)
+               errno = ENOENT;
+
+  out:
+       if (kdp != &kd[0])
+               free(kdp);
+
+       return n;
+}
diff --git a/lib/nbsd_libc/gen/getdiskbyname.3 b/lib/nbsd_libc/gen/getdiskbyname.3
new file mode 100644 (file)
index 0000000..93c01e4
--- /dev/null
@@ -0,0 +1,105 @@
+.\"    $NetBSD: getdiskbyname.3,v 1.13 2009/08/19 15:47:39 joerg Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getdiskbyname.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt GETDISKBYNAME 3
+.Os
+.Sh NAME
+.Nm getdiskbyname ,
+.Nm setdisktab
+.Nd get generic disk description by its name
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/disklabel.h
+.In disktab.h
+.Ft int
+.Fn setdisktab "char *name"
+.Ft struct disklabel *
+.Fn getdiskbyname "const char *name"
+.Sh DESCRIPTION
+The
+.Fn getdiskbyname
+function
+takes a disk name (e.g.
+.Ql rm03 )
+and returns a prototype disk label
+describing its geometry information and the standard
+disk partition tables.
+All information is obtained from the
+.Xr disktab 5
+file.
+.Pp
+The
+.Fn setdisktab
+function changes the default
+.Sy disktab
+file name from
+.Pa /etc/disktab
+.Pq aka Dv _PATH_DISKTAB
+to
+.Fa name .
+.Sh RETURN VALUES
+.Fn getdiskbyname
+returns a null pointer if the entry is not found in the current
+.Pa disktab
+file.
+.Pp
+.Fn setdisktab
+returns 0 on success and \-1 if
+.Fa name
+is a null pointer or points to an empty string.
+.Sh FILES
+.Bl -tag -width /etc/disktab -compact
+.It Pa /etc/disktab
+the default database of disk types.
+.El
+.Sh SEE ALSO
+.Xr disklabel 5 ,
+.Xr disktab 5 ,
+.Xr disklabel 8
+.Sh HISTORY
+The
+.Fn getdiskbyname
+function appeared in
+.Bx 4.3 .
+.Pp
+The
+.Fn setdisktab
+function appeared in
+.Nx 1.4 .
+.Sh BUGS
+The
+.Fn getdiskbyname
+function leaves its results in an internal static object and returns a
+pointer to that object.
+Subsequent calls will modify the same object.
diff --git a/lib/nbsd_libc/gen/getdomainname.3 b/lib/nbsd_libc/gen/getdomainname.3
new file mode 100644 (file)
index 0000000..a6f4888
--- /dev/null
@@ -0,0 +1,99 @@
+.\"    $NetBSD: getdomainname.3,v 1.15 2003/08/07 16:42:49 agc Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)gethostname.3      8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 6, 1994
+.Dt GETDOMAINNAME 3
+.Os
+.Sh NAME
+.Nm getdomainname ,
+.Nm setdomainname
+.Nd get/set domain name of current host
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn getdomainname "char *name" "size_t namelen"
+.Ft int
+.Fn setdomainname "const char *name" "size_t namelen"
+.Sh DESCRIPTION
+.Fn getdomainname
+returns the standard domain name for the current processor, as
+previously set by
+.Fn setdomainname .
+The parameter
+.Fa namelen
+specifies the size of the
+.Fa name
+array.
+The returned name is null-terminated unless insufficient
+space is provided.
+.Pp
+.Fn setdomainname
+sets the domain name of the host machine to be
+.Fa name ,
+which has length
+.Fa namelen .
+This call is restricted to the super-user and
+is normally used only when the system is bootstrapped.
+.Sh RETURN VALUES
+If the call succeeds a value of 0 is returned.
+If the call fails, a value of \-1 is returned and an error code is
+placed in the global location
+.Va errno .
+.Sh ERRORS
+The following errors may be returned by these calls:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+The
+.Fa name
+or
+.Fa namelen
+parameter gave an
+invalid address.
+.It Bq Er EPERM
+The caller tried to set the domain name and was not the super-user.
+.El
+.Sh SEE ALSO
+.Xr gethostid 3 ,
+.Xr gethostname 3 ,
+.Xr sysctl 3
+.Sh HISTORY
+The
+.Nm
+function call appeared in
+.Bx 4.2 .
+.Sh BUGS
+Domain names are limited to
+.Dv MAXHOSTNAMELEN
+(from
+.Ao Pa sys/param.h Ac )
+characters including null-termination, currently 256.
diff --git a/lib/nbsd_libc/gen/getdomainname.c b/lib/nbsd_libc/gen/getdomainname.c
new file mode 100644 (file)
index 0000000..0832218
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: getdomainname.c,v 1.12 2003/08/07 16:42:49 agc Exp $   */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)gethostname.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getdomainname.c,v 1.12 2003/08/07 16:42:49 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/sysctl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(getdomainname,_getdomainname)
+#endif
+
+int
+getdomainname(name, namelen)
+       char *name;
+       size_t namelen;
+{
+       int mib[2];
+       size_t size;
+       int olderrno;
+
+       _DIAGASSERT(name != NULL);
+
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_DOMAINNAME;
+       size = namelen;
+       olderrno = errno;
+       if (sysctl(mib, 2, name, &size, NULL, 0) == -1) {
+               if (errno == ENOMEM) {
+                       errno = olderrno;
+                       return (0);
+               }
+               return (-1);
+       }
+
+       return (0);
+}
diff --git a/lib/nbsd_libc/gen/getfsent.3 b/lib/nbsd_libc/gen/getfsent.3
new file mode 100644 (file)
index 0000000..685a6c7
--- /dev/null
@@ -0,0 +1,148 @@
+.\"    $NetBSD: getfsent.3,v 1.11 2010/03/22 19:30:53 joerg Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getfsent.3 8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt GETFSENT 3
+.Os
+.Sh NAME
+.Nm getfsent ,
+.Nm getfsspec ,
+.Nm getfsfile ,
+.Nm setfsent ,
+.Nm endfsent
+.Nd get file system descriptor file entry
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In fstab.h
+.Ft struct fstab *
+.Fn getfsent void
+.Ft struct fstab *
+.Fn getfsspec "const char *spec"
+.Ft struct fstab *
+.Fn getfsfile "const char *file"
+.Ft int
+.Fn setfsent void
+.Ft void
+.Fn endfsent void
+.Sh DESCRIPTION
+The
+.Fn getfsent ,
+.Fn getfsspec ,
+and
+.Fn getfsfile
+functions
+each return a pointer to an object with the following structure
+containing the broken-out fields of a line in the file system
+description file,
+.In fstab.h .
+.Bd -literal -offset indent
+struct fstab {
+       char    *fs_spec;       /* block special device name */
+       char    *fs_file;       /* file system path prefix */
+       char    *fs_vfstype;    /* type of file system */
+       char    *fs_mntops;     /* comma separated mount options */
+       char    *fs_type;       /* rw, ro, sw, or xx */
+       int     fs_freq;        /* dump frequency, in days */
+       int     fs_passno;      /* pass number on parallel dump */
+};
+.Ed
+.Pp
+The fields have meanings described in
+.Xr fstab 5 .
+.Pp
+The
+.Fn setfsent
+function
+opens the file (closing any previously opened file) or rewinds it
+if it is already open.
+.Pp
+The
+.Fn endfsent
+function
+closes the file.
+.Pp
+The
+.Fn getfsspec
+and
+.Fn getfsfile
+functions
+search the entire file (opening it if necessary) for a matching special
+file name or file system file name.
+.Pp
+For programs wishing to read the entire database,
+.Fn getfsent
+reads the next entry (opening the file if necessary).
+.Pp
+All entries in the file with a type field equivalent to
+.Dv FSTAB_XX
+are ignored.
+.Sh RETURN VALUES
+The
+.Fn getfsent ,
+.Fn getfsspec ,
+and
+.Fn getfsfile
+functions
+return a null pointer (0) on
+.Dv EOF
+or error.
+The
+.Fn setfsent
+function
+returns 0 on failure, 1 on success.
+The
+.Fn endfsent
+function
+returns nothing.
+.Sh FILES
+.Bl -tag -width /etc/fstab -compact
+.It Pa /etc/fstab
+.El
+.Sh SEE ALSO
+.Xr fstab 5
+.Sh HISTORY
+The
+.Fn getfsent
+function appeared in
+.Bx 4.0 ;
+the
+.Fn endfsent ,
+.Fn getfsfile ,
+.Fn getfsspec ,
+and
+.Fn setfsent
+functions appeared in
+.Bx 4.3 .
+.Sh BUGS
+These functions use static data storage;
+if the data is needed for future use, it should be
+copied before any subsequent calls overwrite it.
diff --git a/lib/nbsd_libc/gen/getgrent.3 b/lib/nbsd_libc/gen/getgrent.3
new file mode 100644 (file)
index 0000000..2dea4e3
--- /dev/null
@@ -0,0 +1,344 @@
+.\"    $NetBSD: getgrent.3,v 1.30 2010/03/22 19:30:53 joerg Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getgrent.3 8.2 (Berkeley) 4/19/94
+.\"
+.Dd April 30, 2008
+.Dt GETGRENT 3
+.Os
+.Sh NAME
+.Nm getgrent ,
+.Nm getgrent_r ,
+.Nm getgrgid ,
+.Nm getgrgid_r ,
+.Nm getgrnam ,
+.Nm getgrnam_r ,
+.Nm setgroupent ,
+.\" .Nm setgrfile ,
+.Nm setgrent ,
+.Nm endgrent
+.Nd group database operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In grp.h
+.Ft struct group *
+.Fn getgrent void
+.Ft int
+.Fo getgrent_r
+.Fa "struct group *grp"
+.Fa "char *buffer"
+.Fa "size_t buflen"
+.Fa "struct group **result"
+.Fc
+.Ft struct group *
+.Fn getgrgid "gid_t gid"
+.Ft int
+.Fo getgrgid_r
+.Fa "gid_t gid"
+.Fa "struct group *grp"
+.Fa "char *buffer"
+.Fa "size_t buflen"
+.Fa "struct group **result"
+.Fc
+.Ft struct group *
+.Fn getgrnam "const char *name"
+.Ft int
+.Fo getgrnam_r
+.Fa "const char *name"
+.Fa "struct group *grp"
+.Fa "char *buffer"
+.Fa "size_t buflen"
+.Fa "struct group **result"
+.Fc
+.Ft int
+.Fn setgroupent "int stayopen"
+.\" .Ft void
+.\" .Fn setgrfile "const char *name"
+.Ft void
+.Fn setgrent void
+.Ft void
+.Fn endgrent void
+.Sh DESCRIPTION
+These functions operate on the group database which is described in
+.Xr group 5 .
+Each line of the database is defined by the structure
+.Ar group
+found in the include
+file
+.In grp.h :
+.Bd -literal -offset indent
+struct group {
+       char    *gr_name;       /* group name */
+       char    *gr_passwd;     /* group password */
+       gid_t   gr_gid;         /* group id */
+       char    **gr_mem;       /* group members */
+};
+.Ed
+.Pp
+The functions
+.Fn getgrnam
+and
+.Fn getgrgid
+search the group database for the given group name pointed to by
+.Ar name
+or the group id pointed to by
+.Ar gid ,
+respectively, returning the first one encountered.
+Identical group names or group ids may result in undefined behavior.
+.Pp
+The
+.Fn getgrent
+function sequentially reads the group database and is intended for programs
+that wish to step through the complete list of groups.
+.Pp
+All three functions will open the group file for reading, if necessary.
+.Pp
+The functions
+.Fn getgrnam_r ,
+.Fn getgrgid_r ,
+and
+.Fn getgrent_r
+act like their non re-entrant counterparts
+respectively, updating the contents of
+.Ar grp
+and storing a pointer to that in
+.Ar result ,
+and returning
+.Dv 0 .
+Storage used by
+.Ar grp
+is allocated from
+.Ar buffer ,
+which is
+.Ar buflen
+bytes in size.
+If the requested entry cannot be found,
+.Ar result
+will point to
+.Dv NULL
+and
+.Dv 0
+will be returned.
+If an error occurs,
+a non-zero error number will be returned and
+.Ar result
+will point to
+.Dv NULL .
+Calling
+.Fn getgrent_r
+from multiple threads will result in each thread reading a disjoint portion
+of the group database.
+.Pp
+The
+.Fn setgroupent
+function opens the file, or rewinds it if it is already open.
+If
+.Fa stayopen
+is non-zero, file descriptors are left open, significantly speeding
+functions subsequent calls.
+This functionality is unnecessary for
+.Fn getgrent
+as it doesn't close its file descriptors by default.
+It should also be noted that it is dangerous for long-running
+programs to use this functionality as the group file may be updated.
+.Pp
+The
+.Fn setgrent
+function is equivalent to
+.Fn setgroupent
+with an argument of zero.
+.Pp
+The
+.Fn endgrent
+function closes any open files.
+.Sh RETURN VALUES
+The functions
+.Fn getgrgid ,
+.Fn getgrnam ,
+and
+.Fn getgrent
+return a valid pointer to a group structure on success
+and a
+.Dv NULL
+pointer if the entry was not found or an error occured.
+If an error occured, the global variable
+.Dv errno
+is set to indicate the nature of the failure.
+.Pp
+The functions
+.Fn getgrgid_r ,
+.Fn getgrnam_r ,
+and
+.Fn getgrent_r
+return
+.Dv 0
+on success or entry not found, and non-zero on failure, setting the global
+variable
+.Dv errno
+to indicate the nature of the failure.
+.Pp
+The
+.Fn setgroupent
+function returns the value 1 if successful, otherwise the value
+0 is returned, setting the global variable
+.Dv errno
+to indicate the nature of the failure.
+.Pp
+The
+.Fn endgrent
+and
+.Fn setgrent
+functions have no return value.
+.Sh ERRORS
+The following error codes may be set in
+.Va errno 
+for
+.Nm getgrent ,
+.Nm getgrent_r ,
+.Nm getgrnam ,
+.Nm getgrnam_r ,
+.Nm getgrgid ,
+.Nm getgrgid_r ,
+and
+.Nm setgroupent :
+.Bl -tag -width Er
+.It Bq Er EIO
+An I/O error has occurred.
+.It Bq Er EINTR
+A signal was caught during the database search.
+.It Bq Er EMFILE
+The limit on open files for this process has been reached.
+.It Bq Er ENFILE
+The system limit on open files has been reached.
+.El
+.Pp
+The following error code may be set in
+.Va errno 
+for
+.Nm getgrent_r ,
+.Nm getgrnam_r ,
+and
+.Nm getgrgid_r :
+.Bl -tag -width Er
+.It Bq Er ERANGE
+The resulting
+.Ft struct group
+does not fit in the space defined by
+.Dv buffer
+and
+.Dv buflen
+.El
+.Pp
+Other
+.Dv errno
+values may be set depending on the specific database backends.
+.Sh FILES
+.Bl -tag -width /etc/group -compact
+.It Pa /etc/group
+group database file
+.El
+.Sh SEE ALSO
+.Xr getpwent 3 ,
+.Xr group 5 ,
+.Xr nsswitch.conf 5
+.Sh STANDARDS
+The
+.Fn getgrgid
+and
+.Fn getgrnam
+functions conform to
+.St -p1003.1-90 .
+The
+.Fn getgrgid_r
+and
+.Fn getgrnam_r
+functions conform to
+.St -p1003.1c-95 .
+The
+.Fn endgrent ,
+.Fn getgrent ,
+and
+.Fn setgrent
+functions conform to
+.St -xpg4.2
+and
+.St -p1003.1-2004
+(XSI extension).
+.Sh HISTORY
+The functions
+.Fn endgrent ,
+.Fn getgrent ,
+.Fn getgrgid ,
+.Fn getgrnam ,
+and
+.Fn setgrent
+appeared in
+.At v7 .
+The functions
+.Fn setgrfile
+and
+.Fn setgroupent
+appeared in
+.Bx 4.3 Reno .
+The functions
+.Fn getgrgid_r
+and
+.Fn getgrnam_r
+appeared in
+.Nx 3.0 .
+.Sh COMPATIBILITY
+The historic function
+.Fn setgrfile ,
+which allowed the specification of alternative group databases, has
+been deprecated and is no longer available.
+.Sh BUGS
+The functions
+.Fn getgrent ,
+.Fn getgrgid ,
+.Fn getgrnam ,
+.Fn setgroupent
+and
+.Fn setgrent
+leave their results in an internal static object and return
+a pointer to that object.
+Subsequent calls to the same function will modify the same object.
+.Pp
+The functions
+.Fn getgrent ,
+.Fn endgrent ,
+.Fn setgroupent ,
+and
+.Fn setgrent
+are fairly useless in a networked environment and should be
+avoided, if possible.
+.Fn getgrent
+makes no attempt to suppress duplicate information if multiple
+sources are specified in
+.Xr nsswitch.conf 5
diff --git a/lib/nbsd_libc/gen/getgrent.c b/lib/nbsd_libc/gen/getgrent.c
new file mode 100644 (file)
index 0000000..9e2b695
--- /dev/null
@@ -0,0 +1,1935 @@
+/*     $NetBSD: getgrent.c,v 1.62 2008/04/28 20:22:59 martin Exp $     */
+
+/*-
+ * Copyright (c) 1999-2000, 2004-2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Luke Mewburn.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+/*
+ * Portions Copyright (c) 1994, Jason Downs. 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(S) ``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(S) 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getgrent.c 8.2 (Berkeley) 3/21/94";
+#else
+__RCSID("$NetBSD: getgrent.c,v 1.62 2008/04/28 20:22:59 martin Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+
+#include <sys/param.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <grp.h>
+#include <limits.h>
+#include <nsswitch.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <syslog.h>
+
+#ifdef HESIOD
+#include <hesiod.h>
+#endif
+
+#ifdef YP
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+#endif
+
+#include "gr_private.h"
+
+#ifdef __weak_alias
+__weak_alias(endgrent,_endgrent)
+__weak_alias(getgrent,_getgrent)
+__weak_alias(getgrent_r,_getgrent_r)
+__weak_alias(getgrgid,_getgrgid)
+__weak_alias(getgrgid_r,_getgrgid_r)
+__weak_alias(getgrnam,_getgrnam)
+__weak_alias(getgrnam_r,_getgrnam_r)
+__weak_alias(setgrent,_setgrent)
+__weak_alias(setgroupent,_setgroupent)
+#endif
+
+#ifdef _REENTRANT
+mutex_t        __grmutex = MUTEX_INITIALIZER;
+#endif
+
+/*
+ * _gr_memfrombuf
+ *     Obtain want bytes from buffer (of size buflen) and return a pointer
+ *     to the available memory after adjusting buffer/buflen.
+ *     Returns NULL if there is insufficient space.
+ */
+static char *
+_gr_memfrombuf(size_t want, char **buffer, size_t *buflen)
+{
+       char    *rv;
+
+       if (want > *buflen) {
+               errno = ERANGE;
+               return NULL;
+       }
+       rv = *buffer;
+       *buffer += want;
+       *buflen -= want;
+       return rv;
+}
+
+/*
+ * _gr_parse
+ *     Parses entry as a line per group(5) (without the trailing \n)
+ *     and fills in grp with corresponding values; memory for strings
+ *     and arrays will be allocated from buf (of size buflen).
+ *     Returns 1 if parsed successfully, 0 on parse failure.
+ */
+static int
+_gr_parse(const char *entry, struct group *grp, char *buf, size_t buflen)
+{
+       unsigned long   id;
+       const char      *bp;
+       char            *ep;
+       size_t          count;
+       int             memc;
+
+       _DIAGASSERT(entry != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buf != NULL);
+
+#define COPYTOBUF(to) \
+       do { \
+               (to) = _gr_memfrombuf(count+1, &buf, &buflen); \
+               if ((to) == NULL) \
+                       return 0; \
+               memmove((to), entry, count); \
+               to[count] = '\0'; \
+       } while (0)     /* LINTED */
+
+#if 0
+       if (*entry == '+')                      /* fail on compat `+' token */
+               return 0;
+#endif
+
+       count = strcspn(entry, ":");            /* parse gr_name */
+       if (entry[count] == '\0')
+               return 0;
+       COPYTOBUF(grp->gr_name);
+       entry += count + 1;
+
+       count = strcspn(entry, ":");            /* parse gr_passwd */
+       if (entry[count] == '\0')
+               return 0;
+       COPYTOBUF(grp->gr_passwd);
+       entry += count + 1;
+
+       count = strcspn(entry, ":");            /* parse gr_gid */
+       if (entry[count] == '\0')
+               return 0;
+       id = strtoul(entry, &ep, 10);
+       if (id > GID_MAX || *ep != ':')
+               return 0;
+       grp->gr_gid = (gid_t)id;
+       entry += count + 1;
+
+       memc = 1;                               /* for final NULL */
+       if (*entry != '\0')
+               memc++;                         /* for first item */
+       for (bp = entry; *bp != '\0'; bp++) {
+               if (*bp == ',')
+                       memc++;
+       }
+                               /* grab ALIGNed char **gr_mem from buf */
+       ep = _gr_memfrombuf(memc * sizeof(char *) + ALIGNBYTES, &buf, &buflen);
+       grp->gr_mem = (char **)ALIGN(ep);
+       if (grp->gr_mem == NULL)
+               return 0;
+
+       for (memc = 0; *entry != '\0'; memc++) {
+               count = strcspn(entry, ",");    /* parse member */
+               COPYTOBUF(grp->gr_mem[memc]);
+               entry += count;
+               if (*entry == ',')
+                       entry++;
+       }
+
+#undef COPYTOBUF
+
+       grp->gr_mem[memc] = NULL;
+       return 1;
+}
+
+/*
+ * _gr_copy
+ *     Copy the contents of fromgrp to grp; memory for strings
+ *     and arrays will be allocated from buf (of size buflen).
+ *     Returns 1 if copied successfully, 0 on copy failure.
+ *     NOTE: fromgrp must not use buf for its own pointers.
+ */
+static int
+_gr_copy(struct group *fromgrp, struct group *grp, char *buf, size_t buflen)
+{
+       char    *ep;
+       int     memc;
+
+       _DIAGASSERT(fromgrp != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buf != NULL);
+
+#define COPYSTR(to, from) \
+       do { \
+               size_t count = strlen((from)); \
+               (to) = _gr_memfrombuf(count+1, &buf, &buflen); \
+               if ((to) == NULL) \
+                       return 0; \
+               memmove((to), (from), count); \
+               to[count] = '\0'; \
+       } while (0)     /* LINTED */
+
+       COPYSTR(grp->gr_name, fromgrp->gr_name);
+       COPYSTR(grp->gr_passwd, fromgrp->gr_passwd);
+       grp->gr_gid = fromgrp->gr_gid;
+
+       for (memc = 0; fromgrp->gr_mem[memc]; memc++)
+               continue;
+       memc++;                                 /* for final NULL */
+
+                               /* grab ALIGNed char **gr_mem from buf */
+       ep = _gr_memfrombuf(memc * sizeof(char *) + ALIGNBYTES, &buf, &buflen);
+       grp->gr_mem = (char **)ALIGN(ep);
+       if (grp->gr_mem == NULL)
+               return 0;
+
+       for (memc = 0; fromgrp->gr_mem[memc]; memc++) {
+               COPYSTR(grp->gr_mem[memc], fromgrp->gr_mem[memc]);
+       }
+
+#undef COPYSTR
+
+       grp->gr_mem[memc] = NULL;
+       return 1;
+}
+
+               /*
+                *      files methods
+                */
+
+int
+__grstart_files(struct __grstate_files *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       if (state->fp == NULL) {
+               state->fp = fopen(_PATH_GROUP, "r");
+               if (state->fp == NULL)
+                       return NS_UNAVAIL;
+       } else {
+               rewind(state->fp);
+       }
+       return NS_SUCCESS;
+}
+
+int
+__grend_files(struct __grstate_files *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       if (state->fp) {
+               (void) fclose(state->fp);
+               state->fp = NULL;
+       }
+       return NS_SUCCESS;
+}
+
+/*
+ * __grscan_files
+ *     Scan state->fp for the next desired entry.
+ *     If search is zero, return the next entry.
+ *     If search is non-zero, look for a specific name (if name != NULL),
+ *     or a specific gid (if name == NULL).
+ *     Sets *retval to the errno if the result is not NS_SUCCESS
+ *     or NS_NOTFOUND.
+ */
+int
+__grscan_files(int *retval, struct group *grp, char *buffer, size_t buflen,
+       struct __grstate_files *state, int search, const char *name, gid_t gid)
+{
+       int     rv;
+       char    filebuf[_GETGR_R_SIZE_MAX], *ep;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(state != NULL);
+       /* name is NULL to indicate searching for gid */
+
+       *retval = 0;
+
+       if (state->fp == NULL) {        /* only start if file not open yet */
+               rv = __grstart_files(state);
+               if (rv != NS_SUCCESS)
+                       goto filesgrscan_out;
+       }
+
+       rv = NS_NOTFOUND;
+
+                                                       /* scan line by line */
+       while (fgets(filebuf, sizeof(filebuf), state->fp) != NULL) {
+               ep = strchr(filebuf, '\n');
+               if (ep == NULL) {       /* skip lines that are too big */
+                       int ch;
+
+                       while ((ch = getc(state->fp)) != '\n' && ch != EOF)
+                               continue;
+                       continue;
+               }
+               *ep = '\0';                             /* clear trailing \n */
+
+               if (filebuf[0] == '+')                  /* skip compat line */
+                       continue;
+
+                                                       /* validate line */
+               if (! _gr_parse(filebuf, grp, buffer, buflen)) {
+                       continue;                       /* skip bad lines */
+               }
+               if (! search) {                         /* just want this one */
+                       rv = NS_SUCCESS;
+                       break;
+               }
+                                                       /* want specific */
+               if ((name && strcmp(name, grp->gr_name) == 0) ||
+                   (!name && gid == grp->gr_gid)) {
+                       rv = NS_SUCCESS;
+                       break;
+               }
+       }
+
+ filesgrscan_out:
+       if (rv != NS_SUCCESS && rv != NS_NOTFOUND)
+               *retval = errno;
+       return rv;
+}
+
+
+static struct __grstate_files  _files_state;
+                                       /* storage for non _r functions */
+static struct group            _files_group;
+static char                    _files_groupbuf[_GETGR_R_SIZE_MAX];
+
+/*ARGSUSED*/
+static int
+_files_setgrent(void *nsrv, void *nscb, va_list ap)
+{
+
+       _files_state.stayopen = 0;
+       return __grstart_files(&_files_state);
+}
+
+/*ARGSUSED*/
+static int
+_files_setgroupent(void *nsrv, void *nscb, va_list ap)
+{
+       int     *retval         = va_arg(ap, int *);
+       int      stayopen       = va_arg(ap, int);
+
+       int     rv;
+
+       _files_state.stayopen = stayopen;
+       rv = __grstart_files(&_files_state);
+       *retval = (rv == NS_SUCCESS);
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_endgrent(void *nsrv, void *nscb, va_list ap)
+{
+
+       _files_state.stayopen = 0;
+       return __grend_files(&_files_state);
+}
+
+/*ARGSUSED*/
+static int
+_files_getgrent(void *nsrv, void *nscb, va_list ap)
+{
+       struct group    **retval = va_arg(ap, struct group **);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = __grscan_files(&rerror, &_files_group,
+           _files_groupbuf, sizeof(_files_groupbuf),
+           &_files_state, 0, NULL, 0);
+       if (rv == NS_SUCCESS)
+               *retval = &_files_group;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_getgrent_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       struct group    *grp    = va_arg(ap, struct group *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct group   **result = va_arg(ap, struct group **);
+
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       rv = __grscan_files(retval, grp, buffer, buflen,
+           &_files_state, 0, NULL, 0);
+       if (rv == NS_SUCCESS)
+               *result = grp;
+       else
+               *result = NULL;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_getgrgid(void *nsrv, void *nscb, va_list ap)
+{
+       struct group    **retval = va_arg(ap, struct group **);
+       gid_t            gid    = va_arg(ap, gid_t);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = __grstart_files(&_files_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = __grscan_files(&rerror, &_files_group,
+           _files_groupbuf, sizeof(_files_groupbuf),
+           &_files_state, 1, NULL, gid);
+       if (!_files_state.stayopen)
+               __grend_files(&_files_state);
+       if (rv == NS_SUCCESS)
+               *retval = &_files_group;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_getgrgid_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       gid_t            gid    = va_arg(ap, gid_t);
+       struct group    *grp    = va_arg(ap, struct group *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct group   **result = va_arg(ap, struct group **);
+
+       struct __grstate_files state;
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = __grscan_files(retval, grp, buffer, buflen, &state, 1, NULL, gid);
+       __grend_files(&state);
+       if (rv == NS_SUCCESS)
+               *result = grp;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_getgrnam(void *nsrv, void *nscb, va_list ap)
+{
+       struct group    **retval = va_arg(ap, struct group **);
+       const char      *name   = va_arg(ap, const char *);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = __grstart_files(&_files_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = __grscan_files(&rerror, &_files_group,
+           _files_groupbuf, sizeof(_files_groupbuf),
+           &_files_state, 1, name, 0);
+       if (!_files_state.stayopen)
+               __grend_files(&_files_state);
+       if (rv == NS_SUCCESS)
+               *retval = &_files_group;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_getgrnam_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       const char      *name   = va_arg(ap, const char *);
+       struct group    *grp    = va_arg(ap, struct group *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct group   **result = va_arg(ap, struct group **);
+
+       struct __grstate_files state;
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = __grscan_files(retval, grp, buffer, buflen, &state, 1, name, 0);
+       __grend_files(&state);
+       if (rv == NS_SUCCESS)
+               *result = grp;
+       return rv;
+}
+
+
+#ifdef HESIOD
+               /*
+                *      dns methods
+                */
+
+int
+__grstart_dns(struct __grstate_dns *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       state->num = 0;
+       if (state->context == NULL) {                   /* setup Hesiod */
+               if (hesiod_init(&state->context) == -1)
+                       return NS_UNAVAIL;
+       }
+
+       return NS_SUCCESS;
+}
+
+int
+__grend_dns(struct __grstate_dns *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       state->num = 0;
+       if (state->context) {
+               hesiod_end(state->context);
+               state->context = NULL;
+       }
+       return NS_SUCCESS;
+}
+
+/*
+ * __grscan_dns
+ *     Search Hesiod for the next desired entry.
+ *     If search is zero, return the next entry.
+ *     If search is non-zero, look for a specific name (if name != NULL),
+ *     or a specific gid (if name == NULL).
+ */
+int
+__grscan_dns(int *retval, struct group *grp, char *buffer, size_t buflen,
+       struct __grstate_dns *state, int search, const char *name, gid_t gid)
+{
+       const char      **curzone;
+       char            **hp, *ep;
+       int             rv;
+
+       static const char *zones_gid_group[] = {
+               "gid",
+               "group",
+               NULL
+       };
+
+       static const char *zones_group[] = {
+               "group",
+               NULL
+       };
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(state != NULL);
+       /* name is NULL to indicate searching for gid */
+
+       *retval = 0;
+
+       if (state->context == NULL) {   /* only start if Hesiod not setup */
+               rv = __grstart_dns(state);
+               if (rv != NS_SUCCESS)
+                       return rv;
+       }
+
+ next_dns_entry:
+       hp = NULL;
+       rv = NS_NOTFOUND;
+
+       if (! search) {                 /* find next entry */
+               if (state->num == -1)           /* exhausted search */
+                       return NS_NOTFOUND;
+                                               /* find group-NNN */
+               snprintf(buffer, buflen, "group-%u", state->num);
+               state->num++;
+               curzone = zones_group;
+       } else if (name) {              /* find group name */
+               snprintf(buffer, buflen, "%s", name);
+               curzone = zones_group;
+       } else {                        /* find gid */
+               snprintf(buffer, buflen, "%u", (unsigned int)gid);
+               curzone = zones_gid_group;
+       }
+
+       for (; *curzone; curzone++) {           /* search zones */
+               hp = hesiod_resolve(state->context, buffer, *curzone);
+               if (hp != NULL)
+                       break;
+               if (errno != ENOENT) {
+                       rv = NS_UNAVAIL;
+                       goto dnsgrscan_out;
+               }
+       }
+       if (*curzone == NULL) {
+               if (! search)
+                       state->num = -1;
+               goto dnsgrscan_out;
+       }
+
+       if ((ep = strchr(hp[0], '\n')) != NULL)
+               *ep = '\0';                             /* clear trailing \n */
+       if (_gr_parse(hp[0], grp, buffer, buflen)) {    /* validate line */
+               if (! search) {                         /* just want this one */
+                       rv = NS_SUCCESS;
+               } else if ((name && strcmp(name, grp->gr_name) == 0) ||
+                   (!name && gid == grp->gr_gid)) {    /* want specific */
+                       rv = NS_SUCCESS;
+               }
+       } else {                                        /* dodgy entry */
+               if (!search) {                  /* try again if ! searching */
+                       hesiod_free_list(state->context, hp);
+                       goto next_dns_entry;
+               }
+       }
+
+ dnsgrscan_out:
+       if (rv != NS_SUCCESS && rv != NS_NOTFOUND)
+               *retval = errno;
+       if (hp)
+               hesiod_free_list(state->context, hp);
+       return rv;
+}
+
+static struct __grstate_dns    _dns_state;
+                                       /* storage for non _r functions */
+static struct group            _dns_group;
+static char                    _dns_groupbuf[_GETGR_R_SIZE_MAX];
+
+/*ARGSUSED*/
+static int
+_dns_setgrent(void *nsrv, void *nscb, va_list ap)
+{
+
+       _dns_state.stayopen = 0;
+       return __grstart_dns(&_dns_state);
+}
+
+/*ARGSUSED*/
+static int
+_dns_setgroupent(void *nsrv, void *nscb, va_list ap)
+{
+       int     *retval         = va_arg(ap, int *);
+       int      stayopen       = va_arg(ap, int);
+
+       int     rv;
+
+       _dns_state.stayopen = stayopen;
+       rv = __grstart_dns(&_dns_state);
+       *retval = (rv == NS_SUCCESS);
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_dns_endgrent(void *nsrv, void *nscb, va_list ap)
+{
+
+       _dns_state.stayopen = 0;
+       return __grend_dns(&_dns_state);
+}
+
+/*ARGSUSED*/
+static int
+_dns_getgrent(void *nsrv, void *nscb, va_list ap)
+{
+       struct group    **retval = va_arg(ap, struct group **);
+
+       int       rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = __grscan_dns(&rerror, &_dns_group,
+           _dns_groupbuf, sizeof(_dns_groupbuf), &_dns_state, 0, NULL, 0);
+       if (rv == NS_SUCCESS)
+               *retval = &_dns_group;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_dns_getgrent_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       struct group    *grp    = va_arg(ap, struct group *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct group   **result = va_arg(ap, struct group **);
+
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       rv = __grscan_dns(retval, grp, buffer, buflen,
+           &_dns_state, 0, NULL, 0);
+       if (rv == NS_SUCCESS)
+               *result = grp;
+       else
+               *result = NULL;
+       return rv;
+}
+/*ARGSUSED*/
+static int
+_dns_getgrgid(void *nsrv, void *nscb, va_list ap)
+{
+       struct group    **retval = va_arg(ap, struct group **);
+       gid_t            gid    = va_arg(ap, gid_t);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = __grstart_dns(&_dns_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = __grscan_dns(&rerror, &_dns_group,
+           _dns_groupbuf, sizeof(_dns_groupbuf), &_dns_state, 1, NULL, gid);
+       if (!_dns_state.stayopen)
+               __grend_dns(&_dns_state);
+       if (rv == NS_SUCCESS)
+               *retval = &_dns_group;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_dns_getgrgid_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       gid_t            gid    = va_arg(ap, gid_t);
+       struct group    *grp    = va_arg(ap, struct group *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct group   **result = va_arg(ap, struct group **);
+
+       struct __grstate_dns state;
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = __grscan_dns(retval, grp, buffer, buflen, &state, 1, NULL, gid);
+       __grend_dns(&state);
+       if (rv == NS_SUCCESS)
+               *result = grp;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_dns_getgrnam(void *nsrv, void *nscb, va_list ap)
+{
+       struct group    **retval = va_arg(ap, struct group **);
+       const char      *name   = va_arg(ap, const char *);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = __grstart_dns(&_dns_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = __grscan_dns(&rerror, &_dns_group,
+           _dns_groupbuf, sizeof(_dns_groupbuf), &_dns_state, 1, name, 0);
+       if (!_dns_state.stayopen)
+               __grend_dns(&_dns_state);
+       if (rv == NS_SUCCESS)
+               *retval = &_dns_group;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_dns_getgrnam_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       const char      *name   = va_arg(ap, const char *);
+       struct group    *grp    = va_arg(ap, struct group *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct group   **result = va_arg(ap, struct group **);
+
+       struct __grstate_dns state;
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = __grscan_dns(retval, grp, buffer, buflen, &state, 1, name, 0);
+       __grend_dns(&state);
+       if (rv == NS_SUCCESS)
+               *result = grp;
+       return rv;
+}
+
+#endif /* HESIOD */
+
+
+#ifdef YP
+               /*
+                *      nis methods
+                */
+
+int
+__grstart_nis(struct __grstate_nis *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       state->done = 0;
+       if (state->current) {
+               free(state->current);
+               state->current = NULL;
+       }
+       if (state->domain == NULL) {                    /* setup NIS */
+               switch (yp_get_default_domain(&state->domain)) {
+               case 0:
+                       break;
+               case YPERR_RESRC:
+                       return NS_TRYAGAIN;
+               default:
+                       return NS_UNAVAIL;
+               }
+       }
+       return NS_SUCCESS;
+}
+
+int
+__grend_nis(struct __grstate_nis *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       if (state->domain) {
+               state->domain = NULL;
+       }
+       state->done = 0;
+       if (state->current) {
+               free(state->current);
+               state->current = NULL;
+       }
+       return NS_SUCCESS;
+}
+
+/*
+ * __grscan_nis
+ *     Search NIS for the next desired entry.
+ *     If search is zero, return the next entry.
+ *     If search is non-zero, look for a specific name (if name != NULL),
+ *     or a specific gid (if name == NULL).
+ */
+int
+__grscan_nis(int *retval, struct group *grp, char *buffer, size_t buflen,
+       struct __grstate_nis *state, int search, const char *name, gid_t gid)
+{
+       const char *map;
+       char    *key, *data;
+       int     nisr, rv, keylen, datalen;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(state != NULL);
+       /* name is NULL to indicate searching for gid */
+
+       *retval = 0;
+
+       if (state->domain == NULL) {    /* only start if NIS not setup */
+               rv = __grstart_nis(state);
+               if (rv != NS_SUCCESS)
+                       return rv;
+       }
+
+ next_nis_entry:
+       key = NULL;
+       data = NULL;
+       rv = NS_SUCCESS;
+
+       if (! search)   {                       /* find next entry */
+               if (state->done)                        /* exhausted search */
+                       return NS_NOTFOUND;
+               map = "group.byname";
+               if (state->current) {                   /* already searching */
+                       nisr = yp_next(state->domain, map,
+                           state->current, state->currentlen,
+                           &key, &keylen, &data, &datalen);
+                       free(state->current);
+                       state->current = NULL;
+                       switch (nisr) {
+                       case 0:
+                               state->current = key;
+                               state->currentlen = keylen;
+                               key = NULL;
+                               break;
+                       case YPERR_NOMORE:
+                               rv = NS_NOTFOUND;
+                               state->done = 1;
+                               break;
+                       default:
+                               rv = NS_UNAVAIL;
+                               break;
+                       }
+               } else {                                /* new search */
+                       if (yp_first(state->domain, map,
+                           &state->current, &state->currentlen,
+                           &data, &datalen)) {
+                               rv = NS_UNAVAIL;
+                       }
+               }
+       } else {                                /* search for specific item */
+               if (name) {                     /* find group name */
+                       snprintf(buffer, buflen, "%s", name);
+                       map = "group.byname";
+               } else {                        /* find gid */
+                       snprintf(buffer, buflen, "%u", (unsigned int)gid);
+                       map = "group.bygid";
+               }
+               nisr = yp_match(state->domain, map, buffer, (int)strlen(buffer),
+                   &data, &datalen);
+               switch (nisr) {
+               case 0:
+                       break;
+               case YPERR_KEY:
+                       rv = NS_NOTFOUND;
+                       break;
+               default:
+                       rv = NS_UNAVAIL;
+                       break;
+               }
+       }
+       if (rv == NS_SUCCESS) {                         /* validate data */
+               data[datalen] = '\0';                   /* clear trailing \n */
+               if (_gr_parse(data, grp, buffer, buflen)) {
+                       if (! search) {                 /* just want this one */
+                               rv = NS_SUCCESS;
+                       } else if ((name && strcmp(name, grp->gr_name) == 0) ||
+                           (!name && gid == grp->gr_gid)) {
+                                                       /* want specific */
+                               rv = NS_SUCCESS;
+                       }
+               } else {                                /* dodgy entry */
+                       if (!search) {          /* try again if ! searching */
+                               free(data);
+                               goto next_nis_entry;
+                       }
+               }
+       }
+
+       if (rv != NS_SUCCESS && rv != NS_NOTFOUND)
+               *retval = errno;
+       if (key)
+               free(key);
+       if (data)
+               free(data);
+       return rv;
+}
+
+static struct __grstate_nis    _nis_state;
+                                       /* storage for non _r functions */
+static struct group            _nis_group;
+static char                    _nis_groupbuf[_GETGR_R_SIZE_MAX];
+
+/*ARGSUSED*/
+static int
+_nis_setgrent(void *nsrv, void *nscb, va_list ap)
+{
+
+       _nis_state.stayopen = 0;
+       return __grstart_nis(&_nis_state);
+}
+
+/*ARGSUSED*/
+static int
+_nis_setgroupent(void *nsrv, void *nscb, va_list ap)
+{
+       int     *retval         = va_arg(ap, int *);
+       int      stayopen       = va_arg(ap, int);
+
+       int     rv;
+
+       _nis_state.stayopen = stayopen;
+       rv = __grstart_nis(&_nis_state);
+       *retval = (rv == NS_SUCCESS);
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_nis_endgrent(void *nsrv, void *nscb, va_list ap)
+{
+
+       return __grend_nis(&_nis_state);
+}
+
+/*ARGSUSED*/
+static int
+_nis_getgrent(void *nsrv, void *nscb, va_list ap)
+{
+       struct group    **retval = va_arg(ap, struct group **);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = __grscan_nis(&rerror, &_nis_group,
+           _nis_groupbuf, sizeof(_nis_groupbuf), &_nis_state, 0, NULL, 0);
+       if (rv == NS_SUCCESS)
+               *retval = &_nis_group;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_nis_getgrent_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       struct group    *grp    = va_arg(ap, struct group *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct group   **result = va_arg(ap, struct group **);
+
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       rv = __grscan_nis(retval, grp, buffer, buflen,
+           &_nis_state, 0, NULL, 0);
+       if (rv == NS_SUCCESS)
+               *result = grp;
+       else
+               *result = NULL;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_nis_getgrgid(void *nsrv, void *nscb, va_list ap)
+{
+       struct group    **retval = va_arg(ap, struct group **);
+       gid_t            gid    = va_arg(ap, gid_t);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = __grstart_nis(&_nis_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = __grscan_nis(&rerror, &_nis_group,
+           _nis_groupbuf, sizeof(_nis_groupbuf), &_nis_state, 1, NULL, gid);
+       if (!_nis_state.stayopen)
+               __grend_nis(&_nis_state);
+       if (rv == NS_SUCCESS)
+               *retval = &_nis_group;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_nis_getgrgid_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       gid_t            gid    = va_arg(ap, gid_t);
+       struct group    *grp    = va_arg(ap, struct group *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct group   **result = va_arg(ap, struct group **);
+
+       struct __grstate_nis state;
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = __grscan_nis(retval, grp, buffer, buflen, &state, 1, NULL, gid);
+       __grend_nis(&state);
+       if (rv == NS_SUCCESS)
+               *result = grp;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_nis_getgrnam(void *nsrv, void *nscb, va_list ap)
+{
+       struct group    **retval = va_arg(ap, struct group **);
+       const char      *name   = va_arg(ap, const char *);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = __grstart_nis(&_nis_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = __grscan_nis(&rerror, &_nis_group,
+           _nis_groupbuf, sizeof(_nis_groupbuf), &_nis_state, 1, name, 0);
+       if (!_nis_state.stayopen)
+               __grend_nis(&_nis_state);
+       if (rv == NS_SUCCESS)
+               *retval = &_nis_group;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_nis_getgrnam_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       const char      *name   = va_arg(ap, const char *);
+       struct group    *grp    = va_arg(ap, struct group *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct group   **result = va_arg(ap, struct group **);
+
+       struct __grstate_nis state;
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = __grscan_nis(retval, grp, buffer, buflen, &state, 1, name, 0);
+       __grend_nis(&state);
+       if (rv == NS_SUCCESS)
+               *result = grp;
+       return rv;
+}
+
+#endif /* YP */
+
+
+#ifdef _GROUP_COMPAT
+               /*
+                *      compat methods
+                */
+
+int
+__grstart_compat(struct __grstate_compat *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       if (state->fp == NULL) {
+               state->fp = fopen(_PATH_GROUP, "r");
+               if (state->fp == NULL)
+                       return NS_UNAVAIL;
+       } else {
+               rewind(state->fp);
+       }
+       return NS_SUCCESS;
+}
+
+int
+__grend_compat(struct __grstate_compat *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       if (state->name) {
+               free(state->name);
+               state->name = NULL;
+       }
+       if (state->fp) {
+               (void) fclose(state->fp);
+               state->fp = NULL;
+       }
+       return NS_SUCCESS;
+}
+
+
+/*
+ * __grbad_compat
+ *     log an error if "files" or "compat" is specified in
+ *     group_compat database
+ */
+/*ARGSUSED*/
+int
+__grbad_compat(void *nsrv, void *nscb, va_list ap)
+{
+       static int warned;
+
+       _DIAGASSERT(nsrv != NULL);
+       _DIAGASSERT(nscb != NULL);
+
+       if (!warned) {
+               syslog(LOG_ERR,
+                       "nsswitch.conf group_compat database can't use '%s'",
+                       (const char *)nscb);
+       }
+       warned = 1;
+       return NS_UNAVAIL;
+}
+
+/*
+ * __grscan_compat
+ *     Scan state->fp for the next desired entry.
+ *     If search is zero, return the next entry.
+ *     If search is non-zero, look for a specific name (if name != NULL),
+ *     or a specific gid (if name == NULL).
+ *     Sets *retval to the errno if the result is not NS_SUCCESS or
+ *     NS_NOTFOUND.
+ *
+ *     searchfunc is invoked when a compat "+" lookup is required;
+ *     searchcookie is passed as the first argument to searchfunc,
+ *     the second argument is the group result.
+ *     This should return NS_NOTFOUND when "no more groups" from compat src.
+ *     If searchfunc is NULL then nsdispatch of getgrent is used.
+ *     This is primarily intended for getgroupmembership(3)'s compat backend.
+ */
+int
+__grscan_compat(int *retval, struct group *grp, char *buffer, size_t buflen,
+       struct __grstate_compat *state, int search, const char *name, gid_t gid,
+       int (*searchfunc)(void *, struct group **), void *searchcookie)
+{
+       int             rv;
+       char            filebuf[_GETGR_R_SIZE_MAX], *ep;
+
+       static const ns_dtab compatentdtab[] = {
+               NS_FILES_CB(__grbad_compat, "files")
+               NS_DNS_CB(_dns_getgrent_r, NULL)
+               NS_NIS_CB(_nis_getgrent_r, NULL)
+               NS_COMPAT_CB(__grbad_compat, "compat")
+               NS_NULL_CB
+       };
+       static const ns_dtab compatgiddtab[] = {
+               NS_FILES_CB(__grbad_compat, "files")
+               NS_DNS_CB(_dns_getgrgid_r, NULL)
+               NS_NIS_CB(_nis_getgrgid_r, NULL)
+               NS_COMPAT_CB(__grbad_compat, "compat")
+               NS_NULL_CB
+       };
+       static const ns_dtab compatnamdtab[] = {
+               NS_FILES_CB(__grbad_compat, "files")
+               NS_DNS_CB(_dns_getgrnam_r, NULL)
+               NS_NIS_CB(_nis_getgrnam_r, NULL)
+               NS_COMPAT_CB(__grbad_compat, "compat")
+               NS_NULL_CB
+       };
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(state != NULL);
+       /* name is NULL to indicate searching for gid */
+
+       *retval = 0;
+
+       if (state->fp == NULL) {        /* only start if file not open yet */
+               rv = __grstart_compat(state);
+               if (rv != NS_SUCCESS)
+                       goto compatgrscan_out;
+       }
+       rv = NS_NOTFOUND;
+
+       for (;;) {                                      /* loop through file */
+               if (state->name != NULL) {
+                                       /* processing compat entry */
+                       int             crv, cretval;
+                       struct group    cgrp, *cgrpres;
+
+                       if (state->name[0]) {           /* specific +group: */
+                               crv = nsdispatch(NULL, compatnamdtab,
+                                   NSDB_GROUP_COMPAT, "getgrnam_r",
+                                   __nsdefaultnis,
+                                   &cretval, state->name,
+                                   &cgrp, filebuf, sizeof(filebuf), &cgrpres);
+                               free(state->name);      /* (only check 1 grp) */
+                               state->name = NULL;
+                       } else if (!search) {           /* any group */
+                               if (searchfunc) {
+                                       crv = searchfunc(searchcookie,
+                                           &cgrpres);
+                               } else {
+                                       crv = nsdispatch(NULL, compatentdtab,
+                                           NSDB_GROUP_COMPAT, "getgrent_r",
+                                           __nsdefaultnis,
+                                           &cretval, &cgrp, filebuf,
+                                           sizeof(filebuf), &cgrpres);
+                               }
+                       } else if (name) {              /* specific group */
+                               crv = nsdispatch(NULL, compatnamdtab,
+                                   NSDB_GROUP_COMPAT, "getgrnam_r",
+                                   __nsdefaultnis,
+                                   &cretval, name,
+                                   &cgrp, filebuf, sizeof(filebuf), &cgrpres);
+                       } else {                        /* specific gid */
+                               crv = nsdispatch(NULL, compatgiddtab,
+                                   NSDB_GROUP_COMPAT, "getgrgid_r",
+                                   __nsdefaultnis,
+                                   &cretval, gid,
+                                   &cgrp, filebuf, sizeof(filebuf), &cgrpres);
+                       }
+                       if (crv != NS_SUCCESS) {        /* not found */
+                               free(state->name);
+                               state->name = NULL;
+                               continue;               /* try next line */
+                       }
+                       if (!_gr_copy(cgrpres, grp, buffer, buflen)) {
+                               rv = NS_UNAVAIL;
+                               break;
+                       }
+                       goto compatgrscan_cmpgrp;       /* skip to grp test */
+               }
+
+                                                       /* get next file line */
+               if (fgets(filebuf, sizeof(filebuf), state->fp) == NULL)
+                       break;
+
+               ep = strchr(filebuf, '\n');
+               if (ep == NULL) {       /* skip lines that are too big */
+                       int ch;
+
+                       while ((ch = getc(state->fp)) != '\n' && ch != EOF)
+                               continue;
+                       continue;
+               }
+               *ep = '\0';                             /* clear trailing \n */
+
+               if (filebuf[0] == '+') {                /* parse compat line */
+                       if (state->name)
+                               free(state->name);
+                       state->name = NULL;
+                       switch(filebuf[1]) {
+                       case ':':
+                       case '\0':
+                               state->name = strdup("");
+                               break;
+                       default:
+                               ep = strchr(filebuf + 1, ':');
+                               if (ep == NULL)
+                                       break;
+                               *ep = '\0';
+                               state->name = strdup(filebuf + 1);
+                               break;
+                       }
+                       if (state->name == NULL) {
+                               rv = NS_UNAVAIL;
+                               break;
+                       }
+                       continue;
+               }
+
+                                                       /* validate line */
+               if (! _gr_parse(filebuf, grp, buffer, buflen)) {
+                       continue;                       /* skip bad lines */
+               }
+
+ compatgrscan_cmpgrp:
+               if (! search) {                         /* just want this one */
+                       rv = NS_SUCCESS;
+                       break;
+               }
+                                                       /* want specific */
+               if ((name && strcmp(name, grp->gr_name) == 0) ||
+                   (!name && gid == grp->gr_gid)) {
+                       rv = NS_SUCCESS;
+                       break;
+               }
+
+       }
+
+ compatgrscan_out:
+       if (rv != NS_SUCCESS && rv != NS_NOTFOUND)
+               *retval = errno;
+       return rv;
+}
+
+static struct __grstate_compat _compat_state;
+                                       /* storage for non _r functions */
+static struct group            _compat_group;
+static char                    _compat_groupbuf[_GETGR_R_SIZE_MAX];
+
+/*ARGSUSED*/
+static int
+_compat_setgrent(void *nsrv, void *nscb, va_list ap)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(__grbad_compat, "files")
+               NS_DNS_CB(_dns_setgrent, NULL)
+               NS_NIS_CB(_nis_setgrent, NULL)
+               NS_COMPAT_CB(__grbad_compat, "compat")
+               NS_NULL_CB
+       };
+
+                                       /* force group_compat setgrent() */
+       (void) nsdispatch(NULL, dtab, NSDB_GROUP_COMPAT, "setgrent",
+           __nsdefaultnis_forceall);
+
+                                       /* reset state, keep fp open */
+       _compat_state.stayopen = 0;
+       return __grstart_compat(&_compat_state);
+}
+
+/*ARGSUSED*/
+static int
+_compat_setgroupent(void *nsrv, void *nscb, va_list ap)
+{
+       int     *retval         = va_arg(ap, int *);
+       int      stayopen       = va_arg(ap, int);
+
+       int     rv;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(__grbad_compat, "files")
+               NS_DNS_CB(_dns_setgroupent, NULL)
+               NS_NIS_CB(_nis_setgroupent, NULL)
+               NS_COMPAT_CB(__grbad_compat, "compat")
+               NS_NULL_CB
+       };
+
+                                       /* force group_compat setgroupent() */
+       (void) nsdispatch(NULL, dtab, NSDB_GROUP_COMPAT, "setgroupent",
+           __nsdefaultnis_forceall, &rv, stayopen);
+
+       _compat_state.stayopen = stayopen;
+       rv = __grstart_compat(&_compat_state);
+       *retval = (rv == NS_SUCCESS);
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_compat_endgrent(void *nsrv, void *nscb, va_list ap)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(__grbad_compat, "files")
+               NS_DNS_CB(_dns_endgrent, NULL)
+               NS_NIS_CB(_nis_endgrent, NULL)
+               NS_COMPAT_CB(__grbad_compat, "compat")
+               NS_NULL_CB
+       };
+
+                                       /* force group_compat endgrent() */
+       (void) nsdispatch(NULL, dtab, NSDB_GROUP_COMPAT, "endgrent",
+           __nsdefaultnis_forceall);
+
+                                       /* reset state, close fp */
+       _compat_state.stayopen = 0;
+       return __grend_compat(&_compat_state);
+}
+
+/*ARGSUSED*/
+static int
+_compat_getgrent(void *nsrv, void *nscb, va_list ap)
+{
+       struct group    **retval = va_arg(ap, struct group **);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = __grscan_compat(&rerror, &_compat_group,
+           _compat_groupbuf, sizeof(_compat_groupbuf),
+           &_compat_state, 0, NULL, 0, NULL, NULL);
+       if (rv == NS_SUCCESS)
+               *retval = &_compat_group;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_compat_getgrent_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       struct group    *grp    = va_arg(ap, struct group *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct group   **result = va_arg(ap, struct group **);
+
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       rv = __grscan_compat(retval, grp, buffer, buflen,
+           &_compat_state, 0, NULL, 0, NULL, NULL);
+       if (rv == NS_SUCCESS)
+               *result = grp;
+       else
+               *result = NULL;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_compat_getgrgid(void *nsrv, void *nscb, va_list ap)
+{
+       struct group    **retval = va_arg(ap, struct group **);
+       gid_t            gid    = va_arg(ap, gid_t);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = __grstart_compat(&_compat_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = __grscan_compat(&rerror, &_compat_group,
+           _compat_groupbuf, sizeof(_compat_groupbuf),
+           &_compat_state, 1, NULL, gid, NULL, NULL);
+       if (!_compat_state.stayopen)
+               __grend_compat(&_compat_state);
+       if (rv == NS_SUCCESS)
+               *retval = &_compat_group;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_compat_getgrgid_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       gid_t            gid    = va_arg(ap, gid_t);
+       struct group    *grp    = va_arg(ap, struct group *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct group   **result = va_arg(ap, struct group **);
+
+       struct __grstate_compat state;
+       int             rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = __grscan_compat(retval, grp, buffer, buflen, &state,
+           1, NULL, gid, NULL, NULL);
+       __grend_compat(&state);
+       if (rv == NS_SUCCESS)
+               *result = grp;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_compat_getgrnam(void *nsrv, void *nscb, va_list ap)
+{
+       struct group    **retval = va_arg(ap, struct group **);
+       const char      *name   = va_arg(ap, const char *);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = __grstart_compat(&_compat_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = __grscan_compat(&rerror, &_compat_group,
+           _compat_groupbuf, sizeof(_compat_groupbuf),
+           &_compat_state, 1, name, 0, NULL, NULL);
+       if (!_compat_state.stayopen)
+               __grend_compat(&_compat_state);
+       if (rv == NS_SUCCESS)
+               *retval = &_compat_group;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_compat_getgrnam_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       const char      *name   = va_arg(ap, const char *);
+       struct group    *grp    = va_arg(ap, struct group *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct group   **result = va_arg(ap, struct group **);
+
+       struct __grstate_compat state;
+       int             rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = __grscan_compat(retval, grp, buffer, buflen, &state,
+           1, name, 0, NULL, NULL);
+       __grend_compat(&state);
+       if (rv == NS_SUCCESS)
+               *result = grp;
+       return rv;
+}
+
+#endif /* _GROUP_COMPAT */
+
+
+               /*
+                *      public functions
+                */
+
+struct group *
+getgrent(void)
+{
+       int             rv;
+       struct group    *retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getgrent, NULL)
+               NS_DNS_CB(_dns_getgrent, NULL)
+               NS_NIS_CB(_nis_getgrent, NULL)
+               NS_COMPAT_CB(_compat_getgrent, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&__grmutex);
+       rv = nsdispatch(NULL, dtab, NSDB_GROUP, "getgrent", __nsdefaultcompat,
+           &retval);
+       mutex_unlock(&__grmutex);
+       return (rv == NS_SUCCESS) ? retval : NULL;
+}
+
+int
+getgrent_r(struct group *grp, char *buffer, size_t buflen,
+    struct group **result)
+{
+       int             rv, retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getgrent_r, NULL)
+               NS_DNS_CB(_dns_getgrent_r, NULL)
+               NS_NIS_CB(_nis_getgrent_r, NULL)
+               NS_COMPAT_CB(_compat_getgrent_r, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&__grmutex);
+       rv = nsdispatch(NULL, dtab, NSDB_GROUP, "getgrent_r", __nsdefaultcompat,
+           &retval, grp, buffer, buflen, result);
+       mutex_unlock(&__grmutex);
+       switch (rv) {
+       case NS_SUCCESS:
+       case NS_NOTFOUND:
+               return 0;
+       default:
+               return retval;
+       }
+}
+
+
+struct group *
+getgrgid(gid_t gid)
+{
+       int             rv;
+       struct group    *retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getgrgid, NULL)
+               NS_DNS_CB(_dns_getgrgid, NULL)
+               NS_NIS_CB(_nis_getgrgid, NULL)
+               NS_COMPAT_CB(_compat_getgrgid, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&__grmutex);
+       rv = nsdispatch(NULL, dtab, NSDB_GROUP, "getgrgid", __nsdefaultcompat,
+           &retval, gid);
+       mutex_unlock(&__grmutex);
+       return (rv == NS_SUCCESS) ? retval : NULL;
+}
+
+int
+getgrgid_r(gid_t gid, struct group *grp, char *buffer, size_t buflen,
+       struct group **result)
+{
+       int     rv, retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getgrgid_r, NULL)
+               NS_DNS_CB(_dns_getgrgid_r, NULL)
+               NS_NIS_CB(_nis_getgrgid_r, NULL)
+               NS_COMPAT_CB(_compat_getgrgid_r, NULL)
+               NS_NULL_CB
+       };
+
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       retval = 0;
+       mutex_lock(&__grmutex);
+       rv = nsdispatch(NULL, dtab, NSDB_GROUP, "getgrgid_r", __nsdefaultcompat,
+           &retval, gid, grp, buffer, buflen, result);
+       mutex_unlock(&__grmutex);
+       switch (rv) {
+       case NS_SUCCESS:
+       case NS_NOTFOUND:
+               return 0;
+       default:
+               return retval;
+       }
+}
+
+struct group *
+getgrnam(const char *name)
+{
+       int             rv;
+       struct group    *retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getgrnam, NULL)
+               NS_DNS_CB(_dns_getgrnam, NULL)
+               NS_NIS_CB(_nis_getgrnam, NULL)
+               NS_COMPAT_CB(_compat_getgrnam, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&__grmutex);
+       rv = nsdispatch(NULL, dtab, NSDB_GROUP, "getgrnam", __nsdefaultcompat,
+           &retval, name);
+       mutex_unlock(&__grmutex);
+       return (rv == NS_SUCCESS) ? retval : NULL;
+}
+
+int
+getgrnam_r(const char *name, struct group *grp, char *buffer, size_t buflen,
+       struct group **result)
+{
+       int     rv, retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getgrnam_r, NULL)
+               NS_DNS_CB(_dns_getgrnam_r, NULL)
+               NS_NIS_CB(_nis_getgrnam_r, NULL)
+               NS_COMPAT_CB(_compat_getgrnam_r, NULL)
+               NS_NULL_CB
+       };
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(grp != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       retval = 0;
+       mutex_lock(&__grmutex);
+       rv = nsdispatch(NULL, dtab, NSDB_GROUP, "getgrnam_r", __nsdefaultcompat,
+           &retval, name, grp, buffer, buflen, result);
+       mutex_unlock(&__grmutex);
+       switch (rv) {
+       case NS_SUCCESS:
+       case NS_NOTFOUND:
+               return 0;
+       default:
+               return retval;
+       }
+}
+
+void
+endgrent(void)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_endgrent, NULL)
+               NS_DNS_CB(_dns_endgrent, NULL)
+               NS_NIS_CB(_nis_endgrent, NULL)
+               NS_COMPAT_CB(_compat_endgrent, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&__grmutex);
+                                       /* force all endgrent() methods */
+       (void) nsdispatch(NULL, dtab, NSDB_GROUP, "endgrent",
+           __nsdefaultcompat_forceall);
+       mutex_unlock(&__grmutex);
+}
+
+int
+setgroupent(int stayopen)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_setgroupent, NULL)
+               NS_DNS_CB(_dns_setgroupent, NULL)
+               NS_NIS_CB(_nis_setgroupent, NULL)
+               NS_COMPAT_CB(_compat_setgroupent, NULL)
+               NS_NULL_CB
+       };
+       int     rv, retval;
+
+       mutex_lock(&__grmutex);
+                                       /* force all setgroupent() methods */
+       rv = nsdispatch(NULL, dtab, NSDB_GROUP, "setgroupent",
+           __nsdefaultcompat_forceall, &retval, stayopen);
+       mutex_unlock(&__grmutex);
+       return (rv == NS_SUCCESS) ? retval : 0;
+}
+
+void
+setgrent(void)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_setgrent, NULL)
+               NS_DNS_CB(_dns_setgrent, NULL)
+               NS_NIS_CB(_nis_setgrent, NULL)
+               NS_COMPAT_CB(_compat_setgrent, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&__grmutex);
+                                       /* force all setgrent() methods */
+       (void) nsdispatch(NULL, dtab, NSDB_GROUP, "setgrent",
+           __nsdefaultcompat_forceall);
+       mutex_unlock(&__grmutex);
+}
diff --git a/lib/nbsd_libc/gen/getgrouplist.3 b/lib/nbsd_libc/gen/getgrouplist.3
new file mode 100644 (file)
index 0000000..7638ab0
--- /dev/null
@@ -0,0 +1,152 @@
+.\"    $NetBSD: getgrouplist.3,v 1.14 2008/05/02 18:11:04 martin Exp $
+.\"
+.\" Copyright (c) 2005 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Luke Mewburn.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getgrouplist.3     8.1 (Berkeley) 6/9/93
+.\"
+.Dd January 6, 2005
+.Dt GETGROUPLIST 3
+.Os
+.Sh NAME
+.Nm getgrouplist ,
+.Nm getgroupmembership ,
+.Nd calculate group access list
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn getgrouplist "const char *name" "gid_t basegid" "gid_t *groups" "int *ngroups"
+.Ft int
+.Fn getgroupmembership "const char *name" "gid_t basegid" "gid_t *groups" "int maxgrp" "int *ngroups"
+.Sh DESCRIPTION
+The
+.Fn getgrouplist
+and
+.Fn getgroupmembership
+functions read through the group database and calculate
+the group access list for the user specified in
+.Fa name .
+The
+.Fa basegid
+is automatically included in the groups list.
+Typically this value is given as
+the group number from the password database.
+.Pp
+The resulting group list is returned in the integer array pointed to by
+.Fa groups .
+.Pp
+For
+.Fn getgrouplist ,
+the caller specifies the size of the
+.Fa groups
+array in the integer pointed to by
+.Fa ngroups .
+.Pp
+For
+.Fn getgroupmembership ,
+the caller specifies the size of the
+.Fa groups
+array in
+.Fa maxgrp .
+.Pp
+The actual number of groups found is returned in
+.Fa ngroups .
+.Pp
+Duplicate group ids will be suppressed from the result.
+.Sh RETURN VALUES
+The
+.Fn getgrouplist
+and
+.Fn getgroupmembership
+functions
+return 0 if successful, and
+return \-1 if the size of the group list is too small to
+hold all the user's groups.
+In the latter case, the
+.Fa groups
+array will be filled with as many groups as will fit and
+.Fa ngroups
+will contain the total number of groups found.
+.Sh FILES
+.Bl -tag -width /etc/group -compact
+.It Pa /etc/group
+group membership list
+.El
+.Sh SEE ALSO
+.Xr setgroups 2 ,
+.Xr initgroups 3 ,
+.Xr group 5
+.Sh HISTORY
+The
+.Fn getgrouplist
+function first appeared in
+.Bx 4.4 .
+The
+.Fn getgroupmembership
+function first appeared in
+.Nx 3.0
+to address an API deficiency in
+.Fn getgrouplist .
+.Sh BUGS
+The
+.Fn getgrouplist
+function
+uses the routines based on
+.Xr getgrent 3 .
+If the invoking program uses any of these routines,
+the group structure will
+be overwritten in the call to
+.Fn getgrouplist .
diff --git a/lib/nbsd_libc/gen/getgrouplist.c b/lib/nbsd_libc/gen/getgrouplist.c
new file mode 100644 (file)
index 0000000..cd152ec
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: getgrouplist.c,v 1.22 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 2004-2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Luke Mewburn.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getgrouplist.c     8.2 (Berkeley) 12/8/94";
+#else
+__RCSID("$NetBSD: getgrouplist.c,v 1.22 2008/04/28 20:22:59 martin Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * calculate group access list
+ */
+
+#include "namespace.h"
+#include <sys/param.h>
+
+#include <assert.h>
+#include <nsswitch.h>
+#include <stdarg.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(getgrouplist,_getgrouplist)
+#endif
+
+int
+getgrouplist(const char *uname, gid_t agroup, gid_t *groups, int *grpcnt)
+{
+       int     rv, groupc;
+
+       _DIAGASSERT(uname != NULL);
+       /* groups may be NULL if just sizing when invoked with *grpcnt = 0 */
+       _DIAGASSERT(grpcnt != NULL);
+
+       groupc = 0;
+       rv = getgroupmembership(uname, agroup, groups, *grpcnt, &groupc);
+       *grpcnt = groupc;       /* set groupc to the actual # of groups */
+       return rv;
+}
diff --git a/lib/nbsd_libc/gen/getgroupmembership.c b/lib/nbsd_libc/gen/getgroupmembership.c
new file mode 100644 (file)
index 0000000..78687c0
--- /dev/null
@@ -0,0 +1,405 @@
+/*     $NetBSD: getgroupmembership.c,v 1.4 2008/04/28 20:22:59 martin Exp $    */
+
+/*-
+ * Copyright (c) 2004-2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Luke Mewburn.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getgroupmembership.c,v 1.4 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * calculate group access list
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+
+#include <sys/param.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <grp.h>
+#include <limits.h>
+#include <nsswitch.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef HESIOD
+#include <hesiod.h>
+#endif
+
+#include "gr_private.h"
+
+#ifdef __weak_alias
+__weak_alias(getgroupmembership,_getgroupmembership)
+#endif
+
+/*
+ * __gr_addgid
+ *     Add gid to the groups array (of maxgrp size) at the position
+ *     indicated by *groupc, unless it already exists or *groupc is
+ *     past &groups[maxgrp].
+ *     Returns 1 upon success (including duplicate suppression), 0 otherwise.
+ */
+static int
+__gr_addgid(gid_t gid, gid_t *groups, int maxgrp, int *groupc)
+{
+       int     ret, dupc;
+
+       _DIAGASSERT(groupc != NULL);
+       _DIAGASSERT(groups != NULL);
+
+                                               /* skip duplicates */
+       for (dupc = 0; dupc < MIN(maxgrp, *groupc); dupc++) {
+               if (groups[dupc] == gid)
+                       return 1;
+       }
+
+       ret = 1;
+       if (*groupc < maxgrp)                   /* add this gid */
+               groups[*groupc] = gid;
+       else
+               ret = 0;
+       (*groupc)++;
+       return ret;
+}
+
+
+/*ARGSUSED*/
+static int
+_files_getgroupmembership(void *retval, void *cb_data, va_list ap)
+{
+       int             *result = va_arg(ap, int *);
+       const char      *uname  = va_arg(ap, const char *);
+       gid_t            agroup = va_arg(ap, gid_t);
+       gid_t           *groups = va_arg(ap, gid_t *);
+       int              maxgrp = va_arg(ap, int);
+       int             *groupc = va_arg(ap, int *);
+
+       struct __grstate_files  state;
+       struct group            grp;
+       char                    grpbuf[_GETGR_R_SIZE_MAX];
+       int                     rv, i;
+
+       _DIAGASSERT(result != NULL);
+       _DIAGASSERT(uname != NULL);
+       /* groups may be NULL if just sizing when invoked with maxgrp = 0 */
+       _DIAGASSERT(groupc != NULL);
+
+                                               /* install primary group */
+       (void) __gr_addgid(agroup, groups, maxgrp, groupc);
+
+       memset(&state, 0, sizeof(state));
+       while (__grscan_files(&rv, &grp, grpbuf, sizeof(grpbuf), &state,
+                               0, NULL, 0) == NS_SUCCESS) {
+                                               /* scan members */
+               for (i = 0; grp.gr_mem[i]; i++) {
+                       if (strcmp(grp.gr_mem[i], uname) != 0)
+                               continue;
+                       if (! __gr_addgid(grp.gr_gid, groups, maxgrp, groupc))
+                               *result = -1;
+                       break;
+               }
+       }
+       __grend_files(&state);
+       return NS_NOTFOUND;
+}
+
+
+#ifdef HESIOD
+
+/*ARGSUSED*/
+static int
+_dns_getgroupmembership(void *retval, void *cb_data, va_list ap)
+{
+       int             *result = va_arg(ap, int *);
+       const char      *uname  = va_arg(ap, const char *);
+       gid_t            agroup = va_arg(ap, gid_t);
+       gid_t           *groups = va_arg(ap, gid_t *);
+       int              maxgrp = va_arg(ap, int);
+       int             *groupc = va_arg(ap, int *);
+
+       struct __grstate_dns    state;
+       struct group            grp;
+       char                    grpbuf[_GETGR_R_SIZE_MAX];
+       unsigned long           id;
+       void                    *context;
+       char                    **hp, *cp, *ep;
+       int                     rv, i;
+
+       _DIAGASSERT(result != NULL);
+       _DIAGASSERT(uname != NULL);
+       /* groups may be NULL if just sizing when invoked with maxgrp = 0 */
+       _DIAGASSERT(groupc != NULL);
+
+                                               /* install primary group */
+       (void) __gr_addgid(agroup, groups, maxgrp, groupc);
+
+       hp = NULL;
+       rv = NS_NOTFOUND;
+
+       if (hesiod_init(&context) == -1)                /* setup hesiod */
+               return NS_UNAVAIL;
+
+       hp = hesiod_resolve(context, uname, "grplist"); /* find grplist */
+       if (hp == NULL) {
+               if (errno != ENOENT) {                  /* wasn't "not found"*/
+                       rv = NS_UNAVAIL;
+                       goto dnsgroupmembers_out;
+               }
+                       /* grplist not found, fallback to _dns_grscan */
+               memset(&state, 0, sizeof(state));
+               while (__grscan_dns(&rv, &grp, grpbuf, sizeof(grpbuf), &state,
+                                       0, NULL, 0) == NS_SUCCESS) {
+                                                       /* scan members */
+                       for (i = 0; grp.gr_mem[i]; i++) {
+                               if (strcmp(grp.gr_mem[i], uname) != 0)
+                                       continue;
+                               if (! __gr_addgid(grp.gr_gid, groups, maxgrp,
+                                   groupc))
+                                       *result = -1;
+                               break;
+                       }
+               }
+               __grend_dns(&state);
+               rv = NS_NOTFOUND;
+               goto dnsgroupmembers_out;
+       }
+
+       if ((ep = strchr(hp[0], '\n')) != NULL)
+               *ep = '\0';                             /* clear trailing \n */
+
+       for (cp = hp[0]; *cp != '\0'; ) {               /* parse grplist */
+               if ((cp = strchr(cp, ':')) == NULL)     /* skip grpname */
+                       break;
+               cp++;
+               id = strtoul(cp, &ep, 10);              /* parse gid */
+               if (id > GID_MAX || (*ep != ':' && *ep != '\0')) {
+                       rv = NS_UNAVAIL;
+                       goto dnsgroupmembers_out;
+               }
+               cp = ep;
+               if (*cp == ':')
+                       cp++;
+
+                                                       /* add gid */
+               if (! __gr_addgid((gid_t)id, groups, maxgrp, groupc))
+                       *result = -1;
+       }
+
+       rv = NS_NOTFOUND;
+
+ dnsgroupmembers_out:
+       if (hp)
+               hesiod_free_list(context, hp);
+       hesiod_end(context);
+       return rv;
+}
+
+#endif /* HESIOD */
+
+
+#ifdef YP
+
+/*ARGSUSED*/
+static int
+_nis_getgroupmembership(void *retval, void *cb_data, va_list ap)
+{
+       int             *result = va_arg(ap, int *);
+       const char      *uname  = va_arg(ap, const char *);
+       gid_t            agroup = va_arg(ap, gid_t);
+       gid_t           *groups = va_arg(ap, gid_t *);
+       int              maxgrp = va_arg(ap, int);
+       int             *groupc = va_arg(ap, int *);
+
+       struct __grstate_nis    state;
+       struct group            grp;
+       char                    grpbuf[_GETGR_R_SIZE_MAX];
+       int                     rv, i;
+
+       _DIAGASSERT(result != NULL);
+       _DIAGASSERT(uname != NULL);
+       /* groups may be NULL if just sizing when invoked with maxgrp = 0 */
+       _DIAGASSERT(groupc != NULL);
+
+                                               /* install primary group */
+       (void) __gr_addgid(agroup, groups, maxgrp, groupc);
+
+       memset(&state, 0, sizeof(state));
+       while (__grscan_nis(&rv, &grp, grpbuf, sizeof(grpbuf), &state,
+                               0, NULL, 0) == NS_SUCCESS) {
+                                               /* scan members */
+               for (i = 0; grp.gr_mem[i]; i++) {
+                       if (strcmp(grp.gr_mem[i], uname) != 0)
+                               continue;
+                       if (! __gr_addgid(grp.gr_gid, groups, maxgrp, groupc))
+                               *result = -1;
+                       break;
+               }
+       }
+       __grend_nis(&state);
+
+       return NS_NOTFOUND;
+}
+
+#endif /* YP */
+
+
+#ifdef _GROUP_COMPAT
+
+struct __compatggm {
+       const char      *uname;         /* user to search for */
+       gid_t           *groups;
+       gid_t            agroup;
+       int              maxgrp;
+       int             *groupc;
+};
+
+static int
+_compat_ggm_search(void *cookie, struct group **groupres)
+{
+       struct __compatggm      *cp;
+       int                     rerror, crv;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(__grbad_compat, "files")
+               NS_DNS_CB(_dns_getgroupmembership, NULL)
+               NS_NIS_CB(_nis_getgroupmembership, NULL)
+               NS_COMPAT_CB(__grbad_compat, "compat")
+               NS_NULL_CB
+       };
+
+       *groupres = NULL;       /* we don't care about this */
+       cp = (struct __compatggm *)cookie;
+
+       crv = nsdispatch(NULL, dtab,
+           NSDB_GROUP_COMPAT, "getgroupmembership",
+           __nsdefaultnis,
+           &rerror, cp->uname, cp->agroup, cp->groups, cp->maxgrp, cp->groupc);
+
+       if (crv == NS_SUCCESS)
+               crv = NS_NOTFOUND;      /* indicate "no more +: entries" */
+
+       return crv;
+}
+
+/* ARGSUSED */
+static int
+_compat_getgroupmembership(void *retval, void *cb_data, va_list ap)
+{
+       int             *result = va_arg(ap, int *);
+       const char      *uname  = va_arg(ap, const char *);
+       gid_t            agroup = va_arg(ap, gid_t);
+       gid_t           *groups = va_arg(ap, gid_t *);
+       int              maxgrp = va_arg(ap, int);
+       int             *groupc = va_arg(ap, int *);
+
+       struct __grstate_compat state;
+       struct __compatggm      ggmstate;
+       struct group            grp;
+       char                    grpbuf[_GETGR_R_SIZE_MAX];
+       int                     rv, i;
+
+       _DIAGASSERT(result != NULL);
+       _DIAGASSERT(uname != NULL);
+       /* groups may be NULL if just sizing when invoked with maxgrp = 0 */
+       _DIAGASSERT(groupc != NULL);
+
+                                               /* install primary group */
+       (void) __gr_addgid(agroup, groups, maxgrp, groupc);
+
+       memset(&state, 0, sizeof(state));
+       memset(&ggmstate, 0, sizeof(ggmstate));
+       ggmstate.uname = uname;
+       ggmstate.groups = groups;
+       ggmstate.agroup = agroup;
+       ggmstate.maxgrp = maxgrp;
+       ggmstate.groupc = groupc;
+
+       while (__grscan_compat(&rv, &grp, grpbuf, sizeof(grpbuf), &state,
+                               0, NULL, 0, _compat_ggm_search, &ggmstate)
+               == NS_SUCCESS) {
+                                               /* scan members */
+               for (i = 0; grp.gr_mem[i]; i++) {
+                       if (strcmp(grp.gr_mem[i], uname) != 0)
+                               continue;
+                       if (! __gr_addgid(grp.gr_gid, groups, maxgrp, groupc))
+                               *result = -1;
+                       break;
+               }
+       }
+
+       __grend_compat(&state);
+       return NS_NOTFOUND;
+}
+
+#endif /* _GROUP_COMPAT */
+
+
+int
+getgroupmembership(const char *uname, gid_t agroup,
+    gid_t *groups, int maxgrp, int *groupc)
+{
+       int     rerror;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getgroupmembership, NULL)
+               NS_DNS_CB(_dns_getgroupmembership, NULL)
+               NS_NIS_CB(_nis_getgroupmembership, NULL)
+               NS_COMPAT_CB(_compat_getgroupmembership, NULL)
+               NS_NULL_CB
+       };
+
+       _DIAGASSERT(uname != NULL);
+       /* groups may be NULL if just sizing when invoked with maxgrp = 0 */
+       _DIAGASSERT(groupc != NULL);
+
+       *groupc = 0;
+
+       mutex_lock(&__grmutex);
+                       /*
+                        * Call each backend.
+                        * For compatibility with getgrent(3) semantics,
+                        * a backend should return NS_NOTFOUND even upon
+                        * completion, to allow result merging to occur.
+                        */
+       (void) nsdispatch(NULL, dtab, NSDB_GROUP, "getgroupmembership",
+           __nsdefaultcompat,
+           &rerror, uname, agroup, groups, maxgrp, groupc);
+       mutex_unlock(&__grmutex);
+
+       if (*groupc > maxgrp)                   /* too many groups found */
+               return -1;
+       else
+               return 0;
+}
diff --git a/lib/nbsd_libc/gen/gethostname.3 b/lib/nbsd_libc/gen/gethostname.3
new file mode 100644 (file)
index 0000000..23b5be2
--- /dev/null
@@ -0,0 +1,101 @@
+.\"    $NetBSD: gethostname.3,v 1.17 2006/02/07 18:59:56 wiz Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)gethostname.3      8.1 (Berkeley) 6/4/93
+.\"
+.Dd October 14, 2005
+.Dt GETHOSTNAME 3
+.Os
+.Sh NAME
+.Nm gethostname ,
+.Nm sethostname
+.Nd get/set name of current host
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn gethostname "char *name" "size_t namelen"
+.Ft int
+.Fn sethostname "const char *name" "size_t namelen"
+.Sh DESCRIPTION
+.Fn gethostname
+returns the standard host name for the current processor, as
+previously set by
+.Fn sethostname .
+The parameter
+.Fa namelen
+specifies the size of the
+.Fa name
+array.
+The returned name is null-terminated unless insufficient
+space is provided.
+.Pp
+.Fn sethostname
+sets the name of the host machine to be
+.Fa name ,
+which has length
+.Fa namelen .
+This call is restricted to the super-user and
+is normally used only when the system is bootstrapped.
+.Sh RETURN VALUES
+If the call succeeds a value of 0 is returned.
+If the call fails, a value of \-1 is returned and an error code is
+placed in the global location
+.Va errno .
+.Sh ERRORS
+If the
+.Fn gethostname
+or
+.Fn sethostname
+functions fail,
+they will set
+.Va errno
+for any of the errors specified for the routine
+.Xr sysctl 3 .
+.Sh SEE ALSO
+.Xr gethostid 3 ,
+.Xr sysctl 3 ,
+.Xr sysctl 8
+.Sh STANDARDS
+The
+.Fn gethostname
+function conforms to
+.St -xpg4.2 .
+.Sh HISTORY
+The
+.Nm
+function call appeared in
+.Bx 4.2 .
+.Sh BUGS
+Host names are limited to
+.Dv MAXHOSTNAMELEN
+(from
+.Ao Pa sys/param.h Ac )
+characters including null-termination, currently 256.
diff --git a/lib/nbsd_libc/gen/gethostname.c b/lib/nbsd_libc/gen/gethostname.c
new file mode 100644 (file)
index 0000000..eba55d1
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: gethostname.c,v 1.12 2005/10/14 23:53:41 christos Exp $        */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)gethostname.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: gethostname.c,v 1.12 2005/10/14 23:53:41 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/sysctl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(gethostname,_gethostname)
+#endif
+
+int
+gethostname(name, namelen)
+       char *name;
+       size_t namelen;
+{
+       int mib[2];
+       size_t size;
+
+       _DIAGASSERT(name != NULL);
+
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_HOSTNAME;
+       size = namelen;
+       if (sysctl(mib, 2, name, &size, NULL, 0) == -1)
+               return (-1);
+
+       return (0);
+}
diff --git a/lib/nbsd_libc/gen/getlastlogx.3 b/lib/nbsd_libc/gen/getlastlogx.3
new file mode 100644 (file)
index 0000000..cb7404c
--- /dev/null
@@ -0,0 +1,173 @@
+.\"    $NetBSD: getlastlogx.3,v 1.2 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Thomas Klausner.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd August 26, 2003
+.Dt GETLASTLOGX 3
+.Os
+.Sh NAME
+.Nm getlastlogx ,
+.Nm getutmp ,
+.Nm getutmpx ,
+.Nm updlastlogx ,
+.Nm updwtmpx ,
+.Nm utmpxname
+.Nd user accounting database functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In utmpx.h
+.Ft struct lastlogx *
+.Fn getlastlogx "const char *fname" "uid_t uid" "struct lastlogx *ll"
+.Ft void
+.Fn getutmp "const struct utmpx *ux" "struct utmp *u"
+.Ft void
+.Fn getutmpx "const struct utmp *u" "struct utmpx *ux"
+.Ft int
+.Fn updlastlogx "const char *fname" "uid_t uid" "struct lastlogx *ll"
+.Ft int
+.Fn updwtmpx "const char *file" "const struct utmpx *utx"
+.Ft int
+.Fn utmpxname "const char *fname"
+.Sh DESCRIPTION
+The
+.Fn getlastlogx
+function looks up the entry for the user with user id
+.Fa uid
+in the
+.Xr lastlogx 5
+file given by
+.Fa fname
+and returns it in
+.Fa \&ll .
+If the provided
+.Fa \&ll
+is
+.Dv NULL ,
+the necessary space will be allocated by
+.Fn getlastlogx
+and should be
+.Fn free Ns d
+by the caller.
+.Pp
+The
+.Fn getutmp
+function fills out the entries in the struct utmp
+.Fa u
+with the data provided in the struct utmpx
+.Fa ux .
+.Fn getutmpx
+does the opposite, filling out the entries in the struct utmpx
+.Fa ux
+with the data provided in the struct utmp
+.Fa u ,
+and initializing all the unknown fields to 0.
+The sole exception is the
+.Fa ut_type
+field, which will be initialized to
+.Dv USER_PROCESS .
+.Pp
+The
+.Fn updlastlogx
+function tries to update the information for the user with the user id
+.Fa uid
+in the
+.Xr lastlogx 5
+file given by
+.Fa fname
+with the data supplied in
+.Fa \&ll .
+A
+.Ft struct lastlogx
+is defined like this:
+.Bd -literal
+struct lastlogx {
+        struct timeval ll_tv;           /* time entry was created */
+        char ll_line[_UTX_LINESIZE];    /* tty name */
+        char ll_host[_UTX_HOSTSIZE];    /* host name */
+        struct sockaddr_storage ll_ss;  /* address where entry was made from */
+};
+.Ed
+All the fields should be filled out by the caller.
+.Pp
+The
+.Fn updwtmpx
+function updates the
+.Xr wtmpx 5
+file
+.Fa file
+with the
+.Xr utmpx 5
+entry
+.Fa utx .
+.Pp
+The
+.Fn utmpxname
+function sets the default
+.Xr utmpx 5
+database file name to
+.Fa fname .
+.Sh RETURN VALUES
+.Fn getlastlogx
+returns the found entry on success, or
+.Dv NULL
+if it could not open the database, could not find an entry matching
+.Fa uid
+in there, or could not allocate the necessary space (in case
+.Fa \&ll
+was
+.Dv NULL ) .
+.Pp
+.Fn utmpxname
+returns 1 on success, or 0 if the supplied file name was too long or
+did not end with
+.Sq x .
+.Pp
+.Fn updlastlogx
+and
+.Fn updwtmpx
+return 0 on success, or \-1 in case the database or file respectively
+could not be opened or the data not written into it.
+.Sh SEE ALSO
+.Xr endutxent 3 ,
+.Xr loginx 3 ,
+.Xr utmpx 5
+.Sh HISTORY
+The functions
+.Fn getutmp ,
+.Fn getutmpx ,
+.Fn updwtmpx ,
+and
+.Fn utmpxname
+first appeared in
+.Tn Solaris .
+.Nm getlastlogx
+and
+.Nm updlastlogx
+first appeared in
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/gen/getloadavg.3 b/lib/nbsd_libc/gen/getloadavg.3
new file mode 100644 (file)
index 0000000..954992a
--- /dev/null
@@ -0,0 +1,66 @@
+.\"    $NetBSD: getloadavg.3,v 1.14 2003/08/07 16:42:50 agc Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getloadavg.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt GETLOADAVG 3
+.Os
+.Sh NAME
+.Nm getloadavg
+.Nd get system load averages
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn getloadavg "double loadavg[]" "int nelem"
+.Sh DESCRIPTION
+The
+.Fn getloadavg
+function returns the number of processes in the system run queue
+averaged over various periods of time.
+Up to
+.Fa nelem
+samples are retrieved and assigned to successive elements of
+.Fa loadavg Ns Bq .
+The system imposes a maximum of 3 samples, representing averages
+over the last 1, 5, and 15 minutes, respectively.
+.Sh DIAGNOSTICS
+If the load average was unobtainable, \-1 is returned; otherwise,
+the number of samples actually retrieved is returned.
+.Sh SEE ALSO
+.Xr uptime 1 ,
+.Xr kvm_getloadavg 3 ,
+.Xr sysctl 3
+.Sh HISTORY
+The
+.Fn getloadavg
+function appeared in
+.Bx 4.3 Reno .
diff --git a/lib/nbsd_libc/gen/getloadavg.c b/lib/nbsd_libc/gen/getloadavg.c
new file mode 100644 (file)
index 0000000..870bb31
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: getloadavg.c,v 1.13 2003/08/07 16:42:50 agc Exp $      */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getloadavg.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getloadavg.c,v 1.13 2003/08/07 16:42:50 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+#include <sys/sysctl.h>
+#include <uvm/uvm_param.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(getloadavg,_getloadavg)
+#endif
+
+/*
+ * getloadavg() -- Get system load averages.
+ *
+ * Put `nelem' samples into `loadavg' array.
+ * Return number of samples retrieved, or -1 on error.
+ */
+int
+getloadavg(loadavg, nelem)
+       double loadavg[];
+       int nelem;
+{
+       struct loadavg loadinfo;
+       int i, mib[2];
+       size_t size;
+
+       _DIAGASSERT(loadavg != NULL);
+       _DIAGASSERT(nelem >= 0);
+
+       mib[0] = CTL_VM;
+       mib[1] = VM_LOADAVG;
+       size = sizeof(loadinfo);
+       if (sysctl(mib, 2, &loadinfo, &size, NULL, 0) < 0)
+               return (-1);
+
+       nelem = MIN((size_t) nelem, sizeof(loadinfo.ldavg) / sizeof(fixpt_t));
+       for (i = 0; i < nelem; i++)
+               loadavg[i] = (double) loadinfo.ldavg[i] / loadinfo.fscale;
+       return (nelem);
+}
diff --git a/lib/nbsd_libc/gen/getlogin.c b/lib/nbsd_libc/gen/getlogin.c
new file mode 100644 (file)
index 0000000..b0abc58
--- /dev/null
@@ -0,0 +1,146 @@
+/*     $NetBSD: getlogin.c,v 1.15 2009/01/11 02:46:27 christos Exp $   */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getlogin.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getlogin.c,v 1.15 2009/01/11 02:46:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <pwd.h>
+#include <utmp.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include "reentrant.h"
+#include "extern.h"
+
+#ifdef __weak_alias
+__weak_alias(getlogin,_getlogin)
+__weak_alias(getlogin_r,_getlogin_r)
+__weak_alias(setlogin,_setlogin)
+#endif
+
+int    __logname_valid;                /* known to setlogin() */
+static char logname[MAXLOGNAME + 1];
+
+#ifdef _REENTRANT
+static mutex_t logname_mutex = MUTEX_INITIALIZER;
+#endif
+
+char *
+getlogin(void)
+{
+       char *rv;
+
+       mutex_lock(&logname_mutex);
+       if (__logname_valid == 0) {
+               if (__getlogin(logname, sizeof(logname) - 1) < 0) {
+                       mutex_unlock(&logname_mutex);
+                       return ((char *)NULL);
+               }
+               __logname_valid = 1;
+       }
+       rv = (*logname ? logname : (char *)NULL);
+       mutex_unlock(&logname_mutex);
+
+       return rv;
+}
+
+int
+getlogin_r(char *name, size_t namelen)
+{
+       size_t len;
+       int rv;
+
+       mutex_lock(&logname_mutex);
+       if (__logname_valid == 0) {
+               if (__getlogin(logname, sizeof(logname) - 1) < 0) {
+                       rv = errno;
+                       mutex_unlock(&logname_mutex);
+                       return (rv);
+               }
+               __logname_valid = 1;
+       }
+       len = strlen(logname) + 1;
+       if (len > namelen) {
+               rv = ERANGE;
+       } else {
+               strncpy(name, logname, len);
+               rv = 0;
+       }
+       mutex_unlock(&logname_mutex);
+
+       return (rv);
+}
+
+int
+setlogin(const char *name)
+{
+       int retval; 
+
+       retval = __setlogin(name);
+       __logname_valid = 0;
+
+       return (retval);
+}
diff --git a/lib/nbsd_libc/gen/getmntinfo.3 b/lib/nbsd_libc/gen/getmntinfo.3
new file mode 100644 (file)
index 0000000..1b2227b
--- /dev/null
@@ -0,0 +1,115 @@
+.\"    $NetBSD: getmntinfo.3,v 1.15 2004/05/05 08:48:36 jdolecek Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getmntinfo.3       8.1 (Berkeley) 6/9/93
+.\"
+.Dd April 14, 2004
+.Dt GETMNTINFO 3
+.Os
+.Sh NAME
+.Nm getmntinfo
+.Nd get information about mounted file systems
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/statvfs.h
+.Ft int
+.Fn getmntinfo "struct statvfs **mntbufp" "int flags"
+.Sh DESCRIPTION
+The
+.Fn getmntinfo
+function returns an array of
+.Em statvfs
+structures describing each currently mounted file system (see
+.Xr statvfs 2 ) .
+.Pp
+The
+.Fn getmntinfo
+function
+passes its
+.Fa flags
+parameter transparently to
+.Xr getvfsstat 2 .
+.Sh RETURN VALUES
+On successful completion,
+.Fn getmntinfo
+returns a count of the number of elements in the array.
+The pointer to the array is stored into
+.Fa mntbufp .
+.Pp
+If an error occurs, zero is returned and the external variable
+.Va errno
+is set to indicate the error.
+Although the pointer
+.Fa mntbufp
+will be unmodified, any information previously returned by
+.Fn getmntinfo
+will be lost.
+.Sh ERRORS
+The
+.Fn getmntinfo
+function
+may fail and set
+.Va errno
+for any of the errors specified for the library routines
+.Xr getvfsstat 2
+or
+.Xr malloc 3 .
+.Sh SEE ALSO
+.Xr getvfsstat 2 ,
+.Xr mount 2 ,
+.Xr statvfs 2 ,
+.Xr mount 8
+.Sh HISTORY
+The
+.Fn getmntinfo
+function first appeared in
+.Bx 4.4 .
+It was converted from using
+.Xr getfsstat 2
+to
+.Xr getvfsstat 2
+in
+.Nx 3.0 .
+.Sh BUGS
+The
+.Fn getmntinfo
+function writes the array of structures to an internal static object
+and returns
+a pointer to that object.
+Subsequent calls to
+.Fn getmntinfo
+will modify the same object.
+.Pp
+The memory allocated by
+.Fn getmntinfo
+cannot be
+.Xr free 3 Ns 'd
+by the application.
diff --git a/lib/nbsd_libc/gen/getmntinfo.c b/lib/nbsd_libc/gen/getmntinfo.c
new file mode 100644 (file)
index 0000000..62eca75
--- /dev/null
@@ -0,0 +1,81 @@
+/*     $NetBSD: getmntinfo.c,v 1.16 2005/09/13 01:44:09 christos Exp $ */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getmntinfo.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getmntinfo.c,v 1.16 2005/09/13 01:44:09 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/ucred.h>
+#include <sys/mount.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+
+/*
+ * Return information about mounted filesystems.
+ */
+int
+getmntinfo(mntbufp, flags)
+       struct statvfs **mntbufp;
+       int flags;
+{
+       static struct statvfs *mntbuf;
+       static int mntsize;
+       static size_t bufsize;
+
+       _DIAGASSERT(mntbufp != NULL);
+
+       if (mntsize <= 0 &&
+           (mntsize = getvfsstat(NULL, (size_t)0, MNT_NOWAIT)) == -1)
+               return (0);
+       if (bufsize > 0 &&
+           (mntsize = getvfsstat(mntbuf, bufsize, flags)) == -1)
+               return (0);
+       while (bufsize <= mntsize * sizeof(struct statvfs)) {
+               if (mntbuf)
+                       free(mntbuf);
+               bufsize = (mntsize + 1) * sizeof(struct statvfs);
+               if ((mntbuf = malloc(bufsize)) == NULL)
+                       return (0);
+               if ((mntsize = getvfsstat(mntbuf, bufsize, flags)) == -1)
+                       return (0);
+       }
+       *mntbufp = mntbuf;
+       return (mntsize);
+}
diff --git a/lib/nbsd_libc/gen/getnetgrent.3 b/lib/nbsd_libc/gen/getnetgrent.3
new file mode 100644 (file)
index 0000000..7e45693
--- /dev/null
@@ -0,0 +1,124 @@
+.\"    $NetBSD: getnetgrent.3,v 1.12 2003/08/07 16:42:50 agc Exp $
+.\"
+.\" Copyright (c) 1992, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getnetgrent.3      8.1 (Berkeley) 6/4/93
+.\"
+.Dd January 16, 1999
+.Dt GETNETGRENT 3
+.Os
+.Sh NAME
+.Nm getnetgrent ,
+.Nm innetgr ,
+.Nm setnetgrent ,
+.Nm endnetgrent
+.Nd netgroup database operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In netgroup.h
+.Ft int
+.Fn getnetgrent "const char **host" "const char **user" "const char **domain"
+.Ft int
+.Fn innetgr "const char *netgroup" "const char *host" "const char *user" "const char *domain"
+.Ft void
+.Fn setnetgrent "const char *netgroup"
+.Ft void
+.Fn endnetgrent void
+.Sh DESCRIPTION
+These functions operate on the netgroup database file which is described in
+.Xr netgroup 5 .
+.Pp
+The database defines a set of netgroups, each made up of one or more triples:
+.Bd -literal -offset indent
+(host, user, domain)
+.Ed
+.Pp
+that defines a combination of host, user and domain.
+Any of the three fields may be specified as ``wildcards'' that match any
+string.
+.Pp
+The function
+.Fn getnetgrent
+sets the three pointer arguments to the strings of the next member of the
+current netgroup.
+If any of the string pointers are
+.Dv NULL
+that field is considered a wildcard.
+.Pp
+The functions
+.Fn setnetgrent
+and
+.Fn endnetgrent
+set the current netgroup and terminate the current netgroup respectively.
+If
+.Fn setnetgrent
+is called with a different netgroup than the previous call, an implicit
+.Fn endnetgrent
+is implied.
+.Fn setnetgrent
+also sets the offset to the first member of the netgroup.
+.Pp
+The function
+.Fn innetgr
+searches for a match of all fields within the specified group.
+If any of the
+.Sy host ,
+.Sy user ,
+or
+.Sy domain
+arguments are
+.Dv NULL
+those fields will match any string value in the netgroup member.
+.Sh RETURN VALUES
+The function
+.Fn getnetgrent
+returns 0 for ``no more netgroup members'' and 1 otherwise.
+The function
+.Fn innetgr
+returns 1 for a successful match and 0 otherwise.
+The functions
+.Fn setnetgrent
+and
+.Fn endnetgrent
+have no return value.
+.Sh FILES
+.Bl -tag -width /etc/netgroup -compact
+.It Pa /etc/netgroup
+netgroup database file
+.El
+.Sh SEE ALSO
+.Xr netgroup 5 ,
+.Xr nsswitch.conf 5
+.Sh BUGS
+The function
+.Fn getnetgrent
+returns pointers to dynamically allocated data areas that are free'd when
+the function
+.Fn endnetgrent
+is called.
diff --git a/lib/nbsd_libc/gen/getnetgrent.c b/lib/nbsd_libc/gen/getnetgrent.c
new file mode 100644 (file)
index 0000000..80eb129
--- /dev/null
@@ -0,0 +1,991 @@
+/*     $NetBSD: getnetgrent.c,v 1.41 2009/10/21 01:07:45 snj Exp $     */
+
+/*
+ * Copyright (c) 1994 Christos Zoulas
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getnetgrent.c,v 1.41 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <db.h>
+#include <err.h>
+#include <fcntl.h>
+#define _NETGROUP_PRIVATE
+#include <stringlist.h>
+#include <netgroup.h>
+#include <nsswitch.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef YP
+#include <rpc/rpc.h>
+#include <rpcsvc/ypclnt.h>
+#include <rpcsvc/yp_prot.h>
+#endif
+
+#ifdef __weak_alias
+__weak_alias(endnetgrent,_endnetgrent)
+__weak_alias(getnetgrent,_getnetgrent)
+__weak_alias(innetgr,_innetgr)
+__weak_alias(setnetgrent,_setnetgrent)
+#endif
+
+#define _NG_STAR(s)    (((s) == NULL || *(s) == '\0') ? _ngstar : s)
+#define _NG_EMPTY(s)   ((s) == NULL ? "" : s)
+#define _NG_ISSPACE(p) (isspace((unsigned char) (p)) || (p) == '\n')
+
+static const char _ngstar[] = "*";
+static struct netgroup *_nghead = NULL;
+static struct netgroup *_nglist = NULL;
+static DB *_ng_db;
+
+static int getstring(char **, int, __aconst char **);
+static struct netgroup *getnetgroup(char **);
+static int lookup(char *, char **, int);
+static int addgroup(StringList *, char *);
+static int in_check(const char *, const char *, const char *,
+    struct netgroup *);
+static int in_find(StringList *, char *, const char *, const char *,
+    const char *);
+static char *in_lookup1(const char *, const char *, int);
+static int in_lookup(const char *, const char *, const char *, int);
+
+#ifdef NSSRC_FILES
+static const ns_src default_files_nis[] = {
+       { NSSRC_FILES,  NS_SUCCESS | NS_NOTFOUND },
+#ifdef YP
+       { NSSRC_NIS,    NS_SUCCESS },
+#endif
+       { 0, 0 },
+};
+#endif
+
+/*
+ * getstring(): Get a string delimited by the character, skipping leading and
+ * trailing blanks and advancing the pointer
+ */
+static int
+getstring(char **pp, int del, char __aconst **str)
+{
+       size_t len;
+       char *sp, *ep, *dp;
+
+       _DIAGASSERT(pp != NULL);
+       _DIAGASSERT(str != NULL);
+
+       /* skip leading blanks */
+       for (sp = *pp; *sp && _NG_ISSPACE(*sp); sp++)
+               continue;
+
+       /* accumulate till delimiter or space */
+       for (ep = sp; *ep && *ep != del && !_NG_ISSPACE(*ep); ep++)
+               continue;
+
+       /* hunt for the delimiter */
+       for (dp = ep; *dp && *dp != del && _NG_ISSPACE(*dp); dp++)
+               continue;
+
+       if (*dp != del) {
+               *str = NULL;
+               return 0;
+       }
+
+       *pp = ++dp;
+
+       len = (ep - sp) + 1;
+       if (len > 1) {
+               dp = malloc(len);
+               if (dp == NULL)
+                       return 0;
+               (void)memcpy(dp, sp, len);
+               dp[len - 1] = '\0';
+       } else
+               dp = NULL;
+
+       *str = dp;
+       return 1;
+}
+
+
+/*
+ * getnetgroup(): Parse a netgroup, and advance the pointer
+ */
+static struct netgroup *
+getnetgroup(pp)
+       char    **pp;
+{
+       struct netgroup *ng;
+
+       _DIAGASSERT(pp != NULL);
+       _DIAGASSERT(*pp != NULL);
+
+       ng = malloc(sizeof(struct netgroup));
+       if (ng == NULL)
+               return NULL;
+
+       (*pp)++;        /* skip '(' */
+       if (!getstring(pp, ',', &ng->ng_host))
+               goto badhost;
+
+       if (!getstring(pp, ',', &ng->ng_user))
+               goto baduser;
+
+       if (!getstring(pp, ')', &ng->ng_domain))
+               goto baddomain;
+
+#ifdef DEBUG_NG
+       {
+               char buf[1024];
+               (void) fprintf(stderr, "netgroup %s\n",
+                   _ng_print(buf, sizeof(buf), ng));
+       }
+#endif
+       return ng;
+
+baddomain:
+       if (ng->ng_user)
+               free(ng->ng_user);
+baduser:
+       if (ng->ng_host)
+               free(ng->ng_host);
+badhost:
+       free(ng);
+       return NULL;
+}
+
+void
+_ng_cycle(const char *grp, const StringList *sl)
+{
+       size_t i;
+       warnx("netgroup: Cycle in group `%s'", grp);
+       (void)fprintf(stderr, "groups: ");
+       for (i = 0; i < sl->sl_cur; i++)
+               (void)fprintf(stderr, "%s ", sl->sl_str[i]);
+       (void)fprintf(stderr, "\n");
+}
+
+static int _local_lookup(void *, void *, va_list);
+
+/*ARGSUSED*/
+static int
+_local_lookup(void *rv, void *cb_data, va_list ap)
+{
+       char     *name = va_arg(ap, char *);
+       char    **line = va_arg(ap, char **);
+       int       bywhat = va_arg(ap, int);
+
+       DBT      key, data;
+       size_t   len;
+       char    *ks;
+       int      r;
+
+       if (_ng_db == NULL)
+               return NS_UNAVAIL;
+
+       len = strlen(name) + 2;
+       ks = malloc(len);
+       if (ks == NULL)
+               return NS_UNAVAIL;
+
+       ks[0] = bywhat;
+       (void)memcpy(&ks[1], name, len - 1);
+
+       key.data = (u_char *)ks;
+       key.size = len;
+
+       r = (*_ng_db->get)(_ng_db, &key, &data, 0);
+       free(ks);
+       switch (r) {
+       case 0:
+               break;
+       case 1:
+               return NS_NOTFOUND;
+       case -1:
+                       /* XXX: call endnetgrent() here ? */
+               return NS_UNAVAIL;
+       }
+
+       *line = strdup(data.data);
+       if (*line == NULL)
+               return NS_UNAVAIL;
+       return NS_SUCCESS;
+}
+
+#ifdef YP
+static int _nis_lookup(void *, void *, va_list);
+
+/*ARGSUSED*/
+static int
+_nis_lookup(void *rv, void *cb_data, va_list ap)
+{
+       char     *name = va_arg(ap, char *);
+       char    **line = va_arg(ap, char **);
+       int       bywhat = va_arg(ap, int);
+
+       static char     *__ypdomain;
+       int              i;
+       const char      *map = NULL;
+
+       if(__ypdomain == NULL) {
+               switch (yp_get_default_domain(&__ypdomain)) {
+               case 0:
+                       break;
+               case YPERR_RESRC:
+                       return NS_TRYAGAIN;
+               default:
+                       return NS_UNAVAIL;
+               }
+       }
+
+       switch (bywhat) {
+       case _NG_KEYBYNAME:
+               map = "netgroup";
+               break;
+
+       case _NG_KEYBYUSER:
+               map = "netgroup.byuser";
+               break;
+
+       case _NG_KEYBYHOST:
+               map = "netgroup.byhost";
+               break;
+
+       default:
+               abort();
+       }
+
+       *line = NULL;
+       switch (yp_match(__ypdomain, map, name, (int)strlen(name), line, &i)) {
+       case 0:
+               return NS_SUCCESS;
+       case YPERR_KEY:
+               if (*line)
+                       free(*line);
+               return NS_NOTFOUND;
+       default:
+               if (*line)
+                       free(*line);
+               return NS_UNAVAIL;
+       }
+       /* NOTREACHED */
+}
+#endif
+
+#ifdef NSSRC_FILES
+/*
+ * lookup(): Find the given key in the database or yp, and return its value
+ * in *line; returns 1 if key was found, 0 otherwise
+ */
+static int
+lookup(char *name, char        **line, int bywhat)
+{
+       int             r;
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_local_lookup, NULL)
+               NS_NIS_CB(_nis_lookup, NULL)
+               NS_NULL_CB
+       };
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(line != NULL);
+
+       r = nsdispatch(NULL, dtab, NSDB_NETGROUP, "lookup", default_files_nis,
+           name, line, bywhat);
+       return (r == NS_SUCCESS) ? 1 : 0;
+}
+#else
+static int
+_local_lookupv(int *rv, void *cbdata, ...)
+{
+       int e;
+       va_list ap;
+       va_start(ap, cbdata);
+       e = _local_lookup(rv, cbdata, ap);
+       va_end(ap);
+       return e;
+}
+
+static int
+lookup(name, line, bywhat)
+       char     *name;
+       char    **line;
+       int       bywhat;
+{
+       return _local_lookupv(NULL, NULL, name, line, bywhat) == NS_SUCCESS;
+}
+#endif
+
+/*
+ * _ng_parse(): Parse a line and return: _NG_ERROR: Syntax Error _NG_NONE:
+ * line was empty or a comment _NG_GROUP: line had a netgroup definition,
+ * returned in ng _NG_NAME:  line had a netgroup name, returned in name
+ * 
+ * Public since used by netgroup_mkdb
+ */
+int
+_ng_parse(char **p, char **name, struct netgroup **ng)
+{
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(*p != NULL);
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(ng != NULL);
+
+       while (**p) {
+               if (**p == '#')
+                       /* comment */
+                       return _NG_NONE;
+
+               while (**p && _NG_ISSPACE(**p))
+                       /* skipblank */
+                       (*p)++;
+
+               if (**p == '(') {
+                       if ((*ng = getnetgroup(p)) == NULL)
+                               return _NG_ERROR;
+                       return _NG_GROUP;
+               } else {
+                       char    *np;
+                       size_t  i;
+
+                       for (np = *p; **p && !_NG_ISSPACE(**p); (*p)++)
+                               continue;
+                       if (np != *p) {
+                               i = (*p - np) + 1;
+                               *name = malloc(i);
+                               if (*name == NULL)
+                                       return _NG_ERROR;
+                               (void)memcpy(*name, np, i);
+                               (*name)[i - 1] = '\0';
+                               return _NG_NAME;
+                       }
+               }
+       }
+       return _NG_NONE;
+}
+
+
+/*
+ * addgroup(): Recursively add all the members of the netgroup to this group.
+ * returns 0 upon failure, nonzero upon success.
+ * grp is not a valid pointer after return (either free(3)ed or allocated
+ * to a stringlist). in either case, it shouldn't be used again.
+ */
+static int
+addgroup(StringList *sl, char *grp)
+{
+       char            *line, *p;
+       struct netgroup *ng;
+       char            *name;
+
+       _DIAGASSERT(sl != NULL);
+       _DIAGASSERT(grp != NULL);
+
+#ifdef DEBUG_NG
+       (void)fprintf(stderr, "addgroup(%s)\n", grp);
+#endif
+       /* check for cycles */
+       if (sl_find(sl, grp) != NULL) {
+               _ng_cycle(grp, sl);
+               free(grp);
+               return 0;
+       }
+       if (sl_add(sl, grp) == -1) {
+               free(grp);
+               return 0;
+       }
+
+       /* Lookup this netgroup */
+       line = NULL;
+       if (!lookup(grp, &line, _NG_KEYBYNAME)) {
+               if (line)
+                       free(line);
+               return 0;
+       }
+
+       p = line;
+
+       for (;;) {
+               switch (_ng_parse(&p, &name, &ng)) {
+               case _NG_NONE:
+                       /* Done with the line */
+                       free(line);
+                       return 1;
+
+               case _NG_GROUP:
+                       /* new netgroup */
+                       /* add to the list */
+                       ng->ng_next = _nglist;
+                       _nglist = ng;
+                       break;
+
+               case _NG_NAME:
+                       /* netgroup name */
+                       if (!addgroup(sl, name))
+                               return 0;
+                       break;
+
+               case _NG_ERROR:
+                       return 0;
+
+               default:
+                       abort();
+               }
+       }
+}
+
+
+/*
+ * in_check(): Compare the spec with the netgroup
+ */
+static int
+in_check(const char *host, const char *user, const char *domain,
+    struct netgroup *ng)
+{
+
+       /* host may be NULL */
+       /* user may be NULL */
+       /* domain may be NULL */
+       _DIAGASSERT(ng != NULL);
+
+       if ((host != NULL) && (ng->ng_host != NULL)
+           && strcmp(ng->ng_host, host) != 0)
+               return 0;
+
+       if ((user != NULL) && (ng->ng_user != NULL)
+           && strcmp(ng->ng_user, user) != 0)
+               return 0;
+
+       if ((domain != NULL) && (ng->ng_domain != NULL)
+           && strcmp(ng->ng_domain, domain) != 0)
+               return 0;
+
+       return 1;
+}
+
+
+/*
+ * in_find(): Find a match for the host, user, domain spec.
+ * grp is not a valid pointer after return (either free(3)ed or allocated
+ * to a stringlist). in either case, it shouldn't be used again.
+ */
+static int
+in_find(StringList *sl, char *grp, const char *host, const char *user,
+    const char *domain)
+{
+       char            *line, *p;
+       int              i;
+       struct netgroup *ng;
+       char            *name;
+
+       _DIAGASSERT(sl != NULL);
+       _DIAGASSERT(grp != NULL);
+       /* host may be NULL */
+       /* user may be NULL */
+       /* domain may be NULL */
+
+#ifdef DEBUG_NG
+       (void)fprintf(stderr, "in_find(%s)\n", grp);
+#endif
+       /* check for cycles */
+       if (sl_find(sl, grp) != NULL) {
+               _ng_cycle(grp, sl);
+               free(grp);
+               return 0;
+       }
+       if (sl_add(sl, grp) == -1) {
+               free(grp);
+               return 0;
+       }
+
+       /* Lookup this netgroup */
+       line = NULL;
+       if (!lookup(grp, &line, _NG_KEYBYNAME)) {
+               if (line)
+                       free(line);
+               return 0;
+       }
+
+       p = line;
+
+       for (;;) {
+               switch (_ng_parse(&p, &name, &ng)) {
+               case _NG_NONE:
+                       /* Done with the line */
+                       free(line);
+                       return 0;
+
+               case _NG_GROUP:
+                       /* new netgroup */
+                       i = in_check(host, user, domain, ng);
+                       if (ng->ng_host != NULL)
+                               free(ng->ng_host);
+                       if (ng->ng_user != NULL)
+                               free(ng->ng_user);
+                       if (ng->ng_domain != NULL)
+                               free(ng->ng_domain);
+                       free(ng);
+                       if (i) {
+                               free(line);
+                               return 1;
+                       }
+                       break;
+
+               case _NG_NAME:
+                       /* netgroup name */
+                       if (in_find(sl, name, host, user, domain)) {
+                               free(line);
+                               return 1;
+                       }
+                       break;
+
+               case _NG_ERROR:
+                       free(line);
+                       return 0;
+
+               default:
+                       abort();
+               }
+       }
+}
+
+/*
+ * _ng_makekey(): Make a key from the two names given. The key is of the form
+ * <name1>.<name2> Names strings are replaced with * if they are empty;
+ * Returns NULL if there's a problem.
+ */
+char *
+_ng_makekey(const char *s1, const char *s2, size_t len)
+{
+       char *buf;
+
+       /* s1 may be NULL */
+       /* s2 may be NULL */
+
+       buf = malloc(len);
+       if (buf != NULL)
+               (void)snprintf(buf, len, "%s.%s", _NG_STAR(s1), _NG_STAR(s2));
+       return buf;
+}
+
+void
+_ng_print(char *buf, size_t len, const struct netgroup *ng)
+{
+       _DIAGASSERT(buf != NULL);
+       _DIAGASSERT(ng != NULL);
+
+       (void)snprintf(buf, len, "(%s,%s,%s)", _NG_EMPTY(ng->ng_host),
+           _NG_EMPTY(ng->ng_user), _NG_EMPTY(ng->ng_domain));
+}
+
+
+/*
+ * in_lookup1(): Fast lookup for a key in the appropriate map
+ */
+static char *
+in_lookup1(const char *key, const char *domain, int map)
+{
+       char    *line;
+       size_t   len;
+       char    *ptr;
+       int      res;
+
+       /* key may be NULL */
+       /* domain may be NULL */
+
+       len = (key ? strlen(key) : 1) + (domain ? strlen(domain) : 1) + 2;
+       ptr = _ng_makekey(key, domain, len);
+       if (ptr == NULL)
+               return NULL;
+       res = lookup(ptr, &line, map);
+       free(ptr);
+       return res ? line : NULL;
+}
+
+
+/*
+ * in_lookup(): Fast lookup for a key in the appropriate map
+ */
+static int
+in_lookup(const char *group, const char *key, const char *domain, int map)
+{
+       size_t   len;
+       char    *ptr, *line;
+
+       _DIAGASSERT(group != NULL);
+       /* key may be NULL */
+       /* domain may be NULL */
+
+       if (domain != NULL) {
+               /* Domain specified; look in "group.domain" and "*.domain" */
+               if ((line = in_lookup1(key, domain, map)) == NULL)
+                       line = in_lookup1(NULL, domain, map);
+       } else 
+               line = NULL;
+
+       if (line == NULL) {
+           /* 
+            * domain not specified or domain lookup failed; look in
+            * "group.*" and "*.*"
+            */
+           if (((line = in_lookup1(key, NULL, map)) == NULL) &&
+               ((line = in_lookup1(NULL, NULL, map)) == NULL))
+               return 0;
+       }
+
+       len = strlen(group);
+
+       for (ptr = line; (ptr = strstr(ptr, group)) != NULL;)
+               /* Make sure we did not find a substring */
+               if ((ptr != line && ptr[-1] != ',') ||
+                   (ptr[len] != '\0' && strchr("\n\t ,", ptr[len]) == NULL))
+                       ptr++;
+               else {
+                       free(line);
+                       return 1;
+               }
+
+       free(line);
+       return 0;
+}
+
+/*ARGSUSED*/
+static int
+_local_endnetgrent(void *rv, void *cb_data, va_list ap)
+{
+       for (_nglist = _nghead; _nglist != NULL; _nglist = _nghead) {
+               _nghead = _nglist->ng_next;
+               if (_nglist->ng_host != NULL)
+                       free(_nglist->ng_host);
+               if (_nglist->ng_user != NULL)
+                       free(_nglist->ng_user);
+               if (_nglist->ng_domain != NULL)
+                       free(_nglist->ng_domain);
+               free(_nglist);
+       }
+
+       if (_ng_db) {
+               (void)(*_ng_db->close)(_ng_db);
+               _ng_db = NULL;
+       }
+
+       return NS_SUCCESS;
+}
+
+/*ARGSUSED*/
+static int
+_local_setnetgrent(void *rv, void *cb_data, va_list ap)
+{
+       const char      *ng = va_arg(ap, const char *);
+       StringList      *sl;
+       char            *ng_copy;
+
+       _DIAGASSERT(ng != NULL);
+
+       sl = sl_init();
+       if (sl == NULL)
+               return NS_TRYAGAIN;
+
+       /* Cleanup any previous storage */
+       if (_nghead != NULL)
+               endnetgrent();
+
+       if (_ng_db == NULL)
+               _ng_db = dbopen(_PATH_NETGROUP_DB, O_RDONLY, 0, DB_HASH, NULL);
+
+       ng_copy = strdup(ng);
+       if (ng_copy != NULL)
+               addgroup(sl, ng_copy);
+       _nghead = _nglist;
+       sl_free(sl, 1);
+
+       return NS_SUCCESS;
+}
+
+/*ARGSUSED*/
+static int
+_local_getnetgrent(void *rv, void *cb_data, va_list ap)
+{
+       int *retval = va_arg(ap, int *);
+       const char **host = va_arg(ap, const char **);
+       const char **user = va_arg(ap, const char **);
+       const char **domain = va_arg(ap, const char **);
+
+       _DIAGASSERT(host != NULL);
+       _DIAGASSERT(user != NULL);
+       _DIAGASSERT(domain != NULL);
+
+       *retval = 0;
+
+       if (_nglist == NULL)
+               return NS_TRYAGAIN;
+
+       *host   = _nglist->ng_host;
+       *user   = _nglist->ng_user;
+       *domain = _nglist->ng_domain;
+
+       _nglist = _nglist->ng_next;
+
+       *retval = 1;
+
+       return NS_SUCCESS;
+}
+
+/*ARGSUSED*/
+static int
+_local_innetgr(void *rv, void *cb_data, va_list ap)
+{
+       int *retval = va_arg(ap, int *);
+       const char *grp = va_arg(ap, const char *);
+       const char *host = va_arg(ap, const char *);
+       const char *user = va_arg(ap, const char *);
+       const char *domain = va_arg(ap, const char *);
+
+       int      found;
+       StringList *sl;
+       char *grcpy;
+
+       _DIAGASSERT(grp != NULL);
+       /* host may be NULL */
+       /* user may be NULL */
+       /* domain may be NULL */
+
+       if (_ng_db == NULL)
+               _ng_db = dbopen(_PATH_NETGROUP_DB, O_RDONLY, 0, DB_HASH, NULL);
+
+       /* Try the fast lookup first */
+       if (host != NULL && user == NULL) {
+               if (in_lookup(grp, host, domain, _NG_KEYBYHOST)) {
+                       *retval = 1;
+                       return NS_SUCCESS;
+               }
+       } else if (host == NULL && user != NULL) {
+               if (in_lookup(grp, user, domain, _NG_KEYBYUSER)) {
+                       *retval = 1;
+                       return NS_SUCCESS;
+               }
+       }
+       /* If a domainname is given, we would have found a match */
+       if (domain != NULL) {
+               *retval = 0;
+               return NS_SUCCESS;
+       }
+
+       /* Too bad need the slow recursive way */
+       sl = sl_init();
+       if (sl == NULL) {
+               *retval = 0;
+               return NS_SUCCESS;
+       }
+       if ((grcpy = strdup(grp)) == NULL) {
+               sl_free(sl, 1);
+               *retval = 0;
+               return NS_SUCCESS;
+       }
+       found = in_find(sl, grcpy, host, user, domain);
+       sl_free(sl, 1);
+
+       *retval = found;
+       return NS_SUCCESS;
+}
+
+#ifdef YP
+
+/*ARGSUSED*/
+static int
+_nis_endnetgrent(void *rv, void *cb_data, va_list ap)
+{
+       return _local_endnetgrent(rv, cb_data, ap);
+}
+
+/*ARGSUSED*/
+static int
+_nis_setnetgrent(void *rv, void *cb_data, va_list ap)
+{
+       return _local_setnetgrent(rv, cb_data, ap);
+}
+
+/*ARGSUSED*/
+static int
+_nis_getnetgrent(void *rv, void *cb_data, va_list ap)
+{
+       return _local_getnetgrent(rv, cb_data, ap);
+}
+
+/*ARGSUSED*/
+static int
+_nis_innetgr(void *rv, void *cb_data, va_list ap)
+{
+       return _local_innetgr(rv, cb_data, ap);
+}
+
+#endif
+
+
+#ifdef NSSRC_FILES
+void
+endnetgrent(void)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_local_endnetgrent, NULL)
+               NS_NIS_CB(_nis_endnetgrent, NULL)
+               NS_NULL_CB
+       };
+
+       (void) nsdispatch(NULL, dtab, NSDB_NETGROUP, "endnetgrent",
+                         __nsdefaultcompat);
+}
+#else
+static int
+_local_endnetgrentv(int *rv, void *cbdata, ...)
+{
+       int e;
+       va_list ap;
+       va_start(ap, cbdata);
+       e = _local_endnetgrent(rv, cbdata, ap);
+       va_end(ap);
+       return e;
+}
+
+void
+endnetgrent(void)
+{
+       (void)_local_endnetgrentv(NULL, NULL, NULL);
+}
+#endif
+
+#ifdef NSSRC_FILES
+void
+setnetgrent(const char *ng)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_local_setnetgrent, NULL)
+               NS_NIS_CB(_nis_setnetgrent, NULL)
+               NS_NULL_CB
+       };
+
+       (void) nsdispatch(NULL, dtab, NSDB_NETGROUP, "setnetgrent",
+                          __nsdefaultnis, ng);
+}
+#else
+static int
+_local_setnetgrentv(int *rv, void *cbdata, ...)
+{
+       int e;
+       va_list ap;
+       va_start(ap, cbdata);
+       e = _local_setnetgrent(rv, cbdata, ap);
+       va_end(ap);
+       return e;
+}
+
+void
+setnetgrent(const char *ng)
+{
+       (void) _local_setnetgrentv(NULL, NULL,ng);
+}
+
+#endif
+
+#ifdef NSSRC_FILES
+int
+getnetgrent(const char **host, const char **user, const char **domain)
+{
+       int     r, retval;
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_local_getnetgrent, NULL)
+               NS_NIS_CB(_nis_getnetgrent, NULL)
+               NS_NULL_CB
+       };
+
+       r = nsdispatch(NULL, dtab, NSDB_NETGROUP, "getnetgrent",
+                      __nsdefaultnis, &retval, host, user, domain);
+
+       return (r == NS_SUCCESS) ? retval : 0;
+}
+#else
+static int
+_local_getnetgrentv(int *rv, void *cbdata, ...)
+{
+       int e;
+       va_list ap;
+       va_start(ap, cbdata);
+       e = _local_getnetgrent(rv, cbdata, ap);
+       va_end(ap);
+       return e;
+}
+
+int
+getnetgrent(const char **host, const char **user, const char **domain)
+{
+       return _local_getnetgrentv(NULL, NULL, host, user, domain) == NS_SUCCESS;
+}
+#endif
+
+#ifdef NSSRC_FILES
+int
+innetgr(const char *grp, const char *host, const char *user, 
+       const char *domain)
+{
+       int     r, retval;
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_local_innetgr, NULL)
+               NS_NIS_CB(_nis_innetgr, NULL)
+               NS_NULL_CB
+       };
+
+       r = nsdispatch(NULL, dtab, NSDB_NETGROUP, "innetgr",
+                      __nsdefaultnis, &retval, grp, host, user, domain);
+
+       return (r == NS_SUCCESS) ? retval : 0;
+}
+#else
+static int
+_local_innetgrv(int *rv, void *cbdata, ...)
+{
+       int e;
+       va_list ap;
+       va_start(ap, cbdata);
+       e = _local_innetgr(rv, cbdata, ap);
+       va_end(ap);
+       return e;
+}
+
+int
+innetgr(const char *grp, const char *host, const char *user, 
+       const char *domain)
+{
+       return _local_innetgrv(NULL, NULL, grp, host, user, domain) == NS_SUCCESS;
+}
+#endif
diff --git a/lib/nbsd_libc/gen/getpagesize.3 b/lib/nbsd_libc/gen/getpagesize.3
new file mode 100644 (file)
index 0000000..51b68e6
--- /dev/null
@@ -0,0 +1,66 @@
+.\"    $NetBSD: getpagesize.3,v 1.12 2003/08/07 16:42:50 agc Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getpagesize.3      8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt GETPAGESIZE 3
+.Os
+.Sh NAME
+.Nm getpagesize
+.Nd get system page size
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn getpagesize void
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is obsoleted by
+.Xr sysconf 3 .
+.Ef
+.Pp
+.Fn getpagesize
+returns the number of bytes in a page.
+Page granularity is the granularity of many of the memory management calls.
+.Pp
+The page size is a
+.Em system
+page size and may not be the same as the underlying
+hardware page size.
+.Sh SEE ALSO
+.Xr pagesize 1 ,
+.Xr sbrk 2 ,
+.Xr sysconf 3
+.Sh HISTORY
+The
+.Nm
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/gen/getpagesize.c b/lib/nbsd_libc/gen/getpagesize.c
new file mode 100644 (file)
index 0000000..515339d
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: getpagesize.c,v 1.10 2009/12/14 01:04:46 matt Exp $    */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getpagesize.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getpagesize.c,v 1.10 2009/12/14 01:04:46 matt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/sysctl.h>
+#include <assert.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(getpagesize,_getpagesize)
+#endif
+
+int
+getpagesize()
+{
+       static int pagsz;
+
+       if (pagsz == 0) {
+               int mib[2];
+               size_t size;
+
+               mib[0] = CTL_HW;
+               mib[1] = HW_PAGESIZE;
+               size = sizeof pagsz;
+               if (sysctl(mib, 2, &pagsz, &size, NULL, 0) == -1)
+                       return (-1);
+               _DIAGASSERT(pagsz);
+       }
+       return (pagsz);
+}
diff --git a/lib/nbsd_libc/gen/getpass.3 b/lib/nbsd_libc/gen/getpass.3
new file mode 100644 (file)
index 0000000..64220f0
--- /dev/null
@@ -0,0 +1,96 @@
+.\"    $NetBSD: getpass.3,v 1.13 2010/05/06 11:09:39 jruoho Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getpass.3  8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 6, 2010
+.Dt GETPASS 3
+.Os
+.Sh NAME
+.Nm getpass
+.Nd get a password
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In pwd.h
+.In unistd.h
+.Ft char *
+.Fn getpass "const char *prompt"
+.Sh DESCRIPTION
+The
+.Fn getpass
+function displays a prompt to, and reads in a password from,
+.Pa /dev/tty .
+If this file is not accessible,
+.Fn getpass
+displays the prompt on the standard error output and reads from the standard
+input.
+.Pp
+The password may be up to _PASSWORD_LEN (currently 128)
+characters in length.
+Any additional
+characters and the terminating newline character are discarded.
+.Pp
+.Fn getpass
+turns off character echoing while reading the password.
+.Sh RETURN VALUES
+.Fn getpass
+returns a pointer to the null terminated password.
+.Sh FILES
+.Bl -tag -width /dev/tty -compact
+.It Pa /dev/tty
+.El
+.Sh SEE ALSO
+.Xr crypt 3
+.Sh STANDARDS
+The
+.Fn getpass
+function appeared in
+.St -susv2 ,
+but it was already marked as legacy.
+The function was removed in the
+.St -p1003.1-2001
+standard.
+.Sh HISTORY
+A
+.Fn getpass
+function appeared in
+.At v7 .
+.Sh BUGS
+The
+.Fn getpass
+function leaves its result in an internal static object and returns
+a pointer to that object.
+Subsequent calls to
+.Fn getpass
+will modify the same object.
+.Sh SECURITY CONSIDERATIONS
+The calling process should zero the password as soon as possible to
+avoid leaving the cleartext password visible in the process's address
+space.
diff --git a/lib/nbsd_libc/gen/getpass.c b/lib/nbsd_libc/gen/getpass.c
new file mode 100644 (file)
index 0000000..ee4a896
--- /dev/null
@@ -0,0 +1,107 @@
+/*     $NetBSD: getpass.c,v 1.16 2008/01/01 21:22:55 christos Exp $    */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getpass.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getpass.c,v 1.16 2008/01/01 21:22:55 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <paths.h>
+#include <pwd.h>
+#include <signal.h>
+#include <stdio.h>
+#include <termios.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(getpass,_getpass)
+#endif
+
+char *
+getpass(prompt)
+       const char *prompt;
+{
+       struct termios term;
+       int ch;
+       char *p;
+       FILE *fp, *outfp;
+       int echo;
+       static char buf[_PASSWORD_LEN + 1];
+       sigset_t oset, nset;
+
+       _DIAGASSERT(prompt != NULL);
+
+       /*
+        * note - blocking signals isn't necessarily the
+        * right thing, but we leave it for now.
+        */
+       sigemptyset(&nset);
+       sigaddset(&nset, SIGINT);
+       sigaddset(&nset, SIGTSTP);
+       (void)sigprocmask(SIG_BLOCK, &nset, &oset);
+
+       /*
+        * read and write to /dev/tty if possible; else read from
+        * stdin and write to stderr.
+        */
+       if ((outfp = fp = fopen(_PATH_TTY, "w+")) == NULL) {
+               outfp = stderr;
+               fp = stdin;
+       }
+       (void)tcgetattr(fileno(fp), &term);
+       if ((echo = (term.c_lflag & ECHO)) != 0) {
+               term.c_lflag &= ~ECHO;
+               (void)tcsetattr(fileno(fp), TCSAFLUSH|TCSASOFT, &term);
+       }
+       if (prompt != NULL)
+               (void)fputs(prompt, outfp);
+       rewind(outfp);                  /* implied flush */
+       for (p = buf; (ch = getc(fp)) != EOF && ch != '\n';)
+               if (p < buf + _PASSWORD_LEN)
+                       *p++ = ch;
+       *p = '\0';
+       (void)write(fileno(outfp), "\n", 1);
+       if (echo) {
+               term.c_lflag |= ECHO;
+               (void)tcsetattr(fileno(fp), TCSAFLUSH|TCSASOFT, &term);
+       }
+       if (fp != stdin)
+               (void)fclose(fp);
+       (void)sigprocmask(SIG_SETMASK, &oset, NULL);
+       return(buf);
+}
diff --git a/lib/nbsd_libc/gen/getprogname.3 b/lib/nbsd_libc/gen/getprogname.3
new file mode 100644 (file)
index 0000000..878d6c6
--- /dev/null
@@ -0,0 +1,116 @@
+.\" $NetBSD: getprogname.3,v 1.7 2008/03/29 16:51:40 dholland Exp $
+.\"
+.\" Copyright (c) 2001 Christopher G. Demetriou
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"          This product includes software developed for the
+.\"          NetBSD Project.  See http://www.NetBSD.org/ for
+.\"          information about NetBSD.
+.\" 4. 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 ``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 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.
+.\"
+.\" <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+.\"
+.Dd March 29, 2008
+.Dt GETPROGNAME 3
+.Os
+.Sh NAME
+.Nm getprogname ,
+.Nm setprogname
+.Nd get/set the name of the current program
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft const char *
+.Fn getprogname "void"
+.Ft void
+.Fn setprogname "const char *name"
+.Sh DESCRIPTION
+These utility functions get and set the current program's name
+as used by various error-reporting functions.
+.Pp
+.Fn getprogname
+returns the name of the current program.
+This function is typically useful when generating error messages
+or other diagnostic output.
+If the program name has not been set,
+.Fn getprogname
+will return
+.Dv NULL .
+.Pp
+.Fn setprogname
+sets the name of the current program to be the last pathname
+component of the
+.Fa name
+argument.
+It should be invoked at the start of the program, using the
+.Fa argv[0]
+passed into the program's
+.Fn main
+function.
+A pointer into the string pointed to by the
+.Fa name
+argument is kept as the program name.
+Therefore, the string pointed to by
+.Fa name
+should not be modified during the rest of the program's operation.
+.Pp
+A program's name can only be set once, and in
+.Nx
+that is actually
+done by program start-up code that is run before
+.Fn main
+is called.
+Therefore, in
+.Nx ,
+calling
+.Fn setprogname
+from
+.Fn main
+has no effect.
+However, it does serve to increase the portability of the program:
+on other operating systems,
+.Fn getprogname
+and
+.Fn setprogname
+may be implemented by a portability library, and a call to
+.Fn setprogname
+allows that library to know the program name without
+modifications to that system's program start-up code.
+.Sh SEE ALSO
+.Xr err 3 ,
+.Xr setproctitle 3
+.Sh HISTORY
+The
+.Nm getprogname
+and
+.Nm setprogname
+function calls appeared in
+.Nx 1.6 .
+.Sh RESTRICTIONS
+The string returned by
+.Fn getprogname
+is supplied by the invoking process and should not be trusted by
+setuid or setgid programs.
diff --git a/lib/nbsd_libc/gen/getprogname.c b/lib/nbsd_libc/gen/getprogname.c
new file mode 100644 (file)
index 0000000..417d334
--- /dev/null
@@ -0,0 +1,57 @@
+/* $NetBSD: getprogname.c,v 1.3 2003/07/26 19:24:42 salo Exp $ */
+
+/*
+ * Copyright (c) 2001 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getprogname.c,v 1.3 2003/07/26 19:24:42 salo Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(getprogname,_getprogname)
+#endif
+
+extern const char *__progname;
+
+const char *
+getprogname(void)
+{
+
+       return (__progname);
+}
diff --git a/lib/nbsd_libc/gen/getpwent.3 b/lib/nbsd_libc/gen/getpwent.3
new file mode 100644 (file)
index 0000000..db97f37
--- /dev/null
@@ -0,0 +1,370 @@
+.\"    $NetBSD: getpwent.3,v 1.37 2010/03/22 19:30:53 joerg Exp $
+.\"
+.\" Copyright (c) 1988, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getpwent.3 8.2 (Berkeley) 12/11/93
+.\"
+.Dd April 30, 2008
+.Dt GETPWENT 3
+.Os
+.Sh NAME
+.Nm getpwent ,
+.Nm getpwent_r ,
+.Nm getpwnam ,
+.Nm getpwnam_r ,
+.Nm getpwuid ,
+.Nm getpwuid_r ,
+.Nm setpassent ,
+.Nm setpwent ,
+.Nm endpwent
+.Nd password database operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In pwd.h
+.Ft struct passwd *
+.Fn getpwent void
+.Ft int
+.Fo getpwent_r
+.Fa "struct passwd *pw"
+.Fa "char *buffer"
+.Fa "size_t buflen"
+.Fa "struct passwd **result"
+.Fc
+.Ft struct passwd *
+.Fn getpwnam "const char *name"
+.Ft int
+.Fo getpwnam_r
+.Fa "const char *name"
+.Fa "struct passwd *pw"
+.Fa "char *buffer"
+.Fa "size_t buflen"
+.Fa "struct passwd **result"
+.Fc
+.Ft struct passwd *
+.Fn getpwuid "uid_t uid"
+.Ft int
+.Fo getpwuid_r
+.Fa "uid_t uid"
+.Fa "struct passwd *pw"
+.Fa "char *buffer"
+.Fa "size_t buflen"
+.Fa "struct passwd **result"
+.Fc
+.Ft int
+.Fn setpassent "int stayopen"
+.Ft void
+.Fn setpwent void
+.Ft void
+.Fn endpwent void
+.Sh DESCRIPTION
+These functions
+operate on the password database
+which is described
+in
+.Xr passwd 5 .
+Each entry in the database is defined by the structure
+.Ar passwd
+found in the include
+file
+.In pwd.h :
+.Bd -literal -offset indent
+struct passwd {
+       char    *pw_name;       /* user name */
+       char    *pw_passwd;     /* encrypted password */
+       uid_t   pw_uid;         /* user uid */
+       gid_t   pw_gid;         /* user gid */
+       time_t  pw_change;      /* password change time */
+       char    *pw_class;      /* user login class */
+       char    *pw_gecos;      /* general information */
+       char    *pw_dir;        /* home directory */
+       char    *pw_shell;      /* default shell */
+       time_t  pw_expire;      /* account expiration */
+};
+.Ed
+.Pp
+The functions
+.Fn getpwnam
+and
+.Fn getpwuid
+search the password database for the given user name pointed to by
+.Ar name
+or user id pointed to by
+.Ar uid
+respectively, always returning the first one encountered.
+Identical user names or user ids may result in undefined behavior.
+.Pp
+The
+.Fn getpwent
+function
+sequentially reads the password database and is intended for programs
+that wish to process the complete list of users.
+.Pp
+The functions
+.Fn getpwnam_r ,
+.Fn getpwuid_r ,
+and
+.Fn getpwent_r
+act like their non re-entrant counterparts, updating the contents of
+.Ar pw
+and storing a pointer to that in
+.Ar result ,
+and returning
+.Dv 0 .
+Storage used by
+.Ar pw
+is allocated from
+.Ar buffer ,
+which is
+.Ar buflen
+bytes in size.
+If the requested entry cannot be found,
+.Ar result
+will point to
+.Dv NULL
+and
+.Dv 0
+will be returned.
+If an error occurs,
+a non-zero error number will be returned and
+.Ar result
+will point to
+.Dv NULL .
+Calling
+.Fn getpwent_r
+from multiple threads will result in each thread reading a disjoint portion
+of the password database.
+.Pp
+The
+.Fn setpassent
+function
+accomplishes two purposes.
+First, it causes
+.Fn getpwent
+to
+.Dq rewind
+to the beginning of the database.
+Additionally, if
+.Fa stayopen
+is non-zero, file descriptors are left open, significantly speeding
+up subsequent accesses for all of the functions.
+(This latter functionality is unnecessary for
+.Fn getpwent
+as it doesn't close its file descriptors by default.)
+.Pp
+It is dangerous for long-running programs to keep the file descriptors
+open as the database will become out of date if it is updated while the
+program is running.
+.Pp
+The
+.Fn setpwent
+function
+is equivalent to
+.Fn setpassent
+with an argument of zero.
+.Pp
+The
+.Fn endpwent
+function
+closes any open files.
+.Pp
+These functions have been written to
+.Dq shadow
+the password file, e.g. allow only certain programs to have access
+to the encrypted password.
+If the process which calls them has an effective uid of 0, the encrypted
+password will be returned, otherwise, the password field of the returned
+structure will point to the string
+.Ql * .
+.Sh RETURN VALUES
+The functions
+.Fn getpwent ,
+.Fn getpwnam ,
+and
+.Fn getpwuid ,
+return a valid pointer to a passwd structure on success
+and a
+.Dv NULL
+pointer if the entry was not found or an error occured.
+If an error occured, the global variable
+.Dv errno
+is set to indicate the nature of the failure.
+The
+.Fn setpassent
+function returns 0 on failure, setting the global variable
+.Dv errno
+to indicate the nature of the failure, and 1 on success.
+The
+.Fn endpwent
+and
+.Fn setpwent
+functions
+have no return value.
+The functions
+.Fn getpwnam_r ,
+.Fn getpwuid_r ,
+and
+.Fn getpwent_r
+return
+.Dv 0
+on success or entry not found, and non-zero on failure, setting the global
+variable
+.Dv errno
+to indicate the nature of the failure.
+.Sh ERRORS
+The following error codes may be set in
+.Va errno 
+for
+.Nm getpwent ,
+.Nm getpwent_r ,
+.Nm getpwnam ,
+.Nm getpwnam_r ,
+.Nm getpwuid ,
+.Nm getpwuid_r ,
+and
+.Nm setpassent :
+.Bl -tag -width Er
+.It Bq Er EIO
+An I/O error has occurred.
+.It Bq Er EINTR
+A signal was caught during the database search.
+.It Bq Er EMFILE
+The limit on open files for this process has been reached.
+.It Bq Er ENFILE
+The system limit on open files has been reached.
+.El
+.Pp
+The following error code may be set in
+.Va errno 
+for
+.Nm getpwent_r ,
+.Nm getpwnam_r ,
+and
+.Nm getpwuid_r :
+.Bl -tag -width Er
+.It Bq Er ERANGE
+The resulting
+.Ft struct passwd
+does not fit in the space defined by
+.Dv buffer
+and
+.Dv buflen
+.El
+.Pp
+Other
+.Dv errno
+values may be set depending on the specific database backends.
+.Sh FILES
+.Bl -tag -width /etc/master.passwd -compact
+.It Pa /etc/pwd.db
+The insecure password database file
+.It Pa /etc/spwd.db
+The secure password database file
+.It Pa /etc/master.passwd
+The current password file
+.It Pa /etc/passwd
+A Version 7 format password file
+.El
+.Sh SEE ALSO
+.Xr getlogin 2 ,
+.Xr getgrent 3 ,
+.Xr nsswitch.conf 5 ,
+.Xr passwd 5 ,
+.Xr passwd.conf 5 ,
+.Xr pwd_mkdb 8 ,
+.Xr vipw 8
+.Sh STANDARDS
+The
+.Fn getpwnam
+and
+.Fn getpwuid ,
+functions conform to
+.St -p1003.1-90 .
+The
+.Fn getpwnam_r
+and
+.Fn getpwuid_r
+functions conform to
+.St -p1003.1c-95 .
+The
+.Fn endpwent ,
+.Fn getpwent ,
+and
+.Fn setpwent
+functions conform to
+.St -xpg4.2
+and
+.St -p1003.1-2004
+(XSI extension).
+.Sh HISTORY
+The
+.Nm getpwent ,
+.Nm getpwnam ,
+.Nm getpwuid ,
+.Nm setpwent ,
+and
+.Nm endpwent
+functions appeared in
+.At v7 .
+The
+.Nm setpassent
+function appeared in
+.Bx 4.3 Reno .
+The functions
+.Fn getpwnam_r
+and
+.Fn getpwuid_r
+appeared in
+.Nx 3.0 .
+.Sh BUGS
+The functions
+.Fn getpwent ,
+.Fn getpwnam ,
+and
+.Fn getpwuid ,
+leave their results in an internal static object and return
+a pointer to that object.
+Subsequent calls to any of these functions will modify the same object.
+.Pp
+The functions
+.Fn getpwent ,
+.Fn endpwent ,
+.Fn setpassent ,
+and
+.Fn setpwent
+are fairly useless in a networked environment and should be
+avoided, if possible.
+.Fn getpwent
+makes no attempt to suppress duplicate information if multiple
+sources are specified in
+.Xr nsswitch.conf 5 .
+.Sh COMPATIBILITY
+The historic function
+.Fn setpwfile
+which allowed the specification of alternative password databases,
+has been deprecated and is no longer available.
diff --git a/lib/nbsd_libc/gen/getpwent.c b/lib/nbsd_libc/gen/getpwent.c
new file mode 100644 (file)
index 0000000..c49f5e2
--- /dev/null
@@ -0,0 +1,2579 @@
+/*     $NetBSD: getpwent.c,v 1.77 2010/03/23 20:28:59 drochner Exp $   */
+
+/*-
+ * Copyright (c) 1997-2000, 2004-2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Luke Mewburn.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+/*
+ * Portions Copyright (c) 1994, 1995, Jason Downs.  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(S) ``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(S) 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getpwent.c 8.2 (Berkeley) 4/27/95";
+#else
+__RCSID("$NetBSD: getpwent.c,v 1.77 2010/03/23 20:28:59 drochner Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+
+#include <sys/param.h>
+
+#include <assert.h>
+#include <db.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <netgroup.h>
+#include <nsswitch.h>
+#include <pwd.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <syslog.h>
+#include <unistd.h>
+
+#ifdef HESIOD
+#include <hesiod.h>
+#endif
+
+#ifdef YP
+#include <machine/param.h>
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+#endif
+
+#include "pw_private.h"
+
+#define        _PASSWD_COMPAT  /* "passwd" defaults to compat, so always provide it */
+
+#ifdef __weak_alias
+__weak_alias(endpwent,_endpwent)
+__weak_alias(setpassent,_setpassent)
+__weak_alias(setpwent,_setpwent)
+#endif
+
+#ifdef _REENTRANT
+static         mutex_t                 _pwmutex = MUTEX_INITIALIZER;
+#endif
+
+const char __yp_token[] = "__YP!";     /* Let pwd_mkdb pull this in. */
+
+
+/*
+ * The pwd.db lookup techniques and data extraction code here must be kept
+ * in sync with that in `pwd_mkdb'.
+ */
+
+#if defined(YP) || defined(HESIOD)
+/*
+ * _pw_parse
+ *     Parses entry using pw_scan(3) (without the trailing \n)
+ *     after copying to buf, and fills in pw with corresponding values.
+ *     If old is non-zero, entry is in _PASSWORD_OLDFMT.
+ *     Returns 1 if parsed successfully, 0 on parse failure.
+ */
+static int
+_pw_parse(const char *entry, struct passwd *pw, char *buf, size_t buflen,
+       int old)
+{
+       int     flags;
+
+       _DIAGASSERT(entry != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buf != NULL);
+
+       if (strlcpy(buf, entry, buflen) >= buflen)
+               return 0;
+       flags = _PASSWORD_NOWARN;
+       if (old)
+               flags |= _PASSWORD_OLDFMT;
+       return __pw_scan(buf, pw, &flags);
+}
+#endif /* YP || HESIOD */
+
+/*
+ * _pw_opendb
+ *     if *db is NULL, dbopen(3) /etc/spwd.db or /etc/pwd.db (depending
+ *     upon permissions, etc)
+ */
+static int
+_pw_opendb(DB **db, int *version)
+{
+       static int      warned;
+       DBT             key;
+       DBT             value;
+
+       const char      *dbfile = NULL;
+
+       _DIAGASSERT(db != NULL);
+       _DIAGASSERT(version != NULL);
+       if (*db != NULL)                                        /* open *db */
+               return NS_SUCCESS;
+
+       if (geteuid() == 0) {
+               dbfile = _PATH_SMP_DB;
+               *db = dbopen(dbfile, O_RDONLY, 0, DB_HASH, NULL);
+       }
+       if (*db == NULL) {
+               dbfile = _PATH_MP_DB;
+               *db = dbopen(dbfile, O_RDONLY, 0, DB_HASH, NULL);
+       }
+       if (*db == NULL) {
+               if (!warned) {
+                       int     serrno = errno;
+                       syslog(LOG_ERR, "%s: %m", dbfile);
+                       errno = serrno;
+               }
+               warned = 1;
+               return NS_UNAVAIL;
+       }
+       key.data = __UNCONST("VERSION");
+       key.size = strlen((char *)key.data) + 1;
+       switch ((*(*db)->get)(*db, &key, &value, 0)) {
+       case 0:
+               if (sizeof(*version) != value.size)
+                       return NS_UNAVAIL;
+               (void)memcpy(version, value.data, value.size);
+               break;                  /* found */
+       case 1:
+               *version = 0;           /* not found */
+               break;
+       case -1:
+               return NS_UNAVAIL;      /* error in db routines */
+       default:
+               abort();
+       }
+       return NS_SUCCESS;
+}
+
+/*
+ * _pw_getkey
+ *     Lookup key in *db, filling in pw
+ *     with the result, allocating memory from buffer (size buflen).
+ *     (The caller may point key.data to buffer on entry; the contents
+ *     of key.data will be invalid on exit.)
+ */
+static int
+_pw_getkey(DB *db, DBT *key,
+       struct passwd *pw, char *buffer, size_t buflen, int *pwflags,
+       int version)
+{
+       char            *p, *t;
+       DBT             data;
+
+       _DIAGASSERT(db != NULL);
+       _DIAGASSERT(key != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       /* pwflags may be NULL (if we don't care about them */
+
+       if (db == NULL)                 /* this shouldn't happen */
+               return NS_UNAVAIL;
+
+       switch ((db->get)(db, key, &data, 0)) {
+       case 0:
+               break;                  /* found */
+       case 1:
+               return NS_NOTFOUND;     /* not found */
+       case -1:
+               return NS_UNAVAIL;      /* error in db routines */
+       default:
+               abort();
+       }
+
+       p = (char *)data.data;
+       if (data.size > buflen) {
+               errno = ERANGE;
+               return NS_UNAVAIL;
+       }
+
+                       /*
+                        * THE DECODING BELOW MUST MATCH THAT IN pwd_mkdb.
+                        */
+       t = buffer;
+#define MACRO(a)       do { a } while (/*CONSTCOND*/0)
+#define        EXPAND(e)       MACRO(e = t; while ((*t++ = *p++));)
+#define        SCALAR(v)       MACRO(memmove(&(v), p, sizeof v); p += sizeof v;)
+       EXPAND(pw->pw_name);
+       EXPAND(pw->pw_passwd);
+       SCALAR(pw->pw_uid);
+       SCALAR(pw->pw_gid);
+       if (version == 0) {
+               int32_t tmp;
+               SCALAR(tmp);
+               pw->pw_change = tmp;
+       } else
+               SCALAR(pw->pw_change);
+       EXPAND(pw->pw_class);
+       EXPAND(pw->pw_gecos);
+       EXPAND(pw->pw_dir);
+       EXPAND(pw->pw_shell);
+       if (version == 0) {
+               int32_t tmp;
+               SCALAR(tmp);
+               pw->pw_expire = tmp;
+       } else
+               SCALAR(pw->pw_expire);
+       if (pwflags) {
+               /* See if there's any data left.  If so, read in flags. */
+               if (data.size > (size_t) (p - (char *)data.data)) {
+                       SCALAR(*pwflags);
+               } else {                                /* default */
+                       *pwflags = _PASSWORD_NOUID|_PASSWORD_NOGID;
+               }
+       }
+
+       return NS_SUCCESS;
+}
+
+/*
+ * _pw_memfrombuf
+ *     Obtain want bytes from buffer (of size buflen) and return a pointer
+ *     to the available memory after adjusting buffer/buflen.
+ *     Returns NULL if there is insufficient space.
+ */
+static char *
+_pw_memfrombuf(size_t want, char **buffer, size_t *buflen)
+{
+       char    *rv;
+
+       if (want > *buflen) {
+               errno = ERANGE;
+               return NULL;
+       }
+       rv = *buffer;
+       *buffer += want;
+       *buflen -= want;
+       return rv;
+}
+
+/*
+ * _pw_copy
+ *     Copy the contents of frompw to pw; memory for strings
+ *     and arrays will be allocated from buf (of size buflen).
+ *     If proto != NULL, use various fields in proto in preference to frompw.
+ *     Returns 1 if copied successfully, 0 on copy failure.
+ *     NOTE: frompw must not use buf for its own pointers.
+ */
+static int
+_pw_copy(const struct passwd *frompw, struct passwd *pw,
+       char *buf, size_t buflen, const struct passwd *protopw, int protoflags)
+{
+       size_t  count;
+       int     useproto;
+
+       _DIAGASSERT(frompw != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buf != NULL);
+       /* protopw may be NULL */
+
+       useproto = protopw && protopw->pw_name;
+
+#define        COPYSTR(to, from) \
+       do { \
+               count = strlen((from)); \
+               (to) = _pw_memfrombuf(count+1, &buf, &buflen); \
+               if ((to) == NULL) \
+                       return 0; \
+               memmove((to), (from), count); \
+               to[count] = '\0'; \
+       } while (0)     /* LINTED */
+
+#define        COPYFIELD(field)        COPYSTR(pw->field, frompw->field)
+
+#define        COPYPROTOFIELD(field)   COPYSTR(pw->field, \
+               (useproto && *protopw->field ? protopw->field : frompw->field))
+
+       COPYFIELD(pw_name);
+
+#ifdef PW_OVERRIDE_PASSWD
+       COPYPROTOFIELD(pw_passwd);
+#else
+       COPYFIELD(pw_passwd);
+#endif
+
+       if (useproto && !(protoflags & _PASSWORD_NOUID))
+               pw->pw_uid = protopw->pw_uid;
+       else
+               pw->pw_uid = frompw->pw_uid;
+
+       if (useproto && !(protoflags & _PASSWORD_NOGID))
+               pw->pw_gid = protopw->pw_gid;
+       else
+               pw->pw_gid = frompw->pw_gid;
+
+       pw->pw_change = frompw->pw_change;
+       COPYFIELD(pw_class);
+       COPYPROTOFIELD(pw_gecos);
+       COPYPROTOFIELD(pw_dir);
+       COPYPROTOFIELD(pw_shell);
+
+#undef COPYSTR
+#undef COPYFIELD
+#undef COPYPROTOFIELD
+
+       return 1;
+}
+
+
+               /*
+                *      files methods
+                */
+
+       /* state shared between files methods */
+struct files_state {
+       int      stayopen;              /* see getpassent(3) */
+       DB      *db;                    /* passwd file handle */
+       int      keynum;                /* key counter, -1 if no more */
+       int      version;
+};
+
+static struct files_state      _files_state;
+                                       /* storage for non _r functions */
+static struct passwd           _files_passwd;
+static char                    _files_passwdbuf[_GETPW_R_SIZE_MAX];
+
+static int
+_files_start(struct files_state *state)
+{
+       int     rv;
+
+       _DIAGASSERT(state != NULL);
+
+       state->keynum = 0;
+       rv = _pw_opendb(&state->db, &state->version);
+       if (rv != NS_SUCCESS)
+               return rv;
+       return NS_SUCCESS;
+}
+
+static int
+_files_end(struct files_state *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       state->keynum = 0;
+       if (state->db) {
+               (void)(state->db->close)(state->db);
+               state->db = NULL;
+       }
+       return NS_SUCCESS;
+}
+
+/*
+ * _files_pwscan
+ *     Search state->db for the next desired entry.
+ *     If search is _PW_KEYBYNUM, look for state->keynum.
+ *     If search is _PW_KEYBYNAME, look for name.
+ *     If search is _PW_KEYBYUID, look for uid.
+ *     Sets *retval to the errno if the result is not NS_SUCCESS
+ *     or NS_NOTFOUND.
+ */
+static int
+_files_pwscan(int *retval, struct passwd *pw, char *buffer, size_t buflen,
+       struct files_state *state, int search, const char *name, uid_t uid)
+{
+       const void      *from;
+       size_t           fromlen;
+       DBT              key;
+       int              rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(state != NULL);
+       /* name is NULL to indicate searching for uid */
+
+       *retval = 0;
+
+       if (state->db == NULL) {        /* only start if file not open yet */
+               rv = _files_start(state);
+               if (rv != NS_SUCCESS)
+                       goto filespwscan_out;
+       }
+
+       for (;;) {                              /* search for a match */
+               switch (search) {
+               case _PW_KEYBYNUM:
+                       if (state->keynum == -1)
+                               return NS_NOTFOUND;     /* no more records */
+                       state->keynum++;
+                       from = &state->keynum;
+                       fromlen = sizeof(state->keynum);
+                       break;
+               case _PW_KEYBYNAME:
+                       from = name;
+                       fromlen = strlen(name);
+                       break;
+               case _PW_KEYBYUID:
+                       from = &uid;
+                       fromlen = sizeof(uid);
+                       break;
+               default:
+                       abort();
+               }
+
+               if (buflen <= fromlen) {                /* buffer too small */
+                       *retval = ERANGE;
+                       return NS_UNAVAIL;
+               }
+               buffer[0] = search;                     /* setup key */
+               memmove(buffer + 1, from, fromlen);
+               key.size = fromlen + 1;
+               key.data = (u_char *)buffer;
+
+                                                       /* search for key */
+               rv = _pw_getkey(state->db, &key, pw, buffer, buflen, NULL,
+                   state->version);
+               if (rv != NS_SUCCESS)                   /* no match */
+                       break;
+               if (pw->pw_name[0] == '+' || pw->pw_name[0] == '-') {
+                                               /* if a compat line */
+                       if (search == _PW_KEYBYNUM)
+                               continue;       /* read next if pwent */
+                       rv = NS_NOTFOUND;       /* don't match if pw{nam,uid} */
+                       break;
+               }
+               break;
+       }
+
+       if (rv == NS_NOTFOUND && search == _PW_KEYBYNUM)
+               state->keynum = -1;             /* flag `no more records' */
+
+       if (rv == NS_SUCCESS) {
+               if ((search == _PW_KEYBYUID && pw->pw_uid != uid) ||
+                   (search == _PW_KEYBYNAME && strcmp(pw->pw_name, name) != 0))
+                       rv = NS_NOTFOUND;
+       }
+
+ filespwscan_out:
+       if (rv != NS_SUCCESS && rv != NS_NOTFOUND)
+               *retval = errno;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_setpwent(void *nsrv, void *nscb, va_list ap)
+{
+
+       _files_state.stayopen = 0;
+       return _files_start(&_files_state);
+}
+
+/*ARGSUSED*/
+static int
+_files_setpassent(void *nsrv, void *nscb, va_list ap)
+{
+       int     *retval         = va_arg(ap, int *);
+       int      stayopen       = va_arg(ap, int);
+
+       int     rv;
+
+       _files_state.stayopen = stayopen;
+       rv = _files_start(&_files_state);
+       *retval = (rv == NS_SUCCESS);
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_endpwent(void *nsrv, void *nscb, va_list ap)
+{
+
+       _files_state.stayopen = 0;
+       return _files_end(&_files_state);
+}
+
+/*ARGSUSED*/
+static int
+_files_getpwent(void *nsrv, void *nscb, va_list ap)
+{
+       struct passwd   **retval = va_arg(ap, struct passwd **);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = _files_pwscan(&rerror, &_files_passwd,
+           _files_passwdbuf, sizeof(_files_passwdbuf),
+           &_files_state, _PW_KEYBYNUM, NULL, 0);
+       if (rv == NS_SUCCESS)
+               *retval = &_files_passwd;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_getpwent_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       struct passwd   *pw     = va_arg(ap, struct passwd *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct passwd  **result = va_arg(ap, struct passwd **);
+
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       rv = _files_pwscan(retval, pw, buffer, buflen, &_files_state,
+           _PW_KEYBYNUM, NULL, 0);
+       if (rv == NS_SUCCESS)
+               *result = pw;
+       else
+               *result = NULL;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_getpwnam(void *nsrv, void *nscb, va_list ap)
+{
+       struct passwd   **retval = va_arg(ap, struct passwd **);
+       const char      *name   = va_arg(ap, const char *);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = _files_start(&_files_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = _files_pwscan(&rerror, &_files_passwd,
+           _files_passwdbuf, sizeof(_files_passwdbuf),
+           &_files_state, _PW_KEYBYNAME, name, 0);
+       if (!_files_state.stayopen)
+               _files_end(&_files_state);
+       if (rv == NS_SUCCESS)
+               *retval = &_files_passwd;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_getpwnam_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       const char      *name   = va_arg(ap, const char *);
+       struct passwd   *pw     = va_arg(ap, struct passwd *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct passwd  **result = va_arg(ap, struct passwd **);
+
+       struct files_state state;
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = _files_pwscan(retval, pw, buffer, buflen, &state,
+           _PW_KEYBYNAME, name, 0);
+       _files_end(&state);
+       if (rv == NS_SUCCESS)
+               *result = pw;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_getpwuid(void *nsrv, void *nscb, va_list ap)
+{
+       struct passwd   **retval = va_arg(ap, struct passwd **);
+       uid_t            uid    = va_arg(ap, uid_t);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = _files_start(&_files_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = _files_pwscan(&rerror, &_files_passwd,
+           _files_passwdbuf, sizeof(_files_passwdbuf),
+           &_files_state, _PW_KEYBYUID, NULL, uid);
+       if (!_files_state.stayopen)
+               _files_end(&_files_state);
+       if (rv == NS_SUCCESS)
+               *retval = &_files_passwd;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_files_getpwuid_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       uid_t            uid    = va_arg(ap, uid_t);
+       struct passwd   *pw     = va_arg(ap, struct passwd *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct passwd  **result = va_arg(ap, struct passwd **);
+
+       struct files_state state;
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = _files_pwscan(retval, pw, buffer, buflen, &state,
+           _PW_KEYBYUID, NULL, uid);
+       _files_end(&state);
+       if (rv == NS_SUCCESS)
+               *result = pw;
+       return rv;
+}
+
+
+#ifdef HESIOD
+               /*
+                *      dns methods
+                */
+
+       /* state shared between dns methods */
+struct dns_state {
+       int      stayopen;              /* see getpassent(3) */
+       void    *context;               /* Hesiod context */
+       int      num;                   /* passwd index, -1 if no more */
+};
+
+static struct dns_state                _dns_state;
+                                       /* storage for non _r functions */
+static struct passwd           _dns_passwd;
+static char                    _dns_passwdbuf[_GETPW_R_SIZE_MAX];
+
+static int
+_dns_start(struct dns_state *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       state->num = 0;
+       if (state->context == NULL) {                   /* setup Hesiod */
+               if (hesiod_init(&state->context) == -1)
+                       return NS_UNAVAIL;
+       }
+
+       return NS_SUCCESS;
+}
+
+static int
+_dns_end(struct dns_state *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       state->num = 0;
+       if (state->context) {
+               hesiod_end(state->context);
+               state->context = NULL;
+       }
+       return NS_SUCCESS;
+}
+
+/*
+ * _dns_pwscan
+ *     Look for the Hesiod name provided in buffer in the NULL-terminated
+ *     list of zones,
+ *     and decode into pw/buffer/buflen.
+ */
+static int
+_dns_pwscan(int *retval, struct passwd *pw, char *buffer, size_t buflen,
+       struct dns_state *state, const char **zones)
+{
+       const char      **curzone;
+       char            **hp, *ep;
+       int             rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(state != NULL);
+       _DIAGASSERT(zones != NULL);
+
+       *retval = 0;
+
+       if (state->context == NULL) {   /* only start if Hesiod not setup */
+               rv = _dns_start(state);
+               if (rv != NS_SUCCESS)
+                       return rv;
+       }
+
+       hp = NULL;
+       rv = NS_NOTFOUND;
+
+       for (curzone = zones; *curzone; curzone++) {    /* search zones */
+               hp = hesiod_resolve(state->context, buffer, *curzone);
+               if (hp != NULL)
+                       break;
+               if (errno != ENOENT) {
+                       rv = NS_UNAVAIL;
+                       goto dnspwscan_out;
+               }
+       }
+       if (*curzone == NULL)
+               goto dnspwscan_out;
+
+       if ((ep = strchr(hp[0], '\n')) != NULL)
+               *ep = '\0';                             /* clear trailing \n */
+       if (_pw_parse(hp[0], pw, buffer, buflen, 1))    /* validate line */
+               rv = NS_SUCCESS;
+       else
+               rv = NS_UNAVAIL;
+
+ dnspwscan_out:
+       if (rv != NS_SUCCESS && rv != NS_NOTFOUND)
+               *retval = errno;
+       if (hp)
+               hesiod_free_list(state->context, hp);
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_dns_setpwent(void *nsrv, void *nscb, va_list ap)
+{
+
+       _dns_state.stayopen = 0;
+       return _dns_start(&_dns_state);
+}
+
+/*ARGSUSED*/
+static int
+_dns_setpassent(void *nsrv, void *nscb, va_list ap)
+{
+       int     *retval         = va_arg(ap, int *);
+       int      stayopen       = va_arg(ap, int);
+
+       int     rv;
+
+       _dns_state.stayopen = stayopen;
+       rv = _dns_start(&_dns_state);
+       *retval = (rv == NS_SUCCESS);
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_dns_endpwent(void *nsrv, void *nscb, va_list ap)
+{
+
+       _dns_state.stayopen = 0;
+       return _dns_end(&_dns_state);
+}
+
+/*ARGSUSED*/
+static int
+_dns_getpwent(void *nsrv, void *nscb, va_list ap)
+{
+       struct passwd   **retval = va_arg(ap, struct passwd **);
+
+       char    **hp, *ep;
+       int       rv;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+
+       if (_dns_state.num == -1)                       /* exhausted search */
+               return NS_NOTFOUND;
+
+       if (_dns_state.context == NULL) {
+                       /* only start if Hesiod not setup */
+               rv = _dns_start(&_dns_state);
+               if (rv != NS_SUCCESS)
+                       return rv;
+       }
+
+ next_dns_entry:
+       hp = NULL;
+       rv = NS_NOTFOUND;
+
+                                                       /* find passwd-NNN */
+       snprintf(_dns_passwdbuf, sizeof(_dns_passwdbuf),
+           "passwd-%u", _dns_state.num);
+       _dns_state.num++;
+
+       hp = hesiod_resolve(_dns_state.context, _dns_passwdbuf, "passwd");
+       if (hp == NULL) {
+               if (errno == ENOENT)
+                       _dns_state.num = -1;
+               else
+                       rv = NS_UNAVAIL;
+       } else {
+               if ((ep = strchr(hp[0], '\n')) != NULL)
+                       *ep = '\0';                     /* clear trailing \n */
+                                                       /* validate line */
+               if (_pw_parse(hp[0], &_dns_passwd,
+                   _dns_passwdbuf, sizeof(_dns_passwdbuf), 1))
+                       rv = NS_SUCCESS;
+               else {                          /* dodgy entry, try again */
+                       hesiod_free_list(_dns_state.context, hp);
+                       goto next_dns_entry;
+               }
+       }
+
+       if (hp)
+               hesiod_free_list(_dns_state.context, hp);
+       if (rv == NS_SUCCESS)
+               *retval = &_dns_passwd;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_dns_getpwent_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       struct passwd   *pw     = va_arg(ap, struct passwd *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct passwd  **result = va_arg(ap, struct passwd **);
+
+       char    **hp, *ep;
+       int       rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *retval = 0;
+
+       if (_dns_state.num == -1)                       /* exhausted search */
+               return NS_NOTFOUND;
+
+       if (_dns_state.context == NULL) {
+                       /* only start if Hesiod not setup */
+               rv = _dns_start(&_dns_state);
+               if (rv != NS_SUCCESS)
+                       return rv;
+       }
+
+ next_dns_entry:
+       hp = NULL;
+       rv = NS_NOTFOUND;
+
+                                                       /* find passwd-NNN */
+       snprintf(buffer, buflen, "passwd-%u", _dns_state.num);
+       _dns_state.num++;
+
+       hp = hesiod_resolve(_dns_state.context, buffer, "passwd");
+       if (hp == NULL) {
+               if (errno == ENOENT)
+                       _dns_state.num = -1;
+               else
+                       rv = NS_UNAVAIL;
+       } else {
+               if ((ep = strchr(hp[0], '\n')) != NULL)
+                       *ep = '\0';                     /* clear trailing \n */
+                                                       /* validate line */
+               if (_pw_parse(hp[0], pw, buffer, buflen, 1))
+                       rv = NS_SUCCESS;
+               else {                          /* dodgy entry, try again */
+                       hesiod_free_list(_dns_state.context, hp);
+                       goto next_dns_entry;
+               }
+       }
+
+       if (hp)
+               hesiod_free_list(_dns_state.context, hp);
+       if (rv == NS_SUCCESS)
+               *result = pw;
+       else
+               *result = NULL;
+       return rv;
+}
+
+static const char *_dns_uid_zones[] = {
+       "uid",
+       "passwd",
+       NULL
+};
+
+/*ARGSUSED*/
+static int
+_dns_getpwuid(void *nsrv, void *nscb, va_list ap)
+{
+       struct passwd   **retval = va_arg(ap, struct passwd **);
+       uid_t            uid    = va_arg(ap, uid_t);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = _dns_start(&_dns_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       snprintf(_dns_passwdbuf, sizeof(_dns_passwdbuf),
+           "%u", (unsigned int)uid);
+       rv = _dns_pwscan(&rerror, &_dns_passwd,
+           _dns_passwdbuf, sizeof(_dns_passwdbuf),
+           &_dns_state, _dns_uid_zones);
+       if (!_dns_state.stayopen)
+               _dns_end(&_dns_state);
+       if (rv == NS_SUCCESS && uid == _dns_passwd.pw_uid)
+               *retval = &_dns_passwd;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_dns_getpwuid_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       uid_t            uid    = va_arg(ap, uid_t);
+       struct passwd   *pw     = va_arg(ap, struct passwd *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct passwd  **result = va_arg(ap, struct passwd **);
+
+       struct dns_state state;
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       snprintf(buffer, buflen, "%u", (unsigned int)uid);
+       rv = _dns_pwscan(retval, pw, buffer, buflen, &state, _dns_uid_zones);
+       _dns_end(&state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       if (uid == pw->pw_uid) {
+               *result = pw;
+               return NS_SUCCESS;
+       } else
+               return NS_NOTFOUND;
+}
+
+static const char *_dns_nam_zones[] = {
+       "passwd",
+       NULL
+};
+
+/*ARGSUSED*/
+static int
+_dns_getpwnam(void *nsrv, void *nscb, va_list ap)
+{
+       struct passwd   **retval = va_arg(ap, struct passwd **);
+       const char      *name   = va_arg(ap, const char *);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = _dns_start(&_dns_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       snprintf(_dns_passwdbuf, sizeof(_dns_passwdbuf), "%s", name);
+       rv = _dns_pwscan(&rerror, &_dns_passwd,
+           _dns_passwdbuf, sizeof(_dns_passwdbuf),
+           &_dns_state, _dns_nam_zones);
+       if (!_dns_state.stayopen)
+               _dns_end(&_dns_state);
+       if (rv == NS_SUCCESS && strcmp(name, _dns_passwd.pw_name) == 0)
+               *retval = &_dns_passwd;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_dns_getpwnam_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       const char      *name   = va_arg(ap, const char *);
+       struct passwd   *pw     = va_arg(ap, struct passwd *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct passwd  **result = va_arg(ap, struct passwd **);
+
+       struct dns_state state;
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       snprintf(buffer, buflen, "%s", name);
+       rv = _dns_pwscan(retval, pw, buffer, buflen, &state, _dns_nam_zones);
+       _dns_end(&state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       if (strcmp(name, pw->pw_name) == 0) {
+               *result = pw;
+               return NS_SUCCESS;
+       } else
+               return NS_NOTFOUND;
+}
+
+#endif /* HESIOD */
+
+
+#ifdef YP
+               /*
+                *      nis methods
+                */
+       /* state shared between nis methods */
+struct nis_state {
+       int              stayopen;      /* see getpassent(3) */
+       char            *domain;        /* NIS domain */
+       int              done;          /* non-zero if search exhausted */
+       char            *current;       /* current first/next match */
+       int              currentlen;    /* length of _nis_current */
+       enum {                          /* shadow map type */
+               NISMAP_UNKNOWN,         /*  unknown ... */
+               NISMAP_NONE,            /*  none: use "passwd.by*" */
+               NISMAP_ADJUNCT,         /*  pw_passwd from "passwd.adjunct.*" */
+               NISMAP_MASTER           /*  all from "master.passwd.by*" */
+       }                maptype;
+};
+
+static struct nis_state                _nis_state;
+                                       /* storage for non _r functions */
+static struct passwd           _nis_passwd;
+static char                    _nis_passwdbuf[_GETPW_R_SIZE_MAX];
+
+       /* macros for deciding which NIS maps to use. */
+#define        PASSWD_BYNAME(x)        ((x)->maptype == NISMAP_MASTER \
+                                   ? "master.passwd.byname" : "passwd.byname")
+#define        PASSWD_BYUID(x)         ((x)->maptype == NISMAP_MASTER \
+                                   ? "master.passwd.byuid" : "passwd.byuid")
+
+static int
+_nis_start(struct nis_state *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       state->done = 0;
+       if (state->current) {
+               free(state->current);
+               state->current = NULL;
+       }
+       if (state->domain == NULL) {                    /* setup NIS */
+               switch (yp_get_default_domain(&state->domain)) {
+               case 0:
+                       break;
+               case YPERR_RESRC:
+                       return NS_TRYAGAIN;
+               default:
+                       return NS_UNAVAIL;
+               }
+       }
+
+                               /* determine where to get pw_passwd from */
+       if (state->maptype == NISMAP_UNKNOWN) {
+               int     r, order;
+
+               state->maptype = NISMAP_NONE;   /* default to no adjunct */
+               if (geteuid() != 0)             /* non-root can't use adjunct */
+                       return NS_SUCCESS;
+
+                                               /* look for "master.passwd.*" */
+               r = yp_order(state->domain, "master.passwd.byname", &order);
+               if (r == 0) {
+                       state->maptype = NISMAP_MASTER;
+                       return NS_SUCCESS;
+               }
+
+                       /* master.passwd doesn't exist, try passwd.adjunct */
+               if (r == YPERR_MAP) {
+                       r = yp_order(state->domain, "passwd.adjunct.byname",
+                           &order);
+                       if (r == 0)
+                               state->maptype = NISMAP_ADJUNCT;
+               }
+       }
+       return NS_SUCCESS;
+}
+
+static int
+_nis_end(struct nis_state *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       if (state->domain)
+               state->domain = NULL;
+       state->done = 0;
+       if (state->current)
+               free(state->current);
+       state->current = NULL;
+       state->maptype = NISMAP_UNKNOWN;
+       return NS_SUCCESS;
+}
+
+/*
+ * nis_parse
+ *     wrapper to _pw_parse that obtains the real password from the
+ *     "passwd.adjunct.byname" NIS map if the maptype is NISMAP_ADJUNCT.
+ */
+static int
+_nis_parse(const char *entry, struct passwd *pw, char *buf, size_t buflen,
+       struct nis_state *state)
+{
+       size_t  elen;
+
+       _DIAGASSERT(entry != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buf != NULL);
+       _DIAGASSERT(state != NULL);
+
+       elen = strlen(entry);
+       if (elen >= buflen)
+               return 0;
+       if (! _pw_parse(entry, pw, buf, buflen,
+           !(state->maptype == NISMAP_MASTER)))
+               return 0;
+
+       if ((state->maptype == NISMAP_ADJUNCT) &&
+           (strstr(pw->pw_passwd, "##") != NULL)) {
+               char    *data;
+               int     datalen;
+
+               if (yp_match(state->domain, "passwd.adjunct.byname",
+                   pw->pw_name, (int)strlen(pw->pw_name),
+                   &data, &datalen) == 0) {
+                       char    *bp, *ep;
+                                               /* skip name to get password */
+                       ep = data;
+                       if ((bp = strsep(&ep, ":")) != NULL &&
+                           (bp = strsep(&ep, ":")) != NULL) {
+                                       /* store new pw_passwd after entry */
+                               strlcpy(buf + elen, bp, buflen - elen);
+                               pw->pw_passwd = &buf[elen];
+                       }
+                       free(data);
+               }
+       }
+
+       return 1;
+}
+
+
+/*
+ * _nis_pwscan
+ *     Look for the yp key provided in buffer from map,
+ *     and decode into pw/buffer/buflen.
+ */
+static int
+_nis_pwscan(int *retval, struct passwd *pw, char *buffer, size_t buflen,
+       struct nis_state *state, const char *map)
+{
+       char    *data;
+       int     nisr, rv, datalen;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(state != NULL);
+       _DIAGASSERT(map != NULL);
+
+       *retval = 0;
+
+       if (state->domain == NULL) {    /* only start if NIS not setup */
+               rv = _nis_start(state);
+               if (rv != NS_SUCCESS)
+                       return rv;
+       }
+
+       data = NULL;
+       rv = NS_NOTFOUND;
+
+                                                       /* search map */
+       nisr = yp_match(state->domain, map, buffer, (int)strlen(buffer),
+           &data, &datalen);
+       switch (nisr) {
+       case 0:
+               data[datalen] = '\0';                   /* clear trailing \n */
+               if (_nis_parse(data, pw, buffer, buflen, state))
+                       rv = NS_SUCCESS;                /* validate line */
+               else
+                       rv = NS_UNAVAIL;
+               break;
+       case YPERR_KEY:
+               break;
+       default:
+               rv = NS_UNAVAIL;
+               break;
+       }
+
+       if (rv != NS_SUCCESS && rv != NS_NOTFOUND)
+               *retval = errno;
+       if (data)
+               free(data);
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_nis_setpwent(void *nsrv, void *nscb, va_list ap)
+{
+
+       _nis_state.stayopen = 0;
+       return _nis_start(&_nis_state);
+}
+
+/*ARGSUSED*/
+static int
+_nis_setpassent(void *nsrv, void *nscb, va_list ap)
+{
+       int     *retval         = va_arg(ap, int *);
+       int      stayopen       = va_arg(ap, int);
+
+       int     rv;
+
+       _nis_state.stayopen = stayopen;
+       rv = _nis_start(&_nis_state);
+       *retval = (rv == NS_SUCCESS);
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_nis_endpwent(void *nsrv, void *nscb, va_list ap)
+{
+
+       return _nis_end(&_nis_state);
+}
+
+
+/*ARGSUSED*/
+static int
+_nis_getpwent(void *nsrv, void *nscb, va_list ap)
+{
+       struct passwd   **retval = va_arg(ap, struct passwd **);
+
+       char    *key, *data;
+       int     keylen, datalen, rv, nisr;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+
+       if (_nis_state.done)                            /* exhausted search */
+               return NS_NOTFOUND;
+       if (_nis_state.domain == NULL) {
+                                       /* only start if NIS not setup */
+               rv = _nis_start(&_nis_state);
+               if (rv != NS_SUCCESS)
+                       return rv;
+       }
+
+ next_nis_entry:
+       key = NULL;
+       data = NULL;
+       rv = NS_NOTFOUND;
+
+       if (_nis_state.current) {                       /* already searching */
+               nisr = yp_next(_nis_state.domain, PASSWD_BYNAME(&_nis_state),
+                   _nis_state.current, _nis_state.currentlen,
+                   &key, &keylen, &data, &datalen);
+               free(_nis_state.current);
+               _nis_state.current = NULL;
+               switch (nisr) {
+               case 0:
+                       _nis_state.current = key;
+                       _nis_state.currentlen = keylen;
+                       key = NULL;
+                       break;
+               case YPERR_NOMORE:
+                       _nis_state.done = 1;
+                       goto nisent_out;
+               default:
+                       rv = NS_UNAVAIL;
+                       goto nisent_out;
+               }
+       } else {                                        /* new search */
+               if (yp_first(_nis_state.domain, PASSWD_BYNAME(&_nis_state),
+                   &_nis_state.current, &_nis_state.currentlen,
+                   &data, &datalen)) {
+                       rv = NS_UNAVAIL;
+                       goto nisent_out;
+               }
+       }
+
+       data[datalen] = '\0';                           /* clear trailing \n */
+                                                       /* validate line */
+       if (_nis_parse(data, &_nis_passwd,
+           _nis_passwdbuf, sizeof(_nis_passwdbuf), &_nis_state))
+               rv = NS_SUCCESS;
+       else {                                  /* dodgy entry, try again */
+               free(data);
+               goto next_nis_entry;
+       }
+
+ nisent_out:
+       if (key)
+               free(key);
+       if (data)
+               free(data);
+       if (rv == NS_SUCCESS)
+               *retval = &_nis_passwd;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_nis_getpwent_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       struct passwd   *pw     = va_arg(ap, struct passwd *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct passwd  **result = va_arg(ap, struct passwd **);
+
+       char    *key, *data;
+       int     keylen, datalen, rv, nisr;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *retval = 0;
+
+       if (_nis_state.done)                            /* exhausted search */
+               return NS_NOTFOUND;
+       if (_nis_state.domain == NULL) {
+                                       /* only start if NIS not setup */
+               rv = _nis_start(&_nis_state);
+               if (rv != NS_SUCCESS)
+                       return rv;
+       }
+
+ next_nis_entry:
+       key = NULL;
+       data = NULL;
+       rv = NS_NOTFOUND;
+
+       if (_nis_state.current) {                       /* already searching */
+               nisr = yp_next(_nis_state.domain, PASSWD_BYNAME(&_nis_state),
+                   _nis_state.current, _nis_state.currentlen,
+                   &key, &keylen, &data, &datalen);
+               free(_nis_state.current);
+               _nis_state.current = NULL;
+               switch (nisr) {
+               case 0:
+                       _nis_state.current = key;
+                       _nis_state.currentlen = keylen;
+                       key = NULL;
+                       break;
+               case YPERR_NOMORE:
+                       _nis_state.done = 1;
+                       goto nisent_out;
+               default:
+                       rv = NS_UNAVAIL;
+                       goto nisent_out;
+               }
+       } else {                                        /* new search */
+               if (yp_first(_nis_state.domain, PASSWD_BYNAME(&_nis_state),
+                   &_nis_state.current, &_nis_state.currentlen,
+                   &data, &datalen)) {
+                       rv = NS_UNAVAIL;
+                       goto nisent_out;
+               }
+       }
+
+       data[datalen] = '\0';                           /* clear trailing \n */
+                                                       /* validate line */
+       if (_nis_parse(data, pw, buffer, buflen, &_nis_state))
+               rv = NS_SUCCESS;
+       else {                                  /* dodgy entry, try again */
+               if (key)
+                       free(key);
+               free(data);
+               goto next_nis_entry;
+       }
+
+ nisent_out:
+       if (key)
+               free(key);
+       if (data)
+               free(data);
+       if (rv == NS_SUCCESS)
+               *result = pw;
+       else
+               *result = NULL;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_nis_getpwuid(void *nsrv, void *nscb, va_list ap)
+{
+       struct passwd   **retval = va_arg(ap, struct passwd **);
+       uid_t            uid    = va_arg(ap, uid_t);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = _nis_start(&_nis_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       snprintf(_nis_passwdbuf, sizeof(_nis_passwdbuf), "%u", (unsigned int)uid);
+       rv = _nis_pwscan(&rerror, &_nis_passwd,
+           _nis_passwdbuf, sizeof(_nis_passwdbuf),
+           &_nis_state, PASSWD_BYUID(&_nis_state));
+       if (!_nis_state.stayopen)
+               _nis_end(&_nis_state);
+       if (rv == NS_SUCCESS && uid == _nis_passwd.pw_uid)
+               *retval = &_nis_passwd;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_nis_getpwuid_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       uid_t            uid    = va_arg(ap, uid_t);
+       struct passwd   *pw     = va_arg(ap, struct passwd *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct passwd  **result = va_arg(ap, struct passwd **);
+
+       struct nis_state state;
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = _nis_start(&state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       snprintf(buffer, buflen, "%u", (unsigned int)uid);
+       rv = _nis_pwscan(retval, pw, buffer, buflen,
+           &state, PASSWD_BYUID(&state));
+       _nis_end(&state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       if (uid == pw->pw_uid) {
+               *result = pw;
+               return NS_SUCCESS;
+       } else
+               return NS_NOTFOUND;
+}
+
+/*ARGSUSED*/
+static int
+_nis_getpwnam(void *nsrv, void *nscb, va_list ap)
+{
+       struct passwd   **retval = va_arg(ap, struct passwd **);
+       const char      *name   = va_arg(ap, const char *);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = _nis_start(&_nis_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       snprintf(_nis_passwdbuf, sizeof(_nis_passwdbuf), "%s", name);
+       rv = _nis_pwscan(&rerror, &_nis_passwd,
+           _nis_passwdbuf, sizeof(_nis_passwdbuf),
+           &_nis_state, PASSWD_BYNAME(&_nis_state));
+       if (!_nis_state.stayopen)
+               _nis_end(&_nis_state);
+       if (rv == NS_SUCCESS && strcmp(name, _nis_passwd.pw_name) == 0)
+               *retval = &_nis_passwd;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_nis_getpwnam_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       const char      *name   = va_arg(ap, const char *);
+       struct passwd   *pw     = va_arg(ap, struct passwd *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct passwd  **result = va_arg(ap, struct passwd **);
+
+       struct nis_state state;
+       int     rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       snprintf(buffer, buflen, "%s", name);
+       memset(&state, 0, sizeof(state));
+       rv = _nis_start(&state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = _nis_pwscan(retval, pw, buffer, buflen,
+           &state, PASSWD_BYNAME(&state));
+       _nis_end(&state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       if (strcmp(name, pw->pw_name) == 0) {
+               *result = pw;
+               return NS_SUCCESS;
+       } else
+               return NS_NOTFOUND;
+}
+
+#endif /* YP */
+
+
+#ifdef _PASSWD_COMPAT
+               /*
+                *      compat methods
+                */
+
+       /* state shared between compat methods */
+
+struct compat_state {
+       int              stayopen;      /* see getpassent(3) */
+       DB              *db;            /* passwd DB */
+       int              keynum;        /* key counter, -1 if no more */
+       enum {                          /* current compat mode */
+               COMPAT_NOTOKEN = 0,     /*  no compat token present */
+               COMPAT_NONE,            /*  parsing normal pwd.db line */
+               COMPAT_FULL,            /*  parsing `+' entries */
+               COMPAT_USER,            /*  parsing `+name' entries */
+               COMPAT_NETGROUP         /*  parsing `+@netgroup' entries */
+       }                mode;
+       char            *user;          /* COMPAT_USER "+name" */
+       DB              *exclude;       /* compat exclude DB */
+       struct passwd    proto;         /* proto passwd entry */
+       char             protobuf[_GETPW_R_SIZE_MAX];
+                                       /* buffer for proto ptrs */
+       int              protoflags;    /* proto passwd flags */
+       int              version;
+};
+
+static struct compat_state     _compat_state;
+                                       /* storage for non _r functions */
+static struct passwd           _compat_passwd;
+static char                    _compat_passwdbuf[_GETPW_R_SIZE_MAX];
+
+static int
+_compat_start(struct compat_state *state)
+{
+       int     rv;
+
+       _DIAGASSERT(state != NULL);
+
+       state->keynum = 0;
+       if (state->db == NULL) {                /* not open yet */
+               DBT     key, data;
+               DBT     pkey, pdata;
+               char    bf[MAXLOGNAME];
+
+               rv = _pw_opendb(&state->db, &state->version);
+               if (rv != NS_SUCCESS)
+                       return rv;
+
+               state->mode = COMPAT_NOTOKEN;
+
+               /*
+                *      Determine if the "compat" token is present in pwd.db;
+                *      either "__YP!" or PW_KEYBYNAME+"+".
+                *      Only works if pwd_mkdb installs the token.
+                */
+               key.data = (u_char *)__UNCONST(__yp_token);
+               key.size = strlen(__yp_token);
+
+               bf[0] = _PW_KEYBYNAME;   /* Pre-token database support. */
+               bf[1] = '+';
+               pkey.data = (u_char *)bf;
+               pkey.size = 2;
+
+               if ((state->db->get)(state->db, &key, &data, 0) == 0
+                   || (state->db->get)(state->db, &pkey, &pdata, 0) == 0)
+                       state->mode = COMPAT_NONE;
+       }
+       return NS_SUCCESS;
+}
+
+static int
+_compat_end(struct compat_state *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       state->keynum = 0;
+       if (state->db) {
+               (void)(state->db->close)(state->db);
+               state->db = NULL;
+       }
+       state->mode = COMPAT_NOTOKEN;
+       if (state->user)
+               free(state->user);
+       state->user = NULL;
+       if (state->exclude != NULL)
+               (void)(state->exclude->close)(state->exclude);
+       state->exclude = NULL;
+       state->proto.pw_name = NULL;
+       state->protoflags = 0;
+       return NS_SUCCESS;
+}
+
+/*
+ * _compat_add_exclude
+ *     add the name to the exclude list in state->exclude.
+ */
+static int
+_compat_add_exclude(struct compat_state *state, const char *name)
+{
+       DBT     key, data;
+
+       _DIAGASSERT(state != NULL);
+       _DIAGASSERT(name != NULL);
+
+                               /* initialize the exclusion table if needed */
+       if (state->exclude == NULL) {
+               state->exclude = dbopen(NULL, O_RDWR, 600, DB_HASH, NULL);
+               if (state->exclude == NULL)
+                       return 0;
+       }
+
+       key.size = strlen(name);                        /* set up the key */
+       key.data = (u_char *)__UNCONST(name);
+
+       data.data = NULL;                               /* data is nothing */
+       data.size = 0;
+
+                                                       /* store it */
+       if ((state->exclude->put)(state->exclude, &key, &data, 0) == -1)
+               return 0;
+
+       return 1;
+}
+
+/*
+ * _compat_is_excluded
+ *     test if a name is on the compat mode exclude list
+ */
+static int
+_compat_is_excluded(struct compat_state *state, const char *name)
+{
+       DBT     key, data;
+
+       _DIAGASSERT(state != NULL);
+       _DIAGASSERT(name != NULL);
+
+       if (state->exclude == NULL)
+               return 0;       /* nothing excluded */
+
+       key.size = strlen(name);                        /* set up the key */
+       key.data = (u_char *)__UNCONST(name);
+
+       if ((state->exclude->get)(state->exclude, &key, &data, 0) == 0)
+               return 1;                               /* is excluded */
+
+       return 0;
+}
+
+
+/*
+ * _passwdcompat_bad
+ *     log an error if "files" or "compat" is specified in
+ *     passwd_compat database
+ */
+/*ARGSUSED*/
+static int
+_passwdcompat_bad(void *nsrv, void *nscb, va_list ap)
+{
+       static int warned;
+
+       _DIAGASSERT(nsrv != NULL);
+       _DIAGASSERT(nscb != NULL);
+
+       if (!warned) {
+               syslog(LOG_ERR,
+                       "nsswitch.conf passwd_compat database can't use '%s'",
+                       (char *)nscb);
+       }
+       warned = 1;
+       return NS_UNAVAIL;
+}
+
+/*
+ * _passwdcompat_setpassent
+ *     Call setpassent for all passwd_compat sources.
+ */
+static int
+_passwdcompat_setpassent(int stayopen)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_passwdcompat_bad, "files")
+               NS_DNS_CB(_dns_setpassent, NULL)
+               NS_NIS_CB(_nis_setpassent, NULL)
+               NS_COMPAT_CB(_passwdcompat_bad, "compat")
+               NS_NULL_CB
+       };
+
+       int     rv, result;
+
+       rv = nsdispatch(NULL, dtab, NSDB_PASSWD_COMPAT, "setpassent",
+           __nsdefaultnis_forceall, &result, stayopen);
+       return rv;
+}
+
+/*
+ * _passwdcompat_endpwent
+ *     Call endpwent for all passwd_compat sources.
+ */
+static int
+_passwdcompat_endpwent(void)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_passwdcompat_bad, "files")
+               NS_DNS_CB(_dns_endpwent, NULL)
+               NS_NIS_CB(_nis_endpwent, NULL)
+               NS_COMPAT_CB(_passwdcompat_bad, "compat")
+               NS_NULL_CB
+       };
+
+       return nsdispatch(NULL, dtab, NSDB_PASSWD_COMPAT, "endpwent",
+           __nsdefaultnis_forceall);
+}
+
+/*
+ * _passwdcompat_pwscan
+ *     When a name lookup in compat mode is required (e.g., `+name', or a
+ *     name in `+@netgroup'), look it up in the 'passwd_compat' nsswitch
+ *     database.
+ *     Fail if passwd_compat contains files or compat.
+ */
+static int
+_passwdcompat_pwscan(struct passwd *pw, char *buffer, size_t buflen,
+       int search, const char *name, uid_t uid)
+{
+       static const ns_dtab compatentdtab[] = {
+               NS_FILES_CB(_passwdcompat_bad, "files")
+               NS_DNS_CB(_dns_getpwent_r, NULL)
+               NS_NIS_CB(_nis_getpwent_r, NULL)
+               NS_COMPAT_CB(_passwdcompat_bad, "compat")
+               NS_NULL_CB
+       };
+       static const ns_dtab compatuiddtab[] = {
+               NS_FILES_CB(_passwdcompat_bad, "files")
+               NS_DNS_CB(_dns_getpwuid_r, NULL)
+               NS_NIS_CB(_nis_getpwuid_r, NULL)
+               NS_COMPAT_CB(_passwdcompat_bad, "compat")
+               NS_NULL_CB
+       };
+       static const ns_dtab compatnamdtab[] = {
+               NS_FILES_CB(_passwdcompat_bad, "files")
+               NS_DNS_CB(_dns_getpwnam_r, NULL)
+               NS_NIS_CB(_nis_getpwnam_r, NULL)
+               NS_COMPAT_CB(_passwdcompat_bad, "compat")
+               NS_NULL_CB
+       };
+
+       int             rv, crv;
+       struct passwd   *cpw;
+
+       switch (search) {
+       case _PW_KEYBYNUM:
+               rv = nsdispatch(NULL, compatentdtab,
+                   NSDB_PASSWD_COMPAT, "getpwent_r", __nsdefaultnis,
+                   &crv, pw, buffer, buflen, &cpw);
+               break;
+       case _PW_KEYBYNAME:
+               _DIAGASSERT(name != NULL);
+               rv = nsdispatch(NULL, compatnamdtab,
+                   NSDB_PASSWD_COMPAT, "getpwnam_r", __nsdefaultnis,
+                   &crv, name, pw, buffer, buflen, &cpw);
+               break;
+       case _PW_KEYBYUID:
+               rv = nsdispatch(NULL, compatuiddtab,
+                   NSDB_PASSWD_COMPAT, "getpwuid_r", __nsdefaultnis,
+                   &crv, uid, pw, buffer, buflen, &cpw);
+               break;
+       default:
+               abort();
+               /*NOTREACHED*/
+       }
+       return rv;
+}
+
+/*
+ * _compat_pwscan
+ *     Search state->db for the next desired entry.
+ *     If search is _PW_KEYBYNUM, look for state->keynum.
+ *     If search is _PW_KEYBYNAME, look for name.
+ *     If search is _PW_KEYBYUID, look for uid.
+ *     Sets *retval to the errno if the result is not NS_SUCCESS
+ *     or NS_NOTFOUND.
+ */
+static int
+_compat_pwscan(int *retval, struct passwd *pw, char *buffer, size_t buflen,
+       struct compat_state *state, int search, const char *name, uid_t uid)
+{
+       DBT              key;
+       int              rv, r, pwflags;
+       const char      *user, *host, *dom;
+       const void      *from;
+       size_t           fromlen;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(state != NULL);
+       /* name may be NULL */
+
+       *retval = 0;
+
+       if (state->db == NULL) {
+               rv = _compat_start(state);
+               if (rv != NS_SUCCESS)
+                       return rv;
+       }
+       if (buflen <= 1) {                      /* buffer too small */
+               *retval = ERANGE;
+               return NS_UNAVAIL;
+       }
+
+       for (;;) {                              /* loop over pwd.db */
+               rv = NS_NOTFOUND;
+               if (state->mode != COMPAT_NOTOKEN &&
+                   state->mode != COMPAT_NONE) {
+                                               /* doing a compat lookup */
+                       struct passwd   cpw;
+                       char            cbuf[_GETPW_R_SIZE_MAX];
+
+                       switch (state->mode) {
+
+                       case COMPAT_FULL:
+                                       /* get next user or lookup by key */
+                               rv = _passwdcompat_pwscan(&cpw,
+                                   cbuf, sizeof(cbuf), search, name, uid);
+                               if (rv != NS_SUCCESS)
+                                       state->mode = COMPAT_NONE;
+                               break;
+
+                       case COMPAT_NETGROUP:
+/* XXXREENTRANT: getnetgrent is not thread safe */
+                                       /* get next user from netgroup */
+                               r = getnetgrent(&host, &user, &dom);
+                               if (r == 0) {   /* end of group */
+                                       endnetgrent();
+                                       state->mode = COMPAT_NONE;
+                                       break;
+                               }
+                               if (!user || !*user)
+                                       break;
+                               rv = _passwdcompat_pwscan(&cpw,
+                                   cbuf, sizeof(cbuf),
+                                   _PW_KEYBYNAME, user, 0);
+                               break;
+
+                       case COMPAT_USER:
+                                       /* get specific user */
+                               if (state->user == NULL) {
+                                       state->mode = COMPAT_NONE;
+                                       break;
+                               }
+                               rv = _passwdcompat_pwscan(&cpw,
+                                   cbuf, sizeof(cbuf),
+                                   _PW_KEYBYNAME, state->user, 0);
+                               free(state->user);
+                               state->user = NULL;
+                               state->mode = COMPAT_NONE;
+                               break;
+
+                       case COMPAT_NOTOKEN:
+                       case COMPAT_NONE:
+                               abort();
+
+                       }
+                       if (rv != NS_SUCCESS)   /* if not matched, next loop */
+                               continue;
+
+                               /* copy cpw to pw, applying prototype */
+                       if (! _pw_copy(&cpw, pw, buffer, buflen,
+                           &state->proto, state->protoflags)) {
+                               rv = NS_UNAVAIL;
+                               break;
+                       }
+
+                       if (_compat_is_excluded(state, pw->pw_name))
+                               continue;       /* excluded; next loop */
+
+                       if ((search == _PW_KEYBYNAME
+                                       && strcmp(pw->pw_name, name) != 0)
+                           || (search == _PW_KEYBYUID && pw->pw_uid != uid)) {
+                               continue;       /* not specific; next loop */
+                       }
+
+                       break;                  /* exit loop if found */
+               } else {                        /* not a compat line */
+                       state->proto.pw_name = NULL;
+                                               /* clear prototype */
+               }
+
+               if (state->mode == COMPAT_NOTOKEN) {
+                               /* no compat token; do direct lookup */
+                       switch (search) {
+                       case _PW_KEYBYNUM:
+                               if (state->keynum == -1)  /* no more records */
+                                       return NS_NOTFOUND;
+                               state->keynum++;
+                               from = &state->keynum;
+                               fromlen = sizeof(state->keynum);
+                               break;
+                       case _PW_KEYBYNAME:
+                               from = name;
+                               fromlen = strlen(name);
+                               break;
+                       case _PW_KEYBYUID:
+                               from = &uid;
+                               fromlen = sizeof(uid);
+                               break;
+                       default:
+                               abort();
+                       }
+                       buffer[0] = search;
+               } else {
+                               /* compat token; do line by line */
+                       if (state->keynum == -1)  /* no more records */
+                               return NS_NOTFOUND;
+                       state->keynum++;
+                       from = &state->keynum;
+                       fromlen = sizeof(state->keynum);
+                       buffer[0] = _PW_KEYBYNUM;
+               }
+
+               if (buflen <= fromlen) {                /* buffer too small */
+                       *retval = ERANGE;
+                       return NS_UNAVAIL;
+               }
+               memmove(buffer + 1, from, fromlen);     /* setup key */
+               key.size = fromlen + 1;
+               key.data = (u_char *)buffer;
+
+               rv = _pw_getkey(state->db, &key, pw, buffer, buflen, &pwflags,
+                   state->version);
+               if (rv != NS_SUCCESS)           /* stop on error */
+                       break;
+
+               if (state->mode == COMPAT_NOTOKEN)
+                       break;                  /* stop if no compat token */
+
+               if (pw->pw_name[0] == '+') {
+                                               /* compat inclusion */
+                       switch(pw->pw_name[1]) {
+                       case '\0':              /* `+' */
+                               state->mode = COMPAT_FULL;
+                                               /* reset passwd_compat search */
+/* XXXREENTRANT: setpassent is not thread safe ? */
+                               (void) _passwdcompat_setpassent(0);
+                               break;
+                       case '@':               /* `+@netgroup' */
+                               state->mode = COMPAT_NETGROUP;
+                                               /* reset netgroup search */
+/* XXXREENTRANT: setnetgrent is not thread safe */
+                               setnetgrent(pw->pw_name + 2);
+                               break;
+                       default:                /* `+name' */
+                               state->mode = COMPAT_USER;
+                               if (state->user)
+                                       free(state->user);
+                               state->user = strdup(pw->pw_name + 1);
+                               break;
+                       }
+                                               /* save the prototype */
+                       state->protoflags = pwflags;
+                       if (! _pw_copy(pw, &state->proto, state->protobuf,
+                           sizeof(state->protobuf), NULL, 0)) {
+                               rv = NS_UNAVAIL;
+                               break;
+                       }
+                       continue;               /* loop again after inclusion */
+               } else if (pw->pw_name[0] == '-') {
+                                               /* compat exclusion */
+                       rv = NS_SUCCESS;
+                       switch(pw->pw_name[1]) {
+                       case '\0':              /* `-' */
+                               break;
+                       case '@':               /* `-@netgroup' */
+/* XXXREENTRANT: {set,get,end}netgrent is not thread safe */
+                               setnetgrent(pw->pw_name + 2);
+                               while (getnetgrent(&host, &user, &dom)) {
+                                       if (!user || !*user)
+                                               continue;
+                                       if (! _compat_add_exclude(state,user)) {
+                                               rv = NS_UNAVAIL;
+                                               break;
+                                       }
+                               }
+                               endnetgrent();
+                               break;
+                       default:                /* `-name' */
+                               if (! _compat_add_exclude(state,
+                                   pw->pw_name + 1)) {
+                                       rv = NS_UNAVAIL;
+                               }
+                               break;
+                       }
+                       if (rv != NS_SUCCESS)   /* exclusion failure */
+                               break;
+                       continue;               /* loop again after exclusion */
+               }
+               if (search == _PW_KEYBYNUM ||
+                   (search == _PW_KEYBYUID && pw->pw_uid == uid) ||
+                   (search == _PW_KEYBYNAME && strcmp(pw->pw_name, name) == 0))
+                       break;                  /* token mode match found */
+       }
+
+       if (rv == NS_NOTFOUND &&
+           (search == _PW_KEYBYNUM || state->mode != COMPAT_NOTOKEN))
+               state->keynum = -1;             /* flag `no more records' */
+
+       if (rv == NS_SUCCESS) {
+               if ((search == _PW_KEYBYNAME && strcmp(pw->pw_name, name) != 0)
+                   || (search == _PW_KEYBYUID && pw->pw_uid != uid))
+                       rv = NS_NOTFOUND;
+       }
+
+       if (rv != NS_SUCCESS && rv != NS_NOTFOUND)
+               *retval = errno;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_compat_setpwent(void *nsrv, void *nscb, va_list ap)
+{
+
+                                       /* force passwd_compat setpwent() */
+       (void) _passwdcompat_setpassent(0);
+
+                                       /* reset state, keep db open */
+       _compat_state.stayopen = 0;
+       return _compat_start(&_compat_state);
+}
+
+/*ARGSUSED*/
+static int
+_compat_setpassent(void *nsrv, void *nscb, va_list ap)
+{
+       int     *retval         = va_arg(ap, int *);
+       int      stayopen       = va_arg(ap, int);
+
+       int     rv;
+
+                                       /* force passwd_compat setpassent() */
+       (void) _passwdcompat_setpassent(stayopen);
+
+       _compat_state.stayopen = stayopen;
+       rv = _compat_start(&_compat_state);
+       *retval = (rv == NS_SUCCESS);
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_compat_endpwent(void *nsrv, void *nscb, va_list ap)
+{
+
+                                       /* force passwd_compat endpwent() */
+       (void) _passwdcompat_endpwent();
+
+                                       /* reset state, close db */
+       _compat_state.stayopen = 0;
+       return _compat_end(&_compat_state);
+}
+
+
+/*ARGSUSED*/
+static int
+_compat_getpwent(void *nsrv, void *nscb, va_list ap)
+{
+       struct passwd   **retval = va_arg(ap, struct passwd **);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = _compat_pwscan(&rerror, &_compat_passwd,
+           _compat_passwdbuf, sizeof(_compat_passwdbuf),
+           &_compat_state, _PW_KEYBYNUM, NULL, 0);
+       if (rv == NS_SUCCESS)
+               *retval = &_compat_passwd;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_compat_getpwent_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       struct passwd   *pw     = va_arg(ap, struct passwd *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct passwd  **result = va_arg(ap, struct passwd **);
+
+       int             rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       rv = _compat_pwscan(retval, pw, buffer, buflen, &_compat_state,
+           _PW_KEYBYNUM, NULL, 0);
+       if (rv == NS_SUCCESS)
+               *result = pw;
+       else
+               *result = NULL;
+       return rv;
+}
+
+
+/*ARGSUSED*/
+static int
+_compat_getpwnam(void *nsrv, void *nscb, va_list ap)
+{
+       struct passwd   **retval = va_arg(ap, struct passwd **);
+       const char      *name   = va_arg(ap, const char *);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = _compat_start(&_compat_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = _compat_pwscan(&rerror, &_compat_passwd,
+           _compat_passwdbuf, sizeof(_compat_passwdbuf),
+           &_compat_state, _PW_KEYBYNAME, name, 0);
+       if (!_compat_state.stayopen)
+               _compat_end(&_compat_state);
+       if (rv == NS_SUCCESS)
+               *retval = &_compat_passwd;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_compat_getpwnam_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       const char      *name   = va_arg(ap, const char *);
+       struct passwd   *pw     = va_arg(ap, struct passwd *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct passwd  **result = va_arg(ap, struct passwd **);
+
+       struct compat_state     state;
+       int             rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = _compat_pwscan(retval, pw, buffer, buflen, &state,
+           _PW_KEYBYNAME, name, 0);
+       _compat_end(&state);
+       if (rv == NS_SUCCESS)
+               *result = pw;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_compat_getpwuid(void *nsrv, void *nscb, va_list ap)
+{
+       struct passwd   **retval = va_arg(ap, struct passwd **);
+       uid_t            uid    = va_arg(ap, uid_t);
+
+       int     rv, rerror;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       rv = _compat_start(&_compat_state);
+       if (rv != NS_SUCCESS)
+               return rv;
+       rv = _compat_pwscan(&rerror, &_compat_passwd,
+           _compat_passwdbuf, sizeof(_compat_passwdbuf),
+           &_compat_state, _PW_KEYBYUID, NULL, uid);
+       if (!_compat_state.stayopen)
+               _compat_end(&_compat_state);
+       if (rv == NS_SUCCESS)
+               *retval = &_compat_passwd;
+       return rv;
+}
+
+/*ARGSUSED*/
+static int
+_compat_getpwuid_r(void *nsrv, void *nscb, va_list ap)
+{
+       int             *retval = va_arg(ap, int *);
+       uid_t            uid    = va_arg(ap, uid_t);
+       struct passwd   *pw     = va_arg(ap, struct passwd *);
+       char            *buffer = va_arg(ap, char *);
+       size_t           buflen = va_arg(ap, size_t);
+       struct passwd  **result = va_arg(ap, struct passwd **);
+
+       struct compat_state     state;
+       int             rv;
+
+       _DIAGASSERT(retval != NULL);
+       _DIAGASSERT(pw != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       memset(&state, 0, sizeof(state));
+       rv = _compat_pwscan(retval, pw, buffer, buflen, &state,
+           _PW_KEYBYUID, NULL, uid);
+       _compat_end(&state);
+       if (rv == NS_SUCCESS)
+               *result = pw;
+       return rv;
+}
+
+#endif /* _PASSWD_COMPAT */
+
+
+               /*
+                *      public functions
+                */
+
+struct passwd *
+getpwent(void)
+{
+       int             r;
+       struct passwd   *retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getpwent, NULL)
+               NS_DNS_CB(_dns_getpwent, NULL)
+               NS_NIS_CB(_nis_getpwent, NULL)
+               NS_COMPAT_CB(_compat_getpwent, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&_pwmutex);
+       r = nsdispatch(NULL, dtab, NSDB_PASSWD, "getpwent", __nsdefaultcompat,
+           &retval);
+       mutex_unlock(&_pwmutex);
+       return (r == NS_SUCCESS) ? retval : NULL;
+}
+
+int
+getpwent_r(struct passwd *pwd, char *buffer, size_t buflen,
+    struct passwd **result)
+{
+       int     r, retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getpwent_r, NULL)
+               NS_DNS_CB(_dns_getpwent_r, NULL)
+               NS_NIS_CB(_nis_getpwent_r, NULL)
+               NS_COMPAT_CB(_compat_getpwent_r, NULL)
+               NS_NULL_CB
+       };
+
+       _DIAGASSERT(pwd != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       retval = 0;
+       mutex_lock(&_pwmutex);
+       r = nsdispatch(NULL, dtab, NSDB_PASSWD, "getpwent_r", __nsdefaultcompat,
+           &retval, pwd, buffer, buflen, result);
+       mutex_unlock(&_pwmutex);
+       switch (r) {
+       case NS_SUCCESS:
+       case NS_NOTFOUND:
+               return 0;
+       default:
+               return retval;
+       }
+}
+
+
+struct passwd *
+getpwnam(const char *name)
+{
+       int             rv;
+       struct passwd   *retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getpwnam, NULL)
+               NS_DNS_CB(_dns_getpwnam, NULL)
+               NS_NIS_CB(_nis_getpwnam, NULL)
+               NS_COMPAT_CB(_compat_getpwnam, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&_pwmutex);
+       rv = nsdispatch(NULL, dtab, NSDB_PASSWD, "getpwnam", __nsdefaultcompat,
+           &retval, name);
+       mutex_unlock(&_pwmutex);
+       return (rv == NS_SUCCESS) ? retval : NULL;
+}
+
+int
+getpwnam_r(const char *name, struct passwd *pwd, char *buffer, size_t buflen,
+       struct passwd **result)
+{
+       int     r, retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getpwnam_r, NULL)
+               NS_DNS_CB(_dns_getpwnam_r, NULL)
+               NS_NIS_CB(_nis_getpwnam_r, NULL)
+               NS_COMPAT_CB(_compat_getpwnam_r, NULL)
+               NS_NULL_CB
+       };
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(pwd != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       retval = 0;
+       mutex_lock(&_pwmutex);
+       r = nsdispatch(NULL, dtab, NSDB_PASSWD, "getpwnam_r", __nsdefaultcompat,
+           &retval, name, pwd, buffer, buflen, result);
+       mutex_unlock(&_pwmutex);
+       switch (r) {
+       case NS_SUCCESS:
+       case NS_NOTFOUND:
+               return 0;
+       default:
+               return retval;
+       }
+}
+
+struct passwd *
+getpwuid(uid_t uid)
+{
+       int             rv;
+       struct passwd   *retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getpwuid, NULL)
+               NS_DNS_CB(_dns_getpwuid, NULL)
+               NS_NIS_CB(_nis_getpwuid, NULL)
+               NS_COMPAT_CB(_compat_getpwuid, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&_pwmutex);
+       rv = nsdispatch(NULL, dtab, NSDB_PASSWD, "getpwuid", __nsdefaultcompat,
+           &retval, uid);
+       mutex_unlock(&_pwmutex);
+       return (rv == NS_SUCCESS) ? retval : NULL;
+}
+
+int
+getpwuid_r(uid_t uid, struct passwd *pwd, char *buffer, size_t buflen,
+       struct passwd **result)
+{
+       int     r, retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getpwuid_r, NULL)
+               NS_DNS_CB(_dns_getpwuid_r, NULL)
+               NS_NIS_CB(_nis_getpwuid_r, NULL)
+               NS_COMPAT_CB(_compat_getpwuid_r, NULL)
+               NS_NULL_CB
+       };
+
+       _DIAGASSERT(pwd != NULL);
+       _DIAGASSERT(buffer != NULL);
+       _DIAGASSERT(result != NULL);
+
+       *result = NULL;
+       retval = 0;
+       mutex_lock(&_pwmutex);
+       r = nsdispatch(NULL, dtab, NSDB_PASSWD, "getpwuid_r", __nsdefaultcompat,
+           &retval, uid, pwd, buffer, buflen, result);
+       mutex_unlock(&_pwmutex);
+       switch (r) {
+       case NS_SUCCESS:
+       case NS_NOTFOUND:
+               return 0;
+       default:
+               return retval;
+       }
+}
+
+void
+endpwent(void)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_endpwent, NULL)
+               NS_DNS_CB(_dns_endpwent, NULL)
+               NS_NIS_CB(_nis_endpwent, NULL)
+               NS_COMPAT_CB(_compat_endpwent, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&_pwmutex);
+                                       /* force all endpwent() methods */
+       (void) nsdispatch(NULL, dtab, NSDB_PASSWD, "endpwent",
+           __nsdefaultcompat_forceall);
+       mutex_unlock(&_pwmutex);
+}
+
+/*ARGSUSED*/
+int
+setpassent(int stayopen)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_setpassent, NULL)
+               NS_DNS_CB(_dns_setpassent, NULL)
+               NS_NIS_CB(_nis_setpassent, NULL)
+               NS_COMPAT_CB(_compat_setpassent, NULL)
+               NS_NULL_CB
+       };
+       int     rv, retval;
+
+       mutex_lock(&_pwmutex);
+                                       /* force all setpassent() methods */
+       rv = nsdispatch(NULL, dtab, NSDB_PASSWD, "setpassent",
+           __nsdefaultcompat_forceall, &retval, stayopen);
+       mutex_unlock(&_pwmutex);
+       return (rv == NS_SUCCESS) ? retval : 0;
+}
+
+void
+setpwent(void)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_setpwent, NULL)
+               NS_DNS_CB(_dns_setpwent, NULL)
+               NS_NIS_CB(_nis_setpwent, NULL)
+               NS_COMPAT_CB(_compat_setpwent, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&_pwmutex);
+                                       /* force all setpwent() methods */
+       (void) nsdispatch(NULL, dtab, NSDB_PASSWD, "setpwent",
+           __nsdefaultcompat_forceall);
+       mutex_unlock(&_pwmutex);
+}
diff --git a/lib/nbsd_libc/gen/getttyent.3 b/lib/nbsd_libc/gen/getttyent.3
new file mode 100644 (file)
index 0000000..e0757ba
--- /dev/null
@@ -0,0 +1,219 @@
+.\"    $NetBSD: getttyent.3,v 1.18 2006/04/23 16:46:32 wiz Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getttyent.3        8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 18, 2006
+.Dt GETTTYENT 3
+.Os
+.Sh NAME
+.Nm getttyent ,
+.Nm getttynam ,
+.Nm setttyent ,
+.Nm setttyentpath ,
+.Nm endttyent
+.Nd get ttys file entry
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ttyent.h
+.Ft struct ttyent *
+.Fn getttyent
+.Ft struct ttyent *
+.Fn getttynam "char *name"
+.Ft int
+.Fn setttyent void
+.Ft int
+.Fn setttyentpath "const char *path"
+.Ft int
+.Fn endttyent void
+.Sh DESCRIPTION
+The
+.Fn getttyent ,
+and
+.Fn getttynam
+functions
+each return a pointer to an object, with the following structure,
+containing the broken-out fields of a line from the tty description
+file.
+.Bd -literal
+struct ttyent {
+       char    *ty_name;       /* terminal device name */
+       char    *ty_getty;      /* command to execute */
+       char    *ty_type;       /* terminal type */
+#define        TTY_ON          0x01    /* enable logins */
+#define        TTY_SECURE      0x02    /* allow uid of 0 to login */
+#define        TTY_LOCAL       0x04    /* set 'CLOCAL' on open (dev. specific) */
+#define        TTY_RTSCTS      0x08    /* set 'CRTSCTS' on open (dev. specific) */
+#define        TTY_SOFTCAR     0x10    /* ignore hardware carrier (dev. spec.) */
+#define        TTY_MDMBUF      0x20    /* set 'MDMBUF' on open (dev. specific) */
+#define        TTY_DTRCTS      0x40    /* set 'CDTRCTS' on open (dev. specific) */
+       int     ty_status;      /* flag values */
+       char    *ty_window;     /* command for window manager */
+       char    *ty_comment;    /* comment field */
+       char    *ty_class;      /* category of tty usage */
+};
+.Ed
+.Pp
+The fields are as follows:
+.Bl -tag -width ty_comment
+.It Fa ty_name
+The name of the character-special file.
+.It Fa ty_getty
+The name of the command invoked by
+.Xr init 8
+to initialize tty line characteristics.
+.It Fa ty_type
+The name of the default terminal type connected to this tty line.
+.It Fa ty_status
+A mask of bit fields which indicate various actions allowed on this
+tty line.
+The possible flags are as follows:
+.Bl -tag -width TTY_SOFTCAR
+.It Dv TTY_ON
+Enables logins (i.e.,
+.Xr init 8
+will start the command referenced by
+.Fa ty_getty
+on this entry).
+.It Dv TTY_SECURE
+Allow users with a uid of 0 to login on this terminal.
+.It Dv TTY_LOCAL
+If the terminal port's driver supports it, cause the line
+to be treated as ``local.''
+.It Dv TTY_MDMBUF
+If the terminal port's driver supports it, use
+DTR/DCD hardware flow control on the line by default.
+.It Dv TTY_RTSCTS
+If the terminal port's driver supports it, use
+full-duplex RTS/CTS hardware flow control on the line
+by default.
+.It Dv TTY_SOFTCAR
+If the terminal port's driver supports it, ignore hardware
+carrier on the line.
+.El
+.It Fa ty_window
+The command to execute for a window system associated with the line.
+.It Fa ty_comment
+Any trailing comment field, with any leading hash marks (``#'') or
+whitespace removed.
+.It Fa ty_class
+A key indexing into a termcap-style database (/etc/ttyclasses)
+of attributes for this class of tty.
+No attributes are currently defined or used,
+so there are currently no functions to retrieve them.
+.El
+.Pp
+If any of the fields pointing to character strings are unspecified,
+they are returned as null pointers.
+The field
+.Fa ty_status
+will be zero if no flag values are specified.
+.Pp
+See
+.Xr ttys 5
+for a more complete discussion of the meaning and usage of the
+fields.
+.Pp
+The
+.Fn getttyent
+function
+reads the next line from the ttys file, opening the file if necessary.
+The
+.Fn setttyent
+function
+rewinds the file if open, or opens the file if it is unopened.
+The
+.Fn setttyentpath
+function
+is equivalent to
+.Fn setttyent
+but accepts an additional argument to read the ttys information from
+an alternate file instead of the default location
+.Pq defined in Dv _PATH_TTYS .
+The
+.Fn endttyent
+function
+closes any open files.
+.Pp
+The
+.Fn getttynam
+function
+searches from the beginning of the file until a matching
+.Fa name
+is found
+(or until
+.Dv EOF
+is encountered).
+.Sh RETURN VALUES
+The routines
+.Fn getttyent
+and
+.Fn getttynam
+return a null pointer on
+.Dv EOF
+or error.
+The
+.Fn setttyent
+and
+.Fn setttyentpath
+functions
+and
+.Fn endttyent
+return 0 on failure and 1 on success.
+.Sh FILES
+.Bl -tag -width /etc/ttys -compact
+.It Pa /etc/ttys
+.El
+.Sh SEE ALSO
+.Xr login 1 ,
+.Xr ttyslot 3 ,
+.Xr gettytab 5 ,
+.Xr termcap 5 ,
+.Xr ttys 5 ,
+.Xr getty 8 ,
+.Xr init 8 ,
+.Xr ttyflags 8
+.Sh HISTORY
+The
+.Fn getttyent ,
+.Fn getttynam ,
+.Fn setttyent ,
+and
+.Fn endttyent
+functions appeared in
+.Bx 4.3 .
+The
+.Fn setttyentpath
+function appeared in
+.Nx 4.0 .
+.Sh BUGS
+These functions use static data storage;
+if the data is needed for future use, it should be
+copied before any subsequent calls overwrite it.
diff --git a/lib/nbsd_libc/gen/getttyent.c b/lib/nbsd_libc/gen/getttyent.c
new file mode 100644 (file)
index 0000000..f3f3e2a
--- /dev/null
@@ -0,0 +1,248 @@
+/*     $NetBSD: getttyent.c,v 1.23 2006/04/17 23:29:21 salo Exp $      */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getttyent.c        8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getttyent.c,v 1.23 2006/04/17 23:29:21 salo Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <string.h>
+#include <ttyent.h>
+#include <errno.h>
+#include <err.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(endttyent,_endttyent)
+__weak_alias(getttyent,_getttyent)
+__weak_alias(getttynam,_getttynam)
+__weak_alias(setttyent,_setttyent)
+__weak_alias(setttyentpath,_setttyentpath)
+#endif
+
+static FILE *tf;
+static size_t lineno = 0;
+static char *skip(char *, char *);
+static char *value(char *);
+
+struct ttyent *
+getttynam(const char *tty)
+{
+       struct ttyent *t;
+
+       _DIAGASSERT(tty != NULL);
+
+       setttyent();
+       while ((t = getttyent()) != NULL)
+               if (!strcmp(tty, t->ty_name))
+                       break;
+       endttyent();
+       return (t);
+}
+
+struct ttyent *
+getttyent(void)
+{
+       static struct ttyent tty;
+       int c;
+       char *p;
+       size_t len;
+       static char *line = NULL;
+       char zapchar;
+
+       if (line)
+               free(line);
+
+       if (!tf && !setttyent())
+               return NULL;
+
+       for (;;) {
+               errno = 0;
+               line = fparseln(tf, &len, &lineno, NULL, FPARSELN_UNESCALL);
+               if (line == NULL) {
+                       if (errno != 0)
+                               warn(__func__);
+                       return NULL;
+               }
+               for (p = line; *p && isspace((unsigned char)*p); p++)
+                       continue;
+               if (*p && *p != '#')
+                       break;
+               free(line);
+       }
+
+       tty.ty_name = p;
+       p = skip(p, &zapchar);
+       if (*(tty.ty_getty = p) == '\0')
+               tty.ty_getty = tty.ty_type = NULL;
+       else {
+               p = skip(p, &zapchar);
+               if (*(tty.ty_type = p) == '\0')
+                       tty.ty_type = NULL;
+               else
+                       p = skip(p, &zapchar);
+       }
+       tty.ty_status = 0;
+       tty.ty_window = NULL;
+       tty.ty_class = NULL;
+
+#define        scmp(e) !strncmp(p, e, sizeof(e) - 1) && (isspace((unsigned char) p[sizeof(e) - 1]) || p[sizeof(e) - 1] == '\0')
+#define        vcmp(e) !strncmp(p, e, sizeof(e) - 1) && p[sizeof(e) - 1] == '='
+       for (; *p; p = skip(p, &zapchar)) {
+               if (scmp(_TTYS_OFF))
+                       tty.ty_status &= ~TTY_ON;
+               else if (scmp(_TTYS_ON))
+                       tty.ty_status |= TTY_ON;
+               else if (scmp(_TTYS_SECURE))
+                       tty.ty_status |= TTY_SECURE;
+               else if (scmp(_TTYS_LOCAL))
+                       tty.ty_status |= TTY_LOCAL;
+               else if (scmp(_TTYS_RTSCTS))
+                       tty.ty_status |= TTY_RTSCTS;
+               else if (scmp(_TTYS_DTRCTS))
+                       tty.ty_status |= TTY_DTRCTS;
+               else if (scmp(_TTYS_SOFTCAR))
+                       tty.ty_status |= TTY_SOFTCAR;
+               else if (scmp(_TTYS_MDMBUF))
+                       tty.ty_status |= TTY_MDMBUF;
+               else if (vcmp(_TTYS_WINDOW))
+                       tty.ty_window = value(p);
+               else if (vcmp(_TTYS_CLASS))
+                       tty.ty_class = value(p);
+               else
+                       warnx("%s: %s, %lu: unknown option `%s'",
+                           __func__, _PATH_TTYS, (unsigned long)lineno, p);
+       }
+
+       if (zapchar == '#' || *p == '#')
+               while ((c = *++p) == ' ' || c == '\t')
+                       continue;
+       tty.ty_comment = p;
+       if (*p == '\0')
+               tty.ty_comment = NULL;
+       if ((p = strchr(p, '\n')) != NULL)
+               *p = '\0';
+       return &tty;
+}
+
+#define        QUOTED  1
+
+/*
+ * Skip over the current field, removing quotes, and return a pointer to
+ * the next field.
+ */
+static char *
+skip(char *p, char *zapchar)
+{
+       char *t;
+       int c, q;
+
+       _DIAGASSERT(p != NULL);
+       *zapchar = '\0';
+
+       for (q = 0, t = p; (c = *p) != '\0'; p++) {
+               if (c == '"') {
+                       q ^= QUOTED;    /* obscure, but nice */
+                       continue;
+               }
+               if (q == QUOTED && *p == '\\' && *(p+1) == '"')
+                       p++;
+               *t++ = *p;
+               if (q == QUOTED)
+                       continue;
+               if (c == '#') {
+                       *zapchar = c;
+                       *p = '\0';
+                       *--t = '\0';
+                       return p;
+               }
+               if (c == '\t' || c == ' ' || c == '\n') {
+                       *zapchar = c;
+                       *p++ = '\0';
+                       while ((c = *p) == '\t' || c == ' ' || c == '\n')
+                               p++;
+                       *--t = '\0';
+                       return p;
+               }
+       }
+       if (t != p)
+               *t = '\0';
+       return p;
+}
+
+static char *
+value(char *p)
+{
+
+       _DIAGASSERT(p != NULL);
+
+       return (p = strchr(p, '=')) != NULL ? ++p : NULL;
+}
+
+int
+setttyentpath(const char *path)
+{
+       lineno = 0;
+       if (tf) {
+               rewind(tf);
+               return 1;
+       } else if ((tf = fopen(path, "r")) != NULL)
+               return 1;
+       return 0;
+}
+
+int
+setttyent(void)
+{
+       return setttyentpath(_PATH_TTYS);
+}
+
+int
+endttyent(void)
+{
+       int rval;
+
+       if (tf) {
+               rval = !(fclose(tf) == EOF);
+               tf = NULL;
+               return rval;
+       }
+       return 1;
+}
diff --git a/lib/nbsd_libc/gen/getusershell.3 b/lib/nbsd_libc/gen/getusershell.3
new file mode 100644 (file)
index 0000000..1b36738
--- /dev/null
@@ -0,0 +1,98 @@
+.\"    $NetBSD: getusershell.3,v 1.10 2004/11/23 04:38:19 lukem Exp $
+.\"
+.\" Copyright (c) 1985, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getusershell.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd November 23, 2004
+.Dt GETUSERSHELL 3
+.Os
+.Sh NAME
+.Nm getusershell ,
+.Nm setusershell ,
+.Nm endusershell
+.Nd get valid user shells
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft char *
+.Fn getusershell void
+.Ft void
+.Fn setusershell void
+.Ft void
+.Fn endusershell void
+.Sh DESCRIPTION
+The
+.Fn getusershell
+function
+returns a pointer to a valid user shell as defined by the
+system manager in the shells database as described in
+.Xr shells 5 .
+If the shells database is not available,
+.Fn getusershell
+behaves as if
+.Pa /bin/sh
+and
+.Pa /bin/csh
+were listed.
+.Pp
+The
+.Fn getusershell
+function
+reads the next
+line (opening the file if necessary);
+.Fn setusershell
+rewinds the file;
+.Fn endusershell
+closes it.
+.Sh FILES
+.Bl -tag -width /etc/shells -compact
+.It Pa /etc/shells
+.El
+.Sh DIAGNOSTICS
+The routine
+.Fn getusershell
+returns a null pointer (0) on
+.Dv EOF .
+.Sh SEE ALSO
+.Xr nsswitch.conf 5 ,
+.Xr shells 5
+.Sh HISTORY
+The
+.Fn getusershell
+function appeared in
+.Bx 4.3 .
+.Sh BUGS
+The
+.Fn getusershell
+function leaves its result in an internal static object and returns
+a pointer to that object.
+Subsequent calls to
+.Fn getusershell
+will modify the same object.
diff --git a/lib/nbsd_libc/gen/getusershell.c b/lib/nbsd_libc/gen/getusershell.c
new file mode 100644 (file)
index 0000000..a9c7c24
--- /dev/null
@@ -0,0 +1,546 @@
+/*     $NetBSD: getusershell.c,v 1.27 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999, 2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Luke Mewburn.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * Copyright (c) 1985, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getusershell.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getusershell.c,v 1.27 2008/04/28 20:22:59 martin Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+
+#include <sys/param.h>
+#include <sys/file.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <nsswitch.h>
+#include <paths.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef HESIOD
+#include <hesiod.h>
+#endif
+#ifdef YP
+#include <rpc/rpc.h>
+#include <rpcsvc/ypclnt.h>
+#include <rpcsvc/yp_prot.h>
+#endif
+
+#ifdef __weak_alias
+__weak_alias(endusershell,_endusershell)
+__weak_alias(getusershell,_getusershell)
+__weak_alias(setusershell,_setusershell)
+#endif
+
+/*
+ * Local shells should NOT be added here.
+ * They should be added in /etc/shells.
+ */
+static const char *const okshells[] = { _PATH_BSHELL, _PATH_CSHELL, NULL };
+
+#ifdef _REENTRANT
+static mutex_t __shellmutex = MUTEX_INITIALIZER;
+#endif
+
+static char              curshell[MAXPATHLEN + 2];
+
+static const char *const *curokshell = okshells;
+static int               shellsfound = 0;
+
+               /*
+                *      files methods
+                */
+
+       /* state shared between files methods */
+struct files_state {
+       FILE    *fp;
+};
+
+static struct files_state _files_state;
+
+
+static int
+_files_start(struct files_state *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       if (state->fp == NULL) {
+               state->fp = fopen(_PATH_SHELLS, "r");
+               if (state->fp == NULL)
+                       return NS_UNAVAIL;
+       } else {
+               rewind(state->fp);
+       }
+       return NS_SUCCESS;
+}
+
+static int
+_files_end(struct files_state *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       if (state->fp) {
+               (void) fclose(state->fp);
+               state->fp = NULL;
+       }
+       return NS_SUCCESS;
+}
+
+/*ARGSUSED*/
+static int
+_files_setusershell(void *nsrv, void *nscb, va_list ap)
+{
+
+       return _files_start(&_files_state);
+}
+
+/*ARGSUSED*/
+static int
+_files_endusershell(void *nsrv, void *nscb, va_list ap)
+{
+
+       return _files_end(&_files_state);
+}
+
+/*ARGSUSED*/
+static int
+_files_getusershell(void *nsrv, void *nscb, va_list ap)
+{
+       char    **retval = va_arg(ap, char **);
+
+       char    *sp, *cp;
+       int      rv;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+       if (_files_state.fp == NULL) {  /* only start if file not open yet */
+               rv = _files_start(&_files_state);
+               if (rv != NS_SUCCESS)
+                       return rv;
+       }
+
+       while (fgets(curshell, sizeof(curshell) - 1, _files_state.fp) != NULL) {
+               sp = cp = curshell;
+               while (*cp != '#' && *cp != '/' && *cp != '\0')
+                       cp++;
+               if (*cp == '#' || *cp == '\0')
+                       continue;
+               sp = cp;
+               while (!isspace((unsigned char) *cp) && *cp != '#'
+                   && *cp != '\0')
+                       cp++;
+               *cp++ = '\0';
+               *retval = sp;
+               return NS_SUCCESS;
+       }
+
+       return NS_NOTFOUND;
+}
+
+
+#ifdef HESIOD
+               /*
+                *      dns methods
+                */
+
+       /* state shared between dns methods */
+struct dns_state {
+       void    *context;               /* Hesiod context */
+       int      num;                   /* shell index, -1 if no more */
+};
+
+static struct dns_state                _dns_state;
+
+static int
+_dns_start(struct dns_state *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       state->num = 0;
+       if (state->context == NULL) {                   /* setup Hesiod */
+               if (hesiod_init(&state->context) == -1)
+                       return NS_UNAVAIL;
+       }
+
+       return NS_SUCCESS;
+}
+
+static int
+_dns_end(struct dns_state *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       state->num = 0;
+       if (state->context) {
+               hesiod_end(state->context);
+               state->context = NULL;
+       }
+       return NS_SUCCESS;
+}
+
+/*ARGSUSED*/
+static int
+_dns_setusershell(void *nsrv, void *nscb, va_list ap)
+{
+
+       return _dns_start(&_dns_state);
+}
+
+/*ARGSUSED*/
+static int
+_dns_endusershell(void *nsrv, void *nscb, va_list ap)
+{
+
+       return _dns_end(&_dns_state);
+}
+
+/*ARGSUSED*/
+static int
+_dns_getusershell(void *nsrv, void *nscb, va_list ap)
+{
+       char    **retval = va_arg(ap, char **);
+
+       char      shellname[] = "shells-NNNNNNNNNN";
+       char    **hp, *ep;
+       int       rv;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+
+       if (_dns_state.num == -1)                       /* exhausted search */
+               return NS_NOTFOUND;
+
+       if (_dns_state.context == NULL) {
+                       /* only start if Hesiod not setup */
+               rv = _dns_start(&_dns_state);
+               if (rv != NS_SUCCESS)
+                       return rv;
+       }
+
+       hp = NULL;
+       rv = NS_NOTFOUND;
+
+                                                       /* find shells-NNN */
+       snprintf(shellname, sizeof(shellname), "shells-%d", _dns_state.num);
+       _dns_state.num++;
+
+       hp = hesiod_resolve(_dns_state.context, shellname, "shells");
+       if (hp == NULL) {
+               if (errno == ENOENT)
+                       rv = NS_NOTFOUND;
+               else
+                       rv = NS_UNAVAIL;
+       } else {
+               if ((ep = strchr(hp[0], '\n')) != NULL)
+                       *ep = '\0';                     /* clear trailing \n */
+                                               /* only use first result */
+               strlcpy(curshell, hp[0], sizeof(curshell));
+               *retval = curshell;
+               rv = NS_SUCCESS;
+       }
+
+       if (hp)
+               hesiod_free_list(_dns_state.context, hp);
+       if (rv != NS_SUCCESS)
+               _dns_state.num = -1;            /* any failure halts search */
+       return rv;
+}
+
+#endif /* HESIOD */
+
+
+#ifdef YP
+               /*
+                *      nis methods
+                */
+       /* state shared between nis methods */
+struct nis_state {
+       char            *domain;        /* NIS domain */
+       int              done;          /* non-zero if search exhausted */
+       char            *current;       /* current first/next match */
+       int              currentlen;    /* length of _nis_current */
+};
+
+static struct nis_state                _nis_state;
+
+static int
+_nis_start(struct nis_state *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       state->done = 0;
+       if (state->current) {
+               free(state->current);
+               state->current = NULL;
+       }
+       if (state->domain == NULL) {                    /* setup NIS */
+               switch (yp_get_default_domain(&state->domain)) {
+               case 0:
+                       break;
+               case YPERR_RESRC:
+                       return NS_TRYAGAIN;
+               default:
+                       return NS_UNAVAIL;
+               }
+       }
+       return NS_SUCCESS;
+}
+
+static int
+_nis_end(struct nis_state *state)
+{
+
+       _DIAGASSERT(state != NULL);
+
+       if (state->domain)
+               state->domain = NULL;
+       state->done = 0;
+       if (state->current)
+               free(state->current);
+       state->current = NULL;
+       return NS_SUCCESS;
+}
+
+/*ARGSUSED*/
+static int
+_nis_setusershell(void *nsrv, void *nscb, va_list ap)
+{
+
+       return _nis_start(&_nis_state);
+}
+
+/*ARGSUSED*/
+static int
+_nis_endusershell(void *nsrv, void *nscb, va_list ap)
+{
+
+       return _nis_end(&_nis_state);
+}
+
+/*ARGSUSED*/
+static int
+_nis_getusershell(void *nsrv, void *nscb, va_list ap)
+{
+       char    **retval = va_arg(ap, char **);
+
+       char    *key, *data;
+       int     keylen, datalen, rv, nisr;
+
+       _DIAGASSERT(retval != NULL);
+
+       *retval = NULL;
+
+       if (_nis_state.done)                            /* exhausted search */
+               return NS_NOTFOUND;
+       if (_nis_state.domain == NULL) {
+                                       /* only start if NIS not setup */
+               rv = _nis_start(&_nis_state);
+               if (rv != NS_SUCCESS)
+                       return rv;
+       }
+
+       key = NULL;
+       data = NULL;
+       rv = NS_NOTFOUND;
+
+       if (_nis_state.current) {                       /* already searching */
+               nisr = yp_next(_nis_state.domain, "shells",
+                   _nis_state.current, _nis_state.currentlen,
+                   &key, &keylen, &data, &datalen);
+               free(_nis_state.current);
+               _nis_state.current = NULL;
+               switch (nisr) {
+               case 0:
+                       _nis_state.current = key;
+                       _nis_state.currentlen = keylen;
+                       key = NULL;
+                       break;
+               case YPERR_NOMORE:
+                       rv = NS_NOTFOUND;
+                       goto nisent_out;
+               default:
+                       rv = NS_UNAVAIL;
+                       goto nisent_out;
+               }
+       } else {                                        /* new search */
+               if (yp_first(_nis_state.domain, "shells",
+                   &_nis_state.current, &_nis_state.currentlen,
+                   &data, &datalen)) {
+                       rv = NS_UNAVAIL;
+                       goto nisent_out;
+               }
+       }
+
+       data[datalen] = '\0';                           /* clear trailing \n */
+       strlcpy(curshell, data, sizeof(curshell));
+       *retval = curshell;
+       rv = NS_SUCCESS;
+
+ nisent_out:
+       if (key)
+               free(key);
+       if (data)
+               free(data);
+       if (rv != NS_SUCCESS)                   /* any failure halts search */
+               _nis_state.done = 1;
+       return rv;
+}
+
+#endif /* YP */
+
+
+               /*
+                *      public functions
+                */
+
+void
+endusershell(void)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_endusershell, NULL)
+               NS_DNS_CB(_dns_endusershell, NULL)
+               NS_NIS_CB(_nis_endusershell, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&__shellmutex);
+
+       curokshell = okshells;          /* reset okshells fallback state */
+       shellsfound = 0;
+
+                                       /* force all endusershell() methods */
+       (void) nsdispatch(NULL, dtab, NSDB_SHELLS, "endusershell",
+           __nsdefaultfiles_forceall);
+       mutex_unlock(&__shellmutex);
+}
+
+__aconst char *
+getusershell(void)
+{
+       int              rv;
+       __aconst char   *retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getusershell, NULL)
+               NS_DNS_CB(_dns_getusershell, NULL)
+               NS_NIS_CB(_nis_getusershell, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&__shellmutex);
+
+       retval = NULL;
+       do {
+               rv = nsdispatch(NULL, dtab, NSDB_SHELLS, "getusershell",
+                   __nsdefaultsrc, &retval);
+                               /* loop until failure or non-blank result */
+       } while (rv == NS_SUCCESS && retval[0] == '\0');
+
+       if (rv == NS_SUCCESS) {
+               shellsfound++;
+       } else if (shellsfound == 0) {  /* no shells; fall back to okshells */
+               if (curokshell != NULL) {
+                       retval = __UNCONST(*curokshell);
+                       curokshell++;
+                       rv = NS_SUCCESS;
+               }
+       }
+
+       mutex_unlock(&__shellmutex);
+       return (rv == NS_SUCCESS) ? retval : NULL;
+}
+
+void
+setusershell(void)
+{
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_setusershell, NULL)
+               NS_DNS_CB(_dns_setusershell, NULL)
+               NS_NIS_CB(_nis_setusershell, NULL)
+               NS_NULL_CB
+       };
+
+       mutex_lock(&__shellmutex);
+
+       curokshell = okshells;          /* reset okshells fallback state */
+       shellsfound = 0;
+
+                                       /* force all setusershell() methods */
+       (void) nsdispatch(NULL, dtab, NSDB_SHELLS, "setusershell",
+           __nsdefaultfiles_forceall);
+       mutex_unlock(&__shellmutex);
+}
diff --git a/lib/nbsd_libc/gen/glob.3 b/lib/nbsd_libc/gen/glob.3
new file mode 100644 (file)
index 0000000..7d8e47a
--- /dev/null
@@ -0,0 +1,527 @@
+.\"    $NetBSD: glob.3,v 1.39 2010/11/30 21:03:07 jruoho Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 1993, 1994
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Guido van Rossum.
+.\" 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. 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.
+.\"
+.\"     @(#)glob.3     8.3 (Berkeley) 4/16/94
+.\"
+.Dd November 30, 2010
+.Dt GLOB 3
+.Os
+.Sh NAME
+.Nm glob ,
+.Nm globfree ,
+.Nm glob_pattern_p
+.Nd generate pathnames matching a pattern
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In glob.h
+.Ft int
+.Fn glob "const char * restrict pattern" "int flags" "const int (*errfunc)(const char *, int)" "glob_t * restrict pglob"
+.Ft void
+.Fn globfree "glob_t *pglob"
+.Ft int
+.Fn glob_pattern_p "const char *pattern" "int quote"
+.Sh DESCRIPTION
+The
+.Fn glob
+function
+is a pathname generator that implements the rules for file name pattern
+matching used by the shell.
+.Pp
+The include file
+.Pa glob.h
+defines the structure type
+.Fa glob_t ,
+which contains at least the following fields:
+.Bd -literal
+typedef struct {
+       size_t gl_pathc;        /* count of total paths so far */
+       size_t gl_matchc;       /* count of paths matching pattern */
+       size_t gl_offs;         /* reserved at beginning of gl_pathv */
+       int gl_flags;           /* returned flags */
+       char **gl_pathv;        /* list of paths matching pattern */
+} glob_t;
+.Ed
+.Pp
+The argument
+.Fa pattern
+is a pointer to a pathname pattern to be expanded.
+The
+.Fn glob
+argument
+matches all accessible pathnames against the pattern and creates
+a list of the pathnames that match.
+In order to have access to a pathname,
+.Fn glob
+requires search permission on every component of a path except the last
+and read permission on each directory of any filename component of
+.Fa pattern
+that contains any of the special characters
+.Ql * ,
+.Ql \&?
+or
+.Ql \&[ .
+.Pp
+The
+.Fn glob
+argument
+stores the number of matched pathnames into the
+.Fa gl_pathc
+field, and a pointer to a list of pointers to pathnames into the
+.Fa gl_pathv
+field.
+The first pointer after the last pathname is
+.Dv NULL .
+If the pattern does not match any pathnames, the returned number of
+matched paths is set to zero.
+.Pp
+It is the caller's responsibility to create the structure pointed to by
+.Fa pglob .
+The
+.Fn glob
+function allocates other space as needed, including the memory pointed
+to by
+.Fa gl_pathv .
+.Pp
+The argument
+.Fa flags
+is used to modify the behavior of
+.Fn glob .
+The value of
+.Fa flags
+is the bitwise inclusive
+.Tn OR
+of any of the following
+values defined in
+.Pa glob.h :
+.Bl -tag -width GLOB_ALTDIRFUNC
+.It Dv GLOB_APPEND
+Append pathnames generated to the ones from a previous call (or calls)
+to
+.Fn glob .
+The value of
+.Fa gl_pathc
+will be the total matches found by this call and the previous call(s).
+The pathnames are appended to, not merged with the pathnames returned by
+the previous call(s).
+Between calls, the caller must not change the setting of the
+.Dv GLOB_DOOFFS
+flag, nor change the value of
+.Fa gl_offs
+when
+.Dv GLOB_DOOFFS
+is set, nor (obviously) call
+.Fn globfree
+for
+.Fa pglob .
+.It Dv GLOB_DOOFFS
+Make use of the
+.Fa gl_offs
+field.
+If this flag is set,
+.Fa gl_offs
+is used to specify how many
+.Dv NULL
+pointers to prepend to the beginning
+of the
+.Fa gl_pathv
+field.
+In other words,
+.Fa gl_pathv
+will point to
+.Fa gl_offs
+.Dv NULL
+pointers,
+followed by
+.Fa gl_pathc
+pathname pointers, followed by a
+.Dv NULL
+pointer.
+.It Dv GLOB_ERR
+Causes
+.Fn glob
+to return when it encounters a directory that it cannot open or read.
+Ordinarily,
+.Fn glob
+continues to find matches.
+.It Dv GLOB_MARK
+Each pathname that is a directory that matches
+.Fa pattern
+has a slash
+appended.
+.It Dv GLOB_NOCHECK
+If
+.Fa pattern
+does not match any pathname, then
+.Fn glob
+returns a list
+consisting of only
+.Fa pattern ,
+with the number of total pathnames set to 1, and the number of matched
+pathnames set to 0.
+.It Dv GLOB_NOSORT
+By default, the pathnames are sorted in ascending
+.Tn ASCII
+order;
+this flag prevents that sorting (speeding up
+.Fn glob ) .
+.El
+.Pp
+The following values may also be included in
+.Fa flags ,
+however, they are non-standard extensions to
+.St -p1003.2 .
+.Bl -tag -width GLOB_ALTDIRFUNC
+.It Dv GLOB_ALTDIRFUNC
+The following additional fields in the pglob structure have been
+initialized with alternate functions for glob to use to open, read,
+and close directories and to get stat information on names found
+in those directories.
+.Bd -literal
+       void *(*gl_opendir)(const char * name);
+       struct dirent *(*gl_readdir)(void *);
+       void (*gl_closedir)(void *);
+       int (*gl_lstat)(const char *name, struct stat *st);
+       int (*gl_stat)(const char *name, struct stat *st);
+.Ed
+.Pp
+This extension is provided to allow programs such as
+.Xr restore 8
+to provide globbing from directories stored on tape.
+.It Dv GLOB_BRACE
+Pre-process the pattern string to expand
+.Ql {pat,pat,...}
+strings like
+.Xr csh 1 .
+The pattern
+.Ql {}
+is left unexpanded for historical reasons
+.Po
+.Xr csh 1
+does the same thing to ease typing of
+.Xr find 1
+patterns
+.Pc .
+.It Dv GLOB_MAGCHAR
+Set by the
+.Fn glob
+function if the pattern included globbing characters.
+See the description of the usage of the
+.Fa gl_matchc
+structure member for more details.
+.It Dv GLOB_NOMAGIC
+Is the same as
+.Dv GLOB_NOCHECK
+but it only appends the
+.Fa pattern
+if it does not contain any of the special characters ``*'', ``?'' or ``[''.
+.Dv GLOB_NOMAGIC
+is provided to simplify implementing the historic
+.Xr csh 1
+globbing behavior and should probably not be used anywhere else.
+.It Dv GLOB_NOESCAPE
+Disable the use of the backslash
+.Pq Ql \e
+character for quoting.
+.It Dv GLOB_TILDE
+Expand patterns that start with
+.Ql ~
+to user name home directories.
+.It Dv GLOB_LIMIT
+Limit the amount of memory used to store matched strings to
+.Li 64K ,
+the number of
+.Xr stat 2
+calls to 128, and the number of
+.Xr readdir 3
+calls to 16K.
+This option should be set for programs that can be coerced to a denial of
+service attack via patterns that expand to a very large number of matches,
+such as a long string of
+.Li */../*/..
+.It Dv GLOB_PERIOD
+Allow metacharacters to match a leading period in a filename.
+.It Dv GLOB_NO_DOTDIRS
+Hide
+.Sq Li \&.
+and
+.Sq Li \&..
+from metacharacter matches, regardless of whether
+.Dv GLOB_PERIOD
+is set and whether the pattern component begins with a literal period.
+.Dv GLOB_STAR
+Indicates that two adjacent
+.Li *
+characters will do a recursive match in all subdirs, without following
+symbolic links and three adjacent
+.Li *
+characters will also follow symbolic links.
+.El
+.Pp
+If, during the search, a directory is encountered that cannot be opened
+or read and
+.Fa errfunc
+is
+.Pf non- Dv NULL ,
+.Fn glob
+calls
+.Fa (*errfunc)(path, errno) .
+This may be unintuitive: a pattern like
+.Ql */Makefile
+will try to
+.Xr stat 2
+.Ql foo/Makefile
+even if
+.Ql foo
+is not a directory, resulting in a
+call to
+.Fa errfunc .
+The error routine can suppress this action by testing for
+.Dv ENOENT
+and
+.Dv ENOTDIR ;
+however, the
+.Dv GLOB_ERR
+flag will still cause an immediate
+return when this happens.
+.Pp
+If
+.Fa errfunc
+returns non-zero,
+.Fn glob
+stops the scan and returns
+.Dv GLOB_ABORTED
+after setting
+.Fa gl_pathc
+and
+.Fa gl_pathv
+to reflect any paths already matched.
+This also happens if an error is encountered and
+.Dv GLOB_ERR
+is set in
+.Fa flags ,
+regardless of the return value of
+.Fa errfunc ,
+if called.
+If
+.Dv GLOB_ERR
+is not set and either
+.Fa errfunc
+is
+.Dv NULL
+or
+.Fa errfunc
+returns zero, the error is ignored.
+.Pp
+The
+.Fn globfree
+function frees any space associated with
+.Fa pglob
+from a previous call(s) to
+.Fn glob .
+.Pp
+The
+.Fn glob_pattern_p
+returns
+.Dv 1
+if the
+.Fa pattern
+has any special characters that
+.Fn glob
+will interpret and
+.Dv 0
+otherwise.
+If the
+.Fa quote
+argument is non-zero, then backslash quoted characters are ignored.
+.Pp
+The historical
+.Dv GLOB_QUOTE
+flag is no longer supported.
+Per
+.St -p1003.2-92 ,
+backslash escaping of special characters is the default behaviour;
+it may be disabled by specifying the
+.Dv GLOB_NOESCAPE
+flag.
+.Sh RETURN VALUES
+On successful completion,
+.Fn glob
+returns zero.
+In addition the fields of
+.Fa pglob
+contain the values described below:
+.Bl -tag -width GLOB_NOCHECK
+.It Fa gl_pathc
+contains the total number of matched pathnames so far.
+This includes other matches from previous invocations of
+.Fn glob
+if
+.Dv GLOB_APPEND
+was specified.
+.It Fa gl_matchc
+contains the number of matched pathnames in the current invocation of
+.Fn glob .
+.It Fa gl_flags
+contains a copy of the
+.Fa flags
+parameter with the bit
+.Dv GLOB_MAGCHAR
+set if
+.Fa pattern
+contained any of the special characters ``*'', ``?'' or ``['', cleared
+if not.
+.It Fa gl_pathv
+contains a pointer to a
+.Dv NULL Ns -terminated
+list of matched pathnames.
+However, if
+.Fa gl_pathc
+is zero, the contents of
+.Fa gl_pathv
+are undefined.
+.El
+.Pp
+If
+.Fn glob
+terminates due to an error, it sets
+.Va errno
+and returns one of the following non-zero constants, which are defined
+in the include file
+.In glob.h :
+.Bl -tag -width GLOB_ABORTEDXXX
+.It Dv GLOB_ABORTED
+The scan was stopped because an error was encountered and either
+.Dv GLOB_ERR
+was set or
+.Fa (*errfunc)()
+returned non-zero.
+.It Dv GLOB_NOMATCH
+The pattern does not match any existing pathname, and
+.Dv GLOB_NOCHECK
+was not set in
+.Dv flags .
+.It Dv GLOB_NOSPACE
+An attempt to allocate memory failed, or if
+.Va errno
+was 0
+.Li GLOB_LIMIT
+was specified in the flags and
+.Li ARG_MAX
+patterns were matched.
+.El
+.Pp
+The historical
+.Dv GLOB_ABEND
+return constant is no longer supported.
+Portable applications should use the
+.Dv GLOB_ABORTED
+constant instead.
+.Pp
+The arguments
+.Fa pglob\-\*[Gt]gl_pathc
+and
+.Fa pglob\-\*[Gt]gl_pathv
+are still set as specified above.
+.Sh ENVIRONMENT
+.Bl -tag -width HOME -compact
+.It Ev HOME
+If defined, used as the home directory of the current user in
+tilde expansions.
+.El
+.Sh EXAMPLES
+A rough equivalent of
+.Ql "ls -l *.c *.h"
+can be obtained with the
+following code:
+.Bd -literal -offset indent
+glob_t g;
+
+g.gl_offs = 2;
+glob("*.c", GLOB_DOOFFS, NULL, \*[Am]g);
+glob("*.h", GLOB_DOOFFS | GLOB_APPEND, NULL, \*[Am]g);
+g.gl_pathv[0] = "ls";
+g.gl_pathv[1] = "-l";
+execvp("ls", g.gl_pathv);
+.Ed
+.Sh SEE ALSO
+.Xr sh 1 ,
+.Xr fnmatch 3 ,
+.Xr regexp 3 ,
+.Xr glob 7
+.Sh STANDARDS
+The
+.Fn glob
+function is expected to be
+.St -p1003.2
+compatible with the exception
+that the flags
+.Dv GLOB_ALTDIRFUNC ,
+.Dv GLOB_BRACE ,
+.Dv GLOB_MAGCHAR ,
+.Dv GLOB_NOMAGIC ,
+.Dv GLOB_TILDE ,
+and
+.Dv GLOB_LIMIT
+and the fields
+.Fa gl_matchc
+and
+.Fa gl_flags
+should not be used by applications striving for strict
+.Tn POSIX
+conformance.
+.Sh HISTORY
+The
+.Fn glob
+and
+.Fn globfree
+functions first appeared in
+.Bx 4.4 .
+The
+.Fn glob_pattern_p
+function is modelled after the one found in glibc.
+.Sh BUGS
+Patterns longer than
+.Dv MAXPATHLEN
+may cause unchecked errors.
+.Pp
+The
+.Fn glob
+function may fail and set
+.Va errno
+for any of the errors specified for the library routines
+.Xr stat 2 ,
+.Xr closedir 3 ,
+.Xr opendir 3 ,
+.Xr readdir 3 ,
+.Xr malloc 3 ,
+and
+.Xr free 3 .
diff --git a/lib/nbsd_libc/gen/glob.c b/lib/nbsd_libc/gen/glob.c
new file mode 100644 (file)
index 0000000..c1083f9
--- /dev/null
@@ -0,0 +1,1170 @@
+/*     $NetBSD: glob.c,v 1.28 2011/01/21 23:30:31 christos Exp $       */
+
+/*
+ * Copyright (c) 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Guido van Rossum.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)glob.c     8.3 (Berkeley) 10/13/93";
+#else
+__RCSID("$NetBSD: glob.c,v 1.28 2011/01/21 23:30:31 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * glob(3) -- a superset of the one defined in POSIX 1003.2.
+ *
+ * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
+ *
+ * Optional extra services, controlled by flags not defined by POSIX:
+ *
+ * GLOB_MAGCHAR:
+ *     Set in gl_flags if pattern contained a globbing character.
+ * GLOB_NOMAGIC:
+ *     Same as GLOB_NOCHECK, but it will only append pattern if it did
+ *     not contain any magic characters.  [Used in csh style globbing]
+ * GLOB_ALTDIRFUNC:
+ *     Use alternately specified directory access functions.
+ * GLOB_TILDE:
+ *     expand ~user/foo to the /home/dir/of/user/foo
+ * GLOB_BRACE:
+ *     expand {1,2}{a,b} to 1a 1b 2a 2b 
+ * GLOB_PERIOD:
+ *     allow metacharacters to match leading dots in filenames.
+ * GLOB_NO_DOTDIRS:
+ *     . and .. are hidden from wildcards, even if GLOB_PERIOD is set.
+ * gl_matchc:
+ *     Number of matches in the current invocation of glob.
+ */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <glob.h>
+#include <pwd.h>
+#include <stdio.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef HAVE_NBTOOL_CONFIG_H
+#define NO_GETPW_R
+#endif
+
+#define        GLOB_LIMIT_STRING       65536   /* number of readdirs */
+#define        GLOB_LIMIT_STAT         128     /* number of stat system calls */
+#define        GLOB_LIMIT_READDIR      16384   /* total buffer size of path strings */
+#define        GLOB_LIMIT_PATH         1024    /* number of path elements */
+#define GLOB_LIMIT_BRACE       128     /* Number of brace calls */
+
+struct glob_limit {
+       size_t l_string;
+       size_t l_stat;  
+       size_t l_readdir;       
+       size_t l_brace;
+};
+
+/*
+ * XXX: For NetBSD 1.4.x compatibility. (kill me l8r)
+ */
+#ifndef _DIAGASSERT
+#define _DIAGASSERT(a)
+#endif
+
+#define        DOLLAR          '$'
+#define        DOT             '.'
+#define        EOS             '\0'
+#define        LBRACKET        '['
+#define        NOT             '!'
+#define        QUESTION        '?'
+#define        QUOTE           '\\'
+#define        RANGE           '-'
+#define        RBRACKET        ']'
+#define        SEP             '/'
+#define        STAR            '*'
+#define        TILDE           '~'
+#define        UNDERSCORE      '_'
+#define        LBRACE          '{'
+#define        RBRACE          '}'
+#define        SLASH           '/'
+#define        COMMA           ','
+
+#ifndef USE_8BIT_CHARS
+
+#define        M_QUOTE         0x8000
+#define        M_PROTECT       0x4000
+#define        M_MASK          0xffff
+#define        M_ASCII         0x00ff
+
+typedef u_short Char;
+
+#else
+
+#define        M_QUOTE         (Char)0x80
+#define        M_PROTECT       (Char)0x40
+#define        M_MASK          (Char)0xff
+#define        M_ASCII         (Char)0x7f
+
+typedef char Char;
+
+#endif
+
+
+#define        CHAR(c)         ((Char)((c)&M_ASCII))
+#define        META(c)         ((Char)((c)|M_QUOTE))
+#define        M_ALL           META('*')
+#define        M_END           META(']')
+#define        M_NOT           META('!')
+#define        M_ONE           META('?')
+#define        M_RNG           META('-')
+#define        M_SET           META('[')
+#define        ismeta(c)       (((c)&M_QUOTE) != 0)
+
+
+static int      compare(const void *, const void *);
+static int      g_Ctoc(const Char *, char *, size_t);
+static int      g_lstat(Char *, __gl_stat_t  *, glob_t *);
+static DIR     *g_opendir(Char *, glob_t *);
+static Char    *g_strchr(const Char *, int);
+static int      g_stat(Char *, __gl_stat_t *, glob_t *);
+static int      glob0(const Char *, glob_t *, struct glob_limit *);
+static int      glob1(Char *, glob_t *, struct glob_limit *);
+static int      glob2(Char *, Char *, Char *, const Char *, glob_t *,
+    struct glob_limit *);
+static int      glob3(Char *, Char *, Char *, const Char *, const Char *,
+    const Char *, glob_t *, struct glob_limit *);
+static int      globextend(const Char *, glob_t *, struct glob_limit *);
+static const Char *globtilde(const Char *, Char *, size_t, glob_t *);
+static int      globexp1(const Char *, glob_t *, struct glob_limit *);
+static int      globexp2(const Char *, const Char *, glob_t *, int *,
+    struct glob_limit *);
+static int      match(const Char *, const Char *, const Char *);
+#ifdef DEBUG
+static void     qprintf(const char *, Char *);
+#endif
+
+int
+glob(const char *pattern, int flags, int (*errfunc)(const char *, int),
+    glob_t *pglob)
+{
+       const u_char *patnext;
+       int c;
+       Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
+       struct glob_limit limit = { 0, 0, 0, 0 };
+
+       _DIAGASSERT(pattern != NULL);
+
+       patnext = (const u_char *) pattern;
+       if (!(flags & GLOB_APPEND)) {
+               pglob->gl_pathc = 0;
+               pglob->gl_pathv = NULL;
+               if (!(flags & GLOB_DOOFFS))
+                       pglob->gl_offs = 0;
+       }
+       pglob->gl_flags = flags & ~GLOB_MAGCHAR;
+       pglob->gl_errfunc = errfunc;
+       pglob->gl_matchc = 0;
+
+       bufnext = patbuf;
+       bufend = bufnext + MAXPATHLEN;
+       if (flags & GLOB_NOESCAPE) {
+               while (bufnext < bufend && (c = *patnext++) != EOS) 
+                       *bufnext++ = c;
+       } else {
+               /* Protect the quoted characters. */
+               while (bufnext < bufend && (c = *patnext++) != EOS) 
+                       if (c == QUOTE) {
+                               if ((c = *patnext++) == EOS) {
+                                       c = QUOTE;
+                                       --patnext;
+                               }
+                               *bufnext++ = c | M_PROTECT;
+                       }
+                       else
+                               *bufnext++ = c;
+       }
+       *bufnext = EOS;
+
+       if (flags & GLOB_BRACE)
+           return globexp1(patbuf, pglob, &limit);
+       else
+           return glob0(patbuf, pglob, &limit);
+}
+
+/*
+ * Expand recursively a glob {} pattern. When there is no more expansion
+ * invoke the standard globbing routine to glob the rest of the magic
+ * characters
+ */
+static int
+globexp1(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
+{
+       const Char* ptr = pattern;
+       int rv;
+
+       _DIAGASSERT(pattern != NULL);
+       _DIAGASSERT(pglob != NULL);
+
+       if ((pglob->gl_flags & GLOB_LIMIT) &&
+           limit->l_brace++ >= GLOB_LIMIT_BRACE) {
+               errno = 0;
+               return GLOB_NOSPACE;
+       }
+
+       /* Protect a single {}, for find(1), like csh */
+       if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
+               return glob0(pattern, pglob, limit);
+
+       while ((ptr = (const Char *) g_strchr(ptr, LBRACE)) != NULL)
+               if (!globexp2(ptr, pattern, pglob, &rv, limit))
+                       return rv;
+
+       return glob0(pattern, pglob, limit);
+}
+
+
+/*
+ * Recursive brace globbing helper. Tries to expand a single brace.
+ * If it succeeds then it invokes globexp1 with the new pattern.
+ * If it fails then it tries to glob the rest of the pattern and returns.
+ */
+static int
+globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv,
+    struct glob_limit *limit)
+{
+       int     i;
+       Char   *lm, *ls;
+       const Char *pe, *pm, *pl;
+       Char    patbuf[MAXPATHLEN + 1];
+
+       _DIAGASSERT(ptr != NULL);
+       _DIAGASSERT(pattern != NULL);
+       _DIAGASSERT(pglob != NULL);
+       _DIAGASSERT(rv != NULL);
+
+       /* copy part up to the brace */
+       for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
+               continue;
+       ls = lm;
+
+       /* Find the balanced brace */
+       for (i = 0, pe = ++ptr; *pe; pe++)
+               if (*pe == LBRACKET) {
+                       /* Ignore everything between [] */
+                       for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
+                               continue;
+                       if (*pe == EOS) {
+                               /* 
+                                * We could not find a matching RBRACKET.
+                                * Ignore and just look for RBRACE
+                                */
+                               pe = pm;
+                       }
+               }
+               else if (*pe == LBRACE)
+                       i++;
+               else if (*pe == RBRACE) {
+                       if (i == 0)
+                               break;
+                       i--;
+               }
+
+       /* Non matching braces; just glob the pattern */
+       if (i != 0 || *pe == EOS) {
+               /*
+                * we use `pattern', not `patbuf' here so that that
+                * unbalanced braces are passed to the match
+                */
+               *rv = glob0(pattern, pglob, limit);
+               return 0;
+       }
+
+       for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
+               switch (*pm) {
+               case LBRACKET:
+                       /* Ignore everything between [] */
+                       for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
+                               continue;
+                       if (*pm == EOS) {
+                               /* 
+                                * We could not find a matching RBRACKET.
+                                * Ignore and just look for RBRACE
+                                */
+                               pm = pl;
+                       }
+                       break;
+
+               case LBRACE:
+                       i++;
+                       break;
+
+               case RBRACE:
+                       if (i) {
+                               i--;
+                               break;
+                       }
+                       /* FALLTHROUGH */
+               case COMMA:
+                       if (i && *pm == COMMA)
+                               break;
+                       else {
+                               /* Append the current string */
+                               for (lm = ls; (pl < pm); *lm++ = *pl++)
+                                       continue;
+                               /* 
+                                * Append the rest of the pattern after the
+                                * closing brace
+                                */
+                               for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
+                                       continue;
+
+                               /* Expand the current pattern */
+#ifdef DEBUG
+                               qprintf("globexp2", patbuf);
+#endif
+                               *rv = globexp1(patbuf, pglob, limit);
+
+                               /* move after the comma, to the next string */
+                               pl = pm + 1;
+                       }
+                       break;
+
+               default:
+                       break;
+               }
+       }
+       *rv = 0;
+       return 0;
+}
+
+
+
+/*
+ * expand tilde from the passwd file.
+ */
+static const Char *
+globtilde(const Char *pattern, Char *patbuf, size_t patsize, glob_t *pglob)
+{
+       struct passwd *pwd;
+       const char *h;
+       const Char *p;
+       Char *b;
+       char *d;
+       Char *pend = &patbuf[patsize / sizeof(Char)];
+#ifndef NO_GETPW_R
+       struct passwd pwres;
+       char pwbuf[1024];
+#endif
+
+       pend--;
+
+       _DIAGASSERT(pattern != NULL);
+       _DIAGASSERT(patbuf != NULL);
+       _DIAGASSERT(pglob != NULL);
+
+       if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
+               return pattern;
+
+       /* Copy up to the end of the string or / */
+       for (p = pattern + 1, d = (char *)(void *)patbuf; 
+            d < (char *)(void *)pend && *p && *p != SLASH; 
+            *d++ = *p++)
+               continue;
+
+       if (d == (char *)(void *)pend)
+               return NULL;
+
+       *d = EOS;
+       d = (char *)(void *)patbuf;
+
+       if (*d == EOS) {
+               /* 
+                * handle a plain ~ or ~/ by expanding $HOME 
+                * first and then trying the password file
+                */
+               if ((h = getenv("HOME")) == NULL) {
+#ifdef NO_GETPW_R
+                       if ((pwd = getpwuid(getuid())) == NULL)
+#else
+                       if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf),
+                           &pwd) != 0 || pwd == NULL)
+#endif
+                               return pattern;
+                       else
+                               h = pwd->pw_dir;
+               }
+       }
+       else {
+               /*
+                * Expand a ~user
+                */
+#ifdef NO_GETPW_R
+               if ((pwd = getpwnam(d)) == NULL)
+#else
+               if (getpwnam_r(d, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
+                   pwd == NULL)
+#endif
+                       return pattern;
+               else
+                       h = pwd->pw_dir;
+       }
+
+       /* Copy the home directory */
+       for (b = patbuf; b < pend && *h; *b++ = *h++)
+               continue;
+
+       if (b == pend)
+               return NULL;
+       
+       /* Append the rest of the pattern */
+       while (b < pend && (*b++ = *p++) != EOS)
+               continue;
+
+       if (b == pend)
+               return NULL;
+
+       return patbuf;
+}
+       
+
+/*
+ * The main glob() routine: compiles the pattern (optionally processing
+ * quotes), calls glob1() to do the real pattern matching, and finally
+ * sorts the list (unless unsorted operation is requested).  Returns 0
+ * if things went well, nonzero if errors occurred.  It is not an error
+ * to find no matches.
+ */
+static int
+glob0(const Char *pattern, glob_t *pglob, struct glob_limit *limit)
+{
+       const Char *qpatnext;
+       int c, error;
+       __gl_size_t oldpathc;
+       Char *bufnext, patbuf[MAXPATHLEN+1];
+
+       _DIAGASSERT(pattern != NULL);
+       _DIAGASSERT(pglob != NULL);
+
+       if ((qpatnext = globtilde(pattern, patbuf, sizeof(patbuf),
+           pglob)) == NULL)
+               return GLOB_ABEND;
+       oldpathc = pglob->gl_pathc;
+       bufnext = patbuf;
+
+       /* We don't need to check for buffer overflow any more. */
+       while ((c = *qpatnext++) != EOS) {
+               switch (c) {
+               case LBRACKET:
+                       c = *qpatnext;
+                       if (c == NOT)
+                               ++qpatnext;
+                       if (*qpatnext == EOS ||
+                           g_strchr(qpatnext+1, RBRACKET) == NULL) {
+                               *bufnext++ = LBRACKET;
+                               if (c == NOT)
+                                       --qpatnext;
+                               break;
+                       }
+                       *bufnext++ = M_SET;
+                       if (c == NOT)
+                               *bufnext++ = M_NOT;
+                       c = *qpatnext++;
+                       do {
+                               *bufnext++ = CHAR(c);
+                               if (*qpatnext == RANGE &&
+                                   (c = qpatnext[1]) != RBRACKET) {
+                                       *bufnext++ = M_RNG;
+                                       *bufnext++ = CHAR(c);
+                                       qpatnext += 2;
+                               }
+                       } while ((c = *qpatnext++) != RBRACKET);
+                       pglob->gl_flags |= GLOB_MAGCHAR;
+                       *bufnext++ = M_END;
+                       break;
+               case QUESTION:
+                       pglob->gl_flags |= GLOB_MAGCHAR;
+                       *bufnext++ = M_ONE;
+                       break;
+               case STAR:
+                       pglob->gl_flags |= GLOB_MAGCHAR;
+                       /* collapse adjacent stars to one [or three if globstar]
+                        * to avoid exponential behavior
+                        */
+                       if (bufnext == patbuf || bufnext[-1] != M_ALL ||
+                           ((pglob->gl_flags & GLOB_STAR) != 0 && 
+                           (bufnext - 1 == patbuf || bufnext[-2] != M_ALL ||
+                           bufnext - 2 == patbuf || bufnext[-3] != M_ALL)))
+                               *bufnext++ = M_ALL;
+                       break;
+               default:
+                       *bufnext++ = CHAR(c);
+                       break;
+               }
+       }
+       *bufnext = EOS;
+#ifdef DEBUG
+       qprintf("glob0", patbuf);
+#endif
+
+       if ((error = glob1(patbuf, pglob, limit)) != 0)
+               return error;
+
+       if (pglob->gl_pathc == oldpathc) {      
+               /*
+                * If there was no match we are going to append the pattern 
+                * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was
+                * specified and the pattern did not contain any magic
+                * characters GLOB_NOMAGIC is there just for compatibility
+                * with csh.
+                */
+               if ((pglob->gl_flags & GLOB_NOCHECK) ||
+                   ((pglob->gl_flags & (GLOB_NOMAGIC|GLOB_MAGCHAR))
+                    == GLOB_NOMAGIC)) {
+                       return globextend(pattern, pglob, limit);
+               } else {
+                       return GLOB_NOMATCH;
+               }
+       } else if (!(pglob->gl_flags & GLOB_NOSORT)) {
+               qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
+                   (size_t)pglob->gl_pathc - oldpathc, sizeof(char *),
+                   compare);
+       }
+
+       return 0;
+}
+
+static int
+compare(const void *p, const void *q)
+{
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(q != NULL);
+
+       return strcoll(*(const char * const *)p, *(const char * const *)q);
+}
+
+static int
+glob1(Char *pattern, glob_t *pglob, struct glob_limit *limit)
+{
+       Char pathbuf[MAXPATHLEN+1];
+
+       _DIAGASSERT(pattern != NULL);
+       _DIAGASSERT(pglob != NULL);
+
+       /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
+       if (*pattern == EOS)
+               return 0;
+       /*
+        * we save one character so that we can use ptr >= limit,
+        * in the general case when we are appending non nul chars only.
+        */
+       return glob2(pathbuf, pathbuf,
+           pathbuf + (sizeof(pathbuf) / sizeof(*pathbuf)) - 1, pattern,
+           pglob, limit);
+}
+
+/*
+ * The functions glob2 and glob3 are mutually recursive; there is one level
+ * of recursion for each segment in the pattern that contains one or more
+ * meta characters.
+ */
+static int
+glob2(Char *pathbuf, Char *pathend, Char *pathlim, const Char *pattern,
+    glob_t *pglob, struct glob_limit *limit)
+{
+       __gl_stat_t sb;
+       const Char *p;
+       Char *q;
+       int anymeta;
+       Char *pend;
+       ptrdiff_t diff;
+
+       _DIAGASSERT(pathbuf != NULL);
+       _DIAGASSERT(pathend != NULL);
+       _DIAGASSERT(pattern != NULL);
+       _DIAGASSERT(pglob != NULL);
+
+#ifdef DEBUG
+       qprintf("glob2", pathbuf);
+#endif
+       /*
+        * Loop over pattern segments until end of pattern or until
+        * segment with meta character found.
+        */
+       for (anymeta = 0;;) {
+               if (*pattern == EOS) {          /* End of pattern? */
+                       *pathend = EOS;
+                       if (g_lstat(pathbuf, &sb, pglob))
+                               return 0;
+               
+                       if ((pglob->gl_flags & GLOB_LIMIT) &&
+                           limit->l_stat++ >= GLOB_LIMIT_STAT) {
+                               errno = 0;
+                               *pathend++ = SEP;
+                               *pathend = EOS;
+printf("stat limit\n");
+                               return GLOB_NOSPACE;
+                       }
+                       if (((pglob->gl_flags & GLOB_MARK) &&
+                           pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) ||
+                           (S_ISLNK(sb.st_mode) &&
+                           (g_stat(pathbuf, &sb, pglob) == 0) &&
+                           S_ISDIR(sb.st_mode)))) {
+                               if (pathend >= pathlim)
+                                       return GLOB_ABORTED;
+                               *pathend++ = SEP;
+                               *pathend = EOS;
+                       }
+                       ++pglob->gl_matchc;
+                       return globextend(pathbuf, pglob, limit);
+               }
+
+               /* Find end of next segment, copy tentatively to pathend. */
+               q = pathend;
+               p = pattern;
+               while (*p != EOS && *p != SEP) {
+                       if (ismeta(*p))
+                               anymeta = 1;
+                       if (q >= pathlim)
+                               return GLOB_ABORTED;
+                       *q++ = *p++;
+               }
+
+                /*
+                * No expansion, or path ends in slash-dot shash-dot-dot,
+                * do next segment.
+                */
+               if (pglob->gl_flags & GLOB_PERIOD) {
+                       for (pend = pathend; pend > pathbuf && pend[-1] == '/';
+                           pend--)
+                               continue;
+                       diff = pend - pathbuf;
+               } else {
+                       /* XXX: GCC */
+                       diff = 0;
+                       pend = pathend;
+               }
+                       
+                if ((!anymeta) ||
+                   ((pglob->gl_flags & GLOB_PERIOD) &&
+                    (diff >= 1 && pend[-1] == DOT) &&
+                    (diff >= 2 && (pend[-2] == SLASH || pend[-2] == DOT)) &&
+                    (diff < 3 || pend[-3] == SLASH))) {
+                       pathend = q;
+                       pattern = p;
+                       while (*pattern == SEP) {
+                               if (pathend >= pathlim)
+                                       return GLOB_ABORTED;
+                               *pathend++ = *pattern++;
+                       }
+               } else                  /* Need expansion, recurse. */
+                       return glob3(pathbuf, pathend, pathlim, pattern, p,
+                           pattern, pglob, limit);
+       }
+       /* NOTREACHED */
+}
+
+static int
+glob3(Char *pathbuf, Char *pathend, Char *pathlim, const Char *pattern,
+    const Char *restpattern, const Char *pglobstar, glob_t *pglob,
+    struct glob_limit *limit)
+{
+       struct dirent *dp;
+       DIR *dirp;
+       __gl_stat_t sbuf;
+       int error;
+       char buf[MAXPATHLEN];
+       int globstar = 0;
+       int chase_symlinks = 0;
+       const Char *termstar = NULL;
+
+       /*
+        * The readdirfunc declaration can't be prototyped, because it is
+        * assigned, below, to two functions which are prototyped in glob.h
+        * and dirent.h as taking pointers to differently typed opaque
+        * structures.
+        */
+       struct dirent *(*readdirfunc)(void *);
+
+       _DIAGASSERT(pathbuf != NULL);
+       _DIAGASSERT(pathend != NULL);
+       _DIAGASSERT(pattern != NULL);
+       _DIAGASSERT(restpattern != NULL);
+       _DIAGASSERT(pglob != NULL);
+
+       *pathend = EOS;
+       errno = 0;
+           
+       while (pglobstar < restpattern) {
+               if ((pglobstar[0] & M_MASK) == M_ALL &&
+                   (pglobstar[1] & M_MASK) == M_ALL) {
+                       globstar = 1;
+                       chase_symlinks = (pglobstar[2] & M_MASK) == M_ALL;
+                       termstar = pglobstar + (2 + chase_symlinks);
+                       break;
+               }
+               pglobstar++;
+       } 
+
+       if (globstar) {
+               error = pglobstar == pattern && termstar == restpattern ?
+                   *restpattern == EOS ?
+                   glob2(pathbuf, pathend, pathlim, restpattern - 1, pglob,
+                   limit) :
+                   glob2(pathbuf, pathend, pathlim, restpattern + 1, pglob,
+                   limit) :
+                   glob3(pathbuf, pathend, pathlim, pattern, restpattern,
+                   termstar, pglob, limit);
+               if (error)
+                       return error;
+               *pathend = EOS;
+       }
+
+       if (*pathbuf && (g_lstat(pathbuf, &sbuf, pglob) ||
+           !S_ISDIR(sbuf.st_mode)
+#ifdef S_IFLINK
+            && ((globstar && !chase_symlinks) || !S_ISLNK(sbuf.st_mode))
+#endif
+           ))
+               return 0;
+
+       if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
+               if (pglob->gl_errfunc) {
+                       if (g_Ctoc(pathbuf, buf, sizeof(buf)))
+                               return GLOB_ABORTED;
+                       if (pglob->gl_errfunc(buf, errno) ||
+                           pglob->gl_flags & GLOB_ERR)
+                               return GLOB_ABORTED;
+               }
+               /*
+                * Posix/XOpen: glob should return when it encounters a
+                * directory that it cannot open or read
+                * XXX: Should we ignore ENOTDIR and ENOENT though?
+                * I think that Posix had in mind EPERM...
+                */
+               if (pglob->gl_flags & GLOB_ERR)
+                       return GLOB_ABORTED;
+
+               return 0;
+       }
+
+       error = 0;
+
+       /* Search directory for matching names. */
+       if (pglob->gl_flags & GLOB_ALTDIRFUNC)
+               readdirfunc = pglob->gl_readdir;
+       else
+               readdirfunc = (struct dirent *(*)__P((void *))) readdir;
+       while ((dp = (*readdirfunc)(dirp)) != NULL) {
+               u_char *sc;
+               Char *dc;
+
+               if ((pglob->gl_flags & GLOB_LIMIT) &&
+                   limit->l_readdir++ >= GLOB_LIMIT_READDIR) {
+                       errno = 0;
+                       *pathend++ = SEP;
+                       *pathend = EOS;
+                       return GLOB_NOSPACE;
+               }
+
+               /*
+                * Initial DOT must be matched literally, unless we have
+                * GLOB_PERIOD set.
+                */
+               if ((pglob->gl_flags & GLOB_PERIOD) == 0)
+                       if (dp->d_name[0] == DOT && *pattern != DOT)
+                               continue;
+               /*
+                * If GLOB_NO_DOTDIRS is set, . and .. vanish.
+                */
+               if ((pglob->gl_flags & GLOB_NO_DOTDIRS) &&
+                   (dp->d_name[0] == DOT) &&
+                   ((dp->d_name[1] == EOS) ||
+                    ((dp->d_name[1] == DOT) && (dp->d_name[2] == EOS))))
+                       continue;
+               /*
+                * The resulting string contains EOS, so we can
+                * use the pathlim character, if it is the nul
+                */
+               for (sc = (u_char *) dp->d_name, dc = pathend; 
+                    dc <= pathlim && (*dc++ = *sc++) != EOS;)
+                       continue;
+
+               /*
+                * Have we filled the buffer without seeing EOS?
+                */
+               if (dc > pathlim && *pathlim != EOS) {
+                       /*
+                        * Abort when requested by caller, otherwise
+                        * reset pathend back to last SEP and continue
+                        * with next dir entry.
+                        */
+                       if (pglob->gl_flags & GLOB_ERR) {
+                               error = GLOB_ABORTED;
+                               break;
+                       }
+                       else {
+                               *pathend = EOS;
+                               continue;
+                       }
+               }
+
+               if (globstar) {
+#ifdef S_IFLNK
+                       if (!chase_symlinks &&
+                           (g_lstat(pathbuf, &sbuf, pglob) ||
+                           S_ISLNK(sbuf.st_mode)))
+                               continue;
+#endif
+
+                       if (!match(pathend, pattern, termstar))
+                               continue;
+           
+                       if (--dc < pathlim - 2)
+                               *dc++ = SEP;
+                       *dc = EOS;
+                       error = glob2(pathbuf, dc, pathlim, pglobstar,
+                           pglob, limit);
+                       if (error)
+                               break;
+                       *pathend = EOS;
+               } else {
+                       if (!match(pathend, pattern, restpattern)) {
+                               *pathend = EOS;
+                               continue;
+                       }
+                       error = glob2(pathbuf, --dc, pathlim, restpattern,
+                           pglob, limit);
+                       if (error)
+                               break;
+               }
+       }
+       if (pglob->gl_flags & GLOB_ALTDIRFUNC)
+               (*pglob->gl_closedir)(dirp);
+       else
+               closedir(dirp);
+
+       /*
+        * Again Posix X/Open issue with regards to error handling.
+        */
+       if ((error || errno) && (pglob->gl_flags & GLOB_ERR))
+               return GLOB_ABORTED;
+
+       return error;
+}
+
+
+/*
+ * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
+ * add the new item, and update gl_pathc.
+ *
+ * This assumes the BSD realloc, which only copies the block when its size
+ * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
+ * behavior.
+ *
+ * Return 0 if new item added, error code if memory couldn't be allocated.
+ *
+ * Invariant of the glob_t structure:
+ *     Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
+ *     gl_pathv points to (gl_offs + gl_pathc + 1) items.
+ */
+static int
+globextend(const Char *path, glob_t *pglob, struct glob_limit *limit)
+{
+       char **pathv;
+       size_t i, newsize, len;
+       char *copy;
+       const Char *p;
+
+       _DIAGASSERT(path != NULL);
+       _DIAGASSERT(pglob != NULL);
+
+       newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
+       if ((pglob->gl_flags & GLOB_LIMIT) &&
+           newsize > GLOB_LIMIT_PATH * sizeof(*pathv))
+               goto nospace;
+       pathv = pglob->gl_pathv ? realloc(pglob->gl_pathv, newsize) :
+           malloc(newsize);
+       if (pathv == NULL)
+               return GLOB_NOSPACE;
+
+       if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
+               /* first time around -- clear initial gl_offs items */
+               pathv += pglob->gl_offs;
+               for (i = pglob->gl_offs + 1; --i > 0; )
+                       *--pathv = NULL;
+       }
+       pglob->gl_pathv = pathv;
+
+       for (p = path; *p++;)
+               continue;
+       len = (size_t)(p - path);
+       limit->l_string += len;
+       if ((copy = malloc(len)) != NULL) {
+               if (g_Ctoc(path, copy, len)) {
+                       free(copy);
+                       return GLOB_ABORTED;
+               }
+               pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
+       }
+       pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
+
+       if ((pglob->gl_flags & GLOB_LIMIT) &&
+           (newsize + limit->l_string) >= GLOB_LIMIT_STRING)
+               goto nospace;
+
+       return copy == NULL ? GLOB_NOSPACE : 0;
+nospace:
+       errno = 0;
+       return GLOB_NOSPACE;
+}
+
+
+/*
+ * pattern matching function for filenames.  Each occurrence of the *
+ * pattern causes a recursion level.
+ */
+static int
+match(const Char *name, const Char *pat, const Char *patend)
+{
+       int ok, negate_range;
+       Char c, k;
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(pat != NULL);
+       _DIAGASSERT(patend != NULL);
+
+       while (pat < patend) {
+               c = *pat++;
+               switch (c & M_MASK) {
+               case M_ALL:
+                       while (pat < patend && (*pat & M_MASK) == M_ALL)
+                               pat++;  /* eat consecutive '*' */
+                       if (pat == patend)
+                               return 1;
+                       for (; !match(name, pat, patend); name++)
+                               if (*name == EOS)
+                                       return 0;
+                       return 1;
+               case M_ONE:
+                       if (*name++ == EOS)
+                               return 0;
+                       break;
+               case M_SET:
+                       ok = 0;
+                       if ((k = *name++) == EOS)
+                               return 0;
+                       if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
+                               ++pat;
+                       while (((c = *pat++) & M_MASK) != M_END)
+                               if ((*pat & M_MASK) == M_RNG) {
+                                       if (c <= k && k <= pat[1])
+                                               ok = 1;
+                                       pat += 2;
+                               } else if (c == k)
+                                       ok = 1;
+                       if (ok == negate_range)
+                               return 0;
+                       break;
+               default:
+                       if (*name++ != c)
+                               return 0;
+                       break;
+               }
+       }
+       return *name == EOS;
+}
+
+/* Free allocated data belonging to a glob_t structure. */
+void
+globfree(glob_t *pglob)
+{
+       size_t i;
+       char **pp;
+
+       _DIAGASSERT(pglob != NULL);
+
+       if (pglob->gl_pathv != NULL) {
+               pp = pglob->gl_pathv + pglob->gl_offs;
+               for (i = pglob->gl_pathc; i--; ++pp)
+                       if (*pp)
+                               free(*pp);
+               free(pglob->gl_pathv);
+               pglob->gl_pathv = NULL;
+               pglob->gl_pathc = 0;
+       }
+}
+
+#ifndef __LIBC12_SOURCE__
+int
+glob_pattern_p(const char *pattern, int quote)
+{
+       int range = 0;
+
+       for (; *pattern; pattern++)
+               switch (*pattern) {
+               case QUESTION:
+               case STAR:
+                       return 1;
+
+               case QUOTE:
+                       if (quote && pattern[1] != EOS)
+                             ++pattern;
+                       break;
+
+               case LBRACKET:
+                       range = 1;
+                       break;
+
+               case RBRACKET:
+                       if (range)
+                             return 1;
+                       break;
+               default:
+                       break;
+               }
+
+         return 0;
+}
+#endif
+
+static DIR *
+g_opendir(Char *str, glob_t *pglob)
+{
+       char buf[MAXPATHLEN];
+
+       _DIAGASSERT(str != NULL);
+       _DIAGASSERT(pglob != NULL);
+
+       if (!*str)
+               (void)strlcpy(buf, ".", sizeof(buf));
+       else {
+               if (g_Ctoc(str, buf, sizeof(buf)))
+                       return NULL;
+       }
+
+       if (pglob->gl_flags & GLOB_ALTDIRFUNC)
+               return (*pglob->gl_opendir)(buf);
+
+       return opendir(buf);
+}
+
+static int
+g_lstat(Char *fn, __gl_stat_t *sb, glob_t *pglob)
+{
+       char buf[MAXPATHLEN];
+
+       _DIAGASSERT(fn != NULL);
+       _DIAGASSERT(sb != NULL);
+       _DIAGASSERT(pglob != NULL);
+
+       if (g_Ctoc(fn, buf, sizeof(buf)))
+               return -1;
+       if (pglob->gl_flags & GLOB_ALTDIRFUNC)
+               return (*pglob->gl_lstat)(buf, sb);
+       return lstat(buf, sb);
+}
+
+static int
+g_stat(Char *fn, __gl_stat_t *sb, glob_t *pglob)
+{
+       char buf[MAXPATHLEN];
+
+       _DIAGASSERT(fn != NULL);
+       _DIAGASSERT(sb != NULL);
+       _DIAGASSERT(pglob != NULL);
+
+       if (g_Ctoc(fn, buf, sizeof(buf)))
+               return -1;
+       if (pglob->gl_flags & GLOB_ALTDIRFUNC)
+               return (*pglob->gl_stat)(buf, sb);
+       return stat(buf, sb);
+}
+
+static Char *
+g_strchr(const Char *str, int ch)
+{
+
+       _DIAGASSERT(str != NULL);
+
+       do {
+               if (*str == ch)
+                       return __UNCONST(str);
+       } while (*str++);
+       return NULL;
+}
+
+static int
+g_Ctoc(const Char *str, char *buf, size_t len)
+{
+       char *dc;
+
+       _DIAGASSERT(str != NULL);
+       _DIAGASSERT(buf != NULL);
+
+       if (len == 0)
+               return 1;
+
+       for (dc = buf; len && (*dc++ = *str++) != EOS; len--)
+               continue;
+
+       return len == 0;
+}
+
+#ifdef DEBUG
+static void 
+qprintf(const char *str, Char *s)
+{
+       Char *p;
+
+       _DIAGASSERT(str != NULL);
+       _DIAGASSERT(s != NULL);
+
+       (void)printf("%s:\n", str);
+       for (p = s; *p; p++)
+               (void)printf("%c", CHAR(*p));
+       (void)printf("\n");
+       for (p = s; *p; p++)
+               (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
+       (void)printf("\n");
+       for (p = s; *p; p++)
+               (void)printf("%c", ismeta(*p) ? '_' : ' ');
+       (void)printf("\n");
+}
+#endif
diff --git a/lib/nbsd_libc/gen/gr_private.h b/lib/nbsd_libc/gen/gr_private.h
new file mode 100644 (file)
index 0000000..560ab92
--- /dev/null
@@ -0,0 +1,112 @@
+/*     $NetBSD: gr_private.h,v 1.2 2008/04/28 20:22:59 martin Exp $    */
+
+/*-
+ * Copyright (c) 2004-2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Luke Mewburn.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * Structures and functions used by various group(5) public functions
+ * and their back-end implementations.
+ * These are subject to change without notice and should not be used
+ * outside of libc (even by third-party nss_*.so modules implementing
+ * group(5) back-ends).
+ */
+
+#define _GROUP_COMPAT  /* "group" defaults to compat, so always provide it */
+
+
+       /*
+        * mutex to serialize the public group(5) functions use of the
+        * back-end implementations, which may not be reentrant.
+        */
+extern         mutex_t         __grmutex;
+
+       /*
+        * files methods
+        */
+struct __grstate_files {       /* state shared between files methods */
+       int      stayopen;      /* see getgroupent(3) */
+       FILE    *fp;            /* groups file handle */
+};
+
+extern int     __grstart_files(struct __grstate_files *);
+extern int     __grend_files(struct __grstate_files *);
+extern int     __grscan_files(int *, struct group *, char *, size_t,
+                       struct __grstate_files *, int, const char *, gid_t);
+
+       /*
+        * dns methods
+        */
+struct __grstate_dns {         /* state shared between dns methods */
+       int      stayopen;      /* see getgroupent(3) */
+       void    *context;       /* Hesiod context */
+       int      num;           /* group index, -1 if no more */
+};
+
+extern int     __grstart_dns(struct __grstate_dns *);
+extern int     __grend_dns(struct __grstate_dns *state);
+extern int     __grscan_dns(int *, struct group *, char *, size_t,
+                       struct __grstate_dns *, int, const char *, gid_t);
+
+       /*
+        * nis methods
+        */
+struct __grstate_nis {         /* state shared between nis methods */
+       int      stayopen;      /* see getgroupent(3) */
+       char    *domain;        /* NIS domain */
+       int      done;          /* non-zero if search exhausted */
+       char    *current;       /* current first/next match */
+       int      currentlen;    /* length of _nis_current */
+};
+
+extern int     __grstart_nis(struct __grstate_nis *);
+extern int     __grend_nis(struct __grstate_nis *);
+extern int     __grscan_nis(int *, struct group *, char *, size_t,
+                       struct __grstate_nis *, int, const char *, gid_t);
+
+       /*
+        * compat methods
+        */
+struct __grstate_compat {      /* state shared between compat methods */
+       int      stayopen;      /* see getgroupent(3) */
+       FILE    *fp;            /* file handle */
+/*
+ * XXX:        convert name to a separate compatstate enum and grow name as necessary
+ *     instead of using strdup & free for each + line
+ */
+       char    *name;          /* NULL if reading file,        */
+                               /*   "" if compat "+",          */
+                               /* name if compat "+name"       */
+};
+
+extern int     __grbad_compat(void *nsrv, void *nscb, va_list ap);
+extern int     __grstart_compat(struct __grstate_compat *);
+extern int     __grend_compat(struct __grstate_compat *);
+extern int     __grscan_compat(int *, struct group *, char *, size_t,
+                       struct __grstate_compat *, int, const char *, gid_t,
+                       int (*)(void *, struct group **), void *);
diff --git a/lib/nbsd_libc/gen/humanize_number.3 b/lib/nbsd_libc/gen/humanize_number.3
new file mode 100644 (file)
index 0000000..0179636
--- /dev/null
@@ -0,0 +1,168 @@
+.\"    $NetBSD: humanize_number.3,v 1.9 2011/01/14 10:08:57 jruoho Exp $
+.\"
+.\" Copyright (c) 1999, 2002, 2008 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Luke Mewburn and by Tomas Svensson.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 14, 2011
+.Dt HUMANIZE_NUMBER 3
+.Os
+.Sh NAME
+.Nm dehumanize_number ,
+.Nm humanize_number
+.Nd format a number into a human readable form and viceversa
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn dehumanize_number "const char *str" "int64_t *result"
+.Ft int
+.Fn humanize_number "char *buf" "size_t len" "int64_t number" "const char *suffix" "int scale" "int flags"
+.Sh DESCRIPTION
+The
+.Fn humanize_number
+function formats the signed 64 bit quantity given in
+.Fa number
+into
+.Fa buffer .
+A space and then
+.Fa suffix
+is appended to the end.
+.Fa buffer
+must be at least
+.Fa len
+bytes long.
+.Pp
+If the formatted number (including
+.Fa suffix )
+would be too long to fit into
+.Fa buffer ,
+then divide
+.Fa number
+by 1024 until it will.
+In this case, prefix
+.Fa suffix
+with the appropriate SI designator.
+.Pp
+The prefixes are:
+.Bl -column "Prefix" "Description" "Multiplier" -offset indent
+.It Sy "Prefix" Ta Sy "Description" Ta Sy "Multiplier"
+.It k  kilo    1024
+.It M  mega    1048576
+.It G  giga    1073741824
+.It T  tera    1099511627776
+.It P  peta    1125899906842624
+.It E  exa     1152921504606846976
+.El
+.Pp
+.Fa len
+must be at least 4 plus the length of
+.Fa suffix ,
+in order to ensure a useful result is generated into
+.Fa buffer .
+To use a specific prefix, specify this as
+.Fa scale
+(Multiplier = 1024 ^ scale).
+This can not be combined with any of the
+.Fa scale
+flags below.
+.Pp
+The following flags may be passed in
+.Pa scale :
+.Bl -tag -width Dv -offset indent
+.It Dv HN_AUTOSCALE
+Format the buffer using the lowest multiplier possible.
+.It Dv HN_GETSCALE
+Return the prefix index number (the number of times
+.Fa number
+must be divided to fit) instead of formatting it to the buffer.
+.El
+.Pp
+The following flags may be passed in
+.Pa flags :
+.Bl -tag -width Dv -offset indent
+.It Dv HN_DECIMAL
+If the final result is less than 10, display it using one digit.
+.It Dv HN_NOSPACE
+Do not put a space between
+.Fa number
+and the prefix.
+.It Dv HN_B
+Use 'B' (bytes) as prefix if the original result does not have a prefix.
+.It Dv HN_DIVISOR_1000
+Divide
+.Fa number
+with 1000 instead of 1024.
+.El
+.Pp
+The
+.Fn dehumanize_number
+function parses the string representing an integral value given in
+.Fa str
+and stores the numerical value in the integer pointed to by
+.Fa result .
+The provided string may hold one of the suffixes, which will be interpreted
+and used to scale up its accompanying numerical value.
+.Sh RETURN VALUES
+.Fn humanize_number
+returns the number of characters stored in
+.Fa buffer
+(excluding the terminating NUL) upon success, or \-1 upon failure.
+If
+.Dv HN_GETSCALE
+is specified, the prefix index number will be returned instead.
+.Pp
+.Fn dehumanize_number
+returns 0 if the string was parsed correctly.
+A \-1 is returned to indicate failure and an error code is stored in
+.Va errno .
+.Sh ERRORS
+.Fn dehumanize_number
+will fail and no number will be stored in
+.Fa result
+if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The string in
+.Fa str
+was empty or carried an unknown suffix.
+.It Bq Er ERANGE
+The string in
+.Fa str
+represented a number that does not fit in
+.Fa result .
+.El
+.Sh SEE ALSO
+.Xr strsuftoll 3 ,
+.Xr orders 7 ,
+.Xr humanize_number 9
+.Sh HISTORY
+.Fn humanize_number
+first appeared in
+.Nx 2.0 .
+.Pp
+.Fn dehumanize_number
+first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/gen/humanize_number.c b/lib/nbsd_libc/gen/humanize_number.c
new file mode 100644 (file)
index 0000000..9166b06
--- /dev/null
@@ -0,0 +1,147 @@
+/*     $NetBSD: humanize_number.c,v 1.14 2008/04/28 20:22:59 martin Exp $      */
+
+/*
+ * Copyright (c) 1997, 1998, 1999, 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center, by Luke Mewburn and by Tomas Svensson.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: humanize_number.c,v 1.14 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <locale.h>
+
+int
+humanize_number(char *buf, size_t len, int64_t bytes,
+    const char *suffix, int scale, int flags)
+{
+       const char *prefixes, *sep;
+       int     b, i, r, maxscale, s1, s2, sign;
+       int64_t divisor, max;
+       size_t  baselen;
+
+       _DIAGASSERT(buf != NULL);
+       _DIAGASSERT(suffix != NULL);
+       _DIAGASSERT(scale >= 0);
+
+       if (flags & HN_DIVISOR_1000) {
+               /* SI for decimal multiplies */
+               divisor = 1000;
+               if (flags & HN_B)
+                       prefixes = "B\0k\0M\0G\0T\0P\0E";
+               else
+                       prefixes = "\0\0k\0M\0G\0T\0P\0E";
+       } else {
+               /*
+                * binary multiplies
+                * XXX IEC 60027-2 recommends Ki, Mi, Gi...
+                */
+               divisor = 1024;
+               if (flags & HN_B)
+                       prefixes = "B\0K\0M\0G\0T\0P\0E";
+               else
+                       prefixes = "\0\0K\0M\0G\0T\0P\0E";
+       }
+
+#define        SCALE2PREFIX(scale)     (&prefixes[(scale) << 1])
+       maxscale = 7;
+
+       if (scale >= maxscale &&
+           (scale & (HN_AUTOSCALE | HN_GETSCALE)) == 0)
+               return (-1);
+
+       if (buf == NULL || suffix == NULL)
+               return (-1);
+
+       if (len > 0)
+               buf[0] = '\0';
+       if (bytes < 0) {
+               sign = -1;
+               bytes *= -100;
+               baselen = 3;            /* sign, digit, prefix */
+       } else {
+               sign = 1;
+               bytes *= 100;
+               baselen = 2;            /* digit, prefix */
+       }
+       if (flags & HN_NOSPACE)
+               sep = "";
+       else {
+               sep = " ";
+               baselen++;
+       }
+       baselen += strlen(suffix);
+
+       /* Check if enough room for `x y' + suffix + `\0' */
+       if (len < baselen + 1)
+               return (-1);
+
+       if (scale & (HN_AUTOSCALE | HN_GETSCALE)) {
+               /* See if there is additional columns can be used. */
+               for (max = 100, i = len - baselen; i-- > 0;)
+                       max *= 10;
+
+               /*
+                * Divide the number until it fits the given column.
+                * If there will be an overflow by the rounding below,
+                * divide once more.
+                */
+               for (i = 0; bytes >= max - 50 && i < maxscale; i++)
+                       bytes /= divisor;
+
+               if (scale & HN_GETSCALE)
+                       return (i);
+       } else
+               for (i = 0; i < scale && i < maxscale; i++)
+                       bytes /= divisor;
+
+       /* If a value <= 9.9 after rounding and ... */
+       if (bytes < 995 && i > 0 && flags & HN_DECIMAL) {
+               /* baselen + \0 + .N */
+               if (len < baselen + 1 + 2)
+                       return (-1);
+               b = ((int)bytes + 5) / 10;
+               s1 = b / 10;
+               s2 = b % 10;
+               r = snprintf(buf, len, "%d%s%d%s%s%s",
+                   sign * s1, localeconv()->decimal_point, s2,
+                   sep, SCALE2PREFIX(i), suffix);
+       } else
+               r = snprintf(buf, len, "%" PRId64 "%s%s%s",
+                   sign * ((bytes + 50) / 100),
+                   sep, SCALE2PREFIX(i), suffix);
+
+       return (r);
+}
diff --git a/lib/nbsd_libc/gen/infinity_ieee754.c b/lib/nbsd_libc/gen/infinity_ieee754.c
new file mode 100644 (file)
index 0000000..56a540c
--- /dev/null
@@ -0,0 +1,20 @@
+/*     $NetBSD: infinity_ieee754.c,v 1.3 2005/06/12 05:21:27 lukem Exp $       */
+
+/*
+ * IEEE-compatible infinity.c -- public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: infinity_ieee754.c,v 1.3 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+const union __double_u __infinity =
+#if BYTE_ORDER == BIG_ENDIAN
+       { { 0x7f, 0xf0, 0, 0, 0, 0,    0,    0 } };
+#else
+       { {    0,    0, 0, 0, 0, 0, 0xf0, 0x7f } };
+#endif
diff --git a/lib/nbsd_libc/gen/infinityf_ieee754.c b/lib/nbsd_libc/gen/infinityf_ieee754.c
new file mode 100644 (file)
index 0000000..fedbcf3
--- /dev/null
@@ -0,0 +1,20 @@
+/*     $NetBSD: infinityf_ieee754.c,v 1.2 2005/06/12 05:21:27 lukem Exp $      */
+
+/*
+ * IEEE-compatible infinityf.c -- public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: infinityf_ieee754.c,v 1.2 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+
+const union __float_u __infinityf =
+#if BYTE_ORDER == BIG_ENDIAN
+       { { 0x7f, 0x80,     0,    0 } };
+#else
+       { {    0,    0,  0x80, 0x7f } };
+#endif
diff --git a/lib/nbsd_libc/gen/infinityl_dbl_ieee754.c b/lib/nbsd_libc/gen/infinityl_dbl_ieee754.c
new file mode 100644 (file)
index 0000000..3b77bdf
--- /dev/null
@@ -0,0 +1,21 @@
+/*     $NetBSD: infinityl_dbl_ieee754.c,v 1.1 2003/10/25 22:31:20 kleink Exp $ */
+
+/*
+ * IEEE-compatible infinityl.c -- public domain.
+ * For platforms where long double == double.
+ */
+
+#include <float.h>
+#include <math.h>
+#include <machine/endian.h>
+
+#if LDBL_MANT_DIG != DBL_MANT_DIG
+#error double / long double mismatch
+#endif
+
+const union __long_double_u __infinityl =
+#if BYTE_ORDER == BIG_ENDIAN
+       { { 0x7f, 0xf0, 0, 0, 0, 0,    0,    0 } };
+#else
+       { {    0,    0, 0, 0, 0, 0, 0xf0, 0x7f } };
+#endif
diff --git a/lib/nbsd_libc/gen/infinityl_ieee754.c b/lib/nbsd_libc/gen/infinityl_ieee754.c
new file mode 100644 (file)
index 0000000..7506faa
--- /dev/null
@@ -0,0 +1,39 @@
+/*     $NetBSD: infinityl_ieee754.c,v 1.1 2011/01/17 23:53:03 matt Exp $       */
+
+/*
+ * IEEE-compatible infinityl.c for 64-bit or 128-bit long double format.
+ * This is public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: infinityl_ieee754.c,v 1.1 2011/01/17 23:53:03 matt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <math.h>
+#include <machine/endian.h>
+#include <machine/ieee.h>
+
+#ifdef __HAVE_LONG_DOUBLE
+#define        LDBL_EXPBITS            EXT_EXPBITS
+#define        LDBL_EXP_INFNAN         EXT_EXP_INFNAN
+#else
+#define        LDBL_EXPBITS            DBL_EXPBITS
+#define        LDBL_EXP_INFNAN         DBL_EXP_INFNAN
+#endif
+
+#define        EXP_INFNAN              (LDBL_EXP_INFNAN << (31 - LDBL_EXPBITS))
+
+const union __long_double_u __infinityl = { {
+#if BYTE_ORDER == BIG_ENDIAN
+       [0] = (EXP_INFNAN >> 24) & 0x7f,
+       [1] = (EXP_INFNAN >> 16) & 0xff,
+       [2] = (EXP_INFNAN >>  8) & 0xff,
+       [3] = (EXP_INFNAN >>  0) & 0xff,
+#else
+       [sizeof(long double)-4] = (EXP_INFNAN >>  0) & 0xff,
+       [sizeof(long double)-3] = (EXP_INFNAN >>  8) & 0xff,
+       [sizeof(long double)-2] = (EXP_INFNAN >> 16) & 0xff,
+       [sizeof(long double)-1] = (EXP_INFNAN >> 24) & 0x7f,
+#endif
+} };
diff --git a/lib/nbsd_libc/gen/initdir.c b/lib/nbsd_libc/gen/initdir.c
new file mode 100644 (file)
index 0000000..a4b9e1e
--- /dev/null
@@ -0,0 +1,274 @@
+/*     $NetBSD: initdir.c,v 1.1 2010/09/26 02:26:59 yamt Exp $ */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: initdir.c,v 1.1 2010/09/26 02:26:59 yamt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include "extern.h"
+
+#include <sys/param.h>
+
+#include <assert.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "dirent_private.h"
+
+#define        MAXITERATIONS   100
+
+int
+_initdir(DIR *dirp, int fd, const char *name)
+{
+       int flags = dirp->dd_flags;
+       int pagesz;
+       int incr;
+
+       /*
+        * If the machine's page size is an exact multiple of DIRBLKSIZ,
+        * use a buffer that is cluster boundary aligned.
+        * Hopefully this can be a big win someday by allowing page trades
+        * to user space to be done by getdents()
+        */
+       if (((pagesz = getpagesize()) % DIRBLKSIZ) == 0)
+               incr = pagesz;
+       else
+               incr = DIRBLKSIZ;
+
+       if ((flags & DTF_REWIND) && name == NULL) {
+               return EINVAL;
+       }
+       if ((flags & __DTF_READALL) != 0) {
+               size_t len;
+               size_t space;
+               char *buf, *nbuf;
+               char *ddptr;
+               char *ddeptr;
+               int n;
+               struct dirent **dpv;
+               int i;
+
+               /*
+                * The strategy here for directories on top of a union stack
+                * is to read all the directory entries into a buffer, sort
+                * the buffer, and remove duplicate entries by setting the
+                * inode number to zero.
+                *
+                * For directories on an NFS mounted filesystem, we try
+                * to get a consistent snapshot by trying until we have
+                * successfully read all of the directory without errors
+                * (i.e. 'bad cookie' errors from the server because
+                * the directory was modified). These errors should not
+                * happen often, but need to be dealt with.
+                */
+               i = 0;
+retry:
+               len = 0;
+               space = 0;
+               buf = 0;
+               ddptr = 0;
+
+               do {
+                       /*
+                        * Always make at least DIRBLKSIZ bytes
+                        * available to getdents
+                        */
+                       if (space < DIRBLKSIZ) {
+                               space += incr;
+                               len += incr;
+                               nbuf = realloc(buf, len);
+                               if (nbuf == NULL) {
+                                       dirp->dd_buf = buf;
+                                       return errno;
+                               }
+                               buf = nbuf;
+                               ddptr = buf + (len - space);
+                       }
+
+                       dirp->dd_seek = lseek(fd, (off_t)0, SEEK_CUR);
+                       n = getdents(fd, ddptr, space);
+                       /*
+                        * For NFS: EINVAL means a bad cookie error
+                        * from the server. Keep trying to get a
+                        * consistent view, in this case this means
+                        * starting all over again.
+                        */
+                       if (n == -1 && errno == EINVAL &&
+                           (flags & __DTF_RETRY_ON_BADCOOKIE) != 0) {
+                               free(buf);
+                               lseek(fd, (off_t)0, SEEK_SET);
+                               if (++i > MAXITERATIONS)
+                                       return EINVAL;
+                               goto retry;
+                       }
+                       if (n > 0) {
+                               ddptr += n;
+                               space -= n;
+                       }
+               } while (n > 0);
+
+               ddeptr = ddptr;
+
+               /*
+                * Re-open the directory.
+                * This has the effect of rewinding back to the
+                * top of the union stack and is needed by
+                * programs which plan to fchdir to a descriptor
+                * which has also been read -- see fts.c.
+                */
+               if (flags & DTF_REWIND) {
+                       (void) close(fd);
+                       if ((fd = open(name, O_RDONLY)) == -1 ||
+                           fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
+                               dirp->dd_buf = buf;
+                               return errno;
+                       }
+               }
+
+               /*
+                * There is now a buffer full of (possibly) duplicate
+                * names.
+                */
+               dirp->dd_buf = buf;
+
+               /*
+                * Go round this loop twice...
+                *
+                * Scan through the buffer, counting entries.
+                * On the second pass, save pointers to each one.
+                * Then sort the pointers and remove duplicate names.
+                */
+               if ((flags & DTF_NODUP) != 0) {
+                       for (dpv = 0;;) {
+                               for (n = 0, ddptr = buf; ddptr < ddeptr;) {
+                                       struct dirent *dp;
+
+                                       dp = (struct dirent *)(void *)ddptr;
+                                       if ((long)dp & _DIRENT_ALIGN(dp))
+                                               break;
+                                       /*
+                                        * d_reclen is unsigned,
+                                        * so no need to compare <= 0
+                                        */
+                                       if (dp->d_reclen > (ddeptr + 1 - ddptr))
+                                               break;
+                                       ddptr += dp->d_reclen;
+                                       if (dp->d_fileno) {
+                                               if (dpv)
+                                                       dpv[n] = dp;
+                                               n++;
+                                       }
+                               }
+
+                               if (dpv) {
+                                       struct dirent *xp;
+
+                                       /*
+                                        * This sort must be stable.
+                                        */
+                                       mergesort(dpv, (size_t)n, sizeof(*dpv),
+                                           alphasort);
+
+                                       dpv[n] = NULL;
+                                       xp = NULL;
+
+                                       /*
+                                        * Scan through the buffer in sort
+                                        * order, zapping the inode number
+                                        * of any duplicate names.
+                                        */
+                                       for (n = 0; dpv[n]; n++) {
+                                               struct dirent *dp = dpv[n];
+
+                                               if ((xp == NULL) ||
+                                                   strcmp(dp->d_name,
+                                                     xp->d_name))
+                                                       xp = dp;
+                                               else
+                                                       dp->d_fileno = 0;
+                                               if (dp->d_type == DT_WHT &&
+                                                   (flags & DTF_HIDEW))
+                                                       dp->d_fileno = 0;
+                                       }
+
+                                       free(dpv);
+                                       break;
+                               } else {
+                                       dpv = malloc((n + 1) *
+                                           sizeof(struct dirent *));
+                                       if (dpv == NULL)
+                                               break;
+                               }
+                       }
+               }
+
+               dirp->dd_len = len;
+               dirp->dd_size = ddptr - dirp->dd_buf;
+       } else {
+               dirp->dd_len = incr;
+               dirp->dd_buf = malloc((size_t)dirp->dd_len);
+               if (dirp->dd_buf == NULL)
+                       return errno;
+               dirp->dd_seek = 0;
+               flags &= ~DTF_REWIND;
+       }
+       dirp->dd_loc = 0;
+       dirp->dd_fd = fd;
+       dirp->dd_flags = flags;
+       /*
+        * Set up seek point for rewinddir.
+        */
+       (void)_telldir_unlocked(dirp);
+       return 0;
+}
+
+void
+_finidir(DIR *dirp)
+{
+       struct dirpos *poslist;
+
+       free(dirp->dd_buf);
+
+       /* free seekdir/telldir storage */
+       for (poslist = dirp->dd_internal; poslist; ) {
+               struct dirpos *nextpos = poslist->dp_next;
+               free(poslist);
+               poslist = nextpos;
+       }
+       dirp->dd_internal = NULL;
+}
diff --git a/lib/nbsd_libc/gen/initgroups.3 b/lib/nbsd_libc/gen/initgroups.3
new file mode 100644 (file)
index 0000000..56e52a4
--- /dev/null
@@ -0,0 +1,91 @@
+.\"    $NetBSD: initgroups.3,v 1.15 2003/08/07 16:42:51 agc Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)initgroups.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd August 10, 2002
+.Dt INITGROUPS 3
+.Os
+.Sh NAME
+.Nm initgroups
+.Nd initialize supplementary group IDs
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn initgroups "const char *name" "gid_t basegid"
+.Sh DESCRIPTION
+The
+.Fn initgroups
+function
+uses the
+.Xr getgrouplist 3
+function to calculate the supplementary group IDs for the user
+specified in
+.Fa name .
+This group list is then set up for the current process using
+.Xr setgroups 2 .
+The
+.Fa basegid
+is automatically included in the group list.
+Typically this value is given as
+the group number from the password file.
+.Pp
+If the groups database lists more than
+.Ev NGROUPS
+groups for
+.Fa name
+(including one for
+.Fa basegid ) ,
+the later groups are ignored.
+.Sh RETURN VALUES
+The
+.Fn initgroups
+function
+returns \-1 if it was not invoked by the super-user.
+.Sh SEE ALSO
+.Xr setgroups 2 ,
+.Xr getgrouplist 3
+.Sh HISTORY
+The
+.Fn initgroups
+function appeared in
+.Bx 4.2 .
+.Sh BUGS
+The
+.Fn getgrouplist
+function called by
+.Fn initgroups
+uses the routines based on
+.Xr getgrent 3 .
+If the invoking program uses any of these routines,
+the group structure will
+be overwritten in the call to
+.Fn initgroups .
diff --git a/lib/nbsd_libc/gen/initgroups.c b/lib/nbsd_libc/gen/initgroups.c
new file mode 100644 (file)
index 0000000..e1c293b
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: initgroups.c,v 1.21 2003/08/07 16:42:51 agc Exp $      */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)initgroups.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: initgroups.c,v 1.21 2003/08/07 16:42:51 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+
+#include <assert.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#ifdef __weak_alias
+__weak_alias(initgroups,_initgroups)
+#endif
+
+int
+initgroups(uname, agroup)
+       const char *uname;
+       gid_t agroup;
+{
+       gid_t groups_list[NGROUPS];
+       int ngroups;
+       gid_t *groups = groups_list;
+       int rval;
+
+       _DIAGASSERT(uname != NULL);
+
+       ngroups = NGROUPS;
+       if (getgrouplist(uname, agroup, groups, &ngroups) == -1) {
+               int maxgroups = ngroups;
+               groups = calloc((size_t)maxgroups, sizeof *groups);
+               if (groups == NULL)
+                       return -1;
+               if (getgrouplist(uname, agroup, groups, &ngroups) == -1)
+                       ngroups = maxgroups;
+       }
+       rval = setgroups(ngroups, groups);
+       if (rval == -1 && errno == EINVAL) {
+               int ng = (int)sysconf(_SC_NGROUPS_MAX);
+               if (ng > 0 && ng < ngroups)
+                       rval = setgroups(ng, groups);
+       }
+       if (groups != groups_list)
+               free(groups);
+       return rval;
+}
diff --git a/lib/nbsd_libc/gen/isalnum.3 b/lib/nbsd_libc/gen/isalnum.3
new file mode 100644 (file)
index 0000000..53d6ec0
--- /dev/null
@@ -0,0 +1,97 @@
+.\"    $NetBSD: isalnum.3,v 1.15 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)isalnum.3  5.2 (Berkeley) 6/29/91
+.\"
+.Dd April 17, 2008
+.Dt ISALNUM 3
+.Os
+.Sh NAME
+.Nm isalnum
+.Nd alphanumeric character test
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn isalnum "int c"
+.Sh DESCRIPTION
+The
+.Fn isalnum
+function tests for any character for which
+.Xr isalpha 3
+or
+.Xr isdigit 3
+is true.
+.Sh RETURN VALUES
+The
+.Fn isalnum
+function returns zero if the character tests false and
+returns non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn isalnum
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn isalnum
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/isalpha.3 b/lib/nbsd_libc/gen/isalpha.3
new file mode 100644 (file)
index 0000000..51c9022
--- /dev/null
@@ -0,0 +1,114 @@
+.\"    $NetBSD: isalpha.3,v 1.14 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)isalpha.3  5.2 (Berkeley) 6/29/91
+.\"
+.Dd April 17, 2008
+.Dt ISALPHA 3
+.Os
+.Sh NAME
+.Nm isalpha
+.Nd alphabetic character test
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn isalpha "int c"
+.Sh DESCRIPTION
+The
+.Fn isalpha
+function tests for any character for which
+.Xr isupper 3
+or
+.Xr islower 3
+is true and
+.\" , or any of an implementation-defined set of characters
+for which none of
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr ispunct 3 ,
+or
+.Xr isspace 3
+is true.
+In the
+.Em ``C''
+locale,
+.Fn isalpha
+returns true only for the characters for which
+.Xr isupper 3
+or
+.Xr islower 3
+is true.
+.Sh RETURN VALUES
+The
+.Fn isalpha
+function returns zero if the character tests false and
+returns non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isascii 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn isalpha
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn isalpha
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/isascii.3 b/lib/nbsd_libc/gen/isascii.3
new file mode 100644 (file)
index 0000000..ecb5830
--- /dev/null
@@ -0,0 +1,85 @@
+.\"    $NetBSD: isascii.3,v 1.18 2010/04/30 04:46:18 jruoho Exp $
+.\"
+.\" Copyright (c) 1989, 1991 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.
+.\" 3. 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.
+.\"
+.\"     @(#)isascii.3  5.1 (Berkeley) 5/2/91
+.\"
+.Dd April 30, 2010
+.Dt ISASCII 3
+.Os
+.Sh NAME
+.Nm isascii
+.Nd test for ASCII character
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn isascii "int c"
+.Sh DESCRIPTION
+The
+.Fn isascii
+function tests for an
+.Tn ASCII
+character, which is any character with a value in the
+range from 0 to 127, inclusive.
+.Pp
+The
+.Fn isascii
+is defined on all integer values.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn isascii
+function conforms to
+.St -xpg4
+and
+.St -p1003.1-2001 .
+The
+.St -p1003.1-2008
+revision however marked it as obsolete, noting that
+.Fn isascii
+cannot be used portably in a localized application.
diff --git a/lib/nbsd_libc/gen/isascii.c b/lib/nbsd_libc/gen/isascii.c
new file mode 100644 (file)
index 0000000..b441a32
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: isascii.c,v 1.3 2010/06/01 13:52:08 tnozaki Exp $      */
+
+/*
+ * Copyright (c) 1989 The Regents of the University of California.
+ * All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     from:   @(#)isctype.c   5.2 (Berkeley) 6/1/90
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: isascii.c,v 1.3 2010/06/01 13:52:08 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define _CTYPE_NOINLINE
+#include <ctype.h>
+
+int
+isascii(c)
+       int c;
+{
+       return ((unsigned)(c) <= 0177);
+}
diff --git a/lib/nbsd_libc/gen/isatty.c b/lib/nbsd_libc/gen/isatty.c
new file mode 100644 (file)
index 0000000..2bc3106
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: isatty.c,v 1.12 2003/08/07 16:42:51 agc Exp $  */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isatty.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isatty.c,v 1.12 2003/08/07 16:42:51 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <termios.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(isatty,_isatty)
+#endif
+
+int
+isatty(fd)
+       int fd;
+{
+       struct termios t;
+
+       return(tcgetattr(fd, &t) != -1);
+}
diff --git a/lib/nbsd_libc/gen/isblank.3 b/lib/nbsd_libc/gen/isblank.3
new file mode 100644 (file)
index 0000000..59a5ca1
--- /dev/null
@@ -0,0 +1,102 @@
+.\"    $NetBSD: isblank.3,v 1.13 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)isspace.3  5.3 (Berkeley) 7/31/91
+.\"
+.Dd April 17, 2008
+.Dt ISBLANK 3
+.Os
+.Sh NAME
+.Nm isblank
+.Nd blank-space character test
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn isblank "int c"
+.Sh DESCRIPTION
+The
+.Fn isblank
+function tests for the standard blank-space characters.
+The standard blank-space characters are the following:
+.Pp
+.Bl -tag -width xxxxx -offset indent -compact
+.It Sq \0
+Space character.
+.It Li \et
+Horizontal tab.
+.El
+.Pp
+In the
+.Em ``C''
+locale,
+.Fn isblank
+returns true only for the standard blank-space characters.
+.Sh RETURN VALUES
+The
+.Fn isblank
+function returns zero if the character tests false and
+returns non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh CAVEATS
+The argument to
+.Fn isblank
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/iscntrl.3 b/lib/nbsd_libc/gen/iscntrl.3
new file mode 100644 (file)
index 0000000..efea8f8
--- /dev/null
@@ -0,0 +1,93 @@
+.\"    $NetBSD: iscntrl.3,v 1.13 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)iscntrl.3  5.2 (Berkeley) 6/29/91
+.\"
+.Dd April 17, 2008
+.Dt ISCNTRL 3
+.Os
+.Sh NAME
+.Nm iscntrl
+.Nd control character test
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn iscntrl "int c"
+.Sh DESCRIPTION
+The
+.Fn iscntrl
+function tests for any control character.
+.Sh RETURN VALUES
+The
+.Fn iscntrl
+function returns zero if the character tests false and
+returns non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr isblank 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn iscntrl
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn iscntrl
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/isctype.c b/lib/nbsd_libc/gen/isctype.c
new file mode 100644 (file)
index 0000000..acab4eb
--- /dev/null
@@ -0,0 +1,99 @@
+/* $NetBSD: isctype.c,v 1.21 2010/12/14 02:28:57 joerg Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: isctype.c,v 1.21 2010/12/14 02:28:57 joerg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/ctype_bits.h>
+#define _CTYPE_NOINLINE
+#include <ctype.h>
+#include <langinfo.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stdio.h>
+#if EOF != -1
+#error "EOF != -1"
+#endif
+
+#include "setlocale_local.h"
+
+#define _CTYPE_TAB(table, i)   ((_current_cache()->table + 1)[i])
+
+#define _ISCTYPE_FUNC(name, bit) \
+int \
+is##name(int c) \
+{ \
+       return (int)(_CTYPE_TAB(ctype_tab, c) & (bit)); \
+}
+
+_ISCTYPE_FUNC(alnum,  _CTYPE_U|_CTYPE_L|_CTYPE_N      )
+_ISCTYPE_FUNC(alpha,  _CTYPE_U|_CTYPE_L         )
+_ISCTYPE_FUNC(cntrl,  _CTYPE_C            )
+_ISCTYPE_FUNC(digit,  _CTYPE_N            )
+_ISCTYPE_FUNC(graph,  _CTYPE_P|_CTYPE_U|_CTYPE_L|_CTYPE_N   )
+_ISCTYPE_FUNC(lower,  _CTYPE_L            )
+_ISCTYPE_FUNC(print,  _CTYPE_P|_CTYPE_U|_CTYPE_L|_CTYPE_N|_CTYPE_B)
+_ISCTYPE_FUNC(punct,  _CTYPE_P            )
+_ISCTYPE_FUNC(space,  _CTYPE_S            )
+_ISCTYPE_FUNC(upper,  _CTYPE_U            )
+_ISCTYPE_FUNC(xdigit, _CTYPE_N|_CTYPE_X         )
+
+int
+isblank(int c)
+{
+       /* XXX: FIXME */
+        return c == ' ' || c == '\t';
+}
+
+int
+toupper(int c)
+{
+       return (int)_CTYPE_TAB(toupper_tab, c);
+}
+
+int
+tolower(int c)
+{
+       return (int)_CTYPE_TAB(tolower_tab, c);
+}
+
+int
+_toupper(int c)
+{
+       return (c - 'a' + 'A');
+}
+
+int
+_tolower(int c)
+{
+       return (c - 'A' + 'a');
+}
diff --git a/lib/nbsd_libc/gen/isdigit.3 b/lib/nbsd_libc/gen/isdigit.3
new file mode 100644 (file)
index 0000000..80e297c
--- /dev/null
@@ -0,0 +1,93 @@
+.\"    $NetBSD: isdigit.3,v 1.14 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)isdigit.3  5.2 (Berkeley) 6/29/91
+.\"
+.Dd April 17, 2008
+.Dt ISDIGIT 3
+.Os
+.Sh NAME
+.Nm isdigit
+.Nd decimal-digit character test
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn isdigit "int c"
+.Sh DESCRIPTION
+The
+.Fn isdigit
+function tests for any decimal-digit character.
+.Sh RETURN VALUES
+The
+.Fn isdigit
+function returns zero if the character tests false and
+returns non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn isdigit
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn isdigit
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/isfinite.3 b/lib/nbsd_libc/gen/isfinite.3
new file mode 100644 (file)
index 0000000..2d159a6
--- /dev/null
@@ -0,0 +1,77 @@
+.\"    $NetBSD: isfinite.3,v 1.3 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd October 29, 2003
+.Dt ISFINITE 3
+.Os
+.Sh NAME
+.Nm isfinite
+.Nd test for finite value
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In math.h
+.Ft int
+.Fn isfinite "real-floating x"
+.Sh DESCRIPTION
+The
+.Fn isfinite
+determines whether its argument
+.Fa x
+has a finite value.
+An argument represented in a format wider than its semantic type is
+converted to its semantic type first.
+The determination is then based on the type of the argument.
+.Ss IEEE 754
+It is determined whether the value of
+.Fa x
+is zero, subnormal, or normal, and neither infinite nor NaN.
+.Ss VAX
+It is determined whether the value of
+.Fa x
+is true zero or finite, and neither dirty zero nor ROP.
+.Sh RETURN VALUES
+The
+.Fn isfinite
+macro returns a non-zero value if the value of
+.Fa x
+is finite.
+Otherwise 0 is returned.
+.Sh ERRORS
+No errors are defined.
+.Sh SEE ALSO
+.Xr fpclassify 3 ,
+.Xr isnormal 3 ,
+.Xr math 3 ,
+.Xr signbit 3
+.Sh STANDARDS
+The
+.Fn isfinite
+macro conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/gen/isfinited_ieee754.c b/lib/nbsd_libc/gen/isfinited_ieee754.c
new file mode 100644 (file)
index 0000000..7cdf6eb
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: isfinited_ieee754.c,v 1.2 2008/04/28 20:22:59 martin Exp $     */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: isfinited_ieee754.c,v 1.2 2008/04/28 20:22:59 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.2 isfinite - determine whether an argument has finite value
+ *          IEEE 754 double-precision version
+ */
+int
+__isfinited(double x)
+{
+       union ieee_double_u u;
+
+       u.dblu_d = x;
+
+       if (u.dblu_dbl.dbl_exp == DBL_EXP_INFNAN)
+               return 0;
+
+       return 1;
+}
diff --git a/lib/nbsd_libc/gen/isfinitef_ieee754.c b/lib/nbsd_libc/gen/isfinitef_ieee754.c
new file mode 100644 (file)
index 0000000..6014fb7
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: isfinitef_ieee754.c,v 1.2 2008/04/28 20:22:59 martin Exp $     */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: isfinitef_ieee754.c,v 1.2 2008/04/28 20:22:59 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.2 isfinite - determine whether an argument has finite value
+ *          IEEE 754 single-precision version
+ */
+int
+__isfinitef(float x)
+{
+       union ieee_single_u u;
+
+       u.sngu_f = x;
+
+       if (u.sngu_sng.sng_exp == SNG_EXP_INFNAN)
+               return 0;
+
+       return 1;
+}
diff --git a/lib/nbsd_libc/gen/isfinitel_ieee754.c b/lib/nbsd_libc/gen/isfinitel_ieee754.c
new file mode 100644 (file)
index 0000000..d95bfb4
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: isfinitel_ieee754.c,v 1.1 2011/01/17 23:53:03 matt Exp $       */
+
+/*-
+ * Copyright (c) 2011 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: isfinitel_ieee754.c,v 1.1 2011/01/17 23:53:03 matt Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+#ifdef __HAVE_LONG_DOUBLE
+/*
+ * 7.12.3.2 isfinite - determine whether an argument has finite value
+ *          IEEE 754 compatible 128-bit extended-precision version
+ */
+int
+__isfinitel(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       if (u.extu_ext.ext_exp == EXT_EXP_INFNAN)
+               return 0;
+
+       return 1;
+}
+#endif /* __HAVE_LONG_DOUBLE */
diff --git a/lib/nbsd_libc/gen/isgraph.3 b/lib/nbsd_libc/gen/isgraph.3
new file mode 100644 (file)
index 0000000..083e82c
--- /dev/null
@@ -0,0 +1,93 @@
+.\"    $NetBSD: isgraph.3,v 1.14 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)isgraph.3  5.2 (Berkeley) 6/29/91
+.\"
+.Dd April 17, 2008
+.Dt ISGRAPH 3
+.Os
+.Sh NAME
+.Nm isgraph
+.Nd printing character test (space character exclusive)
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn isgraph "int c"
+.Sh DESCRIPTION
+The
+.Fn isgraph
+function tests for any printing character except space ('\ ').
+.Sh RETURN VALUES
+The
+.Fn isgraph
+function returns zero if the character tests false and
+returns non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn isgraph
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn isgraph
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/isgreater.3 b/lib/nbsd_libc/gen/isgreater.3
new file mode 100644 (file)
index 0000000..e6fed54
--- /dev/null
@@ -0,0 +1,104 @@
+.\" $NetBSD: isgreater.3,v 1.1 2007/02/22 22:08:20 drochner Exp $
+.\"
+.\" Copyright (c) 2003 David Schultz <das@FreeBSD.ORG>
+.\" 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.
+.\"
+.\" FreeBSD: /repoman/r/ncvs/src/lib/libc/gen/isgreater.3,v 1.3 2005/02/06 03:23:31 das Exp
+.\"
+.Dd February 12, 2003
+.Dt ISGREATER 3
+.Os
+.Sh NAME
+.Nm isgreater , isgreaterequal , isless , islessequal ,
+.Nm islessgreater , isunordered
+.Nd "compare two floating-point numbers"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In math.h
+.Ft int
+.Fn isgreater "real-floating x" "real-floating y"
+.Ft int
+.Fn isgreaterequal "real-floating x" "real-floating y"
+.Ft int
+.Fn isless "real-floating x" "real-floating y"
+.Ft int
+.Fn islessequal "real-floating x" "real-floating y"
+.Ft int
+.Fn islessgreater "real-floating x" "real-floating y"
+.Ft int
+.Fn isunordered "real-floating x" "real-floating y"
+.Sh DESCRIPTION
+Each of the macros
+.Fn isgreater ,
+.Fn isgreaterequal ,
+.Fn isless ,
+.Fn islessequal ,
+and
+.Fn islessgreater
+take arguments
+.Fa x
+and
+.Fa y
+and return a non-zero value if and only if its nominal
+relation on
+.Fa x
+and
+.Fa y
+is true.
+These macros always return zero if either
+argument is not a number (NaN), but unlike the corresponding C
+operators, they never raise a floating point exception.
+.Pp
+The
+.Fn isunordered
+macro takes arguments
+.Fa x
+and
+.Fa y
+and returns non-zero if and only if neither
+.Fa x
+nor
+.Fa y
+are NaNs.
+For any pair of floating-point values, one
+of the relationships (less, greater, equal, unordered) holds.
+.Sh SEE ALSO
+.Xr fpclassify 3 ,
+.Xr math 3 ,
+.Xr signbit 3
+.Sh STANDARDS
+The
+.Fn isgreater ,
+.Fn isgreaterequal ,
+.Fn isless ,
+.Fn islessequal ,
+.Fn islessgreater ,
+and
+.Fn isunordered
+macros conform to
+.St -isoC-99 .
+.Sh HISTORY
+The relational macros described above first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/gen/isinf.3 b/lib/nbsd_libc/gen/isinf.3
new file mode 100644 (file)
index 0000000..713e0ca
--- /dev/null
@@ -0,0 +1,84 @@
+.\"    $NetBSD: isinf.3,v 1.12 2004/03/04 23:47:56 wiz Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)isinf.3    8.2 (Berkeley) 1/29/94
+.\"
+.Dd March 5, 2004
+.Dt ISINF 3
+.Os
+.Sh NAME
+.Nm isinf
+.Nd test for infinity
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In math.h
+.Ft int
+.Fn isinf "real-floating x"
+.Sh DESCRIPTION
+The
+.Fn isinf
+macro determines whether its argument
+.Fa x
+is an infinity (positive or negative).
+An argument represented in a format wider than its semantic type is
+converted to its semantic type first.
+The determination is then based on the type of the argument.
+.Ss IEEE 754
+It is determined whether the value of
+.Fa x
+is an infinity.
+.Ss VAX
+Infinities are not supported.
+.Sh RETURN VALUES
+The
+.Fn isinf
+macro returns a non-zero value if the value of
+.Fa x
+is an infinity.
+Otherwise 0 is returned.
+.Sh SEE ALSO
+.Xr fpclassify 3 ,
+.Xr isfinite 3 ,
+.Xr isinff 3 ,
+.Xr isnan 3 ,
+.Xr isnanf 3 ,
+.Xr isnormal 3 ,
+.Xr math 3 ,
+.Xr signbit 3
+.Rs
+.%T "IEEE Standard for Binary Floating-Point Arithmetic"
+.%Q ANSI
+.%R Std 754-1985
+.Re
+.Sh STANDARDS
+The
+.Fn isinf
+macro conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/gen/isinfd_ieee754.c b/lib/nbsd_libc/gen/isinfd_ieee754.c
new file mode 100644 (file)
index 0000000..18899b7
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: isinfd_ieee754.c,v 1.1 2004/03/04 23:42:39 kleink Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isinfd_ieee754.c,v 1.1 2004/03/04 23:42:39 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/* libc.so.12 ABI compatbility */
+#ifdef __weak_alias
+__weak_alias(isinf,__isinfd)
+#endif
+
+/*
+ * 7.12.3.3 isinf - test for infinity
+ *          IEEE 754 double-precision version
+ */
+int
+__isinfd(double x)
+{
+       union ieee_double_u u;
+
+       u.dblu_d = x;
+
+       return (u.dblu_dbl.dbl_exp == DBL_EXP_INFNAN &&
+           (u.dblu_dbl.dbl_frach == 0 && u.dblu_dbl.dbl_fracl == 0));
+}
diff --git a/lib/nbsd_libc/gen/isinff_ieee754.c b/lib/nbsd_libc/gen/isinff_ieee754.c
new file mode 100644 (file)
index 0000000..62f4e0f
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: isinff_ieee754.c,v 1.1 2004/03/04 23:42:39 kleink Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isinff_ieee754.c,v 1.1 2004/03/04 23:42:39 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.3 isinf - test for infinity
+ *          IEEE 754 single-precision version
+ */
+int
+__isinff(float x)
+{
+       union ieee_single_u u;
+
+       u.sngu_f = x;
+
+       return (u.sngu_sng.sng_exp == SNG_EXP_INFNAN &&
+           u.sngu_sng.sng_frac == 0);
+}
diff --git a/lib/nbsd_libc/gen/isinfl_ieee754.c b/lib/nbsd_libc/gen/isinfl_ieee754.c
new file mode 100644 (file)
index 0000000..9c99d3d
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: isinfl_ieee754.c,v 1.4 2011/01/17 23:53:03 matt Exp $  */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isinfl_ieee754.c,v 1.4 2011/01/17 23:53:03 matt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+#ifdef __HAVE_LONG_DOUBLE
+/*
+ * 7.12.3.3 isinf - test for infinity
+ *          IEEE 754 compatible 128-bit extended-precision version
+ */
+int
+__isinfl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return u.extu_ext.ext_exp == EXT_EXP_INFNAN
+           && u.extu_ext.ext_frach == 0 && u.extu_ext.ext_frachm == 0
+           && u.extu_ext.ext_fraclm == 0 && u.extu_ext.ext_fracl == 0;
+}
+#endif /* __HAVE_LONG_DOUBLE */
diff --git a/lib/nbsd_libc/gen/islower.3 b/lib/nbsd_libc/gen/islower.3
new file mode 100644 (file)
index 0000000..1322e36
--- /dev/null
@@ -0,0 +1,107 @@
+.\"    $NetBSD: islower.3,v 1.14 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)islower.3  5.2 (Berkeley) 6/29/91
+.\"
+.Dd April 17, 2008
+.Dt ISLOWER 3
+.Os
+.Sh NAME
+.Nm islower
+.Nd lower-case character test
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn islower "int c"
+.Sh DESCRIPTION
+The
+.Fn islower
+function tests for any lower-case letter
+.\" or any of an
+.\" implementation-defined set of characters
+for which none of
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr ispunct 3 ,
+or
+.Xr isspace 3
+is true.
+In the
+.Em ``C''
+locale,
+.Fn islower
+returns true only for the characters defined as lower-case letters.
+.Sh RETURN VALUES
+The
+.Fn islower
+function returns zero if the character tests false and
+returns non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn islower
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn islower
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/isnan.3 b/lib/nbsd_libc/gen/isnan.3
new file mode 100644 (file)
index 0000000..4244214
--- /dev/null
@@ -0,0 +1,86 @@
+.\"    $NetBSD: isnan.3,v 1.2 2004/03/04 23:49:31 wiz Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"     From: @(#)isinf.3      8.2 (Berkeley) 1/29/94
+.\"    from: NetBSD: isinf.3,v 1.10 2003/08/07 16:42:52 agc Exp
+.\"
+.Dd March 5, 2004
+.Dt ISNAN 3
+.Os
+.Sh NAME
+.Nm isnan
+.Nd test for not-a-number
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In math.h
+.Ft int
+.Fn isnan "real-floating x"
+.Sh DESCRIPTION
+The
+.Fn isnan
+macro determines whether its argument
+.Fa x
+is not-a-number
+.Pq Dq NaN .
+An argument represented in a format wider than its semantic type is
+converted to its semantic type first.
+The determination is then based on the type of the argument.
+.Ss IEEE 754
+It is determined whether the value of
+.Fa x
+is a NaN.
+.Ss VAX
+NaNs are not supported.
+.Sh RETURN VALUES
+The
+.Fn isnan
+macro returns a non-zero value if the value of
+.Fa x
+is a NaN.
+Otherwise 0 is returned.
+.Sh SEE ALSO
+.Xr fpclassify 3 ,
+.Xr isfinite 3 ,
+.Xr isinf 3 ,
+.Xr isinff 3 ,
+.Xr isnanf 3 ,
+.Xr isnormal 3 ,
+.Xr math 3 ,
+.Xr signbit 3
+.Rs
+.%T "IEEE Standard for Binary Floating-Point Arithmetic"
+.%Q ANSI
+.%R Std 754-1985
+.Re
+.Sh STANDARDS
+The
+.Fn isnan
+macro conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/gen/isnand_ieee754.c b/lib/nbsd_libc/gen/isnand_ieee754.c
new file mode 100644 (file)
index 0000000..0ce4bd9
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: isnand_ieee754.c,v 1.1 2004/03/04 23:42:39 kleink Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isnand_ieee754.c,v 1.1 2004/03/04 23:42:39 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/* libc.so.12 ABI compatbility */
+#ifdef __weak_alias
+__weak_alias(isnan,__isnand)
+#endif
+
+/*
+ * 7.12.3.4 isnan - test for a NaN
+ *          IEEE 754 double-precision version
+ */
+int
+__isnand(double x)
+{
+       union ieee_double_u u;
+
+       u.dblu_d = x;
+
+       return (u.dblu_dbl.dbl_exp == DBL_EXP_INFNAN &&
+           (u.dblu_dbl.dbl_frach != 0 || u.dblu_dbl.dbl_fracl != 0));
+}
diff --git a/lib/nbsd_libc/gen/isnanf_ieee754.c b/lib/nbsd_libc/gen/isnanf_ieee754.c
new file mode 100644 (file)
index 0000000..ee3b94d
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: isnanf_ieee754.c,v 1.1 2004/03/04 23:42:39 kleink Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isnanf_ieee754.c,v 1.1 2004/03/04 23:42:39 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.4 isnan - test for a NaN
+ *          IEEE 754 single-precision version
+ */
+int
+__isnanf(float x)
+{
+       union ieee_single_u u;
+
+       u.sngu_f = x;
+
+       return (u.sngu_sng.sng_exp == SNG_EXP_INFNAN &&
+           u.sngu_sng.sng_frac != 0);
+}
diff --git a/lib/nbsd_libc/gen/isnanl_ieee754.c b/lib/nbsd_libc/gen/isnanl_ieee754.c
new file mode 100644 (file)
index 0000000..d74a54b
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: isnanl_ieee754.c,v 1.6 2011/01/17 23:53:03 matt Exp $  */
+
+/*
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ *
+ * from: Header: isinf.c,v 1.1 91/07/08 19:03:34 torek Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)isinf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: isnanl_ieee754.c,v 1.6 2011/01/17 23:53:03 matt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <machine/ieee.h>
+#include <math.h>
+
+#ifdef __HAVE_LONG_DOUBLE
+/*
+ * 7.12.3.4 isnan - test for a NaN
+ *          IEEE 754 compatible 128-bit extended-precision version
+ */
+int
+__isnanl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return u.extu_ext.ext_exp == EXT_EXP_INFNAN 
+           && (u.extu_ext.ext_frach != 0 || u.extu_ext.ext_frachm != 0
+               || u.extu_ext.ext_fraclm != 0 || u.extu_ext.ext_fracl != 0);
+}
+#endif /* __HAVE_LONG_DOUBLE */
diff --git a/lib/nbsd_libc/gen/isnormal.3 b/lib/nbsd_libc/gen/isnormal.3
new file mode 100644 (file)
index 0000000..7ccda97
--- /dev/null
@@ -0,0 +1,77 @@
+.\"    $NetBSD: isnormal.3,v 1.3 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd October 29, 2003
+.Dt ISNORMAL 3
+.Os
+.Sh NAME
+.Nm isnormal
+.Nd test for normal value
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In math.h
+.Ft int
+.Fn isnormal "real-floating x"
+.Sh DESCRIPTION
+The
+.Fn isnormal
+macro determines whether its argument
+.Fa x
+has a normal value.
+An argument represented in a format wider than its semantic type is
+converted to its semantic type first.
+The determination is then based on the type of the argument.
+.Ss IEEE 754
+It is determined whether the value of
+.Fa x
+is normal, and neither zero, subnormal, infinite nor NaN.
+.Ss VAX
+It is determined whether the value of
+.Fa x
+is finite, and neither true zero, dirty zero nor ROP.
+.Sh RETURN VALUES
+The
+.Fn isnormal
+macro returns a non-zero value if the value of
+.Fa x
+is finite.
+Otherwise 0 is returned.
+.Sh ERRORS
+No errors are defined.
+.Sh SEE ALSO
+.Xr fpclassify 3 ,
+.Xr isfinite 3 ,
+.Xr math 3 ,
+.Xr signbit 3
+.Sh STANDARDS
+The
+.Fn isnormal
+macro conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/gen/isprint.3 b/lib/nbsd_libc/gen/isprint.3
new file mode 100644 (file)
index 0000000..e209109
--- /dev/null
@@ -0,0 +1,93 @@
+.\"    $NetBSD: isprint.3,v 1.13 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)isprint.3  5.2 (Berkeley) 6/29/91
+.\"
+.Dd April 17, 2008
+.Dt ISPRINT 3
+.Os
+.Sh NAME
+.Nm isprint
+.Nd printing character test (space character inclusive)
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn isprint "int c"
+.Sh DESCRIPTION
+The
+.Fn isprint
+function tests for any printing character including space (' ').
+.Sh RETURN VALUES
+The
+.Fn isprint
+function returns zero if the character tests false and
+returns non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn isprint
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn isprint
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/ispunct.3 b/lib/nbsd_libc/gen/ispunct.3
new file mode 100644 (file)
index 0000000..8d32ac6
--- /dev/null
@@ -0,0 +1,96 @@
+.\"    $NetBSD: ispunct.3,v 1.13 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"    @(#)ispunct.3   5.2 (Berkeley) 6/29/91
+.\"
+.Dd April 17, 2008
+.Dt ISPUNCT 3
+.Os
+.Sh NAME
+.Nm ispunct
+.Nd punctuation character test
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn ispunct "int c"
+.Sh DESCRIPTION
+The
+.Fn ispunct
+function tests for any printing character except space (' ') or a
+character for which
+.Xr isalnum 3
+is true.
+.Sh RETURN VALUES
+The
+.Fn ispunct
+function returns zero if the character tests false and
+returns non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn ispunct
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn ispunct
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/isspace.3 b/lib/nbsd_libc/gen/isspace.3
new file mode 100644 (file)
index 0000000..bb1dcbb
--- /dev/null
@@ -0,0 +1,120 @@
+.\"    $NetBSD: isspace.3,v 1.14 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)isspace.3  5.3 (Berkeley) 7/31/91
+.\"
+.Dd April 17, 2008
+.Dt ISSPACE 3
+.Os
+.Sh NAME
+.Nm isspace
+.Nd white-space character test
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn isspace "int c"
+.Sh DESCRIPTION
+The
+.Fn isspace
+function tests for the standard white-space characters
+.\" or for any
+.\" of an implementation-defined set of characters
+for which
+.Xr isalnum 3
+is false.
+The standard white-space characters are the following:
+.Pp
+.Bl -tag -width xxxxx -offset indent -compact
+.It Sq \0
+Space character.
+.It Li \ef
+Form feed.
+.It Li \en
+New-line.
+.It Li \er
+Carriage return.
+.It Li \et
+Horizontal tab.
+.It Li \ev
+And vertical tab.
+.El
+.Pp
+In the
+.Em ``C''
+locale,
+.Fn isspace
+returns true only for the standard white-space characters.
+.Sh RETURN VALUES
+The
+.Fn isspace
+function returns zero if the character tests false and
+returns non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn isspace
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn isspace
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/isupper.3 b/lib/nbsd_libc/gen/isupper.3
new file mode 100644 (file)
index 0000000..d969eca
--- /dev/null
@@ -0,0 +1,105 @@
+.\"    $NetBSD: isupper.3,v 1.14 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)isupper.3  5.2 (Berkeley) 6/29/91
+.\"
+.Dd April 17, 2008
+.Dt ISUPPER 3
+.Os
+.Sh NAME
+.Nm isupper
+.Nd upper-case character test
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn isupper "int c"
+.Sh DESCRIPTION
+The
+.Fn isupper
+function tests for any upper-case letter or any of an
+implementation-defined set of characters for which none of
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr ispunct 3 ,
+or
+.Xr isspace 3
+is true.
+In the
+.Em ``C''
+locale,
+.Fn isupper
+returns true only for the characters defined as upper-case letters.
+.Sh RETURN VALUES
+The
+.Fn isupper
+function returns zero if the character tests false and
+returns non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn isupper
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn isupper
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/isxdigit.3 b/lib/nbsd_libc/gen/isxdigit.3
new file mode 100644 (file)
index 0000000..7777af0
--- /dev/null
@@ -0,0 +1,93 @@
+.\"    $NetBSD: isxdigit.3,v 1.13 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)isxdigit.3 5.2 (Berkeley) 6/29/91
+.\"
+.Dd April 17, 2008
+.Dt ISXDIGIT 3
+.Os
+.Sh NAME
+.Nm isxdigit
+.Nd hexadecimal-digit character test
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn isxdigit "int c"
+.Sh DESCRIPTION
+The
+.Fn isxdigit
+function tests for any hexadecimal-digit character.
+.Sh RETURN VALUES
+The
+.Fn isxdigit
+function returns zero if the character tests false and
+returns non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn isxdigit
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn isxdigit
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/ldexp_ieee754.c b/lib/nbsd_libc/gen/ldexp_ieee754.c
new file mode 100644 (file)
index 0000000..cc8149a
--- /dev/null
@@ -0,0 +1,142 @@
+/*     $NetBSD: ldexp_ieee754.c,v 1.5 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Charles M. Hannum.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ldexp_ieee754.c,v 1.5 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <machine/ieee.h>
+#include <errno.h>
+#include <math.h>
+
+/*
+ * Multiply the given value by 2^expon.
+ */
+double
+ldexp(double val, int expon)
+{
+       int oldexp, newexp;
+       union ieee_double_u u, mul;
+
+       u.dblu_d = val;
+       oldexp = u.dblu_dbl.dbl_exp;
+
+       /*
+        * If input is zero, Inf or NaN, just return it.
+        */
+       if (u.dblu_d == 0.0 || oldexp == DBL_EXP_INFNAN)
+               return (val);
+
+       if (oldexp == 0) {
+               /*
+                * u.v is denormal.  We must adjust it so that the exponent
+                * arithmetic below will work.
+                */
+               if (expon <= DBL_EXP_BIAS) {
+                       /*
+                        * Optimization: if the scaling can be done in a single
+                        * multiply, or underflows, just do it now.
+                        */
+                       if (expon <= -DBL_FRACBITS) {
+                               errno = ERANGE;
+                               return (val < 0.0 ? -0.0 : 0.0);
+                       }
+                       mul.dblu_d = 0.0;
+                       mul.dblu_dbl.dbl_exp = expon + DBL_EXP_BIAS;
+                       u.dblu_d *= mul.dblu_d;
+                       if (u.dblu_d == 0.0) {
+                               errno = ERANGE;
+                               return (val < 0.0 ? -0.0 : 0.0);
+                       }
+                       return (u.dblu_d);
+               } else {
+                       /*
+                        * We know that expon is very large, and therefore the
+                        * result cannot be denormal (though it may be Inf).
+                        * Shift u.v by just enough to make it normal.
+                        */
+                       mul.dblu_d = 0.0;
+                       mul.dblu_dbl.dbl_exp = DBL_FRACBITS + DBL_EXP_BIAS;
+                       u.dblu_d *= mul.dblu_d;
+                       expon -= DBL_FRACBITS;
+                       oldexp = u.dblu_dbl.dbl_exp;
+               }
+       }
+
+       /*
+        * u.v is now normalized and oldexp has been adjusted if necessary.
+        * Calculate the new exponent and check for underflow and overflow.
+        */
+       newexp = oldexp + expon;
+
+       if (newexp <= 0) {
+               /*
+                * The output number is either denormal or underflows (see
+                * comments in machine/ieee.h).
+                */
+               if (newexp <= -DBL_FRACBITS) {
+                       errno = ERANGE;
+                       return (val < 0.0 ? -0.0 : 0.0);
+               }
+               /*
+                * Denormalize the result.  We do this with a multiply.  If
+                * expon is very large, it won't fit in a double, so we have
+                * to adjust the exponent first.  This is safe because we know
+                * that u.v is normal at this point.
+                */
+               if (expon <= -DBL_EXP_BIAS) {
+                       u.dblu_dbl.dbl_exp = 1;
+                       expon += oldexp - 1;
+               }
+               mul.dblu_d = 0.0;
+               mul.dblu_dbl.dbl_exp = expon + DBL_EXP_BIAS;
+               u.dblu_d *= mul.dblu_d;
+               return (u.dblu_d);
+       } else if (newexp >= DBL_EXP_INFNAN) {
+               /*
+                * The result overflowed; return +/-Inf.
+                */
+               u.dblu_dbl.dbl_exp = DBL_EXP_INFNAN;
+               u.dblu_dbl.dbl_frach = 0;
+               u.dblu_dbl.dbl_fracl = 0;
+               errno = ERANGE;
+               return (u.dblu_d);
+       } else {
+               /*
+                * The result is normal; just replace the old exponent with the
+                * new one.
+                */
+               u.dblu_dbl.dbl_exp = newexp;
+               return (u.dblu_d);
+       }
+}
diff --git a/lib/nbsd_libc/gen/lockf.3 b/lib/nbsd_libc/gen/lockf.3
new file mode 100644 (file)
index 0000000..293b8ac
--- /dev/null
@@ -0,0 +1,253 @@
+.\" $NetBSD: lockf.3,v 1.10 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 1997 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein and S.P. Zeidler.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd December 19, 1997
+.Dt LOCKF 3
+.Os
+.Sh NAME
+.Nm lockf
+.Nd record locking on files
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn lockf "int filedes" "int function" "off_t size"
+.Sh DESCRIPTION
+The
+.Fn lockf
+function allows sections of a file to be locked with advisory-mode locks.
+Calls to
+.Fn lockf
+from other processes which attempt to lock the locked file section will
+either return an error value or block until the section becomes unlocked.
+All the locks for a process are removed when the process terminates.
+.Pp
+The argument
+.Fa filedes
+is an open file descriptor.
+The file descriptor must have been opened either for write-only
+.Dv ( O_WRONLY )
+or read/write
+.Dv ( O_RDWR )
+operation.
+.Pp
+The
+.Fa function
+argument is a control value which specifies the action to be taken.
+The permissible values for
+.Fa function
+are as follows:
+.Bl -tag -width F_ULOCKXX -compact -offset indent
+.It Sy Function
+.Sy Description
+.It Dv F_ULOCK
+unlock locked sections
+.It Dv F_LOCK
+lock a section for exclusive use
+.It Dv F_TLOCK
+test and lock a section for exclusive use
+.It Dv F_TEST
+test a section for locks by other processes
+.El
+.Pp
+.Dv F_ULOCK
+removes locks from a section of the file;
+.Dv F_LOCK
+and
+.Dv F_TLOCK
+both lock a section of a file if the section is available;
+.Dv F_TEST
+detects if a lock by another process is present on the specified section.
+.Pp
+The
+.Fa size
+argument is the number of contiguous bytes to be locked or
+unlocked.
+The section to be locked or unlocked starts at the current
+offset in the file and extends forward for a positive size or backward
+for a negative size (the preceding bytes up to but not including the
+current offset).
+However, it is not permitted to lock a section that
+starts or extends before the beginning of the file.
+If
+.Fa size
+is 0, the section from the current offset through the largest possible
+file offset is locked (that is, from the current offset through the
+present or any future end-of-file).
+.Pp
+The sections locked with
+.Dv F_LOCK
+or
+.Dv F_TLOCK
+may, in whole or in part, contain or be contained by a previously
+locked section for the same process.
+When this occurs, or if adjacent
+locked sections would occur, the sections are combined into a single
+locked section.
+If the request would cause the number of locks to
+exceed a system-imposed limit, the request will fail.
+.Pp
+.Dv F_LOCK
+and
+.Dv F_TLOCK
+requests differ only by the action taken if the section is not
+available.
+.Dv F_LOCK
+blocks the calling process until the section is available.
+.Dv F_TLOCK
+makes the function fail if the section is already locked by another
+process.
+.Pp
+File locks are released on first close by the locking process of any
+file descriptor for the file.
+.Pp
+.Dv F_ULOCK
+requests release (wholly or in part) one or more locked sections
+controlled by the process.
+Locked sections will be unlocked starting
+at the current file offset through
+.Fa size
+bytes or to the end of file if size is 0.
+When all of a locked section
+is not released (that is, when the beginning or end of the area to be
+unlocked falls within a locked section), the remaining portions of
+that section are still locked by the process.
+Releasing the center
+portion of a locked section will cause the remaining locked beginning
+and end portions to become two separate locked sections.
+If the
+request would cause the number of locks in the system to exceed a
+system-imposed limit, the request will fail.
+.Pp
+An
+.Dv F_ULOCK
+request in which size is non-zero and the offset of the last byte of
+the requested section is the maximum value for an object of type
+off_t, when the process has an existing lock in which size is 0 and
+which includes the last byte of the requested section, will be treated
+as a request to unlock from the start of the requested section with a
+size equal to 0.
+Otherwise an
+.Dv F_ULOCK
+request will attempt to unlock only the requested section.
+.Pp
+A potential for deadlock occurs if a process controlling a locked
+region is put to sleep by attempting to lock the locked region of
+another process.
+This implementation detects that sleeping until a
+locked region is unlocked would cause a deadlock and fails with an
+.Er EDEADLK
+error.
+.Pp
+.Fn lockf ,
+.Xr fcntl 2
+and
+.Xr flock 2
+locks may be safely used concurrently.
+.Pp
+Blocking on a section is interrupted by any signal.
+.Sh RETURN VALUES
+If successful, the
+.Fn lockf
+function returns 0.
+Otherwise, it returns \-1, sets
+.Va errno
+to indicate an error, and existing locks are not changed.
+.Sh ERRORS
+.Fn lockf
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EAGAIN
+The argument
+.Fa function
+is
+.Dv F_TLOCK
+or
+.Dv F_TEST
+and the section is already locked by another process.
+.It Bq Er EBADF
+The argument
+.Fa filedes
+is not a valid open file descriptor.
+.Pp
+The argument
+.Fa function
+is
+.Dv F_LOCK
+or
+.Dv F_TLOCK ,
+and
+.Fa filedes
+is not a valid file descriptor open for writing.
+.It Bq Er EDEADLK
+The argument
+.Fa function
+is
+.Dv F_LOCK
+and a deadlock is detected.
+.It Bq Er EINTR
+The argument
+.Fa function
+is F_LOCK
+and
+.Fn lockf
+was interrupted by the delivery of a signal.
+.It Bq Er EINVAL
+The argument
+.Fa function
+is not one of
+.Dv F_ULOCK ,
+.Dv F_LOCK ,
+.Dv F_TLOCK
+or
+.Dv F_TEST .
+.Pp
+The argument
+.Fa filedes
+refers to a file that does not support locking.
+.It Bq Er ENOLCK
+The argument
+.Fa function
+is
+.Dv F_ULOCK ,
+.Dv F_LOCK
+or
+.Dv F_TLOCK ,
+and satisfying the lock or unlock request would result in the number
+of locked regions in the system exceeding a system-imposed limit.
+.El
+.Sh SEE ALSO
+.Xr fcntl 2 ,
+.Xr flock 2
+.Sh STANDARDS
+The
+.Fn lockf
+function conforms to
+.St -xpg4.2 .
diff --git a/lib/nbsd_libc/gen/lockf.c b/lib/nbsd_libc/gen/lockf.c
new file mode 100644 (file)
index 0000000..c892e9f
--- /dev/null
@@ -0,0 +1,89 @@
+/*     $NetBSD: lockf.c,v 1.3 2008/04/28 20:22:59 martin Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: lockf.c,v 1.3 2008/04/28 20:22:59 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(lockf,_lockf)
+#endif
+
+
+int
+lockf(filedes, function, size)
+       int filedes;
+       int function;
+       off_t size;
+{
+       struct flock fl;
+       int cmd;
+
+       fl.l_start = 0;
+       fl.l_len = size;
+       fl.l_whence = SEEK_CUR;
+
+       switch (function) {
+       case F_ULOCK:
+               cmd = F_SETLK;
+               fl.l_type = F_UNLCK;
+               break;
+       case F_LOCK:
+               cmd = F_SETLKW;
+               fl.l_type = F_WRLCK;
+               break;
+       case F_TLOCK:
+               cmd = F_SETLK;
+               fl.l_type = F_WRLCK;
+               break;
+       case F_TEST:
+               fl.l_type = F_WRLCK;
+               if (fcntl(filedes, F_GETLK, &fl) == -1)
+                       return (-1);
+               if (fl.l_type == F_UNLCK || fl.l_pid == getpid())
+                       return (0);
+               errno = EAGAIN;
+               return (-1);
+               /* NOTREACHED */
+       default:
+               errno = EINVAL;
+               return (-1);
+               /* NOTREACHED */
+       }
+
+       return (fcntl(filedes, cmd, &fl));
+}
diff --git a/lib/nbsd_libc/gen/makecontext.3 b/lib/nbsd_libc/gen/makecontext.3
new file mode 100644 (file)
index 0000000..00b798c
--- /dev/null
@@ -0,0 +1,175 @@
+.\"    $NetBSD: makecontext.3,v 1.9 2010/04/29 06:07:35 jruoho Exp $
+.\"
+.\" Copyright (c) 2001, 2009 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 29, 2010
+.Dt MAKECONTEXT 3
+.Os
+.Sh NAME
+.Nm makecontext ,
+.Nm swapcontext
+.Nd manipulate user contexts
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ucontext.h
+.Ft void
+.Fn makecontext "ucontext_t *ucp" "void (*func)()" "int argc" ...
+.Ft int
+.Fn swapcontext "ucontext_t * restrict oucp" "ucontext_t * restrict ucp"
+.Sh DESCRIPTION
+The
+.Fn makecontext
+function modifies the object pointed to by
+.Fa ucp ,
+which has been initialized using
+.Xr getcontext 2 .
+When this context is resumed using
+.Fn swapcontext
+or
+.Xr setcontext 2 ,
+program execution continues as if
+.Fa func
+had been called with the arguments specified after
+.Fa argc
+in the call of
+.Fn makecontext .
+The value of
+.Fa argc
+must be equal to the number of integer arguments following it,
+and must be equal to the number of integer arguments expected by
+.Fa func ;
+otherwise, the behavior is undefined.
+.Pp
+Before being modified using
+.Fn makecontext ,
+a stack must be allocated for the context (in the
+.Fa uc_stack
+member), and a context to resume after
+.Fa func
+has returned must be determined (pointed to by the
+.Fa uc_link
+member);
+otherwise, the behavior is undefined.
+If
+.Fa uc_link
+is a null pointer, then the context is the main context,
+and the process will exit with an exit status of 0 upon return.
+.Pp
+The
+.Fn swapcontext
+function saves the current context in the object pointed to by
+.Fa oucp ,
+sets the current context to that specified in the object pointed to by
+.Fa ucp ,
+and resumes execution.
+When a context saved by
+.Fn swapcontext
+is restored using
+.Xr setcontext 2 ,
+execution will resume as if the corresponding invocation of
+.Fn swapcontext
+had just returned (successfully).
+.Sh RETURN VALUES
+The
+.Fn makecontext
+function returns no value.
+.Pp
+On success,
+.Fn swapcontext
+returns a value of 0,
+Otherwise, \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn swapcontext
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+The
+.Fa oucp
+argument or the
+.Fa ucp
+argument points to an invalid address.
+.It Bq Er EINVAL
+The contents of the datum pointed to by
+.Fa ucp
+are invalid.
+.El
+.Sh SEE ALSO
+.Xr _exit 2 ,
+.Xr getcontext 2 ,
+.Xr setcontext 2 ,
+.Xr ucontext 2
+.Sh STANDARDS
+The
+.Fn makecontext
+and
+.Fn swapcontext
+functions conform to
+.St -xsh5
+and
+.St -p1003.1-2001 .
+.Pp
+The
+.St -p1003.1-2004
+revision marked the functions
+.Fn makecontext
+and
+.Fn swapcontext
+as obsolete, citing portability issues and recommending the use of
+.Tn POSIX
+threads instead.
+The
+.St -p1003.1-2008
+revision removed the functions from the specification.
+.Pp
+.Bf -symbolic
+The standard does not clearly define the type of integer arguments
+passed to
+.Fa func
+via
+.Fn makecontext ;
+portable applications should not rely on the implementation detail that
+it may be possible to pass pointer arguments to functions.
+.Ef
+This may be clarified in a future revision of the standard.
+.Sh HISTORY
+The
+.Fn makecontext
+and
+.Fn swapcontext
+functions first appeared in
+.At V.4 .
+.Sh CAVEATS
+Due to limitations in the current pthread implementation,
+.Nm
+should not be used in programs which link against the
+.Xr pthread 3
+library (whether threads are used or not).
diff --git a/lib/nbsd_libc/gen/modf_ieee754.c b/lib/nbsd_libc/gen/modf_ieee754.c
new file mode 100644 (file)
index 0000000..2132036
--- /dev/null
@@ -0,0 +1,102 @@
+/* $NetBSD: modf_ieee754.c,v 1.3 2010/01/27 14:10:41 drochner Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Carnegie-Mellon University.
+ * All rights reserved.
+ *
+ * Author: Chris G. Demetriou
+ * 
+ * Permission to use, copy, modify and distribute this software and
+ * its documentation is hereby granted, provided that both the copyright
+ * notice and this permission notice appear in all copies of the
+ * software, derivative works or modified versions, and any portions
+ * thereof, and that both notices appear in supporting documentation.
+ * 
+ * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 
+ * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 
+ * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
+ * 
+ * Carnegie Mellon requests users of this software to return to
+ *
+ *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
+ *  School of Computer Science
+ *  Carnegie Mellon University
+ *  Pittsburgh PA 15213-3890
+ *
+ * any improvements or extensions that they make and grant Carnegie the
+ * rights to redistribute these changes.
+ */
+
+#include <sys/types.h>
+#include <machine/ieee.h>
+#include <errno.h>
+#include <math.h>
+
+/*
+ * double modf(double val, double *iptr)
+ * returns: f and i such that |f| < 1.0, (f + i) = val, and
+ *     sign(f) == sign(i) == sign(val).
+ *
+ * Beware signedness when doing subtraction, and also operand size!
+ */
+double
+modf(double val, double *iptr)
+{
+       union ieee_double_u u, v;
+       u_int64_t frac;
+
+       /*
+        * If input is +/-Inf or NaN, return +/-0 or NaN.
+        */
+       u.dblu_d = val;
+       if (u.dblu_dbl.dbl_exp == DBL_EXP_INFNAN) {
+               *iptr = u.dblu_d;
+               return (0.0 / u.dblu_d);
+       }
+
+       /*
+        * If input can't have a fractional part, return
+        * (appropriately signed) zero, and make i be the input.
+        */
+       if ((int)u.dblu_dbl.dbl_exp - DBL_EXP_BIAS > DBL_FRACBITS - 1) {
+               *iptr = u.dblu_d;
+               v.dblu_d = 0.0;
+               v.dblu_dbl.dbl_sign = u.dblu_dbl.dbl_sign;
+               return (v.dblu_d);
+       }
+
+       /*
+        * If |input| < 1.0, return it, and set i to the appropriately
+        * signed zero.
+        */
+       if (u.dblu_dbl.dbl_exp < DBL_EXP_BIAS) {
+               v.dblu_d = 0.0;
+               v.dblu_dbl.dbl_sign = u.dblu_dbl.dbl_sign;
+               *iptr = v.dblu_d;
+               return (u.dblu_d);
+       }
+
+       /*
+        * There can be a fractional part of the input.
+        * If you look at the math involved for a few seconds, it's
+        * plain to see that the integral part is the input, with the
+        * low (DBL_FRACBITS - (exponent - DBL_EXP_BIAS)) bits zeroed,
+        * the fractional part is the part with the rest of the
+        * bits zeroed.  Just zeroing the high bits to get the
+        * fractional part would yield a fraction in need of
+        * normalization.  Therefore, we take the easy way out, and
+        * just use subtraction to get the fractional part.
+        */
+       v.dblu_d = u.dblu_d;
+       /* Zero the low bits of the fraction, the sleazy way. */
+       frac = ((u_int64_t)v.dblu_dbl.dbl_frach << 32) + v.dblu_dbl.dbl_fracl;
+       frac >>= DBL_FRACBITS - (u.dblu_dbl.dbl_exp - DBL_EXP_BIAS);
+       frac <<= DBL_FRACBITS - (u.dblu_dbl.dbl_exp - DBL_EXP_BIAS);
+       v.dblu_dbl.dbl_fracl = frac & 0xffffffff;
+       v.dblu_dbl.dbl_frach = frac >> 32;
+       *iptr = v.dblu_d;
+
+       u.dblu_d -= v.dblu_d;
+       u.dblu_dbl.dbl_sign = v.dblu_dbl.dbl_sign;
+       return (u.dblu_d);
+}
diff --git a/lib/nbsd_libc/gen/nftw.c b/lib/nbsd_libc/gen/nftw.c
new file mode 100644 (file)
index 0000000..0e51342
--- /dev/null
@@ -0,0 +1,114 @@
+/* $NetBSD */
+
+/*     From OpenBSD: nftw.c,v 1.2 2003/07/21 21:15:32 millert Exp      */
+
+/*
+ * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
+ *
+ * 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.
+ *
+ * Sponsored in part by the Defense Advanced Research Projects
+ * Agency (DARPA) and Air Force Research Laboratory, Air Force
+ * Materiel Command, USAF, under agreement number F39502-99-1-0512.
+ */
+
+#include <sys/cdefs.h>
+
+#ifndef lint
+__RCSID("$NetBSD: nftw.c,v 1.1 2005/12/30 23:07:32 agc Exp $");
+#endif
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <fts.h>
+#include <ftw.h>
+#include <limits.h>
+
+int
+nftw(const char *path, int (*fn)(const char *, const struct stat *, int,
+     struct FTW *), int nfds, int ftwflags)
+{
+       /* LINTED */
+       char * const paths[2] = { __UNCONST(path), NULL };
+       struct FTW f;
+       FTSENT *cur;
+       FTS *ftsp;
+       int ftsflags, fnflag, error, postorder, sverrno;
+
+       /* XXX - nfds is currently unused */
+       if (nfds < 1 || nfds > OPEN_MAX) {
+               errno = EINVAL;
+               return (-1);
+       }
+
+       ftsflags = FTS_COMFOLLOW;
+       if (!(ftwflags & FTW_CHDIR))
+               ftsflags |= FTS_NOCHDIR;
+       if (ftwflags & FTW_MOUNT)
+               ftsflags |= FTS_XDEV;
+       if (ftwflags & FTW_PHYS)
+               ftsflags |= FTS_PHYSICAL;
+       postorder = (ftwflags & FTW_DEPTH) != 0;
+       ftsp = fts_open(paths, ftsflags, NULL);
+       if (ftsp == NULL)
+               return (-1);
+       error = 0;
+       while ((cur = fts_read(ftsp)) != NULL) {
+               switch (cur->fts_info) {
+               case FTS_D:
+                       if (postorder)
+                               continue;
+                       fnflag = FTW_D;
+                       break;
+               case FTS_DNR:
+                       fnflag = FTW_DNR;
+                       break;
+               case FTS_DP:
+                       if (!postorder)
+                               continue;
+                       fnflag = FTW_DP;
+                       break;
+               case FTS_F:
+               case FTS_DEFAULT:
+                       fnflag = FTW_F;
+                       break;
+               case FTS_NS:
+               case FTS_NSOK:
+                       fnflag = FTW_NS;
+                       break;
+               case FTS_SL:
+                       fnflag = FTW_SL;
+                       break;
+               case FTS_SLNONE:
+                       fnflag = FTW_SLN;
+                       break;
+               case FTS_DC:
+                       errno = ELOOP;
+                       /* FALLTHROUGH */
+               default:
+                       error = -1;
+                       goto done;
+               }
+               f.base = cur->fts_pathlen - cur->fts_namelen;
+               f.level = cur->fts_level;
+               error = fn(cur->fts_path, cur->fts_statp, fnflag, &f);
+               if (error != 0)
+                       break;
+       }
+done:
+       sverrno = errno;
+       (void) fts_close(ftsp);
+       errno = sverrno;
+       return (error);
+}
diff --git a/lib/nbsd_libc/gen/nice.3 b/lib/nbsd_libc/gen/nice.3
new file mode 100644 (file)
index 0000000..e59f123
--- /dev/null
@@ -0,0 +1,93 @@
+.\"    $NetBSD: nice.3,v 1.13 2003/08/07 16:42:53 agc Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)nice.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd February 16, 1998
+.Dt NICE 3
+.Os
+.Sh NAME
+.Nm nice
+.Nd set program scheduling priority
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn nice "int incr"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is obsoleted by
+.Xr setpriority 2 .
+.Ef
+.Pp
+The
+.Fn nice
+function obtains the scheduling priority of the process
+from the system and sets it to the priority value specified in
+.Fa incr .
+The priority is a value in the range -20 to 20.
+The default priority is 0; lower priorities cause more favorable scheduling.
+Only the super-user may lower priorities.
+.Pp
+Children inherit the priority of their parent processes via
+.Xr fork 2 .
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn nice
+returns the new nice value minus
+.Dv NZERO .
+Otherwise, \-1 is returned, the process' nice value is not changed, and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn nice
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EPERM
+The
+.Fa incr
+argument is negative and the caller is not the super-user.
+.El
+.Sh SEE ALSO
+.Xr nice 1 ,
+.Xr fork 2 ,
+.Xr setpriority 2 ,
+.Xr renice 8
+.Sh STANDARDS
+The
+.Fn nice
+function conforms to
+.St -xpg4.2 .
+.Sh HISTORY
+A
+.Fn nice
+syscall appeared in
+.At v6 .
diff --git a/lib/nbsd_libc/gen/nice.c b/lib/nbsd_libc/gen/nice.c
new file mode 100644 (file)
index 0000000..9076531
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: nice.c,v 1.12 2003/08/07 16:42:53 agc Exp $    */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)nice.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: nice.c,v 1.12 2003/08/07 16:42:53 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+#include <errno.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(nice,_nice)
+#endif
+
+/*
+ * Backwards compatible nice.
+ */
+int
+nice(incr)
+       int incr;
+{
+       int prio;
+
+       errno = 0;
+       prio = getpriority(PRIO_PROCESS, 0);
+       if (prio == -1 && errno)
+               return (-1);
+       if (setpriority(PRIO_PROCESS, 0, prio + incr) != 0)
+               return (-1);
+       return (getpriority(PRIO_PROCESS, 0));
+}
diff --git a/lib/nbsd_libc/gen/nlist.3 b/lib/nbsd_libc/gen/nlist.3
new file mode 100644 (file)
index 0000000..2a9f991
--- /dev/null
@@ -0,0 +1,79 @@
+.\"    $NetBSD: nlist.3,v 1.11 2003/08/07 16:42:53 agc Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)nlist.3    8.3 (Berkeley) 4/19/94
+.\"
+.Dd April 19, 1994
+.Dt NLIST 3
+.Os
+.Sh NAME
+.Nm nlist
+.Nd retrieve symbol table name list from an executable file
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In nlist.h
+.Ft int
+.Fn nlist "const char *filename" "struct nlist *nl"
+.Sh DESCRIPTION
+The
+.Fn nlist
+function
+retrieves name list entries from the symbol table of an
+executable file.
+(See
+.Xr a.out 5 . )
+The argument
+.Fa \&nl
+is set to reference the
+beginning of the list.
+The list is preened of binary and invalid data;
+if an entry in the
+name list is valid, the
+.Fa n_type
+and
+.Fa n_value
+for the entry are copied into the list
+referenced by
+.Fa \&nl .
+No other data is copied.
+The last entry in the list is always
+.Dv NULL .
+.Sh RETURN VALUES
+The number of invalid entries is returned if successful; otherwise,
+if the file
+.Fa filename
+does not exist or is not executable, the returned value is \-1.
+.Sh SEE ALSO
+.Xr a.out 5
+.Sh HISTORY
+A
+.Fn nlist
+function appeared in
+.At v6 .
diff --git a/lib/nbsd_libc/gen/nlist.c b/lib/nbsd_libc/gen/nlist.c
new file mode 100644 (file)
index 0000000..5689be1
--- /dev/null
@@ -0,0 +1,147 @@
+/* $NetBSD: nlist.c,v 1.22 2009/08/20 08:30:04 he Exp $ */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+/*
+ * Copyright (c) 1996 Christopher G. Demetriou.  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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)nlist.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: nlist.c,v 1.22 2009/08/20 08:30:04 he Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/file.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <nlist.h>
+
+#if 0
+#ifdef __weak_alias
+__weak_alias(nlist,_nlist)
+#endif
+#endif
+
+#include "nlist_private.h"
+
+static const struct {
+       int     (*fdnlist) __P((int, struct nlist *));
+} fdnlist_fmts[] = {
+#ifdef NLIST_AOUT
+       {       __fdnlist_aout          },
+#endif
+#ifdef NLIST_COFF
+       {       __fdnlist_coff          },
+#endif
+#ifdef NLIST_ECOFF
+       {       __fdnlist_ecoff         },
+#endif
+#ifdef NLIST_ELF32
+       {       __fdnlist_elf32         },
+#endif
+#ifdef NLIST_ELF64
+       {       __fdnlist_elf64         },
+#endif
+};
+       
+int
+nlist(name, list)
+       const char *name;
+       struct nlist *list;
+{
+       int fd, n;
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(list != NULL);
+
+       fd = open(name, O_RDONLY, 0);
+       if (fd < 0)
+               return (-1);
+       n = __fdnlist(fd, list);
+       (void)close(fd);
+       return (n);
+}
+
+int
+__fdnlist(fd, list)
+       int fd;
+       struct nlist *list;
+{
+       size_t i;
+       int rv;
+
+       _DIAGASSERT(fd != -1);
+       _DIAGASSERT(list != NULL);
+
+       for (i = 0; i < sizeof(fdnlist_fmts) / sizeof(fdnlist_fmts[0]); i++)
+               if ((rv = (*fdnlist_fmts[i].fdnlist)(fd, list)) != -1)
+                       return (rv);
+       return (-1);
+}
diff --git a/lib/nbsd_libc/gen/nlist_aout.c b/lib/nbsd_libc/gen/nlist_aout.c
new file mode 100644 (file)
index 0000000..e51fd88
--- /dev/null
@@ -0,0 +1,195 @@
+/* $NetBSD: nlist_aout.c,v 1.22 2009/08/20 11:08:59 martin Exp $ */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+/*
+ * Copyright (c) 1996 Christopher G. Demetriou.  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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)nlist.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: nlist_aout.c,v 1.22 2009/08/20 11:08:59 martin Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/file.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <stdlib.h>
+
+struct nlist;
+#include "nlist_private.h"
+
+#ifdef NLIST_AOUT
+#include <a.out.h>
+#include <sys/exec_aout.h>
+
+int
+__fdnlist_aout(fd, list)
+       int fd;
+       struct nlist *list;
+{
+       struct nlist *p, *s;
+       char *strtab;
+       off_t stroff, symoff;
+       int nent;
+       size_t strsize, symsize, cc;
+       struct nlist nbuf[1024];
+       struct exec exec;
+       struct stat st;
+       char *scoreboard, *scored;
+
+       _DIAGASSERT(fd != -1);
+       _DIAGASSERT(list != NULL);
+
+       if (pread(fd, &exec, sizeof(exec), (off_t)0) != sizeof(exec) ||
+           N_BADMAG(exec) || fstat(fd, &st) < 0)
+               return (-1);
+
+       symoff = N_SYMOFF(exec);
+       symsize = (size_t)exec.a_syms;
+       stroff = symoff + symsize;
+
+       /* Check for files too large to mmap. */
+       if ((uintmax_t)(st.st_size - stroff) > (uintmax_t)SIZE_T_MAX) {
+               errno = EFBIG;
+               return (-1);
+       }
+       /*
+        * Map string table into our address space.  This gives us
+        * an easy way to randomly access all the strings, without
+        * making the memory allocation permanent as with malloc/free
+        * (i.e., munmap will return it to the system).
+        */
+       strsize = (size_t)(st.st_size - stroff);
+       strtab = mmap(NULL, strsize, PROT_READ, MAP_PRIVATE|MAP_FILE,
+           fd, stroff);
+       if (strtab == (char *)-1)
+               return (-1);
+       /*
+        * clean out any left-over information for all valid entries.
+        * Type and value defined to be 0 if not found; historical
+        * versions cleared other and desc as well.  Also figure out
+        * the largest string length so don't read any more of the
+        * string table than we have to.
+        *
+        * XXX clearing anything other than n_type and n_value violates
+        * the semantics given in the man page.
+        */
+       nent = 0;
+       for (p = list; !ISLAST(p); ++p) {
+               p->n_type = 0;
+               p->n_other = 0;
+               p->n_desc = 0;
+               p->n_value = 0;
+               ++nent;
+       }
+       if (lseek(fd, symoff, SEEK_SET) == -1)
+               return (-1);
+#if defined(__SSP__) || defined(__SSP_ALL__)
+       scoreboard = malloc((size_t)nent);
+#else
+       scoreboard = alloca((size_t)nent);
+#endif
+       if (scoreboard == NULL)
+               return (-1);
+       (void)memset(scoreboard, 0, (size_t)nent);
+
+       while (symsize > 0) {
+               cc = MIN(symsize, sizeof(nbuf));
+               if (read(fd, nbuf, cc) != (ssize_t) cc)
+                       break;
+               symsize -= cc;
+               for (s = nbuf; cc > 0; ++s, cc -= sizeof(*s)) {
+                       long soff = s->n_un.n_strx;
+
+                       if (soff == 0 || (s->n_type & N_STAB) != 0)
+                               continue;
+                       for (p = list, scored = scoreboard; !ISLAST(p);
+                           p++, scored++)
+                               if (*scored == 0 &&
+                                   !strcmp(&strtab[(size_t)soff],
+                                   p->n_un.n_name)) {
+                                       p->n_value = s->n_value;
+                                       p->n_type = s->n_type;
+                                       p->n_desc = s->n_desc;
+                                       p->n_other = s->n_other;
+                                       *scored = 1;
+                                       if (--nent <= 0)
+                                               break;
+                               }
+               }
+       }
+       munmap(strtab, strsize);
+#if defined(__SSP__) || defined(__SSP_ALL__)
+       free(scoreboard);
+#endif
+       return (nent);
+}
+#endif /* NLIST_AOUT */
diff --git a/lib/nbsd_libc/gen/nlist_coff.c b/lib/nbsd_libc/gen/nlist_coff.c
new file mode 100644 (file)
index 0000000..1ef3475
--- /dev/null
@@ -0,0 +1,199 @@
+/* $NetBSD: nlist_coff.c,v 1.8 2009/08/21 08:42:02 he Exp $ */
+
+/*
+ * Copyright (c) 1996 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nlist_coff.c,v 1.8 2009/08/21 08:42:02 he Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/file.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <nlist.h>
+
+#include "nlist_private.h"
+#ifdef NLIST_COFF
+#include <sys/exec_coff.h>
+#endif
+
+#ifdef NLIST_COFF
+#define        BAD             do { rv = -1; goto out; } while (/*CONSTCOND*/0)
+#define        BADUNMAP        do { rv = -1; goto unmap; } while (/*CONSTCOND*/0)
+
+#define ES_LEN 18
+struct coff_extsym {
+       union {
+               char u_name[8];
+               struct {
+                       int u_zero;
+                       int u_offset;
+               } s;
+       } u;
+       int32_t es_value;
+       int16_t es_scnum;
+       int16_t es_type;
+       int8_t es_class;
+       int8_t es_numaux;
+};
+#define es_name u.u_name
+#define es_zero u.s.u_zero
+#define es_offset u.s.u_offset
+
+int
+__fdnlist_coff(fd, list)
+       int fd;
+       struct nlist *list;
+{
+       struct nlist *p;
+       struct coff_filehdr *filehdrp;
+       struct stat st;
+       char *mappedfile;
+       size_t mappedsize;
+       u_long symoff, extstroff;
+       int rv, nent;
+       long i, nesyms;
+
+       _DIAGASSERT(fd != -1);
+       _DIAGASSERT(list != NULL);
+
+       rv = -1;
+
+       /*
+        * If we can't fstat() the file, something bad is going on.
+        */
+       if (fstat(fd, &st) < 0)
+               BAD;
+
+       /*
+        * Map the file in its entirety.
+        */
+       if ((uintmax_t)st.st_size > (uintmax_t)SIZE_T_MAX) {
+               errno = EFBIG;
+               BAD;
+       }
+       mappedsize = st.st_size;
+       mappedfile = mmap(NULL, mappedsize, PROT_READ, MAP_PRIVATE|MAP_FILE,
+           fd, 0);
+       if (mappedfile == (char *)-1)
+               BAD;
+
+       /*
+        * Make sure we can access the executable's header
+        * directly, and make sure we recognize the executable
+        * as an COFF binary.
+        */
+       if (mappedsize < sizeof (struct coff_filehdr))
+               BADUNMAP;
+       filehdrp = (struct coff_filehdr *)&mappedfile[0];
+
+       if (COFF_BADMAG(filehdrp))
+               BADUNMAP;
+
+       /*
+        * Find the symbol list.
+        */
+       symoff = filehdrp->f_symptr;
+       nesyms = filehdrp->f_nsyms;
+
+       if (symoff + ES_LEN * nesyms > mappedsize)
+               BADUNMAP;
+       extstroff = symoff + ES_LEN * nesyms;
+
+       nent = 0;
+       for (p = list; !ISLAST(p); ++p) {
+               p->n_type = 0;
+               p->n_other = 0;
+               p->n_desc = 0;
+               p->n_value = 0;
+               ++nent;
+       }
+
+       for (i = 0; i < nesyms; i++) {
+               char *symtabname;
+               const char *nlistname;
+               struct coff_extsym esym;
+               char name[10];
+
+               memcpy(&esym, &mappedfile[symoff + ES_LEN * i], ES_LEN);
+               if (esym.es_numaux != 0) {
+                       i += esym.es_numaux;    /* XXX Skip aux entry */
+                       continue;
+               }
+                       
+               if (esym.es_zero != 0) {
+                       memcpy(name, esym.es_name, 8);
+                       name[8] = 0;
+                       symtabname = name;
+               } else if (esym.es_offset != 0)
+                       symtabname = &mappedfile[extstroff + esym.es_offset];
+               else
+                       continue;
+
+               for (p = list; !ISLAST(p); p++) {
+                       nlistname = N_NAME(p);
+                       if (!strcmp(symtabname, nlistname)) {
+                               /*
+                                * Translate (roughly) from COFF to nlist
+                                */
+                               p->n_value = esym.es_value;
+                               p->n_type = N_EXT;              /* XXX */
+                               p->n_desc = 0;                  /* XXX */
+                               p->n_other = 0;                 /* XXX */
+
+                               if (--nent <= 0)
+                                       goto done;
+                               break;  /* into next run of outer loop */
+                       }
+               }
+       }
+
+done:
+       rv = nent;
+unmap:
+       munmap(mappedfile, mappedsize);
+out:
+       return (rv);
+}
+
+#endif /* NLIST_COFF */
diff --git a/lib/nbsd_libc/gen/nlist_ecoff.c b/lib/nbsd_libc/gen/nlist_ecoff.c
new file mode 100644 (file)
index 0000000..8555590
--- /dev/null
@@ -0,0 +1,189 @@
+/* $NetBSD: nlist_ecoff.c,v 1.18 2009/08/21 08:42:02 he Exp $ */
+
+/*
+ * Copyright (c) 1996 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nlist_ecoff.c,v 1.18 2009/08/21 08:42:02 he Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/file.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <nlist.h>
+
+#include "nlist_private.h"
+#ifdef NLIST_ECOFF
+#include <sys/exec_ecoff.h>
+#endif
+
+#ifdef NLIST_ECOFF
+#define        check(off, size)        ((off < 0) || (off + size > mappedsize))
+#define        BAD                     do { rv = -1; goto out; } while (/*CONSTCOND*/0)
+#define        BADUNMAP                do { rv = -1; goto unmap; } while (/*CONSTCOND*/0)
+
+int
+__fdnlist_ecoff(fd, list)
+       int fd;
+       struct nlist *list;
+{
+       struct nlist *p;
+       struct ecoff_exechdr *exechdrp;
+       struct ecoff_symhdr *symhdrp;
+       struct ecoff_extsym *esyms;
+       struct stat st;
+       char *mappedfile;
+       size_t mappedsize;
+       u_long symhdroff, extstroff;
+       u_int symhdrsize;
+       int rv, nent;
+       long i, nesyms;
+
+       _DIAGASSERT(fd != -1);
+       _DIAGASSERT(list != NULL);
+
+       rv = -1;
+
+       /*
+        * If we can't fstat() the file, something bad is going on.
+        */
+       if (fstat(fd, &st) < 0)
+               BAD;
+
+       /*
+        * Map the file in its entirety.
+        */
+       if ((uintmax_t)st.st_size > (uintmax_t)SIZE_T_MAX) {
+               errno = EFBIG;
+               BAD;
+       }
+       mappedsize = st.st_size;
+       mappedfile = mmap(NULL, mappedsize, PROT_READ, MAP_PRIVATE|MAP_FILE,
+           fd, 0);
+       if (mappedfile == (char *)-1)
+               BAD;
+
+       /*
+        * Make sure we can access the executable's header
+        * directly, and make sure the recognize the executable
+        * as an ECOFF binary.
+        */
+       if (check(0, sizeof *exechdrp))
+               BADUNMAP;
+       exechdrp = (struct ecoff_exechdr *)&mappedfile[0];
+
+       if (ECOFF_BADMAG(exechdrp))
+               BADUNMAP;
+
+       /*
+        * Find the symbol list.
+        */
+       symhdroff = exechdrp->f.f_symptr;
+       symhdrsize = exechdrp->f.f_nsyms;
+
+       if ((symhdroff + sizeof *symhdrp) > mappedsize ||
+           sizeof *symhdrp != symhdrsize)
+               BADUNMAP;
+       symhdrp = (struct ecoff_symhdr *)&mappedfile[symhdroff];
+
+       nesyms = symhdrp->esymMax;
+       if (check(symhdrp->cbExtOffset, nesyms * sizeof *esyms))
+               BADUNMAP;
+       esyms = (struct ecoff_extsym *)&mappedfile[symhdrp->cbExtOffset];
+       extstroff = symhdrp->cbSsExtOffset;
+
+       /*
+        * Clean out any left-over information for all valid entries.
+        * Type and value are defined to be 0 if not found; historical
+        * versions cleared other and desc as well.
+        *
+        * XXX Clearing anything other than n_type and n_value violates
+        * the semantics given in the man page.
+        */
+       nent = 0;
+       for (p = list; !ISLAST(p); ++p) {
+               p->n_type = 0;
+               p->n_other = 0;
+               p->n_desc = 0;
+               p->n_value = 0;
+               ++nent;
+       }
+
+       for (i = 0; i < nesyms; i++) {
+               for (p = list; !ISLAST(p); p++) {
+                       const char *nlistname;
+                       char *symtabname;
+
+                       /* This may be incorrect */
+                       nlistname = N_NAME(p);
+                       if (*nlistname == '_')
+                               nlistname++;
+
+                       symtabname =
+                           &mappedfile[extstroff + esyms[i].es_strindex];
+
+                       if (!strcmp(symtabname, nlistname)) {
+                               /*
+                                * Translate (roughly) from ECOFF to nlist
+                                */
+                               p->n_value = esyms[i].es_value;
+                               p->n_type = N_EXT;              /* XXX */
+                               p->n_desc = 0;                  /* XXX */
+                               p->n_other = 0;                 /* XXX */
+
+                               if (--nent <= 0)
+                                       goto done;
+                               break;  /* into next run of outer loop */
+                       }
+               }
+       }
+
+done:
+       rv = nent;
+unmap:
+       munmap(mappedfile, mappedsize);
+out:
+       return (rv);
+}
+
+#endif /* NLIST_ECOFF */
diff --git a/lib/nbsd_libc/gen/nlist_elf32.c b/lib/nbsd_libc/gen/nlist_elf32.c
new file mode 100644 (file)
index 0000000..7658f31
--- /dev/null
@@ -0,0 +1,309 @@
+/* $NetBSD: nlist_elf32.c,v 1.32 2010/08/28 21:30:02 joerg Exp $ */
+
+/*
+ * Copyright (c) 1996 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nlist_elf32.c,v 1.32 2010/08/28 21:30:02 joerg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+/* If not included by nlist_elf64.c, ELFSIZE won't be defined. */
+#ifndef ELFSIZE
+#define        ELFSIZE         32
+#endif
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/file.h>
+#include <sys/ioctl.h>
+#include <sys/ksyms.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <nlist.h>
+
+#include "nlist_private.h"
+#if defined(NLIST_ELF32) || defined(NLIST_ELF64)
+#include <sys/exec_elf.h>
+#endif
+
+#if (defined(NLIST_ELF32) && (ELFSIZE == 32)) || \
+    (defined(NLIST_ELF64) && (ELFSIZE == 64))
+
+/* No need to check for off < 0 because it is unsigned */
+#define        check(off, size)        (off + size > mappedsize)
+#define        BAD                     goto out
+#define        BADUNMAP                goto unmap
+
+int
+ELFNAMEEND(__fdnlist)(fd, list)
+       int fd;
+       struct nlist *list;
+{
+       struct stat st;
+       struct nlist *p;
+       char *mappedfile, *strtab;
+       size_t mappedsize;
+       Elf_Ehdr *ehdrp, ehdr;
+       Elf_Shdr *shdrp, *symshdrp, *symstrshdrp;
+       Elf_Sym *symp;
+       Elf_Off shdr_off;
+       Elf_Word shdr_size;
+#if (ELFSIZE == 32)
+       Elf32_Half nshdr;
+#elif (ELFSIZE == 64)
+       Elf64_Word nshdr;
+#endif
+       size_t i, nsyms;
+       int rv, nent;
+
+       _DIAGASSERT(fd != -1);
+       _DIAGASSERT(list != NULL);
+
+       rv = -1;
+
+       symshdrp = symstrshdrp = NULL;
+
+       /*
+        * If we can't fstat() the file, something bad is going on.
+        */
+       if (fstat(fd, &st) < 0)
+               BAD;
+
+       /*
+        * Map the file in its entirety.
+        */
+       if ((uintmax_t)st.st_size > (uintmax_t)SIZE_T_MAX) {
+               errno = EFBIG;
+               BAD;
+       }
+
+       /*
+        * Read the elf header of the file.
+        */
+       if ((ssize_t)(i = pread(fd, &ehdr, sizeof(Elf_Ehdr), (off_t)0)) == -1)
+               BAD;
+
+       /*
+        * Check that the elf header is correct.
+        */
+       if (i != sizeof(Elf_Ehdr))
+               BAD;
+       if (memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0 ||
+           ehdr.e_ident[EI_CLASS] != ELFCLASS)
+               BAD;
+
+       switch (ehdr.e_machine) {
+       ELFDEFNNAME(MACHDEP_ID_CASES)
+
+       default:
+               BAD;
+       }
+
+       if (S_ISCHR(st.st_mode)) {
+               const char *nlistname;
+               struct ksyms_gsymbol kg;
+               Elf_Sym sym;
+
+               /*
+                * Character device; assume /dev/ksyms.
+                */
+               nent = 0;
+               for (p = list; !ISLAST(p); ++p) {
+
+                       p->n_other = 0;
+                       p->n_desc = 0;
+                       nlistname = N_NAME(p);
+                       if (*nlistname == '_')
+                               nlistname++;
+
+                       kg.kg_name = nlistname;
+                       kg.kg_sym = &sym;
+                       if (ioctl(fd, KIOCGSYMBOL, &kg) == 0) {
+                               p->n_value = sym.st_value;
+                               switch (ELF_ST_TYPE(sym.st_info)) {
+                               case STT_NOTYPE:
+                                       p->n_type = N_UNDF;
+                                       break;
+                               case STT_OBJECT:
+                                       p->n_type = N_DATA;
+                                       break;
+                               case STT_FUNC:
+                                       p->n_type = N_TEXT;
+                                       break;
+                               case STT_FILE:
+                                       p->n_type = N_FN;
+                                       break;
+                               default:
+                                       p->n_type = 0;
+                                       /* catch other enumerations for gcc */
+                                       break;
+                               }
+                               if (ELF_ST_BIND(sym.st_info) != STB_LOCAL)
+                                       p->n_type |= N_EXT;
+                       } else {
+                               nent++;
+                               p->n_value = 0;
+                               p->n_type = 0;
+                       }
+               }
+               return nent;
+       }
+
+       mappedsize = (size_t)st.st_size;
+       mappedfile = mmap(NULL, mappedsize, PROT_READ, MAP_PRIVATE|MAP_FILE,
+           fd, (off_t)0);
+       if (mappedfile == (char *)-1)
+               BAD;
+
+       /*
+        * Make sure we can access the executable's header
+        * directly, and make sure the recognize the executable
+        * as an ELF binary.
+        */
+       if (check(0, sizeof *ehdrp))
+               BADUNMAP;
+       ehdrp = (Elf_Ehdr *)(void *)&mappedfile[0];
+
+       /*
+        * Find the symbol list and string table.
+        */
+       nshdr = ehdrp->e_shnum;
+       shdr_off = ehdrp->e_shoff;
+       shdr_size = ehdrp->e_shentsize * nshdr;
+
+       if (check(shdr_off, shdr_size) ||
+           (sizeof *shdrp != ehdrp->e_shentsize))
+               BADUNMAP;
+       shdrp = (Elf_Shdr *)(void *)&mappedfile[shdr_off];
+
+       for (i = 0; i < nshdr; i++) {
+               if (shdrp[i].sh_type == SHT_SYMTAB) {
+                       symshdrp = &shdrp[i];
+                       symstrshdrp = &shdrp[shdrp[i].sh_link];
+               }
+       }
+
+       /* Make sure we're not stripped. */
+       if (symshdrp == NULL || symshdrp->sh_offset == 0)
+               BADUNMAP;
+
+       /* Make sure the symbols and strings are safely mapped. */
+       if (check(symshdrp->sh_offset, symshdrp->sh_size))
+               BADUNMAP;
+       if (check(symstrshdrp->sh_offset, symstrshdrp->sh_size))
+               BADUNMAP;
+
+       symp = (Elf_Sym *)(void *)&mappedfile[symshdrp->sh_offset];
+       nsyms = symshdrp->sh_size / sizeof(*symp);
+       strtab = &mappedfile[symstrshdrp->sh_offset];
+
+       /*
+        * Clean out any left-over information for all valid entries.
+        * Type and value are defined to be 0 if not found; historical
+        * versions cleared other and desc as well.
+        *
+        * XXX Clearing anything other than n_type and n_value violates
+        * the semantics given in the man page.
+        */
+       nent = 0;
+       for (p = list; !ISLAST(p); ++p) {
+               p->n_type = 0;
+               p->n_other = 0;
+               p->n_desc = 0;
+               p->n_value = 0;
+               ++nent;
+       }
+
+       for (i = 0; i < nsyms; i++) {
+               for (p = list; !ISLAST(p); ++p) {
+                       const char *nlistname;
+                       char *symtabname;
+
+                       /* This may be incorrect */
+                       nlistname = N_NAME(p);
+                       if (*nlistname == '_')
+                               nlistname++;
+
+                       symtabname = &strtab[symp[i].st_name];
+
+                       if (!strcmp(symtabname, nlistname)) {
+                               /*
+                                * Translate (roughly) from ELF to nlist
+                                */
+                               p->n_value = symp[i].st_value;
+                               switch (ELF_ST_TYPE(symp[i].st_info)) {
+                               case STT_NOTYPE:
+                                       p->n_type = N_UNDF;
+                                       break;
+                               case STT_OBJECT:
+                                       p->n_type = N_DATA;
+                                       break;
+                               case STT_FUNC:
+                                       p->n_type = N_TEXT;
+                                       break;
+                               case STT_FILE:
+                                       p->n_type = N_FN;
+                                       break;
+                               default:
+                                       /* catch other enumerations for gcc */
+                                       break;
+                               }
+                               if (ELF_ST_BIND(symp[i].st_info) != STB_LOCAL)
+                                       p->n_type |= N_EXT;
+                               p->n_desc = 0;                  /* XXX */
+                               p->n_other = 0;                 /* XXX */
+
+                               if (--nent <= 0)
+                                       goto done;
+                               break;  /* into next run of outer loop */
+                       }
+               }
+       }
+
+done:
+       rv = nent;
+unmap:
+       munmap(mappedfile, mappedsize);
+out:
+       return (rv);
+}
+
+#endif
diff --git a/lib/nbsd_libc/gen/nlist_elf64.c b/lib/nbsd_libc/gen/nlist_elf64.c
new file mode 100644 (file)
index 0000000..9f9cff2
--- /dev/null
@@ -0,0 +1,44 @@
+/* $NetBSD: nlist_elf64.c,v 1.6 2003/07/26 19:24:43 salo Exp $ */
+
+/*
+ * Copyright (c) 1996 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nlist_elf64.c,v 1.6 2003/07/26 19:24:43 salo Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define        ELFSIZE         64
+
+#include "nlist_elf32.c"
diff --git a/lib/nbsd_libc/gen/nlist_private.h b/lib/nbsd_libc/gen/nlist_private.h
new file mode 100644 (file)
index 0000000..485fc4d
--- /dev/null
@@ -0,0 +1,90 @@
+/* $NetBSD: nlist_private.h,v 1.21 2011/01/17 23:32:31 matt Exp $ */
+
+/*
+ * Copyright (c) 1996 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#if defined(__alpha__)
+#  define      NLIST_ECOFF
+#  define      NLIST_ELF64
+#elif defined(__x86_64__)
+#  define      NLIST_ELF64
+#  define      NLIST_ELF32
+#elif defined(__mips__)
+#  define      NLIST_ECOFF
+#  define      NLIST_ELF32
+#  ifndef __mips_o32
+#    define    NLIST_ELF64
+#  endif
+#elif defined(__arm__) || defined(__i386__) || defined (__m68k__) || \
+    defined(__powerpc__) || defined(__vax__)
+#  define      NLIST_AOUT
+#  define      NLIST_ELF32
+#elif defined(__sparc__)
+#  define      NLIST_AOUT
+#  define      NLIST_ELF32
+#  define      NLIST_ELF64
+#elif defined(__SH5__)
+#  define      NLIST_ELF32
+#  define      NLIST_ELF64
+#elif defined(__sh__)
+#  define      NLIST_COFF
+#  define      NLIST_ELF32
+#elif defined(__hppa__)
+#  define      NLIST_ELF32
+#else
+#  define      NLIST_AOUT
+/* #define     NLIST_ECOFF */
+/* #define     NLIST_ELF32 */
+/* #define     NLIST_ELF64 */
+#endif
+
+#define        ISLAST(p)       (N_NAME(p) == 0 || N_NAME(p)[0] == 0)
+
+struct nlist;
+
+#ifdef NLIST_AOUT
+int    __fdnlist_aout __P((int, struct nlist *));
+#endif
+#ifdef NLIST_COFF
+int    __fdnlist_coff __P((int, struct nlist *));
+#endif
+#ifdef NLIST_ECOFF
+int    __fdnlist_ecoff __P((int, struct nlist *));
+#endif
+#ifdef NLIST_ELF32
+int    __fdnlist_elf32 __P((int, struct nlist *));
+#endif
+#ifdef NLIST_ELF64
+int    __fdnlist_elf64 __P((int, struct nlist *));
+#endif
diff --git a/lib/nbsd_libc/gen/opendir.c b/lib/nbsd_libc/gen/opendir.c
new file mode 100644 (file)
index 0000000..7bb5997
--- /dev/null
@@ -0,0 +1,164 @@
+/*     $NetBSD: opendir.c,v 1.37 2010/09/26 02:26:59 yamt Exp $        */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)opendir.c  8.7 (Berkeley) 12/10/94";
+#else
+__RCSID("$NetBSD: opendir.c,v 1.37 2010/09/26 02:26:59 yamt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include "extern.h"
+
+#include <sys/param.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "dirent_private.h"
+
+static DIR     *__opendir_common(int, const char *, int);
+
+__weak_alias(fdopendir,_fdopendir)
+
+/*
+ * Open a directory.
+ */
+DIR *
+opendir(const char *name)
+{
+
+       _DIAGASSERT(name != NULL);
+
+       return (__opendir2(name, DTF_HIDEW|DTF_NODUP));
+}
+
+DIR *
+__opendir2(const char *name, int flags)
+{
+       int fd;
+
+       if ((fd = open(name, O_RDONLY | O_NONBLOCK)) == -1)
+               return NULL;
+       return __opendir_common(fd, name, flags);
+}
+
+#ifndef __LIBC12_SOURCE__
+DIR *
+_fdopendir(int fd)
+{
+
+       return __opendir_common(fd, NULL, DTF_HIDEW|DTF_NODUP);
+}
+#endif
+
+static DIR *
+__opendir_common(int fd, const char *name, int flags)
+{
+       DIR *dirp = NULL;
+       int serrno;
+       struct stat sb;
+       struct statvfs sfb;
+       int error;
+
+       if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
+               goto error;
+       if (fstat(fd, &sb) || !S_ISDIR(sb.st_mode)) {
+               errno = ENOTDIR;
+               goto error;
+       }
+       if ((dirp = (DIR *)malloc(sizeof(DIR))) == NULL)
+               goto error;
+       dirp->dd_buf = NULL;
+       dirp->dd_internal = NULL;
+#ifdef _REENTRANT
+       if (__isthreaded) {
+               if ((dirp->dd_lock = malloc(sizeof(mutex_t))) == NULL)
+                       goto error;
+               mutex_init((mutex_t *)dirp->dd_lock, NULL);
+       }
+#endif
+
+       /*
+        * Tweak flags for the underlying filesystem.
+        */
+
+       if (fstatvfs1(fd, &sfb, ST_NOWAIT) < 0)
+               goto error;
+       if ((flags & DTF_NODUP) != 0) {
+               if (!strncmp(sfb.f_fstypename, MOUNT_UNION,
+                   sizeof(sfb.f_fstypename)) ||
+                   (sfb.f_flag & MNT_UNION) != 0) {
+                       flags |= __DTF_READALL;
+               } else {
+                       flags &= ~DTF_NODUP;
+               }
+       }
+       if (!strncmp(sfb.f_fstypename, MOUNT_NFS, sizeof(sfb.f_fstypename))) {
+               flags |= __DTF_READALL | __DTF_RETRY_ON_BADCOOKIE;
+       }
+
+       dirp->dd_flags = flags;
+       error = _initdir(dirp, fd, name);
+       if (error) {
+               errno = error;
+               goto error;
+       }
+
+       return (dirp);
+error:
+       serrno = errno;
+       if (dirp != NULL) {
+#ifdef _REENTRANT
+               if (__isthreaded) {
+                       mutex_destroy((mutex_t *)dirp->dd_lock);
+                       free(dirp->dd_lock);
+               }
+#endif
+               free(dirp->dd_buf);
+       }
+       free(dirp);
+       if (fd != -1)
+               (void)close(fd);
+       errno = serrno;
+       return NULL;
+}
diff --git a/lib/nbsd_libc/gen/pause.3 b/lib/nbsd_libc/gen/pause.3
new file mode 100644 (file)
index 0000000..413ffbb
--- /dev/null
@@ -0,0 +1,92 @@
+.\"    $NetBSD: pause.3,v 1.15 2003/08/07 16:42:55 agc Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)pause.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt PAUSE 3
+.Os
+.Sh NAME
+.Nm pause
+.Nd stop until signal
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn pause void
+.Sh DESCRIPTION
+.Bf -symbolic
+Pause is made obsolete by
+.Xr sigsuspend 2 .
+.Ef
+.Pp
+The
+.Fn pause
+function
+forces a process to pause until
+a signal is received from either the
+.Xr kill 2
+function
+or an interval timer.
+(See
+.Xr setitimer 2 . )
+Upon termination of a signal handler started during a
+.Fn pause ,
+the
+.Fn pause
+call will return.
+.Sh RETURN VALUES
+Always returns \-1.
+.Sh ERRORS
+The
+.Fn pause
+function
+always returns:
+.Bl -tag -width Er
+.It Bq Er EINTR
+The call was interrupted.
+.El
+.Sh SEE ALSO
+.Xr kill 2 ,
+.Xr poll 2 ,
+.Xr select 2 ,
+.Xr setitimer 2 ,
+.Xr sigsuspend 2
+.Sh STANDARDS
+The
+.Fn pause
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+A
+.Fn pause
+syscall
+appeared in
+.At v6 .
diff --git a/lib/nbsd_libc/gen/pause.c b/lib/nbsd_libc/gen/pause.c
new file mode 100644 (file)
index 0000000..f11547a
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: pause.c,v 1.10 2003/08/07 16:42:55 agc Exp $   */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)pause.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: pause.c,v 1.10 2003/08/07 16:42:55 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <signal.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(pause,_pause)
+#endif
+
+/*
+ * Backwards compatible pause.
+ */
+int
+pause()
+{
+       sigset_t omask;
+
+       if (sigprocmask(SIG_BLOCK, NULL, &omask) == -1)
+               return -1;
+
+       return sigsuspend(&omask);
+}
diff --git a/lib/nbsd_libc/gen/popen.3 b/lib/nbsd_libc/gen/popen.3
new file mode 100644 (file)
index 0000000..d5cf7bb
--- /dev/null
@@ -0,0 +1,202 @@
+.\"    $NetBSD: popen.3,v 1.16 2007/08/02 23:45:10 wiz Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)popen.3    8.2 (Berkeley) 5/3/95
+.\"
+.Dd August 2, 2007
+.Dt POPEN 3
+.Os
+.Sh NAME
+.Nm popen ,
+.Nm pclose
+.Nd process
+.Tn I/O
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft FILE *
+.Fn popen "const char *command" "const char *type"
+.Ft int
+.Fn pclose "FILE *stream"
+.Sh DESCRIPTION
+The
+.Fn popen
+function
+.Dq opens
+a process by creating an IPC connection,
+forking,
+and invoking the shell.
+Historically,
+.Nm popen
+was implemented with a unidirectional pipe;
+hence many implementations of
+.Nm popen
+only allow the
+.Fa type
+argument to specify reading or writing, not both.
+Since
+.Nm popen
+is now implemented using sockets, the
+.Fa type
+may request a bidirectional data flow.
+The
+.Fa type
+argument is a pointer to a null-terminated string
+which must be
+.Ql r
+for reading,
+.Ql w
+for writing, or
+.Ql r+
+for reading and writing.
+.Pp
+The
+.Fa command
+argument is a pointer to a null-terminated string
+containing a shell command line.
+This command is passed to
+.Pa /bin/sh
+using the
+.Fl c
+flag; interpretation, if any, is performed by the shell.
+.Pp
+The return value from
+.Fn popen
+is a normal standard
+.Tn I/O
+stream in all respects
+save that it must be closed with
+.Fn pclose
+rather than
+.Fn fclose .
+Writing to such a stream
+writes to the standard input of the command;
+the command's standard output is the same as that of the process that called
+.Fn popen ,
+unless this is altered by the command itself.
+Conversely, reading from a
+.Dq popened
+stream reads the command's standard output, and
+the command's standard input is the same as that of the process that called
+.Fn popen .
+.Pp
+Note that output
+.Fn popen
+streams are fully buffered by default.
+.Pp
+The
+.Fn pclose
+function waits for the associated process to terminate
+and returns the exit status of the command
+as returned by
+.Fn wait4 .
+.Sh RETURN VALUES
+The
+.Fn popen
+function returns
+.Dv NULL
+if the
+.Xr fork 2 ,
+.Xr pipe 2 ,
+or
+.Xr socketpair 2
+calls fail,
+or if it cannot allocate memory.
+.Pp
+The
+.Fn pclose
+function
+returns \-1 if
+.Fa stream
+is not associated with a
+.Dq popened
+command, if
+.Fa stream
+has already been
+.Dq pclosed ,
+or if
+.Xr wait4 2
+returns an error.
+.Sh ERRORS
+The
+.Fn popen
+function does not reliably set
+.Va errno .
+.Sh SEE ALSO
+.Xr sh 1 ,
+.Xr fork 2 ,
+.Xr pipe 2 ,
+.Xr socketpair 2 ,
+.Xr wait4 2 ,
+.Xr fclose 3 ,
+.Xr fflush 3 ,
+.Xr fopen 3 ,
+.Xr shquote 3 ,
+.Xr stdio 3 ,
+.Xr system 3
+.Sh STANDARDS
+The
+.Fn popen
+and
+.Fn pclose
+functions conform to
+.St -p1003.2-92 .
+.Sh HISTORY
+A
+.Fn popen
+and a
+.Fn pclose
+function appeared in
+.At v7 .
+.Sh BUGS
+Since the standard input of a command opened for reading
+shares its seek offset with the process that called
+.Fn popen ,
+if the original process has done a buffered read,
+the command's input position may not be as expected.
+Similarly, the output from a command opened for writing
+may become intermingled with that of the original process.
+The latter can be avoided by calling
+.Xr fflush 3
+before
+.Fn popen .
+.Pp
+Failure to execute the shell
+is indistinguishable from the shell's failure to execute command,
+or an immediate exit of the command.
+The only hint is an exit status of 127.
+.Pp
+The
+.Fn popen
+argument
+always calls
+.Xr sh 1 ,
+never calls
+.Xr csh 1 .
diff --git a/lib/nbsd_libc/gen/popen.c b/lib/nbsd_libc/gen/popen.c
new file mode 100644 (file)
index 0000000..edd85d5
--- /dev/null
@@ -0,0 +1,226 @@
+/*     $NetBSD: popen.c,v 1.30 2010/11/14 18:11:42 tron Exp $  */
+
+/*
+ * Copyright (c) 1988, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software written by Ken Arnold and
+ * published in UNIX Review, Vol. 6, No. 8.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)popen.c    8.3 (Berkeley) 5/3/95";
+#else
+__RCSID("$NetBSD: popen.c,v 1.30 2010/11/14 18:11:42 tron Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/wait.h>
+#include <sys/socket.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <paths.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "env.h"
+#include "reentrant.h"
+
+#ifdef __weak_alias
+__weak_alias(popen,_popen)
+__weak_alias(pclose,_pclose)
+#endif
+
+static struct pid {
+       struct pid *next;
+       FILE *fp;
+#ifdef _REENTRANT
+       int fd;
+#endif
+       pid_t pid;
+} *pidlist; 
+       
+#ifdef _REENTRANT
+static rwlock_t pidlist_lock = RWLOCK_INITIALIZER;
+#endif
+
+FILE *
+popen(const char *command, const char *type)
+{
+       struct pid *cur, *old;
+       FILE *iop;
+       const char * volatile xtype = type;
+       int pdes[2], pid, serrno;
+       volatile int twoway;
+
+       _DIAGASSERT(command != NULL);
+       _DIAGASSERT(xtype != NULL);
+
+       if (strchr(xtype, '+')) {
+               twoway = 1;
+               type = "r+";
+               if (socketpair(AF_LOCAL, SOCK_STREAM, 0, pdes) < 0)
+                       return (NULL);
+       } else  {
+               twoway = 0;
+               if ((*xtype != 'r' && *xtype != 'w') || xtype[1] ||
+                   (pipe(pdes) < 0)) {
+                       errno = EINVAL;
+                       return (NULL);
+               }
+       }
+
+       if ((cur = malloc(sizeof(struct pid))) == NULL) {
+               (void)close(pdes[0]);
+               (void)close(pdes[1]);
+               errno = ENOMEM;
+               return (NULL);
+       }
+
+       (void)rwlock_rdlock(&pidlist_lock);
+       (void)__readlockenv();
+       switch (pid = vfork()) {
+       case -1:                        /* Error. */
+               serrno = errno;
+               (void)__unlockenv();
+               (void)rwlock_unlock(&pidlist_lock);
+               free(cur);
+               (void)close(pdes[0]);
+               (void)close(pdes[1]);
+               errno = serrno;
+               return (NULL);
+               /* NOTREACHED */
+       case 0:                         /* Child. */
+               /* POSIX.2 B.3.2.2 "popen() shall ensure that any streams
+                  from previous popen() calls that remain open in the 
+                  parent process are closed in the new child process. */
+               for (old = pidlist; old; old = old->next)
+#ifdef _REENTRANT
+                       close(old->fd); /* don't allow a flush */
+#else
+                       close(fileno(old->fp)); /* don't allow a flush */
+#endif
+
+               if (*xtype == 'r') {
+                       (void)close(pdes[0]);
+                       if (pdes[1] != STDOUT_FILENO) {
+                               (void)dup2(pdes[1], STDOUT_FILENO);
+                               (void)close(pdes[1]);
+                       }
+                       if (twoway)
+                               (void)dup2(STDOUT_FILENO, STDIN_FILENO);
+               } else {
+                       (void)close(pdes[1]);
+                       if (pdes[0] != STDIN_FILENO) {
+                               (void)dup2(pdes[0], STDIN_FILENO);
+                               (void)close(pdes[0]);
+                       }
+               }
+
+               execl(_PATH_BSHELL, "sh", "-c", command, NULL);
+               _exit(127);
+               /* NOTREACHED */
+       }
+       (void)__unlockenv();
+
+       /* Parent; assume fdopen can't fail. */
+       if (*xtype == 'r') {
+               iop = fdopen(pdes[0], xtype);
+#ifdef _REENTRANT
+               cur->fd = pdes[0];
+#endif
+               (void)close(pdes[1]);
+       } else {
+               iop = fdopen(pdes[1], xtype);
+#ifdef _REENTRANT
+               cur->fd = pdes[1];
+#endif
+               (void)close(pdes[0]);
+       }
+
+       /* Link into list of file descriptors. */
+       cur->fp = iop;
+       cur->pid =  pid;
+       cur->next = pidlist;
+       pidlist = cur;
+       (void)rwlock_unlock(&pidlist_lock);
+
+       return (iop);
+}
+
+/*
+ * pclose --
+ *     Pclose returns -1 if stream is not associated with a `popened' command,
+ *     if already `pclosed', or waitpid returns an error.
+ */
+int
+pclose(iop)
+       FILE *iop;
+{
+       struct pid *cur, *last;
+       int pstat;
+       pid_t pid;
+
+       _DIAGASSERT(iop != NULL);
+
+       rwlock_wrlock(&pidlist_lock);
+
+       /* Find the appropriate file pointer. */
+       for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next)
+               if (cur->fp == iop)
+                       break;
+       if (cur == NULL) {
+               (void)rwlock_unlock(&pidlist_lock);
+               return (-1);
+       }
+
+       (void)fclose(iop);
+
+       /* Remove the entry from the linked list. */
+       if (last == NULL)
+               pidlist = cur->next;
+       else
+               last->next = cur->next;
+
+       (void)rwlock_unlock(&pidlist_lock);
+
+       do {
+               pid = waitpid(cur->pid, &pstat, 0);
+       } while (pid == -1 && errno == EINTR);
+
+       free(cur);
+
+       return (pid == -1 ? -1 : pstat);
+}
diff --git a/lib/nbsd_libc/gen/psignal.3 b/lib/nbsd_libc/gen/psignal.3
new file mode 100644 (file)
index 0000000..05e5922
--- /dev/null
@@ -0,0 +1,105 @@
+.\"    $NetBSD: psignal.3,v 1.17 2010/08/27 08:38:41 christos Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)psignal.3  8.2 (Berkeley) 2/27/95
+.\"
+.Dd August 27, 2010
+.Dt PSIGNAL 3
+.Os
+.Sh NAME
+.Nm psignal ,
+.Nm psiginfo ,
+.Nm sys_siglist ,
+.Nm sys_signame
+.Nd system signal messages
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft void
+.Fn psignal "int sig" "const char *s"
+.Fn psiginfo "const siginfo_t *si" "const char *s"
+.Vt extern const char * const sys_siglist[];
+.Vt extern const char * const sys_signame[];
+.Sh DESCRIPTION
+The
+.Fn psignal
+function locates the descriptive message
+string for the given signal number
+.Fa sig
+and writes it to the standard error.
+.Pp
+If the argument
+.Fa s
+is
+.Pf non- Dv NULL
+it is written to the standard error file descriptor
+prior to the message string,
+immediately followed by a colon and a space.
+If the signal number is not recognized
+.Pq Xr sigaction 2 ,
+the string
+.Dq "Unknown signal"
+is produced.
+.Pp
+The
+.Fn psiginfo
+function produces the same output as the
+.Fn psignal
+function, only it uses the signal number information from the
+.Fa si
+argument.
+.Pp
+The message strings can be accessed directly using the external array
+.Va sys_siglist ,
+indexed by recognized signal numbers.
+The external array
+.Va sys_signame
+is used similarly and contains short, upper-case abbreviations for signals
+which are useful for recognizing signal names in user input.
+The defined variable
+.Dv NSIG
+contains a count of the strings in
+.Va sys_siglist
+and
+.Va sys_signame .
+.Sh SEE ALSO
+.Xr sigaction 2 ,
+.Xr perror 3 ,
+.Xr setlocale 3 ,
+.Xr strsignal 3
+.Sh HISTORY
+The
+.Fn psignal
+function appeared in
+.Bx 4.2 .
+The
+.Fn psiginfo
+function appeared in
+.Nx 6.0 .
diff --git a/lib/nbsd_libc/gen/psignal.c b/lib/nbsd_libc/gen/psignal.c
new file mode 100644 (file)
index 0000000..c236351
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: psignal.c,v 1.22 2010/08/27 08:38:41 christos Exp $    */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)psignal.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: psignal.c,v 1.22 2010/08/27 08:38:41 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/uio.h>
+
+#include <limits.h>
+#include <signal.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "extern.h"
+
+#ifdef __weak_alias
+__weak_alias(psignal,_psignal)
+#endif
+
+void
+psignal(int sig, const char *s)
+{
+       struct iovec *v;
+       struct iovec iov[4];
+       char buf[NL_TEXTMAX];
+
+       v = iov;
+       if (s && *s) {
+               v->iov_base = __UNCONST(s);
+               v->iov_len = strlen(s);
+               v++;
+               v->iov_base = __UNCONST(": ");
+               v->iov_len = 2;
+               v++;
+       }
+       v->iov_base = __UNCONST(__strsignal((int)sig, buf, sizeof(buf)));
+       v->iov_len = strlen(v->iov_base);
+       v++;
+       v->iov_base = __UNCONST("\n");
+       v->iov_len = 1;
+       (void)writev(STDERR_FILENO, iov, (v - iov) + 1);
+}
+
+void
+psiginfo(const siginfo_t *si, const char *s)
+{
+       psignal(si->si_signo, s);
+}
diff --git a/lib/nbsd_libc/gen/pthread_atfork.3 b/lib/nbsd_libc/gen/pthread_atfork.3
new file mode 100644 (file)
index 0000000..76c9f08
--- /dev/null
@@ -0,0 +1,120 @@
+.\"    $NetBSD: pthread_atfork.3,v 1.5 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Nathan J. Williams.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd February 12, 2003
+.Dt PTHREAD_ATFORK 3
+.Os
+.Sh NAME
+.Nm pthread_atfork
+.Nd register handlers to be called when process forks
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In pthread.h
+.Ft int
+.Fn pthread_atfork "void (*prepare)(void)" "void (*parent)(void)" "void (*child)(void)"
+.Sh DESCRIPTION
+The
+.Fn pthread_atfork
+function registers the provided handler functions to be called when the
+.Xr fork 2
+function is called.
+Each of the three handlers is called at a different place in the
+.Xr fork 2
+sequence.
+The
+.Ar prepare
+handler is called in the parent process before the fork happens, the
+.Ar parent
+handler is called in the parent process after the fork has happened, and the
+.Ar child
+handler is called in the child process after the fork has happened.
+The
+.Ar parent
+and
+.Ar child
+handlers are called in the order in which they were registered, while the
+.Ar prepare
+handlers are called in reverse of the order in which they were registered.
+.Pp
+Any of the handlers given may be
+.Dv NULL .
+.Pp
+The intended use of
+.Fn pthread_atfork
+is to provide a consistent state to a child process from a multithreaded parent
+process where locks may be acquired and released asynchronously with respect to the
+.Xr fork 2
+call.
+Each subsystem with locks that are used in a child process should register
+handlers with
+.Fn pthread_atfork
+that acquires those locks in the
+.Ar prepare
+handler and releases them in the
+.Ar parent
+handler.
+.Sh RETURN VALUES
+The
+.Fn pthread_atfork
+function returns 0 on success and an error number on failure.
+.Sh ERRORS
+The following error code may be returned:
+.Bl -tag -width Er
+.It Bq Er ENOMEM
+Insufficient memory exists to register the fork handlers.
+.El
+.Sh SEE ALSO
+.Xr fork 2
+.Sh STANDARDS
+The
+.Fn pthread_atfork
+function conforms to
+.St -p1003.1c-95 .
+.Sh HISTORY
+The
+.Fn pthread_atfork
+function first appeared in
+.Nx 2.0 .
+.Sh CAVEATS
+After calling
+.Xr fork 2
+from a multithreaded process, it is only safe to call
+async-signal-safe functions until calling one of the
+.Xr exec 3
+functions.
+The
+.Fn pthread_*
+functions are not async-signal-safe, so it is not safe to use such functions
+in the
+.Ar child
+handler.
+.Sh BUGS
+There is no way to unregister a handler registered with
+.Fn pthread_atfork .
diff --git a/lib/nbsd_libc/gen/pthread_atfork.c b/lib/nbsd_libc/gen/pthread_atfork.c
new file mode 100644 (file)
index 0000000..4f7f560
--- /dev/null
@@ -0,0 +1,203 @@
+/*     $NetBSD: pthread_atfork.c,v 1.8 2008/04/28 20:22:59 martin Exp $        */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Nathan J. Williams.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: pthread_atfork.c,v 1.8 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <errno.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <sys/queue.h>
+#include "reentrant.h"
+
+#ifdef __weak_alias
+__weak_alias(pthread_atfork, _pthread_atfork)
+__weak_alias(fork, _fork)
+#endif /* __weak_alias */
+
+pid_t  __fork __P((void));     /* XXX */
+
+struct atfork_callback {
+       SIMPLEQ_ENTRY(atfork_callback) next;
+       void (*fn)(void);
+};
+
+/*
+ * Hypothetically, we could protect the queues with a rwlock which is
+ * write-locked by pthread_atfork() and read-locked by fork(), but
+ * since the intended use of the functions is obtaining locks to hold
+ * across the fork, forking is going to be serialized anyway.
+ */
+static struct atfork_callback atfork_builtin;
+static mutex_t atfork_lock = MUTEX_INITIALIZER;
+SIMPLEQ_HEAD(atfork_callback_q, atfork_callback);
+
+static struct atfork_callback_q prepareq = SIMPLEQ_HEAD_INITIALIZER(prepareq);
+static struct atfork_callback_q parentq = SIMPLEQ_HEAD_INITIALIZER(parentq);
+static struct atfork_callback_q childq = SIMPLEQ_HEAD_INITIALIZER(childq);
+
+static struct atfork_callback *
+af_alloc(void)
+{
+
+       if (atfork_builtin.fn == NULL)
+               return &atfork_builtin;
+
+       return malloc(sizeof(atfork_builtin));
+}
+
+static void
+af_free(struct atfork_callback *af)
+{
+
+       if (af != &atfork_builtin)
+               free(af);
+}
+
+int
+pthread_atfork(void (*prepare)(void), void (*parent)(void),
+    void (*child)(void))
+{
+       struct atfork_callback *newprepare, *newparent, *newchild;
+
+       newprepare = newparent = newchild = NULL;
+
+       mutex_lock(&atfork_lock);
+       if (prepare != NULL) {
+               newprepare = af_alloc();
+               if (newprepare == NULL) {
+                       mutex_unlock(&atfork_lock);
+                       return ENOMEM;
+               }
+               newprepare->fn = prepare;
+       }
+
+       if (parent != NULL) {
+               newparent = af_alloc();
+               if (newparent == NULL) {
+                       if (newprepare != NULL)
+                               af_free(newprepare);
+                       mutex_unlock(&atfork_lock);
+                       return ENOMEM;
+               }
+               newparent->fn = parent;
+       }
+
+       if (child != NULL) {
+               newchild = af_alloc();
+               if (newchild == NULL) {
+                       if (newprepare != NULL)
+                               af_free(newprepare);
+                       if (newparent != NULL)
+                               af_free(newparent);
+                       mutex_unlock(&atfork_lock);
+                       return ENOMEM;
+               }
+               newchild->fn = child;
+       }
+
+       /*
+        * The order in which the functions are called is specified as
+        * LIFO for the prepare handler and FIFO for the others; insert
+        * at the head and tail as appropriate so that SIMPLEQ_FOREACH()
+        * produces the right order.
+        */
+       if (prepare)
+               SIMPLEQ_INSERT_HEAD(&prepareq, newprepare, next);
+       if (parent)
+               SIMPLEQ_INSERT_TAIL(&parentq, newparent, next);
+       if (child)
+               SIMPLEQ_INSERT_TAIL(&childq, newchild, next);
+       mutex_unlock(&atfork_lock);
+
+       return 0;
+}
+
+pid_t
+fork(void)
+{
+       struct atfork_callback *iter;
+       pid_t ret;
+
+       mutex_lock(&atfork_lock);
+       SIMPLEQ_FOREACH(iter, &prepareq, next)
+               (*iter->fn)();
+
+       ret = __fork();
+
+       if (ret != 0) {
+               /*
+                * We are the parent. It doesn't matter here whether
+                * the fork call succeeded or failed.
+                */
+               SIMPLEQ_FOREACH(iter, &parentq, next)
+                       (*iter->fn)();
+               mutex_unlock(&atfork_lock);
+       } else {
+               /* We are the child */
+               SIMPLEQ_FOREACH(iter, &childq, next)
+                       (*iter->fn)();
+               /*
+                * Note: We are explicitly *not* unlocking
+                * atfork_lock.  Unlocking atfork_lock is problematic,
+                * because if any threads in the parent blocked on it
+                * between the initial lock and the fork() syscall,
+                * unlocking in the child will try to schedule
+                * threads, and either the internal mutex interlock or
+                * the runqueue spinlock could have been held at the
+                * moment of fork(). Since the other threads do not
+                * exist in this process, the spinlock will never be
+                * unlocked, and we would wedge.
+                * Instead, we reinitialize atfork_lock, since we know
+                * that the state of the atfork lists is consistent here,
+                * and that there are no other threads to be affected by
+                * the forcible cleaning of the queue.
+                * This permits double-forking to work, although
+                * it requires knowing that it's "safe" to initialize
+                * a locked mutex in this context.
+                *
+                * The problem exists for users of this interface,
+                * too, since the intented use of pthread_atfork() is
+                * to acquire locks across the fork call to ensure
+                * that the child sees consistent state. There's not
+                * much that can usefully be done in a child handler,
+                * and conventional wisdom discourages using them, but
+                * they're part of the interface, so here we are...
+                */
+               mutex_init(&atfork_lock, NULL);
+       }
+
+       return ret;
+}
diff --git a/lib/nbsd_libc/gen/pw_private.h b/lib/nbsd_libc/gen/pw_private.h
new file mode 100644 (file)
index 0000000..646fb2d
--- /dev/null
@@ -0,0 +1,8 @@
+/*     $NetBSD: pw_private.h,v 1.2 2003/07/26 19:24:43 salo Exp $      */
+
+/*
+ * Written by Jason R. Thorpe <thorpej@NetBSD.org>, June 26, 1998.
+ * Public domain.
+ */
+
+int    __pw_scan __P((char *bp, struct passwd *pw, int *flags));
diff --git a/lib/nbsd_libc/gen/pw_scan.c b/lib/nbsd_libc/gen/pw_scan.c
new file mode 100644 (file)
index 0000000..5bb8a10
--- /dev/null
@@ -0,0 +1,240 @@
+/*     $NetBSD: pw_scan.c,v 1.22 2009/01/29 10:41:39 enami Exp $       */
+
+/*
+ * Copyright (c) 1987, 1993, 1994, 1995
+ *     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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#include "compat_pwd.h"
+
+#else
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: pw_scan.c,v 1.22 2009/01/29 10:41:39 enami Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(_LIBC)
+#include "namespace.h"
+#endif
+#include <sys/types.h>
+
+#include <assert.h>
+#include <err.h>
+#include <limits.h>
+#include <pwd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+
+#ifdef _LIBC
+#include "pw_private.h"
+#endif
+#endif /* ! HAVE_NBTOOL_CONFIG_H */
+
+static int
+gettime(long long *res, const char *p, int *flags, int dowarn, int flag)
+{
+       long long l;
+       char *ep;
+       const char *vp;
+
+       if (*p == '\0') {
+               *flags |= flag;
+               *res = 0;
+               return 1;
+       }
+       l = strtoll(p, &ep, 0);
+       if (p == ep || *ep != '\0') {
+               vp = "Invalid number";
+               goto done;
+       }
+       if (errno == ERANGE && (l == LLONG_MAX || l == LLONG_MIN)) {
+               vp = strerror(errno);
+               goto done;
+       }
+
+       *res = l;
+       return 1;
+done:
+       if (dowarn) {
+               warnx("%s `%s' for %s time", vp, p,
+                   flag == _PASSWORD_NOEXP ? "expiration" : "change");
+       }
+       return 0;
+
+}
+
+static int
+getid(unsigned long *res, const char *p, int *flags, int dowarn, int flag)
+{
+       unsigned long ul;
+       char *ep;
+
+       if (*p == '\0') {
+               *flags |= flag;
+               *res = 0;
+               return 1;
+       }
+       ul = strtoul(p, &ep, 0);
+       if (p == ep || *ep != '\0') {
+               ep = __UNCONST("Invalid number");
+               goto done;
+       }
+       if (errno == ERANGE && ul == ULONG_MAX) {
+               ep = strerror(errno);
+               goto done;
+       }
+       if (ul > *res) {
+               ep = strerror(ERANGE);
+               goto done;
+       }
+
+       *res = ul;
+       return 1;
+done:
+       if (dowarn)
+               warnx("%s %s `%s'", ep, 
+                   flag == _PASSWORD_NOUID ? "uid" : "gid", p);
+       return 0;
+
+}
+
+int
+#ifdef _LIBC
+__pw_scan(char *bp, struct passwd *pw, int *flags)
+#else
+pw_scan( char *bp, struct passwd *pw, int *flags)
+#endif
+{
+       unsigned long id;
+       long long ti;
+       int root, inflags;
+       int dowarn;
+       const char *p, *sh;
+
+       _DIAGASSERT(bp != NULL);
+       _DIAGASSERT(pw != NULL);
+
+       if (flags) {
+               inflags = *flags;
+               *flags = 0;
+       } else {
+               inflags = 0;
+               flags = &inflags;
+       }
+       dowarn = !(inflags & _PASSWORD_NOWARN);
+
+       if (!(pw->pw_name = strsep(&bp, ":")))          /* login */
+               goto fmt;
+       if (strlen(pw->pw_name) > (LOGIN_NAME_MAX - 1)) {
+               if (dowarn)
+                       warnx("username too long, `%s' > %d", pw->pw_name,
+                           LOGIN_NAME_MAX - 1);
+               return 0;
+       }
+
+       root = !strcmp(pw->pw_name, "root");
+
+       if (!(pw->pw_passwd = strsep(&bp, ":")))        /* passwd */
+               goto fmt;
+
+       if (!(p = strsep(&bp, ":")))                    /* uid */
+               goto fmt;
+
+       id = UID_MAX;
+       if (!getid(&id, p, flags, dowarn, _PASSWORD_NOUID))
+               return 0;
+
+       if (root && id) {
+               if (dowarn)
+                       warnx("root uid should be 0");
+               return 0;
+       }
+
+       pw->pw_uid = (uid_t)id;
+
+       if (!(p = strsep(&bp, ":")))                    /* gid */
+               goto fmt;
+
+       id = GID_MAX;
+       if (!getid(&id, p, flags, dowarn, _PASSWORD_NOGID))
+               return 0;
+
+       pw->pw_gid = (gid_t)id;
+
+       if (inflags & _PASSWORD_OLDFMT) {
+               pw->pw_class = __UNCONST("");
+               pw->pw_change = 0;
+               pw->pw_expire = 0;
+               *flags |= (_PASSWORD_NOCHG | _PASSWORD_NOEXP);
+       } else {
+               pw->pw_class = strsep(&bp, ":");        /* class */
+               if (!(p = strsep(&bp, ":")))            /* change */
+                       goto fmt;
+               if (!gettime(&ti, p, flags, dowarn, _PASSWORD_NOCHG))
+                       return 0;
+               pw->pw_change = ti;
+
+               if (!(p = strsep(&bp, ":")))            /* expire */
+                       goto fmt;
+               if (!gettime(&ti, p, flags, dowarn, _PASSWORD_NOEXP))
+                       return 0;
+               pw->pw_expire = ti;
+       }
+
+       pw->pw_gecos = strsep(&bp, ":");                /* gecos */
+       pw->pw_dir = strsep(&bp, ":");                  /* directory */
+       if (!(pw->pw_shell = strsep(&bp, ":")))         /* shell */
+               goto fmt;
+
+#if ! HAVE_NBTOOL_CONFIG_H
+       p = pw->pw_shell;
+       if (root && *p)                                 /* empty == /bin/sh */
+               for (setusershell();;) {
+                       if (!(sh = getusershell())) {
+                               if (dowarn)
+                                       warnx("warning, unknown root shell");
+                               break;
+                       }
+                       if (!strcmp(p, sh))
+                               break;  
+               }
+#endif
+
+       if ((p = strsep(&bp, ":")) != NULL) {                   /* too many */
+fmt:           
+               if (dowarn)
+                       warnx("corrupted entry");
+               return 0;
+       }
+
+       return 1;
+}
diff --git a/lib/nbsd_libc/gen/pwcache.3 b/lib/nbsd_libc/gen/pwcache.3
new file mode 100644 (file)
index 0000000..c0b679a
--- /dev/null
@@ -0,0 +1,220 @@
+.\"    $NetBSD: pwcache.3,v 1.17 2008/05/02 18:11:04 martin Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"
+.\" Copyright (c) 2002 The NetBSD Foundation, Inc.
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.\"
+.\"     @(#)pwcache.3  8.1 (Berkeley) 6/9/93
+.\"
+.Dd January 24, 2002
+.Dt PWCACHE 3
+.Os
+.Sh NAME
+.Nm pwcache ,
+.Nm user_from_uid ,
+.Nm group_from_gid
+.Nd cache password and group entries
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In pwd.h
+.Ft const char *
+.Fn user_from_uid "uid_t uid" "int nouser"
+.Ft int
+.Fn uid_from_user "const char *name" "uid_t *uid"
+.Ft int
+.Fn pwcache_userdb "int (*setpassent)(int)" "void (*endpwent)(void)" "struct passwd * (*getpwnam)(const char *)" "struct passwd * (*getpwuid)(uid_t)"
+.In grp.h
+.Ft const char *
+.Fn group_from_gid "gid_t gid" "int nogroup"
+.Ft int
+.Fn gid_from_group "const char *name" "gid_t *gid"
+.Ft int
+.Fn pwcache_groupdb "int (*setgroupent)(int)" "void (*endgrent)(void)" "struct group * (*getgrnam)(const char *)" "struct group * (*getgrgid)(gid_t)"
+.Sh DESCRIPTION
+The
+.Fn user_from_uid
+function returns the user name associated with the argument
+.Fa uid .
+The user name is cached so that multiple calls with the same
+.Fa uid
+do not require additional calls to
+.Xr getpwuid 3 .
+If there is no user associated with the
+.Fa uid ,
+a pointer is returned
+to a string representation of the
+.Fa uid ,
+unless the argument
+.Fa nouser
+is non-zero, in which case a
+.Dv NULL
+pointer is returned.
+.Pp
+The
+.Fn group_from_gid
+function returns the group name associated with the argument
+.Fa gid .
+The group name is cached so that multiple calls with the same
+.Fa gid
+do not require additional calls to
+.Xr getgrgid 3 .
+If there is no group associated with the
+.Fa gid ,
+a pointer is returned
+to a string representation of the
+.Fa gid ,
+unless the argument
+.Fa nogroup
+is non-zero, in which case a
+.Dv NULL
+pointer is returned.
+.Pp
+The
+.Fn uid_from_user
+function returns the uid associated with the argument
+.Fa name .
+The uid is cached so that multiple calls with the same
+.Fa name
+do not require additional calls to
+.Xr getpwnam 3 .
+If there is no uid associated with the
+.Fa name ,
+the
+.Fn uid_from_user
+function returns \-1; otherwise it stores the uid at the location pointed to by
+.Fa uid
+and returns 0.
+.Pp
+The
+.Fn gid_from_group
+function returns the gid associated with the argument
+.Fa name .
+The gid is cached so that multiple calls with the same
+.Fa name
+do not require additional calls to
+.Xr getgrnam 3 .
+If there is no gid associated with the
+.Fa name ,
+the
+.Fn gid_from_group
+function returns \-1; otherwise it stores the gid at the location pointed to by
+.Fa gid
+and returns 0.
+.Pp
+The
+.Fn pwcache_userdb
+function changes the user database access routines which
+.Fn user_from_uid
+and
+.Fn uid_from_user
+call to search for users.
+The caches are flushed and the existing
+.Fn endpwent
+method is called before switching to the new routines.
+.Fa getpwnam
+and
+.Fa getpwuid
+must be provided, and
+.Fa setpassent
+and
+.Fa endpwent
+may be
+.Dv NULL
+pointers.
+.Pp
+The
+.Fn pwcache_groupdb
+function changes the group database access routines which
+.Fn group_from_gid
+and
+.Fn gid_from_group
+call to search for groups.
+The caches are flushed and the existing
+.Fn endgrent
+method is called before switching to the new routines.
+.Fa getgrnam
+and
+.Fa getgrgid
+must be provided, and
+.Fa setgroupent
+and
+.Fa endgrent
+may be
+.Dv NULL
+pointers.
+.Sh SEE ALSO
+.Xr getgrgid 3 ,
+.Xr getgrnam 3 ,
+.Xr getpwnam 3 ,
+.Xr getpwuid 3
+.Sh HISTORY
+The
+.Fn user_from_uid
+and
+.Fn group_from_gid
+functions first appeared in
+.Bx 4.4 .
+.Pp
+The
+.Fn uid_from_user
+and
+.Fn gid_from_group
+functions first appeared in
+.Nx 1.4 .
+.Pp
+The
+.Fn pwcache_userdb
+and
+.Fn pwcache_groupdb
+functions first appeared in
+.Nx 1.6 .
diff --git a/lib/nbsd_libc/gen/pwcache.c b/lib/nbsd_libc/gen/pwcache.c
new file mode 100644 (file)
index 0000000..2caf96a
--- /dev/null
@@ -0,0 +1,643 @@
+/*     $NetBSD: pwcache.c,v 1.31 2010/03/23 20:28:59 drochner Exp $    */
+
+/*-
+ * Copyright (c) 1992 Keith Muller.
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Keith Muller of the University of California, San Diego.
+ *
+ * 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. 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.
+ */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+/*
+ * XXX Undefine the renames of these functions so that we don't
+ * XXX rename the versions found in the host's <pwd.h> by mistake!
+ */
+#undef group_from_gid
+#undef user_from_uid
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)cache.c    8.1 (Berkeley) 5/31/93";
+#else
+__RCSID("$NetBSD: pwcache.c,v 1.31 2010/03/23 20:28:59 drochner Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/param.h>
+
+#include <assert.h>
+#include <grp.h>
+#include <pwd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#if HAVE_NBTOOL_CONFIG_H
+/* XXX Now, re-apply the renaming that we undid above. */
+#define        group_from_gid  __nbcompat_group_from_gid
+#define        user_from_uid   __nbcompat_user_from_uid
+#endif
+
+#ifdef __weak_alias
+__weak_alias(user_from_uid,_user_from_uid)
+__weak_alias(group_from_gid,_group_from_gid)
+__weak_alias(pwcache_groupdb,_pwcache_groupdb)
+#endif
+
+#if !HAVE_PWCACHE_USERDB || HAVE_NBTOOL_CONFIG_H
+#include "pwcache.h"
+
+/*
+ * routines that control user, group, uid and gid caches (for the archive
+ * member print routine).
+ * IMPORTANT:
+ * these routines cache BOTH hits and misses, a major performance improvement
+ */
+
+/*
+ * function pointers to various name lookup routines.
+ * these may be changed as necessary.
+ */
+static int             (*_pwcache_setgroupent)(int)            = setgroupent;
+static void            (*_pwcache_endgrent)(void)              = endgrent;
+static struct group *  (*_pwcache_getgrnam)(const char *)      = getgrnam;
+static struct group *  (*_pwcache_getgrgid)(gid_t)             = getgrgid;
+static int             (*_pwcache_setpassent)(int)             = setpassent;
+static void            (*_pwcache_endpwent)(void)              = endpwent;
+static struct passwd * (*_pwcache_getpwnam)(const char *)      = getpwnam;
+static struct passwd * (*_pwcache_getpwuid)(uid_t)             = getpwuid;
+
+/*
+ * internal state
+ */
+static int     pwopn;          /* is password file open */
+static int     gropn;          /* is group file open */
+static UIDC    **uidtb;        /* uid to name cache */
+static GIDC    **gidtb;        /* gid to name cache */
+static UIDC    **usrtb;        /* user name to uid cache */
+static GIDC    **grptb;        /* group name to gid cache */
+
+static int     uidtb_fail;     /* uidtb_start() failed ? */
+static int     gidtb_fail;     /* gidtb_start() failed ? */
+static int     usrtb_fail;     /* usrtb_start() failed ? */
+static int     grptb_fail;     /* grptb_start() failed ? */
+
+
+static u_int   st_hash(const char *, size_t, int);
+static int     uidtb_start(void);
+static int     gidtb_start(void);
+static int     usrtb_start(void);
+static int     grptb_start(void);
+
+
+static u_int
+st_hash(const char *name, size_t len, int tabsz)
+{
+       u_int key = 0;
+
+       _DIAGASSERT(name != NULL);
+
+       while (len--) {
+               key += *name++;
+               key = (key << 8) | (key >> 24);
+       }
+
+       return (key % tabsz);
+}
+
+/*
+ * uidtb_start
+ *     creates an an empty uidtb
+ * Return:
+ *     0 if ok, -1 otherwise
+ */
+static int
+uidtb_start(void)
+{
+
+       if (uidtb != NULL)
+               return (0);
+       if (uidtb_fail)
+               return (-1);
+       if ((uidtb = (UIDC **)calloc(UID_SZ, sizeof(UIDC *))) == NULL) {
+               ++uidtb_fail;
+               return (-1);
+       }
+       return (0);
+}
+
+/*
+ * gidtb_start
+ *     creates an an empty gidtb
+ * Return:
+ *     0 if ok, -1 otherwise
+ */
+static int
+gidtb_start(void)
+{
+
+       if (gidtb != NULL)
+               return (0);
+       if (gidtb_fail)
+               return (-1);
+       if ((gidtb = (GIDC **)calloc(GID_SZ, sizeof(GIDC *))) == NULL) {
+               ++gidtb_fail;
+               return (-1);
+       }
+       return (0);
+}
+
+/*
+ * usrtb_start
+ *     creates an an empty usrtb
+ * Return:
+ *     0 if ok, -1 otherwise
+ */
+static int
+usrtb_start(void)
+{
+
+       if (usrtb != NULL)
+               return (0);
+       if (usrtb_fail)
+               return (-1);
+       if ((usrtb = (UIDC **)calloc(UNM_SZ, sizeof(UIDC *))) == NULL) {
+               ++usrtb_fail;
+               return (-1);
+       }
+       return (0);
+}
+
+/*
+ * grptb_start
+ *     creates an an empty grptb
+ * Return:
+ *     0 if ok, -1 otherwise
+ */
+static int
+grptb_start(void)
+{
+
+       if (grptb != NULL)
+               return (0);
+       if (grptb_fail)
+               return (-1);
+       if ((grptb = (GIDC **)calloc(GNM_SZ, sizeof(GIDC *))) == NULL) {
+               ++grptb_fail;
+               return (-1);
+       }
+       return (0);
+}
+
+/*
+ * user_from_uid()
+ *     caches the name (if any) for the uid. If noname clear, we always
+ *     return the stored name (if valid or invalid match).
+ *     We use a simple hash table.
+ * Return
+ *     Pointer to stored name (or a empty string)
+ */
+const char *
+user_from_uid(uid_t uid, int noname)
+{
+       struct passwd *pw;
+       UIDC *ptr, **pptr;
+
+       if ((uidtb == NULL) && (uidtb_start() < 0))
+               return (NULL);
+
+       /*
+        * see if we have this uid cached
+        */
+       pptr = uidtb + (uid % UID_SZ);
+       ptr = *pptr;
+
+       if ((ptr != NULL) && (ptr->valid > 0) && (ptr->uid == uid)) {
+               /*
+                * have an entry for this uid
+                */
+               if (!noname || (ptr->valid == VALID))
+                       return (ptr->name);
+               return (NULL);
+       }
+
+       /*
+        * No entry for this uid, we will add it
+        */
+       if (!pwopn) {
+               if (_pwcache_setpassent != NULL)
+                       (*_pwcache_setpassent)(1);
+               ++pwopn;
+       }
+
+       if (ptr == NULL)
+               *pptr = ptr = (UIDC *)malloc(sizeof(UIDC));
+
+       if ((pw = (*_pwcache_getpwuid)(uid)) == NULL) {
+               /*
+                * no match for this uid in the local password file
+                * a string that is the uid in numeric format
+                */
+               if (ptr == NULL)
+                       return (NULL);
+               ptr->uid = uid;
+               (void)snprintf(ptr->name, UNMLEN, "%lu", (long) uid);
+               ptr->valid = INVALID;
+               if (noname)
+                       return (NULL);
+       } else {
+               /*
+                * there is an entry for this uid in the password file
+                */
+               if (ptr == NULL)
+                       return (pw->pw_name);
+               ptr->uid = uid;
+               (void)strlcpy(ptr->name, pw->pw_name, UNMLEN);
+               ptr->valid = VALID;
+       }
+       return (ptr->name);
+}
+
+/*
+ * group_from_gid()
+ *     caches the name (if any) for the gid. If noname clear, we always
+ *     return the stored name (if valid or invalid match).
+ *     We use a simple hash table.
+ * Return
+ *     Pointer to stored name (or a empty string)
+ */
+const char *
+group_from_gid(gid_t gid, int noname)
+{
+       struct group *gr;
+       GIDC *ptr, **pptr;
+
+       if ((gidtb == NULL) && (gidtb_start() < 0))
+               return (NULL);
+
+       /*
+        * see if we have this gid cached
+        */
+       pptr = gidtb + (gid % GID_SZ);
+       ptr = *pptr;
+
+       if ((ptr != NULL) && (ptr->valid > 0) && (ptr->gid == gid)) {
+               /*
+                * have an entry for this gid
+                */
+               if (!noname || (ptr->valid == VALID))
+                       return (ptr->name);
+               return (NULL);
+       }
+
+       /*
+        * No entry for this gid, we will add it
+        */
+       if (!gropn) {
+               if (_pwcache_setgroupent != NULL)
+                       (*_pwcache_setgroupent)(1);
+               ++gropn;
+       }
+
+       if (ptr == NULL)
+               *pptr = ptr = (GIDC *)malloc(sizeof(GIDC));
+
+       if ((gr = (*_pwcache_getgrgid)(gid)) == NULL) {
+               /*
+                * no match for this gid in the local group file, put in
+                * a string that is the gid in numberic format
+                */
+               if (ptr == NULL)
+                       return (NULL);
+               ptr->gid = gid;
+               (void)snprintf(ptr->name, GNMLEN, "%lu", (long) gid);
+               ptr->valid = INVALID;
+               if (noname)
+                       return (NULL);
+       } else {
+               /*
+                * there is an entry for this group in the group file
+                */
+               if (ptr == NULL)
+                       return (gr->gr_name);
+               ptr->gid = gid;
+               (void)strlcpy(ptr->name, gr->gr_name, GNMLEN);
+               ptr->valid = VALID;
+       }
+       return (ptr->name);
+}
+
+/*
+ * uid_from_user()
+ *     caches the uid for a given user name. We use a simple hash table.
+ * Return
+ *     the uid (if any) for a user name, or a -1 if no match can be found
+ */
+int
+uid_from_user(const char *name, uid_t *uid)
+{
+       struct passwd *pw;
+       UIDC *ptr, **pptr;
+       size_t namelen;
+
+       /*
+        * return -1 for mangled names
+        */
+       if (name == NULL || ((namelen = strlen(name)) == 0))
+               return (-1);
+       if ((usrtb == NULL) && (usrtb_start() < 0))
+               return (-1);
+
+       /*
+        * look up in hash table, if found and valid return the uid,
+        * if found and invalid, return a -1
+        */
+       pptr = usrtb + st_hash(name, namelen, UNM_SZ);
+       ptr = *pptr;
+
+       if ((ptr != NULL) && (ptr->valid > 0) && !strcmp(name, ptr->name)) {
+               if (ptr->valid == INVALID)
+                       return (-1);
+               *uid = ptr->uid;
+               return (0);
+       }
+
+       if (!pwopn) {
+               if (_pwcache_setpassent != NULL)
+                       (*_pwcache_setpassent)(1);
+               ++pwopn;
+       }
+
+       if (ptr == NULL)
+               *pptr = ptr = (UIDC *)malloc(sizeof(UIDC));
+
+       /*
+        * no match, look it up, if no match store it as an invalid entry,
+        * or store the matching uid
+        */
+       if (ptr == NULL) {
+               if ((pw = (*_pwcache_getpwnam)(name)) == NULL)
+                       return (-1);
+               *uid = pw->pw_uid;
+               return (0);
+       }
+       (void)strlcpy(ptr->name, name, UNMLEN);
+       if ((pw = (*_pwcache_getpwnam)(name)) == NULL) {
+               ptr->valid = INVALID;
+               return (-1);
+       }
+       ptr->valid = VALID;
+       *uid = ptr->uid = pw->pw_uid;
+       return (0);
+}
+
+/*
+ * gid_from_group()
+ *     caches the gid for a given group name. We use a simple hash table.
+ * Return
+ *     the gid (if any) for a group name, or a -1 if no match can be found
+ */
+int
+gid_from_group(const char *name, gid_t *gid)
+{
+       struct group *gr;
+       GIDC *ptr, **pptr;
+       size_t namelen;
+
+       /*
+        * return -1 for mangled names
+        */
+       if (name == NULL || ((namelen = strlen(name)) == 0))
+               return (-1);
+       if ((grptb == NULL) && (grptb_start() < 0))
+               return (-1);
+
+       /*
+        * look up in hash table, if found and valid return the uid,
+        * if found and invalid, return a -1
+        */
+       pptr = grptb + st_hash(name, namelen, GID_SZ);
+       ptr = *pptr;
+
+       if ((ptr != NULL) && (ptr->valid > 0) && !strcmp(name, ptr->name)) {
+               if (ptr->valid == INVALID)
+                       return (-1);
+               *gid = ptr->gid;
+               return (0);
+       }
+
+       if (!gropn) {
+               if (_pwcache_setgroupent != NULL)
+                       (*_pwcache_setgroupent)(1);
+               ++gropn;
+       }
+
+       if (ptr == NULL)
+               *pptr = ptr = (GIDC *)malloc(sizeof(GIDC));
+
+       /*
+        * no match, look it up, if no match store it as an invalid entry,
+        * or store the matching gid
+        */
+       if (ptr == NULL) {
+               if ((gr = (*_pwcache_getgrnam)(name)) == NULL)
+                       return (-1);
+               *gid = gr->gr_gid;
+               return (0);
+       }
+
+       (void)strlcpy(ptr->name, name, GNMLEN);
+       if ((gr = (*_pwcache_getgrnam)(name)) == NULL) {
+               ptr->valid = INVALID;
+               return (-1);
+       }
+       ptr->valid = VALID;
+       *gid = ptr->gid = gr->gr_gid;
+       return (0);
+}
+
+#define FLUSHTB(arr, len, fail)                                \
+       do {                                            \
+               if (arr != NULL) {                      \
+                       for (i = 0; i < len; i++)       \
+                               if (arr[i] != NULL)     \
+                                       free(arr[i]);   \
+                       arr = NULL;                     \
+               }                                       \
+               fail = 0;                               \
+       } while (/* CONSTCOND */0);
+
+int
+pwcache_userdb(
+       int             (*a_setpassent)(int),
+       void            (*a_endpwent)(void),
+       struct passwd * (*a_getpwnam)(const char *),
+       struct passwd * (*a_getpwuid)(uid_t))
+{
+       int i;
+
+               /* a_setpassent and a_endpwent may be NULL */
+       if (a_getpwnam == NULL || a_getpwuid == NULL)
+               return (-1);
+
+       if (_pwcache_endpwent != NULL)
+               (*_pwcache_endpwent)();
+       FLUSHTB(uidtb, UID_SZ, uidtb_fail);
+       FLUSHTB(usrtb, UNM_SZ, usrtb_fail);
+       pwopn = 0;
+       _pwcache_setpassent = a_setpassent;
+       _pwcache_endpwent = a_endpwent;
+       _pwcache_getpwnam = a_getpwnam;
+       _pwcache_getpwuid = a_getpwuid;
+
+       return (0);
+}
+
+int
+pwcache_groupdb(
+       int             (*a_setgroupent)(int),
+       void            (*a_endgrent)(void),
+       struct group *  (*a_getgrnam)(const char *),
+       struct group *  (*a_getgrgid)(gid_t))
+{
+       int i;
+
+               /* a_setgroupent and a_endgrent may be NULL */
+       if (a_getgrnam == NULL || a_getgrgid == NULL)
+               return (-1);
+
+       if (_pwcache_endgrent != NULL)
+               (*_pwcache_endgrent)();
+       FLUSHTB(gidtb, GID_SZ, gidtb_fail);
+       FLUSHTB(grptb, GNM_SZ, grptb_fail);
+       gropn = 0;
+       _pwcache_setgroupent = a_setgroupent;
+       _pwcache_endgrent = a_endgrent;
+       _pwcache_getgrnam = a_getgrnam;
+       _pwcache_getgrgid = a_getgrgid;
+
+       return (0);
+}
+
+
+#ifdef TEST_PWCACHE
+
+struct passwd *
+test_getpwnam(const char *name)
+{
+       static struct passwd foo;
+
+       memset(&foo, 0, sizeof(foo));
+       if (strcmp(name, "toor") == 0) {
+               foo.pw_uid = 666;
+               return &foo;
+       }
+       return (getpwnam(name));
+}
+
+int
+main(int argc, char *argv[])
+{
+       uid_t   u;
+       int     r, i;
+
+       printf("pass 1 (default userdb)\n");
+       for (i = 1; i < argc; i++) {
+               printf("i: %d, pwopn %d usrtb_fail %d usrtb %p\n",
+                   i, pwopn, usrtb_fail, usrtb);
+               r = uid_from_user(argv[i], &u);
+               if (r == -1)
+                       printf("  uid_from_user %s: failed\n", argv[i]);
+               else
+                       printf("  uid_from_user %s: %d\n", argv[i], u);
+       }
+       printf("pass 1 finish: pwopn %d usrtb_fail %d usrtb %p\n",
+                   pwopn, usrtb_fail, usrtb);
+
+       puts("");
+       printf("pass 2 (replacement userdb)\n");
+       printf("pwcache_userdb returned %d\n",
+           pwcache_userdb(setpassent, test_getpwnam, getpwuid));
+       printf("pwopn %d usrtb_fail %d usrtb %p\n", pwopn, usrtb_fail, usrtb);
+
+       for (i = 1; i < argc; i++) {
+               printf("i: %d, pwopn %d usrtb_fail %d usrtb %p\n",
+                   i, pwopn, usrtb_fail, usrtb);
+               u = -1;
+               r = uid_from_user(argv[i], &u);
+               if (r == -1)
+                       printf("  uid_from_user %s: failed\n", argv[i]);
+               else
+                       printf("  uid_from_user %s: %d\n", argv[i], u);
+       }
+       printf("pass 2 finish: pwopn %d usrtb_fail %d usrtb %p\n",
+                   pwopn, usrtb_fail, usrtb);
+
+       puts("");
+       printf("pass 3 (null pointers)\n");
+       printf("pwcache_userdb returned %d\n",
+           pwcache_userdb(NULL, NULL, NULL));
+
+       return (0);
+}
+#endif /* TEST_PWCACHE */
+#endif /* !HAVE_PWCACHE_USERDB */
diff --git a/lib/nbsd_libc/gen/pwcache.h b/lib/nbsd_libc/gen/pwcache.h
new file mode 100644 (file)
index 0000000..3bd651b
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: pwcache.h,v 1.5 2003/11/10 08:51:51 wiz Exp $  */
+
+/*-
+ * Copyright (c) 1992 Keith Muller.
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Keith Muller of the University of California, San Diego.
+ *
+ * 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. 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.
+ *
+ *      @(#)cache.h    8.1 (Berkeley) 5/31/93
+ */
+
+/*
+ * Constants and data structures used to implement group and password file
+ * caches. Traditional passwd/group cache routines perform quite poorly with
+ * archives. The chances of hitting a valid lookup with an archive is quite a
+ * bit worse than with files already resident on the file system. These misses
+ * create a MAJOR performance cost. To address this problem, these routines
+ * cache both hits and misses.
+ *
+ * NOTE:  name lengths must be as large as those stored in ANY PROTOCOL and
+ * as stored in the passwd and group files. CACHE SIZES MUST BE PRIME
+ */
+#define UNMLEN         32      /* >= user name found in any protocol */
+#define GNMLEN         32      /* >= group name found in any protocol */
+#define UID_SZ         317     /* size of uid to user_name cache */
+#define UNM_SZ         317     /* size of user_name to uid cache */
+#define GID_SZ         251     /* size of gid to group_name cache */
+#define GNM_SZ         251     /* size of group_name to gid cache */
+#define VALID          1       /* entry and name are valid */
+#define INVALID                2       /* entry valid, name NOT valid */
+
+/*
+ * Node structures used in the user, group, uid, and gid caches.
+ */
+
+typedef struct uidc {
+       int valid;              /* is this a valid or a miss entry */
+       char name[UNMLEN];      /* uid name */
+       uid_t uid;              /* cached uid */
+} UIDC;
+
+typedef struct gidc {
+       int valid;              /* is this a valid or a miss entry */
+       char name[GNMLEN];      /* gid name */
+       gid_t gid;              /* cached gid */
+} GIDC;
diff --git a/lib/nbsd_libc/gen/raise.3 b/lib/nbsd_libc/gen/raise.3
new file mode 100644 (file)
index 0000000..1b3b814
--- /dev/null
@@ -0,0 +1,79 @@
+.\"    $NetBSD: raise.3,v 1.9 2009/01/30 23:52:28 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)raise.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd January 29, 2009
+.Dt RAISE 3
+.Os
+.Sh NAME
+.Nm raise
+.Nd send a signal to the current thread
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn raise "int sig"
+.Sh DESCRIPTION
+The
+.Fn raise
+function sends the signal
+.Fa sig
+to the current thread.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn raise
+function
+may fail and set
+.Va errno
+for any of the errors specified for the
+library functions
+.Xr _lwp_self 2
+and
+.Xr _lwp_kill 2 .
+.Sh SEE ALSO
+.Xr kill 2
+.Sh STANDARDS
+The
+.Fn raise
+function
+conforms to
+.St -ansiC
+and
+.St -susv2 .
diff --git a/lib/nbsd_libc/gen/raise.c b/lib/nbsd_libc/gen/raise.c
new file mode 100644 (file)
index 0000000..2c77d66
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: raise.c,v 1.8 2009/01/29 23:52:21 rmind Exp $  */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)raise.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: raise.c,v 1.8 2009/01/29 23:52:21 rmind Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <lwp.h>
+#include <signal.h>
+
+int
+raise(int s)
+{
+
+       return _lwp_kill(_lwp_self(), s);
+}
diff --git a/lib/nbsd_libc/gen/randomid.3 b/lib/nbsd_libc/gen/randomid.3
new file mode 100644 (file)
index 0000000..dbb31ce
--- /dev/null
@@ -0,0 +1,148 @@
+.\"    $NetBSD: randomid.3,v 1.7 2006/01/05 19:45:29 rpaulo Exp $
+.\"
+.\" Copyright (C) 2006 The NetBSD Foundation
+.\" All rights reserved.
+.\"
+.\" Copyright (C) 2003 WIDE Project.
+.\" 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.
+.\" 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
+.\"
+.Dd January 5, 2006
+.Dt RANDOMID 3
+.Os
+.Sh NAME
+.Nm randomid
+.Nm randomid_new ,
+.Nm randomid_delete ,
+.Nd provide pseudo-random data stream without repetitions
+.Sh SYNOPSIS
+.In sys/types.h
+.In randomid.h
+.Ft uint32_t
+.Fn randomid "randomid_t ctx"
+.Ft randomid_t
+.Fn randomid_new "int bits" "long timeo"
+.Ft void
+.Fn randomid_delete "randomid_t ctx"
+.Sh DESCRIPTION
+The
+.Fn randomid
+function provides pseudo-random data stream,
+which is guaranteed not to generate the same number twice during
+a certain duration.
+.Fa ctx
+is the context which holds internal state for the random number generator.
+.Pp
+To initialize a context,
+.Fa randomid_new
+is used.
+.Fa bits
+specifies the bitwidth of the value generated by
+.Fn randomid .
+Currently 32, 20, and 16 are supported.
+.Fa timeo
+specifies the reinitialization interval in seconds.
+.Fa timeo
+has to be bigger than
+.Dv RANDOMID_TIMEO_MIN .
+.Fa randomid_new
+returns a dynamically-allocated memory region allocated by
+.Xr malloc 3 .
+.Pp
+.Fn randomid_delete
+will
+.Xr free 3
+the internal state
+.Fa ctx .
+.Pp
+The same number may appear after two reinitialization events of the internal state,
+.Fa ctx .
+Reinitialization happens when the random number generator cycle is exhausted,
+or
+.Fa timeo
+seconds have passed since the last reinitialization.
+For instance,
+.Fa ctx
+configured to generate 16 bit data stream will reinitialize its internal state
+every 30000 calls to
+.Fn randomid
+.Po
+or after
+.Fa timeo
+seconds
+.Pc ,
+therefore the same data will not appear until after 30000 calls to
+.Fn randomid
+.Po
+or after
+.Fa timeo
+seconds
+.Pc .
+.Pp
+The internal state,
+.Fa ctx ,
+determines the data stream generated by
+.Fn randomid .
+.Fa ctx
+must be allocated per data stream
+.Pq such as a specific data field .
+It must not be shared among multiple data streams with different usage.
+.\"
+.Sh EXAMPLES
+.Bd -literal -offset indent
+#include \*[Lt]stdio.h\*[Gt]
+#include \*[Lt]sys/types.h\*[Gt]
+#include \*[Lt]randomid.h\*[Gt]
+
+uint32_t
+genid(void)
+{
+       static randomid_t ctx = NULL;
+
+       if (!ctx)
+               ctx = randomid_new(16, (long)3600);
+       return randomid(ctx);
+}
+.Ed
+.\"
+.Sh ERRORS
+.Fn randomid_new
+returns
+.Dv NULL
+on error and sets the external variable
+.Va errno .
+.\"
+.Sh SEE ALSO
+.Xr arc4random 3
+.\"
+.Sh HISTORY
+The pseudo-random data stream generator was designed by Niels Provos for
+.Ox
+IPv4 fragment ID generation.
+.Fn randomid
+is a generalized version of the generator, reworked by Jun-ichiro itojun Hagino,
+and was introduced in
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/gen/randomid.c b/lib/nbsd_libc/gen/randomid.c
new file mode 100644 (file)
index 0000000..4eb9a3b
--- /dev/null
@@ -0,0 +1,324 @@
+/*     $NetBSD: randomid.c,v 1.13 2009/01/11 02:46:27 christos Exp $   */
+/*     $KAME: ip6_id.c,v 1.8 2003/09/06 13:41:06 itojun Exp $  */
+/*     $OpenBSD: ip_id.c,v 1.6 2002/03/15 18:19:52 millert Exp $       */
+
+/*
+ * Copyright (C) 2003 WIDE Project.
+ * 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.
+ * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
+ */
+
+/*
+ * Copyright 1998 Niels Provos <provos@citi.umich.edu>
+ * All rights reserved.
+ *
+ * Theo de Raadt <deraadt@openbsd.org> came up with the idea of using
+ * such a mathematical system to generate more random (yet non-repeating)
+ * ids to solve the resolver/named problem.  But Niels designed the
+ * actual system based on the constraints.
+ *
+ * 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 ``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 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.
+ */
+
+/*
+ * seed = random (bits - 1) bit
+ * n = prime, g0 = generator to n,
+ * j = random so that gcd(j,n-1) == 1
+ * g = g0^j mod n will be a generator again.
+ *
+ * X[0] = random seed.
+ * X[n] = a*X[n-1]+b mod m is a Linear Congruential Generator
+ * with a = 7^(even random) mod m,
+ *      b = random with gcd(b,m) == 1
+ *      m = constant and a maximal period of m-1.
+ *
+ * The transaction id is determined by:
+ * id[n] = seed xor (g^X[n] mod n)
+ *
+ * Effectivly the id is restricted to the lower (bits - 1) bits, thus
+ * yielding two different cycles by toggling the msb on and off.
+ * This avoids reuse issues caused by reseeding.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: randomid.c,v 1.13 2009/01/11 02:46:27 christos Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/time.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <randomid.h>
+
+#ifdef __weak_alias
+__weak_alias(randomid,_randomid)
+__weak_alias(randomid_new,_randomid_new)
+__weak_alias(randomid_delete,_randomid_delete)
+#endif
+
+struct randomconf {
+       const int       rc_bits; /* resulting bits */
+       const u_int32_t rc_max; /* Uniq cycle, avoid blackjack prediction */
+       const u_int32_t rc_gen; /* Starting generator */
+       const u_int32_t rc_n;   /* ru_n: prime, ru_n - 1: product of pfacts[] */
+       const u_int32_t rc_agen; /* determine ru_a as ru_agen^(2*rand) */
+       const u_int32_t rc_m;   /* ru_m = 2^x*3^y */
+       const u_int32_t rc_pfacts[4];   /* factors of ru_n */
+       const int       rc_skip;        /* skip values */
+};
+
+struct randomid_ctx {
+       struct randomconf *ru_conf;
+#define ru_bits                ru_conf->rc_bits
+#define ru_max         ru_conf->rc_max
+#define ru_gen         ru_conf->rc_gen
+#define ru_n           ru_conf->rc_n
+#define ru_agen                ru_conf->rc_agen
+#define ru_m           ru_conf->rc_m
+#define ru_pfacts      ru_conf->rc_pfacts
+#define ru_skip                ru_conf->rc_skip
+       long ru_out;            /* Time after wich will be reseeded */
+       u_int32_t ru_counter;
+       u_int32_t ru_msb;
+
+       u_int32_t ru_x;
+       u_int32_t ru_seed, ru_seed2;
+       u_int32_t ru_a, ru_b;
+       u_int32_t ru_g;
+       time_t ru_reseed;
+};
+
+static struct randomconf randomconf[] = {
+  {
+       32,                     /* resulting bits */
+       1000000000,             /* Uniq cycle, avoid blackjack prediction */
+       2,                      /* Starting generator */
+       2147483629,             /* RU_N-1 = 2^2*3^2*59652323 */
+       7,                      /* determine ru_a as RU_AGEN^(2*rand) */
+       1836660096,             /* RU_M = 2^7*3^15 - don't change */
+       { 2, 3, 59652323, 0 },  /* factors of ru_n */
+       3,                      /* skip values */
+  },
+  {
+       20,                     /* resulting bits */
+       200000,                 /* Uniq cycle, avoid blackjack prediction */
+       2,                      /* Starting generator */
+       524269,                 /* RU_N-1 = 2^2*3^2*14563 */
+       7,                      /* determine ru_a as RU_AGEN^(2*rand) */
+       279936,                 /* RU_M = 2^7*3^7 - don't change */
+       { 2, 3, 14563, 0 },     /* factors of ru_n */
+       3,                      /* skip values */
+  },
+  {
+       16,                     /* resulting bits */
+       30000,                  /* Uniq cycle, avoid blackjack prediction */
+       2,                      /* Starting generator */
+       32749,                  /* RU_N-1 = 2^2*3*2729 */
+       7,                      /* determine ru_a as RU_AGEN^(2*rand) */
+       31104,                  /* RU_M = 2^7*3^5 - don't change */
+       { 2, 3, 2729, 0 },      /* factors of ru_n */
+       0,                      /* skip values */
+  },
+  {
+       .rc_bits = -1,          /* termination */
+  },
+};
+
+static u_int32_t pmod(u_int32_t, u_int32_t, u_int32_t);
+static void initid(struct randomid_ctx *);
+
+struct randomid_ctx *randomid_new(int, long);
+void randomid_delete(struct randomid_ctx *);
+u_int32_t randomid(struct randomid_ctx *);
+
+/*
+ * Do a fast modular exponation, returned value will be in the range
+ * of 0 - (mod-1)
+ */
+
+static u_int32_t
+pmod(u_int32_t gen, u_int32_t expo, u_int32_t mod)
+{
+       u_int64_t s, t, u;
+
+       s = 1;
+       t = gen;
+       u = expo;
+
+       while (u) {
+               if (u & 1)
+                       s = (s * t) % mod;
+               u >>= 1;
+               t = (t * t) % mod;
+       }
+       return ((u_int32_t)s & UINT32_MAX);
+}
+
+/*
+ * Initalizes the seed and chooses a suitable generator. Also toggles
+ * the msb flag. The msb flag is used to generate two distinct
+ * cycles of random numbers and thus avoiding reuse of ids.
+ *
+ * This function is called from id_randomid() when needed, an
+ * application does not have to worry about it.
+ */
+static void
+initid(struct randomid_ctx *p)
+{
+       u_int32_t j, i;
+       int noprime = 1;
+       struct timeval tv;
+
+       p->ru_x = arc4random() % p->ru_m;
+
+       /* (bits - 1) bits of random seed */
+       p->ru_seed = arc4random() & (~0U >> (32 - p->ru_bits + 1));
+       p->ru_seed2 = arc4random() & (~0U >> (32 - p->ru_bits + 1));
+
+       /* Determine the LCG we use */
+       p->ru_b = (arc4random() & (~0U >> (32 - p->ru_bits))) | 1;
+       p->ru_a = pmod(p->ru_agen,
+           (arc4random() & (~0U >> (32 - p->ru_bits))) & (~1U), p->ru_m);
+       while (p->ru_b % 3 == 0)
+               p->ru_b += 2;
+
+       j = arc4random() % p->ru_n;
+
+       /*
+        * Do a fast gcd(j, RU_N - 1), so we can find a j with
+        * gcd(j, RU_N - 1) == 1, giving a new generator for
+        * RU_GEN^j mod RU_N
+        */
+       while (noprime) {
+               for (i = 0; p->ru_pfacts[i] > 0; i++)
+                       if (j % p->ru_pfacts[i] == 0)
+                               break;
+
+               if (p->ru_pfacts[i] == 0)
+                       noprime = 0;
+               else
+                       j = (j + 1) % p->ru_n;
+       }
+
+       p->ru_g = pmod(p->ru_gen, j, p->ru_n);
+       p->ru_counter = 0;
+
+       gettimeofday(&tv, NULL);
+       p->ru_reseed = tv.tv_sec + p->ru_out;
+       p->ru_msb = p->ru_msb ? 0 : (1U << (p->ru_bits - 1));
+}
+
+struct randomid_ctx *
+randomid_new(int bits, long timeo)
+{
+       struct randomconf *conf;
+       struct randomid_ctx *ctx;
+
+       if (timeo < RANDOMID_TIMEO_MIN) {
+               errno = EINVAL;
+               return (NULL);
+       }
+
+       for (conf = randomconf; conf->rc_bits > 0; conf++) {
+               if (bits == conf->rc_bits)
+                       break;
+       }
+
+       /* unsupported bits */
+       if (bits != conf->rc_bits) {
+               errno = ENOTSUP;
+               return (NULL);
+       }
+
+       ctx = malloc(sizeof(*ctx));
+       if (!ctx)
+               return (NULL);
+
+       memset(ctx, 0, sizeof(*ctx));
+       ctx->ru_conf = conf;
+       ctx->ru_out = timeo;
+
+       return (ctx);
+}
+
+void
+randomid_delete(struct randomid_ctx *ctx)
+{
+
+       memset(ctx, 0, sizeof(*ctx));
+       free(ctx);
+}
+
+u_int32_t
+randomid(struct randomid_ctx *p)
+{
+       int i, n;
+       struct timeval tv;
+
+       gettimeofday(&tv, NULL);
+       if (p->ru_counter >= p->ru_max || tv.tv_sec > p->ru_reseed)
+               initid(p);
+
+       /* Skip a random number of ids */
+       if (p->ru_skip) {
+               n = arc4random() & p->ru_skip;
+               if (p->ru_counter + n >= p->ru_max)
+                       initid(p);
+       } else
+               n = 0;
+
+       for (i = 0; i <= n; i++) {
+               /* Linear Congruential Generator */
+               p->ru_x = (u_int32_t)(((u_int64_t)p->ru_a * p->ru_x + p->ru_b) % p->ru_m);
+       }
+
+       p->ru_counter += i;
+
+       return (p->ru_seed ^ pmod(p->ru_g, p->ru_seed2 + p->ru_x, p->ru_n)) |
+           p->ru_msb;
+}
diff --git a/lib/nbsd_libc/gen/readdir.c b/lib/nbsd_libc/gen/readdir.c
new file mode 100644 (file)
index 0000000..13c3eb0
--- /dev/null
@@ -0,0 +1,143 @@
+/*     $NetBSD: readdir.c,v 1.25 2010/09/16 02:38:50 yamt Exp $        */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)readdir.c  8.3 (Berkeley) 9/29/94";
+#else
+__RCSID("$NetBSD: readdir.c,v 1.25 2010/09/16 02:38:50 yamt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include "extern.h"
+#include <sys/param.h>
+
+#include <dirent.h>
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "dirent_private.h"
+
+/*
+ * get next entry in a directory.
+ */
+struct dirent *
+_readdir_unlocked(DIR *dirp, int skipdeleted)
+{
+       struct dirent *dp;
+
+       for (;;) {
+               if (dirp->dd_loc >= dirp->dd_size) {
+                       if (dirp->dd_flags & __DTF_READALL)
+                               return (NULL);
+                       dirp->dd_loc = 0;
+               }
+               if (dirp->dd_loc == 0 && !(dirp->dd_flags & __DTF_READALL)) {
+                       dirp->dd_seek = lseek(dirp->dd_fd, (off_t)0, SEEK_CUR);
+                       dirp->dd_size = getdents(dirp->dd_fd,
+                           dirp->dd_buf, (size_t)dirp->dd_len);
+                       if (dirp->dd_size <= 0)
+                               return (NULL);
+               }
+               dp = (struct dirent *)
+                   (void *)(dirp->dd_buf + (size_t)dirp->dd_loc);
+               if ((intptr_t)dp & _DIRENT_ALIGN(dp))/* bogus pointer check */
+                       return (NULL);
+               /* d_reclen is unsigned; no need to compare it <= 0 */
+               if (dp->d_reclen > dirp->dd_len + 1 - dirp->dd_loc)
+                       return (NULL);
+               dirp->dd_loc += dp->d_reclen;
+               if (dp->d_ino == 0 && skipdeleted)
+                       continue;
+               if (dp->d_type == DT_WHT && (dirp->dd_flags & DTF_HIDEW))
+                       continue;
+               return (dp);
+       }
+}
+
+struct dirent *
+readdir(dirp)
+       DIR *dirp;
+{
+       struct dirent   *dp;
+
+#ifdef _REENTRANT
+       if (__isthreaded) {
+               mutex_lock((mutex_t *)dirp->dd_lock);
+               dp = _readdir_unlocked(dirp, 1);
+               mutex_unlock((mutex_t *)dirp->dd_lock);
+       }
+       else
+#endif
+               dp = _readdir_unlocked(dirp, 1);
+       return (dp);
+}
+
+int
+readdir_r(dirp, entry, result)
+       DIR *dirp;
+       struct dirent *entry;
+       struct dirent **result;
+{
+       struct dirent *dp;
+       int saved_errno;
+
+       saved_errno = errno;
+       errno = 0;
+#ifdef _REENTRANT
+       if (__isthreaded) {
+               mutex_lock((mutex_t *)dirp->dd_lock);
+               if ((dp = _readdir_unlocked(dirp, 1)) != NULL)
+                       memcpy(entry, dp, (size_t)_DIRENT_SIZE(dp));
+               mutex_unlock((mutex_t *)dirp->dd_lock);
+       }
+       else 
+#endif
+               if ((dp = _readdir_unlocked(dirp, 1)) != NULL)
+                       memcpy(entry, dp, (size_t)_DIRENT_SIZE(dp));
+
+       if (errno != 0) {
+               if (dp == NULL)
+                       return (errno);
+       } else
+               errno = saved_errno;
+
+       if (dp != NULL)
+               *result = entry;
+       else
+               *result = NULL;
+
+       return (0);
+}
diff --git a/lib/nbsd_libc/gen/realpath.3 b/lib/nbsd_libc/gen/realpath.3
new file mode 100644 (file)
index 0000000..37cff78
--- /dev/null
@@ -0,0 +1,120 @@
+.\"    $NetBSD: realpath.3,v 1.12 2005/08/13 19:53:53 elad Exp $
+.\"
+.\" Copyright (c) 1994
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Jan-Simon Pendry.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)realpath.3   8.2 (Berkeley) 2/16/94
+.\"
+.Dd August 13, 2005
+.Dt REALPATH 3
+.Os
+.Sh NAME
+.Nm realpath
+.Nd returns the canonicalized absolute pathname
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/param.h
+.In stdlib.h
+.Ft "char *"
+.Fn realpath "const char *pathname" "char resolvedname[MAXPATHLEN]"
+.Sh DESCRIPTION
+The
+.Fn realpath
+function resolves all symbolic links, extra
+.Dq /
+characters and references to
+.Pa /./
+and
+.Pa /../
+in
+.Fa pathname ,
+and copies the resulting absolute pathname into
+the memory referenced by
+.Fa resolvedname .
+The
+.Fa resolvedname
+argument
+.Em must
+refer to a buffer capable of storing at least
+.Dv MAXPATHLEN
+characters.
+.Pp
+The
+.Fn realpath
+function will resolve both absolute and relative paths
+and return the absolute pathname corresponding to
+.Fa pathname .
+.Sh RETURN VALUES
+The
+.Fn realpath
+function returns
+.Fa resolvedname
+on success.
+If an error occurs,
+.Fn realpath
+returns
+.Dv NULL ,
+and
+.Fa resolvedname
+contains the pathname which caused the problem.
+.Sh ERRORS
+The function
+.Fn realpath
+may fail and set the external variable
+.Va errno
+for any of the errors specified for the library functions
+.Xr chdir 2 ,
+.Xr close 2 ,
+.Xr fchdir 2 ,
+.Xr lstat 2 ,
+.Xr open 2 ,
+.Xr readlink 2
+and
+.Xr getcwd 3 .
+.Sh SEE ALSO
+.Xr getcwd 3
+.Sh HISTORY
+The
+.Fn realpath
+function call first appeared in
+.Bx 4.4 .
+.Sh BUGS
+This implementation of
+.Fn realpath
+differs slightly from the Solaris implementation.
+The
+.Bx 4.4
+version always returns absolute pathnames,
+whereas the Solaris implementation will,
+under certain circumstances, return a relative
+.Fa resolvedname
+when given a relative
+.Fa pathname .
diff --git a/lib/nbsd_libc/gen/rewinddir.c b/lib/nbsd_libc/gen/rewinddir.c
new file mode 100644 (file)
index 0000000..a166852
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: rewinddir.c,v 1.13 2010/09/26 02:26:59 yamt Exp $      */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)rewinddir.c        8.1 (Berkeley) 6/8/93";
+#else
+__RCSID("$NetBSD: rewinddir.c,v 1.13 2010/09/26 02:26:59 yamt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include "extern.h"
+#include <sys/types.h>
+
+#include <unistd.h>
+#include <dirent.h>
+
+#include "dirent_private.h"
+
+#ifdef __weak_alias
+__weak_alias(rewinddir,_rewinddir)
+#endif
+
+void
+rewinddir(DIR *dirp)
+{
+       int fd;
+
+#ifdef _REENTRANT
+       if (__isthreaded) {
+               mutex_lock((mutex_t *)dirp->dd_lock);
+       }
+#endif
+       fd = dirp->dd_fd;
+       _finidir(dirp);
+       dirp->dd_seek = lseek(fd, (off_t)0, SEEK_SET);
+       _initdir(dirp, fd, NULL);
+#ifdef _REENTRANT
+       if (__isthreaded) {
+               mutex_unlock((mutex_t *)dirp->dd_lock);
+       }
+#endif
+}
diff --git a/lib/nbsd_libc/gen/scandir.3 b/lib/nbsd_libc/gen/scandir.3
new file mode 100644 (file)
index 0000000..01d88b2
--- /dev/null
@@ -0,0 +1,113 @@
+.\"    $NetBSD: scandir.3,v 1.14 2010/12/17 19:20:42 njoly Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)scandir.3  8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 29, 2010
+.Dt SCANDIR 3
+.Os
+.Sh NAME
+.Nm scandir ,
+.Nm alphasort
+.Nd scan a directory
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In dirent.h
+.Ft int
+.Fn scandir "const char *dirname" "struct dirent ***namelist" "int \*(lp*select\*(rp\*(lpconst struct dirent *\*(rp" "int \*(lp*compar\*(rp\*(lpconst void *, const void *\*(rp"
+.Ft int
+.Fn alphasort "const void *d1" "const void *d2"
+.Sh DESCRIPTION
+The
+.Fn scandir
+function
+reads the directory
+.Fa dirname
+and builds an array of pointers to directory
+entries using
+.Xr malloc 3 .
+It returns the number of entries in the array.
+A pointer to the array of directory entries is stored in the location
+referenced by
+.Fa namelist .
+.Pp
+The
+.Fa select
+parameter is a pointer to a user supplied subroutine which is called by
+.Fn scandir
+to select which entries are to be included in the array.
+The select routine is passed a
+pointer to a directory entry and should return a non-zero
+value if the directory entry is to be included in the array.
+If
+.Fa select
+is null, then all the directory entries will be included.
+.Pp
+The
+.Fa compar
+parameter is a pointer to a user supplied subroutine which is passed to
+.Xr qsort 3
+to sort the completed array.
+If this pointer is null, the array is not sorted.
+.Pp
+The
+.Fn alphasort
+function
+is a routine which can be used for the
+.Fa compar
+parameter to sort the array alphabetically.
+.Pp
+The memory allocated for the array can be deallocated with
+.Xr free 3 ,
+by freeing each pointer in the array and then the array itself.
+.Sh DIAGNOSTICS
+Returns \-1 if the directory cannot be opened for reading or if
+.Xr malloc 3
+cannot allocate enough memory to hold all the data structures.
+.Sh SEE ALSO
+.Xr directory 3 ,
+.Xr dirent 3 ,
+.Xr malloc 3 ,
+.Xr qsort 3
+.Sh STANDARDS
+The
+.Fn scandir
+and
+.Fn alphasort
+functions conform to
+.St -p1003.1-2008 .
+.Sh HISTORY
+The
+.Fn scandir
+and
+.Fn alphasort
+functions appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/gen/scandir.c b/lib/nbsd_libc/gen/scandir.c
new file mode 100644 (file)
index 0000000..d894429
--- /dev/null
@@ -0,0 +1,151 @@
+/*     $NetBSD: scandir.c,v 1.26 2007/06/09 23:57:25 christos Exp $    */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)scandir.c  8.3 (Berkeley) 1/2/94";
+#else
+__RCSID("$NetBSD: scandir.c,v 1.26 2007/06/09 23:57:25 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Scan the directory dirname calling selectfn to make a list of selected
+ * directory entries then sort using qsort and compare routine dcomp.
+ * Returns the number of entries and a pointer to a list of pointers to
+ * struct dirent (through namelist). Returns -1 if there were any errors.
+ */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <dirent.h>
+#include <stdlib.h>
+#include <string.h>
+
+/*
+ * Compute an estimate of the number of entries in a directory based on
+ * the file size. Returns the estimated number of entries or 0 on failure.
+ */
+static size_t
+dirsize(int fd, size_t olen)
+{
+       struct stat stb;
+       size_t nlen;
+
+       if (fstat(fd, &stb) == -1)
+               return 0;
+       /*
+        * Estimate the array size by taking the size of the directory file
+        * and dividing it by a multiple of the minimum size entry. 
+        */
+       nlen = (size_t)(stb.st_size / _DIRENT_MINSIZE((struct dirent *)0));
+       /*
+        * If the size turns up 0, switch to an alternate strategy and use the
+        * file size as the number of entries like ZFS returns. If that turns
+        * out to be 0 too return a minimum of 10 entries, plus the old length.
+        */
+       if (nlen == 0)
+               nlen = (size_t)(stb.st_size ? stb.st_size : 10);
+       return olen + nlen;
+}
+
+int
+scandir(const char *dirname, struct dirent ***namelist,
+    int (*selectfn)(const struct dirent *),
+    int (*dcomp)(const void *, const void *))
+{
+       struct dirent *d, *p, **names, **newnames;
+       size_t nitems, arraysz;
+       DIR *dirp;
+
+       _DIAGASSERT(dirname != NULL);
+       _DIAGASSERT(namelist != NULL);
+
+       if ((dirp = opendir(dirname)) == NULL)
+               return -1;
+
+       if ((arraysz = dirsize(dirp->dd_fd, 0)) == 0)
+               goto bad;
+
+       names = malloc(arraysz * sizeof(*names));
+       if (names == NULL)
+               goto bad;
+
+       nitems = 0;
+       while ((d = readdir(dirp)) != NULL) {
+               if (selectfn != NULL && !(*selectfn)(d))
+                       continue;       /* just selected names */
+
+               /*
+                * Check to make sure the array has space left and
+                * realloc the maximum size.
+                */
+               if (nitems >= arraysz) {
+                       if ((arraysz = dirsize(dirp->dd_fd, arraysz)) == 0)
+                               goto bad2;
+                       newnames = realloc(names, arraysz * sizeof(*names));
+                       if (newnames == NULL)
+                               goto bad2;
+                       names = newnames;
+               }
+
+               /*
+                * Make a minimum size copy of the data
+                */
+               p = malloc((size_t)_DIRENT_SIZE(d));
+               if (p == NULL)
+                       goto bad2;
+               p->d_fileno = d->d_fileno;
+               p->d_reclen = d->d_reclen;
+               p->d_type = d->d_type;
+               p->d_namlen = d->d_namlen;
+               (void)memmove(p->d_name, d->d_name, (size_t)(p->d_namlen + 1));
+               names[nitems++] = p;
+       }
+       (void)closedir(dirp);
+       if (nitems && dcomp != NULL)
+               qsort(names, nitems, sizeof(*names), dcomp);
+       *namelist = names;
+       return nitems;
+
+bad2:
+       while (nitems-- > 0)
+               free(names[nitems]);
+       free(names);
+bad:
+       (void)closedir(dirp);
+       return -1;
+}
diff --git a/lib/nbsd_libc/gen/seekdir.c b/lib/nbsd_libc/gen/seekdir.c
new file mode 100644 (file)
index 0000000..e70eba6
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: seekdir.c,v 1.14 2006/05/17 20:36:50 christos Exp $    */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)seekdir.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: seekdir.c,v 1.14 2006/05/17 20:36:50 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include "extern.h"
+#include <sys/param.h>
+
+#include <dirent.h>
+
+#include "dirent_private.h"
+
+#ifdef __weak_alias
+__weak_alias(seekdir,_seekdir)
+#endif
+
+/*
+ * Seek to an entry in a directory.
+ * _seekdir_unlocked is in telldir.c so that it can share opaque data structures.
+ */
+void
+seekdir(DIR *dirp, long loc)
+{
+
+#ifdef _REENTRANT
+       if (__isthreaded) {
+               mutex_lock((mutex_t *)dirp->dd_lock);
+               _seekdir_unlocked(dirp, loc);
+               mutex_unlock((mutex_t *)dirp->dd_lock);
+       } else
+#endif
+               _seekdir_unlocked(dirp, loc);
+}
diff --git a/lib/nbsd_libc/gen/setdomainname.c b/lib/nbsd_libc/gen/setdomainname.c
new file mode 100644 (file)
index 0000000..8ec82bb
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: setdomainname.c,v 1.12 2003/08/07 16:42:56 agc Exp $   */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)sethostname.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: setdomainname.c,v 1.12 2003/08/07 16:42:56 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/sysctl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(setdomainname,_setdomainname)
+#endif
+
+int
+setdomainname(name, namelen)
+       const char *name;
+       size_t namelen;
+{
+       int mib[2];
+
+       _DIAGASSERT(name != NULL);
+
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_DOMAINNAME;
+       if (sysctl(mib, 2, NULL, NULL, name, namelen) == -1)
+               return (-1);
+       return (0);
+}
diff --git a/lib/nbsd_libc/gen/sethostname.c b/lib/nbsd_libc/gen/sethostname.c
new file mode 100644 (file)
index 0000000..9ff569f
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: sethostname.c,v 1.12 2003/08/07 16:42:56 agc Exp $     */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)sethostname.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: sethostname.c,v 1.12 2003/08/07 16:42:56 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/sysctl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(sethostname,_sethostname)
+#endif
+
+int
+sethostname(name, namelen)
+       const char *name;
+       size_t namelen;
+{
+       int mib[2];
+
+       _DIAGASSERT(name != NULL);
+
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_HOSTNAME;
+       if (sysctl(mib, 2, NULL, NULL, name, namelen) == -1)
+               return (-1);
+       return (0);
+}
diff --git a/lib/nbsd_libc/gen/setjmp.3 b/lib/nbsd_libc/gen/setjmp.3
new file mode 100644 (file)
index 0000000..2c4b389
--- /dev/null
@@ -0,0 +1,229 @@
+.\"    $NetBSD: setjmp.3,v 1.17 2008/05/31 16:15:07 enami Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)setjmp.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 1, 2008
+.Dt SETJMP 3
+.Os
+.Sh NAME
+.Nm sigsetjmp ,
+.Nm siglongjmp ,
+.Nm setjmp ,
+.Nm longjmp ,
+.Nm _setjmp ,
+.Nm _longjmp ,
+.Nm longjmperror
+.Nd non-local jumps
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In setjmp.h
+.Ft int
+.Fn sigsetjmp "sigjmp_buf env" "int savemask"
+.Ft void
+.Fn siglongjmp "sigjmp_buf env" "int val"
+.Ft int
+.Fn setjmp "jmp_buf env"
+.Ft void
+.Fn longjmp "jmp_buf env" "int val"
+.Ft int
+.Fn _setjmp "jmp_buf env"
+.Ft void
+.Fn _longjmp "jmp_buf env" "int val"
+.Ft void
+.Fn longjmperror void
+.Sh DESCRIPTION
+The
+.Fn sigsetjmp ,
+.Fn setjmp ,
+and
+.Fn _setjmp
+functions save their calling environment in
+.Fa env .
+Each of these functions returns 0.
+.Pp
+The corresponding
+.Fn longjmp
+functions restore the environment saved by the most recent
+invocation of the respective
+.Fn setjmp
+function.
+They then return so that program execution continues as if the corresponding
+invocation of the
+.Fn setjmp
+call had just returned the value specified by
+.Fa val ,
+instead of 0.
+.Pp
+Pairs of calls may be intermixed, i.e., both
+.Fn sigsetjmp
+and
+.Fn siglongjmp
+as well as
+.Fn setjmp
+and
+.Fn longjmp
+combinations may be used in the same program.
+However, individual calls may not, e.g., the
+.Fa env
+argument to
+.Fn setjmp
+may not be passed to
+.Fn siglongjmp .
+.Pp
+The
+.Fn longjmp
+routines may not be called after the routine which called the
+.Fn setjmp
+routines returns.
+.Pp
+All accessible objects have values as of the time
+.Fn longjmp
+routine was called, except that the values of objects of automatic storage
+invocation duration that do not have the
+.Li volatile
+type and have been changed between the
+.Fn setjmp
+invocation and
+.Fn longjmp
+call are indeterminate.
+.Pp
+The
+.Fn setjmp Ns / Ns Fn longjmp
+function pairs save and restore the signal mask while
+.Fn _setjmp Ns / Ns Fn _longjmp
+function pairs save and restore only the register set and the stack.
+(See
+.Fn sigprocmask 2 . )
+.Pp
+The
+.Fn sigsetjmp Ns / Ns Fn siglongjmp
+function pairs save and restore the signal mask if the argument
+.Fa savemask
+is non-zero.
+Otherwise, only the register set and the stack are saved.
+.Pp
+In other words,
+.Fn setjmp Ns / Ns Fn longjmp
+are functionally equivalent to
+.Fn sigsetjmp Ns / Ns Fn siglongjmp
+when
+.Fn sigsetjmp
+is called with a non-zero
+.Fa savemask
+argument.
+Conversely,
+.Fn _setjmp Ns / Ns Fn _longjmp
+are functionally equivalent to
+.Fn sigsetjmp Ns / Ns Fn siglongjmp
+when
+.Fn sigsetjmp
+is called with a zero-value
+.Fa savemask .
+.Pp
+The
+.Fn sigsetjmp Ns / Ns Fn siglongjmp
+interfaces are preferred for maximum portability.
+.Sh ERRORS
+If the contents of the
+.Fa env
+are corrupted or correspond to an environment that has already returned,
+the
+.Fn longjmp
+routine calls the routine
+.Xr longjmperror 3 .
+If
+.Fn longjmperror
+returns, the program is aborted (see
+.Xr abort 3 ) .
+The default version of
+.Fn longjmperror
+prints the message
+.Dq Li longjmp botch
+to standard error and returns.
+User programs wishing to exit more gracefully should write their own
+versions of
+.Fn longjmperror .
+.Sh SEE ALSO
+.Xr sigaction 2 ,
+.Xr sigaltstack 2 ,
+.Xr sigprocmask 2 ,
+.Xr pthread_sigmask 3 ,
+.Xr signal 3
+.Sh STANDARDS
+The
+.Fn setjmp
+and
+.Fn longjmp
+functions conform to
+.St -ansiC .
+The
+.Fn sigsetjmp
+and
+.Fn siglongjmp
+functions conform to
+.St -p1003.1-90 .
+.Sh CAVEATS
+Historically, on
+.At V ,
+the
+.Fn setjmp Ns / Ns Fn longjmp
+functions have been equivalent to the
+.Bx
+.Fn _setjmp Ns / Ns Fn _longjmp
+functions and do not restore the signal mask.
+Because of this discrepancy, the
+.Fn sigsetjmp Ns / Ns Fn siglongjmp
+interfaces should be used if portability is desired.
+.Pp
+Use of
+.Fn longjmp
+or
+.Fn siglongjmp
+from inside a signal handler is not as easy as it might seem.
+Generally speaking, all possible code paths between the
+.Fn setjmp
+and
+.Fn longjmp
+must be signal race safe.
+Furthermore, the code paths must not do resource management
+(such as
+.Xr open 2
+or
+.Xr close 2 )
+without blocking the signal in question, or resources might
+be mismanaged.
+Obviously this makes
+.Fn longjmp
+much less useful than previously thought.
diff --git a/lib/nbsd_libc/gen/setjmperr.c b/lib/nbsd_libc/gen/setjmperr.c
new file mode 100644 (file)
index 0000000..f47eb87
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: setjmperr.c,v 1.7 2003/08/07 16:42:56 agc Exp $        */
+
+/*
+ * Copyright (c) 1980, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)setjmperr.c        8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: setjmperr.c,v 1.7 2003/08/07 16:42:56 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * This routine is called from longjmp() when an error occurs.
+ * Programs that wish to exit gracefully from this error may
+ * write their own versions.
+ * If this routine returns, the program is aborted.
+ */
+
+#include <setjmp.h>
+#include <unistd.h>
+
+void
+longjmperror()
+{
+#define        ERRMSG  "longjmp botch.\n"
+       (void)write(STDERR_FILENO, ERRMSG, sizeof(ERRMSG) - 1);
+}
diff --git a/lib/nbsd_libc/gen/setmode.3 b/lib/nbsd_libc/gen/setmode.3
new file mode 100644 (file)
index 0000000..9c131d2
--- /dev/null
@@ -0,0 +1,150 @@
+.\"    $NetBSD: setmode.3,v 1.21 2009/01/11 02:46:27 christos Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)setmode.3  8.2 (Berkeley) 4/28/95
+.\"
+.Dd January 4, 2009
+.Dt SETMODE 3
+.Os
+.Sh NAME
+.Nm getmode ,
+.Nm setmode
+.Nd modify mode bits
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft void *
+.Fn setmode "const char *mode_str"
+.Ft mode_t
+.Fn getmode "const void *set" "mode_t mode"
+.Sh DESCRIPTION
+The
+.Fn setmode
+function accepts a string representation of a file mode change,
+compiles it to binary form, and returns an abstract representation
+that may be passed to
+.Fn getmode .
+The string may be an numeric (octal) or symbolic string of the form
+accepted by
+.Xr chmod 1 ,
+and may represent either an exact mode to set or a change to make to
+the existing mode.
+.Pp
+The
+.Fn getmode
+function
+adjusts the file permission bits given by
+.Fa mode
+according to the compiled change representation
+.Fa set ,
+and returns the adjusted mode.
+While only the permission bits are altered, other parts of the file
+mode, particularly the type, may be examined.
+.Pp
+Because some of the possible symbolic values are defined relative to
+the file creation mask,
+.Fn setmode
+may call
+.Xr umask 2 ,
+temporarily changing the mask.
+If this occurs, the file creation mask will be restored before
+.Fn setmode
+returns.
+If the calling program changes the value of its file creation mask
+after calling
+.Fn setmode ,
+.Fn setmode
+must be called again to recompile the mode string if
+.Fn getmode
+is to modify future file modes correctly.
+.Pp
+If the mode passed to
+.Fn setmode
+is invalid,
+.Fn setmode
+returns
+.Dv NULL .
+.Sh EXAMPLES
+The effects of the shell command
+.Ql "chmod a+x myscript.sh"
+can be duplicated as follows:
+.Bd -literal -offset indent
+const char *file = "myscript.sh";
+struct stat st;
+mode_t newmode;
+
+stat(file, \*[Am]st);
+newmode = getmode(setmode("a+x"), st.st_mode);
+chmod(file, newmode);
+.Ed
+.Sh ERRORS
+The
+.Fn setmode
+function
+may fail and set
+.Va errno
+for any of the errors specified for the library routines
+.Xr malloc 3
+or
+.Xr strtol 3 .
+In addition,
+.Fn setmode
+will fail and set
+.Va errno
+to:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa mode
+argument does not represent a valid mode.
+.El
+.Sh SEE ALSO
+.Xr chmod 1 ,
+.Xr stat 2 ,
+.Xr umask 2 ,
+.Xr malloc 3
+.Sh HISTORY
+The
+.Fn getmode
+and
+.Fn setmode
+functions first appeared in
+.Bx 4.4 .
+.Sh BUGS
+Each call to
+.Nm setmode
+allocates a small amount of memory that there is no correct way to
+free.
+.Pp
+The type of
+.Fa set
+should really be some opaque struct type used only by these functions
+rather than
+.Ft void * .
diff --git a/lib/nbsd_libc/gen/setmode.c b/lib/nbsd_libc/gen/setmode.c
new file mode 100644 (file)
index 0000000..83dd752
--- /dev/null
@@ -0,0 +1,492 @@
+/*     $NetBSD: setmode.c,v 1.31 2005/10/01 20:08:01 christos Exp $    */
+
+/*
+ * Copyright (c) 1989, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Dave Borman at Cray Research, 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)setmode.c  8.2 (Berkeley) 3/25/94";
+#else
+__RCSID("$NetBSD: setmode.c,v 1.31 2005/10/01 20:08:01 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <unistd.h>
+
+#ifdef SETMODE_DEBUG
+#include <stdio.h>
+#endif
+
+#ifdef __weak_alias
+__weak_alias(getmode,_getmode)
+__weak_alias(setmode,_setmode)
+#endif
+
+#define        SET_LEN 6               /* initial # of bitcmd struct to malloc */
+#define        SET_LEN_INCR 4          /* # of bitcmd structs to add as needed */
+
+typedef struct bitcmd {
+       char    cmd;
+       char    cmd2;
+       mode_t  bits;
+} BITCMD;
+
+#define        CMD2_CLR        0x01
+#define        CMD2_SET        0x02
+#define        CMD2_GBITS      0x04
+#define        CMD2_OBITS      0x08
+#define        CMD2_UBITS      0x10
+
+static BITCMD  *addcmd __P((BITCMD *, mode_t, mode_t, mode_t, mode_t));
+static void     compress_mode __P((BITCMD *));
+#ifdef SETMODE_DEBUG
+static void     dumpmode __P((BITCMD *));
+#endif
+
+/*
+ * Given the old mode and an array of bitcmd structures, apply the operations
+ * described in the bitcmd structures to the old mode, and return the new mode.
+ * Note that there is no '=' command; a strict assignment is just a '-' (clear
+ * bits) followed by a '+' (set bits).
+ */
+mode_t
+getmode(bbox, omode)
+       const void *bbox;
+       mode_t omode;
+{
+       const BITCMD *set;
+       mode_t clrval, newmode, value;
+
+       _DIAGASSERT(bbox != NULL);
+
+       set = (const BITCMD *)bbox;
+       newmode = omode;
+       for (value = 0;; set++)
+               switch(set->cmd) {
+               /*
+                * When copying the user, group or other bits around, we "know"
+                * where the bits are in the mode so that we can do shifts to
+                * copy them around.  If we don't use shifts, it gets real
+                * grundgy with lots of single bit checks and bit sets.
+                */
+               case 'u':
+                       value = (newmode & S_IRWXU) >> 6;
+                       goto common;
+
+               case 'g':
+                       value = (newmode & S_IRWXG) >> 3;
+                       goto common;
+
+               case 'o':
+                       value = newmode & S_IRWXO;
+common:                        if (set->cmd2 & CMD2_CLR) {
+                               clrval =
+                                   (set->cmd2 & CMD2_SET) ?  S_IRWXO : value;
+                               if (set->cmd2 & CMD2_UBITS)
+                                       newmode &= ~((clrval<<6) & set->bits);
+                               if (set->cmd2 & CMD2_GBITS)
+                                       newmode &= ~((clrval<<3) & set->bits);
+                               if (set->cmd2 & CMD2_OBITS)
+                                       newmode &= ~(clrval & set->bits);
+                       }
+                       if (set->cmd2 & CMD2_SET) {
+                               if (set->cmd2 & CMD2_UBITS)
+                                       newmode |= (value<<6) & set->bits;
+                               if (set->cmd2 & CMD2_GBITS)
+                                       newmode |= (value<<3) & set->bits;
+                               if (set->cmd2 & CMD2_OBITS)
+                                       newmode |= value & set->bits;
+                       }
+                       break;
+
+               case '+':
+                       newmode |= set->bits;
+                       break;
+
+               case '-':
+                       newmode &= ~set->bits;
+                       break;
+
+               case 'X':
+                       if (omode & (S_IFDIR|S_IXUSR|S_IXGRP|S_IXOTH))
+                               newmode |= set->bits;
+                       break;
+
+               case '\0':
+               default:
+#ifdef SETMODE_DEBUG
+                       (void)printf("getmode:%04o -> %04o\n", omode, newmode);
+#endif
+                       return (newmode);
+               }
+}
+
+#define        ADDCMD(a, b, c, d) do {                                         \
+       if (set >= endset) {                                            \
+               BITCMD *newset;                                         \
+               setlen += SET_LEN_INCR;                                 \
+               newset = realloc(saveset, sizeof(BITCMD) * setlen);     \
+               if (newset == NULL)                                     \
+                       goto out;                                       \
+               set = newset + (set - saveset);                         \
+               saveset = newset;                                       \
+               endset = newset + (setlen - 2);                         \
+       }                                                               \
+       set = addcmd(set, (mode_t)(a), (mode_t)(b), (mode_t)(c), (d));  \
+} while (/*CONSTCOND*/0)
+
+#define        STANDARD_BITS   (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
+
+void *
+setmode(p)
+       const char *p;
+{
+       int serrno;
+       char op, *ep;
+       BITCMD *set, *saveset, *endset;
+       sigset_t signset, sigoset;
+       mode_t mask, perm, permXbits, who;
+       long lval;
+       int equalopdone = 0;    /* pacify gcc */
+       int setlen;
+
+       if (!*p) {
+               errno = EINVAL;
+               return NULL;
+       }
+
+       /*
+        * Get a copy of the mask for the permissions that are mask relative.
+        * Flip the bits, we want what's not set.  Since it's possible that
+        * the caller is opening files inside a signal handler, protect them
+        * as best we can.
+        */
+       sigfillset(&signset);
+       (void)sigprocmask(SIG_BLOCK, &signset, &sigoset);
+       (void)umask(mask = umask(0));
+       mask = ~mask;
+       (void)sigprocmask(SIG_SETMASK, &sigoset, NULL);
+
+       setlen = SET_LEN + 2;
+       
+       if ((set = malloc((u_int)(sizeof(BITCMD) * setlen))) == NULL)
+               return (NULL);
+       saveset = set;
+       endset = set + (setlen - 2);
+
+       /*
+        * If an absolute number, get it and return; disallow non-octal digits
+        * or illegal bits.
+        */
+       if (isdigit((unsigned char)*p)) {
+               errno = 0;
+               lval = strtol(p, &ep, 8);
+               if (*ep) {
+                       errno = EINVAL;
+                       goto out;
+               }
+               if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
+                       goto out;
+               if (lval & ~(STANDARD_BITS|S_ISTXT)) {
+                       errno = EINVAL;
+                       goto out;
+               }
+               perm = (mode_t)lval;
+               ADDCMD('=', (STANDARD_BITS|S_ISTXT), perm, mask);
+               set->cmd = 0;
+               return (saveset);
+       }
+
+       /*
+        * Build list of structures to set/clear/copy bits as described by
+        * each clause of the symbolic mode.
+        */
+       for (;;) {
+               /* First, find out which bits might be modified. */
+               for (who = 0;; ++p) {
+                       switch (*p) {
+                       case 'a':
+                               who |= STANDARD_BITS;
+                               break;
+                       case 'u':
+                               who |= S_ISUID|S_IRWXU;
+                               break;
+                       case 'g':
+                               who |= S_ISGID|S_IRWXG;
+                               break;
+                       case 'o':
+                               who |= S_IRWXO;
+                               break;
+                       default:
+                               goto getop;
+                       }
+               }
+
+getop:         if ((op = *p++) != '+' && op != '-' && op != '=') {
+                       errno = EINVAL;
+                       goto out;
+               }
+               if (op == '=')
+                       equalopdone = 0;
+
+               who &= ~S_ISTXT;
+               for (perm = 0, permXbits = 0;; ++p) {
+                       switch (*p) {
+                       case 'r':
+                               perm |= S_IRUSR|S_IRGRP|S_IROTH;
+                               break;
+                       case 's':
+                               /*
+                                * If specific bits where requested and 
+                                * only "other" bits ignore set-id. 
+                                */
+                               if (who == 0 || (who & ~S_IRWXO))
+                                       perm |= S_ISUID|S_ISGID;
+                               break;
+                       case 't':
+                               /*
+                                * If specific bits where requested and 
+                                * only "other" bits ignore set-id. 
+                                */
+                               if (who == 0 || (who & ~S_IRWXO)) {
+                                       who |= S_ISTXT;
+                                       perm |= S_ISTXT;
+                               }
+                               break;
+                       case 'w':
+                               perm |= S_IWUSR|S_IWGRP|S_IWOTH;
+                               break;
+                       case 'X':
+                               permXbits = S_IXUSR|S_IXGRP|S_IXOTH;
+                               break;
+                       case 'x':
+                               perm |= S_IXUSR|S_IXGRP|S_IXOTH;
+                               break;
+                       case 'u':
+                       case 'g':
+                       case 'o':
+                               /*
+                                * When ever we hit 'u', 'g', or 'o', we have
+                                * to flush out any partial mode that we have,
+                                * and then do the copying of the mode bits.
+                                */
+                               if (perm) {
+                                       ADDCMD(op, who, perm, mask);
+                                       perm = 0;
+                               }
+                               if (op == '=')
+                                       equalopdone = 1;
+                               if (op == '+' && permXbits) {
+                                       ADDCMD('X', who, permXbits, mask);
+                                       permXbits = 0;
+                               }
+                               ADDCMD(*p, who, op, mask);
+                               break;
+
+                       default:
+                               /*
+                                * Add any permissions that we haven't already
+                                * done.
+                                */
+                               if (perm || (op == '=' && !equalopdone)) {
+                                       if (op == '=')
+                                               equalopdone = 1;
+                                       ADDCMD(op, who, perm, mask);
+                                       perm = 0;
+                               }
+                               if (permXbits) {
+                                       ADDCMD('X', who, permXbits, mask);
+                                       permXbits = 0;
+                               }
+                               goto apply;
+                       }
+               }
+
+apply:         if (!*p)
+                       break;
+               if (*p != ',')
+                       goto getop;
+               ++p;
+       }
+       set->cmd = 0;
+#ifdef SETMODE_DEBUG
+       (void)printf("Before compress_mode()\n");
+       dumpmode(saveset);
+#endif
+       compress_mode(saveset);
+#ifdef SETMODE_DEBUG
+       (void)printf("After compress_mode()\n");
+       dumpmode(saveset);
+#endif
+       return (saveset);
+out:
+       serrno = errno;
+       free(saveset);
+       errno = serrno;
+       return NULL;
+}
+
+static BITCMD *
+addcmd(set, op, who, oparg, mask)
+       BITCMD *set;
+       mode_t oparg, who, op, mask;
+{
+
+       _DIAGASSERT(set != NULL);
+
+       switch (op) {
+       case '=':
+               set->cmd = '-';
+               set->bits = who ? who : STANDARD_BITS;
+               set++;
+
+               op = '+';
+               /* FALLTHROUGH */
+       case '+':
+       case '-':
+       case 'X':
+               set->cmd = op;
+               set->bits = (who ? who : mask) & oparg;
+               break;
+
+       case 'u':
+       case 'g':
+       case 'o':
+               set->cmd = op;
+               if (who) {
+                       set->cmd2 = ((who & S_IRUSR) ? CMD2_UBITS : 0) |
+                                   ((who & S_IRGRP) ? CMD2_GBITS : 0) |
+                                   ((who & S_IROTH) ? CMD2_OBITS : 0);
+                       set->bits = (mode_t)~0;
+               } else {
+                       set->cmd2 = CMD2_UBITS | CMD2_GBITS | CMD2_OBITS;
+                       set->bits = mask;
+               }
+       
+               if (oparg == '+')
+                       set->cmd2 |= CMD2_SET;
+               else if (oparg == '-')
+                       set->cmd2 |= CMD2_CLR;
+               else if (oparg == '=')
+                       set->cmd2 |= CMD2_SET|CMD2_CLR;
+               break;
+       }
+       return (set + 1);
+}
+
+#ifdef SETMODE_DEBUG
+static void
+dumpmode(set)
+       BITCMD *set;
+{
+
+       _DIAGASSERT(set != NULL);
+
+       for (; set->cmd; ++set)
+               (void)printf("cmd: '%c' bits %04o%s%s%s%s%s%s\n",
+                   set->cmd, set->bits, set->cmd2 ? " cmd2:" : "",
+                   set->cmd2 & CMD2_CLR ? " CLR" : "",
+                   set->cmd2 & CMD2_SET ? " SET" : "",
+                   set->cmd2 & CMD2_UBITS ? " UBITS" : "",
+                   set->cmd2 & CMD2_GBITS ? " GBITS" : "",
+                   set->cmd2 & CMD2_OBITS ? " OBITS" : "");
+}
+#endif
+
+/*
+ * Given an array of bitcmd structures, compress by compacting consecutive
+ * '+', '-' and 'X' commands into at most 3 commands, one of each.  The 'u',
+ * 'g' and 'o' commands continue to be separate.  They could probably be 
+ * compacted, but it's not worth the effort.
+ */
+static void
+compress_mode(set)
+       BITCMD *set;
+{
+       BITCMD *nset;
+       int setbits, clrbits, Xbits, op;
+
+       _DIAGASSERT(set != NULL);
+
+       for (nset = set;;) {
+               /* Copy over any 'u', 'g' and 'o' commands. */
+               while ((op = nset->cmd) != '+' && op != '-' && op != 'X') {
+                       *set++ = *nset++;
+                       if (!op)
+                               return;
+               }
+
+               for (setbits = clrbits = Xbits = 0;; nset++) {
+                       if ((op = nset->cmd) == '-') {
+                               clrbits |= nset->bits;
+                               setbits &= ~nset->bits;
+                               Xbits &= ~nset->bits;
+                       } else if (op == '+') {
+                               setbits |= nset->bits;
+                               clrbits &= ~nset->bits;
+                               Xbits &= ~nset->bits;
+                       } else if (op == 'X')
+                               Xbits |= nset->bits & ~setbits;
+                       else
+                               break;
+               }
+               if (clrbits) {
+                       set->cmd = '-';
+                       set->cmd2 = 0;
+                       set->bits = clrbits;
+                       set++;
+               }
+               if (setbits) {
+                       set->cmd = '+';
+                       set->cmd2 = 0;
+                       set->bits = setbits;
+                       set++;
+               }
+               if (Xbits) {
+                       set->cmd = 'X';
+                       set->cmd2 = 0;
+                       set->bits = Xbits;
+                       set++;
+               }
+       }
+}
diff --git a/lib/nbsd_libc/gen/setproctitle.3 b/lib/nbsd_libc/gen/setproctitle.3
new file mode 100644 (file)
index 0000000..8d32011
--- /dev/null
@@ -0,0 +1,99 @@
+.\" $NetBSD: setproctitle.3,v 1.18 2003/07/26 19:24:44 salo Exp $
+.\"
+.\" Copyright (c) 1994, 1995 Christopher G. Demetriou
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"          This product includes software developed for the
+.\"          NetBSD Project.  See http://www.NetBSD.org/ for
+.\"          information about NetBSD.
+.\" 4. 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 ``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 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.
+.\"
+.\" <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+.\"
+.Dd April 13, 1994
+.Dt SETPROCTITLE 3
+.Os
+.Sh NAME
+.Nm setproctitle
+.Nd set process title
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft void
+.Fn setproctitle "const char *fmt" "..."
+.Sh DESCRIPTION
+The
+.Fn setproctitle
+function sets the invoking process's title.
+The process title is set to the last component of the program
+name, followed by a colon and the formatted string specified
+by
+.Va fmt .
+If
+.Va fmt
+is
+.Dv NULL ,
+the colon and formatted string are omitted.
+The length of a process title is limited to 2048 bytes.
+.Sh EXAMPLES
+Set the process title to the program name, with no further information:
+.Bd -literal -offset indent
+setproctitle(NULL);
+.Ed
+.Pp
+Set the process title to the program name, an informational string,
+and the process id:
+.Bd -literal -offset indent
+setproctitle("foo! (%d)", getpid());
+.Ed
+.Sh SEE ALSO
+.Xr ps 1 ,
+.Xr w 1 ,
+.Xr getprogname 3 ,
+.Xr printf 3
+.Sh HISTORY
+The
+.Fn setproctitle
+function first appeared in
+.Nx 1.0 .
+.Sh CAVEATS
+It is important never to pass a string with user-supplied data as a
+format without using
+.Ql %s .
+An attacker can put format specifiers in the string to mangle your stack,
+leading to a possible security hole.
+This holds true even if you have built the string
+.Dq by hand
+using a function like
+.Fn snprintf ,
+as the resulting string may still contain user-supplied conversion specifiers
+for later interpolation by
+.Fn setproctitle .
+.Pp
+Always be sure to use the proper secure idiom:
+.Bd -literal -offset indent
+setproctitle("%s", string);
+.Ed
diff --git a/lib/nbsd_libc/gen/setproctitle.c b/lib/nbsd_libc/gen/setproctitle.c
new file mode 100644 (file)
index 0000000..5138922
--- /dev/null
@@ -0,0 +1,98 @@
+/* $NetBSD: setproctitle.c,v 1.22 2008/01/03 04:26:27 christos Exp $ */
+
+/*
+ * Copyright (c) 1994, 1995 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: setproctitle.c,v 1.22 2008/01/03 04:26:27 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/exec.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(setproctitle,_setproctitle)
+#endif
+
+#define        MAX_PROCTITLE   2048
+
+/*
+ * For compatibility with old versions of crt0 that didn't define __ps_strings,
+ * define it as a common here.
+ */
+struct ps_strings *__ps_strings;
+
+void
+setproctitle(const char *fmt, ...)
+{
+       static char buf[MAX_PROCTITLE], *bufp;
+       const char *pname = getprogname();
+
+       if (fmt != NULL) {
+               int len = snprintf(buf, sizeof(buf), "%s: ", pname);
+               if (len >= 0) {
+                       va_list ap;
+
+                       va_start(ap, fmt);
+                       (void)vsnprintf(buf + len, sizeof(buf) - len, fmt, ap);
+                       va_end(ap);
+               }
+       } else
+               (void)snprintf(buf, sizeof(buf), "%s", pname);
+
+       bufp = buf;
+
+#ifdef USRSTACK
+       /*
+        * For compatibility with old versions of crt0 and old kernels, set
+        * __ps_strings to a default value if it's null.
+        * But only if USRSTACK is defined.  It might not be defined if
+        * user-level code can not assume it's a constant (i.e. m68k).
+        */
+       if (__ps_strings == 0)
+               __ps_strings = PS_STRINGS;
+#endif /* USRSTACK */
+
+       if (__ps_strings != 0) {
+               __ps_strings->ps_nargvstr = 1;
+               __ps_strings->ps_argvstr = &bufp;
+       }
+}
diff --git a/lib/nbsd_libc/gen/setprogname.c b/lib/nbsd_libc/gen/setprogname.c
new file mode 100644 (file)
index 0000000..4899523
--- /dev/null
@@ -0,0 +1,65 @@
+/* $NetBSD: setprogname.c,v 1.3 2003/07/26 19:24:44 salo Exp $ */
+
+/*
+ * Copyright (c) 2001 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: setprogname.c,v 1.3 2003/07/26 19:24:44 salo Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+/* In NetBSD, the program name is set by crt0.  It can't be overridden. */
+#undef REALLY_SET_PROGNAME
+
+#include <stdlib.h>
+
+#ifdef REALLY_SET_PROGNAME
+#include <string.h>
+
+extern const char *__progname;
+#endif
+
+/*ARGSUSED*/
+void
+setprogname(const char *progname)
+{
+
+#ifdef REALLY_SET_PROGNAME
+       __progname = strrchr(progname, '/');
+       if (__progname == NULL)
+               __progname = progname;
+       else
+               __progname++;
+#endif
+}
diff --git a/lib/nbsd_libc/gen/shquote.3 b/lib/nbsd_libc/gen/shquote.3
new file mode 100644 (file)
index 0000000..026467f
--- /dev/null
@@ -0,0 +1,244 @@
+.\" $NetBSD: shquote.3,v 1.9 2008/09/07 08:55:46 apb Exp $
+.\"
+.\" Copyright (c) 2001 Christopher G. Demetriou
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"          This product includes software developed for the
+.\"          NetBSD Project.  See http://www.NetBSD.org/ for
+.\"          information about NetBSD.
+.\" 4. 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 ``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 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.
+.\"
+.\" <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+.\"
+.Dd September 7, 2008
+.Dt SHQUOTE 3
+.Os
+.Sh NAME
+.Nm shquote ,
+.Nm shquotev
+.Nd quote argument strings for use with the shell
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft size_t
+.Fn shquote "const char *arg" "char *buf" "size_t bufsize"
+.Ft size_t
+.Fn shquotev "int argc" "char * const *argv" "char *buf" "size_t bufsize"
+.Sh DESCRIPTION
+The
+.Fn shquote
+and
+.Fn shquotev
+functions copy strings and transform the copies by adding shell
+escape and quoting characters.
+They are used to encapsulate
+arguments to be included in command strings passed to the
+.Fn system
+and
+.Fn popen
+functions, so that the arguments will have the correct values
+after being evaluated by the shell.
+.Pp
+The exact method of quoting and escaping may vary, and is intended
+to match the conventions of the shell used by
+.Fn system
+and
+.Fn popen .
+It may not match the conventions used by other shells.
+In this implementation, the following
+transformation is applied to each input string:
+.Bl -bullet -width indent
+.It
+it is surrounded by single quotes
+.Pq ' ,
+.It
+any single quotes in the input are escaped by replacing them with
+the four-character sequence:
+.Li '\e'' ,
+and
+.It
+extraneous pairs of single quotes (caused by multiple adjacent single
+quotes in the input string, or by single quotes at the beginning or
+end of the input string) are elided.
+.El
+.Pp
+The
+.Fn shquote
+function transforms the string specified by its
+.Fa arg
+argument, and places the result into the memory pointed to by
+.Fa buf .
+.Pp
+The
+.Fn shquotev
+function transforms each of the
+.Fa argc
+strings specified by the array
+.Fa argv
+independently.
+The transformed strings are placed in the memory pointed to by
+.Fa buf ,
+separated by spaces.
+It does not modify the pointer array specified by
+.Fa argv
+or the strings pointed to by the pointers in the array.
+.Pp
+Both functions write up to
+.Fa bufsize
+- 1 characters of output into the buffer pointed to by
+.Fa buf ,
+then add a
+.Li NUL
+character to terminate the output string.
+If
+.Fa bufsize
+is given as zero, the
+.Fa buf
+parameter is ignored and no output is written.
+.Sh RETURN VALUES
+The
+.Fn shquote
+and
+.Fn shquotev
+functions return the number of characters necessary to hold the
+result from operating on their input strings,
+not including the terminating
+.Li NUL .
+That is, they return the length of the string that would have
+been written to the output buffer, if it were large enough.
+If an error occurs during processing, the value ((size_t)\-1)
+is returned and
+.Va errno
+is set appropriately.
+.Sh EXAMPLES
+The following code fragment demonstrates how you might use
+.Fn shquotev
+to construct a command string to be used with
+.Fn system .
+The command uses an environment variable (which will be expanded by
+the shell) to determine the actual program to run.
+Note that the environment variable may be expanded by
+the shell into multiple words.
+The first word of the expansion will be used by the shell
+as the name of the program to run,
+and the rest will be passed as arguments to the program.
+.Bd -literal -offset indent
+char **argv, c, *cmd;
+size_t cmdlen, len, qlen;
+int argc;
+
+\&...
+
+/*
+ * Size buffer to hold the command string, and allocate it.
+ * Buffer of length one given to snprintf() for portability.
+ */
+cmdlen = snprintf(\*[Am]c, 1, "${PROG-%s} ", PROG_DEFAULT);
+qlen = shquotev(argc, argv, NULL, 0);
+if (qlen == (size_t)-1) {
+       \&...
+}
+cmdlen += qlen + 1;
+cmd = malloc(cmdlen);
+if (cmd == NULL) {
+       \&...
+}
+
+/* Create the command string. */
+len = snprintf(cmd, cmdlen, "${PROG-%s} ", PROG_DEFAULT);
+qlen = shquotev(argc, argv, cmd + len, cmdlen - len);
+if (qlen == (size_t)-1) {
+       /* Should not ever happen. */
+       \&...
+}
+len += qlen;
+
+/* "cmd" can now be passed to system(). */
+.Ed
+.Pp
+The following example shows how you would implement the same
+functionality using the
+.Fn shquote
+function directly.
+.Bd -literal -offset indent
+char **argv, c, *cmd;
+size_t cmdlen, len, qlen;
+int argc, i;
+
+\&...
+
+/*
+ * Size buffer to hold the command string, and allocate it.
+ * Buffer of length one given to snprintf() for portability.
+ */
+cmdlen = snprintf(\*[Am]c, 1, "${PROG-%s} ", PROG_DEFAULT);
+for (i = 0; i \*[Lt] argc; i++) {
+       qlen = shquote(argv[i], NULL, 0);
+       if (qlen == (size_t)-1) {
+               \&...
+       }
+       cmdlen += qlen + 1;
+}
+cmd = malloc(cmdlen);
+if (cmd == NULL) {
+       \&...
+}
+
+/* Start the command string with the env var reference. */
+len = snprintf(cmd, cmdlen, "${PROG-%s} ", PROG_DEFAULT);
+
+/* Quote all of the arguments when copying them. */
+for (i = 0; i \*[Lt] argc; i++) {
+       qlen = shquote(argv[i], cmd + len, cmdlen - len);
+       if (qlen == (size_t)-1) {
+               /* Should not ever happen. */
+               \&...
+       }
+       len += qlen;
+       cmd[len++] = ' ';
+}
+cmd[--len] = '\e0';
+
+/* "cmd" can now be passed to system(). */
+.Ed
+.Sh SEE ALSO
+.Xr sh 1 ,
+.Xr popen 3 ,
+.Xr system 3
+.Sh BUGS
+This implementation does not currently handle strings containing multibyte
+characters properly.
+To address this issue,
+.Pa /bin/sh
+.Po
+the shell used by
+.Fn system
+and
+.Fn popen
+.Pc
+must first be fixed to handle multibyte characters.
+When that has been done,
+these functions can have multibyte character support enabled.
diff --git a/lib/nbsd_libc/gen/shquote.c b/lib/nbsd_libc/gen/shquote.c
new file mode 100644 (file)
index 0000000..e72837f
--- /dev/null
@@ -0,0 +1,189 @@
+/* $NetBSD: shquote.c,v 1.8 2006/03/19 02:33:02 christos Exp $ */
+
+/*
+ * Copyright (c) 2001 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: shquote.c,v 1.8 2006/03/19 02:33:02 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Define SHQUOTE_USE_MULTIBYTE if you want shquote() to handle multibyte
+ * characters using mbrtowc().
+ *
+ * Please DO NOT rip this #ifdef out of the code.  It's also here to help
+ * portability.
+ */
+#undef SHQUOTE_USE_MULTIBYTE
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <string.h>
+#ifdef SHQUOTE_USE_MULTIBYTE
+#include <limits.h>
+#include <stdio.h>
+#include <wchar.h>
+#endif
+
+#ifdef __weak_alias
+__weak_alias(shquote,_shquote)
+#endif
+
+/*
+ * shquote():
+ *
+ * Requotes arguments so that they'll be interpreted properly by the
+ * shell (/bin/sh).
+ *
+ * Wraps single quotes around the string, and replaces single quotes
+ * in the string with the sequence:
+ *     '\''
+ *
+ * Returns the number of characters required to hold the resulting quoted
+ * argument.
+ *
+ * The buffer supplied is filled in and NUL-terminated.  If 'bufsize'
+ * indicates that the buffer is too short to hold the output string, the
+ * first (bufsize - 1) bytes of quoted argument are filled in and the
+ * buffer is NUL-terminated.
+ *
+ * Changes could be made to optimize the length of strings output by this
+ * function:
+ *
+ *     * if there are no metacharacters or whitespace in the input,
+ *       the output could be the input string.
+ */
+
+#ifdef SHQUOTE_USE_MULTIBYTE
+
+#define        XLATE_OUTCH(x)          wcrtomb(outch, (x), &mbso)
+#define        XLATE_INCH()                                            \
+    do {                                                       \
+       n = mbrtowc(&c, arg, MB_CUR_MAX, &mbsi);                \
+    } while (/*LINTED const cond*/0)
+
+#else
+
+#define        XLATE_OUTCH(x)          (outch[0] = (x), 1)
+#define        XLATE_INCH()                                            \
+    do {                                                       \
+       n = ((c = *arg) != '\0') ? 1 : 0;                       \
+    } while (/*LINTED const cond*/0)
+
+#endif
+
+#define        PUT(x)                                                  \
+    do {                                                       \
+       outchlen = XLATE_OUTCH(x);                              \
+       if (outchlen == (size_t)-1)                             \
+               goto bad;                                       \
+       rv += outchlen;                                         \
+       if (bufsize != 0) {                                     \
+               if (bufsize < outchlen ||                       \
+                   (bufsize == outchlen &&                     \
+                    outch[outchlen - 1] != '\0')) {            \
+                       *buf = '\0';                            \
+                       bufsize = 0;                            \
+               } else {                                        \
+                       memcpy(buf, outch, outchlen);           \
+                       buf += outchlen;                        \
+                       bufsize -= outchlen;                    \
+               }                                               \
+       }                                                       \
+    } while (/*LINTED const cond*/0)
+
+size_t
+shquote(const char *arg, char *buf, size_t bufsize)
+{
+#ifdef SHQUOTE_USE_MULTIBYTE
+       char outch[MB_LEN_MAX];
+       mbstate_t mbsi, mbso;
+       wchar_t c, lastc;
+       size_t outchlen;
+#else
+       char outch[1];
+       char c, lastc;
+       size_t outchlen;
+#endif
+       size_t rv;
+       int n;
+
+       rv = 0;
+       lastc = 0;
+#ifdef SHQUOTE_USE_MULTIBYTE
+       memset(&mbsi, 0, sizeof mbsi);
+       memset(&mbso, 0, sizeof mbso);
+#endif
+
+       if (*arg != '\'')
+               PUT('\'');
+       for (;;) {
+               XLATE_INCH();
+               if (n <= 0)
+                       break;
+               arg += n;
+               lastc = c;
+
+               if (c == '\'') {
+                       if (rv != 0)
+                               PUT('\'');
+                       PUT('\\');
+                       PUT('\'');
+                       for (;;) {
+                               XLATE_INCH();
+                               if (n <= 0 || c != '\'')
+                                       break;
+                               PUT('\\');
+                               PUT('\'');
+                               arg += n;
+                       }
+                       if (n > 0)
+                               PUT('\'');
+               } else
+                       PUT(c);
+       }
+       if (lastc != '\'')
+               PUT('\'');
+
+       /* Put multibyte or NUL terminator, but don't count the NUL. */
+       PUT('\0');
+       rv--;
+
+       return rv;
+
+bad:
+       /* A multibyte character encoding or decoding error occurred. */
+       return (size_t)-1;
+}
diff --git a/lib/nbsd_libc/gen/shquotev.c b/lib/nbsd_libc/gen/shquotev.c
new file mode 100644 (file)
index 0000000..4953f47
--- /dev/null
@@ -0,0 +1,86 @@
+/* $NetBSD: shquotev.c,v 1.5 2005/06/12 05:21:27 lukem Exp $ */
+
+/*
+ * Copyright (c) 2001 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: shquotev.c,v 1.5 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <stdlib.h>
+
+/*
+ * shquotev():
+ *
+ * Apply shquote() to a set of strings, separating the results by spaces.
+ */
+
+size_t
+shquotev(int argc, char * const * argv, char *buf, size_t bufsize)
+{
+       size_t rv, callrv;
+       int i;
+
+       rv = 0;
+
+       if (argc == 0) {
+               if (bufsize != 0)
+                       *buf = '\0';
+               return rv;
+       }
+
+       for (i = 0; i < argc; i++) {
+               callrv = shquote(argv[i], buf, bufsize);
+               if (callrv == (size_t)-1)
+                       goto bad;
+               rv += callrv;
+               buf += callrv;
+               bufsize = (bufsize > callrv) ? (bufsize - callrv) : 0;
+
+               if (i < (argc - 1)) {
+                       rv++;
+                       if (bufsize > 1) {
+                               *buf++ = ' ';
+                               bufsize--;
+                       }
+               }
+       }
+
+       return rv;
+
+bad:
+       return (size_t)-1;
+}
diff --git a/lib/nbsd_libc/gen/sighold.3 b/lib/nbsd_libc/gen/sighold.3
new file mode 100644 (file)
index 0000000..b29e46b
--- /dev/null
@@ -0,0 +1,80 @@
+.\"    $NetBSD: sighold.3,v 1.5 2010/04/30 04:39:16 jruoho Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 30, 2010
+.Dt SIGHOLD 3
+.Os
+.Sh NAME
+.Nm sighold
+.Nd manipulate current signal mask
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sighold "int sig"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is made obsolete by
+.Xr sigprocmask 2 .
+.Ef
+.Pp
+The
+.Fn sighold
+function adds the signal
+.Fa sig
+to the calling process' signal mask.
+.Sh RETURN VALUES
+If successful, the
+.Fn sighold
+function returns 0.
+Otherwise \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn sighold
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The argument
+.Fa sig
+is not a valid signal number.
+.El
+.Sh SEE ALSO
+.Xr sigprocmask 2 ,
+.Xr sigrelse 3
+.Sh STANDARDS
+The
+.Fn sighold
+function conforms to
+.St -p1003.1-2001 .
+It was however marked as obsolete in the
+.St -p1003.1-2008
+revision of the standard.
diff --git a/lib/nbsd_libc/gen/sighold.c b/lib/nbsd_libc/gen/sighold.c
new file mode 100644 (file)
index 0000000..7fa70c9
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: sighold.c,v 1.2 2008/04/28 20:22:59 martin Exp $       */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sighold.c,v 1.2 2008/04/28 20:22:59 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <signal.h>
+#include <stddef.h>
+
+int
+sighold(int sig)
+{
+       sigset_t set;
+
+       sigemptyset(&set);
+       if (sigaddset(&set, sig) != 0)
+               return (-1);
+
+       return (sigprocmask(SIG_BLOCK, &set, NULL));
+}
diff --git a/lib/nbsd_libc/gen/sigignore.3 b/lib/nbsd_libc/gen/sigignore.3
new file mode 100644 (file)
index 0000000..41ed44e
--- /dev/null
@@ -0,0 +1,85 @@
+.\"    $NetBSD: sigignore.3,v 1.6 2010/04/30 06:48:20 wiz Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 30, 2010
+.Dt SIGIGNORE 3
+.Os
+.Sh NAME
+.Nm sigignore
+.Nd manipulate signal dispositions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigignore "int sig"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is made obsolete by
+.Xr sigaction 2 .
+.Ef
+.Pp
+The
+.Fn sigignore
+function sets the disposition of the signal
+.Fa sig
+to
+.Dv SIG_IGN .
+.Sh RETURN VALUES
+If successful, the
+.Fn sigignore
+function returns 0.
+Otherwise \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn sigignore
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The argument
+.Fa sig
+is not a valid signal number;
+or an attempt is made to ignore a signal that cannot be ignored,
+such as
+.Dv SIGKILL
+or
+.Dv SIGSTOP .
+.El
+.Sh SEE ALSO
+.Xr sigaction 2
+.Sh STANDARDS
+The
+.Fn sigignore
+function conforms to
+.St -p1003.1-2001 .
+It was however marked as obsolete in the
+.St -p1003.1-2008
+revision of the standard.
diff --git a/lib/nbsd_libc/gen/sigignore.c b/lib/nbsd_libc/gen/sigignore.c
new file mode 100644 (file)
index 0000000..e9d7322
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: sigignore.c,v 1.2 2008/04/28 20:22:59 martin Exp $     */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sigignore.c,v 1.2 2008/04/28 20:22:59 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <signal.h>
+#include <stddef.h>
+
+int
+sigignore(int sig)
+{
+       struct sigaction sa;
+
+       sa.sa_handler = SIG_IGN;
+       if (sigemptyset(&sa.sa_mask) != 0)
+               return (-1);
+       sa.sa_flags = 0;
+
+       return (sigaction(sig, &sa, NULL));
+}
diff --git a/lib/nbsd_libc/gen/siginterrupt.3 b/lib/nbsd_libc/gen/siginterrupt.3
new file mode 100644 (file)
index 0000000..f032833
--- /dev/null
@@ -0,0 +1,105 @@
+.\"    $NetBSD: siginterrupt.3,v 1.11 2003/08/07 16:42:56 agc Exp $
+.\"
+.\" Copyright (c) 1985, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)siginterrupt.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt SIGINTERRUPT 3
+.Os
+.Sh NAME
+.Nm siginterrupt
+.Nd allow signals to interrupt system calls
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn siginterrupt "int sig" "int flag"
+.Sh DESCRIPTION
+The
+.Fn siginterrupt
+function
+is used to change the system call restart
+behavior when a system call is interrupted by the specified signal.
+If the flag is false (0), then system calls will be restarted if
+they are interrupted by the specified signal
+and no data has been transferred yet.
+System call restart is the default behavior on
+.Bx 4.2 .
+.Pp
+If the flag is true (1),
+then restarting of system calls is disabled.
+If a system call is interrupted by the specified signal
+and no data has been transferred,
+the system call will return \-1 with the global variable
+.Va errno
+set to
+.Dv EINTR .
+Interrupted system calls that have started transferring
+data will return the amount of data actually transferred.
+System call interrupt is the signal behavior found on
+.Bx 4.1
+and
+.At V
+systems.
+.Pp
+Note that the new
+.Bx 4.2
+signal handling semantics are not
+altered in any other way.
+Most notably, signal handlers always remain installed until
+explicitly changed by a subsequent
+.Xr sigaction 2
+call, and the signal mask operates as documented in
+.Xr sigaction 2 .
+Programs may switch between restartable and interruptible
+system call operation as often as desired in the execution of a program.
+.Pp
+Issuing a
+.Fn siginterrupt 3
+call during the execution of a signal handler will cause
+the new action to take place on the next signal to be caught.
+.Sh NOTES
+This library routine uses an extension of the
+.Xr sigaction 2
+system call that is not available in
+.Bx 4.2 ,
+hence it should not be used if backward compatibility is needed.
+.Sh RETURN VALUES
+A 0 value indicates that the call succeeded.
+A \-1 value indicates that an invalid signal number has been supplied.
+.Sh SEE ALSO
+.Xr sigaction 2 ,
+.Xr sigprocmask 2 ,
+.Xr sigsuspend 2
+.Sh HISTORY
+The
+.Fn siginterrupt
+function appeared in
+.Bx 4.3 .
diff --git a/lib/nbsd_libc/gen/siginterrupt.c b/lib/nbsd_libc/gen/siginterrupt.c
new file mode 100644 (file)
index 0000000..56e98b8
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: siginterrupt.c,v 1.12 2003/08/07 16:42:56 agc Exp $    */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)siginterrupt.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: siginterrupt.c,v 1.12 2003/08/07 16:42:56 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <signal.h>
+
+#ifdef __weak_alias
+__weak_alias(siginterrupt,_siginterrupt)
+#endif
+
+extern sigset_t __sigintr;
+/*
+ * Set signal state to prevent restart of system calls
+ * after an instance of the indicated signal.
+ */
+int
+siginterrupt(sig, flag)
+       int sig, flag;
+{
+       struct sigaction sa;
+       int ret;
+
+       if ((ret = sigaction(sig, (struct sigaction *)0, &sa)) < 0)
+               return (ret);
+       if (flag) {
+               sigaddset(&__sigintr, sig);
+               sa.sa_flags &= ~SA_RESTART;
+       } else {
+               sigdelset(&__sigintr, sig);
+               sa.sa_flags |= SA_RESTART;
+       }
+       return (sigaction(sig, &sa, (struct sigaction *)0));
+}
diff --git a/lib/nbsd_libc/gen/siglist.c b/lib/nbsd_libc/gen/siglist.c
new file mode 100644 (file)
index 0000000..3b2e464
--- /dev/null
@@ -0,0 +1,112 @@
+/*     $NetBSD: siglist.c,v 1.17 2007/01/17 23:24:22 hubertf Exp $     */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)siglist.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: siglist.c,v 1.17 2007/01/17 23:24:22 hubertf Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <signal.h>
+
+static const char *const __siglist14[] = {
+       "Signal 0",                     /* 0 */
+       "Hangup",                       /* 1 SIGHUP */
+       "Interrupt",                    /* 2 SIGINT */
+       "Quit",                         /* 3 SIGQUIT */
+       "Illegal instruction",          /* 4 SIGILL */
+       "Trace/BPT trap",               /* 5 SIGTRAP */
+       "Abort trap",                   /* 6 SIGABRT */
+       "EMT trap",                     /* 7 SIGEMT */
+       "Floating point exception",     /* 8 SIGFPE */
+       "Killed",                       /* 9 SIGKILL */
+       "Bus error",                    /* 10 SIGBUS */
+       "Segmentation fault",           /* 11 SIGSEGV */
+       "Bad system call",              /* 12 SIGSYS */
+       "Broken pipe",                  /* 13 SIGPIPE */
+       "Alarm clock",                  /* 14 SIGALRM */
+       "Terminated",                   /* 15 SIGTERM */
+       "Urgent I/O condition",         /* 16 SIGURG */
+       "Suspended (signal)",           /* 17 SIGSTOP */
+       "Suspended",                    /* 18 SIGTSTP */
+       "Continued",                    /* 19 SIGCONT */
+       "Child exited",                 /* 20 SIGCHLD */
+       "Stopped (tty input)",          /* 21 SIGTTIN */
+       "Stopped (tty output)",         /* 22 SIGTTOU */
+       "I/O possible",                 /* 23 SIGIO */
+       "Cputime limit exceeded",       /* 24 SIGXCPU */
+       "Filesize limit exceeded",      /* 25 SIGXFSZ */
+       "Virtual timer expired",        /* 26 SIGVTALRM */
+       "Profiling timer expired",      /* 27 SIGPROF */
+       "Window size changes",          /* 28 SIGWINCH */
+       "Information request",          /* 29 SIGINFO */
+       "User defined signal 1",        /* 30 SIGUSR1 */
+       "User defined signal 2",        /* 31 SIGUSR2 */
+       "Power fail/restart",           /* 32 SIGPWR */
+       "Real time signal 0",           /* 33 SIGRTMIN + 0 */
+       "Real time signal 1",           /* 34 SIGRTMIN + 1 */
+       "Real time signal 2",           /* 35 SIGRTMIN + 2 */
+       "Real time signal 3",           /* 36 SIGRTMIN + 3 */
+       "Real time signal 4",           /* 37 SIGRTMIN + 4 */
+       "Real time signal 5",           /* 38 SIGRTMIN + 5 */
+       "Real time signal 6",           /* 39 SIGRTMIN + 6 */
+       "Real time signal 7",           /* 40 SIGRTMIN + 7 */
+       "Real time signal 8",           /* 41 SIGRTMIN + 8 */
+       "Real time signal 9",           /* 42 SIGRTMIN + 9 */
+       "Real time signal 10",          /* 43 SIGRTMIN + 10 */
+       "Real time signal 11",          /* 44 SIGRTMIN + 11 */
+       "Real time signal 12",          /* 45 SIGRTMIN + 12 */
+       "Real time signal 13",          /* 46 SIGRTMIN + 13 */
+       "Real time signal 14",          /* 47 SIGRTMIN + 14 */
+       "Real time signal 15",          /* 48 SIGRTMIN + 15 */
+       "Real time signal 16",          /* 49 SIGRTMIN + 16 */
+       "Real time signal 17",          /* 50 SIGRTMIN + 17 */
+       "Real time signal 18",          /* 51 SIGRTMIN + 18 */
+       "Real time signal 19",          /* 52 SIGRTMIN + 19 */
+       "Real time signal 20",          /* 53 SIGRTMIN + 20 */
+       "Real time signal 21",          /* 54 SIGRTMIN + 21 */
+       "Real time signal 22",          /* 55 SIGRTMIN + 22 */
+       "Real time signal 23",          /* 56 SIGRTMIN + 23 */
+       "Real time signal 24",          /* 57 SIGRTMIN + 24 */
+       "Real time signal 25",          /* 58 SIGRTMIN + 25 */
+       "Real time signal 26",          /* 59 SIGRTMIN + 26 */
+       "Real time signal 27",          /* 60 SIGRTMIN + 27 */
+       "Real time signal 28",          /* 61 SIGRTMIN + 28 */
+       "Real time signal 29",          /* 62 SIGRTMIN + 29 */
+       "Real time signal 30",          /* 63 SIGRTMIN + 30 */
+};
+
+const int __sys_nsig14 = sizeof(__siglist14) / sizeof(__siglist14[0]);
+
+const char * const *__sys_siglist14 = __siglist14;
diff --git a/lib/nbsd_libc/gen/signal.3 b/lib/nbsd_libc/gen/signal.3
new file mode 100644 (file)
index 0000000..e554195
--- /dev/null
@@ -0,0 +1,191 @@
+.\"    $NetBSD: signal.3,v 1.24 2004/06/13 19:17:06 lha Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)signal.3   8.3 (Berkeley) 4/19/94
+.\"
+.Dd June 11, 2004
+.Dt SIGNAL 3
+.Os
+.Sh NAME
+.Nm signal
+.Nd simplified software signal facilities
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.\" The following is Quite Ugly, but syntactically correct.  Don't try to
+.\" fix it.
+.Ft void \*(lp*
+.Fn signal "int sig" "void \*(lp*func\*(rp\*(lpint\*(rp\*(rp\*(rp\*(lpint"
+.Sh DESCRIPTION
+This
+.Fn signal
+facility
+is a simplified interface to the more general
+.Xr sigaction 2
+facility.
+.Pp
+Signals allow the manipulation of a process from outside its
+domain as well as allowing the process to manipulate itself or
+copies of itself (children).
+There are two general types of signals:
+those that cause termination of a process and those that do not.
+Signals which cause termination of a program might result from
+an irrecoverable error or might be the result of a user at a terminal
+typing the `interrupt' character.
+Signals are used when a process is stopped because it wishes to access
+its control terminal while in the background (see
+.Xr tty 4 ) .
+Signals are optionally generated
+when a process resumes after being stopped,
+when the status of child processes changes,
+or when input is ready at the control terminal.
+Most signals result in the termination of the process receiving them
+if no action
+is taken; some signals instead cause the process receiving them
+to be stopped, or are simply discarded if the process has not
+requested otherwise.
+Except for the
+.Dv SIGKILL
+and
+.Dv SIGSTOP
+signals, the
+.Fn signal
+function allows for a signal to be caught, to be ignored, or to generate
+an interrupt.
+See
+.Xr signal 7
+for comprehensive list of supported signals.
+.Pp
+The
+.Fa func
+procedure allows a user to choose the action upon receipt of a signal.
+To set the default action of the signal to occur as listed above,
+.Fa func
+should be
+.Dv SIG_DFL .
+A
+.Dv SIG_DFL
+resets the default action.
+To ignore the signal
+.Fa func
+should be
+.Dv SIG_IGN .
+This will cause subsequent instances of the signal to be ignored
+and pending instances to be discarded.
+If
+.Dv SIG_IGN
+is not used,
+further occurrences of the signal are
+automatically blocked and
+.Fa func
+is called.
+.Pp
+The handled signal is unblocked when the
+function returns and
+the process continues from where it left off when the signal occurred.
+.Bf -symbolic
+Unlike previous signal facilities, the handler
+func() remains installed after a signal has been delivered.
+.Ef
+.Pp
+For some system calls, if a signal is caught while the call is
+executing and the call is prematurely terminated,
+the call is automatically restarted.
+(The handler is installed using the
+.Dv SA_RESTART
+flag with
+.Xr sigaction 2 ) .
+The affected system calls include
+.Xr read 2 ,
+.Xr write 2 ,
+.Xr sendto 2 ,
+.Xr recvfrom 2 ,
+.Xr sendmsg 2
+and
+.Xr recvmsg 2
+on a communications channel or a low speed device
+and during a
+.Xr ioctl 2
+or
+.Xr wait 2 .
+However, calls that have already committed are not restarted,
+but instead return a partial success (for example, a short read count).
+.Pp
+When a process which has installed signal handlers forks,
+the child process inherits the signals.
+All caught signals may be reset to their default action by a call
+to the
+.Xr execve 2
+function;
+ignored signals remain ignored.
+.Pp
+Only functions that are async-signal-safe can safely be used in signal
+handlers, see
+.Xr signal 7
+for a complete list.
+.Sh RETURN VALUES
+The previous action is returned on a successful call.
+Otherwise,
+.Dv SIG_ERR
+is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn signal
+will fail and no action will take place if one of the following occur:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+Specified
+.Em sig
+is not a valid signal number.
+.It Bq Er EINVAL
+An attempt is made to ignore or supply a handler for
+.Dv SIGKILL
+or
+.Dv SIGSTOP .
+.El
+.Sh SEE ALSO
+.Xr kill 1 ,
+.Xr kill 2 ,
+.Xr ptrace 2 ,
+.Xr sigaction 2 ,
+.Xr sigaltstack 2 ,
+.Xr sigprocmask 2 ,
+.Xr sigsuspend 2 ,
+.Xr psignal 3 ,
+.Xr setjmp 3 ,
+.Xr strsignal 3 ,
+.Xr tty 4 ,
+.Xr signal 7
+.Sh HISTORY
+This
+.Fn signal
+facility appeared in
+.Bx 4.0 .
diff --git a/lib/nbsd_libc/gen/signal.c b/lib/nbsd_libc/gen/signal.c
new file mode 100644 (file)
index 0000000..09f6e57
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: signal.c,v 1.12 2003/08/07 16:42:56 agc Exp $  */
+
+/*
+ * Copyright (c) 1985, 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)signal.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: signal.c,v 1.12 2003/08/07 16:42:56 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Almost backwards compatible signal.
+ */
+#include "namespace.h"
+#include <signal.h>
+
+#ifdef __weak_alias
+__weak_alias(signal,_signal)
+#endif
+
+sigset_t __sigintr;            /* shared with siginterrupt */
+
+sig_t
+signal(s, a)
+       int s;
+       sig_t a;
+{
+       struct sigaction sa, osa;
+
+       sa.sa_handler = a;
+       sigemptyset(&sa.sa_mask);
+       sa.sa_flags = 0;
+       if (!sigismember(&__sigintr, s))
+               sa.sa_flags |= SA_RESTART;
+       if (sigaction(s, &sa, &osa) < 0)
+               return (SIG_ERR);
+       return (osa.sa_handler);
+}
diff --git a/lib/nbsd_libc/gen/signame.c b/lib/nbsd_libc/gen/signame.c
new file mode 100644 (file)
index 0000000..a5f137d
--- /dev/null
@@ -0,0 +1,111 @@
+/*     $NetBSD: signame.c,v 1.13 2005/09/13 01:44:09 christos Exp $    */
+
+/*
+ * Copyright (c) 1983 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "from: @(#)siglist.c    5.6 (Berkeley) 2/23/91";*/
+#else
+__RCSID("$NetBSD: signame.c,v 1.13 2005/09/13 01:44:09 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <signal.h>
+#include <unistd.h>
+
+static const char *const __signame14[] = {
+       "Signal 0",     /* 0 */
+       "HUP",          /* 1 SIGHUP */
+       "INT",          /* 2 SIGINT */
+       "QUIT",         /* 3 SIGQUIT */
+       "ILL",          /* 4 SIGILL */
+       "TRAP",         /* 5 SIGTRAP */
+       "ABRT",         /* 6 SIGABRT */
+       "EMT",          /* 7 SIGEMT */
+       "FPE",          /* 8 SIGFPE */
+       "KILL",         /* 9 SIGKILL */
+       "BUS",          /* 10 SIGBUS */
+       "SEGV",         /* 11 SIGSEGV */
+       "SYS",          /* 12 SIGSYS */
+       "PIPE",         /* 13 SIGPIPE */
+       "ALRM",         /* 14 SIGALRM */
+       "TERM",         /* 15 SIGTERM */
+       "URG",          /* 16 SIGURG */
+       "STOP",         /* 17 SIGSTOP */
+       "TSTP",         /* 18 SIGTSTP */
+       "CONT",         /* 19 SIGCONT */
+       "CHLD",         /* 20 SIGCHLD */
+       "TTIN",         /* 21 SIGTTIN */
+       "TTOU",         /* 22 SIGTTOU */
+       "IO",           /* 23 SIGIO */
+       "XCPU",         /* 24 SIGXCPU */
+       "XFSZ",         /* 25 SIGXFSZ */
+       "VTALRM",       /* 26 SIGVTALRM */
+       "PROF",         /* 27 SIGPROF */
+       "WINCH",        /* 28 SIGWINCH */
+       "INFO",         /* 29 SIGINFO */
+       "USR1",         /* 30 SIGUSR1 */
+       "USR2",         /* 31 SIGUSR2 */
+       "PWR",          /* 32 SIGPWR */
+       "RT0",          /* 33 SIGRTMIN + 0 */
+       "RT1",          /* 34 SIGRTMIN + 1 */
+       "RT2",          /* 35 SIGRTMIN + 2 */
+       "RT3",          /* 36 SIGRTMIN + 3 */
+       "RT4",          /* 37 SIGRTMIN + 4 */
+       "RT5",          /* 38 SIGRTMIN + 5 */
+       "RT6",          /* 39 SIGRTMIN + 6 */
+       "RT7",          /* 40 SIGRTMIN + 7 */
+       "RT8",          /* 41 SIGRTMIN + 8 */
+       "RT9",          /* 42 SIGRTMIN + 9 */
+       "RT10",         /* 43 SIGRTMIN + 10 */
+       "RT11",         /* 44 SIGRTMIN + 11 */
+       "RT12",         /* 45 SIGRTMIN + 12 */
+       "RT13",         /* 46 SIGRTMIN + 13 */
+       "RT14",         /* 47 SIGRTMIN + 14 */
+       "RT15",         /* 48 SIGRTMIN + 15 */
+       "RT16",         /* 49 SIGRTMIN + 16 */
+       "RT17",         /* 50 SIGRTMIN + 17 */
+       "RT18",         /* 51 SIGRTMIN + 18 */
+       "RT19",         /* 52 SIGRTMIN + 19 */
+       "RT20",         /* 53 SIGRTMIN + 20 */
+       "RT21",         /* 54 SIGRTMIN + 21 */
+       "RT22",         /* 55 SIGRTMIN + 22 */
+       "RT23",         /* 56 SIGRTMIN + 23 */
+       "RT24",         /* 57 SIGRTMIN + 24 */
+       "RT25",         /* 58 SIGRTMIN + 25 */
+       "RT26",         /* 59 SIGRTMIN + 26 */
+       "RT27",         /* 60 SIGRTMIN + 27 */
+       "RT28",         /* 61 SIGRTMIN + 28 */
+       "RT29",         /* 62 SIGRTMIN + 29 */
+       "RT30",         /* 63 SIGRTMIN + 30 */
+};
+
+const char * const *__sys_signame14 = __signame14;
diff --git a/lib/nbsd_libc/gen/signbit.3 b/lib/nbsd_libc/gen/signbit.3
new file mode 100644 (file)
index 0000000..71e3eb5
--- /dev/null
@@ -0,0 +1,75 @@
+.\"    $NetBSD: signbit.3,v 1.3 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd October 29, 2003
+.Dt SIGNBIT 3
+.Os
+.Sh NAME
+.Nm signbit
+.Nd test sign
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In math.h
+.Ft int
+.Fn signbit "real-floating x"
+.Sh DESCRIPTION
+The
+.Fn signbit
+macro determines whether the sign of its argument value
+.Fa x
+is negative.
+An argument represented in a format wider than its semantic type is
+converted to its semantic type first.
+The determination is then based on the type of the argument.
+.Ss IEEE754
+The sign is determined for all values, including infinities, zeroes,
+and NaNs
+.Ss VAX
+The sign is determined for finites, true zeros, and dirty zeroes;
+for ROPs the sign is reported negative.
+.Sh RETURN VALUES
+The
+.Fn signbit
+macro returns a non-zero value if the sign of its value
+.Fa x
+is negative.
+Otherwise 0 is returned.
+.Sh ERRORS
+No errors are defined.
+.Sh SEE ALSO
+.Xr fpclassify 3 ,
+.Xr isfinite 3 ,
+.Xr isnormal 3 ,
+.Xr math 3
+.Sh STANDARDS
+The
+.Fn signbit
+macro conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/gen/signbitd_ieee754.c b/lib/nbsd_libc/gen/signbitd_ieee754.c
new file mode 100644 (file)
index 0000000..9ea2f16
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: signbitd_ieee754.c,v 1.2 2008/04/28 20:22:59 martin Exp $      */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: signbitd_ieee754.c,v 1.2 2008/04/28 20:22:59 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.6 signbit - determine whether the sign of an argument is negative
+ *          IEEE 754 double-precision version
+ */
+int
+__signbitd(double x)
+{
+       union ieee_double_u u;
+
+       u.dblu_d = x;
+
+       return (u.dblu_dbl.dbl_sign == 1);
+}
diff --git a/lib/nbsd_libc/gen/signbitf_ieee754.c b/lib/nbsd_libc/gen/signbitf_ieee754.c
new file mode 100644 (file)
index 0000000..df63bd7
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: signbitf_ieee754.c,v 1.2 2008/04/28 20:22:59 martin Exp $      */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: signbitf_ieee754.c,v 1.2 2008/04/28 20:22:59 martin Exp $");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+/*
+ * 7.12.3.6 signbit - determine whether the sign of an argument is negative
+ *          IEEE 754 single-precision version
+ */
+int
+__signbitf(float x)
+{
+       union ieee_single_u u;
+
+       u.sngu_f = x;
+
+       return (u.sngu_sng.sng_sign == 1);
+}
diff --git a/lib/nbsd_libc/gen/signbitl_ieee754.c b/lib/nbsd_libc/gen/signbitl_ieee754.c
new file mode 100644 (file)
index 0000000..7e8b153
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: signbitl_ieee754.c,v 1.1 2011/01/17 23:53:03 matt Exp $        */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD");
+#endif
+
+#include <machine/ieee.h>
+#include <math.h>
+
+#ifdef __HAVE_LONG_DOUBLE
+
+/*
+ * 7.12.3.6 signbit - determine whether the sign of an argument is negative
+ *          IEEE 754 compatible 128-bit extended-precision version
+ */
+int
+__signbitl(long double x)
+{
+       union ieee_ext_u u;
+
+       u.extu_ld = x;
+
+       return (u.extu_ext.ext_sign == 1);
+}
+
+#endif /* __HAVE_LONG_DOUBLE */
diff --git a/lib/nbsd_libc/gen/sigrelse.3 b/lib/nbsd_libc/gen/sigrelse.3
new file mode 100644 (file)
index 0000000..f70cc49
--- /dev/null
@@ -0,0 +1,80 @@
+.\"    $NetBSD: sigrelse.3,v 1.4 2010/04/30 04:39:16 jruoho Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 30, 2010
+.Dt SIGRELSE 3
+.Os
+.Sh NAME
+.Nm sigrelse
+.Nd manipulate current signal mask
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigrelse "int sig"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is made obsolete by
+.Xr sigprocmask 2 .
+.Ef
+.Pp
+The
+.Fn sigrelse
+function removes the signal
+.Fa sig
+from the calling process' signal mask.
+.Sh RETURN VALUES
+If successful, the
+.Fn sigrelse
+function returns 0.
+Otherwise \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn sigrelse
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The argument
+.Fa sig
+is not a valid signal number.
+.El
+.Sh SEE ALSO
+.Xr sigprocmask 2 ,
+.Xr sighold 3
+.Sh STANDARDS
+The
+.Fn sigrelse
+function conforms to
+.St -p1003.1-2001 .
+It was however marked as obsolete in the
+.St -p1003.1-2008
+revision of the standard.
diff --git a/lib/nbsd_libc/gen/sigrelse.c b/lib/nbsd_libc/gen/sigrelse.c
new file mode 100644 (file)
index 0000000..6a6643e
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: sigrelse.c,v 1.2 2008/04/28 20:22:59 martin Exp $      */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sigrelse.c,v 1.2 2008/04/28 20:22:59 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <signal.h>
+#include <stddef.h>
+
+int
+sigrelse(int sig)
+{
+       sigset_t set;
+
+       sigemptyset(&set);
+       if (sigaddset(&set, sig) != 0)
+               return (-1);
+
+       return (sigprocmask(SIG_UNBLOCK, &set, NULL));
+}
diff --git a/lib/nbsd_libc/gen/sigset.3 b/lib/nbsd_libc/gen/sigset.3
new file mode 100644 (file)
index 0000000..c5da281
--- /dev/null
@@ -0,0 +1,125 @@
+.\"    $NetBSD: sigset.3,v 1.8 2010/04/30 06:48:20 wiz Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 30, 2010
+.Dt SIGSET 3
+.Os
+.Sh NAME
+.Nm sigset
+.Nd manipulate signal dispositions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.\" The following is Quite Ugly, but syntactically correct.  Don't try to
+.\" fix it.
+.Ft void \*(lp*
+.Fn sigset "int sig" "void \*(lp*disp\*(rp\*(lpint\*(rp\*(rp\*(rp\*(lpint"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is made obsolete by
+.Xr sigaction 2
+and
+.Xr sigprocmask 2 .
+.Ef
+.Pp
+The
+.Fn sigset
+function manipulates the disposition of the signal
+.Fa sig .
+The new disposition is given in
+.Fa disp .
+.Pp
+If
+.Fa disp
+is one of
+.Dv SIG_DFL ,
+.Dv SIG_IGN ,
+or the address of a handler function,
+the disposition of
+.Fa sig
+is changed accordingly, and
+.Fa sig
+is removed from the process' signal mask.
+Also, if
+.Fa disp
+is the address of a handler function,
+.Fa sig
+will be added to the process' signal mask during execution of the handler.
+.Pp
+If
+.Fa disp
+is equal to
+.Dv SIG_HOLD ,
+.Fa sig
+is added to the calling process' signal mask and the disposition of
+.Fa sig
+remains unchanged.
+.Sh RETURN VALUES
+If successful, the
+.Fn sigset
+function returns
+.Dv SIG_HOLD
+if
+.Fa sig
+had been blocked,
+and the previous disposition of
+.Fa sig
+if it had not been blocked.
+Otherwise
+.Dv SIG_ERR
+is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn sigset
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The argument
+.Fa sig
+is not a valid signal number;
+or an attempt is made to ignore a signal that cannot be ignored,
+such as
+.Dv SIGKILL
+or
+.Dv SIGSTOP .
+.El
+.Sh SEE ALSO
+.Xr sigaction 2 ,
+.Xr sigprocmask 2
+.Sh STANDARDS
+The
+.Fn sigset
+function conforms to
+.St -p1003.1-2001 .
+It was however marked as obsolete in the
+.St -p1003.1-2008
+revision of the standard.
diff --git a/lib/nbsd_libc/gen/sigset.c b/lib/nbsd_libc/gen/sigset.c
new file mode 100644 (file)
index 0000000..466f41d
--- /dev/null
@@ -0,0 +1,95 @@
+/*     $NetBSD: sigset.c,v 1.2 2008/04/28 20:22:59 martin Exp $        */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sigset.c,v 1.2 2008/04/28 20:22:59 martin Exp $");
+#endif
+
+#include "namespace.h"
+#include <errno.h>
+#include <signal.h>
+#include <stddef.h>
+
+sig_t
+sigset(int sig, void (*disp)(int))
+{
+       sigset_t set, oset;
+       struct sigaction sa, osa;
+
+       osa.sa_handler = SIG_ERR;
+
+       if (disp == SIG_HOLD) {
+               /* Add sig to current signal mask. */
+               if (sigemptyset(&set) != 0)
+                       goto out;
+               if (sigaddset(&set, sig) != 0)
+                       goto out;
+               if (sigprocmask(SIG_BLOCK, &set, &oset) != 0)
+                       goto out;
+
+               if (sigismember(&oset, sig)) {
+                       /* Had been masked before, return SIG_HOLD. */
+                       osa.sa_handler = SIG_HOLD;
+               } else {
+                       /* Return previous disposition. */
+                       (void)sigaction(sig, NULL, &osa);
+               }
+       } else if (disp == SIG_ERR) {
+               errno = EINVAL;
+       } else {
+               /* Set up and install new disposition. */
+               sa.sa_handler = disp;
+               if (sigemptyset(&sa.sa_mask) != 0)
+                       goto out;
+               sa.sa_flags = 0;
+
+               if (sigaction(sig, &sa, &osa) != 0) {
+                       osa.sa_handler = SIG_ERR;
+                       goto out;
+               }
+                       
+               /* Delete sig from current signal mask. */
+               if (sigemptyset(&set) != 0)
+                       return (SIG_ERR);
+               if (sigaddset(&set, sig) != 0)
+                       return (SIG_ERR);
+               if (sigprocmask(SIG_UNBLOCK, &set, &oset) != 0)
+                       return (SIG_ERR);
+
+               /* If had been masked before, return SIG_HOLD. */
+               if (sigismember(&oset, sig))
+                       osa.sa_handler = SIG_HOLD;
+       }
+
+ out:
+       return (osa.sa_handler);
+}
diff --git a/lib/nbsd_libc/gen/sigsetops.3 b/lib/nbsd_libc/gen/sigsetops.3
new file mode 100644 (file)
index 0000000..e97e130
--- /dev/null
@@ -0,0 +1,124 @@
+.\"    $NetBSD: sigsetops.3,v 1.14 2003/08/07 16:42:57 agc Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)sigsetops.3        8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt SIGSETOPS 3
+.Os
+.Sh NAME
+.Nm sigemptyset ,
+.Nm sigfillset ,
+.Nm sigaddset ,
+.Nm sigdelset ,
+.Nm sigismember
+.Nd manipulate signal sets
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigemptyset "sigset_t *set"
+.Ft int
+.Fn sigfillset "sigset_t *set"
+.Ft int
+.Fn sigaddset "sigset_t *set" "int signo"
+.Ft int
+.Fn sigdelset "sigset_t *set" "int signo"
+.Ft int
+.Fn sigismember "sigset_t *set" "int signo"
+.Sh DESCRIPTION
+These functions manipulate signal sets stored in a
+.Fa sigset_t .
+Either
+.Fn sigemptyset
+or
+.Fn sigfillset
+must be called for every object of type
+.Fa sigset_t
+before any other use of the object.
+.Pp
+The
+.Fn sigemptyset
+function initializes a signal set to be empty.
+.Pp
+The
+.Fn sigfillset
+function initializes a signal set to contain all signals.
+.Pp
+The
+.Fn sigaddset
+function adds the specified signal
+.Fa signo
+to the signal set.
+.Pp
+The
+.Fn sigdelset
+function deletes the specified signal
+.Fa signo
+from the signal set.
+.Pp
+The
+.Fn sigismember
+function returns whether a specified signal
+.Fa signo
+is contained in the signal set.
+.Pp
+.Fn sigemptyset
+and
+.Fn sigfillset
+are provided as macros, but actual functions are available
+if their names are undefined (with #undef
+.Em name ) .
+.Sh RETURN VALUES
+The
+.Fn sigismember
+function returns 1
+if the signal is a member of the set,
+a 0 otherwise.
+The other functions return 0 upon success.
+A \-1 return value
+indicates an error occurred and the global variable
+.Va errno
+is set to indicate the reason.
+.Sh ERRORS
+These functions could fail if one of the following occurs:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+.Fa signo
+has an invalid value.
+.El
+.Sh SEE ALSO
+.Xr kill 2 ,
+.Xr sigaction 2 ,
+.Xr sigsuspend 2 ,
+.Xr signal 7
+.Sh STANDARDS
+These functions conform to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/gen/sigsetops.c b/lib/nbsd_libc/gen/sigsetops.c
new file mode 100644 (file)
index 0000000..5b22735
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: sigsetops.c,v 1.16 2010/07/31 00:04:43 joerg Exp $     */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ *
+ *     @(#)sigsetops.c 8.1 (Berkeley) 6/4/93
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)sigsetops.c        8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: sigsetops.c,v 1.16 2010/07/31 00:04:43 joerg Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#define        __SIGSETOPS_BODY
+
+#include <errno.h>
+#include <signal.h>
diff --git a/lib/nbsd_libc/gen/sleep.3 b/lib/nbsd_libc/gen/sleep.3
new file mode 100644 (file)
index 0000000..9cf8e19
--- /dev/null
@@ -0,0 +1,77 @@
+.\"    $NetBSD: sleep.3,v 1.15 2003/08/07 16:42:57 agc Exp $
+.\"
+.\" Copyright (c) 1986, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)sleep.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt SLEEP 3
+.Os
+.Sh NAME
+.Nm sleep
+.Nd suspend process execution for interval of seconds
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft unsigned int
+.Fn sleep "unsigned int seconds"
+.Sh DESCRIPTION
+The
+.Fn sleep
+function suspends execution of the calling process until either the
+number of seconds specified by
+.Fa seconds
+have elapsed or a signal is delivered to the calling process and its
+action is to invoke a signal-catching function or to terminate the
+process.
+The suspension time may be longer than requested due to the
+scheduling of other activity by the system.
+.Sh RETURN VALUES
+If the
+.Fn sleep
+function returns because the requested time has elapsed, the value
+returned will be zero.
+If the
+.Fn sleep
+function returns due to the delivery of a signal, the value returned
+will be the unslept amount (the request time minus the time actually
+slept) in seconds.
+.Sh SEE ALSO
+.Xr nanosleep 2 ,
+.Xr usleep 3
+.Sh STANDARDS
+The
+.Fn sleep
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+A
+.Fn sleep
+function appeared in
+.At v7 .
diff --git a/lib/nbsd_libc/gen/sleep.c b/lib/nbsd_libc/gen/sleep.c
new file mode 100644 (file)
index 0000000..a6b3cc9
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: sleep.c,v 1.22 2008/04/28 20:22:59 martin Exp $        */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sleep.c,v 1.22 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <time.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(sleep,_sleep)
+#endif
+
+unsigned int
+sleep(seconds)
+       unsigned int seconds;
+{
+       struct timespec rqt, rmt;
+
+       rqt.tv_sec  = seconds;
+       rqt.tv_nsec = 0;
+
+       nanosleep(&rqt, &rmt);
+
+       return (unsigned int)rmt.tv_sec;
+}
diff --git a/lib/nbsd_libc/gen/stringlist.3 b/lib/nbsd_libc/gen/stringlist.3
new file mode 100644 (file)
index 0000000..2eb83fc
--- /dev/null
@@ -0,0 +1,144 @@
+.\"    $NetBSD: stringlist.3,v 1.15 2010/05/06 09:46:49 jruoho Exp $
+.\"
+.\" Copyright (c) 1997, 1999 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This file was contributed to The NetBSD Foundation by Luke Mewburn.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 6, 2010
+.Dt STRINGLIST 3
+.Os
+.Sh NAME
+.Nm stringlist ,
+.Nm sl_init ,
+.Nm sl_add ,
+.Nm sl_free ,
+.Nm sl_find ,
+.Nm sl_delete
+.Nd stringlist manipulation functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stringlist.h
+.Ft StringList *
+.Fn sl_init
+.Ft int
+.Fn sl_add "StringList *sl" "char *item"
+.Ft void
+.Fn sl_free "StringList *sl" "int freeall"
+.Ft char *
+.Fn sl_find "StringList *sl" "const char *item"
+.Ft int
+.Fn sl_delete "StringList *sl" "const char *item" "int freeit"
+.Sh DESCRIPTION
+The
+.Nm
+functions manipulate stringlists, which are lists of
+strings that extend automatically if necessary.
+.Pp
+The
+.Ar StringList
+structure has the following definition:
+.Bd -literal -offset indent
+typedef struct _stringlist {
+       char    **sl_str;
+       size_t    sl_max;
+       size_t    sl_cur;
+} StringList;
+.Ed
+.Pp
+where:
+.Bl -tag -width "sl_str" -offset indent
+.It Ar sl_str
+is a pointer to the base of the array containing the list,
+.It Ar sl_max
+is the size of
+.Ar sl_str ,
+and
+.It Ar sl_cur
+is the offset in
+.Ar sl_str
+of the current element.
+.El
+.Pp
+The following stringlist manipulation functions are available:
+.Bl -tag -width "sl_delete()" -offset 2n
+.It Fn sl_init
+Create a stringlist.
+Returns a pointer to a
+.Ar StringList ,
+or
+.Dv NULL
+in case of failure.
+.It Fn sl_free
+Releases memory occupied by
+.Ar sl
+and the
+.Ar sl-\*[Gt]sl_str
+array.
+If
+.Ar freeall
+is non-zero, then each of the items within
+.Ar sl-\*[Gt]sl_str
+is released as well.
+.It Fn sl_add
+Add
+.Ar item
+to
+.Ar sl-\*[Gt]sl_str
+at
+.Ar sl-\*[Gt]sl_cur ,
+extending the size of
+.Ar sl-\*[Gt]sl_str .
+Returns zero upon success, \-1 upon failure.
+.It Fn sl_find
+Find
+.Ar item
+in
+.Ar sl ,
+returning
+.Dv NULL
+if it's not found.
+.It Fn sl_delete
+Remove
+.Ar item
+from the list.
+If
+.Ar freeit
+is non-zero, the string is freed.
+Returns
+.Dv 0
+if the name is found
+and
+.Dv \-1
+if the name is not found.
+.El
+.Sh SEE ALSO
+.Xr free 3 ,
+.Xr malloc 3
+.Sh HISTORY
+The
+.Nm
+functions appeared in
+.Nx 1.3 .
diff --git a/lib/nbsd_libc/gen/stringlist.c b/lib/nbsd_libc/gen/stringlist.c
new file mode 100644 (file)
index 0000000..0be588c
--- /dev/null
@@ -0,0 +1,156 @@
+/*     $NetBSD: stringlist.c,v 1.13 2008/04/28 20:22:59 martin Exp $   */
+
+/*-
+ * Copyright (c) 1994, 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: stringlist.c,v 1.13 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <err.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stringlist.h>
+
+#ifdef __weak_alias
+__weak_alias(sl_add,_sl_add)
+__weak_alias(sl_find,_sl_find)
+__weak_alias(sl_free,_sl_free)
+__weak_alias(sl_init,_sl_init)
+__weak_alias(sl_delete,_sl_delete)
+#endif
+
+#define _SL_CHUNKSIZE  20
+
+/*
+ * sl_init(): Initialize a string list
+ */
+StringList *
+sl_init(void)
+{
+       StringList *sl;
+
+       sl = malloc(sizeof(StringList));
+       if (sl == NULL)
+               return NULL;
+
+       sl->sl_cur = 0;
+       sl->sl_max = _SL_CHUNKSIZE;
+       sl->sl_str = malloc(sl->sl_max * sizeof(char *));
+       if (sl->sl_str == NULL) {
+               free(sl);
+               sl = NULL;
+       }
+       return sl;
+}
+
+
+/*
+ * sl_add(): Add an item to the string list
+ */
+int
+sl_add(StringList *sl, char *name)
+{
+
+       _DIAGASSERT(sl != NULL);
+
+       if (sl->sl_cur == sl->sl_max - 1) {
+               char    **new;
+
+               new = realloc(sl->sl_str,
+                   (sl->sl_max + _SL_CHUNKSIZE) * sizeof(char *));
+               if (new == NULL)
+                       return -1;
+               sl->sl_max += _SL_CHUNKSIZE;
+               sl->sl_str = new;
+       }
+       sl->sl_str[sl->sl_cur++] = name;
+       return 0;
+}
+
+
+/*
+ * sl_free(): Free a stringlist
+ */
+void
+sl_free(StringList *sl, int all)
+{
+       size_t i;
+
+       if (sl == NULL)
+               return;
+       if (sl->sl_str) {
+               if (all)
+                       for (i = 0; i < sl->sl_cur; i++)
+                               free(sl->sl_str[i]);
+               free(sl->sl_str);
+       }
+       free(sl);
+}
+
+
+/*
+ * sl_find(): Find a name in the string list
+ */
+char *
+sl_find(StringList *sl, const char *name)
+{
+       size_t i;
+
+       _DIAGASSERT(sl != NULL);
+
+       for (i = 0; i < sl->sl_cur; i++)
+               if (strcmp(sl->sl_str[i], name) == 0)
+                       return sl->sl_str[i];
+
+       return NULL;
+}
+
+int
+sl_delete(StringList *sl, const char *name, int all)
+{
+       size_t i, j;
+
+       for (i = 0; i < sl->sl_cur; i++)
+               if (strcmp(sl->sl_str[i], name) == 0) {
+                       if (all)
+                               free(sl->sl_str[i]);
+                       for (j = i + 1; j < sl->sl_cur; j++)
+                               sl->sl_str[j - 1] = sl->sl_str[j];
+                       sl->sl_str[--sl->sl_cur] = NULL;
+                       return 0;
+               }
+       return -1;
+}
+
diff --git a/lib/nbsd_libc/gen/sysconf.3 b/lib/nbsd_libc/gen/sysconf.3
new file mode 100644 (file)
index 0000000..34235f8
--- /dev/null
@@ -0,0 +1,329 @@
+.\"    $NetBSD: sysconf.3,v 1.37 2010/03/22 19:30:54 joerg Exp $
+.\"
+.\" Copyright (c) 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.
+.\" 3. 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.
+.\"
+.\"    @(#)sysconf.3   8.3 (Berkeley) 4/19/94
+.\"
+.Dd August 6, 2008
+.Dt SYSCONF 3
+.Os
+.Sh NAME
+.Nm sysconf
+.Nd get configurable system variables
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft long
+.Fn sysconf "int name"
+.Sh DESCRIPTION
+This interface is defined by
+.St -p1003.1-88 .
+A far more complete interface is available using
+.Xr sysctl 3 .
+.Pp
+The
+.Fn sysconf
+function provides a method for applications to determine the current
+value of a configurable system limit or option variable.
+The
+.Fa name
+argument specifies the system variable to be queried.
+Symbolic constants for each name value are found in the include file
+.In unistd.h .
+.Pp
+The available values are as follows:
+.Bl -tag -width "123456"
+.It Li _SC_ARG_MAX
+The maximum bytes of argument to
+.Xr execve 2 .
+.It Li _SC_ATEXIT_MAX
+The maxmimum number of functions that may be registered with
+.Xr atexit 3 .
+.It Li _SC_BARRIERS
+The version of
+.St -p1003.1
+and its
+Barriers
+option to which the system attempts to conform,
+otherwise \-1.
+.It Li _SC_CLOCK_SELECTION
+Return the
+.Tn POSIX
+version the implementation of the Clock Selection Option
+on this system conforms to,
+or \-1 if unavailable.
+.It Li _SC_CHILD_MAX
+The maximum number of simultaneous processes per user id.
+.It Li _SC_CLK_TCK
+The number of clock ticks per second.
+.It Li _SC_FSYNC
+Return 1 if the File Synchronization Option is available on this system,
+otherwise \-1.
+.It Li _SC_HOST_NAME_MAX
+The maximum size of a hostname, including NULL.
+.It Li _SC_IOV_MAX
+The maximum number of
+.Va iovec
+structures that a process has available for use with
+.Xr preadv 2 ,
+.Xr pwritev 2 ,
+.Xr readv 2 ,
+.Xr recvmsg 2 ,
+.Xr sendmsg 2
+or
+.Xr writev 2 .
+.It Li _SC_JOB_CONTROL
+Return 1 if job control is available on this system, otherwise \-1.
+.It Li _SC_LOGIN_NAME_MAX
+Returns the size of the storage required for a login name, in bytes,
+including the terminating NUL.
+.It Li _SC_MAPPED_FILES
+Return 1 if the Memory Mapped Files Option is available on this system,
+otherwise \-1.
+.It Li _SC_MEMLOCK
+Return 1 if the Process Memory Locking Option is available on this system,
+otherwise \-1.
+.It Li _SC_MEMLOCK_RANGE
+Return 1 if the Range Memory Locking Option is available on this system,
+otherwise \-1.
+.It Li _SC_MEMORY_PROTECTION
+Return 1 if the Memory Protection Option is available on this system,
+otherwise \-1.
+.It Li _SC_MONOTONIC_CLOCK
+Return the
+.Tn POSIX
+version the implementation of the Monotonic Clock Option
+on this system conforms to,
+or \-1 if unavailable.
+.It Li _SC_NGROUPS_MAX
+The maximum number of supplemental groups.
+.It Li _SC_OPEN_MAX
+The maximum number of open files per process.
+.It Li _SC_PAGESIZE
+The size of a system page in bytes.
+.It Li _SC_PASS_MAX
+The maximum length of the password, not counting NULL.
+.It Li _SC_READER_WRITER_LOCKS
+The version of
+.St -p1003.1
+and its
+Read-Write Locks
+option to which the system attempts to conform,
+otherwise \-1.
+.It Li _SC_REGEXP
+Return 1 if
+.Tn POSIX
+regular expressions are available on this system, otherwise \-1.
+.It Li _SC_SEMAPHORES
+The version of
+.St -p1003.1
+and its
+Semaphores
+option to which the system attempts to conform,
+otherwise \-1.
+.Pp
+Availability of the
+Semaphores
+option depends on the
+.Li P1003_1B_SEMAPHORE
+kernel option.
+.It Li _SC_SHELL
+Return 1 if
+.Tn POSIX
+shell is available on this system, otherwise \-1.
+.It Li _SC_SPIN_LOCKS
+The version of
+.St -p1003.1
+and its
+Spin Locks
+option to which the system attempts to conform,
+otherwise \-1.
+.It Li _SC_STREAM_MAX
+The minimum maximum number of streams that a process may have open
+at any one time.
+.It Li _SC_SYMLOOP_MAX
+The maximum number of symbolic links that may be expanded in a path name.
+.It Li _SC_SYNCHRONIZED_IO
+Return 1 if the Synchronized I/O Option is available on this system,
+otherwise \-1.
+.It Li _SC_THREADS
+The version of
+.St -p1003.1
+and its
+Threads
+option to which the system attempts to conform,
+otherwise \-1.
+.It Li _SC_TIMERS
+The version of
+.St -p1003.1
+and its
+Timers
+option to which the system attempts to conform,
+otherwise \-1.
+.It Li _SC_TZNAME_MAX
+The minimum maximum number of types supported for the name of a
+timezone.
+.It Li _SC_SAVED_IDS
+Returns 1 if saved set-group and saved set-user ID is available,
+otherwise \-1.
+.It Li _SC_VERSION
+The version of ISO/IEC 9945 (POSIX 1003.1) with which the system
+attempts to comply.
+.It Li _SC_XOPEN_SHM
+Return 1 if the
+.St -xpg4.2
+Shared Memory
+option is available on this system,
+otherwise \-1.
+.Pp
+Availability of the
+Shared Memory
+option depends on the
+.Li SYSVSHM
+kernel option.
+.It Li _SC_BC_BASE_MAX
+The maximum ibase/obase values in the
+.Xr bc 1
+utility.
+.It Li _SC_BC_DIM_MAX
+The maximum array size in the
+.Xr bc 1
+utility.
+.It Li _SC_BC_SCALE_MAX
+The maximum scale value in the
+.Xr bc 1
+utility.
+.It Li _SC_BC_STRING_MAX
+The maximum string length in the
+.Xr bc 1
+utility.
+.It Li _SC_COLL_WEIGHTS_MAX
+The maximum number of weights that can be assigned to any entry of
+the LC_COLLATE order keyword in the locale definition file.
+.It Li _SC_EXPR_NEST_MAX
+The maximum number of expressions that can be nested within
+parenthesis by the
+.Xr expr 1
+utility.
+.It Li _SC_LINE_MAX
+The maximum length in bytes of a text-processing utility's input
+line.
+.It Li _SC_RE_DUP_MAX
+The maximum number of repeated occurrences of a regular expression
+permitted when using interval notation.
+.It Li _SC_2_VERSION
+The version of POSIX 1003.2 with which the system attempts to comply.
+.It Li _SC_2_C_BIND
+Return 1 if the system's C-language development facilities support the
+C-Language Bindings Option, otherwise \-1.
+.It Li _SC_2_C_DEV
+Return 1 if the system supports the C-Language Development Utilities Option,
+otherwise \-1.
+.It Li _SC_2_CHAR_TERM
+Return 1 if the system supports at least one terminal type capable of
+all operations described in POSIX 1003.2, otherwise \-1.
+.It Li _SC_2_FORT_DEV
+Return 1 if the system supports the FORTRAN Development Utilities Option,
+otherwise \-1.
+.It Li _SC_2_FORT_RUN
+Return 1 if the system supports the FORTRAN Runtime Utilities Option,
+otherwise \-1.
+.It Li _SC_2_LOCALEDEF
+Return 1 if the system supports the creation of locales, otherwise \-1.
+.It Li _SC_2_SW_DEV
+Return 1 if the system supports the Software Development Utilities Option,
+otherwise \-1.
+.It Li _SC_2_UPE
+Return 1 if the system supports the User Portability Utilities Option,
+otherwise \-1.
+.It Li _SC_GETGR_R_SIZE_MAX
+The minimum size of the
+.Fa buffer
+passed to
+.Xr getgrgid_r 3
+and
+.Xr getgrnam_r 3 .
+.It Li _SC_GETPW_R_SIZE_MAX
+The minimum size of the
+.Fa buffer
+passed to
+.Xr getpwnam_r 3
+and
+.Xr getpwuid_r 3 .
+.It Li _SC_NPROCESSORS_CONF
+The number of processors configured.
+.It Li _SC_NPROCESSORS_ONLN
+The number of processors online (capable of running processes).
+.El
+.Sh RETURN VALUES
+If the call to
+.Nm sysconf
+is not successful, \-1 is returned and
+.Va errno
+is set appropriately.
+Otherwise, if the variable is associated with functionality that is not
+supported, \-1 is returned and
+.Va errno
+is not modified.
+Otherwise, the current variable value is returned.
+.Sh ERRORS
+The
+.Fn sysconf
+function may fail and set
+.Va errno
+for any of the errors specified for the library functions
+.Xr sysctl 3 .
+In addition, the following error may be reported:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The value of the
+.Fa name
+argument is invalid.
+.El
+.Sh SEE ALSO
+.Xr sysctl 3
+.Sh STANDARDS
+The
+.Fn sysconf
+function conforms to
+.St -p1003.1-90 .
+The constants
+.Li _SC_NPROCESSORS_CONF
+and
+.Li _SC_NPROCESSORS_ONLN
+are not part of the standard, but are provided by many systems.
+.Sh HISTORY
+The
+.Nm sysconf
+function first appeared in
+.Bx 4.4 .
+.Sh BUGS
+The value for _SC_STREAM_MAX is a minimum maximum, and required to be
+the same as ANSI C's FOPEN_MAX, so the returned value is a ridiculously
+small and misleading number.
diff --git a/lib/nbsd_libc/gen/sysconf.c b/lib/nbsd_libc/gen/sysconf.c
new file mode 100644 (file)
index 0000000..48e47a8
--- /dev/null
@@ -0,0 +1,413 @@
+/*     $NetBSD: sysconf.c,v 1.33 2008/08/06 17:17:04 matt Exp $        */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Sean Eric Fagan of Cygnus Support.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)sysconf.c  8.2 (Berkeley) 3/20/94";
+#else
+__RCSID("$NetBSD: sysconf.c,v 1.33 2008/08/06 17:17:04 matt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/sysctl.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+
+#include <errno.h>
+#include <limits.h>
+#include <time.h>
+#include <unistd.h>
+#include <paths.h>
+#include <pwd.h>
+
+#ifdef __weak_alias
+__weak_alias(sysconf,__sysconf)
+#endif
+
+/*
+ * sysconf --
+ *     get configurable system variables.
+ *
+ * XXX
+ * POSIX 1003.1 (ISO/IEC 9945-1, 4.8.1.3) states that the variable values
+ * not change during the lifetime of the calling process.  This would seem
+ * to require that any change to system limits kill all running processes.
+ * A workaround might be to cache the values when they are first retrieved
+ * and then simply return the cached value on subsequent calls.  This is
+ * less useful than returning up-to-date values, however.
+ */
+long
+sysconf(int name)
+{
+       struct rlimit rl;
+       size_t len;
+       int mib[CTL_MAXNAME], value;
+       unsigned int mib_len;
+       struct clockinfo tmpclock;
+       static int clk_tck;
+
+       len = sizeof(value);
+
+       /* Default length of the MIB */
+       mib_len = 2;
+
+       switch (name) {
+
+/* 1003.1 */
+       case _SC_ARG_MAX:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_ARGMAX;
+               break;
+       case _SC_CHILD_MAX:
+               return (getrlimit(RLIMIT_NPROC, &rl) ? -1 : (long)rl.rlim_cur);
+       case _O_SC_CLK_TCK:
+               /*
+                * For applications compiled when CLK_TCK was a compile-time
+                * constant.
+                */
+               return 100;
+       case _SC_CLK_TCK:
+               /*
+                * Has to be handled specially because it returns a
+                * struct clockinfo instead of an integer. Also, since
+                * this might be called often by some things that
+                * don't grok CLK_TCK can be a macro expanding to a
+                * function, cache the value.
+                */
+               if (clk_tck == 0) {
+                       mib[0] = CTL_KERN;
+                       mib[1] = KERN_CLOCKRATE;
+                       len = sizeof(struct clockinfo);
+                       clk_tck = sysctl(mib, 2, &tmpclock, &len, NULL, 0)
+                           == -1 ? -1 : tmpclock.hz;
+               }
+               return(clk_tck);
+       case _SC_JOB_CONTROL:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_JOB_CONTROL;
+               goto yesno;
+       case _SC_NGROUPS_MAX:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_NGROUPS;
+               break;
+       case _SC_OPEN_MAX:
+               return (getrlimit(RLIMIT_NOFILE, &rl) ? -1 : (long)rl.rlim_cur);
+       case _SC_STREAM_MAX:
+               mib[0] = CTL_USER;
+               mib[1] = USER_STREAM_MAX;
+               break;
+       case _SC_TZNAME_MAX:
+               mib[0] = CTL_USER;
+               mib[1] = USER_TZNAME_MAX;
+               break;
+       case _SC_SAVED_IDS:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_SAVED_IDS;
+               goto yesno;
+       case _SC_VERSION:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_POSIX1;
+               break;
+
+/* 1003.1b */
+       case _SC_PAGESIZE:
+               return _getpagesize();
+       case _SC_FSYNC:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_FSYNC;
+               goto yesno;
+       case _SC_SYNCHRONIZED_IO:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_SYNCHRONIZED_IO;
+               goto yesno;
+       case _SC_MAPPED_FILES:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_MAPPED_FILES;
+               goto yesno;
+       case _SC_MEMLOCK:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_MEMLOCK;
+               goto yesno;
+       case _SC_MEMLOCK_RANGE:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_MEMLOCK_RANGE;
+               goto yesno;
+       case _SC_MEMORY_PROTECTION:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_MEMORY_PROTECTION;
+               goto yesno;
+       case _SC_MONOTONIC_CLOCK:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_MONOTONIC_CLOCK;
+               goto yesno;
+       case _SC_SEMAPHORES:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_POSIX_SEMAPHORES;
+               goto yesno;
+       case _SC_TIMERS:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_POSIX_TIMERS;
+               goto yesno;
+
+/* 1003.1c */
+       case _SC_LOGIN_NAME_MAX:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_LOGIN_NAME_MAX;
+               break;
+       case _SC_THREADS:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_POSIX_THREADS;
+               goto yesno;
+
+/* 1003.1j */
+       case _SC_BARRIERS:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_POSIX_BARRIERS;
+               goto yesno;
+       case _SC_SPIN_LOCKS:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_POSIX_SPIN_LOCKS;
+               goto yesno;
+       /* Historical; Threads option in 1003.1-2001 */
+       case _SC_READER_WRITER_LOCKS:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_POSIX_READER_WRITER_LOCKS;
+               goto yesno;
+
+/* 1003.2 */
+       case _SC_BC_BASE_MAX:
+               mib[0] = CTL_USER;
+               mib[1] = USER_BC_BASE_MAX;
+               break;
+       case _SC_BC_DIM_MAX:
+               mib[0] = CTL_USER;
+               mib[1] = USER_BC_DIM_MAX;
+               break;
+       case _SC_BC_SCALE_MAX:
+               mib[0] = CTL_USER;
+               mib[1] = USER_BC_SCALE_MAX;
+               break;
+       case _SC_BC_STRING_MAX:
+               mib[0] = CTL_USER;
+               mib[1] = USER_BC_STRING_MAX;
+               break;
+       case _SC_COLL_WEIGHTS_MAX:
+               mib[0] = CTL_USER;
+               mib[1] = USER_COLL_WEIGHTS_MAX;
+               break;
+       case _SC_EXPR_NEST_MAX:
+               mib[0] = CTL_USER;
+               mib[1] = USER_EXPR_NEST_MAX;
+               break;
+       case _SC_LINE_MAX:
+               mib[0] = CTL_USER;
+               mib[1] = USER_LINE_MAX;
+               break;
+       case _SC_RE_DUP_MAX:
+               mib[0] = CTL_USER;
+               mib[1] = USER_RE_DUP_MAX;
+               break;
+       case _SC_2_VERSION:
+               mib[0] = CTL_USER;
+               mib[1] = USER_POSIX2_VERSION;
+               break;
+       case _SC_2_C_BIND:
+               mib[0] = CTL_USER;
+               mib[1] = USER_POSIX2_C_BIND;
+               goto yesno;
+       case _SC_2_C_DEV:
+               mib[0] = CTL_USER;
+               mib[1] = USER_POSIX2_C_DEV;
+               goto yesno;
+       case _SC_2_CHAR_TERM:
+               mib[0] = CTL_USER;
+               mib[1] = USER_POSIX2_CHAR_TERM;
+               goto yesno;
+       case _SC_2_FORT_DEV:
+               mib[0] = CTL_USER;
+               mib[1] = USER_POSIX2_FORT_DEV;
+               goto yesno;
+       case _SC_2_FORT_RUN:
+               mib[0] = CTL_USER;
+               mib[1] = USER_POSIX2_FORT_RUN;
+               goto yesno;
+       case _SC_2_LOCALEDEF:
+               mib[0] = CTL_USER;
+               mib[1] = USER_POSIX2_LOCALEDEF;
+               goto yesno;
+       case _SC_2_SW_DEV:
+               mib[0] = CTL_USER;
+               mib[1] = USER_POSIX2_SW_DEV;
+               goto yesno;
+       case _SC_2_UPE:
+               mib[0] = CTL_USER;
+               mib[1] = USER_POSIX2_UPE;
+               goto yesno;
+
+/* XPG 4.2 */
+       case _SC_IOV_MAX:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_IOV_MAX;
+               break;
+       case _SC_XOPEN_SHM:
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_SYSVIPC;
+               mib[2] = KERN_SYSVIPC_SHM;
+               mib_len = 3;
+               goto yesno;
+
+/* 1003.1-2001, XSI Option Group */
+       case _SC_AIO_LISTIO_MAX:
+               if (sysctlgetmibinfo("kern.aio_listio_max", &mib[0], &mib_len,
+                   NULL, NULL, NULL, SYSCTL_VERSION))
+                       return -1;
+               break; 
+       case _SC_AIO_MAX:
+               if (sysctlgetmibinfo("kern.aio_max", &mib[0], &mib_len,
+                   NULL, NULL, NULL, SYSCTL_VERSION))
+                       return -1;
+               break; 
+       case _SC_ASYNCHRONOUS_IO:
+               if (sysctlgetmibinfo("kern.posix_aio", &mib[0], &mib_len,
+                   NULL, NULL, NULL, SYSCTL_VERSION))
+                       return -1;
+               goto yesno;
+       case _SC_MESSAGE_PASSING:
+               if (sysctlgetmibinfo("kern.posix_msg", &mib[0], &mib_len,
+                   NULL, NULL, NULL, SYSCTL_VERSION))
+                       return -1;
+               goto yesno;
+       case _SC_MQ_OPEN_MAX:
+               if (sysctlgetmibinfo("kern.mqueue.mq_open_max", &mib[0],
+                   &mib_len, NULL, NULL, NULL, SYSCTL_VERSION))
+                       return -1;
+               break; 
+       case _SC_MQ_PRIO_MAX:
+               if (sysctlgetmibinfo("kern.mqueue.mq_prio_max", &mib[0],
+                   &mib_len, NULL, NULL, NULL, SYSCTL_VERSION))
+                       return -1;
+               break; 
+       case _SC_PRIORITY_SCHEDULING:
+               if (sysctlgetmibinfo("kern.posix_sched", &mib[0], &mib_len,
+                   NULL, NULL, NULL, SYSCTL_VERSION))
+                       return -1;
+               goto yesno;
+       case _SC_ATEXIT_MAX:
+               mib[0] = CTL_USER;
+               mib[1] = USER_ATEXIT_MAX;
+               break;
+
+/* 1003.1-2001, TSF */
+       case _SC_GETGR_R_SIZE_MAX:
+               return _GETGR_R_SIZE_MAX;
+       case _SC_GETPW_R_SIZE_MAX:
+               return _GETPW_R_SIZE_MAX;
+
+/* Unsorted */
+       case _SC_HOST_NAME_MAX:
+               return MAXHOSTNAMELEN;
+       case _SC_PASS_MAX:
+               return _PASSWORD_LEN;
+       case _SC_REGEXP:
+               return _POSIX_REGEXP;
+       case _SC_SHELL:
+               return _POSIX_SHELL;
+       case _SC_SYMLOOP_MAX:
+               return MAXSYMLINKS;
+
+yesno:         if (sysctl(mib, mib_len, &value, &len, NULL, 0) == -1)
+                       return (-1);
+               if (value == 0)
+                       return (-1);
+               return (value);
+
+/* Extensions */
+       case _SC_NPROCESSORS_CONF:
+               mib[0] = CTL_HW;
+               mib[1] = HW_NCPU;
+               break;
+       case _SC_NPROCESSORS_ONLN:
+               mib[0] = CTL_HW;
+               mib[1] = HW_NCPUONLINE;
+               break;
+
+/* Native */
+       case _SC_SCHED_RT_TS:
+               if (sysctlgetmibinfo("kern.sched.rtts", &mib[0], &mib_len,
+                   NULL, NULL, NULL, SYSCTL_VERSION))      
+                       return -1;              
+               break;
+       case _SC_SCHED_PRI_MIN:
+               if (sysctlgetmibinfo("kern.sched.pri_min", &mib[0], &mib_len,
+                   NULL, NULL, NULL, SYSCTL_VERSION))
+                       return -1;
+               break;
+       case _SC_SCHED_PRI_MAX:
+               if (sysctlgetmibinfo("kern.sched.pri_max", &mib[0], &mib_len,
+                   NULL, NULL, NULL, SYSCTL_VERSION))
+                       return -1;
+               break;
+       case _SC_THREAD_DESTRUCTOR_ITERATIONS:
+               return _POSIX_THREAD_DESTRUCTOR_ITERATIONS;
+       case _SC_THREAD_KEYS_MAX:
+               return _POSIX_THREAD_KEYS_MAX;
+       case _SC_THREAD_STACK_MIN:
+               return _getpagesize();
+       case _SC_THREAD_THREADS_MAX:
+               if (sysctlgetmibinfo("kern.maxproc", &mib[0], &mib_len,
+                   NULL, NULL, NULL, SYSCTL_VERSION))  /* XXX */
+                       return -1;
+               goto yesno;
+       case _SC_THREAD_ATTR_STACKADDR:
+               return _POSIX_THREAD_ATTR_STACKADDR;
+       case _SC_THREAD_ATTR_STACKSIZE:
+               return _POSIX_THREAD_ATTR_STACKSIZE;
+       case _SC_THREAD_SAFE_FUNCTIONS:
+               return _POSIX_THREAD_SAFE_FUNCTIONS;
+       case _SC_THREAD_PRIORITY_SCHEDULING:
+       case _SC_THREAD_PRIO_INHERIT:
+       case _SC_THREAD_PRIO_PROTECT:
+       case _SC_THREAD_PROCESS_SHARED:
+               return -1;
+       case _SC_TTY_NAME_MAX:
+               return pathconf(_PATH_DEV, _PC_NAME_MAX);
+       default:
+               errno = EINVAL;
+               return (-1);
+       }
+       return (sysctl(mib, mib_len, &value, &len, NULL, 0) == -1 ? -1 : value); 
+}
diff --git a/lib/nbsd_libc/gen/sysctl.3 b/lib/nbsd_libc/gen/sysctl.3
new file mode 100644 (file)
index 0000000..79da555
--- /dev/null
@@ -0,0 +1,724 @@
+.\"    $NetBSD: sysctl.3,v 1.200 2010/03/22 19:30:54 joerg Exp $
+.\"
+.\" Copyright (c) 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.
+.\" 3. 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.
+.\"
+.\"    @(#)sysctl.3    8.4 (Berkeley) 5/9/95
+.\"
+.Dd September 26, 2009
+.Dt SYSCTL 3
+.Os
+.Sh NAME
+.Nm sysctl ,
+.Nm sysctlbyname ,
+.Nm sysctlgetmibinfo ,
+.Nm sysctlnametomib
+.Nd get or set system information
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/param.h
+.In sys/sysctl.h
+.Ft int
+.Fn sysctl "const int *name" "u_int namelen" "void *oldp" "size_t *oldlenp" \
+"const void *newp" "size_t newlen"
+.Ft int
+.Fn sysctlbyname "const char *sname" "void *oldp" "size_t *oldlenp" \
+"const void *newp" "size_t newlen"
+.Ft int
+.Fn sysctlgetmibinfo "const char *sname" "int *name" "u_int *namelenp" \
+"char *cname" "size_t *csz" "struct sysctlnode **rnode" "int v"
+.Ft int
+.Fn sysctlnametomib "const char *sname" "int *name" "size_t *namelenp"
+.Sh DESCRIPTION
+The
+.Nm
+function retrieves system information and allows processes with
+appropriate privileges to set system information.
+The information available from
+.Nm
+consists of integers, strings, and tables.
+Information may be retrieved and set from the command interface
+using the
+.Xr sysctl 8
+utility.
+.Pp
+Unless explicitly noted below,
+.Nm
+returns a consistent snapshot of the data requested.
+Consistency is obtained by locking the destination
+buffer into memory so that the data may be copied out without blocking.
+Calls to
+.Nm
+are serialized to avoid deadlock.
+.Pp
+The state is described using a ``Management Information Base'' (MIB)
+style name, listed in
+.Fa name ,
+which is a
+.Fa namelen
+length array of integers.
+.Pp
+The
+.Fn sysctlbyname
+function accepts a string representation of a MIB entry and internally
+maps it to the appropriate numeric MIB representation.
+Its semantics are otherwise no different from
+.Fn sysctl .
+.Pp
+The information is copied into the buffer specified by
+.Fa oldp .
+The size of the buffer is given by the location specified by
+.Fa oldlenp
+before the call,
+and that location gives the amount of data copied after a successful call.
+If the amount of data available is greater
+than the size of the buffer supplied,
+the call supplies as much data as fits in the buffer provided
+and returns with the error code ENOMEM.
+If the old value is not desired,
+.Fa oldp
+and
+.Fa oldlenp
+should be set to
+.Dv NULL .
+.Pp
+The size of the available data can be determined by calling
+.Nm
+with a
+.Dv NULL
+parameter for
+.Fa oldp .
+The size of the available data will be returned in the location pointed to by
+.Fa oldlenp .
+For some operations, the amount of space may change often.
+For these operations,
+the system attempts to round up so that the returned size is
+large enough for a call to return the data shortly thereafter.
+.Pp
+To set a new value,
+.Fa newp
+is set to point to a buffer of length
+.Fa newlen
+from which the requested value is to be taken.
+If a new value is not to be set,
+.Fa newp
+should be set to
+.Dv NULL
+and
+.Fa newlen
+set to 0.
+.Pp
+The
+.Fn sysctlnametomib
+function can be used to map the string representation of a MIB entry
+to the numeric version.
+The
+.Fa name
+argument should point to an array of integers large enough to hold the
+MIB, and
+.Fa namelenp
+should indicate the number of integer slots available.
+Following a successful translation, the size_t indicated by
+.Fa namelenp
+will be changed to show the number of slots consumed.
+.Pp
+The
+.Fn sysctlgetmibinfo
+function performs name translation similar to
+.Fn sysctlnametomib ,
+but also canonicalizes the name (or returns the first erroneous token
+from the string being parsed) into the space indicated by
+.Fa cname
+and
+.Fa csz .
+.Fa csz
+should indicate the size of the buffer pointed to by
+.Fa cname
+and on return, will indicate the size of the returned string including
+the trailing
+.Sq nul
+character.
+.Pp
+The
+.Fa rnode
+and
+.Fa v
+arguments to
+.Fn sysctlgetmibinfo
+are used to provide a tree for it to parse into, and to get back
+either a pointer to, or a copy of, the terminal node.
+If
+.Fa rnode
+is
+.Dv NULL ,
+.Fn sysctlgetmibinfo
+uses its own internal tree for parsing, and checks it against the
+kernel at each call, to make sure that the name-to-number mapping is
+kept up to date.
+The
+.Fa v
+argument is ignored in this case.
+If
+.Fa rnode
+is not
+.Dv NULL
+but the pointer it references is, on a successful return,
+.Fa rnode
+will be adjusted to point to a copy of the terminal node.
+The
+.Fa v
+argument indicates which version of the
+.Nm
+node structure the caller wants.
+The application must later
+.Fn free
+this copy.
+If neither
+.Fa rnode
+nor the pointer it references are
+.Dv NULL ,
+the pointer is used as the address of a tree over which the parsing is
+done.
+In this last case, the tree is not checked against the kernel, no
+refreshing of the mappings is performed, and the value given by
+.Fa v
+must agree with the version indicated by the tree.
+It is recommended that applications always use
+.Dv SYSCTL_VERSION
+as the value for
+.Fa v ,
+as defined in the include file
+.Pa sys/sysctl.h .
+.Pp
+The numeric and text names of sysctl variables are described in
+.Xr sysctl 7 .
+The numeric names are defined as preprocessor macros.
+The top level names are defined with a CTL_ prefix in
+.In sys/sysctl.h .
+The next and subsequent levels down have different prefixes for each
+subtree.
+.Pp
+For example, the following retrieves the maximum number of processes allowed
+in the system - the
+.Li kern.maxproc
+variable:
+.Bd -literal -offset indent -compact
+int mib[2], maxproc;
+size_t len;
+.sp
+mib[0] = CTL_KERN;
+mib[1] = KERN_MAXPROC;
+len = sizeof(maxproc);
+sysctl(mib, 2, \*[Am]maxproc, \*[Am]len, NULL, 0);
+.Ed
+.sp
+To retrieve the standard search path for the system utilities -
+.Li user.cs_path :
+.Bd -literal -offset indent -compact
+int mib[2];
+size_t len;
+char *p;
+.sp
+mib[0] = CTL_USER;
+mib[1] = USER_CS_PATH;
+sysctl(mib, 2, NULL, \*[Am]len, NULL, 0);
+p = malloc(len);
+sysctl(mib, 2, p, \*[Am]len, NULL, 0);
+.Ed
+.Sh DYNAMIC OPERATIONS
+Several meta-identifiers are provided to perform operations on the
+.Nm
+tree itself, or support alternate means of accessing the data
+instrumented by the
+.Nm
+tree.
+.Bl -column CTLXCREATESYMXXX
+.It Sy Name    Description
+.It CTL\_QUERY Retrieve a mapping of names to numbers below a given node
+.It CTL\_CREATE        Create a new node
+.It CTL\_CREATESYM     Create a new node by its kernel symbol
+.It CTL\_DESTROY       Destroy a node
+.It CTL\_DESCRIBE      Retrieve node descriptions
+.El
+.Pp
+The core interface to all of these meta-functions is the structure
+that the kernel uses to describe the tree internally, as defined in
+.In sys/sysctl.h
+as:
+.Pp
+.Bd -literal
+struct sysctlnode {
+        uint32_t sysctl_flags;          /* flags and type */
+        int32_t sysctl_num;             /* mib number */
+        char sysctl_name[SYSCTL_NAMELEN]; /* node name */
+        uint32_t sysctl_ver;        /* node's version vs. rest of tree */
+        uint32_t __rsvd;
+        union {
+                struct {
+                        uint32_t suc_csize; /* size of child node array */
+                        uint32_t suc_clen; /* number of valid children */
+                        struct sysctlnode* suc_child; /* array of child nodes */
+                } scu_child;
+                struct {
+                        void *sud_data; /* pointer to external data */
+                        size_t sud_offset; /* offset to data */
+                } scu_data;
+                int32_t scu_alias;      /* node this node refers to */
+                int32_t scu_idata;      /* immediate "int" data */
+                u_quad_t scu_qdata;     /* immediate "u_quad_t" data */
+        } sysctl_un;
+        size_t _sysctl_size;            /* size of instrumented data */
+        sysctlfn _sysctl_func;          /* access helper function */
+        struct sysctlnode *sysctl_parent; /* parent of this node */
+        const char *sysctl_desc;        /* description of node */
+};
+
+#define sysctl_csize    sysctl_un.scu_child.suc_csize
+#define sysctl_clen     sysctl_un.scu_child.suc_clen
+#define sysctl_child    sysctl_un.scu_child.suc_child
+#define sysctl_data     sysctl_un.scu_data.sud_data
+#define sysctl_offset   sysctl_un.scu_data.sud_offset
+#define sysctl_alias    sysctl_un.scu_alias
+#define sysctl_idata    sysctl_un.scu_idata
+#define sysctl_qdata    sysctl_un.scu_qdata
+.Ed
+.Pp
+Querying the tree to discover the name to number mapping permits
+dynamic discovery of all the data that the tree currently has
+instrumented.
+For example, to discover all the nodes below the
+CTL_VFS node:
+.Pp
+.Bd -literal -offset indent -compact
+struct sysctlnode query, vfs[128];
+int mib[2];
+size_t len;
+.sp
+mib[0] = CTL_VFS;
+mib[1] = CTL_QUERY;
+memset(\*[Am]query, 0, sizeof(query));
+query.sysctl_flags = SYSCTL_VERSION;
+len = sizeof(vfs);
+sysctl(mib, 2, \*[Am]vfs[0], \*[Am]len, \*[Am]query, sizeof(query));
+.Ed
+.Pp
+Note that a reference to an empty node with
+.Fa sysctl_flags
+set to
+.Dv SYSCTL_VERSION
+is passed to sysctl in order to indicate the version that the program
+is using.
+All dynamic operations passing nodes into sysctl require that the
+version be explicitly specified.
+.Pp
+Creation and destruction of nodes works by constructing part of a new
+node description (or a description of the existing node) and invoking
+CTL_CREATE (or CTL_CREATESYM) or CTL_DESTROY at the parent of the new
+node, with a pointer to the new node passed via the
+.Fa new
+and
+.Fa newlen
+arguments.
+If valid values for
+.Fa old
+and
+.Fa oldlenp
+are passed, a copy of the new node once in the tree will be returned.
+If the create operation fails because a node with the same name or MIB
+number exists, a copy of the conflicting node will be returned.
+.Pp
+The minimum requirements for creating a node are setting the
+.Fa sysctl_flags
+to indicate the new node's type,
+.Fa sysctl_num
+to either the new node's number (or CTL_CREATE or CTL_CREATESYM if a
+dynamically allocated MIB number is acceptable),
+.Fa sysctl_size
+to the size of the data to be instrumented (which must agree with the
+given type), and
+.Fa sysctl_name
+must be set to the new node's name.
+Nodes that are not of type
+.Dq node
+must also have some description of the data to be instrumented, which
+will vary depending on what is to be instrumented.
+.Pp
+If existing kernel data is to be covered by this new node, its address
+should be given in
+.Fa sysctl_data
+or, if CTL_CREATESYM is used,
+.Fa sysctl_data
+should be set to a string containing its name from the kernel's symbol
+table.
+If new data is to be instrumented and an initial value is available,
+the new integer or quad type data should be placed into either
+.Fa sysctl_idata
+or
+.Fa sysctl_qdata ,
+respectively, along with the SYSCTL_IMMEDIATE flag being set, or
+.Fa sysctl_data
+should be set to point to a copy of the new data, and the
+SYSCTL_OWNDATA flag must be set.
+This latter method is the only way that new string and struct type
+nodes can be initialized.
+Invalid kernel addresses are accepted, but any attempt to access those
+nodes will return an error.
+.Pp
+The
+.Fa sysctl_csize ,
+.Fa sysctl_clen ,
+.Fa sysctl_child ,
+.Fa sysctl_parent ,
+and
+.Fa sysctl_alias
+members are used by the kernel to link the tree together and must be
+.Dv NULL
+or 0.
+Nodes created in this manner cannot have helper functions, so
+.Fa sysctl_func
+must also be
+.Dv NULL .
+If the
+.Fa sysctl_ver
+member is non-zero, it must match either the version of the parent or
+the version at the root of the MIB or an error is returned.
+This can be used to ensure that nodes are only added or removed from a
+known state of the tree.
+Note: It may not be possible to determine the version at the root
+of the tree.
+.Pp
+This example creates a new subtree and adds a node to it that controls the
+.Fa audiodebug
+kernel variable, thereby making it tunable at at any time, without
+needing to use
+.Xr ddb 4
+or
+.Xr kvm 3
+to alter the kernel's memory directly.
+.Pp
+.Bd -literal -offset indent -compact
+struct sysctlnode node;
+int mib[2];
+size_t len;
+.sp
+mib[0] = CTL_CREATE;           /* create at top-level */
+len = sizeof(node);
+memset(\*[Am]node, 0, len);
+node.sysctl_flags = SYSCTL_VERSION|CTLFLAG_READWRITE|CTLTYPE_NODE;
+snprintf(node.sysctl_name, sizeof(node.sysctl_name), "local");
+node.sysctl_num = CTL_CREATE;  /* request dynamic MIB number */
+sysctl(\*[Am]mib[0], 1, \*[Am]node, \*[Am]len, \*[Am]node, len);
+.sp
+mib[0] = node.sysctl_num;      /* use new MIB number */
+mib[1] = CTL_CREATESYM;                /* create at second level */
+len = sizeof(node);
+memset(\*[Am]node, 0, len);
+node.sysctl_flags = SYSCTL_VERSION|CTLFLAG_READWRITE|CTLTYPE_INT;
+snprintf(node.sysctl_name, sizeof(node.sysctl_name), "audiodebug");
+node.sysctl_num = CTL_CREATE;
+node.sysctl_data = "audiodebug"; /* kernel symbol to be used */
+sysctl(\*[Am]mib[0], 2, NULL, NULL, \*[Am]node, len);
+.Ed
+.Pp
+The process for deleting nodes is similar, but less data needs to
+be supplied.
+Only the
+.Fa sysctl_num
+field
+needs to be filled in; almost all other fields must be left blank.
+The
+.Fa sysctl_name
+and/or
+.Fa sysctl_ver
+fields can be filled in with the name and version of the existing node
+as additional checks on what will be deleted.
+If all the given data fail to match any node, nothing will be deleted.
+If valid values for
+.Fa old
+and
+.Fa oldlenp
+are supplied and a node is deleted, a copy of what was in the MIB tree
+will be returned.
+.Pp
+This sample code shows the deletion of the two nodes created in the
+above example:
+.Pp
+.Bd -literal -offset indent -compact
+int mib[2];
+.sp
+len = sizeof(node);
+memset(\*[Am]node, 0, len);
+node.sysctl_flags = SYSCTL_VERSION;
+.sp
+mib[0] = 3214;                 /* assumed number for "local" */
+mib[1] = CTL_DESTROY;
+node.sysctl_num = 3215;                /* assumed number for "audiodebug" */
+sysctl(\*[Am]mib[0], 2, NULL, NULL, \*[Am]node, len);
+.sp
+mib[0] = CTL_DESTROY;
+node.sysctl_num = 3214;                /* now deleting "local" */
+sysctl(\*[Am]mib[0], 1, NULL, NULL, \*[Am]node, len);
+.Ed
+.Pp
+Descriptions of each of the nodes can also be retrieved, if they are
+available.
+Descriptions can be retrieved in bulk at each level or on a per-node
+basis.
+The layout of the buffer into which the descriptions are returned is a
+series of variable length structures, each of which describes its own
+size.
+The length indicated includes the terminating
+.Sq nul
+character.
+Nodes that have no description or where the description is not
+available are indicated by an empty string.
+The
+.Fa descr_ver
+will match the
+.Fa sysctl_ver
+value for a given node, so that descriptions for nodes whose number
+have been recycled can be detected and ignored or discarded.
+.Pp
+.Bd -literal
+struct sysctldesc {
+        int32_t         descr_num;      /* mib number of node */
+        uint32_t        descr_ver;      /* version of node */
+        uint32_t        descr_len;      /* length of description string */
+        char            descr_str[1];   /* not really 1...see above */
+};
+.Ed
+.Pp
+The
+.Fn NEXT_DESCR
+macro can be used to skip to the next description in the retrieved
+list.
+.Pp
+.Bd -literal -offset indent -compact
+struct sysctlnode desc;
+struct sysctldesc *d;
+char buf[1024];
+int mib[2];
+size_t len;
+.sp
+/* retrieve kern-level descriptions */
+mib[0] = CTL_KERN;
+mib[1] = CTL_DESCRIBE;
+d = (struct sysctldesc *)\*[Am]buf[0];
+len = sizeof(buf);
+sysctl(mib, 2, d, \*[Am]len, NULL, 0);
+while ((caddr_t)d \*[Lt] (caddr_t)\*[Am]buf[len]) {
+       printf("node %d: %.*s\\n", d-\*[Gt]descr_num, d-\*[Gt]descr_len,
+           d-\*[Gt]descr_str);
+       d = NEXT_DESCR(d);
+}
+.sp
+/* retrieve description for kern.securelevel */
+memset(\*[Am]desc, 0, sizeof(desc));
+desc.sysctl_flags = SYSCTL_VERSION;
+desc.sysctl_num = KERN_SECURELEVEL;
+d = (struct sysctldesc *)\*[Am]buf[0];
+len = sizeof(buf);
+sysctl(mib, 2, d, \*[Am]len, \*[Am]desc, sizeof(desc));
+printf("kern.securelevel: %.*s\\n", d-\*[Gt]descr_len, d-\*[Gt]descr_str);
+.Ed
+.Pp
+Descriptions can also be set as follows, subject to the following rules:
+.Pp
+.Bl -bullet -compact
+.It
+The kernel securelevel is at zero or lower
+.It
+The caller has super-user privileges
+.It
+The node does not currently have a description
+.It
+The node is not marked as
+.Dq permanent
+.El
+.Pp
+.Bd -literal -offset indent -compact
+struct sysctlnode desc;
+int mib[2];
+.sp
+/* presuming the given top-level node was just added... */
+mib[0] = 3214; /* mib numbers taken from previous examples */
+mib[1] = CTL_DESCRIBE;
+memset(\*[Am]desc, 0, sizeof(desc));
+desc.sysctl_flags = SYSCTL_VERSION;
+desc.sysctl_num = 3215;
+desc.sysctl_desc = "audio debug control knob";
+sysctl(mib, 2, NULL, NULL, \*[Am]desc, sizeof(desc));
+.Ed
+.Pp
+Upon successfully setting a description, the new description will be
+returned in the space indicated by the
+.Fa oldp
+and
+.Fa oldlenp
+arguments.
+.Pp
+The
+.Fa sysctl_flags
+field in the struct sysctlnode contains the sysctl version, node type
+information, and a number of flags.
+The macros
+.Fn SYSCTL_VERS ,
+.Fn SYSCTL_TYPE ,
+and
+.Fn SYSCTL_FLAGS
+can be used to access the different fields.
+Valid flags are:
+.Bl -column CTLFLAGXPERMANENTXXX
+.It Sy Name    Description
+.It CTLFLAG\_READONLY  Node is read-only
+.It CTLFLAG\_READWRITE Node is writable by the superuser
+.It CTLFLAG\_ANYWRITE  Node is writable by anyone
+.It CTLFLAG\_PRIVATE   Node is readable only by the superuser
+.It CTLFLAG\_PERMANENT Node cannot be removed (cannot be set by
+processes)
+.It CTLFLAG\_OWNDATA   Node owns data and does not instrument
+existing data
+.It CTLFLAG\_IMMEDIATE Node contains instrumented data and does not
+instrument existing data
+.It CTLFLAG\_HEX       Node's contents should be displayed in a hexadecimal
+form
+.It CTLFLAG\_ROOT      Node is the root of a tree (cannot be set at
+any time)
+.It CTLFLAG\_ANYNUMBER Node matches any MIB number (cannot be set by
+processes)
+.It CTLFLAG\_HIDDEN    Node not displayed by default
+.It CTLFLAG\_ALIAS     Node refers to a sibling node (cannot be set
+by processes)
+.It CTLFLAG\_OWNDESC   Node owns its own description string space
+.El
+.Sh RETURN VALUES
+If the call to
+.Nm
+is successful, 0 is returned.
+Otherwise \-1 is returned and
+.Va errno
+is set appropriately.
+.Sh FILES
+.Bl -tag -width \*[Lt]netinet6/udp6Xvar.h\*[Gt] -compact
+.It Aq Pa sys/sysctl.h
+definitions for top level identifiers, second level kernel and hardware
+identifiers, and user level identifiers
+.It Aq Pa sys/socket.h
+definitions for second level network identifiers
+.It Aq Pa sys/gmon.h
+definitions for third level profiling identifiers
+.It Aq Pa uvm/uvm_param.h
+definitions for second level virtual memory identifiers
+.It Aq Pa netinet/in.h
+definitions for third level IPv4/v6 identifiers and
+fourth level IPv4/v6 identifiers
+.It Aq Pa netinet/icmp_var.h
+definitions for fourth level ICMP identifiers
+.It Aq Pa netinet/icmp6.h
+definitions for fourth level ICMPv6 identifiers
+.It Aq Pa netinet/tcp_var.h
+definitions for fourth level TCP identifiers
+.It Aq Pa netinet/udp_var.h
+definitions for fourth level UDP identifiers
+.It Aq Pa netinet6/udp6_var.h
+definitions for fourth level IPv6 UDP identifiers
+.It Aq Pa netinet6/ipsec.h
+definitions for fourth level IPsec identifiers
+.It Aq Pa netkey/key_var.h
+definitions for third level PF_KEY identifiers
+.It Aq Pa machine/cpu.h
+definitions for second level machdep identifiers
+.El
+.Sh ERRORS
+The following errors may be reported:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+The buffer
+.Fa name ,
+.Fa oldp ,
+.Fa newp ,
+or length pointer
+.Fa oldlenp
+contains an invalid address, or the requested value is temporarily
+unavailable.
+.It Bq Er EINVAL
+The
+.Fa name
+array is zero or greater than CTL_MAXNAME.
+.It Bq Er EINVAL
+A non-null
+.Fa newp
+is given and its specified length in
+.Fa newlen
+is too large or too small, or the given value is not acceptable for
+the given node.
+.It Bq Er EISDIR
+The
+.Fa name
+array specifies an intermediate rather than terminal name.
+.It Bq Er ENOENT
+The
+.Fa name
+array specifies a node that does not exist in the tree.
+.It Bq Er ENOENT
+An attempt was made to destroy a node that does not exist, or to
+create or destroy a node below a node that does not exist.
+.It Bq Er ENOMEM
+The length pointed to by
+.Fa oldlenp
+is too short to hold the requested value.
+.It Bq Er ENOTDIR
+The
+.Fa name
+array specifies a node below a node that addresses data.
+.It Bq Er ENOTEMPTY
+An attempt was made to destroy a node that still has children.
+.It Bq Er EOPNOTSUPP
+The
+.Fa name
+array specifies a value that is unknown or a meta-operation was
+attempted that the requested node does not support.
+.It Bq Er EPERM
+An attempt is made to set a read-only value.
+.It Bq Er EPERM
+A process without appropriate privilege attempts to set a value or to
+create or destroy a node.
+.It Bq Er EPERM
+An attempt to change a value protected by the current kernel security
+level is made.
+.El
+.Sh SEE ALSO
+.Xr sysctl 7 ,
+.Xr sysctl 8 ,
+.Xr secmodel_securelevel 9
+.\" .Xr sysctl 9
+.Sh HISTORY
+The
+.Nm
+function first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/gen/sysctl.c b/lib/nbsd_libc/gen/sysctl.c
new file mode 100644 (file)
index 0000000..6af5685
--- /dev/null
@@ -0,0 +1,403 @@
+/*     $NetBSD: sysctl.c,v 1.30 2008/08/27 08:56:49 christos Exp $     */
+
+/*-
+ * Copyright (c) 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)sysctl.c   8.2 (Berkeley) 1/4/94";
+#else
+__RCSID("$NetBSD: sysctl.c,v 1.30 2008/08/27 08:56:49 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#define __COMPAT_SYSCTL
+#include <sys/sysctl.h>
+
+#include <errno.h>
+#include <paths.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include "extern.h"
+
+#ifdef __weak_alias
+__weak_alias(sysctl,_sysctl)
+#endif
+
+/*
+ * handles requests off the user subtree
+ */
+static int user_sysctl(const int *, u_int, void *, size_t *,
+                       const void *, size_t);
+
+/*
+ * copies out individual nodes taking target version into account
+ */
+static size_t __cvt_node_out(uint, const struct sysctlnode *, void **,
+                            size_t *);
+
+#include <stdlib.h>
+
+int
+sysctl(name, namelen, oldp, oldlenp, newp, newlen)
+       const int *name;
+       unsigned int namelen;
+       void *oldp;
+       const void *newp;
+       size_t *oldlenp, newlen;
+{
+       size_t oldlen, savelen;
+       int error;
+
+       if (name[0] != CTL_USER)
+               return (__sysctl(name, namelen, oldp, oldlenp,
+                                newp, newlen));
+
+       oldlen = (oldlenp == NULL) ? 0 : *oldlenp;
+       savelen = oldlen;
+       error = user_sysctl(name + 1, namelen - 1, oldp, &oldlen, newp, newlen);
+
+       if (error != 0) {
+               errno = error;
+               return (-1);
+       }
+
+       if (oldlenp != NULL) {
+               *oldlenp = oldlen;
+               if (oldp != NULL && oldlen > savelen) {
+                       errno = ENOMEM;
+                       return (-1);
+               }
+       }
+
+       return (0);
+}
+
+static int
+user_sysctl(name, namelen, oldp, oldlenp, newp, newlen)
+       const int *name;
+       unsigned int namelen;
+       void *oldp;
+       const void *newp;
+       size_t *oldlenp, newlen;
+{
+#define _INT(s, n, v, d) {                                     \
+       .sysctl_flags = CTLFLAG_IMMEDIATE|CTLFLAG_PERMANENT|    \
+                       CTLTYPE_INT|SYSCTL_VERSION,             \
+       sysc_init_field(_sysctl_size, sizeof(int)),             \
+       .sysctl_name = (s),                                     \
+       .sysctl_num = (n),                                      \
+       .sysctl_un = { .scu_idata = (v), },                     \
+       sysc_init_field(_sysctl_desc, (d)),                     \
+       }
+
+       /*
+        * the nodes under the "user" node
+        */
+       static const struct sysctlnode sysctl_usermib[] = {
+#if defined(lint)
+               /*
+                * lint doesn't like my initializers
+                */
+               0
+#else /* !lint */
+               {
+                       .sysctl_flags = SYSCTL_VERSION|CTLFLAG_PERMANENT|
+                               CTLTYPE_STRING,
+                       sysc_init_field(_sysctl_size, sizeof(_PATH_STDPATH)),
+                       .sysctl_name = "cs_path",
+                       .sysctl_num = USER_CS_PATH,
+                       /*
+                        * XXX these nasty initializers (and the one in
+                        * the _INT() macro) can go away once all ports
+                        * are using gcc3, and become
+                        *
+                        *      .sysctl_data = _PATH_STDPATH,
+                        *      .sysctl_desc = NULL,
+                        */
+                       .sysctl_un = { .scu_data = { 
+                               sysc_init_field(_sud_data,
+                               __UNCONST(_PATH_STDPATH)),
+                               }, },
+                       sysc_init_field(_sysctl_desc,
+                               "A value for the PATH environment variable "
+                               "that finds all the standard utilities"),
+               },
+               _INT("bc_base_max", USER_BC_BASE_MAX, BC_BASE_MAX,
+                    "The maximum ibase/obase values in the bc(1) utility"),
+               _INT("bc_dim_max", USER_BC_DIM_MAX, BC_DIM_MAX,
+                    "The maximum array size in the bc(1) utility"),
+               _INT("bc_scale_max", USER_BC_SCALE_MAX, BC_SCALE_MAX,
+                    "The maximum scale value in the bc(1) utility"),
+               _INT("bc_string_max", USER_BC_STRING_MAX, BC_STRING_MAX,
+                    "The maximum string length in the bc(1) utility"),
+               _INT("coll_weights_max", USER_COLL_WEIGHTS_MAX,
+                    COLL_WEIGHTS_MAX, "The maximum number of weights that can "
+                    "be assigned to any entry of the LC_COLLATE order keyword "
+                    "in the locale definition file"),
+               _INT("expr_nest_max", USER_EXPR_NEST_MAX, EXPR_NEST_MAX,
+                    "The maximum number of expressions that can be nested "
+                    "within parenthesis by the expr(1) utility"),
+               _INT("line_max", USER_LINE_MAX, LINE_MAX, "The maximum length "
+                    "in bytes of a text-processing utility's input line"),
+               _INT("re_dup_max", USER_RE_DUP_MAX, RE_DUP_MAX, "The maximum "
+                    "number of repeated occurrences of a regular expression "
+                    "permitted when using interval notation"),
+               _INT("posix2_version", USER_POSIX2_VERSION, _POSIX2_VERSION,
+                    "The version of POSIX 1003.2 with which the system "
+                    "attempts to comply"),
+#ifdef _POSIX2_C_BIND
+               _INT("posix2_c_bind", USER_POSIX2_C_BIND, 1,
+                    "Whether the system's C-language development facilities "
+                    "support the C-Language Bindings Option"),
+#else
+               _INT("posix2_c_bind", USER_POSIX2_C_BIND, 0,
+                    "Whether the system's C-language development facilities "
+                    "support the C-Language Bindings Option"),
+#endif
+#ifdef POSIX2_C_DEV
+               _INT("posix2_c_dev", USER_POSIX2_C_DEV, 1,
+                    "Whether the system supports the C-Language Development "
+                    "Utilities Option"),
+#else
+               _INT("posix2_c_dev", USER_POSIX2_C_DEV, 0,
+                    "Whether the system supports the C-Language Development "
+                    "Utilities Option"),
+#endif
+#ifdef POSIX2_CHAR_TERM
+               _INT("posix2_char_term", USER_POSIX2_CHAR_TERM, 1,
+                    "Whether the system supports at least one terminal type "
+                    "capable of all operations described in POSIX 1003.2"),
+#else
+               _INT("posix2_char_term", USER_POSIX2_CHAR_TERM, 0,
+                    "Whether the system supports at least one terminal type "
+                    "capable of all operations described in POSIX 1003.2"),
+#endif
+#ifdef POSIX2_FORT_DEV
+               _INT("posix2_fort_dev", USER_POSIX2_FORT_DEV, 1,
+                    "Whether the system supports the FORTRAN Development "
+                    "Utilities Option"),
+#else
+               _INT("posix2_fort_dev", USER_POSIX2_FORT_DEV, 0,
+                    "Whether the system supports the FORTRAN Development "
+                    "Utilities Option"),
+#endif
+#ifdef POSIX2_FORT_RUN
+               _INT("posix2_fort_run", USER_POSIX2_FORT_RUN, 1,
+                    "Whether the system supports the FORTRAN Runtime "
+                    "Utilities Option"),
+#else
+               _INT("posix2_fort_run", USER_POSIX2_FORT_RUN, 0,
+                    "Whether the system supports the FORTRAN Runtime "
+                    "Utilities Option"),
+#endif
+#ifdef POSIX2_LOCALEDEF
+               _INT("posix2_localedef", USER_POSIX2_LOCALEDEF, 1,
+                    "Whether the system supports the creation of locales"),
+#else
+               _INT("posix2_localedef", USER_POSIX2_LOCALEDEF, 0,
+                    "Whether the system supports the creation of locales"),
+#endif
+#ifdef POSIX2_SW_DEV
+               _INT("posix2_sw_dev", USER_POSIX2_SW_DEV, 1,
+                    "Whether the system supports the Software Development "
+                    "Utilities Option"),
+#else
+               _INT("posix2_sw_dev", USER_POSIX2_SW_DEV, 0,
+                    "Whether the system supports the Software Development "
+                    "Utilities Option"),
+#endif
+#ifdef POSIX2_UPE
+               _INT("posix2_upe", USER_POSIX2_UPE, 1,
+                    "Whether the system supports the User Portability "
+                    "Utilities Option"),
+#else
+               _INT("posix2_upe", USER_POSIX2_UPE, 0,
+                    "Whether the system supports the User Portability "
+                    "Utilities Option"),
+#endif
+               _INT("stream_max", USER_STREAM_MAX, FOPEN_MAX,
+                    "The minimum maximum number of streams that a process "
+                    "may have open at any one time"),
+               _INT("tzname_max", USER_TZNAME_MAX, NAME_MAX,
+                    "The minimum maximum number of types supported for the "
+                    "name of a timezone"),
+               _INT("atexit_max", USER_ATEXIT_MAX, -1,
+                    "The maximum number of functions that may be registered "
+                    "with atexit(3)"),
+#endif /* !lint */
+       };
+#undef _INT
+
+       static const int clen = sizeof(sysctl_usermib) /
+               sizeof(sysctl_usermib[0]);
+
+       const struct sysctlnode *node;
+       int ni;
+       size_t l, sz;
+
+       /*
+        * none of these nodes are writable and they're all terminal (for now)
+        */
+       if (namelen != 1)
+               return (EINVAL);
+
+       l = *oldlenp;
+       if (name[0] == CTL_QUERY) {
+               uint v;
+               node = newp;
+               if (node == NULL)
+                       return (EINVAL);
+               else if (SYSCTL_VERS(node->sysctl_flags) == SYSCTL_VERS_1 &&
+                        newlen == sizeof(struct sysctlnode))
+                       v = SYSCTL_VERS_1;
+               else
+                       return (EINVAL);
+
+               sz = 0;
+               for (ni = 0; ni < clen; ni++)
+                       sz += __cvt_node_out(v, &sysctl_usermib[ni], &oldp, &l);
+               *oldlenp = sz;
+               return (0);
+       }
+
+       if (name[0] == CTL_DESCRIBE) {
+               /*
+                * XXX make sure this is larger than the largest
+                * "user" description
+                */
+               char buf[192];
+               struct sysctldesc *d1 = (void *)&buf[0], *d2 = oldp;
+               size_t d;
+
+               node = newp;
+               if (node != NULL &&
+                   (SYSCTL_VERS(node->sysctl_flags) < SYSCTL_VERS_1 ||
+                    newlen != sizeof(struct sysctlnode)))
+                       return (EINVAL);
+
+               sz = 0;
+               for (ni = 0; ni < clen; ni++) {
+                       memset(&buf[0], 0, sizeof(buf));
+                       if (node != NULL &&
+                           node->sysctl_num != sysctl_usermib[ni].sysctl_num)
+                               continue;
+                       d1->descr_num = sysctl_usermib[ni].sysctl_num;
+                       d1->descr_ver = sysctl_usermib[ni].sysctl_ver;
+                       if (sysctl_usermib[ni].sysctl_desc == NULL)
+                               d1->descr_len = 1;
+                       else {
+                               (void)strlcpy(d1->descr_str,
+                                       sysctl_usermib[ni].sysctl_desc,
+                                       sizeof(buf) - sizeof(*d1));
+                               d1->descr_len = strlen(d1->descr_str) + 1;
+                       }
+                       d = (size_t)__sysc_desc_adv(NULL, d1->descr_len);
+                       if (d2 != NULL)
+                               memcpy(d2, d1, d);
+                       sz += d;
+                       if (node != NULL)
+                               break;
+               }
+               *oldlenp = sz;
+               if (sz == 0 && node != NULL)
+                       return (ENOENT);
+               return (0);
+
+       }
+
+       /*
+        * none of these nodes are writable
+        */
+       if (newp != NULL || newlen != 0)
+               return (EPERM);
+       
+       node = &sysctl_usermib[0];
+       for (ni = 0; ni < clen; ni++)
+               if (name[0] == node[ni].sysctl_num)
+                       break;
+       if (ni == clen)
+               return (EOPNOTSUPP);
+
+       node = &node[ni];
+       if (node->sysctl_flags & CTLFLAG_IMMEDIATE) {
+               switch (SYSCTL_TYPE(node->sysctl_flags)) {
+               case CTLTYPE_INT:
+                       newp = &node->sysctl_idata;
+                       break;
+               case CTLTYPE_QUAD:
+                       newp = &node->sysctl_qdata;
+                       break;
+               default:
+                       return (EINVAL);
+               }
+       }
+       else
+               newp = node->sysctl_data;
+
+       l = MIN(l, node->sysctl_size);
+       if (oldp != NULL)
+               memcpy(oldp, newp, l);
+       *oldlenp = node->sysctl_size;
+
+       return (0);
+}
+
+static size_t
+__cvt_node_out(uint v, const struct sysctlnode *n, void **o, size_t *l)
+{
+       const void *src = n;
+       size_t sz;
+
+       switch (v) {
+#if (SYSCTL_VERSION != SYSCTL_VERS_1)
+#error __cvt_node_out: no support for SYSCTL_VERSION
+#endif /* (SYSCTL_VERSION != SYSCTL_VERS_1) */
+
+       case SYSCTL_VERSION:
+               sz = sizeof(struct sysctlnode);
+               break;
+
+       default:
+               sz = 0;
+               break;
+       }
+
+       if (sz > 0 && *o != NULL && *l >= sz) {
+               memcpy(*o, src, sz);
+               *o = sz + (caddr_t)*o;
+               *l -= sz;
+       }
+
+       return(sz);
+}
diff --git a/lib/nbsd_libc/gen/sysctlbyname.c b/lib/nbsd_libc/gen/sysctlbyname.c
new file mode 100644 (file)
index 0000000..0a6be7f
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: sysctlbyname.c,v 1.7 2010/12/13 23:10:13 pooka Exp $ */
+
+/*-
+ * Copyright (c) 2003,2004 The NetBSD Foundation, Inc.
+ *     All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Andrew Brown.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sysctlbyname.c,v 1.7 2010/12/13 23:10:13 pooka Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifndef RUMP_ACTION
+#include "namespace.h"
+#endif
+#include <sys/param.h>
+#include <sys/sysctl.h>
+
+#ifdef RUMP_ACTION
+#include <rump/rump_syscalls.h>
+#define sysctl(a,b,c,d,e,f) rump_sys___sysctl(a,b,c,d,e,f)
+#else
+#ifdef __weak_alias
+__weak_alias(sysctlbyname,_sysctlbyname)
+#endif
+#endif
+
+/*
+ * trivial sysctlbyname() function for the "lazy".
+ */
+int
+sysctlbyname(const char *gname, void *oldp, size_t *oldlenp,
+            const void *newp, size_t newlen)
+{
+       int name[CTL_MAXNAME], rc;
+       u_int namelen;
+
+       rc = sysctlgetmibinfo(gname, &name[0], &namelen, NULL, NULL, NULL,
+                             SYSCTL_VERSION);
+       if (rc == 0)
+               rc = sysctl(&name[0], namelen, oldp, oldlenp, newp, newlen);
+       return (rc);
+}
diff --git a/lib/nbsd_libc/gen/sysctlgetmibinfo.c b/lib/nbsd_libc/gen/sysctlgetmibinfo.c
new file mode 100644 (file)
index 0000000..10d5c07
--- /dev/null
@@ -0,0 +1,608 @@
+/*     $NetBSD: sysctlgetmibinfo.c,v 1.9 2010/12/13 23:10:13 pooka Exp $ */
+
+/*-
+ * Copyright (c) 2003,2004 The NetBSD Foundation, Inc.
+ *     All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Andrew Brown.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sysctlgetmibinfo.c,v 1.9 2010/12/13 23:10:13 pooka Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifndef RUMP_ACTION
+#include "namespace.h"
+#ifdef _REENTRANT
+#include "reentrant.h"
+#endif /* _REENTRANT */
+#endif /* RUMP_ACTION */
+#include <sys/param.h>
+#include <sys/sysctl.h>
+
+#include <errno.h>
+#include <inttypes.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef RUMP_ACTION
+#include <rump/rump_syscalls.h>
+#define sysctl(a,b,c,d,e,f) rump_sys___sysctl(a,b,c,d,e,f)
+#else
+#ifdef __weak_alias
+__weak_alias(__learn_tree,___learn_tree)
+__weak_alias(sysctlgetmibinfo,_sysctlgetmibinfo)
+#endif
+#endif
+
+/*
+ * the place where we attach stuff we learn on the fly, not
+ * necessarily used.
+ */
+static struct sysctlnode sysctl_mibroot = {
+#if defined(lint)
+       /*
+        * lint doesn't like my initializers
+        */
+       0
+#else /* !lint */
+       .sysctl_flags = SYSCTL_VERSION|CTLFLAG_ROOT|CTLTYPE_NODE,
+       sysc_init_field(_sysctl_size, sizeof(struct sysctlnode)),
+       .sysctl_name = "(root)",
+#endif /* !lint */
+};
+
+/*
+ * routines to handle learning and cleanup
+ */
+static int compar(const void *, const void *);
+static void free_children(struct sysctlnode *);
+static void relearnhead(void);
+
+/*
+ * specifically not static since sysctl(8) "borrows" it.
+ */
+int __learn_tree(int *, u_int, struct sysctlnode *);
+
+/*
+ * for ordering nodes -- a query may or may not be given them in
+ * numeric order
+ */
+static int
+compar(const void *a, const void *b)
+{
+
+       return (((const struct sysctlnode *)a)->sysctl_num -
+               ((const struct sysctlnode *)b)->sysctl_num);
+}
+
+/*
+ * recursively nukes a branch or an entire tree from the given node
+ */
+static void
+free_children(struct sysctlnode *rnode) 
+{
+       struct sysctlnode *node;
+
+       if (rnode == NULL ||
+           SYSCTL_TYPE(rnode->sysctl_flags) != CTLTYPE_NODE ||
+           rnode->sysctl_child == NULL)
+               return;
+
+       for (node = rnode->sysctl_child;
+            node < &rnode->sysctl_child[rnode->sysctl_clen];
+            node++) {
+               free_children(node);
+       }
+       free(rnode->sysctl_child);
+       rnode->sysctl_child = NULL;
+}
+
+/*
+ * verifies that the head of the tree in the kernel is the same as the
+ * head of the tree we already got, integrating new stuff and removing
+ * old stuff, if it's not.
+ */
+static void
+relearnhead(void)
+{
+       struct sysctlnode *h, *i, *o, qnode;
+       size_t si, so;
+       int rc, name, nlen, olen, ni, oi;
+       uint32_t t;
+
+       /*
+        * if there's nothing there, there's no need to expend any
+        * effort
+        */
+       if (sysctl_mibroot.sysctl_child == NULL)
+               return;
+
+       /*
+        * attempt to pull out the head of the tree, starting with the
+        * size we have now, and looping if we need more (or less)
+        * space
+        */
+       si = 0;
+       so = sysctl_mibroot.sysctl_clen * sizeof(struct sysctlnode);
+       name = CTL_QUERY;
+       memset(&qnode, 0, sizeof(qnode));
+       qnode.sysctl_flags = SYSCTL_VERSION;
+       do {
+               si = so;
+               h = malloc(si);
+               rc = sysctl(&name, 1, h, &so, &qnode, sizeof(qnode));
+               if (rc == -1 && errno != ENOMEM)
+                       return;
+               if (si < so)
+                       free(h);
+       } while (si < so);
+
+       /*
+        * order the new copy of the head
+        */
+       nlen = so / sizeof(struct sysctlnode);
+       qsort(h, (size_t)nlen, sizeof(struct sysctlnode), compar);
+
+       /*
+        * verify that everything is the same.  if it is, we don't
+        * need to do any more work here.
+        */
+       olen = sysctl_mibroot.sysctl_clen;
+       rc = (nlen == olen) ? 0 : 1;
+       o = sysctl_mibroot.sysctl_child;
+       for (ni = 0; rc == 0 && ni < nlen; ni++) {
+               if (h[ni].sysctl_num != o[ni].sysctl_num ||
+                   h[ni].sysctl_ver != o[ni].sysctl_ver)
+                       rc = 1;
+       }
+       if (rc == 0) {
+               free(h);
+               return;
+       }
+
+       /*
+        * something changed.  h will become the new head, and we need
+        * pull over any subtrees we already have if they're the same
+        * version.
+        */
+       i = h;
+       ni = oi = 0;
+       while (ni < nlen && oi < olen) {
+               /*
+                * something was inserted or deleted
+                */
+               if (SYSCTL_TYPE(i[ni].sysctl_flags) == CTLTYPE_NODE)
+                       i[ni].sysctl_child = NULL;
+               if (i[ni].sysctl_num != o[oi].sysctl_num) {
+                       if (i[ni].sysctl_num < o[oi].sysctl_num) {
+                               ni++;
+                       }
+                       else {
+                               free_children(&o[oi]);
+                               oi++;
+                       }
+                       continue;
+               }
+
+               /*
+                * same number, but different version, so throw away
+                * any accumulated children
+                */
+               if (i[ni].sysctl_ver != o[oi].sysctl_ver)
+                       free_children(&o[oi]);
+
+               /*
+                * this node is the same, but we only need to
+                * move subtrees.
+                */
+               else if (SYSCTL_TYPE(i[ni].sysctl_flags) == CTLTYPE_NODE) {     
+                       /*
+                        * move subtree to new parent
+                        */
+                       i[ni].sysctl_clen = o[oi].sysctl_clen;
+                       i[ni].sysctl_csize = o[oi].sysctl_csize;
+                       i[ni].sysctl_child = o[oi].sysctl_child;
+                       /*
+                        * reparent inherited subtree
+                        */
+                       for (t = 0;
+                            i[ni].sysctl_child != NULL &&
+                                    t < i[ni].sysctl_clen;
+                            t++)
+                               i[ni].sysctl_child[t].sysctl_parent = &i[ni];
+               }
+               ni++;
+               oi++;
+       }
+
+       /*
+        * left over new nodes need to have empty subtrees cleared
+        */
+       while (ni < nlen) {
+               if (SYSCTL_TYPE(i[ni].sysctl_flags) == CTLTYPE_NODE)
+                       i[ni].sysctl_child = NULL;
+               ni++;
+       }
+
+       /*
+        * left over old nodes need to be cleaned out
+        */
+       while (oi < olen) {
+               free_children(&o[oi]);
+               oi++;
+       }
+
+       /*
+        * pop new head in
+        */
+       sysctl_mibroot.sysctl_clen = nlen;
+       sysctl_mibroot.sysctl_csize = nlen;
+       sysctl_mibroot.sysctl_child = h;
+       free(o);
+}
+
+/*
+ * sucks in the children at a given level and attaches it to the tree.
+ */
+int
+__learn_tree(int *name, u_int namelen, struct sysctlnode *pnode)
+{
+       struct sysctlnode qnode;
+       uint32_t rc;
+       size_t sz;
+
+       if (pnode == NULL)
+               pnode = &sysctl_mibroot;
+       if (SYSCTL_TYPE(pnode->sysctl_flags) != CTLTYPE_NODE) {
+               errno = EINVAL;
+               return (-1);
+       }
+       if (pnode->sysctl_child != NULL)
+               return (0);
+
+       if (pnode->sysctl_clen == 0)
+               sz = SYSCTL_DEFSIZE * sizeof(struct sysctlnode);
+       else
+               sz = pnode->sysctl_clen * sizeof(struct sysctlnode);
+       pnode->sysctl_child = malloc(sz);
+       if (pnode->sysctl_child == NULL)
+               return (-1);
+
+       name[namelen] = CTL_QUERY;
+       pnode->sysctl_clen = 0;
+       pnode->sysctl_csize = 0;
+       memset(&qnode, 0, sizeof(qnode));
+       qnode.sysctl_flags = SYSCTL_VERSION;
+       rc = sysctl(name, namelen + 1, pnode->sysctl_child, &sz,
+                   &qnode, sizeof(qnode));
+       if (sz == 0) {
+               free(pnode->sysctl_child);
+               pnode->sysctl_child = NULL;
+               return (rc);
+       }
+       if (rc) {
+               free(pnode->sysctl_child);
+               pnode->sysctl_child = NULL;
+               if ((sz % sizeof(struct sysctlnode)) != 0)
+                       errno = EINVAL;
+               if (errno != ENOMEM)
+                       return (rc);
+       }
+
+       if (pnode->sysctl_child == NULL) {
+               pnode->sysctl_child = malloc(sz);
+               if (pnode->sysctl_child == NULL)
+                       return (-1);
+
+               rc = sysctl(name, namelen + 1, pnode->sysctl_child, &sz,
+                           &qnode, sizeof(qnode));
+               if (rc) {
+                       free(pnode->sysctl_child);
+                       pnode->sysctl_child = NULL;
+                       return (rc);
+               }
+       }
+
+       /*
+        * how many did we get?
+        */
+       pnode->sysctl_clen = sz / sizeof(struct sysctlnode);
+       pnode->sysctl_csize = sz / sizeof(struct sysctlnode);
+       if (pnode->sysctl_clen * sizeof(struct sysctlnode) != sz) {
+               free(pnode->sysctl_child);
+               pnode->sysctl_child = NULL;
+               errno = EINVAL;
+               return (-1);
+       }
+
+       /*
+        * you know, the kernel doesn't really keep them in any
+        * particular order...just like entries in a directory
+        */
+       qsort(pnode->sysctl_child, pnode->sysctl_clen, 
+           sizeof(struct sysctlnode), compar);
+
+       /*
+        * rearrange parent<->child linkage
+        */
+       for (rc = 0; rc < pnode->sysctl_clen; rc++) {
+               pnode->sysctl_child[rc].sysctl_parent = pnode;
+               if (SYSCTL_TYPE(pnode->sysctl_child[rc].sysctl_flags) ==
+                   CTLTYPE_NODE) {
+                       /*
+                        * these nodes may have children, but we
+                        * haven't discovered that yet.
+                        */
+                       pnode->sysctl_child[rc].sysctl_child = NULL;
+               }
+               pnode->sysctl_child[rc].sysctl_desc = NULL;
+       }
+
+       return (0);
+}
+
+/*
+ * that's "given name" as a string, the integer form of the name fit
+ * to be passed to sysctl(), "canonicalized name" (optional), and a
+ * pointer to the length of the integer form.  oh, and then a pointer
+ * to the node, in case you (the caller) care.  you can leave them all
+ * NULL except for gname, though that might be rather pointless,
+ * unless all you wanna do is verify that a given name is acceptable.
+ *
+ * returns either 0 (everything was fine) or -1 and sets errno
+ * accordingly.  if errno is set to EAGAIN, we detected a change to
+ * the mib while parsing, and you should try again.  in the case of an
+ * invalid node name, cname will be set to contain the offending name.
+ */
+#ifdef _REENTRANT
+static mutex_t sysctl_mutex = MUTEX_INITIALIZER;
+static int sysctlgetmibinfo_unlocked(const char *, int *, u_int *, char *,
+                                    size_t *, struct sysctlnode **, int);
+#endif /* __REENTRANT */
+
+int
+sysctlgetmibinfo(const char *gname, int *iname, u_int *namelenp,
+                char *cname, size_t *csz, struct sysctlnode **rnode, int v)
+#ifdef _REENTRANT
+{
+       int rc;
+
+       mutex_lock(&sysctl_mutex);
+       rc = sysctlgetmibinfo_unlocked(gname, iname, namelenp, cname, csz,
+                                      rnode, v);
+       mutex_unlock(&sysctl_mutex);
+
+       return (rc);
+}
+
+static int
+sysctlgetmibinfo_unlocked(const char *gname, int *iname, u_int *namelenp,
+                         char *cname, size_t *csz, struct sysctlnode **rnode,
+                         int v)
+#endif /* _REENTRANT */
+{
+       struct sysctlnode *pnode, *node;
+       int name[CTL_MAXNAME], n, haven;
+       u_int ni, nl;
+       intmax_t q;
+       char sep[2], token[SYSCTL_NAMELEN],
+               pname[SYSCTL_NAMELEN * CTL_MAXNAME + CTL_MAXNAME];
+       const char *piece, *dot;
+       char *t;
+       size_t l;
+
+       if (rnode != NULL) {
+               if (*rnode == NULL) {
+                       /* XXX later deal with dealing back a sub version */
+                       if (v != SYSCTL_VERSION)
+                               return (EINVAL);
+
+                       pnode = &sysctl_mibroot;
+               }
+               else {
+                       /* this is just someone being silly */
+                       if (SYSCTL_VERS((*rnode)->sysctl_flags) != (uint32_t)v)
+                               return (EINVAL);
+
+                       /* XXX later deal with other people's trees */
+                       if (SYSCTL_VERS((*rnode)->sysctl_flags) !=
+                           SYSCTL_VERSION)
+                               return (EINVAL);
+
+                       pnode = *rnode;
+               }
+       }
+       else
+               pnode = &sysctl_mibroot;
+
+       if (pnode == &sysctl_mibroot)
+               relearnhead();
+
+       nl = ni = 0;
+       token[0] = '\0';
+       pname[0] = '\0';
+       node = NULL;
+
+       /*
+        * default to using '.' as the separator, but allow '/' as
+        * well, and then allow a leading separator
+        */
+       if ((dot = strpbrk(gname, "./")) == NULL)
+               sep[0] = '.';
+       else
+               sep[0] = dot[0];
+       sep[1] = '\0';
+       if (gname[0] == sep[0]) {
+               strlcat(pname, sep, sizeof(pname));
+               gname++;
+       }
+
+#define COPY_OUT_DATA(t, c, cs, nlp, l) do {                   \
+               if ((c) != NULL && (cs) != NULL)                \
+                       *(cs) = strlcpy((c), (t), *(cs));       \
+               else if ((cs) != NULL)                          \
+                       *(cs) = strlen(t) + 1;                  \
+               if ((nlp) != NULL)                              \
+                       *(nlp) = (l);                           \
+       } while (/*CONSTCOND*/0)
+
+       piece = gname;
+       while (piece != NULL && *piece != '\0') {
+               /*
+                * what was i looking for?
+                */
+               dot = strchr(piece, sep[0]);
+               if (dot == NULL) {
+                       l = strlcpy(token, piece, sizeof(token));
+                       if (l > sizeof(token)) {
+                               COPY_OUT_DATA(piece, cname, csz, namelenp, nl);
+                               errno = ENAMETOOLONG;
+                               return (-1);
+                       }
+               }
+               else if (dot - piece > (intptr_t)(sizeof(token) - 1)) {
+                       COPY_OUT_DATA(token, cname, csz, namelenp, nl);
+                       errno = ENAMETOOLONG;
+                       return (-1);
+               }
+               else {
+                       strncpy(token, piece, (size_t)(dot - piece));
+                       token[dot - piece] = '\0';
+               }
+
+               /*
+                * i wonder if this "token" is an integer?
+                */
+               errno = 0;
+               q = strtoimax(token, &t, 0);
+               n = (int)q;
+               if (errno != 0 || *t != '\0')
+                       haven = 0;
+               else if (q < INT_MIN || q > UINT_MAX)
+                       haven = 0;
+               else
+                       haven = 1;
+
+               /*
+                * make sure i have something to look at
+                */
+               if (SYSCTL_TYPE(pnode->sysctl_flags) != CTLTYPE_NODE) {
+                       if (haven && nl > 0) {
+                               strlcat(pname, sep, sizeof(pname));
+                               goto just_numbers;
+                       }
+                       COPY_OUT_DATA(token, cname, csz, namelenp, nl);
+                       errno = ENOTDIR;
+                       return (-1);
+               }
+               if (pnode->sysctl_child == NULL) {
+                       if (__learn_tree(name, nl, pnode) == -1) {
+                               COPY_OUT_DATA(token, cname, csz, namelenp, nl);
+                               return (-1);
+                       }
+               }
+               node = pnode->sysctl_child;
+               if (node == NULL) {
+                       COPY_OUT_DATA(token, cname, csz, namelenp, nl);
+                       errno = ENOENT;
+                       return (-1);
+               }
+
+               /*
+                * now...is it there?
+                */
+               for (ni = 0; ni < pnode->sysctl_clen; ni++)
+                       if ((haven && ((n == node[ni].sysctl_num) ||
+                           (node[ni].sysctl_flags & CTLFLAG_ANYNUMBER))) ||
+                           strcmp(token, node[ni].sysctl_name) == 0)
+                               break;
+               if (ni >= pnode->sysctl_clen) {
+                       COPY_OUT_DATA(token, cname, csz, namelenp, nl);
+                       errno = ENOENT;
+                       return (-1);
+               }
+
+               /*
+                * ah...it is.
+                */
+               pnode = &node[ni];
+               if (nl > 0)
+                       strlcat(pname, sep, sizeof(pname));
+               if (haven && n != pnode->sysctl_num) {
+ just_numbers:
+                       strlcat(pname, token, sizeof(pname));
+                       name[nl] = n;
+               }
+               else {
+                       strlcat(pname, pnode->sysctl_name, sizeof(pname));
+                       name[nl] = pnode->sysctl_num;
+               }
+               piece = (dot != NULL) ? dot + 1 : NULL;
+               nl++;
+               if (nl == CTL_MAXNAME) {
+                       COPY_OUT_DATA(token, cname, csz, namelenp, nl);
+                       errno = ERANGE;
+                       return (-1);
+               }
+       }
+
+       if (nl == 0) {
+               if (namelenp != NULL)
+                       *namelenp = 0;
+               errno = EINVAL;
+               return (-1);
+       }
+
+       COPY_OUT_DATA(pname, cname, csz, namelenp, nl);
+       if (iname != NULL && namelenp != NULL)
+               memcpy(iname, &name[0], MIN(nl, *namelenp) * sizeof(int));
+       if (namelenp != NULL)
+               *namelenp = nl;
+       if (rnode != NULL) {
+               if (*rnode != NULL)
+                       /*
+                        * they gave us a private tree to work in, so
+                        * we give back a pointer into that private
+                        * tree
+                        */
+                       *rnode = pnode;
+               else {
+                       /*
+                        * they gave us a place to put the node data,
+                        * so give them a copy
+                        */
+                       *rnode = malloc(sizeof(struct sysctlnode));
+                       if (*rnode != NULL) {
+                               **rnode = *pnode;
+                               (*rnode)->sysctl_child = NULL;
+                               (*rnode)->sysctl_parent = NULL;
+                       }
+               }
+       }
+
+       return (0);
+}
diff --git a/lib/nbsd_libc/gen/sysctlnametomib.c b/lib/nbsd_libc/gen/sysctlnametomib.c
new file mode 100644 (file)
index 0000000..92376e1
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: sysctlnametomib.c,v 1.6 2010/12/13 23:10:13 pooka Exp $ */
+
+/*-
+ * Copyright (c) 2003,2004 The NetBSD Foundation, Inc.
+ *     All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Andrew Brown.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sysctlnametomib.c,v 1.6 2010/12/13 23:10:13 pooka Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifndef RUMP_ACTION
+#include "namespace.h"
+#endif
+#include <sys/param.h>
+#include <sys/sysctl.h>
+
+#ifdef RUMP_ACTION
+#include <rump/rump_syscalls.h>
+#define sysctl(a,b,c,d,e,f) rump_sys___sysctl(a,b,c,d,e,f)
+#else
+#ifdef __weak_alias
+__weak_alias(sysctlnametomib,_sysctlnametomib)
+#endif
+#endif /* RUMP_ACTION */
+
+/*
+ * freebsd compatible sysctlnametomib() function, implemented as an
+ * extremely thin wrapper around sysctlgetmibinfo().  i think the use
+ * of size_t as the third argument is erroneous, but what can we do
+ * about that?
+ */
+int
+sysctlnametomib(const char *gname, int *iname, size_t *namelenp)
+{
+       u_int unamelen;
+       int rc;
+
+       unamelen = *namelenp;
+       rc = sysctlgetmibinfo(gname, iname, &unamelen, NULL, NULL, NULL,
+                             SYSCTL_VERSION);
+       *namelenp = unamelen;
+
+       return (rc);
+}
diff --git a/lib/nbsd_libc/gen/syslog.3 b/lib/nbsd_libc/gen/syslog.3
new file mode 100644 (file)
index 0000000..278b061
--- /dev/null
@@ -0,0 +1,517 @@
+.\"    $NetBSD: syslog.3,v 1.28 2010/05/13 18:04:58 jruoho Exp $
+.\"    $OpenBSD: syslog.3,v 1.25 2005/07/22 03:16:58 jaredy Exp $
+.\"
+.\" Copyright (c) 1985, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)syslog.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 3, 2010
+.Dt SYSLOG 3
+.Os
+.Sh NAME
+.Nm syslog ,
+.Nm syslog_r ,
+.Nm vsyslog ,
+.Nm vsyslog_r ,
+.Nm syslogp ,
+.Nm syslogp_r ,
+.Nm vsyslogp ,
+.Nm vsyslogp_r ,
+.Nm openlog ,
+.Nm openlog_r ,
+.Nm closelog ,
+.Nm closelog_r ,
+.Nm setlogmask ,
+.Nm setlogmask_r
+.Nd control system log
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In syslog.h
+.Ft void
+.Fn syslog "int priority" "const char *message" "..."
+.Ft void
+.Fn syslog_r "int priority" "struct syslog_data *data" "const char *message" "..."
+.Ft void
+.Fn syslogp "int priority" "const char *msgid" "const char *sdfmt" "const char *message" "..."
+.Ft void
+.Fn syslogp_r "int priority" "struct syslog_data *data" "const char *msgid" "const char *sdfmt" "const char *message" "..."
+.\" .Ft void
+.\" .Fn syslog_ss "int priority" "struct syslog_data *data" "const char *message" "..."
+.Ft void
+.Fn openlog "const char *ident" "int logopt" "int facility"
+.Ft void
+.Fn openlog_r "const char *ident" "int logopt" "int facility" "struct syslog_data *data"
+.Ft void
+.Fn closelog void
+.Ft void
+.Fn closelog_r "struct syslog_data *data"
+.Ft int
+.Fn setlogmask "int maskpri"
+.Ft int
+.Fn setlogmask_r "int maskpri" "struct syslog_data *data"
+.In stdarg.h
+.Ft void
+.Fn vsyslog "int priority" "const char *message" "va_list args"
+.Ft void
+.Fn vsyslog_r "int priority" "struct syslog_data *data" "const char *message" "va_list args"
+.Ft void
+.Fn vsyslogp "int priority" "const char *msgid" "const char *sdfmt" "const char *message" "va_list args"
+.Ft void
+.Fn vsyslogp_r "int priority" "struct syslog_data *data" "const char *msgid" "const char *sdfmt" "const char *message" "va_list args"
+.\" .Ft void
+.\" .Fn vsyslog_ss "int priority" "struct syslog_data *data" "const char *message" "va_list args"
+.Sh DESCRIPTION
+The
+.Fn syslog
+function
+writes
+.Fa message
+to the system message logger.
+The message is then written to the system console, log files,
+logged-in users, or forwarded to other machines as appropriate (see
+.Xr syslogd 8 ) .
+.Pp
+The message is identical to a
+.Xr printf 3
+format string, except that
+.Ql %m
+is replaced by the current error
+message.
+(As denoted by the global variable
+.Va errno ;
+see
+.Xr strerror 3 . )
+A trailing newline is added if none is present.
+.\" shouldn't the newline statement be removed?
+.\" when logging through a socket a newline is
+.\" not added nor is it required. -- ms
+.Pp
+The
+.Fn syslog_r
+function is a multithread-safe version of the
+.Fn syslog
+function.
+It takes a pointer to a
+.Fa syslog_data
+structure which is used to store
+information.
+This parameter must be initialized before
+.Fn syslog_r
+is called.
+The
+.Dv SYSLOG_DATA_INIT
+constant is used for this purpose.
+The
+.Fa syslog_data
+structure and the
+.Dv SYSLOG_DATA_INIT
+constant are defined as:
+.Bd -literal -offset indent
+struct syslog_data {
+        int             log_file;
+        int             connected;
+        int             opened;
+        int             log_stat;
+        const char     *log_tag;
+        int             log_fac;
+        int             log_mask;
+};
+
+#define SYSLOG_DATA_INIT { \e
+    .log_file = -1, \e
+    .log_fac = LOG_USER, \e
+    .log_mask = 0xff, \e
+}
+.Ed
+.Pp
+The structure is composed of the following elements:
+.Bl -tag -width connected -offset indent
+.It Va log_file
+contains the file descriptor of the file where the message is logged
+.It Va connected
+indicates if connect has been done
+.It Va opened
+indicates if
+.Fn openlog_r
+has been called
+.It Va log_stat
+status bits, set by
+.Fn openlog_r
+.It Va log_tag
+string to tag the entry with
+.It Va log_fac
+facility code
+.It Va log_mask
+mask of priorities to be logged
+.El
+.\" .Pp
+.\" The
+.\" .Fn syslog_ss
+.\" is the async-signal-safe version of
+.\" .Fn syslog_r
+.\" and is also multithread-safe.
+.\" It has the following limitations:
+.\" .Bl -enum -offset indent
+.\" .It
+.\" The format string cannot contain multi-byte character sequences.
+.\" .It
+.\" Floating point formats are not supported and print
+.\" .Dq UNK .
+.\" .It
+.\" The time of the event is not sent to
+.\" .Xr syslogd 8 .
+.\" .It
+.\" The error string in the %m format is not printed symbolically but as
+.\" .Dq Error %d .
+.\" .El
+.\" .Pp
+.\" For more information about async-signal-safe functions and signal handlers, see
+.\" .Xr signal 7 .
+.Pp
+The
+.Fn vsyslog
+function
+is an alternative form in which the arguments have already been captured
+using the variable-length argument facilities of
+.Xr varargs 3 .
+.Pp
+The
+.Fn syslogp
+variants take additional arguments which correspond to new fields in the
+syslog-protocol message format.
+All three arguments are evaluated as
+.Xr printf 3
+format strings and any of them can be
+.Dv NULL .
+This enables applications to use message IDs, structured data, and UTF-8 encoded
+content in messages.
+.Pp
+The message is tagged with
+.Fa priority .
+Priorities are encoded as a
+.Fa facility
+and a
+.Em level .
+The facility describes the part of the system
+generating the message.
+The level is selected from the following
+.Em ordered
+(high to low) list:
+.Bl -tag -width LOG_AUTHPRIV
+.It Dv LOG_EMERG
+A panic condition.
+This is normally broadcast to all users.
+.It Dv LOG_ALERT
+A condition that should be corrected immediately, such as a corrupted
+system database.
+.It Dv LOG_CRIT
+Critical conditions, e.g., hard device errors.
+.It Dv LOG_ERR
+Errors.
+.It Dv LOG_WARNING
+Warning messages.
+.It Dv LOG_NOTICE
+Conditions that are not error conditions,
+but should possibly be handled specially.
+.It Dv LOG_INFO
+Informational messages.
+.It Dv LOG_DEBUG
+Messages that contain information
+normally of use only when debugging a program.
+.El
+.Pp
+The
+.Fn vsyslog_r
+is used the same way as
+.Fn vsyslog
+except that it takes an additional pointer to a
+.Fa syslog_data
+structure.
+It is a multithread-safe version of the
+.Fn vsyslog
+function described above.
+.\" The
+.\" .Fn vsyslog_ss
+.\" is the async-signal-safe version of
+.\" .Fn vsyslog_r ,
+.\" is also multithread-safe, and has the same limitations as
+.\" .Fn syslog_ss .
+.Pp
+The
+.Fn openlog
+function
+provides for more specialized processing of the messages sent
+by
+.Fn syslog
+and
+.Fn vsyslog .
+The parameter
+.Fa ident
+is a string that will be prepended to every message.
+The
+.Fa logopt
+argument
+is a bit field specifying logging options, which is formed by
+.Tn OR Ns 'ing
+one or more of the following values:
+.Bl -tag -width LOG_AUTHPRIV
+.It Dv LOG_CONS
+If
+.Fn syslog
+cannot pass the message to
+.Xr syslogd 8
+it will attempt to write the message to the console
+.Pq Dq Pa /dev/console .
+.It Dv LOG_NDELAY
+Open the connection to
+.Xr syslogd 8
+immediately.
+Normally the open is delayed until the first message is logged.
+Useful for programs that need to manage the order in which file
+descriptors are allocated.
+.It Dv LOG_PERROR
+Write the message to standard error output as well to the system log.
+.It Dv LOG_PID
+Log the process id with each message: useful for identifying
+instantiations of daemons.
+(This PID is placed within brackets
+between the ident and the message.)
+.El
+.Pp
+The
+.Fa facility
+parameter encodes a default facility to be assigned to all messages
+that do not have an explicit facility encoded:
+.Bl -tag -width LOG_AUTHPRIV
+.It Dv LOG_AUTH
+The authorization system:
+.Xr login 1 ,
+.Xr su 1 ,
+.Xr getty 8 ,
+etc.
+.It Dv LOG_AUTHPRIV
+The same as
+.Dv LOG_AUTH ,
+but logged to a file readable only by
+selected individuals.
+.It Dv LOG_CRON
+The cron daemon:
+.Xr cron 8 .
+.It Dv LOG_DAEMON
+System daemons, such as
+.Xr routed 8 ,
+that are not provided for explicitly by other facilities.
+.It Dv LOG_FTP
+The file transfer protocol daemon:
+.Xr ftpd 8 .
+.It Dv LOG_KERN
+Messages generated by the kernel.
+These cannot be generated by any user processes.
+.It Dv LOG_LPR
+The line printer spooling system:
+.Xr lpr 1 ,
+.Xr lpc 8 ,
+.Xr lpd 8 ,
+etc.
+.It Dv LOG_MAIL
+The mail system.
+.It Dv LOG_NEWS
+The network news system.
+.It Dv LOG_SYSLOG
+Messages generated internally by
+.Xr syslogd 8 .
+.It Dv LOG_USER
+Messages generated by random user processes.
+This is the default facility identifier if none is specified.
+.It Dv LOG_UUCP
+The uucp system.
+.It Dv LOG_LOCAL0
+Reserved for local use.
+Similarly for
+.Dv LOG_LOCAL1
+through
+.Dv LOG_LOCAL7 .
+.El
+.Pp
+The
+.Fn openlog_r
+function is the multithread-safe version of the
+.Fn openlog
+function.
+It takes an additional pointer to a
+.Fa syslog_data
+structure.
+This function must be used in conjunction with the other
+multithread-safe functions.
+.Pp
+The
+.Fn closelog
+function
+can be used to close the log file.
+.Pp
+The
+.Fn closelog_r
+does the same thing as
+.Xr closelog 3
+but in a multithread-safe way and takes an additional
+pointer to a
+.Fa syslog_data
+structure.
+.Pp
+The
+.Fn setlogmask
+function
+sets the log priority mask to
+.Fa maskpri
+and returns the previous mask.
+Calls to
+.Fn syslog
+with a priority not set in
+.Fa maskpri
+are rejected.
+The mask for an individual priority
+.Fa pri
+is calculated by the macro
+.Fn LOG_MASK pri ;
+the mask for all priorities up to and including
+.Fa toppri
+is given by the macro
+.Fn LOG_UPTO toppri .
+The default allows all priorities to be logged.
+.Pp
+The
+.Fn setlogmask_r
+function is the multithread-safe version of
+.Fn setlogmask .
+It takes an additional pointer to a
+.Fa syslog_data
+structure.
+.Sh RETURN VALUES
+The routines
+.Fn closelog ,
+.Fn closelog_r ,
+.Fn openlog ,
+.Fn openlog_r ,
+.Fn syslog ,
+.Fn syslog_r ,
+.Fn vsyslog ,
+.Fn vsyslog_r ,
+.Fn syslogp ,
+.Fn syslogp_r ,
+.Fn vsyslogp ,
+and
+.Fn vsyslogp_r
+return no value.
+.Pp
+The routines
+.Fn setlogmask
+and
+.Fn setlogmask_r
+always return the previous log mask level.
+.Sh EXAMPLES
+.Bd -literal -offset indent -compact
+syslog(LOG_ALERT, "who: internal error 23");
+
+openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
+
+setlogmask(LOG_UPTO(LOG_ERR));
+
+syslog(LOG_INFO, "Connection from host %d", CallingHost);
+
+syslog(LOG_INFO|LOG_LOCAL2, "foobar error: %m");
+
+syslogp(LOG_INFO|LOG_LOCAL2, NULL, NULL, "foobar error: %m");
+
+syslogp(LOG_INFO, "ID%d", "[meta language=\e"en-US\e"]",
+        "event: %s", 42, EventDescription);
+.Ed
+.Pp
+For the multithread-safe functions:
+.Bd -literal -offset indent
+struct syslog_data sdata = SYSLOG_DATA_INIT;
+
+syslog_r(LOG_INFO|LOG_LOCAL2, \*[Am]sdata, "foobar error: %m");
+.Ed
+.Sh SEE ALSO
+.Xr logger 1 ,
+.Xr syslogd 8
+.Rs
+.%R RFC
+.%N 3164
+.%D August 2001
+.%T The BSD syslog Protocol
+.Re
+.Rs
+.%R Internet-Draft
+.%N draft-ietf-syslog-protocol-23
+.%D September 2007
+.%T The syslog Protocol
+.Re
+.Sh HISTORY
+These non-multithread-safe functions appeared in
+.Bx 4.2 .
+The multithread-safe functions appeared in
+.Ox 3.1
+and then in
+.Nx 4.0 .
+The async-signal-safe functions appeared in
+.Nx 4.0 .
+The syslog-protocol functions appeared in
+.Nx 5.0 .
+.Sh CAVEATS
+It is important never to pass a string with user-supplied data as a
+format without using
+.Ql %s .
+An attacker can put format specifiers in the string to mangle your stack,
+leading to a possible security hole.
+This holds true even if you have built the string
+.Dq by hand
+using a function like
+.Fn snprintf ,
+as the resulting string may still contain user-supplied conversion specifiers
+for later interpolation by
+.Fn syslog .
+.Pp
+Always be sure to use the proper secure idiom:
+.Bd -literal -offset indent
+syslog(priority, "%s", string);
+.Ed
+.Pp
+With
+.Fn syslogp
+the caller is responsible to use the right formatting for the message fields.
+A
+.Fa msgid
+must only contain up to 32 ASCII characters.
+A
+.Fa sdfmt
+has strict rules for paranthesis and character quoting.
+If the
+.Fa msgfmt
+contains UTF-8 characters, then it has to start with a Byte Order Mark.
diff --git a/lib/nbsd_libc/gen/syslog.c b/lib/nbsd_libc/gen/syslog.c
new file mode 100644 (file)
index 0000000..6f96108
--- /dev/null
@@ -0,0 +1,571 @@
+/*     $NetBSD: syslog.c,v 1.48 2010/05/13 22:40:14 christos Exp $     */
+
+/*
+ * Copyright (c) 1983, 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)syslog.c   8.5 (Berkeley) 4/29/95";
+#else
+__RCSID("$NetBSD: syslog.c,v 1.48 2010/05/13 22:40:14 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/syslog.h>
+#include <sys/uio.h>
+#include <sys/un.h>
+#include <netdb.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <paths.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+#include "reentrant.h"
+#include "extern.h"
+
+#ifdef __weak_alias
+__weak_alias(closelog,_closelog)
+__weak_alias(openlog,_openlog)
+__weak_alias(setlogmask,_setlogmask)
+__weak_alias(syslog,_syslog)
+__weak_alias(vsyslog,_vsyslog)
+__weak_alias(syslogp,_syslogp)
+__weak_alias(vsyslogp,_vsyslogp)
+
+__weak_alias(closelog_r,_closelog_r)
+__weak_alias(openlog_r,_openlog_r)
+__weak_alias(setlogmask_r,_setlogmask_r)
+__weak_alias(syslog_r,_syslog_r)
+__weak_alias(vsyslog_r,_vsyslog_r)
+__weak_alias(syslog_ss,_syslog_ss)
+__weak_alias(vsyslog_ss,_vsyslog_ss)
+__weak_alias(syslogp_r,_syslogp_r)
+__weak_alias(vsyslogp_r,_vsyslogp_r)
+__weak_alias(syslogp_ss,_syslogp_ss)
+__weak_alias(vsyslogp_ss,_vsyslogp_ss)
+#endif
+
+static struct syslog_data sdata = SYSLOG_DATA_INIT;
+
+static void    openlog_unlocked_r(const char *, int, int,
+    struct syslog_data *);
+static void    disconnectlog_r(struct syslog_data *);
+static void    connectlog_r(struct syslog_data *);
+
+#define LOG_SIGNAL_SAFE        (int)0x80000000
+
+
+#ifdef _REENTRANT
+static mutex_t syslog_mutex = MUTEX_INITIALIZER;
+#endif
+
+static char hostname[MAXHOSTNAMELEN];
+
+/*
+ * syslog, vsyslog --
+ *     print message on log file; output is intended for syslogd(8).
+ */
+void
+syslog(int pri, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       vsyslog(pri, fmt, ap);
+       va_end(ap);
+}
+
+void
+vsyslog(int pri, const char *fmt, va_list ap)
+{
+       vsyslog_r(pri, &sdata, fmt, ap);
+}
+
+/*
+ * syslogp, vsyslogp --
+ *     like syslog but take additional arguments for MSGID and SD
+ */
+void
+syslogp(int pri, const char *msgid, const char *sdfmt, const char *msgfmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, msgfmt);
+       vsyslogp(pri, msgid, sdfmt, msgfmt, ap);
+       va_end(ap);
+}
+
+void
+vsyslogp(int pri, const char *msgid, const char *sdfmt, const char *msgfmt, va_list ap)
+{
+       vsyslogp_r(pri, &sdata, msgid, sdfmt, msgfmt, ap);
+}
+
+void
+openlog(const char *ident, int logstat, int logfac)
+{
+       openlog_r(ident, logstat, logfac, &sdata);
+}
+
+void
+closelog(void)
+{
+       closelog_r(&sdata);
+}
+
+/* setlogmask -- set the log mask level */
+int
+setlogmask(int pmask)
+{
+       return setlogmask_r(pmask, &sdata);
+}
+
+/* Reentrant version of syslog, i.e. syslog_r() */
+
+void
+syslog_r(int pri, struct syslog_data *data, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       vsyslog_r(pri, data, fmt, ap);
+       va_end(ap);
+}
+
+void
+syslogp_r(int pri, struct syslog_data *data, const char *msgid,
+       const char *sdfmt, const char *msgfmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, msgfmt);
+       vsyslogp_r(pri, data, msgid, sdfmt, msgfmt, ap);
+       va_end(ap);
+}
+
+void
+syslog_ss(int pri, struct syslog_data *data, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       vsyslog_r(pri | LOG_SIGNAL_SAFE, data, fmt, ap);
+       va_end(ap);
+}
+
+void
+syslogp_ss(int pri, struct syslog_data *data, const char *msgid,
+       const char *sdfmt, const char *msgfmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, msgfmt);
+       vsyslogp_r(pri | LOG_SIGNAL_SAFE, data, msgid, sdfmt, msgfmt, ap);
+       va_end(ap);
+}
+
+void
+vsyslog_ss(int pri, struct syslog_data *data, const char *fmt, va_list ap)
+{
+       vsyslog_r(pri | LOG_SIGNAL_SAFE, data, fmt, ap);
+}
+
+void
+vsyslogp_ss(int pri, struct syslog_data *data, const char *msgid,
+       const char *sdfmt, const char *msgfmt, va_list ap)
+{
+       vsyslogp_r(pri | LOG_SIGNAL_SAFE, data, msgid, sdfmt, msgfmt, ap);
+}
+
+
+void
+vsyslog_r(int pri, struct syslog_data *data, const char *fmt, va_list ap)
+{
+       vsyslogp_r(pri, data, NULL, NULL, fmt, ap);
+}
+
+void
+vsyslogp_r(int pri, struct syslog_data *data, const char *msgid,
+       const char *sdfmt, const char *msgfmt, va_list ap)
+{
+       static const char BRCOSP[] = "]: ";
+       static const char CRLF[] = "\r\n";
+       size_t cnt, prlen, tries;
+       char ch, *p, *t;
+       struct timeval tv;
+       struct tm tmnow;
+       time_t now;
+       int fd, saved_errno;
+#define TBUF_LEN       2048
+#define FMT_LEN                1024
+#define MAXTRIES       10
+       char tbuf[TBUF_LEN], fmt_cpy[FMT_LEN], fmt_cat[FMT_LEN] = "";
+       size_t tbuf_left, fmt_left, msgsdlen;
+       char *fmt = fmt_cat;
+       int signal_safe = pri & LOG_SIGNAL_SAFE;
+       struct iovec iov[7];    /* prog + [ + pid + ]: + fmt + crlf */
+       int opened, iovcnt;
+
+       pri &= ~LOG_SIGNAL_SAFE;
+
+#define INTERNALLOG    LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
+       /* Check for invalid bits. */
+       if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
+               syslog_r(INTERNALLOG | signal_safe, data,
+                   "syslog_r: unknown facility/priority: %x", pri);
+               pri &= LOG_PRIMASK|LOG_FACMASK;
+       }
+
+       /* Check priority against setlogmask values. */
+       if (!(LOG_MASK(LOG_PRI(pri)) & data->log_mask))
+               return;
+
+       saved_errno = errno;
+
+       /* Set default facility if none specified. */
+       if ((pri & LOG_FACMASK) == 0)
+               pri |= data->log_fac;
+
+       /* Build the message. */
+       p = tbuf;
+       tbuf_left = TBUF_LEN;
+
+#define DEC()                                                  \
+       do {                                                    \
+               if (prlen >= tbuf_left)                         \
+                       prlen = tbuf_left - 1;                  \
+               p += prlen;                                     \
+               tbuf_left -= prlen;                             \
+       } while (/*CONSTCOND*/0)
+
+       prlen = snprintf_ss(p, tbuf_left, "<%d>1 ", pri);
+       DEC();
+
+       if (!signal_safe && (gettimeofday(&tv, NULL) != -1)) {
+               /* strftime() implies tzset(), localtime_r() doesn't. */
+               tzset();
+               now = (time_t) tv.tv_sec;
+               localtime_r(&now, &tmnow);
+
+               prlen = strftime(p, tbuf_left, "%FT%T", &tmnow);
+               DEC();
+               prlen = snprintf(p, tbuf_left, ".%06ld", (long)tv.tv_usec);
+               DEC();
+               prlen = strftime(p, tbuf_left-1, "%z", &tmnow);
+               /* strftime gives eg. "+0200", but we need "+02:00" */
+               if (prlen == 5) {
+                       p[prlen+1] = p[prlen];
+                       p[prlen]   = p[prlen-1];
+                       p[prlen-1] = p[prlen-2];
+                       p[prlen-2] = ':';
+                       prlen += 1;
+               }
+       } else {
+               prlen = snprintf_ss(p, tbuf_left, "-");
+
+               /* if gmtime_r() was signal-safe we could output the UTC-time:
+               gmtime_r(&now, &tmnow);
+               prlen = strftime(p, tbuf_left, "%FT%TZ", &tmnow);
+               */
+       }
+       DEC();
+       prlen = snprintf_ss(p, tbuf_left, " %s ", hostname);
+       DEC();
+
+       if (data->log_tag == NULL)
+               data->log_tag = getprogname();
+
+       prlen = snprintf_ss(p, tbuf_left, "%s ",
+           data->log_tag ? data->log_tag : "-");
+       if (data->log_stat & (LOG_PERROR|LOG_CONS)) {
+               iovcnt = 0;
+               iov[iovcnt].iov_base = p;
+               iov[iovcnt].iov_len = prlen - 1;
+               iovcnt++;
+       }
+       DEC();
+
+       if (data->log_stat & LOG_PID) {
+               prlen = snprintf_ss(p, tbuf_left, "%d ", getpid());
+               if (data->log_stat & (LOG_PERROR|LOG_CONS)) {
+                       iov[iovcnt].iov_base = __UNCONST("[");
+                       iov[iovcnt].iov_len = 1;
+                       iovcnt++;
+                       iov[iovcnt].iov_base = p;
+                       iov[iovcnt].iov_len = prlen - 1;
+                       iovcnt++;
+                       iov[iovcnt].iov_base = __UNCONST(BRCOSP);
+                       iov[iovcnt].iov_len = 3;
+                       iovcnt++;
+               }
+       } else {
+               prlen = snprintf_ss(p, tbuf_left, "- ");
+               if (data->log_stat & (LOG_PERROR|LOG_CONS)) {
+                       iov[iovcnt].iov_base = __UNCONST(BRCOSP + 1);
+                       iov[iovcnt].iov_len = 2;
+                       iovcnt++;
+               }
+       }
+       DEC();
+
+       /*
+        * concat the format strings, then use one vsnprintf()
+        */
+       if (msgid != NULL && *msgid != '\0') {
+               strlcat(fmt_cat, msgid, FMT_LEN);
+               strlcat(fmt_cat, " ", FMT_LEN);
+       } else
+               strlcat(fmt_cat, "- ", FMT_LEN);
+
+       if (sdfmt != NULL && *sdfmt != '\0') {
+               strlcat(fmt_cat, sdfmt, FMT_LEN);
+       } else
+               strlcat(fmt_cat, "-", FMT_LEN);
+
+       if (data->log_stat & (LOG_PERROR|LOG_CONS))
+               msgsdlen = strlen(fmt_cat) + 1;
+       else
+               msgsdlen = 0;   /* XXX: GCC */
+
+       if (msgfmt != NULL && *msgfmt != '\0') {
+               strlcat(fmt_cat, " ", FMT_LEN);
+               strlcat(fmt_cat, msgfmt, FMT_LEN);
+       }
+
+       /*
+        * We wouldn't need this mess if printf handled %m, or if
+        * strerror() had been invented before syslog().
+        */
+       for (t = fmt_cpy, fmt_left = FMT_LEN; (ch = *fmt) != '\0'; ++fmt) {
+               if (ch == '%' && fmt[1] == 'm') {
+                       char ebuf[128];
+                       ++fmt;
+                       if (signal_safe ||
+                           strerror_r(saved_errno, ebuf, sizeof(ebuf)))
+                               prlen = snprintf_ss(t, fmt_left, "Error %d",
+                                   saved_errno);
+                       else
+                               prlen = snprintf_ss(t, fmt_left, "%s", ebuf);
+                       if (prlen >= fmt_left)
+                               prlen = fmt_left - 1;
+                       t += prlen;
+                       fmt_left -= prlen;
+               } else if (ch == '%' && fmt[1] == '%' && fmt_left > 2) {
+                       *t++ = '%';
+                       *t++ = '%';
+                       fmt++;
+                       fmt_left -= 2;
+               } else {
+                       if (fmt_left > 1) {
+                               *t++ = ch;
+                               fmt_left--;
+                       }
+               }
+       }
+       *t = '\0';
+
+       if (signal_safe)
+               prlen = vsnprintf_ss(p, tbuf_left, fmt_cpy, ap);
+       else
+               prlen = vsnprintf(p, tbuf_left, fmt_cpy, ap);
+
+       if (data->log_stat & (LOG_PERROR|LOG_CONS)) {
+               iov[iovcnt].iov_base = p + msgsdlen;
+               iov[iovcnt].iov_len = prlen - msgsdlen;
+               iovcnt++;
+       }
+
+       DEC();
+       cnt = p - tbuf;
+
+       /* Output to stderr if requested. */
+       if (data->log_stat & LOG_PERROR) {
+               iov[iovcnt].iov_base = __UNCONST(CRLF + 1);
+               iov[iovcnt].iov_len = 1;
+               (void)writev(STDERR_FILENO, iov, iovcnt + 1);
+       }
+
+       /* Get connected, output the message to the local logger. */
+       if (data == &sdata)
+               mutex_lock(&syslog_mutex);
+       opened = !data->opened;
+       if (opened)
+               openlog_unlocked_r(data->log_tag, data->log_stat, 0, data);
+       connectlog_r(data);
+
+       /*
+        * If the send() failed, there are two likely scenarios:
+        *  1) syslogd was restarted
+        *  2) /dev/log is out of socket buffer space
+        * We attempt to reconnect to /dev/log to take care of
+        * case #1 and keep send()ing data to cover case #2
+        * to give syslogd a chance to empty its socket buffer.
+        */
+       for (tries = 0; tries < MAXTRIES; tries++) {
+               if (send(data->log_file, tbuf, cnt, 0) != -1)
+                       break;
+               if (errno != ENOBUFS) {
+                       disconnectlog_r(data);
+                       connectlog_r(data);
+               } else
+                       (void)usleep(1);
+       }
+
+       /*
+        * Output the message to the console; try not to block
+        * as a blocking console should not stop other processes.
+        * Make sure the error reported is the one from the syslogd failure.
+        */
+       if (tries == MAXTRIES && (data->log_stat & LOG_CONS) &&
+           (fd = open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK, 0)) >= 0) {
+               iov[iovcnt].iov_base = __UNCONST(CRLF);
+               iov[iovcnt].iov_len = 2;
+               (void)writev(fd, iov, iovcnt + 1);
+               (void)close(fd);
+       }
+
+       if (data == &sdata)
+               mutex_unlock(&syslog_mutex);
+
+       if (data != &sdata && opened) {
+               /* preserve log tag */
+               const char *ident = data->log_tag;
+               closelog_r(data);
+               data->log_tag = ident;
+       }
+}
+
+static void
+disconnectlog_r(struct syslog_data *data)
+{
+       /*
+        * If the user closed the FD and opened another in the same slot,
+        * that's their problem.  They should close it before calling on
+        * system services.
+        */
+       if (data->log_file != -1) {
+               (void)close(data->log_file);
+               data->log_file = -1;
+       }
+       data->connected = 0;            /* retry connect */
+}
+
+static void
+connectlog_r(struct syslog_data *data)
+{
+       /* AF_UNIX address of local logger */
+       static const struct sockaddr_un sun = {
+               .sun_family = AF_LOCAL,
+               .sun_len = sizeof(sun),
+               .sun_path = _PATH_LOG,
+       };
+
+       if (data->log_file == -1 || fcntl(data->log_file, F_GETFL, 0) == -1) {
+               if ((data->log_file = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
+                       return;
+               (void)fcntl(data->log_file, F_SETFD, FD_CLOEXEC);
+               data->connected = 0;
+       }
+       if (!data->connected) {
+               if (connect(data->log_file,
+                   (const struct sockaddr *)(const void *)&sun,
+                   sizeof(sun)) == -1) {
+                       (void)close(data->log_file);
+                       data->log_file = -1;
+               } else
+                       data->connected = 1;
+       }
+}
+
+static void
+openlog_unlocked_r(const char *ident, int logstat, int logfac,
+    struct syslog_data *data)
+{
+       if (ident != NULL)
+               data->log_tag = ident;
+       data->log_stat = logstat;
+       if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
+               data->log_fac = logfac;
+
+       if (data->log_stat & LOG_NDELAY)        /* open immediately */
+               connectlog_r(data);
+
+       /* We could cache this, but then it might change */
+       if (gethostname(hostname, sizeof(hostname)) == -1
+           || hostname[0] == '\0') {
+               /* can this really happen? */
+               hostname[0] = '-';
+               hostname[1] = '\0';
+       }
+       data->opened = 1;
+}
+
+void
+openlog_r(const char *ident, int logstat, int logfac, struct syslog_data *data)
+{
+       if (data == &sdata)
+               mutex_lock(&syslog_mutex);
+       openlog_unlocked_r(ident, logstat, logfac, data);
+       if (data == &sdata)
+               mutex_unlock(&syslog_mutex);
+}
+
+void
+closelog_r(struct syslog_data *data)
+{
+       if (data == &sdata)
+               mutex_lock(&syslog_mutex);
+       (void)close(data->log_file);
+       data->log_file = -1;
+       data->connected = 0;
+       data->log_tag = NULL;
+       if (data == &sdata)
+               mutex_unlock(&syslog_mutex);
+}
+
+int
+setlogmask_r(int pmask, struct syslog_data *data)
+{
+       int omask;
+
+       omask = data->log_mask;
+       if (pmask != 0)
+               data->log_mask = pmask;
+       return omask;
+}
diff --git a/lib/nbsd_libc/gen/telldir.c b/lib/nbsd_libc/gen/telldir.c
new file mode 100644 (file)
index 0000000..f631642
--- /dev/null
@@ -0,0 +1,122 @@
+/*     $NetBSD: telldir.c,v 1.19 2008/05/04 18:53:26 tonnerre Exp $    */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)telldir.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: telldir.c,v 1.19 2008/05/04 18:53:26 tonnerre Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include "extern.h"
+#include <sys/param.h>
+
+#include <assert.h>
+#include <dirent.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "dirent_private.h"
+
+#ifdef __weak_alias
+__weak_alias(telldir,_telldir)
+#endif
+
+long
+telldir(DIR *dirp)
+{
+       long rv;
+#ifdef _REENTRANT
+       if (__isthreaded) {
+               mutex_lock((mutex_t *)dirp->dd_lock);
+               rv = (intptr_t)_telldir_unlocked(dirp);
+               mutex_unlock((mutex_t *)dirp->dd_lock);
+       } else
+#endif
+               rv = (intptr_t)_telldir_unlocked(dirp);
+       return rv;
+}
+
+/*
+ * return a pointer into a directory
+ */
+long
+_telldir_unlocked(DIR *dirp)
+{
+       struct dirpos *lp;
+
+       for (lp = dirp->dd_internal; lp; lp = lp->dp_next)
+               if (lp->dp_seek == dirp->dd_seek &&
+                   lp->dp_loc == dirp->dd_loc)
+                       return (intptr_t)lp;
+
+       if ((lp = malloc(sizeof(*lp))) == NULL)
+               return (-1);
+
+       lp->dp_seek = dirp->dd_seek;
+       lp->dp_loc = dirp->dd_loc;
+       lp->dp_next = dirp->dd_internal;
+       dirp->dd_internal = lp;
+
+       return (intptr_t)lp;
+}
+
+/*
+ * seek to an entry in a directory.
+ * Only values returned by "telldir" should be passed to seekdir.
+ */
+void
+_seekdir_unlocked(DIR *dirp, long loc)
+{
+       struct dirpos *lp;
+
+       _DIAGASSERT(dirp != NULL);
+
+       for (lp = dirp->dd_internal; lp; lp = lp->dp_next)
+               if ((intptr_t)lp == loc)
+                       break;
+
+       if (lp == NULL)
+               return;
+
+       if (lp->dp_loc == dirp->dd_loc && lp->dp_seek == dirp->dd_seek)
+               return;
+
+       dirp->dd_seek = lseek(dirp->dd_fd, lp->dp_seek, SEEK_SET);
+       dirp->dd_loc = 0;
+       while (dirp->dd_loc < lp->dp_loc)
+               if (_readdir_unlocked(dirp, 0) == NULL)
+                       break;
+}
diff --git a/lib/nbsd_libc/gen/time.3 b/lib/nbsd_libc/gen/time.3
new file mode 100644 (file)
index 0000000..5c44f95
--- /dev/null
@@ -0,0 +1,112 @@
+.\"    $NetBSD: time.3,v 1.15 2010/04/24 01:35:50 dholland Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)time.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 23, 2010
+.Dt TIME 3
+.Os
+.Sh NAME
+.Nm time
+.Nd get time of day
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Ft time_t
+.Fn time "time_t *tloc"
+.Sh DESCRIPTION
+The
+.Fn time
+function
+returns the value of time in seconds since 0 hours, 0 minutes,
+0 seconds, January 1, 1970, Coordinated Universal Time.
+.Pp
+A copy of the time value may be saved to the area indicated by the
+pointer
+.Fa tloc .
+If
+.Fa tloc
+is a
+.Dv NULL
+pointer, no value is stored.
+.Pp
+Upon successful completion,
+.Fn time
+returns the value of time.
+Otherwise a value of
+.Po
+.Po Fa time_t Pc \-1
+.Pc
+is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The following error codes may be set in
+.Va errno :
+.Bl -tag -width Er
+.It Bq Er EFAULT
+An argument address referenced invalid memory.
+.El
+.Sh SEE ALSO
+.Xr gettimeofday 2 ,
+.Xr ctime 3
+.Sh STANDARDS
+The
+.Fn time
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+A
+.Fn time
+function appeared in
+.At v2 .
+It returned a 32-bit value measuring sixtieths of a second, leading to
+rollover every 2.26 years.
+In
+.At v6 ,
+the precision of
+.Fn time
+was changed to seconds, allowing 135.6 years between rollovers.
+.Pp
+In
+.Nx 6.0
+the
+.Vt time_t
+type was changed to be 64 bits wide, including on 32-bit machines,
+making rollover a concern for the far distant future only.
+Note however that any code making the incorrect assumption that
+.Vt time_t
+is the same as
+.Vt long
+will fail on 32-bit machines in 2038.
diff --git a/lib/nbsd_libc/gen/time.c b/lib/nbsd_libc/gen/time.c
new file mode 100644 (file)
index 0000000..e0df22f
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: time.c,v 1.11 2009/01/11 02:46:27 christos Exp $       */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)time.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: time.c,v 1.11 2009/01/11 02:46:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/time.h>
+
+#include <time.h>
+
+time_t
+time(time_t *t)
+{
+       struct timeval tt;
+
+       if (gettimeofday(&tt, NULL) == -1)
+               return (time_t)-1;
+       if (t != NULL)
+               *t = tt.tv_sec;
+       return tt.tv_sec;
+}
diff --git a/lib/nbsd_libc/gen/times.3 b/lib/nbsd_libc/gen/times.3
new file mode 100644 (file)
index 0000000..f14d9eb
--- /dev/null
@@ -0,0 +1,151 @@
+.\"    $NetBSD: times.3,v 1.15 2003/08/07 16:42:58 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)times.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt TIMES 3
+.Os
+.Sh NAME
+.Nm times
+.Nd process times
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/times.h
+.Ft clock_t
+.Fn times "struct tms *tp"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is obsoleted by
+.Xr getrusage 2
+and
+.Xr gettimeofday 2 .
+.Ef
+.Pp
+The
+.Fn times
+function returns the value of time in clock ticks since 0 hours, 0
+minutes, 0 seconds, January 1, 1970, Coordinated Universal Time (UTC).
+.Pp
+The number of clock ticks per second may be determined by calling
+.Xr sysconf 3
+with the
+.Dv _SC_CLK_TCK
+request.
+It is generally (but not always) between 60 and 1024.
+.Pp
+Note that at the common rate of 100 ticks per second on many
+.Nx
+ports, and with a 32-bit unsigned clock_t, this value first wrapped in 1971.
+.Pp
+The
+.Fn times
+call also fills in the structure pointed to by
+.Fa tp
+with time-accounting information.
+.Pp
+The
+.Fa tms
+structure is defined as follows:
+.Bd -literal -offset indent
+typedef struct {
+       clock_t tms_utime;
+       clock_t tms_stime;
+       clock_t tms_cutime;
+       clock_t tms_cstime;
+}
+.Ed
+.Pp
+The elements of this structure are defined as follows:
+.Bl -tag -width tms_cutime
+.It Fa tms_utime
+The
+.Tn CPU
+time charged for the execution of user instructions.
+.It Fa tms_stime
+The
+.Tn CPU
+time charged for execution by the system on behalf of
+the process.
+.It Fa tms_cutime
+The sum of the
+.Fa tms_utime  s
+and
+.Fa tms_cutime  s
+of the child processes.
+.It Fa tms_cstime
+The sum of the
+.Fa tms_stime Ns s
+and
+.Fa tms_cstime Ns s
+of the child processes.
+.El
+.Pp
+All times are measured in clock ticks, as defined above.
+Note that at 100 ticks per second,
+and with a 32-bit unsigned clock_t,
+the values wrap after 497 days.
+.Pp
+The times of a terminated child process are included in the
+.Fa tms_cutime
+and
+.Fa tms_cstime
+elements of the parent when one of the
+.Xr wait 2
+functions returns the process ID of the terminated child to the parent.
+If an error occurs,
+.Fn times
+returns the value
+.Pq (clock_t)\-1 ,
+and sets
+.Va errno
+to indicate the error.
+.Sh ERRORS
+The
+.Fn times
+function
+may fail and set the global variable
+.Va errno
+for any of the errors specified for the library
+routines
+.Xr getrusage 2
+and
+.Xr gettimeofday 2 .
+.Sh SEE ALSO
+.Xr time 1 ,
+.Xr getrusage 2 ,
+.Xr gettimeofday 2 ,
+.Xr wait 2 ,
+.Xr sysconf 3
+.Sh STANDARDS
+The
+.Fn times
+function conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/gen/times.c b/lib/nbsd_libc/gen/times.c
new file mode 100644 (file)
index 0000000..55b05a1
--- /dev/null
@@ -0,0 +1,92 @@
+/*     $NetBSD: times.c,v 1.15 2009/01/11 02:46:27 christos Exp $      */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)times.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: times.c,v 1.15 2009/01/11 02:46:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/time.h>
+#include <sys/times.h>
+#include <sys/resource.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <time.h>
+
+/*
+ * Convert usec to clock ticks; could do (usec * CLK_TCK) / 1000000,
+ * but this would overflow if we switch to nanosec.
+ */
+#define        CONVTCK(r)      \
+    (clock_t)(r.tv_sec * clk_tck + r.tv_usec / (1000000 / (uint)clk_tck))
+
+#ifndef __times_rusage
+#define __times_rusage struct rusage
+#endif
+#ifndef __times_timeval
+#define __times_timeval struct timeval
+#endif
+
+clock_t
+times(struct tms *tp)
+{
+       __times_rusage ru;
+       __times_timeval t;
+       static clock_t clk_tck;
+       
+       _DIAGASSERT(tp != NULL);
+
+       /*
+        * we use a local copy of CLK_TCK because it expands to a
+        * moderately expensive function call.
+        */
+       if (clk_tck == 0)
+               clk_tck = (clock_t)CLK_TCK;
+
+       if (getrusage(RUSAGE_SELF, &ru) < 0)
+               return ((clock_t)-1);
+       tp->tms_utime = CONVTCK(ru.ru_utime);
+       tp->tms_stime = CONVTCK(ru.ru_stime);
+       if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
+               return ((clock_t)-1);
+       tp->tms_cutime = CONVTCK(ru.ru_utime);
+       tp->tms_cstime = CONVTCK(ru.ru_stime);
+       if (gettimeofday(&t, (struct timezone *)0))
+               return ((clock_t)-1);
+       return ((clock_t)(CONVTCK(t)));
+}
diff --git a/lib/nbsd_libc/gen/timezone.3 b/lib/nbsd_libc/gen/timezone.3
new file mode 100644 (file)
index 0000000..6a202da
--- /dev/null
@@ -0,0 +1,75 @@
+.\"    $NetBSD: timezone.3,v 1.12 2003/08/07 16:42:58 agc Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)timezone.3  8.2 (Berkeley) 4/19/94
+.\"
+.Dd April 19, 1994
+.Dt TIMEZONE 3
+.Os
+.Sh NAME
+.Nm timezone
+.Nd return the timezone abbreviation
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.Ft char *
+.Fn timezone "int zone" "int dst"
+.Sh DESCRIPTION
+.Bf -symbolic
+.\" This interface is available from the compatibility library, libcompat;
+This interface is available for compatibility only and will disappear in a
+future software release;
+it is impossible to reliably map timezone's arguments to a time zone
+abbreviation.
+See
+.Xr ctime 3 ;
+see
+.Xr tzset 3
+for the new definition of this interface.
+.Ef
+.Pp
+The
+.Fn timezone
+function returns a pointer to a time zone abbreviation for the specified
+.Ar zone
+and
+.Ar dst
+values.
+.Ar Zone
+is the number of minutes west of GMT and
+.Ar dst
+is non-zero if daylight savings time is in effect.
+.Sh SEE ALSO
+.Xr ctime 3 ,
+.Xr tzset 3
+.Sh HISTORY
+A
+.Fn timezone
+function appeared in
+.At v7 .
diff --git a/lib/nbsd_libc/gen/toascii.3 b/lib/nbsd_libc/gen/toascii.3
new file mode 100644 (file)
index 0000000..e2c0e0f
--- /dev/null
@@ -0,0 +1,83 @@
+.\"    $NetBSD: toascii.3,v 1.13 2010/04/30 04:46:18 jruoho Exp $
+.\"
+.\" Copyright (c) 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.
+.\" 3. 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.
+.\"
+.\"    @(#)toascii.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 30, 2010
+.Dt TOASCII 3
+.Os
+.Sh NAME
+.Nm toascii
+.Nd convert a byte to 7-bit ASCII
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn toascii "int c"
+.Sh DESCRIPTION
+The
+.Fn toascii
+function returns the argument with all but the lower 7 bits cleared.
+.Sh RETURN VALUES
+The
+.Fn toascii
+function always returns a valid ASCII character.
+The result is a non-negative integer in the
+range from 0 to 127, inclusive.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr tolower 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn toascii
+function conforms to
+.St -xpg4
+and
+.St -p1003.1-2001 .
+The
+.St -p1003.1-2008
+revision however marked it as obsolete, noting that
+.Fn toascii
+cannot be used portably in a localized application.
diff --git a/lib/nbsd_libc/gen/toascii.c b/lib/nbsd_libc/gen/toascii.c
new file mode 100644 (file)
index 0000000..7bddde1
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: toascii.c,v 1.2 2003/08/07 16:42:58 agc Exp $  */
+
+/*
+ * Copyright (c) 1989 The Regents of the University of California.
+ * All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     from:   @(#)isctype.c   5.2 (Berkeley) 6/1/90
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: toascii.c,v 1.2 2003/08/07 16:42:58 agc Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <ctype.h>
+
+#undef toascii
+int
+toascii(c)
+       int c;
+{
+       return ((c) & 0177);
+}
diff --git a/lib/nbsd_libc/gen/tolower.3 b/lib/nbsd_libc/gen/tolower.3
new file mode 100644 (file)
index 0000000..253a55e
--- /dev/null
@@ -0,0 +1,102 @@
+.\"    $NetBSD: tolower.3,v 1.14 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1989, 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"    @(#)tolower.3   5.2 (Berkeley) 6/29/91
+.\"
+.Dd April 17, 2008
+.Dt TOLOWER 3
+.Os
+.Sh NAME
+.Nm tolower
+.Nd upper case to lower case letter conversion
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn tolower "int c"
+.Sh DESCRIPTION
+The
+.Fn tolower
+function converts an upper-case letter to the corresponding lower-case
+letter.
+.Sh RETURN VALUES
+If the argument is an upper-case letter, the
+.Fn tolower
+function returns the corresponding lower-case letter if there is
+one; otherwise the argument is returned unchanged.
+.\" In the
+.\" .Em ``C''
+.\" locale,
+.\" .Fn tolower
+.\" maps only the characters for which
+.\" .Xr isupper
+.\" is true to the corresponding characters for which
+.\" .Xr islower
+.\" is true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr toupper 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn tolower
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn tolower
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/tolower_.c b/lib/nbsd_libc/gen/tolower_.c
new file mode 100644 (file)
index 0000000..edc6ee3
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: tolower_.c,v 1.13 2010/06/01 13:52:08 tnozaki Exp $    */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_RCS) && !defined(lint)
+__RCSID("$NetBSD: tolower_.c,v 1.13 2010/06/01 13:52:08 tnozaki Exp $");
+#endif /* LIBC_RCS and not lint */
+
+#include <sys/ctype_bits.h>
+#include <stdio.h>
+#include "ctype_local.h"
+
+#if EOF != -1
+#error "EOF != -1"
+#endif
+
+const short _C_tolower_[1 + _CTYPE_NUM_CHARS] = {
+       EOF,
+       0x00,   0x01,   0x02,   0x03,   0x04,   0x05,   0x06,   0x07,
+       0x08,   0x09,   0x0a,   0x0b,   0x0c,   0x0d,   0x0e,   0x0f,
+       0x10,   0x11,   0x12,   0x13,   0x14,   0x15,   0x16,   0x17,
+       0x18,   0x19,   0x1a,   0x1b,   0x1c,   0x1d,   0x1e,   0x1f,
+       0x20,   0x21,   0x22,   0x23,   0x24,   0x25,   0x26,   0x27,
+       0x28,   0x29,   0x2a,   0x2b,   0x2c,   0x2d,   0x2e,   0x2f,
+       0x30,   0x31,   0x32,   0x33,   0x34,   0x35,   0x36,   0x37,
+       0x38,   0x39,   0x3a,   0x3b,   0x3c,   0x3d,   0x3e,   0x3f,
+       0x40,   'a',    'b',    'c',    'd',    'e',    'f',    'g',
+       'h',    'i',    'j',    'k',    'l',    'm',    'n',    'o',
+       'p',    'q',    'r',    's',    't',    'u',    'v',    'w',
+       'x',    'y',    'z',    0x5b,   0x5c,   0x5d,   0x5e,   0x5f,
+       0x60,   0x61,   0x62,   0x63,   0x64,   0x65,   0x66,   0x67,
+       0x68,   0x69,   0x6a,   0x6b,   0x6c,   0x6d,   0x6e,   0x6f,
+       0x70,   0x71,   0x72,   0x73,   0x74,   0x75,   0x76,   0x77,
+       0x78,   0x79,   0x7a,   0x7b,   0x7c,   0x7d,   0x7e,   0x7f,
+       0x80,   0x81,   0x82,   0x83,   0x84,   0x85,   0x86,   0x87,
+       0x88,   0x89,   0x8a,   0x8b,   0x8c,   0x8d,   0x8e,   0x8f,
+       0x90,   0x91,   0x92,   0x93,   0x94,   0x95,   0x96,   0x97,
+       0x98,   0x99,   0x9a,   0x9b,   0x9c,   0x9d,   0x9e,   0x9f,
+       0xa0,   0xa1,   0xa2,   0xa3,   0xa4,   0xa5,   0xa6,   0xa7,
+       0xa8,   0xa9,   0xaa,   0xab,   0xac,   0xad,   0xae,   0xaf,
+       0xb0,   0xb1,   0xb2,   0xb3,   0xb4,   0xb5,   0xb6,   0xb7,
+       0xb8,   0xb9,   0xba,   0xbb,   0xbc,   0xbd,   0xbe,   0xbf,
+       0xc0,   0xc1,   0xc2,   0xc3,   0xc4,   0xc5,   0xc6,   0xc7,
+       0xc8,   0xc9,   0xca,   0xcb,   0xcc,   0xcd,   0xce,   0xcf,
+       0xd0,   0xd1,   0xd2,   0xd3,   0xd4,   0xd5,   0xd6,   0xd7,
+       0xd8,   0xd9,   0xda,   0xdb,   0xdc,   0xdd,   0xde,   0xdf,
+       0xe0,   0xe1,   0xe2,   0xe3,   0xe4,   0xe5,   0xe6,   0xe7,
+       0xe8,   0xe9,   0xea,   0xeb,   0xec,   0xed,   0xee,   0xef,
+       0xf0,   0xf1,   0xf2,   0xf3,   0xf4,   0xf5,   0xf6,   0xf7,
+       0xf8,   0xf9,   0xfa,   0xfb,   0xfc,   0xfd,   0xfe,   0xff
+};
+
+const short *_tolower_tab_ = &_C_tolower_[0];
diff --git a/lib/nbsd_libc/gen/toupper.3 b/lib/nbsd_libc/gen/toupper.3
new file mode 100644 (file)
index 0000000..b927a54
--- /dev/null
@@ -0,0 +1,101 @@
+.\"    $NetBSD: toupper.3,v 1.17 2008/04/17 16:25:36 apb Exp $
+.\"
+.\" Copyright (c) 1989, 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"    @(#)toupper.3   5.2 (Berkeley) 6/29/91
+.\"
+.Dd April 17, 2008
+.Dt TOUPPER 3
+.Os
+.Sh NAME
+.Nm toupper
+.Nd lower case to upper case letter conversion
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ctype.h
+.Ft int
+.Fn toupper "int c"
+.Sh DESCRIPTION
+The
+.Fn toupper
+function converts a lower-case letter to the corresponding
+upper-case letter.
+.Sh RETURN VALUES
+If the argument is a lower-case letter, the
+.Fn toupper
+function returns the corresponding upper-case letter if there is
+one; otherwise the argument is returned unchanged.
+.\" In the
+.\" .Em ``C''
+.\" locale,
+.\" .Fn toupper
+.\" maps only the characters for which
+.\" .Xr islower
+.\" is true to the corresponding characters for which
+.\" .Xr isupper
+.\" is true.
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isascii 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3 ,
+.Xr stdio 3 ,
+.Xr toascii 3 ,
+.Xr ascii 7
+.Sh STANDARDS
+The
+.Fn toupper
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+The argument to
+.Fn toupper
+must be
+.Dv EOF
+or representable as an
+.Vt unsigned char ;
+otherwise, the behavior is undefined.
+See the
+.Sx CAVEATS
+section of
+.Xr ctype 3
+for more details.
diff --git a/lib/nbsd_libc/gen/toupper_.c b/lib/nbsd_libc/gen/toupper_.c
new file mode 100644 (file)
index 0000000..864f7e1
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: toupper_.c,v 1.13 2010/06/01 13:52:08 tnozaki Exp $    */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_RCS) && !defined(lint)
+__RCSID("$NetBSD: toupper_.c,v 1.13 2010/06/01 13:52:08 tnozaki Exp $");
+#endif /* LIBC_RCS and not lint */
+
+#include <sys/ctype_bits.h>
+#include <stdio.h>
+#include "ctype_local.h"
+
+#if EOF != -1
+#error "EOF != -1"
+#endif
+
+const short _C_toupper_[1 + _CTYPE_NUM_CHARS] = {
+       EOF,
+       0x00,   0x01,   0x02,   0x03,   0x04,   0x05,   0x06,   0x07,
+       0x08,   0x09,   0x0a,   0x0b,   0x0c,   0x0d,   0x0e,   0x0f,
+       0x10,   0x11,   0x12,   0x13,   0x14,   0x15,   0x16,   0x17,
+       0x18,   0x19,   0x1a,   0x1b,   0x1c,   0x1d,   0x1e,   0x1f,
+       0x20,   0x21,   0x22,   0x23,   0x24,   0x25,   0x26,   0x27,
+       0x28,   0x29,   0x2a,   0x2b,   0x2c,   0x2d,   0x2e,   0x2f,
+       0x30,   0x31,   0x32,   0x33,   0x34,   0x35,   0x36,   0x37,
+       0x38,   0x39,   0x3a,   0x3b,   0x3c,   0x3d,   0x3e,   0x3f,
+       0x40,   0x41,   0x42,   0x43,   0x44,   0x45,   0x46,   0x47,
+       0x48,   0x49,   0x4a,   0x4b,   0x4c,   0x4d,   0x4e,   0x4f,
+       0x50,   0x51,   0x52,   0x53,   0x54,   0x55,   0x56,   0x57,
+       0x58,   0x59,   0x5a,   0x5b,   0x5c,   0x5d,   0x5e,   0x5f,
+       0x60,   'A',    'B',    'C',    'D',    'E',    'F',    'G',
+       'H',    'I',    'J',    'K',    'L',    'M',    'N',    'O',
+       'P',    'Q',    'R',    'S',    'T',    'U',    'V',    'W',
+       'X',    'Y',    'Z',    0x7b,   0x7c,   0x7d,   0x7e,   0x7f,
+       0x80,   0x81,   0x82,   0x83,   0x84,   0x85,   0x86,   0x87,
+       0x88,   0x89,   0x8a,   0x8b,   0x8c,   0x8d,   0x8e,   0x8f,
+       0x90,   0x91,   0x92,   0x93,   0x94,   0x95,   0x96,   0x97,
+       0x98,   0x99,   0x9a,   0x9b,   0x9c,   0x9d,   0x9e,   0x9f,
+       0xa0,   0xa1,   0xa2,   0xa3,   0xa4,   0xa5,   0xa6,   0xa7,
+       0xa8,   0xa9,   0xaa,   0xab,   0xac,   0xad,   0xae,   0xaf,
+       0xb0,   0xb1,   0xb2,   0xb3,   0xb4,   0xb5,   0xb6,   0xb7,
+       0xb8,   0xb9,   0xba,   0xbb,   0xbc,   0xbd,   0xbe,   0xbf,
+       0xc0,   0xc1,   0xc2,   0xc3,   0xc4,   0xc5,   0xc6,   0xc7,
+       0xc8,   0xc9,   0xca,   0xcb,   0xcc,   0xcd,   0xce,   0xcf,
+       0xd0,   0xd1,   0xd2,   0xd3,   0xd4,   0xd5,   0xd6,   0xd7,
+       0xd8,   0xd9,   0xda,   0xdb,   0xdc,   0xdd,   0xde,   0xdf,
+       0xe0,   0xe1,   0xe2,   0xe3,   0xe4,   0xe5,   0xe6,   0xe7,
+       0xe8,   0xe9,   0xea,   0xeb,   0xec,   0xed,   0xee,   0xef,
+       0xf0,   0xf1,   0xf2,   0xf3,   0xf4,   0xf5,   0xf6,   0xf7,
+       0xf8,   0xf9,   0xfa,   0xfb,   0xfc,   0xfd,   0xfe,   0xff
+};
+
+const short *_toupper_tab_ = &_C_toupper_[0];
diff --git a/lib/nbsd_libc/gen/ttyname.3 b/lib/nbsd_libc/gen/ttyname.3
new file mode 100644 (file)
index 0000000..a9c0941
--- /dev/null
@@ -0,0 +1,204 @@
+.\"    $NetBSD: ttyname.3,v 1.21 2008/06/25 11:47:29 ad Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)ttyname.3  8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 25, 2008
+.Dt TTYNAME 3
+.Os
+.Sh NAME
+.Nm ttyname ,
+.Nm ttyname_r ,
+.Nm isatty ,
+.Nm ttyslot
+.Nd get name of associated terminal (tty) from file descriptor
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft char *
+.Fn ttyname "int fd"
+.Ft int
+.Fn ttyname_r "int fd" "char *buf" "size_t len"
+.Ft int
+.Fn isatty "int fd"
+.In stdlib.h
+.Ft int
+.Fn ttyslot
+.Sh DESCRIPTION
+These functions operate on the system file descriptors for terminal
+type devices.
+These descriptors are not related to the standard
+.Tn I/O
+.Dv FILE
+typedef, but refer to the special device files found in
+.Pa /dev
+and named
+.Pa /dev/tty Ns Em xx
+and for which an entry exists in the initialization file
+.Pa /etc/ttys
+(see
+.Xr ttys 5 ) ,
+or for pseudo-terminal devices created in ptyfs and named
+.Pa /dev/pts/ Ns Em n .
+.Pp
+The
+.Fn isatty
+function
+determines if the file descriptor
+.Fa fd
+refers to a valid terminal type device.
+.Pp
+The
+.Fn ttyname
+function gets the related device name of a file descriptor for
+which
+.Fn isatty
+is true.
+The
+.Fn ttyname_r
+is the reentrant version of the above, and it places the results in
+.Fa buf .
+If there is not enough space to place the results (indicated by
+.Fa len ) ,
+then it returns an error.
+.Pp
+The
+.Fn ttyslot
+function
+fetches the current process' control terminal number from the
+.Xr ttys 5
+file entry.
+If the terminal is a pseudo-terminal, and there is no special entry
+in the
+.Xr ttys 5
+file for it, the slot number returned is 1 + (last slot number) +
+minor(tty).
+This will return a consistent and unique number for each pseudo-terminal
+device without requiring one to enumerate all of them in
+.Xr ttys 5 .
+.Sh IMPLEMENTATION NOTES
+As an optimisation, these functions attempt to obtain information about
+all devices from the
+.Pa /var/run/dev.db
+database, if it exists.
+If the database exists but is out of date, then these functions
+may produce incorrect results.
+The database should be updated using the
+.Xr dev_mkdb 8
+command.
+.Sh RETURN VALUES
+The
+.Fn ttyname
+function returns the NUL-terminated name if the device is found and
+.Fn isatty
+is true; otherwise
+a
+.Dv NULL
+pointer is returned and
+.Va errno
+is set to indicate the error.
+.Pp
+The
+.Fn ttyname_r
+functions returns 0 on success and an error code on failure.
+.Pp
+The
+.Fn isatty
+function returns 1 if
+.Fa fd
+is associated with a terminal device; otherwise it returns 0 and
+.Va errno
+is set to indicate the error.
+.Pp
+The
+.Fn ttyslot
+function
+returns the unit number of the device file if found; otherwise
+the value zero is returned.
+.Sh FILES
+.Bl -tag -width /etc/ttys -compact
+.It Pa /dev/\(**
+.It Pa /etc/ttys
+.El
+.Sh ERRORS
+The
+.Fn ttyname ,
+.Fn ttyname_r ,
+and
+.Fn isatty
+functions will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa fd
+argument is not a valid file descriptor.
+.It Bq Er ENOTTY
+The
+.Fa fd
+argument does not refer to a terminal device.
+.El
+.Pp
+The
+.Fn ttyname_r
+function will also fail if:
+.Bl -tag -width Er
+.It Bq Er ERANGE
+The buffer provided is not large enough to fit the result.
+.It Bq Er ENOENT
+The terminal device is not found.
+This can happen if the device node has been removed after it was opened.
+.El
+.Sh SEE ALSO
+.Xr ioctl 2 ,
+.Xr ttys 5 ,
+.Xr dev_mkdb 8
+.Sh STANDARDS
+The
+.Fn ttyname
+and
+.Fn isatty
+functions conform to
+.St -p1003.1-90 .
+.Sh HISTORY
+.Fn isatty ,
+.Fn ttyname ,
+and
+.Fn ttyslot
+functions appeared in
+.At v7 .
+.\" Use of the .Pa /var/run/dev.db file was added in ???.
+.Sh BUGS
+The
+.Fn ttyname
+function leaves its result in an internal static object and returns
+a pointer to that object.
+Subsequent calls to
+.Fn ttyname
+will modify the same object.
diff --git a/lib/nbsd_libc/gen/ttyname.c b/lib/nbsd_libc/gen/ttyname.c
new file mode 100644 (file)
index 0000000..6002c1e
--- /dev/null
@@ -0,0 +1,177 @@
+/*     $NetBSD: ttyname.c,v 1.24 2008/06/25 11:47:29 ad Exp $  */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ttyname.c  8.2 (Berkeley) 1/27/94";
+#else
+__RCSID("$NetBSD: ttyname.c,v 1.24 2008/06/25 11:47:29 ad Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <db.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <paths.h>
+#include <string.h>
+#include <termios.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+
+#ifdef __weak_alias
+__weak_alias(ttyname,_ttyname)
+__weak_alias(ttyname_r,_ttyname_r)
+#endif
+
+static int oldttyname(const struct stat *, char *, size_t);
+
+int
+ttyname_r(int fd, char *buf, size_t len)
+{
+       struct stat sb;
+       struct termios ttyb;
+       DB *db;
+       DBT data, key;
+       struct {
+               mode_t type;
+               dev_t dev;
+       } bkey;
+       struct ptmget ptm;
+#define DEVSZ (sizeof(_PATH_DEV) - 1)
+
+       _DIAGASSERT(fd != -1);
+
+       if (len <= DEVSZ) {
+               return ERANGE;
+       }
+
+       /* If it is a pty, deal with it quickly */
+       if (ioctl(fd, TIOCPTSNAME, &ptm) != -1) {
+               if (strlcpy(buf, ptm.sn, len) >= len) {
+                       return ERANGE;
+               }
+               return 0;
+       }
+       /* Must be a terminal. */
+       if (tcgetattr(fd, &ttyb) == -1)
+               return errno;
+
+       /* Must be a character device. */
+       if (fstat(fd, &sb))
+               return errno;
+       if (!S_ISCHR(sb.st_mode))
+               return ENOTTY;
+
+       (void)memcpy(buf, _PATH_DEV, DEVSZ);
+       if ((db = dbopen(_PATH_DEVDB, O_RDONLY, 0, DB_HASH, NULL)) != NULL) {
+               (void)memset(&bkey, 0, sizeof(bkey));
+               bkey.type = S_IFCHR;
+               bkey.dev = sb.st_rdev;
+               key.data = &bkey;
+               key.size = sizeof(bkey);
+               if (!(db->get)(db, &key, &data, 0)) {
+                       if (len - DEVSZ <= data.size) {
+                               return ERANGE;
+                       }
+                       (void)memcpy(buf + DEVSZ, data.data, data.size);
+                       (void)(db->close)(db);
+                       return 0;
+               }
+               (void)(db->close)(db);
+       }
+       if (oldttyname(&sb, buf, len) == -1)
+               return errno;
+       return 0;
+}
+
+static int
+oldttyname(const struct stat *sb, char *buf, size_t len)
+{
+       struct dirent *dirp;
+       DIR *dp;
+       struct stat dsb;
+       size_t dlen;
+
+       _DIAGASSERT(sb != NULL);
+
+       if ((dp = opendir(_PATH_DEV)) == NULL)
+               return -1;
+
+       while ((dirp = readdir(dp)) != NULL) {
+               if (dirp->d_fileno != sb->st_ino)
+                       continue;
+               dlen = dirp->d_namlen + 1;
+               if (len - DEVSZ <= dlen) {
+                       /*
+                        * XXX: we return an error if *any* entry does not
+                        * fit
+                        */
+                       errno = ERANGE;
+                       (void)closedir(dp);
+                       return -1;
+               }
+               (void)memcpy(buf + DEVSZ, dirp->d_name, dlen);
+               if (stat(buf, &dsb) || sb->st_dev != dsb.st_dev ||
+                   sb->st_ino != dsb.st_ino)
+                       continue;
+               (void)closedir(dp);
+               return 0;
+       }
+       (void)closedir(dp);
+       /*
+        * XXX: Documented by TOG to return EBADF or ENOTTY only; neither are
+        * applicable here.
+        */
+       errno = ENOENT;
+       return -1;
+}
+
+char *
+ttyname(int fd)
+{
+       static char buf[MAXPATHLEN];
+       int rv;
+       
+       rv = ttyname_r(fd, buf, sizeof(buf));
+       if (rv != 0) {
+               errno = rv;
+               return NULL;
+       }
+       return buf;
+}
diff --git a/lib/nbsd_libc/gen/ttyslot.c b/lib/nbsd_libc/gen/ttyslot.c
new file mode 100644 (file)
index 0000000..33ac454
--- /dev/null
@@ -0,0 +1,96 @@
+/*     $NetBSD: ttyslot.c,v 1.13 2009/01/11 02:46:27 christos Exp $    */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ttyslot.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: ttyslot.c,v 1.13 2009/01/11 02:46:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <ttyent.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+
+#ifdef __weak_alias
+__weak_alias(ttyslot,_ttyslot)
+#endif
+
+int
+ttyslot(void)
+{
+       struct ttyent *ttyp;
+       int slot = 0, ispty = 0;
+       char *p;
+       int cnt;
+       char *name;
+       struct ptmget ptm;
+
+       setttyent();
+       for (cnt = 0; cnt < 3; ++cnt) {
+               if (ioctl(cnt, TIOCPTSNAME, &ptm) != -1) {
+                       ispty = 1;
+                       name = ptm.sn;
+               } else if ((name = ttyname(cnt)) != NULL) {
+                       ispty = 0;
+               } else
+                       continue;
+
+               if ((p = strstr(name, "/pts/")) != NULL)
+                       ++p;
+               else if ((p = strrchr(name, '/')) != NULL)
+                       ++p;
+               else
+                       p = name;
+
+               for (slot = 1; (ttyp = getttyent()) != NULL; ++slot)
+                       if (!strcmp(ttyp->ty_name, p)) {
+                               endttyent();
+                               return slot;
+                       }
+               break;
+       }
+       endttyent();
+       if (ispty) {
+               struct stat st;
+               if (fstat(cnt, &st) == -1)
+                       return 0;
+               return slot + (int)minor(st.st_rdev) + 1;
+       }
+       return 0;
+}
diff --git a/lib/nbsd_libc/gen/ualarm.3 b/lib/nbsd_libc/gen/ualarm.3
new file mode 100644 (file)
index 0000000..7e5b7d3
--- /dev/null
@@ -0,0 +1,108 @@
+.\"    $NetBSD: ualarm.3,v 1.18 2010/04/29 06:07:35 jruoho Exp $
+.\"
+.\" Copyright (c) 1986, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)ualarm.3   8.2 (Berkeley) 4/19/94
+.\"
+.Dd April 29, 2010
+.Dt UALARM 3
+.Os
+.Sh NAME
+.Nm ualarm
+.Nd schedule signal after specified time
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft useconds_t
+.Fn ualarm "useconds_t microseconds" "useconds_t interval"
+.Sh DESCRIPTION
+.Bf -symbolic
+This is a simplified interface to
+.Xr setitimer 2 .
+.Ef
+.Pp
+The
+.Fn ualarm
+function
+waits a count of
+.Ar microseconds
+before asserting the terminating signal
+.Dv SIGALRM .
+System activity or time used in processing the call may cause a slight
+delay.
+.Pp
+If the
+.Fa interval
+argument is non-zero, the
+.Dv SIGALRM
+signal will be sent
+to the process every
+.Fa interval
+microseconds after the timer expires (e.g. after
+.Fa microseconds
+microseconds have passed).
+.Sh RETURN VALUES
+When the signal has successfully been caught,
+.Fn ualarm
+returns the amount of time left on the clock.
+The maximum number of
+.Ar microseconds
+allowed
+is 2147483647.
+If there is an error setting the timer,
+.Fn ualarm
+returns ((useconds_t) -1).
+.Sh SEE ALSO
+.Xr getitimer 2 ,
+.Xr setitimer 2 ,
+.Xr sigaction 2 ,
+.Xr sigsuspend 2 ,
+.Xr alarm 3 ,
+.Xr signal 3 ,
+.Xr sigvec 3 ,
+.Xr sleep 3 ,
+.Xr usleep 3
+.Sh STANDARDS
+The
+.Fn ualarm
+functions conforms to
+.St -xpg4.2
+and
+.St -p1003.1-2001 .
+The latter standard marked
+.Fn ualarm
+as obsolescent and a later revision,
+.St -p1003.1-2008 ,
+removed the specification of
+.Fn ualarm .
+.Sh HISTORY
+The
+.Fn ualarm
+function appeared in
+.Bx 4.3 .
diff --git a/lib/nbsd_libc/gen/ualarm.c b/lib/nbsd_libc/gen/ualarm.c
new file mode 100644 (file)
index 0000000..2da8670
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: ualarm.c,v 1.10 2003/08/07 16:42:58 agc Exp $  */
+
+/*
+ * Copyright (c) 1985, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ualarm.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: ualarm.c,v 1.10 2003/08/07 16:42:58 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/time.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(ualarm,_ualarm)
+#endif
+
+#define        USPS    1000000         /* # of microseconds in a second */
+
+/*
+ * Generate a SIGALRM signal in ``usecs'' microseconds.
+ * If ``reload'' is non-zero, keep generating SIGALRM
+ * every ``reload'' microseconds after the first signal.
+ */
+useconds_t
+ualarm(usecs, reload)
+       useconds_t usecs;
+       useconds_t reload;
+{
+       struct itimerval new, old;
+
+       new.it_interval.tv_usec = reload % USPS;
+       new.it_interval.tv_sec = reload / USPS;
+       
+       new.it_value.tv_usec = usecs % USPS;
+       new.it_value.tv_sec = usecs / USPS;
+
+       if (setitimer(ITIMER_REAL, &new, &old) == 0)
+               return (useconds_t)(old.it_value.tv_sec * USPS +
+                   old.it_value.tv_usec);
+
+       return (useconds_t)-1;
+}
diff --git a/lib/nbsd_libc/gen/ulimit.3 b/lib/nbsd_libc/gen/ulimit.3
new file mode 100644 (file)
index 0000000..5312050
--- /dev/null
@@ -0,0 +1,119 @@
+.\"    $NetBSD: ulimit.3,v 1.9 2010/04/30 05:09:23 jruoho Exp $
+.\"
+.\" Copyright (c) 1999 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 30, 2010
+.Dt ULIMIT 3
+.Os
+.Sh NAME
+.Nm ulimit
+.Nd get and set process limits
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ulimit.h
+.Ft long int
+.Fn ulimit "int cmd" ...
+.Sh DESCRIPTION
+The
+.Fn ulimit
+function provides a method to query or alter resource limits of the calling
+process.
+The method to be performed is specified by the
+.Fa cmd
+argument; possible values are:
+.Bl -tag -width UL_GETFSIZEXX
+.It Li UL_GETFSIZE
+Return the soft file size limit of the process.
+The value returned is in units of 512-byte blocks.
+If the result cannot be represented in an object of type
+.Fa long int ,
+the result is unspecified.
+.It Li UL_SETFSIZE
+Set the hard and soft file size limits of the process to the value of the
+second argument passed, which is in units of 512-byte blocks, and which is
+expected to be of type
+.Fa long int .
+The new file size limit of the process is returned.
+Any process may decrease the limit, but raising it is only permitted if
+the caller is the super-user.
+.El
+.Pp
+If successful, the
+.Fn ulimit
+function will not change the setting of
+.Va errno .
+.Sh RETURN VALUES
+If successful, the
+.Fn ulimit
+function returns the value of the requested limit.
+Otherwise, it returns \-1, sets
+.Va errno
+to indicate an error, and the limit is not changed.
+Therefore, to detect an error condition applications should set
+.Va errno
+to 0, call
+.Fn ulimit ,
+and check if \-1 is returned and
+.Va errno
+is non-zero.
+.Sh ERRORS
+The
+.Fn ulimit
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa cmd
+argument is not valid.
+.It Bq Er EPERM
+It was attempted to increase a limit, and the caller is not the super-user.
+.El
+.Sh SEE ALSO
+.Xr getrlimit 2 ,
+.Xr setrlimit 2
+.Sh STANDARDS
+The
+.Fn ulimit
+function conforms to
+.St -xsh5
+and
+.St -p1003.1-2001 .
+It was marked as obsolete in the
+.St -p1003.1-2008
+revision, which recommended the use of
+.Xr getrlimit 2
+and
+.Xr setrlimit 2
+instead, noting that because
+.Fn ulimit
+uses the type
+.Vt long
+rather than
+.Vt rlim_t ,
+it may not be sufficient for file sizes on many current systems.
diff --git a/lib/nbsd_libc/gen/ulimit.c b/lib/nbsd_libc/gen/ulimit.c
new file mode 100644 (file)
index 0000000..ba61a22
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: ulimit.c,v 1.3 2008/04/28 20:22:59 martin Exp $        */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ulimit.c,v 1.3 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/resource.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <ulimit.h>
+
+long int
+ulimit(int cmd, ...)
+{
+       va_list ap;
+       struct rlimit rlimit;
+       long int new_limit, result;
+
+       va_start(ap, cmd);
+
+       result = -1L;
+       switch (cmd) {
+       case UL_GETFSIZE:
+               if (getrlimit(RLIMIT_FSIZE, &rlimit) == 0)
+                       result = (long int)(rlimit.rlim_cur / 512);
+               break;
+       case UL_SETFSIZE:
+               new_limit = va_arg(ap, long int);
+               rlimit.rlim_cur = rlimit.rlim_max = (rlim_t)new_limit * 512;
+               if (setrlimit(RLIMIT_FSIZE, &rlimit) == 0)
+                       result = new_limit;
+               break;
+       default:
+               errno = EINVAL;
+       }
+
+       va_end(ap);
+
+       return (result);
+}
diff --git a/lib/nbsd_libc/gen/uname.3 b/lib/nbsd_libc/gen/uname.3
new file mode 100644 (file)
index 0000000..33a2c0c
--- /dev/null
@@ -0,0 +1,93 @@
+.\"    $NetBSD: uname.3,v 1.11 2010/04/27 15:16:28 jruoho Exp $
+.\"
+.\" Copyright (c) 1994
+.\"    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.
+.\" 3. 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.
+.\"
+.\"    @(#)uname.3     8.1 (Berkeley) 1/4/94
+.\"
+.Dd April 27, 2010
+.Dt UNAME 3
+.Os
+.Sh NAME
+.Nm uname
+.Nd get system identification
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/utsname.h
+.Ft int
+.Fn uname "struct utsname *name"
+.Sh DESCRIPTION
+The
+.Fn uname
+function stores nul-terminated strings of information identifying
+the current system into the structure referenced by
+.Fa name .
+.Pp
+The
+.Li utsname
+structure is defined in the
+.In sys/utsname.h
+header file, and contains the following members:
+.Bl -tag -width nodenameXXXX -offset indent
+.It Va sysname
+Name of the operating system implementation.
+.It Va nodename
+Network name of this machine.
+.It Va release
+Release level of the operating system.
+.It Va version
+Version level of the operating system.
+.It Va machine
+Machine hardware platform.
+.El
+.Sh RETURN VALUES
+If
+.Nm uname
+is successful, 0 is returned, otherwise, \-1 is returned and
+.Va errno
+is set appropriately.
+.Sh ERRORS
+The
+.Fn uname
+function may fail and set
+.Va errno
+for any of the errors specified for the library functions
+.Xr sysctl 3 .
+.Sh SEE ALSO
+.Xr uname 1 ,
+.Xr sysctl 3
+.Sh STANDARDS
+The
+.Fn uname
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+The
+.Nm uname
+function first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/gen/uname.c b/lib/nbsd_libc/gen/uname.c
new file mode 100644 (file)
index 0000000..4aa704b
--- /dev/null
@@ -0,0 +1,106 @@
+/*     $NetBSD: uname.c,v 1.10 2007/01/15 22:26:35 cbiere Exp $        */
+
+/*-
+ * Copyright (c) 1994
+ *     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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)uname.c    8.1 (Berkeley) 1/4/94";
+#else
+__RCSID("$NetBSD: uname.c,v 1.10 2007/01/15 22:26:35 cbiere Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/sysctl.h>
+#include <sys/utsname.h>
+
+#include <assert.h>
+#include <errno.h>
+
+#ifdef __weak_alias
+__weak_alias(uname,_uname)
+#endif
+
+int
+uname(name)
+       struct utsname *name;
+{
+       int mib[2];
+       size_t len;
+       char *p;
+
+       _DIAGASSERT(name != NULL);
+
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_OSTYPE;
+       len = sizeof(name->sysname);
+       if (sysctl(mib, 2, &name->sysname, &len, NULL, 0) == -1)
+               goto error;
+
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_HOSTNAME;
+       len = sizeof(name->nodename);
+       if (sysctl(mib, 2, &name->nodename, &len, NULL, 0) == -1)
+               goto error;
+
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_OSRELEASE;
+       len = sizeof(name->release);
+       if (sysctl(mib, 2, &name->release, &len, NULL, 0) == -1)
+               goto error;
+
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_VERSION;
+       len = sizeof(name->version);
+       if (sysctl(mib, 2, &name->version, &len, NULL, 0) == -1)
+               goto error;
+
+       /* The version may have newlines in it, turn them into spaces. */
+       for (p = name->version; len--; ++p) {
+               if (*p == '\n' || *p == '\t') {
+                       if (len > 1)
+                               *p = ' ';
+                       else
+                               *p = '\0';
+               }
+       }
+
+       mib[0] = CTL_HW;
+       mib[1] = HW_MACHINE;
+       len = sizeof(name->machine);
+       if (sysctl(mib, 2, &name->machine, &len, NULL, 0) == -1)
+               goto error;
+       return (0);
+
+error:
+       return (-1);
+}
diff --git a/lib/nbsd_libc/gen/unvis.3 b/lib/nbsd_libc/gen/unvis.3
new file mode 100644 (file)
index 0000000..3f6fdc5
--- /dev/null
@@ -0,0 +1,208 @@
+.\"    $NetBSD: unvis.3,v 1.20 2010/11/28 01:28:21 wiz Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)unvis.3    8.2 (Berkeley) 12/11/93
+.\"
+.Dd November 27, 2010
+.Dt UNVIS 3
+.Os
+.Sh NAME
+.Nm unvis ,
+.Nm strunvis
+.Nd decode a visual representation of characters
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In vis.h
+.Ft int
+.Fn unvis "char *cp" "int c" "int *astate" "int flag"
+.Ft int
+.Fn strunvis "char *dst" "const char *src"
+.Ft int
+.Fn strunvisx "char *dst" "const char *src" "int flag"
+.Sh DESCRIPTION
+The
+.Fn unvis ,
+.Fn strunvis
+and
+.Fn strunvisx
+functions
+are used to decode a visual representation of characters, as produced
+by the
+.Xr vis 3
+function, back into
+the original form.
+.Pp
+The
+.Fn unvis
+function is called with successive characters in
+.Ar c
+until a valid sequence is recognized, at which time the decoded
+character is available at the character pointed to by
+.Ar cp .
+.Pp
+The
+.Fn strunvis
+function decodes the characters pointed to by
+.Ar src
+into the buffer pointed to by
+.Ar dst .
+The
+.Fn strunvis
+function simply copies
+.Ar src
+to
+.Ar dst ,
+decoding any escape sequences along the way,
+and returns the number of characters placed into
+.Ar dst ,
+or \-1 if an
+invalid escape sequence was detected.
+The size of
+.Ar dst
+should be equal to the size of
+.Ar src
+(that is, no expansion takes place during decoding).
+.Pp
+The
+.Fn strunvisx
+function does the same as the
+.Fn strunvis
+function,
+but it allows you to add a flag that specifies the style the string
+.Ar src
+is encoded with.
+Currently, the supported flags are:
+.Dv VIS_HTTPSTYLE
+and
+.Dv VIS_MIMESTYLE .
+.Pp
+The
+.Fn unvis
+function implements a state machine that can be used to decode an
+arbitrary stream of bytes.
+All state associated with the bytes being decoded is stored outside the
+.Fn unvis
+function (that is, a pointer to the state is passed in), so
+calls decoding different streams can be freely intermixed.
+To start decoding a stream of bytes, first initialize an integer to zero.
+Call
+.Fn unvis
+with each successive byte, along with a pointer
+to this integer, and a pointer to a destination character.
+The
+.Fn unvis
+function has several return codes that must be handled properly.
+They are:
+.Bl -tag -width UNVIS_VALIDPUSH
+.It Li \&0 (zero)
+Another character is necessary; nothing has been recognized yet.
+.It Dv UNVIS_VALID
+A valid character has been recognized and is available at the location
+pointed to by cp.
+.It Dv UNVIS_VALIDPUSH
+A valid character has been recognized and is available at the location
+pointed to by cp; however, the character currently passed in should
+be passed in again.
+.It Dv UNVIS_NOCHAR
+A valid sequence was detected, but no character was produced.
+This return code is necessary to indicate a logical break between characters.
+.It Dv UNVIS_SYNBAD
+An invalid escape sequence was detected, or the decoder is in an unknown state.
+The decoder is placed into the starting state.
+.El
+.Pp
+When all bytes in the stream have been processed, call
+.Fn unvis
+one more time with flag set to
+.Dv UNVIS_END
+to extract any remaining character (the character passed in is ignored).
+.Pp
+The
+.Ar flag
+argument is also used to specify the encoding style of the source.
+If set to
+.Dv VIS_HTTPSTYLE
+or
+.Dv VIS_HTTP1808 ,
+.Fn unvis
+will decode URI strings as specified in RFC 1808.
+If set to
+.Dv VIS_HTTP1866 ,
+.Fn unvis
+will decode URI strings as specified in RFC 1866.
+If set to
+.Dv VIS_MIMESTYLE ,
+.Fn unvis
+will decode MIME Quoted-Printable strings as specified in RFC 2045.
+If set to
+.Dv VIS_NOESCAPE ,
+.Fn unvis
+will not decode \e quoted characters.
+.Pp
+The following code fragment illustrates a proper use of
+.Fn unvis .
+.Bd -literal -offset indent
+int state = 0;
+char out;
+
+while ((ch = getchar()) != EOF) {
+again:
+       switch(unvis(\*[Am]out, ch, \*[Am]state, 0)) {
+       case 0:
+       case UNVIS_NOCHAR:
+               break;
+       case UNVIS_VALID:
+               (void)putchar(out);
+               break;
+       case UNVIS_VALIDPUSH:
+               (void)putchar(out);
+               goto again;
+       case UNVIS_SYNBAD:
+               errx(EXIT_FAILURE, "Bad character sequence!");
+       }
+}
+if (unvis(\*[Am]out, '\e0', \*[Am]state, UNVIS_END) == UNVIS_VALID)
+       (void)putchar(out);
+.Ed
+.Sh SEE ALSO
+.Xr unvis 1 ,
+.Xr vis 1 ,
+.Xr vis 3
+.Rs
+.%A R. Fielding
+.%T Relative Uniform Resource Locators
+.%O RFC1808
+.Re
+.Sh HISTORY
+The
+.Fn unvis
+function
+first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/gen/unvis.c b/lib/nbsd_libc/gen/unvis.c
new file mode 100644 (file)
index 0000000..13bc869
--- /dev/null
@@ -0,0 +1,514 @@
+/*     $NetBSD: unvis.c,v 1.32 2010/11/27 21:22:11 christos Exp $      */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)unvis.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: unvis.c,v 1.32 2010/11/27 21:22:11 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <vis.h>
+
+#ifdef __weak_alias
+__weak_alias(strunvis,_strunvis)
+#endif
+
+#if !HAVE_VIS
+/*
+ * decode driven by state machine
+ */
+#define        S_GROUND        0       /* haven't seen escape char */
+#define        S_START         1       /* start decoding special sequence */
+#define        S_META          2       /* metachar started (M) */
+#define        S_META1         3       /* metachar more, regular char (-) */
+#define        S_CTRL          4       /* control char started (^) */
+#define        S_OCTAL2        5       /* octal digit 2 */
+#define        S_OCTAL3        6       /* octal digit 3 */
+#define        S_HEX1          7       /* http hex digit */
+#define        S_HEX2          8       /* http hex digit 2 */
+#define S_MIME1                9       /* mime hex digit 1 */
+#define S_MIME2                10      /* mime hex digit 2 */
+#define S_EATCRNL      11      /* mime eating CRNL */
+#define S_AMP          12      /* seen & */
+#define S_NUMBER       13      /* collecting number */
+#define S_STRING       14      /* collecting string */
+
+#define        isoctal(c)      (((u_char)(c)) >= '0' && ((u_char)(c)) <= '7')
+#define xtod(c)                (isdigit(c) ? (c - '0') : ((tolower(c) - 'a') + 10))
+#define XTOD(c)                (isdigit(c) ? (c - '0') : ((c - 'A') + 10))
+
+/*
+ * RFC 1866
+ */
+static const struct nv {
+       const char *name;
+       uint8_t value;
+} nv[] = {
+       { "AElig",      198 }, /* capital AE diphthong (ligature)  */
+       { "Aacute",     193 }, /* capital A, acute accent  */
+       { "Acirc",      194 }, /* capital A, circumflex accent  */
+       { "Agrave",     192 }, /* capital A, grave accent  */
+       { "Aring",      197 }, /* capital A, ring  */
+       { "Atilde",     195 }, /* capital A, tilde  */
+       { "Auml",       196 }, /* capital A, dieresis or umlaut mark  */
+       { "Ccedil",     199 }, /* capital C, cedilla  */
+       { "ETH",        208 }, /* capital Eth, Icelandic  */
+       { "Eacute",     201 }, /* capital E, acute accent  */
+       { "Ecirc",      202 }, /* capital E, circumflex accent  */
+       { "Egrave",     200 }, /* capital E, grave accent  */
+       { "Euml",       203 }, /* capital E, dieresis or umlaut mark  */
+       { "Iacute",     205 }, /* capital I, acute accent  */
+       { "Icirc",      206 }, /* capital I, circumflex accent  */
+       { "Igrave",     204 }, /* capital I, grave accent  */
+       { "Iuml",       207 }, /* capital I, dieresis or umlaut mark  */
+       { "Ntilde",     209 }, /* capital N, tilde  */
+       { "Oacute",     211 }, /* capital O, acute accent  */
+       { "Ocirc",      212 }, /* capital O, circumflex accent  */
+       { "Ograve",     210 }, /* capital O, grave accent  */
+       { "Oslash",     216 }, /* capital O, slash  */
+       { "Otilde",     213 }, /* capital O, tilde  */
+       { "Ouml",       214 }, /* capital O, dieresis or umlaut mark  */
+       { "THORN",      222 }, /* capital THORN, Icelandic  */
+       { "Uacute",     218 }, /* capital U, acute accent  */
+       { "Ucirc",      219 }, /* capital U, circumflex accent  */
+       { "Ugrave",     217 }, /* capital U, grave accent  */
+       { "Uuml",       220 }, /* capital U, dieresis or umlaut mark  */
+       { "Yacute",     221 }, /* capital Y, acute accent  */
+       { "aacute",     225 }, /* small a, acute accent  */
+       { "acirc",      226 }, /* small a, circumflex accent  */
+       { "acute",      180 }, /* acute accent  */
+       { "aelig",      230 }, /* small ae diphthong (ligature)  */
+       { "agrave",     224 }, /* small a, grave accent  */
+       { "amp",         38 }, /* ampersand  */
+       { "aring",      229 }, /* small a, ring  */
+       { "atilde",     227 }, /* small a, tilde  */
+       { "auml",       228 }, /* small a, dieresis or umlaut mark  */
+       { "brvbar",     166 }, /* broken (vertical) bar  */
+       { "ccedil",     231 }, /* small c, cedilla  */
+       { "cedil",      184 }, /* cedilla  */
+       { "cent",       162 }, /* cent sign  */
+       { "copy",       169 }, /* copyright sign  */
+       { "curren",     164 }, /* general currency sign  */
+       { "deg",        176 }, /* degree sign  */
+       { "divide",     247 }, /* divide sign  */
+       { "eacute",     233 }, /* small e, acute accent  */
+       { "ecirc",      234 }, /* small e, circumflex accent  */
+       { "egrave",     232 }, /* small e, grave accent  */
+       { "eth",        240 }, /* small eth, Icelandic  */
+       { "euml",       235 }, /* small e, dieresis or umlaut mark  */
+       { "frac12",     189 }, /* fraction one-half  */
+       { "frac14",     188 }, /* fraction one-quarter  */
+       { "frac34",     190 }, /* fraction three-quarters  */
+       { "gt",          62 }, /* greater than  */
+       { "iacute",     237 }, /* small i, acute accent  */
+       { "icirc",      238 }, /* small i, circumflex accent  */
+       { "iexcl",      161 }, /* inverted exclamation mark  */
+       { "igrave",     236 }, /* small i, grave accent  */
+       { "iquest",     191 }, /* inverted question mark  */
+       { "iuml",       239 }, /* small i, dieresis or umlaut mark  */
+       { "laquo",      171 }, /* angle quotation mark, left  */
+       { "lt",          60 }, /* less than  */
+       { "macr",       175 }, /* macron  */
+       { "micro",      181 }, /* micro sign  */
+       { "middot",     183 }, /* middle dot  */
+       { "nbsp",       160 }, /* no-break space  */
+       { "not",        172 }, /* not sign  */
+       { "ntilde",     241 }, /* small n, tilde  */
+       { "oacute",     243 }, /* small o, acute accent  */
+       { "ocirc",      244 }, /* small o, circumflex accent  */
+       { "ograve",     242 }, /* small o, grave accent  */
+       { "ordf",       170 }, /* ordinal indicator, feminine  */
+       { "ordm",       186 }, /* ordinal indicator, masculine  */
+       { "oslash",     248 }, /* small o, slash  */
+       { "otilde",     245 }, /* small o, tilde  */
+       { "ouml",       246 }, /* small o, dieresis or umlaut mark  */
+       { "para",       182 }, /* pilcrow (paragraph sign)  */
+       { "plusmn",     177 }, /* plus-or-minus sign  */
+       { "pound",      163 }, /* pound sterling sign  */
+       { "quot",        34 }, /* double quote  */
+       { "raquo",      187 }, /* angle quotation mark, right  */
+       { "reg",        174 }, /* registered sign  */
+       { "sect",       167 }, /* section sign  */
+       { "shy",        173 }, /* soft hyphen  */
+       { "sup1",       185 }, /* superscript one  */
+       { "sup2",       178 }, /* superscript two  */
+       { "sup3",       179 }, /* superscript three  */
+       { "szlig",      223 }, /* small sharp s, German (sz ligature)  */
+       { "thorn",      254 }, /* small thorn, Icelandic  */
+       { "times",      215 }, /* multiply sign  */
+       { "uacute",     250 }, /* small u, acute accent  */
+       { "ucirc",      251 }, /* small u, circumflex accent  */
+       { "ugrave",     249 }, /* small u, grave accent  */
+       { "uml",        168 }, /* umlaut (dieresis)  */
+       { "uuml",       252 }, /* small u, dieresis or umlaut mark  */
+       { "yacute",     253 }, /* small y, acute accent  */
+       { "yen",        165 }, /* yen sign  */
+       { "yuml",       255 }, /* small y, dieresis or umlaut mark  */
+};
+
+/*
+ * unvis - decode characters previously encoded by vis
+ */
+int
+unvis(char *cp, int c, int *astate, int flag)
+{
+       unsigned char uc = (unsigned char)c;
+       unsigned char st, ia, is, lc;
+
+/*
+ * Bottom 8 bits of astate hold the state machine state.
+ * Top 8 bits hold the current character in the http 1866 nv string decoding
+ */
+#define GS(a)          ((a) & 0xff)
+#define SS(a, b)       (((uint32_t)(a) << 24) | (b))
+#define GI(a)          ((uint32_t)(a) >> 24)
+
+       _DIAGASSERT(cp != NULL);
+       _DIAGASSERT(astate != NULL);
+       st = GS(*astate);
+
+       if (flag & UNVIS_END) {
+               switch (st) {
+               case S_OCTAL2:
+               case S_OCTAL3:
+               case S_HEX2:
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_VALID;
+               case S_GROUND:
+                       return UNVIS_NOCHAR;
+               default:
+                       return UNVIS_SYNBAD;
+               }
+       }
+
+       switch (st) {
+
+       case S_GROUND:
+               *cp = 0;
+               if ((flag & VIS_NOESCAPE) == 0 && c == '\\') {
+                       *astate = SS(0, S_START);
+                       return UNVIS_NOCHAR;
+               }
+               if ((flag & VIS_HTTP1808) && c == '%') {
+                       *astate = SS(0, S_HEX1);
+                       return UNVIS_NOCHAR;
+               }
+               if ((flag & VIS_HTTP1866) && c == '&') {
+                       *astate = SS(0, S_AMP);
+                       return UNVIS_NOCHAR;
+               }
+               if ((flag & VIS_MIMESTYLE) && c == '=') {
+                       *astate = SS(0, S_MIME1);
+                       return UNVIS_NOCHAR;
+               }
+               *cp = c;
+               return UNVIS_VALID;
+
+       case S_START:
+               switch(c) {
+               case '\\':
+                       *cp = c;
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_VALID;
+               case '0': case '1': case '2': case '3':
+               case '4': case '5': case '6': case '7':
+                       *cp = (c - '0');
+                       *astate = SS(0, S_OCTAL2);
+                       return UNVIS_NOCHAR;
+               case 'M':
+                       *cp = (char)0200;
+                       *astate = SS(0, S_META);
+                       return UNVIS_NOCHAR;
+               case '^':
+                       *astate = SS(0, S_CTRL);
+                       return UNVIS_NOCHAR;
+               case 'n':
+                       *cp = '\n';
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_VALID;
+               case 'r':
+                       *cp = '\r';
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_VALID;
+               case 'b':
+                       *cp = '\b';
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_VALID;
+               case 'a':
+                       *cp = '\007';
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_VALID;
+               case 'v':
+                       *cp = '\v';
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_VALID;
+               case 't':
+                       *cp = '\t';
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_VALID;
+               case 'f':
+                       *cp = '\f';
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_VALID;
+               case 's':
+                       *cp = ' ';
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_VALID;
+               case 'E':
+                       *cp = '\033';
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_VALID;
+               case '\n':
+                       /*
+                        * hidden newline
+                        */
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_NOCHAR;
+               case '$':
+                       /*
+                        * hidden marker
+                        */
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_NOCHAR;
+               }
+               goto bad;
+
+       case S_META:
+               if (c == '-')
+                       *astate = SS(0, S_META1);
+               else if (c == '^')
+                       *astate = SS(0, S_CTRL);
+               else 
+                       goto bad;
+               return UNVIS_NOCHAR;
+
+       case S_META1:
+               *astate = SS(0, S_GROUND);
+               *cp |= c;
+               return UNVIS_VALID;
+
+       case S_CTRL:
+               if (c == '?')
+                       *cp |= 0177;
+               else
+                       *cp |= c & 037;
+               *astate = SS(0, S_GROUND);
+               return UNVIS_VALID;
+
+       case S_OCTAL2:  /* second possible octal digit */
+               if (isoctal(uc)) {
+                       /*
+                        * yes - and maybe a third
+                        */
+                       *cp = (*cp << 3) + (c - '0');
+                       *astate = SS(0, S_OCTAL3);
+                       return UNVIS_NOCHAR;
+               }
+               /*
+                * no - done with current sequence, push back passed char
+                */
+               *astate = SS(0, S_GROUND);
+               return UNVIS_VALIDPUSH;
+
+       case S_OCTAL3:  /* third possible octal digit */
+               *astate = SS(0, S_GROUND);
+               if (isoctal(uc)) {
+                       *cp = (*cp << 3) + (c - '0');
+                       return UNVIS_VALID;
+               }
+               /*
+                * we were done, push back passed char
+                */
+               return UNVIS_VALIDPUSH;
+
+       case S_HEX1:
+               if (isxdigit(uc)) {
+                       *cp = xtod(uc);
+                       *astate = SS(0, S_HEX2);
+                       return UNVIS_NOCHAR;
+               }
+               /*
+                * no - done with current sequence, push back passed char
+                */
+               *astate = SS(0, S_GROUND);
+               return UNVIS_VALIDPUSH;
+
+       case S_HEX2:
+               *astate = S_GROUND;
+               if (isxdigit(uc)) {
+                       *cp = xtod(uc) | (*cp << 4);
+                       return UNVIS_VALID;
+               }
+               return UNVIS_VALIDPUSH;
+
+       case S_MIME1:
+               if (uc == '\n' || uc == '\r') {
+                       *astate = SS(0, S_EATCRNL);
+                       return UNVIS_NOCHAR;
+               }
+               if (isxdigit(uc) && (isdigit(uc) || isupper(uc))) {
+                       *cp = XTOD(uc);
+                       *astate = SS(0, S_MIME2);
+                       return UNVIS_NOCHAR;
+               }
+               goto bad;
+
+       case S_MIME2:
+               if (isxdigit(uc) && (isdigit(uc) || isupper(uc))) {
+                       *astate = SS(0, S_GROUND);
+                       *cp = XTOD(uc) | (*cp << 4);
+                       return UNVIS_VALID;
+               }
+               goto bad;
+
+       case S_EATCRNL:
+               switch (uc) {
+               case '\r':
+               case '\n':
+                       return UNVIS_NOCHAR;
+               case '=':
+                       *astate = SS(0, S_MIME1);
+                       return UNVIS_NOCHAR;
+               default:
+                       *cp = uc;
+                       *astate = SS(0, S_GROUND);
+                       return UNVIS_VALID;
+               }
+
+       case S_AMP:
+               *cp = 0;
+               if (uc == '#') {
+                       *astate = SS(0, S_NUMBER);
+                       return UNVIS_NOCHAR;
+               }
+               *astate = SS(0, S_STRING);
+               /*FALLTHROUGH*/
+
+       case S_STRING:
+               ia = *cp;               /* index in the array */
+               is = GI(*astate);       /* index in the string */
+               lc = is == 0 ? 0 : nv[ia].name[is - 1]; /* last character */
+
+               if (uc == ';')
+                       uc = '\0';
+
+               for (; ia < __arraycount(nv); ia++) {
+                       if (is != 0 && nv[ia].name[is - 1] != lc)
+                               goto bad;
+                       if (nv[ia].name[is] == uc)
+                               break;
+               }
+
+               if (*cp == __arraycount(nv))
+                       goto bad;
+
+               if (uc != 0) {
+                       *cp = ia;
+                       *astate = SS(is + 1, S_STRING);
+                       return UNVIS_NOCHAR;
+               }
+
+               *cp = nv[ia].value;
+               *astate = SS(0, S_GROUND);
+               return UNVIS_VALID;
+
+       case S_NUMBER:
+               if (uc == ';')
+                       return UNVIS_VALID;
+               if (!isdigit(uc))
+                       goto bad;
+               *cp += (*cp * 10) + uc - '0';
+               return UNVIS_NOCHAR;
+
+       default:
+       bad:
+               /*
+                * decoder in unknown state - (probably uninitialized)
+                */
+               *astate = SS(0, S_GROUND);
+               return UNVIS_SYNBAD;
+       }
+}
+
+/*
+ * strunvis - decode src into dst
+ *
+ *     Number of chars decoded into dst is returned, -1 on error.
+ *     Dst is null terminated.
+ */
+
+int
+strunvisx(char *dst, const char *src, int flag)
+{
+       char c;
+       char *start = dst;
+       int state = 0;
+
+       _DIAGASSERT(src != NULL);
+       _DIAGASSERT(dst != NULL);
+
+       while ((c = *src++) != '\0') {
+ again:
+               switch (unvis(dst, c, &state, flag)) {
+               case UNVIS_VALID:
+                       dst++;
+                       break;
+               case UNVIS_VALIDPUSH:
+                       dst++;
+                       goto again;
+               case 0:
+               case UNVIS_NOCHAR:
+                       break;
+               default:
+                       return (-1);
+               }
+       }
+       if (unvis(dst, c, &state, UNVIS_END) == UNVIS_VALID)
+               dst++;
+       *dst = '\0';
+       return (int)(dst - start);
+}
+
+int
+strunvis(char *dst, const char *src)
+{
+       return strunvisx(dst, src, 0);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/usleep.3 b/lib/nbsd_libc/gen/usleep.3
new file mode 100644 (file)
index 0000000..12ae2e2
--- /dev/null
@@ -0,0 +1,104 @@
+.\"    $NetBSD: usleep.3,v 1.19 2010/04/29 17:29:56 jruoho Exp $
+.\"
+.\" Copyright (c) 1986, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)usleep.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 29, 2010
+.Dt USLEEP 3
+.Os
+.Sh NAME
+.Nm usleep
+.Nd suspend execution for interval of microseconds
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn usleep "useconds_t microseconds"
+.Sh DESCRIPTION
+The
+.Fn usleep
+function
+suspends execution of the calling process
+until either the number of microseconds specified by
+.Fa microseconds
+have elapsed or a signal is delivered to the calling process and its
+action is to invoke a signal catching function or to terminate the
+process.
+The suspension time may be longer than requested due to the
+scheduling of other activity by the system.
+.Pp
+The
+.Fa microseconds
+argument must be less than 1,000,000.
+If the value of
+.Fa microseconds
+is 0, then the call has no effect.
+.Sh RETURN VALUES
+On successful completion,
+.Fn usleep
+returns 0.
+Otherwise, it returns \-1 and sets
+.Va errno
+to indicate the error.
+.Sh ERRORS
+The
+.Fn usleep
+function may fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa microseconds
+interval specified 1,000,000 or more microseconds.
+.El
+.Sh SEE ALSO
+.Xr nanosleep 2 ,
+.Xr sleep 3
+.Sh STANDARDS
+The
+.Fn usleep
+function conforms to
+.St -xpg4.2 .
+It later appeared in the
+.Tn POSIX
+standard, but in
+.St -p1003.1-2004
+it was marked as legacy and the use of
+.Xr nanosleep 2
+was recommended instead.
+The
+.St -p1003.1-2008
+revision removed
+.Fn usleep
+from the specification.
+.Sh HISTORY
+The
+.Fn usleep
+function appeared in
+.Bx 4.3 .
diff --git a/lib/nbsd_libc/gen/usleep.c b/lib/nbsd_libc/gen/usleep.c
new file mode 100644 (file)
index 0000000..8722d5d
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: usleep.c,v 1.19 2008/04/28 20:22:59 martin Exp $       */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: usleep.c,v 1.19 2008/04/28 20:22:59 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <errno.h>
+#include <time.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(usleep,_usleep)
+#endif
+
+int
+usleep(useconds)
+       useconds_t useconds;
+{
+       struct timespec ts;
+
+       if (useconds == 0)
+               return (0);
+
+       if (useconds >= 1000000) {
+               errno = EINVAL;
+               return (-1);
+       }
+
+       ts.tv_sec  = 0;
+       ts.tv_nsec = useconds * 1000;
+
+       nanosleep(&ts, NULL);
+
+       return (0);
+}
diff --git a/lib/nbsd_libc/gen/utime.3 b/lib/nbsd_libc/gen/utime.3
new file mode 100644 (file)
index 0000000..2f2eb6e
--- /dev/null
@@ -0,0 +1,145 @@
+.\"    $NetBSD: utime.3,v 1.21 2010/04/29 17:07:00 jruoho Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)utime.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 29, 2010
+.Dt UTIME 3
+.Os
+.Sh NAME
+.Nm utime
+.Nd set file times
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In utime.h
+.Ft int
+.Fn utime "const char *file" "const struct utimbuf *timep"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is obsoleted by
+.Xr utimes 2 .
+.Ef
+.Pp
+The
+.Fn utime
+function sets the access and modification times of the named file.
+.Pp
+If
+.Fa timep
+is
+.Dv NULL ,
+the access and modification times are set to the current time.
+The calling process must be the owner of the file or have permission to
+write the file.
+.Pp
+If
+.Fa timep
+is
+.Pf non- Dv NULL ,
+.Fa time
+is assumed to be a pointer to a utimbuf structure, as defined in
+.In utime.h :
+.Bd -literal -offset indent
+struct utimbuf {
+       time_t actime;          /* Access time */
+       time_t modtime;         /* Modification time */
+};
+.Ed
+.Pp
+The access time is set to the value of the actime member, and the
+modification time is set to the value of the modtime member.
+The times are measured in seconds since 0 hours, 0 minutes, 0
+seconds, January 1, 1970 Coordinated Universal Time (UTC).
+The calling process must be the owner of the file or be the super-user.
+.Pp
+In either case, the inode-change-time of the file is set to the current
+time.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn utime
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix;
+or the
+.Fa times
+argument is
+.Dv NULL
+and the effective user ID of the process does not
+match the owner of the file, and is not the super-user, and write
+access is denied.
+.It Bq Er EFAULT
+.Fa file
+or
+.Fa times
+points outside the process's allocated address space.
+.It Bq Er EINVAL
+The pathname contains a character with the high-order bit set.
+.It Bq Er EIO
+An I/O error occurred while reading or writing the affected inode.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded 255 characters,
+or an entire path name exceeded 1023 characters.
+.It Bq Er ENOENT
+The named file does not exist.
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er EPERM
+The
+.Fa times
+argument is not
+.Dv NULL
+and the calling process's effective user ID
+does not match the owner of the file and is not the super-user.
+.It Bq Er EROFS
+The file system containing the file is mounted read-only.
+.El
+.Sh SEE ALSO
+.Xr stat 2 ,
+.Xr utimes 2
+.Sh STANDARDS
+The
+.Fn utime
+function conforms to
+.St -p1003.1-90 .
+It was however marked as legacy in the
+.St -p1003.1-2008
+revision of the standard.
+.Sh HISTORY
+A
+.Fn utime
+function appeared in
+.At v7 .
diff --git a/lib/nbsd_libc/gen/utime.c b/lib/nbsd_libc/gen/utime.c
new file mode 100644 (file)
index 0000000..46534b8
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: utime.c,v 1.13 2010/03/23 20:28:59 drochner Exp $      */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)utime.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: utime.c,v 1.13 2010/03/23 20:28:59 drochner Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/time.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stddef.h>
+#include <utime.h>
+
+int
+utime(path, times)
+       const char *path;
+       const struct utimbuf *times;
+{
+       struct timeval tv[2], *tvp;
+
+       _DIAGASSERT(path != NULL);
+
+       if (times == (struct utimbuf *) NULL)
+               tvp = NULL;
+       else {
+               tv[0].tv_sec = times->actime;
+               tv[1].tv_sec = times->modtime;
+               tv[0].tv_usec = tv[1].tv_usec = 0;
+               tvp = tv;
+       }
+       return (utimes(path, tvp));
+}
diff --git a/lib/nbsd_libc/gen/utmp.c b/lib/nbsd_libc/gen/utmp.c
new file mode 100644 (file)
index 0000000..b83a3c0
--- /dev/null
@@ -0,0 +1,106 @@
+/*     $NetBSD: utmp.c,v 1.9 2009/02/05 23:52:55 lukem Exp $    */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: utmp.c,v 1.9 2009/02/05 23:52:55 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+#include <utmp.h>
+#include <sys/stat.h>
+
+static struct utmp utmp;
+static FILE *ut;
+static char utfile[MAXPATHLEN] = _PATH_UTMP;
+
+void
+setutent(void)
+{
+       if (ut == NULL)
+               return;
+       (void)fseeko(ut, (off_t)0, SEEK_SET);
+}
+
+struct utmp *
+getutent(void)
+{
+       if (ut == NULL) {
+               struct stat st;
+               off_t numentries;
+               if ((ut = fopen(utfile, "r")) == NULL)
+                       return NULL;
+               if (fstat(fileno(ut), &st) == -1)
+                       goto out;
+               /*
+                * If we have a an old version utmp file bail.
+                */
+               numentries = st.st_size / sizeof(utmp);
+               if ((off_t)(numentries * sizeof(utmp)) != st.st_size)
+                       goto out;
+       }
+       if (fread(&utmp, sizeof(utmp), 1, ut) == 1)
+               return &utmp;
+out:
+       (void)fclose(ut);
+       return NULL;
+}
+
+void
+endutent(void)
+{
+       if (ut != NULL) {
+               (void)fclose(ut);
+               ut = NULL;
+       }
+}
+
+int
+utmpname(const char *fname)
+{
+       size_t len = strlen(fname);
+
+       if (len >= sizeof(utfile))
+               return 0;
+
+       /* must not end in x! */
+       if (fname[len - 1] == 'x')
+               return 0;
+
+       (void)strlcpy(utfile, fname, sizeof(utfile));
+       endutent();
+       return 1;
+}
diff --git a/lib/nbsd_libc/gen/utmpx.c b/lib/nbsd_libc/gen/utmpx.c
new file mode 100644 (file)
index 0000000..779d565
--- /dev/null
@@ -0,0 +1,481 @@
+/*     $NetBSD: utmpx.c,v 1.26 2009/01/11 02:46:27 christos Exp $       */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: utmpx.c,v 1.26 2009/01/11 02:46:27 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+
+#include <assert.h>
+#include <db.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <utmp.h>
+#include <utmpx.h>
+#include <vis.h>
+
+static FILE *fp;
+static int readonly = 0;
+static int version = 1;
+static struct utmpx ut;
+static char utfile[MAXPATHLEN] = _PATH_UTMPX;
+
+static struct utmpx *utmp_update(const struct utmpx *);
+
+static const char vers[] = "utmpx-2.00";
+
+struct otimeval {
+       long tv_sec;
+       long tv_usec;
+};
+
+static void
+old2new(struct utmpx *utx)
+{
+       struct otimeval otv;
+       struct timeval *tv = &utx->ut_tv;
+       (void)memcpy(&otv, tv, sizeof(otv));
+       tv->tv_sec = otv.tv_sec;
+       tv->tv_usec = otv.tv_usec;
+}
+
+static void
+new2old(struct utmpx *utx)
+{
+       struct timeval tv;
+       struct otimeval *otv = (void *)&utx->ut_tv;
+       (void)memcpy(&tv, otv, sizeof(tv));
+       otv->tv_sec = (long)tv.tv_sec;
+       otv->tv_usec = (long)tv.tv_usec;
+}
+
+void
+setutxent()
+{
+
+       (void)memset(&ut, 0, sizeof(ut));
+       if (fp == NULL)
+               return;
+       (void)fseeko(fp, (off_t)sizeof(ut), SEEK_SET);
+}
+
+
+void
+endutxent()
+{
+
+       (void)memset(&ut, 0, sizeof(ut));
+       if (fp != NULL) {
+               (void)fclose(fp);
+               fp = NULL;
+               readonly = 0;
+       }
+}
+
+
+struct utmpx *
+getutxent()
+{
+
+       if (fp == NULL) {
+               struct stat st;
+
+               if ((fp = fopen(utfile, "r+")) == NULL)
+                       if ((fp = fopen(utfile, "w+")) == NULL) {
+                               if ((fp = fopen(utfile, "r")) == NULL)
+                                       goto fail;
+                               else
+                                       readonly = 1;
+                       }
+                                       
+
+               /* get file size in order to check if new file */
+               if (fstat(fileno(fp), &st) == -1)
+                       goto failclose;
+
+               if (st.st_size == 0) {
+                       /* new file, add signature record */
+                       (void)memset(&ut, 0, sizeof(ut));
+                       ut.ut_type = SIGNATURE;
+                       (void)memcpy(ut.ut_user, vers, sizeof(vers));
+                       if (fwrite(&ut, sizeof(ut), 1, fp) != 1)
+                               goto failclose;
+               } else {
+                       /* old file, read signature record */
+                       if (fread(&ut, sizeof(ut), 1, fp) != 1)
+                               goto failclose;
+                       if (memcmp(ut.ut_user, vers, 5) != 0 ||
+                           ut.ut_type != SIGNATURE)
+                               goto failclose;
+               }
+               version = ut.ut_user[6] - '0';
+       }
+
+       if (fread(&ut, sizeof(ut), 1, fp) != 1)
+               goto fail;
+       if (version == 1)
+               old2new(&ut);
+
+       return &ut;
+failclose:
+       (void)fclose(fp);
+fail:
+       (void)memset(&ut, 0, sizeof(ut));
+       return NULL;
+}
+
+
+struct utmpx *
+getutxid(const struct utmpx *utx)
+{
+
+       _DIAGASSERT(utx != NULL);
+
+       if (utx->ut_type == EMPTY)
+               return NULL;
+
+       do {
+               if (ut.ut_type == EMPTY)
+                       continue;
+               switch (utx->ut_type) {
+               case EMPTY:
+                       return NULL;
+               case RUN_LVL:
+               case BOOT_TIME:
+               case OLD_TIME:
+               case NEW_TIME:
+                       if (ut.ut_type == utx->ut_type)
+                               return &ut;
+                       break;
+               case INIT_PROCESS:
+               case LOGIN_PROCESS:
+               case USER_PROCESS:
+               case DEAD_PROCESS:
+                       switch (ut.ut_type) {
+                       case INIT_PROCESS:
+                       case LOGIN_PROCESS:
+                       case USER_PROCESS:
+                       case DEAD_PROCESS:
+                               if (memcmp(ut.ut_id, utx->ut_id,
+                                   sizeof(ut.ut_id)) == 0)
+                                       return &ut;
+                               break;
+                       default:
+                               break;
+                       }
+                       break;
+               default:
+                       return NULL;
+               }
+       } while (getutxent() != NULL);
+       return NULL;
+}
+
+
+struct utmpx *
+getutxline(const struct utmpx *utx)
+{
+
+       _DIAGASSERT(utx != NULL);
+
+       do {
+               switch (ut.ut_type) {
+               case EMPTY:
+                       break;
+               case LOGIN_PROCESS:
+               case USER_PROCESS:
+                       if (strncmp(ut.ut_line, utx->ut_line,
+                           sizeof(ut.ut_line)) == 0)
+                               return &ut;
+                       break;
+               default:
+                       break;
+               }
+       } while (getutxent() != NULL);
+       return NULL;
+}
+
+
+struct utmpx *
+pututxline(const struct utmpx *utx)
+{
+       struct utmpx temp, *u = NULL;
+       int gotlock = 0;
+
+       _DIAGASSERT(utx != NULL);
+
+       if (utx == NULL)
+               return NULL;
+
+       if (strcmp(_PATH_UTMPX, utfile) == 0)
+               if ((fp != NULL && readonly) || (fp == NULL && geteuid() != 0))
+                       return utmp_update(utx);
+
+
+       (void)memcpy(&temp, utx, sizeof(temp));
+
+       if (fp == NULL) {
+               (void)getutxent();
+               if (fp == NULL || readonly)
+                       return NULL;
+       }
+
+       if (getutxid(&temp) == NULL) {
+               setutxent();
+               if (getutxid(&temp) == NULL) {
+                       if (lockf(fileno(fp), F_LOCK, (off_t)0) == -1)
+                               return NULL;
+                       gotlock++;
+                       if (fseeko(fp, (off_t)0, SEEK_END) == -1)
+                               goto fail;
+               }
+       }
+
+       if (!gotlock) {
+               /* we are not appending */
+               if (fseeko(fp, -(off_t)sizeof(ut), SEEK_CUR) == -1)
+                       return NULL;
+       }
+
+       if (version == 1)
+               new2old(&temp);
+       if (fwrite(&temp, sizeof (temp), 1, fp) != 1)
+               goto fail;
+
+       if (fflush(fp) == -1)
+               goto fail;
+
+       u = memcpy(&ut, &temp, sizeof(ut));
+fail:
+       if (gotlock) {
+               if (lockf(fileno(fp), F_ULOCK, (off_t)0) == -1)
+                       return NULL;
+       }
+       return u;
+}
+
+
+static struct utmpx *
+utmp_update(const struct utmpx *utx)
+{
+       char buf[sizeof(*utx) * 4 + 1];
+       pid_t pid;
+       int status;
+
+       _DIAGASSERT(utx != NULL);
+
+       (void)strvisx(buf, (const char *)(const void *)utx, sizeof(*utx),
+           VIS_WHITE);
+       switch (pid = fork()) {
+       case 0:
+               (void)execl(_PATH_UTMP_UPDATE,
+                   strrchr(_PATH_UTMP_UPDATE, '/') + 1, buf, NULL);
+               _exit(1);
+               /*NOTREACHED*/
+       case -1:
+               return NULL;
+       default:
+               if (waitpid(pid, &status, 0) == -1)
+                       return NULL;
+               if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
+                       return memcpy(&ut, utx, sizeof(ut));
+               return NULL;
+       }
+
+}
+
+/*
+ * The following are extensions and not part of the X/Open spec.
+ */
+int
+updwtmpx(const char *file, const struct utmpx *utx)
+{
+       int fd;
+       int saved_errno;
+
+       _DIAGASSERT(file != NULL);
+       _DIAGASSERT(utx != NULL);
+
+       fd = open(file, O_WRONLY|O_APPEND|O_SHLOCK);
+
+       if (fd == -1) {
+               if ((fd = open(file, O_CREAT|O_WRONLY|O_EXLOCK, 0644)) == -1)
+                       return -1;
+               (void)memset(&ut, 0, sizeof(ut));
+               ut.ut_type = SIGNATURE;
+               (void)memcpy(ut.ut_user, vers, sizeof(vers));
+               if (write(fd, &ut, sizeof(ut)) == -1)
+                       goto failed;
+       }
+       if (write(fd, utx, sizeof(*utx)) == -1)
+               goto failed;
+       if (close(fd) == -1)
+               return -1;
+       return 0;
+
+  failed:
+       saved_errno = errno;
+       (void) close(fd);
+       errno = saved_errno;
+       return -1;
+}
+
+
+int
+utmpxname(const char *fname)
+{
+       size_t len;
+
+       _DIAGASSERT(fname != NULL);
+
+       len = strlen(fname);
+
+       if (len >= sizeof(utfile))
+               return 0;
+
+       /* must end in x! */
+       if (fname[len - 1] != 'x')
+               return 0;
+
+       (void)strlcpy(utfile, fname, sizeof(utfile));
+       endutxent();
+       return 1;
+}
+
+
+void
+getutmp(const struct utmpx *ux, struct utmp *u)
+{
+
+       _DIAGASSERT(ux != NULL);
+       _DIAGASSERT(u != NULL);
+
+       (void)memcpy(u->ut_name, ux->ut_name, sizeof(u->ut_name));
+       (void)memcpy(u->ut_line, ux->ut_line, sizeof(u->ut_line));
+       (void)memcpy(u->ut_host, ux->ut_host, sizeof(u->ut_host));
+       u->ut_time = ux->ut_tv.tv_sec;
+}
+
+void
+getutmpx(const struct utmp *u, struct utmpx *ux)
+{
+
+       _DIAGASSERT(ux != NULL);
+       _DIAGASSERT(u != NULL);
+
+       (void)memcpy(ux->ut_name, u->ut_name, sizeof(u->ut_name));
+       (void)memcpy(ux->ut_line, u->ut_line, sizeof(u->ut_line));
+       (void)memcpy(ux->ut_host, u->ut_host, sizeof(u->ut_host));
+       ux->ut_tv.tv_sec = u->ut_time;
+       ux->ut_tv.tv_usec = 0;
+       (void)memset(&ux->ut_ss, 0, sizeof(ux->ut_ss));
+       ux->ut_pid = 0;
+       ux->ut_type = USER_PROCESS;
+       ux->ut_session = 0;
+       ux->ut_exit.e_termination = 0;
+       ux->ut_exit.e_exit = 0;
+}
+
+struct lastlogx *
+getlastlogx(const char *fname, uid_t uid, struct lastlogx *ll)
+{
+       DBT key, data;
+       DB *db;
+
+       _DIAGASSERT(fname != NULL);
+       _DIAGASSERT(ll != NULL);
+
+       db = dbopen(fname, O_RDONLY|O_SHLOCK, 0, DB_HASH, NULL);
+
+       if (db == NULL)
+               return NULL;
+
+       key.data = &uid;
+       key.size = sizeof(uid);
+
+       if ((db->get)(db, &key, &data, 0) != 0)
+               goto error;
+
+       if (data.size != sizeof(*ll)) {
+               errno = EFTYPE;
+               goto error;
+       }
+
+       if (ll == NULL)
+               if ((ll = malloc(sizeof(*ll))) == NULL)
+                       goto done;
+
+       (void)memcpy(ll, data.data, sizeof(*ll));
+       goto done;
+error:
+       ll = NULL;
+done:
+       (db->close)(db);
+       return ll;
+}
+
+int
+updlastlogx(const char *fname, uid_t uid, struct lastlogx *ll)
+{
+       DBT key, data;
+       int error = 0;
+       DB *db;
+
+       _DIAGASSERT(fname != NULL);
+       _DIAGASSERT(ll != NULL);
+
+       db = dbopen(fname, O_RDWR|O_CREAT|O_EXLOCK, 0644, DB_HASH, NULL);
+
+       if (db == NULL)
+               return -1;
+
+       key.data = &uid;
+       key.size = sizeof(uid);
+       data.data = ll;
+       data.size = sizeof(*ll);
+       if ((db->put)(db, &key, &data, 0) != 0)
+               error = -1;
+
+       (db->close)(db);
+       return error;
+}
diff --git a/lib/nbsd_libc/gen/valloc.3 b/lib/nbsd_libc/gen/valloc.3
new file mode 100644 (file)
index 0000000..2c49a0d
--- /dev/null
@@ -0,0 +1,77 @@
+.\"    $NetBSD: valloc.3,v 1.14 2010/05/08 11:22:58 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)valloc.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 6, 2010
+.Dt VALLOC 3
+.Os
+.Sh NAME
+.Nm valloc
+.Nd aligned memory allocation function
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft void *
+.Fn valloc "size_t size"
+.Sh DESCRIPTION
+.Bf -symbolic
+The
+.Fn valloc
+function is obsoleted by the current version of
+.Xr malloc 3 ,
+which aligns page-sized and larger allocations.
+.Ef
+.Pp
+The
+.Fn valloc
+function
+allocates
+.Fa size
+bytes aligned on a page boundary.
+It is implemented by calling
+.Xr malloc 3
+with a slightly larger request, saving the true beginning of the block
+allocated, and returning a properly aligned pointer.
+.Sh RETURN VALUES
+The
+.Fn valloc
+function returns
+a pointer to the allocated space if successful; otherwise
+a null pointer is returned
+.Sh HISTORY
+The
+.Fn valloc
+function appeared in
+.Bx 3.0 .
+.Sh BUGS
+A
+.Fn vfree
+function has not been implemented.
diff --git a/lib/nbsd_libc/gen/valloc.c b/lib/nbsd_libc/gen/valloc.c
new file mode 100644 (file)
index 0000000..e92b73b
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: valloc.c,v 1.10 2003/08/07 16:42:59 agc Exp $  */
+
+/*
+ * Copyright (c) 1980, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)valloc.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: valloc.c,v 1.10 2003/08/07 16:42:59 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(valloc,_valloc)
+#endif
+
+void *
+valloc(i)
+       size_t i;
+{
+       long valsiz = getpagesize(), j;
+       void *cp = malloc((size_t)(i + (valsiz-1)));
+
+       j = ((long)cp + (valsiz-1)) &~ (valsiz-1);
+       return ((void *)j);
+}
diff --git a/lib/nbsd_libc/gen/verr.c b/lib/nbsd_libc/gen/verr.c
new file mode 100644 (file)
index 0000000..d78e32e
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: verr.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $       */
+
+/*-
+ * Copyright (c) 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)err.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: verr.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <err.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(verr, _verr)
+#endif
+
+#if !HAVE_ERR_H
+__dead void
+verr(int eval, const char *fmt, _BSD_VA_LIST_ ap)
+{
+       int sverrno;
+
+       sverrno = errno;
+       (void)fprintf(stderr, "%s: ", getprogname());
+       if (fmt != NULL) {
+               (void)vfprintf(stderr, fmt, ap);
+               (void)fprintf(stderr, ": ");
+       }
+       (void)fprintf(stderr, "%s\n", strerror(sverrno));
+       exit(eval);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/verrx.c b/lib/nbsd_libc/gen/verrx.c
new file mode 100644 (file)
index 0000000..951b862
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: verrx.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $      */
+
+/*-
+ * Copyright (c) 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)err.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: verrx.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <err.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(verrx, _verrx)
+#endif
+
+#if !HAVE_ERR_H
+__dead void
+verrx(int eval, const char *fmt, _BSD_VA_LIST_ ap)
+{
+       (void)fprintf(stderr, "%s: ", getprogname());
+       if (fmt != NULL)
+               (void)vfprintf(stderr, fmt, ap);
+       (void)fprintf(stderr, "\n");
+       exit(eval);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/vis.3 b/lib/nbsd_libc/gen/vis.3
new file mode 100644 (file)
index 0000000..68c7b84
--- /dev/null
@@ -0,0 +1,354 @@
+.\"    $NetBSD: vis.3,v 1.23 2009/02/10 23:06:31 christos Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)vis.3      8.1 (Berkeley) 6/9/93
+.\"
+.Dd February 10, 2009
+.Dt VIS 3
+.Os
+.Sh NAME
+.Nm vis ,
+.Nm strvis ,
+.Nm strvisx ,
+.Nm svis ,
+.Nm strsvis ,
+.Nm strsvisx
+.Nd visually encode characters
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In vis.h
+.Ft char *
+.Fn vis "char *dst" "int c" "int flag" "int nextc"
+.Ft int
+.Fn strvis "char *dst" "const char *src" "int flag"
+.Ft int
+.Fn strvisx "char *dst" "const char *src" "size_t len" "int flag"
+.Ft char *
+.Fn svis "char *dst" "int c" "int flag" "int nextc" "const char *extra"
+.Ft int
+.Fn strsvis "char *dst" "const char *src" "int flag" "const char *extra"
+.Ft int
+.Fn strsvisx "char *dst" "const char *src" "size_t len" "int flag" "const char *extra"
+.Sh DESCRIPTION
+The
+.Fn vis
+function
+copies into
+.Fa dst
+a string which represents the character
+.Fa c .
+If
+.Fa c
+needs no encoding, it is copied in unaltered.
+The string is null terminated, and a pointer to the end of the string is
+returned.
+The maximum length of any encoding is four
+characters (not including the trailing
+.Dv NUL ) ;
+thus, when
+encoding a set of characters into a buffer, the size of the buffer should
+be four times the number of characters encoded, plus one for the trailing
+.Dv NUL .
+The flag parameter is used for altering the default range of
+characters considered for encoding and for altering the visual
+representation.
+The additional character,
+.Fa nextc ,
+is only used when selecting the
+.Dv VIS_CSTYLE
+encoding format (explained below).
+.Pp
+The
+.Fn strvis
+and
+.Fn strvisx
+functions copy into
+.Fa dst
+a visual representation of
+the string
+.Fa src .
+The
+.Fn strvis
+function encodes characters from
+.Fa src
+up to the
+first
+.Dv NUL .
+The
+.Fn strvisx
+function encodes exactly
+.Fa len
+characters from
+.Fa src
+(this
+is useful for encoding a block of data that may contain
+.Dv NUL Ns 's ) .
+Both forms
+.Dv NUL
+terminate
+.Fa dst .
+The size of
+.Fa dst
+must be four times the number
+of characters encoded from
+.Fa src
+(plus one for the
+.Dv NUL ) .
+Both
+forms return the number of characters in dst (not including
+the trailing
+.Dv NUL ) .
+.Pp
+The functions
+.Fn svis ,
+.Fn strsvis ,
+and
+.Fn strsvisx
+correspond to
+.Fn vis ,
+.Fn strvis ,
+and
+.Fn strvisx
+but have an additional argument
+.Fa extra ,
+pointing to a
+.Dv NUL
+terminated list of characters.
+These characters will be copied encoded or backslash-escaped into
+.Fa dst .
+These functions are useful e.g. to remove the special meaning
+of certain characters to shells.
+.Pp
+The encoding is a unique, invertible representation composed entirely of
+graphic characters; it can be decoded back into the original form using
+the
+.Xr unvis 3
+or
+.Xr strunvis 3
+functions.
+.Pp
+There are two parameters that can be controlled: the range of
+characters that are encoded (applies only to
+.Fn vis ,
+.Fn strvis ,
+and
+.Fn strvisx ) ,
+and the type of representation used.
+By default, all non-graphic characters,
+except space, tab, and newline are encoded.
+(See
+.Xr isgraph 3 . )
+The following flags
+alter this:
+.Bl -tag -width VIS_WHITEX
+.It Dv VIS_SP
+Also encode space.
+.It Dv VIS_TAB
+Also encode tab.
+.It Dv VIS_NL
+Also encode newline.
+.It Dv VIS_WHITE
+Synonym for
+.Dv VIS_SP
+\&|
+.Dv VIS_TAB
+\&|
+.Dv VIS_NL .
+.It Dv VIS_SAFE
+Only encode "unsafe" characters.
+Unsafe means control characters which may cause common terminals to perform
+unexpected functions.
+Currently this form allows space, tab, newline, backspace, bell, and
+return - in addition to all graphic characters - unencoded.
+.El
+.Pp
+(The above flags have no effect for
+.Fn svis ,
+.Fn strsvis ,
+and
+.Fn strsvisx .
+When using these functions, place all graphic characters to be
+encoded in an array pointed to by
+.Fa extra .
+In general, the backslash character should be included in this array, see the
+warning on the use of the
+.Dv VIS_NOSLASH
+flag below).
+.Pp
+There are four forms of encoding.
+All forms use the backslash character
+.Ql \e
+to introduce a special
+sequence; two backslashes are used to represent a real backslash,
+except
+.Dv VIS_HTTPSTYLE
+that uses
+.Ql % ,
+or
+.Dv VIS_MIMESTYLE
+that uses
+.Ql = .
+These are the visual formats:
+.Bl -tag -width VIS_CSTYLE
+.It (default)
+Use an
+.Ql M
+to represent meta characters (characters with the 8th
+bit set), and use caret
+.Ql ^
+to represent control characters see
+.Pf ( Xr iscntrl 3 ) .
+The following formats are used:
+.Bl -tag -width xxxxx
+.It Dv \e^C
+Represents the control character
+.Ql C .
+Spans characters
+.Ql \e000
+through
+.Ql \e037 ,
+and
+.Ql \e177
+(as
+.Ql \e^? ) .
+.It Dv \eM-C
+Represents character
+.Ql C
+with the 8th bit set.
+Spans characters
+.Ql \e241
+through
+.Ql \e376 .
+.It Dv \eM^C
+Represents control character
+.Ql C
+with the 8th bit set.
+Spans characters
+.Ql \e200
+through
+.Ql \e237 ,
+and
+.Ql \e377
+(as
+.Ql \eM^? ) .
+.It Dv \e040
+Represents
+.Tn ASCII
+space.
+.It Dv \e240
+Represents Meta-space.
+.El
+.Pp
+.It Dv VIS_CSTYLE
+Use C-style backslash sequences to represent standard non-printable
+characters.
+The following sequences are used to represent the indicated characters:
+.Bd -unfilled -offset indent
+.Li \ea Tn  - BEL No (007)
+.Li \eb Tn  - BS No (010)
+.Li \ef Tn  - NP No (014)
+.Li \en Tn  - NL No (012)
+.Li \er Tn  - CR No (015)
+.Li \es Tn  - SP No (040)
+.Li \et Tn  - HT No (011)
+.Li \ev Tn  - VT No (013)
+.Li \e0 Tn  - NUL No (000)
+.Ed
+.Pp
+When using this format, the nextc parameter is looked at to determine
+if a
+.Dv NUL
+character can be encoded as
+.Ql \e0
+instead of
+.Ql \e000 .
+If
+.Fa nextc
+is an octal digit, the latter representation is used to
+avoid ambiguity.
+.It Dv VIS_OCTAL
+Use a three digit octal sequence.
+The form is
+.Ql \eddd
+where
+.Em d
+represents an octal digit.
+.It Dv VIS_HTTPSTYLE
+Use URI encoding as described in RFC 1738.
+The form is
+.Ql %xx
+where
+.Em x
+represents a lower case hexadecimal digit.
+.It Dv VIS_MIMESTYLE
+Use MIME Quoted-Printable encoding as described in RFC 2045, only don't
+break lines and don't handle CRLF.
+The form is:
+.Ql %XX
+where
+.Em X
+represents an upper case hexadecimal digit.
+.El
+.Pp
+There is one additional flag,
+.Dv VIS_NOSLASH ,
+which inhibits the
+doubling of backslashes and the backslash before the default
+format (that is, control characters are represented by
+.Ql ^C
+and
+meta characters as
+.Ql M-C ) .
+With this flag set, the encoding is
+ambiguous and non-invertible.
+.Sh SEE ALSO
+.Xr unvis 1 ,
+.Xr vis 1 ,
+.Xr unvis 3
+.Rs
+.%A T. Berners-Lee
+.%T Uniform Resource Locators (URL)
+.%O RFC1738
+.Re
+.Sh HISTORY
+The
+.Fa vis ,
+.Fa strvis ,
+and
+.Fa strvisx
+functions first appeared in
+.Bx 4.4 .
+The
+.Fa svis ,
+.Fa strsvis ,
+and
+.Fa strsvisx
+functions appeared in
+.Nx 1.5 .
diff --git a/lib/nbsd_libc/gen/vis.c b/lib/nbsd_libc/gen/vis.c
new file mode 100644 (file)
index 0000000..4773096
--- /dev/null
@@ -0,0 +1,423 @@
+/*     $NetBSD: vis.c,v 1.41 2009/11/23 10:08:47 plunky Exp $  */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+/*-
+ * Copyright (c) 1999, 2005 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: vis.c,v 1.41 2009/11/23 10:08:47 plunky Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <vis.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(strsvis,_strsvis)
+__weak_alias(strsvisx,_strsvisx)
+__weak_alias(strvis,_strvis)
+__weak_alias(strvisx,_strvisx)
+__weak_alias(svis,_svis)
+__weak_alias(vis,_vis)
+#endif
+
+#if !HAVE_VIS || !HAVE_SVIS
+#include <ctype.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+
+static char *do_svis(char *, int, int, int, const char *);
+
+#undef BELL
+#define BELL '\a'
+
+#define isoctal(c)     (((u_char)(c)) >= '0' && ((u_char)(c)) <= '7')
+#define iswhite(c)     (c == ' ' || c == '\t' || c == '\n')
+#define issafe(c)      (c == '\b' || c == BELL || c == '\r')
+#define xtoa(c)                "0123456789abcdef"[c]
+#define XTOA(c)                "0123456789ABCDEF"[c]
+
+#define MAXEXTRAS      5
+
+#define MAKEEXTRALIST(flag, extra, orig_str)                                 \
+do {                                                                         \
+       const char *orig = orig_str;                                          \
+       const char *o = orig;                                                 \
+       char *e;                                                              \
+       while (*o++)                                                          \
+               continue;                                                     \
+       extra = malloc((size_t)((o - orig) + MAXEXTRAS));                     \
+       if (!extra) break;                                                    \
+       for (o = orig, e = extra; (*e++ = *o++) != '\0';)                     \
+               continue;                                                     \
+       e--;                                                                  \
+       if (flag & VIS_SP) *e++ = ' ';                                        \
+       if (flag & VIS_TAB) *e++ = '\t';                                      \
+       if (flag & VIS_NL) *e++ = '\n';                                       \
+       if ((flag & VIS_NOSLASH) == 0) *e++ = '\\';                           \
+       *e = '\0';                                                            \
+} while (/*CONSTCOND*/0)
+
+/*
+ * This is do_hvis, for HTTP style (RFC 1808)
+ */
+static char *
+do_hvis(char *dst, int c, int flag, int nextc, const char *extra)
+{
+
+       if ((isascii(c) && isalnum(c))
+           /* safe */
+           || c == '$' || c == '-' || c == '_' || c == '.' || c == '+'
+           /* extra */
+           || c == '!' || c == '*' || c == '\'' || c == '(' || c == ')'
+           || c == ',') {
+               dst = do_svis(dst, c, flag, nextc, extra);
+       } else {
+               *dst++ = '%';
+               *dst++ = xtoa(((unsigned int)c >> 4) & 0xf);
+               *dst++ = xtoa((unsigned int)c & 0xf);
+       }
+
+       return dst;
+}
+
+/*
+ * This is do_mvis, for Quoted-Printable MIME (RFC 2045)
+ * NB: No handling of long lines or CRLF.
+ */
+static char *
+do_mvis(char *dst, int c, int flag, int nextc, const char *extra)
+{
+       if ((c != '\n') &&
+           /* Space at the end of the line */
+           ((isspace(c) && (nextc == '\r' || nextc == '\n')) ||
+           /* Out of range */
+           (!isspace(c) && (c < 33 || (c > 60 && c < 62) || c > 126)) ||
+           /* Specific char to be escaped */ 
+           strchr("#$@[\\]^`{|}~", c) != NULL)) {
+               *dst++ = '=';
+               *dst++ = XTOA(((unsigned int)c >> 4) & 0xf);
+               *dst++ = XTOA((unsigned int)c & 0xf);
+       } else {
+               dst = do_svis(dst, c, flag, nextc, extra);
+       }
+       return dst;
+}
+
+/*
+ * This is do_vis, the central code of vis.
+ * dst:              Pointer to the destination buffer
+ * c:        Character to encode
+ * flag:      Flag word
+ * nextc:     The character following 'c'
+ * extra:     Pointer to the list of extra characters to be
+ *           backslash-protected.
+ */
+static char *
+do_svis(char *dst, int c, int flag, int nextc, const char *extra)
+{
+       int isextra;
+       isextra = strchr(extra, c) != NULL;
+       if (!isextra && isascii(c) && (isgraph(c) || iswhite(c) ||
+           ((flag & VIS_SAFE) && issafe(c)))) {
+               *dst++ = c;
+               return dst;
+       }
+       if (flag & VIS_CSTYLE) {
+               switch (c) {
+               case '\n':
+                       *dst++ = '\\'; *dst++ = 'n';
+                       return dst;
+               case '\r':
+                       *dst++ = '\\'; *dst++ = 'r';
+                       return dst;
+               case '\b':
+                       *dst++ = '\\'; *dst++ = 'b';
+                       return dst;
+               case BELL:
+                       *dst++ = '\\'; *dst++ = 'a';
+                       return dst;
+               case '\v':
+                       *dst++ = '\\'; *dst++ = 'v';
+                       return dst;
+               case '\t':
+                       *dst++ = '\\'; *dst++ = 't';
+                       return dst;
+               case '\f':
+                       *dst++ = '\\'; *dst++ = 'f';
+                       return dst;
+               case ' ':
+                       *dst++ = '\\'; *dst++ = 's';
+                       return dst;
+               case '\0':
+                       *dst++ = '\\'; *dst++ = '0';
+                       if (isoctal(nextc)) {
+                               *dst++ = '0';
+                               *dst++ = '0';
+                       }
+                       return dst;
+               default:
+                       if (isgraph(c)) {
+                               *dst++ = '\\'; *dst++ = c;
+                               return dst;
+                       }
+               }
+       }
+       if (isextra || ((c & 0177) == ' ') || (flag & VIS_OCTAL)) {
+               *dst++ = '\\';
+               *dst++ = (u_char)(((u_int32_t)(u_char)c >> 6) & 03) + '0';
+               *dst++ = (u_char)(((u_int32_t)(u_char)c >> 3) & 07) + '0';
+               *dst++ =                             (c       & 07) + '0';
+       } else {
+               if ((flag & VIS_NOSLASH) == 0) *dst++ = '\\';
+               if (c & 0200) {
+                       c &= 0177; *dst++ = 'M';
+               }
+               if (iscntrl(c)) {
+                       *dst++ = '^';
+                       if (c == 0177)
+                               *dst++ = '?';
+                       else
+                               *dst++ = c + '@';
+               } else {
+                       *dst++ = '-'; *dst++ = c;
+               }
+       }
+       return dst;
+}
+
+typedef char *(*visfun_t)(char *, int, int, int, const char *);
+
+/*
+ * Return the appropriate encoding function depending on the flags given.
+ */
+static visfun_t
+getvisfun(int flag)
+{
+       if (flag & VIS_HTTPSTYLE)
+               return do_hvis;
+       if (flag & VIS_MIMESTYLE)
+               return do_mvis;
+       return do_svis;
+}
+
+/*
+ * svis - visually encode characters, also encoding the characters
+ *       pointed to by `extra'
+ */
+char *
+svis(char *dst, int c, int flag, int nextc, const char *extra)
+{
+       char *nextra = NULL;
+       visfun_t f;
+
+       _DIAGASSERT(dst != NULL);
+       _DIAGASSERT(extra != NULL);
+       MAKEEXTRALIST(flag, nextra, extra);
+       if (!nextra) {
+               *dst = '\0';            /* can't create nextra, return "" */
+               return dst;
+       }
+       f = getvisfun(flag);
+       dst = (*f)(dst, c, flag, nextc, nextra);
+       free(nextra);
+       *dst = '\0';
+       return dst;
+}
+
+
+/*
+ * strsvis, strsvisx - visually encode characters from src into dst
+ *
+ *     Extra is a pointer to a \0-terminated list of characters to
+ *     be encoded, too. These functions are useful e. g. to
+ *     encode strings in such a way so that they are not interpreted
+ *     by a shell.
+ *
+ *     Dst must be 4 times the size of src to account for possible
+ *     expansion.  The length of dst, not including the trailing NULL,
+ *     is returned.
+ *
+ *     Strsvisx encodes exactly len bytes from src into dst.
+ *     This is useful for encoding a block of data.
+ */
+int
+strsvis(char *dst, const char *csrc, int flag, const char *extra)
+{
+       int c;
+       char *start;
+       char *nextra = NULL;
+       const unsigned char *src = (const unsigned char *)csrc;
+       visfun_t f;
+
+       _DIAGASSERT(dst != NULL);
+       _DIAGASSERT(src != NULL);
+       _DIAGASSERT(extra != NULL);
+       MAKEEXTRALIST(flag, nextra, extra);
+       if (!nextra) {
+               *dst = '\0';            /* can't create nextra, return "" */
+               return 0;
+       }
+       f = getvisfun(flag);
+       for (start = dst; (c = *src++) != '\0'; /* empty */)
+               dst = (*f)(dst, c, flag, *src, nextra);
+       free(nextra);
+       *dst = '\0';
+       return (int)(dst - start);
+}
+
+
+int
+strsvisx(char *dst, const char *csrc, size_t len, int flag, const char *extra)
+{
+       unsigned char c;
+       char *start;
+       char *nextra = NULL;
+       const unsigned char *src = (const unsigned char *)csrc;
+       visfun_t f;
+
+       _DIAGASSERT(dst != NULL);
+       _DIAGASSERT(src != NULL);
+       _DIAGASSERT(extra != NULL);
+       MAKEEXTRALIST(flag, nextra, extra);
+       if (! nextra) {
+               *dst = '\0';            /* can't create nextra, return "" */
+               return 0;
+       }
+
+       f = getvisfun(flag);
+       for (start = dst; len > 0; len--) {
+               c = *src++;
+               dst = (*f)(dst, c, flag, len > 1 ? *src : '\0', nextra);
+       }
+       free(nextra);
+       *dst = '\0';
+       return (int)(dst - start);
+}
+#endif
+
+#if !HAVE_VIS
+/*
+ * vis - visually encode characters
+ */
+char *
+vis(char *dst, int c, int flag, int nextc)
+{
+       char *extra = NULL;
+       unsigned char uc = (unsigned char)c;
+       visfun_t f;
+
+       _DIAGASSERT(dst != NULL);
+
+       MAKEEXTRALIST(flag, extra, "");
+       if (! extra) {
+               *dst = '\0';            /* can't create extra, return "" */
+               return dst;
+       }
+       f = getvisfun(flag);
+       dst = (*f)(dst, uc, flag, nextc, extra);
+       free(extra);
+       *dst = '\0';
+       return dst;
+}
+
+
+/*
+ * strvis, strvisx - visually encode characters from src into dst
+ *
+ *     Dst must be 4 times the size of src to account for possible
+ *     expansion.  The length of dst, not including the trailing NULL,
+ *     is returned.
+ *
+ *     Strvisx encodes exactly len bytes from src into dst.
+ *     This is useful for encoding a block of data.
+ */
+int
+strvis(char *dst, const char *src, int flag)
+{
+       char *extra = NULL;
+       int rv;
+
+       MAKEEXTRALIST(flag, extra, "");
+       if (!extra) {
+               *dst = '\0';            /* can't create extra, return "" */
+               return 0;
+       }
+       rv = strsvis(dst, src, flag, extra);
+       free(extra);
+       return rv;
+}
+
+
+int
+strvisx(char *dst, const char *src, size_t len, int flag)
+{
+       char *extra = NULL;
+       int rv;
+
+       MAKEEXTRALIST(flag, extra, "");
+       if (!extra) {
+               *dst = '\0';            /* can't create extra, return "" */
+               return 0;
+       }
+       rv = strsvisx(dst, src, len, flag, extra);
+       free(extra);
+       return rv;
+}
+#endif
diff --git a/lib/nbsd_libc/gen/vwarn.c b/lib/nbsd_libc/gen/vwarn.c
new file mode 100644 (file)
index 0000000..802efdc
--- /dev/null
@@ -0,0 +1,71 @@
+/*     $NetBSD: vwarn.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $      */
+
+/*-
+ * Copyright (c) 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)err.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: vwarn.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <err.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(vwarn, _vwarn)
+#endif
+
+#if !HAVE_ERR_H
+void
+vwarn(const char *fmt, _BSD_VA_LIST_ ap)
+{
+       int sverrno;
+
+       sverrno = errno;
+       (void)fprintf(stderr, "%s: ", getprogname());
+       if (fmt != NULL) {
+               (void)vfprintf(stderr, fmt, ap);
+               (void)fprintf(stderr, ": ");
+       }
+       (void)fprintf(stderr, "%s\n", strerror(sverrno));
+}
+#endif
diff --git a/lib/nbsd_libc/gen/vwarnx.c b/lib/nbsd_libc/gen/vwarnx.c
new file mode 100644 (file)
index 0000000..60f849d
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: vwarnx.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $     */
+
+/*-
+ * Copyright (c) 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)err.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: vwarnx.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <err.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(vwarnx, _vwarnx)
+#endif
+
+#if !HAVE_ERR_H
+void
+vwarnx(const char *fmt, _BSD_VA_LIST_ ap)
+{
+       (void)fprintf(stderr, "%s: ", getprogname());
+       if (fmt != NULL)
+               (void)vfprintf(stderr, fmt, ap);
+       (void)fprintf(stderr, "\n");
+}
+#endif
diff --git a/lib/nbsd_libc/gen/wait.c b/lib/nbsd_libc/gen/wait.c
new file mode 100644 (file)
index 0000000..2877c4d
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: wait.c,v 1.8 2003/08/07 16:43:00 agc Exp $     */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)wait.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: wait.c,v 1.8 2003/08/07 16:43:00 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+#include <sys/resource.h>
+
+#ifdef __weak_alias
+__weak_alias(wait,_wait)
+#endif
+
+
+pid_t
+wait(istat)
+       int *istat;
+{
+       return (wait4(WAIT_ANY, istat, 0, (struct rusage *)0));
+}
diff --git a/lib/nbsd_libc/gen/wait3.c b/lib/nbsd_libc/gen/wait3.c
new file mode 100644 (file)
index 0000000..3152552
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: wait3.c,v 1.9 2010/03/23 20:28:59 drochner Exp $       */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)wait3.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: wait3.c,v 1.9 2010/03/23 20:28:59 drochner Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+#include <sys/resource.h>
+
+pid_t
+wait3(istat, options, rup)
+       int *istat;
+       int options;
+       struct rusage *rup;
+{
+       return (wait4(WAIT_ANY, istat, options, rup));
+}
diff --git a/lib/nbsd_libc/gen/waitpid.c b/lib/nbsd_libc/gen/waitpid.c
new file mode 100644 (file)
index 0000000..46a8317
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: waitpid.c,v 1.9 2003/08/07 16:43:01 agc Exp $  */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)waitpid.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: waitpid.c,v 1.9 2003/08/07 16:43:01 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+#include <sys/resource.h>
+
+#ifdef __weak_alias
+__weak_alias(waitpid,_waitpid)
+#endif
+
+pid_t
+waitpid(pid_t pid, int *istat, int options)
+{
+       return (wait4(pid, istat, options, (struct rusage *)0));
+}
diff --git a/lib/nbsd_libc/gen/warn.c b/lib/nbsd_libc/gen/warn.c
new file mode 100644 (file)
index 0000000..2f78466
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: warn.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $       */
+
+/*-
+ * Copyright (c) 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)err.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: warn.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <err.h>
+#include <stdarg.h>
+
+#ifdef __weak_alias
+__weak_alias(warn, _warn)
+#endif
+
+#if !HAVE_ERR_H
+void
+warn(const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       vwarn(fmt, ap);
+       va_end(ap);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/warnx.c b/lib/nbsd_libc/gen/warnx.c
new file mode 100644 (file)
index 0000000..e703c53
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: warnx.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $      */
+
+/*-
+ * Copyright (c) 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)err.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: warnx.c,v 1.14 2007/06/18 14:13:54 ginsbach Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <err.h>
+#include <stdarg.h>
+
+#ifdef __weak_alias
+__weak_alias(warnx, _warnx)
+#endif
+
+#if !HAVE_ERR_H
+void
+warnx(const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       vwarnx(fmt, ap);
+       va_end(ap);
+}
+#endif
diff --git a/lib/nbsd_libc/gen/wordexp.3 b/lib/nbsd_libc/gen/wordexp.3
new file mode 100644 (file)
index 0000000..62eae0a
--- /dev/null
@@ -0,0 +1,226 @@
+.\"    $NetBSD: wordexp.3,v 1.2 2006/04/24 20:27:34 jld Exp $
+.\"
+.\" Copyright (c) 2002 Tim J. Robbins
+.\" 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.
+.\"
+.\" $FreeBSD: /repoman/r/ncvs/src/lib/libc/gen/wordexp.3,v 1.6 2003/09/08 19:57:14 ru Exp $
+.\"
+.Dd July 13, 2004
+.Dt WORDEXP 3
+.Os
+.Sh NAME
+.Nm wordexp
+.Nd "perform shell-style word expansions"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wordexp.h
+.Ft int
+.Fn wordexp "const char * restrict words" "wordexp_t * restrict pwordexp" "int flags"
+.Ft void
+.Fn wordfree "wordexp_t *pwordexp"
+.Sh DESCRIPTION
+The
+.Fn wordexp
+function performs shell-style word expansion on
+.Fa words
+and places the list of expanded words into the structure pointed to by
+.Fa pwordexp .
+.Pp
+The
+.Fa flags
+argument is the bitwise inclusive OR of any of the following constants:
+.Bl -tag -width ".Dv WRDE_SHOWERR"
+.It Dv WRDE_APPEND
+Append the words to those generated by a previous call to
+.Fn wordexp .
+.It Dv WRDE_DOOFFS
+As many
+.Dv NULL
+pointers as are specified by the
+.Va we_offs
+member of
+.Fa we
+are added to the front of
+.Va we_wordv .
+.It Dv WRDE_NOCMD
+Disallow command substitution in
+.Fa words .
+See the note in
+.Sx BUGS
+before using this.
+.It Dv WRDE_REUSE
+The
+.Fa we
+argument was passed to a previous successful call to
+.Fn wordexp
+but has not been passed to
+.Fn wordfree .
+The implementation may reuse the space allocated to it.
+.It Dv WRDE_SHOWERR
+Do not redirect shell error messages to
+.Pa /dev/null .
+.It Dv WRDE_UNDEF
+Report error on an attempt to expand an undefined shell variable.
+.El
+.Pp
+The structure type
+.Nm wordexp_t
+includes the following members:
+.Bd -literal -offset indent
+size_t we_wordc
+char   **we_wordv
+size_t we_offs
+.Ed
+.Pp
+The
+.Fa we_wordc
+member is the count of generated words.
+.Pp
+The
+.Fa we_wordv
+member points to a list of pointers to expanded words.
+.Pp
+The
+.Fa we_offs
+member is the number of slots to reserve at the beginning of the
+.Fa we_wordv
+member.
+.Pp
+It is the caller's responsibility to allocate the storage pointed to by
+.Fa pwordexp .
+The
+.Fn wordexp
+function allocates other space as needed, including memory
+pointed to by the
+.Fa we_wordv
+member.
+.Pp
+The
+.Fn wordfree
+function frees the memory allocated by
+.Fn wordexp .
+.Sh IMPLEMENTATION NOTES
+The
+.Fn wordexp
+function is implemented as a wrapper around the undocumented
+.Ic wordexp
+shell built-in command.
+.Sh RETURN VALUES
+The
+.Fn wordexp
+function returns zero if successful, otherwise it returns one of the following
+error codes:
+.Bl -tag -width ".Dv WRDE_NOSPACE"
+.It Dv WRDE_BADCHAR
+The
+.Fa words
+argument contains one of the following unquoted characters:
+.Aq newline ,
+.Ql | ,
+.Ql \*[Am] ,
+.Ql \&; ,
+.Ql \*[Lt] ,
+.Ql \*[Gt] ,
+.Ql \&( ,
+.Ql \&) ,
+.Ql { ,
+.Ql } .
+.It Dv WRDE_BADVAL
+An attempt was made to expand an undefined shell variable and
+.Dv WRDE_UNDEF
+is set in
+.Fa flags .
+.It Dv WRDE_CMDSUB
+An attempt was made to use command substitution and
+.Dv WRDE_NOCMD
+is set in
+.Fa flags .
+.It Dv WRDE_NOSPACE
+Not enough memory to store the result.
+.It Dv WRDE_SYNTAX
+Shell syntax error in
+.Fa words .
+.It Dv WRDE_ERRNO
+An internal error occured and
+.Va errno
+is set to indicate the error.
+.El
+.Pp
+The
+.Fn wordfree
+function returns no value.
+.Sh ENVIRONMENT
+.Bl -tag -width ".Ev IFS"
+.It Ev IFS
+Field separator.
+.El
+.Sh EXAMPLES
+Invoke the editor on all
+.Pa .c
+files in the current directory
+and
+.Pa /etc/motd
+(error checking omitted):
+.Bd -literal -offset indent
+wordexp_t we;
+
+wordexp("${EDITOR:-vi} *.c /etc/motd", \*[Am]we, 0);
+execvp(we-\*[Gt]we_wordv[0], we-\*[Gt]we_wordv);
+.Ed
+.Sh DIAGNOSTICS
+Diagnostic messages from the shell are written to the standard error output
+if
+.Dv WRDE_SHOWERR
+is set in
+.Fa flags .
+.Sh SEE ALSO
+.Xr sh 1 ,
+.Xr fnmatch 3 ,
+.Xr glob 3 ,
+.Xr popen 3 ,
+.Xr system 3
+.Sh STANDARDS
+The
+.Fn wordexp
+and
+.Fn wordfree
+functions conform to
+.St -p1003.1-2001 .
+Their first release was in
+.St -p1003.2-92 .
+The return value
+.Dv WRDE_ERRNO
+is an extension.
+.Sh BUGS
+Do not pass untrusted user data to
+.Fn wordexp ,
+regardless of whether the
+.Dv WRDE_NOCMD
+flag is set.
+The
+.Fn wordexp
+function attempts to detect input that would cause commands to be
+executed before passing it to the shell
+but it does not use the same parser so it may be fooled.
diff --git a/lib/nbsd_libc/gen/wordexp.c b/lib/nbsd_libc/gen/wordexp.c
new file mode 100644 (file)
index 0000000..a05db38
--- /dev/null
@@ -0,0 +1,346 @@
+/*     $NetBSD: wordexp.c,v 1.3 2009/02/12 04:10:52 lukem Exp $        */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins.
+ * 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.
+ */
+
+#include "namespace.h"
+#include <sys/cdefs.h>
+#include <sys/types.h>
+#include <assert.h>
+#include <sys/wait.h>
+#include <fcntl.h>
+#include <paths.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <wordexp.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: /repoman/r/ncvs/src/lib/libc/gen/wordexp.c,v 1.5 2004/04/09 11:32:32 tjr Exp $");
+#else
+__RCSID("$NetBSD: wordexp.c,v 1.3 2009/02/12 04:10:52 lukem Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+static int     we_askshell(const char *, wordexp_t *, int);
+static int     we_check(const char *, int);
+
+/*
+ * wordexp --
+ *     Perform shell word expansion on `words' and place the resulting list
+ *     of words in `we'. See wordexp(3).
+ *
+ */
+int
+wordexp(const char * __restrict words, wordexp_t * __restrict we, int flags)
+{
+       int error;
+
+       _DIAGASSERT(we != NULL);
+       _DIAGASSERT(words != NULL);
+       if (flags & WRDE_REUSE)
+               wordfree(we);
+       if ((flags & WRDE_APPEND) == 0) {
+               we->we_wordc = 0;
+               we->we_wordv = NULL;
+               we->we_strings = NULL;
+               we->we_nbytes = 0;
+       }
+       if ((error = we_check(words, flags)) != 0) {
+               wordfree(we);
+               return (error);
+       }
+       if ((error = we_askshell(words, we, flags)) != 0) {
+               wordfree(we);
+               return (error);
+       }
+       return (0);
+}
+
+/*
+ * we_askshell --
+ *     Use the `wordexp' /bin/sh builtin function to do most of the work
+ *     in expanding the word string. This function is complicated by
+ *     memory management.
+ */
+static int
+we_askshell(const char *words, wordexp_t *we, int flags)
+{
+       int pdes[2];                    /* Pipe to child */
+       size_t nwords, nbytes;          /* Number of words, bytes from child */
+       int i;                          /* Handy integer */
+       unsigned int ui;                /* For array iteration */
+       size_t sofs;                    /* Offset into we->we_strings */
+       size_t vofs;                    /* Offset into we->we_wordv */
+       pid_t pid;                      /* Process ID of child */
+       int status;                     /* Child exit status */
+       const char *ifs;                /* IFS env. var. */
+       char *np, *p;                   /* Handy pointers */
+       char *nstrings;                 /* Temporary for realloc() */
+       char **nwv;                     /* Temporary for realloc() */
+       FILE *fp;                       /* Stream to read pipe */
+       extern char **environ;
+       char *cmd;
+
+       if ((ifs = getenv("IFS")) == NULL)
+               ifs = " \t\n";
+       if (asprintf(&cmd, "wordexp%c%s\n", *ifs, words) < 0)
+               return (WRDE_NOSPACE);
+       if (pipe(pdes) < 0) {
+               free(cmd);
+               return (WRDE_ERRNO);
+       }
+       if ((fp = fdopen(pdes[0], "r")) == NULL) {
+               free(cmd);
+               return (WRDE_ERRNO);
+       }
+       if ((pid = fork()) < 0) {
+               free(cmd);
+               fclose(fp);
+               close(pdes[1]);
+               return (WRDE_ERRNO);
+       }
+       else if (pid == 0) {
+               /*
+                * We are the child; just get /bin/sh to run the wordexp
+                * builtin on `words'.
+                */
+               int devnull;
+
+               close(pdes[0]);
+               if (pdes[1] != STDOUT_FILENO) {
+                       if (dup2(pdes[1], STDOUT_FILENO) < 0)
+                               _exit(1);
+                       close(pdes[1]);
+               }
+               if ((flags & WRDE_SHOWERR) == 0) {
+                       if ((devnull = open(_PATH_DEVNULL, O_RDWR, 0666)) < 0)
+                               _exit(1);
+                       if (dup2(devnull, STDERR_FILENO) < 0)
+                               _exit(1);
+                       close(devnull);
+               }
+               execle(_PATH_BSHELL, "sh", flags & WRDE_UNDEF ? "-u" : "+u",
+                   "-c", cmd, (char *)NULL, environ);
+               _exit(1);
+       }
+
+       /*
+        * We are the parent; read the output of the shell wordexp function,
+        * which is a decimal word count, an null, a decimal byte count,
+        * (not including terminating null bytes), a null and then followed
+        * by the expanded words separated by nulls.
+        */
+       free(cmd);
+       close(pdes[1]);
+       /* read the word count */       
+       nwords = 0;
+       while ((i = getc(fp)) != EOF) {
+               if (i == '\0')
+                       break;
+               nwords *= 10;
+               nwords += (i - '0');
+       }
+       /* read the byte count */
+       nbytes = 0;
+       while ((i = getc(fp)) != EOF) {
+               if (i == '\0')
+                       break;
+               nbytes *= 10;
+               nbytes += (i - '0');
+       }
+       if (i == EOF) {
+               fclose(fp);
+               waitpid(pid, &status, 0);
+               return (flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX);
+       }
+       nbytes += nwords;
+
+       /*
+        * Allocate or reallocate (when flags & WRDE_APPEND) the word vector
+        * and string storage buffers for the expanded words we're about to
+        * read from the child.
+        */
+       sofs = we->we_nbytes;
+       vofs = we->we_wordc;
+       if ((flags & (WRDE_DOOFFS|WRDE_APPEND)) == (WRDE_DOOFFS|WRDE_APPEND))
+               vofs += we->we_offs;
+       we->we_wordc += nwords;
+       we->we_nbytes += nbytes;
+       if ((nwv = realloc(we->we_wordv, (we->we_wordc + 1 +
+           (flags & WRDE_DOOFFS ?  we->we_offs : 0)) *
+           sizeof(char *))) == NULL) {
+               fclose(fp);
+               waitpid(pid, &status, 0);
+               return (WRDE_NOSPACE);
+       }
+       we->we_wordv = nwv;
+       if ((nstrings = realloc(we->we_strings, we->we_nbytes)) == NULL) {
+               fclose(fp);
+               waitpid(pid, &status, 0);
+               return (WRDE_NOSPACE);
+       }
+       for (ui = 0; ui < vofs; ui++)
+               if (we->we_wordv[ui] != NULL)
+                       we->we_wordv[ui] += nstrings - we->we_strings;
+       we->we_strings = nstrings;
+
+       if (fread(we->we_strings + sofs, sizeof(char), nbytes, fp) != nbytes) {
+               fclose(fp);
+               waitpid(pid, &status, 0);
+               return (flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX);
+       }
+
+       if (waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) ||
+           WEXITSTATUS(status) != 0) {
+               fclose(fp);
+               return (flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX);
+       }
+       fclose(fp);
+
+       /*
+        * Break the null-terminated expanded word strings out into
+        * the vector.
+        */
+       if (vofs == 0 && flags & WRDE_DOOFFS)
+               while (vofs < we->we_offs)
+                       we->we_wordv[vofs++] = NULL;
+       p = we->we_strings + sofs;
+       while (nwords-- != 0) {
+               we->we_wordv[vofs++] = p;
+               if ((np = memchr(p, '\0', nbytes)) == NULL)
+                       return (WRDE_NOSPACE);  /* XXX */
+               nbytes -= np - p + 1;
+               p = np + 1;
+       }
+       we->we_wordv[vofs] = NULL;
+
+       return (0);
+}
+
+/*
+ * we_check --
+ *     Check that the string contains none of the following unquoted
+ *     special characters: <newline> |&;<>(){}
+ *     or command substitutions when WRDE_NOCMD is set in flags.
+ */
+static int
+we_check(const char *words, int flags)
+{
+       char c;
+       int dquote, level, quote, squote;
+
+       quote = squote = dquote = 0;
+       while ((c = *words++) != '\0') {
+               switch (c) {
+               case '\\':
+                       quote ^= 1;
+                       continue;
+               case '\'':
+                       if (quote + dquote == 0)
+                               squote ^= 1;
+                       break;
+               case '"':
+                       if (quote + squote == 0)
+                               dquote ^= 1;
+                       break;
+               case '`':
+                       if (quote + squote == 0 && flags & WRDE_NOCMD)
+                               return (WRDE_CMDSUB);
+                       while ((c = *words++) != '\0' && c != '`')
+                               if (c == '\\' && (c = *words++) == '\0')
+                                       break;
+                       if (c == '\0')
+                               return (WRDE_SYNTAX);
+                       break;
+               case '|': case '&': case ';': case '<': case '>':
+               case '{': case '}': case '(': case ')': case '\n':
+                       if (quote + squote + dquote == 0)
+                               return (WRDE_BADCHAR);
+                       break;
+               case '$':
+                       if ((c = *words++) == '\0')
+                               break;
+                       else if (quote + squote == 0 && c == '(') {
+                               if (flags & WRDE_NOCMD && *words != '(')
+                                       return (WRDE_CMDSUB);
+                               level = 1;
+                               while ((c = *words++) != '\0') {
+                                       if (c == '\\') {
+                                               if ((c = *words++) == '\0')
+                                                       break;
+                                       } else if (c == '(')
+                                               level++;
+                                       else if (c == ')' && --level == 0)
+                                               break;
+                               }
+                               if (c == '\0' || level != 0)
+                                       return (WRDE_SYNTAX);
+                       } else if (quote + squote == 0 && c == '{') {
+                               level = 1;
+                               while ((c = *words++) != '\0') {
+                                       if (c == '\\') {
+                                               if ((c = *words++) == '\0')
+                                                       break;
+                                       } else if (c == '{')
+                                               level++;
+                                       else if (c == '}' && --level == 0)
+                                               break;
+                               }
+                               if (c == '\0' || level != 0)
+                                       return (WRDE_SYNTAX);
+                       } else
+                               c = *--words;
+                       break;
+               default:
+                       break;
+               }
+               quote = 0;
+       }
+       if (quote + squote + dquote != 0)
+               return (WRDE_SYNTAX);
+
+       return (0);
+}
+
+/*
+ * wordfree --
+ *     Free the result of wordexp(). See wordexp(3).
+ *
+ */
+void
+wordfree(wordexp_t *we)
+{
+       _DIAGASSERT(we != NULL);
+       free(we->we_wordv);
+       free(we->we_strings);
+       we->we_wordv = NULL;
+       we->we_strings = NULL;
+       we->we_nbytes = 0;
+       we->we_wordc = 0;
+}
diff --git a/lib/nbsd_libc/gmon/Makefile.inc b/lib/nbsd_libc/gmon/Makefile.inc
new file mode 100644 (file)
index 0000000..f735d56
--- /dev/null
@@ -0,0 +1,28 @@
+#      $NetBSD: Makefile.inc,v 1.9 2009/12/17 06:54:51 mrg Exp $
+#      @(#)Makefile.inc        8.1 (Berkeley) 6/4/93
+
+# gmon sources
+.PATH: ${.CURDIR}/gmon ${ARCHDIR}/gmon
+
+.-include "${ARCHDIR}/gmon/Makefile.inc"
+
+SRCS+= gmon.c mcount.c
+MAN+=  moncontrol.3
+MLINKS+=moncontrol.3 monstartup.3
+
+.if (${MACHINE_ARCH} == "mipseb") || (${MACHINE_ARCH} == "mipsel") || \
+    (${MACHINE_ARCH} == "mips64eb") || (${MACHINE_ARCH} == "mips64el")
+# Turn off as(1) warnings on MIPS, since warnings are fatal with WARNS>0
+# and mcount.c causes warnings from as(1).
+# mcount.c should be fixed and this test removed.
+#
+COPTS.mcount.c+=-Wa,--no-warn
+.endif
+
+
+# mcount and gmon cannot be compiled with profiling
+mcount.po: mcount.o
+       cp mcount.o mcount.po
+
+gmon.po: gmon.o
+       cp gmon.o gmon.po
diff --git a/lib/nbsd_libc/gmon/gmon.c b/lib/nbsd_libc/gmon/gmon.c
new file mode 100644 (file)
index 0000000..01d017c
--- /dev/null
@@ -0,0 +1,544 @@
+/*     $NetBSD: gmon.c,v 1.33 2011/01/05 00:03:52 wiz Exp $    */
+
+/*
+ * Copyright (c) 2003, 2004 Wasabi Systems, Inc.
+ * All rights reserved.
+ *
+ * Written by Nathan J. Williams for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed for the NetBSD Project by
+ *     Wasabi Systems, Inc.
+ * 4. The name of Wasabi Systems, Inc. may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+ * 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.
+ */
+
+/*-
+ * Copyright (c) 1983, 1992, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if !defined(lint) && defined(LIBC_SCCS)
+#if 0
+static char sccsid[] = "@(#)gmon.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: gmon.c,v 1.33 2011/01/05 00:03:52 wiz Exp $");
+#endif
+#endif
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/time.h>
+#include <sys/gmon.h>
+#include <sys/mman.h>
+#include <sys/sysctl.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <unistd.h>
+#include <err.h>
+#include "extern.h"
+#include "reentrant.h"
+
+struct gmonparam _gmonparam = { .state = GMON_PROF_OFF };
+
+#ifdef _REENTRANT
+struct gmonparam *_gmonfree;
+struct gmonparam *_gmoninuse;
+mutex_t _gmonlock = MUTEX_INITIALIZER;
+thread_key_t _gmonkey;
+struct gmonparam _gmondummy;
+#endif
+
+static u_int   s_scale;
+/* see profil(2) where this is describe (incorrectly) */
+#define                SCALE_1_TO_1    0x10000L
+
+void   moncontrol(int);
+void   monstartup(u_long, u_long);
+void   _mcleanup(void);
+static int hertz(void);
+
+#ifdef _REENTRANT
+static void _m_gmon_destructor(void *);
+struct gmonparam *_m_gmon_alloc(void)
+    __attribute__((__no_instrument_function__));
+static void _m_gmon_merge(void);
+static void _m_gmon_merge_two(struct gmonparam *, struct gmonparam *);
+#endif
+
+void
+monstartup(u_long lowpc, u_long highpc)
+{
+       u_long o;
+       char *cp;
+       struct gmonparam *p = &_gmonparam;
+
+       /*
+        * round lowpc and highpc to multiples of the density we're using
+        * so the rest of the scaling (here and in gprof) stays in ints.
+        */
+       p->lowpc = rounddown(lowpc, HISTFRACTION * sizeof(HISTCOUNTER));
+       p->highpc = roundup(highpc, HISTFRACTION * sizeof(HISTCOUNTER));
+       p->textsize = p->highpc - p->lowpc;
+       p->kcountsize = p->textsize / HISTFRACTION;
+       p->hashfraction = HASHFRACTION;
+       p->fromssize = p->textsize / p->hashfraction;
+       p->tolimit = p->textsize * ARCDENSITY / 100;
+       if (p->tolimit < MINARCS)
+               p->tolimit = MINARCS;
+       else if (p->tolimit > MAXARCS)
+               p->tolimit = MAXARCS;
+       p->tossize = p->tolimit * sizeof(struct tostruct);
+
+       cp = sbrk((intptr_t)(p->kcountsize + p->fromssize + p->tossize));
+       if (cp == (char *)-1) {
+               warnx("%s: out of memory", __func__);
+               return;
+       }
+#ifdef notdef
+       (void)memset(cp, 0, p->kcountsize + p->fromssize + p->tossize);
+#endif
+       p->tos = (struct tostruct *)(void *)cp;
+       cp += (size_t)p->tossize;
+       p->kcount = (u_short *)(void *)cp;
+       cp += (size_t)p->kcountsize;
+       p->froms = (u_short *)(void *)cp;
+
+       __minbrk = sbrk((intptr_t)0);
+       p->tos[0].link = 0;
+
+       o = p->highpc - p->lowpc;
+       if (p->kcountsize < o) {
+#ifndef notdef
+               s_scale = ((float)p->kcountsize / o ) * SCALE_1_TO_1;
+#else /* avoid floating point */
+               u_long quot = o / p->kcountsize;
+               
+               if (quot >= 0x10000)
+                       s_scale = 1;
+               else if (quot >= 0x100)
+                       s_scale = 0x10000 / quot;
+               else if (o >= 0x800000)
+                       s_scale = 0x1000000 / (o / (p->kcountsize >> 8));
+               else
+                       s_scale = 0x1000000 / ((o << 8) / p->kcountsize);
+#endif
+       } else
+               s_scale = SCALE_1_TO_1;
+
+#ifdef _REENTRANT
+       _gmondummy.state = GMON_PROF_BUSY;
+       thr_keycreate(&_gmonkey, _m_gmon_destructor);
+#endif
+       moncontrol(1);
+}
+
+#ifdef _REENTRANT
+static void
+_m_gmon_destructor(void *arg)
+{
+       struct gmonparam *p = arg, *q, **prev;
+
+       if (p == &_gmondummy)
+               return;
+
+       thr_setspecific(_gmonkey, &_gmondummy);
+
+       mutex_lock(&_gmonlock);
+       /* XXX eww, linear list traversal. */
+       for (q = _gmoninuse, prev = &_gmoninuse;
+            q != NULL;
+            prev = (struct gmonparam **)(void *)&q->kcount,    /* XXX */
+                q = (struct gmonparam *)(void *)q->kcount) {
+               if (q == p)
+                       *prev = (struct gmonparam *)(void *)q->kcount;
+       }
+       p->kcount = (u_short *)(void *)_gmonfree;
+       _gmonfree = p;
+       mutex_unlock(&_gmonlock);
+
+       thr_setspecific(_gmonkey, NULL);
+}
+
+struct gmonparam *
+_m_gmon_alloc(void)
+{
+       struct gmonparam *p;
+       char *cp;
+
+       mutex_lock(&_gmonlock);
+       if (_gmonfree != NULL) {
+               p = _gmonfree;
+               _gmonfree = (struct gmonparam *)(void *)p->kcount;
+               p->kcount = (u_short *)(void *)_gmoninuse;
+               _gmoninuse = p;
+       } else {
+               mutex_unlock(&_gmonlock);
+               cp = mmap(NULL,
+                   (size_t)(sizeof (struct gmonparam) + 
+                       _gmonparam.fromssize + _gmonparam.tossize),
+                   PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0LL);
+               p = (void *)cp;
+               *p = _gmonparam;
+               p->kcount = NULL;
+               cp += sizeof (struct gmonparam);
+               memset(cp, 0, (size_t)(p->fromssize + p->tossize));
+               p->froms = (u_short *)(void *)cp;
+               p->tos = (struct tostruct *)(void *)(cp + p->fromssize);
+               mutex_lock(&_gmonlock);
+               p->kcount = (u_short *)(void *)_gmoninuse;
+               _gmoninuse = p;
+       }
+       mutex_unlock(&_gmonlock);
+       thr_setspecific(_gmonkey, p);
+
+       return p;
+}
+
+static void
+_m_gmon_merge_two(struct gmonparam *p, struct gmonparam *q)
+{
+       u_long fromindex;
+       u_short *frompcindex, qtoindex, toindex;
+       u_long selfpc;
+       u_long endfrom;
+       long count;
+       struct tostruct *top;
+       
+       endfrom = (q->fromssize / sizeof(*q->froms));
+       for (fromindex = 0; fromindex < endfrom; fromindex++) {
+               if (q->froms[fromindex] == 0)
+                       continue;
+               for (qtoindex = q->froms[fromindex]; qtoindex != 0;
+                    qtoindex = q->tos[qtoindex].link) {
+                       selfpc = q->tos[qtoindex].selfpc;
+                       count = q->tos[qtoindex].count;
+                       /* cribbed from mcount */
+                       frompcindex = &p->froms[fromindex];
+                       toindex = *frompcindex;
+                       if (toindex == 0) {
+                               /*
+                                *      first time traversing this arc
+                                */
+                               toindex = ++p->tos[0].link;
+                               if (toindex >= p->tolimit)
+                                       /* halt further profiling */
+                                       goto overflow;
+                               
+                               *frompcindex = (u_short)toindex;
+                               top = &p->tos[(size_t)toindex];
+                               top->selfpc = selfpc;
+                               top->count = count;
+                               top->link = 0;
+                               goto done;
+                       }
+                       top = &p->tos[(size_t)toindex];
+                       if (top->selfpc == selfpc) {
+                               /*
+                                * arc at front of chain; usual case.
+                                */
+                               top->count+= count;
+                               goto done;
+                       }
+                       /*
+                        * have to go looking down chain for it.
+                        * top points to what we are looking at,
+                        * we know it is not at the head of the chain.
+                        */
+                       for (; /* goto done */; ) {
+                               if (top->link == 0) {
+                                       /*
+                                        * top is end of the chain and
+                                        * none of the chain had
+                                        * top->selfpc == selfpc.  so
+                                        * we allocate a new tostruct
+                                        * and link it to the head of
+                                        * the chain.
+                                        */
+                                       toindex = ++p->tos[0].link;
+                                       if (toindex >= p->tolimit)
+                                               goto overflow;
+                                       
+                                       top = &p->tos[(size_t)toindex];
+                                       top->selfpc = selfpc;
+                                       top->count = count;
+                                       top->link = *frompcindex;
+                                       *frompcindex = (u_short)toindex;
+                                       goto done;
+                               }
+                               /*
+                                * otherwise, check the next arc on the chain.
+                                */
+                               top = &p->tos[top->link];
+                               if (top->selfpc == selfpc) {
+                                       /*
+                                        * there it is.
+                                        * add to its count.
+                                        */
+                                       top->count += count;
+                                       goto done;
+                               }
+                               
+                       }
+
+               done: ;
+               }
+
+       }
+ overflow: ;
+}
+
+static void
+_m_gmon_merge(void)
+{
+       struct gmonparam *q;
+
+       mutex_lock(&_gmonlock);
+
+       for (q = _gmonfree; q != NULL;
+           q = (struct gmonparam *)(void *)q->kcount)
+               _m_gmon_merge_two(&_gmonparam, q);
+
+       for (q = _gmoninuse; q != NULL;
+           q = (struct gmonparam *)(void *)q->kcount) {
+               q->state = GMON_PROF_OFF;
+               _m_gmon_merge_two(&_gmonparam, q);
+       }
+
+       mutex_unlock(&_gmonlock);
+}
+#endif
+
+void
+_mcleanup(void)
+{
+       int fd;
+       int fromindex;
+       int endfrom;
+       u_long frompc;
+       int toindex;
+       struct rawarc rawarc;
+       struct gmonparam *p = &_gmonparam;
+       struct gmonhdr gmonhdr, *hdr;
+       struct clockinfo clockinfo;
+       int mib[2];
+       size_t size;
+       char *profdir;
+       const char *proffile;
+       char  buf[PATH_MAX];
+#ifdef DEBUG
+       int logfd, len;
+       char buf2[200];
+#endif
+
+       /*
+        * We disallow writing to the profiling file, if we are a
+        * set{u,g}id program and our effective {u,g}id does not match
+        * our real one.
+        */
+       if (issetugid() && (geteuid() != getuid() || getegid() != getgid())) {
+               warnx("%s: Profiling of set{u,g}id binaries is not"
+                   " allowed", __func__);
+               return;
+       }
+
+       if (p->state == GMON_PROF_ERROR)
+               warnx("%s: tos overflow", __func__);
+
+       size = sizeof(clockinfo);
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_CLOCKRATE;
+       if (sysctl(mib, 2, &clockinfo, &size, NULL, 0) < 0) {
+               /*
+                * Best guess
+                */
+               clockinfo.profhz = hertz();
+       } else if (clockinfo.profhz == 0) {
+               if (clockinfo.hz != 0)
+                       clockinfo.profhz = clockinfo.hz;
+               else
+                       clockinfo.profhz = hertz();
+       }
+
+       moncontrol(0);
+
+       if ((profdir = getenv("PROFDIR")) != NULL) {
+               /* If PROFDIR contains a null value, no profiling 
+                  output is produced */
+               if (*profdir == '\0')
+                       return;
+
+               if (snprintf(buf, sizeof buf, "%s/%d.%s",
+                   profdir, getpid(), getprogname()) >= (int)(sizeof buf)) {
+                       warnx("%s: internal buffer overflow, PROFDIR too long",
+                           __func__);
+                       return;
+               }
+               
+               proffile = buf;
+       } else {
+               proffile = "gmon.out";
+       }
+
+       fd = open(proffile , O_CREAT|O_TRUNC|O_WRONLY, 0666);
+       if (fd < 0) {
+               warn("%s: Cannot open `%s'", __func__, proffile);
+               return;
+       }
+#ifdef DEBUG
+       logfd = open("gmon.log", O_CREAT|O_TRUNC|O_WRONLY, 0664);
+       if (logfd < 0) {
+               warn("%s: Cannot open `%s'", __func__, "gmon.log");
+               (void)close(fd);
+               return;
+       }
+       len = snprintf(buf2, sizeof buf2, "[mcleanup1] kcount %p ssiz %lu\n",
+           p->kcount, p->kcountsize);
+       (void)write(logfd, buf2, (size_t)len);
+#endif
+#ifdef _REENTRANT
+       _m_gmon_merge();
+#endif
+       hdr = (struct gmonhdr *)&gmonhdr;
+       hdr->lpc = p->lowpc;
+       hdr->hpc = p->highpc;
+       hdr->ncnt = (int)(p->kcountsize + sizeof(gmonhdr));
+       hdr->version = GMONVERSION;
+       hdr->profrate = clockinfo.profhz;
+       (void)write(fd, hdr, sizeof *hdr);
+       (void)write(fd, p->kcount, (size_t)p->kcountsize);
+       endfrom = (int)(p->fromssize / sizeof(*p->froms));
+       for (fromindex = 0; fromindex < endfrom; fromindex++) {
+               if (p->froms[fromindex] == 0)
+                       continue;
+
+               frompc = p->lowpc;
+               frompc += fromindex * p->hashfraction * sizeof(*p->froms);
+               for (toindex = p->froms[fromindex]; toindex != 0;
+                    toindex = p->tos[toindex].link) {
+#ifdef DEBUG
+                       len = snprintf(buf2, sizeof buf2,
+                       "[mcleanup2] frompc 0x%lx selfpc 0x%lx count %lu\n" ,
+                               (u_long)frompc, (u_long)p->tos[toindex].selfpc,
+                               (u_long)p->tos[toindex].count);
+                       (void)write(logfd, buf2, (size_t)len);
+#endif
+                       rawarc.raw_frompc = frompc;
+                       rawarc.raw_selfpc = p->tos[toindex].selfpc;
+                       rawarc.raw_count = p->tos[toindex].count;
+                       (void)write(fd, &rawarc, sizeof rawarc);
+               }
+       }
+       (void)close(fd);
+#ifdef DEBUG
+       (void)close(logfd);
+#endif
+}
+
+/*
+ * Control profiling
+ *     profiling is what mcount checks to see if
+ *     all the data structures are ready.
+ */
+void
+moncontrol(int mode)
+{
+       struct gmonparam *p = &_gmonparam;
+
+       if (mode) {
+               /* start */
+               profil((char *)(void *)p->kcount, (size_t)p->kcountsize,
+                   p->lowpc, s_scale);
+               p->state = GMON_PROF_ON;
+       } else {
+               /* stop */
+               profil(NULL, 0, (u_long)0, 0);
+               p->state = GMON_PROF_OFF;
+       }
+}
+
+/*
+ * discover the tick frequency of the machine
+ * if something goes wrong, we return 0, an impossible hertz.
+ */
+static int
+hertz(void)
+{
+        struct itimerspec tim;
+       timer_t t;
+       int rv = 0;
+
+        tim.it_interval.tv_sec = 0;
+        tim.it_interval.tv_nsec = 1;
+        tim.it_value.tv_sec = 0;
+        tim.it_value.tv_nsec = 0;
+
+       if (timer_create(CLOCK_REALTIME, NULL, &t) == -1)
+               return 0;
+
+       if (timer_settime(t, 0, &tim, NULL) == -1)
+               goto out;
+
+       if (timer_gettime(t, &tim) == -1)
+               goto out;
+
+        if (tim.it_interval.tv_nsec < 2)
+               goto out;
+
+       rv = (int)(1000000000LL / tim.it_interval.tv_nsec);
+out:
+       (void)timer_delete(t);
+       return rv;
+}
diff --git a/lib/nbsd_libc/gmon/moncontrol.3 b/lib/nbsd_libc/gmon/moncontrol.3
new file mode 100644 (file)
index 0000000..bc3dc32
--- /dev/null
@@ -0,0 +1,115 @@
+.\"    $NetBSD: moncontrol.3,v 1.10 2009/04/11 15:33:27 joerg Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 1992, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)moncontrol.3        8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt MONCONTROL 3
+.Os
+.Sh NAME
+.Nm moncontrol ,
+.Nm monstartup
+.Nd control execution profile
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.Fn moncontrol "int mode"
+.Fn monstartup "u_long *lowpc" "u_long *highpc"
+.Sh DESCRIPTION
+An executable program compiled using the
+.Fl pg
+option to
+.Xr cc 1
+automatically includes calls to collect statistics for the
+.Xr gprof 1
+call-graph execution profiler.
+In typical operation, profiling begins at program startup
+and ends when the program calls exit.
+When the program exits, the profiling data are written to the file
+.Em gmon.out ,
+then
+.Xr gprof 1
+can be used to examine the results.
+.Pp
+.Fn moncontrol
+selectively controls profiling within a program.
+When the program starts, profiling begins.
+To stop the collection of histogram ticks and call counts use
+.Fn moncontrol 0 ;
+to resume the collection of histogram ticks and call counts use
+.Fn moncontrol 1 .
+This feature allows the cost of particular operations to be measured.
+Note that an output file will be produced on program exit
+regardless of the state of
+.Fn moncontrol .
+.Pp
+Programs that are not loaded with
+.Fl pg
+may selectively collect profiling statistics by calling
+.Fn monstartup
+with the range of addresses to be profiled.
+.Fa lowpc
+and
+.Fa highpc
+specify the address range that is to be sampled;
+the lowest address sampled is that of
+.Fa lowpc
+and the highest is just below
+.Fa highpc .
+Only functions in that range that have been compiled with the
+.Fl pg
+option to
+.Xr cc 1
+will appear in the call graph part of the output;
+however, all functions in that address range will
+have their execution time measured.
+Profiling begins on return from
+.Fn monstartup .
+.Sh ENVIRONMENT
+.Bl -tag -width "PROFDIR"
+.It Ev PROFDIR
+Directory to place the output file(s) in.
+When this is set, instead of writing the profiling output to
+.Pa gmon.out ,
+a filename is generated from the process id and name of the program
+(e.g.,
+.Pa 123.a.out ) .
+If you are profiling a program that forks,
+or otherwise creates multiple copies,
+setting this is the only reasonable way to get all profiling data.
+.El
+.Sh FILES
+.Bl -tag -width ".Pa gmon.out" -compact
+.It Pa gmon.out
+execution data file
+.El
+.Sh SEE ALSO
+.Xr cc 1 ,
+.Xr gprof 1 ,
+.Xr profil 2
diff --git a/lib/nbsd_libc/hash/Makefile.inc b/lib/nbsd_libc/hash/Makefile.inc
new file mode 100644 (file)
index 0000000..3b5879a
--- /dev/null
@@ -0,0 +1,11 @@
+#      $NetBSD: Makefile.inc,v 1.11 2006/10/27 18:29:21 drochner Exp $
+#      $OpenBSD: Makefile.inc,v 1.5 1997/07/17 06:02:42 millert Exp $
+
+# hash functions
+.PATH: ${ARCHDIR}/hash ${.CURDIR}/hash
+
+.include "${.CURDIR}/hash/md2/Makefile.inc"
+.include "${.CURDIR}/hash/rmd160/Makefile.inc"
+.include "${.CURDIR}/hash/sha1/Makefile.inc"
+.include "${.CURDIR}/hash/sha2/Makefile.inc"
+
diff --git a/lib/nbsd_libc/hash/hashhl.c b/lib/nbsd_libc/hash/hashhl.c
new file mode 100644 (file)
index 0000000..2816407
--- /dev/null
@@ -0,0 +1,145 @@
+/* $NetBSD: hashhl.c,v 1.4 2010/01/17 23:10:20 wiz Exp $ */
+
+/*
+ * ----------------------------------------------------------------------------
+ * "THE BEER-WARE LICENSE" (Revision 42):
+ * <phk@login.dkuug.dk> 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.   Poul-Henning Kamp
+ * ----------------------------------------------------------------------------
+ */
+
+/*
+ * Modified September 24, 2005 by Elad Efrat <elad@NetBSD.org>
+ * Modified April 29, 1997 by Jason R. Thorpe <thorpej@NetBSD.org>
+ */
+
+#ifdef HASH_ALGORITHM
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+/*
+ * Do all the name mangling before we include "namespace.h"
+ */
+#define        CONCAT(x,y)     __CONCAT(x,y)
+
+#ifndef HASH_FNPREFIX
+#define        HASH_FNPREFIX   HASH_ALGORITHM
+#endif /* !HASH_FNPREFIX */
+
+#define        FNPREFIX(x)     CONCAT(HASH_FNPREFIX,x)
+#define        HASH_CTX        CONCAT(HASH_ALGORITHM,_CTX)
+#define        HASH_LEN        CONCAT(HASH_ALGORITHM,_DIGEST_LENGTH)
+#define        HASH_STRLEN     CONCAT(HASH_ALGORITHM,_DIGEST_STRING_LENGTH)
+
+#if !defined(_KERNEL) && defined(__weak_alias) && !defined(HAVE_NBTOOL_CONFIG_H)
+#define        WA(a,b) __weak_alias(a,b)
+WA(FNPREFIX(End),CONCAT(_,FNPREFIX(End)))
+WA(FNPREFIX(FileChunk),CONCAT(_,FNPREFIX(FileChunk)))
+WA(FNPREFIX(File),CONCAT(_,FNPREFIX(File)))
+WA(FNPREFIX(Data),CONCAT(_,FNPREFIX(Data)))
+#undef WA
+#endif
+
+#include "namespace.h"
+#include HASH_INCLUDE
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#ifndef MIN
+#define        MIN(x,y)        ((x)<(y)?(x):(y))
+#endif /* !MIN */
+
+
+char *
+FNPREFIX(End)(HASH_CTX *ctx, char *buf)
+{
+       int i;
+       unsigned char digest[HASH_LEN];
+       static const char hex[]="0123456789abcdef";
+
+       _DIAGASSERT(ctx != 0);
+
+       if (buf == NULL)
+               buf = malloc((size_t)HASH_STRLEN);
+       if (buf == NULL)
+               return (NULL);
+
+       FNPREFIX(Final)(digest, ctx);
+
+       for (i = 0; i < HASH_LEN; i++) {
+               buf[i+i] = hex[(u_int32_t)digest[i] >> 4];
+               buf[i+i+1] = hex[digest[i] & 0x0f];
+       }
+
+       buf[i+i] = '\0';
+       return (buf);
+}
+
+char *
+FNPREFIX(FileChunk)(const char *filename, char *buf, off_t off, off_t len)
+{
+       struct stat sb;
+       u_char buffer[BUFSIZ];
+       HASH_CTX ctx;
+       int fd, save_errno;
+       ssize_t nr;
+
+       FNPREFIX(Init)(&ctx);
+
+       if ((fd = open(filename, O_RDONLY)) < 0)
+               return (NULL);
+       if (len == 0) {
+               if (fstat(fd, &sb) == -1) {
+                       close(fd);
+                       return (NULL);
+               }
+               len = sb.st_size;
+       }
+       if (off > 0 && lseek(fd, off, SEEK_SET) < 0) {
+               close(fd);
+               return (NULL);
+       }
+
+       while ((nr = read(fd, buffer, (size_t) MIN((off_t)sizeof(buffer), len)))
+           > 0) {
+               FNPREFIX(Update)(&ctx, buffer, (unsigned int)nr);
+               if (len > 0 && (len -= nr) == 0)
+                       break;
+       }
+
+       save_errno = errno;
+       close(fd);
+       errno = save_errno;
+       return (nr < 0 ? NULL : FNPREFIX(End)(&ctx, buf));
+}
+
+char *
+FNPREFIX(File)(const char *filename, char *buf)
+{
+       return (FNPREFIX(FileChunk)(filename, buf, (off_t)0, (off_t)0));
+}
+
+char *
+FNPREFIX(Data)(const unsigned char *data, size_t len, char *buf)
+{
+       HASH_CTX ctx;
+
+       _DIAGASSERT(data != 0);
+
+       FNPREFIX(Init)(&ctx);
+       FNPREFIX(Update)(&ctx, data, (unsigned int)len);
+       return (FNPREFIX(End)(&ctx, buf));
+}
+
+#endif /* HASH_ALGORITHM */
diff --git a/lib/nbsd_libc/hash/md2/Makefile.inc b/lib/nbsd_libc/hash/md2/Makefile.inc
new file mode 100644 (file)
index 0000000..8e1adf5
--- /dev/null
@@ -0,0 +1,12 @@
+# $NetBSD: Makefile.inc,v 1.1 2005/09/24 20:51:14 elad Exp $
+
+# hash functions
+.PATH: ${.CURDIR}/hash/md2
+
+SRCS+= md2.c md2hl.c
+
+MAN+=  md2.3
+
+MLINKS+=md2.3 MD2Init.3 md2.3 MD2Update.3 md2.3 MD2Final.3
+MLINKS+=md2.3 MD2End.3  md2.3 MD2File.3   md2.3 MD2Data.3
+MLINKS+=md2.3 MD2Transform.3  md2.3 MD2FileChunk.3
diff --git a/lib/nbsd_libc/hash/md2/md2.3 b/lib/nbsd_libc/hash/md2/md2.3
new file mode 100644 (file)
index 0000000..e6f819c
--- /dev/null
@@ -0,0 +1,123 @@
+.\" $NetBSD: md2.3,v 1.1 2005/09/24 20:51:14 elad Exp $
+.\"
+.\" ----------------------------------------------------------------------------
+.\" "THE BEER-WARE LICENSE" (Revision 42):
+.\" <phk@login.dkuug.dk> 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.   Poul-Henning Kamp
+.\" ----------------------------------------------------------------------------
+.\"
+.\"    from FreeBSD Id: mdX.3,v 1.7 1996/10/22 16:28:56 phk Exp
+.\"
+.Dd September 24, 2005
+.Dt MD2 3
+.Os
+.Sh NAME
+.Nm MD2Init ,
+.Nm MD2Update ,
+.Nm MD2Final ,
+.Nm MD2End ,
+.Nm MD2File ,
+.Nm MD2Data
+.Nd calculate the RSA Data Security, Inc.,
+.Dq MD2
+message digest
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In mdX.h
+.Ft void
+.Fn MD2Init "MD2_CTX *context"
+.Ft void
+.Fn MD2Update "MD2_CTX *context" "const unsigned char *data" "unsigned int len"
+.Ft void
+.Fn MD2Final "unsigned char digest[16]" "MD2_CTX *context"
+.Ft "char *"
+.Fn MD2End "MD2_CTX *context" "char *buf"
+.Ft "char *"
+.Fn MD2File "const char *filename" "char *buf"
+.Ft "char *"
+.Fn MD2Data "const unsigned char *data" "unsigned int len" "char *buf"
+.Sh DESCRIPTION
+The MD2 functions calculate a 128-bit cryptographic checksum (digest)
+for any number of input bytes.
+A cryptographic checksum is a one-way
+hash-function, that is, you cannot find (except by exhaustive search)
+the input corresponding to a particular output.
+This net result is
+a ``fingerprint'' of the input-data, which doesn't disclose the actual
+input.
+.Pp
+The MD2 routines should not be used for any security-related purpose.
+.Pp
+The
+.Fn MD2Init ,
+.Fn MD2Update ,
+and
+.Fn MD2Final
+functions are the core functions.
+Allocate an MD2_CTX, initialize it with
+.Fn MD2Init ,
+run over the data with
+.Fn MD2Update ,
+and finally extract the result using
+.Fn MD2Final .
+.Pp
+.Fn MD2End
+is a wrapper for
+.Fn MD2Final
+which converts the return value to a 33-character
+(including the terminating '\e0')
+.Tn ASCII
+string which represents the 128 bits in hexadecimal.
+.Pp
+.Fn MD2File
+calculates the digest of a file, and uses
+.Fn MD2End
+to return the result.
+If the file cannot be opened, a null pointer is returned.
+.Fn MD2Data
+calculates the digest of a chunk of data in memory, and uses
+.Fn MD2End
+to return the result.
+.Pp
+When using
+.Fn MD2End ,
+.Fn MD2File ,
+or
+.Fn MD2Data ,
+the
+.Ar buf
+argument can be a null pointer, in which case the returned string
+is allocated with
+.Xr malloc 3
+and subsequently must be explicitly deallocated using
+.Xr free 3
+after use.
+If the
+.Ar buf
+argument is non-null it must point to at least 33 characters of buffer space.
+.Sh SEE ALSO
+.Xr md2 3 ,
+.Rs
+.%A B. Kaliski
+.%T The MD2 Message-Digest Algorithm
+.%O RFC 1319
+.Re
+.Rs
+.%A RSA Laboratories
+.%T Frequently Asked Questions About today's Cryptography
+.Re
+.Sh HISTORY
+These functions appeared in
+.Nx 1.3 .
+.Sh AUTHORS
+The original MD2 routines were developed by
+.Tn RSA
+Data Security, Inc., and published in the above references.
+This code is a public domain implementation by Andrew Brown.
+.Sh BUGS
+No method is known to exist which finds two files having the same hash value,
+nor to find a file with a specific hash value.
+There is on the other hand no guarantee that such a method doesn't exist.
diff --git a/lib/nbsd_libc/hash/md2/md2.c b/lib/nbsd_libc/hash/md2/md2.c
new file mode 100644 (file)
index 0000000..8e6367c
--- /dev/null
@@ -0,0 +1,191 @@
+/*     $NetBSD: md2.c,v 1.5 2008/04/28 20:23:00 martin Exp $   */
+
+/*
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Andrew Brown.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: md2.c,v 1.5 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+
+#include <assert.h>
+#include <md2.h>
+#include <string.h>
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#if !HAVE_MD2_H
+
+/* cut-n-pasted from rfc1319 */
+static unsigned char S[256] = {
+       41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6,
+       19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188,
+       76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24,
+       138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251,
+       245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63,
+       148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50,
+       39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165,
+       181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210,
+       150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157,
+       112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27,
+       96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15,
+       85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197,
+       234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65,
+       129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123,
+       8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233,
+       203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228,
+       166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237,
+       31, 26, 219, 153, 141, 51, 159, 17, 131, 20
+};
+
+/* cut-n-pasted from rfc1319 */
+static const unsigned char *pad[] = {
+       (const unsigned char *)"",
+       (const unsigned char *)"\001",
+       (const unsigned char *)"\002\002",
+       (const unsigned char *)"\003\003\003",
+       (const unsigned char *)"\004\004\004\004",
+       (const unsigned char *)"\005\005\005\005\005",
+       (const unsigned char *)"\006\006\006\006\006\006",
+       (const unsigned char *)"\007\007\007\007\007\007\007",
+       (const unsigned char *)"\010\010\010\010\010\010\010\010",
+       (const unsigned char *)"\011\011\011\011\011\011\011\011\011",
+       (const unsigned char *)"\012\012\012\012\012\012\012\012\012\012",
+       (const unsigned char *)"\013\013\013\013\013\013\013\013\013\013\013",
+       (const unsigned char *)
+       "\014\014\014\014\014\014\014\014\014\014\014\014",
+       (const unsigned char *)
+       "\015\015\015\015\015\015\015\015\015\015\015\015\015",
+       (const unsigned char *)
+       "\016\016\016\016\016\016\016\016\016\016\016\016\016\016",
+       (const unsigned char *)
+       "\017\017\017\017\017\017\017\017\017\017\017\017\017\017\017",
+       (const unsigned char *)
+       "\020\020\020\020\020\020\020\020\020\020\020\020\020\020\020\020"
+};
+
+/*
+ * XXX This should not be visible, but due to an accident, it is
+ * XXX so it must remain so.
+ */
+/*static*/ void MD2Transform __P((MD2_CTX *));
+
+#ifdef __weak_alias
+__weak_alias(MD2Init,_MD2Init)
+__weak_alias(MD2Update,_MD2Update)
+__weak_alias(MD2Final,_MD2Final)
+__weak_alias(MD2Transform,_MD2Transform)
+#endif
+
+void
+MD2Init(context)
+       MD2_CTX *context;
+{
+       _DIAGASSERT(context != 0);
+
+       context->i = 16;
+       memset(&context->C[0], 0, sizeof(context->C));
+       memset(&context->X[0], 0, sizeof(context->X));
+}
+
+void
+MD2Update(context, input, inputLen)
+       MD2_CTX *context;
+       const unsigned char *input;
+       unsigned int inputLen;
+{
+       unsigned int idx, piece;
+
+       _DIAGASSERT(context != 0);
+       _DIAGASSERT(input != 0);
+
+       for (idx = 0; idx < inputLen; idx += piece) {
+               piece = 32 - context->i;
+               if ((inputLen - idx) < piece)
+                       piece = inputLen - idx;
+               memcpy(&context->X[context->i], &input[idx], (size_t)piece);
+               if ((context->i += piece) == 32)
+                       MD2Transform(context); /* resets i */
+       }
+}
+
+void
+MD2Final(digest, context)
+       unsigned char digest[16];       /* message digest */
+       MD2_CTX *context;               /* context */
+{
+       unsigned int padlen;
+
+       _DIAGASSERT(digest != 0);
+       _DIAGASSERT(context != 0);
+
+       /* padlen should be 1..16 */
+       padlen = 32 - context->i;
+
+       /* add padding */
+       MD2Update(context, pad[padlen], padlen);
+
+       /* add checksum */
+       MD2Update(context, &context->C[0], (unsigned int) sizeof(context->C));
+
+       /* copy out final digest */
+       memcpy(digest, &context->X[0], (size_t)16);
+
+       /* reset the context */
+       MD2Init(context);
+}
+
+/*static*/ void
+MD2Transform(context)
+       MD2_CTX *context;
+{
+       u_int32_t l, j, k, t;
+
+       /* set block "3" and update "checksum" */
+       for (l = context->C[15], j = 0; j < 16; j++) {
+               context->X[32 + j] = context->X[j] ^ context->X[16 + j];
+               l = context->C[j] ^= S[context->X[16 + j] ^ l];
+       }
+
+       /* mangle input block */
+       for (t = j = 0; j < 18; t = (t + j) % 256, j++)
+               for (k = 0; k < 48; k++)
+                       t = context->X[k] = (context->X[k] ^ S[t]);
+
+       /* reset input pointer */
+       context->i = 16;
+}
+
+#endif /* !HAVE_MD2_H */
diff --git a/lib/nbsd_libc/hash/md2/md2hl.c b/lib/nbsd_libc/hash/md2/md2hl.c
new file mode 100644 (file)
index 0000000..64eb2be
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: md2hl.c,v 1.4 2008/04/13 02:04:31 dholland Exp $ */
+
+/*
+ * Derived from code written by Jason R. Thorpe <thorpej@NetBSD.org>,
+ * April 29, 1997.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: md2hl.c,v 1.4 2008/04/13 02:04:31 dholland Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define        HASH_ALGORITHM  MD2
+#define HASH_INCLUDE   <md2.h>
+
+#include "../hashhl.c"
diff --git a/lib/nbsd_libc/hash/rmd160/Makefile.inc b/lib/nbsd_libc/hash/rmd160/Makefile.inc
new file mode 100644 (file)
index 0000000..0caf265
--- /dev/null
@@ -0,0 +1,13 @@
+# $NetBSD: Makefile.inc,v 1.1 2005/09/24 19:04:52 elad Exp $
+
+# hash functions
+.PATH: ${.CURDIR}/hash/rmd160
+
+SRCS+= rmd160.c rmd160hl.c
+
+MAN+=  rmd160.3
+
+MLINKS+=rmd160.3 RMD160Init.3    rmd160.3 RMD160Update.3
+MLINKS+=rmd160.3 RMD160Final.3   rmd160.3 RMD160Transform.3
+MLINKS+=rmd160.3 RMD160End.3     rmd160.3 RMD160File.3
+MLINKS+=rmd160.3 RMD160Data.3
diff --git a/lib/nbsd_libc/hash/rmd160/rmd160.3 b/lib/nbsd_libc/hash/rmd160/rmd160.3
new file mode 100644 (file)
index 0000000..f9d64e0
--- /dev/null
@@ -0,0 +1,225 @@
+.\"    $NetBSD: rmd160.3,v 1.3 2010/04/05 21:26:30 joerg Exp $
+.\"    $OpenBSD: rmd160.3,v 1.12 2000/04/18 03:01:29 aaron Exp $
+.\"
+.\" Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
+.\" 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.
+.\" 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 ``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 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.
+.\"
+.\" See http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html
+.\"    for detailed information about RIPEMD-160.
+.\"
+.Dd July 16, 1997
+.Dt RMD160 3
+.Os
+.Sh NAME
+.Nm RMD160Init ,
+.Nm RMD160Update ,
+.Nm RMD160Final ,
+.Nm RMD160Transform ,
+.Nm RMD160End ,
+.Nm RMD160File ,
+.Nm RMD160Data
+.Nd calculate the ``RIPEMD-160'' message digest
+.Sh SYNOPSIS
+.In sys/types.h
+.In rmd160.h
+.Ft void
+.Fn RMD160Init "RMD160_CTX *context"
+.Ft void
+.Fn RMD160Update "RMD160_CTX *context" "const u_char *data" "u_int nbytes"
+.Ft void
+.Fn RMD160Final "u_char digest[20]" "RMD160_CTX *context"
+.Ft void
+.Fn RMD160Transform "uint32_t state[5]" "const uint32_t block[16]"
+.Ft "char *"
+.Fn RMD160End "RMD160_CTX *context" "char *buf"
+.Ft "char *"
+.Fn RMD160File "char *filename" "char *buf"
+.Ft "char *"
+.Fn RMD160Data "u_char *data" "size_t len" "char *buf"
+.Sh DESCRIPTION
+The RMD160 functions implement the 160-bit RIPE message digest hash algorithm
+(RMD-160).
+RMD-160 is used to generate a condensed representation
+of a message called a message digest.
+The algorithm takes a
+message less than 2^64 bits as input and produces a 160-bit digest
+suitable for use as a digital signature.
+.Pp
+The RMD160 functions are considered to be more secure than the
+.Xr md4 3
+and
+.Xr md5 3
+functions and at least as secure as the
+.Xr sha1 3
+function.
+All share a similar interface.
+.Pp
+The
+.Fn RMD160Init
+function initializes a RMD160_CTX
+.Ar context
+for use with
+.Fn RMD160Update ,
+and
+.Fn RMD160Final .
+The
+.Fn RMD160Update
+function adds
+.Ar data
+of length
+.Ar nbytes
+to the RMD160_CTX specified by
+.Ar context .
+.Fn RMD160Final
+is called when all data has been added via
+.Fn RMD160Update
+and stores a message digest in the
+.Ar digest
+parameter.
+When a null pointer is passed to
+.Fn RMD160Final
+as first argument only the final padding will be applied and the
+current context can still be used with
+.Fn RMD160Update .
+.Pp
+The
+.Fn RMD160Transform
+function is used by
+.Fn RMD160Update
+to hash 512-bit blocks and forms the core of the algorithm.
+Most programs should use the interface provided by
+.Fn RMD160Init ,
+.Fn RMD160Update
+and
+.Fn RMD160Final
+instead of calling
+.Fn RMD160Transform
+directly.
+.Pp
+The
+.Fn RMD160End
+function is a front end for
+.Fn RMD160Final
+which converts the digest into an
+.Tn ASCII
+representation of the 160 bit digest in hexadecimal.
+.Pp
+The
+.Fn RMD160File
+function calculates the digest for a file and returns the result via
+.Fn RMD160End .
+If
+.Fn RMD160File
+is unable to open the file a NULL pointer is returned.
+.Pp
+The
+.Fn RMD160Data
+function
+calculates the digest of an arbitrary string and returns the result via
+.Fn RMD160End .
+.Pp
+For each of the
+.Fn RMD160End ,
+.Fn RMD160File ,
+and
+.Fn RMD160Data
+functions the
+.Ar buf
+parameter should either be a string of at least 41 characters in
+size or a NULL pointer.
+In the latter case, space will be dynamically allocated via
+.Xr malloc 3
+and should be freed using
+.Xr free 3
+when it is no longer needed.
+.Sh EXAMPLES
+The follow code fragment will calculate the digest for
+the string "abc" which is ``0x8eb208f7e05d987a9b044a8e98c6b087f15a0bfc''.
+.Bd -literal -offset indent
+RMD160_CTX rmd;
+u_char results[20];
+char *buf;
+int n;
+
+buf = "abc";
+n = strlen(buf);
+RMD160Init(\*[Am]rmd);
+RMD160Update(\*[Am]rmd, (u_char *)buf, n);
+RMD160Final(results, \*[Am]rmd);
+
+/* Print the digest as one long hex value */
+printf("0x");
+for (n = 0; n \*[Lt] 20; n++)
+       printf("%02x", results[n]);
+putchar('\en');
+.Ed
+.Pp
+Alternately, the helper functions could be used in the following way:
+.Bd -literal -offset indent
+RMD160_CTX rmd;
+u_char output[41];
+char *buf = "abc";
+
+printf("0x%s\en", RMD160Data(buf, strlen(buf), output));
+.Ed
+.Sh SEE ALSO
+.Xr rmd160 1 ,
+.Xr md4 3 ,
+.Xr md5 3 ,
+.Xr sha1 3
+.Pp
+.Rs
+.%A H. Dobbertin, A. Bosselaers, B. Preneel
+.%T RIPEMD-160, a strengthened version of RIPEMD
+.Re
+.Rs
+.%T Information technology - Security techniques - Hash-functions - Part 3: Dedicated hash-functions
+.%O ISO/IEC 10118-3
+.Re
+.Rs
+.%A H. Dobbertin, A. Bosselaers, B. Preneel
+.%T The RIPEMD-160 cryptographic hash function
+.%J Dr. Dobb's Journal
+.%V Vol. 22, No. 1
+.%D January 1997
+.%P pp. 24-28
+.Re
+.Sh HISTORY
+The RMD-160 functions appeared in
+.Ox 2.1 .
+.Sh AUTHORS
+This implementation of RMD-160 was written by Antoon Bosselaers.
+.Pp
+The
+.Fn RMD160End ,
+.Fn RMD160File ,
+and
+.Fn RMD160Data
+helper functions are derived from code written by Poul-Henning Kamp.
+.Sh BUGS
+If a message digest is to be copied to a multi-byte type (ie:
+an array of five 32-bit integers) it will be necessary to
+perform byte swapping on little endian machines such as the i386, alpha,
+and VAX.
diff --git a/lib/nbsd_libc/hash/rmd160/rmd160hl.c b/lib/nbsd_libc/hash/rmd160/rmd160hl.c
new file mode 100644 (file)
index 0000000..85cc837
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: rmd160hl.c,v 1.6 2008/04/13 02:04:32 dholland Exp $ */
+
+/*
+ * Derived from code written by Jason R. Thorpe <thorpej@NetBSD.org>,
+ * April 29, 1997.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: rmd160hl.c,v 1.6 2008/04/13 02:04:32 dholland Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define        HASH_ALGORITHM  RMD160
+#define HASH_INCLUDE   <sys/rmd160.h>
+
+#include "../hashhl.c"
diff --git a/lib/nbsd_libc/hash/sha1/Makefile.inc b/lib/nbsd_libc/hash/sha1/Makefile.inc
new file mode 100644 (file)
index 0000000..99c35cf
--- /dev/null
@@ -0,0 +1,12 @@
+# $NetBSD: Makefile.inc,v 1.2 2006/10/27 18:29:21 drochner Exp $
+
+# hash functions
+.PATH: ${.CURDIR}/hash/sha1
+
+SRCS+= sha1.c sha1hl.c
+
+MAN+=  sha1.3
+
+MLINKS+=sha1.3 SHA1Init.3 sha1.3 SHA1Update.3 sha1.3 SHA1Final.3
+MLINKS+=sha1.3 SHA1End.3  sha2.3 SHA1File.3   sha1.3 SHA1Data.3
+MLINKS+=sha1.3 SHA1Transform.3  sha1.3 SHA1FileChunk.3
diff --git a/lib/nbsd_libc/hash/sha1/sha1.3 b/lib/nbsd_libc/hash/sha1/sha1.3
new file mode 100644 (file)
index 0000000..762fd03
--- /dev/null
@@ -0,0 +1,203 @@
+.\"    $NetBSD: sha1.3,v 1.6 2010/04/05 21:27:01 joerg Exp $
+.\"    $OpenBSD: sha1.3,v 1.9 1998/03/07 22:18:12 millert Exp $
+.\"
+.\" Copyright (c) 1997, 2004 Todd C. Miller <Todd.Miller@courtesan.com>
+.\"
+.\" 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.
+.\"
+.\" See http://csrc.nist.gov/fips/fip180-1.txt for the detailed standard
+.\"
+.Dd July 10, 1997
+.Dt SHA1 3
+.Os
+.Sh NAME
+.Nm SHA1Init ,
+.Nm SHA1Update ,
+.Nm SHA1Final ,
+.Nm SHA1Transform ,
+.Nm SHA1End ,
+.Nm SHA1File ,
+.Nm SHA1Data
+.Nd calculate the NIST Secure Hash Algorithm
+.Sh SYNOPSIS
+.In sys/types.h
+.In sha1.h
+.Ft void
+.Fn SHA1Init "SHA1_CTX *context"
+.Ft void
+.Fn SHA1Update "SHA1_CTX *context" "const uint8_t *data" "u_int len"
+.Ft void
+.Fn SHA1Final "uint8_t digest[20]" "SHA1_CTX *context"
+.Ft void
+.Fn SHA1Transform "uint32_t state[5]" "uint8_t buffer[64]"
+.Ft "char *"
+.Fn SHA1End "SHA1_CTX *context" "char *buf"
+.Ft "char *"
+.Fn SHA1File "char *filename" "char *buf"
+.Ft "char *"
+.Fn SHA1Data "uint8_t *data" "size_t len" "char *buf"
+.Sh DESCRIPTION
+The SHA1 functions implement the NIST Secure Hash Algorithm (SHA-1),
+FIPS PUB 180-1.
+SHA-1 is used to generate a condensed representation
+of a message called a message digest.
+The algorithm takes a
+message less than 2^64 bits as input and produces a 160-bit digest
+suitable for use as a digital signature.
+.Pp
+The SHA1 functions are considered to be more secure than the
+.Xr md4 3
+and
+.Xr md5 3
+functions with which they share a similar interface.
+.Pp
+The
+.Fn SHA1Init
+function initializes a SHA1_CTX
+.Ar context
+for use with
+.Fn SHA1Update ,
+and
+.Fn SHA1Final .
+The
+.Fn SHA1Update
+function adds
+.Ar data
+of length
+.Ar len
+to the SHA1_CTX specified by
+.Ar context .
+.Fn SHA1Final
+is called when all data has been added via
+.Fn SHA1Update
+and stores a message digest in the
+.Ar digest
+parameter.
+When a null pointer is passed to
+.Fn SHA1Final
+as first argument only the final padding will be applied and the
+current context can still be used with
+.Fn SHA1Update .
+.Pp
+The
+.Fn SHA1Transform
+function is used by
+.Fn SHA1Update
+to hash 512-bit blocks and forms the core of the algorithm.
+Most programs should use the interface provided by
+.Fn SHA1Init ,
+.Fn SHA1Update
+and
+.Fn SHA1Final
+instead of calling
+.Fn SHA1Transform
+directly.
+.Pp
+The
+.Fn SHA1End
+function is a front end for
+.Fn SHA1Final
+which converts the digest into an
+.Tn ASCII
+representation of the 160 bit digest in hexadecimal.
+.Pp
+The
+.Fn SHA1File
+function calculates the digest for a file and returns the result via
+.Fn SHA1End .
+If
+.Fn SHA1File
+is unable to open the file a NULL pointer is returned.
+.Pp
+The
+.Fn SHA1Data
+function
+calculates the digest of an arbitrary string and returns the result via
+.Fn SHA1End .
+.Pp
+For each of the
+.Fn SHA1End ,
+.Fn SHA1File ,
+and
+.Fn SHA1Data
+functions the
+.Ar buf
+parameter should either be a string of at least 41 characters in
+size or a NULL pointer.
+In the latter case, space will be dynamically
+allocated via
+.Xr malloc 3
+and should be freed using
+.Xr free 3
+when it is no longer needed.
+.Sh EXAMPLES
+The follow code fragment will calculate the digest for
+the string "abc" which is ``0xa9993e36476816aba3e25717850c26c9cd0d89d''.
+.Bd -literal -offset indent
+SHA1_CTX sha;
+uint8_t results[20];
+char *buf;
+int n;
+
+buf = "abc";
+n = strlen(buf);
+SHA1Init(\*[Am]sha);
+SHA1Update(\*[Am]sha, (uint8_t *)buf, n);
+SHA1Final(results, \*[Am]sha);
+
+/* Print the digest as one long hex value */
+printf("0x");
+for (n = 0; n \*[Lt] 20; n++)
+       printf("%02x", results[n]);
+putchar('\en');
+.Ed
+.Pp
+Alternately, the helper functions could be used in the following way:
+.Bd -literal -offset indent
+SHA1_CTX sha;
+uint8_t output[41];
+char *buf = "abc";
+
+printf("0x%s", SHA1Data(buf, strlen(buf), output));
+.Ed
+.Sh SEE ALSO
+.\"    .Xr sha1 1 ,
+.Xr md5 1 ,
+.Xr md4 3 ,
+.Xr md5 3
+.Pp
+.Rs
+.%A J. Burrows
+.%T The Secure Hash Standard
+.%O FIPS PUB 180-1
+.Re
+.Sh HISTORY
+The SHA-1 functions appeared in
+.Nx 1.4 .
+.Sh AUTHORS
+This implementation of SHA-1 was written by Steve Reid.
+.Pp
+The
+.Fn SHA1End ,
+.Fn SHA1File ,
+and
+.Fn SHA1Data
+helper functions are derived from code written by Poul-Henning Kamp.
+.Sh BUGS
+This implementation of SHA-1 has not been validated by NIST
+and as such is not in official compliance with the standard.
+.Pp
+If a message digest is to be copied to a multi-byte type (ie:
+an array of five 32-bit integers) it will be necessary to
+perform byte swapping on little endian machines such as the i386, alpha,
+and VAX.
diff --git a/lib/nbsd_libc/hash/sha1/sha1hl.c b/lib/nbsd_libc/hash/sha1/sha1hl.c
new file mode 100644 (file)
index 0000000..a73f4df
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: sha1hl.c,v 1.4 2008/04/13 02:04:32 dholland Exp $ */
+
+/*
+ * Derived from code written by Jason R. Thorpe <thorpej@NetBSD.org>,
+ * April 29, 1997.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sha1hl.c,v 1.4 2008/04/13 02:04:32 dholland Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define        HASH_ALGORITHM  SHA1
+#define HASH_INCLUDE   <sha1.h>
+
+#include "../hashhl.c"
diff --git a/lib/nbsd_libc/hash/sha2/Makefile.inc b/lib/nbsd_libc/hash/sha2/Makefile.inc
new file mode 100644 (file)
index 0000000..4d13c2f
--- /dev/null
@@ -0,0 +1,21 @@
+#      $NetBSD: Makefile.inc,v 1.4 2009/05/26 08:04:11 joerg Exp $
+
+# hash functions
+.PATH: ${.CURDIR}/hash/sha2
+
+SRCS+= sha2.c sha224hl.c sha256hl.c sha384hl.c sha512hl.c
+
+MAN+=  sha2.3
+
+MLINKS+=sha2.3 SHA224_Init.3 sha2.3 SHA224_Update.3 sha2.3 SHA224_Final.3
+MLINKS+=sha2.3 SHA224_End.3  sha2.3 SHA224_File.3   sha2.3 SHA224_Data.3
+MLINKS+=sha2.3 SHA224_Transform.3  sha2.3 SHA224_FileChunk.3
+MLINKS+=sha2.3 SHA256_Init.3 sha2.3 SHA256_Update.3 sha2.3 SHA256_Final.3
+MLINKS+=sha2.3 SHA256_End.3  sha2.3 SHA256_File.3   sha2.3 SHA256_Data.3
+MLINKS+=sha2.3 SHA256_Transform.3  sha2.3 SHA256_FileChunk.3
+MLINKS+=sha2.3 SHA384_Init.3 sha2.3 SHA384_Update.3 sha2.3 SHA384_Final.3
+MLINKS+=sha2.3 SHA384_End.3  sha2.3 SHA384_File.3   sha2.3 SHA384_Data.3
+MLINKS+=sha2.3 SHA384_Transform.3  sha2.3 SHA384_FileChunk.3
+MLINKS+=sha2.3 SHA512_Init.3 sha2.3 SHA512_Update.3 sha2.3 SHA512_Final.3
+MLINKS+=sha2.3 SHA512_End.3  sha2.3 SHA512_File.3   sha2.3 SHA512_Data.3
+MLINKS+=sha2.3 SHA512_Transform.3  sha2.3 SHA512_FileChunk.3
diff --git a/lib/nbsd_libc/hash/sha2/sha2.3 b/lib/nbsd_libc/hash/sha2/sha2.3
new file mode 100644 (file)
index 0000000..8192cf5
--- /dev/null
@@ -0,0 +1,304 @@
+.\" $NetBSD: sha2.3,v 1.5 2009/05/26 08:04:12 joerg Exp $
+.\"    $OpenBSD: sha2.3,v 1.11 2004/06/22 01:57:29 jfb Exp $
+.\"
+.\" Copyright (c) 2003, 2004 Todd C. Miller <Todd.Miller@courtesan.com>
+.\"
+.\" 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.
+.\"
+.\" Sponsored in part by the Defense Advanced Research Projects
+.\" Agency (DARPA) and Air Force Research Laboratory, Air Force
+.\" Materiel Command, USAF, under agreement number F39502-99-1-0512.
+.\"
+.\" See http://www.nist.gov/sha/ for the detailed standard
+.\"
+.Dd May 20, 2009
+.Dt SHA2 3
+.Os
+.Sh NAME
+.Nm SHA256_Init ,
+.Nm SHA256_Update ,
+.Nm SHA256_Pad ,
+.Nm SHA256_Final ,
+.Nm SHA256_Transform ,
+.Nm SHA256_End ,
+.Nm SHA256_File ,
+.Nm SHA256_FileChunk ,
+.Nm SHA256_Data
+.Nd calculate the NIST Secure Hash Standard (version 2)
+.Sh SYNOPSIS
+.In sys/types.h
+.In sha2.h
+.Ft void
+.Fn SHA224_Init "SHA224_CTX *context"
+.Ft void
+.Fn SHA224_Update "SHA224_CTX *context" "const uint8_t *data" "size_t len"
+.Ft void
+.Fn SHA224_Pad "SHA224_CTX *context"
+.Ft void
+.Fn SHA224_Final "uint8_t digest[SHA224_DIGEST_LENGTH]" "SHA224_CTX *context"
+.Ft void
+.Fn SHA224_Transform "uint32_t state[8]" "const uint8_t buffer[SHA224_BLOCK_LENGTH]"
+.Ft "char *"
+.Fn SHA224_End "SHA224_CTX *context" "char *buf"
+.Ft "char *"
+.Fn SHA224_File "const char *filename" "char *buf"
+.Ft "char *"
+.Fn SHA224_FileChunk "const char *filename" "char *buf" "off_t offset" "off_t length"
+.Ft "char *"
+.Fn SHA224_Data "uint8_t *data" "size_t len" "char *buf"
+.Ft void
+.Fn SHA256_Init "SHA256_CTX *context"
+.Ft void
+.Fn SHA256_Update "SHA256_CTX *context" "const uint8_t *data" "size_t len"
+.Ft void
+.Fn SHA256_Pad "SHA256_CTX *context"
+.Ft void
+.Fn SHA256_Final "uint8_t digest[SHA256_DIGEST_LENGTH]" "SHA256_CTX *context"
+.Ft void
+.Fn SHA256_Transform "uint32_t state[8]" "const uint8_t buffer[SHA256_BLOCK_LENGTH]"
+.Ft "char *"
+.Fn SHA256_End "SHA256_CTX *context" "char *buf"
+.Ft "char *"
+.Fn SHA256_File "const char *filename" "char *buf"
+.Ft "char *"
+.Fn SHA256_FileChunk "const char *filename" "char *buf" "off_t offset" "off_t length"
+.Ft "char *"
+.Fn SHA256_Data "uint8_t *data" "size_t len" "char *buf"
+.Ft void
+.Fn SHA384_Init "SHA384_CTX *context"
+.Ft void
+.Fn SHA384_Update "SHA384_CTX *context" "const uint8_t *data" "size_t len"
+.Ft void
+.Fn SHA384_Pad "SHA384_CTX *context"
+.Ft void
+.Fn SHA384_Final "uint8_t digest[SHA384_DIGEST_LENGTH]" "SHA384_CTX *context"
+.Ft void
+.Fn SHA384_Transform "uint64_t state[8]" "const uint8_t buffer[SHA384_BLOCK_LENGTH]"
+.Ft "char *"
+.Fn SHA384_End "SHA384_CTX *context" "char *buf"
+.Ft "char *"
+.Fn SHA384_File "char *filename" "char *buf"
+.Ft "char *"
+.Fn SHA384_FileChunk "char *filename" "char *buf" "off_t offset" "off_t length"
+.Ft "char *"
+.Fn SHA384_Data "uint8_t *data" "size_t len" "char *buf"
+.Ft void
+.Fn SHA512_Init "SHA512_CTX *context"
+.Ft void
+.Fn SHA512_Update "SHA512_CTX *context" "const uint8_t *data" "size_t len"
+.Ft void
+.Fn SHA512_Pad "SHA512_CTX *context"
+.Ft void
+.Fn SHA512_Final "uint8_t digest[SHA512_DIGEST_LENGTH]" "SHA512_CTX *context"
+.Ft void
+.Fn SHA512_Transform "uint64_t state[8]" "const uint8_t buffer[SHA512_BLOCK_LENGTH]"
+.Ft "char *"
+.Fn SHA512_End "SHA512_CTX *context" "char *buf"
+.Ft "char *"
+.Fn SHA512_File "char *filename" "char *buf"
+.Ft "char *"
+.Fn SHA512_FileChunk "char *filename" "char *buf" "off_t offset" "off_t length"
+.Ft "char *"
+.Fn SHA512_Data "uint8_t *data" "size_t len" "char *buf"
+.Sh DESCRIPTION
+The SHA2 functions implement the NIST Secure Hash Standard,
+FIPS PUB 180-2.
+The SHA2 functions are used to generate a condensed representation of a
+message called a message digest, suitable for use as a digital signature.
+There are four families of functions, with names corresponding to
+the number of bits in the resulting message digest.
+The SHA-224 and SHA-256 functions are limited to processing a message of less
+than 2^64 bits as input.
+The SHA-384 and SHA-512 functions can process a message of at most 2^128 - 1
+bits as input.
+.Pp
+The SHA2 functions are considered to be more secure than the
+.Xr sha1 3
+functions with which they share a similar interface.
+The 224, 256, 384, and 512-bit versions of SHA2 share the same interface.
+For brevity, only the 256-bit variants are described below.
+.Pp
+The
+.Fn SHA256_Init
+function initializes a SHA256_CTX
+.Ar context
+for use with
+.Fn SHA256_Update ,
+and
+.Fn SHA256_Final .
+The
+.Fn SHA256_Update
+function adds
+.Ar data
+of length
+.Ar len
+to the SHA256_CTX specified by
+.Ar context .
+.Fn SHA256_Final
+is called when all data has been added via
+.Fn SHA256_Update
+and stores a message digest in the
+.Ar digest
+parameter.
+.Pp
+The
+.Fn SHA256_Pad
+function can be used to apply padding to the message digest as in
+.Fn SHA256_Final ,
+but the current context can still be used with
+.Fn SHA256_Update .
+.Pp
+The
+.Fn SHA256_Transform
+function is used by
+.Fn SHA256_Update
+to hash 512-bit blocks and forms the core of the algorithm.
+Most programs should use the interface provided by
+.Fn SHA256_Init ,
+.Fn SHA256_Update ,
+and
+.Fn SHA256_Final
+instead of calling
+.Fn SHA256_Transform
+directly.
+.Pp
+The
+.Fn SHA256_End
+function is a front end for
+.Fn SHA256_Final
+which converts the digest into an
+.Tn ASCII
+representation of the digest in hexadecimal.
+.Pp
+The
+.Fn SHA256_File
+function calculates the digest for a file and returns the result via
+.Fn SHA256_End .
+If
+.Fn SHA256_File
+is unable to open the file, a
+.Dv NULL
+pointer is returned.
+.Pp
+.Fn SHA256_FileChunk
+behaves like
+.Fn SHA256_File
+but calculates the digest only for that portion of the file starting at
+.Fa offset
+and continuing for
+.Fa length
+bytes or until end of file is reached, whichever comes first.
+A zero
+.Fa length
+can be specified to read until end of file.
+A negative
+.Fa length
+or
+.Fa offset
+will be ignored.
+.Pp
+The
+.Fn SHA256_Data
+function
+calculates the digest of an arbitrary string and returns the result via
+.Fn SHA256_End .
+.Pp
+For each of the
+.Fn SHA256_End ,
+.Fn SHA256_File ,
+.Fn SHA256_FileChunk ,
+and
+.Fn SHA256_Data
+functions the
+.Ar buf
+parameter should either be a string large enough to hold the resulting digest
+(e.g.,
+.Ev SHA224_DIGEST_STRING_LENGTH ,
+.Ev SHA256_DIGEST_STRING_LENGTH ,
+.Ev SHA384_DIGEST_STRING_LENGTH ,
+or
+.Ev SHA512_DIGEST_STRING_LENGTH ,
+depending on the function being used)
+or a
+.Dv NULL
+pointer.
+In the latter case, space will be dynamically allocated via
+.Xr malloc 3
+and should be freed using
+.Xr free 3
+when it is no longer needed.
+.Sh EXAMPLES
+The following code fragment will calculate the SHA-256 digest for the string
+.Qq abc ,
+which is
+.Dq 0xba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad .
+.Bd -literal -offset indent
+SHA256_CTX ctx;
+uint8_t results[SHA256_DIGEST_LENGTH];
+char *buf;
+int n;
+
+buf = "abc";
+n = strlen(buf);
+SHA256_Init(\*[Am]ctx);
+SHA256_Update(\*[Am]ctx, (uint8_t *)buf, n);
+SHA256_Final(results, \*[Am]ctx);
+
+/* Print the digest as one long hex value */
+printf("0x");
+for (n = 0; n \*[Lt] SHA256_DIGEST_LENGTH; n++)
+       printf("%02x", results[n]);
+putchar('\en');
+.Ed
+.Pp
+Alternately, the helper functions could be used in the following way:
+.Bd -literal -offset indent
+SHA256_CTX ctx;
+uint8_t output[SHA256_DIGEST_STRING_LENGTH];
+char *buf = "abc";
+
+printf("0x%s\en", SHA256_Data(buf, strlen(buf), output));
+.Ed
+.Sh SEE ALSO
+.Xr cksum 1 ,
+.Xr md4 3 ,
+.Xr md5 3 ,
+.Xr rmd160 3 ,
+.Xr sha1 3
+.Rs
+.%T Secure Hash Standard
+.%O FIPS PUB 180-2
+.Re
+.Sh HISTORY
+The SHA2 functions appeared in
+.Ox 3.4
+and
+.Nx 3.0 .
+.Sh AUTHORS
+This implementation of the SHA functions was written by Aaron D. Gifford.
+.Pp
+The
+.Fn SHA256_End ,
+.Fn SHA256_File ,
+.Fn SHA256_FileChunk ,
+and
+.Fn SHA256_Data
+helper functions are derived from code written by Poul-Henning Kamp.
+.Sh CAVEATS
+This implementation of the Secure Hash Standard has not been validated by
+NIST and as such is not in official compliance with the standard.
+.Pp
+If a message digest is to be copied to a multi-byte type (i.e.:
+an array of five 32-bit integers) it will be necessary to
+perform byte swapping on little endian machines such as the i386, alpha,
+and vax.
diff --git a/lib/nbsd_libc/hash/sha2/sha224hl.c b/lib/nbsd_libc/hash/sha2/sha224hl.c
new file mode 100644 (file)
index 0000000..52f4bbf
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD */
+
+/*
+ * Derived from code written by Jason R. Thorpe <thorpej@NetBSD.org>,
+ * May 20, 2009.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: sha224hl.c,v 1.1 2009/05/26 08:04:12 joerg Exp $");
+
+#define        HASH_ALGORITHM  SHA224
+#define        HASH_FNPREFIX   SHA224_
+#define HASH_INCLUDE   <sys/sha2.h>
+
+#include "../hashhl.c"
diff --git a/lib/nbsd_libc/hash/sha2/sha256hl.c b/lib/nbsd_libc/hash/sha2/sha256hl.c
new file mode 100644 (file)
index 0000000..960f4da
--- /dev/null
@@ -0,0 +1,18 @@
+/* $NetBSD: sha256hl.c,v 1.8 2008/04/13 02:04:32 dholland Exp $ */
+
+/*
+ * Derived from code written by Jason R. Thorpe <thorpej@NetBSD.org>,
+ * April 29, 1997.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sha256hl.c,v 1.8 2008/04/13 02:04:32 dholland Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define        HASH_ALGORITHM  SHA256
+#define        HASH_FNPREFIX   SHA256_
+#define HASH_INCLUDE   <sys/sha2.h>
+
+#include "../hashhl.c"
diff --git a/lib/nbsd_libc/hash/sha2/sha384hl.c b/lib/nbsd_libc/hash/sha2/sha384hl.c
new file mode 100644 (file)
index 0000000..c503d8b
--- /dev/null
@@ -0,0 +1,18 @@
+/* $NetBSD: sha384hl.c,v 1.8 2008/04/13 02:04:32 dholland Exp $ */
+
+/*
+ * Derived from code written by Jason R. Thorpe <thorpej@NetBSD.org>,
+ * April 29, 1997.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sha384hl.c,v 1.8 2008/04/13 02:04:32 dholland Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define        HASH_ALGORITHM  SHA384
+#define        HASH_FNPREFIX   SHA384_
+#define HASH_INCLUDE   <sys/sha2.h>
+
+#include "../hashhl.c"
diff --git a/lib/nbsd_libc/hash/sha2/sha512hl.c b/lib/nbsd_libc/hash/sha2/sha512hl.c
new file mode 100644 (file)
index 0000000..bc46b16
--- /dev/null
@@ -0,0 +1,18 @@
+/* $NetBSD: sha512hl.c,v 1.8 2008/04/13 02:04:32 dholland Exp $ */
+
+/*
+ * Derived from code written by Jason R. Thorpe <thorpej@NetBSD.org>,
+ * April 29, 1997.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sha512hl.c,v 1.8 2008/04/13 02:04:32 dholland Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define        HASH_ALGORITHM  SHA512
+#define        HASH_FNPREFIX   SHA512_
+#define HASH_INCLUDE   <sys/sha2.h>
+
+#include "../hashhl.c"
diff --git a/lib/nbsd_libc/iconv/Makefile.inc b/lib/nbsd_libc/iconv/Makefile.inc
new file mode 100644 (file)
index 0000000..723bf38
--- /dev/null
@@ -0,0 +1,13 @@
+#      $NetBSD: Makefile.inc,v 1.4 2009/01/11 02:46:28 christos Exp $
+
+.PATH: ${ARCHDIR}/iconv ${.CURDIR}/iconv
+
+SRCS+= iconv.c
+MAN+=  iconv.3
+MLINKS+=iconv.3 iconv_open.3 iconv.3 iconv_close.3
+
+.if ${CITRUS} == "yes"
+CPPFLAGS.iconv.c+=     -DHAVE_CITRUS -I${LIBCDIR}/citrus
+.else
+CPPFLAGS.iconv.c+=     -UHAVE_CITRUS
+.endif
diff --git a/lib/nbsd_libc/iconv/iconv.3 b/lib/nbsd_libc/iconv/iconv.3
new file mode 100644 (file)
index 0000000..b43934a
--- /dev/null
@@ -0,0 +1,244 @@
+.\" $NetBSD: iconv.3,v 1.14 2010/05/05 22:07:58 wiz Exp $
+.\"
+.\" Copyright (c)2003 Citrus Project,
+.\" 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.
+.\"
+.Dd May 5, 2010
+.Dt ICONV 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm iconv_open ,
+.Nm iconv_close ,
+.Nm iconv
+.Nd codeset conversion functions
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In iconv.h
+.Ft iconv_t
+.Fn iconv_open "const char *dstname" "const char *srcname"
+.Ft int
+.Fn iconv_close "iconv_t cd"
+.Ft size_t
+.Fn iconv "iconv_t cd" "const char ** restrict src" "size_t * restrict srcleft" "char ** restrict dst" "size_t * restrict dstleft"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn iconv_open
+function opens a converter from the codeset
+.Fa srcname
+to the codeset
+.Fa dstname
+and returns its descriptor.
+.Pp
+The
+.Fn iconv_close
+function closes the specified converter
+.Fa cd .
+.Pp
+The
+.Fn iconv
+function converts the string in the buffer
+.Fa *src
+of length
+.Fa *srcleft
+bytes and stores the converted string in the buffer
+.Fa *dst
+of size
+.Fa *dstleft
+bytes.
+After calling
+.Fn iconv ,
+the values pointed to by
+.Fa src ,
+.Fa srcleft ,
+.Fa dst ,
+and
+.Fa dstleft
+are updated as follows:
+.Bl -tag -width 01234567 -offset indent
+.It Fa *src
+Pointer to the byte just after the last character fetched.
+.It Fa *srcleft
+Number of remaining bytes in the source buffer.
+.It Fa *dst
+Pointer to the byte just after the last character stored.
+.It Fa *dstleft
+Number of remainder bytes in the destination buffer.
+.El
+.Pp
+If the string pointed to by
+.Fa *src
+contains a byte sequence which is not a valid character in the source
+codeset, the conversion stops just after the last successful conversion.
+If the output buffer is too small to store the converted
+character, the conversion also stops in the same way.
+In these cases, the values pointed to by
+.Fa src ,
+.Fa srcleft ,
+.Fa dst ,
+and
+.Fa dstleft
+are updated to the state just after the last successful conversion.
+.Pp
+If the string pointed to by
+.Fa *src
+contains a character which is valid under the source codeset but
+can not be converted to the destination codeset,
+the character is replaced by an
+.Dq invalid character
+which depends on the destination codeset, e.g.,
+.Sq \&? ,
+and the conversion is continued.
+.Fn iconv
+returns the number of such
+.Dq invalid conversions .
+.Pp
+If the source and/or destination codesets are stateful,
+.Fn iconv
+places these into their initial state.
+There are two special cases of
+.Fn iconv :
+.Bl -enum -offset indent
+.It
+If both
+.Fa dst
+and
+.Fa *dst
+are
+.No non- Ns Dv NULL ,
+.Fn iconv
+stores the shift sequence for the destination switching to the initial state
+in the buffer pointed to by
+.Fa *dst .
+The buffer size is specified by the value pointed to by
+.Fa dstleft
+as above.
+.Fn iconv
+will fail if the buffer is too small to store the shift sequence.
+.It
+On the other hand,
+.Fa dst
+or
+.Fa *dst
+may be
+.Dv NULL .
+In this case, the shift sequence for the destination switching
+to the initial state is discarded.
+.El
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+Upon successful completion of
+.Fn iconv_open ,
+it returns a conversion descriptor.
+Otherwise,
+.Fn iconv_open
+returns (iconv_t)\-1 and sets
+.Va errno
+to indicate the error.
+.Pp
+Upon successful completion of
+.Fn iconv_close ,
+it returns 0.
+Otherwise,
+.Fn iconv_close
+returns \-1 and sets errno to indicate the error.
+.Pp
+Upon successful completion of
+.Fn iconv ,
+it returns the number of
+.Dq invalid
+conversions.
+Otherwise,
+.Fn iconv
+returns (size_t)\-1 and sets errno to indicate the error.
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+The
+.Fn iconv_open
+function may cause an error in the following cases:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+There is no converter specified by
+.Fa srcname
+and
+.Fa dstname .
+.It Bq Er ENOMEM
+Memory is exhausted.
+.El
+.Pp
+The
+.Fn iconv_close
+function may cause an error in the following case:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The conversion descriptor specified by
+.Fa cd
+is invalid.
+.El
+.Pp
+The
+.Fn iconv
+function may cause an error in the following cases:
+.Bl -tag -width Er
+.It Bq Er E2BIG
+The output buffer pointed to by
+.Fa *dst
+is too small to store the result string.
+.It Bq Er EBADF
+The conversion descriptor specified by
+.Fa cd
+is invalid.
+.It Bq Er EILSEQ
+The string pointed to by
+.Fa *src
+contains a byte sequence which does not describe a valid character of
+the source codeset.
+.It Bq Er EINVAL
+The string pointed to by
+.Fa *src
+terminates with an incomplete character or shift sequence.
+.El
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr iconv 1
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+.Fn iconv_open ,
+.Fn iconv_close ,
+and
+.Fn iconv
+conform to
+.St -p1003.1-2001 .
+.\" ----------------------------------------------------------------------
+.Sh BUGS
+If
+.Fn iconv
+is aborted due to the occurrence of some error,
+the
+.Dq invalid conversion
+count mentioned above is unfortunately lost.
diff --git a/lib/nbsd_libc/iconv/iconv.c b/lib/nbsd_libc/iconv/iconv.c
new file mode 100644 (file)
index 0000000..5fd542e
--- /dev/null
@@ -0,0 +1,188 @@
+/*     $NetBSD: iconv.c,v 1.12 2009/08/05 15:17:02 joerg Exp $ */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: iconv.c,v 1.12 2009/08/05 15:17:02 joerg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <paths.h>
+#include <sys/queue.h>
+
+#include <iconv.h>
+
+#ifdef __weak_alias
+__weak_alias(iconv, _iconv)
+__weak_alias(iconv_open, _iconv_open)
+__weak_alias(iconv_close, _iconv_close)
+#endif
+
+#ifdef HAVE_CITRUS
+#include <sys/types.h>
+#include "citrus_types.h"
+#include "citrus_module.h"
+#include "citrus_esdb.h"
+#include "citrus_hash.h"
+#include "citrus_iconv.h"
+
+#define ISBADF(_h_)    (!(_h_) || (_h_) == (iconv_t)-1)
+
+
+iconv_t
+iconv_open(const char *out, const char *in)
+{
+       int ret;
+       struct _citrus_iconv *handle;
+
+       ret = _citrus_iconv_open(&handle, _PATH_ICONV, in, out);
+       if (ret) {
+               errno = ret == ENOENT? EINVAL : ret;
+               return ((iconv_t)-1);
+       }
+
+       return ((iconv_t)(void *)handle);
+}
+
+int
+iconv_close(iconv_t handle)
+{
+       if (ISBADF(handle)) {
+               errno = EBADF;
+               return (-1);
+       }
+
+       _citrus_iconv_close((struct _citrus_iconv *)(void *)handle);
+
+       return (0);
+}
+
+size_t
+iconv(iconv_t handle, const char **in, size_t *szin, char **out, size_t *szout)
+{
+       int err;
+       size_t ret;
+
+       if (ISBADF(handle)) {
+               errno = EBADF;
+               return ((size_t)-1);
+       }
+
+       err = _citrus_iconv_convert(
+               (struct _citrus_iconv *)(void *)handle, in, szin, out, szout,
+               0, &ret);
+       if (err) {
+               errno = err;
+               ret = (size_t)-1;
+       }
+
+       return (ret);
+}
+
+size_t
+__iconv(iconv_t handle, const char **in, size_t *szin, char **out,
+       size_t *szout, u_int32_t flags, size_t *invalids)
+{
+       int err;
+       size_t ret;
+
+       if (ISBADF(handle)) {
+               errno = EBADF;
+               return ((size_t)-1);
+       }
+
+       err = _citrus_iconv_convert(
+               (struct _citrus_iconv *)(void *)handle, in, szin, out, szout,
+               flags, &ret);
+       if (invalids)
+               *invalids = ret;
+       if (err) {
+               errno = err;
+               ret = (size_t)-1;
+       }
+
+       return (ret);
+}
+
+int
+__iconv_get_list(char ***rlist, size_t *rsz)
+{
+       int ret;
+
+       ret = _citrus_esdb_get_list(rlist, rsz);
+       if (ret) {
+               errno = ret;
+               return -1;
+       }
+
+       return 0;
+}
+
+void
+__iconv_free_list(char **list, size_t sz)
+{
+       _citrus_esdb_free_list(list, sz);
+}
+
+#else
+iconv_t
+/*ARGSUSED*/
+iconv_open(const char *in, const char *out)
+{
+       errno = EINVAL;
+       return ((iconv_t)-1);
+}
+int
+/*ARGSUSED*/
+iconv_close(iconv_t handle)
+{
+       errno = EBADF;
+       return (-1);
+}
+size_t
+/*ARGSUSED*/
+iconv(iconv_t handle, const char **in, size_t *szin, char **out, size_t *szout)
+{
+       errno = EBADF;
+       return ((size_t)-1);
+}
+int
+/*ARGSUSED*/
+__iconv_get_list(char ***rlist, size_t *rsz)
+{
+       errno = EINVAL;
+       return -1;
+}
+void
+/*ARGSUSED*/
+__iconv_free_list(char **list, size_t sz)
+{
+}
+#endif
diff --git a/lib/nbsd_libc/include/env.h b/lib/nbsd_libc/include/env.h
new file mode 100644 (file)
index 0000000..20b6bf9
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: env.h,v 1.2 2010/11/14 22:04:36 tron Exp $     */
+
+/*-
+ * Copyright (c) 2010 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matthias Scheler.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/types.h>
+
+#include <stdbool.h>
+
+#include "reentrant.h"
+
+extern ssize_t __getenvslot(const char *name, size_t l_name, bool allocate);
+extern char *__findenvvar(const char *name, size_t l_name);
+
+#ifdef _REENTRANT
+extern bool __readlockenv(void);
+extern bool __writelockenv(void);
+extern bool __unlockenv(void);
+#else
+static __inline bool
+__readlockenv(void)
+{
+       return true;
+}
+
+static __inline bool
+__writelockenv(void)
+{
+       return true;
+}
+
+static __inline bool
+__unlocklockenv(void)
+{
+       return true;
+}
+#endif
+
+extern char **environ;
diff --git a/lib/nbsd_libc/include/extern.h b/lib/nbsd_libc/include/extern.h
new file mode 100644 (file)
index 0000000..5bd012a
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: extern.h,v 1.17 2009/10/21 01:07:45 snj Exp $  */
+
+/*
+ * Copyright (c) 1997 Christos Zoulas.  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 ``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 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.
+ */
+
+__BEGIN_DECLS
+extern char *__minbrk;
+int __getcwd(char *, size_t);
+int __getlogin(char *, size_t);
+int __setlogin(const char *);
+void _resumecontext(void);
+const char *__strerror(int , char *, size_t);
+const char *__strsignal(int , char *, size_t);
+char *__dtoa(double, int, int, int *, int *, char **);
+void __freedtoa(char *);
+int __sysctl(const int *, unsigned int, void *, size_t *, const void *, size_t);
+
+struct sigaction;
+int __sigaction_sigtramp(int, const struct sigaction *,
+    struct sigaction *, const void *, int);
+
+#ifdef WIDE_DOUBLE
+char *__hdtoa(double, const char *, int, int *, int *, char **);
+char *__hldtoa(long double, const char *, int, int *, int *,  char **);
+char *__ldtoa(long double *, int, int, int *, int *, char **);
+#endif
+
+struct syslog_data;
+void   syslog_ss(int, struct syslog_data *, const char *, ...)
+    __attribute__((__format__(__printf__,3,4)));
+void   vsyslog_ss(int, struct syslog_data *, const char *, _BSD_VA_LIST_);
+void    vsyslog_ss(int, struct syslog_data *, const char *, _BSD_VA_LIST_) 
+    __attribute__((__format__(__printf__,3,0))); 
+void   syslogp_ss(int, struct syslog_data *, const char *, const char *, 
+    const char *, ...) __attribute__((__format__(__printf__,5,0))); 
+void   vsyslogp_ss(int, struct syslog_data *, const char *, const char *, 
+    const char *, _BSD_VA_LIST_) __attribute__((__format__(__printf__,5,0))); 
+
+int    snprintf_ss(char * __restrict, size_t, const char * __restrict, ...)
+    __attribute__((__format__(__printf__, 3, 4)));
+int    vsnprintf_ss(char * __restrict, size_t, const char * __restrict,
+    _BSD_VA_LIST_) __attribute__((__format__(__printf__, 3, 0)));
+
+void   _malloc_prefork(void);
+void   _malloc_postfork(void);
+
+__END_DECLS
diff --git a/lib/nbsd_libc/include/fd_setsize.h b/lib/nbsd_libc/include/fd_setsize.h
new file mode 100644 (file)
index 0000000..235b1ad
--- /dev/null
@@ -0,0 +1,9 @@
+#ifndef _FD_SETSIZE_H
+#define _FD_SETSIZE_H
+
+/*
+ * If you need a bigger FD_SETSIZE, this is NOT the place to set it.
+ * This file is a fallback for BIND ports which don't specify their own.
+ */
+
+#endif /* _FD_SETSIZE_H */
diff --git a/lib/nbsd_libc/include/isc/assertions.h b/lib/nbsd_libc/include/isc/assertions.h
new file mode 100644 (file)
index 0000000..7db7361
--- /dev/null
@@ -0,0 +1,132 @@
+/*     $NetBSD: assertions.h,v 1.5 2009/04/12 17:07:16 christos Exp $  */
+
+/*
+ * Copyright (C) 2004, 2005, 2008  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 1997-2001  Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and/or 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 ISC DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/*
+ * Id: assertions.h,v 1.5 2008/11/14 02:36:51 marka Exp
+ */
+
+#ifndef ASSERTIONS_H
+#define ASSERTIONS_H           1
+
+typedef enum {
+       assert_require, assert_ensure, assert_insist, assert_invariant
+} assertion_type;
+
+typedef void (*assertion_failure_callback)(const char *, int, assertion_type,
+                                          const char *, int);
+
+/* coverity[+kill] */
+extern assertion_failure_callback __assertion_failed;
+void set_assertion_failure_callback(assertion_failure_callback f);
+const char *assertion_type_to_text(assertion_type type);
+
+#if defined(CHECK_ALL) || defined(__COVERITY__)
+#define CHECK_REQUIRE          1
+#define CHECK_ENSURE           1
+#define CHECK_INSIST           1
+#define CHECK_INVARIANT                1
+#endif
+
+#if defined(CHECK_NONE) && !defined(__COVERITY__)
+#define CHECK_REQUIRE          0
+#define CHECK_ENSURE           0
+#define CHECK_INSIST           0
+#define CHECK_INVARIANT                0
+#endif
+
+#ifdef _DIAGNOSTIC
+#ifndef CHECK_REQUIRE
+#define CHECK_REQUIRE          1
+#endif
+
+#ifndef CHECK_ENSURE
+#define CHECK_ENSURE           1
+#endif
+
+#ifndef CHECK_INSIST
+#define CHECK_INSIST           1
+#endif
+
+#ifndef CHECK_INVARIANT
+#define CHECK_INVARIANT                1
+#endif
+#endif /* _DIAGNOSTIC */
+
+#if CHECK_REQUIRE != 0
+#define REQUIRE(cond) \
+       ((void) ((cond) || \
+                ((__assertion_failed)(__FILE__, __LINE__, assert_require, \
+                                      #cond, 0), 0)))
+#define REQUIRE_ERR(cond) \
+       ((void) ((cond) || \
+                ((__assertion_failed)(__FILE__, __LINE__, assert_require, \
+                                      #cond, 1), 0)))
+#else
+#define REQUIRE(cond)          ((void) (cond))
+#define REQUIRE_ERR(cond)      ((void) (cond))
+#endif /* CHECK_REQUIRE */
+
+#if CHECK_ENSURE != 0
+#define ENSURE(cond) \
+       ((void) ((cond) || \
+                ((__assertion_failed)(__FILE__, __LINE__, assert_ensure, \
+                                      #cond, 0), 0)))
+#define ENSURE_ERR(cond) \
+       ((void) ((cond) || \
+                ((__assertion_failed)(__FILE__, __LINE__, assert_ensure, \
+                                      #cond, 1), 0)))
+#else
+#define ENSURE(cond)           ((void) (cond))
+#define ENSURE_ERR(cond)       ((void) (cond))
+#endif /* CHECK_ENSURE */
+
+#if CHECK_INSIST != 0
+#define INSIST(cond) \
+       ((void) ((cond) || \
+                ((__assertion_failed)(__FILE__, __LINE__, assert_insist, \
+                                      #cond, 0), 0)))
+#define INSIST_ERR(cond) \
+       ((void) ((cond) || \
+                ((__assertion_failed)(__FILE__, __LINE__, assert_insist, \
+                                      #cond, 1), 0)))
+#else
+#if !defined(__lint__)
+#define INSIST(cond)           ((void) (cond))
+#define INSIST_ERR(cond)       ((void) (cond))
+#else /* !__lint__ */
+#define INSIST(cond)
+#define INSIST_ERR(cond)
+#endif /* !__lint__ */
+#endif /* CHECK_INSIST */
+
+#if CHECK_INVARIANT != 0
+#define INVARIANT(cond) \
+       ((void) ((cond) || \
+                ((__assertion_failed)(__FILE__, __LINE__, assert_invariant, \
+                                      #cond, 0), 0)))
+#define INVARIANT_ERR(cond) \
+       ((void) ((cond) || \
+                ((__assertion_failed)(__FILE__, __LINE__, assert_invariant, \
+                                      #cond, 1), 0)))
+#else
+#define INVARIANT(cond)                ((void) (cond))
+#define INVARIANT_ERR(cond)    ((void) (cond))
+#endif /* CHECK_INVARIANT */
+#endif /* ASSERTIONS_H */
+/*! \file */
diff --git a/lib/nbsd_libc/include/isc/dst.h b/lib/nbsd_libc/include/isc/dst.h
new file mode 100644 (file)
index 0000000..5537e3d
--- /dev/null
@@ -0,0 +1,170 @@
+/*     $NetBSD: dst.h,v 1.1.1.4 2009/04/12 16:35:44 christos Exp $     */
+
+#ifndef DST_H
+#define DST_H
+
+#ifndef HAS_DST_KEY
+typedef struct dst_key {
+       char    *dk_key_name;   /*%< name of the key */
+       int     dk_key_size;    /*%< this is the size of the key in bits */
+       int     dk_proto;       /*%< what protocols this key can be used for */
+       int     dk_alg;         /*%< algorithm number from key record */
+       u_int32_t dk_flags;     /*%< and the flags of the public key */
+       u_int16_t dk_id;        /*%< identifier of the key */
+} DST_KEY;
+#endif /* HAS_DST_KEY */
+/*
+ * do not taint namespace
+ */
+#define        dst_bsafe_init          __dst_bsafe_init
+#define        dst_buffer_to_key       __dst_buffer_to_key
+#define        dst_check_algorithm     __dst_check_algorithm
+#define        dst_compare_keys        __dst_compare_keys
+#define        dst_cylink_init         __dst_cylink_init
+#define        dst_dnskey_to_key       __dst_dnskey_to_key
+#define        dst_eay_dss_init        __dst_eay_dss_init
+#define        dst_free_key            __dst_free_key
+#define        dst_generate_key        __dst_generate_key
+#define        dst_hmac_md5_init       __dst_hmac_md5_init
+#define        dst_init                __dst_init
+#define        dst_key_to_buffer       __dst_key_to_buffer
+#define        dst_key_to_dnskey       __dst_key_to_dnskey
+#define        dst_read_key            __dst_read_key
+#define        dst_rsaref_init         __dst_rsaref_init
+#define        dst_s_build_filename    __dst_s_build_filename
+#define        dst_s_calculate_bits    __dst_s_calculate_bits
+#define        dst_s_conv_bignum_b64_to_u8     __dst_s_conv_bignum_b64_to_u8
+#define        dst_s_conv_bignum_u8_to_b64     __dst_s_conv_bignum_u8_to_b64
+#define        dst_s_dns_key_id        __dst_s_dns_key_id
+#define        dst_s_dump              __dst_s_dump
+#define        dst_s_filename_length   __dst_s_filename_length
+#define        dst_s_fopen             __dst_s_fopen
+#define        dst_s_get_int16         __dst_s_get_int16
+#define        dst_s_get_int32         __dst_s_get_int32
+#define        dst_s_id_calc           __dst_s_id_calc
+#define        dst_s_put_int16         __dst_s_put_int16
+#define        dst_s_put_int32         __dst_s_put_int32
+#define        dst_s_quick_random      __dst_s_quick_random
+#define        dst_s_quick_random_set  __dst_s_quick_random_set
+#define        dst_s_random            __dst_s_random
+#define        dst_s_semi_random       __dst_s_semi_random
+#define        dst_s_verify_str        __dst_s_verify_str
+#define        dst_sig_size            __dst_sig_size
+#define        dst_sign_data           __dst_sign_data
+#define        dst_verify_data         __dst_verify_data
+#define        dst_write_key           __dst_write_key
+
+/* 
+ * DST Crypto API defintions 
+ */
+void     dst_init(void);
+int      dst_check_algorithm(const int);
+
+
+int dst_sign_data(const int,           /*!<   specifies INIT/UPDATE/FINAL/ALL  */
+                 DST_KEY *,            /*!<   the key to use  */
+                 void **,              /*!<   pointer to state structure  */
+                 const u_char *,       /*!<   data to be signed  */
+                 const int,            /*!<   length of input data  */
+                 u_char *,             /*!<   buffer to write signature to  */
+                 const int);           /*!<   size of output buffer  */
+int dst_verify_data(const int,         /*!<   specifies INIT/UPDATE/FINAL/ALL  */
+                   DST_KEY *,          /*!<   the key to use  */
+                   void **,            /*!<   pointer to state structure  */
+                   const u_char *,     /*!<   data to be verified  */
+                   const int,          /*!<   length of input data  */
+                   const u_char *,     /*!<   buffer containing signature  */
+                   const int);         /*!<   length of signature  */
+DST_KEY *dst_read_key(const char *,    /*!<   name of key  */
+                     const u_int16_t,  /*!<   key tag identifier  */
+                     const int,        /*!<   key algorithm  */
+                     const int);       /*!<   Private/PublicKey wanted */
+int      dst_write_key(const DST_KEY *,        /*!<   key to write out  */
+                      const int);      /*!<   Public/Private  */
+DST_KEY *dst_dnskey_to_key(const char *,       /*!<   KEY record name  */
+                          const u_char *,      /*!<   KEY RDATA  */
+                          const int);          /*!<   size of input buffer */
+int      dst_key_to_dnskey(const DST_KEY *,    /*!<   key to translate  */
+                          u_char *,            /*!<   output buffer  */
+                          const int);          /*!<   size of out_storage */
+DST_KEY *dst_buffer_to_key(const char *,       /*!<   name of the key  */
+                          const int,           /*!<   algorithm  */
+                          const int,           /*!<   dns flags  */
+                          const int,           /*!<   dns protocol  */
+                          const u_char *,      /*!<   key in dns wire fmt  */
+                          const int);          /*!<   size of key  */
+int     dst_key_to_buffer(DST_KEY *, u_char *, int);
+
+DST_KEY *dst_generate_key(const char *,        /*!<   name of new key  */
+                         const int,            /*!<   key algorithm to generate  */
+                         const int,            /*!<   size of new key  */
+                         const int,            /*!<   alg dependent parameter */
+                         const int,            /*!<   key DNS flags  */
+                         const int);           /*!<   key DNS protocol  */
+DST_KEY *dst_free_key(DST_KEY *);
+int      dst_compare_keys(const DST_KEY *, const DST_KEY *);
+
+int    dst_sig_size(DST_KEY *);
+
+
+/* support for dns key tags/ids */
+u_int16_t dst_s_dns_key_id(const u_char *, const int);
+u_int16_t dst_s_id_calc(const u_char *, const int);
+
+/* Used by callers as well as by the library.  */
+#define RAW_KEY_SIZE    8192        /*%< large enough to store any key */
+/* DST_API control flags */
+/* These are used used in functions dst_sign_data and dst_verify_data */
+#define SIG_MODE_INIT          1  /*%< initialize digest */
+#define SIG_MODE_UPDATE                2  /*%< add data to digest */
+#define SIG_MODE_FINAL         4  /*%< generate/verify signature */
+#define SIG_MODE_ALL           (SIG_MODE_INIT|SIG_MODE_UPDATE|SIG_MODE_FINAL)
+
+/* Flags for dst_read_private_key()  */
+#define DST_FORCE_READ         0x1000000
+#define DST_CAN_SIGN           0x010F
+#define DST_NO_AUTHEN          0x8000
+#define DST_EXTEND_FLAG         0x1000
+#define DST_STANDARD           0
+#define DST_PRIVATE             0x2000000
+#define DST_PUBLIC              0x4000000
+#define DST_RAND_SEMI           1
+#define DST_RAND_STD            2
+#define DST_RAND_KEY            3
+#define DST_RAND_DSS            4
+
+
+/* DST algorithm codes */
+#define KEY_RSA                        1
+#define KEY_DH                 2
+#define KEY_DSA                        3
+#define KEY_PRIVATE            254
+#define KEY_EXPAND             255
+#define KEY_HMAC_MD5           157
+#define KEY_HMAC_SHA1          158
+#define UNKNOWN_KEYALG         0
+#define DST_MAX_ALGS            KEY_HMAC_SHA1
+
+/* DST constants to locations in KEY record  changes in new KEY record */
+#define DST_FLAGS_SIZE         2
+#define DST_KEY_PROT           2
+#define DST_KEY_ALG            3
+#define DST_EXT_FLAG            4
+#define DST_KEY_START          4
+
+#ifndef SIGN_F_NOKEY 
+#define SIGN_F_NOKEY           0xC000
+#endif
+
+/* error codes from dst routines */
+#define SIGN_INIT_FAILURE      (-23)
+#define SIGN_UPDATE_FAILURE    (-24)
+#define SIGN_FINAL_FAILURE     (-25)
+#define VERIFY_INIT_FAILURE    (-26)
+#define VERIFY_UPDATE_FAILURE  (-27)
+#define VERIFY_FINAL_FAILURE   (-28)
+#define MISSING_KEY_OR_SIGNATURE (-30)
+#define UNSUPPORTED_KEYALG     (-31)
+
+#endif /* DST_H */
+/*! \file */
diff --git a/lib/nbsd_libc/include/isc/eventlib.h b/lib/nbsd_libc/include/isc/eventlib.h
new file mode 100644 (file)
index 0000000..4e9cc2e
--- /dev/null
@@ -0,0 +1,206 @@
+/*     $NetBSD: eventlib.h,v 1.3 2009/04/12 17:07:16 christos Exp $    */
+
+/*
+ * Copyright (C) 2004, 2005, 2008  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 1995-1999, 2001, 2003  Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and/or 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 ISC DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/* eventlib.h - exported interfaces for eventlib
+ * vix 09sep95 [initial]
+ *
+ * Id: eventlib.h,v 1.7 2008/11/14 02:36:51 marka Exp
+ */
+
+#ifndef _EVENTLIB_H
+#define _EVENTLIB_H
+
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <sys/time.h>
+#include <stdio.h>
+
+#ifndef __P
+# define __EVENTLIB_P_DEFINED
+# ifdef __STDC__
+#  define __P(x) x
+# else
+#  define __P(x) ()
+# endif
+#endif
+
+/* In the absence of branded types... */
+typedef struct { void *opaque; } evConnID;
+typedef struct { void *opaque; } evFileID;
+typedef struct { void *opaque; } evStreamID;
+typedef struct { void *opaque; } evTimerID;
+typedef struct { void *opaque; } evWaitID;
+typedef struct { void *opaque; } evContext;
+typedef struct { void *opaque; } evEvent;
+
+#define        evInitID(id) ((id)->opaque = NULL)
+#define        evTestID(id) ((id).opaque != NULL)
+
+typedef void (*evConnFunc)__P((evContext, void *, int, const void *, int,
+                              const void *, int));
+typedef void (*evFileFunc)__P((evContext, void *, int, int));
+typedef        void (*evStreamFunc)__P((evContext, void *, int, int));
+typedef void (*evTimerFunc)__P((evContext, void *,
+                               struct timespec, struct timespec));
+typedef        void (*evWaitFunc)__P((evContext, void *, const void *));
+
+typedef        struct { unsigned char mask[256/8]; } evByteMask;
+#define        EV_BYTEMASK_BYTE(b) ((b) / 8)
+#define        EV_BYTEMASK_MASK(b) (1 << ((b) % 8))
+#define        EV_BYTEMASK_SET(bm, b) \
+       ((bm).mask[EV_BYTEMASK_BYTE(b)] |= EV_BYTEMASK_MASK(b))
+#define        EV_BYTEMASK_CLR(bm, b) \
+       ((bm).mask[EV_BYTEMASK_BYTE(b)] &= ~EV_BYTEMASK_MASK(b))
+#define        EV_BYTEMASK_TST(bm, b) \
+       ((bm).mask[EV_BYTEMASK_BYTE(b)] & EV_BYTEMASK_MASK(b))
+
+#define        EV_POLL         1
+#define        EV_WAIT         2
+#define        EV_NULL         4
+
+#define        EV_READ         1
+#define        EV_WRITE        2
+#define        EV_EXCEPT       4
+
+#define EV_WASNONBLOCKING 8    /* Internal library use. */
+
+/* eventlib.c */
+#define evCreate       __evCreate
+#define evSetDebug     __evSetDebug
+#define evDestroy      __evDestroy
+#define evGetNext      __evGetNext
+#define evDispatch     __evDispatch
+#define evDrop         __evDrop
+#define evMainLoop     __evMainLoop
+#define evHighestFD    __evHighestFD
+#define evGetOption    __evGetOption
+#define evSetOption    __evSetOption
+
+int  evCreate __P((evContext *));
+void evSetDebug __P((evContext, int, FILE *));
+int  evDestroy __P((evContext));
+int  evGetNext __P((evContext, evEvent *, int));
+int  evDispatch __P((evContext, evEvent));
+void evDrop __P((evContext, evEvent));
+int  evMainLoop __P((evContext));
+int  evHighestFD __P((evContext));
+int  evGetOption __P((evContext *, const char *, int *));
+int  evSetOption __P((evContext *, const char *, int));
+
+/* ev_connects.c */
+#define evListen       __evListen
+#define evConnect      __evConnect
+#define evCancelConn   __evCancelConn
+#define evHold         __evHold
+#define evUnhold       __evUnhold
+#define evTryAccept    __evTryAccept
+
+int evListen __P((evContext, int, int, evConnFunc, void *, evConnID *));
+int evConnect __P((evContext, int, const void *, int,
+                  evConnFunc, void *, evConnID *));
+int evCancelConn __P((evContext, evConnID));
+int evHold __P((evContext, evConnID));
+int evUnhold __P((evContext, evConnID));
+int evTryAccept __P((evContext, evConnID, int *));
+
+/* ev_files.c */
+#define evSelectFD     __evSelectFD
+#define evDeselectFD   __evDeselectFD
+
+int evSelectFD __P((evContext, int, int, evFileFunc, void *, evFileID *));
+int evDeselectFD __P((evContext, evFileID));
+
+/* ev_streams.c */
+#define evConsIovec    __evConsIovec
+#define evWrite                __evWrite
+#define evRead         __evRead
+#define evTimeRW       __evTimeRW
+#define evUntimeRW     __evUntimeRW
+#define        evCancelRW      __evCancelRW
+
+struct iovec evConsIovec __P((void *, size_t));
+int evWrite __P((evContext, int, const struct iovec *, int,
+                evStreamFunc func, void *, evStreamID *));
+int evRead __P((evContext, int, const struct iovec *, int,
+               evStreamFunc func, void *, evStreamID *));
+int evTimeRW __P((evContext, evStreamID, evTimerID timer));
+int evUntimeRW __P((evContext, evStreamID));
+int evCancelRW __P((evContext, evStreamID));
+
+/* ev_timers.c */
+#define evConsTime     __evConsTime
+#define evAddTime      __evAddTime
+#define evSubTime      __evSubTime
+#define evCmpTime      __evCmpTime
+#define        evTimeSpec      __evTimeSpec
+#define        evTimeVal       __evTimeVal
+
+#define evNowTime              __evNowTime
+#define evUTCTime              __evUTCTime
+#define evLastEventTime                __evLastEventTime
+#define evSetTimer             __evSetTimer
+#define evClearTimer           __evClearTimer
+#define evConfigTimer          __evConfigTimer
+#define evResetTimer           __evResetTimer
+#define evSetIdleTimer         __evSetIdleTimer
+#define evClearIdleTimer       __evClearIdleTimer
+#define evResetIdleTimer       __evResetIdleTimer
+#define evTouchIdleTimer       __evTouchIdleTimer
+
+struct timespec evConsTime __P((time_t sec, long nsec));
+struct timespec evAddTime __P((struct timespec, struct timespec));
+struct timespec evSubTime __P((struct timespec, struct timespec));
+struct timespec evNowTime __P((void));
+struct timespec evUTCTime __P((void));
+struct timespec evLastEventTime __P((evContext));
+struct timespec evTimeSpec __P((struct timeval));
+struct timeval evTimeVal __P((struct timespec));
+int evCmpTime __P((struct timespec, struct timespec));
+int evSetTimer __P((evContext, evTimerFunc, void *, struct timespec,
+                   struct timespec, evTimerID *));
+int evClearTimer __P((evContext, evTimerID));
+int evConfigTimer __P((evContext, evTimerID, const char *param,
+                     int value));
+int evResetTimer __P((evContext, evTimerID, evTimerFunc, void *,
+                     struct timespec, struct timespec));
+int evSetIdleTimer __P((evContext, evTimerFunc, void *, struct timespec,
+                       evTimerID *));
+int evClearIdleTimer __P((evContext, evTimerID));
+int evResetIdleTimer __P((evContext, evTimerID, evTimerFunc, void *,
+                         struct timespec));
+int evTouchIdleTimer __P((evContext, evTimerID));
+
+/* ev_waits.c */
+#define evWaitFor      __evWaitFor
+#define evDo           __evDo
+#define evUnwait       __evUnwait
+#define evDefer                __evDefer
+
+int evWaitFor __P((evContext, const void *, evWaitFunc, void *, evWaitID *));
+int evDo __P((evContext, const void *));
+int evUnwait __P((evContext, evWaitID));
+int evDefer __P((evContext, evWaitFunc, void *));
+
+#ifdef __EVENTLIB_P_DEFINED
+# undef __P
+#endif
+
+#endif /*_EVENTLIB_H*/
+
+/*! \file */
diff --git a/lib/nbsd_libc/include/isc/heap.h b/lib/nbsd_libc/include/isc/heap.h
new file mode 100644 (file)
index 0000000..30cec98
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: heap.h,v 1.1.1.4 2009/04/12 16:35:44 christos Exp $    */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1997,1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+typedef int (*heap_higher_priority_func)(void *, void *);
+typedef void (*heap_index_func)(void *, int);
+typedef void (*heap_for_each_func)(void *, void *);
+
+typedef struct heap_context {
+       int array_size;
+       int array_size_increment;
+       int heap_size;
+       void **heap;
+       heap_higher_priority_func higher_priority;
+       heap_index_func index;
+} *heap_context;
+
+#define heap_new       __heap_new
+#define heap_free      __heap_free
+#define heap_insert    __heap_insert
+#define heap_delete    __heap_delete
+#define heap_increased __heap_increased
+#define heap_decreased __heap_decreased
+#define heap_element   __heap_element
+#define heap_for_each  __heap_for_each
+
+heap_context   heap_new(heap_higher_priority_func, heap_index_func, int);
+int            heap_free(heap_context);
+int            heap_insert(heap_context, void *);
+int            heap_delete(heap_context, int);
+int            heap_increased(heap_context, int);
+int            heap_decreased(heap_context, int);
+void *         heap_element(heap_context, int);
+int            heap_for_each(heap_context, heap_for_each_func, void *);
+
+/*! \file */
diff --git a/lib/nbsd_libc/include/isc/list.h b/lib/nbsd_libc/include/isc/list.h
new file mode 100644 (file)
index 0000000..46f2e79
--- /dev/null
@@ -0,0 +1,120 @@
+/*     $NetBSD: list.h,v 1.5 2009/04/12 17:07:16 christos Exp $        */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1997,1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#ifndef LIST_H
+#define LIST_H 1
+#include <isc/assertions.h>
+
+#define LIST(type) struct { type *head, *tail; }
+#define INIT_LIST(list) \
+       do { (list).head = NULL; (list).tail = NULL; } while (/*CONSTCOND*/0)
+
+#define LINK(type) struct { type *prev, *next; }
+#define INIT_LINK_TYPE(elt, link, type) \
+       do { \
+               (elt)->link.prev = (type *)(-1); \
+               (elt)->link.next = (type *)(-1); \
+       } while (/*CONSTCOND*/0)
+#define INIT_LINK(elt, link) \
+       INIT_LINK_TYPE(elt, link, void)
+#define LINKED(elt, link) ((void *)((elt)->link.prev) != (void *)(-1) && \
+                          (void *)((elt)->link.next) != (void *)(-1))
+
+#define HEAD(list) ((list).head)
+#define TAIL(list) ((list).tail)
+#define EMPTY(list) ((list).head == NULL)
+
+#define PREPEND(list, elt, link) \
+       do { \
+               INSIST(!LINKED(elt, link));\
+               if ((list).head != NULL) \
+                       (list).head->link.prev = (elt); \
+               else \
+                       (list).tail = (elt); \
+               (elt)->link.prev = NULL; \
+               (elt)->link.next = (list).head; \
+               (list).head = (elt); \
+       } while (/*CONSTCOND*/0)
+
+#define APPEND(list, elt, link) \
+       do { \
+               INSIST(!LINKED(elt, link));\
+               if ((list).tail != NULL) \
+                       (list).tail->link.next = (elt); \
+               else \
+                       (list).head = (elt); \
+               (elt)->link.prev = (list).tail; \
+               (elt)->link.next = NULL; \
+               (list).tail = (elt); \
+       } while (/*CONSTCOND*/0)
+
+#define UNLINK_TYPE(list, elt, link, type) \
+       do { \
+               INSIST(LINKED(elt, link));\
+               if ((elt)->link.next != NULL) \
+                       (elt)->link.next->link.prev = (elt)->link.prev; \
+               else { \
+                       INSIST((list).tail == (elt)); \
+                       (list).tail = (elt)->link.prev; \
+               } \
+               if ((elt)->link.prev != NULL) \
+                       (elt)->link.prev->link.next = (elt)->link.next; \
+               else { \
+                       INSIST((list).head == (elt)); \
+                       (list).head = (elt)->link.next; \
+               } \
+               INIT_LINK_TYPE(elt, link, type); \
+       } while (/*CONSTCOND*/0)
+#define UNLINK(list, elt, link) \
+       UNLINK_TYPE(list, elt, link, void)
+
+#define PREV(elt, link) ((elt)->link.prev)
+#define NEXT(elt, link) ((elt)->link.next)
+
+#define INSERT_BEFORE(list, before, elt, link) \
+       do { \
+               INSIST(!LINKED(elt, link));\
+               if ((before)->link.prev == NULL) \
+                       PREPEND(list, elt, link); \
+               else { \
+                       (elt)->link.prev = (before)->link.prev; \
+                       (before)->link.prev = (elt); \
+                       (elt)->link.prev->link.next = (elt); \
+                       (elt)->link.next = (before); \
+               } \
+       } while (/*CONSTCOND*/0)
+
+#define INSERT_AFTER(list, after, elt, link) \
+       do { \
+               INSIST(!LINKED(elt, link));\
+               if ((after)->link.next == NULL) \
+                       APPEND(list, elt, link); \
+               else { \
+                       (elt)->link.next = (after)->link.next; \
+                       (after)->link.next = (elt); \
+                       (elt)->link.next->link.prev = (elt); \
+                       (elt)->link.prev = (after); \
+               } \
+       } while (/*CONSTCOND*/0)
+
+#define ENQUEUE(list, elt, link) APPEND(list, elt, link)
+#define DEQUEUE(list, elt, link) UNLINK(list, elt, link)
+
+#endif /* LIST_H */
+/*! \file */
diff --git a/lib/nbsd_libc/include/isc/memcluster.h b/lib/nbsd_libc/include/isc/memcluster.h
new file mode 100644 (file)
index 0000000..3c1b489
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: memcluster.h,v 1.1.1.4 2009/04/12 16:35:44 christos Exp $      */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1997,1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#ifndef MEMCLUSTER_H
+#define MEMCLUSTER_H
+
+#include <stdio.h>
+
+#define meminit                __meminit
+#ifdef MEMCLUSTER_DEBUG
+#define memget(s)      __memget_debug(s, __FILE__, __LINE__)
+#define memput(p, s)   __memput_debug(p, s, __FILE__, __LINE__)
+#else /*MEMCLUSTER_DEBUG*/
+#ifdef MEMCLUSTER_RECORD
+#define memget(s)      __memget_record(s, __FILE__, __LINE__)
+#define memput(p, s)   __memput_record(p, s, __FILE__, __LINE__)
+#else /*MEMCLUSTER_RECORD*/
+#define memget         __memget
+#define memput         __memput
+#endif /*MEMCLUSTER_RECORD*/
+#endif /*MEMCLUSTER_DEBUG*/
+#define memstats       __memstats
+#define memactive      __memactive
+
+int    meminit(size_t, size_t);
+void * __memget(size_t);
+void   __memput(void *, size_t);
+void * __memget_debug(size_t, const char *, int);
+void   __memput_debug(void *, size_t, const char *, int);
+void * __memget_record(size_t, const char *, int);
+void   __memput_record(void *, size_t, const char *, int);
+void   memstats(FILE *);
+int    memactive(void);
+
+#endif /* MEMCLUSTER_H */
+/*! \file */
diff --git a/lib/nbsd_libc/include/namespace.h b/lib/nbsd_libc/include/namespace.h
new file mode 100644 (file)
index 0000000..c4bb6bf
--- /dev/null
@@ -0,0 +1,851 @@
+/*     $NetBSD: namespace.h,v 1.146 2010/12/16 18:38:06 christos Exp $ */
+
+/*-
+ * Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _NAMESPACE_H_
+#define _NAMESPACE_H_
+
+#include <sys/cdefs.h>
+
+#ifndef __lint__
+#define aio_suspend    _aio_suspend
+#define brk            _brk
+#define catclose       _catclose
+#define catgets                _catgets
+#define catopen                _catopen
+#define daylight       _daylight
+#define difftime       _difftime
+#define err            _err
+#define errx           _errx
+#ifdef _REENTRANT
+#define fileno         _fileno
+#endif /* _REENTRANT */
+#define fork           _fork
+#define fseeko         _fseeko
+#define ftello         _ftello
+#define getcontext     _getcontext
+#define getenv_r       _getenv_r
+#define imaxabs                _imaxabs
+#define imaxdiv                _imaxdiv
+#define inet_aton      _inet_aton
+#define inet_pton      _inet_pton
+#define pipe           _pipe
+#define sbrk           _sbrk
+#define strerror_r     _strerror_r
+#define strlcat                _strlcat
+#define strlcpy                _strlcpy
+#define strtof         _strtof
+#define strtoimax      _strtoimax
+#define strtold                _strtold
+#define strtoll                _strtoll
+#define strtoull       _strtoull
+#define strtoumax      _strtoumax
+#define sys_errlist    _sys_errlist
+#define sys_nerr       _sys_nerr
+#define sys_siglist    _sys_siglist
+#define        sys_nsig        _sys_nsig
+#define sysconf                __sysconf
+#define verr           _verr
+#define verrx          _verrx
+#define vwarn          _vwarn
+#define vwarnx         _vwarnx
+#define warn           _warn
+#define warnx          _warnx
+
+#ifdef __weak_alias
+#define MD2Data                        _MD2Data
+#define MD2End                 _MD2End
+#define MD2FileChunk           _MD2FileChunk
+#define MD2File                        _MD2File
+#define MD2Final               _MD2Final
+#define MD2Init                        _MD2Init
+#define MD2Transform           _MD2Transform
+#define MD2Update              _MD2Update
+#define MD4Data                        _MD4Data
+#define MD4End                 _MD4End
+#define MD4FileChunk           _MD4FileChunk
+#define MD4File                        _MD4File
+#define MD4Final               _MD4Final
+#define MD4Init                        _MD4Init
+#define MD4Transform           _MD4Transform
+#define MD4Update              _MD4Update
+#define MD5Data                        _MD5Data
+#define MD5End                 _MD5End
+#define MD5FileChunk           _MD5FileChunk
+#define MD5File                        _MD5File
+#define MD5Final               _MD5Final
+#define MD5Init                        _MD5Init
+#define MD5Transform           _MD5Transform
+#define MD5Update              _MD5Update
+#define RMD160Data             _RMD160Data
+#define RMD160End              _RMD160End
+#define RMD160FileChunk                _RMD160FileChunk
+#define RMD160File             _RMD160File
+#define RMD160Final            _RMD160Final
+#define RMD160Init             _RMD160Init
+#define RMD160Transform                _RMD160Transform
+#define RMD160Update           _RMD160Update
+#define SHA1Data               _SHA1Data
+#define SHA1End                        _SHA1End
+#define SHA1FileChunk          _SHA1FileChunk
+#define SHA1File               _SHA1File
+#define SHA1Final              _SHA1Final
+#define SHA1Init               _SHA1Init
+#define SHA1Transform          _SHA1Transform
+#define SHA1Update             _SHA1Update
+#define SHA224_Data            _SHA224_Data
+#define SHA224_End             _SHA224_End
+#define SHA224_FileChunk       _SHA224_FileChunk
+#define SHA224_File            _SHA224_File
+#define SHA224_Final           _SHA224_Final
+#define SHA224_Init            _SHA224_Init
+#define SHA224_Transform       _SHA224_Transform
+#define SHA224_Update          _SHA224_Update
+#define SHA256_Data            _SHA256_Data
+#define SHA256_End             _SHA256_End
+#define SHA256_FileChunk       _SHA256_FileChunk
+#define SHA256_File            _SHA256_File
+#define SHA256_Final           _SHA256_Final
+#define SHA256_Init            _SHA256_Init
+#define SHA256_Transform       _SHA256_Transform
+#define SHA256_Update          _SHA256_Update
+#define SHA384_Data            _SHA384_Data
+#define SHA384_End             _SHA384_End
+#define SHA384_FileChunk       _SHA384_FileChunk
+#define SHA384_File            _SHA384_File
+#define SHA384_Final           _SHA384_Final
+#define SHA384_Init            _SHA384_Init
+#define SHA384_Transform       _SHA384_Transform
+#define SHA384_Update          _SHA384_Update
+#define SHA512_Data            _SHA512_Data
+#define SHA512_End             _SHA512_End
+#define SHA512_FileChunk       _SHA512_FileChunk
+#define SHA512_File            _SHA512_File
+#define SHA512_Final           _SHA512_Final
+#define SHA512_Init            _SHA512_Init
+#define SHA512_Transform       _SHA512_Transform
+#define SHA512_Update          _SHA512_Update
+#define a64l                   _a64l
+#define adjtime                        _adjtime
+#define alarm                  _alarm
+#define alphasort              _alphasort
+#define arc4random             _arc4random
+#define asctime_r              _asctime_r
+#define asprintf               _asprintf
+#define atoll                  _atoll
+#define authnone_create                _authnone_create
+#define authunix_create                _authunix_create
+#define authunix_create_default _authunix_create_default
+#define basename               _basename
+#define bindresvport           _bindresvport
+#define bindresvport_sa                _bindresvport_sa
+#define bm_comp                        _bm_comp
+#define bm_exec                        _bm_exec
+#define bm_free                        _bm_free
+#define callrpc                        _callrpc
+#define cdbr_close             _cdbr_close
+#define cdbr_find              _cdbr_find
+#define cdbr_get               _cdbr_get
+#define cdbr_open              _cdbr_open
+#define cdbw_close             _cdbw_close
+#define cdbw_open              _cdbw_open
+#define cdbw_put               _cdbw_put
+#define cdbw_put_data          _cdbw_put_data
+#define cdbw_put_key           _cdbw_put_key
+#define cdbw_output            _cdbw_output
+#define cfgetispeed            _cfgetispeed
+#define cfgetospeed            _cfgetospeed
+#define cfmakeraw              _cfmakeraw
+#define cfsetispeed            _cfsetispeed
+#define cfsetospeed            _cfsetospeed
+#define cfsetspeed             _cfsetspeed
+#define cgetcap                        _cgetcap
+#define cgetclose              _cgetclose
+#define cgetent                        _cgetent
+#define cgetfirst              _cgetfirst
+#define cgetmatch              _cgetmatch
+#define cgetnext               _cgetnext
+#define cgetnum                        _cgetnum
+#define cgetset                        _cgetset
+#define cgetstr                        _cgetstr
+#define cgetustr               _cgetustr
+#define clnt_broadcast         _clnt_broadcast
+#define clnt_create            _clnt_create
+#define clnt_create_vers       _clnt_create_vers
+#define clnt_dg_create         _clnt_dg_create
+#define clnt_pcreateerror      _clnt_pcreateerror
+#define clnt_perrno            _clnt_perrno
+#define clnt_perror            _clnt_perror
+#define clnt_raw_create                _clnt_raw_create
+#define clnt_tli_create                _clnt_tli_create
+#define clnt_tp_create         _clnt_tp_create
+#define clnt_spcreateerror     _clnt_spcreateerror
+#define clnt_sperrno           _clnt_sperrno
+#define clnt_sperror           _clnt_sperror
+#define clnt_vc_create         _clnt_vc_create
+#define clntraw_create         _clntraw_create
+#define clnttcp_create         _clnttcp_create
+#define clntudp_bufcreate      _clntudp_bufcreate
+#define clntudp_create         _clntudp_create
+#define clock_gettime          _clock_gettime
+#define clock_getres           _clock_getres
+#define clock_settime          _clock_settime
+#define closedir               _closedir
+#define closelog               _closelog
+#define closelog_r             _closelog_r
+#define confstr                        _confstr
+#define csetexpandtc           _csetexpandtc
+#define ctermid                        _ctermid
+#define ctime_r                        _ctime_r
+#define ctime_rz               _ctime_rz
+#define daemon                 _daemon
+#define dbopen                 _dbopen
+#define devname                        _devname
+#define difftime               _difftime
+#define dirname                        _dirname
+#define dn_expand              _dn_expand
+#define drand48                        _drand48
+#define endfsent               _endfsent
+#define endgrent               _endgrent
+#define endhostent             _endhostent
+#define endnetconfig           _endnetconfig
+#define endnetent              _endnetent
+#define endnetgrent            _endnetgrent
+#define endnetpath             _endnetpath
+#define endprotoent            _endprotoent
+#define endprotoent_r          _endprotoent_r
+#define endpwent               _endpwent
+#define endrpcent              _endrpcent
+#define endservent             _endservent
+#define endservent_r           _endservent_r
+#define endttyent              _endttyent
+#define endusershell           _endusershell
+#define erand48                        _erand48
+#define ether_aton             _ether_aton
+#define ether_hostton          _ether_hostton
+#define ether_line             _ether_line
+#define ether_ntoa             _ether_ntoa
+#define ether_ntohost          _ether_ntohost
+#define execl                  _execl
+#define execle                 _execle
+#define execlp                 _execlp
+#define execv                  _execv
+#define execvp                 _execvp
+#define fdopen                 _fdopen
+#define fgetln                 _fgetln
+#define fgetwln                        _fgetwln
+#define fhstatvfs              _fhstatvfs
+#define flockfile              _flockfile
+#define ftrylockfile           _ftrylockfile
+#define funlockfile            _funlockfile
+#define fnmatch                        _fnmatch
+#define fparseln               _fparseln
+#define fpgetmask              _fpgetmask
+#define fpgetround             _fpgetround
+#define fpgetsticky            _fpgetsticky
+#define fpsetmask              _fpsetmask
+#define fpsetround             _fpsetround
+#define fpsetsticky            _fpsetsticky
+#define freenetconfigent       _freenetconfigent
+#define freeaddrinfo           _freeaddrinfo
+#define freeifaddrs            _freeifaddrs
+#define fstatvfs               _fstatvfs
+#define ftok                   _ftok
+#define ftruncate              _ftruncate
+#define fts_children           _fts_children
+#define fts_close              _fts_close
+#define fts_open               _fts_open
+#define fts_read               _fts_read
+#define fts_set                        _fts_set
+#define gai_strerror           _gai_strerror
+#define get_myaddress          _get_myaddress
+#define getaddrinfo            _getaddrinfo
+#define getbsize               _getbsize
+#define getcwd                 _getcwd
+#define getdelim               _getdelim
+#define getdevmajor            _getdevmajor
+#define getdiskbyname          _getdiskbyname
+#define getdomainname          _getdomainname
+#define getfsent               _getfsent
+#define getfsfile              _getfsfile
+#define getfsspec              _getfsspec
+#define getgrent               _getgrent
+#define getgrent_r             _getgrent_r
+#define getgrgid               _getgrgid
+#define getgrgid_r             _getgrgid_r
+#define getgrnam               _getgrnam
+#define getgrnam_r             _getgrnam_r
+#define getgrouplist           _getgrouplist
+#define getgroupmembership     _getgroupmembership
+#define gethostbyaddr          _gethostbyaddr
+#define gethostbyname          _gethostbyname
+#define gethostent             _gethostent
+#define gethostname            _gethostname
+#define getifaddrs             _getifaddrs
+#define getline                        _getline
+#define getloadavg             _getloadavg
+#define getlogin               _getlogin
+#define getlogin_r             _getlogin_r
+#define getmntinfo             _getmntinfo
+#define getmode                        _getmode
+#define getnameinfo            _getnameinfo
+#define getnetbyaddr           _getnetbyaddr
+#define getnetbyname           _getnetbyname
+#define getnetconfig           _getnetconfig
+#define getnetconfigent                _getnetconfigent
+#define getnetent              _getnetent
+#define getnetgrent            _getnetgrent
+#define getnetpath             _getnetpath
+#define getopt                 _getopt
+#define getopt_long            _getopt_long
+#define getpagesize            _getpagesize
+#define getpass                        _getpass
+#define getprogname            _getprogname
+#define getprotobyname         _getprotobyname
+#define getprotobyname_r       _getprotobyname_r
+#define getprotobynumber       _getprotobynumber
+#define getprotobynumber_r     _getprotobynumber_r
+#define getprotoent            _getprotoent
+#define getprotoent_r          _getprotoent_r
+#define getpwent               _getpwent
+#define getpwent_r             _getpwent_r
+#define getpwnam               _getpwnam
+#define getpwnam_r             _getpwnam_r
+#define getpwuid               _getpwuid
+#define getpwuid_r             _getpwuid_r
+#define getrpcbyname           _getrpcbyname
+#define getrpcbyname_r         _getrpcbyname_r
+#define getrpcbynumber         _getrpcbynumber
+#define getrpcbynumber_r       _getrpcbynumber_r
+#define getrpcent              _getrpcent
+#define getrpcent_r            _getrpcent_r
+#define getrpcport             _getrpcport
+#define getservbyname          _getservbyname
+#define getservbyname_r                _getservbyname_r
+#define getservbyport          _getservbyport
+#define getservbyport_r                _getservbyport_r
+#define getservent             _getservent
+#define getservent_r           _getservent_r
+#define getsubopt              _getsubopt
+#define getttyent              _getttyent
+#define getttynam              _getttynam
+#define getusershell           _getusershell
+#define glob                   _glob
+#define globfree               _globfree
+#define gmtime_r               _gmtime_r
+#define group_from_gid         _group_from_gid
+#define heapsort               _heapsort
+#define herror                 _herror
+#define hes_error              _hes_error
+#define hes_free               _hes_free
+#define hes_init               _hes_init
+#define hes_resolve            _hes_resolve
+#define hes_to_bind            _hes_to_bind
+#define hesiod_end             _hesiod_end
+#define hesiod_free_list       _hesiod_free_list
+#define hesiod_init            _hesiod_init
+#define hesiod_resolve         _hesiod_resolve
+#define hesiod_to_bind         _hesiod_to_bind
+#define iconv                  _iconv
+#define iconv_open             _iconv_open
+#define iconv_close            _iconv_close
+#define if_freenameindex       _if_freenameindex
+#define if_indextoname         _if_indextoname
+#define if_nameindex           _if_nameindex
+#define if_nametoindex         _if_nametoindex
+#define in6addr_any            _in6addr_any
+#define in6addr_linklocal_allnodes     _in6addr_linklocal_allnodes
+#define in6addr_linklocal_allrouters   _in6addr_linklocal_allrouters
+#define in6addr_loopback       _in6addr_loopback
+#define in6addr_nodelocal_allnodes     _in6addr_nodelocal_allnodes
+#define inet6_option_alloc     _inet6_option_alloc
+#define inet6_option_append    _inet6_option_append
+#define inet6_option_find      _inet6_option_find
+#define inet6_option_init      _inet6_option_init
+#define inet6_option_next      _inet6_option_next
+#define inet6_option_space     _inet6_option_space
+#define inet6_opt_init         _inet6_opt_init
+#define inet6_opt_append       _inet6_opt_append
+#define inet6_opt_finish       _inet6_opt_finish
+#define inet6_opt_set_val      _inet6_opt_set_val
+#define inet6_opt_next         _inet6_opt_next
+#define inet6_opt_find         _inet6_opt_find
+#define inet6_opt_get_val      _inet6_opt_get_val
+#define inet6_rthdr_add                _inet6_rthdr_add
+#define inet6_rthdr_getaddr    _inet6_rthdr_getaddr
+#define inet6_rthdr_getflags   _inet6_rthdr_getflags
+#define inet6_rthdr_init       _inet6_rthdr_init
+#define inet6_rthdr_lasthop    _inet6_rthdr_lasthop
+#define inet6_rthdr_segments   _inet6_rthdr_segments
+#define inet6_rthdr_space      _inet6_rthdr_space
+#define inet6_rth_space                _inet6_rth_space
+#define inet6_rth_init         _inet6_rth_init
+#define inet6_rth_add          _inet6_rth_add
+#define inet6_rth_reverse      _inet6_rth_reverse
+#define inet6_rth_segments     _inet6_rth_segments
+#define inet6_rth_getaddr      _inet6_rth_getaddr
+#define inet_cidr_ntop         _inet_cidr_ntop
+#define inet_cidr_pton         _inet_cidr_pton
+#define inet_lnaof             _inet_lnaof
+#define inet_makeaddr          _inet_makeaddr
+#define inet_net_ntop          _inet_net_ntop
+#define inet_net_pton          _inet_net_pton
+#define inet_neta              _inet_neta
+#define inet_netof             _inet_netof
+#define inet_network           _inet_network
+#define inet_nsap_addr         _inet_nsap_addr
+#define inet_nsap_ntoa         _inet_nsap_ntoa
+#define inet_ntoa              _inet_ntoa
+#define inet_ntop              _inet_ntop
+#define initgroups             _initgroups
+#define initstate              _initstate
+#define innetgr                        _innetgr
+#define isatty                 _isatty
+#define jrand48                        _jrand48
+#define kill                   _kill
+#define l64a                   _l64a
+#define l64a_r                 _l64a_r
+#define lcong48                        _lcong48
+#define llabs                  _llabs
+#define lldiv                  _lldiv
+#define localtime_r            _localtime_r
+#define localtime_rz           _localtime_rz
+#define lockf                  _lockf
+#define lrand48                        _lrand48
+#define lseek                  _lseek
+#define mergesort              _mergesort
+#define mi_vector_hash         _mi_vector_hash
+#define mkstemp                        _mkstemp
+#define mktime_z               _mktime_z
+#define mmap                   _mmap
+#define mpool_close            _mpool_close
+#define mpool_filter           _mpool_filter
+#define mpool_get              _mpool_get
+#define mpool_new              _mpool_new
+#define mpool_open             _mpool_open
+#define mpool_put              _mpool_put
+#define mpool_sync             _mpool_sync
+#define mq_timedreceive                _mq_timedreceive
+#define mq_timedsend           _mq_timedsend
+#define mrand48                        _mrand48
+#define nc_perror              _nc_perror
+#define nc_sperror             _nc_sperror
+#define nanosleep              _nanosleep
+#define nice                   _nice
+#if 0
+#define nlist                  _nlist
+#endif
+#define nrand48                        _nrand48
+#define ntp_adjtime            _ntp_adjtime
+#define nsdispatch             _nsdispatch
+#define offtime                        _offtime
+#define opendir                        _opendir
+#define fdopendir              _fdopendir
+#define openlog                        _openlog
+#define openlog_r              _openlog_r
+#define pause                  _pause
+#define pclose                 _pclose
+#define pmap_getmaps           _pmap_getmaps
+#define pmap_getport           _pmap_getport
+#define pmap_rmtcall           _pmap_rmtcall
+#define pmap_set               _pmap_set
+#define pmap_unset             _pmap_unset
+#define pollts                 _pollts
+#define popen                  _popen
+#define posix2time             _posix2time
+#define posix2time_z           _posix2time_z
+#define pread                  _pread
+#define pselect                        _pselect
+#define psignal                        _psignal
+#define pthread_atfork         _pthread_atfork
+#define ptree_init             ptree_init
+#define ptree_insert_node      ptree_insert_node
+#define ptree_insert_mask_node ptree_insert_mask_node
+#define ptree_find_filtered_node       ptree_find_filtered_node
+#define ptree_remove_node      ptree_remove_node
+#define ptree_iterate          ptree_iterate
+#define putenv                 _putenv
+#define pwcache_groupdb                _pwcache_groupdb
+#define pwcache_userdb         _pwcache_userdb
+#define pwrite                 _pwrite
+#define qabs                   _qabs
+#define qdiv                   _qdiv
+#define radixsort              _radixsort
+#define random                 _random
+#define randomid               _randomid
+#define randomid_new           _randomid_new
+#define randomid_delete                _randomid_delete
+#define read                   _read
+#define readdir                        _readdir
+#define readdir_r              _readdir_r
+#define readlink               _readlink
+#define realpath               _realpath
+#define regcomp                        _regcomp
+#define regerror               _regerror
+#define regexec                        _regexec
+#define regfree                        _regfree
+#define registerrpc            _registerrpc
+#define res_init               _res_init
+#define res_mkquery            _res_mkquery
+#define res_query              _res_query
+#define res_search             _res_search
+#define rewinddir              _rewinddir
+#define rpc_broadcast          _rpc_broadcast
+#define rpc_broadcast_exp      _rpc_broadcast_exp
+#define rpc_call               _rpc_call
+#define rpc_control            _rpc_control
+#define rpc_reg                        _rpc_reg
+#define rpcb_getmaps           _rpcb_getmaps
+#define rpcb_gettime           _rpcb_gettime
+#define rpcb_rmtcall           _rpcb_rmtcall
+#define rpcb_set               _rpcb_set
+#define rpcb_taddr2uaddr       _rpcb_taddr2uaddr
+#define rpcb_uaddr2taddr       _rpcb_uaddr2taddr
+#define rpcb_unset             _rpcb_unset
+#define scandir                        _scandir
+#define seed48                 _seed48
+#define seekdir                        _seekdir
+#define select                 _select
+#define send                   _send
+#define setdomainname          _setdomainname
+#define setenv                 _setenv
+#define setfsent               _setfsent
+#define setgrent               _setgrent
+#define setgroupent            _setgroupent
+#define sethostent             _sethostent
+#define sethostname            _sethostname
+#define setlogin               _setlogin
+#define setlogmask             _setlogmask
+#define setlogmask_r           _setlogmask_r
+#define setmode                        _setmode
+#define setnetconfig           _setnetconfig
+#define setnetent              _setnetent
+#define setnetgrent            _setnetgrent
+#define setpassent             _setpassent
+#define setnetpath             _setnetpath
+#define setproctitle           _setproctitle
+#define setprotoent            _setprotoent
+#define setprotoent_r          _setprotoent_r
+#define setpwent               _setpwent
+#define setrpcent              _setrpcent
+#define setservent             _setservent
+#define setservent_r           _setservent_r
+#define setstate               _setstate
+#define setttyent              _setttyent
+#define setttyentpath          _setttyentpath
+#define settimeofday           _settimeofday
+#define setusershell           _setusershell
+#define shm_open               _shm_open
+#define shm_unlink             _shm_unlink
+#define shquote                        _shquote
+#define siginterrupt           _siginterrupt
+#define signal                 _signal
+#define sigtimedwait           _sigtimedwait
+#define sl_add                 _sl_add
+#define sl_create              _sl_create
+#define sl_delete              _sl_delete
+#define sl_find                        _sl_find
+#define sl_free                        _sl_free
+#define sl_init                        _sl_init
+#define sleep                  _sleep
+#ifndef snprintf
+#define snprintf               _snprintf
+#endif
+#define snprintf_ss            _snprintf_ss
+#define sradixsort             _sradixsort
+#define srand48                        _srand48
+#define srandom                        _srandom
+#define statvfs(a, b)          _statvfs(a, b)
+#define strcasecmp             _strcasecmp
+#define strdup                 _strdup
+#define stresep                        _stresep
+#define strftime_z             _strftime_z
+#define strndup                        _strndup
+#define strncasecmp            _strncasecmp
+#define strptime               _strptime
+#define strsep                 _strsep
+#define strsignal              _strsignal
+#define strsuftoll             _strsuftoll
+#define strsuftollx            _strsuftollx
+#define strsvis                        _strsvis
+#define strsvisx               _strsvisx
+#define strtok_r               _strtok_r
+#define strunvis               _strunvis
+#define strvis                 _strvis
+#define strvisx                        _strvisx
+#define svc_auth_reg           _svc_auth_reg
+#define svc_create             _svc_create
+#define svc_dg_create          _svc_dg_create
+#define svc_exit               _svc_exit
+#define svc_fd_create          _svc_fd_create
+#define svc_getreq             _svc_getreq
+#define svc_getreqset          _svc_getreqset
+#define svc_getreq_common      _svc_getreq_common
+#define svc_raw_create         _svc_raw_create
+#define svc_register           _svc_register
+#define svc_reg                        _svc_reg
+#define svc_run                        _svc_run
+#define svc_sendreply          _svc_sendreply
+#define svc_tli_create         _svc_tli_create
+#define svc_tp_create          _svc_tp_create
+#define svc_unregister         _svc_unregister
+#define svc_unreg              _svc_unreg
+#define svc_vc_create          _svc_vc_create
+#define svcerr_auth            _svcerr_auth
+#define svcerr_decode          _svcerr_decode
+#define svcerr_noproc          _svcerr_noproc
+#define svcerr_noprog          _svcerr_noprog
+#define svcerr_progvers                _svcerr_progvers
+#define svcerr_systemerr       _svcerr_systemerr
+#define svcerr_weakauth                _svcerr_weakauth
+#define svcfd_create           _svcfd_create
+#define svcraw_create          _svcraw_create
+#define svctcp_create          _svctcp_create
+#define svcudp_bufcreate       _svcudp_bufcreate
+#define svcudp_create          _svcudp_create
+#define svcudp_enablecache     _svcudp_enablecache
+#define svis                   _svis
+#define sysarch                        _sys_sysarch
+#define sysctl                 _sysctl
+#define sysctlbyname           _sysctlbyname
+#define sysctlgetmibinfo       _sysctlgetmibinfo
+#define sysctlnametomib                _sysctlnametomib
+#define syslog                 _syslog
+#define syslog_r               _syslog_r
+#define syslog_ss              _syslog_ss
+#define syslogp                        _syslogp
+#define syslogp_r              _syslogp_r
+#define syslogp_ss             _syslogp_ss
+#define taddr2uaddr            _taddr2uaddr
+#define tcdrain                        _tcdrain
+#define tcflow                 _tcflow
+#define tcflush                        _tcflush
+#define tcgetattr              _tcgetattr
+#define tcgetpgrp              _tcgetpgrp
+#define tcgetsid               _tcgetsid
+#define tcsendbreak            _tcsendbreak
+#define tcsetattr              _tcsetattr
+#define tcsetpgrp              _tcsetpgrp
+#define telldir                        _telldir
+#define time                   _time
+#define time2posix             _time2posix
+#define timegm                 _timegm
+#define timelocal              _timelocal
+#define timeoff                        _timeoff
+#define times                  _times
+#define ttyname                        _ttyname
+#define ttyname_r              _ttyname_r
+#define ttyslot                        _ttyslot
+#define tzname                 _tzname
+#define tzset                  _tzset
+#define tzsetwall              _tzsetwall
+#define uaddr2taddr            _uaddr2taddr
+#define ualarm                 _ualarm
+#define uname                  _uname
+#define unsetenv               _unsetenv
+#define unvis                  _unvis
+#define user_from_uid          _user_from_uid
+#define usleep                 _usleep
+#define utime                  _utime
+#define uuid_create_nil                _uuid_create_nil
+#define uuid_is_nil            _uuid_is_nil
+#define valloc                 _valloc
+#define vdprintf               _vdprintf
+#define vis                    _vis
+#define        vdprintf                _vdprintf
+#ifndef vsnprintf
+#define vsnprintf              _vsnprintf
+#endif
+#define vsnprintf_ss           _vsnprintf_ss
+#define vsyslog                        _vsyslog
+#define vsyslog_r              _vsyslog_r
+#define vsyslog_ss             _vsyslog_ss
+#define vsyslogp               _vsyslogp
+#define vsyslogp_r             _vsyslogp_r
+#define vsyslogp_ss            _vsyslogp_ss
+#define wait                   _wait
+#define wait3                  _wait3
+#define wait4                  _wait4
+#define waitpid                        _waitpid
+#define wcscasecmp             _wcscasecmp
+#define wcsdup                 _wcsdup
+#define wcsncasecmp            _wcsncasecmp
+#define wcstof                 _wcstof
+#define wcstod                 _wcstod
+#define wcstold                        _wcstold
+#define wcwidth                        _wcwidth
+#define xdr_accepted_reply     _xdr_accepted_reply
+#define xdr_array              _xdr_array
+#define xdr_authunix_parms     _xdr_authunix_parms
+#define xdr_bool               _xdr_bool
+#define xdr_bytes              _xdr_bytes
+#define xdr_callhdr            _xdr_callhdr
+#define xdr_callmsg            _xdr_callmsg
+#define xdr_char               _xdr_char
+#define xdr_datum              _xdr_datum
+#define xdr_des_block          _xdr_des_block
+#define xdr_domainname         _xdr_domainname
+#define xdr_double             _xdr_double
+#define xdr_enum               _xdr_enum
+#define xdr_float              _xdr_float
+#define xdr_free               _xdr_free
+#define        xdr_hyper               _xdr_hyper
+#define xdr_int                        _xdr_int
+#define xdr_int16_t            _xdr_int16_t
+#define xdr_int32_t            _xdr_int32_t
+#define xdr_int64_t            _xdr_int64_t
+#define xdr_long               _xdr_long
+#define        xdr_longlong_t          _xdr_longlong_t
+#define xdr_mapname            _xdr_mapname
+#define xdr_netbuf             _xdr_netbuf
+#define xdr_netobj             _xdr_netobj
+#define xdr_opaque             _xdr_opaque
+#define xdr_opaque_auth                _xdr_opaque_auth
+#define xdr_peername           _xdr_peername
+#define xdr_pmap               _xdr_pmap
+#define xdr_pmaplist           _xdr_pmaplist
+#define xdr_pointer            _xdr_pointer
+#define xdr_reference          _xdr_reference
+#define xdr_rejected_reply     _xdr_rejected_reply
+#define xdr_replymsg           _xdr_replymsg
+#define xdr_rmtcall_args       _xdr_rmtcall_args
+#define xdr_rmtcallres         _xdr_rmtcallres
+#define xdr_rpcb               _xdr_rpcb
+#define xdr_rpcb_entry         _xdr_rpcb_entry
+#define xdr_rpcb_entry_list_ptr        _xdr_rpcb_entry_list_ptr
+#define xdr_rpcb_rmtcallargs   _xdr_rpcb_rmtcallargs
+#define xdr_rpcb_rmtcallres    _xdr_rpcb_rmtcallres
+#define xdr_rpcb_stat          _xdr_rpcb_stat
+#define xdr_rpcb_stat_byvers   _xdr_rpcb_stat_byvers
+#define xdr_rpcblist           _xdr_rpcblist
+#define xdr_rpcblist_ptr       _xdr_rpcblist_ptr
+#define xdr_rpcbs_addrlist     _xdr_rpcbs_addrlist
+#define xdr_rpcbs_addrlist_ptr _xdr_rpcbs_addrlist_ptr
+#define xdr_rpcbs_proc         _xdr_rpcbs_proc
+#define xdr_rpcbs_rmtcalllist  _xdr_rpcbs_rmtcalllist
+#define xdr_rpcbs_rmtcalllist_ptr      _xdr_rpcbs_rmtcalllist_ptr
+#define xdr_rpcbs              _xdr_rpcbs
+#define xdr_rpcbs              _xdr_rpcbs
+#define xdr_short              _xdr_short
+#define xdr_string             _xdr_string
+#define xdr_u_char             _xdr_u_char
+#define        xdr_u_hyper             _xdr_u_hyper
+#define xdr_u_int              _xdr_u_int
+#define xdr_u_int16_t          _xdr_u_int16_t
+#define xdr_u_int32_t          _xdr_u_int32_t
+#define xdr_u_int64_t          _xdr_u_int64_t
+#define xdr_u_long             _xdr_u_long
+#define        xdr_u_longlong_t        _xdr_u_longlong_t
+#define xdr_u_short            _xdr_u_short
+#define xdr_union              _xdr_union
+#define xdr_vector             _xdr_vector
+#define xdr_void               _xdr_void
+#define xdr_wrapstring         _xdr_wrapstring
+#define xdr_yp_inaddr          _xdr_yp_inaddr
+#define xdr_ypall              _xdr_ypall
+#define xdr_ypbind_resp                _xdr_ypbind_resp
+#define xdr_ypbind_setdom      _xdr_ypbind_setdom
+#define xdr_ypdomain_wrap_string       _xdr_ypdomain_wrap_string
+#define xdr_ypmap_parms                _xdr_ypmap_parms
+#define xdr_ypmap_wrap_string  _xdr_ypmap_wrap_string
+#define xdr_ypmaplist          _xdr_ypmaplist
+#define xdr_ypowner_wrap_string _xdr_ypowner_wrap_string
+#define xdr_yppushresp_xfr     _xdr_yppushresp_xfr
+#define xdr_ypreq_key          _xdr_ypreq_key
+#define xdr_ypreq_nokey                _xdr_ypreq_nokey
+#define xdr_ypreq_xfr          _xdr_ypreq_xfr
+#define xdr_ypresp_key_val     _xdr_ypresp_key_val
+#define xdr_ypresp_maplist     _xdr_ypresp_maplist
+#define xdr_ypresp_master      _xdr_ypresp_master
+#define xdr_ypresp_order       _xdr_ypresp_order
+#define xdr_ypresp_val         _xdr_ypresp_val
+#define xdrmem_create          _xdrmem_create
+#define xdrrec_create          _xdrrec_create
+#define xdrrec_endofrecord     _xdrrec_endofrecord
+#define xdrrec_eof             _xdrrec_eof
+#define xdrrec_skiprecord      _xdrrec_skiprecord
+#define xdrstdio_create                _xdrstdio_create
+#define xprt_register          _xprt_register
+#define xprt_unregister                _xprt_unregister
+#define yp_all                 _yp_all
+#define yp_bind                        _yp_bind
+#define yp_first               _yp_first
+#define yp_get_default_domain  _yp_get_default_domain
+#define yp_maplist             _yp_maplist
+#define yp_master              _yp_master
+#define yp_match               _yp_match
+#define yp_next                        _yp_next
+#define yp_order               _yp_order
+#define yp_unbind              _yp_unbind
+#define yperr_string           _yperr_string
+#define ypprot_err             _ypprot_err
+#define dlopen                 __dlopen
+#define dlclose                        __dlclose
+#define dlsym                  __dlsym
+#define dlerror                        __dlerror
+#define dladdr                 __dladdr
+#define fmtcheck               __fmtcheck
+
+/* RB trees */
+#define        rb_tree_init            _rb_tree_init
+#define        rb_tree_find_node       _rb_tree_find_node
+#define        rb_tree_find_node_geq   _rb_tree_find_node_geq
+#define        rb_tree_find_node_leq   _rb_tree_find_node_leq
+#define        rb_tree_insert_node     _rb_tree_insert_node
+#define        rb_tree_remove_node     _rb_tree_remove_node
+#define        rb_tree_iterate         _rb_tree_iterate
+#ifdef RBDEBUG
+#define        rb_tree_check           _rb_tree_check
+#define        rb_tree_depths          _rb_tree_depths
+#endif
+
+/* rpc locks */
+#define authdes_lock           __rpc_authdes_lock
+#define authnone_lock          __rpc_authnone_lock
+#define authsvc_lock           __rpc_authsvc_lock
+#define clnt_fd_lock           __rpc_clnt_fd_lock
+#define clntraw_lock           __rpc_clntraw_lock
+#define dname_lock             __rpc_dname_lock
+#define dupreq_lock            __rpc_dupreq_lock
+#define keyserv_lock           __rpc_keyserv_lock
+#define libnsl_trace_lock      __rpc_libnsl_trace_lock
+#define loopnconf_lock         __rpc_loopnconf_lock
+#define ops_lock               __rpc_ops_lock
+#define portnum_lock           __rpc_portnum_lock
+#define proglst_lock           __rpc_proglst_lock
+#define rpcbaddr_cache_lock    __rpc_rpcbaddr_cache_lock
+#define rpcsoc_lock            __rpc_rpcsoc_lock
+#define svc_fd_lock            __rpc_svc_fd_lock
+#define svc_lock               __rpc_svc_lock
+#define svcraw_lock            __rpc_svcraw_lock
+#define xprtlist_lock          __rpc_xprtlist_lock
+
+#define __learn_tree           ___learn_tree
+#endif /* __weak_alias */
+#endif /* !__lint__ */
+
+#endif /* _NAMESPACE_H_ */
diff --git a/lib/nbsd_libc/include/pathnames.h b/lib/nbsd_libc/include/pathnames.h
new file mode 100644 (file)
index 0000000..5705c68
--- /dev/null
@@ -0,0 +1,33 @@
+/*     $NetBSD: pathnames.h,v 1.6 2008/05/29 14:51:25 mrg Exp $        */
+
+/*
+ * Copyright (c) 1997 Matthew R. Green
+ * 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 ``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 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.
+ */
+
+#ifdef RESCUEDIR
+#define        _PATH_BIN_RCMD  RESCUEDIR "/rcmd"
+#else
+#define        _PATH_BIN_RCMD  "/bin/rcmd"
+#endif
diff --git a/lib/nbsd_libc/include/port_after.h b/lib/nbsd_libc/include/port_after.h
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/lib/nbsd_libc/include/port_before.h b/lib/nbsd_libc/include/port_before.h
new file mode 100644 (file)
index 0000000..36217ac
--- /dev/null
@@ -0,0 +1,11 @@
+#include "namespace.h"
+#include <sys/cdefs.h>
+#define ISC_FORMAT_PRINTF(a,b) __attribute__((__format__(__printf__,a,b)))
+#define ISC_SOCKLEN_T  socklen_t
+#define DE_CONST(c,v)  v = ((c) ? \
+       strchr((const void *)(c), *(const char *)(const void *)(c)) : NULL)
+#ifndef lint
+#define UNUSED(a)      (void)&a
+#else
+#define UNUSED(a)      a = a
+#endif
diff --git a/lib/nbsd_libc/include/reentrant.h b/lib/nbsd_libc/include/reentrant.h
new file mode 100644 (file)
index 0000000..fcfe2f9
--- /dev/null
@@ -0,0 +1,266 @@
+/*     $NetBSD: reentrant.h,v 1.14 2009/01/11 02:46:28 christos Exp $  */
+
+/*-
+ * Copyright (c) 1997, 1998, 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin, by Nathan J. Williams, and by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * Requirements:
+ * 
+ * 1. The thread safe mechanism should be lightweight so the library can
+ *    be used by non-threaded applications without unreasonable overhead.
+ * 
+ * 2. There should be no dependency on a thread engine for non-threaded
+ *    applications.
+ * 
+ * 3. There should be no dependency on any particular thread engine.
+ * 
+ * 4. The library should be able to be compiled without support for thread
+ *    safety.
+ * 
+ * 
+ * Rationale:
+ * 
+ * One approach for thread safety is to provide discrete versions of the
+ * library: one thread safe, the other not.  The disadvantage of this is
+ * that libc is rather large, and two copies of a library which are 99%+
+ * identical is not an efficent use of resources.
+ * 
+ * Another approach is to provide a single thread safe library.  However,
+ * it should not add significant run time or code size overhead to non-
+ * threaded applications.
+ * 
+ * Since the NetBSD C library is used in other projects, it should be
+ * easy to replace the mutual exclusion primitives with ones provided by
+ * another system.  Similarly, it should also be easy to remove all
+ * support for thread safety completely if the target environment does
+ * not support threads.
+ * 
+ * 
+ * Implementation Details:
+ * 
+ * The thread primitives used by the library (mutex_t, mutex_lock, etc.)
+ * are macros which expand to the cooresponding primitives provided by
+ * the thread engine or to nothing.  The latter is used so that code is
+ * not unreasonably cluttered with #ifdefs when all thread safe support
+ * is removed.
+ * 
+ * The thread macros can be directly mapped to the mutex primitives from
+ * pthreads, however it should be reasonably easy to wrap another mutex
+ * implementation so it presents a similar interface.
+ * 
+ * The thread functions operate by dispatching to symbols which are, by
+ * default, weak-aliased to no-op functions in thread-stub/thread-stub.c
+ * (some uses of thread operations are conditional on __isthreaded, but
+ * not all of them are).
+ *
+ * When the thread library is linked in, it provides strong-alias versions
+ * of those symbols which dispatch to its own real thread operations.
+ *
+ */
+
+#ifdef _REENTRANT
+
+/*
+ * Abstract thread interface for thread-safe libraries.  These routines
+ * will use stubs in libc if the application is not linked against the
+ * pthread library, and the real function in the pthread library if it
+ * is.
+ */
+
+#include <pthread.h>
+#include <signal.h>
+
+#define        mutex_t                 pthread_mutex_t
+#define        MUTEX_INITIALIZER       PTHREAD_MUTEX_INITIALIZER
+
+#define        mutexattr_t             pthread_mutexattr_t
+
+#define        MUTEX_TYPE_NORMAL       PTHREAD_MUTEX_NORMAL
+#define        MUTEX_TYPE_ERRORCHECK   PTHREAD_MUTEX_ERRORCHECK
+#define        MUTEX_TYPE_RECURSIVE    PTHREAD_MUTEX_RECURSIVE
+
+#define        cond_t                  pthread_cond_t
+#define        COND_INITIALIZER        PTHREAD_COND_INITIALIZER
+
+#define        condattr_t              pthread_condattr_t
+
+#define        rwlock_t                pthread_rwlock_t
+#define        RWLOCK_INITIALIZER      PTHREAD_RWLOCK_INITIALIZER
+
+#define        rwlockattr_t            pthread_rwlockattr_t
+
+#define        thread_key_t            pthread_key_t
+
+#define        thr_t                   pthread_t
+
+#define        thrattr_t               pthread_attr_t
+
+#define        once_t                  pthread_once_t
+#define        ONCE_INITIALIZER        PTHREAD_ONCE_INIT
+
+#ifndef __LIBC_THREAD_STUBS
+
+__BEGIN_DECLS
+int    __libc_mutex_init(mutex_t *, const mutexattr_t *);
+int    __libc_mutex_lock(mutex_t *);
+int    __libc_mutex_trylock(mutex_t *);
+int    __libc_mutex_unlock(mutex_t *);
+int    __libc_mutex_destroy(mutex_t *);
+
+int    __libc_mutexattr_init(mutexattr_t *);
+int    __libc_mutexattr_settype(mutexattr_t *, int);
+int    __libc_mutexattr_destroy(mutexattr_t *);
+__END_DECLS
+
+#define        mutex_init(m, a)        __libc_mutex_init((m), (a))
+#define        mutex_lock(m)           __libc_mutex_lock((m))
+#define        mutex_trylock(m)        __libc_mutex_trylock((m))
+#define        mutex_unlock(m)         __libc_mutex_unlock((m))
+#define        mutex_destroy(m)        __libc_mutex_destroy((m))
+
+#define        mutexattr_init(ma)      __libc_mutexattr_init((ma))
+#define        mutexattr_settype(ma, t) __libc_mutexattr_settype((ma), (t))
+#define        mutexattr_destroy(ma)   __libc_mutexattr_destroy((ma))
+
+__BEGIN_DECLS
+int    __libc_cond_init(cond_t *, const condattr_t *);
+int    __libc_cond_signal(cond_t *);
+int    __libc_cond_broadcast(cond_t *);
+int    __libc_cond_wait(cond_t *, mutex_t *);
+#ifndef __LIBC12_SOURCE__
+int    __libc_cond_timedwait(cond_t *, mutex_t *, const struct timespec *);
+#endif
+int    __libc_cond_destroy(cond_t *);
+__END_DECLS
+
+#define        cond_init(c, t, a)      __libc_cond_init((c), (a))
+#define        cond_signal(c)          __libc_cond_signal((c))
+#define        cond_broadcast(c)       __libc_cond_broadcast((c))
+#define        cond_wait(c, m)         __libc_cond_wait((c), (m))
+#define        cond_timedwait(c, m, t) __libc_cond_timedwait((c), (m), (t))
+#define        cond_destroy(c)         __libc_cond_destroy((c))
+
+__BEGIN_DECLS
+int    __libc_rwlock_init(rwlock_t *, const rwlockattr_t *);
+int    __libc_rwlock_rdlock(rwlock_t *);
+int    __libc_rwlock_wrlock(rwlock_t *);
+int    __libc_rwlock_tryrdlock(rwlock_t *);
+int    __libc_rwlock_trywrlock(rwlock_t *);
+int    __libc_rwlock_unlock(rwlock_t *);
+int    __libc_rwlock_destroy(rwlock_t *);
+__END_DECLS
+
+#define        rwlock_init(l, a)       __libc_rwlock_init((l), (a))
+#define        rwlock_rdlock(l)        __libc_rwlock_rdlock((l))
+#define        rwlock_wrlock(l)        __libc_rwlock_wrlock((l))
+#define        rwlock_tryrdlock(l)     __libc_rwlock_tryrdlock((l))
+#define        rwlock_trywrlock(l)     __libc_rwlock_trywrlock((l))
+#define        rwlock_unlock(l)        __libc_rwlock_unlock((l))
+#define        rwlock_destroy(l)       __libc_rwlock_destroy((l))
+
+__BEGIN_DECLS
+int    __libc_thr_keycreate(thread_key_t *, void (*)(void *));
+int    __libc_thr_setspecific(thread_key_t, const void *);
+void   *__libc_thr_getspecific(thread_key_t);
+int    __libc_thr_keydelete(thread_key_t);
+__END_DECLS
+
+#define        thr_keycreate(k, d)     __libc_thr_keycreate((k), (d))
+#define        thr_setspecific(k, p)   __libc_thr_setspecific((k), (p))
+#define        thr_getspecific(k)      __libc_thr_getspecific((k))
+#define        thr_keydelete(k)        __libc_thr_keydelete((k))
+
+__BEGIN_DECLS
+int    __libc_thr_once(once_t *, void (*)(void));
+int    __libc_thr_sigsetmask(int, const sigset_t *, sigset_t *);
+thr_t  __libc_thr_self(void);
+int    __libc_thr_yield(void);
+void   __libc_thr_create(thr_t *, const thrattr_t *,
+           void *(*)(void *), void *);
+void   __libc_thr_exit(void *) __attribute__((__noreturn__));
+int    *__libc_thr_errno(void);
+int    __libc_thr_setcancelstate(int, int *);
+unsigned int   __libc_thr_curcpu(void);
+
+extern int __isthreaded;
+__END_DECLS
+
+#define        thr_once(o, f)          __libc_thr_once((o), (f))
+#define        thr_sigsetmask(f, n, o) __libc_thr_sigsetmask((f), (n), (o))
+#define        thr_self()              __libc_thr_self()
+#define        thr_yield()             __libc_thr_yield()
+#define        thr_create(tp, ta, f, a) __libc_thr_create((tp), (ta), (f), (a))
+#define        thr_exit(v)             __libc_thr_exit((v))
+#define        thr_errno()             __libc_thr_errno()
+#define        thr_enabled()           (__isthreaded)
+#define thr_setcancelstate(n, o) __libc_thr_setcancelstate((n),(o))
+#define thr_curcpu()           __libc_thr_curcpu()
+#endif /* __LIBC_THREAD_STUBS */
+
+#define        FLOCKFILE(fp)           __flockfile_internal(fp, 1)
+#define        FUNLOCKFILE(fp)         __funlockfile_internal(fp, 1)
+
+#else /* _REENTRANT */
+
+#define        mutex_init(m, a)
+#define        mutex_lock(m)
+#define        mutex_trylock(m)
+#define        mutex_unlock(m)
+#define        mutex_destroy(m)
+
+#define        cond_init(c, t, a)
+#define        cond_signal(c)
+#define        cond_broadcast(c)
+#define        cond_wait(c, m)
+#define        cond_timedwait(c, m, t)
+#define        cond_destroy(c)
+
+#define        rwlock_init(l, a)
+#define        rwlock_rdlock(l)
+#define        rwlock_wrlock(l)
+#define        rwlock_tryrdlock(l)
+#define        rwlock_trywrlock(l)
+#define        rwlock_unlock(l)
+#define        rwlock_destroy(l)
+
+#define        thr_keycreate(k, d)
+#define        thr_setspecific(k, p)
+#define        thr_getspecific(k)
+#define        thr_keydelete(k)
+
+#define        thr_once(o, f)
+#define        thr_sigsetmask(f, n, o)
+#define        thr_self()
+#define        thr_errno()
+#define        thr_curcpu()            ((unsigned int)0)
+
+#define        FLOCKFILE(fp)           
+#define        FUNLOCKFILE(fp)         
+
+#endif /* _REENTRANT */
diff --git a/lib/nbsd_libc/include/resolv_mt.h b/lib/nbsd_libc/include/resolv_mt.h
new file mode 100644 (file)
index 0000000..73a8dcc
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: resolv_mt.h,v 1.1.1.3 2009/04/12 16:35:44 christos Exp $       */
+
+#ifndef _RESOLV_MT_H
+#define _RESOLV_MT_H
+
+#include <sys/types.h>
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+#include <resolv.h>
+
+/* Access functions for the libresolv private interface */
+
+int    __res_enable_mt(void);
+int    __res_disable_mt(void);
+
+/* Per-thread context */
+
+typedef struct {
+int    no_hosts_fallback_private;
+int    retry_save;
+int    retry_private;
+char   inet_nsap_ntoa_tmpbuf[255*3];
+char   sym_ntos_unname[20];
+char   sym_ntop_unname[20];
+char   p_option_nbuf[40];
+char   p_time_nbuf[40];
+char   precsize_ntoa_retbuf[sizeof "90000000.00"];
+char   loc_ntoa_tmpbuf[sizeof
+"1000 60 60.000 N 1000 60 60.000 W -12345678.00m 90000000.00m 90000000.00m 90000000.00m"];
+char   p_secstodate_output[15];
+} mtctxres_t;
+
+/* Thread-specific data (TSD) */
+
+mtctxres_t     *___mtctxres(void);
+#define mtctxres       (___mtctxres())
+
+/* Various static data that should be TSD */
+
+#define sym_ntos_unname                (mtctxres->sym_ntos_unname)
+#define sym_ntop_unname                (mtctxres->sym_ntop_unname)
+#define inet_nsap_ntoa_tmpbuf  (mtctxres->inet_nsap_ntoa_tmpbuf)
+#define p_option_nbuf          (mtctxres->p_option_nbuf)
+#define p_time_nbuf            (mtctxres->p_time_nbuf)
+#define precsize_ntoa_retbuf   (mtctxres->precsize_ntoa_retbuf)
+#define loc_ntoa_tmpbuf                (mtctxres->loc_ntoa_tmpbuf)
+#define p_secstodate_output    (mtctxres->p_secstodate_output)
+
+#endif /* _RESOLV_MT_H */
diff --git a/lib/nbsd_libc/inet/Makefile.inc b/lib/nbsd_libc/inet/Makefile.inc
new file mode 100644 (file)
index 0000000..5d5ce20
--- /dev/null
@@ -0,0 +1,9 @@
+#      $NetBSD: Makefile.inc,v 1.1 2004/05/20 23:13:02 christos Exp $
+
+# net sources
+.PATH: ${.CURDIR}/inet
+
+SRCS+= _inet_aton.c _inet_pton.c inet_addr.c inet_cidr_ntop.c \
+       inet_cidr_pton.c inet_lnaof.c inet_makeaddr.c \
+       inet_net_ntop.c inet_net_pton.c inet_neta.c inet_netof.c \
+       inet_network.c inet_ntoa.c inet_ntop.c inet_pton.c nsap_addr.c
diff --git a/lib/nbsd_libc/inet/_inet_aton.c b/lib/nbsd_libc/inet/_inet_aton.c
new file mode 100644 (file)
index 0000000..0837a67
--- /dev/null
@@ -0,0 +1,29 @@
+/*     $NetBSD: _inet_aton.c,v 1.4 2005/09/13 01:44:09 christos Exp $  */
+
+/*
+ * Written by Klaus Klein, September 14, 1999.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _inet_aton.c,v 1.4 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_inet_aton, inet_aton)
+#else
+
+#include <sys/types.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+int    _inet_aton(const char *, struct in_addr *);
+
+int
+inet_aton(const char *cp, struct in_addr *addr)
+{
+
+       return _inet_aton(cp, addr);
+}
+#endif
diff --git a/lib/nbsd_libc/inet/_inet_pton.c b/lib/nbsd_libc/inet/_inet_pton.c
new file mode 100644 (file)
index 0000000..7970272
--- /dev/null
@@ -0,0 +1,29 @@
+/*     $NetBSD: _inet_pton.c,v 1.4 2005/09/13 01:44:09 christos Exp $  */
+
+/*
+ * Written by Klaus Klein, September 14, 1999.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _inet_pton.c,v 1.4 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_inet_pton, inet_pton)
+#else
+
+#include <sys/types.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+int    _inet_pton(int, const char *, void *);
+
+int
+inet_pton(int af, const char *src, void *dst)
+{
+
+       return _inet_pton(af, src, dst);
+}
+#endif
diff --git a/lib/nbsd_libc/inet/inet.3 b/lib/nbsd_libc/inet/inet.3
new file mode 100644 (file)
index 0000000..30f42d4
--- /dev/null
@@ -0,0 +1,362 @@
+.\"    $NetBSD: inet.3,v 1.1 2004/05/20 23:13:02 christos Exp $
+.\"
+.\" Copyright (c) 1983, 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)inet.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 30, 2003
+.Dt INET 3
+.Os
+.Sh NAME
+.Nm inet_addr ,
+.Nm inet_aton ,
+.Nm inet_lnaof ,
+.Nm inet_makeaddr ,
+.Nm inet_netof ,
+.Nm inet_network ,
+.Nm inet_ntoa ,
+.Nm inet_ntop ,
+.Nm inet_pton ,
+.Nm addr ,
+.Nm ntoa ,
+.Nm network
+.Nd Internet address manipulation routines
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In arpa/inet.h
+.Ft in_addr_t
+.Fn inet_addr "const char *cp"
+.Ft int
+.Fn inet_aton "const char *cp" "struct in_addr *addr"
+.Ft in_addr_t
+.Fn inet_lnaof "struct in_addr in"
+.Ft struct in_addr
+.Fn inet_makeaddr "in_addr_t net" "in_addr_t lna"
+.Ft in_addr_t
+.Fn inet_netof "struct in_addr in"
+.Ft in_addr_t
+.Fn inet_network "const char *cp"
+.Ft char *
+.Fn inet_ntoa "struct in_addr in"
+.Ft const char *
+.Fn inet_ntop "int af" "const void * restrict src" "char * restrict dst" "socklen_t size"
+.Ft int
+.Fn inet_pton "int af" "const char * restrict src" "void * restrict dst"
+.Sh DESCRIPTION
+The routines
+.Fn inet_aton ,
+.Fn inet_addr
+and
+.Fn inet_network
+interpret character strings representing
+numbers expressed in the Internet standard
+.Qq dotted quad
+notation.
+.Pp
+The
+.Fn inet_pton
+function converts a presentation format address (that is, printable form
+as held in a character string) to network format (usually a
+.Ft struct in_addr
+or some other internal binary representation, in network byte order).
+It returns 1 if the address was valid for the specified address family, or
+0 if the address wasn't parsable in the specified address family, or -1
+if some system error occurred (in which case
+.Va errno
+will have been set).
+This function is presently valid for
+.Dv AF_INET
+and
+.Dv AF_INET6 .
+.Pp
+The
+.Fn inet_aton
+routine interprets the specified character string as an Internet address,
+placing the address into the structure provided.
+It returns 1 if the string was successfully interpreted,
+or 0 if the string is invalid.
+.Pp
+The
+.Fn inet_addr
+and
+.Fn inet_network
+functions return numbers suitable for use
+as Internet addresses and Internet network
+numbers, respectively.
+.Pp
+The function
+.Fn inet_ntop
+converts an address from network format (usually a
+.Ft struct in_addr
+or some other binary form, in network byte order) to presentation format
+(suitable for external display purposes).
+It returns NULL if a system error occurs (in which case,
+.Va errno
+will have been set), or it returns a pointer to the destination string.
+.Pp
+The routine
+.Fn inet_ntoa
+takes an Internet address and returns an
+.Tn ASCII
+string representing the address in
+.Qq dotted quad
+notation.
+.Pp
+The routine
+.Fn inet_makeaddr
+takes an Internet network number and a local network address (both in
+host order) and constructs an Internet address from it.
+Note that to convert only a single value to a
+.Ft struct in_addr
+form that value should be passed as the first parameter and
+.Ql 0L
+should be given for the second parameter.
+.Pp
+The routines
+.Fn inet_netof
+and
+.Fn inet_lnaof
+break apart Internet host addresses, returning the network number and
+local network address part, respectively (both in host order).
+.Pp
+All Internet addresses are returned in network
+order (bytes ordered from left to right).
+All network numbers and local address parts are
+returned as machine format integer values.
+.Sh INTERNET ADDRESSES (IP VERSION 4)
+Values specified using the
+.Qq dotted quad
+notation take one
+of the following forms:
+.Bd -literal -offset indent
+a.b.c.d
+a.b.c
+a.b
+a
+.Ed
+.Pp
+When four parts are specified, each is interpreted
+as a byte of data and assigned, from left to right,
+to the four bytes of an Internet address.
+Note that when an Internet address is viewed as a 32-bit
+integer quantity on a system that uses little-endian
+byte order (e.g.
+.Tn Intel i386, i486
+and
+.Tn Pentium
+processors) the bytes referred to above appear as
+.Dq Li d.c.b.a .
+That is, little-endian bytes are ordered from right to left.
+.Pp
+When a three part address is specified, the last
+part is interpreted as a 16-bit quantity and placed
+in the right-most two bytes of the network address.
+This makes the three part address format convenient
+for specifying Class B network addresses as
+.Dq Li 128.net.host .
+.Pp
+When a two part address is supplied, the last part
+is interpreted as a 24-bit quantity and placed in
+the right most three bytes of the network address.
+This makes the two part address format convenient
+for specifying Class A network addresses as
+.Dq Li net.host .
+.Pp
+When only one part is given, the value is stored
+directly in the network address without any byte
+rearrangement.
+.Pp
+All numbers supplied as
+.Dq parts
+in a
+.Qq dotted quad
+notation
+may be decimal, octal, or hexadecimal, as specified
+in the C language (i.e., a leading 0x or 0X implies
+hexadecimal; otherwise, a leading 0 implies octal;
+otherwise, the number is interpreted as decimal).
+.Sh INTERNET ADDRESSES (IP VERSION 6)
+In order to support scoped IPv6 addresses,
+the use of
+.Xr getaddrinfo 3
+and
+.Xr getnameinfo 3
+is recommended rather than the functions presented here.
+.Pp
+The presentation format of an IPv6 address is given in RFC 2373:
+.Pp
+There are three conventional forms for representing IPv6 addresses as
+text strings:
+.Bl -enum
+.It
+The preferred form is x:x:x:x:x:x:x:x, where the 'x's are the
+hexadecimal values of the eight 16-bit pieces of the address.
+Examples:
+.Bd -literal -offset indent
+FEDC:BA98:7654:3210:FEDC:BA98:7654:3210
+1080:0:0:0:8:800:200C:417A
+.Ed
+.Pp
+Note that it is not necessary to write the leading zeros in an
+individual field, but there must be at least one numeral in
+every field (except for the case described in 2).
+.It
+Due to the method of allocating certain styles of IPv6
+addresses, it will be common for addresses to contain long
+strings of zero bits.
+In order to make writing addresses
+containing zero bits easier, a special syntax is available to
+compress the zeros.
+The use of ``::'' indicates multiple groups of 16-bits of zeros.
+The ``::'' can only appear once in an address.
+The ``::'' can also be used to compress the leading
+and/or trailing zeros in an address.
+.Pp
+For example the following addresses:
+.Bd -literal -offset indent
+1080:0:0:0:8:800:200C:417A  a unicast address
+FF01:0:0:0:0:0:0:43         a multicast address
+0:0:0:0:0:0:0:1             the loopback address
+0:0:0:0:0:0:0:0             the unspecified addresses
+.Ed
+.Pp
+may be represented as:
+.Bd -literal -offset indent
+1080::8:800:200C:417A       a unicast address
+FF01::43                    a multicast address
+::1                         the loopback address
+::                          the unspecified addresses
+.Ed
+.It
+An alternative form that is sometimes more convenient when
+dealing with a mixed environment of IPv4 and IPv6 nodes is
+x:x:x:x:x:x:d.d.d.d, where the 'x's are the hexadecimal values
+of the six high-order 16-bit pieces of the address, and the 'd's
+are the decimal values of the four low-order 8-bit pieces of the
+address (standard IPv4 representation).
+Examples:
+.Bd -literal -offset indent
+0:0:0:0:0:0:13.1.68.3
+0:0:0:0:0:FFFF:129.144.52.38
+.Ed
+.Pp
+or in compressed form:
+.Bd -literal -offset indent
+::13.1.68.3
+::FFFF:129.144.52.38
+.Ed
+.El
+.Sh DIAGNOSTICS
+The constant
+.Dv INADDR_NONE
+is returned by
+.Fn inet_addr
+and
+.Fn inet_network
+for malformed requests.
+.Sh SEE ALSO
+.Xr byteorder 3 ,
+.Xr gethostbyname 3 ,
+.Xr getnetent 3 ,
+.Xr inet_net 3 ,
+.Xr hosts 5 ,
+.Xr networks 5
+.Rs
+.%R RFC 2373
+.%D July 1998
+.%T "IP Version 6 Addressing Architecture"
+.Re
+.Rs
+.%R RFC 3493
+.%D February 2003
+.%T "Basic Socket Interface Extensions for IPv6"
+.Re
+.Sh STANDARDS
+The
+.Nm inet_ntop
+and
+.Nm inet_pton
+functions conform to
+.St -p1003.1-2001 .
+Note that
+.Nm inet_pton
+does not accept 1-, 2-, or 3-part  dotted addresses; all four parts
+must be specified.
+This is a narrower input set than that accepted by
+.Nm inet_aton .
+.Sh HISTORY
+The
+.Nm inet_addr ,
+.Nm inet_network ,
+.Nm inet_makeaddr ,
+.Nm inet_lnaof
+and
+.Nm inet_netof
+functions appeared in
+.Bx 4.2 .
+They were changed to use
+.Va in_addr_t
+in place of
+.Va unsigned long
+in
+.Nx 2.0 .
+The
+.Nm inet_aton
+and
+.Nm inet_ntoa
+functions appeared in
+.Bx 4.3 .
+The
+.Nm inet_pton
+and
+.Nm inet_ntop
+functions appeared in BIND 4.9.4 and thence
+.Nx 1.3 ;
+they were also in
+.St -xns5.2 .
+.Sh BUGS
+The value
+.Dv INADDR_NONE
+(0xffffffff) is a valid broadcast address, but
+.Fn inet_addr
+cannot return that value without indicating failure.
+The newer
+.Fn inet_aton
+function does not share this problem.
+.Pp
+The problem of host byte ordering versus network byte ordering is
+confusing.
+.Pp
+The string returned by
+.Fn inet_ntoa
+resides in a static memory area.
+.Pp
+.Fn inet_addr
+should return a
+.Fa "struct in_addr" .
diff --git a/lib/nbsd_libc/inet/inet6_option_space.3 b/lib/nbsd_libc/inet/inet6_option_space.3
new file mode 100644 (file)
index 0000000..c6407ae
--- /dev/null
@@ -0,0 +1,448 @@
+.\"    $NetBSD: inet6_option_space.3,v 1.3 2010/03/22 19:30:54 joerg Exp $
+.\"    $KAME: inet6_option_space.3,v 1.7 2000/05/17 14:32:13 itojun Exp $
+.\"
+.\" Copyright (c) 1983, 1987, 1991, 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.
+.\" 3. 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.
+.\"
+.Dd December 10, 1999
+.Dt INET6_OPTION_SPACE 3
+.Os
+.\"
+.Sh NAME
+.Nm inet6_option_space ,
+.Nm inet6_option_init ,
+.Nm inet6_option_append ,
+.Nm inet6_option_alloc ,
+.Nm inet6_option_next ,
+.Nm inet6_option_find
+.Nd IPv6 Hop-by-Hop and Destination Options manipulation
+.\"
+.Sh SYNOPSIS
+.In netinet/in.h
+.Ft "int"
+.Fn inet6_option_space "int nbytes"
+.Ft "int"
+.Fn inet6_option_init "void *bp" "struct cmsghdr **cmsgp" "int type"
+.Ft "int"
+.Fn inet6_option_append "struct cmsghdr *cmsg" "const uint8_t *typep" "int multx" "int plusy"
+.Ft "uint8_t *"
+.Fn inet6_option_alloc "struct cmsghdr *cmsg" "int datalen" "int multx" "int plusy"
+.Ft "int"
+.Fn inet6_option_next "const struct cmsghdr *cmsg" "uint8_t **tptrp"
+.Ft "int"
+.Fn inet6_option_find "const struct cmsghdr *cmsg" "uint8_t **tptrp" "int type"
+.\"
+.Sh DESCRIPTION
+.\"
+Building and parsing the Hop-by-Hop and Destination options is
+complicated due to alignment constraints, padding and
+ancillary data manipulation.
+RFC 2292 defines a set of functions to help the application.
+The function prototypes for
+these functions are all in the
+.In netinet/in.h
+header.
+.\"
+.Ss inet6_option_space
+.Fn inet6_option_space
+returns the number of bytes required to hold an option when it is stored as
+ancillary data, including the
+.Li cmsghdr
+structure at the beginning,
+and any padding at the end
+.Po
+to make its size a multiple of 8 bytes
+.Pc .
+The argument is the size of the structure defining the option,
+which must include any pad bytes at the beginning
+.Po
+the value
+.Li y
+in the alignment term
+.Dq Li xn + y
+.Pc ,
+the type byte, the length byte, and the option data.
+.Pp
+Note: If multiple options are stored in a single ancillary data
+object, which is the recommended technique, this function
+overestimates the amount of space required by the size of
+.Li N-1
+.Li cmsghdr
+structures,
+where
+.Li N
+is the number of options to be stored in the object.
+This is of little consequence, since it is assumed that most
+Hop-by-Hop option headers and Destination option headers carry only
+one option
+.Pq appendix B of [RFC 2460] .
+.\"
+.Ss inet6_option_init
+.Fn inet6_option_init
+is called once per ancillary data object that will
+contain either Hop-by-Hop or Destination options.
+It returns
+.Li 0
+on success or
+.Li -1
+on an error.
+.Pp
+.Fa bp
+is a pointer to previously allocated space that will contain the
+ancillary data object.
+It must be large enough to contain all the
+individual options to be added by later calls to
+.Fn inet6_option_append
+and
+.Fn inet6_option_alloc .
+.Pp
+.Fa cmsgp
+is a pointer to a pointer to a
+.Li cmsghdr
+structure.
+.Fa *cmsgp
+is initialized by this function to point to the
+.Li cmsghdr
+structure constructed by this function in the buffer pointed to by
+.Fa bp .
+.Pp
+.Fa type
+is either
+.Dv IPV6_HOPOPTS
+or
+.Dv IPV6_DSTOPTS .
+This
+.Fa type
+is stored in the
+.Li cmsg_type
+member of the
+.Li cmsghdr
+structure pointed to by
+.Fa *cmsgp .
+.\"
+.Ss inet6_option_append
+This function appends a Hop-by-Hop option or a Destination option
+into an ancillary data object that has been initialized by
+.Fn inet6_option_init .
+This function returns
+.Li 0
+if it succeeds or
+.Li -1
+on an error.
+.Pp
+.Fa cmsg
+is a pointer to the
+.Li cmsghdr
+structure that must have been
+initialized by
+.Fn inet6_option_init .
+.Pp
+.Fa typep
+is a pointer to the 8-bit option type.
+It is assumed that this
+field is immediately followed by the 8-bit option data length field,
+which is then followed immediately by the option data.
+The caller
+initializes these three fields
+.Pq the type-length-value, or TLV
+before calling this function.
+.Pp
+The option type must have a value from
+.Li 2
+to
+.Li 255 ,
+inclusive.
+.Po
+.Li 0
+and
+.Li 1
+are reserved for the
+.Li Pad1
+and
+.Li PadN
+options, respectively.
+.Pc
+.Pp
+The option data length must have a value between
+.Li 0
+and
+.Li 255 ,
+inclusive, and is the length of the option data that follows.
+.Pp
+.Fa multx
+is the value
+.Li x
+in the alignment term
+.Dq Li xn + y .
+It must have a value of
+.Li 1 ,
+.Li 2 ,
+.Li 4 ,
+or
+.Li 8 .
+.Pp
+.Fa plusy
+is the value
+.Li y
+in the alignment term
+.Dq Li xn + y .
+It must have a value between
+.Li 0
+and
+.Li 7 ,
+inclusive.
+.\"
+.Ss inet6_option_alloc
+This function appends a Hop-by-Hop option or a Destination option
+into an ancillary data object that has been initialized by
+.Fn inet6_option_init .
+This function returns a pointer to the 8-bit
+option type field that starts the option on success, or
+.Dv NULL
+on an error.
+.Pp
+The difference between this function and
+.Fn inet6_option_append
+is that the latter copies the contents of a previously built option into
+the ancillary data object while the current function returns a
+pointer to the space in the data object where the option's TLV must
+then be built by the caller.
+.Pp
+.Fa cmsg
+is a pointer to the
+.Li cmsghdr
+structure that must have been
+initialized by
+.Fn inet6_option_init .
+.Pp
+.Fa datalen
+is the value of the option data length byte for this option.
+This value is required as an argument to allow the function to
+determine if padding must be appended at the end of the option.
+.Po
+The
+.Fn inet6_option_append
+function does not need a data length argument
+since the option data length must already be stored by the caller.
+.Pc
+.Pp
+.Fa multx
+is the value
+.Li x
+in the alignment term
+.Dq Li xn + y .
+It must have a value of
+.Li 1 ,
+.Li 2 ,
+.Li 4 ,
+or
+.Li 8 .
+.Pp
+.Fa plusy
+is the value
+.Li y
+in the alignment term
+.Dq Li xn + y .
+It must have a value between
+.Li 0
+and
+.Li 7 ,
+inclusive.
+.\"
+.Ss inet6_option_next
+This function processes the next Hop-by-Hop option or Destination
+option in an ancillary data object.
+If another option remains to be
+processed, the return value of the function is
+.Li 0
+and
+.Fa *tptrp
+points to
+the 8-bit option type field
+.Po
+which is followed by the 8-bit option
+data length, followed by the option data
+.Pc .
+If no more options remain
+to be processed, the return value is
+.Li -1
+and
+.Fa *tptrp
+is
+.Dv NULL .
+If an error occurs, the return value is
+.Li -1
+and
+.Fa *tptrp
+is not
+.Dv NULL .
+.Pp
+.Fa cmsg
+is a pointer to
+.Li cmsghdr
+structure of which
+.Li cmsg_level
+equals
+.Dv IPPROTO_IPV6
+and
+.Li cmsg_type
+equals either
+.Dv IPV6_HOPOPTS
+or
+.Dv IPV6_DSTOPTS .
+.Pp
+.Fa tptrp
+is a pointer to a pointer to an 8-bit byte and
+.Fa *tptrp
+is used
+by the function to remember its place in the ancillary data object
+each time the function is called.
+The first time this function is
+called for a given ancillary data object,
+.Fa *tptrp
+must be set to
+.Dv NULL .
+.Pp
+Each time this function returns success,
+.Fa *tptrp
+points to the 8-bit
+option type field for the next option to be processed.
+.\"
+.Ss inet6_option_find
+This function is similar to the previously described
+.Fn inet6_option_next
+function, except this function lets the caller
+specify the option type to be searched for, instead of always
+returning the next option in the ancillary data object.
+.Fa cmsg
+is a
+pointer to
+.Li cmsghdr
+structure of which
+.Li cmsg_level
+equals
+.Dv IPPROTO_IPV6
+and
+.Li cmsg_type
+equals either
+.Dv IPV6_HOPOPTS
+or
+.Dv IPV6_DSTOPTS .
+.Pp
+.Fa tptrp
+is a pointer to a pointer to an 8-bit byte and
+.Fa *tptrp
+is used
+by the function to remember its place in the ancillary data object
+each time the function is called.
+The first time this function is
+called for a given ancillary data object,
+.Fa *tptrp
+must be set to
+.Dv NULL .
+.Pa
+This function starts searching for an option of the specified type
+beginning after the value of
+.Fa *tptrp .
+If an option of the specified
+type is located, this function returns
+.Li 0
+and
+.Fa *tptrp
+points to the 8-
+bit option type field for the option of the specified type.
+If an
+option of the specified type is not located, the return value is
+.Li -1
+and
+.Fa *tptrp
+is
+.Dv NULL .
+If an error occurs, the return value is
+.Li -1
+and
+.Fa *tptrp
+is not
+.Dv NULL .
+.\"
+.Sh EXAMPLES
+RFC 2292 gives comprehensive examples in chapter 6.
+.\"
+.Sh DIAGNOSTICS
+.Fn inet6_option_init
+and
+.Fn inet6_option_append
+return
+.Li 0
+on success or
+.Li -1
+on an error.
+.Pp
+.Fn inet6_option_alloc
+returns
+.Dv NULL
+on an error.
+.Pp
+On errors,
+.Fn inet6_option_next
+and
+.Fn inet6_option_find
+return
+.Li -1
+setting
+.Fa *tptrp
+to non
+.Dv NULL
+value.
+.\"
+.Sh SEE ALSO
+.Rs
+.%A W. Stevens
+.%A M. Thomas
+.%T "Advanced Sockets API for IPv6"
+.%N RFC 2292
+.%D February 1998
+.Re
+.Rs
+.%A S. Deering
+.%A R. Hinden
+.%T "Internet Protocol, Version 6 (IPv6) Specification"
+.%N RFC 2460
+.%D December 1998
+.Re
+.\"
+.Sh STANDARDS
+The functions
+are documented in
+.Dq Advanced Sockets API for IPv6
+.Pq RFC 2292 .
+.\"
+.Sh HISTORY
+The implementation first appeared in KAME advanced networking kit.
+.\"
+.Sh BUGS
+The text was shamelessly copied from RFC 2292.
diff --git a/lib/nbsd_libc/inet/inet6_rthdr_space.3 b/lib/nbsd_libc/inet/inet6_rthdr_space.3
new file mode 100644 (file)
index 0000000..50f852c
--- /dev/null
@@ -0,0 +1,321 @@
+.\"    $NetBSD: inet6_rthdr_space.3,v 1.2 2010/03/22 19:30:54 joerg Exp $
+.\"    $KAME: inet6_rthdr_space.3,v 1.8 2000/05/17 14:30:15 itojun Exp $
+.\"
+.\" Copyright (c) 1983, 1987, 1991, 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.
+.\" 3. 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.
+.\"
+.Dd December 10, 1999
+.Dt INET6_RTHDR_SPACE 3
+.Os
+.\"
+.Sh NAME
+.Nm inet6_rthdr_space ,
+.Nm inet6_rthdr_init ,
+.Nm inet6_rthdr_add ,
+.Nm inet6_rthdr_lasthop ,
+.Nm inet6_rthdr_reverse ,
+.Nm inet6_rthdr_segments ,
+.Nm inet6_rthdr_getaddr ,
+.Nm inet6_rthdr_getflags
+.Nd IPv6 Routing Header Options manipulation
+.\"
+.Sh SYNOPSIS
+.In netinet/in.h
+.Ft size_t
+.Fn inet6_rthdr_space "int type" "int segments"
+.Ft "struct cmsghdr *"
+.Fn inet6_rthdr_init "void *bp" "int type"
+.Ft int
+.Fn inet6_rthdr_add "struct cmsghdr *cmsg" "const struct in6_addr *addr" "unsigned int flags"
+.Ft int
+.Fn inet6_rthdr_lasthop "struct cmsghdr *cmsg" "unsigned int flags"
+.Ft int
+.Fn inet6_rthdr_reverse "const struct cmsghdr *in" "struct cmsghdr *out"
+.Ft int
+.Fn inet6_rthdr_segments "const struct cmsghdr *cmsg"
+.Ft "struct in6_addr *"
+.Fn inet6_rthdr_getaddr "struct cmsghdr *cmsg" "int index"
+.Ft int
+.Fn inet6_rthdr_getflags "const struct cmsghdr *cmsg" "int index"
+.\"
+.Sh DESCRIPTION
+RFC 2292 IPv6 advanced API defines eight
+functions that the application calls to build and examine a Routing
+header.
+Four functions build a Routing header:
+.Bl -hang
+.It Fn inet6_rthdr_space
+return #bytes required for ancillary data
+.It Fn inet6_rthdr_init
+initialize ancillary data for Routing header
+.It Fn inet6_rthdr_add
+add IPv6 address \*[Am] flags to Routing header
+.It Fn inet6_rthdr_lasthop
+specify the flags for the final hop
+.El
+.Pp
+Four functions deal with a returned Routing header:
+.Bl -hang
+.It Fn inet6_rthdr_reverse
+reverse a Routing header
+.It Fn inet6_rthdr_segments
+return #segments in a Routing header
+.It Fn inet6_rthdr_getaddr
+fetch one address from a Routing header
+.It Fn inet6_rthdr_getflags
+fetch one flag from a Routing header
+.El
+.Pp
+The function prototypes for these functions are all in the
+.In netinet/in.h
+header.
+.\"
+.Ss inet6_rthdr_space
+This function returns the number of bytes required to hold a Routing
+header of the specified
+.Fa type
+containing the specified number of
+.Fa segments
+.Pq addresses .
+For an IPv6 Type 0 Routing header, the number
+of segments must be between 1 and 23, inclusive.
+The return value
+includes the size of the cmsghdr structure that precedes the Routing
+header, and any required padding.
+.Pp
+If the return value is 0, then either the type of the Routing header
+is not supported by this implementation or the number of segments is
+invalid for this type of Routing header.
+.Pp
+Note: This function returns the size but does not allocate the space
+required for the ancillary data.
+This allows an application to
+allocate a larger buffer, if other ancillary data objects are
+desired, since all the ancillary data objects must be specified to
+.Xr sendmsg 2
+as a single
+.Li msg_control
+buffer.
+.\"
+.Ss inet6_rthdr_init
+This function initializes the buffer pointed to by
+.Fa bp
+to contain a
+.Li cmsghdr
+structure followed by a Routing header of the specified
+.Fa type .
+The
+.Li cmsg_len
+member of the
+.Li cmsghdr
+structure is initialized to the
+size of the structure plus the amount of space required by the
+Routing header.
+The
+.Li cmsg_level
+and
+.Li cmsg_type
+members are also initialized as required.
+.Pp
+The caller must allocate the buffer and its size can be determined by
+calling
+.Fn inet6_rthdr_space .
+.Pp
+Upon success the return value is the pointer to the
+.Li cmsghdr
+structure, and this is then used as the first argument to the next
+two functions.
+Upon an error the return value is
+.Dv NULL .
+.\"
+.Ss inet6_rthdr_add
+This function adds the address pointed to by
+.Fa addr
+to the end of the
+Routing header being constructed and sets the type of this hop to the
+value of
+.Fa flags .
+For an IPv6 Type 0 Routing header,
+.Fa flags
+must be
+either
+.Dv IPV6_RTHDR_LOOSE
+or
+.Dv IPV6_RTHDR_STRICT .
+.Pp
+If successful, the
+.Li cmsg_len
+member of the
+.Li cmsghdr
+structure is
+updated to account for the new address in the Routing header and the
+return value of the function is 0.
+Upon an error the return value of
+the function is -1.
+.\"
+.Ss inet6_rthdr_lasthop
+This function specifies the Strict/Loose flag for the final hop of a
+Routing header.
+For an IPv6 Type 0 Routing header,
+.Fa flags
+must be either
+.Dv IPV6_RTHDR_LOOSE
+or
+.Dv IPV6_RTHDR_STRICT .
+.Pp
+The return value of the function is 0 upon success, or -1 upon an error.
+.Pp
+Notice that a Routing header specifying
+.Li N
+intermediate nodes requires
+.Li N+1
+Strict/Loose flags.
+This requires
+.Li N
+calls to
+.Fn inet6_rthdr_add
+followed by one call to
+.Fn inet6_rthdr_lasthop .
+.\"
+.Ss inet6_rthdr_reverse
+This function takes a Routing header that was received as ancillary
+data
+.Po
+pointed to by the first argument,
+.Fa in
+.Pc
+and writes a new Routing
+header that sends datagrams along the reverse of that route.
+Both
+arguments are allowed to point to the same buffer
+.Pq that is, the reversal can occur in place .
+.Pp
+The return value of the function is 0 on success, or -1 upon an
+error.
+.\"
+.Ss inet6_rthdr_segments
+This function returns the number of segments
+.Pq addresses
+contained in
+the Routing header described by
+.Fa cmsg .
+On success the return value is
+between 1 and 23, inclusive.
+The return value of the function is -1 upon an error.
+.\"
+.Ss inet6_rthdr_getaddr
+This function returns a pointer to the IPv6 address specified by
+.Fa index
+.Po
+which must have a value between 1 and the value returned by
+.Fn inet6_rthdr_segments
+.Pc
+in the Routing header described by
+.Fa cmsg .
+An
+application should first call
+.Fn inet6_rthdr_segments
+to obtain the number of segments in the Routing header.
+.Pp
+Upon an error the return value of the function is
+.Dv NULL .
+.\"
+.Ss inet6_rthdr_getflags
+This function returns the flags value specified by
+.Fa index
+.Po
+which must
+have a value between 0 and the value returned by
+.Fn inet6_rthdr_segments
+.Pc
+in the Routing header described by
+.Fa cmsg .
+For an IPv6 Type 0 Routing header the return value will be either
+.Dv IPV6_RTHDR_LOOSE
+or
+.Dv IPV6_RTHDR_STRICT .
+.Pp
+Upon an error the return value of the function is -1.
+.Pp
+Note: Addresses are indexed starting at 1, and flags starting at 0,
+to maintain consistency with the terminology and figures in RFC 2460.
+.\"
+.Sh EXAMPLES
+RFC 2292 gives comprehensive examples in chapter 8.
+.\"
+.Sh DIAGNOSTICS
+.Fn inet6_rthdr_space
+returns 0 on errors.
+.Pp
+.Fn inet6_rthdr_add ,
+.Fn inet6_rthdr_lasthop
+and
+.Fn inet6_rthdr_reverse
+return 0 on success, and returns -1 on error.
+.Pp
+.Fn inet6_rthdr_init
+and
+.Fn inet6_rthdr_getaddr
+return
+.Dv NULL
+on error.
+.Pp
+.Fn inet6_rthdr_segments
+and
+.Fn inet6_rthdr_getflags
+return -1 on error.
+.\"
+.Sh SEE ALSO
+.Rs
+.%A W. Stevens
+.%A M. Thomas
+.%T "Advanced Sockets API for IPv6"
+.%N RFC 2292
+.%D February 1998
+.Re
+.Rs
+.%A S. Deering
+.%A R. Hinden
+.%T "Internet Protocol, Version 6 (IPv6) Specification"
+.%N RFC 2460
+.%D December 1998
+.Re
+.\"
+.Sh STANDARDS
+The functions
+are documented in
+.Dq Advanced Sockets API for IPv6
+.Pq RFC 2292 .
+.\"
+.Sh HISTORY
+The implementation first appeared in KAME advanced networking kit.
+.\"
+.Sh BUGS
+The text was shamelessly copied from RFC 2292.
+.Pp
+.Fn inet6_rthdr_reverse
+is not implemented yet.
diff --git a/lib/nbsd_libc/inet/inet_cidr_ntop.c b/lib/nbsd_libc/inet/inet_cidr_ntop.c
new file mode 100644 (file)
index 0000000..bd88772
--- /dev/null
@@ -0,0 +1,275 @@
+/*     $NetBSD: inet_cidr_ntop.c,v 1.7 2009/04/12 17:07:16 christos Exp $      */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1998,1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static const char rcsid[] = "Id: inet_cidr_ntop.c,v 1.7 2006/10/11 02:18:18 marka Exp";
+#else
+__RCSID("$NetBSD: inet_cidr_ntop.c,v 1.7 2009/04/12 17:07:16 christos Exp $");
+#endif
+#endif
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+#include <arpa/inet.h>
+
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "port_after.h"
+
+#ifdef __weak_alias
+__weak_alias(inet_cidr_ntop,_inet_cidr_ntop)
+#endif
+
+#ifdef SPRINTF_CHAR
+# define SPRINTF(x) strlen(sprintf/**/x)
+#else
+# define SPRINTF(x) ((size_t)sprintf x)
+#endif
+
+static char *
+inet_cidr_ntop_ipv4(const u_char *src, int bits, char *dst, size_t size);
+static char *
+inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size);
+
+/*%
+ * char *
+ * inet_cidr_ntop(af, src, bits, dst, size)
+ *     convert network address from network to presentation format.
+ *     "src"'s size is determined from its "af".
+ * return:
+ *     pointer to dst, or NULL if an error occurred (check errno).
+ * note:
+ *     192.5.5.1/28 has a nonzero host part, which means it isn't a network
+ *     as called for by inet_net_ntop() but it can be a host address with
+ *     an included netmask.
+ * author:
+ *     Paul Vixie (ISC), October 1998
+ */
+char *
+inet_cidr_ntop(int af, const void *src, int bits, char *dst, size_t size) {
+       switch (af) {
+       case AF_INET:
+               return (inet_cidr_ntop_ipv4(src, bits, dst, size));
+       case AF_INET6:
+               return (inet_cidr_ntop_ipv6(src, bits, dst, size));
+       default:
+               errno = EAFNOSUPPORT;
+               return (NULL);
+       }
+}
+
+static int
+decoct(const u_char *src, size_t bytes, char *dst, size_t size) {
+       char *odst = dst;
+       char *t;
+       size_t b;
+
+       for (b = 1; b <= bytes; b++) {
+               if (size < sizeof "255.")
+                       return (0);
+               t = dst;
+               dst += SPRINTF((dst, "%u", *src++));
+               if (b != bytes) {
+                       *dst++ = '.';
+                       *dst = '\0';
+               }
+               size -= (size_t)(dst - t);
+       }
+       return (dst - odst);
+}
+
+/*%
+ * static char *
+ * inet_cidr_ntop_ipv4(src, bits, dst, size)
+ *     convert IPv4 network address from network to presentation format.
+ *     "src"'s size is determined from its "af".
+ * return:
+ *     pointer to dst, or NULL if an error occurred (check errno).
+ * note:
+ *     network byte order assumed.  this means 192.5.5.240/28 has
+ *     0b11110000 in its fourth octet.
+ * author:
+ *     Paul Vixie (ISC), October 1998
+ */
+static char *
+inet_cidr_ntop_ipv4(const u_char *src, int bits, char *dst, size_t size) {
+       char *odst = dst;
+       size_t len = 4;
+       size_t b;
+       size_t bytes;
+
+       if ((bits < -1) || (bits > 32)) {
+               errno = EINVAL;
+               return (NULL);
+       }
+
+       /* Find number of significant bytes in address. */
+       if (bits == -1)
+               len = 4;
+       else
+               for (len = 1, b = 1 ; b < 4U; b++)
+                       if (*(src + b))
+                               len = b + 1;
+
+       /* Format whole octets plus nonzero trailing octets. */
+       bytes = (((bits <= 0) ? 1 : bits) + 7) / 8;
+       if (len > bytes)
+               bytes = len;
+       b = decoct(src, bytes, dst, size);
+       if (b == 0U)
+               goto emsgsize;
+       dst += b;
+       size -= b;
+
+       if (bits != -1) {
+               /* Format CIDR /width. */
+               if (size < sizeof "/32")
+                       goto emsgsize;
+               dst += SPRINTF((dst, "/%u", bits));
+       }
+
+       return (odst);
+
+ emsgsize:
+       errno = EMSGSIZE;
+       return (NULL);
+}
+static char *
+inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) {
+       /*
+        * Note that int32_t and int16_t need only be "at least" large enough
+        * to contain a value of the specified size.  On some systems, like
+        * Crays, there is no such thing as an integer variable with 16 bits.
+        * Keep this in mind if you think this function should have been coded
+        * to use pointer overlays.  All the world's not a VAX.
+        */
+       char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255/128"];
+       char *tp;
+       struct { int base, len; } best, cur;
+       u_int words[NS_IN6ADDRSZ / NS_INT16SZ];
+       int i;
+
+       if ((bits < -1) || (bits > 128)) {
+               errno = EINVAL;
+               return (NULL);
+       }
+
+       /*
+        * Preprocess:
+        *      Copy the input (bytewise) array into a wordwise array.
+        *      Find the longest run of 0x00's in src[] for :: shorthanding.
+        */
+       memset(words, '\0', sizeof words);
+       for (i = 0; i < NS_IN6ADDRSZ; i++)
+               words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
+       best.base = -1;
+       best.len = 0;
+       cur.base = -1;
+       cur.len = 0;
+       for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
+               if (words[i] == 0) {
+                       if (cur.base == -1)
+                               cur.base = i, cur.len = 1;
+                       else
+                               cur.len++;
+               } else {
+                       if (cur.base != -1) {
+                               if (best.base == -1 || cur.len > best.len)
+                                       best = cur;
+                               cur.base = -1;
+                       }
+               }
+       }
+       if (cur.base != -1) {
+               if (best.base == -1 || cur.len > best.len)
+                       best = cur;
+       }
+       if (best.base != -1 && best.len < 2)
+               best.base = -1;
+
+       /*
+        * Format the result.
+        */
+       tp = tmp;
+       for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
+               /* Are we inside the best run of 0x00's? */
+               if (best.base != -1 && i >= best.base &&
+                   i < (best.base + best.len)) {
+                       if (i == best.base)
+                               *tp++ = ':';
+                       continue;
+               }
+               /* Are we following an initial run of 0x00s or any real hex? */
+               if (i != 0)
+                       *tp++ = ':';
+               /* Is this address an encapsulated IPv4? */
+               if (i == 6 && best.base == 0 && (best.len == 6 ||
+                   (best.len == 7 && words[7] != 0x0001) ||
+                   (best.len == 5 && words[5] == 0xffff))) {
+                       size_t n;
+
+                       if (src[15] || bits == -1 || bits > 120)
+                               n = 4;
+                       else if (src[14] || bits > 112)
+                               n = 3;
+                       else
+                               n = 2;
+                       n = decoct(src+12, n, tp, sizeof tmp - (tp - tmp));
+                       if (n == 0) {
+                               errno = EMSGSIZE;
+                               return (NULL);
+                       }
+                       tp += strlen(tp);
+                       break;
+               }
+               tp += SPRINTF((tp, "%x", words[i]));
+       }
+
+       /* Was it a trailing run of 0x00's? */
+       if (best.base != -1 && (best.base + best.len) == 
+           (NS_IN6ADDRSZ / NS_INT16SZ))
+               *tp++ = ':';
+       *tp = '\0';
+
+       if (bits != -1)
+               tp += SPRINTF((tp, "/%u", bits));
+
+       /*
+        * Check for overflow, copy, and we're done.
+        */
+       if ((size_t)(tp - tmp) > size) {
+               errno = EMSGSIZE;
+               return (NULL);
+       }
+       strcpy(dst, tmp);
+       return (dst);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/inet/inet_cidr_pton.c b/lib/nbsd_libc/inet/inet_cidr_pton.c
new file mode 100644 (file)
index 0000000..1ffbc9a
--- /dev/null
@@ -0,0 +1,289 @@
+/*     $NetBSD: inet_cidr_pton.c,v 1.6 2009/04/12 17:07:16 christos Exp $      */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1998,1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static const char rcsid[] = "Id: inet_cidr_pton.c,v 1.6 2005/04/27 04:56:19 sra Exp";
+#else
+__RCSID("$NetBSD: inet_cidr_pton.c,v 1.6 2009/04/12 17:07:16 christos Exp $");
+#endif
+#endif
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+#include <arpa/inet.h>
+
+#include <isc/assertions.h>
+#include <ctype.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "port_after.h"
+
+#ifdef SPRINTF_CHAR
+# define SPRINTF(x) strlen(sprintf/**/x)
+#else
+# define SPRINTF(x) ((size_t)sprintf x)
+#endif
+
+#ifdef __weak_alias
+__weak_alias(inet_cidr_pton,_inet_cidr_pton)
+#endif
+
+static int     inet_cidr_pton_ipv4 __P((const char *src, u_char *dst,
+                                        int *bits, int ipv6));
+static int     inet_cidr_pton_ipv6 __P((const char *src, u_char *dst,
+                                        int *bits));
+
+static int     getbits(const char *, int ipv6);
+
+/*%
+ * int
+ * inet_cidr_pton(af, src, dst, *bits)
+ *     convert network address from presentation to network format.
+ *     accepts inet_pton()'s input for this "af" plus trailing "/CIDR".
+ *     "dst" is assumed large enough for its "af".  "bits" is set to the
+ *     /CIDR prefix length, which can have defaults (like /32 for IPv4).
+ * return:
+ *     -1 if an error occurred (inspect errno; ENOENT means bad format).
+ *     0 if successful conversion occurred.
+ * note:
+ *     192.5.5.1/28 has a nonzero host part, which means it isn't a network
+ *     as called for by inet_net_pton() but it can be a host address with
+ *     an included netmask.
+ * author:
+ *     Paul Vixie (ISC), October 1998
+ */
+int
+inet_cidr_pton(int af, const char *src, void *dst, int *bits) {
+       switch (af) {
+       case AF_INET:
+               return (inet_cidr_pton_ipv4(src, dst, bits, 0));
+       case AF_INET6:
+               return (inet_cidr_pton_ipv6(src, dst, bits));
+       default:
+               errno = EAFNOSUPPORT;
+               return (-1);
+       }
+}
+
+static const char digits[] = "0123456789";
+
+static int
+inet_cidr_pton_ipv4(const char *src, u_char *dst, int *pbits, int ipv6) {
+       const u_char *odst = dst;
+       int n, ch, tmp, bits;
+       size_t size = 4;
+
+       /* Get the mantissa. */
+       while (ch = *src++, (isascii(ch) && isdigit(ch))) {
+               tmp = 0;
+               do {
+                       n = strchr(digits, ch) - digits;
+                       INSIST(n >= 0 && n <= 9);
+                       tmp *= 10;
+                       tmp += n;
+                       if (tmp > 255)
+                               goto enoent;
+               } while ((ch = *src++) != '\0' && isascii(ch) && isdigit(ch));
+               if (size-- == 0U)
+                       goto emsgsize;
+               *dst++ = (u_char) tmp;
+               if (ch == '\0' || ch == '/')
+                       break;
+               if (ch != '.')
+                       goto enoent;
+       }
+
+       /* Get the prefix length if any. */
+       bits = -1;
+       if (ch == '/' && dst > odst) {
+               bits = getbits(src, ipv6);
+               if (bits == -2)
+                       goto enoent;
+       } else if (ch != '\0')
+               goto enoent;
+
+       /* Prefix length can default to /32 only if all four octets spec'd. */
+       if (bits == -1) {
+               if (dst - odst == 4)
+                       bits = ipv6 ? 128 : 32;
+               else
+                       goto enoent;
+       }
+
+       /* If nothing was written to the destination, we found no address. */
+       if (dst == odst)
+               goto enoent;
+
+       /* If prefix length overspecifies mantissa, life is bad. */
+       if (((bits - (ipv6 ? 96 : 0)) / 8) > (dst - odst))
+               goto enoent;
+
+       /* Extend address to four octets. */
+       while (size-- > 0U)
+               *dst++ = 0;
+
+       *pbits = bits;
+       return (0);
+
+ enoent:
+       errno = ENOENT;
+       return (-1);
+
+ emsgsize:
+       errno = EMSGSIZE;
+       return (-1);
+}
+
+static int
+inet_cidr_pton_ipv6(const char *src, u_char *dst, int *pbits) {
+       static const char xdigits_l[] = "0123456789abcdef",
+                         xdigits_u[] = "0123456789ABCDEF";
+       u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp;
+       const char *xdigits, *curtok;
+       int ch, saw_xdigit;
+       u_int val;
+       int bits;
+
+       memset((tp = tmp), '\0', NS_IN6ADDRSZ);
+       endp = tp + NS_IN6ADDRSZ;
+       colonp = NULL;
+       /* Leading :: requires some special handling. */
+       if (*src == ':')
+               if (*++src != ':')
+                       return (0);
+       curtok = src;
+       saw_xdigit = 0;
+       val = 0;
+       bits = -1;
+       while ((ch = *src++) != '\0') {
+               const char *pch;
+
+               if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL)
+                       pch = strchr((xdigits = xdigits_u), ch);
+               if (pch != NULL) {
+                       val <<= 4;
+                       val |= (pch - xdigits);
+                       if (val > 0xffff)
+                               return (0);
+                       saw_xdigit = 1;
+                       continue;
+               }
+               if (ch == ':') {
+                       curtok = src;
+                       if (!saw_xdigit) {
+                               if (colonp)
+                                       return (0);
+                               colonp = tp;
+                               continue;
+                       } else if (*src == '\0') {
+                               return (0);
+                       }
+                       if (tp + NS_INT16SZ > endp)
+                               return (0);
+                       *tp++ = (u_char) (val >> 8) & 0xff;
+                       *tp++ = (u_char) val & 0xff;
+                       saw_xdigit = 0;
+                       val = 0;
+                       continue;
+               }
+               if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) &&
+                   inet_cidr_pton_ipv4(curtok, tp, &bits, 1) == 0) {
+                       tp += NS_INADDRSZ;
+                       saw_xdigit = 0;
+                       break;  /*%< '\\0' was seen by inet_pton4(). */
+               }
+               if (ch == '/') {
+                       bits = getbits(src, 1);
+                       if (bits == -2)
+                               goto enoent;
+                       break;
+               }
+               goto enoent;
+       }
+       if (saw_xdigit) {
+               if (tp + NS_INT16SZ > endp)
+                       goto emsgsize;
+               *tp++ = (u_char) (val >> 8) & 0xff;
+               *tp++ = (u_char) val & 0xff;
+       }
+       if (colonp != NULL) {
+               /*
+                * Since some memmove()'s erroneously fail to handle
+                * overlapping regions, we'll do the shift by hand.
+                */
+               const int n = tp - colonp;
+               int i;
+
+               if (tp == endp)
+                       goto enoent;
+               for (i = 1; i <= n; i++) {
+                       endp[- i] = colonp[n - i];
+                       colonp[n - i] = 0;
+               }
+               tp = endp;
+       }
+
+       memcpy(dst, tmp, NS_IN6ADDRSZ);
+
+       *pbits = bits;
+       return (0);
+
+ enoent:
+       errno = ENOENT;
+       return (-1);
+
+ emsgsize:
+       errno = EMSGSIZE;
+       return (-1);
+}
+
+static int
+getbits(const char *src, int ipv6) {
+       int bits = 0;
+       char *cp, ch;
+       
+       if (*src == '\0')                       /*%< syntax */
+               return (-2);
+       do {
+               ch = *src++;
+               cp = strchr(digits, ch);
+               if (cp == NULL)                 /*%< syntax */
+                       return (-2);
+               bits *= 10;
+               bits += cp - digits;
+               if (bits == 0 && *src != '\0')  /*%< no leading zeros */
+                       return (-2);
+               if (bits > (ipv6 ? 128 : 32))   /*%< range error */
+                       return (-2);
+       } while (*src != '\0');
+
+       return (bits);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/inet/inet_lnaof.c b/lib/nbsd_libc/inet/inet_lnaof.c
new file mode 100644 (file)
index 0000000..3f66cbe
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: inet_lnaof.c,v 1.1 2004/05/20 23:13:02 christos Exp $  */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)inet_lnaof.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: inet_lnaof.c,v 1.1 2004/05/20 23:13:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#ifdef __weak_alias
+__weak_alias(inet_lnaof,_inet_lnaof)
+#endif
+
+/*
+ * Return the local network address portion of an
+ * internet address; handles class a/b/c network
+ * number formats.
+ */
+in_addr_t
+inet_lnaof(struct in_addr in)
+{
+       in_addr_t i = ntohl(in.s_addr);
+
+       if (IN_CLASSA(i))
+               return ((i)&IN_CLASSA_HOST);
+       else if (IN_CLASSB(i))
+               return ((i)&IN_CLASSB_HOST);
+       else
+               return ((i)&IN_CLASSC_HOST);
+}
diff --git a/lib/nbsd_libc/inet/inet_makeaddr.c b/lib/nbsd_libc/inet/inet_makeaddr.c
new file mode 100644 (file)
index 0000000..0dfdd43
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: inet_makeaddr.c,v 1.1 2004/05/20 23:13:02 christos Exp $       */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)inet_makeaddr.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: inet_makeaddr.c,v 1.1 2004/05/20 23:13:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#ifdef __weak_alias
+__weak_alias(inet_makeaddr,_inet_makeaddr)
+#endif
+
+/*
+ * Formulate an Internet address from network + host.  Used in
+ * building addresses stored in the ifnet structure.
+ */
+struct in_addr
+inet_makeaddr(in_addr_t net, in_addr_t host)
+{
+       in_addr_t addr;
+       struct in_addr ret;
+
+       if (net < 128)
+               addr = (net << IN_CLASSA_NSHIFT) | (host & IN_CLASSA_HOST);
+       else if (net < 65536)
+               addr = (net << IN_CLASSB_NSHIFT) | (host & IN_CLASSB_HOST);
+       else if (net < 16777216L)
+               addr = (net << IN_CLASSC_NSHIFT) | (host & IN_CLASSC_HOST);
+       else
+               addr = net | host;
+       ret.s_addr = htonl(addr);
+       return ret;
+}
diff --git a/lib/nbsd_libc/inet/inet_net.3 b/lib/nbsd_libc/inet/inet_net.3
new file mode 100644 (file)
index 0000000..324955b
--- /dev/null
@@ -0,0 +1,154 @@
+.\"    $NetBSD: inet_net.3,v 1.2 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 1997 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Luke Mewburn.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd December 8, 2001
+.Dt INET_NET 3
+.Os
+.Sh NAME
+.Nm inet_net_ntop ,
+.Nm inet_net_pton
+.Nd Internet network number manipulation routines
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.In netinet/in.h
+.In arpa/inet.h
+.Ft char *
+.Fn inet_net_ntop "int af" "const void *src" "int bits" "char *dst" "size_t size"
+.Ft int
+.Fn inet_net_pton "int af" "const char *src" "void *dst" "size_t size"
+.Sh DESCRIPTION
+The
+.Fn inet_net_ntop
+function converts an Internet network number from network format (usually a
+.Ft struct in_addr
+or some other binary form, in network byte order) to CIDR presentation format
+(suitable for external display purposes).
+.Fa bits
+is the number of bits in
+.Fa src
+that are the network number.
+It returns NULL if a system error occurs (in which case,
+.Va errno
+will have been set), or it returns a pointer to the destination string.
+.Pp
+The
+.Fn inet_net_pton
+function converts a presentation format Internet network number (that is,
+printable form as held in a character string) to network format (usually a
+.Ft struct in_addr
+or some other internal binary representation, in network byte order).
+It returns the number of bits (either computed based on the class, or
+specified with /CIDR), or -1 if a failure occurred
+(in which case
+.Va errno
+will have been set.
+It will be set to
+.Er ENOENT
+if the Internet network number was not valid).
+.Pp
+The currently supported values for
+.Fa af
+are
+.Dv AF_INET
+and
+.Dv AF_INET6 .
+.Fa size
+is the size of the result buffer
+.Fa dst .
+.Sh NETWORK NUMBERS (IP VERSION 4)
+Internet network numbers may be specified in one of the following forms:
+.Bd -literal -offset indent
+a.b.c.d/bits
+a.b.c.d
+a.b.c
+a.b
+a
+.Ed
+.Pp
+When four parts are specified, each is interpreted
+as a byte of data and assigned, from left to right,
+to the four bytes of an Internet network number.  Note
+that when an Internet network number is viewed as a 32-bit
+integer quantity on a system that uses little-endian
+byte order (such as the
+.Tn Intel 386, 486
+and
+.Tn Pentium
+processors) the bytes referred to above appear as
+.Dq Li d.c.b.a .
+That is, little-endian bytes are ordered from right to left.
+.Pp
+When a three part number is specified, the last
+part is interpreted as a 16-bit quantity and placed
+in the right-most two bytes of the Internet network number.
+This makes the three part number format convenient
+for specifying Class B network numbers as
+.Dq Li 128.net.host .
+.Pp
+When a two part number is supplied, the last part
+is interpreted as a 24-bit quantity and placed in
+the right most three bytes of the Internet network number.
+This makes the two part number format convenient
+for specifying Class A network numbers as
+.Dq Li net.host .
+.Pp
+When only one part is given, the value is stored
+directly in the Internet network number without any byte
+rearrangement.
+.Pp
+All numbers supplied as
+.Dq parts
+in a
+.Ql  \&.
+notation
+may be decimal, octal, or hexadecimal, as specified
+in the C language (i.e., a leading 0x or 0X implies
+hexadecimal; otherwise, a leading 0 implies octal;
+otherwise, the number is interpreted as decimal).
+.\"
+.\" .Sh NETWORK NUMBERS (IP VERSION 6)
+.\" XXX - document this!
+.\"
+.Sh SEE ALSO
+.Xr byteorder 3 ,
+.Xr inet 3 ,
+.Xr networks 5
+.Sh HISTORY
+The
+.Nm inet_net_ntop
+and
+.Nm inet_net_pton
+functions appeared in BIND 4.9.4 and thence
+.Nx 1.3 .
+Support for
+.Dv AF_INET6
+appeared in
+.Nx 1.6 .
diff --git a/lib/nbsd_libc/inet/inet_net_ntop.c b/lib/nbsd_libc/inet/inet_net_ntop.c
new file mode 100644 (file)
index 0000000..b5ef9cc
--- /dev/null
@@ -0,0 +1,287 @@
+/*
+ * Copyright (c) 1996,1999 by Internet Software Consortium.
+ *
+ * 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 INTERNET SOFTWARE CONSORTIUM DISCLAIMS
+ * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
+ * CONSORTIUM 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#ifdef notdef
+static const char rcsid[] = "Id: inet_net_ntop.c,v 1.1.2.1 2002/08/02 02:17:21 marka Exp ";
+#else
+__RCSID("$NetBSD: inet_net_ntop.c,v 1.2 2009/02/07 07:25:22 lukem Exp $");
+#endif
+#endif
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "port_after.h"
+
+#ifdef __weak_alias
+__weak_alias(inet_net_ntop,_inet_net_ntop)
+#endif
+
+#ifdef SPRINTF_CHAR
+# define SPRINTF(x) strlen(sprintf/**/x)
+#else
+# define SPRINTF(x) sprintf x
+#endif
+
+static char *  inet_net_ntop_ipv4 __P((const u_char *src, int bits,
+                                       char *dst, size_t size));
+static char *  inet_net_ntop_ipv6 __P((const u_char *src, int bits,
+                                       char *dst, size_t size));
+
+/*
+ * char *
+ * inet_net_ntop(af, src, bits, dst, size)
+ *     convert network number from network to presentation format.
+ *     generates CIDR style result always.
+ * return:
+ *     pointer to dst, or NULL if an error occurred (check errno).
+ * author:
+ *     Paul Vixie (ISC), July 1996
+ */
+char *
+inet_net_ntop(af, src, bits, dst, size)
+       int af;
+       const void *src;
+       int bits;
+       char *dst;
+       size_t size;
+{
+       switch (af) {
+       case AF_INET:
+               return (inet_net_ntop_ipv4(src, bits, dst, size));
+       case AF_INET6:
+               return (inet_net_ntop_ipv6(src, bits, dst, size));
+       default:
+               errno = EAFNOSUPPORT;
+               return (NULL);
+       }
+}
+
+/*
+ * static char *
+ * inet_net_ntop_ipv4(src, bits, dst, size)
+ *     convert IPv4 network number from network to presentation format.
+ *     generates CIDR style result always.
+ * return:
+ *     pointer to dst, or NULL if an error occurred (check errno).
+ * note:
+ *     network byte order assumed.  this means 192.5.5.240/28 has
+ *     0b11110000 in its fourth octet.
+ * author:
+ *     Paul Vixie (ISC), July 1996
+ */
+static char *
+inet_net_ntop_ipv4(src, bits, dst, size)
+       const u_char *src;
+       int bits;
+       char *dst;
+       size_t size;
+{
+       char *odst = dst;
+       char *t;
+       u_int m;
+       int b;
+
+       if (bits < 0 || bits > 32) {
+               errno = EINVAL;
+               return (NULL);
+       }
+
+       if (bits == 0) {
+               if (size < sizeof "0")
+                       goto emsgsize;
+               *dst++ = '0';
+               size--;
+               *dst = '\0';
+       }
+
+       /* Format whole octets. */
+       for (b = bits / 8; b > 0; b--) {
+               if (size <= sizeof "255.")
+                       goto emsgsize;
+               t = dst;
+               dst += SPRINTF((dst, "%u", *src++));
+               if (b > 1) {
+                       *dst++ = '.';
+                       *dst = '\0';
+               }
+               size -= (size_t)(dst - t);
+       }
+
+       /* Format partial octet. */
+       b = bits % 8;
+       if (b > 0) {
+               if (size <= sizeof ".255")
+                       goto emsgsize;
+               t = dst;
+               if (dst != odst)
+                       *dst++ = '.';
+               m = ((1 << b) - 1) << (8 - b);
+               dst += SPRINTF((dst, "%u", *src & m));
+               size -= (size_t)(dst - t);
+       }
+
+       /* Format CIDR /width. */
+       if (size <= sizeof "/32")
+               goto emsgsize;
+       dst += SPRINTF((dst, "/%u", bits));
+       return (odst);
+
+ emsgsize:
+       errno = EMSGSIZE;
+       return (NULL);
+}
+
+/*
+ * static char *
+ * inet_net_ntop_ipv6(src, bits, fakebits, dst, size)
+ *     convert IPv6 network number from network to presentation format.
+ *     generates CIDR style result always. Picks the shortest representation
+ *     unless the IP is really IPv4.
+ *     always prints specified number of bits (bits).
+ * return:
+ *     pointer to dst, or NULL if an error occurred (check errno).
+ * note:
+ *     network byte order assumed.  this means 192.5.5.240/28 has
+ *     0x11110000 in its fourth octet.
+ * author:
+ *     Vadim Kogan (UCB), June 2001
+ *  Original version (IPv4) by Paul Vixie (ISC), July 1996
+ */
+
+static char *
+inet_net_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) {
+       u_int   m;
+       int     b;
+       size_t  p;
+       size_t  zero_s, zero_l, tmp_zero_s, tmp_zero_l;
+       size_t  i;
+       int     is_ipv4 = 0;
+       unsigned char inbuf[16];
+       char outbuf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")];
+       char    *cp;
+       size_t  words;
+       u_char  *s;
+
+       if (bits < 0 || bits > 128) {
+               errno = EINVAL;
+               return (NULL);
+       }
+
+       cp = outbuf;
+
+       if (bits == 0) {
+               *cp++ = ':';
+               *cp++ = ':';
+               *cp = '\0';
+       } else {
+               /* Copy src to private buffer.  Zero host part. */      
+               p = (bits + 7) / 8;
+               memcpy(inbuf, src, p);
+               memset(inbuf + p, 0, 16 - p);
+               b = bits % 8;
+               if (b != 0) {
+                       m = ~0 << (8 - b);
+                       inbuf[p-1] &= m;
+               }
+
+               s = inbuf;
+
+               /* how many words need to be displayed in output */
+               words = (bits + 15) / 16;
+               if (words == 1)
+                       words = 2;
+               
+               /* Find the longest substring of zero's */
+               zero_s = zero_l = tmp_zero_s = tmp_zero_l = 0;
+               for (i = 0; i < (words * 2); i += 2) {
+                       if ((s[i] | s[i+1]) == 0) {
+                               if (tmp_zero_l == 0)
+                                       tmp_zero_s = i / 2;
+                               tmp_zero_l++;
+                       } else {
+                               if (tmp_zero_l && zero_l < tmp_zero_l) {
+                                       zero_s = tmp_zero_s;
+                                       zero_l = tmp_zero_l;
+                                       tmp_zero_l = 0;
+                               }
+                       }
+               }
+
+               if (tmp_zero_l && zero_l < tmp_zero_l) {
+                       zero_s = tmp_zero_s;
+                       zero_l = tmp_zero_l;
+               }
+
+               if (zero_l != words && zero_s == 0 && ((zero_l == 6) ||
+                   ((zero_l == 5 && s[10] == 0xff && s[11] == 0xff) ||
+                   ((zero_l == 7 && s[14] != 0 && s[15] != 1)))))
+                       is_ipv4 = 1;
+
+               /* Format whole words. */
+               for (p = 0; p < words; p++) {
+                       if (zero_l != 0 && p >= zero_s && p < zero_s + zero_l) {
+                               /* Time to skip some zeros */
+                               if (p == zero_s)
+                                       *cp++ = ':';
+                               if (p == words - 1)
+                                       *cp++ = ':';
+                               s++;
+                               s++;
+                               continue;
+                       }
+
+                       if (is_ipv4 && p > 5 ) {
+                               *cp++ = (p == 6) ? ':' : '.';
+                               cp += SPRINTF((cp, "%u", *s++));
+                               /* we can potentially drop the last octet */
+                               if (p != 7 || bits > 120) {
+                                       *cp++ = '.';
+                                       cp += SPRINTF((cp, "%u", *s++));
+                               }
+                       } else {
+                               if (cp != outbuf)
+                                       *cp++ = ':';
+                               cp += SPRINTF((cp, "%x", *s * 256 + s[1]));
+                               s += 2;
+                       }
+               }
+       }
+       /* Format CIDR /width. */
+       (void)SPRINTF((cp, "/%u", bits));
+       if (strlen(outbuf) + 1 > size)
+               goto emsgsize;
+       strcpy(dst, outbuf);
+       
+       return (dst);
+
+emsgsize:
+       errno = EMSGSIZE;
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/inet/inet_net_pton.c b/lib/nbsd_libc/inet/inet_net_pton.c
new file mode 100644 (file)
index 0000000..fda0cc3
--- /dev/null
@@ -0,0 +1,412 @@
+/*
+ * Copyright (c) 1996,1999 by Internet Software Consortium.
+ *
+ * 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 INTERNET SOFTWARE CONSORTIUM DISCLAIMS
+ * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
+ * CONSORTIUM 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static const char rcsid[] = "Id: inet_net_pton.c,v 1.4.2.1 2002/08/02 02:17:21 marka Exp ";
+#else
+__RCSID("$NetBSD: inet_net_pton.c,v 1.1 2004/05/20 23:13:02 christos Exp $");
+#endif
+#endif
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+#include <arpa/inet.h>
+
+#include <isc/assertions.h>
+#include <ctype.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "port_after.h"
+
+#ifdef __weak_alias
+__weak_alias(inet_net_pton,_inet_net_pton)
+#endif
+
+#ifdef SPRINTF_CHAR
+# define SPRINTF(x) strlen(sprintf/**/x)
+#else
+# define SPRINTF(x) ((size_t)sprintf x)
+#endif
+
+
+/*
+ * static int
+ * inet_net_pton_ipv4(src, dst, size)
+ *     convert IPv4 network number from presentation to network format.
+ *     accepts hex octets, hex strings, decimal octets, and /CIDR.
+ *     "size" is in bytes and describes "dst".
+ * return:
+ *     number of bits, either imputed classfully or specified with /CIDR,
+ *     or -1 if some failure occurred (check errno).  ENOENT means it was
+ *     not an IPv4 network specification.
+ * note:
+ *     network byte order assumed.  this means 192.5.5.240/28 has
+ *     0b11110000 in its fourth octet.
+ * author:
+ *     Paul Vixie (ISC), June 1996
+ */
+static int
+inet_net_pton_ipv4( const char *src, u_char *dst, size_t size) {
+       static const char xdigits[] = "0123456789abcdef";
+       static const char digits[] = "0123456789";
+       int n, ch, tmp = 0, dirty, bits;
+       const u_char *odst = dst;
+
+       ch = *src++;
+       if (ch == '0' && (src[0] == 'x' || src[0] == 'X')
+           && isascii((u_char)(src[1]))
+           && isxdigit((u_char)(src[1]))) {
+               /* Hexadecimal: Eat nybble string. */
+               if (size == 0)
+                       goto emsgsize;
+               dirty = 0;
+               src++;  /* skip x or X. */
+               while ((ch = *src++) != '\0' && isascii((u_char)ch)
+                   && isxdigit((u_char)ch)) {
+                       if (isupper((u_char)ch))
+                               ch = tolower((u_char)ch);
+                       n = strchr(xdigits, ch) - xdigits;
+                       INSIST(n >= 0 && n <= 15);
+                       if (dirty == 0)
+                               tmp = n;
+                       else
+                               tmp = (tmp << 4) | n;
+                       if (++dirty == 2) {
+                               if (size-- == 0)
+                                       goto emsgsize;
+                               *dst++ = (u_char) tmp;
+                               dirty = 0;
+                       }
+               }
+               if (dirty) {  /* Odd trailing nybble? */
+                       if (size-- == 0)
+                               goto emsgsize;
+                       *dst++ = (u_char) (tmp << 4);
+               }
+       } else if (isascii((u_char)ch) && isdigit((u_char)ch)) {
+               /* Decimal: eat dotted digit string. */
+               for (;;) {
+                       tmp = 0;
+                       do {
+                               n = strchr(digits, ch) - digits;
+                               INSIST(n >= 0 && n <= 9);
+                               tmp *= 10;
+                               tmp += n;
+                               if (tmp > 255)
+                                       goto enoent;
+                       } while ((ch = *src++) != '\0' &&
+                                isascii((u_char)ch) && isdigit((u_char)ch));
+                       if (size-- == 0)
+                               goto emsgsize;
+                       *dst++ = (u_char) tmp;
+                       if (ch == '\0' || ch == '/')
+                               break;
+                       if (ch != '.')
+                               goto enoent;
+                       ch = *src++;
+                       if (!isascii((u_char)ch) || !isdigit((u_char)ch))
+                               goto enoent;
+               }
+       } else
+               goto enoent;
+
+       bits = -1;
+       if (ch == '/' && isascii((u_char)(src[0])) &&
+           isdigit((u_char)(src[0])) && dst > odst) {
+               /* CIDR width specifier.  Nothing can follow it. */
+               ch = *src++;    /* Skip over the /. */
+               bits = 0;
+               do {
+                       n = strchr(digits, ch) - digits;
+                       INSIST(n >= 0 && n <= 9);
+                       bits *= 10;
+                       bits += n;
+               } while ((ch = *src++) != '\0' && isascii((u_char)ch)
+                   && isdigit((u_char)ch));
+               if (ch != '\0')
+                       goto enoent;
+               if (bits > 32)
+                       goto emsgsize;
+       }
+
+       /* Firey death and destruction unless we prefetched EOS. */
+       if (ch != '\0')
+               goto enoent;
+
+       /* If nothing was written to the destination, we found no address. */
+       if (dst == odst)
+               goto enoent;
+       /* If no CIDR spec was given, infer width from net class. */
+       if (bits == -1) {
+               if (*odst >= 240)       /* Class E */
+                       bits = 32;
+               else if (*odst >= 224)  /* Class D */
+                       bits = 4;
+               else if (*odst >= 192)  /* Class C */
+                       bits = 24;
+               else if (*odst >= 128)  /* Class B */
+                       bits = 16;
+               else                    /* Class A */
+                       bits = 8;
+               /* If imputed mask is narrower than specified octets, widen. */
+               if (bits >= 8 && bits < ((dst - odst) * 8))
+                       bits = (dst - odst) * 8;
+       }
+       /* Extend network to cover the actual mask. */
+       while (bits > ((dst - odst) * 8)) {
+               if (size-- == 0)
+                       goto emsgsize;
+               *dst++ = '\0';
+       }
+       return (bits);
+
+ enoent:
+       errno = ENOENT;
+       return (-1);
+
+ emsgsize:
+       errno = EMSGSIZE;
+       return (-1);
+}
+
+static int
+getbits(const char *src, int *bitsp) {
+       static const char digits[] = "0123456789";
+       int n;
+       int val;
+       char ch;
+
+       val = 0;
+       n = 0;
+       while ((ch = *src++) != '\0') {
+               const char *pch;
+
+               pch = strchr(digits, ch);
+               if (pch != NULL) {
+                       if (n++ != 0 && val == 0)       /* no leading zeros */
+                               return (0);
+                       val *= 10;
+                       val += (pch - digits);
+                       if (val > 128)                  /* range */
+                               return (0);
+                       continue;
+               }
+               return (0);
+       }
+       if (n == 0)
+               return (0);
+       *bitsp = val;
+       return (1);
+}
+
+static int
+getv4(const char *src, u_char *dst, int *bitsp) {
+       static const char digits[] = "0123456789";
+       u_char *odst = dst;
+       int n;
+       u_int val;
+       char ch;
+
+       val = 0;
+       n = 0;
+       while ((ch = *src++) != '\0') {
+               const char *pch;
+
+               pch = strchr(digits, ch);
+               if (pch != NULL) {
+                       if (n++ != 0 && val == 0)       /* no leading zeros */
+                               return (0);
+                       val *= 10;
+                       val += (pch - digits);
+                       if (val > 255)                  /* range */
+                               return (0);
+                       continue;
+               }
+               if (ch == '.' || ch == '/') {
+                       if (dst - odst > 3)             /* too many octets? */
+                               return (0);
+                       *dst++ = val;
+                       if (ch == '/')
+                               return (getbits(src, bitsp));
+                       val = 0;
+                       n = 0;
+                       continue;
+               }
+               return (0);
+       }
+       if (n == 0)
+               return (0);
+       if (dst - odst > 3)             /* too many octets? */
+               return (0);
+       *dst++ = val;
+       return (1);
+}
+
+static int
+inet_net_pton_ipv6(const char *src, u_char *dst, size_t size) {
+       static const char xdigits_l[] = "0123456789abcdef",
+                         xdigits_u[] = "0123456789ABCDEF";
+       u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp;
+       const char *xdigits, *curtok;
+       int ch, saw_xdigit;
+       u_int val;
+       int digits;
+       int bits;
+       size_t bytes;
+       int words;
+       int ipv4;
+
+       memset((tp = tmp), '\0', NS_IN6ADDRSZ);
+       endp = tp + NS_IN6ADDRSZ;
+       colonp = NULL;
+       /* Leading :: requires some special handling. */
+       if (*src == ':')
+               if (*++src != ':')
+                       goto enoent;
+       curtok = src;
+       saw_xdigit = 0;
+       val = 0;
+       digits = 0;
+       bits = -1;
+       ipv4 = 0;
+       while ((ch = *src++) != '\0') {
+               const char *pch;
+
+               if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL)
+                       pch = strchr((xdigits = xdigits_u), ch);
+               if (pch != NULL) {
+                       val <<= 4;
+                       val |= (pch - xdigits);
+                       if (++digits > 4)
+                               goto enoent;
+                       saw_xdigit = 1;
+                       continue;
+               }
+               if (ch == ':') {
+                       curtok = src;
+                       if (!saw_xdigit) {
+                               if (colonp)
+                                       goto enoent;
+                               colonp = tp;
+                               continue;
+                       } else if (*src == '\0')
+                               goto enoent;
+                       if (tp + NS_INT16SZ > endp)
+                               return (0);
+                       *tp++ = (u_char) (val >> 8) & 0xff;
+                       *tp++ = (u_char) val & 0xff;
+                       saw_xdigit = 0;
+                       digits = 0;
+                       val = 0;
+                       continue;
+               }
+               if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) &&
+                    getv4(curtok, tp, &bits) > 0) {
+                       tp += NS_INADDRSZ;
+                       saw_xdigit = 0;
+                       ipv4 = 1;
+                       break;  /* '\0' was seen by inet_pton4(). */
+               }
+               if (ch == '/' && getbits(src, &bits) > 0)
+                       break;
+               goto enoent;
+       }
+       if (saw_xdigit) {
+               if (tp + NS_INT16SZ > endp)
+                       goto enoent;
+               *tp++ = (u_char) (val >> 8) & 0xff;
+               *tp++ = (u_char) val & 0xff;
+       }
+       if (bits == -1)
+               bits = 128;
+
+       words = (bits + 15) / 16;
+       if (words < 2)
+               words = 2;
+       if (ipv4)
+               words = 8;
+       endp =  tmp + 2 * words;
+
+       if (colonp != NULL) {
+               /*
+                * Since some memmove()'s erroneously fail to handle
+                * overlapping regions, we'll do the shift by hand.
+                */
+               const int n = tp - colonp;
+               int i;
+
+               if (tp == endp)
+                       goto enoent;
+               for (i = 1; i <= n; i++) {
+                       endp[- i] = colonp[n - i];
+                       colonp[n - i] = 0;
+               }
+               tp = endp;
+       }
+       if (tp != endp)
+               goto enoent;
+
+       bytes = (bits + 7) / 8;
+       if (bytes > size)
+               goto emsgsize;
+       memcpy(dst, tmp, bytes);
+       return (bits);
+
+ enoent:
+       errno = ENOENT;
+       return (-1);
+
+ emsgsize:
+       errno = EMSGSIZE;
+       return (-1);
+}
+
+/*
+ * int
+ * inet_net_pton(af, src, dst, size)
+ *     convert network number from presentation to network format.
+ *     accepts hex octets, hex strings, decimal octets, and /CIDR.
+ *     "size" is in bytes and describes "dst".
+ * return:
+ *     number of bits, either imputed classfully or specified with /CIDR,
+ *     or -1 if some failure occurred (check errno).  ENOENT means it was
+ *     not a valid network specification.
+ * author:
+ *     Paul Vixie (ISC), June 1996
+ */
+int
+inet_net_pton(int af, const char *src, void *dst, size_t size) {
+       switch (af) {
+       case AF_INET:
+               return (inet_net_pton_ipv4(src, dst, size));
+       case AF_INET6:
+               return (inet_net_pton_ipv6(src, dst, size));
+       default:
+               errno = EAFNOSUPPORT;
+               return (-1);
+       }
+}
diff --git a/lib/nbsd_libc/inet/inet_neta.c b/lib/nbsd_libc/inet/inet_neta.c
new file mode 100644 (file)
index 0000000..d0b90bc
--- /dev/null
@@ -0,0 +1,98 @@
+/*     $NetBSD: inet_neta.c,v 1.1 2004/05/20 23:13:02 christos Exp $   */
+
+/*
+ * Copyright (c) 1996 by Internet Software Consortium.
+ *
+ * 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 INTERNET SOFTWARE CONSORTIUM DISCLAIMS
+ * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
+ * CONSORTIUM 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static const char rcsid[] = "Id: inet_neta.c,v 8.2 1996/08/08 06:54:44 vixie Exp ";
+#else
+__RCSID("$NetBSD: inet_neta.c,v 1.1 2004/05/20 23:13:02 christos Exp $");
+#endif
+#endif
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(inet_neta,_inet_neta)
+#endif
+
+/*
+ * char *
+ * inet_neta(src, dst, size)
+ *     format a u_long network number into presentation format.
+ * return:
+ *     pointer to dst, or NULL if an error occurred (check errno).
+ * note:
+ *     format of ``src'' is as for inet_network().
+ * author:
+ *     Paul Vixie (ISC), July 1996
+ */
+char *
+inet_neta(src, dst, size)
+       u_long src;
+       char *dst;
+       size_t size;
+{
+       char *odst = dst;
+       char *ep;
+       int advance;
+
+       _DIAGASSERT(dst != NULL);
+
+       if (src == 0x00000000) {
+               if (size < sizeof "0.0.0.0")
+                       goto emsgsize;
+               strlcpy(dst, "0.0.0.0", size);
+               return dst;
+       }
+       ep = dst + size;
+       if (ep <= dst)
+               goto emsgsize;
+       while (src & 0xffffffff) {
+               u_char b = (u_char)((src & 0xff000000) >> 24);
+
+               src <<= 8;
+               if (b || src) {
+                       advance = snprintf(dst, (size_t)(ep - dst), "%u", b);
+                       if (advance <= 0 || advance >= ep - dst)
+                               goto emsgsize;
+                       dst += advance;
+                       if (src != 0L) {
+                               if (dst + 1 >= ep)
+                                       goto emsgsize;
+                               *dst++ = '.';
+                               *dst = '\0';
+                       }
+               }
+       }
+       return (odst);
+
+ emsgsize:
+       errno = EMSGSIZE;
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/inet/inet_netof.c b/lib/nbsd_libc/inet/inet_netof.c
new file mode 100644 (file)
index 0000000..4758f3e
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: inet_netof.c,v 1.1 2004/05/20 23:13:02 christos Exp $  */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)inet_netof.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: inet_netof.c,v 1.1 2004/05/20 23:13:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#ifdef __weak_alias
+__weak_alias(inet_netof,_inet_netof)
+#endif
+
+/*
+ * Return the network number from an internet
+ * address; handles class a/b/c network #'s.
+ */
+in_addr_t
+inet_netof(struct in_addr in)
+{
+       in_addr_t i = ntohl(in.s_addr);
+
+       if (IN_CLASSA(i))
+               return (((i)&IN_CLASSA_NET) >> IN_CLASSA_NSHIFT);
+       else if (IN_CLASSB(i))
+               return (((i)&IN_CLASSB_NET) >> IN_CLASSB_NSHIFT);
+       else
+               return (((i)&IN_CLASSC_NET) >> IN_CLASSC_NSHIFT);
+}
diff --git a/lib/nbsd_libc/inet/inet_network.c b/lib/nbsd_libc/inet/inet_network.c
new file mode 100644 (file)
index 0000000..135675d
--- /dev/null
@@ -0,0 +1,114 @@
+/*     $NetBSD: inet_network.c,v 1.4 2008/01/20 04:56:08 christos Exp $        */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)inet_network.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: inet_network.c,v 1.4 2008/01/20 04:56:08 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include <assert.h>
+#include <ctype.h>
+#ifdef _DIAGNOSTIC
+#include <stddef.h>    /* for NULL */
+#endif
+
+#ifdef __weak_alias
+__weak_alias(inet_network,_inet_network)
+#endif
+
+/*
+ * Internet network address interpretation routine.
+ * The library routines call this routine to interpret
+ * network numbers.
+ */
+in_addr_t
+inet_network(const char *cp)
+{
+       in_addr_t val;
+       size_t i, n;
+       u_char c;
+       in_addr_t parts[4], *pp = parts;
+       int digit, base;
+
+       _DIAGASSERT(cp != NULL);
+
+again:
+       val = 0; base = 10; digit = 0;
+       if (*cp == '0')
+               digit = 1, base = 8, cp++;
+       if (*cp == 'x' || *cp == 'X')
+               digit = 0, base = 16, cp++;
+       while ((c = *cp) != 0) {
+               if (isdigit(c)) {
+                       if (base == 8 && (c == '8' || c == '9'))
+                               return (INADDR_NONE);
+                       val = (val * base) + (c - '0');
+                       cp++;
+                       digit = 1;
+                       continue;
+               }
+               if (base == 16 && isxdigit(c)) {
+                       val = (val << 4) + (c + 10 - (islower(c) ? 'a' : 'A'));
+                       cp++;
+                       digit = 1;
+                       continue;
+               }
+               break;
+       }
+       if (!digit)
+               return (INADDR_NONE);
+       if (pp >= parts + 4 || val > 0xff)
+               return (INADDR_NONE);
+       if (*cp == '.') {
+               *pp++ = val, cp++;
+               goto again;
+       }
+       if (*cp && !isspace((u_char) *cp))
+               return (INADDR_NONE);
+       *pp++ = val;
+       n = pp - parts;
+       if (n > 4)
+               return (INADDR_NONE);
+       for (val = 0, i = 0; i < n; i++) {
+               val <<= 8;
+               val |= parts[i] & 0xff;
+       }
+       return (val);
+}
diff --git a/lib/nbsd_libc/inet/inet_ntoa.c b/lib/nbsd_libc/inet/inet_ntoa.c
new file mode 100644 (file)
index 0000000..df7670d
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: inet_ntoa.c,v 1.1 2004/05/20 23:13:02 christos Exp $   */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)inet_ntoa.c        8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: inet_ntoa.c,v 1.1 2004/05/20 23:13:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <stdio.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(inet_ntoa,_inet_ntoa)
+#endif
+
+/*
+ * Convert network-format internet address
+ * to base 256 d.d.d.d representation.
+ */
+/*const*/ char *
+inet_ntoa(struct in_addr in) {
+       static char ret[18];
+
+       strlcpy(ret, "[inet_ntoa error]", sizeof(ret));
+       (void) inet_ntop(AF_INET, &in, ret, sizeof ret);
+       return (ret);
+}
diff --git a/lib/nbsd_libc/inet/inet_ntop.c b/lib/nbsd_libc/inet/inet_ntop.c
new file mode 100644 (file)
index 0000000..ed3a95a
--- /dev/null
@@ -0,0 +1,242 @@
+/*     $NetBSD: inet_ntop.c,v 1.8 2009/04/12 17:07:17 christos Exp $   */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static const char rcsid[] = "Id: inet_ntop.c,v 1.5 2005/11/03 22:59:52 marka Exp";
+#else
+__RCSID("$NetBSD: inet_ntop.c,v 1.8 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "port_after.h"
+
+#ifdef __weak_alias
+__weak_alias(inet_ntop,_inet_ntop)
+#endif
+
+/*%
+ * WARNING: Don't even consider trying to compile this on a system where
+ * sizeof(int) < 4.  sizeof(int) > 4 is fine; all the world's not a VAX.
+ */
+
+static const char *inet_ntop4(const u_char *src, char *dst, socklen_t size);
+static const char *inet_ntop6(const u_char *src, char *dst, socklen_t size);
+
+/* char *
+ * inet_ntop(af, src, dst, size)
+ *     convert a network format address to presentation format.
+ * return:
+ *     pointer to presentation format address (`dst'), or NULL (see errno).
+ * author:
+ *     Paul Vixie, 1996.
+ */
+const char *
+inet_ntop(af, src, dst, size)
+       int af;
+       const void *src;
+       char *dst;
+       socklen_t size;
+{
+
+       _DIAGASSERT(src != NULL);
+       _DIAGASSERT(dst != NULL);
+
+       switch (af) {
+       case AF_INET:
+               return (inet_ntop4(src, dst, size));
+       case AF_INET6:
+               return (inet_ntop6(src, dst, size));
+       default:
+               errno = EAFNOSUPPORT;
+               return (NULL);
+       }
+       /* NOTREACHED */
+}
+
+/* const char *
+ * inet_ntop4(src, dst, size)
+ *     format an IPv4 address, more or less like inet_ntoa()
+ * return:
+ *     `dst' (as a const)
+ * notes:
+ *     (1) uses no statics
+ *     (2) takes a u_char* not an in_addr as input
+ * author:
+ *     Paul Vixie, 1996.
+ */
+static const char *
+inet_ntop4(src, dst, size)
+       const u_char *src;
+       char *dst;
+       socklen_t size;
+{
+       char tmp[sizeof "255.255.255.255"];
+       int l;
+
+       _DIAGASSERT(src != NULL);
+       _DIAGASSERT(dst != NULL);
+
+       l = snprintf(tmp, sizeof(tmp), "%u.%u.%u.%u",
+           src[0], src[1], src[2], src[3]);
+       if (l <= 0 || (socklen_t) l >= size) {
+               errno = ENOSPC;
+               return (NULL);
+       }
+       strlcpy(dst, tmp, size);
+       return (dst);
+}
+
+/* const char *
+ * inet_ntop6(src, dst, size)
+ *     convert IPv6 binary address into presentation (printable) format
+ * author:
+ *     Paul Vixie, 1996.
+ */
+static const char *
+inet_ntop6(src, dst, size)
+       const u_char *src;
+       char *dst;
+       socklen_t size;
+{
+       /*
+        * Note that int32_t and int16_t need only be "at least" large enough
+        * to contain a value of the specified size.  On some systems, like
+        * Crays, there is no such thing as an integer variable with 16 bits.
+        * Keep this in mind if you think this function should have been coded
+        * to use pointer overlays.  All the world's not a VAX.
+        */
+       char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"];
+       char *tp, *ep;
+       struct { int base, len; } best, cur;
+       u_int words[NS_IN6ADDRSZ / NS_INT16SZ];
+       int i;
+       int advance;
+
+       _DIAGASSERT(src != NULL);
+       _DIAGASSERT(dst != NULL);
+
+       /*
+        * Preprocess:
+        *      Copy the input (bytewise) array into a wordwise array.
+        *      Find the longest run of 0x00's in src[] for :: shorthanding.
+        */
+       memset(words, '\0', sizeof words);
+       for (i = 0; i < NS_IN6ADDRSZ; i++)
+               words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
+       best.base = -1;
+       best.len = 0;
+       cur.base = -1;
+       cur.len = 0;
+       for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
+               if (words[i] == 0) {
+                       if (cur.base == -1)
+                               cur.base = i, cur.len = 1;
+                       else
+                               cur.len++;
+               } else {
+                       if (cur.base != -1) {
+                               if (best.base == -1 || cur.len > best.len)
+                                       best = cur;
+                               cur.base = -1;
+                       }
+               }
+       }
+       if (cur.base != -1) {
+               if (best.base == -1 || cur.len > best.len)
+                       best = cur;
+       }
+       if (best.base != -1 && best.len < 2)
+               best.base = -1;
+
+       /*
+        * Format the result.
+        */
+       tp = tmp;
+       ep = tmp + sizeof(tmp);
+       for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
+               /* Are we inside the best run of 0x00's? */
+               if (best.base != -1 && i >= best.base &&
+                   i < (best.base + best.len)) {
+                       if (i == best.base)
+                               *tp++ = ':';
+                       continue;
+               }
+               /* Are we following an initial run of 0x00s or any real hex? */
+               if (i != 0) {
+                       if (tp + 1 >= ep)
+                               return (NULL);
+                       *tp++ = ':';
+               }
+               /* Is this address an encapsulated IPv4? */
+               if (i == 6 && best.base == 0 &&
+                   (best.len == 6 ||
+                   (best.len == 7 && words[7] != 0x0001) ||
+                   (best.len == 5 && words[5] == 0xffff))) {
+                       if (!inet_ntop4(src+12, tp, (socklen_t)(ep - tp)))
+                               return (NULL);
+                       tp += strlen(tp);
+                       break;
+               }
+               advance = snprintf(tp, (size_t)(ep - tp), "%x", words[i]);
+               if (advance <= 0 || advance >= ep - tp)
+                       return (NULL);
+               tp += advance;
+       }
+       /* Was it a trailing run of 0x00's? */
+       if (best.base != -1 && (best.base + best.len) == 
+           (NS_IN6ADDRSZ / NS_INT16SZ)) {
+               if (tp + 1 >= ep)
+                       return (NULL);
+               *tp++ = ':';
+       }
+       if (tp + 1 >= ep)
+               return (NULL);
+       *tp++ = '\0';
+
+       /*
+        * Check for overflow, copy, and we're done.
+        */
+       if ((size_t)(tp - tmp) > size) {
+               errno = ENOSPC;
+               return (NULL);
+       }
+       strlcpy(dst, tmp, size);
+       return (dst);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/inet/inet_pton.c b/lib/nbsd_libc/inet/inet_pton.c
new file mode 100644 (file)
index 0000000..17ae259
--- /dev/null
@@ -0,0 +1,309 @@
+/*     $NetBSD: inet_pton.c,v 1.7 2009/04/12 17:07:17 christos Exp $   */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996,1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static const char rcsid[] = "Id: inet_pton.c,v 1.5 2005/07/28 06:51:47 marka Exp";
+#else
+__RCSID("$NetBSD: inet_pton.c,v 1.7 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+#include <string.h>
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+
+#include "port_after.h"
+
+#ifdef __weak_alias
+__weak_alias(inet_pton,_inet_pton)
+#endif
+
+/*%
+ * WARNING: Don't even consider trying to compile this on a system where
+ * sizeof(int) < 4.  sizeof(int) > 4 is fine; all the world's not a VAX.
+ */
+
+static int     inet_pton4(const char *src, u_char *dst, int pton);
+static int     inet_pton6(const char *src, u_char *dst);
+
+/* int
+ * inet_pton(af, src, dst)
+ *     convert from presentation format (which usually means ASCII printable)
+ *     to network format (which is usually some kind of binary format).
+ * return:
+ *     1 if the address was valid for the specified address family
+ *     0 if the address wasn't valid (`dst' is untouched in this case)
+ *     -1 if some other error occurred (`dst' is untouched in this case, too)
+ * author:
+ *     Paul Vixie, 1996.
+ */
+int
+inet_pton(int af, const char *src, void *dst)
+{
+
+       _DIAGASSERT(src != NULL);
+       _DIAGASSERT(dst != NULL);
+
+       switch (af) {
+       case AF_INET:
+               return (inet_pton4(src, dst, 1));
+       case AF_INET6:
+               return (inet_pton6(src, dst));
+       default:
+               errno = EAFNOSUPPORT;
+               return (-1);
+       }
+       /* NOTREACHED */
+}
+
+/* int
+ * inet_pton4(src, dst, pton)
+ *     when last arg is 0: inet_aton(). with hexadecimal, octal and shorthand.
+ *     when last arg is 1: inet_pton(). decimal dotted-quad only.
+ * return:
+ *     1 if `src' is a valid input, else 0.
+ * notice:
+ *     does not touch `dst' unless it's returning 1.
+ * author:
+ *     Paul Vixie, 1996.
+ */
+static int
+inet_pton4(const char *src, u_char *dst, int pton)
+{
+       u_int32_t val;
+       u_int digit, base;
+       int n;
+       unsigned char c;
+       u_int parts[4];
+       register u_int *pp = parts;
+
+       _DIAGASSERT(src != NULL);
+       _DIAGASSERT(dst != NULL);
+
+       c = *src;
+       for (;;) {
+               /*
+                * Collect number up to ``.''.
+                * Values are specified as for C:
+                * 0x=hex, 0=octal, isdigit=decimal.
+                */
+               if (!isdigit(c))
+                       return (0);
+               val = 0; base = 10;
+               if (c == '0') {
+                       c = *++src;
+                       if (c == 'x' || c == 'X')
+                               base = 16, c = *++src;
+                       else if (isdigit(c) && c != '9')
+                               base = 8;
+               }
+               /* inet_pton() takes decimal only */
+               if (pton && base != 10)
+                       return (0);
+               for (;;) {
+                       if (isdigit(c)) {
+                               digit = c - '0';
+                               if (digit >= base)
+                                       break;
+                               val = (val * base) + digit;
+                               c = *++src;
+                       } else if (base == 16 && isxdigit(c)) {
+                               digit = c + 10 - (islower(c) ? 'a' : 'A');
+                               if (digit >= 16)
+                                       break;
+                               val = (val << 4) | digit;
+                               c = *++src;
+                       } else
+                               break;
+               }
+               if (c == '.') {
+                       /*
+                        * Internet format:
+                        *      a.b.c.d
+                        *      a.b.c   (with c treated as 16 bits)
+                        *      a.b     (with b treated as 24 bits)
+                        *      a       (with a treated as 32 bits)
+                        */
+                       if (pp >= parts + 3)
+                               return (0);
+                       *pp++ = val;
+                       c = *++src;
+               } else
+                       break;
+       }
+       /*
+        * Check for trailing characters.
+        */
+       if (c != '\0' && !isspace(c))
+               return (0);
+       /*
+        * Concoct the address according to
+        * the number of parts specified.
+        */
+       n = pp - parts + 1;
+       /* inet_pton() takes dotted-quad only.  it does not take shorthand. */
+       if (pton && n != 4)
+               return (0);
+       switch (n) {
+
+       case 0:
+               return (0);             /* initial nondigit */
+
+       case 1:                         /* a -- 32 bits */
+               break;
+
+       case 2:                         /* a.b -- 8.24 bits */
+               if (parts[0] > 0xff || val > 0xffffff)
+                       return (0);
+               val |= parts[0] << 24;
+               break;
+
+       case 3:                         /* a.b.c -- 8.8.16 bits */
+               if ((parts[0] | parts[1]) > 0xff || val > 0xffff)
+                       return (0);
+               val |= (parts[0] << 24) | (parts[1] << 16);
+               break;
+
+       case 4:                         /* a.b.c.d -- 8.8.8.8 bits */
+               if ((parts[0] | parts[1] | parts[2] | val) > 0xff)
+                       return (0);
+               val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
+               break;
+       }
+       if (dst) {
+               val = htonl(val);
+               memcpy(dst, &val, NS_INADDRSZ);
+       }
+       return (1);
+}
+
+/* int
+ * inet_pton6(src, dst)
+ *     convert presentation level address to network order binary form.
+ * return:
+ *     1 if `src' is a valid [RFC1884 2.2] address, else 0.
+ * notice:
+ *     (1) does not touch `dst' unless it's returning 1.
+ *     (2) :: in a full address is silently ignored.
+ * credit:
+ *     inspired by Mark Andrews.
+ * author:
+ *     Paul Vixie, 1996.
+ */
+static int
+inet_pton6(const char *src, u_char *dst)
+{
+       static const char xdigits_l[] = "0123456789abcdef",
+                         xdigits_u[] = "0123456789ABCDEF";
+       u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp;
+       const char *xdigits, *curtok;
+       int ch, seen_xdigits;
+       u_int val;
+
+       _DIAGASSERT(src != NULL);
+       _DIAGASSERT(dst != NULL);
+
+       memset((tp = tmp), '\0', NS_IN6ADDRSZ);
+       endp = tp + NS_IN6ADDRSZ;
+       colonp = NULL;
+       /* Leading :: requires some special handling. */
+       if (*src == ':')
+               if (*++src != ':')
+                       return (0);
+       curtok = src;
+       seen_xdigits = 0;
+       val = 0;
+       while ((ch = *src++) != '\0') {
+               const char *pch;
+
+               if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL)
+                       pch = strchr((xdigits = xdigits_u), ch);
+               if (pch != NULL) {
+                       val <<= 4;
+                       val |= (pch - xdigits);
+                       if (++seen_xdigits > 4)
+                               return (0);
+                       continue;
+               }
+               if (ch == ':') {
+                       curtok = src;
+                       if (!seen_xdigits) {
+                               if (colonp)
+                                       return (0);
+                               colonp = tp;
+                               continue;
+                       } else if (*src == '\0')
+                               return (0);
+                       if (tp + NS_INT16SZ > endp)
+                               return (0);
+                       *tp++ = (u_char) (val >> 8) & 0xff;
+                       *tp++ = (u_char) val & 0xff;
+                       seen_xdigits = 0;
+                       val = 0;
+                       continue;
+               }
+               if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) &&
+                   inet_pton4(curtok, tp, 1) > 0) {
+                       tp += NS_INADDRSZ;
+                       seen_xdigits = 0;
+                       break;  /*%< '\\0' was seen by inet_pton4(). */
+               }
+               return (0);
+       }
+       if (seen_xdigits) {
+               if (tp + NS_INT16SZ > endp)
+                       return (0);
+               *tp++ = (u_char) (val >> 8) & 0xff;
+               *tp++ = (u_char) val & 0xff;
+       }
+       if (colonp != NULL) {
+               /*
+                * Since some memmove()'s erroneously fail to handle
+                * overlapping regions, we'll do the shift by hand.
+                */
+               const int n = tp - colonp;
+               int i;
+
+               if (tp == endp)
+                       return (0);
+               for (i = 1; i <= n; i++) {
+                       endp[- i] = colonp[n - i];
+                       colonp[n - i] = 0;
+               }
+               tp = endp;
+       }
+       if (tp != endp)
+               return (0);
+       memcpy(dst, tmp, NS_IN6ADDRSZ);
+       return (1);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/inet/nsap_addr.c b/lib/nbsd_libc/inet/nsap_addr.c
new file mode 100644 (file)
index 0000000..8633205
--- /dev/null
@@ -0,0 +1,130 @@
+/*     $NetBSD: nsap_addr.c,v 1.6 2009/04/12 17:07:17 christos Exp $   */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static const char rcsid[] = "Id: nsap_addr.c,v 1.5 2005/07/28 06:51:48 marka Exp";
+#else
+__RCSID("$NetBSD: nsap_addr.c,v 1.6 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <resolv.h>
+#include <resolv_mt.h>
+
+#include "port_after.h"
+
+#ifdef __weak_alias
+__weak_alias(inet_nsap_addr,_inet_nsap_addr)
+__weak_alias(inet_nsap_ntoa,_inet_nsap_ntoa)
+#endif
+
+static char
+xtob(int c) {
+       return (c - (((c >= '0') && (c <= '9')) ? '0' : '7'));
+}
+
+u_int
+inet_nsap_addr(const char *ascii, u_char *binary, int maxlen) {
+       u_char c, nib;
+       u_int len = 0;
+
+       _DIAGASSERT(ascii != NULL);
+       _DIAGASSERT(binary != NULL);
+
+       if (ascii[0] != '0' || (ascii[1] != 'x' && ascii[1] != 'X'))
+               return (0);
+       ascii += 2;
+
+       while ((c = *ascii++) != '\0' && len < (u_int)maxlen) {
+               if (c == '.' || c == '+' || c == '/')
+                       continue;
+               if (!isascii(c))
+                       return (0);
+               if (islower(c))
+                       c = toupper(c);
+               if (isxdigit(c)) {
+                       nib = xtob(c);
+                       c = *ascii++;
+                       if (c != '\0') {
+                               c = toupper(c);
+                               if (isxdigit(c)) {
+                                       *binary++ = (nib << 4) | xtob(c);
+                                       len++;
+                               } else
+                                       return (0);
+                       }
+                       else
+                               return (0);
+               }
+               else
+                       return (0);
+       }
+       return (len);
+}
+
+char *
+inet_nsap_ntoa(int binlen, const u_char *binary, char *ascii) {
+       int nib;
+       int i;
+       char *tmpbuf = inet_nsap_ntoa_tmpbuf;
+       char *start;
+
+       _DIAGASSERT(binary != NULL);
+
+       if (ascii)
+               start = ascii;
+       else {
+               ascii = tmpbuf;
+               start = tmpbuf;
+       }
+
+       *ascii++ = '0';
+       *ascii++ = 'x';
+
+       if (binlen > 255)
+               binlen = 255;
+
+       for (i = 0; i < binlen; i++) {
+               nib = (u_int32_t)*binary >> 4;
+               *ascii++ = nib + (nib < 10 ? '0' : '7');
+               nib = *binary++ & 0x0f;
+               *ascii++ = nib + (nib < 10 ? '0' : '7');
+               if (((i % 2) == 0 && (i + 1) < binlen))
+                       *ascii++ = '.';
+       }
+       *ascii = '\0';
+       return (start);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/isc/Makefile.inc b/lib/nbsd_libc/isc/Makefile.inc
new file mode 100644 (file)
index 0000000..e7947d4
--- /dev/null
@@ -0,0 +1,6 @@
+#      $NetBSD: Makefile.inc,v 1.1 2004/05/20 19:52:14 christos Exp $
+
+# net sources
+.PATH: ${.CURDIR}/isc
+
+SRCS+= assertions.c ev_timers.c ev_streams.c
diff --git a/lib/nbsd_libc/isc/assertions.c b/lib/nbsd_libc/isc/assertions.c
new file mode 100644 (file)
index 0000000..970231d
--- /dev/null
@@ -0,0 +1,101 @@
+/*     $NetBSD: assertions.c,v 1.6 2009/04/12 17:07:17 christos Exp $  */
+
+/*
+ * Copyright (C) 2004, 2005, 2008  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 1997, 1999, 2001  Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and/or 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 ISC DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#if !defined(LINT) && !defined(CODECENTER) && !defined(lint)
+#ifdef notdef
+static const char rcsid[] = "Id: assertions.c,v 1.5 2008/11/14 02:36:51 marka Exp";
+#else
+__RCSID("$NetBSD: assertions.c,v 1.6 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif
+
+#include "port_before.h"
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <isc/assertions.h>
+
+#include "port_after.h"
+
+/*
+ * Forward.
+ */
+
+static void default_assertion_failed(const char *, int, assertion_type,
+                                    const char *, int);
+
+/*
+ * Public.
+ */
+
+assertion_failure_callback __assertion_failed = default_assertion_failed;
+
+void
+set_assertion_failure_callback(assertion_failure_callback f) {
+       if (f == NULL)
+               __assertion_failed = default_assertion_failed;
+       else
+               __assertion_failed = f;
+}
+
+const char *
+assertion_type_to_text(assertion_type type) {
+       const char *result;
+
+       switch (type) {
+       case assert_require:
+               result = "REQUIRE";
+               break;
+       case assert_ensure:
+               result = "ENSURE";
+               break;
+       case assert_insist:
+               result = "INSIST";
+               break;
+       case assert_invariant:
+               result = "INVARIANT";
+               break;
+       default:
+               result = NULL;
+       }
+       return (result);
+}
+
+/*
+ * Private.
+ */
+
+/* coverity[+kill] */
+static void
+default_assertion_failed(const char *file, int line, assertion_type type,
+                        const char *cond, int print_errno)
+{
+       fprintf(stderr, "%s:%d: %s(%s)%s%s failed.\n",
+               file, line, assertion_type_to_text(type), cond,
+               (print_errno) ? ": " : "",
+               (print_errno) ? strerror(errno) : "");
+       abort();
+       /* NOTREACHED */
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/isc/ev_streams.c b/lib/nbsd_libc/isc/ev_streams.c
new file mode 100644 (file)
index 0000000..2804b9f
--- /dev/null
@@ -0,0 +1,319 @@
+/*     $NetBSD: ev_streams.c,v 1.6 2009/04/12 17:07:17 christos Exp $  */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996-1999 by Internet Software Consortium
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/* ev_streams.c - implement asynch stream file IO for the eventlib
+ * vix 04mar96 [initial]
+ */
+
+#include <sys/cdefs.h>
+#if !defined(LINT) && !defined(CODECENTER) && !defined(lint)
+#ifdef notdef
+static const char rcsid[] = "Id: ev_streams.c,v 1.5 2005/04/27 04:56:36 sra Exp";
+#else
+__RCSID("$NetBSD: ev_streams.c,v 1.6 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif
+
+#include "port_before.h"
+#include "fd_setsize.h"
+
+#include <sys/types.h>
+#include <sys/uio.h>
+
+#include <errno.h>
+
+#include <isc/eventlib.h>
+#include <isc/assertions.h>
+#include "eventlib_p.h"
+
+#include "port_after.h"
+
+#ifndef _LIBC
+static int     copyvec(evStream *str, const struct iovec *iov, int iocnt);
+static void    consume(evStream *str, size_t bytes);
+static void    done(evContext opaqueCtx, evStream *str);
+static void    writable(evContext opaqueCtx, void *uap, int fd, int evmask);
+static void    readable(evContext opaqueCtx, void *uap, int fd, int evmask);
+#endif
+
+struct iovec
+evConsIovec(void *buf, size_t cnt) {
+       struct iovec ret;
+
+       memset(&ret, 0xf5, sizeof ret);
+       ret.iov_base = buf;
+       ret.iov_len = cnt;
+       return (ret);
+}
+
+#ifndef _LIBC
+int
+evWrite(evContext opaqueCtx, int fd, const struct iovec *iov, int iocnt,
+       evStreamFunc func, void *uap, evStreamID *id)
+{
+       evContext_p *ctx = opaqueCtx.opaque;
+       evStream *new;
+       int save;
+
+       OKNEW(new);
+       new->func = func;
+       new->uap = uap;
+       new->fd = fd;
+       new->flags = 0;
+       if (evSelectFD(opaqueCtx, fd, EV_WRITE, writable, new, &new->file) < 0)
+               goto free;
+       if (copyvec(new, iov, iocnt) < 0)
+               goto free;
+       new->prevDone = NULL;
+       new->nextDone = NULL;
+       if (ctx->streams != NULL)
+               ctx->streams->prev = new;
+       new->prev = NULL;
+       new->next = ctx->streams;
+       ctx->streams = new;
+       if (id != NULL)
+               id->opaque = new;
+       return (0);
+ free:
+       save = errno;
+       FREE(new);
+       errno = save;
+       return (-1);
+}
+
+int
+evRead(evContext opaqueCtx, int fd, const struct iovec *iov, int iocnt,
+       evStreamFunc func, void *uap, evStreamID *id)
+{
+       evContext_p *ctx = opaqueCtx.opaque;
+       evStream *new;
+       int save;
+
+       OKNEW(new);
+       new->func = func;
+       new->uap = uap;
+       new->fd = fd;
+       new->flags = 0;
+       if (evSelectFD(opaqueCtx, fd, EV_READ, readable, new, &new->file) < 0)
+               goto free;
+       if (copyvec(new, iov, iocnt) < 0)
+               goto free;
+       new->prevDone = NULL;
+       new->nextDone = NULL;
+       if (ctx->streams != NULL)
+               ctx->streams->prev = new;
+       new->prev = NULL;
+       new->next = ctx->streams;
+       ctx->streams = new;
+       if (id)
+               id->opaque = new;
+       return (0);
+ free:
+       save = errno;
+       FREE(new);
+       errno = save;
+       return (-1);
+}
+
+int
+evTimeRW(evContext opaqueCtx, evStreamID id, evTimerID timer) /*ARGSUSED*/ {
+       evStream *str = id.opaque;
+
+       UNUSED(opaqueCtx);
+
+       str->timer = timer;
+       str->flags |= EV_STR_TIMEROK;
+       return (0);
+}
+
+int
+evUntimeRW(evContext opaqueCtx, evStreamID id) /*ARGSUSED*/ {
+       evStream *str = id.opaque;
+
+       UNUSED(opaqueCtx);
+
+       str->flags &= ~EV_STR_TIMEROK;
+       return (0);
+}
+
+int
+evCancelRW(evContext opaqueCtx, evStreamID id) {
+       evContext_p *ctx = opaqueCtx.opaque;
+       evStream *old = id.opaque;
+
+       /*
+        * The streams list is doubly threaded.  First, there's ctx->streams
+        * that's used by evDestroy() to find and cancel all streams.  Second,
+        * there's ctx->strDone (head) and ctx->strLast (tail) which thread
+        * through the potentially smaller number of "IO completed" streams,
+        * used in evGetNext() to avoid scanning the entire list.
+        */
+
+       /* Unlink from ctx->streams. */
+       if (old->prev != NULL)
+               old->prev->next = old->next;
+       else
+               ctx->streams = old->next;
+       if (old->next != NULL)
+               old->next->prev = old->prev;
+
+       /*
+        * If 'old' is on the ctx->strDone list, remove it.  Update
+        * ctx->strLast if necessary.
+        */
+       if (old->prevDone == NULL && old->nextDone == NULL) {
+               /*
+                * Either 'old' is the only item on the done list, or it's
+                * not on the done list.  If the former, then we unlink it
+                * from the list.  If the latter, we leave the list alone.
+                */
+               if (ctx->strDone == old) {
+                       ctx->strDone = NULL;
+                       ctx->strLast = NULL;
+               }
+       } else {
+               if (old->prevDone != NULL)
+                       old->prevDone->nextDone = old->nextDone;
+               else
+                       ctx->strDone = old->nextDone;
+               if (old->nextDone != NULL)
+                       old->nextDone->prevDone = old->prevDone;
+               else
+                       ctx->strLast = old->prevDone;
+       }
+
+       /* Deallocate the stream. */
+       if (old->file.opaque)
+               evDeselectFD(opaqueCtx, old->file);
+       memput(old->iovOrig, sizeof (struct iovec) * old->iovOrigCount);
+       FREE(old);
+       return (0);
+}
+
+/* Copy a scatter/gather vector and initialize a stream handler's IO. */
+static int
+copyvec(evStream *str, const struct iovec *iov, int iocnt) {
+       int i;
+
+       str->iovOrig = (struct iovec *)memget(sizeof(struct iovec) * iocnt);
+       if (str->iovOrig == NULL) {
+               errno = ENOMEM;
+               return (-1);
+       }
+       str->ioTotal = 0;
+       for (i = 0; i < iocnt; i++) {
+               str->iovOrig[i] = iov[i];
+               str->ioTotal += iov[i].iov_len;
+       }
+       str->iovOrigCount = iocnt;
+       str->iovCur = str->iovOrig;
+       str->iovCurCount = str->iovOrigCount;
+       str->ioDone = 0;
+       return (0);
+}
+
+/* Pull off or truncate lead iovec(s). */
+static void
+consume(evStream *str, size_t bytes) {
+       while (bytes > 0U) {
+               if (bytes < (size_t)str->iovCur->iov_len) {
+                       str->iovCur->iov_len -= bytes;
+                       str->iovCur->iov_base = (void *)
+                               ((u_char *)str->iovCur->iov_base + bytes);
+                       str->ioDone += bytes;
+                       bytes = 0;
+               } else {
+                       bytes -= str->iovCur->iov_len;
+                       str->ioDone += str->iovCur->iov_len;
+                       str->iovCur++;
+                       str->iovCurCount--;
+               }
+       }
+}
+
+/* Add a stream to Done list and deselect the FD. */
+static void
+done(evContext opaqueCtx, evStream *str) {
+       evContext_p *ctx = opaqueCtx.opaque;
+
+       if (ctx->strLast != NULL) {
+               str->prevDone = ctx->strLast;
+               ctx->strLast->nextDone = str;
+               ctx->strLast = str;
+       } else {
+               INSIST(ctx->strDone == NULL);
+               ctx->strDone = ctx->strLast = str;
+       }
+       evDeselectFD(opaqueCtx, str->file);
+       str->file.opaque = NULL;
+       /* evDrop() will call evCancelRW() on us. */
+}
+
+/* Dribble out some bytes on the stream.  (Called by evDispatch().) */
+static void
+writable(evContext opaqueCtx, void *uap, int fd, int evmask) {
+       evStream *str = uap;
+       int bytes;
+
+       UNUSED(evmask);
+
+       bytes = writev(fd, str->iovCur, str->iovCurCount);
+       if (bytes > 0) {
+               if ((str->flags & EV_STR_TIMEROK) != 0)
+                       evTouchIdleTimer(opaqueCtx, str->timer);
+               consume(str, bytes);
+       } else {
+               if (bytes < 0 && errno != EINTR) {
+                       str->ioDone = -1;
+                       str->ioErrno = errno;
+               }
+       }
+       if (str->ioDone == -1 || str->ioDone == str->ioTotal)
+               done(opaqueCtx, str);
+}
+
+/* Scoop up some bytes from the stream.  (Called by evDispatch().) */
+static void
+readable(evContext opaqueCtx, void *uap, int fd, int evmask) {
+       evStream *str = uap;
+       int bytes;
+
+       UNUSED(evmask);
+
+       bytes = readv(fd, str->iovCur, str->iovCurCount);
+       if (bytes > 0) {
+               if ((str->flags & EV_STR_TIMEROK) != 0)
+                       evTouchIdleTimer(opaqueCtx, str->timer);
+               consume(str, bytes);
+       } else {
+               if (bytes == 0)
+                       str->ioDone = 0;
+               else {
+                       if (errno != EINTR) {
+                               str->ioDone = -1;
+                               str->ioErrno = errno;
+                       }
+               }
+       }
+       if (str->ioDone <= 0 || str->ioDone == str->ioTotal)
+               done(opaqueCtx, str);
+}
+#endif
+
+/*! \file */
diff --git a/lib/nbsd_libc/isc/ev_timers.c b/lib/nbsd_libc/isc/ev_timers.c
new file mode 100644 (file)
index 0000000..9a6e730
--- /dev/null
@@ -0,0 +1,518 @@
+/*     $NetBSD: ev_timers.c,v 1.8 2009/04/12 17:07:17 christos Exp $   */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1995-1999 by Internet Software Consortium
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/* ev_timers.c - implement timers for the eventlib
+ * vix 09sep95 [initial]
+ */
+
+#include <sys/cdefs.h>
+#if !defined(LINT) && !defined(CODECENTER) && !defined(lint)
+#ifdef notdef
+static const char rcsid[] = "Id: ev_timers.c,v 1.6 2005/04/27 04:56:36 sra Exp";
+#else
+__RCSID("$NetBSD: ev_timers.c,v 1.8 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif
+
+/* Import. */
+
+#include "port_before.h"
+#include "fd_setsize.h"
+
+#include <errno.h>
+
+#include <isc/assertions.h>
+#include <isc/eventlib.h>
+#include "eventlib_p.h"
+
+#include "port_after.h"
+
+/* Constants. */
+
+#define        MILLION 1000000
+#define BILLION 1000000000
+
+/* Forward. */
+
+#ifndef _LIBC
+static int due_sooner(void *, void *);
+static void set_index(void *, int);
+static void free_timer(void *, void *);
+static void print_timer(void *, void *);
+static void idle_timeout(evContext, void *, struct timespec, struct timespec);
+
+/* Private type. */
+
+typedef struct {
+       evTimerFunc     func;
+       void *          uap;
+       struct timespec lastTouched;
+       struct timespec max_idle;
+       evTimer *       timer;
+} idle_timer;
+#endif
+
+/* Public. */
+
+struct timespec
+evConsTime(time_t sec, long nsec) {
+       struct timespec x;
+
+       x.tv_sec = sec;
+       x.tv_nsec = nsec;
+       return (x);
+}
+
+struct timespec
+evAddTime(struct timespec addend1, struct timespec addend2) {
+       struct timespec x;
+
+       x.tv_sec = addend1.tv_sec + addend2.tv_sec;
+       x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
+       if (x.tv_nsec >= BILLION) {
+               x.tv_sec++;
+               x.tv_nsec -= BILLION;
+       }
+       return (x);
+}
+
+struct timespec
+evSubTime(struct timespec minuend, struct timespec subtrahend) {
+       struct timespec x;
+
+       x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
+       if (minuend.tv_nsec >= subtrahend.tv_nsec)
+               x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
+       else {
+               x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
+               x.tv_sec--;
+       }
+       return (x);
+}
+
+int
+evCmpTime(struct timespec a, struct timespec b) {
+#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
+       time_t s = a.tv_sec - b.tv_sec;
+       long n;
+
+       if (s != 0)
+               return SGN(s);
+
+       n = a.tv_nsec - b.tv_nsec;
+       return SGN(n);
+}
+
+struct timespec
+evNowTime() {
+       struct timeval now;
+#ifdef CLOCK_REALTIME
+       struct timespec tsnow;
+       int m = CLOCK_REALTIME;
+
+#ifdef CLOCK_MONOTONIC
+#ifndef _LIBC
+       if (__evOptMonoTime)
+               m = CLOCK_MONOTONIC;
+#endif
+#endif
+       if (clock_gettime(m, &tsnow) == 0)
+               return (tsnow);
+#endif
+       if (gettimeofday(&now, NULL) < 0)
+               return (evConsTime(0L, 0L));
+       return (evTimeSpec(now));
+}
+
+struct timespec
+evUTCTime(void) {
+       struct timeval now;
+#ifdef CLOCK_REALTIME
+       struct timespec tsnow;
+       if (clock_gettime(CLOCK_REALTIME, &tsnow) == 0)
+               return (tsnow);
+#endif
+       if (gettimeofday(&now, NULL) < 0)
+               return (evConsTime(0L, 0L));
+       return (evTimeSpec(now));
+}
+
+#ifndef _LIBC
+struct timespec
+evLastEventTime(evContext opaqueCtx) {
+       evContext_p *ctx = opaqueCtx.opaque;
+
+       return (ctx->lastEventTime);
+}
+#endif
+
+struct timespec
+evTimeSpec(struct timeval tv) {
+       struct timespec ts;
+
+       ts.tv_sec = tv.tv_sec;
+       ts.tv_nsec = tv.tv_usec * 1000;
+       return (ts);
+}
+
+struct timeval
+evTimeVal(struct timespec ts) {
+       struct timeval tv;
+
+       tv.tv_sec = ts.tv_sec;
+       tv.tv_usec = ts.tv_nsec / 1000;
+       return (tv);
+}
+
+#ifndef _LIBC
+int
+evSetTimer(evContext opaqueCtx,
+          evTimerFunc func,
+          void *uap,
+          struct timespec due,
+          struct timespec inter,
+          evTimerID *opaqueID
+) {
+       evContext_p *ctx = opaqueCtx.opaque;
+       evTimer *id;
+
+       evPrintf(ctx, 1,
+"evSetTimer(ctx %p, func %p, uap %p, due %ld.%09ld, inter %ld.%09ld)\n",
+                ctx, func, uap,
+                (long)due.tv_sec, due.tv_nsec,
+                (long)inter.tv_sec, inter.tv_nsec);
+
+#ifdef __hpux
+       /*
+        * tv_sec and tv_nsec are unsigned.
+        */
+       if (due.tv_nsec >= BILLION)
+               EV_ERR(EINVAL);
+
+       if (inter.tv_nsec >= BILLION)
+               EV_ERR(EINVAL);
+#else
+       if (due.tv_sec < 0 || due.tv_nsec < 0 || due.tv_nsec >= BILLION)
+               EV_ERR(EINVAL);
+
+       if (inter.tv_sec < 0 || inter.tv_nsec < 0 || inter.tv_nsec >= BILLION)
+               EV_ERR(EINVAL);
+#endif
+
+       /* due={0,0} is a magic cookie meaning "now." */
+       if (due.tv_sec == (time_t)0 && due.tv_nsec == 0L)
+               due = evNowTime();
+
+       /* Allocate and fill. */
+       OKNEW(id);
+       id->func = func;
+       id->uap = uap;
+       id->due = due;
+       id->inter = inter;
+
+       if (heap_insert(ctx->timers, id) < 0)
+               return (-1);
+
+       /* Remember the ID if the caller provided us a place for it. */
+       if (opaqueID)
+               opaqueID->opaque = id;
+
+       if (ctx->debug > 7) {
+               evPrintf(ctx, 7, "timers after evSetTimer:\n");
+               (void) heap_for_each(ctx->timers, print_timer, (void *)ctx);
+       }
+
+       return (0);
+}
+
+int
+evClearTimer(evContext opaqueCtx, evTimerID id) {
+       evContext_p *ctx = opaqueCtx.opaque;
+       evTimer *del = id.opaque;
+
+       if (ctx->cur != NULL &&
+           ctx->cur->type == Timer &&
+           ctx->cur->u.timer.this == del) {
+               evPrintf(ctx, 8, "deferring delete of timer (executing)\n");
+               /*
+                * Setting the interval to zero ensures that evDrop() will
+                * clean up the timer.
+                */
+               del->inter = evConsTime(0, 0);
+               return (0);
+       }
+
+       if (heap_element(ctx->timers, del->index) != del)
+               EV_ERR(ENOENT);
+
+       if (heap_delete(ctx->timers, del->index) < 0)
+               return (-1);
+       FREE(del);
+
+       if (ctx->debug > 7) {
+               evPrintf(ctx, 7, "timers after evClearTimer:\n");
+               (void) heap_for_each(ctx->timers, print_timer, (void *)ctx);
+       }
+
+       return (0);
+}
+
+int
+evConfigTimer(evContext opaqueCtx,
+            evTimerID id,
+            const char *param,
+            int value
+) {
+       evContext_p *ctx = opaqueCtx.opaque;
+       evTimer *timer = id.opaque;
+       int result=0;
+
+       UNUSED(value);
+
+       if (heap_element(ctx->timers, timer->index) != timer)
+               EV_ERR(ENOENT);
+
+       if (strcmp(param, "rate") == 0)
+               timer->mode |= EV_TMR_RATE;
+       else if (strcmp(param, "interval") == 0)
+               timer->mode &= ~EV_TMR_RATE;
+       else
+               EV_ERR(EINVAL);
+
+       return (result);
+}
+
+int
+evResetTimer(evContext opaqueCtx,
+            evTimerID id,
+            evTimerFunc func,
+            void *uap,
+            struct timespec due,
+            struct timespec inter
+) {
+       evContext_p *ctx = opaqueCtx.opaque;
+       evTimer *timer = id.opaque;
+       struct timespec old_due;
+       int result=0;
+
+       if (heap_element(ctx->timers, timer->index) != timer)
+               EV_ERR(ENOENT);
+
+#ifdef __hpux
+       /*
+        * tv_sec and tv_nsec are unsigned.
+        */
+       if (due.tv_nsec >= BILLION)
+               EV_ERR(EINVAL);
+
+       if (inter.tv_nsec >= BILLION)
+               EV_ERR(EINVAL);
+#else
+       if (due.tv_sec < 0 || due.tv_nsec < 0 || due.tv_nsec >= BILLION)
+               EV_ERR(EINVAL);
+
+       if (inter.tv_sec < 0 || inter.tv_nsec < 0 || inter.tv_nsec >= BILLION)
+               EV_ERR(EINVAL);
+#endif
+
+       old_due = timer->due;
+
+       timer->func = func;
+       timer->uap = uap;
+       timer->due = due;
+       timer->inter = inter;
+
+       switch (evCmpTime(due, old_due)) {
+       case -1:
+               result = heap_increased(ctx->timers, timer->index);
+               break;
+       case 0:
+               result = 0;
+               break;
+       case 1:
+               result = heap_decreased(ctx->timers, timer->index);
+               break;
+       }
+
+       if (ctx->debug > 7) {
+               evPrintf(ctx, 7, "timers after evResetTimer:\n");
+               (void) heap_for_each(ctx->timers, print_timer, (void *)ctx);
+       }
+
+       return (result);
+}
+
+int
+evSetIdleTimer(evContext opaqueCtx,
+               evTimerFunc func,
+               void *uap,
+               struct timespec max_idle,
+               evTimerID *opaqueID
+) {
+       evContext_p *ctx = opaqueCtx.opaque;
+       idle_timer *tt;
+
+       /* Allocate and fill. */
+       OKNEW(tt);
+       tt->func = func;
+       tt->uap = uap;
+       tt->lastTouched = ctx->lastEventTime;
+       tt->max_idle = max_idle;
+
+       if (evSetTimer(opaqueCtx, idle_timeout, tt,
+                      evAddTime(ctx->lastEventTime, max_idle),
+                      max_idle, opaqueID) < 0) {
+               FREE(tt);
+               return (-1);
+       }
+
+       tt->timer = opaqueID->opaque;
+
+       return (0);
+}
+
+int
+evClearIdleTimer(evContext opaqueCtx, evTimerID id) {
+       evTimer *del = id.opaque;
+       idle_timer *tt = del->uap;
+
+       FREE(tt);
+       return (evClearTimer(opaqueCtx, id));
+}
+
+int
+evResetIdleTimer(evContext opaqueCtx,
+                evTimerID opaqueID,
+                evTimerFunc func,
+                void *uap,
+                struct timespec max_idle
+) {
+       evContext_p *ctx = opaqueCtx.opaque;
+       evTimer *timer = opaqueID.opaque;
+       idle_timer *tt = timer->uap;
+
+       tt->func = func;
+       tt->uap = uap;
+       tt->lastTouched = ctx->lastEventTime;
+       tt->max_idle = max_idle;
+
+       return (evResetTimer(opaqueCtx, opaqueID, idle_timeout, tt,
+                            evAddTime(ctx->lastEventTime, max_idle),
+                            max_idle));
+}
+
+int
+evTouchIdleTimer(evContext opaqueCtx, evTimerID id) {
+       evContext_p *ctx = opaqueCtx.opaque;
+       evTimer *t = id.opaque;
+       idle_timer *tt = t->uap;
+
+       tt->lastTouched = ctx->lastEventTime;
+
+       return (0);
+}
+
+/* Public to the rest of eventlib. */
+
+heap_context
+evCreateTimers(const evContext_p *ctx) {
+
+       UNUSED(ctx);
+
+       return (heap_new(due_sooner, set_index, 2048));
+}
+
+void
+evDestroyTimers(const evContext_p *ctx) {
+       (void) heap_for_each(ctx->timers, free_timer, NULL);
+       (void) heap_free(ctx->timers);
+}
+
+/* Private. */
+
+static int
+due_sooner(void *a, void *b) {
+       evTimer *a_timer, *b_timer;
+
+       a_timer = a;
+       b_timer = b;
+       return (evCmpTime(a_timer->due, b_timer->due) < 0);
+}
+
+static void
+set_index(void *what, int idx) {
+       evTimer *timer;
+
+       timer = what;
+       timer->index = idx;
+}
+
+static void
+free_timer(void *what, void *uap) {
+       evTimer *t = what;
+
+       UNUSED(uap);
+
+       FREE(t);
+}
+
+static void
+print_timer(void *what, void *uap) {
+       evTimer *cur = what;
+       evContext_p *ctx = uap;
+
+       cur = what;
+       evPrintf(ctx, 7,
+           "  func %p, uap %p, due %ld.%09ld, inter %ld.%09ld\n",
+                cur->func, cur->uap,
+                (long)cur->due.tv_sec, cur->due.tv_nsec,
+                (long)cur->inter.tv_sec, cur->inter.tv_nsec);
+}
+
+static void
+idle_timeout(evContext opaqueCtx,
+            void *uap,
+            struct timespec due,
+            struct timespec inter
+) {
+       evContext_p *ctx = opaqueCtx.opaque;
+       idle_timer *this = uap;
+       struct timespec idle;
+
+       UNUSED(due);
+       UNUSED(inter);
+       
+       idle = evSubTime(ctx->lastEventTime, this->lastTouched);
+       if (evCmpTime(idle, this->max_idle) >= 0) {
+               (this->func)(opaqueCtx, this->uap, this->timer->due,
+                            this->max_idle);
+               /*
+                * Setting the interval to zero will cause the timer to
+                * be cleaned up in evDrop().
+                */
+               this->timer->inter = evConsTime(0L, 0L);
+               FREE(this);
+       } else {
+               /* evDrop() will reschedule the timer. */
+               this->timer->inter = evSubTime(this->max_idle, idle);
+       }
+}
+#endif
+
+/*! \file */
diff --git a/lib/nbsd_libc/isc/eventlib_p.h b/lib/nbsd_libc/isc/eventlib_p.h
new file mode 100644 (file)
index 0000000..4d6b788
--- /dev/null
@@ -0,0 +1,283 @@
+/*     $NetBSD: eventlib_p.h,v 1.3 2009/04/12 17:07:17 christos Exp $  */
+
+/*
+ * Copyright (c) 2005 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1995-1999 by Internet Software Consortium
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/*! \file 
+ * \brief private interfaces for eventlib
+ * \author vix 09sep95 [initial]
+ *
+ * Id: eventlib_p.h,v 1.9 2006/03/09 23:57:56 marka Exp
+ */
+
+#ifndef _EVENTLIB_P_H
+#define _EVENTLIB_P_H
+
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <sys/un.h>
+
+#define EVENTLIB_DEBUG 1
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <isc/heap.h>
+#include <isc/list.h>
+#include <isc/memcluster.h>
+
+#define        EV_MASK_ALL     (EV_READ | EV_WRITE | EV_EXCEPT)
+#define EV_ERR(e)              return (errno = (e), -1)
+#define OK(x)          if ((x) < 0) EV_ERR(errno); else (void)NULL
+#define OKFREE(x, y)   if ((x) < 0) { FREE((y)); EV_ERR(errno); } \
+                       else (void)NULL
+
+#define        NEW(p)          if (((p) = memget(sizeof *(p))) != NULL) \
+                               FILL(p); \
+                       else \
+                               (void)NULL;
+#define OKNEW(p)       if (!((p) = memget(sizeof *(p)))) { \
+                               errno = ENOMEM; \
+                               return (-1); \
+                       } else \
+                               FILL(p)
+#define FREE(p)                memput((p), sizeof *(p))
+
+#if EVENTLIB_DEBUG
+#define FILL(p)                memset((p), 0xF5, sizeof *(p))
+#else
+#define FILL(p)
+#endif
+
+#ifdef USE_POLL
+#ifdef HAVE_STROPTS_H
+#include <stropts.h>
+#endif
+#include <poll.h>
+#endif /* USE_POLL */
+
+typedef struct evConn {
+       evConnFunc      func;
+       void *          uap;
+       int             fd;
+       int             flags;
+#define EV_CONN_LISTEN         0x0001          /*%< Connection is a listener. */
+#define EV_CONN_SELECTED       0x0002          /*%< evSelectFD(conn->file). */
+#define EV_CONN_BLOCK          0x0004          /*%< Listener fd was blocking. */
+       evFileID        file;
+       struct evConn * prev;
+       struct evConn * next;
+} evConn;
+
+typedef struct evAccept {
+       int             fd;
+       union {
+               struct sockaddr         sa;
+               struct sockaddr_in      in;
+#ifndef NO_SOCKADDR_UN
+               struct sockaddr_un      un;
+#endif
+       }               la;
+       ISC_SOCKLEN_T   lalen;
+       union {
+               struct sockaddr         sa;
+               struct sockaddr_in      in;
+#ifndef NO_SOCKADDR_UN
+               struct sockaddr_un      un;
+#endif
+       }               ra;
+       ISC_SOCKLEN_T   ralen;
+       int             ioErrno;
+       evConn *        conn;
+       LINK(struct evAccept) link;
+} evAccept;
+
+typedef struct evFile {
+       evFileFunc      func;
+       void *          uap;
+       int             fd;
+       int             eventmask;
+       int             preemptive;
+       struct evFile * prev;
+       struct evFile * next;
+       struct evFile * fdprev;
+       struct evFile * fdnext;
+} evFile;
+
+typedef struct evStream {
+       evStreamFunc    func;
+       void *          uap;
+       evFileID        file;
+       evTimerID       timer;
+       int             flags;
+#define EV_STR_TIMEROK 0x0001  /*%< IFF timer valid. */
+       int             fd;
+       struct iovec *  iovOrig;
+       int             iovOrigCount;
+       struct iovec *  iovCur;
+       int             iovCurCount;
+       int             ioTotal;
+       int             ioDone;
+       int             ioErrno;
+       struct evStream *prevDone, *nextDone;
+       struct evStream *prev, *next;
+} evStream;
+
+typedef struct evTimer {
+       evTimerFunc     func;
+       void *          uap;
+       struct timespec due, inter;
+       int             index;
+       int             mode;
+#define EV_TMR_RATE    1
+} evTimer;
+
+typedef struct evWait {
+       evWaitFunc      func;
+       void *          uap;
+       const void *    tag;
+       struct evWait * next;
+} evWait;
+
+typedef struct evWaitList {
+       evWait *                first;
+       evWait *                last;
+       struct evWaitList *     prev;
+       struct evWaitList *     next;
+} evWaitList;
+
+typedef struct evEvent_p {
+       enum {  Accept, File, Stream, Timer, Wait, Free, Null  } type;
+       union {
+               struct {  evAccept *this;  }                    accept;
+               struct {  evFile *this; int eventmask;  }       file;
+               struct {  evStream *this;  }                    stream;
+               struct {  evTimer *this;  }                     timer;
+               struct {  evWait *this;  }                      wait;
+               struct {  struct evEvent_p *next;  }            free;
+               struct {  const void *placeholder;  }           null;
+       } u;
+} evEvent_p;
+
+#ifdef USE_POLL
+typedef struct { 
+       void            *ctx;   /* pointer to the evContext_p   */ 
+       uint32_t        type;   /* READ, WRITE, EXCEPT, nonblk  */ 
+       uint32_t        result; /* 1 => revents, 0 => events    */ 
+} __evEmulMask; 
+
+#define emulMaskInit(ctx, field, ev, lastnext) \
+       ctx->field.ctx = ctx; \
+       ctx->field.type = ev; \
+       ctx->field.result = lastnext; 
+  
+extern short   *__fd_eventfield(int fd, __evEmulMask *maskp); 
+extern short   __poll_event(__evEmulMask *maskp); 
+extern void            __fd_clr(int fd, __evEmulMask *maskp); 
+extern void            __fd_set(int fd, __evEmulMask *maskp); 
+
+#undef  FD_ZERO 
+#define FD_ZERO(maskp) 
+  
+#undef  FD_SET 
+#define FD_SET(fd, maskp) \
+       __fd_set(fd, maskp) 
+
+#undef  FD_CLR 
+#define FD_CLR(fd, maskp) \
+       __fd_clr(fd, maskp) 
+
+#undef  FD_ISSET 
+#define FD_ISSET(fd, maskp) \
+       ((*__fd_eventfield(fd, maskp) & __poll_event(maskp)) != 0) 
+
+#endif /* USE_POLL */
+
+typedef struct {
+       /* Global. */
+       const evEvent_p *cur;
+       /* Debugging. */
+       int             debug;
+       FILE            *output;
+       /* Connections. */
+       evConn          *conns;
+       LIST(evAccept)  accepts;
+       /* Files. */
+       evFile          *files, *fdNext;
+#ifndef USE_POLL
+       fd_set          rdLast, rdNext;
+       fd_set          wrLast, wrNext;
+       fd_set          exLast, exNext;
+       fd_set          nonblockBefore;
+       int             fdMax, fdCount, highestFD;
+       evFile          *fdTable[FD_SETSIZE];
+#else
+       struct pollfd   *pollfds;       /* Allocated as needed  */ 
+       evFile          **fdTable;      /* Ditto                */ 
+       int             maxnfds;        /* # elements in above  */ 
+       int             firstfd;        /* First active fd      */ 
+       int             fdMax;          /* Last active fd       */ 
+       int             fdCount;        /* # fd:s with I/O      */ 
+       int             highestFD;      /* max fd allowed by OS */ 
+       __evEmulMask    rdLast, rdNext; 
+       __evEmulMask    wrLast, wrNext; 
+       __evEmulMask    exLast, exNext; 
+       __evEmulMask    nonblockBefore; 
+#endif /* USE_POLL */
+#ifdef EVENTLIB_TIME_CHECKS
+       struct timespec lastSelectTime;
+       int             lastFdCount;
+#endif
+       /* Streams. */
+       evStream        *streams;
+       evStream        *strDone, *strLast;
+       /* Timers. */
+       struct timespec lastEventTime;
+       heap_context    timers;
+       /* Waits. */
+       evWaitList      *waitLists;
+       evWaitList      waitDone;
+} evContext_p;
+
+/* eventlib.c */
+#define evPrintf __evPrintf
+void evPrintf(const evContext_p *ctx, int level, const char *fmt, ...)
+     ISC_FORMAT_PRINTF(3, 4);
+
+#ifdef USE_POLL
+extern int evPollfdRealloc(evContext_p *ctx, int pollfd_chunk_size, int fd);
+#endif /* USE_POLL */
+
+/* ev_timers.c */
+#define evCreateTimers __evCreateTimers
+heap_context evCreateTimers(const evContext_p *);
+#define evDestroyTimers __evDestroyTimers
+void evDestroyTimers(const evContext_p *);
+
+/* ev_waits.c */
+#define evFreeWait __evFreeWait
+evWait *evFreeWait(evContext_p *ctx, evWait *old);
+
+/* Global options */
+extern int     __evOptMonoTime;
+
+#endif /*_EVENTLIB_P_H*/
diff --git a/lib/nbsd_libc/libcincludes.mk b/lib/nbsd_libc/libcincludes.mk
new file mode 100644 (file)
index 0000000..66afcc3
--- /dev/null
@@ -0,0 +1,19 @@
+#      $NetBSD: libcincludes.mk,v 1.1 2008/10/26 07:28:06 mrg Exp $
+
+# Makefile fragment shared across several parts that want to look
+# inside libc's include tree.
+
+.if defined(LIBC_MACHINE_ARCH) && \
+    exists(${NETBSDSRCDIR}/lib/libc/arch/${LIBC_MACHINE_ARCH}/SYS.h)
+ARCHSUBDIR=    ${LIBC_MACHINE_ARCH}
+.elif exists(${NETBSDSRCDIR}/lib/libc/arch/${MACHINE_ARCH}/SYS.h)
+ARCHSUBDIR=    ${MACHINE_ARCH}
+.elif exists(${NETBSDSRCDIR}/lib/libc/arch/${MACHINE_CPU}/SYS.h)
+ARCHSUBDIR=    ${MACHINE_CPU}
+.else
+.BEGIN:
+       @echo no ARCHDIR for ${MACHINE_ARCH} nor ${MACHINE_CPU}
+       @false
+.endif
+
+ARCHDIR=       ${NETBSDSRCDIR}/lib/libc/arch/${ARCHSUBDIR}
diff --git a/lib/nbsd_libc/locale/Makefile.inc b/lib/nbsd_libc/locale/Makefile.inc
new file mode 100644 (file)
index 0000000..06fe8ad
--- /dev/null
@@ -0,0 +1,63 @@
+#      from: @(#)Makefile.inc  5.1 (Berkeley) 2/18/91
+#      $NetBSD: Makefile.inc,v 1.58 2010/06/19 13:26:52 tnozaki Exp $
+
+# locale sources
+.PATH: ${ARCHDIR}/locale ${.CURDIR}/locale
+
+SRCS+= _def_messages.c _def_monetary.c _def_numeric.c _def_time.c \
+       setlocale.c __mb_cur_max.c \
+       current_locale.c global_locale.c fix_grouping.c \
+       localeconv.c nl_langinfo.c \
+       generic_lc_all.c dummy_lc_collate.c \
+       wcstol.c wcstoll.c wcstoimax.c wcstoul.c wcstoull.c wcstoumax.c \
+       wcstod.c wcstof.c wcstold.c wcscoll.c wcsxfrm.c wcsftime.c
+
+.if (${CITRUS} == "yes")
+# citrus multibyte locale support
+# we have quirk for libc.a - see the last part of lib/libc/Makefile
+CPPFLAGS+=     -DWITH_RUNE -I${.CURDIR}
+SRCS+= _wctrans.c _wctype.c rune.c runetable.c \
+       multibyte_c90.c multibyte_amd1.c iswctype_mb.c
+CPPFLAGS.rune.c+=              -I${LIBCDIR}/citrus
+CPPFLAGS.runetable.c+=         -I${LIBCDIR}/citrus
+CPPFLAGS.multibyte_c90.c+=     -I${LIBCDIR}/citrus
+CPPFLAGS.multibyte_amd1.c+=    -I${LIBCDIR}/citrus
+.else
+# singlebyte locale - dummy
+CPPFLAGS+=     -UWITH_RUNE
+SRCS+= aliasname.c bsdctype.c localeio.c \
+       multibyte_sb.c iswctype_sb.c \
+       localeio_lc_ctype.c localeio_lc_monetary.c \
+       localeio_lc_numeric.c localeio_lc_time.c localeio_lc_messages.c
+.endif
+
+MAN+=  setlocale.3 nl_langinfo.3
+
+MAN+=  mbtowc.3 mbstowcs.3 wctomb.3 wcstombs.3 mblen.3 \
+
+MAN+=  btowc.3 mbrtowc.3 mbsrtowcs.3 \
+       wctob.3 wcrtomb.3 wcsrtombs.3 \
+       mbrlen.3 mbsinit.3
+
+MAN+=  iswalnum.3 wctype.3 iswctype.3 \
+       towlower.3 wctrans.3 towctrans.3 \
+       wcwidth.3
+
+MAN+=  wcstol.3 wcstod.3 \
+       wcscoll.3 wcsxfrm.3 \
+       wcsftime.3
+
+MLINKS+=setlocale.3 localeconv.3
+
+MLINKS+=iswalnum.3 iswalpha.3 iswalnum.3 iswblank.3 \
+       iswalnum.3 iswcntrl.3 iswalnum.3 iswdigit.3 \
+       iswalnum.3 iswgraph.3 iswalnum.3 iswlower.3 \
+       iswalnum.3 iswprint.3 iswalnum.3 iswpunct.3 \
+       iswalnum.3 iswspace.3 iswalnum.3 iswupper.3 \
+       iswalnum.3 iswxdigit.3
+
+MLINKS+=towlower.3 towupper.3
+
+MLINKS+=wcstod.3 wcstof.3 wcstod.3 wcstold.3
+MLINKS+=wcstol.3 wcstoll.3 wcstol.3 wcstoimax.3 \
+       wcstol.3 wcstoul.3 wcstol.3 wcstoull.3 wcstol.3 wcstoumax.3
diff --git a/lib/nbsd_libc/locale/__mb_cur_max.c b/lib/nbsd_libc/locale/__mb_cur_max.c
new file mode 100644 (file)
index 0000000..08c8f1d
--- /dev/null
@@ -0,0 +1,39 @@
+/*     $NetBSD: __mb_cur_max.c,v 1.2 2001/01/25 01:25:06 itojun Exp $  */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __mb_cur_max.c,v 1.2 2001/01/25 01:25:06 itojun Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <limits.h>
+
+size_t __mb_cur_max = 1;
+size_t __mb_len_max_runtime = MB_LEN_MAX;
+
diff --git a/lib/nbsd_libc/locale/__wctoint.h b/lib/nbsd_libc/locale/__wctoint.h
new file mode 100644 (file)
index 0000000..c5b695f
--- /dev/null
@@ -0,0 +1,79 @@
+/* $NetBSD: __wctoint.h,v 1.1 2001/09/28 11:25:37 yamt Exp $ */
+
+/*-
+ * Copyright (c)2001 Citrus Project,
+ * 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.
+ *
+ *     $Citrus: xpg4dl/FreeBSD/lib/libc/locale/__wctoint.h,v 1.1 2001/09/21 13:52:32 yamt Exp $
+ */
+
+
+__inline static int
+__wctoint(wchar_t wc)
+{
+       int n;
+
+       /* XXX I expect compiler to optimize this. :D */
+       switch (wc) {
+       case L'0': n = 0; break;
+       case L'1': n = 1; break;
+       case L'2': n = 2; break;
+       case L'3': n = 3; break;
+       case L'4': n = 4; break;
+       case L'5': n = 5; break;
+       case L'6': n = 6; break;
+       case L'7': n = 7; break;
+       case L'8': n = 8; break;
+       case L'9': n = 9; break;
+       case L'A': case L'a': n = 10; break;
+       case L'B': case L'b': n = 11; break;
+       case L'C': case L'c': n = 12; break;
+       case L'D': case L'd': n = 13; break;
+       case L'E': case L'e': n = 14; break;
+       case L'F': case L'f': n = 15; break;
+       case L'G': case L'g': n = 16; break;
+       case L'H': case L'h': n = 17; break;
+       case L'I': case L'i': n = 18; break;
+       case L'J': case L'j': n = 19; break;
+       case L'K': case L'k': n = 20; break;
+       case L'L': case L'l': n = 21; break;
+       case L'M': case L'm': n = 22; break;
+       case L'N': case L'n': n = 23; break;
+       case L'O': case L'o': n = 24; break;
+       case L'P': case L'p': n = 25; break;
+       case L'Q': case L'q': n = 26; break;
+       case L'R': case L'r': n = 27; break;
+       case L'S': case L's': n = 28; break;
+       case L'T': case L't': n = 29; break;
+       case L'U': case L'u': n = 30; break;
+       case L'V': case L'v': n = 31; break;
+       case L'W': case L'w': n = 32; break;
+       case L'X': case L'x': n = 33; break;
+       case L'Y': case L'y': n = 34; break;
+       case L'Z': case L'z': n = 35; break;
+       default: n = -1; break; /* error */
+       }
+
+       return n;
+}
diff --git a/lib/nbsd_libc/locale/_def_messages.c b/lib/nbsd_libc/locale/_def_messages.c
new file mode 100644 (file)
index 0000000..8ddaa03
--- /dev/null
@@ -0,0 +1,24 @@
+/*     $NetBSD: _def_messages.c,v 1.6 2005/06/12 05:21:27 lukem Exp $  */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _def_messages.c,v 1.6 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/localedef.h>
+#include <locale.h>
+
+const _MessagesLocale _DefaultMessagesLocale = 
+{
+       "^[Yy]",
+       "^[Nn]",
+       "yes",
+       "no"
+} ;
+
+const _MessagesLocale *_CurrentMessagesLocale = &_DefaultMessagesLocale;
diff --git a/lib/nbsd_libc/locale/_def_monetary.c b/lib/nbsd_libc/locale/_def_monetary.c
new file mode 100644 (file)
index 0000000..7bd1331
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: _def_monetary.c,v 1.8 2005/06/12 05:21:27 lukem Exp $  */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _def_monetary.c,v 1.8 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/localedef.h>
+#include <limits.h>
+#include <locale.h>
+
+const _MonetaryLocale _DefaultMonetaryLocale = 
+{
+       "",
+       "",
+       "",
+       "",
+       "",
+       "",
+       "",
+       (char)CHAR_MAX,
+       (char)CHAR_MAX,
+       (char)CHAR_MAX,
+       (char)CHAR_MAX,
+       (char)CHAR_MAX,
+       (char)CHAR_MAX,
+       (char)CHAR_MAX,
+       (char)CHAR_MAX,
+       (char)CHAR_MAX,
+       (char)CHAR_MAX,
+       (char)CHAR_MAX,
+       (char)CHAR_MAX,
+       (char)CHAR_MAX,
+       (char)CHAR_MAX
+};
+
+const _MonetaryLocale *_CurrentMonetaryLocale = &_DefaultMonetaryLocale;
diff --git a/lib/nbsd_libc/locale/_def_numeric.c b/lib/nbsd_libc/locale/_def_numeric.c
new file mode 100644 (file)
index 0000000..5dd29ac
--- /dev/null
@@ -0,0 +1,23 @@
+/*     $NetBSD: _def_numeric.c,v 1.6 2005/06/12 05:21:27 lukem Exp $   */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _def_numeric.c,v 1.6 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/localedef.h>
+#include <locale.h>
+
+const _NumericLocale _DefaultNumericLocale = 
+{
+       ".",
+       "",
+       ""
+};
+
+const _NumericLocale *_CurrentNumericLocale = &_DefaultNumericLocale;
diff --git a/lib/nbsd_libc/locale/_def_time.c b/lib/nbsd_libc/locale/_def_time.c
new file mode 100644 (file)
index 0000000..bccb1b1
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: _def_time.c,v 1.10 2008/05/17 03:49:54 ginsbach Exp $  */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _def_time.c,v 1.10 2008/05/17 03:49:54 ginsbach Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/localedef.h>
+#include <locale.h>
+
+const _TimeLocale _DefaultTimeLocale = 
+{
+       {
+               "Sun","Mon","Tue","Wed","Thu","Fri","Sat",
+       },
+       {
+               "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
+               "Friday", "Saturday"
+       },
+       {
+               "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+               "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+       },
+       {
+               "January", "February", "March", "April", "May", "June", "July",
+               "August", "September", "October", "November", "December"
+       },
+       {
+               "AM", "PM"
+       },
+       "%a %b %e %H:%M:%S %Y",
+       "%m/%d/%y",
+       "%H:%M:%S",
+       "%I:%M:%S %p"
+};
+
+const _TimeLocale *_CurrentTimeLocale = &_DefaultTimeLocale;
diff --git a/lib/nbsd_libc/locale/_wcstod.h b/lib/nbsd_libc/locale/_wcstod.h
new file mode 100644 (file)
index 0000000..99a3f7e
--- /dev/null
@@ -0,0 +1,126 @@
+/* $NetBSD: _wcstod.h,v 1.2 2010/12/16 17:42:27 wiz Exp $ */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins
+ * 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.
+ *
+ * Original version ID:
+ *   FreeBSD: /repoman/r/ncvs/src/lib/libc/locale/wcstod.c,v 1.4 2004/04/07 09:47:56 tjr Exp
+ *   NetBSD: wcstod.c,v 1.8 2006/04/13 01:25:13 tnozaki Exp
+ */
+
+/*
+ * function template for wcstof, wcstod, wcstold.
+ *
+ * parameters:
+ *     _FUNCNAME    : function name
+ *     _RETURN_TYPE : return type
+ *     _STRTOD_FUNC : real conversion function
+ */
+#ifndef __WCSTOD_H_
+#define __WCSTOD_H_
+
+/*
+ * Convert a string to a double-precision number.
+ *
+ * This is the wide-character counterpart of strto{f,d,ld}(). So that
+ * we do not have to duplicate the code of strto{f,d,ld}() here,
+ * we convert the supplied wide-character string to multibyte and
+ * call strto{f,d,ld}() on the result.
+ * This assumes that the multibyte encoding is compatible with ASCII
+ * for at least the digits, radix character and letters.
+ */
+_RETURN_TYPE
+_FUNCNAME(const wchar_t * __restrict nptr, wchar_t ** __restrict endptr)
+{
+       const wchar_t *src, *start;
+       _RETURN_TYPE val;
+       char *buf, *end;
+       size_t bufsiz, len;
+
+       _DIAGASSERT(nptr != NULL);
+       /* endptr may be null */
+
+       src = nptr;
+       while (iswspace((wint_t)*src) != 0)
+               ++src;
+       if (*src == L'\0')
+               goto no_convert;
+
+       /*
+        * Convert the supplied numeric wide-char. string to multibyte.
+        *
+        * We could attempt to find the end of the numeric portion of the
+        * wide-char. string to avoid converting unneeded characters but
+        * choose not to bother; optimising the uncommon case where
+        * the input string contains a lot of text after the number
+        * duplicates a lot of strto{f,d,ld}()'s functionality and
+        * slows down the most common cases.
+        */
+       start = src;
+       len = wcstombs(NULL, src, 0);
+       if (len == (size_t)-1)
+               /* errno = EILSEQ */
+               goto no_convert;
+
+       _DIAGASSERT(len > 0);
+
+       bufsiz = len;
+       buf = (void *)malloc(bufsiz + 1);
+       if (buf == NULL)
+               /* errno = ENOMEM */
+               goto no_convert;
+
+       len = wcstombs(buf, src, bufsiz + 1);
+
+       _DIAGASSERT(len == bufsiz);
+       _DIAGASSERT(buf[len] == '\0');
+
+       /* Let strto{f,d,ld}() do most of the work for us. */
+       val = _STRTOD_FUNC(buf, &end);
+       if (buf == end) {
+               free(buf);
+               goto no_convert;
+       }
+
+       /*
+        * We only know where the number ended in the _multibyte_
+        * representation of the string. If the caller wants to know
+        * where it ended, count multibyte characters to find the
+        * corresponding position in the wide-char string.
+        */
+       if (endptr != NULL)
+               /* XXX Assume each wide char is one byte. */
+               *endptr = __UNCONST(start + (size_t)(end - buf));
+
+       free(buf);
+
+       return val;
+
+no_convert:
+       if (endptr != NULL)
+               *endptr = __UNCONST(nptr);
+       return 0;
+}
+#endif /*__WCSTOD_H_*/
diff --git a/lib/nbsd_libc/locale/_wcstol.h b/lib/nbsd_libc/locale/_wcstol.h
new file mode 100644 (file)
index 0000000..dd7a6a6
--- /dev/null
@@ -0,0 +1,144 @@
+/* $NetBSD: _wcstol.h,v 1.3 2005/11/29 03:11:59 christos Exp $ */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ * Original version ID:
+ * @(#)strtol.c        8.1 (Berkeley) 6/4/93
+ * NetBSD: wcstol.c,v 1.1 2001/09/27 16:30:36 yamt Exp
+ * Citrus: xpg4dl/FreeBSD/lib/libc/locale/wcstol.c,v 1.2 2001/09/21 16:11:41 yamt Exp
+ */
+
+/*
+ * function template for wcstol, wcstoll and wcstoimax.
+ *
+ * parameters:
+ *     _FUNCNAME : function name
+ *      __INT     : return type
+ *      __INT_MIN : lower limit of the return type
+ *      __INT_MAX : upper limit of the return type
+ */
+
+__INT
+_FUNCNAME(nptr, endptr, base)
+       const wchar_t *nptr;
+       wchar_t **endptr;
+       int base;
+{
+       const wchar_t *s;
+       __INT acc, cutoff;
+       wint_t wc;
+       int i;
+       int neg, any, cutlim;
+
+       _DIAGASSERT(nptr != NULL);
+       /* endptr may be NULL */
+
+#ifdef __GNUC__
+       (void)&acc; (void)&cutoff;
+#endif
+
+       /* check base value */
+       if (base && (base < 2 || base > 36)) {
+               errno = EINVAL;
+               return 0;
+       }
+
+       /*
+        * Skip white space and pick up leading +/- sign if any.
+        * If base is 0, allow 0x for hex and 0 for octal, else
+        * assume decimal; if base is already 16, allow 0x.
+        */
+       s = nptr;
+       do {
+               wc = (wchar_t) *s++;
+       } while (iswspace(wc));
+       if (wc == L'-') {
+               neg = 1;
+               wc = *s++;
+       } else {
+               neg = 0;
+               if (wc == L'+')
+                       wc = *s++;
+       }
+       if ((base == 0 || base == 16) &&
+           wc == L'0' && (*s == L'x' || *s == L'X')) {
+               wc = s[1];
+               s += 2;
+               base = 16;
+       }
+       if (base == 0)
+               base = wc == L'0' ? 8 : 10;
+
+       /*
+        * See strtol for comments as to the logic used.
+        */
+       cutoff = neg ? __INT_MIN : __INT_MAX;
+       cutlim = (int)(cutoff % base);
+       cutoff /= base;
+       if (neg) {
+               if (cutlim > 0) {
+                       cutlim -= base;
+                       cutoff += 1;
+               }
+               cutlim = -cutlim;
+       }
+       for (acc = 0, any = 0;; wc = (wchar_t) *s++) {
+               i = __wctoint(wc);
+               if (i == -1)
+                       break;
+               if (i >= base)
+                       break;
+               if (any < 0)
+                       continue;
+               if (neg) {
+                       if (acc < cutoff || (acc == cutoff && i > cutlim)) {
+                               any = -1;
+                               acc = __INT_MIN;
+                               errno = ERANGE;
+                       } else {
+                               any = 1;
+                               acc *= base;
+                               acc -= i;
+                       }
+               } else {
+                       if (acc > cutoff || (acc == cutoff && i > cutlim)) {
+                               any = -1;
+                               acc = __INT_MAX;
+                               errno = ERANGE;
+                       } else {
+                               any = 1;
+                               acc *= base;
+                               acc += i;
+                       }
+               }
+       }
+       if (endptr != 0)
+               *endptr = __UNCONST(any ? s - 1 : nptr);
+       return (acc);
+}
diff --git a/lib/nbsd_libc/locale/_wcstoul.h b/lib/nbsd_libc/locale/_wcstoul.h
new file mode 100644 (file)
index 0000000..a21a10b
--- /dev/null
@@ -0,0 +1,120 @@
+/* $NetBSD: _wcstoul.h,v 1.3 2005/11/29 03:11:59 christos Exp $ */
+
+/*
+ * 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.
+ * 3. 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.
+ *
+ * Original version ID:
+ * @(#)strtoul.c       8.1 (Berkeley) 6/4/93
+ * Citrus: xpg4dl/FreeBSD/lib/libc/locale/wcstoul.c,v 1.2 2001/09/21 16:11:41 yamt Exp
+ * NetBSD: wcstoul.c,v 1.1 2001/09/27 16:30:37 yamt Exp
+ */
+
+/*
+ * function template for wcstoul, wcstoull and wcstoumax.
+ *
+ * parameters:
+ *     _FUNCNAME  : function name
+ *      __UINT     : return type
+ *      __UINT_MAX : upper limit of the return type
+ */
+
+__UINT
+_FUNCNAME(nptr, endptr, base)
+       const wchar_t *nptr;
+       wchar_t **endptr;
+       int base;
+{
+       const wchar_t *s;
+       __UINT acc, cutoff;
+       wint_t wc;
+       int i;
+       int neg, any, cutlim;
+
+       _DIAGASSERT(nptr != NULL);
+       /* endptr may be NULL */
+
+       if (base && (base < 2 || base > 36)) {
+               errno = EINVAL;
+               return 0;
+       }
+
+       /*
+        * Skip white space and pick up leading +/- sign if any.
+        * If base is 0, allow 0x for hex and 0 for octal, else
+        * assume decimal; if base is already 16, allow 0x.
+        */
+       s = nptr;
+       do {
+               wc = (wchar_t) *s++;
+       } while (iswspace(wc));
+       if (wc == L'-') {
+               neg = 1;
+               wc = *s++;
+       } else {
+               neg = 0;
+               if (wc == L'+')
+                       wc = *s++;
+       }
+       if ((base == 0 || base == 16) &&
+           wc == L'0' && (*s == L'x' || *s == L'X')) {
+               wc = s[1];
+               s += 2;
+               base = 16;
+       }
+       if (base == 0)
+               base = wc == L'0' ? 8 : 10;
+
+       /*
+        * See strtoul for comments as to the logic used.
+        */
+       cutoff = __UINT_MAX / (__UINT)base;
+       cutlim = (int)(__UINT_MAX % (__UINT)base);
+       for (acc = 0, any = 0;; wc = (wchar_t) *s++) {
+               i = __wctoint(wc);
+               if (i == (wint_t)-1)
+                       break;
+               if (i >= base)
+                       break;
+               if (any < 0)
+                       continue;
+               if (acc > cutoff || (acc == cutoff && i > cutlim)) {
+                       any = -1;
+                       acc = __UINT_MAX;
+                       errno = ERANGE;
+               } else {
+                       any = 1;
+                       acc *= (__UINT)base;
+                       acc += i;
+               }
+       }
+       if (neg && any > 0)
+               acc = -acc;
+       if (endptr != 0)
+               *endptr = __UNCONST(any ? s - 1 : nptr);
+       return (acc);
+}
diff --git a/lib/nbsd_libc/locale/_wctrans.c b/lib/nbsd_libc/locale/_wctrans.c
new file mode 100644 (file)
index 0000000..c432c4e
--- /dev/null
@@ -0,0 +1,106 @@
+/*     $NetBSD: _wctrans.c,v 1.17 2010/06/13 04:14:57 tnozaki Exp $    */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Borman at Krystal Technologies.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _wctrans.c,v 1.17 2010/06/13 04:14:57 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <assert.h>
+#include <wctype.h>
+
+#include "runetype_local.h"
+#include "_wctrans_local.h"
+
+/*
+ * _towctrans_ext:
+ *     translate a character (extended part)
+ */
+wint_t
+_towctrans_ext(wint_t c, struct _WCTransEntry const *te)
+{
+       __nbrune_t c0;
+       uint32_t x;
+       _RuneRange *rr;
+       _RuneEntry *base, *re;
+
+       _DIAGASSERT(te != NULL);
+
+       if (c == WEOF)
+               return (c);
+
+       c0 = (__nbrune_t)c; /* XXX assumes wchar_t = int */
+       rr = te->te_extmap;
+       base = rr->rr_rune_ranges;
+       for (x = rr->rr_nranges; x != 0; x >>= 1) {
+               re = base + (x >> 1);
+               if (re->re_min <= c0 && re->re_max >= c0)
+                       return (re->re_map + c0 - re->re_min);
+               else if (c0 >= re->re_max) {
+                       base = re + 1;
+                       x--;
+               }
+       }
+
+       return (c);
+}
diff --git a/lib/nbsd_libc/locale/_wctrans_local.h b/lib/nbsd_libc/locale/_wctrans_local.h
new file mode 100644 (file)
index 0000000..d288ce7
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: _wctrans_local.h,v 1.9 2010/06/02 15:47:25 tnozaki Exp $       */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#ifndef _WCTRANS_LOCAL_H_
+#define _WCTRANS_LOCAL_H_
+
+__BEGIN_DECLS
+wint_t _towctrans_ext(wint_t, _WCTransEntry const *);
+__END_DECLS
+
+static __inline wint_t
+_towctrans_priv(wint_t c, _WCTransEntry const *te)
+{
+       return (_RUNE_ISCACHED(c)
+               ? (wint_t)te->te_cached[(size_t)c]
+               : _towctrans_ext(c, te));
+}
+
+static __inline struct _WCTransEntry *
+_wctrans_lower(_RuneLocale *rl)
+{
+       _DIAGASSERT(rl->rl_wctrans[_WCTRANS_INDEX_LOWER].te_name != NULL);
+
+       return (&rl->rl_wctrans[_WCTRANS_INDEX_LOWER]);
+}
+
+static __inline struct _WCTransEntry *
+_wctrans_upper(_RuneLocale *rl)
+{
+       _DIAGASSERT(rl->rl_wctrans[_WCTRANS_INDEX_UPPER].te_name != NULL);
+
+       return (&rl->rl_wctrans[_WCTRANS_INDEX_UPPER]);
+}
+
+#endif /*_WCTRANS_LOCAL_H_*/
diff --git a/lib/nbsd_libc/locale/_wctype.c b/lib/nbsd_libc/locale/_wctype.c
new file mode 100644 (file)
index 0000000..5e22ceb
--- /dev/null
@@ -0,0 +1,112 @@
+/* $NetBSD: _wctype.c,v 1.9 2010/06/13 04:14:57 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Borman at Krystal Technologies.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _wctype.c,v 1.9 2010/06/13 04:14:57 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <wctype.h>
+
+#include "runetype_local.h"
+#include "_wctrans_local.h"
+#include "_wctype_local.h"
+
+_RuneType
+_runetype_priv(_RuneLocale const *rl, wint_t wc)
+{
+       __nbrune_t wc0;
+       _RuneRange const *rr;
+       _RuneEntry *base, *re;
+       uint32_t x;
+
+       _DIAGASSERT(rl != NULL);
+
+       if (wc == WEOF)
+               return 0U;
+       if (_RUNE_ISCACHED(wc))
+               return rl->rl_runetype[(size_t)wc];
+       wc0 = (__nbrune_t)wc;
+       rr = &rl->rl_runetype_ext;
+       _DIAGASSERT(rr != NULL);
+       base = rr->rr_rune_ranges;
+       for (x = rr->rr_nranges; x != (uint32_t)0; x >>= 1) {
+               re = base + (x >> 1);
+               if (re->re_min <= wc0 && re->re_max >= wc0) {
+                       if (re->re_rune_types)
+                               return re->re_rune_types[wc0 - re->re_min];
+                       else
+                               return re->re_map;
+               } else if (wc0 > re->re_max) {
+                       base = re + 1;
+                       --x;
+               }
+       }
+       return (_RuneType)0U;
+}
+
+int
+_iswctype_priv(_RuneLocale const *rl,
+    wint_t wc, _WCTypeEntry const *te)
+{
+       return !!(_runetype_priv(rl, wc) & te->te_mask);
+}
diff --git a/lib/nbsd_libc/locale/_wctype_local.h b/lib/nbsd_libc/locale/_wctype_local.h
new file mode 100644 (file)
index 0000000..8c03224
--- /dev/null
@@ -0,0 +1,37 @@
+/* $NetBSD: _wctype_local.h,v 1.3 2010/06/02 15:47:25 tnozaki Exp $ */
+
+/*-
+ * Copyright (c) 2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _WCTYPE_LOCAL_H_
+#define _WCTYPE_LOCAL_H_
+
+__BEGIN_DECLS
+_RuneType      _runetype_priv(_RuneLocale const *, wint_t);
+int            _iswctype_priv(_RuneLocale const *, wint_t, _WCTypeEntry const *);
+__END_DECLS
+
+#endif /*_WCTYPE_LOCAL_H_*/
diff --git a/lib/nbsd_libc/locale/aliasname.c b/lib/nbsd_libc/locale/aliasname.c
new file mode 100644 (file)
index 0000000..8d3fc11
--- /dev/null
@@ -0,0 +1,129 @@
+/* $NetBSD: aliasname.c,v 1.4 2009/01/11 02:46:28 christos Exp $ */
+
+/*-
+ * Copyright (c)2002 YAMAMOTO Takashi,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: aliasname.c,v 1.4 2009/01/11 02:46:28 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "aliasname_local.h"
+
+__inline int __is_ws(char);
+
+__inline int __is_ws(char ch)
+{
+
+       return (ch == ' ' || ch == '\t');
+}
+
+const char *
+__unaliasname(const char *dbname, const char *alias, void *buf, size_t bufsize)
+{
+       FILE *fp = NULL;
+       const char *result = NULL;
+       size_t resultlen;
+       size_t aliaslen;
+       const char *p;
+       size_t len;
+
+       _DIAGASSERT(dbname != NULL);
+       _DIAGASSERT(alias != NULL);
+       _DIAGASSERT(buf != NULL);
+
+       fp = fopen(dbname, "r");
+       if (fp == NULL)
+               goto quit;
+
+       aliaslen = strlen(alias);
+
+       while (/*CONSTCOND*/ 1) {
+               p = fgetln(fp, &len);
+               if (p == NULL)
+                       goto quit; /* eof or error */
+
+               _DIAGASSERT(len != 0);
+
+               /* ignore terminating NL */
+               if (p[len - 1] == '\n')
+                       len--;
+
+               /* ignore null line and comment */
+               if (len == 0 || p[0] == '#')
+                       continue;
+
+               if (aliaslen > len)
+                       continue;
+
+               if (memcmp(alias, p, aliaslen))
+                       continue;
+
+               p += aliaslen;
+               len -= aliaslen;
+
+               if (len == 0 || !__is_ws(*p))
+                       continue;
+
+               /* entry was found here */
+               break;
+
+               /* NOTREACHED */
+       }
+
+       /* skip white spaces */
+       do {
+               p++;
+               len--;
+       } while (len != 0 && __is_ws(*p));
+
+       if (len == 0)
+               goto quit;
+
+       /* count length of result */
+       resultlen = 0;
+       while (resultlen < len && !__is_ws(*p))
+               resultlen++;
+
+       /* check if space is enough */
+       if (bufsize < resultlen + 1)
+               goto quit;
+
+       memcpy(buf, p, resultlen);
+       ((char *)buf)[resultlen] = 0;
+       result = buf;
+
+quit:
+       if (fp)
+               fclose(fp);
+
+       return result;
+}
diff --git a/lib/nbsd_libc/locale/aliasname_local.h b/lib/nbsd_libc/locale/aliasname_local.h
new file mode 100644 (file)
index 0000000..bad619b
--- /dev/null
@@ -0,0 +1,74 @@
+/* $NetBSD: aliasname_local.h,v 1.3 2009/01/11 02:46:28 christos Exp $ */
+
+/*-
+ * Copyright (c)2002 YAMAMOTO Takashi,
+ * 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.
+ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _ALIASNAME_LOCAL_H_
+#define _ALIASNAME_LOCAL_H_
+
+const char *__unaliasname(const char *, const char *, void *, size_t);
+
+static __inline int
+__isforcemapping(const char *name)
+{
+       /* don't use strcasecmp, it owes locale. */
+       return
+           name[0] == '/' &&
+           (name[1] == 'F' || name[1] == 'f') &&
+           (name[2] == 'O' || name[2] == 'o') &&
+           (name[3] == 'R' || name[3] == 'r') &&
+           (name[4] == 'C' || name[4] == 'c') &&
+           (name[5] == 'E' || name[5] == 'e') &&
+           name[6] == '\0';
+}
+
+#endif /*_ALIASNAME_LOCAL_H_*/
diff --git a/lib/nbsd_libc/locale/bsdctype.c b/lib/nbsd_libc/locale/bsdctype.c
new file mode 100644 (file)
index 0000000..5e49937
--- /dev/null
@@ -0,0 +1,178 @@
+/* $NetBSD: bsdctype.c,v 1.9 2010/06/20 02:23:15 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: bsdctype.c,v 1.9 2010/06/20 02:23:15 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/endian.h>
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "bsdctype_local.h"
+#include "runetype_misc.h"
+
+const _BSDCTypeLocale _DefaultBSDCTypeLocale = {
+    _C_ctype_,
+    _C_tolower_,
+    _C_toupper_
+};
+
+const _BSDCTypeLocale *_CurrentBSDCTypeLocale = &_DefaultBSDCTypeLocale;
+
+typedef struct {
+       _BSDCTypeLocale bl;
+       unsigned char   blp_ctype_tab  [_CTYPE_NUM_CHARS + 1];
+       short           blp_tolower_tab[_CTYPE_NUM_CHARS + 1];
+       short           blp_toupper_tab[_CTYPE_NUM_CHARS + 1];
+} _BSDCTypeLocalePriv;
+
+static __inline void
+_bsdctype_init_priv(_BSDCTypeLocalePriv *blp)
+{
+#if _CTYPE_CACHE_SIZE != _CTYPE_NUM_CHARS
+       int i;
+
+       for (i = _CTYPE_CACHE_SIZE; i < _CTYPE_NUM_CHARS; ++i) {
+               blp->blp_ctype_tab  [i + 1] = 0;
+               blp->blp_tolower_tab[i + 1] = i;
+               blp->blp_toupper_tab[i + 1] = i;
+       }
+#endif
+       blp->blp_ctype_tab  [0] = 0;
+       blp->blp_tolower_tab[0] = EOF;
+       blp->blp_toupper_tab[0] = EOF;
+       blp->bl.bl_ctype_tab   = &blp->blp_ctype_tab  [0];
+       blp->bl.bl_tolower_tab = &blp->blp_tolower_tab[0];
+       blp->bl.bl_toupper_tab = &blp->blp_toupper_tab[0];
+}
+
+static __inline int
+_bsdctype_read_file(const char * __restrict var, size_t lenvar,
+    _BSDCTypeLocalePriv * __restrict blp)
+{
+       const _FileBSDCTypeLocale *fbl;
+       uint32_t value;
+       int i;
+
+       _DIAGASSERT(blp != NULL);
+
+       if (lenvar < sizeof(*fbl))
+               return EFTYPE;
+       fbl = (const _FileBSDCTypeLocale *)(const void *)var;
+       if (memcmp(&fbl->fbl_id[0], _CTYPE_ID, sizeof(fbl->fbl_id)))
+               return EFTYPE;
+       value = be32toh(fbl->fbl_rev);
+       if (value != _CTYPE_REV)
+               return EFTYPE;
+       value = be32toh(fbl->fbl_num_chars);
+       if (value != _CTYPE_CACHE_SIZE)
+               return EFTYPE;
+       for (i = 0; i < _CTYPE_CACHE_SIZE; ++i) {
+               blp->blp_ctype_tab  [i + 1] = fbl->fbl_ctype_tab[i];
+               blp->blp_tolower_tab[i + 1] = be16toh(fbl->fbl_tolower_tab[i]);
+               blp->blp_toupper_tab[i + 1] = be16toh(fbl->fbl_toupper_tab[i]);
+       }
+       return 0;
+}
+
+static __inline int
+_bsdctype_read_runetype(const char * __restrict var, size_t lenvar,
+    _BSDCTypeLocalePriv * __restrict blp)
+{
+       const _FileRuneLocale *frl;
+       int i;
+
+       _DIAGASSERT(blp != NULL);
+
+       if (lenvar < sizeof(*frl))
+               return EFTYPE;
+       lenvar -= sizeof(*frl);
+       frl = (const _FileRuneLocale *)(const void *)var;
+       if (memcmp(_RUNECT10_MAGIC, &frl->frl_magic[0], sizeof(frl->frl_magic)))
+               return EFTYPE;
+       if (frl->frl_encoding[0] != 'N' || frl->frl_encoding[1] != 'O' ||
+           frl->frl_encoding[2] != 'N' || frl->frl_encoding[3] != 'E' ||
+           frl->frl_encoding[4] != '\0') /* XXX */
+               return EFTYPE;
+       if (be32toh(frl->frl_runetype_ext.frr_nranges) != 0 ||
+           be32toh(frl->frl_maplower_ext.frr_nranges) != 0 ||
+           be32toh(frl->frl_mapupper_ext.frr_nranges) != 0)
+               return EFTYPE;
+       if (lenvar < be32toh((uint32_t)frl->frl_variable_len))
+               return EFTYPE;
+       for (i = 0; i < _CTYPE_CACHE_SIZE; ++i) {
+               blp->blp_ctype_tab  [i + 1] = (unsigned char)
+                   _runetype_to_ctype((_RuneType)
+                   be32toh(frl->frl_runetype[i]));
+               blp->blp_tolower_tab[i + 1] = (short)
+                   be32toh((uint32_t)frl->frl_maplower[i]);
+               blp->blp_toupper_tab[i + 1] = (short)
+                   be32toh((uint32_t)frl->frl_mapupper[i]);
+       }
+       return 0;
+}
+
+int
+_bsdctype_load(const char * __restrict var, size_t lenvar,
+    _BSDCTypeLocale ** __restrict pbl)
+{
+       int ret;
+       _BSDCTypeLocalePriv *blp;
+
+       _DIAGASSERT(var != NULL || lenvar < 1);
+       _DIAGASSERT(pbl != NULL);
+
+       if (lenvar < 1)
+               return EFTYPE;
+       blp = malloc(sizeof(*blp));
+       if (blp == NULL)
+               return errno;
+       _bsdctype_init_priv(blp);
+       switch (*var) {
+       case 'B':
+               _bsdctype_read_file(var, lenvar, blp);
+               break;
+       case 'R':
+               _bsdctype_read_runetype(var, lenvar, blp);
+               break;
+       default:
+               ret = EFTYPE;
+       }
+       if (ret)
+               free(blp);
+       else
+               *pbl = &blp->bl;
+       return ret;
+}
diff --git a/lib/nbsd_libc/locale/bsdctype_file.h b/lib/nbsd_libc/locale/bsdctype_file.h
new file mode 100644 (file)
index 0000000..c5effbf
--- /dev/null
@@ -0,0 +1,46 @@
+/* $NetBSD: bsdctype_file.h,v 1.1 2010/06/13 04:14:57 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _BSDCTYPE_FILE_H_
+#define _BSDCTYPE_FILE_H_
+
+#include "ctype_local.h"
+
+typedef struct {
+       char                    fbl_id[8];
+       uint32_t                fbl_rev;
+       uint32_t                fbl_num_chars;
+       uint8_t                 fbl_ctype_tab  [_CTYPE_CACHE_SIZE];
+       int16_t                 fbl_tolower_tab[_CTYPE_CACHE_SIZE];
+       int16_t                 fbl_toupper_tab[_CTYPE_CACHE_SIZE];
+} __packed _FileBSDCTypeLocale;
+
+#define _CTYPE_ID              "BSDCTYPE"
+#define _CTYPE_REV             2
+
+#endif /*_BSDCTYPE_FILE_H_*/
diff --git a/lib/nbsd_libc/locale/bsdctype_local.h b/lib/nbsd_libc/locale/bsdctype_local.h
new file mode 100644 (file)
index 0000000..112c068
--- /dev/null
@@ -0,0 +1,48 @@
+/* $NetBSD: bsdctype_local.h,v 1.2 2010/06/19 13:26:52 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _BSDCTYPE_LOCAL_H_
+#define _BSDCTYPE_LOCAL_H_
+
+#include "bsdctype_file.h"
+
+typedef struct {
+       const unsigned char     *bl_ctype_tab;
+       const short             *bl_tolower_tab;
+       const short             *bl_toupper_tab;
+} _BSDCTypeLocale;
+
+extern const _BSDCTypeLocale _DefaultBSDCTypeLocale;
+extern const _BSDCTypeLocale *_CurrentBSDCTypeLocale;
+
+__BEGIN_DECLS
+int _bsdctype_load(const char * __restrict, size_t,
+    _BSDCTypeLocale ** __restrict);
+__END_DECLS
+
+#endif /*_BSDCTYPE_LOCAL_H_*/
diff --git a/lib/nbsd_libc/locale/btowc.3 b/lib/nbsd_libc/locale/btowc.3
new file mode 100644 (file)
index 0000000..003531d
--- /dev/null
@@ -0,0 +1,87 @@
+.\" $NetBSD: btowc.3,v 1.4 2004/01/24 16:58:54 wiz Exp $
+.\"
+.\" Copyright (c)2003 Citrus Project,
+.\" 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.
+.\"
+.Dd March 3, 2003
+.Dt BTOWC 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm btowc
+.Nd convert a single byte character to a wide character
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In wchar.h
+.Ft wint_t
+.Fn btowc "int c"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn btowc
+function converts a single byte character
+.Fa c
+in the initial shift state of the current locale to a corresponding
+wide character.
+.Pp
+The behaviour of
+.Fn btowc
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+The
+.Fn btowc
+function returns:
+.Bl -tag -width 012345678901
+.It Dv WEOF
+If
+.Fa c
+is
+.Dv EOF
+or if (unsigned char)
+.Fa c
+does not correspond to a valid single byte character representation.
+.It (otherwise)
+A wide character corresponding to
+.Fa c .
+.El
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+No errors are defined.
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr mbrtowc 3 ,
+.Xr setlocale 3 ,
+.Xr wctob 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn btowc
+function conforms to
+.St -isoC-amd1 .
diff --git a/lib/nbsd_libc/locale/ctype_local.h b/lib/nbsd_libc/locale/ctype_local.h
new file mode 100644 (file)
index 0000000..b5a85d3
--- /dev/null
@@ -0,0 +1,40 @@
+/* $NetBSD: ctype_local.h,v 1.4 2010/06/13 04:14:57 tnozaki Exp $ */
+
+/*-
+ * Copyright (c) 2010 Citrus Project,
+ * 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.
+ */
+#ifndef _CTYPE_LOCAL_H_
+#define _CTYPE_LOCAL_H_
+
+#include <limits.h>
+
+#define _CTYPE_NUM_CHARS       (1 << CHAR_BIT)
+#define _CTYPE_CACHE_SIZE      (1 << 8)
+
+extern const unsigned char _C_ctype_[];
+extern const short _C_toupper_[];
+extern const short _C_tolower_[];
+
+#endif /*_CTYPE_LOCAL_H_*/
diff --git a/lib/nbsd_libc/locale/current_locale.c b/lib/nbsd_libc/locale/current_locale.c
new file mode 100644 (file)
index 0000000..f8bf1f6
--- /dev/null
@@ -0,0 +1,49 @@
+/* $NetBSD: current_locale.c,v 1.2 2009/01/11 02:46:28 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: current_locale.c,v 1.2 2009/01/11 02:46:28 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/cdefs.h>
+#include <sys/types.h>
+#include <langinfo.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stdlib.h>
+
+#include "setlocale_local.h"
+
+static struct _locale_impl_t *__current_locale = &_global_locale;
+
+struct _locale_impl_t **
+_current_locale()
+{
+       return &__current_locale;
+}
diff --git a/lib/nbsd_libc/locale/dummy_lc_collate.c b/lib/nbsd_libc/locale/dummy_lc_collate.c
new file mode 100644 (file)
index 0000000..366160e
--- /dev/null
@@ -0,0 +1,54 @@
+/* $NetBSD: dummy_lc_collate.c,v 1.2 2009/01/11 02:46:28 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: dummy_lc_collate.c,v 1.2 2009/01/11 02:46:28 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <langinfo.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "setlocale_local.h"
+
+/*
+ * macro required by dummy_lc_template.h
+ */
+#define _PREFIX(name)          __CONCAT(_dummy_LC_COLLATE_,name)
+
+#define _CATEGORY_ID           LC_COLLATE
+#define _CATEGORY_NAME         "LC_COLLATE"
+
+#include "dummy_lc_template.h"
+_LOCALE_CATEGORY_ENTRY(_dummy_LC_COLLATE_);
diff --git a/lib/nbsd_libc/locale/dummy_lc_template.h b/lib/nbsd_libc/locale/dummy_lc_template.h
new file mode 100644 (file)
index 0000000..154bf1f
--- /dev/null
@@ -0,0 +1,56 @@
+/* $NetBSD: dummy_lc_template.h,v 1.2 2009/01/11 02:46:28 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _DUMMY_LC_TEMPLATE_H_
+#define _DUMMY_LC_TEMPLATE_H_
+
+#include "generic_lc_template_decl.h"
+
+static const char *
+_PREFIX(setlocale)(const char * __restrict name,
+    struct _locale_impl_t * __restrict locale)
+{
+       if (name != NULL) {
+               if (*name == '\0')
+                       name = _get_locale_env(_CATEGORY_NAME);
+               if (strcmp(name, locale->part_name[(size_t)_CATEGORY_ID])) {
+                       if (!strcmp(_C_LOCALE, name))
+                               name = _C_LOCALE;
+                       else if (!strcmp(_POSIX_LOCALE, name))
+                               name = _POSIX_LOCALE;
+                       else
+                               return NULL;
+                       locale->part_name[(size_t)_CATEGORY_ID] = name;
+               }
+       }
+       return locale->part_name[(size_t)_CATEGORY_ID];
+}
+
+#include "generic_lc_template.h"
+
+#endif /*_DUMMY_LC_TEMPLATE_H_*/
diff --git a/lib/nbsd_libc/locale/fix_grouping.c b/lib/nbsd_libc/locale/fix_grouping.c
new file mode 100644 (file)
index 0000000..5796491
--- /dev/null
@@ -0,0 +1,109 @@
+/* $NetBSD: fix_grouping.c,v 1.5 2010/06/01 13:52:08 tnozaki Exp $ */
+
+/*
+ * Copyright (c) 2001 Alexey Zelkin <phantom@FreeBSD.org>
+ * 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.
+ *
+ * Original version ID:
+ *     FreeBSD: fix_grouping.c,v 1.8 2003/06/26 10:46:16 phantom Exp
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fix_grouping.c,v 1.5 2010/06/01 13:52:08 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <limits.h>
+#include <stddef.h>
+
+#include "fix_grouping.h"
+
+#ifndef NBCHAR_MAX
+#define NBCHAR_MAX     CHAR_MAX
+#endif
+
+#ifndef __UNCONST
+#define __UNCONST(a)    ((void *)(unsigned long)(const void *)(a))
+#endif
+
+static const char nogrouping[] = { NBCHAR_MAX, '\0' };
+
+/* don't use libc's isdigit, it owes locale. */
+#define isdigit(c)     (c >= '0' && c <= '9')
+
+/*
+ * Internal helper used to convert grouping sequences from string
+ * representation into POSIX specified form, i.e.
+ *
+ * "3;3;-1" -> "\003\003\177\000"
+ */
+
+const char *
+__fix_locale_grouping_str(const char *str)
+{
+       char *src, *dst;
+       char n;
+
+       if (str == NULL || *str == '\0') {
+               return nogrouping;
+       }
+
+       for (src = __UNCONST(str), dst = __UNCONST(str); *src != '\0'; src++) {
+
+               /* input string examples: "3;3", "3;2;-1" */
+               if (*src == ';')
+                       continue;
+       
+               if (*src == '-' && *(src+1) == '1') {
+                       *dst++ = NBCHAR_MAX;
+                       src++;
+                       continue;
+               }
+
+               if (!isdigit((unsigned char)*src)) {
+                       /* broken grouping string */
+                       return nogrouping;
+               }
+
+               /* assume all numbers <= 99 */
+               n = *src - '0';
+               if (isdigit((unsigned char)*(src+1))) {
+                       src++;
+                       n *= 10;
+                       n += *src - '0';
+               }
+
+               *dst = n;
+               /* NOTE: assume all input started with "0" as 'no grouping' */
+               if (*dst == '\0')
+                       return (dst == __UNCONST(str)) ? nogrouping : str;
+               dst++;
+       }
+       *dst = '\0';
+       return str;
+}
diff --git a/lib/nbsd_libc/locale/fix_grouping.h b/lib/nbsd_libc/locale/fix_grouping.h
new file mode 100644 (file)
index 0000000..7da8733
--- /dev/null
@@ -0,0 +1,36 @@
+/* $NetBSD: fix_grouping.h,v 1.2 2009/01/11 02:46:28 christos Exp $ */
+
+/*-
+ * Copyright (c) 2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _FIX_GROUPING_H_
+#define _FIX_GROUPING_H_
+
+__BEGIN_DECLS
+const char *__fix_locale_grouping_str(const char *);
+__END_DECLS
+
+#endif /*_FIX_GROUPING_H_*/
diff --git a/lib/nbsd_libc/locale/generic_lc_all.c b/lib/nbsd_libc/locale/generic_lc_all.c
new file mode 100644 (file)
index 0000000..3cf2597
--- /dev/null
@@ -0,0 +1,124 @@
+/* $NetBSD: generic_lc_all.c,v 1.3 2009/10/04 21:05:18 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: generic_lc_all.c,v 1.3 2009/10/04 21:05:18 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <langinfo.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "setlocale_local.h"
+
+/*
+ * macro required by all template headers
+ */
+#define _PREFIX(name)  __CONCAT(_generic_LC_ALL_, name)
+
+#include "generic_lc_template_decl.h"
+
+const char *
+_generic_LC_ALL_setlocale(const char * __restrict name,
+    struct _locale_impl_t * __restrict locale)
+{
+       _locale_category_t *l;
+       char head[_LOCALENAME_LEN_MAX * (_LC_LAST - 1)], *tail;
+       const char *tokens[_LC_LAST], *s, *t;
+       int load_locale_success, i, j;
+
+       l = _find_category(1);
+       _DIAGASSERT(l != NULL);
+       load_locale_success = 0;
+       if (name != NULL) {
+               strlcpy(&head[0], name, sizeof(head));
+               tokens[1] = &head[0];
+               tail = strchr(tokens[1], '/');
+               if (tail == NULL) {
+                       for (i = 2; i < _LC_LAST; ++i)
+                               tokens[i] = tokens[1];
+               } else {
+                       *tail++ = '\0';
+                       for (i = 2; i < _LC_LAST - 1; ++i) {
+                               tokens[i] = (const char *)tail;
+                               tail = strchr(tokens[i], '/');
+                               if (tail == NULL)
+                                       return NULL;
+                               *tail++ = '\0';
+                       }
+                       tokens[_LC_LAST - 1] = (const char *)tail;
+                       tail = strchr(tokens[i], '/');
+                       if (tail != NULL)
+                               return NULL;
+               }
+               if ((*l->setlocale)(tokens[1], locale) != NULL)
+                       load_locale_success = 1;
+       }
+       s = (*l->setlocale)(NULL, locale);
+       _DIAGASSERT(s != NULL);
+       strlcpy(&locale->query[0], s, sizeof(locale->query));
+       for (i = 2, j = 0; i < _LC_LAST; ++i) {
+               l = _find_category(i);
+               _DIAGASSERT(l != NULL);
+               if (name != NULL) {
+                       if ((*l->setlocale)(tokens[i], locale) != NULL)
+                               load_locale_success = 1;
+               }
+               t = (*l->setlocale)(NULL, locale);
+               _DIAGASSERT(t != NULL);
+               if (j == 0) {
+                       if (!strcmp(s, t))
+                               continue;
+                       for (j = 2; j < i; ++j) {
+                               strlcat(&locale->query[0], "/",
+                                   sizeof(locale->query));
+                               strlcat(&locale->query[0], s,
+                                   sizeof(locale->query));
+                       }
+               }
+               strlcat(&locale->query[0], "/", sizeof(locale->query));
+               strlcat(&locale->query[0], t, sizeof(locale->query));
+       }
+       if (name != NULL && !load_locale_success)
+               return NULL;
+       return (const char *)&locale->query[0];
+}
+
+/*
+ * macro requrired by generic_lc_template.h
+ */
+#define _CATEGORY_ID   LC_ALL
+
+#include "generic_lc_template.h"
+_LOCALE_CATEGORY_ENTRY(_generic_LC_ALL_);
diff --git a/lib/nbsd_libc/locale/generic_lc_template.h b/lib/nbsd_libc/locale/generic_lc_template.h
new file mode 100644 (file)
index 0000000..4278ed9
--- /dev/null
@@ -0,0 +1,38 @@
+/* $NetBSD: generic_lc_template.h,v 1.3 2009/03/09 02:22:25 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _GENERIC_LC_TEMPLATE_H_
+#define _GENERIC_LC_TEMPLATE_H_
+
+#define _LOCALE_CATEGORY_ENTRY(name)                   \
+const _locale_category_t name##desc = {                        \
+    .category = _CATEGORY_ID,                          \
+    .setlocale = &name##setlocale,                     \
+}
+
+#endif /*_GENERIC_LC_TEMPLATE_H_*/
diff --git a/lib/nbsd_libc/locale/generic_lc_template_decl.h b/lib/nbsd_libc/locale/generic_lc_template_decl.h
new file mode 100644 (file)
index 0000000..2aed54c
--- /dev/null
@@ -0,0 +1,35 @@
+/* $NetBSD: generic_lc_template_decl.h,v 1.2 2009/01/11 02:46:28 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _GENERIC_LC_TEMPLATE_DECL_H_
+#define _GENERIC_LC_TEMPLATE_DECL_H_
+
+static const char * _PREFIX(setlocale)(const char * __restrict,
+    struct _locale_impl_t * __restrict);
+
+#endif /*_GENERIC_LC_TEMPLATE_DECL_H_*/
diff --git a/lib/nbsd_libc/locale/global_locale.c b/lib/nbsd_libc/locale/global_locale.c
new file mode 100644 (file)
index 0000000..34370bf
--- /dev/null
@@ -0,0 +1,174 @@
+/* $NetBSD: global_locale.c,v 1.11 2010/06/19 13:26:52 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: global_locale.c,v 1.11 2010/06/19 13:26:52 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/ctype_bits.h>
+#include <sys/localedef.h>
+#include <langinfo.h>
+#include <limits.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stdlib.h>
+#ifdef WITH_RUNE
+#include "runetype_local.h"
+#else
+#include "bsdctype_local.h"
+#endif
+
+#include "setlocale_local.h"
+
+static struct lconv _global_ldata = {
+       .decimal_point          = __UNCONST("."),
+       .thousands_sep          = __UNCONST(""),
+       .grouping               = __UNCONST(""),
+       .int_curr_symbol        = __UNCONST(""),
+       .currency_symbol        = __UNCONST(""),
+       .mon_decimal_point      = __UNCONST(""),
+       .mon_thousands_sep      = __UNCONST(""),
+       .mon_grouping           = __UNCONST(""),
+       .positive_sign          = __UNCONST(""),
+       .negative_sign          = __UNCONST(""),
+       .int_frac_digits        = CHAR_MAX,
+       .frac_digits            = CHAR_MAX,
+       .p_cs_precedes          = CHAR_MAX,
+       .p_sep_by_space         = CHAR_MAX,
+       .n_cs_precedes          = CHAR_MAX,
+       .n_sep_by_space         = CHAR_MAX,
+       .p_sign_posn            = CHAR_MAX,
+       .n_sign_posn            = CHAR_MAX,
+       .int_p_cs_precedes      = CHAR_MAX,
+       .int_n_cs_precedes      = CHAR_MAX,
+       .int_p_sep_by_space     = CHAR_MAX,
+       .int_n_sep_by_space     = CHAR_MAX,
+       .int_p_sign_posn        = CHAR_MAX,
+       .int_n_sign_posn        = CHAR_MAX,
+};
+
+static const char *_global_items[(size_t)ALT_DIGITS + 1] = {
+       [(size_t)D_T_FMT    ] = "%a %b %e %H:%M:%S %Y",
+       [(size_t)D_FMT      ] = "%m/%d/%y",
+       [(size_t)T_FMT      ] = "%H:%M:%S",
+       [(size_t)T_FMT_AMPM ] = "%I:%M:%S %p",
+       [(size_t)AM_STR     ] = "AM",
+       [(size_t)PM_STR     ] = "PM",
+       [(size_t)DAY_1      ] = "Sun",
+       [(size_t)DAY_2      ] = "Mon",
+       [(size_t)DAY_3      ] = "Tue",
+       [(size_t)DAY_4      ] = "Wed",
+       [(size_t)DAY_5      ] = "Thu",
+       [(size_t)DAY_6      ] = "Fri",
+       [(size_t)DAY_7      ] = "Sat",
+       [(size_t)ABDAY_1    ] = "Sunday",
+       [(size_t)ABDAY_2    ] = "Monday",
+       [(size_t)ABDAY_3    ] = "Tuesday",
+       [(size_t)ABDAY_4    ] = "Wednesday",
+       [(size_t)ABDAY_5    ] = "Thursday",
+       [(size_t)ABDAY_6    ] = "Friday",
+       [(size_t)ABDAY_7    ] = "Saturday",
+       [(size_t)MON_1      ] = "Jan",
+       [(size_t)MON_2      ] = "Feb",
+       [(size_t)MON_3      ] = "Mar",
+       [(size_t)MON_4      ] = "Apr",
+       [(size_t)MON_5      ] = "May",
+       [(size_t)MON_6      ] = "Jun",
+       [(size_t)MON_7      ] = "Jul",
+       [(size_t)MON_8      ] = "Aug",
+       [(size_t)MON_9      ] = "Sep",
+       [(size_t)MON_10     ] = "Oct",
+       [(size_t)MON_11     ] = "Nov",
+       [(size_t)MON_12     ] = "Dec",
+       [(size_t)ABMON_1    ] = "January",
+       [(size_t)ABMON_2    ] = "February",
+       [(size_t)ABMON_3    ] = "March",
+       [(size_t)ABMON_4    ] = "April",
+       [(size_t)ABMON_5    ] = "May",
+       [(size_t)ABMON_6    ] = "June",
+       [(size_t)ABMON_7    ] = "July",
+       [(size_t)ABMON_8    ] = "August",
+       [(size_t)ABMON_9    ] = "September",
+       [(size_t)ABMON_10   ] = "October",
+       [(size_t)ABMON_11   ] = "November",
+       [(size_t)ABMON_12   ] = "December",
+       [(size_t)RADIXCHAR  ] = ".",
+       [(size_t)THOUSEP    ] = "",
+       [(size_t)YESSTR     ] = "yes",
+       [(size_t)YESEXPR    ] = "^[Yy]",
+       [(size_t)NOSTR      ] = "no",
+       [(size_t)NOEXPR     ] = "^[Nn]",
+       [(size_t)CRNCYSTR   ] = NULL,
+       [(size_t)CODESET    ] = "646",
+       [(size_t)ERA        ] = NULL,
+       [(size_t)ERA_D_FMT  ] = NULL,
+       [(size_t)ERA_D_T_FMT] = NULL,
+       [(size_t)ERA_T_FMT  ] = NULL,
+       [(size_t)ALT_DIGITS ] = NULL,
+};
+
+static struct _locale_cache_t _global_cache = {
+    .ctype_tab   = (const unsigned char *)&_C_ctype_[0],
+    .tolower_tab = (const short *)&_C_tolower_[0],
+    .toupper_tab = (const short *)&_C_toupper_[0],
+    .mb_cur_max = (size_t)1,
+    .ldata = &_global_ldata,
+    .items = &_global_items[0],
+};
+
+struct _locale_impl_t _global_locale = {
+    .cache = &_global_cache,
+    .query = { _C_LOCALE },
+    .part_name = {
+       [(size_t)LC_ALL     ] = _C_LOCALE,
+       [(size_t)LC_COLLATE ] = _C_LOCALE,
+       [(size_t)LC_CTYPE   ] = _C_LOCALE,
+       [(size_t)LC_MONETARY] = _C_LOCALE,
+       [(size_t)LC_NUMERIC ] = _C_LOCALE,
+       [(size_t)LC_TIME    ] = _C_LOCALE,
+       [(size_t)LC_MESSAGES] = _C_LOCALE,
+    },
+    .part_impl = {
+       [(size_t)LC_ALL     ] = (_locale_part_t)NULL,
+       [(size_t)LC_COLLATE ] = (_locale_part_t)NULL,
+       [(size_t)LC_CTYPE   ] = (_locale_part_t)
+#ifdef WITH_RUNE
+           __UNCONST(&_DefaultRuneLocale),
+#else
+           __UNCONST(&_DefaultBSDCTypeLocale),
+#endif
+       [(size_t)LC_MONETARY] = (_locale_part_t)
+           __UNCONST(&_DefaultMonetaryLocale),
+       [(size_t)LC_NUMERIC ] = (_locale_part_t)
+           __UNCONST(&_DefaultNumericLocale),
+       [(size_t)LC_MESSAGES] = (_locale_part_t)
+           __UNCONST(&_DefaultMessagesLocale),
+    },
+};
diff --git a/lib/nbsd_libc/locale/iswalnum.3 b/lib/nbsd_libc/locale/iswalnum.3
new file mode 100644 (file)
index 0000000..d986995
--- /dev/null
@@ -0,0 +1,116 @@
+.\"    $NetBSD: iswalnum.3,v 1.9 2004/01/24 16:58:54 wiz Exp $
+.\"
+.\" Copyright (c) 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)isalnum.3  5.2 (Berkeley) 6/29/91
+.\"
+.Dd December 22, 2000
+.Dt ISWALNUM 3
+.Os
+.Sh NAME
+.Nm iswalnum ,
+.Nm iswalpha ,
+.Nm iswblank ,
+.Nm iswcntrl ,
+.Nm iswdigit ,
+.Nm iswgraph ,
+.Nm iswlower ,
+.Nm iswprint ,
+.Nm iswpunct ,
+.Nm iswspace ,
+.Nm iswupper ,
+.Nm iswxdigit
+.Nd wide character classification utilities
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wctype.h
+.Ft int
+.Fn iswalnum "wint_t wc"
+.Ft int
+.Fn iswalpha "wint_t wc"
+.Ft int
+.Fn iswblank "wint_t wc"
+.Ft int
+.Fn iswcntrl "wint_t wc"
+.Ft int
+.Fn iswdigit "wint_t wc"
+.Ft int
+.Fn iswgraph "wint_t wc"
+.Ft int
+.Fn iswlower "wint_t wc"
+.Ft int
+.Fn iswprint "wint_t wc"
+.Ft int
+.Fn iswpunct "wint_t wc"
+.Ft int
+.Fn iswspace "wint_t wc"
+.Ft int
+.Fn iswupper "wint_t wc"
+.Ft int
+.Fn iswxdigit "wint_t wc"
+.Sh DESCRIPTION
+The functions are character classification utility functions,
+for use with wide characters
+.Po
+.Fa wchar_t
+or
+.Fa wint_t
+.Pc .
+See the description of singlebyte classification functions, like
+.Xr isalnum 3 ,
+for details.
+.Sh RETURN VALUES
+The functions return zero if the character tests false and
+return non-zero if the character tests true.
+.Sh SEE ALSO
+.Xr isalnum 3 ,
+.Xr isalpha 3 ,
+.Xr isblank 3 ,
+.Xr iscntrl 3 ,
+.Xr isdigit 3 ,
+.Xr isgraph 3 ,
+.Xr islower 3 ,
+.Xr isprint 3 ,
+.Xr ispunct 3 ,
+.Xr isspace 3 ,
+.Xr isupper 3 ,
+.Xr isxdigit 3
+.Sh STANDARDS
+The functions conform to
+.St -isoC-99 .
+.Sh CAVEATS
+The argument to these functions must be
+.Dv WEOF
+or a valid
+.Fa wchar_t
+value with the current locale; otherwise, the result is undefined.
diff --git a/lib/nbsd_libc/locale/iswctype.3 b/lib/nbsd_libc/locale/iswctype.3
new file mode 100644 (file)
index 0000000..6225844
--- /dev/null
@@ -0,0 +1,99 @@
+.\" $NetBSD: iswctype.3,v 1.7 2007/05/21 15:20:40 tnozaki Exp $
+.\"
+.\" Copyright (c)2003 Citrus Project,
+.\" 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.
+.\"
+.Dd March 4, 2003
+.Dt ISWCTYPE 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm iswctype
+.Nd test a character for character class identifier
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In wctype.h
+.Ft int
+.Fn iswctype "wint_t wc" "wctype_t charclass"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn iswctype
+function returns a boolean value that indicates whether a wide character
+.Fa wc
+is in
+.Fa charclass .
+.Pp
+The behaviour of
+.Fn iswctype
+is undefined if the
+.Fn iswctype
+function is called with an invalid
+.Fa charclass
+(changes of
+.Dv LC_CTYPE
+category invalidate
+.Fa charclass )
+or invalid wide character
+.Fa wc .
+.Pp
+The behaviour of
+.Fn iswctype
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+The
+.Fn iswctype
+returns:
+.Bl -tag -width 012345678901
+.It 0
+.Fa wc
+is not in
+.Fa charclass .
+.It non-zero
+.Fa wc
+is in
+.Fa charclass .
+.El
+.Pp
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+No errors are defined.
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr setlocale 3 ,
+.Xr towctrans 3 ,
+.Xr wctrans 3 ,
+.Xr wctype 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn iswctype
+function conforms to
+.St -isoC-amd1 .
diff --git a/lib/nbsd_libc/locale/iswctype_mb.c b/lib/nbsd_libc/locale/iswctype_mb.c
new file mode 100644 (file)
index 0000000..651ba1b
--- /dev/null
@@ -0,0 +1,184 @@
+/* $NetBSD: iswctype_mb.c,v 1.11 2010/06/13 04:14:57 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: iswctype_mb.c,v 1.11 2010/06/13 04:14:57 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <assert.h>
+#include <errno.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <string.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#include "setlocale_local.h"
+
+#include "runetype_local.h"
+#include "_wctype_local.h"
+#include "_wctrans_local.h"
+
+#define _RUNE_LOCALE() ((_RuneLocale const *) \
+    (*_current_locale())->part_impl[(size_t)LC_CTYPE])
+
+#define _ISWCTYPE_FUNC(name, index)                    \
+int                                                    \
+isw##name(wint_t wc)                                   \
+{                                                      \
+       _RuneLocale const *rl;                          \
+       _WCTypeEntry const *te;                         \
+                                                       \
+       rl = _RUNE_LOCALE();                            \
+       te = &rl->rl_wctype[index];                     \
+       return _iswctype_priv(rl, wc, te);              \
+}
+_ISWCTYPE_FUNC(alnum,  _WCTYPE_INDEX_ALNUM)
+_ISWCTYPE_FUNC(alpha,  _WCTYPE_INDEX_ALPHA)
+_ISWCTYPE_FUNC(blank,  _WCTYPE_INDEX_BLANK)
+_ISWCTYPE_FUNC(cntrl,  _WCTYPE_INDEX_CNTRL)
+_ISWCTYPE_FUNC(digit,  _WCTYPE_INDEX_DIGIT)
+_ISWCTYPE_FUNC(graph,  _WCTYPE_INDEX_GRAPH)
+_ISWCTYPE_FUNC(lower,  _WCTYPE_INDEX_LOWER)
+_ISWCTYPE_FUNC(print,  _WCTYPE_INDEX_PRINT)
+_ISWCTYPE_FUNC(punct,  _WCTYPE_INDEX_PUNCT)
+_ISWCTYPE_FUNC(space,  _WCTYPE_INDEX_SPACE)
+_ISWCTYPE_FUNC(upper,  _WCTYPE_INDEX_UPPER)
+_ISWCTYPE_FUNC(xdigit, _WCTYPE_INDEX_XDIGIT)
+
+#define _TOWCTRANS_FUNC(name, index)                   \
+wint_t                                                 \
+tow##name(wint_t wc)                                   \
+{                                                      \
+       _RuneLocale const *rl;                          \
+       _WCTransEntry const *te;                        \
+                                                       \
+       rl = _RUNE_LOCALE();                            \
+       te = &rl->rl_wctrans[index];                    \
+       return _towctrans_priv(wc, te);                 \
+}
+_TOWCTRANS_FUNC(upper, _WCTRANS_INDEX_UPPER)
+_TOWCTRANS_FUNC(lower, _WCTRANS_INDEX_LOWER)
+
+wctype_t
+wctype(const char *charclass)
+{
+       _RuneLocale const *rl;
+       size_t i;
+
+       rl = _RUNE_LOCALE();
+       for (i = 0; i < _WCTYPE_NINDEXES; ++i) {
+               if (!strcmp(rl->rl_wctype[i].te_name, charclass))
+                       return (wctype_t)__UNCONST(&rl->rl_wctype[i]);
+       }
+       return (wctype_t)NULL;
+}
+
+wctrans_t
+wctrans(const char *charmap)
+{
+       _RuneLocale const *rl;
+       size_t i;
+
+       rl = _RUNE_LOCALE();
+       for (i = 0; i < _WCTRANS_NINDEXES; ++i) {
+               _DIAGASSERT(rl->rl_wctrans[i].te_name != NULL);
+               if (!strcmp(rl->rl_wctrans[i].te_name, charmap))
+                       return (wctrans_t)__UNCONST(&rl->rl_wctype[i]);
+       }
+       return (wctrans_t)NULL;
+}
+
+int
+iswctype(wint_t wc, wctype_t charclass)
+{
+       _RuneLocale const *rl;
+       _WCTypeEntry const *te;
+
+       if (charclass == NULL) {
+               errno = EINVAL;
+               return 0;
+       }
+       rl = _RUNE_LOCALE();
+       te = (_WCTypeEntry const *)(void *)charclass;
+       return _iswctype_priv(rl, wc, te);
+}
+
+wint_t
+towctrans(wint_t wc, wctrans_t charmap)
+{
+       _WCTransEntry const *te;
+
+       if (charmap == NULL) {
+               errno = EINVAL;
+               return wc;
+       }
+       te = (_WCTransEntry const *)(void *)charmap;
+       return _towctrans_priv(wc, te);
+}
+
+__weak_alias(wcwidth,_wcwidth)
+
+int
+wcwidth(wchar_t wc)
+{
+       _RuneLocale const *rl;
+       _RuneType x;
+
+       if (wc == L'\0')
+               return 0;
+       rl = _RUNE_LOCALE();
+       x = _runetype_priv(rl, wc);
+       if (x & _RUNETYPE_R)
+               return ((unsigned)x & _RUNETYPE_SWM) >> _RUNETYPE_SWS;
+       return -1;
+}
+
+int
+wcswidth(const wchar_t * __restrict ws, size_t wn)
+{
+       _RuneLocale const *rl;
+       _RuneType x;
+       int width;
+
+       _DIAGASSERT(ws != NULL);
+
+       rl = _RUNE_LOCALE();
+       width = 0;
+       while (wn > 0 && *ws != L'\0') {
+               x = _runetype_priv(rl, *ws);
+               if ((x & _RUNETYPE_R) == 0)
+                       return -1;
+               width += ((unsigned)x & _RUNETYPE_SWM) >> _RUNETYPE_SWS;
+               ++ws, --wn;
+       }
+       return width;
+}
diff --git a/lib/nbsd_libc/locale/iswctype_sb.c b/lib/nbsd_libc/locale/iswctype_sb.c
new file mode 100644 (file)
index 0000000..00863ca
--- /dev/null
@@ -0,0 +1,199 @@
+/* $NetBSD: iswctype_sb.c,v 1.11 2010/06/01 18:00:28 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: iswctype_sb.c,v 1.11 2010/06/01 18:00:28 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#define _CTYPE_NOINLINE
+#include <ctype.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#define _ISWCTYPE_FUNC(name)                           \
+int                                                    \
+isw##name(wint_t wc)                                   \
+{                                                      \
+       int c;                                          \
+                                                       \
+       c = (wc == WEOF) ? EOF : (unsigned char)wc;     \
+       return is##name(c);                             \
+}
+_ISWCTYPE_FUNC(alnum)
+_ISWCTYPE_FUNC(alpha)
+_ISWCTYPE_FUNC(blank)
+_ISWCTYPE_FUNC(cntrl)
+_ISWCTYPE_FUNC(digit)
+_ISWCTYPE_FUNC(graph)
+_ISWCTYPE_FUNC(lower)
+_ISWCTYPE_FUNC(print)
+_ISWCTYPE_FUNC(punct)
+_ISWCTYPE_FUNC(space)
+_ISWCTYPE_FUNC(upper)
+_ISWCTYPE_FUNC(xdigit)
+
+#define _TOWCTRANS_FUNC(name)                          \
+wint_t                                                 \
+tow##name(wint_t wc)                                   \
+{                                                      \
+       int c;                                          \
+       c = (wc == WEOF) ? EOF : (unsigned char)wc;     \
+       return to##name(c);                             \
+}
+_TOWCTRANS_FUNC(upper)
+_TOWCTRANS_FUNC(lower)
+
+struct _wctype_priv_t {
+       const char *name;
+       int (*iswctype)(wint_t);
+};
+
+static const struct _wctype_priv_t _wctype_decl[] = {
+    { "alnum",  &iswalnum  },
+    { "alpha",  &iswalpha  },
+    { "blank",  &iswblank  },
+    { "cntrl",  &iswcntrl  },
+    { "digit",  &iswdigit  },
+    { "graph",  &iswgraph  },
+    { "lower",  &iswlower  },
+    { "print",  &iswprint  },
+    { "punct",  &iswpunct  },
+    { "space",  &iswspace  },
+    { "upper",  &iswupper  },
+    { "xdigit", &iswxdigit },
+};
+static const size_t _wctype_decl_size =
+    sizeof(_wctype_decl) / sizeof(struct _wctype_priv_t);
+
+wctype_t
+wctype(const char *charclass)
+{
+       size_t i;
+
+       for (i = 0; i < _wctype_decl_size; ++i) {
+                if (!strcmp(charclass, _wctype_decl[i].name))
+                       return (wctype_t)__UNCONST(&_wctype_decl[i]);
+       }
+       return (wctype_t)NULL;
+}
+
+struct _wctrans_priv_t {
+       const char *name;
+       wint_t (*towctrans)(wint_t);
+};
+
+static const struct _wctrans_priv_t _wctrans_decl[] = {
+    { "upper", &towupper },
+    { "lower", &towlower },
+};
+static const size_t _wctrans_decl_size =
+    sizeof(_wctrans_decl) / sizeof(struct _wctrans_priv_t);
+
+wctrans_t
+/*ARGSUSED*/
+wctrans(const char *charmap)
+{
+       size_t i;
+
+       for (i = 0; i < _wctrans_decl_size; ++i) {
+                if (!strcmp(charmap, _wctrans_decl[i].name))
+                       return (wctrans_t)__UNCONST(&_wctrans_decl[i]);
+       }
+       return (wctrans_t)NULL;
+}
+
+int
+/*ARGSUSED*/
+iswctype(wint_t wc, wctype_t charclass)
+{
+       const struct _wctype_priv_t *p;
+
+       p = (const struct _wctype_priv_t *)(void *)charclass;
+       if (p < &_wctype_decl[0] || p > &_wctype_decl[_wctype_decl_size - 1]) {
+               errno = EINVAL;
+               return 0;
+       }
+       return (*p->iswctype)(wc);
+}
+
+wint_t
+/*ARGSUSED*/
+towctrans(wint_t wc, wctrans_t charmap)
+{
+       const struct _wctrans_priv_t *p;
+
+       p = (const struct _wctrans_priv_t *)(void *)charmap;
+       if (p < &_wctrans_decl[0] || p > &_wctrans_decl[_wctrans_decl_size - 1]) {
+               errno = EINVAL;
+               return wc;
+       }
+       return (*p->towctrans)(wc);
+}
+
+__weak_alias(wcwidth,_wcwidth)
+
+int
+wcwidth(wchar_t wc)
+{ 
+       int c;
+
+       switch (wc) {
+       case L'\0':
+               return 0;
+       case WEOF:
+               c = EOF;
+               break;
+       default:
+               c = (unsigned char)wc;
+       }
+       if (isprint(c))
+               return 1;
+       return -1;
+}
+
+int
+wcswidth(const wchar_t * __restrict ws, size_t wn)
+{
+       const wchar_t *pws;
+       int c;
+
+       pws = ws;
+       while (wn > 0 && *ws != L'\0') {
+               c = (*ws == WEOF) ? EOF : (unsigned char)*ws;
+               if (!isprint(c))
+                       return -1;
+               ++ws, --wn;
+       }
+       return (int)(ws - pws);
+}
diff --git a/lib/nbsd_libc/locale/localeconv.c b/lib/nbsd_libc/locale/localeconv.c
new file mode 100644 (file)
index 0000000..5b6f6db
--- /dev/null
@@ -0,0 +1,45 @@
+/* $NetBSD: localeconv.c,v 1.18 2010/05/22 13:15:59 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: localeconv.c,v 1.18 2010/05/22 13:15:59 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <langinfo.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+
+#include "setlocale_local.h"
+
+struct lconv *
+localeconv()
+{
+       return _current_cache()->ldata;
+}
diff --git a/lib/nbsd_libc/locale/localeio.c b/lib/nbsd_libc/locale/localeio.c
new file mode 100644 (file)
index 0000000..ffd9015
--- /dev/null
@@ -0,0 +1,177 @@
+/*     $NetBSD: localeio.c,v 1.5 2010/06/19 13:26:52 tnozaki Exp $     */
+/*
+ * Copyright (c) 2008, The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Brian Ginsbach.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: localeio.c,v 1.5 2010/06/19 13:26:52 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <locale.h>
+#include <paths.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "localeio.h"
+
+int
+_localeio_map_file(const char * __restrict path,
+    void ** __restrict pvar, size_t * __restrict plenvar)
+{
+       int fd, ret;
+       struct stat st;
+       void *var;
+       size_t lenvar;
+
+       _DIAGASSERT(path != NULL);
+       _DIAGASSERT(pvar != NULL);
+       _DIAGASSERT(plenvar != NULL);
+
+       fd = open(path, O_RDONLY);
+       if (fd == -1)
+               return errno;
+       if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1 || fstat(fd, &st) == 1) {
+               ret = errno;
+               goto error;
+       }
+       if (!S_ISREG(st.st_mode)) {
+               ret = EBADF;
+               goto error;
+       }
+       lenvar = (size_t)st.st_size;
+       if (lenvar < 1) {
+               ret = EFTYPE;
+               goto error;
+       }
+       var = mmap(NULL, lenvar, PROT_READ,
+           MAP_FILE|MAP_PRIVATE, fd, (off_t)0);
+       if (var == MAP_FAILED) {
+               ret = errno;
+               goto error;
+       }
+       *pvar = var;
+       *plenvar = lenvar;
+       return 0;
+error:
+       return ret;
+}
+
+void
+_localeio_unmap_file(void *var, size_t lenvar)
+{
+       munmap(var, lenvar);
+}
+
+int
+__loadlocale(const char *name, size_t nstr, size_t nbytes,
+    size_t localesize, void *currentlocale)
+{
+       int fd, ret;
+       unsigned char **ap, *buf, *bp, *cp, *cbp, *ebp;
+       unsigned char ***locale;
+       struct stat st;
+       size_t i, bufsize;
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(localesize != 0);
+       _DIAGASSERT(currentlocale != NULL);
+
+       if ((fd = open(name, O_RDONLY)) == -1)
+               return ENOENT;
+
+       if ((fstat(fd, &st) == -1) || !S_ISREG(st.st_mode) ||
+           (st.st_size <= 0)) {
+               ret = EFTYPE;
+               goto error1;
+       }
+
+       bufsize = localesize + (size_t)st.st_size;
+       if ((buf = malloc(bufsize)) == NULL) {
+               ret = ENOMEM;
+               goto error1;
+       }
+
+       bp = buf + localesize;
+       if (read(fd, bp, (size_t)st.st_size) != st.st_size) {
+               ret = EFTYPE;
+               goto error2;
+       }
+
+       ap = (unsigned char **)(void *)buf;
+       for (i = (size_t)0, ebp = buf + bufsize; i < nstr; i++) {
+               ap[i] = bp;
+               while (bp != ebp && *bp != '\n')
+                       bp++;
+               if (bp == ebp) {
+                       ret = EFTYPE;
+                       goto error2;
+               }
+               *bp++ = '\0';
+       }
+
+       cp = buf + (sizeof(unsigned char *) * nstr);
+       for (i = 0, cbp = bp; i < nbytes; i++) {
+               int n;
+
+               while (bp != ebp && *bp != '\n')
+                       bp++;
+               if (bp == ebp) {
+                       ret = EFTYPE;
+                       goto error2;
+               }
+               /* ignore overflow/underflow and bad characters */
+               n = (unsigned char)strtol((char *)cbp, NULL, 0);
+               cp[i] = (unsigned char)(n & CHAR_MAX);
+               cbp = bp;
+       }
+
+       locale = currentlocale;
+
+       *locale = (unsigned char **)(void *)buf;
+       (void)close(fd);
+       return 0;
+
+error2:
+       free(buf);
+
+error1:
+       (void)close(fd);
+       return ret;
+}
diff --git a/lib/nbsd_libc/locale/localeio.h b/lib/nbsd_libc/locale/localeio.h
new file mode 100644 (file)
index 0000000..815729e
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: localeio.h,v 1.4 2010/06/19 13:26:52 tnozaki Exp $     */
+/*
+ * Copyright (c) 2008, The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Brian Ginsbach.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+__BEGIN_DECLS
+int _localeio_map_file(const char * __restrict,
+    void ** __restrict, size_t * __restrict);
+void _localeio_unmap_file(void *, size_t);
+int __loadlocale(const char *, size_t, size_t, size_t, void *);
+__END_DECLS
diff --git a/lib/nbsd_libc/locale/localeio_lc_ctype.c b/lib/nbsd_libc/locale/localeio_lc_ctype.c
new file mode 100644 (file)
index 0000000..0916f10
--- /dev/null
@@ -0,0 +1,122 @@
+/* $NetBSD: localeio_lc_ctype.c,v 1.6 2010/06/19 13:26:52 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: localeio_lc_ctype.c,v 1.6 2010/06/19 13:26:52 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/ctype_bits.h>
+#include <sys/queue.h>
+#include <assert.h>
+#include <errno.h>
+#include <langinfo.h>
+#include <limits.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "bsdctype_local.h"
+#include "aliasname_local.h"
+#include "localeio.h"
+
+#include "setlocale_local.h"
+
+/*
+ * macro required by all template headers
+ */
+#define _PREFIX(name)          __CONCAT(_localeio_LC_CTYPE_, name)
+
+/*
+ * macro required by nb_lc_template(_decl).h
+ */
+#define _CATEGORY_TYPE         _BSDCTypeLocale
+
+#include "nb_lc_template_decl.h"
+
+static int
+/*ARGSUSED*/
+_localeio_LC_CTYPE_create_impl(const char * __restrict root,
+    const char * __restrict name, _BSDCTypeLocale ** __restrict pdata)
+{
+       char path[PATH_MAX + 1];
+       void *var;
+       size_t lenvar;
+       int ret;
+
+       _DIAGASSERT(root != NULL);
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(pdata != NULL);
+
+       snprintf(path, sizeof(path),
+           "%s/%s/LC_CTYPE", root, name);
+       ret = _localeio_map_file(path, &var, &lenvar);
+       if (!ret) {
+               ret = _bsdctype_load((const char *)var, lenvar, pdata);
+               _localeio_unmap_file(var, lenvar);
+       }
+       return ret;
+}
+
+static __inline void
+_PREFIX(build_cache)(struct _locale_cache_t * __restrict cache,
+    _BSDCTypeLocale * __restrict data)
+{
+       _DIAGASSERT(cache != NULL);
+       _DIAGASSERT(data != NULL);
+
+       cache->ctype_tab   = data->bl_ctype_tab;
+       cache->tolower_tab = data->bl_tolower_tab;
+       cache->toupper_tab = data->bl_toupper_tab;
+       cache->mb_cur_max  = (size_t)1;
+}
+
+static __inline void
+_PREFIX(fixup)(_BSDCTypeLocale *data)
+{
+       _DIAGASSERT(data != NULL);
+
+       _ctype_       = data->bl_ctype_tab;
+       _tolower_tab_ = data->bl_tolower_tab;
+       _toupper_tab_ = data->bl_toupper_tab;
+}
+
+/*
+ * macro required by nb_lc_template.h
+ */
+#define _CATEGORY_ID           LC_CTYPE
+#define _CATEGORY_NAME         "LC_CTYPE"
+#define _CATEGORY_DEFAULT      _DefaultBSDCTypeLocale
+
+#include "nb_lc_template.h"
+#include "generic_lc_template.h"
+_LOCALE_CATEGORY_ENTRY(_localeio_LC_CTYPE_);
diff --git a/lib/nbsd_libc/locale/localeio_lc_messages.c b/lib/nbsd_libc/locale/localeio_lc_messages.c
new file mode 100644 (file)
index 0000000..adb5754
--- /dev/null
@@ -0,0 +1,83 @@
+/* $NetBSD: localeio_lc_messages.c,v 1.2 2009/01/11 02:46:28 christos Exp $ */
+
+/*
+ * Copyright (c) 2008, The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Brian Ginsbach.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: localeio_lc_messages.c,v 1.2 2009/01/11 02:46:28 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/localedef.h>
+#include <sys/queue.h>
+#include <assert.h>
+#include <errno.h>
+#include <langinfo.h>
+#include <limits.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "setlocale_local.h"
+
+#include "aliasname_local.h"
+#include "localeio.h"
+
+/*
+ * macro required by all template headers
+ */
+#define _PREFIX(name)          __CONCAT(_localeio_LC_MESSAGES_, name)
+
+#include "nb_lc_messages_misc.h"
+#include "nb_lc_template_decl.h"
+
+#define NSTRINGS (sizeof(_MessagesLocale)/sizeof(const char **))
+
+static int
+_localeio_LC_MESSAGES_create_impl(const char * __restrict root,
+    const char * __restrict name, _MessagesLocale ** __restrict pdata)
+{
+       char path[PATH_MAX + 1];
+
+       _DIAGASSERT(root != NULL);
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(pdata != NULL);
+
+       snprintf(path, sizeof(path),
+           "%s/%s/LC_MESSAGES/SYS_LC_MESSAGES", root, name);
+       return __loadlocale(path, NSTRINGS, 0, sizeof(_MessagesLocale),
+           (void *)pdata);
+}
+
+#include "nb_lc_template.h"
+_LOCALE_CATEGORY_ENTRY(_localeio_LC_MESSAGES_);
diff --git a/lib/nbsd_libc/locale/localeio_lc_monetary.c b/lib/nbsd_libc/locale/localeio_lc_monetary.c
new file mode 100644 (file)
index 0000000..ec5918f
--- /dev/null
@@ -0,0 +1,95 @@
+/* $NetBSD: localeio_lc_monetary.c,v 1.2 2009/01/11 02:46:28 christos Exp $ */
+
+/*
+ * Copyright (c) 2008, The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Brian Ginsbach.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: localeio_lc_monetary.c,v 1.2 2009/01/11 02:46:28 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/localedef.h>
+#include <sys/queue.h>
+#include <assert.h>
+#include <errno.h>
+#include <langinfo.h>
+#include <limits.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "setlocale_local.h"
+
+#include "aliasname_local.h"
+#include "fix_grouping.h"
+#include "localeio.h"
+
+/*
+ * macro required by all template headers
+ */
+#define _PREFIX(name)          __CONCAT(_localeio_LC_MONETARY_, name)
+
+#include "nb_lc_monetary_misc.h"
+#include "nb_lc_template_decl.h"
+
+#define NSTRINGS \
+       (offsetof(_MonetaryLocale, int_frac_digits)/sizeof(const char **))
+#define NCHARS \
+       (offsetof(_MonetaryLocale, int_n_sign_posn) - \
+        offsetof(_MonetaryLocale, int_frac_digits) + 1)
+
+static int
+_localeio_LC_MONETARY_create_impl(const char * __restrict root,
+    const char * __restrict name, _MonetaryLocale ** __restrict pdata)
+{
+       char path[PATH_MAX + 1];
+       int ret;
+
+        _DIAGASSERT(root != NULL);
+        _DIAGASSERT(name != NULL);
+        _DIAGASSERT(pdata != NULL);
+
+       snprintf(path, sizeof(path),
+            "%s/%s/LC_MONETARY", root, name);
+       ret = __loadlocale(path, NSTRINGS, NCHARS, sizeof(_MonetaryLocale),
+           (void *)pdata);
+       if (!ret) {
+               (*pdata)->mon_grouping =
+                  __fix_locale_grouping_str((*pdata)->mon_grouping);
+       }
+       return ret;
+}
+
+#include "nb_lc_template.h"
+_LOCALE_CATEGORY_ENTRY(_localeio_LC_MONETARY_);
diff --git a/lib/nbsd_libc/locale/localeio_lc_numeric.c b/lib/nbsd_libc/locale/localeio_lc_numeric.c
new file mode 100644 (file)
index 0000000..364589c
--- /dev/null
@@ -0,0 +1,90 @@
+/* $NetBSD: localeio_lc_numeric.c,v 1.2 2009/01/11 02:46:28 christos Exp $ */
+
+/*
+ * Copyright (c) 2008, The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Brian Ginsbach.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: localeio_lc_numeric.c,v 1.2 2009/01/11 02:46:28 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/localedef.h>
+#include <sys/queue.h>
+#include <assert.h>
+#include <errno.h>
+#include <langinfo.h>
+#include <limits.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "setlocale_local.h"
+
+#include "aliasname_local.h"
+#include "fix_grouping.h"
+#include "localeio.h"
+
+/*
+ * macro required by all template headers
+ */
+#define _PREFIX(name)          __CONCAT(_localeio_LC_NUMERIC_, name)
+
+#include "nb_lc_numeric_misc.h"
+#include "nb_lc_template_decl.h"
+
+#define NSTRINGS (sizeof(_NumericLocale)/sizeof(const char **))
+
+static int
+_localeio_LC_NUMERIC_create_impl(const char * __restrict root,
+    const char * __restrict name, _NumericLocale ** __restrict pdata)
+{
+       char path[PATH_MAX + 1];
+       int ret;
+
+       _DIAGASSERT(root != NULL);
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(pdata != NULL);
+
+       snprintf(path, sizeof(path),
+           "%s/%s/LC_NUMERIC", root, name);
+       ret = __loadlocale(path, NSTRINGS, 0, sizeof(_NumericLocale),
+           (void *)pdata);
+       if (!ret) {
+               (*pdata)->grouping =
+                   __fix_locale_grouping_str((*pdata)->grouping);
+       }
+       return ret;
+}
+
+#include "nb_lc_template.h"
+_LOCALE_CATEGORY_ENTRY(_localeio_LC_NUMERIC_);
diff --git a/lib/nbsd_libc/locale/localeio_lc_time.c b/lib/nbsd_libc/locale/localeio_lc_time.c
new file mode 100644 (file)
index 0000000..7da22da
--- /dev/null
@@ -0,0 +1,84 @@
+/* $NetBSD: localeio_lc_time.c,v 1.2 2009/01/11 02:46:28 christos Exp $ */
+
+/*
+ * Copyright (c) 2008, The NetBSD Foundation, Inc.
+ * All rights reserved.
+ * 
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Brian Ginsbach.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: localeio_lc_time.c,v 1.2 2009/01/11 02:46:28 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/localedef.h>
+#include <sys/queue.h>
+#include <assert.h>
+#include <errno.h>
+#include <langinfo.h>
+#include <limits.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "setlocale_local.h"
+
+#include "aliasname_local.h"
+#include "fix_grouping.h"
+#include "localeio.h"
+
+/*
+ * macro required by all template headers
+ */
+#define _PREFIX(name)          __CONCAT(_localeio_LC_TIME_, name)
+
+#include "nb_lc_time_misc.h"
+#include "nb_lc_template_decl.h"
+
+#define NSTRINGS (sizeof(_TimeLocale)/sizeof(const char **))
+
+static int
+_localeio_LC_TIME_create_impl(const char * __restrict root,
+    const char * __restrict name, _TimeLocale ** __restrict pdata)
+{
+       char path[PATH_MAX + 1];
+
+       _DIAGASSERT(root != NULL);
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(pdata != NULL);
+
+       snprintf(path, sizeof(path),
+           "%s/%s/LC_TIME", root, name);
+       return __loadlocale(path, NSTRINGS, 0, sizeof(_TimeLocale),
+           (void *)pdata);
+}
+
+#include "nb_lc_template.h"
+_LOCALE_CATEGORY_ENTRY(_localeio_LC_TIME_);
diff --git a/lib/nbsd_libc/locale/mblen.3 b/lib/nbsd_libc/locale/mblen.3
new file mode 100644 (file)
index 0000000..e40f9a4
--- /dev/null
@@ -0,0 +1,180 @@
+.\" $NetBSD: mblen.3,v 1.6 2006/10/14 07:51:01 wiz Exp $
+.\"
+.\" Copyright (c)2002 Citrus Project,
+.\" 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.
+.\"
+.Dd February 3, 2002
+.Dt MBLEN 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm mblen
+.Nd get number of bytes in a multibyte character
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn mblen "const char *s" "size_t n"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn mblen
+function usually determines the number of bytes in
+a multibyte character pointed to by
+.Fa s
+and returns it.
+This function shall only examine max n bytes of the array beginning from
+.Fa s .
+.Pp
+In state-dependent encodings,
+.Fa s
+may point the special sequence bytes to change the shift-state.
+Although such sequence bytes corresponds to no individual
+wide-character code,
+the
+.Fn mblen
+changes the own state by them and treats them
+as if they are a part of the subsequent multibyte character.
+.Pp
+Unlike
+.Xr mbrlen 3 ,
+the first
+.Fa n
+bytes pointed to by
+.Fa s
+need to form an entire multibyte character.
+Otherwise, this function causes an error.
+.Pp
+.Fn mblen
+is equivalent to the following call, except the internal state of the
+.Xr mbtowc 3
+function is not affected:
+.Bd -literal -offset indent
+mbtowc(NULL, s, n);
+.Ed
+.Pp
+Calling any other functions in
+.Lb libc
+never changes the internal
+state of
+.Fn mblen ,
+except for calling
+.Xr setlocale 3
+with the
+.Dv LC_CTYPE
+category changed to that of the current locale.
+Such
+.Xr setlocale 3
+calls cause the internal state of this function to be indeterminate.
+.Pp
+The behaviour of
+.Fn mblen
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.Pp
+These are the special cases:
+.Bl -tag -width 0123456789
+.It "s == NULL"
+.Fn mblen
+initializes its own internal state to an initial state, and
+determines whether the current encoding is state-dependent.
+This function returns 0 if the encoding is state-independent,
+otherwise non-zero.
+.It "n == 0"
+In this case,
+the first
+.Fa n
+bytes of the array pointed to by
+.Fa s
+never form a complete character.
+Thus,
+.Fn mblen
+always fails.
+.El
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+Normally,
+.Fn mblen
+returns:
+.Bl -tag -width 0123456789
+.It "0"
+.Fa s
+points to a nul byte
+.Pq Sq \e0 .
+.It "positive"
+The value returned is
+a number of bytes for the valid multibyte character pointed to by
+.Fa s .
+There are no cases that this value is greater than
+.Fa n
+or the value of the
+.Dv MB_CUR_MAX
+macro.
+.It "-1"
+.Fa s
+points to an invalid or incomplete multibyte character.
+The
+.Fn mblen
+also sets
+.Va errno
+to indicate the error.
+.El
+.Pp
+When
+.Fa s
+is equal to
+.Dv NULL ,
+the
+.Fn mblen
+returns:
+.Bl -tag -width 0123456789
+.It "0"
+The current encoding is state-independent.
+.It "non-zero"
+The current encoding is state-dependent.
+.El
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+.Fn mblen
+may cause an error in the following case:
+.Bl -tag -width Er
+.It Bq Er EILSEQ
+.Fa s
+points to an invalid or incomplete multibyte character.
+.El
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr mbrlen 3 ,
+.Xr mbtowc 3 ,
+.Xr setlocale 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn mblen
+function conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/locale/mbrlen.3 b/lib/nbsd_libc/locale/mbrlen.3
new file mode 100644 (file)
index 0000000..34cd0e4
--- /dev/null
@@ -0,0 +1,206 @@
+.\" $NetBSD: mbrlen.3,v 1.9 2008/02/28 19:36:51 tnozaki Exp $
+.\"
+.\" Copyright (c)2002 Citrus Project,
+.\" 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.
+.\"
+.Dd February 3, 2002
+.Dt MBRLEN 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm mbrlen
+.Nd get number of bytes in a multibyte character (restartable)
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In wchar.h
+.Ft size_t
+.Fn mbrlen "const char * restrict s" "size_t n" "mbstate_t * restrict ps"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn mbrlen
+function usually determines the number of bytes in
+a multibyte character pointed to by
+.Fa s
+and returns it.
+This function shall only examine max n bytes of the array beginning from
+.Fa s .
+.Pp
+.Fn mbrlen
+is equivalent to the following call (except
+.Fa ps
+is evaluated only once):
+.Bd -literal -offset indent
+mbrtowc(NULL, s, n, (ps != NULL) ? ps : \*[Am]internal);
+.Ed
+.Pp
+Here,
+.Fa internal
+is an internal state object.
+.Pp
+In state-dependent encodings,
+.Fa s
+may point to the special sequence bytes to change the shift-state.
+Although such sequence bytes corresponds to no individual
+wide-character code, these affect the conversion state object pointed
+to by
+.Fa ps ,
+and the
+.Fn mbrlen
+treats the special sequence bytes
+as if these are a part of the subsequent multibyte character.
+.Pp
+Unlike
+.Xr mblen 3 ,
+.Fn mbrlen
+may accept the byte sequence when it is not a complete character
+but possibly contains part of a valid character.
+In this case, this function will accept all such bytes
+and save them into the conversion state object pointed to by
+.Fa ps .
+They will be used on subsequent calls of this function to restart
+the conversion suspended.
+.Pp
+The behaviour of
+.Fn mbrlen
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.Pp
+These are the special cases:
+.Bl -tag -width 0123456789
+.It "s == NULL"
+.Fn mbrlen
+sets the conversion state object pointed to by
+.Fa ps
+to an initial state and always returns 0.
+Unlike
+.Xr mblen 3 ,
+the value returned does not indicate whether the current encoding of
+the locale is state-dependent.
+.Pp
+In this case,
+.Fn mbrlen
+ignores
+.Fa n .
+.It "n == 0"
+In this case,
+the first
+.Fa n
+bytes of the array pointed to by
+.Fa s
+never form a complete character.
+Thus,
+.Fn mbrlen
+always returns (size_t)-2.
+.It "ps == NULL"
+.Fn mbrlen
+uses its own internal state object to keep the conversion state,
+instead of
+.Fa ps
+mentioned in this manual page.
+.Pp
+Calling any other functions in
+.Lb libc
+never changes the internal
+state of
+.Fn mbrlen ,
+except for calling
+.Xr setlocale 3
+with a changing
+.Dv LC_CTYPE
+category of the current locale.
+Such
+.Xr setlocale 3
+calls cause the internal state of this function to be indeterminate.
+This internal state is initialized at startup time of the program.
+.El
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+The
+.Fn mbrlen
+returns:
+.Bl -tag -width 0123456789
+.It "0"
+.Fa s
+points to a nul byte
+.Pq Sq \e0 .
+.It "positive"
+The value returned is
+a number of bytes for the valid multibyte character pointed to by
+.Fa s .
+There are no cases that this value is greater than
+.Fa n
+or the value of the
+.Dv MB_CUR_MAX
+macro.
+.It "(size_t)-2"
+.Fa s
+points to the byte sequence which possibly contains part of a valid
+multibyte character, but which is incomplete.
+When
+.Fa n
+is at least
+.Dv MB_CUR_MAX ,
+this case can only occur if the array pointed to by
+.Fa s
+contains a redundant shift sequence.
+.It "(size_t)-1"
+.Fa s
+points to an illegal byte sequence which does not form a valid multibyte
+character.
+In this case,
+.Fn mbrtowc
+sets
+.Va errno
+to indicate the error.
+.El
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+.Fn mbrlen
+may cause an error in the following case:
+.Bl -tag -width Er
+.It Bq Er EILSEQ
+.Fa s
+points to an invalid multibyte character.
+.It Bq Er EINVAL
+.Fa ps
+points to an invalid or uninitialized mbstate_t object.
+.El
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr mblen 3 ,
+.Xr mbrtowc 3 ,
+.Xr setlocale 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn mbrlen
+function conforms to
+.St -isoC-amd1 .
+The restrict qualifier is added at
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/locale/mbrtowc.3 b/lib/nbsd_libc/locale/mbrtowc.3
new file mode 100644 (file)
index 0000000..80f7a59
--- /dev/null
@@ -0,0 +1,196 @@
+.\" $NetBSD: mbrtowc.3,v 1.8 2006/10/16 09:10:29 wiz Exp $
+.\"
+.\" Copyright (c)2002 Citrus Project,
+.\" 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.
+.\"
+.Dd February 4, 2002
+.Dt MBRTOWC 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm mbrtowc
+.Nd converts a multibyte character to a wide character (restartable)
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In wchar.h
+.Ft size_t
+.Fn mbrtowc "wchar_t * restrict pwc" "const char * restrict s" "size_t n" \
+"mbstate_t * restrict ps"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn mbrtowc
+usually converts the multibyte character pointed to by
+.Fa s
+to a wide character, and stores the wide character
+to the wchar_t object pointed to by
+.Fa pwc
+if
+.Fa pwc
+is
+.Pf non- Dv NULL
+and
+.Fa s
+points to a valid character.
+The conversion happens in accordance with, and changes the conversion
+state described in the mbstate_t object pointed to by
+.Fa ps .
+This function may examine at most
+.Fa n
+bytes of the array beginning from
+.Fa s .
+.Pp
+If
+.Fa s
+points to a valid character and the character corresponds to a nul wide
+character, then the
+.Fn mbrtowc
+places the mbstate_t object pointed to by
+.Fa ps
+to an initial conversion state.
+.Pp
+Unlike
+.Xr mbtowc 3 ,
+the
+.Fn mbrtowc
+may accept the byte sequence pointed to by
+.Fa s
+not forming a complete multibyte character
+but which may be part of a valid character.
+In this case, this function will accept all such bytes
+and save them into the conversion state object pointed to by
+.Fa ps .
+They will be used at subsequent calls of this function to restart
+the conversion suspended.
+.Pp
+The behaviour of
+.Fn mbrtowc
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.Pp
+These are the special cases:
+.Bl -tag -width 012345678901
+.It "s == NULL"
+.Fn mbrtowc
+sets the conversion state object pointed to by
+.Fa ps
+to an initial state and always returns 0.
+Unlike
+.Xr mbtowc 3 ,
+the value returned does not indicate whether the current encoding of
+the locale is state-dependent.
+.Pp
+In this case,
+.Fn mbrtowc
+ignores
+.Fa pwc
+and
+.Fa n ,
+and is equivalent to the following call:
+.Bd -literal -offset indent
+mbrtowc(NULL, "", 1, ps);
+.Ed
+.It "pwc == NULL"
+The conversion from a multibyte character to a wide character has
+taken place and the conversion state may be affected, but the resulting
+wide character is discarded.
+.It "ps == NULL"
+.Fn mbrtowc
+uses its own internal state object to keep the conversion state,
+instead of
+.Fa ps
+mentioned in this manual page.
+.Pp
+Calling any other functions in
+.Lb libc
+never changes the internal state of
+.Fn mbrtowc ,
+which is initialized at startup time of the program.
+.El
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+In the usual cases,
+.Fn mbrtowc
+returns:
+.Bl -tag -width 012345678901
+.It 0
+The next bytes pointed to by
+.Fa s
+form a nul character.
+.It positive
+If
+.Fa s
+points to a valid character,
+.Fn mbrtowc
+returns the number of bytes in the character.
+.It (size_t)-2
+.Fa s
+points to a byte sequence which possibly contains part of a valid
+multibyte character, but which is incomplete.
+When
+.Fa n
+is at least
+.Dv MB_CUR_MAX ,
+this case can only occur if the array pointed to by
+.Fa s
+contains a redundant shift sequence.
+.It (size_t)-1
+.Fa s
+points to an illegal byte sequence which does not form a valid multibyte
+character.
+In this case,
+.Fn mbrtowc
+sets
+.Va errno
+to indicate the error.
+.El
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+.Fn mbrtowc
+may cause an error in the following case:
+.Bl -tag -width Er
+.It Bq Er EILSEQ
+.Fa s
+points to an invalid or incomplete multibyte character.
+.It Bq Er EINVAL
+.Fa ps
+points to an invalid or uninitialized mbstate_t object.
+.El
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr mbrlen 3 ,
+.Xr mbtowc 3 ,
+.Xr setlocale 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn mbrtowc
+function conforms to
+.St -isoC-amd1 .
+The restrict qualifier is added at
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/locale/mbsinit.3 b/lib/nbsd_libc/locale/mbsinit.3
new file mode 100644 (file)
index 0000000..63ef147
--- /dev/null
@@ -0,0 +1,74 @@
+.\" $NetBSD: mbsinit.3,v 1.6 2006/10/16 08:42:16 wiz Exp $
+.\"
+.\" Copyright (c)2002 Citrus Project,
+.\" 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.
+.\"
+.Dd February 3, 2002
+.Dt MBSINIT 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm mbsinit
+.Nd determines whether the state object is in the initial state
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wchar.h
+.Ft int
+.Fn mbsinit "const mbstate_t *ps"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn mbsinit
+determines whether the state object pointed to by
+.Fa ps
+is the initial conversion state, or not.
+.Pp
+.Fa ps
+may be a null pointer.
+In this case,
+.Fn mbsinit
+will always return non-zero.
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn mbsinit
+returns:
+.Bl -tag -width 0123456789
+.It 0
+The current state is not the initial state.
+.It non-zero
+The current state is the initial state or
+.Fa ps
+is a null pointer.
+.El
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+No errors are defined.
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn mbsinit
+conforms to
+.St -isoC-amd1 .
diff --git a/lib/nbsd_libc/locale/mbsrtowcs.3 b/lib/nbsd_libc/locale/mbsrtowcs.3
new file mode 100644 (file)
index 0000000..a353420
--- /dev/null
@@ -0,0 +1,181 @@
+.\" $NetBSD: mbsrtowcs.3,v 1.12 2010/12/16 17:42:27 wiz Exp $
+.\"
+.\" Copyright (c)2002 Citrus Project,
+.\" 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.
+.\"
+.Dd February 4, 2002
+.Dt MBSRTOWCS 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm mbsrtowcs
+.Nd converts a multibyte character string to a wide-character string \
+(restartable)
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In wchar.h
+.Ft size_t
+.Fn mbsrtowcs "wchar_t * restrict pwcs" "const char ** restrict s" "size_t n" \
+"mbstate_t * restrict ps"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn mbsrtowcs
+converts the multibyte character string indirectly pointed to by
+.Fa s
+to the corresponding wide-character string, and stores it in the
+array pointed to by
+.Fa pwcs .
+The conversion stops due to the following reasons:
+.Bl -bullet
+.It
+The conversion reaches a nul byte.
+In this case, the nul byte is also converted.
+.It
+The
+.Fn mbsrtowcs
+has already stored
+.Fa n
+wide characters.
+.It
+The conversion encounters an invalid character.
+.El
+.Pp
+Each character will be converted as if
+.Xr mbrtowc 3
+is continuously called.
+.Pp
+After conversion,
+if
+.Fa pwcs
+is not a null pointer,
+the pointer object pointed to by
+.Fa s
+is a null pointer (if the conversion is stopped due to reaching a
+nul byte) or the first byte of the character just after the last
+character converted.
+.Pp
+If
+.Fa pwcs
+is not a null pointer and the conversion is stopped due to reaching
+a nul byte, the
+.Fn mbsrtowcs
+places the state object pointed to by
+.Fa ps
+to an initial state after the conversion has taken place.
+.Pp
+The behaviour of
+.Fn mbsrtowcs
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.Pp
+These are the special cases:
+.Bl -tag -width 012345678901
+.It "s == NULL || *s == NULL"
+Undefined (may cause the program to crash).
+.It "pwcs == NULL"
+The conversion has taken place, but the resulting wide-character string
+was discarded.
+In this case, the pointer object pointed to by
+.Fa s
+is not modified and
+.Fa n
+is ignored.
+.It "ps == NULL"
+The
+.Fn mbsrtowcs
+uses its own internal state object to keep the conversion state,
+instead of
+.Fa ps
+mentioned in this manual page.
+.Pp
+Calling any other functions in
+.Lb libc
+never changes the internal state of
+.Fn mbsrtowcs ,
+which is initialized at startup time of the program.
+.El
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn mbsrtowcs
+returns:
+.Bl -tag -width 012345678901
+.It 0 or positive
+The value returned is the number of elements stored in the array
+pointed to by
+.Fa pwcs ,
+except for a terminating nul wide character (if any).
+If
+.Fa pwcs
+is not
+.Dv NULL
+and the value returned is equal to
+.Fa n ,
+the wide-character string pointed to by
+.Fa pwcs
+is not nul-terminated.
+If
+.Fa pwcs
+is a null pointer, the value returned is the number of elements to contain
+the whole string converted, except for a terminating nul wide character.
+.It (size_t)-1
+The array indirectly pointed to by
+.Fa s
+contains a byte sequence forming invalid character.
+In this case,
+.Fn mbsrtowcs
+sets
+.Va errno
+to indicate the error.
+.El
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+.Fn mbsrtowcs
+may cause an error in the following case:
+.Bl -tag -width Er
+.It Bq Er EILSEQ
+The pointer pointed to by
+.Fa s
+points to an invalid or incomplete multibyte character.
+.It Bq Er EINVAL
+.Fa ps
+points to an invalid or uninitialized mbstate_t object.
+.El
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr mbrtowc 3 ,
+.Xr mbstowcs 3 ,
+.Xr setlocale 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn mbsrtowcs
+function conforms to
+.St -isoC-amd1 .
+The restrict qualifier is added at
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/locale/mbstowcs.3 b/lib/nbsd_libc/locale/mbstowcs.3
new file mode 100644 (file)
index 0000000..8d2dfea
--- /dev/null
@@ -0,0 +1,128 @@
+.\" $NetBSD: mbstowcs.3,v 1.11 2010/12/16 17:42:27 wiz Exp $
+.\"
+.\" Copyright (c)2002 Citrus Project,
+.\" 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.
+.\"
+.Dd February 3, 2002
+.Dt MBSTOWCS 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm mbstowcs
+.Nd converts a multibyte character string to a wide-character string
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft size_t
+.Fn mbstowcs "wchar_t * restrict pwcs" "const char * restrict s" "size_t n"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+.Fn mbstowcs
+converts a nul-terminated multibyte character string pointed to by
+.Fa s
+to the corresponding wide-character string and stores it in the array
+pointed to by
+.Fa pwcs .
+This function may modify the first at most
+.Fa n
+elements of the array pointed to by
+.Fa pwcs .
+Each character will be converted as if
+.Xr mbtowc 3
+is continuously called, except the internal state of
+.Xr mbtowc 3
+will not be affected.
+.Pp
+For state-dependent encoding,
+.Fn mbstowcs
+implies the multibyte character string pointed to by
+.Fa s
+always begins with an initial state.
+.Pp
+These are the special cases:
+.Bl -tag -width 012345678901
+.It pwcs == NULL
+.Fn mbstowcs
+returns the number of elements to store the whole wide-character string
+corresponding to the multibyte character string pointed to by
+.Fa s .
+In this case,
+.Fa n
+is ignored.
+.It s == NULL
+Undefined (may cause the program to crash).
+.El
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn mbstowcs
+returns:
+.Bl -tag -width 012345678901
+.It 0 or positive
+Number of elements stored in the array pointed to by
+.Fa pwcs .
+There are no cases that the value returned is greater than
+.Fa n
+(unless
+.Fa pwcs
+is a null pointer) or the value of the
+.Dv MB_CUR_MAX
+macro.
+If the return value is equal to
+.Fa n ,
+the string pointed to by
+.Fa pwcs
+will not be nul-terminated.
+.It (size_t)-1
+.Fa s
+points to a string containing an invalid or incomplete multibyte character.
+The
+.Fn mbstowcs
+also sets
+.Va errno
+to indicate the error.
+.El
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+.Fn mbstowcs
+may cause an error in the following case:
+.Bl -tag -width Er
+.It Bq Er EILSEQ
+.Fa s
+points to a string containing an invalid or incomplete multibyte character.
+.El
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr mbtowc 3 ,
+.Xr setlocale 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn mbstowcs
+function conforms to
+.St -ansiC .
+The restrict qualifier is added at
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/locale/mbtowc.3 b/lib/nbsd_libc/locale/mbtowc.3
new file mode 100644 (file)
index 0000000..317fb33
--- /dev/null
@@ -0,0 +1,182 @@
+.\" $NetBSD: mbtowc.3,v 1.8 2006/10/16 09:10:29 wiz Exp $
+.\"
+.\" Copyright (c)2002 Citrus Project,
+.\" 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.
+.\"
+.Dd February 3, 2002
+.Dt MBTOWC 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm mbtowc
+.Nd converts a multibyte character to a wide character
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn mbtowc "wchar_t * restrict pwc" "const char * restrict s" "size_t n"
+.Sh DESCRIPTION
+.Fn mbtowc
+usually converts the multibyte character pointed to by
+.Fa s
+to a wide character, and stores it in the wchar_t object pointed to by
+.Fa pwc
+if
+.Fa pwc
+is
+.Pf non- Dv NULL
+and
+.Fa s
+points to a valid character.
+This function may inspect at most n bytes of the array beginning from
+.Fa s .
+.Pp
+In state-dependent encodings,
+.Fa s
+may point to the special sequence bytes to change the shift-state.
+Although such sequence bytes correspond to no individual
+wide-character code,
+.Fn mbtowc
+changes its own state by the sequence bytes and treats them
+as if they are a part of the subsequence multibyte character.
+.Pp
+Unlike
+.Xr mbrtowc 3 ,
+the first
+.Fa n
+bytes pointed to by
+.Fa s
+need to form an entire multibyte character.
+Otherwise, this function causes an error.
+.Pp
+Calling any other functions in
+.Lb libc
+never changes the internal state of
+.Fn mbtowc ,
+except for calling
+.Xr setlocale 3
+with changing the
+.Dv LC_CTYPE
+category of the current locale.
+Such
+.Xr setlocale 3
+call causes the internal state of this function to be indeterminate.
+.Pp
+The behaviour of
+.Fn mbtowc
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.Pp
+There are special cases:
+.Bl -tag -width 012345678901
+.It s == NULL
+.Fn mbtowc
+initializes its own internal state to an initial state, and
+determines whether the current encoding is state-dependent.
+This function returns 0 if the encoding is state-independent,
+otherwise non-zero.
+In this case,
+.Fa pwc
+is completely ignored.
+.It pwc == NULL
+.Fn mbtowc
+executes the conversion as if
+.Fa pwc
+is non-NULL, but a result of the conversion is discarded.
+.It n == 0
+In this case,
+the first
+.Fa n
+bytes of the array pointed to by
+.Fa s
+never form a complete character.
+Thus, the
+.Fn mbtowc
+always fails.
+.El
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+Normally, the
+.Fn mbtowc
+returns:
+.Bl -tag -width 012345678901
+.It 0
+.Fa s
+points to a nul byte
+.Pq Sq \e0 .
+.It positive
+Number of bytes for the valid multibyte character pointed to by
+.Fa s .
+There are no cases that the value returned is greater than
+the value of the
+.Dv MB_CUR_MAX
+macro.
+.It -1
+.Fa s
+points to an invalid or an incomplete multibyte character.
+The
+.Fn mbtowc
+also sets
+.Va errno
+to indicate the error.
+.El
+.Pp
+When
+.Fa s
+is equal to
+.Dv NULL ,
+.Fn mbtowc
+returns:
+.Bl -tag -width 0123456789
+.It 0
+The current encoding is state-independent.
+.It non-zero
+The current encoding is state-dependent.
+.El
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+.Fn mbtowc
+may cause an error in the following case:
+.Bl -tag -width Er
+.It Bq Er EILSEQ
+.Fa s
+points to an invalid or incomplete multibyte character.
+.El
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr mblen 3 ,
+.Xr mbrtowc 3 ,
+.Xr setlocale 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn mbtowc
+function conforms to
+.St -ansiC .
+The restrict qualifier is added at
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/locale/multibyte.h b/lib/nbsd_libc/locale/multibyte.h
new file mode 100644 (file)
index 0000000..2b28aec
--- /dev/null
@@ -0,0 +1,126 @@
+/*     $NetBSD: multibyte.h,v 1.5 2009/01/11 02:46:28 christos Exp $   */
+
+/*-
+ * Copyright (c)2002 Citrus Project,
+ * 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.
+ */
+
+#ifndef _MULTIBYTE_H_
+#define _MULTIBYTE_H_
+
+/* mbstate_t private */
+
+#ifdef _BSD_MBSTATE_T_
+typedef        _BSD_MBSTATE_T_ mbstate_t;
+#undef _BSD_MBSTATE_T_
+#endif
+
+typedef struct _RuneStatePriv {
+       _RuneLocale     *__runelocale;
+       char            __private __attribute__((__aligned__));
+} _RuneStatePriv;
+
+typedef union _RuneState {
+       mbstate_t               __pad;
+       struct _RuneStatePriv   __priv;
+#define rs_runelocale          __priv.__runelocale
+#define rs_private             __priv.__private
+} _RuneState;
+#define _PRIVSIZE      (sizeof(mbstate_t)-offsetof(_RuneStatePriv, __private))
+
+
+/* */
+
+static __inline _citrus_ctype_t
+_to_cur_ctype(void)
+{
+       return (_CurrentRuneLocale->rl_citrus_ctype);
+}
+
+static __inline _RuneState *
+_ps_to_runestate(mbstate_t *ps)
+{
+       return (_RuneState *)(void *)ps;
+}
+
+static __inline _RuneState const *
+_ps_to_runestate_const(mbstate_t const *ps)
+{
+       return (_RuneState const *)(void const *)ps;
+}
+
+static __inline _RuneLocale *
+_ps_to_runelocale(mbstate_t const *ps)
+{
+       return _ps_to_runestate_const(ps)->rs_runelocale;
+}
+
+static __inline _citrus_ctype_t
+_ps_to_ctype(mbstate_t const *ps)
+{
+       if (!ps)
+               return _to_cur_ctype();
+
+       _DIAGASSERT(_ps_to_runelocale(ps) != NULL);
+
+       return _ps_to_runelocale(ps)->rl_citrus_ctype;
+}
+
+static __inline void *
+_ps_to_private(mbstate_t *ps)
+{
+       if (ps == NULL)
+               return NULL;
+       return (void *)&_ps_to_runestate(ps)->rs_private;
+}
+
+static __inline void const *
+_ps_to_private_const(mbstate_t const *ps)
+{
+       if (ps == NULL)
+               return NULL;
+       return (void const *)&_ps_to_runestate_const(ps)->rs_private;
+}
+
+static __inline void
+_init_ps(_RuneLocale *rl, mbstate_t *ps)
+{
+       size_t dum;
+       _ps_to_runestate(ps)->rs_runelocale = rl;
+       _citrus_ctype_mbrtowc(rl->rl_citrus_ctype, NULL, NULL, 0,
+                             _ps_to_private(ps), &dum);
+}
+
+static __inline void
+_fixup_ps(_RuneLocale *rl, mbstate_t *ps, int forceinit)
+{
+       /* for future multi-locale facility */
+       _DIAGASSERT(rl != NULL);
+
+       if (ps != NULL && (_ps_to_runelocale(ps) == NULL || forceinit)) {
+               _init_ps(rl, ps);
+       }
+}
+
+#endif /*_MULTIBYTE_H_*/
diff --git a/lib/nbsd_libc/locale/multibyte_amd1.c b/lib/nbsd_libc/locale/multibyte_amd1.c
new file mode 100644 (file)
index 0000000..8c74ddf
--- /dev/null
@@ -0,0 +1,183 @@
+/*     $NetBSD: multibyte_amd1.c,v 1.9 2010/06/13 04:14:57 tnozaki Exp $       */
+
+/*-
+ * Copyright (c)2002, 2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: multibyte_amd1.c,v 1.9 2010/06/13 04:14:57 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <errno.h>
+#include <langinfo.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <wchar.h>
+
+#include "setlocale_local.h"
+
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "runetype_local.h"
+#include "multibyte.h"
+
+#define _RUNE_LOCALE() \
+    ((_RuneLocale *)(*_current_locale())->part_impl[(size_t)LC_CTYPE])
+
+#define _CITRUS_CTYPE() \
+    (_RUNE_LOCALE()->rl_citrus_ctype)
+
+size_t
+mbrlen(const char *s, size_t n, mbstate_t *ps)
+{
+       size_t ret;
+       int err0;
+
+       _fixup_ps(_RUNE_LOCALE(), ps, s == NULL);
+
+       err0 = _citrus_ctype_mbrlen(_ps_to_ctype(ps), s, n,
+                                    _ps_to_private(ps), &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
+
+int
+mbsinit(const mbstate_t *ps)
+{
+       int ret;
+       int err0;
+       _RuneLocale *rl;
+
+       if (ps == NULL)
+               return 1;
+
+       if (_ps_to_runelocale(ps) == NULL)
+               rl = _RUNE_LOCALE();
+       else
+               rl = _ps_to_runelocale(ps);
+
+       /* mbsinit should cause no error... */
+       err0 = _citrus_ctype_mbsinit(rl->rl_citrus_ctype,
+                                     _ps_to_private_const(ps), &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
+
+size_t
+mbrtowc(wchar_t *pwc, const char *s, size_t n, mbstate_t *ps)
+{
+       size_t ret;
+       int err0;
+
+       _fixup_ps(_RUNE_LOCALE(), ps, s == NULL);
+
+       err0 = _citrus_ctype_mbrtowc(_ps_to_ctype(ps), pwc, s, n,
+                                     _ps_to_private(ps), &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
+
+size_t
+mbsrtowcs(wchar_t *pwcs, const char **s, size_t n, mbstate_t *ps)
+{
+       size_t ret;
+       int err0;
+
+       _fixup_ps(_RUNE_LOCALE(), ps, s == NULL);
+
+       err0 = _citrus_ctype_mbsrtowcs(_ps_to_ctype(ps), pwcs, s, n,
+                                       _ps_to_private(ps), &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
+
+size_t
+wcrtomb(char *s, wchar_t wc, mbstate_t *ps)
+{
+       size_t ret;
+       int err0;
+
+       _fixup_ps(_RUNE_LOCALE(), ps, s == NULL);
+
+       err0 = _citrus_ctype_wcrtomb(_ps_to_ctype(ps), s, wc,
+                                      _ps_to_private(ps), &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
+
+size_t
+wcsrtombs(char *s, const wchar_t **ppwcs, size_t n, mbstate_t *ps)
+{
+       size_t ret;
+       int err0;
+
+       _fixup_ps(_RUNE_LOCALE(), ps, s == NULL);
+
+       err0 = _citrus_ctype_wcsrtombs(_ps_to_ctype(ps), s, ppwcs, n,
+                                       _ps_to_private(ps), &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
+
+wint_t
+btowc(int c)
+{
+       wint_t ret;
+       int err0;
+
+       err0 = _citrus_ctype_btowc(_CITRUS_CTYPE(), c, &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
+
+int
+wctob(wint_t wc)
+{
+       int ret;
+       int err0;
+
+       err0 = _citrus_ctype_wctob(_CITRUS_CTYPE(), wc, &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
diff --git a/lib/nbsd_libc/locale/multibyte_c90.c b/lib/nbsd_libc/locale/multibyte_c90.c
new file mode 100644 (file)
index 0000000..6efa35b
--- /dev/null
@@ -0,0 +1,118 @@
+/*     $NetBSD: multibyte_c90.c,v 1.8 2010/06/13 04:14:57 tnozaki Exp $        */
+
+/*-
+ * Copyright (c)2002, 2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: multibyte_c90.c,v 1.8 2010/06/13 04:14:57 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <errno.h>
+#include <langinfo.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stdlib.h>
+#include <wchar.h>
+
+#include "setlocale_local.h"
+
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "runetype_local.h"
+
+#define _RUNE_LOCALE() \
+    ((_RuneLocale *)(*_current_locale())->part_impl[(size_t)LC_CTYPE])
+
+#define _CITRUS_CTYPE() \
+    (_RUNE_LOCALE()->rl_citrus_ctype)
+
+int
+mblen(const char *s, size_t n)
+{
+       int ret;
+       int err0;
+
+       err0 = _citrus_ctype_mblen(_CITRUS_CTYPE(), s, n, &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
+
+size_t
+mbstowcs(wchar_t *pwcs, const char *s, size_t n)
+{
+       size_t ret;
+       int err0;
+
+       err0 = _citrus_ctype_mbstowcs(_CITRUS_CTYPE(), pwcs, s, n, &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
+
+int
+mbtowc(wchar_t *pw, const char *s, size_t n)
+{
+       int ret;
+       int err0;
+
+       err0 = _citrus_ctype_mbtowc(_CITRUS_CTYPE(), pw, s, n, &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
+
+size_t
+wcstombs(char *s, const wchar_t *wcs, size_t n)
+{
+       size_t ret;
+       int err0;
+
+       err0 = _citrus_ctype_wcstombs(_CITRUS_CTYPE(), s, wcs, n, &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
+
+int
+wctomb(char *s, wchar_t wc)
+{
+       int ret;
+       int err0;
+
+       err0 = _citrus_ctype_wctomb(_CITRUS_CTYPE(), s, wc, &ret);
+       if (err0)
+               errno = err0;
+
+       return ret;
+}
diff --git a/lib/nbsd_libc/locale/multibyte_sb.c b/lib/nbsd_libc/locale/multibyte_sb.c
new file mode 100644 (file)
index 0000000..53b3fc4
--- /dev/null
@@ -0,0 +1,265 @@
+/*     $NetBSD: multibyte_sb.c,v 1.5 2004/07/21 20:27:46 tshiozak Exp $        */
+
+/*
+ * Copyright (c) 1991 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "from: @(#)multibyte.c   5.1 (Berkeley) 2/18/91";
+#else
+__RCSID("$NetBSD: multibyte_sb.c,v 1.5 2004/07/21 20:27:46 tshiozak Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <wchar.h>
+
+/*
+ * Stub multibyte character functions.
+ * This cheezy implementation is fixed to the native single-byte
+ * character set.
+ */
+
+/*ARGSUSED*/
+int
+mbsinit(ps)
+       const mbstate_t *ps;
+{
+
+       return 1;
+}
+
+/*ARGSUSED*/
+size_t
+mbrlen(s, n, ps)
+       const char *s;
+       size_t n;
+       mbstate_t *ps;
+{
+
+       /* ps appears to be unused */
+
+       if (s == NULL || *s == '\0')
+               return 0;
+       if (n == 0)
+               return (size_t)-1;
+       return 1;
+}
+
+int
+mblen(s, n)
+       const char *s;
+       size_t n;
+{
+
+       /* s may be NULL */
+
+       return mbrlen(s, n, NULL);
+}
+
+/*ARGSUSED*/
+size_t
+mbrtowc(pwc, s, n, ps)
+       wchar_t *pwc;
+       const char *s;
+       size_t n;
+       mbstate_t *ps;
+{
+
+       /* pwc may be NULL */
+       /* s may be NULL */
+       /* ps appears to be unused */
+
+       if (s == NULL)
+               return 0;
+       if (n == 0)
+               return (size_t)-1;
+       if (pwc)
+               *pwc = (wchar_t) *s;
+       return (*s != '\0');
+}
+
+int
+mbtowc(pwc, s, n)
+       wchar_t *pwc;
+       const char *s;
+       size_t n;
+{
+
+       /* pwc may be NULL */
+       /* s may be NULL */
+
+       return mbrtowc(pwc, s, n, NULL);
+}
+
+/*ARGSUSED*/
+size_t
+wcrtomb(s, wchar, ps)
+       char *s;
+       wchar_t wchar;
+       mbstate_t *ps;
+{
+
+       /* s may be NULL */
+       /* ps appears to be unused */
+
+       if (s == NULL)
+               return 0;
+
+       *s = (char) wchar;
+       return 1;
+}
+
+int
+wctomb(s, wchar)
+       char *s;
+       wchar_t wchar;
+{
+
+       /* s may be NULL */
+
+       return wcrtomb(s, wchar, NULL);
+}
+
+/*ARGSUSED*/
+size_t
+mbsrtowcs(pwcs, s, n, ps)
+       wchar_t *pwcs;
+       const char **s;
+       size_t n;
+       mbstate_t *ps;
+{
+       int count = 0;
+
+       /* pwcs may be NULL */
+       /* s may be NULL */
+       /* ps appears to be unused */
+
+       if (!s || !*s)
+               return 0;
+
+       if (n != 0) {
+               if (pwcs != NULL) {
+                       do {
+                               if ((*pwcs++ = (wchar_t) *(*s)++) == 0)
+                                       break;
+                               count++;
+                       } while (--n != 0);
+               } else {
+                       do {
+                               if (((wchar_t)*(*s)++) == 0)
+                                       break;
+                               count++;
+                       } while (--n != 0);
+               }
+       }
+
+       return count;
+}
+
+size_t
+mbstowcs(pwcs, s, n)
+       wchar_t *pwcs;
+       const char *s;
+       size_t n;
+{
+
+       /* pwcs may be NULL */
+       /* s may be NULL */
+
+       return mbsrtowcs(pwcs, &s, n, NULL);
+}
+
+/*ARGSUSED*/
+size_t
+wcsrtombs(s, pwcs, n, ps)
+       char *s;
+       const wchar_t **pwcs;
+       size_t n;
+       mbstate_t *ps;
+{
+       int count = 0;
+
+       /* s may be NULL */
+       /* pwcs may be NULL */
+       /* ps appears to be unused */
+
+       if (pwcs == NULL || *pwcs == NULL)
+               return (0);
+
+       if (s == NULL) {
+               while (*(*pwcs)++ != 0)
+                       count++;
+               return(count);
+       }
+
+       if (n != 0) {
+               do {
+                       if ((*s++ = (char) *(*pwcs)++) == 0)
+                               break;
+                       count++;
+               } while (--n != 0);
+       }
+
+       return count;
+}
+
+size_t
+wcstombs(s, pwcs, n)
+       char *s;
+       const wchar_t *pwcs;
+       size_t n;
+{
+
+       /* s may be NULL */
+       /* pwcs may be NULL */
+
+       return wcsrtombs(s, &pwcs, n, NULL);
+}
+
+wint_t
+btowc(c)
+       int c;
+{
+       if (c == EOF || c & ~0xFF)
+               return WEOF;
+       return (wint_t)c;
+}
+
+int
+wctob(c)
+       wint_t c;
+{
+       if (c == WEOF || c & ~0xFF)
+               return EOF;
+       return (int)c;
+}
diff --git a/lib/nbsd_libc/locale/nb_lc_messages_misc.h b/lib/nbsd_libc/locale/nb_lc_messages_misc.h
new file mode 100644 (file)
index 0000000..a2ddc82
--- /dev/null
@@ -0,0 +1,66 @@
+/* $NetBSD: nb_lc_messages_misc.h,v 1.3 2010/03/27 15:25:22 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _NB_LC_MESSAGES_MISC_H_
+#define _NB_LC_MESSAGES_MISC_H_
+
+/*
+ * macro required by nb_lc_template(_decl).h
+ */
+#define _CATEGORY_TYPE         _MessagesLocale
+
+static __inline void
+_PREFIX(build_cache)(struct _locale_cache_t * __restrict cache,
+    _MessagesLocale * __restrict data)
+{
+       _DIAGASSERT(cache != NULL);
+       _DIAGASSERT(cache->items != NULL);
+       _DIAGASSERT(data != NULL);
+
+       cache->items[(size_t)YESSTR ] = data->yesstr;
+       cache->items[(size_t)YESEXPR] = data->yesexpr;
+       cache->items[(size_t)NOSTR  ] = data->nostr;
+       cache->items[(size_t)NOEXPR ] = data->noexpr;
+}
+
+static __inline void
+_PREFIX(fixup)(_MessagesLocale *data)
+{
+       _DIAGASSERT(data != NULL);
+
+       _CurrentMessagesLocale = data;
+}
+
+/*
+ * macro required by nb_lc_template.h
+ */
+#define _CATEGORY_ID           LC_MESSAGES
+#define _CATEGORY_NAME         "LC_MESSAGES"
+#define _CATEGORY_DEFAULT      _DefaultMessagesLocale
+
+#endif /*_NB_LC_MESSAGES_MISC_H_*/
diff --git a/lib/nbsd_libc/locale/nb_lc_monetary_misc.h b/lib/nbsd_libc/locale/nb_lc_monetary_misc.h
new file mode 100644 (file)
index 0000000..3b13ad3
--- /dev/null
@@ -0,0 +1,90 @@
+/* $NetBSD: nb_lc_monetary_misc.h,v 1.3 2010/03/27 15:25:22 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _NB_LC_MONETARY_MISC_H_
+#define _NB_LC_MONETARY_MISC_H_
+
+/*
+ * macro required by nb_lc_template(_decl).h
+ */
+#define _CATEGORY_TYPE         _MonetaryLocale
+
+static __inline void
+_PREFIX(build_cache)(struct _locale_cache_t * __restrict cache,
+    _MonetaryLocale * __restrict data)
+{
+       struct lconv *ldata;
+
+       _DIAGASSERT(cache != NULL);
+       _DIAGASSERT(cache->ldata != NULL);
+       _DIAGASSERT(cache->items != NULL);
+       _DIAGASSERT(data != NULL);
+
+       ldata = cache->ldata;
+       ldata->int_curr_symbol   = __UNCONST(data->int_curr_symbol);
+       ldata->currency_symbol   = __UNCONST(data->currency_symbol);
+       ldata->mon_decimal_point = __UNCONST(data->mon_decimal_point);
+       ldata->mon_thousands_sep = __UNCONST(data->mon_thousands_sep);
+       ldata->mon_grouping      = __UNCONST(data->mon_grouping);
+       ldata->positive_sign     = __UNCONST(data->positive_sign);
+       ldata->negative_sign     = __UNCONST(data->negative_sign);
+
+       ldata->int_frac_digits    = data->int_frac_digits;
+       ldata->frac_digits        = data->frac_digits;
+       ldata->p_cs_precedes      = data->p_cs_precedes;
+       ldata->p_sep_by_space     = data->p_sep_by_space;
+       ldata->n_cs_precedes      = data->n_cs_precedes;
+       ldata->n_sep_by_space     = data->n_sep_by_space;
+       ldata->p_sign_posn        = data->p_sign_posn;
+       ldata->n_sign_posn        = data->n_sign_posn;
+       ldata->int_p_cs_precedes  = data->int_p_cs_precedes;
+       ldata->int_n_cs_precedes  = data->int_n_cs_precedes;
+       ldata->int_p_sep_by_space = data-> int_p_sep_by_space;
+       ldata->int_n_sep_by_space = data->int_n_sep_by_space;
+       ldata->int_p_sign_posn    = data->int_p_sign_posn;
+       ldata->int_n_sign_posn    = data->int_n_sign_posn;
+
+       cache->items[(size_t)CRNCYSTR] = NULL; /* NOT IMPLEMENTED YET */
+}
+
+static __inline void
+_PREFIX(fixup)(_MonetaryLocale *data)
+{
+       _DIAGASSERT(data != NULL);
+
+       _CurrentMonetaryLocale = data;
+}
+
+/*
+ * macro required by nb_lc_template.h
+ */
+#define _CATEGORY_ID           LC_MONETARY
+#define _CATEGORY_NAME         "LC_MONETARY"
+#define _CATEGORY_DEFAULT      _DefaultMonetaryLocale
+
+#endif /*_RUNE_LC_MONETARY_MISC_H_*/
diff --git a/lib/nbsd_libc/locale/nb_lc_numeric_misc.h b/lib/nbsd_libc/locale/nb_lc_numeric_misc.h
new file mode 100644 (file)
index 0000000..4336fc1
--- /dev/null
@@ -0,0 +1,72 @@
+/* $NetBSD: nb_lc_numeric_misc.h,v 1.3 2010/03/27 15:25:22 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _NB_LC_NUMERIC_MISC_H_
+#define _NB_LC_NUMERIC_MISC_H_
+
+/*
+ * macro required by nb_lc_template(_decl).h
+ */
+#define _CATEGORY_TYPE         _NumericLocale
+
+static __inline void
+_PREFIX(build_cache)(struct _locale_cache_t * __restrict cache,
+    _NumericLocale * __restrict data)
+{
+       struct lconv *ldata;
+
+       _DIAGASSERT(cache != NULL);
+       _DIAGASSERT(cache->ldata != NULL);
+       _DIAGASSERT(cache->items != NULL);
+       _DIAGASSERT(data != NULL);
+
+       ldata = cache->ldata;
+       ldata->decimal_point = __UNCONST(data->decimal_point);
+       ldata->thousands_sep = __UNCONST(data->thousands_sep);
+       ldata->grouping      = __UNCONST(data->grouping);
+
+       cache->items[(size_t)RADIXCHAR] = data->decimal_point;
+       cache->items[(size_t)THOUSEP  ] = data->thousands_sep;
+}
+
+static __inline void
+_PREFIX(fixup)(_NumericLocale *data)
+{
+       _DIAGASSERT(data != NULL);
+
+       _CurrentNumericLocale = data;
+}
+
+/*
+ * macro required by nb_lc_template.h
+ */
+#define _CATEGORY_ID           LC_NUMERIC
+#define _CATEGORY_NAME         "LC_NUMERIC"
+#define _CATEGORY_DEFAULT      _DefaultNumericLocale
+
+#endif /*_NB_LC_NUMERIC_MISC_H_*/
diff --git a/lib/nbsd_libc/locale/nb_lc_template.h b/lib/nbsd_libc/locale/nb_lc_template.h
new file mode 100644 (file)
index 0000000..8721dca
--- /dev/null
@@ -0,0 +1,248 @@
+/* $NetBSD: nb_lc_template.h,v 1.3 2010/05/22 13:15:59 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)1999, 2008 Citrus Project,
+ * 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.
+ */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Paul Kranenburg.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Borman at Krystal Technologies.
+ *
+ * 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. 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.
+ */
+
+#ifndef _NB_LC_TEMPLATE_H_
+#define _NB_LC_TEMPLATE_H_
+
+#define _nb_part_t             _PREFIX(part_t)
+#define _nb_part_cache         _PREFIX(part_cache)
+#define _nb_default_c          _PREFIX(default_c)
+#define _nb_default_posix      _PREFIX(default_posix)
+#define _nb_mutex              _PREFIX(mutex)
+
+typedef struct _nb_part_t {
+       char name[_LOCALENAME_LEN_MAX];
+       _CATEGORY_TYPE *impl;
+       SIMPLEQ_ENTRY(_nb_part_t) entry;
+} _nb_part_t;
+
+static SIMPLEQ_HEAD(, _nb_part_t) _nb_part_cache =
+    SIMPLEQ_HEAD_INITIALIZER(_nb_part_cache);
+
+static const _nb_part_t _nb_default_c = {
+    _C_LOCALE,
+    __UNCONST(&_CATEGORY_DEFAULT),
+    { NULL },
+};
+
+static const _nb_part_t _nb_default_posix = {
+    _POSIX_LOCALE,
+    __UNCONST(&_CATEGORY_DEFAULT),
+    { NULL },
+};
+
+#ifdef _REENTRANT
+static mutex_t _nb_mutex = MUTEX_INITIALIZER;
+#endif
+
+static int
+_PREFIX(load_sub)(const char * __restrict name, const char * __restrict real,
+    _nb_part_t ** __restrict part, int force)
+{
+       _nb_part_t *p, *q;
+       int ret;
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(part != NULL);
+
+       if (!strcmp(_C_LOCALE, name)) {
+               p = __UNCONST(&_nb_default_c);
+       } else if (!strcmp(_POSIX_LOCALE, name)) {
+               p = __UNCONST(&_nb_default_posix);
+       } else {
+               SIMPLEQ_FOREACH(p, &_nb_part_cache, entry) {
+                       if (!strcmp((const char *)&p->name[0], name))
+                               goto found;
+               }
+               p = malloc(sizeof(*p));
+               if (p == NULL)
+                       return ENOMEM;
+               if (force) {
+                       p->impl = __UNCONST(&_CATEGORY_DEFAULT);
+               } else {
+                       _DIAGASSERT(_PathLocale != NULL);
+                       ret = _PREFIX(create_impl)((const char *)_PathLocale,
+                           name, &p->impl);
+                       if (ret) {
+                               free(p);
+                               return ret;
+                       }
+               }
+               strlcpy(&p->name[0], name, sizeof(p->name));
+               SIMPLEQ_INSERT_TAIL(&_nb_part_cache, p, entry);
+       }
+found:
+       if (real != NULL) {
+               q = malloc(sizeof(*q));
+               if (q == NULL)
+                       return ENOMEM;
+               strlcpy(&q->name[0], real, sizeof(p->name));
+               q->impl = p->impl;
+               SIMPLEQ_INSERT_TAIL(&_nb_part_cache, q, entry);
+               p = q;
+       }
+       *part = p;
+       return 0;
+}
+
+static __inline int
+_PREFIX(load)(const char * __restrict name,
+    _nb_part_t ** __restrict part)
+{
+       int ret, force;
+       char path[PATH_MAX + 1], loccat[PATH_MAX + 1], buf[PATH_MAX + 1];
+       const char *aliaspath, *alias;
+
+#define _LOAD_SUB_ALIAS(key)                                           \
+do {                                                                   \
+       alias = __unaliasname(aliaspath, key, &buf[0], sizeof(buf));    \
+       if (alias != NULL) {                                            \
+               ret = (force = !__isforcemapping(alias))                \
+                   ? _PREFIX(load_sub)(name, NULL, part, force)        \
+                   : _PREFIX(load_sub)(alias, name, part, force);      \
+               _DIAGASSERT(!ret || !force);                            \
+               goto done;                                              \
+       }                                                               \
+} while (/*CONSTCOND*/0)
+
+       /* (1) non-aliased file */
+       mutex_lock(&_nb_mutex);
+       ret = _PREFIX(load_sub)(name, NULL, part, 0);
+       if (ret != ENOENT)
+               goto done;
+
+       /* (2) lookup locname/catname type alias */
+       _DIAGASSERT(_PathLocale != NULL);
+       snprintf(&path[0], sizeof(path),
+           "%s/" _LOCALE_ALIAS_NAME, _PathLocale);
+       aliaspath = (const char *)&path[0];
+       snprintf(&loccat[0], sizeof(loccat),
+           "%s/" _CATEGORY_NAME, name);
+       _LOAD_SUB_ALIAS((const char *)&loccat[0]);
+
+       /* (3) lookup locname type alias */
+       _LOAD_SUB_ALIAS(name);
+
+done:
+       mutex_unlock(&_nb_mutex);
+       return ret;
+}
+
+static const char *
+_PREFIX(setlocale)(const char * __restrict name,
+    struct _locale_impl_t * __restrict locale)
+{
+       _nb_part_t *part;
+
+       /* name may be NULL */
+       _DIAGASSERT(locale != NULL);
+
+       if (name != NULL) {
+               if (*name == '\0')
+                       name = _get_locale_env(_CATEGORY_NAME);
+               _DIAGASSERT(name != NULL);
+               _DIAGASSERT(locale->part_name[(size_t)_CATEGORY_ID] != NULL);
+               if (strcmp(name, locale->part_name[(size_t)_CATEGORY_ID])) {
+                       if (_PREFIX(load)(name, &part))
+                               return NULL;
+                       locale->part_name[(size_t)_CATEGORY_ID]
+                           = &part->name[0];
+                       locale->part_impl[(size_t)_CATEGORY_ID]
+                           = part->impl;
+                       _PREFIX(build_cache)(locale->cache, part->impl);
+                       if (locale == &_global_locale)
+                               _PREFIX(fixup)(part->impl);
+               }
+       }
+       return locale->part_name[(size_t)_CATEGORY_ID];
+}
+
+#include "generic_lc_template.h"
+
+#endif /*_NB_LC_TEMPLATE_H_*/
diff --git a/lib/nbsd_libc/locale/nb_lc_template_decl.h b/lib/nbsd_libc/locale/nb_lc_template_decl.h
new file mode 100644 (file)
index 0000000..f87ef0e
--- /dev/null
@@ -0,0 +1,45 @@
+/* $NetBSD: nb_lc_template_decl.h,v 1.2 2009/01/11 02:46:29 christos Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _NB_LC_TEMPLATE_DECL_H_
+#define _NB_LC_TEMPLATE_DECL_H_
+
+#include "generic_lc_template_decl.h"
+
+static __inline int
+_PREFIX(create_impl)(const char * __restrict,
+    const char * __restrict, _CATEGORY_TYPE ** __restrict);
+
+static __inline void
+_PREFIX(build_cache)(struct _locale_cache_t * __restrict,
+    _CATEGORY_TYPE * __restrict);
+
+static __inline void
+_PREFIX(fixup)(_CATEGORY_TYPE *);
+
+#endif /*_NB_LC_TEMPLATE_DECL_H_*/
diff --git a/lib/nbsd_libc/locale/nb_lc_time_misc.h b/lib/nbsd_libc/locale/nb_lc_time_misc.h
new file mode 100644 (file)
index 0000000..2f426dd
--- /dev/null
@@ -0,0 +1,92 @@
+/* $NetBSD: nb_lc_time_misc.h,v 1.3 2010/03/27 15:25:22 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _NB_LC_TIME_MISC_H_
+#define _NB_LC_TIME_MISC_H_
+
+/*
+ * macro required by nb_lc_template(_decl).h
+ */
+#define _CATEGORY_TYPE         _TimeLocale
+
+#define ABDAY_IDX(idx) ((size_t)idx - (size_t)ABDAY_1)
+#define DAY_IDX(idx)   ((size_t)idx - (size_t)DAY_1)
+#define ABMON_IDX(idx) ((size_t)idx - (size_t)ABMON_1)
+#define MON_IDX(idx)   ((size_t)idx - (size_t)MON_1)
+#define AM_PM_IDX(idx) ((size_t)idx - (size_t)AM_STR)
+
+static __inline void
+/*ARGSUSED*/
+_PREFIX(build_cache)(struct _locale_cache_t * __restrict cache,
+    _TimeLocale * __restrict data)
+{
+       size_t i;
+
+       _DIAGASSERT(cache != NULL);
+       _DIAGASSERT(cache->items != NULL);
+       _DIAGASSERT(data != NULL);
+
+        for (i = (size_t)ABDAY_1; i <= ABDAY_7;  ++i)
+               cache->items[i] = data->abday[ABDAY_IDX(i)];
+        for (i = (size_t)DAY_1;   i <= DAY_7;    ++i)
+               cache->items[i] = data->day[DAY_IDX(i)];
+        for (i = (size_t)ABMON_1; i <= ABMON_12; ++i)
+               cache->items[i] = data->abmon[ABMON_IDX(i)];
+        for (i = (size_t)MON_1;   i <= MON_12;   ++i)
+               cache->items[i] = data->mon[MON_IDX(i)];
+        for (i = (size_t)AM_STR;  i <= PM_STR;   ++i)
+               cache->items[i] = data->am_pm[AM_PM_IDX(i)];
+       cache->items[(size_t)D_T_FMT    ] = data->d_t_fmt;
+       cache->items[(size_t)D_FMT      ] = data->d_fmt;
+       cache->items[(size_t)T_FMT      ] = data->t_fmt;
+       cache->items[(size_t)T_FMT_AMPM ] = data->t_fmt_ampm;
+
+       /* NOT IMPLEMENTED YET */
+       cache->items[(size_t)ERA        ] = NULL;
+       cache->items[(size_t)ERA_D_FMT  ] = NULL;
+       cache->items[(size_t)ERA_D_T_FMT] = NULL;
+       cache->items[(size_t)ERA_T_FMT  ] = NULL;
+       cache->items[(size_t)ALT_DIGITS ] = NULL;
+}
+
+static __inline void
+_PREFIX(fixup)(_TimeLocale *data)
+{
+       _DIAGASSERT(data != NULL);
+
+       _CurrentTimeLocale = data;
+}
+
+/*
+ * macro required by nb_lc_template.h
+ */
+#define _CATEGORY_ID           LC_TIME
+#define _CATEGORY_NAME         "LC_TIME"
+#define _CATEGORY_DEFAULT      _DefaultTimeLocale
+
+#endif /*_NB_LC_TIME_MISC_H_*/
diff --git a/lib/nbsd_libc/locale/nl_langinfo.3 b/lib/nbsd_libc/locale/nl_langinfo.3
new file mode 100644 (file)
index 0000000..0f9b25d
--- /dev/null
@@ -0,0 +1,148 @@
+.\"    $NetBSD: nl_langinfo.3,v 1.19 2010/03/22 19:30:54 joerg Exp $
+.\"
+.\" Written by J.T. Conklin <jtc@NetBSD.org>.
+.\" Public domain.
+.\"
+.Dd February 12, 2003
+.Dt NL_LANGINFO 3
+.Os
+.Sh NAME
+.Nm nl_langinfo
+.Nd get locale information
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In langinfo.h
+.Ft char *
+.Fn nl_langinfo "nl_item item"
+.Sh DESCRIPTION
+The
+.Fn nl_langinfo
+function returns a pointer to a string containing information
+set by the program's locale.
+.Pp
+The names and values of
+.Fa item
+are defined in
+.In langinfo.h .
+The entries under Category indicate in which
+.Xr setlocale 3
+category each item is defined.
+.Bl -column ERA_D_T_FMT LC_MESSAGES
+.It Sy Constant Ta Sy Category Ta Sy Meaning
+.It CODESET    LC_CTYPE        Codeset name
+.It D_T_FMT    LC_TIME String for formatting date and time
+.It D_FMT      LC_TIME Date format string
+.It T_FMT      LC_TIME Time format string
+.It T_FMT_AMPM LC_TIME A.M. or P.M. time format string
+.It AM_STR     LC_TIME Ante-meridiem affix
+.It PM_STR     LC_TIME Post-meridiem affix
+.It DAY_1      LC_TIME Name of the first day of the week (e.g.: Sunday)
+.It DAY_2      LC_TIME Name of the second day of the week (e.g.: Monday)
+.It DAY_3      LC_TIME Name of the third day of the week (e.g.: Tuesday)
+.It DAY_4      LC_TIME Name of the fourth day of the week (e.g.: Wednesday)
+.It DAY_5      LC_TIME Name of the fifth day of the week (e.g.: Thursday)
+.It DAY_6      LC_TIME Name of the sixth day of the week (e.g.: Friday)
+.It DAY_7      LC_TIME Name of the seventh day of the week (e.g.: Saturday)
+.It ABDAY_1    LC_TIME Abbreviated name of the first day of the week
+.It ABDAY_2    LC_TIME Abbreviated name of the second day of the week
+.It ABDAY_3    LC_TIME Abbreviated name of the third day of the week
+.It ABDAY_4    LC_TIME Abbreviated name of the fourth day of the week
+.It ABDAY_5    LC_TIME Abbreviated name of the fifth day of the week
+.It ABDAY_6    LC_TIME Abbreviated name of the sixth day of the week
+.It ABDAY_7    LC_TIME Abbreviated name of the seventh day of the week
+.It MON_1      LC_TIME Name of the first month of the year
+.It MON_2      LC_TIME Name of the second month
+.It MON_3      LC_TIME Name of the third month
+.It MON_4      LC_TIME Name of the fourth month
+.It MON_5      LC_TIME Name of the fifth month
+.It MON_6      LC_TIME Name of the sixth month
+.It MON_7      LC_TIME Name of the seventh month
+.It MON_8      LC_TIME Name of the eighth month
+.It MON_9      LC_TIME Name of the ninth month
+.It MON_10     LC_TIME Name of the tenth month
+.It MON_11     LC_TIME Name of the eleventh month
+.It MON_12     LC_TIME Name of the twelfth month
+.It ABMON_1    LC_TIME Abbreviated name of the first month
+.It ABMON_2    LC_TIME Abbreviated name of the second month
+.It ABMON_3    LC_TIME Abbreviated name of the third month
+.It ABMON_4    LC_TIME Abbreviated name of the fourth month
+.It ABMON_5    LC_TIME Abbreviated name of the fifth month
+.It ABMON_6    LC_TIME Abbreviated name of the sixth month
+.It ABMON_7    LC_TIME Abbreviated name of the seventh month
+.It ABMON_8    LC_TIME Abbreviated name of the eighth month
+.It ABMON_9    LC_TIME Abbreviated name of the ninth month
+.It ABMON_10   LC_TIME Abbreviated name of the tenth month
+.It ABMON_11   LC_TIME Abbreviated name of the eleventh month
+.It ABMON_12   LC_TIME Abbreviated name of the twelfth month
+.It ERA        LC_TIME Era description segments
+.It ERA_D_FMT  LC_TIME Era date format string
+.It ERA_D_T_FMT        LC_TIME Era date and time format string
+.It ERA_T_FMT  LC_TIME Era time format string
+.It ALT_DIGITS LC_TIME Alternative symbols for digits
+.It RADIXCHAR  LC_NUMERIC      Radix character
+.It THOUSEP    LC_NUMERIC      Separator for thousands
+.It YESEXPR    LC_MESSAGES     Affirmative response expression
+.It NOEXPR     LC_MESSAGES     Negative response expression
+.\".It CRNCYSTR        LC_MONETARY     Local currency symbol
+.El
+.Sh RETURN VALUES
+.Fn nl_langinfo
+returns a pointer to an empty string if
+.Fa item
+is invalid.
+.Sh EXAMPLES
+The following example uses
+.Fn nl_langinfo
+to obtain the date and time format for the current locale:
+.Pp
+.Bd -literal -offset indent
+#include \*[Lt]time.h\*[Gt]
+#include \*[Lt]langinfo.h\*[Gt]
+#include \*[Lt]locale.h\*[Gt]
+
+int main(void)
+{
+       char datestring[100];
+       struct tm *tm;
+       time_t t;
+       char *ptr;
+
+       t = time(NULL);
+       tm = localtime(\*[Am]t);
+       (void)setlocale(LC_ALL, "");
+       ptr = nl_langinfo(D_T_FMT);
+       strftime(datestring, sizeof(datestring), ptr, tm);
+       printf("%s\en", datestring);
+       return (0);
+}
+.Ed
+.\" .Pp
+.\" The following example uses
+.\" .Fn nl_langinfo
+.\" to obtain the setting of the currency symbol for the current locale:
+.\" .Pp
+.\" .Bd
+.\"    #include \*[Lt]langinfo.h\*[Gt]
+.\"    #include \*[Lt]locale.h\*[Gt]
+.\"    int main(void)
+.\"    {
+.\"            char *ptr;
+.\"            (void)setlocale(LC_ALL, "");
+.\"            ptr = nl_langinfo(CRNCYSTR);
+.\"            printf("%s", ptr);
+.\"    }
+.\" .Ed
+.Sh SEE ALSO
+.Xr setlocale 3 ,
+.Xr nls 7
+.Sh STANDARDS
+The
+.Fn nl_langinfo
+function conforms to
+.St -p1003.1-2001 .
+.Sh HISTORY
+The
+.Fn nl_langinfo
+function appeared in
+.Nx 1.0 .
diff --git a/lib/nbsd_libc/locale/nl_langinfo.c b/lib/nbsd_libc/locale/nl_langinfo.c
new file mode 100644 (file)
index 0000000..4f2dc60
--- /dev/null
@@ -0,0 +1,53 @@
+/* $NetBSD: nl_langinfo.c,v 1.15 2010/05/22 13:15:59 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nl_langinfo.c,v 1.15 2010/05/22 13:15:59 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <langinfo.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stdlib.h>
+
+#include "setlocale_local.h"
+
+char *
+nl_langinfo(nl_item item)
+{
+       const char *s;
+
+       s = NULL;
+       if (item >= D_T_FMT && item <= ALT_DIGITS)
+               s = _current_cache()->items[(size_t)item];
+       if (s == NULL)
+               s = "";
+       return __UNCONST(s);
+}
diff --git a/lib/nbsd_libc/locale/rune.c b/lib/nbsd_libc/locale/rune.c
new file mode 100644 (file)
index 0000000..2d423fc
--- /dev/null
@@ -0,0 +1,351 @@
+/* $NetBSD: rune.c,v 1.41 2010/11/30 15:25:05 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2010 Citrus Project,
+ * 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.
+ */
+
+#include <sys/endian.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#define __SETLOCALE_SOURCE__
+#include <locale.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <wchar.h>
+
+#include "setlocale_local.h"
+
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+
+#include "runetype_local.h"
+#include "bsdctype_local.h"
+
+#include "multibyte.h"
+
+#include "_wctype_local.h"
+#include "_wctrans_local.h"
+
+typedef struct {
+       _RuneLocale rl;
+       unsigned char   rlp_ctype_tab  [_CTYPE_NUM_CHARS + 1];
+       short           rlp_tolower_tab[_CTYPE_NUM_CHARS + 1];
+       short           rlp_toupper_tab[_CTYPE_NUM_CHARS + 1];
+       char            rlp_codeset[33]; /* XXX */
+} _RuneLocalePriv;
+
+static __inline void
+_rune_wctype_init(_RuneLocale *rl)
+{
+       memcpy(&rl->rl_wctype, &_DefaultRuneLocale.rl_wctype,
+           sizeof(rl->rl_wctype));
+}
+
+static __inline void
+_rune_wctrans_init(_RuneLocale *rl)
+{
+       rl->rl_wctrans[_WCTRANS_INDEX_LOWER].te_name   = "tolower";
+       rl->rl_wctrans[_WCTRANS_INDEX_LOWER].te_cached = &rl->rl_maplower[0];
+       rl->rl_wctrans[_WCTRANS_INDEX_LOWER].te_extmap = &rl->rl_maplower_ext;
+       rl->rl_wctrans[_WCTRANS_INDEX_UPPER].te_name   = "toupper";
+       rl->rl_wctrans[_WCTRANS_INDEX_UPPER].te_cached = &rl->rl_mapupper[0];
+       rl->rl_wctrans[_WCTRANS_INDEX_UPPER].te_extmap = &rl->rl_mapupper_ext;
+}
+
+static __inline void
+_rune_init_priv(_RuneLocalePriv *rlp)
+{
+#if _CTYPE_CACHE_SIZE != _CTYPE_NUM_CHARS
+       int i;
+
+       for (i = _CTYPE_CACHE_SIZE; i < _CTYPE_NUM_CHARS; ++i) {
+               rlp->rlp_ctype_tab  [i + 1] = 0;
+               rlp->rlp_tolower_tab[i + 1] = i;
+               rlp->rlp_toupper_tab[i + 1] = i;
+       }
+#endif
+       rlp->rlp_ctype_tab  [0] = 0;
+       rlp->rlp_tolower_tab[0] = EOF;
+       rlp->rlp_toupper_tab[0] = EOF;
+
+       rlp->rl.rl_ctype_tab   = (const unsigned char *)&rlp->rlp_ctype_tab[0];
+       rlp->rl.rl_tolower_tab = (const short *)&rlp->rlp_tolower_tab[0];
+       rlp->rl.rl_toupper_tab = (const short *)&rlp->rlp_toupper_tab[0];
+       rlp->rl.rl_codeset     = (const char *)&rlp->rlp_codeset[0];
+
+       _rune_wctype_init(&rlp->rl);
+       _rune_wctrans_init(&rlp->rl);
+}
+
+static __inline void
+_rune_find_codeset(char *s, size_t n,
+    char *var, size_t *plenvar)
+{
+       size_t lenvar;
+       const char *endvar;
+
+#define _RUNE_CODESET_LEN (sizeof(_RUNE_CODESET)-1)
+
+       lenvar = *plenvar;
+       for (/**/; lenvar > _RUNE_CODESET_LEN; ++var, --lenvar) {
+               if (!memcmp(var, _RUNE_CODESET, _RUNE_CODESET_LEN)) {
+                       *var = '\0';
+                       *plenvar -= lenvar;
+                       endvar = &var[_RUNE_CODESET_LEN];
+                       while (n-- > 1 && lenvar-- > _RUNE_CODESET_LEN) {
+                               if (*endvar == ' ' || *endvar == '\t')
+                                       break;
+                               *s++ = *endvar++;
+                       }
+                       break;
+               }
+       }
+       *s = '\0';
+}
+
+static __inline int
+_rune_read_file(const char * __restrict var, size_t lenvar,
+    _RuneLocale ** __restrict prl)
+{
+       int ret, i;
+       const _FileRuneLocale *frl;
+       const _FileRuneEntry *fre;
+       const uint32_t *frune;
+       _RuneLocalePriv *rlp;
+       _RuneLocale *rl;
+       _RuneEntry *re;
+       uint32_t *rune;
+       uint32_t runetype_len, maplower_len, mapupper_len, variable_len;
+       size_t len, n;
+
+       if (lenvar < sizeof(*frl))
+               return EFTYPE;
+       lenvar -= sizeof(*frl);
+       frl = (const _FileRuneLocale *)(const void *)var;
+       if (memcmp(_RUNECT10_MAGIC, &frl->frl_magic[0], sizeof(frl->frl_magic)))
+               return EFTYPE;
+
+       runetype_len = be32toh(frl->frl_runetype_ext.frr_nranges);
+       maplower_len = be32toh(frl->frl_maplower_ext.frr_nranges);
+       mapupper_len = be32toh(frl->frl_mapupper_ext.frr_nranges);
+       len = runetype_len + maplower_len + mapupper_len;
+
+       fre = (const _FileRuneEntry *)(const void *)(frl + 1);
+       frune = (const uint32_t *)(const void *)(fre + len);
+
+       variable_len = be32toh((uint32_t)frl->frl_variable_len);
+
+       n = (len * sizeof(*fre)) + variable_len;
+       if (lenvar < n)
+               return EFTYPE;
+       lenvar -= n;
+
+       n = sizeof(*rlp) + (len * sizeof(*re)) + lenvar;
+       rlp = (_RuneLocalePriv *)malloc(n);
+       if (rlp == NULL)
+               return ENOMEM;
+       _rune_init_priv(rlp);
+
+       rl = &rlp->rl;
+       re = (_RuneEntry *)(void *)(rlp + 1);
+       rune = (uint32_t *)(void *)(re + len);
+
+       for (i = 0; i < _CTYPE_CACHE_SIZE; ++i) {
+               rl->rl_runetype[i] = be32toh(frl->frl_runetype[i]);
+               rl->rl_maplower[i] = be32toh((uint32_t)frl->frl_maplower[i]);
+               rl->rl_mapupper[i] = be32toh((uint32_t)frl->frl_mapupper[i]);
+       }
+
+#define READ_RANGE(name)                                               \
+do {                                                                   \
+       const _FileRuneEntry *end_fre;                                  \
+       const uint32_t *end_frune;                                      \
+                                                                       \
+       rl->rl_##name##_ext.rr_nranges = name##_len;                    \
+       rl->rl_##name##_ext.rr_rune_ranges = re;                        \
+                                                                       \
+       end_fre = fre + name##_len;                                     \
+       while (fre < end_fre) {                                         \
+               re->re_min = be32toh((uint32_t)fre->fre_min);           \
+               re->re_max = be32toh((uint32_t)fre->fre_max);           \
+               re->re_map = be32toh((uint32_t)fre->fre_map);           \
+               if (re->re_map != 0) {                                  \
+                       re->re_rune_types = NULL;                       \
+               } else {                                                \
+                       re->re_rune_types = rune;                       \
+                       len = re->re_max - re->re_min + 1;              \
+                       n = len * sizeof(*frune);                       \
+                       if (lenvar < n) {                               \
+                               ret = EFTYPE;                           \
+                               goto err;                               \
+                       }                                               \
+                       lenvar -= n;                                    \
+                       end_frune = frune + len;                        \
+                       while (frune < end_frune)                       \
+                               *rune++ = be32toh(*frune++);            \
+               }                                                       \
+               ++fre, ++re;                                            \
+       }                                                               \
+} while (/*CONSTCOND*/0)
+
+       READ_RANGE(runetype);
+       READ_RANGE(maplower);
+       READ_RANGE(mapupper);
+
+       memcpy((void *)rune, (void const *)frune, variable_len);
+       rl->rl_variable_len = variable_len;
+       rl->rl_variable = (void *)rune;
+
+       if (lenvar > 0) {
+               ret = EFTYPE;
+               goto err;
+       }
+
+       _rune_find_codeset(rlp->rlp_codeset, sizeof(rlp->rlp_codeset),
+           (char *)rl->rl_variable, &rl->rl_variable_len);
+
+       ret = _citrus_ctype_open(&rl->rl_citrus_ctype, frl->frl_encoding,
+           rl->rl_variable, rl->rl_variable_len, _PRIVSIZE);
+       if (ret)
+               goto err;
+       if (__mb_len_max_runtime <
+           _citrus_ctype_get_mb_cur_max(rl->rl_citrus_ctype)) {
+               ret = EINVAL;
+               goto err;
+       }
+
+       for (i = 0; i < _CTYPE_CACHE_SIZE; ++i) {
+               wint_t wc;
+
+               ret = _citrus_ctype_btowc(rl->rl_citrus_ctype, i, &wc);
+               if (ret)
+                       goto err;
+               if (wc == WEOF) {
+                       rlp->rlp_ctype_tab[i + 1] = 0;
+                       rlp->rlp_tolower_tab[i + 1] = i;
+                       rlp->rlp_toupper_tab[i + 1] = i;
+               } else {
+                       rlp->rlp_ctype_tab[i + 1] = (unsigned char)
+                           _runetype_to_ctype(_runetype_priv(rl, wc));
+
+#define CONVERT_MAP(name)                                              \
+do {                                                                   \
+       wint_t map;                                                     \
+       int c;                                                          \
+                                                                       \
+       map = _towctrans_priv(wc, _wctrans_##name(rl));                 \
+       if (map == wc || (_citrus_ctype_wctob(rl->rl_citrus_ctype,      \
+           map, &c)  || c == EOF))                                     \
+               c = i;                                                  \
+       rlp->rlp_to##name##_tab[i + 1] = (short)c;                      \
+} while (/*CONSTCOND*/0)
+
+                       CONVERT_MAP(lower);
+                       CONVERT_MAP(upper);
+               }
+       }
+       *prl = rl;
+       return 0;
+
+err:
+       free(rlp);
+       return ret;
+}
+
+static __inline int
+_rune_read_bsdctype(const char * __restrict var, size_t lenvar,
+    _RuneLocale ** __restrict prl)
+{
+       const _FileBSDCTypeLocale *fbl;
+       uint32_t value;
+       int i, bits;
+       uint16_t lower, upper;
+       _RuneLocalePriv *rlp;
+       _RuneLocale *rl;
+
+        if (lenvar < sizeof(*fbl))
+               return EFTYPE;
+       fbl = (const _FileBSDCTypeLocale *)(const void *)var;
+       if (memcmp(&fbl->fbl_id[0], _CTYPE_ID, sizeof(fbl->fbl_id)))
+               return EFTYPE;
+       value = be32toh(fbl->fbl_rev);
+       if (value != _CTYPE_REV)
+               return EFTYPE;
+       value = be32toh(fbl->fbl_num_chars);
+       if (value != _CTYPE_CACHE_SIZE)
+               return EFTYPE;
+       rlp = (_RuneLocalePriv *)malloc(sizeof(*rlp));
+       if (rlp == NULL)
+               return ENOMEM;
+       _rune_init_priv(rlp);
+       rlp->rlp_codeset[0] = '\0';
+
+       rl = &rlp->rl;
+       for (i = 0; i < _CTYPE_CACHE_SIZE; ++i) {
+               bits  = fbl->fbl_ctype_tab[i];
+               lower = be16toh(fbl->fbl_tolower_tab[i]);
+               upper = be16toh(fbl->fbl_toupper_tab[i]);
+
+               rlp->rlp_ctype_tab  [i + 1] = (unsigned char)bits;
+               rlp->rlp_tolower_tab[i + 1] = (short)lower;
+               rlp->rlp_toupper_tab[i + 1] = (short)upper;
+
+               rl->rl_runetype[i] = _runetype_from_ctype(bits, i);
+               rl->rl_maplower[i] = (__nbrune_t)lower;
+               rl->rl_mapupper[i] = (__nbrune_t)upper;
+       }
+       *prl = rl;
+       return 0;
+}
+
+int
+_rune_load(const char * __restrict var, size_t lenvar,
+    _RuneLocale ** __restrict prl)
+{
+       int ret;
+
+       _DIAGASSERT(var != NULL || lenvar < 1);
+       _DIAGASSERT(prl != NULL);
+
+       if (lenvar < 1)
+               return EFTYPE;
+       switch (*var) {
+       case 'R':
+               ret = _rune_read_file(var, lenvar, prl);
+               break;
+       case 'B':
+               ret = _rune_read_bsdctype(var, lenvar, prl);
+               break;
+       default:
+               ret = EFTYPE;
+       }
+       return ret;
+}
diff --git a/lib/nbsd_libc/locale/runetable.c b/lib/nbsd_libc/locale/runetable.c
new file mode 100644 (file)
index 0000000..75ff584
--- /dev/null
@@ -0,0 +1,351 @@
+/*     $NetBSD: runetable.c,v 1.27 2010/06/19 13:26:52 tnozaki Exp $   */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Borman at Krystal Technologies.
+ *
+ * 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. 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.
+ *
+ * $FreeBSD: src/lib/libc/locale/table.c,v 1.13 2000/02/08 07:43:25 obrien Exp $
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)table.c    8.1 (Berkeley) 6/27/93";
+#else
+__RCSID("$NetBSD: runetable.c,v 1.27 2010/06/19 13:26:52 tnozaki Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <wchar.h>
+
+#include "citrus_module.h"
+#include "citrus_ctype.h"
+#include "runetype_local.h"
+
+const _RuneLocale _DefaultRuneLocale = {
+    {  /*00*/  _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+       /*08*/  _RUNETYPE_C,
+               _RUNETYPE_C|_RUNETYPE_S|_RUNETYPE_B,
+               _RUNETYPE_C|_RUNETYPE_S,
+               _RUNETYPE_C|_RUNETYPE_S,
+               _RUNETYPE_C|_RUNETYPE_S,
+               _RUNETYPE_C|_RUNETYPE_S,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+       /*10*/  _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+       /*18*/  _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+               _RUNETYPE_C,
+       /*20*/  _RUNETYPE_S|_RUNETYPE_B|_RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+       /*28*/  _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+       /*30*/  _RUNETYPE_D|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_X|_RUNETYPE_SW1|0,
+               _RUNETYPE_D|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_X|_RUNETYPE_SW1|1,
+               _RUNETYPE_D|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_X|_RUNETYPE_SW1|2,
+               _RUNETYPE_D|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_X|_RUNETYPE_SW1|3,
+               _RUNETYPE_D|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_X|_RUNETYPE_SW1|4,
+               _RUNETYPE_D|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_X|_RUNETYPE_SW1|5,
+               _RUNETYPE_D|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_X|_RUNETYPE_SW1|6,
+               _RUNETYPE_D|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_X|_RUNETYPE_SW1|7,
+       /*38*/  _RUNETYPE_D|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_X|_RUNETYPE_SW1|8,
+               _RUNETYPE_D|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_X|_RUNETYPE_SW1|9,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+       /*40*/  _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_X|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1|10,
+               _RUNETYPE_U|_RUNETYPE_X|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1|11,
+               _RUNETYPE_U|_RUNETYPE_X|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1|12,
+               _RUNETYPE_U|_RUNETYPE_X|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1|13,
+               _RUNETYPE_U|_RUNETYPE_X|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1|14,
+               _RUNETYPE_U|_RUNETYPE_X|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1|15,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+       /*48*/  _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+       /*50*/  _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+       /*58*/  _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_U|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+       /*60*/  _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_X|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1|10,
+               _RUNETYPE_L|_RUNETYPE_X|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1|11,
+               _RUNETYPE_L|_RUNETYPE_X|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1|12,
+               _RUNETYPE_L|_RUNETYPE_X|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1|13,
+               _RUNETYPE_L|_RUNETYPE_X|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1|14,
+               _RUNETYPE_L|_RUNETYPE_X|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1|15,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+       /*68*/  _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+       /*70*/  _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+       /*78*/  _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_L|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_A|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_P|_RUNETYPE_R|_RUNETYPE_G|_RUNETYPE_SW1,
+               _RUNETYPE_C,
+#ifdef ALL_80_TO_FF_SW1
+       /*80*/  _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+       /*90*/  _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+       /*A0*/  _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+       /*B0*/  _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+       /*C0*/  _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+       /*D0*/  _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+       /*E0*/  _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+       /*F0*/  _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+               _RUNETYPE_R|_RUNETYPE_SW1, _RUNETYPE_R|_RUNETYPE_SW1,
+#endif
+    },
+    {  0x00,   0x01,   0x02,   0x03,   0x04,   0x05,   0x06,   0x07,
+       0x08,   0x09,   0x0a,   0x0b,   0x0c,   0x0d,   0x0e,   0x0f,
+       0x10,   0x11,   0x12,   0x13,   0x14,   0x15,   0x16,   0x17,
+       0x18,   0x19,   0x1a,   0x1b,   0x1c,   0x1d,   0x1e,   0x1f,
+       0x20,   0x21,   0x22,   0x23,   0x24,   0x25,   0x26,   0x27,
+       0x28,   0x29,   0x2a,   0x2b,   0x2c,   0x2d,   0x2e,   0x2f,
+       0x30,   0x31,   0x32,   0x33,   0x34,   0x35,   0x36,   0x37,
+       0x38,   0x39,   0x3a,   0x3b,   0x3c,   0x3d,   0x3e,   0x3f,
+       0x40,   'a',    'b',    'c',    'd',    'e',    'f',    'g',
+       'h',    'i',    'j',    'k',    'l',    'm',    'n',    'o',
+       'p',    'q',    'r',    's',    't',    'u',    'v',    'w',
+       'x',    'y',    'z',    0x5b,   0x5c,   0x5d,   0x5e,   0x5f,
+       0x60,   'a',    'b',    'c',    'd',    'e',    'f',    'g',
+       'h',    'i',    'j',    'k',    'l',    'm',    'n',    'o',
+       'p',    'q',    'r',    's',    't',    'u',    'v',    'w',
+       'x',    'y',    'z',    0x7b,   0x7c,   0x7d,   0x7e,   0x7f,
+       0x80,   0x81,   0x82,   0x83,   0x84,   0x85,   0x86,   0x87,
+       0x88,   0x89,   0x8a,   0x8b,   0x8c,   0x8d,   0x8e,   0x8f,
+       0x90,   0x91,   0x92,   0x93,   0x94,   0x95,   0x96,   0x97,
+       0x98,   0x99,   0x9a,   0x9b,   0x9c,   0x9d,   0x9e,   0x9f,
+       0xa0,   0xa1,   0xa2,   0xa3,   0xa4,   0xa5,   0xa6,   0xa7,
+       0xa8,   0xa9,   0xaa,   0xab,   0xac,   0xad,   0xae,   0xaf,
+       0xb0,   0xb1,   0xb2,   0xb3,   0xb4,   0xb5,   0xb6,   0xb7,
+       0xb8,   0xb9,   0xba,   0xbb,   0xbc,   0xbd,   0xbe,   0xbf,
+       0xc0,   0xc1,   0xc2,   0xc3,   0xc4,   0xc5,   0xc6,   0xc7,
+       0xc8,   0xc9,   0xca,   0xcb,   0xcc,   0xcd,   0xce,   0xcf,
+       0xd0,   0xd1,   0xd2,   0xd3,   0xd4,   0xd5,   0xd6,   0xd7,
+       0xd8,   0xd9,   0xda,   0xdb,   0xdc,   0xdd,   0xde,   0xdf,
+       0xe0,   0xe1,   0xe2,   0xe3,   0xe4,   0xe5,   0xe6,   0xe7,
+       0xe8,   0xe9,   0xea,   0xeb,   0xec,   0xed,   0xee,   0xef,
+       0xf0,   0xf1,   0xf2,   0xf3,   0xf4,   0xf5,   0xf6,   0xf7,
+       0xf8,   0xf9,   0xfa,   0xfb,   0xfc,   0xfd,   0xfe,   0xff,
+    },
+    {  0x00,   0x01,   0x02,   0x03,   0x04,   0x05,   0x06,   0x07,
+       0x08,   0x09,   0x0a,   0x0b,   0x0c,   0x0d,   0x0e,   0x0f,
+       0x10,   0x11,   0x12,   0x13,   0x14,   0x15,   0x16,   0x17,
+       0x18,   0x19,   0x1a,   0x1b,   0x1c,   0x1d,   0x1e,   0x1f,
+       0x20,   0x21,   0x22,   0x23,   0x24,   0x25,   0x26,   0x27,
+       0x28,   0x29,   0x2a,   0x2b,   0x2c,   0x2d,   0x2e,   0x2f,
+       0x30,   0x31,   0x32,   0x33,   0x34,   0x35,   0x36,   0x37,
+       0x38,   0x39,   0x3a,   0x3b,   0x3c,   0x3d,   0x3e,   0x3f,
+       0x40,   'A',    'B',    'C',    'D',    'E',    'F',    'G',
+       'H',    'I',    'J',    'K',    'L',    'M',    'N',    'O',
+       'P',    'Q',    'R',    'S',    'T',    'U',    'V',    'W',
+       'X',    'Y',    'Z',    0x5b,   0x5c,   0x5d,   0x5e,   0x5f,
+       0x60,   'A',    'B',    'C',    'D',    'E',    'F',    'G',
+       'H',    'I',    'J',    'K',    'L',    'M',    'N',    'O',
+       'P',    'Q',    'R',    'S',    'T',    'U',    'V',    'W',
+       'X',    'Y',    'Z',    0x7b,   0x7c,   0x7d,   0x7e,   0x7f,
+       0x80,   0x81,   0x82,   0x83,   0x84,   0x85,   0x86,   0x87,
+       0x88,   0x89,   0x8a,   0x8b,   0x8c,   0x8d,   0x8e,   0x8f,
+       0x90,   0x91,   0x92,   0x93,   0x94,   0x95,   0x96,   0x97,
+       0x98,   0x99,   0x9a,   0x9b,   0x9c,   0x9d,   0x9e,   0x9f,
+       0xa0,   0xa1,   0xa2,   0xa3,   0xa4,   0xa5,   0xa6,   0xa7,
+       0xa8,   0xa9,   0xaa,   0xab,   0xac,   0xad,   0xae,   0xaf,
+       0xb0,   0xb1,   0xb2,   0xb3,   0xb4,   0xb5,   0xb6,   0xb7,
+       0xb8,   0xb9,   0xba,   0xbb,   0xbc,   0xbd,   0xbe,   0xbf,
+       0xc0,   0xc1,   0xc2,   0xc3,   0xc4,   0xc5,   0xc6,   0xc7,
+       0xc8,   0xc9,   0xca,   0xcb,   0xcc,   0xcd,   0xce,   0xcf,
+       0xd0,   0xd1,   0xd2,   0xd3,   0xd4,   0xd5,   0xd6,   0xd7,
+       0xd8,   0xd9,   0xda,   0xdb,   0xdc,   0xdd,   0xde,   0xdf,
+       0xe0,   0xe1,   0xe2,   0xe3,   0xe4,   0xe5,   0xe6,   0xe7,
+       0xe8,   0xe9,   0xea,   0xeb,   0xec,   0xed,   0xee,   0xef,
+       0xf0,   0xf1,   0xf2,   0xf3,   0xf4,   0xf5,   0xf6,   0xf7,
+       0xf8,   0xf9,   0xfa,   0xfb,   0xfc,   0xfd,   0xfe,   0xff,
+    },
+    { 0, NULL },
+    { 0, NULL },
+    { 0, NULL },
+    NULL, 0,
+    "646",
+    &_citrus_ctype_default,
+    {
+       {   "towlower",
+           __UNCONST(&_DefaultRuneLocale.rl_maplower[0]),
+           __UNCONST(&_DefaultRuneLocale.rl_maplower_ext)
+       },
+       {   "towupper",
+           __UNCONST(&_DefaultRuneLocale.rl_mapupper[0]),
+           __UNCONST(&_DefaultRuneLocale.rl_mapupper_ext)
+       },
+    },
+    {
+           { "alnum", _RUNETYPE_A|_RUNETYPE_D },
+           { "alpha", _RUNETYPE_A },
+           { "blank", _RUNETYPE_B },
+           { "cntrl", _RUNETYPE_C },
+           { "digit", _RUNETYPE_D },
+           { "graph", _RUNETYPE_G },
+           { "lower", _RUNETYPE_L },
+           { "print", _RUNETYPE_R },
+           { "punct", _RUNETYPE_P },
+           { "space", _RUNETYPE_S },
+           { "upper", _RUNETYPE_U },
+           { "xdigit", _RUNETYPE_X },
+    },
+    _C_ctype_,
+    _C_tolower_,
+    _C_toupper_
+};
+
+const _RuneLocale *_CurrentRuneLocale = &_DefaultRuneLocale;
diff --git a/lib/nbsd_libc/locale/runetype_file.h b/lib/nbsd_libc/locale/runetype_file.h
new file mode 100644 (file)
index 0000000..67d59db
--- /dev/null
@@ -0,0 +1,136 @@
+/* $NetBSD: runetype_file.h,v 1.3 2010/06/20 02:23:15 tnozaki Exp $ */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Borman at Krystal Technologies.
+ *
+ * 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. 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.
+ *
+ *     @(#)runetype.h  8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef        _RUNETYPE_FILE_H_
+#define        _RUNETYPE_FILE_H_
+
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+#include "ctype_local.h"
+
+/* for cross host tools on older systems */
+#ifndef UINT32_C
+/* assumes sizeof(unsigned int)>=4 */
+#define UINT32_C(c) ((uint32_t)(c##U))
+#endif
+
+typedef uint32_t       __nbrune_t;
+typedef uint64_t       __runepad_t;
+
+#define _DEFAULT_INVALID_RUNE ((__nbrune_t)-3)
+
+/*
+ * The lower 8 bits of runetype[] contain the digit value of the rune.
+ */
+typedef uint32_t _RuneType;
+#define        _RUNETYPE_A     UINT32_C(0x00000100)    /* Alpha */
+#define        _RUNETYPE_C     UINT32_C(0x00000200)    /* Control */
+#define        _RUNETYPE_D     UINT32_C(0x00000400)    /* Digit */
+#define        _RUNETYPE_G     UINT32_C(0x00000800)    /* Graph */
+#define        _RUNETYPE_L     UINT32_C(0x00001000)    /* Lower */
+#define        _RUNETYPE_P     UINT32_C(0x00002000)    /* Punct */
+#define        _RUNETYPE_S     UINT32_C(0x00004000)    /* Space */
+#define        _RUNETYPE_U     UINT32_C(0x00008000)    /* Upper */
+#define        _RUNETYPE_X     UINT32_C(0x00010000)    /* X digit */
+#define        _RUNETYPE_B     UINT32_C(0x00020000)    /* Blank */
+#define        _RUNETYPE_R     UINT32_C(0x00040000)    /* Print */
+#define        _RUNETYPE_I     UINT32_C(0x00080000)    /* Ideogram */
+#define        _RUNETYPE_T     UINT32_C(0x00100000)    /* Special */
+#define        _RUNETYPE_Q     UINT32_C(0x00200000)    /* Phonogram */
+#define        _RUNETYPE_SWM   UINT32_C(0xc0000000)/* Mask to get screen width data */
+#define        _RUNETYPE_SWS   30              /* Bits to shift to get width */
+#define        _RUNETYPE_SW0   UINT32_C(0x20000000)    /* 0 width character */
+#define        _RUNETYPE_SW1   UINT32_C(0x40000000)    /* 1 width character */
+#define        _RUNETYPE_SW2   UINT32_C(0x80000000)    /* 2 width character */
+#define        _RUNETYPE_SW3   UINT32_C(0xc0000000)    /* 3 width character */
+
+/*
+ * rune file format.  network endian.
+ */
+typedef struct {
+       int32_t         fre_min;        /* First rune of the range */
+       int32_t         fre_max;        /* Last rune (inclusive) of the range */
+       int32_t         fre_map;        /* What first maps to in maps */
+       uint32_t        fre_pad1;       /* backward compatibility */
+       __runepad_t     fre_pad2;       /* backward compatibility */
+} __packed _FileRuneEntry;
+
+
+typedef struct {
+       uint32_t        frr_nranges;    /* Number of ranges stored */
+       uint32_t        frr_pad1;       /* backward compatibility */
+       __runepad_t     frr_pad2;       /* backward compatibility */
+} __packed _FileRuneRange;
+
+
+typedef struct {
+       char            frl_magic[8];   /* Magic saying what version we are */
+       char            frl_encoding[32];/* ASCII name of this encoding */
+
+       __runepad_t     frl_pad1;       /* backward compatibility */
+       __runepad_t     frl_pad2;       /* backward compatibility */
+       int32_t         frl_invalid_rune;
+       uint32_t        frl_pad3;       /* backward compatibility */
+
+       _RuneType       frl_runetype[_CTYPE_CACHE_SIZE];
+       int32_t         frl_maplower[_CTYPE_CACHE_SIZE];
+       int32_t         frl_mapupper[_CTYPE_CACHE_SIZE];
+
+       /*
+        * The following are to deal with Runes larger than _CTYPE_CACHE_SIZE - 1.
+        * Their data is actually contiguous with this structure so as to make
+        * it easier to read/write from/to disk.
+        */
+       _FileRuneRange  frl_runetype_ext;
+       _FileRuneRange  frl_maplower_ext;
+       _FileRuneRange  frl_mapupper_ext;
+
+       __runepad_t     frl_pad4;       /* backward compatibility */
+       int32_t         frl_variable_len;/* how long that data is */
+       uint32_t        frl_pad5;       /* backward compatibility */
+
+       /* variable size data follows */
+} __packed _FileRuneLocale;
+
+
+/* magic number for LC_CTYPE (rune)locale declaration */
+#define        _RUNECT10_MAGIC "RuneCT10"      /* Indicates version 0 of RuneLocale */
+
+/* codeset tag */
+#define _RUNE_CODESET "CODESET="
+
+#endif /* !_RUNETYPE_FILE_H_ */
diff --git a/lib/nbsd_libc/locale/runetype_local.h b/lib/nbsd_libc/locale/runetype_local.h
new file mode 100644 (file)
index 0000000..1fd9bb9
--- /dev/null
@@ -0,0 +1,141 @@
+/*     $NetBSD: runetype_local.h,v 1.12 2010/06/20 02:23:15 tnozaki Exp $      */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Borman at Krystal Technologies.
+ *
+ * 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. 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.
+ *
+ *     @(#)rune.h      8.1 (Berkeley) 6/27/93
+ *     @(#)runetype.h  8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef        _RUNETYPE_LOCAL_H_
+#define        _RUNETYPE_LOCAL_H_
+
+#include <sys/cdefs.h>
+#include <sys/types.h>
+#include <stdio.h>
+
+#include "runetype_misc.h"
+
+#define _RUNE_ISCACHED(c)      ((c)>=0 && (c)<_CTYPE_CACHE_SIZE)
+
+
+/*
+ * expanded rune locale declaration.  local to the host.  host endian.
+ */
+typedef struct {
+       __nbrune_t      re_min;         /* First rune of the range */
+       __nbrune_t      re_max;         /* Last rune (inclusive) of the range */
+       __nbrune_t      re_map;         /* What first maps to in maps */
+       _RuneType       *re_rune_types; /* Array of types in range */
+} _RuneEntry;
+
+
+typedef struct {
+       uint32_t        rr_nranges;     /* Number of ranges stored */
+       _RuneEntry      *rr_rune_ranges;
+} _RuneRange;
+
+
+/*
+ * wctrans stuffs.
+ */
+typedef struct _WCTransEntry {
+       const char      *te_name;
+       __nbrune_t      *te_cached;
+       _RuneRange      *te_extmap;
+} _WCTransEntry;
+#define _WCTRANS_INDEX_LOWER   0
+#define _WCTRANS_INDEX_UPPER   1
+#define _WCTRANS_NINDEXES      2
+
+/*
+ * wctype stuffs.
+ */
+typedef struct _WCTypeEntry {
+       const char      *te_name;
+       _RuneType       te_mask;
+} _WCTypeEntry;
+#define _WCTYPE_INDEX_ALNUM    0
+#define _WCTYPE_INDEX_ALPHA    1
+#define _WCTYPE_INDEX_BLANK    2
+#define _WCTYPE_INDEX_CNTRL    3
+#define _WCTYPE_INDEX_DIGIT    4
+#define _WCTYPE_INDEX_GRAPH    5
+#define _WCTYPE_INDEX_LOWER    6
+#define _WCTYPE_INDEX_PRINT    7
+#define _WCTYPE_INDEX_PUNCT    8
+#define _WCTYPE_INDEX_SPACE    9
+#define _WCTYPE_INDEX_UPPER    10
+#define _WCTYPE_INDEX_XDIGIT   11
+#define _WCTYPE_NINDEXES       12
+
+/*
+ * ctype stuffs
+ */
+
+typedef struct _RuneLocale {
+       /*
+        * copied from _FileRuneLocale
+        */
+       _RuneType       rl_runetype[_CTYPE_CACHE_SIZE];
+       __nbrune_t      rl_maplower[_CTYPE_CACHE_SIZE];
+       __nbrune_t      rl_mapupper[_CTYPE_CACHE_SIZE];
+       _RuneRange      rl_runetype_ext;
+       _RuneRange      rl_maplower_ext;
+       _RuneRange      rl_mapupper_ext;
+
+       void            *rl_variable;
+       size_t          rl_variable_len;
+
+       /*
+        * the following portion is generated on the fly
+        */
+       const char                      *rl_codeset;
+       struct _citrus_ctype_rec        *rl_citrus_ctype;
+       _WCTransEntry                   rl_wctrans[_WCTRANS_NINDEXES];
+       _WCTypeEntry                    rl_wctype[_WCTYPE_NINDEXES];
+
+       const unsigned char             *rl_ctype_tab;
+       const short                     *rl_tolower_tab;
+       const short                     *rl_toupper_tab;
+} _RuneLocale;
+
+/*
+ * global variables
+ */
+extern const _RuneLocale _DefaultRuneLocale;
+extern const _RuneLocale *_CurrentRuneLocale;
+
+__BEGIN_DECLS
+int _rune_load(const char * __restrict, size_t, _RuneLocale ** __restrict);
+__END_DECLS
+
+#endif /* !_RUNETYPE_LOCAL_H_ */
diff --git a/lib/nbsd_libc/locale/runetype_misc.h b/lib/nbsd_libc/locale/runetype_misc.h
new file mode 100644 (file)
index 0000000..df4c5b7
--- /dev/null
@@ -0,0 +1,130 @@
+/* $NetBSD: runetype_misc.h,v 1.2 2010/12/14 02:28:57 joerg Exp $ */
+
+/*-
+ * Copyright (c) 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Borman at Krystal Technologies.
+ *
+ * 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. 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.
+ *
+ *     @(#)runetype.h  8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef        _RUNETYPE_MISC_H_
+#define        _RUNETYPE_MISC_H_
+
+#include <sys/ctype_bits.h>
+#include "runetype_file.h"
+
+static __inline int
+_runetype_to_ctype(_RuneType bits)
+{
+       int ret;
+
+       if (bits == (_RuneType)0)
+               return 0;
+       ret = 0;
+       if (bits & _RUNETYPE_U)
+               ret |= _CTYPE_U;
+       if (bits & _RUNETYPE_L)
+               ret |= _CTYPE_L;
+       if (bits & _RUNETYPE_D)
+               ret |= _CTYPE_N;
+       if (bits & _RUNETYPE_S)
+               ret |= _CTYPE_S;
+       if (bits & _RUNETYPE_P)
+               ret |= _CTYPE_P;
+       if (bits & _RUNETYPE_C)
+               ret |= _CTYPE_C;
+       if (bits & _RUNETYPE_X)
+               ret |= _CTYPE_X;
+       /*
+        * TWEAK!  _B has been used incorrectly (or with older
+        * declaration) in ctype.h isprint() macro.
+        * _B does not mean isblank, it means "isprint && !isgraph".
+        * the following is okay since isblank() was hardcoded in
+        * function (i.e. isblank() is inherently locale unfriendly).
+        */
+#if 1
+       if ((bits & (_RUNETYPE_R | _RUNETYPE_G)) == _RUNETYPE_R)
+               ret |= _CTYPE_B;
+#else
+       if (bits & _RUNETYPE_B)
+               ret |= _CTYPE_B;
+#endif
+       return ret;
+}
+
+static __inline _RuneType
+_runetype_from_ctype(int bits, int ch)
+{
+        _RuneType ret;
+
+       /*
+        * TWEAKS!
+        * - old locale file declarations do not have proper _B
+        *   in many cases.
+        * - isprint() declaration in ctype.h incorrectly uses _B.
+        *   _B means "isprint but !isgraph", not "isblank" with the
+        *   declaration.
+        * - _X and _RUNETYPE_X have negligible difference in meaning.
+        * - we don't set digit value, fearing that it would be
+        *   too much of hardcoding.  we may need to revisit it.
+        */
+
+       ret = (_RuneType)0;
+       if (bits & _CTYPE_U)
+               ret |= _RUNETYPE_U;
+       if (bits & _CTYPE_L)
+               ret |= _RUNETYPE_L;
+       if (bits & _CTYPE_N)
+               ret |= _RUNETYPE_D;
+       if (bits & _CTYPE_S)
+               ret |= _RUNETYPE_S;
+       if (bits & _CTYPE_P)
+               ret |= _RUNETYPE_P;
+       if (bits & _CTYPE_C)
+               ret |= _RUNETYPE_C;
+       /* derived flag bits, duplicate of ctype.h */
+       if (bits & (_CTYPE_U|_CTYPE_L))
+               ret |= _RUNETYPE_A;
+       if (bits & (_CTYPE_N|_CTYPE_X))
+               ret |= _RUNETYPE_X;
+       if (bits & (_CTYPE_P|_CTYPE_U|_CTYPE_L|_CTYPE_N))
+               ret |= _RUNETYPE_G;
+       /* we don't really trust _B in the file.  see above. */
+       if (bits & _CTYPE_B)
+               ret |= _RUNETYPE_B;
+       if ((bits & (_CTYPE_P|_CTYPE_U|_CTYPE_L|_CTYPE_N|_CTYPE_B)) ||
+           ch == ' ')
+               ret |= (_RUNETYPE_R | _RUNETYPE_SW1);
+       if (ch == ' ' || ch == '\t')
+               ret |= _RUNETYPE_B;
+       return ret;
+}
+
+#endif /* !_RUNETYPE_MISC_H_ */
diff --git a/lib/nbsd_libc/locale/setlocale.3 b/lib/nbsd_libc/locale/setlocale.3
new file mode 100644 (file)
index 0000000..9d88b99
--- /dev/null
@@ -0,0 +1,407 @@
+.\"    $NetBSD: setlocale.3,v 1.21 2004/01/24 16:58:54 wiz Exp $
+.\"
+.\" Copyright (c) 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Donn Seeley at BSDI.
+.\"
+.\" 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. 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.
+.\"
+.\"    @(#)setlocale.3 8.1 (Berkeley) 6/9/93
+.\"
+.Dd May 30, 2003
+.Dt SETLOCALE 3
+.Os
+.Sh NAME
+.Nm setlocale ,
+.Nm localeconv
+.Nd natural language formatting for C
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In locale.h
+.Ft char *
+.Fn setlocale "int category" "const char *locale"
+.Ft struct lconv *
+.Fn localeconv "void"
+.Sh DESCRIPTION
+The
+.Fn setlocale
+function sets the C library's notion
+of natural language formatting style
+for particular sets of routines.
+Each such style is called a
+.Sq locale
+and is invoked using an appropriate name passed as a C string.
+The
+.Fn localeconv
+routine returns the current locale's parameters
+for formatting numbers.
+.Pp
+The
+.Fn setlocale
+function recognizes several categories of routines.
+These are the categories and the sets of routines they select:
+.Bl -tag -width LC_MONETARY
+.It Dv LC_ALL
+Set the entire locale generically.
+.It Dv LC_COLLATE
+Set a locale for string collation routines.
+This controls alphabetic ordering in
+.Fn strcoll
+and
+.Fn strxfrm .
+.It Dv LC_CTYPE
+Set a locale for the
+.Xr ctype 3
+functions.
+This controls recognition of upper and lower case,
+alphabetic or non-alphabetic characters,
+and so on.
+The real work is done by the
+.Fn setrunelocale
+function.
+.It Dv LC_MESSAGES
+Set a locale for message catalogs.
+This controls the selection of message catalogs by the
+.Xr catgets 3
+and
+.Xr gettext 3
+families of functions.
+.It Dv LC_MONETARY
+Set a locale for formatting monetary values;
+this affects the
+.Fn localeconv
+function.
+.It Dv LC_NUMERIC
+Set a locale for formatting numbers.
+This controls the formatting of decimal points
+in input and output of floating point numbers
+in functions such as
+.Fn printf
+and
+.Fn scanf ,
+as well as values returned by
+.Fn localeconv .
+.It Dv LC_TIME
+Set a locale for formatting dates and times using the
+.Fn strftime
+function.
+.El
+.Pp
+Only three locales are defined by default,
+the empty string
+.Li "\&""\|""
+which denotes the native environment, and the
+.Li "\&""C""
+and
+.Li "\&""POSIX""
+locales, which denote the C language environment.
+A
+.Fa locale
+argument of
+.Dv NULL
+causes
+.Fn setlocale
+to return the current locale.
+By default, C programs start in the
+.Li "\&""C""
+locale.
+The format of the locale string is described in
+.Xr nls 7 .
+.Pp
+The only function in the library that sets the locale is
+.Fn setlocale ;
+the locale is never changed as a side effect of some other routine.
+.Pp
+Changing the setting of
+.Dv LC_MESSAGES
+has no effect on catalogs that have already been opened by
+.Xr catopen 3 .
+.Pp
+The
+.Fn localeconv
+function returns a pointer to a structure
+which provides parameters for formatting numbers,
+especially currency values:
+.Bd -literal -offset indent
+struct lconv {
+       char    *decimal_point;
+       char    *thousands_sep;
+       char    *grouping;
+       char    *int_curr_symbol;
+       char    *currency_symbol;
+       char    *mon_decimal_point;
+       char    *mon_thousands_sep;
+       char    *mon_grouping;
+       char    *positive_sign;
+       char    *negative_sign;
+       char    int_frac_digits;
+       char    frac_digits;
+       char    p_cs_precedes;
+       char    p_sep_by_space;
+       char    n_cs_precedes;
+       char    n_sep_by_space;
+       char    p_sign_posn;
+       char    n_sign_posn;
+       char    int_p_cs_precedes;
+       char    int_n_cs_precedes;
+       char    int_p_sep_by_space;
+       char    int_n_sep_by_space;
+       char    int_p_sign_posn;
+       char    int_n_sign_posn;
+};
+.Ed
+.Pp
+The individual fields have the following meanings:
+.Bl -tag -width int_p_sep_by_space
+.It Fa decimal_point
+The decimal point character, except for monetary values.
+.It Fa thousands_sep
+The separator between groups of digits
+before the decimal point, except for monetary values.
+.It Fa grouping
+The sizes of the groups of digits, except for monetary values.
+This is a pointer to a vector of integers, each of size
+.Va char ,
+representing group size from low order digit groups
+to high order (right to left).
+The list may be terminated with 0 or
+.Dv CHAR_MAX .
+If the list is terminated with 0,
+the last group size before the 0 is repeated to account for all the digits.
+If the list is terminated with
+.Dv CHAR_MAX ,
+no more grouping is performed.
+.It Fa int_curr_symbol
+The standardized (ISO 4217:1995) international currency symbol.
+.It Fa currency_symbol
+The local currency symbol.
+.It Fa mon_decimal_point
+The decimal point character for monetary values.
+.It Fa mon_thousands_sep
+The separator for digit groups in monetary values.
+.It Fa mon_grouping
+Like
+.Fa grouping
+but for monetary values.
+.It Fa positive_sign
+The character used to denote nonnegative monetary values,
+usually the empty string.
+.It Fa negative_sign
+The character used to denote negative monetary values,
+usually a minus sign.
+.It Fa int_frac_digits
+The number of digits after the decimal point
+in an internationally formatted monetary value.
+.It Fa frac_digits
+The number of digits after the decimal point
+in an locally formatted monetary value.
+.It Fa p_cs_precedes
+1 if the currency symbol precedes the monetary value
+for nonnegative values, 0 if it follows.
+.It Fa p_sep_by_space
+1 if a space is inserted between the currency symbol
+and the monetary value for nonnegative values, 0 otherwise.
+.It Fa n_cs_precedes
+Like
+.Fa p_cs_precedes
+but for negative values.
+.It Fa n_sep_by_space
+Like
+.Fa p_sep_by_space
+but for negative values.
+.It Fa p_sign_posn
+The location of the
+.Fa positive_sign
+with respect to a nonnegative quantity and the
+.Fa currency_symbol .
+.It Fa n_sign_posn
+Like
+.Fa p_sign_posn
+but for negative currency values.
+.It Fa int_p_cs_precedes
+1 if the currency symbol precedes the internationally
+formatted monetary value for nonnegative values, 0 if it follows.
+.It Fa int_n_cs_precedes
+Like
+.Fa int_p_cs_precedes
+but for negative values.
+.It Fa int_p_sep_by_space
+1 if a space is inserted between the currency symbol
+and the internationally formatted monetary value for
+nonnegative values, 0 otherwise.
+.It Fa int_n_sep_by_space
+Like
+.Fa int_p_sep_by_space
+but for negative values.
+.It Fa int_p_sign_posn
+The location of the
+.Fa positive_sign
+with respect to a nonnegative quantity and the
+.Fa currency_symbol ,
+for internationally formatted nonnegative monetary values.
+.It Fa int_n_sign_posn
+Like
+.Fa int_p_sign_posn
+but for negative values.
+.El
+.Pp
+The positional parameters in
+.Fa p_sign_posn ,
+.Fa n_sign_posn ,
+.Fa int_p_sign_posn
+and
+.Fa int_n_sign_posn
+are encoded as follows:
+.Bl -tag -width 3n -compact
+.It Li 0
+Parentheses around the entire string.
+.It Li 1
+Before the string.
+.It Li 2
+After the string.
+.It Li 3
+Just before
+.Fa currency_symbol .
+.It Li 4
+Just after
+.Fa currency_symbol .
+.El
+.Pp
+Unless mentioned above,
+an empty string as a value for a field
+indicates a zero length result or
+a value that is not in the current locale.
+A
+.Dv CHAR_MAX
+result similarly denotes an unavailable value.
+.Sh RETURN VALUES
+The
+.Fn setlocale
+function returns
+.Dv NULL
+and fails to change the locale
+if the given combination of
+.Fa category
+and
+.Fa locale
+makes no sense.
+The
+.Fn localeconv
+function returns a pointer to a static object
+which may be altered by later calls to
+.Fn setlocale
+or
+.Fn localeconv .
+.Sh EXAMPLES
+The following code illustrates how a program can initialize the
+international environment for one language, while selectively
+modifying the program's locale such that regular expressions and
+string operations can be applied to text recorded in a different
+language:
+.Bd -literal
+       setlocale(LC_ALL, "de");
+       setlocale(LC_COLLATE, "fr");
+.Ed
+.Pp
+When a process is started, its current locale is set to the C or POSIX
+locale.
+An internationalized program that depends on locale data not defined in
+the C or POSIX locale must invoke the setlocale subroutine in the
+following manner before using any of the locale-specific information:
+.Bd -literal
+       setlocale(LC_ALL, "");
+.Ed
+.\" .Sh FILES                                                  XXX
+.\" .Bl -tag -width /usr/share/locale/locale/category -compact XXX
+.\" .It Pa $PATH_LOCALE/\fIlocale\fP/\fIcategory\fP            XXX
+.\" .It Pa /usr/share/locale/\fIlocale\fP/\fIcategory\fP       XXX
+.\" locale file for the locale \fIlocale\fP                    XXX
+.\" and the category \fIcategory\fP.                           XXX
+.\" .El
+.Sh SEE ALSO
+.Xr catopen 3 ,
+.Xr gettext 3 ,
+.Xr nl_langinfo 3 ,
+.Xr nls 7
+.\" .Xr strcoll 3 ,                                            XXX
+.\" .Xr strxfrm 3                                              XXX
+.Sh STANDARDS
+The
+.Fn setlocale
+and
+.Fn localeconv
+functions conform to
+.St -ansiC
+and
+.St -isoC-90 .
+.Pp
+The
+.Fa int_p_cs_precedes ,
+.Fa int_n_cs_precedes ,
+.Fa int_p_sep_by_space ,
+.Fa int_n_sep_by_space ,
+.Fa int_p_sign_posn
+and
+.Fa int_n_sign_posn
+members of
+.Ft struct lconv
+were introduced in
+.St -isoC-99 .
+.Sh HISTORY
+The
+.Fn setlocale
+and
+.Fn localeconv
+functions first appeared in
+.Bx 4.4 .
+.Sh BUGS
+The current implementation supports only the
+.Li "\&""C""
+and
+.Li "\&""POSIX""
+locales for all but the
+.Dv LC_CTYPE
+locale.
+.Pp
+In spite of the gnarly currency support in
+.Fn localeconv ,
+the standards don't include any functions
+for generalized currency formatting.
+.Pp
+.Dv LC_COLLATE
+does not make sense for many languages.
+Use of
+.Dv LC_MONETARY
+could lead to misleading results until we have a real time currency
+conversion function.
+.Dv LC_NUMERIC
+and
+.Dv LC_TIME
+are personal choices and should not be wrapped up with the other categories.
+.Pp
+Multibyte locales aren't supported for static binaries.
diff --git a/lib/nbsd_libc/locale/setlocale.c b/lib/nbsd_libc/locale/setlocale.c
new file mode 100644 (file)
index 0000000..bc3734e
--- /dev/null
@@ -0,0 +1,141 @@
+/* $NetBSD: setlocale.c,v 1.58 2010/06/07 13:52:30 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: setlocale.c,v 1.58 2010/06/07 13:52:30 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <locale.h>
+#include <limits.h>
+#include <paths.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "setlocale_local.h"
+
+const char *_PathLocale = NULL;
+
+__link_set_decl(all_categories, _locale_category_t);
+
+extern const _locale_category_t _generic_LC_ALL_desc;
+extern const _locale_category_t _dummy_LC_COLLATE_desc;
+#ifdef WITH_RUNE
+extern const _locale_category_t _citrus_LC_CTYPE_desc;
+extern const _locale_category_t _citrus_LC_MONETARY_desc;
+extern const _locale_category_t _citrus_LC_NUMERIC_desc;
+extern const _locale_category_t _citrus_LC_TIME_desc;
+extern const _locale_category_t _citrus_LC_MESSAGES_desc;
+#else
+extern const _locale_category_t _localeio_LC_CTYPE_desc;
+extern const _locale_category_t _localeio_LC_MONETARY_desc;
+extern const _locale_category_t _localeio_LC_NUMERIC_desc;
+extern const _locale_category_t _localeio_LC_TIME_desc;
+extern const _locale_category_t _localeio_LC_MESSAGES_desc;
+#endif
+
+__link_set_add_data(all_categories, _generic_LC_ALL_desc);
+__link_set_add_data(all_categories, _dummy_LC_COLLATE_desc);
+#ifdef WITH_RUNE
+__link_set_add_data(all_categories, _citrus_LC_CTYPE_desc);
+__link_set_add_data(all_categories, _citrus_LC_MONETARY_desc);
+__link_set_add_data(all_categories, _citrus_LC_NUMERIC_desc);
+__link_set_add_data(all_categories, _citrus_LC_TIME_desc);
+__link_set_add_data(all_categories, _citrus_LC_MESSAGES_desc);
+#else
+__link_set_add_data(all_categories, _localeio_LC_CTYPE_desc);
+__link_set_add_data(all_categories, _localeio_LC_MONETARY_desc);
+__link_set_add_data(all_categories, _localeio_LC_NUMERIC_desc);
+__link_set_add_data(all_categories, _localeio_LC_TIME_desc);
+__link_set_add_data(all_categories, _localeio_LC_MESSAGES_desc);
+#endif
+
+_locale_category_t *
+_find_category(int category)
+{
+       _locale_category_t * const *p;
+
+       __link_set_foreach(p, all_categories) {
+               if ((*p)->category == category)
+                       return *p;
+       }
+       return NULL;
+}
+
+const char *
+_get_locale_env(const char *category)
+{
+       const char *name;
+
+       /* 1. check LC_ALL */
+       name = (const char *)getenv("LC_ALL");
+       if (name == NULL || *name == '\0') {
+               /* 2. check LC_* */
+               name = (const char *)getenv(category);
+               if (name == NULL || *name == '\0') {
+                       /* 3. check LANG */
+                       name = getenv("LANG");
+               }
+       }
+       if (name == NULL || *name == '\0' || strchr(name, '/'))
+               /* 4. if none is set, fall to "C" */
+               name = _C_LOCALE;
+       return name;
+}
+
+char *
+__setlocale(int category, const char *name)
+{
+       _locale_category_t *l;
+       struct _locale_impl_t *impl;
+
+       if (category >= LC_ALL && category < _LC_LAST) {
+               l = _find_category(category);
+               if (l != NULL) {
+                       if (issetugid() || ((_PathLocale == NULL &&
+                           (_PathLocale = getenv("PATH_LOCALE")) == NULL) ||
+                           *_PathLocale == '\0'))
+                               _PathLocale = _PATH_LOCALE;
+                       impl = *_current_locale();
+                       return __UNCONST((*l->setlocale)(name, impl));
+               }
+       }
+       return NULL;
+}
+
+char *
+setlocale(int category, const char *locale)
+{
+
+       /* locale may be NULL */
+
+       __mb_len_max_runtime = MB_LEN_MAX;
+       return __setlocale(category, locale);
+}
diff --git a/lib/nbsd_libc/locale/setlocale_local.h b/lib/nbsd_libc/locale/setlocale_local.h
new file mode 100644 (file)
index 0000000..15601a9
--- /dev/null
@@ -0,0 +1,83 @@
+/* $NetBSD: setlocale_local.h,v 1.7 2010/06/07 13:52:30 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2008 Citrus Project,
+ * 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.
+ */
+
+#ifndef _SETLOCALE_LOCAL_H_
+#define _SETLOCALE_LOCAL_H_
+
+#define _LOCALENAME_LEN_MAX 33
+
+#define _C_LOCALE              "C"
+#define _POSIX_LOCALE          "POSIX"
+
+extern const char              *_PathLocale;
+#define _LOCALE_ALIAS_NAME     "locale.alias"
+
+typedef void *_locale_part_t;
+
+struct _locale_cache_t {
+       const unsigned char *ctype_tab;
+       const short *tolower_tab;
+       const short *toupper_tab;
+       size_t mb_cur_max;
+       struct lconv *ldata;
+       const char **items;
+};
+
+struct _locale_impl_t {
+       struct _locale_cache_t *cache;
+       char query[_LOCALENAME_LEN_MAX * (_LC_LAST - 1)];
+       const char *part_name[_LC_LAST];
+       _locale_part_t part_impl[_LC_LAST];
+};
+
+typedef const char *(*_locale_set_t)(const char * __restrict,
+    struct _locale_impl_t * __restrict);
+
+typedef struct {
+       const char* name;
+       int category;
+       _locale_set_t setlocale;
+} _locale_category_t;
+
+__BEGIN_DECLS
+_locale_category_t     *_find_category(int);
+const char             *_get_locale_env(const char *);
+struct _locale_impl_t  **_current_locale(void);
+char                   *__setlocale(int, const char *);
+__END_DECLS
+
+static __inline struct _locale_cache_t *
+_current_cache(void)
+{
+       return (*_current_locale())->cache;
+}
+
+extern struct _locale_impl_t   _global_locale;
+extern size_t __mb_len_max_runtime;
+
+#endif /*_SETLOCALE_LOCAL_H_*/
diff --git a/lib/nbsd_libc/locale/towctrans.3 b/lib/nbsd_libc/locale/towctrans.3
new file mode 100644 (file)
index 0000000..7772755
--- /dev/null
@@ -0,0 +1,87 @@
+.\" $NetBSD: towctrans.3,v 1.6 2005/06/27 14:18:36 wiz Exp $
+.\"
+.\" Copyright (c)2003 Citrus Project,
+.\" 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.
+.\"
+.Dd March 4, 2003
+.Dt TOWCTRANS 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm towctrans
+.Nd convert a wide character with a specified map
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In wctype.h
+.Ft wint_t
+.Fn towctrans "wint_t wc" "wctrans_t charmap"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn towctrans
+function converts a wide character
+.Fa wc
+with a character mapping
+.Fa charmap .
+.Pp
+The behaviour of
+.Fn towctrans
+is undefined if the
+.Fn towctrans
+function is called with an invalid
+.Fa charmap
+(changes of
+.Dv LC_CTYPE
+category invalidate
+.Fa charmap )
+or invalid wide character
+.Fa wc .
+.Pp
+The behaviour of
+.Fn towctrans
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn towctrans
+returns the resulting character of the conversion.
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+No errors are defined.
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr iswctype 3 ,
+.Xr setlocale 3 ,
+.Xr wctrans 3 ,
+.Xr wctype 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn towctrans
+function conforms to
+.St -isoC-amd1 .
diff --git a/lib/nbsd_libc/locale/towlower.3 b/lib/nbsd_libc/locale/towlower.3
new file mode 100644 (file)
index 0000000..f6a675b
--- /dev/null
@@ -0,0 +1,69 @@
+.\"    $NetBSD: towlower.3,v 1.7 2003/09/08 17:54:31 wiz Exp $
+.\"
+.\" Copyright (c) 1989, 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"    @(#)tolower.3   5.2 (Berkeley) 6/29/91
+.\"
+.Dd December 22, 2000
+.Dt TOWLOWER 3
+.Os
+.Sh NAME
+.Nm towlower
+.Nd wide character case letter conversion utilities
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wctype.h
+.Ft wint_t
+.Fn towlower "wint_t wc"
+.Ft wint_t
+.Fn towupper "wint_t wc"
+.Sh DESCRIPTION
+The
+.Fn towlower
+function converts an upper-case wide character to the corresponding lower-case
+letter.
+The
+.Fn towupper
+function converts an lower-case wide character to the corresponding upper-case
+letter.
+.Sh RETURN VALUES
+If the argument is an upper/lower-case letter, the
+.Fn tolower
+function returns the corresponding counterpart if there is
+one; otherwise the argument is returned unchanged.
+.Sh SEE ALSO
+.Xr tolower 3 ,
+.Xr toupper 3
+.Sh STANDARDS
+The functions conform to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/locale/wcrtomb.3 b/lib/nbsd_libc/locale/wcrtomb.3
new file mode 100644 (file)
index 0000000..fb03f05
--- /dev/null
@@ -0,0 +1,145 @@
+.\" $NetBSD: wcrtomb.3,v 1.9 2007/02/20 08:33:25 wiz Exp $
+.\"
+.\" Copyright (c)2002 Citrus Project,
+.\" 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.
+.\"
+.Dd February 4, 2002
+.Dt WCRTOMB 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm wcrtomb
+.Nd converts a wide character to a multibyte character (restartable)
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In wchar.h
+.Ft size_t
+.Fn wcrtomb "char * restrict s" "wchar_t wc" "mbstate_t * restrict ps"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+.Fn wcrtomb
+converts the wide character given by
+.Fa wc
+to the corresponding multibyte character, and stores it in the array
+pointed to by
+.Fa s
+unless
+.Fa s
+is a null pointer.
+This function will modify the first at most
+.Dv MB_CUR_MAX
+bytes of the array pointed to by
+.Fa s .
+.Pp
+The behaviour of
+.Fn wcrtomb
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.Pp
+These are the special cases:
+.Bl -tag -width 012345678901
+.It "wc == 0"
+For state-dependent encodings,
+.Fn wcrtomb
+stores a nul byte preceded by special byte sequence (if any)
+to return to an initial state in the array pointed to by
+.Fa s ,
+and the state object pointed to by
+.Fa ps
+also returns to an initial state.
+.It "s == NULL"
+.Fn wcrtomb
+just places
+.Fa ps
+into an initial state.
+It is equivalent to the following call:
+.Bd -literal -offset indent
+wcrtomb(buf, L'\\0', ps);
+.Ed
+.Pp
+Here,
+.Fa buf
+is a dummy buffer.
+In this case,
+.Fa wc
+is ignored.
+.It "ps == NULL"
+.Fn mbrtowc
+uses its own internal state object to keep the conversion state,
+instead of
+.Fa ps
+mentioned in this manual page.
+.Pp
+Calling any other functions in
+.Lb libc
+never changes the internal
+state of
+.Fn mbrtowc ,
+which is initialized at startup time of the program.
+.El
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn wcrtomb
+returns:
+.Bl -tag -width 012345678901
+.It "positive"
+The number of bytes (including any shift sequences)
+which are stored in the array.
+.It "(size_t)-1"
+.Fa wc
+is not a valid wide character.
+In this case,
+.Fn wcrtomb
+also sets
+.Va errno
+to indicate the error.
+.El
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+.Fn wcrtomb
+may cause an error in the following case:
+.Bl -tag -width Er
+.It Bq Er EILSEQ
+.Fa wc
+is not a valid wide character.
+.It Bq Er EINVAL
+.Fa ps
+points to an invalid or uninitialized mbstate_t object.
+.El
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr setlocale 3 ,
+.Xr wctomb 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn wcrtomb
+function conforms to
+.St -isoC-amd1 .
+The restrict qualifier is added at
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/locale/wcscoll.3 b/lib/nbsd_libc/locale/wcscoll.3
new file mode 100644 (file)
index 0000000..1e23815
--- /dev/null
@@ -0,0 +1,112 @@
+.\" $NetBSD: wcscoll.3,v 1.3 2010/12/16 17:42:27 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"    This product includes software developed by the University of
+.\"    California, Berkeley and its contributors.
+.\" 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.
+.\"
+.\"     @(#)strcoll.3  8.1 (Berkeley) 6/4/93
+.\" FreeBSD: src/lib/libc/string/strcoll.3,v 1.11 2001/10/01 16:09:00 ru Exp
+.\" FreeBSD: /repoman/r/ncvs/src/lib/libc/string/wcscoll.3,v 1.2 2002/12/09 14:04:05 ru Exp
+.\"
+.Dd October 13, 2006
+.Dt WCSCOLL 3
+.Os
+.Sh NAME
+.Nm wcscoll
+.Nd compare wide strings according to current collation
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wchar.h
+.Ft int
+.Fn wcscoll "const wchar_t *s1" "const wchar_t *s2"
+.Sh DESCRIPTION
+The
+.Fn wcscoll
+function compares the nul-terminated strings
+.Fa s1
+and
+.Fa s2
+according to the current locale collation order.
+In the
+.Dq Li C
+locale,
+.Fn wcscoll
+is equivalent to
+.Fn wcscmp .
+.Sh RETURN VALUES
+The
+.Fn wcscoll
+function returns an integer greater than, equal to, or less than
+0, if
+.Fa s1
+is greater than, equal to, or less than
+.Fa s2 .
+.Pp
+No return value is reserved to indicate errors;
+callers should set
+.Va errno
+to 0 before calling
+.Fn wcscoll .
+If it is non-zero upon return from
+.Fn wcscoll ,
+an error has occurred.
+.Sh ERRORS
+The
+.Fn wcscoll
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EILSEQ
+An invalid wide-character code was specified.
+.It Bq Er ENOMEM
+Cannot allocate enough memory for temporary buffers.
+.El
+.Sh SEE ALSO
+.Xr setlocale 3 ,
+.Xr strcoll 3 ,
+.Xr wcscmp 3 ,
+.Xr wcsxfrm 3
+.Sh STANDARDS
+The
+.Fn wcscoll
+function conforms to
+.St -isoC-99 .
+.Sh BUGS
+The current implementation of
+.Fn wcscoll
+function disregards
+.Dv LC_COLLATE
+locales, and falls back to using the
+.Fn wcscmp
+function.
diff --git a/lib/nbsd_libc/locale/wcscoll.c b/lib/nbsd_libc/locale/wcscoll.c
new file mode 100644 (file)
index 0000000..2e589f3
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: wcscoll.c,v 1.1 2003/03/02 22:18:16 tshiozak Exp $     */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcscoll.c,v 1.1 2003/03/02 22:18:16 tshiozak Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <wchar.h>
+
+/*
+ * Compare strings with using collating information.
+ */
+int
+wcscoll(s1, s2)
+       const wchar_t *s1, *s2;
+{
+       /* XXX: LC_COLLATE should be implemented. */
+       return (wcscmp(s1, s2));
+}
diff --git a/lib/nbsd_libc/locale/wcsftime.3 b/lib/nbsd_libc/locale/wcsftime.3
new file mode 100644 (file)
index 0000000..779593a
--- /dev/null
@@ -0,0 +1,69 @@
+.\" $NetBSD: wcsftime.3,v 1.2 2005/04/06 21:39:17 kleink Exp $
+.\"
+.\" Copyright (c) 2002 Tim J. Robbins
+.\" 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.
+.\"
+.\" $FreeBSD: /repoman/r/ncvs/src/lib/libc/locale/wcsftime.3,v 1.2 2002/11/29 17:35:09 ru Exp $
+.\"
+.Dd September 8, 2002
+.Dt WCSFTIME 3
+.Os
+.Sh NAME
+.Nm wcsftime
+.Nd "convert date and time to a wide-character string"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wchar.h
+.Ft size_t
+.Fo wcsftime
+.Fa "wchar_t * restrict wcs" "size_t maxsize"
+.Fa "const wchar_t * restrict format" "const struct tm * restrict timeptr"
+.Fc
+.Sh DESCRIPTION
+The
+.Fn wcsftime
+function is equivalent to the
+.Fn strftime
+function except for the types of its arguments
+and the return value indicating the number of wide characters.
+Refer to
+.Xr strftime 3
+for a detailed description.
+.Sh COMPATIBILITY
+Some early implementations of
+.Fn wcsftime
+had a
+.Fa format
+argument with type
+.Vt "const char *"
+instead of
+.Vt "const wchar_t *" .
+.Sh SEE ALSO
+.Xr strftime 3
+.Sh STANDARDS
+The
+.Fn wcsftime
+function conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/locale/wcsftime.c b/lib/nbsd_libc/locale/wcsftime.c
new file mode 100644 (file)
index 0000000..2816ae1
--- /dev/null
@@ -0,0 +1,108 @@
+/*      $NetBSD: wcsftime.c,v 1.3 2007/05/21 15:32:17 tnozaki Exp $    */
+/*-
+ * Copyright (c) 2002 Tim J. Robbins
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/locale/wcsftime.c,v 1.4 2004/04/07 09:47:56 tjr Exp $");
+#else
+__RCSID("$NetBSD: wcsftime.c,v 1.3 2007/05/21 15:32:17 tnozaki Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <time.h>
+#include <wchar.h>
+
+/*
+ * Convert date and time to a wide-character string.
+ *
+ * This is the wide-character counterpart of strftime(). So that we do not
+ * have to duplicate the code of strftime(), we convert the format string to
+ * multibyte, call strftime(), then convert the result back into wide
+ * characters.
+ *
+ * This technique loses in the presence of stateful multibyte encoding if any
+ * of the conversions in the format string change conversion state. When
+ * stateful encoding is implemented, we will need to reset the state between
+ * format specifications in the format string.
+ */
+size_t
+wcsftime(wchar_t *wcs, size_t maxsize,
+    const wchar_t *format, const struct tm *timeptr)
+{
+       char *dst, *dstp, *sformat;
+       size_t n, sflen;
+       int sverrno;
+
+       sformat = dst = NULL;
+
+       /*
+        * Convert the supplied format string to a multibyte representation
+        * for strftime(), which only handles single-byte characters.
+        */
+       sflen = wcstombs(NULL, format, 0);
+       if (sflen == (size_t)-1)
+               goto error;
+       if ((sformat = malloc(sflen + 1)) == NULL)
+               goto error;
+       wcstombs(sformat, format, sflen + 1);
+
+       /*
+        * Allocate memory for longest multibyte sequence that will fit
+        * into the caller's buffer and call strftime() to fill it.
+        * Then, copy and convert the result back into wide characters in
+        * the caller's buffer.
+        */
+       if (SIZE_T_MAX / MB_CUR_MAX <= maxsize) {
+               /* maxsize is preposterously large - avoid int. overflow. */
+               errno = EINVAL;
+               goto error;
+       }
+       dst = malloc(maxsize * MB_CUR_MAX);
+       if (dst == NULL)
+               goto error;
+       if (strftime(dst, maxsize, sformat, timeptr) == 0)
+               goto error;
+       dstp = dst;
+       n = mbstowcs(wcs, dstp, maxsize);
+       if (n == (size_t)-2 || n == (size_t)-1)
+               goto error;
+
+       free(sformat);
+       free(dst);
+       return n;
+
+error:
+       sverrno = errno;
+       free(sformat);
+       free(dst);
+       errno = sverrno;
+       return 0;
+}
diff --git a/lib/nbsd_libc/locale/wcsrtombs.3 b/lib/nbsd_libc/locale/wcsrtombs.3
new file mode 100644 (file)
index 0000000..1f30eb9
--- /dev/null
@@ -0,0 +1,176 @@
+.\" $NetBSD: wcsrtombs.3,v 1.13 2010/12/16 17:42:27 wiz Exp $
+.\"
+.\" Copyright (c)2002 Citrus Project,
+.\" 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.
+.\"
+.Dd August 8, 2006
+.Dt WCSRTOMBS 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm wcsrtombs
+.Nd converts a wide-character string to a multibyte character string \
+(restartable)
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In wchar.h
+.Ft size_t
+.Fn wcsrtombs "char * restrict s" "const wchar_t ** restrict pwcs" \
+"size_t n" "mbstate_t * restrict ps"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn wcsrtombs
+converts the nul-terminated wide-character string indirectly pointed
+to by
+.Fa pwcs
+to the corresponding multibyte character string,
+and stores it in the array pointed to by
+.Fa s .
+The conversion stops due to the following reasons:
+.Bl -bullet
+.It
+The conversion reaches a nul wide character.
+In this case, the nul wide character is also converted.
+.It
+The
+.Fn wcsrtombs
+has already stored
+.Fa n
+bytes in the array pointed to by
+.Fa s .
+.It
+The conversion encounters an invalid character.
+.El
+.Pp
+Each character will be converted as if
+.Xr wcrtomb 3
+is continuously called, except the internal state of
+.Xr wcrtomb 3
+will not be affected.
+.Pp
+After conversion,
+if
+.Fa s
+is not a null pointer, the pointer object pointed to by
+.Fa pwcs
+is a null pointer (if the conversion is stopped due to reaching a
+nul wide character) or the first byte of the character just after
+the last character converted.
+.Pp
+If
+.Fa s
+is not a null pointer and the conversion is stopped due to reaching
+a nul wide character,
+.Fn wcsrtombs
+places the state object pointed to by
+.Fa ps
+to an initial state after the conversion is taken place.
+.Pp
+The behaviour of
+.Fn wcsrtombs
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.Pp
+These are the special cases:
+.Bl -tag -width 012345678901
+.It "s == NULL"
+.Fn wcsrtombs
+returns the number of bytes to store the whole multibyte character string
+corresponding to the wide-character string pointed to by
+.Fa pwcs ,
+not including the terminating nul byte.
+In this case,
+.Fa n
+is ignored.
+.It "pwcs == NULL || *pwcs == NULL"
+Undefined (may cause the program to crash).
+.It "ps == NULL"
+.Fn wcsrtombs
+uses its own internal state object to keep the conversion state,
+instead of
+.Fa ps
+mentioned in this manual page.
+.Pp
+Calling any other functions in
+.Lb libc
+never changes the internal
+state of
+.Fn wcsrtombs ,
+which is initialized at startup time of the program.
+.El
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn wcsrtombs
+returns:
+.Bl -tag -width 012345678901
+.It 0 or positive
+Number of bytes stored in the array pointed to by
+.Fa s ,
+except for a nul byte.
+There are no cases that the value returned is greater than
+.Fa n
+(unless
+.Fa s
+is a null pointer).
+If the return value is equal to
+.Fa n ,
+the string pointed to by
+.Fa s
+will not be nul-terminated.
+.It (size_t)-1
+.Fa pwcs
+points to a string containing an invalid wide character.
+The
+.Fn wcsrtombs
+also sets
+.Va errno
+to indicate the error.
+.El
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+.Fn wcsrtombs
+may cause an error in the following case:
+.Bl -tag -width Er
+.It Bq Er EILSEQ
+.Fa pwcs
+points to a string containing an invalid wide character.
+.El
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr setlocale 3 ,
+.Xr wcrtomb 3 ,
+.Xr wcstombs 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn wcsrtombs
+function conforms to
+.St -ansiC .
+The restrict qualifier is added at
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/locale/wcstod.3 b/lib/nbsd_libc/locale/wcstod.3
new file mode 100644 (file)
index 0000000..965527f
--- /dev/null
@@ -0,0 +1,78 @@
+.\" $NetBSD: wcstod.3,v 1.5 2007/05/21 15:29:51 tnozaki Exp $
+.\"
+.\" Copyright (c) 2002, 2003 Tim J. Robbins
+.\" 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.
+.\"
+.\" $FreeBSD: wcstod.3,v 1.4 2003/05/22 13:02:27 ru Exp $
+.\"
+.Dd February 22, 2003
+.Dt WCSTOD 3
+.Os
+.Sh NAME
+.Nm wcstof ,
+.Nm wcstod ,
+.Nm wcstold
+.Nd convert string to
+.Vt float , double ,
+or
+.Vt "long double"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wchar.h
+.Ft float
+.Fn wcstof "const wchar_t * restrict nptr" "wchar_t ** restrict endptr"
+.Ft "long double"
+.Fn wcstold "const wchar_t * restrict nptr" "wchar_t ** restrict endptr"
+.Ft double
+.Fn wcstod "const wchar_t * restrict nptr" "wchar_t ** restrict endptr"
+.Sh DESCRIPTION
+The
+.Fn wcstof ,
+.Fn wcstod ,
+and
+.Fn wcstold
+functions are the wide-character versions of the
+.Fn strtof ,
+.Fn strtod ,
+and
+.Fn strtold
+functions.
+Refer to
+.Xr strtod 3
+for details.
+.Sh SEE ALSO
+.Xr strtod 3 ,
+.Xr wcstol 3
+.Sh STANDARDS
+The
+.Fn wcstod
+function conforms to
+.St -isoC-amd1 .
+The
+.Fn wcstof
+and
+.Fn wcstold
+functions conform to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/locale/wcstod.c b/lib/nbsd_libc/locale/wcstod.c
new file mode 100644 (file)
index 0000000..849dfd2
--- /dev/null
@@ -0,0 +1,50 @@
+/* $NetBSD: wcstod.c,v 1.14 2008/04/25 16:43:00 christos Exp $ */
+
+/*-
+ * Copyright (c)2006 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcstod.c,v 1.14 2008/04/25 16:43:00 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+#include <wchar.h>
+#include <wctype.h>
+
+__weak_alias(wcstod,_wcstod)
+
+#define _FUNCNAME      wcstod
+#define _RETURN_TYPE   double
+#define _STRTOD_FUNC   strtod
+
+#include "_wcstod.h"
diff --git a/lib/nbsd_libc/locale/wcstof.c b/lib/nbsd_libc/locale/wcstof.c
new file mode 100644 (file)
index 0000000..9b4e436
--- /dev/null
@@ -0,0 +1,50 @@
+/* $NetBSD: wcstof.c,v 1.3 2008/04/25 16:43:00 christos Exp $ */
+
+/*-
+ * Copyright (c)2006 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcstof.c,v 1.3 2008/04/25 16:43:00 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+#include <wchar.h>
+#include <wctype.h>
+
+__weak_alias(wcstof,_wcstof)
+
+#define _FUNCNAME      wcstof
+#define _RETURN_TYPE   float
+#define _STRTOD_FUNC   strtof
+
+#include "_wcstod.h"
diff --git a/lib/nbsd_libc/locale/wcstoimax.c b/lib/nbsd_libc/locale/wcstoimax.c
new file mode 100644 (file)
index 0000000..7b5ea95
--- /dev/null
@@ -0,0 +1,49 @@
+/* $NetBSD: wcstoimax.c,v 1.3 2007/03/10 00:12:23 hubertf Exp $ */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcstoimax.c,v 1.3 2007/03/10 00:12:23 hubertf Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#include "__wctoint.h"
+
+#define        _FUNCNAME       wcstoimax
+#define        __INT           intmax_t
+#define        __INT_MIN       INTMAX_MIN
+#define        __INT_MAX       INTMAX_MAX
+
+#include "_wcstol.h"
diff --git a/lib/nbsd_libc/locale/wcstol.3 b/lib/nbsd_libc/locale/wcstol.3
new file mode 100644 (file)
index 0000000..5499285
--- /dev/null
@@ -0,0 +1,96 @@
+.\" $NetBSD: wcstol.3,v 1.3 2010/12/16 17:42:27 wiz Exp $
+.\"
+.\" Copyright (c) 2002 Tim J. Robbins
+.\" 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.
+.\"
+.\" $FreeBSD: src/lib/libc/locale/wcstol.3,v 1.4 2002/11/29 17:35:09 ru Exp $
+.\"
+.Dd September 7, 2002
+.Dt WCSTOL 3
+.Os
+.Sh NAME
+.Nm wcstol , wcstoul ,
+.Nm wcstoll , wcstoull ,
+.Nm wcstoimax , wcstoumax
+.Nd "convert a wide-character string value to a"
+.Vt long ,
+.Vt "unsigned long" ,
+.Vt "long long" ,
+.Vt "unsigned long long" ,
+.Vt intmax_t
+or
+.Vt uintmax_t
+integer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wchar.h
+.Ft long
+.Fn wcstol "const wchar_t * restrict nptr" "wchar_t ** restrict endptr" "int base"
+.Ft "unsigned long"
+.Fn wcstoul "const wchar_t * restrict nptr" "wchar_t ** restrict endptr" "int base"
+.Ft "long long"
+.Fn wcstoll "const wchar_t * restrict nptr" "wchar_t ** restrict endptr" "int base"
+.Ft "unsigned long long"
+.Fn wcstoull "const wchar_t * restrict nptr" "wchar_t ** restrict endptr" "int base"
+.In inttypes.h
+.Ft intmax_t
+.Fn wcstoimax "const wchar_t * restrict nptr" "wchar_t ** restrict endptr" "int base"
+.Ft uintmax_t
+.Fn wcstoumax "const wchar_t * restrict nptr" "wchar_t ** restrict endptr" "int base"
+.Sh DESCRIPTION
+The
+.Fn wcstol ,
+.Fn wcstoul ,
+.Fn wcstoll ,
+.Fn wcstoull ,
+.Fn wcstoimax
+and
+.Fn wcstoumax
+functions are wide-character versions of the
+.Fn strtol ,
+.Fn strtoul ,
+.Fn strtoll ,
+.Fn strtoull ,
+.Fn strtoimax
+and
+.Fn strtoumax
+functions, respectively.
+Refer to their manual pages (for example
+.Xr strtol 3 )
+for details.
+.Sh SEE ALSO
+.Xr strtol 3 ,
+.Xr strtoul 3
+.Sh STANDARDS
+The
+.Fn wcstol ,
+.Fn wcstoul ,
+.Fn wcstoll ,
+.Fn wcstoull ,
+.Fn wcstoimax
+and
+.Fn wcstoumax
+functions conform to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/locale/wcstol.c b/lib/nbsd_libc/locale/wcstol.c
new file mode 100644 (file)
index 0000000..0bb35b7
--- /dev/null
@@ -0,0 +1,48 @@
+/* $NetBSD: wcstol.c,v 1.4 2007/03/10 00:12:23 hubertf Exp $ */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcstol.c,v 1.4 2007/03/10 00:12:23 hubertf Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#include "__wctoint.h"
+
+#define        _FUNCNAME       wcstol
+#define        __INT           long
+#define        __INT_MIN       LONG_MIN
+#define        __INT_MAX       LONG_MAX
+
+#include "_wcstol.h"
diff --git a/lib/nbsd_libc/locale/wcstold.c b/lib/nbsd_libc/locale/wcstold.c
new file mode 100644 (file)
index 0000000..a9eaab8
--- /dev/null
@@ -0,0 +1,50 @@
+/* $NetBSD: wcstold.c,v 1.3 2008/07/08 00:23:28 gmcgarry Exp $ */
+
+/*-
+ * Copyright (c)2006 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcstold.c,v 1.3 2008/07/08 00:23:28 gmcgarry Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+#include <wchar.h>
+#include <wctype.h>
+
+__weak_alias(wcstold,_wcstold)
+
+#define _FUNCNAME      wcstold
+#define _RETURN_TYPE   long double
+#define _STRTOD_FUNC   strtold
+
+#include "_wcstod.h"
diff --git a/lib/nbsd_libc/locale/wcstoll.c b/lib/nbsd_libc/locale/wcstoll.c
new file mode 100644 (file)
index 0000000..332d876
--- /dev/null
@@ -0,0 +1,48 @@
+/* $NetBSD: wcstoll.c,v 1.3 2007/03/10 00:12:23 hubertf Exp $ */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcstoll.c,v 1.3 2007/03/10 00:12:23 hubertf Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#include "__wctoint.h"
+
+#define        _FUNCNAME       wcstoll
+#define        __INT           /* LONGLONG */ long long int
+#define        __INT_MIN       LLONG_MIN
+#define        __INT_MAX       LLONG_MAX
+
+#include "_wcstol.h"
diff --git a/lib/nbsd_libc/locale/wcstombs.3 b/lib/nbsd_libc/locale/wcstombs.3
new file mode 100644 (file)
index 0000000..3b426fe
--- /dev/null
@@ -0,0 +1,132 @@
+.\" $NetBSD: wcstombs.3,v 1.12 2010/12/16 17:42:27 wiz Exp $
+.\"
+.\" Copyright (c)2002 Citrus Project,
+.\" 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.
+.\"
+.Dd August 8, 2006
+.Dt WCSTOMBS 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm wcstombs
+.Nd converts a wide-character string to a multibyte character string
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft size_t
+.Fn wcstombs "char * restrict s" "const wchar_t * restrict pwcs" "size_t n"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+.Fn wcstombs
+converts the nul-terminated wide-character string pointed to by
+.Fa pwcs
+to the corresponding multibyte character string,
+and stores it in the array pointed to by
+.Fa s .
+This function may modify the first at most
+.Fa n
+bytes of the array pointed to by
+.Fa s .
+Each character will be converted as if
+.Xr wctomb 3
+is continuously called, except the internal state of
+.Xr wctomb 3
+will not be affected.
+.Pp
+For state-dependent encoding, the
+.Fn wcstombs
+implies the result multibyte character string pointed to by
+.Fa s
+always to begin with an initial state.
+.Pp
+The behaviour of
+.Fn wcstombs
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.Pp
+These are the special cases:
+.Bl -tag -width 012345678901
+.It s == NULL
+The
+.Fn wcstombs
+returns the number of bytes to store the whole multibyte character string
+corresponding to the wide-character string pointed to by
+.Fa pwcs .
+In this case,
+.Fa n
+is ignored.
+.It pwcs == NULL
+Undefined (may cause the program to crash).
+.El
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn wcstombs
+returns:
+.Bl -tag -width 012345678901
+.It 0 or positive
+Number of bytes stored in the array pointed to by
+.Fa s .
+There are no cases that the value returned is greater than
+.Fa n
+(unless
+.Fa s
+is a null pointer).
+If the return value is equal to
+.Fa n ,
+the string pointed to by
+.Fa s
+will not be nul-terminated.
+.It (size_t)-1
+.Fa pwcs
+points to a string containing an invalid wide character.
+.Fn wcstombs
+also sets
+.Va errno
+to indicate the error.
+.El
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+.Fn wcstombs
+may cause an error in the following case:
+.Bl -tag -width Er
+.It Bq Er EILSEQ
+.Fa pwcs
+points to a string containing an invalid wide character.
+.El
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr setlocale 3 ,
+.Xr wctomb 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn wcstombs
+function conforms to
+.St -ansiC .
+The restrict qualifier is added at
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/locale/wcstoul.c b/lib/nbsd_libc/locale/wcstoul.c
new file mode 100644 (file)
index 0000000..a29d610
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: wcstoul.c,v 1.4 2007/03/10 00:12:23 hubertf Exp $      */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcstoul.c,v 1.4 2007/03/10 00:12:23 hubertf Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#include "__wctoint.h"
+
+#define        _FUNCNAME       wcstoul
+#define        __UINT          unsigned long
+#define        __UINT_MAX      ULONG_MAX
+
+#include "_wcstoul.h"
diff --git a/lib/nbsd_libc/locale/wcstoull.c b/lib/nbsd_libc/locale/wcstoull.c
new file mode 100644 (file)
index 0000000..6ef7402
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: wcstoull.c,v 1.3 2007/03/10 00:12:23 hubertf Exp $     */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcstoull.c,v 1.3 2007/03/10 00:12:23 hubertf Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#include "__wctoint.h"
+
+#define        _FUNCNAME       wcstoull
+#define        __UINT          /* LONGLONG */ unsigned long long int
+#define        __UINT_MAX      ULLONG_MAX
+
+#include "_wcstoul.h"
diff --git a/lib/nbsd_libc/locale/wcstoumax.c b/lib/nbsd_libc/locale/wcstoumax.c
new file mode 100644 (file)
index 0000000..fc11ec5
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: wcstoumax.c,v 1.3 2007/03/10 00:12:23 hubertf Exp $    */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcstoumax.c,v 1.3 2007/03/10 00:12:23 hubertf Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#include "__wctoint.h"
+
+#define        _FUNCNAME       wcstoumax
+#define        __UINT          uintmax_t
+#define        __UINT_MAX      UINTMAX_MAX
+
+#include "_wcstoul.h"
diff --git a/lib/nbsd_libc/locale/wcsxfrm.3 b/lib/nbsd_libc/locale/wcsxfrm.3
new file mode 100644 (file)
index 0000000..96d07cc
--- /dev/null
@@ -0,0 +1,107 @@
+.\" $NetBSD: wcsxfrm.3,v 1.4 2010/12/16 17:42:27 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"    This product includes software developed by the University of
+.\"    California, Berkeley and its contributors.
+.\" 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.
+.\"
+.\"     @(#)strxfrm.3  8.1 (Berkeley) 6/4/93
+.\" FreeBSD: src/lib/libc/string/strxfrm.3,v 1.16 2002/09/06 11:24:06 tjr Exp
+.\" FreeBSD: /repoman/r/ncvs/src/lib/libc/string/wcsxfrm.3,v 1.2 2002/12/09 14:04:05 ru Exp
+.\"
+.Dd October 13, 2006
+.Dt WCSXFRM 3
+.Os
+.Sh NAME
+.Nm wcsxfrm
+.Nd transform a wide string under locale
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wchar.h
+.Ft size_t
+.Fn wcsxfrm "wchar_t * restrict dst" "const wchar_t * restrict src" "size_t n"
+.Sh DESCRIPTION
+The
+.Fn wcsxfrm
+function transforms a nul-terminated wide-character string pointed to by
+.Fa src
+according to the current locale collation order then copies the
+transformed string into
+.Fa dst .
+No more than
+.Fa n
+wide characters are copied into
+.Fa dst ,
+including the terminating nul character added.
+If
+.Fa n
+is set to 0
+(it helps to determine an actual size needed for transformation),
+.Fa dst
+is permitted to be a null pointer.
+.Pp
+Comparing two strings using
+.Fn wcscmp
+after
+.Fn wcsxfrm
+is equivalent to comparing two original strings with
+.Fn wcscoll .
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn wcsxfrm
+returns the length of the transformed string not including
+the terminating nul character.
+If this value is
+.Fa n
+or more, the contents of
+.Fa dst
+are indeterminate.
+.Sh SEE ALSO
+.Xr setlocale 3 ,
+.Xr strxfrm 3 ,
+.Xr wcscmp 3 ,
+.Xr wcscoll 3
+.Sh STANDARDS
+The
+.Fn wcsxfrm
+function conforms to
+.St -isoC-99 .
+.Sh BUGS
+The current implementation of
+.Fn wcsxfrm
+function disregards
+.Dv LC_COLLATE
+locales, and falls back to using the
+.Fn wcsncpy
+function.
diff --git a/lib/nbsd_libc/locale/wcsxfrm.c b/lib/nbsd_libc/locale/wcsxfrm.c
new file mode 100644 (file)
index 0000000..87b68ec
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: wcsxfrm.c,v 1.2 2006/10/15 16:14:08 christos Exp $     */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcsxfrm.c,v 1.2 2006/10/15 16:14:08 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <wchar.h>
+
+/*
+ * Compare strings with using collating information.
+ */
+size_t
+wcsxfrm(s1, s2, n)
+       wchar_t *s1;
+       const wchar_t *s2;
+       size_t n;
+{
+       size_t len;
+
+       /* XXX: LC_COLLATE should be implemented. */
+
+       len = wcslen(s2);
+       if (len<n)
+               wcscpy(s1, s2);
+       else {
+               /*
+                * SUSv3 says:
+                *   If the value returned is n or more, the contents
+                *   of the array pointed to by ws1 are unspecified.
+                */
+               /* thus, do nothing */
+       }
+
+       return (len);
+}
diff --git a/lib/nbsd_libc/locale/wctob.3 b/lib/nbsd_libc/locale/wctob.3
new file mode 100644 (file)
index 0000000..f12de66
--- /dev/null
@@ -0,0 +1,87 @@
+.\" $NetBSD: wctob.3,v 1.4 2004/01/24 16:58:54 wiz Exp $
+.\"
+.\" Copyright (c)2003 Citrus Project,
+.\" 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.
+.\"
+.Dd March 3, 2003
+.Dt WCTOB 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm wctob
+.Nd convert a wide character to a single byte character
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In wchar.h
+.Ft int
+.Fn wctob "wint_t wc"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn wctob
+function converts a wide character
+.Fa wc
+to a corresponding single byte character in the initial shift state of
+the current locale.
+.Pp
+The behaviour of
+.Fn wctob
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+The
+.Fn wctob
+function returns:
+.Bl -tag -width 012345678901
+.It Dv EOF
+If
+.Fa wc
+is
+.Dv WEOF
+or if
+.Fa wc
+does not correspond to a valid single byte character representation.
+.It (otherwise)
+A single byte character corresponding to
+.Fa wc .
+.El
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+No errors are defined.
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr btowc 3 ,
+.Xr setlocale 3 ,
+.Xr wcrtomb 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn wctob
+function conforms to
+.St -isoC-amd1 .
diff --git a/lib/nbsd_libc/locale/wctomb.3 b/lib/nbsd_libc/locale/wctomb.3
new file mode 100644 (file)
index 0000000..9ce3fbb
--- /dev/null
@@ -0,0 +1,131 @@
+.\" $NetBSD: wctomb.3,v 1.5 2006/10/14 07:51:01 wiz Exp $
+.\"
+.\" Copyright (c)2002 Citrus Project,
+.\" 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.
+.\"
+.Dd February 3, 2002
+.Dt WCTOMB 3
+.Os
+.Sh NAME
+.Nm wctomb
+.Nd converts a wide character to a multibyte character
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn wctomb "char * s" "const wchar_t wchar"
+.Sh DESCRIPTION
+The
+.Fn wctomb
+converts the wide character
+.Fa wchar
+to the corresponding multibyte character, and stores it in the array
+pointed to by
+.Fa s .
+.Fn wctomb
+may store at most
+.Dv MB_CUR_MAX
+bytes in the array.
+.Pp
+In state-dependent encoding,
+.Fn wctomb
+may store the special sequence to change the conversion state
+before an actual multibyte character into the array pointed to by
+.Fa s .
+If
+.Fa wchar
+is a nul wide character
+.Pq Sq \e0 ,
+this function sets its own internal state to an initial conversion state.
+.Pp
+Calling any other functions in
+.Lb libc
+never changes the internal state of
+.Fn wctomb ,
+except changing the
+.Dv LC_CTYPE
+category of the current locale by calling
+.Xr setlocale 3 .
+Such
+.Xr setlocale 3
+calls cause the internal state of this function to be indeterminate.
+.Pp
+The behaviour of
+.Fn wctomb
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.Pp
+There is one special case:
+.Bl -tag -width 012345678901
+.It s == NULL
+.Fn wctomb
+initializes its own internal state to an initial state, and
+determines whether the current encoding is state-dependent.
+This function returns 0 if the encoding is state-independent,
+otherwise non-zero.
+In this case,
+.Fa wchar
+is completely ignored.
+.El
+.Sh RETURN VALUES
+Normally,
+.Fn wctomb
+returns:
+.Bl -tag -width 012345678901
+.It positive
+Number of bytes for the valid multibyte character pointed to by
+.Fa s .
+There are no cases that the value returned is greater than
+.Fa n
+or the value of the
+.Dv MB_CUR_MAX
+macro.
+.It -1
+.Fa wchar
+is an invalid wide character.
+.El
+.Pp
+If
+.Fa s
+is equal to
+.Dv NULL ,
+.Fn mbtowc
+returns:
+.Bl -tag -width 0123456789
+.It 0
+The current encoding is state-independent.
+.It non-zero
+The current encoding is state-dependent.
+.El
+.Sh ERRORS
+No errors are defined.
+.Sh SEE ALSO
+.Xr setlocale 3
+.Sh STANDARDS
+The
+.Fn wctomb
+function conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/locale/wctrans.3 b/lib/nbsd_libc/locale/wctrans.3
new file mode 100644 (file)
index 0000000..9d412aa
--- /dev/null
@@ -0,0 +1,89 @@
+.\" $NetBSD: wctrans.3,v 1.4 2004/01/24 16:58:54 wiz Exp $
+.\"
+.\" Copyright (c)2003 Citrus Project,
+.\" 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.
+.\"
+.Dd March 4, 2003
+.Dt WCTRANS 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm wctrans
+.Nd get character mapping identifier by name
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In wctype.h
+.Ft wctrans_t
+.Fn wctrans "const char *charmap"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn wctrans
+function returns a character mapping identifier corresponding to the
+locale-specific character mapping name
+.Fa charmap .
+This identifier can be used on the subsequent calls of
+.Fn towctrans .
+The following names are defined in all locales:
+.Bd -literal -offset indent
+tolower toupper
+.Ed
+.Pp
+The behaviour of
+.Fn wctrans
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn wctrans
+returns:
+.Bl -tag -width 012345678901
+.It 0
+If the string
+.Fa charmap
+does not corresponding to a valid character mapping name.
+.It non-zero
+A character mapping identifier corresponding to
+.Fa charmap .
+.El
+.Pp
+Note: wctype_t is a scalar type, e.g., a pointer.
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+No errors are defined.
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr iswctype 3 ,
+.Xr setlocale 3 ,
+.Xr wctype 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn towctrans
+function conforms to
+.St -isoC-amd1 .
diff --git a/lib/nbsd_libc/locale/wctype.3 b/lib/nbsd_libc/locale/wctype.3
new file mode 100644 (file)
index 0000000..fd92f8f
--- /dev/null
@@ -0,0 +1,91 @@
+.\" $NetBSD: wctype.3,v 1.6 2007/05/21 15:20:40 tnozaki Exp $
+.\"
+.\" Copyright (c)2003 Citrus Project,
+.\" 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.
+.\"
+.Dd March 4, 2003
+.Dt WCTYPE 3
+.Os
+.\" ----------------------------------------------------------------------
+.Sh NAME
+.Nm wctype
+.Nd get character class identifier by name
+.\" ----------------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ----------------------------------------------------------------------
+.Sh SYNOPSIS
+.In wctype.h
+.Ft wctype_t
+.Fn wctype "const char *charclass"
+.\" ----------------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn wctype
+function returns a character class identifier corresponding to the
+locale-specific character class name
+.Fa charclass .
+This identifier can be used in subsequent calls of
+.Fn iswctype .
+The following names are defined in all locales:
+.Bd -literal -offset indent
+alnum alpha blank cntrl digit graph
+lower print punct space upper xdigit
+.Ed
+.Pp
+The behaviour of
+.Fn wctype
+is affected by the
+.Dv LC_CTYPE
+category of the current locale.
+.\" ----------------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn wctype
+returns:
+.Bl -tag -width 012345678901
+.It 0
+If
+.Fa charclass
+does not correspond to a valid character class name.
+.It non-zero
+A character class identifier corresponding to
+.Fa charclass .
+.El
+.Pp
+Note: wctype_t is a scalar type, e.g., a pointer.
+.\" ----------------------------------------------------------------------
+.Sh ERRORS
+No errors are defined.
+.\" ----------------------------------------------------------------------
+.Sh SEE ALSO
+.Xr iswctype 3 ,
+.Xr setlocale 3 ,
+.Xr towctrans 3 ,
+.Xr wctrans 3
+.\" ----------------------------------------------------------------------
+.Sh STANDARDS
+The
+.Fn wctype
+function conforms to
+.St -isoC-amd1 .
diff --git a/lib/nbsd_libc/locale/wcwidth.3 b/lib/nbsd_libc/locale/wcwidth.3
new file mode 100644 (file)
index 0000000..9c7fab4
--- /dev/null
@@ -0,0 +1,89 @@
+.\" $NetBSD: wcwidth.3,v 1.3 2006/10/14 07:51:01 wiz Exp $
+.\" FreeBSD: src/lib/libc/locale/wcwidth.3,v 1.6 2004/08/17 04:56:03 trhodes Exp
+.\"
+.\" Copyright (c) 2002 Tim J. Robbins
+.\" 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.
+.\"
+.\"
+.Dd August 17, 2004
+.Dt WCWIDTH 3
+.Os
+.Sh NAME
+.Nm wcwidth
+.Nd "number of column positions of a wide-character code"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wchar.h
+.Ft int
+.Fn wcwidth "wchar_t wc"
+.Sh DESCRIPTION
+The
+.Fn wcwidth
+function determines the number of column positions required to
+display the wide character
+.Fa wc .
+.Sh RETURN VALUES
+The
+.Fn wcwidth
+function returns 0 if the
+.Fa wc
+argument is a nul wide character (L'\e0'),
+\-1 if
+.Fa wc
+is not printable,
+otherwise it returns the number of column positions the
+character occupies.
+.Sh EXAMPLES
+This code fragment reads text from standard input and
+breaks lines that are more than 20 column positions wide,
+similar to the
+.Xr fold 1
+utility:
+.Bd -literal -offset indent
+wint_t ch;
+int column, w;
+
+column = 0;
+while ((ch = getwchar()) != WEOF) {
+       w = wcwidth(ch);
+       if (w \*[Gt] 0 \*[Am]\*[Am] column + w \*[Gt]= 20) {
+               putwchar(L'\en');
+               column = 0;
+       }
+       putwchar(ch);
+       if (ch == L'\en')
+               column = 0;
+       else if (w \*[Gt] 0)
+               column += w;
+}
+.Ed
+.Sh SEE ALSO
+.Xr iswprint 3 ,
+.Xr wcswidth 3
+.Sh STANDARDS
+The
+.Fn wcwidth
+function conforms to
+.St -p1003.1-2001 .
diff --git a/lib/nbsd_libc/md/Makefile.inc b/lib/nbsd_libc/md/Makefile.inc
new file mode 100644 (file)
index 0000000..5663753
--- /dev/null
@@ -0,0 +1,27 @@
+#      $NetBSD: Makefile.inc,v 1.7 2005/09/24 20:51:14 elad Exp $
+
+.include <bsd.own.mk>
+
+# MD4/MD5 sources
+.PATH: ${ARCHDIR}/md ${.CURDIR}/md
+
+SRCS+= md4c.c md5c.c md4hl.c md5hl.c
+
+MAN+=  md4.3 md5.3
+
+MLINKS+=md4.3 MD4Init.3 md4.3 MD4Update.3 md4.3 MD4Final.3
+MLINKS+=md4.3 MD4End.3  md4.3 MD4File.3   md4.3 MD4Data.3
+MLINKS+=md5.3 MD5Init.3 md5.3 MD5Update.3 md5.3 MD5Final.3
+MLINKS+=md5.3 MD5End.3  md5.3 MD5File.3   md5.3 MD5Data.3
+
+CLEANFILES+=   md[45]hl.c md[45].3
+
+.if ${MKMAN} != "no"
+md4.3: mdX.3
+       sed -e 's/mdX/md4/g' -e 's/MDX/MD4/g' $> > $@
+       cat ${>:H}/md4.copyright >> $@
+
+md5.3: mdX.3
+       sed -e 's/mdX/md5/g' -e 's/MDX/MD5/g' $> > $@
+       cat ${>:H}/md5.copyright >> $@
+.endif
diff --git a/lib/nbsd_libc/md/md2hl.c b/lib/nbsd_libc/md/md2hl.c
new file mode 100644 (file)
index 0000000..8d26581
--- /dev/null
@@ -0,0 +1,24 @@
+/*     $NetBSD: md2hl.c,v 1.5 2005/06/12 05:34:34 lukem Exp $  */
+
+/*
+ * Written by Jason R. Thorpe <thorpej@NetBSD.org>, April 29, 1997.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: md2hl.c,v 1.5 2005/06/12 05:34:34 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define        MDALGORITHM     MD2
+
+#include "namespace.h"
+#include <md2.h>
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#if !HAVE_MD2_H
+#include "mdXhl.c"
+#endif
diff --git a/lib/nbsd_libc/md/md4.copyright b/lib/nbsd_libc/md/md4.copyright
new file mode 100644 (file)
index 0000000..5a395f0
--- /dev/null
@@ -0,0 +1,21 @@
+.\"    $NetBSD: md4.copyright,v 1.1 1997/01/30 01:01:40 thorpej Exp $
+.\" from FreeBSD Id: md4.copyright,v 1.2 1996/10/09 21:00:43 wollman Exp
+Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
+rights reserved.
+.Pp
+License to copy and use this software is granted provided that it
+is identified as the "RSA Data Security, Inc. MD4 Message-Digest
+Algorithm" in all material mentioning or referencing this software
+or this function.
+License is also granted to make and use derivative works provided
+that such works are identified as "derived from the RSA Data
+Security, Inc. MD4 Message-Digest Algorithm" in all material
+mentioning or referencing the derived work.
+.Pp
+RSA Data Security, Inc. makes no representations concerning either
+the merchantability of this software or the suitability of this
+software for any particular purpose. It is provided "as is"
+without express or implied warranty of any kind.
+.Pp
+These notices must be retained in any copies of any part of this
+documentation and/or software.
diff --git a/lib/nbsd_libc/md/md4hl.c b/lib/nbsd_libc/md/md4hl.c
new file mode 100644 (file)
index 0000000..4517bf1
--- /dev/null
@@ -0,0 +1,16 @@
+/*     $NetBSD: md4hl.c,v 1.7 2005/09/26 03:01:41 christos Exp $       */
+
+/*
+ * Written by Jason R. Thorpe <thorpej@NetBSD.org>, April 29, 1997.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: md4hl.c,v 1.7 2005/09/26 03:01:41 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define        MDALGORITHM     MD4
+#define MDINCLUDE      <md4.h>
+
+#include "mdXhl.c"
diff --git a/lib/nbsd_libc/md/md5.copyright b/lib/nbsd_libc/md/md5.copyright
new file mode 100644 (file)
index 0000000..b7e1bee
--- /dev/null
@@ -0,0 +1,22 @@
+.\"    $NetBSD: md5.copyright,v 1.1 1997/01/30 01:01:41 thorpej Exp $
+.\" from FreeBSD Id: md5.copyright,v 1.2 1996/10/09 21:00:46 wollman Exp
+Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
+rights reserved.
+.Pp
+License to copy and use this software is granted provided that it
+is identified as the "RSA Data Security, Inc. MD5 Message-Digest
+Algorithm" in all material mentioning or referencing this software
+or this function.
+.Pp
+License is also granted to make and use derivative works provided
+that such works are identified as "derived from the RSA Data
+Security, Inc. MD5 Message-Digest Algorithm" in all material
+mentioning or referencing the derived work.
+.Pp
+RSA Data Security, Inc. makes no representations concerning either
+the merchantability of this software or the suitability of this
+software for any particular purpose. It is provided "as is"
+without express or implied warranty of any kind.
+.Pp
+These notices must be retained in any copies of any part of this
+documentation and/or software.
diff --git a/lib/nbsd_libc/md/md5hl.c b/lib/nbsd_libc/md/md5hl.c
new file mode 100644 (file)
index 0000000..7604efa
--- /dev/null
@@ -0,0 +1,16 @@
+/*     $NetBSD: md5hl.c,v 1.7 2005/09/26 03:01:41 christos Exp $       */
+
+/*
+ * Written by Jason R. Thorpe <thorpej@NetBSD.org>, April 29, 1997.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: md5hl.c,v 1.7 2005/09/26 03:01:41 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define        MDALGORITHM     MD5
+#define MDINCLUDE      <md5.h>
+
+#include "mdXhl.c"
diff --git a/lib/nbsd_libc/md/mdX.3 b/lib/nbsd_libc/md/mdX.3
new file mode 100644 (file)
index 0000000..39934b5
--- /dev/null
@@ -0,0 +1,143 @@
+.\"    $NetBSD: mdX.3,v 1.10 2003/06/13 01:28:41 lukem Exp $
+.\"
+.\" ----------------------------------------------------------------------------
+.\" "THE BEER-WARE LICENSE" (Revision 42):
+.\" <phk@login.dkuug.dk> 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.   Poul-Henning Kamp
+.\" ----------------------------------------------------------------------------
+.\"
+.\"    from FreeBSD Id: mdX.3,v 1.7 1996/10/22 16:28:56 phk Exp
+.\"
+.Dd June 13, 2003
+.Dt MDX 3
+.Os
+.Sh NAME
+.Nm MDXInit ,
+.Nm MDXUpdate ,
+.Nm MDXFinal ,
+.Nm MDXEnd ,
+.Nm MDXFile ,
+.Nm MDXData
+.Nd calculate the RSA Data Security, Inc.,
+.Dq MDX
+message digest
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In mdX.h
+.Ft void
+.Fn MDXInit "MDX_CTX *context"
+.Ft void
+.Fn MDXUpdate "MDX_CTX *context" "const unsigned char *data" "unsigned int len"
+.Ft void
+.Fn MDXFinal "unsigned char digest[16]" "MDX_CTX *context"
+.Ft "char *"
+.Fn MDXEnd "MDX_CTX *context" "char *buf"
+.Ft "char *"
+.Fn MDXFile "const char *filename" "char *buf"
+.Ft "char *"
+.Fn MDXData "const unsigned char *data" "unsigned int len" "char *buf"
+.Sh DESCRIPTION
+The MDX functions calculate a 128-bit cryptographic checksum (digest)
+for any number of input bytes.
+A cryptographic checksum is a one-way
+hash-function, that is, you cannot find (except by exhaustive search)
+the input corresponding to a particular output.
+This net result is
+a ``fingerprint'' of the input-data, which doesn't disclose the actual
+input.
+.Pp
+MD2 is the slowest, MD4 is the fastest and MD5 is somewhere in the middle.
+MD2 can only be used for Privacy-Enhanced Mail.
+MD4 has been criticized for being too weak, so MD5 was developed in
+response as ``MD4 with safety-belts''.
+When in doubt, use MD5.
+.Pp
+The
+.Fn MDXInit ,
+.Fn MDXUpdate ,
+and
+.Fn MDXFinal
+functions are the core functions.
+Allocate an MDX_CTX, initialize it with
+.Fn MDXInit ,
+run over the data with
+.Fn MDXUpdate ,
+and finally extract the result using
+.Fn MDXFinal .
+.Pp
+.Fn MDXEnd
+is a wrapper for
+.Fn MDXFinal
+which converts the return value to a 33-character
+(including the terminating '\e0')
+.Tn ASCII
+string which represents the 128 bits in hexadecimal.
+.Pp
+.Fn MDXFile
+calculates the digest of a file, and uses
+.Fn MDXEnd
+to return the result.
+If the file cannot be opened, a null pointer is returned.
+.Fn MDXData
+calculates the digest of a chunk of data in memory, and uses
+.Fn MDXEnd
+to return the result.
+.Pp
+When using
+.Fn MDXEnd ,
+.Fn MDXFile ,
+or
+.Fn MDXData ,
+the
+.Ar buf
+argument can be a null pointer, in which case the returned string
+is allocated with
+.Xr malloc 3
+and subsequently must be explicitly deallocated using
+.Xr free 3
+after use.
+If the
+.Ar buf
+argument is non-null it must point to at least 33 characters of buffer space.
+.Sh SEE ALSO
+.Xr md2 3 ,
+.Xr md4 3 ,
+.Xr md5 3
+.Rs
+.%A B. Kaliski
+.%T The MD2 Message-Digest Algorithm
+.%O RFC 1319
+.Re
+.Rs
+.%A R. Rivest
+.%T The MD4 Message-Digest Algorithm
+.%O RFC 1186
+.Re
+.Rs
+.%A R. Rivest
+.%T The MD5 Message-Digest Algorithm
+.%O RFC 1321
+.Re
+.Rs
+.%A RSA Laboratories
+.%T Frequently Asked Questions About today's Cryptography
+.Re
+.Sh HISTORY
+These functions appeared in
+.Nx 1.3 .
+.Sh AUTHORS
+The original MDX routines were developed by
+.Tn RSA
+Data Security, Inc., and published in the above references.
+This code is derived directly from these implementations by Poul-Henning Kamp
+.Aq Li phk@login.dkuug.dk
+.Pp
+Phk ristede runen.
+.Sh BUGS
+No method is known to exist which finds two files having the same hash value,
+nor to find a file with a specific hash value.
+There is on the other hand no guarantee that such a method doesn't exist.
+.Sh COPYRIGHT
diff --git a/lib/nbsd_libc/md/mdXhl.c b/lib/nbsd_libc/md/mdXhl.c
new file mode 100644 (file)
index 0000000..69e0e25
--- /dev/null
@@ -0,0 +1,117 @@
+/*     $NetBSD: mdXhl.c,v 1.8 2009/03/06 18:15:24 apb Exp $    */
+
+/*
+ * ----------------------------------------------------------------------------
+ * "THE BEER-WARE LICENSE" (Revision 42):
+ * <phk@login.dkuug.dk> 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.   Poul-Henning Kamp
+ * ----------------------------------------------------------------------------
+ *
+ * from FreeBSD Id: mdXhl.c,v 1.8 1996/10/25 06:48:12 bde Exp
+ */
+
+/*
+ * Modified April 29, 1997 by Jason R. Thorpe <thorpej@NetBSD.org>
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#define        CONCAT(x,y)     __CONCAT(x,y)
+#define        MDNAME(x)       CONCAT(MDALGORITHM,x)
+
+#if !defined(_KERNEL) && defined(__weak_alias) && !defined(HAVE_NBTOOL_CONFIG_H)
+#define        WA(a,b) __weak_alias(a,b)
+WA(MDNAME(End),CONCAT(_,MDNAME(End)))
+WA(MDNAME(File),CONCAT(_,MDNAME(File)))
+WA(MDNAME(Data),CONCAT(_,MDNAME(Data)))
+#undef WA
+#endif
+
+#include "namespace.h"
+
+#include <sys/types.h>
+
+#include MDINCLUDE
+#include <assert.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+
+
+char *
+MDNAME(End)(ctx, buf)
+       MDNAME(_CTX) *ctx;
+       char *buf;
+{
+       int i;
+       unsigned char digest[16];
+       static const char hex[]="0123456789abcdef";
+
+       _DIAGASSERT(ctx != 0);
+
+       if (buf == NULL)
+               buf = malloc(33);
+       if (buf == NULL)
+               return (NULL);
+
+       MDNAME(Final)(digest, ctx);
+
+       for (i = 0; i < 16; i++) {
+               buf[i+i] = hex[(u_int32_t)digest[i] >> 4];
+               buf[i+i+1] = hex[digest[i] & 0x0f];
+       }
+
+       buf[i+i] = '\0';
+       return (buf);
+}
+
+char *
+MDNAME(File)(filename, buf)
+       const char *filename;
+       char *buf;
+{
+       unsigned char buffer[BUFSIZ];
+       MDNAME(_CTX) ctx;
+       int f, i, j;
+
+       _DIAGASSERT(filename != 0);
+       /* buf may be NULL */
+
+       MDNAME(Init)(&ctx);
+       f = open(filename, O_RDONLY, 0666);
+       if (f < 0)
+               return NULL;
+
+       while ((i = read(f, buffer, sizeof(buffer))) > 0)
+               MDNAME(Update)(&ctx, buffer, (unsigned int)i);
+
+       j = errno;
+       close(f);
+       errno = j;
+
+       if (i < 0)
+               return NULL;
+
+       return (MDNAME(End)(&ctx, buf));
+}
+
+char *
+MDNAME(Data)(data, len, buf)
+       const unsigned char *data;
+       unsigned int len;
+       char *buf;
+{
+       MDNAME(_CTX) ctx;
+
+       _DIAGASSERT(data != 0);
+
+       MDNAME(Init)(&ctx);
+       MDNAME(Update)(&ctx, data, len);
+       return (MDNAME(End)(&ctx, buf));
+}
diff --git a/lib/nbsd_libc/misc/Makefile.inc b/lib/nbsd_libc/misc/Makefile.inc
new file mode 100644 (file)
index 0000000..d5cb9ef
--- /dev/null
@@ -0,0 +1,10 @@
+#      $NetBSD: Makefile.inc,v 1.1 2007/11/13 15:21:20 ad Exp $
+#      @(#)Makefile.inc        8.3 (Berkeley) 10/24/94
+
+.PATH: ${.CURDIR}/misc
+
+# constructor
+SRCS+= initfini.c
+
+# for -fstack-protector
+SRCS+= stack_protector.c
diff --git a/lib/nbsd_libc/misc/initfini.c b/lib/nbsd_libc/misc/initfini.c
new file mode 100644 (file)
index 0000000..39d7f11
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: initfini.c,v 1.7 2010/11/14 18:11:42 tron Exp $         */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Andrew Doran.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: initfini.c,v 1.7 2010/11/14 18:11:42 tron Exp $");
+
+#ifdef _LIBC
+#include "namespace.h"
+#endif
+
+void   __libc_init(void) __attribute__((__constructor__, __used__));
+
+void   __guard_setup(void);
+void   __libc_thr_init(void);
+void   __libc_atomic_init(void);
+void   __libc_atexit_init(void);
+void   __libc_env_init(void);
+
+/* LINTED used */
+void
+__libc_init(void)
+{
+
+       /* For -fstack-protector */
+       __guard_setup();
+
+       /* Atomic operations */
+       __libc_atomic_init();
+
+       /* Threads */
+       __libc_thr_init();
+
+       /* Initialize the atexit mutexes */
+       __libc_atexit_init();
+
+       /* Initialize environment memory RB tree. */
+       __libc_env_init();
+}
diff --git a/lib/nbsd_libc/misc/stack_protector.c b/lib/nbsd_libc/misc/stack_protector.c
new file mode 100644 (file)
index 0000000..313982c
--- /dev/null
@@ -0,0 +1,126 @@
+/*     $NetBSD: stack_protector.c,v 1.5 2010/12/07 20:10:53 joerg Exp $        */
+/*     $OpenBSD: stack_protector.c,v 1.10 2006/03/31 05:34:44 deraadt Exp $    */
+
+/*
+ * Copyright (c) 2002 Hiroaki Etoh, Federico G. Schwindt, and Miodrag Vallat.
+ * 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 AUTHORS ``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 AUTHORS 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 <sys/cdefs.h>
+__RCSID("$NetBSD: stack_protector.c,v 1.5 2010/12/07 20:10:53 joerg Exp $");
+
+#ifdef _LIBC
+#include "namespace.h"
+#endif
+#include <sys/param.h>
+#include <sys/sysctl.h>
+#include <ssp/ssp.h>
+#include <signal.h>
+#include <string.h>
+#include <unistd.h>
+#ifdef _LIBC
+#include <syslog.h>
+#include "extern.h"
+#else
+#define __sysctl sysctl
+void xprintf(const char *fmt, ...);
+#include <stdlib.h>
+#endif
+
+long __stack_chk_guard[8] = {0, 0, 0, 0, 0, 0, 0, 0};
+static void __fail(const char *) __attribute__((__noreturn__));
+void __stack_chk_fail_local(void);
+void __guard_setup(void);
+
+void
+__guard_setup(void)
+{
+       int mib[2];
+       size_t len;
+
+       if (__stack_chk_guard[0] != 0)
+               return;
+
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_ARND;
+
+       len = sizeof(__stack_chk_guard);
+       if (__sysctl(mib, 2, __stack_chk_guard, &len, NULL, 0) == -1 ||
+           len != sizeof(__stack_chk_guard)) {
+               /* If sysctl was unsuccessful, use the "terminator canary". */
+               ((unsigned char *)(void *)__stack_chk_guard)[0] = 0;
+               ((unsigned char *)(void *)__stack_chk_guard)[1] = 0;
+               ((unsigned char *)(void *)__stack_chk_guard)[2] = '\n';
+               ((unsigned char *)(void *)__stack_chk_guard)[3] = 255;
+       }
+}
+
+/*ARGSUSED*/
+static void
+__fail(const char *msg)
+{
+#ifdef _LIBC
+       struct syslog_data sdata = SYSLOG_DATA_INIT;
+#endif
+       struct sigaction sa;
+       sigset_t mask;
+
+       /* Immediately block all signal handlers from running code */
+       (void)sigfillset(&mask);
+       (void)sigdelset(&mask, SIGABRT);
+       (void)sigprocmask(SIG_BLOCK, &mask, NULL);
+
+#ifdef _LIBC
+       /* This may fail on a chroot jail... */
+       syslog_ss(LOG_CRIT, &sdata, "%s", msg);
+#else
+       xprintf("%s: %s\n", getprogname(), msg);
+#endif
+
+       (void)memset(&sa, 0, sizeof(sa));
+       (void)sigemptyset(&sa.sa_mask);
+       sa.sa_flags = 0;
+       sa.sa_handler = SIG_DFL;
+       (void)sigaction(SIGABRT, &sa, NULL);
+       (void)raise(SIGABRT);
+       _exit(127);
+}
+
+void
+__stack_chk_fail(void)
+{
+       __fail("stack overflow detected; terminated");
+}
+
+void
+__chk_fail(void)
+{
+       __fail("buffer overflow detected; terminated");
+}
+
+void
+__stack_chk_fail_local(void)
+{
+       __stack_chk_fail();
+}
diff --git a/lib/nbsd_libc/nameser/Makefile.inc b/lib/nbsd_libc/nameser/Makefile.inc
new file mode 100644 (file)
index 0000000..317a1c3
--- /dev/null
@@ -0,0 +1,7 @@
+#      $NetBSD: Makefile.inc,v 1.1 2004/05/20 20:02:26 christos Exp $
+
+# net sources
+.PATH: ${.CURDIR}/nameser
+
+SRCS+= ns_name.c ns_netint.c ns_parse.c ns_print.c \
+       ns_samedomain.c ns_ttl.c
diff --git a/lib/nbsd_libc/nameser/ns_name.c b/lib/nbsd_libc/nameser/ns_name.c
new file mode 100644 (file)
index 0000000..ec2045e
--- /dev/null
@@ -0,0 +1,1161 @@
+/*     $NetBSD: ns_name.c,v 1.8 2009/04/12 19:43:37 christos Exp $     */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996,1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#ifndef lint
+#ifdef notdef
+static const char rcsid[] = "Id: ns_name.c,v 1.11 2009/01/23 19:59:16 each Exp";
+#else
+__RCSID("$NetBSD: ns_name.c,v 1.8 2009/04/12 19:43:37 christos Exp $");
+#endif
+#endif
+
+#include "port_before.h"
+
+#include <sys/types.h>
+
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+
+#include <errno.h>
+#include <resolv.h>
+#include <string.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <limits.h>
+
+#include "port_after.h"
+
+#ifdef SPRINTF_CHAR
+# define SPRINTF(x) strlen(sprintf/**/x)
+#else
+# define SPRINTF(x) ((size_t)sprintf x)
+#endif
+
+#define NS_TYPE_ELT                    0x40 /*%< EDNS0 extended label type */
+#define DNS_LABELTYPE_BITSTRING                0x41
+
+/* Data. */
+
+static const char      digits[] = "0123456789";
+
+static const char digitvalue[256] = {
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*16*/
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*32*/
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*48*/
+        0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1, /*64*/
+       -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*80*/
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*96*/
+       -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*112*/
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*128*/
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*256*/
+};
+
+/* Forward. */
+
+static int             special(int);
+static int             printable(int);
+static int             dn_find(const u_char *, const u_char *,
+                               const u_char * const *,
+                               const u_char * const *);
+static int             encode_bitsring(const char **, const char *,
+                                       unsigned char **, unsigned char **,
+                                       unsigned const char *);
+static int             labellen(const u_char *);
+static int             decode_bitstring(const unsigned char **,
+                                        char *, const char *);
+
+/* Public. */
+
+/*%
+ *     Convert an encoded domain name to printable ascii as per RFC1035.
+
+ * return:
+ *\li  Number of bytes written to buffer, or -1 (with errno set)
+ *
+ * notes:
+ *\li  The root is returned as "."
+ *\li  All other domains are returned in non absolute form
+ */
+int
+ns_name_ntop(const u_char *src, char *dst, size_t dstsiz)
+{
+       const u_char *cp;
+       char *dn, *eom;
+       u_char c;
+       u_int n;
+       int l;
+
+       cp = src;
+       dn = dst;
+       eom = dst + dstsiz;
+
+       while ((n = *cp++) != 0) {
+               if ((n & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
+                       /* Some kind of compression pointer. */
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               if (dn != dst) {
+                       if (dn >= eom) {
+                               errno = EMSGSIZE;
+                               return (-1);
+                       }
+                       *dn++ = '.';
+               }
+               if ((l = labellen(cp - 1)) < 0) {
+                       errno = EMSGSIZE; /*%< XXX */
+                       return (-1);
+               }
+               if (dn + l >= eom) {
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               if ((n & NS_CMPRSFLGS) == NS_TYPE_ELT) {
+                       int m;
+
+                       if (n != DNS_LABELTYPE_BITSTRING) {
+                               /* XXX: labellen should reject this case */
+                               errno = EINVAL;
+                               return (-1);
+                       }
+                       if ((m = decode_bitstring(&cp, dn, eom)) < 0)
+                       {
+                               errno = EMSGSIZE;
+                               return (-1);
+                       }
+                       dn += m; 
+                       continue;
+               }
+               for (; l > 0; l--) {
+                       c = *cp++;
+                       if (special(c)) {
+                               if (dn + 1 >= eom) {
+                                       errno = EMSGSIZE;
+                                       return (-1);
+                               }
+                               *dn++ = '\\';
+                               *dn++ = (char)c;
+                       } else if (!printable(c)) {
+                               if (dn + 3 >= eom) {
+                                       errno = EMSGSIZE;
+                                       return (-1);
+                               }
+                               *dn++ = '\\';
+                               *dn++ = digits[c / 100];
+                               *dn++ = digits[(c % 100) / 10];
+                               *dn++ = digits[c % 10];
+                       } else {
+                               if (dn >= eom) {
+                                       errno = EMSGSIZE;
+                                       return (-1);
+                               }
+                               *dn++ = (char)c;
+                       }
+               }
+       }
+       if (dn == dst) {
+               if (dn >= eom) {
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               *dn++ = '.';
+       }
+       if (dn >= eom) {
+               errno = EMSGSIZE;
+               return (-1);
+       }
+       *dn++ = '\0';
+       return (dn - dst);
+}
+
+/*%
+ *     Convert a ascii string into an encoded domain name as per RFC1035.
+ *
+ * return:
+ *
+ *\li  -1 if it fails
+ *\li  1 if string was fully qualified
+ *\li  0 is string was not fully qualified
+ *
+ * notes:
+ *\li  Enforces label and domain length limits.
+ */
+int
+ns_name_pton(const char *src, u_char *dst, size_t dstsiz) {
+       return (ns_name_pton2(src, dst, dstsiz, NULL));
+}
+
+/*
+ * ns_name_pton2(src, dst, dstsiz, *dstlen)
+ *     Convert a ascii string into an encoded domain name as per RFC1035.
+ * return:
+ *     -1 if it fails
+ *     1 if string was fully qualified
+ *     0 is string was not fully qualified
+ * side effects:
+ *     fills in *dstlen (if non-NULL)
+ * notes:
+ *     Enforces label and domain length limits.
+ */
+int
+ns_name_pton2(const char *src, u_char *dst, size_t dstsiz, size_t *dstlen) {
+       u_char *label, *bp, *eom;
+       int c, n, escaped, e = 0;
+       char *cp;
+
+       escaped = 0;
+       bp = dst;
+       eom = dst + dstsiz;
+       label = bp++;
+
+       while ((c = *src++) != 0) {
+               if (escaped) {
+                       if (c == '[') { /*%< start a bit string label */
+                               if ((cp = strchr(src, ']')) == NULL) {
+                                       errno = EINVAL; /*%< ??? */
+                                       return (-1);
+                               }
+                               if ((e = encode_bitsring(&src, cp + 2,
+                                                        &label, &bp, eom))
+                                   != 0) {
+                                       errno = e;
+                                       return (-1);
+                               }
+                               escaped = 0;
+                               label = bp++;
+                               if ((c = *src++) == 0)
+                                       goto done;
+                               else if (c != '.') {
+                                       errno = EINVAL;
+                                       return  (-1);
+                               }
+                               continue;
+                       }
+                       else if ((cp = strchr(digits, c)) != NULL) {
+                               n = (cp - digits) * 100;
+                               if ((c = *src++) == 0 ||
+                                   (cp = strchr(digits, c)) == NULL) {
+                                       errno = EMSGSIZE;
+                                       return (-1);
+                               }
+                               n += (cp - digits) * 10;
+                               if ((c = *src++) == 0 ||
+                                   (cp = strchr(digits, c)) == NULL) {
+                                       errno = EMSGSIZE;
+                                       return (-1);
+                               }
+                               n += (cp - digits);
+                               if (n > 255) {
+                                       errno = EMSGSIZE;
+                                       return (-1);
+                               }
+                               c = n;
+                       }
+                       escaped = 0;
+               } else if (c == '\\') {
+                       escaped = 1;
+                       continue;
+               } else if (c == '.') {
+                       c = (bp - label - 1);
+                       if ((c & NS_CMPRSFLGS) != 0) {  /*%< Label too big. */
+                               errno = EMSGSIZE;
+                               return (-1);
+                       }
+                       if (label >= eom) {
+                               errno = EMSGSIZE;
+                               return (-1);
+                       }
+                       *label = c;
+                       /* Fully qualified ? */
+                       if (*src == '\0') {
+                               if (c != 0) {
+                                       if (bp >= eom) {
+                                               errno = EMSGSIZE;
+                                               return (-1);
+                                       }
+                                       *bp++ = '\0';
+                               }
+                               if ((bp - dst) > MAXCDNAME) {
+                                       errno = EMSGSIZE;
+                                       return (-1);
+                               }
+                               if (dstlen != NULL)
+                                       *dstlen = (bp - dst);
+                               return (1);
+                       }
+                       if (c == 0 || *src == '.') {
+                               errno = EMSGSIZE;
+                               return (-1);
+                       }
+                       label = bp++;
+                       continue;
+               }
+               if (bp >= eom) {
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               *bp++ = (u_char)c;
+       }
+       c = (bp - label - 1);
+       if ((c & NS_CMPRSFLGS) != 0) {          /*%< Label too big. */
+               errno = EMSGSIZE;
+               return (-1);
+       }
+  done:
+       if (label >= eom) {
+               errno = EMSGSIZE;
+               return (-1);
+       }
+       *label = c;
+       if (c != 0) {
+               if (bp >= eom) {
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               *bp++ = 0;
+       }
+       if ((bp - dst) > MAXCDNAME) {   /*%< src too big */
+               errno = EMSGSIZE;
+               return (-1);
+       }
+       if (dstlen != NULL)
+               *dstlen = (bp - dst);
+       return (0);
+}
+
+/*%
+ *     Convert a network strings labels into all lowercase.
+ *
+ * return:
+ *\li  Number of bytes written to buffer, or -1 (with errno set)
+ *
+ * notes:
+ *\li  Enforces label and domain length limits.
+ */
+
+int
+ns_name_ntol(const u_char *src, u_char *dst, size_t dstsiz)
+{
+       const u_char *cp;
+       u_char *dn, *eom;
+       u_char c;
+       u_int n;
+       int l;
+
+       cp = src;
+       dn = dst;
+       eom = dst + dstsiz;
+
+       if (dn >= eom) {
+               errno = EMSGSIZE;
+               return (-1);
+       }
+       while ((n = *cp++) != 0) {
+               if ((n & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
+                       /* Some kind of compression pointer. */
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               *dn++ = n;
+               if ((l = labellen(cp - 1)) < 0) {
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               if (dn + l >= eom) {
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               for (; l > 0; l--) {
+                       c = *cp++;
+                       if (isascii(c) && isupper(c))
+                               *dn++ = tolower(c);
+                       else
+                               *dn++ = c;
+               }
+       }
+       *dn++ = '\0';
+       return (dn - dst);
+}
+
+/*%
+ *     Unpack a domain name from a message, source may be compressed.
+ *
+ * return:
+ *\li  -1 if it fails, or consumed octets if it succeeds.
+ */
+int
+ns_name_unpack(const u_char *msg, const u_char *eom, const u_char *src,
+              u_char *dst, size_t dstsiz)
+{
+       return (ns_name_unpack2(msg, eom, src, dst, dstsiz, NULL));
+}
+
+/*
+ * ns_name_unpack2(msg, eom, src, dst, dstsiz, *dstlen)
+ *     Unpack a domain name from a message, source may be compressed.
+ * return:
+ *     -1 if it fails, or consumed octets if it succeeds.
+ * side effect:
+ *     fills in *dstlen (if non-NULL).
+ */
+int
+ns_name_unpack2(const u_char *msg, const u_char *eom, const u_char *src,
+               u_char *dst, size_t dstsiz, size_t *dstlen)
+{
+       const u_char *srcp, *dstlim;
+       u_char *dstp;
+       int n, len, checked, l;
+
+       len = -1;
+       checked = 0;
+       dstp = dst;
+       srcp = src;
+       dstlim = dst + dstsiz;
+       if (srcp < msg || srcp >= eom) {
+               errno = EMSGSIZE;
+               return (-1);
+       }
+       /* Fetch next label in domain name. */
+       while ((n = *srcp++) != 0) {
+               /* Check for indirection. */
+               switch (n & NS_CMPRSFLGS) {
+               case 0:
+               case NS_TYPE_ELT:
+                       /* Limit checks. */
+                       if ((l = labellen(srcp - 1)) < 0) {
+                               errno = EMSGSIZE;
+                               return (-1);
+                       }
+                       if (dstp + l + 1 >= dstlim || srcp + l >= eom) {
+                               errno = EMSGSIZE;
+                               return (-1);
+                       }
+                       checked += l + 1;
+                       *dstp++ = n;
+                       memcpy(dstp, srcp, (size_t)l);
+                       dstp += l;
+                       srcp += l;
+                       break;
+
+               case NS_CMPRSFLGS:
+                       if (srcp >= eom) {
+                               errno = EMSGSIZE;
+                               return (-1);
+                       }
+                       if (len < 0)
+                               len = srcp - src + 1;
+                       srcp = msg + (((n & 0x3f) << 8) | (*srcp & 0xff));
+                       if (srcp < msg || srcp >= eom) {  /*%< Out of range. */
+                               errno = EMSGSIZE;
+                               return (-1);
+                       }
+                       checked += 2;
+                       /*
+                        * Check for loops in the compressed name;
+                        * if we've looked at the whole message,
+                        * there must be a loop.
+                        */
+                       if (checked >= eom - msg) {
+                               errno = EMSGSIZE;
+                               return (-1);
+                       }
+                       break;
+
+               default:
+                       errno = EMSGSIZE;
+                       return (-1);                    /*%< flag error */
+               }
+       }
+       *dstp++ = 0;
+       if (dstlen != NULL)
+               *dstlen = dstp - dst;
+       if (len < 0)
+               len = srcp - src;
+       return (len);
+}
+
+/*%
+ *     Pack domain name 'domain' into 'comp_dn'.
+ *
+ * return:
+ *\li  Size of the compressed name, or -1.
+ *
+ * notes:
+ *\li  'dnptrs' is an array of pointers to previous compressed names.
+ *\li  dnptrs[0] is a pointer to the beginning of the message. The array
+ *     ends with NULL.
+ *\li  'lastdnptr' is a pointer to the end of the array pointed to
+ *     by 'dnptrs'.
+ *
+ * Side effects:
+ *\li  The list of pointers in dnptrs is updated for labels inserted into
+ *     the message as we compress the name.  If 'dnptr' is NULL, we don't
+ *     try to compress names. If 'lastdnptr' is NULL, we don't update the
+ *     list.
+ */
+int
+ns_name_pack(const u_char *src, u_char *dst, int dstsiz,
+            const u_char **dnptrs, const u_char **lastdnptr)
+{
+       u_char *dstp;
+       const u_char **cpp, **lpp, *eob, *msg;
+       const u_char *srcp;
+       int n, l, first = 1;
+
+       srcp = src;
+       dstp = dst;
+       eob = dstp + dstsiz;
+       lpp = cpp = NULL;
+       if (dnptrs != NULL) {
+               if ((msg = *dnptrs++) != NULL) {
+                       for (cpp = dnptrs; *cpp != NULL; cpp++)
+                               continue;
+                       lpp = cpp;      /*%< end of list to search */
+               }
+       } else
+               msg = NULL;
+
+       /* make sure the domain we are about to add is legal */
+       l = 0;
+       do {
+               int l0;
+
+               n = *srcp;
+               if ((n & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               if ((l0 = labellen(srcp)) < 0) {
+                       errno = EINVAL;
+                       return (-1);
+               }
+               l += l0 + 1;
+               if (l > MAXCDNAME) {
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               srcp += l0 + 1;
+       } while (n != 0);
+
+       /* from here on we need to reset compression pointer array on error */
+       srcp = src;
+       do {
+               /* Look to see if we can use pointers. */
+               n = *srcp;
+               if (n != 0 && msg != NULL) {
+                       l = dn_find(srcp, msg, (const u_char * const *)dnptrs,
+                                   (const u_char * const *)lpp);
+                       if (l >= 0) {
+                               if (dstp + 1 >= eob) {
+                                       goto cleanup;
+                               }
+                               *dstp++ = ((u_int32_t)l >> 8) | NS_CMPRSFLGS;
+                               *dstp++ = l % 256;
+                               return (dstp - dst);
+                       }
+                       /* Not found, save it. */
+                       if (lastdnptr != NULL && cpp < lastdnptr - 1 &&
+                           (dstp - msg) < 0x4000 && first) {
+                               *cpp++ = dstp;
+                               *cpp = NULL;
+                               first = 0;
+                       }
+               }
+               /* copy label to buffer */
+               if ((n & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
+                       /* Should not happen. */
+                       goto cleanup;
+               }
+               n = labellen(srcp);
+               if (dstp + 1 + n >= eob) {
+                       goto cleanup;
+               }
+               memcpy(dstp, srcp, (size_t)(n + 1));
+               srcp += n + 1;
+               dstp += n + 1;
+       } while (n != 0);
+
+       if (dstp > eob) {
+cleanup:
+               if (msg != NULL)
+                       *lpp = NULL;
+               errno = EMSGSIZE;
+               return (-1);
+       } 
+       return (dstp - dst);
+}
+
+/*%
+ *     Expand compressed domain name to presentation format.
+ *
+ * return:
+ *\li  Number of bytes read out of `src', or -1 (with errno set).
+ *
+ * note:
+ *\li  Root domain returns as "." not "".
+ */
+int
+ns_name_uncompress(const u_char *msg, const u_char *eom, const u_char *src,
+                  char *dst, size_t dstsiz)
+{
+       u_char tmp[NS_MAXCDNAME];
+       int n;
+       
+       if ((n = ns_name_unpack(msg, eom, src, tmp, sizeof tmp)) == -1)
+               return (-1);
+       if (ns_name_ntop(tmp, dst, dstsiz) == -1)
+               return (-1);
+       return (n);
+}
+
+/*%
+ *     Compress a domain name into wire format, using compression pointers.
+ *
+ * return:
+ *\li  Number of bytes consumed in `dst' or -1 (with errno set).
+ *
+ * notes:
+ *\li  'dnptrs' is an array of pointers to previous compressed names.
+ *\li  dnptrs[0] is a pointer to the beginning of the message.
+ *\li  The list ends with NULL.  'lastdnptr' is a pointer to the end of the
+ *     array pointed to by 'dnptrs'. Side effect is to update the list of
+ *     pointers for labels inserted into the message as we compress the name.
+ *\li  If 'dnptr' is NULL, we don't try to compress names. If 'lastdnptr'
+ *     is NULL, we don't update the list.
+ */
+int
+ns_name_compress(const char *src, u_char *dst, size_t dstsiz,
+                const u_char **dnptrs, const u_char **lastdnptr)
+{
+       u_char tmp[NS_MAXCDNAME];
+
+       if (ns_name_pton(src, tmp, sizeof tmp) == -1)
+               return (-1);
+       return (ns_name_pack(tmp, dst, (int)dstsiz, dnptrs, lastdnptr));
+}
+
+/*%
+ * Reset dnptrs so that there are no active references to pointers at or
+ * after src.
+ */
+void
+ns_name_rollback(const u_char *src, const u_char **dnptrs,
+                const u_char **lastdnptr)
+{
+       while (dnptrs < lastdnptr && *dnptrs != NULL) {
+               if (*dnptrs >= src) {
+                       *dnptrs = NULL;
+                       break;
+               }
+               dnptrs++;
+       }
+}
+
+/*%
+ *     Advance *ptrptr to skip over the compressed name it points at.
+ *
+ * return:
+ *\li  0 on success, -1 (with errno set) on failure.
+ */
+int
+ns_name_skip(const u_char **ptrptr, const u_char *eom)
+{
+       const u_char *cp;
+       u_int n;
+       int l;
+
+       cp = *ptrptr;
+       while (cp < eom && (n = *cp++) != 0) {
+               /* Check for indirection. */
+               switch (n & NS_CMPRSFLGS) {
+               case 0:                 /*%< normal case, n == len */
+                       cp += n;
+                       continue;
+               case NS_TYPE_ELT: /*%< EDNS0 extended label */
+                       if ((l = labellen(cp - 1)) < 0) {
+                               errno = EMSGSIZE; /*%< XXX */
+                               return (-1);
+                       }
+                       cp += l;
+                       continue;
+               case NS_CMPRSFLGS:      /*%< indirection */
+                       cp++;
+                       break;
+               default:                /*%< illegal type */
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               break;
+       }
+       if (cp > eom) {
+               errno = EMSGSIZE;
+               return (-1);
+       }
+       *ptrptr = cp;
+       return (0);
+}
+
+/* Find the number of octets an nname takes up, including the root label.
+ * (This is basically ns_name_skip() without compression-pointer support.)
+ * ((NOTE: can only return zero if passed-in namesiz argument is zero.))
+ */
+ssize_t
+ns_name_length(ns_nname_ct nname, size_t namesiz) {
+       ns_nname_ct orig = nname;
+       u_int n;
+
+       while (namesiz-- > 0 && (n = *nname++) != 0) {
+               if ((n & NS_CMPRSFLGS) != 0) {
+                       errno = EISDIR;
+                       return (-1);
+               }
+               if (n > namesiz) {
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               nname += n;
+               namesiz -= n;
+       }
+       return (nname - orig);
+}
+
+/* Compare two nname's for equality.  Return -1 on error (setting errno).
+ */
+int
+ns_name_eq(ns_nname_ct a, size_t as, ns_nname_ct b, size_t bs) {
+       ns_nname_ct ae = a + as, be = b + bs;
+       int ac, bc;
+
+       while (ac = *a, bc = *b, ac != 0 && bc != 0) {
+               if ((ac & NS_CMPRSFLGS) != 0 || (bc & NS_CMPRSFLGS) != 0) {
+                       errno = EISDIR;
+                       return (-1);
+               }
+               if (a + ac >= ae || b + bc >= be) {
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               if (ac != bc || strncasecmp((const char *) ++a,
+                                           (const char *) ++b,
+                                           (size_t)ac) != 0)
+                       return (0);
+               a += ac, b += bc;
+       }
+       return (ac == 0 && bc == 0);
+}
+
+/* Is domain "A" owned by (at or below) domain "B"?
+ */
+int
+ns_name_owned(ns_namemap_ct a, int an, ns_namemap_ct b, int bn) {
+       /* If A is shorter, it cannot be owned by B. */
+       if (an < bn)
+               return (0);
+
+       /* If they are unequal before the length of the shorter, A cannot... */
+       while (bn > 0) {
+               if (a->len != b->len ||
+                   strncasecmp((const char *) a->base,
+                               (const char *) b->base, (size_t)a->len) != 0)
+                       return (0);
+               a++, an--;
+               b++, bn--;
+       }
+
+       /* A might be longer or not, but either way, B owns it. */
+       return (1);
+}
+
+/* Build an array of <base,len> tuples from an nname, top-down order.
+ * Return the number of tuples (labels) thus discovered.
+ */
+int
+ns_name_map(ns_nname_ct nname, size_t namelen, ns_namemap_t map, int mapsize) {
+       u_int n;
+       int l;
+
+       n = *nname++;
+       namelen--;
+
+       /* Root zone? */
+       if (n == 0) {
+               /* Extra data follows name? */
+               if (namelen > 0) {
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               return (0);
+       }
+
+       /* Compression pointer? */
+       if ((n & NS_CMPRSFLGS) != 0) {
+               errno = EISDIR;
+               return (-1);
+       }
+
+       /* Label too long? */
+       if (n > namelen) {
+               errno = EMSGSIZE;
+               return (-1);
+       }
+
+       /* Recurse to get rest of name done first. */
+       l = ns_name_map(nname + n, namelen - n, map, mapsize);
+       if (l < 0)
+               return (-1);
+
+       /* Too many labels? */
+       if (l >= mapsize) {
+               errno = ENAMETOOLONG;
+               return (-1);
+       }
+
+       /* We're on our way back up-stack, store current map data. */
+       map[l].base = nname;
+       map[l].len = n;
+       return (l + 1);
+}
+
+/* Count the labels in a domain name.  Root counts, so COM. has two.  This
+ * is to make the result comparable to the result of ns_name_map().
+ */
+int
+ns_name_labels(ns_nname_ct nname, size_t namesiz) {
+       int ret = 0;
+       u_int n;
+
+       while (namesiz-- > 0 && (n = *nname++) != 0) {
+               if ((n & NS_CMPRSFLGS) != 0) {
+                       errno = EISDIR;
+                       return (-1);
+               }
+               if (n > namesiz) {
+                       errno = EMSGSIZE;
+                       return (-1);
+               }
+               nname += n;
+               namesiz -= n;
+               ret++;
+       }
+       return (ret + 1);
+}
+
+/* Private. */
+
+/*%
+ *     Thinking in noninternationalized USASCII (per the DNS spec),
+ *     is this characted special ("in need of quoting") ?
+ *
+ * return:
+ *\li  boolean.
+ */
+static int
+special(int ch) {
+       switch (ch) {
+       case 0x22: /*%< '"' */
+       case 0x2E: /*%< '.' */
+       case 0x3B: /*%< ';' */
+       case 0x5C: /*%< '\\' */
+       case 0x28: /*%< '(' */
+       case 0x29: /*%< ')' */
+       /* Special modifiers in zone files. */
+       case 0x40: /*%< '@' */
+       case 0x24: /*%< '$' */
+               return (1);
+       default:
+               return (0);
+       }
+}
+
+/*%
+ *     Thinking in noninternationalized USASCII (per the DNS spec),
+ *     is this character visible and not a space when printed ?
+ *
+ * return:
+ *\li  boolean.
+ */
+static int
+printable(int ch) {
+       return (ch > 0x20 && ch < 0x7f);
+}
+
+/*%
+ *     Thinking in noninternationalized USASCII (per the DNS spec),
+ *     convert this character to lower case if it's upper case.
+ */
+static int
+mklower(int ch) {
+       if (ch >= 0x41 && ch <= 0x5A)
+               return (ch + 0x20);
+       return (ch);
+}
+
+/*%
+ *     Search for the counted-label name in an array of compressed names.
+ *
+ * return:
+ *\li  offset from msg if found, or -1.
+ *
+ * notes:
+ *\li  dnptrs is the pointer to the first name on the list,
+ *\li  not the pointer to the start of the message.
+ */
+static int
+dn_find(const u_char *domain, const u_char *msg,
+       const u_char * const *dnptrs,
+       const u_char * const *lastdnptr)
+{
+       const u_char *dn, *cp, *sp;
+       const u_char * const *cpp;
+       u_int n;
+
+       for (cpp = dnptrs; cpp < lastdnptr; cpp++) {
+               sp = *cpp;
+               /*
+                * terminate search on:
+                * root label
+                * compression pointer
+                * unusable offset
+                */
+               while (*sp != 0 && (*sp & NS_CMPRSFLGS) == 0 &&
+                      (sp - msg) < 0x4000) {
+                       dn = domain;
+                       cp = sp;
+                       while ((n = *cp++) != 0) {
+                               /*
+                                * check for indirection
+                                */
+                               switch (n & NS_CMPRSFLGS) {
+                               case 0:         /*%< normal case, n == len */
+                                       n = labellen(cp - 1); /*%< XXX */
+                                       if (n != *dn++)
+                                               goto next;
+
+                                       for (; n > 0; n--)
+                                               if (mklower(*dn++) !=
+                                                   mklower(*cp++))
+                                                       goto next;
+                                       /* Is next root for both ? */
+                                       if (*dn == '\0' && *cp == '\0')
+                                               return (sp - msg);
+                                       if (*dn)
+                                               continue;
+                                       goto next;
+                               case NS_CMPRSFLGS:      /*%< indirection */
+                                       cp = msg + (((n & 0x3f) << 8) | *cp);
+                                       break;
+
+                               default:        /*%< illegal type */
+                                       errno = EMSGSIZE;
+                                       return (-1);
+                               }
+                       }
+ next: ;
+                       sp += *sp + 1;
+               }
+       }
+       errno = ENOENT;
+       return (-1);
+}
+
+static int
+decode_bitstring(const unsigned char **cpp, char *dn, const char *eom)
+{
+       const unsigned char *cp = *cpp;
+       char *beg = dn, tc;
+       int b, blen, plen, i;
+
+       if ((blen = (*cp & 0xff)) == 0)
+               blen = 256;
+       plen = (blen + 3) / 4;
+       plen += sizeof("\\[x/]") + (blen > 99 ? 3 : (blen > 9) ? 2 : 1);
+       if (dn + plen >= eom)
+               return (-1);
+
+       cp++;
+       i = SPRINTF((dn, "\\[x"));
+       if (i < 0)
+               return (-1);
+       dn += i;
+       for (b = blen; b > 7; b -= 8, cp++) {
+               i = SPRINTF((dn, "%02x", *cp & 0xff));
+               if (i < 0)
+                       return (-1);
+               dn += i;
+       }
+       if (b > 4) {
+               tc = *cp++;
+               i = SPRINTF((dn, "%02x", tc & (0xff << (8 - b))));
+               if (i < 0)
+                       return (-1);
+               dn += i;
+       } else if (b > 0) {
+               tc = *cp++;
+               i = SPRINTF((dn, "%1x",
+                              (((u_int32_t)tc >> 4) & 0x0f) & (0x0f << (4 - b)))); 
+               if (i < 0)
+                       return (-1);
+               dn += i;
+       }
+       i = SPRINTF((dn, "/%d]", blen));
+       if (i < 0)
+               return (-1);
+       dn += i;
+
+       *cpp = cp;
+       return (dn - beg);
+}
+
+static int
+encode_bitsring(const char **bp, const char *end, unsigned char **labelp,
+               unsigned char ** dst, unsigned const char *eom)
+{
+       int afterslash = 0;
+       const char *cp = *bp;
+       unsigned char *tp;
+       char c;
+       const char *beg_blen;
+       char *end_blen = NULL;
+       int value = 0, count = 0, tbcount = 0, blen = 0;
+
+       beg_blen = end_blen = NULL;
+
+       /* a bitstring must contain at least 2 characters */
+       if (end - cp < 2)
+               return (EINVAL);
+
+       /* XXX: currently, only hex strings are supported */
+       if (*cp++ != 'x')
+               return (EINVAL);
+       if (!isxdigit((*cp) & 0xff)) /*%< reject '\[x/BLEN]' */
+               return (EINVAL);
+
+       for (tp = *dst + 1; cp < end && tp < eom; cp++) {
+               switch((c = *cp)) {
+               case ']':       /*%< end of the bitstring */
+                       if (afterslash) {
+                               if (beg_blen == NULL)
+                                       return (EINVAL);
+                               blen = (int)strtol(beg_blen, &end_blen, 10);
+                               if (*end_blen != ']')
+                                       return (EINVAL);
+                       }
+                       if (count)
+                               *tp++ = ((value << 4) & 0xff);
+                       cp++;   /*%< skip ']' */
+                       goto done;
+               case '/':
+                       afterslash = 1;
+                       break;
+               default:
+                       if (afterslash) {
+                               if (!isdigit(c&0xff))
+                                       return (EINVAL);
+                               if (beg_blen == NULL) {
+                                       
+                                       if (c == '0') {
+                                               /* blen never begings with 0 */
+                                               return (EINVAL);
+                                       }
+                                       beg_blen = cp;
+                               }
+                       } else {
+                               if (!isxdigit(c&0xff))
+                                       return (EINVAL);
+                               value <<= 4;
+                               value += digitvalue[(int)c];
+                               count += 4;
+                               tbcount += 4;
+                               if (tbcount > 256)
+                                       return (EINVAL);
+                               if (count == 8) {
+                                       *tp++ = value;
+                                       count = 0;
+                               }
+                       }
+                       break;
+               }
+       }
+  done:
+       if (cp >= end || tp >= eom)
+               return (EMSGSIZE);
+
+       /*
+        * bit length validation:
+        * If a <length> is present, the number of digits in the <bit-data>
+        * MUST be just sufficient to contain the number of bits specified
+        * by the <length>. If there are insignificant bits in a final
+        * hexadecimal or octal digit, they MUST be zero.
+        * RFC2673, Section 3.2.
+        */
+       if (blen > 0) {
+               int traillen;
+
+               if (((blen + 3) & ~3) != tbcount)
+                       return (EINVAL);
+               traillen = tbcount - blen; /*%< between 0 and 3 */
+               if (((value << (8 - traillen)) & 0xff) != 0)
+                       return (EINVAL);
+       }
+       else
+               blen = tbcount;
+       if (blen == 256)
+               blen = 0;
+
+       /* encode the type and the significant bit fields */
+       **labelp = DNS_LABELTYPE_BITSTRING;
+       **dst = blen;
+
+       *bp = cp;
+       *dst = tp;
+
+       return (0);
+}
+
+static int
+labellen(const u_char *lp)
+{
+       int bitlen;
+       u_char l = *lp;
+
+       if ((l & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
+               /* should be avoided by the caller */
+               return (-1);
+       }
+
+       if ((l & NS_CMPRSFLGS) == NS_TYPE_ELT) {
+               if (l == DNS_LABELTYPE_BITSTRING) {
+                       if ((bitlen = *(lp + 1)) == 0)
+                               bitlen = 256;
+                       return ((bitlen + 7 ) / 8 + 1);
+               }
+               return (-1);    /*%< unknwon ELT */
+       }
+       return (l);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/nameser/ns_netint.c b/lib/nbsd_libc/nameser/ns_netint.c
new file mode 100644 (file)
index 0000000..7e4e77d
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: ns_netint.c,v 1.6 2009/04/12 17:07:17 christos Exp $   */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996,1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#ifndef lint
+#ifdef notdef
+static const char rcsid[] = "Id: ns_netint.c,v 1.3 2005/04/27 04:56:40 sra Exp";
+#else
+__RCSID("$NetBSD: ns_netint.c,v 1.6 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif
+
+/* Import. */
+
+#include "port_before.h"
+
+#include <arpa/nameser.h>
+
+#include "port_after.h"
+
+/* Public. */
+
+u_int16_t
+ns_get16(const u_char *src) {
+       u_int dst;
+
+       NS_GET16(dst, src);
+       return (dst);
+}
+
+u_int32_t
+ns_get32(const u_char *src) {
+       u_long dst;
+
+       NS_GET32(dst, src);
+       return (dst);
+}
+
+void
+ns_put16(u_int16_t src, u_char *dst) {
+       NS_PUT16(src, dst);
+}
+
+void
+ns_put32(u_int32_t src, u_char *dst) {
+       NS_PUT32(src, dst);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/nameser/ns_parse.c b/lib/nbsd_libc/nameser/ns_parse.c
new file mode 100644 (file)
index 0000000..0076069
--- /dev/null
@@ -0,0 +1,283 @@
+/*     $NetBSD: ns_parse.c,v 1.8 2009/04/12 19:43:37 christos Exp $    */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996,1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#ifndef lint
+#ifdef notdef
+static const char rcsid[] = "Id: ns_parse.c,v 1.10 2009/01/23 19:59:16 each Exp";
+#else
+__RCSID("$NetBSD: ns_parse.c,v 1.8 2009/04/12 19:43:37 christos Exp $");
+#endif
+#endif
+
+/* Import. */
+
+#include "port_before.h"
+
+#include <sys/types.h>
+
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+
+#include <errno.h>
+#include <resolv.h>
+#include <string.h>
+
+#include "port_after.h"
+
+/* Forward. */
+
+static void    setsection(ns_msg *msg, ns_sect sect);
+
+/* Macros. */
+
+#if !defined(SOLARIS2) || defined(__COVERITY__)
+#define RETERR(err) do { errno = (err); return (-1); } while (/*NOTREACHED*//*CONSTCOND*/0)
+#else
+#define RETERR(err) \
+       do { errno = (err); if (errno == errno) return (-1); } while (0)
+#endif
+
+#define PARSE_FMT_PRESO 0      /* Parse using presentation-format names */
+#define PARSE_FMT_WIRE 1       /* Parse using network-format names */
+
+/* Public. */
+
+/* These need to be in the same order as the nres.h:ns_flag enum. */
+struct _ns_flagdata _ns_flagdata[16] = {
+       { 0x8000, 15 },         /*%< qr. */
+       { 0x7800, 11 },         /*%< opcode. */
+       { 0x0400, 10 },         /*%< aa. */
+       { 0x0200, 9 },          /*%< tc. */
+       { 0x0100, 8 },          /*%< rd. */
+       { 0x0080, 7 },          /*%< ra. */
+       { 0x0040, 6 },          /*%< z. */
+       { 0x0020, 5 },          /*%< ad. */
+       { 0x0010, 4 },          /*%< cd. */
+       { 0x000f, 0 },          /*%< rcode. */
+       { 0x0000, 0 },          /*%< expansion (1/6). */
+       { 0x0000, 0 },          /*%< expansion (2/6). */
+       { 0x0000, 0 },          /*%< expansion (3/6). */
+       { 0x0000, 0 },          /*%< expansion (4/6). */
+       { 0x0000, 0 },          /*%< expansion (5/6). */
+       { 0x0000, 0 },          /*%< expansion (6/6). */
+};
+
+int ns_msg_getflag(ns_msg handle, int flag) {
+       return((u_int32_t)((handle)._flags & _ns_flagdata[flag].mask) >> _ns_flagdata[flag].shift);
+}
+
+int
+ns_skiprr(const u_char *ptr, const u_char *eom, ns_sect section, int count) {
+       const u_char *optr = ptr;
+
+       for (; count > 0; count--) {
+               int b, rdlength;
+
+               b = dn_skipname(ptr, eom);
+               if (b < 0)
+                       RETERR(EMSGSIZE);
+               ptr += b/*Name*/ + NS_INT16SZ/*Type*/ + NS_INT16SZ/*Class*/;
+               if (section != ns_s_qd) {
+                       if (ptr + NS_INT32SZ + NS_INT16SZ > eom)
+                               RETERR(EMSGSIZE);
+                       ptr += NS_INT32SZ/*TTL*/;
+                       NS_GET16(rdlength, ptr);
+                       ptr += rdlength/*RData*/;
+               }
+       }
+       if (ptr > eom)
+               RETERR(EMSGSIZE);
+       return (ptr - optr);
+}
+
+int
+ns_initparse(const u_char *msg, int msglen, ns_msg *handle) {
+       const u_char *eom = msg + msglen;
+       int i;
+
+       handle->_msg = msg;
+       handle->_eom = eom;
+       if (msg + NS_INT16SZ > eom)
+               RETERR(EMSGSIZE);
+       NS_GET16(handle->_id, msg);
+       if (msg + NS_INT16SZ > eom)
+               RETERR(EMSGSIZE);
+       NS_GET16(handle->_flags, msg);
+       for (i = 0; i < ns_s_max; i++) {
+               if (msg + NS_INT16SZ > eom)
+                       RETERR(EMSGSIZE);
+               NS_GET16(handle->_counts[i], msg);
+       }
+       for (i = 0; i < ns_s_max; i++)
+               if (handle->_counts[i] == 0)
+                       handle->_sections[i] = NULL;
+               else {
+                       int b = ns_skiprr(msg, eom, (ns_sect)i,
+                                         handle->_counts[i]);
+
+                       if (b < 0)
+                               return (-1);
+                       handle->_sections[i] = msg;
+                       msg += b;
+               }
+       if (msg != eom)
+               RETERR(EMSGSIZE);
+       setsection(handle, ns_s_max);
+       return (0);
+}
+
+int
+ns_parserr(ns_msg *handle, ns_sect section, int rrnum, ns_rr *rr) {
+       int b;
+       int tmp;
+
+       /* Make section right. */
+       tmp = section;
+       if (tmp < 0 || section >= ns_s_max)
+               RETERR(ENODEV);
+       if (section != handle->_sect)
+               setsection(handle, section);
+
+       /* Make rrnum right. */
+       if (rrnum == -1)
+               rrnum = handle->_rrnum;
+       if (rrnum < 0 || rrnum >= handle->_counts[(int)section])
+               RETERR(ENODEV);
+       if (rrnum < handle->_rrnum)
+               setsection(handle, section);
+       if (rrnum > handle->_rrnum) {
+               b = ns_skiprr(handle->_msg_ptr, handle->_eom, section,
+                             rrnum - handle->_rrnum);
+
+               if (b < 0)
+                       return (-1);
+               handle->_msg_ptr += b;
+               handle->_rrnum = rrnum;
+       }
+
+       /* Do the parse. */
+       b = dn_expand(handle->_msg, handle->_eom,
+                     handle->_msg_ptr, rr->name, NS_MAXDNAME);
+       if (b < 0)
+               return (-1);
+       handle->_msg_ptr += b;
+       if (handle->_msg_ptr + NS_INT16SZ + NS_INT16SZ > handle->_eom)
+               RETERR(EMSGSIZE);
+       NS_GET16(rr->type, handle->_msg_ptr);
+       NS_GET16(rr->rr_class, handle->_msg_ptr);
+       if (section == ns_s_qd) {
+               rr->ttl = 0;
+               rr->rdlength = 0;
+               rr->rdata = NULL;
+       } else {
+               if (handle->_msg_ptr + NS_INT32SZ + NS_INT16SZ > handle->_eom)
+                       RETERR(EMSGSIZE);
+               NS_GET32(rr->ttl, handle->_msg_ptr);
+               NS_GET16(rr->rdlength, handle->_msg_ptr);
+               if (handle->_msg_ptr + rr->rdlength > handle->_eom)
+                       RETERR(EMSGSIZE);
+               rr->rdata = handle->_msg_ptr;
+               handle->_msg_ptr += rr->rdlength;
+       }
+       if (++handle->_rrnum > handle->_counts[(int)section])
+               setsection(handle, (ns_sect)((int)section + 1));
+
+       /* All done. */
+       return (0);
+}
+
+/*
+ * This is identical to the above but uses network-format (uncompressed) names.
+ */
+int
+ns_parserr2(ns_msg *handle, ns_sect section, int rrnum, ns_rr2 *rr) {
+       int b;
+       int tmp;
+
+       /* Make section right. */
+       tmp = section;
+       if (tmp < 0 || section >= ns_s_max)
+               RETERR(ENODEV);
+       if (section != handle->_sect)
+               setsection(handle, section);
+
+       /* Make rrnum right. */
+       if (rrnum == -1)
+               rrnum = handle->_rrnum;
+       if (rrnum < 0 || rrnum >= handle->_counts[(int)section])
+               RETERR(ENODEV);
+       if (rrnum < handle->_rrnum)
+               setsection(handle, section);
+       if (rrnum > handle->_rrnum) {
+               b = ns_skiprr(handle->_msg_ptr, handle->_eom, section,
+                             rrnum - handle->_rrnum);
+
+               if (b < 0)
+                       return (-1);
+               handle->_msg_ptr += b;
+               handle->_rrnum = rrnum;
+       }
+
+       /* Do the parse. */
+       b = ns_name_unpack2(handle->_msg, handle->_eom, handle->_msg_ptr,
+                           rr->nname, NS_MAXNNAME, &rr->nnamel);
+       if (b < 0)
+               return (-1);
+       handle->_msg_ptr += b;
+       if (handle->_msg_ptr + NS_INT16SZ + NS_INT16SZ > handle->_eom)
+               RETERR(EMSGSIZE);
+       NS_GET16(rr->type, handle->_msg_ptr);
+       NS_GET16(rr->rr_class, handle->_msg_ptr);
+       if (section == ns_s_qd) {
+               rr->ttl = 0;
+               rr->rdlength = 0;
+               rr->rdata = NULL;
+       } else {
+               if (handle->_msg_ptr + NS_INT32SZ + NS_INT16SZ > handle->_eom)
+                       RETERR(EMSGSIZE);
+               NS_GET32(rr->ttl, handle->_msg_ptr);
+               NS_GET16(rr->rdlength, handle->_msg_ptr);
+               if (handle->_msg_ptr + rr->rdlength > handle->_eom)
+                       RETERR(EMSGSIZE);
+               rr->rdata = handle->_msg_ptr;
+               handle->_msg_ptr += rr->rdlength;
+       }
+       if (++handle->_rrnum > handle->_counts[(int)section])
+               setsection(handle, (ns_sect)((int)section + 1));
+
+       /* All done. */
+       return (0);
+}
+
+/* Private. */
+
+static void
+setsection(ns_msg *msg, ns_sect sect) {
+       msg->_sect = sect;
+       if (sect == ns_s_max) {
+               msg->_rrnum = -1;
+               msg->_msg_ptr = NULL;
+       } else {
+               msg->_rrnum = 0;
+               msg->_msg_ptr = msg->_sections[(int)sect];
+       }
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/nameser/ns_print.c b/lib/nbsd_libc/nameser/ns_print.c
new file mode 100644 (file)
index 0000000..51fe16e
--- /dev/null
@@ -0,0 +1,1258 @@
+/*     $NetBSD: ns_print.c,v 1.10 2009/04/12 19:43:37 christos Exp $   */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#ifndef lint
+#ifdef notdef
+static const char rcsid[] = "Id: ns_print.c,v 1.12 2009/03/03 05:29:58 each Exp";
+#else
+__RCSID("$NetBSD: ns_print.c,v 1.10 2009/04/12 19:43:37 christos Exp $");
+#endif
+#endif
+
+/* Import. */
+
+#include "port_before.h"
+
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+#include <arpa/inet.h>
+
+#include <isc/assertions.h>
+#include <isc/dst.h>
+#include <errno.h>
+#include <resolv.h>
+#include <string.h>
+#include <ctype.h>
+
+#include "port_after.h"
+
+#ifdef SPRINTF_CHAR
+# define SPRINTF(x) strlen(sprintf/**/x)
+#else
+# define SPRINTF(x) ((size_t)sprintf x)
+#endif
+
+/* Forward. */
+
+static size_t  prune_origin(const char *name, const char *origin);
+static int     charstr(const u_char *rdata, const u_char *edata,
+                       char **buf, size_t *buflen);
+static int     addname(const u_char *msg, size_t msglen,
+                       const u_char **p, const char *origin,
+                       char **buf, size_t *buflen);
+static void    addlen(size_t len, char **buf, size_t *buflen);
+static int     addstr(const char *src, size_t len,
+                      char **buf, size_t *buflen);
+static int     addtab(size_t len, size_t target, int spaced,
+                      char **buf, size_t *buflen);
+
+/* Macros. */
+
+#define        T(x) \
+       do { \
+               if ((x) < 0) \
+                       return (-1); \
+       } while (/*CONSTCOND*/0)
+
+static const char base32hex[] =
+        "0123456789ABCDEFGHIJKLMNOPQRSTUV=0123456789abcdefghijklmnopqrstuv";
+
+/* Public. */
+
+/*%
+ *     Convert an RR to presentation format.
+ *
+ * return:
+ *\li  Number of characters written to buf, or -1 (check errno).
+ */
+int
+ns_sprintrr(const ns_msg *handle, const ns_rr *rr,
+           const char *name_ctx, const char *origin,
+           char *buf, size_t buflen)
+{
+       int n;
+
+       n = ns_sprintrrf(ns_msg_base(*handle), ns_msg_size(*handle),
+                        ns_rr_name(*rr), ns_rr_class(*rr), ns_rr_type(*rr),
+                        ns_rr_ttl(*rr), ns_rr_rdata(*rr), ns_rr_rdlen(*rr),
+                        name_ctx, origin, buf, buflen);
+       return (n);
+}
+
+/*%
+ *     Convert the fields of an RR into presentation format.
+ *
+ * return:
+ *\li  Number of characters written to buf, or -1 (check errno).
+ */
+int
+ns_sprintrrf(const u_char *msg, size_t msglen,
+           const char *name, ns_class class, ns_type type,
+           u_long ttl, const u_char *rdata, size_t rdlen,
+           const char *name_ctx, const char *origin,
+           char *buf, size_t buflen)
+{
+       const char *obuf = buf;
+       const u_char *edata = rdata + rdlen;
+       int spaced = 0;
+
+       const char *comment;
+       char tmp[100];
+       int len, x;
+
+       /*
+        * Owner.
+        */
+       if (name_ctx != NULL && ns_samename(name_ctx, name) == 1) {
+               T(addstr("\t\t\t", (size_t)3, &buf, &buflen));
+       } else {
+               len = prune_origin(name, origin);
+               if (*name == '\0') {
+                       goto root;
+               } else if (len == 0) {
+                       T(addstr("@\t\t\t", (size_t)4, &buf, &buflen));
+               } else {
+                       T(addstr(name, (size_t)len, &buf, &buflen));
+                       /* Origin not used or not root, and no trailing dot? */
+                       if (((origin == NULL || origin[0] == '\0') ||
+                           (origin[0] != '.' && origin[1] != '\0' &&
+                           name[len] == '\0')) && name[len - 1] != '.') {
+ root:
+                               T(addstr(".", (size_t)1, &buf, &buflen));
+                               len++;
+                       }
+                       T(spaced = addtab((size_t)len, 24, spaced, &buf, &buflen));
+               }
+       }
+
+       /*
+        * TTL, Class, Type.
+        */
+       T(x = ns_format_ttl(ttl, buf, buflen));
+       addlen((size_t)x, &buf, &buflen);
+       len = SPRINTF((tmp, " %s %s", p_class(class), p_type(type)));
+       T(addstr(tmp, (size_t)len, &buf, &buflen));
+       T(spaced = addtab((size_t)(x + len), (size_t)16, spaced, &buf, &buflen));
+
+       /*
+        * RData.
+        */
+       switch (type) {
+       case ns_t_a:
+               if (rdlen != (size_t)NS_INADDRSZ)
+                       goto formerr;
+               (void) inet_ntop(AF_INET, rdata, buf, buflen);
+               addlen(strlen(buf), &buf, &buflen);
+               break;
+
+       case ns_t_cname:
+       case ns_t_mb:
+       case ns_t_mg:
+       case ns_t_mr:
+       case ns_t_ns:
+       case ns_t_ptr:
+       case ns_t_dname:
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+               break;
+
+       case ns_t_hinfo:
+       case ns_t_isdn:
+               /* First word. */
+               T(len = charstr(rdata, edata, &buf, &buflen));
+               if (len == 0)
+                       goto formerr;
+               rdata += len;
+               T(addstr(" ", (size_t)1, &buf, &buflen));
+
+                   
+               /* Second word, optional in ISDN records. */
+               if (type == ns_t_isdn && rdata == edata)
+                       break;
+                   
+               T(len = charstr(rdata, edata, &buf, &buflen));
+               if (len == 0)
+                       goto formerr;
+               rdata += len;
+               break;
+
+       case ns_t_soa: {
+               u_long t;
+
+               /* Server name. */
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+               T(addstr(" ", (size_t)1, &buf, &buflen));
+
+               /* Administrator name. */
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+               T(addstr(" (\n", (size_t)3, &buf, &buflen));
+               spaced = 0;
+
+               if ((edata - rdata) != 5*NS_INT32SZ)
+                       goto formerr;
+
+               /* Serial number. */
+               t = ns_get32(rdata);  rdata += NS_INT32SZ;
+               T(addstr("\t\t\t\t\t", (size_t)5, &buf, &buflen));
+               len = SPRINTF((tmp, "%lu", t));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+               T(spaced = addtab((size_t)len, (size_t)16, spaced, &buf, &buflen));
+               T(addstr("; serial\n", (size_t)9, &buf, &buflen));
+               spaced = 0;
+
+               /* Refresh interval. */
+               t = ns_get32(rdata);  rdata += NS_INT32SZ;
+               T(addstr("\t\t\t\t\t", (size_t)5, &buf, &buflen));
+               T(len = ns_format_ttl(t, buf, buflen));
+               addlen((size_t)len, &buf, &buflen);
+               T(spaced = addtab((size_t)len, (size_t)16, spaced, &buf, &buflen));
+               T(addstr("; refresh\n", (size_t)10, &buf, &buflen));
+               spaced = 0;
+
+               /* Retry interval. */
+               t = ns_get32(rdata);  rdata += NS_INT32SZ;
+               T(addstr("\t\t\t\t\t", (size_t)5, &buf, &buflen));
+               T(len = ns_format_ttl(t, buf, buflen));
+               addlen((size_t)len, &buf, &buflen);
+               T(spaced = addtab((size_t)len, (size_t)16, spaced, &buf, &buflen));
+               T(addstr("; retry\n", (size_t)8, &buf, &buflen));
+               spaced = 0;
+
+               /* Expiry. */
+               t = ns_get32(rdata);  rdata += NS_INT32SZ;
+               T(addstr("\t\t\t\t\t", (size_t)5, &buf, &buflen));
+               T(len = ns_format_ttl(t, buf, buflen));
+               addlen((size_t)len, &buf, &buflen);
+               T(spaced = addtab((size_t)len, (size_t)16, spaced, &buf, &buflen));
+               T(addstr("; expiry\n", (size_t)9, &buf, &buflen));
+               spaced = 0;
+
+               /* Minimum TTL. */
+               t = ns_get32(rdata);  rdata += NS_INT32SZ;
+               T(addstr("\t\t\t\t\t", (size_t)5, &buf, &buflen));
+               T(len = ns_format_ttl(t, buf, buflen));
+               addlen((size_t)len, &buf, &buflen);
+               T(addstr(" )", (size_t)2, &buf, &buflen));
+               T(spaced = addtab((size_t)len, (size_t)16, spaced, &buf, &buflen));
+               T(addstr("; minimum\n", (size_t)10, &buf, &buflen));
+
+               break;
+           }
+
+       case ns_t_mx:
+       case ns_t_afsdb:
+       case ns_t_rt:
+       case ns_t_kx: {
+               u_int t;
+
+               if (rdlen < (size_t)NS_INT16SZ)
+                       goto formerr;
+
+               /* Priority. */
+               t = ns_get16(rdata);
+               rdata += NS_INT16SZ;
+               len = SPRINTF((tmp, "%u ", t));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+               /* Target. */
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+
+               break;
+           }
+
+       case ns_t_px: {
+               u_int t;
+
+               if (rdlen < (size_t)NS_INT16SZ)
+                       goto formerr;
+
+               /* Priority. */
+               t = ns_get16(rdata);
+               rdata += NS_INT16SZ;
+               len = SPRINTF((tmp, "%u ", t));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+               /* Name1. */
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+               T(addstr(" ", (size_t)1, &buf, &buflen));
+
+               /* Name2. */
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+
+               break;
+           }
+
+       case ns_t_x25:
+               T(len = charstr(rdata, edata, &buf, &buflen));
+               if (len == 0)
+                       goto formerr;
+               rdata += len;
+               break;
+
+       case ns_t_txt:
+       case ns_t_spf:
+               while (rdata < edata) {
+                       T(len = charstr(rdata, edata, &buf, &buflen));
+                       if (len == 0)
+                               goto formerr;
+                       rdata += len;
+                       if (rdata < edata)
+                               T(addstr(" ", (size_t)1, &buf, &buflen));
+               }
+               break;
+
+       case ns_t_nsap: {
+               char t[2+255*3];
+
+               (void) inet_nsap_ntoa((int)rdlen, rdata, t);
+               T(addstr(t, strlen(t), &buf, &buflen));
+               break;
+           }
+
+       case ns_t_aaaa:
+               if (rdlen != (size_t)NS_IN6ADDRSZ)
+                       goto formerr;
+               (void) inet_ntop(AF_INET6, rdata, buf, buflen);
+               addlen(strlen(buf), &buf, &buflen);
+               break;
+
+       case ns_t_loc: {
+               char t[255];
+
+               /* XXX protocol format checking? */
+               (void) loc_ntoa(rdata, t);
+               T(addstr(t, strlen(t), &buf, &buflen));
+               break;
+           }
+
+       case ns_t_naptr: {
+               u_int order, preference;
+               char t[50];
+
+               if (rdlen < 2U*NS_INT16SZ)
+                       goto formerr;
+
+               /* Order, Precedence. */
+               order = ns_get16(rdata);        rdata += NS_INT16SZ;
+               preference = ns_get16(rdata);   rdata += NS_INT16SZ;
+               len = SPRINTF((t, "%u %u ", order, preference));
+               T(addstr(t, (size_t)len, &buf, &buflen));
+
+               /* Flags. */
+               T(len = charstr(rdata, edata, &buf, &buflen));
+               if (len == 0)
+                       goto formerr;
+               rdata += len;
+               T(addstr(" ", (size_t)1, &buf, &buflen));
+
+               /* Service. */
+               T(len = charstr(rdata, edata, &buf, &buflen));
+               if (len == 0)
+                       goto formerr;
+               rdata += len;
+               T(addstr(" ", (size_t)1, &buf, &buflen));
+
+               /* Regexp. */
+               T(len = charstr(rdata, edata, &buf, &buflen));
+               if (len < 0)
+                       return (-1);
+               if (len == 0)
+                       goto formerr;
+               rdata += len;
+               T(addstr(" ", (size_t)1, &buf, &buflen));
+
+               /* Server. */
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+               break;
+           }
+
+       case ns_t_srv: {
+               u_int priority, weight, port;
+               char t[50];
+
+               if (rdlen < 3U*NS_INT16SZ)
+                       goto formerr;
+
+               /* Priority, Weight, Port. */
+               priority = ns_get16(rdata);  rdata += NS_INT16SZ;
+               weight   = ns_get16(rdata);  rdata += NS_INT16SZ;
+               port     = ns_get16(rdata);  rdata += NS_INT16SZ;
+               len = SPRINTF((t, "%u %u %u ", priority, weight, port));
+               T(addstr(t, (size_t)len, &buf, &buflen));
+
+               /* Server. */
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+               break;
+           }
+
+       case ns_t_minfo:
+       case ns_t_rp:
+               /* Name1. */
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+               T(addstr(" ", (size_t)1, &buf, &buflen));
+
+               /* Name2. */
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+
+               break;
+
+       case ns_t_wks: {
+               int n, lcnt;
+
+               if (rdlen < 1U + NS_INT32SZ)
+                       goto formerr;
+
+               /* Address. */
+               (void) inet_ntop(AF_INET, rdata, buf, buflen);
+               addlen(strlen(buf), &buf, &buflen);
+               rdata += NS_INADDRSZ;
+
+               /* Protocol. */
+               len = SPRINTF((tmp, " %u ( ", *rdata));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+               rdata += NS_INT8SZ;
+
+               /* Bit map. */
+               n = 0;
+               lcnt = 0;
+               while (rdata < edata) {
+                       u_int c = *rdata++;
+                       do {
+                               if (c & 0200) {
+                                       if (lcnt == 0) {
+                                               T(addstr("\n\t\t\t\t", (size_t)5,
+                                                        &buf, &buflen));
+                                               lcnt = 10;
+                                               spaced = 0;
+                                       }
+                                       len = SPRINTF((tmp, "%d ", n));
+                                       T(addstr(tmp, (size_t)len, &buf, &buflen));
+                                       lcnt--;
+                               }
+                               c <<= 1;
+                       } while (++n & 07);
+               }
+               T(addstr(")", (size_t)1, &buf, &buflen));
+
+               break;
+           }
+
+       case ns_t_key:
+       case ns_t_dnskey: {
+               char base64_key[NS_MD5RSA_MAX_BASE64];
+               u_int keyflags, protocol, algorithm, key_id;
+               const char *leader;
+               int n;
+
+               if (rdlen < 0U + NS_INT16SZ + NS_INT8SZ + NS_INT8SZ)
+                       goto formerr;
+
+               /* Key flags, Protocol, Algorithm. */
+#ifndef _LIBC
+               key_id = dst_s_dns_key_id(rdata, edata-rdata);
+#else
+               key_id = 0;
+#endif
+               keyflags = ns_get16(rdata);  rdata += NS_INT16SZ;
+               protocol = *rdata++;
+               algorithm = *rdata++;
+               len = SPRINTF((tmp, "0x%04x %u %u",
+                              keyflags, protocol, algorithm));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+               /* Public key data. */
+               len = b64_ntop(rdata, (size_t)(edata - rdata),
+                              base64_key, sizeof base64_key);
+               if (len < 0)
+                       goto formerr;
+               if (len > 15) {
+                       T(addstr(" (", (size_t)2, &buf, &buflen));
+                       leader = "\n\t\t";
+                       spaced = 0;
+               } else
+                       leader = " ";
+               for (n = 0; n < len; n += 48) {
+                       T(addstr(leader, strlen(leader), &buf, &buflen));
+                       T(addstr(base64_key + n, (size_t)MIN(len - n, 48),
+                                &buf, &buflen));
+               }
+               if (len > 15)
+                       T(addstr(" )", (size_t)2, &buf, &buflen));
+               n = SPRINTF((tmp, " ; key_tag= %u", key_id));
+               T(addstr(tmp, (size_t)n, &buf, &buflen));
+
+               break;
+           }
+
+       case ns_t_sig:
+       case ns_t_rrsig: {
+               char base64_key[NS_MD5RSA_MAX_BASE64];
+               u_int typ, algorithm, labels, footprint;
+               const char *leader;
+               u_long t;
+               int n;
+
+               if (rdlen < 22U)
+                       goto formerr;
+
+               /* Type covered, Algorithm, Label count, Original TTL. */
+               typ = ns_get16(rdata);  rdata += NS_INT16SZ;
+               algorithm = *rdata++;
+               labels = *rdata++;
+               t = ns_get32(rdata);  rdata += NS_INT32SZ;
+               len = SPRINTF((tmp, "%s %d %d %lu ",
+                              p_type((int)typ), algorithm, labels, t));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+               if (labels > (u_int)dn_count_labels(name))
+                       goto formerr;
+
+               /* Signature expiry. */
+               t = ns_get32(rdata);  rdata += NS_INT32SZ;
+               len = SPRINTF((tmp, "%s ", p_secstodate(t)));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+               /* Time signed. */
+               t = ns_get32(rdata);  rdata += NS_INT32SZ;
+               len = SPRINTF((tmp, "%s ", p_secstodate(t)));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+               /* Signature Footprint. */
+               footprint = ns_get16(rdata);  rdata += NS_INT16SZ;
+               len = SPRINTF((tmp, "%u ", footprint));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+               /* Signer's name. */
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+
+               /* Signature. */
+               len = b64_ntop(rdata, (size_t)(edata - rdata),
+                              base64_key, sizeof base64_key);
+               if (len > 15) {
+                       T(addstr(" (", (size_t)2, &buf, &buflen));
+                       leader = "\n\t\t";
+                       spaced = 0;
+               } else
+                       leader = " ";
+               if (len < 0)
+                       goto formerr;
+               for (n = 0; n < len; n += 48) {
+                       T(addstr(leader, strlen(leader), &buf, &buflen));
+                       T(addstr(base64_key + n, (size_t)MIN(len - n, 48),
+                                &buf, &buflen));
+               }
+               if (len > 15)
+                       T(addstr(" )", (size_t)2, &buf, &buflen));
+               break;
+           }
+
+       case ns_t_nxt: {
+               int n, c;
+
+               /* Next domain name. */
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+
+               /* Type bit map. */
+               n = edata - rdata;
+               for (c = 0; c < n*8; c++)
+                       if (NS_NXT_BIT_ISSET(c, rdata)) {
+                               len = SPRINTF((tmp, " %s", p_type(c)));
+                               T(addstr(tmp, (size_t)len, &buf, &buflen));
+                       }
+               break;
+           }
+
+       case ns_t_cert: {
+               u_int c_type, key_tag, alg;
+               int n;
+               unsigned int siz;
+               char base64_cert[8192], tmp1[40];
+               const char *leader;
+
+               c_type  = ns_get16(rdata); rdata += NS_INT16SZ;
+               key_tag = ns_get16(rdata); rdata += NS_INT16SZ;
+               alg = (u_int) *rdata++;
+
+               len = SPRINTF((tmp1, "%d %d %d ", c_type, key_tag, alg));
+               T(addstr(tmp1, (size_t)len, &buf, &buflen));
+               siz = (edata-rdata)*4/3 + 4; /* "+4" accounts for trailing \0 */
+               if (siz > sizeof(base64_cert) * 3/4) {
+                       const char *str = "record too long to print";
+                       T(addstr(str, strlen(str), &buf, &buflen));
+               }
+               else {
+                       len = b64_ntop(rdata, (size_t)(edata-rdata),
+                           base64_cert, siz);
+
+                       if (len < 0)
+                               goto formerr;
+                       else if (len > 15) {
+                               T(addstr(" (", (size_t)2, &buf, &buflen));
+                               leader = "\n\t\t";
+                               spaced = 0;
+                       }
+                       else
+                               leader = " ";
+       
+                       for (n = 0; n < len; n += 48) {
+                               T(addstr(leader, strlen(leader),
+                                        &buf, &buflen));
+                               T(addstr(base64_cert + n, (size_t)MIN(len - n, 48),
+                                        &buf, &buflen));
+                       }
+                       if (len > 15)
+                               T(addstr(" )", (size_t)2, &buf, &buflen));
+               }
+               break;
+           }
+
+       case ns_t_tkey: {
+               /* KJD - need to complete this */
+               u_long t;
+               int mode, err, keysize;
+
+               /* Algorithm name. */
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+               T(addstr(" ", (size_t)1, &buf, &buflen));
+
+               /* Inception. */
+               t = ns_get32(rdata);  rdata += NS_INT32SZ;
+               len = SPRINTF((tmp, "%s ", p_secstodate(t)));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+               /* Experation. */
+               t = ns_get32(rdata);  rdata += NS_INT32SZ;
+               len = SPRINTF((tmp, "%s ", p_secstodate(t)));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+               /* Mode , Error, Key Size. */
+               /* Priority, Weight, Port. */
+               mode = ns_get16(rdata);  rdata += NS_INT16SZ;
+               err  = ns_get16(rdata);  rdata += NS_INT16SZ;
+               keysize  = ns_get16(rdata);  rdata += NS_INT16SZ;
+               len = SPRINTF((tmp, "%u %u %u ", mode, err, keysize));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+               /* XXX need to dump key, print otherdata length & other data */
+               break;
+           }
+
+       case ns_t_tsig: {
+               /* BEW - need to complete this */
+               int n;
+
+               T(len = addname(msg, msglen, &rdata, origin, &buf, &buflen));
+               T(addstr(" ", (size_t)1, &buf, &buflen));
+               rdata += 8; /*%< time */
+               n = ns_get16(rdata); rdata += INT16SZ;
+               rdata += n; /*%< sig */
+               n = ns_get16(rdata); rdata += INT16SZ; /*%< original id */
+               sprintf(buf, "%d", ns_get16(rdata));
+               rdata += INT16SZ;
+               addlen(strlen(buf), &buf, &buflen);
+               break;
+           }
+
+       case ns_t_a6: {
+               struct in6_addr a;
+               int pbyte, pbit;
+
+               /* prefix length */
+               if (rdlen == 0U) goto formerr;
+               len = SPRINTF((tmp, "%d ", *rdata));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+               pbit = *rdata;
+               if (pbit > 128) goto formerr;
+               pbyte = (pbit & ~7) / 8;
+               rdata++;
+
+               /* address suffix: provided only when prefix len != 128 */
+               if (pbit < 128) {
+                       if (rdata + pbyte >= edata) goto formerr;
+                       memset(&a, 0, sizeof(a));
+                       memcpy(&a.s6_addr[pbyte], rdata, sizeof(a) - pbyte);
+                       (void) inet_ntop(AF_INET6, &a, buf, buflen);
+                       addlen(strlen(buf), &buf, &buflen);
+                       rdata += sizeof(a) - pbyte;
+               }
+
+               /* prefix name: provided only when prefix len > 0 */
+               if (pbit == 0)
+                       break;
+               if (rdata >= edata) goto formerr;
+               T(addstr(" ", (size_t)1, &buf, &buflen));
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+               
+               break;
+           }
+
+       case ns_t_opt: {
+               len = SPRINTF((tmp, "%u bytes", class));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+               break;
+           }
+
+       case ns_t_ds:
+       case ns_t_dlv:
+       case ns_t_sshfp: {
+               u_int t;
+
+               if (type == ns_t_ds || type == ns_t_dlv) {
+                       if (rdlen < 4U) goto formerr;
+                       t = ns_get16(rdata);
+                       rdata += NS_INT16SZ;
+                       len = SPRINTF((tmp, "%u ", t));
+                       T(addstr(tmp, (size_t)len, &buf, &buflen));
+               } else
+                       if (rdlen < 2U) goto formerr;
+
+               len = SPRINTF((tmp, "%u ", *rdata));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+               rdata++;
+
+               len = SPRINTF((tmp, "%u ", *rdata));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+               rdata++;
+
+               while (rdata < edata) {
+                       len = SPRINTF((tmp, "%02X", *rdata));
+                       T(addstr(tmp, (size_t)len, &buf, &buflen));
+                       rdata++;
+               }
+               break;
+           }
+
+       case ns_t_nsec3:
+       case ns_t_nsec3param: {
+               u_int t, w, l, j, k, c;
+               
+               len = SPRINTF((tmp, "%u ", *rdata));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+               rdata++;
+
+               len = SPRINTF((tmp, "%u ", *rdata));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+               rdata++;
+
+               t = ns_get16(rdata);
+               rdata += NS_INT16SZ;
+               len = SPRINTF((tmp, "%u ", t));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+               t = *rdata++;
+               if (t == 0) {
+                       T(addstr("-", 1, &buf, &buflen));
+               } else {
+                       while (t-- > 0) {
+                               len = SPRINTF((tmp, "%02X", *rdata));
+                               T(addstr(tmp, (size_t)len, &buf, &buflen));
+                               rdata++;
+                       }
+               }
+               if (type == ns_t_nsec3param)
+                       break;
+               T(addstr(" ", 1, &buf, &buflen));
+
+               t = *rdata++;
+               while (t > 0) {
+                       switch (t) {
+                       case 1:
+                               tmp[0] = base32hex[(((uint32_t)rdata[0]>>3)&0x1f)];
+                               tmp[1] = base32hex[(((uint32_t)rdata[0]<<2)&0x1c)];
+                               tmp[2] = tmp[3] = tmp[4] = '=';
+                               tmp[5] = tmp[6] = tmp[7] = '=';
+                               break;
+                       case 2:
+                               tmp[0] = base32hex[(((uint32_t)rdata[0]>>3)&0x1f)];
+                               tmp[1] = base32hex[(((uint32_t)rdata[0]<<2)&0x1c)|
+                                                  (((uint32_t)rdata[1]>>6)&0x03)];
+                               tmp[2] = base32hex[(((uint32_t)rdata[1]>>1)&0x1f)];
+                               tmp[3] = base32hex[(((uint32_t)rdata[1]<<4)&0x10)];
+                               tmp[4] = tmp[5] = tmp[6] = tmp[7] = '=';
+                               break;
+                       case 3:
+                               tmp[0] = base32hex[(((uint32_t)rdata[0]>>3)&0x1f)];
+                               tmp[1] = base32hex[(((uint32_t)rdata[0]<<2)&0x1c)|
+                                                  (((uint32_t)rdata[1]>>6)&0x03)];
+                               tmp[2] = base32hex[(((uint32_t)rdata[1]>>1)&0x1f)];
+                               tmp[3] = base32hex[(((uint32_t)rdata[1]<<4)&0x10)|
+                                                  (((uint32_t)rdata[2]>>4)&0x0f)];
+                               tmp[4] = base32hex[(((uint32_t)rdata[2]<<1)&0x1e)];
+                               tmp[5] = tmp[6] = tmp[7] = '=';
+                               break;
+                       case 4:
+                               tmp[0] = base32hex[(((uint32_t)rdata[0]>>3)&0x1f)];
+                               tmp[1] = base32hex[(((uint32_t)rdata[0]<<2)&0x1c)|
+                                                  (((uint32_t)rdata[1]>>6)&0x03)];
+                               tmp[2] = base32hex[(((uint32_t)rdata[1]>>1)&0x1f)];
+                               tmp[3] = base32hex[(((uint32_t)rdata[1]<<4)&0x10)|
+                                                  (((uint32_t)rdata[2]>>4)&0x0f)];
+                               tmp[4] = base32hex[(((uint32_t)rdata[2]<<1)&0x1e)|
+                                                  (((uint32_t)rdata[3]>>7)&0x01)];
+                               tmp[5] = base32hex[(((uint32_t)rdata[3]>>2)&0x1f)];
+                               tmp[6] = base32hex[((uint32_t)rdata[3]<<3)&0x18];
+                               tmp[7] = '=';
+                               break;
+                       default:
+                               tmp[0] = base32hex[(((uint32_t)rdata[0]>>3)&0x1f)];
+                               tmp[1] = base32hex[(((uint32_t)rdata[0]<<2)&0x1c)|
+                                                  (((uint32_t)rdata[1]>>6)&0x03)];
+                               tmp[2] = base32hex[(((uint32_t)rdata[1]>>1)&0x1f)];
+                               tmp[3] = base32hex[(((uint32_t)rdata[1]<<4)&0x10)|
+                                                  (((uint32_t)rdata[2]>>4)&0x0f)];
+                               tmp[4] = base32hex[(((uint32_t)rdata[2]<<1)&0x1e)|
+                                                  (((uint32_t)rdata[3]>>7)&0x01)];
+                               tmp[5] = base32hex[(((uint32_t)rdata[3]>>2)&0x1f)];
+                               tmp[6] = base32hex[(((uint32_t)rdata[3]<<3)&0x18)|
+                                                  (((uint32_t)rdata[4]>>5)&0x07)];
+                               tmp[7] = base32hex[(rdata[4]&0x1f)];
+                               break;
+                       }
+                       T(addstr(tmp, 8, &buf, &buflen));
+                       if (t >= 5) {
+                               rdata += 5;
+                               t -= 5;
+                       } else {
+                               rdata += t;
+                               t -= t;
+                       }
+               }
+
+               while (rdata < edata) {
+                       w = *rdata++;
+                       l = *rdata++;
+                       for (j = 0; j < l; j++) {
+                               if (rdata[j] == 0)
+                                       continue;
+                               for (k = 0; k < 8; k++) {
+                                       if ((rdata[j] & (0x80 >> k)) == 0)
+                                               continue;
+                                       c = w * 256 + j * 8 + k;
+                                       len = SPRINTF((tmp, " %s", p_type((ns_type)c)));
+                                       T(addstr(tmp, (size_t)len, &buf, &buflen));
+                               }
+                       }
+                       rdata += l;
+               }
+               break;
+           }
+
+       case ns_t_nsec: {
+               u_int w, l, j, k, c;
+
+               T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+
+               while (rdata < edata) {
+                       w = *rdata++;
+                       l = *rdata++;
+                       for (j = 0; j < l; j++) {
+                               if (rdata[j] == 0)
+                                       continue;
+                               for (k = 0; k < 8; k++) {
+                                       if ((rdata[j] & (0x80 >> k)) == 0)
+                                               continue;
+                                       c = w * 256 + j * 8 + k;
+                                       len = SPRINTF((tmp, " %s", p_type((ns_type)c)));
+                                       T(addstr(tmp, (size_t)len, &buf, &buflen));
+                               }
+                       }
+                       rdata += l;
+               }
+               break;
+           }
+
+       case ns_t_dhcid: {
+               int n;
+               unsigned int siz;
+               char base64_dhcid[8192];
+               const char *leader;
+
+               siz = (edata-rdata)*4/3 + 4; /* "+4" accounts for trailing \0 */
+               if (siz > sizeof(base64_dhcid) * 3/4) {
+                       const char *str = "record too long to print";
+                       T(addstr(str, strlen(str), &buf, &buflen));
+               } else {
+                       len = b64_ntop(rdata, (size_t)(edata-rdata),
+                           base64_dhcid, siz);
+               
+                       if (len < 0)
+                               goto formerr;
+
+                       else if (len > 15) {
+                               T(addstr(" (", 2, &buf, &buflen));
+                               leader = "\n\t\t";
+                               spaced = 0;
+                       }
+                       else
+                               leader = " ";
+
+                       for (n = 0; n < len; n += 48) {
+                               T(addstr(leader, strlen(leader),
+                                        &buf, &buflen));
+                               T(addstr(base64_dhcid + n,
+                                   (size_t)MIN(len - n, 48), &buf, &buflen));
+                       }
+                       if (len > 15)
+                               T(addstr(" )", 2, &buf, &buflen));
+               }
+               break;
+       }
+
+       case ns_t_ipseckey: {
+               int n;
+               unsigned int siz;
+               char base64_key[8192];
+               const char *leader;
+       
+               if (rdlen < 2)
+                       goto formerr;
+
+               switch (rdata[1]) {
+               case 0:
+               case 3:
+                       if (rdlen < 3)
+                               goto formerr;
+                       break;
+               case 1:
+                       if (rdlen < 7)
+                               goto formerr;
+                       break;
+               case 2:
+                       if (rdlen < 19)
+                               goto formerr;
+                       break;
+               default:
+                       comment = "unknown IPSECKEY gateway type";
+                       goto hexify;
+               }
+
+               len = SPRINTF((tmp, "%u ", *rdata));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+               rdata++;
+
+               len = SPRINTF((tmp, "%u ", *rdata));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+               rdata++;
+               
+               len = SPRINTF((tmp, "%u ", *rdata));
+               T(addstr(tmp, (size_t)len, &buf, &buflen));
+               rdata++;
+
+               switch (rdata[-2]) {
+               case 0:
+                       T(addstr(".", 1, &buf, &buflen));
+                       break;
+               case 1:
+                       (void) inet_ntop(AF_INET, rdata, buf, buflen);
+                       addlen(strlen(buf), &buf, &buflen);
+                       rdata += 4;
+                       break;
+               case 2:
+                       (void) inet_ntop(AF_INET6, rdata, buf, buflen);
+                       addlen(strlen(buf), &buf, &buflen);
+                       rdata += 16;
+                       break;
+               case 3:
+                       T(addname(msg, msglen, &rdata, origin, &buf, &buflen));
+                       break;
+               }
+
+               if (rdata >= edata)
+                       break;
+
+               siz = (edata-rdata)*4/3 + 4; /* "+4" accounts for trailing \0 */
+               if (siz > sizeof(base64_key) * 3/4) {
+                       const char *str = "record too long to print";
+                       T(addstr(str, strlen(str), &buf, &buflen));
+               } else {
+                       len = b64_ntop(rdata, (size_t)(edata-rdata),
+                           base64_key, siz);
+
+                       if (len < 0)
+                               goto formerr;
+
+                       else if (len > 15) {
+                               T(addstr(" (", 2, &buf, &buflen));
+                               leader = "\n\t\t";
+                               spaced = 0;
+                       }
+                       else
+                               leader = " ";
+
+                       for (n = 0; n < len; n += 48) {
+                               T(addstr(leader, strlen(leader),
+                                        &buf, &buflen));
+                               T(addstr(base64_key + n,
+                                   (size_t)MIN(len - n, 48), &buf, &buflen));
+                       }
+                       if (len > 15)
+                               T(addstr(" )", 2, &buf, &buflen));
+               }
+               break;
+       }
+
+       case ns_t_hip: {
+               unsigned int i, hip_len, algorithm, key_len;
+               char base64_key[NS_MD5RSA_MAX_BASE64];
+               unsigned int siz;
+               const char *leader = "\n\t\t\t\t\t";
+               
+               hip_len = *rdata++;
+               algorithm = *rdata++;
+               key_len = ns_get16(rdata);
+               rdata += NS_INT16SZ;
+
+               siz = key_len*4/3 + 4; /* "+4" accounts for trailing \0 */
+               if (siz > sizeof(base64_key) * 3/4) {
+                       const char *str = "record too long to print";
+                       T(addstr(str, strlen(str), &buf, &buflen));
+               } else {
+                       len = sprintf(tmp, "( %u ", algorithm);
+                       T(addstr(tmp, (size_t)len, &buf, &buflen));
+
+                       for (i = 0; i < hip_len; i++) {
+                               len = sprintf(tmp, "%02X", *rdata);
+                               T(addstr(tmp, (size_t)len, &buf, &buflen));
+                               rdata++;
+                       }
+                       T(addstr(leader, strlen(leader), &buf, &buflen));
+
+                       len = b64_ntop(rdata, key_len, base64_key, siz);
+                       if (len < 0)
+                               goto formerr;
+
+                       T(addstr(base64_key, (size_t)len, &buf, &buflen));
+                               
+                       rdata += key_len;
+                       while (rdata < edata) {
+                               T(addstr(leader, strlen(leader), &buf, &buflen));
+                               T(addname(msg, msglen, &rdata, origin,
+                                         &buf, &buflen));
+                       }
+                       T(addstr(" )", 2, &buf, &buflen));
+               }
+               break;
+       }
+
+       default:
+               comment = "unknown RR type";
+               goto hexify;
+       }
+       return (buf - obuf);
+ formerr:
+       comment = "RR format error";
+ hexify: {
+       int n, m;
+       char *p;
+
+       len = SPRINTF((tmp, "\\# %u%s\t; %s", (unsigned)(edata - rdata),
+                      rdlen != 0U ? " (" : "", comment));
+       T(addstr(tmp, (size_t)len, &buf, &buflen));
+       while (rdata < edata) {
+               p = tmp;
+               p += SPRINTF((p, "\n\t"));
+               spaced = 0;
+               n = MIN(16, edata - rdata);
+               for (m = 0; m < n; m++)
+                       p += SPRINTF((p, "%02x ", rdata[m]));
+               T(addstr(tmp, (size_t)(p - tmp), &buf, &buflen));
+               if (n < 16) {
+                       T(addstr(")", (size_t)1, &buf, &buflen));
+                       T(addtab((size_t)(p - tmp + 1), (size_t)48, spaced, &buf, &buflen));
+               }
+               p = tmp;
+               p += SPRINTF((p, "; "));
+               for (m = 0; m < n; m++)
+                       *p++ = (isascii(rdata[m]) && isprint(rdata[m]))
+                               ? rdata[m]
+                               : '.';
+               T(addstr(tmp, (size_t)(p - tmp), &buf, &buflen));
+               rdata += n;
+       }
+       return (buf - obuf);
+    }
+}
+
+/* Private. */
+
+/*%
+ * size_t
+ * prune_origin(name, origin)
+ *     Find out if the name is at or under the current origin.
+ * return:
+ *     Number of characters in name before start of origin,
+ *     or length of name if origin does not match.
+ * notes:
+ *     This function should share code with samedomain().
+ */
+static size_t
+prune_origin(const char *name, const char *origin) {
+       const char *oname = name;
+
+       while (*name != '\0') {
+               if (origin != NULL && ns_samename(name, origin) == 1)
+                       return (name - oname - (name > oname));
+               while (*name != '\0') {
+                       if (*name == '\\') {
+                               name++;
+                               /* XXX need to handle \nnn form. */
+                               if (*name == '\0')
+                                       break;
+                       } else if (*name == '.') {
+                               name++;
+                               break;
+                       }
+                       name++;
+               }
+       }
+       return (name - oname);
+}
+
+/*%
+ * int
+ * charstr(rdata, edata, buf, buflen)
+ *     Format a <character-string> into the presentation buffer.
+ * return:
+ *     Number of rdata octets consumed
+ *     0 for protocol format error
+ *     -1 for output buffer error
+ * side effects:
+ *     buffer is advanced on success.
+ */
+static int
+charstr(const u_char *rdata, const u_char *edata, char **buf, size_t *buflen) {
+       const u_char *odata = rdata;
+       size_t save_buflen = *buflen;
+       char *save_buf = *buf;
+
+       if (addstr("\"", (size_t)1, buf, buflen) < 0)
+               goto enospc;
+       if (rdata < edata) {
+               int n = *rdata;
+
+               if (rdata + 1 + n <= edata) {
+                       rdata++;
+                       while (n-- > 0) {
+                               if (strchr("\n\"\\", *rdata) != NULL)
+                                       if (addstr("\\", (size_t)1, buf, buflen) < 0)
+                                               goto enospc;
+                               if (addstr((const char *)rdata, (size_t)1,
+                                          buf, buflen) < 0)
+                                       goto enospc;
+                               rdata++;
+                       }
+               }
+       }
+       if (addstr("\"", (size_t)1, buf, buflen) < 0)
+               goto enospc;
+       return (rdata - odata);
+ enospc:
+       errno = ENOSPC;
+       *buf = save_buf;
+       *buflen = save_buflen;
+       return (-1);
+}
+
+static int
+addname(const u_char *msg, size_t msglen,
+       const u_char **pp, const char *origin,
+       char **buf, size_t *buflen)
+{
+       size_t newlen, save_buflen = *buflen;
+       char *save_buf = *buf;
+       int n;
+
+       n = dn_expand(msg, msg + msglen, *pp, *buf, (int)*buflen);
+       if (n < 0)
+               goto enospc;    /*%< Guess. */
+       newlen = prune_origin(*buf, origin);
+       if (**buf == '\0') {
+               goto root;
+       } else if (newlen == 0U) {
+               /* Use "@" instead of name. */
+               if (newlen + 2 > *buflen)
+                       goto enospc;        /* No room for "@\0". */
+               (*buf)[newlen++] = '@';
+               (*buf)[newlen] = '\0';
+       } else {
+               if (((origin == NULL || origin[0] == '\0') ||
+                   (origin[0] != '.' && origin[1] != '\0' &&
+                   (*buf)[newlen] == '\0')) && (*buf)[newlen - 1] != '.') {
+                       /* No trailing dot. */
+ root:
+                       if (newlen + 2 > *buflen)
+                               goto enospc;    /* No room for ".\0". */
+                       (*buf)[newlen++] = '.';
+                       (*buf)[newlen] = '\0';
+               }
+       }
+       *pp += n;
+       addlen(newlen, buf, buflen);
+       **buf = '\0';
+       return (newlen);
+ enospc:
+       errno = ENOSPC;
+       *buf = save_buf;
+       *buflen = save_buflen;
+       return (-1);
+}
+
+static void
+addlen(size_t len, char **buf, size_t *buflen) {
+       INSIST(len <= *buflen);
+       *buf += len;
+       *buflen -= len;
+}
+
+static int
+addstr(const char *src, size_t len, char **buf, size_t *buflen) {
+       if (len >= *buflen) {
+               errno = ENOSPC;
+               return (-1);
+       }
+       memcpy(*buf, src, len);
+       addlen(len, buf, buflen);
+       **buf = '\0';
+       return (0);
+}
+
+static int
+addtab(size_t len, size_t target, int spaced, char **buf, size_t *buflen) {
+       size_t save_buflen = *buflen;
+       char *save_buf = *buf;
+       int t;
+
+       if (spaced || len >= target - 1) {
+               T(addstr("  ", (size_t)2, buf, buflen));
+               spaced = 1;
+       } else {
+               for (t = (target - len - 1) / 8; t >= 0; t--)
+                       if (addstr("\t", (size_t)1, buf, buflen) < 0) {
+                               *buflen = save_buflen;
+                               *buf = save_buf;
+                               return (-1);
+                       }
+               spaced = 0;
+       }
+       return (spaced);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/nameser/ns_samedomain.c b/lib/nbsd_libc/nameser/ns_samedomain.c
new file mode 100644 (file)
index 0000000..05cb48d
--- /dev/null
@@ -0,0 +1,216 @@
+/*     $NetBSD: ns_samedomain.c,v 1.6 2009/04/12 17:07:17 christos Exp $       */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1995,1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#ifndef lint
+#ifdef notdef
+static const char rcsid[] = "Id: ns_samedomain.c,v 1.6 2005/04/27 04:56:40 sra Exp";
+#else
+__RCSID("$NetBSD: ns_samedomain.c,v 1.6 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif
+
+#include "port_before.h"
+
+#include <sys/types.h>
+#include <arpa/nameser.h>
+#include <errno.h>
+#include <string.h>
+
+#include "port_after.h"
+
+#ifndef _LIBC
+/*%
+ *     Check whether a name belongs to a domain.
+ *
+ * Inputs:
+ *\li  a - the domain whose ancestory is being verified
+ *\li  b - the potential ancestor we're checking against
+ *
+ * Return:
+ *\li  boolean - is a at or below b?
+ *
+ * Notes:
+ *\li  Trailing dots are first removed from name and domain.
+ *     Always compare complete subdomains, not only whether the
+ *     domain name is the trailing string of the given name.
+ *
+ *\li  "host.foobar.top" lies in "foobar.top" and in "top" and in ""
+ *     but NOT in "bar.top"
+ */
+
+int
+ns_samedomain(const char *a, const char *b) {
+       size_t la, lb;
+       int diff, i, escaped;
+       const char *cp;
+
+       la = strlen(a);
+       lb = strlen(b);
+
+       /* Ignore a trailing label separator (i.e. an unescaped dot) in 'a'. */
+       if (la != 0U && a[la - 1] == '.') {
+               escaped = 0;
+               /* Note this loop doesn't get executed if la==1. */
+               for (i = la - 2; i >= 0; i--)
+                       if (a[i] == '\\') {
+                               if (escaped)
+                                       escaped = 0;
+                               else
+                                       escaped = 1;
+                       } else
+                               break;
+               if (!escaped)
+                       la--;
+       }
+
+       /* Ignore a trailing label separator (i.e. an unescaped dot) in 'b'. */
+       if (lb != 0U && b[lb - 1] == '.') {
+               escaped = 0;
+               /* note this loop doesn't get executed if lb==1 */
+               for (i = lb - 2; i >= 0; i--)
+                       if (b[i] == '\\') {
+                               if (escaped)
+                                       escaped = 0;
+                               else
+                                       escaped = 1;
+                       } else
+                               break;
+               if (!escaped)
+                       lb--;
+       }
+
+       /* lb == 0 means 'b' is the root domain, so 'a' must be in 'b'. */
+       if (lb == 0U)
+               return (1);
+
+       /* 'b' longer than 'a' means 'a' can't be in 'b'. */
+       if (lb > la)
+               return (0);
+
+       /* 'a' and 'b' being equal at this point indicates sameness. */
+       if (lb == la)
+               return (strncasecmp(a, b, lb) == 0);
+
+       /* Ok, we know la > lb. */
+
+       diff = la - lb;
+
+       /*
+        * If 'a' is only 1 character longer than 'b', then it can't be
+        * a subdomain of 'b' (because of the need for the '.' label
+        * separator).
+        */
+       if (diff < 2)
+               return (0);
+
+       /*
+        * If the character before the last 'lb' characters of 'b'
+        * isn't '.', then it can't be a match (this lets us avoid
+        * having "foobar.com" match "bar.com").
+        */
+       if (a[diff - 1] != '.')
+               return (0);
+
+       /*
+        * We're not sure about that '.', however.  It could be escaped
+         * and thus not a really a label separator.
+        */
+       escaped = 0;
+       for (i = diff - 2; i >= 0; i--)
+               if (a[i] == '\\') {
+                       if (escaped)
+                               escaped = 0;
+                       else
+                               escaped = 1;
+               } else
+                       break;
+       if (escaped)
+               return (0);
+         
+       /* Now compare aligned trailing substring. */
+       cp = a + diff;
+       return (strncasecmp(cp, b, lb) == 0);
+}
+
+/*%
+ *     is "a" a subdomain of "b"?
+ */
+int
+ns_subdomain(const char *a, const char *b) {
+       return (ns_samename(a, b) != 1 && ns_samedomain(a, b));
+}
+#endif
+
+/*%
+ *     make a canonical copy of domain name "src"
+ *
+ * notes:
+ * \code
+ *     foo -> foo.
+ *     foo. -> foo.
+ *     foo.. -> foo.
+ *     foo\. -> foo\..
+ *     foo\\. -> foo\\.
+ * \endcode
+ */
+
+int
+ns_makecanon(const char *src, char *dst, size_t dstsize) {
+       size_t n = strlen(src);
+
+       if (n + sizeof "." > dstsize) {                 /*%< Note: sizeof == 2 */
+               errno = EMSGSIZE;
+               return (-1);
+       }
+       strcpy(dst, src);
+       while (n >= 1U && dst[n - 1] == '.')            /*%< Ends in "." */
+               if (n >= 2U && dst[n - 2] == '\\' &&    /*%< Ends in "\." */
+                   (n < 3U || dst[n - 3] != '\\'))     /*%< But not "\\." */
+                       break;
+               else
+                       dst[--n] = '\0';
+       dst[n++] = '.';
+       dst[n] = '\0';
+       return (0);
+}
+
+/*%
+ *     determine whether domain name "a" is the same as domain name "b"
+ *
+ * return:
+ *\li  -1 on error
+ *\li  0 if names differ
+ *\li  1 if names are the same
+ */
+
+int
+ns_samename(const char *a, const char *b) {
+       char ta[NS_MAXDNAME], tb[NS_MAXDNAME];
+
+       if (ns_makecanon(a, ta, sizeof ta) < 0 ||
+           ns_makecanon(b, tb, sizeof tb) < 0)
+               return (-1);
+       if (strcasecmp(ta, tb) == 0)
+               return (1);
+       else
+               return (0);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/nameser/ns_ttl.c b/lib/nbsd_libc/nameser/ns_ttl.c
new file mode 100644 (file)
index 0000000..2545ffd
--- /dev/null
@@ -0,0 +1,171 @@
+/*     $NetBSD: ns_ttl.c,v 1.7 2009/04/12 17:07:17 christos Exp $      */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996,1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#ifndef lint
+#ifdef notdef
+static const char rcsid[] = "Id: ns_ttl.c,v 1.4 2005/07/28 06:51:49 marka Exp";
+#else
+__RCSID("$NetBSD: ns_ttl.c,v 1.7 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif
+
+/* Import. */
+
+#include "port_before.h"
+
+#include <arpa/nameser.h>
+
+#include <ctype.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "port_after.h"
+
+#ifdef SPRINTF_CHAR
+# define SPRINTF(x) strlen(sprintf/**/x)
+#else
+# define SPRINTF(x) ((size_t)sprintf x)
+#endif
+
+/* Forward. */
+
+static int     fmt1(int t, char s, char **buf, size_t *buflen);
+
+/* Macros. */
+
+#define T(x) if ((x) < 0) return (-1)
+
+/* Public. */
+
+int
+ns_format_ttl(u_long src, char *dst, size_t dstlen) {
+       char *odst = dst;
+       int secs, mins, hours, days, weeks, x;
+       char *p;
+
+       secs = src % 60;   src /= 60;
+       mins = src % 60;   src /= 60;
+       hours = src % 24;  src /= 24;
+       days = src % 7;    src /= 7;
+       weeks = src;       src = 0;
+
+       x = 0;
+       if (weeks) {
+               T(fmt1(weeks, 'W', &dst, &dstlen));
+               x++;
+       }
+       if (days) {
+               T(fmt1(days, 'D', &dst, &dstlen));
+               x++;
+       }
+       if (hours) {
+               T(fmt1(hours, 'H', &dst, &dstlen));
+               x++;
+       }
+       if (mins) {
+               T(fmt1(mins, 'M', &dst, &dstlen));
+               x++;
+       }
+       if (secs || !(weeks || days || hours || mins)) {
+               T(fmt1(secs, 'S', &dst, &dstlen));
+               x++;
+       }
+
+       if (x > 1) {
+               int ch;
+
+               for (p = odst; (ch = *p) != '\0'; p++)
+                       if (isascii(ch) && isupper(ch))
+                               *p = tolower(ch);
+       }
+
+       return (dst - odst);
+}
+
+#ifndef _LIBC
+int
+ns_parse_ttl(const char *src, u_long *dst) {
+       u_long ttl, tmp;
+       int ch, digits, dirty;
+
+       ttl = 0;
+       tmp = 0;
+       digits = 0;
+       dirty = 0;
+       while ((ch = *src++) != '\0') {
+               if (!isascii(ch) || !isprint(ch))
+                       goto einval;
+               if (isdigit(ch)) {
+                       tmp *= 10;
+                       tmp += (ch - '0');
+                       digits++;
+                       continue;
+               }
+               if (digits == 0)
+                       goto einval;
+               if (islower(ch))
+                       ch = toupper(ch);
+               switch (ch) {
+               case 'W':  tmp *= 7;    /*FALLTHROUGH*/
+               case 'D':  tmp *= 24;   /*FALLTHROUGH*/
+               case 'H':  tmp *= 60;   /*FALLTHROUGH*/
+               case 'M':  tmp *= 60;   /*FALLTHROUGH*/
+               case 'S':  break;
+               default:   goto einval;
+               }
+               ttl += tmp;
+               tmp = 0;
+               digits = 0;
+               dirty = 1;
+       }
+       if (digits > 0) {
+               if (dirty)
+                       goto einval;
+               else
+                       ttl += tmp;
+       } else if (!dirty)
+               goto einval;
+       *dst = ttl;
+       return (0);
+
+ einval:
+       errno = EINVAL;
+       return (-1);
+}
+#endif
+
+/* Private. */
+
+static int
+fmt1(int t, char s, char **buf, size_t *buflen) {
+       char tmp[50];
+       size_t len;
+
+       len = SPRINTF((tmp, "%d%c", t, s));
+       if (len + 1 > *buflen)
+               return (-1);
+       strcpy(*buf, tmp);
+       *buf += len;
+       *buflen -= len;
+       return (0);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/net/Lint_htonl.c b/lib/nbsd_libc/net/Lint_htonl.c
new file mode 100644 (file)
index 0000000..e1d7e03
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_htonl.c,v 1.4 2001/08/22 07:42:08 itojun Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <sys/types.h>
+#undef htonl
+
+/*ARGSUSED*/
+uint32_t
+htonl(host32)
+       uint32_t host32;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/net/Lint_htons.c b/lib/nbsd_libc/net/Lint_htons.c
new file mode 100644 (file)
index 0000000..f0b06b2
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_htons.c,v 1.4 2001/08/22 07:42:09 itojun Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <sys/types.h>
+#undef htons
+
+/*ARGSUSED*//*NOSTRICT*/
+uint16_t
+htons(host16)
+       uint16_t host16;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/net/Lint_ntohl.c b/lib/nbsd_libc/net/Lint_ntohl.c
new file mode 100644 (file)
index 0000000..c2be9e4
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_ntohl.c,v 1.4 2001/08/22 07:42:09 itojun Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <sys/types.h>
+#undef ntohl
+
+/*ARGSUSED*/
+uint32_t
+ntohl(net32)
+       uint32_t net32;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/net/Lint_ntohs.c b/lib/nbsd_libc/net/Lint_ntohs.c
new file mode 100644 (file)
index 0000000..6841907
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_ntohs.c,v 1.4 2001/08/22 07:42:09 itojun Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <sys/types.h>
+#undef ntohs
+
+/*ARGSUSED*//*NOSTRICT*/
+uint16_t
+ntohs(net16)
+       uint16_t net16;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/net/Makefile.inc b/lib/nbsd_libc/net/Makefile.inc
new file mode 100644 (file)
index 0000000..7c1f493
--- /dev/null
@@ -0,0 +1,145 @@
+#      $NetBSD: Makefile.inc,v 1.78 2009/10/02 02:45:29 tsarna Exp $
+#      @(#)Makefile.inc        8.2 (Berkeley) 9/5/93
+
+# net sources
+.PATH: ${ARCHDIR}/net ${.CURDIR}/net
+
+SRCS+= __cmsg_alignbytes.c base64.c ethers.c gethnamaddr.c getifaddrs.c \
+       getnetnamadr.c getnetent.c getpeereid.c \
+       getprotobyname.c getprotobynumber.c getprotoent.c \
+       getprotobyname_r.c getprotobynumber_r.c getprotoent_r.c \
+       getservbyname.c getservbyport.c getservent.c \
+       getservbyname_r.c getservbyport_r.c getservent_r.c \
+       iso_addr.c linkaddr.c \
+       nsdispatch.c nslexer.l nsparser.y nsap_addr.c \
+       rcmd.c recv.c send.c sethostent.c \
+       sockatmark.c
+
+.if (${MKHESIOD} != "no")
+SRCS+= hesiod.c
+.endif
+
+SRCS+= getaddrinfo.c getnameinfo.c
+.if (${USE_INET6} != "no")
+SRCS+= ip6opt.c rthdr.c vars6.c
+.endif
+SRCS+= if_indextoname.c if_nameindex.c if_nametoindex.c
+
+LPREFIX=_nsyy
+YPREFIX=_nsyy
+YHEADER=1
+
+CLEANFILES+=nsparser.c nslexer.c nsparser.h
+
+nslexer.c: nslexer.l nsparser.h
+       ${_MKTARGET_LEX}
+       ${LEX.l} -t ${.IMPSRC} | sed -e '/YY_BUF_SIZE/s/16384/1024/' >${.TARGET}
+
+# machine-dependent net sources
+# m-d Makefile.inc must include sources for:
+#      htonl() htons() ntohl() ntohs()
+
+.include "${ARCHDIR}/net/Makefile.inc"
+
+MAN+=  byteorder.3 ethers.3 gethostbyname.3 getifaddrs.3 \
+       getnetent.3 getprotoent.3 getpeereid.3 \
+       getservent.3 inet.3 inet_net.3 iso_addr.3 linkaddr.3 \
+       nsdispatch.3 rcmd.3 resolver.3 sockatmark.3
+
+.if (${MKHESIOD} != "no")
+MAN+=  hesiod.3
+.endif
+
+MLINKS+=byteorder.3 htonl.3 byteorder.3 htons.3 byteorder.3 ntohl.3 \
+       byteorder.3 ntohs.3
+MLINKS+=ethers.3 ether_aton.3 ethers.3 ether_hostton.3 ethers.3 ether_line.3 \
+       ethers.3 ether_ntoa.3 ethers.3 ether_ntohost.3
+MLINKS+=gethostbyname.3 endhostent.3 gethostbyname.3 gethostbyaddr.3 \
+       gethostbyname.3 gethostent.3 gethostbyname.3 sethostent.3 \
+       gethostbyname.3 herror.3 gethostbyname.3 hstrerror.3 \
+       gethostbyname.3 gethostbyname2.3
+MLINKS+=getnetent.3 endnetent.3 getnetent.3 getnetbyaddr.3 \
+       getnetent.3 getnetbyname.3 getnetent.3 setnetent.3
+MLINKS+=getprotoent.3 endprotoent.3 getprotoent.3 getprotobyname.3 \
+       getprotoent.3 getprotobynumber.3 getprotoent.3 setprotoent.3
+MLINKS+=getservent.3 endservent.3 getservent.3 getservbyname.3 \
+       getservent.3 getservbyport.3 getservent.3 setservent.3
+.if (${MKHESIOD} != "no")
+MLINKS+=hesiod.3 hesiod_end.3 hesiod.3 hesiod_free_list.3 \
+       hesiod.3 hesiod_init.3 hesiod.3 hesiod_resolve.3 \
+       hesiod.3 hesiod_to_bind.3
+.endif
+MLINKS+=inet.3 addr.3 inet.3 inet_addr.3 inet.3 inet_aton.3 \
+       inet.3 inet_lnaof.3 inet.3 inet_makeaddr.3 inet.3 inet_netof.3 \
+       inet.3 inet_network.3 inet.3 inet_ntoa.3 inet.3 network.3 \
+       inet.3 ntoa.3 inet.3 inet_ntop.3 inet.3 inet_pton.3
+MLINKS+=inet_net.3 inet_net_ntop.3 inet_net.3 inet_net_pton.3
+MLINKS+=linkaddr.3 link_addr.3 linkaddr.3 link_ntoa.3 linkaddr.3 linkntoa.3
+MLINKS+=rcmd.3 iruserok.3 rcmd.3 rresvport.3 rcmd.3 ruserok.3 rcmd.3 orcmd.3
+MLINKS+=resolver.3 dn_comp.3 \
+       resolver.3 dn_expand.3 \
+       resolver.3 fp_nquery.3 \
+       resolver.3 fp_resstat.3 \
+       resolver.3 hostalias.3 \
+       resolver.3 p_query.3 \
+       resolver.3 res_close.3 \
+       resolver.3 res_findzonecut.3 \
+       resolver.3 res_getservers.3 \
+       resolver.3 res_hostalias.3 \
+       resolver.3 res_init.3 \
+       resolver.3 res_isourserver.3 \
+       resolver.3 res_mkquery.3 \
+       resolver.3 res_nclose.3 \
+       resolver.3 res_ndestroy.3 \
+       resolver.3 res_ninit.3 \
+       resolver.3 res_nmkquery.3 \
+       resolver.3 res_nmkupdate.3 \
+       resolver.3 res_nquery.3 \
+       resolver.3 res_nquerydomain.3 \
+       resolver.3 res_nsearch.3 \
+       resolver.3 res_nsend.3 \
+       resolver.3 res_nsendsigned.3 \
+       resolver.3 res_nupdate.3 \
+       resolver.3 res_ourserver_p.3 \
+       resolver.3 res_pquery.3 \
+       resolver.3 res_query.3 \
+       resolver.3 res_querydomain.3 \
+       resolver.3 res_search.3 \
+       resolver.3 res_send.3 \
+       resolver.3 res_setservers.3 \
+       resolver.3 res_update.3
+
+# IPv6
+MAN+=  gai_strerror.3 getaddrinfo.3 getnameinfo.3 if_indextoname.3 \
+       inet6_option_space.3 inet6_rthdr_space.3 \
+       inet6_opt_init.3 inet6_rth_space.3
+MLINKS+=getaddrinfo.3 freeaddrinfo.3 \
+       getaddrinfo.3 allocaddrinfo.3 \
+       getifaddrs.3 freeifaddrs.3 \
+       if_indextoname.3 if_nametoindex.3 if_indextoname.3 if_nameindex.3 \
+       if_indextoname.3 if_freenameindex.3 \
+       inet6_option_space.3 inet6_option_init.3 \
+       inet6_option_space.3 inet6_option_append.3 \
+       inet6_option_space.3 inet6_option_alloc.3 \
+       inet6_option_space.3 inet6_option_next.3 \
+       inet6_option_space.3 inet6_option_find.3 \
+       inet6_rthdr_space.3 inet6_rthdr_init.3 \
+       inet6_rthdr_space.3 inet6_rthdr_add.3 \
+       inet6_rthdr_space.3 inet6_rthdr_lasthop.3 \
+       inet6_rthdr_space.3 inet6_rthdr_reverse.3 \
+       inet6_rthdr_space.3 inet6_rthdr_segments.3 \
+       inet6_rthdr_space.3 inet6_rthdr_getaddr.3 \
+       inet6_rthdr_space.3 inet6_rthdr_getflags.3 \
+       inet6_opt_init.3 inet6_opt_append.3 \
+       inet6_opt_init.3 inet6_opt_finish.3 \
+       inet6_opt_init.3 inet6_opt_set_val.3 \
+       inet6_opt_init.3 inet6_opt_next.3 \
+       inet6_opt_init.3 inet6_opt_find.3 \
+       inet6_opt_init.3 inet6_opt_get_val.3 \
+       inet6_rth_space.3 inet6_rth_init.3 \
+       inet6_rth_space.3 inet6_rth_add.3 \
+       inet6_rth_space.3 inet6_rth_reverse.3 \
+       inet6_rth_space.3 inet6_rth_segments.3 \
+       inet6_rth_space.3 inet6_rth_getaddr.3 \
+       rcmd.3 rcmd_af.3 rcmd.3 iruserok_sa.3 rcmd.3 rresvport_af.3 \
+       rcmd.3 orcmd_af.3
diff --git a/lib/nbsd_libc/net/base64.c b/lib/nbsd_libc/net/base64.c
new file mode 100644 (file)
index 0000000..1868f76
--- /dev/null
@@ -0,0 +1,343 @@
+/*     $NetBSD: base64.c,v 1.12 2009/04/12 17:07:17 christos Exp $     */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/*
+ * Portions Copyright (c) 1995 by International Business Machines, Inc.
+ *
+ * International Business Machines, Inc. (hereinafter called IBM) grants
+ * permission under its copyrights to use, copy, modify, and distribute this
+ * Software with or without fee, provided that the above copyright notice and
+ * all paragraphs of this notice appear in all copies, and that the name of IBM
+ * not be used in connection with the marketing of any product incorporating
+ * the Software or modifications thereof, without specific, written prior
+ * permission.
+ *
+ * To the extent it has a right to do so, IBM grants an immunity from suit
+ * under its patents, if any, for the use, sale or manufacture of products to
+ * the extent that such products are used for performing Domain Name System
+ * dynamic updates in TCP/IP networks by means of the Software.  No immunity is
+ * granted for any product per se or for any other function of any product.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+ * PARTICULAR PURPOSE.  IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL,
+ * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING
+ * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN
+ * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static const char rcsid[] = "Id: base64.c,v 1.4 2005/04/27 04:56:34 sra Exp";
+#else
+__RCSID("$NetBSD: base64.c,v 1.12 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <resolv.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "port_after.h"
+
+#define Assert(Cond) if (!(Cond)) abort()
+
+static const char Base64[] =
+       "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+static const char Pad64 = '=';
+
+/* (From RFC1521 and draft-ietf-dnssec-secext-03.txt)
+   The following encoding technique is taken from RFC1521 by Borenstein
+   and Freed.  It is reproduced here in a slightly edited form for
+   convenience.
+
+   A 65-character subset of US-ASCII is used, enabling 6 bits to be
+   represented per printable character. (The extra 65th character, "=",
+   is used to signify a special processing function.)
+
+   The encoding process represents 24-bit groups of input bits as output
+   strings of 4 encoded characters. Proceeding from left to right, a
+   24-bit input group is formed by concatenating 3 8-bit input groups.
+   These 24 bits are then treated as 4 concatenated 6-bit groups, each
+   of which is translated into a single digit in the base64 alphabet.
+
+   Each 6-bit group is used as an index into an array of 64 printable
+   characters. The character referenced by the index is placed in the
+   output string.
+
+                         Table 1: The Base64 Alphabet
+
+      Value Encoding  Value Encoding  Value Encoding  Value Encoding
+          0 A            17 R            34 i            51 z
+          1 B            18 S            35 j            52 0
+          2 C            19 T            36 k            53 1
+          3 D            20 U            37 l            54 2
+          4 E            21 V            38 m            55 3
+          5 F            22 W            39 n            56 4
+          6 G            23 X            40 o            57 5
+          7 H            24 Y            41 p            58 6
+          8 I            25 Z            42 q            59 7
+          9 J            26 a            43 r            60 8
+         10 K            27 b            44 s            61 9
+         11 L            28 c            45 t            62 +
+         12 M            29 d            46 u            63 /
+         13 N            30 e            47 v
+         14 O            31 f            48 w         (pad) =
+         15 P            32 g            49 x
+         16 Q            33 h            50 y
+
+   Special processing is performed if fewer than 24 bits are available
+   at the end of the data being encoded.  A full encoding quantum is
+   always completed at the end of a quantity.  When fewer than 24 input
+   bits are available in an input group, zero bits are added (on the
+   right) to form an integral number of 6-bit groups.  Padding at the
+   end of the data is performed using the '=' character.
+
+   Since all base64 input is an integral number of octets, only the
+         -------------------------------------------------                       
+   following cases can arise:
+   
+       (1) the final quantum of encoding input is an integral
+           multiple of 24 bits; here, the final unit of encoded
+          output will be an integral multiple of 4 characters
+          with no "=" padding,
+       (2) the final quantum of encoding input is exactly 8 bits;
+           here, the final unit of encoded output will be two
+          characters followed by two "=" padding characters, or
+       (3) the final quantum of encoding input is exactly 16 bits;
+           here, the final unit of encoded output will be three
+          characters followed by one "=" padding character.
+   */
+
+int
+b64_ntop(u_char const *src, size_t srclength, char *target, size_t targsize) {
+       size_t datalength = 0;
+       u_char input[3];
+       u_char output[4];
+       size_t i;
+
+       _DIAGASSERT(src != NULL);
+       _DIAGASSERT(target != NULL);
+
+       while (2U < srclength) {
+               input[0] = *src++;
+               input[1] = *src++;
+               input[2] = *src++;
+               srclength -= 3;
+
+               output[0] = (u_int32_t)input[0] >> 2;
+               output[1] = ((u_int32_t)(input[0] & 0x03) << 4) +
+                   ((u_int32_t)input[1] >> 4);
+               output[2] = ((u_int32_t)(input[1] & 0x0f) << 2) +
+                   ((u_int32_t)input[2] >> 6);
+               output[3] = input[2] & 0x3f;
+               Assert(output[0] < 64);
+               Assert(output[1] < 64);
+               Assert(output[2] < 64);
+               Assert(output[3] < 64);
+
+               if (datalength + 4 > targsize)
+                       return (-1);
+               target[datalength++] = Base64[output[0]];
+               target[datalength++] = Base64[output[1]];
+               target[datalength++] = Base64[output[2]];
+               target[datalength++] = Base64[output[3]];
+       }
+    
+       /* Now we worry about padding. */
+       if (0U != srclength) {
+               /* Get what's left. */
+               input[0] = input[1] = input[2] = '\0';
+               for (i = 0; i < srclength; i++)
+                       input[i] = *src++;
+       
+               output[0] = (u_int32_t)input[0] >> 2;
+               output[1] = ((u_int32_t)(input[0] & 0x03) << 4) +
+                   ((u_int32_t)input[1] >> 4);
+               output[2] = ((u_int32_t)(input[1] & 0x0f) << 2) +
+                   ((u_int32_t)input[2] >> 6);
+               Assert(output[0] < 64);
+               Assert(output[1] < 64);
+               Assert(output[2] < 64);
+
+               if (datalength + 4 > targsize)
+                       return (-1);
+               target[datalength++] = Base64[output[0]];
+               target[datalength++] = Base64[output[1]];
+               if (srclength == 1U)
+                       target[datalength++] = Pad64;
+               else
+                       target[datalength++] = Base64[output[2]];
+               target[datalength++] = Pad64;
+       }
+       if (datalength >= targsize)
+               return (-1);
+       target[datalength] = '\0';      /*%< Returned value doesn't count \\0. */
+       return (datalength);
+}
+
+/* skips all whitespace anywhere.
+   converts characters, four at a time, starting at (or after)
+   src from base - 64 numbers into three 8 bit bytes in the target area.
+   it returns the number of data bytes stored at the target, or -1 on error.
+ */
+
+int
+b64_pton(src, target, targsize)
+       char const *src;
+       u_char *target;
+       size_t targsize;
+{
+       size_t tarindex;
+       int state, ch;
+       char *pos;
+
+       _DIAGASSERT(src != NULL);
+       _DIAGASSERT(target != NULL);
+
+       state = 0;
+       tarindex = 0;
+
+       while ((ch = (u_char) *src++) != '\0') {
+               if (isspace(ch))        /*%< Skip whitespace anywhere. */
+                       continue;
+
+               if (ch == Pad64)
+                       break;
+
+               pos = strchr(Base64, ch);
+               if (pos == 0)           /*%< A non-base64 character. */
+                       return (-1);
+
+               switch (state) {
+               case 0:
+                       if (target) {
+                               if ((size_t)tarindex >= targsize)
+                                       return (-1);
+                               target[tarindex] = (pos - Base64) << 2;
+                       }
+                       state = 1;
+                       break;
+               case 1:
+                       if (target) {
+                               if ((size_t)tarindex + 1 >= targsize)
+                                       return (-1);
+                               target[tarindex] |= 
+                                   (u_int32_t)(pos - Base64) >> 4;
+                               target[tarindex+1]  = ((pos - Base64) & 0x0f)
+                                                       << 4 ;
+                       }
+                       tarindex++;
+                       state = 2;
+                       break;
+               case 2:
+                       if (target) {
+                               if ((size_t)tarindex + 1 >= targsize)
+                                       return (-1);
+                               target[tarindex] |= 
+                                       (u_int32_t)(pos - Base64) >> 2;
+                               target[tarindex+1] = ((pos - Base64) & 0x03)
+                                                       << 6;
+                       }
+                       tarindex++;
+                       state = 3;
+                       break;
+               case 3:
+                       if (target) {
+                               if ((size_t)tarindex >= targsize)
+                                       return (-1);
+                               target[tarindex] |= (pos - Base64);
+                       }
+                       tarindex++;
+                       state = 0;
+                       break;
+               default:
+                       abort();
+               }
+       }
+
+       /*
+        * We are done decoding Base-64 chars.  Let's see if we ended
+        * on a byte boundary, and/or with erroneous trailing characters.
+        */
+
+       if (ch == Pad64) {              /*%< We got a pad char. */
+               ch = *src++;            /*%< Skip it, get next. */
+               switch (state) {
+               case 0:         /*%< Invalid = in first position */
+               case 1:         /*%< Invalid = in second position */
+                       return (-1);
+
+               case 2:         /*%< Valid, means one byte of info */
+                       /* Skip any number of spaces. */
+                       for (; ch != '\0'; ch = (u_char) *src++)
+                               if (!isspace(ch))
+                                       break;
+                       /* Make sure there is another trailing = sign. */
+                       if (ch != Pad64)
+                               return (-1);
+                       ch = *src++;            /*%< Skip the = */
+                       /* Fall through to "single trailing =" case. */
+                       /* FALLTHROUGH */
+
+               case 3:         /*%< Valid, means two bytes of info */
+                       /*
+                        * We know this char is an =.  Is there anything but
+                        * whitespace after it?
+                        */
+                       for (; ch != '\0'; ch = (u_char) *src++)
+                               if (!isspace(ch))
+                                       return (-1);
+
+                       /*
+                        * Now make sure for cases 2 and 3 that the "extra"
+                        * bits that slopped past the last full byte were
+                        * zeros.  If we don't check them, they become a
+                        * subliminal channel.
+                        */
+                       if (target && target[tarindex] != 0)
+                               return (-1);
+               }
+       } else {
+               /*
+                * We ended by seeing the end of the string.  Make sure we
+                * have no partial bytes lying around.
+                */
+               if (state != 0)
+                       return (-1);
+       }
+
+       return (tarindex);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/net/byteorder.3 b/lib/nbsd_libc/net/byteorder.3
new file mode 100644 (file)
index 0000000..bc52e51
--- /dev/null
@@ -0,0 +1,91 @@
+.\"    $NetBSD: byteorder.3,v 1.14 2006/02/04 22:47:28 uwe Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)byteorder.3        8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 10, 2004
+.Dt BYTEORDER 3
+.Os
+.Sh NAME
+.Nm htonl ,
+.Nm htons ,
+.Nm ntohl ,
+.Nm ntohs
+.Nd convert values between host and network byte order
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In arpa/inet.h
+.Ft uint32_t
+.Fn htonl "uint32_t host32"
+.Ft uint16_t
+.Fn htons "uint16_t host16"
+.Ft uint32_t
+.Fn ntohl "uint32_t net32"
+.Ft uint16_t
+.Fn ntohs "uint16_t net16"
+.Sh DESCRIPTION
+These routines convert 16 and 32 bit quantities between network
+byte order and host byte order.
+.Pp
+On machines which have a byte order which is the same as the network
+order, these routines are defined as macros that expand to the value of
+their argument.
+.Pp
+These routines are most often used in conjunction with Internet
+addresses and ports as returned by
+.Xr gethostbyname 3
+and
+.Xr getservent 3 .
+.Sh SEE ALSO
+.Xr gethostbyname 3 ,
+.Xr getservent 3
+.Sh STANDARDS
+The
+.Fn htonl ,
+.Fn htons ,
+.Fn ntohl ,
+and
+.Fn ntohs
+functions conform to
+.St -p1003.1-2001 .
+Their use of the fixed-width integer types
+.Fa uint16_t
+and
+.Fa uint32_t
+first appeared in
+.St -xns5 .
+.Sh HISTORY
+The
+.Nm byteorder
+functions appeared in
+.Bx 4.2 .
+.Sh BUGS
+The `l' and `s' suffixes in the names are not meaningful in machines
+where long integers are not 32 bits.
diff --git a/lib/nbsd_libc/net/ethers.3 b/lib/nbsd_libc/net/ethers.3
new file mode 100644 (file)
index 0000000..212ed1f
--- /dev/null
@@ -0,0 +1,120 @@
+.\"    $NetBSD: ethers.3,v 1.13 2003/04/16 13:34:41 wiz Exp $
+.\"
+.\" Written by roland@frob.com.  Public domain.
+.\"
+.Dd November 2, 1997
+.Dt ETHERS 3
+.Os
+.Sh NAME
+.Nm ether_ntoa ,
+.Nm ether_aton ,
+.Nm ether_ntohost ,
+.Nm ether_hostton ,
+.Nm ether_line ,
+.Nd get ethers entry
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/socket.h
+.In net/if.h
+.In net/if_ether.h
+.Ft char *
+.Fn ether_ntoa "const struct ether_addr *e"
+.Ft struct ether_addr *
+.Fn ether_aton "const char *s"
+.Ft int
+.Fn ether_ntohost "char *hostname" "const struct ether_addr *e"
+.Ft int
+.Fn ether_hostton "const char *hostname" "struct ether_addr *e"
+.Ft int
+.Fn ether_line "const char *line" "struct ether_addr *e" "char *hostname"
+.Sh DESCRIPTION
+Ethernet addresses are represented by the
+following structure:
+.Bd -literal -offset indent
+struct ether_addr {
+        u_char  ether_addr_octet[6];
+};
+.Ed
+.Pp
+The
+.Fn ether_ntoa
+function converts this structure into an ASCII string of the form
+``xx:xx:xx:xx:xx:xx'', consisting of 6 hexadecimal numbers separated
+by colons.  It returns a pointer to a static buffer that is reused for
+each call.
+The
+.Fn ether_aton
+converts an ASCII string of the same form and to a structure
+containing the 6 octets of the address.  It returns a pointer to a
+static structure that is reused for each call.
+.Pp
+The
+.Fn ether_ntohost
+and
+.Fn ether_hostton
+functions interrogate the data base mapping host names to Ethernet
+addresses,
+.Pa /etc/ethers .
+The
+.Fn ether_ntohost
+function looks up the given Ethernet address and writes the associated
+host name into the character buffer passed.
+The
+.Fn ether_hostton
+function looks up the given host name and writes the associated
+Ethernet address into the structure passed.  Both functions return
+zero if they find the requested host name or address, and -1 if not.
+Each call reads
+.Pa /etc/ethers
+from the beginning; if a + appears alone on a line in the file, then
+.Fn ether_hostton
+will consult the
+.Pa ethers.byname
+YP map, and
+.Fn ether_ntohost
+will consult the
+.Pa ethers.byaddr
+YP map.
+.Pp
+The
+.Fn ether_line
+function parses a line from the
+.Pa /etc/ethers
+file and fills in the passed ``struct ether_addr'' and character
+buffer with the Ethernet address and host name on the line.  It
+returns zero if the line was successfully parsed and -1 if not.
+.Pp
+The
+.Fa hostname
+buffer for
+.Fn ether_line
+and
+.Fn ether_ntohost
+should be at least
+.Dv MAXHOSTNAMELEN
++ 1
+characters long, to prevent a buffer overflow during parsing.
+.Sh FILES
+.Bl -tag -width /etc/ethers -compact
+.It Pa /etc/ethers
+.El
+.Sh SEE ALSO
+.Xr ethers 5
+.Sh HISTORY
+The
+.Fn ether_ntoa ,
+.Fn ether_aton ,
+.Fn ether_ntohost ,
+.Fn ether_hostton ,
+and
+.Fn ether_line
+functions were adopted from
+.Tn SunOS
+and appeared in
+.Nx 1.0 .
+.Sh BUGS
+The data space used by these functions is static; if future use
+requires the data, it should be copied before any subsequent calls to
+these functions overwrite it.
diff --git a/lib/nbsd_libc/net/ethers.c b/lib/nbsd_libc/net/ethers.c
new file mode 100644 (file)
index 0000000..25a582c
--- /dev/null
@@ -0,0 +1,230 @@
+/*     $NetBSD: ethers.c,v 1.21 2006/10/15 10:55:01 martin Exp $       */
+
+/* 
+ * ethers(3N) a la Sun.
+ *
+ * Written by Roland McGrath <roland@frob.com> 10/14/93.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ethers.c,v 1.21 2006/10/15 10:55:01 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/socket.h>
+
+#include <net/if.h>
+#include <net/if_ether.h>
+#include <netinet/in.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <paths.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef YP
+#include <rpcsvc/ypclnt.h>
+#endif
+
+#ifdef __weak_alias
+__weak_alias(ether_aton,_ether_aton)
+__weak_alias(ether_hostton,_ether_hostton)
+__weak_alias(ether_line,_ether_line)
+__weak_alias(ether_ntoa,_ether_ntoa)
+__weak_alias(ether_ntohost,_ether_ntohost)
+#endif
+
+#ifndef _PATH_ETHERS
+#define _PATH_ETHERS "/etc/ethers"
+#endif
+
+char *
+ether_ntoa(e)
+       const struct ether_addr *e;
+{
+       static char a[18];
+
+       _DIAGASSERT(e != NULL);
+
+       (void) snprintf(a, sizeof a, "%02x:%02x:%02x:%02x:%02x:%02x",
+           e->ether_addr_octet[0], e->ether_addr_octet[1],
+           e->ether_addr_octet[2], e->ether_addr_octet[3],
+           e->ether_addr_octet[4], e->ether_addr_octet[5]);
+       return a;
+}
+
+struct ether_addr *
+ether_aton(s)
+       const char *s;
+{
+       static struct ether_addr n;
+       u_int i[6];
+
+       _DIAGASSERT(s != NULL);
+
+       if (sscanf(s, " %x:%x:%x:%x:%x:%x ", &i[0], &i[1],
+           &i[2], &i[3], &i[4], &i[5]) == 6) {
+               n.ether_addr_octet[0] = (u_char)i[0];
+               n.ether_addr_octet[1] = (u_char)i[1];
+               n.ether_addr_octet[2] = (u_char)i[2];
+               n.ether_addr_octet[3] = (u_char)i[3];
+               n.ether_addr_octet[4] = (u_char)i[4];
+               n.ether_addr_octet[5] = (u_char)i[5];
+               return &n;
+       }
+       return NULL;
+}
+
+int
+ether_ntohost(hostname, e)
+       char *hostname;
+       const struct ether_addr *e;
+{
+       FILE *f; 
+       char *p;
+       size_t len;
+       struct ether_addr try;
+#ifdef YP
+       char trybuf[sizeof "xx:xx:xx:xx:xx:xx"];
+       int trylen;
+#endif
+
+       _DIAGASSERT(hostname != NULL);
+       _DIAGASSERT(e != NULL);
+
+#ifdef YP
+       trylen = snprintf(trybuf, sizeof trybuf, "%x:%x:%x:%x:%x:%x", 
+           e->ether_addr_octet[0], e->ether_addr_octet[1],
+           e->ether_addr_octet[2], e->ether_addr_octet[3],
+           e->ether_addr_octet[4], e->ether_addr_octet[5]);
+#endif
+
+       f = fopen(_PATH_ETHERS, "r");
+       if (f == NULL)
+               return -1;
+       while ((p = fgetln(f, &len)) != NULL) {
+               if (p[len - 1] != '\n')
+                       continue;               /* skip lines w/o \n */
+               p[--len] = '\0';
+#ifdef YP
+               /* A + in the file means try YP now.  */
+               if (len == 1 && *p == '+') {
+                       char *ypbuf, *ypdom;
+                       int ypbuflen;
+
+                       if (yp_get_default_domain(&ypdom))
+                               continue;
+                       if (yp_match(ypdom, "ethers.byaddr", trybuf,
+                           trylen, &ypbuf, &ypbuflen))
+                               continue;
+                       if (ether_line(ypbuf, &try, hostname) == 0) {
+                               free(ypbuf);
+                               (void)fclose(f);
+                               return 0;
+                       }
+                       free(ypbuf);
+                       continue;
+               }
+#endif
+               if (ether_line(p, &try, hostname) == 0 &&
+                   memcmp(&try, e, sizeof try) == 0) {
+                       (void)fclose(f);
+                       return 0;
+               }     
+       }
+       (void)fclose(f);
+       errno = ENOENT;
+       return -1;
+}
+
+int
+ether_hostton(hostname, e)
+       const char *hostname;
+       struct ether_addr *e;
+{
+       FILE *f;
+       char *p;
+       size_t len;
+       char try[MAXHOSTNAMELEN + 1];
+#ifdef YP
+       int hostlen = strlen(hostname);
+#endif
+
+       _DIAGASSERT(hostname != NULL);
+       _DIAGASSERT(e != NULL);
+
+       f = fopen(_PATH_ETHERS, "r");
+       if (f==NULL)
+               return -1;
+
+       while ((p = fgetln(f, &len)) != NULL) {
+               if (p[len - 1] != '\n')
+                       continue;               /* skip lines w/o \n */
+               p[--len] = '\0';
+#ifdef YP
+               /* A + in the file means try YP now.  */
+               if (len == 1 && *p == '+') {
+                       char *ypbuf, *ypdom;
+                       int ypbuflen;
+
+                       if (yp_get_default_domain(&ypdom))
+                               continue;
+                       if (yp_match(ypdom, "ethers.byname", hostname, hostlen,
+                           &ypbuf, &ypbuflen))
+                               continue;
+                       if (ether_line(ypbuf, e, try) == 0) {
+                               free(ypbuf);
+                               (void)fclose(f);
+                               return 0;
+                       }
+                       free(ypbuf);
+                       continue;
+               }
+#endif
+               if (ether_line(p, e, try) == 0 && strcmp(hostname, try) == 0) {
+                       (void)fclose(f);
+                       return 0;
+               }
+       }
+       (void)fclose(f);
+       errno = ENOENT;
+       return -1;
+}
+
+int
+ether_line(l, e, hostname)
+       const char *l;
+       struct ether_addr *e;
+       char *hostname;
+{
+       u_int i[6];
+
+#define S2(arg) #arg
+#define S1(arg) S2(arg)
+       static const char fmt[] = " %x:%x:%x:%x:%x:%x"
+           " %" S1(MAXHOSTNAMELEN) "s\n";
+#undef S2
+#undef S1
+       
+       _DIAGASSERT(l != NULL);
+       _DIAGASSERT(e != NULL);
+       _DIAGASSERT(hostname != NULL);
+
+       if (sscanf(l, fmt,
+           &i[0], &i[1], &i[2], &i[3], &i[4], &i[5], hostname) == 7) {
+               e->ether_addr_octet[0] = (u_char)i[0];
+               e->ether_addr_octet[1] = (u_char)i[1];
+               e->ether_addr_octet[2] = (u_char)i[2];
+               e->ether_addr_octet[3] = (u_char)i[3];
+               e->ether_addr_octet[4] = (u_char)i[4];
+               e->ether_addr_octet[5] = (u_char)i[5];
+               return 0;
+       }
+       errno = EINVAL;
+       return -1;
+}
diff --git a/lib/nbsd_libc/net/gai_strerror.3 b/lib/nbsd_libc/net/gai_strerror.3
new file mode 100644 (file)
index 0000000..d3e9059
--- /dev/null
@@ -0,0 +1,96 @@
+.\"    $NetBSD: gai_strerror.3,v 1.5 2010/03/22 19:30:54 joerg Exp $
+.\"    $KAME: gai_strerror.3,v 1.1 2005/01/05 03:04:47 itojun Exp $
+.\"    $OpenBSD: gai_strerror.3,v 1.4 2004/12/20 23:04:53 millert Exp $
+.\"
+.\" Copyright (C) 2004  Internet Systems Consortium, Inc. ("ISC")
+.\" Copyright (C) 2000, 2001  Internet Software Consortium.
+.\"
+.\" 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 ISC DISCLAIMS ALL WARRANTIES WITH
+.\" REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+.\" AND FITNESS.  IN NO EVENT SHALL ISC 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.
+.\"
+.Dd February 22, 2006
+.Dt GAI_STRERROR 3
+.Os
+.Sh NAME
+.Nm gai_strerror
+.Nd get error message string from EAI_xxx error code
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/socket.h
+.In netdb.h
+.Ft const char *
+.Fn gai_strerror "int ecode"
+.Sh DESCRIPTION
+The
+.Fn gai_strerror
+function returns an error message string corresponding to the error code
+returned by
+.Xr getaddrinfo 3
+or
+.Xr getnameinfo 3 .
+.Pp
+The following error codes and their meaning are defined in
+.In netdb.h :
+.Pp
+.Bl -tag -width "EAI_ADDRFAMILYXX" -offset indent -compact
+.It Dv EAI_ADDRFAMILY
+address family for
+.Fa hostname
+not supported
+.It Dv EAI_AGAIN
+temporary failure in name resolution
+.It Dv EAI_BADFLAGS
+invalid value for
+.Fa ai_flags
+.It Dv EAI_BADHINTS
+invalid value for
+.Fa hints
+.It Dv EAI_FAIL
+non-recoverable failure in name resolution
+.It Dv EAI_FAMILY
+.Fa ai_family
+not supported.
+.It Dv EAI_MEMORY
+memory allocation failure
+.It Dv EAI_NODATA
+no address associated with
+.Fa hostname
+.It Dv EAI_NONAME
+.Fa hostname
+or
+.Fa servname
+not provided, or not known
+.It Dv EAI_OVERFLOW
+argument buffer overflow
+.It Dv EAI_PROTOCOL
+resolved protocol is unknown
+.It Dv EAI_SERVICE
+.Fa servname
+not supported for
+.Fa ai_socktype
+.It Dv EAI_SOCKTYPE
+.Fa ai_socktype
+not supported
+.It Dv EAI_SYSTEM
+system error returned in
+.Va errno
+.El
+.Sh RETURN VALUES
+.Fn gai_strerror
+returns a pointer to the error message string corresponding to
+.Fa ecode .
+If
+.Fa ecode
+is out of range, an implementation-specific error message string is returned.
+.Sh SEE ALSO
+.Xr getaddrinfo 3 ,
+.Xr getnameinfo 3
diff --git a/lib/nbsd_libc/net/getaddrinfo.3 b/lib/nbsd_libc/net/getaddrinfo.3
new file mode 100644 (file)
index 0000000..ca0a903
--- /dev/null
@@ -0,0 +1,488 @@
+.\"    $NetBSD: getaddrinfo.3,v 1.55 2010/04/17 20:28:47 wiz Exp $
+.\"    $KAME: getaddrinfo.3,v 1.36 2005/01/05 03:23:05 itojun Exp $
+.\"    $OpenBSD: getaddrinfo.3,v 1.35 2004/12/21 03:40:31 jaredy Exp $
+.\"
+.\" Copyright (C) 2004  Internet Systems Consortium, Inc. ("ISC")
+.\" Copyright (C) 2000, 2001  Internet Software Consortium.
+.\"
+.\" 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 ISC DISCLAIMS ALL WARRANTIES WITH
+.\" REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+.\" AND FITNESS.  IN NO EVENT SHALL ISC 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.
+.\"
+.Dd April 17, 2010
+.Dt GETADDRINFO 3
+.Os
+.Sh NAME
+.Nm getaddrinfo ,
+.Nm freeaddrinfo ,
+.Nm allocaddrinfo
+.Nd host and service name to socket address structure
+.Sh SYNOPSIS
+.In netdb.h
+.Ft int
+.Fn getaddrinfo "const char * restrict hostname" \
+    "const char * restrict servname" \
+    "const struct addrinfo * restrict hints" "struct addrinfo ** restrict res"
+.Ft void
+.Fn freeaddrinfo "struct addrinfo *ai"
+.Ft struct addrinfo *
+.Fn allocaddrinfo "socklen_t len"
+.Sh DESCRIPTION
+The
+.Fn getaddrinfo
+function is used to get a list of
+.Tn IP
+addresses and port numbers for host
+.Fa hostname
+and service
+.Fa servname .
+It is a replacement for and provides more flexibility than the
+.Xr gethostbyname 3
+and
+.Xr getservbyname 3
+functions.
+.Pp
+The
+.Fa hostname
+and
+.Fa servname
+arguments are either pointers to NUL-terminated strings or the null pointer.
+An acceptable value for
+.Fa hostname
+is either a valid host name or a numeric host address string consisting
+of a dotted decimal IPv4 address or an IPv6 address.
+The
+.Fa servname
+is either a decimal port number or a service name listed in
+.Xr services 5 .
+At least one of
+.Fa hostname
+and
+.Fa servname
+must be non-null.
+.Pp
+.Fa hints
+is an optional pointer to a
+.Li struct addrinfo ,
+as defined by
+.In netdb.h :
+.Bd -literal
+struct addrinfo {
+       int ai_flags;           /* input flags */
+       int ai_family;          /* address family for socket */
+       int ai_socktype;        /* socket type */
+       int ai_protocol;        /* protocol for socket */
+       socklen_t ai_addrlen;   /* length of socket-address */
+       struct sockaddr *ai_addr; /* socket-address for socket */
+       char *ai_canonname;     /* canonical name for service location */
+       struct addrinfo *ai_next; /* pointer to next in list */
+};
+.Ed
+.Pp
+This structure can be used to provide hints concerning the type of socket
+that the caller supports or wishes to use.
+The caller can supply the following structure elements in
+.Fa hints :
+.Bl -tag -width "ai_socktypeXX"
+.It Fa ai_family
+The address
+.Pq and protocol
+family that should be used.
+When
+.Fa ai_family
+is set to
+.Dv AF_UNSPEC ,
+it means the caller will accept any address family supported by the
+operating system.
+Note that while address families
+.Pq Dv AF_*
+and protocol families
+.Pq Dv PF_*
+are theoretically distinct, in practice the distinction has been lost.
+.\" (.Dv !? Consistent with usage below though...)
+.Dv "RFC 3493"
+defines
+.Fn getaddrinfo
+in terms of the address family constants
+.Dv AF_*
+even though
+.Fa ai_family
+is to be passed as a protocol family to
+.Xr socket 2 .
+.It Fa ai_socktype
+Denotes the type of socket that is wanted:
+.Dv SOCK_STREAM ,
+.Dv SOCK_DGRAM ,
+or
+.Dv SOCK_RAW .
+When
+.Fa ai_socktype
+is zero the caller will accept any socket type.
+.It Fa ai_protocol
+Indicates which transport protocol is desired,
+.Dv IPPROTO_UDP
+or
+.Dv IPPROTO_TCP .
+If
+.Fa ai_protocol
+is zero the caller will accept any protocol.
+.It Fa ai_flags
+.Fa ai_flags
+is formed by
+.Tn OR Ns 'ing
+the following values:
+.Bl -tag -width "AI_CANONNAMEXX"
+.It Dv AI_CANONNAME
+If the
+.Dv AI_CANONNAME
+bit is set, a successful call to
+.Fn getaddrinfo
+will return a NUL-terminated string containing the canonical name
+of the specified hostname in the
+.Fa ai_canonname
+element of the first
+.Li addrinfo
+structure returned.
+.It Dv AI_NUMERICHOST
+If the
+.Dv AI_NUMERICHOST
+bit is set, it indicates that
+.Fa hostname
+should be treated as a numeric string defining an IPv4 or IPv6 address
+and no name resolution should be attempted.
+.It Dv AI_NUMERICSERV
+If the
+.Dv AI_NUMERICSERV
+bit is set, it indicates that the
+.Fa servname
+string contains a numeric port number.
+This is used to prevent service name resolution.
+.It Dv AI_PASSIVE
+If the
+.Dv AI_PASSIVE
+bit is set it indicates that the returned socket address structure
+is intended for use in a call to
+.Xr bind 2 .
+In this case, if the
+.Fa hostname
+argument is the null pointer, then the IP address portion of the
+socket address structure will be set to
+.Dv INADDR_ANY
+for an IPv4 address or
+.Dv IN6ADDR_ANY_INIT
+for an IPv6 address.
+.Pp
+If the
+.Dv AI_PASSIVE
+bit is not set, the returned socket address structure will be ready
+for use in a call to
+.Xr connect 2
+for a connection-oriented protocol or
+.Xr connect 2 ,
+.Xr sendto 2 ,
+or
+.Xr sendmsg 2
+if a connectionless protocol was chosen.
+The
+.Tn IP
+address portion of the socket address structure will be set to the
+loopback address if
+.Fa hostname
+is the null pointer and
+.Dv AI_PASSIVE
+is not set.
+.El
+.El
+.Pp
+All other elements of the
+.Li addrinfo
+structure passed via
+.Fa hints
+must be zero or the null pointer.
+.Pp
+If
+.Fa hints
+is the null pointer,
+.Fn getaddrinfo
+behaves as if the caller provided a
+.Li struct addrinfo
+with
+.Fa ai_family
+set to
+.Dv AF_UNSPEC
+and all other elements set to zero or
+.Dv NULL .
+.Pp
+After a successful call to
+.Fn getaddrinfo ,
+.Fa *res
+is a pointer to a linked list of one or more
+.Li addrinfo
+structures.
+The list can be traversed by following the
+.Fa ai_next
+pointer in each
+.Li addrinfo
+structure until a null pointer is encountered.
+The three members
+.Fa ai_family ,
+.Fa ai_socktype ,
+and
+.Fa ai_protocol
+in each returned
+.Li addrinfo
+structure are suitable for a call to
+.Xr socket 2 .
+For each
+.Li addrinfo
+structure in the list, the
+.Fa ai_addr
+member points to a filled-in socket address structure of length
+.Fa ai_addrlen .
+.Pp
+This implementation of
+.Fn getaddrinfo
+allows numeric IPv6 address notation with scope identifier,
+as documented in chapter 11 of draft-ietf-ipv6-scoping-arch-02.txt.
+By appending the percent character and scope identifier to addresses,
+one can fill the
+.Li sin6_scope_id
+field for addresses.
+This would make management of scoped addresses easier
+and allows cut-and-paste input of scoped addresses.
+.Pp
+At this moment the code supports only link-local addresses with the format.
+The scope identifier is hardcoded to the name of the hardware interface
+associated
+with the link
+.Po
+such as
+.Li ne0
+.Pc .
+An example is
+.Dq Li fe80::1%ne0 ,
+which means
+.Do
+.Li fe80::1
+on the link associated with the
+.Li ne0
+interface
+.Dc .
+.Pp
+The current implementation assumes a one-to-one relationship between
+the interface and link, which is not necessarily true from the specification.
+.Pp
+All of the information returned by
+.Fn getaddrinfo
+is dynamically allocated: the
+.Li addrinfo
+structures themselves as well as the socket address structures and
+the canonical host name strings included in the
+.Li addrinfo
+structures.
+.Pp
+Memory allocated for the dynamically allocated structures created by
+a successful call to
+.Fn getaddrinfo
+is released by the
+.Fn freeaddrinfo
+function.
+The
+.Fa ai
+pointer should be an
+.Li addrinfo
+structure created by a call to
+.Fn getaddrinfo
+or
+.Fn allocaddrinfo .
+The
+.Fn allocaddrinfo
+function is intended primarily for authors of
+.Xr nsdispatch 3
+plugins implementing
+.Fn getaddrinfo
+backends.
+.Fn allocaddrinfo
+allocates a
+.Li struct addrinfo
+in a way that is compatible with being returned from
+.Fn getaddrinfo
+and being ultimately freed by
+.Fn freeaddrinfo .
+The returned structure is zeroed, except for the
+.Fa ai_addr
+field, which
+will point to
+.Fa len
+bytes of memory for storage of a socket address.
+It is safe to allocate memory separately for
+.Fa ai_canonname
+with
+.Xr malloc 3 ,
+or in any other way that is compatible with deallocation by
+.Xr free 3 .
+.Sh RETURN VALUES
+.Fn getaddrinfo
+returns zero on success or one of the error codes listed in
+.Xr gai_strerror 3
+if an error occurs.
+.Sh EXAMPLES
+The following code tries to connect to
+.Dq Li www.kame.net
+service
+.Dq Li http
+via a stream socket.
+It loops through all the addresses available, regardless of address family.
+If the destination resolves to an IPv4 address, it will use an
+.Dv AF_INET
+socket.
+Similarly, if it resolves to IPv6, an
+.Dv AF_INET6
+socket is used.
+Observe that there is no hardcoded reference to a particular address family.
+The code works even if
+.Fn getaddrinfo
+returns addresses that are not IPv4/v6.
+.Bd -literal -offset indent
+struct addrinfo hints, *res, *res0;
+int error;
+int s;
+const char *cause = NULL;
+
+memset(\*[Am]hints, 0, sizeof(hints));
+hints.ai_family = AF_UNSPEC;
+hints.ai_socktype = SOCK_STREAM;
+error = getaddrinfo("www.kame.net", "http", \*[Am]hints, \*[Am]res0);
+if (error) {
+       errx(1, "%s", gai_strerror(error));
+       /*NOTREACHED*/
+}
+s = -1;
+for (res = res0; res; res = res-\*[Gt]ai_next) {
+       s = socket(res-\*[Gt]ai_family, res-\*[Gt]ai_socktype,
+           res-\*[Gt]ai_protocol);
+       if (s \*[Lt] 0) {
+               cause = "socket";
+               continue;
+       }
+
+       if (connect(s, res-\*[Gt]ai_addr, res-\*[Gt]ai_addrlen) \*[Lt] 0) {
+               cause = "connect";
+               close(s);
+               s = -1;
+               continue;
+       }
+
+       break;  /* okay we got one */
+}
+if (s \*[Lt] 0) {
+       err(1, "%s", cause);
+       /*NOTREACHED*/
+}
+freeaddrinfo(res0);
+.Ed
+.Pp
+The following example tries to open a wildcard listening socket onto service
+.Dq Li http ,
+for all the address families available.
+.Bd -literal -offset indent
+struct addrinfo hints, *res, *res0;
+int error;
+int s[MAXSOCK];
+int nsock;
+const char *cause = NULL;
+
+memset(\*[Am]hints, 0, sizeof(hints));
+hints.ai_family = AF_UNSPEC;
+hints.ai_socktype = SOCK_STREAM;
+hints.ai_flags = AI_PASSIVE;
+error = getaddrinfo(NULL, "http", \*[Am]hints, \*[Am]res0);
+if (error) {
+       errx(1, "%s", gai_strerror(error));
+       /*NOTREACHED*/
+}
+nsock = 0;
+for (res = res0; res \*[Am]\*[Am] nsock \*[Lt] MAXSOCK; res = res-\*[Gt]ai_next) {
+       s[nsock] = socket(res-\*[Gt]ai_family, res-\*[Gt]ai_socktype,
+           res-\*[Gt]ai_protocol);
+       if (s[nsock] \*[Lt] 0) {
+               cause = "socket";
+               continue;
+       }
+
+       if (bind(s[nsock], res-\*[Gt]ai_addr, res-\*[Gt]ai_addrlen) \*[Lt] 0) {
+               cause = "bind";
+               close(s[nsock]);
+               continue;
+       }
+       (void) listen(s[nsock], 5);
+
+       nsock++;
+}
+if (nsock == 0) {
+       err(1, "%s", cause);
+       /*NOTREACHED*/
+}
+freeaddrinfo(res0);
+.Ed
+.Sh SEE ALSO
+.Xr bind 2 ,
+.Xr connect 2 ,
+.Xr send 2 ,
+.Xr socket 2 ,
+.Xr gai_strerror 3 ,
+.Xr gethostbyname 3 ,
+.Xr getnameinfo 3 ,
+.Xr getservbyname 3 ,
+.Xr resolver 3 ,
+.Xr hosts 5 ,
+.Xr resolv.conf 5 ,
+.Xr services 5 ,
+.Xr hostname 7 ,
+.Xr named 8
+.Rs
+.%A R. Gilligan
+.%A S. Thomson
+.%A J. Bound
+.%A J. McCann
+.%A W. Stevens
+.%T Basic Socket Interface Extensions for IPv6
+.%R RFC 3493
+.%D February 2003
+.Re
+.Rs
+.%A S. Deering
+.%A B. Haberman
+.%A T. Jinmei
+.%A E. Nordmark
+.%A B. Zill
+.%T "IPv6 Scoped Address Architecture"
+.%R internet draft
+.%N draft-ietf-ipv6-scoping-arch-02.txt
+.%O work in progress material
+.Re
+.Rs
+.%A Craig Metz
+.%T "Protocol Independence Using the Sockets API"
+.%I USENIX Association
+.%B Proceedings of the FREENIX Track: 2000 USENIX Annual Technical Conference
+.%D June 18-23, 2000
+.%P 99-108
+.%U http://www.usenix.org/events/usenix2000/freenix/metzprotocol/metzprotocol.pdf
+.Re
+.Sh STANDARDS
+The
+.Fn getaddrinfo
+function is defined by the
+.St -p1003.1g-2000
+draft specification and documented in
+.Dv "RFC 3493" ,
+.Dq Basic Socket Interface Extensions for IPv6 .
diff --git a/lib/nbsd_libc/net/getaddrinfo.c b/lib/nbsd_libc/net/getaddrinfo.c
new file mode 100644 (file)
index 0000000..41e6488
--- /dev/null
@@ -0,0 +1,1958 @@
+/*     $NetBSD: getaddrinfo.c,v 1.95 2009/10/02 07:41:08 wiz Exp $     */
+/*     $KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $    */
+
+/*
+ * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
+ * 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.
+ * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
+ */
+
+/*
+ * Issues to be discussed:
+ * - Return values.  There are nonstandard return values defined and used
+ *   in the source code.  This is because RFC2553 is silent about which error
+ *   code must be returned for which situation.
+ * - IPv4 classful (shortened) form.  RFC2553 is silent about it.  XNET 5.2
+ *   says to use inet_aton() to convert IPv4 numeric to binary (alows
+ *   classful form as a result).
+ *   current code - disallow classful form for IPv4 (due to use of inet_pton).
+ * - freeaddrinfo(NULL).  RFC2553 is silent about it.  XNET 5.2 says it is
+ *   invalid.
+ *   current code - SEGV on freeaddrinfo(NULL)
+ * Note:
+ * - The code filters out AFs that are not supported by the kernel,
+ *   when globbing NULL hostname (to loopback, or wildcard).  Is it the right
+ *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
+ *   in ai_flags?
+ * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
+ *   (1) what should we do against numeric hostname (2) what should we do
+ *   against NULL hostname (3) what is AI_ADDRCONFIG itself.  AF not ready?
+ *   non-loopback address configured?  global address configured?
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getaddrinfo.c,v 1.95 2009/10/02 07:41:08 wiz Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <net/if.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <netdb.h>
+#include <resolv.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <syslog.h>
+#include <stdarg.h>
+#include <nsswitch.h>
+
+#ifdef YP
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+#endif
+
+#include "servent.h"
+
+#ifdef __weak_alias
+__weak_alias(getaddrinfo,_getaddrinfo)
+__weak_alias(freeaddrinfo,_freeaddrinfo)
+__weak_alias(gai_strerror,_gai_strerror)
+#endif
+
+#define SUCCESS 0
+#define ANY 0
+#define YES 1
+#define NO  0
+
+static const char in_addrany[] = { 0, 0, 0, 0 };
+static const char in_loopback[] = { 127, 0, 0, 1 };
+#ifdef INET6
+static const char in6_addrany[] = {
+       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+static const char in6_loopback[] = {
+       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
+};
+#endif
+
+static const struct afd {
+       int a_af;
+       int a_addrlen;
+       int a_socklen;
+       int a_off;
+       const char *a_addrany;
+       const char *a_loopback; 
+       int a_scoped;
+} afdl [] = {
+#ifdef INET6
+       {PF_INET6, sizeof(struct in6_addr),
+        sizeof(struct sockaddr_in6),
+        offsetof(struct sockaddr_in6, sin6_addr),
+        in6_addrany, in6_loopback, 1},
+#endif
+       {PF_INET, sizeof(struct in_addr),
+        sizeof(struct sockaddr_in),
+        offsetof(struct sockaddr_in, sin_addr),
+        in_addrany, in_loopback, 0},
+       {0, 0, 0, 0, NULL, NULL, 0},
+};
+
+struct explore {
+       int e_af;
+       int e_socktype;
+       int e_protocol;
+       const char *e_protostr;
+       int e_wild;
+#define WILD_AF(ex)            ((ex)->e_wild & 0x01)
+#define WILD_SOCKTYPE(ex)      ((ex)->e_wild & 0x02)
+#define WILD_PROTOCOL(ex)      ((ex)->e_wild & 0x04)
+};
+
+static const struct explore explore[] = {
+#if 0
+       { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
+#endif
+#ifdef INET6
+       { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
+       { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
+       { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
+#endif
+       { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
+       { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
+       { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
+       { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
+       { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
+       { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
+       { -1, 0, 0, NULL, 0 },
+};
+
+#ifdef INET6
+#define PTON_MAX       16
+#else
+#define PTON_MAX       4
+#endif
+
+static const ns_src default_dns_files[] = {
+       { NSSRC_FILES,  NS_SUCCESS },
+       { NSSRC_DNS,    NS_SUCCESS },
+       { 0, 0 }
+};
+
+#define MAXPACKET      (64*1024)
+
+typedef union {
+       HEADER hdr;
+       u_char buf[MAXPACKET];
+} querybuf;
+
+struct res_target {
+       struct res_target *next;
+       const char *name;       /* domain name */
+       int qclass, qtype;      /* class and type of query */
+       u_char *answer;         /* buffer to put answer */
+       int anslen;             /* size of answer buffer */
+       int n;                  /* result length */
+};
+
+static int str2number(const char *);
+static int explore_fqdn(const struct addrinfo *, const char *,
+       const char *, struct addrinfo **, struct servent_data *);
+static int explore_null(const struct addrinfo *,
+       const char *, struct addrinfo **, struct servent_data *);
+static int explore_numeric(const struct addrinfo *, const char *,
+       const char *, struct addrinfo **, const char *, struct servent_data *);
+static int explore_numeric_scope(const struct addrinfo *, const char *,
+       const char *, struct addrinfo **, struct servent_data *);
+static int get_canonname(const struct addrinfo *,
+       struct addrinfo *, const char *);
+static struct addrinfo *get_ai(const struct addrinfo *,
+       const struct afd *, const char *);
+static int get_portmatch(const struct addrinfo *, const char *,
+    struct servent_data *);
+static int get_port(const struct addrinfo *, const char *, int,
+    struct servent_data *);
+static const struct afd *find_afd(int);
+#ifdef INET6
+static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
+#endif
+
+static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
+       const struct addrinfo *);
+static void aisort(struct addrinfo *s, res_state res);
+static int _dns_getaddrinfo(void *, void *, va_list);
+static void _sethtent(FILE **);
+static void _endhtent(FILE **);
+static struct addrinfo *_gethtent(FILE **, const char *,
+    const struct addrinfo *);
+static int _files_getaddrinfo(void *, void *, va_list);
+#ifdef YP
+static struct addrinfo *_yphostent(char *, const struct addrinfo *);
+static int _yp_getaddrinfo(void *, void *, va_list);
+#endif
+
+static int res_queryN(const char *, struct res_target *, res_state);
+static int res_searchN(const char *, struct res_target *, res_state);
+static int res_querydomainN(const char *, const char *,
+       struct res_target *, res_state);
+
+static const char * const ai_errlist[] = {
+       "Success",
+       "Address family for hostname not supported",    /* EAI_ADDRFAMILY */
+       "Temporary failure in name resolution",         /* EAI_AGAIN      */
+       "Invalid value for ai_flags",                   /* EAI_BADFLAGS   */
+       "Non-recoverable failure in name resolution",   /* EAI_FAIL       */
+       "ai_family not supported",                      /* EAI_FAMILY     */
+       "Memory allocation failure",                    /* EAI_MEMORY     */
+       "No address associated with hostname",          /* EAI_NODATA     */
+       "hostname nor servname provided, or not known", /* EAI_NONAME     */
+       "servname not supported for ai_socktype",       /* EAI_SERVICE    */
+       "ai_socktype not supported",                    /* EAI_SOCKTYPE   */
+       "System error returned in errno",               /* EAI_SYSTEM     */
+       "Invalid value for hints",                      /* EAI_BADHINTS   */
+       "Resolved protocol is unknown",                 /* EAI_PROTOCOL   */
+       "Argument buffer overflow",                     /* EAI_OVERFLOW   */
+       "Unknown error",                                /* EAI_MAX        */
+};
+
+/* XXX macros that make external reference is BAD. */
+
+#define GET_AI(ai, afd, addr)                                  \
+do {                                                           \
+       /* external reference: pai, error, and label free */    \
+       (ai) = get_ai(pai, (afd), (addr));                      \
+       if ((ai) == NULL) {                                     \
+               error = EAI_MEMORY;                             \
+               goto free;                                      \
+       }                                                       \
+} while (/*CONSTCOND*/0)
+
+#define GET_PORT(ai, serv, svd)                                \
+do {                                                           \
+       /* external reference: error and label free */          \
+       error = get_port((ai), (serv), 0, (svd));               \
+       if (error != 0)                                         \
+               goto free;                                      \
+} while (/*CONSTCOND*/0)
+
+#define GET_CANONNAME(ai, str)                                         \
+do {                                                           \
+       /* external reference: pai, error and label free */     \
+       error = get_canonname(pai, (ai), (str));                \
+       if (error != 0)                                         \
+               goto free;                                      \
+} while (/*CONSTCOND*/0)
+
+#define ERR(err)                                               \
+do {                                                           \
+       /* external reference: error, and label bad */          \
+       error = (err);                                          \
+       goto bad;                                               \
+       /*NOTREACHED*/                                          \
+} while (/*CONSTCOND*/0)
+
+#define MATCH_FAMILY(x, y, w)                                          \
+       ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC ||        \
+           (y) == PF_UNSPEC))) 
+#define MATCH(x, y, w)                                                         \
+       ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
+
+const char *
+gai_strerror(int ecode)
+{
+       if (ecode < 0 || ecode > EAI_MAX)
+               ecode = EAI_MAX;
+       return ai_errlist[ecode];
+}
+
+void
+freeaddrinfo(struct addrinfo *ai)
+{
+       struct addrinfo *next;
+
+       _DIAGASSERT(ai != NULL);
+
+       do {
+               next = ai->ai_next;
+               if (ai->ai_canonname)
+                       free(ai->ai_canonname);
+               /* no need to free(ai->ai_addr) */
+               free(ai);
+               ai = next;
+       } while (ai);
+}
+
+static int
+str2number(const char *p)
+{
+       char *ep;
+       unsigned long v;
+
+       _DIAGASSERT(p != NULL);
+
+       if (*p == '\0')
+               return -1;
+       ep = NULL;
+       errno = 0;
+       v = strtoul(p, &ep, 10);
+       if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
+               return v;
+       else
+               return -1;
+}
+
+int
+getaddrinfo(const char *hostname, const char *servname,
+    const struct addrinfo *hints, struct addrinfo **res)
+{
+       struct addrinfo sentinel;
+       struct addrinfo *cur;
+       int error = 0;
+       struct addrinfo ai;
+       struct addrinfo ai0;
+       struct addrinfo *pai;
+       const struct explore *ex;
+       struct servent_data svd;
+
+       /* hostname is allowed to be NULL */
+       /* servname is allowed to be NULL */
+       /* hints is allowed to be NULL */
+       _DIAGASSERT(res != NULL);
+
+       (void)memset(&svd, 0, sizeof(svd));
+       memset(&sentinel, 0, sizeof(sentinel));
+       cur = &sentinel;
+       memset(&ai, 0, sizeof(ai));
+       pai = &ai;
+       pai->ai_flags = 0;
+       pai->ai_family = PF_UNSPEC;
+       pai->ai_socktype = ANY;
+       pai->ai_protocol = ANY;
+       pai->ai_addrlen = 0;
+       pai->ai_canonname = NULL;
+       pai->ai_addr = NULL;
+       pai->ai_next = NULL;
+       
+       if (hostname == NULL && servname == NULL)
+               return EAI_NONAME;
+       if (hints) {
+               /* error check for hints */
+               if (hints->ai_addrlen || hints->ai_canonname ||
+                   hints->ai_addr || hints->ai_next)
+                       ERR(EAI_BADHINTS); /* xxx */
+               if (hints->ai_flags & ~AI_MASK)
+                       ERR(EAI_BADFLAGS);
+               switch (hints->ai_family) {
+               case PF_UNSPEC:
+               case PF_INET:
+#ifdef INET6
+               case PF_INET6:
+#endif
+                       break;
+               default:
+                       ERR(EAI_FAMILY);
+               }
+               memcpy(pai, hints, sizeof(*pai));
+
+               /*
+                * if both socktype/protocol are specified, check if they
+                * are meaningful combination.
+                */
+               if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
+                       for (ex = explore; ex->e_af >= 0; ex++) {
+                               if (pai->ai_family != ex->e_af)
+                                       continue;
+                               if (ex->e_socktype == ANY)
+                                       continue;
+                               if (ex->e_protocol == ANY)
+                                       continue;
+                               if (pai->ai_socktype == ex->e_socktype
+                                && pai->ai_protocol != ex->e_protocol) {
+                                       ERR(EAI_BADHINTS);
+                               }
+                       }
+               }
+       }
+
+       /*
+        * check for special cases.  (1) numeric servname is disallowed if
+        * socktype/protocol are left unspecified. (2) servname is disallowed
+        * for raw and other inet{,6} sockets.
+        */
+       if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
+#ifdef PF_INET6
+        || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
+#endif
+           ) {
+               ai0 = *pai;     /* backup *pai */
+
+               if (pai->ai_family == PF_UNSPEC) {
+#ifdef PF_INET6
+                       pai->ai_family = PF_INET6;
+#else
+                       pai->ai_family = PF_INET;
+#endif
+               }
+               error = get_portmatch(pai, servname, &svd);
+               if (error)
+                       ERR(error);
+
+               *pai = ai0;
+       }
+
+       ai0 = *pai;
+
+       /* NULL hostname, or numeric hostname */
+       for (ex = explore; ex->e_af >= 0; ex++) {
+               *pai = ai0;
+
+               /* PF_UNSPEC entries are prepared for DNS queries only */
+               if (ex->e_af == PF_UNSPEC)
+                       continue;
+
+               if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
+                       continue;
+               if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
+                       continue;
+               if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
+                       continue;
+
+               if (pai->ai_family == PF_UNSPEC)
+                       pai->ai_family = ex->e_af;
+               if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
+                       pai->ai_socktype = ex->e_socktype;
+               if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
+                       pai->ai_protocol = ex->e_protocol;
+
+               if (hostname == NULL)
+                       error = explore_null(pai, servname, &cur->ai_next,
+                           &svd);
+               else
+                       error = explore_numeric_scope(pai, hostname, servname,
+                           &cur->ai_next, &svd);
+
+               if (error)
+                       goto free;
+
+               while (cur->ai_next)
+                       cur = cur->ai_next;
+       }
+
+       /*
+        * XXX
+        * If numeric representation of AF1 can be interpreted as FQDN
+        * representation of AF2, we need to think again about the code below.
+        */
+       if (sentinel.ai_next)
+               goto good;
+
+       if (hostname == NULL)
+               ERR(EAI_NODATA);
+       if (pai->ai_flags & AI_NUMERICHOST)
+               ERR(EAI_NONAME);
+
+       /*
+        * hostname as alphabetical name.
+        * we would like to prefer AF_INET6 than AF_INET, so we'll make a
+        * outer loop by AFs.
+        */
+       for (ex = explore; ex->e_af >= 0; ex++) {
+               *pai = ai0;
+
+               /* require exact match for family field */
+               if (pai->ai_family != ex->e_af)
+                       continue;
+
+               if (!MATCH(pai->ai_socktype, ex->e_socktype,
+                               WILD_SOCKTYPE(ex))) {
+                       continue;
+               }
+               if (!MATCH(pai->ai_protocol, ex->e_protocol,
+                               WILD_PROTOCOL(ex))) {
+                       continue;
+               }
+
+               if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
+                       pai->ai_socktype = ex->e_socktype;
+               if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
+                       pai->ai_protocol = ex->e_protocol;
+
+               error = explore_fqdn(pai, hostname, servname, &cur->ai_next,
+                   &svd);
+
+               while (cur && cur->ai_next)
+                       cur = cur->ai_next;
+       }
+
+       /* XXX */
+       if (sentinel.ai_next)
+               error = 0;
+
+       if (error)
+               goto free;
+
+       if (sentinel.ai_next) {
+ good:
+               endservent_r(&svd);
+               *res = sentinel.ai_next;
+               return SUCCESS;
+       } else
+               error = EAI_FAIL;
+ free:
+ bad:
+       endservent_r(&svd);
+       if (sentinel.ai_next)
+               freeaddrinfo(sentinel.ai_next);
+       *res = NULL;
+       return error;
+}
+
+/*
+ * FQDN hostname, DNS lookup
+ */
+static int
+explore_fqdn(const struct addrinfo *pai, const char *hostname,
+    const char *servname, struct addrinfo **res, struct servent_data *svd)
+{
+       struct addrinfo *result;
+       struct addrinfo *cur;
+       int error = 0;
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getaddrinfo, NULL)
+               { NSSRC_DNS, _dns_getaddrinfo, NULL },  /* force -DHESIOD */
+               NS_NIS_CB(_yp_getaddrinfo, NULL)
+               NS_NULL_CB
+       };
+
+       _DIAGASSERT(pai != NULL);
+       /* hostname may be NULL */
+       /* servname may be NULL */
+       _DIAGASSERT(res != NULL);
+
+       result = NULL;
+
+       /*
+        * if the servname does not match socktype/protocol, ignore it.
+        */
+       if (get_portmatch(pai, servname, svd) != 0)
+               return 0;
+
+       switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
+                       default_dns_files, hostname, pai)) {
+       case NS_TRYAGAIN:
+               error = EAI_AGAIN;
+               goto free;
+       case NS_UNAVAIL:
+               error = EAI_FAIL;
+               goto free;
+       case NS_NOTFOUND:
+               error = EAI_NODATA;
+               goto free;
+       case NS_SUCCESS:
+               error = 0;
+               for (cur = result; cur; cur = cur->ai_next) {
+                       GET_PORT(cur, servname, svd);
+                       /* canonname should be filled already */
+               }
+               break;
+       }
+
+       *res = result;
+
+       return 0;
+
+free:
+       if (result)
+               freeaddrinfo(result);
+       return error;
+}
+
+/*
+ * hostname == NULL.
+ * passive socket -> anyaddr (0.0.0.0 or ::)
+ * non-passive socket -> localhost (127.0.0.1 or ::1)
+ */
+static int
+explore_null(const struct addrinfo *pai, const char *servname,
+    struct addrinfo **res, struct servent_data *svd)
+{
+       int s;
+       const struct afd *afd;
+       struct addrinfo *cur;
+       struct addrinfo sentinel;
+       int error;
+
+       _DIAGASSERT(pai != NULL);
+       /* servname may be NULL */
+       _DIAGASSERT(res != NULL);
+
+       *res = NULL;
+       sentinel.ai_next = NULL;
+       cur = &sentinel;
+
+       /*
+        * filter out AFs that are not supported by the kernel
+        * XXX errno?
+        */
+       s = socket(pai->ai_family, SOCK_DGRAM, 0);
+       if (s < 0) {
+               if (errno != EMFILE)
+                       return 0;
+       } else
+               close(s);
+
+       /*
+        * if the servname does not match socktype/protocol, ignore it.
+        */
+       if (get_portmatch(pai, servname, svd) != 0)
+               return 0;
+
+       afd = find_afd(pai->ai_family);
+       if (afd == NULL)
+               return 0;
+
+       if (pai->ai_flags & AI_PASSIVE) {
+               GET_AI(cur->ai_next, afd, afd->a_addrany);
+               /* xxx meaningless?
+                * GET_CANONNAME(cur->ai_next, "anyaddr");
+                */
+               GET_PORT(cur->ai_next, servname, svd);
+       } else {
+               GET_AI(cur->ai_next, afd, afd->a_loopback);
+               /* xxx meaningless?
+                * GET_CANONNAME(cur->ai_next, "localhost");
+                */
+               GET_PORT(cur->ai_next, servname, svd);
+       }
+       cur = cur->ai_next;
+
+       *res = sentinel.ai_next;
+       return 0;
+
+free:
+       if (sentinel.ai_next)
+               freeaddrinfo(sentinel.ai_next);
+       return error;
+}
+
+/*
+ * numeric hostname
+ */
+static int
+explore_numeric(const struct addrinfo *pai, const char *hostname,
+    const char *servname, struct addrinfo **res, const char *canonname,
+    struct servent_data *svd)
+{
+       const struct afd *afd;
+       struct addrinfo *cur;
+       struct addrinfo sentinel;
+       int error;
+       char pton[PTON_MAX];
+
+       _DIAGASSERT(pai != NULL);
+       /* hostname may be NULL */
+       /* servname may be NULL */
+       _DIAGASSERT(res != NULL);
+
+       *res = NULL;
+       sentinel.ai_next = NULL;
+       cur = &sentinel;
+
+       /*
+        * if the servname does not match socktype/protocol, ignore it.
+        */
+       if (get_portmatch(pai, servname, svd) != 0)
+               return 0;
+
+       afd = find_afd(pai->ai_family);
+       if (afd == NULL)
+               return 0;
+
+       switch (afd->a_af) {
+#if 0 /*X/Open spec*/
+       case AF_INET:
+               if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
+                       if (pai->ai_family == afd->a_af ||
+                           pai->ai_family == PF_UNSPEC /*?*/) {
+                               GET_AI(cur->ai_next, afd, pton);
+                               GET_PORT(cur->ai_next, servname, svd);
+                               if ((pai->ai_flags & AI_CANONNAME)) {
+                                       /*
+                                        * Set the numeric address itself as
+                                        * the canonical name, based on a
+                                        * clarification in rfc2553bis-03.
+                                        */
+                                       GET_CANONNAME(cur->ai_next, canonname);
+                               }
+                               while (cur && cur->ai_next)
+                                       cur = cur->ai_next;
+                       } else
+                               ERR(EAI_FAMILY);        /*xxx*/
+               }
+               break;
+#endif
+       default:
+               if (inet_pton(afd->a_af, hostname, pton) == 1) {
+                       if (pai->ai_family == afd->a_af ||
+                           pai->ai_family == PF_UNSPEC /*?*/) {
+                               GET_AI(cur->ai_next, afd, pton);
+                               GET_PORT(cur->ai_next, servname, svd);
+                               if ((pai->ai_flags & AI_CANONNAME)) {
+                                       /*
+                                        * Set the numeric address itself as
+                                        * the canonical name, based on a
+                                        * clarification in rfc2553bis-03.
+                                        */
+                                       GET_CANONNAME(cur->ai_next, canonname);
+                               }
+                               while (cur->ai_next)
+                                       cur = cur->ai_next;
+                       } else
+                               ERR(EAI_FAMILY);        /*xxx*/
+               }
+               break;
+       }
+
+       *res = sentinel.ai_next;
+       return 0;
+
+free:
+bad:
+       if (sentinel.ai_next)
+               freeaddrinfo(sentinel.ai_next);
+       return error;
+}
+
+/*
+ * numeric hostname with scope
+ */
+static int
+explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
+    const char *servname, struct addrinfo **res, struct servent_data *svd)
+{
+#if !defined(SCOPE_DELIMITER) || !defined(INET6)
+       return explore_numeric(pai, hostname, servname, res, hostname, svd);
+#else
+       const struct afd *afd;
+       struct addrinfo *cur;
+       int error;
+       char *cp, *hostname2 = NULL, *scope, *addr;
+       struct sockaddr_in6 *sin6;
+
+       _DIAGASSERT(pai != NULL);
+       /* hostname may be NULL */
+       /* servname may be NULL */
+       _DIAGASSERT(res != NULL);
+
+       /*
+        * if the servname does not match socktype/protocol, ignore it.
+        */
+       if (get_portmatch(pai, servname, svd) != 0)
+               return 0;
+
+       afd = find_afd(pai->ai_family);
+       if (afd == NULL)
+               return 0;
+
+       if (!afd->a_scoped)
+               return explore_numeric(pai, hostname, servname, res, hostname,
+                   svd);
+
+       cp = strchr(hostname, SCOPE_DELIMITER);
+       if (cp == NULL)
+               return explore_numeric(pai, hostname, servname, res, hostname,
+                   svd);
+
+       /*
+        * Handle special case of <scoped_address><delimiter><scope id>
+        */
+       hostname2 = strdup(hostname);
+       if (hostname2 == NULL)
+               return EAI_MEMORY;
+       /* terminate at the delimiter */
+       hostname2[cp - hostname] = '\0';
+       addr = hostname2;
+       scope = cp + 1;
+
+       error = explore_numeric(pai, addr, servname, res, hostname, svd);
+       if (error == 0) {
+               u_int32_t scopeid;
+
+               for (cur = *res; cur; cur = cur->ai_next) {
+                       if (cur->ai_family != AF_INET6)
+                               continue;
+                       sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
+                       if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
+                               free(hostname2);
+                               return(EAI_NODATA); /* XXX: is return OK? */
+                       }
+                       sin6->sin6_scope_id = scopeid;
+               }
+       }
+
+       free(hostname2);
+
+       return error;
+#endif
+}
+
+static int
+get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
+{
+
+       _DIAGASSERT(pai != NULL);
+       _DIAGASSERT(ai != NULL);
+       _DIAGASSERT(str != NULL);
+
+       if ((pai->ai_flags & AI_CANONNAME) != 0) {
+               ai->ai_canonname = strdup(str);
+               if (ai->ai_canonname == NULL)
+                       return EAI_MEMORY;
+       }
+       return 0;
+}
+
+struct addrinfo *
+allocaddrinfo(socklen_t addrlen)
+{
+       struct addrinfo *ai;
+
+       ai = calloc(sizeof(struct addrinfo) + addrlen, 1);
+       if (ai) {
+               ai->ai_addr = (void *)(ai+1);
+               ai->ai_addrlen = ai->ai_addr->sa_len = addrlen;
+       }
+
+       return ai;
+}
+
+static struct addrinfo *
+get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
+{
+       char *p;
+       struct addrinfo *ai;
+       struct sockaddr *save;
+
+       _DIAGASSERT(pai != NULL);
+       _DIAGASSERT(afd != NULL);
+       _DIAGASSERT(addr != NULL);
+
+       ai = allocaddrinfo((socklen_t)afd->a_socklen);
+       if (ai == NULL)
+               return NULL;
+
+        save = ai->ai_addr;
+       memcpy(ai, pai, sizeof(struct addrinfo));
+
+        /* since we just overwrote all of ai, we have
+           to restore ai_addr and ai_addrlen */
+        ai->ai_addr = save;
+        ai->ai_addrlen = (socklen_t)afd->a_socklen;
+        
+       ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
+       p = (char *)(void *)(ai->ai_addr);
+       memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
+       return ai;
+}
+
+static int
+get_portmatch(const struct addrinfo *ai, const char *servname,
+    struct servent_data *svd)
+{
+
+       _DIAGASSERT(ai != NULL);
+       /* servname may be NULL */
+
+       return get_port(ai, servname, 1, svd);
+}
+
+static int
+get_port(const struct addrinfo *ai, const char *servname, int matchonly,
+    struct servent_data *svd)
+{
+       const char *proto;
+       struct servent *sp;
+       int port;
+       int allownumeric;
+
+       _DIAGASSERT(ai != NULL);
+       /* servname may be NULL */
+
+       if (servname == NULL)
+               return 0;
+       switch (ai->ai_family) {
+       case AF_INET:
+#ifdef AF_INET6
+       case AF_INET6:
+#endif
+               break;
+       default:
+               return 0;
+       }
+
+       switch (ai->ai_socktype) {
+       case SOCK_RAW:
+               return EAI_SERVICE;
+       case SOCK_DGRAM:
+       case SOCK_STREAM:
+               allownumeric = 1;
+               break;
+       case ANY:
+               /*
+                * This was 0.  It is now 1 so that queries specifying
+                * a NULL hint, or hint without socktype (but, hopefully,
+                * with protocol) and numeric address actually work.
+                */
+               allownumeric = 1;
+               break;
+       default:
+               return EAI_SOCKTYPE;
+       }
+
+       port = str2number(servname);
+       if (port >= 0) {
+               if (!allownumeric)
+                       return EAI_SERVICE;
+               if (port < 0 || port > 65535)
+                       return EAI_SERVICE;
+               port = htons(port);
+       } else {
+               struct servent sv;
+               if (ai->ai_flags & AI_NUMERICSERV)
+                       return EAI_NONAME;
+
+               switch (ai->ai_socktype) {
+               case SOCK_DGRAM:
+                       proto = "udp";
+                       break;
+               case SOCK_STREAM:
+                       proto = "tcp";
+                       break;
+               default:
+                       proto = NULL;
+                       break;
+               }
+
+               sp = getservbyname_r(servname, proto, &sv, svd);
+               if (sp == NULL)
+                       return EAI_SERVICE;
+               port = sp->s_port;
+       }
+
+       if (!matchonly) {
+               switch (ai->ai_family) {
+               case AF_INET:
+                       ((struct sockaddr_in *)(void *)
+                           ai->ai_addr)->sin_port = port;
+                       break;
+#ifdef INET6
+               case AF_INET6:
+                       ((struct sockaddr_in6 *)(void *)
+                           ai->ai_addr)->sin6_port = port;
+                       break;
+#endif
+               }
+       }
+
+       return 0;
+}
+
+static const struct afd *
+find_afd(int af)
+{
+       const struct afd *afd;
+
+       if (af == PF_UNSPEC)
+               return NULL;
+       for (afd = afdl; afd->a_af; afd++) {
+               if (afd->a_af == af)
+                       return afd;
+       }
+       return NULL;
+}
+
+#ifdef INET6
+/* convert a string to a scope identifier. XXX: IPv6 specific */
+static int
+ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
+{
+       u_long lscopeid;
+       struct in6_addr *a6;
+       char *ep;
+
+       _DIAGASSERT(scope != NULL);
+       _DIAGASSERT(sin6 != NULL);
+       _DIAGASSERT(scopeid != NULL);
+
+       a6 = &sin6->sin6_addr;
+
+       /* empty scopeid portion is invalid */
+       if (*scope == '\0')
+               return -1;
+
+       if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
+               /*
+                * We currently assume a one-to-one mapping between links
+                * and interfaces, so we simply use interface indices for
+                * like-local scopes.
+                */
+               *scopeid = if_nametoindex(scope);
+               if (*scopeid == 0)
+                       goto trynumeric;
+               return 0;
+       }
+
+       /* still unclear about literal, allow numeric only - placeholder */
+       if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
+               goto trynumeric;
+       if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
+               goto trynumeric;
+       else
+               goto trynumeric;        /* global */
+
+       /* try to convert to a numeric id as a last resort */
+  trynumeric:
+       errno = 0;
+       lscopeid = strtoul(scope, &ep, 10);
+       *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
+       if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
+               return 0;
+       else
+               return -1;
+}
+#endif
+
+/* code duplicate with gethnamaddr.c */
+
+static const char AskedForGot[] =
+       "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
+
+static struct addrinfo *
+getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
+    const struct addrinfo *pai)
+{
+       struct addrinfo sentinel, *cur;
+       struct addrinfo ai;
+       const struct afd *afd;
+       char *canonname;
+       const HEADER *hp;
+       const u_char *cp;
+       int n;
+       const u_char *eom;
+       char *bp, *ep;
+       int type, class, ancount, qdcount;
+       int haveanswer, had_error;
+       char tbuf[MAXDNAME];
+       int (*name_ok) (const char *);
+       char hostbuf[8*1024];
+
+       _DIAGASSERT(answer != NULL);
+       _DIAGASSERT(qname != NULL);
+       _DIAGASSERT(pai != NULL);
+
+       memset(&sentinel, 0, sizeof(sentinel));
+       cur = &sentinel;
+
+       canonname = NULL;
+       eom = answer->buf + anslen;
+       switch (qtype) {
+       case T_A:
+       case T_AAAA:
+       case T_ANY:     /*use T_ANY only for T_A/T_AAAA lookup*/
+               name_ok = res_hnok;
+               break;
+       default:
+               return NULL;    /* XXX should be abort(); */
+       }
+       /*
+        * find first satisfactory answer
+        */
+       hp = &answer->hdr;
+       ancount = ntohs(hp->ancount);
+       qdcount = ntohs(hp->qdcount);
+       bp = hostbuf;
+       ep = hostbuf + sizeof hostbuf;
+       cp = answer->buf + HFIXEDSZ;
+       if (qdcount != 1) {
+               h_errno = NO_RECOVERY;
+               return (NULL);
+       }
+       n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
+       if ((n < 0) || !(*name_ok)(bp)) {
+               h_errno = NO_RECOVERY;
+               return (NULL);
+       }
+       cp += n + QFIXEDSZ;
+       if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
+               /* res_send() has already verified that the query name is the
+                * same as the one we sent; this just gets the expanded name
+                * (i.e., with the succeeding search-domain tacked on).
+                */
+               n = strlen(bp) + 1;             /* for the \0 */
+               if (n >= MAXHOSTNAMELEN) {
+                       h_errno = NO_RECOVERY;
+                       return (NULL);
+               }
+               canonname = bp;
+               bp += n;
+               /* The qname can be abbreviated, but h_name is now absolute. */
+               qname = canonname;
+       }
+       haveanswer = 0;
+       had_error = 0;
+       while (ancount-- > 0 && cp < eom && !had_error) {
+               n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
+               if ((n < 0) || !(*name_ok)(bp)) {
+                       had_error++;
+                       continue;
+               }
+               cp += n;                        /* name */
+               type = _getshort(cp);
+               cp += INT16SZ;                  /* type */
+               class = _getshort(cp);
+               cp += INT16SZ + INT32SZ;        /* class, TTL */
+               n = _getshort(cp);
+               cp += INT16SZ;                  /* len */
+               if (class != C_IN) {
+                       /* XXX - debug? syslog? */
+                       cp += n;
+                       continue;               /* XXX - had_error++ ? */
+               }
+               if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
+                   type == T_CNAME) {
+                       n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
+                       if ((n < 0) || !(*name_ok)(tbuf)) {
+                               had_error++;
+                               continue;
+                       }
+                       cp += n;
+                       /* Get canonical name. */
+                       n = strlen(tbuf) + 1;   /* for the \0 */
+                       if (n > ep - bp || n >= MAXHOSTNAMELEN) {
+                               had_error++;
+                               continue;
+                       }
+                       strlcpy(bp, tbuf, (size_t)(ep - bp));
+                       canonname = bp;
+                       bp += n;
+                       continue;
+               }
+               if (qtype == T_ANY) {
+                       if (!(type == T_A || type == T_AAAA)) {
+                               cp += n;
+                               continue;
+                       }
+               } else if (type != qtype) {
+                       if (type != T_KEY && type != T_SIG) {
+                               struct syslog_data sd = SYSLOG_DATA_INIT;
+                               syslog_r(LOG_NOTICE|LOG_AUTH, &sd,
+              "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
+                                      qname, p_class(C_IN), p_type(qtype),
+                                      p_type(type));
+                       }
+                       cp += n;
+                       continue;               /* XXX - had_error++ ? */
+               }
+               switch (type) {
+               case T_A:
+               case T_AAAA:
+                       if (strcasecmp(canonname, bp) != 0) {
+                               struct syslog_data sd = SYSLOG_DATA_INIT;
+                               syslog_r(LOG_NOTICE|LOG_AUTH, &sd,
+                                      AskedForGot, canonname, bp);
+                               cp += n;
+                               continue;       /* XXX - had_error++ ? */
+                       }
+                       if (type == T_A && n != INADDRSZ) {
+                               cp += n;
+                               continue;
+                       }
+                       if (type == T_AAAA && n != IN6ADDRSZ) {
+                               cp += n;
+                               continue;
+                       }
+                       if (type == T_AAAA) {
+                               struct in6_addr in6;
+                               memcpy(&in6, cp, IN6ADDRSZ);
+                               if (IN6_IS_ADDR_V4MAPPED(&in6)) {
+                                       cp += n;
+                                       continue;
+                               }
+                       }
+                       if (!haveanswer) {
+                               int nn;
+
+                               canonname = bp;
+                               nn = strlen(bp) + 1;    /* for the \0 */
+                               bp += nn;
+                       }
+
+                       /* don't overwrite pai */
+                       ai = *pai;
+                       ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
+                       afd = find_afd(ai.ai_family);
+                       if (afd == NULL) {
+                               cp += n;
+                               continue;
+                       }
+                       cur->ai_next = get_ai(&ai, afd, (const char *)cp);
+                       if (cur->ai_next == NULL)
+                               had_error++;
+                       while (cur && cur->ai_next)
+                               cur = cur->ai_next;
+                       cp += n;
+                       break;
+               default:
+                       abort();
+               }
+               if (!had_error)
+                       haveanswer++;
+       }
+       if (haveanswer) {
+               if (!canonname)
+                       (void)get_canonname(pai, sentinel.ai_next, qname);
+               else
+                       (void)get_canonname(pai, sentinel.ai_next, canonname);
+               h_errno = NETDB_SUCCESS;
+               return sentinel.ai_next;
+       }
+
+       h_errno = NO_RECOVERY;
+       return NULL;
+}
+
+#define SORTEDADDR(p)  (((struct sockaddr_in *)(void *)(p->ai_next->ai_addr))->sin_addr.s_addr)
+#define SORTMATCH(p, s) ((SORTEDADDR(p) & (s).mask) == (s).addr.s_addr)
+
+static void
+aisort(struct addrinfo *s, res_state res)
+{
+       struct addrinfo head, *t, *p;
+       int i;
+
+       head.ai_next = NULL;
+       t = &head;
+
+       for (i = 0; i < res->nsort; i++) {
+               p = s;
+               while (p->ai_next) {
+                       if ((p->ai_next->ai_family != AF_INET)
+                       || SORTMATCH(p, res->sort_list[i])) {
+                               t->ai_next = p->ai_next;
+                               t = t->ai_next;
+                               p->ai_next = p->ai_next->ai_next;
+                       } else {
+                               p = p->ai_next;
+                       }
+               }
+       }
+
+       /* add rest of list and reset s to the new list*/
+       t->ai_next = s->ai_next;
+       s->ai_next = head.ai_next;
+}
+
+/*ARGSUSED*/
+static int
+_dns_getaddrinfo(void *rv, void        *cb_data, va_list ap)
+{
+       struct addrinfo *ai;
+       querybuf *buf, *buf2;
+       const char *name;
+       const struct addrinfo *pai;
+       struct addrinfo sentinel, *cur;
+       struct res_target q, q2;
+       res_state res;
+
+       name = va_arg(ap, char *);
+       pai = va_arg(ap, const struct addrinfo *);
+
+       memset(&q, 0, sizeof(q));
+       memset(&q2, 0, sizeof(q2));
+       memset(&sentinel, 0, sizeof(sentinel));
+       cur = &sentinel;
+
+       buf = malloc(sizeof(*buf));
+       if (buf == NULL) {
+               h_errno = NETDB_INTERNAL;
+               return NS_NOTFOUND;
+       }
+       buf2 = malloc(sizeof(*buf2));
+       if (buf2 == NULL) {
+               free(buf);
+               h_errno = NETDB_INTERNAL;
+               return NS_NOTFOUND;
+       }
+
+       switch (pai->ai_family) {
+       case AF_UNSPEC:
+               /* prefer IPv6 */
+               q.name = name;
+               q.qclass = C_IN;
+               q.qtype = T_AAAA;
+               q.answer = buf->buf;
+               q.anslen = sizeof(buf->buf);
+               q.next = &q2;
+               q2.name = name;
+               q2.qclass = C_IN;
+               q2.qtype = T_A;
+               q2.answer = buf2->buf;
+               q2.anslen = sizeof(buf2->buf);
+               break;
+       case AF_INET:
+               q.name = name;
+               q.qclass = C_IN;
+               q.qtype = T_A;
+               q.answer = buf->buf;
+               q.anslen = sizeof(buf->buf);
+               break;
+       case AF_INET6:
+               q.name = name;
+               q.qclass = C_IN;
+               q.qtype = T_AAAA;
+               q.answer = buf->buf;
+               q.anslen = sizeof(buf->buf);
+               break;
+       default:
+               free(buf);
+               free(buf2);
+               return NS_UNAVAIL;
+       }
+
+       res = __res_get_state();
+       if (res == NULL) {
+               free(buf);
+               free(buf2);
+               return NS_NOTFOUND;
+       }
+
+       if (res_searchN(name, &q, res) < 0) {
+               __res_put_state(res);
+               free(buf);
+               free(buf2);
+               return NS_NOTFOUND;
+       }
+       ai = getanswer(buf, q.n, q.name, q.qtype, pai);
+       if (ai) {
+               cur->ai_next = ai;
+               while (cur && cur->ai_next)
+                       cur = cur->ai_next;
+       }
+       if (q.next) {
+               ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
+               if (ai)
+                       cur->ai_next = ai;
+       }
+       free(buf);
+       free(buf2);
+       if (sentinel.ai_next == NULL) {
+               __res_put_state(res);
+               switch (h_errno) {
+               case HOST_NOT_FOUND:
+                       return NS_NOTFOUND;
+               case TRY_AGAIN:
+                       return NS_TRYAGAIN;
+               default:
+                       return NS_UNAVAIL;
+               }
+       }
+
+       if (res->nsort)
+               aisort(&sentinel, res);
+
+       __res_put_state(res);
+
+       *((struct addrinfo **)rv) = sentinel.ai_next;
+       return NS_SUCCESS;
+}
+
+static void
+_sethtent(FILE **hostf)
+{
+
+       if (!*hostf)
+               *hostf = fopen(_PATH_HOSTS, "r" );
+       else
+               rewind(*hostf);
+}
+
+static void
+_endhtent(FILE **hostf)
+{
+
+       if (*hostf) {
+               (void) fclose(*hostf);
+               *hostf = NULL;
+       }
+}
+
+static struct addrinfo *
+_gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
+{
+       char *p;
+       char *cp, *tname, *cname;
+       struct addrinfo hints, *res0, *res;
+       int error;
+       const char *addr;
+       char hostbuf[8*1024];
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(pai != NULL);
+
+       if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r" )))
+               return (NULL);
+ again:
+       if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
+               return (NULL);
+       if (*p == '#')
+               goto again;
+       if (!(cp = strpbrk(p, "#\n")))
+               goto again;
+       *cp = '\0';
+       if (!(cp = strpbrk(p, " \t")))
+               goto again;
+       *cp++ = '\0';
+       addr = p;
+       /* if this is not something we're looking for, skip it. */
+       cname = NULL;
+       while (cp && *cp) {
+               if (*cp == ' ' || *cp == '\t') {
+                       cp++;
+                       continue;
+               }
+               if (!cname)
+                       cname = cp;
+               tname = cp;
+               if ((cp = strpbrk(cp, " \t")) != NULL)
+                       *cp++ = '\0';
+               if (strcasecmp(name, tname) == 0)
+                       goto found;
+       }
+       goto again;
+
+found:
+       hints = *pai;
+       hints.ai_flags = AI_NUMERICHOST;
+       error = getaddrinfo(addr, NULL, &hints, &res0);
+       if (error)
+               goto again;
+       for (res = res0; res; res = res->ai_next) {
+               /* cover it up */
+               res->ai_flags = pai->ai_flags;
+
+               if (pai->ai_flags & AI_CANONNAME) {
+                       if (get_canonname(pai, res, cname) != 0) {
+                               freeaddrinfo(res0);
+                               goto again;
+                       }
+               }
+       }
+       return res0;
+}
+
+/*ARGSUSED*/
+static int
+_files_getaddrinfo(void *rv, void *cb_data, va_list ap)
+{
+       const char *name;
+       const struct addrinfo *pai;
+       struct addrinfo sentinel, *cur;
+       struct addrinfo *p;
+#ifndef _REENTRANT
+       static
+#endif
+       FILE *hostf = NULL;
+
+       name = va_arg(ap, char *);
+       pai = va_arg(ap, const struct addrinfo *);
+
+       memset(&sentinel, 0, sizeof(sentinel));
+       cur = &sentinel;
+
+       _sethtent(&hostf);
+       while ((p = _gethtent(&hostf, name, pai)) != NULL) {
+               cur->ai_next = p;
+               while (cur && cur->ai_next)
+                       cur = cur->ai_next;
+       }
+       _endhtent(&hostf);
+
+       *((struct addrinfo **)rv) = sentinel.ai_next;
+       if (sentinel.ai_next == NULL)
+               return NS_NOTFOUND;
+       return NS_SUCCESS;
+}
+
+#ifdef YP
+/*ARGSUSED*/
+static struct addrinfo *
+_yphostent(char *line, const struct addrinfo *pai)
+{
+       struct addrinfo sentinel, *cur;
+       struct addrinfo hints, *res, *res0;
+       int error;
+       char *p;
+       const char *addr, *canonname;
+       char *nextline;
+       char *cp;
+
+       _DIAGASSERT(line != NULL);
+       _DIAGASSERT(pai != NULL);
+
+       p = line;
+       addr = canonname = NULL;
+
+       memset(&sentinel, 0, sizeof(sentinel));
+       cur = &sentinel;
+
+nextline:
+       /* terminate line */
+       cp = strchr(p, '\n');
+       if (cp) {
+               *cp++ = '\0';
+               nextline = cp;
+       } else
+               nextline = NULL;
+
+       cp = strpbrk(p, " \t");
+       if (cp == NULL) {
+               if (canonname == NULL)
+                       return (NULL);
+               else
+                       goto done;
+       }
+       *cp++ = '\0';
+
+       addr = p;
+
+       while (cp && *cp) {
+               if (*cp == ' ' || *cp == '\t') {
+                       cp++;
+                       continue;
+               }
+               if (!canonname)
+                       canonname = cp;
+               if ((cp = strpbrk(cp, " \t")) != NULL)
+                       *cp++ = '\0';
+       }
+
+       hints = *pai;
+       hints.ai_flags = AI_NUMERICHOST;
+       error = getaddrinfo(addr, NULL, &hints, &res0);
+       if (error == 0) {
+               for (res = res0; res; res = res->ai_next) {
+                       /* cover it up */
+                       res->ai_flags = pai->ai_flags;
+
+                       if (pai->ai_flags & AI_CANONNAME)
+                               (void)get_canonname(pai, res, canonname);
+               }
+       } else
+               res0 = NULL;
+       if (res0) {
+               cur->ai_next = res0;
+               while (cur->ai_next)
+                       cur = cur->ai_next;
+       }
+
+       if (nextline) {
+               p = nextline;
+               goto nextline;
+       }
+
+done:
+       return sentinel.ai_next;
+}
+
+/*ARGSUSED*/
+static int
+_yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
+{
+       struct addrinfo sentinel, *cur;
+       struct addrinfo *ai = NULL;
+       char *ypbuf;
+       int ypbuflen, r;
+       const char *name;
+       const struct addrinfo *pai;
+       char *ypdomain;
+
+       if (_yp_check(&ypdomain) == 0)
+               return NS_UNAVAIL;
+
+       name = va_arg(ap, char *);
+       pai = va_arg(ap, const struct addrinfo *);
+
+       memset(&sentinel, 0, sizeof(sentinel));
+       cur = &sentinel;
+
+       /* hosts.byname is only for IPv4 (Solaris8) */
+       if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
+               r = yp_match(ypdomain, "hosts.byname", name,
+                       (int)strlen(name), &ypbuf, &ypbuflen);
+               if (r == 0) {
+                       struct addrinfo ai4;
+
+                       ai4 = *pai;
+                       ai4.ai_family = AF_INET;
+                       ai = _yphostent(ypbuf, &ai4);
+                       if (ai) {
+                               cur->ai_next = ai;
+                               while (cur && cur->ai_next)
+                                       cur = cur->ai_next;
+                       }
+               }
+               free(ypbuf);
+       }
+
+       /* ipnodes.byname can hold both IPv4/v6 */
+       r = yp_match(ypdomain, "ipnodes.byname", name,
+               (int)strlen(name), &ypbuf, &ypbuflen);
+       if (r == 0) {
+               ai = _yphostent(ypbuf, pai);
+               if (ai)
+                       cur->ai_next = ai;
+               free(ypbuf);
+       }
+
+       if (sentinel.ai_next == NULL) {
+               h_errno = HOST_NOT_FOUND;
+               return NS_NOTFOUND;
+       }
+       *((struct addrinfo **)rv) = sentinel.ai_next;
+       return NS_SUCCESS;
+}
+#endif
+
+/* resolver logic */
+
+/*
+ * Formulate a normal query, send, and await answer.
+ * Returned answer is placed in supplied buffer "answer".
+ * Perform preliminary check of answer, returning success only
+ * if no error is indicated and the answer count is nonzero.
+ * Return the size of the response on success, -1 on error.
+ * Error number is left in h_errno.
+ *
+ * Caller must parse answer and determine whether it answers the question.
+ */
+static int
+res_queryN(const char *name, /* domain name */ struct res_target *target,
+    res_state res)
+{
+       u_char buf[MAXPACKET];
+       HEADER *hp;
+       int n;
+       struct res_target *t;
+       int rcode;
+       int ancount;
+
+       _DIAGASSERT(name != NULL);
+       /* XXX: target may be NULL??? */
+
+       rcode = NOERROR;
+       ancount = 0;
+
+       for (t = target; t; t = t->next) {
+               int class, type;
+               u_char *answer;
+               int anslen;
+
+               hp = (HEADER *)(void *)t->answer;
+               hp->rcode = NOERROR;    /* default */
+
+               /* make it easier... */
+               class = t->qclass;
+               type = t->qtype;
+               answer = t->answer;
+               anslen = t->anslen;
+#ifdef DEBUG
+               if (res->options & RES_DEBUG)
+                       printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
+#endif
+
+               n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
+                   buf, sizeof(buf));
+#ifdef RES_USE_EDNS0
+               if (n > 0 && (res->options & RES_USE_EDNS0) != 0)
+                       n = res_nopt(res, n, buf, sizeof(buf), anslen);
+#endif
+               if (n <= 0) {
+#ifdef DEBUG
+                       if (res->options & RES_DEBUG)
+                               printf(";; res_nquery: mkquery failed\n");
+#endif
+                       h_errno = NO_RECOVERY;
+                       return n;
+               }
+               n = res_nsend(res, buf, n, answer, anslen);
+#if 0
+               if (n < 0) {
+#ifdef DEBUG
+                       if (res->options & RES_DEBUG)
+                               printf(";; res_query: send error\n");
+#endif
+                       h_errno = TRY_AGAIN;
+                       return n;
+               }
+#endif
+
+               if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
+                       rcode = hp->rcode;      /* record most recent error */
+#ifdef DEBUG
+                       if (res->options & RES_DEBUG)
+                               printf(";; rcode = %u, ancount=%u\n", hp->rcode,
+                                   ntohs(hp->ancount));
+#endif
+                       continue;
+               }
+
+               ancount += ntohs(hp->ancount);
+
+               t->n = n;
+       }
+
+       if (ancount == 0) {
+               switch (rcode) {
+               case NXDOMAIN:
+                       h_errno = HOST_NOT_FOUND;
+                       break;
+               case SERVFAIL:
+                       h_errno = TRY_AGAIN;
+                       break;
+               case NOERROR:
+                       h_errno = NO_DATA;
+                       break;
+               case FORMERR:
+               case NOTIMP:
+               case REFUSED:
+               default:
+                       h_errno = NO_RECOVERY;
+                       break;
+               }
+               return -1;
+       }
+       return ancount;
+}
+
+/*
+ * Formulate a normal query, send, and retrieve answer in supplied buffer.
+ * Return the size of the response on success, -1 on error.
+ * If enabled, implement search rules until answer or unrecoverable failure
+ * is detected.  Error code, if any, is left in h_errno.
+ */
+static int
+res_searchN(const char *name, struct res_target *target, res_state res)
+{
+       const char *cp, * const *domain;
+       HEADER *hp;
+       u_int dots;
+       int trailing_dot, ret, saved_herrno;
+       int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(target != NULL);
+
+       hp = (HEADER *)(void *)target->answer;  /*XXX*/
+
+       errno = 0;
+       h_errno = HOST_NOT_FOUND;       /* default, if we never query */
+       dots = 0;
+       for (cp = name; *cp; cp++)
+               dots += (*cp == '.');
+       trailing_dot = 0;
+       if (cp > name && *--cp == '.')
+               trailing_dot++;
+
+       /*
+        * if there aren't any dots, it could be a user-level alias
+        */
+       if (!dots && (cp = __hostalias(name)) != NULL) {
+               ret = res_queryN(cp, target, res);
+               return ret;
+       }
+
+       /*
+        * If there are dots in the name already, let's just give it a try
+        * 'as is'.  The threshold can be set with the "ndots" option.
+        */
+       saved_herrno = -1;
+       if (dots >= res->ndots) {
+               ret = res_querydomainN(name, NULL, target, res);
+               if (ret > 0)
+                       return (ret);
+               saved_herrno = h_errno;
+               tried_as_is++;
+       }
+
+       /*
+        * We do at least one level of search if
+        *      - there is no dot and RES_DEFNAME is set, or
+        *      - there is at least one dot, there is no trailing dot,
+        *        and RES_DNSRCH is set.
+        */
+       if ((!dots && (res->options & RES_DEFNAMES)) ||
+           (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
+               int done = 0;
+
+               for (domain = (const char * const *)res->dnsrch;
+                  *domain && !done;
+                  domain++) {
+
+                       ret = res_querydomainN(name, *domain, target, res);
+                       if (ret > 0)
+                               return ret;
+
+                       /*
+                        * If no server present, give up.
+                        * If name isn't found in this domain,
+                        * keep trying higher domains in the search list
+                        * (if that's enabled).
+                        * On a NO_DATA error, keep trying, otherwise
+                        * a wildcard entry of another type could keep us
+                        * from finding this entry higher in the domain.
+                        * If we get some other error (negative answer or
+                        * server failure), then stop searching up,
+                        * but try the input name below in case it's
+                        * fully-qualified.
+                        */
+                       if (errno == ECONNREFUSED) {
+                               h_errno = TRY_AGAIN;
+                               return -1;
+                       }
+
+                       switch (h_errno) {
+                       case NO_DATA:
+                               got_nodata++;
+                               /* FALLTHROUGH */
+                       case HOST_NOT_FOUND:
+                               /* keep trying */
+                               break;
+                       case TRY_AGAIN:
+                               if (hp->rcode == SERVFAIL) {
+                                       /* try next search element, if any */
+                                       got_servfail++;
+                                       break;
+                               }
+                               /* FALLTHROUGH */
+                       default:
+                               /* anything else implies that we're done */
+                               done++;
+                       }
+                       /*
+                        * if we got here for some reason other than DNSRCH,
+                        * we only wanted one iteration of the loop, so stop.
+                        */
+                       if (!(res->options & RES_DNSRCH))
+                               done++;
+               }
+       }
+
+       /*
+        * if we have not already tried the name "as is", do that now.
+        * note that we do this regardless of how many dots were in the
+        * name or whether it ends with a dot.
+        */
+       if (!tried_as_is) {
+               ret = res_querydomainN(name, NULL, target, res);
+               if (ret > 0)
+                       return ret;
+       }
+
+       /*
+        * if we got here, we didn't satisfy the search.
+        * if we did an initial full query, return that query's h_errno
+        * (note that we wouldn't be here if that query had succeeded).
+        * else if we ever got a nodata, send that back as the reason.
+        * else send back meaningless h_errno, that being the one from
+        * the last DNSRCH we did.
+        */
+       if (saved_herrno != -1)
+               h_errno = saved_herrno;
+       else if (got_nodata)
+               h_errno = NO_DATA;
+       else if (got_servfail)
+               h_errno = TRY_AGAIN;
+       return -1;
+}
+
+/*
+ * Perform a call on res_query on the concatenation of name and domain,
+ * removing a trailing dot from name if domain is NULL.
+ */
+static int
+res_querydomainN(const char *name, const char *domain,
+    struct res_target *target, res_state res)
+{
+       char nbuf[MAXDNAME];
+       const char *longname = nbuf;
+       size_t n, d;
+
+       _DIAGASSERT(name != NULL);
+       /* XXX: target may be NULL??? */
+
+#ifdef DEBUG
+       if (res->options & RES_DEBUG)
+               printf(";; res_querydomain(%s, %s)\n",
+                       name, domain?domain:"<Nil>");
+#endif
+       if (domain == NULL) {
+               /*
+                * Check for trailing '.';
+                * copy without '.' if present.
+                */
+               n = strlen(name);
+               if (n + 1 > sizeof(nbuf)) {
+                       h_errno = NO_RECOVERY;
+                       return -1;
+               }
+               if (n > 0 && name[--n] == '.') {
+                       strncpy(nbuf, name, n);
+                       nbuf[n] = '\0';
+               } else
+                       longname = name;
+       } else {
+               n = strlen(name);
+               d = strlen(domain);
+               if (n + 1 + d + 1 > sizeof(nbuf)) {
+                       h_errno = NO_RECOVERY;
+                       return -1;
+               }
+               snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
+       }
+       return res_queryN(longname, target, res);
+}
diff --git a/lib/nbsd_libc/net/gethnamaddr.c b/lib/nbsd_libc/net/gethnamaddr.c
new file mode 100644 (file)
index 0000000..1c3a68d
--- /dev/null
@@ -0,0 +1,1441 @@
+/*     $NetBSD: gethnamaddr.c,v 1.76 2010/08/29 15:40:35 christos Exp $        */
+
+/*
+ * ++Copyright++ 1985, 1988, 1993
+ * -
+ * Copyright (c) 1985, 1988, 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.
+ * 3. 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.
+ * -
+ * Portions Copyright (c) 1993 by Digital Equipment Corporation.
+ * 
+ * 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, and that
+ * the name of Digital Equipment Corporation not be used in advertising or
+ * publicity pertaining to distribution of the document or software without
+ * specific, written prior permission.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
+ * CORPORATION 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.
+ * -
+ * --Copyright--
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)gethostnamadr.c    8.1 (Berkeley) 6/4/93";
+static char rcsid[] = "Id: gethnamaddr.c,v 8.21 1997/06/01 20:34:37 vixie Exp ";
+#else
+__RCSID("$NetBSD: gethnamaddr.c,v 1.76 2010/08/29 15:40:35 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(_LIBC)
+#include "namespace.h"
+#endif
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <netdb.h>
+#include <resolv.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <syslog.h>
+
+#ifndef LOG_AUTH
+# define LOG_AUTH 0
+#endif
+
+#define MULTI_PTRS_ARE_ALIASES 1       /* XXX - experimental */
+
+#include <nsswitch.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef YP
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+#endif
+
+#if defined(_LIBC) && defined(__weak_alias)
+__weak_alias(gethostbyaddr,_gethostbyaddr)
+__weak_alias(gethostbyname,_gethostbyname)
+__weak_alias(gethostent,_gethostent)
+#endif
+
+#define        MAXALIASES      35
+#define        MAXADDRS        35
+
+static const char AskedForGot[] =
+                         "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
+
+static char *h_addr_ptrs[MAXADDRS + 1];
+
+#ifdef YP
+static char *__ypdomain;
+#endif
+
+static struct hostent host;
+static char *host_aliases[MAXALIASES];
+static char hostbuf[8*1024];
+static u_int32_t host_addr[16 / sizeof(u_int32_t)];    /* IPv4 or IPv6 */
+static FILE *hostf = NULL;
+static int stayopen = 0;
+
+#define        MAXPACKET       (64*1024)
+
+typedef union {
+    HEADER hdr;
+    u_char buf[MAXPACKET];
+} querybuf;
+
+typedef union {
+    int32_t al;
+    char ac;
+} align;
+
+#ifdef DEBUG
+static void debugprintf(const char *, res_state, ...)
+       __attribute__((__format__(__printf__, 1, 3)));
+#endif
+static struct hostent *getanswer(const querybuf *, int, const char *, int,
+    res_state);
+static void map_v4v6_address(const char *, char *);
+static void map_v4v6_hostent(struct hostent *, char **, char *);
+static void addrsort(char **, int, res_state);
+
+void _sethtent(int);
+void _endhtent(void);
+struct hostent *_gethtent(void);
+void ht_sethostent(int);
+void ht_endhostent(void);
+struct hostent *ht_gethostbyname(char *);
+struct hostent *ht_gethostbyaddr(const char *, int, int);
+void dns_service(void);
+#undef dn_skipname
+int dn_skipname(const u_char *, const u_char *);
+int _gethtbyaddr(void *, void *, va_list);
+int _gethtbyname(void *, void *, va_list);
+struct hostent *_gethtbyname2(const char *, int);
+int _dns_gethtbyaddr(void *, void *, va_list);
+int _dns_gethtbyname(void *, void *, va_list);
+#ifdef YP
+struct hostent *_yphostent(char *, int);
+int _yp_gethtbyaddr(void *, void *, va_list);
+int _yp_gethtbyname(void *, void *, va_list);
+#endif
+
+static struct hostent *gethostbyname_internal(const char *, int, res_state);
+
+static const ns_src default_dns_files[] = {
+       { NSSRC_FILES,  NS_SUCCESS },
+       { NSSRC_DNS,    NS_SUCCESS },
+       { 0, 0 }
+};
+
+
+#ifdef DEBUG
+static void
+debugprintf(const char *msg, res_state res, ...)
+{
+       _DIAGASSERT(msg != NULL);
+
+       if (res->options & RES_DEBUG) {
+               int save = errno;
+               va_list ap;
+
+               va_start (ap, res);
+               vprintf(msg, ap);
+               va_end (ap);
+               
+               errno = save;
+       }
+}
+#else
+# define debugprintf(msg, res, num) /*nada*/
+#endif
+
+#define BOUNDED_INCR(x) \
+       do { \
+               cp += (x); \
+               if (cp > eom) { \
+                       h_errno = NO_RECOVERY; \
+                       return NULL; \
+               } \
+       } while (/*CONSTCOND*/0)
+
+#define BOUNDS_CHECK(ptr, count) \
+       do { \
+               if ((ptr) + (count) > eom) { \
+                       h_errno = NO_RECOVERY; \
+                       return NULL; \
+               } \
+       } while (/*CONSTCOND*/0)
+
+static struct hostent *
+getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
+    res_state res)
+{
+       const HEADER *hp;
+       const u_char *cp;
+       int n;
+       const u_char *eom, *erdata;
+       char *bp, **ap, **hap, *ep;
+       int type, class, ancount, qdcount;
+       int haveanswer, had_error;
+       int toobig = 0;
+       char tbuf[MAXDNAME];
+       const char *tname;
+       int (*name_ok)(const char *);
+
+       _DIAGASSERT(answer != NULL);
+       _DIAGASSERT(qname != NULL);
+
+       tname = qname;
+       host.h_name = NULL;
+       eom = answer->buf + anslen;
+       switch (qtype) {
+       case T_A:
+       case T_AAAA:
+               name_ok = res_hnok;
+               break;
+       case T_PTR:
+               name_ok = res_dnok;
+               break;
+       default:
+               return NULL;    /* XXX should be abort(); */
+       }
+       /*
+        * find first satisfactory answer
+        */
+       hp = &answer->hdr;
+       ancount = ntohs(hp->ancount);
+       qdcount = ntohs(hp->qdcount);
+       bp = hostbuf;
+       ep = hostbuf + sizeof hostbuf;
+       cp = answer->buf;
+       BOUNDED_INCR(HFIXEDSZ);
+       if (qdcount != 1) {
+               h_errno = NO_RECOVERY;
+               return NULL;
+       }
+       n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
+       if ((n < 0) || !(*name_ok)(bp)) {
+               h_errno = NO_RECOVERY;
+               return NULL;
+       }
+       BOUNDED_INCR(n + QFIXEDSZ);
+       if (qtype == T_A || qtype == T_AAAA) {
+               /* res_send() has already verified that the query name is the
+                * same as the one we sent; this just gets the expanded name
+                * (i.e., with the succeeding search-domain tacked on).
+                */
+               n = strlen(bp) + 1;             /* for the \0 */
+               if (n >= MAXHOSTNAMELEN) {
+                       h_errno = NO_RECOVERY;
+                       return NULL;
+               }
+               host.h_name = bp;
+               bp += n;
+               /* The qname can be abbreviated, but h_name is now absolute. */
+               qname = host.h_name;
+       }
+       ap = host_aliases;
+       *ap = NULL;
+       host.h_aliases = host_aliases;
+       hap = h_addr_ptrs;
+       *hap = NULL;
+       host.h_addr_list = h_addr_ptrs;
+       haveanswer = 0;
+       had_error = 0;
+       while (ancount-- > 0 && cp < eom && !had_error) {
+               n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
+               if ((n < 0) || !(*name_ok)(bp)) {
+                       had_error++;
+                       continue;
+               }
+               cp += n;                        /* name */
+               BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
+               type = _getshort(cp);
+               cp += INT16SZ;                  /* type */
+               class = _getshort(cp);
+               cp += INT16SZ + INT32SZ;        /* class, TTL */
+               n = _getshort(cp);
+               cp += INT16SZ;                  /* len */
+               BOUNDS_CHECK(cp, n);
+               erdata = cp + n;
+               if (class != C_IN) {
+                       /* XXX - debug? syslog? */
+                       cp += n;
+                       continue;               /* XXX - had_error++ ? */
+               }
+               if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) {
+                       if (ap >= &host_aliases[MAXALIASES-1])
+                               continue;
+                       n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
+                       if ((n < 0) || !(*name_ok)(tbuf)) {
+                               had_error++;
+                               continue;
+                       }
+                       cp += n;
+                       if (cp != erdata) {
+                               h_errno = NO_RECOVERY;
+                               return NULL;
+                       }
+                       /* Store alias. */
+                       *ap++ = bp;
+                       n = strlen(bp) + 1;     /* for the \0 */
+                       if (n >= MAXHOSTNAMELEN) {
+                               had_error++;
+                               continue;
+                       }
+                       bp += n;
+                       /* Get canonical name. */
+                       n = strlen(tbuf) + 1;   /* for the \0 */
+                       if (n > ep - bp || n >= MAXHOSTNAMELEN) {
+                               had_error++;
+                               continue;
+                       }
+                       strlcpy(bp, tbuf, (size_t)(ep - bp));
+                       host.h_name = bp;
+                       bp += n;
+                       continue;
+               }
+               if (qtype == T_PTR && type == T_CNAME) {
+                       n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
+                       if (n < 0 || !res_dnok(tbuf)) {
+                               had_error++;
+                               continue;
+                       }
+                       cp += n;
+                       if (cp != erdata) {
+                               h_errno = NO_RECOVERY;
+                               return NULL;
+                       }
+                       /* Get canonical name. */
+                       n = strlen(tbuf) + 1;   /* for the \0 */
+                       if (n > ep - bp || n >= MAXHOSTNAMELEN) {
+                               had_error++;
+                               continue;
+                       }
+                       strlcpy(bp, tbuf, (size_t)(ep - bp));
+                       tname = bp;
+                       bp += n;
+                       continue;
+               }
+               if (type != qtype) {
+                       if (type != T_KEY && type != T_SIG)
+                               syslog(LOG_NOTICE|LOG_AUTH,
+              "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
+                                      qname, p_class(C_IN), p_type(qtype),
+                                      p_type(type));
+                       cp += n;
+                       continue;               /* XXX - had_error++ ? */
+               }
+               switch (type) {
+               case T_PTR:
+                       if (strcasecmp(tname, bp) != 0) {
+                               syslog(LOG_NOTICE|LOG_AUTH,
+                                      AskedForGot, qname, bp);
+                               cp += n;
+                               continue;       /* XXX - had_error++ ? */
+                       }
+                       n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
+                       if ((n < 0) || !res_hnok(bp)) {
+                               had_error++;
+                               break;
+                       }
+#if MULTI_PTRS_ARE_ALIASES
+                       cp += n;
+                       if (cp != erdata) {
+                               h_errno = NO_RECOVERY;
+                               return NULL;
+                       }
+                       if (!haveanswer)
+                               host.h_name = bp;
+                       else if (ap < &host_aliases[MAXALIASES-1])
+                               *ap++ = bp;
+                       else
+                               n = -1;
+                       if (n != -1) {
+                               n = strlen(bp) + 1;     /* for the \0 */
+                               if (n >= MAXHOSTNAMELEN) {
+                                       had_error++;
+                                       break;
+                               }
+                               bp += n;
+                       }
+                       break;
+#else
+                       host.h_name = bp;
+                       if (res->options & RES_USE_INET6) {
+                               n = strlen(bp) + 1;     /* for the \0 */
+                               if (n >= MAXHOSTNAMELEN) {
+                                       had_error++;
+                                       break;
+                               }
+                               bp += n;
+                               map_v4v6_hostent(&host, &bp, ep);
+                       }
+                       h_errno = NETDB_SUCCESS;
+                       return &host;
+#endif
+               case T_A:
+               case T_AAAA:
+                       if (strcasecmp(host.h_name, bp) != 0) {
+                               syslog(LOG_NOTICE|LOG_AUTH,
+                                      AskedForGot, host.h_name, bp);
+                               cp += n;
+                               continue;       /* XXX - had_error++ ? */
+                       }
+                       if (n != host.h_length) {
+                               cp += n;
+                               continue;
+                       }
+                       if (type == T_AAAA) {
+                               struct in6_addr in6;
+                               memcpy(&in6, cp, IN6ADDRSZ);
+                               if (IN6_IS_ADDR_V4MAPPED(&in6)) {
+                                       cp += n;
+                                       continue;
+                               }
+                       }
+                       if (!haveanswer) {
+                               int nn;
+
+                               host.h_name = bp;
+                               nn = strlen(bp) + 1;    /* for the \0 */
+                               bp += nn;
+                       }
+
+                       bp += sizeof(align) -
+                           (size_t)((u_long)bp % sizeof(align));
+
+                       if (bp + n >= &hostbuf[sizeof hostbuf]) {
+                               debugprintf("size (%d) too big\n", res, n);
+                               had_error++;
+                               continue;
+                       }
+                       if (hap >= &h_addr_ptrs[MAXADDRS-1]) {
+                               if (!toobig++) {
+                                       debugprintf("Too many addresses (%d)\n",
+                                               res, MAXADDRS);
+                               }
+                               cp += n;
+                               continue;
+                       }
+                       (void)memcpy(*hap++ = bp, cp, (size_t)n);
+                       bp += n;
+                       cp += n;
+                       if (cp != erdata) {
+                               h_errno = NO_RECOVERY;
+                               return NULL;
+                       }
+                       break;
+               default:
+                       abort();
+               }
+               if (!had_error)
+                       haveanswer++;
+       }
+       if (haveanswer) {
+               *ap = NULL;
+               *hap = NULL;
+               /*
+                * Note: we sort even if host can take only one address
+                * in its return structures - should give it the "best"
+                * address in that case, not some random one
+                */
+               if (res->nsort && haveanswer > 1 && qtype == T_A)
+                       addrsort(h_addr_ptrs, haveanswer, res);
+               if (!host.h_name) {
+                       n = strlen(qname) + 1;  /* for the \0 */
+                       if (n > ep - bp || n >= MAXHOSTNAMELEN)
+                               goto no_recovery;
+                       strlcpy(bp, qname, (size_t)(ep - bp));
+                       host.h_name = bp;
+                       bp += n;
+               }
+               if (res->options & RES_USE_INET6)
+                       map_v4v6_hostent(&host, &bp, ep);
+               h_errno = NETDB_SUCCESS;
+               return &host;
+       }
+ no_recovery:
+       h_errno = NO_RECOVERY;
+       return NULL;
+}
+
+struct hostent *
+gethostbyname(const char *name)
+{
+       struct hostent *hp;
+       res_state res = __res_get_state();
+
+       if (res == NULL)
+               return NULL;
+
+       _DIAGASSERT(name != NULL);
+
+       if (res->options & RES_USE_INET6) {
+               hp = gethostbyname_internal(name, AF_INET6, res);
+               if (hp) {
+                       __res_put_state(res);
+                       return hp;
+               }
+       }
+       hp = gethostbyname_internal(name, AF_INET, res);
+       __res_put_state(res);
+       return hp;
+}
+
+struct hostent *
+gethostbyname2(const char *name, int af)
+{
+       struct hostent *hp;
+       res_state res = __res_get_state();
+
+       if (res == NULL)
+               return NULL;
+       hp = gethostbyname_internal(name, af, res);
+       __res_put_state(res);
+       return hp;
+}
+
+static struct hostent *
+gethostbyname_internal(const char *name, int af, res_state res)
+{
+       const char *cp;
+       char *bp, *ep;
+       int size;
+       struct hostent *hp;
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_gethtbyname, NULL)
+               { NSSRC_DNS, _dns_gethtbyname, NULL },  /* force -DHESIOD */
+               NS_NIS_CB(_yp_gethtbyname, NULL)
+               NS_NULL_CB
+       };
+
+       _DIAGASSERT(name != NULL);
+
+       switch (af) {
+       case AF_INET:
+               size = INADDRSZ;
+               break;
+       case AF_INET6:
+               size = IN6ADDRSZ;
+               break;
+       default:
+               h_errno = NETDB_INTERNAL;
+               errno = EAFNOSUPPORT;
+               return NULL;
+       }
+
+       host.h_addrtype = af;
+       host.h_length = size;
+
+       /*
+        * if there aren't any dots, it could be a user-level alias.
+        * this is also done in res_nquery() since we are not the only
+        * function that looks up host names.
+        */
+       if (!strchr(name, '.') && (cp = __hostalias(name)))
+               name = cp;
+
+       /*
+        * disallow names consisting only of digits/dots, unless
+        * they end in a dot.
+        */
+       if (isdigit((u_char) name[0]))
+               for (cp = name;; ++cp) {
+                       if (!*cp) {
+                               if (*--cp == '.')
+                                       break;
+                               /*
+                                * All-numeric, no dot at the end.
+                                * Fake up a hostent as if we'd actually
+                                * done a lookup.
+                                */
+                               if (inet_pton(af, name,
+                                   (char *)(void *)host_addr) <= 0) {
+                                       h_errno = HOST_NOT_FOUND;
+                                       return NULL;
+                               }
+                               strncpy(hostbuf, name, MAXDNAME);
+                               hostbuf[MAXDNAME] = '\0';
+                               bp = hostbuf + MAXDNAME;
+                               ep = hostbuf + sizeof hostbuf;
+                               host.h_name = hostbuf;
+                               host.h_aliases = host_aliases;
+                               host_aliases[0] = NULL;
+                               h_addr_ptrs[0] = (char *)(void *)host_addr;
+                               h_addr_ptrs[1] = NULL;
+                               host.h_addr_list = h_addr_ptrs;
+                               if (res->options & RES_USE_INET6)
+                                       map_v4v6_hostent(&host, &bp, ep);
+                               h_errno = NETDB_SUCCESS;
+                               return &host;
+                       }
+                       if (!isdigit((u_char) *cp) && *cp != '.') 
+                               break;
+               }
+       if ((isxdigit((u_char) name[0]) && strchr(name, ':') != NULL) ||
+           name[0] == ':')
+               for (cp = name;; ++cp) {
+                       if (!*cp) {
+                               if (*--cp == '.')
+                                       break;
+                               /*
+                                * All-IPv6-legal, no dot at the end.
+                                * Fake up a hostent as if we'd actually
+                                * done a lookup.
+                                */
+                               if (inet_pton(af, name,
+                                   (char *)(void *)host_addr) <= 0) {
+                                       h_errno = HOST_NOT_FOUND;
+                                       return NULL;
+                               }
+                               strncpy(hostbuf, name, MAXDNAME);
+                               hostbuf[MAXDNAME] = '\0';
+                               bp = hostbuf + MAXDNAME;
+                               ep = hostbuf + sizeof hostbuf;
+                               host.h_name = hostbuf;
+                               host.h_aliases = host_aliases;
+                               host_aliases[0] = NULL;
+                               h_addr_ptrs[0] = (char *)(void *)host_addr;
+                               h_addr_ptrs[1] = NULL;
+                               host.h_addr_list = h_addr_ptrs;
+                               h_errno = NETDB_SUCCESS;
+                               return &host;
+                       }
+                       if (!isxdigit((u_char) *cp) && *cp != ':' && *cp != '.')
+                               break;
+               }
+
+       hp = NULL;
+       h_errno = NETDB_INTERNAL;
+       if (nsdispatch(&hp, dtab, NSDB_HOSTS, "gethostbyname",
+           default_dns_files, name, strlen(name), af) != NS_SUCCESS)
+               return NULL;
+       h_errno = NETDB_SUCCESS;
+       return hp;
+}
+
+struct hostent *
+gethostbyaddr(const char *addr,        /* XXX should have been def'd as u_char! */
+    socklen_t len, int af)
+{
+       const u_char *uaddr = (const u_char *)addr;
+       socklen_t size;
+       struct hostent *hp;
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_gethtbyaddr, NULL)
+               { NSSRC_DNS, _dns_gethtbyaddr, NULL },  /* force -DHESIOD */
+               NS_NIS_CB(_yp_gethtbyaddr, NULL)
+               NS_NULL_CB
+       };
+       
+       _DIAGASSERT(addr != NULL);
+
+       if (af == AF_INET6 && len == IN6ADDRSZ &&
+           (IN6_IS_ADDR_LINKLOCAL((const struct in6_addr *)(const void *)uaddr) ||
+            IN6_IS_ADDR_SITELOCAL((const struct in6_addr *)(const void *)uaddr))) {
+               h_errno = HOST_NOT_FOUND;
+               return NULL;
+       }
+       if (af == AF_INET6 && len == IN6ADDRSZ &&
+           (IN6_IS_ADDR_V4MAPPED((const struct in6_addr *)(const void *)uaddr) ||
+            IN6_IS_ADDR_V4COMPAT((const struct in6_addr *)(const void *)uaddr))) {
+               /* Unmap. */
+               addr += IN6ADDRSZ - INADDRSZ;
+               uaddr += IN6ADDRSZ - INADDRSZ;
+               af = AF_INET;
+               len = INADDRSZ;
+       }
+       switch (af) {
+       case AF_INET:
+               size = INADDRSZ;
+               break;
+       case AF_INET6:
+               size = IN6ADDRSZ;
+               break;
+       default:
+               errno = EAFNOSUPPORT;
+               h_errno = NETDB_INTERNAL;
+               return NULL;
+       }
+       if (size != len) {
+               errno = EINVAL;
+               h_errno = NETDB_INTERNAL;
+               return NULL;
+       }
+       hp = NULL;
+       h_errno = NETDB_INTERNAL;
+       if (nsdispatch(&hp, dtab, NSDB_HOSTS, "gethostbyaddr",
+           default_dns_files, uaddr, len, af) != NS_SUCCESS)
+               return NULL;
+       h_errno = NETDB_SUCCESS;
+       return hp;
+}
+
+void
+_sethtent(int f)
+{
+       if (!hostf)
+               hostf = fopen(_PATH_HOSTS, "r" );
+       else
+               rewind(hostf);
+       stayopen = f;
+}
+
+void
+_endhtent(void)
+{
+       if (hostf && !stayopen) {
+               (void) fclose(hostf);
+               hostf = NULL;
+       }
+}
+
+struct hostent *
+_gethtent(void)
+{
+       char *p;
+       char *cp, **q;
+       int af, len;
+
+       if (!hostf && !(hostf = fopen(_PATH_HOSTS, "r" ))) {
+               h_errno = NETDB_INTERNAL;
+               return NULL;
+       }
+ again:
+       if (!(p = fgets(hostbuf, sizeof hostbuf, hostf))) {
+               h_errno = HOST_NOT_FOUND;
+               return NULL;
+       }
+       if (*p == '#')
+               goto again;
+       if (!(cp = strpbrk(p, "#\n")))
+               goto again;
+       *cp = '\0';
+       if (!(cp = strpbrk(p, " \t")))
+               goto again;
+       *cp++ = '\0';
+       if (inet_pton(AF_INET6, p, (char *)(void *)host_addr) > 0) {
+               af = AF_INET6;
+               len = IN6ADDRSZ;
+       } else if (inet_pton(AF_INET, p, (char *)(void *)host_addr) > 0) {
+               res_state res = __res_get_state();
+               if (res == NULL)
+                       return NULL;
+               if (res->options & RES_USE_INET6) {
+                       map_v4v6_address((char *)(void *)host_addr,
+                           (char *)(void *)host_addr);
+                       af = AF_INET6;
+                       len = IN6ADDRSZ;
+               } else {
+                       af = AF_INET;
+                       len = INADDRSZ;
+               }
+               __res_put_state(res);
+       } else {
+               goto again;
+       }
+       /* if this is not something we're looking for, skip it. */
+       if (host.h_addrtype != 0 && host.h_addrtype != af)
+               goto again;
+       if (host.h_length != 0 && host.h_length != len)
+               goto again;
+       h_addr_ptrs[0] = (char *)(void *)host_addr;
+       h_addr_ptrs[1] = NULL;
+       host.h_addr_list = h_addr_ptrs;
+       host.h_length = len;
+       host.h_addrtype = af;
+       while (*cp == ' ' || *cp == '\t')
+               cp++;
+       host.h_name = cp;
+       q = host.h_aliases = host_aliases;
+       if ((cp = strpbrk(cp, " \t")) != NULL)
+               *cp++ = '\0';
+       while (cp && *cp) {
+               if (*cp == ' ' || *cp == '\t') {
+                       cp++;
+                       continue;
+               }
+               if (q < &host_aliases[MAXALIASES - 1])
+                       *q++ = cp;
+               if ((cp = strpbrk(cp, " \t")) != NULL)
+                       *cp++ = '\0';
+       }
+       *q = NULL;
+       h_errno = NETDB_SUCCESS;
+       return &host;
+}
+
+/*ARGSUSED*/
+int
+_gethtbyname(void *rv, void *cb_data, va_list ap)
+{
+       struct hostent *hp;
+       const char *name;
+       int af;
+
+       _DIAGASSERT(rv != NULL);
+
+       name = va_arg(ap, char *);
+       /* NOSTRICT skip len */(void)va_arg(ap, int);
+       af = va_arg(ap, int);
+
+       hp = NULL;
+#if 0
+       {
+               res_state res = __res_get_state();
+               if (res == NULL)
+                       return NS_NOTFOUND;
+               if (res->options & RES_USE_INET6)
+                       hp = _gethtbyname2(name, AF_INET6);
+               if (hp==NULL)
+                       hp = _gethtbyname2(name, AF_INET);
+               __res_put_state(res);
+       }
+#else
+       hp = _gethtbyname2(name, af);
+#endif
+       *((struct hostent **)rv) = hp;
+       if (hp == NULL) {
+               h_errno = HOST_NOT_FOUND;
+               return NS_NOTFOUND;
+       }
+       return NS_SUCCESS;
+}
+
+struct hostent *
+_gethtbyname2(const char *name, int af)
+{
+       struct hostent *p;
+       char *tmpbuf, *ptr, **cp;
+       int num;
+       size_t len;
+
+       _DIAGASSERT(name != NULL);
+
+       _sethtent(stayopen);
+       ptr = tmpbuf = NULL;
+       num = 0;
+       while ((p = _gethtent()) != NULL && num < MAXADDRS) {
+               if (p->h_addrtype != af)
+                       continue;
+               if (strcasecmp(p->h_name, name) != 0) {
+                       for (cp = p->h_aliases; *cp != NULL; cp++)
+                               if (strcasecmp(*cp, name) == 0)
+                                       break;
+                       if (*cp == NULL) continue;
+               }
+
+               if (num == 0) {
+                       size_t bufsize;
+                       char *src;
+
+                       bufsize = strlen(p->h_name) + 2 +
+                                 MAXADDRS * p->h_length +
+                                 ALIGNBYTES;
+                       for (cp = p->h_aliases; *cp != NULL; cp++)
+                               bufsize += strlen(*cp) + 1;
+
+                       if ((tmpbuf = malloc(bufsize)) == NULL) {
+                               h_errno = NETDB_INTERNAL;
+                               return NULL;
+                       }
+
+                       ptr = tmpbuf;
+                       src = p->h_name;
+                       while ((*ptr++ = *src++) != '\0');
+                       for (cp = p->h_aliases; *cp != NULL; cp++) {
+                               src = *cp;
+                               while ((*ptr++ = *src++) != '\0');
+                       }
+                       *ptr++ = '\0';
+
+                       ptr = (char *)(void *)ALIGN(ptr);
+               }
+
+               (void)memcpy(ptr, p->h_addr_list[0], (size_t)p->h_length);
+               ptr += p->h_length;
+               num++;
+       }
+       _endhtent();
+       if (num == 0) return NULL;
+
+       len = ptr - tmpbuf;
+       if (len > (sizeof(hostbuf) - ALIGNBYTES)) {
+               free(tmpbuf);
+               errno = ENOSPC;
+               h_errno = NETDB_INTERNAL;
+               return NULL;
+       }
+       ptr = memcpy((void *)ALIGN(hostbuf), tmpbuf, len);
+       free(tmpbuf);
+
+       host.h_name = ptr;
+       while (*ptr++);
+
+       cp = host_aliases;
+       while (*ptr) {
+               *cp++ = ptr;
+               while (*ptr++);
+       }
+       ptr++;
+       *cp = NULL;
+
+       ptr = (char *)(void *)ALIGN(ptr);
+       cp = h_addr_ptrs;
+       while (num--) {
+               *cp++ = ptr;
+               ptr += host.h_length;
+       }
+       *cp = NULL;
+
+       return &host;
+}
+
+/*ARGSUSED*/
+int
+_gethtbyaddr(void *rv, void *cb_data, va_list ap)
+{
+       struct hostent *p;
+       const unsigned char *addr;
+       int len, af;
+
+       _DIAGASSERT(rv != NULL);
+
+       addr = va_arg(ap, unsigned char *);
+       len = va_arg(ap, int);
+       af = va_arg(ap, int);
+       
+       host.h_length = len;
+       host.h_addrtype = af;
+
+       _sethtent(stayopen);
+       while ((p = _gethtent()) != NULL)
+               if (p->h_addrtype == af && !memcmp(p->h_addr, addr,
+                   (size_t)len))
+                       break;
+       _endhtent();
+       *((struct hostent **)rv) = p;
+       if (p==NULL) {
+               h_errno = HOST_NOT_FOUND;
+               return NS_NOTFOUND;
+       }
+       return NS_SUCCESS;
+}
+
+static void
+map_v4v6_address(const char *src, char *dst)
+{
+       u_char *p = (u_char *)dst;
+       char tmp[INADDRSZ];
+       int i;
+
+       _DIAGASSERT(src != NULL);
+       _DIAGASSERT(dst != NULL);
+
+       /* Stash a temporary copy so our caller can update in place. */
+       (void)memcpy(tmp, src, INADDRSZ);
+       /* Mark this ipv6 addr as a mapped ipv4. */
+       for (i = 0; i < 10; i++)
+               *p++ = 0x00;
+       *p++ = 0xff;
+       *p++ = 0xff;
+       /* Retrieve the saved copy and we're done. */
+       (void)memcpy((void *)p, tmp, INADDRSZ);
+}
+
+static void
+map_v4v6_hostent(struct hostent *hp, char **bpp, char *ep)
+{
+       char **ap;
+
+       _DIAGASSERT(hp != NULL);
+       _DIAGASSERT(bpp != NULL);
+       _DIAGASSERT(ep != NULL);
+
+       if (hp->h_addrtype != AF_INET || hp->h_length != INADDRSZ)
+               return;
+       hp->h_addrtype = AF_INET6;
+       hp->h_length = IN6ADDRSZ;
+       for (ap = hp->h_addr_list; *ap; ap++) {
+               int i = sizeof(align) - (size_t)((u_long)*bpp % sizeof(align));
+
+               if (ep - *bpp < (i + IN6ADDRSZ)) {
+                       /* Out of memory.  Truncate address list here.  XXX */
+                       *ap = NULL;
+                       return;
+               }
+               *bpp += i;
+               map_v4v6_address(*ap, *bpp);
+               *ap = *bpp;
+               *bpp += IN6ADDRSZ;
+       }
+}
+
+static void
+addrsort(char **ap, int num, res_state res)
+{
+       int i, j;
+       char **p;
+       short aval[MAXADDRS];
+       int needsort = 0;
+
+       _DIAGASSERT(ap != NULL);
+
+       p = ap;
+       for (i = 0; i < num; i++, p++) {
+           for (j = 0 ; (unsigned)j < res->nsort; j++)
+               if (res->sort_list[j].addr.s_addr == 
+                   (((struct in_addr *)(void *)(*p))->s_addr &
+                   res->sort_list[j].mask))
+                       break;
+           aval[i] = j;
+           if (needsort == 0 && i > 0 && j < aval[i-1])
+               needsort = i;
+       }
+       if (!needsort)
+           return;
+
+       while (needsort < num) {
+           for (j = needsort - 1; j >= 0; j--) {
+               if (aval[j] > aval[j+1]) {
+                   char *hp;
+
+                   i = aval[j];
+                   aval[j] = aval[j+1];
+                   aval[j+1] = i;
+
+                   hp = ap[j];
+                   ap[j] = ap[j+1];
+                   ap[j+1] = hp;
+               } else
+                   break;
+           }
+           needsort++;
+       }
+}
+
+struct hostent *
+gethostent(void)
+{
+       host.h_addrtype = 0;
+       host.h_length = 0;
+       return _gethtent();
+}
+
+/*ARGSUSED*/
+int
+_dns_gethtbyname(void *rv, void *cb_data, va_list ap)
+{
+       querybuf *buf;
+       int n, type;
+       struct hostent *hp;
+       const char *name;
+       int af;
+       res_state res;
+
+       _DIAGASSERT(rv != NULL);
+
+       name = va_arg(ap, char *);
+       /* NOSTRICT skip len */(void)va_arg(ap, int);
+       af = va_arg(ap, int);
+
+       switch (af) {
+       case AF_INET:
+               type = T_A;
+               break;
+       case AF_INET6:
+               type = T_AAAA;
+               break;
+       default:
+               return NS_UNAVAIL;
+       }
+       buf = malloc(sizeof(*buf));
+       if (buf == NULL) {
+               h_errno = NETDB_INTERNAL;
+               return NS_NOTFOUND;
+       }
+       res = __res_get_state();
+       if (res == NULL) {
+               free(buf);
+               return NS_NOTFOUND;
+       }
+       n = res_nsearch(res, name, C_IN, type, buf->buf, sizeof(buf->buf));
+       if (n < 0) {
+               free(buf);
+               debugprintf("res_nsearch failed (%d)\n", res, n);
+               __res_put_state(res);
+               return NS_NOTFOUND;
+       }
+       hp = getanswer(buf, n, name, type, res);
+       free(buf);
+       __res_put_state(res);
+       if (hp == NULL)
+               switch (h_errno) {
+               case HOST_NOT_FOUND:
+                       return NS_NOTFOUND;
+               case TRY_AGAIN:
+                       return NS_TRYAGAIN;
+               default:
+                       return NS_UNAVAIL;
+               }
+       *((struct hostent **)rv) = hp;
+       return NS_SUCCESS;
+}
+
+/*ARGSUSED*/
+int
+_dns_gethtbyaddr(void *rv, void        *cb_data, va_list ap)
+{
+       char qbuf[MAXDNAME + 1], *qp, *ep;
+       int n;
+       querybuf *buf;
+       struct hostent *hp;
+       const unsigned char *uaddr;
+       int len, af, advance;
+       res_state res;
+
+       _DIAGASSERT(rv != NULL);
+
+       uaddr = va_arg(ap, unsigned char *);
+       len = va_arg(ap, int);
+       af = va_arg(ap, int);
+
+       switch (af) {
+       case AF_INET:
+               (void)snprintf(qbuf, sizeof(qbuf), "%u.%u.%u.%u.in-addr.arpa",
+                   (uaddr[3] & 0xff), (uaddr[2] & 0xff),
+                   (uaddr[1] & 0xff), (uaddr[0] & 0xff));
+               break;
+
+       case AF_INET6:
+               qp = qbuf;
+               ep = qbuf + sizeof(qbuf) - 1;
+               for (n = IN6ADDRSZ - 1; n >= 0; n--) {
+                       advance = snprintf(qp, (size_t)(ep - qp), "%x.%x.",
+                           uaddr[n] & 0xf,
+                           ((unsigned int)uaddr[n] >> 4) & 0xf);
+                       if (advance > 0 && qp + advance < ep)
+                               qp += advance;
+                       else {
+                               h_errno = NETDB_INTERNAL;
+                               return NS_NOTFOUND;
+                       }
+               }
+               if (strlcat(qbuf, "ip6.arpa", sizeof(qbuf)) >= sizeof(qbuf)) {
+                       h_errno = NETDB_INTERNAL;
+                       return NS_NOTFOUND;
+               }
+               break;
+       default:
+               abort();
+       }
+
+       buf = malloc(sizeof(*buf));
+       if (buf == NULL) {
+               h_errno = NETDB_INTERNAL;
+               return NS_NOTFOUND;
+       }
+       res = __res_get_state();
+       if (res == NULL) {
+               free(buf);
+               return NS_NOTFOUND;
+       }
+       n = res_nquery(res, qbuf, C_IN, T_PTR, buf->buf, sizeof(buf->buf));
+       if (n < 0) {
+               free(buf);
+               debugprintf("res_nquery failed (%d)\n", res, n);
+               __res_put_state(res);
+               return NS_NOTFOUND;
+       }
+       hp = getanswer(buf, n, qbuf, T_PTR, res);
+       free(buf);
+       if (hp == NULL) {
+               __res_put_state(res);
+               switch (h_errno) {
+               case HOST_NOT_FOUND:
+                       return NS_NOTFOUND;
+               case TRY_AGAIN:
+                       return NS_TRYAGAIN;
+               default:
+                       return NS_UNAVAIL;
+               }
+       }
+       hp->h_addrtype = af;
+       hp->h_length = len;
+       (void)memcpy(host_addr, uaddr, (size_t)len);
+       h_addr_ptrs[0] = (char *)(void *)host_addr;
+       h_addr_ptrs[1] = NULL;
+       if (af == AF_INET && (res->options & RES_USE_INET6)) {
+               map_v4v6_address((char *)(void *)host_addr,
+                   (char *)(void *)host_addr);
+               hp->h_addrtype = AF_INET6;
+               hp->h_length = IN6ADDRSZ;
+       }
+
+       __res_put_state(res);
+       *((struct hostent **)rv) = hp;
+       h_errno = NETDB_SUCCESS;
+       return NS_SUCCESS;
+}
+
+#ifdef YP
+/*ARGSUSED*/
+struct hostent *
+_yphostent(char *line, int af)
+{
+       static struct in_addr host_addrs[MAXADDRS];
+       static struct in6_addr host6_addrs[MAXADDRS];
+       char *p = line;
+       char *cp, **q;
+       char **hap;
+       int addrok;
+       int more;
+       size_t naddrs;
+
+       _DIAGASSERT(line != NULL);
+
+       host.h_name = NULL;
+       host.h_addr_list = h_addr_ptrs;
+       host.h_addrtype = af;
+       switch (af) {
+       case AF_INET:
+               host.h_length = INADDRSZ;
+               break;
+       case AF_INET6:
+               host.h_length = IN6ADDRSZ;
+               break;
+       default:
+               return NULL;
+       }
+       hap = h_addr_ptrs;
+       q = host.h_aliases = host_aliases;
+       naddrs = 0;
+
+nextline:
+       /* check for host_addrs overflow */
+       if (naddrs >= sizeof(host_addrs) / sizeof(host_addrs[0]))
+               goto done;
+       if (naddrs >= sizeof(host6_addrs) / sizeof(host6_addrs[0]))
+               goto done;
+
+       more = 0;
+       cp = strpbrk(p, " \t");
+       if (cp == NULL)
+               goto done;
+       *cp++ = '\0';
+
+       /* p has should have an address */
+       addrok = 0;
+       switch (af) {
+       case AF_INET:
+               addrok = inet_aton(p, &host_addrs[naddrs]);
+               break;
+       case AF_INET6:
+               addrok = inet_pton(af, p, &host6_addrs[naddrs]);
+               break;
+       }
+       if (addrok != 1) {
+               /* skip to the next line */
+               while (cp && *cp) {
+                       if (*cp == '\n') {
+                               cp++;
+                               goto nextline;
+                       }
+                       cp++;
+               }
+
+               goto done;
+       }
+
+       switch (af) {
+       case AF_INET:
+               *hap++ = (char *)(void *)&host_addrs[naddrs++];
+               break;
+       case AF_INET6:
+               *hap++ = (char *)(void *)&host6_addrs[naddrs++];
+               break;
+       }
+
+       while (*cp == ' ' || *cp == '\t')
+               cp++;
+       p = cp;
+       cp = strpbrk(p, " \t\n");
+       if (cp != NULL) {
+               if (*cp == '\n')
+                       more = 1;
+               *cp++ = '\0';
+       }
+       if (!host.h_name)
+               host.h_name = p;
+       else if (strcmp(host.h_name, p)==0)
+               ;
+       else if (q < &host_aliases[MAXALIASES - 1])
+               *q++ = p;
+       p = cp;
+       if (more)
+               goto nextline;
+
+       while (cp && *cp) {
+               if (*cp == ' ' || *cp == '\t') {
+                       cp++;
+                       continue;
+               }
+               if (*cp == '\n') {
+                       cp++;
+                       goto nextline;
+               }
+               if (q < &host_aliases[MAXALIASES - 1])
+                       *q++ = cp;
+               cp = strpbrk(cp, " \t");
+               if (cp != NULL)
+                       *cp++ = '\0';
+       }
+
+done:
+       if (host.h_name == NULL)
+               return NULL;
+       *q = NULL;
+       *hap = NULL;
+       return &host;
+}
+
+/*ARGSUSED*/
+int
+_yp_gethtbyaddr(void *rv, void *cb_data, va_list ap)
+{
+       struct hostent *hp = NULL;
+       static char *__ypcurrent;
+       int __ypcurrentlen, r;
+       char name[INET6_ADDRSTRLEN];    /* XXX enough? */
+       const unsigned char *uaddr;
+       int af;
+       const char *map;
+
+       _DIAGASSERT(rv != NULL);
+
+       uaddr = va_arg(ap, unsigned char *);
+       /* NOSTRICT skip len */(void)va_arg(ap, int);
+       af = va_arg(ap, int);
+       
+       if (!__ypdomain) {
+               if (_yp_check(&__ypdomain) == 0)
+                       return NS_UNAVAIL;
+       }
+       /*
+        * XXX unfortunately, we cannot support IPv6 extended scoped address
+        * notation here.  gethostbyaddr() is not scope-aware.  too bad.
+        */
+       if (inet_ntop(af, uaddr, name, sizeof(name)) == NULL)
+               return NS_UNAVAIL;
+       if (__ypcurrent)
+               free(__ypcurrent);
+       __ypcurrent = NULL;
+       switch (af) {
+       case AF_INET:
+               map = "hosts.byaddr";
+               break;
+       default:
+               map = "ipnodes.byaddr";
+               break;
+       }
+       r = yp_match(__ypdomain, map, name,
+               (int)strlen(name), &__ypcurrent, &__ypcurrentlen);
+       if (r == 0)
+               hp = _yphostent(__ypcurrent, af);
+       if (hp == NULL) {
+               h_errno = HOST_NOT_FOUND;
+               return NS_NOTFOUND;
+       }
+       *((struct hostent **)rv) = hp;
+       return NS_SUCCESS;
+}
+
+/*ARGSUSED*/
+int
+_yp_gethtbyname(void *rv, void *cb_data, va_list ap)
+{
+       struct hostent *hp = NULL;
+       static char *__ypcurrent;
+       int __ypcurrentlen, r;
+       const char *name;
+       int af;
+       const char *map;
+
+       _DIAGASSERT(rv != NULL);
+
+       name = va_arg(ap, char *);
+       /* NOSTRICT skip len */(void)va_arg(ap, int);
+       af = va_arg(ap, int);
+
+       if (!__ypdomain) {
+               if (_yp_check(&__ypdomain) == 0)
+                       return NS_UNAVAIL;
+       }
+       if (__ypcurrent)
+               free(__ypcurrent);
+       __ypcurrent = NULL;
+       switch (af) {
+       case AF_INET:
+               map = "hosts.byname";
+               break;
+       default:
+               map = "ipnodes.byname";
+               break;
+       }
+       r = yp_match(__ypdomain, map, name,
+               (int)strlen(name), &__ypcurrent, &__ypcurrentlen);
+       if (r == 0)
+               hp = _yphostent(__ypcurrent, af);
+       if (hp == NULL) {
+               h_errno = HOST_NOT_FOUND;
+               return NS_NOTFOUND;
+       }
+       *((struct hostent **)rv) = hp;
+       return NS_SUCCESS;
+}
+#endif
diff --git a/lib/nbsd_libc/net/gethostbyname.3 b/lib/nbsd_libc/net/gethostbyname.3
new file mode 100644 (file)
index 0000000..e0224bc
--- /dev/null
@@ -0,0 +1,333 @@
+.\"    $NetBSD: gethostbyname.3,v 1.28 2006/10/07 21:30:39 apb Exp $
+.\"
+.\" Copyright (c) 1983, 1987, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)gethostbyname.3   8.4 (Berkeley) 5/25/95
+.\"
+.Dd October 7, 2006
+.Dt GETHOSTBYNAME 3
+.Os
+.Sh NAME
+.Nm gethostbyname ,
+.Nm gethostbyname2 ,
+.Nm gethostbyaddr ,
+.Nm gethostent ,
+.Nm sethostent ,
+.Nm endhostent ,
+.Nm herror ,
+.Nm hstrerror
+.Nd get network host entry
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In netdb.h
+.Fd extern int h_errno;
+.Ft struct hostent *
+.Fn gethostbyname "const char *name"
+.Ft struct hostent *
+.Fn gethostbyname2 "const char *name" "int af"
+.Ft struct hostent *
+.Fn gethostbyaddr "const char *addr" "socklen_t len" "int type"
+.Ft struct hostent *
+.Fn gethostent void
+.Ft void
+.Fn sethostent "int stayopen"
+.Ft void
+.Fn endhostent void
+.Ft void
+.Fn herror "const char *string"
+.Ft const char *
+.Fn hstrerror "int err"
+.Sh DESCRIPTION
+The
+.Fn gethostbyname ,
+.Fn gethostbyname2
+and
+.Fn gethostbyaddr
+functions
+each return a pointer to an object with the
+following structure describing an internet host.
+.Bd -literal
+struct hostent {
+       char    *h_name;        /* official name of host */
+       char    **h_aliases;    /* alias list */
+       int     h_addrtype;     /* host address type */
+       int     h_length;       /* length of address */
+       char    **h_addr_list;  /* list of addresses from name server */
+};
+#define        h_addr  h_addr_list[0]  /* address, for backward compatibility */
+.Ed
+.Pp
+The members of this structure are:
+.Bl -tag -width h_addr_list
+.It Fa h_name
+Official name of the host.
+.It Fa h_aliases
+A NULL-terminated array of alternative names for the host.
+.It Fa h_addrtype
+The type of address being returned; currently always
+.Dv AF_INET .
+.It Fa h_length
+The length, in bytes, of the address.
+.It Fa h_addr_list
+A NULL-terminated array of network addresses for the host.
+Host addresses are returned in network byte order.
+.It Fa h_addr
+The first address in
+.Fa h_addr_list ;
+this is for backward compatibility.
+.El
+.Pp
+In the case of
+.Fn gethostbyname
+and
+.Fn gethostbyname2 ,
+the host is specified by name,
+or using a string representation of a numeric address.
+In the case of
+.Fn gethostbyaddr ,
+the host is specified using a binary representation of an address.
+.Pp
+The returned
+.Ft "struct hostent"
+structure may contain
+the result of a simple string to binary conversion,
+information obtained from the domain name resolver (see
+.Xr resolver 3 ) ,
+broken-out fields from a line in
+.Pa /etc/hosts ,
+or database entries supplied by the
+.Xr yp 8
+system.
+The order of the lookups is controlled by the
+.Sq hosts
+entry in
+.Xr nsswitch.conf 5 .
+.Pp
+When using the domain name resolver,
+.Fn gethostbyname
+and
+.Fn gethostbyname2
+will search for the named host in the current domain and its parents
+unless the name ends in a dot.
+If the name contains no dot, and if the environment variable
+.Dq Ev HOSTALIASES
+contains the name of an alias file, the alias file will first be searched
+for an alias matching the input name.
+See
+.Xr hostname 7
+for the domain search procedure and the alias file format.
+.Pp
+The
+.Fn gethostbyname2
+function is an evolution of
+.Fn gethostbyname
+which is intended to allow lookups in address families other than
+.Dv AF_INET ,
+for example
+.Dv AF_INET6 .
+Currently the
+.Fa af
+argument must be specified as
+.Dv AF_INET
+or
+.Dv AF_INET6 ,
+else the function will return
+.Dv NULL
+after having set
+.Va h_errno
+to
+.Dv NETDB_INTERNAL .
+.Pp
+The
+.Fn gethostent
+function
+reads the next line of the
+.Pa /etc/hosts
+file, opening the file if necessary.
+.Pp
+The
+.Fn sethostent
+function
+may be used to request the use of a connected
+.Tn TCP
+socket for queries.
+If the
+.Fa stayopen
+flag is non-zero,
+this sets the option to send all queries to the name server using
+.Tn TCP
+and to retain the connection after each call to
+.Fn gethostbyname ,
+.Fn gethostbyname2 ,
+or
+.Fn gethostbyaddr .
+Otherwise, queries are performed using
+.Tn UDP
+datagrams.
+.Pp
+The
+.Fn endhostent
+function
+closes the
+.Tn TCP
+connection.
+.Pp
+The
+.Fn herror
+function writes a message to the diagnostic output consisting of the
+string parameter
+.Fa s ,
+the constant string ": ", and a message corresponding to the value of
+.Va h_errno .
+.Pp
+The
+.Fn hstrerror
+function returns a string which is the message text corresponding to the
+value of the
+.Fa err
+parameter.
+.Sh FILES
+.Bl -tag -width /etc/hosts -compact
+.It Pa /etc/hosts
+.El
+.Sh DIAGNOSTICS
+Error return status from
+.Fn gethostbyent ,
+.Fn gethostbyname ,
+.Fn gethostbyname2 ,
+and
+.Fn gethostbyaddr
+is indicated by return of a null pointer.
+The external integer
+.Va h_errno
+may then be checked to see whether this is a temporary failure
+or an invalid or unknown host.
+The routine
+.Fn herror
+can be used to print an error message describing the failure.
+If its argument
+.Fa string
+is
+.Pf non Dv -NULL ,
+it is printed, followed by a colon and a space.
+The error message is printed with a trailing newline.
+.Pp
+The variable
+.Va h_errno
+can have the following values:
+.Bl -tag -width HOST_NOT_FOUND
+.It Dv HOST_NOT_FOUND
+No such host is known.
+.It Dv TRY_AGAIN
+This is usually a temporary error
+and means that the local server did not receive
+a response from an authoritative server.
+A retry at some later time may succeed.
+.It Dv NO_RECOVERY
+Some unexpected server failure was encountered.
+This is a non-recoverable error.
+.It Dv NO_DATA
+The requested name is valid but does not have an IP address;
+this is not a temporary error.
+This means that the name is known to the name server but there is no address
+associated with this name.
+Another type of request to the name server using this domain name
+will result in an answer;
+for example, a mail-forwarder may be registered for this domain.
+.El
+.Sh SEE ALSO
+.Xr resolver 3 ,
+.Xr hosts 5 ,
+.Xr nsswitch.conf 5 ,
+.Xr hostname 7 ,
+.Xr named 8
+.Sh HISTORY
+The
+.Fn herror
+function appeared in
+.Bx 4.3 .
+The
+.Fn endhostent ,
+.Fn gethostbyaddr ,
+.Fn gethostbyname ,
+.Fn gethostent ,
+and
+.Fn sethostent
+functions appeared in
+.Bx 4.2 .
+The
+.Fn gethostbyname2
+function first appeared in bind-4.9.4.
+IPv6 support was implemented in WIDE Hydrangea IPv6 protocol stack kit.
+.Sh CAVEATS
+If the search routines specified in
+.Xr nsswitch.conf 5
+decide to read the
+.Pa /etc/hosts
+file,
+.Fn gethostbyname ,
+.Fn gethostbyname2 ,
+and
+.Fn gethostbyaddr
+will
+read the next line of the file,
+re-opening the file if necessary.
+.Pp
+The
+.Fn sethostent
+function
+opens and/or rewinds the file
+.Pa /etc/hosts .
+If the
+.Fa stayopen
+argument is non-zero,
+the file will not be closed after each call to
+.Fn gethostbyname ,
+.Fn gethostbyname2 ,
+.Fn gethostbyaddr ,
+or
+.Fn gethostent .
+.Pp
+The
+.Fn endhostent
+function closes the file.
+.Sh BUGS
+These functions use static data storage;
+if the data is needed for future use, it should be
+copied before any subsequent calls overwrite it.
+Only the Internet
+address format is currently understood.
+.Pp
+The
+.Fn gethostent
+does not currently follow the search order specified in
+.Xr nsswitch.conf 5
+and only reads the
+.Pa /etc/hosts
+file.
diff --git a/lib/nbsd_libc/net/getifaddrs.3 b/lib/nbsd_libc/net/getifaddrs.3
new file mode 100644 (file)
index 0000000..f698186
--- /dev/null
@@ -0,0 +1,167 @@
+.\"    $NetBSD: getifaddrs.3,v 1.12 2010/03/22 19:30:54 joerg Exp $
+.\"    BSDI    getifaddrs.3,v 2.5 2000/02/23 14:51:59 dab Exp
+.\"
+.\" Copyright (c) 1995, 1999
+.\"    Berkeley Software Design, Inc.  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.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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.
+.Dd April 21, 2009
+.Dt GETIFADDRS 3
+.Os
+.Sh NAME
+.Nm getifaddrs
+.Nd get interface addresses
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/socket.h
+.In ifaddrs.h
+.Ft int
+.Fn getifaddrs "struct ifaddrs **ifap"
+.Ft void
+.Fn freeifaddrs "struct ifaddrs *ifp"
+.Sh DESCRIPTION
+The
+.Fn getifaddrs
+function stores a reference to a linked list of the network interfaces
+on the local machine in the memory referenced by
+.Fa ifap .
+The list consists of
+.Nm ifaddrs
+structures, as defined in the include file
+.In ifaddrs.h .
+The
+.Nm ifaddrs
+structure contains at least the following entries:
+.Bd -literal
+    struct ifaddrs   *ifa_next;         /* Pointer to next struct */
+    char             *ifa_name;         /* Interface name */
+    u_int             ifa_flags;        /* Interface flags */
+    struct sockaddr  *ifa_addr;         /* Interface address */
+    struct sockaddr  *ifa_netmask;      /* Interface netmask */
+    struct sockaddr  *ifa_broadaddr;    /* Interface broadcast address */
+    struct sockaddr  *ifa_dstaddr;      /* P2P interface destination */
+    void             *ifa_data;                /* Address specific data */
+.Ed
+.Pp
+The
+.Li ifa_next
+field contains a pointer to the next structure on the list.
+This field is
+.Dv NULL
+in last structure on the list.
+.Pp
+The
+.Li ifa_name
+field contains the interface name.
+.Pp
+The
+.Li ifa_flags
+field contains the interface flags, as set by
+.Xr ifconfig 8
+utility.
+.Pp
+The
+.Li ifa_addr
+field references either the address of the interface or the link level
+address of the interface, if one exists, otherwise it is
+.Dv NULL .
+(The
+.Li sa_family
+field of the
+.Li ifa_addr
+field should be consulted to determine the format of the
+.Li ifa_addr
+address.)
+.Pp
+The
+.Li ifa_netmask
+field references the netmask associated with
+.Li ifa_addr ,
+if one is set, otherwise it is
+.Dv NULL .
+.Pp
+The
+.Li ifa_broadaddr
+field,
+which should only be referenced for non-P2P interfaces,
+references the broadcast address associated with
+.Li ifa_addr ,
+if one exists, otherwise it is
+.Dv NULL .
+.Pp
+The
+.Li ifa_dstaddr
+field references the destination address on a P2P interface,
+if one exists, otherwise it is
+.Dv NULL .
+.Pp
+The
+.Li ifa_data
+field references address family specific data.
+For
+.Dv AF_LINK
+addresses it contains a pointer to the
+.Fa struct if_data
+.Pq as defined in include file Aq Pa net/if.h
+which contains various interface attributes and statistics.
+For all other address families, it is
+.Dv NULL .
+.Pp
+The data returned by
+.Fn getifaddrs
+is dynamically allocated and should be freed using
+.Fn freeifaddrs
+when no longer needed.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of -1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn getifaddrs
+may fail and set
+.Va errno
+for any of the errors specified for the library routines
+.Xr ioctl 2 ,
+.Xr socket 2 ,
+.Xr malloc 3
+or
+.Xr sysctl 3 .
+.Sh SEE ALSO
+.Xr ioctl 2 ,
+.Xr socket 2 ,
+.Xr sysctl 3 ,
+.Xr networking 4 ,
+.Xr ifconfig 8
+.Sh HISTORY
+The
+.Nm
+implementation first appeared in
+.Bsx .
+.Sh BUGS
+If both
+.In net/if.h
+and
+.In ifaddrs.h
+are being included,
+.In net/if.h
+.Em must
+be included before
+.In ifaddrs.h .
diff --git a/lib/nbsd_libc/net/getifaddrs.c b/lib/nbsd_libc/net/getifaddrs.c
new file mode 100644 (file)
index 0000000..7fde5ab
--- /dev/null
@@ -0,0 +1,305 @@
+/*     $NetBSD: getifaddrs.c,v 1.13 2010/11/05 16:23:56 pooka Exp $    */
+
+/*
+ * Copyright (c) 1995, 1999
+ *     Berkeley Software Design, Inc.  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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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.
+ *
+ *     BSDI getifaddrs.c,v 2.12 2000/02/23 14:51:59 dab Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getifaddrs.c,v 1.13 2010/11/05 16:23:56 pooka Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifndef RUMP_ACTION
+#include "namespace.h"
+#endif
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <net/if.h>
+#include <sys/param.h>
+#include <net/route.h>
+#include <sys/sysctl.h>
+#include <net/if_dl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <ifaddrs.h>
+#include <stdlib.h>
+#include <string.h>
+
+#if defined(__weak_alias) && !defined(RUMP_ACTION)
+__weak_alias(getifaddrs,_getifaddrs)
+__weak_alias(freeifaddrs,_freeifaddrs)
+#endif
+
+#ifdef RUMP_ACTION
+#include <rump/rump_syscalls.h>
+#define sysctl(a,b,c,d,e,f) rump_sys___sysctl(a,b,c,d,e,f)
+#endif
+
+#define        SALIGN  (sizeof(long) - 1)
+#define        SA_RLEN(sa)     ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : (SALIGN + 1))
+
+int
+getifaddrs(struct ifaddrs **pif)
+{
+       int icnt = 1;
+       int dcnt = 0;
+       int ncnt = 0;
+       int mib[6];
+       size_t needed;
+       char *buf;
+       char *next;
+       struct ifaddrs cif;
+       char *p, *p0;
+       struct rt_msghdr *rtm;
+       struct if_msghdr *ifm;
+       struct ifa_msghdr *ifam;
+       struct sockaddr *sa;
+       struct ifaddrs *ifa, *ift;
+       u_short idx = 0;
+       int i;
+       size_t len, alen;
+       char *data;
+       char *names;
+
+       _DIAGASSERT(pif != NULL);
+
+       mib[0] = CTL_NET;
+       mib[1] = PF_ROUTE;
+       mib[2] = 0;             /* protocol */
+       mib[3] = 0;             /* wildcard address family */
+       mib[4] = NET_RT_IFLIST;
+       mib[5] = 0;             /* no flags */
+       if (sysctl(mib, __arraycount(mib), NULL, &needed, NULL, 0) < 0)
+               return (-1);
+       if ((buf = malloc(needed)) == NULL)
+               return (-1);
+       if (sysctl(mib, __arraycount(mib), buf, &needed, NULL, 0) < 0) {
+               free(buf);
+               return (-1);
+       }
+
+       for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
+               rtm = (struct rt_msghdr *)(void *)next;
+               if (rtm->rtm_version != RTM_VERSION)
+                       continue;
+               switch (rtm->rtm_type) {
+               case RTM_IFINFO:
+                       ifm = (struct if_msghdr *)(void *)rtm;
+                       if (ifm->ifm_addrs & RTA_IFP) {
+                               const struct sockaddr_dl *dl;
+
+                               idx = ifm->ifm_index;
+                               ++icnt;
+                               dl = (struct sockaddr_dl *)(void *)(ifm + 1);
+                               dcnt += SA_RLEN((const struct sockaddr *)(const void *)dl) +
+                                   ALIGNBYTES;
+                               dcnt += sizeof(ifm->ifm_data);
+                               ncnt += dl->sdl_nlen + 1;
+                       } else
+                               idx = 0;
+                       break;
+
+               case RTM_NEWADDR:
+                       ifam = (struct ifa_msghdr *)(void *)rtm;
+                       if (idx && ifam->ifam_index != idx)
+                               abort();        /* this cannot happen */
+
+#define        RTA_MASKS       (RTA_NETMASK | RTA_IFA | RTA_BRD)
+                       if (idx == 0 || (ifam->ifam_addrs & RTA_MASKS) == 0)
+                               break;
+                       p = (char *)(void *)(ifam + 1);
+                       ++icnt;
+                       /* Scan to look for length of address */
+                       alen = 0;
+                       for (p0 = p, i = 0; i < RTAX_MAX; i++) {
+                               if ((RTA_MASKS & ifam->ifam_addrs & (1 << i))
+                                   == 0)
+                                       continue;
+                               sa = (struct sockaddr *)(void *)p;
+                               len = SA_RLEN(sa);
+                               if (i == RTAX_IFA) {
+                                       alen = len;
+                                       break;
+                               }
+                               p += len;
+                       }
+                       for (p = p0, i = 0; i < RTAX_MAX; i++) {
+                               if ((RTA_MASKS & ifam->ifam_addrs & (1 << i))
+                                   == 0)
+                                       continue;
+                               sa = (struct sockaddr *)(void *)p;
+                               len = SA_RLEN(sa);
+                               if (i == RTAX_NETMASK && sa->sa_len == 0)
+                                       dcnt += alen;
+                               else
+                                       dcnt += len;
+                               p += len;
+                       }
+                       break;
+               }
+       }
+
+       if (icnt + dcnt + ncnt == 1) {
+               *pif = NULL;
+               free(buf);
+               return (0);
+       }
+       data = malloc(sizeof(struct ifaddrs) * icnt + dcnt + ncnt);
+       if (data == NULL) {
+               free(buf);
+               return(-1);
+       }
+
+       ifa = (struct ifaddrs *)(void *)data;
+       data += sizeof(struct ifaddrs) * icnt;
+       names = data + dcnt;
+
+       memset(ifa, 0, sizeof(struct ifaddrs) * icnt);
+       ift = ifa;
+
+       idx = 0;
+       for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
+               rtm = (struct rt_msghdr *)(void *)next;
+               if (rtm->rtm_version != RTM_VERSION)
+                       continue;
+               switch (rtm->rtm_type) {
+               case RTM_IFINFO:
+                       ifm = (struct if_msghdr *)(void *)rtm;
+                       if (ifm->ifm_addrs & RTA_IFP) {
+                               const struct sockaddr_dl *dl;
+
+                               idx = ifm->ifm_index;
+                               dl = (struct sockaddr_dl *)(void *)(ifm + 1);
+
+                               memset(&cif, 0, sizeof(cif));
+
+                               cif.ifa_name = names;
+                               cif.ifa_flags = (int)ifm->ifm_flags;
+                               memcpy(names, dl->sdl_data,
+                                   (size_t)dl->sdl_nlen);
+                               names[dl->sdl_nlen] = 0;
+                               names += dl->sdl_nlen + 1;
+
+                               cif.ifa_addr = (struct sockaddr *)(void *)data;
+                               memcpy(data, dl, (size_t)dl->sdl_len);
+                               data += SA_RLEN((const struct sockaddr *)(const void *)dl);
+
+                               /* ifm_data needs to be aligned */
+                               cif.ifa_data = data = (void *)ALIGN(data);
+                               memcpy(data, &ifm->ifm_data, sizeof(ifm->ifm_data));
+                               data += sizeof(ifm->ifm_data);
+                       } else
+                               idx = 0;
+                       break;
+
+               case RTM_NEWADDR:
+                       ifam = (struct ifa_msghdr *)(void *)rtm;
+                       if (idx && ifam->ifam_index != idx)
+                               abort();        /* this cannot happen */
+
+                       if (idx == 0 || (ifam->ifam_addrs & RTA_MASKS) == 0)
+                               break;
+                       ift->ifa_name = cif.ifa_name;
+                       ift->ifa_flags = cif.ifa_flags;
+                       ift->ifa_data = NULL;
+                       p = (char *)(void *)(ifam + 1);
+                       /* Scan to look for length of address */
+                       alen = 0;
+                       for (p0 = p, i = 0; i < RTAX_MAX; i++) {
+                               if ((RTA_MASKS & ifam->ifam_addrs & (1 << i))
+                                   == 0)
+                                       continue;
+                               sa = (struct sockaddr *)(void *)p;
+                               len = SA_RLEN(sa);
+                               if (i == RTAX_IFA) {
+                                       alen = len;
+                                       break;
+                               }
+                               p += len;
+                       }
+                       for (p = p0, i = 0; i < RTAX_MAX; i++) {
+                               if ((RTA_MASKS & ifam->ifam_addrs & (1 << i))
+                                   == 0)
+                                       continue;
+                               sa = (struct sockaddr *)(void *)p;
+                               len = SA_RLEN(sa);
+                               switch (i) {
+                               case RTAX_IFA:
+                                       ift->ifa_addr =
+                                           (struct sockaddr *)(void *)data;
+                                       memcpy(data, p, len);
+                                       data += len;
+                                       if (ift->ifa_addr->sa_family == AF_LINK)
+                                               ift->ifa_data = cif.ifa_data;
+                                       break;
+
+                               case RTAX_NETMASK:
+                                       ift->ifa_netmask =
+                                           (struct sockaddr *)(void *)data;
+                                       if (sa->sa_len == 0) {
+                                               memset(data, 0, alen);
+                                               data += alen;
+                                               break;
+                                       }
+                                       memcpy(data, p, len);
+                                       data += len;
+                                       break;
+
+                               case RTAX_BRD:
+                                       ift->ifa_broadaddr =
+                                           (struct sockaddr *)(void *)data;
+                                       memcpy(data, p, len);
+                                       data += len;
+                                       break;
+                               }
+                               p += len;
+                       }
+
+
+                       ift = (ift->ifa_next = ift + 1);
+                       break;
+               }
+       }
+
+       free(buf);
+       if (--ift >= ifa) {
+               ift->ifa_next = NULL;
+               *pif = ifa;
+       } else {
+               *pif = NULL;
+               free(ifa);
+       }
+       return (0);
+}
+
+void
+freeifaddrs(struct ifaddrs *ifp)
+{
+
+       _DIAGASSERT(ifp != NULL);
+
+       free(ifp);
+}
diff --git a/lib/nbsd_libc/net/getnameinfo.3 b/lib/nbsd_libc/net/getnameinfo.3
new file mode 100644 (file)
index 0000000..5cd3539
--- /dev/null
@@ -0,0 +1,268 @@
+.\"    $NetBSD: getnameinfo.3,v 1.37 2010/03/22 19:30:54 joerg Exp $
+.\"    $KAME: getnameinfo.3,v 1.37 2005/01/05 03:23:05 itojun Exp $
+.\"    $OpenBSD: getnameinfo.3,v 1.36 2004/12/21 09:48:20 jmc Exp $
+.\"
+.\" Copyright (C) 2004  Internet Systems Consortium, Inc. ("ISC")
+.\" Copyright (C) 2000, 2001  Internet Software Consortium.
+.\"
+.\" 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 ISC DISCLAIMS ALL WARRANTIES WITH
+.\" REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+.\" AND FITNESS.  IN NO EVENT SHALL ISC 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.
+.\"
+.Dd March 21, 2005
+.Dt GETNAMEINFO 3
+.Os
+.Sh NAME
+.Nm getnameinfo
+.Nd socket address structure to hostname and service name
+.Sh SYNOPSIS
+.In netdb.h
+.Ft int
+.Fn getnameinfo "const struct sockaddr * restrict sa" "socklen_t salen" \
+    "char * restrict host" "size_t hostlen" "char * restrict serv" \
+    "size_t servlen" "int flags"
+.Sh DESCRIPTION
+The
+.Fn getnameinfo
+function is used to convert a
+.Li sockaddr
+structure to a pair of host name and service strings.
+It is a replacement for and provides more flexibility than the
+.Xr gethostbyaddr 3
+and
+.Xr getservbyport 3
+functions and is the converse of the
+.Xr getaddrinfo 3
+function.
+.Pp
+The
+.Li sockaddr
+structure
+.Fa sa
+should point to either a
+.Li sockaddr_in
+or
+.Li sockaddr_in6
+structure (for IPv4 or IPv6 respectively) that is
+.Fa salen
+bytes long.
+.Pp
+The host and service names associated with
+.Fa sa
+are stored in
+.Fa host
+and
+.Fa serv
+which have length parameters
+.Fa hostlen
+and
+.Fa servlen .
+The maximum value for
+.Fa hostlen
+is
+.Dv NI_MAXHOST
+and the maximum value for
+.Fa servlen
+is
+.Dv NI_MAXSERV ,
+as defined by
+.In netdb.h .
+If a length parameter is zero, no string will be stored.
+Otherwise, enough space must be provided to store the
+host name or service string plus a byte for the NUL terminator.
+.Pp
+The
+.Fa flags
+argument is formed by
+.Sy OR Ns 'ing
+the following values:
+.Bl -tag -width "NI_NUMERICHOSTXX"
+.It Dv NI_NOFQDN
+A fully qualified domain name is not required for local hosts.
+The local part of the fully qualified domain name is returned instead.
+.It Dv NI_NUMERICHOST
+Return the address in numeric form, as if calling
+.Xr inet_ntop 3 ,
+instead of a host name.
+.It Dv NI_NAMEREQD
+A name is required.
+If the host name cannot be found in DNS and this flag is set,
+a non-zero error code is returned.
+If the host name is not found and the flag is not set, the
+address is returned in numeric form.
+.It NI_NUMERICSERV
+The service name is returned as a digit string representing the port number.
+.It NI_DGRAM
+Specifies that the service being looked up is a datagram
+service, and causes
+.Xr getservbyport 3
+to be called with a second argument of
+.Dq udp
+instead of its default of
+.Dq tcp .
+This is required for the few ports (512\-514) that have different services
+for
+.Tn UDP
+and
+.Tn TCP .
+.El
+.Pp
+This implementation allows numeric IPv6 address notation with scope identifier,
+as documented in chapter 11 of draft-ietf-ipv6-scoping-arch-02.txt.
+IPv6 link-local address will appear as a string like
+.Dq Li fe80::1%ne0 .
+Refer to
+.Xr getaddrinfo 3
+for more information.
+.Sh RETURN VALUES
+.Fn getnameinfo
+returns zero on success or one of the error codes listed in
+.Xr gai_strerror 3
+if an error occurs.
+.Sh EXAMPLES
+The following code tries to get a numeric host name, and service name,
+for a given socket address.
+Observe that there is no hardcoded reference to a particular address family.
+.Bd -literal -offset indent
+struct sockaddr *sa;   /* input */
+char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
+
+if (getnameinfo(sa, sa-\*[Gt]sa_len, hbuf, sizeof(hbuf), sbuf,
+    sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) {
+       errx(1, "could not get numeric hostname");
+       /*NOTREACHED*/
+}
+printf("host=%s, serv=%s\en", hbuf, sbuf);
+.Ed
+.Pp
+The following version checks if the socket address has a reverse address mapping:
+.Bd -literal -offset indent
+struct sockaddr *sa;   /* input */
+char hbuf[NI_MAXHOST];
+
+if (getnameinfo(sa, sa-\*[Gt]sa_len, hbuf, sizeof(hbuf), NULL, 0,
+    NI_NAMEREQD)) {
+       errx(1, "could not resolve hostname");
+       /*NOTREACHED*/
+}
+printf("host=%s\en", hbuf);
+.Ed
+.Sh SEE ALSO
+.Xr gai_strerror 3 ,
+.Xr getaddrinfo 3 ,
+.Xr gethostbyaddr 3 ,
+.Xr getservbyport 3 ,
+.Xr inet_ntop 3 ,
+.Xr resolver 3 ,
+.Xr hosts 5 ,
+.Xr resolv.conf 5 ,
+.Xr services 5 ,
+.Xr hostname 7 ,
+.Xr named 8
+.Rs
+.%A R. Gilligan
+.%A S. Thomson
+.%A J. Bound
+.%A W. Stevens
+.%T Basic Socket Interface Extensions for IPv6
+.%R RFC 2553
+.%D March 1999
+.Re
+.Rs
+.%A S. Deering
+.%A B. Haberman
+.%A T. Jinmei
+.%A E. Nordmark
+.%A B. Zill
+.%T "IPv6 Scoped Address Architecture"
+.%R internet draft
+.%N draft-ietf-ipv6-scoping-arch-02.txt
+.%O work in progress material
+.Re
+.Rs
+.%A Craig Metz
+.%T Protocol Independence Using the Sockets API
+.%B "Proceedings of the FREENIX track: 2000 USENIX annual technical conference"
+.%D June 2000
+.Re
+.Sh STANDARDS
+The
+.Fn getnameinfo
+function is defined by the
+.St -p1003.1g-2000
+draft specification and documented in
+.Sy "RFC 2553" ,
+.Dq Basic Socket Interface Extensions for IPv6 .
+.Sh CAVEATS
+.Fn getnameinfo
+can return both numeric and FQDN forms of the address specified in
+.Fa sa .
+There is no return value that indicates whether the string returned in
+.Fa host
+is a result of binary to numeric-text translation (like
+.Xr inet_ntop 3 ) ,
+or is the result of a DNS reverse lookup.
+Because of this, malicious parties could set up a PTR record as follows:
+.Bd -literal -offset indent
+1.0.0.127.in-addr.arpa. IN PTR  10.1.1.1
+.Ed
+.Pp
+and trick the caller of
+.Fn getnameinfo
+into believing that
+.Fa sa
+is
+.Li 10.1.1.1
+when it is actually
+.Li 127.0.0.1 .
+.Pp
+To prevent such attacks, the use of
+.Dv NI_NAMEREQD
+is recommended when the result of
+.Fn getnameinfo
+is used for access control purposes:
+.Bd -literal -offset indent
+struct sockaddr *sa;
+socklen_t salen;
+char addr[NI_MAXHOST];
+struct addrinfo hints, *res;
+int error;
+
+error = getnameinfo(sa, salen, addr, sizeof(addr),
+    NULL, 0, NI_NAMEREQD);
+if (error == 0) {
+       memset(\*[Am]hints, 0, sizeof(hints));
+       hints.ai_socktype = SOCK_DGRAM; /*dummy*/
+       hints.ai_flags = AI_NUMERICHOST;
+       if (getaddrinfo(addr, "0", \*[Am]hints, \*[Am]res) == 0) {
+               /* malicious PTR record */
+               freeaddrinfo(res);
+               printf("bogus PTR record\en");
+               return -1;
+       }
+       /* addr is FQDN as a result of PTR lookup */
+} else {
+       /* addr is numeric string */
+       error = getnameinfo(sa, salen, addr, sizeof(addr),
+           NULL, 0, NI_NUMERICHOST);
+}
+.Ed
+.Sh BUGS
+The implementation of
+.Fn getnameinfo
+is not thread-safe.
+.\".Pp
+.\".Ox
+.\"intentionally uses a different
+.\".Dv NI_MAXHOST
+.\"value from what
+.\".Tn "RFC 2553"
+.\"suggests, to avoid buffer length handling mistakes.
diff --git a/lib/nbsd_libc/net/getnameinfo.c b/lib/nbsd_libc/net/getnameinfo.c
new file mode 100644 (file)
index 0000000..bd373ae
--- /dev/null
@@ -0,0 +1,595 @@
+/*     $NetBSD: getnameinfo.c,v 1.50 2010/06/29 14:44:19 seanb Exp $   */
+/*     $KAME: getnameinfo.c,v 1.45 2000/09/25 22:43:56 itojun Exp $    */
+
+/*
+ * Copyright (c) 2000 Ben Harris.
+ * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
+ * 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.
+ * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
+ */
+
+/*
+ * Issues to be discussed:
+ * - Thread safe-ness must be checked
+ * - RFC2553 says that we should raise error on short buffer.  X/Open says
+ *   we need to truncate the result.  We obey RFC2553 (and X/Open should be
+ *   modified).  ipngwg rough consensus seems to follow RFC2553.
+ * - What is "local" in NI_FQDN?
+ * - NI_NAMEREQD and NI_NUMERICHOST conflict with each other.
+ * - (KAME extension) always attach textual scopeid (fe80::1%lo0), if
+ *   sin6_scope_id is filled - standardization status?
+ *   XXX breaks backward compat for code that expects no scopeid.
+ *   beware on merge.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getnameinfo.c,v 1.50 2010/06/29 14:44:19 seanb Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <net/if.h>
+#include <net/if_dl.h>
+#include <net/if_ieee1394.h>
+#include <net/if_types.h>
+#include <netatalk/at.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+#include <assert.h>
+#include <limits.h>
+#include <netdb.h>
+#include <resolv.h>
+#include <stddef.h>
+#include <string.h>
+
+#include "servent.h"
+
+#ifdef __weak_alias
+__weak_alias(getnameinfo,_getnameinfo)
+#endif
+
+static const struct afd {
+       int             a_af;
+       socklen_t       a_addrlen;
+       socklen_t       a_socklen;
+       int             a_off;
+} afdl [] = {
+#ifdef INET6
+       {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6),
+               offsetof(struct sockaddr_in6, sin6_addr)},
+#endif
+       {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in),
+               offsetof(struct sockaddr_in, sin_addr)},
+       {0, 0, 0, 0},
+};
+
+struct sockinet {
+       u_char  si_len;
+       u_char  si_family;
+       u_short si_port;
+};
+
+static int getnameinfo_inet __P((const struct sockaddr *, socklen_t, char *,
+    socklen_t, char *, socklen_t, int));
+#ifdef INET6
+static int ip6_parsenumeric __P((const struct sockaddr *, const char *, char *,
+                                socklen_t, int));
+static int ip6_sa2str __P((const struct sockaddr_in6 *, char *, size_t,
+                                int));
+#endif
+static int getnameinfo_atalk __P((const struct sockaddr *, socklen_t, char *,
+    socklen_t, char *, socklen_t, int));
+
+static int getnameinfo_link __P((const struct sockaddr *, socklen_t, char *,
+    socklen_t, char *, socklen_t, int));
+static int hexname __P((const u_int8_t *, size_t, char *, socklen_t));
+
+/*
+ * Top-level getnameinfo() code.  Look at the address family, and pick an
+ * appropriate function to call.
+ */
+int
+getnameinfo(sa, salen, host, hostlen, serv, servlen, flags)
+       const struct sockaddr *sa;
+       socklen_t salen;
+       char *host, *serv;
+       socklen_t hostlen, servlen;
+       int flags;
+{
+
+       switch (sa->sa_family) {
+       case AF_APPLETALK:
+               return getnameinfo_atalk(sa, salen, host, hostlen,
+                   serv, servlen, flags);
+       case AF_INET:
+       case AF_INET6:
+               return getnameinfo_inet(sa, salen, host, hostlen,
+                   serv, servlen, flags);
+       case AF_LINK:
+               return getnameinfo_link(sa, salen, host, hostlen,
+                   serv, servlen, flags);
+       default:
+               return EAI_FAMILY;
+       }
+}
+
+/*
+ * getnameinfo_atalk():
+ * Format an AppleTalk address into a printable format.
+ */
+/* ARGSUSED */
+static int
+getnameinfo_atalk(const struct sockaddr *sa, socklen_t salen,
+    char *host, socklen_t hostlen, char *serv, socklen_t servlen,
+    int flags)
+{
+       char numserv[8];
+       int n, m=0;
+
+       const struct sockaddr_at *sat =
+           (const struct sockaddr_at *)(const void *)sa;
+
+       if (serv != NULL && servlen > 0) {
+               snprintf(numserv, sizeof(numserv), "%u", sat->sat_port);
+               if (strlen(numserv) + 1 > servlen)
+                       return EAI_MEMORY;
+               strlcpy(serv, numserv, servlen);
+       }
+
+        n = snprintf(host, hostlen, "%u.%u",
+           ntohs(sat->sat_addr.s_net), sat->sat_addr.s_node);
+
+       if (n < 0 || (socklen_t)(m+n) >= hostlen)
+               goto errout;
+
+       m += n;
+
+       if (sat->sat_range.r_netrange.nr_phase) {
+               n = snprintf(host+m, hostlen-m, " phase %u",
+                       sat->sat_range.r_netrange.nr_phase);
+
+               if (n < 0 || (socklen_t)(m+n) >= hostlen)
+                       goto errout;
+
+               m += n;
+       }
+       if (sat->sat_range.r_netrange.nr_firstnet) {
+               n = snprintf(host+m, hostlen-m, " range %u - %u",
+                       ntohs(sat->sat_range.r_netrange.nr_firstnet),
+                       ntohs(sat->sat_range.r_netrange.nr_lastnet ));
+
+               if (n < 0 || (socklen_t)(m+n) >= hostlen)
+                       goto errout;
+
+               m += n;
+       }
+
+       return 0;
+
+errout:
+       if (host && hostlen>0)
+               host[m] = '\0'; /* XXX ??? */
+
+       return EAI_MEMORY;
+}
+
+/*
+ * getnameinfo_inet():
+ * Format an IPv4 or IPv6 sockaddr into a printable string.
+ */
+static int
+getnameinfo_inet(sa, salen, host, hostlen, serv, servlen, flags)
+       const struct sockaddr *sa;
+       socklen_t salen;
+       char *host;
+       socklen_t hostlen;
+       char *serv;
+       socklen_t servlen;
+       int flags;
+{
+       const struct afd *afd;
+       struct servent *sp;
+       struct hostent *hp;
+       u_short port;
+       int family, i;
+       const char *addr;
+       u_int32_t v4a;
+       char numserv[512];
+       char numaddr[512];
+
+       /* sa is checked below */
+       /* host may be NULL */
+       /* serv may be NULL */
+
+       if (sa == NULL)
+               return EAI_FAIL;
+
+       family = sa->sa_family;
+       for (i = 0; afdl[i].a_af; i++)
+               if (afdl[i].a_af == family) {
+                       afd = &afdl[i];
+                       goto found;
+               }
+       return EAI_FAMILY;
+
+ found:
+       if (salen != afd->a_socklen)
+               return EAI_FAIL;
+
+       /* network byte order */
+       port = ((const struct sockinet *)(const void *)sa)->si_port;
+       addr = (const char *)(const void *)sa + afd->a_off;
+
+       if (serv == NULL || servlen == 0) {
+               /*
+                * do nothing in this case.
+                * in case you are wondering if "&&" is more correct than
+                * "||" here: rfc2553bis-03 says that serv == NULL OR
+                * servlen == 0 means that the caller does not want the result.
+                */
+       } else {
+               struct servent_data svd;
+               struct servent sv;
+
+               if (flags & NI_NUMERICSERV)
+                       sp = NULL;
+               else {
+                       (void)memset(&svd, 0, sizeof(svd));
+                       sp = getservbyport_r(port,
+                               (flags & NI_DGRAM) ? "udp" : "tcp", &sv, &svd);
+               }
+               if (sp) {
+                       if (strlen(sp->s_name) + 1 > servlen) {
+                               endservent_r(&svd);
+                               return EAI_MEMORY;
+                       }
+                       strlcpy(serv, sp->s_name, servlen);
+                       endservent_r(&svd);
+               } else {
+                       snprintf(numserv, sizeof(numserv), "%u", ntohs(port));
+                       if (strlen(numserv) + 1 > servlen)
+                               return EAI_MEMORY;
+                       strlcpy(serv, numserv, servlen);
+               }
+       }
+
+       switch (sa->sa_family) {
+       case AF_INET:
+               v4a = (u_int32_t)
+                   ntohl(((const struct sockaddr_in *)
+                   (const void *)sa)->sin_addr.s_addr);
+               if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
+                       flags |= NI_NUMERICHOST;
+               v4a >>= IN_CLASSA_NSHIFT;
+               if (v4a == 0)
+                       flags |= NI_NUMERICHOST;
+               break;
+#ifdef INET6
+       case AF_INET6:
+           {
+               const struct sockaddr_in6 *sin6;
+               sin6 = (const struct sockaddr_in6 *)(const void *)sa;
+               switch (sin6->sin6_addr.s6_addr[0]) {
+               case 0x00:
+                       if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
+                               ;
+                       else if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
+                               ;
+                       else
+                               flags |= NI_NUMERICHOST;
+                       break;
+               default:
+                       if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
+                               flags |= NI_NUMERICHOST;
+                       }
+                       else if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
+                               flags |= NI_NUMERICHOST;
+                       break;
+               }
+           }
+               break;
+#endif
+       }
+       if (host == NULL || hostlen == 0) {
+               /*
+                * do nothing in this case.
+                * in case you are wondering if "&&" is more correct than
+                * "||" here: rfc2553bis-03 says that host == NULL or
+                * hostlen == 0 means that the caller does not want the result.
+                */
+       } else if (flags & NI_NUMERICHOST) {
+               size_t numaddrlen;
+
+               /* NUMERICHOST and NAMEREQD conflicts with each other */
+               if (flags & NI_NAMEREQD)
+                       return EAI_NONAME;
+
+               switch(afd->a_af) {
+#ifdef INET6
+               case AF_INET6:
+               {
+                       int error;
+
+                       if ((error = ip6_parsenumeric(sa, addr, host,
+                                                     hostlen, flags)) != 0)
+                               return(error);
+                       break;
+               }
+#endif
+               default:
+                       if (inet_ntop(afd->a_af, addr, numaddr, sizeof(numaddr))
+                           == NULL)
+                               return EAI_SYSTEM;
+                       numaddrlen = strlen(numaddr);
+                       if (numaddrlen + 1 > hostlen) /* don't forget terminator */
+                               return EAI_MEMORY;
+                       strlcpy(host, numaddr, hostlen);
+                       break;
+               }
+       } else {
+               hp = gethostbyaddr(addr, afd->a_addrlen, afd->a_af);
+
+               if (hp) {
+#if 0
+                       /*
+                        * commented out, since "for local host" is not
+                        * implemented here - see RFC2553 p30
+                        */
+                       if (flags & NI_NOFQDN) {
+                               char *p;
+                               p = strchr(hp->h_name, '.');
+                               if (p)
+                                       *p = '\0';
+                       }
+#endif
+                       if (strlen(hp->h_name) + 1 > hostlen) {
+                               return EAI_MEMORY;
+                       }
+                       strlcpy(host, hp->h_name, hostlen);
+               } else {
+                       if (flags & NI_NAMEREQD)
+                               return EAI_NONAME;
+                       switch(afd->a_af) {
+#ifdef INET6
+                       case AF_INET6:
+                       {
+                               int error;
+
+                               if ((error = ip6_parsenumeric(sa, addr, host,
+                                                             hostlen,
+                                                             flags)) != 0)
+                                       return(error);
+                               break;
+                       }
+#endif
+                       default:
+                               if (inet_ntop(afd->a_af, addr, host,
+                                   hostlen) == NULL)
+                                       return EAI_SYSTEM;
+                               break;
+                       }
+               }
+       }
+       return(0);
+}
+
+#ifdef INET6
+static int
+ip6_parsenumeric(sa, addr, host, hostlen, flags)
+       const struct sockaddr *sa;
+       const char *addr;
+       char *host;
+       socklen_t hostlen;
+       int flags;
+{
+       size_t numaddrlen;
+       char numaddr[512];
+
+       _DIAGASSERT(sa != NULL);
+       _DIAGASSERT(addr != NULL);
+       _DIAGASSERT(host != NULL);
+
+       if (inet_ntop(AF_INET6, addr, numaddr, sizeof(numaddr)) == NULL)
+               return EAI_SYSTEM;
+
+       numaddrlen = strlen(numaddr);
+       if (numaddrlen + 1 > hostlen) /* don't forget terminator */
+               return EAI_OVERFLOW;
+       strlcpy(host, numaddr, hostlen);
+
+       if (((const struct sockaddr_in6 *)(const void *)sa)->sin6_scope_id) {
+               char zonebuf[MAXHOSTNAMELEN];
+               int zonelen;
+
+               zonelen = ip6_sa2str(
+                   (const struct sockaddr_in6 *)(const void *)sa,
+                   zonebuf, sizeof(zonebuf), flags);
+               if (zonelen < 0)
+                       return EAI_OVERFLOW;
+               if ((size_t) zonelen + 1 + numaddrlen + 1 > hostlen)
+                       return EAI_OVERFLOW;
+               /* construct <numeric-addr><delim><zoneid> */
+               memcpy(host + numaddrlen + 1, zonebuf,
+                   (size_t)zonelen);
+               host[numaddrlen] = SCOPE_DELIMITER;
+               host[numaddrlen + 1 + zonelen] = '\0';
+       }
+
+       return 0;
+}
+
+/* ARGSUSED */
+static int
+ip6_sa2str(sa6, buf, bufsiz, flags)
+       const struct sockaddr_in6 *sa6;
+       char *buf;
+       size_t bufsiz;
+       int flags;
+{
+       unsigned int ifindex;
+       const struct in6_addr *a6;
+       int n;
+
+       _DIAGASSERT(sa6 != NULL);
+       _DIAGASSERT(buf != NULL);
+
+       ifindex = (unsigned int)sa6->sin6_scope_id;
+       a6 = &sa6->sin6_addr;
+
+#ifdef NI_NUMERICSCOPE
+       if ((flags & NI_NUMERICSCOPE) != 0) {
+               n = snprintf(buf, bufsiz, "%u", sa6->sin6_scope_id);
+               if (n < 0 || (size_t)n >= bufsiz)
+                       return -1;
+               else
+                       return n;
+       }
+#endif
+
+       /* if_indextoname() does not take buffer size.  not a good api... */
+       if ((IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) &&
+           bufsiz >= IF_NAMESIZE) {
+               char *p = if_indextoname(ifindex, buf);
+               if (p) {
+                       return(strlen(p));
+               }
+       }
+
+       /* last resort */
+       n = snprintf(buf, bufsiz, "%u", sa6->sin6_scope_id);
+       if (n < 0 || (size_t) n >= bufsiz)
+               return -1;
+       else
+               return n;
+}
+#endif /* INET6 */
+
+
+/*
+ * getnameinfo_link():
+ * Format a link-layer address into a printable format, paying attention to
+ * the interface type.
+ */
+/* ARGSUSED */
+static int
+getnameinfo_link(const struct sockaddr *sa, socklen_t salen,
+    char *host, socklen_t hostlen, char *serv, socklen_t servlen,
+    int flags)
+{
+       const struct sockaddr_dl *sdl =
+           (const struct sockaddr_dl *)(const void *)sa;
+       const struct ieee1394_hwaddr *iha;
+       int n;
+
+       if (serv != NULL && servlen > 0)
+               *serv = '\0';
+
+       if (sdl->sdl_nlen == 0 && sdl->sdl_alen == 0 && sdl->sdl_slen == 0) {
+               n = snprintf(host, hostlen, "link#%u", sdl->sdl_index);
+               if (n < 0 || (socklen_t) n > hostlen) {
+                       *host = '\0';
+                       return EAI_MEMORY;
+               }
+               return 0;
+       }
+
+       switch (sdl->sdl_type) {
+#ifdef IFT_ECONET
+       case IFT_ECONET:
+               if (sdl->sdl_alen < 2)
+                       return EAI_FAMILY;
+               if (CLLADDR(sdl)[1] == 0)
+                       n = snprintf(host, hostlen, "%u", CLLADDR(sdl)[0]);
+               else
+                       n = snprintf(host, hostlen, "%u.%u",
+                           CLLADDR(sdl)[1], CLLADDR(sdl)[0]);
+               if (n < 0 || (socklen_t) n >= hostlen) {
+                       *host = '\0';
+                       return EAI_MEMORY;
+               } else
+                       return 0;
+#endif
+       case IFT_IEEE1394:
+               if (sdl->sdl_alen < sizeof(iha->iha_uid))
+                       return EAI_FAMILY;
+               iha =
+                   (const struct ieee1394_hwaddr *)(const void *)CLLADDR(sdl);
+               return hexname(iha->iha_uid, sizeof(iha->iha_uid),
+                   host, hostlen);
+       /*
+        * The following have zero-length addresses.
+        * IFT_ATM      (net/if_atmsubr.c)
+        * IFT_FAITH    (net/if_faith.c)
+        * IFT_GIF      (net/if_gif.c)
+        * IFT_LOOP     (net/if_loop.c)
+        * IFT_PPP      (net/if_ppp.c, net/if_spppsubr.c)
+        * IFT_SLIP     (net/if_sl.c, net/if_strip.c)
+        * IFT_STF      (net/if_stf.c)
+        * IFT_L2VLAN   (net/if_vlan.c)
+        * IFT_PROPVIRTUAL (net/if_bridge.h>
+        */
+       /*
+        * The following use IPv4 addresses as link-layer addresses:
+        * IFT_OTHER    (net/if_gre.c)
+        */
+       case IFT_ARCNET: /* default below is believed correct for all these. */
+       case IFT_ETHER:
+       case IFT_FDDI:
+       case IFT_HIPPI:
+       case IFT_ISO88025:
+       default:
+               return hexname((const u_int8_t *)CLLADDR(sdl),
+                   (size_t)sdl->sdl_alen, host, hostlen);
+       }
+}
+
+static int
+hexname(cp, len, host, hostlen)
+       const u_int8_t *cp;
+       char *host;
+       size_t len;
+       socklen_t hostlen;
+{
+       int n;
+       size_t i;
+       char *outp = host;
+
+       *outp = '\0';
+       for (i = 0; i < len; i++) {
+               n = snprintf(outp, hostlen, "%s%02x",
+                   i ? ":" : "", cp[i]);
+               if (n < 0 || (socklen_t) n >= hostlen) {
+                       *host = '\0';
+                       return EAI_MEMORY;
+               }
+               outp += n;
+               hostlen -= n;
+       }
+       return 0;
+}
diff --git a/lib/nbsd_libc/net/getnetent.3 b/lib/nbsd_libc/net/getnetent.3
new file mode 100644 (file)
index 0000000..622211e
--- /dev/null
@@ -0,0 +1,152 @@
+.\"    $NetBSD: getnetent.3,v 1.13 2004/05/08 18:52:15 kleink Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getnetent.3        8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 8, 2004
+.Dt GETNETENT 3
+.Os
+.Sh NAME
+.Nm getnetent ,
+.Nm getnetbyaddr ,
+.Nm getnetbyname ,
+.Nm setnetent ,
+.Nm endnetent
+.Nd get network entry
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In netdb.h
+.Ft struct netent *
+.Fn getnetent
+.Ft struct netent *
+.Fn getnetbyname "const char *name"
+.Ft struct netent *
+.Fn getnetbyaddr "uint32_t net" "int type"
+.Fn setnetent "int stayopen"
+.Fn endnetent
+.Sh DESCRIPTION
+The
+.Fn getnetent ,
+.Fn getnetbyname ,
+and
+.Fn getnetbyaddr
+functions
+each return a pointer to an object with the
+following structure
+containing the broken-out
+fields of a line in the network data base as described in
+.Xr networks 5 .
+.Bd -literal -offset indent
+struct netent {
+       char            *n_name;        /* official name of net */
+       char            **n_aliases;    /* alias list */
+       int             n_addrtype;     /* net number type */
+       uint32_t        n_net;          /* net number */
+};
+.Ed
+.Pp
+The members of this structure are:
+.Bl -tag -width n_addrtype
+.It Fa n_name
+The official name of the network.
+.It Fa n_aliases
+A zero terminated list of alternative names for the network.
+.It Fa n_addrtype
+The type of the network number returned; currently only AF_INET.
+.It Fa n_net
+The network number.  Network numbers are returned in machine byte
+order.
+.El
+.Pp
+The
+.Fn getnetent
+function
+reads the next line of the file, opening the file if necessary.
+.Pp
+The
+.Fn setnetent
+function
+opens and rewinds the file.  If the
+.Fa stayopen
+flag is non-zero,
+the net data base will not be closed after each call to
+.Fn getnetbyname
+or
+.Fn getnetbyaddr .
+.Pp
+The
+.Fn endnetent
+function
+closes the file.
+.Pp
+The
+.Fn getnetbyname
+function
+and
+.Fn getnetbyaddr
+sequentially search from the beginning
+of the file until a matching
+net name or
+net address and type is found,
+or until
+.Dv EOF
+is encountered.
+Network numbers are supplied in host order.
+.Sh FILES
+.Bl -tag -width /etc/networks -compact
+.It Pa /etc/networks
+.El
+.Sh DIAGNOSTICS
+Null pointer
+(0) returned on
+.Dv EOF
+or error.
+.Sh SEE ALSO
+.Xr networks 5 ,
+.Xr nsswitch.conf 5
+.Sh HISTORY
+The
+.Fn getnetent ,
+.Fn getnetbyaddr ,
+.Fn getnetbyname ,
+.Fn setnetent ,
+and
+.Fn endnetent
+functions appeared in
+.Bx 4.2 .
+.Sh BUGS
+The data space used by
+these functions is static; if future use requires the data, it should be
+copied before any subsequent calls to these functions overwrite it.
+Only Internet network
+numbers are currently understood.
+Expecting network numbers to fit
+in no more than 32 bits is probably
+naive.
diff --git a/lib/nbsd_libc/net/getnetent.c b/lib/nbsd_libc/net/getnetent.c
new file mode 100644 (file)
index 0000000..f685f32
--- /dev/null
@@ -0,0 +1,170 @@
+/*     $NetBSD: getnetent.c,v 1.18 2007/01/27 22:27:35 christos Exp $  */
+
+/*
+ * 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.
+ * 3. 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.
+ *
+ * Portions Copyright (c) 1993 Carlos Leandro and Rui Salgueiro
+ *    Dep. Matematica Universidade de Coimbra, Portugal, Europe
+ *
+ * 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.
+ *
+ * from getnetent.c   1.1 (Coimbra) 93/06/02
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getnetent.c        8.1 (Berkeley) 6/4/93";
+static char rcsid[] = "Id: getnetent.c,v 8.4 1997/06/01 20:34:37 vixie Exp ";
+#else
+__RCSID("$NetBSD: getnetent.c,v 1.18 2007/01/27 22:27:35 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <stdio.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(endnetent,_endnetent)
+__weak_alias(getnetent,_getnetent)
+__weak_alias(setnetent,_setnetent)
+#endif
+
+#define        MAXALIASES      35
+
+static FILE *netf;
+static char line[BUFSIZ+1];
+static struct netent net;
+static char *net_aliases[MAXALIASES];
+int _net_stayopen;
+
+static void __setnetent __P((int));
+static void __endnetent __P((void));
+
+void
+setnetent(stayopen)
+       int stayopen;
+{
+
+       sethostent(stayopen);
+       __setnetent(stayopen);
+}
+
+void
+endnetent()
+{
+
+       endhostent();
+       __endnetent();
+}
+
+static void
+__setnetent(f)
+       int f;
+{
+
+       if (netf == NULL)
+               netf = fopen(_PATH_NETWORKS, "r" );
+       else
+               rewind(netf);
+       _net_stayopen |= f;
+}
+
+static void
+__endnetent()
+{
+
+       if (netf) {
+               fclose(netf);
+               netf = NULL;
+       }
+       _net_stayopen = 0;
+}
+
+struct netent *
+getnetent()
+{
+       char *p;
+       register char *cp, **q;
+
+       if (netf == NULL && (netf = fopen(_PATH_NETWORKS, "r" )) == NULL)
+               return (NULL);
+#if (defined(__sparc__) && defined(_LP64)) ||          \
+    defined(__alpha__) ||                              \
+    (defined(__i386__) && defined(_LP64)) ||           \
+    (defined(__sh__) && defined(_LP64))
+       net.__n_pad0 = 0;
+#endif
+again:
+       p = fgets(line, sizeof line, netf);
+       if (p == NULL)
+               return (NULL);
+       if (*p == '#')
+               goto again;
+       cp = strpbrk(p, "#\n");
+       if (cp == NULL)
+               goto again;
+       *cp = '\0';
+       net.n_name = p;
+       cp = strpbrk(p, " \t");
+       if (cp == NULL)
+               goto again;
+       *cp++ = '\0';
+       while (*cp == ' ' || *cp == '\t')
+               cp++;
+       p = strpbrk(cp, " \t");
+       if (p != NULL)
+               *p++ = '\0';
+       net.n_net = inet_network(cp);
+       net.n_addrtype = AF_INET;
+       q = net.n_aliases = net_aliases;
+       if (p != NULL) {
+               cp = p;
+               while (cp && *cp) {
+                       if (*cp == ' ' || *cp == '\t') {
+                               cp++;
+                               continue;
+                       }
+                       if (q < &net_aliases[MAXALIASES - 1])
+                               *q++ = cp;
+                       cp = strpbrk(cp, " \t");
+                       if (cp != NULL)
+                               *cp++ = '\0';
+               }
+       }
+       *q = NULL;
+       return (&net);
+}
diff --git a/lib/nbsd_libc/net/getnetnamadr.c b/lib/nbsd_libc/net/getnetnamadr.c
new file mode 100644 (file)
index 0000000..ef2e48f
--- /dev/null
@@ -0,0 +1,647 @@
+/*     $NetBSD: getnetnamadr.c,v 1.41 2008/05/18 22:36:15 lukem Exp $  */
+
+/* Copyright (c) 1993 Carlos Leandro and Rui Salgueiro
+ *     Dep. Matematica Universidade de Coimbra, Portugal, Europe
+ *
+ * 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.
+ */
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getnetbyaddr.c     8.1 (Berkeley) 6/4/93";
+static char sccsid_[] = "from getnetnamadr.c   1.4 (Coimbra) 93/06/03";
+static char rcsid[] = "Id: getnetnamadr.c,v 8.8 1997/06/01 20:34:37 vixie Exp ";
+#else
+__RCSID("$NetBSD: getnetnamadr.c,v 1.41 2008/05/18 22:36:15 lukem Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <netdb.h>
+#include <nsswitch.h>
+#include <resolv.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef YP
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+#endif
+
+#ifdef __weak_alias
+__weak_alias(getnetbyaddr,_getnetbyaddr)
+__weak_alias(getnetbyname,_getnetbyname)
+#endif
+
+extern int _net_stayopen;
+
+#define BYADDR 0
+#define BYNAME 1
+#define        MAXALIASES      35
+
+#define        MAXPACKET       (64*1024)
+
+typedef union {
+       HEADER  hdr;
+       u_char  buf[MAXPACKET];
+} querybuf;
+
+typedef union {
+       long    al;
+       char    ac;
+} align;
+
+#ifdef YP
+static char *__ypdomain;
+static char *__ypcurrent;
+static int   __ypcurrentlen;
+#endif
+
+static struct netent net_entry;
+static char *net_aliases[MAXALIASES];
+
+static int             parse_reversed_addr(const char *, in_addr_t *);
+static struct netent   *getnetanswer(querybuf *, int, int);
+static int             _files_getnetbyaddr(void *, void *, va_list);
+static int             _files_getnetbyname(void *, void *, va_list);
+static int             _dns_getnetbyaddr(void *, void *, va_list);
+static int             _dns_getnetbyname(void *, void *, va_list);
+#ifdef YP
+static int             _yp_getnetbyaddr(void *, void *, va_list);
+static int             _yp_getnetbyname(void *, void *, va_list);
+static struct netent   *_ypnetent(char *);
+#endif
+
+/*
+ * parse_reversed_addr --
+ *     parse str, which should be of the form 'd.c.b.a.IN-ADDR.ARPA'
+ *     (a PTR as per RFC 1101) and convert into an in_addr_t of the
+ *     address 'a.b.c.d'.
+ *     returns 0 on success (storing in *result), or -1 on error.
+ */
+static int
+parse_reversed_addr(const char *str, in_addr_t *result)
+{
+       unsigned long   octet[4];
+       const char      *sp;
+       char            *ep;
+       int             octidx;
+
+       sp = str;
+                               /* find the four octets 'd.b.c.a.' */
+       for (octidx = 0; octidx < 4; octidx++) {
+                                       /* ensure it's a number */
+               if (!isdigit((unsigned char)*sp))
+                       return -1;
+               octet[octidx] = strtoul(sp, &ep, 10);
+                                       /* with a trailing '.' */
+               if (*ep != '.')
+                       return -1;
+                                       /* and is 0 <= octet <= 255 */
+               if (octet[octidx] > 255)
+                       return -1;
+               sp = ep + 1;
+       }
+                               /* ensure trailer is correct */
+       if (strcasecmp(sp, "IN-ADDR.ARPA") != 0)
+               return -1;
+       *result = 0;
+                               /* build result from octets in reverse */
+       for (octidx = 3; octidx >= 0; octidx--) {
+               *result <<= 8;
+               *result |= (octet[octidx] & 0xff);
+       }
+       return 0;
+}
+
+static struct netent *
+getnetanswer(querybuf *answer, int anslen, int net_i)
+{
+       static char     n_name[MAXDNAME];
+       static char     netbuf[PACKETSZ];
+
+       HEADER          *hp;
+       u_char          *cp;
+       int             n;
+       u_char          *eom;
+       int             type, class, ancount, qdcount, haveanswer;
+       char            *in, *bp, **ap, *ep;
+
+       _DIAGASSERT(answer != NULL);
+
+       /*
+        * find first satisfactory answer
+        *
+        *      answer --> +------------+  ( MESSAGE )
+        *                 |   Header   |
+        *                 +------------+
+        *                 |  Question  | the question for the name server
+        *                 +------------+
+        *                 |   Answer   | RRs answering the question
+        *                 +------------+
+        *                 | Authority  | RRs pointing toward an authority
+        *                 | Additional | RRs holding additional information
+        *                 +------------+
+        */
+       eom = answer->buf + anslen;
+       hp = &answer->hdr;
+       ancount = ntohs(hp->ancount); /* #/records in the answer section */
+       qdcount = ntohs(hp->qdcount); /* #/entries in the question section */
+       bp = netbuf;
+       ep = netbuf + sizeof(netbuf);
+       cp = answer->buf + HFIXEDSZ;
+       if (!qdcount) {
+               if (hp->aa)
+                       h_errno = HOST_NOT_FOUND;
+               else
+                       h_errno = TRY_AGAIN;
+               return NULL;
+       }
+       while (qdcount-- > 0) {
+               n = __dn_skipname(cp, eom);
+               if (n < 0 || (cp + n + QFIXEDSZ) > eom) {
+                       h_errno = NO_RECOVERY;
+                       return(NULL);
+               }
+               cp += n + QFIXEDSZ;
+       }
+       ap = net_aliases;
+       *ap = NULL;
+       net_entry.n_aliases = net_aliases;
+       haveanswer = 0;
+       n_name[0] = '\0';
+       while (--ancount >= 0 && cp < eom) {
+               n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
+               if ((n < 0) || !res_dnok(bp))
+                       break;
+               cp += n;
+               (void)strlcpy(n_name, bp, sizeof(n_name));
+               GETSHORT(type, cp);
+               GETSHORT(class, cp);
+               cp += INT32SZ;          /* TTL */
+               GETSHORT(n, cp);
+               if (class == C_IN && type == T_PTR) {
+                       n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
+                       if ((n < 0) || !res_hnok(bp)) {
+                               cp += n;
+                               return NULL;
+                       }
+                       cp += n;
+                       *ap++ = bp;
+                       bp += strlen(bp) + 1;
+                       net_entry.n_addrtype =
+                               (class == C_IN) ? AF_INET : AF_UNSPEC;
+                       haveanswer++;
+               }
+       }
+       if (haveanswer) {
+               *ap = NULL;
+               switch (net_i) {
+               case BYADDR:
+                       net_entry.n_name = *net_entry.n_aliases;
+                       net_entry.n_net = 0L;
+                       break;
+               case BYNAME:
+                       ap = net_entry.n_aliases;
+               next_alias:
+                       in = *ap++;
+                       if (in == NULL) {
+                               h_errno = HOST_NOT_FOUND;
+                               return NULL;
+                       }
+                       net_entry.n_name = n_name;
+                       if (parse_reversed_addr(in, &net_entry.n_net) == -1)
+                               goto next_alias;
+                       break;
+               }
+               net_entry.n_aliases++;
+#if (defined(__sparc__) && defined(_LP64)) ||          \
+    defined(__alpha__) ||                              \
+    (defined(__i386__) && defined(_LP64)) ||           \
+    (defined(__sh__) && defined(_LP64))
+               net_entry.__n_pad0 = 0;
+#endif
+               return &net_entry;
+       }
+       h_errno = TRY_AGAIN;
+       return NULL;
+}
+
+/*ARGSUSED*/
+static int
+_files_getnetbyaddr(void *cbrv, void *cbdata, va_list ap)
+{
+       struct netent   **retval = va_arg(ap, struct netent **);
+       uint32_t          net    = va_arg(ap, uint32_t);
+       int               type   = va_arg(ap, int);
+
+       struct netent    *np;
+
+       setnetent(_net_stayopen);
+       while ((np = getnetent()) != NULL)
+               if (np->n_addrtype == type && np->n_net == net)
+                       break;
+       if (!_net_stayopen)
+               endnetent();
+
+       if (np != NULL) {
+               *retval = np;
+               return NS_SUCCESS;
+       } else {
+               h_errno = HOST_NOT_FOUND;
+               return NS_NOTFOUND;
+       }
+}
+
+/*ARGSUSED*/
+static int
+_dns_getnetbyaddr(void *cbrv, void *cbdata, va_list ap)
+{
+       struct netent   **retval = va_arg(ap, struct netent **);
+       uint32_t          net    = va_arg(ap, uint32_t);
+       int               type   = va_arg(ap, int);
+
+       unsigned int     netbr[4];
+       int              nn, anslen;
+       querybuf        *buf;
+       char             qbuf[MAXDNAME];
+       uint32_t         net2;
+       struct netent   *np;
+       res_state        res;
+
+       if (type != AF_INET)
+               return NS_UNAVAIL;
+
+       for (nn = 4, net2 = net; net2; net2 >>= 8)
+               netbr[--nn] = (unsigned int)(net2 & 0xff);
+       switch (nn) {
+       default:
+               return NS_UNAVAIL;
+       case 3:         /* Class A */
+               snprintf(qbuf, sizeof(qbuf), "0.0.0.%u.in-addr.arpa", netbr[3]);
+               break;
+       case 2:         /* Class B */
+               snprintf(qbuf, sizeof(qbuf), "0.0.%u.%u.in-addr.arpa",
+                   netbr[3], netbr[2]);
+               break;
+       case 1:         /* Class C */
+               snprintf(qbuf, sizeof(qbuf), "0.%u.%u.%u.in-addr.arpa",
+                   netbr[3], netbr[2], netbr[1]);
+               break;
+       case 0:         /* Class D - E */
+               snprintf(qbuf, sizeof(qbuf), "%u.%u.%u.%u.in-addr.arpa",
+                   netbr[3], netbr[2], netbr[1], netbr[0]);
+               break;
+       }
+       buf = malloc(sizeof(*buf));
+       if (buf == NULL) {
+               h_errno = NETDB_INTERNAL;
+               return NS_NOTFOUND;
+       }
+       res = __res_get_state();
+       if (res == NULL) {
+               free(buf);
+               return NS_NOTFOUND;
+       }
+       anslen = res_nquery(res, qbuf, C_IN, T_PTR, buf->buf, sizeof(buf->buf));
+       if (anslen < 0) {
+               free(buf);
+#ifdef DEBUG
+               if (res->options & RES_DEBUG)
+                       printf("res_query failed\n");
+#endif
+               __res_put_state(res);
+               return NS_NOTFOUND;
+       }
+       __res_put_state(res);
+       np = getnetanswer(buf, anslen, BYADDR);
+       free(buf);
+       if (np) {
+               /* maybe net should be unsigned? */
+               uint32_t u_net = net;
+
+               /* Strip trailing zeros */
+               while ((u_net & 0xff) == 0 && u_net != 0)
+                       u_net >>= 8;
+               np->n_net = u_net;
+       }
+
+       if (np != NULL) {
+               *retval = np;
+               return NS_SUCCESS;
+       } else {
+               h_errno = HOST_NOT_FOUND;
+               return NS_NOTFOUND;
+       }
+}
+
+struct netent *
+getnetbyaddr(uint32_t net, int net_type)
+{
+       int              rv;
+       struct netent   *retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getnetbyaddr, NULL)
+               { NSSRC_DNS, _dns_getnetbyaddr, NULL }, /* force -DHESIOD */
+               NS_NIS_CB(_yp_getnetbyaddr, NULL)
+               NS_NULL_CB
+       };
+
+       retval = NULL;
+       h_errno = NETDB_INTERNAL;
+       rv = nsdispatch(NULL, dtab, NSDB_NETWORKS, "getnetbyaddr",
+           __nsdefaultsrc, &retval, net, net_type);
+       if (rv == NS_SUCCESS) {
+               h_errno = NETDB_SUCCESS;
+               return retval;
+       }
+       return NULL;
+}
+
+/*ARGSUSED*/
+static int
+_files_getnetbyname(void *cbrv, void *cbdata, va_list ap)
+{
+       struct netent   **retval = va_arg(ap, struct netent **);
+       const char       *name   = va_arg(ap, const char *);
+
+       struct netent    *np;
+       char            **cp;
+
+       setnetent(_net_stayopen);
+       while ((np = getnetent()) != NULL) {
+               if (strcasecmp(np->n_name, name) == 0)
+                       break;
+               for (cp = np->n_aliases; *cp != 0; cp++)
+                       if (strcasecmp(*cp, name) == 0)
+                               goto found;
+       }
+found:
+       if (!_net_stayopen)
+               endnetent();
+
+       if (np != NULL) {
+               *retval = np;
+               return NS_SUCCESS;
+       } else {
+               h_errno = HOST_NOT_FOUND;
+               return NS_NOTFOUND;
+       }
+}
+
+/*ARGSUSED*/
+static int
+_dns_getnetbyname(void *cbrv, void *cbdata, va_list ap)
+{
+       struct netent   **retval = va_arg(ap, struct netent **);
+       const char       *name   = va_arg(ap, const char *);
+
+       int              anslen;
+       querybuf        *buf;
+       char             qbuf[MAXDNAME];
+       struct netent   *np;
+       res_state        res;
+
+       strlcpy(&qbuf[0], name, sizeof(qbuf));
+       buf = malloc(sizeof(*buf));
+       if (buf == NULL) {
+               h_errno = NETDB_INTERNAL;
+               return NS_NOTFOUND;
+       }
+       res = __res_get_state();
+       if (res == NULL) {
+               free(buf);
+               return NS_NOTFOUND;
+       }
+       anslen = res_nsearch(res, qbuf, C_IN, T_PTR, buf->buf,
+           sizeof(buf->buf));
+       if (anslen < 0) {
+               free(buf);
+#ifdef DEBUG
+               if (res->options & RES_DEBUG)
+                       printf("res_search failed\n");
+#endif
+               __res_put_state(res);
+               return NS_NOTFOUND;
+       }
+       __res_put_state(res);
+       np = getnetanswer(buf, anslen, BYNAME);
+       free(buf);
+
+       if (np != NULL) {
+               *retval = np;
+               return NS_SUCCESS;
+       } else {
+               h_errno = HOST_NOT_FOUND;
+               return NS_NOTFOUND;
+       }
+}
+
+struct netent *
+getnetbyname(const char *name)
+{
+       int              rv;
+       struct netent   *retval;
+
+       static const ns_dtab dtab[] = {
+               NS_FILES_CB(_files_getnetbyname, NULL)
+               { NSSRC_DNS, _dns_getnetbyname, NULL }, /* force -DHESIOD */
+               NS_NIS_CB(_yp_getnetbyname, NULL)
+               NS_NULL_CB
+       };
+
+       _DIAGASSERT(name != NULL);
+
+       retval = NULL;
+       h_errno = NETDB_INTERNAL;
+       rv = nsdispatch(NULL, dtab, NSDB_NETWORKS, "getnetbyname",
+           __nsdefaultsrc, &retval, name);
+       if (rv == NS_SUCCESS) {
+               h_errno = NETDB_SUCCESS;
+               return retval;
+       }
+       return NULL;
+}
+
+#ifdef YP
+/*ARGSUSED*/
+static int
+_yp_getnetbyaddr(void *cbrv, void *cb_data, va_list ap)
+{
+       struct netent   **retval = va_arg(ap, struct netent **);
+       uint32_t          net    = va_arg(ap, uint32_t);
+       int               type   = va_arg(ap, int);
+
+       struct netent   *np;
+       char             qbuf[MAXDNAME];
+       unsigned int     netbr[4];
+       uint32_t         net2;
+       int              r;
+
+       if (type != AF_INET)
+               return NS_UNAVAIL;
+
+       if (!__ypdomain) {
+               if (_yp_check(&__ypdomain) == 0)
+                       return NS_UNAVAIL;
+       }
+       np = NULL;
+       if (__ypcurrent)
+               free(__ypcurrent);
+       __ypcurrent = NULL;
+       for (r = 4, net2 = net; net2; net2 >>= 8)
+               netbr[--r] = (unsigned int)(net2 & 0xff);
+       switch (r) {
+       default:
+               return NS_UNAVAIL;
+       case 3:         /* Class A */
+               snprintf(qbuf, sizeof(qbuf), "%u", netbr[3]);
+               break;
+       case 2:         /* Class B */
+               snprintf(qbuf, sizeof(qbuf), "%u.%u", netbr[2], netbr[3]);
+               break;
+       case 1:         /* Class C */
+               snprintf(qbuf, sizeof(qbuf), "%u.%u.%u", netbr[1], netbr[2],
+                   netbr[3]);
+               break;
+       case 0:         /* Class D - E */
+               snprintf(qbuf, sizeof(qbuf), "%u.%u.%u.%u", netbr[0], netbr[1],
+                   netbr[2], netbr[3]);
+               break;
+       }
+       r = yp_match(__ypdomain, "networks.byaddr", qbuf, (int)strlen(qbuf),
+           &__ypcurrent, &__ypcurrentlen);
+       if (r == 0)
+               np = _ypnetent(__ypcurrent);
+
+       if (np != NULL) {
+               *retval = np;
+               return NS_SUCCESS;
+       } else {
+               h_errno = HOST_NOT_FOUND;
+               return NS_NOTFOUND;
+       }
+}
+
+/*ARGSUSED*/
+static int
+_yp_getnetbyname(void *cbrv, void *cbdata, va_list ap)
+{
+       struct netent   **retval = va_arg(ap, struct netent **);
+       const char       *name   = va_arg(ap, const char *);
+
+       struct netent   *np;
+       int              r;
+
+       if (!__ypdomain) {
+               if (_yp_check(&__ypdomain) == 0)
+                       return NS_UNAVAIL;
+       }
+       np = NULL;
+       if (__ypcurrent)
+               free(__ypcurrent);
+       __ypcurrent = NULL;
+       r = yp_match(__ypdomain, "networks.byname", name, (int)strlen(name),
+           &__ypcurrent, &__ypcurrentlen);
+       if (r == 0)
+               np = _ypnetent(__ypcurrent);
+
+       if (np != NULL) {
+               *retval = np;
+               return NS_SUCCESS;
+       } else {
+               h_errno = HOST_NOT_FOUND;
+               return NS_NOTFOUND;
+       }
+}
+
+static struct netent *
+_ypnetent(char *line)
+{
+       char *cp, *p, **q;
+
+       _DIAGASSERT(line != NULL);
+
+       net_entry.n_name = line;
+       cp = strpbrk(line, " \t");
+       if (cp == NULL)
+               return NULL;
+       *cp++ = '\0';
+       while (*cp == ' ' || *cp == '\t')
+               cp++;
+       p = strpbrk(cp, " \t");
+       if (p != NULL)
+               *p++ = '\0';
+       net_entry.n_net = inet_network(cp);
+#if (defined(__sparc__) && defined(_LP64)) ||          \
+    defined(__alpha__) ||                              \
+    (defined(__i386__) && defined(_LP64)) ||           \
+    (defined(__sh__) && defined(_LP64))
+       net_entry.__n_pad0 = 0;
+#endif
+       net_entry.n_addrtype = AF_INET;
+       q = net_entry.n_aliases = net_aliases;
+       if (p != NULL)  {
+               cp = p;
+               while (cp && *cp) {
+                       if (*cp == ' ' || *cp == '\t') {
+                               cp++;
+                               continue;
+                       }
+                       if (q < &net_aliases[MAXALIASES - 1])
+                               *q++ = cp;
+                       cp = strpbrk(cp, " \t");
+                       if (cp != NULL)
+                               *cp++ = '\0';
+               }
+       }
+       *q = NULL;
+
+       return &net_entry;
+}
+#endif
diff --git a/lib/nbsd_libc/net/getpeereid.3 b/lib/nbsd_libc/net/getpeereid.3
new file mode 100644 (file)
index 0000000..77df2b3
--- /dev/null
@@ -0,0 +1,142 @@
+.\"
+.\" Copyright (c) 2001 Dima Dorfman.
+.\" 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.
+.\"
+.\" $FreeBSD: src/lib/libc/gen/getpeereid.3,v 1.6 2002/12/18 10:13:54 ru Exp $
+.\"
+.\" $NetBSD: getpeereid.3,v 1.2 2008/01/29 13:55:27 abs Exp $
+.\"
+.Dd August 8, 2007
+.Dt GETPEEREID 3
+.Os
+.Sh NAME
+.Nm getpeereid
+.Nd get the effective credentials of a UNIX-domain peer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In unistd.h
+.Ft int
+.Fn getpeereid "int s" "uid_t *euid" "gid_t *egid"
+.Sh DESCRIPTION
+The
+.Fn getpeereid
+function returns the effective user and group IDs of the
+peer connected to a
+.Ux Ns -domain
+socket.
+The argument
+.Fa s
+must be a
+.Ux Ns -domain
+socket
+.Pq Xr unix 4
+of type
+.Dv SOCK_STREAM
+on which either
+.Xr connect 2
+has been called, or one returned from
+.Xr accept 2
+after
+.Xr bind 2
+and
+.Xr listen 2
+have been called.
+If non-NULL, the effective used ID is placed in
+.Fa euid ,
+and the effective group ID in
+.Fa egid .
+.Pp
+The credentials returned to the
+.Xr accept 2
+caller are those of its peer at the time it called
+.Xr connect 2 ;
+the credentials returned to the
+.Xr connect 2
+caller are those of its peer at the time it called
+.Xr bind 2 .
+This mechanism is reliable; there is no way for either side to influence
+the credentials returned to its peer except by calling the appropriate
+system call (i.e., either
+.Xr connect 2
+or
+.Xr bind 2 )
+under different effective credentials.
+.Pp
+One common use of this routine is for a
+.Ux Ns -domain
+server
+to verify the credentials of its client.
+Likewise, the client can verify the credentials of the server.
+.Sh IMPLEMENTATION NOTES
+On
+.Nx ,
+.Fn getpeereid
+is implemented in terms of the
+.Dv LOCAL_PEEREID
+.Xr unix 4
+socket option.
+.Sh RETURN VALUES
+.Rv -std getpeereid
+.Sh ERRORS
+The
+.Fn getpeereid
+function
+fails if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The argument
+.Fa s
+is not a valid descriptor.
+.It Bq Er ENOTSOCK
+The argument
+.Fa s
+is a file, not a socket.
+.It Bq Er ENOTCONN
+The argument
+.Fa s
+does not refer to a socket on which
+.Xr connect 2
+have been called nor one returned from
+.Xr listen 2 .
+.It Bq Er EINVAL
+The argument
+.Fa s
+does not refer to a socket of type
+.Dv SOCK_STREAM ,
+or the kernel returned invalid data.
+.El
+.Sh SEE ALSO
+.Xr connect 2 ,
+.Xr getpeername 2 ,
+.Xr getsockname 2 ,
+.Xr getsockopt 2 ,
+.Xr listen 2 ,
+.Xr unix 4
+.Sh HISTORY
+The
+.Fn getpeereid
+function appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/net/getpeereid.c b/lib/nbsd_libc/net/getpeereid.c
new file mode 100644 (file)
index 0000000..72652ca
--- /dev/null
@@ -0,0 +1,57 @@
+/* $NetBSD: getpeereid.c,v 1.2 2008/04/29 06:53:01 martin Exp $ */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Arne H. Juul.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getpeereid.c,v 1.2 2008/04/29 06:53:01 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <unistd.h>
+#include <sys/un.h>
+#include <sys/socket.h>
+
+
+int
+getpeereid(int s, uid_t *euid, gid_t *egid)
+{
+       struct unpcbid cred;
+       socklen_t len = sizeof(cred);
+       if (getsockopt(s, 0, LOCAL_PEEREID, &cred, &len) < 0) {
+               return -1;
+       } else {
+               if (euid != NULL)
+                       *euid = cred.unp_euid;
+               if (egid != NULL)
+                       *egid = cred.unp_egid;
+               return 0;
+       }
+}
diff --git a/lib/nbsd_libc/net/getprotobyname.c b/lib/nbsd_libc/net/getprotobyname.c
new file mode 100644 (file)
index 0000000..e5aa830
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: getprotobyname.c,v 1.4 2008/04/28 20:23:00 martin Exp $        */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getprotobyname.c,v 1.4 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+
+#include <netdb.h>
+
+#include "protoent.h"
+
+#ifdef __weak_alias
+__weak_alias(getprotobyname,_getprotobyname)
+#endif
+
+#ifdef _REENTRANT
+extern mutex_t _protoent_mutex;
+#endif
+extern struct protoent_data _protoent_data;
+
+struct protoent *
+getprotobyname(const char *name)
+{
+       struct protoent *p;
+
+       mutex_lock(&_protoent_mutex);
+       p = getprotobyname_r(name, &_protoent_data.proto, &_protoent_data);
+       mutex_unlock(&_protoent_mutex);
+       return (p);
+}
diff --git a/lib/nbsd_libc/net/getprotobyname_r.c b/lib/nbsd_libc/net/getprotobyname_r.c
new file mode 100644 (file)
index 0000000..3b621e0
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: getprotobyname_r.c,v 1.3 2005/04/18 19:39:45 kleink Exp $      */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getprotoname.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getprotobyname_r.c,v 1.3 2005/04/18 19:39:45 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <netdb.h>
+#include <string.h>
+
+#include "protoent.h"
+
+#ifdef __weak_alias
+__weak_alias(getprotobyname_r,_getprotobyname_r)
+#endif
+
+struct protoent *
+getprotobyname_r(const char *name, struct protoent *pr,
+    struct protoent_data *pd)
+{
+       struct protoent *p;
+       char **cp;
+
+       _DIAGASSERT(name != NULL);
+
+       setprotoent_r(pd->stayopen, pd);
+       while ((p = getprotoent_r(pr, pd)) != NULL) {
+               if (strcmp(p->p_name, name) == 0)
+                       break;
+               for (cp = p->p_aliases; *cp != NULL; cp++)
+                       if (strcmp(*cp, name) == 0)
+                               goto found;
+       }
+found:
+       if (!pd->stayopen)
+               if (pd->fp != NULL) {
+                       (void)fclose(pd->fp);
+                       pd->fp = NULL;
+               }
+       return p;
+}
diff --git a/lib/nbsd_libc/net/getprotobynumber.c b/lib/nbsd_libc/net/getprotobynumber.c
new file mode 100644 (file)
index 0000000..4840052
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: getprotobynumber.c,v 1.4 2008/04/28 20:23:00 martin Exp $      */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getprotobynumber.c,v 1.4 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+
+#include <netdb.h>
+
+#include "protoent.h"
+
+#ifdef __weak_alias
+__weak_alias(getprotobynumber,_getprotobynumber)
+#endif
+
+#ifdef _REENTRANT
+extern mutex_t _protoent_mutex;
+#endif
+extern struct protoent_data _protoent_data;
+
+struct protoent *
+getprotobynumber(int proto)
+{
+       struct protoent *p;
+
+       mutex_lock(&_protoent_mutex);
+       p = getprotobynumber_r(proto, &_protoent_data.proto, &_protoent_data);
+       mutex_unlock(&_protoent_mutex);
+       return (p);
+}
diff --git a/lib/nbsd_libc/net/getprotobynumber_r.c b/lib/nbsd_libc/net/getprotobynumber_r.c
new file mode 100644 (file)
index 0000000..e1cb4f1
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: getprotobynumber_r.c,v 1.3 2005/04/18 19:39:45 kleink Exp $    */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getproto.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getprotobynumber_r.c,v 1.3 2005/04/18 19:39:45 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <netdb.h>
+#include <stddef.h>
+
+#include "protoent.h"
+
+#ifdef __weak_alias
+__weak_alias(getprotobynumber_r,_getprotobynumber_r)
+#endif
+
+struct protoent *
+getprotobynumber_r(int proto, struct protoent *pr, struct protoent_data *pd)
+{
+       struct protoent *p;
+
+       setprotoent_r(pd->stayopen, pd);
+       while ((p = getprotoent_r(pr, pd)) != NULL)
+               if (p->p_proto == proto)
+                       break;
+       if (!pd->stayopen)
+               if (pd->fp != NULL) {
+                       (void)fclose(pd->fp);
+                       pd->fp = NULL;
+               }
+       return p;
+}
diff --git a/lib/nbsd_libc/net/getprotoent.3 b/lib/nbsd_libc/net/getprotoent.3
new file mode 100644 (file)
index 0000000..8b8d693
--- /dev/null
@@ -0,0 +1,144 @@
+.\"    $NetBSD: getprotoent.3,v 1.11 2003/08/07 16:43:09 agc Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getprotoent.3      8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt GETPROTOENT 3
+.Os
+.Sh NAME
+.Nm getprotoent ,
+.Nm getprotobynumber ,
+.Nm getprotobyname ,
+.Nm setprotoent ,
+.Nm endprotoent
+.Nd get protocol entry
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In netdb.h
+.Ft struct protoent *
+.Fn getprotoent
+.Ft struct protoent *
+.Fn getprotobyname "const char *name"
+.Ft struct protoent *
+.Fn getprotobynumber "int proto"
+.Fn setprotoent "int stayopen"
+.Fn endprotoent
+.Sh DESCRIPTION
+The
+.Fn getprotoent ,
+.Fn getprotobyname ,
+and
+.Fn getprotobynumber
+functions
+each return a pointer to an object with the
+following structure
+containing the broken-out
+fields of a line in the network protocol data base,
+.Pa /etc/protocols .
+.Bd -literal -offset indent
+.Pp
+struct protoent {
+       char    *p_name;        /* official name of protocol */
+       char    **p_aliases;    /* alias list */
+       int     p_proto;        /* protocol number */
+};
+.Ed
+.Pp
+The members of this structure are:
+.Bl -tag -width p_aliases
+.It Fa p_name
+The official name of the protocol.
+.It Fa p_aliases
+A zero terminated list of alternative names for the protocol.
+.It Fa p_proto
+The protocol number.
+.El
+.Pp
+The
+.Fn getprotoent
+function
+reads the next line of the file, opening the file if necessary.
+.Pp
+The
+.Fn setprotoent
+function
+opens and rewinds the file.  If the
+.Fa stayopen
+flag is non-zero,
+the net data base will not be closed after each call to
+.Fn getprotobyname
+or
+.Fn getprotobynumber .
+.Pp
+The
+.Fn endprotoent
+function
+closes the file.
+.Pp
+The
+.Fn getprotobyname
+function
+and
+.Fn getprotobynumber
+sequentially search from the beginning
+of the file until a matching
+protocol name or
+protocol number is found,
+or until
+.Dv EOF
+is encountered.
+.Sh RETURN VALUES
+Null pointer
+(0) returned on
+.Dv EOF
+or error.
+.Sh FILES
+.Bl -tag -width /etc/protocols -compact
+.It Pa /etc/protocols
+.El
+.Sh SEE ALSO
+.Xr protocols 5
+.Sh HISTORY
+The
+.Fn getprotoent ,
+.Fn getprotobynumber ,
+.Fn getprotobyname ,
+.Fn setprotoent ,
+and
+.Fn endprotoent
+functions appeared in
+.Bx 4.2 .
+.Sh BUGS
+These functions use a static data space;
+if the data is needed for future use, it should be
+copied before any subsequent calls overwrite it.
+Only the Internet
+protocols are currently understood.
diff --git a/lib/nbsd_libc/net/getprotoent.c b/lib/nbsd_libc/net/getprotoent.c
new file mode 100644 (file)
index 0000000..1912b4e
--- /dev/null
@@ -0,0 +1,80 @@
+/*     $NetBSD: getprotoent.c,v 1.12 2008/04/28 20:23:00 martin Exp $  */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getprotoent.c,v 1.12 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+
+#include <netdb.h>
+
+#include "protoent.h"
+
+#ifdef __weak_alias
+__weak_alias(endprotoent,_endprotoent)
+__weak_alias(getprotoent,_getprotoent)
+__weak_alias(setprotoent,_setprotoent)
+#endif
+
+#ifdef _REENTRANT
+mutex_t _protoent_mutex = MUTEX_INITIALIZER;
+#endif
+struct protoent_data _protoent_data;
+
+void
+setprotoent(int f)
+{
+       mutex_lock(&_protoent_mutex);
+       setprotoent_r(f, &_protoent_data);
+       mutex_unlock(&_protoent_mutex);
+}
+
+void
+endprotoent(void)
+{
+       mutex_lock(&_protoent_mutex);
+       endprotoent_r(&_protoent_data);
+       mutex_unlock(&_protoent_mutex);
+}
+
+struct protoent *
+getprotoent(void)
+{
+       struct protoent *p;
+
+       mutex_lock(&_protoent_mutex);
+       p = getprotoent_r(&_protoent_data.proto, &_protoent_data);
+       mutex_unlock(&_protoent_mutex);
+       return (p);
+}
diff --git a/lib/nbsd_libc/net/getprotoent_r.c b/lib/nbsd_libc/net/getprotoent_r.c
new file mode 100644 (file)
index 0000000..01b0891
--- /dev/null
@@ -0,0 +1,153 @@
+/*     $NetBSD: getprotoent_r.c,v 1.5 2005/04/18 19:39:45 kleink Exp $ */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getprotoent.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getprotoent_r.c,v 1.5 2005/04/18 19:39:45 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <netdb.h>
+#include <stdio.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "protoent.h"
+
+#ifdef __weak_alias
+__weak_alias(endprotoent_r,_endprotoent_r)
+__weak_alias(getprotoent_r,_getprotoent_r)
+__weak_alias(setprotoent_r,_setprotoent_r)
+#endif
+
+void
+setprotoent_r(int f, struct protoent_data *pd)
+{
+       if (pd->fp == NULL)
+               pd->fp = fopen(_PATH_PROTOCOLS, "r");
+       else
+               rewind(pd->fp);
+       pd->stayopen |= f;
+}
+
+void
+endprotoent_r(struct protoent_data *pd)
+{
+       if (pd->fp) {
+               (void)fclose(pd->fp);
+               pd->fp = NULL;
+       }
+       if (pd->aliases) {
+               free(pd->aliases);
+               pd->aliases = NULL;
+               pd->maxaliases = 0;
+       }
+       if (pd->line) {
+               free(pd->line);
+               pd->line = NULL;
+       }
+       pd->stayopen = 0;
+}
+
+struct protoent *
+getprotoent_r(struct protoent *pr, struct protoent_data *pd)
+{
+       char *p, *cp, **q;
+       size_t i = 0;
+       int oerrno;
+
+       if (pd->fp == NULL && (pd->fp = fopen(_PATH_PROTOCOLS, "r")) == NULL)
+               return NULL;
+
+       for (;;) {
+               if (pd->line)
+                       free(pd->line);
+               pd->line = fparseln(pd->fp, NULL, NULL, NULL,
+                   FPARSELN_UNESCALL);
+               if (pd->line == NULL)
+                       return NULL;
+               pr->p_name = p = pd->line;
+               cp = strpbrk(p, " \t");
+               if (cp == NULL)
+                       continue;
+               *cp++ = '\0';
+               while (*cp == ' ' || *cp == '\t')
+                       cp++;
+               p = strpbrk(cp, " \t");
+               if (p != NULL)
+                       *p++ = '\0';
+               pr->p_proto = atoi(cp);
+               if (pd->aliases == NULL) {
+                       pd->maxaliases = 10;
+                       pd->aliases = malloc(pd->maxaliases * sizeof(char *));
+                       if (pd->aliases == NULL) {
+                               oerrno = errno;
+                               endprotoent_r(pd);
+                               errno = oerrno;
+                               return NULL;
+                       }
+               }
+               q = pr->p_aliases = pd->aliases;
+               if (p != NULL) {
+                       cp = p;
+                       while (cp && *cp) {
+                               if (*cp == ' ' || *cp == '\t') {
+                                       cp++;
+                                       continue;
+                               }
+                               if (i == pd->maxaliases - 2) {
+                                       pd->maxaliases *= 2;
+                                       q = realloc(q,
+                                           pd->maxaliases * sizeof(char *));
+                                       if (q == NULL) {
+                                               oerrno = errno;
+                                               endprotoent_r(pd);
+                                               errno = oerrno;
+                                               return NULL;
+                                       }
+                                       pr->p_aliases = pd->aliases = q;
+                               }
+                               q[i++] = cp;
+
+                               cp = strpbrk(cp, " \t");
+                               if (cp != NULL)
+                                       *cp++ = '\0';
+                       }
+               }
+               q[i] = NULL;
+               return pr;
+       }
+}
diff --git a/lib/nbsd_libc/net/getservbyname.c b/lib/nbsd_libc/net/getservbyname.c
new file mode 100644 (file)
index 0000000..d208ade
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: getservbyname.c,v 1.14 2008/04/28 20:23:00 martin Exp $        */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getservbyname.c,v 1.14 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+
+#include <netdb.h>
+
+#include "servent.h"
+
+#ifdef __weak_alias
+__weak_alias(getservbyname,_getservbyname)
+#endif
+
+#ifdef _REENTRANT
+extern mutex_t _servent_mutex;
+#endif
+extern struct servent_data _servent_data;
+
+struct servent *
+getservbyname(const char *name, const char *proto)
+{
+       struct servent *s;
+
+       mutex_lock(&_servent_mutex);
+       s = getservbyname_r(name, proto, &_servent_data.serv, &_servent_data);
+       mutex_unlock(&_servent_mutex);
+       return (s);
+}
diff --git a/lib/nbsd_libc/net/getservbyname_r.c b/lib/nbsd_libc/net/getservbyname_r.c
new file mode 100644 (file)
index 0000000..62ee2de
--- /dev/null
@@ -0,0 +1,147 @@
+/*     $NetBSD: getservbyname_r.c,v 1.7 2010/04/25 00:54:46 joerg Exp $        */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getservbyname.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getservbyname_r.c,v 1.7 2010/04/25 00:54:46 joerg Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <cdbr.h>
+#include <netdb.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "servent.h"
+
+#ifdef __weak_alias
+__weak_alias(getservbyname_r,_getservbyname_r)
+#endif
+
+static struct servent *
+_servent_getbyname(struct servent_data *sd, struct servent *sp,
+    const char *name, const char *proto)
+{
+
+       if ((sd->flags & (_SV_CDB | _SV_PLAINFILE)) == 0)
+               return NULL;
+
+       if (sd->flags & _SV_CDB) {
+               uint8_t buf[255 * 2 + 2];
+               size_t namelen, protolen;
+               const uint8_t *data, *data_end;
+               const void *data_ptr;
+               size_t datalen;
+
+               namelen = strlen(name);
+               if (namelen == 0 || namelen > 255)
+                       return NULL;
+               if (proto != NULL && *proto == '\0')
+                       return NULL;
+               if (proto != NULL)
+                       protolen = strlen(proto);
+               else
+                       protolen = 0;
+
+               buf[0] = namelen;
+               buf[1] = protolen;
+               memcpy(buf + 2, name, namelen);
+               memcpy(buf + 2 + namelen, proto, protolen);
+
+               if (cdbr_find(sd->cdb, buf, 2 + namelen + protolen,
+                   &data_ptr, &datalen))
+                       return NULL;
+
+               if (datalen < namelen + protolen + 6)
+                       return NULL;
+
+               data = data_ptr;
+               data_end = data + datalen;
+               if (protolen) {
+                       if (data[2] != protolen)
+                               return NULL;
+                       if (memcmp(data + 3, proto, protolen + 1))
+                               return NULL;
+               }
+               data += 3 + data[2] + 1;
+               if (data > data_end)
+                       return NULL;
+               while (data != data_end) {
+                       if (*data == '\0')
+                               return NULL;
+                       if (data + data[0] + 2 > data_end)
+                               return NULL;
+                       if (data[0] == namelen &&
+                           memcmp(data + 1, name, namelen + 1) == 0)
+                               return _servent_parsedb(sd, sp, data_ptr,
+                                   datalen);
+                       data += data[0] + 2;
+               }
+               return NULL;
+       } else {
+               while (_servent_getline(sd) != -1) {
+                       char **cp;
+                       if (_servent_parseline(sd, sp) == NULL)
+                               continue;
+
+                       if (strcmp(name, sp->s_name) == 0)
+                               goto gotname;
+
+                       for (cp = sp->s_aliases; *cp; cp++)
+                               if (strcmp(name, *cp) == 0)
+                                       goto gotname;
+                       continue;
+gotname:
+                       if (proto == NULL || strcmp(sp->s_proto, proto) == 0)
+                               return sp;
+               }
+               return NULL;
+       }
+}
+
+struct servent *
+getservbyname_r(const char *name, const char *proto, struct servent *sp,
+    struct servent_data *sd)
+{
+       _DIAGASSERT(name != NULL);
+       /* proto may be NULL */
+
+       setservent_r(sd->flags & _SV_STAYOPEN, sd);
+       sp = _servent_getbyname(sd, sp, name, proto);
+       if (!(sd->flags & _SV_STAYOPEN))
+               _servent_close(sd);
+       return sp;
+}
diff --git a/lib/nbsd_libc/net/getservbyport.c b/lib/nbsd_libc/net/getservbyport.c
new file mode 100644 (file)
index 0000000..8562c3d
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: getservbyport.c,v 1.12 2008/04/28 20:23:00 martin Exp $        */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getservbyport.c,v 1.12 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+
+#include <netdb.h>
+
+#include "servent.h"
+
+#ifdef __weak_alias
+__weak_alias(getservbyport,_getservbyport)
+#endif
+
+#ifdef _REENTRANT
+extern mutex_t _servent_mutex;
+#endif
+extern struct servent_data _servent_data;
+
+struct servent *
+getservbyport(int port, const char *proto)
+{
+       struct servent *s;
+
+       mutex_lock(&_servent_mutex);
+       s = getservbyport_r(port, proto, &_servent_data.serv, &_servent_data);
+       mutex_unlock(&_servent_mutex);
+       return (s);
+}
diff --git a/lib/nbsd_libc/net/getservbyport_r.c b/lib/nbsd_libc/net/getservbyport_r.c
new file mode 100644 (file)
index 0000000..e5b7ea6
--- /dev/null
@@ -0,0 +1,123 @@
+/*     $NetBSD: getservbyport_r.c,v 1.7 2010/04/25 00:54:46 joerg Exp $        */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getservbyport.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getservbyport_r.c,v 1.7 2010/04/25 00:54:46 joerg Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <cdbr.h>
+#include <netdb.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "servent.h"
+
+#ifdef __weak_alias
+__weak_alias(getservbyport_r,_getservbyport_r)
+#endif
+
+static struct servent *
+_servent_getbyport(struct servent_data *sd, struct servent *sp, int port,
+    const char *proto)
+{
+
+       if ((sd->flags & (_SV_CDB | _SV_PLAINFILE)) == 0)
+               return NULL;
+
+       if (sd->flags & _SV_CDB) {
+               uint8_t buf[255 + 4];
+               size_t protolen;
+               const uint8_t *data;
+               const void *data_ptr;
+               size_t datalen;
+
+               port = be16toh(port);
+
+               if (proto != NULL && *proto == '\0')
+                       return NULL;
+               if (proto != NULL)
+                       protolen = strlen(proto);
+               else
+                       protolen = 0;
+               if (port < 0 || port > 65536)
+                       return NULL;
+
+               buf[0] = 0;
+               buf[1] = protolen;
+               be16enc(buf + 2, port);
+               memcpy(buf + 4, proto, protolen);
+
+               if (cdbr_find(sd->cdb, buf, 4 + protolen,
+                   &data_ptr, &datalen))
+                       return NULL;
+
+               if (datalen < protolen + 4)
+                       return NULL;
+
+               data = data_ptr;
+               if (be16dec(data) != port)
+                       return NULL;
+               if (protolen) {
+                       if (data[2] != protolen)
+                               return NULL;
+                       if (memcmp(data + 3, proto, protolen + 1))
+                               return NULL;
+               }
+               return _servent_parsedb(sd, sp, data, datalen);
+       } else {
+               while (_servent_getline(sd) != -1) {
+                       if (_servent_parseline(sd, sp) == NULL)
+                               continue;
+                       if (sp->s_port != port)
+                               continue;
+                       if (proto == NULL || strcmp(sp->s_proto, proto) == 0)
+                               return sp;
+               }
+               return NULL;
+       }
+}
+
+struct servent *
+getservbyport_r(int port, const char *proto, struct servent *sp,
+    struct servent_data *sd)
+{
+       setservent_r(sd->flags & _SV_STAYOPEN, sd);
+       sp = _servent_getbyport(sd, sp, port, proto);
+       if (!(sd->flags & _SV_STAYOPEN))
+               _servent_close(sd);
+       return sp;
+}
diff --git a/lib/nbsd_libc/net/getservent.3 b/lib/nbsd_libc/net/getservent.3
new file mode 100644 (file)
index 0000000..d6bcdfe
--- /dev/null
@@ -0,0 +1,154 @@
+.\"    $NetBSD: getservent.3,v 1.14 2003/08/07 16:43:10 agc Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getservent.3      8.4 (Berkeley) 5/25/95
+.\"
+.Dd May 25, 1995
+.Dt GETSERVENT 3
+.Os
+.Sh NAME
+.Nm getservent ,
+.Nm getservbyport ,
+.Nm getservbyname ,
+.Nm setservent ,
+.Nm endservent
+.Nd get service entry
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In netdb.h
+.Ft struct servent *
+.Fn getservent
+.Ft struct servent *
+.Fn getservbyname "const char *name" "const char *proto"
+.Ft struct servent *
+.Fn getservbyport "int port" "const char *proto"
+.Ft void
+.Fn setservent "int stayopen"
+.Ft void
+.Fn endservent void
+.Sh DESCRIPTION
+The
+.Fn getservent ,
+.Fn getservbyname ,
+and
+.Fn getservbyport
+functions
+each return a pointer to an object with the
+following structure
+containing the broken-out
+fields of a line in the network services data base,
+.Pa /etc/services .
+.Bd -literal -offset indent
+struct servent {
+       char    *s_name;        /* official name of service */
+       char    **s_aliases;    /* alias list */
+       int     s_port;         /* port service resides at */
+       char    *s_proto;       /* protocol to use */
+};
+.Ed
+.Pp
+The members of this structure are:
+.Bl -tag -width s_aliases
+.It Fa s_name
+The official name of the service.
+.It Fa s_aliases
+A NULL terminated list of alternative names for the service.
+.It Fa s_port
+The port number at which the service resides.
+Port numbers must be given and are returned in network byte order.
+.It Fa s_proto
+The name of the protocol to use when contacting the
+service.
+.El
+.Pp
+The
+.Fn getservent
+function
+reads the next line of the file, opening the file if necessary.
+.Pp
+The
+.Fn setservent
+function
+opens and rewinds the file.  If the
+.Fa stayopen
+flag is non-zero,
+the net data base will not be closed after each call to
+.Fn getservbyname
+or
+.Fn getservbyport .
+.Pp
+The
+.Fn endservent
+function
+closes the file.
+.Pp
+The
+.Fn getservbyname
+and
+.Fn getservbyport
+functions
+sequentially search from the beginning
+of the file until a matching
+protocol name or
+port number is found,
+or until
+.Dv EOF
+is encountered.
+If a protocol name is also supplied (non-\c
+.Dv NULL ) ,
+searches must also match the protocol.
+.Sh FILES
+.Bl -tag -width /etc/services -compact
+.It Pa /etc/services
+.El
+.Sh DIAGNOSTICS
+Null pointer
+(0) returned on
+.Dv EOF
+or error.
+.Sh SEE ALSO
+.Xr getprotoent 3 ,
+.Xr services 5
+.Sh HISTORY
+The
+.Fn getservent ,
+.Fn getservbyport ,
+.Fn getservbyname ,
+.Fn setservent ,
+and
+.Fn endservent
+functions appeared in
+.Bx 4.2 .
+.Sh BUGS
+These functions use static data storage;
+if the data is needed for future use, it should be
+copied before any subsequent calls overwrite it.
+Expecting port numbers to fit in a 32 bit
+quantity is probably naive.
diff --git a/lib/nbsd_libc/net/getservent.c b/lib/nbsd_libc/net/getservent.c
new file mode 100644 (file)
index 0000000..5465d6a
--- /dev/null
@@ -0,0 +1,80 @@
+/*     $NetBSD: getservent.c,v 1.12 2008/04/28 20:23:00 martin Exp $   */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getservent.c,v 1.12 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "reentrant.h"
+
+#include <netdb.h>
+
+#include "servent.h"
+
+#ifdef __weak_alias
+__weak_alias(endservent,_endservent)
+__weak_alias(getservent,_getservent)
+__weak_alias(setservent,_setservent)
+#endif
+
+#ifdef _REENTRANT
+mutex_t _servent_mutex = MUTEX_INITIALIZER;
+#endif
+struct servent_data _servent_data;
+
+void
+setservent(int f)
+{
+       mutex_lock(&_servent_mutex);
+       setservent_r(f, &_servent_data);
+       mutex_unlock(&_servent_mutex);
+}
+
+void
+endservent(void)
+{
+       mutex_lock(&_servent_mutex);
+       endservent_r(&_servent_data);
+       mutex_unlock(&_servent_mutex);
+}
+
+struct servent *
+getservent(void)
+{
+       struct servent *s;
+
+       mutex_lock(&_servent_mutex);
+       s = getservent_r(&_servent_data.serv, &_servent_data);
+       mutex_unlock(&_servent_mutex);
+       return (s);
+}
diff --git a/lib/nbsd_libc/net/getservent_r.c b/lib/nbsd_libc/net/getservent_r.c
new file mode 100644 (file)
index 0000000..22da50f
--- /dev/null
@@ -0,0 +1,323 @@
+/*     $NetBSD: getservent_r.c,v 1.10 2010/04/25 00:54:46 joerg Exp $  */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getservent.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getservent_r.c,v 1.10 2010/04/25 00:54:46 joerg Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <cdbr.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <netdb.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "servent.h"
+
+#ifdef __weak_alias
+__weak_alias(endservent_r,_endservent_r)
+__weak_alias(getservent_r,_getservent_r)
+__weak_alias(setservent_r,_setservent_r)
+#endif
+
+int
+_servent_open(struct servent_data *sd)
+{
+       if (sd->flags & (_SV_CDB | _SV_PLAINFILE)) {
+               sd->flags |= _SV_FIRST;
+               return 0;
+       }
+
+       free(sd->line);
+       sd->line = NULL;
+       free(sd->cdb_buf);
+       sd->cdb_buf = NULL;
+       sd->cdb_buf_len = 0;
+       free(sd->aliases);
+       sd->aliases = NULL;
+       sd->maxaliases = 0;
+       sd->flags |= _SV_FIRST;
+
+       sd->cdb = cdbr_open(_PATH_SERVICES_CDB, CDBR_DEFAULT);
+       if (sd->cdb != NULL) {
+               sd->flags |= _SV_CDB;
+               return 0;
+       }
+               
+       sd->plainfile = fopen(_PATH_SERVICES, "r");
+       if (sd->plainfile != NULL) {
+               sd->flags |= _SV_PLAINFILE;
+               return 0;
+       }
+       return -1;
+}
+
+void
+_servent_close(struct servent_data *sd)
+{
+       if (sd->flags & _SV_CDB) {
+               cdbr_close(sd->cdb);
+               sd->cdb = NULL;
+               sd->flags &= ~_SV_CDB;
+       }
+
+       if (sd->flags & _SV_PLAINFILE) {
+               (void)fclose(sd->plainfile);
+               sd->plainfile = NULL;
+               sd->flags &= ~_SV_PLAINFILE;
+       }
+       sd->flags &= ~_SV_STAYOPEN;
+}
+
+
+int
+_servent_getline(struct servent_data *sd)
+{
+
+       if (sd->flags & _SV_CDB)
+               return -1;
+
+       if ((sd->flags & _SV_PLAINFILE) == 0)
+               return -1;
+
+       free(sd->line);
+       sd->line = NULL;
+
+       if (sd->flags & _SV_FIRST) {
+               (void)rewind((FILE *)sd->plainfile);
+               sd->flags &= ~_SV_FIRST;
+       }
+       sd->line = fparseln(sd->plainfile, NULL, NULL, NULL,
+           FPARSELN_UNESCALL);
+       return sd->line == NULL ? -1 : 0;
+}
+
+struct servent *
+_servent_parseline(struct servent_data *sd, struct servent *sp)
+{
+       size_t i = 0;
+       int oerrno;
+       char *p, *cp, **q;
+
+       if (sd->line == NULL)
+               return NULL;
+
+       sp->s_name = p = sd->line;
+       p = strpbrk(p, " \t");
+       if (p == NULL)
+               return NULL;
+       *p++ = '\0';
+       while (*p == ' ' || *p == '\t')
+               p++;
+       cp = strpbrk(p, ",/");
+       if (cp == NULL)
+               return NULL;
+       *cp++ = '\0';
+       sp->s_port = htons((u_short)atoi(p));
+       sp->s_proto = cp;
+       if (sd->aliases == NULL) {
+               sd->maxaliases = 10;
+               sd->aliases = calloc(sd->maxaliases, sizeof(*sd->aliases));
+               if (sd->aliases == NULL) {
+                       oerrno = errno;
+                       endservent_r(sd);
+                       errno = oerrno;
+                       return NULL;
+               }
+       }
+       sp->s_aliases = sd->aliases;
+       cp = strpbrk(cp, " \t");
+       if (cp != NULL)
+               *cp++ = '\0';
+       while (cp && *cp) {
+               if (*cp == ' ' || *cp == '\t') {
+                       cp++;
+                       continue;
+               }
+               if (i == sd->maxaliases - 2) {
+                       sd->maxaliases *= 2;
+                       q = realloc(sd->aliases, sd->maxaliases * sizeof(*q));
+                       if (q == NULL) {
+                               oerrno = errno;
+                               endservent_r(sd);
+                               errno = oerrno;
+                               return NULL;
+                       }
+                       sp->s_aliases = sd->aliases = q;
+               }
+               sp->s_aliases[i++] = cp;
+               cp = strpbrk(cp, " \t");
+               if (cp != NULL)
+                       *cp++ = '\0';
+       }
+       sp->s_aliases[i] = NULL;
+       return sp;
+}
+
+void
+setservent_r(int f, struct servent_data *sd)
+{
+       (void)_servent_open(sd);
+       sd->flags |= f ? _SV_STAYOPEN : 0;
+}
+
+void
+endservent_r(struct servent_data *sd)
+{
+       _servent_close(sd);
+       free(sd->aliases);
+       sd->aliases = NULL;
+       sd->maxaliases = 0;
+       free(sd->line);
+       sd->line = NULL;
+       free(sd->cdb_buf);
+       sd->cdb_buf = NULL;
+       sd->cdb_buf_len = 0;
+}
+
+struct servent *
+getservent_r(struct servent *sp, struct servent_data *sd)
+{
+
+       if ((sd->flags & (_SV_CDB | _SV_PLAINFILE)) == 0 &&
+           _servent_open(sd) == -1)
+               return NULL;
+
+       if (sd->flags & _SV_CDB) {
+               const void *data;
+               size_t len;
+
+               if (sd->flags & _SV_FIRST) {
+                       sd->cdb_index = 0;
+                       sd->flags &= ~_SV_FIRST;
+               }
+
+               if (cdbr_get(sd->cdb, sd->cdb_index, &data, &len))
+                       return NULL;
+               ++sd->cdb_index;
+               return _servent_parsedb(sd, sp, data, len);
+       }
+       if (sd->flags & _SV_PLAINFILE) {
+               for (;;) {
+                       if (_servent_getline(sd) == -1)
+                               return NULL;
+                       if (_servent_parseline(sd, sp) == NULL)
+                               continue;
+                       return sp;
+               }
+       }
+       return NULL;
+}
+
+struct servent *
+_servent_parsedb(struct servent_data *sd, struct servent *sp,
+    const uint8_t *data, size_t len)
+{
+       char **q;
+       size_t i;
+       int oerrno;
+
+       if ((sd->flags & _SV_STAYOPEN) == 0) {
+               if (len > sd->cdb_buf_len) {
+                       void *tmp = realloc(sd->cdb_buf, len);
+                       if (tmp == NULL)
+                               goto fail;
+                       sd->cdb_buf = tmp;
+                       sd->cdb_buf_len = len;
+               }
+               memcpy(sd->cdb_buf, data, len);
+               data = sd->cdb_buf;
+       }
+
+       if (len < 2)
+               goto fail;
+       sp->s_port = htobe16(be16dec(data));
+       data += 2;
+       len -= 2;
+
+       if (len == 0 || len < (size_t)data[0] + 2)
+               goto fail;
+       sp->s_proto = __UNCONST(data + 1);
+
+       if (sp->s_proto[data[0]] != '\0')
+               goto fail;
+
+       len -= 2 + data[0];
+       data += 2 + data[0];
+
+       if (len == 0)
+               goto fail;
+       if (len < (size_t)data[0] + 2)
+               goto fail;
+
+       sp->s_name = __UNCONST(data + 1);
+       len -= 2 + data[0];
+       data += 2 + data[0];
+
+       if (sd->aliases == NULL) {
+               sd->maxaliases = 10;
+               sd->aliases = malloc(sd->maxaliases * sizeof(char *));
+               if (sd->aliases == NULL)
+                       goto fail;
+       }
+       sp->s_aliases = sd->aliases;
+       i = 0;
+       while (len) {
+               if (len < (size_t)data[0] + 2)
+                       goto fail;
+               if (i == sd->maxaliases - 2) {
+                       sd->maxaliases *= 2;
+                       q = realloc(sd->aliases, sd->maxaliases * sizeof(*q));
+                       if (q == NULL)
+                               goto fail;
+                       sp->s_aliases = sd->aliases = q;
+               }
+               sp->s_aliases[i++] = __UNCONST(data + 1);
+               len -= 2 + data[0];
+               data += 2 + data[0];
+       }
+       sp->s_aliases[i] = NULL;
+       return sp;
+
+fail:
+       oerrno = errno;
+       endservent_r(sd);
+       errno = oerrno;
+       return NULL;
+}
+
diff --git a/lib/nbsd_libc/net/hesiod.3 b/lib/nbsd_libc/net/hesiod.3
new file mode 100644 (file)
index 0000000..f2b9a3e
--- /dev/null
@@ -0,0 +1,150 @@
+.\"    $NetBSD: hesiod.3,v 1.7 2009/03/10 23:36:10 joerg Exp $
+.\"
+.\" from: #Id: hesiod.3,v 1.9.2.1 1997/01/03 21:02:23 ghudson Exp #
+.\"
+.\" Copyright 1988, 1996 by the Massachusetts Institute of Technology.
+.\"
+.\" Permission to use, copy, modify, and distribute this
+.\" software and its documentation for any purpose and without
+.\" fee is hereby granted, provided that the above copyright
+.\" notice appear in all copies and that both that copyright
+.\" notice and this permission notice appear in supporting
+.\" documentation, and that the name of M.I.T. not be used in
+.\" advertising or publicity pertaining to distribution of the
+.\" software without specific, written prior permission.
+.\" M.I.T. makes no representations about the suitability of
+.\" this software for any purpose.  It is provided "as is"
+.\" without express or implied warranty.
+.\"
+.Dd September 16, 2001
+.Dt HESIOD 3
+.Os
+.Sh NAME
+.Nm hesiod ,
+.Nm hesiod_init ,
+.Nm hesiod_resolve ,
+.Nm hesiod_free_list ,
+.Nm hesiod_to_bind ,
+.Nm hesiod_end
+.Nd Hesiod name server interface library
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In hesiod.h
+.Ft int
+.Fn hesiod_init "void **context"
+.Ft char
+.Fn **hesiod_resolve "void *context" "const char *name" "const char *type"
+.Ft void
+.Fn hesiod_free_list "void *context" "char **list"
+.Ft char
+.Fn *hesiod_to_bind "void *context" "const char *name" "const char *type"
+.Ft void
+.Fn hesiod_end "void *context"
+.Sh DESCRIPTION
+This family of functions allows you to perform lookups of Hesiod
+information, which is stored as text records in the Domain Name
+Service.  To perform lookups, you must first initialize a
+.Fa context ,
+an opaque object which stores information used internally by the
+library between calls.
+.Fn hesiod_init
+initializes a context, storing a pointer to the context in the
+location pointed to by the
+.Fa context
+argument.
+.Fn hesiod_end
+frees the resources used by a context.
+.Pp
+.Fn hesiod_resolve
+is the primary interface to the library.  If successful, it returns a
+list of one or more strings giving the records matching
+.Fa name
+and
+.Fa type .
+The last element of the list is followed by a
+.Dv NULL
+pointer.  It is the caller's responsibility to call
+.Fn hesiod_free_list
+to free the resources used by the returned list.
+.Pp
+.Fn hesiod_to_bind
+converts
+.Fa name
+and
+.Fa type
+into the DNS name used by
+.Fn hesiod_resolve .
+It is the caller's responsibility to free the returned string using
+.Xr free 3 .
+.Sh RETURN VALUES
+If successful,
+.Fn hesiod_init
+returns 0; otherwise it returns \-1 and sets
+.Va errno
+to indicate the error.  On failure,
+.Fn hesiod_resolve
+and
+.Fn hesiod_to_bind
+return
+.Dv NULL
+and set the global variable
+.Va errno
+to indicate the error.
+.Sh ENVIRONMENT
+If the environment variable
+.Ev HES_DOMAIN
+is set, it will override the domain in the Hesiod configuration file.
+If the environment variable
+.Ev HESIOD_CONFIG
+is set, it specifies the location of the Hesiod configuration file.
+.Sh ERRORS
+Hesiod calls may fail because of:
+.Bl -tag -width ECONNREFUSED -compact
+.It Er ENOMEM
+Insufficient memory was available to carry out the requested operation.
+.It Er ENOEXEC
+.Fn hesiod_init
+failed because the Hesiod configuration file was invalid.
+.It Er ECONNREFUSED
+.Fn hesiod_resolve
+failed because no name server could be contacted to answer the query.
+.It Er EMSGSIZE
+.Fn hesiod_resolve
+or
+.Fn hesiod_to_bind
+failed because the query or response was too big to fit into the
+packet buffers.
+.It Er ENOENT
+.Fn hesiod_resolve
+failed because the name server had no text records matching
+.Fa name
+and
+.Fa type ,
+or
+.Fn hesiod_to_bind
+failed because the
+.Fa name
+argument had a domain extension which could not be resolved with type
+.Dq rhs-extension
+in the local Hesiod domain.
+.El
+.Sh SEE ALSO
+.Xr hesiod.conf 5 ,
+.Xr named 8
+.Rs
+.%T Hesiod - Project Athena Technical Plan -- Name Service
+.Re
+.Sh AUTHORS
+.An Steve Dyer, IBM/Project Athena
+.An Greg Hudson, MIT Team Athena
+.Pp
+Copyright 1987, 1988, 1995, 1996 by the Massachusetts Institute of Technology.
+.Sh BUGS
+The strings corresponding to the
+.Ev errno
+values set by the Hesiod functions are not particularly indicative of
+what went wrong, especially for
+.Er ENOEXEC
+and
+.Er ENOENT .
diff --git a/lib/nbsd_libc/net/hesiod.c b/lib/nbsd_libc/net/hesiod.c
new file mode 100644 (file)
index 0000000..2e7fb98
--- /dev/null
@@ -0,0 +1,649 @@
+/*     $NetBSD: hesiod.c,v 1.25 2011/01/05 00:09:43 wiz Exp $  */
+
+/* Copyright (c) 1996 by Internet Software Consortium.
+ *
+ * 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 INTERNET SOFTWARE CONSORTIUM DISCLAIMS
+ * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
+ * CONSORTIUM 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.
+ */
+
+/* Copyright 1996 by the Massachusetts Institute of Technology.
+ *
+ * Permission to use, copy, modify, and distribute this
+ * software and its documentation for any purpose and without
+ * fee is hereby granted, provided that the above copyright
+ * notice appear in all copies and that both that copyright
+ * notice and this permission notice appear in supporting
+ * documentation, and that the name of M.I.T. not be used in
+ * advertising or publicity pertaining to distribution of the
+ * software without specific, written prior permission.
+ * M.I.T. makes no representations about the suitability of
+ * this software for any purpose.  It is provided "as is"
+ * without express or implied warranty.
+ */
+
+/* This file is part of the hesiod library.  It implements the core
+ * portion of the hesiod resolver.
+ *
+ * This file is loosely based on an interim version of hesiod.c from
+ * the BIND IRS library, which was in turn based on an earlier version
+ * of this file.  Extensive changes have been made on each step of the
+ * path.
+ *
+ * This implementation is thread-safe because it uses res_nsend().
+ */
+
+#include <sys/cdefs.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__IDSTRING(rcsid_hesiod_c,
+    "#Id: hesiod.c,v 1.18.2.1 1997/01/03 20:48:20 ghudson Exp #");
+__IDSTRING(rcsid_hesiod_p_h,
+    "#Id: hesiod_p.h,v 1.1 1996/12/08 21:39:37 ghudson Exp #");
+__IDSTRING(rcsid_hescompat_c,
+    "#Id: hescompat.c,v 1.1.2.1 1996/12/16 08:37:45 ghudson Exp #");
+__RCSID("$NetBSD: hesiod.c,v 1.25 2011/01/05 00:09:43 wiz Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/param.h>
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <hesiod.h>
+#include <resolv.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(hesiod_init,_hesiod_init)
+__weak_alias(hesiod_end,_hesiod_end)
+__weak_alias(hesiod_to_bind,_hesiod_to_bind)
+__weak_alias(hesiod_resolve,_hesiod_resolve)
+__weak_alias(hesiod_free_list,_hesiod_free_list)
+__weak_alias(hes_init,_hes_init)
+__weak_alias(hes_to_bind,_hes_to_bind)
+__weak_alias(hes_resolve,_hes_resolve)
+__weak_alias(hes_error,_hes_error)
+__weak_alias(hes_free,_hes_free)
+#endif
+
+struct hesiod_p {
+       char    *lhs;                   /* normally ".ns" */
+       char    *rhs;                   /* AKA the default hesiod domain */
+       int      classes[2];            /* The class search order. */
+};
+
+#define        MAX_HESRESP     1024
+
+static int       read_config_file __P((struct hesiod_p *, const char *));
+static char    **get_txt_records __P((int, const char *));
+static int       init_context __P((void));
+static void      translate_errors __P((void));
+
+
+/*
+ * hesiod_init --
+ *     initialize a hesiod_p.
+ */
+int 
+hesiod_init(context)
+       void    **context;
+{
+       struct hesiod_p *ctx;
+       const char      *p, *configname;
+       int serrno;
+
+       _DIAGASSERT(context != NULL);
+
+       ctx = calloc(1, sizeof(struct hesiod_p));
+       if (ctx) {
+               *context = ctx;
+               /*
+                * don't permit overrides from environment
+                * for set.id programs
+                */
+               if (issetugid())
+                       configname = NULL;
+               else
+                       configname = getenv("HESIOD_CONFIG");
+               if (!configname)
+                       configname = _PATH_HESIOD_CONF;
+               if (read_config_file(ctx, configname) >= 0) {
+                       /*
+                        * The default rhs can be overridden by an
+                        * environment variable, unless set.id.
+                        */
+                       if (issetugid())
+                               p = NULL;
+                       else
+                               p = getenv("HES_DOMAIN");
+                       if (p) {
+                               if (ctx->rhs)
+                                       free(ctx->rhs);
+                               ctx->rhs = malloc(strlen(p) + 2);
+                               if (ctx->rhs) {
+                                       *ctx->rhs = '.';
+                                       strcpy(ctx->rhs + 1,
+                                           (*p == '.') ? p + 1 : p);
+                                       return 0;
+                               } else
+                                       errno = ENOMEM;
+                       } else
+                               return 0;
+               }
+       } else
+               errno = ENOMEM;
+
+       serrno = errno;
+       if (ctx) {
+               if (ctx->lhs)
+                       free(ctx->lhs);
+               if (ctx->rhs)
+                       free(ctx->rhs);
+               free(ctx);
+       }
+       errno = serrno;
+       return -1;
+}
+
+/*
+ * hesiod_end --
+ *     Deallocates the hesiod_p.
+ */
+void 
+hesiod_end(context)
+       void    *context;
+{
+       struct hesiod_p *ctx = (struct hesiod_p *) context;
+
+       _DIAGASSERT(context != NULL);
+
+       free(ctx->rhs);
+       if (ctx->lhs)
+               free(ctx->lhs);
+       free(ctx);
+}
+
+/*
+ * hesiod_to_bind --
+ *     takes a hesiod (name, type) and returns a DNS
+ *     name which is to be resolved.
+ */
+char *
+hesiod_to_bind(void *context, const char *name, const char *type)
+{
+       struct hesiod_p *ctx = (struct hesiod_p *) context;
+       char             bindname[MAXDNAME], *p, *ret, **rhs_list = NULL;
+       const char      *rhs;
+       size_t           len;
+
+       _DIAGASSERT(context != NULL);
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(type != NULL);
+
+        if (strlcpy(bindname, name, sizeof(bindname)) >= sizeof(bindname)) {
+                errno = EMSGSIZE;
+                return NULL;
+        }
+
+       /*
+        * Find the right right hand side to use, possibly
+        * truncating bindname.
+        */
+       p = strchr(bindname, '@');
+       if (p) {
+               *p++ = 0;
+               if (strchr(p, '.'))
+                       rhs = name + (p - bindname);
+               else {
+                       rhs_list = hesiod_resolve(context, p, "rhs-extension");
+                       if (rhs_list)
+                               rhs = *rhs_list;
+                       else {
+                               errno = ENOENT;
+                               return NULL;
+                       }
+               }
+       } else
+               rhs = ctx->rhs;
+
+       /* See if we have enough room. */
+       len = strlen(bindname) + 1 + strlen(type);
+       if (ctx->lhs)
+               len += strlen(ctx->lhs) + ((ctx->lhs[0] != '.') ? 1 : 0);
+       len += strlen(rhs) + ((rhs[0] != '.') ? 1 : 0);
+       if (len > sizeof(bindname) - 1) {
+               if (rhs_list)
+                       hesiod_free_list(context, rhs_list);
+               errno = EMSGSIZE;
+               return NULL;
+       }
+       /* Put together the rest of the domain. */
+       strlcat(bindname, ".", sizeof(bindname));
+       strlcat(bindname, type, sizeof(bindname));
+       /* Only append lhs if it isn't empty. */
+       if (ctx->lhs && ctx->lhs[0] != '\0' ) {
+               if (ctx->lhs[0] != '.')
+                       strlcat(bindname, ".", sizeof(bindname));
+               strlcat(bindname, ctx->lhs, sizeof(bindname));
+       }
+       if (rhs[0] != '.')
+               strlcat(bindname, ".", sizeof(bindname));
+       strlcat(bindname, rhs, sizeof(bindname));
+
+       /* rhs_list is no longer needed, since we're done with rhs. */
+       if (rhs_list)
+               hesiod_free_list(context, rhs_list);
+
+       /* Make a copy of the result and return it to the caller. */
+       ret = strdup(bindname);
+       if (ret == NULL)
+               errno = ENOMEM;
+       return ret;
+}
+
+/*
+ * hesiod_resolve --
+ *     Given a hesiod name and type, return an array of strings returned
+ *     by the resolver.
+ */
+char **
+hesiod_resolve(context, name, type)
+       void            *context;
+       const char      *name;
+       const char      *type;
+{
+       struct hesiod_p *ctx = (struct hesiod_p *) context;
+       char            *bindname, **retvec;
+
+       _DIAGASSERT(context != NULL);
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(type != NULL);
+
+       bindname = hesiod_to_bind(context, name, type);
+       if (!bindname)
+               return NULL;
+
+       retvec = get_txt_records(ctx->classes[0], bindname);
+       if (retvec == NULL && errno == ENOENT && ctx->classes[1])
+               retvec = get_txt_records(ctx->classes[1], bindname);
+
+       free(bindname);
+       return retvec;
+}
+
+/*ARGSUSED*/
+void 
+hesiod_free_list(context, list)
+       void     *context;
+       char    **list;
+{
+       char  **p;
+
+       _DIAGASSERT(context != NULL);
+
+       if (list == NULL)
+               return;
+       for (p = list; *p; p++)
+               free(*p);
+       free(list);
+}
+
+
+/* read_config_file --
+ *     Parse the /etc/hesiod.conf file.  Returns 0 on success,
+ *     -1 on failure.  On failure, it might leave values in ctx->lhs
+ *     or ctx->rhs which need to be freed by the caller.
+ */
+static int 
+read_config_file(ctx, filename)
+       struct hesiod_p *ctx;
+       const char      *filename;
+{
+       char    *key, *data, *p, **which;
+       char     buf[MAXDNAME + 7];
+       int      n;
+       FILE    *fp;
+
+       _DIAGASSERT(ctx != NULL);
+       _DIAGASSERT(filename != NULL);
+
+       /* Set default query classes. */
+       ctx->classes[0] = C_IN;
+       ctx->classes[1] = C_HS;
+
+       /* Try to open the configuration file. */
+       fp = fopen(filename, "r");
+       if (!fp) {
+               /* Use compiled in default domain names. */
+               ctx->lhs = strdup(DEF_LHS);
+               ctx->rhs = strdup(DEF_RHS);
+               if (ctx->lhs && ctx->rhs)
+                       return 0;
+               else {
+                       errno = ENOMEM;
+                       return -1;
+               }
+       }
+       ctx->lhs = NULL;
+       ctx->rhs = NULL;
+       while (fgets(buf, sizeof(buf), fp) != NULL) {
+               p = buf;
+               if (*p == '#' || *p == '\n' || *p == '\r')
+                       continue;
+               while (*p == ' ' || *p == '\t')
+                       p++;
+               key = p;
+               while (*p != ' ' && *p != '\t' && *p != '=' && *p)
+                       p++;
+
+               if (*p == '\0')
+                       continue;
+
+               *p++ = 0;
+
+               while (isspace((u_char) *p) || *p == '=')
+                       p++;
+
+               if (*p == '\0')
+                       continue;
+
+               data = p;
+               while (!isspace((u_char) *p) && *p)
+                       p++;
+
+               *p = 0;
+
+               if (strcasecmp(key, "lhs") == 0 ||
+                   strcasecmp(key, "rhs") == 0) {
+                       which = (strcasecmp(key, "lhs") == 0)
+                           ? &ctx->lhs : &ctx->rhs;
+                       *which = strdup(data);
+                       if (!*which) {
+                               errno = ENOMEM;
+                               (void)fclose(fp);
+                               return -1;
+                       }
+               } else {
+                       if (strcasecmp(key, "classes") == 0) {
+                               n = 0;
+                               while (*data && n < 2) {
+                                       p = data;
+                                       while (*p && *p != ',')
+                                               p++;
+                                       if (*p)
+                                               *p++ = 0;
+                                       if (strcasecmp(data, "IN") == 0)
+                                               ctx->classes[n++] = C_IN;
+                                       else
+                                               if (strcasecmp(data, "HS") == 0)
+                                                       ctx->classes[n++] =
+                                                           C_HS;
+                                       data = p;
+                               }
+                               while (n < 2)
+                                       ctx->classes[n++] = 0;
+                       }
+               }
+       }
+       fclose(fp);
+
+       if (!ctx->rhs || ctx->classes[0] == 0 ||
+           ctx->classes[0] == ctx->classes[1]) {
+               errno = ENOEXEC;
+               return -1;
+       }
+       return 0;
+}
+
+/*
+ * get_txt_records --
+ *     Given a DNS class and a DNS name, do a lookup for TXT records, and
+ *     return a list of them.
+ */
+static char **
+get_txt_records(qclass, name)
+       int              qclass;
+       const char      *name;
+{
+       HEADER          *hp;
+       unsigned char    qbuf[PACKETSZ], abuf[MAX_HESRESP], *p, *eom, *eor;
+       char            *dst, **list;
+       int              ancount, qdcount, i, j, n, skip, type, class, len;
+       res_state        res = __res_get_state();
+
+       if (res == NULL)
+               return NULL;
+
+       _DIAGASSERT(name != NULL);
+
+       /* Construct the query. */
+       n = res_nmkquery(res, QUERY, name, qclass, T_TXT, NULL, 0,
+           NULL, qbuf, PACKETSZ);
+       if (n < 0) {
+               errno = EMSGSIZE;
+               __res_put_state(res);
+               return NULL;
+       }
+
+       /* Send the query. */
+       n = res_nsend(res, qbuf, n, abuf, MAX_HESRESP);
+       __res_put_state(res);
+       if (n < 0) {
+               errno = ECONNREFUSED;
+               return NULL;
+       }
+       /* Parse the header of the result. */
+       hp = (HEADER *) (void *) abuf;
+       ancount = ntohs(hp->ancount);
+       qdcount = ntohs(hp->qdcount);
+       p = abuf + sizeof(HEADER);
+       eom = abuf + n;
+
+       /*
+        * Skip questions, trying to get to the answer section
+        * which follows.
+        */
+       for (i = 0; i < qdcount; i++) {
+               skip = dn_skipname(p, eom);
+               if (skip < 0 || p + skip + QFIXEDSZ > eom) {
+                       errno = EMSGSIZE;
+                       return NULL;
+               }
+               p += skip + QFIXEDSZ;
+       }
+
+       /* Allocate space for the text record answers. */
+       list = malloc((ancount + 1) * sizeof(char *));
+       if (!list) {
+               errno = ENOMEM;
+               return NULL;
+       }
+       /* Parse the answers. */
+       j = 0;
+       for (i = 0; i < ancount; i++) {
+               /* Parse the header of this answer. */
+               skip = dn_skipname(p, eom);
+               if (skip < 0 || p + skip + 10 > eom)
+                       break;
+               type = p[skip + 0] << 8 | p[skip + 1];
+               class = p[skip + 2] << 8 | p[skip + 3];
+               len = p[skip + 8] << 8 | p[skip + 9];
+               p += skip + 10;
+               if (p + len > eom) {
+                       errno = EMSGSIZE;
+                       break;
+               }
+               /* Skip entries of the wrong class and type. */
+               if (class != qclass || type != T_TXT) {
+                       p += len;
+                       continue;
+               }
+               /* Allocate space for this answer. */
+               list[j] = malloc((size_t)len);
+               if (!list[j]) {
+                       errno = ENOMEM;
+                       break;
+               }
+               dst = list[j++];
+
+               /* Copy answer data into the allocated area. */
+               eor = p + len;
+               while (p < eor) {
+                       n = (unsigned char) *p++;
+                       if (p + n > eor) {
+                               errno = EMSGSIZE;
+                               break;
+                       }
+                       memcpy(dst, p, (size_t)n);
+                       p += n;
+                       dst += n;
+               }
+               if (p < eor) {
+                       errno = EMSGSIZE;
+                       break;
+               }
+               *dst = 0;
+       }
+
+       /*
+        * If we didn't terminate the loop normally, something
+        * went wrong.
+        */
+       if (i < ancount) {
+               for (i = 0; i < j; i++)
+                       free(list[i]);
+               free(list);
+               return NULL;
+       }
+       if (j == 0) {
+               errno = ENOENT;
+               free(list);
+               return NULL;
+       }
+       list[j] = NULL;
+       return list;
+}
+
+/*
+ * COMPATIBILITY FUNCTIONS
+ */
+
+static int       inited = 0;
+static void     *context;
+static int       errval = HES_ER_UNINIT;
+
+int
+hes_init()
+{
+       init_context();
+       return errval;
+}
+
+char *
+hes_to_bind(name, type)
+       const char      *name;
+       const char      *type;
+{
+       static  char    *bindname;
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(type != NULL);
+
+       if (init_context() < 0)
+               return NULL;
+       if (bindname)
+               free(bindname);
+       bindname = hesiod_to_bind(context, name, type);
+       if (!bindname)
+               translate_errors();
+       return bindname;
+}
+
+char **
+hes_resolve(name, type)
+       const char      *name;
+       const char      *type;
+{
+       static char     **list;
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(type != NULL);
+
+       if (init_context() < 0)
+               return NULL;
+
+       /*
+        * In the old Hesiod interface, the caller was responsible for
+        * freeing the returned strings but not the vector of strings itself.
+        */
+       if (list)
+               free(list);
+
+       list = hesiod_resolve(context, name, type);
+       if (!list)
+               translate_errors();
+       return list;
+}
+
+int
+hes_error()
+{
+       return errval;
+}
+
+void
+hes_free(hp)
+       char **hp;
+{
+       hesiod_free_list(context, hp);
+}
+
+static int
+init_context()
+{
+       if (!inited) {
+               inited = 1;
+               if (hesiod_init(&context) < 0) {
+                       errval = HES_ER_CONFIG;
+                       return -1;
+               }
+               errval = HES_ER_OK;
+       }
+       return 0;
+}
+
+static void
+translate_errors()
+{
+       switch (errno) {
+       case ENOENT:
+               errval = HES_ER_NOTFOUND;
+               break;
+       case ECONNREFUSED:
+       case EMSGSIZE:
+               errval = HES_ER_NET;
+               break;
+       default:
+               /* Not a good match, but the best we can do. */
+               errval = HES_ER_CONFIG;
+               break;
+       }
+}
diff --git a/lib/nbsd_libc/net/if_indextoname.3 b/lib/nbsd_libc/net/if_indextoname.3
new file mode 100644 (file)
index 0000000..6b27d19
--- /dev/null
@@ -0,0 +1,138 @@
+.\"    $NetBSD: if_indextoname.3,v 1.12 2010/03/22 19:30:54 joerg Exp $
+.\"    $KAME: if_indextoname.3,v 1.10 2000/11/24 08:13:51 itojun Exp $
+.\"    BSDI    Id: if_indextoname.3,v 2.2 2000/04/17 22:38:05 dab Exp
+.\"
+.\" Copyright (c) 1997, 2000
+.\"    Berkeley Software Design, Inc.  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.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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.
+.\"
+.Dd March 11, 2005
+.Dt IF_NAMETOINDEX 3
+.Os
+.Sh NAME
+.Nm if_nametoindex ,
+.Nm if_indextoname ,
+.Nm if_nameindex ,
+.Nm if_freenameindex
+.Nd provide mappings between interface names and indexes
+.Sh SYNOPSIS
+.In net/if.h
+.Ft unsigned int
+.Fn if_nametoindex "const char *ifname"
+.Ft char *
+.Fn if_indextoname "unsigned int ifindex" "char *ifname"
+.Ft struct if_nameindex *
+.Fn if_nameindex "void"
+.Ft void
+.Fn if_freenameindex "struct if_nameindex *ptr"
+.Sh DESCRIPTION
+The
+.Fn if_nametoindex
+function maps the interface name specified in
+.Ar ifname
+to its corresponding index.
+If the specified interface does not exist, it returns 0.
+.Pp
+The
+.Fn if_indextoname
+function maps the interface index specified in
+.Ar ifindex
+to it corresponding name, which is copied into the
+buffer pointed to by
+.Ar ifname ,
+which must be of at least IFNAMSIZ bytes.
+This pointer is also the return value of the function.
+If there is no interface corresponding to the specified
+index, NULL is returned.
+.Pp
+The
+.Fn if_nameindex
+function returns an array of
+.Nm if_nameindex
+structures, one structure per interface, as
+defined in the include file
+.In net/if.h .
+The
+.Nm if_nameindex
+structure contains at least the following entries:
+.Bd -literal
+    unsigned int   if_index;  /* 1, 2, ... */
+    char          *if_name;   /* null terminated name: "le0", ... */
+.Ed
+.Pp
+The end of the array of structures is indicated by a structure with an
+.Nm if_index
+of 0 and an
+.Nm if_name
+of NULL.
+A NULL pointer is returned upon an error.
+.Pp
+The
+.Fn if_freenameindex
+function frees the dynamic memory that was
+allocated by
+.Fn if_nameindex .
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn if_nametoindex
+returns the index number of the interface.
+If the interface is not found, a value of 0 is returned and
+.Va errno
+is set to
+.Er ENXIO .
+A value of 0 is also returned if an error
+occurs while retrieving the list of interfaces via
+.Xr getifaddrs 3 .
+.Pp
+Upon successful completion,
+.Fn if_indextoname
+returns
+.Ar ifname .
+If the interface is not found, a NULL pointer is returned and
+.Va errno
+is set to
+.Er ENXIO .
+A NULL pointer is also returned if an error
+occurs while retrieving the list of interfaces via
+.Xr getifaddrs 3 .
+.Pp
+The
+.Fn if_nameindex
+returns a NULL pointer if an error
+occurs while retrieving the list of interfaces via
+.Xr getifaddrs 3 ,
+or if sufficient memory cannot be allocated.
+.Sh SEE ALSO
+.Xr getifaddrs 3 ,
+.Xr networking 4
+.Sh STANDARDS
+The
+.Fn if_nametoindex ,
+.Fn if_indextoname ,
+.Fn if_nameindex ,
+and
+.Fn if_freenameindex
+functions conform to
+.St -p1003.1-2001 ,
+.St -xns5.2 ,
+and RFC 3493.
+.Sh HISTORY
+The implementation first appeared in
+.Bsx .
diff --git a/lib/nbsd_libc/net/if_indextoname.c b/lib/nbsd_libc/net/if_indextoname.c
new file mode 100644 (file)
index 0000000..32877bb
--- /dev/null
@@ -0,0 +1,101 @@
+/*     $NetBSD: if_indextoname.c,v 1.7 2010/12/13 23:10:12 pooka Exp $ */
+/*     $KAME: if_indextoname.c,v 1.7 2000/11/08 03:09:30 itojun Exp $  */
+
+/*-
+ * Copyright (c) 1997, 2000
+ *     Berkeley Software Design, Inc.  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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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.
+ *
+ *     BSDI Id: if_indextoname.c,v 2.3 2000/04/17 22:38:05 dab Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: if_indextoname.c,v 1.7 2010/12/13 23:10:12 pooka Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifndef RUMP_ACTION
+#include "namespace.h"
+#endif
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <net/if_dl.h>
+#include <net/if.h>
+#include <ifaddrs.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#ifndef RUMP_ACTION
+#ifdef __weak_alias
+__weak_alias(if_indextoname,_if_indextoname)
+#endif
+#endif
+
+/*
+ * From RFC 2533:
+ *
+ * The second function maps an interface index into its corresponding
+ * name.
+ *
+ *    #include <net/if.h>
+ *
+ *    char  *if_indextoname(unsigned int ifindex, char *ifname);
+ *
+ * The ifname argument must point to a buffer of at least IF_NAMESIZE
+ * bytes into which the interface name corresponding to the specified
+ * index is returned.  (IF_NAMESIZE is also defined in <net/if.h> and
+ * its value includes a terminating null byte at the end of the
+ * interface name.) This pointer is also the return value of the
+ * function.  If there is no interface corresponding to the specified
+ * index, NULL is returned, and errno is set to ENXIO, if there was a
+ * system error (such as running out of memory), if_indextoname returns
+ * NULL and errno would be set to the proper value (e.g., ENOMEM).
+ */
+
+char *
+if_indextoname(unsigned int ifindex, char *ifname)
+{
+       struct ifaddrs *ifaddrs, *ifa;
+       int error = 0;
+
+       if (getifaddrs(&ifaddrs) < 0)
+               return(NULL);   /* getifaddrs properly set errno */
+
+       for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
+               if (ifa->ifa_addr &&
+                   ifa->ifa_addr->sa_family == AF_LINK &&
+                   ifindex == ((struct sockaddr_dl*)
+                       (void *)ifa->ifa_addr)->sdl_index)
+                       break;
+       }
+
+       if (ifa == NULL) {
+               error = ENXIO;
+               ifname = NULL;
+       }
+       else
+               strlcpy(ifname, ifa->ifa_name, IFNAMSIZ);
+
+       freeifaddrs(ifaddrs);
+
+       errno = error;
+       return(ifname);
+}
diff --git a/lib/nbsd_libc/net/if_nameindex.c b/lib/nbsd_libc/net/if_nameindex.c
new file mode 100644 (file)
index 0000000..2be5a28
--- /dev/null
@@ -0,0 +1,156 @@
+/*     $NetBSD: if_nameindex.c,v 1.6 2000/12/20 18:47:11 christos Exp $        */
+/*     $KAME: if_nameindex.c,v 1.8 2000/11/24 08:20:01 itojun Exp $    */
+
+/*-
+ * Copyright (c) 1997, 2000
+ *     Berkeley Software Design, Inc.  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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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.
+ *
+ *     BSDI Id: if_nameindex.c,v 2.3 2000/04/17 22:38:05 dab Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: if_nameindex.c,v 1.6 2000/12/20 18:47:11 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <net/if_dl.h>
+#include <net/if.h>
+#include <ifaddrs.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(if_nameindex,_if_nameindex)
+__weak_alias(if_freenameindex,_if_freenameindex)
+#endif
+/*
+ * From RFC 2553:
+ *
+ * 4.3 Return All Interface Names and Indexes
+ *
+ *    The if_nameindex structure holds the information about a single
+ *    interface and is defined as a result of including the <net/if.h>
+ *    header.
+ *
+ *       struct if_nameindex {
+ *         unsigned int   if_index;
+ *         char          *if_name;
+ *       };
+ *
+ *    The final function returns an array of if_nameindex structures, one
+ *    structure per interface.
+ *
+ *       struct if_nameindex  *if_nameindex(void);
+ *
+ *    The end of the array of structures is indicated by a structure with
+ *    an if_index of 0 and an if_name of NULL.  The function returns a NULL
+ *    pointer upon an error, and would set errno to the appropriate value.
+ *
+ *    The memory used for this array of structures along with the interface
+ *    names pointed to by the if_name members is obtained dynamically.
+ *    This memory is freed by the next function.
+ *
+ * 4.4.  Free Memory
+ *
+ *    The following function frees the dynamic memory that was allocated by
+ *    if_nameindex().
+ *
+ *        #include <net/if.h>
+ *
+ *        void  if_freenameindex(struct if_nameindex *ptr);
+ *
+ *    The argument to this function must be a pointer that was returned by
+ *    if_nameindex().
+ */
+
+struct if_nameindex *
+if_nameindex(void)
+{
+       struct ifaddrs *ifaddrs, *ifa;
+       unsigned int ni;
+       int nbytes;
+       struct if_nameindex *ifni, *ifni2;
+       char *cp;
+
+       if (getifaddrs(&ifaddrs) < 0)
+               return(NULL);
+
+       /*
+        * First, find out how many interfaces there are, and how
+        * much space we need for the string names.
+        */
+       ni = 0;
+       nbytes = 0;
+       for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
+               if (ifa->ifa_addr &&
+                   ifa->ifa_addr->sa_family == AF_LINK) {
+                       nbytes += strlen(ifa->ifa_name) + 1;
+                       ni++;
+               }
+       }
+
+       /*
+        * Next, allocate a chunk of memory, use the first part
+        * for the array of structures, and the last part for
+        * the strings.
+        */
+       cp = malloc((ni + 1) * sizeof(struct if_nameindex) + nbytes);
+       ifni = (struct if_nameindex *)(void *)cp;
+       if (ifni == NULL)
+               goto out;
+       cp += (ni + 1) * sizeof(struct if_nameindex);
+
+       /*
+        * Now just loop through the list of interfaces again,
+        * filling in the if_nameindex array and making copies
+        * of all the strings.
+        */
+       ifni2 = ifni;
+       for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
+               if (ifa->ifa_addr &&
+                   ifa->ifa_addr->sa_family == AF_LINK) {
+                       ifni2->if_index =
+                           ((struct sockaddr_dl*)
+                           (void *)ifa->ifa_addr)->sdl_index;
+                       ifni2->if_name = cp;
+                       strcpy(cp, ifa->ifa_name);
+                       ifni2++;
+                       cp += strlen(cp) + 1;
+               }
+       }
+       /*
+        * Finally, don't forget to terminate the array.
+        */
+       ifni2->if_index = 0;
+       ifni2->if_name = NULL;
+out:
+       freeifaddrs(ifaddrs);
+       return(ifni);
+}
+
+void
+if_freenameindex(struct if_nameindex *ptr)
+{
+       free(ptr);
+}
diff --git a/lib/nbsd_libc/net/if_nametoindex.c b/lib/nbsd_libc/net/if_nametoindex.c
new file mode 100644 (file)
index 0000000..3e8297d
--- /dev/null
@@ -0,0 +1,92 @@
+/*     $NetBSD: if_nametoindex.c,v 1.4 2000/11/24 08:21:12 itojun Exp $        */
+/*     $KAME: if_nametoindex.c,v 1.6 2000/11/24 08:18:54 itojun Exp $  */
+
+/*-
+ * Copyright (c) 1997, 2000
+ *     Berkeley Software Design, Inc.  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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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.
+ *
+ *     BSDI Id: if_nametoindex.c,v 2.3 2000/04/17 22:38:05 dab Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: if_nametoindex.c,v 1.4 2000/11/24 08:21:12 itojun Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <net/if.h>
+#include <net/if_dl.h>
+#include <ifaddrs.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#ifdef __weak_alias
+__weak_alias(if_nametoindex,_if_nametoindex)
+#endif
+
+/*
+ * From RFC 2553:
+ *
+ * 4.1 Name-to-Index
+ *
+ *
+ *    The first function maps an interface name into its corresponding
+ *    index.
+ *
+ *       #include <net/if.h>
+ *
+ *       unsigned int  if_nametoindex(const char *ifname);
+ *
+ *    If the specified interface name does not exist, the return value is
+ *    0, and errno is set to ENXIO.  If there was a system error (such as
+ *    running out of memory), the return value is 0 and errno is set to the
+ *    proper value (e.g., ENOMEM).
+ */
+
+unsigned int
+if_nametoindex(const char *ifname)
+{
+       struct ifaddrs *ifaddrs, *ifa;
+       unsigned int ni;
+
+       if (getifaddrs(&ifaddrs) < 0)
+               return(0);
+
+       ni = 0;
+
+       for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
+               if (ifa->ifa_addr &&
+                   ifa->ifa_addr->sa_family == AF_LINK &&
+                   strcmp(ifa->ifa_name, ifname) == 0) {
+                       ni = ((struct sockaddr_dl*)
+                           (void *)ifa->ifa_addr)->sdl_index;
+                       break;
+               }
+       }
+
+       freeifaddrs(ifaddrs);
+       if (!ni)
+               errno = ENXIO;
+       return(ni);
+}
diff --git a/lib/nbsd_libc/net/inet6_opt_init.3 b/lib/nbsd_libc/net/inet6_opt_init.3
new file mode 100644 (file)
index 0000000..c5350a9
--- /dev/null
@@ -0,0 +1,337 @@
+.\"    $NetBSD: inet6_opt_init.3,v 1.1 2006/05/05 00:03:21 rpaulo Exp $
+.\"    $KAME: inet6_opt_init.3,v 1.7 2004/12/27 05:08:23 itojun Exp $
+.\"
+.\" Copyright (C) 2004 WIDE Project.
+.\" 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.
+.\" 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
+.\"
+.Dd December 23, 2004
+.Dt INET6_OPT_INIT 3
+.Os
+.\"
+.Sh NAME
+.Nm inet6_opt_init ,
+.Nm inet6_opt_append ,
+.Nm inet6_opt_finish ,
+.Nm inet6_opt_set_val ,
+.Nm inet6_opt_next ,
+.Nm inet6_opt_find ,
+.Nm inet6_opt_get_val
+.Nd IPv6 Hop-by-Hop and Destination Options manipulation
+.\"
+.Sh SYNOPSIS
+.In netinet/in.h
+.Ft "int"
+.Fn inet6_opt_init "void *extbuf" "socklen_t extlen"
+.Ft "int"
+.Fn inet6_opt_append "void *extbuf" "socklen_t extlen" "int offset" "u_int8_t type" "socklen_t len" "u_int8_t align" "void **databufp"
+.Ft "int"
+.Fn inet6_opt_finish "void *extbuf" "socklen_t extlen" "int offset"
+.Ft "int"
+.Fn inet6_opt_set_val "void *databuf" "int offset" "void *val" "socklen_t vallen"
+.Ft "int"
+.Fn inet6_opt_next "void *extbuf" "socklen_t extlen" "int offset" "u_int8_t *typep" "socklen_t *lenp" "void **databufp"
+.Ft "int"
+.Fn inet6_opt_find "void *extbuf" "socklen_t extlen" "int offset" "u_int8_t type" "socklen_t *lenp" "void **databufp"
+.Ft "int"
+.Fn inet6_opt_get_val "void *databuf" "socklen_t offset" "void *val" "socklen_t vallen"
+.\"
+.Sh DESCRIPTION
+Building and parsing the Hop-by-Hop and Destination options is
+complicated.
+The advanced sockets API defines a set of functions to
+help applications create and manipulate Hop-by-Hope and Destination
+options.
+.\"This man page describes the functions specified in
+.\"IETF Draft RFC3542 while the
+.\".Xr inet6_options_space 3
+.\"man page documents the functions defined in RFC 2292.
+.\"It is expected
+.\"that this set of functions will supersede those in RFC 2292 but for
+.\"the time being both APIs are retained.
+These functions use the
+formatting rules specified in Appendix B in RFC2460, i.e., that the
+largest field is placed last in the option.
+The function prototypes
+for these functions are all contained in the
+.In netinet/in.h
+header file.
+.\"
+.Ss inet6_opt_init
+The
+.Fn inet6_opt_init
+function
+returns the number of bytes needed for an empty
+extension header, one without any options.
+If the
+.Va extbuf
+argument points to a valid section of memory
+then the
+.Fn inet6_opt_init
+function also initializes the extension header's length field.
+When attempting to initialize an extension buffer passed in the
+.Va extbuf argument
+.Fa extlen
+must be a positive multiple of 8 or else the function fails and
+returns \-1 to the caller.
+.\"
+.Ss inet6_opt_append
+The
+.Fn inet6_opt_append
+function can perform to different jobs.
+When a valid
+.Fa extbuf
+argument is supplied it appends an option to the extension buffer and
+returns the updated total length as well as a pointer to the newly
+created option in
+.Fa databufp .
+If the value
+of
+.Fa extbuf
+is
+.Dv NULL
+then the
+.Fn inet6_opt_append function only reports what the total length would
+be if the option were actually appended.
+The
+.Fa len
+and
+.Fa align
+arguments specify the length of the option and the required data
+alignment which must be used when appending the option.
+The
+.Fa offset
+argument should be the length returned by the
+.Fn inet6_opt_init
+function or a previous call to
+.Fn inet6_opt_append .
+.Pp
+The
+.Fa type
+argument is the 8-bit option type.
+.Pp
+After
+.Fn inet6_opt_append
+has been called, the application can use the buffer pointed to by
+.Fa databufp
+directly, or use
+.Fn inet6_opt_set_val
+to specify the data to be contained in the option.
+.Pp
+Option types of
+.Li 0
+and
+.Li 1
+are reserved for the
+.Li Pad1
+and
+.Li PadN
+options.
+All other values from 2 through 255 may be used by applications.
+.Pp
+The length of the option data is contained in an 8-bit value and so
+may contain any value from 0 through 255.
+.Pp
+The
+.Fa align
+parameter must have a value of 1, 2, 4, or 8 and cannot exceed the
+value of
+.Fa len .
+The alignment values represent no alignment, 16 bit, 32 bit and 64 bit
+alignments respectively.
+.\"
+.Ss inet6_opt_finish
+The
+.Fn inet6_opt_finish
+calculates the final padding necessary to make the extension header a
+multiple of 8 bytes, as required by the IPv6 extension header
+specification, and returns the extension header's updated total
+length.
+The
+.Fa offset
+argument should be the length returned by
+.Fn inet6_opt_init
+or
+.Fn inet6_opt_append .
+When
+.Fa extbuf
+is not
+.Dv NULL
+the function also sets up the appropriate padding bytes by inserting a
+Pad1 or PadN option of the proper length.
+.Pp
+If the extension header is too small to contain the proper padding
+then an error of \-1 is returned to the caller.
+.\"
+.Ss inet6_opt_set_val
+The
+.Fn inet6_opt_set_val
+function inserts data items of various sizes into the data portion of
+the option.
+The
+.Fa databuf
+argument is a pointer to memory that was returned by the
+.Fn inet6_opt_append
+call and the
+.Fa offset argument specifies where the option should be placed in the
+data buffer.
+The
+.Fa val
+argument points to an area of memory containing the data to be
+inserted into the extension header, and the
+.Fa vallen
+argument indicates how much data to copy.
+.Pp
+The caller should ensure that each field is aligned on its natural
+boundaries as described in Appendix B of RFC2460.
+.Pp
+The function returns the offset for the next field which is calculated as
+.Fa offset
++
+.Fa vallen
+and is used when composing options with multiple fields.
+.\"
+.Ss inet6_opt_next
+The
+.Fn inet6_opt_next
+function parses received extension headers.
+The
+.Fa extbuf
+and
+.Fa extlen
+arguments specify the location and length of the extension header
+being parsed.
+The
+.Fa offset
+argument should either be zero, for the first option, or the length value
+returned by a previous call to
+.Fn inet6_opt_next
+or
+.Fn inet6_opt_find .
+The return value specifies the position where to continue scanning the
+extension buffer.
+The option is returned in the arguments
+.Fa typep , lenp ,
+and
+.Fa databufp .
+.Fa typep, lenp,
+and
+.Fa databufp
+point to the 8-bit option type, the 8-bit option length and the option
+data respectively.
+This function does not return any PAD1 or PADN options.
+When an error occurs or there are no more options the return
+value is \-1.
+.\"
+.Ss inet6_opt_find
+The
+.Fn inet6_opt_find
+function searches the extension buffer for a particular option type,
+passed in through the
+.Fa type
+argument.
+If the option is found then the
+.Fa lenp
+and
+.Fa databufp
+arguments are updated to point to the option's length and data
+respectively.
+.Fa extbuf
+and
+.Fa extlen
+must point to a valid extension buffer and give its length.
+The
+.Fa offset
+argument can be used to search from a location anywhere in the
+extension header.
+.Ss inet6_opt_get_val
+The
+.Fn inet6_opt_get_val
+function extracts data items of various sizes in the data portion of
+the option.
+The
+.Fa databuf
+is a pointer returned by the
+.Fn inet6_opt_next
+or
+.Fn inet6_opt_find
+functions.
+The
+.Fa val
+argument points where the data will be extracted.
+The
+.Fa offset
+argument specifies from where in the data portion of the option the
+value should be extracted; the first byte of option data is specified
+by an offset of zero.
+.Pp
+It is expected that each field is aligned on its natural boundaries as
+described in Appendix B of RFC2460.
+.Pp
+The function returns the offset for the next field
+by calculating
+.Fa offset
++
+.Fa vallen
+which can be used when extracting option content with multiple fields.
+Robust receivers must verify alignment before calling this function.
+.\"
+.Sh DIAGNOSTICS
+All the functions return
+\-1
+on an error.
+.\"
+.Sh EXAMPLES
+RFC3542 gives comprehensive examples in Section 23.
+.Pp
+KAME also provides examples in the
+.Pa advapitest
+directory of its kit.
+.\"
+.Sh SEE ALSO
+.Rs
+.%A W. Stevens
+.%A M. Thomas
+.%A E. Nordmark
+.%A T. Jinmei
+.%T "Advanced Sockets API for IPv6"
+.%N RFC3542
+.%D October 2002
+.Re
+.Rs
+.%A S. Deering
+.%A R. Hinden
+.%T "Internet Protocol, Version 6 (IPv6) Specification"
+.%N RFC2460
+.%D December 1998
+.Re
+.Sh HISTORY
+The implementation first appeared in KAME advanced networking kit.
+.Sh STANDARDS
+The functions are documented in
+.Dq Advanced Sockets API for IPv6
+.Pq RFC3542 .
+.\"
diff --git a/lib/nbsd_libc/net/inet6_option_space.3 b/lib/nbsd_libc/net/inet6_option_space.3
new file mode 100644 (file)
index 0000000..28aadac
--- /dev/null
@@ -0,0 +1,448 @@
+.\"    $NetBSD: inet6_option_space.3,v 1.17 2010/03/22 19:30:54 joerg Exp $
+.\"    $KAME: inet6_option_space.3,v 1.7 2000/05/17 14:32:13 itojun Exp $
+.\"
+.\" Copyright (c) 1983, 1987, 1991, 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.
+.\" 3. 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.
+.\"
+.Dd December 10, 1999
+.Dt INET6_OPTION_SPACE 3
+.Os
+.\"
+.Sh NAME
+.Nm inet6_option_space ,
+.Nm inet6_option_init ,
+.Nm inet6_option_append ,
+.Nm inet6_option_alloc ,
+.Nm inet6_option_next ,
+.Nm inet6_option_find
+.Nd IPv6 Hop-by-Hop and Destination Options manipulation
+.\"
+.Sh SYNOPSIS
+.In netinet/in.h
+.Ft "int"
+.Fn inet6_option_space "int nbytes"
+.Ft "int"
+.Fn inet6_option_init "void *bp" "struct cmsghdr **cmsgp" "int type"
+.Ft "int"
+.Fn inet6_option_append "struct cmsghdr *cmsg" "const uint8_t *typep" "int multx" "int plusy"
+.Ft "uint8_t *"
+.Fn inet6_option_alloc "struct cmsghdr *cmsg" "int datalen" "int multx" "int plusy"
+.Ft "int"
+.Fn inet6_option_next "const struct cmsghdr *cmsg" "uint8_t **tptrp"
+.Ft "int"
+.Fn inet6_option_find "const struct cmsghdr *cmsg" "uint8_t **tptrp" "int type"
+.\"
+.Sh DESCRIPTION
+.\"
+Building and parsing the Hop-by-Hop and Destination options is
+complicated due to alignment constraints, padding and
+ancillary data manipulation.
+RFC 2292 defines a set of functions to help the application.
+The function prototypes for
+these functions are all in the
+.In netinet/in.h
+header.
+.\"
+.Ss inet6_option_space
+.Fn inet6_option_space
+returns the number of bytes required to hold an option when it is stored as
+ancillary data, including the
+.Li cmsghdr
+structure at the beginning,
+and any padding at the end
+.Po
+to make its size a multiple of 8 bytes
+.Pc .
+The argument is the size of the structure defining the option,
+which must include any pad bytes at the beginning
+.Po
+the value
+.Li y
+in the alignment term
+.Dq Li xn + y
+.Pc ,
+the type byte, the length byte, and the option data.
+.Pp
+Note: If multiple options are stored in a single ancillary data
+object, which is the recommended technique, this function
+overestimates the amount of space required by the size of
+.Li N-1
+.Li cmsghdr
+structures,
+where
+.Li N
+is the number of options to be stored in the object.
+This is of little consequence, since it is assumed that most
+Hop-by-Hop option headers and Destination option headers carry only
+one option
+.Pq appendix B of [RFC 2460] .
+.\"
+.Ss inet6_option_init
+.Fn inet6_option_init
+is called once per ancillary data object that will
+contain either Hop-by-Hop or Destination options.
+It returns
+.Li 0
+on success or
+.Li -1
+on an error.
+.Pp
+.Fa bp
+is a pointer to previously allocated space that will contain the
+ancillary data object.
+It must be large enough to contain all the
+individual options to be added by later calls to
+.Fn inet6_option_append
+and
+.Fn inet6_option_alloc .
+.Pp
+.Fa cmsgp
+is a pointer to a pointer to a
+.Li cmsghdr
+structure.
+.Fa *cmsgp
+is initialized by this function to point to the
+.Li cmsghdr
+structure constructed by this function in the buffer pointed to by
+.Fa bp .
+.Pp
+.Fa type
+is either
+.Dv IPV6_HOPOPTS
+or
+.Dv IPV6_DSTOPTS .
+This
+.Fa type
+is stored in the
+.Li cmsg_type
+member of the
+.Li cmsghdr
+structure pointed to by
+.Fa *cmsgp .
+.\"
+.Ss inet6_option_append
+This function appends a Hop-by-Hop option or a Destination option
+into an ancillary data object that has been initialized by
+.Fn inet6_option_init .
+This function returns
+.Li 0
+if it succeeds or
+.Li -1
+on an error.
+.Pp
+.Fa cmsg
+is a pointer to the
+.Li cmsghdr
+structure that must have been
+initialized by
+.Fn inet6_option_init .
+.Pp
+.Fa typep
+is a pointer to the 8-bit option type.
+It is assumed that this
+field is immediately followed by the 8-bit option data length field,
+which is then followed immediately by the option data.
+The caller
+initializes these three fields
+.Pq the type-length-value, or TLV
+before calling this function.
+.Pp
+The option type must have a value from
+.Li 2
+to
+.Li 255 ,
+inclusive.
+.Po
+.Li 0
+and
+.Li 1
+are reserved for the
+.Li Pad1
+and
+.Li PadN
+options, respectively.
+.Pc
+.Pp
+The option data length must have a value between
+.Li 0
+and
+.Li 255 ,
+inclusive, and is the length of the option data that follows.
+.Pp
+.Fa multx
+is the value
+.Li x
+in the alignment term
+.Dq Li xn + y .
+It must have a value of
+.Li 1 ,
+.Li 2 ,
+.Li 4 ,
+or
+.Li 8 .
+.Pp
+.Fa plusy
+is the value
+.Li y
+in the alignment term
+.Dq Li xn + y .
+It must have a value between
+.Li 0
+and
+.Li 7 ,
+inclusive.
+.\"
+.Ss inet6_option_alloc
+This function appends a Hop-by-Hop option or a Destination option
+into an ancillary data object that has been initialized by
+.Fn inet6_option_init .
+This function returns a pointer to the 8-bit
+option type field that starts the option on success, or
+.Dv NULL
+on an error.
+.Pp
+The difference between this function and
+.Fn inet6_option_append
+is that the latter copies the contents of a previously built option into
+the ancillary data object while the current function returns a
+pointer to the space in the data object where the option's TLV must
+then be built by the caller.
+.Pp
+.Fa cmsg
+is a pointer to the
+.Li cmsghdr
+structure that must have been
+initialized by
+.Fn inet6_option_init .
+.Pp
+.Fa datalen
+is the value of the option data length byte for this option.
+This value is required as an argument to allow the function to
+determine if padding must be appended at the end of the option.
+.Po
+The
+.Fn inet6_option_append
+function does not need a data length argument
+since the option data length must already be stored by the caller.
+.Pc
+.Pp
+.Fa multx
+is the value
+.Li x
+in the alignment term
+.Dq Li xn + y .
+It must have a value of
+.Li 1 ,
+.Li 2 ,
+.Li 4 ,
+or
+.Li 8 .
+.Pp
+.Fa plusy
+is the value
+.Li y
+in the alignment term
+.Dq Li xn + y .
+It must have a value between
+.Li 0
+and
+.Li 7 ,
+inclusive.
+.\"
+.Ss inet6_option_next
+This function processes the next Hop-by-Hop option or Destination
+option in an ancillary data object.
+If another option remains to be
+processed, the return value of the function is
+.Li 0
+and
+.Fa *tptrp
+points to
+the 8-bit option type field
+.Po
+which is followed by the 8-bit option
+data length, followed by the option data
+.Pc .
+If no more options remain
+to be processed, the return value is
+.Li -1
+and
+.Fa *tptrp
+is
+.Dv NULL .
+If an error occurs, the return value is
+.Li -1
+and
+.Fa *tptrp
+is not
+.Dv NULL .
+.Pp
+.Fa cmsg
+is a pointer to
+.Li cmsghdr
+structure of which
+.Li cmsg_level
+equals
+.Dv IPPROTO_IPV6
+and
+.Li cmsg_type
+equals either
+.Dv IPV6_HOPOPTS
+or
+.Dv IPV6_DSTOPTS .
+.Pp
+.Fa tptrp
+is a pointer to a pointer to an 8-bit byte and
+.Fa *tptrp
+is used
+by the function to remember its place in the ancillary data object
+each time the function is called.
+The first time this function is
+called for a given ancillary data object,
+.Fa *tptrp
+must be set to
+.Dv NULL .
+.Pp
+Each time this function returns success,
+.Fa *tptrp
+points to the 8-bit
+option type field for the next option to be processed.
+.\"
+.Ss inet6_option_find
+This function is similar to the previously described
+.Fn inet6_option_next
+function, except this function lets the caller
+specify the option type to be searched for, instead of always
+returning the next option in the ancillary data object.
+.Fa cmsg
+is a
+pointer to
+.Li cmsghdr
+structure of which
+.Li cmsg_level
+equals
+.Dv IPPROTO_IPV6
+and
+.Li cmsg_type
+equals either
+.Dv IPV6_HOPOPTS
+or
+.Dv IPV6_DSTOPTS .
+.Pp
+.Fa tptrp
+is a pointer to a pointer to an 8-bit byte and
+.Fa *tptrp
+is used
+by the function to remember its place in the ancillary data object
+each time the function is called.
+The first time this function is
+called for a given ancillary data object,
+.Fa *tptrp
+must be set to
+.Dv NULL .
+.Pa
+This function starts searching for an option of the specified type
+beginning after the value of
+.Fa *tptrp .
+If an option of the specified
+type is located, this function returns
+.Li 0
+and
+.Fa *tptrp
+points to the 8-
+bit option type field for the option of the specified type.
+If an
+option of the specified type is not located, the return value is
+.Li -1
+and
+.Fa *tptrp
+is
+.Dv NULL .
+If an error occurs, the return value is
+.Li -1
+and
+.Fa *tptrp
+is not
+.Dv NULL .
+.\"
+.Sh EXAMPLES
+RFC 2292 gives comprehensive examples in chapter 6.
+.\"
+.Sh DIAGNOSTICS
+.Fn inet6_option_init
+and
+.Fn inet6_option_append
+return
+.Li 0
+on success or
+.Li -1
+on an error.
+.Pp
+.Fn inet6_option_alloc
+returns
+.Dv NULL
+on an error.
+.Pp
+On errors,
+.Fn inet6_option_next
+and
+.Fn inet6_option_find
+return
+.Li -1
+setting
+.Fa *tptrp
+to non
+.Dv NULL
+value.
+.\"
+.Sh SEE ALSO
+.Rs
+.%A W. Stevens
+.%A M. Thomas
+.%T "Advanced Sockets API for IPv6"
+.%N RFC 2292
+.%D February 1998
+.Re
+.Rs
+.%A S. Deering
+.%A R. Hinden
+.%T "Internet Protocol, Version 6 (IPv6) Specification"
+.%N RFC 2460
+.%D December 1998
+.Re
+.\"
+.Sh STANDARDS
+The functions
+are documented in
+.Dq Advanced Sockets API for IPv6
+.Pq RFC 2292 .
+.\"
+.Sh HISTORY
+The implementation first appeared in KAME advanced networking kit.
+.\"
+.Sh BUGS
+The text was shamelessly copied from RFC 2292.
diff --git a/lib/nbsd_libc/net/inet6_rth_space.3 b/lib/nbsd_libc/net/inet6_rth_space.3
new file mode 100644 (file)
index 0000000..6aac100
--- /dev/null
@@ -0,0 +1,223 @@
+.\"    $NetBSD: inet6_rth_space.3,v 1.1 2006/05/05 00:03:21 rpaulo Exp $
+.\"    $KAME: inet6_rth_space.3,v 1.7 2005/01/05 03:00:44 itojun Exp $
+.\"
+.\" Copyright (C) 2004 WIDE Project.
+.\" 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.
+.\" 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
+.\"
+.Dd December 24, 2004
+.Dt INET6_RTH_SPACE 3
+.Os
+.\"
+.Sh NAME
+.Nm inet6_rth_space ,
+.Nm inet6_rth_init ,
+.Nm inet6_rth_add ,
+.Nm inet6_rth_reverse ,
+.Nm inet6_rth_segments ,
+.Nm inet6_rth_getaddr
+.Nd IPv6 Routing Header Options manipulation
+.\"
+.Sh SYNOPSIS
+.In netinet/in.h
+.Ft socklen_t
+.Fn inet6_rth_space "int" "int"
+.Ft "void *"
+.Fn inet6_rth_init "void *" "socklen_t" "int" "int"
+.Ft int
+.Fn inet6_rth_add "void *" "const struct in6_addr *"
+.Ft int
+.Fn inet6_rth_reverse "const void *" "void *"
+.Ft int
+.Fn inet6_rth_segments "const void *"
+.Ft "struct in6_addr *"
+.Fn inet6_rth_getaddr "const void *" "int"
+.\"
+.Sh DESCRIPTION
+The IPv6 Advanced API, RFC 3542, defines the functions that an
+application calls to build and examine IPv6 Routing headers.
+Routing headers are used to perform source routing in IPv6 networks.
+The RFC uses the word 
+.Dq segments
+to describe addresses and that is the term used here as well.
+All of the functions are defined in the
+.In netinet/in.h
+header file.
+The functions described in this manual page all operate
+on routing header structures which are defined in
+.In netinet/ip6.h
+but which should not need to be modified outside the use of this API.
+The size and shape of the route header structures may change, so using
+the APIs is a more portable, long term, solution.
+.Pp
+The functions in the API are split into two groups, those that build a
+routing header and those that parse a received routing header.
+We will describe the builder functions followed by the parser functions.
+.Ss inet6_rth_space
+The
+.Fn inet6_rth_space
+function returns the number of bytes required to hold a Routing Header
+of the type, specified in the
+.Fa type 
+argument and containing the number of addresses specified in the
+.Fa segments
+argumment.
+When the type is 
+.Dv IPV6_RTHDR_TYPE_0
+the number of segments must be from 0 through 127.
+Routing headers of type 
+.Dv IPV6_RTHDR_TYPE_2
+contain only one segment, and are only used with Mobile IPv6.
+The return value from this function is the number of bytes required to
+store the routing header.
+If the value 0 is returned then either the
+route header type was not recognized or another error occurred.
+.Ss inet6_rth_init
+The
+.Fn inet6_rth_init
+function initializes the pre-allocated buffer pointed to by
+.Fa bp
+to contain a routing header of the specified type The
+.Fa bp_len
+argument is used to verify that the buffer is large enough.
+The caller must allocate the buffer pointed to by bp.
+The necessary buffer size should be determined by calling
+.Fn inet6_rth_space
+described in the previous sections.
+.Pp
+The
+.Fn inet6_rth_init
+function returns a pointer to
+.Fa bp
+on success and
+.Dv NULL
+when there is an error.
+.Ss inet6_rth_add
+The
+.Fn inet6_rth_add
+function adds the IPv6 address pointed to by
+.Fa addr
+to the end of the routing header being constructed.
+.Pp
+A successful addition results in the function returning 0, otherwise
+\-1 is returned.
+.Ss inet6_rth_reverse
+The
+.Fn inet6_rth_reverse
+function takes a routing header, pointed to by the
+argument
+.Fa in ,
+and writes a new routing header into the argument pointed to by
+.Fa out .
+The routing header at that sends datagrams along the reverse of that
+route.
+Both arguments are allowed to point to the same buffer meaning
+that the reversal can occur in place.
+.Pp
+The return value of the function is 0 on success, or \-1 when
+there is an error.
+.\"
+.Pp
+The next set of functions operate on a routing header that the
+application wants to parse.
+In the usual case such a routing header
+is received from the network, although these functions can also be
+used with routing headers that the application itself created.
+.Ss inet6_rth_segments
+The
+.Fn inet6_rth_segments
+function returns the number of segments contained in the
+routing header pointed to by
+.Fa bp .
+The return value is the number of segments contained in the routing
+header, or \-1 if an error occurred.
+It is not an error for 0 to be
+returned as a routing header may contain 0 segments.
+.\"
+.Ss inet6_rth_getaddr
+The
+.Fn inet6_rth_getaddr
+function is used to retrieve a single address from a routing header.
+The
+.Fa index
+is the location in the routing header from which the application wants
+to retrieve an address.
+The 
+.Fa index 
+parameter must have a value between 0 and one less than the number of
+segments present in the routing header.
+The
+.Fn inet6_rth_segments 
+function, described in the last section, should be used to determine
+the total number of segments in the routing header.
+The
+.Fn inet6_rth_getaddr
+function returns a pointer to an IPv6 address on success or 
+.Dv NULL
+when an error has occurred.
+.\"
+.Sh DIAGNOSTICS
+The
+.Fn inet6_rth_space
+and
+.Fn inet6_rth_getaddr
+functions return 0 on errors.
+.Pp
+The
+.Fn inet6_rthdr_init
+function returns
+.Dv NULL
+on error.
+The
+.Fn inet6_rth_add
+and
+.Fn inet6_rth_reverse
+functions return 0 on success, or \-1 upon an error.
+.\"
+.Sh EXAMPLES
+RFC 3542 gives extensive examples in Section 21, Appendix B.
+.Pp
+KAME also provides examples in the advapitest directory of its kit.
+.\"
+.Sh SEE ALSO
+.Rs
+.%A W. Stevens
+.%A M. Thomas
+.%A E. Nordmark
+.%A T. Jinmei
+.%T "Advanced Sockets API for IPv6"
+.%N RFC 3542
+.%D May 2003
+.Re
+.Rs
+.%A S. Deering
+.%A R. Hinden
+.%T "Internet Protocol, Version 6 (IPv6) Specification"
+.%N RFC2460
+.%D December 1998
+.Re
+.Sh HISTORY
+The implementation first appeared in KAME advanced networking kit.
diff --git a/lib/nbsd_libc/net/inet6_rthdr_space.3 b/lib/nbsd_libc/net/inet6_rthdr_space.3
new file mode 100644 (file)
index 0000000..1d9a043
--- /dev/null
@@ -0,0 +1,321 @@
+.\"    $NetBSD: inet6_rthdr_space.3,v 1.16 2010/03/22 19:30:54 joerg Exp $
+.\"    $KAME: inet6_rthdr_space.3,v 1.8 2000/05/17 14:30:15 itojun Exp $
+.\"
+.\" Copyright (c) 1983, 1987, 1991, 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.
+.\" 3. 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.
+.\"
+.Dd December 10, 1999
+.Dt INET6_RTHDR_SPACE 3
+.Os
+.\"
+.Sh NAME
+.Nm inet6_rthdr_space ,
+.Nm inet6_rthdr_init ,
+.Nm inet6_rthdr_add ,
+.Nm inet6_rthdr_lasthop ,
+.Nm inet6_rthdr_reverse ,
+.Nm inet6_rthdr_segments ,
+.Nm inet6_rthdr_getaddr ,
+.Nm inet6_rthdr_getflags
+.Nd IPv6 Routing Header Options manipulation
+.\"
+.Sh SYNOPSIS
+.In netinet/in.h
+.Ft size_t
+.Fn inet6_rthdr_space "int type" "int segments"
+.Ft "struct cmsghdr *"
+.Fn inet6_rthdr_init "void *bp" "int type"
+.Ft int
+.Fn inet6_rthdr_add "struct cmsghdr *cmsg" "const struct in6_addr *addr" "unsigned int flags"
+.Ft int
+.Fn inet6_rthdr_lasthop "struct cmsghdr *cmsg" "unsigned int flags"
+.Ft int
+.Fn inet6_rthdr_reverse "const struct cmsghdr *in" "struct cmsghdr *out"
+.Ft int
+.Fn inet6_rthdr_segments "const struct cmsghdr *cmsg"
+.Ft "struct in6_addr *"
+.Fn inet6_rthdr_getaddr "struct cmsghdr *cmsg" "int index"
+.Ft int
+.Fn inet6_rthdr_getflags "const struct cmsghdr *cmsg" "int index"
+.\"
+.Sh DESCRIPTION
+RFC 2292 IPv6 advanced API defines eight
+functions that the application calls to build and examine a Routing
+header.
+Four functions build a Routing header:
+.Bl -hang
+.It Fn inet6_rthdr_space
+return #bytes required for ancillary data
+.It Fn inet6_rthdr_init
+initialize ancillary data for Routing header
+.It Fn inet6_rthdr_add
+add IPv6 address \*[Am] flags to Routing header
+.It Fn inet6_rthdr_lasthop
+specify the flags for the final hop
+.El
+.Pp
+Four functions deal with a returned Routing header:
+.Bl -hang
+.It Fn inet6_rthdr_reverse
+reverse a Routing header
+.It Fn inet6_rthdr_segments
+return #segments in a Routing header
+.It Fn inet6_rthdr_getaddr
+fetch one address from a Routing header
+.It Fn inet6_rthdr_getflags
+fetch one flag from a Routing header
+.El
+.Pp
+The function prototypes for these functions are all in the
+.In netinet/in.h
+header.
+.\"
+.Ss inet6_rthdr_space
+This function returns the number of bytes required to hold a Routing
+header of the specified
+.Fa type
+containing the specified number of
+.Fa segments
+.Pq addresses .
+For an IPv6 Type 0 Routing header, the number
+of segments must be between 1 and 23, inclusive.
+The return value
+includes the size of the cmsghdr structure that precedes the Routing
+header, and any required padding.
+.Pp
+If the return value is 0, then either the type of the Routing header
+is not supported by this implementation or the number of segments is
+invalid for this type of Routing header.
+.Pp
+Note: This function returns the size but does not allocate the space
+required for the ancillary data.
+This allows an application to
+allocate a larger buffer, if other ancillary data objects are
+desired, since all the ancillary data objects must be specified to
+.Xr sendmsg 2
+as a single
+.Li msg_control
+buffer.
+.\"
+.Ss inet6_rthdr_init
+This function initializes the buffer pointed to by
+.Fa bp
+to contain a
+.Li cmsghdr
+structure followed by a Routing header of the specified
+.Fa type .
+The
+.Li cmsg_len
+member of the
+.Li cmsghdr
+structure is initialized to the
+size of the structure plus the amount of space required by the
+Routing header.
+The
+.Li cmsg_level
+and
+.Li cmsg_type
+members are also initialized as required.
+.Pp
+The caller must allocate the buffer and its size can be determined by
+calling
+.Fn inet6_rthdr_space .
+.Pp
+Upon success the return value is the pointer to the
+.Li cmsghdr
+structure, and this is then used as the first argument to the next
+two functions.
+Upon an error the return value is
+.Dv NULL .
+.\"
+.Ss inet6_rthdr_add
+This function adds the address pointed to by
+.Fa addr
+to the end of the
+Routing header being constructed and sets the type of this hop to the
+value of
+.Fa flags .
+For an IPv6 Type 0 Routing header,
+.Fa flags
+must be
+either
+.Dv IPV6_RTHDR_LOOSE
+or
+.Dv IPV6_RTHDR_STRICT .
+.Pp
+If successful, the
+.Li cmsg_len
+member of the
+.Li cmsghdr
+structure is
+updated to account for the new address in the Routing header and the
+return value of the function is 0.
+Upon an error the return value of
+the function is -1.
+.\"
+.Ss inet6_rthdr_lasthop
+This function specifies the Strict/Loose flag for the final hop of a
+Routing header.
+For an IPv6 Type 0 Routing header,
+.Fa flags
+must be either
+.Dv IPV6_RTHDR_LOOSE
+or
+.Dv IPV6_RTHDR_STRICT .
+.Pp
+The return value of the function is 0 upon success, or -1 upon an error.
+.Pp
+Notice that a Routing header specifying
+.Li N
+intermediate nodes requires
+.Li N+1
+Strict/Loose flags.
+This requires
+.Li N
+calls to
+.Fn inet6_rthdr_add
+followed by one call to
+.Fn inet6_rthdr_lasthop .
+.\"
+.Ss inet6_rthdr_reverse
+This function takes a Routing header that was received as ancillary
+data
+.Po
+pointed to by the first argument,
+.Fa in
+.Pc
+and writes a new Routing
+header that sends datagrams along the reverse of that route.
+Both
+arguments are allowed to point to the same buffer
+.Pq that is, the reversal can occur in place .
+.Pp
+The return value of the function is 0 on success, or -1 upon an
+error.
+.\"
+.Ss inet6_rthdr_segments
+This function returns the number of segments
+.Pq addresses
+contained in
+the Routing header described by
+.Fa cmsg .
+On success the return value is
+between 1 and 23, inclusive.
+The return value of the function is -1 upon an error.
+.\"
+.Ss inet6_rthdr_getaddr
+This function returns a pointer to the IPv6 address specified by
+.Fa index
+.Po
+which must have a value between 1 and the value returned by
+.Fn inet6_rthdr_segments
+.Pc
+in the Routing header described by
+.Fa cmsg .
+An
+application should first call
+.Fn inet6_rthdr_segments
+to obtain the number of segments in the Routing header.
+.Pp
+Upon an error the return value of the function is
+.Dv NULL .
+.\"
+.Ss inet6_rthdr_getflags
+This function returns the flags value specified by
+.Fa index
+.Po
+which must
+have a value between 0 and the value returned by
+.Fn inet6_rthdr_segments
+.Pc
+in the Routing header described by
+.Fa cmsg .
+For an IPv6 Type 0 Routing header the return value will be either
+.Dv IPV6_RTHDR_LOOSE
+or
+.Dv IPV6_RTHDR_STRICT .
+.Pp
+Upon an error the return value of the function is -1.
+.Pp
+Note: Addresses are indexed starting at 1, and flags starting at 0,
+to maintain consistency with the terminology and figures in RFC 2460.
+.\"
+.Sh EXAMPLES
+RFC 2292 gives comprehensive examples in chapter 8.
+.\"
+.Sh DIAGNOSTICS
+.Fn inet6_rthdr_space
+returns 0 on errors.
+.Pp
+.Fn inet6_rthdr_add ,
+.Fn inet6_rthdr_lasthop
+and
+.Fn inet6_rthdr_reverse
+return 0 on success, and returns -1 on error.
+.Pp
+.Fn inet6_rthdr_init
+and
+.Fn inet6_rthdr_getaddr
+return
+.Dv NULL
+on error.
+.Pp
+.Fn inet6_rthdr_segments
+and
+.Fn inet6_rthdr_getflags
+return -1 on error.
+.\"
+.Sh SEE ALSO
+.Rs
+.%A W. Stevens
+.%A M. Thomas
+.%T "Advanced Sockets API for IPv6"
+.%N RFC 2292
+.%D February 1998
+.Re
+.Rs
+.%A S. Deering
+.%A R. Hinden
+.%T "Internet Protocol, Version 6 (IPv6) Specification"
+.%N RFC 2460
+.%D December 1998
+.Re
+.\"
+.Sh STANDARDS
+The functions
+are documented in
+.Dq Advanced Sockets API for IPv6
+.Pq RFC 2292 .
+.\"
+.Sh HISTORY
+The implementation first appeared in KAME advanced networking kit.
+.\"
+.Sh BUGS
+The text was shamelessly copied from RFC 2292.
+.Pp
+.Fn inet6_rthdr_reverse
+is not implemented yet.
diff --git a/lib/nbsd_libc/net/ip6opt.c b/lib/nbsd_libc/net/ip6opt.c
new file mode 100644 (file)
index 0000000..f7a9380
--- /dev/null
@@ -0,0 +1,658 @@
+/*     $NetBSD: ip6opt.c,v 1.12 2009/01/30 23:43:30 lukem Exp $        */
+
+/*
+ * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
+ * 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.
+ * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ip6opt.c,v 1.12 2009/01/30 23:43:30 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <netinet/in.h>
+#include <netinet/ip6.h>
+
+#include <assert.h>
+#include <string.h>
+#include <stdio.h>
+
+#ifdef __weak_alias
+__weak_alias(inet6_option_alloc,_inet6_option_alloc)
+__weak_alias(inet6_option_append,_inet6_option_append)
+__weak_alias(inet6_option_find,_inet6_option_find)
+__weak_alias(inet6_option_init,_inet6_option_init)
+__weak_alias(inet6_option_next,_inet6_option_next)
+__weak_alias(inet6_option_space,_inet6_option_space)
+__weak_alias(inet6_opt_init, _inet6_opt_init)
+__weak_alias(inet6_opt_append, _inet6_opt_append)
+__weak_alias(inet6_opt_finish, _inet6_opt_finish)
+__weak_alias(inet6_opt_set_val, _inet6_opt_set_val)
+__weak_alias(inet6_opt_next, _inet6_opt_next)
+__weak_alias(inet6_opt_find, _inet6_opt_find)
+__weak_alias(inet6_opt_get_val, _inet6_opt_get_val)
+#endif
+
+static int ip6optlen(u_int8_t *opt, u_int8_t *lim);
+static void inet6_insert_padopt(u_char *p, size_t len);
+
+/*
+ * This function returns the number of bytes required to hold an option
+ * when it is stored as ancillary data, including the cmsghdr structure
+ * at the beginning, and any padding at the end (to make its size a
+ * multiple of 8 bytes).  The argument is the size of the structure
+ * defining the option, which must include any pad bytes at the
+ * beginning (the value y in the alignment term "xn + y"), the type
+ * byte, the length byte, and the option data.
+ */
+int
+inet6_option_space(nbytes)
+       int nbytes;
+{
+       nbytes += 2;    /* we need space for nxt-hdr and length fields */
+       return(CMSG_SPACE((nbytes + 7) & ~7));
+}
+
+/*
+ * This function is called once per ancillary data object that will
+ * contain either Hop-by-Hop or Destination options.  It returns 0 on
+ * success or -1 on an error.
+ */
+int
+inet6_option_init(bp, cmsgp, type)
+       void *bp;
+       struct cmsghdr **cmsgp;
+       int type;
+{
+       register struct cmsghdr *ch;
+
+       _DIAGASSERT(bp != NULL);
+       _DIAGASSERT(cmsgp != NULL);
+
+       ch = (struct cmsghdr *)bp;
+
+       /* argument validation */
+       if (type != IPV6_HOPOPTS && type != IPV6_DSTOPTS)
+               return(-1);
+       
+       ch->cmsg_level = IPPROTO_IPV6;
+       ch->cmsg_type = type;
+       ch->cmsg_len = CMSG_LEN(0);
+
+       *cmsgp = ch;
+       return(0);
+}
+
+/*
+ * This function appends a Hop-by-Hop option or a Destination option
+ * into an ancillary data object that has been initialized by
+ * inet6_option_init().  This function returns 0 if it succeeds or -1 on
+ * an error.
+ * multx is the value x in the alignment term "xn + y" described
+ * earlier.  It must have a value of 1, 2, 4, or 8.
+ * plusy is the value y in the alignment term "xn + y" described
+ * earlier.  It must have a value between 0 and 7, inclusive.
+ */
+int
+inet6_option_append(cmsg, typep, multx, plusy)
+       struct cmsghdr *cmsg;
+       const u_int8_t *typep;
+       int multx;
+       int plusy;
+{
+       size_t padlen, optlen, off;
+       register u_char *bp;
+       struct ip6_ext *eh;
+
+       _DIAGASSERT(cmsg != NULL);
+       _DIAGASSERT(typep != NULL);
+
+       bp = (u_char *)(void *)cmsg + cmsg->cmsg_len;
+       eh = (struct ip6_ext *)(void *)CMSG_DATA(cmsg);
+
+       /* argument validation */
+       if (multx != 1 && multx != 2 && multx != 4 && multx != 8)
+               return(-1);
+       if (plusy < 0 || plusy > 7)
+               return(-1);
+
+       /*
+        * If this is the first option, allocate space for the
+        * first 2 bytes(for next header and length fields) of
+        * the option header.
+        */
+       if (bp == (u_char *)(void *)eh) {
+               bp += 2;
+               cmsg->cmsg_len += 2;
+       }
+
+       /* calculate pad length before the option. */
+       off = bp - (u_char *)(void *)eh;
+       padlen = (((off % multx) + (multx - 1)) & ~(multx - 1)) -
+               (off % multx);
+       padlen += plusy;
+       padlen %= multx;        /* keep the pad as short as possible */
+       /* insert padding */
+       inet6_insert_padopt(bp, padlen);
+       cmsg->cmsg_len += padlen;
+       bp += padlen;
+
+       /* copy the option */
+       if (typep[0] == IP6OPT_PAD1)
+               optlen = 1;
+       else
+               optlen = typep[1] + 2;
+       memcpy(bp, typep, (size_t)optlen);
+       bp += optlen;
+       cmsg->cmsg_len += optlen;
+
+       /* calculate pad length after the option and insert the padding */
+       off = bp - (u_char *)(void *)eh;
+       padlen = ((off + 7) & ~7) - off;
+       inet6_insert_padopt(bp, padlen);
+       bp += padlen;
+       cmsg->cmsg_len += padlen;
+
+       /* update the length field of the ip6 option header */
+       off = bp - (u_char *)(void *)eh;
+       eh->ip6e_len = (off >> 3) - 1;
+
+       return(0);
+}
+
+/*
+ * This function appends a Hop-by-Hop option or a Destination option
+ * into an ancillary data object that has been initialized by
+ * inet6_option_init().  This function returns a pointer to the 8-bit
+ * option type field that starts the option on success, or NULL on an
+ * error.
+ * The difference between this function and inet6_option_append() is
+ * that the latter copies the contents of a previously built option into
+ * the ancillary data object while the current function returns a
+ * pointer to the space in the data object where the option's TLV must
+ * then be built by the caller.
+ * 
+ */
+u_int8_t *
+inet6_option_alloc(cmsg, datalen, multx, plusy)
+       struct cmsghdr *cmsg;
+       int datalen;
+       int multx;
+       int plusy;
+{
+       size_t padlen, off;
+       register u_int8_t *bp;
+       u_int8_t *retval;
+       struct ip6_ext *eh;
+
+       _DIAGASSERT(cmsg != NULL);
+
+       bp = (u_char *)(void *)cmsg + cmsg->cmsg_len;
+       eh = (struct ip6_ext *)(void *)CMSG_DATA(cmsg);
+
+       /* argument validation */
+       if (multx != 1 && multx != 2 && multx != 4 && multx != 8)
+               return(NULL);
+       if (plusy < 0 || plusy > 7)
+               return(NULL);
+
+       /*
+        * If this is the first option, allocate space for the
+        * first 2 bytes(for next header and length fields) of
+        * the option header.
+        */
+       if (bp == (u_char *)(void *)eh) {
+               bp += 2;
+               cmsg->cmsg_len += 2;
+       }
+
+       /* calculate pad length before the option. */
+       off = bp - (u_char *)(void *)eh;
+       padlen = (((off % multx) + (multx - 1)) & ~(multx - 1)) -
+               (off % multx);
+       padlen += plusy;
+       padlen %= multx;        /* keep the pad as short as possible */
+       /* insert padding */
+       inet6_insert_padopt(bp, padlen);
+       cmsg->cmsg_len += padlen;
+       bp += padlen;
+
+       /* keep space to store specified length of data */
+       retval = bp;
+       bp += datalen;
+       cmsg->cmsg_len += datalen;
+
+       /* calculate pad length after the option and insert the padding */
+       off = bp - (u_char *)(void *)eh;
+       padlen = ((off + 7) & ~7) - off;
+       inet6_insert_padopt(bp, padlen);
+       bp += padlen;
+       cmsg->cmsg_len += padlen;
+
+       /* update the length field of the ip6 option header */
+       off = bp - (u_char *)(void *)eh;
+       eh->ip6e_len = (off >> 3) - 1;
+
+       return(retval);
+}
+
+/*
+ * This function processes the next Hop-by-Hop option or Destination
+ * option in an ancillary data object.  If another option remains to be
+ * processed, the return value of the function is 0 and *tptrp points to
+ * the 8-bit option type field (which is followed by the 8-bit option
+ * data length, followed by the option data).  If no more options remain
+ * to be processed, the return value is -1 and *tptrp is NULL.  If an
+ * error occurs, the return value is -1 and *tptrp is not NULL.
+ * (RFC 2292, 6.3.5)
+ */
+int
+inet6_option_next(cmsg, tptrp)
+       const struct cmsghdr *cmsg;
+       u_int8_t **tptrp;
+{
+       struct ip6_ext *ip6e;
+       int hdrlen, optlen;
+       u_int8_t *lim;
+
+       _DIAGASSERT(cmsg != NULL);
+       _DIAGASSERT(tptrp != NULL);
+
+       if (cmsg->cmsg_level != IPPROTO_IPV6 ||
+           (cmsg->cmsg_type != IPV6_HOPOPTS &&
+            cmsg->cmsg_type != IPV6_DSTOPTS))
+               return(-1);
+
+       /* message length validation */
+       if (cmsg->cmsg_len < CMSG_SPACE(sizeof(struct ip6_ext)))
+               return(-1);
+       ip6e = __UNCONST(CCMSG_DATA(cmsg));
+       hdrlen = (ip6e->ip6e_len + 1) << 3;
+       if (cmsg->cmsg_len < CMSG_SPACE(hdrlen))
+               return(-1);
+
+       /*
+        * If the caller does not specify the starting point,
+        * simply return the 1st option.
+        * Otherwise, search the option list for the next option.
+        */
+       lim = (u_int8_t *)(void *)ip6e + hdrlen;
+       if (*tptrp == NULL)
+               *tptrp = (u_int8_t *)(void *)(ip6e + 1);
+       else {
+               if ((optlen = ip6optlen(*tptrp, lim)) == 0)
+                       return(-1);
+
+               *tptrp = *tptrp + optlen;
+       }
+       if (*tptrp >= lim) {    /* there is no option */
+               *tptrp = NULL;
+               return(-1);
+       }
+       /*
+        * Finally, checks if the next option is safely stored in the
+        * cmsg data.
+        */
+       if (ip6optlen(*tptrp, lim) == 0)
+               return(-1);
+       else
+               return(0);
+}
+
+/*
+ * This function is similar to the inet6_option_next() function,
+ * except this function lets the caller specify the option type to be
+ * searched for, instead of always returning the next option in the
+ * ancillary data object.
+ * Note: RFC 2292 says the type of tptrp is u_int8_t *, but we think
+ *       it's a typo. The variable should be type of u_int8_t **.
+ */
+int
+inet6_option_find(cmsg, tptrp, type)
+       const struct cmsghdr *cmsg;
+       u_int8_t **tptrp;
+       int type;
+{
+       struct ip6_ext *ip6e;
+       int hdrlen, optlen;
+       u_int8_t *optp, *lim;
+
+       _DIAGASSERT(cmsg != NULL);
+       _DIAGASSERT(tptrp != NULL);
+
+       if (cmsg->cmsg_level != IPPROTO_IPV6 ||
+           (cmsg->cmsg_type != IPV6_HOPOPTS &&
+            cmsg->cmsg_type != IPV6_DSTOPTS))
+               return(-1);
+
+       /* message length validation */
+       if (cmsg->cmsg_len < CMSG_SPACE(sizeof(struct ip6_ext)))
+               return(-1);
+       ip6e = __UNCONST(CCMSG_DATA(cmsg));
+       hdrlen = (ip6e->ip6e_len + 1) << 3;
+       if (cmsg->cmsg_len < CMSG_SPACE(hdrlen))
+               return(-1);     
+
+       /*
+        * If the caller does not specify the starting point,
+        * search from the beginning of the option list.
+        * Otherwise, search from *the next option* of the specified point.
+        */
+       lim = (u_int8_t *)(void *)ip6e + hdrlen;
+       if (*tptrp == NULL)
+               *tptrp = (u_int8_t *)(void *)(ip6e + 1);
+       else {
+               if ((optlen = ip6optlen(*tptrp, lim)) == 0)
+                       return(-1);
+
+               *tptrp = *tptrp + optlen;
+       }
+       for (optp = *tptrp; optp < lim; optp += optlen) {
+               if (*optp == type) {
+                       *tptrp = optp;
+                       return(0);
+               }
+               if ((optlen = ip6optlen(optp, lim)) == 0)
+                       return(-1);
+       }
+
+       /* search failed */
+       *tptrp = NULL;
+       return(-1);
+}
+
+/*
+ * Calculate the length of a given IPv6 option. Also checks
+ * if the option is safely stored in user's buffer according to the
+ * calculated length and the limitation of the buffer.
+ */
+static int
+ip6optlen(opt, lim)
+       u_int8_t *opt, *lim;
+{
+       int optlen;
+
+       _DIAGASSERT(opt != NULL);
+       _DIAGASSERT(lim != NULL);
+
+       if (*opt == IP6OPT_PAD1)
+               optlen = 1;
+       else {
+               /* is there enough space to store type and len? */
+               if (opt + 2 > lim)
+                       return(0);
+               optlen = *(opt + 1) + 2;
+       }
+       if (opt + optlen <= lim)
+               return(optlen);
+
+       return(0);
+}
+
+static void
+inet6_insert_padopt(u_char *p, size_t len)
+{
+
+       _DIAGASSERT(p != NULL);
+
+       switch(len) {
+        case 0:
+                return;
+        case 1:
+                p[0] = IP6OPT_PAD1;
+                return;
+        default:
+                p[0] = IP6OPT_PADN;
+                p[1] = len - 2; 
+                memset(&p[2], 0, len - 2);
+                return;
+       }
+}
+
+/*
+ * The following functions are defined in RFC3542, which is a successor
+ * of RFC2292.
+ */
+
+int
+inet6_opt_init(void *extbuf, socklen_t extlen)
+{
+       struct ip6_ext *ext = (struct ip6_ext *)extbuf;
+
+       if (extlen % 8)
+               return (-1);
+
+       if (ext) {
+               if (extlen == 0)
+                       return (-1);
+               ext->ip6e_len = (extlen >> 3) - 1;
+       }
+
+       return (2);             /* sizeof the next and the length fields */
+}
+
+int
+inet6_opt_append(void *extbuf, socklen_t extlen, int offset, u_int8_t type,
+                socklen_t len, u_int8_t align, void **databufp)
+{
+       int currentlen = offset;
+       size_t padlen = 0;
+
+       /*
+        * The option type must have a value from 2 to 255, inclusive.
+        * (0 and 1 are reserved for the Pad1 and PadN options, respectively.)
+        */
+       if (type < 2)
+               return (-1);
+
+       /*
+        * The option data length must have a value between 0 and 255,
+        * inclusive, and is the length of the option data that follows.
+        */
+       if (len > 255)
+               return (-1);
+
+       /*
+        * The align parameter must have a value of 1, 2, 4, or 8.
+        * The align value can not exceed the value of len.
+        */
+       if (align != 1 && align != 2 && align != 4 && align != 8)
+               return (-1);
+       if (align > len)
+               return (-1);
+
+       /* Calculate the padding length. */
+       currentlen += 2 + len;  /* 2 means "type + len" */
+       if (currentlen % align)
+               padlen = align - (currentlen % align);
+
+       /* The option must fit in the extension header buffer. */
+       currentlen += padlen;
+       if (extlen &&           /* XXX: right? */
+           (socklen_t)currentlen > extlen)
+               return (-1);
+
+       if (extbuf) {
+               u_int8_t *optp = (u_int8_t *)extbuf + offset;
+
+               if (padlen == 1) {
+                       /* insert a Pad1 option */
+                       *optp = IP6OPT_PAD1;
+                       optp++;
+               } else if (padlen > 0) {
+                       /* insert a PadN option for alignment */
+                       *optp++ = IP6OPT_PADN;
+                       *optp++ = padlen - 2;
+                       memset(optp, 0, padlen - 2);
+                       optp += (padlen - 2);
+               }
+
+               *optp++ = type;
+               *optp++ = len;
+
+               *databufp = optp;
+       }
+
+       return (currentlen);
+}
+
+int
+inet6_opt_finish(void *extbuf, socklen_t extlen, int offset)
+{
+       int updatelen = offset > 0 ? (1 + ((offset - 1) | 7)) : 0;
+
+       if (extbuf) {
+               u_int8_t *padp;
+               size_t padlen = updatelen - offset;
+
+               if ((socklen_t)updatelen > extlen)
+                       return (-1);
+
+               padp = (u_int8_t *)extbuf + offset;
+               if (padlen == 1)
+                       *padp = IP6OPT_PAD1;
+               else if (padlen > 0) {
+                       *padp++ = IP6OPT_PADN;
+                       *padp++ = (padlen - 2);
+                       memset(padp, 0, padlen - 2);
+               }
+       }
+
+       return (updatelen);
+}
+
+int
+inet6_opt_set_val(void *databuf, int offset, void *val, socklen_t vallen)
+{
+
+       memcpy((u_int8_t *)databuf + offset, val, vallen);
+       return (offset + vallen);
+}
+
+int
+inet6_opt_next(void *extbuf, socklen_t extlen, int offset, u_int8_t *typep,
+              socklen_t *lenp, void **databufp)
+{
+       u_int8_t *optp, *lim;
+       int optlen;
+
+       /* Validate extlen. XXX: is the variable really necessary?? */
+       if (extlen == 0 || (extlen % 8))
+               return (-1);
+       lim = (u_int8_t *)extbuf + extlen;
+
+       /*
+        * If this is the first time this function called for this options
+        * header, simply return the 1st option.
+        * Otherwise, search the option list for the next option.
+        */
+       if (offset == 0)
+               optp = (u_int8_t *)(void *)((struct ip6_hbh *)extbuf + 1);
+       else
+               optp = (u_int8_t *)extbuf + offset;
+
+       /* Find the next option skipping any padding options. */
+       while (optp < lim) {
+               switch(*optp) {
+               case IP6OPT_PAD1:
+                       optp++;
+                       break;
+               case IP6OPT_PADN:
+                       if ((optlen = ip6optlen(optp, lim)) == 0)
+                               goto optend;
+                       optp += optlen;
+                       break;
+               default:        /* found */
+                       if ((optlen = ip6optlen(optp, lim)) == 0)
+                               goto optend;
+                       *typep = *optp;
+                       *lenp = optlen - 2;
+                       *databufp = optp + 2;
+                       return (optp + optlen - (u_int8_t *)extbuf);
+               }
+       }
+
+  optend:
+       *databufp = NULL; /* for safety */
+       return (-1);
+}
+
+int
+inet6_opt_find(void *extbuf, socklen_t extlen, int offset, u_int8_t type,
+              socklen_t *lenp, void **databufp)
+{
+       u_int8_t *optp, *lim;
+       int optlen;
+
+       /* Validate extlen. XXX: is the variable really necessary?? */
+       if (extlen == 0 || (extlen % 8))
+               return (-1);
+       lim = (u_int8_t *)extbuf + extlen;
+
+       /*
+        * If this is the first time this function called for this options
+        * header, simply return the 1st option.
+        * Otherwise, search the option list for the next option.
+        */
+       if (offset == 0)
+               optp = (u_int8_t *)(void *)((struct ip6_hbh *)extbuf + 1);
+       else
+               optp = (u_int8_t *)extbuf + offset;
+
+       /* Find the specified option */
+       while (optp < lim) {
+               if ((optlen = ip6optlen(optp, lim)) == 0)
+                       goto optend;
+
+               if (*optp == type) { /* found */
+                       *lenp = optlen - 2;
+                       *databufp = optp + 2;
+                       return (optp + optlen - (u_int8_t *)extbuf);
+               }
+
+               optp += optlen;
+       }
+
+  optend:
+       *databufp = NULL; /* for safety */
+       return (-1);
+}
+
+int
+inet6_opt_get_val(void *databuf, int offset, void *val, socklen_t vallen)
+{
+
+       /* we can't assume alignment here */
+       memcpy(val, (u_int8_t *)databuf + offset, vallen);
+
+       return (offset + vallen);
+}
diff --git a/lib/nbsd_libc/net/iso_addr.3 b/lib/nbsd_libc/net/iso_addr.3
new file mode 100644 (file)
index 0000000..d8cd185
--- /dev/null
@@ -0,0 +1,110 @@
+.\"    $NetBSD: iso_addr.3,v 1.9 2009/04/11 15:32:03 joerg Exp $
+.\"
+.\" Copyright (c) 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.
+.\" 3. 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.
+.\"
+.\"     @(#)iso_addr.3 8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt ISO_ADDR 3
+.Os
+.Sh NAME
+.Nm iso_addr ,
+.Nm iso_ntoa
+.Nd elementary network address conversion routines for Open System Interconnection
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In netiso/iso.h
+.Ft struct iso_addr *
+.Fn iso_addr "const char *cp"
+.Ft char *
+.Fn iso_ntoa "struct iso_addr *isoa"
+.Sh DESCRIPTION
+The routine
+.Fn iso_addr
+interprets character strings representing
+.Tn OSI
+addresses, returning binary information suitable
+for use in system calls.
+The routine
+.Fn iso_ntoa
+takes
+.Tn OSI
+addresses and returns
+.Tn ASCII
+strings representing NSAPs (network service
+access points) in a
+notation inverse to that accepted by
+.Fn iso_addr .
+.Pp
+Unfortunately, no universal standard exists for representing
+.Tn OSI
+network addresses.
+.Pp
+The format employed by
+.Fn iso_addr
+is a sequence of hexadecimal
+.Dq digits
+(optionally separated by periods),
+of the form:
+.Bd -filled -offset indent
+\*[Lt]hex digits\*[Gt].\*[Lt]hex digits\*[Gt].\*[Lt]hex digits\*[Gt]
+.Ed
+.Pp
+Each pair of hexadecimal digits represents a byte
+with the leading digit indicating the higher-ordered bits.
+A period following an even number of bytes has no
+effect (but may be used to increase legibility).
+A period following an odd number of bytes has the
+effect of causing the byte of address being translated
+to have its higher order bits filled with zeros.
+.Sh RETURN VALUES
+.Fn iso_ntoa
+always returns a null terminated string.
+.Fn iso_addr
+always returns a pointer to a struct iso_addr.
+(See
+.Sx BUGS . )
+.Sh SEE ALSO
+.Xr iso 4
+.Sh HISTORY
+The
+.Fn iso_addr
+and
+.Fn iso_ntoa
+functions appeared in
+.Bx 4.3 Reno .
+.Sh BUGS
+The returned values
+reside in a static memory area.
+.Pp
+The function
+.Fn iso_addr
+should diagnose improperly formed input, and there should be an unambiguous
+way to recognize this.
diff --git a/lib/nbsd_libc/net/iso_addr.c b/lib/nbsd_libc/net/iso_addr.c
new file mode 100644 (file)
index 0000000..cb0b7c1
--- /dev/null
@@ -0,0 +1,130 @@
+/*     $NetBSD: iso_addr.c,v 1.12 2005/11/29 03:11:59 christos Exp $   */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)iso_addr.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: iso_addr.c,v 1.12 2005/11/29 03:11:59 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <netiso/iso.h>
+
+#include <assert.h>
+#include <string.h>
+
+/* States*/
+#define VIRGIN 0
+#define GOTONE 1
+#define GOTTWO 2
+/* Inputs */
+#define        DIGIT   (4*0)
+#define        END     (4*1)
+#define DELIM  (4*2)
+
+struct iso_addr *
+iso_addr(addr)
+       register const char *addr;
+{
+       static struct iso_addr out_addr;
+       register char *cp = out_addr.isoa_genaddr;
+       char *cplim = cp + sizeof(out_addr.isoa_genaddr);
+       register int byte = 0, state = VIRGIN;
+       register int newaddr = 0;       /* pacify gcc */
+
+       _DIAGASSERT(addr != NULL);
+
+       (void)memset(&out_addr, 0, sizeof (out_addr));
+       do {
+               if ((*addr >= '0') && (*addr <= '9')) {
+                       newaddr = *addr - '0';
+               } else if ((*addr >= 'a') && (*addr <= 'f')) {
+                       newaddr = *addr - 'a' + 10;
+               } else if ((*addr >= 'A') && (*addr <= 'F')) {
+                       newaddr = *addr - 'A' + 10;
+               } else if (*addr == 0) 
+                       state |= END;
+               else
+                       state |= DELIM;
+               addr++;
+               switch (state /* | INPUT */) {
+               case GOTTWO | DIGIT:
+                       *cp++ = byte; /*FALLTHROUGH*/
+               case VIRGIN | DIGIT:
+                       state = GOTONE; byte = newaddr; continue;
+               case GOTONE | DIGIT:
+                       state = GOTTWO; byte = newaddr + (byte << 4); continue;
+               default: /* | DELIM */
+                       state = VIRGIN; *cp++ = byte; byte = 0; continue;
+               case GOTONE | END:
+               case GOTTWO | END:
+                       *cp++ = byte; /* FALLTHROUGH */
+               case VIRGIN | END:
+                       break;
+               }
+               break;
+       } while (cp < cplim); 
+       out_addr.isoa_len = cp - out_addr.isoa_genaddr;
+       return (&out_addr);
+}
+
+static const char hexlist[16] = "0123456789abcdef";
+
+char *
+iso_ntoa(isoa)
+       const struct iso_addr *isoa;
+{
+       static char obuf[64];
+       char *out = obuf; 
+       size_t i;
+       const u_char *in = (const u_char *)isoa->isoa_genaddr;
+       const u_char *inlim = in + isoa->isoa_len;
+
+       _DIAGASSERT(isoa != NULL);
+
+       out[1] = 0;
+       while (in < inlim) {
+               i = *in++;
+               *out++ = '.';
+               if (i > 0xf) {
+                       out[1] = hexlist[i & 0xf];
+                       i >>= 4;
+                       out[0] = hexlist[i];
+                       out += 2;
+               } else
+                       *out++ = hexlist[i];
+       }
+       *out = 0;
+       return(obuf + 1);
+}
diff --git a/lib/nbsd_libc/net/linkaddr.3 b/lib/nbsd_libc/net/linkaddr.3
new file mode 100644 (file)
index 0000000..d0f590d
--- /dev/null
@@ -0,0 +1,134 @@
+.\"    $NetBSD: linkaddr.3,v 1.10 2003/08/07 16:43:11 agc Exp $
+.\"
+.\" Copyright (c) 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Donn Seeley at BSDI.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)linkaddr.3 8.1 (Berkeley) 7/28/93
+.\"
+.Dd July 28, 1993
+.Dt LINK_ADDR 3
+.Os
+.Sh NAME
+.Nm link_addr ,
+.Nm link_ntoa
+.Nd elementary address specification routines for link level access
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/socket.h
+.In net/if_dl.h
+.Ft void
+.Fn link_addr "const char *addr" "struct sockaddr_dl *sdl"
+.Ft char *
+.Fn link_ntoa "const struct sockaddr_dl *sdl"
+.Sh DESCRIPTION
+The routine
+.Fn link_addr
+interprets character strings representing link-level addresses,
+returning binary information suitable for use in system calls.
+The routine
+.Fn link_ntoa
+takes a link-level address and returns an
+.Tn ASCII
+string representing some of the information present, including the
+link level address itself, and the interface name or number, if present.
+This facility is experimental and is still subject to change.
+.Pp
+Prior to a call to
+.Fn link_addr ,
+.Fa sdl-\*[Gt]sdl_len
+must be initialized to the size of the link-level socket structure,
+typically
+.Fa sizeof(struct sockaddr_dl) .
+.Pp
+For
+.Fn link_addr ,
+the string
+.Fa addr
+may contain
+an optional network interface identifier of the form
+.Dq "name unit-number" ,
+suitable for the first argument to
+.Xr ifconfig 8 ,
+followed in all cases by a colon and
+an interface address in the form of
+groups of hexadecimal digits
+separated by periods.
+Each group represents a byte of address;
+address bytes are filled left to right from
+low order bytes through high order bytes.
+.Pp
+.\" A regular expression may make this format clearer:
+.\" .Bd -literal -offset indent
+.\" ([a-z]+[0-9]+:)?[0-9a-f]+(\e.[0-9a-f]+)*
+.\" .Ed
+.\" .Pp
+Thus
+.Li le0:8.0.9.13.d.30
+represents an ethernet address
+to be transmitted on the first Lance ethernet interface.
+.Sh RETURN VALUES
+.Fn link_ntoa
+always returns a null terminated string.
+.Fn link_addr
+has no return value (See
+.Sx BUGS ) .
+.Sh SEE ALSO
+.Xr ethers 3 ,
+.Xr iso 4
+.Sh HISTORY
+The
+.Fn link_addr
+and
+.Fn link_ntoa
+functions appeared in
+.Bx 4.3 Reno .
+.Sh BUGS
+The returned values for
+.Fn link_ntoa
+reside in a static memory area.
+.Pp
+The function
+.Fn link_addr
+should diagnose improperly formed input, and there should be an unambiguous
+way to recognize this.
+.Pp
+If the
+.Va sdl_len
+field of the link socket address
+.Fa sdl
+is 0,
+.Fn link_ntoa
+will not insert a colon before the interface address bytes.
+If this translated address is given to
+.Fn link_addr
+without inserting an initial colon,
+the latter will not interpret it correctly.
diff --git a/lib/nbsd_libc/net/linkaddr.c b/lib/nbsd_libc/net/linkaddr.c
new file mode 100644 (file)
index 0000000..401a4ed
--- /dev/null
@@ -0,0 +1,169 @@
+/*     $NetBSD: linkaddr.c,v 1.14 2005/11/29 03:11:59 christos Exp $   */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)linkaddr.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: linkaddr.c,v 1.14 2005/11/29 03:11:59 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <net/if_dl.h>
+
+#include <assert.h>
+#include <string.h>
+
+/* States*/
+#define NAMING 0
+#define GOTONE 1
+#define GOTTWO 2
+#define RESET  3
+/* Inputs */
+#define        DIGIT   (4*0)
+#define        END     (4*1)
+#define DELIM  (4*2)
+#define LETTER (4*3)
+
+void
+link_addr(addr, sdl)
+       register const char *addr;
+       register struct sockaddr_dl *sdl;
+{
+       register char *cp = sdl->sdl_data;
+       char *cplim = sdl->sdl_len + (char *)(void *)sdl;
+       register int byte = 0, state = NAMING;
+       register int newaddr = 0;       /* pacify gcc */
+
+       _DIAGASSERT(addr != NULL);
+       _DIAGASSERT(sdl != NULL);
+
+       (void)memset(&sdl->sdl_family, 0, (size_t)sdl->sdl_len - 1);
+       sdl->sdl_family = AF_LINK;
+       do {
+               state &= ~LETTER;
+               if ((*addr >= '0') && (*addr <= '9')) {
+                       newaddr = *addr - '0';
+               } else if ((*addr >= 'a') && (*addr <= 'f')) {
+                       newaddr = *addr - 'a' + 10;
+               } else if ((*addr >= 'A') && (*addr <= 'F')) {
+                       newaddr = *addr - 'A' + 10;
+               } else if (*addr == 0) {
+                       state |= END;
+               } else if (state == NAMING &&
+                          (((*addr >= 'A') && (*addr <= 'Z')) ||
+                          ((*addr >= 'a') && (*addr <= 'z'))))
+                       state |= LETTER;
+               else
+                       state |= DELIM;
+               addr++;
+               switch (state /* | INPUT */) {
+               case NAMING | DIGIT:
+               case NAMING | LETTER:
+                       *cp++ = addr[-1];
+                       continue;
+               case NAMING | DELIM:
+                       state = RESET;
+                       sdl->sdl_nlen = cp - sdl->sdl_data;
+                       continue;
+               case GOTTWO | DIGIT:
+                       *cp++ = byte;
+                       /* FALLTHROUGH */
+               case RESET | DIGIT:
+                       state = GOTONE;
+                       byte = newaddr;
+                       continue;
+               case GOTONE | DIGIT:
+                       state = GOTTWO;
+                       byte = newaddr + (byte << 4);
+                       continue;
+               default: /* | DELIM */
+                       state = RESET;
+                       *cp++ = byte;
+                       byte = 0;
+                       continue;
+               case GOTONE | END:
+               case GOTTWO | END:
+                       *cp++ = byte;
+                       /* FALLTHROUGH */
+               case RESET | END:
+                       break;
+               }
+               break;
+       } while (cp < cplim); 
+       sdl->sdl_alen = cp - LLADDR(sdl);
+       newaddr = cp - (char *)(void *)sdl;
+       if ((size_t) newaddr > sizeof(*sdl))
+               sdl->sdl_len = newaddr;
+       return;
+}
+
+static const char hexlist[16] = "0123456789abcdef";
+
+char *
+link_ntoa(sdl)
+       register const struct sockaddr_dl *sdl;
+{
+       static char obuf[64];
+       register char *out = obuf; 
+       register size_t i;
+       const u_char *in = (const u_char *)CLLADDR(sdl);
+       const u_char *inlim = in + sdl->sdl_alen;
+       int firsttime = 1;
+
+       _DIAGASSERT(sdl != NULL);
+
+       if (sdl->sdl_nlen) {
+               (void)memcpy(obuf, sdl->sdl_data, (size_t)sdl->sdl_nlen);
+               out += sdl->sdl_nlen;
+               if (sdl->sdl_alen)
+                       *out++ = ':';
+       }
+       while (in < inlim) {
+               if (firsttime)
+                       firsttime = 0;
+               else
+                       *out++ = '.';
+               i = *in++;
+               if (i > 0xf) {
+                       out[1] = hexlist[i & 0xf];
+                       i >>= 4;
+                       out[0] = hexlist[i];
+                       out += 2;
+               } else
+                       *out++ = hexlist[i];
+       }
+       *out = 0;
+       return (obuf);
+}
diff --git a/lib/nbsd_libc/net/nsdispatch.3 b/lib/nbsd_libc/net/nsdispatch.3
new file mode 100644 (file)
index 0000000..d22e8d2
--- /dev/null
@@ -0,0 +1,940 @@
+.\"    $NetBSD: nsdispatch.3,v 1.29 2009/10/14 17:24:03 joerg Exp $
+.\"
+.\" Copyright (c) 1997, 1998, 1999, 2004, 2005, 2008
+.\" The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Luke Mewburn; and by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 8, 2008
+.Dt NSDISPATCH 3
+.Os
+.Sh NAME
+.Nm nsdispatch
+.Nd name-service switch dispatcher routine
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In nsswitch.h
+.Ft int
+.Fo nsdispatch
+.Fa "void *nsdrv"
+.Fa "const ns_dtab dtab[]"
+.Fa "const char *database"
+.Fa "const char *name"
+.Fa "const ns_src defaults[]"
+.Fa "..."
+.Fc
+.Sh DESCRIPTION
+The
+.Fn nsdispatch
+function invokes the callback functions specified in
+.Fa dtab
+in the order given in
+.Pa /etc/nsswitch.conf
+for the database
+.Fa database
+until the action criteria for a source of that database is fulfilled.
+.Pp
+.Fa nsdrv
+is passed to each callback function to use as necessary
+(to pass back to the caller of
+.Fn nsdispatch ) .
+.Pp
+.Fa dtab
+is an array of
+.Fa ns_dtab
+structures, which have the following format:
+.Bl -item -offset indent
+.It
+.Bd -literal
+typedef struct {
+       const char *src;
+       nss_method cb;
+       void *cb_data;
+} ns_dtab;
+.Ed
+.It
+The
+.Fa dtab
+array should consist of one entry for each source type that has a
+static implementation,
+with
+.Fa src
+as the name of the source,
+.Fa cb
+as a callback function which handles that source, and
+.Fa cb_data
+as a pointer to arbitrary data to be passed to the callback function.
+The last entry in
+.Fa dtab
+should contain
+.Dv NULL
+values for
+.Fa src ,
+.Fa cb ,
+and
+.Fa cb_data .
+.It
+The callback function signature is described by the typedef:
+.Bd -ragged -offset indent
+.Ft typedef int
+.Fo \*(lp*nss_method\*(rp
+.Fa "void *cbrv"
+.Fa "void *cbdata"
+.Fa "va_list ap"
+.Fc ;
+.Bl -tag -width cbdata
+.It Fa cbrv
+The
+.Fa nsdrv
+that
+.Fn nsdispatch
+was invoked with.
+.It Fa cbdata
+The
+.Fa cb_data
+member of the array entry for the source that this
+callback function implements in the
+.Fa dtab
+argument of
+.Fn nsdispatch .
+.It Fa ap
+The
+.Fa ...
+arguments to
+.Fn nsdispatch ,
+converted to a
+.Ft va_list .
+.El
+.Ed
+.El
+.Pp
+.Fa database
+and
+.Fa name
+are used to select methods from optional per-source
+dynamically-loaded modules.
+.Fa name
+is usually the name of the function calling
+.Fn nsdispatch .
+Note that the callback functions provided by
+.Fa dtab
+take priority over those implemented in dynamically-loaded modules in the
+event of a conflict.
+.Pp
+.Fa defaults
+contains a list of default sources to try in the case of
+a missing or corrupt
+.Xr nsswitch.conf 5 ,
+or if there isn't a relevant entry for
+.Fa database .
+It is an array of
+.Fa ns_src
+structures, which have the following format:
+.Bl -item -offset indent
+.It
+.Bd -literal
+typedef struct {
+       const char *src;
+       uint32_t flags;
+} ns_src;
+.Ed
+.It
+The
+.Fa defaults
+array should consist of one entry for each source to consult by default
+indicated by
+.Fa src ,
+and
+.Fa flags
+set to the desired behavior
+(usually
+.Dv NS_SUCCESS ;
+refer to
+.Sx Callback function return values
+for more information).
+The last entry in
+.Fa defaults
+should have
+.Fa src
+set to
+.Dv NULL
+and
+.Fa flags
+set to 0.
+.It
+Some invokers of
+.Fn nsdispatch
+(such as
+.Xr setgrent 3 )
+need to force all callback functions to be invoked,
+irrespective of the action criteria listed in
+.Xr nsswitch.conf 5 .
+This can be achieved by adding
+.Dv NS_FORCEALL
+to
+.Fa defaults[0].flags
+before invoking
+.Fn nsdispatch .
+The return value of
+.Fn nsdispatch
+will be the result of the final callback function invoked.
+.It
+For convenience, a global variable defined as:
+.Dl extern const ns_src __nsdefaultsrc[];
+exists which contains a single default entry for
+.Sq files
+for use by callers which don't require complicated default rules.
+.El
+.Pp
+.Fa ...
+are optional extra arguments, which
+are passed to the appropriate callback function as a
+.Xr stdarg 3
+variable argument
+list of the type
+.Fa va_list .
+.Pp
+.Nm
+returns the value of the callback function that caused the dispatcher
+to finish, or
+.Dv NS_NOTFOUND
+otherwise.
+.\"
+.Ss Dynamically-loaded module interface
+The
+.Fn nsdispatch
+function loads callback functions from the run-time link-editor's search
+path using the following naming convention:
+.Bl -item -offset indent
+.It
+.Bd -literal
+nss_\*[Lt]source\*[Gt].so.\*[Lt]version\*[Gt]
+.Ed
+.Bl -tag -width XversionX
+.It Aq source
+The source that the module implements.
+.It Aq version
+The
+.Nm nsdispatch
+module interface version, which is defined by the integer
+.Dv NSS_MODULE_INTERFACE_VERSION ,
+which has the value 0.
+.El
+.El
+.Pp
+When a module is loaded,
+.Fn nsdispatch
+looks for and calls the following function in the module:
+.Pp
+.Bd -ragged -offset indent
+.Ft ns_mtab *
+.Fo nss_module_register
+.Fa "const char *source"
+.Fa "u_int *nelems"
+.Fa "nss_module_unregister_fn *unreg"
+.Fc ;
+.Pp
+.Bl -tag -width source
+.It Fa source
+The name of the source that the module implements, as used by
+.Fn nsdispatch
+to construct the module's name.
+.It Fa nelems
+A pointer to an unsigned integer that
+.Fn nss_module_register
+should set to the number of elements in the
+.Ft ns_mtab
+array returned by
+.Fn nss_module_register ,
+or
+.Dv 0
+if there was a failure.
+.It Fa unreg
+A pointer to a function pointer that
+.Fn nss_module_register
+can optionally set to an unregister function to be invoked when the module is
+unloaded, or
+.Dv NULL
+if there isn't one.
+.El
+.Ed
+.Pp
+The unregister function signature is described by the typedef:
+.Pp
+.Bd -ragged -offset indent
+.Ft typedef void
+.Fo \*(lp*nss_module_unregister_fn\*(rp
+.Fa "ns_mtab *mtab"
+.Fa "u_int nelems"
+.Fc ;
+.Pp
+.Bl -tag -width nelems
+.It Fa mtab
+The array of
+.Ft ns_mtab
+structures returned by
+.Fn nss_module_register .
+.It Fa nelems
+The
+.Fa *nelems
+value set by
+.Fn nss_module_register .
+.El
+.Ed
+.Pp
+.Fn nss_module_register
+returns an array of
+.Ft ns_mtab
+structures
+(with
+.Fa *nelems
+entries), or
+.Dv NULL
+if there was a failure.
+The
+.Ft ns_mtab
+structures have the following format:
+.Bl -item -offset indent
+.It
+.Bd -literal
+typedef struct {
+       const char *database;
+       const char *name;
+       nss_method method;
+       void *mdata;
+} ns_mtab;
+.Ed
+.It
+The
+.Fa mtab
+array should consist of one entry for each callback function (method)
+that is implemented,
+with
+.Fa database
+as the name of the database,
+.Fa name
+as the name of the callback function,
+.Fa method
+as the
+.Ft nss_method
+callback function that implements the method, and
+.Fa mdata
+as a pointer to arbitrary data to be passed to the callback function as its
+.Fa cbdata
+argument.
+.El
+.\"
+.Ss Valid source types
+While there is support for arbitrary sources, the following
+#defines for commonly implemented sources are provided:
+.Bl -column NSSRC_COMPAT COMPAT -offset indent
+.It Sy #define Value
+.It NSSRC_FILES        "files"
+.It NSSRC_DNS  "dns"
+.It NSSRC_NIS  "nis"
+.It NSSRC_COMPAT       "compat"
+.El
+.Pp
+Refer to
+.Xr nsswitch.conf 5
+for a complete description of what each source type is.
+.\"
+.Ss Valid database types
+While there is support for arbitrary databases, the following
+#defines for currently implemented system databases are provided:
+.Bl -column NSDB_PASSWD_COMPAT PASSWD_COMPAT -offset indent
+.It Sy #define Value
+.It NSDB_HOSTS "hosts"
+.It NSDB_GROUP "group"
+.It NSDB_GROUP_COMPAT  "group_compat"
+.It NSDB_NETGROUP      "netgroup"
+.It NSDB_NETWORKS      "networks"
+.It NSDB_PASSWD        "passwd"
+.It NSDB_PASSWD_COMPAT "passwd_compat"
+.It NSDB_SHELLS        "shells"
+.El
+.Pp
+Refer to
+.Xr nsswitch.conf 5
+for a complete description of what each database is.
+.\"
+.Ss Callback function return values
+The callback functions should return one of the following values
+depending upon status of the lookup:
+.Bl -column NS_NOTFOUND -offset indent
+.It Sy "Return value"  Status code
+.It NS_SUCCESS The requested entry was found.
+.It NS_NOTFOUND        The entry is not present at this source.
+.It NS_TRYAGAIN        The source is busy, and may respond to retries.
+.It NS_UNAVAIL The source is not responding, or entry is corrupt.
+.El
+.\"
+.Sh CALLBACK FUNCTION API FOR STANDARD DATABASES
+The organization of the
+.Fa ap
+argument for an
+.Fn nss_method
+callback function for a standard method in a standard database is:
+.Bl -enum -offset indent -compact
+.It
+Pointer to return value of the standard function.
+.It
+First argument of the standard function.
+.It
+(etc.)
+.El
+.Pp
+For example, given the standard function
+.Xr getgrnam 3 :
+.Bd -ragged -offset indent -compact
+.Ft struct group *
+.Fn getgrnam "const char *name"
+.Ed
+the
+.Fa ap
+organization used by the callback functions is:
+.Bl -enum -offset indent -compact
+.It
+.Ft "struct group **"
+.It
+.Ft "const char *"
+.El
+.Pp
+.Sy NOTE:
+Not all standard databases are using this calling convention yet;
+those that aren't are noted below.
+These will be changed in the future.
+.Pp
+The callback function names and
+.Ft va_list
+organization for various standard database callback functions are:
+.\"
+.Ss Methods for hosts database
+.Sy NOTE:
+The method APIs for this database will be changing in the near future.
+.Bl -tag -width 3n
+.It Sy getaddrinfo
+.Ft "char *name" ,
+.Ft "const struct addrinfo *pai"
+.Pp
+Returns
+.Ft "struct addrinfo *"
+via
+.Ft "void *cbrv" .
+.It Sy gethostbyaddr
+.Ft "unsigned char *addr" ,
+.Ft "int addrlen" ,
+.Ft "int af"
+.Pp
+Returns
+.Ft "struct hostent *"
+via
+.Ft "void *cbrv" .
+.It Sy gethostbyname
+.Ft "char *name" ,
+.Ft "int namelen" ,
+.Ft "int af"
+.Pp
+Returns
+.Ft "struct hostent *"
+via
+.Ft "void *cbrv" .
+.El
+.\"
+.Ss Methods for group and group_compat databases
+.Bl -tag -width 3n
+.It Sy endgrent
+Empty
+.Fa ap .
+.Pp
+All methods for all sources are invoked for this method name.
+.It Sy getgrent
+.Ft "struct group **retval"
+.Pp
+.Fa *retval
+should be set to a pointer to an internal static
+.Ft "struct group"
+on success,
+.Dv NULL otherwise.
+.Pp
+.Xr getgrent 3
+returns
+.Fa *retval
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS ,
+.Dv NULL
+otherwise.
+.It Sy getgrent_r
+.Ft "int *retval" ,
+.Ft "struct group *grp" ,
+.Ft "char *buffer" ,
+.Ft "size_t buflen" ,
+.Ft "struct group **result"
+.Pp
+.Fa *retval
+should be set to an appropriate
+.Xr errno 2
+on failure.
+.Pp
+.Xr getgrent_r 3
+returns 0
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS
+or
+.Dv NS_NOTFOUND ,
+and
+.Fa *retval
+otherwise.
+.It Sy getgrgid
+.Ft "struct group **retval" ,
+.Ft "gid_t gid"
+.Pp
+.Fa *retval
+should be set to a pointer to an internal static
+.Ft "struct group"
+on success,
+.Dv NULL otherwise.
+.Pp
+.Xr getgrgid 3
+returns
+.Fa *retval
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS ,
+.Dv NULL
+otherwise.
+.It Sy getgrgid_r
+.Ft "int *retval" ,
+.Ft "gid_t gid" ,
+.Ft "struct group *grp" ,
+.Ft "char *buffer" ,
+.Ft "size_t buflen" ,
+.Ft "struct group **result"
+.Pp
+.Fa *retval
+should be set to an appropriate
+.Xr errno 2
+on failure.
+.Pp
+.Xr getgrgid_r 3
+returns 0
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS
+or
+.Dv NS_NOTFOUND ,
+and
+.Fa *retval
+otherwise.
+.It Sy getgrnam
+.Ft "struct group **retval" ,
+.Ft "const char *name"
+.Pp
+.Fa *retval
+should be set to a pointer to an internal static
+.Ft "struct group"
+on success,
+.Dv NULL otherwise.
+.Pp
+.Xr getgrnam 3
+returns
+.Fa *retval
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS ,
+.Dv NULL
+otherwise.
+.It Sy getgrnam_r
+.Ft "int *retval" ,
+.Ft "const char *name" ,
+.Ft "struct group *grp" ,
+.Ft "char *buffer" ,
+.Ft "size_t buflen" ,
+.Ft "struct group **result"
+.Pp
+.Fa *retval
+should be set to an appropriate
+.Xr errno 2
+on failure.
+.Pp
+.Xr getgrnam_r 3
+returns 0
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS
+or
+.Dv NS_NOTFOUND ,
+and
+.Fa *retval
+otherwise.
+.It Sy getgroupmembership
+.Ft "int *retval" ,
+.Ft "const char *name" ,
+.Ft "gid_t basegid" ,
+.Ft "gid_t *groups" ,
+.Ft "int maxgrp" ,
+.Ft "int *groupc"
+.Pp
+.Fa retval
+is unused.
+.Pp
+Lookups for
+.Sy group_compat
+are also stopped if
+.Dv NS_SUCCESS
+was returned to prevent multiple
+.Dq "+:"
+compat entries from being expanded.
+.Pp
+.Xr getgroupmembership 3
+returns
+is -1 if
+.Fa *groupc
+is greater than to
+.Fa maxgrp ,
+and 0 otherwise.
+.It Sy setgroupent
+.Ft "int *retval" ,
+.Ft "int stayopen"
+.Pp
+.Fa retval
+should be set to 0 on failure and 1 on success.
+.Pp
+All methods for all sources are invoked for this method name.
+.It Sy setgrent
+Empty
+.Fa ap .
+.Pp
+All methods for all sources are invoked for this method name.
+.El
+.\"
+.Ss Methods for netgroup database
+.Sy NOTE:
+The method APIs for this database will be changing in the near future.
+.Bl -tag -width 3n
+.It Sy endnetgrent
+Empty
+.Fa ap .
+.It Sy lookup
+.Ft "char *name" ,
+.Ft "char **line" ,
+.Ft "int bywhat"
+.Pp
+Find the given
+.Fa name
+and return its value in
+.Fa line .
+.Fa bywhat
+is one of
+.Dv _NG_KEYBYNAME ,
+.Dv _NG_KEYBYUSER ,
+or
+.Dv _NG_KEYBYHOST .
+.It Sy getnetgrent
+.Ft "int *retval" ,
+.Ft "const char **host" ,
+.Ft "const char **user" ,
+.Ft "const char **domain"
+.Pp
+.Fa *retval
+should be set to 0 for no more netgroup members and 1 otherwise.
+.Pp
+.Xr getnetgrent 3
+returns
+.Fa *retval
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS ,
+0 otherwise.
+.It Sy innetgr
+.Ft "int *retval" ,
+.Ft "const char *grp" ,
+.Ft "const char *host" ,
+.Ft "const char *user" ,
+.Ft "const char *domain"
+.Pp
+.Fa *retval
+should be set to 1 for a successful match and 0 otherwise.
+.It Sy setnetgrent
+.Ft "const char *netgroup"
+.El
+.\"
+.Ss Methods for networks database
+.Bl -tag -width 3n
+.It Sy getnetbyaddr
+.Ft "struct netent **retval" ,
+.Ft "uint32_t net" ,
+.Ft "int type"
+.Pp
+.Fa *retval
+should be set to a pointer to an internal static
+.Ft "struct netent"
+on success,
+.Dv NULL otherwise.
+.Pp
+.Xr getnetbyaddr 3
+returns
+.Fa *retval
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS ,
+.Dv NULL
+otherwise.
+.It Sy getnetbyname
+.Ft "struct netent **retval" ,
+.Ft "const char *name"
+.Pp
+.Fa *retval
+should be set to a pointer to an internal static
+.Ft "struct netent"
+on success,
+.Dv NULL otherwise.
+.Pp
+.Xr getnetbyname 3
+returns
+.Fa *retval
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS ,
+.Dv NULL
+otherwise.
+.El
+.\"
+.Ss Methods for passwd and passwd_compat databases
+.Bl -tag -width 3n
+.It Sy endpwent
+Empty
+.Fa ap .
+.Pp
+All methods for all sources are invoked for this method name.
+.It Sy getpwent
+.Ft "struct passwd **retval"
+.Pp
+.Fa *retval
+should be set to a pointer to an internal static
+.Ft "struct passwd"
+on success,
+.Dv NULL otherwise.
+.Pp
+.Xr getpwent 3
+returns
+.Fa *retval
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS ,
+.Dv NULL
+otherwise.
+.It Sy getpwent_r
+.Ft "int *retval" ,
+.Ft "struct passwd *pw" ,
+.Ft "char *buffer" ,
+.Ft "size_t buflen" ,
+.Ft "struct passwd **result"
+.Pp
+.Fa *retval
+should be set to an appropriate
+.Xr errno 2
+on failure.
+.Pp
+.Xr getpwent_r 3
+returns 0
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS
+or
+.Dv NS_NOTFOUND ,
+and
+.Fa *retval
+otherwise.
+.It Sy getpwnam
+.Ft "struct passwd **retval" ,
+.Ft "const char *name"
+.Pp
+.Fa *retval
+should be set to a pointer to an internal static
+.Ft "struct passwd"
+on success,
+.Dv NULL otherwise.
+.Pp
+.Xr getpwnam 3
+returns
+.Fa *retval
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS ,
+.Dv NULL
+otherwise.
+.It Sy getpwnam_r
+.Ft "int *retval" ,
+.Ft "const char *name" ,
+.Ft "struct passwd *pw" ,
+.Ft "char *buffer" ,
+.Ft "size_t buflen" ,
+.Ft "struct passwd **result"
+.Pp
+.Fa *retval
+should be set to an appropriate
+.Xr errno 2
+on failure.
+.Pp
+.Xr getpwnam_r 3
+returns 0
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS
+or
+.Dv NS_NOTFOUND ,
+and
+.Fa *retval
+otherwise.
+.It Sy getpwuid
+.Ft "struct passwd **retval" ,
+.Ft "uid_t uid"
+.Pp
+.Fa *retval
+should be set to a pointer to an internal static
+.Ft "struct passwd"
+on success,
+.Dv NULL otherwise.
+.Pp
+.Xr getpwuid 3
+returns
+.Fa *retval
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS ,
+.Dv NULL
+otherwise.
+.It Sy getpwuid_r
+.Ft "int *retval" ,
+.Ft "uid_t uid" ,
+.Ft "struct passwd *pw" ,
+.Ft "char *buffer" ,
+.Ft "size_t buflen" ,
+.Ft "struct passwd **result"
+.Pp
+.Fa *retval
+should be set to an appropriate
+.Xr errno 2
+on failure.
+.Pp
+.Xr getpwuid_r
+returns 0
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS
+or
+.Dv NS_NOTFOUND ,
+and
+.Fa *retval
+otherwise.
+.It Sy setpassent
+.Ft "int *retval" ,
+.Ft "int stayopen"
+.Pp
+.Fa retval
+should be set to 0 on failure and 1 on success.
+.Pp
+All methods for all sources are invoked for this method name.
+.It Sy setpwent
+Empty
+.Fa ap .
+.Pp
+All methods for all sources are invoked for this method name.
+.El
+.\"
+.Ss Methods for shells database
+.Bl -tag -width 3n
+.It Sy endusershell
+Empty
+.Fa ap .
+.Pp
+All methods for all sources are invoked for this method name.
+.It Sy getusershell
+.Ft "char **retval"
+.Pp
+.Xr getusershell 3
+returns
+.Fa *retval
+if
+.Fn nsdispatch
+returns
+.Dv NS_SUCCESS ,
+and 0 otherwise.
+.It Sy setusershell
+Empty
+.Fa ap .
+.Pp
+All methods for all sources are invoked for this method name.
+.El
+.\"
+.Sh SEE ALSO
+.Xr ld.elf_so 1 ,
+.Xr hesiod 3 ,
+.Xr stdarg 3 ,
+.Xr ypclnt 3 ,
+.Xr nsswitch.conf 5
+.Sh HISTORY
+The
+.Nm
+routines first appeared in
+.Nx 1.4 .
+Support for dynamically-loaded modules first appeared in
+.Nx 3.0 .
+.Sh AUTHORS
+Luke Mewburn
+.Aq lukem@NetBSD.org
+wrote this freely distributable name-service switch implementation,
+using ideas from the
+.Tn ULTRIX
+.Xr svc.conf 5
+and
+.Tn Solaris
+.Xr nsswitch.conf 4
+manual pages.
+Support for dynamically-loaded modules was added by Jason Thorpe
+.Aq thorpej@NetBSD.org ,
+based on code developed by the
+.Fx
+Project.
diff --git a/lib/nbsd_libc/net/nsdispatch.c b/lib/nbsd_libc/net/nsdispatch.c
new file mode 100644 (file)
index 0000000..3def5d1
--- /dev/null
@@ -0,0 +1,693 @@
+/*     $NetBSD: nsdispatch.c,v 1.34 2009/02/05 13:21:11 lukem Exp $    */
+
+/*-
+ * Copyright (c) 1997, 1998, 1999, 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Luke Mewburn; and by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*-
+ * Copyright (c) 2003 Networks Associates Technology, Inc.
+ * All rights reserved.
+ *
+ * Portions of this software were developed for the FreeBSD Project by
+ * Jacques A. Vidrine, Safeport Network Services, and Network
+ * Associates Laboratories, the Security Research Division of Network
+ * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035
+ * ("CBOSS"), as part of the DARPA CHATS research program.
+ *
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nsdispatch.c,v 1.34 2009/02/05 13:21:11 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/queue.h>
+
+#include <assert.h>
+#ifdef __ELF__
+#include <dlfcn.h>
+#endif /* __ELF__ */
+#include <err.h>
+#include <fcntl.h>
+#define _NS_PRIVATE
+#include <nsswitch.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "reentrant.h"
+
+extern FILE    *_nsyyin;
+extern int      _nsyyparse(void);
+
+
+#ifdef __weak_alias
+__weak_alias(nsdispatch,_nsdispatch)
+#endif
+
+
+/*
+ * default sourcelist: `files'
+ */
+const ns_src __nsdefaultsrc[] = {
+       { NSSRC_FILES,  NS_SUCCESS },
+       { 0, 0 },
+};
+
+const ns_src __nsdefaultcompat[] = {
+       { NSSRC_COMPAT, NS_SUCCESS },
+       { 0, 0 }
+};
+
+const ns_src __nsdefaultcompat_forceall[] = {
+       { NSSRC_COMPAT, NS_SUCCESS | NS_FORCEALL },
+       { 0, 0 }
+};
+
+const ns_src __nsdefaultfiles[] = {
+       { NSSRC_FILES,  NS_SUCCESS },
+       { 0, 0 },
+};
+
+const ns_src __nsdefaultfiles_forceall[] = {
+       { NSSRC_FILES,  NS_SUCCESS | NS_FORCEALL },
+       { 0, 0 },
+};
+
+const ns_src __nsdefaultnis[] = {
+       { NSSRC_NIS,    NS_SUCCESS },
+       { 0, 0 }
+};
+
+const ns_src __nsdefaultnis_forceall[] = {
+       { NSSRC_NIS,    NS_SUCCESS | NS_FORCEALL },
+       { 0, 0 }
+};
+
+
+/* Database, source mappings. */
+static u_int                    _nsmapsize;
+static ns_dbt                  *_nsmap;
+
+/* Nsswitch modules. */
+static u_int                    _nsmodsize;
+static ns_mod                  *_nsmod;
+
+/* Placeholder for built-in modules' dlopen() handles. */
+static void                    *_nsbuiltin = &_nsbuiltin;
+
+#ifdef _REENTRANT
+/*
+ * Global nsswitch data structures are mostly read-only, but we update them
+ * when we read or re-read nsswitch.conf.
+ */
+static         rwlock_t                _nslock = RWLOCK_INITIALIZER;
+
+/*
+ * List of threads currently in nsdispatch().  We use this to detect
+ * recursive calls and avoid reloading configuration in such cases,
+ * which could cause deadlock.
+ */
+struct _ns_drec {
+       LIST_ENTRY(_ns_drec)    list;
+       thr_t                   thr;
+};
+static LIST_HEAD(, _ns_drec) _ns_drec = LIST_HEAD_INITIALIZER(&_ns_drec);
+static mutex_t _ns_drec_lock = MUTEX_INITIALIZER;
+#endif /* _REENTRANT */
+
+
+/*
+ * Runtime determination of whether we are dynamically linked or not.
+ */
+#ifdef __ELF__
+extern int                     _DYNAMIC __weak_reference(_DYNAMIC);
+#define        is_dynamic()            (&_DYNAMIC != NULL)
+#else
+#define        is_dynamic()            (0)     /* don't bother - switch to ELF! */
+#endif /* __ELF__ */
+
+
+/*
+ * size of dynamic array chunk for _nsmap and _nsmap[x].srclist (and other
+ * growing arrays).
+ */
+#define NSELEMSPERCHUNK                8
+
+/*
+ * Dynamically growable arrays are used for lists of databases, sources,
+ * and modules.  The following "vector" API is used to isolate the
+ * common operations.
+ */
+typedef void   (*_nsvect_free_elem)(void *);
+
+static void *
+_nsvect_append(const void *elem, void *vec, u_int *count, size_t esize)
+{
+       void    *p;
+
+       if ((*count % NSELEMSPERCHUNK) == 0) {
+               p = realloc(vec, (*count + NSELEMSPERCHUNK) * esize);
+               if (p == NULL)
+                       return (NULL);
+               vec = p;
+       }
+       memmove((void *)(((uintptr_t)vec) + (*count * esize)), elem, esize);
+       (*count)++;
+       return (vec);
+}
+
+static void *
+_nsvect_elem(u_int i, void *vec, u_int count, size_t esize)
+{
+
+       if (i < count)
+               return ((void *)((uintptr_t)vec + (i * esize)));
+       else
+               return (NULL);
+}
+
+static void
+_nsvect_free(void *vec, u_int *count, size_t esize, _nsvect_free_elem free_elem)
+{
+       void    *elem;
+       u_int    i;
+
+       for (i = 0; i < *count; i++) {
+               elem = _nsvect_elem(i, vec, *count, esize);
+               if (elem != NULL)
+                       (*free_elem)(elem);
+       }
+       if (vec != NULL)
+               free(vec);
+       *count = 0;
+}
+#define        _NSVECT_FREE(v, c, s, f)                                        \
+do {                                                                   \
+       _nsvect_free((v), (c), (s), (f));                               \
+       (v) = NULL;                                                     \
+} while (/*CONSTCOND*/0)
+
+static int
+_nsdbtcmp(const void *a, const void *b)
+{
+
+       return (strcasecmp(((const ns_dbt *)a)->name,
+           ((const ns_dbt *)b)->name));
+}
+
+static int
+_nsmodcmp(const void *a, const void *b)
+{
+
+       return (strcasecmp(((const ns_mod *)a)->name,
+           ((const ns_mod *)b)->name));
+}
+
+static int
+_nsmtabcmp(const void *a, const void *b)
+{
+       int     cmp;
+
+       cmp = strcmp(((const ns_mtab *)a)->name,
+           ((const ns_mtab *)b)->name);
+       if (cmp)
+               return (cmp);
+
+       return (strcasecmp(((const ns_mtab *)a)->database,
+           ((const ns_mtab *)b)->database));
+}
+
+static void
+_nsmodfree(ns_mod *mod)
+{
+
+       free(__UNCONST(mod->name));
+       if (mod->handle == NULL)
+               return;
+       if (mod->unregister != NULL)
+               (*mod->unregister)(mod->mtab, mod->mtabsize);
+#ifdef __ELF__
+       if (mod->handle != _nsbuiltin)
+               (void) dlclose(mod->handle);
+#endif /* __ELF__ */
+}
+
+/*
+ * Load a built-in or dyanamically linked module.  If the `reg_fn'
+ * argument is non-NULL, assume a built-in module and use `reg_fn'
+ * to register it.  Otherwise, search for a dynamic nsswitch module.
+ */
+static int
+_nsloadmod(const char *source, nss_module_register_fn reg_fn)
+{
+#ifdef __ELF__
+       char    buf[PATH_MAX];
+#endif
+       ns_mod  mod, *new;
+
+       memset(&mod, 0, sizeof(mod));
+       mod.name = strdup(source);
+       if (mod.name == NULL)
+               return (-1);
+
+       if (reg_fn != NULL) {
+               /*
+                * The placeholder is required, as a NULL handle
+                * represents an invalid module.
+                */
+               mod.handle = _nsbuiltin;
+       } else if (!is_dynamic()) {
+               goto out;
+       } else {
+#ifdef __ELF__
+               if (snprintf(buf, sizeof(buf), "nss_%s.so.%d", mod.name,
+                   NSS_MODULE_INTERFACE_VERSION) >= (int)sizeof(buf))
+                       goto out;
+               mod.handle = dlopen(buf, RTLD_LOCAL | RTLD_LAZY);
+               if (mod.handle == NULL) {
+#ifdef _NSS_DEBUG
+                       /*
+                        * This gets pretty annoying, since the built-in
+                        * sources are not yet modules.
+                        */
+                       /* XXX log some error? */
+#endif
+                       goto out;
+               }
+               reg_fn = (nss_module_register_fn) dlsym(mod.handle,
+                   "nss_module_register");
+               if (reg_fn == NULL) {
+                       (void) dlclose(mod.handle);
+                       mod.handle = NULL;
+                       /* XXX log some error? */
+                       goto out;
+               }
+#else /* ! __ELF__ */
+               mod.handle = NULL;
+#endif /* __ELF__ */
+       }
+       mod.mtab = (*reg_fn)(mod.name, &mod.mtabsize, &mod.unregister);
+       if (mod.mtab == NULL || mod.mtabsize == 0) {
+#ifdef __ELF__
+               if (mod.handle != _nsbuiltin)
+                       (void) dlclose(mod.handle);
+#endif /* __ELF__ */
+               mod.handle = NULL;
+               /* XXX log some error? */
+               goto out;
+       }
+       if (mod.mtabsize > 1)
+               qsort(mod.mtab, mod.mtabsize, sizeof(mod.mtab[0]),
+                   _nsmtabcmp);
+ out:
+       new = _nsvect_append(&mod, _nsmod, &_nsmodsize, sizeof(*_nsmod));
+       if (new == NULL) {
+               _nsmodfree(&mod);
+               return (-1);
+       }
+       _nsmod = new;
+       /* _nsmodsize already incremented */
+
+       qsort(_nsmod, _nsmodsize, sizeof(*_nsmod), _nsmodcmp);
+       return (0);
+}
+
+static void
+_nsloadbuiltin(void)
+{
+
+       /* Do nothing, for now. */
+}
+
+int
+_nsdbtaddsrc(ns_dbt *dbt, const ns_src *src)
+{
+       void            *new;
+       const ns_mod    *mod;
+       ns_mod           modkey;
+
+       _DIAGASSERT(dbt != NULL);
+       _DIAGASSERT(src != NULL);
+
+       new = _nsvect_append(src, dbt->srclist, &dbt->srclistsize,
+           sizeof(*src));
+       if (new == NULL)
+               return (-1);
+       dbt->srclist = new;
+       /* dbt->srclistsize already incremented */
+
+       modkey.name = src->name;
+       mod = bsearch(&modkey, _nsmod, _nsmodsize, sizeof(*_nsmod),
+           _nsmodcmp);
+       if (mod == NULL)
+               return (_nsloadmod(src->name, NULL));
+
+       return (0);
+}
+
+void
+_nsdbtdump(const ns_dbt *dbt)
+{
+       unsigned int    i;
+
+       _DIAGASSERT(dbt != NULL);
+
+       printf("%s (%d source%s):", dbt->name, dbt->srclistsize,
+           dbt->srclistsize == 1 ? "" : "s");
+       for (i = 0; i < dbt->srclistsize; i++) {
+               printf(" %s", dbt->srclist[i].name);
+               if (!(dbt->srclist[i].flags &
+                   (NS_UNAVAIL|NS_NOTFOUND|NS_TRYAGAIN)) &&
+                   (dbt->srclist[i].flags & NS_SUCCESS))
+                       continue;
+               printf(" [");
+               if (!(dbt->srclist[i].flags & NS_SUCCESS))
+                       printf(" SUCCESS=continue");
+               if (dbt->srclist[i].flags & NS_UNAVAIL)
+                       printf(" UNAVAIL=return");
+               if (dbt->srclist[i].flags & NS_NOTFOUND)
+                       printf(" NOTFOUND=return");
+               if (dbt->srclist[i].flags & NS_TRYAGAIN)
+                       printf(" TRYAGAIN=return");
+               printf(" ]");
+       }
+       printf("\n");
+}
+
+static void
+_nssrclist_free(ns_src **src, u_int srclistsize)
+{
+       u_int   i;
+
+       for (i = 0; i < srclistsize; i++) {
+               if ((*src)[i].name != NULL)
+                       free(__UNCONST((*src)[i].name));
+       }
+       free(*src);
+       *src = NULL;
+}
+
+static void
+_nsdbtfree(ns_dbt *dbt)
+{
+
+       _nssrclist_free(&dbt->srclist, dbt->srclistsize);
+       if (dbt->name != NULL)
+               free(__UNCONST(dbt->name));
+}
+
+int
+_nsdbtput(const ns_dbt *dbt)
+{
+       ns_dbt  *p;
+       void    *new;
+       u_int   i;
+
+       _DIAGASSERT(dbt != NULL);
+
+       for (i = 0; i < _nsmapsize; i++) {
+               p = _nsvect_elem(i, _nsmap, _nsmapsize, sizeof(*_nsmap));
+               if (strcasecmp(dbt->name, p->name) == 0) {
+                                       /* overwrite existing entry */
+                       if (p->srclist != NULL)
+                               _nssrclist_free(&p->srclist, p->srclistsize);
+                       memmove(p, dbt, sizeof(*dbt));
+                       return (0);
+               }
+       }
+       new = _nsvect_append(dbt, _nsmap, &_nsmapsize, sizeof(*_nsmap));
+       if (new == NULL)
+               return (-1);
+       _nsmap = new;
+       /* _nsmapsize already incremented */
+
+       return (0);
+}
+
+/*
+ * This function is called each time nsdispatch() is called.  If this
+ * is the first call, or if the configuration has changed, (re-)prepare
+ * the global data used by NSS.
+ */
+static int
+_nsconfigure(void)
+{
+#ifdef _REENTRANT
+       static mutex_t  _nsconflock = MUTEX_INITIALIZER;
+#endif
+       static time_t   _nsconfmod;
+       struct stat     statbuf;
+
+       mutex_lock(&_nsconflock);
+
+       if (stat(_PATH_NS_CONF, &statbuf) == -1) {
+               /*
+                * No nsswitch.conf; just use whatever configuration we
+                * currently have, or fall back on the defaults specified
+                * by the caller.
+                */
+               mutex_unlock(&_nsconflock);
+               return (0);
+       }
+
+       if (statbuf.st_mtime <= _nsconfmod) {
+               /* Internal state is up-to-date with nsswitch.conf. */
+               mutex_unlock(&_nsconflock);
+               return (0);
+       }
+
+       /*
+        * Ok, we've decided we need to update the nsswitch configuration
+        * structures.  Acquire a write-lock on _nslock while continuing
+        * to hold _nsconflock.  Acquiring a write-lock blocks while
+        * waiting for other threads already holding a read-lock to clear.
+        * We hold _nsconflock for the duration, and update the time stamp
+        * at the end of the update operation, at which time we release
+        * both locks.
+        */
+       rwlock_wrlock(&_nslock);
+
+       _nsyyin = fopen(_PATH_NS_CONF, "r");
+       if (_nsyyin == NULL) {
+               /*
+                * Unable to open nsswitch.conf; behave as though the
+                * stat() above failed.  Even though we have already
+                * updated _nsconfmod, if the file reappears, the
+                * mtime will change.
+                */
+               goto out;
+       }
+
+       _NSVECT_FREE(_nsmap, &_nsmapsize, sizeof(*_nsmap),
+           (_nsvect_free_elem) _nsdbtfree);
+       _NSVECT_FREE(_nsmod, &_nsmodsize, sizeof(*_nsmod),
+           (_nsvect_free_elem) _nsmodfree);
+
+       _nsloadbuiltin();
+
+       _nsyyparse();
+       (void) fclose(_nsyyin);
+       if (_nsmapsize != 0)
+               qsort(_nsmap, _nsmapsize, sizeof(*_nsmap), _nsdbtcmp);
+
+       _nsconfmod = statbuf.st_mtime;
+
+ out:
+       rwlock_unlock(&_nslock);
+       mutex_unlock(&_nsconflock);
+       return (0);
+}
+
+static nss_method
+_nsmethod(const char *source, const char *database, const char *method,
+    const ns_dtab disp_tab[], void **cb_data)
+{
+       int     curdisp;
+       ns_mod  *mod, modkey;
+       ns_mtab *mtab, mtabkey;
+
+       if (disp_tab != NULL) {
+               for (curdisp = 0; disp_tab[curdisp].src != NULL; curdisp++) {
+                       if (strcasecmp(source, disp_tab[curdisp].src) == 0) {
+                               *cb_data = disp_tab[curdisp].cb_data;
+                               return (disp_tab[curdisp].callback);
+                       }
+               }
+       }
+
+       modkey.name = source;
+       mod = bsearch(&modkey, _nsmod, _nsmodsize, sizeof(*_nsmod),
+           _nsmodcmp);
+       if (mod != NULL && mod->handle != NULL) {
+               mtabkey.database = database;
+               mtabkey.name = method;
+               mtab = bsearch(&mtabkey, mod->mtab, mod->mtabsize,
+                   sizeof(mod->mtab[0]), _nsmtabcmp);
+               if (mtab != NULL) {
+                       *cb_data = mtab->mdata;
+                       return (mtab->method);
+               }
+       }
+
+       *cb_data = NULL;
+       return (NULL);
+}
+
+int
+/*ARGSUSED*/
+nsdispatch(void *retval, const ns_dtab disp_tab[], const char *database,
+           const char *method, const ns_src defaults[], ...)
+{
+       static int       _nsdispatching;
+#ifdef _REENTRANT
+       struct _ns_drec  drec, *ldrec;
+#endif
+       va_list          ap;
+       int              i, result;
+       ns_dbt           key;
+       const ns_dbt    *dbt;
+       const ns_src    *srclist;
+       int              srclistsize;
+       nss_method       cb;
+       void            *cb_data;
+
+       /* retval may be NULL */
+       /* disp_tab may be NULL */
+       _DIAGASSERT(database != NULL);
+       _DIAGASSERT(method != NULL);
+       _DIAGASSERT(defaults != NULL);
+       if (database == NULL || method == NULL || defaults == NULL)
+               return (NS_UNAVAIL);
+
+       /*
+        * In both the threaded and non-threaded cases, avoid reloading
+        * the configuration if the current thread is already running
+        * nsdispatch() (i.e. recursive call).
+        *
+        * In the non-threaded case, this avoids changing the data structures
+        * while we're using them.
+        *
+        * In the threaded case, this avoids trying to take a write lock
+        * while the current thread holds a read lock (which would result
+        * in deadlock).
+        */
+#ifdef _REENTRANT
+       if (__isthreaded) {
+               drec.thr = thr_self();
+               mutex_lock(&_ns_drec_lock);
+               LIST_FOREACH(ldrec, &_ns_drec, list) {
+                       if (ldrec->thr == drec.thr)
+                               break;
+               }
+               LIST_INSERT_HEAD(&_ns_drec, &drec, list);
+               mutex_unlock(&_ns_drec_lock);
+               if (ldrec == NULL && _nsconfigure()) {
+                       mutex_lock(&_ns_drec_lock);
+                       LIST_REMOVE(&drec, list);
+                       mutex_unlock(&_ns_drec_lock);
+                       return (NS_UNAVAIL);
+               }
+       } else
+#endif /* _REENTRANT */
+       if (_nsdispatching++ == 0 && _nsconfigure()) {
+               _nsdispatching--;
+               return (NS_UNAVAIL);
+       }
+
+       rwlock_rdlock(&_nslock);
+
+       key.name = database;
+       dbt = bsearch(&key, _nsmap, _nsmapsize, sizeof(*_nsmap), _nsdbtcmp);
+       if (dbt != NULL) {
+               srclist = dbt->srclist;
+               srclistsize = dbt->srclistsize;
+       } else {
+               srclist = defaults;
+               srclistsize = 0;
+               while (srclist[srclistsize].name != NULL)
+                       srclistsize++;
+       }
+       result = 0;
+
+       for (i = 0; i < srclistsize; i++) {
+               cb = _nsmethod(srclist[i].name, database, method,
+                   disp_tab, &cb_data);
+               result = 0;
+               if (cb != NULL) {
+                       va_start(ap, defaults);
+                       result = (*cb)(retval, cb_data, ap);
+                       va_end(ap);
+                       if (defaults[0].flags & NS_FORCEALL)
+                               continue;
+                       if (result & srclist[i].flags)
+                               break;
+               }
+       }
+       result &= NS_STATUSMASK;        /* clear private flags in result */
+
+       rwlock_unlock(&_nslock);
+
+#ifdef _REENTRANT
+       if (__isthreaded) {
+               mutex_lock(&_ns_drec_lock);
+               LIST_REMOVE(&drec, list);
+               mutex_unlock(&_ns_drec_lock);
+       } else
+#endif /* _REENTRANT */
+               _nsdispatching--;
+
+       return (result ? result : NS_NOTFOUND);
+}
diff --git a/lib/nbsd_libc/net/nslexer.l b/lib/nbsd_libc/net/nslexer.l
new file mode 100644 (file)
index 0000000..45381d1
--- /dev/null
@@ -0,0 +1,109 @@
+%{
+/*     $NetBSD: nslexer.l,v 1.11 2010/12/08 03:19:19 christos Exp $    */
+
+/*-
+ * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Luke Mewburn.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nslexer.l,v 1.11 2010/12/08 03:19:19 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <ctype.h>
+#define _NS_PRIVATE
+#include <nsswitch.h>
+#include <string.h>
+#include <syslog.h>
+
+#include "nsparser.h"
+
+%}
+
+%option yylineno nounput noinput
+%option never-interactive
+
+BLANK          [ \t]
+CR             \n
+STRING         [a-zA-Z][a-zA-Z0-9_]*
+
+%%
+
+{BLANK}+       ;                       /* skip whitespace */
+
+#.*            ;                       /* skip comments */
+
+\\{CR}         ;                       /* allow continuation */
+
+{CR}           return NL;
+
+[sS][uU][cC][cC][eE][sS][sS]           return SUCCESS;
+[uU][nN][aA][vV][aA][iI][lL]           return UNAVAIL;
+[nN][oO][tT][fF][oO][uU][nN][dD]       return NOTFOUND;
+[tT][rR][yY][aA][gG][aA][iI][nN]       return TRYAGAIN;
+
+[rR][eE][tT][uU][rR][nN]               return RETURN;
+[cC][oO][nN][tT][iI][nN][uU][eE]       return CONTINUE;
+
+{STRING}       {
+                       char *p;
+                       size_t i;
+
+                       if ((p = strdup(yytext)) == NULL) {
+                               syslog(LOG_ERR, "libc nsdispatch: %m");
+                               return NL;
+                       }
+
+                       for (i = 0; i < strlen(p); i++) {
+                               if (isupper((unsigned char)p[i]))
+                                       p[i] = tolower((unsigned char)p[i]);
+                       }
+                       _nsyylval.str = p;
+                       return STRING;
+               }
+
+.              return yytext[0];
+
+%%
+
+#undef _nsyywrap
+int
+_nsyywrap()
+{
+       return 1;
+} /* _nsyywrap */
+
+void
+_nsyyerror(msg)
+       const char *msg;
+{
+
+        syslog(LOG_WARNING, "libc nsdispatch: %s line %d: %s at '%s'",
+           _PATH_NS_CONF, yylineno, msg, yytext);
+} /* _nsyyerror */
diff --git a/lib/nbsd_libc/net/nsparser.y b/lib/nbsd_libc/net/nsparser.y
new file mode 100644 (file)
index 0000000..5845eca
--- /dev/null
@@ -0,0 +1,192 @@
+%{
+/*     $NetBSD: nsparser.y,v 1.11 2009/02/05 13:21:11 lukem Exp $      */
+
+/*-
+ * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Luke Mewburn.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nsparser.y,v 1.11 2009/02/05 13:21:11 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#define _NS_PRIVATE
+#include <nsswitch.h>
+#include <stdio.h>
+#include <string.h>
+#include <syslog.h>
+
+
+static void    _nsaddsrctomap __P((const char *));
+
+static ns_dbt          curdbt;
+static ns_src          cursrc;
+
+extern char *  _nsyytext;
+extern int _nsyylineno;
+%}
+
+%union {
+       char *str;
+       int   mapval;
+}
+
+%token NL
+%token SUCCESS UNAVAIL NOTFOUND TRYAGAIN
+%token RETURN CONTINUE
+%token <str> STRING
+
+%type  <mapval> Status Action
+
+%%
+
+File
+       :       /* empty */
+       | Lines
+       ;
+
+Lines
+       : Entry
+       | Lines Entry
+       ;
+
+Entry
+       : NL
+       | Database ':' NL
+       | Database ':' Srclist NL
+               {
+                       int lineno;
+
+                       lineno = _nsyylineno - (*_nsyytext == '\n' ? 1 : 0);
+                       if (_nsdbtput(&curdbt) == -1)
+                               syslog(LOG_WARNING,
+                                   "libc nsdispatch: %s line %d: %s",
+                                   _PATH_NS_CONF, lineno,
+                                   "error adding entry");
+               }
+       | error NL
+               {
+                       yyerrok;
+               }
+       ;
+
+Database
+       : STRING
+               {
+                       curdbt.name = yylval.str;
+                       curdbt.srclist = NULL;
+                       curdbt.srclistsize = 0;
+               }
+       ;
+
+Srclist
+       : Item
+       | Srclist Item
+       ;
+
+Item
+       : STRING
+               {
+                       cursrc.flags = NS_SUCCESS;
+                       _nsaddsrctomap($1);
+               }
+       | STRING '[' { cursrc.flags = NS_SUCCESS; } Criteria ']'
+               {
+                       _nsaddsrctomap($1);
+               }
+       ;
+
+Criteria
+       : Criterion
+       | Criteria Criterion
+       ;
+
+Criterion
+       : Status '=' Action
+               {
+                       if ($3)         /* if action == RETURN set RETURN bit */
+                               cursrc.flags |= $1;  
+                       else            /* else unset it */
+                               cursrc.flags &= ~$1;
+               }
+       ;
+
+Status
+       : SUCCESS       { $$ = NS_SUCCESS; }
+       | UNAVAIL       { $$ = NS_UNAVAIL; }
+       | NOTFOUND      { $$ = NS_NOTFOUND; }
+       | TRYAGAIN      { $$ = NS_TRYAGAIN; }
+       ;
+
+Action
+       : RETURN        { $$ = 1L; }
+       | CONTINUE      { $$ = 0L; }
+       ;
+
+%%
+
+static void
+_nsaddsrctomap(elem)
+       const char *elem;
+{
+       unsigned int    i;
+       int             lineno;
+
+       _DIAGASSERT(elem != NULL);
+
+       lineno = _nsyylineno - (*_nsyytext == '\n' ? 1 : 0);
+       if (curdbt.srclistsize > 0) {
+               if ((strcasecmp(elem, NSSRC_COMPAT) == 0) ||
+                   (strcasecmp(curdbt.srclist[0].name, NSSRC_COMPAT) == 0)) {
+                       syslog(LOG_WARNING,
+                           "libc nsdispatch: %s line %d: %s",
+                           _PATH_NS_CONF, lineno,
+                           "'compat' used with other sources");
+                       return;
+               }
+       }
+       for (i = 0; i < curdbt.srclistsize; i++) {
+               if (strcasecmp(curdbt.srclist[i].name, elem) == 0) {
+                       syslog(LOG_WARNING,
+                           "libc nsdispatch: %s line %d: %s '%s'",
+                           _PATH_NS_CONF, lineno,
+                           "duplicate source", elem);
+                       return;
+               }
+       }
+       cursrc.name = elem;
+       if (_nsdbtaddsrc(&curdbt, &cursrc) == -1) {
+               syslog(LOG_WARNING,
+                   "libc nsdispatch: %s line %d: %s '%s'",
+                   _PATH_NS_CONF, lineno,
+                   "error adding", elem);
+       }
+}
diff --git a/lib/nbsd_libc/net/protoent.h b/lib/nbsd_libc/net/protoent.h
new file mode 100644 (file)
index 0000000..4c98a64
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: protoent.h,v 1.2 2008/04/28 20:23:00 martin Exp $      */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <stdio.h>
+
+struct protoent_data {
+        FILE *fp;
+       struct protoent proto;
+       char **aliases;
+       size_t maxaliases;
+       int stayopen;
+       char *line;
+       void *dummy;
+};
+
+struct protoent        *getprotoent_r(struct protoent *, struct protoent_data *);
+struct protoent        *getprotobyname_r(const char *,
+    struct protoent *, struct protoent_data *);
+struct protoent        *getprotobynumber_r(int,
+    struct protoent *, struct protoent_data *);
+void setprotoent_r(int, struct protoent_data *);
+void endprotoent_r(struct protoent_data *);
diff --git a/lib/nbsd_libc/net/rcmd.3 b/lib/nbsd_libc/net/rcmd.3
new file mode 100644 (file)
index 0000000..41b8ef0
--- /dev/null
@@ -0,0 +1,311 @@
+.\"    $NetBSD: rcmd.3,v 1.28 2010/03/22 19:30:54 joerg Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)rcmd.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd March 30, 2005
+.Dt RCMD 3
+.Os
+.Sh NAME
+.Nm rcmd ,
+.Nm orcmd ,
+.Nm rcmd_af ,
+.Nm orcmd_af ,
+.Nm rresvport ,
+.Nm rresvport_af ,
+.Nm iruserok ,
+.Nm ruserok ,
+.Nm iruserok_sa
+.Nd routines for returning a stream to a remote command
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn rcmd "char **ahost" "int inport" "const char *locuser" "const char *remuser" "const char *cmd" "int *fd2p"
+.Ft int
+.Fn orcmd "char **ahost" "int inport" "const char *locuser" "const char *remuser" "const char *cmd" "int *fd2p"
+.Ft int
+.Fn rcmd_af "char **ahost" "int inport" "const char *locuser" "const char *remuser" "const char *cmd" "int *fd2p" "int af"
+.Ft int
+.Fn orcmd_af "char **ahost" "int inport" "const char *locuser" "const char *remuser" "const char *cmd" "int *fd2p" "int af"
+.Ft int
+.Fn rresvport "int *port"
+.Ft int
+.Fn rresvport_af "int *port" "int family"
+.Ft int
+.Fn iruserok "uint32_t raddr" "int superuser" "const char *ruser" "const char *luser"
+.Ft int
+.Fn ruserok "const char *rhost" "int superuser" "const char *ruser" "const char *luser"
+.Ft int
+.Fn iruserok_sa "const void *raddr" "int rlen" "int superuser" "const char *ruser" "const char *luser"
+.Sh DESCRIPTION
+The
+.Fn rcmd
+function is available for use by anyone to run commands on a
+remote system.  It acts like the
+.Fn orcmd
+command, with the exception that it makes a call out to the
+.Xr rcmd 1
+command, or any other user-specified command, to perform the
+actual connection (thus not requiring
+that the caller be running as the super-user), and is only
+available for the
+.Dq shell/tcp
+port.
+The
+.Fn orcmd
+function
+is used by the super-user to execute a command on
+a remote machine using an authentication scheme based
+on reserved port numbers.
+While
+.Fn rcmd
+and
+.Fn orcmd
+can only handle IPv4 address in the first argument,
+.Fn rcmd_af
+and
+.Fn orcmd_af
+can handle other cases as well.
+The
+.Fn rresvport
+function
+returns a descriptor to a socket
+with an address in the privileged port space.
+The
+.Fn rresvport_af
+function is similar to
+.Fn rresvport ,
+but you can explicitly specify the address family to use.
+Calling
+.Fn rresvport_af
+with
+.Dv AF_INET
+has the same effect as
+.Fn rresvport .
+The
+.Fn iruserok
+and
+.Fn ruserok
+functions are used by servers
+to authenticate clients requesting service with
+.Fn rcmd .
+All six functions are present in the same file and are used
+by the
+.Xr rshd 8
+server (among others).
+.Fn iruserok_sa
+is an address family independent variant of
+.Fn iruserok .
+.Pp
+The
+.Fn rcmd
+function
+looks up the host
+.Fa *ahost
+using
+.Xr gethostbyname 3 ,
+returning \-1 if the host does not exist.
+Otherwise
+.Fa *ahost
+is set to the standard name of the host
+and a connection is established to a server
+residing at the well-known Internet port
+.Fa inport .
+.Pp
+If the connection succeeds,
+a socket in the Internet domain of type
+.Dv SOCK_STREAM
+is returned to the caller, and given to the remote
+command as
+.Em stdin
+and
+.Em stdout .
+If
+.Fa fd2p
+is non-zero, then an auxiliary channel to a control
+process will be set up, and a descriptor for it will be placed
+in
+.Fa *fd2p .
+The control process will return diagnostic
+output from the command (unit 2) on this channel, and will also
+accept bytes on this channel as being
+.Ux
+signal numbers, to be
+forwarded to the process group of the command.
+If
+.Fa fd2p
+is 0, then the
+.Em stderr
+(unit 2 of the remote
+command) will be made the same as the
+.Em stdout
+and no
+provision is made for sending arbitrary signals to the remote process,
+although you may be able to get its attention by using out-of-band data.
+.Pp
+.Fn rcmd_af
+and
+.Fn orcmd_af
+take address family in the last argument.
+If the last argument is
+.Dv PF_UNSPEC ,
+interpretation of
+.Fa *ahost
+will obey the underlying address resolution like DNS.
+.Pp
+The protocol is described in detail in
+.Xr rshd 8 .
+.Pp
+The
+.Fn rresvport
+and
+.Fn rresvport_af
+functions are used to obtain a socket with a privileged
+address bound to it.  This socket is suitable for use
+by
+.Fn rcmd
+and several other functions.  Privileged Internet ports are those
+in the range 0 to 1023.  Only the super-user
+is allowed to bind an address of this sort to a socket.
+.Pp
+The
+.Fn iruserok
+and
+.Fn ruserok
+functions take a remote host's IP address or name, respectively,
+two user names and a flag indicating whether the local user's
+name is that of the super-user.
+Then, if the user is
+.Em NOT
+the super-user, it checks the
+.Pa /etc/hosts.equiv
+file.
+If that lookup is not done, or is unsuccessful, the
+.Pa .rhosts
+in the local user's home directory is checked to see if the request for
+service is allowed.
+.Pp
+If this file does not exist, is not a regular file, is owned by anyone
+other than the user or the super-user, or is writable by anyone other
+than the owner, the check automatically fails.
+Zero is returned if the machine name is listed in the
+.Dq Pa hosts.equiv
+file, or the host and remote user name are found in the
+.Dq Pa .rhosts
+file; otherwise
+.Fn iruserok
+and
+.Fn ruserok
+return \-1.
+If the local domain (as obtained from
+.Xr gethostname 3 )
+is the same as the remote domain, only the machine name need be specified.
+.Pp
+If the IP address of the remote host is known,
+.Fn iruserok
+should be used in preference to
+.Fn ruserok ,
+as it does not require trusting the DNS server for the remote host's domain.
+.Pp
+While
+.Fn iruserok
+can handle IPv4 addresses only,
+.Fn iruserok_sa
+and
+.Fn ruserok
+can handle other address families as well, like IPv6.
+The first argument of
+.Fn iruserok_sa
+is typed as
+.Fa "void *"
+to avoid dependency between
+.In unistd.h
+and
+.In sys/socket.h .
+.Sh ENVIRONMENT
+.Bl -tag -width RCMD_CMDxx -compact
+.It Ev RCMD_CMD
+When using the
+.Fn rcmd
+function, this variable is used as the program to run instead of
+.Xr rcmd 1 .
+.El
+.Sh DIAGNOSTICS
+The
+.Fn rcmd
+function
+returns a valid socket descriptor on success.
+It returns \-1 on error and prints a diagnostic message on the standard error.
+.Pp
+The
+.Fn rresvport
+and
+.Fn rresvport_af
+function
+return a valid, bound socket descriptor on success.
+They return \-1 on error with the global value
+.Va errno
+set according to the reason for failure.
+The error code
+.Dv EAGAIN
+is overloaded to mean ``All network ports in use.''
+.Sh SEE ALSO
+.Xr rcmd 1 ,
+.Xr rlogin 1 ,
+.Xr rsh 1 ,
+.Xr intro 2 ,
+.Xr rexec 3 ,
+.Xr hosts.equiv 5 ,
+.Xr rhosts 5 ,
+.Xr rexecd 8 ,
+.Xr rlogind 8 ,
+.Xr rshd 8
+.Sh HISTORY
+The
+.Fn orcmd ,
+.Fn rresvport ,
+.Fn iruserok
+and
+.Fn ruserok
+functions appeared in
+.Bx 4.2 ,
+where the
+.Fn orcmd
+function was called
+.Fn rcmd .
+The (newer)
+.Fn rcmd
+function appeared in
+.Nx 1.3 .
+.Fn rcmd_af
+and
+.Fn rresvport_af
+were defined in RFC2292.
diff --git a/lib/nbsd_libc/net/rcmd.c b/lib/nbsd_libc/net/rcmd.c
new file mode 100644 (file)
index 0000000..8e136ee
--- /dev/null
@@ -0,0 +1,1025 @@
+/*     $NetBSD: rcmd.c,v 1.65 2007/01/03 11:46:22 ws Exp $     */
+
+/*
+ * Copyright (c) 1983, 1993, 1994
+ *     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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)rcmd.c     8.3 (Berkeley) 3/26/94";
+#else
+__RCSID("$NetBSD: rcmd.c,v 1.65 2007/01/03 11:46:22 ws Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef _LIBC
+#include "namespace.h"
+#endif
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/poll.h>
+#include <sys/wait.h>
+
+#include <netinet/in.h>
+#include <rpc/rpc.h>
+#include <arpa/inet.h>
+#include <netgroup.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <err.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <grp.h>
+#include <netdb.h>
+#include <paths.h>
+#include <pwd.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <syslog.h>
+#include <unistd.h>
+
+#include "pathnames.h"
+
+int    orcmd __P((char **, u_int, const char *, const char *, const char *,
+           int *));
+int    orcmd_af __P((char **, u_int, const char *, const char *, const char *,
+           int *, int));
+int    __ivaliduser __P((FILE *, u_int32_t, const char *, const char *));
+int    __ivaliduser_sa __P((FILE *, const struct sockaddr *, socklen_t,
+           const char *, const char *));
+static int rshrcmd __P((char **, u_int32_t, const char *, const char *,
+           const char *, int *, const char *));
+static int resrcmd __P((struct addrinfo *, char **, u_int32_t, const char *,
+           const char *, const char *, int *));
+static int __icheckhost __P((const struct sockaddr *, socklen_t,
+           const char *));
+static char *__gethostloop __P((const struct sockaddr *, socklen_t));
+
+int
+rcmd(ahost, rport, locuser, remuser, cmd, fd2p)
+       char **ahost;
+       u_short rport;
+       const char *locuser, *remuser, *cmd;
+       int *fd2p;
+{
+
+       return rcmd_af(ahost, rport, locuser, remuser, cmd, fd2p, AF_INET);
+}
+
+int
+rcmd_af(ahost, rport, locuser, remuser, cmd, fd2p, af)
+       char **ahost;
+       u_short rport;
+       const char *locuser, *remuser, *cmd;
+       int *fd2p;
+       int af;
+{
+       static char hbuf[MAXHOSTNAMELEN];
+       char pbuf[NI_MAXSERV];
+       struct addrinfo hints, *res;
+       int error;
+       struct servent *sp;
+
+       _DIAGASSERT(ahost != NULL);
+       _DIAGASSERT(locuser != NULL);
+       _DIAGASSERT(remuser != NULL);
+       _DIAGASSERT(cmd != NULL);
+       /* fd2p may be NULL */
+
+       snprintf(pbuf, sizeof(pbuf), "%u", ntohs(rport));
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = af;
+       hints.ai_socktype = SOCK_STREAM;
+       hints.ai_flags = AI_CANONNAME;
+       error = getaddrinfo(*ahost, pbuf, &hints, &res);
+       if (error) {
+               warnx("%s: %s", *ahost, gai_strerror(error));   /*XXX*/
+               return (-1);
+       }
+       if (res->ai_canonname) {
+               /*
+                * Canonicalise hostname.
+                * XXX: Should we really do this?
+                */
+               strlcpy(hbuf, res->ai_canonname, sizeof(hbuf));
+               *ahost = hbuf;
+       }
+
+       /*
+        * Check if rport is the same as the shell port, and that the fd2p.  If
+        * it is not, the program isn't expecting 'rsh' and so we can't use the
+        * RCMD_CMD environment.
+        */
+       sp = getservbyname("shell", "tcp");
+       if (sp != NULL && sp->s_port == rport)
+               error = rshrcmd(ahost, (u_int32_t)rport,
+                   locuser, remuser, cmd, fd2p, getenv("RCMD_CMD"));
+       else
+               error = resrcmd(res, ahost, (u_int32_t)rport,
+                   locuser, remuser, cmd, fd2p);
+       freeaddrinfo(res);
+       return (error);
+}
+
+/* this is simply a wrapper around hprcmd() that handles ahost first */
+int
+orcmd(ahost, rport, locuser, remuser, cmd, fd2p)
+       char **ahost;
+       u_int rport;
+       const char *locuser, *remuser, *cmd;
+       int *fd2p;
+{
+       return orcmd_af(ahost, rport, locuser, remuser, cmd, fd2p, AF_INET);
+}
+
+int
+orcmd_af(ahost, rport, locuser, remuser, cmd, fd2p, af)
+       char **ahost;
+       u_int rport;
+       const char *locuser, *remuser, *cmd;
+       int *fd2p;
+       int af;
+{
+       static char hbuf[MAXHOSTNAMELEN];
+       char pbuf[NI_MAXSERV];
+       struct addrinfo hints, *res;
+       int error;
+
+       _DIAGASSERT(ahost != NULL);
+       _DIAGASSERT(locuser != NULL);
+       _DIAGASSERT(remuser != NULL);
+       _DIAGASSERT(cmd != NULL);
+       /* fd2p may be NULL */
+
+       snprintf(pbuf, sizeof(pbuf), "%u", ntohs(rport));
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = af;
+       hints.ai_socktype = SOCK_STREAM;
+       hints.ai_flags = AI_CANONNAME;
+       error = getaddrinfo(*ahost, pbuf, &hints, &res);
+       if (error) {
+               warnx("%s: %s", *ahost, gai_strerror(error));   /*XXX*/
+               return (-1);
+       }
+       if (res->ai_canonname) {
+               strlcpy(hbuf, res->ai_canonname, sizeof(hbuf));
+               *ahost = hbuf;
+       }
+       
+       error = resrcmd(res, ahost, rport, locuser, remuser, cmd, fd2p);
+       freeaddrinfo(res);
+       return (error);
+}
+
+/*ARGSUSED*/
+static int
+resrcmd(res, ahost, rport, locuser, remuser, cmd, fd2p)
+       struct addrinfo *res;
+       char **ahost;
+       u_int32_t rport;
+       const char *locuser, *remuser, *cmd;
+       int *fd2p;
+{
+       struct addrinfo *r;
+       struct sockaddr_storage from;
+       struct pollfd reads[2];
+       sigset_t nmask, omask;
+       pid_t pid;
+       int s, lport, timo;
+       int pollr;
+       char c;
+       int refused;
+
+       _DIAGASSERT(res != NULL);
+       _DIAGASSERT(ahost != NULL);
+       _DIAGASSERT(locuser != NULL);
+       _DIAGASSERT(remuser != NULL);
+       _DIAGASSERT(cmd != NULL);
+       /* fd2p may be NULL */
+
+       r = res;
+       refused = 0;
+       pid = getpid();
+       sigemptyset(&nmask);
+       sigaddset(&nmask, SIGURG);
+       if (sigprocmask(SIG_BLOCK, &nmask, &omask) == -1)
+               return -1;
+       for (timo = 1, lport = IPPORT_RESERVED - 1;;) {
+               s = rresvport_af(&lport, r->ai_family);
+               if (s < 0) {
+                       if (errno == EAGAIN)
+                               warnx("rcmd: socket: All ports in use");
+                       else
+                               warn("rcmd: socket");
+                       if (r->ai_next) {
+                               r = r->ai_next;
+                               continue;
+                       } else {
+                               (void)sigprocmask(SIG_SETMASK, &omask, NULL);
+                               return (-1);
+                       }
+               }
+               fcntl(s, F_SETOWN, pid);
+               if (connect(s, r->ai_addr, r->ai_addrlen) >= 0)
+                       break;
+               (void)close(s);
+               if (errno == EADDRINUSE) {
+                       lport--;
+                       continue;
+               } else if (errno == ECONNREFUSED)
+                       refused++;
+               if (r->ai_next) {
+                       int oerrno = errno;
+                       char hbuf[NI_MAXHOST];
+                       const int niflags = NI_NUMERICHOST;
+
+                       hbuf[0] = '\0';
+                       if (getnameinfo(r->ai_addr, r->ai_addrlen,
+                           hbuf, sizeof(hbuf), NULL, 0, niflags) != 0)
+                               strlcpy(hbuf, "(invalid)", sizeof(hbuf));
+                       errno = oerrno;
+                       warn("rcmd: connect to address %s", hbuf);
+                       r = r->ai_next;
+                       hbuf[0] = '\0';
+                       if (getnameinfo(r->ai_addr, r->ai_addrlen,
+                           hbuf, sizeof(hbuf), NULL, 0, niflags) != 0)
+                               strlcpy(hbuf, "(invalid)", sizeof(hbuf));
+                       (void)fprintf(stderr, "Trying %s...\n", hbuf);
+                       continue;
+               }
+               if (refused && timo <= 16) {
+                       (void)sleep((unsigned int)timo);
+                       timo *= 2;
+                       r = res;
+                       refused = 0;
+                       continue;
+               }
+               (void)fprintf(stderr, "%s: %s\n", res->ai_canonname,
+                   strerror(errno));
+               (void)sigprocmask(SIG_SETMASK, &omask, NULL);
+               return (-1);
+       }
+       lport--;
+       if (fd2p == 0) {
+               write(s, "", 1);
+               lport = 0;
+       } else {
+               char num[8];
+               int s2 = rresvport_af(&lport, r->ai_family), s3;
+               socklen_t len = sizeof(from);
+
+               if (s2 < 0)
+                       goto bad;
+               listen(s2, 1);
+               (void)snprintf(num, sizeof(num), "%d", lport);
+               if (write(s, num, strlen(num) + 1) !=
+                   (ssize_t) (strlen(num) + 1)) {
+                       warn("rcmd: write (setting up stderr)");
+                       (void)close(s2);
+                       goto bad;
+               }
+               reads[0].fd = s;
+               reads[0].events = POLLIN;
+               reads[1].fd = s2;
+               reads[1].events = POLLIN;
+               errno = 0;
+               pollr = poll(reads, 2, INFTIM);
+               if (pollr < 1 || (reads[1].revents & POLLIN) == 0) {
+                       if (errno != 0)
+                               warn("poll: setting up stderr");
+                       else
+                               warnx("poll: protocol failure in circuit setup");
+                       (void)close(s2);
+                       goto bad;
+               }
+               s3 = accept(s2, (struct sockaddr *)(void *)&from, &len);
+               (void)close(s2);
+               if (s3 < 0) {
+                       warn("rcmd: accept");
+                       lport = 0;
+                       goto bad;
+               }
+               *fd2p = s3;
+               switch (((struct sockaddr *)(void *)&from)->sa_family) {
+               case AF_INET:
+#ifdef INET6
+               case AF_INET6:
+#endif
+                       if (getnameinfo((struct sockaddr *)(void *)&from, len,
+                           NULL, 0, num, sizeof(num), NI_NUMERICSERV) != 0 ||
+                           (atoi(num) >= IPPORT_RESERVED ||
+                            atoi(num) < IPPORT_RESERVED / 2)) {
+                               warnx("rcmd: protocol failure in circuit setup.");
+                               goto bad2;
+                       }
+                       break;
+               default:
+                       break;
+               }
+       }
+
+       (void)write(s, locuser, strlen(locuser)+1);
+       (void)write(s, remuser, strlen(remuser)+1);
+       (void)write(s, cmd, strlen(cmd)+1);
+       if (read(s, &c, 1) != 1) {
+               warn("%s", *ahost);
+               goto bad2;
+       }
+       if (c != 0) {
+               while (read(s, &c, 1) == 1) {
+                       (void)write(STDERR_FILENO, &c, 1);
+                       if (c == '\n')
+                               break;
+               }
+               goto bad2;
+       }
+       (void)sigprocmask(SIG_SETMASK, &omask, NULL);
+       return (s);
+bad2:
+       if (lport)
+               (void)close(*fd2p);
+bad:
+       (void)close(s);
+       (void)sigprocmask(SIG_SETMASK, &omask, NULL);
+       return (-1);
+}
+
+/*
+ * based on code written by Chris Siebenmann <cks@utcc.utoronto.ca>
+ */
+/* ARGSUSED */
+static int
+rshrcmd(ahost, rport, locuser, remuser, cmd, fd2p, rshcmd)
+       char    **ahost;
+       u_int32_t       rport;
+       const   char *locuser, *remuser, *cmd;
+       int     *fd2p;
+       const   char *rshcmd;
+{
+       pid_t pid;
+       int sp[2], ep[2];
+       char *p;
+       struct passwd *pw, pwres;
+       char pwbuf[1024];
+
+       _DIAGASSERT(ahost != NULL);
+       _DIAGASSERT(locuser != NULL);
+       _DIAGASSERT(remuser != NULL);
+       _DIAGASSERT(cmd != NULL);
+       /* fd2p may be NULL */
+
+       /* What rsh/shell to use. */
+       if (rshcmd == NULL)
+               rshcmd = _PATH_BIN_RCMD;
+
+       /* locuser must exist on this host. */
+       if (getpwnam_r(locuser, &pwres, pwbuf, sizeof(pwbuf), &pw) != 0 ||
+           pw == NULL) {
+               warnx("rshrcmd: unknown user: %s", locuser);
+               return(-1);
+       }
+
+       /* get a socketpair we'll use for stdin and stdout. */
+       if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sp) < 0) {
+               warn("rshrcmd: socketpair");
+               return (-1);
+       }
+       /* we will use this for the fd2 pointer */
+       if (fd2p) {
+               if (socketpair(AF_LOCAL, SOCK_STREAM, 0, ep) < 0) {
+                       warn("rshrcmd: socketpair");
+                       return (-1);
+               }
+               *fd2p = ep[0];
+       }
+       
+       pid = fork();
+       if (pid < 0) {
+               warn("rshrcmd: fork");
+               return (-1);
+       }
+       if (pid == 0) {
+               /*
+                * child
+                * - we use sp[1] to be stdin/stdout, and close sp[0]
+                * - with fd2p, we use ep[1] for stderr, and close ep[0]
+                */
+               (void)close(sp[0]);
+               if (dup2(sp[1], 0) < 0 || dup2(0, 1) < 0) {
+                       warn("rshrcmd: dup2");
+                       _exit(1);
+               }
+               (void)close(sp[1]);
+               if (fd2p) {
+                       if (dup2(ep[1], 2) < 0) {
+                               warn("rshrcmd: dup2");
+                               _exit(1);
+                       }
+                       (void)close(ep[0]);
+                       (void)close(ep[1]);
+               } else if (dup2(0, 2) < 0) {
+                       warn("rshrcmd: dup2");
+                       _exit(1);
+               }
+               /* fork again to lose parent. */
+               pid = fork();
+               if (pid < 0) {
+                       warn("rshrcmd: second fork");
+                       _exit(1);
+               }
+               if (pid > 0)
+                       _exit(0);
+
+               /* Orphan.  Become local user for rshprog. */
+               if (setuid(pw->pw_uid)) {
+                       warn("rshrcmd: setuid(%lu)", (u_long)pw->pw_uid);
+                       _exit(1);
+               }
+
+               /*
+                * If we are rcmd'ing to "localhost" as the same user as we are,
+                * then avoid running remote shell for efficiency.
+                */
+               if (strcmp(*ahost, "localhost") == 0 &&
+                   strcmp(locuser, remuser) == 0) {
+                       if (pw->pw_shell[0] == '\0')
+                               rshcmd = _PATH_BSHELL;
+                       else
+                               rshcmd = pw->pw_shell;
+                       p = strrchr(rshcmd, '/');
+                       execlp(rshcmd, p ? p + 1 : rshcmd, "-c", cmd, NULL);
+               } else {
+                       p = strrchr(rshcmd, '/');
+                       execlp(rshcmd, p ? p + 1 : rshcmd, *ahost, "-l",
+                           remuser, cmd, NULL);
+               }
+               warn("rshrcmd: exec %s", rshcmd);
+               _exit(1);
+       }
+       /* Parent */
+       (void)close(sp[1]);
+       if (fd2p)
+               (void)close(ep[1]);
+
+       (void)waitpid(pid, NULL, 0);
+       return (sp[0]);
+}
+
+int
+rresvport(alport)
+       int *alport;
+{
+
+       _DIAGASSERT(alport != NULL);
+
+       return rresvport_af(alport, AF_INET);
+}
+
+int
+rresvport_af(alport, family)
+       int *alport;
+       int family;
+{
+       struct sockaddr_storage ss;
+       struct sockaddr *sa;
+       int salen;
+       int s;
+       u_int16_t *portp;
+
+       _DIAGASSERT(alport != NULL);
+
+       memset(&ss, 0, sizeof(ss));
+       sa = (struct sockaddr *)(void *)&ss;
+       switch (family) {
+       case AF_INET:
+#ifdef BSD4_4
+               sa->sa_len =
+#endif
+               salen = sizeof(struct sockaddr_in);
+               portp = &((struct sockaddr_in *)(void *)sa)->sin_port;
+               break;
+#ifdef INET6
+       case AF_INET6:
+#ifdef BSD4_4
+               sa->sa_len =
+#endif
+               salen = sizeof(struct sockaddr_in6);
+               portp = &((struct sockaddr_in6 *)(void *)sa)->sin6_port;
+               break;
+#endif
+       default:
+               errno = EAFNOSUPPORT;
+               return (-1);
+       }
+       sa->sa_family = family;
+       s = socket(family, SOCK_STREAM, 0);
+       if (s < 0)
+               return (-1);
+#ifdef BSD4_4
+       switch (family) {
+       case AF_INET:
+       case AF_INET6:
+               *portp = 0;
+               if (bindresvport(s, (struct sockaddr_in *)(void *)sa) < 0) {
+                       int sverr = errno;
+
+                       (void)close(s);
+                       errno = sverr;
+                       return (-1);
+               }
+               *alport = (int)ntohs(*portp);
+               return (s);
+       default:
+               /* is it necessary to try keep code for other AFs? */
+               break;
+       }
+#endif
+       for (;;) {
+               *portp = htons((u_short)*alport);
+               if (bind(s, sa, (socklen_t)salen) >= 0)
+                       return (s);
+               if (errno != EADDRINUSE) {
+                       (void)close(s);
+                       return (-1);
+               }
+               (*alport)--;
+               if (*alport == IPPORT_RESERVED/2) {
+                       (void)close(s);
+                       errno = EAGAIN;         /* close */
+                       return (-1);
+               }
+       }
+}
+
+int    __check_rhosts_file = 1;
+const char *__rcmd_errstr;
+
+int
+ruserok(rhost, superuser, ruser, luser)
+       const char *rhost, *ruser, *luser;
+       int superuser;
+{
+       struct addrinfo hints, *res, *r;
+       int error;
+
+       _DIAGASSERT(rhost != NULL);
+       _DIAGASSERT(ruser != NULL);
+       _DIAGASSERT(luser != NULL);
+
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = PF_UNSPEC;
+       hints.ai_socktype = SOCK_DGRAM; /*dummy*/
+       error = getaddrinfo(rhost, "0", &hints, &res);
+       if (error)
+               return (-1);
+
+       for (r = res; r; r = r->ai_next) {
+               if (iruserok_sa(r->ai_addr, (int)r->ai_addrlen, superuser,
+                   ruser, luser) == 0) {
+                       freeaddrinfo(res);
+                       return (0);
+               }
+       }
+       freeaddrinfo(res);
+       return (-1);
+}
+
+/*
+ * New .rhosts strategy: We are passed an ip address. We spin through
+ * hosts.equiv and .rhosts looking for a match. When the .rhosts only
+ * has ip addresses, we don't have to trust a nameserver.  When it
+ * contains hostnames, we spin through the list of addresses the nameserver
+ * gives us and look for a match.
+ *
+ * Returns 0 if ok, -1 if not ok.
+ */
+int
+iruserok(raddr, superuser, ruser, luser)
+       u_int32_t raddr;
+       int superuser;
+       const char *ruser, *luser;
+{
+       struct sockaddr_in irsin;
+
+       memset(&irsin, 0, sizeof(irsin));
+       irsin.sin_family = AF_INET;
+#ifdef BSD4_4
+       irsin.sin_len = sizeof(struct sockaddr_in);
+#endif
+       memcpy(&irsin.sin_addr, &raddr, sizeof(irsin.sin_addr));
+       return iruserok_sa(&irsin, sizeof(struct sockaddr_in), superuser, ruser,
+                   luser);
+}
+
+/*
+ * 2nd and 3rd arguments are typed like this, to avoid dependency between
+ * unistd.h and sys/socket.h.  There's no better way.
+ */
+int
+iruserok_sa(raddr, rlen, superuser, ruser, luser)
+       const void *raddr;
+       int rlen;
+       int superuser;
+       const char *ruser, *luser;
+{
+       const struct sockaddr *sa;
+       struct stat sbuf;
+       struct passwd *pwd, pwres;
+       FILE *hostf;
+       uid_t uid;
+       gid_t gid;
+       int isvaliduser;
+       char pbuf[MAXPATHLEN];
+       char pwbuf[1024];
+
+       _DIAGASSERT(raddr != NULL);
+       _DIAGASSERT(ruser != NULL);
+       _DIAGASSERT(luser != NULL);
+
+       sa = raddr;
+
+       __rcmd_errstr = NULL;
+
+       hostf = superuser ? NULL : fopen(_PATH_HEQUIV, "r");
+
+       if (hostf) {
+               if (__ivaliduser_sa(hostf, sa, (socklen_t)rlen, luser,
+                   ruser) == 0) {
+                       (void)fclose(hostf);
+                       return (0);
+               }
+               (void)fclose(hostf);
+       }
+
+       isvaliduser = -1;
+       if (__check_rhosts_file || superuser) {
+
+               if (getpwnam_r(luser, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0
+                   || pwd == NULL)
+                       return (-1);
+               (void)strlcpy(pbuf, pwd->pw_dir, sizeof(pbuf));
+               (void)strlcat(pbuf, "/.rhosts", sizeof(pbuf));
+
+               /*
+                * Change effective uid while opening and reading .rhosts.
+                * If root and reading an NFS mounted file system, can't
+                * read files that are protected read/write owner only.
+                */
+               uid = geteuid();
+               gid = getegid();
+               (void)setegid(pwd->pw_gid);
+               initgroups(pwd->pw_name, pwd->pw_gid);
+               (void)seteuid(pwd->pw_uid);
+               hostf = fopen(pbuf, "r");
+
+               if (hostf != NULL) {
+                       /*
+                        * If not a regular file, or is owned by someone other
+                        * than user or root or if writable by anyone but the
+                        * owner, quit.
+                        */
+                       if (lstat(pbuf, &sbuf) < 0)
+                               __rcmd_errstr = ".rhosts lstat failed";
+                       else if (!S_ISREG(sbuf.st_mode))
+                               __rcmd_errstr = ".rhosts not regular file";
+                       else if (fstat(fileno(hostf), &sbuf) < 0)
+                               __rcmd_errstr = ".rhosts fstat failed";
+                       else if (sbuf.st_uid && sbuf.st_uid != pwd->pw_uid)
+                               __rcmd_errstr = "bad .rhosts owner";
+                       else if (sbuf.st_mode & (S_IWGRP|S_IWOTH))
+                               __rcmd_errstr =
+                                       ".rhosts writable by other than owner";
+                       else 
+                               isvaliduser =
+                                   __ivaliduser_sa(hostf, sa, (socklen_t)rlen,
+                                                   luser, ruser);
+
+                       (void)fclose(hostf);
+               }
+               (void)seteuid(uid);
+               (void)setegid(gid);
+
+       }
+       return (isvaliduser);
+}
+
+/*
+ * XXX
+ * Don't make static, used by lpd(8).  We will be able to change the function
+ * into static function, when we bump libc major #.
+ *
+ * Returns 0 if ok, -1 if not ok.
+ */
+#ifdef notdef  /*_LIBC*/
+static
+#endif
+int
+__ivaliduser(hostf, raddr, luser, ruser)
+       FILE *hostf;
+       u_int32_t raddr;
+       const char *luser, *ruser;
+{
+       struct sockaddr_in ivusin;
+
+       memset(&ivusin, 0, sizeof(ivusin));
+       ivusin.sin_family = AF_INET;
+#ifdef BSD4_4
+       ivusin.sin_len = sizeof(struct sockaddr_in);
+#endif
+       memcpy(&ivusin.sin_addr, &raddr, sizeof(ivusin.sin_addr));
+       return __ivaliduser_sa(hostf, (struct sockaddr *)(void *)&ivusin,
+           sizeof(struct sockaddr_in), luser, ruser);
+}
+
+#ifdef notdef  /*_LIBC*/
+static
+#endif
+int
+__ivaliduser_sa(hostf, raddr, salen, luser, ruser)
+       FILE *hostf;
+       const struct sockaddr *raddr;
+       socklen_t salen;
+       const char *luser, *ruser;
+{
+       register char *user, *p;
+       int ch;
+       char buf[MAXHOSTNAMELEN + 128];         /* host + login */
+       const char *auser, *ahost;
+       int hostok, userok;
+       char *rhost = NULL;
+       int firsttime = 1;
+       char domain[MAXHOSTNAMELEN];
+
+       getdomainname(domain, sizeof(domain));
+
+       _DIAGASSERT(hostf != NULL);
+       _DIAGASSERT(luser != NULL);
+       _DIAGASSERT(ruser != NULL);
+
+       while (fgets(buf, sizeof(buf), hostf)) {
+               p = buf;
+               /* Skip lines that are too long. */
+               if (strchr(p, '\n') == NULL) {
+                       while ((ch = getc(hostf)) != '\n' && ch != EOF)
+                               ;
+                       continue;
+               }
+               while (*p != '\n' && *p != ' ' && *p != '\t' && *p != '\0') {
+                       *p = isupper((unsigned char)*p) ?
+                           tolower((unsigned char)*p) : *p;
+                       p++;
+               }
+               if (*p == ' ' || *p == '\t') {
+                       *p++ = '\0';
+                       while (*p == ' ' || *p == '\t')
+                               p++;
+                       user = p;
+                       while (*p != '\n' && *p != ' ' &&
+                           *p != '\t' && *p != '\0')
+                               p++;
+               } else
+                       user = p;
+               *p = '\0';
+
+               if (p == buf)
+                       continue;
+
+               auser = *user ? user : luser;
+               ahost = buf;
+
+               if (ahost[0] == '+')
+                       switch (ahost[1]) {
+                       case '\0':
+                               hostok = 1;
+                               break;
+
+                       case '@':
+                               if (firsttime) {
+                                       rhost = __gethostloop(raddr, salen);
+                                       firsttime = 0;
+                               }
+                               if (rhost)
+                                       hostok = innetgr(&ahost[2], rhost,
+                                           NULL, domain);
+                               else
+                                       hostok = 0;
+                               break;
+
+                       default:
+                               hostok = __icheckhost(raddr, salen, &ahost[1]);
+                               break;
+                       }
+               else if (ahost[0] == '-')
+                       switch (ahost[1]) {
+                       case '\0':
+                               hostok = -1;
+                               break;
+
+                       case '@':
+                               if (firsttime) {
+                                       rhost = __gethostloop(raddr, salen);
+                                       firsttime = 0;
+                               }
+                               if (rhost)
+                                       hostok = -innetgr(&ahost[2], rhost,
+                                           NULL, domain);
+                               else
+                                       hostok = 0;
+                               break;
+
+                       default:
+                               hostok = -__icheckhost(raddr, salen, &ahost[1]);
+                               break;
+                       }
+               else
+                       hostok = __icheckhost(raddr, salen, ahost);
+
+
+               if (auser[0] == '+')
+                       switch (auser[1]) {
+                       case '\0':
+                               userok = 1;
+                               break;
+
+                       case '@':
+                               userok = innetgr(&auser[2], NULL, ruser,
+                                   domain);
+                               break;
+
+                       default:
+                               userok = strcmp(ruser, &auser[1]) == 0;
+                               break;
+                       }
+               else if (auser[0] == '-')
+                       switch (auser[1]) {
+                       case '\0':
+                               userok = -1;
+                               break;
+
+                       case '@':
+                               userok = -innetgr(&auser[2], NULL, ruser,
+                                   domain);
+                               break;
+
+                       default:
+                               userok =
+                                   -(strcmp(ruser, &auser[1]) == 0 ? 1 : 0);
+                               break;
+                       }
+               else
+                       userok = strcmp(ruser, auser) == 0;
+
+               /* Check if one component did not match */
+               if (hostok == 0 || userok == 0)
+                       continue;
+
+               /* Check if we got a forbidden pair */
+               if (userok == -1 || hostok == -1)
+                       return -1;
+
+               /* Check if we got a valid pair */
+               if (hostok == 1 && userok == 1)
+                       return 0;
+       }
+       return -1;
+}
+
+/*
+ * Returns "true" if match, 0 if no match.
+ */
+static int
+__icheckhost(raddr, salen, lhost)
+       const struct sockaddr *raddr;
+       socklen_t salen;
+       const char *lhost;
+{
+       struct addrinfo hints, *res, *r;
+       char h1[NI_MAXHOST], h2[NI_MAXHOST];
+       int error;
+       const int niflags = NI_NUMERICHOST;
+
+       _DIAGASSERT(raddr != NULL);
+       _DIAGASSERT(lhost != NULL);
+
+       h1[0] = '\0';
+       if (getnameinfo(raddr, salen, h1, sizeof(h1), NULL, 0,
+           niflags) != 0)
+               return (0);
+
+       /* Resolve laddr into sockaddr */
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = raddr->sa_family;
+       hints.ai_socktype = SOCK_DGRAM; /*dummy*/
+       res = NULL;
+       error = getaddrinfo(lhost, "0", &hints, &res);
+       if (error)
+               return (0);
+
+       /*
+        * Try string comparisons between raddr and laddr.
+        */
+       for (r = res; r; r = r->ai_next) {
+               h2[0] = '\0';
+               if (getnameinfo(r->ai_addr, r->ai_addrlen, h2, sizeof(h2),
+                   NULL, 0, niflags) != 0)
+                       continue;
+               if (strcmp(h1, h2) == 0) {
+                       freeaddrinfo(res);
+                       return (1);
+               }
+       }
+
+       /* No match. */
+       freeaddrinfo(res);
+       return (0);
+}
+
+/*
+ * Return the hostname associated with the supplied address.
+ * Do a reverse lookup as well for security. If a loop cannot
+ * be found, pack the numeric IP address into the string.
+ */
+static char *
+__gethostloop(raddr, salen)
+       const struct sockaddr *raddr;
+       socklen_t salen;
+{
+       static char remotehost[NI_MAXHOST];
+       char h1[NI_MAXHOST], h2[NI_MAXHOST];
+       struct addrinfo hints, *res, *r;
+       int error;
+       const int niflags = NI_NUMERICHOST;
+
+       _DIAGASSERT(raddr != NULL);
+
+       h1[0] = remotehost[0] = '\0';
+       if (getnameinfo(raddr, salen, remotehost, sizeof(remotehost),
+           NULL, 0, NI_NAMEREQD) != 0)
+               return (NULL);
+       if (getnameinfo(raddr, salen, h1, sizeof(h1), NULL, 0,
+           niflags) != 0)
+               return (NULL);
+
+       /*
+        * Look up the name and check that the supplied
+        * address is in the list
+        */
+       memset(&hints, 0, sizeof(hints));
+       hints.ai_family = raddr->sa_family;
+       hints.ai_socktype = SOCK_DGRAM; /*dummy*/
+       hints.ai_flags = AI_CANONNAME;
+       res = NULL;
+       error = getaddrinfo(remotehost, "0", &hints, &res);
+       if (error)
+               return (NULL);
+
+       for (r = res; r; r = r->ai_next) {
+               h2[0] = '\0';
+               if (getnameinfo(r->ai_addr, r->ai_addrlen, h2, sizeof(h2),
+                   NULL, 0, niflags) != 0)
+                       continue;
+               if (strcmp(h1, h2) == 0) {
+                       freeaddrinfo(res);
+                       return (remotehost);
+               }
+       }
+
+       /*
+        * either the DNS adminstrator has made a configuration
+        * mistake, or someone has attempted to spoof us
+        */
+       syslog(LOG_NOTICE, "rcmd: address %s not listed for host %s",
+           h1, res->ai_canonname ? res->ai_canonname : remotehost);
+       freeaddrinfo(res);
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/net/recv.c b/lib/nbsd_libc/net/recv.c
new file mode 100644 (file)
index 0000000..0b1d5d7
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: recv.c,v 1.9 2003/10/22 15:40:19 drochner Exp $        */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)recv.c     8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: recv.c,v 1.9 2003/10/22 15:40:19 drochner Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <stddef.h>
+
+ssize_t
+recv(s, buf, len, flags)
+       int s, flags;
+       size_t len;
+       void *buf;
+{
+       return (recvfrom(s, buf, len, flags, NULL, NULL));
+}
diff --git a/lib/nbsd_libc/net/resolver.3 b/lib/nbsd_libc/net/resolver.3
new file mode 100644 (file)
index 0000000..e957004
--- /dev/null
@@ -0,0 +1,717 @@
+.\"    $NetBSD: resolver.3,v 1.23 2009/10/02 06:49:23 cegger Exp $
+.\" Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+.\"
+.\" 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 ISC DISCLAIMS ALL WARRANTIES
+.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+.\" MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+.\"
+.\" Copyright (c) 1985, 1995 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms are permitted provided
+.\" that: (1) source distributions retain this entire copyright notice and
+.\" comment, and (2) distributions including binaries display the following
+.\" acknowledgement:  ``This product includes software developed by the
+.\" University of California, Berkeley and its contributors'' in the
+.\" documentation or other materials provided with the distribution and in
+.\" all advertising materials mentioning features or use of this software.
+.\" 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
+.\" WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
+.\" MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+.\"
+.\"    @(#)resolver.3  6.5 (Berkeley) 6/23/90
+.\"    Id: resolver.man3,v 1.2 2009/01/21 00:12:34 each Exp
+.\"
+.Dd July 4, 2000
+.Dt RESOLVER 3 
+.Os
+.Sh NAME
+.Nm res_ninit ,
+.Nm res_ourserver_p ,
+.Nm fp_resstat ,
+.Nm res_hostalias ,
+.Nm res_pquery ,
+.Nm res_nquery ,
+.Nm res_nsearch ,
+.Nm res_nquerydomain ,
+.Nm res_nmkquery ,
+.Nm res_nsend ,
+.Nm res_nupdate ,
+.Nm res_nmkupdate ,
+.Nm res_nclose ,
+.Nm res_nsendsigned ,
+.Nm res_findzonecut ,
+.Nm res_getservers ,
+.Nm res_setservers ,
+.Nm res_ndestroy ,
+.Nm dn_comp ,
+.Nm dn_expand ,
+.\" .Nm hstrerror ,
+.Nm res_init ,
+.Nm res_isourserver ,
+.Nm fp_nquery ,
+.Nm p_query ,
+.Nm hostalias ,
+.Nm res_query ,
+.Nm res_search ,
+.Nm res_querydomain ,
+.Nm res_mkquery ,
+.Nm res_send ,
+.Nm res_update ,
+.Nm res_close ,
+.\" .Nm herror
+.Nd resolver routines
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In netinet/in.h
+.In arpa/nameser.h
+.In resolv.h
+.In res_update.h
+.Vt typedef struct __res_state *res_state ;
+.Pp
+.Ft int
+.Fn res_ninit "res_state statp"
+.Ft int
+.Fn res_ourserver_p "const res_state statp" "const struct sockaddr_in *addr"
+.Ft void
+.Fn fp_resstat "const res_state statp" "FILE *fp"
+.Ft "const char *"
+.Fn res_hostalias "const res_state statp" "const char *name" "char *buf" "size_t buflen"
+.Ft int
+.Fn res_pquery "const res_state statp" "const u_char *msg" "int msglen" "FILE *fp"
+.Ft int
+.Fn res_nquery "res_state statp" "const char *dname" "int class" "int type" "u_char *answer" "int anslen"
+.Ft int
+.Fn res_nsearch "res_state statp" "const char *dname" "int class" "int type" "u_char * answer" "int anslen"
+.Ft int
+.Fn res_nquerydomain "res_state statp" "const char *name" "const char *domain" "int class" "int type" "u_char *answer" "int anslen"
+.Ft int
+.Fo res_nmkquery
+.Fa "res_state statp"
+.Fa "int op"
+.Fa "const char *dname"
+.Fa "int class"
+.Fa "int type"
+.Fa "const u_char *data"
+.Fa "int datalen"
+.Fa "const u_char *newrr"
+.Fa "u_char *buf"
+.Fa "int buflen"
+.Fc
+.Ft int
+.Fn res_nsend "res_state statp" "const u_char *msg" "int msglen" "u_char *answer" "int anslen"
+.Ft int
+.Fn res_nupdate "res_state statp" "ns_updrec *rrecp_in"
+.Ft int
+.Fn res_nmkupdate "res_state statp" "ns_updrec *rrecp_in" "u_char *buf" "int buflen"
+.Ft void
+.Fn res_nclose "res_state statp"
+.Ft int
+.Fn res_nsendsigned "res_state statp" "const u_char *msg" "int msglen" "ns_tsig_key *key" "u_char *answer" "int anslen"
+.Ft int
+.Fn res_findzonecut "res_state statp" "const char *dname" "ns_class class" "int options" "char *zname" "size_t zsize" "struct in_addr *addrs" "int naddrs"
+.Ft int
+.Fn res_getservers "res_state statp" "union res_sockaddr_union *set" "int cnt"
+.Ft void
+.Fn res_setservers "res_state statp" "const union res_sockaddr_union *set" "int cnt"
+.Ft void
+.Fn res_ndestroy "res_state statp"
+.Ft int
+.Fn dn_comp "const char *exp_dn" "u_char *comp_dn" "int length" "u_char **dnptrs" "u_char **lastdnptr"
+.Ft int
+.Fn dn_expand "const u_char *msg" "const u_char *eomorig" "const u_char *comp_dn" "char *exp_dn" "int  length"
+.\" .Ft "const char *"
+.\" .Fn hstrerror "int err"
+.Ss DEPRECATED
+.In sys/types.h
+.In netinet/in.h
+.In arpa/nameser.h
+.In resolv.h
+.In res_update.h
+.Ft int
+.Fn res_init "void"
+.Ft int
+.Fn res_isourserver "const struct sockaddr_in *addr"
+.Ft int
+.Fn fp_nquery "const u_char *msg" "int msglen" "FILE *fp"
+.Ft void
+.Fn p_query "const u_char *msg" "FILE *fp"
+.Ft "const char *"
+.Fn hostalias "const char *name"
+.Ft int
+.Fn res_query "const char *dname" "int class" "int type" "u_char *answer" "int anslen"
+.Ft int
+.Fn res_search "const char *dname" "int class" "int type" "u_char *answer" "int anslen"
+.Ft int
+.Fn res_querydomain "const char *name" "const char *domain" "int class" "int type" "u_char *answer" "int anslen"
+.Ft int
+.Fo res_mkquery
+.Fa "int op"
+.Fa "const char *dname"
+.Fa "int class"
+.Fa "int type"
+.Fa "const char *data"
+.Fa "int datalen"
+.Fa "struct rrec *newrr"
+.Fa "u_char *buf"
+.Fa "int buflen"
+.Fc
+.Ft int
+.Fn res_send "const u_char *msg" "int msglen" "u_char *answer" "int anslen"
+.Ft int
+.Fn res_update "ns_updrec *rrecp_in"
+.Ft void
+.Fn res_close "void"
+.\" .Ft void
+.\" .Fn herror "const char *s"
+.Sh DESCRIPTION
+These routines are used for making, sending and interpreting
+query and reply messages with Internet domain name servers.
+.Pp
+State information is kept in
+.Fa statp
+and is used to control the behavior of these functions.
+.Fa statp
+should be set to all zeros prior to the first call to any of these functions.
+.Pp
+The functions
+.Fn res_init ,
+.Fn res_isourserver ,
+.Fn fp_nquery ,
+.Fn p_query ,
+.Fn hostalias ,
+.Fn res_query ,
+.Fn res_search ,
+.Fn res_querydomain ,
+.Fn res_mkquery ,
+.Fn res_send ,
+.Fn res_update ,
+.Fn res_close
+.\" and
+.\" .Fn herror
+are deprecated and are supplied for compatability with old source
+code.
+They use global configuration and state information that is
+kept in the structure
+.Ft _res
+rather than that referenced through
+.Ft statp .
+.Pp
+Most of the values in 
+.Ft statp
+and
+.Ft _res
+are initialized on the first call to
+.Fn res_ninit
+/
+.Fn res_init
+to reasonable defaults and can be ignored.
+Options
+stored in
+.Ft statp->options
+/
+.Ft _res.options
+are defined in
+.Pa resolv.h
+and are as follows.
+Options are stored as a simple bit mask containing the bitwise 
+.Dq OR
+of the options enabled.
+.Bl -tag -width "RES_USE_INET6"
+.It Dv RES_INIT
+True if the initial name server address and default domain name are
+initialized (i.e.,
+.Fn res_ninit
+/
+.Fn res_init
+has been called).
+.It Dv RES_DEBUG
+Print debugging messages.
+.It Dv RES_AAONLY
+Accept authoritative answers only.
+Should continue until it finds an authoritative answer or finds an error.
+Currently this is not implemented.
+.It Dv RES_USEVC
+Use TCP connections for queries instead of UDP datagrams.
+.It Dv RES_STAYOPEN
+Used with 
+.Dv RES_USEVC 
+to keep the TCP connection open between queries.
+This is useful only in programs that regularly do many queries.
+UDP should be the normal mode used.
+.It Dv RES_IGNTC
+Ignore truncation errors, i.e., don't retry with TCP.
+.It Dv RES_RECURSE
+Set the recursion-desired bit in queries.
+This is the default.
+(\c
+.Fn res_nsend
+/
+.Fn res_send
+does not do iterative queries and expects the name server
+to handle recursion.)
+.It Dv RES_DEFNAMES
+If set,
+.Fn res_nsearch
+/
+.Fn res_search
+will append the default domain name to single-component names
+(those that do not contain a dot).
+This option is enabled by default.
+.It Dv RES_DNSRCH
+If this option is set,
+.Fn res_nsearch
+/
+.Fn res_search
+will search for host names in the current domain and in parent domains; see
+.Xr hostname 7 .
+This is used by the standard host lookup routine
+.Xr gethostbyname 3 .
+This option is enabled by default.
+.It Dv RES_USE_INET6
+Enables support for IPv6-only applications.
+This causes IPv4 addresses to be returned as an IPv4 mapped address.
+For example, 10.1.1.1 will be returned as ::ffff:10.1.1.1.
+The option is meaningful with certain kernel configuration only.
+.It Dv RES_USE_EDNS0
+Enables support for OPT pseudo-RR for EDNS0 extension.
+With the option, resolver code will attach OPT pseudo-RR into DNS queries,
+to inform of our receive buffer size.
+The option will allow DNS servers to take advantage of non-default receive
+buffer size, and to send larger replies.
+DNS query packets with EDNS0 extension is not compatible with
+non-EDNS0 DNS servers.
+.It Dv RES_NOALIASES
+This option turns off the user level aliasing feature controlled by
+the 
+.Ev HOSTALIASES 
+environment variable.
+Network daemons should set this option.
+.It Dv RES_ROTATE
+This options causes the
+.Fn res_nsend
+/
+.Fn res_send
+to rotate the list of nameservers in
+.Fa statp->nsaddr_list
+/
+.Fa _res.nsaddr_list .
+.It Dv RES_KEEPTSIG
+This option causes
+.Fn res_nsendsigned
+to leave the message unchanged after TSIG verification; otherwise the TSIG
+record would be removed and the header updated.
+.It Dv RES_NOTLDQUERY
+This option causes
+.Fn res_nsearch
+to not attempt to resolve an unqualified name as if it were a top level
+domain (TLD).
+This option can cause problems if the site has "localhost" as a TLD rather
+than having localhost on one or more elements of the search list.
+This option has no effect if neither
+.Dv RES_DEFNAMES
+or
+.Dv RES_DNSRCH
+is set.
+.El
+.Pp
+The
+.Fn res_ninit
+/
+.Fn res_init
+routine
+reads the configuration file (if any; see
+.Xr resolv.conf 5 )
+to get the default domain name, search list and
+the Internet address of the local name server(s).
+If no server is configured, the host running the resolver is tried.
+The current domain name is defined by the hostname
+if not specified in the configuration file;
+it can be overridden by the environment variable 
+.Ev LOCALDOMAIN .
+This environment variable may contain several blank-separated
+tokens if you wish to override the
+.Fa search list
+on a per-process basis.  This is similar to the
+.Fa search
+command in the configuration file.
+Another environment variable 
+.Ev RES_OPTIONS 
+can be set to override certain internal resolver options which are otherwise
+set by changing fields in the
+.Ft statp
+/
+.Ft _res
+structure or are inherited from the configuration file's
+.Fa options
+command.
+The syntax of the 
+.Ev RES_OPTIONS 
+environment variable is explained in
+.Xr resolv.conf 5 .
+Initialization normally occurs on the first call
+to one of the other resolver routines.
+.Pp
+The memory referred to by
+.Ft statp
+must be set to all zeros prior to the first call to
+.Fn res_ninit .
+.Fn res_ndestroy
+should be call to free memory allocated by
+.Fn res_ninit 
+after last use.
+.Pp
+The
+.Fn res_nquery
+/
+.Fn res_query
+functions provides interfaces to the server query mechanism.
+They constructs a query, sends it to the local server,
+awaits a response, and makes preliminary checks on the reply.
+The query requests information of the specified
+.Fa type
+and
+.Fa class
+for the specified fully-qualified domain name
+.Fa dname .
+The reply message is left in the
+.Fa answer
+buffer with length
+.Fa anslen
+supplied by the caller.
+.Fn res_nquery
+/
+.Fn res_query
+return -1 on error or the length of the answer.
+.Pp
+The
+.Fn res_nsearch
+/
+.Fn res_search
+routines make a query and awaits a response like
+.Fn res_nquery
+/
+.Fn res_query ,
+but in addition, it implements the default and search rules
+controlled by the 
+.Dv RES_DEFNAMES 
+and 
+.Dv RES_DNSRCH 
+options.
+It returns the length of the first successful reply which is stored in
+.Ft answer
+or -1 on error.
+.Pp
+The remaining routines are lower-level routines used by
+.Fn res_nquery
+/
+.Fn res_query .
+The
+.Fn res_nmkquery
+/
+.Fn res_mkquery
+functions
+constructs a standard query message and places it in
+.Fa buf .
+It returns the size of the query, or \-1 if the query is
+larger than
+.Fa buflen .
+The query type
+.Fa op
+is usually 
+.Dv QUERY , 
+but can be any of the query types defined in
+.Pa <arpa/nameser.h> .
+The domain name for the query is given by
+.Fa dname .
+.Fa newrr
+is currently unused but is intended for making update messages.
+.Pp
+The
+.Fn res_nsend
+/
+.Fn res_send
+/
+.Fn res_nsendsigned
+routines
+sends a pre-formatted query and returns an answer.
+It will call
+.Fn res_ninit
+/
+.Fn res_init
+if 
+.Dv RES_INIT 
+is not set, send the query to the local name server, and
+handle timeouts and retries.  Additionally,
+.Fn res_nsendsigned
+will use TSIG signatures to add authentication to the query and verify the
+response.  In this case, only one nameserver will be contacted.
+The length of the reply message is returned, or \-1 if there were errors.
+.Pp
+.Fn res_nquery
+/
+.Fn res_query ,
+.Fn res_nsearch
+/
+.Fn res_search
+and
+.Fn res_nsend
+/
+.Fn res_send
+return a length that may be bigger than
+.Fa anslen .
+In that case the query should be retried with a bigger buffer.
+NOTE the answer to the second query may be larger still so supplying
+a buffer that bigger that the answer returned by the previous
+query is recommended.
+.Pp
+.Fa answer
+MUST be big enough to receive a maximum UDP response from the server or 
+parts of the answer will be silently discarded.
+The default maximum UDP response size is 512 bytes.
+.Pp
+The function
+.Fn res_ourserver_p
+returns true when 
+.Fa inp
+is one of the servers in
+.Fa statp->nsaddr_list
+/
+.Fa _res.nsaddr_list .
+.Pp
+The functions
+.Fn fp_nquery
+/
+.Fn p_query
+print out the query and any answer in
+.Fa msg
+on
+.Fa fp .
+.Fn p_query
+is equivalent to
+.Fn fp_nquery
+with
+.Fa msglen
+set to 512.
+.Pp
+The function
+.Fn fp_resstat
+prints out the active flag bits in
+.Fa statp->options
+preceeded by the text ";; res options:" on 
+.Fa file .
+.Pp
+The functions
+.Fn res_hostalias
+/
+.Fn hostalias
+lookup up name in the file referred to by the
+.Ev HOSTALIASES
+files return a fully qualified hostname if found or NULL if
+not found or an error occurred.
+.Fn res_hostalias
+uses
+.Fa buf
+to store the result in,
+.Fn hostalias
+uses a static buffer.
+.Pp
+The functions
+.Fn res_getservers
+and
+.Fn res_setservers
+are used to get and set the list of server to be queried.
+.Pp
+The functions
+.Fn res_nupdate
+/
+.Fn res_update
+take a list of ns_updrec
+.Fa rrecp_in .
+Identifies the containing zone for each record and groups the records
+according to containing zone maintaining in zone order then sends and update
+request to the servers for these zones.  The number of zones updated is
+returned or -1 on error.  Note that
+.Fn res_nupdate
+will perform TSIG authenticated dynamic update operations if the key is not
+NULL.
+.Pp
+The function
+.Fn res_findzonecut
+discovers the closest enclosing zone cut for a specified domain name,
+and finds the IP addresses of the zone's master servers.
+.Pp
+The functions 
+.Fn res_nmkupdate
+/
+.Fn res_mkupdate
+take a linked list of ns_updrec
+.Fa rrecp_in
+and construct a UPDATE message in
+.Fa buf .
+.Fn res_nmkupdate
+/
+.Fn res_mkupdate
+return the length of the constructed message on no error or one of the
+following error values.
+.Bl -inset -width "-5"
+.It -1
+An error occurred parsing 
+.Fa rrecp_in .
+.It -2
+The buffer 
+.Fa buf
+was too small.
+.It -3
+The first record was not a zone section or there was a section order problem.
+The section order is S_ZONE, S_PREREQ and S_UPDATE. 
+.It -4
+A number overflow occurred.
+.It -5
+Unknown operation or no records.
+.El
+.Pp
+The functions
+.Fn res_nclose
+/
+.Fn res_close
+close any open files referenced through
+.Fa statp
+/
+.Fa _res .
+.Pp
+The function
+.Fn res_ndestroy
+calls
+.Fn res_nclose
+then frees any memory allocated by
+.Fn res_ninit .
+.Pp
+The
+.Fn dn_comp
+function
+compresses the domain name
+.Fa exp_dn
+and stores it in
+.Fa comp_dn .
+The size of the compressed name is returned or \-1 if there were errors.
+The size of the array pointed to by
+.Fa comp_dn
+is given by
+.Fa length .
+The compression uses
+an array of pointers
+.Fa dnptrs
+to previously-compressed names in the current message.
+The first pointer points to
+the beginning of the message and the list ends with 
+.Dv NULL .
+The limit to the array is specified by
+.Fa lastdnptr .
+A side effect of
+.Fn dn_comp
+is to update the list of pointers for labels inserted into the message
+as the name is compressed.  If
+.Fa dnptr
+is 
+.Dv NULL , 
+names are not compressed.  If
+.Fa lastdnptr
+is 
+.Dv NULL , 
+the list of labels is not updated.
+.Pp
+The
+.Fn dn_expand
+entry expands the compressed domain name
+.Fa comp_dn
+to a full domain name.
+The compressed name is contained in a query or reply message;
+.Fa msg
+is a pointer to the beginning of the message.
+.Fa eomorig
+is a pointer to the first location after the message.
+The uncompressed name is placed in the buffer indicated by
+.Fa exp_dn
+which is of size
+.Fa length .
+The size of compressed name is returned or \-1 if there was an error.
+.Pp
+The variables
+.Ft statp->res_h_errno
+/
+.Ft _res.res_h_errno
+and external variable
+.Ft h_errno
+is set whenever an error occurs during resolver operation.  The following
+definitions are given in
+.Pa <netdb.h> :
+.Bd -literal
+#define NETDB_INTERNAL -1 
+/* see errno */
+#define NETDB_SUCCESS  0  
+/* no problem */
+#define HOST_NOT_FOUND 1  
+/* Authoritative Answer Host not found */
+#define TRY_AGAIN      2  
+/* Non-Authoritative not found, or SERVFAIL */
+#define NO_RECOVERY    3  
+/* Non-Recoverable: FORMERR, REFUSED, NOTIMP */
+#define NO_DATA        4  
+/* Valid name, no data for requested type */
+.Ed
+.\" .Pp
+.\" The
+.\" .Fn herror
+.\" function writes a message to the diagnostic output consisting of the string
+.\" parameter
+.\" .Fa s ,
+.\" the constant string ": ", and a message corresponding to the value of
+.\" .Ft h_errno .
+.\" .Pp
+.\" The
+.\" .Fn hstrerror
+.\" function returns a string which is the message text corresponding to the
+.\" value of the
+.\" .Fa err
+.\" parameter.
+.Sh FILES
+.Bl -tag -width "/etc/resolv.conf    "
+.It Pa
+/etc/resolv.conf
+The configuration file, see
+.Xr resolv.conf 5 .
+.El
+.Sh SEE ALSO
+.Xr gethostbyname 3 , 
+.Xr hostname 7 ,
+.Xr resolv.conf 5 ,
+.Xr named 8
+.Pp
+.%T RFC 974 ,
+.%T RFC 1032 ,
+.%T RFC 1033 ,
+.%T RFC 1034 ,
+.%T RFC 1035 ,
+.%T RFC 1535
+.Rs
+.%T "Name Server Operations Guide for BIND"
+.Re
+.Sh HISTORY
+The
+.Nm
+function appeared in
+.Bx 4.3 .
diff --git a/lib/nbsd_libc/net/rthdr.c b/lib/nbsd_libc/net/rthdr.c
new file mode 100644 (file)
index 0000000..f008c58
--- /dev/null
@@ -0,0 +1,462 @@
+/*     $NetBSD: rthdr.c,v 1.17 2009/02/05 23:22:39 lukem Exp $ */
+
+/*
+ * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
+ * 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.
+ * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: rthdr.c,v 1.17 2009/02/05 23:22:39 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <netinet/in.h>
+#include <netinet/ip6.h>
+
+#include <assert.h>
+#include <string.h>
+#include <stdio.h>
+
+#ifdef __weak_alias
+__weak_alias(inet6_rthdr_add,_inet6_rthdr_add)
+__weak_alias(inet6_rthdr_getaddr,_inet6_rthdr_getaddr)
+__weak_alias(inet6_rthdr_getflags,_inet6_rthdr_getflags)
+__weak_alias(inet6_rthdr_init,_inet6_rthdr_init)
+__weak_alias(inet6_rthdr_lasthop,_inet6_rthdr_lasthop)
+__weak_alias(inet6_rthdr_segments,_inet6_rthdr_segments)
+__weak_alias(inet6_rthdr_space,_inet6_rthdr_space)
+__weak_alias(inet6_rth_space, _inet6_rth_space)
+__weak_alias(inet6_rth_init, _inet6_rth_init)
+__weak_alias(inet6_rth_add, _inet6_rth_add)
+__weak_alias(inet6_rth_reverse, _inet6_rth_reverse)
+__weak_alias(inet6_rth_segments, _inet6_rth_segments)
+__weak_alias(inet6_rth_getaddr, _inet6_rth_getaddr)
+#endif
+
+/*
+ * RFC2292 API
+ */
+
+size_t
+inet6_rthdr_space(type, seg)
+       int type, seg;
+{
+       switch (type) {
+       case IPV6_RTHDR_TYPE_0:
+               if (seg < 1 || seg > 23)
+                       return (0);
+               return (CMSG_SPACE(sizeof(struct in6_addr) * seg +
+                   sizeof(struct ip6_rthdr0)));
+       default:
+               return (0);
+       }
+}
+
+struct cmsghdr *
+inet6_rthdr_init(bp, type)
+       void *bp;
+       int type;
+{
+       struct cmsghdr *ch;
+       struct ip6_rthdr *rthdr;
+
+       _DIAGASSERT(bp != NULL);
+
+       ch = (struct cmsghdr *)bp;
+       rthdr = (struct ip6_rthdr *)(void *)CMSG_DATA(ch);
+
+       ch->cmsg_level = IPPROTO_IPV6;
+       ch->cmsg_type = IPV6_RTHDR;
+
+       switch (type) {
+       case IPV6_RTHDR_TYPE_0:
+#ifdef COMPAT_RFC2292
+               ch->cmsg_len = CMSG_LEN(sizeof(struct ip6_rthdr0) -
+                   sizeof(struct in6_addr));
+#else
+               ch->cmsg_len = CMSG_LEN(sizeof(struct ip6_rthdr0));
+#endif
+               (void)memset(rthdr, 0, sizeof(struct ip6_rthdr0));
+               rthdr->ip6r_type = IPV6_RTHDR_TYPE_0;
+               return (ch);
+       default:
+               return (NULL);
+       }
+}
+
+int
+inet6_rthdr_add(cmsg, addr, flags)
+       struct cmsghdr *cmsg;
+       const struct in6_addr *addr;
+       u_int flags;
+{
+       struct ip6_rthdr *rthdr;
+
+       _DIAGASSERT(cmsg != NULL);
+       _DIAGASSERT(addr != NULL);
+
+       rthdr = (struct ip6_rthdr *)(void *)CMSG_DATA(cmsg);
+
+       switch (rthdr->ip6r_type) {
+       case IPV6_RTHDR_TYPE_0:
+       {
+               struct ip6_rthdr0 *rt0 = (struct ip6_rthdr0 *)(void *)rthdr;
+               if (flags != IPV6_RTHDR_LOOSE && flags != IPV6_RTHDR_STRICT)
+                       return (-1);
+               if (rt0->ip6r0_segleft == 23)
+                       return (-1);
+               if (flags != IPV6_RTHDR_LOOSE)
+                       return (-1);
+               rt0->ip6r0_segleft++;
+               (void)memcpy(((caddr_t)(void *)rt0) +
+                   ((rt0->ip6r0_len + 1) << 3), addr, sizeof(struct in6_addr));
+               rt0->ip6r0_len += sizeof(struct in6_addr) >> 3;
+               cmsg->cmsg_len = CMSG_LEN((rt0->ip6r0_len + 1) << 3);
+               break;
+       }
+       default:
+               return (-1);
+       }
+
+       return (0);
+}
+
+int
+inet6_rthdr_lasthop(cmsg, flags)
+       struct cmsghdr *cmsg;
+       unsigned int flags;
+{
+       struct ip6_rthdr *rthdr;
+
+       _DIAGASSERT(cmsg != NULL);
+
+       rthdr = (struct ip6_rthdr *)(void *)CMSG_DATA(cmsg);
+
+       switch (rthdr->ip6r_type) {
+       case IPV6_RTHDR_TYPE_0:
+       {
+               struct ip6_rthdr0 *rt0 = (struct ip6_rthdr0 *)(void *)rthdr;
+               if (rt0->ip6r0_segleft > 23)
+                       return (-1);
+               if (flags != IPV6_RTHDR_LOOSE)
+                       return (-1);
+               break;
+       }
+       default:
+               return (-1);
+       }
+
+       return (0);
+}
+
+#if 0
+int
+inet6_rthdr_reverse(in, out)
+       const struct cmsghdr *in;
+       struct cmsghdr *out;
+{
+
+       return (-1);
+}
+#endif
+
+int
+inet6_rthdr_segments(cmsg)
+       const struct cmsghdr *cmsg;
+{
+       const struct ip6_rthdr *rthdr;
+
+       _DIAGASSERT(cmsg != NULL);
+
+       rthdr = __UNCONST(CCMSG_DATA(cmsg));
+
+       switch (rthdr->ip6r_type) {
+       case IPV6_RTHDR_TYPE_0:
+       {
+               const struct ip6_rthdr0 *rt0 =
+                   (const struct ip6_rthdr0 *)(const void *)rthdr;
+
+               if (rt0->ip6r0_len % 2 || 46 < rt0->ip6r0_len)
+                       return (-1);
+
+               return (rt0->ip6r0_len * 8) / sizeof(struct in6_addr);
+       }
+
+       default:
+               return (-1);
+       }
+}
+
+struct in6_addr *
+inet6_rthdr_getaddr(cmsg, idx)
+       struct cmsghdr *cmsg;
+       int idx;
+{
+       struct ip6_rthdr *rthdr;
+
+       _DIAGASSERT(cmsg != NULL);
+
+       rthdr = (struct ip6_rthdr *)(void *)CMSG_DATA(cmsg);
+
+       switch (rthdr->ip6r_type) {
+       case IPV6_RTHDR_TYPE_0:
+       {
+               struct ip6_rthdr0 *rt0 = (struct ip6_rthdr0 *)(void *)rthdr;
+               int naddr;
+
+               if (rt0->ip6r0_len % 2 || 46 < rt0->ip6r0_len)
+                       return NULL;
+               naddr = (rt0->ip6r0_len * 8) / sizeof(struct in6_addr);
+               if (idx <= 0 || naddr < idx)
+                       return NULL;
+#ifdef COMPAT_RFC2292
+               return ((struct in6_addr *)(void *)(rt0 + 1)) + idx - 1;
+#else
+               return ((struct in6_addr *)(void *)(rt0 + 1)) + idx;
+#endif
+       }
+
+       default:
+               return NULL;
+       }
+}
+
+int
+inet6_rthdr_getflags(cmsg, idx)
+       const struct cmsghdr *cmsg;
+       int idx;
+{
+       const struct ip6_rthdr *rthdr;
+
+       _DIAGASSERT(cmsg != NULL);
+
+       rthdr = __UNCONST(CCMSG_DATA(cmsg));
+
+       switch (rthdr->ip6r_type) {
+       case IPV6_RTHDR_TYPE_0:
+       {
+               const struct ip6_rthdr0 *rt0 = (const struct ip6_rthdr0 *)
+               (const void *)rthdr;
+               int naddr;
+
+               if (rt0->ip6r0_len % 2 || 46 < rt0->ip6r0_len)
+                       return (-1);
+               naddr = (rt0->ip6r0_len * 8) / sizeof(struct in6_addr);
+               if (idx < 0 || naddr < idx)
+                       return (-1);
+               return IPV6_RTHDR_LOOSE;
+       }
+
+       default:
+               return (-1);
+       }
+}
+
+/*
+ * RFC3542 (2292bis) API
+ */
+
+socklen_t
+inet6_rth_space(int type, int segments)
+{
+       switch (type) {
+       case IPV6_RTHDR_TYPE_0:
+               return (((segments * 2) + 1) << 3);
+       default:
+               return (0);     /* type not suppported */
+       }
+}
+
+void *
+inet6_rth_init(void *bp, socklen_t bp_len, int type, int segments)
+{
+       struct ip6_rthdr *rth;
+       struct ip6_rthdr0 *rth0;
+
+       _DIAGASSERT(bp != NULL);
+
+       rth = (struct ip6_rthdr *)bp;
+
+       switch (type) {
+       case IPV6_RTHDR_TYPE_0:
+               /* length validation */
+               if (bp_len < inet6_rth_space(IPV6_RTHDR_TYPE_0, segments))
+                       return (NULL);
+
+               memset(bp, 0, bp_len);
+               rth0 = (struct ip6_rthdr0 *)(void *)rth;
+               rth0->ip6r0_len = segments * 2;
+               rth0->ip6r0_type = IPV6_RTHDR_TYPE_0;
+               rth0->ip6r0_segleft = 0;
+               rth0->ip6r0_reserved = 0;
+               break;
+       default:
+               return (NULL);  /* type not supported */
+       }
+
+       return (bp);
+}
+
+int
+inet6_rth_add(void *bp, const struct in6_addr *addr)
+{
+       struct ip6_rthdr *rth;
+       struct ip6_rthdr0 *rth0;
+       struct in6_addr *nextaddr;
+
+       _DIAGASSERT(bp != NULL);
+
+       rth = (struct ip6_rthdr *)bp;
+
+       switch (rth->ip6r_type) {
+       case IPV6_RTHDR_TYPE_0:
+               rth0 = (struct ip6_rthdr0 *)(void *)rth;
+               nextaddr = (struct in6_addr *)(void *)(rth0 + 1)
+                   + rth0->ip6r0_segleft;
+               *nextaddr = *addr;
+               rth0->ip6r0_segleft++;
+               break;
+       default:
+               return (-1);    /* type not supported */
+       }
+
+       return (0);
+}
+
+int
+inet6_rth_reverse(const void *in, void *out)
+{
+       const struct ip6_rthdr *rth_in;
+       const struct ip6_rthdr0 *rth0_in;
+       struct ip6_rthdr0 *rth0_out;
+       int i, segments;
+
+       _DIAGASSERT(in != NULL);
+       _DIAGASSERT(out != NULL);
+
+       rth_in = (const struct ip6_rthdr *)in;
+
+       switch (rth_in->ip6r_type) {
+       case IPV6_RTHDR_TYPE_0:
+               rth0_in = (const struct ip6_rthdr0 *)in;
+               rth0_out = (struct ip6_rthdr0 *)out;
+
+               /* parameter validation XXX too paranoid? */
+               if (rth0_in->ip6r0_len % 2)
+                       return (-1);
+               segments = rth0_in->ip6r0_len / 2;
+
+               /* we can't use memcpy here, since in and out may overlap */
+               memmove((void *)rth0_out, (const void *)rth0_in,
+                       (unsigned int)(((rth0_in->ip6r0_len) + 1) << 3));
+               rth0_out->ip6r0_segleft = segments;
+
+               /* reverse the addresses */
+               for (i = 0; i < segments / 2; i++) {
+                       struct in6_addr addr_tmp, *addr1, *addr2;
+
+                       addr1 = (struct in6_addr *)(void *)(rth0_out + 1) + i;
+                       addr2 = (struct in6_addr *)(void *)(rth0_out + 1) +
+                               (segments - i - 1);
+                       addr_tmp = *addr1;
+                       *addr1 = *addr2;
+                       *addr2 = addr_tmp;
+               }
+               
+               break;
+       default:
+               return (-1);    /* type not supported */
+       }
+
+       return (0);
+}
+
+int
+inet6_rth_segments(const void *bp)
+{
+       const struct ip6_rthdr *rh;
+       const struct ip6_rthdr0 *rh0;
+       unsigned int addrs;
+
+       _DIAGASSERT(bp != NULL);
+
+       rh = (const struct ip6_rthdr *)bp;
+
+       switch (rh->ip6r_type) {
+       case IPV6_RTHDR_TYPE_0:
+               rh0 = (const struct ip6_rthdr0 *)bp;
+
+               /*
+                * Validation for a type-0 routing header.
+                * Is this too strict?
+                */
+               if ((rh0->ip6r0_len % 2) != 0 ||
+                   (addrs = (rh0->ip6r0_len / 2)) < rh0->ip6r0_segleft)
+                       return (-1);
+
+               return (addrs);
+       default:
+               return (-1);    /* unknown type */
+       }
+}
+
+struct in6_addr *
+inet6_rth_getaddr(const void *bp, int idx)
+{
+       const struct ip6_rthdr *rh;
+       const struct ip6_rthdr0 *rh0;
+       unsigned int addrs;
+
+       _DIAGASSERT(bp != NULL);
+
+       rh = (const struct ip6_rthdr *)bp;
+
+       switch (rh->ip6r_type) {
+       case IPV6_RTHDR_TYPE_0:
+                rh0 = (const struct ip6_rthdr0 *)bp;
+                
+               /*
+                * Validation for a type-0 routing header.
+                * Is this too strict?
+                */
+               if ((rh0->ip6r0_len % 2) != 0 ||
+                   (addrs = (rh0->ip6r0_len / 2)) < rh0->ip6r0_segleft)
+                       return (NULL);
+
+               if (idx < 0 || addrs <= (unsigned int)idx)
+                       return (NULL);
+
+               return (((struct in6_addr *)(void *)__UNCONST(rh0 + 1)) + idx);
+       default:
+               return (NULL);  /* unknown type */
+       }
+}
diff --git a/lib/nbsd_libc/net/send.c b/lib/nbsd_libc/net/send.c
new file mode 100644 (file)
index 0000000..d7b3514
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: send.c,v 1.9 2003/08/07 16:43:15 agc Exp $     */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)send.c     8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: send.c,v 1.9 2003/08/07 16:43:15 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <stddef.h>
+
+#ifdef __weak_alias
+__weak_alias(send, _send)
+#endif
+
+ssize_t
+send(s, msg, len, flags)
+       int s, flags;
+       size_t len;
+       const void *msg;
+{
+       return (sendto(s, msg, len, flags, NULL, 0));
+}
diff --git a/lib/nbsd_libc/net/servent.h b/lib/nbsd_libc/net/servent.h
new file mode 100644 (file)
index 0000000..c7dfcc2
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: servent.h,v 1.4 2010/04/25 00:54:46 joerg Exp $        */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <stdio.h>
+
+struct servent_data {
+       FILE *plainfile;
+       struct cdbr *cdb;
+       struct servent serv;
+       char **aliases;
+       size_t maxaliases;
+       int flags;
+#define        _SV_STAYOPEN    1
+#define        _SV_CDB         2
+#define        _SV_PLAINFILE   4
+#define        _SV_FIRST       8
+       uint32_t cdb_index;
+       uint8_t *cdb_buf;
+       size_t cdb_buf_len;
+       char *line;
+       void *dummy;
+};
+
+struct servent *getservent_r(struct servent *, struct servent_data *);
+struct servent *getservbyname_r(const char *, const char *,
+    struct servent *, struct servent_data *);
+struct servent *getservbyport_r(int, const char *,
+    struct servent *, struct servent_data *);
+void setservent_r(int, struct servent_data *);
+void endservent_r(struct servent_data *);
+
+int _servent_open(struct servent_data *);
+void _servent_close(struct servent_data *);
+int _servent_getline(struct servent_data *);
+struct servent *_servent_parseline(struct servent_data *, struct servent *);
+struct servent *_servent_parsedb(struct servent_data *, struct servent *,
+    const uint8_t *, size_t);
diff --git a/lib/nbsd_libc/net/sethostent.c b/lib/nbsd_libc/net/sethostent.c
new file mode 100644 (file)
index 0000000..e967095
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: sethostent.c,v 1.16 2007/01/27 22:27:35 christos Exp $ */
+
+/*
+ * Copyright (c) 1985, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)sethostent.c       8.1 (Berkeley) 6/4/93";
+static char rcsid[] = "Id: sethostent.c,v 8.5 1996/09/28 06:51:07 vixie Exp ";
+#else
+__RCSID("$NetBSD: sethostent.c,v 1.16 2007/01/27 22:27:35 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+#include <netdb.h>
+#include <resolv.h>
+
+#ifdef __weak_alias
+__weak_alias(sethostent,_sethostent)
+__weak_alias(endhostent,_endhostent)
+#endif
+
+void   _endhtent __P((void));
+#ifndef _REENTRANT
+void   res_close __P((void));
+#endif
+void   _sethtent __P((int));
+
+void
+/*ARGSUSED*/
+sethostent(stayopen)
+       int stayopen;
+{
+#ifndef _REENTRANT
+       if ((_res.options & RES_INIT) == 0 && res_init() == -1)
+               return;
+       if (stayopen)
+               _res.options |= RES_STAYOPEN | RES_USEVC;
+#endif
+       _sethtent(stayopen);
+}
+
+void
+endhostent()
+{
+#ifndef _REENTRANT
+       _res.options &= ~(RES_STAYOPEN | RES_USEVC);
+       res_close();
+#endif
+       _endhtent();
+}
diff --git a/lib/nbsd_libc/net/sockatmark.3 b/lib/nbsd_libc/net/sockatmark.3
new file mode 100644 (file)
index 0000000..58183f4
--- /dev/null
@@ -0,0 +1,103 @@
+.\"    $NetBSD: sockatmark.3,v 1.9 2008/04/30 13:10:50 martin Exp $
+.\"
+.\" Copyright (c) 2001 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 15, 2003
+.Dt SOCKATMARK 3
+.Os
+.Sh NAME
+.Nm sockatmark
+.Nd determine whether a socket is at the out-of-band mark
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft int
+.Fn sockatmark "int s"
+.Sh DESCRIPTION
+The
+.Nm sockatmark
+function determines whether the socket referenced by the file descriptor
+.Fa s
+is at the out-of-band mark.
+.Sh RETURN VALUES
+If successful, the
+.Nm sockatmark
+function returns 1 to indicate that the socket is at an out-of-band mark;
+0 is returned if there is no out-of-band mark or the mark is preceded
+by in-band data.
+Otherwise, -1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Nm sockatmark
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The argument
+.Fa s
+is not a valid file descriptor.
+.It Bq Er ENOTTY
+The file descriptor
+.Fa s
+does not refer to a socket.
+.El
+.Sh SEE ALSO
+.Xr ioctl 2 ,
+.Xr recv 2 ,
+.Xr socket 2
+.Rs
+.%T "An Introductory 4.4BSD Interprocess Communication Tutorial"
+.%A Stuart Sechrest
+.Re
+.Pq see Pa /usr/share/doc/psd/20.ipctut
+.Rs
+.%T "Advanced 4.4BSD IPC Tutorial"
+.%A Samuel J. Leffler
+.%A Robert S. Fabry
+.%A William N. Joy
+.%A Phil Lapsley
+.%A Steve Miller
+.%A Chris Torek
+.Re
+.Pq see Pa /usr/share/doc/psd/21.ipc
+.Sh STANDARDS
+The
+.Nm sockatmark
+function conforms to
+.St -p1003.1-2001 .
+.Sh HISTORY
+The
+.Nm sockatmark
+function appeared in
+.St -p1003.1g-2000
+as a replacement for the
+.Dv SIOCATMARK
+.Xr ioctl 2
+interface.
diff --git a/lib/nbsd_libc/net/sockatmark.c b/lib/nbsd_libc/net/sockatmark.c
new file mode 100644 (file)
index 0000000..887c2ce
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: sockatmark.c,v 1.2 2008/04/28 20:23:00 martin Exp $    */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sockatmark.c,v 1.2 2008/04/28 20:23:00 martin Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+
+#include <assert.h>
+
+int
+sockatmark(s)
+       int s;
+{
+       int val;
+
+       _DIAGASSERT(s != -1);
+
+       if (ioctl(s, SIOCATMARK, &val) == -1)
+               return (-1);
+
+       return (val);
+}
diff --git a/lib/nbsd_libc/net/vars6.c b/lib/nbsd_libc/net/vars6.c
new file mode 100644 (file)
index 0000000..09abc4c
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: vars6.c,v 1.7 2005/08/07 16:00:01 christos Exp $       */
+
+/*
+ * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
+ * 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.
+ * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: vars6.c,v 1.7 2005/08/07 16:00:01 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <netinet/in.h>
+
+#ifdef __weak_alias
+__weak_alias(in6addr_any, _in6addr_any)
+__weak_alias(in6addr_loopback, _in6addr_loopback)
+__weak_alias(in6addr_nodelocal_allnodes, _in6addr_nodelocal_allnodes)
+__weak_alias(in6addr_linklocal_allnodes, _in6addr_linklocal_allnodes)
+__weak_alias(in6addr_linklocal_allrouters, _in6addr_linklocal_allrouters)
+#endif
+
+/*
+ * Definitions of some constant IPv6 addresses.
+ */
+const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
+const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
+const struct in6_addr in6addr_nodelocal_allnodes = IN6ADDR_NODELOCAL_ALLNODES_INIT;
+const struct in6_addr in6addr_linklocal_allnodes = IN6ADDR_LINKLOCAL_ALLNODES_INIT;
+const struct in6_addr in6addr_linklocal_allrouters = IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
+
diff --git a/lib/nbsd_libc/nls/C.msg b/lib/nbsd_libc/nls/C.msg
new file mode 100644 (file)
index 0000000..cdc7c68
--- /dev/null
@@ -0,0 +1,258 @@
+$set 1
+$ EPERM
+1 Operation not permitted
+$ ENOENT
+2 No such file or directory
+$ ESRCH
+3 No such process
+$ EINTR
+4 Interrupted system call
+$ EIO
+5 Input/output error
+$ ENXIO
+6 Device not configured
+$ E2BIG
+7 Argument list too long
+$ ENOEXEC
+8 Exec format error
+$ EBADF
+9 Bad file descriptor
+$ ECHILD
+10 No child processes
+$ EDEADLK
+11 Resource deadlock avoided
+$ ENOMEM
+12 Cannot allocate memory
+$ EACCES
+13 Permission denied
+$ EFAULT
+14 Bad address
+$ ENOTBLK
+15 Block device required
+$ EBUSY
+16 Device busy
+$ EEXIST
+17 File exists
+$ EXDEV
+18 Cross-device link
+$ ENODEV
+19 Operation not supported by device
+$ ENOTDIR
+20 Not a directory
+$ EISDIR
+21 Is a directory
+$ EINVAL
+22 Invalid argument
+$ ENFILE
+23 Too many open files in system
+$ EMFILE
+24 Too many open files
+$ ENOTTY
+25 Inappropriate ioctl for device
+$ ETXTBSY
+26 Text file busy
+$ EFBIG
+27 File too large
+$ ENOSPC
+28 No space left on device
+$ ESPIPE
+29 Illegal seek
+$ EROFS
+30 Read-only file system
+$ EMLINK
+31 Too many links
+$ EPIPE
+32 Broken pipe
+$ EDOM
+33 Numerical argument out of domain
+$ ERANGE
+34 Result too large or too small
+$ EAGAIN, EWOULDBLOCK
+35 Resource temporarily unavailable
+$ EINPROGRESS
+36 Operation now in progress
+$ EALREADY
+37 Operation already in progress
+$ ENOTSOCK
+38 Socket operation on non-socket
+$ EDESTADDRREQ
+39 Destination address required
+$ EMSGSIZE
+40 Message too long
+$ EPROTOTYPE
+41 Protocol wrong type for socket
+$ ENOPROTOOPT
+42 Protocol option not available
+$ EPROTONOSUPPORT
+43 Protocol not supported
+$ ESOCKTNOSUPPORT
+44 Socket type not supported
+$ EOPNOTSUPP
+45 Operation not supported
+$ EPFNOSUPPORT
+46 Protocol family not supported
+$ EAFNOSUPPORT
+47 Address family not supported by protocol family
+$ EADDRINUSE
+48 Address already in use
+$ EADDRNOTAVAIL
+49 Can't assign requested address
+$ ENETDOWN
+50 Network is down
+$ ENETUNREACH
+51 Network is unreachable
+$ ENETRESET
+52 Network dropped connection on reset
+$ ECONNABORTED
+53 Software caused connection abort
+$ ECONNRESET
+54 Connection reset by peer
+$ ENOBUFS
+55 No buffer space available
+$ EISCONN
+56 Socket is already connected
+$ ENOTCONN
+57 Socket is not connected
+$ ESHUTDOWN
+58 Can't send after socket shutdown
+$ ETOOMANYREFS
+59 Too many references: can't splice
+$ ETIMEDOUT
+60 Connection timed out
+$ ECONNREFUSED
+61 Connection refused
+$ ELOOP
+62 Too many levels of symbolic links
+$ ENAMETOOLONG
+63 File name too long
+$ EHOSTDOWN
+64 Host is down
+$ EHOSTUNREACH
+65 No route to host
+$ ENOTEMPTY
+66 Directory not empty
+$ EPROCLIM
+67 Too many processes
+$ EUSERS
+68 Too many users
+$ EDQUOT
+69 Disc quota exceeded
+$ ESTALE
+70 Stale NFS file handle
+$ EREMOTE
+71 Too many levels of remote in path
+$ EBADRPC
+72 RPC struct is bad
+$ ERPCMISMATCH
+73 RPC version wrong
+$ EPROGUNAVAIL
+74 RPC prog. not avail
+$ EPROGMISMATCH
+75 Program version wrong
+$ EPROCUNAVAIL
+76 Bad procedure for program
+$ ENOLCK
+77 No locks available
+$ ENOSYS
+78 Function not implemented
+$ EFTYPE
+79 Inappropriate file type or format
+$ EAUTH
+80 Authentication error
+$ ENEEDAUTH
+81 Need authenticator
+$ EIDRM
+82 Identifier removed
+$ ENOMSG
+83 No message of desired type
+$ EOVERFLOW
+84 Value too large to be stored in data type
+$ EILSEQ
+85 Illegal byte sequence
+$ ENOTSUP
+86 Not supported
+$ ECANCELED
+87 Operation Canceled
+$ EBADMSG
+88 Bad or Corrupt message
+$ ENODATA
+89 No message available
+$ ENOSR
+90 No STREAM resources
+$ ENOSTR
+91 Not a STREAM
+$ ETIME
+92 STREAM ioctl timeout
+$ ENOATTR
+93 Attribute not found
+$ EMULTIHOP
+94 Multihop attempted
+$ ENOLINK
+95 Link has been severed
+$ EPROTO
+96 Protocol error
+$set 2
+$ SIGHUP
+1 Hangup
+$ SIGINT
+2 Interrupt
+$ SIGQUIT
+3 Quit
+$ SIGILL
+4 Illegal instruction
+$ SIGTRAP
+5 Trace/BPT trap
+$ SIGABRT
+6 Abort trap
+$ SIGEMT
+7 EMT trap
+$ SIGFPE
+8 Floating point exception
+$ SIGKILL
+9 Killed
+$ SIGBUS
+10 Bus error
+$ SIGSEGV
+11 Segmentation fault
+$ SIGSYS
+12 Bad system call
+$ SIGPIPE
+13 Broken pipe
+$ SIGALRM
+14 Alarm clock
+$ SIGTERM
+15 Terminated
+$ SIGURG
+16 Urgent I/O condition
+$ SIGSTOP
+17 Stopped (signal)
+$ SIGTSTP
+18 Stopped
+$ SIGCONT
+19 Continued
+$ SIGCHLD
+20 Child exited
+$ SIGTTIN
+21 Stopped (tty input)
+$ SIGTTOU
+22 Stopped (tty output)
+$ SIGIO
+23 I/O possible
+$ SIGXCPU
+24 Cputime limit exceeded
+$ SIGXFSZ
+25 Filesize limit exceeded
+$ SIGVTALRM
+26 Virtual timer expired
+$ SIGPROF
+27 Profiling timer expired
+$ SIGWINCH
+28 Window size changes
+$ SIGINFO
+29 Information request
+$ SIGUSR1
+30 User defined signal 1
+$ SIGUSR2
+31 User defined signal 2
+$ SIGPWR
+32 Power fail/restart
diff --git a/lib/nbsd_libc/nls/Makefile.inc b/lib/nbsd_libc/nls/Makefile.inc
new file mode 100644 (file)
index 0000000..2266b5d
--- /dev/null
@@ -0,0 +1,16 @@
+#      $NetBSD: Makefile.inc,v 1.10 2009/01/11 02:46:29 christos Exp $
+
+.PATH: ${.CURDIR}/nls
+
+SRCS+= catclose.c catgets.c catopen.c 
+MAN+=  catclose.3 catgets.3 catopen.3
+
+# indirect reference stubs, to be removed soon.
+SRCS+= _catclose.c _catgets.c _catopen.c
+
+.if ${CITRUS} == "yes"
+CPPFLAGS.catopen.c+=   -DHAVE_CITRUS -I${LIBCDIR}/citrus
+.else
+CPPFLAGS.catopen.c+=   -UHAVE_CITRUS -I${LIBCDIR}/locale
+.endif
+
diff --git a/lib/nbsd_libc/nls/Pig.msg b/lib/nbsd_libc/nls/Pig.msg
new file mode 100644 (file)
index 0000000..edff3cd
--- /dev/null
@@ -0,0 +1,236 @@
+$set 1
+$ EPERM
+1 Operationway otnay ermittedpay
+$ ENOENT
+2 Onay uchsay ilefay orway irectoryday
+$ ESRCH
+3 Onay uchsay ocesspray
+$ EINTR
+4 Interruptedway ystemsay allcay
+$ EIO
+5 Inputway/outputway errorway
+$ ENXIO
+6 Eviceday otnay onfiguredcay
+$ E2BIG
+7 Argumentway istlay ootay onglay
+$ ENOEXEC
+8 Execway ormatfay errorway
+$ EBADF
+9 Adbay ilefay escriptorday
+$ ECHILD
+10 Onay ildchay ocessespray
+$ EDEADLK
+11 Esourceray eadlockday avoidedway
+$ ENOMEM
+12 Annotcay allocateway emorymay
+$ EACCES
+13 Ermissionpay eniedday
+$ EFAULT
+14 Adbay addressway
+$ ENOTBLK
+15 Ockblay eviceday equiredray
+$ EBUSY
+16 Eviceday usybay
+$ EEXIST
+17 Ilefay existsway
+$ EXDEV
+18 Osscray-eviceday inklay
+$ ENODEV
+19 Operationway otnay upportedsay ybay eviceday
+$ ENOTDIR
+20 Otnay away irectoryday
+$ EISDIR
+21 Isway away irectoryday
+$ EINVAL
+22 Invalidway argumentway
+$ ENFILE
+23 Ootay anymay openway ilesfay inway ystemsay
+$ EMFILE
+24 Ootay anymay openway ilesfay
+$ ENOTTY
+25 Inappropriateway ioctlway orfay eviceday
+$ ETXTBSY
+26 Exttay ilefay usybay
+$ EFBIG
+27 Ilefay ootay argelay
+$ ENOSPC
+28 Onay acespay eftlay onway eviceday
+$ ESPIPE
+29 Illegalway eeksay
+$ EROFS
+30 Eadray-onlyway ilefay ystemsay
+$ EMLINK
+31 Ootay anymay inkslay
+$ EPIPE
+32 Okenbray ipepay
+$ EDOM
+33 Umericalnay argumentway outway ofway omainday
+$ ERANGE
+34 Esultray ootay argelay
+$ EAGAIN, EWOULDBLOCK
+35 Esourceray emporarilytay unavailableway
+$ EINPROGRESS
+36 Operationway ownay inway ogresspray
+$ EALREADY
+37 Operationway alreadyway inway ogresspray
+$ ENOTSOCK
+38 Ocketsay operationway onway onnay-ocketsay
+$ EDESTADDRREQ
+39 Estinationday addressway equiredray
+$ EMSGSIZE
+40 Essagemay ootay onglay
+$ EPROTOTYPE
+41 Otocolpray ongwray ypetay orfay ocketsay
+$ ENOPROTOOPT
+42 Otocolpray otnay availableway
+$ EPROTONOSUPPORT
+43 Otocolpray otnay upportedsay
+$ ESOCKTNOSUPPORT
+44 Ocketsay ypetay otnay upportedsay
+$ EOPNOTSUPP
+45 Operationway otnay upportedsay
+$ EPFNOSUPPORT
+46 Otocolpray amilyfay otnay upportedsay
+$ EAFNOSUPPORT
+47 Addressway amilyfay otnay upportedsay ybay otocolpray amilyfay
+$ EADDRINUSE
+48 Addressway alreadyway inway useway
+$ EADDRNOTAVAIL
+49 Ancay'tay assignway equestedray addressway
+$ ENETDOWN
+50 Etworknay isway ownday
+$ ENETUNREACH
+51 Etworknay isway unreachableway
+$ ENETRESET
+52 Etworknay oppeddray onnectioncay onway esetray
+$ ECONNABORTED
+53 Oftwaresay ausedcay onnectioncay abortway
+$ ECONNRESET
+54 Onnectioncay esetray ybay eerpay
+$ ENOBUFS
+55 Onay ufferbay acespay availableway
+$ EISCONN
+56 Ocketsay isway alreadyway onnectedcay
+$ ENOTCONN
+57 Ocketsay isway otnay onnectedcay
+$ ESHUTDOWN
+58 Ancay'tay endsay afterway ocketsay utdownshay
+$ ETOOMANYREFS
+59 Ootay anymay eferencesray: ancay'tay icesplay
+$ ETIMEDOUT
+60 Onnectioncay imedtay outway
+$ ECONNREFUSED
+61 Onnectioncay efusedray
+$ ELOOP
+62 Ootay anymay evelslay ofway ymbolicsay inkslay
+$ ENAMETOOLONG
+63 Ilefay amenay ootay onglay
+$ EHOSTDOWN
+64 Osthay isway ownday
+$ EHOSTUNREACH
+65 Onay outeray otay osthay
+$ ENOTEMPTY
+66 Irectoryday otnay emptyway
+$ EPROCLIM
+67 Ootay anymay ocessespray
+$ EUSERS
+68 Ootay anymay usersway
+$ EDQUOT
+69 Iscday otaquay exceededway
+$ ESTALE
+70 Alestay NFSay ilefay andlehay
+$ EREMOTE
+71 Ootay anymay evelslay ofway emoteray inway athpay
+$ EBADRPC
+72 RPCay uctstray isway adbay
+$ ERPCMISMATCH
+73 RPCay ersionvay ongwray
+$ EPROGUNAVAIL
+74 RPCay ogpray. otnay availway
+$ EPROGMISMATCH
+75 Ogrampray ersionvay ongwray
+$ EPROCUNAVAIL
+76 Adbay ocedurepray orfay ogrampray
+$ ENOLCK
+77 Onay ockslay availableway
+$ ENOSYS
+78 Unctionfay otnay implementedway
+$ EFTYPE
+79 Inappropriateway ilefay ypetay orway ormatfay
+$ EAUTH
+80 Authenticationway errorway
+$ ENEEDAUTH
+81 Eednay authenticatorway
+$ EIDRM
+82 Identifierway emovedray
+$ ENOMSG
+83 Onay essagemay ofway esiredday ypetay
+$ EOVERFLOW
+84 Aluevay ootay argelay otay ebay oredstay inway ataday ypetay
+$ EILSEQ
+85 Illegalway ytebay equencesay
+$set 2
+$ SIGHUP
+1 Anguphay
+$ SIGINT
+2 Interruptway
+$ SIGQUIT
+3 Itquay
+$ SIGILL
+4 Illegalway instructionway
+$ SIGTRAP
+5 aceTray/BPTay aptray
+$ SIGABRT
+6 Abortway aptray
+$ SIGEMT
+7 EMTway aptray
+$ SIGFPE
+8 Oatingflay ointpay exceptionway
+$ SIGKILL
+9 Illedkay
+$ SIGBUS
+10 Usbay errorway
+$ SIGSEGV
+11 Egmentationsay aultfay
+$ SIGSYS
+12 Adbay ystemsay allcay
+$ SIGPIPE
+13 Okenbray ipepay
+$ SIGALRM
+14 Alarmway ockclay
+$ SIGTERM
+15 Erminatedtay
+$ SIGURG
+16 Urgentway Iway/Oway onditioncay
+$ SIGSTOP
+17 Oppedstay (ignalsay)
+$ SIGTSTP
+18 Oppedstay
+$ SIGCONT
+19 Ontinuedcay
+$ SIGCHLD
+20 Ildchay exitedway
+$ SIGTTIN
+21 Oppedstay (yttay inputway)
+$ SIGTTOU
+22 Oppedstay (yttay outputway)
+$ SIGIO
+23 Iway/Oway ossiblepay
+$ SIGXCPU
+24 Utimecpay imitlay exceededway
+$ SIGXFSZ
+25 Ilesizefay imitlay exceededway
+$ SIGVTALRM
+26 Irtualvay imertay expiredway
+$ SIGPROF
+27 Ofilingpray imertay expiredway
+$ SIGWINCH
+28 Indowway izesay angeschay
+$ SIGINFO
+29 Informationway equestray
+$ SIGUSR1
+30 Userway efinedday ignalsay 1
+$ SIGUSR2
+31 Userway efinedday ignalsay 2
+$ SIGPWR
+32 Owerpay ailfay/estartray
diff --git a/lib/nbsd_libc/nls/_catclose.c b/lib/nbsd_libc/nls/_catclose.c
new file mode 100644 (file)
index 0000000..97398c7
--- /dev/null
@@ -0,0 +1,26 @@
+/*     $NetBSD: _catclose.c,v 1.7 2005/09/13 01:44:09 christos Exp $   */
+
+/*
+ * Written by J.T. Conklin, 10/05/94
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _catclose.c,v 1.7 2005/09/13 01:44:09 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_catclose, catclose)
+#else
+
+#include <nl_types.h>
+int    _catclose(nl_catd);
+
+int
+catclose(nl_catd catd)
+{
+       return _catclose(catd);
+}
+
+#endif
diff --git a/lib/nbsd_libc/nls/_catgets.c b/lib/nbsd_libc/nls/_catgets.c
new file mode 100644 (file)
index 0000000..ea506e7
--- /dev/null
@@ -0,0 +1,26 @@
+/*     $NetBSD: _catgets.c,v 1.8 2005/09/13 01:44:10 christos Exp $    */
+
+/*
+ * Written by J.T. Conklin, 10/05/94
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _catgets.c,v 1.8 2005/09/13 01:44:10 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_catgets, catgets)
+#else
+
+#include <nl_types.h>
+char   *_catgets(nl_catd, int, int, const char *);
+
+char *
+catgets(nl_catd catd, int set_id, int msg_id, const char *s)
+{
+       return _catgets(catd, set_id, msg_id, s);
+}
+
+#endif
diff --git a/lib/nbsd_libc/nls/_catopen.c b/lib/nbsd_libc/nls/_catopen.c
new file mode 100644 (file)
index 0000000..440a8aa
--- /dev/null
@@ -0,0 +1,26 @@
+/*     $NetBSD: _catopen.c,v 1.7 2005/09/13 01:44:10 christos Exp $    */
+
+/*
+ * Written by J.T. Conklin, 10/05/94
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _catopen.c,v 1.7 2005/09/13 01:44:10 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_catopen, catopen)
+#else
+
+#include <nl_types.h>
+nl_catd        _catopen(__const char *, int);
+
+nl_catd
+catopen(__const char *name, int oflag)
+{
+       return _catopen(name, oflag);
+}
+
+#endif
diff --git a/lib/nbsd_libc/nls/ca.msg b/lib/nbsd_libc/nls/ca.msg
new file mode 100644 (file)
index 0000000..740028f
--- /dev/null
@@ -0,0 +1,258 @@
+$set 1
+$ EPERM
+1 Operació no permesa
+$ ENOENT
+2 Arxiu o directori inexistent
+$ ESRCH
+3 Procés inexistent
+$ EINTR
+4 Crida del sistema interrompuda
+$ EIO
+5 Error d'entrada/sortida
+$ ENXIO
+6 Dispositiu no configurat
+$ E2BIG
+7 Llista de paràmetres massa llarga
+$ ENOEXEC
+8 Error en el format de l'executable
+$ EBADF
+9 Descriptor d'arxiu incorrecte
+$ ECHILD
+10 No hi ha processos fills
+$ EDEADLK
+11 S'ha evitat el bloqueig del recurs
+$ ENOMEM
+12 No es pot assignar la memòria demanada
+$ EACCES
+13 Permís denegat
+$ EFAULT
+14 Adreça incorrecta
+$ ENOTBLK
+15 Es necessita un dispositiu de blocs
+$ EBUSY
+16 Dispositiu ocupat
+$ EEXIST
+17 L'arxiu ja existeix
+$ EXDEV
+18 Enllaç entre dispositius
+$ ENODEV
+19 Operació no suportada pel dispositiu
+$ ENOTDIR
+20 No Ã©s un directori
+$ EISDIR
+21 Ã‰s un directori
+$ EINVAL
+22 Paràmetre incorrecte
+$ ENFILE
+23 Hi ha massa arxius oberts al sistema
+$ EMFILE
+24 Hi ha massa arxius oberts
+$ ENOTTY
+25 L'ioctl no Ã©s adecuat per al dispositiu
+$ ETXTBSY
+26 Arxiu de text ocupat
+$ EFBIG
+27 Arxiu massa gran
+$ ENOSPC
+28 No queda espai lliure en el dispositiu
+$ ESPIPE
+29 Cerca il·legal
+$ EROFS
+30 Sistema d'arxius de només lectura
+$ EMLINK
+31 Massa enllaços
+$ EPIPE
+32 Canal (pipe) trencat
+$ EDOM
+33 El resultat surt fora de rang
+$ ERANGE
+34 Resultat massa gran
+$ EAGAIN, EWOULDBLOCK
+35 El recurs no està disponible temporalment
+$ EINPROGRESS
+36 L'operació es troba en progrés actualment
+$ EALREADY
+37 L'operació ja es troba en progrés
+$ ENOTSOCK
+38 Operació de tipus socket en quelcom que no ho Ã©s
+$ EDESTADDRREQ
+39 Es requereix l'adreça de destí
+$ EMSGSIZE
+40 Missatge massa llarg
+$ EPROTOTYPE
+41 Tipus de protocol incorrecte per al socket
+$ ENOPROTOOPT
+42 Protocol no disponible
+$ EPROTONOSUPPORT
+43 Protocol no suportat
+$ ESOCKTNOSUPPORT
+44 Tipus de socket no suportat
+$ EOPNOTSUPP
+45 Operació no suportada
+$ EPFNOSUPPORT
+46 Família de protocols no suportada
+$ EAFNOSUPPORT
+47 Família d'adreces no suportada per la família de protocols
+$ EADDRINUSE
+48 L'adreça ja es troba en Ãºs
+$ EADDRNOTAVAIL
+49 No es pot assignar l'adreça demanada
+$ ENETDOWN
+50 La xarxa no es troba disponible
+$ ENETUNREACH
+51 No es pot accedir a la xarxa
+$ ENETRESET
+52 La connexió a la xarxa s'ha perdut durant la reinicialització
+$ ECONNABORTED
+53 El programari ha causat l'avort de la connexió
+$ ECONNRESET
+54 L'interlocutor ha reinicialitzat la comunicació
+$ ENOBUFS
+55 No hi ha prou espai per a la memoria intermèdia (buffer)
+$ EISCONN
+56 El socket ja es troba connectat
+$ ENOTCONN
+57 El socket no es troba connectat
+$ ESHUTDOWN
+58 No es pot enviar desprès de la desconnexió del socket
+$ ETOOMANYREFS
+59 Hi ha massa referències: no es poden unir
+$ ETIMEDOUT
+60 El temps de connexió s'ha esgotat
+$ ECONNREFUSED
+61 Connexió rebutjada
+$ ELOOP
+62 Hi ha massa nivells d'enllaços simbòlics
+$ ENAMETOOLONG
+63 Nom d'arxiu massa llarg
+$ EHOSTDOWN
+64 La màquina no es troba disponible
+$ EHOSTUNREACH
+65 No hi ha cap camí fins a la màquina
+$ ENOTEMPTY
+66 El directori no està buit
+$ EPROCLIM
+67 Hi ha massa processos
+$ EUSERS
+68 Hi ha massa usuaris
+$ EDQUOT
+69 Quota de disc sobrepassada
+$ ESTALE
+70 Descriptor d'arxiu NFS incorrecte
+$ EREMOTE
+71 Massa nivells en el camí de destí
+$ EBADRPC
+72 L'estructura RPC es incorrecta
+$ ERPCMISMATCH
+73 La versió del RPC es incorrecta
+$ EPROGUNAVAIL
+74 El programa RPC no es troba disponible
+$ EPROGMISMATCH
+75 Versió incorrecta del programa
+$ EPROCUNAVAIL
+76 Procediment erroni per al programa
+$ ENOLCK
+77 No hi ha bloquejos disponibles
+$ ENOSYS
+78 Funció no implementada
+$ EFTYPE
+79 Tipus d'arxiu o de format inadequat
+$ EAUTH
+80 Error d'autenticació
+$ ENEEDAUTH
+81 Es necessita un autenticador
+$ EIDRM
+82 Identificador eliminat
+$ ENOMSG
+83 No hi ha missatges del tipus desitjat
+$ EOVERFLOW
+84 Valor massa gran per a Ã©sser emmagatzemat en el tipus de dades
+$ EILSEQ
+85 Seqüència de bytes il·legal
+$ ENOTSUP
+86 No suportat
+$ ECANCELED
+87 Operació cancel·lada
+$ EBADMSG
+88 Missatje incorrecte o corrupte
+$ ENODATA
+89 No hi ha missatges disponibles
+$ ENOSR
+90 No hi ha recursos de tipus STREAM
+$ ENOSTR
+91 No Ã©s un STREAM
+$ ETIME
+92 Temps d'espera esgotat en el ioctl STREAM
+$ ENOATTR
+93 Atribut inexistent
+$ EMULTIHOP
+94 S'ha intentat un multisalt
+$ ENOLINK
+95 L'enllaç s'ha servit
+$ EPROTO
+96 Error de protocol
+$set 2
+$ SIGHUP
+1 Fí de línia (hangup)
+$ SIGINT
+2 Interrupció
+$ SIGQUIT
+3 Finalització
+$ SIGILL
+4 Instrucció il·legal
+$ SIGTRAP
+5 Depuració (Trace/BPT)
+$ SIGABRT
+6 Crida d'avort
+$ SIGEMT
+7 Captura d'EMT
+$ SIGFPE
+8 Excepció de coma flotant
+$ SIGKILL
+9 Matat
+$ SIGBUS
+10 Error del bus
+$ SIGSEGV
+11 Error de segmentació
+$ SIGSYS
+12 Crida al sistema incorrecta
+$ SIGPIPE
+13 Canal (pipe) trencat
+$ SIGALRM
+14 Alarma de rellotge
+$ SIGTERM
+15 Finalitzat
+$ SIGURG
+16 Condició urgent d'E/S
+$ SIGSTOP
+17 Parat (per senyal)
+$ SIGTSTP
+18 Parat
+$ SIGCONT
+19 Continuant
+$ SIGCHLD
+20 El fill ha acabat
+$ SIGTTIN
+21 Parat (entrada de tty)
+$ SIGTTOU
+22 Parat (sortida de tty)
+$ SIGIO
+23 I/O permesa
+$ SIGXCPU
+24 S'ha sobrepassat el límit de temps de la CPU
+$ SIGXFSZ
+25 S'ha sobrepassat el límit de la longitud de l'arxiu
+$ SIGVTALRM
+26 El temporitzador virtual ha expirat
+$ SIGPROF
+27 El temporitzador del perfilador ha expirat
+$ SIGWINCH
+28 Canvis en la mida de la finestra
+$ SIGINFO
+29 Demanda d'informació
+$ SIGUSR1
+30 Senyal 1 definida per l'usuari
+$ SIGUSR2
+31 Senyal 2 definida per l'usuari
+$ SIGPWR
+32 Fallada/reinicialització de l'alimentació
diff --git a/lib/nbsd_libc/nls/catclose.3 b/lib/nbsd_libc/nls/catclose.3
new file mode 100644 (file)
index 0000000..abfada7
--- /dev/null
@@ -0,0 +1,32 @@
+.\"    $NetBSD: catclose.3,v 1.12 2003/07/26 19:24:49 salo Exp $
+.\"
+.\" Written by J.T. Conklin <jtc@NetBSD.org>.
+.\" Public domain.
+.\"
+.Dd May 29, 1994
+.Dt CATCLOSE 3
+.Os
+.Sh NAME
+.Nm catclose
+.Nd close message catalog
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In nl_types.h
+.Ft int
+.Fn catclose "nl_catd catd"
+.Sh DESCRIPTION
+The
+.Fn catclose
+function closes the message catalog specified by the argument
+.Fa catd .
+.Sh SEE ALSO
+.Xr gencat 1 ,
+.Xr catgets 3 ,
+.Xr catopen 3 ,
+.Xr nls 7
+.Sh STANDARDS
+The
+.Fn catclose
+function conforms to
+.St -xpg3 .
diff --git a/lib/nbsd_libc/nls/catclose.c b/lib/nbsd_libc/nls/catclose.c
new file mode 100644 (file)
index 0000000..3c99440
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: catclose.c,v 1.13 2008/04/28 20:23:00 martin Exp $     */
+
+/*-
+ * Copyright (c) 1996 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: catclose.c,v 1.13 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define _NLS_PRIVATE
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/mman.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <nl_types.h>
+
+#ifdef __weak_alias
+__weak_alias(catclose, _catclose)
+#endif
+
+int
+_catclose(catd)
+       nl_catd catd;
+{
+       if (catd == (nl_catd) -1) {
+               errno = EBADF;
+               return -1;
+       }
+       
+       if (catd) {
+               munmap(catd->__data, (size_t)catd->__size);
+               free (catd);
+       }
+
+       return 0;
+}
diff --git a/lib/nbsd_libc/nls/catgets.3 b/lib/nbsd_libc/nls/catgets.3
new file mode 100644 (file)
index 0000000..87c798f
--- /dev/null
@@ -0,0 +1,73 @@
+.\"    $NetBSD: catgets.3,v 1.16 2003/07/26 19:24:49 salo Exp $
+.\"
+.\" Written by J.T. Conklin <jtc@NetBSD.org>.
+.\" Public domain.
+.\"
+.Dd February 12, 2003
+.Dt CATGETS 3
+.Os
+.Sh NAME
+.Nm catgets
+.Nd retrieve string from message catalog
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In nl_types.h
+.Ft char *
+.Fn catgets "nl_catd catd" "int set_id" "int msg_id" "const char *s"
+.Sh DESCRIPTION
+The
+.Fn catgets
+function attempts to retrieve message
+.Fa msg_id
+of set
+.Fa set_id
+from the message catalog referenced by the descriptor
+.Fa catd .
+The argument
+.Fa s
+points to a default message which is returned if the function
+is unable to retrieve the specified message.
+.Sh RETURN VALUES
+If the specified message was retrieved successfully,
+.Fn catgets
+returns a pointer to an internal buffer containing the message string;
+otherwise it returns
+.Fa s .
+.Sh ERRORS
+The
+.Fn catgets
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa catd
+argument is not a valid message catalog descriptor open for reading.
+.It Bq Er EINTR
+The operation was interrupted by a signal.
+.It Bq Er ENOMSG
+The message identified by
+.Fa set_id
+and
+.Fa msg_id
+is not in the message catalog.
+.El
+.Sh SEE ALSO
+.Xr gencat 1 ,
+.Xr catclose 3 ,
+.Xr catopen 3 ,
+.Xr nls 7
+.Sh STANDARDS
+The
+.Fn catgets
+function conforms to
+.St -xpg4.2 .
+.Pp
+Major Unix vendors are split over the adoption of the two most
+important message catalog specifications: catgets or
+.Xr gettext 3 .
+The primary concern with the catgets interface is that every
+translatable string has to define a number (or a symbolic constant)
+which must correspond to the message in the catalog.
+Duplicate message IDs are not allowed.
+Constructing message catalogs is difficult.
diff --git a/lib/nbsd_libc/nls/catgets.c b/lib/nbsd_libc/nls/catgets.c
new file mode 100644 (file)
index 0000000..acee17b
--- /dev/null
@@ -0,0 +1,117 @@
+/*     $NetBSD: catgets.c,v 1.18 2008/04/28 20:23:00 martin Exp $      */
+
+/*-
+ * Copyright (c) 1996 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: catgets.c,v 1.18 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define _NLS_PRIVATE
+
+#include "namespace.h"
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <nl_types.h>
+
+#ifdef __weak_alias
+__weak_alias(catgets, _catgets)
+#endif
+
+char *
+_catgets(catd, set_id, msg_id, s)
+       nl_catd catd;
+       int set_id;
+       int msg_id;
+       const char *s;
+{
+       struct _nls_cat_hdr *cat_hdr;
+       struct _nls_set_hdr *set_hdr;
+       struct _nls_msg_hdr *msg_hdr;
+       int l, u, i, r;
+
+       if (catd == (nl_catd) -1) {
+               errno = EBADF;
+               return __UNCONST(s);
+       }
+
+       cat_hdr = (struct _nls_cat_hdr *)catd->__data; 
+       set_hdr = (struct _nls_set_hdr *)(void *)((char *)catd->__data
+               + sizeof(struct _nls_cat_hdr));
+
+       /* binary search, see knuth algorithm b */
+       l = 0;
+       u = ntohl((u_int32_t)cat_hdr->__nsets) - 1;
+       while (l <= u) {
+               i = (l + u) / 2;
+               r = set_id - ntohl((u_int32_t)set_hdr[i].__setno);
+
+               if (r == 0) {
+                       msg_hdr = (struct _nls_msg_hdr *)
+                           (void *)((char *)catd->__data +
+                           sizeof(struct _nls_cat_hdr) +
+                           ntohl((u_int32_t)cat_hdr->__msg_hdr_offset));
+
+                       l = ntohl((u_int32_t)set_hdr[i].__index);
+                       u = l + ntohl((u_int32_t)set_hdr[i].__nmsgs) - 1;
+                       while (l <= u) {
+                               i = (l + u) / 2;
+                               r = msg_id -
+                                   ntohl((u_int32_t)msg_hdr[i].__msgno);
+                               if (r == 0) {
+                                       return ((char *) catd->__data +
+                                           sizeof(struct _nls_cat_hdr) +
+                                           ntohl((u_int32_t)
+                                           cat_hdr->__msg_txt_offset) +
+                                           ntohl((u_int32_t)
+                                           msg_hdr[i].__offset));
+                               } else if (r < 0) {
+                                       u = i - 1;
+                               } else {
+                                       l = i + 1;
+                               }
+                       }
+
+                       /* not found */
+                       goto notfound;
+
+               } else if (r < 0) {
+                       u = i - 1;
+               } else {
+                       l = i + 1;
+               }
+       }
+
+notfound:
+       /* not found */
+       errno = ENOMSG;
+       return __UNCONST(s);
+}
diff --git a/lib/nbsd_libc/nls/catopen.3 b/lib/nbsd_libc/nls/catopen.3
new file mode 100644 (file)
index 0000000..c26364f
--- /dev/null
@@ -0,0 +1,61 @@
+.\"    $NetBSD: catopen.3,v 1.14 2003/07/26 19:24:49 salo Exp $
+.\"
+.\" Written by J.T. Conklin <jtc@NetBSD.org>.
+.\" Public domain.
+.\"
+.Dd May 29, 1994
+.Dt CATOPEN 3
+.Os
+.Sh NAME
+.Nm catopen
+.Nd open message catalog
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In nl_types.h
+.Ft nl_catd
+.Fn catopen "const char *name" "int oflag"
+.Sh DESCRIPTION
+The
+.Fn catopen
+function opens the message catalog specified by
+.Fa name
+and returns a message catalog descriptor.
+If
+.Fa name
+contains a
+.Sq /
+then
+.Fa name
+specifies the full pathname for the message catalog, otherwise the value
+of the environment variable
+.Ev NLSPATH
+is used with
+.Fa name
+substituted for %N.
+.Pp
+The
+.Fa oflag
+argument is reserved for future use and should be set to zero.
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn catopen
+returns a message catalog descriptor.
+Otherwise, (nl_catd) -1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er ENOMEM
+Insufficient memory is available.
+.El
+.Sh SEE ALSO
+.Xr gencat 1 ,
+.Xr catclose 3 ,
+.Xr catgets 3 ,
+.Xr nls 7
+.Sh STANDARDS
+The
+.Fn catopen
+function conforms to
+.St -xpg3 .
diff --git a/lib/nbsd_libc/nls/catopen.c b/lib/nbsd_libc/nls/catopen.c
new file mode 100644 (file)
index 0000000..ac1eabb
--- /dev/null
@@ -0,0 +1,194 @@
+/*     $NetBSD: catopen.c,v 1.28 2009/03/10 13:15:40 joerg Exp $       */
+
+/*-
+ * Copyright (c) 1996 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: catopen.c,v 1.28 2009/03/10 13:15:40 joerg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#define _NLS_PRIVATE
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+
+#include <assert.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <locale.h>
+#include <nl_types.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef HAVE_CITRUS
+#include "citrus_namespace.h"
+#include "citrus_bcs.h"
+#include "citrus_region.h"
+#include "citrus_lookup.h"
+#include "citrus_aliasname_local.h"
+#else
+#include "aliasname_local.h"
+#endif
+
+#define NLS_ALIAS_DB "/usr/share/nls/nls.alias"
+
+#define NLS_DEFAULT_PATH "/usr/share/nls/%L/%N.cat:/usr/share/nls/%N/%L"
+#define NLS_DEFAULT_LANG "C"
+
+#ifdef __weak_alias
+__weak_alias(catopen, _catopen)
+#endif
+
+static nl_catd load_msgcat __P((const char *));
+
+nl_catd
+_catopen(name, oflag)
+       const char *name;
+       int oflag;
+{
+       char tmppath[PATH_MAX+1];
+       const char *nlspath;
+       const char *lang, *reallang;
+       char *t;
+       const char *s, *u;
+       nl_catd catd;
+       char langbuf[PATH_MAX];
+
+       if (name == NULL || *name == '\0')
+               return (nl_catd)-1;
+
+       /* absolute or relative path? */
+       if (strchr(name, '/'))
+               return load_msgcat(name);
+
+       if (issetugid() || (nlspath = getenv("NLSPATH")) == NULL)
+               nlspath = NLS_DEFAULT_PATH;
+       if (oflag == NL_CAT_LOCALE) {
+               lang = setlocale(LC_MESSAGES, NULL);
+       }
+       else {
+               lang = getenv("LANG");
+       }
+       if (lang == NULL || strchr(lang, '/'))
+               lang = NLS_DEFAULT_LANG;
+
+       reallang = __unaliasname(NLS_ALIAS_DB, lang, langbuf, sizeof(langbuf));
+       if (reallang == NULL)
+               reallang = lang;
+
+       s = nlspath;
+       t = tmppath;
+       do {
+               while (*s && *s != ':') {
+                       if (*s == '%') {
+                               switch (*(++s)) {
+                               case 'L':       /* locale */
+                                       u = reallang;
+                                       while (*u && t < tmppath + PATH_MAX)
+                                               *t++ = *u++;
+                                       break;
+                               case 'N':       /* name */
+                                       u = name;
+                                       while (*u && t < tmppath + PATH_MAX)
+                                               *t++ = *u++;
+                                       break;
+                               case 'l':       /* lang */
+                               case 't':       /* territory */
+                               case 'c':       /* codeset */
+                                       break;
+                               default:
+                                       if (t < tmppath + PATH_MAX)
+                                               *t++ = *s;
+                               }
+                       } else {
+                               if (t < tmppath + PATH_MAX)
+                                       *t++ = *s;
+                       }
+                       s++;
+               }
+
+               *t = '\0';
+               catd = load_msgcat(tmppath);
+               if (catd != (nl_catd)-1)
+                       return catd;
+
+               if (*s)
+                       s++;
+               t = tmppath;
+       } while (*s);
+
+       return (nl_catd)-1;
+}
+
+static nl_catd
+load_msgcat(path)
+       const char *path;
+{
+       struct stat st;
+       nl_catd catd;
+       void *data;
+       int fd;
+
+       _DIAGASSERT(path != NULL);
+
+       if ((fd = open(path, O_RDONLY)) == -1)
+               return (nl_catd)-1;
+
+       if (fstat(fd, &st) != 0) {
+               close (fd);
+               return (nl_catd)-1;
+       }
+
+       data = mmap(0, (size_t)st.st_size, PROT_READ, MAP_FILE|MAP_SHARED, fd,
+           (off_t)0);
+       close (fd);
+
+       if (data == MAP_FAILED) {
+               return (nl_catd)-1;
+       }
+
+       if (ntohl((u_int32_t)((struct _nls_cat_hdr *)data)->__magic) !=
+           _NLS_MAGIC) {
+               munmap(data, (size_t)st.st_size);
+               return (nl_catd)-1;
+       }
+
+       if ((catd = malloc(sizeof (*catd))) == NULL) {
+               munmap(data, (size_t)st.st_size);
+               return (nl_catd)-1;
+       }
+
+       catd->__data = data;
+       catd->__size = (int)st.st_size;
+       return catd;
+}
diff --git a/lib/nbsd_libc/nls/cs.msg b/lib/nbsd_libc/nls/cs.msg
new file mode 100644 (file)
index 0000000..97e6cbf
--- /dev/null
@@ -0,0 +1,258 @@
+$set 1
+$ EPERM
+1 Operace není povolena
+$ ENOENT
+2 Neexistující soubor nebo adresáø
+$ ESRCH
+3 Proces neexistuje
+$ EINTR
+4 Systémové volání pøeru¹eno
+$ EIO
+5 Vstupní/výstupní chyba
+$ ENXIO
+6 Zaøízení není nakonfigurováno
+$ E2BIG
+7 Seznam argumentù je pøíli¹ dlouhý
+$ ENOEXEC
+8 Chyba formátu spu¹tìného souboru
+$ EBADF
+9 Â©patný souborový deskriptor
+$ ECHILD
+10 Neexistuje Â¾Ã¡dný potomek procesu
+$ EDEADLK
+11 Zabránìno uváznutí (deadlock) prostøedku
+$ ENOMEM
+12 Nedostatek pamìti
+$ EACCES
+13 Pøístup odmítnut
+$ EFAULT
+14 Chybná adresa
+$ ENOTBLK
+15 Vy¾adováno blokové zaøízení
+$ EBUSY
+16 Zdroj nebo zaøízení je zaneprázdnìno
+$ EEXIST
+17 Soubor existuje
+$ EXDEV
+18 Odkaz vede na jiné zaøízení
+$ ENODEV
+19 Operace není zaøízením podporována
+$ ENOTDIR
+20 Toto není adresáø
+$ EISDIR
+21 Toto je adresáø
+$ EINVAL
+22 Chybný argument
+$ ENFILE
+23 Pøíli¹ mnoho otevøených souborù v systému
+$ EMFILE
+24 Pøíli¹ mnoho otevøených souborù
+$ ENOTTY
+25 Pro dané zaøízení nevhodné ioctl
+$ ETXTBSY
+26 S textovým souborem se pracuje
+$ EFBIG
+27 Soubor je pøíli¹ velký
+$ ENOSPC
+28 Na zaøízení není volné místo
+$ ESPIPE
+29 Neplatný lseek(2)
+$ EROFS
+30 Souborový systém je pouze pro Ã¨tení
+$ EMLINK
+31 Pøíli¹ mnoho odkazù
+$ EPIPE
+32 Pøeru¹ená roura
+$ EDOM
+33 ÃˆÃ­selný argument mimo definièní obor
+$ ERANGE
+34 Výsledek pøíli¹ velký nebo pøíli¹ malý
+$ EAGAIN, EWOULDBLOCK
+35 Prostøedek je doèasnì nedostupný
+$ EINPROGRESS
+36 Operace nyní probíhá
+$ EALREADY
+37 Operace ji¾ probíhá
+$ ENOTSOCK
+38 Socketová operace na neèem, co není socket
+$ EDESTADDRREQ
+39 Vy¾adována adresa cíle
+$ EMSGSIZE
+40 Zpráva je pøíli¹ dlouhá
+$ EPROTOTYPE
+41 Protokol nepodporuje daný typ socketu
+$ ENOPROTOOPT
+42 Protokol není dostupný
+$ EPROTONOSUPPORT
+43 Protokol není podporován
+$ ESOCKTNOSUPPORT
+44 Typ socketu není podporován
+$ EOPNOTSUPP
+45 Operace není podporována
+$ EPFNOSUPPORT
+46 Rodina protokolù není podporována
+$ EAFNOSUPPORT
+47 Rodina adres není protokolem podporována
+$ EADDRINUSE
+48 Adresa je ji¾ pou¾ívána
+$ EADDRNOTAVAIL
+49 Není mo¾no pøidìlit po¾adovanou adresu
+$ ENETDOWN
+50 Sí» je odpojena
+$ ENETUNREACH
+51 Sí» je nedosa¾itelná
+$ ENETRESET
+52 Sí» zru¹ila spojení po resetu
+$ ECONNABORTED
+53 Program zpùsobil ukonèení spojení
+$ ECONNRESET
+54 Spojení zru¹eno partnerem
+$ ENOBUFS
+55 Vyrovnávací pamì» není k dispozici
+$ EISCONN
+56 Socket je ji¾ u¾ pøipojen
+$ ENOTCONN
+57 Socket není pøipojen
+$ ESHUTDOWN
+58 Není mo¾no posílat po shutdownu socketu
+$ ETOOMANYREFS
+59 Pøíli¹ mnoho referencí: nelze spojit
+$ ETIMEDOUT
+60 Pøekroèen Ã¨asový limit pokusu o spojení
+$ ECONNREFUSED
+61 Spojení odmítnuto
+$ ELOOP
+62 Pøíli¹ mnoho Ãºrovní symbolických odkazù
+$ ENAMETOOLONG
+63 Jméno souboru pøíli¹ dlouhé
+$ EHOSTDOWN
+64 Vzdálený uzel je odpojen
+$ EHOSTUNREACH
+65 Neexistuje cesta ke vzdálenému uzlu
+$ ENOTEMPTY
+66 Adresáø není prázdný
+$ EPROCLIM
+67 Pøíli¹ mnoho procesù
+$ EUSERS
+68 Pøíli¹ mnoho u¾ivatelù
+$ EDQUOT
+69 Disková kvóta pøekroèena
+$ ESTALE
+70 Propadnutý souborový ukazatel pro NFS
+$ EREMOTE
+71 Pøíli¹ mnoho Ãºrovní vzdáleného v cestì
+$ EBADRPC
+72 Â©patná RPC struktura
+$ ERPCMISMATCH
+73 RPC: Nekompatibilní verze RPC
+$ EPROGUNAVAIL
+74 RPC: Program není dostupný
+$ EPROGMISMATCH
+75 RPC: Neshoda programu nebo verze
+$ EPROCUNAVAIL
+76 RPC: Procedura není dostupná
+$ ENOLCK
+77 Zámky souborových záznamù nejsou dostupné
+$ ENOSYS
+78 Funkce není implementována
+$ EFTYPE
+79 Nevhodný typ nebo formát souboru
+$ EAUTH
+80 Chyba autentifikace
+$ ENEEDAUTH
+81 Je tøeba se autentifikovat
+$ EIDRM
+82 Identifikátor zru¹en
+$ ENOMSG
+83 Neexistuje zpráva Â¾Ã¡daného typu
+$ EOVERFLOW
+84 Hodnota je pro daný datový typ pøíli¹ velká
+$ EILSEQ
+85 Neplatná posloupnost bajtù
+$ ENOTSUP
+86 Nepodporováno
+$ ECANCELED
+87 Operace strornována
+$ EBADMSG
+88 Â©patná nebo poru¹ená zpráva
+$ ENODATA
+89 Â®Ã¡dná zpráva není dostupná
+$ ENOSR
+90 Â®Ã¡dné STREAM prostøedky
+$ ENOSTR
+91 Není STREAM
+$ ETIME
+92 Vypr¹el Ã¨asový limit STREAM ioctl
+$ ENOATTR
+93 Atribut nebyl nalezen
+$ EMULTIHOP
+94 Pokus o spojení pøes více uzlù
+$ ENOLINK
+95 Odkaz byl zpøetrhán
+$ EPROTO
+96 Chyba protokolu
+$set 2
+$ SIGHUP
+1 Terminál odpojen
+$ SIGINT
+2 Pøeru¹ení
+$ SIGQUIT
+3 Konec
+$ SIGILL
+4 Chybná instrukce
+$ SIGTRAP
+5 Ladící instrukce
+$ SIGABRT
+6 Násilné ukonèení
+$ SIGEMT
+7 Emulovaná instrukce
+$ SIGFPE
+8 Výjimka pohyblivé Ã¨Ã¡rky
+$ SIGKILL
+9 Zabito
+$ SIGBUS
+10 Chyba sbìrnice
+$ SIGSEGV
+11 Chyba segmentace
+$ SIGSYS
+12 Â©patné systémove volání
+$ SIGPIPE
+13 Broken pipe
+$ SIGALRM
+14 Alarm Ã¨asovaè
+$ SIGTERM
+15 Ukonèeno
+$ SIGURG
+16 Naléhavý I/O po¾adavek
+$ SIGSTOP
+17 Pozastaveno (signál)
+$ SIGTSTP
+18 Pozastaveno
+$ SIGCONT
+19 Pokraèování
+$ SIGCHLD
+20 Potomek procesu ukonèen
+$ SIGTTIN
+21 Pozastaveno (terminálový vstup)
+$ SIGTTOU
+22 Pozastaveno (terminálový výstup)
+$ SIGIO
+23 Vstup/výstup mo¾ný
+$ SIGXCPU
+24 Pøekroèen Ã¨asový limit pro CPU
+$ SIGXFSZ
+25 Pøekroèen limit velikosti souboru
+$ SIGVTALRM
+26 Vypr¹el virtuální Ã¨asovaè
+$ SIGPROF
+27 Vypr¹el profilovací Ã¨asovaè
+$ SIGWINCH
+28 Velikost okna zmìnìna
+$ SIGINFO
+29 Informaèní po¾adavek
+$ SIGUSR1
+30 U¾ivatelský signál 1
+$ SIGUSR2
+31 U¾ivatelský signál 2
+$ SIGPWR
+32 Selhání/nastartování napájení
diff --git a/lib/nbsd_libc/nls/de.msg b/lib/nbsd_libc/nls/de.msg
new file mode 100644 (file)
index 0000000..32d4101
--- /dev/null
@@ -0,0 +1,258 @@
+$set 1
+$ EPERM
+1 Operation nicht erlaubt
+$ ENOENT
+2 Datei oder Verzeichnis nicht gefunden
+$ ESRCH
+3 Prozess nicht gefunden
+$ EINTR
+4 Interrupt innerhalb eines Systemaufrufs
+$ EIO
+5 Ein/Ausgabefehler
+$ ENXIO
+6 Gerät ist nicht konfiguriert
+$ E2BIG
+7 Argumentliste ist zu lang
+$ ENOEXEC
+8 Die Datei hat kein bekanntes ausführbares Format
+$ EBADF
+9 Ungültiger Dateideskriptor
+$ ECHILD
+10 Kein Kindprozess
+$ EDEADLK
+11 Ein Deadlock wurde vermieden
+$ ENOMEM
+12 Kann nicht genug Speicher belegen
+$ EACCES
+13 Zugriff verboten
+$ EFAULT
+14 Ungültige Adresse
+$ ENOTBLK
+15 Es wird ein Blockgerät benötigt
+$ EBUSY
+16 Das Gerät ist belegt
+$ EEXIST
+17 Datei existiert bereits
+$ EXDEV
+18 Link zwischen verschiedenen Geräten
+$ ENODEV
+19 Die Operation wird von diesem Gerät nicht unterstützt
+$ ENOTDIR
+20 Kein Verzeichnis
+$ EISDIR
+21 Ist ein Verzeichnis
+$ EINVAL
+22 Ungültiges Argument
+$ ENFILE
+23 Zu viele offene Dateien im gesamten System
+$ EMFILE
+24 Zu viele offene Dateien
+$ ENOTTY
+25 Ungültiger Ioctl für dieses Gerät
+$ ETXTBSY
+26 Ausführbare Datei wird benutzt
+$ EFBIG
+27 Datei zu groß
+$ ENOSPC
+28 Kein Platz mehr auf dem Gerät
+$ ESPIPE
+29 Ungültige Positionierung
+$ EROFS
+30 Dateisystem ist schreibgeschützt
+$ EMLINK
+31 Zu viele Links
+$ EPIPE
+32 Unterbrochene Pipe
+$ EDOM
+33 Numerisches Argument ausserhalb des Wertebereichs
+$ ERANGE
+34 Ergebnis zu groß oder zu klein
+$ EAGAIN, EWOULDBLOCK
+35 Ressource vorübergehend nicht verfügbar
+$ EINPROGRESS
+36 Operation wird jetzt fortgesetzt
+$ EALREADY
+37 Operation wird bereits ausgeführt
+$ ENOTSOCK
+38 Deskriptor ist kein Socket
+$ EDESTADDRREQ
+39 Zieladresse benötigt
+$ EMSGSIZE
+40 Nachricht zu lang
+$ EPROTOTYPE
+41 Ungültiger Protokolltyp für diesen Socket
+$ ENOPROTOOPT
+42 Protokoll nicht verfügbar
+$ EPROTONOSUPPORT
+43 Protokoll nicht unterstützt
+$ ESOCKTNOSUPPORT
+44 Sockettyp nicht unterstützt
+$ EOPNOTSUPP
+45 Operation nicht unterstützt
+$ EPFNOSUPPORT
+46 Protokollfamilie nicht unterstützt
+$ EAFNOSUPPORT
+47 Addressart wird von der Protokollfamilie nicht unterstützt
+$ EADDRINUSE
+48 Adresse wird bereits benutzt
+$ EADDRNOTAVAIL
+49 Kann angeforderte Adresse nicht belegen
+$ ENETDOWN
+50 Netzwerk nicht verfügbar
+$ ENETUNREACH
+51 Netzwerk nicht erreichbar
+$ ENETRESET
+52 Netzwerk hat Verbindung mit Reset abgebrochen
+$ ECONNABORTED
+53 Software verursachte einen Verbindungsabbruch
+$ ECONNRESET
+54 Verbindung wurde von der Gegenstelle geschlossen
+$ ENOBUFS
+55 Keine Buffer verfügbar
+$ EISCONN
+56 Socket ist schon verbunden
+$ ENOTCONN
+57 Socket ist nicht verbunden
+$ ESHUTDOWN
+58 Kann nach einem Socket-Shutdown nicht mehr senden
+$ ETOOMANYREFS
+59 Zu viele Referenzen, kann nicht verbinden
+$ ETIMEDOUT
+60 Verbindungsabbruch durch Zeitüberschreitung
+$ ECONNREFUSED
+61 Verbindung wurde abgelehnt
+$ ELOOP
+62 Zu viele symbolische Links (zirkulär?)
+$ ENAMETOOLONG
+63 Dateiname zu lang
+$ EHOSTDOWN
+64 Host nicht verfügbar
+$ EHOSTUNREACH
+65 Keine Route zum Host
+$ ENOTEMPTY
+66 Verzeichnis ist nicht leer
+$ EPROCLIM
+67 Zu viele Prozesse
+$ EUSERS
+68 Zu viele Benutzer
+$ EDQUOT
+69 Plattenplatzlimit erschöpft
+$ ESTALE
+70 Verwaister NFS-Dateideskriptor
+$ EREMOTE
+71 Zu viele Fernverweise in diesem Zugriff
+$ EBADRPC
+72 RPC-Struktur ist ungültig
+$ ERPCMISMATCH
+73 RPC-Version stimmt nicht
+$ EPROGUNAVAIL
+74 RPC-Programm nicht verfügbar
+$ EPROGMISMATCH
+75 Falsche Programmversion
+$ EPROCUNAVAIL
+76 Falsche Prozedur für dieses Programm
+$ ENOLCK
+77 Keine Dateisperren verfügbar
+$ ENOSYS
+78 Funktion nicht implementiert
+$ EFTYPE
+79 Ungültiger Dateityp oder Dateiformat
+$ EAUTH
+80 Authentikationsfehler
+$ ENEEDAUTH
+81 Authentikator benötigt
+$ EIDRM
+82 Identifizierung entfernt
+$ ENOMSG
+83 Keine Nachricht vom gewünschten Typ
+$ EOVERFLOW
+84 Wert zu groß, um in Datentyp zu speichern
+$ EILSEQ
+85 Illegale Byte-Sequenz
+$ ENOTSUP
+86 Operation nicht unterstützt
+$ ECANCELED
+87 Operation abgebrochen
+$ EBADMSG
+88 Ungültige Nachricht
+$ ENODATA
+89 Keine Nachricht verfügbar
+$ ENOSR
+90 Keine STREAM-Ressourcen verfügbar
+$ ENOSTR
+91 Kein STREAM
+$ ETIME
+92 Zeitüberschreitung bei STREAM Ioctl
+$ ENOATTR
+93 Attribut nicht gefunden
+$ EMULTIHOP
+94 Multihopversuch
+$ ENOLINK
+95 Verbindung wurde getrennt
+$ EPROTO
+96 Protokollfehler
+$set 2
+$ SIGHUP
+1 Verbindungsende
+$ SIGINT
+2 Unterbrechung
+$ SIGQUIT
+3 Programmende
+$ SIGILL
+4 Ungültiger Maschinenbefehl
+$ SIGTRAP
+5 Trace/BPT trap
+$ SIGABRT
+6 Abort trap
+$ SIGEMT
+7 EMT trap
+$ SIGFPE
+8 Fließkommafehler
+$ SIGKILL
+9 Unbedingter Programmabbruch
+$ SIGBUS
+10 Bus-Zugriffsfehler
+$ SIGSEGV
+11 Illegaler Speicherzugriff
+$ SIGSYS
+12 Ungültiger Systemaufruf
+$ SIGPIPE
+13 Unterbrochene Pipe
+$ SIGALRM
+14 Wecker
+$ SIGTERM
+15 Beendet
+$ SIGURG
+16 Dringende Ein/Ausgabeanforderung
+$ SIGSTOP
+17 Gestoppt (Signal)
+$ SIGTSTP
+18 Gestoppt
+$ SIGCONT
+19 Fortgesetzt
+$ SIGCHLD
+20 Kindprozess beendet
+$ SIGTTIN
+21 Gestoppt (Eingabe)
+$ SIGTTOU
+22 Gestoppt (Ausgabe)
+$ SIGIO
+23 Ein/Ausgabe ist möglich
+$ SIGXCPU
+24 CPU-Zeitlimit erschöpft
+$ SIGXFSZ
+25 Dateigröße hat das Limit erreicht
+$ SIGVTALRM
+26 Virtueller Wecker abgelaufen
+$ SIGPROF
+27 Profil-Wecker abgelaufen
+$ SIGWINCH
+28 Fenstergröße hat sich geändert
+$ SIGINFO
+29 Informationsanforderung
+$ SIGUSR1
+30 Benutzerdefiniertes Signal 1
+$ SIGUSR2
+31 Benutzerdefiniertes Signal 2
+$ SIGPWR
+32 Statusänderung der Energieversorgung
diff --git a/lib/nbsd_libc/nls/es.msg b/lib/nbsd_libc/nls/es.msg
new file mode 100644 (file)
index 0000000..7428ed6
--- /dev/null
@@ -0,0 +1,258 @@
+$set 1
+$ EPERM
+1 Operación no permitida
+$ ENOENT
+2 Archivo o directorio inexistente
+$ ESRCH
+3 Proceso inexistente
+$ EINTR
+4 Llamada del sistema interrumpida
+$ EIO
+5 Error de E/S
+$ ENXIO
+6 Dispositivo no configurado
+$ E2BIG
+7 La lista de argumentos es demasiado larga
+$ ENOEXEC
+8 Error en el formato del ejecutable 
+$ EBADF
+9 Descriptor de archivo incorrecto
+$ ECHILD
+10 No hay procesos hijo 
+$ EDEADLK
+11 Se ha evitado bloqueo del recurso
+$ ENOMEM
+12 No se pudo asignar la memoria pedida
+$ EACCES
+13 Permiso denegado
+$ EFAULT
+14 Dirección incorrecta
+$ ENOTBLK
+15 Se necesita un dispositivo de bloques
+$ EBUSY
+16 Dispositivo ocupado
+$ EEXIST
+17 El archivo ya existe
+$ EXDEV
+18 Enlace entre dispositivos
+$ ENODEV
+19 Operación inadecuada para este dispositivo
+$ ENOTDIR
+20 No es un directorio
+$ EISDIR
+21 Es un directorio
+$ EINVAL
+22 Argumento inadecuado
+$ ENFILE
+23 Hay demasiados archivos abiertos en el sistema
+$ EMFILE
+24 Hay demasiados archivos abiertos
+$ ENOTTY
+25 IOCTL inapropiado para el dispositivo
+$ ETXTBSY
+26 Archivo de texto ocupado
+$ EFBIG
+27 Archivo demasiado grande
+$ ENOSPC
+28 No queda espacio libre en el dispositivo
+$ ESPIPE
+29 Búsqueda ilegal
+$ EROFS
+30 Archivo del sistema de sólo lectura
+$ EMLINK
+31 Demasiados enlaces
+$ EPIPE
+32 Canal (pipe) roto
+$ EDOM
+33 El argumento numérico está fuera de rango
+$ ERANGE
+34 El resultado es demasiado grande
+$ EAGAIN, EWOULDBLOCK
+35 El recurso no está disponible temporalmente
+$ EINPROGRESS
+36 Operación actualmente en proceso
+$ EALREADY
+37 La operación ya estaba realizándose
+$ ENOTSOCK
+38 Operación de socket inaceptable por el dispositivo
+$ EDESTADDRREQ
+39 Se necesita una dirección de destino
+$ EMSGSIZE
+40 Mensaje demasiado largo
+$ EPROTOTYPE
+41 Tipo erróneo de protocolo para el socket
+$ ENOPROTOOPT
+42 Protocolo no disponible
+$ EPROTONOSUPPORT
+43 Protocolo no contemplado
+$ ESOCKTNOSUPPORT
+44 Tipo de socket no contemplado
+$ EOPNOTSUPP
+45 Operación no contemplada
+$ EPFNOSUPPORT
+46 Familia de protocolos no contemplada
+$ EAFNOSUPPORT
+47 Familia de direcciones no contemplada por la familia de protocolos
+$ EADDRINUSE
+48 La dirección ya está en uso
+$ EADDRNOTAVAIL
+49 No se pudo asignar la dirección pedida
+$ ENETDOWN
+50 La red no funciona
+$ ENETUNREACH
+51 No se puede acceder a la red
+$ ENETRESET
+52 La conexión a la red se interrumpió al reinicializar
+$ ECONNABORTED
+53 La conexión se ha abortado debido a problemas en el software
+$ ECONNRESET
+54 El interlocutor ha reinicializado la comunicación
+$ ENOBUFS
+55 No queda espacio en el buffer
+$ EISCONN
+56 El socket ya estaba conectado
+$ ENOTCONN
+57 El socket no está conectado
+$ ESHUTDOWN
+58 No se puede enviar tras la desconexión del socket
+$ ETOOMANYREFS
+59 Demasiadas referencias: no se pueden unir
+$ ETIMEDOUT
+60 El tiempo de conexión ha expirado
+$ ECONNREFUSED
+61 Conexión rehusada
+$ ELOOP
+62 Demasiados niveles de enlaces simbólicos
+$ ENAMETOOLONG
+63 Nombre de archivo demasiado largo
+$ EHOSTDOWN
+64 La máquina está fuera de servicio
+$ EHOSTUNREACH
+65 No hay ruta hasta la máquina
+$ ENOTEMPTY
+66 Directorio no vacío
+$ EPROCLIM
+67 Demasiados procesos
+$ EUSERS
+68 Demasiados usuarios
+$ EDQUOT
+69 Cuota de disco sobrepasada
+$ ESTALE
+70 Descriptor de archivo NFS inválido
+$ EREMOTE
+71 Ruta con demasiados niveles
+$ EBADRPC
+72 La estructura de la RPC es errónea
+$ ERPCMISMATCH
+73 La versión de la RPC es errónea
+$ EPROGUNAVAIL
+74 La RPC no está accesible
+$ EPROGMISMATCH
+75 Versión errónea del programa
+$ EPROCUNAVAIL
+76 Procedimiento erróneo para el programa
+$ ENOLCK
+77 No hay bloqueos disponibles
+$ ENOSYS
+78 Función no realizada
+$ EFTYPE
+79 Tipo de archivo o formato inapropiado
+$ EAUTH
+80 Error de la autentificación
+$ ENEEDAUTH
+81 Se necesita un autenticador
+$ EIDRM
+82 Identificador quitado
+$ ENOMSG
+83 No hay mensajes del tipo deseado
+$ EOVERFLOW
+84 Valor demasiado grande para ser almacenado en el tipo de datos
+$ EILSEQ
+85 Secuencia de bytes no legal
+$ ENOTSUP
+86 No soportado
+$ ECANCELED
+87 Operación cancelada
+$ EBADMSG
+88 Mensaje incorrecto o corrupto
+$ ENODATA
+89 No hay mensajes disponibles
+$ ENOSR
+90 No hay recursos de tipo STREAM
+$ ENOSTR
+91 No es un STREAM
+$ ETIME
+92 Tiempo de espera agotado en el ioctl STREAM
+$ ENOATTR
+93 Atributo no encontrado
+$ EMULTIHOP
+94 Se ha intentado un multisalto
+$ ENOLINK
+95 El enlace se ha servido
+$ EPROTO
+96 Error de protocolo
+$set 2
+$ SIGHUP
+1 Fín de línea (hangup)
+$ SIGINT
+2 Interrumpido
+$ SIGQUIT
+3 Terminado
+$ SIGILL
+4 Instrucción ilegal
+$ SIGTRAP
+5 Depuración
+$ SIGABRT
+6 Llamada de aborto
+$ SIGEMT
+7 Captura de EMT
+$ SIGFPE
+8 Excepción de coma flotante
+$ SIGKILL
+9 Matado
+$ SIGBUS
+10 Error en el bus
+$ SIGSEGV
+11 Fallo de segmentación
+$ SIGSYS
+12 Llamada al sistema errónea
+$ SIGPIPE
+13 Canal (pipe) roto
+$ SIGALRM
+14 Alarma del reloj
+$ SIGTERM
+15 Terminado
+$ SIGURG
+16 Condición urgente de E/S
+$ SIGSTOP
+17 Detenido (señal)
+$ SIGTSTP
+18 Detenido
+$ SIGCONT
+19 Continuando
+$ SIGCHLD
+20 Proceso hijo finalizado
+$ SIGTTIN
+21 Detenido (entrada tty)
+$ SIGTTOU
+22 Detenido (salida tty)
+$ SIGIO
+23 E/S posible
+$ SIGXCPU
+24 Se ha sobrepasado el tiempo límite de la CPU
+$ SIGXFSZ
+25 Se ha sobrepasado el límite de longitud de archivo
+$ SIGVTALRM
+26 Temporizador virtual expirado
+$ SIGPROF
+27 Temporizador de perfilación expirado
+$ SIGWINCH
+28 Cambios en el tamaño de la ventana
+$ SIGINFO
+29 Petición de información
+$ SIGUSR1
+30 Señal definida por el usuario nº 1
+$ SIGUSR2
+31 Señal definida por el usuario nº 2
+$ SIGPWR
+32 Fallo o reinicio de la alimentación
diff --git a/lib/nbsd_libc/nls/fi.msg b/lib/nbsd_libc/nls/fi.msg
new file mode 100644 (file)
index 0000000..d947549
--- /dev/null
@@ -0,0 +1,224 @@
+$set 1
+$ EPERM
+1 Toimintoa ei sallita
+$ ENOENT
+2 Tiedostoa tai hakemistoa ei löydy
+$ ESRCH
+3 Prosessia ei löydy
+$ EINTR
+4 Systeemikutsu keskeytyi
+$ EIO
+5 Syöttö/tulostusvirhe
+$ ENXIO
+6 Laitetta ei määritelty
+$ E2BIG
+7 Liikaa argumentteja
+$ ENOEXEC
+8 Tuntematon ohjelmatyyppi
+$ EBADF
+9 Virheellinen tiedosto-osoitin
+$ ECHILD
+10 Ei lapsiprosesseja
+$ EDEADLK
+11 Resurssin ristiinlukitus vältetty
+$ ENOMEM
+12 Muistinvaraus epäonnistui
+$ EACCES
+13 Lupa kielletty
+$ EFAULT
+14 Virheellinen osoite
+$ ENOTBLK
+15 Tarvitaan lohko-osoitettava laite
+$ EBUSY
+16 Laite käytössä
+$ EEXIST
+17 Tiedosto on jo olemassa
+$ EXDEV
+18 Laitteiden välinen linkki
+$ ENODEV
+19 Laite ei tue toimintoa
+$ ENOTDIR
+20 Kohde ei ole hakemisto
+$ EISDIR
+21 Kohde on hakemisto
+$ EINVAL
+22 Virheellinen argumentti
+$ ENFILE
+23 Järjestelmässä on liian monta avointa tiedostoa
+$ EMFILE
+24 Liian monta avointa tiedostoa
+$ ENOTTY
+25 Virheellinen ohjaustoiminto laitteelle
+$ ETXTBSY
+26 Tiedosto on käytössä
+$ EFBIG
+27 Tiedosto liian suuri
+$ ENOSPC
+28 Laitteella ei ole tilaa
+$ ESPIPE
+29 Virheellinen haku
+$ EROFS
+30 Vain luettava tiedostojärjestelmä
+$ EMLINK
+31 Liian monta linkkiä
+$ EPIPE
+32 Katkennut putki
+$ EDOM
+33 Numeerinen syöte virheellinen
+$ ERANGE
+34 Tulos liian suuri
+$ EAGAIN, EWOULDBLOCK
+35 Resurssi ei ole tilapäisesti saatavilla
+$ EINPROGRESS
+36 Toiminta on käynnissä
+$ EALREADY
+37 Toiminta oli jo käynnissä
+$ ENOTSOCK
+38 Socket-operaatio muulla kuin socketilla
+$ EDESTADDRREQ
+39 Tarvitaan kohdeosoite
+$ EMSGSIZE
+40 Sanoma liian pitkä
+$ EPROTOTYPE
+41 Väärä protokolla socketille
+$ ENOPROTOOPT
+42 Protokolla ei ole käytettävissä
+$ EPROTONOSUPPORT
+43 Protokollaa ei tueta
+$ ESOCKTNOSUPPORT
+44 Socket-tyyppiä ei tueta
+$ EOPNOTSUPP
+45 Toimintoa ei tueta
+$ EPFNOSUPPORT
+46 Protokollaperhettä ei tueta
+$ EAFNOSUPPORT
+47 Protokollaperhe ei tue osoiteperhettä
+$ EADDRINUSE
+48 Osoite on jo käytössä
+$ EADDRNOTAVAIL
+49 Ei pysty antamaan pyydettyä osoitetta
+$ ENETDOWN
+50 Verkko ei ole käytettävissä
+$ ENETUNREACH
+51 Verkkoon ei ole yhteyttä
+$ ENETRESET
+52 Verkko sulki yhteyden
+$ ECONNABORTED
+53 Ohjelmiston aiheuttama yhteyden keskeytyminen
+$ ECONNRESET
+54 Isäntä nollasi yhteyden
+$ ENOBUFS
+55 Puskuritila on lopussa
+$ EISCONN
+56 Yhteys on jo olemassa
+$ ENOTCONN
+57 Yhteyttä ei ole olemassa
+$ ESHUTDOWN
+58 Lähettäminen ei ole mahdollista yhteyden katkaisun jälkeen
+$ ETOOMANYREFS
+59 Liikaa viittauksia: ei voi yhdistää
+$ ETIMEDOUT
+60 Yhteyden aikavalvontakatkaisu
+$ ECONNREFUSED
+61 Yhteys hylätty
+$ ELOOP
+62 Liian monta peräkkäistä symbolista linkkiä
+$ ENAMETOOLONG
+63 Tiedoston nimi on liian pitkä
+$ EHOSTDOWN
+64 Isäntä ei vastaa
+$ EHOSTUNREACH
+65 Ei reittiä isäntään
+$ ENOTEMPTY
+66 Hakemisto ei ole tyhjä
+$ EPROCLIM
+67 Liian monta prosessia
+$ EUSERS
+68 Liian monta käyttäjää
+$ EDQUOT
+69 Levytilarajoitus ylittyi
+$ ESTALE
+70 Vanhentunut NFS-yhteys
+$ EREMOTE
+71 Liian monta verkkolevyä polussa
+$ EBADRPC
+72 Virheellinen RPC-pyyntö
+$ ERPCMISMATCH
+73 Väärä RPC-versio
+$ EPROGUNAVAIL
+74 RPC ei käytettävissä
+$ EPROGMISMATCH
+75 Väärä ohjelmaversio
+$ EPROCUNAVAIL
+76 Väärä RPC-pyyntö ohjelmalle
+$ ENOLCK
+77 Lukitus ei käytettävissä
+$ ENOSYS
+78 Toimintoa ei ole
+$ EFTYPE
+79 Väärä tiedostotyyppi tai -formaatti
+$set 2
+$ SIGHUP
+1 Katkaisu
+$ SIGINT
+2 Keskeytys
+$ SIGQUIT
+3 Lopetus
+$ SIGILL
+4 Laiton käsky
+$ SIGTRAP
+5 Jäljitys/BPT ansa
+$ SIGABRT
+6 Poistumisansa
+$ SIGEMT
+7 EMT-ansa
+$ SIGFPE
+8 Liukulukuvirhe
+$ SIGKILL
+9 Tapettu
+$ SIGBUS
+10 Väylävirhe
+$ SIGSEGV
+11 Suojausvirhe
+$ SIGSYS
+12 Virheellinen systeemikutsu
+$ SIGPIPE
+13 Katkennut putki
+$ SIGALRM
+14 Hälytyskello
+$ SIGTERM
+15 Lopetettu
+$ SIGURG
+16 Kiireellinen syöttö/tulostus
+$ SIGSTOP
+17 Pysäytetty (signaali)
+$ SIGTSTP
+18 Pysäytetty
+$ SIGCONT
+19 Jatkettu
+$ SIGCHLD
+20 Lapsiprosessi päättynyt
+$ SIGTTIN
+21 Pysäytetty (tty-syöte)
+$ SIGTTOU
+22 Pysäytetty (tty-tuloste)
+$ SIGIO
+23 Syöttö ja tulostus mahdollisia
+$ SIGXCPU
+24 Keskusyksikköaikarajoitus ylitetty
+$ SIGXFSZ
+25 Tiedoston kokorajoitus ylitetty
+$ SIGVTALRM
+26 Virtuaali-ajastin laukesi
+$ SIGPROF
+27 Profilointiajastin laukesi
+$ SIGWINCH
+28 Ikkunan koko muuttuu
+$ SIGINFO
+29 Informaatiopyyntö
+$ SIGUSR1
+30 Käyttäjän määriteltävä signaali 1
+$ SIGUSR2
+31 Käyttäjän määriteltävä signaali 2
+$ SIGPWR
+32 Virransaannin tilassa muutos
diff --git a/lib/nbsd_libc/nls/fr.msg b/lib/nbsd_libc/nls/fr.msg
new file mode 100644 (file)
index 0000000..099670e
--- /dev/null
@@ -0,0 +1,252 @@
+$set 1
+$ EPERM
+1 Opération non autorisée
+$ ENOENT
+2 Fichier ou répertoire introuvable
+$ ESRCH
+3 Processus introuvable
+$ EINTR
+4 Appel système interrompu
+$ EIO
+5 Erreur d'entrée/sortie
+$ ENXIO
+6 Périphérique non configuré
+$ E2BIG
+7 Liste de paramètres trop longue
+$ ENOEXEC
+8 Erreur de format d'exécutable
+$ EBADF
+9 Descripteur de fichier invalide
+$ ECHILD
+10 Pas de processus fils
+$ EDEADLK
+11 Etreinte fatale Ã©vitée
+$ ENOMEM
+12 Plus de mémoire
+$ EACCES
+13 Autorisation refusée
+$ EFAULT
+14 Adresse invalide
+$ ENOTBLK
+15 Nécessite un périphérique en mode bloc
+$ EBUSY
+16 Périphérique occupé
+$ EEXIST
+17 Fichier existant
+$ EXDEV
+18 Lien hors du périphérique
+$ ENODEV
+19 Opération non supportée par le périphérique
+$ ENOTDIR
+20 N'est pas un répertoire
+$ EISDIR
+21 C'est un réperoire
+$ EINVAL
+22 Paramètre invalide
+$ ENFILE
+23 Trop de fichiers ouverts dans le système
+$ EMFILE
+24 Trop de fichiers ouverts
+$ ENOTTY
+25 Ioctl inconnu du périphérique
+$ ETXTBSY
+26 Fichier exécutable utilisé
+$ EFBIG
+27 Fichier trop grand
+$ ENOSPC
+28 Plus de place sur le périphérique
+$ ESPIPE
+29 Positionnement illégal
+$ EROFS
+30 Système de fichier protégé en Ã©criture
+$ EMLINK
+31 Trop de liens
+$ EPIPE
+32 Tube cassé
+$ EDOM
+33 Paramètre numérique hors du domaine
+$ ERANGE
+34 Résultat trop grand
+$ EAGAIN, EWOULDBLOCK
+35 Ressource temporairement indisponible
+$ EINPROGRESS
+36 Opération actuellement en cours
+$ EALREADY
+37 Opération déjà en cours
+$ ENOTSOCK
+38 Opération réservée aux sockets
+$ EDESTADDRREQ
+39 Adresse de destination nécéssaire
+$ EMSGSIZE
+40 Message trop long
+$ EPROTOTYPE
+41 Protocole inadapté au socket
+$ ENOPROTOOPT
+42 Protocole non disponible
+$ EPROTONOSUPPORT
+43 Protocole non supporté
+$ ESOCKTNOSUPPORT
+44 Type de socket non supporté
+$ EOPNOTSUPP
+45 Opération non supportée
+$ EPFNOSUPPORT
+46 Famille de protocoles non supportée
+$ EAFNOSUPPORT
+47 Famille d'adresses non supporté par cette famille de protocoles
+$ EADDRINUSE
+48 Adresse déjà utilisée
+$ EADDRNOTAVAIL
+49 Impossible d'affecter l'adresse demandée
+$ ENETDOWN
+50 Réseau arrêté
+$ ENETUNREACH
+51 Réseau non atteignable
+$ ENETRESET
+52 Connexion perdue après un RAZ du réseau
+$ ECONNABORTED
+53 Fin de connexion causée par logiciel
+$ ECONNRESET
+54 Connexion terminée par le correspondant
+$ ENOBUFS
+55 Plus de place pour la mémoire tampon
+$ EISCONN
+56 Socket déjà connecté
+$ ENOTCONN
+57 Socket non connecté
+$ ESHUTDOWN
+58 Impossible de transmettre après fermeture du socket
+$ ETOOMANYREFS
+59 Trop de références: impossible Ã  réassembler
+$ ETIMEDOUT
+60 Délai de connexion expiré
+$ ECONNREFUSED
+61 Connexion refusée
+$ ELOOP
+62 Trop de niveaux de liens symboliques
+$ ENAMETOOLONG
+63 Nom de fichier trop long
+$ EHOSTDOWN
+64 Machine arrêtée
+$ EHOSTUNREACH
+65 Pas de route vers cette machine
+$ ENOTEMPTY
+66 Répertoire non vide
+$ EPROCLIM
+67 Trop de processus
+$ EUSERS
+68 Trop d'utilisateurs
+$ EDQUOT
+69 Quota disque Ã©puisé
+$ ESTALE
+70 Identificateur NFS périmé
+$ EREMOTE
+71 Trop de points de montages dans le chemin
+$ EBADRPC
+72 Structure RPC invalide
+$ ERPCMISMATCH
+73 Mauvaise version RPC
+$ EPROGUNAVAIL
+74 Programme RPC non disponible
+$ EPROGMISMATCH
+75 Mauvaise version de programme
+$ EPROCUNAVAIL
+76 Procédure inexistante
+$ ENOLCK
+77 Pas de verrous disponibles
+$ ENOSYS
+78 Fonction non implémentée
+$ EFTYPE
+79 Type ou format de fichier inadapté
+$ EAUTH
+80 Erreur lors de l'authentification
+$ ENEEDAUTH
+81 Authentication nécessaire
+$ EIDRM  
+82 Identifiant supprimé
+$ ENOMSG
+83 Pas de message du type demandé
+$ EOVERFLOW
+84 Valeur trop grande pour stocker dans le type de données
+$ EILSEQ
+85 Séquence d'octets illégale
+$ ENOTSUP
+86 Non supporté
+$ ECANCELED
+87 Opération annulée
+$ EBADMSG
+88 Message invalide ou corrompu
+$ ENODATA
+89 Pas de message disponible
+$ ENOSR
+90 Pas de ressource de type STREAM disponible
+$ ENOSTR
+91 N'est pas un STREAM
+$ ETIME 
+92 Délai expiré pour un ioctl STREAM
+$ ENOATTR 
+93 Attribut non trouvé
+$set 2
+$ SIGHUP
+1 Raccroché
+$ SIGINT
+2 Interruption
+$ SIGQUIT
+3 Quitte
+$ SIGILL
+4 Instruction illégale
+$ SIGTRAP
+5 Point de trace/arrêt
+$ SIGABRT
+6 Avorté
+$ SIGEMT
+7 Appel Ã©mulateur
+$ SIGFPE
+8 Exception numérique
+$ SIGKILL
+9 Tué
+$ SIGBUS
+10 Erreur bus
+$ SIGSEGV
+11 Erreur de segmentation
+$ SIGSYS
+12 Appel système invalide
+$ SIGPIPE
+13 Tube cassé
+$ SIGALRM
+14 Alarme
+$ SIGTERM
+15 Terminé
+$ SIGURG
+16 Condition d'E/S urgente
+$ SIGSTOP
+17 Arrêté par un signal
+$ SIGTSTP
+18 Arrêté
+$ SIGCONT
+19 Reprise
+$ SIGCHLD
+20 Fin d'un fils
+$ SIGTTIN
+21 Arrêté (lecture sur tty)
+$ SIGTTOU
+22 Arrêté (écriture sur tty)
+$ SIGIO
+23 E/S possible
+$ SIGXCPU
+24 Limite du temps CPU atteinte
+$ SIGXFSZ
+25 Limite de taille de fichier atteinte
+$ SIGVTALRM
+26 Timer virtuel expiré
+$ SIGPROF
+27 Timer de profiling expiré
+$ SIGWINCH
+28 Changement de taille de la fenêtre
+$ SIGINFO
+29 Demande d'informations
+$ SIGUSR1
+30 Signal utilisateur 1
+$ SIGUSR2
+31 Signal utilisateur 2
+$ SIGPWR
+32 Coupure/reprise d'alimentation
diff --git a/lib/nbsd_libc/nls/nl.msg b/lib/nbsd_libc/nls/nl.msg
new file mode 100644 (file)
index 0000000..dc63a29
--- /dev/null
@@ -0,0 +1,258 @@
+$set 1
+$ EPERM
+1 Bewerking niet toegestaan
+$ ENOENT
+2 Bestand of directory niet gevonden
+$ ESRCH
+3 Taak bestaat niet
+$ EINTR
+4 Onderbroken systeemaanroep
+$ EIO
+5 Invoer/uitvoer fout
+$ ENXIO
+6 Apparaat niet geconfigureerd
+$ E2BIG
+7 Argumenten lijst is te lang
+$ ENOEXEC
+8 Programma kan niet worden uitgevoerd
+$ EBADF
+9 Ongeldige bestandsverwijzing
+$ ECHILD
+10 Geen kind processen
+$ EDEADLK
+11 Een "deadlock" is vermeden
+$ ENOMEM
+12 Kan geen geheugen meer verkrijgen
+$ EACCES
+13 Toegang geweigerd
+$ EFAULT
+14 Ongeldig adres
+$ ENOTBLK
+15 Een per blok adresseerbaar apparaat is vereist
+$ EBUSY
+16 Apparaat is bezig
+$ EEXIST
+17 Bestand bestaat reeds
+$ EXDEV
+18 Verwijzing tussen bestanden op verschillende bestandssystemen
+$ ENODEV
+19 Bewerking wordt niet ondersteund door dit apparaat
+$ ENOTDIR
+20 Dit is geen directory
+$ EISDIR
+21 Dit is een directory
+$ EINVAL
+22 Ongeldig argument
+$ ENFILE
+23 Te veel open bestanden in het systeem
+$ EMFILE
+24 Te veel open bestanden
+$ ENOTTY
+25 ioctl niet van toepassing op dit apparaat
+$ ETXTBSY
+26 Programma bestand is bezig
+$ EFBIG
+27 Bestand is te groot
+$ ENOSPC
+28 Geen ruimte meer op dit apparaat
+$ ESPIPE
+29 Onuitvoerbare zoekopdracht
+$ EROFS
+30 Van dit bestandssysteem kan alleen worden gelezen
+$ EMLINK
+31 Te veel bestandsverwijzingen
+$ EPIPE
+32 Verbroken pijp
+$ EDOM
+33 Numeriek argument valt buiten domein
+$ ERANGE
+34 Resultaat te groot of te klein
+$ EAGAIN, EWOULDBLOCK
+35 Middel tijdelijk onbeschikbaar
+$ EINPROGRESS
+36 Bewerking in gang gezet
+$ EALREADY
+37 Bewerking is al in gang gezet
+$ ENOTSOCK
+38 Voor deze bewerking is een contactpunt vereist
+$ EDESTADDRREQ
+39 Een bestemmingsadres is vereist
+$ EMSGSIZE
+40 Te grote boodschap
+$ EPROTOTYPE
+41 Protocol past niet bij dit contactpunt
+$ ENOPROTOOPT
+42 Protocol is niet beschikbaar
+$ EPROTONOSUPPORT
+43 Protocol is niet ondersteund
+$ ESOCKTNOSUPPORT
+44 Dit soort contactpunt is niet ondersteund
+$ EOPNOTSUPP
+45 Bewerking niet ondersteund
+$ EPFNOSUPPORT
+46 Protocol familie niet ondersteund
+$ EAFNOSUPPORT
+47 Adressen familie niet ondersteund door protocol familie
+$ EADDRINUSE
+48 Adres is al in gebruik
+$ EADDRNOTAVAIL
+49 Het gevraagde adres kan niet worden toegekend
+$ ENETDOWN
+50 Netwerk is plat
+$ ENETUNREACH
+51 Netwerk is onbereikbaar
+$ ENETRESET
+52 Netwerk onderbrak verbinding tijdens herstart
+$ ECONNABORTED
+53 Verbroken verbinding veroorzaakt door software
+$ ECONNRESET
+54 Verbinding werd aan de andere kant verbroken
+$ ENOBUFS
+55 Geen buffer ruimte meer beschikbaar
+$ EISCONN
+56 Dit contactpunt is al verbonden
+$ ENOTCONN
+57 Contactpunt is niet verbonden
+$ ESHUTDOWN
+58 Een afgesloten contactpunt kan geen gegevens meer verzenden
+$ ETOOMANYREFS
+59 Te veel verwijzingen: splitsen niet mogelijk
+$ ETIMEDOUT
+60 Verbinding te lang niet mogelijk
+$ ECONNREFUSED
+61 Verbinding geweigerd
+$ ELOOP
+62 Te veel niveaus van symbolische verwijzingen
+$ ENAMETOOLONG
+63 Bestandsnaam te lang
+$ EHOSTDOWN
+64 Bestemming niet actief
+$ EHOSTUNREACH
+65 Bestemming niet bereikbaar
+$ ENOTEMPTY
+66 Directory is niet leeg
+$ EPROCLIM
+67 Te veel taken
+$ EUSERS
+68 Te veel gebruikers
+$ EDQUOT
+69 Schijf quota overschreden
+$ ESTALE
+70 Verlopen NFS bestandsverwijzing
+$ EREMOTE
+71 Te veel verwijzingen op afstand in dit pad
+$ EBADRPC
+72 RPC argument structuur is incorrect
+$ ERPCMISMATCH
+73 RPC versie is verkeerd
+$ EPROGUNAVAIL
+74 RPC programma niet beschikbaar
+$ EPROGMISMATCH
+75 Programma versie is verkeerd
+$ EPROCUNAVAIL
+76 Taak kan door dit programma niet worden uitgevoerd
+$ ENOLCK
+77 Geen locks beschikbaar
+$ ENOSYS
+78 Deze systeem functie is niet geimplementeerd
+$ EFTYPE
+79 Bestandsformaat niet van toepassing
+$ EAUTH
+80 Aanmeldingsfout
+$ ENEEDAUTH
+81 Aanmeldingsprocedure benodigd
+$ EIDRM
+82 De aanwijzer is verwijderd
+$ ENOMSG
+83 Geen boodschap van het gewenste type
+$ EOVERFLOW
+84 Waarde te groot om te bewaren in data type
+$ EILSEQ
+85 Ongeldige byte reeks
+$ ENOTSUP
+86 Niet ondersteund
+$ ECANCELED
+87 Bewerking geannuleerd
+$ EBADMSG
+88 Verkeerde of defecte boodschap
+$ ENODATA
+89 Geen boodschap beschikbaar
+$ ENOSR
+90 Geen STREAM voorraad
+$ ENOSTR
+91 Dit is geen STREAM
+$ ETIME
+92 STREAM ioctl verlopen
+$ ENOATTR
+93 Attribuut niet gevonden
+$ EMULTIHOP
+94 Multihopverzoek
+$ ENOLINK
+95 Verbinding werd verstoord
+$ EPROTO
+96 Protocolfout
+$set 2
+$ SIGHUP
+1 Opgehangen
+$ SIGINT
+2 Onderbroken
+$ SIGQUIT
+3 Opgegeven
+$ SIGILL
+4 Verboden instructie
+$ SIGTRAP
+5 Spoor/BPT val
+$ SIGABRT
+6 Abort val
+$ SIGEMT
+7 EMT val
+$ SIGFPE
+8 Drijvende komma fout
+$ SIGKILL
+9 Gedood
+$ SIGBUS
+10 Bus fout
+$ SIGSEGV
+11 Segmentatie fout
+$ SIGSYS
+12 Verkeerde systeemaanroep
+$ SIGPIPE
+13 Gebroken pijp
+$ SIGALRM
+14 Wekker
+$ SIGTERM
+15 Beeindigd
+$ SIGURG
+16 Dringende I/O opgemerkt
+$ SIGSTOP
+17 Gestopt (signaal)
+$ SIGTSTP
+18 Gestopt
+$ SIGCONT
+19 Voortgezet
+$ SIGCHLD
+20 Kindproces beeindigd
+$ SIGTTIN
+21 Gestopt (tty invoer)
+$ SIGTTOU
+22 Gestopt (tty uitvoer)
+$ SIGIO
+23 I/O mogelijk
+$ SIGXCPU
+24 Te veel CPU tijd verbruikt
+$ SIGXFSZ
+25 Maximum bestandsgrootte overschreden
+$ SIGVTALRM
+26 Virtuele wekker
+$ SIGPROF
+27 Profiling wekker
+$ SIGWINCH
+28 Venstergrootte veranderd
+$ SIGINFO
+29 Informatie verzoek
+$ SIGUSR1
+30 Gebruikersignaal 1
+$ SIGUSR2
+31 Gebruikersignaal 2
+$ SIGPWR
+32 Stroom uitval/inschakeling
diff --git a/lib/nbsd_libc/nls/no.msg b/lib/nbsd_libc/nls/no.msg
new file mode 100644 (file)
index 0000000..762f45c
--- /dev/null
@@ -0,0 +1,222 @@
+$set 1
+$ EPERM
+1 Operasjonen er ikke tillatt
+$ ENOENT
+2 Filen eller katalogen finnes ikke
+$ ESRCH
+3 Prosessen finnes ikke
+$ EINTR
+4 Avbrudt systemkall
+$ EIO
+5 I/O feil
+$ ENXIO
+6 Enheten er ikke konfigurert
+$ E2BIG
+7 Argumentlisten er for lang
+$ ENOEXEC
+8 Ukjent kjørbart format
+$ EBADF
+9 Ugyldig fildeskriptor
+$ ECHILD
+10 Ingen barneprosess
+$ EDEADLK
+11 VranglÃ¥s unngÃ¥tt
+$ ENOMEM
+12 Kan ikke allokere nok minne
+$ EACCES
+13 Ingen adgang
+$ EFAULT
+14 Ugyldig adresse
+$ ENOTBLK
+15 Blokk-enhet pÃ¥krevd
+$ EBUSY
+16 Enheten er opptatt
+$ EEXIST
+17 Filen finnes
+$ EXDEV
+18 Link mellom forskjellige enheter
+$ ENODEV
+19 Operasjonen er ikke støttet av enheten
+$ ENOTDIR
+20 Ikke en katalog
+$ EISDIR
+21 Er en katalog
+$ EINVAL
+22 Ugyldig argument
+$ ENFILE
+23 For mange Ã¥pne filer i systemet
+$ EMFILE
+24 For mange Ã¥pne filer
+$ ENOTTY
+25 Ugyldig ioctl for enheten
+$ ETXTBSY
+26 Kjørbar fil i bruk
+$ EFBIG
+27 Filen er for stor
+$ ENOSPC
+28 Ingen ledig plass pÃ¥ enheten
+$ ESPIPE
+29 Ugyldig seek operasjon
+$ EROFS
+30 Filsystemet er skrivebeskyttet
+$ EMLINK
+31 For mange linker
+$ EPIPE
+32 Brudt pipe
+$ EDOM
+33 Numerisk argument utenfor arbeidsomrÃ¥det
+$ ERANGE
+34 Resultatet er for stort
+$ EAGAIN, EWOULDBLOCK
+35 Ressurs midlertidig utilgjengelig
+$ EINPROGRESS
+36 Operasjonen er nÃ¥ i gang
+$ EALREADY
+37 Operasjonen er allerede i gang
+$ ENOTSOCK
+38 Deskriptoren er ikke en socket
+$ EDESTADDRREQ
+39 Mottakeradresse er pÃ¥krevd
+$ EMSGSIZE
+40 Meldingen er for lang
+$ EPROTOTYPE
+41 Ugyldig protokolltype for denne socketen
+$ ENOPROTOOPT
+42 Protokollen er ikke tilgjengelig
+$ EPROTONOSUPPORT
+43 Protokollen er ikke støttet
+$ ESOCKTNOSUPPORT
+44 Socket-typen er ikke støttet
+$ EOPNOTSUPP
+45 Operasjonen er ikke støttet
+$ EPFNOSUPPORT
+46 Protokollfamilien er ikke støttet
+$ EAFNOSUPPORT
+47 Adressetypen er ikke støttet av protokollfamilien
+$ EADDRINUSE
+48 Adressen er allerede i bruk
+$ EADDRNOTAVAIL
+49 Kan ikke bruke den Ã¸nskede adressen
+$ ENETDOWN
+50 Nettverket er nede
+$ ENETUNREACH
+51 Nettverket er utilgjengelig
+$ ENETRESET
+52 Nettverket kuttet forbindelsen ved reset
+$ ECONNABORTED
+53 Programvaren forÃ¥rsaket brudd av forbindelsen
+$ ECONNRESET
+54 Forbindelsen avbrudt av korrespondenten
+$ ENOBUFS
+55 Buffer-plass ikke tilgjengelig
+$ EISCONN
+56 Socketen er allerede forbundet
+$ ENOTCONN
+57 Socketen er ikke forbundet
+$ ESHUTDOWN
+58 Kan ikke sende etter at socketen er tatt ned
+$ ETOOMANYREFS
+59 For mange referanser: kan ikke slÃ¥ dem sammen
+$ ETIMEDOUT
+60 Tiden til forbindelsen utløp
+$ ECONNREFUSED
+61 Forbindelse nektet
+$ ELOOP
+62 For mange nivÃ¥er med symbolske linker
+$ ENAMETOOLONG
+63 Filnavnet er for langt
+$ EHOSTDOWN
+64 Maskinen er nede
+$ EHOSTUNREACH
+65 Ingen rute til maskinen
+$ ENOTEMPTY
+66 Katalogen er ikke tom
+$ EPROCLIM
+67 For mange prosesser
+$ EUSERS
+68 For mange brukere
+$ EDQUOT
+69 Diskkvote overskredet
+$ ESTALE
+70 FastlÃ¥st NFS fildeskriptor
+$ EREMOTE
+71 For mange nivÃ¥er med remote i stien
+$ EBADRPC
+72 Ugyldig RPC struktur
+$ ERPCMISMATCH
+73 Feil RPC versjon
+$ EPROGUNAVAIL
+74 RPC program ikke tilgjengelig
+$ EPROGMISMATCH
+75 Feil programversjon
+$ EPROCUNAVAIL
+76 Prosedyren finnes ikke i programmet
+$ ENOLCK
+77 Ingen lÃ¥sing tilgjengelig
+$ ENOSYS
+78 Funksjonen er ikke implementert
+$ EFTYPE
+79 Ugyldig filtype eller format
+$set 2
+$ SIGHUP
+1 Hangup
+$ SIGINT
+2 Avbrudd
+$ SIGQUIT
+3 Avslutt
+$ SIGILL
+4 Ugyldig instruksjon
+$ SIGTRAP
+5 Trace/BPT trap
+$ SIGABRT
+6 Abort trap
+$ SIGEMT
+7 EMT trap
+$ SIGFPE
+8 Flyttallsfeil
+$ SIGKILL
+9 Drept
+$ SIGBUS
+10 Buss feil
+$ SIGSEGV
+11 Segmenteringsfeil
+$ SIGSYS
+12 Ugyldig systemkall
+$ SIGPIPE
+13 Brudt pipe
+$ SIGALRM
+14 Alarmklokke
+$ SIGTERM
+15 Terminert
+$ SIGURG
+16 Urgent I/O condition
+$ SIGSTOP
+17 Stoppet (signal)
+$ SIGTSTP
+18 Stoppet
+$ SIGCONT
+19 Fortsetter
+$ SIGCHLD
+20 Barn avsluttet
+$ SIGTTIN
+21 Stoppet (tty input)
+$ SIGTTOU
+22 Stoppet (tty output)
+$ SIGIO
+23 I/O mulig
+$ SIGXCPU
+24 CPU-tid overskredet
+$ SIGXFSZ
+25 Maksimal filstørrelse overskredet
+$ SIGVTALRM
+26 Virtuell timer utløpt
+$ SIGPROF
+27 Profileringstimer utløpt
+$ SIGWINCH
+28 Vindustørrelse endres
+$ SIGINFO
+29 Informasjonsforespørsel
+$ SIGUSR1
+30 Brukerdefinert signal 1
+$ SIGUSR2
+31 Brukerdefinert signal 2
diff --git a/lib/nbsd_libc/nls/pl.msg b/lib/nbsd_libc/nls/pl.msg
new file mode 100644 (file)
index 0000000..4c5d253
--- /dev/null
@@ -0,0 +1,236 @@
+$set 1
+$ EPERM
+1 Operacja nie dozwolona
+$ ENOENT
+2 Nie ma takiego pliku ani katalogu
+$ ESRCH
+3 Nie ma takiego procesu
+$ EINTR
+4 Przerwane wywo³anie systemowe
+$ EIO
+5 B³±d wej¶cia/wyj¶cia
+$ ENXIO
+6 Urz±dzenie nie skonfigurowane
+$ E2BIG
+7 Lista argumentów jest za d³uga
+$ ENOEXEC
+8 B³êdny format pliku wykonywalnego
+$ EBADF
+9 Z³y deskryptor pliku
+$ ECHILD
+10 Brak procesów potomnych
+$ EDEADLK
+11 Unikniêto zakleszczenia zasobów
+$ ENOMEM
+12 Brak pamiêci do przydzia³u
+$ EACCES
+13 Brak dostêpu
+$ EFAULT
+14 Z³y adres
+$ ENOTBLK
+15 Wymagane urz±dzenie blokowe
+$ EBUSY
+16 Urz±dzenie zajête
+$ EEXIST
+17 Plik istnieje
+$ EXDEV
+18 Powi±zanie miedzy urz±dzeniami
+$ ENODEV
+19 Operacja nie obs³ugiwana przez urz±dzenie
+$ ENOTDIR
+20 To nie jest katalog
+$ EISDIR
+21 To jest katalog
+$ EINVAL
+22 B³êdny argument
+$ ENFILE
+23 Za du¿o otwrtych plików w systemie
+$ EMFILE
+24 Za du¿o otwartych plików
+$ ENOTTY
+25 Niew³a¶ciwy dostêp do urz±dzenia
+$ ETXTBSY
+26 Plik tekstowy zajêty
+$ EFBIG
+27 Plik zbyt du¿y
+$ ENOSPC
+28 Nie ma miejsca na urz±dzeniu
+$ ESPIPE
+29 B³êdne przesuniêcie
+$ EROFS
+30 System plików tylko do odczytu
+$ EMLINK
+31 Za du¿o linków
+$ EPIPE
+32 Przerwany potok
+$ EDOM
+33 Argument liczbowy spoza zakresu
+$ ERANGE
+34 Za du¿y wynik
+$ EAGAIN, EWOULDBLOCK
+35 Zasoby chwilowo niedostêpne
+$ EINPROGRESS
+36 Operacja jest w³a¶nie wykonywana
+$ EALREADY
+37 Operacja jest ju¿ wykonywana
+$ ENOTSOCK
+38 Operacja na obiekcie, który nie jest gniazdem
+$ EDESTADDRREQ
+39 Wymagany adres przeznaczenia
+$ EMSGSIZE
+40 Wiadomo¶æ za d³uga
+$ EPROTOTYPE
+41 Ty protoko³u nie pasuje do gniazda
+$ ENOPROTOOPT
+42 Protocó³ nie jest dostêpny
+$ EPROTONOSUPPORT
+43 Protocó³ nie jest obs³ugiwany
+$ ESOCKTNOSUPPORT
+44 Nie obs³ugiwany typ gniazda
+$ EOPNOTSUPP
+45 Operacja nie obs³ugiwana
+$ EPFNOSUPPORT
+46 Nie obs³ugiwana rodzina protoko³ów
+$ EAFNOSUPPORT
+47 Rodzina adresów nie obs³ugiwana przez rodzinê protoko³ów
+$ EADDRINUSE
+48 Adres jest aktualnie w u¿yciu
+$ EADDRNOTAVAIL
+49 Nie mo¿na przypisaæ Â¿Â±danego adresu
+$ ENETDOWN
+50 Sieæ nie dzia³a
+$ ENETUNREACH
+51 Sieæ jest niedostêpna
+$ ENETRESET
+52 Sieæ przerwa³a po³±czenie po resecie
+$ ECONNABORTED
+53 Oprogramowanie spowodowa³o przerwanie po³±czenia
+$ ECONNRESET
+54 Po³±czenie zerwane przez drug± stronê
+$ ENOBUFS
+55 Brak miejsca w buforze
+$ EISCONN
+56 Gniazdo jest ju¿ po³±czone
+$ ENOTCONN
+57 Gniazdo nie jest po³±czone
+$ ESHUTDOWN
+58 Nie mo¿na wysy³aæ po zamkniêciu gniazda
+$ ETOOMANYREFS
+59 Za du¿o powi±zañ: dowi±zanie nie mo¿liwe
+$ ETIMEDOUT
+60 Przekroczono czas oczekiwania na po³±czenie
+$ ECONNREFUSED
+61 Po³±czenie odrzucone
+$ ELOOP
+62 Za du¿o wzajemnych symlinków
+$ ENAMETOOLONG
+63 Zbyt d³uga nazwa pliku
+$ EHOSTDOWN
+64 Host jest wy³±czony
+$ EHOSTUNREACH
+65 Brak drogi do hosta
+$ ENOTEMPTY
+66 Katalog nie jest pusty
+$ EPROCLIM
+67 Za du¿o procesów
+$ EUSERS
+68 Zbyt wielu u¿ytkowników
+$ EDQUOT
+69 Przekroczono limit miejsca na dysku
+$ ESTALE
+70 Uchwyt pliku NFS jest nieaktualny
+$ EREMOTE
+71 Za du¿o poziomów zagnie¿d¿enia w Â¶cie¿ce
+$ EBADRPC
+72 RPC b³êdna struktura
+$ ERPCMISMATCH
+73 RPC z³a wersja
+$ EPROGUNAVAIL
+74 RPC program niedostêpny
+$ EPROGMISMATCH
+75 Z³a wersja programu
+$ EPROCUNAVAIL
+76 Z³a procedura dla programu
+$ ENOLCK
+77 Blokady nie s± dostêpne
+$ ENOSYS
+78 Niezaimplementowana funkcja
+$ EFTYPE
+79 Niew³a¶ciwy typ lub format pliku
+$ EAUTH
+80 B³±d uwierzytelnienia
+$ ENEEDAUTH
+81 Wymagane uwierzytelnienie
+$ EIDRM
+82 Identyfikator zosta³ usuniêty
+$ ENOMSG
+83 Brak komunikatu po¿adanego typu
+$ EOVERFLOW
+84 Warto¶æ za du¿a aby zapamiêtaæ j± w zdefiniowanym typie danych
+$ EILSEQ
+85 B³êdna sekwencja bajtów
+$set 2
+$ SIGHUP
+1 Roz³±czenie
+$ SIGINT
+2 Przerwanie
+$ SIGQUIT
+3 Wyj¶cie
+$ SIGILL
+4 Nieznana instrukcja
+$ SIGTRAP
+5 Pu³apka debuggera/BPT
+$ SIGABRT
+6 Przerwanana pu³apka
+$ SIGEMT
+7 Pu³apka EMT
+$ SIGFPE
+8 B³±d w obliczeniach zmiennoprzecinkowych
+$ SIGKILL
+9 Unicestwiony
+$ SIGBUS
+10 B³±d szyny
+$ SIGSEGV
+11 Naruszenie ochrony pamiêci
+$ SIGSYS
+12 B³êdne wywo³anie systemowe
+$ SIGPIPE
+13 Przerwany potok
+$ SIGALRM
+14 Budzik
+$ SIGTERM
+15 Zakoñczony
+$ SIGURG
+16 Nag³y wypadek I/O
+$ SIGSTOP
+17 Zatrzymany (sygna³)
+$ SIGTSTP
+18 Zatrzymany
+$ SIGCONT
+19 Kontynuacja
+$ SIGCHLD
+20 Proces potomny zakoñczy³ pracê
+$ SIGTTIN
+21 Zatrzymany (wej¶cie z tty)
+$ SIGTTOU
+22 Zatrzymany (wyj¶cie z tty)
+$ SIGIO
+23 Wej/Wyj dozwolone
+$ SIGXCPU
+24 Przekroczony limit czasu procesora
+$ SIGXFSZ
+25 przekroczony limit wielko¶ci pliku
+$ SIGVTALRM
+26 Wirtualny stoper wyczerpany
+$ SIGPROF
+27 Koniec stopera profiluj±cego
+$ SIGWINCH
+28 Zmiana rozmiaru okna
+$ SIGINFO
+29 Â¯Â±danie infromacji
+$ SIGUSR1
+30 Sygna³ u¿ytkownika 1
+$ SIGUSR2
+31 Sygna³ u¿ytkownika 2
+$ SIGPWR
+32 Awaria zasilania/restart
diff --git a/lib/nbsd_libc/nls/sk.msg b/lib/nbsd_libc/nls/sk.msg
new file mode 100644 (file)
index 0000000..d784d37
--- /dev/null
@@ -0,0 +1,258 @@
+$set 1
+$ EPERM
+1 Operácia nie je povolená
+$ ENOENT
+2 Neexistujúci súbor alebo adresár
+$ ESRCH
+3 Proces neexistuje
+$ EINTR
+4 Systémové volanie preru¹ené
+$ EIO
+5 Chyba vstupu/výstupu
+$ ENXIO
+6 Zariadenie nie je nakonfigurované
+$ E2BIG
+7 Príli¹ dlhý zoznam argumentov
+$ ENOEXEC
+8 Chybný formát spusteného súboru
+$ EBADF
+9 Chybný deskriptor súboru
+$ ECHILD
+10 Neexistuje Â¾iaden potomok procesu
+$ EDEADLK
+11 Bolo zabránené zablokovaniu prostriedku
+$ ENOMEM
+12 Nie je mo¾né prideli» pamä»
+$ EACCES
+13 Prístup odmietnutý
+$ EFAULT
+14 Chybná adresa
+$ ENOTBLK
+15 Vy¾adované blokové zariadenie
+$ EBUSY
+16 Zariadenie je pou¾ívané
+$ EEXIST
+17 Súbor existuje
+$ EXDEV
+18 Odkaz medzi zariadeniami
+$ ENODEV
+19 Operácia nie je zariadením podporovaná
+$ ENOTDIR
+20 Nie je adresár
+$ EISDIR
+21 Je adresár
+$ EINVAL
+22 Chybný argument
+$ ENFILE
+23 Priveµa otvorených súborov v systéme
+$ EMFILE
+24 Priveµa otvorených súborov
+$ ENOTTY
+25 Nevhodné ioctl pre dané zariadenie
+$ ETXTBSY
+26 Textový súbor je pou¾ívaný
+$ EFBIG
+27 Súbor je príli¹ veµký
+$ ENOSPC
+28 Na zariadení nie je voµné miesto
+$ ESPIPE
+29 Neprípustné nastavenie pozície
+$ EROFS
+30 Súborový systém je len na Ã¨Ã­tanie
+$ EMLINK
+31 Priveµa odkazov
+$ EPIPE
+32 Preru¹ená rúra
+$ EDOM
+33 ÃˆÃ­selný argument mimo definièný obor
+$ ERANGE
+34 Výsledok príli¹ veµký alebo príli¹ malý
+$ EAGAIN, EWOULDBLOCK
+35 Zdroj je doèasne nedostupný
+$ EINPROGRESS
+36 Operácia práve prebieha
+$ EALREADY
+37 Operácia u¾ prebieha
+$ ENOTSOCK
+38 Socketová operácia na objekte, ktorý nie je socket
+$ EDESTADDRREQ
+39 Vy¾adovaná cieµová adresa
+$ EMSGSIZE
+40 Príli¹ dlhá správa
+$ EPROTOTYPE
+41 Protokol nie je socketom podporovaný
+$ ENOPROTOOPT
+42 Protokol nie je k dispozícii
+$ EPROTONOSUPPORT
+43 Protokol nie je podporovaný
+$ ESOCKTNOSUPPORT
+44 Typ socketu nie je podporovaný
+$ EOPNOTSUPP
+45 Operácia nie je podporovaná
+$ EPFNOSUPPORT
+46 Rodina protokolov nie je podporovaná
+$ EAFNOSUPPORT
+47 Rodina adries nie je podporovaná rodinou protokolov
+$ EADDRINUSE
+48 Adresa je u¾ pou¾ívaná
+$ EADDRNOTAVAIL
+49 Nie je mo¾né prideli» po¾adovanú adresu
+$ ENETDOWN
+50 Sie» je nefunkèná
+$ ENETUNREACH
+51 Sie» je nedostupná
+$ ENETRESET
+52 Sie» zru¹ila spojenie po resete
+$ ECONNABORTED
+53 Program spôsobil ukonèenie spojenia
+$ ECONNRESET
+54 Spojenie zru¹ené druhou stranou
+$ ENOBUFS
+55 Vyrovnávacia pamä» nie je k dispozícii
+$ EISCONN
+56 Socket je u¾ pripojený
+$ ENOTCONN
+57 Socket nie je pripojený
+$ ESHUTDOWN
+58 Nie je mo¾né posiela» po uzavretí socketu
+$ ETOOMANYREFS
+59 Príli¹ mnoho odkazov: nie je mo¾né spoji»
+$ ETIMEDOUT
+60 Ãˆasový limit pre spojenie vypr¹al
+$ ECONNREFUSED
+61 Spojenie odmietnuté
+$ ELOOP
+62 Priveµa Ãºrovní symbolických odkazov
+$ ENAMETOOLONG
+63 Meno súboru príli¹ dlhé
+$ EHOSTDOWN
+64 Vzdialený uzol je odpojený
+$ EHOSTUNREACH
+65 Neexistuje cesta k vzdialenému uzlu
+$ ENOTEMPTY
+66 Adresár nie je prázdny
+$ EPROCLIM
+67 Priveµa procesov
+$ EUSERS
+68 Priveµa pou¾ívateµov
+$ EDQUOT
+69 Disková kvóta prekroèená
+$ ESTALE
+70 Zastaralý NFS súborový ukazateµ
+$ EREMOTE
+71 Priveµa Ãºrovní vzdialeného v ceste
+$ EBADRPC
+72 RPC Â¹truktúra je chybná
+$ ERPCMISMATCH
+73 Chybná verzia RPC
+$ EPROGUNAVAIL
+74 RPC program nie je k dispozícii
+$ EPROGMISMATCH
+75 Chybná verzia RPC programu
+$ EPROCUNAVAIL
+76 Chybná RPC procedúra pre program
+$ ENOLCK
+77 Zámky nie sú k dispozícii
+$ ENOSYS
+78 Funkcia nie je implementovaná
+$ EFTYPE
+79 Nevhodný typ alebo formát súboru
+$ EAUTH
+80 Overenie práv neúspe¹né
+$ ENEEDAUTH
+81 Vy¾adovaný overovací objekt
+$ EIDRM
+82 Identifikátor odstránený
+$ ENOMSG
+83 Neexistuje správa Â¾elaného typu
+$ EOVERFLOW
+84 Hodnota je pre daný dátový typ priveµká
+$ EILSEQ
+85 Neprípustná postupnos» bajtov
+$ ENOTSUP
+86 Nie je podporované
+$ ECANCELED
+87 Operácia zru¹ená
+$ EBADMSG
+88 Chybná alebo poru¹ená správa
+$ ENODATA
+89 Â®iadna správa nie je k dispozícii
+$ ENOSR
+90 Â®iadne STREAM zdroje
+$ ENOSTR
+91 Nie je STREAM
+$ ETIME
+92 Ãˆasový limit pre STREAM ioctl vypr¹al
+$ ENOATTR
+93 Atribút nenájdený
+$ EMULTIHOP
+94 Pokus o spojenie cez viacero uzlov
+$ ENOLINK
+95 Odkaz bol pretrhnutý
+$ EPROTO
+96 Chyba protokolu
+$set 2
+$ SIGHUP
+1 Terminál odpojený
+$ SIGINT
+2 Preru¹enie
+$ SIGQUIT
+3 Koniec
+$ SIGILL
+4 Chybná in¹trukcia
+$ SIGTRAP
+5 Trasovacia/ladiaca in¹trukcia
+$ SIGABRT
+6 Násilné ukonèenie
+$ SIGEMT
+7 Emulovaná in¹trukcia
+$ SIGFPE
+8 Výnimka pohyblivej rádovej Ã¨iarky
+$ SIGKILL
+9 Zabité
+$ SIGBUS
+10 Chyba na zbernici
+$ SIGSEGV
+11 Chyba segmentácie
+$ SIGSYS
+12 Chybné systémové volanie
+$ SIGPIPE
+13 Preru¹ená rúra
+$ SIGALRM
+14 Budík
+$ SIGTERM
+15 Ukonèené
+$ SIGURG
+16 Naliehavý vstupný/výstupný stav
+$ SIGSTOP
+17 Pozastavené (signál)
+$ SIGTSTP
+18 Pozastavené
+$ SIGCONT
+19 Pokraèovanie
+$ SIGCHLD
+20 Potomok procesu ukonèený
+$ SIGTTIN
+21 Pozastavené (terminálový vstup)
+$ SIGTTOU
+22 Pozastavené (terminálový výstup)
+$ SIGIO
+23 Vstup/výstup mo¾ný
+$ SIGXCPU
+24 Prekroèený Ã¨asový limit pre procesor
+$ SIGXFSZ
+25 Prekroèený limit veµkosti súboru
+$ SIGVTALRM
+26 Vypr¹al virtuálny Ã¨asovaè
+$ SIGPROF
+27 Vypr¹al profilovací Ã¨asovaè
+$ SIGWINCH
+28 Veµkos» okna zmenená
+$ SIGINFO
+29 Â®iados» o informáciu
+$ SIGUSR1
+30 Pou¾ívateµom definovaný signál 1
+$ SIGUSR2
+31 Pou¾ívateµom definovaný signál 2
+$ SIGPWR
+32 Zlyhanie/opakované spustenie napájania
diff --git a/lib/nbsd_libc/nls/sv.msg b/lib/nbsd_libc/nls/sv.msg
new file mode 100644 (file)
index 0000000..a309983
--- /dev/null
@@ -0,0 +1,224 @@
+$set 1
+$ EPERM
+1 OtillÃ¥ten operation
+$ ENOENT
+2 Filen eller katalogen finns ej
+$ ESRCH
+3 Denna process finns ej
+$ EINTR
+4 Avbrutet systemanrop
+$ EIO
+5 In-/utmatningsfel
+$ ENXIO
+6 Enheten Ã¤r ej konfigurerad
+$ E2BIG
+7 Argumentlistan Ã¤r för lÃ¥ng
+$ ENOEXEC
+8 Ej körbar fil
+$ EBADF
+9 Felaktigt filhandtag
+$ ECHILD
+10 Inga barnprocesser
+$ EDEADLK
+11 Undvek resursdödläge
+$ ENOMEM
+12 Kan ej erhÃ¥lla minne
+$ EACCES
+13 TillstÃ¥nd nekas
+$ EFAULT
+14 Felaktig adress
+$ ENOTBLK
+15 Blockenhet krävs
+$ EBUSY
+16 Enheten Ã¤r upptagen
+$ EEXIST
+17 Filen finns redan
+$ EXDEV
+18 Länken korsar enheter
+$ ENODEV
+19 Enheten stöder ej operationen
+$ ENOTDIR
+20 Ã„r ej en katalog
+$ EISDIR
+21 Ã„r en katalog
+$ EINVAL
+22 Ogiltigt argument
+$ ENFILE
+23 För mÃ¥nga Ã¶ppna filer i systemet
+$ EMFILE
+24 För mÃ¥nga Ã¶ppna filer
+$ ENOTTY
+25 Olämplig ioctl för enheten
+$ ETXTBSY
+26 Programfilen Ã¤r upptagen
+$ EFBIG
+27 Filen Ã¤r för stor
+$ ENOSPC
+28 Inget utrymme kvar pÃ¥ enheten
+$ ESPIPE
+29 OtillÃ¥ten sökning
+$ EROFS
+30 Skrivskyddat filsystem
+$ EMLINK
+31 För mÃ¥nga länkar
+$ EPIPE
+32 Avbruten kommunikationskanal
+$ EDOM
+33 Numeriskt argument utanför domänen
+$ ERANGE
+34 Resultatet Ã¤r för stort
+$ EAGAIN, EWOULDBLOCK
+35 Resursen Ã¤r tillfälligt otillgänglig
+$ EINPROGRESS
+36 Operationen Ã¤r igÃ¥ng
+$ EALREADY
+37 Operationen Ã¤r redan igÃ¥ng
+$ ENOTSOCK
+38 Sockeloperation pÃ¥ icke-sockel
+$ EDESTADDRREQ
+39 Destinationsadress erfordras
+$ EMSGSIZE
+40 För lÃ¥ngt meddelande
+$ EPROTOTYPE
+41 Fel protokolltyp för sockeln
+$ ENOPROTOOPT
+42 Protokollet otillgängligt
+$ EPROTONOSUPPORT
+43 Protokollet Ã¤r ej understött
+$ ESOCKTNOSUPPORT
+44 Sockeltypen Ã¤r ej understödd
+$ EOPNOTSUPP
+45 Operationen Ã¤r ej understödd
+$ EPFNOSUPPORT
+46 Protokollfamiljen Ã¤r ej understödd
+$ EAFNOSUPPORT
+47 Adressfamiljen Ã¤r ej understödd av protokollfamiljen
+$ EADDRINUSE
+48 Adressen Ã¤r upptagen
+$ EADDRNOTAVAIL
+49 Kan ej tilldela den begärda adressen
+$ ENETDOWN
+50 Nätverket fungerar inte
+$ ENETUNREACH
+51 Nätverket Ã¤r ej kontaktbart
+$ ENETRESET
+52 Nätverket tappade kontakten vid Ã¥terställningen
+$ ECONNABORTED
+53 Mjukvara orsakade nedkoppling
+$ ECONNRESET
+54 Motparten avbröt uppkopplingen
+$ ENOBUFS
+55 Inget buffertutrymme tillgängligt
+$ EISCONN
+56 Sockeln Ã¤r redan uppkopplad
+$ ENOTCONN
+57 Sockeln Ã¤r ej uppkopplad
+$ ESHUTDOWN
+58 Kan ej sända efter att sockeln nedkopplats
+$ ETOOMANYREFS
+59 För mÃ¥nga referenser: kan inte delas
+$ ETIMEDOUT
+60 Uppkopplingstiden tog slut
+$ ECONNREFUSED
+61 Uppkopplingen nekad
+$ ELOOP
+62 För mÃ¥nga nivÃ¥er av symboliska länkar
+$ ENAMETOOLONG
+63 Alldeles för lÃ¥ngt filnamn
+$ EHOSTDOWN
+64 Värddatorn Ã¤r nere
+$ EHOSTUNREACH
+65 Väg till värddatorn saknas
+$ ENOTEMPTY
+66 Katalogen ej tom
+$ EPROCLIM
+67 För mÃ¥nga processer
+$ EUSERS
+68 För mÃ¥nga användare
+$ EDQUOT
+69 Diskkvot Ã¶verskriden
+$ ESTALE
+70 Inaktuellt NFS-filhandtag
+$ EREMOTE
+71 För mÃ¥nga fjärrnivÃ¥er i sökvägen
+$ EBADRPC
+72 Felaktig RPC-struktur
+$ ERPCMISMATCH
+73 Felaktig RPC-version
+$ EPROGUNAVAIL
+74 RPC-programmet otillgängligt
+$ EPROGMISMATCH
+75 Fel programversion
+$ EPROCUNAVAIL
+76 Felaktig procedur för programmet
+$ ENOLCK
+77 Inga lÃ¥s tillgängliga
+$ ENOSYS
+78 Funktionen Ã¤r ej implementerad
+$ EFTYPE
+79 Olämplig filtyp eller format
+$set 2
+$ SIGHUP
+1 Lägg pÃ¥
+$ SIGINT
+2 Avbryt
+$ SIGQUIT
+3 Avsluta
+$ SIGILL
+4 Olaglig instruktion
+$ SIGTRAP
+5 SpÃ¥r- eller brytpunktsfälla
+$ SIGABRT
+6 Avslutsfälla
+$ SIGEMT
+7 Emuleringsfälla
+$ SIGFPE
+8 Flyttalsavbrott
+$ SIGKILL
+9 Dräpt
+$ SIGBUS
+10 Bussfel
+$ SIGSEGV
+11 Segmentfel
+$ SIGSYS
+12 Felaktigt systemanrop
+$ SIGPIPE
+13 Avbruten kommunikationskanal
+$ SIGALRM
+14 Ã„ggklocka
+$ SIGTERM
+15 Terminerad
+$ SIGURG
+16 BrÃ¥dskande In/Ut-tillstÃ¥nd
+$ SIGSTOP
+17 Stoppad (signal)
+$ SIGTSTP
+18 Stoppad
+$ SIGCONT
+19 Fortsätter
+$ SIGCHLD
+20 Barn avslutat
+$ SIGTTIN
+21 Stoppad (terminalinmatning)
+$ SIGTTOU
+22 Stoppad (terminalutmatning)
+$ SIGIO
+23 In- och utmatning möjlig
+$ SIGXCPU
+24 Cputidsgränsen Ã¶verskriden
+$ SIGXFSZ
+25 Filstorleksgränsen Ã¶verskriden
+$ SIGVTALRM
+26 Virtuella Ã¤ggklockan ringde
+$ SIGPROF
+27 Profileringsäggklockan ringde
+$ SIGWINCH
+28 Fönsterstorleken Ã¤ndras
+$ SIGINFO
+29 InformationsförfrÃ¥gan
+$ SIGUSR1
+30 Användardefinierad signal 1
+$ SIGUSR2
+31 Användardefinierad signal 2
+$ SIGPWR
+32 Kraftbortfall/omstart
diff --git a/lib/nbsd_libc/quad/Makefile.inc b/lib/nbsd_libc/quad/Makefile.inc
new file mode 100644 (file)
index 0000000..62e53c1
--- /dev/null
@@ -0,0 +1,23 @@
+#      $NetBSD: Makefile.inc,v 1.11 2009/12/06 05:34:42 uebayasi Exp $
+#      @(#)Makefile.inc        8.1 (Berkeley) 6/4/93
+
+# Quad support
+SRCS.quad=     cmpdi2.c divdi3.c fixdfdi.c fixsfdi.c fixunsdfdi.c \
+       fixunssfdi.c floatdidf.c floatdisf.c floatunsdidf.c \
+       moddi3.c muldi3.c negdi2.c qdivrem.c \
+       ucmpdi2.c udivdi3.c umoddi3.c 
+
+.if   (${MACHINE_ARCH} == "m68k")
+SRCS.quad+=    ashldi3.S ashrdi3.S lshrdi3.S
+.elif (${MACHINE_ARCH} == "m68000")
+SRCS.quad+=    ashldi3.S lshrdi3.S
+.else
+SRCS.quad+=    ashldi3.c ashrdi3.c lshrdi3.c
+.endif
+
+# XXX as far as I can tell, these are never used and can be removed
+SRCS.quad+=    adddi3.c anddi3.c iordi3.c notdi2.c subdi3.c xordi3.c
+
+SRCS+= ${SRCS.quad}
+
+.PATH: ${ARCHDIR}/quad ${.CURDIR}/quad
diff --git a/lib/nbsd_libc/quad/TESTS/Makefile b/lib/nbsd_libc/quad/TESTS/Makefile
new file mode 100644 (file)
index 0000000..decf428
--- /dev/null
@@ -0,0 +1,12 @@
+#      $NetBSD: Makefile,v 1.2 1995/02/27 17:31:26 cgd Exp $
+#      @(#)Makefile    8.1 (Berkeley) 6/4/93
+
+all: mul divrem
+
+MUL=   mul.c ../muldi3.c
+mul: ${MUL}
+       gcc -g -DSPARC_XXX ${MUL} -o $@
+
+DIVREM=        divrem.c ../qdivrem.c
+divrem: ${DIVREM}
+       gcc -g -DSPARC_XXX ${DIVREM} -o $@
diff --git a/lib/nbsd_libc/quad/TESTS/divrem.c b/lib/nbsd_libc/quad/TESTS/divrem.c
new file mode 100644 (file)
index 0000000..7c2139d
--- /dev/null
@@ -0,0 +1,80 @@
+/*     $NetBSD: divrem.c,v 1.4 2003/08/07 16:43:18 agc Exp $   */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#ifndef lint
+static char copyright[] =
+"@(#) Copyright (c) 1992, 1993\n\
+       The Regents of the University of California.  All rights reserved.\n";
+#endif /* not lint */
+
+#ifndef lint
+#if 0
+static char sccsid[] = "@(#)divrem.c   8.1 (Berkeley) 6/4/93";
+#else
+static char rcsid[] = "$NetBSD: divrem.c,v 1.4 2003/08/07 16:43:18 agc Exp $";
+#endif
+#endif /* not lint */
+
+#include <stdio.h>
+
+main()
+{
+       union { long long q; unsigned int v[2]; } a, b, q, r;
+       char buf[300];
+       extern long long __qdivrem(unsigned long long, unsigned long long,
+           unsigned long long *);
+
+       for (;;) {
+               printf("> ");
+               if (fgets(buf, sizeof buf, stdin) == NULL)
+                       break;
+               if (sscanf(buf, "%u:%u %u:%u",
+                           &a.v[0], &a.v[1], &b.v[0], &b.v[1]) != 4 &&
+                   sscanf(buf, "0x%x:%x 0x%x:%x",
+                           &a.v[0], &a.v[1], &b.v[0], &b.v[1]) != 4) {
+                       printf("eh?\n");
+                       continue;
+               }
+               q.q = __qdivrem(a.q, b.q, &r.q);
+               printf("%x:%x /%% %x:%x => q=%x:%x r=%x:%x\n",
+                   a.v[0], a.v[1], b.v[0], b.v[1],
+                   q.v[0], q.v[1], r.v[0], r.v[1]);
+               printf("  = %X%08X / %X%08X => %X%08X\n\
+  = %X%08X %% %X%08X => %X%08X\n",
+                   a.v[0], a.v[1], b.v[0], b.v[1], q.v[0], q.v[1],
+                   a.v[0], a.v[1], b.v[0], b.v[1], r.v[0], r.v[1]);
+       }
+       exit(0);
+}
diff --git a/lib/nbsd_libc/quad/TESTS/mul.c b/lib/nbsd_libc/quad/TESTS/mul.c
new file mode 100644 (file)
index 0000000..2826d7a
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: mul.c,v 1.4 2003/08/07 16:43:19 agc Exp $      */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#ifndef lint
+static char copyright[] =
+"@(#) Copyright (c) 1992, 1993\n\
+       The Regents of the University of California.  All rights reserved.\n";
+#endif /* not lint */
+
+#ifndef lint
+#if 0
+static char sccsid[] = "@(#)mul.c      8.1 (Berkeley) 6/4/93";
+#else
+static char rcsid[] = "$NetBSD: mul.c,v 1.4 2003/08/07 16:43:19 agc Exp $";
+#endif
+#endif /* not lint */
+
+#include <stdio.h>
+
+main()
+{
+       union { long long q; unsigned int v[2]; } a, b, m;
+       char buf[300];
+       extern long long __muldi3(long long, long long);
+
+       for (;;) {
+               printf("> ");
+               if (fgets(buf, sizeof buf, stdin) == NULL)
+                       break;
+               if (sscanf(buf, "%u:%u %u:%u",
+                           &a.v[0], &a.v[1], &b.v[0], &b.v[1]) != 4 &&
+                   sscanf(buf, "0x%x:%x 0x%x:%x",
+                           &a.v[0], &a.v[1], &b.v[0], &b.v[1]) != 4) {
+                       printf("eh?\n");
+                       continue;
+               }
+               m.q = __muldi3(a.q, b.q);
+               printf("%x:%x * %x:%x => %x:%x\n",
+                   a.v[0], a.v[1], b.v[0], b.v[1], m.v[0], m.v[1]);
+               printf("  = %X%08X * %X%08X => %X%08X\n",
+                   a.v[0], a.v[1], b.v[0], b.v[1], m.v[0], m.v[1]);
+       }
+       exit(0);
+}
diff --git a/lib/nbsd_libc/quad/fixdfdi.c b/lib/nbsd_libc/quad/fixdfdi.c
new file mode 100644 (file)
index 0000000..dd0f17f
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: fixdfdi.c,v 1.4 2003/08/07 16:43:16 agc Exp $  */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fixdfdi.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fixdfdi.c,v 1.4 2003/08/07 16:43:16 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Convert double to (signed) quad.
+ * We clamp anything that is out of range.
+ */
+quad_t
+__fixdfdi(x)
+       double x;
+{
+       if (x < 0)
+               if (x <= QUAD_MIN)
+                       return (QUAD_MIN);
+               else
+                       return ((quad_t)-(u_quad_t)-x);
+       else
+               if (x >= QUAD_MAX)
+                       return (QUAD_MAX);
+               else
+                       return ((quad_t)(u_quad_t)x);
+}
diff --git a/lib/nbsd_libc/quad/fixsfdi.c b/lib/nbsd_libc/quad/fixsfdi.c
new file mode 100644 (file)
index 0000000..56cc03e
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: fixsfdi.c,v 1.4 2003/08/07 16:43:16 agc Exp $  */
+
+/*-
+ * Copyright (c) 1992 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fixsfdi.c  5.1 (Berkeley) 7/7/92";
+#else
+__RCSID("$NetBSD: fixsfdi.c,v 1.4 2003/08/07 16:43:16 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Convert float to (signed) quad.
+ * We clamp anything that is out of range.
+ *
+ * N.B.: must use new ANSI syntax (sorry).
+ */
+quad_t
+__fixsfdi(float x)
+{
+       if (x < 0)
+               if (x <= QUAD_MIN)
+                       return (QUAD_MIN);
+               else
+                       return ((quad_t)-(u_quad_t)-x);
+       else
+               if (x >= QUAD_MAX)
+                       return (QUAD_MAX);
+               else
+                       return ((quad_t)(u_quad_t)x);
+}
diff --git a/lib/nbsd_libc/quad/fixunsdfdi.c b/lib/nbsd_libc/quad/fixunsdfdi.c
new file mode 100644 (file)
index 0000000..7db43a1
--- /dev/null
@@ -0,0 +1,83 @@
+/*     $NetBSD: fixunsdfdi.c,v 1.7 2003/08/07 16:43:16 agc Exp $       */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fixunsdfdi.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fixunsdfdi.c,v 1.7 2003/08/07 16:43:16 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+#define        ONE_FOURTH      ((int)1 << (INT_BITS - 2))
+#define        ONE_HALF        (ONE_FOURTH * 2.0)
+#define        ONE             (ONE_FOURTH * 4.0)
+
+/*
+ * Convert double to (unsigned) quad.
+ * Not sure what to do with negative numbers---for now, anything out
+ * of range becomes UQUAD_MAX.
+ */
+u_quad_t
+__fixunsdfdi(x)
+       double x;
+{
+       union uu t;
+       unsigned int tmp;
+
+       if (x < 0)
+               return (UQUAD_MAX);     /* ??? should be 0?  ERANGE??? */
+#ifdef notdef                          /* this falls afoul of a GCC bug */
+       if (x >= UQUAD_MAX)
+               return (UQUAD_MAX);
+#else                                  /* so we wire in 2^64-1 instead */
+       if (x >= 18446744073709551615.0)        /* XXX */
+               return (UQUAD_MAX);
+#endif
+       /*
+        * Now we know that 0 <= x <= 18446744073709549568.  The upper
+        * limit is one ulp less than 18446744073709551615 tested for above.
+        * Dividing this by 2^32 will *not* round irrespective of any
+        * rounding modes (except if the result is an IEEE denorm).
+        * Furthermore, the quotient will fit into a 32-bit integer.
+        */
+       tmp = x / ONE;
+       t.ul[L] = (unsigned int) (x - tmp * ONE);
+       t.ul[H] = tmp;
+       return (t.uq);
+}
diff --git a/lib/nbsd_libc/quad/fixunssfdi.c b/lib/nbsd_libc/quad/fixunssfdi.c
new file mode 100644 (file)
index 0000000..21cfc30
--- /dev/null
@@ -0,0 +1,103 @@
+/*     $NetBSD: fixunssfdi.c,v 1.6 2003/08/07 16:43:16 agc Exp $       */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fixunssfdi.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fixunssfdi.c,v 1.6 2003/08/07 16:43:16 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+#define        ONE_FOURTH      ((int)1 << (INT_BITS - 2))
+#define        ONE_HALF        (ONE_FOURTH * 2.0)
+#define        ONE             (ONE_FOURTH * 4.0)
+
+/*
+ * Convert float to (unsigned) quad.  We do most of our work in double,
+ * out of sheer paranoia.
+ *
+ * Not sure what to do with negative numbers---for now, anything out
+ * of range becomes UQUAD_MAX.
+ *
+ * N.B.: must use new ANSI syntax (sorry).
+ */
+u_quad_t
+__fixunssfdi(float f)
+{
+       double x, toppart;
+       union uu t;
+
+       if (f < 0)
+               return (UQUAD_MAX);     /* ??? should be 0?  ERANGE??? */
+#ifdef notdef                          /* this falls afoul of a GCC bug */
+       if (f >= UQUAD_MAX)
+               return (UQUAD_MAX);
+#else                                  /* so we wire in 2^64-1 instead */
+       if (f >= 18446744073709551615.0)        /* XXX */
+               return (UQUAD_MAX);
+#endif
+       x = f;
+       /*
+        * Get the upper part of the result.  Note that the divide
+        * may round up; we want to avoid this if possible, so we
+        * subtract `1/2' first.
+        */
+       toppart = (x - ONE_HALF) / ONE;
+       /*
+        * Now build a u_quad_t out of the top part.  The difference
+        * between x and this is the bottom part (this may introduce
+        * a few fuzzy bits, but what the heck).  With any luck this
+        * difference will be nonnegative: x should wind up in the
+        * range [0..UINT_MAX].  For paranoia, we assume [INT_MIN..
+        * 2*UINT_MAX] instead.
+        */
+       t.ul[H] = (unsigned int)toppart;
+       t.ul[L] = 0;
+       x -= (double)t.uq;
+       if (x < 0) {
+               t.ul[H]--;
+               x += UINT_MAX;
+       }
+       if (x > UINT_MAX) {
+               t.ul[H]++;
+               x -= UINT_MAX;
+       }
+       t.ul[L] = (u_int)x;
+       return (t.uq);
+}
diff --git a/lib/nbsd_libc/quad/floatdidf.c b/lib/nbsd_libc/quad/floatdidf.c
new file mode 100644 (file)
index 0000000..ff60cb9
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: floatdidf.c,v 1.6 2003/08/07 16:43:16 agc Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)floatdidf.c        8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: floatdidf.c,v 1.6 2003/08/07 16:43:16 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Convert (signed) quad to double.
+ */
+double
+__floatdidf(x)
+       quad_t x;
+{
+       double d;
+       union uu u;
+       int neg;
+
+       /*
+        * Get an unsigned number first, by negating if necessary.
+        */
+       if (x < 0)
+               u.q = -x, neg = 1;
+       else
+               u.q = x, neg = 0;
+
+       /*
+        * Now u.ul[H] has the factor of 2^32 (or whatever) and u.ul[L]
+        * has the units.  Ideally we could just set d, add INT_BITS to
+        * its exponent, and then add the units, but this is portable
+        * code and does not know how to get at an exponent.  Machine-
+        * specific code may be able to do this more efficiently.
+        */
+       d = (double)u.ul[H] * (((int)1 << (INT_BITS - 2)) * 4.0);
+       d += u.ul[L];
+
+       return (neg ? -d : d);
+}
diff --git a/lib/nbsd_libc/quad/floatdisf.c b/lib/nbsd_libc/quad/floatdisf.c
new file mode 100644 (file)
index 0000000..0802fb9
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: floatdisf.c,v 1.6 2003/08/07 16:43:16 agc Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)floatdisf.c        8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: floatdisf.c,v 1.6 2003/08/07 16:43:16 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Convert (signed) quad to float.
+ */
+float
+__floatdisf(x)
+       quad_t x;
+{
+       float f;
+       union uu u;
+       int neg;
+
+       /*
+        * Get an unsigned number first, by negating if necessary.
+        */
+       if (x < 0)
+               u.q = -x, neg = 1;
+       else
+               u.q = x, neg = 0;
+
+       /*
+        * Now u.ul[H] has the factor of 2^32 (or whatever) and u.ul[L]
+        * has the units.  Ideally we could just set f, add INT_BITS to
+        * its exponent, and then add the units, but this is portable
+        * code and does not know how to get at an exponent.  Machine-
+        * specific code may be able to do this more efficiently.
+        *
+        * Using double here may be excessive paranoia.
+        */
+       f = (double)u.ul[H] * (((int)1 << (INT_BITS - 2)) * 4.0);
+       f += u.ul[L];
+
+       return (neg ? -f : f);
+}
diff --git a/lib/nbsd_libc/quad/floatunsdidf.c b/lib/nbsd_libc/quad/floatunsdidf.c
new file mode 100644 (file)
index 0000000..17d8b6c
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: floatunsdidf.c,v 1.6 2003/08/07 16:43:16 agc Exp $     */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This software was developed by the Computer Systems Engineering group
+ * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
+ * contributed to Berkeley.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)floatunsdidf.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: floatunsdidf.c,v 1.6 2003/08/07 16:43:16 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "quad.h"
+
+/*
+ * Convert (unsigned) quad to double.
+ * This is exactly like floatdidf.c except that negatives never occur.
+ */
+double
+__floatunsdidf(x)
+       u_quad_t x;
+{
+       double d;
+       union uu u;
+
+       u.uq = x;
+       d = (double)u.ul[H] * (((int)1 << (INT_BITS - 2)) * 4.0);
+       d += u.ul[L];
+       return (d);
+}
diff --git a/lib/nbsd_libc/regex/COPYRIGHT b/lib/nbsd_libc/regex/COPYRIGHT
new file mode 100644 (file)
index 0000000..f7a8f20
--- /dev/null
@@ -0,0 +1,54 @@
+$NetBSD: COPYRIGHT,v 1.5 2003/08/07 16:43:19 agc Exp $
+
+Copyright 1992, 1993, 1994 Henry Spencer.  All rights reserved.
+This software is not subject to any license of the American Telephone
+and Telegraph Company or of the Regents of the University of California.
+
+Permission is granted to anyone to use this software for any purpose on
+any computer system, and to alter it and redistribute it, subject
+to the following restrictions:
+
+1. The author is not responsible for the consequences of use of this
+   software, no matter how awful, even if they arise from flaws in it.
+
+2. The origin of this software must not be misrepresented, either by
+   explicit claim or by omission.  Since few users ever read sources,
+   credits must appear in the documentation.
+
+3. Altered versions must be plainly marked as such, and must not be
+   misrepresented as being the original software.  Since few users
+   ever read sources, credits must appear in the documentation.
+
+4. This notice may not be removed or altered.
+
+=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+/*-
+ * Copyright (c) 1994
+ *     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.
+ * 3. 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.
+ *
+ *     @(#)COPYRIGHT   8.1 (Berkeley) 3/16/94
+ */
diff --git a/lib/nbsd_libc/regex/Makefile.inc b/lib/nbsd_libc/regex/Makefile.inc
new file mode 100644 (file)
index 0000000..4dd74cf
--- /dev/null
@@ -0,0 +1,14 @@
+#      $NetBSD: Makefile.inc,v 1.7 1997/11/14 02:04:46 mrg Exp $
+#      @(#)Makefile.inc        8.1 (Berkeley) 6/4/93
+
+# regex sources
+.PATH: ${.CURDIR}/regex
+
+CPPFLAGS+=-DPOSIX_MISTAKE
+
+SRCS+= regcomp.c regerror.c regexec.c regfree.c
+
+MAN+=  regex.3 re_format.7
+
+MLINKS+=regex.3 regcomp.3 regex.3 regexec.3 regex.3 regerror.3 \
+       regex.3 regfree.3
diff --git a/lib/nbsd_libc/regex/WHATSNEW b/lib/nbsd_libc/regex/WHATSNEW
new file mode 100644 (file)
index 0000000..93eb936
--- /dev/null
@@ -0,0 +1,95 @@
+#      $NetBSD: WHATSNEW,v 1.6 1995/02/27 13:28:25 cgd Exp $
+# @(#)WHATSNEW 8.3 (Berkeley) 3/18/94
+
+New in alpha3.4:  The complex bug alluded to below has been fixed (in a
+slightly kludgey temporary way that may hurt efficiency a bit; this is
+another "get it out the door for 4.4" release).  The tests at the end of
+the tests file have accordingly been uncommented.  The primary sign of
+the bug was that something like a?b matching ab matched b rather than ab.
+(The bug was essentially specific to this exact situation, else it would
+have shown up earlier.)
+
+New in alpha3.3:  The definition of word boundaries has been altered
+slightly, to more closely match the usual programming notion that "_"
+is an alphabetic.  Stuff used for pre-ANSI systems is now in a subdir,
+and the makefile no longer alludes to it in mysterious ways.  The
+makefile has generally been cleaned up some.  Fixes have been made
+(again!) so that the regression test will run without -DREDEBUG, at
+the cost of weaker checking.  A workaround for a bug in some folks'
+<assert.h> has been added.  And some more things have been added to
+tests, including a couple right at the end which are commented out
+because the code currently flunks them (complex bug; fix coming).
+Plus the usual minor cleanup.
+
+New in alpha3.2:  Assorted bits of cleanup and portability improvement
+(the development base is now a BSDI system using GCC instead of an ancient
+Sun system, and the newer compiler exposed some glitches).  Fix for a
+serious bug that affected REs using many [] (including REG_ICASE REs
+because of the way they are implemented), *sometimes*, depending on
+memory-allocation patterns.  The header-file prototypes no longer name
+the parameters, avoiding possible name conflicts.  The possibility that
+some clot has defined CHAR_MIN as (say) `-128' instead of `(-128)' is
+now handled gracefully.  "uchar" is no longer used as an internal type
+name (too many people have the same idea).  Still the same old lousy
+performance, alas.
+
+New in alpha3.1:  Basically nothing, this release is just a bookkeeping
+convenience.  Stay tuned.
+
+New in alpha3.0:  Performance is no better, alas, but some fixes have been
+made and some functionality has been added.  (This is basically the "get
+it out the door in time for 4.4" release.)  One bug fix:  regfree() didn't
+free the main internal structure (how embarrassing).  It is now possible
+to put NULs in either the RE or the target string, using (resp.) a new
+REG_PEND flag and the old REG_STARTEND flag.  The REG_NOSPEC flag to
+regcomp() makes all characters ordinary, so you can match a literal
+string easily (this will become more useful when performance improves!).
+There are now primitives to match beginnings and ends of words, although
+the syntax is disgusting and so is the implementation.  The REG_ATOI
+debugging interface has changed a bit.  And there has been considerable
+internal cleanup of various kinds.
+
+New in alpha2.3:  Split change list out of README, and moved flags notes
+into Makefile.  Macro-ized the name of regex(7) in regex(3), since it has
+to change for 4.4BSD.  Cleanup work in engine.c, and some new regression
+tests to catch tricky cases thereof.
+
+New in alpha2.2:  Out-of-date manpages updated.  Regerror() acquires two
+small extensions -- REG_ITOA and REG_ATOI -- which avoid debugging kludges
+in my own test program and might be useful to others for similar purposes.
+The regression test will now compile (and run) without REDEBUG.  The
+BRE \$ bug is fixed.  Most uses of "uchar" are gone; it's all chars now.
+Char/uchar parameters are now written int/unsigned, to avoid possible
+portability problems with unpromoted parameters.  Some unsigned casts have
+been introduced to minimize portability problems with shifting into sign
+bits.
+
+New in alpha2.1:  Lots of little stuff, cleanup and fixes.  The one big
+thing is that regex.h is now generated, using mkh, rather than being
+supplied in the distribution; due to circularities in dependencies,
+you have to build regex.h explicitly by "make h".  The two known bugs
+have been fixed (and the regression test now checks for them), as has a
+problem with assertions not being suppressed in the absence of REDEBUG.
+No performance work yet.
+
+New in alpha2:  Backslash-anything is an ordinary character, not an
+error (except, of course, for the handful of backslashed metacharacters
+in BREs), which should reduce script breakage.  The regression test
+checks *where* null strings are supposed to match, and has generally
+been tightened up somewhat.  Small bug fixes in parameter passing (not
+harmful, but technically errors) and some other areas.  Debugging
+invoked by defining REDEBUG rather than not defining NDEBUG.
+
+New in alpha+3:  full prototyping for internal routines, using a little
+helper program, mkh, which extracts prototypes given in stylized comments.
+More minor cleanup.  Buglet fix:  it's CHAR_BIT, not CHAR_BITS.  Simple
+pre-screening of input when a literal string is known to be part of the
+RE; this does wonders for performance.
+
+New in alpha+2:  minor bits of cleanup.  Notably, the number "32" for the
+word width isn't hardwired into regexec.c any more, the public header
+file prototypes the functions if __STDC__ is defined, and some small typos
+in the manpages have been fixed.
+
+New in alpha+1:  improvements to the manual pages, and an important
+extension, the REG_STARTEND option to regexec().
diff --git a/lib/nbsd_libc/regex/cclass.h b/lib/nbsd_libc/regex/cclass.h
new file mode 100644 (file)
index 0000000..3ab2ccb
--- /dev/null
@@ -0,0 +1,104 @@
+/*     $NetBSD: cclass.h,v 1.7 2003/08/07 16:43:19 agc Exp $   */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. 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.
+ *
+ *     @(#)cclass.h    8.3 (Berkeley) 3/20/94
+ */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994 Henry Spencer.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ *     @(#)cclass.h    8.3 (Berkeley) 3/20/94
+ */
+
+/* character-class table */
+static const struct cclass {
+       const char *name;
+       const char *chars;
+       const char *multis;
+} cclasses[] = {
+       { "alnum",      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
+0123456789",                           "" },
+       { "alpha",      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
+                                       "" },
+       { "blank",      " \t",          "" },
+       { "cntrl",      "\007\b\t\n\v\f\r\1\2\3\4\5\6\16\17\20\21\22\23\24\
+\25\26\27\30\31\32\33\34\35\36\37\177",        "" },
+       { "digit",      "0123456789",   "" },
+       { "graph",      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
+0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
+                                       "" },
+       { "lower",      "abcdefghijklmnopqrstuvwxyz",
+                                       "" },
+       { "print",      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
+0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ ",
+                                       "" },
+       { "punct",      "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
+                                       "" },
+       { "space",      "\t\n\v\f\r ",  "" },
+       { "upper",      "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
+                                       "" },
+       { "xdigit",     "0123456789ABCDEFabcdef",
+                                       "" },
+       { NULL,         0,              "" }
+};
diff --git a/lib/nbsd_libc/regex/cname.h b/lib/nbsd_libc/regex/cname.h
new file mode 100644 (file)
index 0000000..4b9ef39
--- /dev/null
@@ -0,0 +1,175 @@
+/*     $NetBSD: cname.h,v 1.7 2003/08/07 16:43:19 agc Exp $    */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. 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.
+ *
+ *     @(#)cname.h     8.3 (Berkeley) 3/20/94
+ */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994 Henry Spencer.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ *     @(#)cname.h     8.3 (Berkeley) 3/20/94
+ */
+
+/* character-name table */
+static const struct cname {
+       const char *name;
+       char code;
+} cnames[] = {
+       { "NUL",                        '\0' },
+       { "SOH",                        '\001' },
+       { "STX",                        '\002' },
+       { "ETX",                        '\003' },
+       { "EOT",                        '\004' },
+       { "ENQ",                        '\005' },
+       { "ACK",                        '\006' },
+       { "BEL",                        '\007' },
+       { "alert",                      '\007' },
+       { "BS",                         '\010' },
+       { "backspace",                  '\b' },
+       { "HT",                         '\011' },
+       { "tab",                        '\t' },
+       { "LF",                         '\012' },
+       { "newline",                    '\n' },
+       { "VT",                         '\013' },
+       { "vertical-tab",               '\v' },
+       { "FF",                         '\014' },
+       { "form-feed",                  '\f' },
+       { "CR",                         '\015' },
+       { "carriage-return",            '\r' },
+       { "SO",                         '\016' },
+       { "SI",                         '\017' },
+       { "DLE",                        '\020' },
+       { "DC1",                        '\021' },
+       { "DC2",                        '\022' },
+       { "DC3",                        '\023' },
+       { "DC4",                        '\024' },
+       { "NAK",                        '\025' },
+       { "SYN",                        '\026' },
+       { "ETB",                        '\027' },
+       { "CAN",                        '\030' },
+       { "EM",                         '\031' },
+       { "SUB",                        '\032' },
+       { "ESC",                        '\033' },
+       { "IS4",                        '\034' },
+       { "FS",                         '\034' },
+       { "IS3",                        '\035' },
+       { "GS",                         '\035' },
+       { "IS2",                        '\036' },
+       { "RS",                         '\036' },
+       { "IS1",                        '\037' },
+       { "US",                         '\037' },
+       { "space",                      ' ' },
+       { "exclamation-mark",           '!' },
+       { "quotation-mark",             '"' },
+       { "number-sign",                '#' },
+       { "dollar-sign",                '$' },
+       { "percent-sign",               '%' },
+       { "ampersand",                  '&' },
+       { "apostrophe",                 '\'' },
+       { "left-parenthesis",           '(' },
+       { "right-parenthesis",          ')' },
+       { "asterisk",                   '*' },
+       { "plus-sign",                  '+' },
+       { "comma",                      ',' },
+       { "hyphen",                     '-' },
+       { "hyphen-minus",               '-' },
+       { "period",                     '.' },
+       { "full-stop",                  '.' },
+       { "slash",                      '/' },
+       { "solidus",                    '/' },
+       { "zero",                       '0' },
+       { "one",                        '1' },
+       { "two",                        '2' },
+       { "three",                      '3' },
+       { "four",                       '4' },
+       { "five",                       '5' },
+       { "six",                        '6' },
+       { "seven",                      '7' },
+       { "eight",                      '8' },
+       { "nine",                       '9' },
+       { "colon",                      ':' },
+       { "semicolon",                  ';' },
+       { "less-than-sign",             '<' },
+       { "equals-sign",                '=' },
+       { "greater-than-sign",          '>' },
+       { "question-mark",              '?' },
+       { "commercial-at",              '@' },
+       { "left-square-bracket",        '[' },
+       { "backslash",                  '\\' },
+       { "reverse-solidus",            '\\' },
+       { "right-square-bracket",       ']' },
+       { "circumflex",                 '^' },
+       { "circumflex-accent",          '^' },
+       { "underscore",                 '_' },
+       { "low-line",                   '_' },
+       { "grave-accent",               '`' },
+       { "left-brace",                 '{' },
+       { "left-curly-bracket",         '{' },
+       { "vertical-line",              '|' },
+       { "right-brace",                '}' },
+       { "right-curly-bracket",        '}' },
+       { "tilde",                      '~' },
+       { "DEL",                        '\177' },
+       { NULL,                         0 },
+};
diff --git a/lib/nbsd_libc/regex/engine.c b/lib/nbsd_libc/regex/engine.c
new file mode 100644 (file)
index 0000000..f51ff9c
--- /dev/null
@@ -0,0 +1,1188 @@
+/*     $NetBSD: engine.c,v 1.22 2009/02/12 05:06:54 lukem Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. 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.
+ *
+ *     @(#)engine.c    8.5 (Berkeley) 3/20/94
+ */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994 Henry Spencer.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ *     @(#)engine.c    8.5 (Berkeley) 3/20/94
+ */
+
+/*
+ * The matching engine and friends.  This file is #included by regexec.c
+ * after suitable #defines of a variety of macros used herein, so that
+ * different state representations can be used without duplicating masses
+ * of code.
+ */
+
+#ifdef SNAMES
+#define        matcher smatcher
+#define        fast    sfast
+#define        slow    sslow
+#define        dissect sdissect
+#define        backref sbackref
+#define        step    sstep
+#define        print   sprint
+#define        at      sat
+#define        match   smat
+#define        nope    snope
+#endif
+#ifdef LNAMES
+#define        matcher lmatcher
+#define        fast    lfast
+#define        slow    lslow
+#define        dissect ldissect
+#define        backref lbackref
+#define        step    lstep
+#define        print   lprint
+#define        at      lat
+#define        match   lmat
+#define        nope    lnope
+#endif
+
+/* another structure passed up and down to avoid zillions of parameters */
+struct match {
+       struct re_guts *g;
+       int eflags;
+       regmatch_t *pmatch;     /* [nsub+1] (0 element unused) */
+       const char *offp;       /* offsets work from here */
+       const char *beginp;     /* start of string -- virtual NUL precedes */
+       const char *endp;       /* end of string -- virtual NUL here */
+       const char *coldp;      /* can be no match starting before here */
+       const char **lastpos;   /* [nplus+1] */
+       STATEVARS;
+       states st;              /* current states */
+       states fresh;           /* states for a fresh start */
+       states tmp;             /* temporary */
+       states empty;           /* empty set of states */
+};
+
+/* ========= begin header generated by ./mkh ========= */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* === engine.c === */
+static int matcher(struct re_guts *g, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags);
+static const char *dissect(struct match *m, const char *start, const char *stop, sopno startst, sopno stopst);
+static const char *backref(struct match *m, const char *start, const char *stop, sopno startst, sopno stopst, sopno lev);
+static const char *fast(struct match *m, const char *start, const char *stop, sopno startst, sopno stopst);
+static const char *slow(struct match *m, const char *start, const char *stop, sopno startst, sopno stopst);
+static states step(struct re_guts *g, sopno start, sopno stop, states bef, int ch, states aft);
+#define        BOL     (OUT+1)
+#define        EOL     (BOL+1)
+#define        BOLEOL  (BOL+2)
+#define        NOTHING (BOL+3)
+#define        BOW     (BOL+4)
+#define        EOW     (BOL+5)
+#define        CODEMAX (BOL+5)         /* highest code used */
+#define        NONCHAR(c)      ((c) > CHAR_MAX)
+#define        NNONCHAR        (CODEMAX-CHAR_MAX)
+#ifdef REDEBUG
+static void print(struct match *m, char *caption, states st, int ch, FILE *d);
+#endif
+#ifdef REDEBUG
+static void at(struct match *m, char *title, char *start, char *stop, sopno startst, sopno stopst);
+#endif
+#ifdef REDEBUG
+static char *pchar(int ch);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+/* ========= end header generated by ./mkh ========= */
+
+#ifdef REDEBUG
+#define        SP(t, s, c)     print(m, t, s, c, stdout)
+#define        AT(t, p1, p2, s1, s2)   at(m, t, p1, p2, s1, s2)
+#define        NOTE(str)       { if (m->eflags&REG_TRACE) printf("=%s\n", (str)); }
+static int nope = 0;
+#else
+#define        SP(t, s, c)     /* nothing */
+#define        AT(t, p1, p2, s1, s2)   /* nothing */
+#define        NOTE(s) /* nothing */
+#endif
+
+/*
+ - matcher - the actual matching engine
+ == static int matcher(struct re_guts *g, char *string, \
+ ==    size_t nmatch, regmatch_t pmatch[], int eflags);
+ */
+static int                     /* 0 success, REG_NOMATCH failure */
+matcher(
+    struct re_guts *g,
+    const char *string,
+    size_t nmatch,
+    regmatch_t pmatch[],
+    int eflags)
+{
+       const char *endp;
+       size_t i;
+       struct match mv;
+       struct match *m = &mv;
+       const char *dp;
+       const sopno gf = g->firststate+1;       /* +1 for OEND */
+       const sopno gl = g->laststate;
+       const char *start;
+       const char *stop;
+       int error = 0;
+
+       _DIAGASSERT(g != NULL);
+       _DIAGASSERT(string != NULL);
+       /* pmatch checked below */
+
+       /* simplify the situation where possible */
+       if (g->cflags&REG_NOSUB)
+               nmatch = 0;
+       if (eflags&REG_STARTEND) {
+               _DIAGASSERT(pmatch != NULL);
+               start = string + (size_t)pmatch[0].rm_so;
+               stop = string + (size_t)pmatch[0].rm_eo;
+       } else {
+               start = string;
+               stop = start + strlen(start);
+       }
+       if (stop < start)
+               return(REG_INVARG);
+
+       /* prescreening; this does wonders for this rather slow code */
+       if (g->must != NULL) {
+               for (dp = start; dp < stop; dp++)
+                       if (*dp == g->must[0] && stop - dp >= g->mlen &&
+                               memcmp(dp, g->must, (size_t)g->mlen) == 0)
+                               break;
+               if (dp == stop)         /* we didn't find g->must */
+                       return(REG_NOMATCH);
+       }
+
+       /* match struct setup */
+       m->g = g;
+       m->eflags = eflags;
+       m->pmatch = NULL;
+       m->lastpos = NULL;
+       m->offp = string;
+       m->beginp = start;
+       m->endp = stop;
+       STATESETUP(m, 4);
+       SETUP(m->st);
+       SETUP(m->fresh);
+       SETUP(m->tmp);
+       SETUP(m->empty);
+       CLEAR(m->empty);
+
+       /* this loop does only one repetition except for backrefs */
+       for (;;) {
+               endp = fast(m, start, stop, gf, gl);
+               if (endp == NULL) {             /* a miss */
+                       error = REG_NOMATCH;
+                       goto done;
+               }
+               if (nmatch == 0 && !g->backrefs)
+                       break;          /* no further info needed */
+
+               /* where? */
+               assert(m->coldp != NULL);
+               for (;;) {
+                       NOTE("finding start");
+                       endp = slow(m, m->coldp, stop, gf, gl);
+                       if (endp != NULL)
+                               break;
+                       assert(m->coldp < m->endp);
+                       m->coldp++;
+               }
+               if (nmatch == 1 && !g->backrefs)
+                       break;          /* no further info needed */
+
+               /* oh my, he wants the subexpressions... */
+               if (m->pmatch == NULL)
+                       m->pmatch = (regmatch_t *)malloc((m->g->nsub + 1) *
+                                                       sizeof(regmatch_t));
+               if (m->pmatch == NULL) {
+                       error = REG_ESPACE;
+                       goto done;
+               }
+               for (i = 1; i <= m->g->nsub; i++)
+                       m->pmatch[i].rm_so = m->pmatch[i].rm_eo = (regoff_t)-1;
+               if (!g->backrefs && !(m->eflags&REG_BACKR)) {
+                       NOTE("dissecting");
+                       dp = dissect(m, m->coldp, endp, gf, gl);
+               } else {
+                       if (g->nplus > 0 && m->lastpos == NULL)
+                               m->lastpos = malloc((g->nplus+1) *
+                                                       sizeof(const char *));
+                       if (g->nplus > 0 && m->lastpos == NULL) {
+                               error = REG_ESPACE;
+                               goto done;
+                       }
+                       NOTE("backref dissect");
+                       dp = backref(m, m->coldp, endp, gf, gl, (sopno)0);
+               }
+               if (dp != NULL)
+                       break;
+
+               /* uh-oh... we couldn't find a subexpression-level match */
+               assert(g->backrefs);    /* must be back references doing it */
+               assert(g->nplus == 0 || m->lastpos != NULL);
+               for (;;) {
+                       if (dp != NULL || endp <= m->coldp)
+                               break;          /* defeat */
+                       NOTE("backoff");
+                       endp = slow(m, m->coldp, endp-1, gf, gl);
+                       if (endp == NULL)
+                               break;          /* defeat */
+                       /* try it on a shorter possibility */
+#ifndef NDEBUG
+                       for (i = 1; i <= m->g->nsub; i++) {
+                               assert(m->pmatch[i].rm_so == (regoff_t)-1);
+                               assert(m->pmatch[i].rm_eo == (regoff_t)-1);
+                       }
+#endif
+                       NOTE("backoff dissect");
+                       dp = backref(m, m->coldp, endp, gf, gl, (sopno)0);
+               }
+               assert(dp == NULL || dp == endp);
+               if (dp != NULL)         /* found a shorter one */
+                       break;
+
+               /* despite initial appearances, there is no match here */
+               NOTE("false alarm");
+               start = m->coldp + 1;   /* recycle starting later */
+               assert(start <= stop);
+       }
+
+       /* fill in the details if requested */
+       if (nmatch > 0) {
+               _DIAGASSERT(pmatch != NULL);
+               pmatch[0].rm_so = m->coldp - m->offp;
+               pmatch[0].rm_eo = endp - m->offp;
+       }
+       if (nmatch > 1) {
+               assert(m->pmatch != NULL);
+               for (i = 1; i < nmatch; i++)
+                       if (i <= m->g->nsub)
+                               pmatch[i] = m->pmatch[i];
+                       else {
+                               pmatch[i].rm_so = (regoff_t)-1;
+                               pmatch[i].rm_eo = (regoff_t)-1;
+                       }
+       }
+
+done:
+       if (m->pmatch != NULL) {
+               free(m->pmatch);
+               m->pmatch = NULL;
+       }
+       if (m->lastpos != NULL) {
+               free(m->lastpos);
+               m->lastpos = NULL;
+       }
+       STATETEARDOWN(m);
+       return error;
+}
+
+/*
+ - dissect - figure out what matched what, no back references
+ == static const char *dissect(struct match *m, const char *start, \
+ ==    const char *stop, sopno startst, sopno stopst);
+ */
+static const char *                    /* == stop (success) always */
+dissect(
+    struct match *m,
+    const char *start,
+    const char *stop,
+    sopno startst,
+    sopno stopst)
+{
+       int i;
+       sopno ss;       /* start sop of current subRE */
+       sopno es;       /* end sop of current subRE */
+       const char *sp; /* start of string matched by it */
+       const char *stp; /* string matched by it cannot pass here */
+       const char *rest; /* start of rest of string */
+       const char *tail; /* string unmatched by rest of RE */
+       sopno ssub;     /* start sop of subsubRE */
+       sopno esub;     /* end sop of subsubRE */
+       const char *ssp; /* start of string matched by subsubRE */
+       const char *sep; /* end of string matched by subsubRE */
+       const char *oldssp; /* previous ssp */
+#ifndef NDEBUG
+       const char *dp;
+#endif
+
+       _DIAGASSERT(m != NULL);
+       _DIAGASSERT(start != NULL);
+       _DIAGASSERT(stop != NULL);
+
+       AT("diss", start, stop, startst, stopst);
+       sp = start;
+       for (ss = startst; ss < stopst; ss = es) {
+               /* identify end of subRE */
+               es = ss;
+               switch (OP(m->g->strip[es])) {
+               case OPLUS_:
+               case OQUEST_:
+                       es += OPND(m->g->strip[es]);
+                       break;
+               case OCH_:
+                       while (OP(m->g->strip[es]) != O_CH)
+                               es += OPND(m->g->strip[es]);
+                       break;
+               }
+               es++;
+
+               /* figure out what it matched */
+               switch (OP(m->g->strip[ss])) {
+               case OEND:
+                       assert(nope);
+                       break;
+               case OCHAR:
+                       sp++;
+                       break;
+               case OBOL:
+               case OEOL:
+               case OBOW:
+               case OEOW:
+                       break;
+               case OANY:
+               case OANYOF:
+                       sp++;
+                       break;
+               case OBACK_:
+               case O_BACK:
+                       assert(nope);
+                       break;
+               /* cases where length of match is hard to find */
+               case OQUEST_:
+                       stp = stop;
+                       for (;;) {
+                               /* how long could this one be? */
+                               rest = slow(m, sp, stp, ss, es);
+                               assert(rest != NULL);   /* it did match */
+                               /* could the rest match the rest? */
+                               tail = slow(m, rest, stop, es, stopst);
+                               if (tail == stop)
+                                       break;          /* yes! */
+                               /* no -- try a shorter match for this one */
+                               stp = rest - 1;
+                               assert(stp >= sp);      /* it did work */
+                       }
+                       ssub = ss + 1;
+                       esub = es - 1;
+                       /* did innards match? */
+                       if (slow(m, sp, rest, ssub, esub) != NULL) {
+#ifdef NDEBUG
+                               (void)
+#else
+                               dp = 
+#endif
+                                   dissect(m, sp, rest, ssub, esub);
+                               assert(dp == rest);
+                       } else          /* no */
+                               assert(sp == rest);
+                       sp = rest;
+                       break;
+               case OPLUS_:
+                       stp = stop;
+                       for (;;) {
+                               /* how long could this one be? */
+                               rest = slow(m, sp, stp, ss, es);
+                               assert(rest != NULL);   /* it did match */
+                               /* could the rest match the rest? */
+                               tail = slow(m, rest, stop, es, stopst);
+                               if (tail == stop)
+                                       break;          /* yes! */
+                               /* no -- try a shorter match for this one */
+                               stp = rest - 1;
+                               assert(stp >= sp);      /* it did work */
+                       }
+                       ssub = ss + 1;
+                       esub = es - 1;
+                       ssp = sp;
+                       oldssp = ssp;
+                       for (;;) {      /* find last match of innards */
+                               sep = slow(m, ssp, rest, ssub, esub);
+                               if (sep == NULL || sep == ssp)
+                                       break;  /* failed or matched null */
+                               oldssp = ssp;   /* on to next try */
+                               ssp = sep;
+                       }
+                       if (sep == NULL) {
+                               /* last successful match */
+                               sep = ssp;
+                               ssp = oldssp;
+                       }
+                       assert(sep == rest);    /* must exhaust substring */
+                       assert(slow(m, ssp, sep, ssub, esub) == rest);
+#ifdef NDEBUG
+                       (void)
+#else
+                       dp =
+#endif
+                           dissect(m, ssp, sep, ssub, esub);
+                       assert(dp == sep);
+                       sp = rest;
+                       break;
+               case OCH_:
+                       stp = stop;
+                       for (;;) {
+                               /* how long could this one be? */
+                               rest = slow(m, sp, stp, ss, es);
+                               assert(rest != NULL);   /* it did match */
+                               /* could the rest match the rest? */
+                               tail = slow(m, rest, stop, es, stopst);
+                               if (tail == stop)
+                                       break;          /* yes! */
+                               /* no -- try a shorter match for this one */
+                               stp = rest - 1;
+                               assert(stp >= sp);      /* it did work */
+                       }
+                       ssub = ss + 1;
+                       esub = ss + OPND(m->g->strip[ss]) - 1;
+                       assert(OP(m->g->strip[esub]) == OOR1);
+                       for (;;) {      /* find first matching branch */
+                               if (slow(m, sp, rest, ssub, esub) == rest)
+                                       break;  /* it matched all of it */
+                               /* that one missed, try next one */
+                               assert(OP(m->g->strip[esub]) == OOR1);
+                               esub++;
+                               assert(OP(m->g->strip[esub]) == OOR2);
+                               ssub = esub + 1;
+                               esub += OPND(m->g->strip[esub]);
+                               if (OP(m->g->strip[esub]) == OOR2)
+                                       esub--;
+                               else
+                                       assert(OP(m->g->strip[esub]) == O_CH);
+                       }
+#ifdef NDEBUG
+                       (void)
+#else
+                       dp =
+#endif
+                           dissect(m, sp, rest, ssub, esub);
+                       assert(dp == rest);
+                       sp = rest;
+                       break;
+               case O_PLUS:
+               case O_QUEST:
+               case OOR1:
+               case OOR2:
+               case O_CH:
+                       assert(nope);
+                       break;
+               case OLPAREN:
+                       i = OPND(m->g->strip[ss]);
+                       assert(0 < i && i <= m->g->nsub);
+                       m->pmatch[i].rm_so = sp - m->offp;
+                       break;
+               case ORPAREN:
+                       i = OPND(m->g->strip[ss]);
+                       assert(0 < i && i <= m->g->nsub);
+                       m->pmatch[i].rm_eo = sp - m->offp;
+                       break;
+               default:                /* uh oh */
+                       assert(nope);
+                       break;
+               }
+       }
+
+       assert(sp == stop);
+       return(sp);
+}
+
+/*
+ - backref - figure out what matched what, figuring in back references
+ == static const char *backref(struct match *m, const char *start, \
+ ==    const char *stop, sopno startst, sopno stopst, sopno lev);
+ */
+static const char *            /* == stop (success) or NULL (failure) */
+backref(
+    struct match *m,
+    const char *start,
+    const char *stop,
+    sopno startst,
+    sopno stopst,
+    sopno lev)                 /* PLUS nesting level */
+{
+       int i;
+       sopno ss;       /* start sop of current subRE */
+       const char *sp; /* start of string matched by it */
+       sopno ssub;     /* start sop of subsubRE */
+       sopno esub;     /* end sop of subsubRE */
+       const char *ssp; /* start of string matched by subsubRE */
+       const char *dp;
+       size_t len;
+       int hard;
+       sop s;
+       regoff_t offsave;
+       cset *cs;
+
+       _DIAGASSERT(m != NULL);
+       _DIAGASSERT(start != NULL);
+       _DIAGASSERT(stop != NULL);
+
+       AT("back", start, stop, startst, stopst);
+       sp = start;
+
+       /* get as far as we can with easy stuff */
+       hard = 0;
+       for (ss = startst; !hard && ss < stopst; ss++)
+               switch (OP(s = m->g->strip[ss])) {
+               case OCHAR:
+                       if (sp == stop || *sp++ != (char)OPND(s))
+                               return(NULL);
+                       break;
+               case OANY:
+                       if (sp == stop)
+                               return(NULL);
+                       sp++;
+                       break;
+               case OANYOF:
+                       cs = &m->g->sets[OPND(s)];
+                       if (sp == stop || !CHIN(cs, *sp++))
+                               return(NULL);
+                       break;
+               case OBOL:
+                       if ( (sp == m->beginp && !(m->eflags&REG_NOTBOL)) ||
+                                       (sp < m->endp && *(sp-1) == '\n' &&
+                                               (m->g->cflags&REG_NEWLINE)) )
+                               { /* yes */ }
+                       else
+                               return(NULL);
+                       break;
+               case OEOL:
+                       if ( (sp == m->endp && !(m->eflags&REG_NOTEOL)) ||
+                                       (sp < m->endp && *sp == '\n' &&
+                                               (m->g->cflags&REG_NEWLINE)) )
+                               { /* yes */ }
+                       else
+                               return(NULL);
+                       break;
+               case OBOW:
+                       if (( (sp == m->beginp && !(m->eflags&REG_NOTBOL)) ||
+                                       (sp < m->endp && *(sp-1) == '\n' &&
+                                               (m->g->cflags&REG_NEWLINE)) ||
+                                       (sp > m->beginp &&
+                                                       !ISWORD(*(sp-1))) ) &&
+                                       (sp < m->endp && ISWORD(*sp)) )
+                               { /* yes */ }
+                       else
+                               return(NULL);
+                       break;
+               case OEOW:
+                       if (( (sp == m->endp && !(m->eflags&REG_NOTEOL)) ||
+                                       (sp < m->endp && *sp == '\n' &&
+                                               (m->g->cflags&REG_NEWLINE)) ||
+                                       (sp < m->endp && !ISWORD(*sp)) ) &&
+                                       (sp > m->beginp && ISWORD(*(sp-1))) )
+                               { /* yes */ }
+                       else
+                               return(NULL);
+                       break;
+               case O_QUEST:
+                       break;
+               case OOR1:      /* matches null but needs to skip */
+                       ss++;
+                       s = m->g->strip[ss];
+                       do {
+                               assert(OP(s) == OOR2);
+                               ss += OPND(s);
+                       } while (OP(s = m->g->strip[ss]) != O_CH);
+                       /* note that the ss++ gets us past the O_CH */
+                       break;
+               default:        /* have to make a choice */
+                       hard = 1;
+                       break;
+               }
+       if (!hard) {            /* that was it! */
+               if (sp != stop)
+                       return(NULL);
+               return(sp);
+       }
+       ss--;                   /* adjust for the for's final increment */
+
+       /* the hard stuff */
+       AT("hard", sp, stop, ss, stopst);
+       s = m->g->strip[ss];
+       switch (OP(s)) {
+       case OBACK_:            /* the vilest depths */
+               i = OPND(s);
+               assert(0 < i && i <= m->g->nsub);
+               if (m->pmatch[i].rm_eo == (regoff_t)-1)
+                       return(NULL);
+               assert(m->pmatch[i].rm_so != (regoff_t)-1);
+               len = (size_t)(m->pmatch[i].rm_eo - m->pmatch[i].rm_so);
+               if (len == 0)
+                       return(NULL);
+               assert(stop - m->beginp >= len);
+               if (sp > stop - len)
+                       return(NULL);   /* not enough left to match */
+               ssp = m->offp + (size_t)m->pmatch[i].rm_so;
+               if (memcmp(sp, ssp, len) != 0)
+                       return(NULL);
+               while (m->g->strip[ss] != SOP(O_BACK, i))
+                       ss++;
+               return(backref(m, sp+len, stop, ss+1, stopst, lev));
+
+       case OQUEST_:           /* to null or not */
+               dp = backref(m, sp, stop, ss+1, stopst, lev);
+               if (dp != NULL)
+                       return(dp);     /* not */
+               return(backref(m, sp, stop, ss+OPND(s)+1, stopst, lev));
+
+       case OPLUS_:
+               assert(m->lastpos != NULL);
+               assert(lev+1 <= m->g->nplus);
+               m->lastpos[lev+1] = sp;
+               return(backref(m, sp, stop, ss+1, stopst, lev+1));
+
+       case O_PLUS:
+               if (sp == m->lastpos[lev])      /* last pass matched null */
+                       return(backref(m, sp, stop, ss+1, stopst, lev-1));
+               /* try another pass */
+               m->lastpos[lev] = sp;
+               dp = backref(m, sp, stop, ss-OPND(s)+1, stopst, lev);
+               if (dp == NULL)
+                       dp = backref(m, sp, stop, ss+1, stopst, lev-1);
+               return(dp);
+
+       case OCH_:              /* find the right one, if any */
+               ssub = ss + 1;
+               esub = ss + OPND(s) - 1;
+               assert(OP(m->g->strip[esub]) == OOR1);
+               for (;;) {      /* find first matching branch */
+                       dp = backref(m, sp, stop, ssub, esub, lev);
+                       if (dp != NULL)
+                               return(dp);
+                       /* that one missed, try next one */
+                       if (OP(m->g->strip[esub]) == O_CH)
+                               return(NULL);   /* there is none */
+                       esub++;
+                       assert(OP(m->g->strip[esub]) == OOR2);
+                       ssub = esub + 1;
+                       esub += OPND(m->g->strip[esub]);
+                       if (OP(m->g->strip[esub]) == OOR2)
+                               esub--;
+                       else
+                               assert(OP(m->g->strip[esub]) == O_CH);
+               }
+
+       case OLPAREN:           /* must undo assignment if rest fails */
+               i = OPND(s);
+               assert(0 < i && i <= m->g->nsub);
+               offsave = m->pmatch[i].rm_so;
+               m->pmatch[i].rm_so = sp - m->offp;
+               dp = backref(m, sp, stop, ss+1, stopst, lev);
+               if (dp != NULL)
+                       return(dp);
+               m->pmatch[i].rm_so = offsave;
+               return(NULL);
+
+       case ORPAREN:           /* must undo assignment if rest fails */
+               i = OPND(s);
+               assert(0 < i && i <= m->g->nsub);
+               offsave = m->pmatch[i].rm_eo;
+               m->pmatch[i].rm_eo = sp - m->offp;
+               dp = backref(m, sp, stop, ss+1, stopst, lev);
+               if (dp != NULL)
+                       return(dp);
+               m->pmatch[i].rm_eo = offsave;
+               return(NULL);
+
+       default:                /* uh oh */
+               assert(nope);
+               break;
+       }
+
+       /* "can't happen" */
+       assert(nope);
+       /* NOTREACHED */
+       return NULL;
+}
+
+/*
+ - fast - step through the string at top speed
+ == static const char *fast(struct match *m, const char *start, \
+ ==    const char *stop, sopno startst, sopno stopst);
+ */
+static const char *            /* where tentative match ended, or NULL */
+fast(
+    struct match *m,
+    const char *start,
+    const char *stop,
+    sopno startst,
+    sopno stopst)
+{
+       states st = m->st;
+       states fresh = m->fresh;
+       states tmp = m->tmp;
+       const char *p = start;
+       int c = (start == m->beginp) ? OUT : *(start-1);
+       int lastc;      /* previous c */
+       int flagch;
+       int i;
+       const char *coldp; /* last p after which no match was underway */
+
+       _DIAGASSERT(m != NULL);
+       _DIAGASSERT(start != NULL);
+       _DIAGASSERT(stop != NULL);
+
+       CLEAR(st);
+       SET1(st, startst);
+       st = step(m->g, startst, stopst, st, NOTHING, st);
+       ASSIGN(fresh, st);
+       SP("start", st, *p);
+       coldp = NULL;
+       for (;;) {
+               /* next character */
+               lastc = c;
+               c = (p == m->endp) ? OUT : *p;
+               if (EQ(st, fresh))
+                       coldp = p;
+
+               /* is there an EOL and/or BOL between lastc and c? */
+               flagch = '\0';
+               i = 0;
+               if ( (lastc == '\n' && m->g->cflags&REG_NEWLINE) ||
+                               (lastc == OUT && !(m->eflags&REG_NOTBOL)) ) {
+                       flagch = BOL;
+                       i = m->g->nbol;
+               }
+               if ( (c == '\n' && m->g->cflags&REG_NEWLINE) ||
+                               (c == OUT && !(m->eflags&REG_NOTEOL)) ) {
+                       flagch = (flagch == BOL) ? BOLEOL : EOL;
+                       i += m->g->neol;
+               }
+               if (i != 0) {
+                       for (; i > 0; i--)
+                               st = step(m->g, startst, stopst, st, flagch, st);
+                       SP("boleol", st, c);
+               }
+
+               /* how about a word boundary? */
+               if ( (flagch == BOL || (lastc != OUT && !ISWORD(lastc))) &&
+                                       (c != OUT && ISWORD(c)) ) {
+                       flagch = BOW;
+               }
+               if ( (lastc != OUT && ISWORD(lastc)) &&
+                               (flagch == EOL || (c != OUT && !ISWORD(c))) ) {
+                       flagch = EOW;
+               }
+               if (flagch == BOW || flagch == EOW) {
+                       st = step(m->g, startst, stopst, st, flagch, st);
+                       SP("boweow", st, c);
+               }
+
+               /* are we done? */
+               if (ISSET(st, stopst) || p == stop)
+                       break;          /* NOTE BREAK OUT */
+
+               /* no, we must deal with this character */
+               ASSIGN(tmp, st);
+               ASSIGN(st, fresh);
+               assert(c != OUT);
+               st = step(m->g, startst, stopst, tmp, c, st);
+               SP("aft", st, c);
+               assert(EQ(step(m->g, startst, stopst, st, NOTHING, st), st));
+               p++;
+       }
+
+       assert(coldp != NULL);
+       m->coldp = coldp;
+       if (ISSET(st, stopst))
+               return(p+1);
+       else
+               return(NULL);
+}
+
+/*
+ - slow - step through the string more deliberately
+ == static const char *slow(struct match *m, const char *start, \
+ ==    const char *stop, sopno startst, sopno stopst);
+ */
+static const char *                    /* where it ended */
+slow(
+    struct match *m,
+    const char *start,
+    const char *stop,
+    sopno startst,
+    sopno stopst)
+{
+       states st = m->st;
+       states empty = m->empty;
+       states tmp = m->tmp;
+       const char *p = start;
+       int c = (start == m->beginp) ? OUT : *(start-1);
+       int lastc;      /* previous c */
+       int flagch;
+       int i;
+       const char *matchp;     /* last p at which a match ended */
+
+       _DIAGASSERT(m != NULL);
+       _DIAGASSERT(start != NULL);
+       _DIAGASSERT(stop != NULL);
+
+       AT("slow", start, stop, startst, stopst);
+       CLEAR(st);
+       SET1(st, startst);
+       SP("sstart", st, *p);
+       st = step(m->g, startst, stopst, st, NOTHING, st);
+       matchp = NULL;
+       for (;;) {
+               /* next character */
+               lastc = c;
+               c = (p == m->endp) ? OUT : *p;
+
+               /* is there an EOL and/or BOL between lastc and c? */
+               flagch = '\0';
+               i = 0;
+               if ( (lastc == '\n' && m->g->cflags&REG_NEWLINE) ||
+                               (lastc == OUT && !(m->eflags&REG_NOTBOL)) ) {
+                       flagch = BOL;
+                       i = m->g->nbol;
+               }
+               if ( (c == '\n' && m->g->cflags&REG_NEWLINE) ||
+                               (c == OUT && !(m->eflags&REG_NOTEOL)) ) {
+                       flagch = (flagch == BOL) ? BOLEOL : EOL;
+                       i += m->g->neol;
+               }
+               if (i != 0) {
+                       for (; i > 0; i--)
+                               st = step(m->g, startst, stopst, st, flagch, st);
+                       SP("sboleol", st, c);
+               }
+
+               /* how about a word boundary? */
+               if ( (flagch == BOL || (lastc != OUT && !ISWORD(lastc))) &&
+                                       (c != OUT && ISWORD(c)) ) {
+                       flagch = BOW;
+               }
+               if ( (lastc != OUT && ISWORD(lastc)) &&
+                               (flagch == EOL || (c != OUT && !ISWORD(c))) ) {
+                       flagch = EOW;
+               }
+               if (flagch == BOW || flagch == EOW) {
+                       st = step(m->g, startst, stopst, st, flagch, st);
+                       SP("sboweow", st, c);
+               }
+
+               /* are we done? */
+               if (ISSET(st, stopst))
+                       matchp = p;
+               if (EQ(st, empty) || p == stop)
+                       break;          /* NOTE BREAK OUT */
+
+               /* no, we must deal with this character */
+               ASSIGN(tmp, st);
+               ASSIGN(st, empty);
+               assert(c != OUT);
+               st = step(m->g, startst, stopst, tmp, c, st);
+               SP("saft", st, c);
+               assert(EQ(step(m->g, startst, stopst, st, NOTHING, st), st));
+               p++;
+       }
+
+       return(matchp);
+}
+
+
+/*
+ - step - map set of states reachable before char to set reachable after
+ == static states step(struct re_guts *g, sopno start, sopno stop, \
+ ==    states bef, int ch, states aft);
+ == #define    BOL     (OUT+1)
+ == #define    EOL     (BOL+1)
+ == #define    BOLEOL  (BOL+2)
+ == #define    NOTHING (BOL+3)
+ == #define    BOW     (BOL+4)
+ == #define    EOW     (BOL+5)
+ == #define    CODEMAX (BOL+5)         // highest code used
+ == #define    NONCHAR(c)      ((c) > CHAR_MAX)
+ == #define    NNONCHAR        (CODEMAX-CHAR_MAX)
+ */
+static states
+step(
+    struct re_guts *g,
+    sopno start,               /* start state within strip */
+    sopno stop,                        /* state after stop state within strip */
+    states bef,                        /* states reachable before */
+    int ch,                    /* character or NONCHAR code */
+    states aft)                        /* states already known reachable after */
+{
+       cset *cs;
+       sop s;
+       sopno pc;
+       onestate here;          /* note, macros know this name */
+       sopno look;
+       int i;
+
+       _DIAGASSERT(g != NULL);
+
+       for (pc = start, INIT(here, pc); pc != stop; pc++, INC(here)) {
+               s = g->strip[pc];
+               switch (OP(s)) {
+               case OEND:
+                       assert(pc == stop-1);
+                       break;
+               case OCHAR:
+                       /* only characters can match */
+                       assert(!NONCHAR(ch) || ch != (char)OPND(s));
+                       if (ch == (char)OPND(s))
+                               FWD(aft, bef, 1);
+                       break;
+               case OBOL:
+                       if (ch == BOL || ch == BOLEOL)
+                               FWD(aft, bef, 1);
+                       break;
+               case OEOL:
+                       if (ch == EOL || ch == BOLEOL)
+                               FWD(aft, bef, 1);
+                       break;
+               case OBOW:
+                       if (ch == BOW)
+                               FWD(aft, bef, 1);
+                       break;
+               case OEOW:
+                       if (ch == EOW)
+                               FWD(aft, bef, 1);
+                       break;
+               case OANY:
+                       if (!NONCHAR(ch))
+                               FWD(aft, bef, 1);
+                       break;
+               case OANYOF:
+                       cs = &g->sets[OPND(s)];
+                       if (!NONCHAR(ch) && CHIN(cs, ch))
+                               FWD(aft, bef, 1);
+                       break;
+               case OBACK_:            /* ignored here */
+               case O_BACK:
+                       FWD(aft, aft, 1);
+                       break;
+               case OPLUS_:            /* forward, this is just an empty */
+                       FWD(aft, aft, 1);
+                       break;
+               case O_PLUS:            /* both forward and back */
+                       FWD(aft, aft, 1);
+                       i = ISSETBACK(aft, OPND(s));
+                       BACK(aft, aft, OPND(s));
+                       if (!i && ISSETBACK(aft, OPND(s))) {
+                               /* oho, must reconsider loop body */
+                               pc -= OPND(s) + 1;
+                               INIT(here, pc);
+                       }
+                       break;
+               case OQUEST_:           /* two branches, both forward */
+                       FWD(aft, aft, 1);
+                       FWD(aft, aft, OPND(s));
+                       break;
+               case O_QUEST:           /* just an empty */
+                       FWD(aft, aft, 1);
+                       break;
+               case OLPAREN:           /* not significant here */
+               case ORPAREN:
+                       FWD(aft, aft, 1);
+                       break;
+               case OCH_:              /* mark the first two branches */
+                       FWD(aft, aft, 1);
+                       assert(OP(g->strip[pc+OPND(s)]) == OOR2);
+                       FWD(aft, aft, OPND(s));
+                       break;
+               case OOR1:              /* done a branch, find the O_CH */
+                       if (ISSTATEIN(aft, here)) {
+                               for (look = 1;
+                                               OP(s = g->strip[pc+look]) != O_CH;
+                                               look += OPND(s))
+                                       assert(OP(s) == OOR2);
+                               FWD(aft, aft, look);
+                       }
+                       break;
+               case OOR2:              /* propagate OCH_'s marking */
+                       FWD(aft, aft, 1);
+                       if (OP(g->strip[pc+OPND(s)]) != O_CH) {
+                               assert(OP(g->strip[pc+OPND(s)]) == OOR2);
+                               FWD(aft, aft, OPND(s));
+                       }
+                       break;
+               case O_CH:              /* just empty */
+                       FWD(aft, aft, 1);
+                       break;
+               default:                /* ooooops... */
+                       assert(nope);
+                       break;
+               }
+       }
+
+       return(aft);
+}
+
+#ifdef REDEBUG
+/*
+ - print - print a set of states
+ == #ifdef REDEBUG
+ == static void print(struct match *m, char *caption, states st, \
+ ==    int ch, FILE *d);
+ == #endif
+ */
+static void
+print(
+    struct match *m,
+    char *caption,
+    states st,
+    int ch,
+    FILE *d)
+{
+       struct re_guts *g = m->g;
+       int i;
+       int first = 1;
+
+       _DIAGASSERT(m != NULL);
+       _DIAGASSERT(caption != NULL);
+
+       if (!(m->eflags&REG_TRACE))
+               return;
+
+       _DIAGASSERT(d != NULL);
+
+       fprintf(d, "%s", caption);
+       if (ch != '\0')
+               fprintf(d, " %s", pchar(ch));
+       for (i = 0; i < g->nstates; i++)
+               if (ISSET(st, i)) {
+                       fprintf(d, "%s%d", (first) ? "\t" : ", ", i);
+                       first = 0;
+               }
+       fprintf(d, "\n");
+}
+
+/* 
+ - at - print current situation
+ == #ifdef REDEBUG
+ == static void at(struct match *m, char *title, char *start, char *stop, \
+ ==                                            sopno startst, sopno stopst);
+ == #endif
+ */
+static void
+at(
+    struct match *m,
+    char *title,
+    char *start,
+    char *stop,
+    sopno startst,
+    sopno stopst)
+{
+
+       _DIAGASSERT(m != NULL);
+       _DIAGASSERT(title != NULL);
+       _DIAGASSERT(start != NULL);
+       _DIAGASSERT(stop != NULL);
+
+       if (!(m->eflags&REG_TRACE))
+               return;
+
+       printf("%s %s-", title, pchar(*start));
+       printf("%s ", pchar(*stop));
+       printf("%ld-%ld\n", (long)startst, (long)stopst);
+}
+
+#ifndef PCHARDONE
+#define        PCHARDONE       /* never again */
+/*
+ - pchar - make a character printable
+ == #ifdef REDEBUG
+ == static char *pchar(int ch);
+ == #endif
+ *
+ * Is this identical to regchar() over in debug.c?  Well, yes.  But a
+ * duplicate here avoids having a debugging-capable regexec.o tied to
+ * a matching debug.o, and this is convenient.  It all disappears in
+ * the non-debug compilation anyway, so it doesn't matter much.
+ */
+static char *                  /* -> representation */
+pchar(
+    int ch)
+{
+       static char pbuf[10];
+
+       if (isprint(ch) || ch == ' ')
+               (void)snprintf(pbuf, sizeof pbuf, "%c", ch);
+       else
+               (void)snprintf(pbuf, sizeof pbuf, "\\%o", ch);
+       return(pbuf);
+}
+#endif
+#endif
+
+#undef matcher
+#undef fast
+#undef slow
+#undef dissect
+#undef backref
+#undef step
+#undef print
+#undef at
+#undef match
+#undef nope
diff --git a/lib/nbsd_libc/regex/re_format.7 b/lib/nbsd_libc/regex/re_format.7
new file mode 100644 (file)
index 0000000..2b1ced5
--- /dev/null
@@ -0,0 +1,315 @@
+.\"    $NetBSD: re_format.7,v 1.9 2009/04/21 14:46:02 joerg Exp $
+.\"
+.\" Copyright (c) 1992, 1993, 1994
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Henry Spencer.
+.\"
+.\" 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. 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.
+.\"
+.\" Copyright (c) 1992, 1993, 1994 Henry Spencer.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Henry Spencer.
+.\"
+.\" 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. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"    This product includes software developed by the University of
+.\"    California, Berkeley and its contributors.
+.\" 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.
+.\"
+.\"    @(#)re_format.7 8.3 (Berkeley) 3/20/94
+.\"
+.Dd March 20, 1994
+.Dt RE_FORMAT 7
+.Os
+.Sh NAME
+.Nm re_format
+.Nd POSIX 1003.2 regular expressions
+.Sh DESCRIPTION
+Regular expressions (``RE''s),
+as defined in POSIX 1003.2, come in two forms:
+modern REs (roughly those of
+.Xr egrep 1 ;
+1003.2 calls these ``extended'' REs)
+and obsolete REs (roughly those of
+.Xr ed 1 ;
+1003.2 ``basic'' REs).
+Obsolete REs mostly exist for backward compatibility in some old programs;
+they will be discussed at the end.
+1003.2 leaves some aspects of RE syntax and semantics open;
+`\(dg' marks decisions on these aspects that
+may not be fully portable to other 1003.2 implementations.
+.Pp
+A (modern) RE is one\(dg or more non-empty\(dg
+.Em branches ,
+separated by `|'.
+It matches anything that matches one of the branches.
+.Pp
+A branch is one\(dg or more
+.Em pieces ,
+concatenated.
+It matches a match for the first, followed by a match for the second, etc.
+.Pp
+A piece is an
+.Em atom
+possibly followed
+by a single\(dg `*', `+', `?', or
+.Em bound .
+An atom followed by `*' matches a sequence of 0 or more matches of the atom.
+An atom followed by `+' matches a sequence of 1 or more matches of the atom.
+An atom followed by `?' matches a sequence of 0 or 1 matches of the atom.
+.Pp
+A
+.Em bound
+is `{' followed by an unsigned decimal integer, possibly followed by `,'
+possibly followed by another unsigned decimal integer,
+always followed by `}'.
+The integers must lie between 0 and RE_DUP_MAX (255\(dg) inclusive,
+and if there are two of them, the first may not exceed the second.
+An atom followed by a bound containing one integer
+.Em i
+and no comma matches a sequence of exactly
+.Em i
+matches of the atom.
+An atom followed by a bound containing one integer
+.Em i
+and a comma matches a sequence of
+.Em i
+or more matches of the atom.
+An atom followed by a bound containing two integers
+.Em i
+and
+.Em j
+matches a sequence of
+.Em i
+through
+.Em j
+(inclusive) matches of the atom.
+.Pp
+An atom is a regular expression enclosed in `()' (matching a match for the
+regular expression), an empty set of `()' (matching the null string)\(dg, a
+.Em bracket expression
+(see below), `.' (matching any single character),
+`^' (matching the null string at the beginning of a line),
+`$' (matching the null string at the end of a line),
+a `\e' followed by one of the characters `^.[$()|*+?{\e'
+(matching that character taken as an ordinary character),
+a `\e' followed by any other character\(dg
+(matching that character taken as an ordinary character,
+as if the `\e' had not been present\(dg),
+or a single character with no other significance (matching that character).
+A `{' followed by a character other than a digit is an ordinary
+character, not the beginning of a bound\(dg.
+It is illegal to end an RE with `\e'.
+.Pp
+A
+.Em bracket expression
+is a list of characters enclosed in `[]'.
+It normally matches any single character from the list (but see below).
+If the list begins with `^',
+it matches any single character (but see below)
+.Em not
+from the rest of the list.
+If two characters in the list are separated by `\-', this is shorthand
+for the full
+.Em range
+of characters between those two (inclusive) in the collating sequence,
+e.g. `[0-9]' in ASCII matches any decimal digit.
+It is illegal\(dg for two ranges to share an endpoint, e.g. `a-c-e'.
+Ranges are very collating-sequence-dependent,
+and portable programs should avoid relying on them.
+.Pp
+To include a literal `]' in the list, make it the first character
+(following a possible `^').
+To include a literal `\-', make it the first or last character,
+or the second endpoint of a range.
+To use a literal `\-' as the first endpoint of a range,
+enclose it in `[.' and `.]' to make it a collating element (see below).
+With the exception of these and some combinations using `[' (see next
+paragraphs), all other special characters, including `\e', lose their
+special significance within a bracket expression.
+.Pp
+Within a bracket expression, a collating element (a character,
+a multi-character sequence that collates as if it were a single character,
+or a collating-sequence name for either)
+enclosed in `[.' and `.]' stands for the
+sequence of characters of that collating element.
+The sequence is a single element of the bracket expression's list.
+A bracket expression containing a multi-character collating element
+can thus match more than one character,
+e.g. if the collating sequence includes a `ch' collating element,
+then the RE `[[.ch.]]*c' matches the first five characters
+of `chchcc'.
+.Pp
+Within a bracket expression, a collating element enclosed in `[=' and
+`=]' is an equivalence class, standing for the sequences of characters
+of all collating elements equivalent to that one, including itself.
+(If there are no other equivalent collating elements,
+the treatment is as if the enclosing delimiters were `[.' and `.]'.)
+For example, if o and '\(^o' are the members of an equivalence class,
+then `[[=o=]]', `[[=\(^o'=]]', and `[o\(^o']' are all synonymous.
+An equivalence class may not\(dg be an endpoint
+of a range.
+.Pp
+Within a bracket expression, the name of a
+.Em character class
+enclosed in `[:' and `:]' stands for the list of all characters
+belonging to that class.
+Standard character class names are:
+.Bl -column "alnum" "digit" "xdigit"
+.It alnum      digit   punct
+.It alpha      graph   space
+.It blank      lower   upper
+.It cntrl      print   xdigit
+.El
+.Pp
+These stand for the character classes defined in
+.Xr ctype 3 .
+A locale may provide others.
+A character class may not be used as an endpoint of a range.
+.Pp
+There are two special cases\(dg of bracket expressions:
+the bracket expressions `[[:\*[Lt]:]]' and `[[:\*[Gt]:]]' match
+the null string at the beginning and end of a word respectively.
+A word is defined as a sequence of word characters
+which is neither preceded nor followed by word characters.
+A word character is an
+.Em alnum
+character (as defined by
+.Xr ctype 3 )
+or an underscore.
+This is an extension, compatible with but not specified by POSIX 1003.2,
+and should be used with caution in software intended to be portable
+to other systems.
+.Pp
+In the event that an RE could match more than one substring of a given
+string, the RE matches the one starting earliest in the string.
+If the RE could match more than one substring starting at that point,
+it matches the longest.
+Subexpressions also match the longest possible substrings, subject to
+the constraint that the whole match be as long as possible,
+with subexpressions starting earlier in the RE taking priority over
+ones starting later.
+Note that higher-level subexpressions thus take priority over
+their lower-level component subexpressions.
+.Pp
+Match lengths are measured in characters, not collating elements.
+A null string is considered longer than no match at all.
+For example,
+`bb*' matches the three middle characters of `abbbc',
+`(wee|week)(knights|nights)' matches all ten characters of `weeknights',
+when `(.*).*' is matched against `abc' the parenthesized subexpression
+matches all three characters, and
+when `(a*)*' is matched against `bc' both the whole RE and the parenthesized
+subexpression match the null string.
+.Pp
+If case-independent matching is specified,
+the effect is much as if all case distinctions had vanished from the
+alphabet.
+When an alphabetic that exists in multiple cases appears as an
+ordinary character outside a bracket expression, it is effectively
+transformed into a bracket expression containing both cases,
+e.g. `x' becomes `[xX]'.
+When it appears inside a bracket expression, all case counterparts
+of it are added to the bracket expression, so that (e.g.) `[x]'
+becomes `[xX]' and `[^x]' becomes `[^xX]'.
+.Pp
+No particular limit is imposed on the length of REs\(dg.
+Programs intended to be portable should not employ REs longer
+than 256 bytes,
+as an implementation can refuse to accept such REs and remain
+POSIX-compliant.
+.Pp
+Obsolete (``basic'') regular expressions differ in several respects.
+`|', `+', and `?' are ordinary characters and there is no equivalent
+for their functionality.
+The delimiters for bounds are `\e{' and `\e}',
+with `{' and `}' by themselves ordinary characters.
+The parentheses for nested subexpressions are `\e(' and `\e)',
+with `(' and `)' by themselves ordinary characters.
+`^' is an ordinary character except at the beginning of the
+RE or\(dg the beginning of a parenthesized subexpression,
+`$' is an ordinary character except at the end of the
+RE or\(dg the end of a parenthesized subexpression,
+and `*' is an ordinary character if it appears at the beginning of the
+RE or the beginning of a parenthesized subexpression
+(after a possible leading `^').
+Finally, there is one new type of atom, a
+.Em back reference :
+`\e' followed by a non-zero decimal digit
+.Em d
+matches the same sequence of characters
+matched by the
+.Em d Ns th parenthesized subexpression
+(numbering subexpressions by the positions of their opening parentheses,
+left to right),
+so that (e.g.) `\e([bc]\e)\e1' matches `bb' or `cc' but not `bc'.
+.Sh SEE ALSO
+.Xr regex 3
+.Pp
+POSIX 1003.2, section 2.8 (Regular Expression Notation).
+.Sh BUGS
+Having two kinds of REs is a botch.
+.Pp
+The current 1003.2 spec says that `)' is an ordinary character in
+the absence of an unmatched `(';
+this was an unintentional result of a wording error, and change is likely.
+Avoid relying on it.
+.Pp
+Back references are a dreadful botch,
+posing major problems for efficient implementations.
+They are also somewhat vaguely defined
+(does `a\e(\e(b\e)*\e2\e)*d' match `abbbd'?).
+Avoid using them.
+.Pp
+1003.2's specification of case-independent matching is vague.
+The ``one case implies all cases'' definition given above
+is current consensus among implementors as to the right interpretation.
+.Pp
+The syntax for word boundaries is incredibly ugly.
diff --git a/lib/nbsd_libc/regex/regcomp.c b/lib/nbsd_libc/regex/regcomp.c
new file mode 100644 (file)
index 0000000..fdaa6ac
--- /dev/null
@@ -0,0 +1,1902 @@
+/*     $NetBSD: regcomp.c,v 1.29 2009/02/12 05:06:54 lukem Exp $       */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. 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.
+ *
+ *     @(#)regcomp.c   8.5 (Berkeley) 3/20/94
+ */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994 Henry Spencer.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ *     @(#)regcomp.c   8.5 (Berkeley) 3/20/94
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)regcomp.c  8.5 (Berkeley) 3/20/94";
+#else
+__RCSID("$NetBSD: regcomp.c,v 1.29 2009/02/12 05:06:54 lukem Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <regex.h>
+
+#ifdef __weak_alias
+__weak_alias(regcomp,_regcomp)
+#endif
+
+#include "utils.h"
+#include "regex2.h"
+
+#include "cclass.h"
+#include "cname.h"
+
+/*
+ * parse structure, passed up and down to avoid global variables and
+ * other clumsinesses
+ */
+struct parse {
+       const char *next;       /* next character in RE */
+       const char *end;        /* end of string (-> NUL normally) */
+       int error;              /* has an error been seen? */
+       sop *strip;             /* malloced strip */
+       sopno ssize;            /* malloced strip size (allocated) */
+       sopno slen;             /* malloced strip length (used) */
+       int ncsalloc;           /* number of csets allocated */
+       struct re_guts *g;
+#      define  NPAREN  10      /* we need to remember () 1-9 for back refs */
+       sopno pbegin[NPAREN];   /* -> ( ([0] unused) */
+       sopno pend[NPAREN];     /* -> ) ([0] unused) */
+};
+
+/* ========= begin header generated by ./mkh ========= */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* === regcomp.c === */
+static void p_ere(struct parse *p, int stop);
+static void p_ere_exp(struct parse *p);
+static void p_str(struct parse *p);
+static void p_bre(struct parse *p, int end1, int end2);
+static int p_simp_re(struct parse *p, int starordinary);
+static int p_count(struct parse *p);
+static void p_bracket(struct parse *p);
+static void p_b_term(struct parse *p, cset *cs);
+static void p_b_cclass(struct parse *p, cset *cs);
+static void p_b_eclass(struct parse *p, cset *cs);
+static char p_b_symbol(struct parse *p);
+static char p_b_coll_elem(struct parse *p, int endc);
+static int othercase(int ch);
+static void bothcases(struct parse *p, int ch);
+static void ordinary(struct parse *p, int ch);
+static void nonnewline(struct parse *p);
+static void repeat(struct parse *p, sopno start, int from, int to);
+static int seterr(struct parse *p, int e);
+static cset *allocset(struct parse *p);
+static void freeset(struct parse *p, cset *cs);
+static int freezeset(struct parse *p, cset *cs);
+static int firstch(struct parse *p, cset *cs);
+static int nch(struct parse *p, cset *cs);
+static void mcadd(struct parse *p, cset *cs, const char *cp);
+#if 0
+static void mcsub(cset *cs, char *cp);
+static int mcin(cset *cs, char *cp);
+static char *mcfind(cset *cs, char *cp);
+#endif
+static void mcinvert(struct parse *p, cset *cs);
+static void mccase(struct parse *p, cset *cs);
+static int isinsets(struct re_guts *g, int c);
+static int samesets(struct re_guts *g, int c1, int c2);
+static void categorize(struct parse *p, struct re_guts *g);
+static sopno dupl(struct parse *p, sopno start, sopno finish);
+static void doemit(struct parse *p, sop op, sopno opnd);
+static void doinsert(struct parse *p, sop op, sopno opnd, sopno pos);
+static void dofwd(struct parse *p, sopno pos, sopno value);
+static void enlarge(struct parse *p, sopno size);
+static void stripsnug(struct parse *p, struct re_guts *g);
+static void findmust(struct parse *p, struct re_guts *g);
+static sopno pluscount(struct parse *p, struct re_guts *g);
+
+#ifdef __cplusplus
+}
+#endif
+/* ========= end header generated by ./mkh ========= */
+
+static char nuls[10];          /* place to point scanner in event of error */
+
+/*
+ * macros for use with parse structure
+ * BEWARE:  these know that the parse structure is named `p' !!!
+ */
+#define        PEEK()  (*p->next)
+#define        PEEK2() (*(p->next+1))
+#define        MORE()  (p->next < p->end)
+#define        MORE2() (p->next+1 < p->end)
+#define        SEE(c)  (MORE() && PEEK() == (c))
+#define        SEETWO(a, b)    (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
+#define        EAT(c)  ((SEE(c)) ? (NEXT(), 1) : 0)
+#define        EATTWO(a, b)    ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
+#define        NEXT()  (p->next++)
+#define        NEXT2() (p->next += 2)
+#define        NEXTn(n)        (p->next += (n))
+#define        GETNEXT()       (*p->next++)
+#define        SETERROR(e)     seterr(p, (e))
+#define        REQUIRE(co, e)  (void) ((co) || SETERROR(e))
+#define        MUSTSEE(c, e)   (REQUIRE(MORE() && PEEK() == (c), e))
+#define        MUSTEAT(c, e)   (void) (REQUIRE(MORE() && GETNEXT() == (c), e))
+#define        MUSTNOTSEE(c, e)        (REQUIRE(!MORE() || PEEK() != (c), e))
+#define        EMIT(op, sopnd) doemit(p, (sop)(op), sopnd)
+#define        INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
+#define        AHEAD(pos)              dofwd(p, pos, HERE()-(pos))
+#define        ASTERN(sop, pos)        EMIT(sop, HERE()-pos)
+#define        HERE()          (p->slen)
+#define        THERE()         (p->slen - 1)
+#define        THERETHERE()    (p->slen - 2)
+#define        DROP(n) (p->slen -= (n))
+
+#ifndef NDEBUG
+static int never = 0;          /* for use in asserts; shuts lint up */
+#else
+#define        never   0               /* some <assert.h>s have bugs too */
+#endif
+
+/*
+ - regcomp - interface for parser and compilation
+ = extern int regcomp(regex_t *, const char *, int);
+ = #define     REG_BASIC       0000
+ = #define     REG_EXTENDED    0001
+ = #define     REG_ICASE       0002
+ = #define     REG_NOSUB       0004
+ = #define     REG_NEWLINE     0010
+ = #define     REG_NOSPEC      0020
+ = #define     REG_PEND        0040
+ = #define     REG_DUMP        0200
+ */
+int                            /* 0 success, otherwise REG_something */
+regcomp(
+    regex_t *preg,
+    const char *pattern,
+    int cflags)
+{
+       struct parse pa;
+       struct re_guts *g;
+       struct parse *p = &pa;
+       int i;
+       size_t len;
+#ifdef REDEBUG
+#      define  GOODFLAGS(f)    (f)
+#else
+#      define  GOODFLAGS(f)    ((f)&~REG_DUMP)
+#endif
+
+       _DIAGASSERT(preg != NULL);
+       _DIAGASSERT(pattern != NULL);
+
+       cflags = GOODFLAGS(cflags);
+       if ((cflags&REG_EXTENDED) && (cflags&REG_NOSPEC))
+               return(REG_INVARG);
+
+       if (cflags&REG_PEND) {
+               if (preg->re_endp < pattern)
+                       return(REG_INVARG);
+               len = preg->re_endp - pattern;
+       } else
+               len = strlen(pattern);
+
+       /* do the mallocs early so failure handling is easy */
+       g = (struct re_guts *)malloc(sizeof(struct re_guts) +
+                                                       (NC-1)*sizeof(cat_t));
+       if (g == NULL)
+               return(REG_ESPACE);
+       p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
+       p->strip = (sop *)malloc(p->ssize * sizeof(sop));
+       p->slen = 0;
+       if (p->strip == NULL) {
+               free(g);
+               return(REG_ESPACE);
+       }
+
+       /* set things up */
+       p->g = g;
+       p->next = pattern;
+       p->end = p->next + len;
+       p->error = 0;
+       p->ncsalloc = 0;
+       for (i = 0; i < NPAREN; i++) {
+               p->pbegin[i] = 0;
+               p->pend[i] = 0;
+       }
+       g->csetsize = NC;
+       g->sets = NULL;
+       g->setbits = NULL;
+       g->ncsets = 0;
+       g->cflags = cflags;
+       g->iflags = 0;
+       g->nbol = 0;
+       g->neol = 0;
+       g->must = NULL;
+       g->mlen = 0;
+       g->nsub = 0;
+       g->ncategories = 1;     /* category 0 is "everything else" */
+       g->categories = &g->catspace[-(CHAR_MIN)];
+       (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
+       g->backrefs = 0;
+
+       /* do it */
+       EMIT(OEND, 0);
+       g->firststate = THERE();
+       if (cflags&REG_EXTENDED)
+               p_ere(p, OUT);
+       else if (cflags&REG_NOSPEC)
+               p_str(p);
+       else
+               p_bre(p, OUT, OUT);
+       EMIT(OEND, 0);
+       g->laststate = THERE();
+
+       /* tidy up loose ends and fill things in */
+       categorize(p, g);
+       stripsnug(p, g);
+       findmust(p, g);
+       g->nplus = pluscount(p, g);
+       g->magic = MAGIC2;
+       preg->re_nsub = g->nsub;
+       preg->re_g = g;
+       preg->re_magic = MAGIC1;
+#ifndef REDEBUG
+       /* not debugging, so can't rely on the assert() in regexec() */
+       if (g->iflags&BAD)
+               SETERROR(REG_ASSERT);
+#endif
+
+       /* win or lose, we're done */
+       if (p->error != 0)      /* lose */
+               regfree(preg);
+       return(p->error);
+}
+
+/*
+ - p_ere - ERE parser top level, concatenation and alternation
+ == static void p_ere(struct parse *p, int stop);
+ */
+static void
+p_ere(
+    struct parse *p,
+    int stop)                  /* character this ERE should end at */
+{
+       char c;
+       sopno prevback = 0;     /* pacify gcc */
+       sopno prevfwd = 0;      /* pacify gcc */
+       sopno conc;
+       int first = 1;          /* is this the first alternative? */
+
+       _DIAGASSERT(p != NULL);
+
+       for (;;) {
+               /* do a bunch of concatenated expressions */
+               conc = HERE();
+               while (MORE() && (c = PEEK()) != '|' && c != stop)
+                       p_ere_exp(p);
+               REQUIRE(HERE() != conc, REG_EMPTY);     /* require nonempty */
+
+               if (!EAT('|'))
+                       break;          /* NOTE BREAK OUT */
+
+               if (first) {
+                       INSERT(OCH_, conc);     /* offset is wrong */
+                       prevfwd = conc;
+                       prevback = conc;
+                       first = 0;
+               }
+               ASTERN(OOR1, prevback);
+               prevback = THERE();
+               AHEAD(prevfwd);                 /* fix previous offset */
+               prevfwd = HERE();
+               EMIT(OOR2, 0);                  /* offset is very wrong */
+       }
+
+       if (!first) {           /* tail-end fixups */
+               AHEAD(prevfwd);
+               ASTERN(O_CH, prevback);
+       }
+
+       assert(!MORE() || SEE(stop));
+}
+
+/*
+ - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
+ == static void p_ere_exp(struct parse *p);
+ */
+static void
+p_ere_exp(
+    struct parse *p)
+{
+       char c;
+       sopno pos;
+       int count;
+       int count2;
+       sopno subno;
+       int wascaret = 0;
+
+       _DIAGASSERT(p != NULL);
+
+       assert(MORE());         /* caller should have ensured this */
+       c = GETNEXT();
+
+       pos = HERE();
+       switch (c) {
+       case '(':
+               REQUIRE(MORE(), REG_EPAREN);
+               p->g->nsub++;
+               subno = p->g->nsub;
+               if (subno < NPAREN)
+                       p->pbegin[subno] = HERE();
+               EMIT(OLPAREN, subno);
+               if (!SEE(')'))
+                       p_ere(p, ')');
+               if (subno < NPAREN) {
+                       p->pend[subno] = HERE();
+                       assert(p->pend[subno] != 0);
+               }
+               EMIT(ORPAREN, subno);
+               MUSTEAT(')', REG_EPAREN);
+               break;
+#ifndef POSIX_MISTAKE
+       case ')':               /* happens only if no current unmatched ( */
+               /*
+                * You may ask, why the ifndef?  Because I didn't notice
+                * this until slightly too late for 1003.2, and none of the
+                * other 1003.2 regular-expression reviewers noticed it at
+                * all.  So an unmatched ) is legal POSIX, at least until
+                * we can get it fixed.
+                */
+               SETERROR(REG_EPAREN);
+               break;
+#endif
+       case '^':
+               EMIT(OBOL, 0);
+               p->g->iflags |= USEBOL;
+               p->g->nbol++;
+               wascaret = 1;
+               break;
+       case '$':
+               EMIT(OEOL, 0);
+               p->g->iflags |= USEEOL;
+               p->g->neol++;
+               break;
+       case '|':
+               SETERROR(REG_EMPTY);
+               break;
+       case '*':
+       case '+':
+       case '?':
+               SETERROR(REG_BADRPT);
+               break;
+       case '.':
+               if (p->g->cflags&REG_NEWLINE)
+                       nonnewline(p);
+               else
+                       EMIT(OANY, 0);
+               break;
+       case '[':
+               p_bracket(p);
+               break;
+       case '\\':
+               REQUIRE(MORE(), REG_EESCAPE);
+               c = GETNEXT();
+               ordinary(p, c);
+               break;
+       case '{':               /* okay as ordinary except if digit follows */
+               REQUIRE(!MORE() || !isdigit((unsigned char)PEEK()), REG_BADRPT);
+               /* FALLTHROUGH */
+       default:
+               ordinary(p, c);
+               break;
+       }
+
+       if (!MORE())
+               return;
+       c = PEEK();
+       /* we call { a repetition if followed by a digit */
+       if (!( c == '*' || c == '+' || c == '?' ||
+           (c == '{' && MORE2() && isdigit((unsigned char)PEEK2())) ))
+               return;         /* no repetition, we're done */
+       NEXT();
+
+       REQUIRE(!wascaret, REG_BADRPT);
+       switch (c) {
+       case '*':       /* implemented as +? */
+               /* this case does not require the (y|) trick, noKLUDGE */
+               INSERT(OPLUS_, pos);
+               ASTERN(O_PLUS, pos);
+               INSERT(OQUEST_, pos);
+               ASTERN(O_QUEST, pos);
+               break;
+       case '+':
+               INSERT(OPLUS_, pos);
+               ASTERN(O_PLUS, pos);
+               break;
+       case '?':
+               /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
+               INSERT(OCH_, pos);              /* offset slightly wrong */
+               ASTERN(OOR1, pos);              /* this one's right */
+               AHEAD(pos);                     /* fix the OCH_ */
+               EMIT(OOR2, 0);                  /* offset very wrong... */
+               AHEAD(THERE());                 /* ...so fix it */
+               ASTERN(O_CH, THERETHERE());
+               break;
+       case '{':
+               count = p_count(p);
+               if (EAT(',')) {
+                       if (isdigit((unsigned char)PEEK())) {
+                               count2 = p_count(p);
+                               REQUIRE(count <= count2, REG_BADBR);
+                       } else          /* single number with comma */
+                               count2 = INFINITY;
+               } else          /* just a single number */
+                       count2 = count;
+               repeat(p, pos, count, count2);
+               if (!EAT('}')) {        /* error heuristics */
+                       while (MORE() && PEEK() != '}')
+                               NEXT();
+                       REQUIRE(MORE(), REG_EBRACE);
+                       SETERROR(REG_BADBR);
+               }
+               break;
+       }
+
+       if (!MORE())
+               return;
+       c = PEEK();
+       if (!( c == '*' || c == '+' || c == '?' ||
+           (c == '{' && MORE2() && isdigit((unsigned char)PEEK2())) ) )
+               return;
+       SETERROR(REG_BADRPT);
+}
+
+/*
+ - p_str - string (no metacharacters) "parser"
+ == static void p_str(struct parse *p);
+ */
+static void
+p_str(
+    struct parse *p)
+{
+
+       _DIAGASSERT(p != NULL);
+
+       REQUIRE(MORE(), REG_EMPTY);
+       while (MORE())
+               ordinary(p, GETNEXT());
+}
+
+/*
+ - p_bre - BRE parser top level, anchoring and concatenation
+ == static void p_bre(struct parse *p, int end1, \
+ ==    int end2);
+ * Giving end1 as OUT essentially eliminates the end1/end2 check.
+ *
+ * This implementation is a bit of a kludge, in that a trailing $ is first
+ * taken as an ordinary character and then revised to be an anchor.  The
+ * only undesirable side effect is that '$' gets included as a character
+ * category in such cases.  This is fairly harmless; not worth fixing.
+ * The amount of lookahead needed to avoid this kludge is excessive.
+ */
+static void
+p_bre(
+    struct parse *p,
+    int end1,          /* first terminating character */
+    int end2)          /* second terminating character */
+{
+       sopno start;
+       int first = 1;                  /* first subexpression? */
+       int wasdollar = 0;
+
+       _DIAGASSERT(p != NULL);
+
+       start = HERE();
+
+       if (EAT('^')) {
+               EMIT(OBOL, 0);
+               p->g->iflags |= USEBOL;
+               p->g->nbol++;
+       }
+       while (MORE() && !SEETWO(end1, end2)) {
+               wasdollar = p_simp_re(p, first);
+               first = 0;
+       }
+       if (wasdollar) {        /* oops, that was a trailing anchor */
+               DROP(1);
+               EMIT(OEOL, 0);
+               p->g->iflags |= USEEOL;
+               p->g->neol++;
+       }
+
+       REQUIRE(HERE() != start, REG_EMPTY);    /* require nonempty */
+}
+
+/*
+ - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
+ == static int p_simp_re(struct parse *p, int starordinary);
+ */
+static int                     /* was the simple RE an unbackslashed $? */
+p_simp_re(
+    struct parse *p,
+    int starordinary)          /* is a leading * an ordinary character? */
+{
+       int c;
+       int count;
+       int count2;
+       sopno pos;
+       int i;
+       sopno subno;
+#      define  BACKSL  (1<<CHAR_BIT)
+
+       _DIAGASSERT(p != NULL);
+
+       pos = HERE();           /* repetion op, if any, covers from here */
+
+       assert(MORE());         /* caller should have ensured this */
+       c = GETNEXT();
+       if (c == '\\') {
+               REQUIRE(MORE(), REG_EESCAPE);
+               c = BACKSL | (unsigned char)GETNEXT();
+       }
+       switch (c) {
+       case '.':
+               if (p->g->cflags&REG_NEWLINE)
+                       nonnewline(p);
+               else
+                       EMIT(OANY, 0);
+               break;
+       case '[':
+               p_bracket(p);
+               break;
+       case BACKSL|'{':
+               SETERROR(REG_BADRPT);
+               break;
+       case BACKSL|'(':
+               p->g->nsub++;
+               subno = p->g->nsub;
+               if (subno < NPAREN)
+                       p->pbegin[subno] = HERE();
+               EMIT(OLPAREN, subno);
+               /* the MORE here is an error heuristic */
+               if (MORE() && !SEETWO('\\', ')'))
+                       p_bre(p, '\\', ')');
+               if (subno < NPAREN) {
+                       p->pend[subno] = HERE();
+                       assert(p->pend[subno] != 0);
+               }
+               EMIT(ORPAREN, subno);
+               REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
+               break;
+       case BACKSL|')':        /* should not get here -- must be user */
+       case BACKSL|'}':
+               SETERROR(REG_EPAREN);
+               break;
+       case BACKSL|'1':
+       case BACKSL|'2':
+       case BACKSL|'3':
+       case BACKSL|'4':
+       case BACKSL|'5':
+       case BACKSL|'6':
+       case BACKSL|'7':
+       case BACKSL|'8':
+       case BACKSL|'9':
+               i = (c&~BACKSL) - '0';
+               assert(i < NPAREN);
+               if (p->pend[i] != 0) {
+                       assert(i <= p->g->nsub);
+                       EMIT(OBACK_, i);
+                       assert(p->pbegin[i] != 0);
+                       assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
+                       assert(OP(p->strip[p->pend[i]]) == ORPAREN);
+                       (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
+                       EMIT(O_BACK, i);
+               } else
+                       SETERROR(REG_ESUBREG);
+               p->g->backrefs = 1;
+               break;
+       case '*':
+               REQUIRE(starordinary, REG_BADRPT);
+               /* FALLTHROUGH */
+       default:
+               ordinary(p, c &~ BACKSL);
+               break;
+       }
+
+       if (EAT('*')) {         /* implemented as +? */
+               /* this case does not require the (y|) trick, noKLUDGE */
+               INSERT(OPLUS_, pos);
+               ASTERN(O_PLUS, pos);
+               INSERT(OQUEST_, pos);
+               ASTERN(O_QUEST, pos);
+       } else if (EATTWO('\\', '{')) {
+               count = p_count(p);
+               if (EAT(',')) {
+                       if (MORE() && isdigit((unsigned char)PEEK())) {
+                               count2 = p_count(p);
+                               REQUIRE(count <= count2, REG_BADBR);
+                       } else          /* single number with comma */
+                               count2 = INFINITY;
+               } else          /* just a single number */
+                       count2 = count;
+               repeat(p, pos, count, count2);
+               if (!EATTWO('\\', '}')) {       /* error heuristics */
+                       while (MORE() && !SEETWO('\\', '}'))
+                               NEXT();
+                       REQUIRE(MORE(), REG_EBRACE);
+                       SETERROR(REG_BADBR);
+               }
+       } else if (c == (unsigned char)'$')     /* $ (but not \$) ends it */
+               return(1);
+
+       return(0);
+}
+
+/*
+ - p_count - parse a repetition count
+ == static int p_count(struct parse *p);
+ */
+static int                     /* the value */
+p_count(
+    struct parse *p)
+{
+       int count = 0;
+       int ndigits = 0;
+
+       _DIAGASSERT(p != NULL);
+
+       while (MORE() && isdigit((unsigned char)PEEK()) && count <= DUPMAX) {
+               count = count*10 + (GETNEXT() - '0');
+               ndigits++;
+       }
+
+       REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
+       return(count);
+}
+
+/*
+ - p_bracket - parse a bracketed character list
+ == static void p_bracket(struct parse *p);
+ *
+ * Note a significant property of this code:  if the allocset() did SETERROR,
+ * no set operations are done.
+ */
+static void
+p_bracket(
+    struct parse *p)
+{
+       cset *cs;
+       int invert = 0;
+
+       _DIAGASSERT(p != NULL);
+
+       cs = allocset(p);
+
+       /* Dept of Truly Sickening Special-Case Kludges */
+       if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]",
+                                           (size_t)6) == 0) {
+               EMIT(OBOW, 0);
+               NEXTn(6);
+               return;
+       }
+       if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]",
+                                           (size_t)6) == 0) {
+               EMIT(OEOW, 0);
+               NEXTn(6);
+               return;
+       }
+
+       if (EAT('^'))
+               invert++;       /* make note to invert set at end */
+       if (EAT(']'))
+               CHadd(cs, ']');
+       else if (EAT('-'))
+               CHadd(cs, '-');
+       while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
+               p_b_term(p, cs);
+       if (EAT('-'))
+               CHadd(cs, '-');
+       MUSTEAT(']', REG_EBRACK);
+
+       if (p->error != 0)      /* don't mess things up further */
+               return;
+
+       if (p->g->cflags&REG_ICASE) {
+               int i;
+               int ci;
+
+               for (i = p->g->csetsize - 1; i >= 0; i--)
+                       if (CHIN(cs, i) && isalpha(i)) {
+                               ci = othercase(i);
+                               if (ci != i)
+                                       CHadd(cs, ci);
+                       }
+               if (cs->multis != NULL)
+                       mccase(p, cs);
+       }
+       if (invert) {
+               int i;
+
+               for (i = p->g->csetsize - 1; i >= 0; i--)
+                       if (CHIN(cs, i))
+                               CHsub(cs, i);
+                       else
+                               CHadd(cs, i);
+               if (p->g->cflags&REG_NEWLINE)
+                       CHsub(cs, '\n');
+               if (cs->multis != NULL)
+                       mcinvert(p, cs);
+       }
+
+       assert(cs->multis == NULL);             /* xxx */
+
+       if (nch(p, cs) == 1) {          /* optimize singleton sets */
+               ordinary(p, firstch(p, cs));
+               freeset(p, cs);
+       } else
+               EMIT(OANYOF, freezeset(p, cs));
+}
+
+/*
+ - p_b_term - parse one term of a bracketed character list
+ == static void p_b_term(struct parse *p, cset *cs);
+ */
+static void
+p_b_term(
+    struct parse *p,
+    cset *cs)
+{
+       char c;
+       char start, finish;
+       int i;
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(cs != NULL);
+
+       /* classify what we've got */
+       switch ((MORE()) ? PEEK() : '\0') {
+       case '[':
+               c = (MORE2()) ? PEEK2() : '\0';
+               break;
+
+       case '-':
+               SETERROR(REG_ERANGE);
+               return;                 /* NOTE RETURN */
+
+       default:
+               c = '\0';
+               break;
+       }
+
+       switch (c) {
+       case ':':               /* character class */
+               NEXT2();
+               REQUIRE(MORE(), REG_EBRACK);
+               c = PEEK();
+               REQUIRE(c != '-' && c != ']', REG_ECTYPE);
+               p_b_cclass(p, cs);
+               REQUIRE(MORE(), REG_EBRACK);
+               REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
+               break;
+       case '=':               /* equivalence class */
+               NEXT2();
+               REQUIRE(MORE(), REG_EBRACK);
+               c = PEEK();
+               REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
+               p_b_eclass(p, cs);
+               REQUIRE(MORE(), REG_EBRACK);
+               REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
+               break;
+       default:                /* symbol, ordinary character, or range */
+/* xxx revision needed for multichar stuff */
+               start = p_b_symbol(p);
+               if (SEE('-') && MORE2() && PEEK2() != ']') {
+                       /* range */
+                       NEXT();
+                       if (EAT('-'))
+                               finish = '-';
+                       else
+                               finish = p_b_symbol(p);
+               } else
+                       finish = start;
+/* xxx what about signed chars here... */
+               REQUIRE(start <= finish, REG_ERANGE);
+               for (i = start; i <= finish; i++)
+                       CHadd(cs, i);
+               break;
+       }
+}
+
+/*
+ - p_b_cclass - parse a character-class name and deal with it
+ == static void p_b_cclass(struct parse *p, cset *cs);
+ */
+static void
+p_b_cclass(
+    struct parse *p,
+    cset *cs)
+{
+       const char *sp;
+       const struct cclass *cp;
+       size_t len;
+       const char *u;
+       char c;
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(cs != NULL);
+
+       sp = p->next;
+
+       while (MORE() && isalpha((unsigned char)PEEK()))
+               NEXT();
+       len = p->next - sp;
+       for (cp = cclasses; cp->name != NULL; cp++)
+               if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
+                       break;
+       if (cp->name == NULL) {
+               /* oops, didn't find it */
+               SETERROR(REG_ECTYPE);
+               return;
+       }
+
+       u = cp->chars;
+       while ((c = *u++) != '\0')
+               CHadd(cs, c);
+       for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
+               MCadd(p, cs, u);
+}
+
+/*
+ - p_b_eclass - parse an equivalence-class name and deal with it
+ == static void p_b_eclass(struct parse *p, cset *cs);
+ *
+ * This implementation is incomplete. xxx
+ */
+static void
+p_b_eclass(
+    struct parse *p,
+    cset *cs)
+{
+       char c;
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(cs != NULL);
+
+       c = p_b_coll_elem(p, '=');
+       CHadd(cs, c);
+}
+
+/*
+ - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
+ == static char p_b_symbol(struct parse *p);
+ */
+static char                    /* value of symbol */
+p_b_symbol(
+    struct parse *p)
+{
+       char value;
+
+       _DIAGASSERT(p != NULL);
+
+       REQUIRE(MORE(), REG_EBRACK);
+       if (!EATTWO('[', '.'))
+               return(GETNEXT());
+
+       /* collating symbol */
+       value = p_b_coll_elem(p, '.');
+       REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
+       return(value);
+}
+
+/*
+ - p_b_coll_elem - parse a collating-element name and look it up
+ == static char p_b_coll_elem(struct parse *p, int endc);
+ */
+static char                    /* value of collating element */
+p_b_coll_elem(
+    struct parse *p,
+    int endc)                  /* name ended by endc,']' */
+{
+       const char *sp;
+       const struct cname *cp;
+       size_t len;
+
+       _DIAGASSERT(p != NULL);
+
+       sp = p->next;
+
+       while (MORE() && !SEETWO(endc, ']'))
+               NEXT();
+       if (!MORE()) {
+               SETERROR(REG_EBRACK);
+               return(0);
+       }
+       len = p->next - sp;
+       for (cp = cnames; cp->name != NULL; cp++)
+               if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
+                       return(cp->code);       /* known name */
+       if (len == 1)
+               return(*sp);    /* single character */
+       SETERROR(REG_ECOLLATE);                 /* neither */
+       return(0);
+}
+
+/*
+ - othercase - return the case counterpart of an alphabetic
+ == static int othercase(int ch);
+ */
+static int                     /* if no counterpart, return ch */
+othercase(
+    int ch)
+{
+       assert(isalpha(ch));
+       if (isupper(ch))
+               return(tolower(ch));
+       else if (islower(ch))
+               return(toupper(ch));
+       else                    /* peculiar, but could happen */
+               return(ch);
+}
+
+/*
+ - bothcases - emit a dualcase version of a two-case character
+ == static void bothcases(struct parse *p, int ch);
+ *
+ * Boy, is this implementation ever a kludge...
+ */
+static void
+bothcases(
+    struct parse *p,
+    int ch)
+{
+       const char *oldnext;
+       const char *oldend;
+       char bracket[3];
+
+       _DIAGASSERT(p != NULL);
+
+       oldnext = p->next;
+       oldend = p->end;
+
+       assert(othercase(ch) != ch);    /* p_bracket() would recurse */
+       p->next = bracket;
+       p->end = bracket+2;
+       bracket[0] = ch;
+       bracket[1] = ']';
+       bracket[2] = '\0';
+       p_bracket(p);
+       assert(p->next == bracket+2);
+       p->next = oldnext;
+       p->end = oldend;
+}
+
+/*
+ - ordinary - emit an ordinary character
+ == static void ordinary(struct parse *p, int ch);
+ */
+static void
+ordinary(
+    struct parse *p,
+    int ch)
+{
+       cat_t *cap;
+
+       _DIAGASSERT(p != NULL);
+
+       cap = p->g->categories;
+       if ((p->g->cflags&REG_ICASE) && isalpha((unsigned char) ch)
+           && othercase((unsigned char) ch) != (unsigned char) ch)
+               bothcases(p, (unsigned char) ch);
+       else {
+               EMIT(OCHAR, (unsigned char)ch);
+               if (cap[ch] == 0)
+                       cap[ch] = p->g->ncategories++;
+       }
+}
+
+/*
+ - nonnewline - emit REG_NEWLINE version of OANY
+ == static void nonnewline(struct parse *p);
+ *
+ * Boy, is this implementation ever a kludge...
+ */
+static void
+nonnewline(
+    struct parse *p)
+{
+       const char *oldnext;
+       const char *oldend;
+       char bracket[4];
+
+       _DIAGASSERT(p != NULL);
+
+       oldnext = p->next;
+       oldend = p->end;
+
+       p->next = bracket;
+       p->end = bracket+3;
+       bracket[0] = '^';
+       bracket[1] = '\n';
+       bracket[2] = ']';
+       bracket[3] = '\0';
+       p_bracket(p);
+       assert(p->next == bracket+3);
+       p->next = oldnext;
+       p->end = oldend;
+}
+
+/*
+ - repeat - generate code for a bounded repetition, recursively if needed
+ == static void repeat(struct parse *p, sopno start, int from, int to);
+ */
+static void
+repeat(
+    struct parse *p,
+    sopno start,               /* operand from here to end of strip */
+    int from,                  /* repeated from this number */
+    int to)                    /* to this number of times (maybe INFINITY) */
+{
+       sopno finish;
+#      define  N       2
+#      define  INF     3
+#      define  REP(f, t)       ((f)*8 + (t))
+#      define  MAP(n)  (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
+       sopno copy;
+
+       _DIAGASSERT(p != NULL);
+
+       finish = HERE();
+
+       if (p->error != 0)      /* head off possible runaway recursion */
+               return;
+
+       assert(from <= to);
+
+       switch (REP(MAP(from), MAP(to))) {
+       case REP(0, 0):                 /* must be user doing this */
+               DROP(finish-start);     /* drop the operand */
+               break;
+       case REP(0, 1):                 /* as x{1,1}? */
+       case REP(0, N):                 /* as x{1,n}? */
+       case REP(0, INF):               /* as x{1,}? */
+               /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
+               INSERT(OCH_, start);            /* offset is wrong... */
+               repeat(p, start+1, 1, to);
+               ASTERN(OOR1, start);
+               AHEAD(start);                   /* ... fix it */
+               EMIT(OOR2, 0);
+               AHEAD(THERE());
+               ASTERN(O_CH, THERETHERE());
+               break;
+       case REP(1, 1):                 /* trivial case */
+               /* done */
+               break;
+       case REP(1, N):                 /* as x?x{1,n-1} */
+               /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
+               INSERT(OCH_, start);
+               ASTERN(OOR1, start);
+               AHEAD(start);
+               EMIT(OOR2, 0);                  /* offset very wrong... */
+               AHEAD(THERE());                 /* ...so fix it */
+               ASTERN(O_CH, THERETHERE());
+               copy = dupl(p, start+1, finish+1);
+               assert(copy == finish+4);
+               repeat(p, copy, 1, to-1);
+               break;
+       case REP(1, INF):               /* as x+ */
+               INSERT(OPLUS_, start);
+               ASTERN(O_PLUS, start);
+               break;
+       case REP(N, N):                 /* as xx{m-1,n-1} */
+               copy = dupl(p, start, finish);
+               repeat(p, copy, from-1, to-1);
+               break;
+       case REP(N, INF):               /* as xx{n-1,INF} */
+               copy = dupl(p, start, finish);
+               repeat(p, copy, from-1, to);
+               break;
+       default:                        /* "can't happen" */
+               SETERROR(REG_ASSERT);   /* just in case */
+               break;
+       }
+}
+
+/*
+ - seterr - set an error condition
+ == static int seterr(struct parse *p, int e);
+ */
+static int                     /* useless but makes type checking happy */
+seterr(
+    struct parse *p,
+    int e)
+{
+
+       _DIAGASSERT(p != NULL);
+
+       if (p->error == 0)      /* keep earliest error condition */
+               p->error = e;
+       p->next = nuls;         /* try to bring things to a halt */
+       p->end = nuls;
+       return(0);              /* make the return value well-defined */
+}
+
+/*
+ - allocset - allocate a set of characters for []
+ == static cset *allocset(struct parse *p);
+ */
+static cset *
+allocset(
+    struct parse *p)
+{
+       int no;
+       size_t nc;
+       size_t nbytes;
+       cset *cs;
+       size_t css;
+       int i;
+
+       _DIAGASSERT(p != NULL);
+
+       no = p->g->ncsets++;
+       css = (size_t)p->g->csetsize;
+       if (no >= p->ncsalloc) {        /* need another column of space */
+               p->ncsalloc += CHAR_BIT;
+               nc = p->ncsalloc;
+               assert(nc % CHAR_BIT == 0);
+               nbytes = nc / CHAR_BIT * css;
+               if (p->g->sets == NULL)
+                       p->g->sets = malloc(nc * sizeof(cset));
+               else
+                       p->g->sets = realloc(p->g->sets, nc * sizeof(cset));
+               if (p->g->setbits == NULL)
+                       p->g->setbits = malloc(nbytes);
+               else {
+                       p->g->setbits = realloc(p->g->setbits, nbytes);
+                       /* xxx this isn't right if setbits is now NULL */
+                       for (i = 0; i < no; i++)
+                               p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
+               }
+               if (p->g->sets != NULL && p->g->setbits != NULL)
+                       (void) memset((char *)p->g->setbits + (nbytes - css),
+                                                               0, css);
+               else {
+                       no = 0;
+                       SETERROR(REG_ESPACE);
+                       /* caller's responsibility not to do set ops */
+               }
+       }
+
+       assert(p->g->sets != NULL);     /* xxx */
+       cs = &p->g->sets[no];
+       cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
+       cs->mask = 1 << ((no) % CHAR_BIT);
+       cs->hash = 0;
+       cs->smultis = 0;
+       cs->multis = NULL;
+
+       return(cs);
+}
+
+/*
+ - freeset - free a now-unused set
+ == static void freeset(struct parse *p, cset *cs);
+ */
+static void
+freeset(
+    struct parse *p,
+    cset *cs)
+{
+       size_t i;
+       cset *top;
+       size_t css;
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(cs != NULL);
+
+       top = &p->g->sets[p->g->ncsets];
+       css = (size_t)p->g->csetsize;
+
+       for (i = 0; i < css; i++)
+               CHsub(cs, i);
+       if (cs == top-1)        /* recover only the easy case */
+               p->g->ncsets--;
+}
+
+/*
+ - freezeset - final processing on a set of characters
+ == static int freezeset(struct parse *p, cset *cs);
+ *
+ * The main task here is merging identical sets.  This is usually a waste
+ * of time (although the hash code minimizes the overhead), but can win
+ * big if REG_ICASE is being used.  REG_ICASE, by the way, is why the hash
+ * is done using addition rather than xor -- all ASCII [aA] sets xor to
+ * the same value!
+ */
+static int                     /* set number */
+freezeset(
+    struct parse *p,
+    cset *cs)
+{
+       uch h;
+       size_t i;
+       cset *top;
+       cset *cs2;
+       size_t css;
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(cs != NULL);
+
+       h = cs->hash;
+       top = &p->g->sets[p->g->ncsets];
+       css = (size_t)p->g->csetsize;
+
+       /* look for an earlier one which is the same */
+       for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
+               if (cs2->hash == h && cs2 != cs) {
+                       /* maybe */
+                       for (i = 0; i < css; i++)
+                               if (!!CHIN(cs2, i) != !!CHIN(cs, i))
+                                       break;          /* no */
+                       if (i == css)
+                               break;                  /* yes */
+               }
+
+       if (cs2 < top) {        /* found one */
+               freeset(p, cs);
+               cs = cs2;
+       }
+
+       return((int)(cs - p->g->sets));
+}
+
+/*
+ - firstch - return first character in a set (which must have at least one)
+ == static int firstch(struct parse *p, cset *cs);
+ */
+static int                     /* character; there is no "none" value */
+firstch(
+    struct parse *p,
+    cset *cs)
+{
+       size_t i;
+       size_t css;
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(cs != NULL);
+
+       css = (size_t)p->g->csetsize;
+
+       for (i = 0; i < css; i++)
+               if (CHIN(cs, i))
+                       return((char)i);
+       assert(never);
+       return(0);              /* arbitrary */
+}
+
+/*
+ - nch - number of characters in a set
+ == static int nch(struct parse *p, cset *cs);
+ */
+static int
+nch(
+    struct parse *p,
+    cset *cs)
+{
+       size_t i;
+       size_t css;
+       int n = 0;
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(cs != NULL);
+
+       css = (size_t)p->g->csetsize;
+
+       for (i = 0; i < css; i++)
+               if (CHIN(cs, i))
+                       n++;
+       return(n);
+}
+
+/*
+ - mcadd - add a collating element to a cset
+ == static void mcadd(struct parse *p, cset *cs, \
+ ==    char *cp);
+ */
+static void
+mcadd(
+    struct parse *p,
+    cset *cs,
+    const char *cp)
+{
+       size_t oldend;
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(cs != NULL);
+       _DIAGASSERT(cp != NULL);
+
+       oldend = cs->smultis;
+
+       cs->smultis += strlen(cp) + 1;
+       if (cs->multis == NULL)
+               cs->multis = malloc(cs->smultis);
+       else
+               cs->multis = realloc(cs->multis, cs->smultis);
+       if (cs->multis == NULL) {
+               SETERROR(REG_ESPACE);
+               return;
+       }
+
+       (void) strcpy(cs->multis + oldend - 1, cp);
+       cs->multis[cs->smultis - 1] = '\0';
+}
+
+#if 0
+/*
+ - mcsub - subtract a collating element from a cset
+ == static void mcsub(cset *cs, char *cp);
+ */
+static void
+mcsub(
+    cset *cs,
+    char *cp)
+{
+       char *fp;
+       size_t len;
+
+       _DIAGASSERT(cs != NULL);
+       _DIAGASSERT(cp != NULL);
+
+       fp = mcfind(cs, cp);
+       len = strlen(fp);
+
+       assert(fp != NULL);
+       (void) memmove(fp, fp + len + 1,
+                               cs->smultis - (fp + len + 1 - cs->multis));
+       cs->smultis -= len;
+
+       if (cs->smultis == 0) {
+               free(cs->multis);
+               cs->multis = NULL;
+               return;
+       }
+
+       cs->multis = realloc(cs->multis, cs->smultis);
+       assert(cs->multis != NULL);
+}
+
+/*
+ - mcin - is a collating element in a cset?
+ == static int mcin(cset *cs, char *cp);
+ */
+static int
+mcin(
+    cset *cs,
+    char *cp)
+{
+
+       _DIAGASSERT(cs != NULL);
+       _DIAGASSERT(cp != NULL);
+
+       return(mcfind(cs, cp) != NULL);
+}
+
+/*
+ - mcfind - find a collating element in a cset
+ == static char *mcfind(cset *cs, char *cp);
+ */
+static char *
+mcfind(
+    cset *cs,
+    char *cp)
+{
+       char *p;
+
+       _DIAGASSERT(cs != NULL);
+       _DIAGASSERT(cp != NULL);
+
+       if (cs->multis == NULL)
+               return(NULL);
+       for (p = cs->multis; *p != '\0'; p += strlen(p) + 1)
+               if (strcmp(cp, p) == 0)
+                       return(p);
+       return(NULL);
+}
+#endif
+
+/*
+ - mcinvert - invert the list of collating elements in a cset
+ == static void mcinvert(struct parse *p, cset *cs);
+ *
+ * This would have to know the set of possibilities.  Implementation
+ * is deferred.
+ */
+/* ARGSUSED */
+static void
+mcinvert(
+    struct parse *p,
+    cset *cs)
+{
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(cs != NULL);
+
+       assert(cs->multis == NULL);     /* xxx */
+}
+
+/*
+ - mccase - add case counterparts of the list of collating elements in a cset
+ == static void mccase(struct parse *p, cset *cs);
+ *
+ * This would have to know the set of possibilities.  Implementation
+ * is deferred.
+ */
+/* ARGSUSED */
+static void
+mccase(
+    struct parse *p,
+    cset *cs)
+{
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(cs != NULL);
+
+       assert(cs->multis == NULL);     /* xxx */
+}
+
+/*
+ - isinsets - is this character in any sets?
+ == static int isinsets(struct re_guts *g, int c);
+ */
+static int                     /* predicate */
+isinsets(
+    struct re_guts *g,
+    int c)
+{
+       uch *col;
+       int i;
+       int ncols;
+       unsigned uc = (unsigned char)c;
+
+       _DIAGASSERT(g != NULL);
+
+       ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
+
+       for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
+               if (col[uc] != 0)
+                       return(1);
+       return(0);
+}
+
+/*
+ - samesets - are these two characters in exactly the same sets?
+ == static int samesets(struct re_guts *g, int c1, int c2);
+ */
+static int                     /* predicate */
+samesets(
+    struct re_guts *g,
+    int c1,
+    int c2)
+{
+       uch *col;
+       int i;
+       int ncols;
+       unsigned uc1 = (unsigned char)c1;
+       unsigned uc2 = (unsigned char)c2;
+
+       _DIAGASSERT(g != NULL);
+
+       ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
+
+       for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
+               if (col[uc1] != col[uc2])
+                       return(0);
+       return(1);
+}
+
+/*
+ - categorize - sort out character categories
+ == static void categorize(struct parse *p, struct re_guts *g);
+ */
+static void
+categorize(
+    struct parse *p,
+    struct re_guts *g)
+{
+       cat_t *cats;
+       int c;
+       int c2;
+       cat_t cat;
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(g != NULL);
+
+       cats = g->categories;
+
+       /* avoid making error situations worse */
+       if (p->error != 0)
+               return;
+
+       for (c = CHAR_MIN; c <= CHAR_MAX; c++)
+               if (cats[c] == 0 && isinsets(g, c)) {
+                       cat = g->ncategories++;
+                       cats[c] = cat;
+                       for (c2 = c+1; c2 <= CHAR_MAX; c2++)
+                               if (cats[c2] == 0 && samesets(g, c, c2))
+                                       cats[c2] = cat;
+               }
+}
+
+/*
+ - dupl - emit a duplicate of a bunch of sops
+ == static sopno dupl(struct parse *p, sopno start, sopno finish);
+ */
+static sopno                   /* start of duplicate */
+dupl(
+    struct parse *p,
+    sopno start,                       /* from here */
+    sopno finish)                      /* to this less one */
+{
+       sopno ret;
+       sopno len = finish - start;
+
+       _DIAGASSERT(p != NULL);
+
+       ret = HERE();
+
+       assert(finish >= start);
+       if (len == 0)
+               return(ret);
+       enlarge(p, p->ssize + len);     /* this many unexpected additions */
+       assert(p->ssize >= p->slen + len);
+       (void)memcpy(p->strip + p->slen, p->strip + start,
+           (size_t)len * sizeof(sop));
+       p->slen += len;
+       return(ret);
+}
+
+/*
+ - doemit - emit a strip operator
+ == static void doemit(struct parse *p, sop op, size_t opnd);
+ *
+ * It might seem better to implement this as a macro with a function as
+ * hard-case backup, but it's just too big and messy unless there are
+ * some changes to the data structures.  Maybe later.
+ */
+static void
+doemit(
+    struct parse *p,
+    sop op,
+    sopno opnd)
+{
+
+       _DIAGASSERT(p != NULL);
+
+       /* avoid making error situations worse */
+       if (p->error != 0)
+               return;
+
+       /* deal with oversize operands ("can't happen", more or less) */
+       assert(opnd < 1<<OPSHIFT);
+
+       /* deal with undersized strip */
+       if (p->slen >= p->ssize)
+               enlarge(p, (p->ssize+1) / 2 * 3);       /* +50% */
+       assert(p->slen < p->ssize);
+
+       /* finally, it's all reduced to the easy case */
+       p->strip[p->slen++] = SOP(op, opnd);
+}
+
+/*
+ - doinsert - insert a sop into the strip
+ == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
+ */
+static void
+doinsert(
+    struct parse *p,
+    sop op,
+    sopno opnd,
+    sopno pos)
+{
+       sopno sn;
+       sop s;
+       int i;
+
+       _DIAGASSERT(p != NULL);
+
+       /* avoid making error situations worse */
+       if (p->error != 0)
+               return;
+
+       sn = HERE();
+       EMIT(op, opnd);         /* do checks, ensure space */
+       assert(HERE() == sn+1);
+       s = p->strip[sn];
+
+       /* adjust paren pointers */
+       assert(pos > 0);
+       for (i = 1; i < NPAREN; i++) {
+               if (p->pbegin[i] >= pos) {
+                       p->pbegin[i]++;
+               }
+               if (p->pend[i] >= pos) {
+                       p->pend[i]++;
+               }
+       }
+
+       memmove(&p->strip[pos+1], &p->strip[pos], (HERE()-pos-1)*sizeof(sop));
+       p->strip[pos] = s;
+}
+
+/*
+ - dofwd - complete a forward reference
+ == static void dofwd(struct parse *p, sopno pos, sop value);
+ */
+static void
+dofwd(
+    struct parse *p,
+    sopno pos,
+    sopno value)
+{
+
+       _DIAGASSERT(p != NULL);
+
+       /* avoid making error situations worse */
+       if (p->error != 0)
+               return;
+
+       assert(value < 1<<OPSHIFT);
+       p->strip[pos] = OP(p->strip[pos]) | value;
+}
+
+/*
+ - enlarge - enlarge the strip
+ == static void enlarge(struct parse *p, sopno size);
+ */
+static void
+enlarge(
+    struct parse *p,
+    sopno size)
+{
+       sop *sp;
+
+       _DIAGASSERT(p != NULL);
+
+       if (p->ssize >= size)
+               return;
+
+       sp = (sop *)realloc(p->strip, size*sizeof(sop));
+       if (sp == NULL) {
+               SETERROR(REG_ESPACE);
+               return;
+       }
+       p->strip = sp;
+       p->ssize = size;
+}
+
+/*
+ - stripsnug - compact the strip
+ == static void stripsnug(struct parse *p, struct re_guts *g);
+ */
+static void
+stripsnug(
+    struct parse *p,
+    struct re_guts *g)
+{
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(g != NULL);
+
+       g->nstates = p->slen;
+       g->strip = realloc(p->strip, p->slen * sizeof(sop));
+       if (g->strip == NULL) {
+               SETERROR(REG_ESPACE);
+               g->strip = p->strip;
+       }
+}
+
+/*
+ - findmust - fill in must and mlen with longest mandatory literal string
+ == static void findmust(struct parse *p, struct re_guts *g);
+ *
+ * This algorithm could do fancy things like analyzing the operands of |
+ * for common subsequences.  Someday.  This code is simple and finds most
+ * of the interesting cases.
+ *
+ * Note that must and mlen got initialized during setup.
+ */
+static void
+findmust(
+    struct parse *p,
+    struct re_guts *g)
+{
+       sop *scan;
+       sop *start = NULL;
+       sop *newstart = NULL;
+       sopno newlen;
+       sop s;
+       char *cp;
+       sopno i;
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(g != NULL);
+
+       /* avoid making error situations worse */
+       if (p->error != 0)
+               return;
+
+       /* find the longest OCHAR sequence in strip */
+       newlen = 0;
+       scan = g->strip + 1;
+       do {
+               s = *scan++;
+               switch (OP(s)) {
+               case OCHAR:             /* sequence member */
+                       if (newlen == 0)                /* new sequence */
+                               newstart = scan - 1;
+                       newlen++;
+                       break;
+               case OPLUS_:            /* things that don't break one */
+               case OLPAREN:
+               case ORPAREN:
+                       break;
+               case OQUEST_:           /* things that must be skipped */
+               case OCH_:
+                       scan--;
+                       do {
+                               scan += OPND(s);
+                               s = *scan;
+                               /* assert() interferes w debug printouts */
+                               if (OP(s) != O_QUEST && OP(s) != O_CH &&
+                                                       OP(s) != OOR2) {
+                                       g->iflags |= BAD;
+                                       return;
+                               }
+                       } while (OP(s) != O_QUEST && OP(s) != O_CH);
+                       /* FALLTHROUGH */
+               default:                /* things that break a sequence */
+                       if (newlen > g->mlen) {         /* ends one */
+                               start = newstart;
+                               g->mlen = newlen;
+                       }
+                       newlen = 0;
+                       break;
+               }
+       } while (OP(s) != OEND);
+
+       if (start == NULL)
+               g->mlen = 0;
+
+       if (g->mlen == 0)       /* there isn't one */
+               return;
+
+       /* turn it into a character string */
+       g->must = malloc((size_t)g->mlen + 1);
+       if (g->must == NULL) {          /* argh; just forget it */
+               g->mlen = 0;
+               return;
+       }
+       cp = g->must;
+       scan = start;
+       for (i = g->mlen; i > 0; i--) {
+               while (OP(s = *scan++) != OCHAR)
+                       continue;
+               assert(cp < g->must + g->mlen);
+               *cp++ = (char)OPND(s);
+       }
+       assert(cp == g->must + g->mlen);
+       *cp++ = '\0';           /* just on general principles */
+}
+
+/*
+ - pluscount - count + nesting
+ == static sopno pluscount(struct parse *p, struct re_guts *g);
+ */
+static sopno                   /* nesting depth */
+pluscount(
+    struct parse *p,
+    struct re_guts *g)
+{
+       sop *scan;
+       sop s;
+       sopno plusnest = 0;
+       sopno maxnest = 0;
+
+       _DIAGASSERT(p != NULL);
+       _DIAGASSERT(g != NULL);
+
+       if (p->error != 0)
+               return(0);      /* there may not be an OEND */
+
+       scan = g->strip + 1;
+       do {
+               s = *scan++;
+               switch (OP(s)) {
+               case OPLUS_:
+                       plusnest++;
+                       break;
+               case O_PLUS:
+                       if (plusnest > maxnest)
+                               maxnest = plusnest;
+                       plusnest--;
+                       break;
+               }
+       } while (OP(s) != OEND);
+       if (plusnest != 0)
+               g->iflags |= BAD;
+       return(maxnest);
+}
diff --git a/lib/nbsd_libc/regex/regerror.c b/lib/nbsd_libc/regex/regerror.c
new file mode 100644 (file)
index 0000000..e00d7c0
--- /dev/null
@@ -0,0 +1,223 @@
+/*     $NetBSD: regerror.c,v 1.23 2007/02/09 23:44:18 junyoung Exp $   */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. 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.
+ *
+ *     @(#)regerror.c  8.4 (Berkeley) 3/20/94
+ */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994 Henry Spencer.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ *     @(#)regerror.c  8.4 (Berkeley) 3/20/94
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)regerror.c 8.4 (Berkeley) 3/20/94";
+#else
+__RCSID("$NetBSD: regerror.c,v 1.23 2007/02/09 23:44:18 junyoung Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <regex.h>
+
+#ifdef __weak_alias
+__weak_alias(regerror,_regerror)
+#endif
+
+#include "utils.h"
+
+/* ========= begin header generated by ./mkh ========= */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* === regerror.c === */
+static const char *regatoi(const regex_t *preg, char *localbuf, size_t buflen);
+
+#ifdef __cplusplus
+}
+#endif
+/* ========= end header generated by ./mkh ========= */
+/*
+ = #define     REG_NOMATCH      1
+ = #define     REG_BADPAT       2
+ = #define     REG_ECOLLATE     3
+ = #define     REG_ECTYPE       4
+ = #define     REG_EESCAPE      5
+ = #define     REG_ESUBREG      6
+ = #define     REG_EBRACK       7
+ = #define     REG_EPAREN       8
+ = #define     REG_EBRACE       9
+ = #define     REG_BADBR       10
+ = #define     REG_ERANGE      11
+ = #define     REG_ESPACE      12
+ = #define     REG_BADRPT      13
+ = #define     REG_EMPTY       14
+ = #define     REG_ASSERT      15
+ = #define     REG_INVARG      16
+ = #define     REG_ATOI        255     // convert name to number (!)
+ = #define     REG_ITOA        0400    // convert number to name (!)
+ */
+static const struct rerr {
+       int code;
+       const char *name;
+       const char *explain;
+} rerrs[] = {
+       { REG_NOMATCH,  "REG_NOMATCH",  "regexec() failed to match" },
+       { REG_BADPAT,   "REG_BADPAT",   "invalid regular expression" },
+       { REG_ECOLLATE, "REG_ECOLLATE", "invalid collating element" },
+       { REG_ECTYPE,   "REG_ECTYPE",   "invalid character class" },
+       { REG_EESCAPE,  "REG_EESCAPE",  "trailing backslash (\\)" },
+       { REG_ESUBREG,  "REG_ESUBREG",  "invalid backreference number" },
+       { REG_EBRACK,   "REG_EBRACK",   "brackets ([ ]) not balanced" },
+       { REG_EPAREN,   "REG_EPAREN",   "parentheses not balanced" },
+       { REG_EBRACE,   "REG_EBRACE",   "braces not balanced" },
+       { REG_BADBR,    "REG_BADBR",    "invalid repetition count(s)" },
+       { REG_ERANGE,   "REG_ERANGE",   "invalid character range" },
+       { REG_ESPACE,   "REG_ESPACE",   "out of memory" },
+       { REG_BADRPT,   "REG_BADRPT",   "repetition-operator operand invalid" },
+       { REG_EMPTY,    "REG_EMPTY",    "empty (sub)expression" },
+       { REG_ASSERT,   "REG_ASSERT",   "\"can't happen\" -- you found a bug" },
+       { REG_INVARG,   "REG_INVARG",   "invalid argument to regex routine" },
+       { 0,            "",             "*** unknown regexp error code ***" }
+};
+
+/*
+ * regerror - the interface to error numbers
+ * extern size_t regerror(int, const regex_t *, char *, size_t);
+ */
+/* ARGSUSED */
+size_t
+regerror(
+    int errcode,
+    const regex_t *preg,
+    char *errbuf,
+    size_t errbuf_size)
+{
+       const struct rerr *r;
+       size_t len;
+       int target = errcode &~ REG_ITOA;
+       const char *s;
+       char convbuf[50];
+
+       _DIAGASSERT(errcode != REG_ATOI || preg != NULL);
+       _DIAGASSERT(errbuf != NULL);
+
+       if (errcode == REG_ATOI)
+               s = regatoi(preg, convbuf, sizeof convbuf);
+       else {
+               for (r = rerrs; r->code != 0; r++)
+                       if (r->code == target)
+                               break;
+       
+               if (errcode & REG_ITOA) {
+                       if (r->code != 0) {
+                               (void)strlcpy(convbuf, r->name, sizeof convbuf);
+                       } else
+                               (void)snprintf(convbuf, sizeof convbuf,
+                                   "REG_0x%x", target);
+                       s = convbuf;
+               } else
+                       s = r->explain;
+       }
+
+       len = strlen(s) + 1;
+       if (errbuf_size > 0)
+               (void)strlcpy(errbuf, s, errbuf_size);
+
+       return(len);
+}
+
+/*
+ * regatoi - internal routine to implement REG_ATOI
+ * static const char *regatoi(const regex_t *preg, char *localbuf,
+ * size_t buflen);
+ */
+static const char *
+regatoi(
+    const regex_t *preg,
+    char *localbuf,
+    size_t buflen)
+{
+       const struct rerr *r;
+
+       for (r = rerrs; r->code != 0; r++)
+               if (strcmp(r->name, preg->re_endp) == 0)
+                       break;
+       if (r->code == 0)
+               return "0";
+
+       (void)snprintf(localbuf, buflen, "%d", r->code);
+       return localbuf;
+}
diff --git a/lib/nbsd_libc/regex/regex.3 b/lib/nbsd_libc/regex/regex.3
new file mode 100644 (file)
index 0000000..dae8e17
--- /dev/null
@@ -0,0 +1,631 @@
+.\"    $NetBSD: regex.3,v 1.21 2010/03/22 19:30:54 joerg Exp $
+.\"
+.\" Copyright (c) 1992, 1993, 1994
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Henry Spencer.
+.\"
+.\" 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. 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.
+.\"
+.\" Copyright (c) 1992, 1993, 1994 Henry Spencer.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Henry Spencer.
+.\"
+.\" 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. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"    This product includes software developed by the University of
+.\"    California, Berkeley and its contributors.
+.\" 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.
+.\"
+.\"    @(#)regex.3     8.4 (Berkeley) 3/20/94
+.\"
+.Dd December 29, 2003
+.Dt REGEX 3
+.Os
+.Sh NAME
+.Nm regex ,
+.Nm regcomp ,
+.Nm regexec ,
+.Nm regerror ,
+.Nm regfree
+.Nd regular-expression library
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In regex.h
+.Ft int
+.Fn regcomp "regex_t * restrict preg" "const char * restrict pattern" "int cflags"
+.Ft int
+.Fn regexec "const regex_t * restrict preg" "const char * restrict string" "size_t nmatch" "regmatch_t pmatch[]" "int eflags"
+.Ft size_t
+.Fn regerror "int errcode" "const regex_t * restrict preg" "char * restrict errbuf" "size_t errbuf_size"
+.Ft void
+.Fn regfree "regex_t *preg"
+.Sh DESCRIPTION
+These routines implement
+.St -p1003.2-92
+regular expressions (``RE''s);
+see
+.Xr re_format 7 .
+.Fn regcomp
+compiles an RE written as a string into an internal form,
+.Fn regexec
+matches that internal form against a string and reports results,
+.Fn regerror
+transforms error codes from either into human-readable messages,
+and
+.Fn regfree
+frees any dynamically-allocated storage used by the internal form
+of an RE.
+.Pp
+The header
+.In regex.h
+declares two structure types,
+.Fa regex_t
+and
+.Fa regmatch_t ,
+the former for compiled internal forms and the latter for match reporting.
+It also declares the four functions,
+a type
+.Fa regoff_t ,
+and a number of constants with names starting with ``REG_''.
+.Pp
+.Fn regcomp
+compiles the regular expression contained in the
+.Fa pattern
+string,
+subject to the flags in
+.Fa cflags ,
+and places the results in the
+.Fa regex_t
+structure pointed to by
+.Fa preg .
+.Fa cflags
+is the bitwise OR of zero or more of the following flags:
+.Bl -tag -width XXXREG_EXTENDED
+.It Dv REG_EXTENDED
+Compile modern (``extended'') REs, rather than the obsolete
+(``basic'') REs that are the default.
+.It Dv REG_BASIC
+This is a synonym for 0,
+provided as a counterpart to REG_EXTENDED to improve readability.
+.It Dv REG_NOSPEC
+Compile with recognition of all special characters turned off.
+All characters are thus considered ordinary, so the ``RE'' is a literal
+string.
+This is an extension, compatible with but not specified by
+.St -p1003.2-92 ,
+and should be used with caution in software intended to be portable to
+other systems.
+.Dv REG_EXTENDED
+and
+.Dv REG_NOSPEC
+may not be used in the same call to
+.Fn regcomp .
+.It Dv REG_ICASE
+Compile for matching that ignores upper/lower case distinctions.
+See
+.Xr re_format 7 .
+.It Dv REG_NOSUB
+Compile for matching that need only report success or failure, not
+what was matched.
+.It Dv REG_NEWLINE
+Compile for newline-sensitive matching.
+By default, newline is a completely ordinary character with no special
+meaning in either REs or strings.
+With this flag,
+`[^' bracket expressions and `.' never match newline,
+a `^' anchor matches the null string after any newline in the string
+in addition to its normal function,
+and the `$' anchor matches the null string before any newline in the
+string in addition to its normal function.
+.It Dv REG_PEND
+The regular expression ends, not at the first NUL, but just before the
+character pointed to by the
+.Fa re_endp
+member of the structure pointed to by
+.Fa preg .
+The
+.Fa re_endp
+member is of type
+.Fa "const\ char\ *" .
+This flag permits inclusion of NULs in the RE; they are considered
+ordinary characters.
+This is an extension, compatible with but not specified by
+.St -p1003.2-92 ,
+and should be used with caution in software intended to be portable to
+other systems.
+.El
+.Pp
+When successful,
+.Fn regcomp
+returns 0 and fills in the structure pointed to by
+.Fa preg .
+One member of that structure (other than
+.Fa re_endp )
+is publicized:
+.Fa re_nsub ,
+of type
+.Fa size_t ,
+contains the number of parenthesized subexpressions within the RE
+(except that the value of this member is undefined if the
+.Dv REG_NOSUB
+flag was used).
+If
+.Fn regcomp
+fails, it returns a non-zero error code;
+see
+.Sx DIAGNOSTICS .
+.Pp
+.Fn regexec
+matches the compiled RE pointed to by
+.Fa preg
+against the
+.Fa string ,
+subject to the flags in
+.Fa eflags ,
+and reports results using
+.Fa nmatch ,
+.Fa pmatch ,
+and the returned value.
+The RE must have been compiled by a previous invocation of
+.Fn regcomp .
+The compiled form is not altered during execution of
+.Fn regexec ,
+so a single compiled RE can be used simultaneously by multiple threads.
+.Pp
+By default,
+the NUL-terminated string pointed to by
+.Fa string
+is considered to be the text of an entire line, minus any terminating
+newline.
+The
+.Fa eflags
+argument is the bitwise OR of zero or more of the following flags:
+.Bl -tag -width XXXREG_NOTBOL
+.It Dv REG_NOTBOL
+The first character of the string
+is not the beginning of a line, so the `^' anchor should not match before it.
+This does not affect the behavior of newlines under
+.Dv REG_NEWLINE .
+.It Dv REG_NOTEOL
+The NUL terminating the string does not end a line, so the `$' anchor
+should not match before it.
+This does not affect the behavior of newlines under
+.Dv REG_NEWLINE .
+.It Dv REG_STARTEND
+The string is considered to start at
+.Fa string
++
+.Fa pmatch[0].rm_so
+and to have a terminating NUL located at
+.Fa string
++
+.Fa pmatch[0].rm_eo
+(there need not actually be a NUL at that location),
+regardless of the value of
+.Fa nmatch .
+See below for the definition of
+.Fa pmatch
+and
+.Fa nmatch .
+This is an extension, compatible with but not specified by
+.St -p1003.2-92 ,
+and should be used with caution in software intended to be portable to
+other systems.
+Note that a non-zero
+.Fa rm_so
+does not imply
+.Dv REG_NOTBOL ;
+.Dv REG_STARTEND
+affects only the location of the string, not how it is matched.
+.El
+.Pp
+See
+.Xr re_format 7
+for a discussion of what is matched in situations where an RE or a
+portion thereof could match any of several substrings of
+.Fa string .
+.Pp
+Normally,
+.Fn regexec
+returns 0 for success and the non-zero code
+.Dv REG_NOMATCH
+for failure.
+Other non-zero error codes may be returned in exceptional situations;
+see
+.Sx DIAGNOSTICS .
+.Pp
+If
+.Dv REG_NOSUB
+was specified in the compilation of the RE, or if
+.Fa nmatch
+is 0,
+.Fn regexec
+ignores the
+.Fa pmatch
+argument (but see below for the case where
+.Dv REG_STARTEND
+is specified).
+Otherwise,
+.Fa pmatch
+points to an array of
+.Fa nmatch
+structures of type
+.Fa regmatch_t .
+Such a structure has at least the members
+.Fa rm_so
+and
+.Fa rm_eo ,
+both of type
+.Fa regoff_t
+(a signed arithmetic type at least as large as an
+.Fa off_t
+and a
+.Fa ssize_t ) ,
+containing respectively the offset of the first character of a substring
+and the offset of the first character after the end of the substring.
+Offsets are measured from the beginning of the
+.Fa string
+argument given to
+.Fn regexec .
+An empty substring is denoted by equal offsets,
+both indicating the character following the empty substring.
+.Pp
+The 0th member of the
+.Fa pmatch
+array is filled in to indicate what substring of
+.Fa string
+was matched by the entire RE.
+Remaining members report what substring was matched by parenthesized
+subexpressions within the RE;
+member
+.Fa i
+reports subexpression
+.Fa i ,
+with subexpressions counted (starting at 1) by the order of their
+opening parentheses in the RE, left to right.
+Unused entries in the array\(emcorresponding either to subexpressions that
+did not participate in the match at all, or to subexpressions that do not
+exist in the RE (that is,
+.Fa i
+\*[Gt]
+.Fa preg-\*[Gt]re_nsub )
+\(emhave both
+.Fa rm_so
+and
+.Fa rm_eo
+set to -1.
+If a subexpression participated in the match several times,
+the reported substring is the last one it matched.
+(Note, as an example in particular, that when the RE `(b*)+' matches `bbb',
+the parenthesized subexpression matches each of the three `b's and then
+an infinite number of empty strings following the last `b',
+so the reported substring is one of the empties.)
+.Pp
+If
+.Dv REG_STARTEND
+is specified,
+.Fa pmatch
+must point to at least one
+.Fa regmatch_t
+(even if
+.Fa nmatch
+is 0 or
+.Dv REG_NOSUB
+was specified),
+to hold the input offsets for
+.Dv REG_STARTEND .
+Use for output is still entirely controlled by
+.Fa nmatch ;
+if
+.Fa nmatch
+is 0 or
+.Dv REG_NOSUB
+was specified,
+the value of
+.Fa pmatch [0]
+will not be changed by a successful
+.Fn regexec .
+.Pp
+.Fn regerror
+maps a non-zero
+.Fa errcode
+from either
+.Fn regcomp
+or
+.Fn regexec
+to a human-readable, printable message.
+If
+.Fa preg
+is non-NULL,
+the error code should have arisen from use of the
+.Fa regex_t
+pointed to by
+.Fa preg ,
+and if the error code came from
+.Fn regcomp ,
+it should have been the result from the most recent
+.Fn regcomp
+using that
+.Fa regex_t . (
+.Fn regerror
+may be able to supply a more detailed message using information
+from the
+.Fa regex_t . )
+.Fn regerror
+places the NUL-terminated message into the buffer pointed to by
+.Fa errbuf ,
+limiting the length (including the NUL) to at most
+.Fa errbuf_size
+bytes.
+If the whole message won't fit,
+as much of it as will fit before the terminating NUL is supplied.
+In any case,
+the returned value is the size of buffer needed to hold the whole
+message (including terminating NUL).
+If
+.Fa errbuf_size
+is 0,
+.Fa errbuf
+is ignored but the return value is still correct.
+.Pp
+If the
+.Fa errcode
+given to
+.Fn regerror
+is first ORed with
+.Dv REG_ITOA ,
+the ``message'' that results is the printable name of the error code,
+e.g. ``REG_NOMATCH'',
+rather than an explanation thereof.
+If
+.Fa errcode
+is
+.Dv REG_ATOI ,
+then
+.Fa preg
+shall be non-NULL and the
+.Fa re_endp
+member of the structure it points to
+must point to the printable name of an error code;
+in this case, the result in
+.Fa errbuf
+is the decimal digits of
+the numeric value of the error code
+(0 if the name is not recognized).
+.Dv REG_ITOA
+and
+.Dv REG_ATOI
+are intended primarily as debugging facilities;
+they are extensions, compatible with but not specified by
+.St -p1003.2-92 ,
+and should be used with caution in software intended to be portable to
+other systems.
+Be warned also that they are considered experimental and changes are possible.
+.Pp
+.Fn regfree
+frees any dynamically-allocated storage associated with the compiled RE
+pointed to by
+.Fa preg .
+The remaining
+.Fa regex_t
+is no longer a valid compiled RE
+and the effect of supplying it to
+.Fn regexec
+or
+.Fn regerror
+is undefined.
+.Pp
+None of these functions references global variables except for tables
+of constants;
+all are safe for use from multiple threads if the arguments are safe.
+.Sh IMPLEMENTATION CHOICES
+There are a number of decisions that
+.St -p1003.2-92
+leaves up to the implementor,
+either by explicitly saying ``undefined'' or by virtue of them being
+forbidden by the RE grammar.
+This implementation treats them as follows.
+.Pp
+See
+.Xr re_format 7
+for a discussion of the definition of case-independent matching.
+.Pp
+There is no particular limit on the length of REs,
+except insofar as memory is limited.
+Memory usage is approximately linear in RE size, and largely insensitive
+to RE complexity, except for bounded repetitions.
+See BUGS for one short RE using them
+that will run almost any system out of memory.
+.Pp
+A backslashed character other than one specifically given a magic meaning
+by
+.St -p1003.2-92
+(such magic meanings occur only in obsolete [``basic''] REs)
+is taken as an ordinary character.
+.Pp
+Any unmatched [ is a
+.Dv REG_EBRACK
+error.
+.Pp
+Equivalence classes cannot begin or end bracket-expression ranges.
+The endpoint of one range cannot begin another.
+.Pp
+.Dv RE_DUP_MAX ,
+the limit on repetition counts in bounded repetitions, is 255.
+.Pp
+A repetition operator (?, *, +, or bounds) cannot follow another
+repetition operator.
+A repetition operator cannot begin an expression or subexpression
+or follow `^' or `|'.
+.Pp
+`|' cannot appear first or last in a (sub)expression or after another `|',
+i.e. an operand of `|' cannot be an empty subexpression.
+An empty parenthesized subexpression, `()', is legal and matches an
+empty (sub)string.
+An empty string is not a legal RE.
+.Pp
+A `{' followed by a digit is considered the beginning of bounds for a
+bounded repetition, which must then follow the syntax for bounds.
+A `{'
+.Em not
+followed by a digit is considered an ordinary character.
+.Pp
+`^' and `$' beginning and ending subexpressions in obsolete (``basic'')
+REs are anchors, not ordinary characters.
+.Sh DIAGNOSTICS
+Non-zero error codes from
+.Fn regcomp
+and
+.Fn regexec
+include the following:
+.Pp
+.Bl -tag -width XXXREG_ECOLLATE -compact
+.It Dv REG_NOMATCH
+.Fn regexec
+failed to match
+.It Dv REG_BADPAT
+invalid regular expression
+.It Dv REG_ECOLLATE
+invalid collating element
+.It Dv REG_ECTYPE
+invalid character class
+.It Dv REG_EESCAPE
+\e applied to unescapable character
+.It Dv REG_ESUBREG
+invalid backreference number
+.It Dv REG_EBRACK
+brackets [ ] not balanced
+.It Dv REG_EPAREN
+parentheses ( ) not balanced
+.It Dv REG_EBRACE
+braces { } not balanced
+.It Dv REG_BADBR
+invalid repetition count(s) in { }
+.It Dv REG_ERANGE
+invalid character range in [ ]
+.It Dv REG_ESPACE
+ran out of memory
+.It Dv REG_BADRPT
+?, *, or + operand invalid
+.It Dv REG_EMPTY
+empty (sub)expression
+.It Dv REG_ASSERT
+``can't happen''\(emyou found a bug
+.It Dv REG_INVARG
+invalid argument, e.g. negative-length string
+.El
+.Sh SEE ALSO
+.Xr grep 1 ,
+.Xr sed 1 ,
+.Xr re_format 7
+.Pp
+.St -p1003.2-92 ,
+sections 2.8 (Regular Expression Notation)
+and
+B.5 (C Binding for Regular Expression Matching).
+.Sh HISTORY
+Originally written by Henry Spencer.
+Altered for inclusion in the
+.Bx 4.4
+distribution.
+.Sh BUGS
+There is one known functionality bug.
+The implementation of internationalization is incomplete:
+the locale is always assumed to be the default one of
+.St -p1003.2-92 ,
+and only the collating elements etc. of that locale are available.
+.Pp
+The back-reference code is subtle and doubts linger about its correctness
+in complex cases.
+.Pp
+.Fn regexec
+performance is poor.
+This will improve with later releases.
+.Fa nmatch
+exceeding 0 is expensive;
+.Fa nmatch
+exceeding 1 is worse.
+.Fa regexec
+is largely insensitive to RE complexity
+.Em except
+that back references are massively expensive.
+RE length does matter; in particular, there is a strong speed bonus
+for keeping RE length under about 30 characters,
+with most special characters counting roughly double.
+.Pp
+.Fn regcomp
+implements bounded repetitions by macro expansion,
+which is costly in time and space if counts are large
+or bounded repetitions are nested.
+An RE like, say,
+`((((a{1,100}){1,100}){1,100}){1,100}){1,100}'
+will (eventually) run almost any existing machine out of swap space.
+.Pp
+There are suspected problems with response to obscure error conditions.
+Notably,
+certain kinds of internal overflow,
+produced only by truly enormous REs or by multiply nested bounded repetitions,
+are probably not handled well.
+.Pp
+Due to a mistake in
+.St -p1003.2-92 ,
+things like `a)b' are legal REs because `)' is a special character
+only in the presence of a previous unmatched `('.
+This can't be fixed until the spec is fixed.
+.Pp
+The standard's definition of back references is vague.
+For example, does
+`a\e(\e(b\e)*\e2\e)*d' match `abbbd'?
+Until the standard is clarified, behavior in such cases should not be
+relied on.
+.Pp
+The implementation of word-boundary matching is a bit of a kludge,
+and bugs may lurk in combinations of word-boundary matching and anchoring.
diff --git a/lib/nbsd_libc/regex/regex2.h b/lib/nbsd_libc/regex/regex2.h
new file mode 100644 (file)
index 0000000..0fdbe74
--- /dev/null
@@ -0,0 +1,209 @@
+/*     $NetBSD: regex2.h,v 1.12 2009/02/12 05:06:54 lukem Exp $        */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. 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.
+ *
+ *     @(#)regex2.h    8.4 (Berkeley) 3/20/94
+ */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994 Henry Spencer.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ *     @(#)regex2.h    8.4 (Berkeley) 3/20/94
+ */
+
+/*
+ * First, the stuff that ends up in the outside-world include file
+ = typedef off_t regoff_t;
+ = typedef struct {
+ =     int re_magic;
+ =     size_t re_nsub;         // number of parenthesized subexpressions
+ =     const char *re_endp;    // end pointer for REG_PEND
+ =     struct re_guts *re_g;   // none of your business :-)
+ = } regex_t;
+ = typedef struct {
+ =     regoff_t rm_so;         // start of match
+ =     regoff_t rm_eo;         // end of match
+ = } regmatch_t;
+ */
+/*
+ * internals of regex_t
+ */
+#define        MAGIC1  ((('r'^0200)<<8) | 'e')
+
+/*
+ * The internal representation is a *strip*, a sequence of
+ * operators ending with an endmarker.  (Some terminology etc. is a
+ * historical relic of earlier versions which used multiple strips.)
+ * Certain oddities in the representation are there to permit running
+ * the machinery backwards; in particular, any deviation from sequential
+ * flow must be marked at both its source and its destination.  Some
+ * fine points:
+ *
+ * - OPLUS_ and O_PLUS are *inside* the loop they create.
+ * - OQUEST_ and O_QUEST are *outside* the bypass they create.
+ * - OCH_ and O_CH are *outside* the multi-way branch they create, while
+ *   OOR1 and OOR2 are respectively the end and the beginning of one of
+ *   the branches.  Note that there is an implicit OOR2 following OCH_
+ *   and an implicit OOR1 preceding O_CH.
+ *
+ * In state representations, an operator's bit is on to signify a state
+ * immediately *preceding* "execution" of that operator.
+ */
+typedef u_int32_t sop; /* strip operator */
+typedef int sopno;
+#define        OPRMASK ((u_int32_t)0xf8000000UL)
+#define        OPDMASK ((u_int32_t)0x07ffffffUL)
+#define        OPSHIFT ((unsigned)27)
+#define        OP(n)   ((n)&OPRMASK)
+#define        OPND(n) ((int)((n)&OPDMASK))
+#define        SOP(op, opnd)   ((op)|(opnd))
+
+#define OPC(n) (((u_int32_t)(n))<<OPSHIFT)
+/* operators              meaning      operand                 */
+/*                                     (back, fwd are offsets) */
+#define        OEND    OPC(1)  /* endmarker    -                       */
+#define        OCHAR   OPC(2)  /* character    unsigned char           */
+#define        OBOL    OPC(3)  /* left anchor  -                       */
+#define        OEOL    OPC(4)  /* right anchor -                       */
+#define        OANY    OPC(5)  /* .            -                       */
+#define        OANYOF  OPC(6)  /* [...]        set number              */
+#define        OBACK_  OPC(7)  /* begin \d     paren number            */
+#define        O_BACK  OPC(8)  /* end \d       paren number            */
+#define        OPLUS_  OPC(9)  /* + prefix     fwd to suffix           */
+#define        O_PLUS  OPC(10) /* + suffix     back to prefix          */
+#define        OQUEST_ OPC(11) /* ? prefix     fwd to suffix           */
+#define        O_QUEST OPC(12) /* ? suffix     back to prefix          */
+#define        OLPAREN OPC(13) /* (            fwd to )                */
+#define        ORPAREN OPC(14) /* )            back to (               */
+#define        OCH_    OPC(15) /* begin choice fwd to OOR2             */
+#define        OOR1    OPC(16) /* | pt. 1      back to OOR1 or OCH_    */
+#define        OOR2    OPC(17) /* | pt. 2      fwd to OOR2 or O_CH     */
+#define        O_CH    OPC(18) /* end choice   back to OOR1            */
+#define        OBOW    OPC(19) /* begin word   -                       */
+#define        OEOW    OPC(20) /* end word     -                       */
+
+/*
+ * Structure for [] character-set representation.  Character sets are
+ * done as bit vectors, grouped 8 to a byte vector for compactness.
+ * The individual set therefore has both a pointer to the byte vector
+ * and a mask to pick out the relevant bit of each byte.  A hash code
+ * simplifies testing whether two sets could be identical.
+ *
+ * This will get trickier for multicharacter collating elements.  As
+ * preliminary hooks for dealing with such things, we also carry along
+ * a string of multi-character elements, and decide the size of the
+ * vectors at run time.
+ */
+typedef struct {
+       uch *ptr;               /* -> uch [csetsize] */
+       uch mask;               /* bit within array */
+       uch hash;               /* hash code */
+       size_t smultis;
+       char *multis;           /* -> char[smulti]  ab\0cd\0ef\0\0 */
+} cset;
+/* note that CHadd and CHsub are unsafe, and CHIN doesn't yield 0/1 */
+#define        CHadd(cs, c)    ((cs)->ptr[(uch)(c)] |= (cs)->mask, (cs)->hash += (c))
+#define        CHsub(cs, c)    ((cs)->ptr[(uch)(c)] &= ~(cs)->mask, (cs)->hash -= (c))
+#define        CHIN(cs, c)     ((cs)->ptr[(uch)(c)] & (cs)->mask)
+#define        MCadd(p, cs, cp)        mcadd(p, cs, cp)        /* regcomp() internal fns */
+#define        MCsub(p, cs, cp)        mcsub(p, cs, cp)
+#define        MCin(p, cs, cp) mcin(p, cs, cp)
+
+/* stuff for character categories */
+typedef unsigned char cat_t;
+
+/*
+ * main compiled-expression structure
+ */
+struct re_guts {
+       int magic;
+#              define  MAGIC2  ((('R'^0200)<<8)|'E')
+       sop *strip;             /* malloced area for strip */
+       int csetsize;           /* number of bits in a cset vector */
+       int ncsets;             /* number of csets in use */
+       cset *sets;             /* -> cset [ncsets] */
+       uch *setbits;           /* -> uch[csetsize][ncsets/CHAR_BIT] */
+       int cflags;             /* copy of regcomp() cflags argument */
+       sopno nstates;          /* = number of sops */
+       sopno firststate;       /* the initial OEND (normally 0) */
+       sopno laststate;        /* the final OEND */
+       int iflags;             /* internal flags */
+#              define  USEBOL  01      /* used ^ */
+#              define  USEEOL  02      /* used $ */
+#              define  BAD     04      /* something wrong */
+       int nbol;               /* number of ^ used */
+       int neol;               /* number of $ used */
+       int ncategories;        /* how many character categories */
+       cat_t *categories;      /* ->catspace[-CHAR_MIN] */
+       char *must;             /* match must contain this string */
+       int mlen;               /* length of must */
+       size_t nsub;            /* copy of re_nsub */
+       int backrefs;           /* does it use back references? */
+       sopno nplus;            /* how deep does it nest +s? */
+       /* catspace must be last */
+       cat_t catspace[1];      /* actually [NC] */
+};
+
+/* misc utilities */
+#define        OUT     (CHAR_MAX+1)    /* a non-character value */
+#define        ISWORD(c)       (isalnum((unsigned char)c) || (c) == '_')
diff --git a/lib/nbsd_libc/regex/regexec.c b/lib/nbsd_libc/regex/regexec.c
new file mode 100644 (file)
index 0000000..d0e1084
--- /dev/null
@@ -0,0 +1,234 @@
+/*     $NetBSD: regexec.c,v 1.21 2009/02/12 05:06:54 lukem Exp $       */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. 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.
+ *
+ *     @(#)regexec.c   8.3 (Berkeley) 3/20/94
+ */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994 Henry Spencer.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ *     @(#)regexec.c   8.3 (Berkeley) 3/20/94
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)regexec.c  8.3 (Berkeley) 3/20/94";
+#else
+__RCSID("$NetBSD: regexec.c,v 1.21 2009/02/12 05:06:54 lukem Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * the outer shell of regexec()
+ *
+ * This file includes engine.c *twice*, after muchos fiddling with the
+ * macros that code uses.  This lets the same code operate on two different
+ * representations for state sets.
+ */
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <regex.h>
+
+#ifdef __weak_alias
+__weak_alias(regexec,_regexec)
+#endif
+
+#include "utils.h"
+#include "regex2.h"
+
+/* macros for manipulating states, small version */
+#define        states  unsigned long
+#define        states1 unsigned long   /* for later use in regexec() decision */
+#define        CLEAR(v)        ((v) = 0)
+#define        SET0(v, n)      ((v) &= ~((unsigned long)1 << (n)))
+#define        SET1(v, n)      ((v) |= (unsigned long)1 << (n))
+#define        ISSET(v, n)     (((v) & ((unsigned long)1 << (n))) != 0)
+#define        ASSIGN(d, s)    ((d) = (s))
+#define        EQ(a, b)        ((a) == (b))
+#define        STATEVARS       int dummy       /* dummy version */
+#define        STATESETUP(m, n)        /* nothing */
+#define        STATETEARDOWN(m)        /* nothing */
+#define        SETUP(v)        ((v) = 0)
+#define        onestate        unsigned long
+#define        INIT(o, n)      ((o) = (unsigned long)1 << (n))
+#define        INC(o)  ((o) <<= 1)
+#define        ISSTATEIN(v, o) (((v) & (o)) != 0)
+/* some abbreviations; note that some of these know variable names! */
+/* do "if I'm here, I can also be there" etc without branches */
+#define        FWD(dst, src, n)        ((dst) |= ((unsigned long)(src)&(here)) << (n))
+#define        BACK(dst, src, n)       ((dst) |= ((unsigned long)(src)&(here)) >> (n))
+#define        ISSETBACK(v, n) (((v) & ((unsigned long)here >> (n))) != 0)
+/* function names */
+#define SNAMES                 /* engine.c looks after details */
+
+#include "engine.c"
+
+/* now undo things */
+#undef states
+#undef CLEAR
+#undef SET0
+#undef SET1
+#undef ISSET
+#undef ASSIGN
+#undef EQ
+#undef STATEVARS
+#undef STATESETUP
+#undef STATETEARDOWN
+#undef SETUP
+#undef onestate
+#undef INIT
+#undef INC
+#undef ISSTATEIN
+#undef FWD
+#undef BACK
+#undef ISSETBACK
+#undef SNAMES
+
+/* macros for manipulating states, large version */
+#define        states  char *
+#define        CLEAR(v)        memset(v, 0, (size_t)m->g->nstates)
+#define        SET0(v, n)      ((v)[n] = 0)
+#define        SET1(v, n)      ((v)[n] = 1)
+#define        ISSET(v, n)     ((v)[n])
+#define        ASSIGN(d, s)    memcpy(d, s, (size_t)m->g->nstates)
+#define        EQ(a, b)        (memcmp(a, b, (size_t)m->g->nstates) == 0)
+#define        STATEVARS       int vn; char *space
+#define        STATESETUP(m, nv) \
+    if (((m)->space = malloc((size_t)((nv)*(m)->g->nstates))) == NULL) \
+       return(REG_ESPACE); \
+    else \
+       (m)->vn = 0
+
+#define        STATETEARDOWN(m)        { free((m)->space); m->space = NULL; }
+#define        SETUP(v)        ((v) = &m->space[(size_t)(m->vn++ * m->g->nstates)])
+#define        onestate        int
+#define        INIT(o, n)      ((o) = (n))
+#define        INC(o)  ((o)++)
+#define        ISSTATEIN(v, o) ((v)[o])
+/* some abbreviations; note that some of these know variable names! */
+/* do "if I'm here, I can also be there" etc without branches */
+#define        FWD(dst, src, n)        ((dst)[here+(n)] |= (src)[here])
+#define        BACK(dst, src, n)       ((dst)[here-(n)] |= (src)[here])
+#define        ISSETBACK(v, n) ((v)[here - (n)])
+/* function names */
+#define        LNAMES                  /* flag */
+
+#include "engine.c"
+
+/*
+ - regexec - interface for matching
+ = extern int regexec(const regex_t *, const char *, size_t, \
+ =                                     regmatch_t [], int);
+ = #define     REG_NOTBOL      00001
+ = #define     REG_NOTEOL      00002
+ = #define     REG_STARTEND    00004
+ = #define     REG_TRACE       00400   // tracing of execution
+ = #define     REG_LARGE       01000   // force large representation
+ = #define     REG_BACKR       02000   // force use of backref code
+ *
+ * We put this here so we can exploit knowledge of the state representation
+ * when choosing which matcher to call.  Also, by this point the matchers
+ * have been prototyped.
+ */
+int                            /* 0 success, REG_NOMATCH failure */
+regexec(
+    const regex_t *preg,
+    const char *string,
+    size_t nmatch,
+    regmatch_t pmatch[],
+    int eflags)
+{
+       struct re_guts *g = preg->re_g;
+       char *s;
+#ifdef REDEBUG
+#      define  GOODFLAGS(f)    (f)
+#else
+#      define  GOODFLAGS(f)    ((f)&(REG_NOTBOL|REG_NOTEOL|REG_STARTEND))
+#endif
+
+       _DIAGASSERT(preg != NULL);
+       _DIAGASSERT(string != NULL);
+
+       if (preg->re_magic != MAGIC1 || g->magic != MAGIC2)
+               return(REG_BADPAT);
+       assert(!(g->iflags&BAD));
+       if (g->iflags&BAD)              /* backstop for no-debug case */
+               return(REG_BADPAT);
+       eflags = GOODFLAGS(eflags);
+
+       s = __UNCONST(string);
+
+       if (g->nstates <= (sopno)(CHAR_BIT*sizeof(states1)) && !(eflags&REG_LARGE))
+               return(smatcher(g, s, nmatch, pmatch, eflags));
+       else
+               return(lmatcher(g, s, nmatch, pmatch, eflags));
+}
diff --git a/lib/nbsd_libc/regex/regfree.c b/lib/nbsd_libc/regex/regfree.c
new file mode 100644 (file)
index 0000000..ce011ea
--- /dev/null
@@ -0,0 +1,129 @@
+/*     $NetBSD: regfree.c,v 1.15 2007/02/09 23:44:18 junyoung Exp $    */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. 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.
+ *
+ *     @(#)regfree.c   8.3 (Berkeley) 3/20/94
+ */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994 Henry Spencer.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ *     @(#)regfree.c   8.3 (Berkeley) 3/20/94
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)regfree.c  8.3 (Berkeley) 3/20/94";
+#else
+__RCSID("$NetBSD: regfree.c,v 1.15 2007/02/09 23:44:18 junyoung Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <regex.h>
+
+#ifdef __weak_alias
+__weak_alias(regfree,_regfree)
+#endif
+
+#include "utils.h"
+#include "regex2.h"
+
+/*
+ - regfree - free everything
+ = extern void regfree(regex_t *);
+ */
+void
+regfree(
+    regex_t *preg)
+{
+       struct re_guts *g;
+
+       _DIAGASSERT(preg != NULL);
+
+       _DIAGASSERT(preg->re_magic == MAGIC1);
+       if (preg->re_magic != MAGIC1)   /* oops */
+               return;                 /* nice to complain, but hard */
+
+       g = preg->re_g;
+       if (g == NULL || g->magic != MAGIC2)    /* oops again */
+               return;
+       preg->re_magic = 0;             /* mark it invalid */
+       g->magic = 0;                   /* mark it invalid */
+
+       if (g->strip != NULL)
+               free(g->strip);
+       if (g->sets != NULL)
+               free(g->sets);
+       if (g->setbits != NULL)
+               free(g->setbits);
+       if (g->must != NULL)
+               free(g->must);
+       free(g);
+}
diff --git a/lib/nbsd_libc/regex/utils.h b/lib/nbsd_libc/regex/utils.h
new file mode 100644 (file)
index 0000000..762caee
--- /dev/null
@@ -0,0 +1,91 @@
+/*     $NetBSD: utils.h,v 1.6 2003/08/07 16:43:21 agc Exp $    */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. 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.
+ *
+ *     @(#)utils.h     8.3 (Berkeley) 3/20/94
+ */
+
+/*-
+ * Copyright (c) 1992, 1993, 1994 Henry Spencer.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ *     @(#)utils.h     8.3 (Berkeley) 3/20/94
+ */
+
+/* utility definitions */
+#define        DUPMAX          _POSIX2_RE_DUP_MAX      /* xxx is this right? */
+#define        INFINITY        (DUPMAX + 1)
+#define        NC              (CHAR_MAX - CHAR_MIN + 1)
+typedef unsigned char uch;
+
+/* switch off assertions (if not already off) if no REDEBUG */
+#ifndef REDEBUG
+#ifndef NDEBUG
+#define        NDEBUG  /* no assertions please */
+#endif
+#endif
+#include <assert.h>
+
+/* for old systems with bcopy() but no memmove() */
+#ifdef USEBCOPY
+#define        memmove(d, s, c)        bcopy(s, d, c)
+#endif
diff --git a/lib/nbsd_libc/resolv/Makefile.inc b/lib/nbsd_libc/resolv/Makefile.inc
new file mode 100644 (file)
index 0000000..6b52829
--- /dev/null
@@ -0,0 +1,12 @@
+#      $NetBSD: Makefile.inc,v 1.4 2007/01/28 02:14:05 christos Exp $
+
+# net sources
+.PATH: ${.CURDIR}/resolv
+CPPFLAGS+=-DCOMPAT__RES -DUSE_POLL
+
+SRCS+= __dn_comp.c __res_close.c __res_send.c h_errno.c \
+       herror.c res_comp.c res_data.c res_debug.c \
+       res_init.c res_mkquery.c res_query.c res_send.c \
+       res_state.c mtctxres.c
+# For COMPAT__RES
+SRCS+= res_compat.c
diff --git a/lib/nbsd_libc/resolv/__dn_comp.c b/lib/nbsd_libc/resolv/__dn_comp.c
new file mode 100644 (file)
index 0000000..f840331
--- /dev/null
@@ -0,0 +1,34 @@
+/*     $NetBSD: __dn_comp.c,v 1.5 2007/01/17 16:39:20 seanb Exp $      */
+
+/*
+ * written by matthew green, 22/04/97.
+ * public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __dn_comp.c,v 1.5 2007/01/17 16:39:20 seanb Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(__dn_comp,dn_comp)
+#else
+
+#include <sys/types.h>
+#include <netinet/in.h>
+#include <resolv.h>
+
+/* XXX THIS IS A MESS!  SEE <resolv.h> XXX */
+
+#undef dn_comp
+int    dn_comp(const char *, u_char *, int, u_char **, u_char **);
+
+int
+dn_comp(const char *exp_dn, u_char *comp_dn, int length, u_char **dnptrs,
+    u_char **lastdnptr)
+{
+
+       return __dn_comp(exp_dn, comp_dn, length, dnptrs, lastdnptr);
+}
+
+#endif
diff --git a/lib/nbsd_libc/resolv/__res_close.c b/lib/nbsd_libc/resolv/__res_close.c
new file mode 100644 (file)
index 0000000..1d6d2ab
--- /dev/null
@@ -0,0 +1,33 @@
+/*     $NetBSD: __res_close.c,v 1.4 2005/09/13 01:44:10 christos Exp $ */
+
+/*
+ * written by matthew green, 22/04/97.
+ * public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __res_close.c,v 1.4 2005/09/13 01:44:10 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(__res_close, res_close)
+#else
+
+#include <sys/types.h>
+#include <netinet/in.h>
+#include <resolv.h>
+
+/* XXX THIS IS A MESS!  SEE <resolv.h> XXX */
+
+#undef res_close
+void   res_close(void);
+
+void
+res_close(void)
+{
+
+       __res_close();
+}
+
+#endif
diff --git a/lib/nbsd_libc/resolv/__res_send.c b/lib/nbsd_libc/resolv/__res_send.c
new file mode 100644 (file)
index 0000000..af1ea36
--- /dev/null
@@ -0,0 +1,33 @@
+/*     $NetBSD: __res_send.c,v 1.4 2005/09/13 01:44:10 christos Exp $  */
+
+/*
+ * written by matthew green, 22/04/97.
+ * public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __res_send.c,v 1.4 2005/09/13 01:44:10 christos Exp $");
+#endif
+
+#if defined(__indr_reference)
+__indr_reference(__res_send, res_send)
+#else
+
+#include <sys/types.h>
+#include <netinet/in.h>
+#include <resolv.h>
+
+/* XXX THIS IS A MESS!  SEE <resolv.h> XXX */
+
+#undef res_send
+int    res_send(const u_char *, int, u_char *, int);
+
+int
+res_send(const u_char *buf, int buflen, u_char *ans, int anssiz)
+{
+
+       return __res_send(buf, buflen, ans, anssiz);
+}
+
+#endif
diff --git a/lib/nbsd_libc/resolv/h_errno.c b/lib/nbsd_libc/resolv/h_errno.c
new file mode 100644 (file)
index 0000000..ec18d35
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: h_errno.c,v 1.3 2008/06/21 20:41:48 christos Exp $     */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: h_errno.c,v 1.3 2008/06/21 20:41:48 christos Exp $");
+#endif
+
+#include <sys/types.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+#include <resolv.h>
+#include <netdb.h>
+
+#undef h_errno
+
+extern int h_errno;
+extern struct __res_state _nres;
+
+int *
+__h_errno(void)
+{
+       return &_nres.res_h_errno;
+}
+
+void
+__h_errno_set(res_state res, int err)
+{
+       h_errno = res->res_h_errno = err;
+}
diff --git a/lib/nbsd_libc/resolv/herror.c b/lib/nbsd_libc/resolv/herror.c
new file mode 100644 (file)
index 0000000..a1f0010
--- /dev/null
@@ -0,0 +1,140 @@
+/*     $NetBSD: herror.c,v 1.8 2009/04/12 17:07:17 christos Exp $      */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#ifdef notdef
+static const char sccsid[] = "@(#)herror.c     8.1 (Berkeley) 6/4/93";
+static const char rcsid[] = "Id: herror.c,v 1.4 2005/04/27 04:56:41 sra Exp";
+#else
+__RCSID("$NetBSD: herror.c,v 1.8 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/uio.h>
+
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+
+#include <netdb.h>
+#include <resolv.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "port_after.h"
+
+const char *h_errlist[] = {
+       "Resolver Error 0 (no error)",
+       "Unknown host",                         /*%< 1 HOST_NOT_FOUND */
+       "Host name lookup failure",             /*%< 2 TRY_AGAIN */
+       "Unknown server error",                 /*%< 3 NO_RECOVERY */
+       "No address associated with name",      /*%< 4 NO_ADDRESS */
+};
+int    h_nerr = { sizeof h_errlist / sizeof h_errlist[0] };
+
+#if !(__GLIBC__ > 2 || __GLIBC__ == 2 &&  __GLIBC_MINOR__ >= 3)
+#undef h_errno
+int    h_errno;
+#endif
+
+#ifdef __weak_alias
+__weak_alias(herror,_herror)
+#endif
+
+/*%
+ * herror --
+ *     print the error indicated by the h_errno value.
+ */
+void
+herror(const char *s) {
+       struct iovec iov[4], *v = iov;
+       char *t;
+
+       if (s != NULL && *s != '\0') {
+               DE_CONST(s, t);
+               v->iov_base = t;
+               v->iov_len = strlen(t);
+               v++;
+               DE_CONST(": ", t);
+               v->iov_base = t;
+               v->iov_len = 2;
+               v++;
+       }
+       DE_CONST(hstrerror(*__h_errno()), t);
+       v->iov_base = t;
+       v->iov_len = strlen(v->iov_base);
+       v++;
+       DE_CONST("\n", t);
+       v->iov_base = t;
+       v->iov_len = 1;
+       writev(STDERR_FILENO, iov, (v - iov) + 1);
+}
+
+/*%
+ * hstrerror --
+ *     return the string associated with a given "host" errno value.
+ */
+const char *
+hstrerror(int err) {
+       if (err < 0)
+               return ("Resolver internal error");
+       else if (err < h_nerr)
+               return (h_errlist[err]);
+       return ("Unknown resolver error");
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/resolv/mtctxres.c b/lib/nbsd_libc/resolv/mtctxres.c
new file mode 100644 (file)
index 0000000..6e3281a
--- /dev/null
@@ -0,0 +1,130 @@
+/*     $NetBSD: mtctxres.c,v 1.4 2007/03/30 20:40:52 ghen Exp $        */
+
+#include <port_before.h>
+#ifdef DO_PTHREADS
+#include <pthread.h>
+#endif
+#include <errno.h>
+#include <netdb.h>
+#include <stdlib.h>
+#include <string.h>
+#include <resolv_mt.h>
+#include <port_after.h>
+
+#ifdef DO_PTHREADS
+static pthread_key_t   key;
+static int             mt_key_initialized = 0;
+
+static int             __res_init_ctx(void);
+static void            __res_destroy_ctx(void *);
+
+#if defined(sun) && !defined(__GNUC__)
+#pragma init   (_mtctxres_init)
+#endif
+#endif
+
+static mtctxres_t      sharedctx;
+
+#ifdef DO_PTHREADS
+/*
+ * Initialize the TSD key. By doing this at library load time, we're
+ * implicitly running without interference from other threads, so there's
+ * no need for locking.
+ */
+static void
+_mtctxres_init(void) {
+       int pthread_keycreate_ret;
+
+       pthread_keycreate_ret = pthread_key_create(&key, __res_destroy_ctx);
+       if (pthread_keycreate_ret == 0)
+               mt_key_initialized = 1;
+}
+#endif
+
+/*
+ * To support binaries that used the private MT-safe interface in
+ * Solaris 8, we still need to provide the __res_enable_mt()
+ * and __res_disable_mt() entry points. They're do-nothing routines.
+ */
+int
+__res_enable_mt(void) {
+       return (-1);
+}
+
+int
+__res_disable_mt(void) {
+       return (0);
+}
+
+#ifdef DO_PTHREADS
+static int
+__res_init_ctx(void) {
+
+       mtctxres_t      *mt;
+       int             ret;
+
+
+       if (pthread_getspecific(key) != 0) {
+               /* Already exists */
+               return (0);
+       }
+
+       if ((mt = malloc(sizeof (mtctxres_t))) == 0) {
+               errno = ENOMEM;
+               return (-1);
+       }
+
+       memset(mt, 0, sizeof (mtctxres_t));
+
+       if ((ret = pthread_setspecific(key, mt)) != 0) {
+               free(mt);
+               errno = ret;
+               return (-1);
+       }
+
+       return (0);
+}
+
+static void
+__res_destroy_ctx(void *value) {
+
+       mtctxres_t      *mt = (mtctxres_t *)value;
+
+       if (mt != 0)
+               free(mt);
+}
+#endif
+
+mtctxres_t *
+___mtctxres(void) {
+#ifdef DO_PTHREADS
+       mtctxres_t      *mt;
+
+       /*
+        * This if clause should only be executed if we are linking
+        * statically.  When linked dynamically _mtctxres_init() should
+        * be called at binding time due the #pragma above.
+        */
+       if (!mt_key_initialized) {
+               static pthread_mutex_t keylock = PTHREAD_MUTEX_INITIALIZER;
+                if (pthread_mutex_lock(&keylock) == 0) {
+                       _mtctxres_init();
+                       (void) pthread_mutex_unlock(&keylock);
+               }
+       }
+
+       /*
+        * If we have already been called in this thread return the existing
+        * context.  Otherwise recreat a new context and return it.  If
+        * that fails return a global context.
+        */
+       if (mt_key_initialized) {
+               if (((mt = pthread_getspecific(key)) != 0) ||
+                   (__res_init_ctx() == 0 &&
+                    (mt = pthread_getspecific(key)) != 0)) {
+                       return (mt);
+               }
+       }
+#endif
+       return (&sharedctx);
+}
diff --git a/lib/nbsd_libc/resolv/res_comp.c b/lib/nbsd_libc/resolv/res_comp.c
new file mode 100644 (file)
index 0000000..eaa4b2b
--- /dev/null
@@ -0,0 +1,285 @@
+/*     $NetBSD: res_comp.c,v 1.10 2009/04/12 17:07:17 christos Exp $   */
+
+/*
+ * Copyright (c) 1985, 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+/*
+ * Portions Copyright (c) 1993 by Digital Equipment Corporation.
+ * 
+ * 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, and that
+ * the name of Digital Equipment Corporation not be used in advertising or
+ * publicity pertaining to distribution of the document or software without
+ * specific, written prior permission.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
+ * CORPORATION 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.
+ */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#ifdef notdef
+static const char sccsid[] = "@(#)res_comp.c   8.1 (Berkeley) 6/4/93";
+static const char rcsid[] = "Id: res_comp.c,v 1.5 2005/07/28 06:51:50 marka Exp";
+#else
+__RCSID("$NetBSD: res_comp.c,v 1.10 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+#include <ctype.h>
+#include <resolv.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include "port_after.h"
+
+#ifdef __weak_alias
+__weak_alias(dn_expand,_dn_expand)
+__weak_alias(dn_comp,__dn_comp)
+#if 0
+__weak_alias(dn_skipname,__dn_skipname)
+__weak_alias(res_hnok,__res_hnok)
+__weak_alias(res_ownok,__res_ownok)
+__weak_alias(res_mailok,__res_mailok)
+__weak_alias(res_dnok,__res_dnok)
+#endif
+#endif
+
+/*%
+ * Expand compressed domain name 'src' to full domain name.
+ *
+ * \li 'msg' is a pointer to the begining of the message,
+ * \li 'eom' points to the first location after the message,
+ * \li 'dst' is a pointer to a buffer of size 'dstsiz' for the result.
+ * \li Return size of compressed name or -1 if there was an error.
+ */
+int
+dn_expand(const u_char *msg, const u_char *eom, const u_char *src,
+         char *dst, int dstsiz)
+{
+       int n = ns_name_uncompress(msg, eom, src, dst, (size_t)dstsiz);
+
+       if (n > 0 && dst[0] == '.')
+               dst[0] = '\0';
+       return (n);
+}
+
+/*%
+ * Pack domain name 'exp_dn' in presentation form into 'comp_dn'.
+ *
+ * \li Return the size of the compressed name or -1.
+ * \li 'length' is the size of the array pointed to by 'comp_dn'.
+ */
+int
+dn_comp(const char *src, u_char *dst, int dstsiz,
+       u_char **dnptrs, u_char **lastdnptr)
+{
+       return (ns_name_compress(src, dst, (size_t)dstsiz,
+                                (const u_char **)dnptrs,
+                                (const u_char **)lastdnptr));
+}
+
+/*%
+ * Skip over a compressed domain name. Return the size or -1.
+ */
+int
+dn_skipname(const u_char *ptr, const u_char *eom) {
+       const u_char *saveptr = ptr;
+
+       if (ns_name_skip(&ptr, eom) == -1)
+               return (-1);
+       return (ptr - saveptr);
+}
+
+/*%
+ * Verify that a domain name uses an acceptable character set.
+ *
+ * Note the conspicuous absence of ctype macros in these definitions.  On
+ * non-ASCII hosts, we can't depend on string literals or ctype macros to
+ * tell us anything about network-format data.  The rest of the BIND system
+ * is not careful about this, but for some reason, we're doing it right here.
+ */
+#define PERIOD 0x2e
+#define        hyphenchar(c) ((c) == 0x2d)
+#define bslashchar(c) ((c) == 0x5c)
+#define periodchar(c) ((c) == PERIOD)
+#define asterchar(c) ((c) == 0x2a)
+#define alphachar(c) (((c) >= 0x41 && (c) <= 0x5a) \
+                  || ((c) >= 0x61 && (c) <= 0x7a))
+#define digitchar(c) ((c) >= 0x30 && (c) <= 0x39)
+
+#define borderchar(c) (alphachar(c) || digitchar(c))
+#define middlechar(c) (borderchar(c) || hyphenchar(c))
+#define        domainchar(c) ((c) > 0x20 && (c) < 0x7f)
+
+int
+res_hnok(const char *dn) {
+       int pch = PERIOD, ch = *dn++;
+
+       while (ch != '\0') {
+               int nch = *dn++;
+
+               if (periodchar(ch)) {
+                       ;
+               } else if (periodchar(pch)) {
+                       if (!borderchar(ch))
+                               return (0);
+               } else if (periodchar(nch) || nch == '\0') {
+                       if (!borderchar(ch))
+                               return (0);
+               } else {
+                       if (!middlechar(ch))
+                               return (0);
+               }
+               pch = ch, ch = nch;
+       }
+       return (1);
+}
+
+/*%
+ * hostname-like (A, MX, WKS) owners can have "*" as their first label
+ * but must otherwise be as a host name.
+ */
+int
+res_ownok(const char *dn) {
+       if (asterchar(dn[0])) {
+               if (periodchar(dn[1]))
+                       return (res_hnok(dn+2));
+               if (dn[1] == '\0')
+                       return (1);
+       }
+       return (res_hnok(dn));
+}
+
+/*%
+ * SOA RNAMEs and RP RNAMEs can have any printable character in their first
+ * label, but the rest of the name has to look like a host name.
+ */
+int
+res_mailok(const char *dn) {
+       int ch, escaped = 0;
+
+       /* "." is a valid missing representation */
+       if (*dn == '\0')
+               return (1);
+
+       /* otherwise <label>.<hostname> */
+       while ((ch = *dn++) != '\0') {
+               if (!domainchar(ch))
+                       return (0);
+               if (!escaped && periodchar(ch))
+                       break;
+               if (escaped)
+                       escaped = 0;
+               else if (bslashchar(ch))
+                       escaped = 1;
+       }
+       if (periodchar(ch))
+               return (res_hnok(dn));
+       return (0);
+}
+
+/*%
+ * This function is quite liberal, since RFC1034's character sets are only
+ * recommendations.
+ */
+int
+res_dnok(const char *dn) {
+       int ch;
+
+       while ((ch = *dn++) != '\0')
+               if (!domainchar(ch))
+                       return (0);
+       return (1);
+}
+
+#ifdef BIND_4_COMPAT
+/*%
+ * This module must export the following externally-visible symbols:
+ *     ___putlong
+ *     ___putshort
+ *     __getlong
+ *     __getshort
+ * Note that one _ comes from C and the others come from us.
+ */
+
+#ifdef SOLARIS2
+#ifdef  __putlong
+#undef  __putlong
+#endif
+#ifdef  __putshort
+#undef  __putshort
+#endif
+#pragma weak    putlong         =       __putlong
+#pragma weak    putshort        =       __putshort
+#endif /* SOLARIS2 */
+
+void __putlong(u_int32_t src, u_char *dst) { ns_put32(src, dst); }
+void __putshort(u_int16_t src, u_char *dst) { ns_put16(src, dst); }
+#ifndef __ultrix__
+u_int32_t _getlong(const u_char *src) { return (ns_get32(src)); }
+u_int16_t _getshort(const u_char *src) { return (ns_get16(src)); }
+#endif /*__ultrix__*/
+#endif /*BIND_4_COMPAT*/
+
+/*! \file */
diff --git a/lib/nbsd_libc/resolv/res_compat.c b/lib/nbsd_libc/resolv/res_compat.c
new file mode 100644 (file)
index 0000000..01e30d2
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: res_compat.c,v 1.3 2009/11/22 18:04:37 mbalmer Exp $   */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: res_compat.c,v 1.3 2009/11/22 18:04:37 mbalmer Exp $");
+#endif
+
+#include <sys/types.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+#include <netdb.h>
+#include <string.h>
+#define __OLD_RES_STATE
+#include <resolv.h>
+
+#undef _res
+
+/*
+ * Binary Compatibility; this symbol does not appear in a header file
+ * Most userland programs use this to set res_options before res_init()
+ * is called. There are hooks to res_init() to consult the data in this
+ * structure. The hooks are provided indirectly by the two functions below.
+ * We depend on the fact the first 440 [32 bit machines] bytes are
+ * shared between the two structures.
+ */
+#ifndef __BIND_NOSTATIC 
+struct __res_state _res
+#if defined(__BIND_RES_TEXT)
+       = { RES_TIMEOUT, }      /* Motorola, et al. */
+# endif 
+;
+
+void *__res_get_old_state(void);
+void __res_put_old_state(void *);
+
+void *
+__res_get_old_state(void)
+{
+       return &_res;
+}
+
+void
+__res_put_old_state(void *res)
+{
+       (void)memcpy(&_res, res, sizeof(_res));
+}
+#endif
diff --git a/lib/nbsd_libc/resolv/res_data.c b/lib/nbsd_libc/resolv/res_data.c
new file mode 100644 (file)
index 0000000..53c7e47
--- /dev/null
@@ -0,0 +1,363 @@
+/*     $NetBSD: res_data.c,v 1.14 2009/10/24 05:35:37 christos Exp $   */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1995-1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#ifdef notdef
+static const char rcsid[] = "Id: res_data.c,v 1.7 2008/12/11 09:59:00 marka Exp";
+#else
+__RCSID("$NetBSD: res_data.c,v 1.14 2009/10/24 05:35:37 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+
+#include <ctype.h>
+#include <netdb.h>
+#include <resolv.h>
+#include <res_update.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "port_after.h"
+
+#include "res_private.h"
+
+#ifdef __weak_alias
+__weak_alias(res_init,_res_init)
+__weak_alias(res_mkquery,_res_mkquery)
+__weak_alias(res_query,_res_query)
+__weak_alias(res_search,_res_search)
+__weak_alias(res_send,__res_send)
+__weak_alias(res_close,__res_close)
+/* XXX: these leaked in the old bind8 libc */
+__weak_alias(res_querydomain,__res_querydomain)
+__weak_alias(res_send_setqhook,__res_send_setqhook)
+__weak_alias(res_send_setrhook,__res_send_setrhook)
+#if 0
+__weak_alias(p_query,__p_query)
+__weak_alias(fp_query,__fp_query)
+__weak_alias(fp_nquery,__fp_nquery)
+__weak_alias(res_isourserver,__res_isourserver)
+__weak_alias(res_opt,_res_opt)
+__weak_alias(hostalias,__hostalias)
+#endif
+#endif
+
+const char *_res_opcodes[] = {
+       "QUERY",
+       "IQUERY",
+       "CQUERYM",
+       "CQUERYU",      /*%< experimental */
+       "NOTIFY",       /*%< experimental */
+       "UPDATE",
+       "6",
+       "7",
+       "8",
+       "9",
+       "10",
+       "11",
+       "12",
+       "13",
+       "ZONEINIT",
+       "ZONEREF",
+};
+
+#ifdef BIND_UPDATE
+const char *_res_sectioncodes[] = {
+       "ZONE",
+       "PREREQUISITES",
+       "UPDATE",
+       "ADDITIONAL",
+};
+#endif
+
+#ifndef __BIND_NOSTATIC 
+extern struct __res_state _nres;
+
+/* Proto. */
+
+int  res_ourserver_p(const res_state, const struct sockaddr *);
+
+int
+res_init(void) {
+       int rv;
+#ifdef COMPAT__RES
+       /*
+        * Compatibility with program that were accessing _res directly
+        * to set options. We keep another struct res that is the same
+        * size as the original res structure, and then copy fields to
+        * it so that we achieve the same initialization
+        */
+       extern void *__res_get_old_state(void);
+       extern void __res_put_old_state(void *);
+       res_state ores = __res_get_old_state();
+
+       if (ores->options != 0)
+               _nres.options = ores->options;
+       if (ores->retrans != 0)
+               _nres.retrans = ores->retrans;
+       if (ores->retry != 0)
+               _nres.retry = ores->retry;
+#endif
+
+       /*
+        * These three fields used to be statically initialized.  This made
+        * it hard to use this code in a shared library.  It is necessary,
+        * now that we're doing dynamic initialization here, that we preserve
+        * the old semantics: if an application modifies one of these three
+        * fields of _res before res_init() is called, res_init() will not
+        * alter them.  Of course, if an application is setting them to
+        * _zero_ before calling res_init(), hoping to override what used
+        * to be the static default, we can't detect it and unexpected results
+        * will follow.  Zero for any of these fields would make no sense,
+        * so one can safely assume that the applications were already getting
+        * unexpected results.
+        *
+        * _nres.options is tricky since some apps were known to diddle the bits
+        * before res_init() was first called. We can't replicate that semantic
+        * with dynamic initialization (they may have turned bits off that are
+        * set in RES_DEFAULT).  Our solution is to declare such applications
+        * "broken".  They could fool us by setting RES_INIT but none do (yet).
+        */
+       if (!_nres.retrans)
+               _nres.retrans = RES_TIMEOUT;
+       if (!_nres.retry)
+               _nres.retry = 4;
+       if (!(_nres.options & RES_INIT))
+               _nres.options = RES_DEFAULT;
+
+       /*
+        * This one used to initialize implicitly to zero, so unless the app
+        * has set it to something in particular, we can randomize it now.
+        */
+       if (!_nres.id)
+               _nres.id = res_nrandomid(&_nres);
+
+       rv = __res_vinit(&_nres, 1);
+#ifdef COMPAT__RES
+       __res_put_old_state(&_nres);
+#endif
+       return rv;
+}
+
+void
+p_query(const u_char *msg) {
+       fp_query(msg, stdout);
+}
+
+void
+fp_query(const u_char *msg, FILE *file) {
+       fp_nquery(msg, PACKETSZ, file);
+}
+
+void
+fp_nquery(const u_char *msg, int len, FILE *file) {
+       if ((_nres.options & RES_INIT) == 0U && res_init() == -1)
+               return;
+
+       res_pquery(&_nres, msg, len, file);
+}
+
+int
+res_mkquery(int op,                    /*!< opcode of query  */
+           const char *dname,          /*!< domain name  */
+           int class, int type,        /*!< class and type of query  */
+           const u_char *data,         /*!< resource record data  */
+           int datalen,                /*!< length of data  */
+           const u_char *newrr_in,     /*!< new rr for modify or append  */
+           u_char *buf,                /*!< buffer to put query  */
+           int buflen)                 /*!< size of buffer  */
+{
+       if ((_nres.options & RES_INIT) == 0U && res_init() == -1) {
+               RES_SET_H_ERRNO(&_nres, NETDB_INTERNAL);
+               return (-1);
+       }
+       return (res_nmkquery(&_nres, op, dname, class, type,
+                            data, datalen,
+                            newrr_in, buf, buflen));
+}
+
+#ifdef _LIBRESOLV
+int
+res_mkupdate(ns_updrec *rrecp_in, u_char *buf, int buflen) {
+       if ((_nres.options & RES_INIT) == 0U && res_init() == -1) {
+               RES_SET_H_ERRNO(&_nres, NETDB_INTERNAL);
+               return (-1);
+       }
+
+       return (res_nmkupdate(&_nres, rrecp_in, buf, buflen));
+}
+#endif
+
+int
+res_query(const char *name,    /*!< domain name  */
+         int class, int type,  /*!< class and type of query  */
+         u_char *answer,       /*!< buffer to put answer  */
+         int anslen)           /*!< size of answer buffer  */
+{
+       if ((_nres.options & RES_INIT) == 0U && res_init() == -1) {
+               RES_SET_H_ERRNO(&_nres, NETDB_INTERNAL);
+               return (-1);
+       }
+       return (res_nquery(&_nres, name, class, type, answer, anslen));
+}
+
+void
+res_send_setqhook(res_send_qhook hook) {
+       _nres.qhook = hook;
+}
+
+void
+res_send_setrhook(res_send_rhook hook) {
+       _nres.rhook = hook;
+}
+
+int
+res_isourserver(const struct sockaddr_in *inp) {
+       return (res_ourserver_p(&_nres, (const struct sockaddr *)(const void *)inp));
+}
+
+int
+res_send(const u_char *buf, int buflen, u_char *ans, int anssiz) {
+       if ((_nres.options & RES_INIT) == 0U && res_init() == -1) {
+               /* errno should have been set by res_init() in this case. */
+               return (-1);
+       }
+
+       return (res_nsend(&_nres, buf, buflen, ans, anssiz));
+}
+
+#ifdef _LIBRESOLV
+int
+res_sendsigned(const u_char *buf, int buflen, ns_tsig_key *key,
+              u_char *ans, int anssiz)
+{
+       if ((_nres.options & RES_INIT) == 0U && res_init() == -1) {
+               /* errno should have been set by res_init() in this case. */
+               return (-1);
+       }
+
+       return (res_nsendsigned(&_nres, buf, buflen, key, ans, anssiz));
+}
+#endif
+
+void
+res_close(void) {
+       res_nclose(&_nres);
+}
+
+#ifdef _LIBRESOLV
+int
+res_update(ns_updrec *rrecp_in) {
+       if ((_nres.options & RES_INIT) == 0U && res_init() == -1) {
+               RES_SET_H_ERRNO(&_nres, NETDB_INTERNAL);
+               return (-1);
+       }
+
+       return (res_nupdate(&_nres, rrecp_in, NULL));
+}
+#endif
+
+int
+res_search(const char *name,   /*!< domain name  */
+          int class, int type, /*!< class and type of query  */
+          u_char *answer,      /*!< buffer to put answer  */
+          int anslen)          /*!< size of answer  */
+{
+       if ((_nres.options & RES_INIT) == 0U && res_init() == -1) {
+               RES_SET_H_ERRNO(&_nres, NETDB_INTERNAL);
+               return (-1);
+       }
+
+       return (res_nsearch(&_nres, name, class, type, answer, anslen));
+}
+
+int
+res_querydomain(const char *name,
+               const char *domain,
+               int class, int type,    /*!< class and type of query  */
+               u_char *answer,         /*!< buffer to put answer  */
+               int anslen)             /*!< size of answer  */
+{
+       if ((_nres.options & RES_INIT) == 0U && res_init() == -1) {
+               RES_SET_H_ERRNO(&_nres, NETDB_INTERNAL);
+               return (-1);
+       }
+
+       return (res_nquerydomain(&_nres, name, domain,
+                                class, type,
+                                answer, anslen));
+}
+
+int
+res_opt(int a, u_char *b, int c, int d)
+{
+       return res_nopt(&_nres, a, b, c, d);
+}
+
+u_int
+res_randomid(void) {
+       if ((_nres.options & RES_INIT) == 0U && res_init() == -1) {
+               RES_SET_H_ERRNO(&_res, NETDB_INTERNAL);
+               return (u_int)-1;
+       }
+
+       return (res_nrandomid(&_nres));
+}
+
+const char *
+hostalias(const char *name) {
+       static char abuf[MAXDNAME];
+
+       return (res_hostalias(&_nres, name, abuf, sizeof abuf));
+}
+
+#ifdef ultrix
+int
+local_hostname_length(const char *hostname) {
+       int len_host, len_domain;
+
+       if (!*_nres.defdname)
+               res_init();
+       len_host = strlen(hostname);
+       len_domain = strlen(_nres.defdname);
+       if (len_host > len_domain &&
+           !strcasecmp(hostname + len_host - len_domain, _nres.defdname) &&
+           hostname[len_host - len_domain - 1] == '.')
+               return (len_host - len_domain - 1);
+       return (0);
+}
+#endif /*ultrix*/
+
+#endif
+
+/*! \file */
diff --git a/lib/nbsd_libc/resolv/res_debug.c b/lib/nbsd_libc/resolv/res_debug.c
new file mode 100644 (file)
index 0000000..4d9ec37
--- /dev/null
@@ -0,0 +1,1249 @@
+/*     $NetBSD: res_debug.c,v 1.11 2009/04/12 17:07:17 christos Exp $  */
+
+/*
+ * Portions Copyright (C) 2004, 2005, 2008, 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (C) 1996-2003  Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and/or 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 ISC DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/*
+ * Copyright (c) 1985
+ *    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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+/*
+ * Portions Copyright (c) 1993 by Digital Equipment Corporation.
+ *
+ * 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, and that
+ * the name of Digital Equipment Corporation not be used in advertising or
+ * publicity pertaining to distribution of the document or software without
+ * specific, written prior permission.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
+ * CORPORATION 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.
+ */
+
+/*
+ * Portions Copyright (c) 1995 by International Business Machines, Inc.
+ *
+ * International Business Machines, Inc. (hereinafter called IBM) grants
+ * permission under its copyrights to use, copy, modify, and distribute this
+ * Software with or without fee, provided that the above copyright notice and
+ * all paragraphs of this notice appear in all copies, and that the name of IBM
+ * not be used in connection with the marketing of any product incorporating
+ * the Software or modifications thereof, without specific, written prior
+ * permission.
+ *
+ * To the extent it has a right to do so, IBM grants an immunity from suit
+ * under its patents, if any, for the use, sale or manufacture of products to
+ * the extent that such products are used for performing Domain Name System
+ * dynamic updates in TCP/IP networks by means of the Software.  No immunity is
+ * granted for any product per se or for any other function of any product.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+ * PARTICULAR PURPOSE.  IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL,
+ * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING
+ * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN
+ * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#ifdef notdef
+static const char sccsid[] = "@(#)res_debug.c  8.1 (Berkeley) 6/4/93";
+static const char rcsid[] = "Id: res_debug.c,v 1.19 2009/02/26 11:20:20 tbox Exp";
+#else
+__RCSID("$NetBSD: res_debug.c,v 1.11 2009/04/12 17:07:17 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+
+#include <ctype.h>
+#include <errno.h>
+#include <math.h>
+#include <netdb.h>
+#include <resolv.h>
+#include <resolv_mt.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "port_after.h"
+
+#ifdef SPRINTF_CHAR
+# define SPRINTF(x) strlen(sprintf/**/x)
+#else
+# define SPRINTF(x) sprintf x
+#endif
+
+extern const char *_res_opcodes[];
+extern const char *_res_sectioncodes[];
+
+#if 0
+#ifdef __weak_alias
+__weak_alias(res_pquery,__res_pquery)
+__weak_alias(res_nametoclass,__res_nametoclass)
+__weak_alias(res_nametotype,__res_nametotype)
+#endif
+#endif
+
+#ifndef _LIBC
+/*%
+ * Print the current options.
+ */
+void
+fp_resstat(const res_state statp, FILE *file) {
+       u_long mask;
+
+       fprintf(file, ";; res options:");
+       for (mask = 1;  mask != 0U;  mask <<= 1)
+               if (statp->options & mask)
+                       fprintf(file, " %s", p_option(mask));
+       putc('\n', file);
+}
+#endif
+
+static void
+do_section(const res_state statp,
+          ns_msg *handle, ns_sect section,
+          int pflag, FILE *file)
+{
+       int n, sflag, rrnum;
+       static int buflen = 2048;
+       char *buf;
+       ns_opcode opcode;
+       ns_rr rr;
+
+       /*
+        * Print answer records.
+        */
+       sflag = (statp->pfcode & pflag);
+       if (statp->pfcode && !sflag)
+               return;
+
+       buf = malloc((size_t)buflen);
+       if (buf == NULL) {
+               fprintf(file, ";; memory allocation failure\n");
+               return;
+       }
+
+       opcode = (ns_opcode) ns_msg_getflag(*handle, ns_f_opcode);
+       rrnum = 0;
+       for (;;) {
+               if (ns_parserr(handle, section, rrnum, &rr)) {
+                       if (errno != ENODEV)
+                               fprintf(file, ";; ns_parserr: %s\n",
+                                       strerror(errno));
+                       else if (rrnum > 0 && sflag != 0 &&
+                                (statp->pfcode & RES_PRF_HEAD1))
+                               putc('\n', file);
+                       goto cleanup;
+               }
+               if (rrnum == 0 && sflag != 0 && (statp->pfcode & RES_PRF_HEAD1))
+                       fprintf(file, ";; %s SECTION:\n",
+                               p_section(section, opcode));
+               if (section == ns_s_qd)
+                       fprintf(file, ";;\t%s, type = %s, class = %s\n",
+                               ns_rr_name(rr),
+                               p_type(ns_rr_type(rr)),
+                               p_class(ns_rr_class(rr)));
+               else if (section == ns_s_ar && ns_rr_type(rr) == ns_t_opt) {
+                       u_int16_t optcode, optlen, rdatalen = ns_rr_rdlen(rr);
+                       u_int32_t ttl = ns_rr_ttl(rr);
+
+                       fprintf(file,
+                               "; EDNS: version: %u, udp=%u, flags=%04x\n",
+                               (ttl>>16)&0xff, ns_rr_class(rr), ttl&0xffff);
+
+                       while (rdatalen >= 4) {
+                               const u_char *cp = ns_rr_rdata(rr);
+                               int i;
+
+                               GETSHORT(optcode, cp);
+                               GETSHORT(optlen, cp);
+
+                               if (optcode == NS_OPT_NSID) {
+                                       fputs("; NSID: ", file);
+                                       if (optlen == 0) {
+                                               fputs("; NSID\n", file);
+                                       } else {
+                                               fputs("; NSID: ", file);
+                                               for (i = 0; i < optlen; i++)
+                                                       fprintf(file, "%02x ",
+                                                               cp[i]);
+                                               fputs(" (",file);
+                                               for (i = 0; i < optlen; i++)
+                                                       fprintf(file, "%c",
+                                                               isprint(cp[i])?
+                                                               cp[i] : '.');
+                                               fputs(")\n", file);
+                                       }
+                               } else {
+                                       if (optlen == 0) {
+                                               fprintf(file, "; OPT=%u\n",
+                                                       optcode);
+                                       } else {
+                                               fprintf(file, "; OPT=%u: ",
+                                                       optcode);
+                                               for (i = 0; i < optlen; i++)
+                                                       fprintf(file, "%02x ",
+                                                               cp[i]);
+                                               fputs(" (",file);
+                                               for (i = 0; i < optlen; i++)
+                                                       fprintf(file, "%c",
+                                                               isprint(cp[i]) ?
+                                                                       cp[i] : '.');
+                                               fputs(")\n", file);
+                                       }
+                               }
+                               rdatalen -= 4 + optlen;
+                       }
+               } else {
+                       n = ns_sprintrr(handle, &rr, NULL, NULL,
+                                       buf, (u_int)buflen);
+                       if (n < 0) {
+                               if (errno == ENOSPC) {
+                                       free(buf);
+                                       buf = NULL;
+                                       if (buflen < 131072)
+                                               buf = malloc((size_t)(buflen += 1024));
+                                       if (buf == NULL) {
+                                               fprintf(file,
+                                             ";; memory allocation failure\n");
+                                             return;
+                                       }
+                                       continue;
+                               }
+                               fprintf(file, ";; ns_sprintrr: %s\n",
+                                       strerror(errno));
+                               goto cleanup;
+                       }
+                       fputs(buf, file);
+                       fputc('\n', file);
+               }
+               rrnum++;
+       }
+ cleanup:
+       if (buf != NULL)
+               free(buf);
+}
+
+/*%
+ * Print the contents of a query.
+ * This is intended to be primarily a debugging routine.
+ */
+void
+res_pquery(const res_state statp, const u_char *msg, int len, FILE *file) {
+       ns_msg handle;
+       int qdcount, ancount, nscount, arcount;
+       u_int opcode, rcode, id;
+
+       if (ns_initparse(msg, len, &handle) < 0) {
+               fprintf(file, ";; ns_initparse: %s\n", strerror(errno));
+               return;
+       }
+       opcode = ns_msg_getflag(handle, ns_f_opcode);
+       rcode = ns_msg_getflag(handle, ns_f_rcode);
+       id = ns_msg_id(handle);
+       qdcount = ns_msg_count(handle, ns_s_qd);
+       ancount = ns_msg_count(handle, ns_s_an);
+       nscount = ns_msg_count(handle, ns_s_ns);
+       arcount = ns_msg_count(handle, ns_s_ar);
+
+       /*
+        * Print header fields.
+        */
+       if ((!statp->pfcode) || (statp->pfcode & RES_PRF_HEADX) || rcode)
+               fprintf(file,
+                       ";; ->>HEADER<<- opcode: %s, status: %s, id: %d\n",
+                       _res_opcodes[opcode], p_rcode((int)rcode), id);
+       if ((!statp->pfcode) || (statp->pfcode & RES_PRF_HEADX))
+               putc(';', file);
+       if ((!statp->pfcode) || (statp->pfcode & RES_PRF_HEAD2)) {
+               fprintf(file, "; flags:");
+               if (ns_msg_getflag(handle, ns_f_qr))
+                       fprintf(file, " qr");
+               if (ns_msg_getflag(handle, ns_f_aa))
+                       fprintf(file, " aa");
+               if (ns_msg_getflag(handle, ns_f_tc))
+                       fprintf(file, " tc");
+               if (ns_msg_getflag(handle, ns_f_rd))
+                       fprintf(file, " rd");
+               if (ns_msg_getflag(handle, ns_f_ra))
+                       fprintf(file, " ra");
+               if (ns_msg_getflag(handle, ns_f_z))
+                       fprintf(file, " ??");
+               if (ns_msg_getflag(handle, ns_f_ad))
+                       fprintf(file, " ad");
+               if (ns_msg_getflag(handle, ns_f_cd))
+                       fprintf(file, " cd");
+       }
+       if ((!statp->pfcode) || (statp->pfcode & RES_PRF_HEAD1)) {
+               fprintf(file, "; %s: %d",
+                       p_section(ns_s_qd, (int)opcode), qdcount);
+               fprintf(file, ", %s: %d",
+                       p_section(ns_s_an, (int)opcode), ancount);
+               fprintf(file, ", %s: %d",
+                       p_section(ns_s_ns, (int)opcode), nscount);
+               fprintf(file, ", %s: %d",
+                       p_section(ns_s_ar, (int)opcode), arcount);
+       }
+       if ((!statp->pfcode) || (statp->pfcode &
+               (RES_PRF_HEADX | RES_PRF_HEAD2 | RES_PRF_HEAD1))) {
+               putc('\n',file);
+       }
+       /*
+        * Print the various sections.
+        */
+       do_section(statp, &handle, ns_s_qd, RES_PRF_QUES, file);
+       do_section(statp, &handle, ns_s_an, RES_PRF_ANS, file);
+       do_section(statp, &handle, ns_s_ns, RES_PRF_AUTH, file);
+       do_section(statp, &handle, ns_s_ar, RES_PRF_ADD, file);
+       if (qdcount == 0 && ancount == 0 &&
+           nscount == 0 && arcount == 0)
+               putc('\n', file);
+}
+
+const u_char *
+p_cdnname(const u_char *cp, const u_char *msg, int len, FILE *file) {
+       char name[MAXDNAME];
+       int n;
+
+       if ((n = dn_expand(msg, msg + len, cp, name, sizeof name)) < 0)
+               return (NULL);
+       if (name[0] == '\0')
+               putc('.', file);
+       else
+               fputs(name, file);
+       return (cp + n);
+}
+
+const u_char *
+p_cdname(const u_char *cp, const u_char *msg, FILE *file) {
+       return (p_cdnname(cp, msg, PACKETSZ, file));
+}
+
+/*%
+ * Return a fully-qualified domain name from a compressed name (with
+   length supplied).  */
+
+const u_char *
+p_fqnname(cp, msg, msglen, name, namelen)
+       const u_char *cp, *msg;
+       int msglen;
+       char *name;
+       int namelen;
+{
+       int n, newlen;
+
+       if ((n = dn_expand(msg, cp + msglen, cp, name, namelen)) < 0)
+               return (NULL);
+       newlen = strlen(name);
+       if (newlen == 0 || name[newlen - 1] != '.') {
+               if (newlen + 1 >= namelen)      /*%< Lack space for final dot */
+                       return (NULL);
+               else
+                       strcpy(name + newlen, ".");
+       }
+       return (cp + n);
+}
+
+/* XXX:        the rest of these functions need to become length-limited, too. */
+
+const u_char *
+p_fqname(const u_char *cp, const u_char *msg, FILE *file) {
+       char name[MAXDNAME];
+       const u_char *n;
+
+       n = p_fqnname(cp, msg, MAXCDNAME, name, sizeof name);
+       if (n == NULL)
+               return (NULL);
+       fputs(name, file);
+       return (n);
+}
+
+/*%
+ * Names of RR classes and qclasses.  Classes and qclasses are the same, except
+ * that C_ANY is a qclass but not a class.  (You can ask for records of class
+ * C_ANY, but you can't have any records of that class in the database.)
+ */
+const struct res_sym __p_class_syms[] = {
+       {C_IN,          "IN",           (char *)0},
+       {C_CHAOS,       "CH",           (char *)0},
+       {C_CHAOS,       "CHAOS",        (char *)0},
+       {C_HS,          "HS",           (char *)0},
+       {C_HS,          "HESIOD",       (char *)0},
+       {C_ANY,         "ANY",          (char *)0},
+       {C_NONE,        "NONE",         (char *)0},
+       {C_IN,          (char *)0,      (char *)0}
+};
+
+/*%
+ * Names of message sections.
+ */
+const struct res_sym __p_default_section_syms[] = {
+       {ns_s_qd,       "QUERY",        (char *)0},
+       {ns_s_an,       "ANSWER",       (char *)0},
+       {ns_s_ns,       "AUTHORITY",    (char *)0},
+       {ns_s_ar,       "ADDITIONAL",   (char *)0},
+       {0,             (char *)0,      (char *)0}
+};
+
+const struct res_sym __p_update_section_syms[] = {
+       {S_ZONE,        "ZONE",         (char *)0},
+       {S_PREREQ,      "PREREQUISITE", (char *)0},
+       {S_UPDATE,      "UPDATE",       (char *)0},
+       {S_ADDT,        "ADDITIONAL",   (char *)0},
+       {0,             (char *)0,      (char *)0}
+};
+
+const struct res_sym __p_key_syms[] = {
+       {NS_ALG_MD5RSA,         "RSA",          "RSA KEY with MD5 hash"},
+       {NS_ALG_DH,             "DH",           "Diffie Hellman"},
+       {NS_ALG_DSA,            "DSA",          "Digital Signature Algorithm"},
+       {NS_ALG_EXPIRE_ONLY,    "EXPIREONLY",   "No algorithm"},
+       {NS_ALG_PRIVATE_OID,    "PRIVATE",      "Algorithm obtained from OID"},
+       {0,                     NULL,           NULL}
+};
+
+const struct res_sym __p_cert_syms[] = {
+       {cert_t_pkix,   "PKIX",         "PKIX (X.509v3) Certificate"},
+       {cert_t_spki,   "SPKI",         "SPKI certificate"},
+       {cert_t_pgp,    "PGP",          "PGP certificate"},
+       {cert_t_url,    "URL",          "URL Private"},
+       {cert_t_oid,    "OID",          "OID Private"},
+       {0,             NULL,           NULL}
+};
+
+/*%
+ * Names of RR types and qtypes.  Types and qtypes are the same, except
+ * that T_ANY is a qtype but not a type.  (You can ask for records of type
+ * T_ANY, but you can't have any records of that type in the database.)
+ */
+const struct res_sym __p_type_syms[] = {
+       {ns_t_a,        "A",            "address"},
+       {ns_t_ns,       "NS",           "name server"},
+       {ns_t_md,       "MD",           "mail destination (deprecated)"},
+       {ns_t_mf,       "MF",           "mail forwarder (deprecated)"},
+       {ns_t_cname,    "CNAME",        "canonical name"},
+       {ns_t_soa,      "SOA",          "start of authority"},
+       {ns_t_mb,       "MB",           "mailbox"},
+       {ns_t_mg,       "MG",           "mail group member"},
+       {ns_t_mr,       "MR",           "mail rename"},
+       {ns_t_null,     "NULL",         "null"},
+       {ns_t_wks,      "WKS",          "well-known service (deprecated)"},
+       {ns_t_ptr,      "PTR",          "domain name pointer"},
+       {ns_t_hinfo,    "HINFO",        "host information"},
+       {ns_t_minfo,    "MINFO",        "mailbox information"},
+       {ns_t_mx,       "MX",           "mail exchanger"},
+       {ns_t_txt,      "TXT",          "text"},
+       {ns_t_rp,       "RP",           "responsible person"},
+       {ns_t_afsdb,    "AFSDB",        "DCE or AFS server"},
+       {ns_t_x25,      "X25",          "X25 address"},
+       {ns_t_isdn,     "ISDN",         "ISDN address"},
+       {ns_t_rt,       "RT",           "router"},
+       {ns_t_nsap,     "NSAP",         "nsap address"},
+       {ns_t_nsap_ptr, "NSAP_PTR",     "domain name pointer"},
+       {ns_t_sig,      "SIG",          "signature"},
+       {ns_t_key,      "KEY",          "key"},
+       {ns_t_px,       "PX",           "mapping information"},
+       {ns_t_gpos,     "GPOS",         "geographical position (withdrawn)"},
+       {ns_t_aaaa,     "AAAA",         "IPv6 address"},
+       {ns_t_loc,      "LOC",          "location"},
+       {ns_t_nxt,      "NXT",          "next valid name (unimplemented)"},
+       {ns_t_eid,      "EID",          "endpoint identifier (unimplemented)"},
+       {ns_t_nimloc,   "NIMLOC",       "NIMROD locator (unimplemented)"},
+       {ns_t_srv,      "SRV",          "server selection"},
+       {ns_t_atma,     "ATMA",         "ATM address (unimplemented)"},
+       {ns_t_naptr,    "NAPTR",        "naptr"},
+       {ns_t_kx,       "KX",           "key exchange"},
+       {ns_t_cert,     "CERT",         "certificate"},
+       {ns_t_a6,       "A",            "IPv6 address (experminental)"},
+       {ns_t_dname,    "DNAME",        "non-terminal redirection"},
+       {ns_t_opt,      "OPT",          "opt"},
+       {ns_t_apl,      "apl",          "apl"},
+       {ns_t_ds,       "DS",           "delegation signer"},
+       {ns_t_sshfp,    "SSFP",         "SSH fingerprint"},
+       {ns_t_ipseckey, "IPSECKEY",     "IPSEC key"},
+       {ns_t_rrsig,    "RRSIG",        "rrsig"},
+       {ns_t_nsec,     "NSEC",         "nsec"},
+       {ns_t_dnskey,   "DNSKEY",       "DNS key"},
+       {ns_t_dhcid,    "DHCID",       "dynamic host configuration identifier"},
+       {ns_t_nsec3,    "NSEC3",        "nsec3"},
+       {ns_t_nsec3param, "NSEC3PARAM", "NSEC3 parameters"},
+       {ns_t_hip,      "HIP",          "host identity protocol"},
+       {ns_t_spf,      "SPF",          "sender policy framework"},
+       {ns_t_tkey,     "TKEY",         "tkey"},
+       {ns_t_tsig,     "TSIG",         "transaction signature"},
+       {ns_t_ixfr,     "IXFR",         "incremental zone transfer"},
+       {ns_t_axfr,     "AXFR",         "zone transfer"},
+       {ns_t_zxfr,     "ZXFR",         "compressed zone transfer"},
+       {ns_t_mailb,    "MAILB",        "mailbox-related data (deprecated)"},
+       {ns_t_maila,    "MAILA",        "mail agent (deprecated)"},
+       {ns_t_naptr,    "NAPTR",        "URN Naming Authority"},
+       {ns_t_kx,       "KX",           "Key Exchange"},
+       {ns_t_cert,     "CERT",         "Certificate"},
+       {ns_t_a6,       "A6",           "IPv6 Address"},
+       {ns_t_dname,    "DNAME",        "dname"},
+       {ns_t_sink,     "SINK",         "Kitchen Sink (experimental)"},
+       {ns_t_opt,      "OPT",          "EDNS Options"},
+       {ns_t_any,      "ANY",          "\"any\""},
+       {ns_t_dlv,      "DLV",          "DNSSEC look-aside validation"},
+       {0,             NULL,           NULL}
+};
+
+/*%
+ * Names of DNS rcodes.
+ */
+const struct res_sym __p_rcode_syms[] = {
+       {ns_r_noerror,  "NOERROR",              "no error"},
+       {ns_r_formerr,  "FORMERR",              "format error"},
+       {ns_r_servfail, "SERVFAIL",             "server failed"},
+       {ns_r_nxdomain, "NXDOMAIN",             "no such domain name"},
+       {ns_r_notimpl,  "NOTIMP",               "not implemented"},
+       {ns_r_refused,  "REFUSED",              "refused"},
+       {ns_r_yxdomain, "YXDOMAIN",             "domain name exists"},
+       {ns_r_yxrrset,  "YXRRSET",              "rrset exists"},
+       {ns_r_nxrrset,  "NXRRSET",              "rrset doesn't exist"},
+       {ns_r_notauth,  "NOTAUTH",              "not authoritative"},
+       {ns_r_notzone,  "NOTZONE",              "Not in zone"},
+       {ns_r_max,      "",                     ""},
+       {ns_r_badsig,   "BADSIG",               "bad signature"},
+       {ns_r_badkey,   "BADKEY",               "bad key"},
+       {ns_r_badtime,  "BADTIME",              "bad time"},
+       {0,             NULL,                   NULL}
+};
+
+int
+sym_ston(const struct res_sym *syms, const char *name, int *success) {
+       for (; syms->name != 0; syms++) {
+               if (strcasecmp (name, syms->name) == 0) {
+                       if (success)
+                               *success = 1;
+                       return (syms->number);
+               }
+       }
+       if (success)
+               *success = 0;
+       return (syms->number);          /*%< The default value. */
+}
+
+const char *
+sym_ntos(const struct res_sym *syms, int number, int *success) {
+       char *unname = sym_ntos_unname;
+
+       for (; syms->name != 0; syms++) {
+               if (number == syms->number) {
+                       if (success)
+                               *success = 1;
+                       return (syms->name);
+               }
+       }
+
+       sprintf(unname, "%d", number);          /*%< XXX nonreentrant */
+       if (success)
+               *success = 0;
+       return (unname);
+}
+
+const char *
+sym_ntop(const struct res_sym *syms, int number, int *success) {
+       char *unname = sym_ntop_unname;
+
+       for (; syms->name != 0; syms++) {
+               if (number == syms->number) {
+                       if (success)
+                               *success = 1;
+                       return (syms->humanname);
+               }
+       }
+       sprintf(unname, "%d", number);          /*%< XXX nonreentrant */
+       if (success)
+               *success = 0;
+       return (unname);
+}
+
+/*%
+ * Return a string for the type.
+ */
+const char *
+p_type(int type) {
+       int success;
+       const char *result;
+       static char typebuf[20];
+
+       result = sym_ntos(__p_type_syms, type, &success);
+       if (success)
+               return (result);
+       if (type < 0 || type > 0xffff)
+               return ("BADTYPE");
+       sprintf(typebuf, "TYPE%d", type);
+       return (typebuf);
+}
+
+/*%
+ * Return a string for the type.
+ */
+const char *
+p_section(int section, int opcode) {
+       const struct res_sym *symbols;
+
+       switch (opcode) {
+       case ns_o_update:
+               symbols = __p_update_section_syms;
+               break;
+       default:
+               symbols = __p_default_section_syms;
+               break;
+       }
+       return (sym_ntos(symbols, section, (int *)0));
+}
+
+/*%
+ * Return a mnemonic for class.
+ */
+const char *
+p_class(int class) {
+       int success;
+       const char *result;
+       static char classbuf[20];
+
+       result = sym_ntos(__p_class_syms, class, &success);
+       if (success)
+               return (result);
+       if (class < 0 || class > 0xffff)
+               return ("BADCLASS");
+       sprintf(classbuf, "CLASS%d", class);
+       return (classbuf);
+}
+
+/*%
+ * Return a mnemonic for an option
+ */
+const char *
+p_option(u_long option) {
+       char *nbuf = p_option_nbuf;
+
+       switch (option) {
+       case RES_INIT:          return "init";
+       case RES_DEBUG:         return "debug";
+       case RES_AAONLY:        return "aaonly(unimpl)";
+       case RES_USEVC:         return "usevc";
+       case RES_PRIMARY:       return "primry(unimpl)";
+       case RES_IGNTC:         return "igntc";
+       case RES_RECURSE:       return "recurs";
+       case RES_DEFNAMES:      return "defnam";
+       case RES_STAYOPEN:      return "styopn";
+       case RES_DNSRCH:        return "dnsrch";
+       case RES_INSECURE1:     return "insecure1";
+       case RES_INSECURE2:     return "insecure2";
+       case RES_NOALIASES:     return "noaliases";
+       case RES_USE_INET6:     return "inet6";
+#ifdef RES_USE_EDNS0   /*%< KAME extension */
+       case RES_USE_EDNS0:     return "edns0";
+       case RES_NSID:          return "nsid";
+#endif
+#ifdef RES_USE_DNAME
+       case RES_USE_DNAME:     return "dname";
+#endif
+#ifdef RES_USE_DNSSEC
+       case RES_USE_DNSSEC:    return "dnssec";
+#endif
+#ifdef RES_NOTLDQUERY
+       case RES_NOTLDQUERY:    return "no-tld-query";
+#endif
+#ifdef RES_NO_NIBBLE2
+       case RES_NO_NIBBLE2:    return "no-nibble2";
+#endif
+                               /* XXX nonreentrant */
+       default:                sprintf(nbuf, "?0x%lx?", (u_long)option);
+                               return (nbuf);
+       }
+}
+
+/*%
+ * Return a mnemonic for a time to live.
+ */
+const char *
+p_time(u_int32_t value) {
+       char *nbuf = p_time_nbuf;
+
+       if (ns_format_ttl((u_long)value, nbuf, sizeof nbuf) < 0)
+               sprintf(nbuf, "%u", value);
+       return (nbuf);
+}
+
+/*%
+ * Return a string for the rcode.
+ */
+const char *
+p_rcode(int rcode) {
+       return (sym_ntos(__p_rcode_syms, rcode, (int *)0));
+}
+
+/*%
+ * Return a string for a res_sockaddr_union.
+ */
+const char *
+p_sockun(union res_sockaddr_union u, char *buf, size_t size) {
+       char ret[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:123.123.123.123"];
+
+       switch (u.sin.sin_family) {
+       case AF_INET:
+               inet_ntop(AF_INET, &u.sin.sin_addr, ret, sizeof ret);
+               break;
+#ifdef HAS_INET6_STRUCTS
+       case AF_INET6:
+               inet_ntop(AF_INET6, &u.sin6.sin6_addr, ret, sizeof ret);
+               break;
+#endif
+       default:
+               sprintf(ret, "[af%d]", u.sin.sin_family);
+               break;
+       }
+       if (size > 0U) {
+               strncpy(buf, ret, size - 1);
+               buf[size - 1] = '0';
+       }
+       return (buf);
+}
+
+/*%
+ * routines to convert between on-the-wire RR format and zone file format.
+ * Does not contain conversion to/from decimal degrees; divide or multiply
+ * by 60*60*1000 for that.
+ */
+
+static unsigned int poweroften[10] = {1, 10, 100, 1000, 10000, 100000,
+                                     1000000,10000000,100000000,1000000000};
+
+/*% takes an XeY precision/size value, returns a string representation. */
+static const char *
+precsize_ntoa(u_int32_t prec)
+{
+       char *retbuf = precsize_ntoa_retbuf;
+       unsigned long val;
+       int mantissa, exponent;
+
+       mantissa = (int)((prec >> 4) & 0x0f) % 10;
+       exponent = (int)((prec >> 0) & 0x0f) % 10;
+
+       val = mantissa * poweroften[exponent];
+
+       (void) sprintf(retbuf, "%lu.%.2lu", val/100, val%100);
+       return (retbuf);
+}
+
+/*% converts ascii size/precision X * 10**Y(cm) to 0xXY.  moves pointer.  */
+static u_int8_t
+precsize_aton(const char **strptr) {
+       unsigned int mval = 0, cmval = 0;
+       u_int8_t retval = 0;
+       const char *cp;
+       int exponent;
+       int mantissa;
+
+       cp = *strptr;
+
+       while (isdigit((unsigned char)*cp))
+               mval = mval * 10 + (*cp++ - '0');
+
+       if (*cp == '.') {               /*%< centimeters */
+               cp++;
+               if (isdigit((unsigned char)*cp)) {
+                       cmval = (*cp++ - '0') * 10;
+                       if (isdigit((unsigned char)*cp)) {
+                               cmval += (*cp++ - '0');
+                       }
+               }
+       }
+       cmval = (mval * 100) + cmval;
+
+       for (exponent = 0; exponent < 9; exponent++)
+               if (cmval < poweroften[exponent+1])
+                       break;
+
+       mantissa = cmval / poweroften[exponent];
+       if (mantissa > 9)
+               mantissa = 9;
+
+       retval = (mantissa << 4) | exponent;
+
+       *strptr = cp;
+
+       return (retval);
+}
+
+/*% converts ascii lat/lon to unsigned encoded 32-bit number.  moves pointer. */
+static u_int32_t
+latlon2ul(const char **latlonstrptr, int *which) {
+       const char *cp;
+       u_int32_t retval;
+       int deg = 0, min = 0, secs = 0, secsfrac = 0;
+
+       cp = *latlonstrptr;
+
+       while (isdigit((unsigned char)*cp))
+               deg = deg * 10 + (*cp++ - '0');
+
+       while (isspace((unsigned char)*cp))
+               cp++;
+
+       if (!(isdigit((unsigned char)*cp)))
+               goto fndhemi;
+
+       while (isdigit((unsigned char)*cp))
+               min = min * 10 + (*cp++ - '0');
+
+       while (isspace((unsigned char)*cp))
+               cp++;
+
+       if (!(isdigit((unsigned char)*cp)))
+               goto fndhemi;
+
+       while (isdigit((unsigned char)*cp))
+               secs = secs * 10 + (*cp++ - '0');
+
+       if (*cp == '.') {               /*%< decimal seconds */
+               cp++;
+               if (isdigit((unsigned char)*cp)) {
+                       secsfrac = (*cp++ - '0') * 100;
+                       if (isdigit((unsigned char)*cp)) {
+                               secsfrac += (*cp++ - '0') * 10;
+                               if (isdigit((unsigned char)*cp)) {
+                                       secsfrac += (*cp++ - '0');
+                               }
+                       }
+               }
+       }
+
+       while (!isspace((unsigned char)*cp))    /*%< if any trailing garbage */
+               cp++;
+
+       while (isspace((unsigned char)*cp))
+               cp++;
+
+ fndhemi:
+       switch (*cp) {
+       case 'N': case 'n':
+       case 'E': case 'e':
+               retval = ((unsigned)1<<31)
+                       + (((((deg * 60) + min) * 60) + secs) * 1000)
+                       + secsfrac;
+               break;
+       case 'S': case 's':
+       case 'W': case 'w':
+               retval = ((unsigned)1<<31)
+                       - (((((deg * 60) + min) * 60) + secs) * 1000)
+                       - secsfrac;
+               break;
+       default:
+               retval = 0;     /*%< invalid value -- indicates error */
+               break;
+       }
+
+       switch (*cp) {
+       case 'N': case 'n':
+       case 'S': case 's':
+               *which = 1;     /*%< latitude */
+               break;
+       case 'E': case 'e':
+       case 'W': case 'w':
+               *which = 2;     /*%< longitude */
+               break;
+       default:
+               *which = 0;     /*%< error */
+               break;
+       }
+
+       cp++;                   /*%< skip the hemisphere */
+       while (!isspace((unsigned char)*cp))    /*%< if any trailing garbage */
+               cp++;
+
+       while (isspace((unsigned char)*cp))     /*%< move to next field */
+               cp++;
+
+       *latlonstrptr = cp;
+
+       return (retval);
+}
+
+/*%
+ * converts a zone file representation in a string to an RDATA on-the-wire
+ * representation. */
+int
+loc_aton(ascii, binary)
+       const char *ascii;
+       u_char *binary;
+{
+       const char *cp, *maxcp;
+       u_char *bcp;
+
+       u_int32_t latit = 0, longit = 0, alt = 0;
+       u_int32_t lltemp1 = 0, lltemp2 = 0;
+       int altmeters = 0, altfrac = 0, altsign = 1;
+       u_int8_t hp = 0x16;     /*%< default = 1e6 cm = 10000.00m = 10km */
+       u_int8_t vp = 0x13;     /*%< default = 1e3 cm = 10.00m */
+       u_int8_t siz = 0x12;    /*%< default = 1e2 cm = 1.00m */
+       int which1 = 0, which2 = 0;
+
+       cp = ascii;
+       maxcp = cp + strlen(ascii);
+
+       lltemp1 = latlon2ul(&cp, &which1);
+
+       lltemp2 = latlon2ul(&cp, &which2);
+
+       switch (which1 + which2) {
+       case 3:                 /*%< 1 + 2, the only valid combination */
+               if ((which1 == 1) && (which2 == 2)) { /*%< normal case */
+                       latit = lltemp1;
+                       longit = lltemp2;
+               } else if ((which1 == 2) && (which2 == 1)) { /*%< reversed */
+                       longit = lltemp1;
+                       latit = lltemp2;
+               } else {        /*%< some kind of brokenness */
+                       return (0);
+               }
+               break;
+       default:                /*%< we didn't get one of each */
+               return (0);
+       }
+
+       /* altitude */
+       if (*cp == '-') {
+               altsign = -1;
+               cp++;
+       }
+
+       if (*cp == '+')
+               cp++;
+
+       while (isdigit((unsigned char)*cp))
+               altmeters = altmeters * 10 + (*cp++ - '0');
+
+       if (*cp == '.') {               /*%< decimal meters */
+               cp++;
+               if (isdigit((unsigned char)*cp)) {
+                       altfrac = (*cp++ - '0') * 10;
+                       if (isdigit((unsigned char)*cp)) {
+                               altfrac += (*cp++ - '0');
+                       }
+               }
+       }
+
+       alt = (10000000 + (altsign * (altmeters * 100 + altfrac)));
+
+       while (!isspace((unsigned char)*cp) && (cp < maxcp)) /*%< if trailing garbage or m */
+               cp++;
+
+       while (isspace((unsigned char)*cp) && (cp < maxcp))
+               cp++;
+
+       if (cp >= maxcp)
+               goto defaults;
+
+       siz = precsize_aton(&cp);
+
+       while (!isspace((unsigned char)*cp) && (cp < maxcp))    /*%< if trailing garbage or m */
+               cp++;
+
+       while (isspace((unsigned char)*cp) && (cp < maxcp))
+               cp++;
+
+       if (cp >= maxcp)
+               goto defaults;
+
+       hp = precsize_aton(&cp);
+
+       while (!isspace((unsigned char)*cp) && (cp < maxcp))    /*%< if trailing garbage or m */
+               cp++;
+
+       while (isspace((unsigned char)*cp) && (cp < maxcp))
+               cp++;
+
+       if (cp >= maxcp)
+               goto defaults;
+
+       vp = precsize_aton(&cp);
+
+ defaults:
+
+       bcp = binary;
+       *bcp++ = (u_int8_t) 0;  /*%< version byte */
+       *bcp++ = siz;
+       *bcp++ = hp;
+       *bcp++ = vp;
+       PUTLONG(latit,bcp);
+       PUTLONG(longit,bcp);
+       PUTLONG(alt,bcp);
+
+       return (16);            /*%< size of RR in octets */
+}
+
+/*% takes an on-the-wire LOC RR and formats it in a human readable format. */
+const char *
+loc_ntoa(binary, ascii)
+       const u_char *binary;
+       char *ascii;
+{
+       static const char *error = "?";
+       static char tmpbuf[sizeof
+"1000 60 60.000 N 1000 60 60.000 W -12345678.00m 90000000.00m 90000000.00m 90000000.00m"];
+       const u_char *cp = binary;
+
+       int latdeg, latmin, latsec, latsecfrac;
+       int longdeg, longmin, longsec, longsecfrac;
+       char northsouth, eastwest;
+       const char *altsign;
+       int altmeters, altfrac;
+
+       const u_int32_t referencealt = 100000 * 100;
+
+       int32_t latval, longval, altval;
+       u_int32_t templ;
+       u_int8_t sizeval, hpval, vpval, versionval;
+
+       char *sizestr, *hpstr, *vpstr;
+
+       versionval = *cp++;
+
+       if (ascii == NULL)
+               ascii = tmpbuf;
+
+       if (versionval) {
+               (void) sprintf(ascii, "; error: unknown LOC RR version");
+               return (ascii);
+       }
+
+       sizeval = *cp++;
+
+       hpval = *cp++;
+       vpval = *cp++;
+
+       GETLONG(templ, cp);
+       latval = (templ - ((unsigned)1<<31));
+
+       GETLONG(templ, cp);
+       longval = (templ - ((unsigned)1<<31));
+
+       GETLONG(templ, cp);
+       if (templ < referencealt) { /*%< below WGS 84 spheroid */
+               altval = referencealt - templ;
+               altsign = "-";
+       } else {
+               altval = templ - referencealt;
+               altsign = "";
+       }
+
+       if (latval < 0) {
+               northsouth = 'S';
+               latval = -latval;
+       } else
+               northsouth = 'N';
+
+       latsecfrac = latval % 1000;
+       latval = latval / 1000;
+       latsec = latval % 60;
+       latval = latval / 60;
+       latmin = latval % 60;
+       latval = latval / 60;
+       latdeg = latval;
+
+       if (longval < 0) {
+               eastwest = 'W';
+               longval = -longval;
+       } else
+               eastwest = 'E';
+
+       longsecfrac = longval % 1000;
+       longval = longval / 1000;
+       longsec = longval % 60;
+       longval = longval / 60;
+       longmin = longval % 60;
+       longval = longval / 60;
+       longdeg = longval;
+
+       altfrac = altval % 100;
+       altmeters = (altval / 100);
+
+       sizestr = strdup(precsize_ntoa((u_int32_t)sizeval));
+       hpstr = strdup(precsize_ntoa((u_int32_t)hpval));
+       vpstr = strdup(precsize_ntoa((u_int32_t)vpval));
+
+       sprintf(ascii,
+           "%d %.2d %.2d.%.3d %c %d %.2d %.2d.%.3d %c %s%d.%.2dm %sm %sm %sm",
+               latdeg, latmin, latsec, latsecfrac, northsouth,
+               longdeg, longmin, longsec, longsecfrac, eastwest,
+               altsign, altmeters, altfrac,
+               (sizestr != NULL) ? sizestr : error,
+               (hpstr != NULL) ? hpstr : error,
+               (vpstr != NULL) ? vpstr : error);
+
+       if (sizestr != NULL)
+               free(sizestr);
+       if (hpstr != NULL)
+               free(hpstr);
+       if (vpstr != NULL)
+               free(vpstr);
+
+       return (ascii);
+}
+
+
+/*% Return the number of DNS hierarchy levels in the name. */
+int
+dn_count_labels(const char *name) {
+       int i, len, count;
+
+       len = strlen(name);
+       for (i = 0, count = 0; i < len; i++) {
+               /* XXX need to check for \. or use named's nlabels(). */
+               if (name[i] == '.')
+                       count++;
+       }
+
+       /* don't count initial wildcard */
+       if (name[0] == '*')
+               if (count)
+                       count--;
+
+       /* don't count the null label for root. */
+       /* if terminating '.' not found, must adjust */
+       /* count to include last label */
+       if (len > 0 && name[len-1] != '.')
+               count++;
+       return (count);
+}
+
+/*%
+ * Make dates expressed in seconds-since-Jan-1-1970 easy to read.
+ * SIG records are required to be printed like this, by the Secure DNS RFC.
+ */
+char *
+p_secstodate (u_long secs) {
+       /* XXX nonreentrant */
+       char *output = p_secstodate_output;
+       time_t myclock = secs;
+       struct tm *mytime;
+#ifdef HAVE_TIME_R
+       struct tm res;
+       
+       mytime = gmtime_r(&myclock, &res);
+#else
+       mytime = gmtime(&myclock);
+#endif
+       mytime->tm_year += 1900;
+       mytime->tm_mon += 1;
+       sprintf(output, "%04d%02d%02d%02d%02d%02d",
+               mytime->tm_year, mytime->tm_mon, mytime->tm_mday,
+               mytime->tm_hour, mytime->tm_min, mytime->tm_sec);
+       return (output);
+}
+
+u_int16_t
+res_nametoclass(const char *buf, int *successp) {
+       unsigned long result;
+       char *endptr;
+       int success;
+
+       result = sym_ston(__p_class_syms, buf, &success);
+       if (success)
+               goto done;
+
+       if (strncasecmp(buf, "CLASS", 5) != 0 ||
+           !isdigit((unsigned char)buf[5]))
+               goto done;
+       errno = 0;
+       result = strtoul(buf + 5, &endptr, 10);
+       if (errno == 0 && *endptr == '\0' && result <= 0xffffU)
+               success = 1;
+ done:
+       if (successp)
+               *successp = success;
+       return (u_int16_t)(result);
+}
+
+u_int16_t
+res_nametotype(const char *buf, int *successp) {
+       unsigned long result;
+       char *endptr;
+       int success;
+
+       result = sym_ston(__p_type_syms, buf, &success);
+       if (success)
+               goto done;
+
+       if (strncasecmp(buf, "type", 4) != 0 ||
+           !isdigit((unsigned char)buf[4]))
+               goto done;
+       errno = 0;
+       result = strtoul(buf + 4, &endptr, 10);
+       if (errno == 0 && *endptr == '\0' && result <= 0xffffU)
+               success = 1;
+ done:
+       if (successp)
+               *successp = success;
+       return (u_int16_t)(result);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/resolv/res_debug.h b/lib/nbsd_libc/resolv/res_debug.h
new file mode 100644 (file)
index 0000000..dc7e96a
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: res_debug.h,v 1.1.1.4 2009/04/12 16:35:47 christos Exp $       */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#ifndef _RES_DEBUG_H_
+#define _RES_DEBUG_H_
+
+#ifndef DEBUG
+#   define Dprint(cond, args) /*empty*/
+#   define DprintQ(cond, args, query, size) /*empty*/
+#   define Aerror(statp, file, string, error, address) /*empty*/
+#   define Perror(statp, file, string, error) /*empty*/
+#else
+#   define Dprint(cond, args) if (cond) {fprintf args;} else {}
+#   define DprintQ(cond, args, query, size) if (cond) {\
+                       fprintf args;\
+                       res_pquery(statp, query, size, stdout);\
+               } else {}
+#endif
+
+#endif /* _RES_DEBUG_H_ */ 
+/*! \file */
diff --git a/lib/nbsd_libc/resolv/res_init.c b/lib/nbsd_libc/resolv/res_init.c
new file mode 100644 (file)
index 0000000..4668c98
--- /dev/null
@@ -0,0 +1,940 @@
+/*     $NetBSD: res_init.c,v 1.22 2009/10/24 17:24:01 christos Exp $   */
+
+/*
+ * Copyright (c) 1985, 1989, 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+/*
+ * Portions Copyright (c) 1993 by Digital Equipment Corporation.
+ * 
+ * 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, and that
+ * the name of Digital Equipment Corporation not be used in advertising or
+ * publicity pertaining to distribution of the document or software without
+ * specific, written prior permission.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
+ * CORPORATION 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.
+ */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#ifdef notdef
+static const char sccsid[] = "@(#)res_init.c   8.1 (Berkeley) 6/7/93";
+static const char rcsid[] = "Id: res_init.c,v 1.26 2008/12/11 09:59:00 marka Exp";
+#else
+__RCSID("$NetBSD: res_init.c,v 1.22 2009/10/24 17:24:01 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/event.h>
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <netdb.h>
+
+#define HAVE_MD5
+#include <md5.h>
+
+#ifndef HAVE_MD5
+# include "../dst/md5.h"
+#else
+# ifdef SOLARIS2
+#  include <sys/md5.h>
+# endif
+#endif
+#ifndef _MD5_H_
+# define _MD5_H_ 1     /*%< make sure we do not include rsaref md5.h file */
+#endif
+
+#include "port_after.h"
+
+#if 0
+#ifdef __weak_alias
+__weak_alias(res_ninit,_res_ninit)
+__weak_alias(res_randomid,__res_randomid)
+__weak_alias(res_nclose,_res_nclose)
+__weak_alias(res_ndestroy,_res_ndestroy)
+__weak_alias(res_get_nibblesuffix,__res_get_nibblesuffix)
+__weak_alias(res_get_nibblesuffix2,__res_get_nibblesuffix2)
+__weak_alias(res_getservers,__res_getservers)
+__weak_alias(res_setservers,__res_setservers)
+#endif
+#endif
+
+
+/* ensure that sockaddr_in6 and IN6ADDR_ANY_INIT are declared / defined */
+#include <resolv.h>
+
+#include "res_private.h"
+
+#define RESOLVSORT
+/*% Options.  Should all be left alone. */
+#ifndef DEBUG
+#define DEBUG
+#endif
+
+#ifdef SOLARIS2
+#include <sys/systeminfo.h>
+#endif
+
+static void res_setoptions __P((res_state, const char *, const char *));
+
+#ifdef RESOLVSORT
+static const char sort_mask[] = "/&";
+#define ISSORTMASK(ch) (strchr(sort_mask, ch) != NULL)
+static u_int32_t net_mask __P((struct in_addr));
+#endif
+
+#if !defined(isascii)  /*%< XXX - could be a function */
+# define isascii(c) (!(c & 0200))
+#endif
+
+static struct timespec __res_conf_time;
+static const struct timespec ts = { 0, 0 };
+
+/*
+ * Resolver state default settings.
+ */
+
+/*%
+ * Set up default settings.  If the configuration file exist, the values
+ * there will have precedence.  Otherwise, the server address is set to
+ * INADDR_ANY and the default domain name comes from the gethostname().
+ *
+ * An interrim version of this code (BIND 4.9, pre-4.4BSD) used 127.0.0.1
+ * rather than INADDR_ANY ("0.0.0.0") as the default name server address
+ * since it was noted that INADDR_ANY actually meant ``the first interface
+ * you "ifconfig"'d at boot time'' and if this was a SLIP or PPP interface,
+ * it had to be "up" in order for you to reach your own name server.  It
+ * was later decided that since the recommended practice is to always 
+ * install local static routes through 127.0.0.1 for all your network
+ * interfaces, that we could solve this problem without a code change.
+ *
+ * The configuration file should always be used, since it is the only way
+ * to specify a default domain.  If you are running a server on your local
+ * machine, you should say "nameserver 0.0.0.0" or "nameserver 127.0.0.1"
+ * in the configuration file.
+ *
+ * Return 0 if completes successfully, -1 on error
+ */
+int
+res_ninit(res_state statp) {
+       return (__res_vinit(statp, 0));
+}
+
+/*% This function has to be reachable by res_data.c but not publically. */
+int
+__res_vinit(res_state statp, int preinit) {
+       register FILE *fp;
+       register char *cp, **pp;
+       register int n;
+       char buf[BUFSIZ];
+       int nserv = 0;    /*%< number of nameserver records read from file */
+       int haveenv = 0;
+       int havesearch = 0;
+#ifdef RESOLVSORT
+       int nsort = 0;
+       char *net;
+#endif
+       int dots;
+       union res_sockaddr_union u[2];
+       int maxns = MAXNS;
+
+       RES_SET_H_ERRNO(statp, 0);
+
+       if ((statp->options & RES_INIT) != 0U)
+               res_ndestroy(statp);
+
+       if (!preinit) {
+               statp->retrans = RES_TIMEOUT;
+               statp->retry = RES_DFLRETRY;
+               statp->options = RES_DEFAULT;
+       }
+       statp->_rnd = malloc(16);
+       res_rndinit(statp);
+       statp->id = res_nrandomid(statp);
+
+       memset(u, 0, sizeof(u));
+#ifdef USELOOPBACK
+       u[nserv].sin.sin_addr = inet_makeaddr(IN_LOOPBACKNET, 1);
+#else
+       u[nserv].sin.sin_addr.s_addr = INADDR_ANY;
+#endif
+       u[nserv].sin.sin_family = AF_INET;
+       u[nserv].sin.sin_port = htons(NAMESERVER_PORT);
+#ifdef HAVE_SA_LEN
+       u[nserv].sin.sin_len = sizeof(struct sockaddr_in);
+#endif
+       nserv++;
+#ifdef HAS_INET6_STRUCTS
+#ifdef USELOOPBACK
+       u[nserv].sin6.sin6_addr = in6addr_loopback;
+#else
+       u[nserv].sin6.sin6_addr = in6addr_any;
+#endif
+       u[nserv].sin6.sin6_family = AF_INET6;
+       u[nserv].sin6.sin6_port = htons(NAMESERVER_PORT);
+#ifdef HAVE_SA_LEN
+       u[nserv].sin6.sin6_len = sizeof(struct sockaddr_in6);
+#endif
+       nserv++;
+#endif
+       statp->nscount = 0;
+       statp->ndots = 1;
+       statp->pfcode = 0;
+       statp->_vcsock = -1;
+       statp->_flags = 0;
+       statp->qhook = NULL;
+       statp->rhook = NULL;
+       statp->_u._ext.nscount = 0;
+       statp->_u._ext.ext = malloc(sizeof(*statp->_u._ext.ext));
+       if (statp->_u._ext.ext != NULL) {
+               memset(statp->_u._ext.ext, 0, sizeof(*statp->_u._ext.ext));
+               statp->_u._ext.ext->nsaddrs[0].sin = statp->nsaddr;
+               strcpy(statp->_u._ext.ext->nsuffix, "ip6.arpa");
+               strcpy(statp->_u._ext.ext->nsuffix2, "ip6.int");
+       } else {
+               /*
+                * Historically res_init() rarely, if at all, failed.
+                * Examples and applications exist which do not check
+                * our return code.  Furthermore several applications
+                * simply call us to get the systems domainname.  So
+                * rather then immediately fail here we store the
+                * failure, which is returned later, in h_errno.  And
+                * prevent the collection of 'nameserver' information
+                * by setting maxns to 0.  Thus applications that fail
+                * to check our return code wont be able to make
+                * queries anyhow.
+                */
+               RES_SET_H_ERRNO(statp, NETDB_INTERNAL);
+               maxns = 0;
+       }
+#ifdef RESOLVSORT
+       statp->nsort = 0;
+#endif
+       res_setservers(statp, u, nserv);
+
+#ifdef SOLARIS2
+       /*
+        * The old libresolv derived the defaultdomain from NIS/NIS+.
+        * We want to keep this behaviour
+        */
+       {
+               char buf[sizeof(statp->defdname)], *cp;
+               int ret;
+
+               if ((ret = sysinfo(SI_SRPC_DOMAIN, buf, sizeof(buf))) > 0 &&
+                       (unsigned int)ret <= sizeof(buf)) {
+                       if (buf[0] == '+')
+                               buf[0] = '.';
+                       cp = strchr(buf, '.');
+                       cp = (cp == NULL) ? buf : (cp + 1);
+                       (void)strlcpy(statp->defdname, cp,
+                           sizeof(statp->defdname));
+               }
+       }
+#endif /* SOLARIS2 */
+
+       /* Allow user to override the local domain definition */
+       if ((cp = getenv("LOCALDOMAIN")) != NULL) {
+               (void)strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
+               statp->defdname[sizeof(statp->defdname) - 1] = '\0';
+               haveenv++;
+
+               /*
+                * Set search list to be blank-separated strings
+                * from rest of env value.  Permits users of LOCALDOMAIN
+                * to still have a search list, and anyone to set the
+                * one that they want to use as an individual (even more
+                * important now that the rfc1535 stuff restricts searches)
+                */
+               cp = statp->defdname;
+               pp = statp->dnsrch;
+               *pp++ = cp;
+               for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
+                       if (*cp == '\n')        /*%< silly backwards compat */
+                               break;
+                       else if (*cp == ' ' || *cp == '\t') {
+                               *cp = 0;
+                               n = 1;
+                       } else if (n) {
+                               *pp++ = cp;
+                               n = 0;
+                               havesearch = 1;
+                       }
+               }
+               /* null terminate last domain if there are excess */
+               while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
+                       cp++;
+               *cp = '\0';
+               *pp++ = 0;
+       }
+
+#define        MATCH(line, name) \
+       (!strncmp(line, name, sizeof(name) - 1) && \
+       (line[sizeof(name) - 1] == ' ' || \
+        line[sizeof(name) - 1] == '\t'))
+
+       nserv = 0;
+       if ((fp = fopen(_PATH_RESCONF, "r")) != NULL) {
+           struct stat st;
+           struct kevent kc;
+
+           /* read the config file */
+           while (fgets(buf, sizeof(buf), fp) != NULL) {
+               /* skip comments */
+               if (*buf == ';' || *buf == '#')
+                       continue;
+               /* read default domain name */
+               if (MATCH(buf, "domain")) {
+                   if (haveenv)        /*%< skip if have from environ */
+                           continue;
+                   cp = buf + sizeof("domain") - 1;
+                   while (*cp == ' ' || *cp == '\t')
+                           cp++;
+                   if ((*cp == '\0') || (*cp == '\n'))
+                           continue;
+                   strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
+                   statp->defdname[sizeof(statp->defdname) - 1] = '\0';
+                   if ((cp = strpbrk(statp->defdname, " \t\n")) != NULL)
+                           *cp = '\0';
+                   havesearch = 0;
+                   continue;
+               }
+               /* set search list */
+               if (MATCH(buf, "search")) {
+                   if (haveenv)        /*%< skip if have from environ */
+                           continue;
+                   cp = buf + sizeof("search") - 1;
+                   while (*cp == ' ' || *cp == '\t')
+                           cp++;
+                   if ((*cp == '\0') || (*cp == '\n'))
+                           continue;
+                   strncpy(statp->defdname, cp, sizeof(statp->defdname) - 1);
+                   statp->defdname[sizeof(statp->defdname) - 1] = '\0';
+                   if ((cp = strchr(statp->defdname, '\n')) != NULL)
+                           *cp = '\0';
+                   /*
+                    * Set search list to be blank-separated strings
+                    * on rest of line.
+                    */
+                   cp = statp->defdname;
+                   pp = statp->dnsrch;
+                   *pp++ = cp;
+                   for (n = 0; *cp && pp < statp->dnsrch + MAXDNSRCH; cp++) {
+                           if (*cp == ' ' || *cp == '\t') {
+                                   *cp = 0;
+                                   n = 1;
+                           } else if (n) {
+                                   *pp++ = cp;
+                                   n = 0;
+                           }
+                   }
+                   /* null terminate last domain if there are excess */
+                   while (*cp != '\0' && *cp != ' ' && *cp != '\t')
+                           cp++;
+                   *cp = '\0';
+                   *pp++ = 0;
+                   havesearch = 1;
+                   continue;
+               }
+               /* read nameservers to query */
+               if (MATCH(buf, "nameserver") && nserv < maxns) {
+                   struct addrinfo hints, *ai;
+                   char sbuf[NI_MAXSERV];
+                   const size_t minsiz =
+                       sizeof(statp->_u._ext.ext->nsaddrs[0]);
+
+                   cp = buf + sizeof("nameserver") - 1;
+                   while (*cp == ' ' || *cp == '\t')
+                       cp++;
+                   cp[strcspn(cp, ";# \t\n")] = '\0';
+                   if ((*cp != '\0') && (*cp != '\n')) {
+                       memset(&hints, 0, sizeof(hints));
+                       hints.ai_family = PF_UNSPEC;
+                       hints.ai_socktype = SOCK_DGRAM; /*dummy*/
+                       hints.ai_flags = AI_NUMERICHOST;
+                       sprintf(sbuf, "%u", NAMESERVER_PORT);
+                       if (getaddrinfo(cp, sbuf, &hints, &ai) == 0 &&
+                           ai->ai_addrlen <= minsiz) {
+                           if (statp->_u._ext.ext != NULL) {
+                               memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
+                                   ai->ai_addr, ai->ai_addrlen);
+                           }
+                           if (ai->ai_addrlen <=
+                               sizeof(statp->nsaddr_list[nserv])) {
+                               memcpy(&statp->nsaddr_list[nserv],
+                                   ai->ai_addr, ai->ai_addrlen);
+                           } else
+                               statp->nsaddr_list[nserv].sin_family = 0;
+                           freeaddrinfo(ai);
+                           nserv++;
+                       }
+                   }
+                   continue;
+               }
+#ifdef RESOLVSORT
+               if (MATCH(buf, "sortlist")) {
+                   struct in_addr a;
+
+                   cp = buf + sizeof("sortlist") - 1;
+                   while (nsort < MAXRESOLVSORT) {
+                       while (*cp == ' ' || *cp == '\t')
+                           cp++;
+                       if (*cp == '\0' || *cp == '\n' || *cp == ';')
+                           break;
+                       net = cp;
+                       while (*cp && !ISSORTMASK(*cp) && *cp != ';' &&
+                              isascii(*cp) && !isspace((unsigned char)*cp))
+                               cp++;
+                       n = *cp;
+                       *cp = 0;
+                       if (inet_aton(net, &a)) {
+                           statp->sort_list[nsort].addr = a;
+                           if (ISSORTMASK(n)) {
+                               *cp++ = n;
+                               net = cp;
+                               while (*cp && *cp != ';' &&
+                                       isascii(*cp) &&
+                                       !isspace((unsigned char)*cp))
+                                   cp++;
+                               n = *cp;
+                               *cp = 0;
+                               if (inet_aton(net, &a)) {
+                                   statp->sort_list[nsort].mask = a.s_addr;
+                               } else {
+                                   statp->sort_list[nsort].mask = 
+                                       net_mask(statp->sort_list[nsort].addr);
+                               }
+                           } else {
+                               statp->sort_list[nsort].mask = 
+                                   net_mask(statp->sort_list[nsort].addr);
+                           }
+                           nsort++;
+                       }
+                       *cp = n;
+                   }
+                   continue;
+               }
+#endif
+               if (MATCH(buf, "options")) {
+                   res_setoptions(statp, buf + sizeof("options") - 1, "conf");
+                   continue;
+               }
+           }
+           if (nserv > 0) 
+               statp->nscount = nserv;
+#ifdef RESOLVSORT
+           statp->nsort = nsort;
+#endif
+           statp->_u._ext.ext->resfd = dup(fileno(fp));
+           (void) fclose(fp);
+           if (fstat(statp->_u._ext.ext->resfd, &st) != -1)
+                   __res_conf_time = statp->_u._ext.ext->res_conf_time =
+                       st.st_mtimespec;
+           statp->_u._ext.ext->kq = kqueue();
+           (void)fcntl(statp->_u._ext.ext->kq, F_SETFD, FD_CLOEXEC);
+           (void)fcntl(statp->_u._ext.ext->resfd, F_SETFD, FD_CLOEXEC);
+           EV_SET(&kc, statp->_u._ext.ext->resfd, EVFILT_VNODE,
+               EV_ADD|EV_ENABLE|EV_CLEAR, NOTE_DELETE|NOTE_WRITE| NOTE_EXTEND|
+               NOTE_ATTRIB|NOTE_LINK|NOTE_RENAME|NOTE_REVOKE, 0, 0);
+           (void)kevent(statp->_u._ext.ext->kq, &kc, 1, NULL, 0, &ts);
+       } else {
+           statp->_u._ext.ext->kq = -1;
+           statp->_u._ext.ext->resfd = -1;
+       }
+/*
+ * Last chance to get a nameserver.  This should not normally
+ * be necessary
+ */
+#ifdef NO_RESOLV_CONF
+       if(nserv == 0)
+               nserv = get_nameservers(statp);
+#endif
+
+       if (statp->defdname[0] == 0 &&
+           gethostname(buf, sizeof(statp->defdname) - 1) == 0 &&
+           (cp = strchr(buf, '.')) != NULL)
+               strcpy(statp->defdname, cp + 1);
+
+       /* find components of local domain that might be searched */
+       if (havesearch == 0) {
+               pp = statp->dnsrch;
+               *pp++ = statp->defdname;
+               *pp = NULL;
+
+               dots = 0;
+               for (cp = statp->defdname; *cp; cp++)
+                       dots += (*cp == '.');
+
+               cp = statp->defdname;
+               while (pp < statp->dnsrch + MAXDFLSRCH) {
+                       if (dots < LOCALDOMAINPARTS)
+                               break;
+                       cp = strchr(cp, '.') + 1;    /*%< we know there is one */
+                       *pp++ = cp;
+                       dots--;
+               }
+               *pp = NULL;
+#ifdef DEBUG
+               if (statp->options & RES_DEBUG) {
+                       printf(";; res_init()... default dnsrch list:\n");
+                       for (pp = statp->dnsrch; *pp; pp++)
+                               printf(";;\t%s\n", *pp);
+                       printf(";;\t..END..\n");
+               }
+#endif
+       }
+
+       if ((cp = getenv("RES_OPTIONS")) != NULL)
+               res_setoptions(statp, cp, "env");
+       statp->options |= RES_INIT;
+       return (statp->res_h_errno);
+}
+
+int
+res_check(res_state statp, struct timespec *mtime)
+{
+       /*
+        * If the times are equal, then we check if there
+        * was a kevent related to resolv.conf and reload.
+        * If the times are not equal, then we don't bother
+        * to check the kevent, because another thread already
+        * did, loaded and changed the time.
+        */
+       if (timespeccmp(&statp->_u._ext.ext->res_conf_time,
+           &__res_conf_time, ==)) {
+               struct kevent ke;
+               if (statp->_u._ext.ext->kq == -1)
+                       goto out;
+
+               switch (kevent(statp->_u._ext.ext->kq, NULL, 0, &ke, 1, &ts)) {
+               case 0:
+               case -1:
+out:
+                       if (mtime)
+                               *mtime = __res_conf_time;
+                       return 0;
+               default:
+                       break;
+               }
+       }
+       (void)__res_vinit(statp, 0);
+       if (mtime)
+               *mtime = __res_conf_time;
+       return 1;
+}
+
+static void
+res_setoptions(res_state statp, const char *options, const char *source)
+{
+       const char *cp = options;
+       int i;
+       struct __res_state_ext *ext = statp->_u._ext.ext;
+
+#ifdef DEBUG
+       if (statp->options & RES_DEBUG)
+               printf(";; res_setoptions(\"%s\", \"%s\")...\n",
+                      options, source);
+#endif
+       while (*cp) {
+               /* skip leading and inner runs of spaces */
+               while (*cp == ' ' || *cp == '\t')
+                       cp++;
+               /* search for and process individual options */
+               if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
+                       i = atoi(cp + sizeof("ndots:") - 1);
+                       if (i <= RES_MAXNDOTS)
+                               statp->ndots = i;
+                       else
+                               statp->ndots = RES_MAXNDOTS;
+#ifdef DEBUG
+                       if (statp->options & RES_DEBUG)
+                               printf(";;\tndots=%d\n", statp->ndots);
+#endif
+               } else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
+                       i = atoi(cp + sizeof("timeout:") - 1);
+                       if (i <= RES_MAXRETRANS)
+                               statp->retrans = i;
+                       else
+                               statp->retrans = RES_MAXRETRANS;
+#ifdef DEBUG
+                       if (statp->options & RES_DEBUG)
+                               printf(";;\ttimeout=%d\n", statp->retrans);
+#endif
+#ifdef SOLARIS2
+               } else if (!strncmp(cp, "retrans:", sizeof("retrans:") - 1)) {
+                       /*
+                        * For backward compatibility, 'retrans' is
+                        * supported as an alias for 'timeout', though
+                        * without an imposed maximum.
+                        */
+                       statp->retrans = atoi(cp + sizeof("retrans:") - 1);
+               } else if (!strncmp(cp, "retry:", sizeof("retry:") - 1)){
+                       /*
+                        * For backward compatibility, 'retry' is
+                        * supported as an alias for 'attempts', though
+                        * without an imposed maximum.
+                        */
+                       statp->retry = atoi(cp + sizeof("retry:") - 1);
+#endif /* SOLARIS2 */
+               } else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)){
+                       i = atoi(cp + sizeof("attempts:") - 1);
+                       if (i <= RES_MAXRETRY)
+                               statp->retry = i;
+                       else
+                               statp->retry = RES_MAXRETRY;
+#ifdef DEBUG
+                       if (statp->options & RES_DEBUG)
+                               printf(";;\tattempts=%d\n", statp->retry);
+#endif
+               } else if (!strncmp(cp, "debug", sizeof("debug") - 1)) {
+#ifdef DEBUG
+                       if (!(statp->options & RES_DEBUG)) {
+                               printf(";; res_setoptions(\"%s\", \"%s\")..\n",
+                                      options, source);
+                               statp->options |= RES_DEBUG;
+                       }
+                       printf(";;\tdebug\n");
+#endif
+               } else if (!strncmp(cp, "no_tld_query",
+                                   sizeof("no_tld_query") - 1) ||
+                          !strncmp(cp, "no-tld-query",
+                                   sizeof("no-tld-query") - 1)) {
+                       statp->options |= RES_NOTLDQUERY;
+               } else if (!strncmp(cp, "inet6", sizeof("inet6") - 1)) {
+                       statp->options |= RES_USE_INET6;
+               } else if (!strncmp(cp, "rotate", sizeof("rotate") - 1)) {
+                       statp->options |= RES_ROTATE;
+               } else if (!strncmp(cp, "no-check-names",
+                                   sizeof("no-check-names") - 1)) {
+                       statp->options |= RES_NOCHECKNAME;
+               }
+#ifdef RES_USE_EDNS0
+               else if (!strncmp(cp, "edns0", sizeof("edns0") - 1)) {
+                       statp->options |= RES_USE_EDNS0;
+               }
+#endif
+               else if (!strncmp(cp, "dname", sizeof("dname") - 1)) {
+                       statp->options |= RES_USE_DNAME;
+               }
+               else if (!strncmp(cp, "nibble:", sizeof("nibble:") - 1)) {
+                       if (ext == NULL)
+                               goto skip;
+                       cp += sizeof("nibble:") - 1;
+                       i = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix) - 1);
+                       strncpy(ext->nsuffix, cp, (size_t)i);
+                       ext->nsuffix[i] = '\0';
+               }
+               else if (!strncmp(cp, "nibble2:", sizeof("nibble2:") - 1)) {
+                       if (ext == NULL)
+                               goto skip;
+                       cp += sizeof("nibble2:") - 1;
+                       i = MIN(strcspn(cp, " \t"), sizeof(ext->nsuffix2) - 1);
+                       strncpy(ext->nsuffix2, cp, (size_t)i);
+                       ext->nsuffix2[i] = '\0';
+               }
+               else if (!strncmp(cp, "v6revmode:", sizeof("v6revmode:") - 1)) {
+                       cp += sizeof("v6revmode:") - 1;
+                       /* "nibble" and "bitstring" used to be valid */
+                       if (!strncmp(cp, "single", sizeof("single") - 1)) {
+                               statp->options |= RES_NO_NIBBLE2;
+                       } else if (!strncmp(cp, "both", sizeof("both") - 1)) {
+                               statp->options &=
+                                        ~RES_NO_NIBBLE2;
+                       }
+               }
+               else {
+                       /* XXX - print a warning here? */
+               }
+   skip:
+               /* skip to next run of spaces */
+               while (*cp && *cp != ' ' && *cp != '\t')
+                       cp++;
+       }
+}
+
+#ifdef RESOLVSORT
+/* XXX - should really support CIDR which means explicit masks always. */
+static u_int32_t
+net_mask(in)           /*!< XXX - should really use system's version of this  */
+       struct in_addr in;
+{
+       register u_int32_t i = ntohl(in.s_addr);
+
+       if (IN_CLASSA(i))
+               return (htonl(IN_CLASSA_NET));
+       else if (IN_CLASSB(i))
+               return (htonl(IN_CLASSB_NET));
+       return (htonl(IN_CLASSC_NET));
+}
+#endif
+
+static u_char srnd[16];
+
+void
+res_rndinit(res_state statp)
+{
+       struct timeval now;
+       u_int32_t u32;
+       u_int16_t u16;
+       u_char *rnd = statp->_rnd == NULL ? srnd : statp->_rnd;
+
+       gettimeofday(&now, NULL);
+       u32 = (u_int32_t)now.tv_sec;
+       memcpy(rnd, &u32, 4);
+       u32 = now.tv_usec;
+       memcpy(rnd + 4, &u32, 4);
+       u32 += (u_int32_t)now.tv_sec;
+       memcpy(rnd + 8, &u32, 4);
+       u16 = getpid();
+       memcpy(rnd + 12, &u16, 2);
+}
+
+u_int
+res_nrandomid(res_state statp) {
+       struct timeval now;
+       u_int16_t u16;
+       MD5_CTX ctx;
+       u_char *rnd = statp->_rnd == NULL ? srnd : statp->_rnd;
+
+       gettimeofday(&now, NULL);
+       u16 = (u_int16_t) (now.tv_sec ^ now.tv_usec);
+       memcpy(rnd + 14, &u16, 2);
+#ifndef HAVE_MD5
+       MD5_Init(&ctx);
+       MD5_Update(&ctx, rnd, 16);
+       MD5_Final(rnd, &ctx);
+#else
+       MD5Init(&ctx);
+       MD5Update(&ctx, rnd, 16);
+       MD5Final(rnd, &ctx);
+#endif
+       memcpy(&u16, rnd + 14, 2);
+       return ((u_int) u16);
+}
+
+/*%
+ * This routine is for closing the socket if a virtual circuit is used and
+ * the program wants to close it.  This provides support for endhostent()
+ * which expects to close the socket.
+ *
+ * This routine is not expected to be user visible.
+ */
+void
+res_nclose(res_state statp) {
+       int ns;
+
+       if (statp->_vcsock >= 0) { 
+               (void) close(statp->_vcsock);
+               statp->_vcsock = -1;
+               statp->_flags &= ~(RES_F_VC | RES_F_CONN);
+       }
+       for (ns = 0; ns < statp->_u._ext.nscount; ns++) {
+               if (statp->_u._ext.nssocks[ns] != -1) {
+                       (void) close(statp->_u._ext.nssocks[ns]);
+                       statp->_u._ext.nssocks[ns] = -1;
+               }
+       }
+}
+
+void
+res_ndestroy(res_state statp) {
+       res_nclose(statp);
+       if (statp->_u._ext.ext != NULL) {
+               if (statp->_u._ext.ext->kq != -1)
+                       (void)close(statp->_u._ext.ext->kq);
+               if (statp->_u._ext.ext->resfd != -1)
+                       (void)close(statp->_u._ext.ext->resfd);
+               free(statp->_u._ext.ext);
+               statp->_u._ext.ext = NULL;
+       }
+       if (statp->_rnd != NULL) {
+               free(statp->_rnd);
+               statp->_rnd = NULL;
+       }
+       statp->options &= ~RES_INIT;
+}
+
+const char *
+res_get_nibblesuffix(res_state statp) {
+       if (statp->_u._ext.ext)
+               return (statp->_u._ext.ext->nsuffix);
+       return ("ip6.arpa");
+}
+
+const char *
+res_get_nibblesuffix2(res_state statp) {
+       if (statp->_u._ext.ext)
+               return (statp->_u._ext.ext->nsuffix2);
+       return ("ip6.int");
+}
+
+void
+res_setservers(res_state statp, const union res_sockaddr_union *set, int cnt) {
+       int i, nserv;
+       size_t size;
+
+       /* close open servers */
+       res_nclose(statp);
+
+       /* cause rtt times to be forgotten */
+       statp->_u._ext.nscount = 0;
+
+       nserv = 0;
+       for (i = 0; i < cnt && nserv < MAXNS; i++) {
+               switch (set->sin.sin_family) {
+               case AF_INET:
+                       size = sizeof(set->sin);
+                       if (statp->_u._ext.ext)
+                               memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
+                                       &set->sin, size);
+                       if (size <= sizeof(statp->nsaddr_list[nserv]))
+                               memcpy(&statp->nsaddr_list[nserv],
+                                       &set->sin, size);
+                       else
+                               statp->nsaddr_list[nserv].sin_family = 0;
+                       nserv++;
+                       break;
+
+#ifdef HAS_INET6_STRUCTS
+               case AF_INET6:
+                       size = sizeof(set->sin6);
+                       if (statp->_u._ext.ext)
+                               memcpy(&statp->_u._ext.ext->nsaddrs[nserv],
+                                       &set->sin6, size);
+                       if (size <= sizeof(statp->nsaddr_list[nserv]))
+                               memcpy(&statp->nsaddr_list[nserv],
+                                       &set->sin6, size);
+                       else
+                               statp->nsaddr_list[nserv].sin_family = 0;
+                       nserv++;
+                       break;
+#endif
+
+               default:
+                       break;
+               }
+               set++;
+       }
+       statp->nscount = nserv;
+       
+}
+
+int
+res_getservers(res_state statp, union res_sockaddr_union *set, int cnt) {
+       int i;
+       size_t size;
+       u_int16_t family;
+
+       for (i = 0; i < statp->nscount && i < cnt; i++) {
+               if (statp->_u._ext.ext)
+                       family = statp->_u._ext.ext->nsaddrs[i].sin.sin_family;
+               else 
+                       family = statp->nsaddr_list[i].sin_family;
+
+               switch (family) {
+               case AF_INET:
+                       size = sizeof(set->sin);
+                       if (statp->_u._ext.ext)
+                               memcpy(&set->sin,
+                                      &statp->_u._ext.ext->nsaddrs[i],
+                                      size);
+                       else
+                               memcpy(&set->sin, &statp->nsaddr_list[i],
+                                      size);
+                       break;
+
+#ifdef HAS_INET6_STRUCTS
+               case AF_INET6:
+                       size = sizeof(set->sin6);
+                       if (statp->_u._ext.ext)
+                               memcpy(&set->sin6,
+                                      &statp->_u._ext.ext->nsaddrs[i],
+                                      size);
+                       else
+                               memcpy(&set->sin6, &statp->nsaddr_list[i],
+                                      size);
+                       break;
+#endif
+
+               default:
+                       set->sin.sin_family = 0;
+                       break;
+               }
+               set++;
+       }
+       return (statp->nscount);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/resolv/res_mkquery.c b/lib/nbsd_libc/resolv/res_mkquery.c
new file mode 100644 (file)
index 0000000..43b9513
--- /dev/null
@@ -0,0 +1,322 @@
+/*     $NetBSD: res_mkquery.c,v 1.12 2009/04/12 19:43:37 christos Exp $        */
+
+/*
+ * Portions Copyright (C) 2004, 2005, 2008  Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (C) 1996, 1997, 1988, 1999, 2001, 2003  Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and/or 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 ISC DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/*
+ * Copyright (c) 1985, 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+/*
+ * Portions Copyright (c) 1993 by Digital Equipment Corporation.
+ *
+ * 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, and that
+ * the name of Digital Equipment Corporation not be used in advertising or
+ * publicity pertaining to distribution of the document or software without
+ * specific, written prior permission.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
+ * CORPORATION 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#ifdef notdef
+static const char sccsid[] = "@(#)res_mkquery.c        8.1 (Berkeley) 6/4/93";
+static const char rcsid[] = "Id: res_mkquery.c,v 1.10 2008/12/11 09:59:00 marka Exp";
+#else
+__RCSID("$NetBSD: res_mkquery.c,v 1.12 2009/04/12 19:43:37 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+#include <netdb.h>
+#include <resolv.h>
+#include <stdio.h>
+#include <string.h>
+#include "port_after.h"
+
+#if 0
+#ifdef __weak_alias
+__weak_alias(res_nmkquery,_res_nmkquery)
+__weak_alias(res_nopt,_res_nopt)
+#endif
+#endif
+
+/* Options.  Leave them on. */
+#ifndef DEBUG
+#define DEBUG
+#endif
+
+extern const char *_res_opcodes[];
+
+/*%
+ * Form all types of queries.
+ * Returns the size of the result or -1.
+ */
+int
+res_nmkquery(res_state statp,
+            int op,                    /*!< opcode of query  */
+            const char *dname,         /*!< domain name  */
+            int class, int type,       /*!< class and type of query  */
+            const u_char *data,        /*!< resource record data  */
+            int datalen,               /*!< length of data  */
+            const u_char *newrr_in,    /*!< new rr for modify or append  */
+            u_char *buf,               /*!< buffer to put query  */
+            int buflen)                /*!< size of buffer  */
+{
+       register HEADER *hp;
+       register u_char *cp, *ep;
+       register int n;
+       u_char *dnptrs[20], **dpp, **lastdnptr;
+
+       UNUSED(newrr_in);
+
+#ifdef DEBUG
+       if (statp->options & RES_DEBUG)
+               printf(";; res_nmkquery(%s, %s, %s, %s)\n",
+                      _res_opcodes[op], dname, p_class(class), p_type(type));
+#endif
+       /*
+        * Initialize header fields.
+        */
+       if ((buf == NULL) || (buflen < HFIXEDSZ))
+               return (-1);
+       memset(buf, 0, HFIXEDSZ);
+       hp = (HEADER *)(void *)buf;
+       statp->id = res_nrandomid(statp);
+       hp->id = htons(statp->id);
+       hp->opcode = op;
+       hp->rd = (statp->options & RES_RECURSE) != 0U;
+       hp->rcode = NOERROR;
+       cp = buf + HFIXEDSZ;
+       ep = buf + buflen;
+       dpp = dnptrs;
+       *dpp++ = buf;
+       *dpp++ = NULL;
+       lastdnptr = dnptrs + sizeof dnptrs / sizeof dnptrs[0];
+       /*
+        * perform opcode specific processing
+        */
+       switch (op) {
+       case QUERY:     /*FALLTHROUGH*/
+       case NS_NOTIFY_OP:
+               if (ep - cp < QFIXEDSZ)
+                       return (-1);
+               if ((n = dn_comp(dname, cp, ep - cp - QFIXEDSZ, dnptrs,
+                   lastdnptr)) < 0)
+                       return (-1);
+               cp += n;
+               ns_put16(type, cp);
+               cp += INT16SZ;
+               ns_put16(class, cp);
+               cp += INT16SZ;
+               hp->qdcount = htons(1);
+               if (op == QUERY || data == NULL)
+                       break;
+               /*
+                * Make an additional record for completion domain.
+                */
+               if ((ep - cp) < RRFIXEDSZ)
+                       return (-1);
+               n = dn_comp((const char *)data, cp, ep - cp - RRFIXEDSZ,
+                           dnptrs, lastdnptr);
+               if (n < 0)
+                       return (-1);
+               cp += n;
+               ns_put16(T_NULL, cp);
+               cp += INT16SZ;
+               ns_put16(class, cp);
+               cp += INT16SZ;
+               ns_put32(0, cp);
+               cp += INT32SZ;
+               ns_put16(0, cp);
+               cp += INT16SZ;
+               hp->arcount = htons(1);
+               break;
+
+       case IQUERY:
+               /*
+                * Initialize answer section
+                */
+               if (ep - cp < 1 + RRFIXEDSZ + datalen)
+                       return (-1);
+               *cp++ = '\0';   /*%< no domain name */
+               ns_put16(type, cp);
+               cp += INT16SZ;
+               ns_put16(class, cp);
+               cp += INT16SZ;
+               ns_put32(0, cp);
+               cp += INT32SZ;
+               ns_put16(datalen, cp);
+               cp += INT16SZ;
+               if (datalen) {
+                       memcpy(cp, data, (size_t)datalen);
+                       cp += datalen;
+               }
+               hp->ancount = htons(1);
+               break;
+
+       default:
+               return (-1);
+       }
+       return (cp - buf);
+}
+
+#ifdef RES_USE_EDNS0
+/* attach OPT pseudo-RR, as documented in RFC2671 (EDNS0). */
+
+int
+res_nopt(res_state statp,
+        int n0,                /*%< current offset in buffer */
+        u_char *buf,           /*%< buffer to put query */
+        int buflen,            /*%< size of buffer */
+        int anslen)            /*%< UDP answer buffer size */
+{
+       register HEADER *hp;
+       register u_char *cp, *ep;
+       u_int16_t flags = 0;
+
+#ifdef DEBUG
+       if ((statp->options & RES_DEBUG) != 0U)
+               printf(";; res_nopt()\n");
+#endif
+
+       hp = (HEADER *)(void *)buf;
+       cp = buf + n0;
+       ep = buf + buflen;
+
+       if ((ep - cp) < 1 + RRFIXEDSZ)
+               return (-1);
+
+       *cp++ = 0;                              /*%< "." */
+       ns_put16(ns_t_opt, cp);                 /*%< TYPE */
+       cp += INT16SZ;
+       ns_put16(anslen & 0xffff, cp);          /*%< CLASS = UDP payload size */
+       cp += INT16SZ;
+       *cp++ = NOERROR;                        /*%< extended RCODE */
+       *cp++ = 0;                              /*%< EDNS version */
+
+       if (statp->options & RES_USE_DNSSEC) {
+#ifdef DEBUG
+               if (statp->options & RES_DEBUG)
+                       printf(";; res_opt()... ENDS0 DNSSEC\n");
+#endif
+               flags |= NS_OPT_DNSSEC_OK;
+       }
+       ns_put16(flags, cp);
+       cp += INT16SZ;
+
+       ns_put16(0U, cp);                       /*%< RDLEN */
+       cp += INT16SZ;
+
+       hp->arcount = htons(ntohs(hp->arcount) + 1);
+
+       return (cp - buf);
+}
+
+/*
+ * Construct variable data (RDATA) block for OPT psuedo-RR, append it
+ * to the buffer, then update the RDLEN field (previously set to zero by
+ * res_nopt()) with the new RDATA length.
+ */
+int
+res_nopt_rdata(res_state statp,
+         int n0,               /*%< current offset in buffer */
+         u_char *buf,          /*%< buffer to put query */
+         int buflen,           /*%< size of buffer */
+         u_char *rdata,        /*%< ptr to start of opt rdata */
+         u_short code,         /*%< OPTION-CODE */
+         u_short len,          /*%< OPTION-LENGTH */
+         u_char *data)         /*%< OPTION_DATA */
+{
+       register u_char *cp, *ep;
+
+#ifdef DEBUG
+       if ((statp->options & RES_DEBUG) != 0U)
+               printf(";; res_nopt_rdata()\n");
+#endif
+
+       cp = buf + n0;
+       ep = buf + buflen;
+
+       if ((ep - cp) < (4 + len))
+               return (-1);
+
+       if (rdata < (buf + 2) || rdata >= ep)
+               return (-1);
+
+       ns_put16(code, cp);
+       cp += INT16SZ;
+
+       ns_put16(len, cp);
+       cp += INT16SZ;
+
+       memcpy(cp, data, (size_t)len);
+       cp += len;
+
+       len = cp - rdata;
+       ns_put16(len, rdata - 2);       /* Update RDLEN field */
+
+       return (cp - buf);
+}
+#endif
+
+/*! \file */
diff --git a/lib/nbsd_libc/resolv/res_private.h b/lib/nbsd_libc/resolv/res_private.h
new file mode 100644 (file)
index 0000000..6f78bc0
--- /dev/null
@@ -0,0 +1,26 @@
+/*     $NetBSD: res_private.h,v 1.3 2009/10/24 17:24:01 christos Exp $ */
+
+#ifndef res_private_h
+#define res_private_h
+
+struct __res_state_ext {
+       union res_sockaddr_union nsaddrs[MAXNS];
+       struct sort_list {
+               int     af;
+               union {
+                       struct in_addr  ina;
+                       struct in6_addr in6a;
+               } addr, mask;
+       } sort_list[MAXRESOLVSORT];
+       char nsuffix[64];
+       char nsuffix2[64];
+       struct timespec res_conf_time;
+       int kq, resfd;
+};
+
+extern int res_ourserver_p(const res_state, const struct sockaddr *);
+extern int __res_vinit(res_state, int);
+
+#endif
+
+/*! \file */
diff --git a/lib/nbsd_libc/resolv/res_query.c b/lib/nbsd_libc/resolv/res_query.c
new file mode 100644 (file)
index 0000000..c264efb
--- /dev/null
@@ -0,0 +1,483 @@
+/*     $NetBSD: res_query.c,v 1.13 2009/10/24 21:37:57 christos Exp $  */
+
+/*
+ * Portions Copyright (C) 2004, 2005, 2008  Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (C) 1996-2001, 2003  Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and/or 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 ISC DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+/*
+ * Portions Copyright (c) 1993 by Digital Equipment Corporation.
+ *
+ * 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, and that
+ * the name of Digital Equipment Corporation not be used in advertising or
+ * publicity pertaining to distribution of the document or software without
+ * specific, written prior permission.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
+ * CORPORATION 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.
+ */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#ifdef notdef
+static const char sccsid[] = "@(#)res_query.c  8.1 (Berkeley) 6/4/93";
+static const char rcsid[] = "Id: res_query.c,v 1.11 2008/11/14 02:36:51 marka Exp";
+#else
+__RCSID("$NetBSD: res_query.c,v 1.13 2009/10/24 21:37:57 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+#include <ctype.h>
+#include <errno.h>
+#include <netdb.h>
+#include <resolv.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include "port_after.h"
+
+#if 0
+#ifdef __weak_alias
+__weak_alias(res_nquery,_res_nquery)
+__weak_alias(res_nsearch,_res_nsearch)
+__weak_alias(res_nquerydomain,__res_nquerydomain)
+__weak_alias(res_hostalias,__res_hostalias)
+#endif
+#endif
+
+/* Options.  Leave them on. */
+#ifndef DEBUG
+#define DEBUG
+#endif
+
+#if PACKETSZ > 1024
+#define MAXPACKET      PACKETSZ
+#else
+#define MAXPACKET      1024
+#endif
+
+/*%
+ * Formulate a normal query, send, and await answer.
+ * Returned answer is placed in supplied buffer "answer".
+ * Perform preliminary check of answer, returning success only
+ * if no error is indicated and the answer count is nonzero.
+ * Return the size of the response on success, -1 on error.
+ * Error number is left in H_ERRNO.
+ *
+ * Caller must parse answer and determine whether it answers the question.
+ */
+int
+res_nquery(res_state statp,
+          const char *name,    /*%< domain name */
+          int class, int type, /*%< class and type of query */
+          u_char *answer,      /*%< buffer to put answer */
+          int anslen)          /*%< size of answer buffer */
+{
+       u_char buf[MAXPACKET];
+       HEADER *hp = (HEADER *)(void *)answer;
+       u_int oflags;
+       u_char *rdata;
+       int n;
+
+       oflags = statp->_flags;
+
+again:
+       hp->rcode = NOERROR;    /*%< default */
+#ifdef DEBUG
+       if (statp->options & RES_DEBUG)
+               printf(";; res_query(%s, %d, %d)\n", name, class, type);
+#endif
+
+       n = res_nmkquery(statp, QUERY, name, class, type, NULL, 0, NULL,
+                        buf, sizeof(buf));
+#ifdef RES_USE_EDNS0
+       if (n > 0 && (statp->_flags & RES_F_EDNS0ERR) == 0 &&
+           (statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC|RES_NSID)) != 0U) {
+               n = res_nopt(statp, n, buf, sizeof(buf), anslen);
+               rdata = &buf[n];
+               if (n > 0 && (statp->options & RES_NSID) != 0U) {
+                       n = res_nopt_rdata(statp, n, buf, sizeof(buf), rdata,
+                                          NS_OPT_NSID, 0, NULL);
+               }
+       }
+#endif
+       if (n <= 0) {
+#ifdef DEBUG
+               if (statp->options & RES_DEBUG)
+                       printf(";; res_query: mkquery failed\n");
+#endif
+               RES_SET_H_ERRNO(statp, NO_RECOVERY);
+               return (n);
+       }
+
+       n = res_nsend(statp, buf, n, answer, anslen);
+       if (n < 0) {
+#ifdef RES_USE_EDNS0
+               /* if the query choked with EDNS0, retry without EDNS0 */
+               if ((statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U &&
+                   ((oflags ^ statp->_flags) & RES_F_EDNS0ERR) != 0) {
+                       statp->_flags |= RES_F_EDNS0ERR;
+                       if (statp->options & RES_DEBUG)
+                               printf(";; res_nquery: retry without EDNS0\n");
+                       goto again;
+               }
+#endif
+#ifdef DEBUG
+               if (statp->options & RES_DEBUG)
+                       printf(";; res_query: send error\n");
+#endif
+               RES_SET_H_ERRNO(statp, TRY_AGAIN);
+               return (n);
+       }
+
+       if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
+#ifdef DEBUG
+               if (statp->options & RES_DEBUG)
+                       printf(";; rcode = (%s), counts = an:%d ns:%d ar:%d\n",
+                              p_rcode(hp->rcode),
+                              ntohs(hp->ancount),
+                              ntohs(hp->nscount),
+                              ntohs(hp->arcount));
+#endif
+               switch (hp->rcode) {
+               case NXDOMAIN:
+                       RES_SET_H_ERRNO(statp, HOST_NOT_FOUND);
+                       break;
+               case SERVFAIL:
+                       RES_SET_H_ERRNO(statp, TRY_AGAIN);
+                       break;
+               case NOERROR:
+                       RES_SET_H_ERRNO(statp, NO_DATA);
+                       break;
+               case FORMERR:
+               case NOTIMP:
+               case REFUSED:
+               default:
+                       RES_SET_H_ERRNO(statp, NO_RECOVERY);
+                       break;
+               }
+               return (-1);
+       }
+       return (n);
+}
+
+/*%
+ * Formulate a normal query, send, and retrieve answer in supplied buffer.
+ * Return the size of the response on success, -1 on error.
+ * If enabled, implement search rules until answer or unrecoverable failure
+ * is detected.  Error code, if any, is left in H_ERRNO.
+ */
+int
+res_nsearch(res_state statp,
+           const char *name,   /*%< domain name */
+           int class, int type,        /*%< class and type of query */
+           u_char *answer,     /*%< buffer to put answer */
+           int anslen)         /*%< size of answer */
+{
+       const char *cp, * const *domain;
+       HEADER *hp = (HEADER *)(void *)answer;
+       char tmp[NS_MAXDNAME];
+       u_int dots;
+       int trailing_dot, ret, saved_herrno;
+       int got_nodata = 0, got_servfail = 0, root_on_list = 0;
+       int tried_as_is = 0;
+       int searched = 0;
+
+       errno = 0;
+       RES_SET_H_ERRNO(statp, HOST_NOT_FOUND);  /*%< True if we never query. */
+       dots = 0;
+       for (cp = name; *cp != '\0'; cp++)
+               dots += (*cp == '.');
+       trailing_dot = 0;
+       if (cp > name && *--cp == '.')
+               trailing_dot++;
+
+       /* If there aren't any dots, it could be a user-level alias. */
+       if (!dots && (cp = res_hostalias(statp, name, tmp, sizeof tmp))!= NULL)
+               return (res_nquery(statp, cp, class, type, answer, anslen));
+
+       /*
+        * If there are enough dots in the name, let's just give it a
+        * try 'as is'. The threshold can be set with the "ndots" option.
+        * Also, query 'as is', if there is a trailing dot in the name.
+        */
+       saved_herrno = -1;
+       if (dots >= statp->ndots || trailing_dot) {
+               ret = res_nquerydomain(statp, name, NULL, class, type,
+                                        answer, anslen);
+               if (ret > 0 || trailing_dot)
+                       return (ret);
+               saved_herrno = statp->res_h_errno;
+               tried_as_is++;
+       }
+
+       /*
+        * We do at least one level of search if
+        *      - there is no dot and RES_DEFNAME is set, or
+        *      - there is at least one dot, there is no trailing dot,
+        *        and RES_DNSRCH is set.
+        */
+       if ((!dots && (statp->options & RES_DEFNAMES) != 0U) ||
+           (dots && !trailing_dot && (statp->options & RES_DNSRCH) != 0U)) {
+               int done = 0;
+
+               for (domain = (const char * const *)statp->dnsrch;
+                    *domain && !done;
+                    domain++) {
+                       searched = 1;
+
+                       if (domain[0][0] == '\0' ||
+                           (domain[0][0] == '.' && domain[0][1] == '\0'))
+                               root_on_list++;
+
+                       ret = res_nquerydomain(statp, name, *domain,
+                                              class, type,
+                                              answer, anslen);
+                       if (ret > 0)
+                               return (ret);
+
+                       /*
+                        * If no server present, give up.
+                        * If name isn't found in this domain,
+                        * keep trying higher domains in the search list
+                        * (if that's enabled).
+                        * On a NO_DATA error, keep trying, otherwise
+                        * a wildcard entry of another type could keep us
+                        * from finding this entry higher in the domain.
+                        * If we get some other error (negative answer or
+                        * server failure), then stop searching up,
+                        * but try the input name below in case it's
+                        * fully-qualified.
+                        */
+                       if (errno == ECONNREFUSED) {
+                               RES_SET_H_ERRNO(statp, TRY_AGAIN);
+                               return (-1);
+                       }
+
+                       switch (statp->res_h_errno) {
+                       case NO_DATA:
+                               got_nodata++;
+                               /* FALLTHROUGH */
+                       case HOST_NOT_FOUND:
+                               /* keep trying */
+                               break;
+                       case TRY_AGAIN:
+                               if (hp->rcode == SERVFAIL) {
+                                       /* try next search element, if any */
+                                       got_servfail++;
+                                       break;
+                               }
+                               /* FALLTHROUGH */
+                       default:
+                               /* anything else implies that we're done */
+                               done++;
+                       }
+
+                       /* if we got here for some reason other than DNSRCH,
+                        * we only wanted one iteration of the loop, so stop.
+                        */
+                       if ((statp->options & RES_DNSRCH) == 0U)
+                               done++;
+               }
+       }
+
+       /*
+        * If the query has not already been tried as is then try it
+        * unless RES_NOTLDQUERY is set and there were no dots.
+        */
+       if ((dots || !searched || (statp->options & RES_NOTLDQUERY) == 0U) &&
+           !(tried_as_is || root_on_list)) {
+               ret = res_nquerydomain(statp, name, NULL, class, type,
+                                      answer, anslen);
+               if (ret > 0)
+                       return (ret);
+       }
+
+       /* if we got here, we didn't satisfy the search.
+        * if we did an initial full query, return that query's H_ERRNO
+        * (note that we wouldn't be here if that query had succeeded).
+        * else if we ever got a nodata, send that back as the reason.
+        * else send back meaningless H_ERRNO, that being the one from
+        * the last DNSRCH we did.
+        */
+       if (saved_herrno != -1)
+               RES_SET_H_ERRNO(statp, saved_herrno);
+       else if (got_nodata)
+               RES_SET_H_ERRNO(statp, NO_DATA);
+       else if (got_servfail)
+               RES_SET_H_ERRNO(statp, TRY_AGAIN);
+       return (-1);
+}
+
+/*%
+ * Perform a call on res_query on the concatenation of name and domain,
+ * removing a trailing dot from name if domain is NULL.
+ */
+int
+res_nquerydomain(res_state statp,
+           const char *name,
+           const char *domain,
+           int class, int type,        /*%< class and type of query */
+           u_char *answer,             /*%< buffer to put answer */
+           int anslen)         /*%< size of answer */
+{
+       char nbuf[MAXDNAME];
+       const char *longname = nbuf;
+       int n, d;
+
+#ifdef DEBUG
+       if (statp->options & RES_DEBUG)
+               printf(";; res_nquerydomain(%s, %s, %d, %d)\n",
+                      name, domain?domain:"<Nil>", class, type);
+#endif
+       if (domain == NULL) {
+               /*
+                * Check for trailing '.';
+                * copy without '.' if present.
+                */
+               n = strlen(name);
+               if (n >= MAXDNAME) {
+                       RES_SET_H_ERRNO(statp, NO_RECOVERY);
+                       return (-1);
+               }
+               n--;
+               if (n >= 0 && name[n] == '.') {
+                       strncpy(nbuf, name, (size_t)n);
+                       nbuf[n] = '\0';
+               } else
+                       longname = name;
+       } else {
+               n = strlen(name);
+               d = strlen(domain);
+               if (n + d + 1 >= MAXDNAME) {
+                       RES_SET_H_ERRNO(statp, NO_RECOVERY);
+                       return (-1);
+               }
+               sprintf(nbuf, "%s.%s", name, domain);
+       }
+       return (res_nquery(statp, longname, class, type, answer, anslen));
+}
+
+const char *
+res_hostalias(const res_state statp, const char *name, char *dst, size_t siz) {
+       char *file, *cp1, *cp2;
+       char buf[BUFSIZ];
+       FILE *fp;
+
+       if (statp->options & RES_NOALIASES)
+               return (NULL);
+       /*
+        * forbid hostaliases for setuid binary, due to possible security
+        * breach.
+        */
+       if (issetugid())
+               return (NULL);
+       file = getenv("HOSTALIASES");
+       if (file == NULL || (fp = fopen(file, "r")) == NULL)
+               return (NULL);
+       buf[sizeof(buf) - 1] = '\0';
+       while (fgets(buf, sizeof(buf), fp)) {
+               for (cp1 = buf; *cp1 && !isspace((unsigned char)*cp1); ++cp1)
+                       ;
+               if (!*cp1)
+                       break;
+               *cp1 = '\0';
+               if (ns_samename(buf, name) == 1) {
+                       while (isspace((unsigned char)*++cp1))
+                               ;
+                       if (!*cp1)
+                               break;
+                       for (cp2 = cp1 + 1; *cp2 &&
+                            !isspace((unsigned char)*cp2); ++cp2)
+                               ;
+                       *cp2 = '\0';
+                       strncpy(dst, cp1, siz - 1);
+                       dst[siz - 1] = '\0';
+                       fclose(fp);
+                       return (dst);
+               }
+       }
+       fclose(fp);
+       return (NULL);
+}
+
+/*! \file */
diff --git a/lib/nbsd_libc/resolv/res_send.c b/lib/nbsd_libc/resolv/res_send.c
new file mode 100644 (file)
index 0000000..7023297
--- /dev/null
@@ -0,0 +1,1147 @@
+/*     $NetBSD: res_send.c,v 1.20 2009/10/24 17:24:01 christos Exp $   */
+
+/*
+ * Portions Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (C) 1996-2003  Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and/or 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 ISC DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/*
+ * Copyright (c) 1985, 1989, 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+/*
+ * Portions Copyright (c) 1993 by Digital Equipment Corporation.
+ *
+ * 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, and that
+ * the name of Digital Equipment Corporation not be used in advertising or
+ * publicity pertaining to distribution of the document or software without
+ * specific, written prior permission.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
+ * CORPORATION 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.
+ */
+
+/*
+ * Copyright (c) 2005 by Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#ifdef notdef
+static const char sccsid[] = "@(#)res_send.c   8.1 (Berkeley) 6/4/93";
+static const char rcsid[] = "Id: res_send.c,v 1.22 2009/01/22 23:49:23 tbox Exp";
+#else
+__RCSID("$NetBSD: res_send.c,v 1.20 2009/10/24 17:24:01 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*! \file
+ * \brief
+ * Send query to name server and wait for reply.
+ */
+
+#include "namespace.h"
+#include "port_before.h"
+#include "fd_setsize.h"
+
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <sys/socket.h>
+#include <sys/uio.h>
+
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+#include <arpa/inet.h>
+
+#include <errno.h>
+#include <netdb.h>
+#include <resolv.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <isc/eventlib.h>
+
+#include "port_after.h"
+
+#if 0
+#ifdef __weak_alias
+__weak_alias(res_ourserver_p,__res_ourserver_p)
+__weak_alias(res_nameinquery,__res_nameinquery)
+__weak_alias(res_queriesmatch,__res_queriesmatch)
+__weak_alias(res_nsend,__res_nsend)
+#endif
+#endif
+
+
+#ifdef USE_POLL
+#ifdef HAVE_STROPTS_H
+#include <stropts.h>
+#endif
+#include <poll.h>
+#endif /* USE_POLL */
+
+/* Options.  Leave them on. */
+#ifndef DEBUG
+#define DEBUG
+#endif
+#include "res_debug.h"
+#include "res_private.h"
+
+#define EXT(res) ((res)->_u._ext)
+
+#ifndef USE_POLL
+static const int highestFD = FD_SETSIZE - 1;
+#else
+static int highestFD = 0;
+#endif
+
+/* Forward. */
+
+static int             get_salen __P((const struct sockaddr *));
+static struct sockaddr * get_nsaddr __P((res_state, size_t));
+static int             send_vc(res_state, const u_char *, int,
+                               u_char *, int, int *, int);
+static int             send_dg(res_state, const u_char *, int,
+                               u_char *, int, int *, int, int,
+                               int *, int *);
+static void            Aerror(const res_state, FILE *, const char *, int,
+                              const struct sockaddr *, int);
+static void            Perror(const res_state, FILE *, const char *, int);
+static int             sock_eq(struct sockaddr *, struct sockaddr *);
+#if defined(NEED_PSELECT) && !defined(USE_POLL)
+static int             pselect(int, void *, void *, void *,
+                               struct timespec *,
+                               const sigset_t *);
+#endif
+void res_pquery(const res_state, const u_char *, int, FILE *);
+
+static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
+
+/* Public. */
+
+/*%
+ *     looks up "ina" in _res.ns_addr_list[]
+ *
+ * returns:
+ *\li  0  : not found
+ *\li  >0 : found
+ *
+ * author:
+ *\li  paul vixie, 29may94
+ */
+int
+res_ourserver_p(const res_state statp, const struct sockaddr *sa) {
+       const struct sockaddr_in *inp, *srv;
+       const struct sockaddr_in6 *in6p, *srv6;
+       int ns;
+
+       switch (sa->sa_family) {
+       case AF_INET:
+               inp = (const struct sockaddr_in *)(const void *)sa;
+               for (ns = 0;  ns < statp->nscount;  ns++) {
+                       srv = (struct sockaddr_in *)(void *)get_nsaddr(statp, (size_t)ns);
+                       if (srv->sin_family == inp->sin_family &&
+                           srv->sin_port == inp->sin_port &&
+                           (srv->sin_addr.s_addr == INADDR_ANY ||
+                            srv->sin_addr.s_addr == inp->sin_addr.s_addr))
+                               return (1);
+               }
+               break;
+       case AF_INET6:
+               if (EXT(statp).ext == NULL)
+                       break;
+               in6p = (const struct sockaddr_in6 *)(const void *)sa;
+               for (ns = 0;  ns < statp->nscount;  ns++) {
+                       srv6 = (struct sockaddr_in6 *)(void *)get_nsaddr(statp, (size_t)ns);
+                       if (srv6->sin6_family == in6p->sin6_family &&
+                           srv6->sin6_port == in6p->sin6_port &&
+#ifdef HAVE_SIN6_SCOPE_ID
+                           (srv6->sin6_scope_id == 0 ||
+                            srv6->sin6_scope_id == in6p->sin6_scope_id) &&
+#endif
+                           (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
+                            IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
+                               return (1);
+               }
+               break;
+       default:
+               break;
+       }
+       return (0);
+}
+
+/*%
+ *     look for (name,type,class) in the query section of packet (buf,eom)
+ *
+ * requires:
+ *\li  buf + HFIXEDSZ <= eom
+ *
+ * returns:
+ *\li  -1 : format error
+ *\li  0  : not found
+ *\li  >0 : found
+ *
+ * author:
+ *\li  paul vixie, 29may94
+ */
+int
+res_nameinquery(const char *name, int type, int class,
+               const u_char *buf, const u_char *eom)
+{
+       const u_char *cp = buf + HFIXEDSZ;
+       int qdcount = ntohs(((const HEADER*)(const void *)buf)->qdcount);
+
+       while (qdcount-- > 0) {
+               char tname[MAXDNAME+1];
+               int n, ttype, tclass;
+
+               n = dn_expand(buf, eom, cp, tname, sizeof tname);
+               if (n < 0)
+                       return (-1);
+               cp += n;
+               if (cp + 2 * INT16SZ > eom)
+                       return (-1);
+               ttype = ns_get16(cp); cp += INT16SZ;
+               tclass = ns_get16(cp); cp += INT16SZ;
+               if (ttype == type && tclass == class &&
+                   ns_samename(tname, name) == 1)
+                       return (1);
+       }
+       return (0);
+}
+
+/*%
+ *     is there a 1:1 mapping of (name,type,class)
+ *     in (buf1,eom1) and (buf2,eom2)?
+ *
+ * returns:
+ *\li  -1 : format error
+ *\li  0  : not a 1:1 mapping
+ *\li  >0 : is a 1:1 mapping
+ *
+ * author:
+ *\li  paul vixie, 29may94
+ */
+int
+res_queriesmatch(const u_char *buf1, const u_char *eom1,
+                const u_char *buf2, const u_char *eom2)
+{
+       const u_char *cp = buf1 + HFIXEDSZ;
+       int qdcount = ntohs(((const HEADER*)(const void *)buf1)->qdcount);
+
+       if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
+               return (-1);
+
+       /*
+        * Only header section present in replies to
+        * dynamic update packets.
+        */
+       if ((((const HEADER *)(const void *)buf1)->opcode == ns_o_update) &&
+           (((const HEADER *)(const void *)buf2)->opcode == ns_o_update))
+               return (1);
+
+       if (qdcount != ntohs(((const HEADER*)(const void *)buf2)->qdcount))
+               return (0);
+       while (qdcount-- > 0) {
+               char tname[MAXDNAME+1];
+               int n, ttype, tclass;
+
+               n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
+               if (n < 0)
+                       return (-1);
+               cp += n;
+               if (cp + 2 * INT16SZ > eom1)
+                       return (-1);
+               ttype = ns_get16(cp);   cp += INT16SZ;
+               tclass = ns_get16(cp); cp += INT16SZ;
+               if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
+                       return (0);
+       }
+       return (1);
+}
+
+int
+res_nsend(res_state statp,
+         const u_char *buf, int buflen, u_char *ans, int anssiz)
+{
+       int gotsomewhere, terrno, tries, v_circuit, resplen, ns, n;
+       char abuf[NI_MAXHOST];
+
+#ifdef USE_POLL
+       highestFD = sysconf(_SC_OPEN_MAX) - 1;
+#endif
+
+       (void)res_check(statp, NULL);
+
+       /* No name servers or res_init() failure */
+       if (statp->nscount == 0 || EXT(statp).ext == NULL) {
+               errno = ESRCH;
+               return (-1);
+       }
+       if (anssiz < HFIXEDSZ) {
+               errno = EINVAL;
+               return (-1);
+       }
+       DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
+               (stdout, ";; res_send()\n"), buf, buflen);
+       v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
+       gotsomewhere = 0;
+       terrno = ETIMEDOUT;
+
+       /*
+        * If the ns_addr_list in the resolver context has changed, then
+        * invalidate our cached copy and the associated timing data.
+        */
+       if (EXT(statp).nscount != 0) {
+               int needclose = 0;
+               struct sockaddr_storage peer;
+               ISC_SOCKLEN_T peerlen;
+
+               if (EXT(statp).nscount != statp->nscount)
+                       needclose++;
+               else
+                       for (ns = 0; ns < statp->nscount; ns++) {
+                               if (statp->nsaddr_list[ns].sin_family &&
+                                   !sock_eq((struct sockaddr *)(void *)&statp->nsaddr_list[ns],
+                                            (struct sockaddr *)(void *)&EXT(statp).ext->nsaddrs[ns])) {
+                                       needclose++;
+                                       break;
+                               }
+
+                               if (EXT(statp).nssocks[ns] == -1)
+                                       continue;
+                               peerlen = sizeof(peer);
+                               if (getpeername(EXT(statp).nssocks[ns],
+                                   (struct sockaddr *)(void *)&peer, &peerlen) < 0) {
+                                       needclose++;
+                                       break;
+                               }
+                               if (!sock_eq((struct sockaddr *)(void *)&peer,
+                                   get_nsaddr(statp, (size_t)ns))) {
+                                       needclose++;
+                                       break;
+                               }
+                       }
+               if (needclose) {
+                       res_nclose(statp);
+                       EXT(statp).nscount = 0;
+               }
+       }
+
+       /*
+        * Maybe initialize our private copy of the ns_addr_list.
+        */
+       if (EXT(statp).nscount == 0) {
+               for (ns = 0; ns < statp->nscount; ns++) {
+                       EXT(statp).nstimes[ns] = RES_MAXTIME;
+                       EXT(statp).nssocks[ns] = -1;
+                       if (!statp->nsaddr_list[ns].sin_family)
+                               continue;
+                       EXT(statp).ext->nsaddrs[ns].sin =
+                                statp->nsaddr_list[ns];
+               }
+               EXT(statp).nscount = statp->nscount;
+       }
+
+       /*
+        * Some resolvers want to even out the load on their nameservers.
+        * Note that RES_BLAST overrides RES_ROTATE.
+        */
+       if ((statp->options & RES_ROTATE) != 0U &&
+           (statp->options & RES_BLAST) == 0U) {
+               union res_sockaddr_union inu;
+               struct sockaddr_in ina;
+               int lastns = statp->nscount - 1;
+               int fd;
+               u_int16_t nstime;
+
+               if (EXT(statp).ext != NULL)
+                       inu = EXT(statp).ext->nsaddrs[0];
+               ina = statp->nsaddr_list[0];
+               fd = EXT(statp).nssocks[0];
+               nstime = EXT(statp).nstimes[0];
+               for (ns = 0; ns < lastns; ns++) {
+                       if (EXT(statp).ext != NULL)
+                               EXT(statp).ext->nsaddrs[ns] =
+                                       EXT(statp).ext->nsaddrs[ns + 1];
+                       statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
+                       EXT(statp).nssocks[ns] = EXT(statp).nssocks[ns + 1];
+                       EXT(statp).nstimes[ns] = EXT(statp).nstimes[ns + 1];
+               }
+               if (EXT(statp).ext != NULL)
+                       EXT(statp).ext->nsaddrs[lastns] = inu;
+               statp->nsaddr_list[lastns] = ina;
+               EXT(statp).nssocks[lastns] = fd;
+               EXT(statp).nstimes[lastns] = nstime;
+       }
+
+       /*
+        * Send request, RETRY times, or until successful.
+        */
+       for (tries = 0; tries < statp->retry; tries++) {
+           for (ns = 0; ns < statp->nscount; ns++) {
+               struct sockaddr *nsap;
+               int nsaplen;
+               nsap = get_nsaddr(statp, (size_t)ns);
+               nsaplen = get_salen(nsap);
+               statp->_flags &= ~RES_F_LASTMASK;
+               statp->_flags |= (ns << RES_F_LASTSHIFT);
+ same_ns:
+               if (statp->qhook) {
+                       int done = 0, loops = 0;
+
+                       do {
+                               res_sendhookact act;
+
+                               act = (*statp->qhook)(&nsap, &buf, &buflen,
+                                                     ans, anssiz, &resplen);
+                               switch (act) {
+                               case res_goahead:
+                                       done = 1;
+                                       break;
+                               case res_nextns:
+                                       res_nclose(statp);
+                                       goto next_ns;
+                               case res_done:
+                                       return (resplen);
+                               case res_modified:
+                                       /* give the hook another try */
+                                       if (++loops < 42) /*doug adams*/
+                                               break;
+                                       /*FALLTHROUGH*/
+                               case res_error:
+                                       /*FALLTHROUGH*/
+                               default:
+                                       goto fail;
+                               }
+                       } while (!done);
+               }
+
+               Dprint(((statp->options & RES_DEBUG) &&
+                       getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf),
+                                   NULL, 0, niflags) == 0),
+                      (stdout, ";; Querying server (# %d) address = %s\n",
+                       ns + 1, abuf));
+
+
+               if (v_circuit) {
+                       /* Use VC; at most one attempt per server. */
+                       tries = statp->retry;
+                       n = send_vc(statp, buf, buflen, ans, anssiz, &terrno,
+                                   ns);
+                       if (n < 0)
+                               goto fail;
+                       if (n == 0)
+                               goto next_ns;
+                       resplen = n;
+               } else {
+                       /* Use datagrams. */
+                       n = send_dg(statp, buf, buflen, ans, anssiz, &terrno,
+                                   ns, tries, &v_circuit, &gotsomewhere);
+                       if (n < 0)
+                               goto fail;
+                       if (n == 0)
+                               goto next_ns;
+                       if (v_circuit)
+                               goto same_ns;
+                       resplen = n;
+               }
+
+               Dprint((statp->options & RES_DEBUG) ||
+                      ((statp->pfcode & RES_PRF_REPLY) &&
+                       (statp->pfcode & RES_PRF_HEAD1)),
+                      (stdout, ";; got answer:\n"));
+
+               DprintQ((statp->options & RES_DEBUG) ||
+                       (statp->pfcode & RES_PRF_REPLY),
+                       (stdout, "%s", ""),
+                       ans, (resplen > anssiz) ? anssiz : resplen);
+
+               /*
+                * If we have temporarily opened a virtual circuit,
+                * or if we haven't been asked to keep a socket open,
+                * close the socket.
+                */
+               if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
+                   (statp->options & RES_STAYOPEN) == 0U) {
+                       res_nclose(statp);
+               }
+               if (statp->rhook) {
+                       int done = 0, loops = 0;
+
+                       do {
+                               res_sendhookact act;
+
+                               act = (*statp->rhook)(nsap, buf, buflen,
+                                                     ans, anssiz, &resplen);
+                               switch (act) {
+                               case res_goahead:
+                               case res_done:
+                                       done = 1;
+                                       break;
+                               case res_nextns:
+                                       res_nclose(statp);
+                                       goto next_ns;
+                               case res_modified:
+                                       /* give the hook another try */
+                                       if (++loops < 42) /*doug adams*/
+                                               break;
+                                       /*FALLTHROUGH*/
+                               case res_error:
+                                       /*FALLTHROUGH*/
+                               default:
+                                       goto fail;
+                               }
+                       } while (!done);
+
+               }
+               return (resplen);
+ next_ns: ;
+          } /*foreach ns*/
+       } /*foreach retry*/
+       res_nclose(statp);
+       if (!v_circuit) {
+               if (!gotsomewhere)
+                       errno = ECONNREFUSED;   /*%< no nameservers found */
+               else
+                       errno = ETIMEDOUT;      /*%< no answer obtained */
+       } else
+               errno = terrno;
+       return (-1);
+ fail:
+       res_nclose(statp);
+       return (-1);
+}
+
+/* Private */
+
+static int
+get_salen(sa)
+       const struct sockaddr *sa;
+{
+
+#ifdef HAVE_SA_LEN
+       /* There are people do not set sa_len.  Be forgiving to them. */
+       if (sa->sa_len)
+               return (sa->sa_len);
+#endif
+
+       if (sa->sa_family == AF_INET)
+               return (sizeof(struct sockaddr_in));
+       else if (sa->sa_family == AF_INET6)
+               return (sizeof(struct sockaddr_in6));
+       else
+               return (0);     /*%< unknown, die on connect */
+}
+
+/*%
+ * pick appropriate nsaddr_list for use.  see res_init() for initialization.
+ */
+static struct sockaddr *
+get_nsaddr(statp, n)
+       res_state statp;
+       size_t n;
+{
+
+       if (!statp->nsaddr_list[n].sin_family && EXT(statp).ext) {
+               /*
+                * - EXT(statp).ext->nsaddrs[n] holds an address that is larger
+                *   than struct sockaddr, and
+                * - user code did not update statp->nsaddr_list[n].
+                */
+               return (struct sockaddr *)(void *)&EXT(statp).ext->nsaddrs[n];
+       } else {
+               /*
+                * - user code updated statp->nsaddr_list[n], or
+                * - statp->nsaddr_list[n] has the same content as
+                *   EXT(statp).ext->nsaddrs[n].
+                */
+               return (struct sockaddr *)(void *)&statp->nsaddr_list[n];
+       }
+}
+
+static int
+send_vc(res_state statp,
+       const u_char *buf, int buflen, u_char *ans, int anssiz,
+       int *terrno, int ns)
+{
+       const HEADER *hp = (const HEADER *)(const void *)buf;
+       HEADER *anhp = (HEADER *)(void *)ans;
+       struct sockaddr *nsap;
+       int nsaplen;
+       int truncating, connreset, resplen, n;
+       struct iovec iov[2];
+       u_short len;
+       u_char *cp;
+       void *tmp;
+#ifdef SO_NOSIGPIPE
+       int on = 1;
+#endif
+
+       nsap = get_nsaddr(statp, (size_t)ns);
+       nsaplen = get_salen(nsap);
+
+       connreset = 0;
+ same_ns:
+       truncating = 0;
+
+       /* Are we still talking to whom we want to talk to? */
+       if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
+               struct sockaddr_storage peer;
+               ISC_SOCKLEN_T size = sizeof peer;
+
+               if (getpeername(statp->_vcsock,
+                               (struct sockaddr *)(void *)&peer, &size) < 0 ||
+                   !sock_eq((struct sockaddr *)(void *)&peer, nsap)) {
+                       res_nclose(statp);
+                       statp->_flags &= ~RES_F_VC;
+               }
+       }
+
+       if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
+               if (statp->_vcsock >= 0)
+                       res_nclose(statp);
+
+               statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM, 0);
+               if (statp->_vcsock > highestFD) {
+                       res_nclose(statp);
+                       errno = ENOTSOCK;
+               }
+               if (statp->_vcsock < 0) {
+                       switch (errno) {
+                       case EPROTONOSUPPORT:
+#ifdef EPFNOSUPPORT
+                       case EPFNOSUPPORT:
+#endif
+                       case EAFNOSUPPORT:
+                               Perror(statp, stderr, "socket(vc)", errno);
+                               return (0);
+                       default:
+                               *terrno = errno;
+                               Perror(statp, stderr, "socket(vc)", errno);
+                               return (-1);
+                       }
+               }
+#ifdef SO_NOSIGPIPE
+               /*
+                * Disable generation of SIGPIPE when writing to a closed
+                * socket.  Write should return -1 and set errno to EPIPE
+                * instead.
+                *
+                * Push on even if setsockopt(SO_NOSIGPIPE) fails.
+                */
+               (void)setsockopt(statp->_vcsock, SOL_SOCKET, SO_NOSIGPIPE, &on,
+                                sizeof(on));
+#endif
+               errno = 0;
+               if (connect(statp->_vcsock, nsap, (socklen_t)nsaplen) < 0) {
+                       *terrno = errno;
+                       Aerror(statp, stderr, "connect/vc", errno, nsap,
+                           nsaplen);
+                       res_nclose(statp);
+                       return (0);
+               }
+               statp->_flags |= RES_F_VC;
+       }
+
+       /*
+        * Send length & message
+        */
+       ns_put16((u_short)buflen, (u_char*)(void *)&len);
+       iov[0] = evConsIovec(&len, INT16SZ);
+       DE_CONST(buf, tmp);
+       iov[1] = evConsIovec(tmp, (size_t)buflen);
+       if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
+               *terrno = errno;
+               Perror(statp, stderr, "write failed", errno);
+               res_nclose(statp);
+               return (0);
+       }
+       /*
+        * Receive length & response
+        */
+ read_len:
+       cp = ans;
+       len = INT16SZ;
+       while ((n = read(statp->_vcsock, (char *)cp, (size_t)len)) > 0) {
+               cp += n;
+               if ((len -= n) == 0)
+                       break;
+       }
+       if (n <= 0) {
+               *terrno = errno;
+               Perror(statp, stderr, "read failed", errno);
+               res_nclose(statp);
+               /*
+                * A long running process might get its TCP
+                * connection reset if the remote server was
+                * restarted.  Requery the server instead of
+                * trying a new one.  When there is only one
+                * server, this means that a query might work
+                * instead of failing.  We only allow one reset
+                * per query to prevent looping.
+                */
+               if (*terrno == ECONNRESET && !connreset) {
+                       connreset = 1;
+                       res_nclose(statp);
+                       goto same_ns;
+               }
+               res_nclose(statp);
+               return (0);
+       }
+       resplen = ns_get16(ans);
+       if (resplen > anssiz) {
+               Dprint(statp->options & RES_DEBUG,
+                      (stdout, ";; response truncated\n")
+                      );
+               truncating = 1;
+               len = anssiz;
+       } else
+               len = resplen;
+       if (len < HFIXEDSZ) {
+               /*
+                * Undersized message.
+                */
+               Dprint(statp->options & RES_DEBUG,
+                      (stdout, ";; undersized: %d\n", len));
+               *terrno = EMSGSIZE;
+               res_nclose(statp);
+               return (0);
+       }
+       cp = ans;
+       while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (size_t)len)) > 0){
+               cp += n;
+               len -= n;
+       }
+       if (n <= 0) {
+               *terrno = errno;
+               Perror(statp, stderr, "read(vc)", errno);
+               res_nclose(statp);
+               return (0);
+       }
+       if (truncating) {
+               /*
+                * Flush rest of answer so connection stays in synch.
+                */
+               anhp->tc = 1;
+               len = resplen - anssiz;
+               while (len != 0) {
+                       char junk[PACKETSZ];
+
+                       n = read(statp->_vcsock, junk,
+                                (len > sizeof junk) ? sizeof junk : len);
+                       if (n > 0)
+                               len -= n;
+                       else
+                               break;
+               }
+       }
+       /*
+        * If the calling applicating has bailed out of
+        * a previous call and failed to arrange to have
+        * the circuit closed or the server has got
+        * itself confused, then drop the packet and
+        * wait for the correct one.
+        */
+       if (hp->id != anhp->id) {
+               DprintQ((statp->options & RES_DEBUG) ||
+                       (statp->pfcode & RES_PRF_REPLY),
+                       (stdout, ";; old answer (unexpected):\n"),
+                       ans, (resplen > anssiz) ? anssiz: resplen);
+               goto read_len;
+       }
+
+       /*
+        * All is well, or the error is fatal.  Signal that the
+        * next nameserver ought not be tried.
+        */
+       return (resplen);
+}
+
+static int
+send_dg(res_state statp, const u_char *buf, int buflen, u_char *ans,
+       int anssiz, int *terrno, int ns, int tries, int *v_circuit,
+       int *gotsomewhere)
+{
+       const HEADER *hp = (const HEADER *)(const void *)buf;
+       HEADER *anhp = (HEADER *)(void *)ans;
+       const struct sockaddr *nsap;
+       int nsaplen;
+       struct timespec now, timeout, finish;
+       struct sockaddr_storage from;
+       ISC_SOCKLEN_T fromlen;
+       int resplen, seconds, n, s;
+#ifdef USE_POLL
+       int     polltimeout;
+       struct pollfd   pollfd;
+#else
+       fd_set dsmask;
+#endif
+
+       nsap = get_nsaddr(statp, (size_t)ns);
+       nsaplen = get_salen(nsap);
+       if (EXT(statp).nssocks[ns] == -1) {
+               EXT(statp).nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM, 0);
+               if (EXT(statp).nssocks[ns] > highestFD) {
+                       res_nclose(statp);
+                       errno = ENOTSOCK;
+               }
+               if (EXT(statp).nssocks[ns] < 0) {
+                       switch (errno) {
+                       case EPROTONOSUPPORT:
+#ifdef EPFNOSUPPORT
+                       case EPFNOSUPPORT:
+#endif
+                       case EAFNOSUPPORT:
+                               Perror(statp, stderr, "socket(dg)", errno);
+                               return (0);
+                       default:
+                               *terrno = errno;
+                               Perror(statp, stderr, "socket(dg)", errno);
+                               return (-1);
+                       }
+               }
+#ifndef CANNOT_CONNECT_DGRAM
+               /*
+                * On a 4.3BSD+ machine (client and server,
+                * actually), sending to a nameserver datagram
+                * port with no nameserver will cause an
+                * ICMP port unreachable message to be returned.
+                * If our datagram socket is "connected" to the
+                * server, we get an ECONNREFUSED error on the next
+                * socket operation, and select returns if the
+                * error message is received.  We can thus detect
+                * the absence of a nameserver without timing out.
+                */
+               if (connect(EXT(statp).nssocks[ns], nsap, (socklen_t)nsaplen) < 0) {
+                       Aerror(statp, stderr, "connect(dg)", errno, nsap,
+                           nsaplen);
+                       res_nclose(statp);
+                       return (0);
+               }
+#endif /* !CANNOT_CONNECT_DGRAM */
+               Dprint(statp->options & RES_DEBUG,
+                      (stdout, ";; new DG socket\n"))
+       }
+       s = EXT(statp).nssocks[ns];
+#ifndef CANNOT_CONNECT_DGRAM
+       if (send(s, (const char*)buf, (size_t)buflen, 0) != buflen) {
+               Perror(statp, stderr, "send", errno);
+               res_nclose(statp);
+               return (0);
+       }
+#else /* !CANNOT_CONNECT_DGRAM */
+       if (sendto(s, (const char*)buf, buflen, 0, nsap, nsaplen) != buflen)
+       {
+               Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
+               res_nclose(statp);
+               return (0);
+       }
+#endif /* !CANNOT_CONNECT_DGRAM */
+
+       /*
+        * Wait for reply.
+        */
+       seconds = (statp->retrans << tries);
+       if (ns > 0)
+               seconds /= statp->nscount;
+       if (seconds <= 0)
+               seconds = 1;
+       now = evNowTime();
+       timeout = evConsTime((long)seconds, 0L);
+       finish = evAddTime(now, timeout);
+       goto nonow;
+ wait:
+       now = evNowTime();
+ nonow:
+#ifndef USE_POLL
+       FD_ZERO(&dsmask);
+       FD_SET(s, &dsmask);
+       if (evCmpTime(finish, now) > 0)
+               timeout = evSubTime(finish, now);
+       else
+               timeout = evConsTime(0L, 0L);
+       n = pselect(s + 1, &dsmask, NULL, NULL, &timeout, NULL);
+#else
+       timeout = evSubTime(finish, now);
+       if (timeout.tv_sec < 0)
+               timeout = evConsTime(0L, 0L);
+       polltimeout = 1000*(int)timeout.tv_sec +
+               (int)timeout.tv_nsec/1000000;
+       pollfd.fd = s;
+       pollfd.events = POLLRDNORM;
+       n = poll(&pollfd, 1, polltimeout);
+#endif /* USE_POLL */
+
+       if (n == 0) {
+               Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
+               *gotsomewhere = 1;
+               return (0);
+       }
+       if (n < 0) {
+               if (errno == EINTR)
+                       goto wait;
+#ifndef USE_POLL
+               Perror(statp, stderr, "select", errno);
+#else
+               Perror(statp, stderr, "poll", errno);
+#endif /* USE_POLL */
+               res_nclose(statp);
+               return (0);
+       }
+       errno = 0;
+       fromlen = sizeof(from);
+       resplen = recvfrom(s, (char*)ans, (size_t)anssiz,0,
+                          (struct sockaddr *)(void *)&from, &fromlen);
+       if (resplen <= 0) {
+               Perror(statp, stderr, "recvfrom", errno);
+               res_nclose(statp);
+               return (0);
+       }
+       *gotsomewhere = 1;
+       if (resplen < HFIXEDSZ) {
+               /*
+                * Undersized message.
+                */
+               Dprint(statp->options & RES_DEBUG,
+                      (stdout, ";; undersized: %d\n",
+                       resplen));
+               *terrno = EMSGSIZE;
+               res_nclose(statp);
+               return (0);
+       }
+       if (hp->id != anhp->id) {
+               /*
+                * response from old query, ignore it.
+                * XXX - potential security hazard could
+                *       be detected here.
+                */
+               DprintQ((statp->options & RES_DEBUG) ||
+                       (statp->pfcode & RES_PRF_REPLY),
+                       (stdout, ";; old answer:\n"),
+                       ans, (resplen > anssiz) ? anssiz : resplen);
+               goto wait;
+       }
+       if (!(statp->options & RES_INSECURE1) &&
+           !res_ourserver_p(statp, (struct sockaddr *)(void *)&from)) {
+               /*
+                * response from wrong server? ignore it.
+                * XXX - potential security hazard could
+                *       be detected here.
+                */
+               DprintQ((statp->options & RES_DEBUG) ||
+                       (statp->pfcode & RES_PRF_REPLY),
+                       (stdout, ";; not our server:\n"),
+                       ans, (resplen > anssiz) ? anssiz : resplen);
+               goto wait;
+       }
+#ifdef RES_USE_EDNS0
+       if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
+               /*
+                * Do not retry if the server do not understand EDNS0.
+                * The case has to be captured here, as FORMERR packet do not
+                * carry query section, hence res_queriesmatch() returns 0.
+                */
+               DprintQ(statp->options & RES_DEBUG,
+                       (stdout, "server rejected query with EDNS0:\n"),
+                       ans, (resplen > anssiz) ? anssiz : resplen);
+               /* record the error */
+               statp->_flags |= RES_F_EDNS0ERR;
+               res_nclose(statp);
+               return (0);
+       }
+#endif
+       if (!(statp->options & RES_INSECURE2) &&
+           !res_queriesmatch(buf, buf + buflen,
+                             ans, ans + anssiz)) {
+               /*
+                * response contains wrong query? ignore it.
+                * XXX - potential security hazard could
+                *       be detected here.
+                */
+               DprintQ((statp->options & RES_DEBUG) ||
+                       (statp->pfcode & RES_PRF_REPLY),
+                       (stdout, ";; wrong query name:\n"),
+                       ans, (resplen > anssiz) ? anssiz : resplen);
+               goto wait;
+       }
+       if (anhp->rcode == SERVFAIL ||
+           anhp->rcode == NOTIMP ||
+           anhp->rcode == REFUSED) {
+               DprintQ(statp->options & RES_DEBUG,
+                       (stdout, "server rejected query:\n"),
+                       ans, (resplen > anssiz) ? anssiz : resplen);
+               res_nclose(statp);
+               /* don't retry if called from dig */
+               if (!statp->pfcode)
+                       return (0);
+       }
+       if (!(statp->options & RES_IGNTC) && anhp->tc) {
+               /*
+                * To get the rest of answer,
+                * use TCP with same server.
+                */
+               Dprint(statp->options & RES_DEBUG,
+                      (stdout, ";; truncated answer\n"));
+               *v_circuit = 1;
+               res_nclose(statp);
+               return (1);
+       }
+       /*
+        * All is well, or the error is fatal.  Signal that the
+        * next nameserver ought not be tried.
+        */
+       return (resplen);
+}
+
+static void
+Aerror(const res_state statp, FILE *file, const char *string, int error,
+       const struct sockaddr *address, int alen)
+{
+       int save = errno;
+       char hbuf[NI_MAXHOST];
+       char sbuf[NI_MAXSERV];
+
+       alen = alen;
+
+       if ((statp->options & RES_DEBUG) != 0U) {
+               if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf),
+                   sbuf, sizeof(sbuf), niflags)) {
+                       strncpy(hbuf, "?", sizeof(hbuf) - 1);
+                       hbuf[sizeof(hbuf) - 1] = '\0';
+                       strncpy(sbuf, "?", sizeof(sbuf) - 1);
+                       sbuf[sizeof(sbuf) - 1] = '\0';
+               }
+               fprintf(file, "res_send: %s ([%s].%s): %s\n",
+                       string, hbuf, sbuf, strerror(error));
+       }
+       errno = save;
+}
+
+static void
+Perror(const res_state statp, FILE *file, const char *string, int error) {
+       int save = errno;
+
+       if ((statp->options & RES_DEBUG) != 0U)
+               fprintf(file, "res_send: %s: %s\n",
+                       string, strerror(error));
+       errno = save;
+}
+
+static int
+sock_eq(struct sockaddr *a, struct sockaddr *b) {
+       struct sockaddr_in *a4, *b4;
+       struct sockaddr_in6 *a6, *b6;
+
+       if (a->sa_family != b->sa_family)
+               return 0;
+       switch (a->sa_family) {
+       case AF_INET:
+               a4 = (struct sockaddr_in *)(void *)a;
+               b4 = (struct sockaddr_in *)(void *)b;
+               return a4->sin_port == b4->sin_port &&
+                   a4->sin_addr.s_addr == b4->sin_addr.s_addr;
+       case AF_INET6:
+               a6 = (struct sockaddr_in6 *)(void *)a;
+               b6 = (struct sockaddr_in6 *)(void *)b;
+               return a6->sin6_port == b6->sin6_port &&
+#ifdef HAVE_SIN6_SCOPE_ID
+                   a6->sin6_scope_id == b6->sin6_scope_id &&
+#endif
+                   IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
+       default:
+               return 0;
+       }
+}
+
+#if defined(NEED_PSELECT) && !defined(USE_POLL)
+/* XXX needs to move to the porting library. */
+static int
+pselect(int nfds, void *rfds, void *wfds, void *efds,
+       struct timespec *tsp, const sigset_t *sigmask)
+{
+       struct timeval tv, *tvp;
+       sigset_t sigs;
+       int n;
+
+       if (tsp) {
+               tvp = &tv;
+               tv = evTimeVal(*tsp);
+       } else
+               tvp = NULL;
+       if (sigmask)
+               sigprocmask(SIG_SETMASK, sigmask, &sigs);
+       n = select(nfds, rfds, wfds, efds, tvp);
+       if (sigmask)
+               sigprocmask(SIG_SETMASK, &sigs, NULL);
+       if (tsp)
+               *tsp = evTimeSpec(tv);
+       return (n);
+}
+#endif
diff --git a/lib/nbsd_libc/resolv/res_state.c b/lib/nbsd_libc/resolv/res_state.c
new file mode 100644 (file)
index 0000000..f758862
--- /dev/null
@@ -0,0 +1,73 @@
+/*     $NetBSD: res_state.c,v 1.8 2009/01/11 02:46:29 christos Exp $   */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: res_state.c,v 1.8 2009/01/11 02:46:29 christos Exp $");
+#endif
+
+#include <sys/types.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+#include <netdb.h>
+#include <resolv.h>
+
+struct __res_state _nres
+# if defined(__BIND_RES_TEXT)
+       = { .retrans = RES_TIMEOUT, }   /*%< Motorola, et al. */
+# endif
+       ;
+
+res_state __res_get_state_nothread(void);
+void __res_put_state_nothread(res_state);
+
+#ifdef __weak_alias
+__weak_alias(__res_get_state, __res_get_state_nothread)
+__weak_alias(__res_put_state, __res_put_state_nothread)
+/* Source compatibility; only for single threaded programs */
+__weak_alias(__res_state, __res_get_state_nothread)
+#endif
+
+res_state
+__res_get_state_nothread(void)
+{
+       if ((_nres.options & RES_INIT) == 0 && res_ninit(&_nres) == -1) {
+               h_errno = NETDB_INTERNAL;
+               return NULL;
+       }
+       return &_nres;
+}
+
+void
+/*ARGSUSED*/
+__res_put_state_nothread(res_state res)
+{
+}
diff --git a/lib/nbsd_libc/rpc/DISCLAIMER b/lib/nbsd_libc/rpc/DISCLAIMER
new file mode 100644 (file)
index 0000000..0acd291
--- /dev/null
@@ -0,0 +1,30 @@
+/*     $NetBSD: DISCLAIMER,v 1.2 1998/01/09 04:11:51 perry Exp $       */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
diff --git a/lib/nbsd_libc/rpc/Makefile.inc b/lib/nbsd_libc/rpc/Makefile.inc
new file mode 100644 (file)
index 0000000..9bb274f
--- /dev/null
@@ -0,0 +1,168 @@
+#      $NetBSD: Makefile.inc,v 1.17 2008/10/25 19:07:26 mrg Exp $
+
+# librpc sources
+.PATH: ${.CURDIR}/rpc
+
+SRCS+= auth_none.c auth_unix.c authunix_prot.c bindresvport.c \
+       clnt_bcast.c clnt_dg.c clnt_generic.c clnt_perror.c \
+       clnt_raw.c clnt_simple.c \
+       clnt_vc.c rpc_dtablesize.c \
+       getnetconfig.c getnetpath.c getrpcent.c getrpcport.c \
+       mt_misc.c pmap_clnt.c pmap_getmaps.c pmap_getport.c pmap_prot.c \
+       pmap_prot2.c pmap_rmt.c rpc_prot.c rpc_commondata.c rpc_callmsg.c \
+       rpc_generic.c rpc_soc.c rpcb_clnt.c rpcb_prot.c rpcb_st_xdr.c \
+       svc.c svc_auth.c svc_dg.c svc_auth_unix.c svc_generic.c svc_raw.c \
+       svc_run.c svc_simple.c svc_vc.c \
+       xdr.c xdr_array.c xdr_float.c xdr_mem.c xdr_rec.c xdr_reference.c \
+       xdr_stdio.c __rpc_getxid.c
+
+CPPFLAGS+=     -DPORTMAP
+
+MAN+=  bindresvport.3 getnetconfig.3 getnetpath.3 getrpcent.3 getrpcport.3 \
+       rpc.3 rpc_soc.3 rpc_clnt_auth.3 rpc_clnt_calls.3 rpc_clnt_create.3 \
+       rpc_svc_calls.3 rpc_svc_create.3 rpc_svc_err.3 rpc_svc_reg.3 \
+       rpc_xdr.3 rpcbind.3 xdr.3
+MLINKS+=       bindresvport.3 bindresvport_sa.3 \
+               getnetconfig.3 setnetconfig.3 \
+               getnetconfig.3 getnetconfigent.3 \
+               getnetconfig.3 endnetconfig.3 \
+               getnetconfig.3 nc_perror.3 \
+               getnetconfig.3 nc_sperror.3 \
+               getnetpath.3 setnetpath.3 \
+               getnetpath.3 endnetpath.3 \
+               getrpcent.3 getrpcbyname.3 \
+               getrpcent.3 getrpcbynumber.3 \
+               getrpcent.3 endrpcent.3 \
+               getrpcent.3 setrpcent.3 \
+               rpc_clnt_auth.3 auth_destroy.3 \
+               rpc_clnt_auth.3 authnone_create.3 \
+               rpc_clnt_auth.3 authsys_create.3 \
+               rpc_clnt_auth.3 authsys_create_default.3 \
+               rpc_clnt_calls.3 clnt_call.3 \
+               rpc_clnt_calls.3 clnt_perrno.3 \
+               rpc_clnt_calls.3 clnt_perror.3 \
+               rpc_clnt_calls.3 clnt_sperrno.3 \
+               rpc_clnt_calls.3 clnt_sperror.3 \
+               rpc_clnt_calls.3 rpc_call.3 \
+               rpc_clnt_calls.3 rpc_broadcast.3 \
+               rpc_clnt_calls.3 rpc_broadcast_exp.3 \
+               rpc_clnt_calls.3 clnt_freeres.3 \
+               rpc_clnt_calls.3 clnt_geterr.3 \
+               rpc_clnt_create.3 clnt_control.3 \
+               rpc_clnt_create.3 clnt_create.3 \
+               rpc_clnt_create.3 clnt_create_vers.3 \
+               rpc_clnt_create.3 clnt_destroy.3 \
+               rpc_clnt_create.3 clnt_pcreateerror.3 \
+               rpc_clnt_create.3 clnt_spcreateerror.3 \
+               rpc_clnt_create.3 clnt_dg_create.3 \
+               rpc_clnt_create.3 clnt_raw_create.3 \
+               rpc_clnt_create.3 clnt_tli_create.3 \
+               rpc_clnt_create.3 clnt_tp_create.3 \
+               rpc_clnt_create.3 clnt_vc_create.3 \
+               rpc_svc_calls.3 svc_dg_enablecache.3 \
+               rpc_svc_calls.3 svc_exit.3 \
+               rpc_svc_calls.3 svc_freeargs.3 \
+               rpc_svc_calls.3 svc_getargs.3 \
+               rpc_svc_calls.3 svc_getreq_common.3 \
+               rpc_svc_calls.3 svc_getreq_poll.3 \
+               rpc_svc_calls.3 svc_getreqset.3 \
+               rpc_svc_calls.3 svc_getrpccaller.3 \
+               rpc_svc_calls.3 __svc_getcallercreds.3 \
+               rpc_svc_calls.3 svc_pollset.3 \
+               rpc_svc_calls.3 svc_run.3 \
+               rpc_svc_calls.3 svc_sendreply.3 \
+               rpc_svc_create.3 svc_control.3 \
+               rpc_svc_create.3 svc_create.3 \
+               rpc_svc_create.3 svc_dg_create.3 \
+               rpc_svc_create.3 svc_destroy.3 \
+               rpc_svc_create.3 svc_fd_create.3 \
+               rpc_svc_create.3 svc_raw_create.3 \
+               rpc_svc_create.3 svc_tli_create.3 \
+               rpc_svc_create.3 svc_tp_create.3 \
+               rpc_svc_create.3 svc_vc_create.3 \
+               rpc_svc_err.3 svcerr_auth.3 \
+               rpc_svc_err.3 svcerr_decode.3 \
+               rpc_svc_err.3 svcerr_noproc.3 \
+               rpc_svc_err.3 svcerr_noprog.3 \
+               rpc_svc_err.3 svcerr_progvers.3 \
+               rpc_svc_err.3 svcerr_systemerr.3 \
+               rpc_svc_err.3 svcerr_weakauth.3 \
+               rpc_svc_reg.3 rpc_reg.3 \
+               rpc_svc_reg.3 svc_reg.3 \
+               rpc_svc_reg.3 svc_unreg.3 \
+               rpc_svc_reg.3 svc_auth_reg.3 \
+               rpc_svc_reg.3 xprt_register.3 \
+               rpc_svc_reg.3 xprt_unregister.3 \
+               rpc_xdr.3 xdr_accepted_reply.3 \
+               rpc_xdr.3 xdr_authsys_parms.3 \
+               rpc_xdr.3 xdr_callhdr.3 \
+               rpc_xdr.3 xdr_callmsg.3 \
+               rpc_xdr.3 xdr_opaque_auth.3 \
+               rpc_xdr.3 xdr_rejected_reply.3 \
+               rpc_xdr.3 xdr_replymsg.3 \
+               rpcbind.3 rpcb_getmaps.3 \
+               rpcbind.3 rpcb_getaddr.3 \
+               rpcbind.3 rpcb_gettime.3 \
+               rpcbind.3 rpcb_rmtcall.3 \
+               rpcbind.3 rpcb_set.3 \
+               rpcbind.3 rpcb_unset.3 \
+               rpc_soc.3 authunix_create.3 \
+               rpc_soc.3 authunix_create_default.3 \
+               rpc_soc.3 callrpc.3 \
+               rpc_soc.3 clnt_broadcast.3 \
+               rpc_soc.3 clntraw_create.3 \
+               rpc_soc.3 clnttcp_create.3 \
+               rpc_soc.3 clntudp_bufcreate.3 \
+               rpc_soc.3 clntudp_create.3 \
+               rpc_soc.3 get_myaddress.3 \
+               rpc_soc.3 pmap_getmaps.3 \
+               rpc_soc.3 pmap_getport.3 \
+               rpc_soc.3 pmap_rmtcall.3 \
+               rpc_soc.3 pmap_set.3 \
+               rpc_soc.3 pmap_unset.3 \
+               rpc_soc.3 registerrpc.3 \
+               rpc_soc.3 rpc_createerr.3 \
+               rpc_soc.3 svc_fds.3 \
+               rpc_soc.3 svc_fdset.3 \
+               rpc_soc.3 svc_getcaller.3 \
+               rpc_soc.3 svc_register.3 \
+               rpc_soc.3 svc_unregister.3 \
+               rpc_soc.3 svcfd_create.3 \
+               rpc_soc.3 svcraw_create.3 \
+               rpc_soc.3 svctcp_create.3 \
+               rpc_soc.3 svcudp_create.3 \
+               rpc_soc.3 svcudp_bufcreate.3 \
+               rpc_soc.3 xdr_pmap.3 \
+               rpc_soc.3 xdr_pmaplist.3 \
+               xdr.3 xdr_array.3 \
+               xdr.3 xdr_bool.3 \
+               xdr.3 xdr_bytes.3 \
+               xdr.3 xdr_char.3 \
+               xdr.3 xdr_destroy.3 \
+               xdr.3 xdr_double.3 \
+               xdr.3 xdr_enum.3 \
+               xdr.3 xdr_float.3 \
+               xdr.3 xdr_free.3 \
+               xdr.3 xdr_getpos.3 \
+               xdr.3 xdr_inline.3 \
+               xdr.3 xdr_int.3 \
+               xdr.3 xdr_long.3 \
+               xdr.3 xdrmem_create.3 \
+               xdr.3 xdr_opaque.3 \
+               xdr.3 xdr_pointer.3 \
+               xdr.3 xdrrec_create.3 \
+               xdr.3 xdrrec_endofrecord.3 \
+               xdr.3 xdrrec_eof.3 \
+               xdr.3 xdrrec_skiprecord.3 \
+               xdr.3 xdr_reference.3 \
+               xdr.3 xdr_setpos.3 \
+               xdr.3 xdr_short.3 \
+               xdr.3 xdrstdio_create.3 \
+               xdr.3 xdr_string.3 \
+               xdr.3 xdr_u_char.3 \
+               xdr.3 xdr_u_long.3 \
+               xdr.3 xdr_u_short.3 \
+               xdr.3 xdr_union.3 \
+               xdr.3 xdr_vector.3 \
+               xdr.3 xdr_void.3 \
+               xdr.3 xdr_wrapstring.3
diff --git a/lib/nbsd_libc/rpc/README b/lib/nbsd_libc/rpc/README
new file mode 100644 (file)
index 0000000..3f12eb3
--- /dev/null
@@ -0,0 +1,235 @@
+#      $NetBSD: README,v 1.2 1998/01/09 04:11:52 perry Exp $
+
+RPCSRC 4.0 7/11/89
+
+This distribution contains Sun Microsystem's implementation of the
+RPC and XDR protocols and is compatible with 4.2BSD and 4.3BSD.  Also
+included is complete documentation, utilities, RPC service
+specification files, and demonstration services in the format used by
+the RPC protocol compiler (rpcgen).  See WHAT'S NEW below for
+details.
+
+NOTE ABOUT SECURE RPC:
+
+This release of RPCSRC contains most of the code needed to implement
+Secure RPC (see "DES Authentication" in the RPC Protocol Specification,
+doc/rpc.rfc.ms).  Due to legal considerations, we are unable to
+distribute an implementation of DES, the Data Encryption Standard, which
+Secure RPC requires.  For this reason, all of the files, documentation, and
+programs associated with Secure RPC have been placed into a separate
+directory, secure_rpc.  The RPC library contained in the main body of this
+release *DOES NOT* support Secure RPC.  See secure_rpc/README for more
+details.  (A DES library was posted in Volume 18 of comp.sources.unix.)
+
+If you wish to report bugs found in this release, send mail to:
+
+Portable ONC/NFS
+Sun Microsystems, Inc
+MS 12-33
+2550 Garcia Avenue
+Mountain View, CA  94043
+
+or send Email to nfsnet@sun.com (the Internet) or sun!nfsnet (Usenet).
+
+ROADMAP
+
+The directory hierarchy is as follows:
+
+    demo/       Various demonstration services
+    demo/dir        Remote directory lister
+    demo/msg        Remote console message delivery service
+    demo/sort       Remote sort service
+
+    doc/        Documentation for RPC, XDR and NFS in "-ms" format.
+
+    etc/        Utilities (rpcinfo and portmap).  portmap must be
+                started by root before any other RPC network services are
+                used.  SEE BELOW FOR BUGFIX TO 4.3BSD COMPILER.
+
+    man/        Manual pages for RPC library, rpcgen, and utilities.
+
+    rpc/        The RPC and XDR library.  SEE BELOW
+                FOR BUGFIX TO 4.2BSD COMPILER.
+
+    rpcgen/     The RPC Language compiler (for .x files)
+
+    rpcsvc/     Service definition files for various services and the
+                server and client code for the Remote Status service.
+
+    secure_rpc/ The files in this directory are used to build a version of
+                the RPC library with DES Authentication.  See the README
+                file in that directory for more details.
+
+BUILD INSTRUCTIONS
+
+Makefiles can be found in all directories except for man.  The
+Makefile in the top directory will cause these others to be invoked
+(except for in the doc, man and demo directories), in turn building the
+entire release.
+
+WARNING!  THE DEFAULT INSTALLATION PROCEDURES WILL INSTALL FILES
+IN /usr/include, /usr/lib, /usr/bin and /etc.
+
+The master RPC include file, rpc/rpc.h, is used by all programs and
+routines that use RPC.  It includes other RPC and system include files
+needed by the RPC system.  PLEASE NOTE: If your system has NFS, it
+may have been based on Sun's NFS Source.  The include files installed
+by this package may duplicate include files you will find on your NFS
+system.  The RPCSRC 4.0 include files are upwardly compatible to all
+NFS Source include files as of the date of this distribution (not
+including any new definitions or declarations added by your system
+vendor).  HOWEVER: Please read the comments towards the end of
+rpc/rpc.h regarding rpc/netdb.h.  You may need to uncomment the
+inclusion of that file if the structures it defines are already
+defined by your system's include files.
+
+After making any compiler fixes that are needed (see below), at
+the top directory, type:
+
+    make install
+
+For all installations, the Makefile macro DESTDIR is prepended to the
+installation path.  It is defined to be null in the Makefiles, so
+installations are relative to root.  (You will probably need root
+privileges for installing the files under the default path.)  To
+install the files under some other tree (e.g., /usr/local), use the
+command:
+
+    make install DESTDIR=/usr/local
+
+This will place the include files in /usr/local/usr/include, the RPC
+library in /usr/local/usr/lib, rpcgen in /usr/local/usr/bin, and the
+utilities in /usr/local/etc.  You'll have to edit the Makefiles or
+install the files by hand if you want to do anything other than this
+kind of relocation of the installation tree.
+
+The RPC library will be built and installed first.  By default it is
+installed in /usr/lib as "librpclib.a".  The directory
+/usr/include/rpc will also be created, and several header files will
+be installed there.  ALL RPC SERVICES INCLUDE THESE HEADER FILES.
+
+The programs in etc/ link in routines from librpclib.a.  If you change
+where it is installed, be sure to edit etc/'s Makefile to reflect this.
+These programs are installed in /etc.  PORTMAP MUST BE RUNNING ON
+YOUR SYSTEM BEFORE YOU START ANY OTHER RPC SERVICE.
+
+rpcgen is installed in /usr/bin.  This program is required to build
+the demonstration services in demo and the rstat client and server in
+rpcsvc/.
+
+The rpcsvc/ directory will install its files in the directory
+/usr/include/rpcsvc.  The Remote Status service (rstat_svc) will be
+compiled and installed in /etc.  If you wish to make this service
+available, you should either start this service when needed or have
+it started at boot time by invoking it in your /etc/rc.local script.
+(Be sure that portmap is started first!)  Sun has modified its
+version of inetd to automatically start RPC services.  (Use "make
+LIB=" when building rstat on a Sun Workstation.)  The Remote Status
+client (rstat) will be installed in /usr/bin.  This program queries
+the rstat_svc on a remote host and prints a system status summary
+similar to the one printed by "uptime".
+
+The documentation is not built during the "make install" command.
+Typing "make" in the doc directory will cause all of the manuals to
+be formatted using nroff into a single file.  We have had a report
+that certain "troff" equivalents have trouble processing the full
+manual.  If you have trouble, try building the manuals individually
+(see the Makefile).
+
+The demonstration services in the demo directory are not built by the
+top-level "make install" command.  To build these, cd to the demo
+directory and enter "make".  The three services will be built.
+RPCGEN MUST BE INSTALLED in a path that make can find.  To run the
+services, start the portmap program as root and invoke the service
+(you probably will want to put it in the background).  rpcinfo can be
+used to check that the service succeeded in getting registered with
+portmap, and to ping the service (see rpcinfo's man page).  You can
+then use the corresponding client program to exercise the service.
+To build these services on a Sun workstation, you must prevent the
+Makefile from trying to link the RPC library (as these routines are
+already a part of Sun's libc).  Use: "make LIB=".
+
+BUGFIX FOR 4.3BSD COMPILER
+
+The use of a 'void *' declaration for one of the arguments in
+the reply_proc() procedure in etc/rpcinfo.c will trigger a bug
+in the 4.3BSD compiler.  The bug is fixed by the following change to
+the compiler file mip/manifest.h:
+
+*** manifest.h.r1.1    Thu Apr 30 13:52:25 1987
+--- manifest.h.r1.2    Mon Nov 23 18:58:17 1987
+***************
+*** 21,27 ****
+  /*
+   * Bogus type values
+   */
+! #define TNULL        PTR             /* pointer to UNDEF */
+  #define TVOID        FTN             /* function returning UNDEF (for void) */
+  
+  /*
+--- 21,27 ----
+  /*
+   * Bogus type values
+   */
+! #define TNULL        INCREF(MOETY)   /* pointer to MOETY -- impossible type */
+  #define TVOID        FTN             /* function returning UNDEF (for void) */
+  
+  /*
+
+If you cannot fix your compiler, change the declaration in reply_proc()
+from 'void *' to 'char *'.
+
+BUGFIX FOR 4.2BSD COMPILER
+
+Unpatched 4.2BSD compilers complain about valid C.  You can make old
+compilers happy by changing some voids to ints.  However, the fix to
+the 4.2 VAX compiler is as follows (to mip/trees.c):
+
+*** trees.c.r1.1       Mon May 11 13:47:58 1987
+--- trees.c.r1.2       Wed Jul  2 18:28:52 1986
+***************
+*** 1247,1253 ****
+               if(o==CAST && mt1==0)return(TYPL+TYMATCH);
+               if( mt12 & MDBI ) return( TYPL+LVAL+TYMATCH );
+               else if( (mt1&MENU)||(mt2&MENU) ) return( LVAL+NCVT+TYPL+PTMATCH+PUN );
+!              else if( mt12 == 0 ) break;
+               else if( mt1 & MPTR ) return( LVAL+PTMATCH+PUN );
+               else if( mt12 & MPTI ) return( TYPL+LVAL+TYMATCH+PUN );
+               break;
+--- 1261,1269 ----
+               if(o==CAST && mt1==0)return(TYPL+TYMATCH);
+               if( mt12 & MDBI ) return( TYPL+LVAL+TYMATCH );
+               else if( (mt1&MENU)||(mt2&MENU) ) return( LVAL+NCVT+TYPL+PTMATCH+PUN );
+!              /* if right is TVOID and looks like a CALL, is not ok */
+!              else if (mt2 == 0 && (p->in.right->in.op == CALL || p->in.right->in.op == UNARY CALL))
+!                      break;
+               else if( mt1 & MPTR ) return( LVAL+PTMATCH+PUN );
+               else if( mt12 & MPTI ) return( TYPL+LVAL+TYMATCH+PUN );
+               break;
+
+WHAT'S NEW IN THIS RELEASE: RPCSRC 4.0
+
+The previous release was RPCSRC 3.9.  As with all previous releases,
+this release is based directly on files from Sun Microsystem's
+implementation.
+
+Upgrade from RPCSRC 3.9
+
+1)  RPCSRC 4.0 upgrades RPCSRC 3.9.  Improvements from SunOS 4.0 have
+    been integrated into this release.
+
+Secure RPC (in the secure_rpc/ directory)
+
+2)  DES Authentication routines and programs are provided.
+3)  A new manual, "Secure NFS" is provided, which describes Secure RPC
+    and Secure NFS.
+4)  Skeleton routines and manual pages are provided which describe the
+    DES encryption procedures required by Secure RPC.  HOWEVER, NO DES
+    ROUTINE IS PROVIDED.
+
+New Functionality
+
+5)  rpcinfo can now be used to de-register services from the portmapper
+    which may have terminated abnormally.
+6)  A new client, rstat, is provided which queries the rstat_svc and
+    prints a status line similar to the one displayed by "uptime".
diff --git a/lib/nbsd_libc/rpc/__rpc_getxid.c b/lib/nbsd_libc/rpc/__rpc_getxid.c
new file mode 100644 (file)
index 0000000..ab350d4
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: __rpc_getxid.c,v 1.3 2003/09/13 21:27:46 itojun Exp $  */
+/*     $OpenBSD: ip_id.c,v 1.6 2002/03/15 18:19:52 millert Exp $       */
+
+/*
+ * Copyright (C) 2003 WIDE Project.
+ * 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.
+ * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __rpc_getxid.c,v 1.3 2003/09/13 21:27:46 itojun Exp $");
+#endif
+
+#include <sys/types.h>
+
+#include "namespace.h"
+
+#include <stdlib.h>
+#include <randomid.h>
+#include <rpc/rpc.h>
+#include "rpc_internal.h"
+
+u_int32_t
+__rpc_getxid(void)
+{
+       static randomid_t ctx = NULL;
+
+       if (!ctx) {
+               ctx = randomid_new(32, RANDOMID_TIMEO_DEFAULT);
+               if (!ctx)
+                       abort();
+       }
+
+       return randomid(ctx);
+}
diff --git a/lib/nbsd_libc/rpc/auth_none.c b/lib/nbsd_libc/rpc/auth_none.c
new file mode 100644 (file)
index 0000000..46f739e
--- /dev/null
@@ -0,0 +1,163 @@
+/*     $NetBSD: auth_none.c,v 1.14 2001/01/16 15:46:52 lukem Exp $     */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)auth_none.c 1.19 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)auth_none.c 2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: auth_none.c,v 1.14 2001/01/16 15:46:52 lukem Exp $");
+#endif
+#endif
+
+/*
+ * auth_none.c
+ * Creates a client authentication handle for passing "null" 
+ * credentials and verifiers to remote systems. 
+ * 
+ * Copyright (C) 1984, Sun Microsystems, Inc. 
+ */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+#include <rpc/auth.h>
+
+#ifdef __weak_alias
+__weak_alias(authnone_create,_authnone_create)
+#endif
+
+#define MAX_MARSHAL_SIZE 20
+
+/*
+ * Authenticator operations routines
+ */
+
+static bool_t authnone_marshal __P((AUTH *, XDR *));
+static void authnone_verf __P((AUTH *));
+static bool_t authnone_validate __P((AUTH *, struct opaque_auth *));
+static bool_t authnone_refresh __P((AUTH *));
+static void authnone_destroy __P((AUTH *));
+
+static const struct auth_ops ops = {
+       authnone_verf,
+       authnone_marshal,
+       authnone_validate,
+       authnone_refresh,
+       authnone_destroy
+};
+
+static struct authnone_private {
+       AUTH    no_client;
+       char    marshalled_client[MAX_MARSHAL_SIZE];
+       u_int   mcnt;
+} *authnone_private;
+
+AUTH *
+authnone_create()
+{
+       struct authnone_private *ap = authnone_private;
+       XDR xdr_stream;
+       XDR *xdrs;
+
+       if (ap == 0) {
+               ap = (struct authnone_private *)calloc(1, sizeof (*ap));
+               if (ap == 0)
+                       return (0);
+               authnone_private = ap;
+       }
+       if (!ap->mcnt) {
+               ap->no_client.ah_cred = ap->no_client.ah_verf = _null_auth;
+               ap->no_client.ah_ops = &ops;
+               xdrs = &xdr_stream;
+               xdrmem_create(xdrs, ap->marshalled_client,
+                   (u_int)MAX_MARSHAL_SIZE, XDR_ENCODE);
+               (void)xdr_opaque_auth(xdrs, &ap->no_client.ah_cred);
+               (void)xdr_opaque_auth(xdrs, &ap->no_client.ah_verf);
+               ap->mcnt = XDR_GETPOS(xdrs);
+               XDR_DESTROY(xdrs);
+       }
+       return (&ap->no_client);
+}
+
+/*ARGSUSED*/
+static bool_t
+authnone_marshal(client, xdrs)
+       AUTH *client;
+       XDR *xdrs;
+{
+       struct authnone_private *ap = authnone_private;
+
+       _DIAGASSERT(xdrs != NULL);
+
+       if (ap == 0)
+               return (0);
+       return ((*xdrs->x_ops->x_putbytes)(xdrs,
+           ap->marshalled_client, ap->mcnt));
+}
+
+/*ARGSUSED*/
+static void 
+authnone_verf(client)
+       AUTH *client;
+{
+}
+
+/*ARGSUSED*/
+static bool_t
+authnone_validate(client, auth)
+       AUTH *client;
+       struct opaque_auth *auth;
+{
+
+       return (TRUE);
+}
+
+/*ARGSUSED*/
+static bool_t
+authnone_refresh(client)
+       AUTH *client;
+{
+
+       return (FALSE);
+}
+
+/*ARGSUSED*/
+static void
+authnone_destroy(client)
+       AUTH *client;
+{
+}
diff --git a/lib/nbsd_libc/rpc/auth_unix.c b/lib/nbsd_libc/rpc/auth_unix.c
new file mode 100644 (file)
index 0000000..8792eb3
--- /dev/null
@@ -0,0 +1,384 @@
+/*     $NetBSD: auth_unix.c,v 1.22 2009/01/11 02:46:29 christos Exp $  */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ *
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)auth_unix.c 1.19 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)auth_unix.c 2.2 88/08/01 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: auth_unix.c,v 1.22 2009/01/11 02:46:29 christos Exp $");
+#endif
+#endif
+
+/*
+ * auth_unix.c, Implements UNIX style authentication parameters. 
+ *  
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ * The system is very weak.  The client uses no encryption for it's
+ * credentials and only sends null verifiers.  The server sends backs
+ * null verifiers or optionally a verifier that suggests a new short hand
+ * for the credentials.
+ *
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/param.h>
+
+#include <assert.h>
+#include <err.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+#include <rpc/auth.h>
+#include <rpc/auth_unix.h>
+
+#ifdef __weak_alias
+__weak_alias(authunix_create,_authunix_create)
+__weak_alias(authunix_create_default,_authunix_create_default)
+#endif
+
+
+/* auth_unix.c */
+static void authunix_nextverf __P((AUTH *));
+static bool_t authunix_marshal __P((AUTH *, XDR *));
+static bool_t authunix_validate __P((AUTH *, struct opaque_auth *));
+static bool_t authunix_refresh __P((AUTH *));
+static void authunix_destroy __P((AUTH *));
+static void marshal_new_auth __P((AUTH *));
+static const struct auth_ops *authunix_ops __P((void));
+
+/*
+ * This struct is pointed to by the ah_private field of an auth_handle.
+ */
+struct audata {
+       struct opaque_auth      au_origcred;    /* original credentials */
+       struct opaque_auth      au_shcred;      /* short hand cred */
+       u_long                  au_shfaults;    /* short hand cache faults */
+       char                    au_marshed[MAX_AUTH_BYTES];
+       u_int                   au_mpos;        /* xdr pos at end of marshed */
+};
+#define        AUTH_PRIVATE(auth)      ((struct audata *)auth->ah_private)
+
+/*
+ * Create a unix style authenticator.
+ * Returns an auth handle with the given stuff in it.
+ */
+AUTH *
+authunix_create(machname, uid, gid, len, aup_gids)
+       char *machname;
+       int uid;
+       int gid;
+       int len;
+       int *aup_gids;
+{
+       struct authunix_parms aup;
+       char mymem[MAX_AUTH_BYTES];
+       struct timeval now;
+       XDR xdrs;
+       AUTH *auth;
+       struct audata *au;
+
+       /*
+        * Allocate and set up auth handle
+        */
+       au = NULL;
+       auth = mem_alloc(sizeof(*auth));
+#ifndef KERNEL
+       if (auth == NULL) {
+               warnx("authunix_create: out of memory");
+               goto cleanup_authunix_create;
+       }
+#endif
+       au = mem_alloc(sizeof(*au));
+#ifndef KERNEL
+       if (au == NULL) {
+               warnx("authunix_create: out of memory");
+               goto cleanup_authunix_create;
+       }
+#endif
+       auth->ah_ops = authunix_ops();
+       auth->ah_private = au;
+       auth->ah_verf = au->au_shcred = _null_auth;
+       au->au_shfaults = 0;
+       au->au_origcred.oa_base = NULL;
+
+       /*
+        * fill in param struct from the given params
+        */
+       (void)gettimeofday(&now, NULL);
+       aup.aup_time = (u_long)now.tv_sec;      /* XXX: truncate on 32 bit */
+       aup.aup_machname = machname;
+       aup.aup_uid = uid;
+       aup.aup_gid = gid;
+       aup.aup_len = (u_int)len;
+       aup.aup_gids = aup_gids;
+
+       /*
+        * Serialize the parameters into origcred
+        */
+       xdrmem_create(&xdrs, mymem, MAX_AUTH_BYTES, XDR_ENCODE);
+       if (! xdr_authunix_parms(&xdrs, &aup)) 
+               abort();
+       au->au_origcred.oa_length = len = XDR_GETPOS(&xdrs);
+       au->au_origcred.oa_flavor = AUTH_UNIX;
+#ifdef KERNEL
+       au->au_origcred.oa_base = mem_alloc((size_t)len);
+#else
+       if ((au->au_origcred.oa_base = mem_alloc((size_t)len)) == NULL) {
+               warnx("authunix_create: out of memory");
+               goto cleanup_authunix_create;
+       }
+#endif
+       memmove(au->au_origcred.oa_base, mymem, (size_t)len);
+
+       /*
+        * set auth handle to reflect new cred.
+        */
+       auth->ah_cred = au->au_origcred;
+       marshal_new_auth(auth);
+       return (auth);
+#ifndef KERNEL
+ cleanup_authunix_create:
+       if (auth)
+               mem_free(auth, sizeof(*auth));
+       if (au) {
+               if (au->au_origcred.oa_base)
+                       mem_free(au->au_origcred.oa_base, (u_int)len);
+               mem_free(au, sizeof(*au));
+       }
+       return (NULL);
+#endif
+}
+
+/*
+ * Returns an auth handle with parameters determined by doing lots of
+ * syscalls.
+ */
+AUTH *
+authunix_create_default()
+{
+       int len;
+       char machname[MAXHOSTNAMELEN + 1];
+       uid_t uid;
+       gid_t gid;
+       gid_t gids[NGRPS];
+
+       if (gethostname(machname, sizeof machname) == -1)
+               abort();
+       machname[sizeof(machname) - 1] = 0;
+       uid = geteuid();
+       gid = getegid();
+       if ((len = getgroups(NGRPS, gids)) < 0)
+               abort();
+       /* XXX: interface problem; those should all have been unsigned */
+       return (authunix_create(machname, (int)uid, (int)gid, len,
+           (int *)gids));
+}
+
+/*
+ * authunix operations
+ */
+
+/* ARGSUSED */
+static void
+authunix_nextverf(auth)
+       AUTH *auth;
+{
+       /* no action necessary */
+}
+
+static bool_t
+authunix_marshal(auth, xdrs)
+       AUTH *auth;
+       XDR *xdrs;
+{
+       struct audata *au;
+
+       _DIAGASSERT(auth != NULL);
+       _DIAGASSERT(xdrs != NULL);
+
+       au = AUTH_PRIVATE(auth);
+       return (XDR_PUTBYTES(xdrs, au->au_marshed, au->au_mpos));
+}
+
+static bool_t
+authunix_validate(auth, verf)
+       AUTH *auth;
+       struct opaque_auth *verf;
+{
+       struct audata *au;
+       XDR xdrs;
+
+       _DIAGASSERT(auth != NULL);
+       _DIAGASSERT(verf != NULL);
+
+       if (verf->oa_flavor == AUTH_SHORT) {
+               au = AUTH_PRIVATE(auth);
+               xdrmem_create(&xdrs, verf->oa_base, verf->oa_length,
+                   XDR_DECODE);
+
+               if (au->au_shcred.oa_base != NULL) {
+                       mem_free(au->au_shcred.oa_base,
+                           au->au_shcred.oa_length);
+                       au->au_shcred.oa_base = NULL;
+               }
+               if (xdr_opaque_auth(&xdrs, &au->au_shcred)) {
+                       auth->ah_cred = au->au_shcred;
+               } else {
+                       xdrs.x_op = XDR_FREE;
+                       (void)xdr_opaque_auth(&xdrs, &au->au_shcred);
+                       au->au_shcred.oa_base = NULL;
+                       auth->ah_cred = au->au_origcred;
+               }
+               marshal_new_auth(auth);
+       }
+       return (TRUE);
+}
+
+static bool_t
+authunix_refresh(auth)
+       AUTH *auth;
+{
+       struct audata *au = AUTH_PRIVATE(auth);
+       struct authunix_parms aup;
+       struct timeval now;
+       XDR xdrs;
+       int stat;
+
+       _DIAGASSERT(auth != NULL);
+
+       if (auth->ah_cred.oa_base == au->au_origcred.oa_base) {
+               /* there is no hope.  Punt */
+               return (FALSE);
+       }
+       au->au_shfaults++;
+
+       /* first deserialize the creds back into a struct authunix_parms */
+       aup.aup_machname = NULL;
+       aup.aup_gids = NULL;
+       xdrmem_create(&xdrs, au->au_origcred.oa_base,
+           au->au_origcred.oa_length, XDR_DECODE);
+       stat = xdr_authunix_parms(&xdrs, &aup);
+       if (! stat) 
+               goto done;
+
+       /* update the time and serialize in place */
+       (void)gettimeofday(&now, NULL);
+       aup.aup_time = (u_long)now.tv_sec;      /* XXX: truncate on 32 bit */
+       xdrs.x_op = XDR_ENCODE;
+       XDR_SETPOS(&xdrs, 0);
+       stat = xdr_authunix_parms(&xdrs, &aup);
+       if (! stat)
+               goto done;
+       auth->ah_cred = au->au_origcred;
+       marshal_new_auth(auth);
+done:
+       /* free the struct authunix_parms created by deserializing */
+       xdrs.x_op = XDR_FREE;
+       (void)xdr_authunix_parms(&xdrs, &aup);
+       XDR_DESTROY(&xdrs);
+       return (stat);
+}
+
+static void
+authunix_destroy(auth)
+       AUTH *auth;
+{
+       struct audata *au;
+
+       _DIAGASSERT(auth != NULL);
+
+       au = AUTH_PRIVATE(auth);
+       mem_free(au->au_origcred.oa_base, au->au_origcred.oa_length);
+
+       if (au->au_shcred.oa_base != NULL)
+               mem_free(au->au_shcred.oa_base, au->au_shcred.oa_length);
+
+       mem_free(auth->ah_private, sizeof(struct audata));
+
+       if (auth->ah_verf.oa_base != NULL)
+               mem_free(auth->ah_verf.oa_base, auth->ah_verf.oa_length);
+
+       mem_free(auth, sizeof(*auth));
+}
+
+/*
+ * Marshals (pre-serializes) an auth struct.
+ * sets private data, au_marshed and au_mpos
+ */
+static void
+marshal_new_auth(auth)
+       AUTH *auth;
+{
+       XDR     xdr_stream;
+       XDR     *xdrs = &xdr_stream;
+       struct audata *au;
+
+       _DIAGASSERT(auth != NULL);
+
+       au = AUTH_PRIVATE(auth);
+       xdrmem_create(xdrs, au->au_marshed, MAX_AUTH_BYTES, XDR_ENCODE);
+       if ((! xdr_opaque_auth(xdrs, &(auth->ah_cred))) ||
+           (! xdr_opaque_auth(xdrs, &(auth->ah_verf))))
+               warnx("auth_none.c - Fatal marshalling problem");
+       else
+               au->au_mpos = XDR_GETPOS(xdrs);
+       XDR_DESTROY(xdrs);
+}
+
+static const struct auth_ops *
+authunix_ops()
+{
+       static struct auth_ops ops;
+#ifdef _REENTRANT
+       extern mutex_t ops_lock;
+#endif
+
+       /* VARIABLES PROTECTED BY ops_lock: ops */
+
+       mutex_lock(&ops_lock);
+       if (ops.ah_nextverf == NULL) {
+               ops.ah_nextverf = authunix_nextverf;
+               ops.ah_marshal = authunix_marshal;
+               ops.ah_validate = authunix_validate;
+               ops.ah_refresh = authunix_refresh;
+               ops.ah_destroy = authunix_destroy;
+       }
+       mutex_unlock(&ops_lock);
+       return (&ops);
+}
diff --git a/lib/nbsd_libc/rpc/authunix_prot.c b/lib/nbsd_libc/rpc/authunix_prot.c
new file mode 100644 (file)
index 0000000..b90e313
--- /dev/null
@@ -0,0 +1,83 @@
+/*     $NetBSD: authunix_prot.c,v 1.13 2006/05/11 17:11:57 mrg Exp $   */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)authunix_prot.c 1.15 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)authunix_prot.c     2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: authunix_prot.c,v 1.13 2006/05/11 17:11:57 mrg Exp $");
+#endif
+#endif
+
+/*
+ * authunix_prot.c
+ * XDR for UNIX style authentication parameters for RPC
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+
+#include <assert.h>
+
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+#include <rpc/auth.h>
+#include <rpc/auth_unix.h>
+
+#ifdef __weak_alias
+__weak_alias(xdr_authunix_parms,_xdr_authunix_parms)
+#endif
+
+/*
+ * XDR for unix authentication parameters.
+ */
+bool_t
+xdr_authunix_parms(xdrs, p)
+       XDR *xdrs;
+       struct authunix_parms *p;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(p != NULL);
+
+       if (xdr_u_long(xdrs, &(p->aup_time))
+           && xdr_string(xdrs, &(p->aup_machname), MAX_MACHINE_NAME)
+           && xdr_int(xdrs, &(p->aup_uid))
+           && xdr_int(xdrs, &(p->aup_gid))
+           && xdr_array(xdrs, (char **)(void *)&(p->aup_gids),
+                   &(p->aup_len), NGRPS, sizeof(int), (xdrproc_t)xdr_int) ) {
+               return (TRUE);
+       }
+       return (FALSE);
+}
diff --git a/lib/nbsd_libc/rpc/bindresvport.3 b/lib/nbsd_libc/rpc/bindresvport.3
new file mode 100644 (file)
index 0000000..ddc8530
--- /dev/null
@@ -0,0 +1,106 @@
+.\"    @(#)bindresvport.3n     2.2 88/08/02 4.0 RPCSRC; from 1.7 88/03/14 SMI
+.\"    $NetBSD: bindresvport.3,v 1.13 2007/01/27 07:58:47 cbiere Exp $
+.\"
+.Dd January 27, 2007
+.Dt BINDRESVPORT 3
+.Os
+.Sh NAME
+.Nm bindresvport ,
+.Nm bindresvport_sa
+.Nd bind a socket to a reserved privileged IP port
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In rpc/rpc.h
+.Ft int
+.Fn bindresvport "int sd" "struct sockaddr_in *sin"
+.Ft int
+.Fn bindresvport_sa "int sd" "struct sockaddr *sa"
+.Sh DESCRIPTION
+.Fn bindresvport
+and
+.Fn bindresvport_sa
+are used to bind a socket descriptor to a reserved privileged
+.Tn IP
+port, that is, a
+port number in the range 0-1023.
+The routine returns 0 if it is successful,
+otherwise -1 is returned and
+.Va errno
+set to reflect the cause of the error.
+.Pp
+If
+.Fa sin
+is a pointer to a
+.Ft "struct sockaddr_in"
+then the appropriate fields in the structure should be defined.
+Note that
+.Fa sin-\*[Gt]sin_family
+must be initialized to the address family of the socket, passed by
+.Fa sd .
+If
+.Fa sin-\*[Gt]sin_port
+is
+.Sq 0
+then a port (in the range 600-1023) will be
+chosen, and if
+.Xr bind 2
+is successful, the
+.Fa sin-\*[Gt]sin_port
+will be updated to contain the allocated port.
+.Pp
+If
+.Fa sin
+is the
+.Dv NULL
+pointer,
+a port will be allocated (as above).
+However, there is no way for
+.Fn bindresvport
+to return the allocated port in this case.
+.Xr getsockname 2
+can be used to determine the assigned port.
+.Pp
+Only root can bind to a privileged port; this call will fail for any
+other users.
+.Pp
+Function prototype of
+.Fn bindresvport
+is biased to
+.Dv AF_INET
+socket.
+.Fn bindresvport_sa
+acts exactly the same, with more neutral function prototype.
+Note that both functions behave exactly the same, and
+both support
+.Dv AF_INET6
+sockets as well as
+.Dv AF_INET
+sockets.
+.Sh RETURN VALUES
+If the bind is successful, a 0 value is returned.
+A return value of -1 indicates an error, which is
+further specified in the global
+.Va errno .
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EPFNOSUPPORT
+If second argument was supplied,
+and address family did not match between arguments.
+.El
+.Pp
+.Fn bindresvport
+may also fail and set
+.Va errno
+for any of the errors specified for the calls
+.Xr bind 2 ,
+.Xr getsockopt 2 ,
+or
+.Xr setsockopt 2 .
+.Sh SEE ALSO
+.Xr bind 2 ,
+.Xr getsockname 2 ,
+.Xr getsockopt 2 ,
+.Xr setsockopt 2 ,
+.Xr ip 4
diff --git a/lib/nbsd_libc/rpc/bindresvport.c b/lib/nbsd_libc/rpc/bindresvport.c
new file mode 100644 (file)
index 0000000..1c8dc3e
--- /dev/null
@@ -0,0 +1,164 @@
+/*     $NetBSD: bindresvport.c,v 1.21 2003/01/18 11:29:03 thorpej Exp $        */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)bindresvport.c 1.8 88/02/08 SMI";
+static char *sccsid = "@(#)bindresvport.c      2.2 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: bindresvport.c,v 1.21 2003/01/18 11:29:03 thorpej Exp $");
+#endif
+#endif
+
+/*
+ * Copyright (c) 1987 by Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <netinet/in.h>
+
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <rpc/rpc.h>
+
+#ifdef __weak_alias
+__weak_alias(bindresvport,_bindresvport)
+__weak_alias(bindresvport_sa,_bindresvport_sa)
+#endif
+
+/*
+ * Bind a socket to a privileged IP port
+ */
+int
+bindresvport(sd, brsin)
+       int sd;
+       struct sockaddr_in *brsin;
+{
+       return bindresvport_sa(sd, (struct sockaddr *)(void *)brsin);
+}
+
+/*
+ * Bind a socket to a privileged IP port
+ */
+int
+bindresvport_sa(sd, sa)
+       int sd;
+       struct sockaddr *sa;
+{
+       int error, old;
+       struct sockaddr_storage myaddr;
+       struct sockaddr_in *brsin;
+#ifdef INET6
+       struct sockaddr_in6 *brsin6;
+#endif
+       int proto, portrange, portlow;
+       u_int16_t *portp;
+       socklen_t salen;
+       int af;
+
+       if (sa == NULL) {
+               salen = sizeof(myaddr);
+               sa = (struct sockaddr *)(void *)&myaddr;
+
+               if (getsockname(sd, sa, &salen) == -1)
+                       return -1;      /* errno is correctly set */
+
+               af = sa->sa_family;
+               memset(sa, 0, salen);
+       } else
+               af = sa->sa_family;
+
+       switch (af) {
+       case AF_INET:
+               proto = IPPROTO_IP;
+               portrange = IP_PORTRANGE;
+               portlow = IP_PORTRANGE_LOW;
+               brsin = (struct sockaddr_in *)(void *)sa;
+               salen = sizeof(struct sockaddr_in);
+               portp = &brsin->sin_port;
+               break;
+#ifdef INET6
+       case AF_INET6:
+               proto = IPPROTO_IPV6;
+               portrange = IPV6_PORTRANGE;
+               portlow = IPV6_PORTRANGE_LOW;
+               brsin6 = (struct sockaddr_in6 *)(void *)sa;
+               salen = sizeof(struct sockaddr_in6);
+               portp = &brsin6->sin6_port;
+               break;
+#endif
+       default:
+               errno = EPFNOSUPPORT;
+               return (-1);
+       }
+       sa->sa_family = af;
+       sa->sa_len = salen;
+
+       if (*portp == 0) {
+               socklen_t oldlen = sizeof(old);
+
+               error = getsockopt(sd, proto, portrange, &old, &oldlen);
+               if (error < 0)
+                       return (error);
+               error = setsockopt(sd, proto, portrange, &portlow,
+                   sizeof(portlow));
+               if (error < 0)
+                       return (error);
+       }
+
+       error = bind(sd, sa, salen);
+
+       if (*portp == 0) {
+               int saved_errno = errno;
+
+               if (error < 0) {
+                       if (setsockopt(sd, proto, portrange, &old,
+                           sizeof(old)) < 0)
+                               errno = saved_errno;
+                       return (error);
+               }
+
+               if (sa != (struct sockaddr *)(void *)&myaddr) {
+                       /* What did the kernel assign? */
+                       if (getsockname(sd, sa, &salen) < 0)
+                               errno = saved_errno;
+                       return (error);
+               }
+       }
+       return (error);
+}
diff --git a/lib/nbsd_libc/rpc/clnt_bcast.c b/lib/nbsd_libc/rpc/clnt_bcast.c
new file mode 100644 (file)
index 0000000..a70f411
--- /dev/null
@@ -0,0 +1,686 @@
+/*     $NetBSD: clnt_bcast.c,v 1.22 2010/03/07 23:49:14 dholland Exp $ */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc. 
+ */
+
+/* #ident      "@(#)clnt_bcast.c       1.18    94/05/03 SMI" */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)clnt_bcast.c 1.15 89/04/21 Copyr 1988 Sun Micro";
+#else
+__RCSID("$NetBSD: clnt_bcast.c,v 1.22 2010/03/07 23:49:14 dholland Exp $");
+#endif
+#endif
+
+/*
+ * clnt_bcast.c
+ * Client interface to broadcast service.
+ *
+ * Copyright (C) 1988, Sun Microsystems, Inc.
+ *
+ * The following is kludged-up support for simple rpc broadcasts.
+ * Someday a large, complicated system will replace these routines.
+ */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/queue.h>
+#include <net/if.h>
+#include <netinet/in.h>
+#include <ifaddrs.h>
+#include <sys/poll.h>
+#include <rpc/rpc.h>
+#ifdef PORTMAP
+#include <rpc/pmap_prot.h>
+#include <rpc/pmap_clnt.h>
+#include <rpc/pmap_rmt.h>
+#endif
+#include <rpc/nettype.h>
+#include <arpa/inet.h>
+#ifdef RPC_DEBUG
+#include <stdio.h>
+#endif
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <netdb.h>
+#include <err.h>
+#include <string.h>
+
+#include "rpc_internal.h"
+
+#define        MAXBCAST 20     /* Max no of broadcasting transports */
+#define        INITTIME 4000   /* Time to wait initially */
+#define        WAITTIME 8000   /* Maximum time to wait */
+
+/*
+ * If nettype is NULL, it broadcasts on all the available
+ * datagram_n transports. May potentially lead to broadacst storms
+ * and hence should be used with caution, care and courage.
+ *
+ * The current parameter xdr packet size is limited by the max tsdu
+ * size of the transport. If the max tsdu size of any transport is
+ * smaller than the parameter xdr packet, then broadcast is not
+ * sent on that transport.
+ *
+ * Also, the packet size should be less the packet size of
+ * the data link layer (for ethernet it is 1400 bytes).  There is
+ * no easy way to find out the max size of the data link layer and
+ * we are assuming that the args would be smaller than that.
+ *
+ * The result size has to be smaller than the transport tsdu size.
+ *
+ * If PORTMAP has been defined, we send two packets for UDP, one for
+ * rpcbind and one for portmap. For those machines which support
+ * both rpcbind and portmap, it will cause them to reply twice, and
+ * also here it will get two responses ... inefficient and clumsy.
+ */
+
+#ifdef __weak_alias
+__weak_alias(rpc_broadcast_exp,_rpc_broadcast_exp)
+__weak_alias(rpc_broadcast,_rpc_broadcast)
+#endif
+
+struct broadif {
+       int index;
+       struct sockaddr_storage broadaddr;
+       TAILQ_ENTRY(broadif) link;
+};
+
+typedef TAILQ_HEAD(, broadif) broadlist_t;
+
+int __rpc_getbroadifs __P((int, int, int, broadlist_t *));
+void __rpc_freebroadifs __P((broadlist_t *));
+int __rpc_broadenable __P((int, int, struct broadif *));
+
+int __rpc_lowvers = 0;
+
+int
+__rpc_getbroadifs(int af, int proto, int socktype, broadlist_t *list)
+{
+       int count = 0;
+       struct broadif *bip;
+       struct ifaddrs *ifap, *ifp;
+#ifdef INET6
+       struct sockaddr_in6 *sin6;
+#endif
+       struct sockaddr_in *gbsin;
+       struct addrinfo hints, *res;
+
+       _DIAGASSERT(list != NULL);
+
+       if (getifaddrs(&ifp) < 0)
+               return 0;
+
+       memset(&hints, 0, sizeof hints);
+
+       hints.ai_family = af;
+       hints.ai_protocol = proto;
+       hints.ai_socktype = socktype;
+
+       if (getaddrinfo(NULL, "sunrpc", &hints, &res) != 0) {
+               freeifaddrs(ifp);
+               return 0;
+       }
+
+       for (ifap = ifp; ifap != NULL; ifap = ifap->ifa_next) {
+               if (ifap->ifa_addr->sa_family != af ||
+                   !(ifap->ifa_flags & IFF_UP))
+                       continue;
+               bip = malloc(sizeof(*bip));
+               if (bip == NULL)
+                       break;
+               bip->index = if_nametoindex(ifap->ifa_name);
+               if (
+#ifdef INET6
+                   af != AF_INET6 &&
+#endif
+                   (ifap->ifa_flags & IFF_BROADCAST) &&
+                   ifap->ifa_broadaddr) {
+                       memcpy(&bip->broadaddr, ifap->ifa_broadaddr,
+                           (size_t)ifap->ifa_broadaddr->sa_len);
+                       gbsin = (struct sockaddr_in *)(void *)&bip->broadaddr;
+                       gbsin->sin_port =
+                           ((struct sockaddr_in *)
+                           (void *)res->ai_addr)->sin_port;
+               } else
+#ifdef INET6
+               if (af == AF_INET6 && (ifap->ifa_flags & IFF_MULTICAST)) {
+                       sin6 = (struct sockaddr_in6 *)(void *)&bip->broadaddr;
+                       inet_pton(af, RPCB_MULTICAST_ADDR, &sin6->sin6_addr);
+                       sin6->sin6_family = af;
+                       sin6->sin6_len = sizeof *sin6;
+                       sin6->sin6_port =
+                           ((struct sockaddr_in6 *)
+                           (void *)res->ai_addr)->sin6_port;
+                       sin6->sin6_scope_id = bip->index;
+               } else
+#endif
+               {
+                       free(bip);
+                       continue;
+               }
+               TAILQ_INSERT_TAIL(list, bip, link);
+               count++;
+       }
+       freeifaddrs(ifp);
+       freeaddrinfo(res);
+
+       return count;
+}
+
+void
+__rpc_freebroadifs(broadlist_t *list)
+{
+       struct broadif *bip, *next;
+
+       _DIAGASSERT(list != NULL);
+
+       bip = TAILQ_FIRST(list);
+
+       while (bip != NULL) {
+               next = TAILQ_NEXT(bip, link);
+               free(bip);
+               bip = next;
+       }
+}
+
+int
+/*ARGSUSED*/
+__rpc_broadenable(int af, int s, struct broadif *bip)
+{
+       int o = 1;
+
+#if 0
+       _DIAGASSERT(bip != NULL);
+
+       if (af == AF_INET6) {
+               fprintf(stderr, "set v6 multicast if to %d\n", bip->index);
+               if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_IF, &bip->index,
+                   sizeof bip->index) < 0)
+                       return -1;
+       } else
+#endif
+               if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &o, sizeof o) < 0)
+                       return -1;
+
+       return 0;
+}
+
+
+enum clnt_stat
+rpc_broadcast_exp(prog, vers, proc, xargs, argsp, xresults, resultsp,
+       eachresult, inittime, waittime, nettype)
+       rpcprog_t       prog;           /* program number */
+       rpcvers_t       vers;           /* version number */
+       rpcproc_t       proc;           /* procedure number */
+       xdrproc_t       xargs;          /* xdr routine for args */
+       const char *    argsp;          /* pointer to args */
+       xdrproc_t       xresults;       /* xdr routine for results */
+       caddr_t         resultsp;       /* pointer to results */
+       resultproc_t    eachresult;     /* call with each result obtained */
+       int             inittime;       /* how long to wait initially */
+       int             waittime;       /* maximum time to wait */
+       const char              *nettype;       /* transport type */
+{
+       enum clnt_stat  stat = RPC_SUCCESS; /* Return status */
+       XDR             xdr_stream; /* XDR stream */
+       XDR             *xdrs = &xdr_stream;
+       struct rpc_msg  msg;    /* RPC message */
+       char            *outbuf = NULL; /* Broadcast msg buffer */
+       char            *inbuf = NULL; /* Reply buf */
+       ssize_t         inlen;
+       u_int           maxbufsize = 0;
+       AUTH            *sys_auth = authunix_create_default();
+       size_t          i;
+       void            *handle;
+       char            uaddress[1024]; /* A self imposed limit */
+       char            *uaddrp = uaddress;
+       int             pmap_reply_flag; /* reply recvd from PORTMAP */
+       /* An array of all the suitable broadcast transports */
+       struct {
+               int fd;         /* File descriptor */
+               int af;
+               int proto;
+               struct netconfig *nconf; /* Netconfig structure */
+               u_int asize;    /* Size of the addr buf */
+               u_int dsize;    /* Size of the data buf */
+               struct sockaddr_storage raddr; /* Remote address */
+               broadlist_t nal;
+       } fdlist[MAXBCAST];
+       struct pollfd pfd[MAXBCAST];
+       size_t fdlistno = 0;
+       struct r_rpcb_rmtcallargs barg; /* Remote arguments */
+       struct r_rpcb_rmtcallres bres; /* Remote results */
+       size_t outlen;
+       struct netconfig *nconf;
+       int msec;
+       int pollretval;
+       int fds_found;
+       struct timespec ts;
+
+#ifdef PORTMAP
+       size_t outlen_pmap = 0;
+       u_long port;            /* Remote port number */
+       int pmap_flag = 0;      /* UDP exists ? */
+       char *outbuf_pmap = NULL;
+       struct rmtcallargs barg_pmap;   /* Remote arguments */
+       struct rmtcallres bres_pmap; /* Remote results */
+       u_int udpbufsz = 0;
+#endif                         /* PORTMAP */
+
+       if (sys_auth == NULL) {
+               return (RPC_SYSTEMERROR);
+       }
+       /*
+        * initialization: create a fd, a broadcast address, and send the
+        * request on the broadcast transport.
+        * Listen on all of them and on replies, call the user supplied
+        * function.
+        */
+
+       if (nettype == NULL)
+               nettype = "datagram_n";
+       if ((handle = __rpc_setconf(nettype)) == NULL) {
+               AUTH_DESTROY(sys_auth);
+               return (RPC_UNKNOWNPROTO);
+       }
+       while ((nconf = __rpc_getconf(handle)) != NULL) {
+               int fd;
+               struct __rpc_sockinfo si;
+
+               if (nconf->nc_semantics != NC_TPI_CLTS)
+                       continue;
+               if (fdlistno >= MAXBCAST)
+                       break;  /* No more slots available */
+               if (!__rpc_nconf2sockinfo(nconf, &si))
+                       continue;
+
+               TAILQ_INIT(&fdlist[fdlistno].nal);
+               if (__rpc_getbroadifs(si.si_af, si.si_proto, si.si_socktype, 
+                   &fdlist[fdlistno].nal) == 0)
+                       continue;
+
+               fd = socket(si.si_af, si.si_socktype, si.si_proto);
+               if (fd < 0) {
+                       stat = RPC_CANTSEND;
+                       continue;
+               }
+               fdlist[fdlistno].af = si.si_af;
+               fdlist[fdlistno].proto = si.si_proto;
+               fdlist[fdlistno].fd = fd;
+               fdlist[fdlistno].nconf = nconf;
+               fdlist[fdlistno].asize = __rpc_get_a_size(si.si_af);
+               pfd[fdlistno].events = POLLIN | POLLPRI |
+                       POLLRDNORM | POLLRDBAND;
+               pfd[fdlistno].fd = fdlist[fdlistno].fd = fd;
+               fdlist[fdlistno].dsize = __rpc_get_t_size(si.si_af, si.si_proto,
+                                                         0);
+
+               if (maxbufsize <= fdlist[fdlistno].dsize)
+                       maxbufsize = fdlist[fdlistno].dsize;
+                       
+#ifdef PORTMAP
+               if (si.si_af == AF_INET && si.si_proto == IPPROTO_UDP) {
+                       udpbufsz = fdlist[fdlistno].dsize;
+                       if ((outbuf_pmap = malloc(udpbufsz)) == NULL) {
+                               close(fd);
+                               stat = RPC_SYSTEMERROR;
+                               goto done_broad;
+                       }
+                       pmap_flag = 1;
+               }
+#endif
+               fdlistno++;
+       }
+
+       if (fdlistno == 0) {
+               if (stat == RPC_SUCCESS)
+                       stat = RPC_UNKNOWNPROTO;
+               goto done_broad;
+       }
+       if (maxbufsize == 0) {
+               if (stat == RPC_SUCCESS)
+                       stat = RPC_CANTSEND;
+               goto done_broad;
+       }
+       inbuf = malloc(maxbufsize);
+       outbuf = malloc(maxbufsize);
+       if ((inbuf == NULL) || (outbuf == NULL)) {
+               stat = RPC_SYSTEMERROR;
+               goto done_broad;
+       }
+
+       /* Serialize all the arguments which have to be sent */
+       msg.rm_xid = __RPC_GETXID();
+       msg.rm_direction = CALL;
+       msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
+       msg.rm_call.cb_prog = RPCBPROG;
+       msg.rm_call.cb_vers = RPCBVERS;
+       msg.rm_call.cb_proc = RPCBPROC_CALLIT;
+       barg.prog = prog;
+       barg.vers = vers;
+       barg.proc = proc;
+       barg.args.args_val = argsp;
+       barg.xdr_args = xargs;
+       bres.addr = uaddrp;
+       bres.results.results_val = resultsp;
+       bres.xdr_res = xresults;
+       msg.rm_call.cb_cred = sys_auth->ah_cred;
+       msg.rm_call.cb_verf = sys_auth->ah_verf;
+       xdrmem_create(xdrs, outbuf, maxbufsize, XDR_ENCODE);
+       if ((!xdr_callmsg(xdrs, &msg)) ||
+           (!xdr_rpcb_rmtcallargs(xdrs,
+           (struct rpcb_rmtcallargs *)(void *)&barg))) {
+               stat = RPC_CANTENCODEARGS;
+               goto done_broad;
+       }
+       outlen = xdr_getpos(xdrs);
+       xdr_destroy(xdrs);
+
+#ifdef PORTMAP
+       /* Prepare the packet for version 2 PORTMAP */
+       if (pmap_flag) {
+               msg.rm_xid++;   /* One way to distinguish */
+               msg.rm_call.cb_prog = PMAPPROG;
+               msg.rm_call.cb_vers = PMAPVERS;
+               msg.rm_call.cb_proc = PMAPPROC_CALLIT;
+               barg_pmap.prog = prog;
+               barg_pmap.vers = vers;
+               barg_pmap.proc = proc;
+               barg_pmap.args_ptr = argsp;
+               barg_pmap.xdr_args = xargs;
+               bres_pmap.port_ptr = &port;
+               bres_pmap.xdr_results = xresults;
+               bres_pmap.results_ptr = resultsp;
+               xdrmem_create(xdrs, outbuf_pmap, udpbufsz, XDR_ENCODE);
+               if ((! xdr_callmsg(xdrs, &msg)) ||
+                   (! xdr_rmtcall_args(xdrs, &barg_pmap))) {
+                       stat = RPC_CANTENCODEARGS;
+                       goto done_broad;
+               }
+               outlen_pmap = xdr_getpos(xdrs);
+               xdr_destroy(xdrs);
+       }
+#endif                         /* PORTMAP */
+
+       /*
+        * Basic loop: broadcast the packets to transports which
+        * support data packets of size such that one can encode
+        * all the arguments.
+        * Wait a while for response(s).
+        * The response timeout grows larger per iteration.
+        */
+       for (msec = inittime; msec <= waittime; msec += msec) {
+               struct broadif *bip;
+
+               /* Broadcast all the packets now */
+               for (i = 0; i < fdlistno; i++) {
+                       if (fdlist[i].dsize < outlen) {
+                               stat = RPC_CANTSEND;
+                               continue;
+                       }
+                       for (bip = TAILQ_FIRST(&fdlist[i].nal); bip != NULL;
+                            bip = TAILQ_NEXT(bip, link)) {
+                               void *addr;
+
+                               addr = &bip->broadaddr;
+
+                               __rpc_broadenable(fdlist[i].af, fdlist[i].fd,
+                                   bip);
+
+                               /*
+                                * Only use version 3 if lowvers is not set
+                                */
+
+                               if (!__rpc_lowvers)
+                                       if ((size_t)sendto(fdlist[i].fd, outbuf,
+                                           outlen, 0, (struct sockaddr*)addr,
+                                           (size_t)fdlist[i].asize) !=
+                                           outlen) {
+                                               warn("clnt_bcast: cannot send"
+                                                     " broadcast packet");
+                                               stat = RPC_CANTSEND;
+                                               continue;
+                                       }
+#ifdef RPC_DEBUG
+                               if (!__rpc_lowvers)
+                                       fprintf(stderr, "Broadcast packet sent "
+                                               "for %s\n",
+                                                fdlist[i].nconf->nc_netid);
+#endif
+#ifdef PORTMAP
+                               /*
+                                * Send the version 2 packet also
+                                * for UDP/IP
+                                */
+                               if (pmap_flag &&
+                                   fdlist[i].proto == IPPROTO_UDP) {
+                                       if ((size_t)sendto(fdlist[i].fd,
+                                           outbuf_pmap, outlen_pmap, 0, addr,
+                                           (size_t)fdlist[i].asize) !=
+                                               outlen_pmap) {
+                                               warnx("clnt_bcast: "
+                                                   "Cannot send "
+                                                   "broadcast packet");
+                                               stat = RPC_CANTSEND;
+                                               continue;
+                                       }
+                               }
+#ifdef RPC_DEBUG
+                               fprintf(stderr, "PMAP Broadcast packet "
+                                       "sent for %s\n",
+                                       fdlist[i].nconf->nc_netid);
+#endif
+#endif                         /* PORTMAP */
+                       }
+                       /* End for sending all packets on this transport */
+               }       /* End for sending on all transports */
+
+               if (eachresult == NULL) {
+                       stat = RPC_SUCCESS;
+                       goto done_broad;
+               }
+
+               /*
+                * Get all the replies from these broadcast requests
+                */
+       recv_again:
+               ts.tv_sec = msec / 1000;
+               ts.tv_nsec = (msec % 1000) * 1000000;
+
+               switch (pollretval = pollts(pfd, fdlistno, &ts, NULL)) {
+               case 0:         /* timed out */
+                       stat = RPC_TIMEDOUT;
+                       continue;
+               case -1:        /* some kind of error - we ignore it */
+                       goto recv_again;
+               }               /* end of poll results switch */
+
+               for (i = fds_found = 0;
+                    i < fdlistno && fds_found < pollretval; i++) {
+                       bool_t done = FALSE;
+
+                       if (pfd[i].revents == 0)
+                               continue;
+                       else if (pfd[i].revents & POLLNVAL) {
+                               /*
+                                * Something bad has happened to this descri-
+                                * ptor. We can cause pollts() to ignore
+                                * it simply by using a negative fd.  We do that
+                                * rather than compacting the pfd[] and fdlist[]
+                                * arrays.
+                                */
+                               pfd[i].fd = -1;
+                               fds_found++;
+                               continue;
+                       } else
+                               fds_found++;
+#ifdef RPC_DEBUG
+                       fprintf(stderr, "response for %s\n",
+                               fdlist[i].nconf->nc_netid);
+#endif
+               try_again:
+                       inlen = recvfrom(fdlist[i].fd, inbuf, fdlist[i].dsize,
+                           0, (struct sockaddr *)(void *)&fdlist[i].raddr,
+                           &fdlist[i].asize);
+                       if (inlen < 0) {
+                               if (errno == EINTR)
+                                       goto try_again;
+                               warnx("clnt_bcast: Cannot receive reply to "
+                                       "broadcast");
+                               stat = RPC_CANTRECV;
+                               continue;
+                       }
+                       if (inlen < (ssize_t)sizeof(u_int32_t))
+                               continue; /* Drop that and go ahead */
+                       /*
+                        * see if reply transaction id matches sent id.
+                        * If so, decode the results. If return id is xid + 1
+                        * it was a PORTMAP reply
+                        */
+                       if (*((u_int32_t *)(void *)(inbuf)) ==
+                           *((u_int32_t *)(void *)(outbuf))) {
+                               pmap_reply_flag = 0;
+                               msg.acpted_rply.ar_verf = _null_auth;
+                               msg.acpted_rply.ar_results.where =
+                                       (caddr_t)(void *)&bres;
+                               msg.acpted_rply.ar_results.proc =
+                                       (xdrproc_t)xdr_rpcb_rmtcallres;
+#ifdef PORTMAP
+                       } else if (pmap_flag &&
+                               *((u_int32_t *)(void *)(inbuf)) ==
+                               *((u_int32_t *)(void *)(outbuf_pmap))) {
+                               pmap_reply_flag = 1;
+                               msg.acpted_rply.ar_verf = _null_auth;
+                               msg.acpted_rply.ar_results.where =
+                                       (caddr_t)(void *)&bres_pmap;
+                               msg.acpted_rply.ar_results.proc =
+                                       (xdrproc_t)xdr_rmtcallres;
+#endif                         /* PORTMAP */
+                       } else
+                               continue;
+                       xdrmem_create(xdrs, inbuf, (u_int)inlen, XDR_DECODE);
+                       if (xdr_replymsg(xdrs, &msg)) {
+                               if ((msg.rm_reply.rp_stat == MSG_ACCEPTED) &&
+                                   (msg.acpted_rply.ar_stat == SUCCESS)) {
+                                       struct netbuf taddr, *np;
+                                       struct sockaddr_in *bsin;
+
+#ifdef PORTMAP
+                                       if (pmap_flag && pmap_reply_flag) {
+                                               bsin = (struct sockaddr_in *)
+                                                   (void *)&fdlist[i].raddr;
+                                               bsin->sin_port =
+                                                   htons((u_short)port);
+                                               taddr.len = taddr.maxlen = 
+                                                   fdlist[i].raddr.ss_len;
+                                               taddr.buf = &fdlist[i].raddr;
+                                               done = (*eachresult)(resultsp,
+                                                   &taddr, fdlist[i].nconf);
+                                       } else {
+#endif
+#ifdef RPC_DEBUG
+                                               fprintf(stderr, "uaddr %s\n",
+                                                   uaddrp);
+#endif
+                                               np = uaddr2taddr(
+                                                   fdlist[i].nconf, uaddrp);
+                                               done = (*eachresult)(resultsp,
+                                                   np, fdlist[i].nconf);
+                                               free(np);
+#ifdef PORTMAP
+                                       }
+#endif
+                               }
+                               /* otherwise, we just ignore the errors ... */
+                       }
+                       /* else some kind of deserialization problem ... */
+
+                       xdrs->x_op = XDR_FREE;
+                       msg.acpted_rply.ar_results.proc = (xdrproc_t) xdr_void;
+                       (void) xdr_replymsg(xdrs, &msg);
+                       (void) (*xresults)(xdrs, resultsp);
+                       XDR_DESTROY(xdrs);
+                       if (done) {
+                               stat = RPC_SUCCESS;
+                               goto done_broad;
+                       } else {
+                               goto recv_again;
+                       }
+               }               /* The recv for loop */
+       }                       /* The giant for loop */
+
+done_broad:
+       if (inbuf)
+               (void) free(inbuf);
+       if (outbuf)
+               (void) free(outbuf);
+#ifdef PORTMAP
+       if (outbuf_pmap)
+               (void) free(outbuf_pmap);
+#endif
+       for (i = 0; i < fdlistno; i++) {
+               (void) close(fdlist[i].fd);
+               __rpc_freebroadifs(&fdlist[i].nal);
+       }
+       AUTH_DESTROY(sys_auth);
+       (void) __rpc_endconf(handle);
+
+       return (stat);
+}
+
+
+enum clnt_stat
+rpc_broadcast(prog, vers, proc, xargs, argsp, xresults, resultsp,
+                       eachresult, nettype)
+       rpcprog_t       prog;           /* program number */
+       rpcvers_t       vers;           /* version number */
+       rpcproc_t       proc;           /* procedure number */
+       xdrproc_t       xargs;          /* xdr routine for args */
+       const char *    argsp;          /* pointer to args */
+       xdrproc_t       xresults;       /* xdr routine for results */
+       caddr_t         resultsp;       /* pointer to results */
+       resultproc_t    eachresult;     /* call with each result obtained */
+       const char              *nettype;       /* transport type */
+{
+       enum clnt_stat  dummy;
+
+       dummy = rpc_broadcast_exp(prog, vers, proc, xargs, argsp,
+               xresults, resultsp, eachresult,
+               INITTIME, WAITTIME, nettype);
+       return (dummy);
+}
diff --git a/lib/nbsd_libc/rpc/clnt_dg.c b/lib/nbsd_libc/rpc/clnt_dg.c
new file mode 100644 (file)
index 0000000..d077878
--- /dev/null
@@ -0,0 +1,769 @@
+/*     $NetBSD: clnt_dg.c,v 1.24 2010/12/08 02:06:38 joerg Exp $       */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc. 
+ */
+
+/* #ident      "@(#)clnt_dg.c  1.23    94/04/22 SMI" */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)clnt_dg.c 1.19 89/03/16 Copyr 1988 Sun Micro";
+#else
+__RCSID("$NetBSD: clnt_dg.c,v 1.24 2010/12/08 02:06:38 joerg Exp $");
+#endif
+#endif
+
+/*
+ * Implements a connectionless client side RPC.
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/poll.h>
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#include <rpc/rpc.h>
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include <err.h>
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(clnt_dg_create,_clnt_dg_create)
+#endif
+
+#define        RPC_MAX_BACKOFF         30 /* seconds */
+
+
+static struct clnt_ops *clnt_dg_ops __P((void));
+static bool_t time_not_ok __P((struct timeval *));
+static enum clnt_stat clnt_dg_call __P((CLIENT *, rpcproc_t, xdrproc_t,
+    const char *, xdrproc_t, caddr_t, struct timeval));
+static void clnt_dg_geterr __P((CLIENT *, struct rpc_err *));
+static bool_t clnt_dg_freeres __P((CLIENT *, xdrproc_t, caddr_t));
+static void clnt_dg_abort __P((CLIENT *));
+static bool_t clnt_dg_control __P((CLIENT *, u_int, char *));
+static void clnt_dg_destroy __P((CLIENT *));
+
+
+
+
+/*
+ *     This machinery implements per-fd locks for MT-safety.  It is not
+ *     sufficient to do per-CLIENT handle locks for MT-safety because a
+ *     user may create more than one CLIENT handle with the same fd behind
+ *     it.  Therfore, we allocate an array of flags (dg_fd_locks), protected
+ *     by the clnt_fd_lock mutex, and an array (dg_cv) of condition variables
+ *     similarly protected.  Dg_fd_lock[fd] == 1 => a call is activte on some
+ *     CLIENT handle created for that fd.
+ *     The current implementation holds locks across the entire RPC and reply,
+ *     including retransmissions.  Yes, this is silly, and as soon as this
+ *     code is proven to work, this should be the first thing fixed.  One step
+ *     at a time.
+ */
+static int     *dg_fd_locks;
+#ifdef _REENTRANT
+#define __rpc_lock_value __isthreaded;
+extern mutex_t clnt_fd_lock;
+static cond_t  *dg_cv;
+#define        release_fd_lock(fd, mask) {             \
+       mutex_lock(&clnt_fd_lock);      \
+       dg_fd_locks[fd] = 0;            \
+       mutex_unlock(&clnt_fd_lock);    \
+       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);     \
+       cond_signal(&dg_cv[fd]);        \
+}
+#else
+#define release_fd_lock(fd,mask)
+#define __rpc_lock_value 0
+#endif
+
+static const char mem_err_clnt_dg[] = "clnt_dg_create: out of memory";
+
+/* VARIABLES PROTECTED BY clnt_fd_lock: dg_fd_locks, dg_cv */
+
+/*
+ * Private data kept per client handle
+ */
+struct cu_data {
+       int                     cu_fd;          /* connections fd */
+       bool_t                  cu_closeit;     /* opened by library */
+       struct sockaddr_storage cu_raddr;       /* remote address */
+       int                     cu_rlen;
+       struct timeval          cu_wait;        /* retransmit interval */
+       struct timeval          cu_total;       /* total time for the call */
+       struct rpc_err          cu_error;
+       XDR                     cu_outxdrs;
+       u_int                   cu_xdrpos;
+       u_int                   cu_sendsz;      /* send size */
+       char                    *cu_outbuf;
+       u_int                   cu_recvsz;      /* recv size */
+       struct pollfd           cu_pfdp;
+       char                    cu_inbuf[1];
+};
+
+/*
+ * Connection less client creation returns with client handle parameters.
+ * Default options are set, which the user can change using clnt_control().
+ * fd should be open and bound.
+ * NB: The rpch->cl_auth is initialized to null authentication.
+ *     Caller may wish to set this something more useful.
+ *
+ * sendsz and recvsz are the maximum allowable packet sizes that can be
+ * sent and received. Normally they are the same, but they can be
+ * changed to improve the program efficiency and buffer allocation.
+ * If they are 0, use the transport default.
+ *
+ * If svcaddr is NULL, returns NULL.
+ */
+CLIENT *
+clnt_dg_create(fd, svcaddr, program, version, sendsz, recvsz)
+       int fd;                         /* open file descriptor */
+       const struct netbuf *svcaddr;   /* servers address */
+       rpcprog_t program;              /* program number */
+       rpcvers_t version;              /* version number */
+       u_int sendsz;                   /* buffer recv size */
+       u_int recvsz;                   /* buffer send size */
+{
+       CLIENT *cl = NULL;              /* client handle */
+       struct cu_data *cu = NULL;      /* private data */
+       struct rpc_msg call_msg;
+#ifdef _REENTRANT
+       sigset_t mask;
+#endif
+       sigset_t newmask;
+       struct __rpc_sockinfo si;
+       int one = 1;
+
+       sigfillset(&newmask);
+       thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
+       mutex_lock(&clnt_fd_lock);
+       if (dg_fd_locks == NULL) {
+#ifdef _REENTRANT
+               size_t cv_allocsz;
+#endif
+               size_t fd_allocsz;
+               int dtbsize = __rpc_dtbsize();
+
+               fd_allocsz = dtbsize * sizeof (int);
+               dg_fd_locks = mem_alloc(fd_allocsz);
+               if (dg_fd_locks == NULL) {
+                       mutex_unlock(&clnt_fd_lock);
+                       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);
+                       goto err1;
+               } else
+                       memset(dg_fd_locks, '\0', fd_allocsz);
+
+#ifdef _REENTRANT
+               cv_allocsz = dtbsize * sizeof (cond_t);
+               dg_cv = mem_alloc(cv_allocsz);
+               if (dg_cv == NULL) {
+                       mem_free(dg_fd_locks, fd_allocsz);
+                       dg_fd_locks = NULL;
+                       mutex_unlock(&clnt_fd_lock);
+                       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);
+                       goto err1;
+               } else {
+                       int i;
+
+                       for (i = 0; i < dtbsize; i++)
+                               cond_init(&dg_cv[i], 0, (void *) 0);
+               }
+#endif
+       }
+
+       mutex_unlock(&clnt_fd_lock);
+       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);
+
+       if (svcaddr == NULL) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNADDR;
+               return (NULL);
+       }
+
+       if (!__rpc_fd2sockinfo(fd, &si)) {
+               rpc_createerr.cf_stat = RPC_TLIERROR;
+               rpc_createerr.cf_error.re_errno = 0;
+               return (NULL);
+       }
+       /*
+        * Find the receive and the send size
+        */
+       sendsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)sendsz);
+       recvsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)recvsz);
+       if ((sendsz == 0) || (recvsz == 0)) {
+               rpc_createerr.cf_stat = RPC_TLIERROR; /* XXX */
+               rpc_createerr.cf_error.re_errno = 0;
+               return (NULL);
+       }
+
+       if ((cl = mem_alloc(sizeof (CLIENT))) == NULL)
+               goto err1;
+       /*
+        * Should be multiple of 4 for XDR.
+        */
+       sendsz = ((sendsz + 3) / 4) * 4;
+       recvsz = ((recvsz + 3) / 4) * 4;
+       cu = malloc(sizeof (*cu) + sendsz + recvsz);
+       if (cu == NULL)
+               goto err1;
+       memset(cu, 0, sizeof(*cu));
+       (void) memcpy(&cu->cu_raddr, svcaddr->buf, (size_t)svcaddr->len);
+       cu->cu_rlen = svcaddr->len;
+       cu->cu_outbuf = &cu->cu_inbuf[recvsz];
+       /* Other values can also be set through clnt_control() */
+       cu->cu_wait.tv_sec = 15;        /* heuristically chosen */
+       cu->cu_wait.tv_usec = 0;
+       cu->cu_total.tv_sec = -1;
+       cu->cu_total.tv_usec = -1;
+       cu->cu_sendsz = sendsz;
+       cu->cu_recvsz = recvsz;
+       call_msg.rm_xid = __RPC_GETXID();
+       call_msg.rm_call.cb_prog = program;
+       call_msg.rm_call.cb_vers = version;
+       xdrmem_create(&(cu->cu_outxdrs), cu->cu_outbuf, sendsz, XDR_ENCODE);
+       if (! xdr_callhdr(&(cu->cu_outxdrs), &call_msg)) {
+               rpc_createerr.cf_stat = RPC_CANTENCODEARGS;  /* XXX */
+               rpc_createerr.cf_error.re_errno = 0;
+               goto err2;
+       }
+       cu->cu_xdrpos = XDR_GETPOS(&(cu->cu_outxdrs));
+
+       /* XXX fvdl - do we still want this? */
+#if 0
+       (void)bindresvport_sa(fd, (struct sockaddr *)svcaddr->buf);
+#endif
+       ioctl(fd, FIONBIO, (char *)(void *)&one);
+
+       /*
+        * By default, closeit is always FALSE. It is users responsibility
+        * to do a close on it, else the user may use clnt_control
+        * to let clnt_destroy do it for him/her.
+        */
+       cu->cu_closeit = FALSE;
+       cu->cu_fd = fd;
+       cu->cu_pfdp.fd = cu->cu_fd;
+       cu->cu_pfdp.events = POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND;
+       cl->cl_ops = clnt_dg_ops();
+       cl->cl_private = (caddr_t)(void *)cu;
+       cl->cl_auth = authnone_create();
+       cl->cl_tp = NULL;
+       cl->cl_netid = NULL;
+       return (cl);
+err1:
+       warnx(mem_err_clnt_dg);
+       rpc_createerr.cf_stat = RPC_SYSTEMERROR;
+       rpc_createerr.cf_error.re_errno = errno;
+err2:
+       if (cl) {
+               mem_free(cl, sizeof (CLIENT));
+               if (cu)
+                       mem_free(cu, sizeof (*cu) + sendsz + recvsz);
+       }
+       return (NULL);
+}
+
+static enum clnt_stat
+clnt_dg_call(cl, proc, xargs, argsp, xresults, resultsp, utimeout)
+       CLIENT  *cl;                    /* client handle */
+       rpcproc_t       proc;           /* procedure number */
+       xdrproc_t       xargs;          /* xdr routine for args */
+       const char *    argsp;          /* pointer to args */
+       xdrproc_t       xresults;       /* xdr routine for results */
+       caddr_t         resultsp;       /* pointer to results */
+       struct timeval  utimeout;       /* seconds to wait before giving up */
+{
+       struct cu_data *cu;
+       XDR *xdrs;
+       size_t outlen;
+       struct rpc_msg reply_msg;
+       XDR reply_xdrs;
+       bool_t ok;
+       int nrefreshes = 2;             /* number of times to refresh cred */
+       struct timeval timeout;
+       struct timeval retransmit_time;
+       struct timeval next_sendtime, starttime, time_waited, tv;
+#ifdef _REENTRANT
+       sigset_t mask, *maskp = &mask;
+#else
+       sigset_t *maskp = NULL;
+#endif
+       sigset_t newmask;
+       ssize_t recvlen = 0;
+       struct timespec ts;
+       int n;
+
+       _DIAGASSERT(cl != NULL);
+
+       cu = (struct cu_data *)cl->cl_private;
+
+       sigfillset(&newmask);
+       thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
+       mutex_lock(&clnt_fd_lock);
+       while (dg_fd_locks[cu->cu_fd])
+               cond_wait(&dg_cv[cu->cu_fd], &clnt_fd_lock);
+       dg_fd_locks[cu->cu_fd] = __rpc_lock_value;
+       mutex_unlock(&clnt_fd_lock);
+       if (cu->cu_total.tv_usec == -1) {
+               timeout = utimeout;     /* use supplied timeout */
+       } else {
+               timeout = cu->cu_total; /* use default timeout */
+       }
+
+       time_waited.tv_sec = 0;
+       time_waited.tv_usec = 0;
+       retransmit_time = next_sendtime = cu->cu_wait;
+       gettimeofday(&starttime, NULL);
+
+call_again:
+       xdrs = &(cu->cu_outxdrs);
+       xdrs->x_op = XDR_ENCODE;
+       XDR_SETPOS(xdrs, cu->cu_xdrpos);
+       /*
+        * the transaction is the first thing in the out buffer
+        */
+       (*(u_int32_t *)(void *)(cu->cu_outbuf))++;
+       if ((! XDR_PUTINT32(xdrs, (int32_t *)&proc)) ||
+           (! AUTH_MARSHALL(cl->cl_auth, xdrs)) ||
+           (! (*xargs)(xdrs, __UNCONST(argsp)))) {
+               cu->cu_error.re_status = RPC_CANTENCODEARGS;
+               goto out;
+       }
+       outlen = (size_t)XDR_GETPOS(xdrs);
+
+send_again:
+       if ((size_t)sendto(cu->cu_fd, cu->cu_outbuf, outlen, 0,
+           (struct sockaddr *)(void *)&cu->cu_raddr, (socklen_t)cu->cu_rlen)
+           != outlen) {
+               cu->cu_error.re_errno = errno;
+               cu->cu_error.re_status = RPC_CANTSEND;
+               goto out;
+       }
+
+       /*
+        * Hack to provide rpc-based message passing
+        */
+       if (timeout.tv_sec == 0 && timeout.tv_usec == 0) {
+               cu->cu_error.re_status = RPC_TIMEDOUT;
+               goto out;
+       }
+       /*
+        * sub-optimal code appears here because we have
+        * some clock time to spare while the packets are in flight.
+        * (We assume that this is actually only executed once.)
+        */
+       reply_msg.acpted_rply.ar_verf = _null_auth;
+       reply_msg.acpted_rply.ar_results.where = resultsp;
+       reply_msg.acpted_rply.ar_results.proc = xresults;
+
+
+       for (;;) {
+               /* Decide how long to wait. */
+               if (timercmp(&next_sendtime, &timeout, <))
+                       timersub(&next_sendtime, &time_waited, &tv);
+               else
+                       timersub(&timeout, &time_waited, &tv);
+               if (tv.tv_sec < 0 || tv.tv_usec < 0)
+                       tv.tv_sec = tv.tv_usec = 0;
+               TIMEVAL_TO_TIMESPEC(&tv, &ts);
+
+               n = pollts(&cu->cu_pfdp, 1, &ts, maskp);
+               if (n == 1) {
+                       /* We have some data now */
+                       do {
+                               recvlen = recvfrom(cu->cu_fd, cu->cu_inbuf,
+                                   cu->cu_recvsz, 0, NULL, NULL);
+                       } while (recvlen < 0 && errno == EINTR);
+                       
+                       if (recvlen < 0 && errno != EWOULDBLOCK) {
+                               cu->cu_error.re_errno = errno;
+                               cu->cu_error.re_status = RPC_CANTRECV;
+                               goto out;
+                       }
+                       if (recvlen >= (ssize_t)sizeof(uint32_t) &&
+                           (*((uint32_t *)(void *)(cu->cu_inbuf)) == 
+                               *((uint32_t *)(void *)(cu->cu_outbuf)))) {
+                               /* We now assume we have the proper reply. */
+                               break;
+                       }              
+               }
+               if (n == -1) {
+                       cu->cu_error.re_errno = errno;
+                       cu->cu_error.re_status = RPC_CANTRECV;
+                       goto out;
+               }
+
+               gettimeofday(&tv, NULL);
+               timersub(&tv, &starttime, &time_waited);
+
+               /* Check for timeout. */
+               if (timercmp(&time_waited, &timeout, >)) {
+                       cu->cu_error.re_status = RPC_TIMEDOUT;
+                       goto out;
+               }
+
+               /* Retransmit if necessary. */
+               if (timercmp(&time_waited, &next_sendtime, >)) {
+                       /* update retransmit_time */
+                       if (retransmit_time.tv_sec < RPC_MAX_BACKOFF)
+                               timeradd(&retransmit_time, &retransmit_time,
+                                   &retransmit_time);
+                       timeradd(&next_sendtime, &retransmit_time,
+                           &next_sendtime);
+                       goto send_again;
+               }
+       }
+
+       /*
+        * now decode and validate the response
+        */
+
+       xdrmem_create(&reply_xdrs, cu->cu_inbuf, (u_int)recvlen, XDR_DECODE);
+       ok = xdr_replymsg(&reply_xdrs, &reply_msg);
+       /* XDR_DESTROY(&reply_xdrs);    save a few cycles on noop destroy */
+       if (ok) {
+               if ((reply_msg.rm_reply.rp_stat == MSG_ACCEPTED) &&
+                       (reply_msg.acpted_rply.ar_stat == SUCCESS))
+                       cu->cu_error.re_status = RPC_SUCCESS;
+               else
+                       _seterr_reply(&reply_msg, &(cu->cu_error));
+
+               if (cu->cu_error.re_status == RPC_SUCCESS) {
+                       if (! AUTH_VALIDATE(cl->cl_auth,
+                                           &reply_msg.acpted_rply.ar_verf)) {
+                               cu->cu_error.re_status = RPC_AUTHERROR;
+                               cu->cu_error.re_why = AUTH_INVALIDRESP;
+                       }
+                       if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) {
+                               xdrs->x_op = XDR_FREE;
+                               (void) xdr_opaque_auth(xdrs,
+                                       &(reply_msg.acpted_rply.ar_verf));
+                       }
+               }               /* end successful completion */
+               /*
+                * If unsuccesful AND error is an authentication error
+                * then refresh credentials and try again, else break
+                */
+               else if (cu->cu_error.re_status == RPC_AUTHERROR)
+                       /* maybe our credentials need to be refreshed ... */
+                       if (nrefreshes > 0 && AUTH_REFRESH(cl->cl_auth)) {
+                               nrefreshes--;
+                               goto call_again;
+                       }
+               /* end of unsuccessful completion */
+       }       /* end of valid reply message */
+       else {
+               cu->cu_error.re_status = RPC_CANTDECODERES;
+
+       }
+out:
+       release_fd_lock(cu->cu_fd, mask);
+       return (cu->cu_error.re_status);
+}
+
+static void
+clnt_dg_geterr(cl, errp)
+       CLIENT *cl;
+       struct rpc_err *errp;
+{
+       struct cu_data *cu;
+
+       _DIAGASSERT(cl != NULL);
+       _DIAGASSERT(errp != NULL);
+
+       cu = (struct cu_data *)cl->cl_private;
+       *errp = cu->cu_error;
+}
+
+static bool_t
+clnt_dg_freeres(cl, xdr_res, res_ptr)
+       CLIENT *cl;
+       xdrproc_t xdr_res;
+       caddr_t res_ptr;
+{
+       struct cu_data *cu;
+       XDR *xdrs;
+       bool_t dummy;
+#ifdef _REENTRANT
+       sigset_t mask;
+#endif
+       sigset_t newmask;
+
+       _DIAGASSERT(cl != NULL);
+       cu = (struct cu_data *)cl->cl_private;
+       xdrs = &(cu->cu_outxdrs);
+
+       sigfillset(&newmask);
+       thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
+       mutex_lock(&clnt_fd_lock);
+       while (dg_fd_locks[cu->cu_fd])
+               cond_wait(&dg_cv[cu->cu_fd], &clnt_fd_lock);
+       xdrs->x_op = XDR_FREE;
+       dummy = (*xdr_res)(xdrs, res_ptr);
+       mutex_unlock(&clnt_fd_lock);
+       thr_sigsetmask(SIG_SETMASK, &mask, NULL);
+       cond_signal(&dg_cv[cu->cu_fd]);
+       return (dummy);
+}
+
+/*ARGSUSED*/
+static void
+clnt_dg_abort(h)
+       CLIENT *h;
+{
+}
+
+static bool_t
+clnt_dg_control(cl, request, info)
+       CLIENT *cl;
+       u_int request;
+       char *info;
+{
+       struct cu_data *cu;
+       struct netbuf *addr;
+#ifdef _REENTRANT
+       sigset_t mask;
+#endif
+       sigset_t newmask;
+
+       _DIAGASSERT(cl != NULL);
+       /* info is handled below */
+
+       cu = (struct cu_data *)cl->cl_private;
+
+       sigfillset(&newmask);
+       thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
+       mutex_lock(&clnt_fd_lock);
+       while (dg_fd_locks[cu->cu_fd])
+               cond_wait(&dg_cv[cu->cu_fd], &clnt_fd_lock);
+       dg_fd_locks[cu->cu_fd] = __rpc_lock_value;
+       mutex_unlock(&clnt_fd_lock);
+       switch (request) {
+       case CLSET_FD_CLOSE:
+               cu->cu_closeit = TRUE;
+               release_fd_lock(cu->cu_fd, mask);
+               return (TRUE);
+       case CLSET_FD_NCLOSE:
+               cu->cu_closeit = FALSE;
+               release_fd_lock(cu->cu_fd, mask);
+               return (TRUE);
+       }
+
+       /* for other requests which use info */
+       if (info == NULL) {
+               release_fd_lock(cu->cu_fd, mask);
+               return (FALSE);
+       }
+       switch (request) {
+       case CLSET_TIMEOUT:
+               if (time_not_ok((struct timeval *)(void *)info)) {
+                       release_fd_lock(cu->cu_fd, mask);
+                       return (FALSE);
+               }
+               cu->cu_total = *(struct timeval *)(void *)info;
+               break;
+       case CLGET_TIMEOUT:
+               *(struct timeval *)(void *)info = cu->cu_total;
+               break;
+       case CLGET_SERVER_ADDR:         /* Give him the fd address */
+               /* Now obsolete. Only for backward compatibility */
+               (void) memcpy(info, &cu->cu_raddr, (size_t)cu->cu_rlen);
+               break;
+       case CLSET_RETRY_TIMEOUT:
+               if (time_not_ok((struct timeval *)(void *)info)) {
+                       release_fd_lock(cu->cu_fd, mask);
+                       return (FALSE);
+               }
+               cu->cu_wait = *(struct timeval *)(void *)info;
+               break;
+       case CLGET_RETRY_TIMEOUT:
+               *(struct timeval *)(void *)info = cu->cu_wait;
+               break;
+       case CLGET_FD:
+               *(int *)(void *)info = cu->cu_fd;
+               break;
+       case CLGET_SVC_ADDR:
+               addr = (struct netbuf *)(void *)info;
+               addr->buf = &cu->cu_raddr;
+               addr->len = cu->cu_rlen;
+               addr->maxlen = sizeof cu->cu_raddr;
+               break;
+       case CLSET_SVC_ADDR:            /* set to new address */
+               addr = (struct netbuf *)(void *)info;
+               if (addr->len < sizeof cu->cu_raddr) {
+                       release_fd_lock(cu->cu_fd, mask);
+                       return (FALSE);
+               }
+               (void) memcpy(&cu->cu_raddr, addr->buf, (size_t)addr->len);
+               cu->cu_rlen = addr->len;
+               break;
+       case CLGET_XID:
+               /*
+                * use the knowledge that xid is the
+                * first element in the call structure *.
+                * This will get the xid of the PREVIOUS call
+                */
+               *(u_int32_t *)(void *)info =
+                   ntohl(*(u_int32_t *)(void *)cu->cu_outbuf);
+               break;
+
+       case CLSET_XID:
+               /* This will set the xid of the NEXT call */
+               *(u_int32_t *)(void *)cu->cu_outbuf =
+                   htonl(*(u_int32_t *)(void *)info - 1);
+               /* decrement by 1 as clnt_dg_call() increments once */
+               break;
+
+       case CLGET_VERS:
+               /*
+                * This RELIES on the information that, in the call body,
+                * the version number field is the fifth field from the
+                * begining of the RPC header. MUST be changed if the
+                * call_struct is changed
+                */
+               *(u_int32_t *)(void *)info =
+                   ntohl(*(u_int32_t *)(void *)(cu->cu_outbuf +
+                   4 * BYTES_PER_XDR_UNIT));
+               break;
+
+       case CLSET_VERS:
+               *(u_int32_t *)(void *)(cu->cu_outbuf + 4 * BYTES_PER_XDR_UNIT)
+                       = htonl(*(u_int32_t *)(void *)info);
+               break;
+
+       case CLGET_PROG:
+               /*
+                * This RELIES on the information that, in the call body,
+                * the program number field is the fourth field from the
+                * begining of the RPC header. MUST be changed if the
+                * call_struct is changed
+                */
+               *(u_int32_t *)(void *)info =
+                   ntohl(*(u_int32_t *)(void *)(cu->cu_outbuf +
+                   3 * BYTES_PER_XDR_UNIT));
+               break;
+
+       case CLSET_PROG:
+               *(u_int32_t *)(void *)(cu->cu_outbuf + 3 * BYTES_PER_XDR_UNIT)
+                       = htonl(*(u_int32_t *)(void *)info);
+               break;
+
+       default:
+               release_fd_lock(cu->cu_fd, mask);
+               return (FALSE);
+       }
+       release_fd_lock(cu->cu_fd, mask);
+       return (TRUE);
+}
+
+static void
+clnt_dg_destroy(cl)
+       CLIENT *cl;
+{
+       struct cu_data *cu;
+       int cu_fd;
+#ifdef _REENTRANT
+       sigset_t mask;
+#endif
+       sigset_t newmask;
+
+       _DIAGASSERT(cl != NULL);
+
+       cu = (struct cu_data *)cl->cl_private;
+       cu_fd = cu->cu_fd;
+
+       sigfillset(&newmask);
+       thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
+       mutex_lock(&clnt_fd_lock);
+       while (dg_fd_locks[cu_fd])
+               cond_wait(&dg_cv[cu_fd], &clnt_fd_lock);
+       if (cu->cu_closeit)
+               (void) close(cu_fd);
+       XDR_DESTROY(&(cu->cu_outxdrs));
+       mem_free(cu, (sizeof (*cu) + cu->cu_sendsz + cu->cu_recvsz));
+       if (cl->cl_netid && cl->cl_netid[0])
+               mem_free(cl->cl_netid, strlen(cl->cl_netid) +1);
+       if (cl->cl_tp && cl->cl_tp[0])
+               mem_free(cl->cl_tp, strlen(cl->cl_tp) +1);
+       mem_free(cl, sizeof (CLIENT));
+       mutex_unlock(&clnt_fd_lock);
+       thr_sigsetmask(SIG_SETMASK, &mask, NULL);
+       cond_signal(&dg_cv[cu_fd]);
+}
+
+static struct clnt_ops *
+clnt_dg_ops()
+{
+       static struct clnt_ops ops;
+#ifdef _REENTRANT
+       extern mutex_t  ops_lock;
+       sigset_t mask;
+#endif
+       sigset_t newmask;
+
+/* VARIABLES PROTECTED BY ops_lock: ops */
+
+       sigfillset(&newmask);
+       thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
+       mutex_lock(&ops_lock);
+       if (ops.cl_call == NULL) {
+               ops.cl_call = clnt_dg_call;
+               ops.cl_abort = clnt_dg_abort;
+               ops.cl_geterr = clnt_dg_geterr;
+               ops.cl_freeres = clnt_dg_freeres;
+               ops.cl_destroy = clnt_dg_destroy;
+               ops.cl_control = clnt_dg_control;
+       }
+       mutex_unlock(&ops_lock);
+       thr_sigsetmask(SIG_SETMASK, &mask, NULL);
+       return (&ops);
+}
+
+/*
+ * Make sure that the time is not garbage.  -1 value is allowed.
+ */
+static bool_t
+time_not_ok(t)
+       struct timeval *t;
+{
+
+       _DIAGASSERT(t != NULL);
+
+       return (t->tv_sec < -1 || t->tv_sec > 100000000 ||
+               t->tv_usec < -1 || t->tv_usec > 1000000);
+}
diff --git a/lib/nbsd_libc/rpc/clnt_generic.c b/lib/nbsd_libc/rpc/clnt_generic.c
new file mode 100644 (file)
index 0000000..79fb9f8
--- /dev/null
@@ -0,0 +1,379 @@
+/*     $NetBSD: clnt_generic.c,v 1.27 2008/04/25 17:44:44 christos Exp $       */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc. 
+ */
+
+/* #ident      "@(#)clnt_generic.c     1.20    94/05/03 SMI" */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)clnt_generic.c 1.32 89/03/16 Copyr 1988 Sun Micro";
+#else
+__RCSID("$NetBSD: clnt_generic.c,v 1.27 2008/04/25 17:44:44 christos Exp $");
+#endif
+#endif
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <assert.h>
+#include <stdio.h>
+#include <errno.h>
+#include <rpc/rpc.h>
+#include <rpc/nettype.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(clnt_create_vers,_clnt_create_vers)
+__weak_alias(clnt_create,_clnt_create)
+__weak_alias(clnt_tp_create,_clnt_tp_create)
+__weak_alias(clnt_tli_create,_clnt_tli_create)
+#endif
+
+/*
+ * Generic client creation with version checking the value of
+ * vers_out is set to the highest server supported value
+ * vers_low <= vers_out <= vers_high  AND an error results
+ * if this can not be done.
+ */
+CLIENT *
+clnt_create_vers(hostname, prog, vers_out, vers_low, vers_high, nettype)
+       const char *hostname;
+       rpcprog_t prog;
+       rpcvers_t *vers_out;
+       rpcvers_t vers_low;
+       rpcvers_t vers_high;
+       const char *nettype;
+{
+       CLIENT *clnt;
+       struct timeval to;
+       enum clnt_stat rpc_stat;
+       struct rpc_err rpcerr;
+
+       _DIAGASSERT(hostname != NULL);
+       _DIAGASSERT(vers_out != NULL);
+       /* XXX: nettype appears to support being NULL */
+
+       clnt = clnt_create(hostname, prog, vers_high, nettype);
+       if (clnt == NULL) {
+               return (NULL);
+       }
+       to.tv_sec = 10;
+       to.tv_usec = 0;
+       rpc_stat = clnt_call(clnt, NULLPROC, (xdrproc_t) xdr_void,
+           NULL, (xdrproc_t) xdr_void, NULL, to);
+       if (rpc_stat == RPC_SUCCESS) {
+               *vers_out = vers_high;
+               return (clnt);
+       }
+       if (rpc_stat == RPC_PROGVERSMISMATCH) {
+               unsigned long minvers, maxvers;
+
+               clnt_geterr(clnt, &rpcerr);
+               minvers = rpcerr.re_vers.low;
+               maxvers = rpcerr.re_vers.high;
+               if (maxvers < vers_high)
+                       vers_high = (rpcvers_t)maxvers;
+               if (minvers > vers_low)
+                       vers_low = (rpcvers_t)minvers;
+               if (vers_low > vers_high) {
+                       goto error;
+               }
+               CLNT_CONTROL(clnt, CLSET_VERS, (char *)(void *)&vers_high);
+               rpc_stat = clnt_call(clnt, NULLPROC, (xdrproc_t) xdr_void,
+                   NULL, (xdrproc_t) xdr_void, NULL, to);
+               if (rpc_stat == RPC_SUCCESS) {
+                       *vers_out = vers_high;
+                       return (clnt);
+               }
+       }
+       clnt_geterr(clnt, &rpcerr);
+
+error:
+       rpc_createerr.cf_stat = rpc_stat;
+       rpc_createerr.cf_error = rpcerr;
+       clnt_destroy(clnt);
+       return (NULL);
+}
+
+/*
+ * Top level client creation routine.
+ * Generic client creation: takes (servers name, program-number, nettype) and
+ * returns client handle. Default options are set, which the user can
+ * change using the rpc equivalent of ioctl()'s.
+ *
+ * It tries for all the netids in that particular class of netid until
+ * it succeeds.
+ * XXX The error message in the case of failure will be the one
+ * pertaining to the last create error.
+ *
+ * It calls clnt_tp_create();
+ */
+CLIENT *
+clnt_create(hostname, prog, vers, nettype)
+       const char *hostname;                           /* server name */
+       rpcprog_t prog;                         /* program number */
+       rpcvers_t vers;                         /* version number */
+       const char *nettype;                            /* net type */
+{
+       struct netconfig *nconf;
+       CLIENT *clnt = NULL;
+       void *handle;
+       enum clnt_stat  save_cf_stat = RPC_SUCCESS;
+       struct rpc_err  save_cf_error;
+
+       _DIAGASSERT(hostname != NULL);
+       /* XXX: nettype appears to support being NULL */
+
+       if ((handle = __rpc_setconf(nettype)) == NULL) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+               return (NULL);
+       }
+       rpc_createerr.cf_stat = RPC_SUCCESS;
+       while (clnt == NULL) {
+               if ((nconf = __rpc_getconf(handle)) == NULL) {
+                       if (rpc_createerr.cf_stat == RPC_SUCCESS)
+                               rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+                       break;
+               }
+#ifdef CLNT_DEBUG
+               printf("trying netid %s\n", nconf->nc_netid);
+#endif
+               clnt = clnt_tp_create(hostname, prog, vers, nconf);
+               if (clnt)
+                       break;
+               else
+                       /*
+                        *      Since we didn't get a name-to-address
+                        *      translation failure here, we remember
+                        *      this particular error.  The object of
+                        *      this is to enable us to return to the
+                        *      caller a more-specific error than the
+                        *      unhelpful ``Name to address translation
+                        *      failed'' which might well occur if we
+                        *      merely returned the last error (because
+                        *      the local loopbacks are typically the
+                        *      last ones in /etc/netconfig and the most
+                        *      likely to be unable to translate a host
+                        *      name).
+                        */
+                       if (rpc_createerr.cf_stat != RPC_N2AXLATEFAILURE) {
+                               save_cf_stat = rpc_createerr.cf_stat;
+                               save_cf_error = rpc_createerr.cf_error;
+                       }
+       }
+
+       /*
+        *      Attempt to return an error more specific than ``Name to address
+        *      translation failed''
+        */
+       if ((rpc_createerr.cf_stat == RPC_N2AXLATEFAILURE) &&
+               (save_cf_stat != RPC_SUCCESS)) {
+               rpc_createerr.cf_stat = save_cf_stat;
+               rpc_createerr.cf_error = save_cf_error;
+       }
+       __rpc_endconf(handle);
+       return (clnt);
+}
+
+/*
+ * Generic client creation: takes (servers name, program-number, netconf) and
+ * returns client handle. Default options are set, which the user can
+ * change using the rpc equivalent of ioctl()'s : clnt_control()
+ * It finds out the server address from rpcbind and calls clnt_tli_create()
+ */
+CLIENT *
+clnt_tp_create(hostname, prog, vers, nconf)
+       const char *hostname;                   /* server name */
+       rpcprog_t prog;                         /* program number */
+       rpcvers_t vers;                         /* version number */
+       const struct netconfig *nconf;          /* net config struct */
+{
+       struct netbuf *svcaddr;                 /* servers address */
+       CLIENT *cl = NULL;                      /* client handle */
+
+       _DIAGASSERT(hostname != NULL);
+       /* nconf is handled below */
+
+       if (nconf == NULL) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+               return (NULL);
+       }
+
+       /*
+        * Get the address of the server
+        */
+       if ((svcaddr = __rpcb_findaddr(prog, vers, nconf, hostname,
+               &cl)) == NULL) {
+               /* appropriate error number is set by rpcbind libraries */
+               return (NULL);
+       }
+       if (cl == NULL) {
+               cl = clnt_tli_create(RPC_ANYFD, nconf, svcaddr,
+                                       prog, vers, 0, 0);
+       } else {
+               /* Reuse the CLIENT handle and change the appropriate fields */
+               if (CLNT_CONTROL(cl, CLSET_SVC_ADDR, (void *)svcaddr) == TRUE) {
+                       if (cl->cl_netid == NULL) {
+                               cl->cl_netid = strdup(nconf->nc_netid);
+                               if (cl->cl_netid == NULL)
+                                       goto out;
+                       }
+                       if (cl->cl_tp == NULL) {
+                               cl->cl_tp = strdup(nconf->nc_device);
+                               if (cl->cl_tp == NULL)
+                                       goto out;
+                       }
+                       (void) CLNT_CONTROL(cl, CLSET_PROG, (void *)&prog);
+                       (void) CLNT_CONTROL(cl, CLSET_VERS, (void *)&vers);
+               } else {
+                       CLNT_DESTROY(cl);
+                       cl = clnt_tli_create(RPC_ANYFD, nconf, svcaddr,
+                                       prog, vers, 0, 0);
+               }
+       }
+       free(svcaddr->buf);
+       free(svcaddr);
+       return (cl);
+out:
+       clnt_destroy(cl);
+       return NULL;
+}
+
+/*
+ * Generic client creation:  returns client handle.
+ * Default options are set, which the user can
+ * change using the rpc equivalent of ioctl()'s : clnt_control().
+ * If fd is RPC_ANYFD, it will be opened using nconf.
+ * It will be bound if not so.
+ * If sizes are 0; appropriate defaults will be chosen.
+ */
+CLIENT *
+clnt_tli_create(fd, nconf, svcaddr, prog, vers, sendsz, recvsz)
+       int fd;                         /* fd */
+       const struct netconfig *nconf;  /* netconfig structure */
+       const struct netbuf *svcaddr;   /* servers address */
+       rpcprog_t prog;                 /* program number */
+       rpcvers_t vers;                 /* version number */
+       u_int sendsz;                   /* send size */
+       u_int recvsz;                   /* recv size */
+{
+       CLIENT *cl;                     /* client handle */
+       bool_t madefd = FALSE;          /* whether fd opened here */
+       long servtype;
+       struct __rpc_sockinfo si;
+
+       /* nconf is handled below */
+       _DIAGASSERT(svcaddr != NULL);
+
+       if (fd == RPC_ANYFD) {
+               if (nconf == NULL) {
+                       rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+                       return (NULL);
+               }
+
+               fd = __rpc_nconf2fd(nconf);
+
+               if (fd == -1)
+                       goto err;
+
+               madefd = TRUE;
+               servtype = nconf->nc_semantics;
+               if (!__rpc_fd2sockinfo(fd, &si))
+                       goto err;
+
+               bindresvport(fd, NULL);
+       } else {
+               if (!__rpc_fd2sockinfo(fd, &si))
+                       goto err;
+               servtype = __rpc_socktype2seman(si.si_socktype);
+               if (servtype == -1) {
+                       rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+                       return NULL;
+               }
+
+       }
+
+       if (si.si_af != ((struct sockaddr *)svcaddr->buf)->sa_family) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNHOST;        /* XXX */
+               goto err1;
+       }
+
+       switch (servtype) {
+       case NC_TPI_COTS_ORD:
+               cl = clnt_vc_create(fd, svcaddr, prog, vers, sendsz, recvsz);
+               if (!nconf || !cl)
+                       break;
+               __rpc_setnodelay(fd, &si);
+               break;
+       case NC_TPI_CLTS:
+               cl = clnt_dg_create(fd, svcaddr, prog, vers, sendsz, recvsz);
+               break;
+       default:
+               goto err;
+       }
+
+       if (cl == NULL)
+               goto err1; /* borrow errors from clnt_dg/vc creates */
+       if (nconf) {
+               cl->cl_netid = strdup(nconf->nc_netid);
+               if (cl->cl_netid == NULL)
+                       goto err0;
+               cl->cl_tp = strdup(nconf->nc_device);
+               if (cl->cl_tp == NULL)
+                       goto err0;
+       } else {
+               cl->cl_netid = __UNCONST("");
+               cl->cl_tp = __UNCONST("");
+       }
+       if (madefd) {
+               (void) CLNT_CONTROL(cl, CLSET_FD_CLOSE, NULL);
+/*             (void) CLNT_CONTROL(cl, CLSET_POP_TIMOD, NULL);  */
+       };
+
+       return (cl);
+
+err0:
+       clnt_destroy(cl);
+err:
+       rpc_createerr.cf_stat = RPC_SYSTEMERROR;
+       rpc_createerr.cf_error.re_errno = errno;
+err1:  if (madefd)
+               (void) close(fd);
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/rpc/clnt_perror.c b/lib/nbsd_libc/rpc/clnt_perror.c
new file mode 100644 (file)
index 0000000..005f1d7
--- /dev/null
@@ -0,0 +1,331 @@
+/*     $NetBSD: clnt_perror.c,v 1.28 2008/04/25 17:44:44 christos Exp $        */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)clnt_perror.c 1.15 87/10/07 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)clnt_perror.c       2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: clnt_perror.c,v 1.28 2008/04/25 17:44:44 christos Exp $");
+#endif
+#endif
+
+/*
+ * clnt_perror.c
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ */
+#include "namespace.h"
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <rpc/rpc.h>
+#include <rpc/types.h>
+#include <rpc/auth.h>
+#include <rpc/clnt.h>
+
+#ifdef __weak_alias
+__weak_alias(clnt_pcreateerror,_clnt_pcreateerror)
+__weak_alias(clnt_perrno,_clnt_perrno)
+__weak_alias(clnt_perror,_clnt_perror)
+__weak_alias(clnt_spcreateerror,_clnt_spcreateerror)
+__weak_alias(clnt_sperrno,_clnt_sperrno)
+__weak_alias(clnt_sperror,_clnt_sperror)
+#endif
+
+static char *buf;
+static size_t buflen;
+
+static char *_buf __P((void));
+static char *auth_errmsg __P((enum auth_stat));
+
+static char *
+_buf()
+{
+
+       buflen = 256;
+       if (buf == 0)
+               buf = malloc(buflen);
+       return (buf);
+}
+
+/*
+ * Print reply error info
+ */
+char *
+clnt_sperror(rpch, s)
+       CLIENT *rpch;
+       const char *s;
+{
+       struct rpc_err e;
+       char *err;
+       char *str;
+       char *strstart;
+       size_t len, i;
+
+       _DIAGASSERT(rpch != NULL);
+       _DIAGASSERT(s != NULL);
+
+       str = _buf(); /* side effect: sets "buflen" */
+       if (str == 0)
+               return (0);
+       len = buflen;
+       strstart = str;
+       CLNT_GETERR(rpch, &e);
+
+       i = snprintf(str, len, "%s: ", s);  
+       str += i;
+       len -= i;
+
+       (void)strncpy(str, clnt_sperrno(e.re_status), len - 1);
+       i = strlen(str);
+       str += i;
+       len -= i;
+
+       switch (e.re_status) {
+       case RPC_SUCCESS:
+       case RPC_CANTENCODEARGS:
+       case RPC_CANTDECODERES:
+       case RPC_TIMEDOUT:     
+       case RPC_PROGUNAVAIL:
+       case RPC_PROCUNAVAIL:
+       case RPC_CANTDECODEARGS:
+       case RPC_SYSTEMERROR:
+       case RPC_UNKNOWNHOST:
+       case RPC_UNKNOWNPROTO:
+       case RPC_PMAPFAILURE:
+       case RPC_PROGNOTREGISTERED:
+       case RPC_FAILED:
+               break;
+
+       case RPC_CANTSEND:
+       case RPC_CANTRECV:
+               i = snprintf(str, len, "; errno = %s", strerror(e.re_errno)); 
+               str += i;
+               len -= i;
+               break;
+
+       case RPC_VERSMISMATCH:
+               i = snprintf(str, len, "; low version = %u, high version = %u", 
+                       e.re_vers.low, e.re_vers.high);
+               str += i;
+               len -= i;
+               break;
+
+       case RPC_AUTHERROR:
+               err = auth_errmsg(e.re_why);
+               i = snprintf(str, len, "; why = ");
+               str += i;
+               len -= i;
+               if (err != NULL) {
+                       i = snprintf(str, len, "%s",err);
+               } else {
+                       i = snprintf(str, len,
+                               "(unknown authentication error - %d)",
+                               (int) e.re_why);
+               }
+               str += i;
+               len -= i;
+               break;
+
+       case RPC_PROGVERSMISMATCH:
+               i = snprintf(str, len, "; low version = %u, high version = %u", 
+                       e.re_vers.low, e.re_vers.high);
+               str += i;
+               len -= i;
+               break;
+
+       default:        /* unknown */
+               i = snprintf(str, len, "; s1 = %u, s2 = %u", 
+                       e.re_lb.s1, e.re_lb.s2);
+               str += i;
+               len -= i;
+               break;
+       }
+       return(strstart) ;
+}
+
+void
+clnt_perror(rpch, s)
+       CLIENT *rpch;
+       const char *s;
+{
+
+       _DIAGASSERT(rpch != NULL);
+       _DIAGASSERT(s != NULL);
+
+       (void) fprintf(stderr, "%s\n", clnt_sperror(rpch,s));
+}
+
+static const char *const rpc_errlist[] = {
+       [RPC_SUCCESS] =                 "RPC: Success",
+       [RPC_CANTENCODEARGS] =          "RPC: Can't encode arguments",
+       [RPC_CANTDECODERES] =           "RPC: Can't decode result",
+       [RPC_CANTSEND] =                "RPC: Unable to send",
+       [RPC_CANTRECV] =                "RPC: Unable to receive",
+       [RPC_TIMEDOUT] =                "RPC: Timed out",
+       [RPC_VERSMISMATCH] =            "RPC: Incompatible versions of RPC",
+       [RPC_AUTHERROR] =               "RPC: Authentication error",
+       [RPC_PROGUNAVAIL] =             "RPC: Program unavailable",
+       [RPC_PROGVERSMISMATCH] =        "RPC: Program/version mismatch",
+       [RPC_PROCUNAVAIL] =             "RPC: Procedure unavailable",
+       [RPC_CANTDECODEARGS] =          "RPC: Server can't decode arguments",
+       [RPC_SYSTEMERROR] =             "RPC: Remote system error",
+       [RPC_UNKNOWNHOST] =             "RPC: Unknown host",
+       [RPC_PMAPFAILURE] =             "RPC: Port mapper failure",
+       [RPC_PROGNOTREGISTERED] =       "RPC: Program not registered",
+       [RPC_FAILED] =                  "RPC: Failed (unspecified error)",
+       [RPC_UNKNOWNPROTO] =            "RPC: Unknown protocol",
+       [RPC_UNKNOWNADDR] =             "RPC: Remote address unknown",
+       [RPC_TLIERROR] =                "RPC: Misc error in the TLI library",
+       [RPC_NOBROADCAST] =             "RPC: Broadcasting not supported",
+       [RPC_N2AXLATEFAILURE] =         "RPC: Name -> addr translation failed",
+       [RPC_INPROGRESS] =              "RPC: In progress",
+       [RPC_STALERACHANDLE] =          "RPC: Stale handle",
+};
+
+
+/*
+ * This interface for use by clntrpc
+ */
+char *
+clnt_sperrno(stat)
+       enum clnt_stat stat;
+{
+       unsigned int errnum = stat;
+       const char *msg;
+
+       msg = NULL;
+       if (errnum < (sizeof(rpc_errlist)/sizeof(rpc_errlist[0]))) {
+               msg = rpc_errlist[errnum];
+       }
+       if (msg == NULL) {
+               msg = "RPC: (unknown error code)";
+       }
+       return __UNCONST(msg);
+}
+
+void
+clnt_perrno(num)
+       enum clnt_stat num;
+{
+       (void) fprintf(stderr, "%s\n", clnt_sperrno(num));
+}
+
+
+char *
+clnt_spcreateerror(s)
+       const char *s;
+{
+       char *str;
+       size_t len, i;
+
+       _DIAGASSERT(s != NULL);
+
+       str = _buf(); /* side effect: sets "buflen" */
+       if (str == 0)
+               return(0);
+       len = buflen;
+       i = snprintf(str, len, "%s: ", s);
+       len -= i;
+       (void)strncat(str, clnt_sperrno(rpc_createerr.cf_stat), len - 1);
+       switch (rpc_createerr.cf_stat) {
+       case RPC_PMAPFAILURE:
+               (void) strncat(str, " - ", len - 1);
+               (void) strncat(str,
+                   clnt_sperrno(rpc_createerr.cf_error.re_status), len - 4);
+               break;
+
+       case RPC_SYSTEMERROR:
+               (void)strncat(str, " - ", len - 1);
+               (void)strncat(str, strerror(rpc_createerr.cf_error.re_errno),
+                   len - 4);
+               break;
+
+       case RPC_CANTSEND:
+       case RPC_CANTDECODERES:
+       case RPC_CANTENCODEARGS:
+       case RPC_SUCCESS:
+       case RPC_UNKNOWNPROTO:
+       case RPC_PROGNOTREGISTERED:
+       case RPC_FAILED:
+       case RPC_UNKNOWNHOST:
+       case RPC_CANTDECODEARGS:
+       case RPC_PROCUNAVAIL:
+       case RPC_PROGVERSMISMATCH:
+       case RPC_PROGUNAVAIL:
+       case RPC_AUTHERROR:
+       case RPC_VERSMISMATCH:
+       case RPC_TIMEDOUT:
+       case RPC_CANTRECV:
+       default:
+               break;
+       }
+       return (str);
+}
+
+void
+clnt_pcreateerror(s)
+       const char *s;
+{
+
+       _DIAGASSERT(s != NULL);
+
+       (void) fprintf(stderr, "%s\n", clnt_spcreateerror(s));
+}
+
+static const char *const auth_errlist[] = {
+       "Authentication OK",                    /* 0 - AUTH_OK */
+       "Invalid client credential",            /* 1 - AUTH_BADCRED */
+       "Server rejected credential",           /* 2 - AUTH_REJECTEDCRED */
+       "Invalid client verifier",              /* 3 - AUTH_BADVERF */
+       "Server rejected verifier",             /* 4 - AUTH_REJECTEDVERF */
+       "Client credential too weak",           /* 5 - AUTH_TOOWEAK */
+       "Invalid server verifier",              /* 6 - AUTH_INVALIDRESP */
+       "Failed (unspecified error)"            /* 7 - AUTH_FAILED */
+};
+
+static char *
+auth_errmsg(stat)
+       enum auth_stat stat;
+{
+       unsigned int errnum = stat;
+
+       if (errnum < (sizeof(auth_errlist)/sizeof(auth_errlist[0])))
+               return __UNCONST(auth_errlist[errnum]);
+
+       return(NULL);
+}
diff --git a/lib/nbsd_libc/rpc/clnt_raw.c b/lib/nbsd_libc/rpc/clnt_raw.c
new file mode 100644 (file)
index 0000000..50787f5
--- /dev/null
@@ -0,0 +1,331 @@
+/*     $NetBSD: clnt_raw.c,v 1.29 2008/04/25 17:44:44 christos Exp $   */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ *
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)clnt_raw.c 1.22 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)clnt_raw.c  2.2 88/08/01 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: clnt_raw.c,v 1.29 2008/04/25 17:44:44 christos Exp $");
+#endif
+#endif
+
+/*
+ * clnt_raw.c
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ * Memory based rpc for simple testing and timing.
+ * Interface to create an rpc client and server in the same process.
+ * This lets us similate rpc and get round trip overhead, without
+ * any interference from the kernel.
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <assert.h>
+#include <err.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <rpc/rpc.h>
+#include <rpc/raw.h>
+
+#ifdef __weak_alias
+__weak_alias(clntraw_create,_clntraw_create)
+__weak_alias(clnt_raw_create,_clnt_raw_create)
+#endif
+
+#ifdef _REENTRANT
+extern mutex_t clntraw_lock;
+#endif
+
+#define MCALL_MSG_SIZE 24
+
+/*
+ * This is the "network" we will be moving stuff over.
+ */
+static struct clntraw_private {
+       CLIENT  client_object;
+       XDR     xdr_stream;
+       char    *_raw_buf;
+       union {
+           struct rpc_msg      mashl_rpcmsg;
+           char                mashl_callmsg[MCALL_MSG_SIZE];
+       } u;
+       u_int   mcnt;
+} *clntraw_private;
+
+static enum clnt_stat clnt_raw_call __P((CLIENT *, rpcproc_t, xdrproc_t,
+    const char *, xdrproc_t, caddr_t, struct timeval));
+static void clnt_raw_geterr __P((CLIENT *, struct rpc_err *));
+static bool_t clnt_raw_freeres __P((CLIENT *, xdrproc_t, caddr_t));
+static void clnt_raw_abort __P((CLIENT *));
+static bool_t clnt_raw_control __P((CLIENT *, u_int, char *));
+static void clnt_raw_destroy __P((CLIENT *));
+static struct clnt_ops *clnt_raw_ops __P((void));
+
+/*
+ * Create a client handle for memory based rpc.
+ */
+CLIENT *
+clnt_raw_create(prog, vers)
+       rpcprog_t prog;
+       rpcvers_t vers;
+{
+       struct clntraw_private *clp = clntraw_private;
+       struct rpc_msg call_msg;
+       XDR *xdrs = &clp->xdr_stream;
+       CLIENT  *client = &clp->client_object;
+
+       mutex_lock(&clntraw_lock);
+       if (clp == NULL) {
+               clp = calloc((size_t)1, sizeof (*clp));
+               if (clp == NULL)
+                       goto out;
+               if (__rpc_rawcombuf == NULL)
+                       __rpc_rawcombuf =
+                           malloc(UDPMSGSIZE);
+               if (__rpc_rawcombuf == NULL)
+                       goto out;
+               clp->_raw_buf = __rpc_rawcombuf;
+               clntraw_private = clp;
+       }
+       /*
+        * pre-serialize the static part of the call msg and stash it away
+        */
+       call_msg.rm_direction = CALL;
+       call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
+       /* XXX: prog and vers have been long historically :-( */
+       call_msg.rm_call.cb_prog = (u_int32_t)prog;
+       call_msg.rm_call.cb_vers = (u_int32_t)vers;
+       xdrmem_create(xdrs, clp->u.mashl_callmsg, MCALL_MSG_SIZE, XDR_ENCODE); 
+       if (! xdr_callhdr(xdrs, &call_msg))
+               warnx("clntraw_create - Fatal header serialization error.");
+       clp->mcnt = XDR_GETPOS(xdrs);
+       XDR_DESTROY(xdrs);
+
+       /*
+        * Set xdrmem for client/server shared buffer
+        */
+       xdrmem_create(xdrs, clp->_raw_buf, UDPMSGSIZE, XDR_FREE);
+
+       /*
+        * create client handle
+        */
+       client->cl_ops = clnt_raw_ops();
+       client->cl_auth = authnone_create();
+       mutex_unlock(&clntraw_lock);
+       return (client);
+out:
+       if (clp)
+               free(clp);
+       mutex_unlock(&clntraw_lock);
+       return NULL;
+
+}
+
+/* ARGSUSED */
+static enum clnt_stat 
+clnt_raw_call(h, proc, xargs, argsp, xresults, resultsp, timeout)
+       CLIENT *h;
+       rpcproc_t proc;
+       xdrproc_t xargs;
+       const char *argsp;
+       xdrproc_t xresults;
+       caddr_t resultsp;
+       struct timeval timeout;
+{
+       struct clntraw_private *clp = clntraw_private;
+       XDR *xdrs = &clp->xdr_stream;
+       struct rpc_msg msg;
+       enum clnt_stat status;
+       struct rpc_err error;
+
+       _DIAGASSERT(h != NULL);
+
+       mutex_lock(&clntraw_lock);
+       if (clp == NULL) {
+               mutex_unlock(&clntraw_lock);
+               return (RPC_FAILED);
+       }
+       mutex_unlock(&clntraw_lock);
+
+call_again:
+       /*
+        * send request
+        */
+       xdrs->x_op = XDR_ENCODE;
+       XDR_SETPOS(xdrs, 0);
+       clp->u.mashl_rpcmsg.rm_xid ++ ;
+       if ((! XDR_PUTBYTES(xdrs, clp->u.mashl_callmsg, clp->mcnt)) ||
+           (! XDR_PUTINT32(xdrs, (int32_t *)&proc)) ||
+           (! AUTH_MARSHALL(h->cl_auth, xdrs)) ||
+           (! (*xargs)(xdrs, __UNCONST(argsp)))) {
+               return (RPC_CANTENCODEARGS);
+       }
+       (void)XDR_GETPOS(xdrs);  /* called just to cause overhead */
+
+       /*
+        * We have to call server input routine here because this is
+        * all going on in one process. Yuk.
+        */
+       svc_getreq_common(FD_SETSIZE);
+
+       /*
+        * get results
+        */
+       xdrs->x_op = XDR_DECODE;
+       XDR_SETPOS(xdrs, 0);
+       msg.acpted_rply.ar_verf = _null_auth;
+       msg.acpted_rply.ar_results.where = resultsp;
+       msg.acpted_rply.ar_results.proc = xresults;
+       if (! xdr_replymsg(xdrs, &msg)) {
+               /*
+                * It's possible for xdr_replymsg() to fail partway
+                * through its attempt to decode the result from the
+                * server. If this happens, it will leave the reply
+                * structure partially populated with dynamically
+                * allocated memory. (This can happen if someone uses
+                * clntudp_bufcreate() to create a CLIENT handle and
+                * specifies a receive buffer size that is too small.)
+                * This memory must be free()ed to avoid a leak.
+                */
+               int op = xdrs->x_op;
+               xdrs->x_op = XDR_FREE;
+               xdr_replymsg(xdrs, &msg);
+               xdrs->x_op = op;
+               return (RPC_CANTDECODERES);
+       }
+       _seterr_reply(&msg, &error);
+       status = error.re_status;
+
+       if (status == RPC_SUCCESS) {
+               if (! AUTH_VALIDATE(h->cl_auth, &msg.acpted_rply.ar_verf)) {
+                       status = RPC_AUTHERROR;
+               }
+       }  /* end successful completion */
+       else {
+               if (AUTH_REFRESH(h->cl_auth))
+                       goto call_again;
+       }  /* end of unsuccessful completion */
+
+       if (status == RPC_SUCCESS) {
+               if (! AUTH_VALIDATE(h->cl_auth, &msg.acpted_rply.ar_verf)) {
+                       status = RPC_AUTHERROR;
+               }
+               if (msg.acpted_rply.ar_verf.oa_base != NULL) {
+                       xdrs->x_op = XDR_FREE;
+                       (void)xdr_opaque_auth(xdrs, &(msg.acpted_rply.ar_verf));
+               }
+       }
+
+       return (status);
+}
+
+/*ARGSUSED*/
+static void
+clnt_raw_geterr(cl, error)
+       CLIENT *cl;
+       struct rpc_err *error;
+{
+}
+
+
+/* ARGSUSED */
+static bool_t
+clnt_raw_freeres(cl, xdr_res, res_ptr)
+       CLIENT *cl;
+       xdrproc_t xdr_res;
+       caddr_t res_ptr;
+{
+       struct clntraw_private *clp = clntraw_private;
+       XDR *xdrs = &clp->xdr_stream;
+       bool_t rval;
+
+       mutex_lock(&clntraw_lock);
+       if (clp == NULL) {
+               rval = (bool_t) RPC_FAILED;
+               mutex_unlock(&clntraw_lock);
+               return (rval);
+       }
+       mutex_unlock(&clntraw_lock);
+       xdrs->x_op = XDR_FREE;
+       return ((*xdr_res)(xdrs, res_ptr));
+}
+
+/*ARGSUSED*/
+static void
+clnt_raw_abort(cl)
+       CLIENT *cl;
+{
+}
+
+/*ARGSUSED*/
+static bool_t
+clnt_raw_control(cl, ui, str)
+       CLIENT *cl;
+       u_int ui;
+       char *str;
+{
+       return (FALSE);
+}
+
+/*ARGSUSED*/
+static void
+clnt_raw_destroy(cl)
+       CLIENT *cl;
+{
+}
+
+static struct clnt_ops *
+clnt_raw_ops()
+{
+       static struct clnt_ops ops;
+#ifdef _REENTRANT
+       extern mutex_t  ops_lock;
+#endif
+
+       /* VARIABLES PROTECTED BY ops_lock: ops */
+
+       mutex_lock(&ops_lock);
+       if (ops.cl_call == NULL) {
+               ops.cl_call = clnt_raw_call;
+               ops.cl_abort = clnt_raw_abort;
+               ops.cl_geterr = clnt_raw_geterr;
+               ops.cl_freeres = clnt_raw_freeres;
+               ops.cl_destroy = clnt_raw_destroy;
+               ops.cl_control = clnt_raw_control;
+       }
+       mutex_unlock(&ops_lock);
+       return (&ops);
+}
diff --git a/lib/nbsd_libc/rpc/clnt_simple.c b/lib/nbsd_libc/rpc/clnt_simple.c
new file mode 100644 (file)
index 0000000..5480783
--- /dev/null
@@ -0,0 +1,216 @@
+/*     $NetBSD: clnt_simple.c,v 1.30 2010/12/08 02:06:38 joerg Exp $   */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc. 
+ */
+
+/* #ident      "@(#)clnt_simple.c      1.17    94/04/24 SMI" */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)clnt_simple.c 1.49 89/01/31 Copyr 1984 Sun Micro";
+#else
+__RCSID("$NetBSD: clnt_simple.c,v 1.30 2010/12/08 02:06:38 joerg Exp $");
+#endif
+#endif
+
+/*
+ * clnt_simple.c
+ * Simplified front end to client rpc.
+ *
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/param.h>
+#include <stdio.h>
+#include <assert.h>
+#include <errno.h>
+#include <rpc/rpc.h>
+#include <string.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(rpc_call,_rpc_call)
+#endif
+
+#ifndef MAXHOSTNAMELEN
+#define        MAXHOSTNAMELEN 64
+#endif
+
+#ifndef NETIDLEN
+#define        NETIDLEN 32
+#endif
+
+struct rpc_call_private {
+       int     valid;                  /* Is this entry valid ? */
+       CLIENT  *client;                /* Client handle */
+       pid_t   pid;                    /* process-id at moment of creation */
+       rpcprog_t prognum;              /* Program */
+       rpcvers_t versnum;              /* Version */
+       char    host[MAXHOSTNAMELEN];   /* Servers host */
+       char    nettype[NETIDLEN];      /* Network type */
+};
+static struct rpc_call_private *rpc_call_private_main;
+
+#ifdef _REENTRANT
+static void rpc_call_destroy __P((void *));
+
+static void
+rpc_call_destroy(void *vp)
+{
+       struct rpc_call_private *rcp = (struct rpc_call_private *)vp;
+
+       if (rcp) {
+               if (rcp->client)
+                       CLNT_DESTROY(rcp->client);
+               free(rcp);
+       }
+}
+static thread_key_t rpc_call_key;
+static once_t rpc_call_once = ONCE_INITIALIZER;
+
+static void
+rpc_call_setup(void)
+{
+
+       thr_keycreate(&rpc_call_key, rpc_call_destroy);
+}
+#endif
+
+
+/*
+ * This is the simplified interface to the client rpc layer.
+ * The client handle is not destroyed here and is reused for
+ * the future calls to same prog, vers, host and nettype combination.
+ *
+ * The total time available is 25 seconds.
+ */
+enum clnt_stat
+rpc_call(host, prognum, versnum, procnum, inproc, in, outproc, out, nettype)
+       const char *host;                       /* host name */
+       rpcprog_t prognum;                      /* program number */
+       rpcvers_t versnum;                      /* version number */
+       rpcproc_t procnum;                      /* procedure number */
+       xdrproc_t inproc, outproc;      /* in/out XDR procedures */
+       const char *in;
+       char  *out;                     /* recv/send data */
+       const char *nettype;                    /* nettype */
+{
+       struct rpc_call_private *rcp = (struct rpc_call_private *) 0;
+       enum clnt_stat clnt_stat;
+       struct timeval timeout, tottimeout;
+
+       _DIAGASSERT(host != NULL);
+       /* XXX: in may be NULL ??? */
+       /* XXX: out may be NULL ??? */
+       /* XXX: nettype may be NULL ??? */
+
+#ifdef _REENTRANT
+       if (__isthreaded == 0) {
+               rcp = rpc_call_private_main;
+       } else {
+               thr_once(&rpc_call_once, rpc_call_setup);
+               rcp = thr_getspecific(rpc_call_key);
+       }
+#else
+       rcp = rpc_call_private_main;
+#endif
+       if (rcp == NULL) {
+               rcp = malloc(sizeof (*rcp));
+               if (rcp == NULL) {
+                       rpc_createerr.cf_stat = RPC_SYSTEMERROR;
+                       rpc_createerr.cf_error.re_errno = errno;
+                       return (rpc_createerr.cf_stat);
+               }
+               if (__isthreaded == 0)
+                       rpc_call_private_main = rcp;
+               else
+                       thr_setspecific(rpc_call_key, (void *) rcp);
+               rcp->valid = 0;
+               rcp->client = NULL;
+       }
+       if ((nettype == NULL) || (nettype[0] == 0))
+               nettype = "netpath";
+       if (!(rcp->valid && rcp->pid == getpid() &&
+               (rcp->prognum == prognum) &&
+               (rcp->versnum == versnum) &&
+               (!strcmp(rcp->host, host)) &&
+               (!strcmp(rcp->nettype, nettype)))) {
+               int fd;
+
+               rcp->valid = 0;
+               if (rcp->client)
+                       CLNT_DESTROY(rcp->client);
+               /*
+                * Using the first successful transport for that type
+                */
+               rcp->client = clnt_create(host, prognum, versnum, nettype);
+               rcp->pid = getpid();
+               if (rcp->client == NULL) {
+                       return (rpc_createerr.cf_stat);
+               }
+               /*
+                * Set time outs for connectionless case.  Do it
+                * unconditionally.  Faster than doing a t_getinfo()
+                * and then doing the right thing.
+                */
+               timeout.tv_usec = 0;
+               timeout.tv_sec = 5;
+               (void) CLNT_CONTROL(rcp->client,
+                               CLSET_RETRY_TIMEOUT, (char *)(void *)&timeout);
+               if (CLNT_CONTROL(rcp->client, CLGET_FD, (char *)(void *)&fd))
+                       (void)fcntl(fd, F_SETFD, FD_CLOEXEC);
+               rcp->prognum = prognum;
+               rcp->versnum = versnum;
+               if ((strlen(host) < (size_t)MAXHOSTNAMELEN) &&
+                   (strlen(nettype) < (size_t)NETIDLEN)) {
+                       (void) strcpy(rcp->host, host);
+                       (void) strcpy(rcp->nettype, nettype);
+                       rcp->valid = 1;
+               } else {
+                       rcp->valid = 0;
+               }
+       } /* else reuse old client */
+       tottimeout.tv_sec = 25;
+       tottimeout.tv_usec = 0;
+       clnt_stat = CLNT_CALL(rcp->client, procnum, inproc, in,
+           outproc, out, tottimeout);
+       /*
+        * if call failed, empty cache
+        */
+       if (clnt_stat != RPC_SUCCESS)
+               rcp->valid = 0;
+       return (clnt_stat);
+}
diff --git a/lib/nbsd_libc/rpc/clnt_vc.c b/lib/nbsd_libc/rpc/clnt_vc.c
new file mode 100644 (file)
index 0000000..4cb6329
--- /dev/null
@@ -0,0 +1,783 @@
+/*     $NetBSD: clnt_vc.c,v 1.17 2010/12/08 02:06:38 joerg Exp $       */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)clnt_tcp.c 1.37 87/10/05 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)clnt_tcp.c  2.2 88/08/01 4.0 RPCSRC";
+static char sccsid[] = "@(#)clnt_vc.c 1.19 89/03/16 Copyr 1988 Sun Micro";
+#else
+__RCSID("$NetBSD: clnt_vc.c,v 1.17 2010/12/08 02:06:38 joerg Exp $");
+#endif
+#endif
+/*
+ * clnt_tcp.c, Implements a TCP/IP based, client side RPC.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ * TCP based RPC supports 'batched calls'.
+ * A sequence of calls may be batched-up in a send buffer.  The rpc call
+ * return immediately to the client even though the call was not necessarily
+ * sent.  The batching occurs if the results' xdr routine is NULL (0) AND
+ * the rpc timeout value is zero (see clnt.h, rpc).
+ *
+ * Clients should NOT casually batch calls that in fact return results; that is,
+ * the server side should be aware that a call is batched and not produce any
+ * return message.  Batched calls that produce many result messages can
+ * deadlock (netlock) the client and the server....
+ *
+ * Now go hang yourself.
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/poll.h>
+#include <sys/socket.h>
+
+#include <assert.h>
+#include <err.h>
+#include <errno.h>
+#include <netdb.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <signal.h>
+
+#include <rpc/rpc.h>
+
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(clnt_vc_create,_clnt_vc_create)
+#endif
+
+#define MCALL_MSG_SIZE 24
+
+static enum clnt_stat clnt_vc_call __P((CLIENT *, rpcproc_t, xdrproc_t,
+    const char *, xdrproc_t, caddr_t, struct timeval));
+static void clnt_vc_geterr __P((CLIENT *, struct rpc_err *));
+static bool_t clnt_vc_freeres __P((CLIENT *, xdrproc_t, caddr_t));
+static void clnt_vc_abort __P((CLIENT *));
+static bool_t clnt_vc_control __P((CLIENT *, u_int, char *));
+static void clnt_vc_destroy __P((CLIENT *));
+static struct clnt_ops *clnt_vc_ops __P((void));
+static bool_t time_not_ok __P((struct timeval *));
+static int read_vc __P((caddr_t, caddr_t, int));
+static int write_vc __P((caddr_t, caddr_t, int));
+
+struct ct_data {
+       int             ct_fd;
+       bool_t          ct_closeit;
+       struct timeval  ct_wait;
+       bool_t          ct_waitset;       /* wait set by clnt_control? */
+       struct netbuf   ct_addr; 
+       struct rpc_err  ct_error;
+       union {
+               char    ct_mcallc[MCALL_MSG_SIZE];      /* marshalled callmsg */
+               u_int32_t ct_mcalli;
+       } ct_u;
+       u_int           ct_mpos;                        /* pos after marshal */
+       XDR             ct_xdrs;
+};
+
+/*
+ *      This machinery implements per-fd locks for MT-safety.  It is not
+ *      sufficient to do per-CLIENT handle locks for MT-safety because a
+ *      user may create more than one CLIENT handle with the same fd behind
+ *      it.  Therfore, we allocate an array of flags (vc_fd_locks), protected
+ *      by the clnt_fd_lock mutex, and an array (vc_cv) of condition variables
+ *      similarly protected.  Vc_fd_lock[fd] == 1 => a call is activte on some
+ *      CLIENT handle created for that fd.
+ *      The current implementation holds locks across the entire RPC and reply.
+ *      Yes, this is silly, and as soon as this code is proven to work, this
+ *      should be the first thing fixed.  One step at a time.
+ */
+#ifdef _REENTRANT
+static int      *vc_fd_locks;
+#define __rpc_lock_value __isthreaded;
+extern mutex_t  clnt_fd_lock;
+static cond_t   *vc_cv;
+#define release_fd_lock(fd, mask) {             \
+       mutex_lock(&clnt_fd_lock);      \
+       vc_fd_locks[fd] = 0;            \
+       mutex_unlock(&clnt_fd_lock);    \
+       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);        \
+       cond_signal(&vc_cv[fd]);        \
+}
+#else
+#define release_fd_lock(fd,mask)
+#define __rpc_lock_value 0
+#endif
+
+
+/*
+ * Create a client handle for a connection.
+ * Default options are set, which the user can change using clnt_control()'s.
+ * The rpc/vc package does buffering similar to stdio, so the client
+ * must pick send and receive buffer sizes, 0 => use the default.
+ * NB: fd is copied into a private area.
+ * NB: The rpch->cl_auth is set null authentication. Caller may wish to
+ * set this something more useful.
+ *
+ * fd should be an open socket
+ */
+CLIENT *
+clnt_vc_create(fd, raddr, prog, vers, sendsz, recvsz)
+       int fd;
+       const struct netbuf *raddr;
+       rpcprog_t prog;
+       rpcvers_t vers;
+       u_int sendsz;
+       u_int recvsz;
+{
+       CLIENT *h;
+       struct ct_data *ct = NULL;
+       struct rpc_msg call_msg;
+#ifdef _REENTRANT
+       sigset_t mask;
+#endif
+       sigset_t newmask;
+       struct sockaddr_storage ss;
+       socklen_t slen;
+       struct __rpc_sockinfo si;
+
+       _DIAGASSERT(raddr != NULL);
+
+       h  = mem_alloc(sizeof(*h));
+       if (h == NULL) {
+               warnx("clnt_vc_create: out of memory");
+               rpc_createerr.cf_stat = RPC_SYSTEMERROR;
+               rpc_createerr.cf_error.re_errno = errno;
+               goto fooy;
+       }
+       ct = mem_alloc(sizeof(*ct));
+       if (ct == NULL) {
+               warnx("clnt_vc_create: out of memory");
+               rpc_createerr.cf_stat = RPC_SYSTEMERROR;
+               rpc_createerr.cf_error.re_errno = errno;
+               goto fooy;
+       }
+
+       sigfillset(&newmask);
+       thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
+#ifdef _REENTRANT
+       mutex_lock(&clnt_fd_lock);
+       if (vc_fd_locks == NULL) {
+               size_t cv_allocsz, fd_allocsz;
+               int dtbsize = __rpc_dtbsize();
+
+               fd_allocsz = dtbsize * sizeof (int);
+               vc_fd_locks = mem_alloc(fd_allocsz);
+               if (vc_fd_locks == NULL) {
+                       mutex_unlock(&clnt_fd_lock);
+                       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);
+                       goto fooy;
+               } else
+                       memset(vc_fd_locks, '\0', fd_allocsz);
+
+               _DIAGASSERT(vc_cv == NULL);
+               cv_allocsz = dtbsize * sizeof (cond_t);
+               vc_cv = mem_alloc(cv_allocsz);
+               if (vc_cv == NULL) {
+                       mem_free(vc_fd_locks, fd_allocsz);
+                       vc_fd_locks = NULL;
+                       mutex_unlock(&clnt_fd_lock);
+                       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);
+                       goto fooy;
+               } else {
+                       int i;
+
+                       for (i = 0; i < dtbsize; i++)
+                               cond_init(&vc_cv[i], 0, (void *) 0);
+               }
+       } else
+               _DIAGASSERT(vc_cv != NULL);
+#endif
+
+       /*
+        * XXX - fvdl connecting while holding a mutex?
+        */
+       slen = sizeof ss;
+       if (getpeername(fd, (struct sockaddr *)(void *)&ss, &slen) < 0) {
+               if (errno != ENOTCONN) {
+                       rpc_createerr.cf_stat = RPC_SYSTEMERROR;
+                       rpc_createerr.cf_error.re_errno = errno;
+                       mutex_unlock(&clnt_fd_lock);
+                       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);
+                       goto fooy;
+               }
+               if (connect(fd, (struct sockaddr *)raddr->buf, raddr->len) < 0){
+                       rpc_createerr.cf_stat = RPC_SYSTEMERROR;
+                       rpc_createerr.cf_error.re_errno = errno;
+                       mutex_unlock(&clnt_fd_lock);
+                       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);
+                       goto fooy;
+               }
+       }
+       mutex_unlock(&clnt_fd_lock);
+       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);
+       if (!__rpc_fd2sockinfo(fd, &si))
+               goto fooy;
+
+       ct->ct_closeit = FALSE;
+
+       /*
+        * Set up private data struct
+        */
+       ct->ct_fd = fd;
+       ct->ct_wait.tv_usec = 0;
+       ct->ct_waitset = FALSE;
+       ct->ct_addr.buf = malloc((size_t)raddr->maxlen);
+       if (ct->ct_addr.buf == NULL)
+               goto fooy;
+       memcpy(ct->ct_addr.buf, &raddr->buf, (size_t)raddr->len);
+       ct->ct_addr.len = raddr->maxlen;
+       ct->ct_addr.maxlen = raddr->maxlen;
+
+       /*
+        * Initialize call message
+        */
+       call_msg.rm_xid = __RPC_GETXID();
+       call_msg.rm_direction = CALL;
+       call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
+       call_msg.rm_call.cb_prog = (u_int32_t)prog;
+       call_msg.rm_call.cb_vers = (u_int32_t)vers;
+
+       /*
+        * pre-serialize the static part of the call msg and stash it away
+        */
+       xdrmem_create(&(ct->ct_xdrs), ct->ct_u.ct_mcallc, MCALL_MSG_SIZE,
+           XDR_ENCODE);
+       if (! xdr_callhdr(&(ct->ct_xdrs), &call_msg)) {
+               if (ct->ct_closeit) {
+                       (void)close(fd);
+               }
+               goto fooy;
+       }
+       ct->ct_mpos = XDR_GETPOS(&(ct->ct_xdrs));
+       XDR_DESTROY(&(ct->ct_xdrs));
+
+       /*
+        * Create a client handle which uses xdrrec for serialization
+        * and authnone for authentication.
+        */
+       h->cl_ops = clnt_vc_ops();
+       h->cl_private = ct;
+       h->cl_auth = authnone_create();
+       sendsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)sendsz);
+       recvsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)recvsz);
+       xdrrec_create(&(ct->ct_xdrs), sendsz, recvsz,
+           h->cl_private, read_vc, write_vc);
+       return (h);
+
+fooy:
+       /*
+        * Something goofed, free stuff and barf
+        */
+       if (ct)
+               mem_free(ct, sizeof(struct ct_data));
+       if (h)
+               mem_free(h, sizeof(CLIENT));
+       return (NULL);
+}
+
+static enum clnt_stat
+clnt_vc_call(h, proc, xdr_args, args_ptr, xdr_results, results_ptr, timeout)
+       CLIENT *h;
+       rpcproc_t proc;
+       xdrproc_t xdr_args;
+       const char *args_ptr;
+       xdrproc_t xdr_results;
+       caddr_t results_ptr;
+       struct timeval timeout;
+{
+       struct ct_data *ct;
+       XDR *xdrs;
+       struct rpc_msg reply_msg;
+       u_int32_t x_id;
+       u_int32_t *msg_x_id;
+       bool_t shipnow;
+       int refreshes = 2;
+#ifdef _REENTRANT
+       sigset_t mask, newmask;
+#endif
+
+       _DIAGASSERT(h != NULL);
+
+       ct = (struct ct_data *) h->cl_private;
+
+#ifdef _REENTRANT
+       sigfillset(&newmask);
+       thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
+       mutex_lock(&clnt_fd_lock);
+       while (vc_fd_locks[ct->ct_fd])
+               cond_wait(&vc_cv[ct->ct_fd], &clnt_fd_lock);
+       vc_fd_locks[ct->ct_fd] = __rpc_lock_value;
+       mutex_unlock(&clnt_fd_lock);
+#endif
+
+       xdrs = &(ct->ct_xdrs);
+       msg_x_id = &ct->ct_u.ct_mcalli;
+
+       if (!ct->ct_waitset) {
+               if (time_not_ok(&timeout) == FALSE)
+               ct->ct_wait = timeout;
+       }
+
+       shipnow =
+           (xdr_results == NULL && timeout.tv_sec == 0
+           && timeout.tv_usec == 0) ? FALSE : TRUE;
+
+call_again:
+       xdrs->x_op = XDR_ENCODE;
+       ct->ct_error.re_status = RPC_SUCCESS;
+       x_id = ntohl(--(*msg_x_id));
+       if ((! XDR_PUTBYTES(xdrs, ct->ct_u.ct_mcallc, ct->ct_mpos)) ||
+           (! XDR_PUTINT32(xdrs, (int32_t *)&proc)) ||
+           (! AUTH_MARSHALL(h->cl_auth, xdrs)) ||
+           (! (*xdr_args)(xdrs, __UNCONST(args_ptr)))) {
+               if (ct->ct_error.re_status == RPC_SUCCESS)
+                       ct->ct_error.re_status = RPC_CANTENCODEARGS;
+               (void)xdrrec_endofrecord(xdrs, TRUE);
+               release_fd_lock(ct->ct_fd, mask);
+               return (ct->ct_error.re_status);
+       }
+       if (! xdrrec_endofrecord(xdrs, shipnow)) {
+               release_fd_lock(ct->ct_fd, mask);
+               return (ct->ct_error.re_status = RPC_CANTSEND);
+       }
+       if (! shipnow) {
+               release_fd_lock(ct->ct_fd, mask);
+               return (RPC_SUCCESS);
+       }
+       /*
+        * Hack to provide rpc-based message passing
+        */
+       if (timeout.tv_sec == 0 && timeout.tv_usec == 0) {
+               release_fd_lock(ct->ct_fd, mask);
+               return(ct->ct_error.re_status = RPC_TIMEDOUT);
+       }
+
+
+       /*
+        * Keep receiving until we get a valid transaction id
+        */
+       xdrs->x_op = XDR_DECODE;
+       for (;;) {
+               reply_msg.acpted_rply.ar_verf = _null_auth;
+               reply_msg.acpted_rply.ar_results.where = NULL;
+               reply_msg.acpted_rply.ar_results.proc = (xdrproc_t)xdr_void;
+               if (! xdrrec_skiprecord(xdrs)) {
+                       release_fd_lock(ct->ct_fd, mask);
+                       return (ct->ct_error.re_status);
+               }
+               /* now decode and validate the response header */
+               if (! xdr_replymsg(xdrs, &reply_msg)) {
+                       if (ct->ct_error.re_status == RPC_SUCCESS)
+                               continue;
+                       release_fd_lock(ct->ct_fd, mask);
+                       return (ct->ct_error.re_status);
+               }
+               if (reply_msg.rm_xid == x_id)
+                       break;
+       }
+
+       /*
+        * process header
+        */
+       _seterr_reply(&reply_msg, &(ct->ct_error));
+       if (ct->ct_error.re_status == RPC_SUCCESS) {
+               if (! AUTH_VALIDATE(h->cl_auth,
+                   &reply_msg.acpted_rply.ar_verf)) {
+                       ct->ct_error.re_status = RPC_AUTHERROR;
+                       ct->ct_error.re_why = AUTH_INVALIDRESP;
+               } else if (! (*xdr_results)(xdrs, results_ptr)) {
+                       if (ct->ct_error.re_status == RPC_SUCCESS)
+                               ct->ct_error.re_status = RPC_CANTDECODERES;
+               }
+               /* free verifier ... */
+               if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) {
+                       xdrs->x_op = XDR_FREE;
+                       (void)xdr_opaque_auth(xdrs,
+                           &(reply_msg.acpted_rply.ar_verf));
+               }
+       }  /* end successful completion */
+       else {
+               /* maybe our credentials need to be refreshed ... */
+               if (refreshes-- && AUTH_REFRESH(h->cl_auth))
+                       goto call_again;
+       }  /* end of unsuccessful completion */
+       release_fd_lock(ct->ct_fd, mask);
+       return (ct->ct_error.re_status);
+}
+
+static void
+clnt_vc_geterr(h, errp)
+       CLIENT *h;
+       struct rpc_err *errp;
+{
+       struct ct_data *ct;
+
+       _DIAGASSERT(h != NULL);
+       _DIAGASSERT(errp != NULL);
+
+       ct = (struct ct_data *) h->cl_private;
+       *errp = ct->ct_error;
+}
+
+static bool_t
+clnt_vc_freeres(cl, xdr_res, res_ptr)
+       CLIENT *cl;
+       xdrproc_t xdr_res;
+       caddr_t res_ptr;
+{
+       struct ct_data *ct;
+       XDR *xdrs;
+       bool_t dummy;
+#ifdef _REENTRANT
+       sigset_t mask;
+#endif
+       sigset_t newmask;
+
+       _DIAGASSERT(cl != NULL);
+
+       ct = (struct ct_data *)cl->cl_private;
+       xdrs = &(ct->ct_xdrs);
+
+       sigfillset(&newmask);
+       thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
+       mutex_lock(&clnt_fd_lock);
+#ifdef _REENTRANT
+       while (vc_fd_locks[ct->ct_fd])
+               cond_wait(&vc_cv[ct->ct_fd], &clnt_fd_lock);
+#endif
+
+       xdrs->x_op = XDR_FREE;
+       dummy = (*xdr_res)(xdrs, res_ptr);
+       mutex_unlock(&clnt_fd_lock);
+       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);
+       cond_signal(&vc_cv[ct->ct_fd]);
+
+       return dummy;
+}
+
+/*ARGSUSED*/
+static void
+clnt_vc_abort(cl)
+       CLIENT *cl;
+{
+}
+
+static bool_t
+clnt_vc_control(cl, request, info)
+       CLIENT *cl;
+       u_int request;
+       char *info;
+{
+       struct ct_data *ct;
+       void *infop = info;
+#ifdef _REENTRANT
+       sigset_t mask;
+#endif
+       sigset_t newmask;
+
+       _DIAGASSERT(cl != NULL);
+
+       ct = (struct ct_data *)cl->cl_private;
+
+       sigfillset(&newmask);
+       thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
+       mutex_lock(&clnt_fd_lock);
+#ifdef _REENTRANT
+       while (vc_fd_locks[ct->ct_fd])
+               cond_wait(&vc_cv[ct->ct_fd], &clnt_fd_lock);
+       vc_fd_locks[ct->ct_fd] = __rpc_lock_value;
+#endif
+       mutex_unlock(&clnt_fd_lock);
+
+       switch (request) {
+       case CLSET_FD_CLOSE:
+               ct->ct_closeit = TRUE;
+               release_fd_lock(ct->ct_fd, mask);
+               return (TRUE);
+       case CLSET_FD_NCLOSE:
+               ct->ct_closeit = FALSE;
+               release_fd_lock(ct->ct_fd, mask);
+               return (TRUE);
+       default:
+               break;
+       }
+
+       /* for other requests which use info */
+       if (info == NULL) {
+               release_fd_lock(ct->ct_fd, mask);
+               return (FALSE);
+       }
+       switch (request) {
+       case CLSET_TIMEOUT:
+               if (time_not_ok((struct timeval *)(void *)info)) {
+                       release_fd_lock(ct->ct_fd, mask);
+                       return (FALSE);
+               }
+               ct->ct_wait = *(struct timeval *)infop;
+               ct->ct_waitset = TRUE;
+               break;
+       case CLGET_TIMEOUT:
+               *(struct timeval *)infop = ct->ct_wait;
+               break;
+       case CLGET_SERVER_ADDR:
+               (void) memcpy(info, ct->ct_addr.buf, (size_t)ct->ct_addr.len);
+               break;
+       case CLGET_FD:
+               *(int *)(void *)info = ct->ct_fd;
+               break;
+       case CLGET_SVC_ADDR:
+               /* The caller should not free this memory area */
+               *(struct netbuf *)(void *)info = ct->ct_addr;
+               break;
+       case CLSET_SVC_ADDR:            /* set to new address */
+               release_fd_lock(ct->ct_fd, mask);
+               return (FALSE);
+       case CLGET_XID:
+               /*
+                * use the knowledge that xid is the
+                * first element in the call structure
+                * This will get the xid of the PREVIOUS call
+                */
+               *(u_int32_t *)(void *)info =
+                   ntohl(*(u_int32_t *)(void *)&ct->ct_u.ct_mcalli);
+               break;
+       case CLSET_XID:
+               /* This will set the xid of the NEXT call */
+               *(u_int32_t *)(void *)&ct->ct_u.ct_mcalli =
+                   htonl(*((u_int32_t *)(void *)info) + 1);
+               /* increment by 1 as clnt_vc_call() decrements once */
+               break;
+       case CLGET_VERS:
+               /*
+                * This RELIES on the information that, in the call body,
+                * the version number field is the fifth field from the
+                * begining of the RPC header. MUST be changed if the
+                * call_struct is changed
+                */
+               *(u_int32_t *)(void *)info =
+                   ntohl(*(u_int32_t *)(void *)(ct->ct_u.ct_mcallc +
+                   4 * BYTES_PER_XDR_UNIT));
+               break;
+
+       case CLSET_VERS:
+               *(u_int32_t *)(void *)(ct->ct_u.ct_mcallc +
+                   4 * BYTES_PER_XDR_UNIT) =
+                   htonl(*(u_int32_t *)(void *)info);
+               break;
+
+       case CLGET_PROG:
+               /*
+                * This RELIES on the information that, in the call body,
+                * the program number field is the fourth field from the
+                * begining of the RPC header. MUST be changed if the
+                * call_struct is changed
+                */
+               *(u_int32_t *)(void *)info =
+                   ntohl(*(u_int32_t *)(void *)(ct->ct_u.ct_mcallc +
+                   3 * BYTES_PER_XDR_UNIT));
+               break;
+
+       case CLSET_PROG:
+               *(u_int32_t *)(void *)(ct->ct_u.ct_mcallc +
+                   3 * BYTES_PER_XDR_UNIT) =
+                   htonl(*(u_int32_t *)(void *)info);
+               break;
+
+       default:
+               release_fd_lock(ct->ct_fd, mask);
+               return (FALSE);
+       }
+       release_fd_lock(ct->ct_fd, mask);
+       return (TRUE);
+}
+
+
+static void
+clnt_vc_destroy(cl)
+       CLIENT *cl;
+{
+       struct ct_data *ct;
+#ifdef _REENTRANT
+       int ct_fd;
+       sigset_t mask;
+#endif
+       sigset_t newmask;
+
+       _DIAGASSERT(cl != NULL);
+
+       ct = (struct ct_data *) cl->cl_private;
+       ct_fd = ct->ct_fd;
+
+       sigfillset(&newmask);
+       thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
+       mutex_lock(&clnt_fd_lock);
+#ifdef _REENTRANT
+       while (vc_fd_locks[ct_fd])
+               cond_wait(&vc_cv[ct_fd], &clnt_fd_lock);
+#endif
+       if (ct->ct_closeit && ct->ct_fd != -1) {
+               (void)close(ct->ct_fd);
+       }
+       XDR_DESTROY(&(ct->ct_xdrs));
+       if (ct->ct_addr.buf)
+               free(ct->ct_addr.buf);
+       mem_free(ct, sizeof(struct ct_data));
+       mem_free(cl, sizeof(CLIENT));
+       mutex_unlock(&clnt_fd_lock);
+       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);
+
+       cond_signal(&vc_cv[ct_fd]);
+}
+
+/*
+ * Interface between xdr serializer and tcp connection.
+ * Behaves like the system calls, read & write, but keeps some error state
+ * around for the rpc level.
+ */
+static int
+read_vc(ctp, buf, len)
+       caddr_t ctp;
+       caddr_t buf;
+       int len;
+{
+       struct ct_data *ct = (struct ct_data *)(void *)ctp;
+       struct pollfd fd;
+       struct timespec ts;
+
+       if (len == 0)
+               return (0);
+
+       TIMEVAL_TO_TIMESPEC(&ct->ct_wait, &ts);
+       fd.fd = ct->ct_fd;
+       fd.events = POLLIN;
+       for (;;) {
+               switch (pollts(&fd, 1, &ts, NULL)) {
+               case 0:
+                       ct->ct_error.re_status = RPC_TIMEDOUT;
+                       return (-1);
+
+               case -1:
+                       if (errno == EINTR)
+                               continue;
+                       ct->ct_error.re_status = RPC_CANTRECV;
+                       ct->ct_error.re_errno = errno;
+                       return (-1);
+               }
+               break;
+       }
+       switch (len = read(ct->ct_fd, buf, (size_t)len)) {
+
+       case 0:
+               /* premature eof */
+               ct->ct_error.re_errno = ECONNRESET;
+               ct->ct_error.re_status = RPC_CANTRECV;
+               len = -1;  /* it's really an error */
+               break;
+
+       case -1:
+               ct->ct_error.re_errno = errno;
+               ct->ct_error.re_status = RPC_CANTRECV;
+               break;
+       }
+       return (len);
+}
+
+static int
+write_vc(ctp, buf, len)
+       caddr_t ctp;
+       caddr_t buf;
+       int len;
+{
+       struct ct_data *ct = (struct ct_data *)(void *)ctp;
+       int i, cnt;
+
+       for (cnt = len; cnt > 0; cnt -= i, buf += i) {
+               if ((i = write(ct->ct_fd, buf, (size_t)cnt)) == -1) {
+                       ct->ct_error.re_errno = errno;
+                       ct->ct_error.re_status = RPC_CANTSEND;
+                       return (-1);
+               }
+       }
+       return (len);
+}
+
+static struct clnt_ops *
+clnt_vc_ops()
+{
+       static struct clnt_ops ops;
+#ifdef _REENTRANT
+       extern mutex_t  ops_lock;
+       sigset_t mask;
+#endif
+       sigset_t newmask;
+
+       /* VARIABLES PROTECTED BY ops_lock: ops */
+
+       sigfillset(&newmask);
+       thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
+       mutex_lock(&ops_lock);
+       if (ops.cl_call == NULL) {
+               ops.cl_call = clnt_vc_call;
+               ops.cl_abort = clnt_vc_abort;
+               ops.cl_geterr = clnt_vc_geterr;
+               ops.cl_freeres = clnt_vc_freeres;
+               ops.cl_destroy = clnt_vc_destroy;
+               ops.cl_control = clnt_vc_control;
+       }
+       mutex_unlock(&ops_lock);
+       thr_sigsetmask(SIG_SETMASK, &(mask), NULL);
+       return (&ops);
+}
+
+/*
+ * Make sure that the time is not garbage.   -1 value is disallowed.
+ * Note this is different from time_not_ok in clnt_dg.c
+ */
+static bool_t
+time_not_ok(t)
+       struct timeval *t;
+{
+
+       _DIAGASSERT(t != NULL);
+
+       return (t->tv_sec <= -1 || t->tv_sec > 100000000 ||
+               t->tv_usec <= -1 || t->tv_usec > 1000000);
+}
diff --git a/lib/nbsd_libc/rpc/getnetconfig.3 b/lib/nbsd_libc/rpc/getnetconfig.3
new file mode 100644 (file)
index 0000000..cd3c30e
--- /dev/null
@@ -0,0 +1,183 @@
+.\"    @(#)getnetconfig.3n 1.28 93/06/02 SMI; from SVr4
+.\"    $NetBSD: getnetconfig.3,v 1.7 2003/04/16 13:34:43 wiz Exp $
+.\" Copyright 1989 AT&T
+.Dd April 22, 2000
+.Dt GETNETCONFIG 3
+.Os
+.Sh NAME
+.Nm getnetconfig ,
+.Nm setnetconfig ,
+.Nm endnetconfig ,
+.Nm getnetconfigent ,
+.Nm freenetconfigent ,
+.Nm nc_perror ,
+.Nm nc_sperror
+.Nd get network configuration database entry
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In netconfig.h
+.Ft struct netconfig *
+.Fn getnetconfig "void *handlep"
+.Ft void *
+.Fn setnetconfig "void"
+.Ft int
+.Fn endnetconfig "void *handlep"
+.Ft struct netconfig *
+.Fn getnetconfigent "const char *netid"
+.Ft void
+.Fn freenetconfigent "struct netconfig *netconfigp"
+.Ft void
+.Fn nc_perror "const char *msg"
+.Ft char *
+.Fn nc_sperror "void"
+.Sh DESCRIPTION
+The library routines described on this page
+provide the application access to
+the system network configuration database,
+.Pa /etc/netconfig .
+.Bd -literal
+struct netconfig {
+        char *nc_netid;              /* Network ID */
+        unsigned long nc_semantics;  /* Semantics */
+        unsigned long nc_flag;       /* Flags */
+        char *nc_protofmly;          /* Protocol family */
+        char *nc_proto;              /* Protocol name */
+        char *nc_device;             /* Network device pathname */
+        unsigned long nc_nlookups;   /* Number of directory lookup libs */
+        char **nc_lookups;           /* Names of the libraries */
+};
+.Ed
+.Pp
+.Fn getnetconfig
+returns a pointer to the
+current entry in the
+.Pa netconfig
+database, formatted as a struct netconfig.
+Successive calls will return successive netconfig
+entries in the netconfig database.
+.Fn getnetconfig
+can be used to search the entire netconfig
+file.
+.Fn getnetconfig
+returns
+.Dv NULL
+at the end of the file.
+.Fa handlep
+is the handle obtained through
+.Fn setnetconfig .
+.Pp
+A call to
+.Fn setnetconfig
+has the effect of ``binding'' to or
+``rewinding'' the netconfig database.
+.Fn setnetconfig
+must be called before the first call to
+.Fn getnetconfig
+and may be called at any other time.
+.Fn setnetconfig
+need not be called before a call to
+.Fn getnetconfigent .
+.Fn setnetconfig
+returns a unique handle to be used by
+.Fn getnetconfig .
+.Pp
+.Fn endnetconfig
+should be called when processing is complete to release resources for reuse.
+.Fa handlep
+is the handle obtained through
+.Fn setnetconfig .
+Programmers should be aware, however, that the last call to
+.Fn endnetconfig
+frees all memory allocated by
+.Fn getnetconfig
+for the
+struct netconfig data structure.
+.Fn endnetconfig
+may not be called before
+.Fn setnetconfig .
+.Pp
+.Fn getnetconfigent
+returns a pointer
+to the netconfig structure corresponding
+to
+.Fa netid .
+It returns
+.Dv NULL
+if
+.Fa netid
+is invalid
+(that is, does not name an entry in the netconfig database).
+.Pp
+.Fn freenetconfigent
+frees the netconfig structure pointed to by
+.Fa netconfigp
+(previously returned by
+.Fn getnetconfigent ) .
+.Pp
+.Fn nc_perror
+prints a message to the standard error indicating why any of the
+above routines failed.
+The message is prepended with the string
+.Fa msg
+and a colon.
+A newline character is appended at the end of the message.
+.Pp
+.Fn nc_sperror
+is similar to
+.Fn nc_perror
+but instead of sending the message
+to the standard error, will return a pointer to a string that
+contains the error message.
+.Pp
+.Fn nc_perror
+and
+.Fn nc_sperror
+can also be used with the
+.Va NETPATH
+access routines defined in
+.Xr getnetpath 3 .
+.Sh RETURN VALUES
+.Fn setnetconfig
+returns a unique handle to be used by
+.Fn getnetconfig .
+In the case of an error,
+.Fn setnetconfig
+returns NULL and
+.Fn nc_perror
+or
+.Fn nc_sperror
+can be used to print the reason for failure.
+.Pp
+.Fn getnetconfig
+returns a pointer to the current entry in the netconfig
+database, formatted as a struct netconfig.
+.Fn getnetconfig
+returns NULL
+at the end of the file, or upon failure.
+.Pp
+.Fn endnetconfig
+returns 0 on success and -1 on failure
+(for example, if
+.Fn setnetconfig
+was not called previously).
+.Pp
+On success,
+.Fn getnetconfigent
+returns a pointer to the
+.Li struct netconfig
+structure corresponding to
+.Ar netid ;
+otherwise it returns
+.Dv NULL .
+.Pp
+.Fn nc_sperror
+returns a pointer to a buffer which contains the error message string.
+This buffer is overwritten on each call.
+In multithreaded applications, this buffer is
+implemented as thread-specific data.
+.Sh FILES
+.Pa /etc/netconfig
+.Sh SEE ALSO
+.Xr getnetpath 3 ,
+.Xr netconfig 5
diff --git a/lib/nbsd_libc/rpc/getnetconfig.c b/lib/nbsd_libc/rpc/getnetconfig.c
new file mode 100644 (file)
index 0000000..7577673
--- /dev/null
@@ -0,0 +1,695 @@
+/*     $NetBSD: getnetconfig.c,v 1.18 2010/12/08 02:06:38 joerg Exp $  */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user or with the express written consent of
+ * Sun Microsystems, Inc.
+ *
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ *
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ *
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ *
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ *
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static        char sccsid[] = "@(#)getnetconfig.c      1.12 91/12/19 SMI";
+#else
+__RCSID("$NetBSD: getnetconfig.c,v 1.18 2010/12/08 02:06:38 joerg Exp $");
+#endif
+#endif
+
+/*
+ * Copyright (c) 1989 by Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <stdio.h>
+#include <assert.h>
+#include <errno.h>
+#include <netconfig.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <rpc/rpc.h>
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(getnetconfig,_getnetconfig)
+__weak_alias(setnetconfig,_setnetconfig)
+__weak_alias(endnetconfig,_endnetconfig)
+__weak_alias(getnetconfigent,_getnetconfigent)
+__weak_alias(freenetconfigent,_freenetconfigent)
+__weak_alias(nc_perror,_nc_perror)
+__weak_alias(nc_sperror,_nc_sperror)
+#endif
+
+/*
+ * The five library routines in this file provide application access to the
+ * system network configuration database, /etc/netconfig.  In addition to the
+ * netconfig database and the routines for accessing it, the environment
+ * variable NETPATH and its corresponding routines in getnetpath.c may also be
+ * used to specify the network transport to be used.
+ */
+
+
+/*
+ * netconfig errors
+ */
+
+#define NC_NONETCONFIG ENOENT
+#define NC_NOMEM       ENOMEM
+#define NC_NOTINIT     EINVAL      /* setnetconfig was not called first */
+#define NC_BADFILE     EBADF       /* format for netconfig file is bad */
+
+/*
+ * semantics as strings (should be in netconfig.h)
+ */
+#define NC_TPI_CLTS_S      "tpi_clts"
+#define        NC_TPI_COTS_S       "tpi_cots"
+#define        NC_TPI_COTS_ORD_S   "tpi_cots_ord"
+#define        NC_TPI_RAW_S        "tpi_raw"
+
+/*
+ * flags as characters (also should be in netconfig.h)
+ */
+#define        NC_NOFLAG_C     '-'
+#define        NC_VISIBLE_C    'v'
+#define        NC_BROADCAST_C  'b'
+
+/*
+ * Character used to indicate there is no name-to-address lookup library
+ */
+#define NC_NOLOOKUP    "-"
+
+static const char * const _nc_errors[] = {
+       "Netconfig database not found",
+       "Not enough memory",
+       "Not initialized",
+       "Netconfig database has invalid format"
+};
+
+struct netconfig_info {
+       int             eof;    /* all entries has been read */
+       int             ref;    /* # of times setnetconfig() has been called */
+       struct netconfig_list   *head;  /* head of the list */
+       struct netconfig_list   *tail;  /* last of the list */
+};
+
+struct netconfig_list {
+       char                    *linep; /* hold line read from netconfig */
+       struct netconfig        *ncp;
+       struct netconfig_list   *next;
+};
+
+struct netconfig_vars {
+           int   valid;        /* token that indicates valid netconfig_vars */
+           int   flag;         /* first time flag */
+           struct netconfig_list *nc_configs;
+                                /* pointer to the current netconfig entry */
+};
+
+#define NC_VALID       0xfeed
+#define NC_STORAGE     0xf00d
+#define NC_INVALID     0
+
+
+static int *__nc_error __P((void));
+static int parse_ncp __P((char *, struct netconfig *));
+static struct netconfig *dup_ncp __P((struct netconfig *));
+
+
+static FILE *nc_file;          /* for netconfig db */
+static struct netconfig_info   ni = { 0, 0, NULL, NULL};
+
+#define MAXNETCONFIGLINE    1000
+
+#ifdef _REENTRANT
+static thread_key_t nc_key;
+static once_t nc_once = ONCE_INITIALIZER;
+
+static void 
+__nc_error_setup(void)
+{
+       thr_keycreate(&nc_key, free);
+}
+#endif
+
+static int *
+__nc_error()
+{
+#ifdef _REENTRANT
+       int *nc_addr = NULL;
+#endif
+       static int nc_error = 0;
+
+#ifdef _REENTRANT
+       if (__isthreaded == 0)
+               return &nc_error;
+       thr_once(&nc_once, __nc_error_setup);
+       nc_addr = thr_getspecific(nc_key) ;
+       if (nc_addr == NULL) {
+               nc_addr = malloc(sizeof (int));
+               if (nc_addr == NULL)
+                       return &nc_error;
+               if (thr_setspecific(nc_key, (void *) nc_addr) != 0) {
+                       if (nc_addr)
+                               free(nc_addr);
+                       return &nc_error;
+               }
+               *nc_addr = 0;
+       }
+       return nc_addr;
+#else
+       return &nc_error;
+#endif
+}
+
+#define nc_error        (*(__nc_error()))
+/*
+ * A call to setnetconfig() establishes a /etc/netconfig "session".  A session
+ * "handle" is returned on a successful call.  At the start of a session (after
+ * a call to setnetconfig()) searches through the /etc/netconfig database will
+ * proceed from the start of the file.  The session handle must be passed to
+ * getnetconfig() to parse the file.  Each call to getnetconfig() using the
+ * current handle will process one subsequent entry in /etc/netconfig.
+ * setnetconfig() must be called before the first call to getnetconfig().
+ * (Handles are used to allow for nested calls to setnetpath()).
+ *
+ * A new session is established with each call to setnetconfig(), with a new
+ * handle being returned on each call.  Previously established sessions remain
+ * active until endnetconfig() is called with that session's handle as an
+ * argument.
+ *
+ * setnetconfig() need *not* be called before a call to getnetconfigent().
+ * setnetconfig() returns a NULL pointer on failure (for example, if
+ * the netconfig database is not present).
+ */
+void *
+setnetconfig()
+{
+       struct netconfig_vars *nc_vars;
+
+       if ((nc_vars = malloc(sizeof(*nc_vars))) == NULL) {
+               return(NULL);
+       }
+
+       /*
+        * For multiple calls, i.e. nc_file is not NULL, we just return the
+        * handle without reopening the netconfig db.
+        */
+       ni.ref++;
+       if ((nc_file != NULL) || (nc_file = fopen(NETCONFIG, "r")) != NULL) {
+               nc_vars->valid = NC_VALID;
+               nc_vars->flag = 0;
+               nc_vars->nc_configs = ni.head;
+               return ((void *)nc_vars);
+       }
+       ni.ref--;
+       nc_error = NC_NONETCONFIG;
+       free(nc_vars);
+       return (NULL);
+}
+
+
+/*
+ * When first called, getnetconfig() returns a pointer to the first entry in
+ * the netconfig database, formatted as a struct netconfig.  On each subsequent
+ * call, getnetconfig() returns a pointer to the next entry in the database.
+ * getnetconfig() can thus be used to search the entire netconfig file.
+ * getnetconfig() returns NULL at end of file.
+ */
+
+struct netconfig *
+getnetconfig(handlep)
+       void *handlep;
+{
+       struct netconfig_vars *ncp = (struct netconfig_vars *)handlep;
+       char *stringp;          /* tmp string pointer */
+       struct netconfig_list   *list;
+       struct netconfig *np;
+
+       /*
+        * Verify that handle is valid
+        */
+       if (ncp == NULL || nc_file == NULL) {
+               nc_error = NC_NOTINIT;
+               return (NULL);
+       }
+
+       switch (ncp->valid) {
+       case NC_VALID:
+               /*
+                * If entry has already been read into the list,
+                * we return the entry in the linked list.
+                * If this is the first time call, check if there are any
+                * entries in linked list.  If no entries, we need to read the
+                * netconfig db.
+                * If we have been here and the next entry is there, we just
+                * return it.
+                */
+               if (ncp->flag == 0) {   /* first time */
+                       ncp->flag = 1;
+                       ncp->nc_configs = ni.head;
+                       if (ncp->nc_configs != NULL) /* entry already exist */
+                               return(ncp->nc_configs->ncp);
+               }
+               else if (ncp->nc_configs != NULL &&
+                   ncp->nc_configs->next != NULL) {
+                       ncp->nc_configs = ncp->nc_configs->next;
+                       return(ncp->nc_configs->ncp);
+               }
+
+               /*
+                * If we cannot find the entry in the list and is end of file,
+                * we give up.
+                */
+               if (ni.eof == 1)
+                       return(NULL);
+               break;
+       default:
+               nc_error = NC_NOTINIT;
+               return (NULL);
+       }
+
+       stringp = malloc(MAXNETCONFIGLINE);
+       if (stringp == NULL)
+               return (NULL);
+
+#ifdef MEM_CHK
+       if (malloc_verify() == 0) {
+               fprintf(stderr, "memory heap corrupted in getnetconfig\n");
+               exit(1);
+       }
+#endif
+
+       /*
+        * Read a line from netconfig file.
+        */
+       do {
+               if (fgets(stringp, MAXNETCONFIGLINE, nc_file) == NULL) {
+                       free(stringp);
+                       ni.eof = 1;
+                       return (NULL);
+               }
+       } while (*stringp == '#');
+
+       list = malloc(sizeof(*list));
+       if (list == NULL) {
+               free(stringp);
+               return(NULL);
+       }
+       np = malloc(sizeof(*np));
+       if (np == NULL) {
+               free(stringp);
+               free(list);
+               return(NULL);
+       }
+       list->ncp = np;
+       list->next = NULL;
+       list->ncp->nc_lookups = NULL;
+       list->linep = stringp;
+       if (parse_ncp(stringp, list->ncp) == -1) {
+               free(stringp);
+               free(np);
+               free(list);
+               return (NULL);
+       } else {
+               /*
+                * If this is the first entry that's been read, it is the
+                * head of the list.  If not, put the entry at the end of
+                * the list.  Reposition the current pointer of the handle to
+                * the last entry in the list.
+                */
+               if (ni.head == NULL)            /* first entry */
+                       ni.head = ni.tail = list;
+               else {
+                       ni.tail->next = list;
+                       ni.tail = ni.tail->next;
+               }
+               ncp->nc_configs = ni.tail;
+               return(ni.tail->ncp);
+       }
+}
+
+/*
+ * endnetconfig() may be called to "unbind" or "close" the netconfig database
+ * when processing is complete, releasing resources for reuse.  endnetconfig()
+ * may not be called before setnetconfig().  endnetconfig() returns 0 on
+ * success and -1 on failure (for example, if setnetconfig() was not called
+ * previously).
+ */
+int
+endnetconfig(handlep)
+       void *handlep;
+{
+       struct netconfig_vars *nc_handlep = (struct netconfig_vars *)handlep;
+
+       struct netconfig_list *q, *p;
+
+       /*
+        * Verify that handle is valid
+        */
+       if (nc_handlep == NULL || (nc_handlep->valid != NC_VALID &&
+           nc_handlep->valid != NC_STORAGE)) {
+               nc_error = NC_NOTINIT;
+               return (-1);
+       }
+
+       /*
+        * Return 0 if anyone still needs it.
+        */
+       nc_handlep->valid = NC_INVALID;
+       nc_handlep->flag = 0;
+       nc_handlep->nc_configs = NULL;
+       if (--ni.ref > 0) {
+               free(nc_handlep);
+               return(0);
+       }
+
+       /*
+        * Noone needs these entries anymore, then frees them.
+        * Make sure all info in netconfig_info structure has been
+        * reinitialized.
+        */
+       q = p = ni.head;
+       ni.eof = ni.ref = 0;
+       ni.head = NULL;
+       ni.tail = NULL;
+       while (q) {
+               p = q->next;
+               if (q->ncp->nc_lookups != NULL) free(q->ncp->nc_lookups);
+               free(q->ncp);
+               free(q->linep);
+               free(q);
+               q = p;
+       }
+       free(nc_handlep);
+
+       fclose(nc_file);
+       nc_file = NULL;
+       return (0);
+}
+
+/*
+ * getnetconfigent(netid) returns a pointer to the struct netconfig structure
+ * corresponding to netid.  It returns NULL if netid is invalid (that is, does
+ * not name an entry in the netconfig database).  It returns NULL and sets
+ * errno in case of failure (for example, if the netconfig database cannot be
+ * opened).
+ */
+
+struct netconfig *
+getnetconfigent(netid)
+       const char *netid;
+{
+       FILE *file;                     /* NETCONFIG db's file pointer */
+       char *linep;                    /* holds current netconfig line */
+       char *stringp;                  /* temporary string pointer */
+       struct netconfig *ncp = NULL;   /* returned value */
+       struct netconfig_list *list;    /* pointer to cache list */
+
+       if (netid == NULL || strlen(netid) == 0)
+               return (NULL);
+
+       /*
+        * Look up table if the entries have already been read and parsed in
+        * getnetconfig(), then copy this entry into a buffer and return it.
+        * If we cannot find the entry in the current list and there are more
+        * entries in the netconfig db that has not been read, we then read the
+        * db and try find the match netid.
+        * If all the netconfig db has been read and placed into the list and
+        * there is no match for the netid, return NULL.
+        */
+       if (ni.head != NULL) {
+               for (list = ni.head; list; list = list->next) {
+                       if (strcmp(list->ncp->nc_netid, netid) == 0)
+                           return(dup_ncp(list->ncp));
+               }
+               if (ni.eof == 1)        /* that's all the entries */
+                       return(NULL);
+       }
+
+       if ((file = fopen(NETCONFIG, "r")) == NULL)
+           return (NULL);
+
+       if ((linep = malloc(MAXNETCONFIGLINE)) == NULL) {
+               fclose(file);
+               return (NULL);
+       }
+       do {
+               ptrdiff_t len;
+               char *tmpp;     /* tmp string pointer */
+
+               do {
+                       if ((stringp = fgets(linep, MAXNETCONFIGLINE, file))
+                           == NULL)
+                               break;
+               } while (*stringp == '#');
+               if (stringp == NULL)    /* eof */
+                       break;
+               if ((tmpp = strpbrk(stringp, "\t ")) == NULL) {
+                                       /* can't parse file */
+                       nc_error = NC_BADFILE;
+                       break;
+               }
+               if (strlen(netid) == (size_t) (len = tmpp - stringp) && /* a match */
+                   strncmp(stringp, netid, (size_t)len) == 0) {
+                       if ((ncp = malloc(sizeof(*ncp))) == NULL)
+                               break;
+                       ncp->nc_lookups = NULL;
+                       if (parse_ncp(linep, ncp) == -1) {
+                               free(ncp);
+                               ncp = NULL;
+                       }
+                       break;
+               }
+       } while (stringp != NULL);
+       if (ncp == NULL)
+               free(linep);
+       fclose(file);
+       return(ncp);
+}
+
+/*
+ * freenetconfigent(netconfigp) frees the netconfig structure pointed to by
+ * netconfigp (previously returned by getnetconfigent()).
+ */
+
+void
+freenetconfigent(netconfigp)
+       struct netconfig *netconfigp;
+{
+       if (netconfigp != NULL) {
+                               /* holds all netconfigp's strings */
+               free(netconfigp->nc_netid);
+               if (netconfigp->nc_lookups != NULL)
+                       free(netconfigp->nc_lookups);
+               free(netconfigp);
+       }
+}
+
+/*
+ * Parse line and stuff it in a struct netconfig
+ * Typical line might look like:
+ *     udp tpi_cots vb inet udp /dev/udp /usr/lib/ip.so,/usr/local/ip.so
+ *
+ * We return -1 if any of the tokens don't parse, or malloc fails.
+ *
+ * Note that we modify stringp (putting NULLs after tokens) and
+ * we set the ncp's string field pointers to point to these tokens within
+ * stringp.
+ */
+
+static int
+parse_ncp(stringp, ncp)
+       char *stringp;          /* string to parse */
+       struct netconfig *ncp;  /* where to put results */
+{
+       char    *tokenp;        /* for processing tokens */
+       char    *lasts;
+
+       _DIAGASSERT(stringp != NULL);
+       _DIAGASSERT(ncp != NULL);
+
+       nc_error = NC_BADFILE;
+                       /* nearly anything that breaks is for this reason */
+       stringp[strlen(stringp)-1] = '\0';      /* get rid of newline */
+       /* netid */
+       if ((ncp->nc_netid = strtok_r(stringp, "\t ", &lasts)) == NULL)
+               return (-1);
+
+       /* semantics */
+       if ((tokenp = strtok_r(NULL, "\t ", &lasts)) == NULL)
+               return (-1);
+       if (strcmp(tokenp, NC_TPI_COTS_ORD_S) == 0)
+               ncp->nc_semantics = NC_TPI_COTS_ORD;
+       else if (strcmp(tokenp, NC_TPI_COTS_S) == 0)
+               ncp->nc_semantics = NC_TPI_COTS;
+       else if (strcmp(tokenp, NC_TPI_CLTS_S) == 0)
+               ncp->nc_semantics = NC_TPI_CLTS;
+       else if (strcmp(tokenp, NC_TPI_RAW_S) == 0)
+               ncp->nc_semantics = NC_TPI_RAW;
+       else
+               return (-1);
+
+       /* flags */
+       if ((tokenp = strtok_r(NULL, "\t ", &lasts)) == NULL)
+               return (-1);
+       for (ncp->nc_flag = NC_NOFLAG; *tokenp != '\0'; tokenp++) {
+               switch (*tokenp) {
+               case NC_NOFLAG_C:
+                       break;
+               case NC_VISIBLE_C:
+                       ncp->nc_flag |= NC_VISIBLE;
+                       break;
+               case NC_BROADCAST_C:
+                       ncp->nc_flag |= NC_BROADCAST;
+                       break;
+               default:
+                       return (-1);
+               }
+       }
+       /* protocol family */
+       if ((ncp->nc_protofmly = strtok_r(NULL, "\t ", &lasts)) == NULL)
+               return (-1);
+       /* protocol name */
+       if ((ncp->nc_proto = strtok_r(NULL, "\t ", &lasts)) == NULL)
+               return (-1);
+       /* network device */
+       if ((ncp->nc_device = strtok_r(NULL, "\t ", &lasts)) == NULL)
+               return (-1);
+       if ((tokenp = strtok_r(NULL, "\t ", &lasts)) == NULL)
+               return (-1);
+       if (strcmp(tokenp, NC_NOLOOKUP) == 0) {
+               ncp->nc_nlookups = 0;
+               ncp->nc_lookups = NULL;
+       } else {
+               char *cp;           /* tmp string */
+
+               if (ncp->nc_lookups != NULL)    /* from last visit */
+                       free(ncp->nc_lookups);
+               /* preallocate one string pointer */
+               ncp->nc_lookups = malloc(sizeof(*ncp->nc_lookups));
+               ncp->nc_nlookups = 0;
+               while ((cp = tokenp) != NULL) {
+                       tokenp = _get_next_token(cp, ',');
+                       ncp->nc_lookups[(size_t)ncp->nc_nlookups++] = cp;
+                       ncp->nc_lookups = (char **)
+                           realloc(ncp->nc_lookups,
+                           (size_t)(ncp->nc_nlookups+1) *sizeof(char *));      
+                                               /* for next loop */
+               }
+       }
+       return (0);
+}
+
+/*
+ * Returns a string describing the reason for failure.
+ */
+char *
+nc_sperror()
+{
+       const char *message;
+
+       switch(nc_error) {
+       case NC_NONETCONFIG:
+               message = _nc_errors[0];
+               break;
+       case NC_NOMEM:
+               message = _nc_errors[1];
+               break;
+       case NC_NOTINIT:
+               message = _nc_errors[2];
+               break;
+       case NC_BADFILE:
+               message = _nc_errors[3];
+               break;
+       default:
+               message = "Unknown network selection error";
+       }
+       return __UNCONST(message);
+}
+
+/*
+ * Prints a message onto standard error describing the reason for failure.
+ */
+void
+nc_perror(s)
+       const char *s;
+{
+
+       _DIAGASSERT(s != NULL);
+
+       fprintf(stderr, "%s: %s", s, nc_sperror());
+}
+
+/*
+ * Duplicates the matched netconfig buffer.
+ */
+static struct netconfig *
+       dup_ncp(ncp)
+       struct netconfig        *ncp;
+{
+       struct netconfig        *p;
+       char    *tmp;
+       u_int   i;
+
+       _DIAGASSERT(ncp != NULL);
+
+       if ((tmp = malloc(MAXNETCONFIGLINE)) == NULL)
+               return(NULL);
+       if ((p = malloc(sizeof(*p))) == NULL) {
+               free(tmp);
+               return(NULL);
+       }
+       /*
+        * First we dup all the data from matched netconfig buffer.  Then we
+        * adjust some of the member pointer to a pre-allocated buffer where
+        * contains part of the data.
+        * To follow the convention used in parse_ncp(), we store all the
+        * necessary information in the pre-allocated buffer and let each
+        * of the netconfig char pointer member point to the right address
+        * in the buffer.
+        */
+       *p = *ncp;
+       p->nc_netid = (char *)strcpy(tmp,ncp->nc_netid);
+       tmp = strchr(tmp, '\0') + 1;
+       p->nc_protofmly = (char *)strcpy(tmp,ncp->nc_protofmly);
+       tmp = strchr(tmp, '\0') + 1;
+       p->nc_proto = (char *)strcpy(tmp,ncp->nc_proto);
+       tmp = strchr(tmp, '\0') + 1;
+       p->nc_device = (char *)strcpy(tmp,ncp->nc_device);
+       p->nc_lookups = malloc((size_t)(p->nc_nlookups+1) * sizeof(char *));
+       if (p->nc_lookups == NULL) {
+               free(p->nc_netid);
+               free(p);
+               return(NULL);
+       }
+       for (i=0; i < p->nc_nlookups; i++) {
+               tmp = strchr(tmp, '\0') + 1;
+               p->nc_lookups[i] = strcpy(tmp,ncp->nc_lookups[i]);
+       }
+       return(p);
+}
diff --git a/lib/nbsd_libc/rpc/getnetpath.3 b/lib/nbsd_libc/rpc/getnetpath.3
new file mode 100644 (file)
index 0000000..b63116a
--- /dev/null
@@ -0,0 +1,124 @@
+.\"    @(#)getnetpath.3n 1.26 93/05/07 SMI; from SVr4
+.\"    $NetBSD: getnetpath.3,v 1.6 2003/04/16 13:34:43 wiz Exp $
+.\" Copyright 1989 AT&T
+.Dd April 22, 2000
+.Dt GETNETPATH 3
+.Os
+.Sh NAME
+.Nm getnetpath ,
+.Nm setnetpath ,
+.Nm endnetpath
+.Nd get /etc/netconfig entry corresponding to NETPATH component
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In netconfig.h
+.Ft struct netconfig *
+.Fn getnetpath "void *handlep"
+.Ft void *
+.Fn setnetpath "void"
+.Ft int
+.Fn endnetpath "void *handlep"
+.Sh DESCRIPTION
+The routines described in this page provide the application access to the system
+network configuration database,
+.Pa /etc/netconfig ,
+as it is
+.Dq filtered
+by the NETPATH
+environment variable (see
+.Xr environ 7 ) .
+See
+.Xr getnetconfig 3
+for other routines that also access the
+network configuration database directly.
+The NETPATH variable is a list of colon-separated network identifiers.
+.Pp
+.Fn getnetpath
+returns a pointer to the
+netconfig database entry corresponding to the first valid
+NETPATH component.
+The netconfig entry is formatted as a struct netconfig.
+On each subsequent call,
+.Fn getnetpath
+returns a pointer to the netconfig entry that corresponds to the next
+valid NETPATH component.
+.Fn getnetpath
+can thus be used to search the netconfig database for all networks
+included in the NETPATH variable.
+When NETPATH has been exhausted,
+.Fn getnetpath
+returns NULL.
+.Pp
+A call to
+.Fn setnetpath
+.Dq binds
+to or
+.Dq rewinds
+NETPATH.
+.Fn setnetpath
+must be called before the first call to
+.Fn getnetpath
+and may be called at any other time.
+It returns a handle that is used by
+.Fn getnetpath .
+.Pp
+.Fn getnetpath
+silently ignores invalid NETPATH
+components.
+A NETPATH component is invalid if there is no corresponding
+entry in the netconfig database.
+.Pp
+If the NETPATH variable is unset,
+.Fn getnetpath
+behaves as if NETPATH
+were set to the sequence of
+.Dq default
+or
+.Dq visible
+networks in the netconfig database, in the
+order in which they are listed.
+.\"This proviso holds also for this
+.\"whole manpage.
+.Pp
+.Fn endnetpath
+may be called to
+.Dq unbind
+from NETPATH
+when processing is complete, releasing resources for reuse.
+Programmers should be aware, however, that
+.Fn endnetpath
+frees all memory allocated by
+.Fn getnetpath
+for the struct netconfig data structure.
+.Sh RETURN VALUES
+.Fn setnetpath
+returns a handle that is used by
+.Fn getnetpath .
+In case of an error,
+.Fn setnetpath
+returns NULL.
+.Pp
+.Fn endnetpath
+returns 0 on success and -1 on failure
+(for example, if
+.Fn setnetpath
+was not called previously).
+.Fn nc_perror
+or
+.Fn nc_sperror
+can be used to print out the reason for failure.
+See
+.Xr getnetconfig 3 .
+.Pp
+When first called,
+.Fn getnetpath
+returns a pointer to the netconfig database entry corresponding to the first
+valid NETPATH component.
+When NETPATH has been exhausted,
+.Fn getnetpath
+returns NULL.
+.Sh SEE ALSO
+.Xr getnetconfig 3 ,
+.Xr netconfig 5 ,
+.Xr environ 7
diff --git a/lib/nbsd_libc/rpc/getnetpath.c b/lib/nbsd_libc/rpc/getnetpath.c
new file mode 100644 (file)
index 0000000..2a43737
--- /dev/null
@@ -0,0 +1,287 @@
+/*     $NetBSD: getnetpath.c,v 1.14 2008/05/24 16:04:15 christos Exp $ */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user or with the express written consent of
+ * Sun Microsystems, Inc.
+ *
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ *
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ *
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ *
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ *
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static        char sccsid[] = "@(#)getnetpath.c        1.11 91/12/19 SMI";
+#else
+__RCSID("$NetBSD: getnetpath.c,v 1.14 2008/05/24 16:04:15 christos Exp $");
+#endif
+#endif
+
+/*
+ * Copyright (c) 1989 by Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+#include <stdio.h>
+#include <assert.h>
+#include <errno.h>
+#include <netconfig.h>
+#include <stdlib.h>
+#include <string.h>
+#include <syslog.h>
+
+#ifdef __weak_alias
+__weak_alias(getnetpath,_getnetpath)
+__weak_alias(setnetpath,_setnetpath)
+__weak_alias(endnetpath,_endnetpath)
+#endif
+
+/*
+ * internal structure to keep track of a netpath "session"
+ */
+struct netpath_chain {
+       struct netconfig *ncp;                  /* an nconf entry */
+       struct netpath_chain *nchain_next;      /* next nconf entry allocated */
+};
+
+
+struct netpath_vars {
+       int   valid;            /* token that indicates a valid netpath_vars */
+       void *nc_handlep;       /* handle for current netconfig "session" */
+       char *netpath;          /* pointer to current view-point in NETPATH */
+       char *netpath_start;    /* pointer to start of our copy of NETPATH */
+       struct netpath_chain *ncp_list;  /* list of nconfs allocated this session*/
+};
+
+#define NP_VALID       0xf00d
+#define NP_INVALID     0
+
+char *_get_next_token __P((char *, int));
+
+
+/*
+ * A call to setnetpath() establishes a NETPATH "session".  setnetpath()
+ * must be called before the first call to getnetpath().  A "handle" is
+ * returned to distinguish the session; this handle should be passed
+ * subsequently to getnetpath().  (Handles are used to allow for nested calls
+ * to setnetpath()).
+ * If setnetpath() is unable to establish a session (due to lack of memory
+ * resources, or the absence of the /etc/netconfig file), a NULL pointer is
+ * returned.
+ */
+
+void *
+setnetpath()
+{
+       struct netpath_vars *np_sessionp;   /* this session's variables */
+       char *npp;                              /* NETPATH env variable */
+
+#ifdef MEM_CHK
+       malloc_debug(1);
+#endif
+
+       if ((np_sessionp = malloc(sizeof(*np_sessionp))) == NULL)
+               return (NULL);
+       if ((np_sessionp->nc_handlep = setnetconfig()) == NULL) {
+               free(np_sessionp);
+               syslog (LOG_ERR, "rpc: failed to open " NETCONFIG);
+               return (NULL);
+       }
+       np_sessionp->valid = NP_VALID;
+       np_sessionp->ncp_list = NULL;
+       if ((npp = getenv(NETPATH)) == NULL)
+               np_sessionp->netpath = NULL;
+       else {
+               (void) endnetconfig(np_sessionp->nc_handlep);
+                                       /* won't need nc session*/
+               np_sessionp->nc_handlep = NULL;
+               if ((np_sessionp->netpath = malloc(strlen(npp)+1)) == NULL) {
+                       free(np_sessionp);
+                       return (NULL);
+               } else
+                       (void) strcpy(np_sessionp->netpath, npp);
+       }
+       np_sessionp->netpath_start = np_sessionp->netpath;
+       return ((void *)np_sessionp);
+}
+
+/*
+ * When first called, getnetpath() returns a pointer to the netconfig
+ * database entry corresponding to the first valid NETPATH component.  The
+ * netconfig entry is formatted as a struct netconfig.
+ * On each subsequent call, getnetpath returns a pointer to the netconfig
+ * entry that corresponds to the next valid NETPATH component.  getnetpath
+ * can thus be used to search the netconfig database for all networks
+ * included in the NETPATH variable.
+ * When NETPATH has been exhausted, getnetpath() returns NULL.  It returns
+ * NULL and sets errno in case of an error (e.g., setnetpath was not called
+ * previously).
+ * getnetpath() silently ignores invalid NETPATH components.  A NETPATH
+ * compnent is invalid if there is no corresponding entry in the netconfig
+ * database.
+ * If the NETPATH variable is unset, getnetpath() behaves as if NETPATH
+ * were set to the sequence of default or visible networks in the netconfig
+ * database, in the order in which they are listed.
+ */
+
+struct netconfig *
+getnetpath(handlep)
+       void *handlep;
+{
+       struct netpath_vars *np_sessionp = (struct netpath_vars *)handlep;
+       struct netconfig *ncp = NULL;   /* temp. holds a netconfig session */
+       struct netpath_chain *chainp;   /* holds chain of ncp's we alloc */
+       char  *npp;             /* holds current NETPATH */
+
+       if (np_sessionp == NULL || np_sessionp->valid != NP_VALID) {
+               errno = EINVAL;
+               return (NULL);
+       }
+       if (np_sessionp->netpath_start == NULL) { /* NETPATH was not set */
+               do {                /* select next visible network */
+                       if (np_sessionp->nc_handlep == NULL) {
+                               np_sessionp->nc_handlep = setnetconfig();
+                               if (np_sessionp->nc_handlep == NULL)
+                                       syslog (LOG_ERR,
+                                           "rpc: failed to open " NETCONFIG);
+                       }
+                       if ((ncp = getnetconfig(np_sessionp->nc_handlep))
+                           == NULL)
+                               return(NULL);
+               } while ((ncp->nc_flag & NC_VISIBLE) == 0);
+               return (ncp);
+       }
+       /*
+        * Find first valid network ID in netpath.
+        */
+       while ((npp = np_sessionp->netpath) != NULL && strlen(npp) != 0) {
+               np_sessionp->netpath = _get_next_token(npp, ':');
+               /*
+                * npp is a network identifier.
+                */
+               if ((ncp = getnetconfigent(npp)) != NULL) {
+                                       /* cobble alloc chain entry */
+                       chainp = malloc(sizeof (struct netpath_chain));
+                       if (chainp == NULL) {
+                               freenetconfigent(ncp);
+                               return NULL;
+                       }
+                       chainp->ncp = ncp;
+                       chainp->nchain_next = NULL;
+                       if (np_sessionp->ncp_list == NULL)
+                               np_sessionp->ncp_list = chainp;
+                       else
+                               np_sessionp->ncp_list->nchain_next = chainp;
+                       return (ncp);
+               }
+               /* couldn't find this token in the database; go to next one. */
+       }
+       return (NULL);
+}
+
+/*
+ * endnetpath() may be called to unbind NETPATH when processing is complete,
+ * releasing resources for reuse.  It returns 0 on success and -1 on failure
+ * (e.g. if setnetpath() was not called previously.
+ */
+int
+endnetpath(handlep)
+       void *handlep;
+{
+       struct netpath_vars *np_sessionp = (struct netpath_vars *)handlep;
+       struct netpath_chain *chainp, *lastp;
+
+       if (np_sessionp == NULL || np_sessionp->valid != NP_VALID) {
+               errno = EINVAL;
+               return (-1);
+       }
+       if (np_sessionp->nc_handlep != NULL)
+               endnetconfig(np_sessionp->nc_handlep);
+       if (np_sessionp->netpath_start != NULL)
+               free(np_sessionp->netpath_start);
+       for (chainp = np_sessionp->ncp_list; chainp != NULL;
+           lastp=chainp, chainp=chainp->nchain_next, free(lastp)) {
+               freenetconfigent(chainp->ncp);
+       }
+       free(np_sessionp);
+#ifdef MEM_CHK
+       if (malloc_verify() == 0) {
+               fprintf(stderr, "memory heap corrupted in endnetpath\n");
+               exit(1);
+       }
+#endif
+       return (0);
+}
+
+
+/*
+ * Returns pointer to the rest-of-the-string after the current token.
+ * The token itself starts at arg, and we null terminate it.  We return NULL
+ * if either the arg is empty, or if this is the last token.
+ */
+
+char *
+_get_next_token(
+       char *npp,              /* string */
+       int token               /* char to parse string for */
+)
+{
+       char  *cp;              /* char pointer */
+       char  *np;              /* netpath pointer */
+       char  *ep;              /* escape pointer */
+
+       _DIAGASSERT(npp != NULL);
+
+       if ((cp = strchr(npp, token)) == NULL)
+               return (NULL);
+       /*
+        * did find a token, but it might be escaped.
+        */
+       if ((cp > npp) && (cp[-1] == '\\')) {
+               /*
+                * if slash was also escaped, carry on, otherwise find
+                * next token
+                */
+               if ((cp > npp + 1) && (cp[-2] != '\\')) {
+                       /* shift r-o-s  onto the escaped token */
+                       strcpy(&cp[-1], cp);  /* XXX: overlapping string copy */
+                       /*
+                        * Do a recursive call.
+                        * We don't know how many escaped tokens there might be.
+                        */
+                       return (_get_next_token(cp, token));
+               }
+       }
+
+       *cp++ = '\0';           /* null-terminate token */
+       /* get rid of any backslash escapes */
+       ep = npp;
+       while ((np = strchr(ep, '\\')) != 0) {
+               if (np[1] == '\\')
+                       np++;
+               strcpy(np, (ep = &np[1]));  /* XXX: overlapping string copy */
+       }
+       return (cp);            /* return ptr to r-o-s */
+}
diff --git a/lib/nbsd_libc/rpc/getrpcent.3 b/lib/nbsd_libc/rpc/getrpcent.3
new file mode 100644 (file)
index 0000000..fd85ad4
--- /dev/null
@@ -0,0 +1,96 @@
+.\"    @(#)getrpcent.3n        2.2 88/08/02 4.0 RPCSRC; from 1.11 88/03/14 SMI
+.\"    $NetBSD: getrpcent.3,v 1.14 2004/08/16 10:18:27 wiz Exp $
+.\"
+.Dd August 16, 2004
+.Dt GETRPCENT 3
+.Os
+.Sh NAME
+.Nm getrpcent ,
+.Nm getrpcbyname ,
+.Nm getrpcbynumber ,
+.Nm endrpcent ,
+.Nm setrpcent
+.Nd get RPC entry
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In rpc/rpc.h
+.Ft struct rpcent *
+.Fn getrpcent void
+.Ft struct rpcent *
+.Fn getrpcbyname "const char *name"
+.Ft struct rpcent *
+.Fn getrpcbynumber "int number"
+.Ft void
+.Fn setrpcent "int stayopen"
+.Ft void
+.Fn endrpcent void
+.Sh DESCRIPTION
+.Fn getrpcent ,
+.Fn getrpcbyname ,
+and
+.Fn getrpcbynumber ,
+each return a pointer to an object with the
+following structure
+containing the broken-out
+fields of a line in the rpc program number data base,
+.Pa /etc/rpc :
+.Bd -literal -offset indent
+struct rpcent {
+       char    *r_name;        /* name of server for this rpc program */
+       char    **r_aliases;    /* alias list */
+       long    r_number;       /* rpc program number */
+};
+.Ed
+.Pp
+The members of this structure are:
+.Bl -tag -width r_aliases -offset indent
+.It r_name
+The name of the server for this rpc program.
+.It r_aliases
+A zero terminated list of alternative names for the rpc program.
+.It r_number
+The rpc program number for this service.
+.El
+.Pp
+.Fn getrpcent
+reads the next line of the file, opening the file if necessary.
+.Pp
+.Fn setrpcent
+opens and rewinds the file.
+If the
+.Fa stayopen
+flag is non-zero,
+the net data base will not be closed after each call to
+.Fn getrpcent
+(either directly, or indirectly through one of
+the other
+.Dq getrpc
+calls).
+.Pp
+.Fn endrpcent
+closes the file.
+.Pp
+.Fn getrpcbyname
+and
+.Fn getrpcbynumber
+sequentially search from the beginning
+of the file until a matching rpc program name or
+program number is found, or until end-of-file is encountered.
+.Sh FILES
+.Pa /etc/rpc
+.Sh DIAGNOSTICS
+A
+.Dv NULL
+pointer is returned on
+.Dv EOF
+or error.
+.Sh SEE ALSO
+.Xr rpc 5 ,
+.Xr rpcinfo 8 ,
+.Xr ypserv 8
+.Sh BUGS
+All information
+is contained in a static area
+so it must be copied if it is
+to be saved.
diff --git a/lib/nbsd_libc/rpc/getrpcent.c b/lib/nbsd_libc/rpc/getrpcent.c
new file mode 100644 (file)
index 0000000..696893f
--- /dev/null
@@ -0,0 +1,222 @@
+/*     $NetBSD: getrpcent.c,v 1.21 2004/08/16 02:47:54 ginsbach Exp $  */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user or with the express written consent of
+ * Sun Microsystems, Inc.
+ *
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ *
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ *
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ *
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ *
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)getrpcent.c 1.14 91/03/11 Copyr 1984 Sun Micro";
+#else
+__RCSID("$NetBSD: getrpcent.c,v 1.21 2004/08/16 02:47:54 ginsbach Exp $");
+#endif
+#endif
+
+/*
+ * Copyright (c) 1984 by Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include <assert.h>
+#include <netdb.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <rpc/rpc.h>
+
+#ifdef __weak_alias
+__weak_alias(endrpcent,_endrpcent)
+__weak_alias(getrpcbyname,_getrpcbyname)
+__weak_alias(getrpcbynumber,_getrpcbynumber)
+__weak_alias(getrpcent,_getrpcent)
+__weak_alias(setrpcent,_setrpcent)
+#endif
+
+/*
+ * Internet version.
+ */
+static struct rpcdata {
+       FILE    *rpcf;
+       int     stayopen;
+#define        MAXALIASES      35
+       char    *rpc_aliases[MAXALIASES];
+       struct  rpcent rpc;
+       char    line[BUFSIZ+1];
+} *rpcdata;
+
+static struct rpcent *interpret(char *val, size_t len);
+
+#define        RPCDB   "/etc/rpc"
+
+static struct rpcdata *_rpcdata(void);
+
+static struct rpcdata *
+_rpcdata(void)
+{
+       struct rpcdata *d = rpcdata;
+
+       if (d == 0) {
+               d = (struct rpcdata *)calloc(1, sizeof (struct rpcdata));
+               rpcdata = d;
+       }
+       return (d);
+}
+
+struct rpcent *
+getrpcbynumber(int number)
+{
+       struct rpcent *rpc;
+
+       setrpcent(0);
+       while ((rpc = getrpcent()) != NULL) {
+               if (rpc->r_number == number)
+                       break;
+       }
+       endrpcent();
+       return (rpc);
+}
+
+struct rpcent *
+getrpcbyname(const char *name)
+{
+       struct rpcent *rpc;
+       char **rp;
+
+       _DIAGASSERT(name != NULL);
+
+       setrpcent(0);
+       while ((rpc = getrpcent()) != NULL) {
+               if (strcmp(rpc->r_name, name) == 0)
+                       break;
+               for (rp = rpc->r_aliases; *rp != NULL; rp++) {
+                       if (strcmp(*rp, name) == 0)
+                               goto found;
+               }
+       }
+found:
+       endrpcent();
+       return (rpc);
+}
+
+void
+setrpcent(int f)
+{
+       struct rpcdata *d = _rpcdata();
+
+       if (d == 0)
+               return;
+       if (d->rpcf == NULL)
+               d->rpcf = fopen(RPCDB, "r");
+       else
+               rewind(d->rpcf);
+       d->stayopen |= f;
+}
+
+void
+endrpcent(void)
+{
+       struct rpcdata *d = _rpcdata();
+
+       if (d == 0)
+               return;
+       if (d->rpcf && !d->stayopen) {
+               fclose(d->rpcf);
+               d->rpcf = NULL;
+       }
+}
+
+struct rpcent *
+getrpcent(void)
+{
+       struct rpcdata *d = _rpcdata();
+
+       if (d == 0)
+               return(NULL);
+       if (d->rpcf == NULL && (d->rpcf = fopen(RPCDB, "r")) == NULL)
+               return (NULL);
+       if (fgets(d->line, BUFSIZ, d->rpcf) == NULL)
+               return (NULL);
+       return (interpret(d->line, strlen(d->line)));
+}
+
+static struct rpcent *
+interpret(char *val, size_t len)
+{
+       struct rpcdata *d = _rpcdata();
+       char *p;
+       char *cp, **q;
+
+       _DIAGASSERT(val != NULL);
+
+       if (d == 0)
+               return (0);
+       (void) strncpy(d->line, val, len);
+       p = d->line;
+       d->line[len] = '\n';
+       if (*p == '#')
+               return (getrpcent());
+       cp = strpbrk(p, "#\n");
+       if (cp == NULL)
+               return (getrpcent());
+       *cp = '\0';
+       cp = strpbrk(p, " \t");
+       if (cp == NULL)
+               return (getrpcent());
+       *cp++ = '\0';
+       /* THIS STUFF IS INTERNET SPECIFIC */
+       d->rpc.r_name = d->line;
+       while (*cp == ' ' || *cp == '\t')
+               cp++;
+       d->rpc.r_number = atoi(cp);
+       q = d->rpc.r_aliases = d->rpc_aliases;
+       cp = strpbrk(cp, " \t");
+       if (cp != NULL) 
+               *cp++ = '\0';
+       while (cp && *cp) {
+               if (*cp == ' ' || *cp == '\t') {
+                       cp++;
+                       continue;
+               }
+               if (q < &(d->rpc_aliases[MAXALIASES - 1]))
+                       *q++ = cp;
+               cp = strpbrk(cp, " \t");
+               if (cp != NULL)
+                       *cp++ = '\0';
+       }
+       *q = NULL;
+       return (&d->rpc);
+}
diff --git a/lib/nbsd_libc/rpc/getrpcport.3 b/lib/nbsd_libc/rpc/getrpcport.3
new file mode 100644 (file)
index 0000000..1ac3a53
--- /dev/null
@@ -0,0 +1,34 @@
+.\"    @(#)getrpcport.3r       2.2 88/08/02 4.0 RPCSRC; from 1.12 88/02/26 SMI
+.\"    $NetBSD: getrpcport.3,v 1.5 2003/01/18 11:29:04 thorpej Exp $
+.\"
+.Dd October 6, 1987
+.Dt GETRPCPORT 3
+.Os
+.Sh NAME
+.Nm getrpcport
+.Nd get RPC port number
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.Ft int
+.Fn getrpcport "char *host" "int prognum" "int versnum" "int proto"
+.Sh DESCRIPTION
+.Fn getrpcport
+returns the port number for version
+.Fa versnum
+of the RPC program
+.Fa prognum
+running on
+.Fa host
+and using protocol
+.Fa proto .
+It returns 0 if it cannot contact the portmapper, or if
+.Fa prognum
+is not registered.
+If
+.Fa prognum
+is registered but not with version
+.Fa versnum ,
+it will still return a port number (for some version of the program)
+indicating that the program is indeed registered.
+The version mismatch will be detected upon the first call to the service.
diff --git a/lib/nbsd_libc/rpc/getrpcport.c b/lib/nbsd_libc/rpc/getrpcport.c
new file mode 100644 (file)
index 0000000..4a44a7d
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: getrpcport.c,v 1.16 2000/01/22 22:19:18 mycroft Exp $  */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)getrpcport.c 1.3 87/08/11 SMI";
+static char *sccsid = "@(#)getrpcport.c        2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: getrpcport.c,v 1.16 2000/01/22 22:19:18 mycroft Exp $");
+#endif
+#endif
+
+/*
+ * Copyright (c) 1985 by Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <assert.h>
+#include <netdb.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <rpc/rpc.h>
+#include <rpc/pmap_clnt.h>
+
+#ifdef __weak_alias
+__weak_alias(getrpcport,_getrpcport)
+#endif
+
+int
+getrpcport(host, prognum, versnum, proto)
+       char *host;
+       int prognum, versnum, proto;
+{
+       struct sockaddr_in addr;
+       struct hostent *hp;
+
+       _DIAGASSERT(host != NULL);
+
+       if ((hp = gethostbyname(host)) == NULL)
+               return (0);
+       memset(&addr, 0, sizeof(addr));
+       addr.sin_len = sizeof(struct sockaddr_in);
+       addr.sin_family = AF_INET;
+       addr.sin_port =  0;
+       if (hp->h_length > addr.sin_len)
+               hp->h_length = addr.sin_len;
+       memcpy(&addr.sin_addr.s_addr, hp->h_addr, (size_t)hp->h_length);
+       /* Inconsistent interfaces need casts! :-( */
+       return (pmap_getport(&addr, (u_long)prognum, (u_long)versnum, 
+           (u_int)proto));
+}
diff --git a/lib/nbsd_libc/rpc/mt_misc.c b/lib/nbsd_libc/rpc/mt_misc.c
new file mode 100644 (file)
index 0000000..269348d
--- /dev/null
@@ -0,0 +1,137 @@
+/*     $NetBSD: mt_misc.c,v 1.8 2010/12/08 02:06:38 joerg Exp $        */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Frank van der Linden.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ *     Define and initialize MT data for libnsl.
+ *     The _libnsl_lock_init() function below is the library's .init handler.
+ */
+
+/* #pragma ident       "@(#)mt_misc.c  1.24    93/04/29 SMI" */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: mt_misc.c,v 1.8 2010/12/08 02:06:38 joerg Exp $");
+#endif
+
+#include       "namespace.h"
+#include       "reentrant.h"
+#include       <rpc/rpc.h>
+#include       <sys/time.h>
+#include       <stdlib.h>
+#include       <string.h>
+
+#ifdef _REENTRANT
+
+/* protects the services list (svc.c) */
+rwlock_t       svc_lock = RWLOCK_INITIALIZER;
+/* protects svc_fdset and the xports[] array */
+rwlock_t       svc_fd_lock = RWLOCK_INITIALIZER;
+/* protects the RPCBIND address cache */
+rwlock_t       rpcbaddr_cache_lock = RWLOCK_INITIALIZER;
+
+/* protects authdes cache (svcauth_des.c) */
+mutex_t        authdes_lock = MUTEX_INITIALIZER;
+/* auth_none.c serialization */
+mutex_t        authnone_lock = MUTEX_INITIALIZER;
+/* protects the Auths list (svc_auth.c) */
+mutex_t        authsvc_lock = MUTEX_INITIALIZER;
+/* protects client-side fd lock array */
+mutex_t        clnt_fd_lock = MUTEX_INITIALIZER;
+/* clnt_raw.c serialization */
+mutex_t        clntraw_lock = MUTEX_INITIALIZER;
+/* domainname and domain_fd (getdname.c) and default_domain (rpcdname.c) */
+mutex_t        dname_lock = MUTEX_INITIALIZER;
+/* dupreq variables (svc_dg.c) */
+mutex_t        dupreq_lock = MUTEX_INITIALIZER;
+/* protects first_time and hostname (key_call.c) */
+mutex_t        keyserv_lock = MUTEX_INITIALIZER;
+/* serializes rpc_trace() (rpc_trace.c) */
+mutex_t        libnsl_trace_lock = MUTEX_INITIALIZER;
+/* loopnconf (rpcb_clnt.c) */
+mutex_t        loopnconf_lock = MUTEX_INITIALIZER;
+/* serializes ops initializations */
+mutex_t        ops_lock = MUTEX_INITIALIZER;
+/* protects ``port'' static in bindresvport() */
+mutex_t        portnum_lock = MUTEX_INITIALIZER;
+/* protects proglst list (svc_simple.c) */
+mutex_t        proglst_lock = MUTEX_INITIALIZER;
+/* serializes clnt_com_create() (rpc_soc.c) */
+mutex_t        rpcsoc_lock = MUTEX_INITIALIZER;
+/* svc_raw.c serialization */
+mutex_t        svcraw_lock = MUTEX_INITIALIZER;
+/* xprtlist (svc_generic.c) */
+mutex_t        xprtlist_lock = MUTEX_INITIALIZER;
+/* serializes calls to public key routines */
+mutex_t serialize_pkey = MUTEX_INITIALIZER;
+
+#endif /* _REENTRANT */
+
+
+#undef rpc_createerr
+
+struct rpc_createerr rpc_createerr;
+
+#ifdef _REENTRANT
+static thread_key_t rce_key;
+static once_t rce_once = ONCE_INITIALIZER;
+
+static void 
+__rpc_createerr_setup(void)
+{
+
+       thr_keycreate(&rce_key, free);
+}
+#endif /* _REENTRANT */
+
+struct rpc_createerr*
+__rpc_createerr()
+{
+#ifdef _REENTRANT
+       struct rpc_createerr *rce_addr = 0;
+
+       if (__isthreaded == 0)
+               return (&rpc_createerr);
+       thr_once(&rce_once, __rpc_createerr_setup);
+       rce_addr = thr_getspecific(rce_key);
+       if (rce_addr == NULL) {
+               rce_addr = malloc(sizeof(*rce_addr));
+               if (rce_addr == NULL)
+                       return &rpc_createerr;
+               thr_setspecific(rce_key, (void *) rce_addr);
+               memset(rce_addr, 0, sizeof (struct rpc_createerr));
+       }
+               
+       return (rce_addr);
+#else
+       return &rpc_createerr;
+#endif
+}
+
diff --git a/lib/nbsd_libc/rpc/pmap_clnt.c b/lib/nbsd_libc/rpc/pmap_clnt.c
new file mode 100644 (file)
index 0000000..1b40037
--- /dev/null
@@ -0,0 +1,125 @@
+/*     $NetBSD: pmap_clnt.c,v 1.18 2003/01/18 11:29:05 thorpej Exp $   */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)pmap_clnt.c 1.37 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)pmap_clnt.c 2.2 88/08/01 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: pmap_clnt.c,v 1.18 2003/01/18 11:29:05 thorpej Exp $");
+#endif
+#endif
+
+/*
+ * pmap_clnt.c
+ * Client interface to pmap rpc service.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+
+#include <unistd.h>
+
+#include <rpc/rpc.h>
+#include <rpc/pmap_prot.h>
+#include <rpc/pmap_clnt.h>
+#include <rpc/nettype.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(pmap_set,_pmap_set)
+__weak_alias(pmap_unset,_pmap_unset)
+#endif
+
+bool_t
+pmap_set(u_long program, u_long version, int protocol, int port)
+{
+       bool_t rslt;
+       struct netbuf *na;
+       struct netconfig *nconf;
+       char buf[32];
+
+       if ((protocol != IPPROTO_UDP) && (protocol != IPPROTO_TCP)) {
+               return (FALSE);
+       }
+       nconf = __rpc_getconfip(protocol == IPPROTO_UDP ? "udp" : "tcp");
+       if (nconf == NULL) {
+               return (FALSE);
+       }
+       snprintf(buf, sizeof buf, "0.0.0.0.%d.%d", 
+           (((u_int32_t)port) >> 8) & 0xff, port & 0xff);
+       na = uaddr2taddr(nconf, buf);
+       if (na == NULL) {
+               freenetconfigent(nconf);
+               return (FALSE);
+       }
+       rslt = rpcb_set((rpcprog_t)program, (rpcvers_t)version, nconf, na);
+       free(na);
+       freenetconfigent(nconf);
+       return (rslt);
+}
+
+/*
+ * Remove the mapping between program, version and port.
+ * Calls the pmap service remotely to do the un-mapping.
+ */
+bool_t
+pmap_unset(u_long program, u_long version)
+{
+       struct netconfig *nconf;
+       bool_t udp_rslt = FALSE;
+       bool_t tcp_rslt = FALSE;
+
+       nconf = __rpc_getconfip("udp");
+       if (nconf != NULL) {
+               udp_rslt = rpcb_unset((rpcprog_t)program, (rpcvers_t)version,
+                   nconf);
+               freenetconfigent(nconf);
+       }
+       nconf = __rpc_getconfip("tcp");
+       if (nconf != NULL) {
+               tcp_rslt = rpcb_unset((rpcprog_t)program, (rpcvers_t)version,
+                   nconf);
+               freenetconfigent(nconf);
+       }
+       /*
+        * XXX: The call may still succeed even if only one of the
+        * calls succeeded.  This was the best that could be
+        * done for backward compatibility.
+        */
+       return (tcp_rslt || udp_rslt);
+}
diff --git a/lib/nbsd_libc/rpc/pmap_getmaps.c b/lib/nbsd_libc/rpc/pmap_getmaps.c
new file mode 100644 (file)
index 0000000..74c8b5e
--- /dev/null
@@ -0,0 +1,106 @@
+/*     $NetBSD: pmap_getmaps.c,v 1.16 2000/07/06 03:10:34 christos Exp $       */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)pmap_getmaps.c 1.10 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)pmap_getmaps.c      2.2 88/08/01 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: pmap_getmaps.c,v 1.16 2000/07/06 03:10:34 christos Exp $");
+#endif
+#endif
+
+/*
+ * pmap_getmap.c
+ * Client interface to pmap rpc service.
+ * contains pmap_getmaps, which is only tcp service involved
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+
+#include <net/if.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <netdb.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include <rpc/rpc.h>
+#include <rpc/pmap_prot.h>
+#include <rpc/pmap_clnt.h>
+
+#ifdef __weak_alias
+__weak_alias(pmap_getmaps,_pmap_getmaps)
+#endif
+
+#define NAMELEN 255
+#define MAX_BROADCAST_SIZE 1400
+
+/*
+ * Get a copy of the current port maps.
+ * Calls the pmap service remotely to do get the maps.
+ */
+struct pmaplist *
+pmap_getmaps(address)
+        struct sockaddr_in *address;
+{
+       struct pmaplist *head = NULL;
+       int sock = -1;
+       struct timeval minutetimeout;
+       CLIENT *client;
+
+       _DIAGASSERT(address != NULL);
+
+       minutetimeout.tv_sec = 60;
+       minutetimeout.tv_usec = 0;
+       address->sin_port = htons(PMAPPORT);
+       client = clnttcp_create(address, PMAPPROG,
+           PMAPVERS, &sock, 50, 500);
+       if (client != NULL) {
+               if (CLNT_CALL(client, (rpcproc_t)PMAPPROC_DUMP,
+                   (xdrproc_t)xdr_void, NULL,
+                   (xdrproc_t)xdr_pmaplist, &head, minutetimeout) !=
+                   RPC_SUCCESS) {
+                       clnt_perror(client, "pmap_getmaps rpc problem");
+               }
+               CLNT_DESTROY(client);
+       }
+       address->sin_port = 0;
+       return (head);
+}
diff --git a/lib/nbsd_libc/rpc/pmap_getport.c b/lib/nbsd_libc/rpc/pmap_getport.c
new file mode 100644 (file)
index 0000000..5134ac7
--- /dev/null
@@ -0,0 +1,130 @@
+/*     $NetBSD: pmap_getport.c,v 1.18 2008/01/28 01:10:22 christos Exp $       */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)pmap_getport.c 1.9 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)pmap_getport.c      2.2 88/08/01 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: pmap_getport.c,v 1.18 2008/01/28 01:10:22 christos Exp $");
+#endif
+#endif
+
+/*
+ * pmap_getport.c
+ * Client interface to pmap rpc service.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <net/if.h>
+
+#include <assert.h>
+#include <unistd.h>
+
+#include <rpc/rpc.h>
+#include <rpc/pmap_prot.h>
+#include <rpc/pmap_clnt.h>
+
+#ifdef __weak_alias
+__weak_alias(pmap_getport,_pmap_getport)
+#endif
+
+static const struct timeval timeout = { 5, 0 };
+static const struct timeval tottimeout = { 60, 0 };
+
+/*
+ * Find the mapped port for program,version.
+ * Calls the pmap service remotely to do the lookup.
+ * Returns 0 if no map exists.
+ */
+
+static void
+remote_pmap_getport(CLIENT *client, struct pmap *parms, u_short *port)
+{
+       if (CLNT_CALL(client, (rpcproc_t)PMAPPROC_GETPORT, (xdrproc_t)xdr_pmap,
+           parms, (xdrproc_t)xdr_u_short, port, tottimeout) != RPC_SUCCESS) {
+               rpc_createerr.cf_stat = RPC_PMAPFAILURE;
+               clnt_geterr(client, &rpc_createerr.cf_error);
+       } else if (*port == 0) {
+               rpc_createerr.cf_stat = RPC_PROGNOTREGISTERED;
+               clnt_geterr(client, &rpc_createerr.cf_error);
+       }
+       CLNT_DESTROY(client);
+}
+
+static CLIENT *
+get_client(struct sockaddr_in *address, int tcp)
+{
+       int sock = -1;
+       if (tcp)
+               return clnttcp_create(address, PMAPPROG, PMAPVERS, &sock, 0, 0);
+       else
+               return clntudp_bufcreate(address, PMAPPROG, PMAPVERS, timeout,
+                   &sock, RPCSMALLMSGSIZE, RPCSMALLMSGSIZE);
+}
+
+u_short
+pmap_getport(struct sockaddr_in *address, u_long program, u_long version,
+    u_int protocol)
+{
+       u_short port = 0;
+       CLIENT *client;
+       struct pmap parms;
+
+       _DIAGASSERT(address != NULL);
+
+       parms.pm_prog = program;
+       parms.pm_vers = version;
+       parms.pm_prot = protocol;
+       parms.pm_port = 0;  /* not needed or used */
+
+       address->sin_port = htons(PMAPPORT);
+
+       client = get_client(address, protocol == IPPROTO_TCP);
+       if (client != NULL)
+               remote_pmap_getport(client, &parms, &port);
+
+       if (port == 0) {
+               client = get_client(address, protocol != IPPROTO_TCP);
+               if (client != NULL)
+                       remote_pmap_getport(client, &parms, &port);
+       }
+
+       address->sin_port = 0;
+       return port;
+}
diff --git a/lib/nbsd_libc/rpc/pmap_prot.c b/lib/nbsd_libc/rpc/pmap_prot.c
new file mode 100644 (file)
index 0000000..85aa613
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: pmap_prot.c,v 1.10 2000/01/22 22:19:18 mycroft Exp $   */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)pmap_prot.c 1.17 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)pmap_prot.c 2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: pmap_prot.c,v 1.10 2000/01/22 22:19:18 mycroft Exp $");
+#endif
+#endif
+
+/*
+ * pmap_prot.c
+ * Protocol for the local binder service, or pmap.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+
+#include <assert.h>
+
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+#include <rpc/pmap_prot.h>
+
+#ifdef __weak_alias
+__weak_alias(xdr_pmap,_xdr_pmap)
+#endif
+
+
+bool_t
+xdr_pmap(xdrs, regs)
+       XDR *xdrs;
+       struct pmap *regs;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(regs != NULL);
+
+       if (xdr_u_long(xdrs, &regs->pm_prog) && 
+               xdr_u_long(xdrs, &regs->pm_vers) && 
+               xdr_u_long(xdrs, &regs->pm_prot))
+               return (xdr_u_long(xdrs, &regs->pm_port));
+       return (FALSE);
+}
diff --git a/lib/nbsd_libc/rpc/pmap_prot2.c b/lib/nbsd_libc/rpc/pmap_prot2.c
new file mode 100644 (file)
index 0000000..8a6bd60
--- /dev/null
@@ -0,0 +1,153 @@
+/*     $NetBSD: pmap_prot2.c,v 1.15 2001/01/04 14:42:20 lukem Exp $    */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)pmap_prot2.c 1.3 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)pmap_prot2.c        2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: pmap_prot2.c,v 1.15 2001/01/04 14:42:20 lukem Exp $");
+#endif
+#endif
+
+/*
+ * pmap_prot2.c
+ * Protocol for the local binder service, or pmap.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+
+#include <assert.h>
+
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+#include <rpc/pmap_prot.h>
+
+#ifdef __weak_alias
+__weak_alias(xdr_pmaplist,_xdr_pmaplist)
+#endif
+
+/* 
+ * What is going on with linked lists? (!)
+ * First recall the link list declaration from pmap_prot.h:
+ *
+ * struct pmaplist {
+ *     struct pmap pml_map;
+ *     struct pmaplist *pml_map;
+ * };
+ *
+ * Compare that declaration with a corresponding xdr declaration that 
+ * is (a) pointer-less, and (b) recursive:
+ *
+ * typedef union switch (bool_t) {
+ * 
+ *     case TRUE: struct {
+ *             struct pmap;
+ *             pmaplist_t foo;
+ *     };
+ *
+ *     case FALSE: struct {};
+ * } pmaplist_t;
+ *
+ * Notice that the xdr declaration has no nxt pointer while
+ * the C declaration has no bool_t variable.  The bool_t can be
+ * interpreted as ``more data follows me''; if FALSE then nothing
+ * follows this bool_t; if TRUE then the bool_t is followed by
+ * an actual struct pmap, and then (recursively) by the 
+ * xdr union, pamplist_t.  
+ *
+ * This could be implemented via the xdr_union primitive, though this
+ * would cause a one recursive call per element in the list.  Rather than do
+ * that we can ``unwind'' the recursion
+ * into a while loop and do the union arms in-place.
+ *
+ * The head of the list is what the C programmer wishes to past around
+ * the net, yet is the data that the pointer points to which is interesting;
+ * this sounds like a job for xdr_reference!
+ */
+bool_t
+xdr_pmaplist(xdrs, rp)
+       XDR *xdrs;
+       struct pmaplist **rp;
+{
+       /*
+        * more_elements is pre-computed in case the direction is
+        * XDR_ENCODE or XDR_FREE.  more_elements is overwritten by
+        * xdr_bool when the direction is XDR_DECODE.
+        */
+       bool_t more_elements;
+       int freeing;
+       struct pmaplist **next  = NULL; /* pacify gcc */
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(rp != NULL);
+
+       freeing = (xdrs->x_op == XDR_FREE);
+
+       for (;;) {
+               more_elements = (bool_t)(*rp != NULL);
+               if (! xdr_bool(xdrs, &more_elements))
+                       return (FALSE);
+               if (! more_elements)
+                       return (TRUE);  /* we are done */
+               /*
+                * the unfortunate side effect of non-recursion is that in
+                * the case of freeing we must remember the next object
+                * before we free the current object ...
+                */
+               if (freeing)
+                       next = &((*rp)->pml_next); 
+               if (! xdr_reference(xdrs, (caddr_t *)rp,
+                   (u_int)sizeof(struct pmaplist), (xdrproc_t)xdr_pmap))
+                       return (FALSE);
+               rp = (freeing) ? next : &((*rp)->pml_next);
+       }
+}
+
+
+/*
+ * xdr_pmaplist_ptr() is specified to take a PMAPLIST *, but is identical in
+ * functionality to xdr_pmaplist().
+ */
+bool_t
+xdr_pmaplist_ptr(xdrs, rp)
+       XDR *xdrs;
+       struct pmaplist *rp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(rp != NULL);
+
+       return xdr_pmaplist(xdrs, (struct pmaplist **)(void *)rp);
+}
diff --git a/lib/nbsd_libc/rpc/pmap_rmt.c b/lib/nbsd_libc/rpc/pmap_rmt.c
new file mode 100644 (file)
index 0000000..f7e43cc
--- /dev/null
@@ -0,0 +1,184 @@
+/*     $NetBSD: pmap_rmt.c,v 1.30 2010/03/23 20:28:59 drochner Exp $   */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)pmap_rmt.c 1.21 87/08/27 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)pmap_rmt.c  2.2 88/08/01 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: pmap_rmt.c,v 1.30 2010/03/23 20:28:59 drochner Exp $");
+#endif
+#endif
+
+/*
+ * pmap_rmt.c
+ * Client interface to pmap rpc service.
+ * remote call and broadcast service
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/poll.h>
+#include <sys/socket.h>
+
+#include <net/if.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include <assert.h>
+#include <err.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <rpc/rpc.h>
+#include <rpc/pmap_prot.h>
+#include <rpc/pmap_clnt.h>
+#include <rpc/pmap_rmt.h>
+
+#ifdef __weak_alias
+__weak_alias(xdr_rmtcall_args,_xdr_rmtcall_args)
+__weak_alias(xdr_rmtcallres,_xdr_rmtcallres)
+#endif
+
+static const struct timeval timeout = { 3, 0 };
+
+/*
+ * pmapper remote-call-service interface.
+ * This routine is used to call the pmapper remote call service
+ * which will look up a service program in the port maps, and then
+ * remotely call that routine with the given parameters.  This allows
+ * programs to do a lookup and call in one step.
+*/
+enum clnt_stat
+pmap_rmtcall(addr, prog, vers, proc, xdrargs, argsp, xdrres, resp, tout,
+    port_ptr)
+       struct sockaddr_in *addr;
+       u_long prog, vers, proc;
+       xdrproc_t xdrargs, xdrres;
+       caddr_t argsp, resp;
+       struct timeval tout;
+       u_long *port_ptr;
+{
+       int sock = -1;
+       CLIENT *client;
+       struct rmtcallargs a;
+       struct rmtcallres r;
+       enum clnt_stat stat;
+
+       _DIAGASSERT(addr != NULL);
+       _DIAGASSERT(port_ptr != NULL);
+
+       addr->sin_port = htons(PMAPPORT);
+       client = clntudp_create(addr, PMAPPROG, PMAPVERS, timeout, &sock);
+       if (client != NULL) {
+               a.prog = prog;
+               a.vers = vers;
+               a.proc = proc;
+               a.args_ptr = argsp;
+               a.xdr_args = xdrargs;
+               r.port_ptr = port_ptr;
+               r.results_ptr = resp;
+               r.xdr_results = xdrres;
+               stat = CLNT_CALL(client, (rpcproc_t)PMAPPROC_CALLIT,
+                   (xdrproc_t)xdr_rmtcall_args, &a, (xdrproc_t)xdr_rmtcallres,
+                   &r, tout);
+               CLNT_DESTROY(client);
+       } else {
+               stat = RPC_FAILED;
+       }
+       addr->sin_port = 0;
+       return (stat);
+}
+
+
+/*
+ * XDR remote call arguments
+ * written for XDR_ENCODE direction only
+ */
+bool_t
+xdr_rmtcall_args(xdrs, cap)
+       XDR *xdrs;
+       struct rmtcallargs *cap;
+{
+       u_int lenposition, argposition, position;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(cap != NULL);
+
+       if (xdr_u_long(xdrs, &(cap->prog)) &&
+           xdr_u_long(xdrs, &(cap->vers)) &&
+           xdr_u_long(xdrs, &(cap->proc))) {
+               lenposition = XDR_GETPOS(xdrs);
+               if (! xdr_u_long(xdrs, &(cap->arglen)))
+                   return (FALSE);
+               argposition = XDR_GETPOS(xdrs);
+               if (! (*(cap->xdr_args))(xdrs, cap->args_ptr))
+                   return (FALSE);
+               position = XDR_GETPOS(xdrs);
+               cap->arglen = (u_long)position - (u_long)argposition;
+               XDR_SETPOS(xdrs, lenposition);
+               if (! xdr_u_long(xdrs, &(cap->arglen)))
+                   return (FALSE);
+               XDR_SETPOS(xdrs, position);
+               return (TRUE);
+       }
+       return (FALSE);
+}
+
+/*
+ * XDR remote call results
+ * written for XDR_DECODE direction only
+ */
+bool_t
+xdr_rmtcallres(xdrs, crp)
+       XDR *xdrs;
+       struct rmtcallres *crp;
+{
+       caddr_t port_ptr;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(crp != NULL);
+
+       port_ptr = (caddr_t)(void *)crp->port_ptr;
+       if (xdr_reference(xdrs, &port_ptr, sizeof (u_long),
+           (xdrproc_t)xdr_u_long) && xdr_u_long(xdrs, &crp->resultslen)) {
+               crp->port_ptr = (u_long *)(void *)port_ptr;
+               return ((*(crp->xdr_results))(xdrs, crp->results_ptr));
+       }
+       return (FALSE);
+}
diff --git a/lib/nbsd_libc/rpc/rpc.3 b/lib/nbsd_libc/rpc/rpc.3
new file mode 100644 (file)
index 0000000..889e676
--- /dev/null
@@ -0,0 +1,417 @@
+.\" @(#)rpc.3n 1.31 93/08/31 SMI; from SVr4
+.\" Copyright 1989 AT&T
+.\"    $NetBSD: rpc.3,v 1.22 2010/03/22 19:30:54 joerg Exp $
+.Dd May 7, 1993
+.Dt RPC 3
+.Os
+.Sh NAME
+.Nm rpc
+.Nd library routines for remote procedure calls
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In rpc/rpc.h
+.In netconfig.h
+.Sh DESCRIPTION
+These
+routines allow C language programs to make procedure
+calls on other machines across a network.
+First, the client sends a request to the server.
+On receipt of the request, the server calls a dispatch routine
+to perform the requested service, and then sends back a reply.
+.Pp
+All
+RPC routines require the header
+.In rpc/rpc.h .
+Routines that take a
+.Fa netconfig
+structure also require that
+.In netconfig.h
+be included.
+.Ss Nettype
+Some of the high-level
+RPC interface routines take a
+.Fa nettype
+string as one of the parameters
+(for example,
+.Fn clnt_create ,
+.Fn svc_create ,
+.Fn rpc_reg ,
+.Fn rpc_call .
+This string defines a class of transports which can be used
+for a particular application.
+.Pp
+.Fa nettype
+can be one of the following:
+.Bl -tag -width datagram_v
+.It netpath
+Choose from the transports which have been
+indicated by their token names in the
+.Ev NETPATH
+environment variable.
+If
+.Ev NETPATH
+is unset or
+.Dv NULL
+, it defaults to
+.Fa visible .
+.Fa netpath
+is the default
+.Fa nettype .
+.It visible
+Choose the transports which have the visible flag (v)
+set in the
+.Pa /etc/netconfig
+file.
+.It circuit_v
+This is same as
+.Fa visible
+except that it chooses only the connection oriented transports
+(semantics
+.Fa tpi_cots
+or
+.Fa tpi_cots_ord )
+from the entries in the
+.Pa /etc/netconfig
+file.
+.It datagram_v
+This is same as
+.Fa visible
+except that it chooses only the connectionless datagram transports
+(semantics
+.Fa tpi_clts )
+from the entries in the
+.Pa /etc/netconfig
+file.
+.It circuit_n
+This is same as
+.Fa netpath
+except that it chooses only the connection oriented datagram transports
+(semantics
+.Fa tpi_cots
+or
+.Fa tpi_cots_ord ) .
+.It datagram_n
+This is same as
+.Fa netpath
+except that it chooses only the connectionless datagram transports
+(semantics
+.Fa tpi_clts ) .
+.It udp
+This refers to Internet UDP, both version 4 and 6.
+.It tcp
+This refers to Internet TCP, both version 4 and 6.
+.El
+.Pp
+If
+.Fa nettype
+is
+.Dv NULL ,
+it defaults to
+.Fa netpath .
+The transports are tried in left to right order in the
+.Ev NETPATH
+variable or in top to down order in the
+.Pa /etc/netconfig
+file.
+.Ss Derived Types
+The derived types used in the RPC interfaces are defined as follows:
+.Bd -literal
+       typedef uint32_t rpcprog_t;
+       typedef uint32_t rpcvers_t;
+       typedef uint32_t rpcproc_t;
+       typedef uint32_t rpcprot_t;
+       typedef uint32_t rpcport_t;
+       typedef   int32_t rpc_inline_t;
+.Ed
+.Ss Data Structures
+Some of the data structures used by the
+RPC package are shown below.
+.Ss The AUTH Structure
+.Bd -literal
+/*
+ * Authentication info. Opaque to client.
+ */
+struct opaque_auth {
+    enum_t    oa_flavor;    /* flavor of auth */
+    caddr_t    oa_base;    /* address of more auth stuff */
+    u_int    oa_length;    /* not to exceed MAX_AUTH_BYTES */
+};
+
+/*
+ * Auth handle, interface to client side authenticators.
+ */
+typedef struct {
+    struct    opaque_auth    ah_cred;
+    struct    opaque_auth    ah_verf;
+    struct auth_ops {
+        void    (*ah_nextverf)(\|);
+        int    (*ah_marshal)(\|);    /* nextverf \*[Am] serialize */
+        int    (*ah_validate)(\|);    /* validate verifier */
+        int    (*ah_refresh)(\|);    /* refresh credentials */
+        void    (*ah_destroy)(\|);    /* destroy this structure */
+    } *ah_ops;
+    caddr_t ah_private;
+} AUTH;
+.Ed
+.Ss The CLIENT Structure
+.Bd -literal
+/*
+ * Client rpc handle.
+ * Created by individual implementations.
+ * Client is responsible for initializing auth.
+ */
+
+typedef struct {
+    AUTH    *cl_auth;    /* authenticator */
+    struct clnt_ops {
+        enum clnt_stat    (*cl_call)();    /* call remote procedure */
+        void    (*cl_abort)();        /* abort a call */
+        void    (*cl_geterr)();        /* get specific error code */
+        bool_t    (*cl_freeres)();    /* frees results */
+        void    (*cl_destroy)();    /* destroy this structure */
+        bool_t    (*cl_control)();    /* the ioctl() of rpc */
+    } *cl_ops;
+    caddr_t    cl_private;    /* private stuff */
+    char    *cl_netid;    /* network identifier */
+    char    *cl_tp;        /* device name */
+} CLIENT;
+.Ed
+.Ss The SVCXPRT structure
+.Bd -literal
+enum xprt_stat {
+    XPRT_DIED,
+    XPRT_MOREREQS,
+    XPRT_IDLE
+};
+
+/*
+ * Server side transport handle
+ */
+typedef struct {
+    int    xp_fd;    /* file descriptor for the server handle */
+    u_short    xp_port;    /* obsolete */
+    const struct xp_ops {
+        bool_t    (*xp_recv)();    /* receive incoming requests */
+        enum xprt_stat    (*xp_stat)();    /* get transport status */
+        bool_t    (*xp_getargs)();    /* get arguments */
+        bool_t    (*xp_reply)();      /* send reply */
+        bool_t    (*xp_freeargs)(); /* free mem allocated for args */
+        void    (*xp_destroy)();    /* destroy this struct */
+    } *xp_ops;
+    int    xp_addrlen;    /* length of remote addr.  Obsolete */
+    struct sockaddr_in    xp_raddr; /* Obsolete */
+    const struct xp_ops2 {
+        bool_t    (*xp_control)();    /* catch-all function */
+    } *xp_ops2;
+    char    *xp_tp;    /* transport provider device name */
+    char    *xp_netid;    /* network identifier */
+    struct netbuf    xp_ltaddr;    /* local transport address */
+    struct netbuf    xp_rtaddr;    /* remote transport address */
+    struct opaque_auth    xp_verf;    /* raw response verifier */
+    caddr_t    xp_p1;    /* private: for use by svc ops */
+    caddr_t    xp_p2;    /* private: for use by svc ops */
+    caddr_t    xp_p3;    /* private: for use by svc lib */
+    int    xp_type    /* transport type */
+} SVCXPRT;
+.Ed
+.Ss The svc_req structure
+.Bd -literal
+struct svc_req {
+    rpcprog_t    rq_prog;    /* service program number */
+    rpcvers_t    rq_vers;    /* service protocol version */
+    rpcproc_t    rq_proc;    /* the desired procedure */
+    struct opaque_auth    rq_cred;    /* raw creds from the wire */
+    caddr_t    rq_clntcred;    /* read only cooked cred */
+    SVCXPRT    *rq_xprt;    /* associated transport */
+};
+.Ed
+.Ss The XDR structure
+.Bd -literal
+/*
+ * XDR operations.
+ * XDR_ENCODE causes the type to be encoded into the stream.
+ * XDR_DECODE causes the type to be extracted from the stream.
+ * XDR_FREE can be used to release the space allocated by an XDR_DECODE
+ * request.
+ */
+enum xdr_op {
+    XDR_ENCODE=0,
+    XDR_DECODE=1,
+    XDR_FREE=2
+};
+/*
+ * This is the number of bytes per unit of external data.
+ */
+#define BYTES_PER_XDR_UNIT    (4)
+#define RNDUP(x)  ((((x) + BYTES_PER_XDR_UNIT - 1) /
+                   BYTES_PER_XDR_UNIT) \e * BYTES_PER_XDR_UNIT)
+
+/*
+ * A xdrproc_t exists for each data type which is to be encoded or
+ * decoded.  The second argument to the xdrproc_t is a pointer to
+ * an opaque pointer.  The opaque pointer generally points to a
+ * structure of the data type to be decoded.  If this points to 0,
+ * then the type routines should allocate dynamic storage of the
+ * appropriate size and return it.
+ * bool_t  (*xdrproc_t)(XDR *, caddr_t *);
+ */
+typedef  bool_t (*xdrproc_t)();
+
+/*
+ * The XDR handle.
+ * Contains operation which is being applied to the stream,
+ * an operations vector for the particular implementation
+ */
+typedef struct {
+    enum xdr_op    x_op;    /* operation; fast additional param */
+    struct xdr_ops {
+        bool_t    (*x_getlong)();    /* get a long from underlying stream */
+        bool_t    (*x_putlong)();    /* put a long to underlying stream */
+        bool_t    (*x_getbytes)(); /* get bytes from underlying stream */
+        bool_t    (*x_putbytes)(); /* put bytes to underlying stream */
+        u_int    (*x_getpostn)(); /* returns bytes off from beginning */
+        bool_t    (*x_setpostn)(); /* lets you reposition the stream */
+        long *    (*x_inline)();    /* buf quick ptr to buffered data */
+        void    (*x_destroy)();    /* free privates of this xdr_stream */
+    } *x_ops;
+    caddr_t    x_public;    /* users' data */
+    caddr_t    x_private;    /* pointer to private data */
+    caddr_t    x_base;    /* private used for position info */
+    int    x_handy;    /* extra private word */
+} XDR;
+
+/*
+ * The netbuf structure. This structure is defined in \*[Lt]xti.h\*[Gt] on SysV
+ * systems, but NetBSD does not use XTI.
+ *
+ * Usually, buf will point to a struct sockaddr, and len and maxlen
+ * will contain the length and maximum length of that socket address,
+ * respectively.
+ */
+struct netbuf {
+       unsigned int maxlen;
+       unsigned int len;
+       void *buf;
+};
+
+/*
+ * The format of the address and options arguments of the XTI t_bind call.
+ * Only provided for compatibility, it should not be used other than
+ * as an argument to svc_tli_create().
+ */
+
+struct t_bind {
+       struct netbuf   addr;
+       unsigned int    qlen;
+};
+.Ed
+.Ss Index to Routines
+The following table lists RPC routines and the manual reference
+pages on which they are described:
+.Bl -column "authunix_create_default()" "rpc_clnt_create(3)"
+.It Em "RPC Routine" Ta Em "Manual Reference Page"
+.Pp
+.It Fn auth_destroy Ta Xr rpc_clnt_auth 3 ,
+.It Fn authdes_create Ta Xr rpc_soc 3 ,
+.It Fn authnone_create Ta Xr rpc_clnt_auth 3 ,
+.It Fn authsys_create Ta Xr rpc_clnt_auth 3 ,
+.It Fn authsys_create_default Ta Xr rpc_clnt_auth 3 ,
+.It Fn authunix_create Ta Xr rpc_soc 3 ,
+.It Fn authunix_create_default Ta Xr rpc_soc 3 ,
+.It Fn callrpc Ta Xr rpc_soc 3 ,
+.It Fn clnt_broadcast Ta Xr rpc_soc 3 ,
+.It Fn clnt_call Ta Xr rpc_clnt_calls 3 ,
+.It Fn clnt_control Ta Xr rpc_clnt_create 3 ,
+.It Fn clnt_create Ta Xr rpc_clnt_create 3 ,
+.It Fn clnt_destroy Ta Xr rpc_clnt_create 3 ,
+.It Fn clnt_dg_create Ta Xr rpc_clnt_create 3 ,
+.It Fn clnt_freeres Ta Xr rpc_clnt_calls 3 ,
+.It Fn clnt_geterr Ta Xr rpc_clnt_calls 3 ,
+.It Fn clnt_pcreateerror Ta Xr rpc_clnt_create 3 ,
+.It Fn clnt_perrno Ta Xr rpc_clnt_calls 3 ,
+.It Fn clnt_perror Ta Xr rpc_clnt_calls 3 ,
+.It Fn clnt_raw_create Ta Xr rpc_clnt_create 3 ,
+.It Fn clnt_spcreateerror Ta Xr rpc_clnt_create 3 ,
+.It Fn clnt_sperrno Ta Xr rpc_clnt_calls 3 ,
+.It Fn clnt_sperror Ta Xr rpc_clnt_calls 3 ,
+.It Fn clnt_tli_create Ta Xr rpc_clnt_create 3 ,
+.It Fn clnt_tp_create Ta Xr rpc_clnt_create 3 ,
+.It Fn clnt_udpcreate Ta Xr rpc_soc 3 ,
+.It Fn clnt_vc_create Ta Xr rpc_clnt_create 3 ,
+.It Fn clntraw_create Ta Xr rpc_soc 3 ,
+.It Fn clnttcp_create Ta Xr rpc_soc 3 ,
+.It Fn clntudp_bufcreate Ta Xr rpc_soc 3 ,
+.It Fn get_myaddress Ta Xr rpc_soc 3 ,
+.It Fn pmap_getmaps Ta Xr rpc_soc 3 ,
+.It Fn pmap_getport Ta Xr rpc_soc 3 ,
+.It Fn pmap_rmtcall Ta Xr rpc_soc 3 ,
+.It Fn pmap_set Ta Xr rpc_soc 3 ,
+.It Fn pmap_unset Ta Xr rpc_soc 3 ,
+.It Fn registerrpc Ta Xr rpc_soc 3 ,
+.It Fn rpc_broadcast Ta Xr rpc_clnt_calls 3 ,
+.It Fn rpc_broadcast_exp Ta Xr rpc_clnt_calls 3 ,
+.It Fn rpc_call Ta Xr rpc_clnt_calls 3 ,
+.It Fn rpc_reg Ta Xr rpc_svc_calls 3 ,
+.It Fn svc_create Ta Xr rpc_svc_create 3 ,
+.It Fn svc_destroy Ta Xr rpc_svc_create 3 ,
+.It Fn svc_dg_create Ta Xr rpc_svc_create 3 ,
+.It Fn svc_dg_enablecache Ta Xr rpc_svc_calls 3 ,
+.It Fn svc_fd_create Ta Xr rpc_svc_create 3 ,
+.It Fn svc_fds Ta Xr rpc_soc 3 ,
+.It Fn svc_freeargs Ta Xr rpc_svc_reg 3 ,
+.It Fn svc_getargs Ta Xr rpc_svc_reg 3 ,
+.It Fn svc_getcaller Ta Xr rpc_soc 3 ,
+.It Fn svc_getreq Ta Xr rpc_soc 3 ,
+.It Fn svc_getreqset Ta Xr rpc_svc_calls 3 ,
+.It Fn svc_getrpccaller Ta Xr rpc_svc_calls 3 ,
+.It Fn svc_kerb_reg Ta Xr kerberos_rpc 3 ,
+.It Fn svc_raw_create Ta Xr rpc_svc_create 3 ,
+.It Fn svc_reg Ta Xr rpc_svc_calls 3 ,
+.It Fn svc_register Ta Xr rpc_soc 3 ,
+.It Fn svc_run Ta Xr rpc_svc_reg 3 ,
+.It Fn svc_sendreply Ta Xr rpc_svc_reg 3 ,
+.It Fn svc_tli_create Ta Xr rpc_svc_create 3 ,
+.It Fn svc_tp_create Ta Xr rpc_svc_create 3 ,
+.It Fn svc_unreg Ta Xr rpc_svc_calls 3 ,
+.It Fn svc_unregister Ta  Xr rpc_soc 3 ,
+.It Fn svc_vc_create Ta Xr rpc_svc_create 3 ,
+.It Fn svcerr_auth Ta Xr rpc_svc_err 3 ,
+.It Fn svcerr_decode Ta Xr rpc_svc_err 3 ,
+.It Fn svcerr_noproc Ta Xr rpc_svc_err 3 ,
+.It Fn svcerr_noprog Ta Xr rpc_svc_err 3 ,
+.It Fn svcerr_progvers Ta Xr rpc_svc_err 3 ,
+.It Fn svcerr_systemerr Ta Xr rpc_svc_err 3 ,
+.It Fn svcerr_weakauth Ta Xr rpc_svc_err 3 ,
+.It Fn svcfd_create Ta Xr rpc_soc 3 ,
+.It Fn svcraw_create Ta Xr rpc_soc 3 ,
+.It Fn svctcp_create Ta Xr rpc_soc 3 ,
+.It Fn svcudp_bufcreate Ta Xr rpc_soc 3 ,
+.It Fn svcudp_create Ta Xr rpc_soc 3 ,
+.It Fn xdr_accepted_reply Ta Xr rpc_xdr 3 ,
+.It Fn xdr_authsys_parms Ta Xr rpc_xdr 3 ,
+.It Fn xdr_authunix_parms Ta Xr rpc_soc 3 ,
+.It Fn xdr_callhdr Ta Xr rpc_xdr 3 ,
+.It Fn xdr_callmsg Ta Xr rpc_xdr 3 ,
+.It Fn xdr_opaque_auth Ta Xr rpc_xdr 3 ,
+.It Fn xdr_rejected_reply Ta Xr rpc_xdr 3 ,
+.It Fn xdr_replymsg Ta Xr rpc_xdr 3 ,
+.It Fn xprt_register Ta Xr rpc_svc_calls 3 ,
+.It Fn xprt_unregister Ta Xr rpc_svc_calls 3 ,
+.El
+.Sh FILES
+.Pa /etc/netconfig
+.Sh SEE ALSO
+.Xr getnetconfig 3 ,
+.Xr getnetpath 3 ,
+.Xr rpc_clnt_auth 3 ,
+.Xr rpc_clnt_calls 3 ,
+.Xr rpc_clnt_create 3 ,
+.Xr rpc_svc_calls 3 ,
+.Xr rpc_svc_create 3 ,
+.Xr rpc_svc_err 3 ,
+.Xr rpc_svc_reg 3 ,
+.Xr rpc_xdr 3 ,
+.Xr rpcbind 3 ,
+.Xr xdr 3 ,
+.Xr netconfig 5
diff --git a/lib/nbsd_libc/rpc/rpc_callmsg.c b/lib/nbsd_libc/rpc/rpc_callmsg.c
new file mode 100644 (file)
index 0000000..1010bdc
--- /dev/null
@@ -0,0 +1,212 @@
+/*     $NetBSD: rpc_callmsg.c,v 1.18 2008/04/25 17:44:44 christos Exp $        */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)rpc_callmsg.c 1.4 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)rpc_callmsg.c       2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: rpc_callmsg.c,v 1.18 2008/04/25 17:44:44 christos Exp $");
+#endif
+#endif
+
+/*
+ * rpc_callmsg.c
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ */
+
+#include "namespace.h"
+
+#include <sys/param.h>
+
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <rpc/rpc.h>
+
+#ifdef __weak_alias
+__weak_alias(xdr_callmsg,_xdr_callmsg)
+#endif
+
+/*
+ * XDR a call message
+ */
+bool_t
+xdr_callmsg(xdrs, cmsg)
+       XDR *xdrs;
+       struct rpc_msg *cmsg;
+{
+       int32_t *buf;
+       struct opaque_auth *oa;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(cmsg != NULL);
+
+       if (xdrs->x_op == XDR_ENCODE) {
+               if (cmsg->rm_call.cb_cred.oa_length > MAX_AUTH_BYTES) {
+                       return (FALSE);
+               }
+               if (cmsg->rm_call.cb_verf.oa_length > MAX_AUTH_BYTES) {
+                       return (FALSE);
+               }
+               buf = XDR_INLINE(xdrs, 8 * BYTES_PER_XDR_UNIT
+                       + RNDUP(cmsg->rm_call.cb_cred.oa_length)
+                       + 2 * BYTES_PER_XDR_UNIT
+                       + RNDUP(cmsg->rm_call.cb_verf.oa_length));
+               if (buf != NULL) {
+                       IXDR_PUT_INT32(buf, cmsg->rm_xid);
+                       IXDR_PUT_ENUM(buf, cmsg->rm_direction);
+                       if (cmsg->rm_direction != CALL) {
+                               return (FALSE);
+                       }
+                       IXDR_PUT_INT32(buf, cmsg->rm_call.cb_rpcvers);
+                       if (cmsg->rm_call.cb_rpcvers != RPC_MSG_VERSION) {
+                               return (FALSE);
+                       }
+                       IXDR_PUT_INT32(buf, cmsg->rm_call.cb_prog);
+                       IXDR_PUT_INT32(buf, cmsg->rm_call.cb_vers);
+                       IXDR_PUT_INT32(buf, cmsg->rm_call.cb_proc);
+                       oa = &cmsg->rm_call.cb_cred;
+                       IXDR_PUT_ENUM(buf, oa->oa_flavor);
+                       IXDR_PUT_INT32(buf, oa->oa_length);
+                       if (oa->oa_length) {
+                               memmove(buf, oa->oa_base, oa->oa_length);
+                               buf += RNDUP(oa->oa_length) / sizeof (int32_t);
+                       }
+                       oa = &cmsg->rm_call.cb_verf;
+                       IXDR_PUT_ENUM(buf, oa->oa_flavor);
+                       IXDR_PUT_INT32(buf, oa->oa_length);
+                       if (oa->oa_length) {
+                               memmove(buf, oa->oa_base, oa->oa_length);
+                               /* no real need....
+                               buf += RNDUP(oa->oa_length) / sizeof (int32_t);
+                               */
+                       }
+                       return (TRUE);
+               }
+       }
+       if (xdrs->x_op == XDR_DECODE) {
+               buf = XDR_INLINE(xdrs, 8 * BYTES_PER_XDR_UNIT);
+               if (buf != NULL) {
+                       cmsg->rm_xid = IXDR_GET_U_INT32(buf);
+                       cmsg->rm_direction = IXDR_GET_ENUM(buf, enum msg_type);
+                       if (cmsg->rm_direction != CALL) {
+                               return (FALSE);
+                       }
+                       cmsg->rm_call.cb_rpcvers = IXDR_GET_U_INT32(buf);
+                       if (cmsg->rm_call.cb_rpcvers != RPC_MSG_VERSION) {
+                               return (FALSE);
+                       }
+                       cmsg->rm_call.cb_prog = IXDR_GET_U_INT32(buf);
+                       cmsg->rm_call.cb_vers = IXDR_GET_U_INT32(buf);
+                       cmsg->rm_call.cb_proc = IXDR_GET_U_INT32(buf);
+                       oa = &cmsg->rm_call.cb_cred;
+                       oa->oa_flavor = IXDR_GET_ENUM(buf, enum_t);
+                       oa->oa_length = (u_int)IXDR_GET_U_INT32(buf);
+                       if (oa->oa_length) {
+                               if (oa->oa_length > MAX_AUTH_BYTES) {
+                                       return (FALSE);
+                               }
+                               if (oa->oa_base == NULL) {
+                                       oa->oa_base = mem_alloc(oa->oa_length);
+                                       if (oa->oa_base == NULL)
+                                               return (FALSE);
+                               }
+                               buf = XDR_INLINE(xdrs, RNDUP(oa->oa_length));
+                               if (buf == NULL) {
+                                       if (xdr_opaque(xdrs, oa->oa_base,
+                                           oa->oa_length) == FALSE) {
+                                               return (FALSE);
+                                       }
+                               } else {
+                                       memmove(oa->oa_base, buf,
+                                           oa->oa_length);
+                                       /* no real need....
+                                       buf += RNDUP(oa->oa_length) /
+                                               sizeof (int32_t);
+                                       */
+                               }
+                       }
+                       oa = &cmsg->rm_call.cb_verf;
+                       buf = XDR_INLINE(xdrs, 2 * BYTES_PER_XDR_UNIT);
+                       if (buf == NULL) {
+                               if (xdr_enum(xdrs, &oa->oa_flavor) == FALSE ||
+                                   xdr_u_int(xdrs, &oa->oa_length) == FALSE) {
+                                       return (FALSE);
+                               }
+                       } else {
+                               oa->oa_flavor = IXDR_GET_ENUM(buf, enum_t);
+                               oa->oa_length = (u_int)IXDR_GET_U_INT32(buf);
+                       }
+                       if (oa->oa_length) {
+                               if (oa->oa_length > MAX_AUTH_BYTES) {
+                                       return (FALSE);
+                               }
+                               if (oa->oa_base == NULL) {
+                                       oa->oa_base = mem_alloc(oa->oa_length);
+                                       if (oa->oa_base == NULL)
+                                               return (FALSE);
+                               }
+                               buf = XDR_INLINE(xdrs, RNDUP(oa->oa_length));
+                               if (buf == NULL) {
+                                       if (xdr_opaque(xdrs, oa->oa_base,
+                                           oa->oa_length) == FALSE) {
+                                               return (FALSE);
+                                       }
+                               } else {
+                                       memmove(oa->oa_base, buf,
+                                           oa->oa_length);
+                                       /* no real need...
+                                       buf += RNDUP(oa->oa_length) /
+                                               sizeof (int32_t);
+                                       */
+                               }
+                       }
+                       return (TRUE);
+               }
+       }
+       if (
+           xdr_u_int32_t(xdrs, &(cmsg->rm_xid)) &&
+           xdr_enum(xdrs, (enum_t *)(void *)&(cmsg->rm_direction)) &&
+           (cmsg->rm_direction == CALL) &&
+           xdr_u_int32_t(xdrs, &(cmsg->rm_call.cb_rpcvers)) &&
+           (cmsg->rm_call.cb_rpcvers == RPC_MSG_VERSION) &&
+           xdr_u_int32_t(xdrs, &(cmsg->rm_call.cb_prog)) &&
+           xdr_u_int32_t(xdrs, &(cmsg->rm_call.cb_vers)) &&
+           xdr_u_int32_t(xdrs, &(cmsg->rm_call.cb_proc)) &&
+           xdr_opaque_auth(xdrs, &(cmsg->rm_call.cb_cred)) )
+               return (xdr_opaque_auth(xdrs, &(cmsg->rm_call.cb_verf)));
+       return (FALSE);
+}
diff --git a/lib/nbsd_libc/rpc/rpc_clnt_auth.3 b/lib/nbsd_libc/rpc/rpc_clnt_auth.3
new file mode 100644 (file)
index 0000000..242958b
--- /dev/null
@@ -0,0 +1,97 @@
+.\" @(#)rpc_clnt_auth.3n 1.21 93/05/07 SMI; from SVr4
+.\" Copyright 1989 AT&T
+.\" @(#)rpc_clnt_auth 1.4 89/07/20 SMI;
+.\" Copyright (c) 1988 Sun Microsystems, Inc. - All Rights Reserved.
+.\"    $NetBSD: rpc_clnt_auth.3,v 1.6 2003/04/16 13:34:43 wiz Exp $
+.Dd May 7, 1993
+.Dt RPC_CLNT_AUTH 3
+.Os
+.Sh NAME
+.Nm auth_destroy ,
+.Nm authnone_create ,
+.Nm authsys_create ,
+.Nm authsys_create_default
+.Nd library routines for client side remote procedure call authentication
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In rpc/rpc.h
+.Ft "void"
+.Fn auth_destroy "AUTH *auth"
+.Ft "AUTH *"
+.Fn authnone_create "void"
+.Ft "AUTH *"
+.Fn authsys_create "const char *host" "const uid_t uid" "const gid_t gid" "const int len" "const gid_t *aup_gids"
+.Ft "AUTH *"
+.Fn authsys_create_default "void"
+.Sh DESCRIPTION
+These routines are part of the
+RPC library that allows C language programs to make procedure
+calls on other machines across the network,
+with desired authentication.
+.Pp
+These routines are normally called after creating the
+.Dv CLIENT
+handle.
+The
+.Fa cl_auth
+field of the
+.Dv CLIENT
+structure should be initialized by the
+.Dv AUTH
+structure returned by some of the following routines.
+The client's authentication information
+is passed to the server when the
+RPC
+call is made.
+.Pp
+Only the
+.Dv NULL
+and the
+.Dv SYS
+style of authentication is discussed here.
+.Sh ROUTINES
+.Bl -tag -width authsys_create_default()
+.It Fn auth_destroy
+A function macro that destroys the authentication
+information associated with
+.Fa auth .
+Destruction usually involves deallocation
+of private data structures.
+The use of
+.Fn auth
+is undefined after calling
+.Fn auth_destroy .
+.Pp
+.It Fn authnone_create
+Create and return an RPC
+authentication handle that passes nonusable
+authentication information with each remote procedure call.
+This is the default authentication used by RPC.
+.Pp
+.It Fn authsys_create
+Create and return an RPC authentication handle that contains
+.Dv AUTH_SYS
+authentication information.
+The parameter
+.Fa host
+is the name of the machine on which the information was
+created;
+.Fa uid
+is the user's user ID;
+.Fa gid
+is the user's current group ID;
+.Fa len
+and
+.Fa aup_gids
+refer to a counted array of groups to which the user belongs.
+.Pp
+.It Fn authsys_create_default
+Call
+.Fn authsys_create
+with the appropriate parameters.
+.El
+.Sh SEE ALSO
+.Xr rpc 3 ,
+.Xr rpc_clnt_calls 3 ,
+.Xr rpc_clnt_create 3
diff --git a/lib/nbsd_libc/rpc/rpc_clnt_calls.3 b/lib/nbsd_libc/rpc/rpc_clnt_calls.3
new file mode 100644 (file)
index 0000000..2f464a1
--- /dev/null
@@ -0,0 +1,296 @@
+.\" @(#)rpc_clnt_calls.3n 1.30 93/08/31 SMI; from SVr4
+.\" Copyright 1989 AT&T
+.\" @(#)rpc_clnt_calls 1.4 89/07/20 SMI;
+.\" Copyright (c) 1988 Sun Microsystems, Inc. - All Rights Reserved.
+.\"    $NetBSD: rpc_clnt_calls.3,v 1.7 2005/12/03 15:16:19 yamt Exp $
+.Dd December 4, 2005
+.Dt RPC_CLNT_CALLS 3
+.Os
+.Sh NAME
+.Nm rpc_clnt_calls ,
+.Nm clnt_call ,
+.Nm clnt_freeres ,
+.Nm clnt_geterr ,
+.Nm clnt_perrno ,
+.Nm clnt_perror ,
+.Nm clnt_sperrno ,
+.Nm clnt_sperror ,
+.Nm rpc_broadcast ,
+.Nm rpc_broadcast_exp ,
+.Nm rpc_call
+.Nd library routines for client side calls
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In rpc/rpc.h
+.Ft "enum clnt_stat"
+.Fn clnt_call "CLIENT *clnt" "const rpcproc_t procnum" "const xdrproc_t inproc" "const char *in" "const xdrproc_t outproc" "caddr_t out" "const struct timeval tout"
+.Ft bool_t
+.Fn clnt_freeres "CLIENT *clnt" "const xdrproc_t outproc" "caddr_t out"
+.Ft void
+.Fn clnt_geterr "const CLIENT * clnt" "struct rpc_err * errp"
+.Ft void
+.Fn clnt_perrno "const enum clnt_stat stat"
+.Ft void
+.Fn clnt_perror "const CLIENT * clnt" "const char *s"
+.Ft "char *"
+.Fn clnt_sperrno "const enum clnt_stat stat"
+.Ft "char *"
+.Fn clnt_sperror "const CLIENT *clnt" "const char * s"
+.\" Note the clustered Fn arguments. It can't take more than 9. XXX
+.Ft "enum clnt_stat"
+.Fn rpc_broadcast "const rpcprog_t prognum, const rpcvers_t versnum" "const rpcproc_t procnum" "const xdrproc_t inproc" "const char *in" "const xdrproc_t outproc" "caddr_t out" "const resultproc_t eachresult" "const char *nettype"
+.Ft "enum clnt_stat"
+.Fn rpc_broadcast_exp "rpcprog_t prognum, const rpcvers_t versnum" "const rpcproc_t procnum, const xdrproc_t xargs" "caddr_t argsp, const xdrproc_t xresults" "caddr_t resultsp" "const int inittime" "const int waittime" "const resultproc_t eachresult" "const char * nettype"
+.Ft "enum clnt_stat"
+.Fn rpc_call "const char *host, const rpcprog_t prognum" "const rpcvers_t versnum" "const rpcproc_t procnum, const xdrproc_t inproc" "const char *in" "const xdrproc_t outproc" "char *out" "const char *nettype"
+.Sh DESCRIPTION
+RPC library routines allow C language programs to make procedure
+calls on other machines across the network.
+First, the client calls a procedure to send a request to the server.
+Upon receipt of the request, the server calls a dispatch routine
+to perform the requested service, and then sends back a reply.
+.Pp
+The
+.Fn clnt_call ,
+.Fn rpc_call ,
+and
+.Fn rpc_broadcast
+routines handle the client side of the procedure call.
+The remaining routines deal with error handling in the case of errors.
+.Pp
+Some of the routines take a
+.Dv CLIENT
+handle as one of the parameters.
+A
+.Dv CLIENT
+handle can be created by an RPC creation routine such as
+.Fn clnt_create
+(see
+.Xr rpc_clnt_create 3 ) .
+.Pp
+These routines are safe for use in multithreaded applications.
+.Dv CLIENT
+handles can be shared between threads, however in this implementation
+requests by different threads are serialized (that is, the first request will
+receive its results before the second request is sent).
+.Sh ROUTINES
+See
+.Xr rpc 3
+for the definition of the
+.Dv CLIENT
+data structure.
+.Pp
+.Bl -tag -width XXXXX
+.It Fn clnt_call
+A function macro that calls the remote procedure
+.Fa procnum
+associated with the client handle,
+.Fa clnt ,
+which is obtained with an RPC
+client creation routine such as
+.Fn clnt_create
+(see
+.Xr rpc_clnt_create 3 ) .
+The parameter
+.Fn inproc
+is the XDR function used to encode the procedure's parameters, and
+.Fn outproc
+is the XDR function used to decode the procedure's results;
+.Fn in
+is the address of the procedure's argument(s), and
+.Fn out
+is the address of where to place the result(s).
+.Fn tout
+is the time allowed for results to be returned, which is overridden by
+a time-out set explicitly through
+.Fn clnt_control ,
+see
+.Xr rpc_clnt_create 3 .
+If the remote call succeeds, the status returned is
+.Dv RPC_SUCCESS ,
+otherwise an appropriate status is returned.
+.Pp
+.It Fn clnt_freeres
+A function macro that frees any data allocated by the
+RPC/XDR system when it decoded the results of an RPC call.
+The parameter
+.Fa out
+is the address of the results, and
+.Fa outproc
+is the XDR routine describing the results.
+This routine returns 1 if the results were successfully freed,
+and 0 otherwise.
+.Pp
+.It Fn clnt_geterr
+A function macro that copies the error structure out of the client
+handle to the structure at address
+.Fa errp .
+.Pp
+.It Fn clnt_perrno
+Print a message to standard error corresponding
+to the condition indicated by
+.Fa stat .
+A newline is appended.
+Normally used after a procedure call fails for a routine
+for which a client handle is not needed, for instance
+.Fn rpc_call .
+.Pp
+.It Fn clnt_perror
+Print a message to the standard error indicating why an
+RPC call failed;
+.Fa clnt
+is the handle used to do the call.
+The message is prepended with string
+.Fa s
+and a colon.
+A newline is appended.
+Normally used after a remote procedure call fails
+for a routine which requires a client handle,
+for instance
+.Fn clnt_call .
+.Pp
+.It Fn clnt_sperrno
+Take the same arguments as
+.Fn clnt_perrno ,
+but instead of sending a message to the standard error
+indicating why an RPC
+call failed, return a pointer to a string which contains the message.
+.Fn clnt_sperrno
+is normally used instead of
+.Fn clnt_perrno
+when the program does not have a standard error (as a program
+running as a server quite likely does not), or if the programmer
+does not want the message to be output with
+.Fn printf
+(see
+.Xr printf 3 ) ,
+or if a message format different than that supported by
+.Fn clnt_perrno
+is to be used.
+Note:
+unlike
+.Fn clnt_sperror
+and
+.Fn clnt_spcreaterror
+(see
+.Xr rpc_clnt_create 3 ) ,
+.Fn clnt_sperrno
+does not return pointer to static data so the
+result will not get overwritten on each call.
+.Pp
+.It Fn clnt_sperror
+Like
+.Fn clnt_perror ,
+except that (like
+.Fn clnt_sperrno )
+it returns a string instead of printing to standard error.
+However,
+.Fn clnt_sperror
+does not append a newline at the end of the message.
+Warning:
+returns pointer to a buffer that is overwritten
+on each call.
+.Pp
+.It Fn rpc_broadcast
+Like
+.Fn rpc_call ,
+except the call message is broadcast to
+all the connectionless transports specified by
+.Fa nettype .
+If
+.Fa nettype
+is
+.Dv NULL ,
+it defaults to
+.Dq netpath .
+Each time it receives a response,
+this routine calls
+.Fn eachresult ,
+whose form is:
+.Ft bool_t
+.Fn eachresult "caddr_t out" "const struct netbuf * addr" "const struct netconfig * netconf"
+where
+.Fa out
+is the same as
+.Fa out
+passed to
+.Fn rpc_broadcast ,
+except that the remote procedure's output is decoded there;
+.Fa addr
+points to the address of the machine that sent the results, and
+.Fa netconf
+is the netconfig structure of the transport on which the remote
+server responded.
+If
+.Fn eachresult
+returns 0,
+.Fn rpc_broadcast
+waits for more replies;
+otherwise it returns with appropriate status.
+Warning:
+broadcast file descriptors are limited in size to the
+maximum transfer size of that transport.
+For Ethernet, this value is 1500 bytes.
+.Fn rpc_broadcast
+uses
+.Dv AUTH_SYS
+credentials by default (see
+.Xr rpc_clnt_auth 3 ) .
+.Pp
+.It Fn rpc_broadcast_exp
+Like
+.Fn rpc_broadcast ,
+except that the initial timeout,
+.Fa inittime
+and the maximum timeout,
+.Fa waittime
+are specified in milliseconds.
+.Fa inittime
+is the initial time that
+.Fn rpc_broadcast_exp
+waits before resending the request.
+After the first resend, the re-transmission interval
+increases exponentially until it exceeds
+.Fa waittime .
+.Pp
+.It Fn rpc_call
+Call the remote procedure associated with
+.Fa prognum ,
+.Fa versnum ,
+and
+.Fa procnum
+on the machine,
+.Fa host .
+The parameter
+.Fa inproc
+is used to encode the procedure's parameters, and
+.Fa outproc
+is used to decode the procedure's results;
+.Fa in
+is the address of the procedure's argument(s), and
+.Fa out
+is the address of where to place the result(s).
+.Fa nettype
+can be any of the values listed on
+.Xr rpc 3 .
+This routine returns
+.Dv RPC_SUCCESS
+if it succeeds, or an appropriate status is returned.
+Use the
+.Fn clnt_perrno
+routine to translate failure status into error messages.
+Warning:
+.Fn rpc_call
+uses the first available transport belonging
+to the class
+.Fa nettype ,
+on which it can create a connection.
+You do not have control of timeouts or authentication
+using this routine.
+.El
+.Sh SEE ALSO
+.Xr printf 3 ,
+.Xr rpc 3 ,
+.Xr rpc_clnt_auth 3 ,
+.Xr rpc_clnt_create 3
diff --git a/lib/nbsd_libc/rpc/rpc_clnt_create.3 b/lib/nbsd_libc/rpc/rpc_clnt_create.3
new file mode 100644 (file)
index 0000000..195a8c4
--- /dev/null
@@ -0,0 +1,443 @@
+.\" @(#)rpc_clnt_create.3n 1.36 93/08/31 SMI; from SVr4
+.\" Copyright 1989 AT&T
+.\" @(#)rpc_clnt_create 1.5 89/07/24 SMI;
+.\" Copyright (c) 1988 Sun Microsystems, Inc. - All Rights Reserved.
+.\"    $NetBSD: rpc_clnt_create.3,v 1.11 2009/05/23 18:57:25 christos Exp $
+.Dd May 23, 2009
+.Dt RPC_CLNT_CREATE 3
+.Os
+.Sh NAME
+.Nm rpc_clnt_create ,
+.Nm clnt_control ,
+.Nm clnt_create ,
+.Nm clnt_create_vers ,
+.Nm clnt_destroy ,
+.Nm clnt_dg_create ,
+.Nm clnt_pcreateerror ,
+.Nm clnt_raw_create ,
+.Nm clnt_spcreateerror ,
+.Nm clnt_tli_create ,
+.Nm clnt_tp_create ,
+.Nm clnt_vc_create ,
+.Nm rpc_createerr
+.Nd "library routines for dealing with creation and manipulation of CLIENT handles"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In rpc/rpc.h
+.Ft bool_t
+.Fn clnt_control "CLIENT *clnt" "const u_int req" "char *info"
+.Ft "CLIENT *"
+.Fn clnt_create "const char * host" "const rpcprog_t prognum" "const rpcvers_t versnum" "const char *nettype"
+.Ft "CLIENT *"
+.Fn clnt_create_vers "const char * host" "const rpcprog_t prognum" "rpcvers_t *vers_outp" "const rpcvers_t vers_low" "const rpcvers_t vers_high" "char *nettype"
+.Ft void
+.Fn clnt_destroy "CLIENT * clnt"
+.Ft "CLIENT *"
+.Fn clnt_dg_create "const int fildes" "const struct netbuf *svcaddr" "const rpcprog_t prognum" "const rpcvers_t versnum" "const u_int sendsz" "const u_int recvsz"
+.Ft void
+.Fn clnt_pcreateerror "const char *s"
+.Ft "char *"
+.Fn clnt_spcreateerror "const char *s"
+.Ft "CLIENT *"
+.Fn clnt_raw_create "const rpcprog_t prognum" "const rpcvers_t versnum"
+.Ft "CLIENT *"
+.Fn clnt_tli_create "const int fildes" "const struct netconfig *netconf" "const struct netbuf *svcaddr" "const rpcprog_t prognum" "const rpcvers_t versnum" "const u_int sendsz" "const u_int recvsz"
+.Ft "CLIENT *"
+.Fn clnt_tp_create "const char * host" "const rpcprog_t prognum" "const rpcvers_t versnum" "const struct netconfig *netconf"
+.Ft "CLIENT *"
+.Fn clnt_vc_create "const int fildes" "const struct netbuf *svcaddr" "const rpcprog_t prognum" "const rpcvers_t versnum" "const u_int sendsz" "const u_int recvsz"
+.Sh DESCRIPTION
+RPC library routines allow C language programs to make procedure
+calls on other machines across the network.
+First a
+.Dv CLIENT
+handle is created and then the client calls a procedure to send a
+request to the server.
+On receipt of the request, the server calls a dispatch routine
+to perform the requested service, and then sends a reply.
+.Sh ROUTINES
+.Bl -tag -width YYYYYYY
+.It Fn clnt_control
+A function macro to change or retrieve various information
+about a client object.
+.Fa req
+indicates the type of operation, and
+.Fa info
+is a pointer to the information.
+For both connectionless and connection-oriented transports,
+the supported values of
+.Fa req
+and their argument types and what they do are:
+.Bl -column "CLSET_FD_NCLOSE" "struct timeval *" "set total timeout"
+.It Dv CLSET_TIMEOUT Ta "struct timeval *" Ta "set total timeout"
+.It Dv CLGET_TIMEOUT Ta "struct timeval *" Ta "get total timeout"
+.El
+.Pp
+Note:
+if you set the timeout using
+.Fn clnt_control ,
+the timeout argument passed by
+.Fn clnt_call
+is ignored in all subsequent calls.
+.Pp
+Note:
+If you set the timeout value to 0
+.Fn clnt_control
+immediately returns an error (
+.Dv RPC_TIMEDOUT ) .
+Set the timeout parameter to 0 for batching calls.
+.Bl -column CLSET_FD_NCLOSE "struct timeval *" "do not close fd on destroy"
+.It Dv CLGET_SVC_ADDR Ta "struct netbuf *" Ta "get servers address"
+.It Dv CLGET_FD Ta "int *" Ta "get fd from handle"
+.It Dv CLSET_FD_CLOSE Ta "void" Ta "close fd on destroy"
+.It Dv CLSET_FD_NCLOSE Ta void Ta "don't close fd on destroy"
+.It Dv CLGET_VERS Ta "unsigned long *" Ta "get RPC program version"
+.It Dv CLSET_VERS Ta "unsigned long *" Ta "set RPC program version"
+.It Dv CLGET_XID Ta "unsigned long *" Ta "get XID of previous call"
+.It Dv CLSET_XID Ta "unsigned long *" Ta "set XID of next call"
+.El
+.Pp
+The following operations are valid for connectionless transports only:
+.Bl -column CLSET_RETRY_TIMEOUT "struct timeval *" "set total timeout"
+.It Dv CLSET_RETRY_TIMEOUT Ta "struct timeval *" Ta "set the retry timeout"
+.It Dv CLGET_RETRY_TIMEOUT Ta "struct timeval *" Ta "get the retry timeout"
+.El
+.Pp
+The retry timeout is the time that RPC
+waits for the server to reply before retransmitting the request.
+.Fn clnt_control
+returns
+.Dv TRUE
+on success and
+.Dv FALSE
+on failure.
+.Pp
+.It Fn clnt_create
+Generic client creation routine for program
+.Fa prognum
+and version
+.Fa versnum .
+.Fa host
+identifies the name of the remote host where the server
+is located.
+.Fa nettype
+indicates the class of transport protocol to use.
+The transports are tried in left to right order in
+.Ev NETPATH
+environment variable or in top to bottom order in
+the netconfig database.
+.Fn clnt_create
+tries all the transports of the
+.Fa nettype
+class available from the
+.Ev NETPATH
+environment variable and the netconfig database,
+and chooses the first successful one.
+A default timeout is set and can be modified using
+.Fn clnt_control .
+This routine returns
+.Dv NULL
+if it fails.
+The
+.Fn clnt_pcreateerror
+routine can be used to print the reason for failure.
+.Pp
+Note:
+.Fn clnt_create
+returns a valid client handle even
+if the particular version number supplied to
+.Fn clnt_create
+is not registered with the
+.Xr rpcbind 8
+service.
+This mismatch will be discovered by a
+.Fn clnt_call
+later (see
+.Xr rpc_clnt_calls 3 ) .
+.Pp
+.It Fn clnt_create_vers
+Generic client creation routine which is similar to
+.Fn clnt_create
+but which also checks for the
+version availability.
+.Fa host
+identifies the name of the remote host where the server
+is located.
+.Fa nettype
+indicates the class transport protocols to be used.
+If the routine is successful it returns a client handle created for
+the highest version between
+.Fa vers_low
+and
+.Fa vers_high
+that is supported by the server.
+.Fa vers_outp
+is set to this value.
+That is, after a successful return
+.Fa vers_low
+\*[Le]
+.Fa *vers_outp
+\*[Le]
+.Fa vers_high .
+If no version between
+.Fa vers_low
+and
+.Fa vers_high
+is supported by the server then the routine fails and returns
+.Dv NULL .
+A default timeout is set and can be modified using
+.Fn clnt_control .
+This routine returns
+.Dv NULL
+if it fails.
+The
+.Fn clnt_pcreateerror
+routine can be used to print the reason for failure.
+Note:
+.Fn clnt_create
+returns a valid client handle even
+if the particular version number supplied to
+.Fn clnt_create
+is not registered with the
+.Xr rpcbind 8
+service.
+This mismatch will be discovered by a
+.Fn clnt_call
+later (see
+.Xr rpc_clnt_calls 3 ) .
+However,
+.Fn clnt_create_vers
+does this for you and returns a valid handle
+only if a version within
+the range supplied is supported by the server.
+.Pp
+.It Fn clnt_destroy
+A function macro that destroys the client's RPC handle.
+Destruction usually involves deallocation
+of private data structures, including
+.Fa clnt
+itself.
+Use of
+.Fa clnt
+is undefined after calling
+.Fn clnt_destroy .
+If the RPC library opened the associated file descriptor, or
+.Dv CLSET_FD_CLOSE
+was set using
+.Fn clnt_control ,
+the file descriptor will be closed.
+The caller should call
+.Fn auth_destroy "clnt-\*[Gt]cl_auth"
+(before calling
+.Fn clnt_destroy )
+to destroy the associated
+.Dv AUTH
+structure (see
+.Xr rpc_clnt_auth 3 ) .
+.Pp
+.It Fn clnt_dg_create
+This routine creates an RPC client for the remote program
+.Fa prognum
+and version
+.Fa versnum ;
+the client uses a connectionless transport.
+The remote program is located at address
+.Fa svcaddr .
+The parameter
+.Fa fildes
+is an open and bound file descriptor.
+This routine will resend the call message in intervals of
+15 seconds until a response is received or until the
+call times out.
+The total time for the call to time out is specified by
+.Fn clnt_call
+(see
+.Fn clnt_call
+in
+.Xr rpc_clnt_calls 3 ) .
+The retry time out and the total time out periods can
+be changed using
+.Fn clnt_control .
+The user may set the size of the send and receive
+buffers with the parameters
+.Fa sendsz
+and
+.Fa recvsz ;
+values of 0 choose suitable defaults.
+This routine returns
+.Dv NULL
+if it fails.
+.Pp
+.It Fn clnt_pcreateerror
+Print a message to standard error indicating
+why a client RPC handle could not be created.
+The message is prepended with the string
+.Fa s
+and a colon, and appended with a newline.
+.Pp
+.It Fn clnt_spcreateerror
+Like
+.Fn clnt_pcreateerror ,
+except that it returns a string
+instead of printing to the standard error.
+A newline is not appended to the message in this case.
+Warning:
+returns a pointer to a buffer that is overwritten
+on each call.
+.Pp
+.It Fn clnt_raw_create
+This routine creates an RPC
+client handle for the remote program
+.Fa prognum
+and version
+.Fa versnum .
+The transport used to pass messages to the service is
+a buffer within the process's address space,
+so the corresponding RPC
+server should live in the same address space;
+(see
+.Fn svc_raw_create
+in
+.Xr rpc_svc_create 3 ) .
+This allows simulation of RPC and measurement of
+RPC overheads, such as round trip times,
+without any kernel or networking interference.
+This routine returns
+.Dv NULL
+if it fails.
+.Fn clnt_raw_create
+should be called after
+.Fn svc_raw_create .
+.Pp
+.It Fn clnt_tli_create
+This routine creates an RPC
+client handle for the remote program
+.Fa prognum
+and version
+.Fa versnum .
+The remote program is located at address
+.Fa svcaddr .
+If
+.Fa svcaddr
+is
+.Dv NULL
+and it is connection-oriented, it is assumed that the file descriptor
+is connected.
+For connectionless transports, if
+.Fa svcaddr
+is
+.Dv NULL ,
+.Dv RPC_UNKNOWNADDR
+error is set.
+.Fa fildes
+is a file descriptor which may be open, bound and connected.
+If it is
+.Dv RPC_ANYFD ,
+it opens a file descriptor on the transport specified by
+.Fa netconf .
+If
+.Fa fildes
+is
+.Dv RPC_ANYFD
+and
+.Fa netconf
+is
+.Dv NULL ,
+a
+.Dv RPC_UNKNOWNPROTO
+error is set.
+If
+.Fa fildes
+is unbound, then it will attempt to bind the descriptor.
+The user may specify the size of the buffers with the parameters
+.Fa sendsz
+and
+.Fa recvsz ;
+values of 0 choose suitable defaults.
+Depending upon the type of the transport (connection-oriented
+or connectionless),
+.Fn clnt_tli_create
+calls appropriate client creation routines.
+This routine returns
+.Dv NULL
+if it fails.
+The
+.Fn clnt_pcreateerror
+routine can be used to print the reason for failure.
+The remote rpcbind
+service (see
+.Xr rpcbind 8 )
+is not consulted for the address of the remote
+service.
+.Pp
+.It Fn clnt_tp_create
+Like
+.Fn clnt_create
+except
+.Fn clnt_tp_create
+tries only one transport specified through
+.Fa netconf .
+.Fn clnt_tp_create
+creates a client handle for the program
+.Fa prognum ,
+the version
+.Fa versnum ,
+and for the transport specified by
+.Fa netconf .
+Default options are set,
+which can be changed using
+.Fn clnt_control
+calls.
+The remote rpcbind service on the host
+.Fa host
+is consulted for the address of the remote service.
+This routine returns
+.Dv NULL
+if it fails.
+The
+.Fn clnt_pcreateerror
+routine can be used to print the reason for failure.
+.Pp
+.It Fn clnt_vc_create
+This routine creates an RPC
+client for the remote program
+.Fa prognum
+and version
+.Fa versnum ;
+the client uses a connection-oriented transport.
+The remote program is located at address
+.Fa svcaddr .
+The parameter
+.Fa fildes
+is an open and bound file descriptor.
+The user may specify the size of the send and receive buffers
+with the parameters
+.Fa sendsz
+and
+.Fa recvsz ;
+values of 0 choose suitable defaults.
+This routine returns
+.Dv NULL
+if it fails.
+The address
+.Fa svcaddr
+should not be
+.Dv NULL
+and should point to the actual address of the remote program.
+.Fn clnt_vc_create
+does not consult the remote rpcbind service for this information.
+.Pp
+.It struct rpc_createerr rpc_createerr;
+A global variable whose value is set by any RPC
+client handle creation routine
+that fails.
+It is used by the routine
+.Fn clnt_pcreateerror
+to print the reason for the failure.
+.El
+.Sh SEE ALSO
+.Xr rpc 3 ,
+.Xr rpc_clnt_auth 3 ,
+.Xr rpc_clnt_calls 3 ,
+.Xr rpcbind 8
diff --git a/lib/nbsd_libc/rpc/rpc_commondata.c b/lib/nbsd_libc/rpc/rpc_commondata.c
new file mode 100644 (file)
index 0000000..a023ac6
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: rpc_commondata.c,v 1.8 2003/01/18 11:29:05 thorpej Exp $       */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)rpc_commondata.c    2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: rpc_commondata.c,v 1.8 2003/01/18 11:29:05 thorpej Exp $");
+#endif
+#endif
+
+#include <rpc/rpc.h>
+
+/*
+ * This file should only contain common data (global data) that is exported
+ * by public interfaces 
+ */
+struct opaque_auth _null_auth;
+fd_set svc_fdset;
+int svc_maxfd = -1;
+#ifndef _REENTRANT
+#undef rpc_createerr
+struct rpc_createerr rpc_createerr;
+#endif
diff --git a/lib/nbsd_libc/rpc/rpc_dtablesize.c b/lib/nbsd_libc/rpc/rpc_dtablesize.c
new file mode 100644 (file)
index 0000000..e947154
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: rpc_dtablesize.c,v 1.14 1998/11/15 17:32:43 christos Exp $     */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)rpc_dtablesize.c 1.2 87/08/11 Copyr 1987 Sun Micro";
+static char *sccsid = "@(#)rpc_dtablesize.c    2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: rpc_dtablesize.c,v 1.14 1998/11/15 17:32:43 christos Exp $");
+#endif
+#endif
+
+#include "namespace.h"
+
+#include <unistd.h>
+
+int _rpc_dtablesize __P((void));       /* XXX */
+
+/*
+ * Cache the result of sysconf(_SC_OPEN_MAX), so we don't have to do an
+ * expensive system call every time.
+ */
+int
+_rpc_dtablesize()
+{
+       static int size;
+       if (size == 0)
+               size = (int)sysconf(_SC_OPEN_MAX);
+       return (size);
+}
diff --git a/lib/nbsd_libc/rpc/rpc_generic.c b/lib/nbsd_libc/rpc/rpc_generic.c
new file mode 100644 (file)
index 0000000..a695ab4
--- /dev/null
@@ -0,0 +1,897 @@
+/*     $NetBSD: rpc_generic.c,v 1.24 2010/12/08 02:06:38 joerg Exp $   */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc. 
+ */
+
+/* #pragma ident       "@(#)rpc_generic.c      1.17    94/04/24 SMI" */
+
+/*
+ * rpc_generic.c, Miscl routines for RPC.
+ *
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: rpc_generic.c,v 1.24 2010/12/08 02:06:38 joerg Exp $");
+#endif
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/resource.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <arpa/inet.h>
+#include <rpc/rpc.h>
+#include <assert.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <netdb.h>
+#include <netconfig.h>
+#include <malloc.h>
+#include <string.h>
+#include <syslog.h>
+#include <rpc/nettype.h>
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(taddr2uaddr,_taddr2uaddr)
+__weak_alias(uaddr2taddr,_uaddr2taddr)
+#endif
+
+struct handle {
+       NCONF_HANDLE *nhandle;
+       int nflag;              /* Whether NETPATH or NETCONFIG */
+       int nettype;
+};
+
+static const struct _rpcnettype {
+       const char *name;
+       const int type;
+} _rpctypelist[] = {
+       { "netpath", _RPC_NETPATH },
+       { "visible", _RPC_VISIBLE },
+       { "circuit_v", _RPC_CIRCUIT_V },
+       { "datagram_v", _RPC_DATAGRAM_V },
+       { "circuit_n", _RPC_CIRCUIT_N },
+       { "datagram_n", _RPC_DATAGRAM_N },
+       { "tcp", _RPC_TCP },
+       { "udp", _RPC_UDP },
+       { 0, _RPC_NONE }
+};
+
+struct netid_af {
+       const char      *netid;
+       int             af;
+       int             protocol;
+};
+
+static const struct netid_af na_cvt[] = {
+       { "udp",  AF_INET,  IPPROTO_UDP },
+       { "tcp",  AF_INET,  IPPROTO_TCP },
+#ifdef INET6
+       { "udp6", AF_INET6, IPPROTO_UDP },
+       { "tcp6", AF_INET6, IPPROTO_TCP },
+#endif
+       { "local", AF_LOCAL, 0 }
+};
+
+#if 0
+static char *strlocase __P((char *));
+#endif
+static int getnettype __P((const char *));
+
+/*
+ * Cache the result of getrlimit(), so we don't have to do an
+ * expensive call every time.
+ */
+int
+__rpc_dtbsize()
+{
+       static int tbsize;
+       struct rlimit rl;
+
+       if (tbsize) {
+               return (tbsize);
+       }
+       if (getrlimit(RLIMIT_NOFILE, &rl) == 0) {
+               return (tbsize = (int)rl.rlim_max);
+       }
+       /*
+        * Something wrong.  I'll try to save face by returning a
+        * pessimistic number.
+        */
+       return (32);
+}
+
+
+/*
+ * Find the appropriate buffer size
+ */
+u_int
+/*ARGSUSED*/
+__rpc_get_t_size(af, proto, size)
+       int af, proto;
+       int size;       /* Size requested */
+{
+       int maxsize, defsize;
+
+       maxsize = 256 * 1024;   /* XXX */
+       switch (proto) {
+       case IPPROTO_TCP:
+               defsize = 64 * 1024;    /* XXX */
+               break;
+       case IPPROTO_UDP:
+               defsize = UDPMSGSIZE;
+               break;
+       default:
+               defsize = RPC_MAXDATASIZE;
+               break;
+       }
+       if (size == 0)
+               return defsize;
+
+       /* Check whether the value is within the upper max limit */
+       return (size > maxsize ? (u_int)maxsize : (u_int)size);
+}
+
+/*
+ * Find the appropriate address buffer size
+ */
+u_int
+__rpc_get_a_size(af)
+       int af;
+{
+       switch (af) {
+       case AF_INET:
+               return sizeof (struct sockaddr_in);
+#ifdef INET6
+       case AF_INET6:
+               return sizeof (struct sockaddr_in6);
+#endif
+       case AF_LOCAL:
+               return sizeof (struct sockaddr_un);
+       default:
+               break;
+       }
+       return ((u_int)RPC_MAXADDRSIZE);
+}
+
+#if 0
+static char *
+strlocase(p)
+       char *p;
+{
+       char *t = p;
+
+       _DIAGASSERT(p != NULL);
+
+       for (; *p; p++)
+               if (isupper(*p))
+                       *p = tolower(*p);
+       return (t);
+}
+#endif
+
+/*
+ * Returns the type of the network as defined in <rpc/nettype.h>
+ * If nettype is NULL, it defaults to NETPATH.
+ */
+static int
+getnettype(nettype)
+       const char *nettype;
+{
+       int i;
+
+       if ((nettype == NULL) || (nettype[0] == 0)) {
+               return (_RPC_NETPATH);  /* Default */
+       }
+
+#if 0
+       nettype = strlocase(nettype);
+#endif
+       for (i = 0; _rpctypelist[i].name; i++)
+               if (strcasecmp(nettype, _rpctypelist[i].name) == 0) {
+                       return (_rpctypelist[i].type);
+               }
+       return (_rpctypelist[i].type);
+}
+
+/*
+ * For the given nettype (tcp or udp only), return the first structure found.
+ * This should be freed by calling freenetconfigent()
+ */
+
+#ifdef _REENTRANT
+static thread_key_t tcp_key, udp_key;
+static once_t __rpc_getconfigp_once = ONCE_INITIALIZER;
+
+static void
+__rpc_getconfigp_setup(void)
+{
+
+       thr_keycreate(&tcp_key, free);
+       thr_keycreate(&udp_key, free);
+}
+#endif
+
+struct netconfig *
+__rpc_getconfip(nettype)
+       const char *nettype;
+{
+       char *netid;
+       char *netid_tcp = NULL;
+       char *netid_udp = NULL;
+       static char *netid_tcp_main;
+       static char *netid_udp_main;
+       struct netconfig *dummy;
+#ifdef _REENTRANT
+       if (__isthreaded == 0) {
+               netid_udp = netid_udp_main;
+               netid_tcp = netid_tcp_main;
+       } else {
+               thr_once(&__rpc_getconfigp_once, __rpc_getconfigp_setup);
+               netid_tcp = thr_getspecific(tcp_key);
+               netid_udp = thr_getspecific(udp_key);
+       }
+#else
+       netid_udp = netid_udp_main;
+       netid_tcp = netid_tcp_main;
+#endif
+
+       _DIAGASSERT(nettype != NULL);
+
+       if (!netid_udp && !netid_tcp) {
+               struct netconfig *nconf;
+               void *confighandle;
+
+               if (!(confighandle = setnetconfig())) {
+                       syslog (LOG_ERR, "rpc: failed to open " NETCONFIG);
+                       return (NULL);
+               }
+               while ((nconf = getnetconfig(confighandle)) != NULL) {
+                       if (strcmp(nconf->nc_protofmly, NC_INET) == 0) {
+                               if (strcmp(nconf->nc_proto, NC_TCP) == 0) {
+                                       netid_tcp = strdup(nconf->nc_netid);
+                                       if (netid_tcp == NULL)
+                                               return NULL;
+#ifdef _REENTRANT
+                                       if (__isthreaded == 0)
+                                               netid_tcp_main = netid_tcp;
+                                       else
+                                               thr_setspecific(tcp_key,
+                                                       (void *) netid_tcp);
+#else
+                                       netid_tcp_main = netid_tcp;
+#endif
+                               } else
+                               if (strcmp(nconf->nc_proto, NC_UDP) == 0) {
+                                       netid_udp = strdup(nconf->nc_netid);
+                                       if (netid_udp == NULL)
+                                               return NULL;
+#ifdef _REENTRANT
+                                       if (__isthreaded == 0)
+                                               netid_udp_main = netid_udp;
+                                       else
+                                               thr_setspecific(udp_key,
+                                                       (void *) netid_udp);
+#else
+                                       netid_udp_main = netid_udp;
+#endif
+                               }
+                       }
+               }
+               endnetconfig(confighandle);
+       }
+       if (strcmp(nettype, "udp") == 0)
+               netid = netid_udp;
+       else if (strcmp(nettype, "tcp") == 0)
+               netid = netid_tcp;
+       else {
+               return (NULL);
+       }
+       if ((netid == NULL) || (netid[0] == 0)) {
+               return (NULL);
+       }
+       dummy = getnetconfigent(netid);
+       return (dummy);
+}
+
+/*
+ * Returns the type of the nettype, which should then be used with
+ * __rpc_getconf().
+ */
+void *
+__rpc_setconf(nettype)
+       const char *nettype;
+{
+       struct handle *handle;
+
+       /* nettype may be NULL; getnettype() supports that */
+
+       handle = malloc(sizeof(*handle));
+       if (handle == NULL) {
+               return (NULL);
+       }
+       switch (handle->nettype = getnettype(nettype)) {
+       case _RPC_NETPATH:
+       case _RPC_CIRCUIT_N:
+       case _RPC_DATAGRAM_N:
+               if (!(handle->nhandle = setnetpath())) {
+                       free(handle);
+                       return (NULL);
+               }
+               handle->nflag = TRUE;
+               break;
+       case _RPC_VISIBLE:
+       case _RPC_CIRCUIT_V:
+       case _RPC_DATAGRAM_V:
+       case _RPC_TCP:
+       case _RPC_UDP:
+               if (!(handle->nhandle = setnetconfig())) {
+                       syslog (LOG_ERR, "rpc: failed to open " NETCONFIG);
+                       free(handle);
+                       return (NULL);
+               }
+               handle->nflag = FALSE;
+               break;
+       default:
+               free(handle);
+               return (NULL);
+       }
+
+       return (handle);
+}
+
+/*
+ * Returns the next netconfig struct for the given "net" type.
+ * __rpc_setconf() should have been called previously.
+ */
+struct netconfig *
+__rpc_getconf(vhandle)
+       void *vhandle;
+{
+       struct handle *handle;
+       struct netconfig *nconf;
+
+       handle = (struct handle *)vhandle;
+       if (handle == NULL) {
+               return (NULL);
+       }
+       for (;;) {
+               if (handle->nflag)
+                       nconf = getnetpath(handle->nhandle);
+               else
+                       nconf = getnetconfig(handle->nhandle);
+               if (nconf == NULL)
+                       break;
+               if ((nconf->nc_semantics != NC_TPI_CLTS) &&
+                       (nconf->nc_semantics != NC_TPI_COTS) &&
+                       (nconf->nc_semantics != NC_TPI_COTS_ORD))
+                       continue;
+               switch (handle->nettype) {
+               case _RPC_VISIBLE:
+                       if (!(nconf->nc_flag & NC_VISIBLE))
+                               continue;
+                       /* FALLTHROUGH */
+               case _RPC_NETPATH:      /* Be happy */
+                       break;
+               case _RPC_CIRCUIT_V:
+                       if (!(nconf->nc_flag & NC_VISIBLE))
+                               continue;
+                       /* FALLTHROUGH */
+               case _RPC_CIRCUIT_N:
+                       if ((nconf->nc_semantics != NC_TPI_COTS) &&
+                               (nconf->nc_semantics != NC_TPI_COTS_ORD))
+                               continue;
+                       break;
+               case _RPC_DATAGRAM_V:
+                       if (!(nconf->nc_flag & NC_VISIBLE))
+                               continue;
+                       /* FALLTHROUGH */
+               case _RPC_DATAGRAM_N:
+                       if (nconf->nc_semantics != NC_TPI_CLTS)
+                               continue;
+                       break;
+               case _RPC_TCP:
+                       if (((nconf->nc_semantics != NC_TPI_COTS) &&
+                               (nconf->nc_semantics != NC_TPI_COTS_ORD)) ||
+                               (strcmp(nconf->nc_protofmly, NC_INET)
+#ifdef INET6
+                                && strcmp(nconf->nc_protofmly, NC_INET6))
+#else
+                               )
+#endif
+                               ||
+                               strcmp(nconf->nc_proto, NC_TCP))
+                               continue;
+                       break;
+               case _RPC_UDP:
+                       if ((nconf->nc_semantics != NC_TPI_CLTS) ||
+                               (strcmp(nconf->nc_protofmly, NC_INET)
+#ifdef INET6
+                               && strcmp(nconf->nc_protofmly, NC_INET6))
+#else
+                               )
+#endif
+                               ||
+                               strcmp(nconf->nc_proto, NC_UDP))
+                               continue;
+                       break;
+               }
+               break;
+       }
+       return (nconf);
+}
+
+void
+__rpc_endconf(vhandle)
+       void * vhandle;
+{
+       struct handle *handle;
+
+       handle = (struct handle *) vhandle;
+       if (handle == NULL) {
+               return;
+       }
+       if (handle->nflag) {
+               endnetpath(handle->nhandle);
+       } else {
+               endnetconfig(handle->nhandle);
+       }
+       free(handle);
+}
+
+/*
+ * Used to ping the NULL procedure for clnt handle.
+ * Returns NULL if fails, else a non-NULL pointer.
+ */
+void *
+rpc_nullproc(clnt)
+       CLIENT *clnt;
+{
+       struct timeval TIMEOUT = {25, 0};
+
+       if (clnt_call(clnt, NULLPROC, (xdrproc_t) xdr_void, NULL,
+               (xdrproc_t) xdr_void, NULL, TIMEOUT) != RPC_SUCCESS) {
+               return (NULL);
+       }
+       return ((void *) clnt);
+}
+
+/*
+ * Try all possible transports until
+ * one succeeds in finding the netconf for the given fd.
+ */
+struct netconfig *
+__rpcgettp(fd)
+       int fd;
+{
+       const char *netid;
+       struct __rpc_sockinfo si;
+
+       if (!__rpc_fd2sockinfo(fd, &si))
+               return NULL;
+
+       if (!__rpc_sockinfo2netid(&si, &netid))
+               return NULL;
+
+       return getnetconfigent(__UNCONST(netid));
+}
+
+int
+__rpc_fd2sockinfo(int fd, struct __rpc_sockinfo *sip)
+{
+       socklen_t len;
+       int type, proto;
+       struct sockaddr_storage ss;
+
+       _DIAGASSERT(sip != NULL);
+
+       len = sizeof ss;
+       if (getsockname(fd, (struct sockaddr *)(void *)&ss, &len) < 0)
+               return 0;
+       sip->si_alen = len;
+
+       len = sizeof type;
+       if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &len) < 0)
+               return 0;
+
+       /* XXX */
+       if (ss.ss_family != AF_LOCAL) {
+               if (type == SOCK_STREAM)
+                       proto = IPPROTO_TCP;
+               else if (type == SOCK_DGRAM)
+                       proto = IPPROTO_UDP;
+               else
+                       return 0;
+       } else
+               proto = 0;
+
+       sip->si_af = ss.ss_family;
+       sip->si_proto = proto;
+       sip->si_socktype = type;
+
+       return 1;
+}
+
+/*
+ * Linear search, but the number of entries is small.
+ */
+int
+__rpc_nconf2sockinfo(const struct netconfig *nconf, struct __rpc_sockinfo *sip)
+{
+       size_t i;
+
+       _DIAGASSERT(nconf != NULL);
+       _DIAGASSERT(sip != NULL);
+
+       for (i = 0; i < (sizeof na_cvt) / (sizeof (struct netid_af)); i++)
+               if (!strcmp(na_cvt[i].netid, nconf->nc_netid)) {
+                       sip->si_af = na_cvt[i].af;
+                       sip->si_proto = na_cvt[i].protocol;
+                       sip->si_socktype =
+                           __rpc_seman2socktype((int)nconf->nc_semantics);
+                       if (sip->si_socktype == -1)
+                               return 0;
+                       sip->si_alen = __rpc_get_a_size(sip->si_af);
+                       return 1;
+               }
+
+       return 0;
+}
+
+int
+__rpc_nconf2fd(const struct netconfig *nconf)
+{
+       struct __rpc_sockinfo si;
+
+       _DIAGASSERT(nconf != NULL);
+
+       if (!__rpc_nconf2sockinfo(nconf, &si))
+               return 0;
+
+       return socket(si.si_af, si.si_socktype, si.si_proto);
+}
+
+int
+__rpc_sockinfo2netid(struct __rpc_sockinfo *sip, const char **netid)
+{
+       size_t i;
+
+       _DIAGASSERT(sip != NULL);
+       /* netid may be NULL */
+
+       for (i = 0; i < (sizeof na_cvt) / (sizeof (struct netid_af)); i++)
+               if (na_cvt[i].af == sip->si_af &&
+                   na_cvt[i].protocol == sip->si_proto) {
+                       if (netid)
+                               *netid = na_cvt[i].netid;
+                       return 1;
+               }
+
+       return 0;
+}
+
+char *
+taddr2uaddr(const struct netconfig *nconf, const struct netbuf *nbuf)
+{
+       struct __rpc_sockinfo si;
+
+       _DIAGASSERT(nconf != NULL);
+       _DIAGASSERT(nbuf != NULL);
+
+       if (!__rpc_nconf2sockinfo(nconf, &si))
+               return NULL;
+       return __rpc_taddr2uaddr_af(si.si_af, nbuf);
+}
+
+struct netbuf *
+uaddr2taddr(const struct netconfig *nconf, const char *uaddr)
+{
+       struct __rpc_sockinfo si;
+
+       _DIAGASSERT(nconf != NULL);
+       _DIAGASSERT(uaddr != NULL);
+       
+       if (!__rpc_nconf2sockinfo(nconf, &si))
+               return NULL;
+       return __rpc_uaddr2taddr_af(si.si_af, uaddr);
+}
+
+char *
+__rpc_taddr2uaddr_af(int af, const struct netbuf *nbuf)
+{
+       char *ret;
+       struct sockaddr_in *sinp;
+       struct sockaddr_un *sun;
+       char namebuf[INET_ADDRSTRLEN];
+#ifdef INET6
+       struct sockaddr_in6 *sin6;
+       char namebuf6[INET6_ADDRSTRLEN];
+#endif
+       u_int16_t port;
+
+       _DIAGASSERT(nbuf != NULL);
+
+       switch (af) {
+       case AF_INET:
+               sinp = nbuf->buf;
+               if (inet_ntop(af, &sinp->sin_addr, namebuf, sizeof namebuf)
+                   == NULL)
+                       return NULL;
+               port = ntohs(sinp->sin_port);
+               if (asprintf(&ret, "%s.%u.%u", namebuf, ((u_int32_t)port) >> 8,
+                   port & 0xff) < 0)
+                       return NULL;
+               break;
+#ifdef INET6
+       case AF_INET6:
+               sin6 = nbuf->buf;
+               if (inet_ntop(af, &sin6->sin6_addr, namebuf6, sizeof namebuf6)
+                   == NULL)
+                       return NULL;
+               port = ntohs(sin6->sin6_port);
+               if (asprintf(&ret, "%s.%u.%u", namebuf6, ((u_int32_t)port) >> 8,
+                   port & 0xff) < 0)
+                       return NULL;
+               break;
+#endif
+       case AF_LOCAL:
+               sun = nbuf->buf;
+               sun->sun_path[sizeof(sun->sun_path) - 1] = '\0'; /* safety */
+               ret = strdup(sun->sun_path);
+               break;
+       default:
+               return NULL;
+       }
+
+       return ret;
+}
+
+struct netbuf *
+__rpc_uaddr2taddr_af(int af, const char *uaddr)
+{
+       struct netbuf *ret = NULL;
+       char *addrstr, *p;
+       unsigned port, portlo, porthi;
+       struct sockaddr_in *sinp;
+#ifdef INET6
+       struct sockaddr_in6 *sin6;
+#endif
+       struct sockaddr_un *sun;
+
+       _DIAGASSERT(uaddr != NULL);
+
+       addrstr = strdup(uaddr);
+       if (addrstr == NULL)
+               return NULL;
+
+       /*
+        * AF_LOCAL addresses are expected to be absolute
+        * pathnames, anything else will be AF_INET or AF_INET6.
+        */
+       port = 0;
+       if (*addrstr != '/') {
+               p = strrchr(addrstr, '.');
+               if (p == NULL)
+                       goto out;
+               portlo = (unsigned)atoi(p + 1);
+               *p = '\0';
+
+               p = strrchr(addrstr, '.');
+               if (p == NULL)
+                       goto out;
+               porthi = (unsigned)atoi(p + 1);
+               *p = '\0';
+               port = (porthi << 8) | portlo;
+       }
+
+       ret = malloc(sizeof(*ret));
+       if (ret == NULL)
+               goto out;
+       
+       switch (af) {
+       case AF_INET:
+               sinp = malloc(sizeof(*sinp));
+               if (sinp == NULL)
+                       goto out;
+               memset(sinp, 0, sizeof *sinp);
+               sinp->sin_family = AF_INET;
+               sinp->sin_port = htons(port);
+               if (inet_pton(AF_INET, addrstr, &sinp->sin_addr) <= 0) {
+                       free(sinp);
+                       free(ret);
+                       ret = NULL;
+                       goto out;
+               }
+               sinp->sin_len = ret->maxlen = ret->len = sizeof *sinp;
+               ret->buf = sinp;
+               break;
+#ifdef INET6
+       case AF_INET6:
+               sin6 = malloc(sizeof(*sin6));
+               if (sin6 == NULL)
+                       goto out;
+               memset(sin6, 0, sizeof *sin6);
+               sin6->sin6_family = AF_INET6;
+               sin6->sin6_port = htons(port);
+               if (inet_pton(AF_INET6, addrstr, &sin6->sin6_addr) <= 0) {
+                       free(sin6);
+                       free(ret);
+                       ret = NULL;
+                       goto out;
+               }
+               sin6->sin6_len = ret->maxlen = ret->len = sizeof *sin6;
+               ret->buf = sin6;
+               break;
+#endif
+       case AF_LOCAL:
+               sun = malloc(sizeof(*sun));
+               if (sun == NULL)
+                       goto out;
+               memset(sun, 0, sizeof *sun);
+               sun->sun_family = AF_LOCAL;
+               strncpy(sun->sun_path, addrstr, sizeof(sun->sun_path) - 1);
+               ret->len = ret->maxlen = sun->sun_len = SUN_LEN(sun);
+               ret->buf = sun;
+               break;
+       default:
+               break;
+       }
+out:
+       free(addrstr);
+       return ret;
+}
+
+int
+__rpc_seman2socktype(int semantics)
+{
+       switch (semantics) {
+       case NC_TPI_CLTS:
+               return SOCK_DGRAM;
+       case NC_TPI_COTS_ORD:
+               return SOCK_STREAM;
+       case NC_TPI_RAW:
+               return SOCK_RAW;
+       default:
+               break;
+       }
+
+       return -1;
+}
+
+int
+__rpc_socktype2seman(int socktype)
+{
+       switch (socktype) {
+       case SOCK_DGRAM:
+               return NC_TPI_CLTS;
+       case SOCK_STREAM:
+               return NC_TPI_COTS_ORD;
+       case SOCK_RAW:
+               return NC_TPI_RAW;
+       default:
+               break;
+       }
+
+       return -1;
+}
+
+/*
+ * XXXX - IPv6 scope IDs can't be handled in universal addresses.
+ * Here, we compare the original server address to that of the RPC
+ * service we just received back from a call to rpcbind on the remote
+ * machine. If they are both "link local" or "site local", copy
+ * the scope id of the server address over to the service address.
+ */
+/* ARGSUSED */
+int
+__rpc_fixup_addr(struct netbuf *new, const struct netbuf *svc)
+{
+#ifdef INET6
+       struct sockaddr *sa_new, *sa_svc;
+       struct sockaddr_in6 *sin6_new, *sin6_svc;
+
+       _DIAGASSERT(new != NULL);
+       _DIAGASSERT(svc != NULL);
+
+       sa_svc = (struct sockaddr *)svc->buf;
+       sa_new = (struct sockaddr *)new->buf;
+
+       if (sa_new->sa_family == sa_svc->sa_family &&
+           sa_new->sa_family == AF_INET6) {
+               sin6_new = (struct sockaddr_in6 *)new->buf;
+               sin6_svc = (struct sockaddr_in6 *)svc->buf;
+
+               if ((IN6_IS_ADDR_LINKLOCAL(&sin6_new->sin6_addr) &&
+                    IN6_IS_ADDR_LINKLOCAL(&sin6_svc->sin6_addr)) ||
+                   (IN6_IS_ADDR_SITELOCAL(&sin6_new->sin6_addr) &&
+                    IN6_IS_ADDR_SITELOCAL(&sin6_svc->sin6_addr))) {
+                       sin6_new->sin6_scope_id = sin6_svc->sin6_scope_id;
+               }
+       }
+#endif
+       return 1;
+}
+
+int
+__rpc_sockisbound(int fd)
+{
+       struct sockaddr_storage ss;
+       socklen_t slen;
+
+       slen = sizeof (struct sockaddr_storage);
+       if (getsockname(fd, (struct sockaddr *)(void *)&ss, &slen) < 0)
+               return 0;
+
+       switch (ss.ss_family) {
+               case AF_INET:
+                       return (((struct sockaddr_in *)
+                           (void *)&ss)->sin_port != 0);
+#ifdef INET6
+               case AF_INET6:
+                       return (((struct sockaddr_in6 *)
+                           (void *)&ss)->sin6_port != 0);
+#endif
+               case AF_LOCAL:
+                       /* XXX check this */
+                       return (((struct sockaddr_un *)
+                           (void *)&ss)->sun_path[0] != '\0');
+               default:
+                       break;
+       }
+
+       return 0;
+}
+
+/*
+ * For TCP transport, Host Requirements RFCs mandate
+ * Nagle (RFC-896) processing.  But for RPC, Nagle
+ * processing adds adds unwanted latency to the last,
+ * partial TCP segment of each RPC message. See:
+ *   R. W. Scheifler and J. Gettys, The X Window System,
+ *   ACM Transactions on Graphics 16:8 (Aug. 1983), pp. 57-69. 
+ * So for TCP transport, disable Nagle via TCP_NODELAY.
+ * XXX: moral equivalent for non-TCP protocols?
+ */
+int
+__rpc_setnodelay(int fd, const struct __rpc_sockinfo *si)
+{
+       int one = 1;
+       if (si->si_proto != IPPROTO_TCP)
+               return 0;
+       return setsockopt(fd, si->si_proto, TCP_NODELAY, &one, sizeof(one));
+}
diff --git a/lib/nbsd_libc/rpc/rpc_internal.h b/lib/nbsd_libc/rpc/rpc_internal.h
new file mode 100644 (file)
index 0000000..54cd48e
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: rpc_internal.h,v 1.6 2009/04/04 15:31:08 christos Exp $        */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Frank van der Linden.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+/*
+ * Private include file for XDR functions only used internally in libc.
+ * These are not exported interfaces.
+ */
+
+bool_t __xdrrec_getrec(XDR *, enum xprt_stat *, bool_t);
+bool_t __xdrrec_setnonblock(XDR *, int);
+void __xprt_unregister_unlocked(SVCXPRT *);
+bool_t __svc_clean_idle(fd_set *, int, bool_t);
+
+u_int __rpc_get_a_size(int);
+int __rpc_dtbsize(void);
+struct netconfig *__rpcgettp(int);
+int  __rpc_get_default_domain(char **);
+
+char *__rpc_taddr2uaddr_af(int, const struct netbuf *);
+struct netbuf *__rpc_uaddr2taddr_af(int, const char *);
+int __rpc_fixup_addr(struct netbuf *, const struct netbuf *);
+int __rpc_sockinfo2netid(struct __rpc_sockinfo *, const char **);
+int __rpc_seman2socktype(int);
+int __rpc_socktype2seman(int);
+void *rpc_nullproc(CLIENT *);
+int __rpc_sockisbound(int);
+
+struct netbuf *__rpcb_findaddr(rpcprog_t, rpcvers_t, const struct netconfig *,
+    const char *, CLIENT **);
+bool_t __rpc_control(int, void *);
+
+char *_get_next_token(char *, int);
+
+u_int32_t __rpc_getxid(void);
+#define __RPC_GETXID() (__rpc_getxid())
+
+extern SVCXPRT **__svc_xports;
+extern int __svc_maxrec;
diff --git a/lib/nbsd_libc/rpc/rpc_prot.c b/lib/nbsd_libc/rpc/rpc_prot.c
new file mode 100644 (file)
index 0000000..8f0cfb3
--- /dev/null
@@ -0,0 +1,364 @@
+/*     $NetBSD: rpc_prot.c,v 1.18 2003/05/29 18:15:25 christos Exp $   */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)rpc_prot.c 1.36 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)rpc_prot.c  2.3 88/08/07 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: rpc_prot.c,v 1.18 2003/05/29 18:15:25 christos Exp $");
+#endif
+#endif
+
+/*
+ * rpc_prot.c
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ * This set of routines implements the rpc message definition,
+ * its serializer and some common rpc utility routines.
+ * The routines are meant for various implementations of rpc -
+ * they are NOT for the rpc client or rpc service implementations!
+ * Because authentication stuff is easy and is part of rpc, the opaque
+ * routines are also in this program.
+ */
+
+#include "namespace.h"
+
+#include <sys/param.h>
+
+#include <assert.h>
+
+#include <rpc/rpc.h>
+
+#ifdef __weak_alias
+__weak_alias(xdr_accepted_reply,_xdr_accepted_reply)
+__weak_alias(xdr_callhdr,_xdr_callhdr)
+__weak_alias(xdr_des_block,_xdr_des_block)
+__weak_alias(xdr_opaque_auth,_xdr_opaque_auth)
+__weak_alias(xdr_rejected_reply,_xdr_rejected_reply)
+__weak_alias(xdr_replymsg,_xdr_replymsg)
+#endif
+
+static void accepted __P((enum accept_stat, struct rpc_err *));
+static void rejected __P((enum reject_stat, struct rpc_err *));
+
+/* * * * * * * * * * * * * * XDR Authentication * * * * * * * * * * * */
+
+/*
+ * XDR an opaque authentication struct
+ * (see auth.h)
+ */
+bool_t
+xdr_opaque_auth(xdrs, ap)
+       XDR *xdrs;
+       struct opaque_auth *ap;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(ap != NULL);
+
+       if (xdr_enum(xdrs, &(ap->oa_flavor)))
+               return (xdr_bytes(xdrs, &ap->oa_base,
+                       &ap->oa_length, MAX_AUTH_BYTES));
+       return (FALSE);
+}
+
+/*
+ * XDR a DES block
+ */
+bool_t
+xdr_des_block(xdrs, blkp)
+       XDR *xdrs;
+       des_block *blkp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(blkp != NULL);
+
+       return (xdr_opaque(xdrs, (caddr_t)(void *)blkp, sizeof(des_block)));
+}
+
+/* * * * * * * * * * * * * * XDR RPC MESSAGE * * * * * * * * * * * * * * * */
+
+/*
+ * XDR the MSG_ACCEPTED part of a reply message union
+ */
+bool_t 
+xdr_accepted_reply(xdrs, ar)
+       XDR *xdrs;   
+       struct accepted_reply *ar;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(ar != NULL);
+
+       /* personalized union, rather than calling xdr_union */
+       if (! xdr_opaque_auth(xdrs, &(ar->ar_verf)))
+               return (FALSE);
+       if (! xdr_enum(xdrs, (enum_t *)(void *)&(ar->ar_stat)))
+               return (FALSE);
+       switch (ar->ar_stat) {
+
+       case SUCCESS:
+               return ((*(ar->ar_results.proc))(xdrs, ar->ar_results.where));
+
+       case PROG_MISMATCH:
+               if (! xdr_u_int32_t(xdrs, &(ar->ar_vers.low)))
+                       return (FALSE);
+               return (xdr_u_int32_t(xdrs, &(ar->ar_vers.high)));
+
+       case GARBAGE_ARGS:
+       case SYSTEM_ERR:
+       case PROC_UNAVAIL:
+       case PROG_UNAVAIL:
+               break;
+       }
+       return (TRUE);  /* TRUE => open ended set of problems */
+}
+
+/*
+ * XDR the MSG_DENIED part of a reply message union
+ */
+bool_t 
+xdr_rejected_reply(xdrs, rr)
+       XDR *xdrs;
+       struct rejected_reply *rr;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(rr != NULL);
+
+       /* personalized union, rather than calling xdr_union */
+       if (! xdr_enum(xdrs, (enum_t *)(void *)&(rr->rj_stat)))
+               return (FALSE);
+       switch (rr->rj_stat) {
+
+       case RPC_MISMATCH:
+               if (! xdr_u_int32_t(xdrs, &(rr->rj_vers.low)))
+                       return (FALSE);
+               return (xdr_u_int32_t(xdrs, &(rr->rj_vers.high)));
+
+       case AUTH_ERROR:
+               return (xdr_enum(xdrs, (enum_t *)(void *)&(rr->rj_why)));
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+static const struct xdr_discrim reply_dscrm[3] = {
+       { (int)MSG_ACCEPTED, (xdrproc_t)xdr_accepted_reply },
+       { (int)MSG_DENIED, (xdrproc_t)xdr_rejected_reply },
+       { __dontcare__, NULL_xdrproc_t } };
+
+/*
+ * XDR a reply message
+ */
+bool_t
+xdr_replymsg(xdrs, rmsg)
+       XDR *xdrs;
+       struct rpc_msg *rmsg;
+{
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(rmsg != NULL);
+
+       if (
+           xdr_u_int32_t(xdrs, &(rmsg->rm_xid)) && 
+           xdr_enum(xdrs, (enum_t *)(void *)&(rmsg->rm_direction)) &&
+           (rmsg->rm_direction == REPLY) )
+               return (xdr_union(xdrs, (enum_t *)(void *)&(rmsg->rm_reply.rp_stat),
+                  (caddr_t)(void *)&(rmsg->rm_reply.ru), reply_dscrm,
+                  NULL_xdrproc_t));
+       return (FALSE);
+}
+
+
+/*
+ * Serializes the "static part" of a call message header.
+ * The fields include: rm_xid, rm_direction, rpcvers, prog, and vers.
+ * The rm_xid is not really static, but the user can easily munge on the fly.
+ */
+bool_t
+xdr_callhdr(xdrs, cmsg)
+       XDR *xdrs;
+       struct rpc_msg *cmsg;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(cmsg != NULL);
+
+       cmsg->rm_direction = CALL;
+       cmsg->rm_call.cb_rpcvers = RPC_MSG_VERSION;
+       if (
+           (xdrs->x_op == XDR_ENCODE) &&
+           xdr_u_int32_t(xdrs, &(cmsg->rm_xid)) &&
+           xdr_enum(xdrs, (enum_t *)(void *)&(cmsg->rm_direction)) &&
+           xdr_u_int32_t(xdrs, &(cmsg->rm_call.cb_rpcvers)) &&
+           xdr_u_int32_t(xdrs, &(cmsg->rm_call.cb_prog)) )
+               return (xdr_u_int32_t(xdrs, &(cmsg->rm_call.cb_vers)));
+       return (FALSE);
+}
+
+/* ************************** Client utility routine ************* */
+
+static void
+accepted(acpt_stat, error)
+       enum accept_stat acpt_stat;
+       struct rpc_err *error;
+{
+
+       _DIAGASSERT(error != NULL);
+
+       switch (acpt_stat) {
+
+       case PROG_UNAVAIL:
+               error->re_status = RPC_PROGUNAVAIL;
+               return;
+
+       case PROG_MISMATCH:
+               error->re_status = RPC_PROGVERSMISMATCH;
+               return;
+
+       case PROC_UNAVAIL:
+               error->re_status = RPC_PROCUNAVAIL;
+               return;
+
+       case GARBAGE_ARGS:
+               error->re_status = RPC_CANTDECODEARGS;
+               return;
+
+       case SYSTEM_ERR:
+               error->re_status = RPC_SYSTEMERROR;
+               return;
+
+       case SUCCESS:
+               error->re_status = RPC_SUCCESS;
+               return;
+       }
+       /* NOTREACHED */
+       /* something's wrong, but we don't know what ... */
+       error->re_status = RPC_FAILED;
+       error->re_lb.s1 = (int32_t)MSG_ACCEPTED;
+       error->re_lb.s2 = (int32_t)acpt_stat;
+}
+
+static void 
+rejected(rjct_stat, error)
+       enum reject_stat rjct_stat;
+       struct rpc_err *error;
+{
+
+       _DIAGASSERT(error != NULL);
+
+       switch (rjct_stat) {
+       case RPC_MISMATCH:
+               error->re_status = RPC_VERSMISMATCH;
+               return;
+
+       case AUTH_ERROR:
+               error->re_status = RPC_AUTHERROR;
+               return;
+       }
+       /* something's wrong, but we don't know what ... */
+       /* NOTREACHED */
+       error->re_status = RPC_FAILED;
+       error->re_lb.s1 = (int32_t)MSG_DENIED;
+       error->re_lb.s2 = (int32_t)rjct_stat;
+}
+
+/*
+ * given a reply message, fills in the error
+ */
+void
+_seterr_reply(msg, error)
+       struct rpc_msg *msg;
+       struct rpc_err *error;
+{
+
+       _DIAGASSERT(msg != NULL);
+       _DIAGASSERT(error != NULL);
+
+       /* optimized for normal, SUCCESSful case */
+       switch (msg->rm_reply.rp_stat) {
+
+       case MSG_ACCEPTED:
+               if (msg->acpted_rply.ar_stat == SUCCESS) {
+                       error->re_status = RPC_SUCCESS;
+                       return;
+               }
+               accepted(msg->acpted_rply.ar_stat, error);
+               break;
+
+       case MSG_DENIED:
+               rejected(msg->rjcted_rply.rj_stat, error);
+               break;
+
+       default:
+               error->re_status = RPC_FAILED;
+               error->re_lb.s1 = (int32_t)(msg->rm_reply.rp_stat);
+               break;
+       }
+       switch (error->re_status) {
+
+       case RPC_VERSMISMATCH:
+               error->re_vers.low = msg->rjcted_rply.rj_vers.low;
+               error->re_vers.high = msg->rjcted_rply.rj_vers.high;
+               break;
+
+       case RPC_AUTHERROR:
+               error->re_why = msg->rjcted_rply.rj_why;
+               break;
+
+       case RPC_PROGVERSMISMATCH:
+               error->re_vers.low = msg->acpted_rply.ar_vers.low;
+               error->re_vers.high = msg->acpted_rply.ar_vers.high;
+               break;
+
+       case RPC_FAILED:
+       case RPC_SUCCESS:
+       case RPC_PROGNOTREGISTERED:
+       case RPC_PMAPFAILURE:
+       case RPC_UNKNOWNPROTO:
+       case RPC_UNKNOWNHOST:
+       case RPC_SYSTEMERROR:
+       case RPC_CANTDECODEARGS:
+       case RPC_PROCUNAVAIL:
+       case RPC_PROGUNAVAIL:
+       case RPC_TIMEDOUT:
+       case RPC_CANTRECV:
+       case RPC_CANTSEND:
+       case RPC_CANTDECODERES:
+       case RPC_CANTENCODEARGS:
+       default:
+               break;
+       }
+}
diff --git a/lib/nbsd_libc/rpc/rpc_soc.3 b/lib/nbsd_libc/rpc/rpc_soc.3
new file mode 100644 (file)
index 0000000..e9296c1
--- /dev/null
@@ -0,0 +1,1066 @@
+.\"    @(#)rpc.3n      2.4 88/08/08 4.0 RPCSRC; from 1.19 88/06/24 SMI
+.\"    $NetBSD: rpc_soc.3,v 1.13 2009/01/11 02:46:29 christos Exp $
+.\" Converted to mdoc by Thomas Klausner <wiz@NetBSD.org>
+.\"
+.Dd December 12, 2008
+.Dt RPC_SOC 3
+.Os
+.Sh NAME
+.Nm rpc_soc ,
+.Nm auth_destroy ,
+.Nm authnone_create ,
+.Nm authunix_create ,
+.Nm authunix_create_default ,
+.Nm callrpc ,
+.Nm clnt_broadcast ,
+.Nm clnt_call ,
+.Nm clnt_control ,
+.Nm clnt_create ,
+.Nm clnt_destroy ,
+.Nm clnt_freeres ,
+.Nm clnt_geterr ,
+.Nm clnt_pcreateerror ,
+.Nm clnt_perrno ,
+.Nm clnt_perror ,
+.Nm clnt_spcreateerror ,
+.Nm clnt_sperrno ,
+.Nm clnt_sperror ,
+.Nm clntraw_create ,
+.Nm clnttcp_create ,
+.Nm clntudp_bufcreate ,
+.Nm clntudp_create ,
+.Nm get_myaddress ,
+.Nm pmap_getmaps ,
+.Nm pmap_getport ,
+.Nm pmap_rmtcall ,
+.Nm pmap_set ,
+.Nm pmap_unset ,
+.Nm registerrpc ,
+.Nm rpc_createerr ,
+.Nm svc_destroy ,
+.Nm svc_fds ,
+.Nm svc_fdset ,
+.Nm svc_getargs ,
+.Nm svc_getcaller ,
+.Nm svc_getreg ,
+.Nm svc_getregset ,
+.Nm svc_getrpccaller ,
+.Nm svc_register ,
+.Nm svc_run ,
+.Nm svc_sendreply ,
+.Nm svc_unregister ,
+.Nm svcerr_auth ,
+.Nm svcerr_decode ,
+.Nm svcerr_noproc ,
+.Nm svcerr_noprog ,
+.Nm svcerr_progvers ,
+.Nm svcerr_systemerr ,
+.Nm svcerr_weakauth ,
+.Nm svcfd_create ,
+.Nm svcraw_create ,
+.Nm xdr_accepted_reply ,
+.Nm xdr_authunix_parms ,
+.Nm xdr_callhdr ,
+.Nm xdr_callmsg ,
+.Nm xdr_opaque_auth ,
+.Nm xdr_pmap ,
+.Nm xdr_pmaplist ,
+.Nm xdr_rejected_reply ,
+.Nm xdr_replymsg ,
+.Nm xprt_register ,
+.Nm xprt_unregister
+.Nd library routines for remote procedure calls
+.Sh SYNOPSIS
+.In rpc/rpc.h
+.Ft void
+.Fn auth_destroy "AUTH *auth"
+.Ft AUTH *
+.Fn authnone_create "void"
+.Ft AUTH *
+.Fn authunix_create "char *host" "int uid" "int gid" "int len" "int *aup_gids"
+.Ft AUTH *
+.Fn authunix_create_default "void"
+.Ft int
+.Fn callrpc "char *host" "u_long prognum" "u_long versnum" \
+"u_long procnum" "xdrproc_t inproc" "char *in" "xdrproc_t outproc" "char *out"
+.Ft enum clnt_stat
+.Fn clnt_broadcast "u_long prognum" "u_long versnum" "u_long procnum" \
+"xdrproc_t inproc" "char *in" "xdrproc_t outproc" "char *out" \
+"resultproc_t eachresult"
+.Ft enum clnt_stat
+.Fn clnt_call "CLIENT *clnt" "u_long procnum" "xdrproc_t inproc" \
+"char *in" "xdrproc_t outproc" "char *out" "struct timeval tout"
+.Ft int
+.Fn clnt_destroy "CLIENT *clnt"
+.Ft CLIENT *
+.Fn clnt_create "char *host" "u_long prog" "u_long vers" "char *proto"
+.Ft bool_t
+.Fn clnt_control "CLIENT *cl" "u_int req" "char *info"
+.Ft int
+.Fn clnt_freeres "CLIENT *clnt" "xdrproc_t outproc" "char *out"
+.Ft void
+.Fn clnt_geterr "CLIENT *clnt" "struct rpc_err errp"
+.Ft void
+.Fn clnt_pcreateerror "char *s"
+.Ft void
+.Fn clnt_perrno "enum clnt_stat stat"
+.Ft int
+.Fn clnt_perror "CLIENT *clnt" "char *s"
+.Ft char *
+.Fn clnt_spcreateerror "const char *s"
+.Ft char *
+.Fn clnt_sperrno "enum clnt_stat stat"
+.Ft char *
+.Fn clnt_sperror "CLIENT *rpch" "char *s"
+.Ft CLIENT *
+.Fn clntraw_create "u_long prognum" "u_long versnum"
+.Ft CLIENT *
+.Fn clnttcp_create "struct sockaddr_in *addr" "u_long prognum" \
+"u_long versnum" "int *sockp" "u_int sendsz" "u_int recvsz"
+.Ft CLIENT *
+.Fn clntudp_create "struct sockaddr_in *addr" "u_long prognum" \
+"u_long versnum" "struct timeval wait" "int *sockp"
+.Ft CLIENT *
+.Fn clntudp_bufcreate "struct sockaddr_in *addr" "u_long prognum" \
+"u_long versnum" "struct timeval wait" "int *sockp" \
+"unsigned int sendsize" "unsigned int recosize"
+.Ft int
+.Fn get_myaddress "struct sockaddr_in *addr"
+.Ft struct pmaplist *
+.Fn pmap_getmaps "struct sockaddr_in *addr"
+.Ft u_short
+.Fn pmap_getport "struct sockaddr_in *addr" "u_long prognum" \
+"u_long versnum" "u_long protocol"
+.Ft enum clnt_stat
+.Fo pmap_rmtcall
+.Fa "struct sockaddr_in *addr"
+.Fa "u_long prognum"
+.Fa "u_long versnum"
+.Fa "u_long procnum"
+.Fa "xdrproc_t inproc"
+.Fa "char *in"
+.Fa "xdrpoc_t outproc"
+.Fa "char *out"
+.Fa "struct timeval tout"
+.Fa "u_long *portp"
+.Fc
+.Ft int
+.Fn pmap_set "u_long prognum" "u_long versnum" "int protocol" \
+"int port"
+.Ft int
+.Fn pmap_unset "u_long prognum" "u_long versnum"
+.Ft int
+.Fn registerrpc "u_long prognum" "u_long versnum" "u_long procnum" \
+"char *(*procname)()" "xdrproc_t inproc" "xdrproc_t outproc"
+.Fd struct rpc_createerr rpc_createerr;
+.Ft int
+.Fn svc_destroy "SVCXPRT *xprt"
+.Fd fd_set svc_fdset;
+.Fd int svc_fds;
+.Ft int
+.Fn svc_freeargs "SVCXPRT *xprt" "xdrproc_t inproc" "char *in"
+.Ft int
+.Fn svc_getargs "SVCXPRT *xprt" "xdrproc_t inproc" "char *in"
+.Ft struct sockaddr_in *
+.Fn svc_getcaller "SVCXPRT *xprt"
+.Ft int
+.Fn svc_getreqset "fd_set *rdfds"
+.Ft int
+.Fn svc_getreq "int rdfds"
+.Ft struct netbuf *
+.Fn svc_getrpccaller "SVCXPRT *xprt"
+.Ft int
+.Fn svc_register "SVCXPRT *xprt" "u_long prognum" "u_long versnum" \
+"void (*dispatch)()" "u_long protocol"
+.Ft int
+.Fn svc_run "void"
+.Ft int
+.Fn svc_sendreply "SVCXPRT *xprt" "xdrproc_t outproc" "char *out"
+.Ft void
+.Fn svc_unregister "u_long prognum" "u_long versnum"
+.Ft void
+.Fn svcerr_auth "SVCXPRT *xprt" "enum auth_stat why"
+.Ft void
+.Fn svcerr_decode "SVCXPRT *xprt"
+.Ft void
+.Fn svcerr_noproc "SVCXPRT *xprt"
+.Ft void
+.Fn svcerr_noprog "SVCXPRT *xprt"
+.Ft void
+.Fn svcerr_progvers "SVCXPRT *xprt"
+.Ft void
+.Fn svcerr_systemerr "SVCXPRT *xprt"
+.Ft void
+.Fn svcerr_weakauth "SVCXPRT *xprt"
+.Ft SVCXPRT *
+.Fn svcraw_create "void"
+.Ft SVCXPRT *
+.Fn svctcp_create "int sock" "u_int send_buf_size" \
+"u_int recv_buf_size"
+.Ft SVCXPRT *
+.Fn svcfd_create "int fd" "u_int sendsize" "u_int recvsize"
+.Ft SVCXPRT *
+.Fn svcudp_bufcreate "int sock" "u_int sendsize" "u_int recosize"
+.Ft SVCXPRT *
+.Fn svcudp_create "int sock"
+.Ft int
+.Fn xdr_accepted_reply "XDR *xdrs" "struct accepted_reply *ar"
+.Ft int
+.Fn xdr_authunix_parms "XDR *xdrs" "struct authunix_parms *aupp"
+.Ft void
+.Fn xdr_callhdr "XDR *xdrs" "struct rpc_msg *chdr"
+.Ft int
+.Fn xdr_callmsg "XDR *xdrs" "struct rpc_msg *cmsg"
+.Ft int
+.Fn xdr_opaque_auth "XDR *xdrs" "struct opaque_auth *ap"
+.Ft int
+.Fn xdr_pmap "XDR *xdrs" "struct pmap *regs"
+.Ft int
+.Fn xdr_pmaplist "XDR *xdrs" "struct pmaplist **rp"
+.Ft int
+.Fn xdr_rejected_reply "XDR *xdrs" "struct rejected_reply *rr"
+.Ft int
+.Fn xdr_replymsg "XDR *xdrs" "struct rpc_msg *rmsg"
+.Ft void
+.Fn xprt_register "SVCXPRT *xprt"
+.Ft void
+.Fn xprt_unregister "SVCXPRT *xprt"
+.Sh DESCRIPTION
+.Em "The svc and clnt functions described in this page are the old, TS-RPC"
+.Em "interface to the XDR and RPC library, and exist for backward compatibility."
+.Em "The new interface is described in the pages referenced from"
+.Xr rpc 3 .
+.Pp
+These routines allow C programs to make procedure
+calls on other machines across the network.
+First, the client calls a procedure to send a
+data packet to the server.
+Upon receipt of the packet, the server calls a dispatch routine
+to perform the requested service, and then sends back a
+reply.
+Finally, the procedure call returns to the client.
+.\" XXX: NOTYET
+.\".Pp
+.\"Routines that are used for Secure RPC (DES authentication) are described in
+.\".Xr rpc_secure 3 .
+.\"Secure RPC can be used only if DES encryption is available.
+.Pp
+.Bl -tag -width xxx
+.It Fn auth_destroy
+A macro that destroys the authentication information associated with
+.Fa auth .
+Destruction usually involves deallocation of private data structures.
+The use of
+.Fa auth
+is undefined after calling
+.Fn auth_destroy .
+.It Fn authnone_create
+Create and returns an RPC authentication handle that passes nonusable
+authentication information with each remote procedure call.
+This is the default authentication used by RPC.
+.It Fn authunix_create
+Create and return an RPC authentication handle that contains
+.\" XXX: .UX ?
+authentication information.
+The parameter
+.Fa host
+is the name of the machine on which the information was
+created;
+.Fa uid
+is the user's user ID;
+.Fa gid
+is the user's current group id;
+.Fa len
+and
+.Fa aup_gids
+refer to a counted array of groups to which the user belongs.
+It is easy to impersonate a user.
+.It Fn authunix_create_default
+Calls
+.Fn authunix_create
+with the appropriate parameters.
+.It Fn callrpc
+Call the remote procedure associated with
+.Fa prognum ,
+.Fa versnum ,
+and
+.Fa procnum
+on the machine,
+.Fa host .
+The parameter
+.Fa in
+is the address of the procedure's argument(s), and
+.Fa out
+is the address of where to place the result(s);
+.Fa inproc
+is used to encode the procedure's parameters, and
+.Fa outproc
+is used to decode the procedure's results.
+This routine returns zero if it succeeds, or the value of
+.Va "enum clnt_stat"
+cast to an integer if it fails.
+The routine
+.Fn clnt_perrno
+is handy for translating failure statuses into messages.
+.Pp
+Warning: calling remote procedures with this routine
+uses UDP/IP as a transport; see
+.Fn clntudp_create
+for restrictions.
+You do not have control of timeouts or authentication using
+this routine.
+.It Fn clnt_broadcast
+Like
+.Fn callrpc ,
+except the call message is broadcast to all locally
+connected broadcast nets.
+Each time it receives a response, this routine calls
+.Fn eachresult ,
+whose form is
+.Ft int
+.Fn eachresult "char *out" "struct sockaddr_in *addr"
+where
+.Fa out
+is the same as
+.Fa out
+passed to
+.Fn clnt_broadcast ,
+except that the remote procedure's output is decoded there;
+.Fa addr
+points to the address of the machine that sent the results.
+If
+.Fn eachresult
+returns zero,
+.Fn clnt_broadcast
+waits for more replies; otherwise it returns with appropriate
+status.
+.Pp
+Warning: broadcast sockets are limited in size to the
+maximum transfer unit of the data link.
+For ethernet, this value is 1500 bytes.
+.It Fn clnt_call
+A macro that calls the remote procedure
+.Fa procnum
+associated with the client handle,
+.Fa clnt ,
+which is obtained with an RPC client creation routine such as
+.Fn clnt_create .
+The parameter
+.Fa in
+is the address of the procedure's argument(s), and
+.Fa out
+is the address of where to place the result(s);
+.Fa inproc
+is used to encode the procedure's parameters, and
+.Fa outproc
+is used to decode the procedure's results;
+.Fa tout
+is the time allowed for results to come back.
+.It Fn clnt_destroy
+A macro that destroys the client's RPC handle.
+Destruction usually involves deallocation
+of private data structures, including
+.Fa clnt
+itself.
+Use of
+.Fa clnt
+is undefined after calling
+.Fn clnt_destroy .
+If the RPC library opened the associated socket, it will close it
+also.
+Otherwise, the socket remains open.
+.It Fn clnt_create
+Generic client creation routine.
+.Fa host
+identifies the name of the remote host where the server
+is located.
+.Fa proto
+indicates which kind of transport protocol to use.
+The currently supported values for this field are
+.Dq udp
+and
+.Dq tcp .
+Default timeouts are set, but can be modified using
+.Fn clnt_control .
+.Pp
+.Em Warning :
+Using UDP has its shortcomings.
+Since UDP-based RPC messages can only hold up to 8 Kbytes of encoded
+data, this transport cannot be used for procedures that take
+large arguments or return huge results.
+.It Fn clnt_control
+A macro used to change or retrieve various information
+about a client object.
+.Fa req
+indicates the type of operation, and
+.Fa info
+is a pointer to the information.
+For both UDP and TCP the supported values of
+.Fa req
+and their argument types and what they do are:
+.Bl -tag -width CLSET_RETRY_TIMEOUTX
+.It CLSET_TIMEOUT
+.Vt struct timeval ;
+set total timeout.
+.It CLGET_TIMEOUT
+.Vt struct timeval ;
+get total timeout.
+.Pp
+Note: if you set the timeout using
+.Fn clnt_control ,
+the timeout parameter passed to
+.Fn clnt_call
+will be ignored in all future calls.
+.It CLGET_SERVER_ADDR
+.Vt struct sockaddr_in ;
+get server's address.
+.El
+.Pp
+The following operations are valid for UDP only:
+.Bl -tag -width CLSET_RETRY_TIMEOUT
+.It CLSET_RETRY_TIMEOUT
+.Vt struct timeval ;
+set the retry timeout.
+.It CLGET_RETRY_TIMEOUT
+.Vt struct timeval ;
+get the retry timeout.
+.Pp
+The retry timeout is the time that UDP RPC waits for the server to
+reply before retransmitting the request.
+.El
+.It Fn clnt_freeres
+A macro that frees any data allocated by the RPC/XDR system when it
+decoded the results of an RPC call.
+The parameter
+.Fa out
+is the address of the results, and
+.Fa outproc
+is the XDR routine describing the results.
+This routine returns one if the results were successfully freed,
+and zero otherwise.
+.It Fn clnt_geterr
+A macro that copies the error structure out of the client
+handle to the structure at address
+.Fa errp .
+.It Fn clnt_pcreateerror
+Print a message to standard error indicating why a client RPC handle
+could not be created.
+The message is prepended with string
+.Fa s
+and a colon.
+A newline character is appended at the end of the message.
+Used when a
+.Fn clnt_create ,
+.Fn clntraw_create ,
+.Fn clnttcp_create ,
+or
+.Fn clntudp_create
+call fails.
+.It Fn clnt_perrno
+Print a message to standard error corresponding
+to the condition indicated by
+.Fa stat .
+A newline character is appended at the end of the message.
+Used after
+.Fn callrpc .
+.It Fn clnt_perror
+Print a message to standard error indicating why an RPC call failed;
+.Fa clnt
+is the handle used to do the call.
+The message is prepended with string
+.Fa s
+and a colon.
+A newline character is appended at the end of the message.
+Used after
+.Fn clnt_call .
+.It Fn clnt_spcreateerror
+Like
+.Fn clnt_pcreateerror ,
+except that it returns a string
+instead of printing to the standard error.
+.Pp
+Bugs: returns pointer to static data that is overwritten
+on each call.
+.It Fn clnt_sperrno
+Take the same arguments as
+.Fn clnt_perrno ,
+but instead of sending a message to the standard error
+indicating why an RPC call failed, return a pointer to a string which
+contains the message.
+.Pp
+.Fn clnt_sperrno
+is used instead of
+.Fn clnt_perrno
+if the program does not have a standard error (as a program
+running as a server quite likely does not), or if the
+programmer does not want the message to be output with
+.Xr printf 3 ,
+or if a message format different than that supported by
+.Fn clnt_perrno
+is to be used.
+Note: unlike
+.Fn clnt_sperror
+and
+.Fn clnt_spcreateerror ,
+.Fn clnt_sperrno
+returns a pointer to static data, but the
+result will not get overwritten on each call.
+.It Fn clnt_sperror
+Like
+.Fn clnt_perror ,
+except that (like
+.Fn clnt_sperrno )
+it returns a string instead of printing to standard error.
+.Pp
+Bugs: returns pointer to static data that is overwritten
+on each call.
+.It Fn clntraw_create
+This routine creates a toy RPC client for the remote program
+.Fa prognum ,
+version
+.Fa versnum .
+The transport used to pass messages to the service is
+actually a buffer within the process's address space, so the
+corresponding RPC server should live in the same address space; see
+.Fn svcraw_create .
+This allows simulation of RPC and acquisition of RPC overheads, such
+as round trip times, without any kernel interference.
+This routine returns
+.Dv NULL
+if it fails.
+.It Fn clnttcp_create
+This routine creates an RPC client for the remote program
+.Fa prognum ,
+version
+.Fa versnum ;
+the client uses TCP/IP as a transport.
+The remote program is located at Internet address
+.Fa *addr .
+If
+.Fa addr-\*[Gt]sin_port
+is zero, then it is set to the actual port that the remote
+program is listening on (the remote
+.Xr rpcbind 8
+or
+.Cm portmap
+service is consulted for this information).
+The parameter
+.Fa sockp
+is a socket; if it is
+.Dv RPC_ANYSOCK ,
+then this routine opens a new one and sets
+.Fa sockp .
+Since TCP-based RPC uses buffered I/O ,
+the user may specify the size of the send and receive buffers
+with the parameters
+.Fa sendsz
+and
+.Fa recvsz ;
+values of zero choose suitable defaults.
+This routine returns
+.Dv NULL
+if it fails.
+.It Fn clntudp_create
+This routine creates an RPC client for the remote program
+.Fa prognum ,
+version
+.Fa versnum ;
+the client uses UDP/IP as a transport.
+The remote program is located at Internet address
+.Fa addr .
+If
+.Fa addr-\*[Gt]sin_port
+is zero, then it is set to actual port that the remote
+program is listening on (the remote
+.Xr rpcbind 8
+or
+.Cm portmap
+service is consulted for this information).
+The parameter
+.Fa sockp
+is a socket; if it is
+.Dv RPC_ANYSOCK ,
+then this routine opens a new one and sets
+.Fa sockp .
+The UDP transport resends the call message in intervals of
+.Fa wait
+time until a response is received or until the call times out.
+The total time for the call to time out is specified by
+.Fa clnt_call .
+.Pp
+Warning: since UDP-based RPC messages can only hold up to 8 Kbytes
+of encoded data, this transport cannot be used for procedures
+that take large arguments or return huge results.
+.It Fn clntudp_bufcreate
+This routine creates an RPC client for the remote program
+.Fa prognum ,
+on
+.Fa versnum ;
+the client uses UDP/IP as a transport.
+The remote program is located at Internet address
+.Fa addr .
+If
+.Fa addr-\*[Gt]sin_port
+is zero, then it is set to actual port that the remote
+program is listening on (the remote
+.Xr rpcbind 8
+or
+.Cm portmap
+service is consulted for this information).
+The parameter
+.Fa sockp
+is a socket; if it is
+.Dv RPC_ANYSOCK ,
+then this routine opens a new one and sets
+.Fa sockp .
+The UDP transport resends the call message in intervals of
+.Fa wait
+time until a response is received or until the call times out.
+The total time for the call to time out is specified by
+.Fa clnt_call .
+.Pp
+This allows the user to specify the maximum packet size for sending and
+receiving UDP-based RPC messages.
+.It Fn get_myaddress
+Stuff the machine's IP address into
+.Fa *addr ,
+without consulting the library routines that deal with
+.Pa /etc/hosts .
+The port number is always set to
+.Fn htons "PMAPPORT" .
+Returns zero on success, non-zero on failure.
+.It Fn pmap_getmaps
+A user interface to the
+.Xr rpcbind 8
+service, which returns a list of the current RPC program-to-port
+mappings on the host located at IP address
+.Fa *addr .
+This routine can return
+.Dv NULL .
+The command
+.Dl Cm rpcinfo Fl p
+uses this routine.
+.It Fn pmap_getport
+A user interface to the
+.Xr rpcbind 8
+service, which returns the port number
+on which waits a service that supports program number
+.Fa prognum ,
+version
+.Fa versnum ,
+and speaks the transport protocol associated with
+.Fa protocol .
+The value of
+.Fa protocol
+is most likely
+.Dv IPPROTO_UDP
+or
+.Dv IPPROTO_TCP .
+A return value of zero means that the mapping does not exist
+or that the RPC system failured to contact the remote
+.Xr rpcbind 8
+service.
+In the latter case, the global variable
+.Fn rpc_createerr
+contains the RPC status.
+.It Fn pmap_rmtcall
+A user interface to the
+.Xr rpcbind 8
+service, which instructs
+.Xr rpcbind 8
+on the host at IP address
+.Fa *addr
+to make an RPC call on your behalf to a procedure on that host.
+The parameter
+.Fa *portp
+will be modified to the program's port number if the
+procedure succeeds.
+The definitions of other parameters are discussed in
+.Fn callrpc
+and
+.Fn clnt_call .
+This procedure should be used for a
+.Dq ping
+and nothing else.
+See also
+.Fn clnt_broadcast .
+.It Fn pmap_set
+A user interface to the
+.Xr rpcbind 8
+service, which establishes a mapping between the triple
+.Fa [ prognum ,
+.Fa versnum ,
+.Fa protocol ]
+and
+.Fa port
+on the machine's
+.Xr rpcbind 8
+service.
+The value of
+.Fa protocol
+is most likely
+.Dv IPPROTO_UDP
+or
+.Dv IPPROTO_TCP .
+This routine returns one if it succeeds, zero otherwise.
+Automatically done by
+.Fn svc_register .
+.It Fn pmap_unset
+A user interface to the
+.Xr rpcbind 8
+service, which destroys all mapping between the triple
+.Fa [ prognum ,
+.Fa versnum ,
+.Fa * ]
+and
+.Fa ports
+on the machine's
+.Xr rpcbind 8
+service.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn registerrpc
+Register procedure
+.Fa procname
+with the RPC service package.
+If a request arrives for program
+.Fa prognum ,
+version
+.Fa versnum ,
+and procedure
+.Fa procnum ,
+.Fa procname
+is called with a pointer to its parameter(s);
+.Fa progname
+should return a pointer to its static result(s);
+.Fa inproc
+is used to decode the parameters while
+.Fa outproc
+is used to encode the results.
+This routine returns zero if the registration succeeded, \-1
+otherwise.
+.Pp
+Warning: remote procedures registered in this form
+are accessed using the UDP/IP transport; see
+.Fn svcudp_bufcreate
+for restrictions.
+.It struct rpc_createerr rpc_createerr ;
+A global variable whose value is set by any RPC
+client creation routine that does not succeed.
+Use the routine
+.Fn clnt_pcreateerror
+to print the reason why.
+.It Fn svc_destroy
+A macro that destroys the RPC service transport handle,
+.Fa xprt .
+Destruction usually involves deallocation
+of private data structures, including
+.Fa xprt
+itself.
+Use of
+.Fa xprt
+is undefined after calling this routine.
+.It fd_set svc_fdset ;
+A global variable reflecting the RPC service side's read file
+descriptor bit mask; it is suitable as a parameter to the
+.Xr select 2
+system call.
+This is only of interest if a service implementor does not call
+.Fn svc_run ,
+but rather does his own asynchronous event processing.
+This variable is read-only (do not pass its address to
+.Xr select 2 ! ) ,
+yet it may change after calls to
+.Fn svc_getreqset
+or any creation routines.
+.It int svc_fds;
+Similar to
+.Fn svc_fedset ,
+but limited to 32 descriptors.
+This interface is obsoleted by
+.Fn svc_fdset .
+.It Fn svc_freeargs
+A macro that frees any data allocated by the RPC/XDR
+system when it decoded the arguments to a service procedure using
+.Fn svc_getargs .
+This routine returns 1 if the results were successfully freed,
+and zero otherwise.
+.It Fn svc_getargs
+A macro that decodes the arguments of an RPC request associated with
+the RPC service transport handle,
+.Fa xprt .
+The parameter
+.Fa in
+is the address where the arguments will be placed;
+.Fa inproc
+is the XDR routine used to decode the arguments.
+This routine returns one if decoding succeeds, and zero otherwise.
+.It Fn svc_getcaller
+The obsolete way of getting the network address of the caller
+of a procedure associated with the RPC service transport handle,
+.Fa xprt ,
+use
+.Fn svc_getrpccaller .
+.It Fn svc_getreqset
+This routine is only of interest if a service implementor
+does not call
+.Fn svc_run ,
+but instead implements custom asynchronous event processing.
+It is called when the
+.Xr select 2
+system call has determined that an RPC request has arrived on some
+RPC socket(s) ;
+.Fa rdfds
+is the resultant read file descriptor bit mask.
+The routine returns when all sockets associated with the
+value of
+.Fa rdfds
+have been serviced.
+.It Fn svc_getreq
+Similar to
+.Fn svc_getreqset ,
+but limited to 32 descriptors.
+This interface is obsoleted by
+.Fn svc_getreqset .
+.It Fn svc_getrpccaller
+The approved way of getting the network address of the caller
+of a procedure associated with the RPC service transport handle,
+.Fa xprt .
+.It Fn svc_register
+Associates
+.Fa prognum
+and
+.Fa versnum
+with the service dispatch procedure,
+.Fa dispatch .
+If
+.Fa protocol
+is zero, the service is not registered with the
+.Xr rpcbind 8
+service.
+If
+.Fa protocol
+is non-zero, then a mapping of the triple
+.Fa [ prognum ,
+.Fa versnum ,
+.Fa protocol ]
+to
+.Fa xprt-\*[Gt]xp_port
+is established with the local
+.Xr rpcbind 8
+service (generally
+.Fa protocol
+is zero,
+.Dv IPPROTO_UDP
+or
+.Dv IPPROTO_TCP ) .
+The procedure
+.Fa dispatch
+has the following form:
+.Ft int
+.Fn dispatch "struct svc_req *request" "SVCXPRT *xprt" .
+.Pp
+The
+.Fn svc_register
+routine returns one if it succeeds, and zero otherwise.
+.It Fn svc_run
+This routine never returns.
+It waits for RPC requests to arrive, and calls the appropriate service
+procedure using
+.Fn svc_getreq
+when one arrives.
+This procedure is usually waiting for a
+.Xr select 2
+system call to return.
+.It Fn svc_sendreply
+Called by an RPC service's dispatch routine to send the results of a
+remote procedure call.
+The parameter
+.Fa xprt
+is the request's associated transport handle;
+.Fa outproc
+is the XDR routine which is used to encode the results; and
+.Fa out
+is the address of the results.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn svc_unregister
+Remove all mapping of the double
+.Fa [ prognum ,
+.Fa versnum ]
+to dispatch routines, and of the triple
+.Fa [ prognum ,
+.Fa versnum ,
+.Fa * ]
+to port number.
+.It Fn svcerr_auth
+Called by a service dispatch routine that refuses to perform
+a remote procedure call due to an authentication error.
+.It Fn svcerr_decode
+Called by a service dispatch routine that cannot successfully
+decode its parameters.
+See also
+.Fn svc_getargs .
+.It Fn svcerr_noproc
+Called by a service dispatch routine that does not implement
+the procedure number that the caller requests.
+.It Fn svcerr_noprog
+Called when the desired program is not registered with the RPC
+package.
+Service implementors usually do not need this routine.
+.It Fn svcerr_progvers
+Called when the desired version of a program is not registered
+with the RPC package.
+Service implementors usually do not need this routine.
+.It Fn svcerr_systemerr
+Called by a service dispatch routine when it detects a system error
+not covered by any particular protocol.
+For example, if a service can no longer allocate storage,
+it may call this routine.
+.It Fn svcerr_weakauth
+Called by a service dispatch routine that refuses to perform
+a remote procedure call due to insufficient
+authentication parameters.
+The routine calls
+.Fn svcerr_auth "xprt" "AUTH_TOOWEAK" .
+.It Fn svcraw_create
+This routine creates a toy RPC service transport, to which it returns
+a pointer.
+The transport is really a buffer within the process's address space,
+so the corresponding RPC client should live in the same address space;
+see
+.Fn clntraw_create .
+This routine allows simulation of RPC and acquisition of RPC overheads
+(such as round trip times), without any kernel interference.
+This routine returns
+.Dv NULL
+if it fails.
+.It Fn svctcp_create
+This routine creates a TCP/IP-based RPC service transport, to which it
+returns a pointer.
+The transport is associated with the socket
+.Fa sock ,
+which may be
+.Dv RPC_ANYSOCK ,
+in which case a new socket is created.
+If the socket is not bound to a local TCP
+port, then this routine binds it to an arbitrary port.
+Upon completion,
+.Fa xprt-\*[Gt]xp_sock
+is the transport's socket descriptor, and
+.Fa xprt-\*[Gt]xp_port
+is the transport's port number.
+This routine returns
+.Dv NULL
+if it fails.
+Since TCP-based RPC uses buffered I/O ,
+users may specify the size of buffers; values of zero
+choose suitable defaults.
+.It Fn svcfd_create
+Create a service on top of any open descriptor.
+Typically, this descriptor is a connected socket
+for a stream protocol such as TCP.
+.Fa sendsize
+and
+.Fa recvsize
+indicate sizes for the send and receive buffers.
+If they are zero, a reasonable default is chosen.
+.It Fn svcudp_bufcreate
+This routine creates a UDP/IP-based RPC
+service transport, to which it returns a pointer.
+The transport is associated with the socket
+.Fa sock ,
+which may be
+.Dv RPC_ANYSOCK ,
+in which case a new socket is created.
+If the socket is not bound to a local UDP
+port, then this routine binds it to an arbitrary port.
+Upon completion,
+.Fa xprt-\*[Gt]xp_sock
+is the transport's socket descriptor, and
+.Fa xprt-\*[Gt]xp_port
+is the transport's port number.
+This routine returns
+.Dv NULL
+if it fails.
+.Pp
+This allows the user to specify the maximum packet size for sending and
+receiving UDP-based RPC messages.
+.It Fn svcudp_create
+This acts as
+.Fn svcudp_bufcreate with
+predefined sizes for the maximum packet sizes.
+.It Fn xdr_accepted_reply
+Used for encoding RPC reply messages.
+This routine is useful for users who wish to generate RPC-style
+messages without using the RPC package.
+.It Fn xdr_authunix_parms
+Used for describing UNIX credentials.
+This routine is useful for users who wish to generate these
+credentials without using the RPC authentication package.
+.It Fn xdr_callhdr
+Used for describing RPC call header messages.
+This routine is useful for users who wish to generate RPC-style
+messages without using the RPC package.
+.It Fn xdr_callmsg
+Used for describing RPC call messages.
+This routine is useful for users who wish to generate RPC-style
+messages without using the RPC package.
+.It Fn xdr_opaque_auth
+Used for describing RPC authentication information messages.
+This routine is useful for users who wish to generate RPC-style
+messages without using the RPC package.
+.It Fn xdr_pmap
+Used for describing parameters to various
+.Xr rpcbind 8
+procedures, externally.
+This routine is useful for users who wish to generate
+these parameters without using the
+.Em pmap
+interface.
+.It Fn xdr_pmaplist
+Used for describing a list of port mappings, externally.
+This routine is useful for users who wish to generate
+these parameters without using the
+.Em pmap
+interface.
+.It Fn xdr_rejected_reply
+Used for describing RPC reply messages.
+This routine is useful for users who wish to generate RPC-style
+messages without using the RPC package.
+.It Fn xdr_replymsg
+Used for describing RPC reply messages.
+This routine is useful for users who wish to generate RPC-style
+messages without using the RPC package.
+.It Fn xprt_register
+After RPC service transport handles are created,
+they should register themselves with the RPC service package.
+This routine modifies the global variable
+.Va svc_fds .
+Service implementors usually do not need this routine.
+.It Fn xprt_unregister
+Before an RPC service transport handle is destroyed,
+it should unregister itself with the RPC service package.
+This routine modifies the global variable
+.Va svc_fds .
+Service implementors usually do not need this routine.
+.El
+.Sh SEE ALSO
+.\".Xr rpc_secure 3 ,
+.Xr xdr 3
+.Pp
+The following manuals:
+.Rs
+.%B Remote Procedure Calls: Protocol Specification
+.Re
+.Rs
+.%B Remote Procedure Call Programming Guide
+.Re
+.Rs
+.%B rpcgen Programming Guide
+.Re
+.Pp
+.Rs
+.%A Sun Microsystems, Inc., USC-ISI
+.%T "RPC: Remote Procedure Call Protocol Specification"
+.%J RFC
+.%V 1050
+.Re
diff --git a/lib/nbsd_libc/rpc/rpc_soc.c b/lib/nbsd_libc/rpc/rpc_soc.c
new file mode 100644 (file)
index 0000000..dc19ece
--- /dev/null
@@ -0,0 +1,457 @@
+/*     $NetBSD: rpc_soc.c,v 1.13 2010/12/08 02:06:38 joerg Exp $       */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+/* #ident      "@(#)rpc_soc.c  1.17    94/04/24 SMI" */
+
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc.
+ * In addition, portions of such source code were derived from Berkeley
+ * 4.3 BSD under license from the Regents of the University of
+ * California.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)rpc_soc.c 1.41 89/05/02 Copyr 1988 Sun Micro";
+#else
+__RCSID("$NetBSD: rpc_soc.c,v 1.13 2010/12/08 02:06:38 joerg Exp $");
+#endif
+#endif
+
+#ifdef PORTMAP
+/*
+ * rpc_soc.c
+ *
+ * The backward compatibility routines for the earlier implementation
+ * of RPC, where the only transports supported were tcp/ip and udp/ip.
+ * Based on berkeley socket abstraction, now implemented on the top
+ * of TLI/Streams
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <stdio.h>
+#include <rpc/rpc.h>
+#include <rpc/pmap_clnt.h>
+#include <rpc/pmap_prot.h>
+#include <rpc/nettype.h>
+#include <netinet/in.h>
+#include <assert.h>
+#include <errno.h>
+#include <netdb.h>
+#include <stdlib.h>
+#include <string.h>
+#include <syslog.h>
+#include <unistd.h>
+
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(clntudp_bufcreate,_clntudp_bufcreate)
+__weak_alias(clntudp_create,_clntudp_create)
+__weak_alias(clnttcp_create,_clnttcp_create)
+__weak_alias(clntraw_create,_clntraw_create)
+__weak_alias(get_myaddress,_get_myaddress)
+__weak_alias(svcfd_create,_svcfd_create)
+__weak_alias(svcudp_bufcreate,_svcudp_bufcreate)
+__weak_alias(svcudp_create,_svcudp_create)
+__weak_alias(svctcp_create,_svctcp_create)
+__weak_alias(svcraw_create,_svcraw_create)
+__weak_alias(callrpc,_callrpc)
+__weak_alias(registerrpc,_registerrpc)
+__weak_alias(clnt_broadcast,_clnt_broadcast)
+#endif
+
+#ifdef _REENTRANT
+extern mutex_t rpcsoc_lock;
+#endif
+
+static CLIENT *clnt_com_create __P((struct sockaddr_in *, rpcprog_t, rpcvers_t,
+                                   int *, u_int, u_int, const char *));
+static SVCXPRT *svc_com_create __P((int, u_int, u_int, const char *));
+static bool_t rpc_wrap_bcast __P((char *, struct netbuf *, struct netconfig *));
+
+/*
+ * A common clnt create routine
+ */
+static CLIENT *
+clnt_com_create(raddr, prog, vers, sockp, sendsz, recvsz, tp)
+       struct sockaddr_in *raddr;
+       rpcprog_t prog;
+       rpcvers_t vers;
+       int *sockp;
+       u_int sendsz;
+       u_int recvsz;
+       const char *tp;
+{
+       CLIENT *cl;
+       int madefd = FALSE;
+       int fd;
+       struct netconfig *nconf;
+       struct netbuf bindaddr;
+
+       _DIAGASSERT(raddr != NULL);
+       _DIAGASSERT(sockp != NULL);
+       _DIAGASSERT(tp != NULL);
+
+       fd = *sockp;
+
+       mutex_lock(&rpcsoc_lock);
+       if ((nconf = __rpc_getconfip(tp)) == NULL) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+               mutex_unlock(&rpcsoc_lock);
+               return (NULL);
+       }
+       if (fd == RPC_ANYSOCK) {
+               fd = __rpc_nconf2fd(nconf);
+               if (fd == -1)
+                       goto syserror;
+               madefd = TRUE;
+       }
+
+       if (raddr->sin_port == 0) {
+               u_int proto;
+               u_short sport;
+
+               mutex_unlock(&rpcsoc_lock);     /* pmap_getport is recursive */
+               proto = strcmp(tp, "udp") == 0 ? IPPROTO_UDP : IPPROTO_TCP;
+               sport = pmap_getport(raddr, (u_long)prog, (u_long)vers,
+                   proto);
+               if (sport == 0) {
+                       goto err;
+               }
+               raddr->sin_port = htons(sport);
+               mutex_lock(&rpcsoc_lock);       /* pmap_getport is recursive */
+       }
+
+       /* Transform sockaddr_in to netbuf */
+       bindaddr.maxlen = bindaddr.len =  sizeof (struct sockaddr_in);
+       bindaddr.buf = raddr;
+
+       bindresvport(fd, NULL);
+       cl = clnt_tli_create(fd, nconf, &bindaddr, prog, vers,
+                               sendsz, recvsz);
+       if (cl) {
+               if (madefd == TRUE) {
+                       /*
+                        * The fd should be closed while destroying the handle.
+                        */
+                       (void) CLNT_CONTROL(cl, CLSET_FD_CLOSE, NULL);
+                       *sockp = fd;
+               }
+               (void) freenetconfigent(nconf);
+               mutex_unlock(&rpcsoc_lock);
+               return (cl);
+       }
+       goto err;
+
+syserror:
+       rpc_createerr.cf_stat = RPC_SYSTEMERROR;
+       rpc_createerr.cf_error.re_errno = errno;
+
+err:   if (madefd == TRUE)
+               (void) close(fd);
+       (void) freenetconfigent(nconf);
+       mutex_unlock(&rpcsoc_lock);
+       return (NULL);
+}
+
+CLIENT *
+clntudp_bufcreate(raddr, prog, vers, wait, sockp, sendsz, recvsz)
+       struct sockaddr_in *raddr;
+       u_long prog;
+       u_long vers;
+       struct timeval wait;
+       int *sockp;
+       u_int sendsz;
+       u_int recvsz;
+{
+       CLIENT *cl;
+
+       _DIAGASSERT(raddr != NULL);
+       _DIAGASSERT(sockp != NULL);
+
+       cl = clnt_com_create(raddr, (rpcprog_t)prog, (rpcvers_t)vers, sockp,
+           sendsz, recvsz, "udp");
+       if (cl == NULL) {
+               return (NULL);
+       }
+       (void) CLNT_CONTROL(cl, CLSET_RETRY_TIMEOUT, (char *)(void *)&wait);
+       return (cl);
+}
+
+CLIENT *
+clntudp_create(raddr, program, version, wait, sockp)
+       struct sockaddr_in *raddr;
+       u_long program;
+       u_long version;
+       struct timeval wait;
+       int *sockp;
+{
+       return clntudp_bufcreate(raddr, program, version, wait, sockp,
+                                       UDPMSGSIZE, UDPMSGSIZE);
+}
+
+CLIENT *
+clnttcp_create(raddr, prog, vers, sockp, sendsz, recvsz)
+       struct sockaddr_in *raddr;
+       u_long prog;
+       u_long vers;
+       int *sockp;
+       u_int sendsz;
+       u_int recvsz;
+{
+       return clnt_com_create(raddr, (rpcprog_t)prog, (rpcvers_t)vers, sockp,
+           sendsz, recvsz, "tcp");
+}
+
+CLIENT *
+clntraw_create(prog, vers)
+       u_long prog;
+       u_long vers;
+{
+       return clnt_raw_create((rpcprog_t)prog, (rpcvers_t)vers);
+}
+
+/*
+ * A common server create routine
+ */
+static SVCXPRT *
+svc_com_create(fd, sendsize, recvsize, netid)
+       int fd;
+       u_int sendsize;
+       u_int recvsize;
+       const char *netid;
+{
+       struct netconfig *nconf;
+       SVCXPRT *svc;
+       int madefd = FALSE;
+       int port;
+       struct sockaddr_in sccsin;
+
+       _DIAGASSERT(netid != NULL);
+
+       if ((nconf = __rpc_getconfip(netid)) == NULL) {
+               (void) syslog(LOG_ERR, "Could not get %s transport", netid);
+               return (NULL);
+       }
+       if (fd == RPC_ANYSOCK) {
+               fd = __rpc_nconf2fd(nconf);
+               if (fd == -1) {
+                       (void) freenetconfigent(nconf);
+                       (void) syslog(LOG_ERR,
+                       "svc%s_create: could not open connection", netid);
+                       return (NULL);
+               }
+               madefd = TRUE;
+       }
+
+       memset(&sccsin, 0, sizeof sccsin);
+       sccsin.sin_family = AF_INET;
+       bindresvport(fd, &sccsin);
+       listen(fd, SOMAXCONN);
+       svc = svc_tli_create(fd, nconf, NULL, sendsize, recvsize);
+       (void) freenetconfigent(nconf);
+       if (svc == NULL) {
+               if (madefd)
+                       (void) close(fd);
+               return (NULL);
+       }
+       port = (((struct sockaddr_in *)svc->xp_ltaddr.buf)->sin_port);
+       svc->xp_port = ntohs(port);
+       return (svc);
+}
+
+SVCXPRT *
+svctcp_create(fd, sendsize, recvsize)
+       int fd;
+       u_int sendsize;
+       u_int recvsize;
+{
+       return svc_com_create(fd, sendsize, recvsize, "tcp");
+}
+
+SVCXPRT *
+svcudp_bufcreate(fd, sendsz, recvsz)
+       int fd;
+       u_int sendsz, recvsz;
+{
+       return svc_com_create(fd, sendsz, recvsz, "udp");
+}
+
+SVCXPRT *
+svcfd_create(fd, sendsize, recvsize)
+       int fd;
+       u_int sendsize;
+       u_int recvsize;
+{
+       return svc_fd_create(fd, sendsize, recvsize);
+}
+
+
+SVCXPRT *
+svcudp_create(fd)
+       int fd;
+{
+       return svc_com_create(fd, UDPMSGSIZE, UDPMSGSIZE, "udp");
+}
+
+SVCXPRT *
+svcraw_create()
+{
+       return svc_raw_create();
+}
+
+int
+get_myaddress(addr)
+       struct sockaddr_in *addr;
+{
+
+       _DIAGASSERT(addr != NULL);
+
+       memset((void *) addr, 0, sizeof(*addr));
+       addr->sin_family = AF_INET;
+       addr->sin_port = htons(PMAPPORT);
+       addr->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+       return (0);
+}
+
+/*
+ * For connectionless "udp" transport. Obsoleted by rpc_call().
+ */
+int
+callrpc(host, prognum, versnum, procnum, inproc, in, outproc, out)
+       char *host;
+       int prognum, versnum, procnum;
+       xdrproc_t inproc, outproc;
+       char *in, *out;
+{
+       return (int)rpc_call(host, (rpcprog_t)prognum, (rpcvers_t)versnum,
+           (rpcproc_t)procnum, inproc, in, outproc, out, "udp");
+}
+
+/*
+ * For connectionless kind of transport. Obsoleted by rpc_reg()
+ */
+int
+registerrpc(prognum, versnum, procnum, progname, inproc, outproc)
+       int prognum, versnum, procnum;
+       char *(*progname) __P((char [UDPMSGSIZE]));
+       xdrproc_t inproc, outproc;
+{
+       return rpc_reg((rpcprog_t)prognum, (rpcvers_t)versnum,
+           (rpcproc_t)procnum, progname, inproc, outproc, __UNCONST("udp"));
+}
+
+/*
+ * All the following clnt_broadcast stuff is convulated; it supports
+ * the earlier calling style of the callback function
+ */
+#ifdef _REENTRANT
+static thread_key_t    clnt_broadcast_key;
+#endif
+static resultproc_t    clnt_broadcast_result_main;
+
+/*
+ * Need to translate the netbuf address into sockaddr_in address.
+ * Dont care about netid here.
+ */
+/* ARGSUSED */
+static bool_t
+rpc_wrap_bcast(resultp, addr, nconf)
+       char *resultp;          /* results of the call */
+       struct netbuf *addr;    /* address of the guy who responded */
+       struct netconfig *nconf; /* Netconf of the transport */
+{
+       resultproc_t clnt_broadcast_result;
+
+       _DIAGASSERT(resultp != NULL);
+       _DIAGASSERT(addr != NULL);
+       _DIAGASSERT(nconf != NULL);
+
+       if (strcmp(nconf->nc_netid, "udp"))
+               return (FALSE);
+#ifdef _REENTRANT
+       if (__isthreaded == 0)
+               clnt_broadcast_result = clnt_broadcast_result_main;
+       else
+               clnt_broadcast_result = thr_getspecific(clnt_broadcast_key);
+#else
+       clnt_broadcast_result = clnt_broadcast_result_main;
+#endif
+       return (*clnt_broadcast_result)(resultp,
+                               (struct sockaddr_in *)addr->buf);
+}
+
+#ifdef _REENTRANT
+static once_t clnt_broadcast_once = ONCE_INITIALIZER;
+
+static void
+clnt_broadcast_setup(void)
+{
+
+       thr_keycreate(&clnt_broadcast_key, free);
+}
+#endif
+
+/*
+ * Broadcasts on UDP transport. Obsoleted by rpc_broadcast().
+ */
+enum clnt_stat
+clnt_broadcast(prog, vers, proc, xargs, argsp, xresults, resultsp, eachresult)
+       u_long          prog;           /* program number */
+       u_long          vers;           /* version number */
+       u_long          proc;           /* procedure number */
+       xdrproc_t       xargs;          /* xdr routine for args */
+       caddr_t         argsp;          /* pointer to args */
+       xdrproc_t       xresults;       /* xdr routine for results */
+       caddr_t         resultsp;       /* pointer to results */
+       resultproc_t    eachresult;     /* call with each result obtained */
+{
+#ifdef _REENTRANT
+       if (__isthreaded == 0)
+               clnt_broadcast_result_main = eachresult;
+       else {
+               thr_once(&clnt_broadcast_once, clnt_broadcast_setup);
+               thr_setspecific(clnt_broadcast_key, (void *) eachresult);
+       }
+#else
+       clnt_broadcast_result_main = eachresult;
+#endif
+       return rpc_broadcast((rpcprog_t)prog, (rpcvers_t)vers,
+           (rpcproc_t)proc, xargs, argsp, xresults, resultsp,
+           (resultproc_t) rpc_wrap_bcast, "udp");
+}
+
+#endif /* PORTMAP */
diff --git a/lib/nbsd_libc/rpc/rpc_svc_calls.3 b/lib/nbsd_libc/rpc/rpc_svc_calls.3
new file mode 100644 (file)
index 0000000..e04b6d4
--- /dev/null
@@ -0,0 +1,261 @@
+.\" @(#)rpc_svc_calls.3n 1.28 93/05/10 SMI; from SVr4
+.\" Copyright 1989 AT&T
+.\" @(#)rpc_svc_calls 1.5 89/07/25 SMI;
+.\" Copyright (c) 1988 Sun Microsystems, Inc. - All Rights Reserved.
+.\"    $NetBSD: rpc_svc_calls.3,v 1.12 2010/03/22 19:30:54 joerg Exp $
+.Dd May 3, 1993
+.Dt RPC_SVC_CALLS 3
+.Os
+.Sh NAME
+.Nm svc_dg_enablecache ,
+.Nm svc_exit ,
+.Nm svc_fdset ,
+.Nm svc_freeargs ,
+.Nm svc_getargs ,
+.Nm svc_getreq_common ,
+.Nm svc_getreq_poll ,
+.Nm svc_getreqset ,
+.Nm svc_getrpccaller ,
+.Nm svc_pollset ,
+.Nm svc_run ,
+.Nm svc_sendreply
+.Nd library routines for RPC servers
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In rpc/rpc.h
+.Ft int
+.Fn svc_dg_enablecache "SVCXPRT *xprt" "const unsigned cache_size"
+.Ft void
+.Fn svc_exit "void"
+.Ft bool_t
+.Fn svc_freeargs "const SVCXPRT *xprt" "const xdrproc_t inproc" "caddr_t in"
+.Ft bool_t
+.Fn svc_getargs "const SVCXPRT *xprt" "const xdrproc_t inproc" "caddr_t in"
+.Ft void
+.Fn svc_getreq_common "const int fd"
+.Ft void
+.Fn svc_getreq_poll "struct pollfd *pfdp" "const int pollretval"
+.Ft void
+.Fn svc_getreqset "fd_set * rdfds"
+.Ft "struct netbuf *"
+.Fn svc_getrpccaller "const SVCXPRT *xprt"
+.Ft "struct sockcred *"
+.Fn __svc_getcallercreds "const SVCXPRT *xprt"
+.Vt struct pollfd svc_pollset[FD_SETSIZE];
+.Ft void
+.Fn svc_run "void"
+.Ft bool_t
+.Fn svc_sendreply "const SVCXPRT *xprt" "const xdrproc_t outproc" "const caddr_t *out"
+.Sh DESCRIPTION
+These routines are part of the
+RPC
+library which allows C language programs to make procedure
+calls on other machines across the network.
+.Pp
+These routines are associated with the server side of the
+RPC mechanism.
+Some of them are called by the server side dispatch function,
+while others
+(such as
+.Fn svc_run )
+are called when the server is initiated.
+.\" .Pp
+.\" In the current implementation, the service transport handle,
+.\" .Dv SVCXPRT ,
+.\" contains a single data area for decoding arguments and encoding results.
+.\" Therefore, this structure cannot be freely shared between threads that call
+.\" functions that do this.  Routines on this page that are affected by this
+.\" restriction are marked as unsafe for MT applications.
+.Sh ROUTINES
+See
+.Xr rpc 3
+for the definition of the
+.Dv SVCXPRT
+data structure.
+.Pp
+.Bl -tag -width __svc_getcallercreds()
+.It Fn svc_dg_enablecache
+This function allocates a duplicate request cache for the
+service endpoint
+.Fa xprt ,
+large enough to hold
+.Fa cache_size
+entries.
+Once enabled, there is no way to disable caching.
+This routine returns 0 if space necessary for a cache of the given size
+was successfully allocated, and 1 otherwise.
+.It Fn svc_exit
+This function when called by any of the RPC server procedure or
+otherwise, causes
+.Fn svc_run
+to return.
+.Pp
+As currently implemented,
+.Fn svc_exit
+zeroes the
+.Dv svc_fdset
+global variable.
+If RPC server activity is to be resumed,
+services must be reregistered with the RPC library
+either through one of the
+.Fn rpc_svc_create
+functions, or using
+.Fn xprt_register .
+.Fn svc_exit
+has global scope and ends all RPC server activity.
+.Ft "fd_set svc_fdset"
+A global variable reflecting the
+RPC server's read file descriptor bit mask; it is suitable as a parameter
+to the
+.Xr select 2
+system call.
+This is only of interest
+if service implementors do not call
+.Fn svc_run ,
+but rather do their own asynchronous event processing.
+This variable is read-only (do not pass its address to
+.Xr select 2 ! ) ,
+yet it may change after calls to
+.Fn svc_getreqset
+or any creation routines.
+.Pp
+.It Fn svc_freeargs
+A function macro that frees any data allocated by the
+RPC/XDR system when it decoded the arguments to a service procedure
+using
+.Fn svc_getargs .
+This routine returns
+.Dv TRUE
+if the results were successfully
+freed, and
+.Dv FALSE
+otherwise.
+.Pp
+.It Fn svc_getargs
+A function macro that decodes the arguments of an
+RPC request associated with the RPC
+service transport handle
+.Fa xprt .
+The parameter
+.Fa in
+is the address where the arguments will be placed;
+.Fa inproc
+is the XDR
+routine used to decode the arguments.
+This routine returns
+.Dv TRUE
+if decoding succeeds, and
+.Dv FALSE
+otherwise.
+.It Fn svc_getreq_common
+This routine is called to handle a request on the given
+file descriptor.
+.Pp
+.It Fn svc_getreq_poll
+This routine is only of interest if a service implementor
+does not call
+.Fn svc_run ,
+but instead implements custom asynchronous event processing.
+It is called when
+.Xr poll 2
+has determined that an RPC request has arrived on some RPC
+file descriptors;
+.Fn pollretval
+is the return value from
+.Xr poll 2
+and
+.Fa pfdp
+is the array of
+.Fa pollfd
+structures on which the
+.Xr poll 2
+was done.
+It is assumed to be an array large enough to
+contain the maximal number of descriptors allowed.
+.Pp
+.It Fn svc_getreqset
+This routine is only of interest if a service implementor
+does not call
+.Fn svc_run ,
+but instead implements custom asynchronous event processing.
+It is called when
+.Xr poll 2
+has determined that an RPC
+request has arrived on some RPC file descriptors;
+.Fa rdfds
+is the resultant read file descriptor bit mask.
+The routine returns when all file descriptors
+associated with the value of
+.Fa rdfds
+have been serviced.
+.Pp
+.It Fn svc_getrpccaller
+The approved way of getting the network address of the caller
+of a procedure associated with the
+RPC service transport handle
+.Fa xprt .
+.Pp
+.It Fn __svc_getcallercreds
+.Em Warning: this macro is specific to
+.Nx
+.Em and thus not portable.
+This macro returns a pointer to a sockcred structure, defined in
+.In sys/socket.h ,
+identifying the calling client.
+This only works if the client is calling the server over an
+.Dv AF_LOCAL
+socket.
+.It Fa struct pollfd svc_pollset[FD_SETSIZE];
+.Va svc_pollset
+is an array of
+.Vt pollfd
+structures derived from
+.Va svc_fdset[] .
+It is suitable as a parameter to the
+.Xr  poll 2
+system call.
+The derivation of
+.Va svc_pollset
+from
+.Va svc_fdset
+is made in the current implementation in
+.Fn svc_run .
+Service implementors who do not call
+.Fn svc_run
+and who wish to use this array must perform this derivation themselves.
+.Pp
+.It Fn svc_run
+This routine never returns.
+It waits for RPC
+requests to arrive, and calls the appropriate service
+procedure using
+.Fn svc_getreq_poll
+when one arrives.
+This procedure is usually waiting for the
+.Xr poll 2
+system call to return.
+.Pp
+.It Fn svc_sendreply
+Called by an RPC service's dispatch routine to send the results of a
+remote procedure call.
+The parameter
+.Fa xprt
+is the request's associated transport handle;
+.Fa outproc
+is the XDR
+routine which is used to encode the results; and
+.Fa out
+is the address of the results.
+This routine returns
+.Dv TRUE
+if it succeeds,
+.Dv FALSE
+otherwise.
+.El
+.Sh SEE ALSO
+.Xr poll 2 ,
+.Xr rpc 3 ,
+.Xr rpc_svc_create 3 ,
+.Xr rpc_svc_err 3 ,
+.Xr rpc_svc_reg 3
diff --git a/lib/nbsd_libc/rpc/rpc_svc_create.3 b/lib/nbsd_libc/rpc/rpc_svc_create.3
new file mode 100644 (file)
index 0000000..ff07a52
--- /dev/null
@@ -0,0 +1,315 @@
+.\" @(#)rpc_svc_create.3n 1.26 93/08/26 SMI; from SVr4
+.\" Copyright 1989 AT&T
+.\" @(#)rpc_svc_create 1.3 89/06/28 SMI;
+.\" Copyright (c) 1988 Sun Microsystems, Inc. - All Rights Reserved.
+.\" $NetBSD: rpc_svc_create.3,v 1.11 2010/03/22 19:30:54 joerg Exp $
+.Dd May 3, 1993
+.Dt RPC_SVC_CREATE 3
+.Os
+.Sh NAME
+.Nm rpc_svc_create ,
+.Nm svc_control ,
+.Nm svc_create ,
+.Nm svc_destroy ,
+.Nm svc_dg_create ,
+.Nm svc_fd_create ,
+.Nm svc_raw_create ,
+.Nm svc_tli_create ,
+.Nm svc_tp_create ,
+.Nm svc_vc_create
+.Nd library routines for the creation of server handles
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In rpc/rpc.h
+.Ft bool_t
+.Fn svc_control "SVCXPRT *svc" "const u_int req" "void *info"
+.Ft int
+.Fn svc_create "const void (*dispatch)(struct svc_req *, SVCXPRT *)" "const rpcprog_t prognum" "const rpcvers_t versnum" "const char *nettype"
+.Ft SVCXPRT *"
+.Fn svc_dg_create "const int fildes" "const u_int sendsz" "const u_int recvsz"
+.Ft void
+.Fn svc_destroy "SVCXPRT *xprt"
+.Ft "SVCXPRT *"
+.Fn svc_fd_create "const int fildes" "const u_int sendsz" "const u_int recvsz"
+.Ft "SVCXPRT *"
+.Fn svc_raw_create "void"
+.Ft "SVCXPRT *"
+.Fn svc_tli_create "const int fildes" "const struct netconfig *netconf" "const struct t_bind *bindaddr" "const u_int sendsz" "const u_int recvsz"
+.Ft "SVCXPRT *"
+.Fn svc_tp_create "const void (*dispatch)(const struct svc_reg *, const SVCXPRT  *)" "const rpcprog_t prognum" "const rpcvers_t versnum" "const struct netconfig *netconf"
+.Ft "SVCXPRT *"
+.Fn svc_vc_create "const int fildes" "const u_int sendsz" "const u_int recvsz"
+.Sh DESCRIPTION
+These routines are part of the RPC
+library which allows C language programs to make procedure
+calls on servers across the network.
+These routines deal with the creation of service handles.
+Once the handle is created, the server can be invoked by calling
+.Fn svc_run .
+.Sh ROUTINES
+See
+.Xr rpc 3
+for the definition of the
+.Dv SVCXPRT
+data structure.
+.Pp
+.Bl -tag -width XXXXX
+.It Fn svc_control
+A function to change or retrieve various information
+about a service object.
+.Fa req
+indicates the type of operation and
+.Fa info
+is a pointer to the information.
+The supported values of
+.Fa req ,
+their argument types, and what they do are:
+.Bl -tag -width SVCGET_XID
+.It Dv SVCGET_VERSQUIET
+If a request is received for a program number
+served by this server but the version number
+is outside the range registered with the server,
+an
+.Dv RPC_PROGVERSMISMATCH
+error will normally
+be returned.
+.Fa info
+should be a pointer to an integer.
+Upon successful completion of the
+.Dv SVCGET_VERSQUIET
+request,
+.Fa *info
+contains an
+integer which describes the server's current
+behavior:  0 indicates normal server behavior
+(that is, an
+.Dv RPC_PROGVERSMISMATCH
+error
+will be returned); 1 indicates that the out of
+range request will be silently ignored.
+.Pp
+.It Dv SVCSET_VERSQUIET
+If a request is received for a program number
+served by this server but the version number
+is outside the range registered with the server,
+an
+.Dv RPC_PROGVERSMISMATCH
+error will normally be returned.
+It is sometimes desirable to change this behavior.
+.Fa info
+should be a
+pointer to an integer which is either 0
+(indicating normal server behavior - an
+.Dv RPC_PROGVERSMISMATCH
+error will be returned),
+or 1 (indicating that the out of range request
+should be silently ignored).
+.El
+.Pp
+.It Fn svc_create
+.Fn svc_create
+creates server handles for all the transports
+belonging to the class
+.Fa nettype .
+.Fa nettype
+defines a class of transports which can be used
+for a particular application.
+The transports are tried in left to right order in
+.Ev NETPATH
+variable or in top to bottom order in the netconfig database.
+If
+.Fa nettype
+is
+.Dv NULL ,
+it defaults to
+.Dv netpath .
+.Pp
+.Fn svc_create
+registers itself with the rpcbind
+service (see
+.Xr rpcbind 8 ) .
+.Fa dispatch
+is called when there is a remote procedure call for the given
+.Fa prognum
+and
+.Fa versnum ;
+this requires calling
+.Fn svc_run
+(see
+.Fn svc_run
+in
+.Xr rpc_svc_reg 3 ) .
+If
+.Fn svc_create
+succeeds, it returns the number of server
+handles it created,
+otherwise it returns 0 and an error message is logged.
+.Pp
+.It Fn svc_destroy
+A function macro that destroys the RPC
+service handle
+.Fa xprt .
+Destruction usually involves deallocation
+of private data structures,
+including
+.Fa xprt
+itself.
+Use of
+.Fa xprt
+is undefined after calling this routine.
+.Pp
+.It Fn svc_dg_create
+This routine creates a connectionless RPC
+service handle, and returns a pointer to it.
+This routine returns
+.Dv NULL
+if it fails, and an error message is logged.
+.Fa sendsz
+and
+.Fa recvsz
+are parameters used to specify the size of the buffers.
+If they are 0, suitable defaults are chosen.
+The file descriptor
+.Fa fildes
+should be open and bound.
+The server is not registered with
+.Xr rpcbind 8 .
+.Em Warning :
+since connectionless-based RPC
+messages can only hold limited amount of encoded data,
+this transport cannot be used for procedures
+that take large arguments or return huge results.
+.Pp
+.It Fn svc_fd_create
+This routine creates a service on top of an open and bound file descriptor,
+and returns the handle to it.
+Typically, this descriptor is a connected file descriptor for a
+connection-oriented transport.
+.Fa sendsz
+and
+.Fa recvsz
+indicate sizes for the send and receive buffers.
+If they are 0, reasonable defaults are chosen.
+This routine returns
+.Dv NULL
+if it fails, and an error message is logged.
+.Pp
+.It Fn svc_raw_create
+This routine creates an RPC
+service handle and returns a pointer to it.
+The transport is really a buffer within the process's
+address space, so the corresponding RPC
+client should live in the same address space;
+(see
+.Fn clnt_raw_create
+in
+.Xr rpc_clnt_create 3 ) .
+This routine allows simulation of RPC and acquisition of
+RPC overheads (such as round trip times),
+without any kernel and networking interference.
+This routine returns
+.Dv NULL
+if it fails, and an error message is logged.
+.Em Note :
+.Fn svc_run
+should not be called when the raw interface is being used.
+.Pp
+.It Fn svc_tli_create
+This routine creates an RPC
+server handle, and returns a pointer to it.
+.Fa fildes
+is the file descriptor on which the service is listening.
+If
+.Fa fildes
+is
+.Dv RPC_ANYFD ,
+it opens a file descriptor on the transport specified by
+.Fa netconf .
+If the file descriptor is unbound and
+.Fa bindaddr
+is non-null
+.Fa fildes
+is bound to the address specified by
+.Fa bindaddr ,
+otherwise
+.Fa fildes
+is bound to a default address chosen by the transport.
+.Pp
+Note: the
+.Vt t_bind
+structure comes from the TLI/XTI SysV interface, which
+.Nx
+does not use.
+The structure is defined in
+.In rpc/types.h
+for compatibility as:
+.Bd -literal
+struct t_bind {
+    struct netbuf addr;        /* network address, see rpc(3) */
+    unsigned int  qlen;        /* queue length (for listen(2)) */
+};
+.Ed
+.Pp
+In the case where the default address is chosen,
+the number of outstanding connect requests is set to 8
+for connection-oriented transports.
+The user may specify the size of the send and receive buffers
+with the parameters
+.Fa sendsz
+and
+.Fa recvsz ;
+values of 0 choose suitable defaults.
+This routine returns
+.Dv NULL
+if it fails,
+and an error message is logged.
+The server is not registered with the
+.Xr rpcbind 8
+service.
+.Pp
+.It Fn svc_tp_create
+.Fn svc_tp_create
+creates a server handle for the network
+specified by
+.Fa netconf ,
+and registers itself with the rpcbind service.
+.Fa dispatch
+is called when there is a remote procedure call
+for the given
+.Fa prognum
+and
+.Fa versnum ;
+this requires calling
+.Fn svc_run .
+.Fn svc_tp_create
+returns the service handle if it succeeds,
+otherwise a
+.Dv NULL
+is returned and an error message is logged.
+.Pp
+.It Fn svc_vc_create
+This routine creates a connection-oriented RPC
+service and returns a pointer to it.
+This routine returns
+.Dv NULL
+if it fails, and an error message is logged.
+The users may specify the size of the send and receive buffers
+with the parameters
+.Fa sendsz
+and
+.Fa recvsz ;
+values of 0 choose suitable defaults.
+The file descriptor
+.Fa fildes
+should be open and bound.
+The server is not registered with the
+.Xr rpcbind 8
+service.
+.El
+.Sh SEE ALSO
+.Xr rpc 3 ,
+.Xr rpc_svc_calls 3 ,
+.Xr rpc_svc_err 3 ,
+.Xr rpc_svc_reg 3 ,
+.Xr rpcbind 8
diff --git a/lib/nbsd_libc/rpc/rpc_svc_err.3 b/lib/nbsd_libc/rpc/rpc_svc_err.3
new file mode 100644 (file)
index 0000000..0eb0ebc
--- /dev/null
@@ -0,0 +1,101 @@
+.\" @(#)rpc_svc_err.3n 1.23 93/08/31 SMI; from SVr4
+.\" Copyright 1989 AT&T
+.\" @(#)rpc_svc_err 1.4 89/06/28 SMI;
+.\" Copyright (c) 1988 Sun Microsystems, Inc. - All Rights Reserved.
+.\"    $NetBSD: rpc_svc_err.3,v 1.6 2003/04/16 13:34:43 wiz Exp $
+.Dd May 3, 1993
+.Dt RPC_SVC_ERR 3
+.Os
+.Sh NAME
+.Nm rpc_svc_err ,
+.Nm svcerr_auth ,
+.Nm svcerr_decode ,
+.Nm svcerr_noproc ,
+.Nm svcerr_noprog ,
+.Nm svcerr_progvers ,
+.Nm svcerr_systemerr ,
+.Nm svcerr_weakauth
+.Nd library routines for server side remote procedure call errors
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In rpc/rpc.h
+.Ft void
+.Fn svcerr_auth "const SVCXPRT1 *xprt" "const enum auth_stat why"
+.Ft void
+.Fn svcerr_decode "const SVCXPRT *xprt"
+.Ft void
+.Fn svcerr_noproc "const SVCXPRT *xprt"
+.Ft void
+.Fn svcerr_noprog "const SVCXPRT *xprt"
+.Ft void
+.Fn svcerr_progvers "const SVCXPRT *xprt" "rpcvers_t low_vers" "rpcvers_t high_vers"
+.Ft void
+.Fn svcerr_systemerr "const SVCXPRT *xprt"
+.Ft void
+.Fn svcerr_weakauth "const SVCXPRT *xprt"
+.Sh DESCRIPTION
+These routines are part of the RPC
+library which allows C language programs to make procedure
+calls on other machines across the network.
+.Pp
+These routines can be called by the server side
+dispatch function if there is any error in the
+transaction with the client.
+.Sh ROUTINES
+See
+.Xr rpc 3
+for the definition of the
+.Vt SVCXPRT
+data structure.
+.Pp
+.Bl -tag -width XXXXX
+.It Fn svcerr_auth
+Called by a service dispatch routine that refuses to perform
+a remote procedure call due to an authentication error.
+.Pp
+.Fn svcerr_decode
+Called by a service dispatch routine that cannot successfully
+decode the remote parameters
+(see
+.Fn svc_getargs
+in
+.Xr rpc_svc_reg 3 ) .
+.Pp
+.It Fn svcerr_noproc
+Called by a service dispatch routine that does not implement
+the procedure number that the caller requests.
+.Pp
+.It Fn svcerr_noprog
+Called when the desired program is not registered with the
+RPC package.
+Service implementors usually do not need this routine.
+.Pp
+.It Fn svcerr_progvers
+Called when the desired version of a program is not registered with the
+RPC package.
+.Fa low_vers
+is the lowest version number,
+and
+.Fa high_vers
+is the highest version number.
+Service implementors usually do not need this routine.
+.Pp
+.It Fn svcerr_systemerr
+Called by a service dispatch routine when it detects a system
+error not covered by any particular protocol.
+For example, if a service can no longer allocate storage,
+it may call this routine.
+.Pp
+.It Fn svcerr_weakauth
+Called by a service dispatch routine that refuses to perform
+a remote procedure call due to insufficient (but correct)
+authentication parameters.
+The routine calls
+.Fn svcerr_auth "xprt" "AUTH_TOOWEAK" .
+.El
+.Sh SEE ALSO
+.Xr rpc 3 ,
+.Xr rpc_svc_calls 3 ,
+.Xr rpc_svc_create 3 ,
+.Xr rpc_svc_reg 3
diff --git a/lib/nbsd_libc/rpc/rpc_svc_reg.3 b/lib/nbsd_libc/rpc/rpc_svc_reg.3
new file mode 100644 (file)
index 0000000..5e9c3b5
--- /dev/null
@@ -0,0 +1,196 @@
+.\" @(#)rpc_svc_reg.3n 1.32 93/08/31 SMI; from SVr4
+.\" Copyright 1989 AT&T
+.\" @(#)rpc_svc_call 1.6 89/07/20 SMI;
+.\" Copyright (c) 1988 Sun Microsystems, Inc. - All Rights Reserved.
+.\"    $NetBSD: rpc_svc_reg.3,v 1.9 2009/03/11 13:36:01 joerg Exp $
+.Dd May 3, 1993
+.Dt RPC_SVC_REG 3
+.Os
+.Sh NAME
+.Nm rpc_svc_reg ,
+.Nm rpc_reg ,
+.Nm svc_reg ,
+.Nm svc_unreg ,
+.Nm svc_auth_reg ,
+.Nm xprt_register ,
+.Nm xprt_unregister
+.Nd library routines for registering servers
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In rpc/rpc.h
+.Ft bool_t
+.Fn rpc_reg "const rpcprog_t prognum" "const rpcvers_t versnum" "const rpcproc_t procnum" "const char *(*procname)()" "const xdrproc_t inproc" "const xdrproc_t outproc" "const char *nettype"
+.Ft int
+.Fn svc_reg "const SVCXPRT *xprt" "const rpcprog_t prognum" "const rpcvers_t versnum" "const void (*dispatch(struct svc_req *, SVCXPRT *)" "const struct netconfig *netconf"
+.Ft void
+.Fn svc_unreg "const rpcprog_t prognum" "const rpcvers_t versnum"
+.Ft int
+.Fn svc_auth_reg "const int cred_flavor" "const enum auth_stat (*handler(struct svc_req *, struct rpc_msg *))"
+.Ft void
+.Fn xprt_register "const SVCXPRT *xprt"
+.Ft void
+.Fn xprt_unregister "const SVCXPRT *xprt"
+.Sh DESCRIPTION
+These routines are a part of the RPC
+library which allows the RPC
+servers to register themselves with rpcbind
+(see
+.Xr rpcbind 8 ) ,
+and associate the given program and version
+number with the dispatch function.
+When the RPC server receives a RPC request, the library invokes the
+dispatch routine with the appropriate arguments.
+.Sh ROUTINES
+See
+.Xr rpc 3
+for the definition of the
+.Vt SVCXPRT
+data structure.
+.Pp
+.Bl -tag -width XXXXX
+.It Fn rpc_reg
+Register program
+.Fa prognum ,
+procedure
+.Fa procname ,
+and version
+.Fa versnum
+with the RPC
+service package.
+If a request arrives for program
+.Fa prognum ,
+version
+.Fa versnum ,
+and procedure
+.Fa procnum ,
+.Fa procname
+is called with a pointer to its parameter(s);
+.Fa procname
+should return a pointer to its static result(s);
+.Fa inproc
+is the XDR function used to decode the parameters while
+.Fa outproc
+is the XDR function used to encode the results.
+Procedures are registered on all available transports of the class
+.Fa nettype .
+See
+.Xr rpc 3 .
+This routine returns 0 if the registration succeeded,
+-1 otherwise.
+.Pp
+.It Fn svc_reg
+Associates
+.Fa prognum
+and
+.Fa versnum
+with the service dispatch procedure,
+.Fa dispatch .
+If
+.Fa netconf
+is
+.Dv NULL ,
+the service is not registered with the
+.Xr rpcbind 8
+service.
+If
+.Fa netconf
+is non-zero,
+then a mapping of the triple
+[
+.Fa prognum ,
+.Fa versnum ,
+.Fa netconf-\*[Gt]nc_netid ]
+to
+.Fa xprt-\*[Gt]xp_ltaddr
+is established with the local rpcbind
+service.
+.Pp
+The
+.Fn svc_reg
+routine returns 1 if it succeeds,
+and 0 otherwise.
+.Pp
+.It Fn svc_unreg
+Remove from the rpcbind
+service, all mappings of the triple
+[
+.Fa prognum ,
+.Fa versnum ,
+all-transports ]
+to network address
+and all mappings within the RPC service package
+of the double
+[
+.Fa prognum ,
+.Fa versnum ]
+to dispatch routines.
+.Pp
+.It Fn svc_auth_reg
+Registers the service authentication routine
+.Fa handler
+with the dispatch mechanism so that it can be
+invoked to authenticate RPC requests received
+with authentication type
+.Fa cred_flavor .
+This interface allows developers to add new authentication
+types to their RPC applications without needing to modify
+the libraries.
+Service implementors usually do not need this routine.
+.Pp
+Typical service application would call
+.Fn svc_auth_reg
+after registering the service and prior to calling
+.Fn svc_run .
+When needed to process an RPC credential of type
+.Fa cred_flavor ,
+the
+.Fa handler
+procedure will be called with two parameters
+.Fa "struct svc_req *rqst" ,
+and
+.Fa "struct rpc_msg * msg" ,
+and is expected to return a valid
+.Vt "enum auth_stat"
+value.
+There is no provision to change or delete an authentication handler
+once registered.
+.Pp
+The
+.Fn svc_auth_reg
+routine returns 0 if the registration is successful,
+1 if
+.Fa cred_flavor
+already has an authentication handler registered for it,
+and -1 otherwise.
+.Pp
+.It Fn xprt_register
+After RPC service transport handle
+.Fa xprt
+is created, it is registered with the RPC
+service package.
+This routine modifies the global variable
+.Va svc_fdset
+(see
+.Xr rpc_svc_calls 3 ) .
+Service implementors usually do not need this routine.
+.Pp
+.It Fn xprt_unregister
+Before an RPC service transport handle
+.Fa xprt
+is destroyed, it unregisters itself with the
+RPC service package.
+This routine modifies the global variable
+.Va svc_fdset
+(see
+.Xr rpc_svc_calls 3 ) .
+Service implementors usually do not need this routine.
+.El
+.Sh SEE ALSO
+.Xr select 2 ,
+.Xr rpc 3 ,
+.Xr rpc_svc_calls 3 ,
+.Xr rpc_svc_create 3 ,
+.Xr rpc_svc_err 3 ,
+.Xr rpcbind 3 ,
+.Xr rpcbind 8
diff --git a/lib/nbsd_libc/rpc/rpc_xdr.3 b/lib/nbsd_libc/rpc/rpc_xdr.3
new file mode 100644 (file)
index 0000000..62e7c85
--- /dev/null
@@ -0,0 +1,100 @@
+.\" @(#)rpc_xdr.3n 1.24 93/08/31 SMI; from SVr4
+.\" Copyright 1989 AT&T
+.\" @(#)rpc_xdr.new 1.1 89/04/06 SMI;
+.\" Copyright (c) 1988 Sun Microsystems, Inc. - All Rights Reserved.
+.\" $NetBSD: rpc_xdr.3,v 1.8 2009/04/11 16:03:29 joerg Exp $
+.Dd May 3, 1993
+.Dt RPC_XDR 3
+.Os
+.Sh NAME
+.Nm xdr_accepted_reply ,
+.Nm xdr_authsys_parms ,
+.Nm xdr_callhdr ,
+.Nm xdr_callmsg ,
+.Nm xdr_opaque_auth ,
+.Nm xdr_rejected_reply ,
+.Nm xdr_replymsg
+.Nd XDR library routines for remote procedure calls
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In rpc/rpc.h
+.Ft bool_t
+.Fn xdr_accepted_reply "XDR *xdrs" "const struct accepted_reply *ar"
+.Ft bool_t
+.Fn xdr_authsys_parms "XDR *xdrs" "struct authsys_parms *aupp"
+.Ft void
+.Fn xdr_callhdr "XDR *xdrs" "struct rpc_msg *chdr"
+.Ft bool_t
+.Fn xdr_callmsg "XDR *xdrs" "struct rpc_msg *cmsg"
+.Ft bool_t
+.Fn xdr_opaque_auth "XDR *xdrs" "struct opaque_auth *ap"
+.Ft bool_t
+.Fn xdr_rejected_reply "XDR *xdrs" "const struct rejected_reply *rr"
+.Ft bool_t
+.Fn xdr_replymsg "XDR *xdrs" "const struct rpc_msg *rmsg"
+.Sh DESCRIPTION
+These routines are used for describing the
+RPC messages in XDR language.
+They should normally be used by those who do not
+want to use the RPC
+package directly.
+These routines return TRUE if they succeed, FALSE otherwise.
+.Sh ROUTINES
+See
+.Xr rpc 3
+for the definition of the
+.Vt XDR
+data structure.
+.Pp
+.Bl -tag -width XXXXX
+.It Fn xdr_accepted_reply
+Used to translate between RPC
+reply messages and their external representation.
+It includes the status of the RPC
+call in the XDR language format.
+In the case of success, it also includes the call results.
+.Pp
+.It Fn xdr_authsys_parms
+Used for describing UNIX operating system credentials.
+It includes machine-name, uid, gid list, etc.
+.Pp
+.It Fn xdr_callhdr
+Used for describing RPC call header messages.
+It encodes the static part of the call message header in the
+XDR language format.
+It includes information such as transaction
+ID, RPC version number, program and version number.
+.Pp
+.It Fn xdr_callmsg
+Used for describing
+RPC call messages.
+This includes all the  RPC
+call information such as transaction
+ID, RPC version number, program number, version number,
+authentication information, etc.
+This is normally used by servers to determine information about the client
+RPC call.
+.Pp
+.It Fn xdr_opaque_auth
+Used for describing RPC
+opaque authentication information messages.
+.Pp
+.It Fn xdr_rejected_reply
+Used for describing RPC reply messages.
+It encodes the rejected RPC message in the XDR language format.
+The message could be rejected either because of version
+number mis-match or because of authentication errors.
+.Pp
+.It Fn xdr_replymsg
+Used for describing RPC
+reply messages.
+It translates between the
+RPC reply message and its external representation.
+This reply could be either an acceptance,
+rejection or
+.Dv NULL .
+.El
+.Sh SEE ALSO
+.Xr rpc 3 ,
+.Xr xdr 3
diff --git a/lib/nbsd_libc/rpc/rpcb_clnt.c b/lib/nbsd_libc/rpc/rpcb_clnt.c
new file mode 100644 (file)
index 0000000..82d3b76
--- /dev/null
@@ -0,0 +1,1296 @@
+/*     $NetBSD: rpcb_clnt.c,v 1.25 2010/03/23 20:28:58 drochner Exp $  */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc. 
+ */
+
+/* #ident      "@(#)rpcb_clnt.c        1.27    94/04/24 SMI" */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)rpcb_clnt.c 1.30 89/06/21 Copyr 1988 Sun Micro";
+#else
+__RCSID("$NetBSD: rpcb_clnt.c,v 1.25 2010/03/23 20:28:58 drochner Exp $");
+#endif
+#endif
+
+/*
+ * rpcb_clnt.c
+ * interface to rpcbind rpc service.
+ *
+ * Copyright (C) 1988, Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/utsname.h>
+#include <rpc/rpc.h>
+#include <rpc/rpcb_prot.h>
+#include <rpc/nettype.h>
+#include <netconfig.h>
+#ifdef PORTMAP
+#include <netinet/in.h>                /* FOR IPPROTO_TCP/UDP definitions */
+#include <rpc/pmap_prot.h>
+#endif
+#include <assert.h>
+#include <errno.h>
+#include <netdb.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <syslog.h>
+#include <unistd.h>
+
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(rpcb_set,_rpcb_set)
+__weak_alias(rpcb_unset,_rpcb_unset)
+__weak_alias(rpcb_getmaps,_rpcb_getmaps)
+__weak_alias(rpcb_taddr2uaddr,_rpcb_taddr2uaddr)
+__weak_alias(rpcb_uaddr2taddr,_rpcb_uaddr2taddr)
+#endif
+
+static struct timeval tottimeout = { 60, 0 };
+static const struct timeval rmttimeout = { 3, 0 };
+
+static const char nullstring[] = "\000";
+
+#define        CACHESIZE 6
+
+struct address_cache {
+       char *ac_host;
+       char *ac_netid;
+       char *ac_uaddr;
+       struct netbuf *ac_taddr;
+       struct address_cache *ac_next;
+};
+
+static struct address_cache *front;
+static int cachesize;
+
+#define        CLCR_GET_RPCB_TIMEOUT   1
+#define        CLCR_SET_RPCB_TIMEOUT   2
+
+
+extern int __rpc_lowvers;
+
+static struct address_cache *check_cache __P((const char *, const char *));
+static void delete_cache __P((struct netbuf *));
+static void add_cache __P((const char *, const char *, struct netbuf *,
+                          char *));
+static CLIENT *getclnthandle __P((const char *, const struct netconfig *,
+                                 char **));
+static CLIENT *local_rpcb __P((void));
+static struct netbuf *got_entry __P((rpcb_entry_list_ptr,
+                                    const struct netconfig *));
+
+/*
+ * This routine adjusts the timeout used for calls to the remote rpcbind.
+ * Also, this routine can be used to set the use of portmapper version 2
+ * only when doing rpc_broadcasts
+ * These are private routines that may not be provided in future releases.
+ */
+bool_t
+__rpc_control(request, info)
+       int     request;
+       void    *info;
+{
+
+       _DIAGASSERT(info != NULL);
+
+       switch (request) {
+       case CLCR_GET_RPCB_TIMEOUT:
+               *(struct timeval *)info = tottimeout;
+               break;
+       case CLCR_SET_RPCB_TIMEOUT:
+               tottimeout = *(struct timeval *)info;
+               break;
+       case CLCR_SET_LOWVERS:
+               __rpc_lowvers = *(int *)info;
+               break;
+       case CLCR_GET_LOWVERS:
+               *(int *)info = __rpc_lowvers;
+               break;
+       default:
+               return (FALSE);
+       }
+       return (TRUE);
+}
+
+/*
+ *     It might seem that a reader/writer lock would be more reasonable here.
+ *     However because getclnthandle(), the only user of the cache functions,
+ *     may do a delete_cache() operation if a check_cache() fails to return an
+ *     address useful to clnt_tli_create(), we may as well use a mutex.
+ */
+/*
+ * As it turns out, if the cache lock is *not* a reader/writer lock, we will
+ * block all clnt_create's if we are trying to connect to a host that's down,
+ * since the lock will be held all during that time.
+ */
+#ifdef _REENTRANT
+extern rwlock_t        rpcbaddr_cache_lock;
+#endif
+
+/*
+ * The routines check_cache(), add_cache(), delete_cache() manage the
+ * cache of rpcbind addresses for (host, netid).
+ */
+
+static struct address_cache *
+check_cache(host, netid)
+       const char *host, *netid;
+{
+       struct address_cache *cptr;
+
+       _DIAGASSERT(host != NULL);
+       _DIAGASSERT(netid != NULL);
+
+       /* READ LOCK HELD ON ENTRY: rpcbaddr_cache_lock */
+
+       for (cptr = front; cptr != NULL; cptr = cptr->ac_next) {
+               if (!strcmp(cptr->ac_host, host) &&
+                   !strcmp(cptr->ac_netid, netid)) {
+#ifdef ND_DEBUG
+                       fprintf(stderr, "Found cache entry for %s: %s\n",
+                               host, netid);
+#endif
+                       return (cptr);
+               }
+       }
+       return NULL;
+}
+
+static void
+delete_cache(addr)
+       struct netbuf *addr;
+{
+       struct address_cache *cptr, *prevptr = NULL;
+
+       _DIAGASSERT(addr != NULL);
+
+       /* WRITE LOCK HELD ON ENTRY: rpcbaddr_cache_lock */
+       for (cptr = front; cptr != NULL; cptr = cptr->ac_next) {
+               if (!memcmp(cptr->ac_taddr->buf, addr->buf, addr->len)) {
+                       free(cptr->ac_host);
+                       free(cptr->ac_netid);
+                       free(cptr->ac_taddr->buf);
+                       free(cptr->ac_taddr);
+                       if (cptr->ac_uaddr)
+                               free(cptr->ac_uaddr);
+                       if (prevptr)
+                               prevptr->ac_next = cptr->ac_next;
+                       else
+                               front = cptr->ac_next;
+                       free(cptr);
+                       cachesize--;
+                       break;
+               }
+               prevptr = cptr;
+       }
+}
+
+static void
+add_cache(host, netid, taddr, uaddr)
+       const char *host, *netid;
+       char *uaddr;
+       struct netbuf *taddr;
+{
+       struct address_cache  *ad_cache, *cptr, *prevptr;
+
+       _DIAGASSERT(host != NULL);
+       _DIAGASSERT(netid != NULL);
+       /* uaddr may be NULL */
+       /* taddr may be NULL ??? */
+
+       ad_cache = malloc(sizeof(*ad_cache));
+       if (!ad_cache) {
+               return;
+       }
+       ad_cache->ac_host = strdup(host);
+       ad_cache->ac_netid = strdup(netid);
+       ad_cache->ac_uaddr = uaddr ? strdup(uaddr) : NULL;
+       ad_cache->ac_taddr = malloc(sizeof(*ad_cache->ac_taddr));
+       if (!ad_cache->ac_host || !ad_cache->ac_netid || !ad_cache->ac_taddr ||
+               (uaddr && !ad_cache->ac_uaddr)) {
+               goto out;
+       }
+       ad_cache->ac_taddr->len = ad_cache->ac_taddr->maxlen = taddr->len;
+       ad_cache->ac_taddr->buf = malloc(taddr->len);
+       if (ad_cache->ac_taddr->buf == NULL) {
+out:
+               if (ad_cache->ac_host)
+                       free(ad_cache->ac_host);
+               if (ad_cache->ac_netid)
+                       free(ad_cache->ac_netid);
+               if (ad_cache->ac_uaddr)
+                       free(ad_cache->ac_uaddr);
+               if (ad_cache->ac_taddr)
+                       free(ad_cache->ac_taddr);
+               free(ad_cache);
+               return;
+       }
+       memcpy(ad_cache->ac_taddr->buf, taddr->buf, taddr->len);
+#ifdef ND_DEBUG
+       fprintf(stderr, "Added to cache: %s : %s\n", host, netid);
+#endif
+
+/* VARIABLES PROTECTED BY rpcbaddr_cache_lock:  cptr */
+
+       rwlock_wrlock(&rpcbaddr_cache_lock);
+       if (cachesize < CACHESIZE) {
+               ad_cache->ac_next = front;
+               front = ad_cache;
+               cachesize++;
+       } else {
+               /* Free the last entry */
+               cptr = front;
+               prevptr = NULL;
+               while (cptr->ac_next) {
+                       prevptr = cptr;
+                       cptr = cptr->ac_next;
+               }
+
+#ifdef ND_DEBUG
+               fprintf(stderr, "Deleted from cache: %s : %s\n",
+                       cptr->ac_host, cptr->ac_netid);
+#endif
+               free(cptr->ac_host);
+               free(cptr->ac_netid);
+               free(cptr->ac_taddr->buf);
+               free(cptr->ac_taddr);
+               if (cptr->ac_uaddr)
+                       free(cptr->ac_uaddr);
+
+               if (prevptr) {
+                       prevptr->ac_next = NULL;
+                       ad_cache->ac_next = front;
+                       front = ad_cache;
+               } else {
+                       front = ad_cache;
+                       ad_cache->ac_next = NULL;
+               }
+               free(cptr);
+       }
+       rwlock_unlock(&rpcbaddr_cache_lock);
+}
+
+/*
+ * This routine will return a client handle that is connected to the
+ * rpcbind. Returns NULL on error and free's everything.
+ */
+static CLIENT *
+getclnthandle(host, nconf, targaddr)
+       const char *host;
+       const struct netconfig *nconf;
+       char **targaddr;
+{
+       CLIENT *client;
+       struct netbuf *addr, taddr;
+       struct netbuf addr_to_delete;
+       struct __rpc_sockinfo si;
+       struct addrinfo hints, *res, *tres;
+       struct address_cache *ad_cache;
+       char *tmpaddr;
+
+       _DIAGASSERT(host != NULL);
+       _DIAGASSERT(nconf != NULL);
+       /* targaddr may be NULL */
+
+/* VARIABLES PROTECTED BY rpcbaddr_cache_lock:  ad_cache */
+
+       /* Get the address of the rpcbind.  Check cache first */
+       client = NULL;
+       addr_to_delete.len = 0;
+       addr_to_delete.buf = NULL;
+       rwlock_rdlock(&rpcbaddr_cache_lock);
+       ad_cache = check_cache(host, nconf->nc_netid);
+       if (ad_cache != NULL) {
+               addr = ad_cache->ac_taddr;
+               client = clnt_tli_create(RPC_ANYFD, nconf, addr,
+                   (rpcprog_t)RPCBPROG, (rpcvers_t)RPCBVERS4, 0, 0);
+               if (client != NULL) {
+                       if (targaddr)
+                               *targaddr = ad_cache->ac_uaddr;
+                       rwlock_unlock(&rpcbaddr_cache_lock);
+                       return (client);
+               }
+               addr_to_delete.len = addr->len;
+               addr_to_delete.buf = malloc(addr->len);
+               if (addr_to_delete.buf == NULL) {
+                       addr_to_delete.len = 0;
+               } else {
+                       memcpy(addr_to_delete.buf, addr->buf, addr->len);
+               }
+       }
+       rwlock_unlock(&rpcbaddr_cache_lock);
+       if (addr_to_delete.len != 0) {
+               /*
+                * Assume this may be due to cache data being
+                *  outdated
+                */
+               rwlock_wrlock(&rpcbaddr_cache_lock);
+               delete_cache(&addr_to_delete);
+               rwlock_unlock(&rpcbaddr_cache_lock);
+               free(addr_to_delete.buf);
+       }
+       if (!__rpc_nconf2sockinfo(nconf, &si)) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+               return NULL;
+       }
+
+       memset(&hints, 0, sizeof hints);
+       hints.ai_family = si.si_af;
+       hints.ai_socktype = si.si_socktype;
+       hints.ai_protocol = si.si_proto;
+
+#ifdef CLNT_DEBUG
+       printf("trying netid %s family %d proto %d socktype %d\n",
+           nconf->nc_netid, si.si_af, si.si_proto, si.si_socktype);
+#endif
+
+       if (getaddrinfo(host, "sunrpc", &hints, &res) != 0) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNHOST;
+               return NULL;
+       }
+
+       for (tres = res; tres != NULL; tres = tres->ai_next) {
+               taddr.buf = tres->ai_addr;
+               taddr.len = taddr.maxlen = tres->ai_addrlen;
+
+#ifdef ND_DEBUG
+               {
+                       char *ua;
+
+                       ua = taddr2uaddr(nconf, &taddr);
+                       fprintf(stderr, "Got it [%s]\n", ua);
+                       free(ua);
+               }
+#endif
+
+#ifdef ND_DEBUG
+               {
+                       int i;
+
+                       fprintf(stderr, "\tnetbuf len = %d, maxlen = %d\n",
+                               taddr.len, taddr.maxlen);
+                       fprintf(stderr, "\tAddress is ");
+                       for (i = 0; i < taddr.len; i++)
+                               fprintf(stderr, "%u.", ((char *)(taddr.buf))[i]);
+                       fprintf(stderr, "\n");
+               }
+#endif
+               client = clnt_tli_create(RPC_ANYFD, nconf, &taddr,
+                   (rpcprog_t)RPCBPROG, (rpcvers_t)RPCBVERS4, 0, 0);
+#ifdef ND_DEBUG
+               if (! client) {
+                       clnt_pcreateerror("rpcbind clnt interface");
+               }
+#endif
+
+               if (client) {
+                       tmpaddr = targaddr ? taddr2uaddr(nconf, &taddr) : NULL;
+                       add_cache(host, nconf->nc_netid, &taddr, tmpaddr);
+                       if (targaddr)
+                               *targaddr = tmpaddr;
+                       break;
+               }
+       }
+       freeaddrinfo(res);
+       return (client);
+}
+
+/* XXX */
+#define IN4_LOCALHOST_STRING   "127.0.0.1"
+#define IN6_LOCALHOST_STRING   "::1"
+
+/*
+ * This routine will return a client handle that is connected to the local
+ * rpcbind. Returns NULL on error and free's everything.
+ */
+static CLIENT *
+local_rpcb()
+{
+       CLIENT *client;
+       static struct netconfig *loopnconf;
+       static const char *hostname;
+#ifdef _REENTRANT
+       extern mutex_t loopnconf_lock;
+#endif
+       int sock;
+       size_t tsize;
+       struct netbuf nbuf;
+       struct sockaddr_un sun;
+
+       /*
+        * Try connecting to the local rpcbind through a local socket
+        * first. If this doesn't work, try all transports defined in
+        * the netconfig file.
+        */
+       memset(&sun, 0, sizeof sun);
+       sock = socket(AF_LOCAL, SOCK_STREAM, 0);
+       if (sock < 0)
+               goto try_nconf;
+       sun.sun_family = AF_LOCAL;
+       strcpy(sun.sun_path, _PATH_RPCBINDSOCK);
+       nbuf.len = sun.sun_len = SUN_LEN(&sun);
+       nbuf.maxlen = sizeof (struct sockaddr_un);
+       nbuf.buf = &sun;
+
+       tsize = __rpc_get_t_size(AF_LOCAL, 0, 0);
+       client = clnt_vc_create(sock, &nbuf, (rpcprog_t)RPCBPROG,
+           (rpcvers_t)RPCBVERS, tsize, tsize);
+
+       if (client != NULL) {
+               /* XXX - mark the socket to be closed in destructor */
+               (void) CLNT_CONTROL(client, CLSET_FD_CLOSE, NULL);
+               return client;
+       }
+
+       /* XXX - nobody needs this socket anymore, free the descriptor */
+       close(sock);
+
+try_nconf:
+
+/* VARIABLES PROTECTED BY loopnconf_lock: loopnconf */
+       mutex_lock(&loopnconf_lock);
+       if (loopnconf == NULL) {
+               struct netconfig *nconf, *tmpnconf = NULL;
+               void *nc_handle;
+               int fd;
+
+               nc_handle = setnetconfig();
+               if (nc_handle == NULL) {
+                       /* fails to open netconfig file */
+                       syslog (LOG_ERR, "rpc: failed to open " NETCONFIG);
+                       rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+                       mutex_unlock(&loopnconf_lock);
+                       return (NULL);
+               }
+               while ((nconf = getnetconfig(nc_handle)) != NULL) {
+#ifdef INET6
+                       if ((strcmp(nconf->nc_protofmly, NC_INET6) == 0 ||
+#else
+                       if ((
+#endif
+                            strcmp(nconf->nc_protofmly, NC_INET) == 0) &&
+                           (nconf->nc_semantics == NC_TPI_COTS ||
+                            nconf->nc_semantics == NC_TPI_COTS_ORD)) {
+                               fd = __rpc_nconf2fd(nconf);
+                               /*
+                                * Can't create a socket, assume that
+                                * this family isn't configured in the kernel.
+                                */
+                               if (fd < 0)
+                                       continue;
+                               close(fd);
+                               tmpnconf = nconf;
+                               if (!strcmp(nconf->nc_protofmly, NC_INET))
+                                       hostname = IN4_LOCALHOST_STRING;
+                               else
+                                       hostname = IN6_LOCALHOST_STRING;
+                       }
+               }
+               if (tmpnconf == NULL) {
+                       rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+                       mutex_unlock(&loopnconf_lock);
+                       return (NULL);
+               }
+               loopnconf = getnetconfigent(tmpnconf->nc_netid);
+               /* loopnconf is never freed */
+               endnetconfig(nc_handle);
+       }
+       mutex_unlock(&loopnconf_lock);
+       client = getclnthandle(hostname, loopnconf, NULL);
+       return (client);
+}
+
+/*
+ * Set a mapping between program, version and address.
+ * Calls the rpcbind service to do the mapping.
+ */
+bool_t
+rpcb_set(program, version, nconf, address)
+       rpcprog_t program;
+       rpcvers_t version;
+       const struct netconfig *nconf;  /* Network structure of transport */
+       const struct netbuf *address;           /* Services netconfig address */
+{
+       CLIENT *client;
+       bool_t rslt = FALSE;
+       RPCB parms;
+       char uidbuf[32];
+
+       /* parameter checking */
+       if (nconf == NULL) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+               return (FALSE);
+       }
+       if (address == NULL) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNADDR;
+               return (FALSE);
+       }
+       client = local_rpcb();
+       if (! client) {
+               return (FALSE);
+       }
+
+       /* convert to universal */
+       parms.r_addr = taddr2uaddr(__UNCONST(nconf), __UNCONST(address));
+       if (!parms.r_addr) {
+               CLNT_DESTROY(client);
+               rpc_createerr.cf_stat = RPC_N2AXLATEFAILURE;
+               return (FALSE); /* no universal address */
+       }
+       parms.r_prog = program;
+       parms.r_vers = version;
+       parms.r_netid = nconf->nc_netid;
+       /*
+        * Though uid is not being used directly, we still send it for
+        * completeness.  For non-unix platforms, perhaps some other
+        * string or an empty string can be sent.
+        */
+       (void) snprintf(uidbuf, sizeof uidbuf, "%d", geteuid());
+       parms.r_owner = uidbuf;
+
+       CLNT_CALL(client, (rpcproc_t)RPCBPROC_SET, (xdrproc_t) xdr_rpcb,
+           (char *)(void *)&parms, (xdrproc_t) xdr_bool,
+           (char *)(void *)&rslt, tottimeout);
+
+       CLNT_DESTROY(client);
+       free(parms.r_addr);
+       return (rslt);
+}
+
+/*
+ * Remove the mapping between program, version and netbuf address.
+ * Calls the rpcbind service to do the un-mapping.
+ * If netbuf is NULL, unset for all the transports, otherwise unset
+ * only for the given transport.
+ */
+bool_t
+rpcb_unset(program, version, nconf)
+       rpcprog_t program;
+       rpcvers_t version;
+       const struct netconfig *nconf;
+{
+       CLIENT *client;
+       bool_t rslt = FALSE;
+       RPCB parms;
+       char uidbuf[32];
+
+       client = local_rpcb();
+       if (! client) {
+               return (FALSE);
+       }
+
+       parms.r_prog = program;
+       parms.r_vers = version;
+       if (nconf)
+               parms.r_netid = nconf->nc_netid;
+       else {
+               parms.r_netid = __UNCONST(&nullstring[0]); /* unsets  all */
+       }
+       parms.r_addr = __UNCONST(&nullstring[0]);
+       (void) snprintf(uidbuf, sizeof uidbuf, "%d", geteuid());
+       parms.r_owner = uidbuf;
+
+       CLNT_CALL(client, (rpcproc_t)RPCBPROC_UNSET, (xdrproc_t) xdr_rpcb,
+           (char *)(void *)&parms, (xdrproc_t) xdr_bool,
+           (char *)(void *)&rslt, tottimeout);
+
+       CLNT_DESTROY(client);
+       return (rslt);
+}
+
+/*
+ * From the merged list, find the appropriate entry
+ */
+static struct netbuf *
+got_entry(relp, nconf)
+       rpcb_entry_list_ptr relp;
+       const struct netconfig *nconf;
+{
+       struct netbuf *na = NULL;
+       rpcb_entry_list_ptr sp;
+       rpcb_entry *rmap;
+
+       _DIAGASSERT(nconf != NULL);
+
+       for (sp = relp; sp != NULL; sp = sp->rpcb_entry_next) {
+               rmap = &sp->rpcb_entry_map;
+               if ((strcmp(nconf->nc_proto, rmap->r_nc_proto) == 0) &&
+                   (strcmp(nconf->nc_protofmly, rmap->r_nc_protofmly) == 0) &&
+                   (nconf->nc_semantics == rmap->r_nc_semantics) &&
+                   (rmap->r_maddr != NULL) && (rmap->r_maddr[0] != 0)) {
+                       na = uaddr2taddr(nconf, rmap->r_maddr);
+#ifdef ND_DEBUG
+                       fprintf(stderr, "\tRemote address is [%s].\n",
+                               rmap->r_maddr);
+                       if (!na)
+                               fprintf(stderr,
+                                   "\tCouldn't resolve remote address!\n");
+#endif
+                       break;
+               }
+       }
+       return (na);
+}
+
+/*
+ * An internal function which optimizes rpcb_getaddr function.  It also
+ * returns the client handle that it uses to contact the remote rpcbind.
+ *
+ * The algorithm used: If the transports is TCP or UDP, it first tries
+ * version 2 (portmap), 4 and then 3 (svr4).  This order should be
+ * changed in the next OS release to 4, 2 and 3.  We are assuming that by
+ * that time, version 4 would be available on many machines on the network.
+ * With this algorithm, we get performance as well as a plan for
+ * obsoleting version 2.
+ *
+ * For all other transports, the algorithm remains as 4 and then 3.
+ *
+ * XXX: Due to some problems with t_connect(), we do not reuse the same client
+ * handle for COTS cases and hence in these cases we do not return the
+ * client handle.  This code will change if t_connect() ever
+ * starts working properly.  Also look under clnt_vc.c.
+ */
+struct netbuf *
+__rpcb_findaddr(program, version, nconf, host, clpp)
+       rpcprog_t program;
+       rpcvers_t version;
+       const struct netconfig *nconf;
+       const char *host;
+       CLIENT **clpp;
+{
+       CLIENT *client = NULL;
+       RPCB parms;
+       enum clnt_stat clnt_st;
+       char *ua = NULL;
+       rpcvers_t vers;
+       struct netbuf *address = NULL;
+       rpcvers_t start_vers = RPCBVERS4;
+       struct netbuf servaddr;
+
+       /* nconf is handled below */
+       _DIAGASSERT(host != NULL);
+       /* clpp may be NULL */
+
+       /* parameter checking */
+       if (nconf == NULL) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+               return (NULL);
+       }
+
+       parms.r_addr = NULL;
+
+#ifdef PORTMAP
+       /* Try version 2 for TCP or UDP */
+       if (strcmp(nconf->nc_protofmly, NC_INET) == 0) {
+               u_short port = 0;
+               struct netbuf remote;
+               rpcvers_t pmapvers = 2;
+               struct pmap pmapparms;
+
+               /*
+                * Try UDP only - there are some portmappers out
+                * there that use UDP only.
+                */
+               if (strcmp(nconf->nc_proto, NC_TCP) == 0) {
+                       struct netconfig *newnconf;
+
+                       if ((newnconf = getnetconfigent("udp")) == NULL) {
+                               rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+                               return (NULL);
+                       }
+                       client = getclnthandle(host, newnconf, &parms.r_addr);
+                       freenetconfigent(newnconf);
+               } else {
+                       client = getclnthandle(host, nconf, &parms.r_addr);
+               }
+               if (client == NULL) {
+                       return (NULL);
+               }
+
+               /* Set the version */
+               CLNT_CONTROL(client, CLSET_VERS, (char *)(void *)&pmapvers);
+               pmapparms.pm_prog = program;
+               pmapparms.pm_vers = version;
+               pmapparms.pm_prot = strcmp(nconf->nc_proto, NC_TCP) ?
+                                       IPPROTO_UDP : IPPROTO_TCP;
+               pmapparms.pm_port = 0;  /* not needed */
+               clnt_st = CLNT_CALL(client, (rpcproc_t)PMAPPROC_GETPORT,
+                   (xdrproc_t) xdr_pmap, (caddr_t)(void *)&pmapparms,
+                   (xdrproc_t) xdr_u_short, (caddr_t)(void *)&port,
+                   tottimeout);
+               if (clnt_st != RPC_SUCCESS) {
+                       if ((clnt_st == RPC_PROGVERSMISMATCH) ||
+                               (clnt_st == RPC_PROGUNAVAIL))
+                               goto try_rpcbind; /* Try different versions */
+                       rpc_createerr.cf_stat = RPC_PMAPFAILURE;
+                       clnt_geterr(client, &rpc_createerr.cf_error);
+                       goto error;
+               } else if (port == 0) {
+                       address = NULL;
+                       rpc_createerr.cf_stat = RPC_PROGNOTREGISTERED;
+                       goto error;
+               }
+               port = htons(port);
+               CLNT_CONTROL(client, CLGET_SVC_ADDR, (char *)(void *)&remote);
+               if (((address = malloc(sizeof(struct netbuf))) == NULL) ||
+                   ((address->buf = malloc(remote.len)) == NULL)) {
+                       rpc_createerr.cf_stat = RPC_SYSTEMERROR;
+                       clnt_geterr(client, &rpc_createerr.cf_error);
+                       if (address) {
+                               free(address);
+                               address = NULL;
+                       }
+                       goto error;
+               }
+               memcpy(address->buf, remote.buf, remote.len);
+               memcpy(&((char *)address->buf)[sizeof (short)],
+                               (char *)(void *)&port, sizeof (short));
+               address->len = address->maxlen = remote.len;
+               goto done;
+       }
+#endif
+
+try_rpcbind:
+       /*
+        * Now we try version 4 and then 3.
+        * We also send the remote system the address we used to
+        * contact it in case it can help to connect back with us
+        */
+       parms.r_prog = program;
+       parms.r_vers = version;
+       parms.r_owner = __UNCONST(&nullstring[0]);      /* not needed; */
+                                                       /* just for xdring */
+       parms.r_netid = nconf->nc_netid; /* not really needed */
+
+       /*
+        * If a COTS transport is being used, try getting address via CLTS
+        * transport.  This works only with version 4.
+        * NOTE: This is being done for all transports EXCEPT LOOPBACK
+        * because with loopback the cost to go to a COTS is same as
+        * the cost to go through CLTS, plus you get the advantage of
+        * finding out immediately if the local rpcbind process is dead.
+        */
+#if 1
+       if ((nconf->nc_semantics == NC_TPI_COTS_ORD ||
+                       nconf->nc_semantics == NC_TPI_COTS) &&
+           (strcmp(nconf->nc_protofmly, NC_LOOPBACK) != 0))
+#else
+       if (client != NULL) {
+               CLNT_DESTROY(client);
+               client = NULL;
+       }
+       if (nconf->nc_semantics == NC_TPI_CLTS)
+#endif
+       {
+               void *handle;
+               struct netconfig *nconf_clts;
+               rpcb_entry_list_ptr relp = NULL;
+
+               if (client == NULL) {
+                       /* This did not go through the above PORTMAP/TCP code */
+#if 1
+                       if ((handle = __rpc_setconf("datagram_v")) != NULL)
+#else
+                       if ((handle = __rpc_setconf("circuit_v")) != NULL)
+#endif
+                       {
+                               while ((nconf_clts = __rpc_getconf(handle))
+                                       != NULL) {
+                                       if (strcmp(nconf_clts->nc_protofmly,
+                                               nconf->nc_protofmly) != 0) {
+                                               continue;
+                                       }
+                                       client = getclnthandle(host, nconf_clts,
+                                                       &parms.r_addr);
+                                       break;
+                               }
+                               __rpc_endconf(handle);
+                       }
+                       if (client == NULL)
+                               goto regular_rpcbind;   /* Go the regular way */
+               } else {
+                       /* This is a UDP PORTMAP handle.  Change to version 4 */
+                       vers = RPCBVERS4;
+                       CLNT_CONTROL(client, CLSET_VERS, (char *)(void *)&vers);
+               }
+               /*
+                * We also send the remote system the address we used to
+                * contact it in case it can help it connect back with us
+                */
+               if (parms.r_addr == NULL) {
+                       /* for XDRing */
+                       parms.r_addr = __UNCONST(&nullstring[0]); 
+               }
+               clnt_st = CLNT_CALL(client, (rpcproc_t)RPCBPROC_GETADDRLIST,
+                   (xdrproc_t) xdr_rpcb, (char *)(void *)&parms,
+                   (xdrproc_t) xdr_rpcb_entry_list_ptr,
+                   (char *)(void *)&relp, tottimeout);
+               if (clnt_st == RPC_SUCCESS) {
+                       if ((address = got_entry(relp, nconf)) != NULL) {
+                               xdr_free((xdrproc_t) xdr_rpcb_entry_list_ptr,
+                                   (char *)(void *)&relp);
+                               CLNT_CONTROL(client, CLGET_SVC_ADDR,
+                                       (char *)(void *)&servaddr);
+                               __rpc_fixup_addr(address, &servaddr);
+                               goto done;
+                       }
+                       /* Entry not found for this transport */
+                       xdr_free((xdrproc_t) xdr_rpcb_entry_list_ptr,
+                           (char *)(void *)&relp);
+                       /*
+                        * XXX: should have perhaps returned with error but
+                        * since the remote machine might not always be able
+                        * to send the address on all transports, we try the
+                        * regular way with regular_rpcbind
+                        */
+                       goto regular_rpcbind;
+               } else if ((clnt_st == RPC_PROGVERSMISMATCH) ||
+                       (clnt_st == RPC_PROGUNAVAIL)) {
+                       start_vers = RPCBVERS;  /* Try version 3 now */
+                       goto regular_rpcbind; /* Try different versions */
+               } else {
+                       rpc_createerr.cf_stat = RPC_PMAPFAILURE;
+                       clnt_geterr(client, &rpc_createerr.cf_error);
+                       goto error;
+               }
+       }
+
+regular_rpcbind:
+
+       /* Now the same transport is to be used to get the address */
+#if 1
+       if (client && ((nconf->nc_semantics == NC_TPI_COTS_ORD) ||
+                       (nconf->nc_semantics == NC_TPI_COTS)))
+#else
+       if (client && nconf->nc_semantics == NC_TPI_CLTS)
+#endif
+       {
+               /* A CLTS type of client - destroy it */
+               CLNT_DESTROY(client);
+               client = NULL;
+       }
+
+       if (client == NULL) {
+               client = getclnthandle(host, nconf, &parms.r_addr);
+               if (client == NULL) {
+                       goto error;
+               }
+       }
+       if (parms.r_addr == NULL)
+               parms.r_addr = __UNCONST(&nullstring[0]);
+
+       /* First try from start_vers and then version 3 (RPCBVERS) */
+       for (vers = start_vers;  vers >= RPCBVERS; vers--) {
+               /* Set the version */
+               CLNT_CONTROL(client, CLSET_VERS, (char *)(void *)&vers);
+               clnt_st = CLNT_CALL(client, (rpcproc_t)RPCBPROC_GETADDR,
+                   (xdrproc_t) xdr_rpcb, (char *)(void *)&parms,
+                   (xdrproc_t) xdr_wrapstring, (char *)(void *) &ua,
+                   tottimeout);
+               if (clnt_st == RPC_SUCCESS) {
+                       if ((ua == NULL) || (ua[0] == 0)) {
+                               /* address unknown */
+                               rpc_createerr.cf_stat = RPC_PROGNOTREGISTERED;
+                               goto error;
+                       }
+                       address = uaddr2taddr(nconf, ua);
+#ifdef ND_DEBUG
+                       fprintf(stderr, "\tRemote address is [%s]\n", ua);
+                       if (!address)
+                               fprintf(stderr,
+                                       "\tCouldn't resolve remote address!\n");
+#endif
+                       xdr_free((xdrproc_t)xdr_wrapstring,
+                           (char *)(void *)&ua);
+
+                       if (! address) {
+                               /* We don't know about your universal address */
+                               rpc_createerr.cf_stat = RPC_N2AXLATEFAILURE;
+                               goto error;
+                       }
+                       CLNT_CONTROL(client, CLGET_SVC_ADDR,
+                           (char *)(void *)&servaddr);
+                       __rpc_fixup_addr(address, &servaddr);
+                       goto done;
+               } else if (clnt_st == RPC_PROGVERSMISMATCH) {
+                       struct rpc_err rpcerr;
+
+                       clnt_geterr(client, &rpcerr);
+                       if (rpcerr.re_vers.low > RPCBVERS4)
+                               goto error;  /* a new version, can't handle */
+               } else if (clnt_st != RPC_PROGUNAVAIL) {
+                       /* Cant handle this error */
+                       rpc_createerr.cf_stat = clnt_st;
+                       clnt_geterr(client, &rpc_createerr.cf_error);
+                       goto error;
+               }
+       }
+
+error:
+       if (client) {
+               CLNT_DESTROY(client);
+               client = NULL;
+       }
+done:
+       if (nconf->nc_semantics != NC_TPI_CLTS) {
+               /* This client is the connectionless one */
+               if (client) {
+                       CLNT_DESTROY(client);
+                       client = NULL;
+               }
+       }
+       if (clpp) {
+               *clpp = client;
+       } else if (client) {
+               CLNT_DESTROY(client);
+       }
+       return (address);
+}
+
+
+/*
+ * Find the mapped address for program, version.
+ * Calls the rpcbind service remotely to do the lookup.
+ * Uses the transport specified in nconf.
+ * Returns FALSE (0) if no map exists, else returns 1.
+ *
+ * Assuming that the address is all properly allocated
+ */
+int
+rpcb_getaddr(program, version, nconf, address, host)
+       rpcprog_t program;
+       rpcvers_t version;
+       const struct netconfig *nconf;
+       struct netbuf *address;
+       const char *host;
+{
+       struct netbuf *na;
+
+       _DIAGASSERT(address != NULL);
+
+       if ((na = __rpcb_findaddr(program, version, nconf,
+                               host, NULL)) == NULL)
+               return (FALSE);
+
+       if (na->len > address->maxlen) {
+               /* Too long address */
+               free(na->buf);
+               free(na);
+               rpc_createerr.cf_stat = RPC_FAILED;
+               return (FALSE);
+       }
+       memcpy(address->buf, na->buf, (size_t)na->len);
+       address->len = na->len;
+       free(na->buf);
+       free(na);
+       return (TRUE);
+}
+
+/*
+ * Get a copy of the current maps.
+ * Calls the rpcbind service remotely to get the maps.
+ *
+ * It returns only a list of the services
+ * It returns NULL on failure.
+ */
+rpcblist *
+rpcb_getmaps(nconf, host)
+       const struct netconfig *nconf;
+       const char *host;
+{
+       rpcblist_ptr head = NULL;
+       CLIENT *client;
+       enum clnt_stat clnt_st;
+       rpcvers_t vers = 0;
+
+       client = getclnthandle(host, nconf, NULL);
+       if (client == NULL) {
+               return (head);
+       }
+       clnt_st = CLNT_CALL(client, (rpcproc_t)RPCBPROC_DUMP,
+           (xdrproc_t) xdr_void, NULL, (xdrproc_t) xdr_rpcblist_ptr,
+           (char *)(void *)&head, tottimeout);
+       if (clnt_st == RPC_SUCCESS)
+               goto done;
+
+       if ((clnt_st != RPC_PROGVERSMISMATCH) &&
+           (clnt_st != RPC_PROGUNAVAIL)) {
+               rpc_createerr.cf_stat = RPC_RPCBFAILURE;
+               clnt_geterr(client, &rpc_createerr.cf_error);
+               goto done;
+       }
+
+       /* fall back to earlier version */
+       CLNT_CONTROL(client, CLGET_VERS, (char *)(void *)&vers);
+       if (vers == RPCBVERS4) {
+               vers = RPCBVERS;
+               CLNT_CONTROL(client, CLSET_VERS, (char *)(void *)&vers);
+               if (CLNT_CALL(client, (rpcproc_t)RPCBPROC_DUMP,
+                   (xdrproc_t) xdr_void, NULL, (xdrproc_t) xdr_rpcblist_ptr,
+                   (char *)(void *)&head, tottimeout) == RPC_SUCCESS)
+                       goto done;
+       }
+       rpc_createerr.cf_stat = RPC_RPCBFAILURE;
+       clnt_geterr(client, &rpc_createerr.cf_error);
+
+done:
+       CLNT_DESTROY(client);
+       return (head);
+}
+
+/*
+ * rpcbinder remote-call-service interface.
+ * This routine is used to call the rpcbind remote call service
+ * which will look up a service program in the address maps, and then
+ * remotely call that routine with the given parameters. This allows
+ * programs to do a lookup and call in one step.
+*/
+enum clnt_stat
+rpcb_rmtcall(nconf, host, prog, vers, proc, xdrargs, argsp,
+               xdrres, resp, tout, addr_ptr)
+       const struct netconfig *nconf;  /* Netconfig structure */
+       const char *host;                       /* Remote host name */
+       rpcprog_t prog;
+       rpcvers_t vers;
+       rpcproc_t proc;                 /* Remote proc identifiers */
+       xdrproc_t xdrargs, xdrres;      /* XDR routines */
+       const char *argsp;              /* Argument */
+       caddr_t resp;                   /* Result */
+       struct timeval tout;            /* Timeout value for this call */
+       const struct netbuf *addr_ptr;  /* Preallocated netbuf address */
+{
+       CLIENT *client;
+       enum clnt_stat stat;
+       struct r_rpcb_rmtcallargs a;
+       struct r_rpcb_rmtcallres r;
+       rpcvers_t rpcb_vers;
+
+       stat = RPC_FAILED;      /* XXXGCC -Wuninitialized [dreamcast] */
+
+       client = getclnthandle(host, nconf, NULL);
+       if (client == NULL) {
+               return (RPC_FAILED);
+       }
+       CLNT_CONTROL(client, CLSET_RETRY_TIMEOUT, __UNCONST(&rmttimeout));
+       a.prog = prog;
+       a.vers = vers;
+       a.proc = proc;
+       a.args.args_val = argsp;
+       a.xdr_args = xdrargs;
+       r.addr = NULL;
+       r.results.results_val = resp;
+       r.xdr_res = xdrres;
+
+       for (rpcb_vers = RPCBVERS4; rpcb_vers >= RPCBVERS; rpcb_vers--) {
+               CLNT_CONTROL(client, CLSET_VERS, (char *)(void *)&rpcb_vers);
+               stat = CLNT_CALL(client, (rpcproc_t)RPCBPROC_CALLIT,
+                   (xdrproc_t) xdr_rpcb_rmtcallargs, (char *)(void *)&a,
+                   (xdrproc_t) xdr_rpcb_rmtcallres, (char *)(void *)&r, tout);
+               if ((stat == RPC_SUCCESS) && (addr_ptr != NULL)) {
+                       struct netbuf *na;
+                       na = uaddr2taddr(__UNCONST(nconf), r.addr);
+                       if (!na) {
+                               stat = RPC_N2AXLATEFAILURE;
+                               ((struct netbuf *)__UNCONST(addr_ptr))->len = 0;
+                               goto error;
+                       }
+                       if (na->len > addr_ptr->maxlen) {
+                               /* Too long address */
+                               stat = RPC_FAILED; /* XXX A better error no */
+                               free(na->buf);
+                               free(na);
+                               ((struct netbuf *)__UNCONST(addr_ptr))->len = 0;
+                               goto error;
+                       }
+                       memcpy(addr_ptr->buf, na->buf, (size_t)na->len);
+                       ((struct netbuf *)__UNCONST(addr_ptr))->len = na->len;
+                       free(na->buf);
+                       free(na);
+                       break;
+               } else if ((stat != RPC_PROGVERSMISMATCH) &&
+                           (stat != RPC_PROGUNAVAIL)) {
+                       goto error;
+               }
+       }
+error:
+       CLNT_DESTROY(client);
+       if (r.addr)
+               xdr_free((xdrproc_t) xdr_wrapstring, (char *)(void *)&r.addr);
+       return (stat);
+}
+
+/*
+ * Gets the time on the remote host.
+ * Returns 1 if succeeds else 0.
+ */
+bool_t
+rpcb_gettime(host, timep)
+       const char *host;
+       time_t *timep;
+{
+       CLIENT *client = NULL;
+       void *handle;
+       struct netconfig *nconf;
+       rpcvers_t vers;
+       enum clnt_stat st;
+
+
+       if ((host == NULL) || (host[0] == 0)) {
+               time(timep);
+               return (TRUE);
+       }
+
+       if ((handle = __rpc_setconf("netpath")) == NULL) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+               return (FALSE);
+       }
+       rpc_createerr.cf_stat = RPC_SUCCESS;
+       while (client == NULL) {
+               if ((nconf = __rpc_getconf(handle)) == NULL) {
+                       if (rpc_createerr.cf_stat == RPC_SUCCESS)
+                               rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+                       break;
+               }
+               client = getclnthandle(host, nconf, NULL);
+               if (client)
+                       break;
+       }
+       __rpc_endconf(handle);
+       if (client == NULL) {
+               return (FALSE);
+       }
+
+       st = CLNT_CALL(client, (rpcproc_t)RPCBPROC_GETTIME,
+               (xdrproc_t) xdr_void, NULL,
+               (xdrproc_t) xdr_int, (char *)(void *)timep, tottimeout);
+
+       if ((st == RPC_PROGVERSMISMATCH) || (st == RPC_PROGUNAVAIL)) {
+               CLNT_CONTROL(client, CLGET_VERS, (char *)(void *)&vers);
+               if (vers == RPCBVERS4) {
+                       /* fall back to earlier version */
+                       vers = RPCBVERS;
+                       CLNT_CONTROL(client, CLSET_VERS, (char *)(void *)&vers);
+                       st = CLNT_CALL(client, (rpcproc_t)RPCBPROC_GETTIME,
+                               (xdrproc_t) xdr_void, NULL,
+                               (xdrproc_t) xdr_int, (char *)(void *)timep,
+                               tottimeout);
+               }
+       }
+       CLNT_DESTROY(client);
+       return (st == RPC_SUCCESS? TRUE: FALSE);
+}
+
+/*
+ * Converts taddr to universal address.  This routine should never
+ * really be called because local n2a libraries are always provided.
+ */
+char *
+rpcb_taddr2uaddr(nconf, taddr)
+       struct netconfig *nconf;
+       struct netbuf *taddr;
+{
+       CLIENT *client;
+       char *uaddr = NULL;
+
+
+       /* parameter checking */
+       if (nconf == NULL) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+               return (NULL);
+       }
+       if (taddr == NULL) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNADDR;
+               return (NULL);
+       }
+       client = local_rpcb();
+       if (! client) {
+               return (NULL);
+       }
+
+       CLNT_CALL(client, (rpcproc_t)RPCBPROC_TADDR2UADDR,
+           (xdrproc_t) xdr_netbuf, (char *)(void *)taddr,
+           (xdrproc_t) xdr_wrapstring, (char *)(void *)&uaddr, tottimeout);
+       CLNT_DESTROY(client);
+       return (uaddr);
+}
+
+/*
+ * Converts universal address to netbuf.  This routine should never
+ * really be called because local n2a libraries are always provided.
+ */
+struct netbuf *
+rpcb_uaddr2taddr(nconf, uaddr)
+       struct netconfig *nconf;
+       char *uaddr;
+{
+       CLIENT *client;
+       struct netbuf *taddr;
+
+
+       /* parameter checking */
+       if (nconf == NULL) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
+               return (NULL);
+       }
+       if (uaddr == NULL) {
+               rpc_createerr.cf_stat = RPC_UNKNOWNADDR;
+               return (NULL);
+       }
+       client = local_rpcb();
+       if (! client) {
+               return (NULL);
+       }
+
+       taddr = (struct netbuf *)calloc(1, sizeof (struct netbuf));
+       if (taddr == NULL) {
+               CLNT_DESTROY(client);
+               return (NULL);
+       }
+       if (CLNT_CALL(client, (rpcproc_t)RPCBPROC_UADDR2TADDR,
+           (xdrproc_t) xdr_wrapstring, (char *)(void *)&uaddr,
+           (xdrproc_t) xdr_netbuf, (char *)(void *)taddr,
+           tottimeout) != RPC_SUCCESS) {
+               free(taddr);
+               taddr = NULL;
+       }
+       CLNT_DESTROY(client);
+       return (taddr);
+}
diff --git a/lib/nbsd_libc/rpc/rpcb_prot.c b/lib/nbsd_libc/rpc/rpcb_prot.c
new file mode 100644 (file)
index 0000000..37c73e7
--- /dev/null
@@ -0,0 +1,369 @@
+/*     $NetBSD: rpcb_prot.c,v 1.9 2006/05/11 17:11:57 mrg Exp $        */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc. 
+ */
+
+/* #ident      "@(#)rpcb_prot.c        1.13    94/04/24 SMI" */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)rpcb_prot.c 1.9 89/04/21 Copyr 1984 Sun Micro";
+#else
+__RCSID("$NetBSD: rpcb_prot.c,v 1.9 2006/05/11 17:11:57 mrg Exp $");
+#endif
+#endif
+
+/*
+ * rpcb_prot.c
+ * XDR routines for the rpcbinder version 3.
+ *
+ * Copyright (C) 1984, 1988, Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+
+#include <rpc/rpc.h>
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+#include <rpc/rpcb_prot.h>
+
+#include <assert.h>
+
+#ifdef __weak_alias
+__weak_alias(xdr_rpcb,_xdr_rpcb)
+__weak_alias(xdr_rpcblist_ptr,_xdr_rpcblist_ptr)
+__weak_alias(xdr_rpcblist,_xdr_rpcblist)
+__weak_alias(xdr_rpcb_entry,_xdr_rpcb_entry)
+__weak_alias(xdr_rpcb_entry_list_ptr,_xdr_rpcb_entry_list_ptr)
+__weak_alias(xdr_rpcb_rmtcallargs,_xdr_rpcb_rmtcallargs)
+__weak_alias(xdr_rpcb_rmtcallres,_xdr_rpcb_rmtcallres)
+__weak_alias(xdr_netbuf,_xdr_netbuf)
+#endif
+
+
+bool_t
+xdr_rpcb(xdrs, objp)
+       XDR *xdrs;
+       RPCB *objp;
+{
+
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_u_int32_t(xdrs, &objp->r_prog)) {
+               return (FALSE);
+       }
+       if (!xdr_u_int32_t(xdrs, &objp->r_vers)) {
+               return (FALSE);
+       }
+       if (!xdr_string(xdrs, &objp->r_netid, (u_int)~0)) {
+               return (FALSE);
+       }
+       if (!xdr_string(xdrs, &objp->r_addr, (u_int)~0)) {
+               return (FALSE);
+       }
+       if (!xdr_string(xdrs, &objp->r_owner, (u_int)~0)) {
+               return (FALSE);
+       }
+       return (TRUE);
+}
+
+/*
+ * rpcblist_ptr implements a linked list.  The RPCL definition from
+ * rpcb_prot.x is:
+ *
+ * struct rpcblist {
+ *     rpcb            rpcb_map;
+ *     struct rpcblist *rpcb_next;
+ * };
+ * typedef rpcblist *rpcblist_ptr;
+ *
+ * Recall that "pointers" in XDR are encoded as a boolean, indicating whether
+ * there's any data behind the pointer, followed by the data (if any exists).
+ * The boolean can be interpreted as ``more data follows me''; if FALSE then
+ * nothing follows the boolean; if TRUE then the boolean is followed by an
+ * actual struct rpcb, and another rpcblist_ptr (declared in RPCL as "struct
+ * rpcblist *").
+ *
+ * This could be implemented via the xdr_pointer type, though this would
+ * result in one recursive call per element in the list.  Rather than do that
+ * we can ``unwind'' the recursion into a while loop and use xdr_reference to
+ * serialize the rpcb elements.
+ */
+
+bool_t
+xdr_rpcblist_ptr(xdrs, rp)
+       XDR *xdrs;
+       rpcblist_ptr *rp;
+{
+       /*
+        * more_elements is pre-computed in case the direction is
+        * XDR_ENCODE or XDR_FREE.  more_elements is overwritten by
+        * xdr_bool when the direction is XDR_DECODE.
+        */
+       bool_t more_elements;
+       int freeing;
+       rpcblist_ptr next;
+       rpcblist_ptr next_copy;
+
+       _DIAGASSERT(xdrs != NULL);
+       /* XXX: rp may be NULL ??? */
+
+       freeing = (xdrs->x_op == XDR_FREE);
+       next = NULL;
+
+       for (;;) {
+               more_elements = (bool_t)(*rp != NULL);
+               if (! xdr_bool(xdrs, &more_elements)) {
+                       return (FALSE);
+               }
+               if (! more_elements) {
+                       return (TRUE);  /* we are done */
+               }
+               /*
+                * the unfortunate side effect of non-recursion is that in
+                * the case of freeing we must remember the next object
+                * before we free the current object ...
+                */
+               if (freeing && *rp)
+                       next = (*rp)->rpcb_next;
+               if (! xdr_reference(xdrs, (caddr_t *)rp,
+                   (u_int)sizeof (rpcblist), (xdrproc_t)xdr_rpcb)) {
+                       return (FALSE);
+               }
+               if (freeing) {
+                       next_copy = next;
+                       rp = &next_copy;
+                       /*
+                        * Note that in the subsequent iteration, next_copy
+                        * gets nulled out by the xdr_reference
+                        * but next itself survives.
+                        */
+               } else if (*rp) {
+                       rp = &((*rp)->rpcb_next);
+               }
+       }
+       /*NOTREACHED*/
+}
+
+/*
+ * xdr_rpcblist() is specified to take a RPCBLIST **, but is identical in
+ * functionality to xdr_rpcblist_ptr().
+ */
+bool_t
+xdr_rpcblist(xdrs, rp)
+       XDR *xdrs;
+       RPCBLIST **rp;
+{
+       bool_t  dummy;
+
+       dummy = xdr_rpcblist_ptr(xdrs, (rpcblist_ptr *)rp);
+       return (dummy);
+}
+
+
+bool_t
+xdr_rpcb_entry(xdrs, objp)
+       XDR *xdrs;
+       rpcb_entry *objp;
+{
+
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_string(xdrs, &objp->r_maddr, (u_int)~0)) {
+               return (FALSE);
+       }
+       if (!xdr_string(xdrs, &objp->r_nc_netid, (u_int)~0)) {
+               return (FALSE);
+       }
+       if (!xdr_u_int32_t(xdrs, &objp->r_nc_semantics)) {
+               return (FALSE);
+       }
+       if (!xdr_string(xdrs, &objp->r_nc_protofmly, (u_int)~0)) {
+               return (FALSE);
+       }
+       if (!xdr_string(xdrs, &objp->r_nc_proto, (u_int)~0)) {
+               return (FALSE);
+       }
+       return (TRUE);
+}
+
+bool_t
+xdr_rpcb_entry_list_ptr(xdrs, rp)
+       XDR *xdrs;
+       rpcb_entry_list_ptr *rp;
+{
+       /*
+        * more_elements is pre-computed in case the direction is
+        * XDR_ENCODE or XDR_FREE.  more_elements is overwritten by
+        * xdr_bool when the direction is XDR_DECODE.
+        */
+       bool_t more_elements;
+       int freeing;
+       rpcb_entry_list_ptr next;
+       rpcb_entry_list_ptr next_copy;
+
+       _DIAGASSERT(xdrs != NULL);
+       /* XXX: rp is allowed to be NULL ??? */
+
+       freeing = (xdrs->x_op == XDR_FREE);
+       next = NULL;
+
+       for (;;) {
+               more_elements = (bool_t)(*rp != NULL);
+               if (! xdr_bool(xdrs, &more_elements)) {
+                       return (FALSE);
+               }
+               if (! more_elements) {
+                       return (TRUE);  /* we are done */
+               }
+               /*
+                * the unfortunate side effect of non-recursion is that in
+                * the case of freeing we must remember the next object
+                * before we free the current object ...
+                */
+               if (freeing && *rp)
+                       next = (*rp)->rpcb_entry_next;
+               if (! xdr_reference(xdrs, (caddr_t *)rp,
+                   (u_int)sizeof (rpcb_entry_list),
+                                   (xdrproc_t)xdr_rpcb_entry)) {
+                       return (FALSE);
+               }
+               if (freeing) {
+                       next_copy = next;
+                       rp = &next_copy;
+                       /*
+                        * Note that in the subsequent iteration, next_copy
+                        * gets nulled out by the xdr_reference
+                        * but next itself survives.
+                        */
+               } else if (*rp) {
+                       rp = &((*rp)->rpcb_entry_next);
+               }
+       }
+       /*NOTREACHED*/
+}
+
+/*
+ * XDR remote call arguments
+ * written for XDR_ENCODE direction only
+ */
+bool_t
+xdr_rpcb_rmtcallargs(xdrs, p)
+       XDR *xdrs;
+       struct rpcb_rmtcallargs *p;
+{
+       struct r_rpcb_rmtcallargs *objp =
+           (struct r_rpcb_rmtcallargs *)(void *)p;
+       u_int lenposition, argposition, position;
+       int32_t *buf;
+
+       _DIAGASSERT(p != NULL);
+
+       buf = XDR_INLINE(xdrs, 3 * BYTES_PER_XDR_UNIT);
+       if (buf == NULL) {
+               if (!xdr_u_int32_t(xdrs, &objp->prog)) {
+                       return (FALSE);
+               }
+               if (!xdr_u_int32_t(xdrs, &objp->vers)) {
+                       return (FALSE);
+               }
+               if (!xdr_u_int32_t(xdrs, &objp->proc)) {
+                       return (FALSE);
+               }
+       } else {
+               IXDR_PUT_U_INT32(buf, objp->prog);
+               IXDR_PUT_U_INT32(buf, objp->vers);
+               IXDR_PUT_U_INT32(buf, objp->proc);
+       }
+
+       /*
+        * All the jugglery for just getting the size of the arguments
+        */
+       lenposition = XDR_GETPOS(xdrs);
+       if (! xdr_u_int(xdrs, &(objp->args.args_len))) {
+               return (FALSE);
+       }
+       argposition = XDR_GETPOS(xdrs);
+       if (! (*objp->xdr_args)(xdrs, objp->args.args_val)) {
+               return (FALSE);
+       }
+       position = XDR_GETPOS(xdrs);
+       objp->args.args_len = (u_int)((u_long)position - (u_long)argposition);
+       XDR_SETPOS(xdrs, lenposition);
+       if (! xdr_u_int(xdrs, &(objp->args.args_len))) {
+               return (FALSE);
+       }
+       XDR_SETPOS(xdrs, position);
+       return (TRUE);
+}
+
+/*
+ * XDR remote call results
+ * written for XDR_DECODE direction only
+ */
+bool_t
+xdr_rpcb_rmtcallres(xdrs, p)
+       XDR *xdrs;
+       struct rpcb_rmtcallres *p;
+{
+       bool_t dummy;
+       struct r_rpcb_rmtcallres *objp = (struct r_rpcb_rmtcallres *)(void *)p;
+
+       _DIAGASSERT(p != NULL);
+
+       if (!xdr_string(xdrs, &objp->addr, (u_int)~0)) {
+               return (FALSE);
+       }
+       if (!xdr_u_int(xdrs, &objp->results.results_len)) {
+               return (FALSE);
+       }
+       dummy = (*(objp->xdr_res))(xdrs, objp->results.results_val);
+       return (dummy);
+}
+
+bool_t
+xdr_netbuf(xdrs, objp)
+       XDR *xdrs;
+       struct netbuf *objp;
+{
+       bool_t dummy;
+
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_u_int32_t(xdrs, (u_int32_t *) &objp->maxlen)) {
+               return (FALSE);
+       }
+       dummy = xdr_bytes(xdrs, (char **)(void *)&(objp->buf),
+                       (u_int *)&(objp->len), objp->maxlen);
+       return (dummy);
+}
diff --git a/lib/nbsd_libc/rpc/rpcb_st_xdr.c b/lib/nbsd_libc/rpc/rpcb_st_xdr.c
new file mode 100644 (file)
index 0000000..ed235e3
--- /dev/null
@@ -0,0 +1,287 @@
+/*     $NetBSD: rpcb_st_xdr.c,v 1.7 2006/05/11 17:11:57 mrg Exp $      */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright 1991 Sun Microsystems, Inc.
+ * rpcb_stat_xdr.c
+ */
+
+/*
+ * This file was generated from rpcb_prot.x, but includes only those
+ * routines used with the rpcbind stats facility.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: rpcb_st_xdr.c,v 1.7 2006/05/11 17:11:57 mrg Exp $");
+#endif
+
+#include "namespace.h"
+#include <rpc/rpc.h>
+
+#include <assert.h>
+
+/* Link list of all the stats about getport and getaddr */
+
+#ifdef __weak_alias
+__weak_alias(xdr_rpcbs_addrlist,_xdr_rpcbs_addrlist)
+__weak_alias(xdr_rpcbs_rmtcalllist,_xdr_rpcbs_rmtcalllist)
+__weak_alias(xdr_rpcbs_proc,_xdr_rpcbs_proc)
+__weak_alias(xdr_rpcbs_addrlist_ptr,_xdr_rpcbs_addrlist_ptr)
+__weak_alias(xdr_rpcbs_rmtcalllist_ptr,_xdr_rpcbs_rmtcalllist_ptr)
+__weak_alias(xdr_rpcb_stat,_xdr_rpcb_stat)
+__weak_alias(xdr_rpcb_stat_byvers,_xdr_rpcb_stat_byvers)
+#endif
+
+bool_t
+xdr_rpcbs_addrlist(xdrs, objp)
+       XDR *xdrs;
+       rpcbs_addrlist *objp;
+{
+
+       _DIAGASSERT(objp != NULL);
+
+           if (!xdr_u_int32_t(xdrs, &objp->prog)) {
+               return (FALSE);
+           }
+           if (!xdr_u_int32_t(xdrs, &objp->vers)) {
+               return (FALSE);
+           }
+           if (!xdr_int(xdrs, &objp->success)) {
+               return (FALSE);
+           }
+           if (!xdr_int(xdrs, &objp->failure)) {
+               return (FALSE);
+           }
+           if (!xdr_string(xdrs, &objp->netid, (u_int)~0)) {
+               return (FALSE);
+           }
+
+           if (!xdr_pointer(xdrs, (char **)(void *)&objp->next,
+                       sizeof (rpcbs_addrlist),
+                       (xdrproc_t)xdr_rpcbs_addrlist)) {
+               return (FALSE);
+           }
+
+       return (TRUE);
+}
+
+/* Link list of all the stats about rmtcall */
+
+bool_t
+xdr_rpcbs_rmtcalllist(xdrs, objp)
+       XDR *xdrs;
+       rpcbs_rmtcalllist *objp;
+{
+       int32_t *buf;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (xdrs->x_op == XDR_ENCODE) {
+       buf = XDR_INLINE(xdrs, 6 * BYTES_PER_XDR_UNIT);
+       if (buf == NULL) {
+               if (!xdr_u_int32_t(xdrs, &objp->prog)) {
+                       return (FALSE);
+               }
+               if (!xdr_u_int32_t(xdrs, &objp->vers)) {
+                       return (FALSE);
+               }
+               if (!xdr_u_int32_t(xdrs, &objp->proc)) {
+                       return (FALSE);
+               }
+               if (!xdr_int(xdrs, &objp->success)) {
+                       return (FALSE);
+               }
+               if (!xdr_int(xdrs, &objp->failure)) {
+                       return (FALSE);
+               }
+               if (!xdr_int(xdrs, &objp->indirect)) {
+                       return (FALSE);
+               }
+       } else {
+               IXDR_PUT_U_INT32(buf, objp->prog);
+               IXDR_PUT_U_INT32(buf, objp->vers);
+               IXDR_PUT_U_INT32(buf, objp->proc);
+               IXDR_PUT_INT32(buf, objp->success);
+               IXDR_PUT_INT32(buf, objp->failure);
+               IXDR_PUT_INT32(buf, objp->indirect);
+       }
+       if (!xdr_string(xdrs, &objp->netid, (u_int)~0)) {
+               return (FALSE);
+       }
+       if (!xdr_pointer(xdrs, (char **)(void *)&objp->next,
+                       sizeof (rpcbs_rmtcalllist),
+                       (xdrproc_t)xdr_rpcbs_rmtcalllist)) {
+               return (FALSE);
+       }
+       return (TRUE);
+       } else if (xdrs->x_op == XDR_DECODE) {
+       buf = XDR_INLINE(xdrs, 6 * BYTES_PER_XDR_UNIT);
+       if (buf == NULL) {
+               if (!xdr_u_int32_t(xdrs, &objp->prog)) {
+                       return (FALSE);
+               }
+               if (!xdr_u_int32_t(xdrs, &objp->vers)) {
+                       return (FALSE);
+               }
+               if (!xdr_u_int32_t(xdrs, &objp->proc)) {
+                       return (FALSE);
+               }
+               if (!xdr_int(xdrs, &objp->success)) {
+                       return (FALSE);
+               }
+               if (!xdr_int(xdrs, &objp->failure)) {
+                       return (FALSE);
+               }
+               if (!xdr_int(xdrs, &objp->indirect)) {
+                       return (FALSE);
+               }
+       } else {
+               objp->prog = (rpcprog_t)IXDR_GET_U_INT32(buf);
+               objp->vers = (rpcvers_t)IXDR_GET_U_INT32(buf);
+               objp->proc = (rpcproc_t)IXDR_GET_U_INT32(buf);
+               objp->success = (int)IXDR_GET_INT32(buf);
+               objp->failure = (int)IXDR_GET_INT32(buf);
+               objp->indirect = (int)IXDR_GET_INT32(buf);
+       }
+       if (!xdr_string(xdrs, &objp->netid, (u_int)~0)) {
+               return (FALSE);
+       }
+       if (!xdr_pointer(xdrs, (char **)(void *)&objp->next,
+                       sizeof (rpcbs_rmtcalllist),
+                       (xdrproc_t)xdr_rpcbs_rmtcalllist)) {
+               return (FALSE);
+       }
+       return (TRUE);
+       }
+       if (!xdr_u_int32_t(xdrs, &objp->prog)) {
+               return (FALSE);
+       }
+       if (!xdr_u_int32_t(xdrs, &objp->vers)) {
+               return (FALSE);
+       }
+       if (!xdr_u_int32_t(xdrs, &objp->proc)) {
+               return (FALSE);
+       }
+       if (!xdr_int(xdrs, &objp->success)) {
+               return (FALSE);
+       }
+       if (!xdr_int(xdrs, &objp->failure)) {
+               return (FALSE);
+       }
+       if (!xdr_int(xdrs, &objp->indirect)) {
+               return (FALSE);
+       }
+       if (!xdr_string(xdrs, &objp->netid, (u_int)~0)) {
+               return (FALSE);
+       }
+       if (!xdr_pointer(xdrs, (char **)(void *)&objp->next,
+                       sizeof (rpcbs_rmtcalllist),
+                       (xdrproc_t)xdr_rpcbs_rmtcalllist)) {
+               return (FALSE);
+       }
+       return (TRUE);
+}
+
+bool_t
+xdr_rpcbs_proc(xdrs, objp)
+       XDR *xdrs;
+       rpcbs_proc objp;
+{
+       if (!xdr_vector(xdrs, (char *)(void *)objp, RPCBSTAT_HIGHPROC,
+           sizeof (int), (xdrproc_t)xdr_int)) {
+               return (FALSE);
+       }
+       return (TRUE);
+}
+
+bool_t
+xdr_rpcbs_addrlist_ptr(xdrs, objp)
+       XDR *xdrs;
+       rpcbs_addrlist_ptr *objp;
+{
+       if (!xdr_pointer(xdrs, (char **)objp, sizeof (rpcbs_addrlist),
+                       (xdrproc_t)xdr_rpcbs_addrlist)) {
+               return (FALSE);
+       }
+       return (TRUE);
+}
+
+bool_t
+xdr_rpcbs_rmtcalllist_ptr(xdrs, objp)
+       XDR *xdrs;
+       rpcbs_rmtcalllist_ptr *objp;
+{
+       if (!xdr_pointer(xdrs, (char **)objp, sizeof (rpcbs_rmtcalllist),
+                       (xdrproc_t)xdr_rpcbs_rmtcalllist)) {
+               return (FALSE);
+       }
+       return (TRUE);
+}
+
+bool_t
+xdr_rpcb_stat(xdrs, objp)
+       XDR *xdrs;
+       rpcb_stat *objp;
+{
+
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_rpcbs_proc(xdrs, objp->info)) {
+               return (FALSE);
+       }
+       if (!xdr_int(xdrs, &objp->setinfo)) {
+               return (FALSE);
+       }
+       if (!xdr_int(xdrs, &objp->unsetinfo)) {
+               return (FALSE);
+       }
+       if (!xdr_rpcbs_addrlist_ptr(xdrs, &objp->addrinfo)) {
+               return (FALSE);
+       }
+       return (TRUE);
+}
+
+/*
+ * One rpcb_stat structure is returned for each version of rpcbind
+ * being monitored.
+ */
+bool_t
+xdr_rpcb_stat_byvers(xdrs, objp)
+       XDR *xdrs;
+       rpcb_stat_byvers objp;
+{
+       if (!xdr_vector(xdrs, (char *)(void *)objp, RPCBVERS_STAT,
+           sizeof (rpcb_stat), (xdrproc_t)xdr_rpcb_stat)) {
+               return (FALSE);
+       }
+       return (TRUE);
+}
diff --git a/lib/nbsd_libc/rpc/rpcbind.3 b/lib/nbsd_libc/rpc/rpcbind.3
new file mode 100644 (file)
index 0000000..436b8ab
--- /dev/null
@@ -0,0 +1,201 @@
+.\" @(#)rpcbind.3n 1.25 93/05/07 SMI; from SVr4
+.\" Copyright 1989 AT&T
+.\" Copyright (c) 1988 Sun Microsystems, Inc. - All Rights Reserved.
+.\"    $NetBSD: rpcbind.3,v 1.11 2009/04/11 16:07:20 joerg Exp $
+.Dd December 4, 2005
+.Dt RPCBIND 3
+.Os
+.Sh NAME
+.Nm rpcb_getmaps ,
+.Nm rpcb_getaddr ,
+.Nm rpcb_gettime ,
+.Nm rpcb_rmtcall ,
+.Nm rpcb_set ,
+.Nm rpcb_unset
+.Nd library routines for RPC bind service
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In rpc/rpc.h
+.Ft "struct rpcblist *"
+.Fn rpcb_getmaps "const struct netconfig *netconf" "const char *host"
+.Ft bool_t
+.Fn rpcb_getaddr "const rpcprog_t prognum" "const rpcvers_t versnum" "const struct netconfig *netconf" "struct netbuf *svcaddr" "const char *host"
+.Ft bool_t
+.Fn rpcb_gettime "const char *host" "time_t * timep"
+.Ft "enum clnt_stat"
+.Fn rpcb_rmtcall "const struct netconfig *netconf" "const char *host" "const rpcprog_t prognum, const rpcvers_t versnum" "const rpcproc_t procnum, const xdrproc_t inproc" "const char *in" "const xdrproc_t outproc" "caddr_t out" "const struct timeval tout, struct netbuf  *svcaddr"
+.Ft bool_t
+.Fn rpcb_set "const rpcprog_t prognum" "const rpcvers_t versnum" "const struct netconfig *netconf" "const struct netbuf *svcaddr"
+.Ft bool_t
+.Fn rpcb_unset "const rpcprog_t prognum" "const rpcvers_t versnum" "const struct netconfig *netconf"
+.Sh DESCRIPTION
+These routines allow client C programs to make procedure
+calls to the RPC binder service.
+(see
+.Xr rpcbind 8 )
+maintains a list of mappings between programs
+and their universal addresses.
+.Sh ROUTINES
+.Bl -tag -width XXXXX
+.It Fn rpcb_getmaps
+An interface to the rpcbind service,
+which returns a list of the current
+RPC program-to-address mappings on
+.Fa host .
+It uses the transport specified through
+.Fa netconf
+to contact the remote rpcbind
+service on
+.Fa host .
+This routine will return
+.Dv NULL ,
+if the remote rpcbind could not be contacted.
+.Pp
+.It Fn rpcb_getaddr
+An interface to the rpcbind
+service, which finds the address of the service on
+.Fa host
+that is registered with program number
+.Fa prognum ,
+version
+.Fa versnum ,
+and speaks the transport protocol associated with
+.Fa netconf .
+The address found is returned in
+.Fa svcaddr .
+.Fa svcaddr
+should be preallocated.
+This routine returns
+.Dv TRUE
+if it succeeds.
+A return value of
+.Dv FALSE
+means that the mapping does not exist
+or that the RPC
+system failed to contact the remote
+rpcbind service.
+In the latter case, the global variable
+.Va rpc_createerr
+(see
+.Xr rpc_clnt_create 3
+contains the
+RPC status.
+.Pp
+.It Fn rpcb_gettime
+This routine returns the time on
+.Fa host
+in
+.Fa timep .
+If
+.Fa host
+is
+.Dv NULL ,
+.Fn rpcb_gettime
+returns the time on its own machine.
+This routine returns
+.Dv TRUE
+if it succeeds,
+.Dv FALSE
+if it fails.
+.Fn rpcb_gettime
+can be used to synchronize the time between the
+client and the remote server.
+.Pp
+.It Fn rpcb_rmtcall
+An interface to the rpcbind service, which instructs
+rpcbind on
+.Fa host
+to make an RPC
+call on your behalf to a procedure on that host.
+The
+.Fn netconfig
+structure should correspond to a connectionless transport.
+The parameter
+.Fa svcaddr
+will be modified to the server's address if the procedure succeeds
+(see
+.Fn rpc_call
+and
+.Fn clnt_call
+in
+.Xr rpc_clnt_calls 3
+for the definitions of other parameters).
+.Pp
+This procedure should normally be used for a
+``ping'' and nothing else.
+This routine allows programs to do lookup and call, all in one step.
+.Pp
+Note: Even if the server is not running
+.Fn rpcb_rmtcall
+does not return any error messages to the caller.
+In such a case, the caller times out.
+.Pp
+Note:
+.Fn rpcb_rmtcall
+is only available for connectionless transports.
+.Pp
+.It Fn rpcb_set
+An interface to the rpcbind
+service, which establishes a mapping between the triple
+[
+.Fa prognum ,
+.Fa versnum ,
+.Fa netconf-\*[Gt]nc_netid ]
+and
+.Fa svcaddr
+on the machine's rpcbind
+service.
+The value of
+.Fa nc_netid
+must correspond to a network identifier that is defined by the
+netconfig database.
+This routine returns
+.Dv TRUE
+if it succeeds,
+.Dv FALSE
+otherwise.
+(See also
+.Fn svc_reg
+in
+.Xr rpc_svc_calls 3 .
+If there already exists such an entry with rpcbind,
+.Fn rpcb_set
+will fail.
+.Pp
+.It Fn rpcb_unset
+An interface to the rpcbind
+service, which destroys the mapping between the triple
+[
+.Fa prognum ,
+.Fa versnum ,
+.Fa netconf-\*[Gt]nc_netid ]
+and the address on the machine's rpcbind
+service.
+If
+.Fa netconf
+is
+.Dv NULL ,
+.Fn rpcb_unset
+destroys all mapping between the triple
+[
+.Fa prognum ,
+.Fa versnum ,
+.Fa all-transports ]
+and the addresses on the machine's rpcbind service.
+This routine returns
+.Dv TRUE
+if it succeeds,
+.Dv FALSE
+otherwise.
+Only the owner of the service or the super-user can destroy the mapping.
+(See also
+.Fn svc_unreg
+in
+.Xr rpc_svc_calls 3 .
+.El
+.Sh SEE ALSO
+.Xr rpc_clnt_calls 3 ,
+.Xr rpc_svc_calls 3 ,
+.Xr rpcbind 8 ,
+.Xr rpcinfo 8
diff --git a/lib/nbsd_libc/rpc/svc.c b/lib/nbsd_libc/rpc/svc.c
new file mode 100644 (file)
index 0000000..67c67f5
--- /dev/null
@@ -0,0 +1,799 @@
+/*     $NetBSD: svc.c,v 1.30 2010/07/08 20:12:37 tron Exp $    */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint) 
+#if 0
+static char *sccsid = "@(#)svc.c 1.44 88/02/08 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)svc.c       2.4 88/08/11 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: svc.c,v 1.30 2010/07/08 20:12:37 tron Exp $");
+#endif
+#endif
+
+/*
+ * svc.c, Server-side remote procedure call interface.
+ *
+ * There are two sets of procedures here.  The xprt routines are
+ * for handling transport handles.  The svc routines handle the
+ * list of service routines.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/poll.h>
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <err.h>
+
+#include <rpc/rpc.h>
+#ifdef PORTMAP
+#include <rpc/pmap_clnt.h>
+#endif
+
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(svc_getreq,_svc_getreq)
+__weak_alias(svc_getreqset,_svc_getreqset)
+__weak_alias(svc_getreq_common,_svc_getreq_common)
+__weak_alias(svc_register,_svc_register)
+__weak_alias(svc_reg,_svc_reg)
+__weak_alias(svc_unreg,_svc_unreg)
+__weak_alias(svc_sendreply,_svc_sendreply)
+__weak_alias(svc_unregister,_svc_unregister)
+__weak_alias(svcerr_auth,_svcerr_auth)
+__weak_alias(svcerr_decode,_svcerr_decode)
+__weak_alias(svcerr_noproc,_svcerr_noproc)
+__weak_alias(svcerr_noprog,_svcerr_noprog)
+__weak_alias(svcerr_progvers,_svcerr_progvers)
+__weak_alias(svcerr_systemerr,_svcerr_systemerr)
+__weak_alias(svcerr_weakauth,_svcerr_weakauth)
+__weak_alias(xprt_register,_xprt_register)
+__weak_alias(xprt_unregister,_xprt_unregister)
+__weak_alias(rpc_control,_rpc_control)
+#endif
+
+SVCXPRT **__svc_xports;
+int __svc_maxrec;
+
+#define        RQCRED_SIZE     400             /* this size is excessive */
+
+#define SVC_VERSQUIET 0x0001           /* keep quiet about vers mismatch */
+#define version_keepquiet(xp) ((u_long)(xp)->xp_p3 & SVC_VERSQUIET)
+
+#define max(a, b) (a > b ? a : b)
+
+/*
+ * The services list
+ * Each entry represents a set of procedures (an rpc program).
+ * The dispatch routine takes request structs and runs the
+ * apropriate procedure.
+ */
+static struct svc_callout {
+       struct svc_callout *sc_next;
+       rpcprog_t           sc_prog;
+       rpcvers_t           sc_vers;
+       char               *sc_netid;
+       void                (*sc_dispatch) __P((struct svc_req *, SVCXPRT *));
+} *svc_head;
+
+#ifdef _REENTRANT
+extern rwlock_t svc_lock;
+extern rwlock_t svc_fd_lock;
+#endif
+
+static struct svc_callout *svc_find __P((rpcprog_t, rpcvers_t,
+                                        struct svc_callout **, char *));
+static void __xprt_do_unregister __P((SVCXPRT *xprt, bool_t dolock));
+
+/* ***************  SVCXPRT related stuff **************** */
+
+/*
+ * Activate a transport handle.
+ */
+void
+xprt_register(xprt)
+       SVCXPRT *xprt;
+{
+       int sock;
+
+       _DIAGASSERT(xprt != NULL);
+
+       sock = xprt->xp_fd;
+
+       rwlock_wrlock(&svc_fd_lock);
+       if (__svc_xports == NULL) {
+               __svc_xports = mem_alloc(FD_SETSIZE * sizeof(SVCXPRT *));
+               if (__svc_xports == NULL) {
+                       warn("xprt_register");
+                       goto out;
+               }
+               memset(__svc_xports, '\0', FD_SETSIZE * sizeof(SVCXPRT *));
+       }
+       if (sock < FD_SETSIZE) {
+               __svc_xports[sock] = xprt;
+               FD_SET(sock, &svc_fdset);
+               svc_maxfd = max(svc_maxfd, sock);
+       }
+out:
+       rwlock_unlock(&svc_fd_lock);
+}
+
+void
+xprt_unregister(SVCXPRT *xprt)
+{
+       __xprt_do_unregister(xprt, TRUE);
+}
+
+void
+__xprt_unregister_unlocked(SVCXPRT *xprt)
+{
+       __xprt_do_unregister(xprt, FALSE);
+}
+
+/*
+ * De-activate a transport handle. 
+ */
+static void
+__xprt_do_unregister(xprt, dolock)
+       SVCXPRT *xprt;
+       bool_t dolock;
+{ 
+       int sock;
+
+       _DIAGASSERT(xprt != NULL);
+
+       sock = xprt->xp_fd;
+
+       if (dolock)
+               rwlock_wrlock(&svc_fd_lock);
+       if ((sock < FD_SETSIZE) && (__svc_xports[sock] == xprt)) {
+               __svc_xports[sock] = NULL;
+               FD_CLR(sock, &svc_fdset);
+               if (sock >= svc_maxfd) {
+                       for (svc_maxfd--; svc_maxfd>=0; svc_maxfd--)
+                               if (__svc_xports[svc_maxfd])
+                                       break;
+               }
+       }
+       if (dolock)
+               rwlock_unlock(&svc_fd_lock);
+}
+
+/*
+ * Add a service program to the callout list.
+ * The dispatch routine will be called when a rpc request for this
+ * program number comes in.
+ */
+bool_t
+svc_reg(xprt, prog, vers, dispatch, nconf)
+       SVCXPRT *xprt;
+       const rpcprog_t prog;
+       const rpcvers_t vers;
+       void (*dispatch) __P((struct svc_req *, SVCXPRT *));
+       const struct netconfig *nconf;
+{
+       bool_t dummy;
+       struct svc_callout *prev;
+       struct svc_callout *s;
+       struct netconfig *tnconf;
+       char *netid = NULL;
+       int flag = 0;
+
+       _DIAGASSERT(xprt != NULL);
+       /* XXX: dispatch may be NULL ??? */
+
+/* VARIABLES PROTECTED BY svc_lock: s, prev, svc_head */
+
+       if (xprt->xp_netid) {
+               netid = strdup(xprt->xp_netid);
+               flag = 1;
+       } else if (nconf && nconf->nc_netid) {
+               netid = strdup(nconf->nc_netid);
+               flag = 1;
+       } else if ((tnconf = __rpcgettp(xprt->xp_fd)) != NULL) {
+               netid = strdup(tnconf->nc_netid);
+               flag = 1;
+               freenetconfigent(tnconf);
+       } /* must have been created with svc_raw_create */
+       if ((netid == NULL) && (flag == 1)) {
+               return (FALSE);
+       }
+
+       rwlock_wrlock(&svc_lock);
+       if ((s = svc_find(prog, vers, &prev, netid)) != NULL) {
+               if (netid)
+                       free(netid);
+               if (s->sc_dispatch == dispatch)
+                       goto rpcb_it; /* he is registering another xptr */
+               rwlock_unlock(&svc_lock);
+               return (FALSE);
+       }
+       s = mem_alloc(sizeof (struct svc_callout));
+       if (s == NULL) {
+               if (netid)
+                       free(netid);
+               rwlock_unlock(&svc_lock);
+               return (FALSE);
+       }
+
+       if ((xprt->xp_netid == NULL) && (flag == 1) && netid)
+               if ((((SVCXPRT *) xprt)->xp_netid = strdup(netid)) == NULL) {
+                       warn("svc_reg");
+                       mem_free(s, sizeof(struct svc_callout));
+                       rwlock_unlock(&svc_lock);
+                       return FALSE;
+               }
+
+       s->sc_prog = prog;
+       s->sc_vers = vers;
+       s->sc_dispatch = dispatch;
+       s->sc_netid = netid;
+       s->sc_next = svc_head;
+       svc_head = s;
+
+rpcb_it:
+       rwlock_unlock(&svc_lock);
+       /* now register the information with the local binder service */
+       if (nconf) {
+               dummy = rpcb_set(prog, vers, __UNCONST(nconf),
+               &((SVCXPRT *) xprt)->xp_ltaddr);
+               return (dummy);
+       }
+       return (TRUE);
+}
+
+/*
+ * Remove a service program from the callout list.
+ */
+void
+svc_unreg(prog, vers)
+       const rpcprog_t prog;
+       const rpcvers_t vers;
+{
+       struct svc_callout *prev;
+       struct svc_callout *s;
+
+       /* unregister the information anyway */
+       (void) rpcb_unset(prog, vers, NULL);
+       rwlock_wrlock(&svc_lock);
+       while ((s = svc_find(prog, vers, &prev, NULL)) != NULL) {
+               if (prev == NULL) {
+                       svc_head = s->sc_next;
+               } else {
+                       prev->sc_next = s->sc_next;
+               }
+               s->sc_next = NULL;
+               if (s->sc_netid)
+                       mem_free(s->sc_netid, sizeof (s->sc_netid) + 1);
+               mem_free(s, sizeof (struct svc_callout));
+       }
+       rwlock_unlock(&svc_lock);
+}
+
+/* ********************** CALLOUT list related stuff ************* */
+
+#ifdef PORTMAP
+/*
+ * Add a service program to the callout list.
+ * The dispatch routine will be called when a rpc request for this
+ * program number comes in.
+ */
+bool_t
+svc_register(xprt, prog, vers, dispatch, protocol)
+       SVCXPRT *xprt;
+       u_long prog;
+       u_long vers;
+       void (*dispatch) __P((struct svc_req *, SVCXPRT *));
+       int protocol;
+{
+       struct svc_callout *prev;
+       struct svc_callout *s;
+
+       _DIAGASSERT(xprt != NULL);
+       _DIAGASSERT(dispatch != NULL);
+
+       if ((s = svc_find((rpcprog_t)prog, (rpcvers_t)vers, &prev, NULL)) !=
+           NULL) {
+               if (s->sc_dispatch == dispatch)
+                       goto pmap_it;  /* he is registering another xptr */
+               return (FALSE);
+       }
+       s = mem_alloc(sizeof(struct svc_callout));
+       if (s == NULL) {
+               return (FALSE);
+       }
+       s->sc_prog = (rpcprog_t)prog;
+       s->sc_vers = (rpcvers_t)vers;
+       s->sc_dispatch = dispatch;
+       s->sc_next = svc_head;
+       svc_head = s;
+pmap_it:
+       /* now register the information with the local binder service */
+       if (protocol) {
+               return (pmap_set(prog, vers, protocol, xprt->xp_port));
+       }
+       return (TRUE);
+}
+
+/*
+ * Remove a service program from the callout list.
+ */
+void
+svc_unregister(prog, vers)
+       u_long prog;
+       u_long vers;
+{
+       struct svc_callout *prev;
+       struct svc_callout *s;
+
+       if ((s = svc_find((rpcprog_t)prog, (rpcvers_t)vers, &prev, NULL)) ==
+           NULL)
+               return;
+       if (prev == NULL) {
+               svc_head = s->sc_next;
+       } else {
+               prev->sc_next = s->sc_next;
+       }
+       s->sc_next = NULL;
+       mem_free(s, sizeof(struct svc_callout));
+       /* now unregister the information with the local binder service */
+       (void)pmap_unset(prog, vers);
+}
+#endif /* PORTMAP */
+
+/*
+ * Search the callout list for a program number, return the callout
+ * struct.
+ */
+static struct svc_callout *
+svc_find(prog, vers, prev, netid)
+       rpcprog_t prog;
+       rpcvers_t vers;
+       struct svc_callout **prev;
+       char *netid;
+{
+       struct svc_callout *s, *p;
+
+       _DIAGASSERT(prev != NULL);
+       /* netid is handled below */
+
+       p = NULL;
+       for (s = svc_head; s != NULL; s = s->sc_next) {
+               if (((s->sc_prog == prog) && (s->sc_vers == vers)) &&
+                   ((netid == NULL) || (s->sc_netid == NULL) ||
+                   (strcmp(netid, s->sc_netid) == 0)))
+                       break;
+               p = s;
+       }
+       *prev = p;
+       return (s);
+}
+
+/* ******************* REPLY GENERATION ROUTINES  ************ */
+
+/*
+ * Send a reply to an rpc request
+ */
+bool_t
+svc_sendreply(xprt, xdr_results, xdr_location)
+       SVCXPRT *xprt;
+       xdrproc_t xdr_results;
+       const char *xdr_location;
+{
+       struct rpc_msg rply; 
+
+       _DIAGASSERT(xprt != NULL);
+
+       rply.rm_direction = REPLY;  
+       rply.rm_reply.rp_stat = MSG_ACCEPTED; 
+       rply.acpted_rply.ar_verf = xprt->xp_verf; 
+       rply.acpted_rply.ar_stat = SUCCESS;
+       rply.acpted_rply.ar_results.where = xdr_location;
+       rply.acpted_rply.ar_results.proc = xdr_results;
+       return (SVC_REPLY(xprt, &rply)); 
+}
+
+/*
+ * No procedure error reply
+ */
+void
+svcerr_noproc(xprt)
+       SVCXPRT *xprt;
+{
+       struct rpc_msg rply;
+
+       _DIAGASSERT(xprt != NULL);
+
+       rply.rm_direction = REPLY;
+       rply.rm_reply.rp_stat = MSG_ACCEPTED;
+       rply.acpted_rply.ar_verf = xprt->xp_verf;
+       rply.acpted_rply.ar_stat = PROC_UNAVAIL;
+       SVC_REPLY(xprt, &rply);
+}
+
+/*
+ * Can't decode args error reply
+ */
+void
+svcerr_decode(xprt)
+       SVCXPRT *xprt;
+{
+       struct rpc_msg rply; 
+
+       _DIAGASSERT(xprt != NULL);
+
+       rply.rm_direction = REPLY; 
+       rply.rm_reply.rp_stat = MSG_ACCEPTED; 
+       rply.acpted_rply.ar_verf = xprt->xp_verf;
+       rply.acpted_rply.ar_stat = GARBAGE_ARGS;
+       SVC_REPLY(xprt, &rply); 
+}
+
+/*
+ * Some system error
+ */
+void
+svcerr_systemerr(xprt)
+       SVCXPRT *xprt;
+{
+       struct rpc_msg rply; 
+
+       _DIAGASSERT(xprt != NULL);
+
+       rply.rm_direction = REPLY; 
+       rply.rm_reply.rp_stat = MSG_ACCEPTED; 
+       rply.acpted_rply.ar_verf = xprt->xp_verf;
+       rply.acpted_rply.ar_stat = SYSTEM_ERR;
+       SVC_REPLY(xprt, &rply); 
+}
+
+#if 0
+/*
+ * Tell RPC package to not complain about version errors to the client.         This
+ * is useful when revving broadcast protocols that sit on a fixed address.
+ * There is really one (or should be only one) example of this kind of
+ * protocol: the portmapper (or rpc binder).
+ */
+void
+__svc_versquiet_on(xprt)
+       SVCXPRT *xprt;
+{
+       u_long  tmp;
+
+       _DIAGASSERT(xprt != NULL);
+
+       tmp = ((u_long) xprt->xp_p3) | SVC_VERSQUIET;
+       xprt->xp_p3 = (caddr_t) tmp;
+}
+
+void
+__svc_versquiet_off(xprt)
+       SVCXPRT *xprt;
+{
+       u_long  tmp;
+
+       _DIAGASSERT(xprt != NULL);
+
+       tmp = ((u_long) xprt->xp_p3) & ~SVC_VERSQUIET;
+       xprt->xp_p3 = (caddr_t) tmp;
+}
+
+void
+svc_versquiet(xprt)
+       SVCXPRT *xprt;
+{
+       __svc_versquiet_on(xprt);
+}
+
+int
+__svc_versquiet_get(xprt)
+       SVCXPRT *xprt;
+{
+
+       _DIAGASSERT(xprt != NULL);
+
+       return ((int) xprt->xp_p3) & SVC_VERSQUIET;
+}
+#endif
+
+/*
+ * Authentication error reply
+ */
+void
+svcerr_auth(xprt, why)
+       SVCXPRT *xprt;
+       enum auth_stat why;
+{
+       struct rpc_msg rply;
+
+       _DIAGASSERT(xprt != NULL);
+
+       rply.rm_direction = REPLY;
+       rply.rm_reply.rp_stat = MSG_DENIED;
+       rply.rjcted_rply.rj_stat = AUTH_ERROR;
+       rply.rjcted_rply.rj_why = why;
+       SVC_REPLY(xprt, &rply);
+}
+
+/*
+ * Auth too weak error reply
+ */
+void
+svcerr_weakauth(xprt)
+       SVCXPRT *xprt;
+{
+
+       _DIAGASSERT(xprt != NULL);
+
+       svcerr_auth(xprt, AUTH_TOOWEAK);
+}
+
+/*
+ * Program unavailable error reply
+ */
+void 
+svcerr_noprog(xprt)
+       SVCXPRT *xprt;
+{
+       struct rpc_msg rply;  
+
+       _DIAGASSERT(xprt != NULL);
+
+       rply.rm_direction = REPLY;   
+       rply.rm_reply.rp_stat = MSG_ACCEPTED;  
+       rply.acpted_rply.ar_verf = xprt->xp_verf;  
+       rply.acpted_rply.ar_stat = PROG_UNAVAIL;
+       SVC_REPLY(xprt, &rply);
+}
+
+/*
+ * Program version mismatch error reply
+ */
+void  
+svcerr_progvers(xprt, low_vers, high_vers)
+       SVCXPRT *xprt; 
+       rpcvers_t low_vers;
+       rpcvers_t high_vers;
+{
+       struct rpc_msg rply;
+
+       _DIAGASSERT(xprt != NULL);
+
+       rply.rm_direction = REPLY;
+       rply.rm_reply.rp_stat = MSG_ACCEPTED;
+       rply.acpted_rply.ar_verf = xprt->xp_verf;
+       rply.acpted_rply.ar_stat = PROG_MISMATCH;
+       rply.acpted_rply.ar_vers.low = (u_int32_t)low_vers;
+       rply.acpted_rply.ar_vers.high = (u_int32_t)high_vers;
+       SVC_REPLY(xprt, &rply);
+}
+
+/* ******************* SERVER INPUT STUFF ******************* */
+
+/*
+ * Get server side input from some transport.
+ *
+ * Statement of authentication parameters management:
+ * This function owns and manages all authentication parameters, specifically
+ * the "raw" parameters (msg.rm_call.cb_cred and msg.rm_call.cb_verf) and
+ * the "cooked" credentials (rqst->rq_clntcred).
+ * However, this function does not know the structure of the cooked
+ * credentials, so it make the following assumptions: 
+ *   a) the structure is contiguous (no pointers), and
+ *   b) the cred structure size does not exceed RQCRED_SIZE bytes. 
+ * In all events, all three parameters are freed upon exit from this routine.
+ * The storage is trivially management on the call stack in user land, but
+ * is mallocated in kernel land.
+ */
+
+void
+svc_getreq(rdfds)
+       int rdfds;
+{
+       fd_set readfds;
+
+       FD_ZERO(&readfds);
+       readfds.fds_bits[0] = (unsigned int)rdfds;
+       svc_getreqset(&readfds);
+}
+
+void
+svc_getreqset(readfds)
+       fd_set *readfds;
+{
+       uint32_t mask, *maskp;
+       int sock, bit, fd;
+
+       _DIAGASSERT(readfds != NULL);
+
+       maskp = readfds->fds_bits;
+       for (sock = 0; sock < FD_SETSIZE; sock += NFDBITS) {
+           for (mask = *maskp++; (bit = ffs((int)mask)) != 0;
+               mask ^= (1 << (bit - 1))) {
+               /* sock has input waiting */
+               fd = sock + bit - 1;
+               svc_getreq_common(fd);
+           }
+       }
+}
+
+void
+svc_getreq_common(fd)
+       int fd;
+{
+       SVCXPRT *xprt;
+       struct svc_req r;
+       struct rpc_msg msg;
+       int prog_found;
+       rpcvers_t low_vers;
+       rpcvers_t high_vers;
+       enum xprt_stat stat;
+       char cred_area[2*MAX_AUTH_BYTES + RQCRED_SIZE];
+
+       msg.rm_call.cb_cred.oa_base = cred_area;
+       msg.rm_call.cb_verf.oa_base = &(cred_area[MAX_AUTH_BYTES]);
+       r.rq_clntcred = &(cred_area[2*MAX_AUTH_BYTES]);
+
+       rwlock_rdlock(&svc_fd_lock);
+       xprt = __svc_xports[fd];
+       rwlock_unlock(&svc_fd_lock);
+       if (xprt == NULL)
+               /* But do we control sock? */
+               return;
+       /* now receive msgs from xprtprt (support batch calls) */
+       do {
+               if (SVC_RECV(xprt, &msg)) {
+
+                       /* now find the exported program and call it */
+                       struct svc_callout *s;
+                       enum auth_stat why;
+
+                       r.rq_xprt = xprt;
+                       r.rq_prog = msg.rm_call.cb_prog;
+                       r.rq_vers = msg.rm_call.cb_vers;
+                       r.rq_proc = msg.rm_call.cb_proc;
+                       r.rq_cred = msg.rm_call.cb_cred;
+                       /* first authenticate the message */
+                       if ((why = _authenticate(&r, &msg)) != AUTH_OK) {
+                               svcerr_auth(xprt, why);
+                               goto call_done;
+                       }
+                       /* now match message with a registered service*/
+                       prog_found = FALSE;
+                       low_vers = (rpcvers_t) -1L;
+                       high_vers = (rpcvers_t) 0L;
+                       for (s = svc_head; s != NULL; s = s->sc_next) {
+                               if (s->sc_prog == r.rq_prog) {
+                                       if (s->sc_vers == r.rq_vers) {
+                                               (*s->sc_dispatch)(&r, xprt);
+                                               goto call_done;
+                                       }  /* found correct version */
+                                       prog_found = TRUE;
+                                       if (s->sc_vers < low_vers)
+                                               low_vers = s->sc_vers;
+                                       if (s->sc_vers > high_vers)
+                                               high_vers = s->sc_vers;
+                               }   /* found correct program */
+                       }
+                       /*
+                        * if we got here, the program or version
+                        * is not served ...
+                        */
+                       if (prog_found)
+                               svcerr_progvers(xprt, low_vers, high_vers);
+                       else
+                                svcerr_noprog(xprt);
+                       /* Fall through to ... */
+               }
+               /*
+                * Check if the xprt has been disconnected in a
+                * recursive call in the service dispatch routine.
+                * If so, then break.
+                */
+               rwlock_rdlock(&svc_fd_lock);
+               if (xprt != __svc_xports[fd]) {
+                       rwlock_unlock(&svc_fd_lock);
+                       break;
+               }
+               rwlock_unlock(&svc_fd_lock);
+call_done:
+               if ((stat = SVC_STAT(xprt)) == XPRT_DIED){
+                       SVC_DESTROY(xprt);
+                       break;
+               }
+       } while (stat == XPRT_MOREREQS);
+}
+
+
+void
+svc_getreq_poll(pfdp, pollretval)
+       struct pollfd   *pfdp;
+       int     pollretval;
+{
+       int i;
+       int fds_found;
+
+       _DIAGASSERT(pfdp != NULL);
+
+       for (i = fds_found = 0; fds_found < pollretval; i++) {
+               struct pollfd *p = &pfdp[i];
+
+               if (p->revents) {
+                       /* fd has input waiting */
+                       fds_found++;
+                       /*
+                        *      We assume that this function is only called
+                        *      via someone select()ing from svc_fdset or
+                        *      pollts()ing from svc_pollset[].  Thus it's safe
+                        *      to handle the POLLNVAL event by simply turning
+                        *      the corresponding bit off in svc_fdset.  The
+                        *      svc_pollset[] array is derived from svc_fdset
+                        *      and so will also be updated eventually.
+                        *
+                        *      XXX Should we do an xprt_unregister() instead?
+                        */
+                       if (p->revents & POLLNVAL) {
+                               rwlock_wrlock(&svc_fd_lock);
+                               FD_CLR(p->fd, &svc_fdset);
+                               rwlock_unlock(&svc_fd_lock);
+                       } else
+                               svc_getreq_common(p->fd);
+               }
+       }
+}
+
+bool_t
+rpc_control(int what, void *arg)
+{
+       int val;
+
+       switch (what) {
+       case RPC_SVC_CONNMAXREC_SET:
+               val = *(int *)arg;
+               if (val <= 0)
+                       return FALSE;
+               __svc_maxrec = val;
+               return TRUE;
+       case RPC_SVC_CONNMAXREC_GET:
+               *(int *)arg = __svc_maxrec;
+               return TRUE;
+       default:
+               break;
+       }
+       return FALSE;
+}
diff --git a/lib/nbsd_libc/rpc/svc_auth.c b/lib/nbsd_libc/rpc/svc_auth.c
new file mode 100644 (file)
index 0000000..e257d79
--- /dev/null
@@ -0,0 +1,226 @@
+/*     $NetBSD: svc_auth.c,v 1.15 2003/09/09 03:56:40 itojun Exp $     */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc. 
+ */
+
+/* #ident      "@(#)svc_auth.c 1.16    94/04/24 SMI" */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)svc_auth.c 1.26 89/02/07 Copyr 1984 Sun Micro";
+#else
+__RCSID("$NetBSD: svc_auth.c,v 1.15 2003/09/09 03:56:40 itojun Exp $");
+#endif
+#endif
+
+/*
+ * svc_auth.c, Server-side rpc authenticator interface.
+ *
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <rpc/rpc.h>
+#include <assert.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(svc_auth_reg,_svc_auth_reg)
+#endif
+
+/*
+ * svcauthsw is the bdevsw of server side authentication.
+ *
+ * Server side authenticators are called from authenticate by
+ * using the client auth struct flavor field to index into svcauthsw.
+ * The server auth flavors must implement a routine that looks
+ * like:
+ *
+ *     enum auth_stat
+ *     flavorx_auth(rqst, msg)
+ *             struct svc_req *rqst;
+ *             struct rpc_msg *msg;
+ *
+ */
+
+/* declarations to allow servers to specify new authentication flavors */
+struct authsvc {
+       int     flavor;
+       enum    auth_stat (*handler) __P((struct svc_req *, struct rpc_msg *));
+       struct  authsvc   *next;
+};
+static struct authsvc *Auths = NULL;
+
+/*
+ * The call rpc message, msg has been obtained from the wire.  The msg contains
+ * the raw form of credentials and verifiers.  authenticate returns AUTH_OK
+ * if the msg is successfully authenticated.  If AUTH_OK then the routine also
+ * does the following things:
+ * set rqst->rq_xprt->verf to the appropriate response verifier;
+ * sets rqst->rq_client_cred to the "cooked" form of the credentials.
+ *
+ * NB: rqst->rq_cxprt->verf must be pre-alloctaed;
+ * its length is set appropriately.
+ *
+ * The caller still owns and is responsible for msg->u.cmb.cred and
+ * msg->u.cmb.verf.  The authentication system retains ownership of
+ * rqst->rq_client_cred, the cooked credentials.
+ *
+ * There is an assumption that any flavour less than AUTH_NULL is
+ * invalid.
+ */
+enum auth_stat
+_authenticate(rqst, msg)
+       struct svc_req *rqst;
+       struct rpc_msg *msg;
+{
+       int cred_flavor;
+       struct authsvc *asp;
+       enum auth_stat dummy;
+#ifdef _REENTRANT
+       extern mutex_t authsvc_lock;
+#endif
+
+       _DIAGASSERT(rqst != NULL);
+       _DIAGASSERT(msg != NULL);
+
+/* VARIABLES PROTECTED BY authsvc_lock: asp, Auths */
+
+       rqst->rq_cred = msg->rm_call.cb_cred;
+       rqst->rq_xprt->xp_verf.oa_flavor = _null_auth.oa_flavor;
+       rqst->rq_xprt->xp_verf.oa_length = 0;
+       cred_flavor = rqst->rq_cred.oa_flavor;
+       switch (cred_flavor) {
+       case AUTH_NULL:
+               dummy = _svcauth_null(rqst, msg);
+               return (dummy);
+       case AUTH_SYS:
+               dummy = _svcauth_unix(rqst, msg);
+               return (dummy);
+       case AUTH_SHORT:
+               dummy = _svcauth_short(rqst, msg);
+               return (dummy);
+#if 0
+       case AUTH_DES:
+               dummy = __svcauth_des(rqst, msg);
+               return (dummy);
+#endif
+       default:
+               break;
+       }
+
+       /* flavor doesn't match any of the builtin types, so try new ones */
+       mutex_lock(&authsvc_lock);
+       for (asp = Auths; asp; asp = asp->next) {
+               if (asp->flavor == cred_flavor) {
+                       enum auth_stat as;
+
+                       as = (*asp->handler)(rqst, msg);
+                       mutex_unlock(&authsvc_lock);
+                       return (as);
+               }
+       }
+       mutex_unlock(&authsvc_lock);
+
+       return (AUTH_REJECTEDCRED);
+}
+
+/*ARGSUSED*/
+enum auth_stat
+_svcauth_null(rqst, msg)
+       struct svc_req *rqst;
+       struct rpc_msg *msg;
+{
+       return (AUTH_OK);
+}
+
+/*
+ *  Allow the rpc service to register new authentication types that it is
+ *  prepared to handle.  When an authentication flavor is registered,
+ *  the flavor is checked against already registered values.  If not
+ *  registered, then a new Auths entry is added on the list.
+ *
+ *  There is no provision to delete a registration once registered.
+ *
+ *  This routine returns:
+ *      0 if registration successful
+ *      1 if flavor already registered
+ *     -1 if can't register (errno set)
+ */
+
+int
+svc_auth_reg(cred_flavor, handler)
+       int cred_flavor;
+       enum auth_stat (*handler) __P((struct svc_req *, struct rpc_msg *));
+{
+       struct authsvc *asp;
+#ifdef _REENTRANT
+       extern mutex_t authsvc_lock;
+#endif
+
+       switch (cred_flavor) {
+           case AUTH_NULL:
+           case AUTH_SYS:
+           case AUTH_SHORT:
+#if 0
+           case AUTH_DES:
+#endif
+               /* already registered */
+               return (1);
+
+           default:
+               mutex_lock(&authsvc_lock);
+               for (asp = Auths; asp; asp = asp->next) {
+                       if (asp->flavor == cred_flavor) {
+                               /* already registered */
+                               mutex_unlock(&authsvc_lock);
+                               return (1);
+                       }
+               }
+
+               /* this is a new one, so go ahead and register it */
+               asp = mem_alloc(sizeof (*asp));
+               if (asp == NULL) {
+                       mutex_unlock(&authsvc_lock);
+                       return (-1);
+               }
+               asp->flavor = cred_flavor;
+               asp->handler = handler;
+               asp->next = Auths;
+               Auths = asp;
+               mutex_unlock(&authsvc_lock);
+               break;
+       }
+       return (0);
+}
diff --git a/lib/nbsd_libc/rpc/svc_auth_unix.c b/lib/nbsd_libc/rpc/svc_auth_unix.c
new file mode 100644 (file)
index 0000000..c454657
--- /dev/null
@@ -0,0 +1,149 @@
+/*     $NetBSD: svc_auth_unix.c,v 1.18 2003/01/18 11:29:06 thorpej Exp $       */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)svc_auth_unix.c 1.28 88/02/08 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)svc_auth_unix.c     2.3 88/08/01 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: svc_auth_unix.c,v 1.18 2003/01/18 11:29:06 thorpej Exp $");
+#endif
+#endif
+
+/*
+ * svc_auth_unix.c
+ * Handles UNIX flavor authentication parameters on the service side of rpc.
+ * There are two svc auth implementations here: AUTH_UNIX and AUTH_SHORT.
+ * _svcauth_unix does full blown unix style uid,gid+gids auth,
+ * _svcauth_short uses a shorthand auth to index into a cache of longhand auths.
+ * Note: the shorthand has been gutted for efficiency.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <rpc/rpc.h>
+
+/*
+ * Unix longhand authenticator
+ */
+enum auth_stat
+_svcauth_unix(rqst, msg)
+       struct svc_req *rqst;
+       struct rpc_msg *msg;
+{
+       enum auth_stat stat;
+       XDR xdrs;
+       struct authunix_parms *aup;
+       int32_t *buf;
+       struct area {
+               struct authunix_parms area_aup;
+               char area_machname[MAX_MACHINE_NAME+1];
+               int area_gids[NGRPS];
+       } *area;
+       u_int auth_len;
+       size_t str_len, gid_len, i;
+
+       _DIAGASSERT(rqst != NULL);
+       _DIAGASSERT(msg != NULL);
+
+       area = (struct area *) rqst->rq_clntcred;
+       aup = &area->area_aup;
+       aup->aup_machname = area->area_machname;
+       aup->aup_gids = area->area_gids;
+       auth_len = (u_int)msg->rm_call.cb_cred.oa_length;
+       xdrmem_create(&xdrs, msg->rm_call.cb_cred.oa_base, auth_len,XDR_DECODE);
+       buf = XDR_INLINE(&xdrs, auth_len);
+       if (buf != NULL) {
+               aup->aup_time = IXDR_GET_INT32(buf);
+               str_len = (size_t)IXDR_GET_U_INT32(buf);
+               if (str_len > MAX_MACHINE_NAME) {
+                       stat = AUTH_BADCRED;
+                       goto done;
+               }
+               memmove(aup->aup_machname, buf, str_len);
+               aup->aup_machname[str_len] = 0;
+               str_len = RNDUP(str_len);
+               buf += str_len / sizeof (int32_t);
+               aup->aup_uid = (int)IXDR_GET_INT32(buf);
+               aup->aup_gid = (int)IXDR_GET_INT32(buf);
+               gid_len = (size_t)IXDR_GET_U_INT32(buf);
+               if (gid_len > NGRPS) {
+                       stat = AUTH_BADCRED;
+                       goto done;
+               }
+               aup->aup_len = gid_len;
+               for (i = 0; i < gid_len; i++) {
+                       aup->aup_gids[i] = (int)IXDR_GET_INT32(buf);
+               }
+               /*
+                * five is the smallest unix credentials structure -
+                * timestamp, hostname len (0), uid, gid, and gids len (0).
+                */
+               if ((5 + gid_len) * BYTES_PER_XDR_UNIT + str_len > auth_len) {
+                       (void) printf("bad auth_len gid %ld str %ld auth %u\n",
+                           (long)gid_len, (long)str_len, auth_len);
+                       stat = AUTH_BADCRED;
+                       goto done;
+               }
+       } else if (! xdr_authunix_parms(&xdrs, aup)) {
+               xdrs.x_op = XDR_FREE;
+               (void)xdr_authunix_parms(&xdrs, aup);
+               stat = AUTH_BADCRED;
+               goto done;
+       }
+       rqst->rq_xprt->xp_verf.oa_flavor = AUTH_NULL;
+       rqst->rq_xprt->xp_verf.oa_length = 0;
+       stat = AUTH_OK;
+done:
+       XDR_DESTROY(&xdrs);
+       return (stat);
+}
+
+
+/*
+ * Shorthand unix authenticator
+ * Looks up longhand in a cache.
+ */
+/*ARGSUSED*/
+enum auth_stat 
+_svcauth_short(rqst, msg)
+       struct svc_req *rqst;
+       struct rpc_msg *msg;
+{
+       return (AUTH_REJECTEDCRED);
+}
diff --git a/lib/nbsd_libc/rpc/svc_dg.c b/lib/nbsd_libc/rpc/svc_dg.c
new file mode 100644 (file)
index 0000000..14f19f7
--- /dev/null
@@ -0,0 +1,652 @@
+/*     $NetBSD: svc_dg.c,v 1.12 2008/04/25 17:44:44 christos Exp $     */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc.
+ */
+
+/* #ident      "@(#)svc_dg.c   1.17    94/04/24 SMI" */
+
+
+/*
+ * svc_dg.c, Server side for connectionless RPC.
+ *
+ * Does some caching in the hopes of achieving execute-at-most-once semantics.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: svc_dg.c,v 1.12 2008/04/25 17:44:44 christos Exp $");
+#endif
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <rpc/rpc.h>
+#include <assert.h>
+#include <errno.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef RPC_CACHE_DEBUG
+#include <netconfig.h>
+#include <netdir.h>
+#endif
+#include <err.h>
+
+#include "rpc_internal.h"
+#include "svc_dg.h"
+
+#define        su_data(xprt)   ((struct svc_dg_data *)(xprt->xp_p2))
+#define        rpc_buffer(xprt) ((xprt)->xp_p1)
+
+#ifdef __weak_alias
+__weak_alias(svc_dg_create,_svc_dg_create)
+#endif
+
+#ifndef MAX
+#define        MAX(a, b)       (((a) > (b)) ? (a) : (b))
+#endif
+
+static void svc_dg_ops __P((SVCXPRT *));
+static enum xprt_stat svc_dg_stat __P((SVCXPRT *));
+static bool_t svc_dg_recv __P((SVCXPRT *, struct rpc_msg *));
+static bool_t svc_dg_reply __P((SVCXPRT *, struct rpc_msg *));
+static bool_t svc_dg_getargs __P((SVCXPRT *, xdrproc_t, caddr_t));
+static bool_t svc_dg_freeargs __P((SVCXPRT *, xdrproc_t, caddr_t));
+static void svc_dg_destroy __P((SVCXPRT *));
+static bool_t svc_dg_control __P((SVCXPRT *, const u_int, void *));
+static int cache_get __P((SVCXPRT *, struct rpc_msg *, char **, size_t *));
+static void cache_set __P((SVCXPRT *, size_t));
+
+/*
+ * Usage:
+ *     xprt = svc_dg_create(sock, sendsize, recvsize);
+ * Does other connectionless specific initializations.
+ * Once *xprt is initialized, it is registered.
+ * see (svc.h, xprt_register). If recvsize or sendsize are 0 suitable
+ * system defaults are chosen.
+ * The routines returns NULL if a problem occurred.
+ */
+static const char svc_dg_str[] = "svc_dg_create: %s";
+static const char svc_dg_err1[] = "could not get transport information";
+static const char svc_dg_err2[] = " transport does not support data transfer";
+static const char __no_mem_str[] = "out of memory";
+
+SVCXPRT *
+svc_dg_create(fd, sendsize, recvsize)
+       int fd;
+       u_int sendsize;
+       u_int recvsize;
+{
+       SVCXPRT *xprt;
+       struct svc_dg_data *su = NULL;
+       struct __rpc_sockinfo si;
+       struct sockaddr_storage ss;
+       socklen_t slen;
+
+       if (!__rpc_fd2sockinfo(fd, &si)) {
+               warnx(svc_dg_str, svc_dg_err1);
+               return (NULL);
+       }
+       /*
+        * Find the receive and the send size
+        */
+       sendsize = __rpc_get_t_size(si.si_af, si.si_proto, (int)sendsize);
+       recvsize = __rpc_get_t_size(si.si_af, si.si_proto, (int)recvsize);
+       if ((sendsize == 0) || (recvsize == 0)) {
+               warnx(svc_dg_str, svc_dg_err2);
+               return (NULL);
+       }
+
+       xprt = mem_alloc(sizeof (SVCXPRT));
+       if (xprt == NULL)
+               goto freedata;
+       memset(xprt, 0, sizeof (SVCXPRT));
+
+       su = mem_alloc(sizeof (*su));
+       if (su == NULL)
+               goto freedata;
+       su->su_iosz = ((MAX(sendsize, recvsize) + 3) / 4) * 4;
+       if ((rpc_buffer(xprt) = malloc(su->su_iosz)) == NULL)
+               goto freedata;
+       xdrmem_create(&(su->su_xdrs), rpc_buffer(xprt), su->su_iosz,
+               XDR_DECODE);
+       su->su_cache = NULL;
+       xprt->xp_fd = fd;
+       xprt->xp_p2 = (caddr_t)(void *)su;
+       xprt->xp_verf.oa_base = su->su_verfbody;
+       svc_dg_ops(xprt);
+       xprt->xp_rtaddr.maxlen = sizeof (struct sockaddr_storage);
+
+       slen = sizeof ss;
+       if (getsockname(fd, (struct sockaddr *)(void *)&ss, &slen) < 0)
+               goto freedata;
+       xprt->xp_ltaddr.buf = mem_alloc(sizeof (struct sockaddr_storage));
+       xprt->xp_ltaddr.maxlen = sizeof (struct sockaddr_storage);
+       xprt->xp_ltaddr.len = slen;
+       memcpy(xprt->xp_ltaddr.buf, &ss, slen);
+
+       xprt_register(xprt);
+       return (xprt);
+freedata:
+       (void) warnx(svc_dg_str, __no_mem_str);
+       if (xprt) {
+               if (su)
+                       (void) mem_free(su, sizeof (*su));
+               (void) mem_free(xprt, sizeof (SVCXPRT));
+       }
+       return (NULL);
+}
+
+/*ARGSUSED*/
+static enum xprt_stat
+svc_dg_stat(xprt)
+       SVCXPRT *xprt;
+{
+       return (XPRT_IDLE);
+}
+
+static bool_t
+svc_dg_recv(xprt, msg)
+       SVCXPRT *xprt;
+       struct rpc_msg *msg;
+{
+       struct svc_dg_data *su;
+       XDR *xdrs;
+       char *reply;
+       struct sockaddr_storage ss;
+       socklen_t alen;
+       size_t replylen;
+       ssize_t rlen;
+
+       _DIAGASSERT(xprt != NULL);
+       _DIAGASSERT(msg != NULL);
+
+       su = su_data(xprt);
+       xdrs = &(su->su_xdrs);
+
+again:
+       alen = sizeof (struct sockaddr_storage);
+       rlen = recvfrom(xprt->xp_fd, rpc_buffer(xprt), su->su_iosz, 0,
+           (struct sockaddr *)(void *)&ss, &alen);
+       if (rlen == -1 && errno == EINTR)
+               goto again;
+       if (rlen == -1 || (rlen < (ssize_t)(4 * sizeof (u_int32_t))))
+               return (FALSE);
+       if (xprt->xp_rtaddr.len < alen) {
+               if (xprt->xp_rtaddr.len != 0)
+                       mem_free(xprt->xp_rtaddr.buf, xprt->xp_rtaddr.len);
+               xprt->xp_rtaddr.buf = mem_alloc(alen);
+               xprt->xp_rtaddr.len = alen;
+       }
+       memcpy(xprt->xp_rtaddr.buf, &ss, alen);
+#ifdef PORTMAP
+       if (ss.ss_family == AF_INET) {
+               xprt->xp_raddr = *(struct sockaddr_in *)xprt->xp_rtaddr.buf;
+               xprt->xp_addrlen = sizeof (struct sockaddr_in);
+       }
+#endif
+       xdrs->x_op = XDR_DECODE;
+       XDR_SETPOS(xdrs, 0);
+       if (! xdr_callmsg(xdrs, msg)) {
+               return (FALSE);
+       }
+       su->su_xid = msg->rm_xid;
+       if (su->su_cache != NULL) {
+               if (cache_get(xprt, msg, &reply, &replylen)) {
+                       (void)sendto(xprt->xp_fd, reply, replylen, 0,
+                           (struct sockaddr *)(void *)&ss, alen);
+                       return (FALSE);
+               }
+       }
+       return (TRUE);
+}
+
+static bool_t
+svc_dg_reply(xprt, msg)
+       SVCXPRT *xprt;
+       struct rpc_msg *msg;
+{
+       struct svc_dg_data *su;
+       XDR *xdrs;
+       bool_t stat = FALSE;
+       size_t slen;
+
+       _DIAGASSERT(xprt != NULL);
+       _DIAGASSERT(msg != NULL);
+
+       su = su_data(xprt);
+       xdrs = &(su->su_xdrs);
+
+       xdrs->x_op = XDR_ENCODE;
+       XDR_SETPOS(xdrs, 0);
+       msg->rm_xid = su->su_xid;
+       if (xdr_replymsg(xdrs, msg)) {
+               slen = XDR_GETPOS(xdrs);
+               if (sendto(xprt->xp_fd, rpc_buffer(xprt), slen, 0,
+                   (struct sockaddr *)xprt->xp_rtaddr.buf,
+                   (socklen_t)xprt->xp_rtaddr.len) == (ssize_t) slen) {
+                       stat = TRUE;
+                       if (su->su_cache)
+                               cache_set(xprt, slen);
+               }
+       }
+       return (stat);
+}
+
+static bool_t
+svc_dg_getargs(xprt, xdr_args, args_ptr)
+       SVCXPRT *xprt;
+       xdrproc_t xdr_args;
+       caddr_t args_ptr;
+{
+       return (*xdr_args)(&(su_data(xprt)->su_xdrs), args_ptr);
+}
+
+static bool_t
+svc_dg_freeargs(xprt, xdr_args, args_ptr)
+       SVCXPRT *xprt;
+       xdrproc_t xdr_args;
+       caddr_t args_ptr;
+{
+       XDR *xdrs;
+
+       _DIAGASSERT(xprt != NULL);
+
+       xdrs = &(su_data(xprt)->su_xdrs);
+       xdrs->x_op = XDR_FREE;
+       return (*xdr_args)(xdrs, args_ptr);
+}
+
+static void
+svc_dg_destroy(xprt)
+       SVCXPRT *xprt;
+{
+       struct svc_dg_data *su;
+
+       _DIAGASSERT(xprt != NULL);
+
+       su = su_data(xprt);
+
+       xprt_unregister(xprt);
+       if (xprt->xp_fd != -1)
+               (void)close(xprt->xp_fd);
+       XDR_DESTROY(&(su->su_xdrs));
+       (void) mem_free(rpc_buffer(xprt), su->su_iosz);
+       (void) mem_free(su, sizeof (*su));
+       if (xprt->xp_rtaddr.buf)
+               (void) mem_free(xprt->xp_rtaddr.buf, xprt->xp_rtaddr.maxlen);
+       if (xprt->xp_ltaddr.buf)
+               (void) mem_free(xprt->xp_ltaddr.buf, xprt->xp_ltaddr.maxlen);
+       if (xprt->xp_tp)
+               (void) free(xprt->xp_tp);
+       (void) mem_free(xprt, sizeof (SVCXPRT));
+}
+
+static bool_t
+/*ARGSUSED*/
+svc_dg_control(xprt, rq, in)
+       SVCXPRT *xprt;
+       const u_int     rq;
+       void            *in;
+{
+       return (FALSE);
+}
+
+static void
+svc_dg_ops(xprt)
+       SVCXPRT *xprt;
+{
+       static struct xp_ops ops;
+       static struct xp_ops2 ops2;
+#ifdef _REENTRANT
+       extern mutex_t ops_lock;
+#endif
+
+       _DIAGASSERT(xprt != NULL);
+
+/* VARIABLES PROTECTED BY ops_lock: ops */
+
+       mutex_lock(&ops_lock);
+       if (ops.xp_recv == NULL) {
+               ops.xp_recv = svc_dg_recv;
+               ops.xp_stat = svc_dg_stat;
+               ops.xp_getargs = svc_dg_getargs;
+               ops.xp_reply = svc_dg_reply;
+               ops.xp_freeargs = svc_dg_freeargs;
+               ops.xp_destroy = svc_dg_destroy;
+               ops2.xp_control = svc_dg_control;
+       }
+       xprt->xp_ops = &ops;
+       xprt->xp_ops2 = &ops2;
+       mutex_unlock(&ops_lock);
+}
+
+/*  The CACHING COMPONENT */
+
+/*
+ * Could have been a separate file, but some part of it depends upon the
+ * private structure of the client handle.
+ *
+ * Fifo cache for cl server
+ * Copies pointers to reply buffers into fifo cache
+ * Buffers are sent again if retransmissions are detected.
+ */
+
+#define        SPARSENESS 4    /* 75% sparse */
+
+#define        ALLOC(type, size)       \
+       mem_alloc((sizeof (type) * (size)))
+
+#define        MEMZERO(addr, type, size)        \
+       (void) memset((void *) (addr), 0, sizeof (type) * (int) (size))
+
+#define        FREE(addr, type, size)  \
+       mem_free((addr), (sizeof (type) * (size)))
+
+/*
+ * An entry in the cache
+ */
+typedef struct cache_node *cache_ptr;
+struct cache_node {
+       /*
+        * Index into cache is xid, proc, vers, prog and address
+        */
+       u_int32_t cache_xid;
+       rpcproc_t cache_proc;
+       rpcvers_t cache_vers;
+       rpcprog_t cache_prog;
+       struct netbuf cache_addr;
+       /*
+        * The cached reply and length
+        */
+       char *cache_reply;
+       size_t cache_replylen;
+       /*
+        * Next node on the list, if there is a collision
+        */
+       cache_ptr cache_next;
+};
+
+/*
+ * The entire cache
+ */
+struct cl_cache {
+       u_int uc_size;          /* size of cache */
+       cache_ptr *uc_entries;  /* hash table of entries in cache */
+       cache_ptr *uc_fifo;     /* fifo list of entries in cache */
+       u_int uc_nextvictim;    /* points to next victim in fifo list */
+       rpcprog_t uc_prog;      /* saved program number */
+       rpcvers_t uc_vers;      /* saved version number */
+       rpcproc_t uc_proc;      /* saved procedure number */
+};
+
+
+/*
+ * the hashing function
+ */
+#define        CACHE_LOC(transp, xid)  \
+       (xid % (SPARSENESS * ((struct cl_cache *) \
+               su_data(transp)->su_cache)->uc_size))
+
+#ifdef _REENTRANT
+extern mutex_t dupreq_lock;
+#endif
+
+/*
+ * Enable use of the cache. Returns 1 on success, 0 on failure.
+ * Note: there is no disable.
+ */
+static const char cache_enable_str[] = "svc_enablecache: %s %s";
+static const char alloc_err[] = "could not allocate cache ";
+static const char enable_err[] = "cache already enabled";
+
+int
+svc_dg_enablecache(transp, size)
+       SVCXPRT *transp;
+       u_int size;
+{
+       struct svc_dg_data *su;
+       struct cl_cache *uc;
+
+       _DIAGASSERT(transp != NULL);
+
+       su = su_data(transp);
+
+       mutex_lock(&dupreq_lock);
+       if (su->su_cache != NULL) {
+               (void) warnx(cache_enable_str, enable_err, " ");
+               mutex_unlock(&dupreq_lock);
+               return (0);
+       }
+       uc = ALLOC(struct cl_cache, 1);
+       if (uc == NULL) {
+               warnx(cache_enable_str, alloc_err, " ");
+               mutex_unlock(&dupreq_lock);
+               return (0);
+       }
+       uc->uc_size = size;
+       uc->uc_nextvictim = 0;
+       uc->uc_entries = ALLOC(cache_ptr, size * SPARSENESS);
+       if (uc->uc_entries == NULL) {
+               warnx(cache_enable_str, alloc_err, "data");
+               FREE(uc, struct cl_cache, 1);
+               mutex_unlock(&dupreq_lock);
+               return (0);
+       }
+       MEMZERO(uc->uc_entries, cache_ptr, size * SPARSENESS);
+       uc->uc_fifo = ALLOC(cache_ptr, size);
+       if (uc->uc_fifo == NULL) {
+               warnx(cache_enable_str, alloc_err, "fifo");
+               FREE(uc->uc_entries, cache_ptr, size * SPARSENESS);
+               FREE(uc, struct cl_cache, 1);
+               mutex_unlock(&dupreq_lock);
+               return (0);
+       }
+       MEMZERO(uc->uc_fifo, cache_ptr, size);
+       su->su_cache = (char *)(void *)uc;
+       mutex_unlock(&dupreq_lock);
+       return (1);
+}
+
+/*
+ * Set an entry in the cache.  It assumes that the uc entry is set from
+ * the earlier call to cache_get() for the same procedure.  This will always
+ * happen because cache_get() is calle by svc_dg_recv and cache_set() is called
+ * by svc_dg_reply().  All this hoopla because the right RPC parameters are
+ * not available at svc_dg_reply time.
+ */
+
+static const char cache_set_str[] = "cache_set: %s";
+static const char cache_set_err1[] = "victim not found";
+static const char cache_set_err2[] = "victim alloc failed";
+static const char cache_set_err3[] = "could not allocate new rpc buffer";
+
+static void
+cache_set(xprt, replylen)
+       SVCXPRT *xprt;
+       size_t replylen;
+{
+       cache_ptr victim;
+       cache_ptr *vicp;
+       struct svc_dg_data *su;
+       struct cl_cache *uc;
+       u_int loc;
+       char *newbuf;
+#ifdef RPC_CACHE_DEBUG
+       struct netconfig *nconf;
+       char *uaddr;
+#endif
+
+       _DIAGASSERT(xprt != NULL);
+
+       su = su_data(xprt);
+       uc = (struct cl_cache *) su->su_cache;
+
+       mutex_lock(&dupreq_lock);
+       /*
+        * Find space for the new entry, either by
+        * reusing an old entry, or by mallocing a new one
+        */
+       victim = uc->uc_fifo[uc->uc_nextvictim];
+       if (victim != NULL) {
+               loc = CACHE_LOC(xprt, victim->cache_xid);
+               for (vicp = &uc->uc_entries[loc];
+                       *vicp != NULL && *vicp != victim;
+                       vicp = &(*vicp)->cache_next)
+                       ;
+               if (*vicp == NULL) {
+                       warnx(cache_set_str, cache_set_err1);
+                       mutex_unlock(&dupreq_lock);
+                       return;
+               }
+               *vicp = victim->cache_next;     /* remove from cache */
+               newbuf = victim->cache_reply;
+       } else {
+               victim = ALLOC(struct cache_node, 1);
+               if (victim == NULL) {
+                       warnx(cache_set_str, cache_set_err2);
+                       mutex_unlock(&dupreq_lock);
+                       return;
+               }
+               newbuf = mem_alloc(su->su_iosz);
+               if (newbuf == NULL) {
+                       warnx(cache_set_str, cache_set_err3);
+                       FREE(victim, struct cache_node, 1);
+                       mutex_unlock(&dupreq_lock);
+                       return;
+               }
+       }
+
+       /*
+        * Store it away
+        */
+#ifdef RPC_CACHE_DEBUG
+       if (nconf = getnetconfigent(xprt->xp_netid)) {
+               uaddr = taddr2uaddr(nconf, &xprt->xp_rtaddr);
+               freenetconfigent(nconf);
+               printf(
+       "cache set for xid= %x prog=%d vers=%d proc=%d for rmtaddr=%s\n",
+                       su->su_xid, uc->uc_prog, uc->uc_vers,
+                       uc->uc_proc, uaddr);
+               free(uaddr);
+       }
+#endif
+       victim->cache_replylen = replylen;
+       victim->cache_reply = rpc_buffer(xprt);
+       rpc_buffer(xprt) = newbuf;
+       xdrmem_create(&(su->su_xdrs), rpc_buffer(xprt),
+                       su->su_iosz, XDR_ENCODE);
+       victim->cache_xid = su->su_xid;
+       victim->cache_proc = uc->uc_proc;
+       victim->cache_vers = uc->uc_vers;
+       victim->cache_prog = uc->uc_prog;
+       victim->cache_addr = xprt->xp_rtaddr;
+       victim->cache_addr.buf = ALLOC(char, xprt->xp_rtaddr.len);
+       (void) memcpy(victim->cache_addr.buf, xprt->xp_rtaddr.buf,
+           (size_t)xprt->xp_rtaddr.len);
+       loc = CACHE_LOC(xprt, victim->cache_xid);
+       victim->cache_next = uc->uc_entries[loc];
+       uc->uc_entries[loc] = victim;
+       uc->uc_fifo[uc->uc_nextvictim++] = victim;
+       uc->uc_nextvictim %= uc->uc_size;
+       mutex_unlock(&dupreq_lock);
+}
+
+/*
+ * Try to get an entry from the cache
+ * return 1 if found, 0 if not found and set the stage for cache_set()
+ */
+static int
+cache_get(xprt, msg, replyp, replylenp)
+       SVCXPRT *xprt;
+       struct rpc_msg *msg;
+       char **replyp;
+       size_t *replylenp;
+{
+       u_int loc;
+       cache_ptr ent;
+       struct svc_dg_data *su;
+       struct cl_cache *uc;
+#ifdef RPC_CACHE_DEBUG
+       struct netconfig *nconf;
+       char *uaddr;
+#endif
+
+       _DIAGASSERT(xprt != NULL);
+       _DIAGASSERT(msg != NULL);
+       _DIAGASSERT(replyp != NULL);
+       _DIAGASSERT(replylenp != NULL);
+
+       su = su_data(xprt);
+       uc = (struct cl_cache *) su->su_cache;
+
+       mutex_lock(&dupreq_lock);
+       loc = CACHE_LOC(xprt, su->su_xid);
+       for (ent = uc->uc_entries[loc]; ent != NULL; ent = ent->cache_next) {
+               if (ent->cache_xid == su->su_xid &&
+                       ent->cache_proc == msg->rm_call.cb_proc &&
+                       ent->cache_vers == msg->rm_call.cb_vers &&
+                       ent->cache_prog == msg->rm_call.cb_prog &&
+                       ent->cache_addr.len == xprt->xp_rtaddr.len &&
+                       (memcmp(ent->cache_addr.buf, xprt->xp_rtaddr.buf,
+                               xprt->xp_rtaddr.len) == 0)) {
+#ifdef RPC_CACHE_DEBUG
+                       if (nconf = getnetconfigent(xprt->xp_netid)) {
+                               uaddr = taddr2uaddr(nconf, &xprt->xp_rtaddr);
+                               freenetconfigent(nconf);
+                               printf(
+       "cache entry found for xid=%x prog=%d vers=%d proc=%d for rmtaddr=%s\n",
+                                       su->su_xid, msg->rm_call.cb_prog,
+                                       msg->rm_call.cb_vers,
+                                       msg->rm_call.cb_proc, uaddr);
+                               free(uaddr);
+                       }
+#endif
+                       *replyp = ent->cache_reply;
+                       *replylenp = ent->cache_replylen;
+                       mutex_unlock(&dupreq_lock);
+                       return (1);
+               }
+       }
+       /*
+        * Failed to find entry
+        * Remember a few things so we can do a set later
+        */
+       uc->uc_proc = msg->rm_call.cb_proc;
+       uc->uc_vers = msg->rm_call.cb_vers;
+       uc->uc_prog = msg->rm_call.cb_prog;
+       mutex_unlock(&dupreq_lock);
+       return (0);
+}
diff --git a/lib/nbsd_libc/rpc/svc_dg.h b/lib/nbsd_libc/rpc/svc_dg.h
new file mode 100644 (file)
index 0000000..91eb383
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: svc_dg.h,v 1.1 2000/06/02 23:11:16 fvdl Exp $  */
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+/*
+ * XXX - this file exists only so that the rpcbind code can pull it in.
+ * This should go away. It should only be include by svc_dg.c and
+ * rpcb_svc_com.c in the rpcbind code.
+ */
+
+/*
+ * kept in xprt->xp_p2
+ */
+struct svc_dg_data {
+       /* XXX: optbuf should be the first field, used by ti_opts.c code */
+       size_t          su_iosz;                /* size of send.recv buffer */
+       u_int32_t       su_xid;                 /* transaction id */
+       XDR             su_xdrs;                        /* XDR handle */
+       char            su_verfbody[MAX_AUTH_BYTES];    /* verifier body */
+       void            *su_cache;              /* cached data, NULL if none */
+};
+
+#define __rpcb_get_dg_xidp(x)  (&((struct svc_dg_data *)(x)->xp_p2)->su_xid)
diff --git a/lib/nbsd_libc/rpc/svc_generic.c b/lib/nbsd_libc/rpc/svc_generic.c
new file mode 100644 (file)
index 0000000..7235557
--- /dev/null
@@ -0,0 +1,320 @@
+/*     $NetBSD: svc_generic.c,v 1.10 2008/04/25 17:44:44 christos Exp $        */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc.
+ */
+
+/* #ident      "@(#)svc_generic.c      1.19    94/04/24 SMI" */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)svc_generic.c 1.21 89/02/28 Copyr 1988 Sun Micro";
+#else
+__RCSID("$NetBSD: svc_generic.c,v 1.10 2008/04/25 17:44:44 christos Exp $");
+#endif
+#endif
+
+/*
+ * svc_generic.c, Server side for RPC.
+ *
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <rpc/rpc.h>
+#include <rpc/nettype.h>
+#include <stdio.h>
+#include <errno.h>
+#include <malloc.h>
+#include <string.h>
+#include <unistd.h>
+#include <err.h>
+
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(svc_create,_svc_create)
+__weak_alias(svc_tp_create,_svc_tp_create)
+__weak_alias(svc_tli_create,_svc_tli_create)
+#endif
+
+extern int __svc_vc_setflag __P((SVCXPRT *, int));
+
+/*
+ * The highest level interface for server creation.
+ * It tries for all the nettokens in that particular class of token
+ * and returns the number of handles it can create and/or find.
+ *
+ * It creates a link list of all the handles it could create.
+ * If svc_create() is called multiple times, it uses the handle
+ * created earlier instead of creating a new handle every time.
+ */
+int
+svc_create(dispatch, prognum, versnum, nettype)
+       void (*dispatch) __P((struct svc_req *, SVCXPRT *));
+       rpcprog_t prognum;              /* Program number */
+       rpcvers_t versnum;              /* Version number */
+       const char *nettype;            /* Networktype token */
+{
+       struct xlist {
+               SVCXPRT *xprt;          /* Server handle */
+               struct xlist *next;     /* Next item */
+       } *l;
+       static struct xlist *xprtlist;  /* A link list of all the handles */
+       int num = 0;
+       SVCXPRT *xprt;
+       struct netconfig *nconf;
+       void *handle;
+#ifdef _REENTRANT
+       extern mutex_t xprtlist_lock;
+#endif
+
+/* VARIABLES PROTECTED BY xprtlist_lock: xprtlist */
+
+       if ((handle = __rpc_setconf(nettype)) == NULL) {
+               warnx("svc_create: unknown protocol");
+               return (0);
+       }
+       while ((nconf = __rpc_getconf(handle)) != NULL) {
+               mutex_lock(&xprtlist_lock);
+               for (l = xprtlist; l; l = l->next) {
+                       if (strcmp(l->xprt->xp_netid, nconf->nc_netid) == 0) {
+                               /* Found an old one, use it */
+                               (void) rpcb_unset(prognum, versnum, nconf);
+                               if (svc_reg(l->xprt, prognum, versnum,
+                                       dispatch, nconf) == FALSE)
+                                       warnx(
+               "svc_create: could not register prog %u vers %u on %s",
+                                       (unsigned)prognum, (unsigned)versnum,
+                                        nconf->nc_netid);
+                               else
+                                       num++;
+                               break;
+                       }
+               }
+               if (l == NULL) {
+                       /* It was not found. Now create a new one */
+                       xprt = svc_tp_create(dispatch, prognum, versnum, nconf);
+                       if (xprt) {
+                               l = malloc(sizeof(*l));
+                               if (l == NULL) {
+                                       warnx("svc_create: no memory");
+                                       mutex_unlock(&xprtlist_lock);
+                                       return (0);
+                               }
+                               l->xprt = xprt;
+                               l->next = xprtlist;
+                               xprtlist = l;
+                               num++;
+                       }
+               }
+               mutex_unlock(&xprtlist_lock);
+       }
+       __rpc_endconf(handle);
+       /*
+        * In case of num == 0; the error messages are generated by the
+        * underlying layers; and hence not needed here.
+        */
+       return (num);
+}
+
+/*
+ * The high level interface to svc_tli_create().
+ * It tries to create a server for "nconf" and registers the service
+ * with the rpcbind. It calls svc_tli_create();
+ */
+SVCXPRT *
+svc_tp_create(dispatch, prognum, versnum, nconf)
+       void (*dispatch) __P((struct svc_req *, SVCXPRT *));
+       rpcprog_t prognum;              /* Program number */
+       rpcvers_t versnum;              /* Version number */
+       const struct netconfig *nconf; /* Netconfig structure for the network */
+{
+       SVCXPRT *xprt;
+
+       if (nconf == NULL) {
+               warnx(
+       "svc_tp_create: invalid netconfig structure for prog %u vers %u",
+                               (unsigned)prognum, (unsigned)versnum);
+               return (NULL);
+       }
+       xprt = svc_tli_create(RPC_ANYFD, nconf, NULL, 0, 0);
+       if (xprt == NULL) {
+               return (NULL);
+       }
+       (void) rpcb_unset(prognum, versnum, __UNCONST(nconf));
+       if (svc_reg(xprt, prognum, versnum, dispatch, nconf) == FALSE) {
+               warnx(
+               "svc_tp_create: Could not register prog %u vers %u on %s",
+                               (unsigned)prognum, (unsigned)versnum,
+                               nconf->nc_netid);
+               SVC_DESTROY(xprt);
+               return (NULL);
+       }
+       return (xprt);
+}
+
+/*
+ * If fd is RPC_ANYFD, then it opens a fd for the given transport
+ * provider (nconf cannot be NULL then). If the t_state is T_UNBND and
+ * bindaddr is NON-NULL, it performs a t_bind using the bindaddr. For
+ * NULL bindadr and Connection oriented transports, the value of qlen
+ * is set to 8.
+ *
+ * If sendsz or recvsz are zero, their default values are chosen.
+ */
+SVCXPRT *
+svc_tli_create(fd, nconf, bindaddr, sendsz, recvsz)
+       int fd;                         /* Connection end point */
+       const struct netconfig *nconf;  /* Netconfig struct for nettoken */
+       const struct t_bind *bindaddr;  /* Local bind address */
+       u_int sendsz;                   /* Max sendsize */
+       u_int recvsz;                   /* Max recvsize */
+{
+       SVCXPRT *xprt = NULL;           /* service handle */
+       bool_t madefd = FALSE;          /* whether fd opened here  */
+       struct __rpc_sockinfo si;
+       struct sockaddr_storage ss;
+       socklen_t slen;
+
+       if (fd == RPC_ANYFD) {
+               if (nconf == NULL) {
+                       warnx("svc_tli_create: invalid netconfig");
+                       return (NULL);
+               }
+               fd = __rpc_nconf2fd(nconf);
+               if (fd == -1) {
+                       warnx(
+                           "svc_tli_create: could not open connection for %s",
+                                       nconf->nc_netid);
+                       return (NULL);
+               }
+               __rpc_nconf2sockinfo(nconf, &si);
+               madefd = TRUE;
+       } else {
+               /*
+                * It is an open descriptor. Get the transport info.
+                */
+               if (!__rpc_fd2sockinfo(fd, &si)) {
+                       warnx(
+               "svc_tli_create: could not get transport information");
+                       return (NULL);
+               }
+       }
+
+       /*
+        * If the fd is unbound, try to bind it.
+        */
+       if (madefd || !__rpc_sockisbound(fd)) {
+               if (bindaddr == NULL) {
+                       if (bindresvport(fd, NULL) < 0) {
+                               memset(&ss, 0, sizeof ss);
+                               ss.ss_family = si.si_af;
+                               ss.ss_len = si.si_alen;
+                               if (bind(fd, (struct sockaddr *)(void *)&ss,
+                                   (socklen_t)si.si_alen) < 0) {
+                                       warnx(
+                       "svc_tli_create: could not bind to anonymous port");
+                                       goto freedata;
+                               }
+                       }
+                       listen(fd, SOMAXCONN);
+               } else {
+                       if (bind(fd,
+                           (struct sockaddr *)bindaddr->addr.buf,
+                           (socklen_t)si.si_alen) < 0) {
+                               warnx(
+               "svc_tli_create: could not bind to requested address");
+                               goto freedata;
+                       }
+                       listen(fd, (int)bindaddr->qlen);
+               }
+                       
+       }
+       /*
+        * call transport specific function.
+        */
+       switch (si.si_socktype) {
+               case SOCK_STREAM:
+                       slen = sizeof ss;
+                       if (getpeername(fd, (struct sockaddr *)(void *)&ss, &slen)
+                           == 0) {
+                               /* accepted socket */
+                               xprt = svc_fd_create(fd, sendsz, recvsz);
+                       } else
+                               xprt = svc_vc_create(fd, sendsz, recvsz);
+                       if (!nconf || !xprt)
+                               break;
+#if 0
+                       /* XXX fvdl */
+                       if (strcmp(nconf->nc_protofmly, "inet") == 0 ||
+                           strcmp(nconf->nc_protofmly, "inet6") == 0)
+                               (void) __svc_vc_setflag(xprt, TRUE);
+#endif
+                       break;
+               case SOCK_DGRAM:
+                       xprt = svc_dg_create(fd, sendsz, recvsz);
+                       break;
+               default:
+                       warnx("svc_tli_create: bad service type");
+                       goto freedata;
+       }
+
+       if (xprt == NULL)
+               /*
+                * The error messages here are spitted out by the lower layers:
+                * svc_vc_create(), svc_fd_create() and svc_dg_create().
+                */
+               goto freedata;
+
+       /* Fill in type of service */
+       xprt->xp_type = __rpc_socktype2seman(si.si_socktype);
+
+       if (nconf) {
+               xprt->xp_netid = strdup(nconf->nc_netid);
+               xprt->xp_tp = strdup(nconf->nc_device);
+               if (xprt->xp_netid == NULL || xprt->xp_tp == NULL) {
+                       svc_destroy(xprt);
+                       return NULL;
+               }
+       }
+       return (xprt);
+
+freedata:
+       if (madefd)
+               (void) close(fd);
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/rpc/svc_raw.c b/lib/nbsd_libc/rpc/svc_raw.c
new file mode 100644 (file)
index 0000000..ffeef60
--- /dev/null
@@ -0,0 +1,277 @@
+/*     $NetBSD: svc_raw.c,v 1.21 2008/05/24 15:59:59 christos Exp $    */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc. 
+ */
+
+/* #ident      "@(#)svc_raw.c  1.16    94/04/24 SMI" */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)svc_raw.c 1.25 89/01/31 Copyr 1984 Sun Micro";
+#else
+__RCSID("$NetBSD: svc_raw.c,v 1.21 2008/05/24 15:59:59 christos Exp $");
+#endif
+#endif
+
+/*
+ * svc_raw.c,   This a toy for simple testing and timing.
+ * Interface to create an rpc client and server in the same UNIX process.
+ * This lets us similate rpc and get rpc (round trip) overhead, without
+ * any interference from the kernel.
+ *
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <rpc/rpc.h>
+#include <sys/types.h>
+#include <rpc/raw.h>
+#include <assert.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(svc_raw_create,_svc_raw_create)
+#endif
+
+#ifndef UDPMSGSIZE
+#define        UDPMSGSIZE 8800
+#endif
+
+/*
+ * This is the "network" that we will be moving data over
+ */
+static struct svc_raw_private {
+       char    *raw_buf;       /* should be shared with the cl handle */
+       SVCXPRT server;
+       XDR     xdr_stream;
+       char    verf_body[MAX_AUTH_BYTES];
+} *svc_raw_private;
+
+#ifdef _REENTRANT
+extern mutex_t svcraw_lock;
+#endif
+
+static enum xprt_stat svc_raw_stat __P((SVCXPRT *));
+static bool_t svc_raw_recv __P((SVCXPRT *, struct rpc_msg *));
+static bool_t svc_raw_reply __P((SVCXPRT *, struct rpc_msg *));
+static bool_t svc_raw_getargs __P((SVCXPRT *, xdrproc_t, caddr_t));
+static bool_t svc_raw_freeargs __P((SVCXPRT *, xdrproc_t, caddr_t));
+static void svc_raw_destroy __P((SVCXPRT *));
+static void svc_raw_ops __P((SVCXPRT *));
+static bool_t svc_raw_control __P((SVCXPRT *, const u_int, void *));
+
+char *__rpc_rawcombuf = NULL;
+
+SVCXPRT *
+svc_raw_create()
+{
+       struct svc_raw_private *srp;
+/* VARIABLES PROTECTED BY svcraw_lock: svc_raw_private, srp */
+
+       mutex_lock(&svcraw_lock);
+       srp = svc_raw_private;
+       if (srp == NULL) {
+               srp = calloc(1, sizeof(*srp));
+               if (srp == NULL)
+                       goto out;
+               if (__rpc_rawcombuf == NULL)
+                       __rpc_rawcombuf = malloc(UDPMSGSIZE);
+               if (__rpc_rawcombuf == NULL)
+                       goto out;
+               srp->raw_buf = __rpc_rawcombuf; /* Share it with the client */
+               svc_raw_private = srp;
+       }
+       srp->server.xp_fd = FD_SETSIZE;
+       srp->server.xp_port = 0;
+       srp->server.xp_p3 = NULL;
+       svc_raw_ops(&srp->server);
+       srp->server.xp_verf.oa_base = srp->verf_body;
+       xdrmem_create(&srp->xdr_stream, srp->raw_buf, UDPMSGSIZE, XDR_DECODE);
+       xprt_register(&srp->server);
+       mutex_unlock(&svcraw_lock);
+       return (&srp->server);
+out:
+       if (srp != NULL)
+               free(srp);
+       mutex_unlock(&svcraw_lock);
+       return (NULL);
+}
+
+/*ARGSUSED*/
+static enum xprt_stat
+svc_raw_stat(xprt)
+SVCXPRT *xprt; /* args needed to satisfy ANSI-C typechecking */
+{
+       return (XPRT_IDLE);
+}
+
+/*ARGSUSED*/
+static bool_t
+svc_raw_recv(xprt, msg)
+       SVCXPRT *xprt;
+       struct rpc_msg *msg;
+{
+       struct svc_raw_private *srp;
+       XDR *xdrs;
+
+       mutex_lock(&svcraw_lock);
+       srp = svc_raw_private;
+       if (srp == NULL) {
+               mutex_unlock(&svcraw_lock);
+               return (FALSE);
+       }
+       mutex_unlock(&svcraw_lock);
+
+       xdrs = &srp->xdr_stream;
+       xdrs->x_op = XDR_DECODE;
+       (void) XDR_SETPOS(xdrs, 0);
+       if (! xdr_callmsg(xdrs, msg)) {
+               return (FALSE);
+       }
+       return (TRUE);
+}
+
+/*ARGSUSED*/
+static bool_t
+svc_raw_reply(xprt, msg)
+       SVCXPRT *xprt;
+       struct rpc_msg *msg;
+{
+       struct svc_raw_private *srp;
+       XDR *xdrs;
+
+       mutex_lock(&svcraw_lock);
+       srp = svc_raw_private;
+       if (srp == NULL) {
+               mutex_unlock(&svcraw_lock);
+               return (FALSE);
+       }
+       mutex_unlock(&svcraw_lock);
+
+       xdrs = &srp->xdr_stream;
+       xdrs->x_op = XDR_ENCODE;
+       (void) XDR_SETPOS(xdrs, 0);
+       if (! xdr_replymsg(xdrs, msg)) {
+               return (FALSE);
+       }
+       (void) XDR_GETPOS(xdrs);  /* called just for overhead */
+       return (TRUE);
+}
+
+/*ARGSUSED*/
+static bool_t
+svc_raw_getargs(xprt, xdr_args, args_ptr)
+       SVCXPRT *xprt;
+       xdrproc_t xdr_args;
+       caddr_t args_ptr;
+{
+       struct svc_raw_private *srp;
+
+       mutex_lock(&svcraw_lock);
+       srp = svc_raw_private;
+       if (srp == NULL) {
+               mutex_unlock(&svcraw_lock);
+               return (FALSE);
+       }
+       mutex_unlock(&svcraw_lock);
+       return (*xdr_args)(&srp->xdr_stream, args_ptr);
+}
+
+/*ARGSUSED*/
+static bool_t
+svc_raw_freeargs(xprt, xdr_args, args_ptr)
+       SVCXPRT *xprt;
+       xdrproc_t xdr_args;
+       caddr_t args_ptr;
+{
+       struct svc_raw_private *srp;
+       XDR *xdrs;
+
+       mutex_lock(&svcraw_lock);
+       srp = svc_raw_private;
+       if (srp == NULL) {
+               mutex_unlock(&svcraw_lock);
+               return (FALSE);
+       }
+       mutex_unlock(&svcraw_lock);
+
+       xdrs = &srp->xdr_stream;
+       xdrs->x_op = XDR_FREE;
+       return (*xdr_args)(xdrs, args_ptr);
+}
+
+/*ARGSUSED*/
+static void
+svc_raw_destroy(xprt)
+SVCXPRT *xprt;
+{
+}
+
+/*ARGSUSED*/
+static bool_t
+svc_raw_control(xprt, rq, in)
+       SVCXPRT *xprt;
+       const u_int     rq;
+       void            *in;
+{
+       return (FALSE);
+}
+
+static void
+svc_raw_ops(xprt)
+       SVCXPRT *xprt;
+{
+       static struct xp_ops ops;
+       static struct xp_ops2 ops2;
+#ifdef _REENTRANT
+       extern mutex_t ops_lock;
+#endif
+
+       _DIAGASSERT(xprt != NULL);
+
+/* VARIABLES PROTECTED BY ops_lock: ops */
+
+       mutex_lock(&ops_lock);
+       if (ops.xp_recv == NULL) {
+               ops.xp_recv = svc_raw_recv;
+               ops.xp_stat = svc_raw_stat;
+               ops.xp_getargs = svc_raw_getargs;
+               ops.xp_reply = svc_raw_reply;
+               ops.xp_freeargs = svc_raw_freeargs;
+               ops.xp_destroy = svc_raw_destroy;
+               ops2.xp_control = svc_raw_control;
+       }
+       xprt->xp_ops = &ops;
+       xprt->xp_ops2 = &ops2;
+       mutex_unlock(&ops_lock);
+}
diff --git a/lib/nbsd_libc/rpc/svc_run.c b/lib/nbsd_libc/rpc/svc_run.c
new file mode 100644 (file)
index 0000000..56aea55
--- /dev/null
@@ -0,0 +1,110 @@
+/*     $NetBSD: svc_run.c,v 1.19 2003/01/18 11:29:07 thorpej Exp $     */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)svc_run.c 1.1 87/10/13 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)svc_run.c   2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: svc_run.c,v 1.19 2003/01/18 11:29:07 thorpej Exp $");
+#endif
+#endif
+
+/*
+ * This is the rpc server side idle loop
+ * Wait for input, call server program.
+ */
+#include "namespace.h"
+#include "reentrant.h"
+#include <err.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <rpc/rpc.h>
+
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(svc_run,_svc_run)
+__weak_alias(svc_exit,_svc_exit)
+#endif
+
+void
+svc_run()
+{
+       fd_set readfds, cleanfds;
+       struct timeval timeout;
+#ifdef _REENTRANT
+       extern rwlock_t svc_fd_lock;
+#endif
+
+       timeout.tv_sec = 30;
+       timeout.tv_usec = 0;
+
+       for (;;) {
+               rwlock_rdlock(&svc_fd_lock);
+               readfds = svc_fdset;
+               cleanfds = svc_fdset;
+               rwlock_unlock(&svc_fd_lock);
+               switch (select(svc_maxfd+1, &readfds, NULL, NULL, &timeout)) {
+               case -1:
+                       if (errno == EINTR) {
+                               continue;
+                       }
+                       warn("svc_run: - select failed");
+                       return;
+               case 0:
+                       __svc_clean_idle(&cleanfds, 30, FALSE);
+                       continue;
+               default:
+                       svc_getreqset(&readfds);
+               }
+       }
+}
+
+/*
+ *      This function causes svc_run() to exit by telling it that it has no
+ *      more work to do.
+ */
+void
+svc_exit()
+{
+#ifdef _REENTRANT
+       extern rwlock_t svc_fd_lock;
+#endif
+
+       rwlock_wrlock(&svc_fd_lock);
+       FD_ZERO(&svc_fdset);
+       rwlock_unlock(&svc_fd_lock);
+}
diff --git a/lib/nbsd_libc/rpc/svc_simple.c b/lib/nbsd_libc/rpc/svc_simple.c
new file mode 100644 (file)
index 0000000..bf67c00
--- /dev/null
@@ -0,0 +1,327 @@
+/*     $NetBSD: svc_simple.c,v 1.30 2008/04/25 17:44:44 christos Exp $ */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986-1991 by Sun Microsystems Inc. 
+ */
+
+/* #pragma ident       "@(#)svc_simple.c       1.18    94/04/24 SMI" */
+
+/*
+ * svc_simple.c
+ * Simplified front end to rpc.
+ */
+
+/*
+ * This interface creates a virtual listener for all the services
+ * started thru rpc_reg(). It listens on the same endpoint for
+ * all the services and then executes the corresponding service
+ * for the given prognum and procnum.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: svc_simple.c,v 1.30 2008/04/25 17:44:44 christos Exp $");
+#endif
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <rpc/rpc.h>
+#include <rpc/nettype.h>
+#include <assert.h>
+#include <err.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(rpc_reg,_rpc_reg)
+#endif
+
+static void universal __P((struct svc_req *, SVCXPRT *));
+
+static struct proglst {
+       char *(*p_progname) __P((char *));
+       rpcprog_t p_prognum;
+       rpcvers_t p_versnum;
+       rpcproc_t p_procnum;
+       SVCXPRT *p_transp;
+       char *p_netid;
+       char *p_xdrbuf;
+       int p_recvsz;
+       xdrproc_t p_inproc, p_outproc;
+       struct proglst *p_nxt;
+} *proglst;
+
+static const char rpc_reg_err[] = "%s: %s";
+static const char rpc_reg_msg[] = "rpc_reg: ";
+static const char __reg_err1[] = "can't find appropriate transport";
+static const char __reg_err2[] = "can't get protocol info";
+static const char __reg_err3[] = "unsupported transport size";
+static const char __no_mem_str[] = "out of memory";
+
+/*
+ * For simplified, easy to use kind of rpc interfaces.
+ * nettype indicates the type of transport on which the service will be
+ * listening. Used for conservation of the system resource. Only one
+ * handle is created for all the services (actually one of each netid)
+ * and same xdrbuf is used for same netid. The size of the arguments
+ * is also limited by the recvsize for that transport, even if it is
+ * a COTS transport. This may be wrong, but for cases like these, they
+ * should not use the simplified interfaces like this.
+ */
+
+int
+rpc_reg(prognum, versnum, procnum, progname, inproc, outproc, nettype)
+       rpcprog_t prognum;                      /* program number */
+       rpcvers_t versnum;                      /* version number */
+       rpcproc_t procnum;                      /* procedure number */
+       char *(*progname) __P((char *)); /* Server routine */
+       xdrproc_t inproc, outproc;      /* in/out XDR procedures */
+       char *nettype;                  /* nettype */
+{
+       struct netconfig *nconf;
+       int done = FALSE;
+       void *handle;
+#ifdef _REENTRANT
+       extern mutex_t proglst_lock;
+#endif
+
+       if (procnum == NULLPROC) {
+               warnx("%s can't reassign procedure number %u", rpc_reg_msg,
+                       NULLPROC);
+               return (-1);
+       }
+
+       if (nettype == NULL)
+               nettype = __UNCONST("netpath"); /* The default behavior */
+       if ((handle = __rpc_setconf(nettype)) == NULL) {
+               warnx(rpc_reg_err, rpc_reg_msg, __reg_err1);
+               return (-1);
+       }
+/* VARIABLES PROTECTED BY proglst_lock: proglst */
+       mutex_lock(&proglst_lock);
+       while ((nconf = __rpc_getconf(handle)) != NULL) {
+               struct proglst *pl;
+               SVCXPRT *svcxprt;
+               int madenow;
+               u_int recvsz;
+               char *xdrbuf;
+               char *netid;
+
+               madenow = FALSE;
+               svcxprt = NULL;
+               recvsz = 0;
+               xdrbuf = NULL;
+               netid = NULL;
+               for (pl = proglst; pl; pl = pl->p_nxt)
+                       if (strcmp(pl->p_netid, nconf->nc_netid) == 0) {
+                               svcxprt = pl->p_transp;
+                               xdrbuf = pl->p_xdrbuf;
+                               recvsz = pl->p_recvsz;
+                               netid = pl->p_netid;
+                               break;
+                       }
+
+               if (svcxprt == NULL) {
+                       struct __rpc_sockinfo si;
+
+                       svcxprt = svc_tli_create(RPC_ANYFD, nconf, NULL, 0, 0);
+                       if (svcxprt == NULL)
+                               continue;
+                       if (!__rpc_fd2sockinfo(svcxprt->xp_fd, &si)) {
+                               warnx(rpc_reg_err, rpc_reg_msg, __reg_err2);
+                               SVC_DESTROY(svcxprt);
+                               continue;
+                       }
+                       recvsz = __rpc_get_t_size(si.si_af, si.si_proto, 0);
+                       if (recvsz == 0) {
+                               warnx(rpc_reg_err, rpc_reg_msg, __reg_err3);
+                               SVC_DESTROY(svcxprt);
+                               continue;
+                       }
+                       if (((xdrbuf = malloc((size_t)recvsz)) == NULL) ||
+                               ((netid = strdup(nconf->nc_netid)) == NULL)) {
+                               warnx(rpc_reg_err, rpc_reg_msg, __no_mem_str);
+                               if (xdrbuf != NULL)
+                                       free(xdrbuf);
+                               if (netid != NULL)
+                                       free(netid);
+                               SVC_DESTROY(svcxprt);
+                               break;
+                       }
+                       madenow = TRUE;
+               }
+               /*
+                * Check if this (program, version, netid) had already been
+                * registered.  The check may save a few RPC calls to rpcbind
+                */
+               for (pl = proglst; pl; pl = pl->p_nxt)
+                       if ((pl->p_prognum == prognum) &&
+                               (pl->p_versnum == versnum) &&
+                               (strcmp(pl->p_netid, netid) == 0))
+                               break;
+               if (pl == NULL) { /* Not yet */
+                       (void) rpcb_unset(prognum, versnum, nconf);
+               } else {
+                       /* so that svc_reg does not call rpcb_set() */
+                       nconf = NULL;
+               }
+
+               if (!svc_reg(svcxprt, prognum, versnum, universal, nconf)) {
+                       warnx("%s couldn't register prog %u vers %u for %s",
+                               rpc_reg_msg, (unsigned)prognum,
+                               (unsigned)versnum, netid);
+                       if (madenow) {
+                               SVC_DESTROY(svcxprt);
+                               free(xdrbuf);
+                               free(netid);
+                       }
+                       continue;
+               }
+
+               pl = malloc(sizeof(*pl));
+               if (pl == NULL) {
+                       warnx(rpc_reg_err, rpc_reg_msg, __no_mem_str);
+                       if (madenow) {
+                               SVC_DESTROY(svcxprt);
+                               free(xdrbuf);
+                               free(netid);
+                       }
+                       break;
+               }
+               pl->p_progname = progname;
+               pl->p_prognum = prognum;
+               pl->p_versnum = versnum;
+               pl->p_procnum = procnum;
+               pl->p_inproc = inproc;
+               pl->p_outproc = outproc;
+               pl->p_transp = svcxprt;
+               pl->p_xdrbuf = xdrbuf;
+               pl->p_recvsz = recvsz;
+               pl->p_netid = netid;
+               pl->p_nxt = proglst;
+               proglst = pl;
+               done = TRUE;
+       }
+       __rpc_endconf(handle);
+       mutex_unlock(&proglst_lock);
+
+       if (done == FALSE) {
+               warnx("%s cant find suitable transport for %s",
+                       rpc_reg_msg, nettype);
+               return (-1);
+       }
+       return (0);
+}
+
+/*
+ * The universal handler for the services registered using registerrpc.
+ * It handles both the connectionless and the connection oriented cases.
+ */
+
+static void
+universal(rqstp, transp)
+       struct svc_req *rqstp;
+       SVCXPRT *transp;
+{
+       rpcprog_t prog;
+       rpcvers_t vers;
+       rpcproc_t proc;
+       char *outdata;
+       char *xdrbuf;
+       struct proglst *pl;
+#ifdef _REENTRANT
+       extern mutex_t proglst_lock;
+#endif
+
+       _DIAGASSERT(rqstp != NULL);
+       _DIAGASSERT(transp != NULL);
+
+       /*
+        * enforce "procnum 0 is echo" convention
+        */
+       if (rqstp->rq_proc == NULLPROC) {
+               if (svc_sendreply(transp, (xdrproc_t) xdr_void, NULL) ==
+                   FALSE) {
+                       warnx("svc_sendreply failed");
+               }
+               return;
+       }
+       prog = rqstp->rq_prog;
+       vers = rqstp->rq_vers;
+       proc = rqstp->rq_proc;
+       mutex_lock(&proglst_lock);
+       for (pl = proglst; pl; pl = pl->p_nxt)
+               if (pl->p_prognum == prog && pl->p_procnum == proc &&
+                       pl->p_versnum == vers &&
+                       (strcmp(pl->p_netid, transp->xp_netid) == 0)) {
+                       /* decode arguments into a CLEAN buffer */
+                       xdrbuf = pl->p_xdrbuf;
+                       /* Zero the arguments: reqd ! */
+                       (void) memset(xdrbuf, 0, (size_t)pl->p_recvsz);
+                       /*
+                        * Assuming that sizeof (xdrbuf) would be enough
+                        * for the arguments; if not then the program
+                        * may bomb. BEWARE!
+                        */
+                       if (!svc_getargs(transp, pl->p_inproc, xdrbuf)) {
+                               svcerr_decode(transp);
+                               mutex_unlock(&proglst_lock);
+                               return;
+                       }
+                       outdata = (*(pl->p_progname))(xdrbuf);
+                       if (outdata == NULL &&
+                               pl->p_outproc != (xdrproc_t) xdr_void){
+                               /* there was an error */
+                               mutex_unlock(&proglst_lock);
+                               return;
+                       }
+                       if (!svc_sendreply(transp, pl->p_outproc, outdata)) {
+                               warnx(
+                       "rpc: rpc_reg trouble replying to prog %u vers %u",
+                               (unsigned)prog, (unsigned)vers);
+                               mutex_unlock(&proglst_lock);
+                               return;
+                       }
+                       /* free the decoded arguments */
+                       (void) svc_freeargs(transp, pl->p_inproc, xdrbuf);
+                       mutex_unlock(&proglst_lock);
+                       return;
+               }
+       mutex_unlock(&proglst_lock);
+       /* This should never happen */
+       warnx("rpc: rpc_reg: never registered prog %u vers %u",
+               (unsigned)prog, (unsigned)vers);
+       return;
+}
diff --git a/lib/nbsd_libc/rpc/svc_vc.c b/lib/nbsd_libc/rpc/svc_vc.c
new file mode 100644 (file)
index 0000000..8c334c6
--- /dev/null
@@ -0,0 +1,839 @@
+/*     $NetBSD: svc_vc.c,v 1.22 2009/02/12 04:38:52 lukem Exp $        */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)svc_tcp.c 1.21 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)svc_tcp.c   2.2 88/08/01 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: svc_vc.c,v 1.22 2009/02/12 04:38:52 lukem Exp $");
+#endif
+#endif
+
+/*
+ * svc_vc.c, Server side for Connection Oriented based RPC. 
+ *
+ * Actually implements two flavors of transporter -
+ * a tcp rendezvouser (a listner and connection establisher)
+ * and a record/tcp stream.
+ */
+
+#include "namespace.h"
+#include "reentrant.h"
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/poll.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/time.h>
+#include <netinet/in.h>
+
+#include <assert.h>
+#include <err.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <rpc/rpc.h>
+
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(svc_fd_create,_svc_fd_create)
+__weak_alias(svc_vc_create,_svc_vc_create)
+#endif
+
+#ifdef _REENTRANT
+extern rwlock_t svc_fd_lock;
+#endif
+
+static SVCXPRT *makefd_xprt __P((int, u_int, u_int));
+static bool_t rendezvous_request __P((SVCXPRT *, struct rpc_msg *));
+static enum xprt_stat rendezvous_stat __P((SVCXPRT *));
+static void svc_vc_destroy __P((SVCXPRT *));
+static void __svc_vc_dodestroy __P((SVCXPRT *));
+static int read_vc __P((caddr_t, caddr_t, int));
+static int write_vc __P((caddr_t, caddr_t, int));
+static enum xprt_stat svc_vc_stat __P((SVCXPRT *));
+static bool_t svc_vc_recv __P((SVCXPRT *, struct rpc_msg *));
+static bool_t svc_vc_getargs __P((SVCXPRT *, xdrproc_t, caddr_t));
+static bool_t svc_vc_freeargs __P((SVCXPRT *, xdrproc_t, caddr_t));
+static bool_t svc_vc_reply __P((SVCXPRT *, struct rpc_msg *));
+static void svc_vc_rendezvous_ops __P((SVCXPRT *));
+static void svc_vc_ops __P((SVCXPRT *));
+static bool_t svc_vc_control __P((SVCXPRT *, const u_int, void *));
+static bool_t svc_vc_rendezvous_control __P((SVCXPRT *, const u_int,
+                                            void *));
+
+struct cf_rendezvous { /* kept in xprt->xp_p1 for rendezvouser */
+       u_int sendsize;
+       u_int recvsize;
+       int maxrec;
+};
+
+struct cf_conn {  /* kept in xprt->xp_p1 for actual connection */
+       enum xprt_stat strm_stat;
+       u_int32_t x_id;
+       XDR xdrs;
+       char verf_body[MAX_AUTH_BYTES];
+       u_int sendsize;
+       u_int recvsize;
+       int maxrec;
+       bool_t nonblock;
+       struct timeval last_recv_time;
+};
+
+/*
+ * Usage:
+ *     xprt = svc_vc_create(sock, send_buf_size, recv_buf_size);
+ *
+ * Creates, registers, and returns a (rpc) tcp based transporter.
+ * Once *xprt is initialized, it is registered as a transporter
+ * see (svc.h, xprt_register).  This routine returns
+ * a NULL if a problem occurred.
+ *
+ * The filedescriptor passed in is expected to refer to a bound, but
+ * not yet connected socket.
+ *
+ * Since streams do buffered io similar to stdio, the caller can specify
+ * how big the send and receive buffers are via the second and third parms;
+ * 0 => use the system default.
+ */
+SVCXPRT *
+svc_vc_create(fd, sendsize, recvsize)
+       int fd;
+       u_int sendsize;
+       u_int recvsize;
+{
+       SVCXPRT *xprt;
+       struct cf_rendezvous *r = NULL;
+       struct __rpc_sockinfo si;
+       struct sockaddr_storage sslocal;
+       socklen_t slen;
+       int one = 1;
+
+       if (!__rpc_fd2sockinfo(fd, &si))
+               return NULL;
+
+       r = mem_alloc(sizeof(*r));
+       if (r == NULL) {
+               warnx("svc_vc_create: out of memory");
+               return NULL;
+       }
+       r->sendsize = __rpc_get_t_size(si.si_af, si.si_proto, (int)sendsize);
+       r->recvsize = __rpc_get_t_size(si.si_af, si.si_proto, (int)recvsize);
+       r->maxrec = __svc_maxrec;
+       xprt = mem_alloc(sizeof(SVCXPRT));
+       if (xprt == NULL) {
+               warnx("svc_vc_create: out of memory");
+               goto cleanup_svc_vc_create;
+       }
+       xprt->xp_tp = NULL;
+       xprt->xp_p1 = (caddr_t)(void *)r;
+       xprt->xp_p2 = NULL;
+       xprt->xp_p3 = NULL;
+       xprt->xp_verf = _null_auth;
+       svc_vc_rendezvous_ops(xprt);
+       xprt->xp_port = (u_short)-1;    /* It is the rendezvouser */
+       xprt->xp_fd = fd;
+
+       slen = sizeof (struct sockaddr_storage);
+       if (getsockname(fd, (struct sockaddr *)(void *)&sslocal, &slen) < 0) {
+               warnx("svc_vc_create: could not retrieve local addr");
+               goto cleanup_svc_vc_create;
+       }
+
+       /*
+        * We want to be able to check credentials on local sockets.
+        */
+       if (sslocal.ss_family == AF_LOCAL)
+               if (setsockopt(fd, 0, LOCAL_CREDS, &one, sizeof one) < 0)
+                       goto cleanup_svc_vc_create;
+
+       xprt->xp_ltaddr.maxlen = xprt->xp_ltaddr.len = sslocal.ss_len;
+       xprt->xp_ltaddr.buf = mem_alloc((size_t)sslocal.ss_len);
+       if (xprt->xp_ltaddr.buf == NULL) {
+               warnx("svc_vc_create: no mem for local addr");
+               goto cleanup_svc_vc_create;
+       }
+       memcpy(xprt->xp_ltaddr.buf, &sslocal, (size_t)sslocal.ss_len);
+
+       xprt->xp_rtaddr.maxlen = sizeof (struct sockaddr_storage);
+       xprt_register(xprt);
+       return (xprt);
+cleanup_svc_vc_create:
+       if (xprt)
+               mem_free(xprt, sizeof(*xprt));
+       if (r != NULL)
+               mem_free(r, sizeof(*r));
+       return (NULL);
+}
+
+/*
+ * Like svtcp_create(), except the routine takes any *open* UNIX file
+ * descriptor as its first input.
+ */
+SVCXPRT *
+svc_fd_create(fd, sendsize, recvsize)
+       int fd;
+       u_int sendsize;
+       u_int recvsize;
+{
+       struct sockaddr_storage ss;
+       socklen_t slen;
+       SVCXPRT *ret;
+
+       _DIAGASSERT(fd != -1);
+
+       ret = makefd_xprt(fd, sendsize, recvsize);
+       if (ret == NULL)
+               return NULL;
+
+       slen = sizeof (struct sockaddr_storage);
+       if (getsockname(fd, (struct sockaddr *)(void *)&ss, &slen) < 0) {
+               warnx("svc_fd_create: could not retrieve local addr");
+               goto freedata;
+       }
+       ret->xp_ltaddr.maxlen = ret->xp_ltaddr.len = ss.ss_len;
+       ret->xp_ltaddr.buf = mem_alloc((size_t)ss.ss_len);
+       if (ret->xp_ltaddr.buf == NULL) {
+               warnx("svc_fd_create: no mem for local addr");
+               goto freedata;
+       }
+       memcpy(ret->xp_ltaddr.buf, &ss, (size_t)ss.ss_len);
+
+       slen = sizeof (struct sockaddr_storage);
+       if (getpeername(fd, (struct sockaddr *)(void *)&ss, &slen) < 0) {
+               warnx("svc_fd_create: could not retrieve remote addr");
+               goto freedata;
+       }
+       ret->xp_rtaddr.maxlen = ret->xp_rtaddr.len = ss.ss_len;
+       ret->xp_rtaddr.buf = mem_alloc((size_t)ss.ss_len);
+       if (ret->xp_rtaddr.buf == NULL) {
+               warnx("svc_fd_create: no mem for local addr");
+               goto freedata;
+       }
+       memcpy(ret->xp_rtaddr.buf, &ss, (size_t)ss.ss_len);
+#ifdef PORTMAP
+       if (ss.ss_family == AF_INET) {
+               ret->xp_raddr = *(struct sockaddr_in *)ret->xp_rtaddr.buf;
+               ret->xp_addrlen = sizeof (struct sockaddr_in);
+       }
+#endif
+
+       return ret;
+
+freedata:
+       if (ret->xp_ltaddr.buf != NULL)
+               mem_free(ret->xp_ltaddr.buf, rep->xp_ltaddr.maxlen);
+
+       return NULL;
+}
+
+static SVCXPRT *
+makefd_xprt(fd, sendsize, recvsize)
+       int fd;
+       u_int sendsize;
+       u_int recvsize;
+{
+       SVCXPRT *xprt;
+       struct cf_conn *cd;
+       const char *netid;
+       struct __rpc_sockinfo si;
+       _DIAGASSERT(fd != -1);
+
+       xprt = mem_alloc(sizeof(SVCXPRT));
+       if (xprt == NULL)
+               goto out;
+       memset(xprt, 0, sizeof *xprt);
+       cd = mem_alloc(sizeof(struct cf_conn));
+       if (cd == NULL)
+               goto out;
+       cd->strm_stat = XPRT_IDLE;
+       xdrrec_create(&(cd->xdrs), sendsize, recvsize,
+           (caddr_t)(void *)xprt, read_vc, write_vc);
+       xprt->xp_p1 = (caddr_t)(void *)cd;
+       xprt->xp_verf.oa_base = cd->verf_body;
+       svc_vc_ops(xprt);  /* truely deals with calls */
+       xprt->xp_port = 0;  /* this is a connection, not a rendezvouser */
+       xprt->xp_fd = fd;
+       if (__rpc_fd2sockinfo(fd, &si) && __rpc_sockinfo2netid(&si, &netid))
+               if ((xprt->xp_netid = strdup(netid)) == NULL)
+                       goto out;
+
+       xprt_register(xprt);
+       return (xprt);
+out:
+       warn("svc_tcp: makefd_xprt");
+       if (xprt)
+               mem_free(xprt, sizeof(SVCXPRT));
+       return NULL;
+}
+
+/*ARGSUSED*/
+static bool_t
+rendezvous_request(xprt, msg)
+       SVCXPRT *xprt;
+       struct rpc_msg *msg;
+{
+       int sock, flags;
+       struct cf_rendezvous *r;
+       struct cf_conn *cd;
+       struct sockaddr_storage addr;
+       socklen_t len;
+       struct __rpc_sockinfo si;
+       SVCXPRT *newxprt;
+       fd_set cleanfds;
+
+       _DIAGASSERT(xprt != NULL);
+       _DIAGASSERT(msg != NULL);
+
+       r = (struct cf_rendezvous *)xprt->xp_p1;
+again:
+       len = sizeof addr;
+       if ((sock = accept(xprt->xp_fd, (struct sockaddr *)(void *)&addr,
+           &len)) < 0) {
+               if (errno == EINTR)
+                       goto again;
+               /*
+                * Clean out the most idle file descriptor when we're
+                * running out.
+                */
+               if (errno == EMFILE || errno == ENFILE) {
+                       cleanfds = svc_fdset;
+                       if (__svc_clean_idle(&cleanfds, 0, FALSE))
+                               goto again;
+               }
+               return (FALSE);
+       }
+       /*
+        * make a new transporter (re-uses xprt)
+        */
+       newxprt = makefd_xprt(sock, r->sendsize, r->recvsize);
+       if (newxprt == NULL)
+               goto out;
+       newxprt->xp_rtaddr.buf = mem_alloc(len);
+       if (newxprt->xp_rtaddr.buf == NULL)
+               goto out;
+       memcpy(newxprt->xp_rtaddr.buf, &addr, len);
+       newxprt->xp_rtaddr.len = len;
+#ifdef PORTMAP
+       if (addr.ss_family == AF_INET) {
+               newxprt->xp_raddr = *(struct sockaddr_in *)newxprt->xp_rtaddr.buf;
+               newxprt->xp_addrlen = sizeof (struct sockaddr_in);
+       }
+#endif
+       if (__rpc_fd2sockinfo(sock, &si))
+               __rpc_setnodelay(sock, &si);
+
+       cd = (struct cf_conn *)newxprt->xp_p1;
+
+       cd->recvsize = r->recvsize;
+       cd->sendsize = r->sendsize;
+       cd->maxrec = r->maxrec;
+
+       if (cd->maxrec != 0) {
+               flags = fcntl(sock, F_GETFL, 0);
+               if (flags  == -1)
+                       goto out;
+               if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1)
+                       goto out;
+               if (cd->recvsize > (u_int)cd->maxrec)
+                       cd->recvsize = cd->maxrec;
+               cd->nonblock = TRUE;
+               __xdrrec_setnonblock(&cd->xdrs, cd->maxrec);
+       } else
+               cd->nonblock = FALSE;
+
+       (void)gettimeofday(&cd->last_recv_time, NULL);
+
+       return (FALSE); /* there is never an rpc msg to be processed */
+out:
+       (void)close(sock);
+       return (FALSE); /* there was an error */
+}
+
+/*ARGSUSED*/
+static enum xprt_stat
+rendezvous_stat(xprt)
+       SVCXPRT *xprt;
+{
+
+       return (XPRT_IDLE);
+}
+
+static void
+svc_vc_destroy(xprt)
+       SVCXPRT *xprt;
+{
+       _DIAGASSERT(xprt != NULL);
+
+       xprt_unregister(xprt);
+       __svc_vc_dodestroy(xprt);
+}
+
+static void
+__svc_vc_dodestroy(xprt)
+       SVCXPRT *xprt;
+{
+       struct cf_conn *cd;
+       struct cf_rendezvous *r;
+
+       cd = (struct cf_conn *)xprt->xp_p1;
+
+       if (xprt->xp_fd != RPC_ANYFD)
+               (void)close(xprt->xp_fd);
+       if (xprt->xp_port != 0) {
+               /* a rendezvouser socket */
+               r = (struct cf_rendezvous *)xprt->xp_p1;
+               mem_free(r, sizeof (struct cf_rendezvous));
+               xprt->xp_port = 0;
+       } else {
+               /* an actual connection socket */
+               XDR_DESTROY(&(cd->xdrs));
+               mem_free(cd, sizeof(struct cf_conn));
+       }
+       if (xprt->xp_rtaddr.buf)
+               mem_free(xprt->xp_rtaddr.buf, xprt->xp_rtaddr.maxlen);
+       if (xprt->xp_ltaddr.buf)
+               mem_free(xprt->xp_ltaddr.buf, xprt->xp_ltaddr.maxlen);
+       if (xprt->xp_tp)
+               free(xprt->xp_tp);
+       if (xprt->xp_netid)
+               free(xprt->xp_netid);
+       mem_free(xprt, sizeof(SVCXPRT));
+}
+
+/*ARGSUSED*/
+static bool_t
+svc_vc_control(xprt, rq, in)
+       SVCXPRT *xprt;
+       const u_int rq;
+       void *in;
+{
+       return (FALSE);
+}
+
+/*ARGSUSED*/
+static bool_t
+svc_vc_rendezvous_control(xprt, rq, in)
+       SVCXPRT *xprt;
+       const u_int rq;
+       void *in;
+{
+       struct cf_rendezvous *cfp;
+
+       cfp = (struct cf_rendezvous *)xprt->xp_p1;
+       if (cfp == NULL)
+               return (FALSE);
+       switch (rq) {
+               case SVCGET_CONNMAXREC:
+                       *(int *)in = cfp->maxrec;
+                       break;
+               case SVCSET_CONNMAXREC:
+                       cfp->maxrec = *(int *)in;
+                       break;
+               default:
+                       return (FALSE);
+       }
+       return (TRUE);
+}
+
+/*
+ * reads data from the tcp connection.
+ * any error is fatal and the connection is closed.
+ * (And a read of zero bytes is a half closed stream => error.)
+ * All read operations timeout after 35 seconds.  A timeout is
+ * fatal for the connection.
+ */
+static int
+read_vc(xprtp, buf, len)
+       caddr_t xprtp;
+       caddr_t buf;
+       int len;
+{
+       SVCXPRT *xprt;
+       int sock;
+       struct pollfd pollfd;
+       struct sockaddr *sa;
+       struct msghdr msg;
+       struct cmsghdr *cmp;
+       void *crmsg = NULL;
+       struct sockcred *sc;
+       socklen_t crmsgsize;
+       struct cf_conn *cfp;
+       static const struct timespec ts = { 35, 0 };
+
+       xprt = (SVCXPRT *)(void *)xprtp;
+       _DIAGASSERT(xprt != NULL);
+
+       sock = xprt->xp_fd;
+
+       sa = (struct sockaddr *)xprt->xp_rtaddr.buf;
+       if (sa->sa_family == AF_LOCAL && xprt->xp_p2 == NULL) {
+               memset(&msg, 0, sizeof msg);
+               crmsgsize = CMSG_SPACE(SOCKCREDSIZE(NGROUPS));
+               crmsg = malloc(crmsgsize);
+               if (crmsg == NULL)
+                       goto fatal_err;
+               memset(crmsg, 0, crmsgsize);
+
+               msg.msg_control = crmsg;
+               msg.msg_controllen = crmsgsize;
+
+               if (recvmsg(sock, &msg, 0) < 0)
+                       goto fatal_err;
+
+               if (msg.msg_controllen == 0 ||
+                   (msg.msg_flags & MSG_CTRUNC) != 0)
+                       goto fatal_err;
+
+               cmp = CMSG_FIRSTHDR(&msg);
+               if (cmp->cmsg_level != SOL_SOCKET ||
+                   cmp->cmsg_type != SCM_CREDS)
+                       goto fatal_err;
+
+               sc = (struct sockcred *)(void *)CMSG_DATA(cmp);
+
+               xprt->xp_p2 = mem_alloc(SOCKCREDSIZE(sc->sc_ngroups));
+               if (xprt->xp_p2 == NULL)
+                       goto fatal_err;
+
+               memcpy(xprt->xp_p2, sc, SOCKCREDSIZE(sc->sc_ngroups));
+               free(crmsg);
+               crmsg = NULL;
+       }
+
+       cfp = (struct cf_conn *)xprt->xp_p1;
+
+       if (cfp->nonblock) {
+               len = read(sock, buf, (size_t)len);
+               if (len < 0) {
+                       if (errno == EAGAIN)
+                               len = 0;
+                       else
+                               goto fatal_err;
+               }
+               if (len != 0)
+                       gettimeofday(&cfp->last_recv_time, NULL);
+               return len;
+       }
+
+       do {
+               pollfd.fd = sock;
+               pollfd.events = POLLIN;
+               switch (pollts(&pollfd, 1, &ts, NULL)) {
+               case -1:
+                       if (errno == EINTR) {
+                               continue;
+                       }
+                       /*FALLTHROUGH*/
+               case 0:
+                       goto fatal_err;
+
+               default:
+                       break;
+               }
+       } while ((pollfd.revents & POLLIN) == 0);
+
+       if ((len = read(sock, buf, (size_t)len)) > 0) {
+               gettimeofday(&cfp->last_recv_time, NULL);
+               return (len);
+       }
+
+fatal_err:
+       if (crmsg != NULL)
+               free(crmsg);
+       ((struct cf_conn *)(xprt->xp_p1))->strm_stat = XPRT_DIED;
+       return (-1);
+}
+
+/*
+ * writes data to the tcp connection.
+ * Any error is fatal and the connection is closed.
+ */
+static int
+write_vc(xprtp, buf, len)
+       caddr_t xprtp;
+       caddr_t buf;
+       int len;
+{
+       SVCXPRT *xprt;
+       int i, cnt;
+       struct cf_conn *cd;
+       struct timeval tv0, tv1;
+
+       xprt = (SVCXPRT *)(void *)xprtp;
+       _DIAGASSERT(xprt != NULL);
+
+       cd = (struct cf_conn *)xprt->xp_p1;
+
+       if (cd->nonblock)
+               gettimeofday(&tv0, NULL);
+
+       for (cnt = len; cnt > 0; cnt -= i, buf += i) {
+               if ((i = write(xprt->xp_fd, buf, (size_t)cnt)) < 0) {
+                       if (errno != EAGAIN || !cd->nonblock) {
+                               cd->strm_stat = XPRT_DIED;
+                               return (-1);
+                       }
+                       if (cd->nonblock && i != cnt) {
+                               /*
+                                * For non-blocking connections, do not
+                                * take more than 2 seconds writing the
+                                * data out.
+                                *
+                                * XXX 2 is an arbitrary amount.
+                                */
+                               gettimeofday(&tv1, NULL);
+                               if (tv1.tv_sec - tv0.tv_sec >= 2) {
+                                       cd->strm_stat = XPRT_DIED;
+                                       return (-1);
+                               }
+                       }
+               }
+       }
+       return (len);
+}
+
+static enum xprt_stat
+svc_vc_stat(xprt)
+       SVCXPRT *xprt;
+{
+       struct cf_conn *cd;
+
+       _DIAGASSERT(xprt != NULL);
+
+       cd = (struct cf_conn *)(xprt->xp_p1);
+
+       if (cd->strm_stat == XPRT_DIED)
+               return (XPRT_DIED);
+       if (! xdrrec_eof(&(cd->xdrs)))
+               return (XPRT_MOREREQS);
+       return (XPRT_IDLE);
+}
+
+static bool_t
+svc_vc_recv(xprt, msg)
+       SVCXPRT *xprt;
+       struct rpc_msg *msg;
+{
+       struct cf_conn *cd;
+       XDR *xdrs;
+
+       _DIAGASSERT(xprt != NULL);
+       _DIAGASSERT(msg != NULL);
+
+       cd = (struct cf_conn *)(xprt->xp_p1);
+       xdrs = &(cd->xdrs);
+
+       if (cd->nonblock) {
+               if (!__xdrrec_getrec(xdrs, &cd->strm_stat, TRUE))
+                       return FALSE;
+       }
+
+       xdrs->x_op = XDR_DECODE;
+       (void)xdrrec_skiprecord(xdrs);
+
+       if (xdr_callmsg(xdrs, msg)) {
+               cd->x_id = msg->rm_xid;
+               return (TRUE);
+       }
+       cd->strm_stat = XPRT_DIED;
+       return (FALSE);
+}
+
+static bool_t
+svc_vc_getargs(xprt, xdr_args, args_ptr)
+       SVCXPRT *xprt;
+       xdrproc_t xdr_args;
+       caddr_t args_ptr;
+{
+
+       _DIAGASSERT(xprt != NULL);
+       /* args_ptr may be NULL */
+
+       return ((*xdr_args)(&(((struct cf_conn *)(xprt->xp_p1))->xdrs),
+           args_ptr));
+}
+
+static bool_t
+svc_vc_freeargs(xprt, xdr_args, args_ptr)
+       SVCXPRT *xprt;
+       xdrproc_t xdr_args;
+       caddr_t args_ptr;
+{
+       XDR *xdrs;
+
+       _DIAGASSERT(xprt != NULL);
+       /* args_ptr may be NULL */
+
+       xdrs = &(((struct cf_conn *)(xprt->xp_p1))->xdrs);
+
+       xdrs->x_op = XDR_FREE;
+       return ((*xdr_args)(xdrs, args_ptr));
+}
+
+static bool_t
+svc_vc_reply(xprt, msg)
+       SVCXPRT *xprt;
+       struct rpc_msg *msg;
+{
+       struct cf_conn *cd;
+       XDR *xdrs;
+       bool_t rstat;
+
+       _DIAGASSERT(xprt != NULL);
+       _DIAGASSERT(msg != NULL);
+
+       cd = (struct cf_conn *)(xprt->xp_p1);
+       xdrs = &(cd->xdrs);
+
+       xdrs->x_op = XDR_ENCODE;
+       msg->rm_xid = cd->x_id;
+       rstat = xdr_replymsg(xdrs, msg);
+       (void)xdrrec_endofrecord(xdrs, TRUE);
+       return (rstat);
+}
+
+static void
+svc_vc_ops(xprt)
+       SVCXPRT *xprt;
+{
+       static struct xp_ops ops;
+       static struct xp_ops2 ops2;
+#ifdef _REENTRANT
+       extern mutex_t ops_lock;
+#endif
+
+/* VARIABLES PROTECTED BY ops_lock: ops, ops2 */
+
+       mutex_lock(&ops_lock);
+       if (ops.xp_recv == NULL) {
+               ops.xp_recv = svc_vc_recv;
+               ops.xp_stat = svc_vc_stat;
+               ops.xp_getargs = svc_vc_getargs;
+               ops.xp_reply = svc_vc_reply;
+               ops.xp_freeargs = svc_vc_freeargs;
+               ops.xp_destroy = svc_vc_destroy;
+               ops2.xp_control = svc_vc_control;
+       }
+       xprt->xp_ops = &ops;
+       xprt->xp_ops2 = &ops2;
+       mutex_unlock(&ops_lock);
+}
+
+static void
+svc_vc_rendezvous_ops(xprt)
+       SVCXPRT *xprt;
+{
+       static struct xp_ops ops;
+       static struct xp_ops2 ops2;
+#ifdef _REENTRANT
+       extern mutex_t ops_lock;
+#endif
+/* XXXGCC vax compiler unhappy otherwise */
+#ifdef __vax__     
+extern void abort(void);
+#endif
+
+       mutex_lock(&ops_lock);
+       if (ops.xp_recv == NULL) {
+               ops.xp_recv = rendezvous_request;
+               ops.xp_stat = rendezvous_stat;
+               ops.xp_getargs =
+                   (bool_t (*) __P((SVCXPRT *, xdrproc_t, caddr_t)))abort;
+               ops.xp_reply =
+                   (bool_t (*) __P((SVCXPRT *, struct rpc_msg *)))abort;
+               ops.xp_freeargs =
+                   (bool_t (*) __P((SVCXPRT *, xdrproc_t, caddr_t)))abort;
+               ops.xp_destroy = svc_vc_destroy;
+               ops2.xp_control = svc_vc_rendezvous_control;
+       }
+       xprt->xp_ops = &ops;
+       xprt->xp_ops2 = &ops2;
+       mutex_unlock(&ops_lock);
+}
+
+/*
+ * Destroy xprts that have not have had any activity in 'timeout' seconds.
+ * If 'cleanblock' is true, blocking connections (the default) are also
+ * cleaned. If timeout is 0, the least active connection is picked.
+ */
+bool_t
+__svc_clean_idle(fd_set *fds, int timeout, bool_t cleanblock)
+{
+       int i, ncleaned;
+       SVCXPRT *xprt, *least_active;
+       struct timeval tv, tdiff, tmax;
+       struct cf_conn *cd;
+
+       gettimeofday(&tv, NULL);
+       tmax.tv_sec = tmax.tv_usec = 0;
+       least_active = NULL;
+       rwlock_wrlock(&svc_fd_lock);
+       for (i = ncleaned = 0; i <= svc_maxfd; i++) {
+               if (FD_ISSET(i, fds)) {
+                       xprt = __svc_xports[i];
+                       if (xprt == NULL || xprt->xp_ops == NULL ||
+                           xprt->xp_ops->xp_recv != svc_vc_recv)
+                               continue;
+                       cd = (struct cf_conn *)xprt->xp_p1;
+                       if (!cleanblock && !cd->nonblock)
+                               continue;
+                       if (timeout == 0) {
+                               timersub(&tv, &cd->last_recv_time, &tdiff);
+                               if (timercmp(&tdiff, &tmax, >)) {
+                                       tmax = tdiff;
+                                       least_active = xprt;
+                               }
+                               continue;
+                       }
+                       if (tv.tv_sec - cd->last_recv_time.tv_sec > timeout) {
+                               __xprt_unregister_unlocked(xprt);
+                               __svc_vc_dodestroy(xprt);
+                               ncleaned++;
+                       }
+               }
+       }
+       if (timeout == 0 && least_active != NULL) {
+               __xprt_unregister_unlocked(least_active);
+               __svc_vc_dodestroy(least_active);
+               ncleaned++;
+       }
+       rwlock_unlock(&svc_fd_lock);
+       return ncleaned > 0 ? TRUE : FALSE;
+}
diff --git a/lib/nbsd_libc/rpc/xdr.3 b/lib/nbsd_libc/rpc/xdr.3
new file mode 100644 (file)
index 0000000..4b606ca
--- /dev/null
@@ -0,0 +1,514 @@
+.\"    @(#)xdr.3n      2.2 88/08/03 4.0 RPCSRC; from 1.16 88/03/14 SMI
+.\"    $NetBSD: xdr.3,v 1.12 2009/10/13 21:39:55 joerg Exp $
+.\"
+.Dd April 17, 2003
+.Dt XDR 3
+.Os
+.Sh NAME
+.Nm xdr ,
+.Nm xdr_array ,
+.Nm xdr_bool ,
+.Nm xdr_bytes ,
+.Nm xdr_char ,
+.Nm xdr_destroy ,
+.Nm xdr_double ,
+.Nm xdr_enum ,
+.Nm xdr_float ,
+.Nm xdr_free ,
+.Nm xdr_getpos ,
+.Nm xdr_hyper ,
+.Nm xdr_inline ,
+.Nm xdr_int ,
+.Nm xdr_long ,
+.Nm xdr_longlong_t ,
+.Nm xdrmem_create ,
+.Nm xdr_opaque ,
+.Nm xdr_pointer ,
+.Nm xdrrec_create ,
+.Nm xdrrec_endofrecord ,
+.Nm xdrrec_eof ,
+.Nm xdrrec_skiprecord ,
+.Nm xdr_reference ,
+.Nm xdr_setpos ,
+.Nm xdr_short ,
+.Nm xdrstdio_create ,
+.Nm xdr_string ,
+.Nm xdr_u_char ,
+.Nm xdr_u_hyper ,
+.Nm xdr_u_long ,
+.Nm xdr_u_longlong_t ,
+.Nm xdr_u_short ,
+.Nm xdr_union ,
+.Nm xdr_vector ,
+.Nm xdr_void ,
+.Nm xdr_wrapstring
+.Nd library routines for external data representation
+.Sh SYNOPSIS
+.Ft int
+.Fn xdr_array "XDR *xdrs" "char **arrp" "u_int *sizep" "u_int maxsize" \
+"u_int elsize" "xdrproc_t elproc"
+.Ft int
+.Fn xdr_bool "XDR *xdrs" "bool_t *bp"
+.Ft int
+.Fn xdr_bytes "XDR *xdrs" "char **sp" "u_int *sizep" "u_int maxsize"
+.Ft int
+.Fn xdr_char "XDR *xdrs" "char *cp"
+.Ft void
+.Fn xdr_destroy "XDR *xdrs"
+.Ft int
+.Fn xdr_double "XDR *xdrs" "double *dp"
+.Ft int
+.Fn xdr_enum "XDR *xdrs" "enum_t *ep"
+.Ft int
+.Fn xdr_float "XDR *xdrs" "float *fp"
+.Ft void
+.Fn xdr_free "xdrproc_t proc" "char *objp"
+.Ft u_int
+.Fn xdr_getpos "XDR *xdrs"
+.Ft int
+.Fn xdr_hyper "XDR *xdrs" "longlong_t *llp"
+.Ft long *
+.Fn xdr_inline "XDR *xdrs" "int len"
+.Ft int
+.Fn xdr_int "XDR *xdrs" "int *ip"
+.Ft int
+.Fn xdr_long "XDR *xdrs" "long *lp"
+.Ft int
+.Fn xdr_longlong_t "XDR *xdrs" "longlong_t *llp"
+.Ft void
+.Fn xdrmem_create "XDR *xdrs" "char *addr" "u_int size" \
+"enum xdr_op op"
+.Ft int
+.Fn xdr_opaque "XDR *xdrs" "char *cp" "u_int cnt"
+.Ft int
+.Fn xdr_pointer "XDR *xdrs" "char **objpp" "u_int objsize" \
+"xdrproc_t xdrobj"
+.Ft void
+.Fn xdrrec_create "XDR *xdrs" "u_int sendsize" "u_int recvsize" \
+"char *handle" "int (*readit)()" "int (*writeit)()"
+.Ft int
+.Fn xdrrec_endofrecord "XDR *xdrs" "int sendnow"
+.Ft int
+.Fn xdrrec_eof "XDR *xdrs"
+.Ft int
+.Fn xdrrec_skiprecord "XDR *xdrs"
+.Ft int
+.Fn xdr_reference "XDR *xdrs" "char **pp" "u_int size" \
+"xdrproc_t proc"
+.Ft int
+.Fn xdr_setpos "XDR *xdrs" "u_int pos"
+.Ft int
+.Fn xdr_short "XDR *xdrs" "short *sp"
+.Ft void
+.Fn xdrstdio_create "XDR *xdrs" "FILE *file" "enum xdr_op op"
+.Ft int
+.Fn xdr_string "XDR *xdrs" "char **sp" "u_int maxsize"
+.Ft int
+.Fn xdr_u_char "XDR *xdrs" "unsigned char *ucp"
+.Ft int
+.Fn xdr_u_hyper "XDR *xdrs" "u_longlong_t *ullp"
+.Ft int
+.Fn xdr_u_int "XDR *xdrs" "unsigned *up"
+.Ft int
+.Fn xdr_u_long "XDR *xdrs" "unsigned long *ulp"
+.Ft int
+.Fn xdr_u_longlong_t "XDR *xdrs" "u_longlong_t *ullp"
+.Ft int
+.Fn xdr_u_short "XDR *xdrs" "unsigned short *usp"
+.Ft int
+.Fn xdr_union "XDR *xdrs" "int *dscmp" "char *unp" \
+"struct xdr_discrim *choices" "bool_t (*defaultarm)(\|)"
+.Ft int
+.Fn xdr_vector "XDR *xdrs" "char *arrp" "u_int size" \
+"u_int elsize" "xdrproc_t elproc"
+.Ft int
+.Fn xdr_void "void"
+.Ft int
+.Fn xdr_wrapstring "XDR *xdrs" "char **sp"
+.Sh DESCRIPTION
+These routines allow C programmers to describe
+arbitrary data structures in a machine-independent fashion.
+Data for remote procedure calls are transmitted using these
+routines.
+.Bl -tag -width xxx
+.It Fn xdr_array
+A filter primitive that translates between variable-length
+arrays and their corresponding external representations.
+The parameter
+.Fa arrp
+is the address of the pointer to the array, while
+.Fa sizep
+is the address of the element count of the array;
+this element count cannot exceed
+.Fa maxsize .
+The parameter
+.Fa elsize
+is the
+.Em sizeof
+each of the array's elements, and
+.Fa elproc
+is an XDR filter that translates between the array elements' C form,
+and their external representation.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_bool
+A filter primitive that translates between booleans (C integers)
+and their external representations.
+When encoding data, this filter produces values of either one or
+zero.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_bytes
+A filter primitive that translates between counted byte
+strings and their external representations.
+The parameter
+.Fa sp
+is the address of the string pointer.
+The length of the string is located at address
+.Fa sizep ;
+strings cannot be longer than
+.Fa maxsize .
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_char
+A filter primitive that translates between C characters
+and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+Note: encoded characters are not packed, and occupy 4 bytes each.
+For arrays of characters, it is worthwhile to consider
+.Fn xdr_bytes ,
+.Fn xdr_opaque
+or
+.Fn xdr_string .
+.It Fn xdr_destroy
+A macro that invokes the destroy routine associated with the XDR
+stream,
+.Fa xdrs .
+Destruction usually involves freeing private data structures
+associated with the stream.
+Using
+.Fa xdrs
+after invoking
+.Fn xdr_destroy
+is undefined.
+.It Fn xdr_double
+A filter primitive that translates between C double precision numbers
+and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_enum
+A filter primitive that translates between C enums (actually integers)
+and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_float
+A filter primitive that translates between C floats
+and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_free
+Generic freeing routine.
+The first argument is the XDR routine for the object being freed.
+The second argument is a pointer to the object itself.
+Note: the pointer passed to this routine is
+.Em not
+freed, but what it points to
+.Em is
+freed (recursively).
+.It Fn xdr_getpos
+A macro that invokes the get-position routine associated with the XDR
+stream,
+.Fa xdrs .
+The routine returns an unsigned integer, which indicates the position
+of the XDR byte stream.
+A desirable feature of XDR streams is that simple arithmetic works
+with this number, although the XDR stream instances need not guarantee
+this.
+.It Fn xdr_hyper
+A filter primitive that translates between ANSI C long long integers
+and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_inline
+A macro that invokes the in-line routine associated with the XDR
+stream,
+.Fa xdrs .
+The routine returns a pointer
+to a contiguous piece of the stream's buffer;
+.Fa len
+is the byte length of the desired buffer.
+Note: pointer is cast to
+.Vt "long *" .
+.Pp
+Warning:
+.Fn xdr_inline
+may return
+.Dv NULL
+if it cannot allocate a contiguous piece of a buffer.
+Therefore the behavior may vary among stream instances;
+it exists for the sake of efficiency.
+.It Fn xdr_int
+A filter primitive that translates between C integers
+and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_long
+A filter primitive that translates between C long integers
+and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_longlong_t
+A filter primitive that translates between ANSI C long long integers
+and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdrmem_create
+This routine initializes the XDR stream object pointed to by
+.Fa xdrs .
+The stream's data is written to, or read from,
+a chunk of memory at location
+.Fa addr
+whose length is no more than
+.Fa size
+bytes long.
+The
+.Fa op
+determines the direction of the XDR stream (either
+.Dv XDR_ENCODE ,
+.Dv XDR_DECODE ,
+or
+.Dv XDR_FREE ) .
+.It Fn xdr_opaque
+A filter primitive that translates between fixed size opaque data
+and its external representation.
+The parameter
+.Fa cp
+is the address of the opaque object, and
+.Fa cnt
+is its size in bytes.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_pointer
+Like
+.Fn xdr_reference
+except that it serializes
+.Dv NULL
+pointers, whereas
+.Fn xdr_reference
+does not.
+Thus,
+.Fn xdr_pointer
+can represent recursive data structures, such as binary trees or
+linked lists.
+.It Fn xdrrec_create
+This routine initializes the XDR stream object pointed to by
+.Fa xdrs .
+The stream's data is written to a buffer of size
+.Fa sendsize ;
+a value of zero indicates the system should use a suitable default.
+The stream's data is read from a buffer of size
+.Fa recvsize ;
+it too can be set to a suitable default by passing a zero value.
+When a stream's output buffer is full,
+.Fa writeit
+is called.
+Similarly, when a stream's input buffer is empty,
+.Fa readit
+is called.
+The behavior of these two routines is similar to the system calls
+.Xr read 2
+and
+.Xr write 2 ,
+except that
+.Fa handle
+is passed to the former routines as the first parameter.
+Note: the XDR stream's
+.Fa op
+field must be set by the caller.
+.Pp
+Warning: this XDR stream implements an intermediate record stream.
+Therefore there are additional bytes in the stream
+to provide record boundary information.
+.It Fn xdrrec_endofrecord
+This routine can be invoked only on streams created by
+.Fn xdrrec_create .
+The data in the output buffer is marked as a completed record,
+and the output buffer is optionally written out if
+.Fa sendnow
+is non-zero.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdrrec_eof
+This routine can be invoked only on streams created by
+.Fn xdrrec_create .
+After consuming the rest of the current record in the stream,
+this routine returns one if the stream has no more input,
+zero otherwise.
+.It Fn xdrrec_skiprecord
+This routine can be invoked only on streams created by
+.Fn xdrrec_create .
+It tells the XDR implementation that the rest of the current record
+in the stream's input buffer should be discarded.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_reference
+A primitive that provides pointer chasing within structures.
+The parameter
+.Fa pp
+is the address of the pointer;
+.Fa size
+is the
+.Em sizeof
+the structure that
+.Fa *pp
+points to; and
+.Fa proc
+is an XDR procedure that filters the structure
+between its C form and its external representation.
+This routine returns one if it succeeds, zero otherwise.
+.Pp
+Warning: this routine does not understand
+.Dv NULL
+pointers.
+Use
+.Fn xdr_pointer
+instead.
+.It Fn xdr_setpos
+A macro that invokes the set position routine associated with the XDR
+stream
+.Fa xdrs .
+The parameter
+.Fa pos
+is a position value obtained from
+.Fn xdr_getpos .
+This routine returns one if the XDR stream could be repositioned,
+and zero otherwise.
+.Pp
+Warning: it is difficult to reposition some types of XDR streams, so
+this routine may fail with one type of stream and succeed with
+another.
+.It Fn xdr_short
+A filter primitive that translates between C short integers
+and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdrstdio_create
+This routine initializes the XDR stream object pointed to by
+.Fa xdrs .
+The XDR stream data is written to, or read from, the Standard I/O
+stream
+.Fa file .
+The parameter
+.Fa op
+determines the direction of the XDR stream (either
+.Dv XDR_ENCODE ,
+.Dv XDR_DECODE ,
+or
+.Dv XDR_FREE ) .
+.Pp
+Warning: the destroy routine associated with such XDR streams calls
+.Xr fflush 3
+on the file stream, but never
+.Xr fclose 3 .
+.It Fn xdr_string
+A filter primitive that translates between C strings and
+their corresponding external representations.
+Strings cannot be longer than
+.Fa maxsize .
+Note:
+.Fa sp
+is the address of the string's pointer.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_u_char
+A filter primitive that translates between unsigned C characters
+and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_u_hyper
+A filter primitive that translates between unsigned ANSI C long long
+integers and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_u_int
+A filter primitive that translates between C unsigned integers
+ and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_u_long
+A filter primitive that translates between C unsigned long integers
+and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_u_longlong_t
+A filter primitive that translates between unsigned ANSI C long long
+integers and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_u_short
+A filter primitive that translates between C unsigned short integers
+and their external representations.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_union
+A filter primitive that translates between a discriminated C union
+and its corresponding external representation.
+It first translates the discriminant of the union located at
+.Fa dscmp .
+This discriminant is always an enum_t.
+Next the union located at
+.Fa unp
+is translated.
+The parameter
+.Fa choices
+is a pointer to an array of
+.Fn xdr_discrim
+structures.
+Each structure contains an ordered pair of
+.Fa [ value ,
+.Fa proc ] .
+If the union's discriminant is equal to the associated
+.Fa value ,
+then the
+.Fa proc
+is called to translate the union.
+The end of the
+.Fn xdr_discrim
+structure array is denoted by a routine of value
+.Dv NULL .
+If the discriminant is not found in the
+.Fa choices
+array, then the
+.Fa defaultarm
+procedure is called (if it is not
+.Dv NULL ) .
+Returns one if it succeeds, zero otherwise.
+.It Fn xdr_vector
+A filter primitive that translates between fixed-length
+arrays and their corresponding external representations.
+The parameter
+.Fa arrp
+is the address of the pointer to the array, while
+.Fa size
+is the element count of the array.
+The parameter
+.Fa elsize
+is the
+.Em sizeof
+each of the array's elements, and
+.Fa elproc
+is an XDR filter that translates between the array elements' C form,
+and their external representation.
+This routine returns one if it succeeds, zero otherwise.
+.It Fn xdr_void
+This routine always returns one.
+It may be passed to RPC routines that require a function parameter,
+where nothing is to be done.
+.It Fn xdr_wrapstring
+A primitive that calls
+.Fn xdr_string "xdrs" "sp" "MAXUN.UNSIGNED" ;
+where
+.Dv MAXUN.UNSIGNED
+is the maximum value of an unsigned integer.
+.Fn xdr_wrapstring
+is handy because the RPC package passes a maximum of two XDR
+routines as parameters, and
+.Fn xdr_string ,
+one of the most frequently used primitives, requires three.
+Returns one if it succeeds, zero otherwise.
+.El
+.Sh SEE ALSO
+.Xr rpc 3
+.Pp
+The following manuals:
+.Rs
+.%B "eXternal Data Representation Standard: Protocol Specification"
+.Re
+.Rs
+.%B "eXternal Data Representation: Sun Technical Notes"
+.Re
+.Rs
+.%A Sun Microsystems, Inc., USC-ISI
+.%T "XDR: External Data Representation Standard"
+.%R "RFC 1014, USC-ISI"
+.%V 1014
+.Re
diff --git a/lib/nbsd_libc/rpc/xdr.c b/lib/nbsd_libc/rpc/xdr.c
new file mode 100644 (file)
index 0000000..e084d0d
--- /dev/null
@@ -0,0 +1,1003 @@
+/*     $NetBSD: xdr.c,v 1.28 2006/05/14 02:15:31 christos Exp $        */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)xdr.c 1.35 87/08/12";
+static char *sccsid = "@(#)xdr.c       2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: xdr.c,v 1.28 2006/05/14 02:15:31 christos Exp $");
+#endif
+#endif
+
+/*
+ * xdr.c, Generic XDR routines implementation.
+ *
+ * Copyright (C) 1986, Sun Microsystems, Inc.
+ *
+ * These are the "generic" xdr routines used to serialize and de-serialize
+ * most common data items.  See xdr.h for more info on the interface to
+ * xdr.
+ */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <err.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+
+#ifdef __weak_alias
+__weak_alias(xdr_bool,_xdr_bool)
+__weak_alias(xdr_bytes,_xdr_bytes)
+__weak_alias(xdr_char,_xdr_char)
+__weak_alias(xdr_enum,_xdr_enum)
+__weak_alias(xdr_free,_xdr_free)
+__weak_alias(xdr_hyper,_xdr_hyper)
+__weak_alias(xdr_int,_xdr_int)
+__weak_alias(xdr_int16_t,_xdr_int16_t)
+__weak_alias(xdr_int32_t,_xdr_int32_t)
+__weak_alias(xdr_int64_t,_xdr_int64_t)
+__weak_alias(xdr_long,_xdr_long)
+__weak_alias(xdr_longlong_t,_xdr_longlong_t)
+__weak_alias(xdr_netobj,_xdr_netobj)
+__weak_alias(xdr_opaque,_xdr_opaque)
+__weak_alias(xdr_short,_xdr_short)
+__weak_alias(xdr_string,_xdr_string)
+__weak_alias(xdr_u_char,_xdr_u_char)
+__weak_alias(xdr_u_hyper,_xdr_u_hyper)
+__weak_alias(xdr_u_int,_xdr_u_int)
+__weak_alias(xdr_u_int16_t,_xdr_u_int16_t)
+__weak_alias(xdr_u_int32_t,_xdr_u_int32_t)
+__weak_alias(xdr_u_int64_t,_xdr_u_int64_t)
+__weak_alias(xdr_u_long,_xdr_u_long)
+__weak_alias(xdr_u_longlong_t,_xdr_u_longlong_t)
+__weak_alias(xdr_u_short,_xdr_u_short)
+__weak_alias(xdr_union,_xdr_union)
+__weak_alias(xdr_void,_xdr_void)
+__weak_alias(xdr_wrapstring,_xdr_wrapstring)
+#endif
+
+/*
+ * constants specific to the xdr "protocol"
+ */
+#define XDR_FALSE      ((long) 0)
+#define XDR_TRUE       ((long) 1)
+#define LASTUNSIGNED   ((u_int) 0-1)
+
+/*
+ * for unit alignment
+ */
+static const char xdr_zero[BYTES_PER_XDR_UNIT] = { 0, 0, 0, 0 };
+
+/*
+ * Free a data structure using XDR
+ * Not a filter, but a convenient utility nonetheless
+ */
+void
+xdr_free(proc, objp)
+       xdrproc_t proc;
+       char *objp;
+{
+       XDR x;
+       
+       x.x_op = XDR_FREE;
+       (*proc)(&x, objp);
+}
+
+/*
+ * XDR nothing
+ */
+bool_t
+xdr_void(/* xdrs, addr */)
+       /* XDR *xdrs; */
+       /* caddr_t addr; */
+{
+
+       return (TRUE);
+}
+
+
+/*
+ * XDR integers
+ */
+bool_t
+xdr_int(xdrs, ip)
+       XDR *xdrs;
+       int *ip;
+{
+       long l;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(ip != NULL);
+
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+               l = (long) *ip;
+               return (XDR_PUTLONG(xdrs, &l));
+
+       case XDR_DECODE:
+               if (!XDR_GETLONG(xdrs, &l)) {
+                       return (FALSE);
+               }
+               *ip = (int) l;
+               return (TRUE);
+
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+/*
+ * XDR unsigned integers
+ */
+bool_t
+xdr_u_int(xdrs, up)
+       XDR *xdrs;
+       u_int *up;
+{
+       u_long l;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(up != NULL);
+
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+               l = (u_long) *up;
+               return (XDR_PUTLONG(xdrs, (long *)&l));
+
+       case XDR_DECODE:
+               if (!XDR_GETLONG(xdrs, (long *)&l)) {
+                       return (FALSE);
+               }
+               *up = (u_int) l;
+               return (TRUE);
+
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+
+/*
+ * XDR long integers
+ * same as xdr_u_long - open coded to save a proc call!
+ */
+bool_t
+xdr_long(xdrs, lp)
+       XDR *xdrs;
+       long *lp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(lp != NULL);
+
+       switch (xdrs->x_op) {
+       case XDR_ENCODE:
+               return (XDR_PUTLONG(xdrs, lp));
+       case XDR_DECODE:
+               return (XDR_GETLONG(xdrs, lp));
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+/*
+ * XDR unsigned long integers
+ * same as xdr_long - open coded to save a proc call!
+ */
+bool_t
+xdr_u_long(xdrs, ulp)
+       XDR *xdrs;
+       u_long *ulp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(ulp != NULL);
+
+       switch (xdrs->x_op) {
+       case XDR_ENCODE:
+               return (XDR_PUTLONG(xdrs, (long *)ulp));
+       case XDR_DECODE:
+               return (XDR_GETLONG(xdrs, (long *)ulp));
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+
+/*
+ * XDR 32-bit integers
+ * same as xdr_u_int32_t - open coded to save a proc call!
+ */
+bool_t
+xdr_int32_t(xdrs, int32_p)
+       XDR *xdrs;
+       int32_t *int32_p;
+{
+       long l;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(int32_p != NULL);
+
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+               l = (long) *int32_p;
+               return (XDR_PUTLONG(xdrs, &l));
+
+       case XDR_DECODE:
+               if (!XDR_GETLONG(xdrs, &l)) {
+                       return (FALSE);
+               }
+               *int32_p = (int32_t) l;
+               return (TRUE);
+
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+/*
+ * XDR unsigned 32-bit integers
+ * same as xdr_int32_t - open coded to save a proc call!
+ */
+bool_t
+xdr_u_int32_t(xdrs, u_int32_p)
+       XDR *xdrs;
+       u_int32_t *u_int32_p;
+{
+       u_long l;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(u_int32_p != NULL);
+
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+               l = (u_long) *u_int32_p;
+               return (XDR_PUTLONG(xdrs, (long *)&l));
+
+       case XDR_DECODE:
+               if (!XDR_GETLONG(xdrs, (long *)&l)) {
+                       return (FALSE);
+               }
+               *u_int32_p = (u_int32_t) l;
+               return (TRUE);
+
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+
+/*
+ * XDR short integers
+ */
+bool_t
+xdr_short(xdrs, sp)
+       XDR *xdrs;
+       short *sp;
+{
+       long l;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(sp != NULL);
+
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+               l = (long) *sp;
+               return (XDR_PUTLONG(xdrs, &l));
+
+       case XDR_DECODE:
+               if (!XDR_GETLONG(xdrs, &l)) {
+                       return (FALSE);
+               }
+               *sp = (short) l;
+               return (TRUE);
+
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+/*
+ * XDR unsigned short integers
+ */
+bool_t
+xdr_u_short(xdrs, usp)
+       XDR *xdrs;
+       u_short *usp;
+{
+       u_long l;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(usp != NULL);
+
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+               l = (u_long) *usp;
+               return (XDR_PUTLONG(xdrs, (long *)&l));
+
+       case XDR_DECODE:
+               if (!XDR_GETLONG(xdrs, (long *)&l)) {
+                       return (FALSE);
+               }
+               *usp = (u_short) l;
+               return (TRUE);
+
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+
+/*
+ * XDR 16-bit integers
+ */
+bool_t
+xdr_int16_t(xdrs, int16_p)
+       XDR *xdrs;
+       int16_t *int16_p;
+{
+       long l;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(int16_p != NULL);
+
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+               l = (long) *int16_p;
+               return (XDR_PUTLONG(xdrs, &l));
+
+       case XDR_DECODE:
+               if (!XDR_GETLONG(xdrs, &l)) {
+                       return (FALSE);
+               }
+               *int16_p = (int16_t) l;
+               return (TRUE);
+
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+/*
+ * XDR unsigned 16-bit integers
+ */
+bool_t
+xdr_u_int16_t(xdrs, u_int16_p)
+       XDR *xdrs;
+       u_int16_t *u_int16_p;
+{
+       u_long l;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(u_int16_p != NULL);
+
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+               l = (u_long) *u_int16_p;
+               return (XDR_PUTLONG(xdrs, (long *)&l));
+
+       case XDR_DECODE:
+               if (!XDR_GETLONG(xdrs, (long *)&l)) {
+                       return (FALSE);
+               }
+               *u_int16_p = (u_int16_t) l;
+               return (TRUE);
+
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+
+/*
+ * XDR a char
+ */
+bool_t
+xdr_char(xdrs, cp)
+       XDR *xdrs;
+       char *cp;
+{
+       int i;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(cp != NULL);
+
+       i = (*cp);
+       if (!xdr_int(xdrs, &i)) {
+               return (FALSE);
+       }
+       *cp = i;
+       return (TRUE);
+}
+
+/*
+ * XDR an unsigned char
+ */
+bool_t
+xdr_u_char(xdrs, cp)
+       XDR *xdrs;
+       u_char *cp;
+{
+       u_int u;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(cp != NULL);
+
+       u = (*cp);
+       if (!xdr_u_int(xdrs, &u)) {
+               return (FALSE);
+       }
+       *cp = u;
+       return (TRUE);
+}
+
+/*
+ * XDR booleans
+ */
+bool_t
+xdr_bool(xdrs, bp)
+       XDR *xdrs;
+       bool_t *bp;
+{
+       long lb;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(bp != NULL);
+
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+               lb = *bp ? XDR_TRUE : XDR_FALSE;
+               return (XDR_PUTLONG(xdrs, &lb));
+
+       case XDR_DECODE:
+               if (!XDR_GETLONG(xdrs, &lb)) {
+                       return (FALSE);
+               }
+               *bp = (lb == XDR_FALSE) ? FALSE : TRUE;
+               return (TRUE);
+
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+/*
+ * XDR enumerations
+ */
+bool_t
+xdr_enum(xdrs, ep)
+       XDR *xdrs;
+       enum_t *ep;
+{
+       long l;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(ep != NULL);
+
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+               l = (long) *ep;
+               return (XDR_PUTLONG(xdrs, &l));
+
+       case XDR_DECODE:
+               if (!XDR_GETLONG(xdrs, &l)) {
+                       return (FALSE);
+               }
+               *ep = (enum_t) l;
+               return (TRUE);
+
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+/*
+ * XDR opaque data
+ * Allows the specification of a fixed size sequence of opaque bytes.
+ * cp points to the opaque object and cnt gives the byte length.
+ */
+bool_t
+xdr_opaque(xdrs, cp, cnt)
+       XDR *xdrs;
+       caddr_t cp;
+       u_int cnt;
+{
+       u_int rndup;
+       static int crud[BYTES_PER_XDR_UNIT];
+
+       _DIAGASSERT(xdrs != NULL);
+               /*
+                * if no data we are done
+                */
+       if (cnt == 0)
+               return (TRUE);
+       _DIAGASSERT(cp != NULL);
+
+       /*
+        * round byte count to full xdr units
+        */
+       rndup = cnt % BYTES_PER_XDR_UNIT;
+       if (rndup > 0)
+               rndup = BYTES_PER_XDR_UNIT - rndup;
+
+       if (xdrs->x_op == XDR_DECODE) {
+               if (!XDR_GETBYTES(xdrs, cp, cnt)) {
+                       return (FALSE);
+               }
+               if (rndup == 0)
+                       return (TRUE);
+               return (XDR_GETBYTES(xdrs, (caddr_t)(void *)crud, rndup));
+       }
+
+       if (xdrs->x_op == XDR_ENCODE) {
+               if (!XDR_PUTBYTES(xdrs, cp, cnt)) {
+                       return (FALSE);
+               }
+               if (rndup == 0)
+                       return (TRUE);
+               return (XDR_PUTBYTES(xdrs, xdr_zero, rndup));
+       }
+
+       if (xdrs->x_op == XDR_FREE) {
+               return (TRUE);
+       }
+
+       return (FALSE);
+}
+
+/*
+ * XDR counted bytes
+ * *cpp is a pointer to the bytes, *sizep is the count.
+ * If *cpp is NULL maxsize bytes are allocated
+ */
+bool_t
+xdr_bytes(xdrs, cpp, sizep, maxsize)
+       XDR *xdrs;
+       char **cpp;
+       u_int *sizep;
+       u_int maxsize;
+{
+       char *sp;               /* sp is the actual string pointer */
+       u_int nodesize;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(cpp != NULL);
+       _DIAGASSERT(sizep != NULL);
+
+       sp = *cpp;
+
+       /*
+        * first deal with the length since xdr bytes are counted
+        */
+       if (! xdr_u_int(xdrs, sizep)) {
+               return (FALSE);
+       }
+       nodesize = *sizep;
+       if ((nodesize > maxsize) && (xdrs->x_op != XDR_FREE)) {
+               return (FALSE);
+       }
+
+       /*
+        * now deal with the actual bytes
+        */
+       switch (xdrs->x_op) {
+
+       case XDR_DECODE:
+               if (nodesize == 0) {
+                       return (TRUE);
+               }
+               if (sp == NULL) {
+                       *cpp = sp = mem_alloc(nodesize);
+               }
+               if (sp == NULL) {
+                       warnx("xdr_bytes: out of memory");
+                       return (FALSE);
+               }
+               /* FALLTHROUGH */
+
+       case XDR_ENCODE:
+               return (xdr_opaque(xdrs, sp, nodesize));
+
+       case XDR_FREE:
+               if (sp != NULL) {
+                       mem_free(sp, nodesize);
+                       *cpp = NULL;
+               }
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+/*
+ * Implemented here due to commonality of the object.
+ */
+bool_t
+xdr_netobj(xdrs, np)
+       XDR *xdrs;
+       struct netobj *np;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(np != NULL);
+
+       return (xdr_bytes(xdrs, &np->n_bytes, &np->n_len, MAX_NETOBJ_SZ));
+}
+
+/*
+ * XDR a descriminated union
+ * Support routine for discriminated unions.
+ * You create an array of xdrdiscrim structures, terminated with
+ * an entry with a null procedure pointer.  The routine gets
+ * the discriminant value and then searches the array of xdrdiscrims
+ * looking for that value.  It calls the procedure given in the xdrdiscrim
+ * to handle the discriminant.  If there is no specific routine a default
+ * routine may be called.
+ * If there is no specific or default routine an error is returned.
+ */
+bool_t
+xdr_union(xdrs, dscmp, unp, choices, dfault)
+       XDR *xdrs;
+       enum_t *dscmp;          /* enum to decide which arm to work on */
+       char *unp;              /* the union itself */
+       const struct xdr_discrim *choices; /* [value, xdr proc] for each arm */
+       xdrproc_t dfault;       /* default xdr routine */
+{
+       enum_t dscm;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(dscmp != NULL);
+       _DIAGASSERT(unp != NULL);
+       _DIAGASSERT(choices != NULL);
+       /* dfault may be NULL */
+
+       /*
+        * we deal with the discriminator;  it's an enum
+        */
+       if (! xdr_enum(xdrs, dscmp)) {
+               return (FALSE);
+       }
+       dscm = *dscmp;
+
+       /*
+        * search choices for a value that matches the discriminator.
+        * if we find one, execute the xdr routine for that value.
+        */
+       for (; choices->proc != NULL_xdrproc_t; choices++) {
+               if (choices->value == dscm)
+                       return ((*(choices->proc))(xdrs, unp));
+       }
+
+       /*
+        * no match - execute the default xdr routine if there is one
+        */
+       return ((dfault == NULL_xdrproc_t) ? FALSE :
+           (*dfault)(xdrs, unp));
+}
+
+
+/*
+ * Non-portable xdr primitives.
+ * Care should be taken when moving these routines to new architectures.
+ */
+
+
+/*
+ * XDR null terminated ASCII strings
+ * xdr_string deals with "C strings" - arrays of bytes that are
+ * terminated by a NULL character.  The parameter cpp references a
+ * pointer to storage; If the pointer is null, then the necessary
+ * storage is allocated.  The last parameter is the max allowed length
+ * of the string as specified by a protocol.
+ */
+bool_t
+xdr_string(xdrs, cpp, maxsize)
+       XDR *xdrs;
+       char **cpp;
+       u_int maxsize;
+{
+       char *sp;               /* sp is the actual string pointer */
+       u_int size = 0;         /* XXX: GCC */
+       u_int nodesize;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(cpp != NULL);
+
+       sp = *cpp;
+
+       /*
+        * first deal with the length since xdr strings are counted-strings
+        */
+       switch (xdrs->x_op) {
+       case XDR_FREE:
+               if (sp == NULL) {
+                       return(TRUE);   /* already free */
+               }
+               /* FALLTHROUGH */
+       case XDR_ENCODE:
+               size = strlen(sp);
+               break;
+       case XDR_DECODE:
+               break;
+       }
+       if (! xdr_u_int(xdrs, &size)) {
+               return (FALSE);
+       }
+       if (size > maxsize) {
+               return (FALSE);
+       }
+       nodesize = size + 1;
+
+       /*
+        * now deal with the actual bytes
+        */
+       switch (xdrs->x_op) {
+
+       case XDR_DECODE:
+               if (nodesize == 0) {
+                       return (TRUE);
+               }
+               if (sp == NULL)
+                       *cpp = sp = mem_alloc(nodesize);
+               if (sp == NULL) {
+                       warnx("xdr_string: out of memory");
+                       return (FALSE);
+               }
+               sp[size] = 0;
+               /* FALLTHROUGH */
+
+       case XDR_ENCODE:
+               return (xdr_opaque(xdrs, sp, size));
+
+       case XDR_FREE:
+               mem_free(sp, nodesize);
+               *cpp = NULL;
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+/* 
+ * Wrapper for xdr_string that can be called directly from 
+ * routines like clnt_call
+ */
+bool_t
+xdr_wrapstring(xdrs, cpp)
+       XDR *xdrs;
+       char **cpp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(cpp != NULL);
+
+       return xdr_string(xdrs, cpp, LASTUNSIGNED);
+}
+
+/*
+ * NOTE: xdr_hyper(), xdr_u_hyper(), xdr_longlong_t(), and xdr_u_longlong_t()
+ * are in the "non-portable" section because they require that a `long long'
+ * be a 64-bit type.
+ *
+ *     --thorpej@NetBSD.org, November 30, 1999
+ */
+
+/*
+ * XDR 64-bit integers
+ */
+bool_t
+xdr_int64_t(xdrs, llp)
+       XDR *xdrs;
+       int64_t *llp;
+{
+       u_long ul[2];
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(llp != NULL);
+
+       switch (xdrs->x_op) {
+       case XDR_ENCODE:
+               ul[0] = (u_long)((u_int64_t)*llp >> 32) & 0xffffffff;
+               ul[1] = (u_long)((u_int64_t)*llp) & 0xffffffff;
+               if (XDR_PUTLONG(xdrs, (long *)&ul[0]) == FALSE)
+                       return (FALSE);
+               return (XDR_PUTLONG(xdrs, (long *)&ul[1]));
+       case XDR_DECODE:
+               if (XDR_GETLONG(xdrs, (long *)&ul[0]) == FALSE)
+                       return (FALSE);
+               if (XDR_GETLONG(xdrs, (long *)&ul[1]) == FALSE)
+                       return (FALSE);
+               *llp = (int64_t)
+                   (((u_int64_t)ul[0] << 32) | ((u_int64_t)ul[1]));
+               return (TRUE);
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+
+/*
+ * XDR unsigned 64-bit integers
+ */
+bool_t
+xdr_u_int64_t(xdrs, ullp)
+       XDR *xdrs;
+       u_int64_t *ullp;
+{
+       u_long ul[2];
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(ullp != NULL);
+
+       switch (xdrs->x_op) {
+       case XDR_ENCODE:
+               ul[0] = (u_long)(*ullp >> 32) & 0xffffffff;
+               ul[1] = (u_long)(*ullp) & 0xffffffff;
+               if (XDR_PUTLONG(xdrs, (long *)&ul[0]) == FALSE)
+                       return (FALSE);
+               return (XDR_PUTLONG(xdrs, (long *)&ul[1]));
+       case XDR_DECODE:
+               if (XDR_GETLONG(xdrs, (long *)&ul[0]) == FALSE)
+                       return (FALSE);
+               if (XDR_GETLONG(xdrs, (long *)&ul[1]) == FALSE)
+                       return (FALSE);
+               *ullp = (u_int64_t)
+                   (((u_int64_t)ul[0] << 32) | ((u_int64_t)ul[1]));
+               return (TRUE);
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+
+/*
+ * XDR hypers
+ */
+bool_t
+xdr_hyper(xdrs, llp)
+       XDR *xdrs;
+       longlong_t *llp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(llp != NULL);
+
+       /*
+        * Don't bother open-coding this; it's a fair amount of code.  Just
+        * call xdr_int64_t().
+        */
+       return (xdr_int64_t(xdrs, (int64_t *)llp));
+}
+
+
+/*
+ * XDR unsigned hypers
+ */
+bool_t
+xdr_u_hyper(xdrs, ullp)
+       XDR *xdrs;
+       u_longlong_t *ullp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(ullp != NULL);
+
+       /*
+        * Don't bother open-coding this; it's a fair amount of code.  Just
+        * call xdr_u_int64_t().
+        */
+       return (xdr_u_int64_t(xdrs, (u_int64_t *)ullp));
+}
+
+
+/*
+ * XDR longlong_t's
+ */
+bool_t
+xdr_longlong_t(xdrs, llp)
+       XDR *xdrs;
+       longlong_t *llp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(llp != NULL);
+
+       /*
+        * Don't bother open-coding this; it's a fair amount of code.  Just
+        * call xdr_int64_t().
+        */
+       return (xdr_int64_t(xdrs, (int64_t *)llp));
+}
+
+
+/*
+ * XDR u_longlong_t's
+ */
+bool_t
+xdr_u_longlong_t(xdrs, ullp)
+       XDR *xdrs;
+       u_longlong_t *ullp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(ullp != NULL);
+
+       /*
+        * Don't bother open-coding this; it's a fair amount of code.  Just
+        * call xdr_u_int64_t().
+        */
+       return (xdr_u_int64_t(xdrs, (u_int64_t *)ullp));
+}
diff --git a/lib/nbsd_libc/rpc/xdr_array.c b/lib/nbsd_libc/rpc/xdr_array.c
new file mode 100644 (file)
index 0000000..2ddfd34
--- /dev/null
@@ -0,0 +1,170 @@
+/*     $NetBSD: xdr_array.c,v 1.16 2005/08/05 10:39:05 wiz Exp $       */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)xdr_array.c 1.10 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)xdr_array.c 2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: xdr_array.c,v 1.16 2005/08/05 10:39:05 wiz Exp $");
+#endif
+#endif
+
+/*
+ * xdr_array.c, Generic XDR routines implementation.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ * These are the "non-trivial" xdr primitives used to serialize and de-serialize
+ * arrays.  See xdr.h for more info on the interface to xdr.
+ */
+
+#include "namespace.h"
+
+#include <err.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+
+#ifdef __weak_alias
+__weak_alias(xdr_array,_xdr_array)
+__weak_alias(xdr_vector,_xdr_vector)
+#endif
+
+/*
+ * XDR an array of arbitrary elements
+ * *addrp is a pointer to the array, *sizep is the number of elements.
+ * If addrp is NULL (*sizep * elsize) bytes are allocated.
+ * elsize is the size (in bytes) of each element, and elproc is the
+ * xdr procedure to call to handle each element of the array.
+ */
+bool_t
+xdr_array(xdrs, addrp, sizep, maxsize, elsize, elproc)
+       XDR *xdrs;
+       caddr_t *addrp;         /* array pointer */
+       u_int *sizep;           /* number of elements */
+       u_int maxsize;          /* max numberof elements */
+       u_int elsize;           /* size in bytes of each element */
+       xdrproc_t elproc;       /* xdr routine to handle each element */
+{
+       u_int i;
+       caddr_t target = *addrp;
+       u_int c;  /* the actual element count */
+       bool_t stat = TRUE;
+       u_int nodesize;
+
+       /* like strings, arrays are really counted arrays */
+       if (!xdr_u_int(xdrs, sizep))
+               return (FALSE);
+
+       c = *sizep;
+       if ((c > maxsize || UINT_MAX/elsize < c) &&
+           (xdrs->x_op != XDR_FREE))
+               return (FALSE);
+       nodesize = c * elsize;
+
+       /*
+        * if we are deserializing, we may need to allocate an array.
+        * We also save time by checking for a null array if we are freeing.
+        */
+       if (target == NULL)
+               switch (xdrs->x_op) {
+               case XDR_DECODE:
+                       if (c == 0)
+                               return (TRUE);
+                       *addrp = target = mem_alloc(nodesize);
+                       if (target == NULL) {
+                               warnx("xdr_array: out of memory");
+                               return (FALSE);
+                       }
+                       memset(target, 0, nodesize);
+                       break;
+
+               case XDR_FREE:
+                       return (TRUE);
+
+               case XDR_ENCODE:
+                       break;
+       }
+       
+       /*
+        * now we xdr each element of array
+        */
+       for (i = 0; (i < c) && stat; i++) {
+               stat = (*elproc)(xdrs, target);
+               target += elsize;
+       }
+
+       /*
+        * the array may need freeing
+        */
+       if (xdrs->x_op == XDR_FREE) {
+               mem_free(*addrp, nodesize);
+               *addrp = NULL;
+       }
+       return (stat);
+}
+
+/*
+ * xdr_vector():
+ *
+ * XDR a fixed length array. Unlike variable-length arrays,
+ * the storage of fixed length arrays is static and unfreeable.
+ * > basep: base of the array
+ * > size: size of the array
+ * > elemsize: size of each element
+ * > xdr_elem: routine to XDR each element
+ */
+bool_t
+xdr_vector(xdrs, basep, nelem, elemsize, xdr_elem)
+       XDR *xdrs;
+       char *basep;
+       u_int nelem;
+       u_int elemsize;
+       xdrproc_t xdr_elem;     
+{
+       u_int i;
+       char *elptr;
+
+       elptr = basep;
+       for (i = 0; i < nelem; i++) {
+               if (!(*xdr_elem)(xdrs, elptr)) {
+                       return(FALSE);
+               }
+               elptr += elemsize;
+       }
+       return(TRUE);   
+}
diff --git a/lib/nbsd_libc/rpc/xdr_float.c b/lib/nbsd_libc/rpc/xdr_float.c
new file mode 100644 (file)
index 0000000..60d778f
--- /dev/null
@@ -0,0 +1,319 @@
+/*     $NetBSD: xdr_float.c,v 1.35 2009/02/14 06:26:42 lukem Exp $     */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)xdr_float.c 1.12 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)xdr_float.c 2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: xdr_float.c,v 1.35 2009/02/14 06:26:42 lukem Exp $");
+#endif
+#endif
+
+/*
+ * xdr_float.c, Generic XDR routines implementation.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ * These are the "floating point" xdr routines used to (de)serialize
+ * most common data items.  See xdr.h for more info on the interface to
+ * xdr.
+ */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/param.h>
+
+#include <stdio.h>
+
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+
+#ifdef __weak_alias
+__weak_alias(xdr_double,_xdr_double)
+__weak_alias(xdr_float,_xdr_float)
+#endif
+
+/*
+ * NB: Not portable.
+ * This routine works on machines with IEEE754 FP and Vaxen.
+ */
+
+#if defined(__m68k__) || defined(__sparc__) || defined(__i386__) || \
+    defined(__mips__) || defined(__ns32k__) || defined(__alpha__) || \
+    defined(__arm__) || defined(__powerpc__) || defined(__sh__) || \
+    defined(__x86_64__) || defined(__hppa__) || defined(__ia64__)
+#include <machine/endian.h>
+#define IEEEFP
+#endif
+
+#if defined(__vax__)
+
+/* What IEEE single precision floating point looks like on a Vax */
+struct ieee_single {
+       unsigned int    mantissa: 23;
+       unsigned int    exp     : 8;
+       unsigned int    sign    : 1;
+};
+
+/* Vax single precision floating point */
+struct vax_single {
+       unsigned int    mantissa1 : 7;
+       unsigned int    exp       : 8;
+       unsigned int    sign      : 1;
+       unsigned int    mantissa2 : 16;
+};
+
+#define VAX_SNG_BIAS   0x81
+#define IEEE_SNG_BIAS  0x7f
+
+static struct sgl_limits {
+       struct vax_single s;
+       struct ieee_single ieee;
+} sgl_limits[2] = {
+       {{ 0x7f, 0xff, 0x0, 0xffff },   /* Max Vax */
+       { 0x0, 0xff, 0x0 }},            /* Max IEEE */
+       {{ 0x0, 0x0, 0x0, 0x0 },        /* Min Vax */
+       { 0x0, 0x0, 0x0 }}              /* Min IEEE */
+};
+#endif /* vax */
+
+bool_t
+xdr_float(xdrs, fp)
+       XDR *xdrs;
+       float *fp;
+{
+#ifndef IEEEFP
+       struct ieee_single is;
+       struct vax_single vs, *vsp;
+       struct sgl_limits *lim;
+       size_t i;
+#endif
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+#ifdef IEEEFP
+               return (XDR_PUTINT32(xdrs, (int32_t *)(void *)fp));
+#else
+               vs = *((struct vax_single *)fp);
+               for (i = 0, lim = sgl_limits;
+                       i < sizeof(sgl_limits)/sizeof(struct sgl_limits);
+                       i++, lim++) {
+                       if ((vs.mantissa2 == lim->s.mantissa2) &&
+                               (vs.exp == lim->s.exp) &&
+                               (vs.mantissa1 == lim->s.mantissa1)) {
+                               is = lim->ieee;
+                               goto shipit;
+                       }
+               }
+               is.exp = vs.exp - VAX_SNG_BIAS + IEEE_SNG_BIAS;
+               is.mantissa = (vs.mantissa1 << 16) | vs.mantissa2;
+       shipit:
+               is.sign = vs.sign;
+               return (XDR_PUTINT32(xdrs, (int32_t *)(void *)&is));
+#endif
+
+       case XDR_DECODE:
+#ifdef IEEEFP
+               return (XDR_GETINT32(xdrs, (int32_t *)(void *)fp));
+#else
+               vsp = (struct vax_single *)fp;
+               if (!XDR_GETINT32(xdrs, (int32_t *)(void *)&is))
+                       return (FALSE);
+               for (i = 0, lim = sgl_limits;
+                       i < sizeof(sgl_limits)/sizeof(struct sgl_limits);
+                       i++, lim++) {
+                       if ((is.exp == lim->ieee.exp) &&
+                               (is.mantissa == lim->ieee.mantissa)) {
+                               *vsp = lim->s;
+                               goto doneit;
+                       }
+               }
+               vsp->exp = is.exp - IEEE_SNG_BIAS + VAX_SNG_BIAS;
+               vsp->mantissa2 = is.mantissa;
+               vsp->mantissa1 = (is.mantissa >> 16);
+       doneit:
+               vsp->sign = is.sign;
+               return (TRUE);
+#endif
+
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
+
+#if defined(__vax__)
+/* What IEEE double precision floating point looks like on a Vax */
+struct ieee_double {
+       unsigned int    mantissa1 : 20;
+       unsigned int    exp       : 11;
+       unsigned int    sign      : 1;
+       unsigned int    mantissa2 : 32;
+};
+
+/* Vax double precision floating point */
+struct  vax_double {
+       unsigned int    mantissa1 : 7;
+       unsigned int    exp       : 8;
+       unsigned int    sign      : 1;
+       unsigned int    mantissa2 : 16;
+       unsigned int    mantissa3 : 16;
+       unsigned int    mantissa4 : 16;
+};
+
+#define VAX_DBL_BIAS   0x81
+#define IEEE_DBL_BIAS  0x3ff
+#define MASK(nbits)    ((1 << nbits) - 1)
+
+static struct dbl_limits {
+       struct  vax_double d;
+       struct  ieee_double ieee;
+} dbl_limits[2] = {
+       {{ 0x7f, 0xff, 0x0, 0xffff, 0xffff, 0xffff },   /* Max Vax */
+       { 0x0, 0x7ff, 0x0, 0x0 }},                      /* Max IEEE */
+       {{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},               /* Min Vax */
+       { 0x0, 0x0, 0x0, 0x0 }}                         /* Min IEEE */
+};
+
+#endif /* vax */
+
+
+bool_t
+xdr_double(xdrs, dp)
+       XDR *xdrs;
+       double *dp;
+{
+#ifdef IEEEFP
+       int32_t *i32p;
+       bool_t rv;
+#else
+       int32_t *lp;
+       struct  ieee_double id;
+       struct  vax_double vd;
+       struct dbl_limits *lim;
+       size_t i;
+#endif
+
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+#ifdef IEEEFP
+               i32p = (int32_t *)(void *)dp;
+#if (BYTE_ORDER == BIG_ENDIAN) || \
+    (defined(__arm__) && !defined(__VFP_FP__))
+               rv = XDR_PUTINT32(xdrs, i32p);
+               if (!rv)
+                       return (rv);
+               rv = XDR_PUTINT32(xdrs, i32p+1);
+#else
+               rv = XDR_PUTINT32(xdrs, i32p+1);
+               if (!rv)
+                       return (rv);
+               rv = XDR_PUTINT32(xdrs, i32p);
+#endif
+               return (rv);
+#else
+               vd = *((struct vax_double *)dp);
+               for (i = 0, lim = dbl_limits;
+                       i < sizeof(dbl_limits)/sizeof(struct dbl_limits);
+                       i++, lim++) {
+                       if ((vd.mantissa4 == lim->d.mantissa4) &&
+                               (vd.mantissa3 == lim->d.mantissa3) &&
+                               (vd.mantissa2 == lim->d.mantissa2) &&
+                               (vd.mantissa1 == lim->d.mantissa1) &&
+                               (vd.exp == lim->d.exp)) {
+                               id = lim->ieee;
+                               goto shipit;
+                       }
+               }
+               id.exp = vd.exp - VAX_DBL_BIAS + IEEE_DBL_BIAS;
+               id.mantissa1 = (vd.mantissa1 << 13) | (vd.mantissa2 >> 3);
+               id.mantissa2 = ((vd.mantissa2 & MASK(3)) << 29) |
+                               (vd.mantissa3 << 13) |
+                               ((vd.mantissa4 >> 3) & MASK(13));
+       shipit:
+               id.sign = vd.sign;
+               lp = (int32_t *)(void *)&id;
+               return (XDR_PUTINT32(xdrs, lp++) && XDR_PUTINT32(xdrs, lp));
+#endif
+
+       case XDR_DECODE:
+#ifdef IEEEFP
+               i32p = (int32_t *)(void *)dp;
+#if BYTE_ORDER == BIG_ENDIAN || \
+    (defined(__arm__) && !defined(__VFP_FP__))
+               rv = XDR_GETINT32(xdrs, i32p);
+               if (!rv)
+                       return (rv);
+               rv = XDR_GETINT32(xdrs, i32p+1);
+#else
+               rv = XDR_GETINT32(xdrs, i32p+1);
+               if (!rv)
+                       return (rv);
+               rv = XDR_GETINT32(xdrs, i32p);
+#endif
+               return (rv);
+#else
+               lp = (int32_t *)(void *)&id;
+               if (!XDR_GETINT32(xdrs, lp++) || !XDR_GETINT32(xdrs, lp))
+                       return (FALSE);
+               for (i = 0, lim = dbl_limits;
+                       i < sizeof(dbl_limits)/sizeof(struct dbl_limits);
+                       i++, lim++) {
+                       if ((id.mantissa2 == lim->ieee.mantissa2) &&
+                               (id.mantissa1 == lim->ieee.mantissa1) &&
+                               (id.exp == lim->ieee.exp)) {
+                               vd = lim->d;
+                               goto doneit;
+                       }
+               }
+               vd.exp = id.exp - IEEE_DBL_BIAS + VAX_DBL_BIAS;
+               vd.mantissa1 = (id.mantissa1 >> 13);
+               vd.mantissa2 = ((id.mantissa1 & MASK(13)) << 3) |
+                               (id.mantissa2 >> 29);
+               vd.mantissa3 = (id.mantissa2 >> 13);
+               vd.mantissa4 = (id.mantissa2 << 3);
+       doneit:
+               vd.sign = id.sign;
+               *dp = *((double *)(void *)&vd);
+               return (TRUE);
+#endif
+
+       case XDR_FREE:
+               return (TRUE);
+       }
+       /* NOTREACHED */
+       return (FALSE);
+}
diff --git a/lib/nbsd_libc/rpc/xdr_mem.c b/lib/nbsd_libc/rpc/xdr_mem.c
new file mode 100644 (file)
index 0000000..366d7c9
--- /dev/null
@@ -0,0 +1,269 @@
+/*     $NetBSD: xdr_mem.c,v 1.17 2006/10/15 16:14:46 christos Exp $    */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)xdr_mem.c 1.19 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)xdr_mem.c   2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: xdr_mem.c,v 1.17 2006/10/15 16:14:46 christos Exp $");
+#endif
+#endif
+
+/*
+ * xdr_mem.h, XDR implementation using memory buffers.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ * If you have some data to be interpreted as external data representation
+ * or to be converted to external data representation in a memory buffer,
+ * then this is the package for you.
+ *
+ */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+
+#include <netinet/in.h>
+
+#include <string.h>
+
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+
+#ifdef __weak_alias
+__weak_alias(xdrmem_create,_xdrmem_create)
+#endif
+
+static void xdrmem_destroy __P((XDR *));
+static bool_t xdrmem_getlong_aligned __P((XDR *, long *));
+static bool_t xdrmem_putlong_aligned __P((XDR *, const long *));
+static bool_t xdrmem_getlong_unaligned __P((XDR *, long *));
+static bool_t xdrmem_putlong_unaligned __P((XDR *, const long *));
+static bool_t xdrmem_getbytes __P((XDR *, char *, u_int));
+static bool_t xdrmem_putbytes __P((XDR *, const char *, u_int));
+/* XXX: w/64-bit pointers, u_int not enough! */
+static u_int xdrmem_getpos __P((XDR *));
+static bool_t xdrmem_setpos __P((XDR *, u_int));
+static int32_t *xdrmem_inline_aligned __P((XDR *, u_int));
+static int32_t *xdrmem_inline_unaligned __P((XDR *, u_int));
+
+static const struct    xdr_ops xdrmem_ops_aligned = {
+       xdrmem_getlong_aligned,
+       xdrmem_putlong_aligned,
+       xdrmem_getbytes,
+       xdrmem_putbytes,
+       xdrmem_getpos,
+       xdrmem_setpos,
+       xdrmem_inline_aligned,
+       xdrmem_destroy,
+       NULL,   /* xdrmem_control */
+};
+
+static const struct    xdr_ops xdrmem_ops_unaligned = {
+       xdrmem_getlong_unaligned,
+       xdrmem_putlong_unaligned,
+       xdrmem_getbytes,
+       xdrmem_putbytes,
+       xdrmem_getpos,
+       xdrmem_setpos,
+       xdrmem_inline_unaligned,
+       xdrmem_destroy,
+       NULL,   /* xdrmem_control */
+};
+
+/*
+ * The procedure xdrmem_create initializes a stream descriptor for a
+ * memory buffer.  
+ */
+void
+xdrmem_create(xdrs, addr, size, op)
+       XDR *xdrs;
+       char *addr;
+       u_int size;
+       enum xdr_op op;
+{
+
+       xdrs->x_op = op;
+       xdrs->x_ops = ((unsigned long)addr & (sizeof(int32_t) - 1))
+           ? &xdrmem_ops_unaligned : &xdrmem_ops_aligned;
+       xdrs->x_private = xdrs->x_base = addr;
+       xdrs->x_handy = size;
+}
+
+/*ARGSUSED*/
+static void
+xdrmem_destroy(xdrs)
+       XDR *xdrs;
+{
+
+}
+
+static bool_t
+xdrmem_getlong_aligned(xdrs, lp)
+       XDR *xdrs;
+       long *lp;
+{
+
+       if (xdrs->x_handy < sizeof(int32_t))
+               return (FALSE);
+       xdrs->x_handy -= sizeof(int32_t);
+       *lp = ntohl(*(u_int32_t *)xdrs->x_private);
+       xdrs->x_private = (char *)xdrs->x_private + sizeof(int32_t);
+       return (TRUE);
+}
+
+static bool_t
+xdrmem_putlong_aligned(xdrs, lp)
+       XDR *xdrs;
+       const long *lp;
+{
+
+       if (xdrs->x_handy < sizeof(int32_t))
+               return (FALSE);
+       xdrs->x_handy -= sizeof(int32_t);
+       *(u_int32_t *)xdrs->x_private = htonl((u_int32_t)*lp);
+       xdrs->x_private = (char *)xdrs->x_private + sizeof(int32_t);
+       return (TRUE);
+}
+
+static bool_t
+xdrmem_getlong_unaligned(xdrs, lp)
+       XDR *xdrs;
+       long *lp;
+{
+       u_int32_t l;
+
+       if (xdrs->x_handy < sizeof(int32_t))
+               return (FALSE);
+       xdrs->x_handy -= sizeof(int32_t);
+       memmove(&l, xdrs->x_private, sizeof(int32_t));
+       *lp = ntohl(l);
+       xdrs->x_private = (char *)xdrs->x_private + sizeof(int32_t);
+       return (TRUE);
+}
+
+static bool_t
+xdrmem_putlong_unaligned(xdrs, lp)
+       XDR *xdrs;
+       const long *lp;
+{
+       u_int32_t l;
+
+       if (xdrs->x_handy < sizeof(int32_t))
+               return (FALSE);
+       xdrs->x_handy -= sizeof(int32_t);
+       l = htonl((u_int32_t)*lp);
+       memmove(xdrs->x_private, &l, sizeof(int32_t));
+       xdrs->x_private = (char *)xdrs->x_private + sizeof(int32_t);
+       return (TRUE);
+}
+
+static bool_t
+xdrmem_getbytes(xdrs, addr, len)
+       XDR *xdrs;
+       char *addr;
+       u_int len;
+{
+
+       if (xdrs->x_handy < len)
+               return (FALSE);
+       xdrs->x_handy -= len;
+       memmove(addr, xdrs->x_private, len);
+       xdrs->x_private = (char *)xdrs->x_private + len;
+       return (TRUE);
+}
+
+static bool_t
+xdrmem_putbytes(xdrs, addr, len)
+       XDR *xdrs;
+       const char *addr;
+       u_int len;
+{
+
+       if (xdrs->x_handy < len)
+               return (FALSE);
+       xdrs->x_handy -= len;
+       memmove(xdrs->x_private, addr, len);
+       xdrs->x_private = (char *)xdrs->x_private + len;
+       return (TRUE);
+}
+
+static u_int
+xdrmem_getpos(xdrs)
+       XDR *xdrs;
+{
+
+       /* XXX w/64-bit pointers, u_int not enough! */
+       return (u_int)((u_long)xdrs->x_private - (u_long)xdrs->x_base);
+}
+
+static bool_t
+xdrmem_setpos(xdrs, pos)
+       XDR *xdrs;
+       u_int pos;
+{
+       char *newaddr = xdrs->x_base + pos;
+       char *lastaddr = (char *)xdrs->x_private + xdrs->x_handy;
+
+       if ((long)newaddr > (long)lastaddr)
+               return (FALSE);
+       xdrs->x_private = newaddr;
+       xdrs->x_handy = (int)((long)lastaddr - (long)newaddr);
+       return (TRUE);
+}
+
+static int32_t *
+xdrmem_inline_aligned(xdrs, len)
+       XDR *xdrs;
+       u_int len;
+{
+       int32_t *buf = 0;
+
+       if (xdrs->x_handy >= len) {
+               xdrs->x_handy -= len;
+               buf = (int32_t *)xdrs->x_private;
+               xdrs->x_private = (char *)xdrs->x_private + len;
+       }
+       return (buf);
+}
+
+/* ARGSUSED */
+static int32_t *
+xdrmem_inline_unaligned(xdrs, len)
+       XDR *xdrs;
+       u_int len;
+{
+
+       return (0);
+}
diff --git a/lib/nbsd_libc/rpc/xdr_rec.c b/lib/nbsd_libc/rpc/xdr_rec.c
new file mode 100644 (file)
index 0000000..6347f25
--- /dev/null
@@ -0,0 +1,805 @@
+/*     $NetBSD: xdr_rec.c,v 1.31 2010/11/23 14:02:01 christos Exp $    */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint) 
+#if 0
+static char *sccsid = "@(#)xdr_rec.c 1.21 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)xdr_rec.c   2.2 88/08/01 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: xdr_rec.c,v 1.31 2010/11/23 14:02:01 christos Exp $");
+#endif
+#endif
+
+/*
+ * xdr_rec.c, Implements TCP/IP based XDR streams with a "record marking"
+ * layer above tcp (for rpc's use).
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ * These routines interface XDRSTREAMS to a tcp/ip connection.
+ * There is a record marking layer between the xdr stream
+ * and the tcp transport level.  A record is composed on one or more
+ * record fragments.  A record fragment is a thirty-two bit header followed
+ * by n bytes of data, where n is contained in the header.  The header
+ * is represented as a htonl(u_long).  Thegh order bit encodes
+ * whether or not the fragment is the last fragment of the record
+ * (1 => fragment is last, 0 => more fragments to follow. 
+ * The other 31 bits encode the byte length of the fragment.
+ */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+
+#include <netinet/in.h>
+
+#include <err.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+#include <rpc/auth.h>
+#include <rpc/svc.h>
+#include <rpc/clnt.h>
+
+#include "rpc_internal.h"
+
+#ifdef __weak_alias
+__weak_alias(xdrrec_create,_xdrrec_create)
+__weak_alias(xdrrec_endofrecord,_xdrrec_endofrecord)
+__weak_alias(xdrrec_eof,_xdrrec_eof)
+__weak_alias(xdrrec_skiprecord,_xdrrec_skiprecord)
+#endif
+
+static bool_t  xdrrec_getlong __P((XDR *, long *));
+static bool_t  xdrrec_putlong __P((XDR *, const long *));
+static bool_t  xdrrec_getbytes __P((XDR *, char *, u_int));
+
+static bool_t  xdrrec_putbytes __P((XDR *, const char *, u_int));
+static u_int   xdrrec_getpos __P((XDR *));
+static bool_t  xdrrec_setpos __P((XDR *, u_int));
+static int32_t *xdrrec_inline __P((XDR *, u_int));
+static void    xdrrec_destroy __P((XDR *));
+
+static const struct  xdr_ops xdrrec_ops = {
+       xdrrec_getlong,
+       xdrrec_putlong,
+       xdrrec_getbytes,
+       xdrrec_putbytes,
+       xdrrec_getpos,
+       xdrrec_setpos,
+       xdrrec_inline,
+       xdrrec_destroy,
+       NULL, /* xdrrec_control */
+};
+
+/*
+ * A record is composed of one or more record fragments.
+ * A record fragment is a four-byte header followed by zero to
+ * 2**32-1 bytes.  The header is treated as a long unsigned and is
+ * encode/decoded to the network via htonl/ntohl.  The low order 31 bits
+ * are a byte count of the fragment.  The highest order bit is a boolean:
+ * 1 => this fragment is the last fragment of the record,
+ * 0 => this fragment is followed by more fragment(s).
+ *
+ * The fragment/record machinery is not general;  it is constructed to
+ * meet the needs of xdr and rpc based on tcp.
+ */
+
+#define LAST_FRAG ((u_int32_t)(1 << 31))
+
+typedef struct rec_strm {
+       char *tcp_handle;
+       /*
+        * out-goung bits
+        */
+       int (*writeit) __P((char *, char *, int));
+       char *out_base; /* output buffer (points to frag header) */
+       char *out_finger;       /* next output position */
+       char *out_boundry;      /* data cannot up to this address */
+       u_int32_t *frag_header; /* beginning of curren fragment */
+       bool_t frag_sent;       /* true if buffer sent in middle of record */
+       /*
+        * in-coming bits
+        */
+       int (*readit) __P((char *, char *, int));
+       u_long in_size; /* fixed size of the input buffer */
+       char *in_base;
+       char *in_finger;        /* location of next byte to be had */
+       char *in_boundry;       /* can read up to this location */
+       long fbtbc;             /* fragment bytes to be consumed */
+       bool_t last_frag;
+       u_int sendsize;
+       u_int recvsize;
+
+       bool_t nonblock;
+       bool_t in_haveheader;
+       u_int32_t in_header;
+       char *in_hdrp;
+       int in_hdrlen;
+       int in_reclen;
+       int in_received;
+       int in_maxrec;
+} RECSTREAM;
+
+static u_int   fix_buf_size __P((u_int));
+static bool_t  flush_out __P((RECSTREAM *, bool_t));
+static bool_t  fill_input_buf __P((RECSTREAM *));
+static bool_t  get_input_bytes __P((RECSTREAM *, char *, u_int));
+static bool_t  set_input_fragment __P((RECSTREAM *));
+static bool_t  skip_input_bytes __P((RECSTREAM *, long));
+static bool_t  realloc_stream __P((RECSTREAM *, int));
+
+
+/*
+ * Create an xdr handle for xdrrec
+ * xdrrec_create fills in xdrs.  Sendsize and recvsize are
+ * send and recv buffer sizes (0 => use default).
+ * tcp_handle is an opaque handle that is passed as the first parameter to
+ * the procedures readit and writeit.  Readit and writeit are read and
+ * write respectively.   They are like the system
+ * calls expect that they take an opaque handle rather than an fd.
+ */
+void
+xdrrec_create(xdrs, sendsize, recvsize, tcp_handle, readit, writeit)
+       XDR *xdrs;
+       u_int sendsize;
+       u_int recvsize;
+       char *tcp_handle;
+       /* like read, but pass it a tcp_handle, not sock */
+       int (*readit) __P((char *, char *, int));
+       /* like write, but pass it a tcp_handle, not sock */
+       int (*writeit) __P((char *, char *, int));
+{
+       RECSTREAM *rstrm = mem_alloc(sizeof(RECSTREAM));
+
+       if (rstrm == NULL) {
+               warnx("xdrrec_create: out of memory");
+               /* 
+                *  This is bad.  Should rework xdrrec_create to 
+                *  return a handle, and in this case return NULL
+                */
+               return;
+       }
+
+       rstrm->sendsize = sendsize = fix_buf_size(sendsize);
+       rstrm->out_base = malloc(rstrm->sendsize);
+       if (rstrm->out_base == NULL) {
+               warnx("xdrrec_create: out of memory");
+               mem_free(rstrm, sizeof(RECSTREAM));
+               return;
+       }
+
+       rstrm->recvsize = recvsize = fix_buf_size(recvsize);
+       rstrm->in_base = malloc(recvsize);
+       if (rstrm->in_base == NULL) {
+               warnx("xdrrec_create: out of memory");
+               mem_free(rstrm->out_base, sendsize);
+               mem_free(rstrm, sizeof(RECSTREAM));
+               return;
+       }
+       /*
+        * now the rest ...
+        */
+       xdrs->x_ops = &xdrrec_ops;
+       xdrs->x_private = rstrm;
+       rstrm->tcp_handle = tcp_handle;
+       rstrm->readit = readit;
+       rstrm->writeit = writeit;
+       rstrm->out_finger = rstrm->out_boundry = rstrm->out_base;
+       rstrm->frag_header = (u_int32_t *)(void *)rstrm->out_base;
+       rstrm->out_finger += sizeof(u_int32_t);
+       rstrm->out_boundry += sendsize;
+       rstrm->frag_sent = FALSE;
+       rstrm->in_size = recvsize;
+       rstrm->in_boundry = rstrm->in_base;
+       rstrm->in_finger = (rstrm->in_boundry += recvsize);
+       rstrm->fbtbc = 0;
+       rstrm->last_frag = TRUE;
+       rstrm->in_haveheader = FALSE;
+       rstrm->in_hdrlen = 0;
+       rstrm->in_hdrp = (char *)(void *)&rstrm->in_header;
+       rstrm->nonblock = FALSE;
+       rstrm->in_reclen = 0;
+       rstrm->in_received = 0;
+}
+
+
+/*
+ * The reoutines defined below are the xdr ops which will go into the
+ * xdr handle filled in by xdrrec_create.
+ */
+
+static bool_t
+xdrrec_getlong(xdrs, lp)
+       XDR *xdrs;
+       long *lp;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
+       int32_t *buflp = (int32_t *)(void *)(rstrm->in_finger);
+       int32_t mylong;
+
+       /* first try the inline, fast case */
+       if ((rstrm->fbtbc >= (long)sizeof(int32_t)) &&
+               (((uintptr_t)rstrm->in_boundry - (uintptr_t)buflp) >= sizeof(int32_t))) {
+               *lp = (long)ntohl((u_int32_t)(*buflp));
+               rstrm->fbtbc -= sizeof(int32_t);
+               rstrm->in_finger += sizeof(int32_t);
+       } else {
+               if (! xdrrec_getbytes(xdrs, (char *)(void *)&mylong,
+                   sizeof(int32_t)))
+                       return (FALSE);
+               *lp = (long)ntohl((u_int32_t)mylong);
+       }
+       return (TRUE);
+}
+
+static bool_t
+xdrrec_putlong(xdrs, lp)
+       XDR *xdrs;
+       const long *lp;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
+       int32_t *dest_lp = ((int32_t *)(void *)(rstrm->out_finger));
+
+       if ((rstrm->out_finger += sizeof(int32_t)) > rstrm->out_boundry) {
+               /*
+                * this case should almost never happen so the code is
+                * inefficient
+                */
+               rstrm->out_finger -= sizeof(int32_t);
+               rstrm->frag_sent = TRUE;
+               if (! flush_out(rstrm, FALSE))
+                       return (FALSE);
+               dest_lp = ((int32_t *)(void *)(rstrm->out_finger));
+               rstrm->out_finger += sizeof(int32_t);
+       }
+       *dest_lp = (int32_t)htonl((u_int32_t)(*lp));
+       return (TRUE);
+}
+
+static bool_t  /* must manage buffers, fragments, and records */
+xdrrec_getbytes(xdrs, addr, len)
+       XDR *xdrs;
+       char *addr;
+       u_int len;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
+       u_int current;
+
+       while (len > 0) {
+               current = (u_int)rstrm->fbtbc;
+               if (current == 0) {
+                       if (rstrm->last_frag)
+                               return (FALSE);
+                       if (! set_input_fragment(rstrm))
+                               return (FALSE);
+                       continue;
+               }
+               current = (len < current) ? len : current;
+               if (! get_input_bytes(rstrm, addr, current))
+                       return (FALSE);
+               addr += current; 
+               rstrm->fbtbc -= current;
+               len -= current;
+       }
+       return (TRUE);
+}
+
+static bool_t
+xdrrec_putbytes(xdrs, addr, len)
+       XDR *xdrs;
+       const char *addr;
+       u_int len;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
+       size_t current;
+
+       while (len > 0) {
+               current = (size_t)((u_long)rstrm->out_boundry -
+                   (u_long)rstrm->out_finger);
+               current = (len < current) ? len : current;
+               memmove(rstrm->out_finger, addr, current);
+               rstrm->out_finger += current;
+               addr += current;
+               len -= current;
+               if (rstrm->out_finger == rstrm->out_boundry) {
+                       rstrm->frag_sent = TRUE;
+                       if (! flush_out(rstrm, FALSE))
+                               return (FALSE);
+               }
+       }
+       return (TRUE);
+}
+
+static u_int
+xdrrec_getpos(xdrs)
+       XDR *xdrs;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)xdrs->x_private;
+       off_t pos;
+
+       pos = lseek((int)(u_long)rstrm->tcp_handle, (off_t)0, 1);
+       if (pos != -1)
+               switch (xdrs->x_op) {
+
+               case XDR_ENCODE:
+                       pos += rstrm->out_finger - rstrm->out_base;
+                       break;
+
+               case XDR_DECODE:
+                       pos -= rstrm->in_boundry - rstrm->in_finger;
+                       break;
+
+               default:
+                       pos = (off_t) -1;
+                       break;
+               }
+       return ((u_int) pos);
+}
+
+static bool_t
+xdrrec_setpos(xdrs, pos)
+       XDR *xdrs;
+       u_int pos;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)xdrs->x_private;
+       u_int currpos = xdrrec_getpos(xdrs);
+       int delta = currpos - pos;
+       char *newpos;
+
+       if ((int)currpos != -1)
+               switch (xdrs->x_op) {
+
+               case XDR_ENCODE:
+                       newpos = rstrm->out_finger - delta;
+                       if ((newpos > (char *)(void *)(rstrm->frag_header)) &&
+                               (newpos < rstrm->out_boundry)) {
+                               rstrm->out_finger = newpos;
+                               return (TRUE);
+                       }
+                       break;
+
+               case XDR_DECODE:
+                       newpos = rstrm->in_finger - delta;
+                       if ((delta < (int)(rstrm->fbtbc)) &&
+                               (newpos <= rstrm->in_boundry) &&
+                               (newpos >= rstrm->in_base)) {
+                               rstrm->in_finger = newpos;
+                               rstrm->fbtbc -= delta;
+                               return (TRUE);
+                       }
+                       break;
+
+               case XDR_FREE:
+                       break;
+               }
+       return (FALSE);
+}
+
+static int32_t *
+xdrrec_inline(xdrs, len)
+       XDR *xdrs;
+       u_int len;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)xdrs->x_private;
+       int32_t *buf = NULL;
+
+       switch (xdrs->x_op) {
+
+       case XDR_ENCODE:
+               if ((rstrm->out_finger + len) <= rstrm->out_boundry) {
+                       buf = (int32_t *)(void *)rstrm->out_finger;
+                       rstrm->out_finger += len;
+               }
+               break;
+
+       case XDR_DECODE:
+               if ((len <= (u_int)rstrm->fbtbc) &&
+                       ((rstrm->in_finger + len) <= rstrm->in_boundry)) {
+                       buf = (int32_t *)(void *)rstrm->in_finger;
+                       rstrm->fbtbc -= len;
+                       rstrm->in_finger += len;
+               }
+               break;
+
+       case XDR_FREE:
+               break;
+       }
+       return (buf);
+}
+
+static void
+xdrrec_destroy(xdrs)
+       XDR *xdrs;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)xdrs->x_private;
+
+       mem_free(rstrm->out_base, rstrm->sendsize);
+       mem_free(rstrm->in_base, rstrm->recvsize);
+       mem_free(rstrm, sizeof(RECSTREAM));
+}
+
+
+/*
+ * Exported routines to manage xdr records
+ */
+
+/*
+ * Before reading (deserializing from the stream, one should always call
+ * this procedure to guarantee proper record alignment.
+ */
+bool_t
+xdrrec_skiprecord(xdrs)
+       XDR *xdrs;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
+       enum xprt_stat xstat;
+
+       if (rstrm->nonblock) {
+               if (__xdrrec_getrec(xdrs, &xstat, FALSE)) {
+                       rstrm->fbtbc = 0;
+                       return TRUE;
+               }
+               if (rstrm->in_finger == rstrm->in_boundry &&
+                   xstat == XPRT_MOREREQS) {
+                       rstrm->fbtbc = 0;
+                       return TRUE;
+               }
+               return FALSE;
+       }
+       while (rstrm->fbtbc > 0 || (! rstrm->last_frag)) {
+               if (! skip_input_bytes(rstrm, rstrm->fbtbc))
+                       return (FALSE);
+               rstrm->fbtbc = 0;
+               if ((! rstrm->last_frag) && (! set_input_fragment(rstrm)))
+                       return (FALSE);
+       }
+       rstrm->last_frag = FALSE;
+       return (TRUE);
+}
+
+/*
+ * Look ahead fuction.
+ * Returns TRUE iff there is no more input in the buffer 
+ * after consuming the rest of the current record.
+ */
+bool_t
+xdrrec_eof(xdrs)
+       XDR *xdrs;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
+
+       while (rstrm->fbtbc > 0 || (! rstrm->last_frag)) {
+               if (!skip_input_bytes(rstrm, rstrm->fbtbc))
+                       return (TRUE);
+               rstrm->fbtbc = 0;
+               if ((!rstrm->last_frag) && (!set_input_fragment(rstrm)))
+                       return (TRUE);
+       }
+       if (rstrm->in_finger == rstrm->in_boundry)
+               return (TRUE);
+       return (FALSE);
+}
+
+/*
+ * The client must tell the package when an end-of-record has occurred.
+ * The second paraemters tells whether the record should be flushed to the
+ * (output) tcp stream.  (This let's the package support batched or
+ * pipelined procedure calls.)  TRUE => immmediate flush to tcp connection.
+ */
+bool_t
+xdrrec_endofrecord(xdrs, sendnow)
+       XDR *xdrs;
+       bool_t sendnow;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
+       u_long len;  /* fragment length */
+
+       if (sendnow || rstrm->frag_sent ||
+               ((u_long)rstrm->out_finger + sizeof(u_int32_t) >=
+               (u_long)rstrm->out_boundry)) {
+               rstrm->frag_sent = FALSE;
+               return (flush_out(rstrm, TRUE));
+       }
+       len = (u_long)(rstrm->out_finger) - (u_long)(rstrm->frag_header) -
+          sizeof(u_int32_t);
+       *(rstrm->frag_header) = htonl((u_int32_t)len | LAST_FRAG);
+       rstrm->frag_header = (u_int32_t *)(void *)rstrm->out_finger;
+       rstrm->out_finger += sizeof(u_int32_t);
+       return (TRUE);
+}
+
+/*
+ * Fill the stream buffer with a record for a non-blocking connection.
+ * Return true if a record is available in the buffer, false if not.
+ */
+bool_t
+__xdrrec_getrec(xdrs, statp, expectdata)
+       XDR *xdrs;
+       enum xprt_stat *statp;
+       bool_t expectdata;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
+       ssize_t n;
+       int fraglen;
+
+       if (!rstrm->in_haveheader) {
+               n = rstrm->readit(rstrm->tcp_handle, rstrm->in_hdrp,
+                   (int)sizeof (rstrm->in_header) - rstrm->in_hdrlen);
+               if (n == 0) {
+                       *statp = expectdata ? XPRT_DIED : XPRT_IDLE;
+                       return FALSE;
+               }
+               if (n < 0) {
+                       *statp = XPRT_DIED;
+                       return FALSE;
+               }
+               rstrm->in_hdrp += n;
+               rstrm->in_hdrlen += n;
+               if (rstrm->in_hdrlen < (int)sizeof(rstrm->in_header)) {
+                       *statp = XPRT_MOREREQS;
+                       return FALSE;
+               }
+               rstrm->in_header = ntohl(rstrm->in_header);
+               fraglen = (int)(rstrm->in_header & ~LAST_FRAG);
+               if (fraglen == 0 || fraglen > rstrm->in_maxrec ||
+                   (rstrm->in_reclen + fraglen) > rstrm->in_maxrec) {
+                       *statp = XPRT_DIED;
+                       return FALSE;
+               }
+               rstrm->in_reclen += fraglen;
+               if ((u_int)rstrm->in_reclen > rstrm->recvsize) {
+                       if (!realloc_stream(rstrm, rstrm->in_reclen)) {
+                               *statp = XPRT_DIED;
+                               return FALSE;
+                       }
+               }
+               if (rstrm->in_header & LAST_FRAG) {
+                       rstrm->in_header &= ~LAST_FRAG;
+                       rstrm->last_frag = TRUE;
+               }
+       }
+
+       n =  rstrm->readit(rstrm->tcp_handle,
+           rstrm->in_base + rstrm->in_received,
+           (rstrm->in_reclen - rstrm->in_received));
+
+       if (n < 0) {
+               *statp = XPRT_DIED;
+               return FALSE;
+       }
+
+       if (n == 0) {
+               *statp = expectdata ? XPRT_DIED : XPRT_IDLE;
+               return FALSE;
+       }
+
+       rstrm->in_received += n;
+
+       if (rstrm->in_received == rstrm->in_reclen) {
+               rstrm->in_haveheader = FALSE;
+               rstrm->in_hdrp = (char *)(void *)&rstrm->in_header;
+               rstrm->in_hdrlen = 0;
+               if (rstrm->last_frag) {
+                       rstrm->fbtbc = rstrm->in_reclen;
+                       rstrm->in_boundry = rstrm->in_base + rstrm->in_reclen;
+                       rstrm->in_finger = rstrm->in_base;
+                       rstrm->in_reclen = rstrm->in_received = 0;
+                       *statp = XPRT_MOREREQS;
+                       return TRUE;
+               }
+       }
+
+       *statp = XPRT_MOREREQS;
+       return FALSE;
+}
+
+bool_t
+__xdrrec_setnonblock(xdrs, maxrec)
+       XDR *xdrs;
+       int maxrec;
+{
+       RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private);
+
+       rstrm->nonblock = TRUE;
+       if (maxrec == 0)
+               maxrec = rstrm->recvsize;
+       rstrm->in_maxrec = maxrec;
+       return TRUE;
+}
+
+
+/*
+ * Internal useful routines
+ */
+static bool_t
+flush_out(rstrm, eor)
+       RECSTREAM *rstrm;
+       bool_t eor;
+{
+       u_int32_t eormask = (eor == TRUE) ? LAST_FRAG : 0;
+       u_int32_t len = (u_int32_t)((u_long)(rstrm->out_finger) - 
+               (u_long)(rstrm->frag_header) - sizeof(u_int32_t));
+
+       *(rstrm->frag_header) = htonl(len | eormask);
+       len = (u_int32_t)((u_long)(rstrm->out_finger) - 
+           (u_long)(rstrm->out_base));
+       if ((*(rstrm->writeit))(rstrm->tcp_handle, rstrm->out_base, (int)len)
+               != (int)len)
+               return (FALSE);
+       rstrm->frag_header = (u_int32_t *)(void *)rstrm->out_base;
+       rstrm->out_finger = (char *)rstrm->out_base + sizeof(u_int32_t);
+       return (TRUE);
+}
+
+static bool_t  /* knows nothing about records!  Only about input buffers */
+fill_input_buf(rstrm)
+       RECSTREAM *rstrm;
+{
+       char *where;
+       u_int32_t i;
+       int len;
+
+       if (rstrm->nonblock)
+               return FALSE;
+       where = rstrm->in_base;
+       i = (u_int32_t)((u_long)rstrm->in_boundry % BYTES_PER_XDR_UNIT);
+       where += i;
+       len = (u_int32_t)(rstrm->in_size - i);
+       if ((len = (*(rstrm->readit))(rstrm->tcp_handle, where, len)) == -1)
+               return (FALSE);
+       rstrm->in_finger = where;
+       where += len;
+       rstrm->in_boundry = where;
+       return (TRUE);
+}
+
+static bool_t  /* knows nothing about records!  Only about input buffers */
+get_input_bytes(rstrm, addr, len)
+       RECSTREAM *rstrm;
+       char *addr;
+       u_int len;
+{
+       u_int current;
+
+       if (rstrm->nonblock) {
+               if (len > ((uintptr_t)rstrm->in_boundry - (uintptr_t)rstrm->in_finger))
+                       return FALSE;
+               memcpy(addr, rstrm->in_finger, len);
+               rstrm->in_finger += len;
+               return TRUE;
+       }
+
+       while (len > 0) {
+               current = ((uintptr_t)rstrm->in_boundry -
+                   (uintptr_t)rstrm->in_finger);
+               if (current == 0) {
+                       if (! fill_input_buf(rstrm))
+                               return (FALSE);
+                       continue;
+               }
+               current = (len < current) ? len : current;
+               memmove(addr, rstrm->in_finger, current);
+               rstrm->in_finger += current;
+               addr += current;
+               len -= current;
+       }
+       return (TRUE);
+}
+
+static bool_t  /* next two bytes of the input stream are treated as a header */
+set_input_fragment(rstrm)
+       RECSTREAM *rstrm;
+{
+       u_int32_t header;
+
+       if (rstrm->nonblock)
+               return FALSE;
+       if (! get_input_bytes(rstrm, (char *)(void *)&header, sizeof(header)))
+               return (FALSE);
+       header = ntohl(header);
+       rstrm->last_frag = ((header & LAST_FRAG) == 0) ? FALSE : TRUE;
+       /*
+        * Sanity check. Try not to accept wildly incorrect
+        * record sizes. Unfortunately, the only record size
+        * we can positively identify as being 'wildly incorrect'
+        * is zero. Ridiculously large record sizes may look wrong,
+        * but we don't have any way to be certain that they aren't
+        * what the client actually intended to send us.
+        */
+       if (header == 0)
+               return(FALSE);
+       rstrm->fbtbc = header & (~LAST_FRAG);
+       return (TRUE);
+}
+
+static bool_t  /* consumes input bytes; knows nothing about records! */
+skip_input_bytes(rstrm, cnt)
+       RECSTREAM *rstrm;
+       long cnt;
+{
+       u_int32_t current;
+
+       while (cnt > 0) {
+               current = (size_t)((long)rstrm->in_boundry - 
+                   (long)rstrm->in_finger);
+               if (current == 0) {
+                       if (! fill_input_buf(rstrm))
+                               return (FALSE);
+                       continue;
+               }
+               current = ((u_int32_t)cnt < current) ? (u_int32_t)cnt : current;
+               rstrm->in_finger += current;
+               cnt -= current;
+       }
+       return (TRUE);
+}
+
+static u_int
+fix_buf_size(s)
+       u_int s;
+{
+
+       if (s < 100)
+               s = 4000;
+       return (RNDUP(s));
+}
+
+/*
+ * Reallocate the input buffer for a non-block stream.
+ */
+static bool_t
+realloc_stream(rstrm, size)
+       RECSTREAM *rstrm;
+       int size;
+{
+       ptrdiff_t diff;
+       char *buf;
+
+       if ((u_int)size > rstrm->recvsize) {
+               buf = realloc(rstrm->in_base, (size_t)size);
+               if (buf == NULL)
+                       return FALSE;
+               diff = buf - rstrm->in_base;
+               rstrm->in_finger += diff;
+               rstrm->in_base = buf;
+               rstrm->in_boundry = buf + size;
+               rstrm->recvsize = size;
+               rstrm->in_size = size;
+       }
+
+       return TRUE;
+}
diff --git a/lib/nbsd_libc/rpc/xdr_reference.c b/lib/nbsd_libc/rpc/xdr_reference.c
new file mode 100644 (file)
index 0000000..b0f074c
--- /dev/null
@@ -0,0 +1,151 @@
+/*     $NetBSD: xdr_reference.c,v 1.15 2008/04/25 17:44:44 christos Exp $      */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint) 
+#if 0
+static char *sccsid = "@(#)xdr_reference.c 1.11 87/08/11 SMI";
+static char *sccsid = "@(#)xdr_reference.c     2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: xdr_reference.c,v 1.15 2008/04/25 17:44:44 christos Exp $");
+#endif
+#endif
+
+/*
+ * xdr_reference.c, Generic XDR routines implementation.
+ *
+ * Copyright (C) 1987, Sun Microsystems, Inc.
+ *
+ * These are the "non-trivial" xdr primitives used to serialize and de-serialize
+ * "pointers".  See xdr.h for more info on the interface to xdr.
+ */
+
+#include "namespace.h"
+
+#include <err.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+
+#ifdef __weak_alias
+__weak_alias(xdr_pointer,_xdr_pointer)
+__weak_alias(xdr_reference,_xdr_reference)
+#endif
+
+/*
+ * XDR an indirect pointer
+ * xdr_reference is for recursively translating a structure that is
+ * referenced by a pointer inside the structure that is currently being
+ * translated.  pp references a pointer to storage. If *pp is null
+ * the  necessary storage is allocated.
+ * size is the sizeof the referneced structure.
+ * proc is the routine to handle the referenced structure.
+ */
+bool_t
+xdr_reference(xdrs, pp, size, proc)
+       XDR *xdrs;
+       caddr_t *pp;            /* the pointer to work on */
+       u_int size;             /* size of the object pointed to */
+       xdrproc_t proc;         /* xdr routine to handle the object */
+{
+       caddr_t loc = *pp;
+       bool_t stat;
+
+       if (loc == NULL)
+               switch (xdrs->x_op) {
+               case XDR_FREE:
+                       return (TRUE);
+
+               case XDR_DECODE:
+                       *pp = loc = mem_alloc(size);
+                       if (loc == NULL) {
+                               warnx("xdr_reference: out of memory");
+                               return (FALSE);
+                       }
+                       memset(loc, 0, size);
+                       break;
+
+               case XDR_ENCODE:
+                       break;
+               }
+
+       stat = (*proc)(xdrs, loc);
+
+       if (xdrs->x_op == XDR_FREE) {
+               mem_free(loc, size);
+               *pp = NULL;
+       }
+       return (stat);
+}
+
+
+/*
+ * xdr_pointer():
+ *
+ * XDR a pointer to a possibly recursive data structure. This
+ * differs with xdr_reference in that it can serialize/deserialiaze
+ * trees correctly.
+ *
+ *  What's sent is actually a union:
+ *
+ *  union object_pointer switch (boolean b) {
+ *  case TRUE: object_data data;
+ *  case FALSE: void nothing;
+ *  }
+ *
+ * > objpp: Pointer to the pointer to the object.
+ * > obj_size: size of the object.
+ * > xdr_obj: routine to XDR an object.
+ *
+ */
+bool_t
+xdr_pointer(xdrs,objpp,obj_size,xdr_obj)
+       XDR *xdrs;
+       char **objpp;
+       u_int obj_size;
+       xdrproc_t xdr_obj;
+{
+
+       bool_t more_data;
+
+       more_data = (*objpp != NULL);
+       if (! xdr_bool(xdrs,&more_data)) {
+               return (FALSE);
+       }
+       if (! more_data) {
+               *objpp = NULL;
+               return (TRUE);
+       }
+       return (xdr_reference(xdrs,objpp,obj_size,xdr_obj));
+}
diff --git a/lib/nbsd_libc/rpc/xdr_stdio.c b/lib/nbsd_libc/rpc/xdr_stdio.c
new file mode 100644 (file)
index 0000000..fcf8dd8
--- /dev/null
@@ -0,0 +1,203 @@
+/*     $NetBSD: xdr_stdio.c,v 1.17 2006/10/15 16:14:46 christos Exp $  */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)xdr_stdio.c 1.16 87/08/11 Copyr 1984 Sun Micro";
+static char *sccsid = "@(#)xdr_stdio.c 2.1 88/07/29 4.0 RPCSRC";
+#else
+__RCSID("$NetBSD: xdr_stdio.c,v 1.17 2006/10/15 16:14:46 christos Exp $");
+#endif
+#endif
+
+/*
+ * xdr_stdio.c, XDR implementation on standard i/o file.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ * This set of routines implements a XDR on a stdio stream.
+ * XDR_ENCODE serializes onto the stream, XDR_DECODE de-serializes
+ * from the stream.
+ */
+
+#include "namespace.h"
+
+#include <stdio.h>
+
+#include <rpc/types.h>
+#include <rpc/xdr.h>
+
+#ifdef __weak_alias
+__weak_alias(xdrstdio_create,_xdrstdio_create)
+#endif
+
+static void xdrstdio_destroy __P((XDR *));
+static bool_t xdrstdio_getlong __P((XDR *, long *));
+static bool_t xdrstdio_putlong __P((XDR *, const long *));
+static bool_t xdrstdio_getbytes __P((XDR *, char *, u_int));
+static bool_t xdrstdio_putbytes __P((XDR *, const char *, u_int));
+static u_int xdrstdio_getpos __P((XDR *));
+static bool_t xdrstdio_setpos __P((XDR *, u_int));
+static int32_t *xdrstdio_inline __P((XDR *, u_int));
+
+/*
+ * Ops vector for stdio type XDR
+ */
+static const struct xdr_ops    xdrstdio_ops = {
+       xdrstdio_getlong,       /* deseraialize a long int */
+       xdrstdio_putlong,       /* seraialize a long int */
+       xdrstdio_getbytes,      /* deserialize counted bytes */
+       xdrstdio_putbytes,      /* serialize counted bytes */
+       xdrstdio_getpos,        /* get offset in the stream */
+       xdrstdio_setpos,        /* set offset in the stream */
+       xdrstdio_inline,        /* prime stream for inline macros */
+       xdrstdio_destroy,       /* destroy stream */
+       NULL,                   /* xdrstdio_control */
+};
+
+/*
+ * Initialize a stdio xdr stream.
+ * Sets the xdr stream handle xdrs for use on the stream file.
+ * Operation flag is set to op.
+ */
+void
+xdrstdio_create(xdrs, file, op)
+       XDR *xdrs;
+       FILE *file;
+       enum xdr_op op;
+{
+
+       xdrs->x_op = op;
+       xdrs->x_ops = &xdrstdio_ops;
+       xdrs->x_private = file;
+       xdrs->x_handy = 0;
+       xdrs->x_base = 0;
+}
+
+/*
+ * Destroy a stdio xdr stream.
+ * Cleans up the xdr stream handle xdrs previously set up by xdrstdio_create.
+ */
+static void
+xdrstdio_destroy(xdrs)
+       XDR *xdrs;
+{
+       (void)fflush((FILE *)xdrs->x_private);
+               /* XXX: should we close the file ?? */
+}
+
+static bool_t
+xdrstdio_getlong(xdrs, lp)
+       XDR *xdrs;
+       long *lp;
+{
+       u_int32_t temp;
+
+       if (fread(&temp, sizeof(int32_t), 1, (FILE *)xdrs->x_private) != 1)
+               return (FALSE);
+       *lp = (long)ntohl(temp);
+       return (TRUE);
+}
+
+static bool_t
+xdrstdio_putlong(xdrs, lp)
+       XDR *xdrs;
+       const long *lp;
+{
+       int32_t mycopy = htonl((u_int32_t)*lp);
+
+       if (fwrite(&mycopy, sizeof(int32_t), 1, (FILE *)xdrs->x_private) != 1)
+               return (FALSE);
+       return (TRUE);
+}
+
+static bool_t
+xdrstdio_getbytes(xdrs, addr, len)
+       XDR *xdrs;
+       char *addr;
+       u_int len;
+{
+
+       if ((len != 0) && (fread(addr, (size_t)len, 1, (FILE *)xdrs->x_private) != 1))
+               return (FALSE);
+       return (TRUE);
+}
+
+static bool_t
+xdrstdio_putbytes(xdrs, addr, len)
+       XDR *xdrs;
+       const char *addr;
+       u_int len;
+{
+
+       if ((len != 0) && (fwrite(addr, (size_t)len, 1,
+           (FILE *)xdrs->x_private) != 1))
+               return (FALSE);
+       return (TRUE);
+}
+
+static u_int
+xdrstdio_getpos(xdrs)
+       XDR *xdrs;
+{
+
+       return ((u_int) ftell((FILE *)xdrs->x_private));
+}
+
+static bool_t
+xdrstdio_setpos(xdrs, pos) 
+       XDR *xdrs;
+       u_int pos;
+{ 
+
+       return ((fseek((FILE *)xdrs->x_private, (long)pos, 0) < 0) ?
+               FALSE : TRUE);
+}
+
+/* ARGSUSED */
+static int32_t *
+xdrstdio_inline(xdrs, len)
+       XDR *xdrs;
+       u_int len;
+{
+
+       /*
+        * Must do some work to implement this: must insure
+        * enough data in the underlying stdio buffer,
+        * that the buffer is aligned so that we can indirect through a
+        * long *, and stuff this pointer in xdrs->x_buf.  Doing
+        * a fread or fwrite to a scratch buffer would defeat
+        * most of the gains to be had here and require storage
+        * management on this buffer, so we don't do this.
+        */
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/shlib_version b/lib/nbsd_libc/shlib_version
new file mode 100644 (file)
index 0000000..6c0bd46
--- /dev/null
@@ -0,0 +1,34 @@
+#      $NetBSD: shlib_version,v 1.220 2010/12/16 18:38:06 christos Exp $
+#      Remember to update distrib/sets/lists/base/shl.* when changing
+#
+# things we wish to do on next major version bump:
+# - libc/net/rcmd.c: make __ivaliduser() and __ivaliduser_sa() static
+# - libc/net: resolver update to BIND8/9?
+# - md2, md4, md5, rmd160 & sha1 functions should take the same arguments AFAP
+# - libc/gen/assert.c: __{diag,}assert13() -> __{diag,}assert()
+# - libc/gen/times.c: remove; __times13() -> times()
+# - libc/gen/timezone.c: remove; __timezone13 -> timezone
+# - libc/net/getaddrinfo.c, netdb.h: remove __ai_pad0
+# - libc/gen/utmpx.c, utmpx.h: remove lastlogxname, __getlastlogx13 -> getlastlogx
+# - infinity{,f,l}.c, math.h: __infinity -> __huge_val
+# - libc/gen/is{inf,nan}d_ieee754.c: remove is{inf,nan} aliases
+# - libc/arch/vax/gen/is{inf,nan}.c: remove
+# - libc/db/hash/ndbm.c: remove; __ndbm13 -> ndbm
+# - libc/net/getnet{ent,namadr}.c, netdb.h: remove __n_pad0
+# - libc/stdio: make _file an int, hide struct FILE, stdin, stdout, stderr impls
+# - libc/stdio: make fpos_t larger.  see BUGS section in fgetpos(3).
+#   probably s/fpos_t/off_t/ in __sFILE and __sseek().  it involves
+#   funopen(3) api change.
+# - remove frexp, ldexp, modf: they belong to libm.
+# - make sure we can support thread local [on arm don't use r9 for example,
+#   consider other risc architectures: mips, powerpc, sparc, etc]
+# - rename __libc_mutex_lock and similar back to pthread_mutex_lock.
+#   the functions are used by third party code without prototypes.
+#   for example in assembler code.
+# - kill sigcontext: never request version 0 or 1 signal trampoline.
+#   always request version 2 trampoline. (on vax, 3).
+# - change _ctype_ table in ctype.h and gen/ctype_.c 8bit -> 16 or 32bit.
+#   it's insufficient bitwidth to implement all ctype class.
+#   see isblank's comment in ctype.h.
+major=12
+minor=175
diff --git a/lib/nbsd_libc/softfloat/Makefile.inc b/lib/nbsd_libc/softfloat/Makefile.inc
new file mode 100644 (file)
index 0000000..72a260f
--- /dev/null
@@ -0,0 +1,20 @@
+#      $NetBSD: Makefile.inc,v 1.7 2011/01/17 10:08:35 matt Exp $
+
+SOFTFLOAT_BITS?=64
+.PATH:         ${ARCHDIR}/softfloat \
+               ${.CURDIR}/softfloat/bits${SOFTFLOAT_BITS} ${.CURDIR}/softfloat
+
+CPPFLAGS+=     -I${ARCHDIR}/softfloat -I${.CURDIR}/softfloat
+CPPFLAGS+=     -DSOFTFLOAT_FOR_GCC
+
+SRCS.softfloat= softfloat.c
+
+SRCS.softfloat+=fpgetround.c fpsetround.c fpgetmask.c fpsetmask.c \
+               fpgetsticky.c fpsetsticky.c
+
+SRCS.softfloat+=eqsf2.c nesf2.c gtsf2.c gesf2.c ltsf2.c lesf2.c negsf2.c \
+               eqdf2.c nedf2.c gtdf2.c gedf2.c ltdf2.c ledf2.c negdf2.c \
+               eqtf2.c netf2.c gttf2.c getf2.c lttf2.c letf2.c negtf2.c \
+               nexf2.c gtxf2.c gexf2.c negxf2.c unordsf2.c unorddf2.c
+
+SRCS+=         ${SRCS.softfloat}
diff --git a/lib/nbsd_libc/softfloat/README.NetBSD b/lib/nbsd_libc/softfloat/README.NetBSD
new file mode 100644 (file)
index 0000000..e486eba
--- /dev/null
@@ -0,0 +1,8 @@
+$NetBSD: README.NetBSD,v 1.2 2002/05/21 23:51:05 bjh21 Exp $
+
+This is a modified version of part of John Hauser's SoftFloat 2a package.
+This version has been heavily modified to support its use with GCC to
+implement built-in floating-point operations, but compiling
+softfloat.c without SOFTFLOAT_FOR_GCC defined should get you the same
+results as from the original.
+
diff --git a/lib/nbsd_libc/softfloat/README.txt b/lib/nbsd_libc/softfloat/README.txt
new file mode 100644 (file)
index 0000000..b771b8c
--- /dev/null
@@ -0,0 +1,39 @@
+$NetBSD: README.txt,v 1.1 2000/06/06 08:15:02 bjh21 Exp $
+
+Package Overview for SoftFloat Release 2a
+
+John R. Hauser
+1998 December 13
+
+
+SoftFloat is a software implementation of floating-point that conforms to
+the IEC/IEEE Standard for Binary Floating-Point Arithmetic.  SoftFloat is
+distributed in the form of C source code.  Compiling the SoftFloat sources
+generates two things:
+
+-- A SoftFloat object file (typically `softfloat.o') containing the complete
+   set of IEC/IEEE floating-point routines.
+
+-- A `timesoftfloat' program for evaluating the speed of the SoftFloat
+   routines.  (The SoftFloat module is linked into this program.)
+
+The SoftFloat package is documented in four text files:
+
+   softfloat.txt          Documentation for using the SoftFloat functions.
+   softfloat-source.txt   Documentation for compiling SoftFloat.
+   softfloat-history.txt  History of major changes to SoftFloat.
+   timesoftfloat.txt      Documentation for using `timesoftfloat'.
+
+Other files in the package comprise the source code for SoftFloat.
+
+Please be aware that some work is involved in porting this software to other
+targets.  It is not just a matter of getting `make' to complete without
+error messages.  I would have written the code that way if I could, but
+there are fundamental differences between systems that I can't make go away.
+You should not attempt to compile SoftFloat without first reading both
+`softfloat.txt' and `softfloat-source.txt'.
+
+At the time of this writing, the most up-to-date information about
+SoftFloat and the latest release can be found at the Web page `http://
+HTTP.CS.Berkeley.EDU/~jhauser/arithmetic/SoftFloat.html'.
+
diff --git a/lib/nbsd_libc/softfloat/bits32/softfloat-macros b/lib/nbsd_libc/softfloat/bits32/softfloat-macros
new file mode 100644 (file)
index 0000000..59e6e76
--- /dev/null
@@ -0,0 +1,648 @@
+
+/*
+===============================================================================
+
+This C source fragment is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+Shifts `a' right by the number of bits given in `count'.  If any nonzero
+bits are shifted off, they are ``jammed'' into the least significant bit of
+the result by setting the least significant bit to 1.  The value of `count'
+can be arbitrarily large; in particular, if `count' is greater than 32, the
+result will be either 0 or 1, depending on whether `a' is zero or nonzero.
+The result is stored in the location pointed to by `zPtr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void shift32RightJamming( bits32 a, int16 count, bits32 *zPtr )
+{
+    bits32 z;
+
+    if ( count == 0 ) {
+        z = a;
+    }
+    else if ( count < 32 ) {
+        z = ( a>>count ) | ( ( a<<( ( - count ) & 31 ) ) != 0 );
+    }
+    else {
+        z = ( a != 0 );
+    }
+    *zPtr = z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Shifts the 64-bit value formed by concatenating `a0' and `a1' right by the
+number of bits given in `count'.  Any bits shifted off are lost.  The value
+of `count' can be arbitrarily large; in particular, if `count' is greater
+than 64, the result will be 0.  The result is broken into two 32-bit pieces
+which are stored at the locations pointed to by `z0Ptr' and `z1Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ shift64Right(
+     bits32 a0, bits32 a1, int16 count, bits32 *z0Ptr, bits32 *z1Ptr )
+{
+    bits32 z0, z1;
+    int8 negCount = ( - count ) & 31;
+
+    if ( count == 0 ) {
+        z1 = a1;
+        z0 = a0;
+    }
+    else if ( count < 32 ) {
+        z1 = ( a0<<negCount ) | ( a1>>count );
+        z0 = a0>>count;
+    }
+    else {
+        z1 = ( count < 64 ) ? ( a0>>( count & 31 ) ) : 0;
+        z0 = 0;
+    }
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Shifts the 64-bit value formed by concatenating `a0' and `a1' right by the
+number of bits given in `count'.  If any nonzero bits are shifted off, they
+are ``jammed'' into the least significant bit of the result by setting the
+least significant bit to 1.  The value of `count' can be arbitrarily large;
+in particular, if `count' is greater than 64, the result will be either 0
+or 1, depending on whether the concatenation of `a0' and `a1' is zero or
+nonzero.  The result is broken into two 32-bit pieces which are stored at
+the locations pointed to by `z0Ptr' and `z1Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ shift64RightJamming(
+     bits32 a0, bits32 a1, int16 count, bits32 *z0Ptr, bits32 *z1Ptr )
+{
+    bits32 z0, z1;
+    int8 negCount = ( - count ) & 31;
+
+    if ( count == 0 ) {
+        z1 = a1;
+        z0 = a0;
+    }
+    else if ( count < 32 ) {
+        z1 = ( a0<<negCount ) | ( a1>>count ) | ( ( a1<<negCount ) != 0 );
+        z0 = a0>>count;
+    }
+    else {
+        if ( count == 32 ) {
+            z1 = a0 | ( a1 != 0 );
+        }
+        else if ( count < 64 ) {
+            z1 = ( a0>>( count & 31 ) ) | ( ( ( a0<<negCount ) | a1 ) != 0 );
+        }
+        else {
+            z1 = ( ( a0 | a1 ) != 0 );
+        }
+        z0 = 0;
+    }
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Shifts the 96-bit value formed by concatenating `a0', `a1', and `a2' right
+by 32 _plus_ the number of bits given in `count'.  The shifted result is
+at most 64 nonzero bits; these are broken into two 32-bit pieces which are
+stored at the locations pointed to by `z0Ptr' and `z1Ptr'.  The bits shifted
+off form a third 32-bit result as follows:  The _last_ bit shifted off is
+the most-significant bit of the extra result, and the other 31 bits of the
+extra result are all zero if and only if _all_but_the_last_ bits shifted off
+were all zero.  This extra result is stored in the location pointed to by
+`z2Ptr'.  The value of `count' can be arbitrarily large.
+    (This routine makes more sense if `a0', `a1', and `a2' are considered
+to form a fixed-point value with binary point between `a1' and `a2'.  This
+fixed-point value is shifted right by the number of bits given in `count',
+and the integer part of the result is returned at the locations pointed to
+by `z0Ptr' and `z1Ptr'.  The fractional part of the result may be slightly
+corrupted as described above, and is returned at the location pointed to by
+`z2Ptr'.)
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ shift64ExtraRightJamming(
+     bits32 a0,
+     bits32 a1,
+     bits32 a2,
+     int16 count,
+     bits32 *z0Ptr,
+     bits32 *z1Ptr,
+     bits32 *z2Ptr
+ )
+{
+    bits32 z0, z1, z2;
+    int8 negCount = ( - count ) & 31;
+
+    if ( count == 0 ) {
+        z2 = a2;
+        z1 = a1;
+        z0 = a0;
+    }
+    else {
+        if ( count < 32 ) {
+            z2 = a1<<negCount;
+            z1 = ( a0<<negCount ) | ( a1>>count );
+            z0 = a0>>count;
+        }
+        else {
+            if ( count == 32 ) {
+                z2 = a1;
+                z1 = a0;
+            }
+            else {
+                a2 |= a1;
+                if ( count < 64 ) {
+                    z2 = a0<<negCount;
+                    z1 = a0>>( count & 31 );
+                }
+                else {
+                    z2 = ( count == 64 ) ? a0 : ( a0 != 0 );
+                    z1 = 0;
+                }
+            }
+            z0 = 0;
+        }
+        z2 |= ( a2 != 0 );
+    }
+    *z2Ptr = z2;
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Shifts the 64-bit value formed by concatenating `a0' and `a1' left by the
+number of bits given in `count'.  Any bits shifted off are lost.  The value
+of `count' must be less than 32.  The result is broken into two 32-bit
+pieces which are stored at the locations pointed to by `z0Ptr' and `z1Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ shortShift64Left(
+     bits32 a0, bits32 a1, int16 count, bits32 *z0Ptr, bits32 *z1Ptr )
+{
+
+    *z1Ptr = a1<<count;
+    *z0Ptr =
+        ( count == 0 ) ? a0 : ( a0<<count ) | ( a1>>( ( - count ) & 31 ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Shifts the 96-bit value formed by concatenating `a0', `a1', and `a2' left
+by the number of bits given in `count'.  Any bits shifted off are lost.
+The value of `count' must be less than 32.  The result is broken into three
+32-bit pieces which are stored at the locations pointed to by `z0Ptr',
+`z1Ptr', and `z2Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ shortShift96Left(
+     bits32 a0,
+     bits32 a1,
+     bits32 a2,
+     int16 count,
+     bits32 *z0Ptr,
+     bits32 *z1Ptr,
+     bits32 *z2Ptr
+ )
+{
+    bits32 z0, z1, z2;
+    int8 negCount;
+
+    z2 = a2<<count;
+    z1 = a1<<count;
+    z0 = a0<<count;
+    if ( 0 < count ) {
+        negCount = ( ( - count ) & 31 );
+        z1 |= a2>>negCount;
+        z0 |= a1>>negCount;
+    }
+    *z2Ptr = z2;
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Adds the 64-bit value formed by concatenating `a0' and `a1' to the 64-bit
+value formed by concatenating `b0' and `b1'.  Addition is modulo 2^64, so
+any carry out is lost.  The result is broken into two 32-bit pieces which
+are stored at the locations pointed to by `z0Ptr' and `z1Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ add64(
+     bits32 a0, bits32 a1, bits32 b0, bits32 b1, bits32 *z0Ptr, bits32 *z1Ptr )
+{
+    bits32 z1;
+
+    z1 = a1 + b1;
+    *z1Ptr = z1;
+    *z0Ptr = a0 + b0 + ( z1 < a1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Adds the 96-bit value formed by concatenating `a0', `a1', and `a2' to the
+96-bit value formed by concatenating `b0', `b1', and `b2'.  Addition is
+modulo 2^96, so any carry out is lost.  The result is broken into three
+32-bit pieces which are stored at the locations pointed to by `z0Ptr',
+`z1Ptr', and `z2Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ add96(
+     bits32 a0,
+     bits32 a1,
+     bits32 a2,
+     bits32 b0,
+     bits32 b1,
+     bits32 b2,
+     bits32 *z0Ptr,
+     bits32 *z1Ptr,
+     bits32 *z2Ptr
+ )
+{
+    bits32 z0, z1, z2;
+    int8 carry0, carry1;
+
+    z2 = a2 + b2;
+    carry1 = ( z2 < a2 );
+    z1 = a1 + b1;
+    carry0 = ( z1 < a1 );
+    z0 = a0 + b0;
+    z1 += carry1;
+    z0 += ( z1 < (bits32)carry1 );
+    z0 += carry0;
+    *z2Ptr = z2;
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Subtracts the 64-bit value formed by concatenating `b0' and `b1' from the
+64-bit value formed by concatenating `a0' and `a1'.  Subtraction is modulo
+2^64, so any borrow out (carry out) is lost.  The result is broken into two
+32-bit pieces which are stored at the locations pointed to by `z0Ptr' and
+`z1Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ sub64(
+     bits32 a0, bits32 a1, bits32 b0, bits32 b1, bits32 *z0Ptr, bits32 *z1Ptr )
+{
+
+    *z1Ptr = a1 - b1;
+    *z0Ptr = a0 - b0 - ( a1 < b1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Subtracts the 96-bit value formed by concatenating `b0', `b1', and `b2' from
+the 96-bit value formed by concatenating `a0', `a1', and `a2'.  Subtraction
+is modulo 2^96, so any borrow out (carry out) is lost.  The result is broken
+into three 32-bit pieces which are stored at the locations pointed to by
+`z0Ptr', `z1Ptr', and `z2Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ sub96(
+     bits32 a0,
+     bits32 a1,
+     bits32 a2,
+     bits32 b0,
+     bits32 b1,
+     bits32 b2,
+     bits32 *z0Ptr,
+     bits32 *z1Ptr,
+     bits32 *z2Ptr
+ )
+{
+    bits32 z0, z1, z2;
+    int8 borrow0, borrow1;
+
+    z2 = a2 - b2;
+    borrow1 = ( a2 < b2 );
+    z1 = a1 - b1;
+    borrow0 = ( a1 < b1 );
+    z0 = a0 - b0;
+    z0 -= ( z1 < (bits32)borrow1 );
+    z1 -= borrow1;
+    z0 -= borrow0;
+    *z2Ptr = z2;
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Multiplies `a' by `b' to obtain a 64-bit product.  The product is broken
+into two 32-bit pieces which are stored at the locations pointed to by
+`z0Ptr' and `z1Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void mul32To64( bits32 a, bits32 b, bits32 *z0Ptr, bits32 *z1Ptr )
+{
+    bits16 aHigh, aLow, bHigh, bLow;
+    bits32 z0, zMiddleA, zMiddleB, z1;
+
+    aLow = a;
+    aHigh = a>>16;
+    bLow = b;
+    bHigh = b>>16;
+    z1 = ( (bits32) aLow ) * bLow;
+    zMiddleA = ( (bits32) aLow ) * bHigh;
+    zMiddleB = ( (bits32) aHigh ) * bLow;
+    z0 = ( (bits32) aHigh ) * bHigh;
+    zMiddleA += zMiddleB;
+    z0 += ( ( (bits32) ( zMiddleA < zMiddleB ) )<<16 ) + ( zMiddleA>>16 );
+    zMiddleA <<= 16;
+    z1 += zMiddleA;
+    z0 += ( z1 < zMiddleA );
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Multiplies the 64-bit value formed by concatenating `a0' and `a1' by `b'
+to obtain a 96-bit product.  The product is broken into three 32-bit pieces
+which are stored at the locations pointed to by `z0Ptr', `z1Ptr', and
+`z2Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ mul64By32To96(
+     bits32 a0,
+     bits32 a1,
+     bits32 b,
+     bits32 *z0Ptr,
+     bits32 *z1Ptr,
+     bits32 *z2Ptr
+ )
+{
+    bits32 z0, z1, z2, more1;
+
+    mul32To64( a1, b, &z1, &z2 );
+    mul32To64( a0, b, &z0, &more1 );
+    add64( z0, more1, 0, z1, &z0, &z1 );
+    *z2Ptr = z2;
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Multiplies the 64-bit value formed by concatenating `a0' and `a1' to the
+64-bit value formed by concatenating `b0' and `b1' to obtain a 128-bit
+product.  The product is broken into four 32-bit pieces which are stored at
+the locations pointed to by `z0Ptr', `z1Ptr', `z2Ptr', and `z3Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ mul64To128(
+     bits32 a0,
+     bits32 a1,
+     bits32 b0,
+     bits32 b1,
+     bits32 *z0Ptr,
+     bits32 *z1Ptr,
+     bits32 *z2Ptr,
+     bits32 *z3Ptr
+ )
+{
+    bits32 z0, z1, z2, z3;
+    bits32 more1, more2;
+
+    mul32To64( a1, b1, &z2, &z3 );
+    mul32To64( a1, b0, &z1, &more2 );
+    add64( z1, more2, 0, z2, &z1, &z2 );
+    mul32To64( a0, b0, &z0, &more1 );
+    add64( z0, more1, 0, z1, &z0, &z1 );
+    mul32To64( a0, b1, &more1, &more2 );
+    add64( more1, more2, 0, z2, &more1, &z2 );
+    add64( z0, z1, 0, more1, &z0, &z1 );
+    *z3Ptr = z3;
+    *z2Ptr = z2;
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns an approximation to the 32-bit integer quotient obtained by dividing
+`b' into the 64-bit value formed by concatenating `a0' and `a1'.  The
+divisor `b' must be at least 2^31.  If q is the exact quotient truncated
+toward zero, the approximation returned lies between q and q + 2 inclusive.
+If the exact quotient q is larger than 32 bits, the maximum positive 32-bit
+unsigned integer is returned.
+-------------------------------------------------------------------------------
+*/
+static bits32 estimateDiv64To32( bits32 a0, bits32 a1, bits32 b )
+{
+    bits32 b0, b1;
+    bits32 rem0, rem1, term0, term1;
+    bits32 z;
+
+    if ( b <= a0 ) return 0xFFFFFFFF;
+    b0 = b>>16;
+    z = ( b0<<16 <= a0 ) ? 0xFFFF0000 : ( a0 / b0 )<<16;
+    mul32To64( b, z, &term0, &term1 );
+    sub64( a0, a1, term0, term1, &rem0, &rem1 );
+    while ( ( (sbits32) rem0 ) < 0 ) {
+        z -= 0x10000;
+        b1 = b<<16;
+        add64( rem0, rem1, b0, b1, &rem0, &rem1 );
+    }
+    rem0 = ( rem0<<16 ) | ( rem1>>16 );
+    z |= ( b0<<16 <= rem0 ) ? 0xFFFF : rem0 / b0;
+    return z;
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC
+/*
+-------------------------------------------------------------------------------
+Returns an approximation to the square root of the 32-bit significand given
+by `a'.  Considered as an integer, `a' must be at least 2^31.  If bit 0 of
+`aExp' (the least significant bit) is 1, the integer returned approximates
+2^31*sqrt(`a'/2^31), where `a' is considered an integer.  If bit 0 of `aExp'
+is 0, the integer returned approximates 2^31*sqrt(`a'/2^30).  In either
+case, the approximation returned lies strictly within +/-2 of the exact
+value.
+-------------------------------------------------------------------------------
+*/
+static bits32 estimateSqrt32( int16 aExp, bits32 a )
+{
+    static const bits16 sqrtOddAdjustments[] = {
+        0x0004, 0x0022, 0x005D, 0x00B1, 0x011D, 0x019F, 0x0236, 0x02E0,
+        0x039C, 0x0468, 0x0545, 0x0631, 0x072B, 0x0832, 0x0946, 0x0A67
+    };
+    static const bits16 sqrtEvenAdjustments[] = {
+        0x0A2D, 0x08AF, 0x075A, 0x0629, 0x051A, 0x0429, 0x0356, 0x029E,
+        0x0200, 0x0179, 0x0109, 0x00AF, 0x0068, 0x0034, 0x0012, 0x0002
+    };
+    int8 index;
+    bits32 z;
+
+    index = ( a>>27 ) & 15;
+    if ( aExp & 1 ) {
+        z = 0x4000 + ( a>>17 ) - sqrtOddAdjustments[ index ];
+        z = ( ( a / z )<<14 ) + ( z<<15 );
+        a >>= 1;
+    }
+    else {
+        z = 0x8000 + ( a>>17 ) - sqrtEvenAdjustments[ index ];
+        z = a / z + z;
+        z = ( 0x20000 <= z ) ? 0xFFFF8000 : ( z<<15 );
+        if ( z <= a ) return (bits32) ( ( (sbits32) a )>>1 );
+    }
+    return ( ( estimateDiv64To32( a, 0, z ) )>>1 ) + ( z>>1 );
+
+}
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Returns the number of leading 0 bits before the most-significant 1 bit of
+`a'.  If `a' is zero, 32 is returned.
+-------------------------------------------------------------------------------
+*/
+static int8 countLeadingZeros32( bits32 a )
+{
+    static const int8 countLeadingZerosHigh[] = {
+        8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
+        3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+    };
+    int8 shiftCount;
+
+    shiftCount = 0;
+    if ( a < 0x10000 ) {
+        shiftCount += 16;
+        a <<= 16;
+    }
+    if ( a < 0x1000000 ) {
+        shiftCount += 8;
+        a <<= 8;
+    }
+    shiftCount += countLeadingZerosHigh[ a>>24 ];
+    return shiftCount;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the 64-bit value formed by concatenating `a0' and `a1' is
+equal to the 64-bit value formed by concatenating `b0' and `b1'.  Otherwise,
+returns 0.
+-------------------------------------------------------------------------------
+*/
+INLINE flag eq64( bits32 a0, bits32 a1, bits32 b0, bits32 b1 )
+{
+
+    return ( a0 == b0 ) && ( a1 == b1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the 64-bit value formed by concatenating `a0' and `a1' is less
+than or equal to the 64-bit value formed by concatenating `b0' and `b1'.
+Otherwise, returns 0.
+-------------------------------------------------------------------------------
+*/
+INLINE flag le64( bits32 a0, bits32 a1, bits32 b0, bits32 b1 )
+{
+
+    return ( a0 < b0 ) || ( ( a0 == b0 ) && ( a1 <= b1 ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the 64-bit value formed by concatenating `a0' and `a1' is less
+than the 64-bit value formed by concatenating `b0' and `b1'.  Otherwise,
+returns 0.
+-------------------------------------------------------------------------------
+*/
+INLINE flag lt64( bits32 a0, bits32 a1, bits32 b0, bits32 b1 )
+{
+
+    return ( a0 < b0 ) || ( ( a0 == b0 ) && ( a1 < b1 ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the 64-bit value formed by concatenating `a0' and `a1' is not
+equal to the 64-bit value formed by concatenating `b0' and `b1'.  Otherwise,
+returns 0.
+-------------------------------------------------------------------------------
+*/
+INLINE flag ne64( bits32 a0, bits32 a1, bits32 b0, bits32 b1 )
+{
+
+    return ( a0 != b0 ) || ( a1 != b1 );
+
+}
+
diff --git a/lib/nbsd_libc/softfloat/bits32/softfloat.c b/lib/nbsd_libc/softfloat/bits32/softfloat.c
new file mode 100644 (file)
index 0000000..bf9c37e
--- /dev/null
@@ -0,0 +1,2349 @@
+/* $NetBSD: softfloat.c,v 1.1 2002/05/21 23:51:07 bjh21 Exp $ */
+
+/*
+ * This version hacked for use with gcc -msoft-float by bjh21.
+ * (Mostly a case of #ifdefing out things GCC doesn't need or provides
+ *  itself).
+ */
+
+/*
+ * Things you may want to define:
+ *
+ * SOFTFLOAT_FOR_GCC - build only those functions necessary for GCC (with
+ *   -msoft-float) to work.  Include "softfloat-for-gcc.h" to get them
+ *   properly renamed.
+ */
+
+/*
+ * This differs from the standard bits32/softfloat.c in that float64
+ * is defined to be a 64-bit integer rather than a structure.  The
+ * structure is float64s, with translation between the two going via
+ * float64u.
+ */
+
+/*
+===============================================================================
+
+This C source file is part of the SoftFloat IEC/IEEE Floating-Point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: softfloat.c,v 1.1 2002/05/21 23:51:07 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef SOFTFLOAT_FOR_GCC
+#include "softfloat-for-gcc.h"
+#endif
+
+#include "milieu.h"
+#include "softfloat.h"
+
+/*
+ * Conversions between floats as stored in memory and floats as
+ * SoftFloat uses them
+ */
+#ifndef FLOAT64_DEMANGLE
+#define FLOAT64_DEMANGLE(a)    (a)
+#endif
+#ifndef FLOAT64_MANGLE
+#define FLOAT64_MANGLE(a)      (a)
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Floating-point rounding mode and exception flags.
+-------------------------------------------------------------------------------
+*/
+fp_rnd float_rounding_mode = float_round_nearest_even;
+fp_except float_exception_flags = 0;
+
+/*
+-------------------------------------------------------------------------------
+Primitive arithmetic functions, including multi-word arithmetic, and
+division and square root approximations.  (Can be specialized to target if
+desired.)
+-------------------------------------------------------------------------------
+*/
+#include "softfloat-macros"
+
+/*
+-------------------------------------------------------------------------------
+Functions and definitions to determine:  (1) whether tininess for underflow
+is detected before or after rounding by default, (2) what (if anything)
+happens when exceptions are raised, (3) how signaling NaNs are distinguished
+from quiet NaNs, (4) the default generated quiet NaNs, and (4) how NaNs
+are propagated from function inputs to output.  These details are target-
+specific.
+-------------------------------------------------------------------------------
+*/
+#include "softfloat-specialize"
+
+/*
+-------------------------------------------------------------------------------
+Returns the fraction bits of the single-precision floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE bits32 extractFloat32Frac( float32 a )
+{
+
+    return a & 0x007FFFFF;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the exponent bits of the single-precision floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE int16 extractFloat32Exp( float32 a )
+{
+
+    return ( a>>23 ) & 0xFF;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the sign bit of the single-precision floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE flag extractFloat32Sign( float32 a )
+{
+
+    return a>>31;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Normalizes the subnormal single-precision floating-point value represented
+by the denormalized significand `aSig'.  The normalized exponent and
+significand are stored at the locations pointed to by `zExpPtr' and
+`zSigPtr', respectively.
+-------------------------------------------------------------------------------
+*/
+static void
+ normalizeFloat32Subnormal( bits32 aSig, int16 *zExpPtr, bits32 *zSigPtr )
+{
+    int8 shiftCount;
+
+    shiftCount = countLeadingZeros32( aSig ) - 8;
+    *zSigPtr = aSig<<shiftCount;
+    *zExpPtr = 1 - shiftCount;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Packs the sign `zSign', exponent `zExp', and significand `zSig' into a
+single-precision floating-point value, returning the result.  After being
+shifted into the proper positions, the three fields are simply added
+together to form the result.  This means that any integer portion of `zSig'
+will be added into the exponent.  Since a properly normalized significand
+will have an integer portion equal to 1, the `zExp' input should be 1 less
+than the desired result exponent whenever `zSig' is a complete, normalized
+significand.
+-------------------------------------------------------------------------------
+*/
+INLINE float32 packFloat32( flag zSign, int16 zExp, bits32 zSig )
+{
+
+    return ( ( (bits32) zSign )<<31 ) + ( ( (bits32) zExp )<<23 ) + zSig;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes an abstract floating-point value having sign `zSign', exponent `zExp',
+and significand `zSig', and returns the proper single-precision floating-
+point value corresponding to the abstract input.  Ordinarily, the abstract
+value is simply rounded and packed into the single-precision format, with
+the inexact exception raised if the abstract input cannot be represented
+exactly.  However, if the abstract value is too large, the overflow and
+inexact exceptions are raised and an infinity or maximal finite value is
+returned.  If the abstract value is too small, the input value is rounded to
+a subnormal number, and the underflow and inexact exceptions are raised if
+the abstract input cannot be represented exactly as a subnormal single-
+precision floating-point number.
+    The input significand `zSig' has its binary point between bits 30
+and 29, which is 7 bits to the left of the usual location.  This shifted
+significand must be normalized or smaller.  If `zSig' is not normalized,
+`zExp' must be 0; in that case, the result returned is a subnormal number,
+and it must not require rounding.  In the usual case that `zSig' is
+normalized, `zExp' must be 1 less than the ``true'' floating-point exponent.
+The handling of underflow and overflow follows the IEC/IEEE Standard for
+Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float32 roundAndPackFloat32( flag zSign, int16 zExp, bits32 zSig )
+{
+    int8 roundingMode;
+    flag roundNearestEven;
+    int8 roundIncrement, roundBits;
+    flag isTiny;
+
+    roundingMode = float_rounding_mode;
+    roundNearestEven = roundingMode == float_round_nearest_even;
+    roundIncrement = 0x40;
+    if ( ! roundNearestEven ) {
+        if ( roundingMode == float_round_to_zero ) {
+            roundIncrement = 0;
+        }
+        else {
+            roundIncrement = 0x7F;
+            if ( zSign ) {
+                if ( roundingMode == float_round_up ) roundIncrement = 0;
+            }
+            else {
+                if ( roundingMode == float_round_down ) roundIncrement = 0;
+            }
+        }
+    }
+    roundBits = zSig & 0x7F;
+    if ( 0xFD <= (bits16) zExp ) {
+        if (    ( 0xFD < zExp )
+             || (    ( zExp == 0xFD )
+                  && ( (sbits32) ( zSig + roundIncrement ) < 0 ) )
+           ) {
+            float_raise( float_flag_overflow | float_flag_inexact );
+            return packFloat32( zSign, 0xFF, 0 ) - ( roundIncrement == 0 );
+        }
+        if ( zExp < 0 ) {
+            isTiny =
+                   ( float_detect_tininess == float_tininess_before_rounding )
+                || ( zExp < -1 )
+                || ( zSig + roundIncrement < 0x80000000 );
+            shift32RightJamming( zSig, - zExp, &zSig );
+            zExp = 0;
+            roundBits = zSig & 0x7F;
+            if ( isTiny && roundBits ) float_raise( float_flag_underflow );
+        }
+    }
+    if ( roundBits ) float_exception_flags |= float_flag_inexact;
+    zSig = ( zSig + roundIncrement )>>7;
+    zSig &= ~ ( ( ( roundBits ^ 0x40 ) == 0 ) & roundNearestEven );
+    if ( zSig == 0 ) zExp = 0;
+    return packFloat32( zSign, zExp, zSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes an abstract floating-point value having sign `zSign', exponent `zExp',
+and significand `zSig', and returns the proper single-precision floating-
+point value corresponding to the abstract input.  This routine is just like
+`roundAndPackFloat32' except that `zSig' does not have to be normalized.
+Bit 31 of `zSig' must be zero, and `zExp' must be 1 less than the ``true''
+floating-point exponent.
+-------------------------------------------------------------------------------
+*/
+static float32
+ normalizeRoundAndPackFloat32( flag zSign, int16 zExp, bits32 zSig )
+{
+    int8 shiftCount;
+
+    shiftCount = countLeadingZeros32( zSig ) - 1;
+    return roundAndPackFloat32( zSign, zExp - shiftCount, zSig<<shiftCount );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the least-significant 32 fraction bits of the double-precision
+floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE bits32 extractFloat64Frac1( float64 a )
+{
+
+    return FLOAT64_DEMANGLE(a) & LIT64( 0x00000000FFFFFFFF );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the most-significant 20 fraction bits of the double-precision
+floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE bits32 extractFloat64Frac0( float64 a )
+{
+
+    return ( FLOAT64_DEMANGLE(a)>>32 ) & 0x000FFFFF;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the exponent bits of the double-precision floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE int16 extractFloat64Exp( float64 a )
+{
+
+    return ( FLOAT64_DEMANGLE(a)>>52 ) & 0x7FF;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the sign bit of the double-precision floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE flag extractFloat64Sign( float64 a )
+{
+
+    return FLOAT64_DEMANGLE(a)>>63;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Normalizes the subnormal double-precision floating-point value represented
+by the denormalized significand formed by the concatenation of `aSig0' and
+`aSig1'.  The normalized exponent is stored at the location pointed to by
+`zExpPtr'.  The most significant 21 bits of the normalized significand are
+stored at the location pointed to by `zSig0Ptr', and the least significant
+32 bits of the normalized significand are stored at the location pointed to
+by `zSig1Ptr'.
+-------------------------------------------------------------------------------
+*/
+static void
+ normalizeFloat64Subnormal(
+     bits32 aSig0,
+     bits32 aSig1,
+     int16 *zExpPtr,
+     bits32 *zSig0Ptr,
+     bits32 *zSig1Ptr
+ )
+{
+    int8 shiftCount;
+
+    if ( aSig0 == 0 ) {
+        shiftCount = countLeadingZeros32( aSig1 ) - 11;
+        if ( shiftCount < 0 ) {
+            *zSig0Ptr = aSig1>>( - shiftCount );
+            *zSig1Ptr = aSig1<<( shiftCount & 31 );
+        }
+        else {
+            *zSig0Ptr = aSig1<<shiftCount;
+            *zSig1Ptr = 0;
+        }
+        *zExpPtr = - shiftCount - 31;
+    }
+    else {
+        shiftCount = countLeadingZeros32( aSig0 ) - 11;
+        shortShift64Left( aSig0, aSig1, shiftCount, zSig0Ptr, zSig1Ptr );
+        *zExpPtr = 1 - shiftCount;
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Packs the sign `zSign', the exponent `zExp', and the significand formed by
+the concatenation of `zSig0' and `zSig1' into a double-precision floating-
+point value, returning the result.  After being shifted into the proper
+positions, the three fields `zSign', `zExp', and `zSig0' are simply added
+together to form the most significant 32 bits of the result.  This means
+that any integer portion of `zSig0' will be added into the exponent.  Since
+a properly normalized significand will have an integer portion equal to 1,
+the `zExp' input should be 1 less than the desired result exponent whenever
+`zSig0' and `zSig1' concatenated form a complete, normalized significand.
+-------------------------------------------------------------------------------
+*/
+INLINE float64
+ packFloat64( flag zSign, int16 zExp, bits32 zSig0, bits32 zSig1 )
+{
+
+    return FLOAT64_MANGLE( ( ( (bits64) zSign )<<63 ) +
+                          ( ( (bits64) zExp )<<52 ) + 
+                          ( ( (bits64) zSig0 )<<32 ) + zSig1 );
+
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes an abstract floating-point value having sign `zSign', exponent `zExp',
+and extended significand formed by the concatenation of `zSig0', `zSig1',
+and `zSig2', and returns the proper double-precision floating-point value
+corresponding to the abstract input.  Ordinarily, the abstract value is
+simply rounded and packed into the double-precision format, with the inexact
+exception raised if the abstract input cannot be represented exactly.
+However, if the abstract value is too large, the overflow and inexact
+exceptions are raised and an infinity or maximal finite value is returned.
+If the abstract value is too small, the input value is rounded to a
+subnormal number, and the underflow and inexact exceptions are raised if the
+abstract input cannot be represented exactly as a subnormal double-precision
+floating-point number.
+    The input significand must be normalized or smaller.  If the input
+significand is not normalized, `zExp' must be 0; in that case, the result
+returned is a subnormal number, and it must not require rounding.  In the
+usual case that the input significand is normalized, `zExp' must be 1 less
+than the ``true'' floating-point exponent.  The handling of underflow and
+overflow follows the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float64
+ roundAndPackFloat64(
+     flag zSign, int16 zExp, bits32 zSig0, bits32 zSig1, bits32 zSig2 )
+{
+    int8 roundingMode;
+    flag roundNearestEven, increment, isTiny;
+
+    roundingMode = float_rounding_mode;
+    roundNearestEven = ( roundingMode == float_round_nearest_even );
+    increment = ( (sbits32) zSig2 < 0 );
+    if ( ! roundNearestEven ) {
+        if ( roundingMode == float_round_to_zero ) {
+            increment = 0;
+        }
+        else {
+            if ( zSign ) {
+                increment = ( roundingMode == float_round_down ) && zSig2;
+            }
+            else {
+                increment = ( roundingMode == float_round_up ) && zSig2;
+            }
+        }
+    }
+    if ( 0x7FD <= (bits16) zExp ) {
+        if (    ( 0x7FD < zExp )
+             || (    ( zExp == 0x7FD )
+                  && eq64( 0x001FFFFF, 0xFFFFFFFF, zSig0, zSig1 )
+                  && increment
+                )
+           ) {
+            float_raise( float_flag_overflow | float_flag_inexact );
+            if (    ( roundingMode == float_round_to_zero )
+                 || ( zSign && ( roundingMode == float_round_up ) )
+                 || ( ! zSign && ( roundingMode == float_round_down ) )
+               ) {
+                return packFloat64( zSign, 0x7FE, 0x000FFFFF, 0xFFFFFFFF );
+            }
+            return packFloat64( zSign, 0x7FF, 0, 0 );
+        }
+        if ( zExp < 0 ) {
+            isTiny =
+                   ( float_detect_tininess == float_tininess_before_rounding )
+                || ( zExp < -1 )
+                || ! increment
+                || lt64( zSig0, zSig1, 0x001FFFFF, 0xFFFFFFFF );
+            shift64ExtraRightJamming(
+                zSig0, zSig1, zSig2, - zExp, &zSig0, &zSig1, &zSig2 );
+            zExp = 0;
+            if ( isTiny && zSig2 ) float_raise( float_flag_underflow );
+            if ( roundNearestEven ) {
+                increment = ( (sbits32) zSig2 < 0 );
+            }
+            else {
+                if ( zSign ) {
+                    increment = ( roundingMode == float_round_down ) && zSig2;
+                }
+                else {
+                    increment = ( roundingMode == float_round_up ) && zSig2;
+                }
+            }
+        }
+    }
+    if ( zSig2 ) float_exception_flags |= float_flag_inexact;
+    if ( increment ) {
+        add64( zSig0, zSig1, 0, 1, &zSig0, &zSig1 );
+        zSig1 &= ~ ( ( zSig2 + zSig2 == 0 ) & roundNearestEven );
+    }
+    else {
+        if ( ( zSig0 | zSig1 ) == 0 ) zExp = 0;
+    }
+    return packFloat64( zSign, zExp, zSig0, zSig1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes an abstract floating-point value having sign `zSign', exponent `zExp',
+and significand formed by the concatenation of `zSig0' and `zSig1', and
+returns the proper double-precision floating-point value corresponding
+to the abstract input.  This routine is just like `roundAndPackFloat64'
+except that the input significand has fewer bits and does not have to be
+normalized.  In all cases, `zExp' must be 1 less than the ``true'' floating-
+point exponent.
+-------------------------------------------------------------------------------
+*/
+static float64
+ normalizeRoundAndPackFloat64(
+     flag zSign, int16 zExp, bits32 zSig0, bits32 zSig1 )
+{
+    int8 shiftCount;
+    bits32 zSig2;
+
+    if ( zSig0 == 0 ) {
+        zSig0 = zSig1;
+        zSig1 = 0;
+        zExp -= 32;
+    }
+    shiftCount = countLeadingZeros32( zSig0 ) - 11;
+    if ( 0 <= shiftCount ) {
+        zSig2 = 0;
+        shortShift64Left( zSig0, zSig1, shiftCount, &zSig0, &zSig1 );
+    }
+    else {
+        shift64ExtraRightJamming(
+            zSig0, zSig1, 0, - shiftCount, &zSig0, &zSig1, &zSig2 );
+    }
+    zExp -= shiftCount;
+    return roundAndPackFloat64( zSign, zExp, zSig0, zSig1, zSig2 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the 32-bit two's complement integer `a' to
+the single-precision floating-point format.  The conversion is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 int32_to_float32( int32 a )
+{
+    flag zSign;
+
+    if ( a == 0 ) return 0;
+    if ( a == (sbits32) 0x80000000 ) return packFloat32( 1, 0x9E, 0 );
+    zSign = ( a < 0 );
+    return normalizeRoundAndPackFloat32( zSign, 0x9C, zSign ? - a : a );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the 32-bit two's complement integer `a' to
+the double-precision floating-point format.  The conversion is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 int32_to_float64( int32 a )
+{
+    flag zSign;
+    bits32 absA;
+    int8 shiftCount;
+    bits32 zSig0, zSig1;
+
+    if ( a == 0 ) return packFloat64( 0, 0, 0, 0 );
+    zSign = ( a < 0 );
+    absA = zSign ? - a : a;
+    shiftCount = countLeadingZeros32( absA ) - 11;
+    if ( 0 <= shiftCount ) {
+        zSig0 = absA<<shiftCount;
+        zSig1 = 0;
+    }
+    else {
+        shift64Right( absA, 0, - shiftCount, &zSig0, &zSig1 );
+    }
+    return packFloat64( zSign, 0x412 - shiftCount, zSig0, zSig1 );
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the single-precision floating-point value
+`a' to the 32-bit two's complement integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic---which means in particular that the conversion is rounded
+according to the current rounding mode.  If `a' is a NaN, the largest
+positive integer is returned.  Otherwise, if the conversion overflows, the
+largest integer with the same sign as `a' is returned.
+-------------------------------------------------------------------------------
+*/
+int32 float32_to_int32( float32 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits32 aSig, aSigExtra;
+    int32 z;
+    int8 roundingMode;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    shiftCount = aExp - 0x96;
+    if ( 0 <= shiftCount ) {
+        if ( 0x9E <= aExp ) {
+            if ( a != 0xCF000000 ) {
+                float_raise( float_flag_invalid );
+                if ( ! aSign || ( ( aExp == 0xFF ) && aSig ) ) {
+                    return 0x7FFFFFFF;
+                }
+            }
+            return (sbits32) 0x80000000;
+        }
+        z = ( aSig | 0x00800000 )<<shiftCount;
+        if ( aSign ) z = - z;
+    }
+    else {
+        if ( aExp < 0x7E ) {
+            aSigExtra = aExp | aSig;
+            z = 0;
+        }
+        else {
+            aSig |= 0x00800000;
+            aSigExtra = aSig<<( shiftCount & 31 );
+            z = aSig>>( - shiftCount );
+        }
+        if ( aSigExtra ) float_exception_flags |= float_flag_inexact;
+        roundingMode = float_rounding_mode;
+        if ( roundingMode == float_round_nearest_even ) {
+            if ( (sbits32) aSigExtra < 0 ) {
+                ++z;
+                if ( (bits32) ( aSigExtra<<1 ) == 0 ) z &= ~1;
+            }
+            if ( aSign ) z = - z;
+        }
+        else {
+            aSigExtra = ( aSigExtra != 0 );
+            if ( aSign ) {
+                z += ( roundingMode == float_round_down ) & aSigExtra;
+                z = - z;
+            }
+            else {
+                z += ( roundingMode == float_round_up ) & aSigExtra;
+            }
+        }
+    }
+    return z;
+
+}
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the single-precision floating-point value
+`a' to the 32-bit two's complement integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic, except that the conversion is always rounded toward zero.
+If `a' is a NaN, the largest positive integer is returned.  Otherwise, if
+the conversion overflows, the largest integer with the same sign as `a' is
+returned.
+-------------------------------------------------------------------------------
+*/
+int32 float32_to_int32_round_to_zero( float32 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits32 aSig;
+    int32 z;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    shiftCount = aExp - 0x9E;
+    if ( 0 <= shiftCount ) {
+        if ( a != 0xCF000000 ) {
+            float_raise( float_flag_invalid );
+            if ( ! aSign || ( ( aExp == 0xFF ) && aSig ) ) return 0x7FFFFFFF;
+        }
+        return (sbits32) 0x80000000;
+    }
+    else if ( aExp <= 0x7E ) {
+        if ( aExp | aSig ) float_exception_flags |= float_flag_inexact;
+        return 0;
+    }
+    aSig = ( aSig | 0x00800000 )<<8;
+    z = aSig>>( - shiftCount );
+    if ( (bits32) ( aSig<<( shiftCount & 31 ) ) ) {
+        float_exception_flags |= float_flag_inexact;
+    }
+    if ( aSign ) z = - z;
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the single-precision floating-point value
+`a' to the double-precision floating-point format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float32_to_float64( float32 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits32 aSig, zSig0, zSig1;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    if ( aExp == 0xFF ) {
+        if ( aSig ) return commonNaNToFloat64( float32ToCommonNaN( a ) );
+        return packFloat64( aSign, 0x7FF, 0, 0 );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloat64( aSign, 0, 0, 0 );
+        normalizeFloat32Subnormal( aSig, &aExp, &aSig );
+        --aExp;
+    }
+    shift64Right( aSig, 0, 3, &zSig0, &zSig1 );
+    return packFloat64( aSign, aExp + 0x380, zSig0, zSig1 );
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC
+/*
+-------------------------------------------------------------------------------
+Rounds the single-precision floating-point value `a' to an integer,
+and returns the result as a single-precision floating-point value.  The
+operation is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_round_to_int( float32 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits32 lastBitMask, roundBitsMask;
+    int8 roundingMode;
+    float32 z;
+
+    aExp = extractFloat32Exp( a );
+    if ( 0x96 <= aExp ) {
+        if ( ( aExp == 0xFF ) && extractFloat32Frac( a ) ) {
+            return propagateFloat32NaN( a, a );
+        }
+        return a;
+    }
+    if ( aExp <= 0x7E ) {
+        if ( (bits32) ( a<<1 ) == 0 ) return a;
+        float_exception_flags |= float_flag_inexact;
+        aSign = extractFloat32Sign( a );
+        switch ( float_rounding_mode ) {
+         case float_round_nearest_even:
+            if ( ( aExp == 0x7E ) && extractFloat32Frac( a ) ) {
+                return packFloat32( aSign, 0x7F, 0 );
+            }
+            break;
+        case float_round_to_zero:
+           break;
+         case float_round_down:
+            return aSign ? 0xBF800000 : 0;
+         case float_round_up:
+            return aSign ? 0x80000000 : 0x3F800000;
+        }
+        return packFloat32( aSign, 0, 0 );
+    }
+    lastBitMask = 1;
+    lastBitMask <<= 0x96 - aExp;
+    roundBitsMask = lastBitMask - 1;
+    z = a;
+    roundingMode = float_rounding_mode;
+    if ( roundingMode == float_round_nearest_even ) {
+        z += lastBitMask>>1;
+        if ( ( z & roundBitsMask ) == 0 ) z &= ~ lastBitMask;
+    }
+    else if ( roundingMode != float_round_to_zero ) {
+        if ( extractFloat32Sign( z ) ^ ( roundingMode == float_round_up ) ) {
+            z += roundBitsMask;
+        }
+    }
+    z &= ~ roundBitsMask;
+    if ( z != a ) float_exception_flags |= float_flag_inexact;
+    return z;
+
+}
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of adding the absolute values of the single-precision
+floating-point values `a' and `b'.  If `zSign' is 1, the sum is negated
+before being returned.  `zSign' is ignored if the result is a NaN.
+The addition is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float32 addFloat32Sigs( float32 a, float32 b, flag zSign )
+{
+    int16 aExp, bExp, zExp;
+    bits32 aSig, bSig, zSig;
+    int16 expDiff;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    bSig = extractFloat32Frac( b );
+    bExp = extractFloat32Exp( b );
+    expDiff = aExp - bExp;
+    aSig <<= 6;
+    bSig <<= 6;
+    if ( 0 < expDiff ) {
+        if ( aExp == 0xFF ) {
+            if ( aSig ) return propagateFloat32NaN( a, b );
+            return a;
+        }
+        if ( bExp == 0 ) {
+            --expDiff;
+        }
+        else {
+            bSig |= 0x20000000;
+        }
+        shift32RightJamming( bSig, expDiff, &bSig );
+        zExp = aExp;
+    }
+    else if ( expDiff < 0 ) {
+        if ( bExp == 0xFF ) {
+            if ( bSig ) return propagateFloat32NaN( a, b );
+            return packFloat32( zSign, 0xFF, 0 );
+        }
+        if ( aExp == 0 ) {
+            ++expDiff;
+        }
+        else {
+            aSig |= 0x20000000;
+        }
+        shift32RightJamming( aSig, - expDiff, &aSig );
+        zExp = bExp;
+    }
+    else {
+        if ( aExp == 0xFF ) {
+            if ( aSig | bSig ) return propagateFloat32NaN( a, b );
+            return a;
+        }
+        if ( aExp == 0 ) return packFloat32( zSign, 0, ( aSig + bSig )>>6 );
+        zSig = 0x40000000 + aSig + bSig;
+        zExp = aExp;
+        goto roundAndPack;
+    }
+    aSig |= 0x20000000;
+    zSig = ( aSig + bSig )<<1;
+    --zExp;
+    if ( (sbits32) zSig < 0 ) {
+        zSig = aSig + bSig;
+        ++zExp;
+    }
+ roundAndPack:
+    return roundAndPackFloat32( zSign, zExp, zSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of subtracting the absolute values of the single-
+precision floating-point values `a' and `b'.  If `zSign' is 1, the
+difference is negated before being returned.  `zSign' is ignored if the
+result is a NaN.  The subtraction is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float32 subFloat32Sigs( float32 a, float32 b, flag zSign )
+{
+    int16 aExp, bExp, zExp;
+    bits32 aSig, bSig, zSig;
+    int16 expDiff;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    bSig = extractFloat32Frac( b );
+    bExp = extractFloat32Exp( b );
+    expDiff = aExp - bExp;
+    aSig <<= 7;
+    bSig <<= 7;
+    if ( 0 < expDiff ) goto aExpBigger;
+    if ( expDiff < 0 ) goto bExpBigger;
+    if ( aExp == 0xFF ) {
+        if ( aSig | bSig ) return propagateFloat32NaN( a, b );
+        float_raise( float_flag_invalid );
+        return float32_default_nan;
+    }
+    if ( aExp == 0 ) {
+        aExp = 1;
+        bExp = 1;
+    }
+    if ( bSig < aSig ) goto aBigger;
+    if ( aSig < bSig ) goto bBigger;
+    return packFloat32( float_rounding_mode == float_round_down, 0, 0 );
+ bExpBigger:
+    if ( bExp == 0xFF ) {
+        if ( bSig ) return propagateFloat32NaN( a, b );
+        return packFloat32( zSign ^ 1, 0xFF, 0 );
+    }
+    if ( aExp == 0 ) {
+        ++expDiff;
+    }
+    else {
+        aSig |= 0x40000000;
+    }
+    shift32RightJamming( aSig, - expDiff, &aSig );
+    bSig |= 0x40000000;
+ bBigger:
+    zSig = bSig - aSig;
+    zExp = bExp;
+    zSign ^= 1;
+    goto normalizeRoundAndPack;
+ aExpBigger:
+    if ( aExp == 0xFF ) {
+        if ( aSig ) return propagateFloat32NaN( a, b );
+        return a;
+    }
+    if ( bExp == 0 ) {
+        --expDiff;
+    }
+    else {
+        bSig |= 0x40000000;
+    }
+    shift32RightJamming( bSig, expDiff, &bSig );
+    aSig |= 0x40000000;
+ aBigger:
+    zSig = aSig - bSig;
+    zExp = aExp;
+ normalizeRoundAndPack:
+    --zExp;
+    return normalizeRoundAndPackFloat32( zSign, zExp, zSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of adding the single-precision floating-point values `a'
+and `b'.  The operation is performed according to the IEC/IEEE Standard for
+Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_add( float32 a, float32 b )
+{
+    flag aSign, bSign;
+
+    aSign = extractFloat32Sign( a );
+    bSign = extractFloat32Sign( b );
+    if ( aSign == bSign ) {
+        return addFloat32Sigs( a, b, aSign );
+    }
+    else {
+        return subFloat32Sigs( a, b, aSign );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of subtracting the single-precision floating-point values
+`a' and `b'.  The operation is performed according to the IEC/IEEE Standard
+for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_sub( float32 a, float32 b )
+{
+    flag aSign, bSign;
+
+    aSign = extractFloat32Sign( a );
+    bSign = extractFloat32Sign( b );
+    if ( aSign == bSign ) {
+        return subFloat32Sigs( a, b, aSign );
+    }
+    else {
+        return addFloat32Sigs( a, b, aSign );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of multiplying the single-precision floating-point values
+`a' and `b'.  The operation is performed according to the IEC/IEEE Standard
+for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_mul( float32 a, float32 b )
+{
+    flag aSign, bSign, zSign;
+    int16 aExp, bExp, zExp;
+    bits32 aSig, bSig, zSig0, zSig1;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    bSig = extractFloat32Frac( b );
+    bExp = extractFloat32Exp( b );
+    bSign = extractFloat32Sign( b );
+    zSign = aSign ^ bSign;
+    if ( aExp == 0xFF ) {
+        if ( aSig || ( ( bExp == 0xFF ) && bSig ) ) {
+            return propagateFloat32NaN( a, b );
+        }
+        if ( ( bExp | bSig ) == 0 ) {
+            float_raise( float_flag_invalid );
+            return float32_default_nan;
+        }
+        return packFloat32( zSign, 0xFF, 0 );
+    }
+    if ( bExp == 0xFF ) {
+        if ( bSig ) return propagateFloat32NaN( a, b );
+        if ( ( aExp | aSig ) == 0 ) {
+            float_raise( float_flag_invalid );
+            return float32_default_nan;
+        }
+        return packFloat32( zSign, 0xFF, 0 );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloat32( zSign, 0, 0 );
+        normalizeFloat32Subnormal( aSig, &aExp, &aSig );
+    }
+    if ( bExp == 0 ) {
+        if ( bSig == 0 ) return packFloat32( zSign, 0, 0 );
+        normalizeFloat32Subnormal( bSig, &bExp, &bSig );
+    }
+    zExp = aExp + bExp - 0x7F;
+    aSig = ( aSig | 0x00800000 )<<7;
+    bSig = ( bSig | 0x00800000 )<<8;
+    mul32To64( aSig, bSig, &zSig0, &zSig1 );
+    zSig0 |= ( zSig1 != 0 );
+    if ( 0 <= (sbits32) ( zSig0<<1 ) ) {
+        zSig0 <<= 1;
+        --zExp;
+    }
+    return roundAndPackFloat32( zSign, zExp, zSig0 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of dividing the single-precision floating-point value `a'
+by the corresponding value `b'.  The operation is performed according to the
+IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_div( float32 a, float32 b )
+{
+    flag aSign, bSign, zSign;
+    int16 aExp, bExp, zExp;
+    bits32 aSig, bSig, zSig, rem0, rem1, term0, term1;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    bSig = extractFloat32Frac( b );
+    bExp = extractFloat32Exp( b );
+    bSign = extractFloat32Sign( b );
+    zSign = aSign ^ bSign;
+    if ( aExp == 0xFF ) {
+        if ( aSig ) return propagateFloat32NaN( a, b );
+        if ( bExp == 0xFF ) {
+            if ( bSig ) return propagateFloat32NaN( a, b );
+            float_raise( float_flag_invalid );
+            return float32_default_nan;
+        }
+        return packFloat32( zSign, 0xFF, 0 );
+    }
+    if ( bExp == 0xFF ) {
+        if ( bSig ) return propagateFloat32NaN( a, b );
+        return packFloat32( zSign, 0, 0 );
+    }
+    if ( bExp == 0 ) {
+        if ( bSig == 0 ) {
+            if ( ( aExp | aSig ) == 0 ) {
+                float_raise( float_flag_invalid );
+                return float32_default_nan;
+            }
+            float_raise( float_flag_divbyzero );
+            return packFloat32( zSign, 0xFF, 0 );
+        }
+        normalizeFloat32Subnormal( bSig, &bExp, &bSig );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloat32( zSign, 0, 0 );
+        normalizeFloat32Subnormal( aSig, &aExp, &aSig );
+    }
+    zExp = aExp - bExp + 0x7D;
+    aSig = ( aSig | 0x00800000 )<<7;
+    bSig = ( bSig | 0x00800000 )<<8;
+    if ( bSig <= ( aSig + aSig ) ) {
+        aSig >>= 1;
+        ++zExp;
+    }
+    zSig = estimateDiv64To32( aSig, 0, bSig );
+    if ( ( zSig & 0x3F ) <= 2 ) {
+        mul32To64( bSig, zSig, &term0, &term1 );
+        sub64( aSig, 0, term0, term1, &rem0, &rem1 );
+        while ( (sbits32) rem0 < 0 ) {
+            --zSig;
+            add64( rem0, rem1, 0, bSig, &rem0, &rem1 );
+        }
+        zSig |= ( rem1 != 0 );
+    }
+    return roundAndPackFloat32( zSign, zExp, zSig );
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC
+/*
+-------------------------------------------------------------------------------
+Returns the remainder of the single-precision floating-point value `a'
+with respect to the corresponding value `b'.  The operation is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_rem( float32 a, float32 b )
+{
+    flag aSign, bSign, zSign;
+    int16 aExp, bExp, expDiff;
+    bits32 aSig, bSig, q, allZero, alternateASig;
+    sbits32 sigMean;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    bSig = extractFloat32Frac( b );
+    bExp = extractFloat32Exp( b );
+    bSign = extractFloat32Sign( b );
+    if ( aExp == 0xFF ) {
+        if ( aSig || ( ( bExp == 0xFF ) && bSig ) ) {
+            return propagateFloat32NaN( a, b );
+        }
+        float_raise( float_flag_invalid );
+        return float32_default_nan;
+    }
+    if ( bExp == 0xFF ) {
+        if ( bSig ) return propagateFloat32NaN( a, b );
+        return a;
+    }
+    if ( bExp == 0 ) {
+        if ( bSig == 0 ) {
+            float_raise( float_flag_invalid );
+            return float32_default_nan;
+        }
+        normalizeFloat32Subnormal( bSig, &bExp, &bSig );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return a;
+        normalizeFloat32Subnormal( aSig, &aExp, &aSig );
+    }
+    expDiff = aExp - bExp;
+    aSig = ( aSig | 0x00800000 )<<8;
+    bSig = ( bSig | 0x00800000 )<<8;
+    if ( expDiff < 0 ) {
+        if ( expDiff < -1 ) return a;
+        aSig >>= 1;
+    }
+    q = ( bSig <= aSig );
+    if ( q ) aSig -= bSig;
+    expDiff -= 32;
+    while ( 0 < expDiff ) {
+        q = estimateDiv64To32( aSig, 0, bSig );
+        q = ( 2 < q ) ? q - 2 : 0;
+        aSig = - ( ( bSig>>2 ) * q );
+        expDiff -= 30;
+    }
+    expDiff += 32;
+    if ( 0 < expDiff ) {
+        q = estimateDiv64To32( aSig, 0, bSig );
+        q = ( 2 < q ) ? q - 2 : 0;
+        q >>= 32 - expDiff;
+        bSig >>= 2;
+        aSig = ( ( aSig>>1 )<<( expDiff - 1 ) ) - bSig * q;
+    }
+    else {
+        aSig >>= 2;
+        bSig >>= 2;
+    }
+    do {
+        alternateASig = aSig;
+        ++q;
+        aSig -= bSig;
+    } while ( 0 <= (sbits32) aSig );
+    sigMean = aSig + alternateASig;
+    if ( ( sigMean < 0 ) || ( ( sigMean == 0 ) && ( q & 1 ) ) ) {
+        aSig = alternateASig;
+    }
+    zSign = ( (sbits32) aSig < 0 );
+    if ( zSign ) aSig = - aSig;
+    return normalizeRoundAndPackFloat32( aSign ^ zSign, bExp, aSig );
+
+}
+#endif
+
+#ifndef SOFTFLOAT_FOR_GCC
+/*
+-------------------------------------------------------------------------------
+Returns the square root of the single-precision floating-point value `a'.
+The operation is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_sqrt( float32 a )
+{
+    flag aSign;
+    int16 aExp, zExp;
+    bits32 aSig, zSig, rem0, rem1, term0, term1;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    if ( aExp == 0xFF ) {
+        if ( aSig ) return propagateFloat32NaN( a, 0 );
+        if ( ! aSign ) return a;
+        float_raise( float_flag_invalid );
+        return float32_default_nan;
+    }
+    if ( aSign ) {
+        if ( ( aExp | aSig ) == 0 ) return a;
+        float_raise( float_flag_invalid );
+        return float32_default_nan;
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return 0;
+        normalizeFloat32Subnormal( aSig, &aExp, &aSig );
+    }
+    zExp = ( ( aExp - 0x7F )>>1 ) + 0x7E;
+    aSig = ( aSig | 0x00800000 )<<8;
+    zSig = estimateSqrt32( aExp, aSig ) + 2;
+    if ( ( zSig & 0x7F ) <= 5 ) {
+        if ( zSig < 2 ) {
+            zSig = 0x7FFFFFFF;
+            goto roundAndPack;
+        }
+        else {
+            aSig >>= aExp & 1;
+            mul32To64( zSig, zSig, &term0, &term1 );
+            sub64( aSig, 0, term0, term1, &rem0, &rem1 );
+            while ( (sbits32) rem0 < 0 ) {
+                --zSig;
+                shortShift64Left( 0, zSig, 1, &term0, &term1 );
+                term1 |= 1;
+                add64( rem0, rem1, term0, term1, &rem0, &rem1 );
+            }
+            zSig |= ( ( rem0 | rem1 ) != 0 );
+        }
+    }
+    shift32RightJamming( zSig, 1, &zSig );
+ roundAndPack:
+    return roundAndPackFloat32( 0, zExp, zSig );
+
+}
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is equal to
+the corresponding value `b', and 0 otherwise.  The comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float32_eq( float32 a, float32 b )
+{
+
+    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )
+         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )
+       ) {
+        if ( float32_is_signaling_nan( a ) || float32_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    return ( a == b ) || ( (bits32) ( ( a | b )<<1 ) == 0 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is less than
+or equal to the corresponding value `b', and 0 otherwise.  The comparison
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float32_le( float32 a, float32 b )
+{
+    flag aSign, bSign;
+
+    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )
+         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    aSign = extractFloat32Sign( a );
+    bSign = extractFloat32Sign( b );
+    if ( aSign != bSign ) return aSign || ( (bits32) ( ( a | b )<<1 ) == 0 );
+    return ( a == b ) || ( aSign ^ ( a < b ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is less than
+the corresponding value `b', and 0 otherwise.  The comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float32_lt( float32 a, float32 b )
+{
+    flag aSign, bSign;
+
+    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )
+         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    aSign = extractFloat32Sign( a );
+    bSign = extractFloat32Sign( b );
+    if ( aSign != bSign ) return aSign && ( (bits32) ( ( a | b )<<1 ) != 0 );
+    return ( a != b ) && ( aSign ^ ( a < b ) );
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC /* Not needed */
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is equal to
+the corresponding value `b', and 0 otherwise.  The invalid exception is
+raised if either operand is a NaN.  Otherwise, the comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float32_eq_signaling( float32 a, float32 b )
+{
+
+    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )
+         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    return ( a == b ) || ( (bits32) ( ( a | b )<<1 ) == 0 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is less than or
+equal to the corresponding value `b', and 0 otherwise.  Quiet NaNs do not
+cause an exception.  Otherwise, the comparison is performed according to the
+IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float32_le_quiet( float32 a, float32 b )
+{
+    flag aSign, bSign;
+    int16 aExp, bExp;
+
+    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )
+         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )
+       ) {
+        if ( float32_is_signaling_nan( a ) || float32_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    aSign = extractFloat32Sign( a );
+    bSign = extractFloat32Sign( b );
+    if ( aSign != bSign ) return aSign || ( (bits32) ( ( a | b )<<1 ) == 0 );
+    return ( a == b ) || ( aSign ^ ( a < b ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is less than
+the corresponding value `b', and 0 otherwise.  Quiet NaNs do not cause an
+exception.  Otherwise, the comparison is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float32_lt_quiet( float32 a, float32 b )
+{
+    flag aSign, bSign;
+
+    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )
+         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )
+       ) {
+        if ( float32_is_signaling_nan( a ) || float32_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    aSign = extractFloat32Sign( a );
+    bSign = extractFloat32Sign( b );
+    if ( aSign != bSign ) return aSign && ( (bits32) ( ( a | b )<<1 ) != 0 );
+    return ( a != b ) && ( aSign ^ ( a < b ) );
+
+}
+#endif /* !SOFTFLOAT_FOR_GCC */
+
+#ifndef SOFTFLOAT_FOR_GCC /* Not needed */
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the double-precision floating-point value
+`a' to the 32-bit two's complement integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic---which means in particular that the conversion is rounded
+according to the current rounding mode.  If `a' is a NaN, the largest
+positive integer is returned.  Otherwise, if the conversion overflows, the
+largest integer with the same sign as `a' is returned.
+-------------------------------------------------------------------------------
+*/
+int32 float64_to_int32( float64 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits32 aSig0, aSig1, absZ, aSigExtra;
+    int32 z;
+    int8 roundingMode;
+
+    aSig1 = extractFloat64Frac1( a );
+    aSig0 = extractFloat64Frac0( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    shiftCount = aExp - 0x413;
+    if ( 0 <= shiftCount ) {
+        if ( 0x41E < aExp ) {
+            if ( ( aExp == 0x7FF ) && ( aSig0 | aSig1 ) ) aSign = 0;
+            goto invalid;
+        }
+        shortShift64Left(
+            aSig0 | 0x00100000, aSig1, shiftCount, &absZ, &aSigExtra );
+        if ( 0x80000000 < absZ ) goto invalid;
+    }
+    else {
+        aSig1 = ( aSig1 != 0 );
+        if ( aExp < 0x3FE ) {
+            aSigExtra = aExp | aSig0 | aSig1;
+            absZ = 0;
+        }
+        else {
+            aSig0 |= 0x00100000;
+            aSigExtra = ( aSig0<<( shiftCount & 31 ) ) | aSig1;
+            absZ = aSig0>>( - shiftCount );
+        }
+    }
+    roundingMode = float_rounding_mode;
+    if ( roundingMode == float_round_nearest_even ) {
+        if ( (sbits32) aSigExtra < 0 ) {
+            ++absZ;
+            if ( (bits32) ( aSigExtra<<1 ) == 0 ) absZ &= ~1;
+        }
+        z = aSign ? - absZ : absZ;
+    }
+    else {
+        aSigExtra = ( aSigExtra != 0 );
+        if ( aSign ) {
+            z = - (   absZ
+                    + ( ( roundingMode == float_round_down ) & aSigExtra ) );
+        }
+        else {
+            z = absZ + ( ( roundingMode == float_round_up ) & aSigExtra );
+        }
+    }
+    if ( ( aSign ^ ( z < 0 ) ) && z ) {
+ invalid:
+        float_raise( float_flag_invalid );
+        return aSign ? (sbits32) 0x80000000 : 0x7FFFFFFF;
+    }
+    if ( aSigExtra ) float_exception_flags |= float_flag_inexact;
+    return z;
+
+}
+#endif /* !SOFTFLOAT_FOR_GCC */
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the double-precision floating-point value
+`a' to the 32-bit two's complement integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic, except that the conversion is always rounded toward zero.
+If `a' is a NaN, the largest positive integer is returned.  Otherwise, if
+the conversion overflows, the largest integer with the same sign as `a' is
+returned.
+-------------------------------------------------------------------------------
+*/
+int32 float64_to_int32_round_to_zero( float64 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits32 aSig0, aSig1, absZ, aSigExtra;
+    int32 z;
+
+    aSig1 = extractFloat64Frac1( a );
+    aSig0 = extractFloat64Frac0( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    shiftCount = aExp - 0x413;
+    if ( 0 <= shiftCount ) {
+        if ( 0x41E < aExp ) {
+            if ( ( aExp == 0x7FF ) && ( aSig0 | aSig1 ) ) aSign = 0;
+            goto invalid;
+        }
+        shortShift64Left(
+            aSig0 | 0x00100000, aSig1, shiftCount, &absZ, &aSigExtra );
+    }
+    else {
+        if ( aExp < 0x3FF ) {
+            if ( aExp | aSig0 | aSig1 ) {
+                float_exception_flags |= float_flag_inexact;
+            }
+            return 0;
+        }
+        aSig0 |= 0x00100000;
+        aSigExtra = ( aSig0<<( shiftCount & 31 ) ) | aSig1;
+        absZ = aSig0>>( - shiftCount );
+    }
+    z = aSign ? - absZ : absZ;
+    if ( ( aSign ^ ( z < 0 ) ) && z ) {
+ invalid:
+        float_raise( float_flag_invalid );
+        return aSign ? (sbits32) 0x80000000 : 0x7FFFFFFF;
+    }
+    if ( aSigExtra ) float_exception_flags |= float_flag_inexact;
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the double-precision floating-point value
+`a' to the single-precision floating-point format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float64_to_float32( float64 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits32 aSig0, aSig1, zSig;
+    bits32 allZero;
+
+    aSig1 = extractFloat64Frac1( a );
+    aSig0 = extractFloat64Frac0( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    if ( aExp == 0x7FF ) {
+        if ( aSig0 | aSig1 ) {
+            return commonNaNToFloat32( float64ToCommonNaN( a ) );
+        }
+        return packFloat32( aSign, 0xFF, 0 );
+    }
+    shift64RightJamming( aSig0, aSig1, 22, &allZero, &zSig );
+    if ( aExp ) zSig |= 0x40000000;
+    return roundAndPackFloat32( aSign, aExp - 0x381, zSig );
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC
+/*
+-------------------------------------------------------------------------------
+Rounds the double-precision floating-point value `a' to an integer,
+and returns the result as a double-precision floating-point value.  The
+operation is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_round_to_int( float64 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits32 lastBitMask, roundBitsMask;
+    int8 roundingMode;
+    float64 z;
+
+    aExp = extractFloat64Exp( a );
+    if ( 0x413 <= aExp ) {
+        if ( 0x433 <= aExp ) {
+            if (    ( aExp == 0x7FF )
+                 && ( extractFloat64Frac0( a ) | extractFloat64Frac1( a ) ) ) {
+                return propagateFloat64NaN( a, a );
+            }
+            return a;
+        }
+        lastBitMask = 1;
+        lastBitMask = ( lastBitMask<<( 0x432 - aExp ) )<<1;
+        roundBitsMask = lastBitMask - 1;
+        z = a;
+        roundingMode = float_rounding_mode;
+        if ( roundingMode == float_round_nearest_even ) {
+            if ( lastBitMask ) {
+                add64( z.high, z.low, 0, lastBitMask>>1, &z.high, &z.low );
+                if ( ( z.low & roundBitsMask ) == 0 ) z.low &= ~ lastBitMask;
+            }
+            else {
+                if ( (sbits32) z.low < 0 ) {
+                    ++z.high;
+                    if ( (bits32) ( z.low<<1 ) == 0 ) z.high &= ~1;
+                }
+            }
+        }
+        else if ( roundingMode != float_round_to_zero ) {
+            if (   extractFloat64Sign( z )
+                 ^ ( roundingMode == float_round_up ) ) {
+                add64( z.high, z.low, 0, roundBitsMask, &z.high, &z.low );
+            }
+        }
+        z.low &= ~ roundBitsMask;
+    }
+    else {
+        if ( aExp <= 0x3FE ) {
+            if ( ( ( (bits32) ( a.high<<1 ) ) | a.low ) == 0 ) return a;
+            float_exception_flags |= float_flag_inexact;
+            aSign = extractFloat64Sign( a );
+            switch ( float_rounding_mode ) {
+             case float_round_nearest_even:
+                if (    ( aExp == 0x3FE )
+                     && ( extractFloat64Frac0( a ) | extractFloat64Frac1( a ) )
+                   ) {
+                    return packFloat64( aSign, 0x3FF, 0, 0 );
+                }
+                break;
+             case float_round_down:
+                return
+                      aSign ? packFloat64( 1, 0x3FF, 0, 0 )
+                    : packFloat64( 0, 0, 0, 0 );
+             case float_round_up:
+                return
+                      aSign ? packFloat64( 1, 0, 0, 0 )
+                    : packFloat64( 0, 0x3FF, 0, 0 );
+            }
+            return packFloat64( aSign, 0, 0, 0 );
+        }
+        lastBitMask = 1;
+        lastBitMask <<= 0x413 - aExp;
+        roundBitsMask = lastBitMask - 1;
+        z.low = 0;
+        z.high = a.high;
+        roundingMode = float_rounding_mode;
+        if ( roundingMode == float_round_nearest_even ) {
+            z.high += lastBitMask>>1;
+            if ( ( ( z.high & roundBitsMask ) | a.low ) == 0 ) {
+                z.high &= ~ lastBitMask;
+            }
+        }
+        else if ( roundingMode != float_round_to_zero ) {
+            if (   extractFloat64Sign( z )
+                 ^ ( roundingMode == float_round_up ) ) {
+                z.high |= ( a.low != 0 );
+                z.high += roundBitsMask;
+            }
+        }
+        z.high &= ~ roundBitsMask;
+    }
+    if ( ( z.low != a.low ) || ( z.high != a.high ) ) {
+        float_exception_flags |= float_flag_inexact;
+    }
+    return z;
+
+}
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of adding the absolute values of the double-precision
+floating-point values `a' and `b'.  If `zSign' is 1, the sum is negated
+before being returned.  `zSign' is ignored if the result is a NaN.
+The addition is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float64 addFloat64Sigs( float64 a, float64 b, flag zSign )
+{
+    int16 aExp, bExp, zExp;
+    bits32 aSig0, aSig1, bSig0, bSig1, zSig0, zSig1, zSig2;
+    int16 expDiff;
+
+    aSig1 = extractFloat64Frac1( a );
+    aSig0 = extractFloat64Frac0( a );
+    aExp = extractFloat64Exp( a );
+    bSig1 = extractFloat64Frac1( b );
+    bSig0 = extractFloat64Frac0( b );
+    bExp = extractFloat64Exp( b );
+    expDiff = aExp - bExp;
+    if ( 0 < expDiff ) {
+        if ( aExp == 0x7FF ) {
+            if ( aSig0 | aSig1 ) return propagateFloat64NaN( a, b );
+            return a;
+        }
+        if ( bExp == 0 ) {
+            --expDiff;
+        }
+        else {
+            bSig0 |= 0x00100000;
+        }
+        shift64ExtraRightJamming(
+            bSig0, bSig1, 0, expDiff, &bSig0, &bSig1, &zSig2 );
+        zExp = aExp;
+    }
+    else if ( expDiff < 0 ) {
+        if ( bExp == 0x7FF ) {
+            if ( bSig0 | bSig1 ) return propagateFloat64NaN( a, b );
+            return packFloat64( zSign, 0x7FF, 0, 0 );
+        }
+        if ( aExp == 0 ) {
+            ++expDiff;
+        }
+        else {
+            aSig0 |= 0x00100000;
+        }
+        shift64ExtraRightJamming(
+            aSig0, aSig1, 0, - expDiff, &aSig0, &aSig1, &zSig2 );
+        zExp = bExp;
+    }
+    else {
+        if ( aExp == 0x7FF ) {
+            if ( aSig0 | aSig1 | bSig0 | bSig1 ) {
+                return propagateFloat64NaN( a, b );
+            }
+            return a;
+        }
+        add64( aSig0, aSig1, bSig0, bSig1, &zSig0, &zSig1 );
+        if ( aExp == 0 ) return packFloat64( zSign, 0, zSig0, zSig1 );
+        zSig2 = 0;
+        zSig0 |= 0x00200000;
+        zExp = aExp;
+        goto shiftRight1;
+    }
+    aSig0 |= 0x00100000;
+    add64( aSig0, aSig1, bSig0, bSig1, &zSig0, &zSig1 );
+    --zExp;
+    if ( zSig0 < 0x00200000 ) goto roundAndPack;
+    ++zExp;
+ shiftRight1:
+    shift64ExtraRightJamming( zSig0, zSig1, zSig2, 1, &zSig0, &zSig1, &zSig2 );
+ roundAndPack:
+    return roundAndPackFloat64( zSign, zExp, zSig0, zSig1, zSig2 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of subtracting the absolute values of the double-
+precision floating-point values `a' and `b'.  If `zSign' is 1, the
+difference is negated before being returned.  `zSign' is ignored if the
+result is a NaN.  The subtraction is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float64 subFloat64Sigs( float64 a, float64 b, flag zSign )
+{
+    int16 aExp, bExp, zExp;
+    bits32 aSig0, aSig1, bSig0, bSig1, zSig0, zSig1;
+    int16 expDiff;
+
+    aSig1 = extractFloat64Frac1( a );
+    aSig0 = extractFloat64Frac0( a );
+    aExp = extractFloat64Exp( a );
+    bSig1 = extractFloat64Frac1( b );
+    bSig0 = extractFloat64Frac0( b );
+    bExp = extractFloat64Exp( b );
+    expDiff = aExp - bExp;
+    shortShift64Left( aSig0, aSig1, 10, &aSig0, &aSig1 );
+    shortShift64Left( bSig0, bSig1, 10, &bSig0, &bSig1 );
+    if ( 0 < expDiff ) goto aExpBigger;
+    if ( expDiff < 0 ) goto bExpBigger;
+    if ( aExp == 0x7FF ) {
+        if ( aSig0 | aSig1 | bSig0 | bSig1 ) {
+            return propagateFloat64NaN( a, b );
+        }
+        float_raise( float_flag_invalid );
+        return float64_default_nan;
+    }
+    if ( aExp == 0 ) {
+        aExp = 1;
+        bExp = 1;
+    }
+    if ( bSig0 < aSig0 ) goto aBigger;
+    if ( aSig0 < bSig0 ) goto bBigger;
+    if ( bSig1 < aSig1 ) goto aBigger;
+    if ( aSig1 < bSig1 ) goto bBigger;
+    return packFloat64( float_rounding_mode == float_round_down, 0, 0, 0 );
+ bExpBigger:
+    if ( bExp == 0x7FF ) {
+        if ( bSig0 | bSig1 ) return propagateFloat64NaN( a, b );
+        return packFloat64( zSign ^ 1, 0x7FF, 0, 0 );
+    }
+    if ( aExp == 0 ) {
+        ++expDiff;
+    }
+    else {
+        aSig0 |= 0x40000000;
+    }
+    shift64RightJamming( aSig0, aSig1, - expDiff, &aSig0, &aSig1 );
+    bSig0 |= 0x40000000;
+ bBigger:
+    sub64( bSig0, bSig1, aSig0, aSig1, &zSig0, &zSig1 );
+    zExp = bExp;
+    zSign ^= 1;
+    goto normalizeRoundAndPack;
+ aExpBigger:
+    if ( aExp == 0x7FF ) {
+        if ( aSig0 | aSig1 ) return propagateFloat64NaN( a, b );
+        return a;
+    }
+    if ( bExp == 0 ) {
+        --expDiff;
+    }
+    else {
+        bSig0 |= 0x40000000;
+    }
+    shift64RightJamming( bSig0, bSig1, expDiff, &bSig0, &bSig1 );
+    aSig0 |= 0x40000000;
+ aBigger:
+    sub64( aSig0, aSig1, bSig0, bSig1, &zSig0, &zSig1 );
+    zExp = aExp;
+ normalizeRoundAndPack:
+    --zExp;
+    return normalizeRoundAndPackFloat64( zSign, zExp - 10, zSig0, zSig1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of adding the double-precision floating-point values `a'
+and `b'.  The operation is performed according to the IEC/IEEE Standard for
+Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_add( float64 a, float64 b )
+{
+    flag aSign, bSign;
+
+    aSign = extractFloat64Sign( a );
+    bSign = extractFloat64Sign( b );
+    if ( aSign == bSign ) {
+        return addFloat64Sigs( a, b, aSign );
+    }
+    else {
+        return subFloat64Sigs( a, b, aSign );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of subtracting the double-precision floating-point values
+`a' and `b'.  The operation is performed according to the IEC/IEEE Standard
+for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_sub( float64 a, float64 b )
+{
+    flag aSign, bSign;
+
+    aSign = extractFloat64Sign( a );
+    bSign = extractFloat64Sign( b );
+    if ( aSign == bSign ) {
+        return subFloat64Sigs( a, b, aSign );
+    }
+    else {
+        return addFloat64Sigs( a, b, aSign );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of multiplying the double-precision floating-point values
+`a' and `b'.  The operation is performed according to the IEC/IEEE Standard
+for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_mul( float64 a, float64 b )
+{
+    flag aSign, bSign, zSign;
+    int16 aExp, bExp, zExp;
+    bits32 aSig0, aSig1, bSig0, bSig1, zSig0, zSig1, zSig2, zSig3;
+
+    aSig1 = extractFloat64Frac1( a );
+    aSig0 = extractFloat64Frac0( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    bSig1 = extractFloat64Frac1( b );
+    bSig0 = extractFloat64Frac0( b );
+    bExp = extractFloat64Exp( b );
+    bSign = extractFloat64Sign( b );
+    zSign = aSign ^ bSign;
+    if ( aExp == 0x7FF ) {
+        if (    ( aSig0 | aSig1 )
+             || ( ( bExp == 0x7FF ) && ( bSig0 | bSig1 ) ) ) {
+            return propagateFloat64NaN( a, b );
+        }
+        if ( ( bExp | bSig0 | bSig1 ) == 0 ) goto invalid;
+        return packFloat64( zSign, 0x7FF, 0, 0 );
+    }
+    if ( bExp == 0x7FF ) {
+        if ( bSig0 | bSig1 ) return propagateFloat64NaN( a, b );
+        if ( ( aExp | aSig0 | aSig1 ) == 0 ) {
+ invalid:
+            float_raise( float_flag_invalid );
+            return float64_default_nan;
+        }
+        return packFloat64( zSign, 0x7FF, 0, 0 );
+    }
+    if ( aExp == 0 ) {
+        if ( ( aSig0 | aSig1 ) == 0 ) return packFloat64( zSign, 0, 0, 0 );
+        normalizeFloat64Subnormal( aSig0, aSig1, &aExp, &aSig0, &aSig1 );
+    }
+    if ( bExp == 0 ) {
+        if ( ( bSig0 | bSig1 ) == 0 ) return packFloat64( zSign, 0, 0, 0 );
+        normalizeFloat64Subnormal( bSig0, bSig1, &bExp, &bSig0, &bSig1 );
+    }
+    zExp = aExp + bExp - 0x400;
+    aSig0 |= 0x00100000;
+    shortShift64Left( bSig0, bSig1, 12, &bSig0, &bSig1 );
+    mul64To128( aSig0, aSig1, bSig0, bSig1, &zSig0, &zSig1, &zSig2, &zSig3 );
+    add64( zSig0, zSig1, aSig0, aSig1, &zSig0, &zSig1 );
+    zSig2 |= ( zSig3 != 0 );
+    if ( 0x00200000 <= zSig0 ) {
+        shift64ExtraRightJamming(
+            zSig0, zSig1, zSig2, 1, &zSig0, &zSig1, &zSig2 );
+        ++zExp;
+    }
+    return roundAndPackFloat64( zSign, zExp, zSig0, zSig1, zSig2 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of dividing the double-precision floating-point value `a'
+by the corresponding value `b'.  The operation is performed according to the
+IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_div( float64 a, float64 b )
+{
+    flag aSign, bSign, zSign;
+    int16 aExp, bExp, zExp;
+    bits32 aSig0, aSig1, bSig0, bSig1, zSig0, zSig1, zSig2;
+    bits32 rem0, rem1, rem2, rem3, term0, term1, term2, term3;
+
+    aSig1 = extractFloat64Frac1( a );
+    aSig0 = extractFloat64Frac0( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    bSig1 = extractFloat64Frac1( b );
+    bSig0 = extractFloat64Frac0( b );
+    bExp = extractFloat64Exp( b );
+    bSign = extractFloat64Sign( b );
+    zSign = aSign ^ bSign;
+    if ( aExp == 0x7FF ) {
+        if ( aSig0 | aSig1 ) return propagateFloat64NaN( a, b );
+        if ( bExp == 0x7FF ) {
+            if ( bSig0 | bSig1 ) return propagateFloat64NaN( a, b );
+            goto invalid;
+        }
+        return packFloat64( zSign, 0x7FF, 0, 0 );
+    }
+    if ( bExp == 0x7FF ) {
+        if ( bSig0 | bSig1 ) return propagateFloat64NaN( a, b );
+        return packFloat64( zSign, 0, 0, 0 );
+    }
+    if ( bExp == 0 ) {
+        if ( ( bSig0 | bSig1 ) == 0 ) {
+            if ( ( aExp | aSig0 | aSig1 ) == 0 ) {
+ invalid:
+                float_raise( float_flag_invalid );
+                return float64_default_nan;
+            }
+            float_raise( float_flag_divbyzero );
+            return packFloat64( zSign, 0x7FF, 0, 0 );
+        }
+        normalizeFloat64Subnormal( bSig0, bSig1, &bExp, &bSig0, &bSig1 );
+    }
+    if ( aExp == 0 ) {
+        if ( ( aSig0 | aSig1 ) == 0 ) return packFloat64( zSign, 0, 0, 0 );
+        normalizeFloat64Subnormal( aSig0, aSig1, &aExp, &aSig0, &aSig1 );
+    }
+    zExp = aExp - bExp + 0x3FD;
+    shortShift64Left( aSig0 | 0x00100000, aSig1, 11, &aSig0, &aSig1 );
+    shortShift64Left( bSig0 | 0x00100000, bSig1, 11, &bSig0, &bSig1 );
+    if ( le64( bSig0, bSig1, aSig0, aSig1 ) ) {
+        shift64Right( aSig0, aSig1, 1, &aSig0, &aSig1 );
+        ++zExp;
+    }
+    zSig0 = estimateDiv64To32( aSig0, aSig1, bSig0 );
+    mul64By32To96( bSig0, bSig1, zSig0, &term0, &term1, &term2 );
+    sub96( aSig0, aSig1, 0, term0, term1, term2, &rem0, &rem1, &rem2 );
+    while ( (sbits32) rem0 < 0 ) {
+        --zSig0;
+        add96( rem0, rem1, rem2, 0, bSig0, bSig1, &rem0, &rem1, &rem2 );
+    }
+    zSig1 = estimateDiv64To32( rem1, rem2, bSig0 );
+    if ( ( zSig1 & 0x3FF ) <= 4 ) {
+        mul64By32To96( bSig0, bSig1, zSig1, &term1, &term2, &term3 );
+        sub96( rem1, rem2, 0, term1, term2, term3, &rem1, &rem2, &rem3 );
+        while ( (sbits32) rem1 < 0 ) {
+            --zSig1;
+            add96( rem1, rem2, rem3, 0, bSig0, bSig1, &rem1, &rem2, &rem3 );
+        }
+        zSig1 |= ( ( rem1 | rem2 | rem3 ) != 0 );
+    }
+    shift64ExtraRightJamming( zSig0, zSig1, 0, 11, &zSig0, &zSig1, &zSig2 );
+    return roundAndPackFloat64( zSign, zExp, zSig0, zSig1, zSig2 );
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC
+/*
+-------------------------------------------------------------------------------
+Returns the remainder of the double-precision floating-point value `a'
+with respect to the corresponding value `b'.  The operation is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_rem( float64 a, float64 b )
+{
+    flag aSign, bSign, zSign;
+    int16 aExp, bExp, expDiff;
+    bits32 aSig0, aSig1, bSig0, bSig1, q, term0, term1, term2;
+    bits32 allZero, alternateASig0, alternateASig1, sigMean1;
+    sbits32 sigMean0;
+    float64 z;
+
+    aSig1 = extractFloat64Frac1( a );
+    aSig0 = extractFloat64Frac0( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    bSig1 = extractFloat64Frac1( b );
+    bSig0 = extractFloat64Frac0( b );
+    bExp = extractFloat64Exp( b );
+    bSign = extractFloat64Sign( b );
+    if ( aExp == 0x7FF ) {
+        if (    ( aSig0 | aSig1 )
+             || ( ( bExp == 0x7FF ) && ( bSig0 | bSig1 ) ) ) {
+            return propagateFloat64NaN( a, b );
+        }
+        goto invalid;
+    }
+    if ( bExp == 0x7FF ) {
+        if ( bSig0 | bSig1 ) return propagateFloat64NaN( a, b );
+        return a;
+    }
+    if ( bExp == 0 ) {
+        if ( ( bSig0 | bSig1 ) == 0 ) {
+ invalid:
+            float_raise( float_flag_invalid );
+            return float64_default_nan;
+        }
+        normalizeFloat64Subnormal( bSig0, bSig1, &bExp, &bSig0, &bSig1 );
+    }
+    if ( aExp == 0 ) {
+        if ( ( aSig0 | aSig1 ) == 0 ) return a;
+        normalizeFloat64Subnormal( aSig0, aSig1, &aExp, &aSig0, &aSig1 );
+    }
+    expDiff = aExp - bExp;
+    if ( expDiff < -1 ) return a;
+    shortShift64Left(
+        aSig0 | 0x00100000, aSig1, 11 - ( expDiff < 0 ), &aSig0, &aSig1 );
+    shortShift64Left( bSig0 | 0x00100000, bSig1, 11, &bSig0, &bSig1 );
+    q = le64( bSig0, bSig1, aSig0, aSig1 );
+    if ( q ) sub64( aSig0, aSig1, bSig0, bSig1, &aSig0, &aSig1 );
+    expDiff -= 32;
+    while ( 0 < expDiff ) {
+        q = estimateDiv64To32( aSig0, aSig1, bSig0 );
+        q = ( 4 < q ) ? q - 4 : 0;
+        mul64By32To96( bSig0, bSig1, q, &term0, &term1, &term2 );
+        shortShift96Left( term0, term1, term2, 29, &term1, &term2, &allZero );
+        shortShift64Left( aSig0, aSig1, 29, &aSig0, &allZero );
+        sub64( aSig0, 0, term1, term2, &aSig0, &aSig1 );
+        expDiff -= 29;
+    }
+    if ( -32 < expDiff ) {
+        q = estimateDiv64To32( aSig0, aSig1, bSig0 );
+        q = ( 4 < q ) ? q - 4 : 0;
+        q >>= - expDiff;
+        shift64Right( bSig0, bSig1, 8, &bSig0, &bSig1 );
+        expDiff += 24;
+        if ( expDiff < 0 ) {
+            shift64Right( aSig0, aSig1, - expDiff, &aSig0, &aSig1 );
+        }
+        else {
+            shortShift64Left( aSig0, aSig1, expDiff, &aSig0, &aSig1 );
+        }
+        mul64By32To96( bSig0, bSig1, q, &term0, &term1, &term2 );
+        sub64( aSig0, aSig1, term1, term2, &aSig0, &aSig1 );
+    }
+    else {
+        shift64Right( aSig0, aSig1, 8, &aSig0, &aSig1 );
+        shift64Right( bSig0, bSig1, 8, &bSig0, &bSig1 );
+    }
+    do {
+        alternateASig0 = aSig0;
+        alternateASig1 = aSig1;
+        ++q;
+        sub64( aSig0, aSig1, bSig0, bSig1, &aSig0, &aSig1 );
+    } while ( 0 <= (sbits32) aSig0 );
+    add64(
+        aSig0, aSig1, alternateASig0, alternateASig1, &sigMean0, &sigMean1 );
+    if (    ( sigMean0 < 0 )
+         || ( ( ( sigMean0 | sigMean1 ) == 0 ) && ( q & 1 ) ) ) {
+        aSig0 = alternateASig0;
+        aSig1 = alternateASig1;
+    }
+    zSign = ( (sbits32) aSig0 < 0 );
+    if ( zSign ) sub64( 0, 0, aSig0, aSig1, &aSig0, &aSig1 );
+    return
+        normalizeRoundAndPackFloat64( aSign ^ zSign, bExp - 4, aSig0, aSig1 );
+
+}
+#endif
+
+#ifndef SOFTFLOAT_FOR_GCC
+/*
+-------------------------------------------------------------------------------
+Returns the square root of the double-precision floating-point value `a'.
+The operation is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_sqrt( float64 a )
+{
+    flag aSign;
+    int16 aExp, zExp;
+    bits32 aSig0, aSig1, zSig0, zSig1, zSig2, doubleZSig0;
+    bits32 rem0, rem1, rem2, rem3, term0, term1, term2, term3;
+    float64 z;
+
+    aSig1 = extractFloat64Frac1( a );
+    aSig0 = extractFloat64Frac0( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    if ( aExp == 0x7FF ) {
+        if ( aSig0 | aSig1 ) return propagateFloat64NaN( a, a );
+        if ( ! aSign ) return a;
+        goto invalid;
+    }
+    if ( aSign ) {
+        if ( ( aExp | aSig0 | aSig1 ) == 0 ) return a;
+ invalid:
+        float_raise( float_flag_invalid );
+        return float64_default_nan;
+    }
+    if ( aExp == 0 ) {
+        if ( ( aSig0 | aSig1 ) == 0 ) return packFloat64( 0, 0, 0, 0 );
+        normalizeFloat64Subnormal( aSig0, aSig1, &aExp, &aSig0, &aSig1 );
+    }
+    zExp = ( ( aExp - 0x3FF )>>1 ) + 0x3FE;
+    aSig0 |= 0x00100000;
+    shortShift64Left( aSig0, aSig1, 11, &term0, &term1 );
+    zSig0 = ( estimateSqrt32( aExp, term0 )>>1 ) + 1;
+    if ( zSig0 == 0 ) zSig0 = 0x7FFFFFFF;
+    doubleZSig0 = zSig0 + zSig0;
+    shortShift64Left( aSig0, aSig1, 9 - ( aExp & 1 ), &aSig0, &aSig1 );
+    mul32To64( zSig0, zSig0, &term0, &term1 );
+    sub64( aSig0, aSig1, term0, term1, &rem0, &rem1 );
+    while ( (sbits32) rem0 < 0 ) {
+        --zSig0;
+        doubleZSig0 -= 2;
+        add64( rem0, rem1, 0, doubleZSig0 | 1, &rem0, &rem1 );
+    }
+    zSig1 = estimateDiv64To32( rem1, 0, doubleZSig0 );
+    if ( ( zSig1 & 0x1FF ) <= 5 ) {
+        if ( zSig1 == 0 ) zSig1 = 1;
+        mul32To64( doubleZSig0, zSig1, &term1, &term2 );
+        sub64( rem1, 0, term1, term2, &rem1, &rem2 );
+        mul32To64( zSig1, zSig1, &term2, &term3 );
+        sub96( rem1, rem2, 0, 0, term2, term3, &rem1, &rem2, &rem3 );
+        while ( (sbits32) rem1 < 0 ) {
+            --zSig1;
+            shortShift64Left( 0, zSig1, 1, &term2, &term3 );
+            term3 |= 1;
+            term2 |= doubleZSig0;
+            add96( rem1, rem2, rem3, 0, term2, term3, &rem1, &rem2, &rem3 );
+        }
+        zSig1 |= ( ( rem1 | rem2 | rem3 ) != 0 );
+    }
+    shift64ExtraRightJamming( zSig0, zSig1, 0, 10, &zSig0, &zSig1, &zSig2 );
+    return roundAndPackFloat64( 0, zExp, zSig0, zSig1, zSig2 );
+
+}
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is equal to
+the corresponding value `b', and 0 otherwise.  The comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float64_eq( float64 a, float64 b )
+{
+
+    if (    (    ( extractFloat64Exp( a ) == 0x7FF )
+              && ( extractFloat64Frac0( a ) | extractFloat64Frac1( a ) ) )
+         || (    ( extractFloat64Exp( b ) == 0x7FF )
+              && ( extractFloat64Frac0( b ) | extractFloat64Frac1( b ) ) )
+       ) {
+        if ( float64_is_signaling_nan( a ) || float64_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    return ( a == b ) ||
+       ( (bits64) ( ( FLOAT64_DEMANGLE(a) | FLOAT64_DEMANGLE(b) )<<1 ) == 0 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is less than
+or equal to the corresponding value `b', and 0 otherwise.  The comparison
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float64_le( float64 a, float64 b )
+{
+    flag aSign, bSign;
+
+    if (    (    ( extractFloat64Exp( a ) == 0x7FF )
+              && ( extractFloat64Frac0( a ) | extractFloat64Frac1( a ) ) )
+         || (    ( extractFloat64Exp( b ) == 0x7FF )
+              && ( extractFloat64Frac0( b ) | extractFloat64Frac1( b ) ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    aSign = extractFloat64Sign( a );
+    bSign = extractFloat64Sign( b );
+    if ( aSign != bSign )
+       return aSign ||
+           ( (bits64) ( ( FLOAT64_DEMANGLE(a) | FLOAT64_DEMANGLE(b) )<<1 ) ==
+             0 );
+    return ( a == b ) ||
+       ( aSign ^ ( FLOAT64_DEMANGLE(a) < FLOAT64_DEMANGLE(b) ) );
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is less than
+the corresponding value `b', and 0 otherwise.  The comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float64_lt( float64 a, float64 b )
+{
+    flag aSign, bSign;
+
+    if (    (    ( extractFloat64Exp( a ) == 0x7FF )
+              && ( extractFloat64Frac0( a ) | extractFloat64Frac1( a ) ) )
+         || (    ( extractFloat64Exp( b ) == 0x7FF )
+              && ( extractFloat64Frac0( b ) | extractFloat64Frac1( b ) ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    aSign = extractFloat64Sign( a );
+    bSign = extractFloat64Sign( b );
+    if ( aSign != bSign )
+       return aSign &&
+           ( (bits64) ( ( FLOAT64_DEMANGLE(a) | FLOAT64_DEMANGLE(b) )<<1 ) !=
+             0 );
+    return ( a != b ) &&
+       ( aSign ^ ( FLOAT64_DEMANGLE(a) < FLOAT64_DEMANGLE(b) ) );
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is equal to
+the corresponding value `b', and 0 otherwise.  The invalid exception is
+raised if either operand is a NaN.  Otherwise, the comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float64_eq_signaling( float64 a, float64 b )
+{
+
+    if (    (    ( extractFloat64Exp( a ) == 0x7FF )
+              && ( extractFloat64Frac0( a ) | extractFloat64Frac1( a ) ) )
+         || (    ( extractFloat64Exp( b ) == 0x7FF )
+              && ( extractFloat64Frac0( b ) | extractFloat64Frac1( b ) ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    return ( a == b ) || ( (bits64) ( ( a | b )<<1 ) == 0 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is less than or
+equal to the corresponding value `b', and 0 otherwise.  Quiet NaNs do not
+cause an exception.  Otherwise, the comparison is performed according to the
+IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float64_le_quiet( float64 a, float64 b )
+{
+    flag aSign, bSign;
+
+    if (    (    ( extractFloat64Exp( a ) == 0x7FF )
+              && ( extractFloat64Frac0( a ) | extractFloat64Frac1( a ) ) )
+         || (    ( extractFloat64Exp( b ) == 0x7FF )
+              && ( extractFloat64Frac0( b ) | extractFloat64Frac1( b ) ) )
+       ) {
+        if ( float64_is_signaling_nan( a ) || float64_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    aSign = extractFloat64Sign( a );
+    bSign = extractFloat64Sign( b );
+    if ( aSign != bSign ) return aSign || ( (bits64) ( ( a | b )<<1 ) == 0 );
+    return ( a == b ) || ( aSign ^ ( a < b ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is less than
+the corresponding value `b', and 0 otherwise.  Quiet NaNs do not cause an
+exception.  Otherwise, the comparison is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float64_lt_quiet( float64 a, float64 b )
+{
+    flag aSign, bSign;
+
+    if (    (    ( extractFloat64Exp( a ) == 0x7FF )
+              && ( extractFloat64Frac0( a ) | extractFloat64Frac1( a ) ) )
+         || (    ( extractFloat64Exp( b ) == 0x7FF )
+              && ( extractFloat64Frac0( b ) | extractFloat64Frac1( b ) ) )
+       ) {
+        if ( float64_is_signaling_nan( a ) || float64_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    aSign = extractFloat64Sign( a );
+    bSign = extractFloat64Sign( b );
+    if ( aSign != bSign ) return aSign && ( (bits64) ( ( a | b )<<1 ) != 0 );
+    return ( a != b ) && ( aSign ^ ( a < b ) );
+
+}
+
+#endif
diff --git a/lib/nbsd_libc/softfloat/bits64/softfloat-macros b/lib/nbsd_libc/softfloat/bits64/softfloat-macros
new file mode 100644 (file)
index 0000000..731941b
--- /dev/null
@@ -0,0 +1,745 @@
+/* $NetBSD: softfloat-macros,v 1.2 2009/02/16 10:23:35 tron Exp $ */
+
+/*
+===============================================================================
+
+This C source fragment is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+/*
+-------------------------------------------------------------------------------
+Shifts `a' right by the number of bits given in `count'.  If any nonzero
+bits are shifted off, they are ``jammed'' into the least significant bit of
+the result by setting the least significant bit to 1.  The value of `count'
+can be arbitrarily large; in particular, if `count' is greater than 32, the
+result will be either 0 or 1, depending on whether `a' is zero or nonzero.
+The result is stored in the location pointed to by `zPtr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void shift32RightJamming( bits32 a, int16 count, bits32 *zPtr )
+{
+    bits32 z;
+
+    if ( count == 0 ) {
+        z = a;
+    }
+    else if ( count < 32 ) {
+        z = ( a>>count ) | ( ( a<<( ( - count ) & 31 ) ) != 0 );
+    }
+    else {
+        z = ( a != 0 );
+    }
+    *zPtr = z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Shifts `a' right by the number of bits given in `count'.  If any nonzero
+bits are shifted off, they are ``jammed'' into the least significant bit of
+the result by setting the least significant bit to 1.  The value of `count'
+can be arbitrarily large; in particular, if `count' is greater than 64, the
+result will be either 0 or 1, depending on whether `a' is zero or nonzero.
+The result is stored in the location pointed to by `zPtr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void shift64RightJamming( bits64 a, int16 count, bits64 *zPtr )
+{
+    bits64 z;
+
+    if ( count == 0 ) {
+        z = a;
+    }
+    else if ( count < 64 ) {
+        z = ( a>>count ) | ( ( a<<( ( - count ) & 63 ) ) != 0 );
+    }
+    else {
+        z = ( a != 0 );
+    }
+    *zPtr = z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Shifts the 128-bit value formed by concatenating `a0' and `a1' right by 64
+_plus_ the number of bits given in `count'.  The shifted result is at most
+64 nonzero bits; this is stored at the location pointed to by `z0Ptr'.  The
+bits shifted off form a second 64-bit result as follows:  The _last_ bit
+shifted off is the most-significant bit of the extra result, and the other
+63 bits of the extra result are all zero if and only if _all_but_the_last_
+bits shifted off were all zero.  This extra result is stored in the location
+pointed to by `z1Ptr'.  The value of `count' can be arbitrarily large.
+    (This routine makes more sense if `a0' and `a1' are considered to form a
+fixed-point value with binary point between `a0' and `a1'.  This fixed-point
+value is shifted right by the number of bits given in `count', and the
+integer part of the result is returned at the location pointed to by
+`z0Ptr'.  The fractional part of the result may be slightly corrupted as
+described above, and is returned at the location pointed to by `z1Ptr'.)
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ shift64ExtraRightJamming(
+     bits64 a0, bits64 a1, int16 count, bits64 *z0Ptr, bits64 *z1Ptr )
+{
+    bits64 z0, z1;
+    int8 negCount = ( - count ) & 63;
+
+    if ( count == 0 ) {
+        z1 = a1;
+        z0 = a0;
+    }
+    else if ( count < 64 ) {
+        z1 = ( a0<<negCount ) | ( a1 != 0 );
+        z0 = a0>>count;
+    }
+    else {
+        if ( count == 64 ) {
+            z1 = a0 | ( a1 != 0 );
+        }
+        else {
+            z1 = ( ( a0 | a1 ) != 0 );
+        }
+        z0 = 0;
+    }
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Shifts the 128-bit value formed by concatenating `a0' and `a1' right by the
+number of bits given in `count'.  Any bits shifted off are lost.  The value
+of `count' can be arbitrarily large; in particular, if `count' is greater
+than 128, the result will be 0.  The result is broken into two 64-bit pieces
+which are stored at the locations pointed to by `z0Ptr' and `z1Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ shift128Right(
+     bits64 a0, bits64 a1, int16 count, bits64 *z0Ptr, bits64 *z1Ptr )
+{
+    bits64 z0, z1;
+    int8 negCount = ( - count ) & 63;
+
+    if ( count == 0 ) {
+        z1 = a1;
+        z0 = a0;
+    }
+    else if ( count < 64 ) {
+        z1 = ( a0<<negCount ) | ( a1>>count );
+        z0 = a0>>count;
+    }
+    else {
+        z1 = ( count < 64 ) ? ( a0>>( count & 63 ) ) : 0;
+        z0 = 0;
+    }
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Shifts the 128-bit value formed by concatenating `a0' and `a1' right by the
+number of bits given in `count'.  If any nonzero bits are shifted off, they
+are ``jammed'' into the least significant bit of the result by setting the
+least significant bit to 1.  The value of `count' can be arbitrarily large;
+in particular, if `count' is greater than 128, the result will be either
+0 or 1, depending on whether the concatenation of `a0' and `a1' is zero or
+nonzero.  The result is broken into two 64-bit pieces which are stored at
+the locations pointed to by `z0Ptr' and `z1Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ shift128RightJamming(
+     bits64 a0, bits64 a1, int16 count, bits64 *z0Ptr, bits64 *z1Ptr )
+{
+    bits64 z0, z1;
+    int8 negCount = ( - count ) & 63;
+
+    if ( count == 0 ) {
+        z1 = a1;
+        z0 = a0;
+    }
+    else if ( count < 64 ) {
+        z1 = ( a0<<negCount ) | ( a1>>count ) | ( ( a1<<negCount ) != 0 );
+        z0 = a0>>count;
+    }
+    else {
+        if ( count == 64 ) {
+            z1 = a0 | ( a1 != 0 );
+        }
+        else if ( count < 128 ) {
+            z1 = ( a0>>( count & 63 ) ) | ( ( ( a0<<negCount ) | a1 ) != 0 );
+        }
+        else {
+            z1 = ( ( a0 | a1 ) != 0 );
+        }
+        z0 = 0;
+    }
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Shifts the 192-bit value formed by concatenating `a0', `a1', and `a2' right
+by 64 _plus_ the number of bits given in `count'.  The shifted result is
+at most 128 nonzero bits; these are broken into two 64-bit pieces which are
+stored at the locations pointed to by `z0Ptr' and `z1Ptr'.  The bits shifted
+off form a third 64-bit result as follows:  The _last_ bit shifted off is
+the most-significant bit of the extra result, and the other 63 bits of the
+extra result are all zero if and only if _all_but_the_last_ bits shifted off
+were all zero.  This extra result is stored in the location pointed to by
+`z2Ptr'.  The value of `count' can be arbitrarily large.
+    (This routine makes more sense if `a0', `a1', and `a2' are considered
+to form a fixed-point value with binary point between `a1' and `a2'.  This
+fixed-point value is shifted right by the number of bits given in `count',
+and the integer part of the result is returned at the locations pointed to
+by `z0Ptr' and `z1Ptr'.  The fractional part of the result may be slightly
+corrupted as described above, and is returned at the location pointed to by
+`z2Ptr'.)
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ shift128ExtraRightJamming(
+     bits64 a0,
+     bits64 a1,
+     bits64 a2,
+     int16 count,
+     bits64 *z0Ptr,
+     bits64 *z1Ptr,
+     bits64 *z2Ptr
+ )
+{
+    bits64 z0, z1, z2;
+    int8 negCount = ( - count ) & 63;
+
+    if ( count == 0 ) {
+        z2 = a2;
+        z1 = a1;
+        z0 = a0;
+    }
+    else {
+        if ( count < 64 ) {
+            z2 = a1<<negCount;
+            z1 = ( a0<<negCount ) | ( a1>>count );
+            z0 = a0>>count;
+        }
+        else {
+            if ( count == 64 ) {
+                z2 = a1;
+                z1 = a0;
+            }
+            else {
+                a2 |= a1;
+                if ( count < 128 ) {
+                    z2 = a0<<negCount;
+                    z1 = a0>>( count & 63 );
+                }
+                else {
+                    z2 = ( count == 128 ) ? a0 : ( a0 != 0 );
+                    z1 = 0;
+                }
+            }
+            z0 = 0;
+        }
+        z2 |= ( a2 != 0 );
+    }
+    *z2Ptr = z2;
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Shifts the 128-bit value formed by concatenating `a0' and `a1' left by the
+number of bits given in `count'.  Any bits shifted off are lost.  The value
+of `count' must be less than 64.  The result is broken into two 64-bit
+pieces which are stored at the locations pointed to by `z0Ptr' and `z1Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ shortShift128Left(
+     bits64 a0, bits64 a1, int16 count, bits64 *z0Ptr, bits64 *z1Ptr )
+{
+
+    *z1Ptr = a1<<count;
+    *z0Ptr =
+        ( count == 0 ) ? a0 : ( a0<<count ) | ( a1>>( ( - count ) & 63 ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Shifts the 192-bit value formed by concatenating `a0', `a1', and `a2' left
+by the number of bits given in `count'.  Any bits shifted off are lost.
+The value of `count' must be less than 64.  The result is broken into three
+64-bit pieces which are stored at the locations pointed to by `z0Ptr',
+`z1Ptr', and `z2Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ shortShift192Left(
+     bits64 a0,
+     bits64 a1,
+     bits64 a2,
+     int16 count,
+     bits64 *z0Ptr,
+     bits64 *z1Ptr,
+     bits64 *z2Ptr
+ )
+{
+    bits64 z0, z1, z2;
+    int8 negCount;
+
+    z2 = a2<<count;
+    z1 = a1<<count;
+    z0 = a0<<count;
+    if ( 0 < count ) {
+        negCount = ( ( - count ) & 63 );
+        z1 |= a2>>negCount;
+        z0 |= a1>>negCount;
+    }
+    *z2Ptr = z2;
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Adds the 128-bit value formed by concatenating `a0' and `a1' to the 128-bit
+value formed by concatenating `b0' and `b1'.  Addition is modulo 2^128, so
+any carry out is lost.  The result is broken into two 64-bit pieces which
+are stored at the locations pointed to by `z0Ptr' and `z1Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ add128(
+     bits64 a0, bits64 a1, bits64 b0, bits64 b1, bits64 *z0Ptr, bits64 *z1Ptr )
+{
+    bits64 z1;
+
+    z1 = a1 + b1;
+    *z1Ptr = z1;
+    *z0Ptr = a0 + b0 + ( z1 < a1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Adds the 192-bit value formed by concatenating `a0', `a1', and `a2' to the
+192-bit value formed by concatenating `b0', `b1', and `b2'.  Addition is
+modulo 2^192, so any carry out is lost.  The result is broken into three
+64-bit pieces which are stored at the locations pointed to by `z0Ptr',
+`z1Ptr', and `z2Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ add192(
+     bits64 a0,
+     bits64 a1,
+     bits64 a2,
+     bits64 b0,
+     bits64 b1,
+     bits64 b2,
+     bits64 *z0Ptr,
+     bits64 *z1Ptr,
+     bits64 *z2Ptr
+ )
+{
+    bits64 z0, z1, z2;
+    int8 carry0, carry1;
+
+    z2 = a2 + b2;
+    carry1 = ( z2 < a2 );
+    z1 = a1 + b1;
+    carry0 = ( z1 < a1 );
+    z0 = a0 + b0;
+    z1 += carry1;
+    z0 += ( z1 < (bits64)carry1 );
+    z0 += carry0;
+    *z2Ptr = z2;
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Subtracts the 128-bit value formed by concatenating `b0' and `b1' from the
+128-bit value formed by concatenating `a0' and `a1'.  Subtraction is modulo
+2^128, so any borrow out (carry out) is lost.  The result is broken into two
+64-bit pieces which are stored at the locations pointed to by `z0Ptr' and
+`z1Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ sub128(
+     bits64 a0, bits64 a1, bits64 b0, bits64 b1, bits64 *z0Ptr, bits64 *z1Ptr )
+{
+
+    *z1Ptr = a1 - b1;
+    *z0Ptr = a0 - b0 - ( a1 < b1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Subtracts the 192-bit value formed by concatenating `b0', `b1', and `b2'
+from the 192-bit value formed by concatenating `a0', `a1', and `a2'.
+Subtraction is modulo 2^192, so any borrow out (carry out) is lost.  The
+result is broken into three 64-bit pieces which are stored at the locations
+pointed to by `z0Ptr', `z1Ptr', and `z2Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ sub192(
+     bits64 a0,
+     bits64 a1,
+     bits64 a2,
+     bits64 b0,
+     bits64 b1,
+     bits64 b2,
+     bits64 *z0Ptr,
+     bits64 *z1Ptr,
+     bits64 *z2Ptr
+ )
+{
+    bits64 z0, z1, z2;
+    int8 borrow0, borrow1;
+
+    z2 = a2 - b2;
+    borrow1 = ( a2 < b2 );
+    z1 = a1 - b1;
+    borrow0 = ( a1 < b1 );
+    z0 = a0 - b0;
+    z0 -= ( z1 < (bits64)borrow1 );
+    z1 -= borrow1;
+    z0 -= borrow0;
+    *z2Ptr = z2;
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Multiplies `a' by `b' to obtain a 128-bit product.  The product is broken
+into two 64-bit pieces which are stored at the locations pointed to by
+`z0Ptr' and `z1Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void mul64To128( bits64 a, bits64 b, bits64 *z0Ptr, bits64 *z1Ptr )
+{
+    bits32 aHigh, aLow, bHigh, bLow;
+    bits64 z0, zMiddleA, zMiddleB, z1;
+
+    aLow = a;
+    aHigh = a>>32;
+    bLow = b;
+    bHigh = b>>32;
+    z1 = ( (bits64) aLow ) * bLow;
+    zMiddleA = ( (bits64) aLow ) * bHigh;
+    zMiddleB = ( (bits64) aHigh ) * bLow;
+    z0 = ( (bits64) aHigh ) * bHigh;
+    zMiddleA += zMiddleB;
+    z0 += ( ( (bits64) ( zMiddleA < zMiddleB ) )<<32 ) + ( zMiddleA>>32 );
+    zMiddleA <<= 32;
+    z1 += zMiddleA;
+    z0 += ( z1 < zMiddleA );
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Multiplies the 128-bit value formed by concatenating `a0' and `a1' by
+`b' to obtain a 192-bit product.  The product is broken into three 64-bit
+pieces which are stored at the locations pointed to by `z0Ptr', `z1Ptr', and
+`z2Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ mul128By64To192(
+     bits64 a0,
+     bits64 a1,
+     bits64 b,
+     bits64 *z0Ptr,
+     bits64 *z1Ptr,
+     bits64 *z2Ptr
+ )
+{
+    bits64 z0, z1, z2, more1;
+
+    mul64To128( a1, b, &z1, &z2 );
+    mul64To128( a0, b, &z0, &more1 );
+    add128( z0, more1, 0, z1, &z0, &z1 );
+    *z2Ptr = z2;
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Multiplies the 128-bit value formed by concatenating `a0' and `a1' to the
+128-bit value formed by concatenating `b0' and `b1' to obtain a 256-bit
+product.  The product is broken into four 64-bit pieces which are stored at
+the locations pointed to by `z0Ptr', `z1Ptr', `z2Ptr', and `z3Ptr'.
+-------------------------------------------------------------------------------
+*/
+INLINE void
+ mul128To256(
+     bits64 a0,
+     bits64 a1,
+     bits64 b0,
+     bits64 b1,
+     bits64 *z0Ptr,
+     bits64 *z1Ptr,
+     bits64 *z2Ptr,
+     bits64 *z3Ptr
+ )
+{
+    bits64 z0, z1, z2, z3;
+    bits64 more1, more2;
+
+    mul64To128( a1, b1, &z2, &z3 );
+    mul64To128( a1, b0, &z1, &more2 );
+    add128( z1, more2, 0, z2, &z1, &z2 );
+    mul64To128( a0, b0, &z0, &more1 );
+    add128( z0, more1, 0, z1, &z0, &z1 );
+    mul64To128( a0, b1, &more1, &more2 );
+    add128( more1, more2, 0, z2, &more1, &z2 );
+    add128( z0, z1, 0, more1, &z0, &z1 );
+    *z3Ptr = z3;
+    *z2Ptr = z2;
+    *z1Ptr = z1;
+    *z0Ptr = z0;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns an approximation to the 64-bit integer quotient obtained by dividing
+`b' into the 128-bit value formed by concatenating `a0' and `a1'.  The
+divisor `b' must be at least 2^63.  If q is the exact quotient truncated
+toward zero, the approximation returned lies between q and q + 2 inclusive.
+If the exact quotient q is larger than 64 bits, the maximum positive 64-bit
+unsigned integer is returned.
+-------------------------------------------------------------------------------
+*/
+static bits64 estimateDiv128To64( bits64 a0, bits64 a1, bits64 b )
+{
+    bits64 b0, b1;
+    bits64 rem0, rem1, term0, term1;
+    bits64 z;
+
+    if ( b <= a0 ) return LIT64( 0xFFFFFFFFFFFFFFFF );
+    b0 = b>>32;
+    z = ( b0<<32 <= a0 ) ? LIT64( 0xFFFFFFFF00000000 ) : ( a0 / b0 )<<32;
+    mul64To128( b, z, &term0, &term1 );
+    sub128( a0, a1, term0, term1, &rem0, &rem1 );
+    while ( ( (sbits64) rem0 ) < 0 ) {
+        z -= LIT64( 0x100000000 );
+        b1 = b<<32;
+        add128( rem0, rem1, b0, b1, &rem0, &rem1 );
+    }
+    rem0 = ( rem0<<32 ) | ( rem1>>32 );
+    z |= ( b0<<32 <= rem0 ) ? 0xFFFFFFFF : rem0 / b0;
+    return z;
+
+}
+
+#if !defined(SOFTFLOAT_FOR_GCC) || defined(FLOATX80) || defined(FLOAT128)
+/*
+-------------------------------------------------------------------------------
+Returns an approximation to the square root of the 32-bit significand given
+by `a'.  Considered as an integer, `a' must be at least 2^31.  If bit 0 of
+`aExp' (the least significant bit) is 1, the integer returned approximates
+2^31*sqrt(`a'/2^31), where `a' is considered an integer.  If bit 0 of `aExp'
+is 0, the integer returned approximates 2^31*sqrt(`a'/2^30).  In either
+case, the approximation returned lies strictly within +/-2 of the exact
+value.
+-------------------------------------------------------------------------------
+*/
+static bits32 estimateSqrt32( int16 aExp, bits32 a )
+{
+    static const bits16 sqrtOddAdjustments[] = {
+        0x0004, 0x0022, 0x005D, 0x00B1, 0x011D, 0x019F, 0x0236, 0x02E0,
+        0x039C, 0x0468, 0x0545, 0x0631, 0x072B, 0x0832, 0x0946, 0x0A67
+    };
+    static const bits16 sqrtEvenAdjustments[] = {
+        0x0A2D, 0x08AF, 0x075A, 0x0629, 0x051A, 0x0429, 0x0356, 0x029E,
+        0x0200, 0x0179, 0x0109, 0x00AF, 0x0068, 0x0034, 0x0012, 0x0002
+    };
+    int8 idx;
+    bits32 z;
+
+    idx = ( a>>27 ) & 15;
+    if ( aExp & 1 ) {
+        z = 0x4000 + ( a>>17 ) - sqrtOddAdjustments[ idx ];
+        z = ( ( a / z )<<14 ) + ( z<<15 );
+        a >>= 1;
+    }
+    else {
+        z = 0x8000 + ( a>>17 ) - sqrtEvenAdjustments[ idx ];
+        z = a / z + z;
+        z = ( 0x20000 <= z ) ? 0xFFFF8000 : ( z<<15 );
+        if ( z <= a ) return (bits32) ( ( (sbits32) a )>>1 );
+    }
+    return ( (bits32) ( ( ( (bits64) a )<<31 ) / z ) ) + ( z>>1 );
+
+}
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Returns the number of leading 0 bits before the most-significant 1 bit of
+`a'.  If `a' is zero, 32 is returned.
+-------------------------------------------------------------------------------
+*/
+static int8 countLeadingZeros32( bits32 a )
+{
+    static const int8 countLeadingZerosHigh[] = {
+        8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
+        3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+    };
+    int8 shiftCount;
+
+    shiftCount = 0;
+    if ( a < 0x10000 ) {
+        shiftCount += 16;
+        a <<= 16;
+    }
+    if ( a < 0x1000000 ) {
+        shiftCount += 8;
+        a <<= 8;
+    }
+    shiftCount += countLeadingZerosHigh[ a>>24 ];
+    return shiftCount;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the number of leading 0 bits before the most-significant 1 bit of
+`a'.  If `a' is zero, 64 is returned.
+-------------------------------------------------------------------------------
+*/
+static int8 countLeadingZeros64( bits64 a )
+{
+    int8 shiftCount;
+
+    shiftCount = 0;
+    if ( a < ( (bits64) 1 )<<32 ) {
+        shiftCount += 32;
+    }
+    else {
+        a >>= 32;
+    }
+    shiftCount += countLeadingZeros32( a );
+    return shiftCount;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the 128-bit value formed by concatenating `a0' and `a1'
+is equal to the 128-bit value formed by concatenating `b0' and `b1'.
+Otherwise, returns 0.
+-------------------------------------------------------------------------------
+*/
+INLINE flag eq128( bits64 a0, bits64 a1, bits64 b0, bits64 b1 )
+{
+
+    return ( a0 == b0 ) && ( a1 == b1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the 128-bit value formed by concatenating `a0' and `a1' is less
+than or equal to the 128-bit value formed by concatenating `b0' and `b1'.
+Otherwise, returns 0.
+-------------------------------------------------------------------------------
+*/
+INLINE flag le128( bits64 a0, bits64 a1, bits64 b0, bits64 b1 )
+{
+
+    return ( a0 < b0 ) || ( ( a0 == b0 ) && ( a1 <= b1 ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the 128-bit value formed by concatenating `a0' and `a1' is less
+than the 128-bit value formed by concatenating `b0' and `b1'.  Otherwise,
+returns 0.
+-------------------------------------------------------------------------------
+*/
+INLINE flag lt128( bits64 a0, bits64 a1, bits64 b0, bits64 b1 )
+{
+
+    return ( a0 < b0 ) || ( ( a0 == b0 ) && ( a1 < b1 ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the 128-bit value formed by concatenating `a0' and `a1' is
+not equal to the 128-bit value formed by concatenating `b0' and `b1'.
+Otherwise, returns 0.
+-------------------------------------------------------------------------------
+*/
+INLINE flag ne128( bits64 a0, bits64 a1, bits64 b0, bits64 b1 )
+{
+
+    return ( a0 != b0 ) || ( a1 != b1 );
+
+}
+
diff --git a/lib/nbsd_libc/softfloat/bits64/softfloat.c b/lib/nbsd_libc/softfloat/bits64/softfloat.c
new file mode 100644 (file)
index 0000000..b0d2bdf
--- /dev/null
@@ -0,0 +1,5552 @@
+/* $NetBSD: softfloat.c,v 1.5 2007/11/08 21:31:04 martin Exp $ */
+
+/*
+ * This version hacked for use with gcc -msoft-float by bjh21.
+ * (Mostly a case of #ifdefing out things GCC doesn't need or provides
+ *  itself).
+ */
+
+/*
+ * Things you may want to define:
+ *
+ * SOFTFLOAT_FOR_GCC - build only those functions necessary for GCC (with
+ *   -msoft-float) to work.  Include "softfloat-for-gcc.h" to get them
+ *   properly renamed.
+ */
+
+/*
+===============================================================================
+
+This C source file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: softfloat.c,v 1.5 2007/11/08 21:31:04 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef SOFTFLOAT_FOR_GCC
+#include "softfloat-for-gcc.h"
+#endif
+
+#include "milieu.h"
+#include "softfloat.h"
+
+/*
+ * Conversions between floats as stored in memory and floats as
+ * SoftFloat uses them
+ */
+#ifndef FLOAT64_DEMANGLE
+#define FLOAT64_DEMANGLE(a)    (a)
+#endif
+#ifndef FLOAT64_MANGLE
+#define FLOAT64_MANGLE(a)      (a)
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Floating-point rounding mode, extended double-precision rounding precision,
+and exception flags.
+-------------------------------------------------------------------------------
+*/
+fp_rnd float_rounding_mode = float_round_nearest_even;
+fp_except float_exception_flags = 0;
+#ifdef FLOATX80
+int8 floatx80_rounding_precision = 80;
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Primitive arithmetic functions, including multi-word arithmetic, and
+division and square root approximations.  (Can be specialized to target if
+desired.)
+-------------------------------------------------------------------------------
+*/
+#include "softfloat-macros"
+
+/*
+-------------------------------------------------------------------------------
+Functions and definitions to determine:  (1) whether tininess for underflow
+is detected before or after rounding by default, (2) what (if anything)
+happens when exceptions are raised, (3) how signaling NaNs are distinguished
+from quiet NaNs, (4) the default generated quiet NaNs, and (5) how NaNs
+are propagated from function inputs to output.  These details are target-
+specific.
+-------------------------------------------------------------------------------
+*/
+#include "softfloat-specialize"
+
+#if !defined(SOFTFLOAT_FOR_GCC) || defined(FLOATX80) || defined(FLOAT128)
+/*
+-------------------------------------------------------------------------------
+Takes a 64-bit fixed-point value `absZ' with binary point between bits 6
+and 7, and returns the properly rounded 32-bit integer corresponding to the
+input.  If `zSign' is 1, the input is negated before being converted to an
+integer.  Bit 63 of `absZ' must be zero.  Ordinarily, the fixed-point input
+is simply rounded to an integer, with the inexact exception raised if the
+input cannot be represented exactly as an integer.  However, if the fixed-
+point input is too large, the invalid exception is raised and the largest
+positive or negative integer is returned.
+-------------------------------------------------------------------------------
+*/
+static int32 roundAndPackInt32( flag zSign, bits64 absZ )
+{
+    int8 roundingMode;
+    flag roundNearestEven;
+    int8 roundIncrement, roundBits;
+    int32 z;
+
+    roundingMode = float_rounding_mode;
+    roundNearestEven = ( roundingMode == float_round_nearest_even );
+    roundIncrement = 0x40;
+    if ( ! roundNearestEven ) {
+        if ( roundingMode == float_round_to_zero ) {
+            roundIncrement = 0;
+        }
+        else {
+            roundIncrement = 0x7F;
+            if ( zSign ) {
+                if ( roundingMode == float_round_up ) roundIncrement = 0;
+            }
+            else {
+                if ( roundingMode == float_round_down ) roundIncrement = 0;
+            }
+        }
+    }
+    roundBits = absZ & 0x7F;
+    absZ = ( absZ + roundIncrement )>>7;
+    absZ &= ~ ( ( ( roundBits ^ 0x40 ) == 0 ) & roundNearestEven );
+    z = absZ;
+    if ( zSign ) z = - z;
+    if ( ( absZ>>32 ) || ( z && ( ( z < 0 ) ^ zSign ) ) ) {
+        float_raise( float_flag_invalid );
+        return zSign ? (sbits32) 0x80000000 : 0x7FFFFFFF;
+    }
+    if ( roundBits ) float_exception_flags |= float_flag_inexact;
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes the 128-bit fixed-point value formed by concatenating `absZ0' and
+`absZ1', with binary point between bits 63 and 64 (between the input words),
+and returns the properly rounded 64-bit integer corresponding to the input.
+If `zSign' is 1, the input is negated before being converted to an integer.
+Ordinarily, the fixed-point input is simply rounded to an integer, with
+the inexact exception raised if the input cannot be represented exactly as
+an integer.  However, if the fixed-point input is too large, the invalid
+exception is raised and the largest positive or negative integer is
+returned.
+-------------------------------------------------------------------------------
+*/
+static int64 roundAndPackInt64( flag zSign, bits64 absZ0, bits64 absZ1 )
+{
+    int8 roundingMode;
+    flag roundNearestEven, increment;
+    int64 z;
+
+    roundingMode = float_rounding_mode;
+    roundNearestEven = ( roundingMode == float_round_nearest_even );
+    increment = ( (sbits64) absZ1 < 0 );
+    if ( ! roundNearestEven ) {
+        if ( roundingMode == float_round_to_zero ) {
+            increment = 0;
+        }
+        else {
+            if ( zSign ) {
+                increment = ( roundingMode == float_round_down ) && absZ1;
+            }
+            else {
+                increment = ( roundingMode == float_round_up ) && absZ1;
+            }
+        }
+    }
+    if ( increment ) {
+        ++absZ0;
+        if ( absZ0 == 0 ) goto overflow;
+        absZ0 &= ~ ( ( (bits64) ( absZ1<<1 ) == 0 ) & roundNearestEven );
+    }
+    z = absZ0;
+    if ( zSign ) z = - z;
+    if ( z && ( ( z < 0 ) ^ zSign ) ) {
+ overflow:
+        float_raise( float_flag_invalid );
+        return
+              zSign ? (sbits64) LIT64( 0x8000000000000000 )
+            : LIT64( 0x7FFFFFFFFFFFFFFF );
+    }
+    if ( absZ1 ) float_exception_flags |= float_flag_inexact;
+    return z;
+
+}
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Returns the fraction bits of the single-precision floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE bits32 extractFloat32Frac( float32 a )
+{
+
+    return a & 0x007FFFFF;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the exponent bits of the single-precision floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE int16 extractFloat32Exp( float32 a )
+{
+
+    return ( a>>23 ) & 0xFF;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the sign bit of the single-precision floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE flag extractFloat32Sign( float32 a )
+{
+
+    return a>>31;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Normalizes the subnormal single-precision floating-point value represented
+by the denormalized significand `aSig'.  The normalized exponent and
+significand are stored at the locations pointed to by `zExpPtr' and
+`zSigPtr', respectively.
+-------------------------------------------------------------------------------
+*/
+static void
+ normalizeFloat32Subnormal( bits32 aSig, int16 *zExpPtr, bits32 *zSigPtr )
+{
+    int8 shiftCount;
+
+    shiftCount = countLeadingZeros32( aSig ) - 8;
+    *zSigPtr = aSig<<shiftCount;
+    *zExpPtr = 1 - shiftCount;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Packs the sign `zSign', exponent `zExp', and significand `zSig' into a
+single-precision floating-point value, returning the result.  After being
+shifted into the proper positions, the three fields are simply added
+together to form the result.  This means that any integer portion of `zSig'
+will be added into the exponent.  Since a properly normalized significand
+will have an integer portion equal to 1, the `zExp' input should be 1 less
+than the desired result exponent whenever `zSig' is a complete, normalized
+significand.
+-------------------------------------------------------------------------------
+*/
+INLINE float32 packFloat32( flag zSign, int16 zExp, bits32 zSig )
+{
+
+    return ( ( (bits32) zSign )<<31 ) + ( ( (bits32) zExp )<<23 ) + zSig;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes an abstract floating-point value having sign `zSign', exponent `zExp',
+and significand `zSig', and returns the proper single-precision floating-
+point value corresponding to the abstract input.  Ordinarily, the abstract
+value is simply rounded and packed into the single-precision format, with
+the inexact exception raised if the abstract input cannot be represented
+exactly.  However, if the abstract value is too large, the overflow and
+inexact exceptions are raised and an infinity or maximal finite value is
+returned.  If the abstract value is too small, the input value is rounded to
+a subnormal number, and the underflow and inexact exceptions are raised if
+the abstract input cannot be represented exactly as a subnormal single-
+precision floating-point number.
+    The input significand `zSig' has its binary point between bits 30
+and 29, which is 7 bits to the left of the usual location.  This shifted
+significand must be normalized or smaller.  If `zSig' is not normalized,
+`zExp' must be 0; in that case, the result returned is a subnormal number,
+and it must not require rounding.  In the usual case that `zSig' is
+normalized, `zExp' must be 1 less than the ``true'' floating-point exponent.
+The handling of underflow and overflow follows the IEC/IEEE Standard for
+Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float32 roundAndPackFloat32( flag zSign, int16 zExp, bits32 zSig )
+{
+    int8 roundingMode;
+    flag roundNearestEven;
+    int8 roundIncrement, roundBits;
+    flag isTiny;
+
+    roundingMode = float_rounding_mode;
+    roundNearestEven = ( roundingMode == float_round_nearest_even );
+    roundIncrement = 0x40;
+    if ( ! roundNearestEven ) {
+        if ( roundingMode == float_round_to_zero ) {
+            roundIncrement = 0;
+        }
+        else {
+            roundIncrement = 0x7F;
+            if ( zSign ) {
+                if ( roundingMode == float_round_up ) roundIncrement = 0;
+            }
+            else {
+                if ( roundingMode == float_round_down ) roundIncrement = 0;
+            }
+        }
+    }
+    roundBits = zSig & 0x7F;
+    if ( 0xFD <= (bits16) zExp ) {
+        if (    ( 0xFD < zExp )
+             || (    ( zExp == 0xFD )
+                  && ( (sbits32) ( zSig + roundIncrement ) < 0 ) )
+           ) {
+            float_raise( float_flag_overflow | float_flag_inexact );
+            return packFloat32( zSign, 0xFF, 0 ) - ( roundIncrement == 0 );
+        }
+        if ( zExp < 0 ) {
+            isTiny =
+                   ( float_detect_tininess == float_tininess_before_rounding )
+                || ( zExp < -1 )
+                || ( zSig + roundIncrement < 0x80000000 );
+            shift32RightJamming( zSig, - zExp, &zSig );
+            zExp = 0;
+            roundBits = zSig & 0x7F;
+            if ( isTiny && roundBits ) float_raise( float_flag_underflow );
+        }
+    }
+    if ( roundBits ) float_exception_flags |= float_flag_inexact;
+    zSig = ( zSig + roundIncrement )>>7;
+    zSig &= ~ ( ( ( roundBits ^ 0x40 ) == 0 ) & roundNearestEven );
+    if ( zSig == 0 ) zExp = 0;
+    return packFloat32( zSign, zExp, zSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes an abstract floating-point value having sign `zSign', exponent `zExp',
+and significand `zSig', and returns the proper single-precision floating-
+point value corresponding to the abstract input.  This routine is just like
+`roundAndPackFloat32' except that `zSig' does not have to be normalized.
+Bit 31 of `zSig' must be zero, and `zExp' must be 1 less than the ``true''
+floating-point exponent.
+-------------------------------------------------------------------------------
+*/
+static float32
+ normalizeRoundAndPackFloat32( flag zSign, int16 zExp, bits32 zSig )
+{
+    int8 shiftCount;
+
+    shiftCount = countLeadingZeros32( zSig ) - 1;
+    return roundAndPackFloat32( zSign, zExp - shiftCount, zSig<<shiftCount );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the fraction bits of the double-precision floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE bits64 extractFloat64Frac( float64 a )
+{
+
+    return FLOAT64_DEMANGLE(a) & LIT64( 0x000FFFFFFFFFFFFF );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the exponent bits of the double-precision floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE int16 extractFloat64Exp( float64 a )
+{
+
+    return ( FLOAT64_DEMANGLE(a)>>52 ) & 0x7FF;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the sign bit of the double-precision floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE flag extractFloat64Sign( float64 a )
+{
+
+    return FLOAT64_DEMANGLE(a)>>63;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Normalizes the subnormal double-precision floating-point value represented
+by the denormalized significand `aSig'.  The normalized exponent and
+significand are stored at the locations pointed to by `zExpPtr' and
+`zSigPtr', respectively.
+-------------------------------------------------------------------------------
+*/
+static void
+ normalizeFloat64Subnormal( bits64 aSig, int16 *zExpPtr, bits64 *zSigPtr )
+{
+    int8 shiftCount;
+
+    shiftCount = countLeadingZeros64( aSig ) - 11;
+    *zSigPtr = aSig<<shiftCount;
+    *zExpPtr = 1 - shiftCount;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Packs the sign `zSign', exponent `zExp', and significand `zSig' into a
+double-precision floating-point value, returning the result.  After being
+shifted into the proper positions, the three fields are simply added
+together to form the result.  This means that any integer portion of `zSig'
+will be added into the exponent.  Since a properly normalized significand
+will have an integer portion equal to 1, the `zExp' input should be 1 less
+than the desired result exponent whenever `zSig' is a complete, normalized
+significand.
+-------------------------------------------------------------------------------
+*/
+INLINE float64 packFloat64( flag zSign, int16 zExp, bits64 zSig )
+{
+
+    return FLOAT64_MANGLE( ( ( (bits64) zSign )<<63 ) +
+                          ( ( (bits64) zExp )<<52 ) + zSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes an abstract floating-point value having sign `zSign', exponent `zExp',
+and significand `zSig', and returns the proper double-precision floating-
+point value corresponding to the abstract input.  Ordinarily, the abstract
+value is simply rounded and packed into the double-precision format, with
+the inexact exception raised if the abstract input cannot be represented
+exactly.  However, if the abstract value is too large, the overflow and
+inexact exceptions are raised and an infinity or maximal finite value is
+returned.  If the abstract value is too small, the input value is rounded to
+a subnormal number, and the underflow and inexact exceptions are raised if
+the abstract input cannot be represented exactly as a subnormal double-
+precision floating-point number.
+    The input significand `zSig' has its binary point between bits 62
+and 61, which is 10 bits to the left of the usual location.  This shifted
+significand must be normalized or smaller.  If `zSig' is not normalized,
+`zExp' must be 0; in that case, the result returned is a subnormal number,
+and it must not require rounding.  In the usual case that `zSig' is
+normalized, `zExp' must be 1 less than the ``true'' floating-point exponent.
+The handling of underflow and overflow follows the IEC/IEEE Standard for
+Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float64 roundAndPackFloat64( flag zSign, int16 zExp, bits64 zSig )
+{
+    int8 roundingMode;
+    flag roundNearestEven;
+    int16 roundIncrement, roundBits;
+    flag isTiny;
+
+    roundingMode = float_rounding_mode;
+    roundNearestEven = ( roundingMode == float_round_nearest_even );
+    roundIncrement = 0x200;
+    if ( ! roundNearestEven ) {
+        if ( roundingMode == float_round_to_zero ) {
+            roundIncrement = 0;
+        }
+        else {
+            roundIncrement = 0x3FF;
+            if ( zSign ) {
+                if ( roundingMode == float_round_up ) roundIncrement = 0;
+            }
+            else {
+                if ( roundingMode == float_round_down ) roundIncrement = 0;
+            }
+        }
+    }
+    roundBits = zSig & 0x3FF;
+    if ( 0x7FD <= (bits16) zExp ) {
+        if (    ( 0x7FD < zExp )
+             || (    ( zExp == 0x7FD )
+                  && ( (sbits64) ( zSig + roundIncrement ) < 0 ) )
+           ) {
+            float_raise( float_flag_overflow | float_flag_inexact );
+            return FLOAT64_MANGLE(
+               FLOAT64_DEMANGLE(packFloat64( zSign, 0x7FF, 0 )) -
+               ( roundIncrement == 0 ));
+        }
+        if ( zExp < 0 ) {
+            isTiny =
+                   ( float_detect_tininess == float_tininess_before_rounding )
+                || ( zExp < -1 )
+                || ( zSig + roundIncrement < LIT64( 0x8000000000000000 ) );
+            shift64RightJamming( zSig, - zExp, &zSig );
+            zExp = 0;
+            roundBits = zSig & 0x3FF;
+            if ( isTiny && roundBits ) float_raise( float_flag_underflow );
+        }
+    }
+    if ( roundBits ) float_exception_flags |= float_flag_inexact;
+    zSig = ( zSig + roundIncrement )>>10;
+    zSig &= ~ ( ( ( roundBits ^ 0x200 ) == 0 ) & roundNearestEven );
+    if ( zSig == 0 ) zExp = 0;
+    return packFloat64( zSign, zExp, zSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes an abstract floating-point value having sign `zSign', exponent `zExp',
+and significand `zSig', and returns the proper double-precision floating-
+point value corresponding to the abstract input.  This routine is just like
+`roundAndPackFloat64' except that `zSig' does not have to be normalized.
+Bit 63 of `zSig' must be zero, and `zExp' must be 1 less than the ``true''
+floating-point exponent.
+-------------------------------------------------------------------------------
+*/
+static float64
+ normalizeRoundAndPackFloat64( flag zSign, int16 zExp, bits64 zSig )
+{
+    int8 shiftCount;
+
+    shiftCount = countLeadingZeros64( zSig ) - 1;
+    return roundAndPackFloat64( zSign, zExp - shiftCount, zSig<<shiftCount );
+
+}
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Returns the fraction bits of the extended double-precision floating-point
+value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE bits64 extractFloatx80Frac( floatx80 a )
+{
+
+    return a.low;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the exponent bits of the extended double-precision floating-point
+value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE int32 extractFloatx80Exp( floatx80 a )
+{
+
+    return a.high & 0x7FFF;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the sign bit of the extended double-precision floating-point value
+`a'.
+-------------------------------------------------------------------------------
+*/
+INLINE flag extractFloatx80Sign( floatx80 a )
+{
+
+    return a.high>>15;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Normalizes the subnormal extended double-precision floating-point value
+represented by the denormalized significand `aSig'.  The normalized exponent
+and significand are stored at the locations pointed to by `zExpPtr' and
+`zSigPtr', respectively.
+-------------------------------------------------------------------------------
+*/
+static void
+ normalizeFloatx80Subnormal( bits64 aSig, int32 *zExpPtr, bits64 *zSigPtr )
+{
+    int8 shiftCount;
+
+    shiftCount = countLeadingZeros64( aSig );
+    *zSigPtr = aSig<<shiftCount;
+    *zExpPtr = 1 - shiftCount;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Packs the sign `zSign', exponent `zExp', and significand `zSig' into an
+extended double-precision floating-point value, returning the result.
+-------------------------------------------------------------------------------
+*/
+INLINE floatx80 packFloatx80( flag zSign, int32 zExp, bits64 zSig )
+{
+    floatx80 z;
+
+    z.low = zSig;
+    z.high = ( ( (bits16) zSign )<<15 ) + zExp;
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes an abstract floating-point value having sign `zSign', exponent `zExp',
+and extended significand formed by the concatenation of `zSig0' and `zSig1',
+and returns the proper extended double-precision floating-point value
+corresponding to the abstract input.  Ordinarily, the abstract value is
+rounded and packed into the extended double-precision format, with the
+inexact exception raised if the abstract input cannot be represented
+exactly.  However, if the abstract value is too large, the overflow and
+inexact exceptions are raised and an infinity or maximal finite value is
+returned.  If the abstract value is too small, the input value is rounded to
+a subnormal number, and the underflow and inexact exceptions are raised if
+the abstract input cannot be represented exactly as a subnormal extended
+double-precision floating-point number.
+    If `roundingPrecision' is 32 or 64, the result is rounded to the same
+number of bits as single or double precision, respectively.  Otherwise, the
+result is rounded to the full precision of the extended double-precision
+format.
+    The input significand must be normalized or smaller.  If the input
+significand is not normalized, `zExp' must be 0; in that case, the result
+returned is a subnormal number, and it must not require rounding.  The
+handling of underflow and overflow follows the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static floatx80
+ roundAndPackFloatx80(
+     int8 roundingPrecision, flag zSign, int32 zExp, bits64 zSig0, bits64 zSig1
+ )
+{
+    int8 roundingMode;
+    flag roundNearestEven, increment, isTiny;
+    int64 roundIncrement, roundMask, roundBits;
+
+    roundingMode = float_rounding_mode;
+    roundNearestEven = ( roundingMode == float_round_nearest_even );
+    if ( roundingPrecision == 80 ) goto precision80;
+    if ( roundingPrecision == 64 ) {
+        roundIncrement = LIT64( 0x0000000000000400 );
+        roundMask = LIT64( 0x00000000000007FF );
+    }
+    else if ( roundingPrecision == 32 ) {
+        roundIncrement = LIT64( 0x0000008000000000 );
+        roundMask = LIT64( 0x000000FFFFFFFFFF );
+    }
+    else {
+        goto precision80;
+    }
+    zSig0 |= ( zSig1 != 0 );
+    if ( ! roundNearestEven ) {
+        if ( roundingMode == float_round_to_zero ) {
+            roundIncrement = 0;
+        }
+        else {
+            roundIncrement = roundMask;
+            if ( zSign ) {
+                if ( roundingMode == float_round_up ) roundIncrement = 0;
+            }
+            else {
+                if ( roundingMode == float_round_down ) roundIncrement = 0;
+            }
+        }
+    }
+    roundBits = zSig0 & roundMask;
+    if ( 0x7FFD <= (bits32) ( zExp - 1 ) ) {
+        if (    ( 0x7FFE < zExp )
+             || ( ( zExp == 0x7FFE ) && ( zSig0 + roundIncrement < zSig0 ) )
+           ) {
+            goto overflow;
+        }
+        if ( zExp <= 0 ) {
+            isTiny =
+                   ( float_detect_tininess == float_tininess_before_rounding )
+                || ( zExp < 0 )
+                || ( zSig0 <= zSig0 + roundIncrement );
+            shift64RightJamming( zSig0, 1 - zExp, &zSig0 );
+            zExp = 0;
+            roundBits = zSig0 & roundMask;
+            if ( isTiny && roundBits ) float_raise( float_flag_underflow );
+            if ( roundBits ) float_exception_flags |= float_flag_inexact;
+            zSig0 += roundIncrement;
+            if ( (sbits64) zSig0 < 0 ) zExp = 1;
+            roundIncrement = roundMask + 1;
+            if ( roundNearestEven && ( roundBits<<1 == roundIncrement ) ) {
+                roundMask |= roundIncrement;
+            }
+            zSig0 &= ~ roundMask;
+            return packFloatx80( zSign, zExp, zSig0 );
+        }
+    }
+    if ( roundBits ) float_exception_flags |= float_flag_inexact;
+    zSig0 += roundIncrement;
+    if ( zSig0 < roundIncrement ) {
+        ++zExp;
+        zSig0 = LIT64( 0x8000000000000000 );
+    }
+    roundIncrement = roundMask + 1;
+    if ( roundNearestEven && ( roundBits<<1 == roundIncrement ) ) {
+        roundMask |= roundIncrement;
+    }
+    zSig0 &= ~ roundMask;
+    if ( zSig0 == 0 ) zExp = 0;
+    return packFloatx80( zSign, zExp, zSig0 );
+ precision80:
+    increment = ( (sbits64) zSig1 < 0 );
+    if ( ! roundNearestEven ) {
+        if ( roundingMode == float_round_to_zero ) {
+            increment = 0;
+        }
+        else {
+            if ( zSign ) {
+                increment = ( roundingMode == float_round_down ) && zSig1;
+            }
+            else {
+                increment = ( roundingMode == float_round_up ) && zSig1;
+            }
+        }
+    }
+    if ( 0x7FFD <= (bits32) ( zExp - 1 ) ) {
+        if (    ( 0x7FFE < zExp )
+             || (    ( zExp == 0x7FFE )
+                  && ( zSig0 == LIT64( 0xFFFFFFFFFFFFFFFF ) )
+                  && increment
+                )
+           ) {
+            roundMask = 0;
+ overflow:
+            float_raise( float_flag_overflow | float_flag_inexact );
+            if (    ( roundingMode == float_round_to_zero )
+                 || ( zSign && ( roundingMode == float_round_up ) )
+                 || ( ! zSign && ( roundingMode == float_round_down ) )
+               ) {
+                return packFloatx80( zSign, 0x7FFE, ~ roundMask );
+            }
+            return packFloatx80( zSign, 0x7FFF, LIT64( 0x8000000000000000 ) );
+        }
+        if ( zExp <= 0 ) {
+            isTiny =
+                   ( float_detect_tininess == float_tininess_before_rounding )
+                || ( zExp < 0 )
+                || ! increment
+                || ( zSig0 < LIT64( 0xFFFFFFFFFFFFFFFF ) );
+            shift64ExtraRightJamming( zSig0, zSig1, 1 - zExp, &zSig0, &zSig1 );
+            zExp = 0;
+            if ( isTiny && zSig1 ) float_raise( float_flag_underflow );
+            if ( zSig1 ) float_exception_flags |= float_flag_inexact;
+            if ( roundNearestEven ) {
+                increment = ( (sbits64) zSig1 < 0 );
+            }
+            else {
+                if ( zSign ) {
+                    increment = ( roundingMode == float_round_down ) && zSig1;
+                }
+                else {
+                    increment = ( roundingMode == float_round_up ) && zSig1;
+                }
+            }
+            if ( increment ) {
+                ++zSig0;
+                zSig0 &=
+                    ~ ( ( (bits64) ( zSig1<<1 ) == 0 ) & roundNearestEven );
+                if ( (sbits64) zSig0 < 0 ) zExp = 1;
+            }
+            return packFloatx80( zSign, zExp, zSig0 );
+        }
+    }
+    if ( zSig1 ) float_exception_flags |= float_flag_inexact;
+    if ( increment ) {
+        ++zSig0;
+        if ( zSig0 == 0 ) {
+            ++zExp;
+            zSig0 = LIT64( 0x8000000000000000 );
+        }
+        else {
+            zSig0 &= ~ ( ( (bits64) ( zSig1<<1 ) == 0 ) & roundNearestEven );
+        }
+    }
+    else {
+        if ( zSig0 == 0 ) zExp = 0;
+    }
+    return packFloatx80( zSign, zExp, zSig0 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes an abstract floating-point value having sign `zSign', exponent
+`zExp', and significand formed by the concatenation of `zSig0' and `zSig1',
+and returns the proper extended double-precision floating-point value
+corresponding to the abstract input.  This routine is just like
+`roundAndPackFloatx80' except that the input significand does not have to be
+normalized.
+-------------------------------------------------------------------------------
+*/
+static floatx80
+ normalizeRoundAndPackFloatx80(
+     int8 roundingPrecision, flag zSign, int32 zExp, bits64 zSig0, bits64 zSig1
+ )
+{
+    int8 shiftCount;
+
+    if ( zSig0 == 0 ) {
+        zSig0 = zSig1;
+        zSig1 = 0;
+        zExp -= 64;
+    }
+    shiftCount = countLeadingZeros64( zSig0 );
+    shortShift128Left( zSig0, zSig1, shiftCount, &zSig0, &zSig1 );
+    zExp -= shiftCount;
+    return
+        roundAndPackFloatx80( roundingPrecision, zSign, zExp, zSig0, zSig1 );
+
+}
+
+#endif
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Returns the least-significant 64 fraction bits of the quadruple-precision
+floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE bits64 extractFloat128Frac1( float128 a )
+{
+
+    return a.low;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the most-significant 48 fraction bits of the quadruple-precision
+floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE bits64 extractFloat128Frac0( float128 a )
+{
+
+    return a.high & LIT64( 0x0000FFFFFFFFFFFF );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the exponent bits of the quadruple-precision floating-point value
+`a'.
+-------------------------------------------------------------------------------
+*/
+INLINE int32 extractFloat128Exp( float128 a )
+{
+
+    return ( a.high>>48 ) & 0x7FFF;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the sign bit of the quadruple-precision floating-point value `a'.
+-------------------------------------------------------------------------------
+*/
+INLINE flag extractFloat128Sign( float128 a )
+{
+
+    return a.high>>63;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Normalizes the subnormal quadruple-precision floating-point value
+represented by the denormalized significand formed by the concatenation of
+`aSig0' and `aSig1'.  The normalized exponent is stored at the location
+pointed to by `zExpPtr'.  The most significant 49 bits of the normalized
+significand are stored at the location pointed to by `zSig0Ptr', and the
+least significant 64 bits of the normalized significand are stored at the
+location pointed to by `zSig1Ptr'.
+-------------------------------------------------------------------------------
+*/
+static void
+ normalizeFloat128Subnormal(
+     bits64 aSig0,
+     bits64 aSig1,
+     int32 *zExpPtr,
+     bits64 *zSig0Ptr,
+     bits64 *zSig1Ptr
+ )
+{
+    int8 shiftCount;
+
+    if ( aSig0 == 0 ) {
+        shiftCount = countLeadingZeros64( aSig1 ) - 15;
+        if ( shiftCount < 0 ) {
+            *zSig0Ptr = aSig1>>( - shiftCount );
+            *zSig1Ptr = aSig1<<( shiftCount & 63 );
+        }
+        else {
+            *zSig0Ptr = aSig1<<shiftCount;
+            *zSig1Ptr = 0;
+        }
+        *zExpPtr = - shiftCount - 63;
+    }
+    else {
+        shiftCount = countLeadingZeros64( aSig0 ) - 15;
+        shortShift128Left( aSig0, aSig1, shiftCount, zSig0Ptr, zSig1Ptr );
+        *zExpPtr = 1 - shiftCount;
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Packs the sign `zSign', the exponent `zExp', and the significand formed
+by the concatenation of `zSig0' and `zSig1' into a quadruple-precision
+floating-point value, returning the result.  After being shifted into the
+proper positions, the three fields `zSign', `zExp', and `zSig0' are simply
+added together to form the most significant 32 bits of the result.  This
+means that any integer portion of `zSig0' will be added into the exponent.
+Since a properly normalized significand will have an integer portion equal
+to 1, the `zExp' input should be 1 less than the desired result exponent
+whenever `zSig0' and `zSig1' concatenated form a complete, normalized
+significand.
+-------------------------------------------------------------------------------
+*/
+INLINE float128
+ packFloat128( flag zSign, int32 zExp, bits64 zSig0, bits64 zSig1 )
+{
+    float128 z;
+
+    z.low = zSig1;
+    z.high = ( ( (bits64) zSign )<<63 ) + ( ( (bits64) zExp )<<48 ) + zSig0;
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes an abstract floating-point value having sign `zSign', exponent `zExp',
+and extended significand formed by the concatenation of `zSig0', `zSig1',
+and `zSig2', and returns the proper quadruple-precision floating-point value
+corresponding to the abstract input.  Ordinarily, the abstract value is
+simply rounded and packed into the quadruple-precision format, with the
+inexact exception raised if the abstract input cannot be represented
+exactly.  However, if the abstract value is too large, the overflow and
+inexact exceptions are raised and an infinity or maximal finite value is
+returned.  If the abstract value is too small, the input value is rounded to
+a subnormal number, and the underflow and inexact exceptions are raised if
+the abstract input cannot be represented exactly as a subnormal quadruple-
+precision floating-point number.
+    The input significand must be normalized or smaller.  If the input
+significand is not normalized, `zExp' must be 0; in that case, the result
+returned is a subnormal number, and it must not require rounding.  In the
+usual case that the input significand is normalized, `zExp' must be 1 less
+than the ``true'' floating-point exponent.  The handling of underflow and
+overflow follows the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float128
+ roundAndPackFloat128(
+     flag zSign, int32 zExp, bits64 zSig0, bits64 zSig1, bits64 zSig2 )
+{
+    int8 roundingMode;
+    flag roundNearestEven, increment, isTiny;
+
+    roundingMode = float_rounding_mode;
+    roundNearestEven = ( roundingMode == float_round_nearest_even );
+    increment = ( (sbits64) zSig2 < 0 );
+    if ( ! roundNearestEven ) {
+        if ( roundingMode == float_round_to_zero ) {
+            increment = 0;
+        }
+        else {
+            if ( zSign ) {
+                increment = ( roundingMode == float_round_down ) && zSig2;
+            }
+            else {
+                increment = ( roundingMode == float_round_up ) && zSig2;
+            }
+        }
+    }
+    if ( 0x7FFD <= (bits32) zExp ) {
+        if (    ( 0x7FFD < zExp )
+             || (    ( zExp == 0x7FFD )
+                  && eq128(
+                         LIT64( 0x0001FFFFFFFFFFFF ),
+                         LIT64( 0xFFFFFFFFFFFFFFFF ),
+                         zSig0,
+                         zSig1
+                     )
+                  && increment
+                )
+           ) {
+            float_raise( float_flag_overflow | float_flag_inexact );
+            if (    ( roundingMode == float_round_to_zero )
+                 || ( zSign && ( roundingMode == float_round_up ) )
+                 || ( ! zSign && ( roundingMode == float_round_down ) )
+               ) {
+                return
+                    packFloat128(
+                        zSign,
+                        0x7FFE,
+                        LIT64( 0x0000FFFFFFFFFFFF ),
+                        LIT64( 0xFFFFFFFFFFFFFFFF )
+                    );
+            }
+            return packFloat128( zSign, 0x7FFF, 0, 0 );
+        }
+        if ( zExp < 0 ) {
+            isTiny =
+                   ( float_detect_tininess == float_tininess_before_rounding )
+                || ( zExp < -1 )
+                || ! increment
+                || lt128(
+                       zSig0,
+                       zSig1,
+                       LIT64( 0x0001FFFFFFFFFFFF ),
+                       LIT64( 0xFFFFFFFFFFFFFFFF )
+                   );
+            shift128ExtraRightJamming(
+                zSig0, zSig1, zSig2, - zExp, &zSig0, &zSig1, &zSig2 );
+            zExp = 0;
+            if ( isTiny && zSig2 ) float_raise( float_flag_underflow );
+            if ( roundNearestEven ) {
+                increment = ( (sbits64) zSig2 < 0 );
+            }
+            else {
+                if ( zSign ) {
+                    increment = ( roundingMode == float_round_down ) && zSig2;
+                }
+                else {
+                    increment = ( roundingMode == float_round_up ) && zSig2;
+                }
+            }
+        }
+    }
+    if ( zSig2 ) float_exception_flags |= float_flag_inexact;
+    if ( increment ) {
+        add128( zSig0, zSig1, 0, 1, &zSig0, &zSig1 );
+        zSig1 &= ~ ( ( zSig2 + zSig2 == 0 ) & roundNearestEven );
+    }
+    else {
+        if ( ( zSig0 | zSig1 ) == 0 ) zExp = 0;
+    }
+    return packFloat128( zSign, zExp, zSig0, zSig1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes an abstract floating-point value having sign `zSign', exponent `zExp',
+and significand formed by the concatenation of `zSig0' and `zSig1', and
+returns the proper quadruple-precision floating-point value corresponding
+to the abstract input.  This routine is just like `roundAndPackFloat128'
+except that the input significand has fewer bits and does not have to be
+normalized.  In all cases, `zExp' must be 1 less than the ``true'' floating-
+point exponent.
+-------------------------------------------------------------------------------
+*/
+static float128
+ normalizeRoundAndPackFloat128(
+     flag zSign, int32 zExp, bits64 zSig0, bits64 zSig1 )
+{
+    int8 shiftCount;
+    bits64 zSig2;
+
+    if ( zSig0 == 0 ) {
+        zSig0 = zSig1;
+        zSig1 = 0;
+        zExp -= 64;
+    }
+    shiftCount = countLeadingZeros64( zSig0 ) - 15;
+    if ( 0 <= shiftCount ) {
+        zSig2 = 0;
+        shortShift128Left( zSig0, zSig1, shiftCount, &zSig0, &zSig1 );
+    }
+    else {
+        shift128ExtraRightJamming(
+            zSig0, zSig1, 0, - shiftCount, &zSig0, &zSig1, &zSig2 );
+    }
+    zExp -= shiftCount;
+    return roundAndPackFloat128( zSign, zExp, zSig0, zSig1, zSig2 );
+
+}
+
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the 32-bit two's complement integer `a'
+to the single-precision floating-point format.  The conversion is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 int32_to_float32( int32 a )
+{
+    flag zSign;
+
+    if ( a == 0 ) return 0;
+    if ( a == (sbits32) 0x80000000 ) return packFloat32( 1, 0x9E, 0 );
+    zSign = ( a < 0 );
+    return normalizeRoundAndPackFloat32( zSign, 0x9C, zSign ? - a : a );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the 32-bit two's complement integer `a'
+to the double-precision floating-point format.  The conversion is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 int32_to_float64( int32 a )
+{
+    flag zSign;
+    uint32 absA;
+    int8 shiftCount;
+    bits64 zSig;
+
+    if ( a == 0 ) return 0;
+    zSign = ( a < 0 );
+    absA = zSign ? - a : a;
+    shiftCount = countLeadingZeros32( absA ) + 21;
+    zSig = absA;
+    return packFloat64( zSign, 0x432 - shiftCount, zSig<<shiftCount );
+
+}
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the 32-bit two's complement integer `a'
+to the extended double-precision floating-point format.  The conversion
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+floatx80 int32_to_floatx80( int32 a )
+{
+    flag zSign;
+    uint32 absA;
+    int8 shiftCount;
+    bits64 zSig;
+
+    if ( a == 0 ) return packFloatx80( 0, 0, 0 );
+    zSign = ( a < 0 );
+    absA = zSign ? - a : a;
+    shiftCount = countLeadingZeros32( absA ) + 32;
+    zSig = absA;
+    return packFloatx80( zSign, 0x403E - shiftCount, zSig<<shiftCount );
+
+}
+
+#endif
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the 32-bit two's complement integer `a' to
+the quadruple-precision floating-point format.  The conversion is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float128 int32_to_float128( int32 a )
+{
+    flag zSign;
+    uint32 absA;
+    int8 shiftCount;
+    bits64 zSig0;
+
+    if ( a == 0 ) return packFloat128( 0, 0, 0, 0 );
+    zSign = ( a < 0 );
+    absA = zSign ? - a : a;
+    shiftCount = countLeadingZeros32( absA ) + 17;
+    zSig0 = absA;
+    return packFloat128( zSign, 0x402E - shiftCount, zSig0<<shiftCount, 0 );
+
+}
+
+#endif
+
+#ifndef SOFTFLOAT_FOR_GCC /* __floatdi?f is in libgcc2.c */
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the 64-bit two's complement integer `a'
+to the single-precision floating-point format.  The conversion is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 int64_to_float32( int64 a )
+{
+    flag zSign;
+    uint64 absA;
+    int8 shiftCount;
+
+    if ( a == 0 ) return 0;
+    zSign = ( a < 0 );
+    absA = zSign ? - a : a;
+    shiftCount = countLeadingZeros64( absA ) - 40;
+    if ( 0 <= shiftCount ) {
+        return packFloat32( zSign, 0x95 - shiftCount, absA<<shiftCount );
+    }
+    else {
+        shiftCount += 7;
+        if ( shiftCount < 0 ) {
+            shift64RightJamming( absA, - shiftCount, &absA );
+        }
+        else {
+            absA <<= shiftCount;
+        }
+        return roundAndPackFloat32( zSign, 0x9C - shiftCount, absA );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the 64-bit two's complement integer `a'
+to the double-precision floating-point format.  The conversion is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 int64_to_float64( int64 a )
+{
+    flag zSign;
+
+    if ( a == 0 ) return 0;
+    if ( a == (sbits64) LIT64( 0x8000000000000000 ) ) {
+        return packFloat64( 1, 0x43E, 0 );
+    }
+    zSign = ( a < 0 );
+    return normalizeRoundAndPackFloat64( zSign, 0x43C, zSign ? - a : a );
+
+}
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the 64-bit two's complement integer `a'
+to the extended double-precision floating-point format.  The conversion
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+floatx80 int64_to_floatx80( int64 a )
+{
+    flag zSign;
+    uint64 absA;
+    int8 shiftCount;
+
+    if ( a == 0 ) return packFloatx80( 0, 0, 0 );
+    zSign = ( a < 0 );
+    absA = zSign ? - a : a;
+    shiftCount = countLeadingZeros64( absA );
+    return packFloatx80( zSign, 0x403E - shiftCount, absA<<shiftCount );
+
+}
+
+#endif
+
+#endif /* !SOFTFLOAT_FOR_GCC */
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the 64-bit two's complement integer `a' to
+the quadruple-precision floating-point format.  The conversion is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float128 int64_to_float128( int64 a )
+{
+    flag zSign;
+    uint64 absA;
+    int8 shiftCount;
+    int32 zExp;
+    bits64 zSig0, zSig1;
+
+    if ( a == 0 ) return packFloat128( 0, 0, 0, 0 );
+    zSign = ( a < 0 );
+    absA = zSign ? - a : a;
+    shiftCount = countLeadingZeros64( absA ) + 49;
+    zExp = 0x406E - shiftCount;
+    if ( 64 <= shiftCount ) {
+        zSig1 = 0;
+        zSig0 = absA;
+        shiftCount -= 64;
+    }
+    else {
+        zSig1 = absA;
+        zSig0 = 0;
+    }
+    shortShift128Left( zSig0, zSig1, shiftCount, &zSig0, &zSig1 );
+    return packFloat128( zSign, zExp, zSig0, zSig1 );
+
+}
+
+#endif
+
+#ifndef SOFTFLOAT_FOR_GCC /* Not needed */
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the single-precision floating-point value
+`a' to the 32-bit two's complement integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic---which means in particular that the conversion is rounded
+according to the current rounding mode.  If `a' is a NaN, the largest
+positive integer is returned.  Otherwise, if the conversion overflows, the
+largest integer with the same sign as `a' is returned.
+-------------------------------------------------------------------------------
+*/
+int32 float32_to_int32( float32 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits32 aSig;
+    bits64 aSig64;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    if ( ( aExp == 0xFF ) && aSig ) aSign = 0;
+    if ( aExp ) aSig |= 0x00800000;
+    shiftCount = 0xAF - aExp;
+    aSig64 = aSig;
+    aSig64 <<= 32;
+    if ( 0 < shiftCount ) shift64RightJamming( aSig64, shiftCount, &aSig64 );
+    return roundAndPackInt32( aSign, aSig64 );
+
+}
+#endif /* !SOFTFLOAT_FOR_GCC */
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the single-precision floating-point value
+`a' to the 32-bit two's complement integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic, except that the conversion is always rounded toward zero.
+If `a' is a NaN, the largest positive integer is returned.  Otherwise, if
+the conversion overflows, the largest integer with the same sign as `a' is
+returned.
+-------------------------------------------------------------------------------
+*/
+int32 float32_to_int32_round_to_zero( float32 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits32 aSig;
+    int32 z;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    shiftCount = aExp - 0x9E;
+    if ( 0 <= shiftCount ) {
+        if ( a != 0xCF000000 ) {
+            float_raise( float_flag_invalid );
+            if ( ! aSign || ( ( aExp == 0xFF ) && aSig ) ) return 0x7FFFFFFF;
+        }
+        return (sbits32) 0x80000000;
+    }
+    else if ( aExp <= 0x7E ) {
+        if ( aExp | aSig ) float_exception_flags |= float_flag_inexact;
+        return 0;
+    }
+    aSig = ( aSig | 0x00800000 )<<8;
+    z = aSig>>( - shiftCount );
+    if ( (bits32) ( aSig<<( shiftCount & 31 ) ) ) {
+        float_exception_flags |= float_flag_inexact;
+    }
+    if ( aSign ) z = - z;
+    return z;
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC /* __fix?fdi provided by libgcc2.c */
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the single-precision floating-point value
+`a' to the 64-bit two's complement integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic---which means in particular that the conversion is rounded
+according to the current rounding mode.  If `a' is a NaN, the largest
+positive integer is returned.  Otherwise, if the conversion overflows, the
+largest integer with the same sign as `a' is returned.
+-------------------------------------------------------------------------------
+*/
+int64 float32_to_int64( float32 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits32 aSig;
+    bits64 aSig64, aSigExtra;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    shiftCount = 0xBE - aExp;
+    if ( shiftCount < 0 ) {
+        float_raise( float_flag_invalid );
+        if ( ! aSign || ( ( aExp == 0xFF ) && aSig ) ) {
+            return LIT64( 0x7FFFFFFFFFFFFFFF );
+        }
+        return (sbits64) LIT64( 0x8000000000000000 );
+    }
+    if ( aExp ) aSig |= 0x00800000;
+    aSig64 = aSig;
+    aSig64 <<= 40;
+    shift64ExtraRightJamming( aSig64, 0, shiftCount, &aSig64, &aSigExtra );
+    return roundAndPackInt64( aSign, aSig64, aSigExtra );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the single-precision floating-point value
+`a' to the 64-bit two's complement integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic, except that the conversion is always rounded toward zero.  If
+`a' is a NaN, the largest positive integer is returned.  Otherwise, if the
+conversion overflows, the largest integer with the same sign as `a' is
+returned.
+-------------------------------------------------------------------------------
+*/
+int64 float32_to_int64_round_to_zero( float32 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits32 aSig;
+    bits64 aSig64;
+    int64 z;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    shiftCount = aExp - 0xBE;
+    if ( 0 <= shiftCount ) {
+        if ( a != 0xDF000000 ) {
+            float_raise( float_flag_invalid );
+            if ( ! aSign || ( ( aExp == 0xFF ) && aSig ) ) {
+                return LIT64( 0x7FFFFFFFFFFFFFFF );
+            }
+        }
+        return (sbits64) LIT64( 0x8000000000000000 );
+    }
+    else if ( aExp <= 0x7E ) {
+        if ( aExp | aSig ) float_exception_flags |= float_flag_inexact;
+        return 0;
+    }
+    aSig64 = aSig | 0x00800000;
+    aSig64 <<= 40;
+    z = aSig64>>( - shiftCount );
+    if ( (bits64) ( aSig64<<( shiftCount & 63 ) ) ) {
+        float_exception_flags |= float_flag_inexact;
+    }
+    if ( aSign ) z = - z;
+    return z;
+
+}
+#endif /* !SOFTFLOAT_FOR_GCC */
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the single-precision floating-point value
+`a' to the double-precision floating-point format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float32_to_float64( float32 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits32 aSig;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    if ( aExp == 0xFF ) {
+        if ( aSig ) return commonNaNToFloat64( float32ToCommonNaN( a ) );
+        return packFloat64( aSign, 0x7FF, 0 );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloat64( aSign, 0, 0 );
+        normalizeFloat32Subnormal( aSig, &aExp, &aSig );
+        --aExp;
+    }
+    return packFloat64( aSign, aExp + 0x380, ( (bits64) aSig )<<29 );
+
+}
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the single-precision floating-point value
+`a' to the extended double-precision floating-point format.  The conversion
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+floatx80 float32_to_floatx80( float32 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits32 aSig;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    if ( aExp == 0xFF ) {
+        if ( aSig ) return commonNaNToFloatx80( float32ToCommonNaN( a ) );
+        return packFloatx80( aSign, 0x7FFF, LIT64( 0x8000000000000000 ) );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloatx80( aSign, 0, 0 );
+        normalizeFloat32Subnormal( aSig, &aExp, &aSig );
+    }
+    aSig |= 0x00800000;
+    return packFloatx80( aSign, aExp + 0x3F80, ( (bits64) aSig )<<40 );
+
+}
+
+#endif
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the single-precision floating-point value
+`a' to the double-precision floating-point format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float128 float32_to_float128( float32 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits32 aSig;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    if ( aExp == 0xFF ) {
+        if ( aSig ) return commonNaNToFloat128( float32ToCommonNaN( a ) );
+        return packFloat128( aSign, 0x7FFF, 0, 0 );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloat128( aSign, 0, 0, 0 );
+        normalizeFloat32Subnormal( aSig, &aExp, &aSig );
+        --aExp;
+    }
+    return packFloat128( aSign, aExp + 0x3F80, ( (bits64) aSig )<<25, 0 );
+
+}
+
+#endif
+
+#ifndef SOFTFLOAT_FOR_GCC /* Not needed */
+/*
+-------------------------------------------------------------------------------
+Rounds the single-precision floating-point value `a' to an integer, and
+returns the result as a single-precision floating-point value.  The
+operation is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_round_to_int( float32 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits32 lastBitMask, roundBitsMask;
+    int8 roundingMode;
+    float32 z;
+
+    aExp = extractFloat32Exp( a );
+    if ( 0x96 <= aExp ) {
+        if ( ( aExp == 0xFF ) && extractFloat32Frac( a ) ) {
+            return propagateFloat32NaN( a, a );
+        }
+        return a;
+    }
+    if ( aExp <= 0x7E ) {
+        if ( (bits32) ( a<<1 ) == 0 ) return a;
+        float_exception_flags |= float_flag_inexact;
+        aSign = extractFloat32Sign( a );
+        switch ( float_rounding_mode ) {
+         case float_round_nearest_even:
+            if ( ( aExp == 0x7E ) && extractFloat32Frac( a ) ) {
+                return packFloat32( aSign, 0x7F, 0 );
+            }
+            break;
+        case float_round_to_zero:
+           break;
+         case float_round_down:
+            return aSign ? 0xBF800000 : 0;
+         case float_round_up:
+            return aSign ? 0x80000000 : 0x3F800000;
+        }
+        return packFloat32( aSign, 0, 0 );
+    }
+    lastBitMask = 1;
+    lastBitMask <<= 0x96 - aExp;
+    roundBitsMask = lastBitMask - 1;
+    z = a;
+    roundingMode = float_rounding_mode;
+    if ( roundingMode == float_round_nearest_even ) {
+        z += lastBitMask>>1;
+        if ( ( z & roundBitsMask ) == 0 ) z &= ~ lastBitMask;
+    }
+    else if ( roundingMode != float_round_to_zero ) {
+        if ( extractFloat32Sign( z ) ^ ( roundingMode == float_round_up ) ) {
+            z += roundBitsMask;
+        }
+    }
+    z &= ~ roundBitsMask;
+    if ( z != a ) float_exception_flags |= float_flag_inexact;
+    return z;
+
+}
+#endif /* !SOFTFLOAT_FOR_GCC */
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of adding the absolute values of the single-precision
+floating-point values `a' and `b'.  If `zSign' is 1, the sum is negated
+before being returned.  `zSign' is ignored if the result is a NaN.
+The addition is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float32 addFloat32Sigs( float32 a, float32 b, flag zSign )
+{
+    int16 aExp, bExp, zExp;
+    bits32 aSig, bSig, zSig;
+    int16 expDiff;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    bSig = extractFloat32Frac( b );
+    bExp = extractFloat32Exp( b );
+    expDiff = aExp - bExp;
+    aSig <<= 6;
+    bSig <<= 6;
+    if ( 0 < expDiff ) {
+        if ( aExp == 0xFF ) {
+            if ( aSig ) return propagateFloat32NaN( a, b );
+            return a;
+        }
+        if ( bExp == 0 ) {
+            --expDiff;
+        }
+        else {
+            bSig |= 0x20000000;
+        }
+        shift32RightJamming( bSig, expDiff, &bSig );
+        zExp = aExp;
+    }
+    else if ( expDiff < 0 ) {
+        if ( bExp == 0xFF ) {
+            if ( bSig ) return propagateFloat32NaN( a, b );
+            return packFloat32( zSign, 0xFF, 0 );
+        }
+        if ( aExp == 0 ) {
+            ++expDiff;
+        }
+        else {
+            aSig |= 0x20000000;
+        }
+        shift32RightJamming( aSig, - expDiff, &aSig );
+        zExp = bExp;
+    }
+    else {
+        if ( aExp == 0xFF ) {
+            if ( aSig | bSig ) return propagateFloat32NaN( a, b );
+            return a;
+        }
+        if ( aExp == 0 ) return packFloat32( zSign, 0, ( aSig + bSig )>>6 );
+        zSig = 0x40000000 + aSig + bSig;
+        zExp = aExp;
+        goto roundAndPack;
+    }
+    aSig |= 0x20000000;
+    zSig = ( aSig + bSig )<<1;
+    --zExp;
+    if ( (sbits32) zSig < 0 ) {
+        zSig = aSig + bSig;
+        ++zExp;
+    }
+ roundAndPack:
+    return roundAndPackFloat32( zSign, zExp, zSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of subtracting the absolute values of the single-
+precision floating-point values `a' and `b'.  If `zSign' is 1, the
+difference is negated before being returned.  `zSign' is ignored if the
+result is a NaN.  The subtraction is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float32 subFloat32Sigs( float32 a, float32 b, flag zSign )
+{
+    int16 aExp, bExp, zExp;
+    bits32 aSig, bSig, zSig;
+    int16 expDiff;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    bSig = extractFloat32Frac( b );
+    bExp = extractFloat32Exp( b );
+    expDiff = aExp - bExp;
+    aSig <<= 7;
+    bSig <<= 7;
+    if ( 0 < expDiff ) goto aExpBigger;
+    if ( expDiff < 0 ) goto bExpBigger;
+    if ( aExp == 0xFF ) {
+        if ( aSig | bSig ) return propagateFloat32NaN( a, b );
+        float_raise( float_flag_invalid );
+        return float32_default_nan;
+    }
+    if ( aExp == 0 ) {
+        aExp = 1;
+        bExp = 1;
+    }
+    if ( bSig < aSig ) goto aBigger;
+    if ( aSig < bSig ) goto bBigger;
+    return packFloat32( float_rounding_mode == float_round_down, 0, 0 );
+ bExpBigger:
+    if ( bExp == 0xFF ) {
+        if ( bSig ) return propagateFloat32NaN( a, b );
+        return packFloat32( zSign ^ 1, 0xFF, 0 );
+    }
+    if ( aExp == 0 ) {
+        ++expDiff;
+    }
+    else {
+        aSig |= 0x40000000;
+    }
+    shift32RightJamming( aSig, - expDiff, &aSig );
+    bSig |= 0x40000000;
+ bBigger:
+    zSig = bSig - aSig;
+    zExp = bExp;
+    zSign ^= 1;
+    goto normalizeRoundAndPack;
+ aExpBigger:
+    if ( aExp == 0xFF ) {
+        if ( aSig ) return propagateFloat32NaN( a, b );
+        return a;
+    }
+    if ( bExp == 0 ) {
+        --expDiff;
+    }
+    else {
+        bSig |= 0x40000000;
+    }
+    shift32RightJamming( bSig, expDiff, &bSig );
+    aSig |= 0x40000000;
+ aBigger:
+    zSig = aSig - bSig;
+    zExp = aExp;
+ normalizeRoundAndPack:
+    --zExp;
+    return normalizeRoundAndPackFloat32( zSign, zExp, zSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of adding the single-precision floating-point values `a'
+and `b'.  The operation is performed according to the IEC/IEEE Standard for
+Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_add( float32 a, float32 b )
+{
+    flag aSign, bSign;
+
+    aSign = extractFloat32Sign( a );
+    bSign = extractFloat32Sign( b );
+    if ( aSign == bSign ) {
+        return addFloat32Sigs( a, b, aSign );
+    }
+    else {
+        return subFloat32Sigs( a, b, aSign );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of subtracting the single-precision floating-point values
+`a' and `b'.  The operation is performed according to the IEC/IEEE Standard
+for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_sub( float32 a, float32 b )
+{
+    flag aSign, bSign;
+
+    aSign = extractFloat32Sign( a );
+    bSign = extractFloat32Sign( b );
+    if ( aSign == bSign ) {
+        return subFloat32Sigs( a, b, aSign );
+    }
+    else {
+        return addFloat32Sigs( a, b, aSign );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of multiplying the single-precision floating-point values
+`a' and `b'.  The operation is performed according to the IEC/IEEE Standard
+for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_mul( float32 a, float32 b )
+{
+    flag aSign, bSign, zSign;
+    int16 aExp, bExp, zExp;
+    bits32 aSig, bSig;
+    bits64 zSig64;
+    bits32 zSig;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    bSig = extractFloat32Frac( b );
+    bExp = extractFloat32Exp( b );
+    bSign = extractFloat32Sign( b );
+    zSign = aSign ^ bSign;
+    if ( aExp == 0xFF ) {
+        if ( aSig || ( ( bExp == 0xFF ) && bSig ) ) {
+            return propagateFloat32NaN( a, b );
+        }
+        if ( ( bExp | bSig ) == 0 ) {
+            float_raise( float_flag_invalid );
+            return float32_default_nan;
+        }
+        return packFloat32( zSign, 0xFF, 0 );
+    }
+    if ( bExp == 0xFF ) {
+        if ( bSig ) return propagateFloat32NaN( a, b );
+        if ( ( aExp | aSig ) == 0 ) {
+            float_raise( float_flag_invalid );
+            return float32_default_nan;
+        }
+        return packFloat32( zSign, 0xFF, 0 );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloat32( zSign, 0, 0 );
+        normalizeFloat32Subnormal( aSig, &aExp, &aSig );
+    }
+    if ( bExp == 0 ) {
+        if ( bSig == 0 ) return packFloat32( zSign, 0, 0 );
+        normalizeFloat32Subnormal( bSig, &bExp, &bSig );
+    }
+    zExp = aExp + bExp - 0x7F;
+    aSig = ( aSig | 0x00800000 )<<7;
+    bSig = ( bSig | 0x00800000 )<<8;
+    shift64RightJamming( ( (bits64) aSig ) * bSig, 32, &zSig64 );
+    zSig = zSig64;
+    if ( 0 <= (sbits32) ( zSig<<1 ) ) {
+        zSig <<= 1;
+        --zExp;
+    }
+    return roundAndPackFloat32( zSign, zExp, zSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of dividing the single-precision floating-point value `a'
+by the corresponding value `b'.  The operation is performed according to the
+IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_div( float32 a, float32 b )
+{
+    flag aSign, bSign, zSign;
+    int16 aExp, bExp, zExp;
+    bits32 aSig, bSig, zSig;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    bSig = extractFloat32Frac( b );
+    bExp = extractFloat32Exp( b );
+    bSign = extractFloat32Sign( b );
+    zSign = aSign ^ bSign;
+    if ( aExp == 0xFF ) {
+        if ( aSig ) return propagateFloat32NaN( a, b );
+        if ( bExp == 0xFF ) {
+            if ( bSig ) return propagateFloat32NaN( a, b );
+            float_raise( float_flag_invalid );
+            return float32_default_nan;
+        }
+        return packFloat32( zSign, 0xFF, 0 );
+    }
+    if ( bExp == 0xFF ) {
+        if ( bSig ) return propagateFloat32NaN( a, b );
+        return packFloat32( zSign, 0, 0 );
+    }
+    if ( bExp == 0 ) {
+        if ( bSig == 0 ) {
+            if ( ( aExp | aSig ) == 0 ) {
+                float_raise( float_flag_invalid );
+                return float32_default_nan;
+            }
+            float_raise( float_flag_divbyzero );
+            return packFloat32( zSign, 0xFF, 0 );
+        }
+        normalizeFloat32Subnormal( bSig, &bExp, &bSig );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloat32( zSign, 0, 0 );
+        normalizeFloat32Subnormal( aSig, &aExp, &aSig );
+    }
+    zExp = aExp - bExp + 0x7D;
+    aSig = ( aSig | 0x00800000 )<<7;
+    bSig = ( bSig | 0x00800000 )<<8;
+    if ( bSig <= ( aSig + aSig ) ) {
+        aSig >>= 1;
+        ++zExp;
+    }
+    zSig = ( ( (bits64) aSig )<<32 ) / bSig;
+    if ( ( zSig & 0x3F ) == 0 ) {
+        zSig |= ( (bits64) bSig * zSig != ( (bits64) aSig )<<32 );
+    }
+    return roundAndPackFloat32( zSign, zExp, zSig );
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC /* Not needed */
+/*
+-------------------------------------------------------------------------------
+Returns the remainder of the single-precision floating-point value `a'
+with respect to the corresponding value `b'.  The operation is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_rem( float32 a, float32 b )
+{
+    flag aSign, bSign, zSign;
+    int16 aExp, bExp, expDiff;
+    bits32 aSig, bSig;
+    bits32 q;
+    bits64 aSig64, bSig64, q64;
+    bits32 alternateASig;
+    sbits32 sigMean;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    bSig = extractFloat32Frac( b );
+    bExp = extractFloat32Exp( b );
+    bSign = extractFloat32Sign( b );
+    if ( aExp == 0xFF ) {
+        if ( aSig || ( ( bExp == 0xFF ) && bSig ) ) {
+            return propagateFloat32NaN( a, b );
+        }
+        float_raise( float_flag_invalid );
+        return float32_default_nan;
+    }
+    if ( bExp == 0xFF ) {
+        if ( bSig ) return propagateFloat32NaN( a, b );
+        return a;
+    }
+    if ( bExp == 0 ) {
+        if ( bSig == 0 ) {
+            float_raise( float_flag_invalid );
+            return float32_default_nan;
+        }
+        normalizeFloat32Subnormal( bSig, &bExp, &bSig );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return a;
+        normalizeFloat32Subnormal( aSig, &aExp, &aSig );
+    }
+    expDiff = aExp - bExp;
+    aSig |= 0x00800000;
+    bSig |= 0x00800000;
+    if ( expDiff < 32 ) {
+        aSig <<= 8;
+        bSig <<= 8;
+        if ( expDiff < 0 ) {
+            if ( expDiff < -1 ) return a;
+            aSig >>= 1;
+        }
+        q = ( bSig <= aSig );
+        if ( q ) aSig -= bSig;
+        if ( 0 < expDiff ) {
+            q = ( ( (bits64) aSig )<<32 ) / bSig;
+            q >>= 32 - expDiff;
+            bSig >>= 2;
+            aSig = ( ( aSig>>1 )<<( expDiff - 1 ) ) - bSig * q;
+        }
+        else {
+            aSig >>= 2;
+            bSig >>= 2;
+        }
+    }
+    else {
+        if ( bSig <= aSig ) aSig -= bSig;
+        aSig64 = ( (bits64) aSig )<<40;
+        bSig64 = ( (bits64) bSig )<<40;
+        expDiff -= 64;
+        while ( 0 < expDiff ) {
+            q64 = estimateDiv128To64( aSig64, 0, bSig64 );
+            q64 = ( 2 < q64 ) ? q64 - 2 : 0;
+            aSig64 = - ( ( bSig * q64 )<<38 );
+            expDiff -= 62;
+        }
+        expDiff += 64;
+        q64 = estimateDiv128To64( aSig64, 0, bSig64 );
+        q64 = ( 2 < q64 ) ? q64 - 2 : 0;
+        q = q64>>( 64 - expDiff );
+        bSig <<= 6;
+        aSig = ( ( aSig64>>33 )<<( expDiff - 1 ) ) - bSig * q;
+    }
+    do {
+        alternateASig = aSig;
+        ++q;
+        aSig -= bSig;
+    } while ( 0 <= (sbits32) aSig );
+    sigMean = aSig + alternateASig;
+    if ( ( sigMean < 0 ) || ( ( sigMean == 0 ) && ( q & 1 ) ) ) {
+        aSig = alternateASig;
+    }
+    zSign = ( (sbits32) aSig < 0 );
+    if ( zSign ) aSig = - aSig;
+    return normalizeRoundAndPackFloat32( aSign ^ zSign, bExp, aSig );
+
+}
+#endif /* !SOFTFLOAT_FOR_GCC */
+
+#ifndef SOFTFLOAT_FOR_GCC /* Not needed */
+/*
+-------------------------------------------------------------------------------
+Returns the square root of the single-precision floating-point value `a'.
+The operation is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float32_sqrt( float32 a )
+{
+    flag aSign;
+    int16 aExp, zExp;
+    bits32 aSig, zSig;
+    bits64 rem, term;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    if ( aExp == 0xFF ) {
+        if ( aSig ) return propagateFloat32NaN( a, 0 );
+        if ( ! aSign ) return a;
+        float_raise( float_flag_invalid );
+        return float32_default_nan;
+    }
+    if ( aSign ) {
+        if ( ( aExp | aSig ) == 0 ) return a;
+        float_raise( float_flag_invalid );
+        return float32_default_nan;
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return 0;
+        normalizeFloat32Subnormal( aSig, &aExp, &aSig );
+    }
+    zExp = ( ( aExp - 0x7F )>>1 ) + 0x7E;
+    aSig = ( aSig | 0x00800000 )<<8;
+    zSig = estimateSqrt32( aExp, aSig ) + 2;
+    if ( ( zSig & 0x7F ) <= 5 ) {
+        if ( zSig < 2 ) {
+            zSig = 0x7FFFFFFF;
+            goto roundAndPack;
+        }
+        aSig >>= aExp & 1;
+        term = ( (bits64) zSig ) * zSig;
+        rem = ( ( (bits64) aSig )<<32 ) - term;
+        while ( (sbits64) rem < 0 ) {
+            --zSig;
+            rem += ( ( (bits64) zSig )<<1 ) | 1;
+        }
+        zSig |= ( rem != 0 );
+    }
+    shift32RightJamming( zSig, 1, &zSig );
+ roundAndPack:
+    return roundAndPackFloat32( 0, zExp, zSig );
+
+}
+#endif /* !SOFTFLOAT_FOR_GCC */
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is equal to
+the corresponding value `b', and 0 otherwise.  The comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float32_eq( float32 a, float32 b )
+{
+
+    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )
+         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )
+       ) {
+        if ( float32_is_signaling_nan( a ) || float32_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    return ( a == b ) || ( (bits32) ( ( a | b )<<1 ) == 0 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is less than
+or equal to the corresponding value `b', and 0 otherwise.  The comparison
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float32_le( float32 a, float32 b )
+{
+    flag aSign, bSign;
+
+    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )
+         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    aSign = extractFloat32Sign( a );
+    bSign = extractFloat32Sign( b );
+    if ( aSign != bSign ) return aSign || ( (bits32) ( ( a | b )<<1 ) == 0 );
+    return ( a == b ) || ( aSign ^ ( a < b ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is less than
+the corresponding value `b', and 0 otherwise.  The comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float32_lt( float32 a, float32 b )
+{
+    flag aSign, bSign;
+
+    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )
+         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    aSign = extractFloat32Sign( a );
+    bSign = extractFloat32Sign( b );
+    if ( aSign != bSign ) return aSign && ( (bits32) ( ( a | b )<<1 ) != 0 );
+    return ( a != b ) && ( aSign ^ ( a < b ) );
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC /* Not needed */
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is equal to
+the corresponding value `b', and 0 otherwise.  The invalid exception is
+raised if either operand is a NaN.  Otherwise, the comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float32_eq_signaling( float32 a, float32 b )
+{
+
+    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )
+         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    return ( a == b ) || ( (bits32) ( ( a | b )<<1 ) == 0 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is less than or
+equal to the corresponding value `b', and 0 otherwise.  Quiet NaNs do not
+cause an exception.  Otherwise, the comparison is performed according to the
+IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float32_le_quiet( float32 a, float32 b )
+{
+    flag aSign, bSign;
+
+    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )
+         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )
+       ) {
+        if ( float32_is_signaling_nan( a ) || float32_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    aSign = extractFloat32Sign( a );
+    bSign = extractFloat32Sign( b );
+    if ( aSign != bSign ) return aSign || ( (bits32) ( ( a | b )<<1 ) == 0 );
+    return ( a == b ) || ( aSign ^ ( a < b ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is less than
+the corresponding value `b', and 0 otherwise.  Quiet NaNs do not cause an
+exception.  Otherwise, the comparison is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float32_lt_quiet( float32 a, float32 b )
+{
+    flag aSign, bSign;
+
+    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )
+         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )
+       ) {
+        if ( float32_is_signaling_nan( a ) || float32_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    aSign = extractFloat32Sign( a );
+    bSign = extractFloat32Sign( b );
+    if ( aSign != bSign ) return aSign && ( (bits32) ( ( a | b )<<1 ) != 0 );
+    return ( a != b ) && ( aSign ^ ( a < b ) );
+
+}
+#endif /* !SOFTFLOAT_FOR_GCC */
+
+#ifndef SOFTFLOAT_FOR_GCC /* Not needed */
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the double-precision floating-point value
+`a' to the 32-bit two's complement integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic---which means in particular that the conversion is rounded
+according to the current rounding mode.  If `a' is a NaN, the largest
+positive integer is returned.  Otherwise, if the conversion overflows, the
+largest integer with the same sign as `a' is returned.
+-------------------------------------------------------------------------------
+*/
+int32 float64_to_int32( float64 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits64 aSig;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    if ( ( aExp == 0x7FF ) && aSig ) aSign = 0;
+    if ( aExp ) aSig |= LIT64( 0x0010000000000000 );
+    shiftCount = 0x42C - aExp;
+    if ( 0 < shiftCount ) shift64RightJamming( aSig, shiftCount, &aSig );
+    return roundAndPackInt32( aSign, aSig );
+
+}
+#endif /* !SOFTFLOAT_FOR_GCC */
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the double-precision floating-point value
+`a' to the 32-bit two's complement integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic, except that the conversion is always rounded toward zero.
+If `a' is a NaN, the largest positive integer is returned.  Otherwise, if
+the conversion overflows, the largest integer with the same sign as `a' is
+returned.
+-------------------------------------------------------------------------------
+*/
+int32 float64_to_int32_round_to_zero( float64 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits64 aSig, savedASig;
+    int32 z;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    if ( 0x41E < aExp ) {
+        if ( ( aExp == 0x7FF ) && aSig ) aSign = 0;
+        goto invalid;
+    }
+    else if ( aExp < 0x3FF ) {
+        if ( aExp || aSig ) float_exception_flags |= float_flag_inexact;
+        return 0;
+    }
+    aSig |= LIT64( 0x0010000000000000 );
+    shiftCount = 0x433 - aExp;
+    savedASig = aSig;
+    aSig >>= shiftCount;
+    z = aSig;
+    if ( aSign ) z = - z;
+    if ( ( z < 0 ) ^ aSign ) {
+ invalid:
+        float_raise( float_flag_invalid );
+        return aSign ? (sbits32) 0x80000000 : 0x7FFFFFFF;
+    }
+    if ( ( aSig<<shiftCount ) != savedASig ) {
+        float_exception_flags |= float_flag_inexact;
+    }
+    return z;
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC /* Not needed */
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the double-precision floating-point value
+`a' to the 64-bit two's complement integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic---which means in particular that the conversion is rounded
+according to the current rounding mode.  If `a' is a NaN, the largest
+positive integer is returned.  Otherwise, if the conversion overflows, the
+largest integer with the same sign as `a' is returned.
+-------------------------------------------------------------------------------
+*/
+int64 float64_to_int64( float64 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits64 aSig, aSigExtra;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    if ( aExp ) aSig |= LIT64( 0x0010000000000000 );
+    shiftCount = 0x433 - aExp;
+    if ( shiftCount <= 0 ) {
+        if ( 0x43E < aExp ) {
+            float_raise( float_flag_invalid );
+            if (    ! aSign
+                 || (    ( aExp == 0x7FF )
+                      && ( aSig != LIT64( 0x0010000000000000 ) ) )
+               ) {
+                return LIT64( 0x7FFFFFFFFFFFFFFF );
+            }
+            return (sbits64) LIT64( 0x8000000000000000 );
+        }
+        aSigExtra = 0;
+        aSig <<= - shiftCount;
+    }
+    else {
+        shift64ExtraRightJamming( aSig, 0, shiftCount, &aSig, &aSigExtra );
+    }
+    return roundAndPackInt64( aSign, aSig, aSigExtra );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the double-precision floating-point value
+`a' to the 64-bit two's complement integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic, except that the conversion is always rounded toward zero.
+If `a' is a NaN, the largest positive integer is returned.  Otherwise, if
+the conversion overflows, the largest integer with the same sign as `a' is
+returned.
+-------------------------------------------------------------------------------
+*/
+int64 float64_to_int64_round_to_zero( float64 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits64 aSig;
+    int64 z;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    if ( aExp ) aSig |= LIT64( 0x0010000000000000 );
+    shiftCount = aExp - 0x433;
+    if ( 0 <= shiftCount ) {
+        if ( 0x43E <= aExp ) {
+            if ( a != LIT64( 0xC3E0000000000000 ) ) {
+                float_raise( float_flag_invalid );
+                if (    ! aSign
+                     || (    ( aExp == 0x7FF )
+                          && ( aSig != LIT64( 0x0010000000000000 ) ) )
+                   ) {
+                    return LIT64( 0x7FFFFFFFFFFFFFFF );
+                }
+            }
+            return (sbits64) LIT64( 0x8000000000000000 );
+        }
+        z = aSig<<shiftCount;
+    }
+    else {
+        if ( aExp < 0x3FE ) {
+            if ( aExp | aSig ) float_exception_flags |= float_flag_inexact;
+            return 0;
+        }
+        z = aSig>>( - shiftCount );
+        if ( (bits64) ( aSig<<( shiftCount & 63 ) ) ) {
+            float_exception_flags |= float_flag_inexact;
+        }
+    }
+    if ( aSign ) z = - z;
+    return z;
+
+}
+#endif /* !SOFTFLOAT_FOR_GCC */
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the double-precision floating-point value
+`a' to the single-precision floating-point format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float64_to_float32( float64 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits64 aSig;
+    bits32 zSig;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    if ( aExp == 0x7FF ) {
+        if ( aSig ) return commonNaNToFloat32( float64ToCommonNaN( a ) );
+        return packFloat32( aSign, 0xFF, 0 );
+    }
+    shift64RightJamming( aSig, 22, &aSig );
+    zSig = aSig;
+    if ( aExp || zSig ) {
+        zSig |= 0x40000000;
+        aExp -= 0x381;
+    }
+    return roundAndPackFloat32( aSign, aExp, zSig );
+
+}
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the double-precision floating-point value
+`a' to the extended double-precision floating-point format.  The conversion
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+floatx80 float64_to_floatx80( float64 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits64 aSig;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    if ( aExp == 0x7FF ) {
+        if ( aSig ) return commonNaNToFloatx80( float64ToCommonNaN( a ) );
+        return packFloatx80( aSign, 0x7FFF, LIT64( 0x8000000000000000 ) );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloatx80( aSign, 0, 0 );
+        normalizeFloat64Subnormal( aSig, &aExp, &aSig );
+    }
+    return
+        packFloatx80(
+            aSign, aExp + 0x3C00, ( aSig | LIT64( 0x0010000000000000 ) )<<11 );
+
+}
+
+#endif
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the double-precision floating-point value
+`a' to the quadruple-precision floating-point format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float128 float64_to_float128( float64 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits64 aSig, zSig0, zSig1;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    if ( aExp == 0x7FF ) {
+        if ( aSig ) return commonNaNToFloat128( float64ToCommonNaN( a ) );
+        return packFloat128( aSign, 0x7FFF, 0, 0 );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloat128( aSign, 0, 0, 0 );
+        normalizeFloat64Subnormal( aSig, &aExp, &aSig );
+        --aExp;
+    }
+    shift128Right( aSig, 0, 4, &zSig0, &zSig1 );
+    return packFloat128( aSign, aExp + 0x3C00, zSig0, zSig1 );
+
+}
+
+#endif
+
+#ifndef SOFTFLOAT_FOR_GCC
+/*
+-------------------------------------------------------------------------------
+Rounds the double-precision floating-point value `a' to an integer, and
+returns the result as a double-precision floating-point value.  The
+operation is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_round_to_int( float64 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits64 lastBitMask, roundBitsMask;
+    int8 roundingMode;
+    float64 z;
+
+    aExp = extractFloat64Exp( a );
+    if ( 0x433 <= aExp ) {
+        if ( ( aExp == 0x7FF ) && extractFloat64Frac( a ) ) {
+            return propagateFloat64NaN( a, a );
+        }
+        return a;
+    }
+    if ( aExp < 0x3FF ) {
+        if ( (bits64) ( a<<1 ) == 0 ) return a;
+        float_exception_flags |= float_flag_inexact;
+        aSign = extractFloat64Sign( a );
+        switch ( float_rounding_mode ) {
+         case float_round_nearest_even:
+            if ( ( aExp == 0x3FE ) && extractFloat64Frac( a ) ) {
+                return packFloat64( aSign, 0x3FF, 0 );
+            }
+            break;
+        case float_round_to_zero:
+           break;
+         case float_round_down:
+            return aSign ? LIT64( 0xBFF0000000000000 ) : 0;
+         case float_round_up:
+            return
+            aSign ? LIT64( 0x8000000000000000 ) : LIT64( 0x3FF0000000000000 );
+        }
+        return packFloat64( aSign, 0, 0 );
+    }
+    lastBitMask = 1;
+    lastBitMask <<= 0x433 - aExp;
+    roundBitsMask = lastBitMask - 1;
+    z = a;
+    roundingMode = float_rounding_mode;
+    if ( roundingMode == float_round_nearest_even ) {
+        z += lastBitMask>>1;
+        if ( ( z & roundBitsMask ) == 0 ) z &= ~ lastBitMask;
+    }
+    else if ( roundingMode != float_round_to_zero ) {
+        if ( extractFloat64Sign( z ) ^ ( roundingMode == float_round_up ) ) {
+            z += roundBitsMask;
+        }
+    }
+    z &= ~ roundBitsMask;
+    if ( z != a ) float_exception_flags |= float_flag_inexact;
+    return z;
+
+}
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of adding the absolute values of the double-precision
+floating-point values `a' and `b'.  If `zSign' is 1, the sum is negated
+before being returned.  `zSign' is ignored if the result is a NaN.
+The addition is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float64 addFloat64Sigs( float64 a, float64 b, flag zSign )
+{
+    int16 aExp, bExp, zExp;
+    bits64 aSig, bSig, zSig;
+    int16 expDiff;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    bSig = extractFloat64Frac( b );
+    bExp = extractFloat64Exp( b );
+    expDiff = aExp - bExp;
+    aSig <<= 9;
+    bSig <<= 9;
+    if ( 0 < expDiff ) {
+        if ( aExp == 0x7FF ) {
+            if ( aSig ) return propagateFloat64NaN( a, b );
+            return a;
+        }
+        if ( bExp == 0 ) {
+            --expDiff;
+        }
+        else {
+            bSig |= LIT64( 0x2000000000000000 );
+        }
+        shift64RightJamming( bSig, expDiff, &bSig );
+        zExp = aExp;
+    }
+    else if ( expDiff < 0 ) {
+        if ( bExp == 0x7FF ) {
+            if ( bSig ) return propagateFloat64NaN( a, b );
+            return packFloat64( zSign, 0x7FF, 0 );
+        }
+        if ( aExp == 0 ) {
+            ++expDiff;
+        }
+        else {
+            aSig |= LIT64( 0x2000000000000000 );
+        }
+        shift64RightJamming( aSig, - expDiff, &aSig );
+        zExp = bExp;
+    }
+    else {
+        if ( aExp == 0x7FF ) {
+            if ( aSig | bSig ) return propagateFloat64NaN( a, b );
+            return a;
+        }
+        if ( aExp == 0 ) return packFloat64( zSign, 0, ( aSig + bSig )>>9 );
+        zSig = LIT64( 0x4000000000000000 ) + aSig + bSig;
+        zExp = aExp;
+        goto roundAndPack;
+    }
+    aSig |= LIT64( 0x2000000000000000 );
+    zSig = ( aSig + bSig )<<1;
+    --zExp;
+    if ( (sbits64) zSig < 0 ) {
+        zSig = aSig + bSig;
+        ++zExp;
+    }
+ roundAndPack:
+    return roundAndPackFloat64( zSign, zExp, zSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of subtracting the absolute values of the double-
+precision floating-point values `a' and `b'.  If `zSign' is 1, the
+difference is negated before being returned.  `zSign' is ignored if the
+result is a NaN.  The subtraction is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float64 subFloat64Sigs( float64 a, float64 b, flag zSign )
+{
+    int16 aExp, bExp, zExp;
+    bits64 aSig, bSig, zSig;
+    int16 expDiff;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    bSig = extractFloat64Frac( b );
+    bExp = extractFloat64Exp( b );
+    expDiff = aExp - bExp;
+    aSig <<= 10;
+    bSig <<= 10;
+    if ( 0 < expDiff ) goto aExpBigger;
+    if ( expDiff < 0 ) goto bExpBigger;
+    if ( aExp == 0x7FF ) {
+        if ( aSig | bSig ) return propagateFloat64NaN( a, b );
+        float_raise( float_flag_invalid );
+        return float64_default_nan;
+    }
+    if ( aExp == 0 ) {
+        aExp = 1;
+        bExp = 1;
+    }
+    if ( bSig < aSig ) goto aBigger;
+    if ( aSig < bSig ) goto bBigger;
+    return packFloat64( float_rounding_mode == float_round_down, 0, 0 );
+ bExpBigger:
+    if ( bExp == 0x7FF ) {
+        if ( bSig ) return propagateFloat64NaN( a, b );
+        return packFloat64( zSign ^ 1, 0x7FF, 0 );
+    }
+    if ( aExp == 0 ) {
+        ++expDiff;
+    }
+    else {
+        aSig |= LIT64( 0x4000000000000000 );
+    }
+    shift64RightJamming( aSig, - expDiff, &aSig );
+    bSig |= LIT64( 0x4000000000000000 );
+ bBigger:
+    zSig = bSig - aSig;
+    zExp = bExp;
+    zSign ^= 1;
+    goto normalizeRoundAndPack;
+ aExpBigger:
+    if ( aExp == 0x7FF ) {
+        if ( aSig ) return propagateFloat64NaN( a, b );
+        return a;
+    }
+    if ( bExp == 0 ) {
+        --expDiff;
+    }
+    else {
+        bSig |= LIT64( 0x4000000000000000 );
+    }
+    shift64RightJamming( bSig, expDiff, &bSig );
+    aSig |= LIT64( 0x4000000000000000 );
+ aBigger:
+    zSig = aSig - bSig;
+    zExp = aExp;
+ normalizeRoundAndPack:
+    --zExp;
+    return normalizeRoundAndPackFloat64( zSign, zExp, zSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of adding the double-precision floating-point values `a'
+and `b'.  The operation is performed according to the IEC/IEEE Standard for
+Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_add( float64 a, float64 b )
+{
+    flag aSign, bSign;
+
+    aSign = extractFloat64Sign( a );
+    bSign = extractFloat64Sign( b );
+    if ( aSign == bSign ) {
+        return addFloat64Sigs( a, b, aSign );
+    }
+    else {
+        return subFloat64Sigs( a, b, aSign );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of subtracting the double-precision floating-point values
+`a' and `b'.  The operation is performed according to the IEC/IEEE Standard
+for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_sub( float64 a, float64 b )
+{
+    flag aSign, bSign;
+
+    aSign = extractFloat64Sign( a );
+    bSign = extractFloat64Sign( b );
+    if ( aSign == bSign ) {
+        return subFloat64Sigs( a, b, aSign );
+    }
+    else {
+        return addFloat64Sigs( a, b, aSign );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of multiplying the double-precision floating-point values
+`a' and `b'.  The operation is performed according to the IEC/IEEE Standard
+for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_mul( float64 a, float64 b )
+{
+    flag aSign, bSign, zSign;
+    int16 aExp, bExp, zExp;
+    bits64 aSig, bSig, zSig0, zSig1;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    bSig = extractFloat64Frac( b );
+    bExp = extractFloat64Exp( b );
+    bSign = extractFloat64Sign( b );
+    zSign = aSign ^ bSign;
+    if ( aExp == 0x7FF ) {
+        if ( aSig || ( ( bExp == 0x7FF ) && bSig ) ) {
+            return propagateFloat64NaN( a, b );
+        }
+        if ( ( bExp | bSig ) == 0 ) {
+            float_raise( float_flag_invalid );
+            return float64_default_nan;
+        }
+        return packFloat64( zSign, 0x7FF, 0 );
+    }
+    if ( bExp == 0x7FF ) {
+        if ( bSig ) return propagateFloat64NaN( a, b );
+        if ( ( aExp | aSig ) == 0 ) {
+            float_raise( float_flag_invalid );
+            return float64_default_nan;
+        }
+        return packFloat64( zSign, 0x7FF, 0 );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloat64( zSign, 0, 0 );
+        normalizeFloat64Subnormal( aSig, &aExp, &aSig );
+    }
+    if ( bExp == 0 ) {
+        if ( bSig == 0 ) return packFloat64( zSign, 0, 0 );
+        normalizeFloat64Subnormal( bSig, &bExp, &bSig );
+    }
+    zExp = aExp + bExp - 0x3FF;
+    aSig = ( aSig | LIT64( 0x0010000000000000 ) )<<10;
+    bSig = ( bSig | LIT64( 0x0010000000000000 ) )<<11;
+    mul64To128( aSig, bSig, &zSig0, &zSig1 );
+    zSig0 |= ( zSig1 != 0 );
+    if ( 0 <= (sbits64) ( zSig0<<1 ) ) {
+        zSig0 <<= 1;
+        --zExp;
+    }
+    return roundAndPackFloat64( zSign, zExp, zSig0 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of dividing the double-precision floating-point value `a'
+by the corresponding value `b'.  The operation is performed according to
+the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_div( float64 a, float64 b )
+{
+    flag aSign, bSign, zSign;
+    int16 aExp, bExp, zExp;
+    bits64 aSig, bSig, zSig;
+    bits64 rem0, rem1;
+    bits64 term0, term1;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    bSig = extractFloat64Frac( b );
+    bExp = extractFloat64Exp( b );
+    bSign = extractFloat64Sign( b );
+    zSign = aSign ^ bSign;
+    if ( aExp == 0x7FF ) {
+        if ( aSig ) return propagateFloat64NaN( a, b );
+        if ( bExp == 0x7FF ) {
+            if ( bSig ) return propagateFloat64NaN( a, b );
+            float_raise( float_flag_invalid );
+            return float64_default_nan;
+        }
+        return packFloat64( zSign, 0x7FF, 0 );
+    }
+    if ( bExp == 0x7FF ) {
+        if ( bSig ) return propagateFloat64NaN( a, b );
+        return packFloat64( zSign, 0, 0 );
+    }
+    if ( bExp == 0 ) {
+        if ( bSig == 0 ) {
+            if ( ( aExp | aSig ) == 0 ) {
+                float_raise( float_flag_invalid );
+                return float64_default_nan;
+            }
+            float_raise( float_flag_divbyzero );
+            return packFloat64( zSign, 0x7FF, 0 );
+        }
+        normalizeFloat64Subnormal( bSig, &bExp, &bSig );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloat64( zSign, 0, 0 );
+        normalizeFloat64Subnormal( aSig, &aExp, &aSig );
+    }
+    zExp = aExp - bExp + 0x3FD;
+    aSig = ( aSig | LIT64( 0x0010000000000000 ) )<<10;
+    bSig = ( bSig | LIT64( 0x0010000000000000 ) )<<11;
+    if ( bSig <= ( aSig + aSig ) ) {
+        aSig >>= 1;
+        ++zExp;
+    }
+    zSig = estimateDiv128To64( aSig, 0, bSig );
+    if ( ( zSig & 0x1FF ) <= 2 ) {
+        mul64To128( bSig, zSig, &term0, &term1 );
+        sub128( aSig, 0, term0, term1, &rem0, &rem1 );
+        while ( (sbits64) rem0 < 0 ) {
+            --zSig;
+            add128( rem0, rem1, 0, bSig, &rem0, &rem1 );
+        }
+        zSig |= ( rem1 != 0 );
+    }
+    return roundAndPackFloat64( zSign, zExp, zSig );
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC
+/*
+-------------------------------------------------------------------------------
+Returns the remainder of the double-precision floating-point value `a'
+with respect to the corresponding value `b'.  The operation is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_rem( float64 a, float64 b )
+{
+    flag aSign, bSign, zSign;
+    int16 aExp, bExp, expDiff;
+    bits64 aSig, bSig;
+    bits64 q, alternateASig;
+    sbits64 sigMean;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    bSig = extractFloat64Frac( b );
+    bExp = extractFloat64Exp( b );
+    bSign = extractFloat64Sign( b );
+    if ( aExp == 0x7FF ) {
+        if ( aSig || ( ( bExp == 0x7FF ) && bSig ) ) {
+            return propagateFloat64NaN( a, b );
+        }
+        float_raise( float_flag_invalid );
+        return float64_default_nan;
+    }
+    if ( bExp == 0x7FF ) {
+        if ( bSig ) return propagateFloat64NaN( a, b );
+        return a;
+    }
+    if ( bExp == 0 ) {
+        if ( bSig == 0 ) {
+            float_raise( float_flag_invalid );
+            return float64_default_nan;
+        }
+        normalizeFloat64Subnormal( bSig, &bExp, &bSig );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return a;
+        normalizeFloat64Subnormal( aSig, &aExp, &aSig );
+    }
+    expDiff = aExp - bExp;
+    aSig = ( aSig | LIT64( 0x0010000000000000 ) )<<11;
+    bSig = ( bSig | LIT64( 0x0010000000000000 ) )<<11;
+    if ( expDiff < 0 ) {
+        if ( expDiff < -1 ) return a;
+        aSig >>= 1;
+    }
+    q = ( bSig <= aSig );
+    if ( q ) aSig -= bSig;
+    expDiff -= 64;
+    while ( 0 < expDiff ) {
+        q = estimateDiv128To64( aSig, 0, bSig );
+        q = ( 2 < q ) ? q - 2 : 0;
+        aSig = - ( ( bSig>>2 ) * q );
+        expDiff -= 62;
+    }
+    expDiff += 64;
+    if ( 0 < expDiff ) {
+        q = estimateDiv128To64( aSig, 0, bSig );
+        q = ( 2 < q ) ? q - 2 : 0;
+        q >>= 64 - expDiff;
+        bSig >>= 2;
+        aSig = ( ( aSig>>1 )<<( expDiff - 1 ) ) - bSig * q;
+    }
+    else {
+        aSig >>= 2;
+        bSig >>= 2;
+    }
+    do {
+        alternateASig = aSig;
+        ++q;
+        aSig -= bSig;
+    } while ( 0 <= (sbits64) aSig );
+    sigMean = aSig + alternateASig;
+    if ( ( sigMean < 0 ) || ( ( sigMean == 0 ) && ( q & 1 ) ) ) {
+        aSig = alternateASig;
+    }
+    zSign = ( (sbits64) aSig < 0 );
+    if ( zSign ) aSig = - aSig;
+    return normalizeRoundAndPackFloat64( aSign ^ zSign, bExp, aSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the square root of the double-precision floating-point value `a'.
+The operation is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float64_sqrt( float64 a )
+{
+    flag aSign;
+    int16 aExp, zExp;
+    bits64 aSig, zSig, doubleZSig;
+    bits64 rem0, rem1, term0, term1;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+    if ( aExp == 0x7FF ) {
+        if ( aSig ) return propagateFloat64NaN( a, a );
+        if ( ! aSign ) return a;
+        float_raise( float_flag_invalid );
+        return float64_default_nan;
+    }
+    if ( aSign ) {
+        if ( ( aExp | aSig ) == 0 ) return a;
+        float_raise( float_flag_invalid );
+        return float64_default_nan;
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return 0;
+        normalizeFloat64Subnormal( aSig, &aExp, &aSig );
+    }
+    zExp = ( ( aExp - 0x3FF )>>1 ) + 0x3FE;
+    aSig |= LIT64( 0x0010000000000000 );
+    zSig = estimateSqrt32( aExp, aSig>>21 );
+    aSig <<= 9 - ( aExp & 1 );
+    zSig = estimateDiv128To64( aSig, 0, zSig<<32 ) + ( zSig<<30 );
+    if ( ( zSig & 0x1FF ) <= 5 ) {
+        doubleZSig = zSig<<1;
+        mul64To128( zSig, zSig, &term0, &term1 );
+        sub128( aSig, 0, term0, term1, &rem0, &rem1 );
+        while ( (sbits64) rem0 < 0 ) {
+            --zSig;
+            doubleZSig -= 2;
+            add128( rem0, rem1, zSig>>63, doubleZSig | 1, &rem0, &rem1 );
+        }
+        zSig |= ( ( rem0 | rem1 ) != 0 );
+    }
+    return roundAndPackFloat64( 0, zExp, zSig );
+
+}
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is equal to the
+corresponding value `b', and 0 otherwise.  The comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float64_eq( float64 a, float64 b )
+{
+
+    if (    ( ( extractFloat64Exp( a ) == 0x7FF ) && extractFloat64Frac( a ) )
+         || ( ( extractFloat64Exp( b ) == 0x7FF ) && extractFloat64Frac( b ) )
+       ) {
+        if ( float64_is_signaling_nan( a ) || float64_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    return ( a == b ) ||
+       ( (bits64) ( ( FLOAT64_DEMANGLE(a) | FLOAT64_DEMANGLE(b) )<<1 ) == 0 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is less than or
+equal to the corresponding value `b', and 0 otherwise.  The comparison is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float64_le( float64 a, float64 b )
+{
+    flag aSign, bSign;
+
+    if (    ( ( extractFloat64Exp( a ) == 0x7FF ) && extractFloat64Frac( a ) )
+         || ( ( extractFloat64Exp( b ) == 0x7FF ) && extractFloat64Frac( b ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    aSign = extractFloat64Sign( a );
+    bSign = extractFloat64Sign( b );
+    if ( aSign != bSign )
+       return aSign ||
+           ( (bits64) ( ( FLOAT64_DEMANGLE(a) | FLOAT64_DEMANGLE(b) )<<1 ) ==
+             0 );
+    return ( a == b ) ||
+       ( aSign ^ ( FLOAT64_DEMANGLE(a) < FLOAT64_DEMANGLE(b) ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is less than
+the corresponding value `b', and 0 otherwise.  The comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float64_lt( float64 a, float64 b )
+{
+    flag aSign, bSign;
+
+    if (    ( ( extractFloat64Exp( a ) == 0x7FF ) && extractFloat64Frac( a ) )
+         || ( ( extractFloat64Exp( b ) == 0x7FF ) && extractFloat64Frac( b ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    aSign = extractFloat64Sign( a );
+    bSign = extractFloat64Sign( b );
+    if ( aSign != bSign )
+       return aSign &&
+           ( (bits64) ( ( FLOAT64_DEMANGLE(a) | FLOAT64_DEMANGLE(b) )<<1 ) !=
+             0 );
+    return ( a != b ) &&
+       ( aSign ^ ( FLOAT64_DEMANGLE(a) < FLOAT64_DEMANGLE(b) ) );
+
+}
+
+#ifndef SOFTFLOAT_FOR_GCC
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is equal to the
+corresponding value `b', and 0 otherwise.  The invalid exception is raised
+if either operand is a NaN.  Otherwise, the comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float64_eq_signaling( float64 a, float64 b )
+{
+
+    if (    ( ( extractFloat64Exp( a ) == 0x7FF ) && extractFloat64Frac( a ) )
+         || ( ( extractFloat64Exp( b ) == 0x7FF ) && extractFloat64Frac( b ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    return ( a == b ) || ( (bits64) ( ( a | b )<<1 ) == 0 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is less than or
+equal to the corresponding value `b', and 0 otherwise.  Quiet NaNs do not
+cause an exception.  Otherwise, the comparison is performed according to the
+IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float64_le_quiet( float64 a, float64 b )
+{
+    flag aSign, bSign;
+
+    if (    ( ( extractFloat64Exp( a ) == 0x7FF ) && extractFloat64Frac( a ) )
+         || ( ( extractFloat64Exp( b ) == 0x7FF ) && extractFloat64Frac( b ) )
+       ) {
+        if ( float64_is_signaling_nan( a ) || float64_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    aSign = extractFloat64Sign( a );
+    bSign = extractFloat64Sign( b );
+    if ( aSign != bSign ) return aSign || ( (bits64) ( ( a | b )<<1 ) == 0 );
+    return ( a == b ) || ( aSign ^ ( a < b ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is less than
+the corresponding value `b', and 0 otherwise.  Quiet NaNs do not cause an
+exception.  Otherwise, the comparison is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float64_lt_quiet( float64 a, float64 b )
+{
+    flag aSign, bSign;
+
+    if (    ( ( extractFloat64Exp( a ) == 0x7FF ) && extractFloat64Frac( a ) )
+         || ( ( extractFloat64Exp( b ) == 0x7FF ) && extractFloat64Frac( b ) )
+       ) {
+        if ( float64_is_signaling_nan( a ) || float64_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    aSign = extractFloat64Sign( a );
+    bSign = extractFloat64Sign( b );
+    if ( aSign != bSign ) return aSign && ( (bits64) ( ( a | b )<<1 ) != 0 );
+    return ( a != b ) && ( aSign ^ ( a < b ) );
+
+}
+#endif
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the extended double-precision floating-
+point value `a' to the 32-bit two's complement integer format.  The
+conversion is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic---which means in particular that the conversion
+is rounded according to the current rounding mode.  If `a' is a NaN, the
+largest positive integer is returned.  Otherwise, if the conversion
+overflows, the largest integer with the same sign as `a' is returned.
+-------------------------------------------------------------------------------
+*/
+int32 floatx80_to_int32( floatx80 a )
+{
+    flag aSign;
+    int32 aExp, shiftCount;
+    bits64 aSig;
+
+    aSig = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    aSign = extractFloatx80Sign( a );
+    if ( ( aExp == 0x7FFF ) && (bits64) ( aSig<<1 ) ) aSign = 0;
+    shiftCount = 0x4037 - aExp;
+    if ( shiftCount <= 0 ) shiftCount = 1;
+    shift64RightJamming( aSig, shiftCount, &aSig );
+    return roundAndPackInt32( aSign, aSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the extended double-precision floating-
+point value `a' to the 32-bit two's complement integer format.  The
+conversion is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic, except that the conversion is always rounded
+toward zero.  If `a' is a NaN, the largest positive integer is returned.
+Otherwise, if the conversion overflows, the largest integer with the same
+sign as `a' is returned.
+-------------------------------------------------------------------------------
+*/
+int32 floatx80_to_int32_round_to_zero( floatx80 a )
+{
+    flag aSign;
+    int32 aExp, shiftCount;
+    bits64 aSig, savedASig;
+    int32 z;
+
+    aSig = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    aSign = extractFloatx80Sign( a );
+    if ( 0x401E < aExp ) {
+        if ( ( aExp == 0x7FFF ) && (bits64) ( aSig<<1 ) ) aSign = 0;
+        goto invalid;
+    }
+    else if ( aExp < 0x3FFF ) {
+        if ( aExp || aSig ) float_exception_flags |= float_flag_inexact;
+        return 0;
+    }
+    shiftCount = 0x403E - aExp;
+    savedASig = aSig;
+    aSig >>= shiftCount;
+    z = aSig;
+    if ( aSign ) z = - z;
+    if ( ( z < 0 ) ^ aSign ) {
+ invalid:
+        float_raise( float_flag_invalid );
+        return aSign ? (sbits32) 0x80000000 : 0x7FFFFFFF;
+    }
+    if ( ( aSig<<shiftCount ) != savedASig ) {
+        float_exception_flags |= float_flag_inexact;
+    }
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the extended double-precision floating-
+point value `a' to the 64-bit two's complement integer format.  The
+conversion is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic---which means in particular that the conversion
+is rounded according to the current rounding mode.  If `a' is a NaN,
+the largest positive integer is returned.  Otherwise, if the conversion
+overflows, the largest integer with the same sign as `a' is returned.
+-------------------------------------------------------------------------------
+*/
+int64 floatx80_to_int64( floatx80 a )
+{
+    flag aSign;
+    int32 aExp, shiftCount;
+    bits64 aSig, aSigExtra;
+
+    aSig = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    aSign = extractFloatx80Sign( a );
+    shiftCount = 0x403E - aExp;
+    if ( shiftCount <= 0 ) {
+        if ( shiftCount ) {
+            float_raise( float_flag_invalid );
+            if (    ! aSign
+                 || (    ( aExp == 0x7FFF )
+                      && ( aSig != LIT64( 0x8000000000000000 ) ) )
+               ) {
+                return LIT64( 0x7FFFFFFFFFFFFFFF );
+            }
+            return (sbits64) LIT64( 0x8000000000000000 );
+        }
+        aSigExtra = 0;
+    }
+    else {
+        shift64ExtraRightJamming( aSig, 0, shiftCount, &aSig, &aSigExtra );
+    }
+    return roundAndPackInt64( aSign, aSig, aSigExtra );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the extended double-precision floating-
+point value `a' to the 64-bit two's complement integer format.  The
+conversion is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic, except that the conversion is always rounded
+toward zero.  If `a' is a NaN, the largest positive integer is returned.
+Otherwise, if the conversion overflows, the largest integer with the same
+sign as `a' is returned.
+-------------------------------------------------------------------------------
+*/
+int64 floatx80_to_int64_round_to_zero( floatx80 a )
+{
+    flag aSign;
+    int32 aExp, shiftCount;
+    bits64 aSig;
+    int64 z;
+
+    aSig = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    aSign = extractFloatx80Sign( a );
+    shiftCount = aExp - 0x403E;
+    if ( 0 <= shiftCount ) {
+        aSig &= LIT64( 0x7FFFFFFFFFFFFFFF );
+        if ( ( a.high != 0xC03E ) || aSig ) {
+            float_raise( float_flag_invalid );
+            if ( ! aSign || ( ( aExp == 0x7FFF ) && aSig ) ) {
+                return LIT64( 0x7FFFFFFFFFFFFFFF );
+            }
+        }
+        return (sbits64) LIT64( 0x8000000000000000 );
+    }
+    else if ( aExp < 0x3FFF ) {
+        if ( aExp | aSig ) float_exception_flags |= float_flag_inexact;
+        return 0;
+    }
+    z = aSig>>( - shiftCount );
+    if ( (bits64) ( aSig<<( shiftCount & 63 ) ) ) {
+        float_exception_flags |= float_flag_inexact;
+    }
+    if ( aSign ) z = - z;
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the extended double-precision floating-
+point value `a' to the single-precision floating-point format.  The
+conversion is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 floatx80_to_float32( floatx80 a )
+{
+    flag aSign;
+    int32 aExp;
+    bits64 aSig;
+
+    aSig = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    aSign = extractFloatx80Sign( a );
+    if ( aExp == 0x7FFF ) {
+        if ( (bits64) ( aSig<<1 ) ) {
+            return commonNaNToFloat32( floatx80ToCommonNaN( a ) );
+        }
+        return packFloat32( aSign, 0xFF, 0 );
+    }
+    shift64RightJamming( aSig, 33, &aSig );
+    if ( aExp || aSig ) aExp -= 0x3F81;
+    return roundAndPackFloat32( aSign, aExp, aSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the extended double-precision floating-
+point value `a' to the double-precision floating-point format.  The
+conversion is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 floatx80_to_float64( floatx80 a )
+{
+    flag aSign;
+    int32 aExp;
+    bits64 aSig, zSig;
+
+    aSig = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    aSign = extractFloatx80Sign( a );
+    if ( aExp == 0x7FFF ) {
+        if ( (bits64) ( aSig<<1 ) ) {
+            return commonNaNToFloat64( floatx80ToCommonNaN( a ) );
+        }
+        return packFloat64( aSign, 0x7FF, 0 );
+    }
+    shift64RightJamming( aSig, 1, &zSig );
+    if ( aExp || aSig ) aExp -= 0x3C01;
+    return roundAndPackFloat64( aSign, aExp, zSig );
+
+}
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the extended double-precision floating-
+point value `a' to the quadruple-precision floating-point format.  The
+conversion is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float128 floatx80_to_float128( floatx80 a )
+{
+    flag aSign;
+    int16 aExp;
+    bits64 aSig, zSig0, zSig1;
+
+    aSig = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    aSign = extractFloatx80Sign( a );
+    if ( ( aExp == 0x7FFF ) && (bits64) ( aSig<<1 ) ) {
+        return commonNaNToFloat128( floatx80ToCommonNaN( a ) );
+    }
+    shift128Right( aSig<<1, 0, 16, &zSig0, &zSig1 );
+    return packFloat128( aSign, aExp, zSig0, zSig1 );
+
+}
+
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Rounds the extended double-precision floating-point value `a' to an integer,
+and returns the result as an extended quadruple-precision floating-point
+value.  The operation is performed according to the IEC/IEEE Standard for
+Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_round_to_int( floatx80 a )
+{
+    flag aSign;
+    int32 aExp;
+    bits64 lastBitMask, roundBitsMask;
+    int8 roundingMode;
+    floatx80 z;
+
+    aExp = extractFloatx80Exp( a );
+    if ( 0x403E <= aExp ) {
+        if ( ( aExp == 0x7FFF ) && (bits64) ( extractFloatx80Frac( a )<<1 ) ) {
+            return propagateFloatx80NaN( a, a );
+        }
+        return a;
+    }
+    if ( aExp < 0x3FFF ) {
+        if (    ( aExp == 0 )
+             && ( (bits64) ( extractFloatx80Frac( a )<<1 ) == 0 ) ) {
+            return a;
+        }
+        float_exception_flags |= float_flag_inexact;
+        aSign = extractFloatx80Sign( a );
+        switch ( float_rounding_mode ) {
+         case float_round_nearest_even:
+            if ( ( aExp == 0x3FFE ) && (bits64) ( extractFloatx80Frac( a )<<1 )
+               ) {
+                return
+                    packFloatx80( aSign, 0x3FFF, LIT64( 0x8000000000000000 ) );
+            }
+            break;
+        case float_round_to_zero:
+           break;
+         case float_round_down:
+            return
+                  aSign ?
+                      packFloatx80( 1, 0x3FFF, LIT64( 0x8000000000000000 ) )
+                : packFloatx80( 0, 0, 0 );
+         case float_round_up:
+            return
+                  aSign ? packFloatx80( 1, 0, 0 )
+                : packFloatx80( 0, 0x3FFF, LIT64( 0x8000000000000000 ) );
+        }
+        return packFloatx80( aSign, 0, 0 );
+    }
+    lastBitMask = 1;
+    lastBitMask <<= 0x403E - aExp;
+    roundBitsMask = lastBitMask - 1;
+    z = a;
+    roundingMode = float_rounding_mode;
+    if ( roundingMode == float_round_nearest_even ) {
+        z.low += lastBitMask>>1;
+        if ( ( z.low & roundBitsMask ) == 0 ) z.low &= ~ lastBitMask;
+    }
+    else if ( roundingMode != float_round_to_zero ) {
+        if ( extractFloatx80Sign( z ) ^ ( roundingMode == float_round_up ) ) {
+            z.low += roundBitsMask;
+        }
+    }
+    z.low &= ~ roundBitsMask;
+    if ( z.low == 0 ) {
+        ++z.high;
+        z.low = LIT64( 0x8000000000000000 );
+    }
+    if ( z.low != a.low ) float_exception_flags |= float_flag_inexact;
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of adding the absolute values of the extended double-
+precision floating-point values `a' and `b'.  If `zSign' is 1, the sum is
+negated before being returned.  `zSign' is ignored if the result is a NaN.
+The addition is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static floatx80 addFloatx80Sigs( floatx80 a, floatx80 b, flag zSign )
+{
+    int32 aExp, bExp, zExp;
+    bits64 aSig, bSig, zSig0, zSig1;
+    int32 expDiff;
+
+    aSig = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    bSig = extractFloatx80Frac( b );
+    bExp = extractFloatx80Exp( b );
+    expDiff = aExp - bExp;
+    if ( 0 < expDiff ) {
+        if ( aExp == 0x7FFF ) {
+            if ( (bits64) ( aSig<<1 ) ) return propagateFloatx80NaN( a, b );
+            return a;
+        }
+        if ( bExp == 0 ) --expDiff;
+        shift64ExtraRightJamming( bSig, 0, expDiff, &bSig, &zSig1 );
+        zExp = aExp;
+    }
+    else if ( expDiff < 0 ) {
+        if ( bExp == 0x7FFF ) {
+            if ( (bits64) ( bSig<<1 ) ) return propagateFloatx80NaN( a, b );
+            return packFloatx80( zSign, 0x7FFF, LIT64( 0x8000000000000000 ) );
+        }
+        if ( aExp == 0 ) ++expDiff;
+        shift64ExtraRightJamming( aSig, 0, - expDiff, &aSig, &zSig1 );
+        zExp = bExp;
+    }
+    else {
+        if ( aExp == 0x7FFF ) {
+            if ( (bits64) ( ( aSig | bSig )<<1 ) ) {
+                return propagateFloatx80NaN( a, b );
+            }
+            return a;
+        }
+        zSig1 = 0;
+        zSig0 = aSig + bSig;
+        if ( aExp == 0 ) {
+            normalizeFloatx80Subnormal( zSig0, &zExp, &zSig0 );
+            goto roundAndPack;
+        }
+        zExp = aExp;
+        goto shiftRight1;
+    }
+    zSig0 = aSig + bSig;
+    if ( (sbits64) zSig0 < 0 ) goto roundAndPack;
+ shiftRight1:
+    shift64ExtraRightJamming( zSig0, zSig1, 1, &zSig0, &zSig1 );
+    zSig0 |= LIT64( 0x8000000000000000 );
+    ++zExp;
+ roundAndPack:
+    return
+        roundAndPackFloatx80(
+            floatx80_rounding_precision, zSign, zExp, zSig0, zSig1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of subtracting the absolute values of the extended
+double-precision floating-point values `a' and `b'.  If `zSign' is 1, the
+difference is negated before being returned.  `zSign' is ignored if the
+result is a NaN.  The subtraction is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static floatx80 subFloatx80Sigs( floatx80 a, floatx80 b, flag zSign )
+{
+    int32 aExp, bExp, zExp;
+    bits64 aSig, bSig, zSig0, zSig1;
+    int32 expDiff;
+    floatx80 z;
+
+    aSig = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    bSig = extractFloatx80Frac( b );
+    bExp = extractFloatx80Exp( b );
+    expDiff = aExp - bExp;
+    if ( 0 < expDiff ) goto aExpBigger;
+    if ( expDiff < 0 ) goto bExpBigger;
+    if ( aExp == 0x7FFF ) {
+        if ( (bits64) ( ( aSig | bSig )<<1 ) ) {
+            return propagateFloatx80NaN( a, b );
+        }
+        float_raise( float_flag_invalid );
+        z.low = floatx80_default_nan_low;
+        z.high = floatx80_default_nan_high;
+        return z;
+    }
+    if ( aExp == 0 ) {
+        aExp = 1;
+        bExp = 1;
+    }
+    zSig1 = 0;
+    if ( bSig < aSig ) goto aBigger;
+    if ( aSig < bSig ) goto bBigger;
+    return packFloatx80( float_rounding_mode == float_round_down, 0, 0 );
+ bExpBigger:
+    if ( bExp == 0x7FFF ) {
+        if ( (bits64) ( bSig<<1 ) ) return propagateFloatx80NaN( a, b );
+        return packFloatx80( zSign ^ 1, 0x7FFF, LIT64( 0x8000000000000000 ) );
+    }
+    if ( aExp == 0 ) ++expDiff;
+    shift128RightJamming( aSig, 0, - expDiff, &aSig, &zSig1 );
+ bBigger:
+    sub128( bSig, 0, aSig, zSig1, &zSig0, &zSig1 );
+    zExp = bExp;
+    zSign ^= 1;
+    goto normalizeRoundAndPack;
+ aExpBigger:
+    if ( aExp == 0x7FFF ) {
+        if ( (bits64) ( aSig<<1 ) ) return propagateFloatx80NaN( a, b );
+        return a;
+    }
+    if ( bExp == 0 ) --expDiff;
+    shift128RightJamming( bSig, 0, expDiff, &bSig, &zSig1 );
+ aBigger:
+    sub128( aSig, 0, bSig, zSig1, &zSig0, &zSig1 );
+    zExp = aExp;
+ normalizeRoundAndPack:
+    return
+        normalizeRoundAndPackFloatx80(
+            floatx80_rounding_precision, zSign, zExp, zSig0, zSig1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of adding the extended double-precision floating-point
+values `a' and `b'.  The operation is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_add( floatx80 a, floatx80 b )
+{
+    flag aSign, bSign;
+
+    aSign = extractFloatx80Sign( a );
+    bSign = extractFloatx80Sign( b );
+    if ( aSign == bSign ) {
+        return addFloatx80Sigs( a, b, aSign );
+    }
+    else {
+        return subFloatx80Sigs( a, b, aSign );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of subtracting the extended double-precision floating-
+point values `a' and `b'.  The operation is performed according to the
+IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_sub( floatx80 a, floatx80 b )
+{
+    flag aSign, bSign;
+
+    aSign = extractFloatx80Sign( a );
+    bSign = extractFloatx80Sign( b );
+    if ( aSign == bSign ) {
+        return subFloatx80Sigs( a, b, aSign );
+    }
+    else {
+        return addFloatx80Sigs( a, b, aSign );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of multiplying the extended double-precision floating-
+point values `a' and `b'.  The operation is performed according to the
+IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_mul( floatx80 a, floatx80 b )
+{
+    flag aSign, bSign, zSign;
+    int32 aExp, bExp, zExp;
+    bits64 aSig, bSig, zSig0, zSig1;
+    floatx80 z;
+
+    aSig = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    aSign = extractFloatx80Sign( a );
+    bSig = extractFloatx80Frac( b );
+    bExp = extractFloatx80Exp( b );
+    bSign = extractFloatx80Sign( b );
+    zSign = aSign ^ bSign;
+    if ( aExp == 0x7FFF ) {
+        if (    (bits64) ( aSig<<1 )
+             || ( ( bExp == 0x7FFF ) && (bits64) ( bSig<<1 ) ) ) {
+            return propagateFloatx80NaN( a, b );
+        }
+        if ( ( bExp | bSig ) == 0 ) goto invalid;
+        return packFloatx80( zSign, 0x7FFF, LIT64( 0x8000000000000000 ) );
+    }
+    if ( bExp == 0x7FFF ) {
+        if ( (bits64) ( bSig<<1 ) ) return propagateFloatx80NaN( a, b );
+        if ( ( aExp | aSig ) == 0 ) {
+ invalid:
+            float_raise( float_flag_invalid );
+            z.low = floatx80_default_nan_low;
+            z.high = floatx80_default_nan_high;
+            return z;
+        }
+        return packFloatx80( zSign, 0x7FFF, LIT64( 0x8000000000000000 ) );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloatx80( zSign, 0, 0 );
+        normalizeFloatx80Subnormal( aSig, &aExp, &aSig );
+    }
+    if ( bExp == 0 ) {
+        if ( bSig == 0 ) return packFloatx80( zSign, 0, 0 );
+        normalizeFloatx80Subnormal( bSig, &bExp, &bSig );
+    }
+    zExp = aExp + bExp - 0x3FFE;
+    mul64To128( aSig, bSig, &zSig0, &zSig1 );
+    if ( 0 < (sbits64) zSig0 ) {
+        shortShift128Left( zSig0, zSig1, 1, &zSig0, &zSig1 );
+        --zExp;
+    }
+    return
+        roundAndPackFloatx80(
+            floatx80_rounding_precision, zSign, zExp, zSig0, zSig1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of dividing the extended double-precision floating-point
+value `a' by the corresponding value `b'.  The operation is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_div( floatx80 a, floatx80 b )
+{
+    flag aSign, bSign, zSign;
+    int32 aExp, bExp, zExp;
+    bits64 aSig, bSig, zSig0, zSig1;
+    bits64 rem0, rem1, rem2, term0, term1, term2;
+    floatx80 z;
+
+    aSig = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    aSign = extractFloatx80Sign( a );
+    bSig = extractFloatx80Frac( b );
+    bExp = extractFloatx80Exp( b );
+    bSign = extractFloatx80Sign( b );
+    zSign = aSign ^ bSign;
+    if ( aExp == 0x7FFF ) {
+        if ( (bits64) ( aSig<<1 ) ) return propagateFloatx80NaN( a, b );
+        if ( bExp == 0x7FFF ) {
+            if ( (bits64) ( bSig<<1 ) ) return propagateFloatx80NaN( a, b );
+            goto invalid;
+        }
+        return packFloatx80( zSign, 0x7FFF, LIT64( 0x8000000000000000 ) );
+    }
+    if ( bExp == 0x7FFF ) {
+        if ( (bits64) ( bSig<<1 ) ) return propagateFloatx80NaN( a, b );
+        return packFloatx80( zSign, 0, 0 );
+    }
+    if ( bExp == 0 ) {
+        if ( bSig == 0 ) {
+            if ( ( aExp | aSig ) == 0 ) {
+ invalid:
+                float_raise( float_flag_invalid );
+                z.low = floatx80_default_nan_low;
+                z.high = floatx80_default_nan_high;
+                return z;
+            }
+            float_raise( float_flag_divbyzero );
+            return packFloatx80( zSign, 0x7FFF, LIT64( 0x8000000000000000 ) );
+        }
+        normalizeFloatx80Subnormal( bSig, &bExp, &bSig );
+    }
+    if ( aExp == 0 ) {
+        if ( aSig == 0 ) return packFloatx80( zSign, 0, 0 );
+        normalizeFloatx80Subnormal( aSig, &aExp, &aSig );
+    }
+    zExp = aExp - bExp + 0x3FFE;
+    rem1 = 0;
+    if ( bSig <= aSig ) {
+        shift128Right( aSig, 0, 1, &aSig, &rem1 );
+        ++zExp;
+    }
+    zSig0 = estimateDiv128To64( aSig, rem1, bSig );
+    mul64To128( bSig, zSig0, &term0, &term1 );
+    sub128( aSig, rem1, term0, term1, &rem0, &rem1 );
+    while ( (sbits64) rem0 < 0 ) {
+        --zSig0;
+        add128( rem0, rem1, 0, bSig, &rem0, &rem1 );
+    }
+    zSig1 = estimateDiv128To64( rem1, 0, bSig );
+    if ( (bits64) ( zSig1<<1 ) <= 8 ) {
+        mul64To128( bSig, zSig1, &term1, &term2 );
+        sub128( rem1, 0, term1, term2, &rem1, &rem2 );
+        while ( (sbits64) rem1 < 0 ) {
+            --zSig1;
+            add128( rem1, rem2, 0, bSig, &rem1, &rem2 );
+        }
+        zSig1 |= ( ( rem1 | rem2 ) != 0 );
+    }
+    return
+        roundAndPackFloatx80(
+            floatx80_rounding_precision, zSign, zExp, zSig0, zSig1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the remainder of the extended double-precision floating-point value
+`a' with respect to the corresponding value `b'.  The operation is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_rem( floatx80 a, floatx80 b )
+{
+    flag aSign, bSign, zSign;
+    int32 aExp, bExp, expDiff;
+    bits64 aSig0, aSig1, bSig;
+    bits64 q, term0, term1, alternateASig0, alternateASig1;
+    floatx80 z;
+
+    aSig0 = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    aSign = extractFloatx80Sign( a );
+    bSig = extractFloatx80Frac( b );
+    bExp = extractFloatx80Exp( b );
+    bSign = extractFloatx80Sign( b );
+    if ( aExp == 0x7FFF ) {
+        if (    (bits64) ( aSig0<<1 )
+             || ( ( bExp == 0x7FFF ) && (bits64) ( bSig<<1 ) ) ) {
+            return propagateFloatx80NaN( a, b );
+        }
+        goto invalid;
+    }
+    if ( bExp == 0x7FFF ) {
+        if ( (bits64) ( bSig<<1 ) ) return propagateFloatx80NaN( a, b );
+        return a;
+    }
+    if ( bExp == 0 ) {
+        if ( bSig == 0 ) {
+ invalid:
+            float_raise( float_flag_invalid );
+            z.low = floatx80_default_nan_low;
+            z.high = floatx80_default_nan_high;
+            return z;
+        }
+        normalizeFloatx80Subnormal( bSig, &bExp, &bSig );
+    }
+    if ( aExp == 0 ) {
+        if ( (bits64) ( aSig0<<1 ) == 0 ) return a;
+        normalizeFloatx80Subnormal( aSig0, &aExp, &aSig0 );
+    }
+    bSig |= LIT64( 0x8000000000000000 );
+    zSign = aSign;
+    expDiff = aExp - bExp;
+    aSig1 = 0;
+    if ( expDiff < 0 ) {
+        if ( expDiff < -1 ) return a;
+        shift128Right( aSig0, 0, 1, &aSig0, &aSig1 );
+        expDiff = 0;
+    }
+    q = ( bSig <= aSig0 );
+    if ( q ) aSig0 -= bSig;
+    expDiff -= 64;
+    while ( 0 < expDiff ) {
+        q = estimateDiv128To64( aSig0, aSig1, bSig );
+        q = ( 2 < q ) ? q - 2 : 0;
+        mul64To128( bSig, q, &term0, &term1 );
+        sub128( aSig0, aSig1, term0, term1, &aSig0, &aSig1 );
+        shortShift128Left( aSig0, aSig1, 62, &aSig0, &aSig1 );
+        expDiff -= 62;
+    }
+    expDiff += 64;
+    if ( 0 < expDiff ) {
+        q = estimateDiv128To64( aSig0, aSig1, bSig );
+        q = ( 2 < q ) ? q - 2 : 0;
+        q >>= 64 - expDiff;
+        mul64To128( bSig, q<<( 64 - expDiff ), &term0, &term1 );
+        sub128( aSig0, aSig1, term0, term1, &aSig0, &aSig1 );
+        shortShift128Left( 0, bSig, 64 - expDiff, &term0, &term1 );
+        while ( le128( term0, term1, aSig0, aSig1 ) ) {
+            ++q;
+            sub128( aSig0, aSig1, term0, term1, &aSig0, &aSig1 );
+        }
+    }
+    else {
+        term1 = 0;
+        term0 = bSig;
+    }
+    sub128( term0, term1, aSig0, aSig1, &alternateASig0, &alternateASig1 );
+    if (    lt128( alternateASig0, alternateASig1, aSig0, aSig1 )
+         || (    eq128( alternateASig0, alternateASig1, aSig0, aSig1 )
+              && ( q & 1 ) )
+       ) {
+        aSig0 = alternateASig0;
+        aSig1 = alternateASig1;
+        zSign = ! zSign;
+    }
+    return
+        normalizeRoundAndPackFloatx80(
+            80, zSign, bExp + expDiff, aSig0, aSig1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the square root of the extended double-precision floating-point
+value `a'.  The operation is performed according to the IEC/IEEE Standard
+for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+floatx80 floatx80_sqrt( floatx80 a )
+{
+    flag aSign;
+    int32 aExp, zExp;
+    bits64 aSig0, aSig1, zSig0, zSig1, doubleZSig0;
+    bits64 rem0, rem1, rem2, rem3, term0, term1, term2, term3;
+    floatx80 z;
+
+    aSig0 = extractFloatx80Frac( a );
+    aExp = extractFloatx80Exp( a );
+    aSign = extractFloatx80Sign( a );
+    if ( aExp == 0x7FFF ) {
+        if ( (bits64) ( aSig0<<1 ) ) return propagateFloatx80NaN( a, a );
+        if ( ! aSign ) return a;
+        goto invalid;
+    }
+    if ( aSign ) {
+        if ( ( aExp | aSig0 ) == 0 ) return a;
+ invalid:
+        float_raise( float_flag_invalid );
+        z.low = floatx80_default_nan_low;
+        z.high = floatx80_default_nan_high;
+        return z;
+    }
+    if ( aExp == 0 ) {
+        if ( aSig0 == 0 ) return packFloatx80( 0, 0, 0 );
+        normalizeFloatx80Subnormal( aSig0, &aExp, &aSig0 );
+    }
+    zExp = ( ( aExp - 0x3FFF )>>1 ) + 0x3FFF;
+    zSig0 = estimateSqrt32( aExp, aSig0>>32 );
+    shift128Right( aSig0, 0, 2 + ( aExp & 1 ), &aSig0, &aSig1 );
+    zSig0 = estimateDiv128To64( aSig0, aSig1, zSig0<<32 ) + ( zSig0<<30 );
+    doubleZSig0 = zSig0<<1;
+    mul64To128( zSig0, zSig0, &term0, &term1 );
+    sub128( aSig0, aSig1, term0, term1, &rem0, &rem1 );
+    while ( (sbits64) rem0 < 0 ) {
+        --zSig0;
+        doubleZSig0 -= 2;
+        add128( rem0, rem1, zSig0>>63, doubleZSig0 | 1, &rem0, &rem1 );
+    }
+    zSig1 = estimateDiv128To64( rem1, 0, doubleZSig0 );
+    if ( ( zSig1 & LIT64( 0x3FFFFFFFFFFFFFFF ) ) <= 5 ) {
+        if ( zSig1 == 0 ) zSig1 = 1;
+        mul64To128( doubleZSig0, zSig1, &term1, &term2 );
+        sub128( rem1, 0, term1, term2, &rem1, &rem2 );
+        mul64To128( zSig1, zSig1, &term2, &term3 );
+        sub192( rem1, rem2, 0, 0, term2, term3, &rem1, &rem2, &rem3 );
+        while ( (sbits64) rem1 < 0 ) {
+            --zSig1;
+            shortShift128Left( 0, zSig1, 1, &term2, &term3 );
+            term3 |= 1;
+            term2 |= doubleZSig0;
+            add192( rem1, rem2, rem3, 0, term2, term3, &rem1, &rem2, &rem3 );
+        }
+        zSig1 |= ( ( rem1 | rem2 | rem3 ) != 0 );
+    }
+    shortShift128Left( 0, zSig1, 1, &zSig0, &zSig1 );
+    zSig0 |= doubleZSig0;
+    return
+        roundAndPackFloatx80(
+            floatx80_rounding_precision, 0, zExp, zSig0, zSig1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the extended double-precision floating-point value `a' is
+equal to the corresponding value `b', and 0 otherwise.  The comparison is
+performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag floatx80_eq( floatx80 a, floatx80 b )
+{
+
+    if (    (    ( extractFloatx80Exp( a ) == 0x7FFF )
+              && (bits64) ( extractFloatx80Frac( a )<<1 ) )
+         || (    ( extractFloatx80Exp( b ) == 0x7FFF )
+              && (bits64) ( extractFloatx80Frac( b )<<1 ) )
+       ) {
+        if (    floatx80_is_signaling_nan( a )
+             || floatx80_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    return
+           ( a.low == b.low )
+        && (    ( a.high == b.high )
+             || (    ( a.low == 0 )
+                  && ( (bits16) ( ( a.high | b.high )<<1 ) == 0 ) )
+           );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the extended double-precision floating-point value `a' is
+less than or equal to the corresponding value `b', and 0 otherwise.  The
+comparison is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag floatx80_le( floatx80 a, floatx80 b )
+{
+    flag aSign, bSign;
+
+    if (    (    ( extractFloatx80Exp( a ) == 0x7FFF )
+              && (bits64) ( extractFloatx80Frac( a )<<1 ) )
+         || (    ( extractFloatx80Exp( b ) == 0x7FFF )
+              && (bits64) ( extractFloatx80Frac( b )<<1 ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    aSign = extractFloatx80Sign( a );
+    bSign = extractFloatx80Sign( b );
+    if ( aSign != bSign ) {
+        return
+               aSign
+            || (    ( ( (bits16) ( ( a.high | b.high )<<1 ) ) | a.low | b.low )
+                 == 0 );
+    }
+    return
+          aSign ? le128( b.high, b.low, a.high, a.low )
+        : le128( a.high, a.low, b.high, b.low );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the extended double-precision floating-point value `a' is
+less than the corresponding value `b', and 0 otherwise.  The comparison
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag floatx80_lt( floatx80 a, floatx80 b )
+{
+    flag aSign, bSign;
+
+    if (    (    ( extractFloatx80Exp( a ) == 0x7FFF )
+              && (bits64) ( extractFloatx80Frac( a )<<1 ) )
+         || (    ( extractFloatx80Exp( b ) == 0x7FFF )
+              && (bits64) ( extractFloatx80Frac( b )<<1 ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    aSign = extractFloatx80Sign( a );
+    bSign = extractFloatx80Sign( b );
+    if ( aSign != bSign ) {
+        return
+               aSign
+            && (    ( ( (bits16) ( ( a.high | b.high )<<1 ) ) | a.low | b.low )
+                 != 0 );
+    }
+    return
+          aSign ? lt128( b.high, b.low, a.high, a.low )
+        : lt128( a.high, a.low, b.high, b.low );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the extended double-precision floating-point value `a' is equal
+to the corresponding value `b', and 0 otherwise.  The invalid exception is
+raised if either operand is a NaN.  Otherwise, the comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag floatx80_eq_signaling( floatx80 a, floatx80 b )
+{
+
+    if (    (    ( extractFloatx80Exp( a ) == 0x7FFF )
+              && (bits64) ( extractFloatx80Frac( a )<<1 ) )
+         || (    ( extractFloatx80Exp( b ) == 0x7FFF )
+              && (bits64) ( extractFloatx80Frac( b )<<1 ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    return
+           ( a.low == b.low )
+        && (    ( a.high == b.high )
+             || (    ( a.low == 0 )
+                  && ( (bits16) ( ( a.high | b.high )<<1 ) == 0 ) )
+           );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the extended double-precision floating-point value `a' is less
+than or equal to the corresponding value `b', and 0 otherwise.  Quiet NaNs
+do not cause an exception.  Otherwise, the comparison is performed according
+to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag floatx80_le_quiet( floatx80 a, floatx80 b )
+{
+    flag aSign, bSign;
+
+    if (    (    ( extractFloatx80Exp( a ) == 0x7FFF )
+              && (bits64) ( extractFloatx80Frac( a )<<1 ) )
+         || (    ( extractFloatx80Exp( b ) == 0x7FFF )
+              && (bits64) ( extractFloatx80Frac( b )<<1 ) )
+       ) {
+        if (    floatx80_is_signaling_nan( a )
+             || floatx80_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    aSign = extractFloatx80Sign( a );
+    bSign = extractFloatx80Sign( b );
+    if ( aSign != bSign ) {
+        return
+               aSign
+            || (    ( ( (bits16) ( ( a.high | b.high )<<1 ) ) | a.low | b.low )
+                 == 0 );
+    }
+    return
+          aSign ? le128( b.high, b.low, a.high, a.low )
+        : le128( a.high, a.low, b.high, b.low );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the extended double-precision floating-point value `a' is less
+than the corresponding value `b', and 0 otherwise.  Quiet NaNs do not cause
+an exception.  Otherwise, the comparison is performed according to the
+IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag floatx80_lt_quiet( floatx80 a, floatx80 b )
+{
+    flag aSign, bSign;
+
+    if (    (    ( extractFloatx80Exp( a ) == 0x7FFF )
+              && (bits64) ( extractFloatx80Frac( a )<<1 ) )
+         || (    ( extractFloatx80Exp( b ) == 0x7FFF )
+              && (bits64) ( extractFloatx80Frac( b )<<1 ) )
+       ) {
+        if (    floatx80_is_signaling_nan( a )
+             || floatx80_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    aSign = extractFloatx80Sign( a );
+    bSign = extractFloatx80Sign( b );
+    if ( aSign != bSign ) {
+        return
+               aSign
+            && (    ( ( (bits16) ( ( a.high | b.high )<<1 ) ) | a.low | b.low )
+                 != 0 );
+    }
+    return
+          aSign ? lt128( b.high, b.low, a.high, a.low )
+        : lt128( a.high, a.low, b.high, b.low );
+
+}
+
+#endif
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the quadruple-precision floating-point
+value `a' to the 32-bit two's complement integer format.  The conversion
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic---which means in particular that the conversion is rounded
+according to the current rounding mode.  If `a' is a NaN, the largest
+positive integer is returned.  Otherwise, if the conversion overflows, the
+largest integer with the same sign as `a' is returned.
+-------------------------------------------------------------------------------
+*/
+int32 float128_to_int32( float128 a )
+{
+    flag aSign;
+    int32 aExp, shiftCount;
+    bits64 aSig0, aSig1;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    aSign = extractFloat128Sign( a );
+    if ( ( aExp == 0x7FFF ) && ( aSig0 | aSig1 ) ) aSign = 0;
+    if ( aExp ) aSig0 |= LIT64( 0x0001000000000000 );
+    aSig0 |= ( aSig1 != 0 );
+    shiftCount = 0x4028 - aExp;
+    if ( 0 < shiftCount ) shift64RightJamming( aSig0, shiftCount, &aSig0 );
+    return roundAndPackInt32( aSign, aSig0 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the quadruple-precision floating-point
+value `a' to the 32-bit two's complement integer format.  The conversion
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic, except that the conversion is always rounded toward zero.  If
+`a' is a NaN, the largest positive integer is returned.  Otherwise, if the
+conversion overflows, the largest integer with the same sign as `a' is
+returned.
+-------------------------------------------------------------------------------
+*/
+int32 float128_to_int32_round_to_zero( float128 a )
+{
+    flag aSign;
+    int32 aExp, shiftCount;
+    bits64 aSig0, aSig1, savedASig;
+    int32 z;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    aSign = extractFloat128Sign( a );
+    aSig0 |= ( aSig1 != 0 );
+    if ( 0x401E < aExp ) {
+        if ( ( aExp == 0x7FFF ) && aSig0 ) aSign = 0;
+        goto invalid;
+    }
+    else if ( aExp < 0x3FFF ) {
+        if ( aExp || aSig0 ) float_exception_flags |= float_flag_inexact;
+        return 0;
+    }
+    aSig0 |= LIT64( 0x0001000000000000 );
+    shiftCount = 0x402F - aExp;
+    savedASig = aSig0;
+    aSig0 >>= shiftCount;
+    z = aSig0;
+    if ( aSign ) z = - z;
+    if ( ( z < 0 ) ^ aSign ) {
+ invalid:
+        float_raise( float_flag_invalid );
+        return aSign ? (sbits32) 0x80000000 : 0x7FFFFFFF;
+    }
+    if ( ( aSig0<<shiftCount ) != savedASig ) {
+        float_exception_flags |= float_flag_inexact;
+    }
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the quadruple-precision floating-point
+value `a' to the 64-bit two's complement integer format.  The conversion
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic---which means in particular that the conversion is rounded
+according to the current rounding mode.  If `a' is a NaN, the largest
+positive integer is returned.  Otherwise, if the conversion overflows, the
+largest integer with the same sign as `a' is returned.
+-------------------------------------------------------------------------------
+*/
+int64 float128_to_int64( float128 a )
+{
+    flag aSign;
+    int32 aExp, shiftCount;
+    bits64 aSig0, aSig1;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    aSign = extractFloat128Sign( a );
+    if ( aExp ) aSig0 |= LIT64( 0x0001000000000000 );
+    shiftCount = 0x402F - aExp;
+    if ( shiftCount <= 0 ) {
+        if ( 0x403E < aExp ) {
+            float_raise( float_flag_invalid );
+            if (    ! aSign
+                 || (    ( aExp == 0x7FFF )
+                      && ( aSig1 || ( aSig0 != LIT64( 0x0001000000000000 ) ) )
+                    )
+               ) {
+                return LIT64( 0x7FFFFFFFFFFFFFFF );
+            }
+            return (sbits64) LIT64( 0x8000000000000000 );
+        }
+        shortShift128Left( aSig0, aSig1, - shiftCount, &aSig0, &aSig1 );
+    }
+    else {
+        shift64ExtraRightJamming( aSig0, aSig1, shiftCount, &aSig0, &aSig1 );
+    }
+    return roundAndPackInt64( aSign, aSig0, aSig1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the quadruple-precision floating-point
+value `a' to the 64-bit two's complement integer format.  The conversion
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic, except that the conversion is always rounded toward zero.
+If `a' is a NaN, the largest positive integer is returned.  Otherwise, if
+the conversion overflows, the largest integer with the same sign as `a' is
+returned.
+-------------------------------------------------------------------------------
+*/
+int64 float128_to_int64_round_to_zero( float128 a )
+{
+    flag aSign;
+    int32 aExp, shiftCount;
+    bits64 aSig0, aSig1;
+    int64 z;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    aSign = extractFloat128Sign( a );
+    if ( aExp ) aSig0 |= LIT64( 0x0001000000000000 );
+    shiftCount = aExp - 0x402F;
+    if ( 0 < shiftCount ) {
+        if ( 0x403E <= aExp ) {
+            aSig0 &= LIT64( 0x0000FFFFFFFFFFFF );
+            if (    ( a.high == LIT64( 0xC03E000000000000 ) )
+                 && ( aSig1 < LIT64( 0x0002000000000000 ) ) ) {
+                if ( aSig1 ) float_exception_flags |= float_flag_inexact;
+            }
+            else {
+                float_raise( float_flag_invalid );
+                if ( ! aSign || ( ( aExp == 0x7FFF ) && ( aSig0 | aSig1 ) ) ) {
+                    return LIT64( 0x7FFFFFFFFFFFFFFF );
+                }
+            }
+            return (sbits64) LIT64( 0x8000000000000000 );
+        }
+        z = ( aSig0<<shiftCount ) | ( aSig1>>( ( - shiftCount ) & 63 ) );
+        if ( (bits64) ( aSig1<<shiftCount ) ) {
+            float_exception_flags |= float_flag_inexact;
+        }
+    }
+    else {
+        if ( aExp < 0x3FFF ) {
+            if ( aExp | aSig0 | aSig1 ) {
+                float_exception_flags |= float_flag_inexact;
+            }
+            return 0;
+        }
+        z = aSig0>>( - shiftCount );
+        if (    aSig1
+             || ( shiftCount && (bits64) ( aSig0<<( shiftCount & 63 ) ) ) ) {
+            float_exception_flags |= float_flag_inexact;
+        }
+    }
+    if ( aSign ) z = - z;
+    return z;
+
+}
+
+/*
+ * just like above - but do not care for overflow of signed results
+ */
+uint64 float128_to_uint64_round_to_zero( float128 a )
+{
+    flag aSign;
+    int32 aExp, shiftCount;
+    bits64 aSig0, aSig1;
+    uint64 z;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    aSign = extractFloat128Sign( a );
+    if ( aExp ) aSig0 |= LIT64( 0x0001000000000000 );
+    shiftCount = aExp - 0x402F;
+    if ( 0 < shiftCount ) {
+        if ( 0x403F <= aExp ) {
+            aSig0 &= LIT64( 0x0000FFFFFFFFFFFF );
+            if (    ( a.high == LIT64( 0xC03E000000000000 ) )
+                 && ( aSig1 < LIT64( 0x0002000000000000 ) ) ) {
+                if ( aSig1 ) float_exception_flags |= float_flag_inexact;
+            }
+            else {
+                float_raise( float_flag_invalid );
+            }
+            return LIT64( 0xFFFFFFFFFFFFFFFF );
+        }
+        z = ( aSig0<<shiftCount ) | ( aSig1>>( ( - shiftCount ) & 63 ) );
+        if ( (bits64) ( aSig1<<shiftCount ) ) {
+            float_exception_flags |= float_flag_inexact;
+        }
+    }
+    else {
+        if ( aExp < 0x3FFF ) {
+            if ( aExp | aSig0 | aSig1 ) {
+                float_exception_flags |= float_flag_inexact;
+            }
+            return 0;
+        }
+        z = aSig0>>( - shiftCount );
+        if (aSig1 || ( shiftCount && (bits64) ( aSig0<<( shiftCount & 63 ) ) ) ) {
+            float_exception_flags |= float_flag_inexact;
+        }
+    }
+    if ( aSign ) z = - z;
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the quadruple-precision floating-point
+value `a' to the single-precision floating-point format.  The conversion
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float32 float128_to_float32( float128 a )
+{
+    flag aSign;
+    int32 aExp;
+    bits64 aSig0, aSig1;
+    bits32 zSig;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    aSign = extractFloat128Sign( a );
+    if ( aExp == 0x7FFF ) {
+        if ( aSig0 | aSig1 ) {
+            return commonNaNToFloat32( float128ToCommonNaN( a ) );
+        }
+        return packFloat32( aSign, 0xFF, 0 );
+    }
+    aSig0 |= ( aSig1 != 0 );
+    shift64RightJamming( aSig0, 18, &aSig0 );
+    zSig = aSig0;
+    if ( aExp || zSig ) {
+        zSig |= 0x40000000;
+        aExp -= 0x3F81;
+    }
+    return roundAndPackFloat32( aSign, aExp, zSig );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the quadruple-precision floating-point
+value `a' to the double-precision floating-point format.  The conversion
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float64 float128_to_float64( float128 a )
+{
+    flag aSign;
+    int32 aExp;
+    bits64 aSig0, aSig1;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    aSign = extractFloat128Sign( a );
+    if ( aExp == 0x7FFF ) {
+        if ( aSig0 | aSig1 ) {
+            return commonNaNToFloat64( float128ToCommonNaN( a ) );
+        }
+        return packFloat64( aSign, 0x7FF, 0 );
+    }
+    shortShift128Left( aSig0, aSig1, 14, &aSig0, &aSig1 );
+    aSig0 |= ( aSig1 != 0 );
+    if ( aExp || aSig0 ) {
+        aSig0 |= LIT64( 0x4000000000000000 );
+        aExp -= 0x3C01;
+    }
+    return roundAndPackFloat64( aSign, aExp, aSig0 );
+
+}
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the quadruple-precision floating-point
+value `a' to the extended double-precision floating-point format.  The
+conversion is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+floatx80 float128_to_floatx80( float128 a )
+{
+    flag aSign;
+    int32 aExp;
+    bits64 aSig0, aSig1;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    aSign = extractFloat128Sign( a );
+    if ( aExp == 0x7FFF ) {
+        if ( aSig0 | aSig1 ) {
+            return commonNaNToFloatx80( float128ToCommonNaN( a ) );
+        }
+        return packFloatx80( aSign, 0x7FFF, LIT64( 0x8000000000000000 ) );
+    }
+    if ( aExp == 0 ) {
+        if ( ( aSig0 | aSig1 ) == 0 ) return packFloatx80( aSign, 0, 0 );
+        normalizeFloat128Subnormal( aSig0, aSig1, &aExp, &aSig0, &aSig1 );
+    }
+    else {
+        aSig0 |= LIT64( 0x0001000000000000 );
+    }
+    shortShift128Left( aSig0, aSig1, 15, &aSig0, &aSig1 );
+    return roundAndPackFloatx80( 80, aSign, aExp, aSig0, aSig1 );
+
+}
+
+#endif
+
+/*
+-------------------------------------------------------------------------------
+Rounds the quadruple-precision floating-point value `a' to an integer, and
+returns the result as a quadruple-precision floating-point value.  The
+operation is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float128 float128_round_to_int( float128 a )
+{
+    flag aSign;
+    int32 aExp;
+    bits64 lastBitMask, roundBitsMask;
+    int8 roundingMode;
+    float128 z;
+
+    aExp = extractFloat128Exp( a );
+    if ( 0x402F <= aExp ) {
+        if ( 0x406F <= aExp ) {
+            if (    ( aExp == 0x7FFF )
+                 && ( extractFloat128Frac0( a ) | extractFloat128Frac1( a ) )
+               ) {
+                return propagateFloat128NaN( a, a );
+            }
+            return a;
+        }
+        lastBitMask = 1;
+        lastBitMask = ( lastBitMask<<( 0x406E - aExp ) )<<1;
+        roundBitsMask = lastBitMask - 1;
+        z = a;
+        roundingMode = float_rounding_mode;
+        if ( roundingMode == float_round_nearest_even ) {
+            if ( lastBitMask ) {
+                add128( z.high, z.low, 0, lastBitMask>>1, &z.high, &z.low );
+                if ( ( z.low & roundBitsMask ) == 0 ) z.low &= ~ lastBitMask;
+            }
+            else {
+                if ( (sbits64) z.low < 0 ) {
+                    ++z.high;
+                    if ( (bits64) ( z.low<<1 ) == 0 ) z.high &= ~1;
+                }
+            }
+        }
+        else if ( roundingMode != float_round_to_zero ) {
+            if (   extractFloat128Sign( z )
+                 ^ ( roundingMode == float_round_up ) ) {
+                add128( z.high, z.low, 0, roundBitsMask, &z.high, &z.low );
+            }
+        }
+        z.low &= ~ roundBitsMask;
+    }
+    else {
+        if ( aExp < 0x3FFF ) {
+            if ( ( ( (bits64) ( a.high<<1 ) ) | a.low ) == 0 ) return a;
+            float_exception_flags |= float_flag_inexact;
+            aSign = extractFloat128Sign( a );
+            switch ( float_rounding_mode ) {
+             case float_round_nearest_even:
+                if (    ( aExp == 0x3FFE )
+                     && (   extractFloat128Frac0( a )
+                          | extractFloat128Frac1( a ) )
+                   ) {
+                    return packFloat128( aSign, 0x3FFF, 0, 0 );
+                }
+                break;
+            case float_round_to_zero:
+               break;
+             case float_round_down:
+                return
+                      aSign ? packFloat128( 1, 0x3FFF, 0, 0 )
+                    : packFloat128( 0, 0, 0, 0 );
+             case float_round_up:
+                return
+                      aSign ? packFloat128( 1, 0, 0, 0 )
+                    : packFloat128( 0, 0x3FFF, 0, 0 );
+            }
+            return packFloat128( aSign, 0, 0, 0 );
+        }
+        lastBitMask = 1;
+        lastBitMask <<= 0x402F - aExp;
+        roundBitsMask = lastBitMask - 1;
+        z.low = 0;
+        z.high = a.high;
+        roundingMode = float_rounding_mode;
+        if ( roundingMode == float_round_nearest_even ) {
+            z.high += lastBitMask>>1;
+            if ( ( ( z.high & roundBitsMask ) | a.low ) == 0 ) {
+                z.high &= ~ lastBitMask;
+            }
+        }
+        else if ( roundingMode != float_round_to_zero ) {
+            if (   extractFloat128Sign( z )
+                 ^ ( roundingMode == float_round_up ) ) {
+                z.high |= ( a.low != 0 );
+                z.high += roundBitsMask;
+            }
+        }
+        z.high &= ~ roundBitsMask;
+    }
+    if ( ( z.low != a.low ) || ( z.high != a.high ) ) {
+        float_exception_flags |= float_flag_inexact;
+    }
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of adding the absolute values of the quadruple-precision
+floating-point values `a' and `b'.  If `zSign' is 1, the sum is negated
+before being returned.  `zSign' is ignored if the result is a NaN.
+The addition is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float128 addFloat128Sigs( float128 a, float128 b, flag zSign )
+{
+    int32 aExp, bExp, zExp;
+    bits64 aSig0, aSig1, bSig0, bSig1, zSig0, zSig1, zSig2;
+    int32 expDiff;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    bSig1 = extractFloat128Frac1( b );
+    bSig0 = extractFloat128Frac0( b );
+    bExp = extractFloat128Exp( b );
+    expDiff = aExp - bExp;
+    if ( 0 < expDiff ) {
+        if ( aExp == 0x7FFF ) {
+            if ( aSig0 | aSig1 ) return propagateFloat128NaN( a, b );
+            return a;
+        }
+        if ( bExp == 0 ) {
+            --expDiff;
+        }
+        else {
+            bSig0 |= LIT64( 0x0001000000000000 );
+        }
+        shift128ExtraRightJamming(
+            bSig0, bSig1, 0, expDiff, &bSig0, &bSig1, &zSig2 );
+        zExp = aExp;
+    }
+    else if ( expDiff < 0 ) {
+        if ( bExp == 0x7FFF ) {
+            if ( bSig0 | bSig1 ) return propagateFloat128NaN( a, b );
+            return packFloat128( zSign, 0x7FFF, 0, 0 );
+        }
+        if ( aExp == 0 ) {
+            ++expDiff;
+        }
+        else {
+            aSig0 |= LIT64( 0x0001000000000000 );
+        }
+        shift128ExtraRightJamming(
+            aSig0, aSig1, 0, - expDiff, &aSig0, &aSig1, &zSig2 );
+        zExp = bExp;
+    }
+    else {
+        if ( aExp == 0x7FFF ) {
+            if ( aSig0 | aSig1 | bSig0 | bSig1 ) {
+                return propagateFloat128NaN( a, b );
+            }
+            return a;
+        }
+        add128( aSig0, aSig1, bSig0, bSig1, &zSig0, &zSig1 );
+        if ( aExp == 0 ) return packFloat128( zSign, 0, zSig0, zSig1 );
+        zSig2 = 0;
+        zSig0 |= LIT64( 0x0002000000000000 );
+        zExp = aExp;
+        goto shiftRight1;
+    }
+    aSig0 |= LIT64( 0x0001000000000000 );
+    add128( aSig0, aSig1, bSig0, bSig1, &zSig0, &zSig1 );
+    --zExp;
+    if ( zSig0 < LIT64( 0x0002000000000000 ) ) goto roundAndPack;
+    ++zExp;
+ shiftRight1:
+    shift128ExtraRightJamming(
+        zSig0, zSig1, zSig2, 1, &zSig0, &zSig1, &zSig2 );
+ roundAndPack:
+    return roundAndPackFloat128( zSign, zExp, zSig0, zSig1, zSig2 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of subtracting the absolute values of the quadruple-
+precision floating-point values `a' and `b'.  If `zSign' is 1, the
+difference is negated before being returned.  `zSign' is ignored if the
+result is a NaN.  The subtraction is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+static float128 subFloat128Sigs( float128 a, float128 b, flag zSign )
+{
+    int32 aExp, bExp, zExp;
+    bits64 aSig0, aSig1, bSig0, bSig1, zSig0, zSig1;
+    int32 expDiff;
+    float128 z;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    bSig1 = extractFloat128Frac1( b );
+    bSig0 = extractFloat128Frac0( b );
+    bExp = extractFloat128Exp( b );
+    expDiff = aExp - bExp;
+    shortShift128Left( aSig0, aSig1, 14, &aSig0, &aSig1 );
+    shortShift128Left( bSig0, bSig1, 14, &bSig0, &bSig1 );
+    if ( 0 < expDiff ) goto aExpBigger;
+    if ( expDiff < 0 ) goto bExpBigger;
+    if ( aExp == 0x7FFF ) {
+        if ( aSig0 | aSig1 | bSig0 | bSig1 ) {
+            return propagateFloat128NaN( a, b );
+        }
+        float_raise( float_flag_invalid );
+        z.low = float128_default_nan_low;
+        z.high = float128_default_nan_high;
+        return z;
+    }
+    if ( aExp == 0 ) {
+        aExp = 1;
+        bExp = 1;
+    }
+    if ( bSig0 < aSig0 ) goto aBigger;
+    if ( aSig0 < bSig0 ) goto bBigger;
+    if ( bSig1 < aSig1 ) goto aBigger;
+    if ( aSig1 < bSig1 ) goto bBigger;
+    return packFloat128( float_rounding_mode == float_round_down, 0, 0, 0 );
+ bExpBigger:
+    if ( bExp == 0x7FFF ) {
+        if ( bSig0 | bSig1 ) return propagateFloat128NaN( a, b );
+        return packFloat128( zSign ^ 1, 0x7FFF, 0, 0 );
+    }
+    if ( aExp == 0 ) {
+        ++expDiff;
+    }
+    else {
+        aSig0 |= LIT64( 0x4000000000000000 );
+    }
+    shift128RightJamming( aSig0, aSig1, - expDiff, &aSig0, &aSig1 );
+    bSig0 |= LIT64( 0x4000000000000000 );
+ bBigger:
+    sub128( bSig0, bSig1, aSig0, aSig1, &zSig0, &zSig1 );
+    zExp = bExp;
+    zSign ^= 1;
+    goto normalizeRoundAndPack;
+ aExpBigger:
+    if ( aExp == 0x7FFF ) {
+        if ( aSig0 | aSig1 ) return propagateFloat128NaN( a, b );
+        return a;
+    }
+    if ( bExp == 0 ) {
+        --expDiff;
+    }
+    else {
+        bSig0 |= LIT64( 0x4000000000000000 );
+    }
+    shift128RightJamming( bSig0, bSig1, expDiff, &bSig0, &bSig1 );
+    aSig0 |= LIT64( 0x4000000000000000 );
+ aBigger:
+    sub128( aSig0, aSig1, bSig0, bSig1, &zSig0, &zSig1 );
+    zExp = aExp;
+ normalizeRoundAndPack:
+    --zExp;
+    return normalizeRoundAndPackFloat128( zSign, zExp - 14, zSig0, zSig1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of adding the quadruple-precision floating-point values
+`a' and `b'.  The operation is performed according to the IEC/IEEE Standard
+for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float128 float128_add( float128 a, float128 b )
+{
+    flag aSign, bSign;
+
+    aSign = extractFloat128Sign( a );
+    bSign = extractFloat128Sign( b );
+    if ( aSign == bSign ) {
+        return addFloat128Sigs( a, b, aSign );
+    }
+    else {
+        return subFloat128Sigs( a, b, aSign );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of subtracting the quadruple-precision floating-point
+values `a' and `b'.  The operation is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float128 float128_sub( float128 a, float128 b )
+{
+    flag aSign, bSign;
+
+    aSign = extractFloat128Sign( a );
+    bSign = extractFloat128Sign( b );
+    if ( aSign == bSign ) {
+        return subFloat128Sigs( a, b, aSign );
+    }
+    else {
+        return addFloat128Sigs( a, b, aSign );
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of multiplying the quadruple-precision floating-point
+values `a' and `b'.  The operation is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float128 float128_mul( float128 a, float128 b )
+{
+    flag aSign, bSign, zSign;
+    int32 aExp, bExp, zExp;
+    bits64 aSig0, aSig1, bSig0, bSig1, zSig0, zSig1, zSig2, zSig3;
+    float128 z;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    aSign = extractFloat128Sign( a );
+    bSig1 = extractFloat128Frac1( b );
+    bSig0 = extractFloat128Frac0( b );
+    bExp = extractFloat128Exp( b );
+    bSign = extractFloat128Sign( b );
+    zSign = aSign ^ bSign;
+    if ( aExp == 0x7FFF ) {
+        if (    ( aSig0 | aSig1 )
+             || ( ( bExp == 0x7FFF ) && ( bSig0 | bSig1 ) ) ) {
+            return propagateFloat128NaN( a, b );
+        }
+        if ( ( bExp | bSig0 | bSig1 ) == 0 ) goto invalid;
+        return packFloat128( zSign, 0x7FFF, 0, 0 );
+    }
+    if ( bExp == 0x7FFF ) {
+        if ( bSig0 | bSig1 ) return propagateFloat128NaN( a, b );
+        if ( ( aExp | aSig0 | aSig1 ) == 0 ) {
+ invalid:
+            float_raise( float_flag_invalid );
+            z.low = float128_default_nan_low;
+            z.high = float128_default_nan_high;
+            return z;
+        }
+        return packFloat128( zSign, 0x7FFF, 0, 0 );
+    }
+    if ( aExp == 0 ) {
+        if ( ( aSig0 | aSig1 ) == 0 ) return packFloat128( zSign, 0, 0, 0 );
+        normalizeFloat128Subnormal( aSig0, aSig1, &aExp, &aSig0, &aSig1 );
+    }
+    if ( bExp == 0 ) {
+        if ( ( bSig0 | bSig1 ) == 0 ) return packFloat128( zSign, 0, 0, 0 );
+        normalizeFloat128Subnormal( bSig0, bSig1, &bExp, &bSig0, &bSig1 );
+    }
+    zExp = aExp + bExp - 0x4000;
+    aSig0 |= LIT64( 0x0001000000000000 );
+    shortShift128Left( bSig0, bSig1, 16, &bSig0, &bSig1 );
+    mul128To256( aSig0, aSig1, bSig0, bSig1, &zSig0, &zSig1, &zSig2, &zSig3 );
+    add128( zSig0, zSig1, aSig0, aSig1, &zSig0, &zSig1 );
+    zSig2 |= ( zSig3 != 0 );
+    if ( LIT64( 0x0002000000000000 ) <= zSig0 ) {
+        shift128ExtraRightJamming(
+            zSig0, zSig1, zSig2, 1, &zSig0, &zSig1, &zSig2 );
+        ++zExp;
+    }
+    return roundAndPackFloat128( zSign, zExp, zSig0, zSig1, zSig2 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of dividing the quadruple-precision floating-point value
+`a' by the corresponding value `b'.  The operation is performed according to
+the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float128 float128_div( float128 a, float128 b )
+{
+    flag aSign, bSign, zSign;
+    int32 aExp, bExp, zExp;
+    bits64 aSig0, aSig1, bSig0, bSig1, zSig0, zSig1, zSig2;
+    bits64 rem0, rem1, rem2, rem3, term0, term1, term2, term3;
+    float128 z;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    aSign = extractFloat128Sign( a );
+    bSig1 = extractFloat128Frac1( b );
+    bSig0 = extractFloat128Frac0( b );
+    bExp = extractFloat128Exp( b );
+    bSign = extractFloat128Sign( b );
+    zSign = aSign ^ bSign;
+    if ( aExp == 0x7FFF ) {
+        if ( aSig0 | aSig1 ) return propagateFloat128NaN( a, b );
+        if ( bExp == 0x7FFF ) {
+            if ( bSig0 | bSig1 ) return propagateFloat128NaN( a, b );
+            goto invalid;
+        }
+        return packFloat128( zSign, 0x7FFF, 0, 0 );
+    }
+    if ( bExp == 0x7FFF ) {
+        if ( bSig0 | bSig1 ) return propagateFloat128NaN( a, b );
+        return packFloat128( zSign, 0, 0, 0 );
+    }
+    if ( bExp == 0 ) {
+        if ( ( bSig0 | bSig1 ) == 0 ) {
+            if ( ( aExp | aSig0 | aSig1 ) == 0 ) {
+ invalid:
+                float_raise( float_flag_invalid );
+                z.low = float128_default_nan_low;
+                z.high = float128_default_nan_high;
+                return z;
+            }
+            float_raise( float_flag_divbyzero );
+            return packFloat128( zSign, 0x7FFF, 0, 0 );
+        }
+        normalizeFloat128Subnormal( bSig0, bSig1, &bExp, &bSig0, &bSig1 );
+    }
+    if ( aExp == 0 ) {
+        if ( ( aSig0 | aSig1 ) == 0 ) return packFloat128( zSign, 0, 0, 0 );
+        normalizeFloat128Subnormal( aSig0, aSig1, &aExp, &aSig0, &aSig1 );
+    }
+    zExp = aExp - bExp + 0x3FFD;
+    shortShift128Left(
+        aSig0 | LIT64( 0x0001000000000000 ), aSig1, 15, &aSig0, &aSig1 );
+    shortShift128Left(
+        bSig0 | LIT64( 0x0001000000000000 ), bSig1, 15, &bSig0, &bSig1 );
+    if ( le128( bSig0, bSig1, aSig0, aSig1 ) ) {
+        shift128Right( aSig0, aSig1, 1, &aSig0, &aSig1 );
+        ++zExp;
+    }
+    zSig0 = estimateDiv128To64( aSig0, aSig1, bSig0 );
+    mul128By64To192( bSig0, bSig1, zSig0, &term0, &term1, &term2 );
+    sub192( aSig0, aSig1, 0, term0, term1, term2, &rem0, &rem1, &rem2 );
+    while ( (sbits64) rem0 < 0 ) {
+        --zSig0;
+        add192( rem0, rem1, rem2, 0, bSig0, bSig1, &rem0, &rem1, &rem2 );
+    }
+    zSig1 = estimateDiv128To64( rem1, rem2, bSig0 );
+    if ( ( zSig1 & 0x3FFF ) <= 4 ) {
+        mul128By64To192( bSig0, bSig1, zSig1, &term1, &term2, &term3 );
+        sub192( rem1, rem2, 0, term1, term2, term3, &rem1, &rem2, &rem3 );
+        while ( (sbits64) rem1 < 0 ) {
+            --zSig1;
+            add192( rem1, rem2, rem3, 0, bSig0, bSig1, &rem1, &rem2, &rem3 );
+        }
+        zSig1 |= ( ( rem1 | rem2 | rem3 ) != 0 );
+    }
+    shift128ExtraRightJamming( zSig0, zSig1, 0, 15, &zSig0, &zSig1, &zSig2 );
+    return roundAndPackFloat128( zSign, zExp, zSig0, zSig1, zSig2 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the remainder of the quadruple-precision floating-point value `a'
+with respect to the corresponding value `b'.  The operation is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float128 float128_rem( float128 a, float128 b )
+{
+    flag aSign, bSign, zSign;
+    int32 aExp, bExp, expDiff;
+    bits64 aSig0, aSig1, bSig0, bSig1, q, term0, term1, term2;
+    bits64 allZero, alternateASig0, alternateASig1, sigMean1;
+    sbits64 sigMean0;
+    float128 z;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    aSign = extractFloat128Sign( a );
+    bSig1 = extractFloat128Frac1( b );
+    bSig0 = extractFloat128Frac0( b );
+    bExp = extractFloat128Exp( b );
+    bSign = extractFloat128Sign( b );
+    if ( aExp == 0x7FFF ) {
+        if (    ( aSig0 | aSig1 )
+             || ( ( bExp == 0x7FFF ) && ( bSig0 | bSig1 ) ) ) {
+            return propagateFloat128NaN( a, b );
+        }
+        goto invalid;
+    }
+    if ( bExp == 0x7FFF ) {
+        if ( bSig0 | bSig1 ) return propagateFloat128NaN( a, b );
+        return a;
+    }
+    if ( bExp == 0 ) {
+        if ( ( bSig0 | bSig1 ) == 0 ) {
+ invalid:
+            float_raise( float_flag_invalid );
+            z.low = float128_default_nan_low;
+            z.high = float128_default_nan_high;
+            return z;
+        }
+        normalizeFloat128Subnormal( bSig0, bSig1, &bExp, &bSig0, &bSig1 );
+    }
+    if ( aExp == 0 ) {
+        if ( ( aSig0 | aSig1 ) == 0 ) return a;
+        normalizeFloat128Subnormal( aSig0, aSig1, &aExp, &aSig0, &aSig1 );
+    }
+    expDiff = aExp - bExp;
+    if ( expDiff < -1 ) return a;
+    shortShift128Left(
+        aSig0 | LIT64( 0x0001000000000000 ),
+        aSig1,
+        15 - ( expDiff < 0 ),
+        &aSig0,
+        &aSig1
+    );
+    shortShift128Left(
+        bSig0 | LIT64( 0x0001000000000000 ), bSig1, 15, &bSig0, &bSig1 );
+    q = le128( bSig0, bSig1, aSig0, aSig1 );
+    if ( q ) sub128( aSig0, aSig1, bSig0, bSig1, &aSig0, &aSig1 );
+    expDiff -= 64;
+    while ( 0 < expDiff ) {
+        q = estimateDiv128To64( aSig0, aSig1, bSig0 );
+        q = ( 4 < q ) ? q - 4 : 0;
+        mul128By64To192( bSig0, bSig1, q, &term0, &term1, &term2 );
+        shortShift192Left( term0, term1, term2, 61, &term1, &term2, &allZero );
+        shortShift128Left( aSig0, aSig1, 61, &aSig0, &allZero );
+        sub128( aSig0, 0, term1, term2, &aSig0, &aSig1 );
+        expDiff -= 61;
+    }
+    if ( -64 < expDiff ) {
+        q = estimateDiv128To64( aSig0, aSig1, bSig0 );
+        q = ( 4 < q ) ? q - 4 : 0;
+        q >>= - expDiff;
+        shift128Right( bSig0, bSig1, 12, &bSig0, &bSig1 );
+        expDiff += 52;
+        if ( expDiff < 0 ) {
+            shift128Right( aSig0, aSig1, - expDiff, &aSig0, &aSig1 );
+        }
+        else {
+            shortShift128Left( aSig0, aSig1, expDiff, &aSig0, &aSig1 );
+        }
+        mul128By64To192( bSig0, bSig1, q, &term0, &term1, &term2 );
+        sub128( aSig0, aSig1, term1, term2, &aSig0, &aSig1 );
+    }
+    else {
+        shift128Right( aSig0, aSig1, 12, &aSig0, &aSig1 );
+        shift128Right( bSig0, bSig1, 12, &bSig0, &bSig1 );
+    }
+    do {
+        alternateASig0 = aSig0;
+        alternateASig1 = aSig1;
+        ++q;
+        sub128( aSig0, aSig1, bSig0, bSig1, &aSig0, &aSig1 );
+    } while ( 0 <= (sbits64) aSig0 );
+    add128(
+        aSig0, aSig1, alternateASig0, alternateASig1, (bits64 *)&sigMean0, &sigMean1 );
+    if (    ( sigMean0 < 0 )
+         || ( ( ( sigMean0 | sigMean1 ) == 0 ) && ( q & 1 ) ) ) {
+        aSig0 = alternateASig0;
+        aSig1 = alternateASig1;
+    }
+    zSign = ( (sbits64) aSig0 < 0 );
+    if ( zSign ) sub128( 0, 0, aSig0, aSig1, &aSig0, &aSig1 );
+    return
+        normalizeRoundAndPackFloat128( aSign ^ zSign, bExp - 4, aSig0, aSig1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the square root of the quadruple-precision floating-point value `a'.
+The operation is performed according to the IEC/IEEE Standard for Binary
+Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+float128 float128_sqrt( float128 a )
+{
+    flag aSign;
+    int32 aExp, zExp;
+    bits64 aSig0, aSig1, zSig0, zSig1, zSig2, doubleZSig0;
+    bits64 rem0, rem1, rem2, rem3, term0, term1, term2, term3;
+    float128 z;
+
+    aSig1 = extractFloat128Frac1( a );
+    aSig0 = extractFloat128Frac0( a );
+    aExp = extractFloat128Exp( a );
+    aSign = extractFloat128Sign( a );
+    if ( aExp == 0x7FFF ) {
+        if ( aSig0 | aSig1 ) return propagateFloat128NaN( a, a );
+        if ( ! aSign ) return a;
+        goto invalid;
+    }
+    if ( aSign ) {
+        if ( ( aExp | aSig0 | aSig1 ) == 0 ) return a;
+ invalid:
+        float_raise( float_flag_invalid );
+        z.low = float128_default_nan_low;
+        z.high = float128_default_nan_high;
+        return z;
+    }
+    if ( aExp == 0 ) {
+        if ( ( aSig0 | aSig1 ) == 0 ) return packFloat128( 0, 0, 0, 0 );
+        normalizeFloat128Subnormal( aSig0, aSig1, &aExp, &aSig0, &aSig1 );
+    }
+    zExp = ( ( aExp - 0x3FFF )>>1 ) + 0x3FFE;
+    aSig0 |= LIT64( 0x0001000000000000 );
+    zSig0 = estimateSqrt32( aExp, aSig0>>17 );
+    shortShift128Left( aSig0, aSig1, 13 - ( aExp & 1 ), &aSig0, &aSig1 );
+    zSig0 = estimateDiv128To64( aSig0, aSig1, zSig0<<32 ) + ( zSig0<<30 );
+    doubleZSig0 = zSig0<<1;
+    mul64To128( zSig0, zSig0, &term0, &term1 );
+    sub128( aSig0, aSig1, term0, term1, &rem0, &rem1 );
+    while ( (sbits64) rem0 < 0 ) {
+        --zSig0;
+        doubleZSig0 -= 2;
+        add128( rem0, rem1, zSig0>>63, doubleZSig0 | 1, &rem0, &rem1 );
+    }
+    zSig1 = estimateDiv128To64( rem1, 0, doubleZSig0 );
+    if ( ( zSig1 & 0x1FFF ) <= 5 ) {
+        if ( zSig1 == 0 ) zSig1 = 1;
+        mul64To128( doubleZSig0, zSig1, &term1, &term2 );
+        sub128( rem1, 0, term1, term2, &rem1, &rem2 );
+        mul64To128( zSig1, zSig1, &term2, &term3 );
+        sub192( rem1, rem2, 0, 0, term2, term3, &rem1, &rem2, &rem3 );
+        while ( (sbits64) rem1 < 0 ) {
+            --zSig1;
+            shortShift128Left( 0, zSig1, 1, &term2, &term3 );
+            term3 |= 1;
+            term2 |= doubleZSig0;
+            add192( rem1, rem2, rem3, 0, term2, term3, &rem1, &rem2, &rem3 );
+        }
+        zSig1 |= ( ( rem1 | rem2 | rem3 ) != 0 );
+    }
+    shift128ExtraRightJamming( zSig0, zSig1, 0, 14, &zSig0, &zSig1, &zSig2 );
+    return roundAndPackFloat128( 0, zExp, zSig0, zSig1, zSig2 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the quadruple-precision floating-point value `a' is equal to
+the corresponding value `b', and 0 otherwise.  The comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float128_eq( float128 a, float128 b )
+{
+
+    if (    (    ( extractFloat128Exp( a ) == 0x7FFF )
+              && ( extractFloat128Frac0( a ) | extractFloat128Frac1( a ) ) )
+         || (    ( extractFloat128Exp( b ) == 0x7FFF )
+              && ( extractFloat128Frac0( b ) | extractFloat128Frac1( b ) ) )
+       ) {
+        if (    float128_is_signaling_nan( a )
+             || float128_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    return
+           ( a.low == b.low )
+        && (    ( a.high == b.high )
+             || (    ( a.low == 0 )
+                  && ( (bits64) ( ( a.high | b.high )<<1 ) == 0 ) )
+           );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the quadruple-precision floating-point value `a' is less than
+or equal to the corresponding value `b', and 0 otherwise.  The comparison
+is performed according to the IEC/IEEE Standard for Binary Floating-Point
+Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float128_le( float128 a, float128 b )
+{
+    flag aSign, bSign;
+
+    if (    (    ( extractFloat128Exp( a ) == 0x7FFF )
+              && ( extractFloat128Frac0( a ) | extractFloat128Frac1( a ) ) )
+         || (    ( extractFloat128Exp( b ) == 0x7FFF )
+              && ( extractFloat128Frac0( b ) | extractFloat128Frac1( b ) ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    aSign = extractFloat128Sign( a );
+    bSign = extractFloat128Sign( b );
+    if ( aSign != bSign ) {
+        return
+               aSign
+            || (    ( ( (bits64) ( ( a.high | b.high )<<1 ) ) | a.low | b.low )
+                 == 0 );
+    }
+    return
+          aSign ? le128( b.high, b.low, a.high, a.low )
+        : le128( a.high, a.low, b.high, b.low );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the quadruple-precision floating-point value `a' is less than
+the corresponding value `b', and 0 otherwise.  The comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float128_lt( float128 a, float128 b )
+{
+    flag aSign, bSign;
+
+    if (    (    ( extractFloat128Exp( a ) == 0x7FFF )
+              && ( extractFloat128Frac0( a ) | extractFloat128Frac1( a ) ) )
+         || (    ( extractFloat128Exp( b ) == 0x7FFF )
+              && ( extractFloat128Frac0( b ) | extractFloat128Frac1( b ) ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    aSign = extractFloat128Sign( a );
+    bSign = extractFloat128Sign( b );
+    if ( aSign != bSign ) {
+        return
+               aSign
+            && (    ( ( (bits64) ( ( a.high | b.high )<<1 ) ) | a.low | b.low )
+                 != 0 );
+    }
+    return
+          aSign ? lt128( b.high, b.low, a.high, a.low )
+        : lt128( a.high, a.low, b.high, b.low );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the quadruple-precision floating-point value `a' is equal to
+the corresponding value `b', and 0 otherwise.  The invalid exception is
+raised if either operand is a NaN.  Otherwise, the comparison is performed
+according to the IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float128_eq_signaling( float128 a, float128 b )
+{
+
+    if (    (    ( extractFloat128Exp( a ) == 0x7FFF )
+              && ( extractFloat128Frac0( a ) | extractFloat128Frac1( a ) ) )
+         || (    ( extractFloat128Exp( b ) == 0x7FFF )
+              && ( extractFloat128Frac0( b ) | extractFloat128Frac1( b ) ) )
+       ) {
+        float_raise( float_flag_invalid );
+        return 0;
+    }
+    return
+           ( a.low == b.low )
+        && (    ( a.high == b.high )
+             || (    ( a.low == 0 )
+                  && ( (bits64) ( ( a.high | b.high )<<1 ) == 0 ) )
+           );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the quadruple-precision floating-point value `a' is less than
+or equal to the corresponding value `b', and 0 otherwise.  Quiet NaNs do not
+cause an exception.  Otherwise, the comparison is performed according to the
+IEC/IEEE Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float128_le_quiet( float128 a, float128 b )
+{
+    flag aSign, bSign;
+
+    if (    (    ( extractFloat128Exp( a ) == 0x7FFF )
+              && ( extractFloat128Frac0( a ) | extractFloat128Frac1( a ) ) )
+         || (    ( extractFloat128Exp( b ) == 0x7FFF )
+              && ( extractFloat128Frac0( b ) | extractFloat128Frac1( b ) ) )
+       ) {
+        if (    float128_is_signaling_nan( a )
+             || float128_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    aSign = extractFloat128Sign( a );
+    bSign = extractFloat128Sign( b );
+    if ( aSign != bSign ) {
+        return
+               aSign
+            || (    ( ( (bits64) ( ( a.high | b.high )<<1 ) ) | a.low | b.low )
+                 == 0 );
+    }
+    return
+          aSign ? le128( b.high, b.low, a.high, a.low )
+        : le128( a.high, a.low, b.high, b.low );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the quadruple-precision floating-point value `a' is less than
+the corresponding value `b', and 0 otherwise.  Quiet NaNs do not cause an
+exception.  Otherwise, the comparison is performed according to the IEC/IEEE
+Standard for Binary Floating-Point Arithmetic.
+-------------------------------------------------------------------------------
+*/
+flag float128_lt_quiet( float128 a, float128 b )
+{
+    flag aSign, bSign;
+
+    if (    (    ( extractFloat128Exp( a ) == 0x7FFF )
+              && ( extractFloat128Frac0( a ) | extractFloat128Frac1( a ) ) )
+         || (    ( extractFloat128Exp( b ) == 0x7FFF )
+              && ( extractFloat128Frac0( b ) | extractFloat128Frac1( b ) ) )
+       ) {
+        if (    float128_is_signaling_nan( a )
+             || float128_is_signaling_nan( b ) ) {
+            float_raise( float_flag_invalid );
+        }
+        return 0;
+    }
+    aSign = extractFloat128Sign( a );
+    bSign = extractFloat128Sign( b );
+    if ( aSign != bSign ) {
+        return
+               aSign
+            && (    ( ( (bits64) ( ( a.high | b.high )<<1 ) ) | a.low | b.low )
+                 != 0 );
+    }
+    return
+          aSign ? lt128( b.high, b.low, a.high, a.low )
+        : lt128( a.high, a.low, b.high, b.low );
+
+}
+
+#endif
+
+
+#if defined(SOFTFLOAT_FOR_GCC) && defined(SOFTFLOAT_NEED_FIXUNS)
+
+/*
+ * These two routines are not part of the original softfloat distribution.
+ *
+ * They are based on the corresponding conversions to integer but return
+ * unsigned numbers instead since these functions are required by GCC.
+ *
+ * Added by Mark Brinicombe <mark@NetBSD.org>  27/09/97
+ *
+ * float64 version overhauled for SoftFloat 2a [bjh21 2000-07-15]
+ */
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the double-precision floating-point value
+`a' to the 32-bit unsigned integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-point
+Arithmetic, except that the conversion is always rounded toward zero.  If
+`a' is a NaN, the largest positive integer is returned.  If the conversion
+overflows, the largest integer positive is returned.
+-------------------------------------------------------------------------------
+*/
+uint32 float64_to_uint32_round_to_zero( float64 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits64 aSig, savedASig;
+    uint32 z;
+
+    aSig = extractFloat64Frac( a );
+    aExp = extractFloat64Exp( a );
+    aSign = extractFloat64Sign( a );
+
+    if (aSign) {
+        float_raise( float_flag_invalid );
+       return(0);
+    }
+
+    if ( 0x41E < aExp ) {
+        float_raise( float_flag_invalid );
+        return 0xffffffff;
+    }
+    else if ( aExp < 0x3FF ) {
+        if ( aExp || aSig ) float_exception_flags |= float_flag_inexact;
+        return 0;
+    }
+    aSig |= LIT64( 0x0010000000000000 );
+    shiftCount = 0x433 - aExp;
+    savedASig = aSig;
+    aSig >>= shiftCount;
+    z = aSig;
+    if ( ( aSig<<shiftCount ) != savedASig ) {
+        float_exception_flags |= float_flag_inexact;
+    }
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the single-precision floating-point value
+`a' to the 32-bit unsigned integer format.  The conversion is
+performed according to the IEC/IEEE Standard for Binary Floating-point
+Arithmetic, except that the conversion is always rounded toward zero.  If
+`a' is a NaN, the largest positive integer is returned.  If the conversion
+overflows, the largest positive integer is returned.
+-------------------------------------------------------------------------------
+*/
+uint32 float32_to_uint32_round_to_zero( float32 a )
+{
+    flag aSign;
+    int16 aExp, shiftCount;
+    bits32 aSig;
+    uint32 z;
+
+    aSig = extractFloat32Frac( a );
+    aExp = extractFloat32Exp( a );
+    aSign = extractFloat32Sign( a );
+    shiftCount = aExp - 0x9E;
+
+    if (aSign) {
+        float_raise( float_flag_invalid );
+       return(0);
+    }
+    if ( 0 < shiftCount ) {
+        float_raise( float_flag_invalid );
+        return 0xFFFFFFFF;
+    }
+    else if ( aExp <= 0x7E ) {
+        if ( aExp | aSig ) float_exception_flags |= float_flag_inexact;
+        return 0;
+    }
+    aSig = ( aSig | 0x800000 )<<8;
+    z = aSig>>( - shiftCount );
+    if ( aSig<<( shiftCount & 31 ) ) {
+        float_exception_flags |= float_flag_inexact;
+    }
+    return z;
+
+}
+
+#endif
diff --git a/lib/nbsd_libc/softfloat/eqdf2.c b/lib/nbsd_libc/softfloat/eqdf2.c
new file mode 100644 (file)
index 0000000..7f3c017
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: eqdf2.c,v 1.1 2000/06/06 08:15:02 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: eqdf2.c,v 1.1 2000/06/06 08:15:02 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+flag __eqdf2(float64, float64);
+
+flag
+__eqdf2(float64 a, float64 b)
+{
+
+       /* libgcc1.c says !(a == b) */
+       return !float64_eq(a, b);
+}
diff --git a/lib/nbsd_libc/softfloat/eqsf2.c b/lib/nbsd_libc/softfloat/eqsf2.c
new file mode 100644 (file)
index 0000000..0ef3e93
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: eqsf2.c,v 1.1 2000/06/06 08:15:03 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: eqsf2.c,v 1.1 2000/06/06 08:15:03 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+flag __eqsf2(float32, float32);
+
+flag
+__eqsf2(float32 a, float32 b)
+{
+
+       /* libgcc1.c says !(a == b) */
+       return !float32_eq(a, b);
+}
diff --git a/lib/nbsd_libc/softfloat/eqtf2.c b/lib/nbsd_libc/softfloat/eqtf2.c
new file mode 100644 (file)
index 0000000..8184e8c
--- /dev/null
@@ -0,0 +1,26 @@
+/* $NetBSD: eqtf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $ */
+
+/*
+ * Written by Matt Thomas, 2011.  This file is in the Public Domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: eqtf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#ifdef FLOAT128
+flag __eqtf2(float128, float128);
+
+flag
+__eqtf2(float128 a, float128 b)
+{
+
+       /* libgcc1.c says !(a == b) */
+       return !float128_eq(a, b);
+}
+#endif /* FLOAT128 */
diff --git a/lib/nbsd_libc/softfloat/fpgetmask.c b/lib/nbsd_libc/softfloat/fpgetmask.c
new file mode 100644 (file)
index 0000000..5430e96
--- /dev/null
@@ -0,0 +1,55 @@
+/* $NetBSD: fpgetmask.c,v 1.4 2008/04/28 20:23:00 martin Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Neil A. Carson and Mark Brinicombe
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetmask.c,v 1.4 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+#ifdef SOFTFLOAT_FOR_GCC
+#include "softfloat-for-gcc.h"
+#endif
+#include "milieu.h"
+#include "softfloat.h"
+
+#ifdef __weak_alias
+__weak_alias(fpgetmask,_fpgetmask)
+#endif
+
+fp_except
+fpgetmask(void)
+{
+
+       return float_exception_mask;
+}
diff --git a/lib/nbsd_libc/softfloat/fpgetround.c b/lib/nbsd_libc/softfloat/fpgetround.c
new file mode 100644 (file)
index 0000000..4f428ab
--- /dev/null
@@ -0,0 +1,55 @@
+/* $NetBSD: fpgetround.c,v 1.3 2008/04/28 20:23:00 martin Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Neil A. Carson and Mark Brinicombe
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetround.c,v 1.3 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+#ifdef SOFTFLOAT_FOR_GCC
+#include "softfloat-for-gcc.h"
+#endif
+#include "milieu.h"
+#include "softfloat.h"
+
+#ifdef __weak_alias
+__weak_alias(fpgetround,_fpgetround)
+#endif
+
+fp_rnd
+fpgetround(void)
+{
+
+       return float_rounding_mode;
+}
diff --git a/lib/nbsd_libc/softfloat/fpgetsticky.c b/lib/nbsd_libc/softfloat/fpgetsticky.c
new file mode 100644 (file)
index 0000000..67cfe65
--- /dev/null
@@ -0,0 +1,55 @@
+/* $NetBSD: fpgetsticky.c,v 1.3 2008/04/28 20:23:00 martin Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Neil A. Carson and Mark Brinicombe
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpgetsticky.c,v 1.3 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+#ifdef SOFTFLOAT_FOR_GCC
+#include "softfloat-for-gcc.h"
+#endif
+#include "milieu.h"
+#include "softfloat.h"
+
+#ifdef __weak_alias
+__weak_alias(fpgetsticky,_fpgetsticky)
+#endif
+
+fp_except
+fpgetsticky(void)
+{
+
+       return float_exception_flags;
+}
diff --git a/lib/nbsd_libc/softfloat/fpsetmask.c b/lib/nbsd_libc/softfloat/fpsetmask.c
new file mode 100644 (file)
index 0000000..3657107
--- /dev/null
@@ -0,0 +1,58 @@
+/* $NetBSD: fpsetmask.c,v 1.4 2008/04/28 20:23:00 martin Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Neil A. Carson and Mark Brinicombe
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetmask.c,v 1.4 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+#ifdef SOFTFLOAT_FOR_GCC
+#include "softfloat-for-gcc.h"
+#endif
+#include "milieu.h"
+#include "softfloat.h"
+
+#ifdef __weak_alias
+__weak_alias(fpsetmask,_fpsetmask)
+#endif
+
+fp_except
+fpsetmask(fp_except mask)
+{
+       fp_except old;
+
+       old = float_exception_mask;
+       float_exception_mask = mask;
+       return old;
+}
diff --git a/lib/nbsd_libc/softfloat/fpsetround.c b/lib/nbsd_libc/softfloat/fpsetround.c
new file mode 100644 (file)
index 0000000..16c20d3
--- /dev/null
@@ -0,0 +1,58 @@
+/* $NetBSD: fpsetround.c,v 1.3 2008/04/28 20:23:00 martin Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Neil A. Carson and Mark Brinicombe
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetround.c,v 1.3 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+#ifdef SOFTFLOAT_FOR_GCC
+#include "softfloat-for-gcc.h"
+#endif
+#include "milieu.h"
+#include "softfloat.h"
+
+#ifdef __weak_alias
+__weak_alias(fpsetround,_fpsetround)
+#endif
+
+fp_rnd
+fpsetround(fp_rnd rnd_dir)
+{
+       fp_rnd old;
+
+       old = float_rounding_mode;
+       float_rounding_mode = rnd_dir;
+       return old;
+}
diff --git a/lib/nbsd_libc/softfloat/fpsetsticky.c b/lib/nbsd_libc/softfloat/fpsetsticky.c
new file mode 100644 (file)
index 0000000..2f47367
--- /dev/null
@@ -0,0 +1,58 @@
+/* $NetBSD: fpsetsticky.c,v 1.3 2008/04/28 20:23:00 martin Exp $ */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Neil A. Carson and Mark Brinicombe
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fpsetsticky.c,v 1.3 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <ieeefp.h>
+#ifdef SOFTFLOAT_FOR_GCC
+#include "softfloat-for-gcc.h"
+#endif
+#include "milieu.h"
+#include "softfloat.h"
+
+#ifdef __weak_alias
+__weak_alias(fpsetsticky,_fpsetsticky)
+#endif
+
+fp_except
+fpsetsticky(fp_except except)
+{
+       fp_except old;
+
+       old = float_exception_flags;
+       float_exception_flags = except;
+       return old;
+}
diff --git a/lib/nbsd_libc/softfloat/gedf2.c b/lib/nbsd_libc/softfloat/gedf2.c
new file mode 100644 (file)
index 0000000..cba854d
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: gedf2.c,v 1.1 2000/06/06 08:15:05 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: gedf2.c,v 1.1 2000/06/06 08:15:05 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+flag __gedf2(float64, float64);
+
+flag
+__gedf2(float64 a, float64 b)
+{
+
+       /* libgcc1.c says (a >= b) - 1 */
+       return float64_le(b, a) - 1;
+}
diff --git a/lib/nbsd_libc/softfloat/gesf2.c b/lib/nbsd_libc/softfloat/gesf2.c
new file mode 100644 (file)
index 0000000..4d7a9dc
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: gesf2.c,v 1.1 2000/06/06 08:15:05 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: gesf2.c,v 1.1 2000/06/06 08:15:05 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+flag __gesf2(float32, float32);
+
+flag
+__gesf2(float32 a, float32 b)
+{
+
+       /* libgcc1.c says (a >= b) - 1 */
+       return float32_le(b, a) - 1;
+}
diff --git a/lib/nbsd_libc/softfloat/getf2.c b/lib/nbsd_libc/softfloat/getf2.c
new file mode 100644 (file)
index 0000000..c97708a
--- /dev/null
@@ -0,0 +1,28 @@
+/* $NetBSD: getf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $ */
+
+/*
+ * Written by Matt Thomas, 2011.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef FLOAT128
+
+flag __getf2(float128, float128);
+
+flag
+__getf2(float128 a, float128 b)
+{
+
+       /* libgcc1.c says (a >= b) - 1 */
+       return float128_le(b, a) - 1;
+}
+
+#endif /* FLOAT128 */
diff --git a/lib/nbsd_libc/softfloat/gexf2.c b/lib/nbsd_libc/softfloat/gexf2.c
new file mode 100644 (file)
index 0000000..98404d5
--- /dev/null
@@ -0,0 +1,27 @@
+/* $NetBSD: gexf2.c,v 1.2 2004/09/27 10:16:24 he Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: gexf2.c,v 1.2 2004/09/27 10:16:24 he Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef FLOATX80
+
+flag __gexf2(floatx80, floatx80);
+
+flag
+__gexf2(floatx80 a, floatx80 b)
+{
+
+       /* libgcc1.c says (a >= b) - 1 */
+       return floatx80_le(b, a) - 1;
+}
+#endif /* FLOATX80 */
diff --git a/lib/nbsd_libc/softfloat/gtdf2.c b/lib/nbsd_libc/softfloat/gtdf2.c
new file mode 100644 (file)
index 0000000..c9ba393
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: gtdf2.c,v 1.1 2000/06/06 08:15:05 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: gtdf2.c,v 1.1 2000/06/06 08:15:05 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+flag __gtdf2(float64, float64);
+
+flag
+__gtdf2(float64 a, float64 b)
+{
+
+       /* libgcc1.c says a > b */
+       return float64_lt(b, a);
+}
diff --git a/lib/nbsd_libc/softfloat/gtsf2.c b/lib/nbsd_libc/softfloat/gtsf2.c
new file mode 100644 (file)
index 0000000..7725875
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: gtsf2.c,v 1.1 2000/06/06 08:15:06 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: gtsf2.c,v 1.1 2000/06/06 08:15:06 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+flag __gtsf2(float32, float32);
+
+flag
+__gtsf2(float32 a, float32 b)
+{
+
+       /* libgcc1.c says a > b */
+       return float32_lt(b, a);
+}
diff --git a/lib/nbsd_libc/softfloat/gttf2.c b/lib/nbsd_libc/softfloat/gttf2.c
new file mode 100644 (file)
index 0000000..8ef472c
--- /dev/null
@@ -0,0 +1,28 @@
+/* $NetBSD: gttf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $ */
+
+/*
+ * Written by Matt Thomas, 2011.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: gttf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef FLOAT128
+
+flag __gttf2(float128, float128);
+
+flag
+__gttf2(float128 a, float128 b)
+{
+
+       /* libgcc1.c says a > b */
+       return float128_lt(b, a);
+}
+
+#endif /* FLOAT128 */
diff --git a/lib/nbsd_libc/softfloat/gtxf2.c b/lib/nbsd_libc/softfloat/gtxf2.c
new file mode 100644 (file)
index 0000000..20c8de1
--- /dev/null
@@ -0,0 +1,27 @@
+/* $NetBSD: gtxf2.c,v 1.2 2004/09/27 10:16:24 he Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: gtxf2.c,v 1.2 2004/09/27 10:16:24 he Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef FLOATX80
+
+flag __gtxf2(floatx80, floatx80);
+
+flag
+__gtxf2(floatx80 a, floatx80 b)
+{
+
+       /* libgcc1.c says a > b */
+       return floatx80_lt(b, a);
+}
+#endif /* FLOATX80 */
diff --git a/lib/nbsd_libc/softfloat/ledf2.c b/lib/nbsd_libc/softfloat/ledf2.c
new file mode 100644 (file)
index 0000000..f2b9428
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: ledf2.c,v 1.1 2000/06/06 08:15:06 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ledf2.c,v 1.1 2000/06/06 08:15:06 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+flag __ledf2(float64, float64);
+
+flag
+__ledf2(float64 a, float64 b)
+{
+
+       /* libgcc1.c says 1 - (a <= b) */
+       return 1 - float64_le(a, b);
+}
diff --git a/lib/nbsd_libc/softfloat/lesf2.c b/lib/nbsd_libc/softfloat/lesf2.c
new file mode 100644 (file)
index 0000000..e9e26a6
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: lesf2.c,v 1.1 2000/06/06 08:15:06 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: lesf2.c,v 1.1 2000/06/06 08:15:06 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+flag __lesf2(float32, float32);
+
+flag
+__lesf2(float32 a, float32 b)
+{
+
+       /* libgcc1.c says 1 - (a <= b) */
+       return 1 - float32_le(a, b);
+}
diff --git a/lib/nbsd_libc/softfloat/letf2.c b/lib/nbsd_libc/softfloat/letf2.c
new file mode 100644 (file)
index 0000000..20b1e1e
--- /dev/null
@@ -0,0 +1,28 @@
+/* $NetBSD: letf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $ */
+
+/*
+ * Written by Matt Thomas, 2011.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: letf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef FLOAT128
+
+flag __letf2(float128, float128);
+
+flag
+__letf2(float128 a, float128 b)
+{
+
+       /* libgcc1.c says 1 - (a <= b) */
+       return 1 - float128_le(a, b);
+}
+
+#endif /* FLOAT128 */
diff --git a/lib/nbsd_libc/softfloat/ltdf2.c b/lib/nbsd_libc/softfloat/ltdf2.c
new file mode 100644 (file)
index 0000000..9ab849f
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: ltdf2.c,v 1.1 2000/06/06 08:15:06 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ltdf2.c,v 1.1 2000/06/06 08:15:06 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+flag __ltdf2(float64, float64);
+
+flag
+__ltdf2(float64 a, float64 b)
+{
+
+       /* libgcc1.c says -(a < b) */
+       return -float64_lt(a, b);
+}
diff --git a/lib/nbsd_libc/softfloat/ltsf2.c b/lib/nbsd_libc/softfloat/ltsf2.c
new file mode 100644 (file)
index 0000000..1bd736d
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: ltsf2.c,v 1.1 2000/06/06 08:15:06 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ltsf2.c,v 1.1 2000/06/06 08:15:06 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+flag __ltsf2(float32, float32);
+
+flag
+__ltsf2(float32 a, float32 b)
+{
+
+       /* libgcc1.c says -(a < b) */
+       return -float32_lt(a, b);
+}
diff --git a/lib/nbsd_libc/softfloat/lttf2.c b/lib/nbsd_libc/softfloat/lttf2.c
new file mode 100644 (file)
index 0000000..f4b9273
--- /dev/null
@@ -0,0 +1,28 @@
+/* $NetBSD: lttf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $ */
+
+/*
+ * Written by Matt Thomas, 2011.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: lttf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef FLOAT128
+
+flag __lttf2(float128, float128);
+
+flag
+__lttf2(float128 a, float128 b)
+{
+
+       /* libgcc1.c says -(a < b) */
+       return -float128_lt(a, b);
+}
+
+#endif /* FLOAT128 */
diff --git a/lib/nbsd_libc/softfloat/nedf2.c b/lib/nbsd_libc/softfloat/nedf2.c
new file mode 100644 (file)
index 0000000..09735c7
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: nedf2.c,v 1.1 2000/06/06 08:15:07 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nedf2.c,v 1.1 2000/06/06 08:15:07 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+flag __nedf2(float64, float64);
+
+flag
+__nedf2(float64 a, float64 b)
+{
+
+       /* libgcc1.c says a != b */
+       return !float64_eq(a, b);
+}
diff --git a/lib/nbsd_libc/softfloat/negdf2.c b/lib/nbsd_libc/softfloat/negdf2.c
new file mode 100644 (file)
index 0000000..fb55bb2
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: negdf2.c,v 1.1 2000/06/06 08:15:07 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: negdf2.c,v 1.1 2000/06/06 08:15:07 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+float64 __negdf2(float64);
+
+float64
+__negdf2(float64 a)
+{
+
+       /* libgcc1.c says -a */
+       return a ^ FLOAT64_MANGLE(0x8000000000000000ULL);
+}
diff --git a/lib/nbsd_libc/softfloat/negsf2.c b/lib/nbsd_libc/softfloat/negsf2.c
new file mode 100644 (file)
index 0000000..b2f2e67
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: negsf2.c,v 1.1 2000/06/06 08:15:07 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: negsf2.c,v 1.1 2000/06/06 08:15:07 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+float32 __negsf2(float32);
+
+float32
+__negsf2(float32 a)
+{
+
+       /* libgcc1.c says INTIFY(-a) */
+       return a ^ 0x80000000;
+}
diff --git a/lib/nbsd_libc/softfloat/negtf2.c b/lib/nbsd_libc/softfloat/negtf2.c
new file mode 100644 (file)
index 0000000..16268bd
--- /dev/null
@@ -0,0 +1,29 @@
+/* $NetBSD: negtf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $ */
+
+/*
+ * Written by Matt Thomas, 2011.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: negtf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef FLOAT128
+
+float128 __negtf2(float128);
+
+float128
+__negtf2(float128 a)
+{
+
+       /* libgcc1.c says -a */
+       a.high ^= FLOAT64_MANGLE(0x8000000000000000ULL);
+       return a;
+}
+
+#endif /* FLOAT128 */
diff --git a/lib/nbsd_libc/softfloat/negxf2.c b/lib/nbsd_libc/softfloat/negxf2.c
new file mode 100644 (file)
index 0000000..e8eb7b9
--- /dev/null
@@ -0,0 +1,27 @@
+/* $NetBSD: negxf2.c,v 1.2 2004/09/27 10:16:24 he Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: negxf2.c,v 1.2 2004/09/27 10:16:24 he Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef FLOATX80
+
+floatx80 __negxf2(floatx80);
+
+floatx80
+__negxf2(floatx80 a)
+{
+
+       /* libgcc1.c says -a */
+       return __mulxf3(a,__floatsixf(-1));
+}
+#endif /* FLOATX80 */
diff --git a/lib/nbsd_libc/softfloat/nesf2.c b/lib/nbsd_libc/softfloat/nesf2.c
new file mode 100644 (file)
index 0000000..97d7e73
--- /dev/null
@@ -0,0 +1,24 @@
+/* $NetBSD: nesf2.c,v 1.1 2000/06/06 08:15:07 bjh21 Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nesf2.c,v 1.1 2000/06/06 08:15:07 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+flag __nesf2(float32, float32);
+
+flag
+__nesf2(float32 a, float32 b)
+{
+
+       /* libgcc1.c says a != b */
+       return !float32_eq(a, b);
+}
diff --git a/lib/nbsd_libc/softfloat/netf2.c b/lib/nbsd_libc/softfloat/netf2.c
new file mode 100644 (file)
index 0000000..5481d79
--- /dev/null
@@ -0,0 +1,28 @@
+/* $NetBSD: netf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $ */
+
+/*
+ * Written by Matt Thomas, 2011.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: netf2.c,v 1.1 2011/01/17 10:08:35 matt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef FLOAT128
+
+flag __netf2(float128, float128);
+
+flag
+__netf2(float128 a, float128 b)
+{
+
+       /* libgcc1.c says a != b */
+       return !float128_eq(a, b);
+}
+
+#endif /* FLOAT128 */
diff --git a/lib/nbsd_libc/softfloat/nexf2.c b/lib/nbsd_libc/softfloat/nexf2.c
new file mode 100644 (file)
index 0000000..ee8d86f
--- /dev/null
@@ -0,0 +1,27 @@
+/* $NetBSD: nexf2.c,v 1.2 2004/09/27 10:16:24 he Exp $ */
+
+/*
+ * Written by Ben Harris, 2000.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nexf2.c,v 1.2 2004/09/27 10:16:24 he Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef FLOATX80
+
+flag __nexf2(floatx80, floatx80);
+
+flag
+__nexf2(floatx80 a, floatx80 b)
+{
+
+       /* libgcc1.c says a != b */
+       return !floatx80_eq(a, b);
+}
+#endif /* FLOATX80 */
diff --git a/lib/nbsd_libc/softfloat/softfloat-for-gcc.h b/lib/nbsd_libc/softfloat/softfloat-for-gcc.h
new file mode 100644 (file)
index 0000000..665cdc4
--- /dev/null
@@ -0,0 +1,169 @@
+/* $NetBSD: softfloat-for-gcc.h,v 1.8 2009/12/14 01:07:42 matt Exp $ */
+
+/*
+ * Move private identifiers with external linkage into implementation
+ * namespace.  -- Klaus Klein <kleink@NetBSD.org>, May 5, 1999
+ */
+#define float_exception_flags  _softfloat_float_exception_flags
+#define float_exception_mask   _softfloat_float_exception_mask
+#define float_rounding_mode    _softfloat_float_rounding_mode
+#define float_raise            _softfloat_float_raise
+
+/* The following batch are called by GCC through wrappers */
+#define float32_eq             _softfloat_float32_eq
+#define float32_le             _softfloat_float32_le
+#define float32_lt             _softfloat_float32_lt
+#define float64_eq             _softfloat_float64_eq
+#define float64_le             _softfloat_float64_le
+#define float64_lt             _softfloat_float64_lt
+#define float128_eq            _softfloat_float128_eq
+#define float128_le            _softfloat_float128_le
+#define float128_lt            _softfloat_float128_lt
+
+/*
+ * Macros to define functions with the GCC expected names
+ */
+
+#define float32_add                    __addsf3
+#define float64_add                    __adddf3
+#define floatx80_add                   __addxf3
+#define float128_add                   __addtf3
+
+#define float32_sub                    __subsf3
+#define float64_sub                    __subdf3
+#define floatx80_sub                   __subxf3
+#define float128_sub                   __subtf3
+
+#define float32_mul                    __mulsf3
+#define float64_mul                    __muldf3
+#define floatx80_mul                   __mulxf3
+#define float128_mul                   __multf3
+
+#define float32_div                    __divsf3
+#define float64_div                    __divdf3
+#define floatx80_div                   __divxf3
+#define float128_div                   __divtf3
+
+#if 0
+#define float32_neg                    __negsf2
+#define float64_neg                    __negdf2
+#define floatx80_neg                   __negxf2
+#define float128_neg                   __negtf2
+#endif
+
+#define int32_to_float32               __floatsisf
+#define int32_to_float64               __floatsidf
+#define int32_to_floatx80              __floatsixf
+#define int32_to_float128              __floatsitf
+
+#define int64_to_float32               __floatdisf
+#define int64_to_float64               __floatdidf
+#define int64_to_floatx80              __floatdixf
+#define int64_to_float128              __floatditf
+
+#define int128_to_float32              __floattisf
+#define int128_to_float64              __floattidf
+#define int128_to_floatx80             __floattixf
+#define int128_to_float128             __floattitf
+
+#define uint32_to_float32              __floatunsisf
+#define uint32_to_float64              __floatunsidf
+#define uint32_to_floatx80             __floatunsixf
+#define uint32_to_float128             __floatunsitf
+
+#define uint64_to_float32              __floatundisf
+#define uint64_to_float64              __floatundidf
+#define uint64_to_floatx80             __floatundixf
+#define uint64_to_float128             __floatunditf
+
+#define uint128_to_float32             __floatuntisf
+#define uint128_to_float64             __floatuntidf
+#define uint128_to_floatx80            __floatuntixf
+#define uint128_to_float128            __floatuntitf
+
+#define float32_to_int32_round_to_zero __fixsfsi
+#define float64_to_int32_round_to_zero __fixdfsi
+#define floatx80_to_int32_round_to_zero __fixxfsi
+#define float128_to_int32_round_to_zero __fixtfsi
+
+#define float32_to_int64_round_to_zero __fixsfdi
+#define float64_to_int64_round_to_zero __fixdfdi
+#define floatx80_to_int64_round_to_zero        __fixxfdi
+#define float128_to_int64_round_to_zero        __fixtfdi
+
+#define float32_to_int128_round_to_zero __fixsfti
+#define float64_to_int128_round_to_zero __fixdfti
+#define floatx80_to_int128_round_to_zero __fixxfti
+#define float128_to_int128_round_to_zero __fixtfti
+
+#define float32_to_uint32_round_to_zero        __fixunssfsi
+#define float64_to_uint32_round_to_zero        __fixunsdfsi
+#define floatx80_to_uint32_round_to_zero       __fixunsxfsi
+#define float128_to_uint32_round_to_zero       __fixunstfsi
+
+#define float32_to_uint64_round_to_zero        __fixunssfdi
+#define float64_to_uint64_round_to_zero        __fixunsdfdi
+#define floatx80_to_uint64_round_to_zero       __fixunsxfdi
+#define float128_to_uint64_round_to_zero       __fixunstfdi
+
+#define float32_to_uint128_round_to_zero       __fixunssfti
+#define float64_to_uint128_round_to_zero       __fixunsdfti
+#define floatx80_to_uint128_round_to_zero      __fixunsxfti
+#define float128_to_uint128_round_to_zero      __fixunstfti
+
+#define float32_to_float64             __extendsfdf2
+#define float32_to_floatx80            __extendsfxf2
+#define float32_to_float128            __extendsftf2
+#define float64_to_floatx80            __extenddfxf2
+#define float64_to_float128            __extenddftf2
+
+#define float128_to_float64            __trunctfdf2
+#define floatx80_to_float64            __truncxfdf2
+#define float128_to_float32            __trunctfsf2
+#define floatx80_to_float32            __truncxfsf2
+#define float64_to_float32             __truncdfsf2
+
+#if 0
+#define float32_cmp                    __cmpsf2
+#define float32_unord                  __unordsf2
+#define float32_eq                     __eqsf2
+#define float32_ne                     __nesf2
+#define float32_ge                     __gesf2
+#define float32_lt                     __ltsf2
+#define float32_le                     __lesf2
+#define float32_gt                     __gtsf2
+#endif
+
+#if 0
+#define float64_cmp                    __cmpdf2
+#define float64_unord                  __unorddf2
+#define float64_eq                     __eqdf2
+#define float64_ne                     __nedf2
+#define float64_ge                     __gedf2
+#define float64_lt                     __ltdf2
+#define float64_le                     __ledf2
+#define float64_gt                     __gtdf2
+#endif
+
+/* XXX not in libgcc */
+#if 1
+#define floatx80_cmp                   __cmpxf2
+#define floatx80_unord                 __unordxf2
+#define floatx80_eq                    __eqxf2
+#define floatx80_ne                    __nexf2
+#define floatx80_ge                    __gexf2
+#define floatx80_lt                    __ltxf2
+#define floatx80_le                    __lexf2
+#define floatx80_gt                    __gtxf2
+#endif
+
+#if 0
+#define float128_cmp                   __cmptf2
+#define float128_unord                 __unordtf2
+#define float128_eq                    __eqtf2
+#define float128_ne                    __netf2
+#define float128_ge                    __getf2
+#define float128_lt                    __lttf2
+#define float128_le                    __letf2
+#define float128_gt                    __gttf2
+#endif
diff --git a/lib/nbsd_libc/softfloat/softfloat-history.txt b/lib/nbsd_libc/softfloat/softfloat-history.txt
new file mode 100644 (file)
index 0000000..14fe066
--- /dev/null
@@ -0,0 +1,52 @@
+$NetBSD: softfloat-history.txt,v 1.1 2000/06/06 08:15:08 bjh21 Exp $
+
+History of Major Changes to SoftFloat, up to Release 2a
+
+John R. Hauser
+1998 December 16
+
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+Release 2a (1998 December)
+
+-- Added functions to convert between 64-bit integers (int64) and all
+   supported floating-point formats.
+
+-- Fixed a bug in all 64-bit-version square root functions except
+   `float32_sqrt' that caused the result sometimes to be off by 1 unit in
+   the last place (1 ulp) from what it should be.  (Bug discovered by Paul
+   Donahue.)
+
+-- Improved the makefiles.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+Release 2 (1997 June)
+
+-- Created the 64-bit (bits64) version, adding the floatx80 and float128
+   formats.
+
+-- Changed the source directory structure, splitting the sources into a
+   `bits32' and a `bits64' version.  Renamed `environment.h' to `milieu.h'
+   (to avoid confusion with environment variables).
+
+-- Fixed a small error that caused `float64_round_to_int' often to round the
+   wrong way in nearest/even mode when the operand was between 2^20 and 2^21
+   and halfway between two integers.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+Release 1a (1996 July)
+
+-- Corrected a mistake that caused borderline underflow cases not to raise
+   the underflow flag when they should have.  (Problem reported by Doug
+   Priest.)
+
+-- Added the `float_detect_tininess' variable to control whether tininess is
+   detected before or after rounding.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+Release 1 (1996 July)
+
+-- Original release.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
diff --git a/lib/nbsd_libc/softfloat/softfloat-source.txt b/lib/nbsd_libc/softfloat/softfloat-source.txt
new file mode 100644 (file)
index 0000000..49de2e0
--- /dev/null
@@ -0,0 +1,383 @@
+$NetBSD: softfloat-source.txt,v 1.2 2006/11/24 19:46:58 christos Exp $
+
+SoftFloat Release 2a Source Documentation
+
+John R. Hauser
+1998 December 14
+
+
+-------------------------------------------------------------------------------
+Introduction
+
+SoftFloat is a software implementation of floating-point that conforms to
+the IEC/IEEE Standard for Binary Floating-Point Arithmetic.  SoftFloat can
+support four floating-point formats:  single precision, double precision,
+extended double precision, and quadruple precision.  All operations required
+by the IEEE Standard are implemented, except for conversions to and from
+decimal.  SoftFloat is distributed in the form of C source code, so a
+C compiler is needed to compile the code.  Support for the extended double-
+precision and quadruple-precision formats is dependent on the C compiler
+implementing a 64-bit integer type.
+
+This document gives information needed for compiling and/or porting
+SoftFloat.
+
+The source code for SoftFloat is intended to be relatively machine-
+independent and should be compilable using any ISO/ANSI C compiler.  At the
+time of this writing, SoftFloat has been successfully compiled with the GNU
+C Compiler (`gcc') for several platforms.
+
+
+-------------------------------------------------------------------------------
+Limitations
+
+SoftFloat as written requires an ISO/ANSI-style C compiler.  No attempt has
+been made to accommodate compilers that are not ISO-conformant.  Older ``K&R-
+style'' compilers are not adequate for compiling SoftFloat.  All testing I
+have done so far has been with the GNU C Compiler.  Compilation with other
+compilers should be possible but has not been tested.
+
+The SoftFloat sources assume that source code file names can be longer than
+8 characters.  In order to compile under an MS-DOS-type system, many of the
+source files will need to be renamed, and the source and makefiles edited
+appropriately.  Once compiled, the SoftFloat binary does not depend on the
+existence of long file names.
+
+The underlying machine is assumed to be binary with a word size that is a
+power of 2.  Bytes are 8 bits.  Support for the extended double-precision
+and quadruple-precision formats depends on the C compiler implementing
+a 64-bit integer type.  If the largest integer type supported by the
+C compiler is 32 bits, SoftFloat is limited to the single- and double-
+precision formats.
+
+
+-------------------------------------------------------------------------------
+Contents
+
+    Introduction
+    Limitations
+    Contents
+    Legal Notice
+    SoftFloat Source Directory Structure
+    SoftFloat Source Files
+        processors/*.h
+        softfloat/bits*/*/softfloat.h
+        softfloat/bits*/*/milieu.h
+        softfloat/bits*/*/softfloat-specialize
+        softfloat/bits*/softfloat-macros
+        softfloat/bits*/softfloat.c
+    Steps to Creating a `softfloat.o'
+    Making `softfloat.o' a Library
+    Testing SoftFloat
+    Timing SoftFloat
+    Compiler Options and Efficiency
+    Processor-Specific Optimization of `softfloat.c' Using `softfloat-macros'
+    Contact Information
+
+
+
+-------------------------------------------------------------------------------
+Legal Notice
+
+SoftFloat was written by John R. Hauser.  This work was made possible in
+part by the International Computer Science Institute, located at Suite 600,
+1947 Center Street, Berkeley, California 94704.  Funding was partially
+provided by the National Science Foundation under grant MIP-9311980.  The
+original version of this code was written as part of a project to build
+a fixed-point vector processor in collaboration with the University of
+California at Berkeley, overseen by Profs. Nelson Morgan and John Wawrzynek.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+
+-------------------------------------------------------------------------------
+SoftFloat Source Directory Structure
+
+Because SoftFloat is targeted to multiple platforms, its source code
+is slightly scattered between target-specific and target-independent
+directories and files.  The directory structure is as follows:
+
+    processors
+    softfloat
+        bits64
+            templates
+            386-Win32-gcc
+            SPARC-Solaris-gcc
+        bits32
+            templates
+            386-Win32-gcc
+            SPARC-Solaris-gcc
+
+The two topmost directories and their contents are:
+
+    softfloat    - Most of the source code needed for SoftFloat.
+    processors   - Target-specific header files that are not specific to
+                       SoftFloat.
+
+The `softfloat' directory is further split into two parts:
+
+    bits64       - SoftFloat implementation using 64-bit integers.
+    bits32       - SoftFloat implementation using only 32-bit integers.
+
+Within these directories are subdirectories for each of the targeted
+platforms.  The SoftFloat source code is distributed with targets
+`386-Win32-gcc' and `SPARC-Solaris-gcc' (and perhaps others) already
+prepared for both the 32-bit and 64-bit implementations.  Source files that
+are not within these target-specific subdirectories are intended to be
+target-independent.
+
+The naming convention used for the target-specific directories is
+`<processor>-<executable-type>-<compiler>'.  The names of the supplied
+target directories should be interpreted as follows:
+
+  <processor>:
+    386          - Intel 386-compatible processor.
+    SPARC        - SPARC processor (as used by Sun machines).
+  <executable-type>:
+    Win32        - Microsoft Win32 executable.
+    Solaris      - Sun Solaris executable.
+  <compiler>:
+    gcc          - GNU C Compiler.
+
+You do not need to maintain this convention if you do not want to.
+
+Alongside the supplied target-specific directories is a `templates'
+directory containing a set of ``generic'' target-specific source files.  A
+new target directory can be created by copying the `templates' directory and
+editing the files inside.  (Complete instructions for porting SoftFloat to a
+new target are in the section _Steps_to_Creating_a_`softfloat.o'_.)  Note
+that the `templates' directory will not work as a target directory without
+some editing.  To avoid confusion, it would be wise to refrain from editing
+the files inside `templates' directly.
+
+
+-------------------------------------------------------------------------------
+SoftFloat Source Files
+
+The purpose of each source file is described below.  In the following,
+the `*' symbol is used in place of the name of a specific target, such as
+`386-Win32-gcc' or `SPARC-Solaris-gcc', or in place of some other text, as
+in `bits*' for either `bits32' or `bits64'.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+processors/*.h
+
+The target-specific `processors' header file defines integer types
+of various sizes, and also defines certain C preprocessor macros that
+characterize the target.  The two examples supplied are `386-gcc.h' and
+`SPARC-gcc.h'.  The naming convention used for processor header files is
+`<processor>-<compiler>.h'.
+
+If 64-bit integers are supported by the compiler, the macro name `BITS64'
+should be defined here along with the corresponding 64-bit integer
+types.  In addition, the function-like macro `LIT64' must be defined for
+constructing 64-bit integer literals (constants).  The `LIT64' macro is used
+consistently in the SoftFloat code to annotate 64-bit literals.
+
+If `BITS64' is not defined, only the 32-bit version of SoftFloat can be
+compiled.  If `BITS64' _is_ defined, either can be compiled.
+
+If an inlining attribute (such as an `inline' keyword) is provided by the
+compiler, the macro `INLINE' should be defined to the appropriate keyword.
+If not, `INLINE' can be set to the keyword `static'.  The `INLINE' macro
+appears in the SoftFloat source code before every function that should
+be inlined by the compiler.  SoftFloat depends on inlining to obtain
+good speed.  Even if inlining cannot be forced with a language keyword,
+the compiler may still be able to perform inlining on its own as an
+optimization.  If a command-line option is needed to convince the compiler
+to perform this optimization, this should be assured in the makefile.  (See
+the section _Compiler_Options_and_Efficiency_ below.)
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+softfloat/bits*/*/softfloat.h
+
+The target-specific `softfloat.h' header file defines the SoftFloat
+interface as seen by clients.
+
+Unlike the actual function definitions in `softfloat.c', the declarations
+in `softfloat.h' do not use any of the types defined by the `processors'
+header file.  This is done so that clients will not have to include the
+`processors' header file in order to use SoftFloat.  Nevertheless, the
+target-specific declarations in `softfloat.h' must match what `softfloat.c'
+expects.  For example, if `int32' is defined as `int' in the `processors'
+header file, then in `softfloat.h' the output of `float32_to_int32' should
+be stated as `int', although in `softfloat.c' it is given in target-
+independent form as `int32'.
+
+For the `bits64' implementation of SoftFloat, the macro names `FLOATX80' and
+`FLOAT128' must be defined in order for the extended double-precision and
+quadruple-precision formats to be enabled in the code.  Conversely, either
+or both of the extended formats can be disabled by simply removing the
+`#define' of the respective macro.  When an extended format is not enabled,
+none of the functions that either input or output the format are defined,
+and no space is taken up in `softfloat.o' by such functions.  There is no
+provision for disabling the usual single- and double-precision formats.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+softfloat/bits*/*/milieu.h
+
+The target-specific `milieu.h' header file provides declarations that are
+needed to compile SoftFloat.  In addition, deviations from ISO/ANSI C by
+the compiler (such as names not properly declared in system header files)
+are corrected in this header if possible.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+softfloat/bits*/*/softfloat-specialize
+
+This target-specific C source fragment defines:
+
+-- whether tininess for underflow is detected before or after rounding by
+       default;
+-- what (if anything) special happens when exceptions are raised;
+-- how signaling NaNs are distinguished from quiet NaNs;
+-- the default generated quiet NaNs; and
+-- how NaNs are propagated from function inputs to output.
+
+These details are not decided by the IEC/IEEE Standard.  This fragment is
+included verbatim within `softfloat.c' when SoftFloat is compiled.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+softfloat/bits*/softfloat-macros
+
+This target-independent C source fragment defines a number of arithmetic
+functions used as primitives within the `softfloat.c' source.  Most of the
+functions defined here are intended to be inlined for efficiency.  This
+fragment is included verbatim within `softfloat.c' when SoftFloat is
+compiled.
+
+Target-specific variations on this file are possible.  See the section
+_Processor-Specific_Optimization_of_`softfloat.c'_Using_`softfloat-macros'_
+below.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+softfloat/bits*/softfloat.c
+
+The target-independent `softfloat.c' source file contains the body of the
+SoftFloat implementation.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+The inclusion of the files above within each other (using `#include') can be
+shown graphically as follows:
+
+    softfloat/bits*/softfloat.c
+        softfloat/bits*/*/milieu.h
+            processors/*.h
+        softfloat/bits*/*/softfloat.h
+        softfloat/bits*/*/softfloat-specialize
+        softfloat/bits*/softfloat-macros
+
+Note in particular that `softfloat.c' does not include the `processors'
+header file directly.  Rather, `softfloat.c' includes the target-specific
+`milieu.h' header file, which in turn includes the processor header file.
+
+
+-------------------------------------------------------------------------------
+Steps to Creating a `softfloat.o'
+
+Porting and/or compiling SoftFloat involves the following steps:
+
+1. If one does not already exist, create an appropriate `.h' file in the
+   `processors' directory.
+
+2. If `BITS64' is defined in the `processors' header file, choose whether
+   to compile the 32-bit or 64-bit implementation of SoftFloat.  If
+   `BITS64' is not defined, your only choice is the 32-bit implementation.
+   The remaining steps occur within either the `bits32' or `bits64'
+   subdirectories.
+
+3. If one does not already exist, create an appropriate target-specific
+   subdirectory by copying the given `templates' directory.
+
+4. In the target-specific subdirectory, edit the files `softfloat-specialize'
+   and `softfloat.h' to define the desired exception handling functions
+   and mode control values.  In the `softfloat.h' header file, ensure also
+   that all declarations give the proper target-specific type (such as
+   `int' or `long') corresponding to the target-independent type used in
+   `softfloat.c' (such as `int32').  None of the type names declared in the
+   `processors' header file should appear in `softfloat.h'.
+
+5. In the target-specific subdirectory, edit the files `milieu.h' and
+   `Makefile' to reflect the current environment.
+
+6. In the target-specific subdirectory, execute `make'.
+
+For the targets that are supplied, if the expected compiler is available
+(usually `gcc'), it should only be necessary to execute `make' in the
+target-specific subdirectory.
+
+
+-------------------------------------------------------------------------------
+Making `softfloat.o' a Library
+
+SoftFloat is not made into a software library by the supplied makefile.
+If desired, `softfloat.o' can easily be put into its own library (in Unix,
+`softfloat.a') using the usual system tool (in Unix, `ar').
+
+
+-------------------------------------------------------------------------------
+Testing SoftFloat
+
+SoftFloat can be tested using the `testsoftfloat' program by the same
+author.  The `testsoftfloat' program is part of the TestFloat package
+available at the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/arithmetic/
+TestFloat.html'.
+
+
+-------------------------------------------------------------------------------
+Timing SoftFloat
+
+A program called `timesoftfloat' for timing the SoftFloat functions is
+included with the SoftFloat source code.  Compiling `timesoftfloat' should
+pose no difficulties once `softfloat.o' exists.  The supplied makefile
+will create a `timesoftfloat' executable by default after generating
+`softfloat.o'.  See `timesoftfloat.txt' for documentation about using
+`timesoftfloat'.
+
+
+-------------------------------------------------------------------------------
+Compiler Options and Efficiency
+
+In order to get good speed with SoftFloat, it is important that the compiler
+inline the routines that have been marked `INLINE' in the code.  Even if
+inlining cannot be forced by an appropriate definition of the `INLINE'
+macro, the compiler may still be able to perform inlining on its own as
+an optimization.  In that case, the makefile should be edited to give the
+compiler whatever option is required to cause it to inline small functions.
+
+The ability of the processor to do fast shifts has been assumed.  Efficiency
+will not be as good on processors for which this is not the case (such as
+the original Motorola 68000 or Intel 8086 processors).
+
+
+-------------------------------------------------------------------------------
+Processor-Specific Optimization of `softfloat.c' Using `softfloat-macros'
+
+The `softfloat-macros' source fragment defines arithmetic functions used
+as primitives by `softfloat.c'.  This file has been written in a target-
+independent form.  For a given target, it may be possible to improve on
+these functions using target-specific and/or non-ISO-C features (such
+as `asm' statements).  For example, one of the ``macro'' functions takes
+two word-size integers and returns their full product in two words.
+This operation can be done directly in hardware on many processors; but
+because it is not available through standard C, the function defined in
+`softfloat-macros' uses four multiplies to achieve the same result.
+
+To address these shortcomings, a customized version of `softfloat-macros'
+can be created in any of the target-specific subdirectories.  A simple
+modification to the target's makefile should be sufficient to ensure that
+the custom version is used instead of the generic one.
+
+
+-------------------------------------------------------------------------------
+Contact Information
+
+At the time of this writing, the most up-to-date information about
+SoftFloat and the latest release can be found at the Web page `http://
+HTTP.CS.Berkeley.EDU/~jhauser/arithmetic/SoftFloat.html'.
+
+
diff --git a/lib/nbsd_libc/softfloat/softfloat-specialize b/lib/nbsd_libc/softfloat/softfloat-specialize
new file mode 100644 (file)
index 0000000..b9853e4
--- /dev/null
@@ -0,0 +1,491 @@
+/*     $NetBSD: softfloat-specialize,v 1.4 2004/09/26 21:13:27 jmmv Exp $      */
+
+/* This is a derivative work. */
+
+/*
+===============================================================================
+
+This C source fragment is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+#include <signal.h>
+
+/*
+-------------------------------------------------------------------------------
+Underflow tininess-detection mode, statically initialized to default value.
+(The declaration in `softfloat.h' must match the `int8' type here.)
+-------------------------------------------------------------------------------
+*/
+#ifdef SOFTFLOAT_FOR_GCC
+static
+#endif
+int8 float_detect_tininess = float_tininess_after_rounding;
+
+/*
+-------------------------------------------------------------------------------
+Raises the exceptions specified by `flags'.  Floating-point traps can be
+defined here if desired.  It is currently not possible for such a trap to
+substitute a result value.  If traps are not implemented, this routine
+should be simply `float_exception_flags |= flags;'.
+-------------------------------------------------------------------------------
+*/
+fp_except float_exception_mask = 0;
+void float_raise( fp_except flags )
+{
+
+    float_exception_flags |= flags;
+
+    if ( flags & float_exception_mask ) {
+       raise( SIGFPE );
+    }
+}
+
+/*
+-------------------------------------------------------------------------------
+Internal canonical NaN format.
+-------------------------------------------------------------------------------
+*/
+typedef struct {
+    flag sign;
+    bits64 high, low;
+} commonNaNT;
+
+/*
+-------------------------------------------------------------------------------
+The pattern for a default generated single-precision NaN.
+-------------------------------------------------------------------------------
+*/
+#define float32_default_nan 0xFFFFFFFF
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is a NaN;
+otherwise returns 0.
+-------------------------------------------------------------------------------
+*/
+#ifdef SOFTFLOAT_FOR_GCC
+static
+#endif
+flag float32_is_nan( float32 a )
+{
+
+    return ( 0xFF000000 < (bits32) ( a<<1 ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the single-precision floating-point value `a' is a signaling
+NaN; otherwise returns 0.
+-------------------------------------------------------------------------------
+*/
+#if defined(SOFTFLOAT_FOR_GCC) && !defined(SOFTFLOATSPARC64_FOR_GCC) && \
+    !defined(SOFTFLOAT_M68K_FOR_GCC)
+static
+#endif
+flag float32_is_signaling_nan( float32 a )
+{
+
+    return ( ( ( a>>22 ) & 0x1FF ) == 0x1FE ) && ( a & 0x003FFFFF );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the single-precision floating-point NaN
+`a' to the canonical NaN format.  If `a' is a signaling NaN, the invalid
+exception is raised.
+-------------------------------------------------------------------------------
+*/
+static commonNaNT float32ToCommonNaN( float32 a )
+{
+    commonNaNT z;
+
+    if ( float32_is_signaling_nan( a ) ) float_raise( float_flag_invalid );
+    z.sign = a>>31;
+    z.low = 0;
+    z.high = ( (bits64) a )<<41;
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the canonical NaN `a' to the single-
+precision floating-point format.
+-------------------------------------------------------------------------------
+*/
+static float32 commonNaNToFloat32( commonNaNT a )
+{
+
+    return ( ( (bits32) a.sign )<<31 ) | 0x7FC00000 | ( a.high>>41 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes two single-precision floating-point values `a' and `b', one of which
+is a NaN, and returns the appropriate NaN result.  If either `a' or `b' is a
+signaling NaN, the invalid exception is raised.
+-------------------------------------------------------------------------------
+*/
+static float32 propagateFloat32NaN( float32 a, float32 b )
+{
+    flag aIsNaN, aIsSignalingNaN, bIsNaN, bIsSignalingNaN;
+
+    aIsNaN = float32_is_nan( a );
+    aIsSignalingNaN = float32_is_signaling_nan( a );
+    bIsNaN = float32_is_nan( b );
+    bIsSignalingNaN = float32_is_signaling_nan( b );
+    a |= 0x00400000;
+    b |= 0x00400000;
+    if ( aIsSignalingNaN | bIsSignalingNaN ) float_raise( float_flag_invalid );
+    if ( aIsNaN ) {
+        return ( aIsSignalingNaN & bIsNaN ) ? b : a;
+    }
+    else {
+        return b;
+    }
+
+}
+
+/*
+-------------------------------------------------------------------------------
+The pattern for a default generated double-precision NaN.
+-------------------------------------------------------------------------------
+*/
+#define float64_default_nan LIT64( 0xFFFFFFFFFFFFFFFF )
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is a NaN;
+otherwise returns 0.
+-------------------------------------------------------------------------------
+*/
+#ifdef SOFTFLOAT_FOR_GCC
+static
+#endif
+flag float64_is_nan( float64 a )
+{
+
+    return ( LIT64( 0xFFE0000000000000 ) <
+            (bits64) ( FLOAT64_DEMANGLE(a)<<1 ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the double-precision floating-point value `a' is a signaling
+NaN; otherwise returns 0.
+-------------------------------------------------------------------------------
+*/
+#if defined(SOFTFLOAT_FOR_GCC) && !defined(SOFTFLOATSPARC64_FOR_GCC) && \
+    !defined(SOFTFLOATM68K_FOR_GCC)
+static
+#endif
+flag float64_is_signaling_nan( float64 a )
+{
+
+    return
+           ( ( ( FLOAT64_DEMANGLE(a)>>51 ) & 0xFFF ) == 0xFFE )
+        && ( FLOAT64_DEMANGLE(a) & LIT64( 0x0007FFFFFFFFFFFF ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the double-precision floating-point NaN
+`a' to the canonical NaN format.  If `a' is a signaling NaN, the invalid
+exception is raised.
+-------------------------------------------------------------------------------
+*/
+static commonNaNT float64ToCommonNaN( float64 a )
+{
+    commonNaNT z;
+
+    if ( float64_is_signaling_nan( a ) ) float_raise( float_flag_invalid );
+    z.sign = FLOAT64_DEMANGLE(a)>>63;
+    z.low = 0;
+    z.high = FLOAT64_DEMANGLE(a)<<12;
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the canonical NaN `a' to the double-
+precision floating-point format.
+-------------------------------------------------------------------------------
+*/
+static float64 commonNaNToFloat64( commonNaNT a )
+{
+
+    return FLOAT64_MANGLE(
+       ( ( (bits64) a.sign )<<63 )
+        | LIT64( 0x7FF8000000000000 )
+        | ( a.high>>12 ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes two double-precision floating-point values `a' and `b', one of which
+is a NaN, and returns the appropriate NaN result.  If either `a' or `b' is a
+signaling NaN, the invalid exception is raised.
+-------------------------------------------------------------------------------
+*/
+static float64 propagateFloat64NaN( float64 a, float64 b )
+{
+    flag aIsNaN, aIsSignalingNaN, bIsNaN, bIsSignalingNaN;
+
+    aIsNaN = float64_is_nan( a );
+    aIsSignalingNaN = float64_is_signaling_nan( a );
+    bIsNaN = float64_is_nan( b );
+    bIsSignalingNaN = float64_is_signaling_nan( b );
+    a |= FLOAT64_MANGLE(LIT64( 0x0008000000000000 ));
+    b |= FLOAT64_MANGLE(LIT64( 0x0008000000000000 ));
+    if ( aIsSignalingNaN | bIsSignalingNaN ) float_raise( float_flag_invalid );
+    if ( aIsNaN ) {
+        return ( aIsSignalingNaN & bIsNaN ) ? b : a;
+    }
+    else {
+        return b;
+    }
+
+}
+
+#ifdef FLOATX80
+
+/*
+-------------------------------------------------------------------------------
+The pattern for a default generated extended double-precision NaN.  The
+`high' and `low' values hold the most- and least-significant bits,
+respectively.
+-------------------------------------------------------------------------------
+*/
+#define floatx80_default_nan_high 0xFFFF
+#define floatx80_default_nan_low  LIT64( 0xFFFFFFFFFFFFFFFF )
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the extended double-precision floating-point value `a' is a
+NaN; otherwise returns 0.
+-------------------------------------------------------------------------------
+*/
+flag floatx80_is_nan( floatx80 a )
+{
+
+    return ( ( a.high & 0x7FFF ) == 0x7FFF ) && (bits64) ( a.low<<1 );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the extended double-precision floating-point value `a' is a
+signaling NaN; otherwise returns 0.
+-------------------------------------------------------------------------------
+*/
+flag floatx80_is_signaling_nan( floatx80 a )
+{
+    bits64 aLow;
+
+    aLow = a.low & ~ LIT64( 0x4000000000000000 );
+    return
+           ( ( a.high & 0x7FFF ) == 0x7FFF )
+        && (bits64) ( aLow<<1 )
+        && ( a.low == aLow );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the extended double-precision floating-
+point NaN `a' to the canonical NaN format.  If `a' is a signaling NaN, the
+invalid exception is raised.
+-------------------------------------------------------------------------------
+*/
+static commonNaNT floatx80ToCommonNaN( floatx80 a )
+{
+    commonNaNT z;
+
+    if ( floatx80_is_signaling_nan( a ) ) float_raise( float_flag_invalid );
+    z.sign = a.high>>15;
+    z.low = 0;
+    z.high = a.low<<1;
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the canonical NaN `a' to the extended
+double-precision floating-point format.
+-------------------------------------------------------------------------------
+*/
+static floatx80 commonNaNToFloatx80( commonNaNT a )
+{
+    floatx80 z;
+
+    z.low = LIT64( 0xC000000000000000 ) | ( a.high>>1 );
+    z.high = ( ( (bits16) a.sign )<<15 ) | 0x7FFF;
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes two extended double-precision floating-point values `a' and `b', one
+of which is a NaN, and returns the appropriate NaN result.  If either `a' or
+`b' is a signaling NaN, the invalid exception is raised.
+-------------------------------------------------------------------------------
+*/
+static floatx80 propagateFloatx80NaN( floatx80 a, floatx80 b )
+{
+    flag aIsNaN, aIsSignalingNaN, bIsNaN, bIsSignalingNaN;
+
+    aIsNaN = floatx80_is_nan( a );
+    aIsSignalingNaN = floatx80_is_signaling_nan( a );
+    bIsNaN = floatx80_is_nan( b );
+    bIsSignalingNaN = floatx80_is_signaling_nan( b );
+    a.low |= LIT64( 0xC000000000000000 );
+    b.low |= LIT64( 0xC000000000000000 );
+    if ( aIsSignalingNaN | bIsSignalingNaN ) float_raise( float_flag_invalid );
+    if ( aIsNaN ) {
+        return ( aIsSignalingNaN & bIsNaN ) ? b : a;
+    }
+    else {
+        return b;
+    }
+
+}
+
+#endif
+
+#ifdef FLOAT128
+
+/*
+-------------------------------------------------------------------------------
+The pattern for a default generated quadruple-precision NaN.  The `high' and
+`low' values hold the most- and least-significant bits, respectively.
+-------------------------------------------------------------------------------
+*/
+#define float128_default_nan_high LIT64( 0xFFFFFFFFFFFFFFFF )
+#define float128_default_nan_low  LIT64( 0xFFFFFFFFFFFFFFFF )
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the quadruple-precision floating-point value `a' is a NaN;
+otherwise returns 0.
+-------------------------------------------------------------------------------
+*/
+flag float128_is_nan( float128 a )
+{
+
+    return
+           ( LIT64( 0xFFFE000000000000 ) <= (bits64) ( a.high<<1 ) )
+        && ( a.low || ( a.high & LIT64( 0x0000FFFFFFFFFFFF ) ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns 1 if the quadruple-precision floating-point value `a' is a
+signaling NaN; otherwise returns 0.
+-------------------------------------------------------------------------------
+*/
+flag float128_is_signaling_nan( float128 a )
+{
+
+    return
+           ( ( ( a.high>>47 ) & 0xFFFF ) == 0xFFFE )
+        && ( a.low || ( a.high & LIT64( 0x00007FFFFFFFFFFF ) ) );
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the quadruple-precision floating-point NaN
+`a' to the canonical NaN format.  If `a' is a signaling NaN, the invalid
+exception is raised.
+-------------------------------------------------------------------------------
+*/
+static commonNaNT float128ToCommonNaN( float128 a )
+{
+    commonNaNT z;
+
+    if ( float128_is_signaling_nan( a ) ) float_raise( float_flag_invalid );
+    z.sign = a.high>>63;
+    shortShift128Left( a.high, a.low, 16, &z.high, &z.low );
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Returns the result of converting the canonical NaN `a' to the quadruple-
+precision floating-point format.
+-------------------------------------------------------------------------------
+*/
+static float128 commonNaNToFloat128( commonNaNT a )
+{
+    float128 z;
+
+    shift128Right( a.high, a.low, 16, &z.high, &z.low );
+    z.high |= ( ( (bits64) a.sign )<<63 ) | LIT64( 0x7FFF800000000000 );
+    return z;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+Takes two quadruple-precision floating-point values `a' and `b', one of
+which is a NaN, and returns the appropriate NaN result.  If either `a' or
+`b' is a signaling NaN, the invalid exception is raised.
+-------------------------------------------------------------------------------
+*/
+static float128 propagateFloat128NaN( float128 a, float128 b )
+{
+    flag aIsNaN, aIsSignalingNaN, bIsNaN, bIsSignalingNaN;
+
+    aIsNaN = float128_is_nan( a );
+    aIsSignalingNaN = float128_is_signaling_nan( a );
+    bIsNaN = float128_is_nan( b );
+    bIsSignalingNaN = float128_is_signaling_nan( b );
+    a.high |= LIT64( 0x0000800000000000 );
+    b.high |= LIT64( 0x0000800000000000 );
+    if ( aIsSignalingNaN | bIsSignalingNaN ) float_raise( float_flag_invalid );
+    if ( aIsNaN ) {
+        return ( aIsSignalingNaN & bIsNaN ) ? b : a;
+    }
+    else {
+        return b;
+    }
+
+}
+
+#endif
+
diff --git a/lib/nbsd_libc/softfloat/softfloat.txt b/lib/nbsd_libc/softfloat/softfloat.txt
new file mode 100644 (file)
index 0000000..a3ad43e
--- /dev/null
@@ -0,0 +1,372 @@
+$NetBSD: softfloat.txt,v 1.2 2006/11/24 19:46:58 christos Exp $
+
+SoftFloat Release 2a General Documentation
+
+John R. Hauser
+1998 December 13
+
+
+-------------------------------------------------------------------------------
+Introduction
+
+SoftFloat is a software implementation of floating-point that conforms to
+the IEC/IEEE Standard for Binary Floating-Point Arithmetic.  As many as four
+formats are supported:  single precision, double precision, extended double
+precision, and quadruple precision.  All operations required by the standard
+are implemented, except for conversions to and from decimal.
+
+This document gives information about the types defined and the routines
+implemented by SoftFloat.  It does not attempt to define or explain the
+IEC/IEEE Floating-Point Standard.  Details about the standard are available
+elsewhere.
+
+
+-------------------------------------------------------------------------------
+Limitations
+
+SoftFloat is written in C and is designed to work with other C code.  The
+SoftFloat header files assume an ISO/ANSI-style C compiler.  No attempt
+has been made to accommodate compilers that are not ISO-conformant.  In
+particular, the distributed header files will not be acceptable to any
+compiler that does not recognize function prototypes.
+
+Support for the extended double-precision and quadruple-precision formats
+depends on a C compiler that implements 64-bit integer arithmetic.  If the
+largest integer format supported by the C compiler is 32 bits, SoftFloat is
+limited to only single and double precisions.  When that is the case, all
+references in this document to the extended double precision, quadruple
+precision, and 64-bit integers should be ignored.
+
+
+-------------------------------------------------------------------------------
+Contents
+
+    Introduction
+    Limitations
+    Contents
+    Legal Notice
+    Types and Functions
+    Rounding Modes
+    Extended Double-Precision Rounding Precision
+    Exceptions and Exception Flags
+    Function Details
+        Conversion Functions
+        Standard Arithmetic Functions
+        Remainder Functions
+        Round-to-Integer Functions
+        Comparison Functions
+        Signaling NaN Test Functions
+        Raise-Exception Function
+    Contact Information
+
+
+
+-------------------------------------------------------------------------------
+Legal Notice
+
+SoftFloat was written by John R. Hauser.  This work was made possible in
+part by the International Computer Science Institute, located at Suite 600,
+1947 Center Street, Berkeley, California 94704.  Funding was partially
+provided by the National Science Foundation under grant MIP-9311980.  The
+original version of this code was written as part of a project to build
+a fixed-point vector processor in collaboration with the University of
+California at Berkeley, overseen by Profs. Nelson Morgan and John Wawrzynek.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+
+-------------------------------------------------------------------------------
+Types and Functions
+
+When 64-bit integers are supported by the compiler, the `softfloat.h' header
+file defines four types:  `float32' (single precision), `float64' (double
+precision), `floatx80' (extended double precision), and `float128'
+(quadruple precision).  The `float32' and `float64' types are defined in
+terms of 32-bit and 64-bit integer types, respectively, while the `float128'
+type is defined as a structure of two 64-bit integers, taking into account
+the byte order of the particular machine being used.  The `floatx80' type
+is defined as a structure containing one 16-bit and one 64-bit integer, with
+the machine's byte order again determining the order of the `high' and `low'
+fields.
+
+When 64-bit integers are _not_ supported by the compiler, the `softfloat.h'
+header file defines only two types:  `float32' and `float64'.  Because
+ISO/ANSI C guarantees at least one built-in integer type of 32 bits,
+the `float32' type is identified with an appropriate integer type.  The
+`float64' type is defined as a structure of two 32-bit integers, with the
+machine's byte order determining the order of the fields.
+
+In either case, the types in `softfloat.h' are defined such that if a system
+implements the usual C `float' and `double' types according to the IEC/IEEE
+Standard, then the `float32' and `float64' types should be indistinguishable
+in memory from the native `float' and `double' types.  (On the other hand,
+when `float32' or `float64' values are placed in processor registers by
+the compiler, the type of registers used may differ from those used for the
+native `float' and `double' types.)
+
+SoftFloat implements the following arithmetic operations:
+
+-- Conversions among all the floating-point formats, and also between
+   integers (32-bit and 64-bit) and any of the floating-point formats.
+
+-- The usual add, subtract, multiply, divide, and square root operations
+   for all floating-point formats.
+
+-- For each format, the floating-point remainder operation defined by the
+   IEC/IEEE Standard.
+
+-- For each floating-point format, a ``round to integer'' operation that
+   rounds to the nearest integer value in the same format.  (The floating-
+   point formats can hold integer values, of course.)
+
+-- Comparisons between two values in the same floating-point format.
+
+The only functions required by the IEC/IEEE Standard that are not provided
+are conversions to and from decimal.
+
+
+-------------------------------------------------------------------------------
+Rounding Modes
+
+All four rounding modes prescribed by the IEC/IEEE Standard are implemented
+for all operations that require rounding.  The rounding mode is selected
+by the global variable `float_rounding_mode'.  This variable may be set
+to one of the values `float_round_nearest_even', `float_round_to_zero',
+`float_round_down', or `float_round_up'.  The rounding mode is initialized
+to nearest/even.
+
+
+-------------------------------------------------------------------------------
+Extended Double-Precision Rounding Precision
+
+For extended double precision (`floatx80') only, the rounding precision
+of the standard arithmetic operations is controlled by the global variable
+`floatx80_rounding_precision'.  The operations affected are:
+
+   floatx80_add   floatx80_sub   floatx80_mul   floatx80_div   floatx80_sqrt
+
+When `floatx80_rounding_precision' is set to its default value of 80, these
+operations are rounded (as usual) to the full precision of the extended
+double-precision format.  Setting `floatx80_rounding_precision' to 32
+or to 64 causes the operations listed to be rounded to reduced precision
+equivalent to single precision (`float32') or to double precision
+(`float64'), respectively.  When rounding to reduced precision, additional
+bits in the result significand beyond the rounding point are set to zero.
+The consequences of setting `floatx80_rounding_precision' to a value other
+than 32, 64, or 80 is not specified.  Operations other than the ones listed
+above are not affected by `floatx80_rounding_precision'.
+
+
+-------------------------------------------------------------------------------
+Exceptions and Exception Flags
+
+All five exception flags required by the IEC/IEEE Standard are
+implemented.  Each flag is stored as a unique bit in the global variable
+`float_exception_flags'.  The positions of the exception flag bits within
+this variable are determined by the bit masks `float_flag_inexact',
+`float_flag_underflow', `float_flag_overflow', `float_flag_divbyzero', and
+`float_flag_invalid'.  The exception flags variable is initialized to all 0,
+meaning no exceptions.
+
+An individual exception flag can be cleared with the statement
+
+    float_exception_flags &= ~ float_flag_<exception>;
+
+where `<exception>' is the appropriate name.  To raise a floating-point
+exception, the SoftFloat function `float_raise' should be used (see below).
+
+In the terminology of the IEC/IEEE Standard, SoftFloat can detect tininess
+for underflow either before or after rounding.  The choice is made by
+the global variable `float_detect_tininess', which can be set to either
+`float_tininess_before_rounding' or `float_tininess_after_rounding'.
+Detecting tininess after rounding is better because it results in fewer
+spurious underflow signals.  The other option is provided for compatibility
+with some systems.  Like most systems, SoftFloat always detects loss of
+accuracy for underflow as an inexact result.
+
+
+-------------------------------------------------------------------------------
+Function Details
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+Conversion Functions
+
+All conversions among the floating-point formats are supported, as are all
+conversions between a floating-point format and 32-bit and 64-bit signed
+integers.  The complete set of conversion functions is:
+
+   int32_to_float32      int64_to_float32
+   int32_to_float64      int64_to_float32
+   int32_to_floatx80     int64_to_floatx80
+   int32_to_float128     int64_to_float128
+
+   float32_to_int32      float32_to_int64
+   float32_to_int32      float64_to_int64
+   floatx80_to_int32     floatx80_to_int64
+   float128_to_int32     float128_to_int64
+
+   float32_to_float64    float32_to_floatx80   float32_to_float128
+   float64_to_float32    float64_to_floatx80   float64_to_float128
+   floatx80_to_float32   floatx80_to_float64   floatx80_to_float128
+   float128_to_float32   float128_to_float64   float128_to_floatx80
+
+Each conversion function takes one operand of the appropriate type and
+returns one result.  Conversions from a smaller to a larger floating-point
+format are always exact and so require no rounding.  Conversions from 32-bit
+integers to double precision and larger formats are also exact, and likewise
+for conversions from 64-bit integers to extended double and quadruple
+precisions.
+
+Conversions from floating-point to integer raise the invalid exception if
+the source value cannot be rounded to a representable integer of the desired
+size (32 or 64 bits).  If the floating-point operand is a NaN, the largest
+positive integer is returned.  Otherwise, if the conversion overflows, the
+largest integer with the same sign as the operand is returned.
+
+On conversions to integer, if the floating-point operand is not already an
+integer value, the operand is rounded according to the current rounding
+mode as specified by `float_rounding_mode'.  Because C (and perhaps other
+languages) require that conversions to integers be rounded toward zero, the
+following functions are provided for improved speed and convenience:
+
+   float32_to_int32_round_to_zero    float32_to_int64_round_to_zero
+   float64_to_int32_round_to_zero    float64_to_int64_round_to_zero
+   floatx80_to_int32_round_to_zero   floatx80_to_int64_round_to_zero
+   float128_to_int32_round_to_zero   float128_to_int64_round_to_zero
+
+These variant functions ignore `float_rounding_mode' and always round toward
+zero.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+Standard Arithmetic Functions
+
+The following standard arithmetic functions are provided:
+
+   float32_add    float32_sub    float32_mul    float32_div    float32_sqrt
+   float64_add    float64_sub    float64_mul    float64_div    float64_sqrt
+   floatx80_add   floatx80_sub   floatx80_mul   floatx80_div   floatx80_sqrt
+   float128_add   float128_sub   float128_mul   float128_div   float128_sqrt
+
+Each function takes two operands, except for `sqrt' which takes only one.
+The operands and result are all of the same type.
+
+Rounding of the extended double-precision (`floatx80') functions is affected
+by the `floatx80_rounding_precision' variable, as explained above in the
+section _Extended_Double-Precision_Rounding_Precision_.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+Remainder Functions
+
+For each format, SoftFloat implements the remainder function according to
+the IEC/IEEE Standard.  The remainder functions are:
+
+   float32_rem
+   float64_rem
+   floatx80_rem
+   float128_rem
+
+Each remainder function takes two operands.  The operands and result are all
+of the same type.  Given operands x and y, the remainder functions return
+the value x - n*y, where n is the integer closest to x/y.  If x/y is exactly
+halfway between two integers, n is the even integer closest to x/y.  The
+remainder functions are always exact and so require no rounding.
+
+Depending on the relative magnitudes of the operands, the remainder
+functions can take considerably longer to execute than the other SoftFloat
+functions.  This is inherent in the remainder operation itself and is not a
+flaw in the SoftFloat implementation.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+Round-to-Integer Functions
+
+For each format, SoftFloat implements the round-to-integer function
+specified by the IEC/IEEE Standard.  The functions are:
+
+   float32_round_to_int
+   float64_round_to_int
+   floatx80_round_to_int
+   float128_round_to_int
+
+Each function takes a single floating-point operand and returns a result of
+the same type.  (Note that the result is not an integer type.)  The operand
+is rounded to an exact integer according to the current rounding mode, and
+the resulting integer value is returned in the same floating-point format.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+Comparison Functions
+
+The following floating-point comparison functions are provided:
+
+   float32_eq    float32_le    float32_lt
+   float64_eq    float64_le    float64_lt
+   floatx80_eq   floatx80_le   floatx80_lt
+   float128_eq   float128_le   float128_lt
+
+Each function takes two operands of the same type and returns a 1 or 0
+representing either _true_ or _false_.  The abbreviation `eq' stands for
+``equal'' (=); `le' stands for ``less than or equal'' (<=); and `lt' stands
+for ``less than'' (<).
+
+The standard greater-than (>), greater-than-or-equal (>=), and not-equal
+(!=) functions are easily obtained using the functions provided.  The
+not-equal function is just the logical complement of the equal function.
+The greater-than-or-equal function is identical to the less-than-or-equal
+function with the operands reversed; and the greater-than function can be
+obtained from the less-than function in the same way.
+
+The IEC/IEEE Standard specifies that the less-than-or-equal and less-than
+functions raise the invalid exception if either input is any kind of NaN.
+The equal functions, on the other hand, are defined not to raise the invalid
+exception on quiet NaNs.  For completeness, SoftFloat provides the following
+additional functions:
+
+   float32_eq_signaling    float32_le_quiet    float32_lt_quiet
+   float64_eq_signaling    float64_le_quiet    float64_lt_quiet
+   floatx80_eq_signaling   floatx80_le_quiet   floatx80_lt_quiet
+   float128_eq_signaling   float128_le_quiet   float128_lt_quiet
+
+The `signaling' equal functions are identical to the standard functions
+except that the invalid exception is raised for any NaN input.  Likewise,
+the `quiet' comparison functions are identical to their counterparts except
+that the invalid exception is not raised for quiet NaNs.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+Signaling NaN Test Functions
+
+The following functions test whether a floating-point value is a signaling
+NaN:
+
+   float32_is_signaling_nan
+   float64_is_signaling_nan
+   floatx80_is_signaling_nan
+   float128_is_signaling_nan
+
+The functions take one operand and return 1 if the operand is a signaling
+NaN and 0 otherwise.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+Raise-Exception Function
+
+SoftFloat provides a function for raising floating-point exceptions:
+
+    float_raise
+
+The function takes a mask indicating the set of exceptions to raise.  No
+result is returned.  In addition to setting the specified exception flags,
+this function may cause a trap or abort appropriate for the current system.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+
+-------------------------------------------------------------------------------
+Contact Information
+
+At the time of this writing, the most up-to-date information about
+SoftFloat and the latest release can be found at the Web page `http://
+HTTP.CS.Berkeley.EDU/~jhauser/arithmetic/SoftFloat.html'.
+
+
diff --git a/lib/nbsd_libc/softfloat/templates/milieu.h b/lib/nbsd_libc/softfloat/templates/milieu.h
new file mode 100644 (file)
index 0000000..2fcfa1f
--- /dev/null
@@ -0,0 +1,48 @@
+\r
+/*\r
+===============================================================================\r
+\r
+This C header file is part of the SoftFloat IEC/IEEE Floating-point\r
+Arithmetic Package, Release 2a.\r
+\r
+Written by John R. Hauser.  This work was made possible in part by the\r
+International Computer Science Institute, located at Suite 600, 1947 Center\r
+Street, Berkeley, California 94704.  Funding was partially provided by the\r
+National Science Foundation under grant MIP-9311980.  The original version\r
+of this code was written as part of a project to build a fixed-point vector\r
+processor in collaboration with the University of California at Berkeley,\r
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information\r
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/\r
+arithmetic/SoftFloat.html'.\r
+\r
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort\r
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT\r
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO\r
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY\r
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.\r
+\r
+Derivative works are acceptable, even for commercial purposes, so long as\r
+(1) they include prominent notice that the work is derivative, and (2) they\r
+include prominent notice akin to these four paragraphs for those parts of\r
+this code that are retained.\r
+\r
+===============================================================================\r
+*/\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Include common integer types and flags.\r
+-------------------------------------------------------------------------------\r
+*/\r
+#include "../../../processors/!!!processor.h"\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Symbolic Boolean literals.\r
+-------------------------------------------------------------------------------\r
+*/\r
+enum {\r
+    FALSE = 0,\r
+    TRUE  = 1\r
+};\r
+\r
diff --git a/lib/nbsd_libc/softfloat/templates/softfloat-specialize b/lib/nbsd_libc/softfloat/templates/softfloat-specialize
new file mode 100644 (file)
index 0000000..d8b2500
--- /dev/null
@@ -0,0 +1,464 @@
+\r
+/*\r
+===============================================================================\r
+\r
+This C source fragment is part of the SoftFloat IEC/IEEE Floating-point\r
+Arithmetic Package, Release 2a.\r
+\r
+Written by John R. Hauser.  This work was made possible in part by the\r
+International Computer Science Institute, located at Suite 600, 1947 Center\r
+Street, Berkeley, California 94704.  Funding was partially provided by the\r
+National Science Foundation under grant MIP-9311980.  The original version\r
+of this code was written as part of a project to build a fixed-point vector\r
+processor in collaboration with the University of California at Berkeley,\r
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information\r
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/\r
+arithmetic/SoftFloat.html'.\r
+\r
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort\r
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT\r
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO\r
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY\r
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.\r
+\r
+Derivative works are acceptable, even for commercial purposes, so long as\r
+(1) they include prominent notice that the work is derivative, and (2) they\r
+include prominent notice akin to these four paragraphs for those parts of\r
+this code that are retained.\r
+\r
+===============================================================================\r
+*/\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Underflow tininess-detection mode, statically initialized to default value.\r
+(The declaration in `softfloat.h' must match the `int8' type here.)\r
+-------------------------------------------------------------------------------\r
+*/\r
+int8 float_detect_tininess = float_tininess_after_rounding;\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Raises the exceptions specified by `flags'.  Floating-point traps can be\r
+defined here if desired.  It is currently not possible for such a trap to\r
+substitute a result value.  If traps are not implemented, this routine\r
+should be simply `float_exception_flags |= flags;'.\r
+-------------------------------------------------------------------------------\r
+*/\r
+void float_raise( int8 flags )\r
+{\r
+\r
+    float_exception_flags |= flags;\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Internal canonical NaN format.\r
+-------------------------------------------------------------------------------\r
+*/\r
+typedef struct {\r
+    flag sign;\r
+    bits64 high, low;\r
+} commonNaNT;\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+The pattern for a default generated single-precision NaN.\r
+-------------------------------------------------------------------------------\r
+*/\r
+#define float32_default_nan 0xFFFFFFFF\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns 1 if the single-precision floating-point value `a' is a NaN;\r
+otherwise returns 0.\r
+-------------------------------------------------------------------------------\r
+*/\r
+flag float32_is_nan( float32 a )\r
+{\r
+\r
+    return ( 0xFF000000 < (bits32) ( a<<1 ) );\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns 1 if the single-precision floating-point value `a' is a signaling\r
+NaN; otherwise returns 0.\r
+-------------------------------------------------------------------------------\r
+*/\r
+flag float32_is_signaling_nan( float32 a )\r
+{\r
+\r
+    return ( ( ( a>>22 ) & 0x1FF ) == 0x1FE ) && ( a & 0x003FFFFF );\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns the result of converting the single-precision floating-point NaN\r
+`a' to the canonical NaN format.  If `a' is a signaling NaN, the invalid\r
+exception is raised.\r
+-------------------------------------------------------------------------------\r
+*/\r
+static commonNaNT float32ToCommonNaN( float32 a )\r
+{\r
+    commonNaNT z;\r
+\r
+    if ( float32_is_signaling_nan( a ) ) float_raise( float_flag_invalid );\r
+    z.sign = a>>31;\r
+    z.low = 0;\r
+    z.high = ( (bits64) a )<<41;\r
+    return z;\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns the result of converting the canonical NaN `a' to the single-\r
+precision floating-point format.\r
+-------------------------------------------------------------------------------\r
+*/\r
+static float32 commonNaNToFloat32( commonNaNT a )\r
+{\r
+\r
+    return ( ( (bits32) a.sign )<<31 ) | 0x7FC00000 | ( a.high>>41 );\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Takes two single-precision floating-point values `a' and `b', one of which\r
+is a NaN, and returns the appropriate NaN result.  If either `a' or `b' is a\r
+signaling NaN, the invalid exception is raised.\r
+-------------------------------------------------------------------------------\r
+*/\r
+static float32 propagateFloat32NaN( float32 a, float32 b )\r
+{\r
+    flag aIsNaN, aIsSignalingNaN, bIsNaN, bIsSignalingNaN;\r
+\r
+    aIsNaN = float32_is_nan( a );\r
+    aIsSignalingNaN = float32_is_signaling_nan( a );\r
+    bIsNaN = float32_is_nan( b );\r
+    bIsSignalingNaN = float32_is_signaling_nan( b );\r
+    a |= 0x00400000;\r
+    b |= 0x00400000;\r
+    if ( aIsSignalingNaN | bIsSignalingNaN ) float_raise( float_flag_invalid );\r
+    if ( aIsNaN ) {\r
+        return ( aIsSignalingNaN & bIsNaN ) ? b : a;\r
+    }\r
+    else {\r
+        return b;\r
+    }\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+The pattern for a default generated double-precision NaN.\r
+-------------------------------------------------------------------------------\r
+*/\r
+#define float64_default_nan LIT64( 0xFFFFFFFFFFFFFFFF )\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns 1 if the double-precision floating-point value `a' is a NaN;\r
+otherwise returns 0.\r
+-------------------------------------------------------------------------------\r
+*/\r
+flag float64_is_nan( float64 a )\r
+{\r
+\r
+    return ( LIT64( 0xFFE0000000000000 ) < (bits64) ( a<<1 ) );\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns 1 if the double-precision floating-point value `a' is a signaling\r
+NaN; otherwise returns 0.\r
+-------------------------------------------------------------------------------\r
+*/\r
+flag float64_is_signaling_nan( float64 a )\r
+{\r
+\r
+    return\r
+           ( ( ( a>>51 ) & 0xFFF ) == 0xFFE )\r
+        && ( a & LIT64( 0x0007FFFFFFFFFFFF ) );\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns the result of converting the double-precision floating-point NaN\r
+`a' to the canonical NaN format.  If `a' is a signaling NaN, the invalid\r
+exception is raised.\r
+-------------------------------------------------------------------------------\r
+*/\r
+static commonNaNT float64ToCommonNaN( float64 a )\r
+{\r
+    commonNaNT z;\r
+\r
+    if ( float64_is_signaling_nan( a ) ) float_raise( float_flag_invalid );\r
+    z.sign = a>>63;\r
+    z.low = 0;\r
+    z.high = a<<12;\r
+    return z;\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns the result of converting the canonical NaN `a' to the double-\r
+precision floating-point format.\r
+-------------------------------------------------------------------------------\r
+*/\r
+static float64 commonNaNToFloat64( commonNaNT a )\r
+{\r
+\r
+    return\r
+          ( ( (bits64) a.sign )<<63 )\r
+        | LIT64( 0x7FF8000000000000 )\r
+        | ( a.high>>12 );\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Takes two double-precision floating-point values `a' and `b', one of which\r
+is a NaN, and returns the appropriate NaN result.  If either `a' or `b' is a\r
+signaling NaN, the invalid exception is raised.\r
+-------------------------------------------------------------------------------\r
+*/\r
+static float64 propagateFloat64NaN( float64 a, float64 b )\r
+{\r
+    flag aIsNaN, aIsSignalingNaN, bIsNaN, bIsSignalingNaN;\r
+\r
+    aIsNaN = float64_is_nan( a );\r
+    aIsSignalingNaN = float64_is_signaling_nan( a );\r
+    bIsNaN = float64_is_nan( b );\r
+    bIsSignalingNaN = float64_is_signaling_nan( b );\r
+    a |= LIT64( 0x0008000000000000 );\r
+    b |= LIT64( 0x0008000000000000 );\r
+    if ( aIsSignalingNaN | bIsSignalingNaN ) float_raise( float_flag_invalid );\r
+    if ( aIsNaN ) {\r
+        return ( aIsSignalingNaN & bIsNaN ) ? b : a;\r
+    }\r
+    else {\r
+        return b;\r
+    }\r
+\r
+}\r
+\r
+#ifdef FLOATX80\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+The pattern for a default generated extended double-precision NaN.  The\r
+`high' and `low' values hold the most- and least-significant bits,\r
+respectively.\r
+-------------------------------------------------------------------------------\r
+*/\r
+#define floatx80_default_nan_high 0xFFFF\r
+#define floatx80_default_nan_low  LIT64( 0xFFFFFFFFFFFFFFFF )\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns 1 if the extended double-precision floating-point value `a' is a\r
+NaN; otherwise returns 0.\r
+-------------------------------------------------------------------------------\r
+*/\r
+flag floatx80_is_nan( floatx80 a )\r
+{\r
+\r
+    return ( ( a.high & 0x7FFF ) == 0x7FFF ) && (bits64) ( a.low<<1 );\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns 1 if the extended double-precision floating-point value `a' is a\r
+signaling NaN; otherwise returns 0.\r
+-------------------------------------------------------------------------------\r
+*/\r
+flag floatx80_is_signaling_nan( floatx80 a )\r
+{\r
+    bits64 aLow;\r
+\r
+    aLow = a.low & ~ LIT64( 0x4000000000000000 );\r
+    return\r
+           ( ( a.high & 0x7FFF ) == 0x7FFF )\r
+        && (bits64) ( aLow<<1 )\r
+        && ( a.low == aLow );\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns the result of converting the extended double-precision floating-\r
+point NaN `a' to the canonical NaN format.  If `a' is a signaling NaN, the\r
+invalid exception is raised.\r
+-------------------------------------------------------------------------------\r
+*/\r
+static commonNaNT floatx80ToCommonNaN( floatx80 a )\r
+{\r
+    commonNaNT z;\r
+\r
+    if ( floatx80_is_signaling_nan( a ) ) float_raise( float_flag_invalid );\r
+    z.sign = a.high>>15;\r
+    z.low = 0;\r
+    z.high = a.low<<1;\r
+    return z;\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns the result of converting the canonical NaN `a' to the extended\r
+double-precision floating-point format.\r
+-------------------------------------------------------------------------------\r
+*/\r
+static floatx80 commonNaNToFloatx80( commonNaNT a )\r
+{\r
+    floatx80 z;\r
+\r
+    z.low = LIT64( 0xC000000000000000 ) | ( a.high>>1 );\r
+    z.high = ( ( (bits16) a.sign )<<15 ) | 0x7FFF;\r
+    return z;\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Takes two extended double-precision floating-point values `a' and `b', one\r
+of which is a NaN, and returns the appropriate NaN result.  If either `a' or\r
+`b' is a signaling NaN, the invalid exception is raised.\r
+-------------------------------------------------------------------------------\r
+*/\r
+static floatx80 propagateFloatx80NaN( floatx80 a, floatx80 b )\r
+{\r
+    flag aIsNaN, aIsSignalingNaN, bIsNaN, bIsSignalingNaN;\r
+\r
+    aIsNaN = floatx80_is_nan( a );\r
+    aIsSignalingNaN = floatx80_is_signaling_nan( a );\r
+    bIsNaN = floatx80_is_nan( b );\r
+    bIsSignalingNaN = floatx80_is_signaling_nan( b );\r
+    a.low |= LIT64( 0xC000000000000000 );\r
+    b.low |= LIT64( 0xC000000000000000 );\r
+    if ( aIsSignalingNaN | bIsSignalingNaN ) float_raise( float_flag_invalid );\r
+    if ( aIsNaN ) {\r
+        return ( aIsSignalingNaN & bIsNaN ) ? b : a;\r
+    }\r
+    else {\r
+        return b;\r
+    }\r
+\r
+}\r
+\r
+#endif\r
+\r
+#ifdef FLOAT128\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+The pattern for a default generated quadruple-precision NaN.  The `high' and\r
+`low' values hold the most- and least-significant bits, respectively.\r
+-------------------------------------------------------------------------------\r
+*/\r
+#define float128_default_nan_high LIT64( 0xFFFFFFFFFFFFFFFF )\r
+#define float128_default_nan_low  LIT64( 0xFFFFFFFFFFFFFFFF )\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns 1 if the quadruple-precision floating-point value `a' is a NaN;\r
+otherwise returns 0.\r
+-------------------------------------------------------------------------------\r
+*/\r
+flag float128_is_nan( float128 a )\r
+{\r
+\r
+    return\r
+           ( LIT64( 0xFFFE000000000000 ) <= (bits64) ( a.high<<1 ) )\r
+        && ( a.low || ( a.high & LIT64( 0x0000FFFFFFFFFFFF ) ) );\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns 1 if the quadruple-precision floating-point value `a' is a\r
+signaling NaN; otherwise returns 0.\r
+-------------------------------------------------------------------------------\r
+*/\r
+flag float128_is_signaling_nan( float128 a )\r
+{\r
+\r
+    return\r
+           ( ( ( a.high>>47 ) & 0xFFFF ) == 0xFFFE )\r
+        && ( a.low || ( a.high & LIT64( 0x00007FFFFFFFFFFF ) ) );\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns the result of converting the quadruple-precision floating-point NaN\r
+`a' to the canonical NaN format.  If `a' is a signaling NaN, the invalid\r
+exception is raised.\r
+-------------------------------------------------------------------------------\r
+*/\r
+static commonNaNT float128ToCommonNaN( float128 a )\r
+{\r
+    commonNaNT z;\r
+\r
+    if ( float128_is_signaling_nan( a ) ) float_raise( float_flag_invalid );\r
+    z.sign = a.high>>63;\r
+    shortShift128Left( a.high, a.low, 16, &z.high, &z.low );\r
+    return z;\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Returns the result of converting the canonical NaN `a' to the quadruple-\r
+precision floating-point format.\r
+-------------------------------------------------------------------------------\r
+*/\r
+static float128 commonNaNToFloat128( commonNaNT a )\r
+{\r
+    float128 z;\r
+\r
+    shift128Right( a.high, a.low, 16, &z.high, &z.low );\r
+    z.high |= ( ( (bits64) a.sign )<<63 ) | LIT64( 0x7FFF800000000000 );\r
+    return z;\r
+\r
+}\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Takes two quadruple-precision floating-point values `a' and `b', one of\r
+which is a NaN, and returns the appropriate NaN result.  If either `a' or\r
+`b' is a signaling NaN, the invalid exception is raised.\r
+-------------------------------------------------------------------------------\r
+*/\r
+static float128 propagateFloat128NaN( float128 a, float128 b )\r
+{\r
+    flag aIsNaN, aIsSignalingNaN, bIsNaN, bIsSignalingNaN;\r
+\r
+    aIsNaN = float128_is_nan( a );\r
+    aIsSignalingNaN = float128_is_signaling_nan( a );\r
+    bIsNaN = float128_is_nan( b );\r
+    bIsSignalingNaN = float128_is_signaling_nan( b );\r
+    a.high |= LIT64( 0x0000800000000000 );\r
+    b.high |= LIT64( 0x0000800000000000 );\r
+    if ( aIsSignalingNaN | bIsSignalingNaN ) float_raise( float_flag_invalid );\r
+    if ( aIsNaN ) {\r
+        return ( aIsSignalingNaN & bIsNaN ) ? b : a;\r
+    }\r
+    else {\r
+        return b;\r
+    }\r
+\r
+}\r
+\r
+#endif\r
+\r
diff --git a/lib/nbsd_libc/softfloat/templates/softfloat.h b/lib/nbsd_libc/softfloat/templates/softfloat.h
new file mode 100644 (file)
index 0000000..8c0fe10
--- /dev/null
@@ -0,0 +1,290 @@
+\r
+/*\r
+===============================================================================\r
+\r
+This C header file is part of the SoftFloat IEC/IEEE Floating-point\r
+Arithmetic Package, Release 2a.\r
+\r
+Written by John R. Hauser.  This work was made possible in part by the\r
+International Computer Science Institute, located at Suite 600, 1947 Center\r
+Street, Berkeley, California 94704.  Funding was partially provided by the\r
+National Science Foundation under grant MIP-9311980.  The original version\r
+of this code was written as part of a project to build a fixed-point vector\r
+processor in collaboration with the University of California at Berkeley,\r
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information\r
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/\r
+arithmetic/SoftFloat.html'.\r
+\r
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort\r
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT\r
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO\r
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY\r
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.\r
+\r
+Derivative works are acceptable, even for commercial purposes, so long as\r
+(1) they include prominent notice that the work is derivative, and (2) they\r
+include prominent notice akin to these four paragraphs for those parts of\r
+this code that are retained.\r
+\r
+===============================================================================\r
+*/\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+The macro `FLOATX80' must be defined to enable the extended double-precision\r
+floating-point format `floatx80'.  If this macro is not defined, the\r
+`floatx80' type will not be defined, and none of the functions that either\r
+input or output the `floatx80' type will be defined.  The same applies to\r
+the `FLOAT128' macro and the quadruple-precision format `float128'.\r
+-------------------------------------------------------------------------------\r
+*/\r
+#define FLOATX80\r
+#define FLOAT128\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE floating-point types.\r
+-------------------------------------------------------------------------------\r
+*/\r
+typedef !!!bits32 float32;\r
+typedef !!!bits64 float64;\r
+#ifdef FLOATX80\r
+typedef struct {\r
+    !!!bits16 high;\r
+    !!!bits64 low;\r
+} floatx80;\r
+#endif\r
+#ifdef FLOAT128\r
+typedef struct {\r
+    !!!bits64 high, low;\r
+} float128;\r
+#endif\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE floating-point underflow tininess-detection mode.\r
+-------------------------------------------------------------------------------\r
+*/\r
+extern !!!int8 float_detect_tininess;\r
+enum {\r
+    float_tininess_after_rounding  = 0,\r
+    float_tininess_before_rounding = 1\r
+};\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE floating-point rounding mode.\r
+-------------------------------------------------------------------------------\r
+*/\r
+extern !!!int8 float_rounding_mode;\r
+enum {\r
+    float_round_nearest_even = 0,\r
+    float_round_to_zero      = 1,\r
+    float_round_down         = 2,\r
+    float_round_up           = 3\r
+};\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE floating-point exception flags.\r
+-------------------------------------------------------------------------------\r
+*/\r
+extern !!!int8 float_exception_flags;\r
+enum {\r
+    float_flag_inexact   =  1,\r
+    float_flag_underflow =  2,\r
+    float_flag_overflow  =  4,\r
+    float_flag_divbyzero =  8,\r
+    float_flag_invalid   = 16\r
+};\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Routine to raise any or all of the software IEC/IEEE floating-point\r
+exception flags.\r
+-------------------------------------------------------------------------------\r
+*/\r
+void float_raise( !!!int8 );\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE integer-to-floating-point conversion routines.\r
+-------------------------------------------------------------------------------\r
+*/\r
+float32 int32_to_float32( !!!int32 );\r
+float64 int32_to_float64( !!!int32 );\r
+#ifdef FLOATX80\r
+floatx80 int32_to_floatx80( !!!int32 );\r
+#endif\r
+#ifdef FLOAT128\r
+float128 int32_to_float128( !!!int32 );\r
+#endif\r
+float32 int64_to_float32( !!!int64 );\r
+float64 int64_to_float64( !!!int64 );\r
+#ifdef FLOATX80\r
+floatx80 int64_to_floatx80( !!!int64 );\r
+#endif\r
+#ifdef FLOAT128\r
+float128 int64_to_float128( !!!int64 );\r
+#endif\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE single-precision conversion routines.\r
+-------------------------------------------------------------------------------\r
+*/\r
+!!!int32 float32_to_int32( float32 );\r
+!!!int32 float32_to_int32_round_to_zero( float32 );\r
+!!!int64 float32_to_int64( float32 );\r
+!!!int64 float32_to_int64_round_to_zero( float32 );\r
+float64 float32_to_float64( float32 );\r
+#ifdef FLOATX80\r
+floatx80 float32_to_floatx80( float32 );\r
+#endif\r
+#ifdef FLOAT128\r
+float128 float32_to_float128( float32 );\r
+#endif\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE single-precision operations.\r
+-------------------------------------------------------------------------------\r
+*/\r
+float32 float32_round_to_int( float32 );\r
+float32 float32_add( float32, float32 );\r
+float32 float32_sub( float32, float32 );\r
+float32 float32_mul( float32, float32 );\r
+float32 float32_div( float32, float32 );\r
+float32 float32_rem( float32, float32 );\r
+float32 float32_sqrt( float32 );\r
+!!!flag float32_eq( float32, float32 );\r
+!!!flag float32_le( float32, float32 );\r
+!!!flag float32_lt( float32, float32 );\r
+!!!flag float32_eq_signaling( float32, float32 );\r
+!!!flag float32_le_quiet( float32, float32 );\r
+!!!flag float32_lt_quiet( float32, float32 );\r
+!!!flag float32_is_signaling_nan( float32 );\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE double-precision conversion routines.\r
+-------------------------------------------------------------------------------\r
+*/\r
+!!!int32 float64_to_int32( float64 );\r
+!!!int32 float64_to_int32_round_to_zero( float64 );\r
+!!!int64 float64_to_int64( float64 );\r
+!!!int64 float64_to_int64_round_to_zero( float64 );\r
+float32 float64_to_float32( float64 );\r
+#ifdef FLOATX80\r
+floatx80 float64_to_floatx80( float64 );\r
+#endif\r
+#ifdef FLOAT128\r
+float128 float64_to_float128( float64 );\r
+#endif\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE double-precision operations.\r
+-------------------------------------------------------------------------------\r
+*/\r
+float64 float64_round_to_int( float64 );\r
+float64 float64_add( float64, float64 );\r
+float64 float64_sub( float64, float64 );\r
+float64 float64_mul( float64, float64 );\r
+float64 float64_div( float64, float64 );\r
+float64 float64_rem( float64, float64 );\r
+float64 float64_sqrt( float64 );\r
+!!!flag float64_eq( float64, float64 );\r
+!!!flag float64_le( float64, float64 );\r
+!!!flag float64_lt( float64, float64 );\r
+!!!flag float64_eq_signaling( float64, float64 );\r
+!!!flag float64_le_quiet( float64, float64 );\r
+!!!flag float64_lt_quiet( float64, float64 );\r
+!!!flag float64_is_signaling_nan( float64 );\r
+\r
+#ifdef FLOATX80\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE extended double-precision conversion routines.\r
+-------------------------------------------------------------------------------\r
+*/\r
+!!!int32 floatx80_to_int32( floatx80 );\r
+!!!int32 floatx80_to_int32_round_to_zero( floatx80 );\r
+!!!int64 floatx80_to_int64( floatx80 );\r
+!!!int64 floatx80_to_int64_round_to_zero( floatx80 );\r
+float32 floatx80_to_float32( floatx80 );\r
+float64 floatx80_to_float64( floatx80 );\r
+#ifdef FLOAT128\r
+float128 floatx80_to_float128( floatx80 );\r
+#endif\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE extended double-precision rounding precision.  Valid\r
+values are 32, 64, and 80.\r
+-------------------------------------------------------------------------------\r
+*/\r
+extern !!!int8 floatx80_rounding_precision;\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE extended double-precision operations.\r
+-------------------------------------------------------------------------------\r
+*/\r
+floatx80 floatx80_round_to_int( floatx80 );\r
+floatx80 floatx80_add( floatx80, floatx80 );\r
+floatx80 floatx80_sub( floatx80, floatx80 );\r
+floatx80 floatx80_mul( floatx80, floatx80 );\r
+floatx80 floatx80_div( floatx80, floatx80 );\r
+floatx80 floatx80_rem( floatx80, floatx80 );\r
+floatx80 floatx80_sqrt( floatx80 );\r
+!!!flag floatx80_eq( floatx80, floatx80 );\r
+!!!flag floatx80_le( floatx80, floatx80 );\r
+!!!flag floatx80_lt( floatx80, floatx80 );\r
+!!!flag floatx80_eq_signaling( floatx80, floatx80 );\r
+!!!flag floatx80_le_quiet( floatx80, floatx80 );\r
+!!!flag floatx80_lt_quiet( floatx80, floatx80 );\r
+!!!flag floatx80_is_signaling_nan( floatx80 );\r
+\r
+#endif\r
+\r
+#ifdef FLOAT128\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE quadruple-precision conversion routines.\r
+-------------------------------------------------------------------------------\r
+*/\r
+!!!int32 float128_to_int32( float128 );\r
+!!!int32 float128_to_int32_round_to_zero( float128 );\r
+!!!int64 float128_to_int64( float128 );\r
+!!!int64 float128_to_int64_round_to_zero( float128 );\r
+float32 float128_to_float32( float128 );\r
+float64 float128_to_float64( float128 );\r
+#ifdef FLOATX80\r
+floatx80 float128_to_floatx80( float128 );\r
+#endif\r
+\r
+/*\r
+-------------------------------------------------------------------------------\r
+Software IEC/IEEE quadruple-precision operations.\r
+-------------------------------------------------------------------------------\r
+*/\r
+float128 float128_round_to_int( float128 );\r
+float128 float128_add( float128, float128 );\r
+float128 float128_sub( float128, float128 );\r
+float128 float128_mul( float128, float128 );\r
+float128 float128_div( float128, float128 );\r
+float128 float128_rem( float128, float128 );\r
+float128 float128_sqrt( float128 );\r
+!!!flag float128_eq( float128, float128 );\r
+!!!flag float128_le( float128, float128 );\r
+!!!flag float128_lt( float128, float128 );\r
+!!!flag float128_eq_signaling( float128, float128 );\r
+!!!flag float128_le_quiet( float128, float128 );\r
+!!!flag float128_lt_quiet( float128, float128 );\r
+!!!flag float128_is_signaling_nan( float128 );\r
+\r
+#endif\r
+\r
diff --git a/lib/nbsd_libc/softfloat/timesoftfloat.c b/lib/nbsd_libc/softfloat/timesoftfloat.c
new file mode 100644 (file)
index 0000000..f7a27f4
--- /dev/null
@@ -0,0 +1,2641 @@
+/* $NetBSD: timesoftfloat.c,v 1.1 2000/06/06 08:15:11 bjh21 Exp $ */
+
+/*
+===============================================================================
+
+This C source file is part of the SoftFloat IEC/IEEE Floating-point
+Arithmetic Package, Release 2a.
+
+Written by John R. Hauser.  This work was made possible in part by the
+International Computer Science Institute, located at Suite 600, 1947 Center
+Street, Berkeley, California 94704.  Funding was partially provided by the
+National Science Foundation under grant MIP-9311980.  The original version
+of this code was written as part of a project to build a fixed-point vector
+processor in collaboration with the University of California at Berkeley,
+overseen by Profs. Nelson Morgan and John Wawrzynek.  More information
+is available through the Web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
+arithmetic/SoftFloat.html'.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+Derivative works are acceptable, even for commercial purposes, so long as
+(1) they include prominent notice that the work is derivative, and (2) they
+include prominent notice akin to these four paragraphs for those parts of
+this code that are retained.
+
+===============================================================================
+*/
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: timesoftfloat.c,v 1.1 2000/06/06 08:15:11 bjh21 Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <stdio.h>
+#include <time.h>
+#include "milieu.h"
+#include "softfloat.h"
+
+enum {
+    minIterations = 1000
+};
+
+static void fail( const char *message, ... )
+{
+    va_list varArgs;
+
+    fputs( "timesoftfloat: ", stderr );
+    va_start( varArgs, message );
+    vfprintf( stderr, message, varArgs );
+    va_end( varArgs );
+    fputs( ".\n", stderr );
+    exit( EXIT_FAILURE );
+
+}
+
+static char *functionName;
+static char *roundingPrecisionName, *roundingModeName, *tininessModeName;
+
+static void reportTime( int32 count, long clocks )
+{
+
+    printf(
+        "%8.1f kops/s: %s",
+        ( count / ( ( (float) clocks ) / CLOCKS_PER_SEC ) ) / 1000,
+        functionName
+    );
+    if ( roundingModeName ) {
+        if ( roundingPrecisionName ) {
+            fputs( ", precision ", stdout );
+            fputs( roundingPrecisionName, stdout );
+        }
+        fputs( ", rounding ", stdout );
+        fputs( roundingModeName, stdout );
+        if ( tininessModeName ) {
+            fputs( ", tininess ", stdout );
+            fputs( tininessModeName, stdout );
+            fputs( " rounding", stdout );
+        }
+    }
+    fputc( '\n', stdout );
+
+}
+
+enum {
+    numInputs_int32 = 32
+};
+
+static const int32 inputs_int32[ numInputs_int32 ] = {
+    0xFFFFBB79, 0x405CF80F, 0x00000000, 0xFFFFFD04,
+    0xFFF20002, 0x0C8EF795, 0xF00011FF, 0x000006CA,
+    0x00009BFE, 0xFF4862E3, 0x9FFFEFFE, 0xFFFFFFB7,
+    0x0BFF7FFF, 0x0000F37A, 0x0011DFFE, 0x00000006,
+    0xFFF02006, 0xFFFFF7D1, 0x10200003, 0xDE8DF765,
+    0x00003E02, 0x000019E8, 0x0008FFFE, 0xFFFFFB5C,
+    0xFFDF7FFE, 0x07C42FBF, 0x0FFFE3FF, 0x040B9F13,
+    0xBFFFFFF8, 0x0001BF56, 0x000017F6, 0x000A908A
+};
+
+static void time_a_int32_z_float32( float32 function( int32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_int32[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_int32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_int32[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_int32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_a_int32_z_float64( float64 function( int32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_int32[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_int32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_int32[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_int32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#ifdef FLOATX80
+
+static void time_a_int32_z_floatx80( floatx80 function( int32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_int32[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_int32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_int32[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_int32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#endif
+
+#ifdef FLOAT128
+
+static void time_a_int32_z_float128( float128 function( int32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_int32[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_int32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_int32[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_int32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#endif
+
+enum {
+    numInputs_int64 = 32
+};
+
+static const int64 inputs_int64[ numInputs_int64 ] = {
+    LIT64( 0xFBFFC3FFFFFFFFFF ),
+    LIT64( 0x0000000003C589BC ),
+    LIT64( 0x00000000400013FE ),
+    LIT64( 0x0000000000186171 ),
+    LIT64( 0xFFFFFFFFFFFEFBFA ),
+    LIT64( 0xFFFFFD79E6DFFC73 ),
+    LIT64( 0x0000000010001DFF ),
+    LIT64( 0xDD1A0F0C78513710 ),
+    LIT64( 0xFFFF83FFFFFEFFFE ),
+    LIT64( 0x00756EBD1AD0C1C7 ),
+    LIT64( 0x0003FDFFFFFFFFBE ),
+    LIT64( 0x0007D0FB2C2CA951 ),
+    LIT64( 0x0007FC0007FFFFFE ),
+    LIT64( 0x0000001F942B18BB ),
+    LIT64( 0x0000080101FFFFFE ),
+    LIT64( 0xFFFFFFFFFFFF0978 ),
+    LIT64( 0x000000000008BFFF ),
+    LIT64( 0x0000000006F5AF08 ),
+    LIT64( 0xFFDEFF7FFFFFFFFE ),
+    LIT64( 0x0000000000000003 ),
+    LIT64( 0x3FFFFFFFFF80007D ),
+    LIT64( 0x0000000000000078 ),
+    LIT64( 0xFFF80000007FDFFD ),
+    LIT64( 0x1BBC775B78016AB0 ),
+    LIT64( 0xFFF9001FFFFFFFFE ),
+    LIT64( 0xFFFD4767AB98E43F ),
+    LIT64( 0xFFFFFEFFFE00001E ),
+    LIT64( 0xFFFFFFFFFFF04EFD ),
+    LIT64( 0x07FFFFFFFFFFF7FF ),
+    LIT64( 0xFFFC9EAA38F89050 ),
+    LIT64( 0x00000020FBFFFFFE ),
+    LIT64( 0x0000099AE6455357 )
+};
+
+static void time_a_int64_z_float32( float32 function( int64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_int64[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_int64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_int64[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_int64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_a_int64_z_float64( float64 function( int64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_int64[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_int64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_int64[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_int64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#ifdef FLOATX80
+
+static void time_a_int64_z_floatx80( floatx80 function( int64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_int64[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_int64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_int64[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_int64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#endif
+
+#ifdef FLOAT128
+
+static void time_a_int64_z_float128( float128 function( int64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_int64[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_int64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_int64[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_int64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#endif
+
+enum {
+    numInputs_float32 = 32
+};
+
+static const float32 inputs_float32[ numInputs_float32 ] = {
+    0x4EFA0000, 0xC1D0B328, 0x80000000, 0x3E69A31E,
+    0xAF803EFF, 0x3F800000, 0x17BF8000, 0xE74A301A,
+    0x4E010003, 0x7EE3C75D, 0xBD803FE0, 0xBFFEFF00,
+    0x7981F800, 0x431FFFFC, 0xC100C000, 0x3D87EFFF,
+    0x4103FEFE, 0xBC000007, 0xBF01F7FF, 0x4E6C6B5C,
+    0xC187FFFE, 0xC58B9F13, 0x4F88007F, 0xDF004007,
+    0xB7FFD7FE, 0x7E8001FB, 0x46EFFBFF, 0x31C10000,
+    0xDB428661, 0x33F89B1F, 0xA3BFEFFF, 0x537BFFBE
+};
+
+static void time_a_float32_z_int32( int32 function( float32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float32[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float32[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_a_float32_z_int64( int64 function( float32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float32[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float32[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_a_float32_z_float64( float64 function( float32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float32[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float32[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#ifdef FLOATX80
+
+static void time_a_float32_z_floatx80( floatx80 function( float32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float32[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float32[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#endif
+
+#ifdef FLOAT128
+
+static void time_a_float32_z_float128( float128 function( float32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float32[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float32[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#endif
+
+static void time_az_float32( float32 function( float32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float32[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float32[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_ab_float32_z_flag( flag function( float32, float32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNumA, inputNumB;
+
+    count = 0;
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function(
+                inputs_float32[ inputNumA ], inputs_float32[ inputNumB ] );
+            inputNumA = ( inputNumA + 1 ) & ( numInputs_float32 - 1 );
+            if ( inputNumA == 0 ) ++inputNumB;
+            inputNumB = ( inputNumB + 1 ) & ( numInputs_float32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+            function(
+                inputs_float32[ inputNumA ], inputs_float32[ inputNumB ] );
+        inputNumA = ( inputNumA + 1 ) & ( numInputs_float32 - 1 );
+        if ( inputNumA == 0 ) ++inputNumB;
+        inputNumB = ( inputNumB + 1 ) & ( numInputs_float32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_abz_float32( float32 function( float32, float32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNumA, inputNumB;
+
+    count = 0;
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function(
+                inputs_float32[ inputNumA ], inputs_float32[ inputNumB ] );
+            inputNumA = ( inputNumA + 1 ) & ( numInputs_float32 - 1 );
+            if ( inputNumA == 0 ) ++inputNumB;
+            inputNumB = ( inputNumB + 1 ) & ( numInputs_float32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+            function(
+                inputs_float32[ inputNumA ], inputs_float32[ inputNumB ] );
+        inputNumA = ( inputNumA + 1 ) & ( numInputs_float32 - 1 );
+        if ( inputNumA == 0 ) ++inputNumB;
+        inputNumB = ( inputNumB + 1 ) & ( numInputs_float32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static const float32 inputs_float32_pos[ numInputs_float32 ] = {
+    0x4EFA0000, 0x41D0B328, 0x00000000, 0x3E69A31E,
+    0x2F803EFF, 0x3F800000, 0x17BF8000, 0x674A301A,
+    0x4E010003, 0x7EE3C75D, 0x3D803FE0, 0x3FFEFF00,
+    0x7981F800, 0x431FFFFC, 0x4100C000, 0x3D87EFFF,
+    0x4103FEFE, 0x3C000007, 0x3F01F7FF, 0x4E6C6B5C,
+    0x4187FFFE, 0x458B9F13, 0x4F88007F, 0x5F004007,
+    0x37FFD7FE, 0x7E8001FB, 0x46EFFBFF, 0x31C10000,
+    0x5B428661, 0x33F89B1F, 0x23BFEFFF, 0x537BFFBE
+};
+
+static void time_az_float32_pos( float32 function( float32 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float32_pos[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float32_pos[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float32 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+enum {
+    numInputs_float64 = 32
+};
+
+static const float64 inputs_float64[ numInputs_float64 ] = {
+    LIT64( 0x422FFFC008000000 ),
+    LIT64( 0xB7E0000480000000 ),
+    LIT64( 0xF3FD2546120B7935 ),
+    LIT64( 0x3FF0000000000000 ),
+    LIT64( 0xCE07F766F09588D6 ),
+    LIT64( 0x8000000000000000 ),
+    LIT64( 0x3FCE000400000000 ),
+    LIT64( 0x8313B60F0032BED8 ),
+    LIT64( 0xC1EFFFFFC0002000 ),
+    LIT64( 0x3FB3C75D224F2B0F ),
+    LIT64( 0x7FD00000004000FF ),
+    LIT64( 0xA12FFF8000001FFF ),
+    LIT64( 0x3EE0000000FE0000 ),
+    LIT64( 0x0010000080000004 ),
+    LIT64( 0x41CFFFFE00000020 ),
+    LIT64( 0x40303FFFFFFFFFFD ),
+    LIT64( 0x3FD000003FEFFFFF ),
+    LIT64( 0xBFD0000010000000 ),
+    LIT64( 0xB7FC6B5C16CA55CF ),
+    LIT64( 0x413EEB940B9D1301 ),
+    LIT64( 0xC7E00200001FFFFF ),
+    LIT64( 0x47F00021FFFFFFFE ),
+    LIT64( 0xBFFFFFFFF80000FF ),
+    LIT64( 0xC07FFFFFE00FFFFF ),
+    LIT64( 0x001497A63740C5E8 ),
+    LIT64( 0xC4BFFFE0001FFFFF ),
+    LIT64( 0x96FFDFFEFFFFFFFF ),
+    LIT64( 0x403FC000000001FE ),
+    LIT64( 0xFFD00000000001F6 ),
+    LIT64( 0x0640400002000000 ),
+    LIT64( 0x479CEE1E4F789FE0 ),
+    LIT64( 0xC237FFFFFFFFFDFE )
+};
+
+static void time_a_float64_z_int32( int32 function( float64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float64[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float64[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_a_float64_z_int64( int64 function( float64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float64[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float64[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_a_float64_z_float32( float32 function( float64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float64[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float64[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#ifdef FLOATX80
+
+static void time_a_float64_z_floatx80( floatx80 function( float64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float64[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float64[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#endif
+
+#ifdef FLOAT128
+
+static void time_a_float64_z_float128( float128 function( float64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float64[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float64[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#endif
+
+static void time_az_float64( float64 function( float64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float64[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float64[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_ab_float64_z_flag( flag function( float64, float64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNumA, inputNumB;
+
+    count = 0;
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function(
+                inputs_float64[ inputNumA ], inputs_float64[ inputNumB ] );
+            inputNumA = ( inputNumA + 1 ) & ( numInputs_float64 - 1 );
+            if ( inputNumA == 0 ) ++inputNumB;
+            inputNumB = ( inputNumB + 1 ) & ( numInputs_float64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+            function(
+                inputs_float64[ inputNumA ], inputs_float64[ inputNumB ] );
+        inputNumA = ( inputNumA + 1 ) & ( numInputs_float64 - 1 );
+        if ( inputNumA == 0 ) ++inputNumB;
+        inputNumB = ( inputNumB + 1 ) & ( numInputs_float64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_abz_float64( float64 function( float64, float64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNumA, inputNumB;
+
+    count = 0;
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function(
+                inputs_float64[ inputNumA ], inputs_float64[ inputNumB ] );
+            inputNumA = ( inputNumA + 1 ) & ( numInputs_float64 - 1 );
+            if ( inputNumA == 0 ) ++inputNumB;
+            inputNumB = ( inputNumB + 1 ) & ( numInputs_float64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+            function(
+                inputs_float64[ inputNumA ], inputs_float64[ inputNumB ] );
+        inputNumA = ( inputNumA + 1 ) & ( numInputs_float64 - 1 );
+        if ( inputNumA == 0 ) ++inputNumB;
+        inputNumB = ( inputNumB + 1 ) & ( numInputs_float64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static const float64 inputs_float64_pos[ numInputs_float64 ] = {
+    LIT64( 0x422FFFC008000000 ),
+    LIT64( 0x37E0000480000000 ),
+    LIT64( 0x73FD2546120B7935 ),
+    LIT64( 0x3FF0000000000000 ),
+    LIT64( 0x4E07F766F09588D6 ),
+    LIT64( 0x0000000000000000 ),
+    LIT64( 0x3FCE000400000000 ),
+    LIT64( 0x0313B60F0032BED8 ),
+    LIT64( 0x41EFFFFFC0002000 ),
+    LIT64( 0x3FB3C75D224F2B0F ),
+    LIT64( 0x7FD00000004000FF ),
+    LIT64( 0x212FFF8000001FFF ),
+    LIT64( 0x3EE0000000FE0000 ),
+    LIT64( 0x0010000080000004 ),
+    LIT64( 0x41CFFFFE00000020 ),
+    LIT64( 0x40303FFFFFFFFFFD ),
+    LIT64( 0x3FD000003FEFFFFF ),
+    LIT64( 0x3FD0000010000000 ),
+    LIT64( 0x37FC6B5C16CA55CF ),
+    LIT64( 0x413EEB940B9D1301 ),
+    LIT64( 0x47E00200001FFFFF ),
+    LIT64( 0x47F00021FFFFFFFE ),
+    LIT64( 0x3FFFFFFFF80000FF ),
+    LIT64( 0x407FFFFFE00FFFFF ),
+    LIT64( 0x001497A63740C5E8 ),
+    LIT64( 0x44BFFFE0001FFFFF ),
+    LIT64( 0x16FFDFFEFFFFFFFF ),
+    LIT64( 0x403FC000000001FE ),
+    LIT64( 0x7FD00000000001F6 ),
+    LIT64( 0x0640400002000000 ),
+    LIT64( 0x479CEE1E4F789FE0 ),
+    LIT64( 0x4237FFFFFFFFFDFE )
+};
+
+static void time_az_float64_pos( float64 function( float64 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            function( inputs_float64_pos[ inputNum ] );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        function( inputs_float64_pos[ inputNum ] );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float64 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#ifdef FLOATX80
+
+enum {
+    numInputs_floatx80 = 32
+};
+
+static const struct {
+    bits16 high;
+    bits64 low;
+} inputs_floatx80[ numInputs_floatx80 ] = {
+    { 0xC03F, LIT64( 0xA9BE15A19C1E8B62 ) },
+    { 0x8000, LIT64( 0x0000000000000000 ) },
+    { 0x75A8, LIT64( 0xE59591E4788957A5 ) },
+    { 0xBFFF, LIT64( 0xFFF0000000000040 ) },
+    { 0x0CD8, LIT64( 0xFC000000000007FE ) },
+    { 0x43BA, LIT64( 0x99A4000000000000 ) },
+    { 0x3FFF, LIT64( 0x8000000000000000 ) },
+    { 0x4081, LIT64( 0x94FBF1BCEB5545F0 ) },
+    { 0x403E, LIT64( 0xFFF0000000002000 ) },
+    { 0x3FFE, LIT64( 0xC860E3C75D224F28 ) },
+    { 0x407E, LIT64( 0xFC00000FFFFFFFFE ) },
+    { 0x737A, LIT64( 0x800000007FFDFFFE ) },
+    { 0x4044, LIT64( 0xFFFFFF80000FFFFF ) },
+    { 0xBBFE, LIT64( 0x8000040000001FFE ) },
+    { 0xC002, LIT64( 0xFF80000000000020 ) },
+    { 0xDE8D, LIT64( 0xFFFFFFFFFFE00004 ) },
+    { 0xC004, LIT64( 0x8000000000003FFB ) },
+    { 0x407F, LIT64( 0x800000000003FFFE ) },
+    { 0xC000, LIT64( 0xA459EE6A5C16CA55 ) },
+    { 0x8003, LIT64( 0xC42CBF7399AEEB94 ) },
+    { 0xBF7F, LIT64( 0xF800000000000006 ) },
+    { 0xC07F, LIT64( 0xBF56BE8871F28FEA ) },
+    { 0xC07E, LIT64( 0xFFFF77FFFFFFFFFE ) },
+    { 0xADC9, LIT64( 0x8000000FFFFFFFDE ) },
+    { 0xC001, LIT64( 0xEFF7FFFFFFFFFFFF ) },
+    { 0x4001, LIT64( 0xBE84F30125C497A6 ) },
+    { 0xC06B, LIT64( 0xEFFFFFFFFFFFFFFF ) },
+    { 0x4080, LIT64( 0xFFFFFFFFBFFFFFFF ) },
+    { 0x87E9, LIT64( 0x81FFFFFFFFFFFBFF ) },
+    { 0xA63F, LIT64( 0x801FFFFFFEFFFFFE ) },
+    { 0x403C, LIT64( 0x801FFFFFFFF7FFFF ) },
+    { 0x4018, LIT64( 0x8000000000080003 ) }
+};
+
+static void time_a_floatx80_z_int32( int32 function( floatx80 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    floatx80 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_floatx80[ inputNum ].low;
+            a.high = inputs_floatx80[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_floatx80[ inputNum ].low;
+        a.high = inputs_floatx80[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_a_floatx80_z_int64( int64 function( floatx80 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    floatx80 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_floatx80[ inputNum ].low;
+            a.high = inputs_floatx80[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_floatx80[ inputNum ].low;
+        a.high = inputs_floatx80[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_a_floatx80_z_float32( float32 function( floatx80 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    floatx80 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_floatx80[ inputNum ].low;
+            a.high = inputs_floatx80[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_floatx80[ inputNum ].low;
+        a.high = inputs_floatx80[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_a_floatx80_z_float64( float64 function( floatx80 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    floatx80 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_floatx80[ inputNum ].low;
+            a.high = inputs_floatx80[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_floatx80[ inputNum ].low;
+        a.high = inputs_floatx80[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#ifdef FLOAT128
+
+static void time_a_floatx80_z_float128( float128 function( floatx80 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    floatx80 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_floatx80[ inputNum ].low;
+            a.high = inputs_floatx80[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_floatx80[ inputNum ].low;
+        a.high = inputs_floatx80[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#endif
+
+static void time_az_floatx80( floatx80 function( floatx80 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    floatx80 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_floatx80[ inputNum ].low;
+            a.high = inputs_floatx80[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_floatx80[ inputNum ].low;
+        a.high = inputs_floatx80[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_ab_floatx80_z_flag( flag function( floatx80, floatx80 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNumA, inputNumB;
+    floatx80 a, b;
+
+    count = 0;
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_floatx80[ inputNumA ].low;
+            a.high = inputs_floatx80[ inputNumA ].high;
+            b.low = inputs_floatx80[ inputNumB ].low;
+            b.high = inputs_floatx80[ inputNumB ].high;
+            function( a, b );
+            inputNumA = ( inputNumA + 1 ) & ( numInputs_floatx80 - 1 );
+            if ( inputNumA == 0 ) ++inputNumB;
+            inputNumB = ( inputNumB + 1 ) & ( numInputs_floatx80 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_floatx80[ inputNumA ].low;
+        a.high = inputs_floatx80[ inputNumA ].high;
+        b.low = inputs_floatx80[ inputNumB ].low;
+        b.high = inputs_floatx80[ inputNumB ].high;
+        function( a, b );
+        inputNumA = ( inputNumA + 1 ) & ( numInputs_floatx80 - 1 );
+        if ( inputNumA == 0 ) ++inputNumB;
+        inputNumB = ( inputNumB + 1 ) & ( numInputs_floatx80 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_abz_floatx80( floatx80 function( floatx80, floatx80 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNumA, inputNumB;
+    floatx80 a, b;
+
+    count = 0;
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_floatx80[ inputNumA ].low;
+            a.high = inputs_floatx80[ inputNumA ].high;
+            b.low = inputs_floatx80[ inputNumB ].low;
+            b.high = inputs_floatx80[ inputNumB ].high;
+            function( a, b );
+            inputNumA = ( inputNumA + 1 ) & ( numInputs_floatx80 - 1 );
+            if ( inputNumA == 0 ) ++inputNumB;
+            inputNumB = ( inputNumB + 1 ) & ( numInputs_floatx80 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_floatx80[ inputNumA ].low;
+        a.high = inputs_floatx80[ inputNumA ].high;
+        b.low = inputs_floatx80[ inputNumB ].low;
+        b.high = inputs_floatx80[ inputNumB ].high;
+        function( a, b );
+        inputNumA = ( inputNumA + 1 ) & ( numInputs_floatx80 - 1 );
+        if ( inputNumA == 0 ) ++inputNumB;
+        inputNumB = ( inputNumB + 1 ) & ( numInputs_floatx80 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static const struct {
+    bits16 high;
+    bits64 low;
+} inputs_floatx80_pos[ numInputs_floatx80 ] = {
+    { 0x403F, LIT64( 0xA9BE15A19C1E8B62 ) },
+    { 0x0000, LIT64( 0x0000000000000000 ) },
+    { 0x75A8, LIT64( 0xE59591E4788957A5 ) },
+    { 0x3FFF, LIT64( 0xFFF0000000000040 ) },
+    { 0x0CD8, LIT64( 0xFC000000000007FE ) },
+    { 0x43BA, LIT64( 0x99A4000000000000 ) },
+    { 0x3FFF, LIT64( 0x8000000000000000 ) },
+    { 0x4081, LIT64( 0x94FBF1BCEB5545F0 ) },
+    { 0x403E, LIT64( 0xFFF0000000002000 ) },
+    { 0x3FFE, LIT64( 0xC860E3C75D224F28 ) },
+    { 0x407E, LIT64( 0xFC00000FFFFFFFFE ) },
+    { 0x737A, LIT64( 0x800000007FFDFFFE ) },
+    { 0x4044, LIT64( 0xFFFFFF80000FFFFF ) },
+    { 0x3BFE, LIT64( 0x8000040000001FFE ) },
+    { 0x4002, LIT64( 0xFF80000000000020 ) },
+    { 0x5E8D, LIT64( 0xFFFFFFFFFFE00004 ) },
+    { 0x4004, LIT64( 0x8000000000003FFB ) },
+    { 0x407F, LIT64( 0x800000000003FFFE ) },
+    { 0x4000, LIT64( 0xA459EE6A5C16CA55 ) },
+    { 0x0003, LIT64( 0xC42CBF7399AEEB94 ) },
+    { 0x3F7F, LIT64( 0xF800000000000006 ) },
+    { 0x407F, LIT64( 0xBF56BE8871F28FEA ) },
+    { 0x407E, LIT64( 0xFFFF77FFFFFFFFFE ) },
+    { 0x2DC9, LIT64( 0x8000000FFFFFFFDE ) },
+    { 0x4001, LIT64( 0xEFF7FFFFFFFFFFFF ) },
+    { 0x4001, LIT64( 0xBE84F30125C497A6 ) },
+    { 0x406B, LIT64( 0xEFFFFFFFFFFFFFFF ) },
+    { 0x4080, LIT64( 0xFFFFFFFFBFFFFFFF ) },
+    { 0x07E9, LIT64( 0x81FFFFFFFFFFFBFF ) },
+    { 0x263F, LIT64( 0x801FFFFFFEFFFFFE ) },
+    { 0x403C, LIT64( 0x801FFFFFFFF7FFFF ) },
+    { 0x4018, LIT64( 0x8000000000080003 ) }
+};
+
+static void time_az_floatx80_pos( floatx80 function( floatx80 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    floatx80 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_floatx80_pos[ inputNum ].low;
+            a.high = inputs_floatx80_pos[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_floatx80_pos[ inputNum ].low;
+        a.high = inputs_floatx80_pos[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_floatx80 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#endif
+
+#ifdef FLOAT128
+
+enum {
+    numInputs_float128 = 32
+};
+
+static const struct {
+    bits64 high, low;
+} inputs_float128[ numInputs_float128 ] = {
+    { LIT64( 0x3FDA200000100000 ), LIT64( 0x0000000000000000 ) },
+    { LIT64( 0x3FFF000000000000 ), LIT64( 0x0000000000000000 ) },
+    { LIT64( 0x85F14776190C8306 ), LIT64( 0xD8715F4E3D54BB92 ) },
+    { LIT64( 0xF2B00000007FFFFF ), LIT64( 0xFFFFFFFFFFF7FFFF ) },
+    { LIT64( 0x8000000000000000 ), LIT64( 0x0000000000000000 ) },
+    { LIT64( 0xBFFFFFFFFFE00000 ), LIT64( 0x0000008000000000 ) },
+    { LIT64( 0x407F1719CE722F3E ), LIT64( 0xDA6B3FE5FF29425B ) },
+    { LIT64( 0x43FFFF8000000000 ), LIT64( 0x0000000000400000 ) },
+    { LIT64( 0x401E000000000100 ), LIT64( 0x0000000000002000 ) },
+    { LIT64( 0x3FFED71DACDA8E47 ), LIT64( 0x4860E3C75D224F28 ) },
+    { LIT64( 0xBF7ECFC1E90647D1 ), LIT64( 0x7A124FE55623EE44 ) },
+    { LIT64( 0x0DF7007FFFFFFFFF ), LIT64( 0xFFFFFFFFEFFFFFFF ) },
+    { LIT64( 0x3FE5FFEFFFFFFFFF ), LIT64( 0xFFFFFFFFFFFFEFFF ) },
+    { LIT64( 0x403FFFFFFFFFFFFF ), LIT64( 0xFFFFFFFFFFFFFBFE ) },
+    { LIT64( 0xBFFB2FBF7399AFEB ), LIT64( 0xA459EE6A5C16CA55 ) },
+    { LIT64( 0xBDB8FFFFFFFFFFFC ), LIT64( 0x0000000000000400 ) },
+    { LIT64( 0x3FC8FFDFFFFFFFFF ), LIT64( 0xFFFFFFFFF0000000 ) },
+    { LIT64( 0x3FFBFFFFFFDFFFFF ), LIT64( 0xFFF8000000000000 ) },
+    { LIT64( 0x407043C11737BE84 ), LIT64( 0xDDD58212ADC937F4 ) },
+    { LIT64( 0x8001000000000000 ), LIT64( 0x0000001000000001 ) },
+    { LIT64( 0xC036FFFFFFFFFFFF ), LIT64( 0xFE40000000000000 ) },
+    { LIT64( 0x4002FFFFFE000002 ), LIT64( 0x0000000000000000 ) },
+    { LIT64( 0x4000C3FEDE897773 ), LIT64( 0x326AC4FD8EFBE6DC ) },
+    { LIT64( 0xBFFF0000000FFFFF ), LIT64( 0xFFFFFE0000000000 ) },
+    { LIT64( 0x62C3E502146E426D ), LIT64( 0x43F3CAA0DC7DF1A0 ) },
+    { LIT64( 0xB5CBD32E52BB570E ), LIT64( 0xBCC477CB11C6236C ) },
+    { LIT64( 0xE228FFFFFFC00000 ), LIT64( 0x0000000000000000 ) },
+    { LIT64( 0x3F80000000000000 ), LIT64( 0x0000000080000008 ) },
+    { LIT64( 0xC1AFFFDFFFFFFFFF ), LIT64( 0xFFFC000000000000 ) },
+    { LIT64( 0xC96F000000000000 ), LIT64( 0x00000001FFFBFFFF ) },
+    { LIT64( 0x3DE09BFE7923A338 ), LIT64( 0xBCC8FBBD7CEC1F4F ) },
+    { LIT64( 0x401CFFFFFFFFFFFF ), LIT64( 0xFFFFFFFEFFFFFF80 ) }
+};
+
+static void time_a_float128_z_int32( int32 function( float128 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    float128 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_float128[ inputNum ].low;
+            a.high = inputs_float128[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_float128[ inputNum ].low;
+        a.high = inputs_float128[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_a_float128_z_int64( int64 function( float128 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    float128 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_float128[ inputNum ].low;
+            a.high = inputs_float128[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_float128[ inputNum ].low;
+        a.high = inputs_float128[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_a_float128_z_float32( float32 function( float128 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    float128 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_float128[ inputNum ].low;
+            a.high = inputs_float128[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_float128[ inputNum ].low;
+        a.high = inputs_float128[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_a_float128_z_float64( float64 function( float128 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    float128 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_float128[ inputNum ].low;
+            a.high = inputs_float128[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_float128[ inputNum ].low;
+        a.high = inputs_float128[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#ifdef FLOATX80
+
+static void time_a_float128_z_floatx80( floatx80 function( float128 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    float128 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_float128[ inputNum ].low;
+            a.high = inputs_float128[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_float128[ inputNum ].low;
+        a.high = inputs_float128[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#endif
+
+static void time_az_float128( float128 function( float128 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    float128 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_float128[ inputNum ].low;
+            a.high = inputs_float128[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_float128[ inputNum ].low;
+        a.high = inputs_float128[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_ab_float128_z_flag( flag function( float128, float128 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNumA, inputNumB;
+    float128 a, b;
+
+    count = 0;
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_float128[ inputNumA ].low;
+            a.high = inputs_float128[ inputNumA ].high;
+            b.low = inputs_float128[ inputNumB ].low;
+            b.high = inputs_float128[ inputNumB ].high;
+            function( a, b );
+            inputNumA = ( inputNumA + 1 ) & ( numInputs_float128 - 1 );
+            if ( inputNumA == 0 ) ++inputNumB;
+            inputNumB = ( inputNumB + 1 ) & ( numInputs_float128 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_float128[ inputNumA ].low;
+        a.high = inputs_float128[ inputNumA ].high;
+        b.low = inputs_float128[ inputNumB ].low;
+        b.high = inputs_float128[ inputNumB ].high;
+        function( a, b );
+        inputNumA = ( inputNumA + 1 ) & ( numInputs_float128 - 1 );
+        if ( inputNumA == 0 ) ++inputNumB;
+        inputNumB = ( inputNumB + 1 ) & ( numInputs_float128 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static void time_abz_float128( float128 function( float128, float128 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNumA, inputNumB;
+    float128 a, b;
+
+    count = 0;
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_float128[ inputNumA ].low;
+            a.high = inputs_float128[ inputNumA ].high;
+            b.low = inputs_float128[ inputNumB ].low;
+            b.high = inputs_float128[ inputNumB ].high;
+            function( a, b );
+            inputNumA = ( inputNumA + 1 ) & ( numInputs_float128 - 1 );
+            if ( inputNumA == 0 ) ++inputNumB;
+            inputNumB = ( inputNumB + 1 ) & ( numInputs_float128 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNumA = 0;
+    inputNumB = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_float128[ inputNumA ].low;
+        a.high = inputs_float128[ inputNumA ].high;
+        b.low = inputs_float128[ inputNumB ].low;
+        b.high = inputs_float128[ inputNumB ].high;
+        function( a, b );
+        inputNumA = ( inputNumA + 1 ) & ( numInputs_float128 - 1 );
+        if ( inputNumA == 0 ) ++inputNumB;
+        inputNumB = ( inputNumB + 1 ) & ( numInputs_float128 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+static const struct {
+    bits64 high, low;
+} inputs_float128_pos[ numInputs_float128 ] = {
+    { LIT64( 0x3FDA200000100000 ), LIT64( 0x0000000000000000 ) },
+    { LIT64( 0x3FFF000000000000 ), LIT64( 0x0000000000000000 ) },
+    { LIT64( 0x05F14776190C8306 ), LIT64( 0xD8715F4E3D54BB92 ) },
+    { LIT64( 0x72B00000007FFFFF ), LIT64( 0xFFFFFFFFFFF7FFFF ) },
+    { LIT64( 0x0000000000000000 ), LIT64( 0x0000000000000000 ) },
+    { LIT64( 0x3FFFFFFFFFE00000 ), LIT64( 0x0000008000000000 ) },
+    { LIT64( 0x407F1719CE722F3E ), LIT64( 0xDA6B3FE5FF29425B ) },
+    { LIT64( 0x43FFFF8000000000 ), LIT64( 0x0000000000400000 ) },
+    { LIT64( 0x401E000000000100 ), LIT64( 0x0000000000002000 ) },
+    { LIT64( 0x3FFED71DACDA8E47 ), LIT64( 0x4860E3C75D224F28 ) },
+    { LIT64( 0x3F7ECFC1E90647D1 ), LIT64( 0x7A124FE55623EE44 ) },
+    { LIT64( 0x0DF7007FFFFFFFFF ), LIT64( 0xFFFFFFFFEFFFFFFF ) },
+    { LIT64( 0x3FE5FFEFFFFFFFFF ), LIT64( 0xFFFFFFFFFFFFEFFF ) },
+    { LIT64( 0x403FFFFFFFFFFFFF ), LIT64( 0xFFFFFFFFFFFFFBFE ) },
+    { LIT64( 0x3FFB2FBF7399AFEB ), LIT64( 0xA459EE6A5C16CA55 ) },
+    { LIT64( 0x3DB8FFFFFFFFFFFC ), LIT64( 0x0000000000000400 ) },
+    { LIT64( 0x3FC8FFDFFFFFFFFF ), LIT64( 0xFFFFFFFFF0000000 ) },
+    { LIT64( 0x3FFBFFFFFFDFFFFF ), LIT64( 0xFFF8000000000000 ) },
+    { LIT64( 0x407043C11737BE84 ), LIT64( 0xDDD58212ADC937F4 ) },
+    { LIT64( 0x0001000000000000 ), LIT64( 0x0000001000000001 ) },
+    { LIT64( 0x4036FFFFFFFFFFFF ), LIT64( 0xFE40000000000000 ) },
+    { LIT64( 0x4002FFFFFE000002 ), LIT64( 0x0000000000000000 ) },
+    { LIT64( 0x4000C3FEDE897773 ), LIT64( 0x326AC4FD8EFBE6DC ) },
+    { LIT64( 0x3FFF0000000FFFFF ), LIT64( 0xFFFFFE0000000000 ) },
+    { LIT64( 0x62C3E502146E426D ), LIT64( 0x43F3CAA0DC7DF1A0 ) },
+    { LIT64( 0x35CBD32E52BB570E ), LIT64( 0xBCC477CB11C6236C ) },
+    { LIT64( 0x6228FFFFFFC00000 ), LIT64( 0x0000000000000000 ) },
+    { LIT64( 0x3F80000000000000 ), LIT64( 0x0000000080000008 ) },
+    { LIT64( 0x41AFFFDFFFFFFFFF ), LIT64( 0xFFFC000000000000 ) },
+    { LIT64( 0x496F000000000000 ), LIT64( 0x00000001FFFBFFFF ) },
+    { LIT64( 0x3DE09BFE7923A338 ), LIT64( 0xBCC8FBBD7CEC1F4F ) },
+    { LIT64( 0x401CFFFFFFFFFFFF ), LIT64( 0xFFFFFFFEFFFFFF80 ) }
+};
+
+static void time_az_float128_pos( float128 function( float128 ) )
+{
+    clock_t startClock, endClock;
+    int32 count, i;
+    int8 inputNum;
+    float128 a;
+
+    count = 0;
+    inputNum = 0;
+    startClock = clock();
+    do {
+        for ( i = minIterations; i; --i ) {
+            a.low = inputs_float128_pos[ inputNum ].low;
+            a.high = inputs_float128_pos[ inputNum ].high;
+            function( a );
+            inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+        }
+        count += minIterations;
+    } while ( clock() - startClock < CLOCKS_PER_SEC );
+    inputNum = 0;
+    startClock = clock();
+    for ( i = count; i; --i ) {
+        a.low = inputs_float128_pos[ inputNum ].low;
+        a.high = inputs_float128_pos[ inputNum ].high;
+        function( a );
+        inputNum = ( inputNum + 1 ) & ( numInputs_float128 - 1 );
+    }
+    endClock = clock();
+    reportTime( count, endClock - startClock );
+
+}
+
+#endif
+
+enum {
+    INT32_TO_FLOAT32 = 1,
+    INT32_TO_FLOAT64,
+#ifdef FLOATX80
+    INT32_TO_FLOATX80,
+#endif
+#ifdef FLOAT128
+    INT32_TO_FLOAT128,
+#endif
+    INT64_TO_FLOAT32,
+    INT64_TO_FLOAT64,
+#ifdef FLOATX80
+    INT64_TO_FLOATX80,
+#endif
+#ifdef FLOAT128
+    INT64_TO_FLOAT128,
+#endif
+    FLOAT32_TO_INT32,
+    FLOAT32_TO_INT32_ROUND_TO_ZERO,
+    FLOAT32_TO_INT64,
+    FLOAT32_TO_INT64_ROUND_TO_ZERO,
+    FLOAT32_TO_FLOAT64,
+#ifdef FLOATX80
+    FLOAT32_TO_FLOATX80,
+#endif
+#ifdef FLOAT128
+    FLOAT32_TO_FLOAT128,
+#endif
+    FLOAT32_ROUND_TO_INT,
+    FLOAT32_ADD,
+    FLOAT32_SUB,
+    FLOAT32_MUL,
+    FLOAT32_DIV,
+    FLOAT32_REM,
+    FLOAT32_SQRT,
+    FLOAT32_EQ,
+    FLOAT32_LE,
+    FLOAT32_LT,
+    FLOAT32_EQ_SIGNALING,
+    FLOAT32_LE_QUIET,
+    FLOAT32_LT_QUIET,
+    FLOAT64_TO_INT32,
+    FLOAT64_TO_INT32_ROUND_TO_ZERO,
+    FLOAT64_TO_INT64,
+    FLOAT64_TO_INT64_ROUND_TO_ZERO,
+    FLOAT64_TO_FLOAT32,
+#ifdef FLOATX80
+    FLOAT64_TO_FLOATX80,
+#endif
+#ifdef FLOAT128
+    FLOAT64_TO_FLOAT128,
+#endif
+    FLOAT64_ROUND_TO_INT,
+    FLOAT64_ADD,
+    FLOAT64_SUB,
+    FLOAT64_MUL,
+    FLOAT64_DIV,
+    FLOAT64_REM,
+    FLOAT64_SQRT,
+    FLOAT64_EQ,
+    FLOAT64_LE,
+    FLOAT64_LT,
+    FLOAT64_EQ_SIGNALING,
+    FLOAT64_LE_QUIET,
+    FLOAT64_LT_QUIET,
+#ifdef FLOATX80
+    FLOATX80_TO_INT32,
+    FLOATX80_TO_INT32_ROUND_TO_ZERO,
+    FLOATX80_TO_INT64,
+    FLOATX80_TO_INT64_ROUND_TO_ZERO,
+    FLOATX80_TO_FLOAT32,
+    FLOATX80_TO_FLOAT64,
+#ifdef FLOAT128
+    FLOATX80_TO_FLOAT128,
+#endif
+    FLOATX80_ROUND_TO_INT,
+    FLOATX80_ADD,
+    FLOATX80_SUB,
+    FLOATX80_MUL,
+    FLOATX80_DIV,
+    FLOATX80_REM,
+    FLOATX80_SQRT,
+    FLOATX80_EQ,
+    FLOATX80_LE,
+    FLOATX80_LT,
+    FLOATX80_EQ_SIGNALING,
+    FLOATX80_LE_QUIET,
+    FLOATX80_LT_QUIET,
+#endif
+#ifdef FLOAT128
+    FLOAT128_TO_INT32,
+    FLOAT128_TO_INT32_ROUND_TO_ZERO,
+    FLOAT128_TO_INT64,
+    FLOAT128_TO_INT64_ROUND_TO_ZERO,
+    FLOAT128_TO_FLOAT32,
+    FLOAT128_TO_FLOAT64,
+#ifdef FLOATX80
+    FLOAT128_TO_FLOATX80,
+#endif
+    FLOAT128_ROUND_TO_INT,
+    FLOAT128_ADD,
+    FLOAT128_SUB,
+    FLOAT128_MUL,
+    FLOAT128_DIV,
+    FLOAT128_REM,
+    FLOAT128_SQRT,
+    FLOAT128_EQ,
+    FLOAT128_LE,
+    FLOAT128_LT,
+    FLOAT128_EQ_SIGNALING,
+    FLOAT128_LE_QUIET,
+    FLOAT128_LT_QUIET,
+#endif
+    NUM_FUNCTIONS
+};
+
+static struct {
+    char *name;
+    int8 numInputs;
+    flag roundingPrecision, roundingMode;
+    flag tininessMode, tininessModeAtReducedPrecision;
+} functions[ NUM_FUNCTIONS ] = {
+    { 0, 0, 0, 0, 0, 0 },
+    { "int32_to_float32",                1, FALSE, TRUE,  FALSE, FALSE },
+    { "int32_to_float64",                1, FALSE, FALSE, FALSE, FALSE },
+#ifdef FLOATX80
+    { "int32_to_floatx80",               1, FALSE, FALSE, FALSE, FALSE },
+#endif
+#ifdef FLOAT128
+    { "int32_to_float128",               1, FALSE, FALSE, FALSE, FALSE },
+#endif
+    { "int64_to_float32",                1, FALSE, TRUE,  FALSE, FALSE },
+    { "int64_to_float64",                1, FALSE, TRUE,  FALSE, FALSE },
+#ifdef FLOATX80
+    { "int64_to_floatx80",               1, FALSE, FALSE, FALSE, FALSE },
+#endif
+#ifdef FLOAT128
+    { "int64_to_float128",               1, FALSE, FALSE, FALSE, FALSE },
+#endif
+    { "float32_to_int32",                1, FALSE, TRUE,  FALSE, FALSE },
+    { "float32_to_int32_round_to_zero",  1, FALSE, FALSE, FALSE, FALSE },
+    { "float32_to_int64",                1, FALSE, TRUE,  FALSE, FALSE },
+    { "float32_to_int64_round_to_zero",  1, FALSE, FALSE, FALSE, FALSE },
+    { "float32_to_float64",              1, FALSE, FALSE, FALSE, FALSE },
+#ifdef FLOATX80
+    { "float32_to_floatx80",             1, FALSE, FALSE, FALSE, FALSE },
+#endif
+#ifdef FLOAT128
+    { "float32_to_float128",             1, FALSE, FALSE, FALSE, FALSE },
+#endif
+    { "float32_round_to_int",            1, FALSE, TRUE,  FALSE, FALSE },
+    { "float32_add",                     2, FALSE, TRUE,  FALSE, FALSE },
+    { "float32_sub",                     2, FALSE, TRUE,  FALSE, FALSE },
+    { "float32_mul",                     2, FALSE, TRUE,  TRUE,  FALSE },
+    { "float32_div",                     2, FALSE, TRUE,  FALSE, FALSE },
+    { "float32_rem",                     2, FALSE, FALSE, FALSE, FALSE },
+    { "float32_sqrt",                    1, FALSE, TRUE,  FALSE, FALSE },
+    { "float32_eq",                      2, FALSE, FALSE, FALSE, FALSE },
+    { "float32_le",                      2, FALSE, FALSE, FALSE, FALSE },
+    { "float32_lt",                      2, FALSE, FALSE, FALSE, FALSE },
+    { "float32_eq_signaling",            2, FALSE, FALSE, FALSE, FALSE },
+    { "float32_le_quiet",                2, FALSE, FALSE, FALSE, FALSE },
+    { "float32_lt_quiet",                2, FALSE, FALSE, FALSE, FALSE },
+    { "float64_to_int32",                1, FALSE, TRUE,  FALSE, FALSE },
+    { "float64_to_int32_round_to_zero",  1, FALSE, FALSE, FALSE, FALSE },
+    { "float64_to_int64",                1, FALSE, TRUE,  FALSE, FALSE },
+    { "float64_to_int64_round_to_zero",  1, FALSE, FALSE, FALSE, FALSE },
+    { "float64_to_float32",              1, FALSE, TRUE,  TRUE,  FALSE },
+#ifdef FLOATX80
+    { "float64_to_floatx80",             1, FALSE, FALSE, FALSE, FALSE },
+#endif
+#ifdef FLOAT128
+    { "float64_to_float128",             1, FALSE, FALSE, FALSE, FALSE },
+#endif
+    { "float64_round_to_int",            1, FALSE, TRUE,  FALSE, FALSE },
+    { "float64_add",                     2, FALSE, TRUE,  FALSE, FALSE },
+    { "float64_sub",                     2, FALSE, TRUE,  FALSE, FALSE },
+    { "float64_mul",                     2, FALSE, TRUE,  TRUE,  FALSE },
+    { "float64_div",                     2, FALSE, TRUE,  FALSE, FALSE },
+    { "float64_rem",                     2, FALSE, FALSE, FALSE, FALSE },
+    { "float64_sqrt",                    1, FALSE, TRUE,  FALSE, FALSE },
+    { "float64_eq",                      2, FALSE, FALSE, FALSE, FALSE },
+    { "float64_le",                      2, FALSE, FALSE, FALSE, FALSE },
+    { "float64_lt",                      2, FALSE, FALSE, FALSE, FALSE },
+    { "float64_eq_signaling",            2, FALSE, FALSE, FALSE, FALSE },
+    { "float64_le_quiet",                2, FALSE, FALSE, FALSE, FALSE },
+    { "float64_lt_quiet",                2, FALSE, FALSE, FALSE, FALSE },
+#ifdef FLOATX80
+    { "floatx80_to_int32",               1, FALSE, TRUE,  FALSE, FALSE },
+    { "floatx80_to_int32_round_to_zero", 1, FALSE, FALSE, FALSE, FALSE },
+    { "floatx80_to_int64",               1, FALSE, TRUE,  FALSE, FALSE },
+    { "floatx80_to_int64_round_to_zero", 1, FALSE, FALSE, FALSE, FALSE },
+    { "floatx80_to_float32",             1, FALSE, TRUE,  TRUE,  FALSE },
+    { "floatx80_to_float64",             1, FALSE, TRUE,  TRUE,  FALSE },
+#ifdef FLOAT128
+    { "floatx80_to_float128",            1, FALSE, FALSE, FALSE, FALSE },
+#endif
+    { "floatx80_round_to_int",           1, FALSE, TRUE,  FALSE, FALSE },
+    { "floatx80_add",                    2, TRUE,  TRUE,  FALSE, TRUE  },
+    { "floatx80_sub",                    2, TRUE,  TRUE,  FALSE, TRUE  },
+    { "floatx80_mul",                    2, TRUE,  TRUE,  TRUE,  TRUE  },
+    { "floatx80_div",                    2, TRUE,  TRUE,  FALSE, TRUE  },
+    { "floatx80_rem",                    2, FALSE, FALSE, FALSE, FALSE },
+    { "floatx80_sqrt",                   1, TRUE,  TRUE,  FALSE, FALSE },
+    { "floatx80_eq",                     2, FALSE, FALSE, FALSE, FALSE },
+    { "floatx80_le",                     2, FALSE, FALSE, FALSE, FALSE },
+    { "floatx80_lt",                     2, FALSE, FALSE, FALSE, FALSE },
+    { "floatx80_eq_signaling",           2, FALSE, FALSE, FALSE, FALSE },
+    { "floatx80_le_quiet",               2, FALSE, FALSE, FALSE, FALSE },
+    { "floatx80_lt_quiet",               2, FALSE, FALSE, FALSE, FALSE },
+#endif
+#ifdef FLOAT128
+    { "float128_to_int32",               1, FALSE, TRUE,  FALSE, FALSE },
+    { "float128_to_int32_round_to_zero", 1, FALSE, FALSE, FALSE, FALSE },
+    { "float128_to_int64",               1, FALSE, TRUE,  FALSE, FALSE },
+    { "float128_to_int64_round_to_zero", 1, FALSE, FALSE, FALSE, FALSE },
+    { "float128_to_float32",             1, FALSE, TRUE,  TRUE,  FALSE },
+    { "float128_to_float64",             1, FALSE, TRUE,  TRUE,  FALSE },
+#ifdef FLOATX80
+    { "float128_to_floatx80",            1, FALSE, TRUE,  TRUE,  FALSE },
+#endif
+    { "float128_round_to_int",           1, FALSE, TRUE,  FALSE, FALSE },
+    { "float128_add",                    2, FALSE, TRUE,  FALSE, FALSE },
+    { "float128_sub",                    2, FALSE, TRUE,  FALSE, FALSE },
+    { "float128_mul",                    2, FALSE, TRUE,  TRUE,  FALSE },
+    { "float128_div",                    2, FALSE, TRUE,  FALSE, FALSE },
+    { "float128_rem",                    2, FALSE, FALSE, FALSE, FALSE },
+    { "float128_sqrt",                   1, FALSE, TRUE,  FALSE, FALSE },
+    { "float128_eq",                     2, FALSE, FALSE, FALSE, FALSE },
+    { "float128_le",                     2, FALSE, FALSE, FALSE, FALSE },
+    { "float128_lt",                     2, FALSE, FALSE, FALSE, FALSE },
+    { "float128_eq_signaling",           2, FALSE, FALSE, FALSE, FALSE },
+    { "float128_le_quiet",               2, FALSE, FALSE, FALSE, FALSE },
+    { "float128_lt_quiet",               2, FALSE, FALSE, FALSE, FALSE },
+#endif
+};
+
+enum {
+    ROUND_NEAREST_EVEN = 1,
+    ROUND_TO_ZERO,
+    ROUND_DOWN,
+    ROUND_UP,
+    NUM_ROUNDINGMODES
+};
+enum {
+    TININESS_BEFORE_ROUNDING = 1,
+    TININESS_AFTER_ROUNDING,
+    NUM_TININESSMODES
+};
+
+static void
+ timeFunctionVariety(
+     uint8 functionCode,
+     int8 roundingPrecision,
+     int8 roundingMode,
+     int8 tininessMode
+ )
+{
+    uint8 roundingCode;
+    int8 tininessCode;
+
+    functionName = functions[ functionCode ].name;
+    if ( roundingPrecision == 32 ) {
+        roundingPrecisionName = "32";
+    }
+    else if ( roundingPrecision == 64 ) {
+        roundingPrecisionName = "64";
+    }
+    else if ( roundingPrecision == 80 ) {
+        roundingPrecisionName = "80";
+    }
+    else {
+        roundingPrecisionName = 0;
+    }
+#ifdef FLOATX80
+    floatx80_rounding_precision = roundingPrecision;
+#endif
+    switch ( roundingMode ) {
+     case 0:
+        roundingModeName = 0;
+        roundingCode = float_round_nearest_even;
+        break;
+     case ROUND_NEAREST_EVEN:
+        roundingModeName = "nearest_even";
+        roundingCode = float_round_nearest_even;
+        break;
+     case ROUND_TO_ZERO:
+        roundingModeName = "to_zero";
+        roundingCode = float_round_to_zero;
+        break;
+     case ROUND_DOWN:
+        roundingModeName = "down";
+        roundingCode = float_round_down;
+        break;
+     case ROUND_UP:
+        roundingModeName = "up";
+        roundingCode = float_round_up;
+        break;
+    }
+    float_rounding_mode = roundingCode;
+    switch ( tininessMode ) {
+     case 0:
+        tininessModeName = 0;
+        tininessCode = float_tininess_after_rounding;
+        break;
+     case TININESS_BEFORE_ROUNDING:
+        tininessModeName = "before";
+        tininessCode = float_tininess_before_rounding;
+        break;
+     case TININESS_AFTER_ROUNDING:
+        tininessModeName = "after";
+        tininessCode = float_tininess_after_rounding;
+        break;
+    }
+    float_detect_tininess = tininessCode;
+    switch ( functionCode ) {
+     case INT32_TO_FLOAT32:
+        time_a_int32_z_float32( int32_to_float32 );
+        break;
+     case INT32_TO_FLOAT64:
+        time_a_int32_z_float64( int32_to_float64 );
+        break;
+#ifdef FLOATX80
+     case INT32_TO_FLOATX80:
+        time_a_int32_z_floatx80( int32_to_floatx80 );
+        break;
+#endif
+#ifdef FLOAT128
+     case INT32_TO_FLOAT128:
+        time_a_int32_z_float128( int32_to_float128 );
+        break;
+#endif
+     case INT64_TO_FLOAT32:
+        time_a_int64_z_float32( int64_to_float32 );
+        break;
+     case INT64_TO_FLOAT64:
+        time_a_int64_z_float64( int64_to_float64 );
+        break;
+#ifdef FLOATX80
+     case INT64_TO_FLOATX80:
+        time_a_int64_z_floatx80( int64_to_floatx80 );
+        break;
+#endif
+#ifdef FLOAT128
+     case INT64_TO_FLOAT128:
+        time_a_int64_z_float128( int64_to_float128 );
+        break;
+#endif
+     case FLOAT32_TO_INT32:
+        time_a_float32_z_int32( float32_to_int32 );
+        break;
+     case FLOAT32_TO_INT32_ROUND_TO_ZERO:
+        time_a_float32_z_int32( float32_to_int32_round_to_zero );
+        break;
+     case FLOAT32_TO_INT64:
+        time_a_float32_z_int64( float32_to_int64 );
+        break;
+     case FLOAT32_TO_INT64_ROUND_TO_ZERO:
+        time_a_float32_z_int64( float32_to_int64_round_to_zero );
+        break;
+     case FLOAT32_TO_FLOAT64:
+        time_a_float32_z_float64( float32_to_float64 );
+        break;
+#ifdef FLOATX80
+     case FLOAT32_TO_FLOATX80:
+        time_a_float32_z_floatx80( float32_to_floatx80 );
+        break;
+#endif
+#ifdef FLOAT128
+     case FLOAT32_TO_FLOAT128:
+        time_a_float32_z_float128( float32_to_float128 );
+        break;
+#endif
+     case FLOAT32_ROUND_TO_INT:
+        time_az_float32( float32_round_to_int );
+        break;
+     case FLOAT32_ADD:
+        time_abz_float32( float32_add );
+        break;
+     case FLOAT32_SUB:
+        time_abz_float32( float32_sub );
+        break;
+     case FLOAT32_MUL:
+        time_abz_float32( float32_mul );
+        break;
+     case FLOAT32_DIV:
+        time_abz_float32( float32_div );
+        break;
+     case FLOAT32_REM:
+        time_abz_float32( float32_rem );
+        break;
+     case FLOAT32_SQRT:
+        time_az_float32_pos( float32_sqrt );
+        break;
+     case FLOAT32_EQ:
+        time_ab_float32_z_flag( float32_eq );
+        break;
+     case FLOAT32_LE:
+        time_ab_float32_z_flag( float32_le );
+        break;
+     case FLOAT32_LT:
+        time_ab_float32_z_flag( float32_lt );
+        break;
+     case FLOAT32_EQ_SIGNALING:
+        time_ab_float32_z_flag( float32_eq_signaling );
+        break;
+     case FLOAT32_LE_QUIET:
+        time_ab_float32_z_flag( float32_le_quiet );
+        break;
+     case FLOAT32_LT_QUIET:
+        time_ab_float32_z_flag( float32_lt_quiet );
+        break;
+     case FLOAT64_TO_INT32:
+        time_a_float64_z_int32( float64_to_int32 );
+        break;
+     case FLOAT64_TO_INT32_ROUND_TO_ZERO:
+        time_a_float64_z_int32( float64_to_int32_round_to_zero );
+        break;
+     case FLOAT64_TO_INT64:
+        time_a_float64_z_int64( float64_to_int64 );
+        break;
+     case FLOAT64_TO_INT64_ROUND_TO_ZERO:
+        time_a_float64_z_int64( float64_to_int64_round_to_zero );
+        break;
+     case FLOAT64_TO_FLOAT32:
+        time_a_float64_z_float32( float64_to_float32 );
+        break;
+#ifdef FLOATX80
+     case FLOAT64_TO_FLOATX80:
+        time_a_float64_z_floatx80( float64_to_floatx80 );
+        break;
+#endif
+#ifdef FLOAT128
+     case FLOAT64_TO_FLOAT128:
+        time_a_float64_z_float128( float64_to_float128 );
+        break;
+#endif
+     case FLOAT64_ROUND_TO_INT:
+        time_az_float64( float64_round_to_int );
+        break;
+     case FLOAT64_ADD:
+        time_abz_float64( float64_add );
+        break;
+     case FLOAT64_SUB:
+        time_abz_float64( float64_sub );
+        break;
+     case FLOAT64_MUL:
+        time_abz_float64( float64_mul );
+        break;
+     case FLOAT64_DIV:
+        time_abz_float64( float64_div );
+        break;
+     case FLOAT64_REM:
+        time_abz_float64( float64_rem );
+        break;
+     case FLOAT64_SQRT:
+        time_az_float64_pos( float64_sqrt );
+        break;
+     case FLOAT64_EQ:
+        time_ab_float64_z_flag( float64_eq );
+        break;
+     case FLOAT64_LE:
+        time_ab_float64_z_flag( float64_le );
+        break;
+     case FLOAT64_LT:
+        time_ab_float64_z_flag( float64_lt );
+        break;
+     case FLOAT64_EQ_SIGNALING:
+        time_ab_float64_z_flag( float64_eq_signaling );
+        break;
+     case FLOAT64_LE_QUIET:
+        time_ab_float64_z_flag( float64_le_quiet );
+        break;
+     case FLOAT64_LT_QUIET:
+        time_ab_float64_z_flag( float64_lt_quiet );
+        break;
+#ifdef FLOATX80
+     case FLOATX80_TO_INT32:
+        time_a_floatx80_z_int32( floatx80_to_int32 );
+        break;
+     case FLOATX80_TO_INT32_ROUND_TO_ZERO:
+        time_a_floatx80_z_int32( floatx80_to_int32_round_to_zero );
+        break;
+     case FLOATX80_TO_INT64:
+        time_a_floatx80_z_int64( floatx80_to_int64 );
+        break;
+     case FLOATX80_TO_INT64_ROUND_TO_ZERO:
+        time_a_floatx80_z_int64( floatx80_to_int64_round_to_zero );
+        break;
+     case FLOATX80_TO_FLOAT32:
+        time_a_floatx80_z_float32( floatx80_to_float32 );
+        break;
+     case FLOATX80_TO_FLOAT64:
+        time_a_floatx80_z_float64( floatx80_to_float64 );
+        break;
+#ifdef FLOAT128
+     case FLOATX80_TO_FLOAT128:
+        time_a_floatx80_z_float128( floatx80_to_float128 );
+        break;
+#endif
+     case FLOATX80_ROUND_TO_INT:
+        time_az_floatx80( floatx80_round_to_int );
+        break;
+     case FLOATX80_ADD:
+        time_abz_floatx80( floatx80_add );
+        break;
+     case FLOATX80_SUB:
+        time_abz_floatx80( floatx80_sub );
+        break;
+     case FLOATX80_MUL:
+        time_abz_floatx80( floatx80_mul );
+        break;
+     case FLOATX80_DIV:
+        time_abz_floatx80( floatx80_div );
+        break;
+     case FLOATX80_REM:
+        time_abz_floatx80( floatx80_rem );
+        break;
+     case FLOATX80_SQRT:
+        time_az_floatx80_pos( floatx80_sqrt );
+        break;
+     case FLOATX80_EQ:
+        time_ab_floatx80_z_flag( floatx80_eq );
+        break;
+     case FLOATX80_LE:
+        time_ab_floatx80_z_flag( floatx80_le );
+        break;
+     case FLOATX80_LT:
+        time_ab_floatx80_z_flag( floatx80_lt );
+        break;
+     case FLOATX80_EQ_SIGNALING:
+        time_ab_floatx80_z_flag( floatx80_eq_signaling );
+        break;
+     case FLOATX80_LE_QUIET:
+        time_ab_floatx80_z_flag( floatx80_le_quiet );
+        break;
+     case FLOATX80_LT_QUIET:
+        time_ab_floatx80_z_flag( floatx80_lt_quiet );
+        break;
+#endif
+#ifdef FLOAT128
+     case FLOAT128_TO_INT32:
+        time_a_float128_z_int32( float128_to_int32 );
+        break;
+     case FLOAT128_TO_INT32_ROUND_TO_ZERO:
+        time_a_float128_z_int32( float128_to_int32_round_to_zero );
+        break;
+     case FLOAT128_TO_INT64:
+        time_a_float128_z_int64( float128_to_int64 );
+        break;
+     case FLOAT128_TO_INT64_ROUND_TO_ZERO:
+        time_a_float128_z_int64( float128_to_int64_round_to_zero );
+        break;
+     case FLOAT128_TO_FLOAT32:
+        time_a_float128_z_float32( float128_to_float32 );
+        break;
+     case FLOAT128_TO_FLOAT64:
+        time_a_float128_z_float64( float128_to_float64 );
+        break;
+#ifdef FLOATX80
+     case FLOAT128_TO_FLOATX80:
+        time_a_float128_z_floatx80( float128_to_floatx80 );
+        break;
+#endif
+     case FLOAT128_ROUND_TO_INT:
+        time_az_float128( float128_round_to_int );
+        break;
+     case FLOAT128_ADD:
+        time_abz_float128( float128_add );
+        break;
+     case FLOAT128_SUB:
+        time_abz_float128( float128_sub );
+        break;
+     case FLOAT128_MUL:
+        time_abz_float128( float128_mul );
+        break;
+     case FLOAT128_DIV:
+        time_abz_float128( float128_div );
+        break;
+     case FLOAT128_REM:
+        time_abz_float128( float128_rem );
+        break;
+     case FLOAT128_SQRT:
+        time_az_float128_pos( float128_sqrt );
+        break;
+     case FLOAT128_EQ:
+        time_ab_float128_z_flag( float128_eq );
+        break;
+     case FLOAT128_LE:
+        time_ab_float128_z_flag( float128_le );
+        break;
+     case FLOAT128_LT:
+        time_ab_float128_z_flag( float128_lt );
+        break;
+     case FLOAT128_EQ_SIGNALING:
+        time_ab_float128_z_flag( float128_eq_signaling );
+        break;
+     case FLOAT128_LE_QUIET:
+        time_ab_float128_z_flag( float128_le_quiet );
+        break;
+     case FLOAT128_LT_QUIET:
+        time_ab_float128_z_flag( float128_lt_quiet );
+        break;
+#endif
+    }
+
+}
+
+static void
+ timeFunction(
+     uint8 functionCode,
+     int8 roundingPrecisionIn,
+     int8 roundingModeIn,
+     int8 tininessModeIn
+ )
+{
+    int8 roundingPrecision, roundingMode, tininessMode;
+
+    roundingPrecision = 32;
+    for (;;) {
+        if ( ! functions[ functionCode ].roundingPrecision ) {
+            roundingPrecision = 0;
+        }
+        else if ( roundingPrecisionIn ) {
+            roundingPrecision = roundingPrecisionIn;
+        }
+        for ( roundingMode = 1;
+              roundingMode < NUM_ROUNDINGMODES;
+              ++roundingMode
+            ) {
+            if ( ! functions[ functionCode ].roundingMode ) {
+                roundingMode = 0;
+            }
+            else if ( roundingModeIn ) {
+                roundingMode = roundingModeIn;
+            }
+            for ( tininessMode = 1;
+                  tininessMode < NUM_TININESSMODES;
+                  ++tininessMode
+                ) {
+                if (    ( roundingPrecision == 32 )
+                     || ( roundingPrecision == 64 ) ) {
+                    if ( ! functions[ functionCode ]
+                               .tininessModeAtReducedPrecision
+                       ) {
+                        tininessMode = 0;
+                    }
+                    else if ( tininessModeIn ) {
+                        tininessMode = tininessModeIn;
+                    }
+                }
+                else {
+                    if ( ! functions[ functionCode ].tininessMode ) {
+                        tininessMode = 0;
+                    }
+                    else if ( tininessModeIn ) {
+                        tininessMode = tininessModeIn;
+                    }
+                }
+                timeFunctionVariety(
+                    functionCode, roundingPrecision, roundingMode, tininessMode
+                );
+                if ( tininessModeIn || ! tininessMode ) break;
+            }
+            if ( roundingModeIn || ! roundingMode ) break;
+        }
+        if ( roundingPrecisionIn || ! roundingPrecision ) break;
+        if ( roundingPrecision == 80 ) {
+            break;
+        }
+        else if ( roundingPrecision == 64 ) {
+            roundingPrecision = 80;
+        }
+        else if ( roundingPrecision == 32 ) {
+            roundingPrecision = 64;
+        }
+    }
+
+}
+
+main( int argc, char **argv )
+{
+    char *argPtr;
+    flag functionArgument;
+    uint8 functionCode;
+    int8 operands, roundingPrecision, roundingMode, tininessMode;
+
+    if ( argc <= 1 ) goto writeHelpMessage;
+    functionArgument = FALSE;
+    functionCode = 0;
+    operands = 0;
+    roundingPrecision = 0;
+    roundingMode = 0;
+    tininessMode = 0;
+    --argc;
+    ++argv;
+    while ( argc && ( argPtr = argv[ 0 ] ) ) {
+        if ( argPtr[ 0 ] == '-' ) ++argPtr;
+        if ( strcmp( argPtr, "help" ) == 0 ) {
+ writeHelpMessage:
+            fputs(
+"timesoftfloat [<option>...] <function>\n"
+"  <option>:  (* is default)\n"
+"    -help            --Write this message and exit.\n"
+#ifdef FLOATX80
+"    -precision32     --Only time rounding precision equivalent to float32.\n"
+"    -precision64     --Only time rounding precision equivalent to float64.\n"
+"    -precision80     --Only time maximum rounding precision.\n"
+#endif
+"    -nearesteven     --Only time rounding to nearest/even.\n"
+"    -tozero          --Only time rounding to zero.\n"
+"    -down            --Only time rounding down.\n"
+"    -up              --Only time rounding up.\n"
+"    -tininessbefore  --Only time underflow tininess before rounding.\n"
+"    -tininessafter   --Only time underflow tininess after rounding.\n"
+"  <function>:\n"
+"    int32_to_<float>                 <float>_add   <float>_eq\n"
+"    <float>_to_int32                 <float>_sub   <float>_le\n"
+"    <float>_to_int32_round_to_zero   <float>_mul   <float>_lt\n"
+"    int64_to_<float>                 <float>_div   <float>_eq_signaling\n"
+"    <float>_to_int64                 <float>_rem   <float>_le_quiet\n"
+"    <float>_to_int64_round_to_zero                 <float>_lt_quiet\n"
+"    <float>_to_<float>\n"
+"    <float>_round_to_int\n"
+"    <float>_sqrt\n"
+"    -all1            --All 1-operand functions.\n"
+"    -all2            --All 2-operand functions.\n"
+"    -all             --All functions.\n"
+"  <float>:\n"
+"    float32          --Single precision.\n"
+"    float64          --Double precision.\n"
+#ifdef FLOATX80
+"    floatx80         --Extended double precision.\n"
+#endif
+#ifdef FLOAT128
+"    float128         --Quadruple precision.\n"
+#endif
+                ,
+                stdout
+            );
+            return EXIT_SUCCESS;
+        }
+#ifdef FLOATX80
+        else if ( strcmp( argPtr, "precision32" ) == 0 ) {
+            roundingPrecision = 32;
+        }
+        else if ( strcmp( argPtr, "precision64" ) == 0 ) {
+            roundingPrecision = 64;
+        }
+        else if ( strcmp( argPtr, "precision80" ) == 0 ) {
+            roundingPrecision = 80;
+        }
+#endif
+        else if (    ( strcmp( argPtr, "nearesteven" ) == 0 )
+                  || ( strcmp( argPtr, "nearest_even" ) == 0 ) ) {
+            roundingMode = ROUND_NEAREST_EVEN;
+        }
+        else if (    ( strcmp( argPtr, "tozero" ) == 0 )
+                  || ( strcmp( argPtr, "to_zero" ) == 0 ) ) {
+            roundingMode = ROUND_TO_ZERO;
+        }
+        else if ( strcmp( argPtr, "down" ) == 0 ) {
+            roundingMode = ROUND_DOWN;
+        }
+        else if ( strcmp( argPtr, "up" ) == 0 ) {
+            roundingMode = ROUND_UP;
+        }
+        else if ( strcmp( argPtr, "tininessbefore" ) == 0 ) {
+            tininessMode = TININESS_BEFORE_ROUNDING;
+        }
+        else if ( strcmp( argPtr, "tininessafter" ) == 0 ) {
+            tininessMode = TININESS_AFTER_ROUNDING;
+        }
+        else if ( strcmp( argPtr, "all1" ) == 0 ) {
+            functionArgument = TRUE;
+            functionCode = 0;
+            operands = 1;
+        }
+        else if ( strcmp( argPtr, "all2" ) == 0 ) {
+            functionArgument = TRUE;
+            functionCode = 0;
+            operands = 2;
+        }
+        else if ( strcmp( argPtr, "all" ) == 0 ) {
+            functionArgument = TRUE;
+            functionCode = 0;
+            operands = 0;
+        }
+        else {
+            for ( functionCode = 1;
+                  functionCode < NUM_FUNCTIONS;
+                  ++functionCode 
+                ) {
+                if ( strcmp( argPtr, functions[ functionCode ].name ) == 0 ) {
+                    break;
+                }
+            }
+            if ( functionCode == NUM_FUNCTIONS ) {
+                fail( "Invalid option or function `%s'", argv[ 0 ] );
+            }
+            functionArgument = TRUE;
+        }
+        --argc;
+        ++argv;
+    }
+    if ( ! functionArgument ) fail( "Function argument required" );
+    if ( functionCode ) {
+        timeFunction(
+            functionCode, roundingPrecision, roundingMode, tininessMode );
+    }
+    else if ( operands == 1 ) {
+        for ( functionCode = 1; functionCode < NUM_FUNCTIONS; ++functionCode
+            ) {
+            if ( functions[ functionCode ].numInputs == 1 ) {
+                timeFunction(
+                    functionCode, roundingPrecision, roundingMode, tininessMode
+                );
+            }
+        }
+    }
+    else if ( operands == 2 ) {
+        for ( functionCode = 1; functionCode < NUM_FUNCTIONS; ++functionCode
+            ) {
+            if ( functions[ functionCode ].numInputs == 2 ) {
+                timeFunction(
+                    functionCode, roundingPrecision, roundingMode, tininessMode
+                );
+            }
+        }
+    }
+    else {
+        for ( functionCode = 1; functionCode < NUM_FUNCTIONS; ++functionCode
+            ) {
+            timeFunction(
+                functionCode, roundingPrecision, roundingMode, tininessMode );
+        }
+    }
+    return EXIT_SUCCESS;
+
+}
+
diff --git a/lib/nbsd_libc/softfloat/timesoftfloat.txt b/lib/nbsd_libc/softfloat/timesoftfloat.txt
new file mode 100644 (file)
index 0000000..c1763f9
--- /dev/null
@@ -0,0 +1,149 @@
+$NetBSD: timesoftfloat.txt,v 1.1 2000/06/06 08:15:11 bjh21 Exp $
+
+Documentation for the `timesoftfloat' Program of SoftFloat Release 2a
+
+John R. Hauser
+1998 December 14
+
+
+-------------------------------------------------------------------------------
+Introduction
+
+The `timesoftfloat' program evaluates the speed of SoftFloat's floating-
+point routines.  Each routine can be evaluated for every relevant rounding
+mode, tininess mode, and/or rounding precision.
+
+
+-------------------------------------------------------------------------------
+Contents
+
+    Introduction
+    Contents
+    Legal Notice
+    Executing `timesoftfloat'
+    Options
+        -help
+        -precision32, -precision64, -precision80
+        -nearesteven, -tozero, -down, -up
+        -tininessbefore, -tininessafter
+    Function Sets
+
+
+
+-------------------------------------------------------------------------------
+Legal Notice
+
+The `timesoftfloat' program was written by John R. Hauser.
+
+THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE.  Although reasonable effort
+has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
+TIMES RESULT IN INCORRECT BEHAVIOR.  USE OF THIS SOFTWARE IS RESTRICTED TO
+PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
+AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
+
+
+-------------------------------------------------------------------------------
+Executing `timesoftfloat'
+
+The `timesoftfloat' program is intended to be invoked from a command line
+interpreter as follows:
+
+    timesoftfloat [<option>...] <function>
+
+Here square brackets ([]) indicate optional items, while angled brackets
+(<>) denote parameters to be filled in.  The `<function>' argument is
+the name of the SoftFloat routine to evaluate, such as `float32_add' or
+`float64_to_int32'.  The allowed options are detailed in the next section,
+_Options_.  If `timesoftfloat' is executed without any arguments, a summary
+of usage is written.  It is also possible to evaluate all machine functions
+in a single invocation as explained in the section _Function_Sets_ later in
+this document.
+
+Ordinarily, a function's speed will be evaulated separately for each of
+the four rounding modes, one after the other.  If the rounding mode is not
+supposed to have any affect on the results of a function--for instance,
+some operations do not require rounding--only the nearest/even rounding mode
+is timed.  In the same way, if a function is affected by the way in which
+underflow tininess is detected, `timesoftfloat' times the function both with
+tininess detected before rounding and after rounding.  For extended double-
+precision operations affected by rounding precision control, `timesoftfloat'
+also times the function for all three rounding precision modes, one after
+the other.  Evaluation of a function can be limited to a single rounding
+mode, a single tininess mode, and/or a single rounding precision with
+appropriate options (see _Options_).
+
+For each function and mode evaluated, `timesoftfloat' reports the speed of
+the function in kops/s, or ``thousands of operations per second''.  This
+unit of measure differs from the traditional MFLOPS (``millions of floating-
+point operations per second'') only in being a factor of 1000 smaller.
+(1000 kops/s is exactly 1 MFLOPS.)  Speeds are reported in thousands instead
+of millions because software floating-point often executes at less than
+1 MFLOPS.
+
+The speeds reported by `timesoftfloat' may be affected somewhat by other
+programs executing at the same time as `timesoftfloat'.
+
+Note that the remainder operations (`float32_rem', `float64_rem',
+`floatx80_rem' and `float128_rem') will be markedly slower than other
+operations, particularly for extended double precision (`floatx80') and
+quadruple precision (`float128').  This is inherent to the remainder
+function itself and is not a failing of the SoftFloat implementation.
+
+
+-------------------------------------------------------------------------------
+Options
+
+The `timesoftfloat' program accepts several command options.  If mutually
+contradictory options are given, the last one has priority.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+-help
+
+The `-help' option causes a summary of program usage to be written, after
+which the program exits.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+-precision32, -precision64, -precision80
+
+For extended double-precision functions affected by rounding precision
+control, the `-precision32' option restricts evaluation to only the cases
+in which rounding precision is equivalent to single precision.  The other
+rounding precision options are not timed.  Likewise, the `-precision64'
+and `-precision80' options fix the rounding precision equivalent to double
+precision or extended double precision, respectively.  These options are
+ignored for functions not affected by rounding precision control.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+-nearesteven, -tozero, -down, -up
+
+The `-nearesteven' option restricts evaluation to only the cases in which
+the rounding mode is nearest/even.  The other rounding mode options are not
+timed.  Likewise, `-tozero' forces rounding to zero; `-down' forces rounding
+down; and `-up' forces rounding up.  These options are ignored for functions
+that are exact and thus do not round.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+-tininessbefore, -tininessafter
+
+The `-tininessbefore' option restricts evaluation to only the cases
+detecting underflow tininess before rounding.  Tininess after rounding
+is not timed.  Likewise, `-tininessafter' forces underflow tininess to be
+detected after rounding only.  These options are ignored for functions not
+affected by the way in which underflow tininess is detected.
+
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+
+-------------------------------------------------------------------------------
+Function Sets
+
+Just as `timesoftfloat' can test an operation for all four rounding modes in
+sequence, multiple operations can also be tested with a single invocation.
+Three sets are recognized:  `-all1', `-all2', and `-all'.  The set `-all1'
+comprises all one-operand functions; `-all2' is all two-operand functions;
+and `-all' is all functions.  A function set can be used in place of a
+function name in the command line, as in
+
+    timesoftfloat [<option>...] -all
+
+
diff --git a/lib/nbsd_libc/softfloat/unorddf2.c b/lib/nbsd_libc/softfloat/unorddf2.c
new file mode 100644 (file)
index 0000000..d4ac29c
--- /dev/null
@@ -0,0 +1,28 @@
+/* $NetBSD: unorddf2.c,v 1.1 2003/05/06 08:58:19 rearnsha Exp $ */
+
+/*
+ * Written by Richard Earnshaw, 2003.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: unorddf2.c,v 1.1 2003/05/06 08:58:19 rearnsha Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+flag __unorddf2(float64, float64);
+
+flag
+__unorddf2(float64 a, float64 b)
+{
+       /*
+        * The comparison is unordered if either input is a NaN.
+        * Test for this by comparing each operand with itself.
+        * We must perform both comparisons to correctly check for
+        * signalling NaNs.
+        */
+       return 1 ^ (float64_eq(a, a) & float64_eq(b, b));
+}
diff --git a/lib/nbsd_libc/softfloat/unordsf2.c b/lib/nbsd_libc/softfloat/unordsf2.c
new file mode 100644 (file)
index 0000000..03a1969
--- /dev/null
@@ -0,0 +1,28 @@
+/* $NetBSD: unordsf2.c,v 1.1 2003/05/06 08:58:20 rearnsha Exp $ */
+
+/*
+ * Written by Richard Earnshaw, 2003.  This file is in the Public Domain.
+ */
+
+#include "softfloat-for-gcc.h"
+#include "milieu.h"
+#include "softfloat.h"
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: unordsf2.c,v 1.1 2003/05/06 08:58:20 rearnsha Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+flag __unordsf2(float32, float32);
+
+flag
+__unordsf2(float32 a, float32 b)
+{
+       /*
+        * The comparison is unordered if either input is a NaN.
+        * Test for this by comparing each operand with itself.
+        * We must perform both comparisons to correctly check for
+        * signalling NaNs.
+        */
+       return 1 ^ (float32_eq(a, a) & float32_eq(b, b));
+}
diff --git a/lib/nbsd_libc/ssp/Makefile.inc b/lib/nbsd_libc/ssp/Makefile.inc
new file mode 100644 (file)
index 0000000..63895f1
--- /dev/null
@@ -0,0 +1,14 @@
+#      $NetBSD: Makefile.inc,v 1.2 2007/05/30 21:14:35 tls Exp $
+
+.PATH: ${.CURDIR}/ssp
+
+SSP_SRCS=      gets_chk.c fgets_chk.c memcpy_chk.c memmove_chk.c memset_chk.c \
+               snprintf_chk.c sprintf_chk.c strcat_chk.c strcpy_chk.c \
+               strncat_chk.c strncpy_chk.c vsnprintf_chk.c vsprintf_chk.c
+
+.for i in ${SSP_SRCS}
+SRCS+=${i}
+WARNS.${i}=4
+.endfor
+
+MAN+=  ssp.3 __builtin_object_size.3
diff --git a/lib/nbsd_libc/ssp/__builtin_object_size.3 b/lib/nbsd_libc/ssp/__builtin_object_size.3
new file mode 100644 (file)
index 0000000..9590d4f
--- /dev/null
@@ -0,0 +1,90 @@
+.\"    $NetBSD: __builtin_object_size.3,v 1.8 2010/12/19 09:33:52 jruoho Exp $
+.\"
+.\" Copyright (c) 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Christos Zoulas.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.\"
+.Dd December 19, 2010
+.Dt __BUILTIN_OBJECT_SIZE 3
+.Os
+.Sh NAME
+.Nm __builtin_object_size
+.Nd return the size of the given object
+.Sh SYNOPSIS
+.Ft size_t
+.Fn __builtin_object_size "void *ptr" "int type"
+.Sh DESCRIPTION
+The
+.Fn __builtin_object_size
+function is a
+.Xr gcc 1
+built-in function that returns the size of the
+.Fa ptr
+object if known at compile time and the object does not have any side
+effects.
+.Sh RETURN VALUES
+If the size of the object is not known or it has side effects the
+.Fn __builtin_object_size
+function returns:
+.Bl -tag -width (size_t)-1 -offset indent
+.It Dv (size_t)-1
+for
+.Fa type
+.Dv 0
+and
+.Dv 1 .
+.It Dv (size_t)0
+for
+.Fa type
+.Dv 2
+and
+.Dv 3 .
+.El
+.Pp
+If the size of the object is known, then the
+.Fn __builtin_object_size
+function returns the maximum size of all the objects that the compiler
+knows that they can be pointed to by
+.Fa ptr
+when
+.Fa type
+.Dv \*[Am] 2 == 0 ,
+and the minimum size when
+.Fa type
+.Dv \*[Am] 2 != 0 .
+.Sh SEE ALSO
+.Xr gcc 1 ,
+.Xr __builtin_return_address 3 ,
+.Xr attribute 3 ,
+.Xr ssp 3
+.Sh HISTORY
+The
+.Fn __builtin_object_size
+appeared in
+.Tn GCC 4.1 .
+.Sh CAVEATS
+This is a non-standard, compiler-specific extension.
diff --git a/lib/nbsd_libc/ssp/fgets_chk.c b/lib/nbsd_libc/ssp/fgets_chk.c
new file mode 100644 (file)
index 0000000..377579f
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: fgets_chk.c,v 1.6 2009/02/05 05:41:51 lukem Exp $      */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: fgets_chk.c,v 1.6 2009/02/05 05:41:51 lukem Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <stdio.h>
+#include <string.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <ssp/stdio.h>
+
+#undef fgets
+
+char *
+__fgets_chk(char * __restrict buf, int len, size_t slen, FILE *fp)
+{
+       if (slen >= (size_t)INT_MAX)
+               return fgets(buf, len, fp);
+
+       if (len >= 0 && (size_t)len > slen)
+               __chk_fail();
+
+       return fgets(buf, len, fp);
+}
diff --git a/lib/nbsd_libc/ssp/gets_chk.c b/lib/nbsd_libc/ssp/gets_chk.c
new file mode 100644 (file)
index 0000000..1825f20
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: gets_chk.c,v 1.6 2010/01/17 23:13:32 wiz Exp $ */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: gets_chk.c,v 1.6 2010/01/17 23:13:32 wiz Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <stdio.h>
+#include <string.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <ssp/stdio.h>
+
+#undef gets
+
+char *
+__gets_chk(char * __restrict buf, size_t slen)
+{
+       char *abuf;
+       size_t len;
+
+       if (slen >= (size_t)INT_MAX)
+               return gets(buf);
+
+       if ((abuf = malloc(slen + 1)) == NULL)
+               return gets(buf);
+
+       if (fgets(abuf, (int)(slen + 1), stdin) == NULL) {
+               free(abuf);
+               return NULL;
+       }
+
+       len = strlen(abuf);
+       if (len > 0 && abuf[len - 1] == '\n')
+               --len;
+
+       if (len >= slen)
+               __chk_fail();
+
+       (void)memcpy(buf, abuf, len);
+
+       buf[len] = '\0';
+       free(abuf);
+       return buf;
+}
diff --git a/lib/nbsd_libc/ssp/memcpy_chk.c b/lib/nbsd_libc/ssp/memcpy_chk.c
new file mode 100644 (file)
index 0000000..7c7a888
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: memcpy_chk.c,v 1.4 2008/04/28 20:23:00 martin Exp $    */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: memcpy_chk.c,v 1.4 2008/04/28 20:23:00 martin Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <string.h>
+
+#undef memcpy
+
+void *
+__memcpy_chk(void * __restrict dst, const void * __restrict src, size_t len,
+    size_t slen)
+{
+       if (len > slen)
+               __chk_fail();
+       return memcpy(dst, src, len);
+}
diff --git a/lib/nbsd_libc/ssp/memmove_chk.c b/lib/nbsd_libc/ssp/memmove_chk.c
new file mode 100644 (file)
index 0000000..0292057
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: memmove_chk.c,v 1.4 2008/04/28 20:23:00 martin Exp $   */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: memmove_chk.c,v 1.4 2008/04/28 20:23:00 martin Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <string.h>
+
+#undef memmove
+
+void *
+__memmove_chk(void *dst, void *src, size_t len,
+    size_t slen)
+{
+       if (len > slen)
+               __chk_fail();
+       return memmove(dst, src, len);
+}
diff --git a/lib/nbsd_libc/ssp/memset_chk.c b/lib/nbsd_libc/ssp/memset_chk.c
new file mode 100644 (file)
index 0000000..6911e77
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: memset_chk.c,v 1.4 2008/04/28 20:23:00 martin Exp $    */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: memset_chk.c,v 1.4 2008/04/28 20:23:00 martin Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <string.h>
+
+#undef memset
+
+void *
+__memset_chk(void * __restrict dst, int val, size_t len, size_t slen)
+{
+       if (len > slen)
+               __chk_fail();
+       return memset(dst, val, len);
+}
diff --git a/lib/nbsd_libc/ssp/snprintf_chk.c b/lib/nbsd_libc/ssp/snprintf_chk.c
new file mode 100644 (file)
index 0000000..cede5a4
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: snprintf_chk.c,v 1.5 2008/04/28 20:23:00 martin Exp $  */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: snprintf_chk.c,v 1.5 2008/04/28 20:23:00 martin Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <ssp/stdio.h>
+
+#undef vsnprintf
+
+/*ARGSUSED*/
+int
+__snprintf_chk(char * __restrict buf, size_t len, int flags, size_t slen,
+    const char * __restrict fmt, ...)
+{
+       va_list ap;
+       int rv;
+
+       if (len > slen)
+               __chk_fail();
+
+       va_start(ap, fmt);
+       rv = vsnprintf(buf, len, fmt, ap);
+       va_end(ap);
+
+       return rv;
+}
diff --git a/lib/nbsd_libc/ssp/sprintf_chk.c b/lib/nbsd_libc/ssp/sprintf_chk.c
new file mode 100644 (file)
index 0000000..1e92479
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: sprintf_chk.c,v 1.6 2009/02/05 05:40:36 lukem Exp $    */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: sprintf_chk.c,v 1.6 2009/02/05 05:40:36 lukem Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <stdio.h>
+#include <limits.h>
+#include <stdarg.h>
+#include <ssp/stdio.h>
+
+#undef vsnprintf
+#undef vsprintf
+
+int
+/*ARGSUSED*/
+__sprintf_chk(char * __restrict buf, int flags, size_t slen,
+    const char * __restrict fmt, ...)
+{
+       va_list ap;
+       int rv;
+
+       va_start(ap, fmt);
+       if (slen > (size_t)INT_MAX)
+               rv = vsprintf(buf, fmt, ap);
+       else {
+               if ((rv = vsnprintf(buf, slen, fmt, ap)) >= 0 && (size_t)rv >= slen)
+                       __chk_fail();
+       }
+       va_end(ap);
+
+       return rv;
+}
diff --git a/lib/nbsd_libc/ssp/ssp.3 b/lib/nbsd_libc/ssp/ssp.3
new file mode 100644 (file)
index 0000000..35ca1bd
--- /dev/null
@@ -0,0 +1,121 @@
+.\"    $NetBSD: ssp.3,v 1.5 2010/12/19 08:28:40 jruoho Exp $
+.\"
+.\" Copyright (c) 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Christos Zoulas.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.\"
+.Dd December 19, 2010
+.Dt SSP 3
+.Os
+.Sh NAME
+.Nm ssp
+.Nd bounds checked libc functions
+.Sh LIBRARY
+.Lb libssp
+.Sh SYNOPSIS
+.In ssp/stdio.h
+.Ft int
+.Fn sprintf "char *str" "const char *fmt" "..."
+.Ft int
+.Fn vsprintf "char *str" "const char *fmt" "va_list ap"
+.Ft int
+.Fn snprintf "char *str" "size_t len" "const char *fmt" "..."
+.Ft int
+.Fn vsnprintf "char *str" "size_t len" "const char *fmt" "va_list ap"
+.Ft char *
+.Fn gets "char *str"
+.Ft char *
+.Fn fgets "char *str" "int len" "FILE *fp"
+.In ssp/string.h
+.Ft void *
+.Fn memcpy "void *str" "const void *ptr" "size_t len"
+.Ft void *
+.Fn memmove "void *str" "const void *ptr" "size_t len"
+.Ft void *
+.Fn memset "void *str" "int val" "size_t len"
+.Ft char *
+.Fn strcpy "char *str" "const char *ptr" "size_t len"
+.Ft char *
+.Fn strcat "char *str" "const char *ptr" "size_t len"
+.Ft char *
+.Fn strncpy "char *str" "const char *ptr" "size_t len"
+.Ft char *
+.Fn strncat "char *str" "const char *ptr" "size_t len"
+.In ssp/strings.h
+.Ft void *
+.Fn bcopy "const void *ptr" "void *str" "size_t len"
+.Ft void *
+.Fn bzero "void *str" "size_t len"
+.In ssp/unistd.h
+.Ft ssize_t
+.Fn read "int fd" "void *str" "size_t len"
+.Ft int
+.Fn readlink "const char * restrict path" "char * restrict str" "size_t len"
+.Ft int
+.Fn getcwd "char *str" "size_t len"
+.Sh DESCRIPTION
+When
+.Dv _FORTIFY_SOURCE
+bounds checking is enabled as described below, the above functions get
+overwritten to use the
+.Xr __builtin_object_size 3
+function to compute the size of
+.Fa str ,
+if known at compile time,
+and perform bounds check on it in order
+to avoid data buffer or stack buffer overflows.
+If an overflow is detected, the routines will call
+.Xr abort 3 .
+.Pp
+To enable these function overrides the following should be added to the
+.Xr gcc 1
+command line:
+.Dq \-I/usr/include/ssp
+to override the standard include files and
+.Dq \-D_FORTIFY_SOURCE=1
+or
+.Dq \-D_FORTIFY_SOURCE=2 .
+.Pp
+If
+.Dv _FORTIFY_SOURCE is set to
+.Dv 1
+the code will compute the maximum possible buffer size for
+.Fa str ,
+and if set to
+.Dv 2
+it will compute the minimum buffer size.
+.Sh SEE ALSO
+.Xr gcc 1 ,
+.Xr __builtin_object_size 3 ,
+.Xr stdio 3 ,
+.Xr string 3 ,
+.Xr security 8
+.Sh HISTORY
+The
+.Nm ssp
+library appeared
+.Nx 4.0 .
diff --git a/lib/nbsd_libc/ssp/strcat_chk.c b/lib/nbsd_libc/ssp/strcat_chk.c
new file mode 100644 (file)
index 0000000..212cdd9
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: strcat_chk.c,v 1.4 2009/11/17 20:44:26 drochner Exp $  */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: strcat_chk.c,v 1.4 2009/11/17 20:44:26 drochner Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <string.h>
+
+char *
+__strcat_chk(char * __restrict dst, const char * __restrict src, size_t slen)
+{
+       char *d;
+
+       for (d = dst; *d; d++) {
+               if (slen-- == 0)
+                       __chk_fail();
+       }
+
+       while (*src) {
+               if (slen-- == 0)
+                       __chk_fail();
+               *d++ = *src++;
+       }
+
+       if (slen-- == 0)
+               __chk_fail();
+
+       *d = '\0';
+       return dst;
+}
diff --git a/lib/nbsd_libc/ssp/strcpy_chk.c b/lib/nbsd_libc/ssp/strcpy_chk.c
new file mode 100644 (file)
index 0000000..74f9af3
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: strcpy_chk.c,v 1.5 2010/12/28 16:19:25 christos Exp $  */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: strcpy_chk.c,v 1.5 2010/12/28 16:19:25 christos Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <string.h>
+
+#undef memcpy
+
+char *
+__strcpy_chk(char * __restrict dst, const char * __restrict src, size_t slen)
+{
+       size_t len = strlen(src);
+
+       if (len >= slen)
+               __chk_fail();
+
+       return memcpy(dst, src, len + 1);
+}
diff --git a/lib/nbsd_libc/ssp/strncat_chk.c b/lib/nbsd_libc/ssp/strncat_chk.c
new file mode 100644 (file)
index 0000000..ae66792
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: strncat_chk.c,v 1.4 2009/11/17 20:44:26 drochner Exp $ */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: strncat_chk.c,v 1.4 2009/11/17 20:44:26 drochner Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <string.h>
+#include <stdio.h>
+
+char *
+__strncat_chk(char * __restrict dst, const char * __restrict src, size_t len,
+    size_t slen)
+{
+       char *d;
+
+       if (len == 0)
+               return dst;
+
+       if (len > slen)
+               __chk_fail();
+
+       for (d = dst; *d; d++) {
+               if (slen-- == 0)
+                       __chk_fail();
+       }
+
+       do {
+               if ((*d = *src++) == '\0')
+                       break;
+               if (slen-- == 0)
+                       __chk_fail();
+               d++;
+       } while (--len != 0);
+
+       if (slen-- == 0)
+               __chk_fail();
+
+       *d = '\0';
+       return dst;
+}
diff --git a/lib/nbsd_libc/ssp/strncpy_chk.c b/lib/nbsd_libc/ssp/strncpy_chk.c
new file mode 100644 (file)
index 0000000..2fe5211
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: strncpy_chk.c,v 1.4 2008/04/28 20:23:00 martin Exp $   */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: strncpy_chk.c,v 1.4 2008/04/28 20:23:00 martin Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <string.h>
+
+#undef strncpy
+
+char *
+__strncpy_chk(char * __restrict dst, const char * __restrict src, size_t len,
+    size_t slen)
+{
+       if (len > slen)
+               __chk_fail();
+
+       return strncpy(dst, src, len);
+}
diff --git a/lib/nbsd_libc/ssp/vsnprintf_chk.c b/lib/nbsd_libc/ssp/vsnprintf_chk.c
new file mode 100644 (file)
index 0000000..2b88029
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: vsnprintf_chk.c,v 1.5 2008/04/28 20:23:00 martin Exp $ */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: vsnprintf_chk.c,v 1.5 2008/04/28 20:23:00 martin Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <ssp/stdio.h>
+
+#undef vsnprintf
+
+int
+__vsnprintf_chk(char * __restrict buf, size_t len, int flags, size_t slen,
+    const char * __restrict fmt, va_list ap)
+{
+       if (len > slen)
+               __chk_fail();
+
+       return vsnprintf(buf, len, fmt, ap);
+}
diff --git a/lib/nbsd_libc/ssp/vsprintf_chk.c b/lib/nbsd_libc/ssp/vsprintf_chk.c
new file mode 100644 (file)
index 0000000..fec8a18
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: vsprintf_chk.c,v 1.6 2009/02/05 05:39:38 lukem Exp $   */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+__RCSID("$NetBSD: vsprintf_chk.c,v 1.6 2009/02/05 05:39:38 lukem Exp $");
+
+/*LINTLIBRARY*/
+
+#include <ssp/ssp.h>
+#include <stdio.h>
+#include <limits.h>
+#include <stdarg.h>
+#include <ssp/stdio.h>
+
+#undef vsprintf
+#undef vsnprintf
+
+/*ARGSUSED*/
+int
+__vsprintf_chk(char * __restrict buf, int flags, size_t slen,
+    const char * __restrict fmt, va_list ap)
+{
+       int rv;
+
+       if (slen > (size_t)INT_MAX)
+               rv = vsprintf(buf, fmt, ap);
+       else {
+               if ((rv = vsnprintf(buf, slen, fmt, ap)) >= 0 && (size_t)rv >= slen)
+                       __chk_fail();
+       }
+
+       return rv;
+}
diff --git a/lib/nbsd_libc/stdio/Makefile.inc b/lib/nbsd_libc/stdio/Makefile.inc
new file mode 100644 (file)
index 0000000..2314360
--- /dev/null
@@ -0,0 +1,67 @@
+#      from: @(#)Makefile.inc  5.7 (Berkeley) 6/27/91
+#      $NetBSD: Makefile.inc,v 1.40 2010/12/22 16:59:10 christos Exp $
+
+# stdio sources
+.PATH: ${.CURDIR}/stdio
+
+CPPFLAGS+=-DWIDE_DOUBLE
+
+SRCS+= asprintf.c clrerr.c dprintf.c fclose.c fdopen.c feof.c ferror.c \
+       fflush.c fgetc.c fgetln.c fgetpos.c fgets.c fgetstr.c fgetwc.c \
+       fgetwln.c fgetws.c fileno.c findfp.c flags.c flockfile.c fopen.c \
+       fparseln.c fprintf.c fpurge.c fputc.c fputs.c fputwc.c fputws.c \
+       fread.c freopen.c fscanf.c fseek.c fseeko.c fsetpos.c ftell.c ftello.c \
+       funopen.c fvwrite.c fwalk.c fwide.c fwprintf.c fwrite.c fwscanf.c \
+       getc.c getchar.c getdelim.c getline.c gettemp.c getw.c getwc.c \
+       getwchar.c makebuf.c mkdtemp.c mkstemp.c perror.c printf.c putc.c \
+       putchar.c puts.c putw.c putwc.c putwchar.c refill.c remove.c rewind.c \
+       rget.c scanf.c setbuf.c setbuffer.c setvbuf.c snprintf.c snprintf_ss.c \
+       sscanf.c stdio.c swprintf.c swscanf.c tmpfile.c ungetc.c ungetwc.c \
+       vasprintf.c vdprintf.c vfprintf.c vfscanf.c vfwprintf.c vfwscanf.c \
+       vprintf.c vscanf.c vsnprintf.c vsnprintf_ss.c vsscanf.c vswprintf.c \
+       vswscanf.c vwprintf.c vwscanf.c wbuf.c wprintf.c wscanf.c wsetup.c
+SRCS+= fmemopen.c
+
+.if !defined(AUDIT)
+SRCS+= gets.c sprintf.c vsprintf.c tempnam.c tmpnam.c mktemp.c
+.endif
+
+# namespace purity wrappers
+SRCS+= _fileno.c _fseeko.c _ftello.c
+
+MAN+=  fclose.3 ferror.3 fflush.3 fgetln.3 fgets.3 fgetwln.3 fgetws.3 \
+       flockfile.3 fmemopen.3 fopen.3 fparseln.3 fputs.3 fputws.3 fread.3 \
+       fseek.3 funopen.3 fwide.3 getc.3 getdelim.3 getwc.3 mktemp.3 printf.3 \
+       putc.3 putwc.3 remove.3 scanf.3 setbuf.3 stdio.3 tmpnam.3 \
+       ungetc.3 ungetwc.3 wprintf.3 wscanf.3
+
+MLINKS+=ferror.3 clearerr.3 ferror.3 feof.3 ferror.3 fileno.3
+MLINKS+=fflush.3 fpurge.3
+MLINKS+=flockfile.3 ftrylockfile.3 flockfile.3 funlockfile.3
+MLINKS+=fgets.3 gets.3
+MLINKS+=fopen.3 fdopen.3 fopen.3 freopen.3
+MLINKS+=fputs.3 puts.3
+MLINKS+=fread.3 fwrite.3
+MLINKS+=fseek.3 fgetpos.3 fseek.3 fseeko.3 fseek.3 fsetpos.3 fseek.3 ftell.3 \
+       fseek.3 ftello.3 fseek.3 rewind.3
+MLINKS+=funopen.3 fropen.3 funopen.3 fwopen.3
+MLINKS+=getc.3 fgetc.3 getc.3 getc_unlocked.3 getc.3 getchar.3 \
+       getc.3 getchar_unlocked.3 getc.3 getw.3
+MLINKS+=getdelim.3 getline.3
+MLINKS+=mktemp.3 mkdtemp.3 mktemp.3 mkstemp.3
+MLINKS+=printf.3 asprintf.3 printf.3 fprintf.3 printf.3 snprintf.3 \
+       printf.3 sprintf.3 printf.3 vasprintf.3 printf.3 vfprintf.3 \
+       printf.3 vprintf.3 printf.3 vsnprintf.3 printf.3 vsprintf.3 \
+       printf.3 dprintf.3 printf.3 vdprintf.3 printf.3 vsnprintf_ss.3
+MLINKS+=putc.3 fputc.3 putc.3 putc_unlocked.3 putc.3 putchar.3 \
+       putc.3 putchar_unlocked.3 putc.3 putw.3
+MLINKS+=scanf.3 fscanf.3 scanf.3 sscanf.3 scanf.3 vfscanf.3 scanf.3 vscanf.3 \
+       scanf.3 vsscanf.3
+MLINKS+=setbuf.3 setbuffer.3 setbuf.3 setlinebuf.3 setbuf.3 setvbuf.3
+MLINKS+=tmpnam.3 tempnam.3 tmpnam.3 tmpfile.3
+MLINKS+=putwc.3 fputwc.3 putwc.3 putwchar.3
+MLINKS+=getwc.3 fgetwc.3 getwc.3 getwchar.3
+MLINKS+=wprintf.3 fwprintf.3 wprintf.3 swprintf.3
+MLINKS+=wprintf.3 vwprintf.3 wprintf.3 vfwprintf.3 wprintf.3 vswprintf.3
+MLINKS+=wscanf.3 fwscanf.3 wscanf.3 swscanf.3 wscanf.3 vwscanf.3
+MLINKS+=wscanf.3 vswscanf.3 wscanf.3 vfwscanf.3
diff --git a/lib/nbsd_libc/stdio/_fileno.c b/lib/nbsd_libc/stdio/_fileno.c
new file mode 100644 (file)
index 0000000..4975ecf
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: _fileno.c,v 1.5 2009/10/21 01:07:45 snj Exp $  */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _fileno.c,v 1.5 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_fileno, fileno)
+#else
+
+#include <stdio.h>
+#undef fileno
+int    _fileno (FILE *);
+
+int
+fileno(FILE *stream)
+{
+
+       return _fileno(stream);
+}
+#endif
diff --git a/lib/nbsd_libc/stdio/_fseeko.c b/lib/nbsd_libc/stdio/_fseeko.c
new file mode 100644 (file)
index 0000000..c34f17e
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: _fseeko.c,v 1.5 2009/10/21 01:07:45 snj Exp $  */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _fseeko.c,v 1.5 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_fseeko, fseeko)
+#else
+
+#include <stdio.h>
+int    _fseeko(FILE *, off_t, int);
+
+int
+fseeko(FILE *stream, off_t offset, int whence)
+{
+
+       return _fseeko(stream, offset, whence);
+}
+#endif
diff --git a/lib/nbsd_libc/stdio/_ftello.c b/lib/nbsd_libc/stdio/_ftello.c
new file mode 100644 (file)
index 0000000..0004cce
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: _ftello.c,v 1.5 2009/10/21 01:07:45 snj Exp $  */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _ftello.c,v 1.5 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_ftello, ftello)
+#else
+
+#include <stdio.h>
+off_t  _ftello(FILE *);
+
+off_t
+ftello(FILE *stream)
+{
+
+       return _ftello(stream);
+}
+#endif
diff --git a/lib/nbsd_libc/stdio/asprintf.c b/lib/nbsd_libc/stdio/asprintf.c
new file mode 100644 (file)
index 0000000..f537637
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: asprintf.c,v 1.18 2009/10/25 20:44:13 christos Exp $   */
+
+/*
+ * Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
+ * 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.
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: asprintf.c,v 1.18 2009/10/25 20:44:13 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(asprintf, _asprintf)
+#endif
+
+int
+asprintf(char **str, char const *fmt, ...)
+{
+       int ret;
+       va_list ap;
+       FILE f;
+       struct __sfileext fext;
+       unsigned char *_base;
+
+       _DIAGASSERT(str != NULL);
+
+       _FILEEXT_SETUP(&f, &fext);
+       f._file = -1;
+       f._flags = __SWR | __SSTR | __SALC;
+       f._bf._base = f._p = malloc((size_t)128);
+       if (f._bf._base == NULL)
+               goto err;
+       f._bf._size = f._w = 127;               /* Leave room for the NUL */
+       va_start(ap, fmt);
+       ret = __vfprintf_unlocked(&f, fmt, ap);
+       va_end(ap);
+       if (ret < 0)
+               goto err;
+       *f._p = '\0';
+       _base = realloc(f._bf._base, (size_t)ret + 1);
+       if (_base == NULL)
+               goto err;
+       *str = (char *)_base;
+       return (ret);
+
+err:
+       if (f._bf._base)
+               free(f._bf._base);
+       *str = NULL;
+       errno = ENOMEM;
+       return (-1);
+}
diff --git a/lib/nbsd_libc/stdio/clrerr.c b/lib/nbsd_libc/stdio/clrerr.c
new file mode 100644 (file)
index 0000000..d5cfef0
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: clrerr.c,v 1.10 2003/08/07 16:43:21 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)clrerr.c   8.1 (Berkeley) 6/4/93";
+#endif
+__RCSID("$NetBSD: clrerr.c,v 1.10 2003/08/07 16:43:21 agc Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+#undef clearerr
+
+void
+clearerr(fp)
+       FILE *fp;
+{
+       _DIAGASSERT(fp != NULL);
+
+       FLOCKFILE(fp);
+       __sclearerr(fp);
+       FUNLOCKFILE(fp);
+}
diff --git a/lib/nbsd_libc/stdio/dprintf.c b/lib/nbsd_libc/stdio/dprintf.c
new file mode 100644 (file)
index 0000000..724068a
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: dprintf.c,v 1.1 2010/09/06 14:52:55 christos Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: dprintf.c,v 1.1 2010/09/06 14:52:55 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <stdio.h>
+#include <stdarg.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+int
+dprintf(int fd, const char * __restrict fmt, ...)
+{
+       va_list ap;
+       int ret;
+
+       va_start(ap, fmt);
+       ret = vdprintf(fd, fmt, ap);
+       va_end(ap);
+       return ret;
+}
diff --git a/lib/nbsd_libc/stdio/fclose.3 b/lib/nbsd_libc/stdio/fclose.3
new file mode 100644 (file)
index 0000000..a6c8898
--- /dev/null
@@ -0,0 +1,93 @@
+.\"    $NetBSD: fclose.3,v 1.9 2003/08/07 16:43:21 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)fclose.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt FCLOSE 3
+.Os
+.Sh NAME
+.Nm fclose
+.Nd close a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft int
+.Fn fclose "FILE *stream"
+.Sh DESCRIPTION
+The
+.Fn fclose
+function
+dissociates the named
+.Fa stream
+from its underlying file or set of functions.
+If the stream was being used for output, any buffered data is written
+first, using
+.Xr fflush 3 .
+.Sh RETURN VALUES
+Upon successful completion 0 is returned.
+Otherwise,
+.Dv EOF
+is returned and the global variable
+.Va errno
+is set to indicate the error.
+In either case no further access to the stream is possible.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EBADF
+The argument
+.Fa stream
+is not an open stream.
+.El
+.Pp
+The
+.Fn fclose
+function
+may also fail and set
+.Va errno
+for any of the errors specified for the routines
+.Xr close 2
+or
+.Xr fflush 3 .
+.Sh SEE ALSO
+.Xr close 2 ,
+.Xr fflush 3 ,
+.Xr fopen 3 ,
+.Xr setbuf 3
+.Sh STANDARDS
+The
+.Fn fclose
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdio/fclose.c b/lib/nbsd_libc/stdio/fclose.c
new file mode 100644 (file)
index 0000000..c1e0d24
--- /dev/null
@@ -0,0 +1,78 @@
+/*     $NetBSD: fclose.c,v 1.17 2010/01/11 20:39:29 joerg Exp $        */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fclose.c   8.1 (Berkeley) 6/4/93";
+#endif
+__RCSID("$NetBSD: fclose.c,v 1.17 2010/01/11 20:39:29 joerg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include "reentrant.h"
+#include "local.h"
+
+int
+fclose(fp)
+       FILE *fp;
+{
+       int r;
+
+       _DIAGASSERT(fp != NULL);
+
+       if (fp->_flags == 0) {  /* not open! */
+               errno = EBADF;
+               return (EOF);
+       }
+       FLOCKFILE(fp);
+       WCIO_FREE(fp);
+       r = fp->_flags & __SWR ? __sflush(fp) : 0;
+       if (fp->_close != NULL && (*fp->_close)(fp->_cookie) < 0)
+               r = EOF;
+       if (fp->_flags & __SMBF)
+               free((char *)fp->_bf._base);
+       if (HASUB(fp))
+               FREEUB(fp);
+       FREELB(fp);
+       FUNLOCKFILE(fp);
+       fp->_file = -1;
+       fp->_flags = 0;         /* Release this FILE for reuse. */
+       fp->_r = fp->_w = 0;    /* Mess up if reaccessed. */
+       return (r);
+}
diff --git a/lib/nbsd_libc/stdio/fdopen.c b/lib/nbsd_libc/stdio/fdopen.c
new file mode 100644 (file)
index 0000000..d579b20
--- /dev/null
@@ -0,0 +1,123 @@
+/*     $NetBSD: fdopen.c,v 1.15 2008/03/13 15:40:00 christos Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fdopen.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fdopen.c,v 1.15 2008/03/13 15:40:00 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <limits.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(fdopen,_fdopen)
+#endif
+
+FILE *
+fdopen(fd, mode)
+       int fd;
+       const char *mode;
+{
+       FILE *fp;
+       int flags, oflags, fdflags, tmp;
+
+       _DIAGASSERT(fd != -1);
+
+       /*
+        * File descriptors are a full int, but _file is only a short.
+        * If we get a valid file descriptor that is greater or equal to
+        * USHRT_MAX, then the fd will get sign-extended into an
+        * invalid file descriptor.  Handle this case by failing the
+        * open. (We treat the short as unsigned, and special-case -1).
+        */
+       if (fd >= USHRT_MAX) {
+               errno = EMFILE;
+               return NULL;
+       }
+
+       if ((flags = __sflags(mode, &oflags)) == 0)
+               return (NULL);
+
+       /* Make sure the mode the user wants is a subset of the actual mode. */
+       if ((fdflags = fcntl(fd, F_GETFL, 0)) < 0)
+               return (NULL);
+       tmp = fdflags & O_ACCMODE;
+       if (tmp != O_RDWR && (tmp != (oflags & O_ACCMODE))) {
+               errno = EINVAL;
+               return (NULL);
+       }
+
+       if (oflags & O_NONBLOCK) {
+               struct stat st;
+               if (fstat(fd, &st) == -1) {
+                       return (NULL);
+               }
+               if (!S_ISREG(st.st_mode)) {
+                       errno = EFTYPE;
+                       return (NULL);
+               }
+       }
+
+       if ((fp = __sfp()) == NULL)
+               return (NULL);
+       fp->_flags = flags;
+       /*
+        * If opened for appending, but underlying descriptor does not have
+        * O_APPEND bit set, assert __SAPP so that __swrite() will lseek to
+        * end before each write.
+        */
+       if ((oflags & O_APPEND) && !(fdflags & O_APPEND))
+               fp->_flags |= __SAPP;
+       fp->_file = fd;
+       fp->_cookie = fp;
+       fp->_read = __sread;
+       fp->_write = __swrite;
+       fp->_seek = __sseek;
+       fp->_close = __sclose;
+       return (fp);
+}
diff --git a/lib/nbsd_libc/stdio/feof.c b/lib/nbsd_libc/stdio/feof.c
new file mode 100644 (file)
index 0000000..904b9b4
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: feof.c,v 1.11 2003/08/07 16:43:22 agc Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)feof.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: feof.c,v 1.11 2003/08/07 16:43:22 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * A subroutine version of the macro feof.
+ */
+#undef feof
+
+int
+feof(fp)
+       FILE *fp;
+{
+       int r;
+
+       _DIAGASSERT(fp != NULL);
+
+       FLOCKFILE(fp);
+       r = __sfeof(fp);
+       FUNLOCKFILE(fp);
+       return r;
+}
diff --git a/lib/nbsd_libc/stdio/ferror.3 b/lib/nbsd_libc/stdio/ferror.3
new file mode 100644 (file)
index 0000000..270a766
--- /dev/null
@@ -0,0 +1,121 @@
+.\"    $NetBSD: ferror.3,v 1.14 2010/05/08 11:35:14 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)ferror.3   8.2 (Berkeley) 4/19/94
+.\"
+.Dd May 6, 2010
+.Dt FERROR 3
+.Os
+.Sh NAME
+.Nm clearerr ,
+.Nm feof ,
+.Nm ferror ,
+.Nm fileno
+.Nd check and reset stream status
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft void
+.Fn clearerr "FILE *stream"
+.Ft int
+.Fn feof "FILE *stream"
+.Ft int
+.Fn ferror "FILE *stream"
+.Ft int
+.Fn fileno "FILE *stream"
+.Sh DESCRIPTION
+The function
+.Fn clearerr
+clears the end-of-file and error indicators for the stream pointed
+to by
+.Fa stream .
+.Pp
+The function
+.Fn feof
+tests the end-of-file indicator for the stream pointed to by
+.Fa stream ,
+returning non-zero if it is set.
+The end-of-file indicator can only be cleared by the function
+.Fn clearerr .
+.Pp
+The function
+.Fn ferror
+tests the error indicator for the stream pointed to by
+.Fa stream ,
+returning non-zero if it is set.
+The error indicator can only be reset by the
+.Fn clearerr
+function.
+.Pp
+The function
+.Fn fileno
+examines the argument
+.Fa stream
+and returns its integer descriptor.
+.Sh ERRORS
+The functions
+.Fn clearerr ,
+.Fn feof ,
+and
+.Fn ferror
+should neither fail nor set the external variable
+.Va errno .
+However, the function
+.Fn fileno
+may fail and return \-1 in case the argument
+.Fa stream
+is not associated with a valid file descriptor.
+(In this case the
+.Nx
+implementation does not follow the optional
+.Tn POSIX
+recommendation to set the
+.Va errno
+variable to
+.Er EBADF . )
+.Sh SEE ALSO
+.Xr open 2 ,
+.Xr stdio 3
+.Sh STANDARDS
+The functions
+.Fn clearerr ,
+.Fn feof ,
+and
+.Fn ferror
+conform to
+.St -ansiC .
+The function
+.Fn fileno
+conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/stdio/ferror.c b/lib/nbsd_libc/stdio/ferror.c
new file mode 100644 (file)
index 0000000..97b58a7
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: ferror.c,v 1.11 2003/08/07 16:43:22 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ferror.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: ferror.c,v 1.11 2003/08/07 16:43:22 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * A subroutine version of the macro ferror.
+ */
+#undef ferror
+
+int
+ferror(fp)
+       FILE *fp;
+{
+       int r;
+
+       _DIAGASSERT(fp != NULL);
+
+       FLOCKFILE(fp);
+       r = __sferror(fp);
+       FUNLOCKFILE(fp);
+       return r;
+}
diff --git a/lib/nbsd_libc/stdio/fflush.3 b/lib/nbsd_libc/stdio/fflush.3
new file mode 100644 (file)
index 0000000..8f85226
--- /dev/null
@@ -0,0 +1,110 @@
+.\"    $NetBSD: fflush.3,v 1.12 2003/08/07 16:43:22 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)fflush.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt FFLUSH 3
+.Os
+.Sh NAME
+.Nm fflush ,
+.Nm fpurge
+.Nd flush a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft int
+.Fn fflush "FILE *stream"
+.Ft int
+.Fn fpurge "FILE *stream"
+.Sh DESCRIPTION
+The function
+.Fn fflush
+forces a write of all buffered data for the given output or update
+.Fa stream
+via the stream's underlying write function.
+The open status of the stream is unaffected.
+.Pp
+If the
+.Fa stream
+argument is
+.Dv NULL ,
+.Fn fflush
+flushes
+.Em all
+open output streams.
+.Pp
+The function
+.Fn fpurge
+erases any input or output buffered in the given
+.Fa stream .
+For output streams this discards any unwritten output.
+For input streams this discards any input read from the underlying object
+but not yet obtained via
+.Xr getc 3 ;
+this includes any text pushed back via
+.Xr ungetc 3 .
+.Sh RETURN VALUES
+Upon successful completion 0 is returned.
+Otherwise,
+.Dv EOF
+is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa stream
+is not an open stream, or, in the case of
+.Fn fflush ,
+not a stream open for writing.
+.El
+.Pp
+The function
+.Fn fflush
+may also fail and set
+.Va errno
+for any of the errors specified for the routine
+.Xr write 2 .
+.Sh SEE ALSO
+.Xr write 2 ,
+.Xr fclose 3 ,
+.Xr fopen 3 ,
+.Xr setbuf 3
+.Sh STANDARDS
+The
+.Fn fflush
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdio/fflush.c b/lib/nbsd_libc/stdio/fflush.c
new file mode 100644 (file)
index 0000000..a78ad5e
--- /dev/null
@@ -0,0 +1,112 @@
+/*     $NetBSD: fflush.c,v 1.15 2003/08/07 16:43:22 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fflush.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fflush.c,v 1.15 2003/08/07 16:43:22 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef _REENTRANT
+extern rwlock_t __sfp_lock;
+#endif
+
+/* Flush a single file, or (if fp is NULL) all files.  */
+int
+fflush(fp)
+       FILE *fp;
+{
+       int r;
+
+       if (fp == NULL) {
+               rwlock_rdlock(&__sfp_lock);
+               r = _fwalk(__sflush);
+               rwlock_unlock(&__sfp_lock);
+               return r;
+       }
+
+       FLOCKFILE(fp);
+       if ((fp->_flags & (__SWR | __SRW)) == 0) {
+               errno = EBADF;
+               r = EOF;
+       } else {
+               r = __sflush(fp);
+       }
+       FUNLOCKFILE(fp);
+       return r;
+}
+
+int
+__sflush(fp)
+       FILE *fp;
+{
+       unsigned char *p;
+       int n, t;
+
+       _DIAGASSERT(fp != NULL);
+
+       t = fp->_flags;
+       if ((t & __SWR) == 0)
+               return (0);
+
+       if ((p = fp->_bf._base) == NULL)
+               return (0);
+
+       n = fp->_p - p;         /* write this much */
+
+       /*
+        * Set these immediately to avoid problems with longjmp and to allow
+        * exchange buffering (via setvbuf) in user write function.
+        */
+       fp->_p = p;
+       fp->_w = t & (__SLBF|__SNBF) ? 0 : fp->_bf._size;
+
+       for (; n > 0; n -= t, p += t) {
+               t = (*fp->_write)(fp->_cookie, (char *)p, n);
+               if (t <= 0) {
+                       fp->_flags |= __SERR;
+                       return (EOF);
+               }
+       }
+       return (0);
+}
diff --git a/lib/nbsd_libc/stdio/fgetc.c b/lib/nbsd_libc/stdio/fgetc.c
new file mode 100644 (file)
index 0000000..4783cfe
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: fgetc.c,v 1.11 2003/08/07 16:43:22 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fgetc.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fgetc.c,v 1.11 2003/08/07 16:43:22 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+int
+fgetc(fp)
+       FILE *fp;
+{
+       int r;
+
+       _DIAGASSERT(fp != NULL);
+
+       FLOCKFILE(fp);
+       r = __sgetc(fp);
+       FUNLOCKFILE(fp);
+       return r;
+}
diff --git a/lib/nbsd_libc/stdio/fgetln.3 b/lib/nbsd_libc/stdio/fgetln.3
new file mode 100644 (file)
index 0000000..9b4577a
--- /dev/null
@@ -0,0 +1,155 @@
+.\"    $NetBSD: fgetln.3,v 1.14 2004/05/10 17:15:28 drochner Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)fgetln.3   8.3 (Berkeley) 4/19/94
+.\"
+.Dd April 21, 2004
+.Dt FGETLN 3
+.Os
+.Sh NAME
+.Nm fgetln
+.Nd get a line from a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft char *
+.Fn fgetln "FILE * restrict stream" "size_t * restrict len"
+.Sh DESCRIPTION
+The
+.Fn fgetln
+function
+returns a pointer to the next line from the stream referenced by
+.Fa stream .
+This line is
+.Em not
+a C string as it does not end with a terminating
+.Dv NUL
+character.
+The length of the line, including the final newline,
+is stored in the memory location to which
+.Fa len
+points.
+(Note, however, that if the line is the last
+in a file that does not end in a newline,
+the returned text will not contain a newline.)
+.Sh RETURN VALUES
+Upon successful completion a pointer is returned;
+this pointer becomes invalid after the next
+.Tn I/O
+operation on
+.Fa stream
+(whether successful or not)
+or as soon as the stream is closed.
+Otherwise,
+.Dv NULL
+is returned.
+The
+.Fn fgetln
+function
+does not distinguish between end-of-file and error; the routines
+.Xr feof 3
+and
+.Xr ferror 3
+must be used
+to determine which occurred.
+If an error occurs, the global variable
+.Va errno
+is set to indicate the error.
+The end-of-file condition is remembered, even on a terminal, and all
+subsequent attempts to read will return
+.Dv NULL
+until the condition is
+cleared with
+.Xr clearerr 3 .
+.Pp
+The text to which the returned pointer points may be modified,
+provided that no changes are made beyond the returned size.
+These changes are lost as soon as the pointer becomes invalid.
+.Sh ERRORS
+.Bl -tag -width [EBADF]
+.It Bq Er EBADF
+The argument
+.Fa stream
+is not a stream open for reading.
+.El
+.Pp
+The
+.Fn fgetln
+function
+may also fail and set
+.Va errno
+for any of the errors specified for the routines
+.Xr fflush 3 ,
+.Xr malloc 3 ,
+.Xr read 2 ,
+.Xr stat 2 ,
+or
+.Xr realloc 3 .
+.Sh SEE ALSO
+.Xr ferror 3 ,
+.Xr fgets 3 ,
+.Xr fopen 3 ,
+.Xr putc 3
+.Sh HISTORY
+The
+.Fn fgetln
+function first appeared in
+.Bx 4.4 .
+.Sh CAVEATS
+Since the returned buffer is not a C string (it is not null terminated), a
+common practice is to replace the newline character with
+.Sq \e0 .
+However, if the last line in a file does not contain a newline,
+the returned text won't contain a newline either.
+The following code demonstrates how to deal with this problem by allocating a
+temporary buffer:
+.Bd -literal
+       char *buf, *lbuf;
+       size_t len;
+
+       lbuf = NULL;
+       while ((buf = fgetln(fp, &len))) {
+               if (buf[len - 1] == '\en')
+                       buf[len - 1] = '\e0';
+               else {
+                       if ((lbuf = (char *)malloc(len + 1)) == NULL)
+                               err(1, NULL);
+                       memcpy(lbuf, buf, len);
+                       lbuf[len] = '\e0';
+                       buf = lbuf;
+               }
+               printf("%s\en", buf);
+
+               if (lbuf != NULL) {
+                       free(lbuf);
+                       lbuf = NULL;
+               }
+       }
+.Ed
diff --git a/lib/nbsd_libc/stdio/fgetln.c b/lib/nbsd_libc/stdio/fgetln.c
new file mode 100644 (file)
index 0000000..af7c222
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: fgetln.c,v 1.16 2009/12/02 09:03:13 roy Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: fgetln.c,v 1.16 2009/12/02 09:03:13 roy Exp $");
+
+#include "namespace.h"
+
+#include <stdio.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(fgetln,_fgetln)
+#endif
+
+/*
+ * Get an input line.
+ * This now uses getdelim(3) for a code reduction.
+ * The upside is that strings are now always NULL terminated, but relying
+ * on this is non portable - better to use the POSIX getdelim(3) function.
+ */
+char *
+fgetln(FILE *fp, size_t *lenp)
+{
+       char *p;
+       
+       FLOCKFILE(fp);
+       p = __fgetstr(fp, lenp, '\n');
+       FUNLOCKFILE(fp);
+       return p;
+}
diff --git a/lib/nbsd_libc/stdio/fgetpos.c b/lib/nbsd_libc/stdio/fgetpos.c
new file mode 100644 (file)
index 0000000..e0c97e9
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: fgetpos.c,v 1.11 2003/08/07 16:43:23 agc Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fgetpos.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fgetpos.c,v 1.11 2003/08/07 16:43:23 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+
+int
+fgetpos(fp, pos)
+       FILE *fp;
+       fpos_t *pos;
+{
+       _DIAGASSERT(fp != NULL);
+       _DIAGASSERT(pos != NULL);
+
+       return((*pos = (off_t)ftello(fp)) == (off_t)-1);
+}
diff --git a/lib/nbsd_libc/stdio/fgets.3 b/lib/nbsd_libc/stdio/fgets.3
new file mode 100644 (file)
index 0000000..2c52152
--- /dev/null
@@ -0,0 +1,201 @@
+.\"    $NetBSD: fgets.3,v 1.22 2010/05/13 18:38:24 jruoho Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)fgets.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 13, 2010
+.Dt FGETS 3
+.Os
+.Sh NAME
+.Nm fgets ,
+.Nm gets
+.Nd get a line from a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft char *
+.Fn fgets "char * restrict str" "int size" "FILE * restrict stream"
+.Ft char *
+.Fn gets "char *str"
+.Sh DESCRIPTION
+The
+.Fn fgets
+function
+reads at most one less than the number of characters specified by
+.Fa size
+from the given
+.Fa stream
+and stores them in the string
+.Fa str .
+Reading stops when a newline character is found,
+at end-of-file or error.
+The newline, if any, is retained, and a
+.Ql \e0
+character is appended to end the string.
+.Pp
+The
+.Fn gets
+function
+is equivalent to
+.Fn fgets
+with an infinite
+.Fa size
+and a
+.Fa stream
+of
+.Em stdin ,
+except that the newline character (if any) is not stored in the string.
+It is the caller's responsibility to ensure that the input line,
+if any, is sufficiently short to fit in the string.
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn fgets
+and
+.Fn gets
+return
+a pointer to the string.
+If end-of-file or an error occurs before any characters are read,
+they return
+.Dv NULL .
+The
+.Fn fgets
+and
+.Fn gets
+functions
+do not distinguish between end-of-file and error, and callers must use
+.Xr feof 3
+and
+.Xr ferror 3
+to determine which occurred.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EBADF
+The given
+.Fa stream
+is not a readable stream.
+.El
+.Pp
+The function
+.Fn fgets
+may also fail and set
+.Va errno
+for any of the errors specified for the routines
+.Xr fflush 3 ,
+.Xr fstat 2 ,
+.Xr read 2 ,
+or
+.Xr malloc 3 .
+.Pp
+The function
+.Fn gets
+may also fail and set
+.Va errno
+for any of the errors specified for the routine
+.Xr getchar 3 .
+.Sh SEE ALSO
+.Xr feof 3 ,
+.Xr ferror 3 ,
+.Xr fgetln 3
+.Sh STANDARDS
+The functions
+.Fn fgets
+and
+.Fn gets
+conform to
+.St -ansiC
+and
+.St -p1003.1-2001 .
+The
+.St -p1003.1-2008
+revision marked
+.Fn gets
+as obsolescent.
+.Sh CAVEATS
+The following bit of code illustrates a case where the programmer assumes a
+string is too long if it does not contain a newline:
+.Bd -literal
+       char buf[1024], *p;
+
+       while (fgets(buf, sizeof(buf), fp) != NULL) {
+               if ((p = strchr(buf, '\en')) == NULL) {
+                       fprintf(stderr, "input line too long.\en");
+                       exit(1);
+               }
+               *p = '\e0';
+               printf("%s\en", buf);
+       }
+.Ed
+.Pp
+While the error would be true if a line longer than 1023 characters
+were read, it would be false in two other cases:
+.Bl -enum -offset indent
+.It
+If the last line in a file does not contain a newline, the string returned by
+.Fn fgets
+will not contain a newline either.
+Thus
+.Fn strchr
+will return
+.Dv NULL
+and the program will terminate, even if the line was valid.
+.It
+All C string functions, including
+.Fn strchr ,
+correctly assume the end of the string is represented by a null
+.Pq Sq \e0
+character.
+If the first character of a line returned by
+.Fn fgets
+were null,
+.Fn strchr
+would immediately return without considering the rest of the returned text
+which may indeed include a newline.
+.El
+.Pp
+Consider using
+.Xr fgetln 3
+instead when dealing with untrusted input.
+.Sh SECURITY CONSIDERATIONS
+Since it is usually impossible to ensure that the next input line
+is less than some arbitrary length, and because overflowing the
+input buffer is almost invariably a security violation, programs
+should
+.Em NEVER
+use
+.Fn gets .
+The
+.Fn gets
+function
+exists purely to conform to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdio/fgets.c b/lib/nbsd_libc/stdio/fgets.c
new file mode 100644 (file)
index 0000000..15a7370
--- /dev/null
@@ -0,0 +1,134 @@
+/*     $NetBSD: fgets.c,v 1.27 2009/10/25 20:44:13 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fgets.c    8.2 (Berkeley) 12/22/93";
+#else
+__RCSID("$NetBSD: fgets.c,v 1.27 2009/10/25 20:44:13 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include "reentrant.h"
+#include "local.h"
+#ifdef _FORTIFY_SOURCE
+#undef fgets
+#endif
+
+/*
+ * Read at most n-1 characters from the given file.
+ * Stop when a newline has been read, or the count runs out.
+ * Return first argument, or NULL if no characters were read.
+ */
+char *
+fgets(buf, n, fp)
+       char *buf;
+       int n;
+       FILE *fp;
+{
+       int len;
+       char *s;
+       unsigned char *p, *t;
+
+       _DIAGASSERT(buf != NULL);
+       _DIAGASSERT(fp != NULL);
+
+       FLOCKFILE(fp);
+       _SET_ORIENTATION(fp, -1);
+       s = buf;
+       n--;                    /* leave space for NUL */
+       do {
+               /*
+                * If the buffer is empty, refill it.
+                */
+               if (fp->_r <= 0) {
+                       if (__srefill(fp)) {
+                               /* EOF/error: stop with partial or no line */
+                               if (s == buf) {
+                                       FUNLOCKFILE(fp);
+                                       return (NULL);
+                               }
+                               break;
+                       }
+               }
+               len = fp->_r;
+               p = fp->_p;
+
+               /*
+                * Scan through at most n bytes of the current buffer,
+                * looking for '\n'.  If found, copy up to and including
+                * newline, and stop.  Otherwise, copy entire chunk
+                * and loop.
+                */
+               if (len > n) {
+                       if (n < 0) {
+                               /*
+                                * Caller's length <= 0
+                                * We can't write into the buffer, so cannot
+                                * return a string, so must return NULL.
+                                * Set errno and __SERR so it is consistent.
+                                * TOG gives no indication of what to do here!
+                                */
+                               errno = EINVAL;
+                               fp->_flags |= __SERR;
+                               FUNLOCKFILE(fp);
+                               return NULL;
+                       }
+                       len = n;
+               }
+               t = memchr(p, '\n', (size_t)len);
+               if (t != NULL) {
+                       len = (int)(++t - p);
+                       fp->_r -= len;
+                       fp->_p = t;
+                       (void)memcpy(s, p, (size_t)len);
+                       s[len] = 0;
+                       FUNLOCKFILE(fp);
+                       return (buf);
+               }
+               fp->_r -= len;
+               fp->_p += len;
+               (void)memcpy(s, p, (size_t)len);
+               s += len;
+               n -= len;
+       } while (n != 0);
+       *s = 0;
+       FUNLOCKFILE(fp);
+       return (buf);
+}
diff --git a/lib/nbsd_libc/stdio/fgetstr.c b/lib/nbsd_libc/stdio/fgetstr.c
new file mode 100644 (file)
index 0000000..3512a6f
--- /dev/null
@@ -0,0 +1,66 @@
+/* $NetBSD: fgetstr.c,v 1.11 2010/01/11 20:39:29 joerg Exp $   */
+
+/*
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Roy Marples.
+ *
+ * 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 ``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 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 <sys/cdefs.h>
+__RCSID("$NetBSD: fgetstr.c,v 1.11 2010/01/11 20:39:29 joerg Exp $");
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * Get an input line.
+ * This now uses getdelim(3) for a code reduction.
+ * The upside is that strings are now always NULL terminated, but relying
+ * on this is non portable - better to use the POSIX getdelim(3) function.
+ */
+char *
+__fgetstr(FILE *__restrict fp, size_t *__restrict lenp, int sep)
+{
+       ssize_t n;
+
+       _DIAGASSERT(fp != NULL);
+       _DIAGASSERT(lenp != NULL);
+
+       n = __getdelim(&_EXT(fp)->_fgetstr_buf, &_EXT(fp)->_fgetstr_len, sep, fp);
+       if (n == -1) {
+               *lenp = 0;
+               if (__sferror(fp) && errno == EOVERFLOW) /* fixup errno */
+                       errno = EINVAL;
+               return NULL;
+       }
+       *lenp = n;
+       return _EXT(fp)->_fgetstr_buf;
+}
diff --git a/lib/nbsd_libc/stdio/fgetwc.c b/lib/nbsd_libc/stdio/fgetwc.c
new file mode 100644 (file)
index 0000000..f875e34
--- /dev/null
@@ -0,0 +1,101 @@
+/* $NetBSD: fgetwc.c,v 1.11 2009/10/25 20:44:13 christos Exp $ */
+
+/*-
+ * Copyright (c)2001 Citrus Project,
+ * 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.
+ *
+ * $Citrus$
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fgetwc.c,v 1.11 2009/10/25 20:44:13 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <wchar.h>
+#include "reentrant.h"
+#include "local.h"
+
+wint_t
+__fgetwc_unlock(FILE *fp)
+{
+       struct wchar_io_data *wcio;
+       wchar_t wc;
+       size_t nr;
+
+       _DIAGASSERT(fp != NULL);
+
+       _SET_ORIENTATION(fp, 1);
+       wcio = WCIO_GET(fp);
+       _DIAGASSERT(wcio != NULL);
+
+       /* if there're ungetwc'ed wchars, use them */
+       if (wcio->wcio_ungetwc_inbuf)
+               return wcio->wcio_ungetwc_buf[--wcio->wcio_ungetwc_inbuf];
+
+       if (fp->_r <= 0) {
+restart:
+               if (__srefill(fp) != 0)
+                       return WEOF;
+       }
+       nr = mbrtowc(&wc, (const char *)fp->_p,
+           (size_t)fp->_r, &wcio->wcio_mbstate_in);
+       if (nr == (size_t)-1) {
+               fp->_flags |= __SERR;
+               return WEOF;
+       } else if (nr == (size_t)-2) {
+               fp->_p += fp->_r;
+               fp->_r = 0;
+               goto restart;
+       }
+       if (wc == L'\0') {
+               while (*fp->_p != '\0') {
+                       ++fp->_p;
+                       --fp->_r;
+               }
+               nr = 1;
+       }
+       fp->_p += nr;
+       fp->_r -= nr;
+
+       return wc;
+}
+
+wint_t
+fgetwc(FILE *fp)
+{
+       wint_t r;
+
+       _DIAGASSERT(fp != NULL);
+
+       FLOCKFILE(fp);
+       r = __fgetwc_unlock(fp);
+       FUNLOCKFILE(fp);
+
+       return (r);
+}
+
diff --git a/lib/nbsd_libc/stdio/fgetwln.3 b/lib/nbsd_libc/stdio/fgetwln.3
new file mode 100644 (file)
index 0000000..a17e595
--- /dev/null
@@ -0,0 +1,121 @@
+.\"    $NetBSD: fgetwln.3,v 1.2 2010/12/16 17:42:27 wiz Exp $
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"    This product includes software developed by the University of
+.\"    California, Berkeley and its contributors.
+.\" 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.
+.\"
+.\"     @(#)fgetln.3   8.3 (Berkeley) 4/19/94
+.\" $FreeBSD: src/lib/libc/stdio/fgetwln.3,v 1.1 2004/07/16 06:06:09 tjr Exp $
+.\"
+.Dd July 16, 2004
+.Dt FGETWLN 3
+.Os
+.Sh NAME
+.Nm fgetwln
+.Nd get a line of wide characters from a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.In wchar.h
+.Ft wchar_t *
+.Fn fgetwln "FILE * restrict stream" "size_t * restrict len"
+.Sh DESCRIPTION
+The
+.Fn fgetwln
+function
+returns a pointer to the next line from the stream referenced by
+.Fa stream .
+This line is
+.Em not
+a standard wide-character string as it does not end with a terminating
+null wide character.
+The length of the line, including the final newline,
+is stored in the memory location to which
+.Fa len
+points.
+(Note, however, that if the line is the last
+in a file that does not end in a newline,
+the returned text will not contain a newline.)
+.Sh RETURN VALUES
+Upon successful completion a pointer is returned;
+this pointer becomes invalid after the next
+.Tn I/O
+operation on
+.Fa stream
+(whether successful or not)
+or as soon as the stream is closed.
+Otherwise,
+.Dv NULL
+is returned.
+The
+.Fn fgetwln
+function
+does not distinguish between end-of-file and error; the routines
+.Xr feof 3
+and
+.Xr ferror 3
+must be used
+to determine which occurred.
+If an error occurs, the global variable
+.Va errno
+is set to indicate the error.
+The end-of-file condition is remembered, even on a terminal, and all
+subsequent attempts to read will return
+.Dv NULL
+until the condition is
+cleared with
+.Xr clearerr 3 .
+.Pp
+The text to which the returned pointer points may be modified,
+provided that no changes are made beyond the returned size.
+These changes are lost as soon as the pointer becomes invalid.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EBADF
+The argument
+.Fa stream
+is not a stream open for reading.
+.El
+.Pp
+The
+.Fn fgetwln
+function
+may also fail and set
+.Va errno
+for any of the errors specified for the routines
+.Xr mbrtowc 3 ,
+.Xr realloc 3 ,
+or
+.Xr read 2 .
+.Sh SEE ALSO
+.Xr ferror 3 ,
+.Xr fgetln 3 ,
+.Xr fgetws 3 ,
+.Xr fopen 3
diff --git a/lib/nbsd_libc/stdio/fgetwln.c b/lib/nbsd_libc/stdio/fgetwln.c
new file mode 100644 (file)
index 0000000..71ae0f1
--- /dev/null
@@ -0,0 +1,108 @@
+/*     $NetBSD: fgetwln.c,v 1.4 2010/01/11 20:39:29 joerg Exp $        */
+
+/*-
+ * Copyright (c) 2002-2004 Tim J. Robbins.
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/stdio/fgetwln.c,v 1.2 2004/08/06 17:00:09 tjr Exp $");
+#else
+__RCSID("$NetBSD: fgetwln.c,v 1.4 2010/01/11 20:39:29 joerg Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(fgetwln,_fgetwln)
+#endif
+
+/*
+ * Expand the line buffer.  Return -1 on error.
+#ifdef notdef
+ * The `new size' does not account for a terminating '\0',
+ * so we add 1 here.
+#endif
+ */
+static int
+__slbexpand(FILE *fp, size_t newsize)
+{
+       void *p;
+
+#ifdef notdef
+       ++newsize;
+#endif
+       _DIAGASSERT(fp != NULL);
+
+       if (_EXT(fp)->_fgetstr_len >= newsize)
+               return (0);
+       if ((p = realloc(_EXT(fp)->_fgetstr_buf, newsize)) == NULL)
+               return (-1);
+       _EXT(fp)->_fgetstr_buf = p;
+       _EXT(fp)->_fgetstr_len = newsize;
+       return (0);
+}
+
+wchar_t *
+fgetwln(FILE * __restrict fp, size_t *lenp)
+{
+       wint_t wc;
+       size_t len;
+
+       FLOCKFILE(fp);
+       _SET_ORIENTATION(fp, 1);
+
+       len = 0;
+       while ((wc = __fgetwc_unlock(fp)) != WEOF) {
+#define        GROW    512
+               if (len * sizeof(wchar_t) >= _EXT(fp)->_fgetstr_len &&
+                   __slbexpand(fp, (len + GROW) * sizeof(wchar_t)))
+                       goto error;
+               *((wchar_t *)(void *)_EXT(fp)->_fgetstr_buf + len++) = wc;
+               if (wc == L'\n')
+                       break;
+       }
+       if (len == 0)
+               goto error;
+
+       FUNLOCKFILE(fp);
+       *lenp = len;
+       return ((wchar_t *)(void *)_EXT(fp)->_fgetstr_buf);
+
+error:
+       FUNLOCKFILE(fp);
+       *lenp = 0;
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/stdio/fgetws.3 b/lib/nbsd_libc/stdio/fgetws.3
new file mode 100644 (file)
index 0000000..e0cc000
--- /dev/null
@@ -0,0 +1,122 @@
+.\" $NetBSD: fgetws.3,v 1.3 2010/12/16 17:42:27 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)fgets.3    8.1 (Berkeley) 6/4/93
+.\"
+.\" Original version ID:
+.\" FreeBSD: src/lib/libc/stdio/fgets.3,v 1.16 2002/05/31 05:01:17 archie Exp
+.\" FreeBSD: src/lib/libc/stdio/fgetws.3,v 1.2 2002/09/06 11:23:55 tjr Exp
+.\"
+.Dd August 6, 2002
+.Dt FGETWS 3
+.Os
+.Sh NAME
+.Nm fgetws
+.Nd get a line of wide characters from a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.In wchar.h
+.Ft "wchar_t *"
+.Fn fgetws "wchar_t * restrict ws" "int n" "FILE * restrict fp"
+.Sh DESCRIPTION
+The
+.Fn fgetws
+function
+reads at most one less than the number of characters specified by
+.Fa n
+from the given
+.Fa fp
+and stores them in the wide-character string
+.Fa ws .
+Reading stops when a newline character is found,
+at end-of-file or error.
+The newline, if any, is retained.
+If any characters are read and there is no error, a
+.Ql \e0
+character is appended to end the string.
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn fgetws
+returns
+.Fa ws .
+If end-of-file occurs before any characters are read,
+.Fn fgetws
+returns
+.Dv NULL
+and the buffer contents remain unchanged.
+If an error occurs,
+.Fn fgetws
+returns
+.Dv NULL
+and the buffer contents are indeterminate.
+The
+.Fn fgetws
+function
+does not distinguish between end-of-file and error, and callers must use
+.Xr feof 3
+and
+.Xr ferror 3
+to determine which occurred.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EBADF
+The given
+.Fa fp
+argument is not a readable stream.
+.It Bq Er EILSEQ
+The data obtained from the input stream does not form a valid
+multibyte character.
+.El
+.Pp
+The function
+.Fn fgetws
+may also fail and set
+.Va errno
+for any of the errors specified for the routines
+.Xr fflush 3 ,
+.Xr fstat 2 ,
+.Xr read 2 ,
+or
+.Xr malloc 3 .
+.Sh SEE ALSO
+.Xr feof 3 ,
+.Xr ferror 3 ,
+.Xr fgets 3
+.Sh STANDARDS
+The
+.Fn fgetws
+function
+conforms to
+.St -p1003.1-2001 .
diff --git a/lib/nbsd_libc/stdio/fgetws.c b/lib/nbsd_libc/stdio/fgetws.c
new file mode 100644 (file)
index 0000000..c78ee5a
--- /dev/null
@@ -0,0 +1,91 @@
+/* $NetBSD: fgetws.c,v 1.2 2006/07/03 17:06:36 tnozaki Exp $ */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins.
+ * 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.
+ *
+ * Original version ID:
+ * FreeBSD: src/lib/libc/stdio/fgetws.c,v 1.4 2002/09/20 13:25:40 tjr Exp
+ *
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIB_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fgetws.c,v 1.2 2006/07/03 17:06:36 tnozaki Exp $");
+#endif
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <wchar.h>
+#include "reentrant.h"
+#include "local.h"
+
+wchar_t *
+fgetws(ws, n, fp)
+       wchar_t * __restrict ws;
+       int n;
+       FILE * __restrict fp;
+{
+       wchar_t *wsp;
+       wint_t wc;
+
+       _DIAGASSERT(fp != NULL);
+       _DIAGASSERT(ws != NULL);
+
+       FLOCKFILE(fp);
+       _SET_ORIENTATION(fp, 1);
+
+       if (n <= 0) {
+               errno = EINVAL;
+               goto error;
+       }
+
+       wsp = ws;
+       while (n-- > 1) {
+               wc = __fgetwc_unlock(fp);
+               if (__sferror(fp) != 0)
+                       goto error;
+               if (__sfeof(fp) != 0) {
+                       if (wsp == ws) {
+                               /* EOF/error, no characters read yet. */
+                               goto error;
+                       }
+                       break;
+               }
+               *wsp++ = (wchar_t)wc;
+               if (wc == L'\n') {
+                       break;
+               }
+       }
+
+       *wsp++ = L'\0';
+       FUNLOCKFILE(fp);
+
+       return (ws);
+
+error:
+       FUNLOCKFILE(fp);
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/stdio/fileext.h b/lib/nbsd_libc/stdio/fileext.h
new file mode 100644 (file)
index 0000000..ce0436b
--- /dev/null
@@ -0,0 +1,74 @@
+/* $NetBSD: fileext.h,v 1.6 2010/01/11 20:39:29 joerg Exp $ */
+
+/*-
+ * Copyright (c)2001 Citrus Project,
+ * 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.
+ *
+ * $Citrus$
+ */
+
+/*
+ * file extension
+ */
+struct __sfileext {
+       struct  __sbuf _ub; /* ungetc buffer */
+       struct wchar_io_data _wcio;     /* wide char i/o status */
+       size_t _fgetstr_len;
+       char *_fgetstr_buf;
+#ifdef _REENTRANT
+       mutex_t _lock;  /* Lock for FLOCKFILE/FUNLOCKFILE */
+       cond_t _lockcond; /* Condition variable for signalling lock releases */
+       thr_t _lockowner; /* The thread currently holding the lock */
+       int _lockcount; /* Count of recursive locks */
+       int _lockinternal; /* Flag of whether the lock is held inside stdio */
+       int _lockcancelstate; /* Stashed cancellation state on internal lock */
+#endif 
+};
+
+#define _EXT(fp) ((struct __sfileext *)(void *)((fp)->_ext._base))
+#define _UB(fp) _EXT(fp)->_ub
+#ifdef _REENTRANT
+#define _LOCK(fp) (_EXT(fp)->_lock)
+#define _LOCKCOND(fp) (_EXT(fp)->_lockcond)
+#define _LOCKOWNER(fp) (_EXT(fp)->_lockowner)
+#define _LOCKCOUNT(fp) (_EXT(fp)->_lockcount)
+#define _LOCKINTERNAL(fp) (_EXT(fp)->_lockinternal)
+#define _LOCKCANCELSTATE(fp) (_EXT(fp)->_lockcancelstate)
+#define _FILEEXT_SETUP(f, fext) do { \
+       /* LINTED */(f)->_ext._base = (unsigned char *)(fext); \
+       (fext)->_fgetstr_len = 0; \
+       (fext)->_fgetstr_buf = NULL; \
+       mutex_init(&_LOCK(f), NULL); \
+       cond_init(&_LOCKCOND(f), 0, NULL); \
+       _LOCKOWNER(f) = NULL; \
+       _LOCKCOUNT(f) = 0; \
+       _LOCKINTERNAL(f) = 0; \
+       } while (/* CONSTCOND */ 0)
+#else
+#define _FILEEXT_SETUP(f, fext) do { \
+       /* LINTED */(f)->_ext._base = (unsigned char *)(fext); \
+       (fext)->_fgetstr_len = 0; \
+       (fext)->_fgetstr_buf = NULL; \
+       } while (/* CONSTCOND */ 0)
+#endif
diff --git a/lib/nbsd_libc/stdio/fileno.c b/lib/nbsd_libc/stdio/fileno.c
new file mode 100644 (file)
index 0000000..6550a28
--- /dev/null
@@ -0,0 +1,71 @@
+/*     $NetBSD: fileno.c,v 1.12 2004/05/09 17:27:53 kleink Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fileno.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fileno.c,v 1.12 2004/05/09 17:27:53 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * A subroutine version of the macro fileno.
+ */
+#undef fileno
+int _fileno __P((FILE *));     /* XXX */
+
+__weak_alias(fileno,_fileno)
+
+int
+_fileno(fp)
+       FILE *fp;
+{
+       int r;
+
+       _DIAGASSERT(fp != NULL);
+
+       FLOCKFILE(fp);
+       r = __sfileno(fp);
+       FUNLOCKFILE(fp);
+       return r;
+}
diff --git a/lib/nbsd_libc/stdio/findfp.c b/lib/nbsd_libc/stdio/findfp.c
new file mode 100644 (file)
index 0000000..4b31118
--- /dev/null
@@ -0,0 +1,213 @@
+/*     $NetBSD: findfp.c,v 1.25 2010/09/06 14:52:55 christos Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)findfp.c   8.2 (Berkeley) 1/4/94";
+#else
+__RCSID("$NetBSD: findfp.c,v 1.25 2010/09/06 14:52:55 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include "reentrant.h"
+#include "local.h"
+#include "glue.h"
+
+int    __sdidinit;
+
+#define        NDYNAMIC 10             /* add ten more whenever necessary */
+
+#define        std(flags, file) \
+/*       p     r  w  flags  file  bf     lfbsize  cookie       close */ \
+       { NULL, 0, 0, flags, file, { NULL, 0 }, 0, __sF + file, __sclose, \
+/*       read      seek     write     ext                              up */ \
+         __sread,  __sseek, __swrite, { (void *)(__sFext + file), 0 }, NULL, \
+/*       ur ubuf,                 nbuf      lb     blksize  offset */ \
+         0, { '\0', '\0', '\0' }, { '\0' }, { NULL, 0 }, 0, (fpos_t)0 }
+
+                               /* the usual - (stdin + stdout + stderr) */
+static FILE usual[FOPEN_MAX - 3];
+static struct __sfileext usualext[FOPEN_MAX - 3];
+static struct glue uglue = { 0, FOPEN_MAX - 3, usual };
+
+#if defined(_REENTRANT) && !defined(__lint__) /* XXX lint is busted */
+#define        STDEXT { ._lock = MUTEX_INITIALIZER, ._lockcond = COND_INITIALIZER }
+struct __sfileext __sFext[3] = { STDEXT,
+                                STDEXT,
+                                STDEXT};
+#else
+struct __sfileext __sFext[3];
+#endif
+
+FILE __sF[3] = {
+       std(__SRD, STDIN_FILENO),               /* stdin */
+       std(__SWR, STDOUT_FILENO),              /* stdout */
+       std(__SWR|__SNBF, STDERR_FILENO)        /* stderr */
+};
+struct glue __sglue = { &uglue, 3, __sF };
+
+static struct glue *moreglue __P((int));
+void f_prealloc __P((void));
+
+#ifdef _REENTRANT
+rwlock_t __sfp_lock = RWLOCK_INITIALIZER;
+#endif
+
+static struct glue *
+moreglue(n)
+       int n;
+{
+       struct glue *g;
+       FILE *p;
+       struct __sfileext *pext;
+       static FILE empty;
+
+       g = (struct glue *)malloc(sizeof(*g) + ALIGNBYTES + n * sizeof(FILE)
+               + n * sizeof(struct __sfileext));
+       if (g == NULL)
+               return (NULL);
+       p = (FILE *)ALIGN((u_long)(g + 1));
+       g->next = NULL;
+       g->niobs = n;
+       g->iobs = p;
+       pext = (void *)(p + n);
+       while (--n >= 0) {
+               *p = empty;
+               _FILEEXT_SETUP(p, pext);
+               p++;
+               pext++;
+       }
+       return (g);
+}
+
+void
+__sfpinit(FILE *fp)
+{
+       fp->_flags = 1;         /* reserve this slot; caller sets real flags */
+       fp->_p = NULL;          /* no current pointer */
+       fp->_w = 0;             /* nothing to read or write */
+       fp->_r = 0;
+       fp->_bf._base = NULL;   /* no buffer */
+       fp->_bf._size = 0;
+       fp->_lbfsize = 0;       /* not line buffered */
+       fp->_file = -1;         /* no file */
+/*     fp->_cookie = <any>; */ /* caller sets cookie, _read/_write etc */
+       _UB(fp)._base = NULL;   /* no ungetc buffer */
+       _UB(fp)._size = 0;
+       memset(WCIO_GET(fp), 0, sizeof(struct wchar_io_data));
+}
+
+/*
+ * Find a free FILE for fopen et al.
+ */
+FILE *
+__sfp()
+{
+       FILE *fp;
+       int n;
+       struct glue *g;
+
+       if (!__sdidinit)
+               __sinit();
+
+       rwlock_wrlock(&__sfp_lock);
+       for (g = &__sglue;; g = g->next) {
+               for (fp = g->iobs, n = g->niobs; --n >= 0; fp++)
+                       if (fp->_flags == 0)
+                               goto found;
+               if (g->next == NULL && (g->next = moreglue(NDYNAMIC)) == NULL)
+                       break;
+       }
+       rwlock_unlock(&__sfp_lock);
+       return (NULL);
+found:
+       __sfpinit(fp);
+       rwlock_unlock(&__sfp_lock);
+       return (fp);
+}
+
+/*
+ * XXX.  Force immediate allocation of internal memory.  Not used by stdio,
+ * but documented historically for certain applications.  Bad applications.
+ */
+void
+f_prealloc()
+{
+       struct glue *g;
+       int n;
+
+       n = (int)sysconf(_SC_OPEN_MAX) - FOPEN_MAX + 20; /* 20 for slop. */
+       for (g = &__sglue; (n -= g->niobs) > 0 && g->next; g = g->next)
+               /* void */;
+       if (n > 0)
+               g->next = moreglue(n);
+}
+
+/*
+ * exit() calls _cleanup() through *__cleanup, set whenever we
+ * open or buffer a file.  This chicanery is done so that programs
+ * that do not use stdio need not link it all in.
+ *
+ * The name `_cleanup' is, alas, fairly well known outside stdio.
+ */
+void
+_cleanup()
+{
+       /* (void) _fwalk(fclose); */
+       (void) fflush(NULL);                    /* `cheating' */
+}
+
+/*
+ * __sinit() is called whenever stdio's internal variables must be set up.
+ */
+void
+__sinit()
+{
+       int i;
+
+       for (i = 0; i < FOPEN_MAX - 3; i++)
+               _FILEEXT_SETUP(&usual[i], &usualext[i]);
+
+       /* make sure we clean up on exit */
+       __cleanup = _cleanup;           /* conservative */
+       __sdidinit = 1;
+}
diff --git a/lib/nbsd_libc/stdio/flags.c b/lib/nbsd_libc/stdio/flags.c
new file mode 100644 (file)
index 0000000..d977267
--- /dev/null
@@ -0,0 +1,112 @@
+/*     $NetBSD: flags.c,v 1.14 2003/08/07 16:43:23 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)flags.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: flags.c,v 1.14 2003/08/07 16:43:23 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <errno.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * Return the (stdio) flags for a given mode.  Store the flags
+ * to be passed to an open() syscall through *optr.
+ * Return 0 on error.
+ */
+int
+__sflags(mode, optr)
+       const char *mode;
+       int *optr;
+{
+       int ret, m, o;
+
+       _DIAGASSERT(mode != NULL);
+
+       switch (*mode++) {
+
+       case 'r':       /* open for reading */
+               ret = __SRD;
+               m = O_RDONLY;
+               o = 0;
+               break;
+
+       case 'w':       /* open for writing */
+               ret = __SWR;
+               m = O_WRONLY;
+               o = O_CREAT | O_TRUNC;
+               break;
+
+       case 'a':       /* open for appending */
+               ret = __SWR;
+               m = O_WRONLY;
+               o = O_CREAT | O_APPEND;
+               break;
+
+       default:        /* illegal mode */
+               errno = EINVAL;
+               return (0);
+       }
+
+       /*
+        * [rwa]\+ or [rwa]b\+ means read and write 
+        * f means open only plain files.
+        */
+       for (; *mode; mode++)
+               switch (*mode) {
+               case '+':
+                       ret = __SRW;
+                       m = O_RDWR;
+                       break;
+               case 'f':
+                       o |= O_NONBLOCK;
+                       break;
+               case 'b':
+                       break;
+               default:        /* We could produce a warning here */
+                       break;
+               }
+
+       *optr = m | o;
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/floatio.h b/lib/nbsd_libc/stdio/floatio.h
new file mode 100644 (file)
index 0000000..6c04cc2
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: floatio.h,v 1.5 2005/05/14 23:51:02 christos Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ *
+ *     @(#)floatio.h   8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * Floating point scanf/printf (input/output) definitions.
+ */
+
+/* 11-bit exponent (VAX G floating point) is 308 decimal digits */
+#define        MAXEXP          308
+/* 128 bit fraction takes up 39 decimal digits; max reasonable precision */
+#define        MAXFRACT        39
+/*    
+ * MAXEXPDIG is the maximum number of decimal digits needed to store a
+ * floating point exponent in the largest supported format.  It should
+ * be ceil(log10(LDBL_MAX_10_EXP)) or, if hexadecimal floating point 
+ * conversions are supported, ceil(log10(LDBL_MAX_EXP)).  But since it
+ * is presently never greater than 5 in practice, we fudge it.
+ */   
+#define MAXEXPDIG       6
+#if LDBL_MAX_EXP > 999999
+#error "floating point buffers too small"
+#endif 
diff --git a/lib/nbsd_libc/stdio/flockfile.3 b/lib/nbsd_libc/stdio/flockfile.3
new file mode 100644 (file)
index 0000000..d14099f
--- /dev/null
@@ -0,0 +1,120 @@
+.\"    $NetBSD: flockfile.3,v 1.4 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 28, 2003
+.Dt FLOCKFILE 3
+.Os
+.Sh NAME
+.Nm flockfile ,
+.Nm ftrylockfile ,
+.Nm funlockfile
+.Nd stdio stream locking functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft void
+.Fn flockfile "FILE *file"
+.Ft int
+.Fn ftrylockfile "FILE *file"
+.Ft void
+.Fn funlockfile "FILE *file"
+.Sh DESCRIPTION
+The
+.Fn flockfile ,
+.Fn ftrylockfile ,
+and
+.Fn funlockfile
+functions provide applications with explicit control of locking of
+stdio stream objects.
+They can be used by a thread to execute a sequence of I/O operations
+as a unit, without interference from another thread.
+.Pp
+Locks on stdio streams are recursive, and a lock count is maintained.
+stdio streams are created unlocked, with a lock count of zero.
+After successful acquisition of the lock, its count is incremented
+to one, indicating locked state of the stdio stream.
+Each subsequent relock operation performed by the owner thread
+increments the lock count by one, and each subsequent unlock
+operation performed by the owner thread decrements the lock count by one,
+allowing matching lock and unlock operations to be nested.
+After its lock count is decremented to zero, the stdio stream returns
+to unlocked state, and ownership of the stdio stream is relinquished.
+.Pp
+The
+.Fn flockfile
+function acquires the ownership of
+.Fa file
+for the calling thread.
+If
+.Fa file
+is already owned by another thread, the calling thread is suspended
+until the acquisition is possible (i.e.,
+.Fa file
+is relinquished again and the calling thread is scheduled to acquire it).
+.Pp
+The
+.Fn ftrylockfile
+function acquires the ownership of
+.Fa file
+for the calling thread only if
+.Fa file
+is available.
+.Pp
+The
+.Fn funlockfile
+function relinquishes the ownership of
+.Fa file
+previously granted to the calling thread.
+Only the current owner of
+.Fa file
+may
+.Fn funlockfile
+it.
+.Sh RETURN VALUES
+If successful, the
+.Fn ftrylockfile
+function returns 0.
+Otherwise, it returns non-zero to indicate that the lock cannot be acquired.
+.Sh SEE ALSO
+.Xr getc_unlocked 3 ,
+.Xr getchar_unlocked 3 ,
+.Xr putc_unlocked 3 ,
+.Xr putchar_unlocked 3
+.Sh STANDARDS
+The
+.Fn flockfile ,
+.Fn ftrylockfile
+and
+.Fn funlockfile
+functions conform to
+.St -p1003.1-2001 .
+.Sh BUGS
+The design of these interfaces does not allow for addressing the
+problem of priority inversion.
diff --git a/lib/nbsd_libc/stdio/flockfile.c b/lib/nbsd_libc/stdio/flockfile.c
new file mode 100644 (file)
index 0000000..f06d806
--- /dev/null
@@ -0,0 +1,183 @@
+/*     $NetBSD: flockfile.c,v 1.10 2010/12/08 02:07:03 joerg Exp $     */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Nathan J. Williams.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: flockfile.c,v 1.10 2010/12/08 02:07:03 joerg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(flockfile,_flockfile)
+__weak_alias(ftrylockfile,_ftrylockfile)
+__weak_alias(funlockfile,_funlockfile)
+#endif
+
+#ifdef _REENTRANT
+/*
+ * XXX This code makes the assumption that a thr_t (pthread_t) is a 
+ * XXX pointer.
+ */
+
+void
+flockfile(FILE *fp)
+{
+
+       __flockfile_internal(fp, 0);
+}
+
+int
+ftrylockfile(FILE *fp)
+{
+       int retval;
+
+       if (__isthreaded == 0)
+               return 0;
+
+       retval = 0;
+       mutex_lock(&_LOCK(fp));
+               
+       if (_LOCKOWNER(fp) == thr_self()) {
+               _LOCKCOUNT(fp)++;
+       } else if (_LOCKOWNER(fp) == NULL) {
+               _LOCKOWNER(fp) = thr_self();
+               _LOCKCOUNT(fp) = 1;
+       } else
+               retval = -1;
+
+       mutex_unlock(&_LOCK(fp));
+
+       return retval;
+}
+
+void
+funlockfile(FILE *fp)
+{
+
+       __funlockfile_internal(fp, 0);
+}
+
+void
+__flockfile_internal(FILE *fp, int internal)
+{
+
+       if (__isthreaded == 0)
+               return;
+
+       mutex_lock(&_LOCK(fp));
+       
+       if (_LOCKOWNER(fp) == thr_self()) {
+               _LOCKCOUNT(fp)++;
+               if (internal)
+                       _LOCKINTERNAL(fp)++;
+       } else {
+               /* danger! cond_wait() is a cancellation point. */
+               int oldstate;
+               thr_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
+               while (_LOCKOWNER(fp) != NULL)
+                       cond_wait(&_LOCKCOND(fp), &_LOCK(fp));
+               thr_setcancelstate(oldstate, NULL);
+               _LOCKOWNER(fp) = thr_self();
+               _LOCKCOUNT(fp) = 1;
+               if (internal)
+                       _LOCKINTERNAL(fp) = 1;
+       }
+
+       if (_LOCKINTERNAL(fp) == 1)
+               /* stash cancellation state and disable */
+               thr_setcancelstate(PTHREAD_CANCEL_DISABLE,
+                   &_LOCKCANCELSTATE(fp));
+
+       mutex_unlock(&_LOCK(fp));
+}
+void
+__funlockfile_internal(FILE *fp, int internal)
+{
+
+       if (__isthreaded == 0)
+               return;
+
+       mutex_lock(&_LOCK(fp));
+
+       if (internal) {
+               _LOCKINTERNAL(fp)--;
+               if (_LOCKINTERNAL(fp) == 0)
+                       thr_setcancelstate(_LOCKCANCELSTATE(fp), NULL);
+       }
+
+       _LOCKCOUNT(fp)--;
+       if (_LOCKCOUNT(fp) == 0) {
+               _LOCKOWNER(fp) = NULL;
+               cond_signal(&_LOCKCOND(fp));
+       }
+
+       mutex_unlock(&_LOCK(fp));
+}
+
+#else /* _REENTRANT */
+
+void
+flockfile(FILE *fp)
+{
+       /* LINTED deliberate lack of effect */
+       (void)fp;
+
+       return;
+}
+
+int
+ftrylockfile(FILE *fp)
+{
+       /* LINTED deliberate lack of effect */
+       (void)fp;
+
+       return (0);
+}
+
+void
+funlockfile(FILE *fp)
+{
+       /* LINTED deliberate lack of effect */
+       (void)fp;
+
+       return;
+}
+
+#endif /* _REENTRANT */
diff --git a/lib/nbsd_libc/stdio/fmemopen.3 b/lib/nbsd_libc/stdio/fmemopen.3
new file mode 100644 (file)
index 0000000..e028315
--- /dev/null
@@ -0,0 +1,193 @@
+.\"    $NetBSD: fmemopen.3,v 1.5 2010/10/07 00:14:14 enami Exp $
+.\"
+.\" Copyright (c) 2010 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Christos Zoulas.
+.\"
+.\" 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. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"        This product includes software developed by the NetBSD
+.\"        Foundation, Inc. and its contributors.
+.\" 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd September 24, 2010
+.Dt FMEMOPEN 3
+.Os
+.Sh NAME
+.Nm fmemopen
+.Nd open a stream that points to the given buffer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft FILE *
+.Fn fmemopen "void  *restrict buffer" "size_t size" "const char *restrict mode"
+.Sh DESCRIPTION
+The
+.Fn fmemopen
+function
+associates a stream with the given
+.Fa buffer
+and
+.Fa size .
+The
+.Fa buffer
+can be either
+.Dv NULL ,
+or must be of the given
+.Fa size .
+If the
+.Fa buffer
+is
+.Dv NULL ,
+a
+.Fa buffer
+of the given
+.Fa size
+will be dynamically allocated using
+.Xr malloc 3
+and freed when
+.Xr fclose 3
+is called.
+.Pp
+The
+.Fa mode
+argument has the same meaning as in
+.Xr fopen 3 .
+.Pp
+The stream treats the buffer as it would treat a file tracking the current
+position to perform I/O operations.
+For example, in the beginning the stream points to the beginning of the buffer,
+unless
+.Dv a
+was specified in the
+.Fa mode
+argument, and then it points to the first
+.Dv NUL
+byte.
+If a
+.Dv NULL
+.Fa buffer
+was specified, then the stream will always point at the first byte of the
+.Fa buffer .
+.Pp
+The stream also keeps track of the
+.Fa size
+of the
+.Fa buffer .
+The
+.Fa size
+is initialized depending on the mode:
+.Bl -tag -width r/w+
+.It Dv r/r+
+Set to the
+.Fa size
+argument.
+.It Dv w/w+
+Set to
+.Dv 0 .
+.It Dv a/a+
+Set to the first
+.Dv NUL
+byte, or the
+.Fa size
+argument if one is not found.
+.El
+.Pp
+Read or write operations advance the buffer, but not to exceed the given
+.Fa size
+of the
+.Fa buffer .
+Trying to read beyond the
+.Fa size
+of the
+.Fa buffer
+results in
+.Dv EOF
+returned.
+.Dv NUL
+bytes are read normally.
+Trying to write beyond the
+.Fa size
+of the
+.Fa buffer
+has no effect.
+.Pp
+When a stream open for writing is either flushed or closed, a
+.Dv NUL
+byte is written at the current position or at the end of the current
+.Fa size
+as kept internally, if there is room.
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn fmemopen
+returns a
+.Dv FILE
+pointer.
+Otherwise,
+.Dv NULL
+is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa size
+was
+.Dv 0 ;
+or the
+.Fa mode
+argument is invalid;
+or the
+.Fa buffer
+argument is
+.Dv NULL
+and the
+.Fa mode
+argument does not specify a
+.Dv + .
+.El
+.Pp
+The
+.Fn fmemopen
+function
+may also fail and set
+.Va errno
+for any of the errors
+specified for the routine
+.Xr malloc 3 .
+.Sh SEE ALSO
+.Xr fclose 3 ,
+.Xr fflush 3 ,
+.Xr fopen 3 ,
+.Xr malloc 3
+.Sh HISTORY
+The
+.Fn fmemopen
+functions first appeared in
+.Nx 6.0 .
diff --git a/lib/nbsd_libc/stdio/fmemopen.c b/lib/nbsd_libc/stdio/fmemopen.c
new file mode 100644 (file)
index 0000000..33840e3
--- /dev/null
@@ -0,0 +1,220 @@
+/* $NetBSD: fmemopen.c,v 1.5 2010/09/27 17:08:29 tnozaki Exp $ */
+
+/*-
+ * Copyright (c)2007, 2010 Takehiko NOZAKI,
+ * 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.
+ *
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fmemopen.c,v 1.5 2010/09/27 17:08:29 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+struct fmemopen_cookie {
+       char *head, *tail, *cur, *eob;
+};
+
+static int
+fmemopen_read(void *cookie, char *buf, int nbytes)
+{
+       struct fmemopen_cookie *p;
+       char *s;
+
+       _DIAGASSERT(cookie != NULL);
+       _DIAGASSERT(buf != NULL && nbytes > 0);
+
+       p = (struct fmemopen_cookie *)cookie;
+       s = p->cur;
+       do {
+               if (p->cur == p->tail)
+                       break;
+               *buf++ = *p->cur++;
+       } while (--nbytes > 0);
+
+       return (int)(p->cur - s);
+}
+
+static int
+fmemopen_write(void *cookie, const char *buf, int nbytes)
+{
+       struct fmemopen_cookie *p;
+       char *s;
+
+       _DIAGASSERT(cookie != NULL);
+       _DIAGASSERT(buf != NULL && nbytes > 0);
+
+       p = (struct fmemopen_cookie *)cookie;
+       if (p->cur >= p->tail)
+               return 0;
+       s = p->cur;
+       do {
+               if (p->cur == p->tail - 1) {
+                       if (*buf == '\0') {
+                               *p->cur++ = '\0';
+                               goto ok;
+                       }
+                       break;
+               }
+               *p->cur++ = *buf++;
+       } while (--nbytes > 0);
+       *p->cur = '\0';
+ok:
+       if (p->cur > p->eob)
+               p->eob = p->cur;
+
+       return (int)(p->cur - s);
+}
+
+static fpos_t
+fmemopen_seek(void *cookie, fpos_t offset, int whence)
+{
+       struct fmemopen_cookie *p;
+       _DIAGASSERT(cookie != NULL);
+
+       p = (struct fmemopen_cookie *)cookie;
+       switch (whence) {
+       case SEEK_SET:
+               break;
+       case SEEK_CUR:
+               offset += p->cur - p->head;
+               break;
+       case SEEK_END:
+               offset += p->eob - p->head;
+               break;
+       default:
+               errno = EINVAL;
+               goto error;
+       }
+       if (offset >= (fpos_t)0 && offset <= p->tail - p->head) {
+               p->cur = p->head + (ptrdiff_t)offset;
+               return (fpos_t)(p->cur - p->head);
+       }
+error:
+       return (fpos_t)-1;
+}
+
+static int
+fmemopen_close0(void *cookie)
+{
+       _DIAGASSERT(cookie != NULL);
+
+       free(cookie);
+
+       return 0;
+}
+
+static int
+fmemopen_close1(void *cookie)
+{
+       struct fmemopen_cookie *p;
+
+       _DIAGASSERT(cookie != NULL);
+
+       p = (struct fmemopen_cookie *)cookie;
+       free(p->head);
+       free(p);
+
+       return 0;
+}
+
+
+FILE *
+fmemopen(void * __restrict buf, size_t size, const char * __restrict mode)
+{
+       int flags, oflags;
+       FILE *fp;
+       struct fmemopen_cookie *cookie;
+
+       if (size < (size_t)1)
+               goto invalid;
+
+       flags = __sflags(mode, &oflags);
+       if (flags == 0)
+               return NULL;
+
+       if ((oflags & O_RDWR) == 0 && buf == NULL)
+               goto invalid;
+
+       fp = __sfp();
+       if (fp == NULL)
+               return NULL;
+       fp->_file = -1;
+
+       cookie = malloc(sizeof(*cookie));
+       if (cookie == NULL)
+               goto release;
+
+       if (buf == NULL) {
+               cookie->head = malloc(size);
+               if (cookie->head == NULL) {
+                       free(cookie);
+                       goto release;
+               }
+               *cookie->head = '\0';
+               fp->_close = &fmemopen_close1;
+       } else {
+               cookie->head = (char *)buf;
+               if (oflags & O_TRUNC)
+                       *cookie->head = '\0';
+               fp->_close = &fmemopen_close0;
+       }
+
+       cookie->tail = cookie->head + size;
+       cookie->eob  = cookie->head;
+       do {
+               if (*cookie->eob == '\0')
+                       break;
+               ++cookie->eob;
+       } while (--size > 0);
+
+       cookie->cur = (oflags & O_APPEND) ? cookie->eob : cookie->head;
+
+       fp->_flags  = flags;
+       fp->_write  = (flags & __SRD) ? NULL : &fmemopen_write;
+       fp->_read   = (flags & __SWR) ? NULL : &fmemopen_read;
+       fp->_seek   = &fmemopen_seek;
+       fp->_cookie = (void *)cookie;
+
+       return fp;
+
+invalid:
+       errno = EINVAL;
+       return NULL;
+
+release:
+       fp->_flags = 0;
+       return NULL;
+}
diff --git a/lib/nbsd_libc/stdio/fopen.3 b/lib/nbsd_libc/stdio/fopen.3
new file mode 100644 (file)
index 0000000..ad897b6
--- /dev/null
@@ -0,0 +1,278 @@
+.\"    $NetBSD: fopen.3,v 1.24 2010/04/05 21:34:47 joerg Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)fopen.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt FOPEN 3
+.Os
+.Sh NAME
+.Nm fopen ,
+.Nm fdopen ,
+.Nm freopen
+.Nd stream open functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft FILE *
+.Fn fopen "const char * restrict path" "const char * restrict mode"
+.Ft FILE *
+.Fn fdopen "int fildes" "const char *mode"
+.Ft FILE *
+.Fn freopen "const char * restrict path" "const char * restrict mode" "FILE * restrict stream"
+.Sh DESCRIPTION
+The
+.Fn fopen
+function
+opens the file whose name is the string pointed to by
+.Fa path
+and associates a stream with it.
+.Pp
+The argument
+.Fa mode
+points to a string beginning with one of the following
+sequences (Additional characters may follow these sequences.):
+.Bl -tag -width indent
+.It Dq Li r
+Open for reading.
+.It Dq Li r+
+Open for reading and writing.
+.It Dq Li w
+Open for writing.
+Truncate file to zero length or create file.
+.It Dq Li w+
+Open for reading and writing.
+Truncate file to zero length or create file.
+.It Dq Li a
+Append; open for writing.
+The file is created if it does not exist.
+.It Dq Li a+
+Append; open for reading and writing.
+The file is created if it does not exist.
+.El
+.Pp
+The
+.Fa mode
+string can also include the letter ``b'' either as a last character or
+as a character between the characters in any of the two-character strings
+described above.
+This is strictly for compatibility with
+.St -ansiC
+and has no effect; the ``b'' is ignored.
+.Pp
+The letter ``f'' in the mode string restricts fopen to regular
+files; if the file opened is not a regular file,
+.Fn fopen
+will fail.
+This is a non
+.St -ansiC
+extension.
+.Pp
+Any created files will have mode
+.Pf \*q Dv S_IRUSR
+\&|
+.Dv S_IWUSR
+\&|
+.Dv S_IRGRP
+\&|
+.Dv S_IWGRP
+\&|
+.Dv S_IROTH
+\&|
+.Dv S_IWOTH Ns \*q
+.Pq Li 0666 ,
+as modified by the process'
+umask value (see
+.Xr umask 2 ) .
+.Pp
+Opening a file with append mode causes all subsequent writes to it
+to be forced to the then current end of file, regardless of intervening
+repositioning of the stream.
+.Pp
+The
+.Fn fopen
+and
+.Fn freopen
+functions initially position the stream at the start of the file
+unless the file is opened with append mode,
+in which case the stream is initially positioned at the end of the file.
+.\" PR 6072 claims this paragraph is not correct.
+.\" .Pp
+.\" Reads and writes may be intermixed on read/write streams in any order,
+.\" and do not require an intermediate seek as in previous versions of
+.\" .Em stdio .
+.\" This is not portable to other systems, however;
+.\" .Tn ANSI C
+.\" requires that
+.\" a file positioning function intervene between output and input, unless
+.\" an input operation encounters end-of-file.
+.Pp
+The
+.Fn fdopen
+function associates a stream with the existing file descriptor,
+.Fa fildes .
+The
+.Fa mode
+of the stream must be compatible with the mode of the file descriptor.
+The stream is positioned at the file offset of the file descriptor.
+.Pp
+The
+.Fn freopen
+function
+opens the file whose name is the string pointed to by
+.Fa path
+and associates the stream pointed to by
+.Fa stream
+with it.
+The original stream (if it exists) is closed.
+The
+.Fa mode
+argument is used just as in the
+.Fn fopen
+function.
+The primary use of the
+.Fn freopen
+function
+is to change the file associated with a
+standard text stream
+.Pf ( Em stderr ,
+.Em stdin ,
+or
+.Em stdout ) .
+.Sh RETURN VALUES
+Upon successful completion
+.Fn fopen ,
+.Fn fdopen
+and
+.Fn freopen
+return a
+.Tn FILE
+pointer.
+Otherwise,
+.Dv NULL
+is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa mode
+provided to
+.Fn fopen ,
+.Fn fdopen ,
+or
+.Fn freopen
+was invalid.
+.It Bq Er EFTYPE
+The file is not a regular file and the character ``f'' is specified
+in the mode.
+.El
+.Pp
+The
+.Fn fopen ,
+.Fn fdopen
+and
+.Fn freopen
+functions
+may also fail and set
+.Va errno
+for any of the errors specified for the routine
+.Xr malloc 3 .
+.Pp
+The
+.Fn fopen
+function
+may also fail and set
+.Va errno
+for any of the errors specified for the routine
+.Xr open 2 .
+.Pp
+The
+.Fn fdopen
+function
+may also fail and set
+.Va errno
+for any of the errors specified for the routine
+.Xr fcntl 2 .
+.Pp
+The
+.Fn freopen
+function
+may also fail and set
+.Va errno
+for any of the errors specified for the routines
+.Xr open 2 ,
+.Xr fclose 3
+and
+.Xr fflush 3 .
+.Sh SEE ALSO
+.Xr open 2 ,
+.Xr fclose 3 ,
+.Xr fileno 3 ,
+.Xr fseek 3 ,
+.Xr funopen 3
+.Sh STANDARDS
+The
+.Fn fopen
+and
+.Fn freopen
+functions
+conform to
+.St -ansiC .
+The
+.Fn fdopen
+function conforms to
+.St -p1003.1-90 .
+.Sh CAVEATS
+Proper code using
+.Fn fdopen
+with error checking should
+.Xr close 2
+.Fa fildes
+in case of failure, and
+.Xr fclose 3
+the resulting FILE * in case of success.
+.Bd -literal
+       FILE *file;
+       int fd;
+
+       if ((file = fdopen(fd, "r")) != NULL) {
+               /* perform operations on the FILE * */
+               fclose(file);
+       } else {
+               /* failure, report the error */
+               close(fd);
+       }
+.Ed
diff --git a/lib/nbsd_libc/stdio/fopen.c b/lib/nbsd_libc/stdio/fopen.c
new file mode 100644 (file)
index 0000000..c75e1c0
--- /dev/null
@@ -0,0 +1,119 @@
+/*     $NetBSD: fopen.c,v 1.13 2008/03/13 15:40:00 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fopen.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fopen.c,v 1.13 2008/03/13 15:40:00 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <assert.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <errno.h>
+#include <limits.h>
+#include "reentrant.h"
+#include "local.h"
+
+FILE *
+fopen(file, mode)
+       const char *file;
+       const char *mode;
+{
+       FILE *fp;
+       int f;
+       int flags, oflags;
+
+       _DIAGASSERT(file != NULL);
+       if ((flags = __sflags(mode, &oflags)) == 0)
+               return (NULL);
+       if ((fp = __sfp()) == NULL)
+               return (NULL);
+       if ((f = open(file, oflags, DEFFILEMODE)) < 0)
+               goto release;
+       if (oflags & O_NONBLOCK) {
+               struct stat st;
+               if (fstat(f, &st) == -1) {
+                       int sverrno = errno;
+                       (void)close(f);
+                       errno = sverrno;
+                       goto release;
+               }
+               if (!S_ISREG(st.st_mode)) {
+                       (void)close(f);
+                       errno = EFTYPE;
+                       goto release;
+               }
+       }
+       /*
+        * File descriptors are a full int, but _file is only a short.
+        * If we get a valid file descriptor that is greater or equal to
+        * USHRT_MAX, then the fd will get sign-extended into an
+        * invalid file descriptor.  Handle this case by failing the
+        * open. (We treat the short as unsigned, and special-case -1).
+        */
+       if (f >= USHRT_MAX) {
+               errno = EMFILE;
+               goto release;
+       }
+
+       fp->_file = f;
+       fp->_flags = flags;
+       fp->_cookie = fp;
+       fp->_read = __sread;
+       fp->_write = __swrite;
+       fp->_seek = __sseek;
+       fp->_close = __sclose;
+
+       /*
+        * When opening in append mode, even though we use O_APPEND,
+        * we need to seek to the end so that ftell() gets the right
+        * answer.  If the user then alters the seek pointer, or
+        * the file extends, this will fail, but there is not much
+        * we can do about this.  (We could set __SAPP and check in
+        * fseek and ftell.)
+        */
+       if (oflags & O_APPEND)
+               (void) __sseek((void *)fp, (fpos_t)0, SEEK_END);
+       return (fp);
+release:
+       fp->_flags = 0;                 /* release */
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/stdio/fparseln.3 b/lib/nbsd_libc/stdio/fparseln.3
new file mode 100644 (file)
index 0000000..41fe962
--- /dev/null
@@ -0,0 +1,148 @@
+.\"    $NetBSD: fparseln.3,v 1.4 2009/10/21 01:07:45 snj Exp $
+.\"
+.\" Copyright (c) 1997 Christos Zoulas.  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 ``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 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.
+.\"
+.Dd November 30, 2002
+.Dt FPARSELN 3
+.Os
+.Sh NAME
+.Nm fparseln
+.Nd return the next logical line from a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft "char *"
+.Fo "fparseln"
+.Fa "FILE *stream" "size_t *len" "size_t *lineno"
+.Fa "const char delim[3]" "int flags"
+.Fc
+.Sh DESCRIPTION
+The
+.Fn fparseln
+function
+returns a pointer to the next logical line from the stream referenced by
+.Fa stream .
+This string is
+.Dv NUL
+terminated and it is dynamically allocated on each invocation.
+It is the responsibility of the caller to free the pointer.
+.Pp
+By default, if a character is escaped, both it and the preceding escape
+character will be present in the returned string.
+Various
+.Fa flags
+alter this behaviour.
+.Pp
+The meaning of the arguments is as follows:
+.Bl -tag -width "lineno"
+.It Fa stream
+The stream to read from.
+.It Fa len
+If not
+.Dv NULL ,
+the length of the string is stored in the memory location to which it
+points.
+.It Fa lineno
+If not
+.Dv NULL ,
+the value of the memory location to which is pointed to, is incremented
+by the number of lines actually read from the file.
+.It Fa delim
+Contains the escape, continuation, and comment characters.
+If a character is
+.Dv NUL
+then processing for that character is disabled.
+If
+.Dv NULL ,
+all characters default to values specified below.
+The contents of
+.Fa delim
+is as follows:
+.Bl -tag -width "delim[0]"
+.It Fa delim[0]
+The escape character, which defaults to
+.Cm \e ,
+is used to remove any special meaning from the next character.
+.It Fa delim[1]
+The continuation character, which defaults to
+.Cm \e ,
+is used to indicate that the next line should be concatenated with the
+current one if this character is the last character on the current line
+and is not escaped.
+.It Fa delim[2]
+The comment character, which defaults to
+.Cm # ,
+if not escaped indicates the beginning of a comment that extends until the
+end of the current line.
+.El
+.It Fa flags
+If non-zero, alter the operation of
+.Fn fparseln .
+The various flags, which may be
+.Em or Ns -ed
+together, are:
+.Bl -tag -width "FPARSELN_UNESCCOMM"
+.It Dv FPARSELN_UNESCCOMM
+Remove escape preceding an escaped comment.
+.It Dv FPARSELN_UNESCCONT
+Remove escape preceding an escaped continuation.
+.It Dv FPARSELN_UNESCESC
+Remove escape preceding an escaped escape.
+.It Dv FPARSELN_UNESCREST
+Remove escape preceding any other character.
+.It Dv FPARSELN_UNESCALL
+All of the above.
+.El
+.Pp
+.El
+.Sh RETURN VALUES
+Upon successful completion a pointer to the parsed line is returned;
+otherwise,
+.Dv NULL
+is returned.
+.Pp
+The
+.Fn fparseln
+function uses internally
+.Xr fgetln 3 ,
+so all error conditions that apply to
+.Xr fgetln 3 ,
+apply to
+.Fn fparseln .
+In addition
+.Fn fparseln
+may set
+.Va errno
+to
+.Bq Er ENOMEM
+and return
+.Dv NULL
+if it runs out of memory.
+.Sh SEE ALSO
+.Xr fgetln 3
+.Sh HISTORY
+The
+.Fn fparseln
+function first appeared in
+.Nx 1.4 .
diff --git a/lib/nbsd_libc/stdio/fparseln.c b/lib/nbsd_libc/stdio/fparseln.c
new file mode 100644 (file)
index 0000000..902f6fe
--- /dev/null
@@ -0,0 +1,249 @@
+/*     $NetBSD: fparseln.c,v 1.10 2009/10/21 01:07:45 snj Exp $        */
+
+/*
+ * Copyright (c) 1997 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fparseln.c,v 1.10 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(fparseln,_fparseln)
+#endif
+
+#if ! HAVE_FPARSELN || BROKEN_FPARSELN
+
+#ifndef HAVE_NBTOOL_CONFIG_H
+#include "reentrant.h"
+#include "local.h"
+#else
+#define FLOCKFILE(fp)
+#define FUNLOCKFILE(fp)
+#endif
+
+#if defined(_REENTRANT) && !HAVE_NBTOOL_CONFIG_H
+#define __fgetln(f, l) __fgetstr(f, l, '\n')
+#else
+#define __fgetln(f, l) fgetln(f, l)
+#endif
+
+static int isescaped(const char *, const char *, int);
+
+/* isescaped():
+ *     Return true if the character in *p that belongs to a string
+ *     that starts in *sp, is escaped by the escape character esc.
+ */
+static int
+isescaped(const char *sp, const char *p, int esc)
+{
+       const char     *cp;
+       size_t          ne;
+
+       _DIAGASSERT(sp != NULL);
+       _DIAGASSERT(p != NULL);
+
+       /* No escape character */
+       if (esc == '\0')
+               return 0;
+
+       /* Count the number of escape characters that precede ours */
+       for (ne = 0, cp = p; --cp >= sp && *cp == esc; ne++)
+               continue;
+
+       /* Return true if odd number of escape characters */
+       return (ne & 1) != 0;
+}
+
+
+/* fparseln():
+ *     Read a line from a file parsing continuations ending in \
+ *     and eliminating trailing newlines, or comments starting with
+ *     the comment char.
+ */
+char *
+fparseln(FILE *fp, size_t *size, size_t *lineno, const char str[3], int flags)
+{
+       static const char dstr[3] = { '\\', '\\', '#' };
+
+       size_t  s, len;
+       char   *buf;
+       char   *ptr, *cp;
+       int     cnt;
+       char    esc, con, nl, com;
+
+       _DIAGASSERT(fp != NULL);
+
+       len = 0;
+       buf = NULL;
+       cnt = 1;
+
+       if (str == NULL)
+               str = dstr;
+
+       esc = str[0];
+       con = str[1];
+       com = str[2];
+       /*
+        * XXX: it would be cool to be able to specify the newline character,
+        * but unfortunately, fgetln does not let us
+        */
+       nl  = '\n';
+
+       FLOCKFILE(fp);
+
+       while (cnt) {
+               cnt = 0;
+
+               if (lineno)
+                       (*lineno)++;
+
+               if ((ptr = __fgetln(fp, &s)) == NULL)
+                       break;
+
+               if (s && com) {         /* Check and eliminate comments */
+                       for (cp = ptr; cp < ptr + s; cp++)
+                               if (*cp == com && !isescaped(ptr, cp, esc)) {
+                                       s = cp - ptr;
+                                       cnt = s == 0 && buf == NULL;
+                                       break;
+                               }
+               }
+
+               if (s && nl) {          /* Check and eliminate newlines */
+                       cp = &ptr[s - 1];
+
+                       if (*cp == nl)
+                               s--;    /* forget newline */
+               }
+
+               if (s && con) {         /* Check and eliminate continuations */
+                       cp = &ptr[s - 1];
+
+                       if (*cp == con && !isescaped(ptr, cp, esc)) {
+                               s--;    /* forget continuation char */
+                               cnt = 1;
+                       }
+               }
+
+               if (s == 0) {
+                       /*
+                        * nothing to add, skip realloc except in case
+                        * we need a minimal buf to return an empty line
+                        */
+                       if (cnt || buf != NULL)
+                               continue;
+               }
+
+               if ((cp = realloc(buf, len + s + 1)) == NULL) {
+                       FUNLOCKFILE(fp);
+                       free(buf);
+                       return NULL;
+               }
+               buf = cp;
+
+               (void) memcpy(buf + len, ptr, s);
+               len += s;
+               buf[len] = '\0';
+       }
+
+       FUNLOCKFILE(fp);
+
+       if ((flags & FPARSELN_UNESCALL) != 0 && esc && buf != NULL &&
+           strchr(buf, esc) != NULL) {
+               ptr = cp = buf;
+               while (cp[0] != '\0') {
+                       int skipesc;
+
+                       while (cp[0] != '\0' && cp[0] != esc)
+                               *ptr++ = *cp++;
+                       if (cp[0] == '\0' || cp[1] == '\0')
+                               break;
+
+                       skipesc = 0;
+                       if (cp[1] == com)
+                               skipesc += (flags & FPARSELN_UNESCCOMM);
+                       if (cp[1] == con)
+                               skipesc += (flags & FPARSELN_UNESCCONT);
+                       if (cp[1] == esc)
+                               skipesc += (flags & FPARSELN_UNESCESC);
+                       if (cp[1] != com && cp[1] != con && cp[1] != esc)
+                               skipesc = (flags & FPARSELN_UNESCREST);
+
+                       if (skipesc)
+                               cp++;
+                       else
+                               *ptr++ = *cp++;
+                       *ptr++ = *cp++;
+               }
+               *ptr = '\0';
+               len = strlen(buf);
+       }
+
+       if (size)
+               *size = len;
+       return buf;
+}
+
+#ifdef TEST
+
+int main(int, char **);
+
+int
+main(int argc, char **argv)
+{
+       char   *ptr;
+       size_t  size, line;
+
+       line = 0;
+       while ((ptr = fparseln(stdin, &size, &line, NULL,
+           FPARSELN_UNESCALL)) != NULL)
+               printf("line %d (%d) |%s|\n", line, size, ptr);
+       return 0;
+}
+
+/*
+
+# This is a test
+line 1
+line 2 \
+line 3 # Comment
+line 4 \# Not comment \\\\
+
+# And a comment \
+line 5 \\\
+line 6
+
+*/
+
+#endif /* TEST */
+#endif /* ! HAVE_FPARSELN || BROKEN_FPARSELN */
diff --git a/lib/nbsd_libc/stdio/fprintf.c b/lib/nbsd_libc/stdio/fprintf.c
new file mode 100644 (file)
index 0000000..54e4f33
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: fprintf.c,v 1.11 2003/08/07 16:43:24 agc Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fprintf.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fprintf.c,v 1.11 2003/08/07 16:43:24 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stdio.h>
+
+int
+fprintf(FILE *fp, const char *fmt, ...)
+{
+       int ret;
+       va_list ap;
+
+       _DIAGASSERT(fp != NULL);
+       _DIAGASSERT(fmt != NULL);
+
+       va_start(ap, fmt);
+       ret = vfprintf(fp, fmt, ap);
+       va_end(ap);
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/fpurge.c b/lib/nbsd_libc/stdio/fpurge.c
new file mode 100644 (file)
index 0000000..3e0706d
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: fpurge.c,v 1.13 2003/08/07 16:43:24 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fpurge.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fpurge.c,v 1.13 2003/08/07 16:43:24 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * fpurge: like fflush, but without writing anything: leave the
+ * given FILE's buffer empty.
+ */
+int
+fpurge(fp)
+       FILE *fp;
+{
+
+       _DIAGASSERT(fp != NULL);
+
+       if (fp->_flags == 0) {
+               errno = EBADF;
+               return (EOF);
+       }
+       FLOCKFILE(fp);
+       if (HASUB(fp))
+               FREEUB(fp);
+       WCIO_FREE(fp);
+       fp->_p = fp->_bf._base;
+       fp->_r = 0;
+       fp->_w = fp->_flags & (__SLBF|__SNBF) ? 0 : fp->_bf._size;
+       FUNLOCKFILE(fp);
+       return (0);
+}
diff --git a/lib/nbsd_libc/stdio/fputc.c b/lib/nbsd_libc/stdio/fputc.c
new file mode 100644 (file)
index 0000000..1bc81e3
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: fputc.c,v 1.12 2003/08/07 16:43:24 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fputc.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fputc.c,v 1.12 2003/08/07 16:43:24 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+int
+fputc(c, fp)
+       int c;
+       FILE *fp;
+{
+       int r;
+
+       _DIAGASSERT(fp != NULL);
+
+       FLOCKFILE(fp); 
+       r = __sputc(c, fp);
+       FUNLOCKFILE(fp);
+       return r;
+}
diff --git a/lib/nbsd_libc/stdio/fputs.3 b/lib/nbsd_libc/stdio/fputs.3
new file mode 100644 (file)
index 0000000..352579c
--- /dev/null
@@ -0,0 +1,107 @@
+.\"    $NetBSD: fputs.3,v 1.11 2003/08/07 16:43:24 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)fputs.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt FPUTS 3
+.Os
+.Sh NAME
+.Nm fputs ,
+.Nm puts
+.Nd output a line to a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft int
+.Fn fputs "const char * restrict str" "FILE * restrict stream"
+.Ft int
+.Fn puts "const char *str"
+.Sh DESCRIPTION
+The function
+.Fn fputs
+writes the string pointed to by
+.Fa str
+to the stream pointed to by
+.Fa stream .
+.\" The terminating
+.\" .Dv NUL
+.\" character is not written.
+.Pp
+The function
+.Fn puts
+writes the string
+.Fa str ,
+and a terminating newline character,
+to the stream
+.Em stdout .
+.Sh RETURN VALUES
+The
+.Fn fputs
+function
+returns 0 on success and
+.Dv EOF
+on error;
+.Fn puts
+returns a nonnegative integer on success and
+.Dv EOF
+on error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa stream
+supplied
+is not a writable stream.
+.El
+.Pp
+The functions
+.Fn fputs
+and
+.Fn puts
+may also fail and set
+.Va errno
+for any of the errors specified for the routines
+.Xr write 2 .
+.Sh SEE ALSO
+.Xr ferror 3 ,
+.Xr putc 3 ,
+.Xr stdio 3
+.Sh STANDARDS
+The functions
+.Fn fputs
+and
+.Fn puts
+conform to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdio/fputs.c b/lib/nbsd_libc/stdio/fputs.c
new file mode 100644 (file)
index 0000000..5463595
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: fputs.c,v 1.14 2005/06/22 19:45:22 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fputs.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fputs.c,v 1.14 2005/06/22 19:45:22 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include "reentrant.h"
+#include "local.h"
+#include "fvwrite.h"
+
+/*
+ * Write the given string to the given file.
+ */
+int
+fputs(s, fp)
+       const char *s;
+       FILE *fp;
+{
+       struct __suio uio;
+       struct __siov iov;
+       int r;
+
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(fp != NULL);
+
+       if (s == NULL)
+               s = "(null)";
+
+       iov.iov_base = __UNCONST(s);
+       iov.iov_len = uio.uio_resid = strlen(s);
+       uio.uio_iov = &iov;
+       uio.uio_iovcnt = 1;
+       FLOCKFILE(fp);
+       _SET_ORIENTATION(fp, -1);
+       r = __sfvwrite(fp, &uio);
+       FUNLOCKFILE(fp);
+       return r;
+}
diff --git a/lib/nbsd_libc/stdio/fputwc.c b/lib/nbsd_libc/stdio/fputwc.c
new file mode 100644 (file)
index 0000000..3c9b35a
--- /dev/null
@@ -0,0 +1,100 @@
+/* $NetBSD: fputwc.c,v 1.4 2005/06/12 05:21:27 lukem Exp $ */
+
+/*-
+ * Copyright (c)2001 Citrus Project,
+ * 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.
+ *
+ * $Citrus$
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fputwc.c,v 1.4 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <wchar.h>
+#include "reentrant.h"
+#include "local.h"
+#include "fvwrite.h"
+
+wint_t
+__fputwc_unlock(wchar_t wc, FILE *fp)
+{
+       struct wchar_io_data *wcio;
+       mbstate_t *st;
+       size_t size;
+       char buf[MB_LEN_MAX];
+       struct __suio uio;
+       struct __siov iov;
+
+       _DIAGASSERT(fp != NULL);
+       
+       /* LINTED we don't play with buf */
+       iov.iov_base = (void *)buf;
+       uio.uio_iov = &iov;
+       uio.uio_iovcnt = 1;
+
+       _SET_ORIENTATION(fp, 1);
+       wcio = WCIO_GET(fp);
+       if (wcio == 0) {
+               errno = ENOMEM;
+               return WEOF;
+       }
+
+       wcio->wcio_ungetwc_inbuf = 0;
+       st = &wcio->wcio_mbstate_out;
+
+       size = wcrtomb(buf, wc, st);
+       if (size == (size_t)-1) {
+               errno = EILSEQ;
+               return WEOF;
+       }
+
+       _DIAGASSERT(size != 0);
+
+       uio.uio_resid = iov.iov_len = size;
+       if (__sfvwrite(fp, &uio)) {
+               return WEOF;
+       }
+
+       return (wint_t)wc;
+}
+
+wint_t
+fputwc(wchar_t wc, FILE *fp)
+{
+       wint_t r;
+
+       _DIAGASSERT(fp != NULL);
+
+       FLOCKFILE(fp);
+       r = __fputwc_unlock(wc, fp);
+       FUNLOCKFILE(fp);
+
+       return (r);
+}
diff --git a/lib/nbsd_libc/stdio/fputws.3 b/lib/nbsd_libc/stdio/fputws.3
new file mode 100644 (file)
index 0000000..858a7af
--- /dev/null
@@ -0,0 +1,89 @@
+.\" $NetBSD: fputws.3,v 1.3 2010/12/16 17:42:27 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)fputs.3    8.1 (Berkeley) 6/4/93
+.\"
+.\" Original version ID:
+.\" FreeBSD: src/lib/libc/stdio/fputs.3,v 1.8 2001/10/01 16:08:59 ru Exp
+.\" FreeBSD: src/lib/libc/stdio/fputws.c,v 1.4 2002/09/20 13:25:40 tjr Exp
+.\"
+.Dd August 6, 2002
+.Dt FPUTWS 3
+.Os
+.Sh NAME
+.Nm fputws
+.Nd output a line of wide characters to a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.In wchar.h
+.Ft int
+.Fn fputws "const wchar_t * restrict ws" "FILE * restrict fp"
+.Sh DESCRIPTION
+The
+.Fn fputws
+function writes the wide-character string pointed to by
+.Fa ws
+to the stream pointed to by
+.Fa fp .
+.Sh RETURN VALUES
+The
+.Fn fputws
+function
+returns 0 on success and \-1 on error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa fp
+argument supplied
+is not a writable stream.
+.El
+.Pp
+The
+.Fn fputws
+function may also fail and set
+.Va errno
+for any of the errors specified for the routine
+.Xr write 2 .
+.Sh SEE ALSO
+.Xr ferror 3 ,
+.Xr fputs 3 ,
+.Xr putwc 3 ,
+.Xr stdio 3
+.Sh STANDARDS
+The
+.Fn fputws
+function conforms to
+.St -p1003.1-2001 .
diff --git a/lib/nbsd_libc/stdio/fputws.c b/lib/nbsd_libc/stdio/fputws.c
new file mode 100644 (file)
index 0000000..f1599b9
--- /dev/null
@@ -0,0 +1,65 @@
+/* $NetBSD: fputws.c,v 1.1 2003/03/07 07:11:37 tshiozak Exp $ */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins.
+ * 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.
+ *
+ * Original version ID:
+ * FreeBSD: src/lib/libc/stdio/fputws.c,v 1.4 2002/09/20 13:25:40 tjr Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fputws.c,v 1.1 2003/03/07 07:11:37 tshiozak Exp $");
+#endif
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <wchar.h>
+#include "reentrant.h"
+#include "local.h"
+
+int
+fputws(ws, fp)
+       const wchar_t * __restrict ws;
+       FILE * __restrict fp;
+{
+       _DIAGASSERT(fp != NULL);
+       _DIAGASSERT(ws != NULL);
+
+       FLOCKFILE(fp);
+       _SET_ORIENTATION(fp, 1);
+
+       while (*ws != '\0') {
+               if (__fputwc_unlock(*ws++, fp) == WEOF) {
+                       FUNLOCKFILE(fp);
+                       return (-1);
+               }
+       }
+
+       FUNLOCKFILE(fp);
+
+       return (0);
+}
diff --git a/lib/nbsd_libc/stdio/fread.3 b/lib/nbsd_libc/stdio/fread.3
new file mode 100644 (file)
index 0000000..dc9a91d
--- /dev/null
@@ -0,0 +1,124 @@
+.\"    $NetBSD: fread.3,v 1.14 2009/01/11 02:46:29 christos Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)fread.3    8.2 (Berkeley) 3/8/94
+.\"
+.Dd December 19, 2008
+.Dt FREAD 3
+.Os
+.Sh NAME
+.Nm fread ,
+.Nm fwrite
+.Nd binary stream input/output
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft size_t
+.Fn fread "void * restrict ptr" "size_t size" "size_t nmemb" "FILE * restrict stream"
+.Ft size_t
+.Fn fwrite "const void * restrict ptr" "size_t size" "size_t nmemb" "FILE * restrict stream"
+.Sh DESCRIPTION
+The function
+.Fn fread
+reads
+.Fa nmemb
+objects, each
+.Fa size
+bytes long, from the stream pointed to by
+.Fa stream ,
+storing them at the location given by
+.Fa ptr .
+.Pp
+The function
+.Fn fwrite
+writes
+.Fa nmemb
+objects, each
+.Fa size
+bytes long, to the stream pointed to by
+.Fa stream ,
+obtaining them from the location given by
+.Fa ptr .
+.Pp
+Mixing
+.Fn fread
+and
+.Fn fwrite
+calls without setting the file position explicitly using
+.Fn fsetpos
+between read and write or write and read operations will lead to unexpected
+results because of buffering the file pointer not being set to the
+expected position after each operation completes.
+This behavior is allowed by ANSI C for efficiency and it will not be changed.
+.Sh RETURN VALUES
+The functions
+.Fn fread
+and
+.Fn fwrite
+advance the file position indicator for the stream
+by the number of bytes read or written.
+They return the number of objects read or written.
+If
+.Fa size
+or
+.Fa nmemb
+is 0, the functions return 0 and the state of
+.Fa stream
+remains unchanged.
+If an error occurs, or the end-of-file is reached,
+the return value is a short object count (or zero).
+.Pp
+The function
+.Fn fread
+does not distinguish between end-of-file and error, and callers
+must use
+.Xr feof 3
+and
+.Xr ferror 3
+to determine which occurred.
+The function
+.Fn fwrite
+returns a value less than
+.Fa nmemb
+only if a write error has occurred.
+.Sh SEE ALSO
+.Xr read 2 ,
+.Xr write 2
+.Sh STANDARDS
+The functions
+.Fn fread
+and
+.Fn fwrite
+conform to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdio/fread.c b/lib/nbsd_libc/stdio/fread.c
new file mode 100644 (file)
index 0000000..d61fa81
--- /dev/null
@@ -0,0 +1,95 @@
+/*     $NetBSD: fread.c,v 1.20 2009/10/25 20:44:13 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fread.c    8.2 (Berkeley) 12/11/93";
+#else
+__RCSID("$NetBSD: fread.c,v 1.20 2009/10/25 20:44:13 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include "reentrant.h"
+#include "local.h"
+
+size_t
+fread(buf, size, count, fp)
+       void *buf;
+       size_t size, count;
+       FILE *fp;
+{
+       size_t resid;
+       char *p;
+       int r;
+       size_t total;
+
+       _DIAGASSERT(fp != NULL);
+       /*
+        * The ANSI standard requires a return value of 0 for a count
+        * or a size of 0.  Whilst ANSI imposes no such requirements on
+        * fwrite, the SUSv2 does.
+        */
+       if ((resid = count * size) == 0)
+               return (0);
+
+       _DIAGASSERT(buf != NULL);
+
+       FLOCKFILE(fp);
+       if (fp->_r < 0)
+               fp->_r = 0;
+       total = resid;
+       p = buf;
+       while (resid > (size_t)(r = fp->_r)) {
+               (void)memcpy(p, fp->_p, (size_t)r);
+               fp->_p += r;
+               /* fp->_r = 0 ... done in __srefill */
+               p += r;
+               resid -= r;
+               if (__srefill(fp)) {
+                       /* no more input: return partial result */
+                       FUNLOCKFILE(fp);
+                       return ((total - resid) / size);
+               }
+       }
+       (void)memcpy(p, fp->_p, resid);
+       fp->_r -= resid;
+       fp->_p += resid;
+       FUNLOCKFILE(fp);
+       return (count);
+}
diff --git a/lib/nbsd_libc/stdio/freopen.c b/lib/nbsd_libc/stdio/freopen.c
new file mode 100644 (file)
index 0000000..5b370fa
--- /dev/null
@@ -0,0 +1,205 @@
+/*     $NetBSD: freopen.c,v 1.16 2010/01/11 20:39:29 joerg Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)freopen.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: freopen.c,v 1.16 2010/01/11 20:39:29 joerg Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include <limits.h>
+#include "reentrant.h"
+#include "local.h"
+
+/* 
+ * Re-direct an existing, open (probably) file to some other file. 
+ * ANSI is written such that the original file gets closed if at
+ * all possible, no matter what.
+ */
+FILE *
+freopen(file, mode, fp)
+       const char *file, *mode;
+       FILE *fp;
+{
+       int f;
+       int flags, isopen, oflags, sverrno, wantfd;
+
+       _DIAGASSERT(file != NULL);
+       _DIAGASSERT(mode != NULL);
+       _DIAGASSERT(fp != NULL);
+
+       if ((flags = __sflags(mode, &oflags)) == 0) {
+               (void) fclose(fp);
+               return (NULL);
+       }
+
+       if (!__sdidinit)
+               __sinit();
+
+       /*
+        * There are actually programs that depend on being able to "freopen"
+        * descriptors that weren't originally open.  Keep this from breaking.
+        * Remember whether the stream was open to begin with, and which file
+        * descriptor (if any) was associated with it.  If it was attached to
+        * a descriptor, defer closing it; freopen("/dev/stdin", "r", stdin)
+        * should work.  This is unnecessary if it was not a Unix file.
+        */
+       if (fp->_flags == 0) {
+               fp->_flags = __SEOF;    /* hold on to it */
+               isopen = 0;
+               wantfd = -1;
+       } else {
+               /* flush the stream; ANSI doesn't require this. */
+               if (fp->_flags & __SWR)
+                       (void) __sflush(fp);
+               /* if close is NULL, closing is a no-op, hence pointless */
+               isopen = fp->_close != NULL;
+               if ((wantfd = __sfileno(fp)) == -1 && isopen) {
+                       (void) (*fp->_close)(fp->_cookie);
+                       isopen = 0;
+               }
+       }
+
+       /* Get a new descriptor to refer to the new file. */
+       f = open(file, oflags, DEFFILEMODE);
+       if (f < 0 && isopen) {
+               /* If out of fd's close the old one and try again. */
+               if (errno == ENFILE || errno == EMFILE) {
+                       (void) (*fp->_close)(fp->_cookie);
+                       isopen = 0;
+                       f = open(file, oflags, DEFFILEMODE);
+               }
+       }
+       sverrno = errno;
+
+       /*
+        * Finish closing fp.  Even if the open succeeded above, we cannot
+        * keep fp->_base: it may be the wrong size.  This loses the effect
+        * of any setbuffer calls, but stdio has always done this before.
+        */
+       if (isopen && f != wantfd)
+               (void) (*fp->_close)(fp->_cookie);
+       if (fp->_flags & __SMBF)
+               free((char *)fp->_bf._base);
+       fp->_w = 0;
+       fp->_r = 0;
+       fp->_p = NULL;
+       fp->_bf._base = NULL;
+       fp->_bf._size = 0;
+       fp->_lbfsize = 0;
+       if (HASUB(fp))
+               FREEUB(fp);
+       WCIO_FREE(fp);
+       _UB(fp)._size = 0;
+       FREELB(fp);
+
+       if (f < 0) {                    /* did not get it after all */
+               fp->_flags = 0;         /* set it free */
+               errno = sverrno;        /* restore in case _close clobbered */
+               return (NULL);
+       }
+
+       if (oflags & O_NONBLOCK) {
+               struct stat st;
+               if (fstat(f, &st) == -1) {
+                       sverrno = errno;
+                       (void)close(f);
+                       errno = sverrno;
+                       return (NULL);
+               }
+               if (!S_ISREG(st.st_mode)) {
+                       (void)close(f);
+                       errno = EFTYPE;
+                       return (NULL);
+               }
+       }
+
+       /*
+        * If reopening something that was open before on a real file, try
+        * to maintain the descriptor.  Various C library routines (perror)
+        * assume stderr is always fd STDERR_FILENO, even if being freopen'd.
+        */
+       if (wantfd >= 0 && f != wantfd) {
+               if (dup2(f, wantfd) >= 0) {
+                       (void) close(f);
+                       f = wantfd;
+               }
+       }
+
+       /*
+        * File descriptors are a full int, but _file is only a short.
+        * If we get a valid file descriptor that is greater or equal to
+        * USHRT_MAX, then the fd will get sign-extended into an
+        * invalid file descriptor.  Handle this case by failing the
+        * open. (We treat the short as unsigned, and special-case -1).
+        */
+       if (f >= USHRT_MAX) {
+               (void)close(f);
+               errno = EMFILE;
+               return NULL;
+       }
+
+       fp->_flags = flags;
+       fp->_file = f;
+       fp->_cookie = fp;
+       fp->_read = __sread;
+       fp->_write = __swrite;
+       fp->_seek = __sseek;
+       fp->_close = __sclose;
+
+       /*
+        * When reopening in append mode, even though we use O_APPEND,
+        * we need to seek to the end so that ftell() gets the right
+        * answer.  If the user then alters the seek pointer, or
+        * the file extends, this will fail, but there is not much
+        * we can do about this.  (We could set __SAPP and check in
+        * fseek and ftell.)
+        */
+       if (oflags & O_APPEND)
+               (void) __sseek((void *)fp, (fpos_t)0, SEEK_END);
+       return (fp);
+}
diff --git a/lib/nbsd_libc/stdio/fscanf.c b/lib/nbsd_libc/stdio/fscanf.c
new file mode 100644 (file)
index 0000000..817e9a1
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: fscanf.c,v 1.12 2003/08/07 16:43:25 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fscanf.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fscanf.c,v 1.12 2003/08/07 16:43:25 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stdio.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+int
+fscanf(FILE *fp, char const *fmt, ...)
+{
+       int ret;
+       va_list ap;
+
+       va_start(ap, fmt);
+       ret = __svfscanf(fp, fmt, ap);
+       va_end(ap);
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/fseek.3 b/lib/nbsd_libc/stdio/fseek.3
new file mode 100644 (file)
index 0000000..9b776db
--- /dev/null
@@ -0,0 +1,251 @@
+.\"    $NetBSD: fseek.3,v 1.25 2010/10/22 21:29:31 christos Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)fseek.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd October 22, 2010
+.Dt FSEEK 3
+.Os
+.Sh NAME
+.Nm fgetpos ,
+.Nm fseek ,
+.Nm fseeko ,
+.Nm fsetpos ,
+.Nm ftell ,
+.Nm ftello ,
+.Nm rewind
+.Nd reposition a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft int
+.Fn fseek "FILE *stream" "long int offset" "int whence"
+.Ft int
+.Fn fseeko "FILE *stream" "off_t offset" "int whence"
+.Ft long int
+.Fn ftell "FILE *stream"
+.Ft off_t
+.Fn ftello "FILE *stream"
+.Ft void
+.Fn rewind "FILE *stream"
+.Ft int
+.Fn fgetpos "FILE * restrict stream" "fpos_t * restrict pos"
+.Ft int
+.Fn fsetpos "FILE * restrict stream" "const fpos_t * restrict pos"
+.Sh DESCRIPTION
+The
+.Fn fseek
+function sets the file position indicator for the stream pointed
+to by
+.Fa stream .
+The new position, measured in bytes, is obtained by adding
+.Fa offset
+bytes to the position specified by
+.Fa whence .
+If
+.Fa whence
+is set to
+.Dv SEEK_SET ,
+.Dv SEEK_CUR ,
+or
+.Dv SEEK_END ,
+the offset is relative to the
+start of the file, the current position indicator, or end-of-file,
+respectively.
+A successful call to the
+.Fn fseek
+function clears the end-of-file indicator for the stream and undoes
+any effects of the
+.Xr ungetc 3
+function on the same stream.
+.Pp
+The
+.Fn fseeko
+function is identical to the
+.Fn fseek
+function except that the
+.Fa offset
+argument is of type
+.Fa off_t .
+.Pp
+The
+.Fn ftell
+function
+obtains the current value of the file position indicator for the
+stream pointed to by
+.Fa stream .
+.Pp
+The
+.Fn ftello
+function is identical to the
+.Fn ftell
+function except that the return value is of type
+.Fa off_t .
+.Pp
+The
+.Fn rewind
+function sets the file position indicator for the stream pointed
+to by
+.Fa stream
+to the beginning of the file.
+It is equivalent to:
+.Pp
+.Dl (void)fseek(stream, 0L, SEEK_SET)
+.Pp
+except that the error indicator for the stream is also cleared
+(see
+.Xr clearerr 3 ) .
+.Pp
+In this implementation, the
+.Fn fgetpos
+and
+.Fn fsetpos
+functions
+are alternative interfaces equivalent to
+.Fn ftell ,
+.Fn ftello ,
+.Fn fseek ,
+and
+.Fn fseeko
+(with whence set to
+.Dv SEEK_SET ) ,
+setting and storing the current value of
+the file offset into or from the object referenced by
+.Fa pos .
+In others implementations, an
+.Dq Fa fpos_t
+object may be a complex object
+and these routines may be the only way to portably reposition a text stream.
+.Sh RETURN VALUES
+The
+.Fn rewind
+function
+returns no value.
+Upon successful completion,
+.Fn fgetpos ,
+.Fn fseek ,
+.Fn fseeko ,
+and
+.Fn fsetpos
+return 0.
+The functions
+.Fn ftell
+and
+.Fn ftello
+return the current offset.
+Otherwise,
+.Fn fseek ,
+.Fn fseeko ,
+.Fn ftell ,
+and
+.Fn ftello
+return \-1 while
+.Fn fgetpos
+and
+.Fn fsetpos
+return a nonzero value.
+On error all functions the global variable
+.Va errno
+is set to indicate the error.
+Since the
+.Fn rewind
+function does not return an error code, applications need to clear
+.Va errno
+before calling it in order to detect errors.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa stream
+specified
+is not a seekable stream.
+.It Bq Er EINVAL
+The
+.Fa whence
+argument to
+.Fn fseek
+was not
+.Dv SEEK_SET ,
+.Dv SEEK_END ,
+or
+.Dv SEEK_CUR .
+.It Bq Er EOVERFLOW
+For
+.Fn ftell ,
+the current file offset cannot be represented correctly in an object of type
+.Fa long .
+.El
+.Pp
+The function
+.Fn fgetpos ,
+.Fn fseek ,
+.Fn fseeko ,
+.Fn fsetpos ,
+.Fn ftell ,
+.Fn ftello ,
+and
+.Fn rewind
+may also fail and set
+.Va errno
+for any of the errors specified for the routines
+.Xr fflush 3 ,
+.Xr fstat 2 ,
+.Xr lseek 2 ,
+and
+.Xr malloc 3 .
+.Sh SEE ALSO
+.Xr lseek 2
+.Sh STANDARDS
+The
+.Fn fgetpos ,
+.Fn fsetpos ,
+.Fn fseek ,
+.Fn ftell ,
+and
+.Fn rewind
+functions
+conform to
+.St -ansiC .
+The
+.Fn fseeko
+and
+.Fn ftello
+functions conform to
+.St -xsh5 .
+.Sh BUGS
+The
+.Fn fgetpos
+and
+.Fn fsetpos
+functions don't store/set shift states of the stream in this implementation.
diff --git a/lib/nbsd_libc/stdio/fseek.c b/lib/nbsd_libc/stdio/fseek.c
new file mode 100644 (file)
index 0000000..bcfa5a9
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: fseek.c,v 1.23 2008/04/29 06:53:01 martin Exp $        */
+
+/*-
+ * Copyright (c) 2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by David Laight.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fseek.c,v 1.23 2008/04/29 06:53:01 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * Seek the given file to the given offset.
+ * Zero extend the offset if SEEK_SET to allow access to 4GB files
+ */
+int
+fseek(FILE *fp, long l_offset, int whence)
+{
+       off_t offset;
+
+       if (whence == SEEK_SET)
+               offset = (unsigned long)l_offset;
+       else
+               offset = l_offset;
+       return fseeko(fp, offset, whence);
+}
diff --git a/lib/nbsd_libc/stdio/fseeko.c b/lib/nbsd_libc/stdio/fseeko.c
new file mode 100644 (file)
index 0000000..a8708af
--- /dev/null
@@ -0,0 +1,263 @@
+/*     $NetBSD: fseeko.c,v 1.8 2009/01/31 00:08:05 lukem Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fseeko.c,v 1.8 2009/01/31 00:08:05 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(fseeko, _fseeko)
+#endif
+
+#define        POS_ERR (-(fpos_t)1)
+
+/*
+ * Seek the given file to the given offset.
+ * `Whence' must be one of the three SEEK_* macros.
+ */
+int
+fseeko(FILE *fp, off_t offset, int whence)
+{
+       fpos_t (*seekfn)(void *, fpos_t, int);
+       fpos_t target, curoff;
+       size_t n;
+       struct stat st;
+       int havepos;
+
+       _DIAGASSERT(fp != NULL);
+
+       /* make sure stdio is set up */
+       if (!__sdidinit)
+               __sinit();
+
+       FLOCKFILE(fp);
+
+       /*
+        * Have to be able to seek.
+        */
+       if ((seekfn = fp->_seek) == NULL) {
+               errno = ESPIPE;                 /* historic practice */
+               FUNLOCKFILE(fp);
+               return (-1);
+       }
+
+       /*
+        * Change any SEEK_CUR to SEEK_SET, and check `whence' argument.
+        * After this, whence is either SEEK_SET or SEEK_END.
+        */
+       switch (whence) {
+
+       case SEEK_CUR:
+               /*
+                * In order to seek relative to the current stream offset,
+                * we have to first find the current stream offset a la
+                * ftell (see ftell for details).
+                */
+               __sflush(fp);   /* may adjust seek offset on append stream */
+               if (fp->_flags & __SOFF)
+                       curoff = fp->_offset;
+               else {
+                       curoff = (*seekfn)(fp->_cookie, (fpos_t)0, SEEK_CUR);
+                       if (curoff == POS_ERR) {
+                               FUNLOCKFILE(fp);
+                               return (-1);
+                       }
+               }
+               if (fp->_flags & __SRD) {
+                       curoff -= fp->_r;
+                       if (HASUB(fp))
+                               curoff -= fp->_ur;
+               } else if (fp->_flags & __SWR && fp->_p != NULL)
+                       curoff += fp->_p - fp->_bf._base;
+
+               offset += curoff;
+               whence = SEEK_SET;
+               havepos = 1;
+               break;
+
+       case SEEK_SET:
+       case SEEK_END:
+               curoff = 0;             /* XXX just to keep gcc quiet */
+               havepos = 0;
+               break;
+
+       default:
+               errno = EINVAL;
+               FUNLOCKFILE(fp);
+               return (-1);
+       }
+
+       /*
+        * Can only optimise if:
+        *      reading (and not reading-and-writing);
+        *      not unbuffered; and
+        *      this is a `regular' Unix file (and hence seekfn==__sseek).
+        * We must check __NBF first, because it is possible to have __NBF
+        * and __SOPT both set.
+        */
+       if (fp->_bf._base == NULL)
+               __smakebuf(fp);
+       if (fp->_flags & (__SWR | __SRW | __SNBF | __SNPT))
+               goto dumb;
+       if ((fp->_flags & __SOPT) == 0) {
+               if (seekfn != __sseek ||
+                   __sfileno(fp) == -1 || fstat(__sfileno(fp), &st) ||
+                   !S_ISREG(st.st_mode)) {
+                       fp->_flags |= __SNPT;
+                       goto dumb;
+               }
+               fp->_blksize = st.st_blksize;
+               fp->_flags |= __SOPT;
+       }
+
+       /*
+        * We are reading; we can try to optimise.
+        * Figure out where we are going and where we are now.
+        */
+       if (whence == SEEK_SET)
+               target = offset;
+       else {
+               if (fstat(__sfileno(fp), &st))
+                       goto dumb;
+               target = st.st_size + offset;
+       }
+
+       if (!havepos) {
+               if (fp->_flags & __SOFF)
+                       curoff = fp->_offset;
+               else {
+                       curoff = (*seekfn)(fp->_cookie, (fpos_t)0, SEEK_CUR);
+                       if (curoff == POS_ERR)
+                               goto dumb;
+               }
+               curoff -= fp->_r;
+               if (HASUB(fp))
+                       curoff -= fp->_ur;
+       }
+
+       /*
+        * Compute the number of bytes in the input buffer (pretending
+        * that any ungetc() input has been discarded).  Adjust current
+        * offset backwards by this count so that it represents the
+        * file offset for the first byte in the current input buffer.
+        */
+       if (HASUB(fp)) {
+               curoff += fp->_r;       /* kill off ungetc */
+               n = fp->_up - fp->_bf._base;
+               curoff -= n;
+               n += fp->_ur;
+       } else {
+               n = fp->_p - fp->_bf._base;
+               curoff -= n;
+               n += fp->_r;
+       }
+
+       /*
+        * If the target offset is within the current buffer,
+        * simply adjust the pointers, clear EOF, undo ungetc(),
+        * and return.  (If the buffer was modified, we have to
+        * skip this; see fgetln.c.)
+        */
+       if ((fp->_flags & __SMOD) == 0 &&
+           target >= curoff && target < (fpos_t)(curoff + n)) {
+               int o = (int)(target - curoff);
+
+               fp->_p = fp->_bf._base + o;
+               fp->_r = n - o;
+               if (HASUB(fp))
+                       FREEUB(fp);
+               fp->_flags &= ~__SEOF;
+               FUNLOCKFILE(fp);
+               return (0);
+       }
+
+       /*
+        * The place we want to get to is not within the current buffer,
+        * but we can still be kind to the kernel copyout mechanism.
+        * By aligning the file offset to a block boundary, we can let
+        * the kernel use the VM hardware to map pages instead of
+        * copying bytes laboriously.  Using a block boundary also
+        * ensures that we only read one block, rather than two.
+        */
+       curoff = target & ~(fp->_blksize - 1);
+       if ((*seekfn)(fp->_cookie, curoff, SEEK_SET) == POS_ERR)
+               goto dumb;
+       fp->_r = 0;
+       fp->_p = fp->_bf._base;
+       if (HASUB(fp))
+               FREEUB(fp);
+       fp->_flags &= ~__SEOF;
+       n = (int)(target - curoff);
+       if (n) {
+               if (__srefill(fp) || (size_t)fp->_r < n)
+                       goto dumb;
+               fp->_p += n;
+               fp->_r -= n;
+       }
+       FUNLOCKFILE(fp);
+       return (0);
+
+       /*
+        * We get here if we cannot optimise the seek ... just
+        * do it.  Allow the seek function to change fp->_bf._base.
+        */
+dumb:
+       if (__sflush(fp) ||
+           (*seekfn)(fp->_cookie, (fpos_t)offset, whence) == POS_ERR) {
+               FUNLOCKFILE(fp);
+               return (-1);
+       }
+       /* success: clear EOF indicator and discard ungetc() data */
+       if (HASUB(fp))
+               FREEUB(fp);
+       fp->_p = fp->_bf._base;
+       fp->_r = 0;
+       /* fp->_w = 0; */       /* unnecessary (I think...) */
+       fp->_flags &= ~__SEOF;
+       FUNLOCKFILE(fp);
+       return (0);
+}
diff --git a/lib/nbsd_libc/stdio/fsetpos.c b/lib/nbsd_libc/stdio/fsetpos.c
new file mode 100644 (file)
index 0000000..6fbd3e2
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: fsetpos.c,v 1.10 2003/08/07 16:43:25 agc Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fsetpos.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fsetpos.c,v 1.10 2003/08/07 16:43:25 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+
+/*
+ * fsetpos: like fseek.
+ */
+int
+fsetpos(iop, pos)
+       FILE *iop;
+       const fpos_t *pos;
+{
+       _DIAGASSERT(iop != NULL);
+       _DIAGASSERT(pos != NULL);
+
+       return (fseeko(iop, (off_t)*pos, SEEK_SET));
+}
diff --git a/lib/nbsd_libc/stdio/ftell.c b/lib/nbsd_libc/stdio/ftell.c
new file mode 100644 (file)
index 0000000..828a23a
--- /dev/null
@@ -0,0 +1,107 @@
+/*     $NetBSD: ftell.c,v 1.17 2010/10/24 17:44:32 tron Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ftell.c    8.2 (Berkeley) 5/4/95";
+#else
+__RCSID("$NetBSD: ftell.c,v 1.17 2010/10/24 17:44:32 tron Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * ftell: return current offset.
+ */
+long
+ftell(fp)
+       FILE *fp;
+{
+       fpos_t pos;
+
+
+       FLOCKFILE(fp);
+
+       if (fp->_seek == NULL) {
+               FUNLOCKFILE(fp);
+               errno = ESPIPE;                 /* historic practice */
+               return -1L;
+       }
+
+       /*
+        * Find offset of underlying I/O object, then
+        * adjust for buffered bytes.
+        */
+       __sflush(fp);           /* may adjust seek offset on append stream */
+       if (fp->_flags & __SOFF)
+               pos = fp->_offset;
+       else {
+               pos = (*fp->_seek)(fp->_cookie, (fpos_t)0, SEEK_CUR);
+               if (pos == -1L) {
+                       FUNLOCKFILE(fp);
+                       return (long)(pos);
+               }
+       }
+       if (fp->_flags & __SRD) {
+               /*
+                * Reading.  Any unread characters (including
+                * those from ungetc) cause the position to be
+                * smaller than that in the underlying object.
+                */
+               pos -= fp->_r;
+               if (HASUB(fp))
+                       pos -= fp->_ur;
+       } else if (fp->_flags & __SWR && fp->_p != NULL) {
+               /*
+                * Writing.  Any buffered characters cause the
+                * position to be greater than that in the
+                * underlying object.
+                */
+               pos += fp->_p - fp->_bf._base;
+       }
+       FUNLOCKFILE(fp);
+
+       if (__fpos_overflow(pos)) {
+               errno = EOVERFLOW;
+               return -1L;
+       }
+               
+       return (long)(pos);
+}
diff --git a/lib/nbsd_libc/stdio/ftello.c b/lib/nbsd_libc/stdio/ftello.c
new file mode 100644 (file)
index 0000000..6c1bd1a
--- /dev/null
@@ -0,0 +1,102 @@
+/*     $NetBSD: ftello.c,v 1.4 2003/08/07 16:43:26 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ftello.c,v 1.4 2003/08/07 16:43:26 agc Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(ftello, _ftello)
+#endif
+
+/*
+ * ftell: return current offset.
+ */
+off_t
+ftello(fp)
+       FILE *fp;
+{
+       fpos_t pos;
+
+
+       FLOCKFILE(fp);
+
+       if (fp->_seek == NULL) {
+               FUNLOCKFILE(fp);
+               errno = ESPIPE;                 /* historic practice */
+               return ((off_t)-1);
+       }
+
+       /*
+        * Find offset of underlying I/O object, then
+        * adjust for buffered bytes.
+        */
+       __sflush(fp);           /* may adjust seek offset on append stream */
+       if (fp->_flags & __SOFF)
+               pos = fp->_offset;
+       else {
+               pos = (*fp->_seek)(fp->_cookie, (fpos_t)0, SEEK_CUR);
+               if (pos == (fpos_t)-1) {
+                       FUNLOCKFILE(fp);
+                       return (pos);
+               }
+       }
+       if (fp->_flags & __SRD) {
+               /*
+                * Reading.  Any unread characters (including
+                * those from ungetc) cause the position to be
+                * smaller than that in the underlying object.
+                */
+               pos -= fp->_r;
+               if (HASUB(fp))
+                       pos -= fp->_ur;
+       } else if (fp->_flags & __SWR && fp->_p != NULL) {
+               /*
+                * Writing.  Any buffered characters cause the
+                * position to be greater than that in the
+                * underlying object.
+                */
+               pos += fp->_p - fp->_bf._base;
+       }
+       FUNLOCKFILE(fp);
+       return (pos);
+}
diff --git a/lib/nbsd_libc/stdio/funopen.3 b/lib/nbsd_libc/stdio/funopen.3
new file mode 100644 (file)
index 0000000..376a561
--- /dev/null
@@ -0,0 +1,175 @@
+.\"    $NetBSD: funopen.3,v 1.15 2010/03/22 19:30:54 joerg Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\" 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. 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.
+.\"
+.\"     @(#)funopen.3  8.1 (Berkeley) 6/9/93
+.\"
+.Dd June 9, 1993
+.Dt FUNOPEN 3
+.Os
+.Sh NAME
+.Nm funopen ,
+.Nm fropen ,
+.Nm fwopen
+.Nd open a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft FILE *
+.Fn funopen "void  *cookie" "int  (*readfn)(void *, char *, int)" "int (*writefn)(void *, const char *, int)" "fpos_t (*seekfn)(void *, fpos_t, int)" "int (*closefn)(void *)"
+.Ft FILE *
+.Fn fropen "void  *cookie" "int  (*readfn)(void *, char *, int)"
+.Ft FILE *
+.Fn fwopen "void  *cookie" "int  (*writefn)(void *, const char *, int)"
+.Sh DESCRIPTION
+The
+.Fn funopen
+function
+associates a stream with up to four
+.Dq Tn I/O No functions .
+Either
+.Fa readfn
+or
+.Fa writefn
+must be specified;
+the others can be given as an appropriately-typed
+.Dv NULL
+pointer.
+These
+.Tn I/O
+functions will be used to read, write, seek and
+close the new stream.
+.Pp
+In general, omitting a function means that any attempt to perform the
+associated operation on the resulting stream will fail.
+If the close function is omitted, closing the stream will flush
+any buffered output and then succeed.
+.Pp
+The calling conventions of
+.Fa readfn ,
+.Fa writefn ,
+.Fa seekfn
+and
+.Fa closefn
+must match those, respectively, of
+.Xr read 2 ,
+.Xr write 2 ,
+.Xr lseek 2 ,
+and
+.Xr close 2 ;
+except that they are passed the
+.Fa cookie
+argument specified to
+.Fn funopen
+in place of the traditional file descriptor argument,
+and
+.Fa seekfn
+uses
+.Li fpos_t
+instead of
+.Li off_t .
+.Pp
+Read and write
+.Tn I/O
+functions are allowed to change the underlying buffer
+on fully buffered or line buffered streams by calling
+.Xr setvbuf 3 .
+They are also not required to completely fill or empty the buffer.
+They are not, however, allowed to change streams from unbuffered to buffered
+or to change the state of the line buffering flag.
+They must also be prepared to have read or write calls occur on buffers other
+than the one most recently specified.
+.Pp
+All user
+.Tn I/O
+functions can report an error by returning \-1.
+Additionally, all of the functions should set the external variable
+.Va errno
+appropriately if an error occurs.
+.Pp
+An error on
+.Fn closefn
+does not keep the stream open.
+.Pp
+As a convenience, the include file
+.In stdio.h
+defines the macros
+.Fn fropen
+and
+.Fn fwopen
+as calls to
+.Fn funopen
+with only a read or write function specified.
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn funopen
+returns a
+.Dv FILE
+pointer.
+Otherwise,
+.Dv NULL
+is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fn funopen
+function
+was called without either a read or write function.
+The
+.Fn funopen
+function
+may also fail and set
+.Va errno
+for any of the errors
+specified for the routine
+.Xr malloc 3 .
+.El
+.Sh SEE ALSO
+.Xr fcntl 2 ,
+.Xr open 2 ,
+.Xr fclose 3 ,
+.Xr fopen 3 ,
+.Xr fseek 3 ,
+.Xr setbuf 3
+.Sh HISTORY
+The
+.Fn funopen
+functions first appeared in
+.Bx 4.4 .
+.Sh BUGS
+The
+.Fn funopen
+function
+may not be portable to systems other than
+.Bx .
diff --git a/lib/nbsd_libc/stdio/funopen.c b/lib/nbsd_libc/stdio/funopen.c
new file mode 100644 (file)
index 0000000..c308d90
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: funopen.c,v 1.10 2005/11/29 03:12:00 christos Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)funopen.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: funopen.c,v 1.10 2005/11/29 03:12:00 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdio.h>
+#include <errno.h>
+#include "reentrant.h"
+#include "local.h"
+
+FILE *
+funopen(cookie, readfn, writefn, seekfn, closefn)
+       const void *cookie;
+       int (*readfn) __P((void *, char *, int));
+       int (*writefn) __P((void *, const char *, int));
+       fpos_t (*seekfn) __P((void *, fpos_t, int));
+       int (*closefn) __P((void *));
+{
+       FILE *fp;
+       int flags;
+
+       if (readfn == NULL) {
+               if (writefn == NULL) {          /* illegal */
+                       errno = EINVAL;
+                       return (NULL);
+               } else
+                       flags = __SWR;          /* write only */
+       } else {
+               if (writefn == NULL)
+                       flags = __SRD;          /* read only */
+               else
+                       flags = __SRW;          /* read-write */
+       }
+       if ((fp = __sfp()) == NULL)
+               return (NULL);
+       fp->_flags = flags;
+       fp->_file = -1;
+       fp->_cookie = __UNCONST(cookie);
+       fp->_read = readfn;
+       fp->_write = writefn;
+       fp->_seek = seekfn;
+       fp->_close = closefn;
+       return (fp);
+}
diff --git a/lib/nbsd_libc/stdio/fvwrite.c b/lib/nbsd_libc/stdio/fvwrite.c
new file mode 100644 (file)
index 0000000..557b3b3
--- /dev/null
@@ -0,0 +1,227 @@
+/*     $NetBSD: fvwrite.c,v 1.21 2009/10/25 20:44:13 christos Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fvwrite.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fvwrite.c,v 1.21 2009/10/25 20:44:13 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "reentrant.h"
+#include "local.h"
+#include "fvwrite.h"
+
+/*
+ * Write some memory regions.  Return zero on success, EOF on error.
+ *
+ * This routine is large and unsightly, but most of the ugliness due
+ * to the three different kinds of output buffering is handled here.
+ */
+int
+__sfvwrite(fp, uio)
+       FILE *fp;
+       struct __suio *uio;
+{
+       int len;
+       char *p;
+       struct __siov *iov;
+       int w, s;
+       char *nl;
+       int nlknown, nldist;
+
+       _DIAGASSERT(fp != NULL);
+       _DIAGASSERT(uio != NULL);
+
+       if ((int)uio->uio_resid < 0) {
+               errno = EINVAL;
+               return (EOF);
+       }
+       if ((len = uio->uio_resid) == 0)
+               return (0);
+       /* make sure we can write */
+       if (cantwrite(fp)) {
+               errno = EBADF;
+               return (EOF);
+       }
+
+#define        MIN(a, b) ((a) < (b) ? (a) : (b))
+#define        COPY(n)   (void)memcpy(fp->_p, p, (size_t)(n))
+
+       iov = uio->uio_iov;
+       p = iov->iov_base;
+       len = iov->iov_len;
+       iov++;
+#define GETIOV(extra_work) \
+       while (len == 0) { \
+               extra_work; \
+               p = iov->iov_base; \
+               len = iov->iov_len; \
+               iov++; \
+       }
+       if (fp->_flags & __SNBF) {
+               /*
+                * Unbuffered: write up to BUFSIZ bytes at a time.
+                */
+               do {
+                       GETIOV(;);
+                       w = (*fp->_write)(fp->_cookie, p,
+                           (int)MIN(len, BUFSIZ));
+                       if (w <= 0)
+                               goto err;
+                       p += w;
+                       len -= w;
+               } while ((uio->uio_resid -= w) != 0);
+       } else if ((fp->_flags & __SLBF) == 0) {
+               /*
+                * Fully buffered: fill partially full buffer, if any,
+                * and then flush.  If there is no partial buffer, write
+                * one _bf._size byte chunk directly (without copying).
+                *
+                * String output is a special case: write as many bytes
+                * as fit, but pretend we wrote everything.  This makes
+                * snprintf() return the number of bytes needed, rather
+                * than the number used, and avoids its write function
+                * (so that the write function can be invalid).
+                */
+               do {
+                       GETIOV(;);
+                       if ((fp->_flags & (__SALC | __SSTR)) ==
+                           (__SALC | __SSTR) && fp->_w < len) {
+                               int blen = fp->_p - fp->_bf._base;
+                               unsigned char *_base;
+                               int _size;
+
+                               /* Allocate space exponentially. */
+                               _size = fp->_bf._size;
+                               do {
+                                       _size = (_size << 1) + 1;
+                               } while (_size < blen + len);
+                               _base = realloc(fp->_bf._base,
+                                   (size_t)(_size + 1));
+                               if (_base == NULL)
+                                       goto err;
+                               fp->_w += _size - fp->_bf._size;
+                               fp->_bf._base = _base;
+                               fp->_bf._size = _size;
+                               fp->_p = _base + blen;
+                       }
+                       w = fp->_w;
+                       if (fp->_flags & __SSTR) {
+                               if (len < w)
+                                       w = len;
+                               COPY(w);        /* copy MIN(fp->_w,len), */
+                               fp->_w -= w;
+                               fp->_p += w;
+                               w = len;        /* but pretend copied all */
+                       } else if (fp->_p > fp->_bf._base && len > w) {
+                               /* fill and flush */
+                               COPY(w);
+                               /* fp->_w -= w; */ /* unneeded */
+                               fp->_p += w;
+                               if (fflush(fp))
+                                       goto err;
+                       } else if (len >= (w = fp->_bf._size)) {
+                               /* write directly */
+                               w = (*fp->_write)(fp->_cookie, p, w);
+                               if (w <= 0)
+                                       goto err;
+                       } else {
+                               /* fill and done */
+                               w = len;
+                               COPY(w);
+                               fp->_w -= w;
+                               fp->_p += w;
+                       }
+                       p += w;
+                       len -= w;
+               } while ((uio->uio_resid -= w) != 0);
+       } else {
+               /*
+                * Line buffered: like fully buffered, but we
+                * must check for newlines.  Compute the distance
+                * to the first newline (including the newline),
+                * or `infinity' if there is none, then pretend
+                * that the amount to write is MIN(len,nldist).
+                */
+               nlknown = 0;
+               nldist = 0;     /* XXX just to keep gcc happy */
+               do {
+                       GETIOV(nlknown = 0);
+                       if (!nlknown) {
+                               nl = memchr(p, '\n', (size_t)len);
+                               nldist = nl ? nl + 1 - p : len + 1;
+                               nlknown = 1;
+                       }
+                       s = MIN(len, nldist);
+                       w = fp->_w + fp->_bf._size;
+                       if (fp->_p > fp->_bf._base && s > w) {
+                               COPY(w);
+                               /* fp->_w -= w; */
+                               fp->_p += w;
+                               if (fflush(fp))
+                                       goto err;
+                       } else if (s >= (w = fp->_bf._size)) {
+                               w = (*fp->_write)(fp->_cookie, p, w);
+                               if (w <= 0)
+                                       goto err;
+                       } else {
+                               w = s;
+                               COPY(w);
+                               fp->_w -= w;
+                               fp->_p += w;
+                       }
+                       if ((nldist -= w) == 0) {
+                               /* copied the newline: flush and forget */
+                               if (fflush(fp))
+                                       goto err;
+                               nlknown = 0;
+                       }
+                       p += w;
+                       len -= w;
+               } while ((uio->uio_resid -= w) != 0);
+       }
+       return (0);
+
+err:
+       fp->_flags |= __SERR;
+       return (EOF);
+}
diff --git a/lib/nbsd_libc/stdio/fvwrite.h b/lib/nbsd_libc/stdio/fvwrite.h
new file mode 100644 (file)
index 0000000..844d9ab
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: fvwrite.h,v 1.7 2003/08/07 16:43:26 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ *
+ *     @(#)fvwrite.h   8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * I/O descriptors for __sfvwrite().
+ */
+struct __siov {
+       void    *iov_base;
+       size_t  iov_len;
+};
+struct __suio {
+       struct  __siov *uio_iov;
+       int     uio_iovcnt;
+       int     uio_resid;
+};
+
+extern int __sfvwrite(FILE *, struct __suio *);
diff --git a/lib/nbsd_libc/stdio/fwalk.c b/lib/nbsd_libc/stdio/fwalk.c
new file mode 100644 (file)
index 0000000..b06edd1
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: fwalk.c,v 1.11 2003/08/07 16:43:26 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fwalk.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fwalk.c,v 1.11 2003/08/07 16:43:26 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+#include "glue.h"
+
+int
+_fwalk(function)
+       int (*function) __P((FILE *));
+{
+       FILE *fp;
+       int n, ret;
+       struct glue *g;
+
+       _DIAGASSERT(function != NULL);
+
+       ret = 0;
+       for (g = &__sglue; g != NULL; g = g->next)
+               for (fp = g->iobs, n = g->niobs; --n >= 0; fp++)
+                       if (fp->_flags != 0)
+                               ret |= (*function)(fp);
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/fwide.3 b/lib/nbsd_libc/stdio/fwide.3
new file mode 100644 (file)
index 0000000..62bc368
--- /dev/null
@@ -0,0 +1,94 @@
+.\"    $NetBSD: fwide.3,v 1.6 2003/09/08 17:54:32 wiz Exp $
+.\"
+.\" Copyright (c)2001 Citrus Project,
+.\" 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.
+.\"
+.\" $Citrus: xpg4dl/FreeBSD/lib/libc/stdio/fwide.3,v 1.2 2001/12/07 04:47:08 yamt Exp $
+.\"
+.Dd October 24, 2001
+.Dt FWIDE 3
+.Os
+.Sh NAME
+.Nm fwide
+.Nd get/set orientation of a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.In wchar.h
+.Ft int
+.Fn fwide "FILE *stream" "int mode"
+.Sh DESCRIPTION
+The
+.Fn fwide
+function
+determines the orientation of the stream pointed at by
+.Fa stream .
+.Pp
+If the orientation of
+.Fa stream
+has already been determined,
+.Fn fwide
+leaves it unchanged.
+Otherwise,
+.Fn fwide
+sets the orientation of
+.Fa stream
+according to
+.Fa mode .
+.Pp
+If
+.Fa mode
+is less than zero,
+.Fa stream
+is set to byte-oriented.
+If it is greater than zero,
+.Fa stream
+is set to wide-oriented.
+Otherwise,
+.Fa mode
+is zero, and
+.Fa stream
+is unchanged.
+.Sh RETURN VALUES
+.Fn fwide
+returns a value according to orientation after the call of
+.Fn fwide ;
+a value less than zero if byte-oriented, a value greater than zero
+if wide-oriented, and zero if the stream has no orientation.
+.Sh SEE ALSO
+.Xr ferror 3 ,
+.Xr fgetc 3 ,
+.Xr fgetwc 3 ,
+.Xr fopen 3 ,
+.Xr fputc 3 ,
+.Xr fputwc 3 ,
+.Xr freopen 3 ,
+.Xr stdio 3
+.Sh STANDARDS
+The
+.Fn fwide
+function
+conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/stdio/fwide.c b/lib/nbsd_libc/stdio/fwide.c
new file mode 100644 (file)
index 0000000..daa6d1d
--- /dev/null
@@ -0,0 +1,72 @@
+/* $NetBSD: fwide.c,v 1.3 2005/06/12 05:21:27 lukem Exp $ */
+
+/*-
+ * Copyright (c)2001 Citrus Project,
+ * 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.
+ *
+ * $Citrus$
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: fwide.c,v 1.3 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <stdio.h>
+#include <wchar.h>
+#include "reentrant.h"
+#include "local.h"
+
+int
+fwide(FILE *fp, int mode)
+{
+       struct wchar_io_data *wcio;
+
+       _DIAGASSERT(fp != NULL);
+
+       /*
+        * this implementation use only -1, 0, 1
+        * for mode value.
+        * (we don't need to do this, but
+        *  this can make things simpler.)
+        */
+       if (mode > 0)
+               mode = 1;
+       else if (mode < 0)
+               mode = -1;
+
+       FLOCKFILE(fp);
+       wcio = WCIO_GET(fp);
+       if (!wcio)
+               return 0; /* XXX */
+
+       if (wcio->wcio_mode == 0 && mode != 0)
+               wcio->wcio_mode = mode;
+       else
+               mode = wcio->wcio_mode;
+       FUNLOCKFILE(fp);
+
+       return mode;
+}
diff --git a/lib/nbsd_libc/stdio/fwprintf.c b/lib/nbsd_libc/stdio/fwprintf.c
new file mode 100644 (file)
index 0000000..5360687
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: fwprintf.c,v 1.1 2005/05/14 23:51:02 christos Exp $    */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/stdio/fwprintf.c,v 1.1 2002/09/21 13:00:30 tjr Exp $");
+#else
+__RCSID("$NetBSD: fwprintf.c,v 1.1 2005/05/14 23:51:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <wchar.h>
+
+int
+fwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt, ...)
+{
+       int ret;
+       va_list ap;
+
+       va_start(ap, fmt);
+       ret = vfwprintf(fp, fmt, ap);
+       va_end(ap);
+
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/fwrite.c b/lib/nbsd_libc/stdio/fwrite.c
new file mode 100644 (file)
index 0000000..c48a47c
--- /dev/null
@@ -0,0 +1,88 @@
+/*     $NetBSD: fwrite.c,v 1.16 2005/11/29 03:12:00 christos Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)fwrite.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: fwrite.c,v 1.16 2005/11/29 03:12:00 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+#include "fvwrite.h"
+
+/*
+ * Write `count' objects (each size `size') from memory to the given file.
+ * Return the number of whole objects written.
+ */
+size_t
+fwrite(buf, size, count, fp)
+       const void *buf;
+       size_t size, count;
+       FILE *fp;
+{
+       size_t n;
+       struct __suio uio;
+       struct __siov iov;
+
+       _DIAGASSERT(fp != NULL);
+       /*
+        * SUSv2 requires a return value of 0 for a count or a size of 0.
+        */
+       if ((n = count * size) == 0)
+               return (0);
+       _DIAGASSERT(buf != NULL);
+
+       iov.iov_base = __UNCONST(buf);
+       uio.uio_resid = iov.iov_len = n;
+       uio.uio_iov = &iov;
+       uio.uio_iovcnt = 1;
+
+       /*
+        * The usual case is success (__sfvwrite returns 0);
+        * skip the divide if this happens, since divides are
+        * generally slow and since this occurs whenever size==0.
+        */
+       FLOCKFILE(fp);
+       if (__sfvwrite(fp, &uio) != 0)
+               count = ((n - uio.uio_resid) / size);
+       FUNLOCKFILE(fp);
+       return (count);
+}
diff --git a/lib/nbsd_libc/stdio/fwscanf.c b/lib/nbsd_libc/stdio/fwscanf.c
new file mode 100644 (file)
index 0000000..4595c33
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: fwscanf.c,v 1.1 2005/05/14 23:51:02 christos Exp $     */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/stdio/fwscanf.c,v 1.1 2002/09/23 12:40:06 tjr Exp $");
+#else
+__RCSID("$NetBSD: fwscanf.c,v 1.1 2005/05/14 23:51:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <wchar.h>
+
+int
+fwscanf(FILE * __restrict fp, const wchar_t * __restrict fmt, ...)
+{
+       va_list ap;
+       int r;
+
+       va_start(ap, fmt);
+       r = vfwscanf(fp, fmt, ap);
+       va_end(ap);
+
+       return (r);
+}
diff --git a/lib/nbsd_libc/stdio/getc.3 b/lib/nbsd_libc/stdio/getc.3
new file mode 100644 (file)
index 0000000..e070744
--- /dev/null
@@ -0,0 +1,170 @@
+.\"    $NetBSD: getc.3,v 1.12 2003/08/07 16:43:26 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)getc.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 25, 2001
+.Dt GETC 3
+.Os
+.Sh NAME
+.Nm fgetc ,
+.Nm getc ,
+.Nm getchar ,
+.Nm getc_unlocked ,
+.Nm getchar_unlocked ,
+.Nm getw
+.Nd get next character or word from input stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft int
+.Fn fgetc "FILE *stream"
+.Ft int
+.Fn getc "FILE *stream"
+.Ft int
+.Fn getchar
+.Ft int
+.Fn getc_unlocked "FILE *stream"
+.Ft int
+.Fn getchar_unlocked
+.Ft int
+.Fn getw "FILE *stream"
+.Sh DESCRIPTION
+The
+.Fn fgetc
+function
+obtains the next input character (if present) from the stream pointed at by
+.Fa stream ,
+or the next character pushed back on the stream via
+.Xr ungetc 3 .
+.Pp
+The
+.Fn getc
+function
+acts essentially identically to
+.Fn fgetc ,
+but is a macro that expands in-line.
+.Pp
+The
+.Fn getchar
+function
+is equivalent to:
+getc with the argument stdin.
+.Pp
+The
+.Fn getc_unlocked
+and
+.Fn getchar_unlocked
+functions provide functionality identical to that of
+.Fn getc
+and
+.Fn getchar ,
+respectively, but do not perform implicit locking of the streams they
+operate on.
+In multi-threaded programs they may be used
+.Em only
+within a scope in which the stream
+has been successfully locked by the calling thread using either
+.Xr flockfile 3
+or
+.Xr ftrylockfile 3 ,
+and may later be released using
+.Xr funlockfile 3 .
+.Pp
+The
+.Fn getw
+function
+obtains the next
+.Em int
+(if present)
+from the stream pointed at by
+.Fa stream .
+.Sh RETURN VALUES
+If successful, these routines return the next requested object
+from the
+.Fa stream .
+If the stream is at end-of-file or a read error occurs,
+the routines return
+.Dv EOF .
+The routines
+.Xr feof 3
+and
+.Xr ferror 3
+must be used to distinguish between end-of-file and error.
+If an error occurs, the global variable
+.Va errno
+is set to indicate the error.
+The end-of-file condition is remembered, even on a terminal, and all
+subsequent attempts to read will return
+.Dv EOF
+until the condition is cleared with
+.Xr clearerr 3 .
+.Sh SEE ALSO
+.Xr ferror 3 ,
+.Xr flockfile 3 ,
+.Xr fopen 3 ,
+.Xr fread 3 ,
+.Xr ftrylockfile 3 ,
+.Xr funlockfile 3 ,
+.Xr putc 3 ,
+.Xr ungetc 3
+.Sh STANDARDS
+The
+.Fn fgetc ,
+.Fn getc
+and
+.Fn getchar
+functions
+conform to
+.St -ansiC .
+The
+.Fn getc_unlocked
+and
+.Fn getchar_unlocked
+functions conform to
+.St -p1003.1-96 .
+.Sh BUGS
+Since
+.Dv EOF
+is a valid integer value,
+.Xr feof 3
+and
+.Xr ferror 3
+must be used to check for failure after calling
+.Fn getw .
+The size and byte order of an
+.Em int
+varies from one machine to another, and
+.Fn getw
+is not recommended for portable applications.
diff --git a/lib/nbsd_libc/stdio/getc.c b/lib/nbsd_libc/stdio/getc.c
new file mode 100644 (file)
index 0000000..55bef64
--- /dev/null
@@ -0,0 +1,78 @@
+/*     $NetBSD: getc.c,v 1.11 2003/08/07 16:43:26 agc Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getc.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getc.c,v 1.11 2003/08/07 16:43:26 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * A subroutine version of the macro getc.
+ */
+#undef getc
+#undef getc_unlocked
+
+int
+getc(fp)
+       FILE *fp;
+{
+       int r;
+
+       _DIAGASSERT(fp != NULL);
+
+       FLOCKFILE(fp);
+       r = __sgetc(fp);
+       FUNLOCKFILE(fp);
+       return r;
+}
+
+int
+getc_unlocked(fp)
+       FILE *fp;
+{
+
+       _DIAGASSERT(fp != NULL);
+
+       return (__sgetc(fp));
+}
diff --git a/lib/nbsd_libc/stdio/getchar.c b/lib/nbsd_libc/stdio/getchar.c
new file mode 100644 (file)
index 0000000..75cae92
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: getchar.c,v 1.9 2003/08/07 16:43:27 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getchar.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getchar.c,v 1.9 2003/08/07 16:43:27 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * A subroutine version of the macro getchar.
+ */
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+#undef getchar
+#undef getchar_unlocked
+
+int
+getchar()
+{
+       FILE *fp = stdin;
+       int r;
+
+        FLOCKFILE(fp);
+        r = __sgetc(fp);
+        FUNLOCKFILE(fp);
+        return r;
+}
+
+int
+getchar_unlocked()
+{
+       return (__sgetc(stdin));
+}
diff --git a/lib/nbsd_libc/stdio/getdelim.3 b/lib/nbsd_libc/stdio/getdelim.3
new file mode 100644 (file)
index 0000000..121c96d
--- /dev/null
@@ -0,0 +1,153 @@
+.\"     $NetBSD: getdelim.3,v 1.8 2010/06/30 13:38:10 jruoho Exp $
+.\"
+.\" Copyright (c) 2009 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Roy Marples.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd June 30, 2010
+.Dt GETDELIM 3
+.Os
+.Sh NAME
+.Nm getdelim ,
+.Nm getline
+.Nd read a delimited record from a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft ssize_t
+.Fn getdelim "char ** restrict lineptr" "size_t * restrict n" "int delimiter" "FILE * restrict stream"
+.Ft ssize_t
+.Fn getline "char ** restrict lineptr" "size_t * restrict n" "FILE * restrict stream"
+.Sh DESCRIPTION
+The
+.Fn getdelim
+function reads from the
+.Fa stream
+until it encounters a character matching
+.Fa delimiter ,
+storing the input in
+.Fa *lineptr .
+The buffer is
+.Dv NUL Ns No -terminated
+and includes the delimiter.
+The
+.Fa delimiter
+character must be representable as an unsigned char.
+.Pp
+If
+.Fa *n
+is non-zero, then
+.Fa *lineptr
+must be pre-allocated to at least
+.Fa *n
+bytes.
+The buffer should be allocated dynamically;
+it must be possible to
+.Xr free 3
+.Fa *lineptr .
+.Fn getdelim
+ensures that
+.Fa *lineptr
+is large enough to hold the input, updating
+.Fa *n
+to reflect the new size.
+.Pp
+The
+.Fn getline
+function is equivalent to
+.Fn getdelim
+with
+.Fa delimiter
+set to the newline character.
+.Sh RETURN VALUES
+The
+.Fn getdelim
+and
+.Fn getline
+functions return the number of characters read, including the delimiter.
+If no characters were read and the stream is at end-of-file, the functions
+return \-1.
+If an error occurs, the functions return \-1 and the global variable
+.Va errno
+is set to indicate the error.
+.Pp
+The functions do not distinguish between end-of-file and error,
+and callers must use
+.Xr feof 3
+and
+.Xr ferror 3
+to determine which occurred.
+.Sh EXAMPLES
+The following code fragment reads lines from a file and writes them to
+standard output.
+.Bd -literal -offset indent
+char *line = NULL;
+size_t linesize = 0;
+ssize_t linelen;
+while ((linelen = getline(\*[Am]line, \*[Am]linesize, fp)) != -1)
+       fwrite(line, linelen, 1, stdout);
+
+if (ferror(fp))
+       perror("getline");
+.Ed
+.Sh ERRORS
+.Bl -tag -width [EOVERFLOW]
+.It Bq Er EINVAL
+.Fa *lineptr
+or
+.Fa *n
+is a
+.Dv NULL
+pointer.
+.It Bq Er EOVERFLOW
+More than SSIZE_MAX characters were read without encountering the delimiter.
+.El
+.Pp
+The
+.Fn getdelim
+and
+.Fn getline
+functions may also fail and set
+.Va errno
+for any of the errors specified in the routines
+.Xr fflush 3 ,
+.Xr malloc 3 ,
+.Xr read 2 ,
+.Xr stat 2 ,
+or
+.Xr realloc 3 .
+.Sh SEE ALSO
+.Xr ferror 3 ,
+.Xr fgets 3 ,
+.Xr fopen 3
+.Sh STANDARDS
+The
+.Fn getdelim
+and
+.Fn getline
+functions conform to
+.St -p1003.1-2008 .
diff --git a/lib/nbsd_libc/stdio/getdelim.c b/lib/nbsd_libc/stdio/getdelim.c
new file mode 100644 (file)
index 0000000..c3ab877
--- /dev/null
@@ -0,0 +1,154 @@
+/* $NetBSD: getdelim.c,v 1.12 2009/12/07 21:31:43 roy Exp $ */
+
+/*
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Roy Marples.
+ *
+ * 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 ``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 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 <sys/cdefs.h>
+__RCSID("$NetBSD: getdelim.c,v 1.12 2009/12/07 21:31:43 roy Exp $");
+
+#include "namespace.h"
+
+#include <sys/param.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(getdelim, _getdelim)
+#endif
+
+/* Minimum buffer size we create.
+ * This should allow config files to fit into our power of 2 buffer growth
+ * without the need for a realloc. */
+#define MINBUF 128
+
+ssize_t
+__getdelim(char **__restrict buf, size_t *__restrict buflen,
+    int sep, FILE *__restrict fp)
+{
+       unsigned char *p;
+       size_t len, newlen, off;
+       char *newb;
+
+       _DIAGASSERT(fp != NULL);
+
+       if (buf == NULL || buflen == NULL) {
+               errno = EINVAL;
+               return -1;
+       }
+
+       /* If buf is NULL, we have to assume a size of zero */
+       if (*buf == NULL)
+               *buflen = 0;
+
+       _SET_ORIENTATION(fp, -1);
+       off = 0;
+       do {
+               /* If the input buffer is empty, refill it */
+               if (fp->_r <= 0 && __srefill(fp)) {
+                       if (__sferror(fp))
+                               goto error;
+                       /* No error, so EOF. */
+                       break;
+               }
+
+               /* Scan through looking for the separator */
+               p = memchr(fp->_p, sep, (size_t)fp->_r);
+               if (p == NULL)
+                       len = fp->_r;
+               else
+                       len = (p - fp->_p) + 1;
+
+               newlen = off + len;
+               /* Ensure we can handle it */
+               if (newlen < off || newlen > SSIZE_MAX) {
+                       errno = EOVERFLOW;
+                       goto error;
+               }
+               newlen++; /* reserve space for the NULL terminator */
+               if (newlen > *buflen) {
+                       if (newlen < MINBUF)
+                               newlen = MINBUF;
+                       if (!powerof2(newlen)) {
+                               /* Grow the buffer to the next power of 2 */
+                               newlen--;
+                               newlen |= newlen >> 1;
+                               newlen |= newlen >> 2;
+                               newlen |= newlen >> 4;
+                               newlen |= newlen >> 8;
+                               newlen |= newlen >> 16;
+#if SIZE_T_MAX > 0xffffffffU
+                               newlen |= newlen >> 32;
+#endif
+                               newlen++;
+                       }
+
+                       newb = realloc(*buf, newlen);
+                       if (newb == NULL)
+                               goto error;
+                       *buf = newb;
+                       *buflen = newlen;
+               }
+
+               (void)memcpy((*buf + off), fp->_p, len);
+               /* Safe, len is never greater than what fp->_r can fit. */
+               fp->_r -= (int)len;
+               fp->_p += (int)len;
+               off += len;
+       } while (p == NULL);
+
+       /* POSIX demands we return -1 on EOF. */
+       if (off == 0) 
+               return -1;
+
+       if (*buf != NULL)
+               *(*buf + off) = '\0';
+       return off;
+
+error:
+       fp->_flags |= __SERR;
+       return -1;
+}
+
+ssize_t
+getdelim(char **__restrict buf, size_t *__restrict buflen,
+    int sep, FILE *__restrict fp)
+{
+       ssize_t n;
+
+       FLOCKFILE(fp);
+       n = __getdelim(buf, buflen, sep, fp);
+       FUNLOCKFILE(fp);
+       return n;
+}
diff --git a/lib/nbsd_libc/stdio/getline.c b/lib/nbsd_libc/stdio/getline.c
new file mode 100644 (file)
index 0000000..e5d4bab
--- /dev/null
@@ -0,0 +1,45 @@
+/* $NetBSD: getline.c,v 1.3 2009/12/02 08:46:33 roy Exp $ */
+
+/*
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Roy Marples.
+ *
+ * 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 ``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 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 <sys/cdefs.h>
+__RCSID("$NetBSD: getline.c,v 1.3 2009/12/02 08:46:33 roy Exp $");
+
+#include "namespace.h"
+
+#include <stdio.h>
+
+#ifdef __weak_alias
+__weak_alias(getline, _getline)
+#endif
+
+ssize_t
+getline(char **__restrict buf, size_t *__restrict buflen, FILE *__restrict fp)
+{
+       return getdelim(buf, buflen, '\n', fp);
+}
diff --git a/lib/nbsd_libc/stdio/gets.c b/lib/nbsd_libc/stdio/gets.c
new file mode 100644 (file)
index 0000000..8526d8a
--- /dev/null
@@ -0,0 +1,80 @@
+/*     $NetBSD: gets.c,v 1.16 2007/06/03 17:39:26 christos Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)gets.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: gets.c,v 1.16 2007/06/03 17:39:26 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+#ifdef _FORTIFY_SOURCE
+#undef gets
+#endif
+
+__warn_references(gets, "warning: this program uses gets(), which is unsafe.")
+
+char *
+gets(buf)
+       char *buf;
+{
+       int c;
+       char *s;
+
+       _DIAGASSERT(buf != NULL);
+
+       FLOCKFILE(stdin);
+       for (s = buf; (c = getchar_unlocked()) != '\n'; ) {
+               if (c == EOF) {
+                       if (s == buf) {
+                               FUNLOCKFILE(stdin);
+                               return (NULL);
+                       } else {
+                               break;
+                       }
+               } else {
+                       *s++ = c;
+               }
+       }
+       *s = 0;
+       FUNLOCKFILE(stdin);
+       return (buf);
+}
diff --git a/lib/nbsd_libc/stdio/gettemp.c b/lib/nbsd_libc/stdio/gettemp.c
new file mode 100644 (file)
index 0000000..b5b8e93
--- /dev/null
@@ -0,0 +1,170 @@
+/*     $NetBSD: gettemp.c,v 1.14 2008/10/20 10:28:38 apb Exp $ */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#if !HAVE_NBTOOL_CONFIG_H || !HAVE_MKSTEMP || !HAVE_MKDTEMP
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)mktemp.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: gettemp.c,v 1.14 2008/10/20 10:28:38 apb Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#if HAVE_NBTOOL_CONFIG_H
+#define        GETTEMP         __nbcompat_gettemp
+#else
+#include "reentrant.h"
+#include "local.h"
+#define        GETTEMP         __gettemp
+#endif
+
+int
+GETTEMP(path, doopen, domkdir)
+       char *path;
+       int *doopen;
+       int domkdir;
+{
+       char *start, *trv;
+       struct stat sbuf;
+       u_int pid;
+
+       /* To guarantee multiple calls generate unique names even if
+          the file is not created. 676 different possibilities with 7
+          or more X's, 26 with 6 or less. */
+       static char xtra[2] = "aa";
+       int xcnt = 0;
+
+       _DIAGASSERT(path != NULL);
+       /* doopen may be NULL */
+
+       pid = getpid();
+
+       /* Move to end of path and count trailing X's. */
+       for (trv = path; *trv; ++trv)
+               if (*trv == 'X')
+                       xcnt++;
+               else
+                       xcnt = 0;       
+
+       /* Use at least one from xtra.  Use 2 if more than 6 X's. */
+       if (*(trv - 1) == 'X')
+               *--trv = xtra[0];
+       if (xcnt > 6 && *(trv - 1) == 'X')
+               *--trv = xtra[1];
+
+       /* Set remaining X's to pid digits with 0's to the left. */
+       while (*--trv == 'X') {
+               *trv = (pid % 10) + '0';
+               pid /= 10;
+       }
+
+       /* update xtra for next call. */
+       if (xtra[0] != 'z')
+               xtra[0]++;
+       else {
+               xtra[0] = 'a';
+               if (xtra[1] != 'z')
+                       xtra[1]++;
+               else
+                       xtra[1] = 'a';
+       }
+
+       /*
+        * check the target directory; if you have six X's and it
+        * doesn't exist this runs for a *very* long time.
+        */
+       for (start = trv + 1;; --trv) {
+               if (trv <= path)
+                       break;
+               if (*trv == '/') {
+                       *trv = '\0';
+                       if (stat(path, &sbuf))
+                               return (0);
+                       if (!S_ISDIR(sbuf.st_mode)) {
+                               errno = ENOTDIR;
+                               return (0);
+                       }
+                       *trv = '/';
+                       break;
+               }
+       }
+
+       for (;;) {
+               if (doopen) {
+                       if ((*doopen =
+                           open(path, O_CREAT | O_EXCL | O_RDWR, 0600)) >= 0)
+                               return (1);
+                       if (errno != EEXIST)
+                               return (0);
+               } else if (domkdir) {
+                       if (mkdir(path, 0700) >= 0)
+                               return (1);
+                       if (errno != EEXIST)
+                               return (0);
+               } else if (lstat(path, &sbuf))
+                       return (errno == ENOENT ? 1 : 0);
+
+               /* tricky little algorithm for backward compatibility */
+               for (trv = start;;) {
+                       if (!*trv)
+                               return (0);
+                       if (*trv == 'z')
+                               *trv++ = 'a';
+                       else {
+                               if (isdigit((unsigned char)*trv))
+                                       *trv = 'a';
+                               else
+                                       ++*trv;
+                               break;
+                       }
+               }
+       }
+       /*NOTREACHED*/
+}
+
+#endif /* !HAVE_NBTOOL_CONFIG_H || !HAVE_MKSTEMP || !HAVE_MKDTEMP */
diff --git a/lib/nbsd_libc/stdio/getw.c b/lib/nbsd_libc/stdio/getw.c
new file mode 100644 (file)
index 0000000..6ccd8ce
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: getw.c,v 1.9 2003/08/07 16:43:27 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getw.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getw.c,v 1.9 2003/08/07 16:43:27 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+
+int
+getw(fp)
+       FILE *fp;
+{
+       int x;
+
+       _DIAGASSERT(fp != NULL);
+
+       return (fread((void *)&x, sizeof(x), 1, fp) == 1 ? x : EOF);
+}
diff --git a/lib/nbsd_libc/stdio/getwc.3 b/lib/nbsd_libc/stdio/getwc.3
new file mode 100644 (file)
index 0000000..f8e7dd1
--- /dev/null
@@ -0,0 +1,114 @@
+.\"    $NetBSD: getwc.3,v 1.9 2010/12/16 17:42:27 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)getc.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 6, 2010
+.Dt GETWC 3
+.Os
+.Sh NAME
+.Nm fgetwc ,
+.Nm getwc ,
+.Nm getwchar ,
+.Nd get next wide character from input stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.In wchar.h
+.Ft wint_t
+.Fn fgetwc "FILE *stream"
+.Ft wint_t
+.Fn getwc "FILE *stream"
+.Ft wint_t
+.Fn getwchar
+.Sh DESCRIPTION
+The
+.Fn fgetwc
+function
+obtains the next input wide character (if present) from the stream pointed at by
+.Fa stream ,
+or the next character pushed back on the stream via
+.Xr ungetwc 3 .
+.Pp
+The
+.Fn getwc
+function
+acts essentially identically to
+.Fn fgetwc ,
+but is a macro that expands in-line.
+.Pp
+The
+.Fn getwchar
+function
+is equivalent to
+.Fn getwc
+with the argument stdin.
+.Sh RETURN VALUES
+If successful, these routines return the next wide character
+from the
+.Fa stream .
+If the stream is at end-of-file or a read error occurs,
+the routines return
+.Dv WEOF .
+The routines
+.Xr feof 3
+and
+.Xr ferror 3
+must be used to distinguish between end-of-file and error.
+If an error occurs, the global variable
+.Va errno
+is set to indicate the error.
+The end-of-file condition is remembered, even on a terminal, and all
+subsequent attempts to read will return
+.Dv WEOF
+until the condition is cleared with
+.Xr clearerr 3 .
+.Sh SEE ALSO
+.Xr ferror 3 ,
+.Xr fopen 3 ,
+.Xr fread 3 ,
+.Xr putwc 3 ,
+.Xr stdio 3 ,
+.Xr ungetwc 3
+.Sh STANDARDS
+The
+.Fn fgetwc ,
+.Fn getwc
+and
+.Fn getwchar
+functions
+conform to
+.St -isoC-99
+and
+.St -p1003.1-2001 .
diff --git a/lib/nbsd_libc/stdio/getwc.c b/lib/nbsd_libc/stdio/getwc.c
new file mode 100644 (file)
index 0000000..9557a6c
--- /dev/null
@@ -0,0 +1,49 @@
+/* $NetBSD: getwc.c,v 1.3 2005/06/12 05:21:27 lukem Exp $ */
+
+/*-
+ * Copyright (c)2001 Citrus Project,
+ * 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.
+ *
+ * $Citrus$
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getwc.c,v 1.3 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdio.h>
+#include <wchar.h>
+
+/*
+ * A subroutine version of the macro getwc.
+ */
+#undef getwc
+
+wint_t
+getwc(FILE *fp)
+{
+
+       return fgetwc(fp);
+}
diff --git a/lib/nbsd_libc/stdio/getwchar.c b/lib/nbsd_libc/stdio/getwchar.c
new file mode 100644 (file)
index 0000000..74b8d70
--- /dev/null
@@ -0,0 +1,49 @@
+/* $NetBSD: getwchar.c,v 1.3 2005/06/12 05:21:27 lukem Exp $ */
+
+/*-
+ * Copyright (c)2001 Citrus Project,
+ * 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.
+ *
+ * $Citrus$
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: getwchar.c,v 1.3 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdio.h>
+#include <wchar.h>
+
+/*
+ * A subroutine version of the macro getwchar.
+ */
+#undef getwchar
+
+wint_t
+getwchar()
+{
+
+       return fgetwc(stdin);
+}
diff --git a/lib/nbsd_libc/stdio/glue.h b/lib/nbsd_libc/stdio/glue.h
new file mode 100644 (file)
index 0000000..c0c85a5
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: glue.h,v 1.5 2003/08/07 16:43:27 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ *
+ *     @(#)glue.h      8.1 (Berkeley) 6/4/93
+ */
+
+/*
+ * The first few FILEs are statically allocated; others are dynamically
+ * allocated and linked in via this glue structure.
+ */
+struct glue {
+       struct  glue *next;
+       int     niobs;
+       FILE    *iobs;
+};
+
+extern struct glue __sglue;
diff --git a/lib/nbsd_libc/stdio/local.h b/lib/nbsd_libc/stdio/local.h
new file mode 100644 (file)
index 0000000..7a03bc9
--- /dev/null
@@ -0,0 +1,128 @@
+/*     $NetBSD: local.h,v 1.29 2010/10/24 17:44:32 tron Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ *
+ *     @(#)local.h     8.3 (Berkeley) 7/3/94
+ */
+
+#include "wcio.h"
+#include "fileext.h"
+
+#include <limits.h>
+#include <stdbool.h>
+
+/*
+ * Information local to this implementation of stdio,
+ * in particular, macros and private variables.
+ */
+
+extern int     __sflush __P((FILE *));
+extern FILE    *__sfp __P((void));
+extern void    __sfpinit __P((FILE *));
+extern int     __srefill __P((FILE *));
+extern int     __sread __P((void *, char *, int));
+extern int     __swrite __P((void *, char const *, int));
+extern fpos_t  __sseek __P((void *, fpos_t, int));
+extern int     __sclose __P((void *));
+extern void    __sinit __P((void));
+extern void    _cleanup __P((void));
+extern void    (*__cleanup) __P((void));
+extern void    __smakebuf __P((FILE *));
+extern int     __swhatbuf __P((FILE *, size_t *, int *));
+extern int     _fwalk __P((int (*)(FILE *)));
+extern char    *_mktemp __P((char *));
+extern int     __swsetup __P((FILE *));
+extern int     __sflags __P((const char *, int *));
+extern int     __svfscanf __P((FILE * __restrict, const char * __restrict,
+                   _BSD_VA_LIST_))
+                   __attribute__((__format__(__scanf__, 2, 0)));
+extern int     __svfscanf_unlocked __P((FILE * __restrict, const char * __restrict,
+                   _BSD_VA_LIST_))
+                   __attribute__((__format__(__scanf__, 2, 0)));
+extern int     __vfprintf_unlocked __P((FILE * __restrict, const char * __restrict,
+                   _BSD_VA_LIST_));
+
+
+extern int     __sdidinit;
+
+extern int     __gettemp __P((char *, int *, int));
+
+extern wint_t  __fgetwc_unlock __P((FILE *));
+extern wint_t  __fputwc_unlock __P((wchar_t, FILE *));
+
+extern ssize_t __getdelim(char **__restrict, size_t *__restrict, int,
+    FILE *__restrict);
+extern char    *__fgetstr __P((FILE * __restrict, size_t * __restrict, int));
+extern int      __vfwprintf_unlocked __P((FILE *, const wchar_t *,
+    _BSD_VA_LIST_));
+extern int      __vfwscanf_unlocked __P((FILE * __restrict,
+    const wchar_t * __restrict, _BSD_VA_LIST_));
+
+/*
+ * Return true iff the given FILE cannot be written now.
+ */
+#define        cantwrite(fp) \
+       ((((fp)->_flags & __SWR) == 0 || (fp)->_bf._base == NULL) && \
+        __swsetup(fp))
+
+/*
+ * Test whether the given stdio file has an active ungetc buffer;
+ * release such a buffer, without restoring ordinary unread data.
+ */
+#define        HASUB(fp) (_UB(fp)._base != NULL)
+#define        FREEUB(fp) { \
+       if (_UB(fp)._base != (fp)->_ubuf) \
+               free((char *)_UB(fp)._base); \
+       _UB(fp)._base = NULL; \
+}
+
+/*
+ * test for an fgetln() buffer.
+ */
+#define        FREELB(fp) { \
+       free(_EXT(fp)->_fgetstr_buf); \
+       _EXT(fp)->_fgetstr_buf = NULL; \
+       _EXT(fp)->_fgetstr_len = 0; \
+}
+
+extern void __flockfile_internal __P((FILE *, int));
+extern void __funlockfile_internal __P((FILE *, int));
+
+/*
+ * Detect if the current file position fits in a long int.
+ */
+
+static __inline bool
+__fpos_overflow(fpos_t pos)
+{
+  return (pos < LONG_MIN) || (pos > LONG_MAX);
+}
diff --git a/lib/nbsd_libc/stdio/makebuf.c b/lib/nbsd_libc/stdio/makebuf.c
new file mode 100644 (file)
index 0000000..cf0e680
--- /dev/null
@@ -0,0 +1,131 @@
+/*     $NetBSD: makebuf.c,v 1.15 2008/03/13 15:40:00 christos Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)makebuf.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: makebuf.c,v 1.15 2008/03/13 15:40:00 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * Allocate a file buffer, or switch to unbuffered I/O.
+ * Per the ANSI C standard, ALL tty devices default to line buffered.
+ *
+ * As a side effect, we set __SOPT or __SNPT (en/dis-able fseek
+ * optimisation) right after the fstat() that finds the buffer size.
+ */
+void
+__smakebuf(fp)
+       FILE *fp;
+{
+       void *p;
+       int flags;
+       size_t size;
+       int couldbetty;
+
+       _DIAGASSERT(fp != NULL);
+
+       if (fp->_flags & __SNBF) {
+               fp->_bf._base = fp->_p = fp->_nbuf;
+               fp->_bf._size = 1;
+               return;
+       }
+       flags = __swhatbuf(fp, &size, &couldbetty);
+       if ((p = malloc(size)) == NULL) {
+               fp->_flags |= __SNBF;
+               fp->_bf._base = fp->_p = fp->_nbuf;
+               fp->_bf._size = 1;
+               return;
+       }
+       __cleanup = _cleanup;
+       flags |= __SMBF;
+       fp->_bf._base = fp->_p = p;
+       fp->_bf._size = size;
+       if (couldbetty && isatty(__sfileno(fp)))
+               flags |= __SLBF;
+       fp->_flags |= flags;
+}
+
+/*
+ * Internal routine to determine `proper' buffering for a file.
+ */
+int
+__swhatbuf(fp, bufsize, couldbetty)
+       FILE *fp;
+       size_t *bufsize;
+       int *couldbetty;
+{
+       struct stat st;
+
+       _DIAGASSERT(fp != NULL);
+       _DIAGASSERT(bufsize != NULL);
+       _DIAGASSERT(couldbetty != NULL);
+
+       if (__sfileno(fp) == -1 || fstat(__sfileno(fp), &st) < 0) {
+               *couldbetty = 0;
+               *bufsize = BUFSIZ;
+               return (__SNPT);
+       }
+
+       /* could be a tty iff it is a character device */
+       *couldbetty = S_ISCHR(st.st_mode);
+       if (st.st_blksize == 0) {
+               *bufsize = BUFSIZ;
+               return (__SNPT);
+       }
+
+       /*
+        * Optimise fseek() only if it is a regular file.  (The test for
+        * __sseek is mainly paranoia.)  It is safe to set _blksize
+        * unconditionally; it will only be used if __SOPT is also set.
+        */
+       *bufsize = st.st_blksize;
+       fp->_blksize = st.st_blksize;
+       return ((st.st_mode & S_IFMT) == S_IFREG && fp->_seek == __sseek ?
+           __SOPT : __SNPT);
+}
diff --git a/lib/nbsd_libc/stdio/mkdtemp.c b/lib/nbsd_libc/stdio/mkdtemp.c
new file mode 100644 (file)
index 0000000..914f857
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: mkdtemp.c,v 1.10 2008/10/20 10:28:38 apb Exp $ */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#if !HAVE_NBTOOL_CONFIG_H || !HAVE_MKDTEMP
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)mktemp.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: mkdtemp.c,v 1.10 2008/10/20 10:28:38 apb Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if HAVE_NBTOOL_CONFIG_H
+#define        GETTEMP         __nbcompat_gettemp
+#else
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include "reentrant.h"
+#include "local.h"
+#define        GETTEMP         __gettemp
+#endif
+
+char *
+mkdtemp(path)
+       char *path;
+{
+       _DIAGASSERT(path != NULL);
+
+       return (GETTEMP(path, (int *)NULL, 1) ? path : (char *)NULL);
+}
+
+#endif /* !HAVE_NBTOOL_CONFIG_H || !HAVE_MKDTEMP */
diff --git a/lib/nbsd_libc/stdio/mkstemp.c b/lib/nbsd_libc/stdio/mkstemp.c
new file mode 100644 (file)
index 0000000..241deae
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: mkstemp.c,v 1.10 2008/10/20 10:28:38 apb Exp $ */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#if !HAVE_NBTOOL_CONFIG_H || !HAVE_MKSTEMP
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)mktemp.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: mkstemp.c,v 1.10 2008/10/20 10:28:38 apb Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#if HAVE_NBTOOL_CONFIG_H
+#define        GETTEMP         __nbcompat_gettemp
+#else
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include "reentrant.h"
+#include "local.h"
+#define        GETTEMP         __gettemp
+#endif
+
+#ifdef __weak_alias
+__weak_alias(mkstemp,_mkstemp)
+#endif
+
+int
+mkstemp(path)
+       char *path;
+{
+       int fd;
+
+       _DIAGASSERT(path != NULL);
+
+       return (GETTEMP(path, &fd, 0) ? fd : -1);
+}
+
+#endif /* !HAVE_NBTOOL_CONFIG_H || !HAVE_MKSTEMP */
diff --git a/lib/nbsd_libc/stdio/mktemp.3 b/lib/nbsd_libc/stdio/mktemp.3
new file mode 100644 (file)
index 0000000..37718dd
--- /dev/null
@@ -0,0 +1,329 @@
+.\"    $NetBSD: mktemp.3,v 1.28 2010/05/14 03:22:49 joerg Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)mktemp.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 29, 2010
+.Dt MKTEMP 3
+.Os
+.Sh NAME
+.Nm mktemp ,
+.Nm mkstemp ,
+.Nm mkdtemp
+.Nd make unique temporary file or directory name
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft char *
+.Fn mktemp "char *template"
+.Ft int
+.Fn mkstemp "char *template"
+.Ft char *
+.Fn mkdtemp "char *template"
+.Sh DESCRIPTION
+The
+.Fn mktemp
+function
+takes the given file name template and overwrites a portion of it
+to create a file name.
+This file name is unique and suitable for use
+by the application.
+The template may be any file name with some number of
+.So Li X
+.Sc Ns s
+appended
+to it, for example
+.Pa /tmp/temp.XXXXXX .
+The trailing
+.So Li X
+.Sc Ns s
+are replaced with the current process number and/or a
+unique letter combination.
+The number of unique file names
+.Fn mktemp
+can return depends on the number of
+.So Li X
+.Sc Ns s
+provided.
+Although the
+.Nx
+implementation of the functions will accept any number of trailing
+.So Li X
+.Sc Ns s ,
+for portability reasons one should use only six.
+Using six
+.So Li X
+.Sc Ns s
+will result in
+.Fn mktemp
+testing roughly 26 ** 6 (308915776) combinations.
+.Pp
+The
+.Fn mkstemp
+function
+makes the same replacement to the template and creates the template file,
+mode 0600, returning a file descriptor opened for reading and writing.
+This avoids the race between testing for a file's existence and opening it
+for use.
+.Pp
+The
+.Fn mkdtemp
+function
+is similar to
+.Fn mkstemp ,
+but it creates a mode 0700 directory instead and returns the path.
+.Pp
+Please note that the permissions of the file or directory being created are
+subject to the restrictions imposed by the
+.Xr umask 2
+system call.
+It may thus happen that the created file is unreadable and/or unwritable.
+.Sh RETURN VALUES
+The
+.Fn mktemp
+and
+.Fn mkdtemp
+functions
+return a pointer to the template on success and
+.Dv NULL
+on failure.
+The
+.Fn mkstemp
+function
+returns \-1 if no suitable file could be created.
+If either call fails an error code is placed in the global variable
+.Va errno .
+.Sh EXAMPLES
+Quite often a programmer will want to replace a use of
+.Fn mktemp
+with
+.Fn mkstemp ,
+usually to avoid the problems described above.
+Doing this correctly requires a good understanding of the code in question.
+.Pp
+For instance, code of this form:
+.Bd -literal -offset indent
+char sfn[15] = "";
+FILE *sfp;
+
+strlcpy(sfn, "/tmp/ed.XXXXXX", sizeof sfn);
+if (mktemp(sfn) == NULL || (sfp = fopen(sfn, "w+")) == NULL) {
+        fprintf(stderr, "%s: %s\en", sfn, strerror(errno));
+        return (NULL);
+}
+return (sfp);
+.Ed
+.Pp
+should be rewritten like this:
+.Bd -literal -offset indent
+char sfn[15] = "";
+FILE *sfp;
+int fd = -1;
+
+strlcpy(sfn, "/tmp/ed.XXXXXX", sizeof sfn);
+if ((fd = mkstemp(sfn)) == -1 ||
+    (sfp = fdopen(fd, "w+")) == NULL) {
+        if (fd != -1) {
+                unlink(sfn);
+                close(fd);
+        }
+        fprintf(stderr, "%s: %s\en", sfn, strerror(errno));
+        return (NULL);
+}
+return (sfp);
+.Ed
+.Pp
+Often one will find code which uses
+.Fn mktemp
+very early on, perhaps to globally initialize the template nicely, but the
+code which calls
+.Xr open 2
+or
+.Xr fopen 3
+on that filename will occur much later.
+(In almost all cases, the use of
+.Xr fopen 3
+will mean that the flags
+.Dv O_CREAT
+|
+.Dv O_EXCL
+are not given to
+.Xr open 2 ,
+and thus a symbolic link race becomes possible, hence making
+necessary the use of
+.Xr fdopen 3
+as seen above).
+Furthermore, one must be careful about code which opens, closes, and then
+re-opens the file in question.
+Finally, one must ensure that upon error the temporary file is
+removed correctly.
+.Pp
+There are also cases where modifying the code to use
+.Fn mktemp ,
+in concert with
+.Xr open 2
+using the flags
+.Dv O_CREAT
+|
+.Dv O_EXCL ,
+is better, as long as the code retries a new template if
+.Xr open 2
+fails with an
+.Va errno
+of
+.Er EEXIST .
+.Sh ERRORS
+The
+.Fn mktemp ,
+.Fn mkstemp
+and
+.Fn mkdtemp
+functions
+may set
+.Va errno
+to one of the following values:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+The pathname portion of the template is not an existing directory.
+.El
+.Pp
+The
+.Fn mktemp ,
+.Fn mkstemp
+and
+.Fn mkdtemp
+functions
+may also set
+.Va errno
+to any value specified by the
+.Xr stat 2
+function.
+.Pp
+The
+.Fn mkstemp
+function
+may also set
+.Va errno
+to any value specified by the
+.Xr open 2
+function.
+.Pp
+The
+.Fn mkdtemp
+function
+may also set
+.Va errno
+to any value specified by the
+.Xr mkdir 2
+function.
+.Sh SEE ALSO
+.Xr chmod 2 ,
+.Xr getpid 2 ,
+.Xr open 2 ,
+.Xr stat 2 ,
+.Xr umask 2
+.Sh STANDARDS
+The
+.Fn mktemp
+conforms to
+.St -p1003.1-2001 .
+It was however removed from the specification in the
+.St -p1003.1-2008
+revision.
+The
+.Fn mkstemp
+and
+.Fn mkdtemp
+functions conform to
+.St -p1003.1-2004
+and
+.St -p1003.1-2008 ,
+respectively.
+.Sh HISTORY
+A
+.Fn mktemp
+function appeared in
+.At v7 .
+.Pp
+The
+.Fn mkstemp
+function appeared in
+.Bx 4.4 .
+.Pp
+The
+.Fn mkdtemp
+function appeared in
+.Nx 1.4 .
+.Sh BUGS
+For
+.Fn mktemp
+there is an obvious race between file name selection and file
+creation and deletion: the program is typically written to call
+.Xr tmpnam 3 ,
+.Xr tempnam 3 ,
+or
+.Fn mktemp .
+Subsequently, the program calls
+.Xr open 2
+or
+.Xr fopen 3
+and erroneously opens a file (or symbolic link, fifo or other
+device) that the attacker has created in the expected file location.
+Hence
+.Fn mkstemp
+is recommended, since it atomically creates the file.
+An attacker can guess the filenames produced by
+.Fn mktemp .
+Whenever it is possible,
+.Fn mkstemp
+or
+.Fn mkdtemp
+should be used instead.
+.Pp
+For this reason,
+.Xr ld 1
+will output a warning message whenever it links code that uses
+.Fn mktemp .
+.Pp
+The
+.Fn mkdtemp
+function is nonstandard and should not be used if portability is required.
+.Sh SECURITY CONSIDERATIONS
+The use of
+.Fn mktemp
+should generally be avoided, as a hostile process can exploit a race
+condition in the time between the generation of a temporary filename by
+.Fn mktemp
+and the invoker's use of the temporary name.
+A link-time warning will be issued advising the use of
+.Fn mkstemp
+or
+.Fn mkdtemp
+instead.
diff --git a/lib/nbsd_libc/stdio/mktemp.c b/lib/nbsd_libc/stdio/mktemp.c
new file mode 100644 (file)
index 0000000..6eb71b0
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: mktemp.c,v 1.19 2003/08/07 16:43:28 agc Exp $  */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)mktemp.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: mktemp.c,v 1.19 2003/08/07 16:43:28 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include "reentrant.h"
+#include "local.h"
+
+char *
+_mktemp(path)
+       char *path;
+{
+
+       _DIAGASSERT(path != NULL);
+
+       return (__gettemp(path, (int *)NULL, 0) ? path : (char *)NULL);
+}
+
+__warn_references(mktemp,
+    "warning: mktemp() possibly used unsafely, use mkstemp() or mkdtemp()")
+
+char *
+mktemp(path)
+       char *path;
+{
+
+       _DIAGASSERT(path != NULL);
+
+       return (__gettemp(path, (int *)NULL, 0) ? path : (char *)NULL);
+}
diff --git a/lib/nbsd_libc/stdio/perror.c b/lib/nbsd_libc/stdio/perror.c
new file mode 100644 (file)
index 0000000..de38e88
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: perror.c,v 1.24 2006/01/26 11:13:42 kleink Exp $       */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)perror.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: perror.c,v 1.24 2006/01/26 11:13:42 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+#include "extern.h"
+
+/*
+ * Since perror() is not allowed to change the contents of strerror()'s
+ * static buffer, both functions supply their own buffers to strerror_r().
+ */
+
+void
+perror(const char *s)
+{
+       const char *separator;
+       char buf[NL_TEXTMAX];
+
+       if (s == NULL)
+               s = "";
+       if (*s == '\0')
+               separator = "";
+       else
+               separator = ": ";
+
+       (void)strerror_r(errno, buf, sizeof(buf));
+       (void)fprintf(stderr, "%s%s%s\n", s, separator, buf);
+}
diff --git a/lib/nbsd_libc/stdio/printf.3 b/lib/nbsd_libc/stdio/printf.3
new file mode 100644 (file)
index 0000000..3361d26
--- /dev/null
@@ -0,0 +1,1000 @@
+.\"    $NetBSD: printf.3,v 1.58 2010/12/26 12:39:54 jnemeth Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)printf.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd December 26, 2010
+.Dt PRINTF 3
+.Os
+.Sh NAME
+.Nm printf ,
+.Nm fprintf ,
+.Nm dprintf
+.Nm sprintf ,
+.Nm snprintf ,
+.Nm asprintf ,
+.Nm vprintf ,
+.Nm vfprintf ,
+.Nm vsprintf ,
+.Nm vdprintf ,
+.Nm vsnprintf ,
+.Nm vsnprintf_ss ,
+.Nm vasprintf
+.Nd formatted output conversion
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft int
+.Fn printf "const char * restrict format" ...
+.Ft int
+.Fn fprintf "FILE * restrict stream" "const char * restrict format" ...
+.Ft int
+.Fn dprintf "int fd" "const char * restrict format" ...
+.Ft int
+.Fn sprintf "char * restrict str" "const char * restrict format" ...
+.Ft int
+.Fn snprintf "char * restrict str" "size_t size" "const char * restrict format" ...
+.Ft int
+.Fn asprintf "char ** restrict ret" "const char * restrict format" ...
+.In stdarg.h
+.Ft int
+.Fn vprintf "const char * restrict format" "va_list ap"
+.Ft int
+.Fn vfprintf "FILE * restrict stream" "const char * restrict format" "va_list ap"
+.Ft int
+.Fn vsprintf "char * restrict str" "const char * restrict format" "va_list ap"
+.Ft int
+.Fn vdprintf "int fd" "const char * restrict format" "va_list ap"
+.Ft int
+.Fn vsnprintf "char * restrict str" "size_t size" "const char * restrict format" "va_list ap"
+.Ft int
+.Fn vsnprintf_ss "char * restrict str" "size_t size" "const char * restrict format" "va_list ap"
+.Ft int
+.Fn vasprintf "char ** restrict ret" "const char * restrict format" "va_list ap"
+.Sh DESCRIPTION
+The
+.Fn printf
+family of functions produces output according to a
+.Fa format
+as described below.
+The
+.Fn printf
+and
+.Fn vprintf
+functions
+write output to
+.Em stdout ,
+the standard output stream;
+.Fn fprintf
+and
+.Fn vfprintf
+write output to the given output
+.Fa stream ;
+.Fn dprintf
+and
+.Fn vdprintf
+write output to the give file descriptor
+.Fa fd ;
+.Fn sprintf ,
+.Fn snprintf ,
+.Fn vsprintf ,
+.Fn vsnprintf ,
+and
+.Fn vsnprintf_ss
+write to the character string
+.Fa str ;
+and
+.Fn asprintf
+and
+.Fn vasprintf
+write to a dynamically allocated string that is stored in
+.Fa ret .
+.Pp
+These functions write the output under the control of a
+.Fa format
+string that specifies how subsequent arguments
+(or arguments accessed via the variable-length argument facilities of
+.Xr stdarg 3 )
+are converted for output.
+.Pp
+.Fn vsnprintf_ss
+is a signal-safe standalone version that does not handle
+floating point formats.
+.Pp
+.Fn asprintf
+and
+.Fn vasprintf
+return a pointer to a buffer sufficiently large to hold the
+string in the
+.Fa ret
+argument.
+This pointer should be passed to
+.Xr free 3
+to release the allocated storage when it is no longer needed.
+If sufficient space cannot be allocated, these functions
+will return \-1 and set
+.Fa ret
+to be a
+.Dv NULL
+pointer.
+Please note that these functions are not standardized, and not all
+implementations can be assumed to set the
+.Fa ret
+argument to
+.Dv NULL
+on error.
+It is more portable to check for a return value of \-1 instead.
+.Pp
+.Fn snprintf ,
+.Fn vsnprintf ,
+and
+.Fn vsnprintf_ss
+will write at most
+.Fa size Ns \-1
+of the characters printed into the output string
+(the
+.Fa size Ns 'th
+character then gets the terminating
+.Ql \e0 ) ;
+if the return value is greater than or equal to the
+.Fa size
+argument, the string was too short
+and some of the printed characters were discarded.
+If
+.Fa size
+is zero, nothing is written and
+.Fa str
+may be a
+.Dv NULL
+pointer.
+.Pp
+.Fn sprintf
+and
+.Fn vsprintf
+effectively assume an infinite
+.Fa size .
+.Pp
+The format string is composed of zero or more directives:
+ordinary
+.\" multibyte
+characters (not
+.Cm % ) ,
+which are copied unchanged to the output stream;
+and conversion specifications, each of which results
+in fetching zero or more subsequent arguments.
+Each conversion specification is introduced by
+the character
+.Cm % .
+The arguments must correspond properly (after type promotion)
+with the conversion specifier.
+After the
+.Cm % ,
+the following appear in sequence:
+.Bl -bullet
+.It
+An optional field, consisting of a decimal digit string followed by a
+.Cm $ ,
+specifying the next argument to access.
+If this field is not provided, the argument following the last
+argument accessed will be used.
+Arguments are numbered starting at
+.Cm 1 .
+If unaccessed arguments in the format string are interspersed with ones that
+are accessed the results will be indeterminate.
+.It
+Zero or more of the following flags:
+.Bl -tag -width ".So \  Sc (space)"
+.It Sq Cm #
+The value should be converted to an
+.Dq alternate form .
+For
+.Cm c ,
+.Cm d ,
+.Cm i ,
+.Cm n ,
+.Cm p ,
+.Cm s ,
+and
+.Cm u
+conversions, this option has no effect.
+For
+.Cm o
+conversions, the precision of the number is increased to force the first
+character of the output string to a zero (except if a zero value is printed
+with an explicit precision of zero).
+For
+.Cm x
+and
+.Cm X
+conversions, a non-zero result has the string
+.Ql 0x
+(or
+.Ql 0X
+for
+.Cm X
+conversions) prepended to it.
+For
+.Cm a ,
+.Cm A ,
+.Cm e ,
+.Cm E ,
+.Cm f ,
+.Cm F ,
+.Cm g ,
+and
+.Cm G
+conversions, the result will always contain a decimal point, even if no
+digits follow it (normally, a decimal point appears in the results of
+those conversions only if a digit follows).
+For
+.Cm g
+and
+.Cm G
+conversions, trailing zeros are not removed from the result as they
+would otherwise be.
+.It So Cm 0 Sc (zero)
+Zero padding.
+For all conversions except
+.Cm n ,
+the converted value is padded on the left with zeros rather than blanks.
+If a precision is given with a numeric conversion
+.Pf ( Cm d ,
+.Cm i ,
+.Cm o ,
+.Cm u ,
+.Cm i ,
+.Cm x ,
+and
+.Cm X ) ,
+the
+.Cm 0
+flag is ignored.
+.It Sq Cm \-
+A negative field width flag;
+the converted value is to be left adjusted on the field boundary.
+Except for
+.Cm n
+conversions, the converted value is padded on the right with blanks,
+rather than on the left with blanks or zeros.
+A
+.Sq Cm \-
+overrides a
+.Sq Cm \&0
+if both are given.
+.It So "\ " Sc (space)
+A blank should be left before a positive number
+produced by a signed conversion
+.Pf ( Cm a ,
+.Cm A
+.Cm d ,
+.Cm e ,
+.Cm E ,
+.Cm f ,
+.Cm F ,
+.Cm g ,
+.Cm G ,
+or
+.Cm i ) .
+.It Sq Cm +
+A sign must always be placed before a
+number produced by a signed conversion.
+A
+.Sq Cm +
+overrides a space if both are used.
+.It Sq Cm '
+Decimal conversions
+.Cm ( d , u ,
+or
+.Cm i )
+or the integral portion of a floating point conversion
+.Cm ( f
+or
+.Cm F )
+should be grouped and separated by thousands using
+the non-monetary separator returned by
+.Xr localeconv 3 .
+.El
+.It
+An optional decimal digit string specifying a minimum field width.
+If the converted value has fewer characters than the field width, it will
+be padded with spaces on the left (or right, if the left-adjustment
+flag has been given) to fill out the field width.
+.It
+An optional precision, in the form of a period
+.Sq Cm \&.
+followed by an optional digit string.
+If the digit string is omitted, the precision is taken as zero.
+This gives the minimum number of digits to appear for
+.Cm d ,
+.Cm i ,
+.Cm o ,
+.Cm u ,
+.Cm x ,
+and
+.Cm X
+conversions, the number of digits to appear after the decimal-point for
+.Cm a ,
+.Cm A ,
+.Cm e ,
+.Cm E ,
+.Cm f ,
+and
+.Cm F
+conversions, the maximum number of significant digits for
+.Cm g
+and
+.Cm G
+conversions, or the maximum number of characters to be printed from a
+string for
+.Cm s
+conversions.
+.It
+An optional length modifier, that specifies the size of the argument.
+The following length modifiers are valid for the
+.Cm d , i , n , o , u , x ,
+or
+.Cm X
+conversion:
+.Bl -column ".Cm q Em (deprecated)" ".Vt signed char" ".Vt unsigned long long" ".Vt long long *"
+.It Sy Modifier Ta Cm d , i Ta Cm o , u , x , X Ta Cm n
+.It Cm hh Ta Vt "signed char" Ta Vt "unsigned char" Ta Vt "signed char *"
+.It Cm h Ta Vt short Ta Vt "unsigned short" Ta Vt "short *"
+.It Cm l No (ell) Ta Vt long Ta Vt "unsigned long" Ta Vt "long *"
+.It Cm ll No (ell ell) Ta Vt "long long" Ta Vt "unsigned long long" Ta Vt "long long *"
+.It Cm j Ta Vt intmax_t Ta Vt uintmax_t Ta Vt "intmax_t *"
+.It Cm t Ta Vt ptrdiff_t Ta (see note) Ta Vt "ptrdiff_t *"
+.It Cm z Ta (see note) Ta Vt size_t Ta (see note)
+.It Cm q Em (deprecated) Ta Vt quad_t Ta Vt u_quad_t Ta Vt "quad_t *"
+.El
+.Pp
+Note:
+the
+.Cm t
+modifier, when applied to a
+.Cm o , u , x ,
+or
+.Cm X
+conversion, indicates that the argument is of an unsigned type
+equivalent in size to a
+.Vt ptrdiff_t .
+The
+.Cm z
+modifier, when applied to a
+.Cm d
+or
+.Cm i
+conversion, indicates that the argument is of a signed type equivalent in
+size to a
+.Vt size_t .
+Similarly, when applied to an
+.Cm n
+conversion, it indicates that the argument is a pointer to a signed type
+equivalent in size to a
+.Vt size_t .
+.Pp
+Note:
+if the standard integer types described in
+.Xr stdint 3
+are used, it is recommended that the predefined format string specifier
+macros are used when possible.
+These are further described in
+.Xr inttypes 3 .
+.Pp
+The following length modifier is valid for the
+.Cm a ,
+.Cm A ,
+.Cm e ,
+.Cm E ,
+.Cm f ,
+.Cm F ,
+.Cm g ,
+or
+.Cm G
+conversion:
+.Bl -column ".Sy Modifier" ".Cm a , A , e , E , f , F , g , G"
+.It Sy Modifier Ta Cm a , A , e , E , f , F , g , G
+.It Cm l No (ell) Ta Vt double
+(ignored, same behavior as without it)
+.It Cm L Ta Vt "long double"
+.El
+.Pp
+The following length modifier is valid for the
+.Cm c
+or
+.Cm s
+conversion:
+.Bl -column ".Sy Modifier" ".Vt wint_t" ".Vt wchar_t *"
+.It Sy Modifier Ta Cm c Ta Cm s
+.It Cm l No (ell) Ta Vt wint_t Ta Vt "wchar_t *"
+.El
+.It
+A character that specifies the type of conversion to be applied.
+.El
+.Pp
+A field width or precision, or both, may be indicated by
+an asterisk
+.Ql *
+or an asterisk followed by one or more decimal digits and a
+.Ql $
+instead of a
+digit string.
+In this case, an
+.Vt int
+argument supplies the field width or precision.
+A negative field width is treated as a left adjustment flag followed by a
+positive field width; a negative precision is treated as though it were
+missing.
+If a single format directive mixes positional
+.Pq Li nn$
+and non-positional arguments, the results are undefined.
+.Pp
+The conversion specifiers and their meanings are:
+.Bl -tag -width ".Cm diouxX"
+.It Cm diouxX
+The
+.Vt int
+(or appropriate variant) argument is converted to signed decimal
+.Pf ( Cm d
+and
+.Cm i ) ,
+unsigned octal
+.Pq Cm o ,
+unsigned decimal
+.Pq Cm u ,
+or unsigned hexadecimal
+.Pf ( Cm x
+and
+.Cm X )
+notation.
+The letters
+.Dq Li abcdef
+are used for
+.Cm x
+conversions; the letters
+.Dq Li ABCDEF
+are used for
+.Cm X
+conversions.
+The precision, if any, gives the minimum number of digits that must
+appear; if the converted value requires fewer digits, it is padded on
+the left with zeros.
+.It Cm DOU
+The
+.Vt long int
+argument is converted to signed decimal, unsigned octal, or unsigned
+decimal, as if the format had been
+.Cm ld ,
+.Cm lo ,
+or
+.Cm lu
+respectively.
+These conversion characters are deprecated, and will eventually disappear.
+.It Cm eE
+The
+.Vt double
+argument is rounded and converted in the style
+.Sm off
+.Oo \- Oc Ar d Li \&. Ar ddd Li e \*[Pm] Ar dd
+.Sm on
+where there is one digit before the
+decimal-point character
+and the number of digits after it is equal to the precision;
+if the precision is missing,
+it is taken as 6; if the precision is
+zero, no decimal-point character appears.
+An
+.Cm E
+conversion uses the letter
+.Ql E
+(rather than
+.Ql e )
+to introduce the exponent.
+The exponent always contains at least two digits; if the value is zero,
+the exponent is 00.
+.Pp
+For
+.Cm a ,
+.Cm A ,
+.Cm e ,
+.Cm E ,
+.Cm f ,
+.Cm F ,
+.Cm g ,
+and
+.Cm G
+conversions, positive and negative infinity are represented as
+.Li inf
+and
+.Li -inf
+respectively when using the lowercase conversion character, and
+.Li INF
+and
+.Li -INF
+respectively when using the uppercase conversion character.
+Similarly, NaN is represented as
+.Li nan
+when using the lowercase conversion, and
+.Li NAN
+when using the uppercase conversion.
+.It Cm fF
+The
+.Vt double
+argument is rounded and converted to decimal notation in the style
+.Sm off
+.Oo \- Oc Ar ddd Li \&. Ar ddd ,
+.Sm on
+where the number of digits after the decimal-point character
+is equal to the precision specification.
+If the precision is missing, it is taken as 6; if the precision is
+explicitly zero, no decimal-point character appears.
+If a decimal point appears, at least one digit appears before it.
+.It Cm gG
+The
+.Vt double
+argument is converted in style
+.Cm f
+or
+.Cm e
+(or in style
+.Cm F
+or
+.Cm E
+for
+.Cm G
+conversions).
+The precision specifies the number of significant digits.
+If the precision is missing, 6 digits are given; if the precision is zero,
+it is treated as 1.
+Style
+.Cm e
+is used if the exponent from its conversion is less than \-4 or greater than
+or equal to the precision.
+Trailing zeros are removed from the fractional part of the result; a
+decimal point appears only if it is followed by at least one digit.
+.It Cm aA
+The
+.Vt double
+argument is rounded and converted to hexadecimal notation in the style
+.Sm off
+.Oo \- Oc Li 0x Ar h Li \&. Ar hhhp Oo \*[Pm] Oc Ar d ,
+.Sm on
+where the number of digits after the hexadecimal-point character
+is equal to the precision specification.
+If the precision is missing, it is taken as enough to represent
+the floating-point number exactly, and no rounding occurs.
+If the precision is zero, no hexadecimal-point character appears.
+The
+.Cm p
+is a literal character
+.Ql p ,
+and the exponent consists of a positive or negative sign
+followed by a decimal number representing an exponent of 2.
+The
+.Cm A
+conversion uses the prefix
+.Dq Li 0X
+(rather than
+.Dq Li 0x ) ,
+the letters
+.Dq Li ABCDEF
+(rather than
+.Dq Li abcdef )
+to represent the hex digits, and the letter
+.Ql P
+(rather than
+.Ql p )
+to separate the mantissa and exponent.
+.Pp
+Note that there may be multiple valid ways to represent floating-point
+numbers in this hexadecimal format.
+For example,
+.Li 0x3.24p+0 , 0x6.48p-1
+and
+.Li 0xc.9p-2
+are all equivalent.
+The format chosen depends on the internal representation of the
+number, but the implementation guarantees that the length of the
+mantissa will be minimized.
+Zeroes are always represented with a mantissa of 0 (preceded by a
+.Ql -
+if appropriate) and an exponent of
+.Li +0 .
+.It Cm C
+Treated as
+.Cm c
+with the
+.Cm l
+(ell) modifier.
+.It Cm c
+The
+.Vt int
+argument is converted to an
+.Vt "unsigned char" ,
+and the resulting character is written.
+.Pp
+If the
+.Cm l
+(ell) modifier is used, the
+.Vt wint_t
+argument shall be converted to a
+.Vt wchar_t ,
+and the (potentially multi-byte) sequence representing the
+single wide character is written, including any shift sequences.
+If a shift sequence is used, the shift state is also restored
+to the original state after the character.
+.It Cm S
+Treated as
+.Cm s
+with the
+.Cm l
+(ell) modifier.
+.It Cm s
+The
+.Vt "char *"
+argument is expected to be a pointer to an array of character type (pointer
+to a string).
+Characters from the array are written up to (but not including)
+a terminating
+.Dv NUL
+character;
+if a precision is specified, no more than the number specified are
+written.
+If a precision is given, no null character
+need be present; if the precision is not specified, or is greater than
+the size of the array, the array must contain a terminating
+.Dv NUL
+character.
+.Pp
+If the
+.Cm l
+(ell) modifier is used, the
+.Vt "wchar_t *"
+argument is expected to be a pointer to an array of wide characters
+(pointer to a wide string).
+For each wide character in the string, the (potentially multi-byte)
+sequence representing the
+wide character is written, including any shift sequences.
+If any shift sequence is used, the shift state is also restored
+to the original state after the string.
+Wide characters from the array are written up to (but not including)
+a terminating wide
+.Dv NUL
+character;
+if a precision is specified, no more than the number of bytes specified are
+written (including shift sequences).
+Partial characters are never written.
+If a precision is given, no null character
+need be present; if the precision is not specified, or is greater than
+the number of bytes required to render the multibyte representation of
+the string, the array must contain a terminating wide
+.Dv NUL
+character.
+.It Cm p
+The
+.Vt "void *"
+pointer argument is printed in hexadecimal (as if by
+.Ql %#x
+or
+.Ql %#lx ) .
+.It Cm n
+The number of characters written so far is stored into the
+integer indicated by the
+.Vt "int *"
+(or variant) pointer argument.
+No argument is converted.
+.It Cm %
+A
+.Ql %
+is written.
+No argument is converted.
+The complete conversion specification is
+.Ql %% .
+.El
+.Pp
+The decimal point
+character is defined in the program's locale (category
+.Dv LC_NUMERIC ) .
+.Pp
+In no case does a non-existent or small field width cause truncation of
+a numeric field; if the result of a conversion is wider than the field
+width, the
+field is expanded to contain the conversion result.
+.Sh RETURN VALUES
+These functions return
+the number of characters printed, or that would be printed if there
+was adequate space in case of
+.Fn snprintf ,
+.Fn vsnprintf ,
+and
+.Fn vsnprintf_ss
+(not including the trailing
+.Ql \e0
+used to end output to strings).
+If an output error was encountered, these functions shall return a
+negative value.
+.Sh EXAMPLES
+To print a date and time in the form
+.Dq Li "Sunday, July 3, 10:02" ,
+where
+.Fa weekday
+and
+.Fa month
+are pointers to strings:
+.Bd -literal -offset indent
+#include \*[Lt]stdio.h\*[Gt]
+fprintf(stdout, "%s, %s %d, %.2d:%.2d\en",
+       weekday, month, day, hour, min);
+.Ed
+.Pp
+To print \*(Pi
+to five decimal places:
+.Bd -literal -offset indent
+#include \*[Lt]math.h\*[Gt]
+#include \*[Lt]stdio.h\*[Gt]
+fprintf(stdout, "pi = %.5f\en", 4 * atan(1.0));
+.Ed
+.Pp
+To allocate a 128 byte string and print into it:
+.Bd -literal -offset indent
+#include \*[Lt]stdio.h\*[Gt]
+#include \*[Lt]stdlib.h\*[Gt]
+#include \*[Lt]stdarg.h\*[Gt]
+char *newfmt(const char *fmt, ...)
+{
+               char *p;
+               va_list ap;
+               if ((p = malloc(128)) == NULL)
+                       return (NULL);
+               va_start(ap, fmt);
+               (void) vsnprintf(p, 128, fmt, ap);
+               va_end(ap);
+               return (p);
+}
+.Ed
+.Sh ERRORS
+In addition to the errors documented for the
+.Xr write 2
+system call, the
+.Fn printf
+family of functions may fail if:
+.Bl -tag -width Er
+.It Bq Er EILSEQ
+An invalid wide-character code was encountered.
+.It Bq Er ENOMEM
+Insufficient storage space is available.
+.El
+.Sh SEE ALSO
+.Xr printf 1 ,
+.Xr fmtcheck 3 ,
+.Xr scanf 3 ,
+.Xr setlocale 3 ,
+.Xr wprintf 3 ,
+.Xr printf 9
+.Sh STANDARDS
+Subject to the caveats noted in the
+.Sx BUGS
+section below, the
+.Fn fprintf ,
+.Fn printf ,
+.Fn sprintf ,
+.Fn vprintf ,
+.Fn vfprintf ,
+and
+.Fn vsprintf
+functions
+conform to
+.St -ansiC
+and
+.St -isoC-99 .
+With the same reservation, the
+.Fn snprintf
+and
+.Fn vsnprintf
+functions conform to
+.St -isoC-99 .
+.Sh HISTORY
+The functions
+.Fn snprintf
+and
+.Fn vsnprintf
+first appeared in
+.Bx 4.4 .
+The functions
+.Fn asprintf
+and
+.Fn vasprintf
+are modeled on the ones that first appeared in the GNU C library.
+The function
+.Fn vsnprintf_ss
+is non-standard and appeared in
+.Nx 4.0 .
+The functions
+.Fn dprintf
+and
+.Fn vdprintf
+are parts of
+.St -p1003.1-2008
+and appeared in
+.Nx 6.0 .
+.Sh CAVEATS
+Because
+.Fn sprintf
+and
+.Fn vsprintf
+assume an infinitely long string, callers must be careful not to
+overflow the actual space; this is often impossible to assure.
+For safety, programmers should use the
+.Fn snprintf
+and
+.Fn asprintf
+family of interfaces instead.
+Unfortunately, the
+.Fn snprintf
+interfaces are not available on older
+systems and the
+.Fn asprintf
+interfaces are not yet portable.
+.Pp
+It is important never to pass a string with user-supplied data as a
+format without using
+.Ql %s .
+An attacker can put format specifiers in the string to mangle your stack,
+leading to a possible security hole.
+This holds true even if you have built the string
+.Dq by hand
+using a function like
+.Fn snprintf ,
+as the resulting string may still contain user-supplied conversion specifiers
+for later interpolation by
+.Fn printf .
+.Pp
+Be sure to use the proper secure idiom:
+.Bd -literal -offset indent
+snprintf(buffer, sizeof(buffer), "%s", string);
+.Ed
+.Pp
+There is no way for printf to know the size of each argument passed.
+If you use positional arguments you must ensure that all parameters, up to the
+last positionally specified parameter, are used in the format string.
+This allows for the format string to be parsed for this information.
+Failure to do this will mean your code is non-portable and liable to fail.
+.Pp
+In this implementation, passing a
+.Dv NULL
+.Vt char *
+argument to the
+.Cm %s
+format specifier will output
+.Em "(null)"
+instead of crashing.
+Programs that depend on this behavior are non-portable and may crash
+on other systems or in the future.
+.Sh BUGS
+The conversion formats
+.Cm \&%D ,
+.Cm \&%O ,
+and
+.Cm \&%U
+are not standard and are provided only for backward compatibility.
+The effect of padding the
+.Cm %p
+format with zeros (either by the
+.Sq Cm 0
+flag or by specifying a precision), and the benign effect (i.e. none)
+of the
+.Sq Cm #
+flag on
+.Cm %n
+and
+.Cm %p
+conversions, as well as other nonsensical combinations such as
+.Cm %Ld ,
+are not standard; such combinations should be avoided.
+.Pp
+The
+.Nm
+family of functions do not correctly handle multibyte characters in the
+.Fa format
+argument.
+.Sh SECURITY CONSIDERATIONS
+The
+.Fn sprintf
+and
+.Fn vsprintf
+functions are easily misused in a manner which enables malicious users
+to arbitrarily change a running program's functionality through
+a buffer overflow attack.
+Because
+.Fn sprintf
+and
+.Fn vsprintf
+assume an infinitely long string,
+callers must be careful not to overflow the actual space;
+this is often hard to assure.
+For safety, programmers should use the
+.Fn snprintf
+interface instead.
+For example:
+.Bd -literal
+void
+foo(const char *arbitrary_string, const char *and_another)
+{
+       char onstack[8];
+
+#ifdef BAD
+       /*
+        * This first sprintf is bad behavior.  Do not use sprintf!
+        */
+       sprintf(onstack, "%s, %s", arbitrary_string, and_another);
+#else
+       /*
+        * The following two lines demonstrate better use of
+        * snprintf().
+        */
+       snprintf(onstack, sizeof(onstack), "%s, %s", arbitrary_string,
+           and_another);
+#endif
+}
+.Ed
+.Pp
+The
+.Fn printf
+and
+.Fn sprintf
+family of functions are also easily misused in a manner
+allowing malicious users to arbitrarily change a running program's
+functionality by either causing the program
+to print potentially sensitive data
+.Dq "left on the stack" ,
+or causing it to generate a memory fault or bus error
+by dereferencing an invalid pointer.
+.Pp
+.Cm %n
+can be used to write arbitrary data to potentially carefully-selected
+addresses.
+Programmers are therefore strongly advised to never pass untrusted strings
+as the
+.Fa format
+argument, as an attacker can put format specifiers in the string
+to mangle your stack,
+leading to a possible security hole.
+This holds true even if the string was built using a function like
+.Fn snprintf ,
+as the resulting string may still contain user-supplied conversion specifiers
+for later interpolation by
+.Fn printf .
+.Pp
+Always use the proper secure idiom:
+.Pp
+.Dl "snprintf(buffer, sizeof(buffer), \*q%s\*q, string);"
diff --git a/lib/nbsd_libc/stdio/printf.c b/lib/nbsd_libc/stdio/printf.c
new file mode 100644 (file)
index 0000000..1c195ff
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: printf.c,v 1.11 2003/08/07 16:43:29 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)printf.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: printf.c,v 1.11 2003/08/07 16:43:29 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stdio.h>
+
+int
+printf(char const *fmt, ...)
+{
+       int ret;
+       va_list ap;
+
+       va_start(ap, fmt);
+       ret = vfprintf(stdout, fmt, ap);
+       va_end(ap);
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/putc.3 b/lib/nbsd_libc/stdio/putc.3
new file mode 100644 (file)
index 0000000..e7d3dae
--- /dev/null
@@ -0,0 +1,170 @@
+.\"    $NetBSD: putc.3,v 1.12 2010/05/06 09:01:34 jruoho Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)putc.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 6, 2010
+.Dt PUTC 3
+.Os
+.Sh NAME
+.Nm fputc ,
+.Nm putc ,
+.Nm putchar ,
+.Nm putc_unlocked ,
+.Nm putchar_unlocked ,
+.Nm putw
+.Nd output a character or word to a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft int
+.Fn fputc "int c" "FILE *stream"
+.Ft int
+.Fn putc "int c" "FILE *stream"
+.Ft int
+.Fn putchar "int c"
+.Ft int
+.Fn putc_unlocked "int c" "FILE *stream"
+.Ft int
+.Fn putchar_unlocked "int c"
+.Ft int
+.Fn putw "int w" "FILE *stream"
+.Sh DESCRIPTION
+The
+.Fn fputc
+function
+writes the character
+.Fa c
+(converted to an ``unsigned char'')
+to the output stream pointed to by
+.Fa stream .
+.Pp
+.Fn putc
+acts essentially identically to
+.Fn fputc ,
+but is a macro that expands in-line.
+It may evaluate
+.Fa stream
+more than once, so arguments given to
+.Fn putc
+should not be expressions with potential side effects.
+.Pp
+.Fn putchar
+is identical to
+.Fn putc
+with an output stream of
+.Em stdout .
+.Pp
+The
+.Fn putc_unlocked
+and
+.Fn putchar_unlocked
+functions provide functionality identical to that of
+.Fn putc
+and
+.Fn putchar ,
+respectively, but do not perform implicit locking of the streams they
+operate on.
+In multi-threaded programs they may be used
+.Em only
+within a scope in which the stream
+has been successfully locked by the calling thread using either
+.Xr flockfile 3
+or
+.Xr ftrylockfile 3 ,
+and may later be released using
+.Xr funlockfile 3 .
+.Pp
+The
+.Fn putw
+function
+writes the specified
+.Em int
+to the named output
+.Fa stream .
+.Sh RETURN VALUES
+The functions,
+.Fn fputc ,
+.Fn putc
+and
+.Fn putchar
+return the character written.
+If an error occurs, the value
+.Dv EOF
+is returned.
+The
+.Fn putw
+function
+returns 0 on success;
+.Dv EOF
+is returned if
+a write error occurs,
+or if an attempt is made to write a read-only stream.
+.Sh SEE ALSO
+.Xr ferror 3 ,
+.Xr fopen 3 ,
+.Xr getc 3 ,
+.Xr stdio 3
+.Sh STANDARDS
+The functions
+.Fn fputc ,
+.Fn putc ,
+and
+.Fn putchar ,
+conform to
+.St -ansiC .
+The functions
+.Fn putc_unlocked
+and
+.Fn putchar_unlocked
+conform to
+.St -p1003.1-96 .
+.Sh HISTORY
+The functions
+.Fn putc ,
+.Fn putchar ,
+and
+.Fn putw
+first appeared in
+.At v6 .
+The function
+.Fn fputc
+appeared in
+.At v7 .
+.Sh BUGS
+The size and byte order of an
+.Em int
+varies from one machine to another, and
+.Fn putw
+is not recommended for portable applications.
diff --git a/lib/nbsd_libc/stdio/putc.c b/lib/nbsd_libc/stdio/putc.c
new file mode 100644 (file)
index 0000000..b3d6a5a
--- /dev/null
@@ -0,0 +1,80 @@
+/*     $NetBSD: putc.c,v 1.11 2003/08/07 16:43:29 agc Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)putc.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: putc.c,v 1.11 2003/08/07 16:43:29 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * A subroutine version of the macro putc.
+ */
+#undef putc
+#undef putc_unlocked
+
+int
+putc(c, fp)
+       int c;
+       FILE *fp;
+{
+       int r;
+
+       _DIAGASSERT(fp != NULL);
+
+       FLOCKFILE(fp);
+       r = __sputc(c, fp);
+       FUNLOCKFILE(fp);
+       return r;
+}
+
+int
+putc_unlocked(c, fp)
+       int c;
+       FILE *fp;
+{
+
+       _DIAGASSERT(fp != NULL);
+
+       return (__sputc(c, fp));
+}
diff --git a/lib/nbsd_libc/stdio/putchar.c b/lib/nbsd_libc/stdio/putchar.c
new file mode 100644 (file)
index 0000000..4f7aca9
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: putchar.c,v 1.9 2003/08/07 16:43:29 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)putchar.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: putchar.c,v 1.9 2003/08/07 16:43:29 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+#undef putchar
+#undef putchar_unlocked
+
+/*
+ * A subroutine version of the macro putchar
+ */
+int
+putchar(c)
+       int c;
+{
+       FILE *fp = stdout;
+        int r;
+
+       FLOCKFILE(fp);
+       r = __sputc(c, fp);
+       FUNLOCKFILE(fp);
+       return r;
+}
+
+int
+putchar_unlocked(c)
+       int c;
+{
+       return (__sputc(c, stdout));
+}
diff --git a/lib/nbsd_libc/stdio/puts.c b/lib/nbsd_libc/stdio/puts.c
new file mode 100644 (file)
index 0000000..810b96c
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: puts.c,v 1.15 2006/03/17 02:25:23 chris Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)puts.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: puts.c,v 1.15 2006/03/17 02:25:23 chris Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include "fvwrite.h"
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * Write the given string to stdout, appending a newline.
+ */
+int
+puts(s)
+       char const *s;
+{
+       size_t c;
+       struct __suio uio;
+       struct __siov iov[2];
+       int r;
+
+       _DIAGASSERT(s != NULL);
+
+       if (s == NULL)
+               s = "(null)";
+
+       c = strlen(s);
+
+       iov[0].iov_base = __UNCONST(s);
+       iov[0].iov_len = c;
+       iov[1].iov_base = __UNCONST("\n");
+       iov[1].iov_len = 1;
+       uio.uio_resid = c + 1;
+       uio.uio_iov = &iov[0];
+       uio.uio_iovcnt = 2;
+       FLOCKFILE(stdout);
+       r = __sfvwrite(stdout, &uio);
+       FUNLOCKFILE(stdout);
+       return (r ? EOF : '\n');
+}
diff --git a/lib/nbsd_libc/stdio/putw.c b/lib/nbsd_libc/stdio/putw.c
new file mode 100644 (file)
index 0000000..728959b
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: putw.c,v 1.11 2003/08/07 16:43:29 agc Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)putw.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: putw.c,v 1.11 2003/08/07 16:43:29 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "fvwrite.h"
+#include "reentrant.h"
+#include "local.h"
+
+int
+putw(w, fp)
+       int w;
+       FILE *fp;
+{
+       struct __suio uio;
+       struct __siov iov;
+       int r;
+
+       _DIAGASSERT(fp != NULL);
+
+       iov.iov_base = &w;
+       iov.iov_len = uio.uio_resid = sizeof(w);
+       uio.uio_iov = &iov;
+       uio.uio_iovcnt = 1;
+       FLOCKFILE(fp);
+       r = __sfvwrite(fp, &uio);
+       FUNLOCKFILE(fp);
+       return r;
+}
diff --git a/lib/nbsd_libc/stdio/putwc.3 b/lib/nbsd_libc/stdio/putwc.3
new file mode 100644 (file)
index 0000000..7cde413
--- /dev/null
@@ -0,0 +1,101 @@
+.\"    $NetBSD: putwc.3,v 1.9 2010/12/16 17:42:27 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)putc.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd October 20, 2001
+.Dt PUTWC 3
+.Os
+.Sh NAME
+.Nm fputwc ,
+.Nm putwc ,
+.Nm putwchar ,
+.Nd output a wide character to a stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.In wchar.h
+.Ft wint_t
+.Fn fputwc "wchar_t wc" "FILE *stream"
+.Ft wint_t
+.Fn putwc "wchar_t wc" "FILE *stream"
+.Ft wint_t
+.Fn putwchar "wchar_t wc"
+.Sh DESCRIPTION
+The
+.Fn fputwc
+function
+writes the wide character
+.Fa wc
+to the output stream pointed to by
+.Fa stream .
+.Pp
+.Fn putwc
+acts essentially identically to
+.Fn fputwc ,
+but is a macro that expands in-line.
+It may evaluate
+.Fa stream
+more than once, so arguments given to
+.Fn putwc
+should not be expressions with potential side effects.
+.Pp
+.Fn putwchar
+is identical to
+.Fn putwc
+with an output stream of
+.Em stdout .
+.Sh RETURN VALUES
+The functions
+.Fn fputwc ,
+.Fn putwc ,
+and
+.Fn putwchar
+return the wide character written.
+If an error occurs, the value
+.Dv WEOF
+is returned.
+.Sh SEE ALSO
+.Xr ferror 3 ,
+.Xr fopen 3 ,
+.Xr getwc 3 ,
+.Xr stdio 3
+.Sh STANDARDS
+The functions
+.Fn fputwc ,
+.Fn putwc ,
+and
+.Fn putwchar ,
+conform to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/stdio/putwc.c b/lib/nbsd_libc/stdio/putwc.c
new file mode 100644 (file)
index 0000000..1d46145
--- /dev/null
@@ -0,0 +1,49 @@
+/* $NetBSD: putwc.c,v 1.4 2005/06/12 05:21:27 lukem Exp $ */
+
+/*-
+ * Copyright (c)2001 Citrus Project,
+ * 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.
+ *
+ * $Citrus$
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: putwc.c,v 1.4 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdio.h>
+#include <wchar.h>
+
+/*
+ * A subroutine version of the macro putwc.
+ */
+#undef putwc
+
+wint_t
+putwc(wchar_t wc, FILE *fp)
+{
+
+       return fputwc(wc, fp);
+}
diff --git a/lib/nbsd_libc/stdio/putwchar.c b/lib/nbsd_libc/stdio/putwchar.c
new file mode 100644 (file)
index 0000000..ec09ee1
--- /dev/null
@@ -0,0 +1,49 @@
+/* $NetBSD: putwchar.c,v 1.4 2005/06/12 05:21:27 lukem Exp $ */
+
+/*-
+ * Copyright (c)2001 Citrus Project,
+ * 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.
+ *
+ * $Citrus$
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: putwchar.c,v 1.4 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdio.h>
+#include <wchar.h>
+
+/*
+ * A subroutine version of the macro putwchar.
+ */
+#undef putwchar
+
+wint_t
+putwchar(wchar_t wc)
+{
+
+       return fputwc(wc, stdout);
+}
diff --git a/lib/nbsd_libc/stdio/refill.c b/lib/nbsd_libc/stdio/refill.c
new file mode 100644 (file)
index 0000000..ebedd3c
--- /dev/null
@@ -0,0 +1,148 @@
+/*     $NetBSD: refill.c,v 1.14 2010/09/10 10:29:23 drochner Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)refill.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: refill.c,v 1.14 2010/09/10 10:29:23 drochner Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef _REENTRANT
+extern rwlock_t __sfp_lock;
+#endif
+
+static int lflush __P((FILE *));
+
+static int
+lflush(fp)
+       FILE *fp;
+{
+
+       _DIAGASSERT(fp != NULL);
+
+       if ((fp->_flags & (__SLBF|__SWR)) == (__SLBF|__SWR))
+               return (__sflush(fp));
+       return (0);
+}
+
+/*
+ * Refill a stdio buffer.
+ * Return EOF on eof or error, 0 otherwise.
+ */
+int
+__srefill(fp)
+       FILE *fp;
+{
+
+       _DIAGASSERT(fp != NULL);
+
+       /* make sure stdio is set up */
+       if (!__sdidinit)
+               __sinit();
+
+       fp->_r = 0;             /* largely a convenience for callers */
+
+       /* SysV does not make this test; take it out for compatibility */
+       if (fp->_flags & __SEOF)
+               return (EOF);
+
+       /* if not already reading, have to be reading and writing */
+       if ((fp->_flags & __SRD) == 0) {
+               if ((fp->_flags & __SRW) == 0) {
+                       errno = EBADF;
+                       fp->_flags |= __SERR;
+                       return (EOF);
+               }
+               /* switch to reading */
+               if (fp->_flags & __SWR) {
+                       if (__sflush(fp))
+                               return (EOF);
+                       fp->_flags &= ~__SWR;
+                       fp->_w = 0;
+                       fp->_lbfsize = 0;
+               }
+               fp->_flags |= __SRD;
+       } else {
+               /*
+                * We were reading.  If there is an ungetc buffer,
+                * we must have been reading from that.  Drop it,
+                * restoring the previous buffer (if any).  If there
+                * is anything in that buffer, return.
+                */
+               if (HASUB(fp)) {
+                       FREEUB(fp);
+                       if ((fp->_r = fp->_ur) != 0) {
+                               fp->_p = fp->_up;
+                               return (0);
+                       }
+               }
+       }
+
+       if (fp->_bf._base == NULL)
+               __smakebuf(fp);
+
+       /*
+        * Before reading from a line buffered or unbuffered file,
+        * flush all line buffered output files, per the ANSI C
+        * standard.
+        */
+       if (fp->_flags & (__SLBF|__SNBF)) {
+               rwlock_rdlock(&__sfp_lock);
+               (void) _fwalk(lflush);
+               rwlock_unlock(&__sfp_lock);
+       }
+       fp->_p = fp->_bf._base;
+       fp->_r = (*fp->_read)(fp->_cookie, (char *)fp->_p, fp->_bf._size);
+       fp->_flags &= ~__SMOD;  /* buffer contents are again pristine */
+       if (fp->_r <= 0) {
+               if (fp->_r == 0)
+                       fp->_flags |= __SEOF;
+               else {
+                       fp->_r = 0;
+                       fp->_flags |= __SERR;
+               }
+               return (EOF);
+       }
+       return (0);
+}
diff --git a/lib/nbsd_libc/stdio/remove.3 b/lib/nbsd_libc/stdio/remove.3
new file mode 100644 (file)
index 0000000..17895c3
--- /dev/null
@@ -0,0 +1,87 @@
+.\"    $NetBSD: remove.3,v 1.12 2003/08/07 16:43:30 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)remove.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt REMOVE 3
+.Os
+.Sh NAME
+.Nm remove
+.Nd remove directory entry
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft int
+.Fn remove "const char *path"
+.Sh DESCRIPTION
+The
+.Fn remove
+function removes the file or directory specified by
+.Fa path .
+.Pp
+If
+.Fa path
+specifies a directory,
+.Fn remove "path"
+is the equivalent of
+.Fn rmdir "path" .
+Otherwise, it is the equivalent of
+.Fn unlink "path" .
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn remove
+returns 0.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn remove
+function
+may fail and set
+.Va errno
+for any of the errors specified for the routines
+.Xr rmdir 2
+or
+.Xr unlink 2 .
+.Sh SEE ALSO
+.Xr rmdir 2 ,
+.Xr unlink 2 ,
+.Xr symlink 7
+.Sh STANDARDS
+The
+.Fn remove
+function conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdio/remove.c b/lib/nbsd_libc/stdio/remove.c
new file mode 100644 (file)
index 0000000..f006cd5
--- /dev/null
@@ -0,0 +1,71 @@
+/*     $NetBSD: remove.c,v 1.13 2003/08/07 16:43:30 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)remove.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: remove.c,v 1.13 2003/08/07 16:43:30 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <unistd.h>
+
+int
+remove(file)
+       const char *file;
+{
+       struct stat sb;
+
+       _DIAGASSERT(file != NULL);
+
+       if (lstat(file, &sb) < 0)
+               return (-1);
+
+       /*
+        * The file system may prohibit using unlink(2) on directories,
+        * so always use rmdir(2) in that case.
+        */
+       if (S_ISDIR(sb.st_mode))
+               return (rmdir(file));
+       else
+               return (unlink(file));
+}
diff --git a/lib/nbsd_libc/stdio/rewind.c b/lib/nbsd_libc/stdio/rewind.c
new file mode 100644 (file)
index 0000000..899ec58
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: rewind.c,v 1.13 2003/08/07 16:43:30 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)rewind.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: rewind.c,v 1.13 2003/08/07 16:43:30 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+void
+rewind(fp)
+       FILE *fp;
+{
+
+       _DIAGASSERT(fp != NULL);
+
+       FLOCKFILE(fp);
+       (void) fseek(fp, 0L, SEEK_SET);
+       __sclearerr(fp);
+       FUNLOCKFILE(fp);
+}
diff --git a/lib/nbsd_libc/stdio/rget.c b/lib/nbsd_libc/stdio/rget.c
new file mode 100644 (file)
index 0000000..26a871d
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: rget.c,v 1.12 2003/08/07 16:43:30 agc Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)rget.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: rget.c,v 1.12 2003/08/07 16:43:30 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * Handle getc() when the buffer ran out:
+ * Refill, then return the first character
+ * in the newly-filled buffer.
+ */
+int
+__srget(fp)
+       FILE *fp;
+{
+
+       _DIAGASSERT(fp != NULL);
+
+       _SET_ORIENTATION(fp, -1);
+       if (__srefill(fp) == 0) {
+               fp->_r--;
+               return (*fp->_p++);
+       }
+       return (EOF);
+}
diff --git a/lib/nbsd_libc/stdio/scanf.3 b/lib/nbsd_libc/stdio/scanf.3
new file mode 100644 (file)
index 0000000..2da8999
--- /dev/null
@@ -0,0 +1,478 @@
+.\"    $NetBSD: scanf.3,v 1.27 2010/05/14 03:04:32 joerg Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)scanf.3    8.2 (Berkeley) 12/11/93
+.\"
+.Dd March 21, 2010
+.Dt SCANF 3
+.Os
+.Sh NAME
+.Nm scanf ,
+.Nm fscanf ,
+.Nm sscanf ,
+.Nm vscanf ,
+.Nm vsscanf ,
+.Nm vfscanf
+.Nd input format conversion
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft int
+.Fn scanf "const char * restrict format" ...
+.Ft int
+.Fn fscanf "FILE * restrict stream" "const char * restrict format" ...
+.Ft int
+.Fn sscanf "const char * restrict str" "const char * restrict format" ...
+.In stdarg.h
+.Ft int
+.Fn vscanf "const char * restrict format" "va_list ap"
+.Ft int
+.Fn vsscanf "const char * restrict str" "const char * restrict format" "va_list ap"
+.Ft int
+.Fn vfscanf "FILE * restrict stream" "const char * restrict format" "va_list ap"
+.Sh DESCRIPTION
+The
+.Fn scanf
+family of functions scans input according to a
+.Fa format
+as described below.
+This format may contain
+.Em conversion specifiers ;
+the results from such conversions, if any,
+are stored through the
+.Em pointer
+arguments.
+.Pp
+The
+.Fn scanf
+function
+reads input from the standard input stream
+.Em stdin ,
+.Fn fscanf
+reads input from the stream pointer
+.Fa stream ,
+and
+.Fn sscanf
+reads its input from the character string pointed to by
+.Fa str .
+The
+.Fn vfscanf
+function
+is analogous to
+.Xr vfprintf 3
+and reads input from the stream pointer
+.Fa stream
+using a variable argument list of pointers (see
+.Xr stdarg 3 ) .
+The
+.Fn vscanf
+function scans a variable argument list from the standard input and
+the
+.Fn vsscanf
+function scans it from a string;
+these are analogous to
+the
+.Fn vprintf
+and
+.Fn vsprintf
+functions respectively.
+.Pp
+Each successive
+.Em pointer
+argument must correspond properly with
+each successive conversion specifier
+(but see `suppression' below).
+All conversions are introduced by the
+.Cm %
+(percent sign) character.
+The
+.Fa format
+string
+may also contain other characters.
+White space (such as blanks, tabs, or newlines) in the
+.Fa format
+string match any amount of white space, including none, in the input.
+Everything else
+matches only itself.
+Scanning stops
+when an input character does not match such a format character.
+Scanning also stops
+when an input conversion cannot be made (see below).
+.Sh CONVERSIONS
+Following the
+.Cm %
+character introducing a conversion
+there may be a number of
+.Em flag
+characters, as follows:
+.Bl -tag -width indent
+.It Cm *
+Suppresses assignment.
+The conversion that follows occurs as usual, but no pointer is used;
+the result of the conversion is simply discarded.
+.It Cm h
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Em short int
+(rather than
+.Em int ) .
+.It Cm hh
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Em char
+(rather than
+.Em int ) .
+.It Cm j
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to an
+.Em intmax_t
+(rather than
+.Em int ) .
+.It Cm l
+Indicates either that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Em long int
+(rather than
+.Em int ) ,
+or that the conversion will be one of
+.Cm efg
+and the next pointer is a pointer to
+.Em double
+(rather than
+.Em float ) .
+.It Cm ll
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Em long long int
+(rather than
+.Em int ) .
+.It Cm q
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Em quad_t
+(rather than
+.Em int ) .
+.It Cm t
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Em ptrdiff_t
+(rather than
+.Em int ) .
+.It Cm z
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Em size_t
+(rather than
+.Em int ) .
+.It Cm L
+Indicates that the conversion will be
+.Cm efg
+and the next pointer is a pointer to
+.Em long double .
+.El
+.Pp
+In addition to these flags,
+there may be an optional maximum field width,
+expressed as a decimal integer,
+between the
+.Cm %
+and the conversion.
+If no width is given,
+a default of `infinity' is used (with one exception, below);
+otherwise at most this many characters are scanned
+in processing the conversion.
+Before conversion begins,
+most conversions skip white space;
+this white space is not counted against the field width.
+.Pp
+The following conversions are available:
+.Bl -tag -width XXXX
+.It Cm %
+Matches a literal `%'.
+That is, `%\&%' in the format string
+matches a single input `%' character.
+No conversion is done, and assignment does not occur.
+.It Cm d
+Matches an optionally signed decimal integer;
+the next pointer must be a pointer to
+.Em int .
+.It Cm D
+Equivalent to
+.Cm ld ;
+this exists only for backwards compatibility.
+.It Cm i
+Matches an optionally signed integer;
+the next pointer must be a pointer to
+.Em int .
+The integer is read in base 16 if it begins
+with
+.Ql 0x
+or
+.Ql 0X ,
+in base 8 if it begins with
+.Ql 0 ,
+and in base 10 otherwise.
+Only characters that correspond to the base are used.
+.It Cm o
+Matches an octal integer;
+the next pointer must be a pointer to
+.Em unsigned int .
+.It Cm O
+Equivalent to
+.Cm lo ;
+this exists for backwards compatibility.
+.It Cm u
+Matches an optionally signed decimal integer;
+the next pointer must be a pointer to
+.Em unsigned int .
+.It Cm x
+Matches an optionally signed hexadecimal integer;
+the next pointer must be a pointer to
+.Em unsigned int .
+.It Cm X
+Equivalent to
+.Cm x .
+.It Cm f
+Matches an optionally signed floating-point number;
+the next pointer must be a pointer to
+.Em float .
+.It Cm e
+Equivalent to
+.Cm f .
+.It Cm g
+Equivalent to
+.Cm f .
+.It Cm E
+Equivalent to
+.Cm f .
+.It Cm G
+Equivalent to
+.Cm f .
+.It Cm s
+Matches a sequence of non-white-space characters;
+the next pointer must be a pointer to
+.Em char ,
+and the array must be large enough to accept all the sequence and the
+terminating
+.Dv NUL
+character.
+The input string stops at white space
+or at the maximum field width, whichever occurs first.
+.It Cm c
+Matches a sequence of
+.Em width
+count
+characters (default 1);
+the next pointer must be a pointer to
+.Em char ,
+and there must be enough room for all the characters
+(no terminating
+.Dv NUL
+is added).
+The usual skip of leading white space is suppressed.
+To skip white space first, use an explicit space in the format.
+.It Cm \&[
+Matches a nonempty sequence of characters from the specified set
+of accepted characters;
+the next pointer must be a pointer to
+.Em char ,
+and there must be enough room for all the characters in the string,
+plus a terminating
+.Dv NUL
+character.
+The usual skip of leading white space is suppressed.
+The string is to be made up of characters in
+(or not in)
+a particular set;
+the set is defined by the characters between the open bracket
+.Cm \&[
+character
+and a close bracket
+.Cm \&]
+character.
+The set
+.Em excludes
+those characters
+if the first character after the open bracket is a circumflex
+.Cm ^ .
+To include a close bracket in the set,
+make it the first character after the open bracket
+or the circumflex;
+any other position will end the set.
+The hyphen character
+.Cm -
+is also special;
+when placed between two other characters,
+it adds all intervening characters to the set.
+To include a hyphen,
+make it the last character before the final close bracket.
+For instance,
+.Ql [^]0-9-]
+means the set `everything except close bracket, zero through nine,
+and hyphen'.
+The string ends with the appearance of a character not in the
+(or, with a circumflex, in) set
+or when the field width runs out.
+.It Cm p
+Matches a pointer value (as printed by
+.Ql %p
+in
+.Xr printf 3 ) ;
+the next pointer must be a pointer to
+.Em void .
+.It Cm n
+Nothing is expected;
+instead, the number of characters consumed thus far from the input
+is stored through the next pointer,
+which must be a pointer to
+.Em int .
+This is
+.Em not
+a conversion, although it can be suppressed with the
+.Cm *
+flag.
+.El
+.Pp
+For backwards compatibility,
+other conversion characters (except
+.Ql \e0 )
+are taken as if they were
+.Ql %d
+or, if uppercase,
+.Ql %ld ,
+and a `conversion' of
+.Ql %\e0
+causes an immediate return of
+.Dv EOF .
+.Pp
+The format string specifier macros described in
+.Xr inttypes 3
+should be used for the standard
+.Dq C99
+fixed-size integers documented in
+.Xr stdint 3 .
+.Sh RETURN VALUES
+These
+functions
+return
+the number of input items assigned, which can be fewer than provided
+for, or even zero, in the event of a matching failure.
+Zero
+indicates that, while there was input available,
+no conversions were assigned;
+typically this is due to an invalid input character,
+such as an alphabetic character for a
+.Ql %d
+conversion.
+The value
+.Dv EOF
+is returned if an input failure occurs before any conversion such as an
+end-of-file occurs.
+If an error or end-of-file occurs after conversion has begun,
+the number of conversions which were successfully completed is returned.
+.Sh SEE ALSO
+.Xr getc 3 ,
+.Xr inttypes 3 ,
+.Xr printf 3 ,
+.Xr strtod 3 ,
+.Xr strtol 3 ,
+.Xr strtoul 3
+.Sh STANDARDS
+The functions
+.Fn fscanf ,
+.Fn scanf ,
+and
+.Fn sscanf
+conform to
+.St -isoC-90 .
+The
+.Cm %j ,
+.Cm %t
+and
+.Cm %z
+conversion format modifiers
+conform to
+.St -isoC-99 .
+The
+.Fn vfscanf ,
+.Fn vscanf
+and
+.Fn vsscanf
+functions conform to
+.St -isoC-99 .
+.Sh HISTORY
+The functions
+.Fn vscanf ,
+.Fn vsscanf
+and
+.Fn vfscanf
+appeared in
+.Bx 4.4
+or even
+.Bx 4.3 .
+.Sh NOTES
+All of the backwards compatibility formats will be removed in the future.
+.Sh BUGS
+Numerical strings are truncated to 512 characters; for example,
+.Cm %f
+and
+.Cm %d
+are implicitly
+.Cm %512f
+and
+.Cm %512d .
diff --git a/lib/nbsd_libc/stdio/scanf.c b/lib/nbsd_libc/stdio/scanf.c
new file mode 100644 (file)
index 0000000..1fbf753
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: scanf.c,v 1.12 2003/08/07 16:43:31 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)scanf.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: scanf.c,v 1.12 2003/08/07 16:43:31 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stdio.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+int
+scanf(char const *fmt, ...)
+{
+       int ret;
+       va_list ap;
+
+       _DIAGASSERT(fmt != NULL);
+
+       va_start(ap, fmt);
+       ret = __svfscanf(stdin, fmt, ap);
+       va_end(ap);
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/setbuf.3 b/lib/nbsd_libc/stdio/setbuf.3
new file mode 100644 (file)
index 0000000..3fdac7f
--- /dev/null
@@ -0,0 +1,202 @@
+.\"    $NetBSD: setbuf.3,v 1.13 2003/08/07 16:43:31 agc Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)setbuf.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt SETBUF 3
+.Os
+.Sh NAME
+.Nm setbuf ,
+.Nm setbuffer ,
+.Nm setlinebuf ,
+.Nm setvbuf
+.Nd stream buffering operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft void
+.Fn setbuf "FILE * restrict stream" "char * restrict buf"
+.Ft void
+.Fn setbuffer "FILE *stream" "char *buf" "size_t size"
+.Ft int
+.Fn setlinebuf "FILE *stream"
+.Ft int
+.Fn setvbuf "FILE * restrict stream" "char * restrict buf" "int mode" "size_t size"
+.Sh DESCRIPTION
+The three types of buffering available are unbuffered, block buffered,
+and line buffered.
+When an output stream is unbuffered, information appears on the
+destination file or terminal as soon as written;
+when it is block buffered many characters are saved up and written as a block;
+when it is line buffered characters are saved up until a newline is
+output or input is read from any stream attached to a terminal device
+(typically stdin).
+The function
+.Xr fflush 3
+may be used to force the block out early.
+(See
+.Xr fclose 3 . )
+.Pp
+Normally all files are block buffered.
+When the first
+.Tn I/O
+operation occurs on a file,
+.Xr malloc 3
+is called,
+and an optimally-sized buffer is obtained.
+If a stream refers to a terminal
+(as
+.Em stdout
+normally does) it is line buffered.
+The standard error stream
+.Em stderr
+is initially unbuffered.
+.Pp
+The
+.Fn setvbuf
+function
+may be used to alter the buffering behavior of a stream.
+The
+.Fa mode
+parameter must be one of the following three macros:
+.Bl -tag -width _IOFBF -offset indent
+.It Dv _IONBF
+unbuffered
+.It Dv _IOLBF
+line buffered
+.It Dv _IOFBF
+fully buffered
+.El
+.Pp
+The
+.Fa size
+parameter may be given as zero
+to obtain deferred optimal-size buffer allocation as usual.
+If it is not zero,
+then except for unbuffered files, the
+.Fa buf
+argument should point to a buffer at least
+.Fa size
+bytes long;
+this buffer will be used instead of the current buffer.
+(If the
+.Fa size
+argument
+is not zero but
+.Fa buf
+is
+.Dv NULL ,
+a buffer of the given size will be allocated immediately,
+and released on close.
+This is an extension to ANSI C;
+portable code should use a size of 0 with any
+.Dv NULL
+buffer.)
+.Pp
+The
+.Fn setvbuf
+function may be used at any time,
+but may have peculiar side effects
+(such as discarding input or flushing output)
+if the stream is ``active''.
+Portable applications should call it only once on any given stream,
+and before any
+.Tn I/O
+is performed.
+.Pp
+The other three calls are, in effect, simply aliases for calls to
+.Fn setvbuf .
+Except for the lack of a return value, the
+.Fn setbuf
+function is exactly equivalent to the call
+.Pp
+.Dl "setvbuf(stream, buf, buf ? _IOFBF : _IONBF, BUFSIZ);"
+.Pp
+The
+.Fn setbuffer
+function
+is the same, except that the size of the buffer is up to the caller,
+rather than being determined by the default
+.Dv BUFSIZ .
+The
+.Fn setlinebuf
+function
+is exactly equivalent to the call:
+.Pp
+.Dl "setvbuf(stream, (char *)NULL, _IOLBF, 0);"
+.Sh RETURN VALUES
+The
+.Fn setvbuf
+function returns 0 on success, or
+.Dv EOF
+if the request cannot be honored
+(note that the stream is still functional in this case).
+.Pp
+The
+.Fn setlinebuf
+function returns what the equivalent
+.Fn setvbuf
+would have returned.
+.Sh SEE ALSO
+.Xr fclose 3 ,
+.Xr fopen 3 ,
+.Xr fread 3 ,
+.Xr malloc 3 ,
+.Xr printf 3 ,
+.Xr puts 3
+.Sh STANDARDS
+The
+.Fn setbuf
+and
+.Fn setvbuf
+functions
+conform to
+.St -ansiC .
+.Sh BUGS
+The
+.Fn setbuffer
+and
+.Fn setlinebuf
+functions are not portable to versions of
+.Bx
+before
+.Bx 4.2 .
+On
+.Bx 4.2
+and
+.Bx 4.3
+systems,
+.Fn setbuf
+always uses a suboptimal buffer size and should be avoided.
diff --git a/lib/nbsd_libc/stdio/setbuf.c b/lib/nbsd_libc/stdio/setbuf.c
new file mode 100644 (file)
index 0000000..08c23c0
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: setbuf.c,v 1.9 2003/08/07 16:43:31 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)setbuf.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: setbuf.c,v 1.9 2003/08/07 16:43:31 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+void
+setbuf(fp, buf)
+       FILE *fp;
+       char *buf;
+{
+
+       _DIAGASSERT(fp != NULL);
+       /* buf may be NULL */
+
+       (void) setvbuf(fp, buf, buf ? _IOFBF : _IONBF, BUFSIZ);
+}
diff --git a/lib/nbsd_libc/stdio/setbuffer.c b/lib/nbsd_libc/stdio/setbuffer.c
new file mode 100644 (file)
index 0000000..6ef5b35
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: setbuffer.c,v 1.12 2009/10/25 20:44:13 christos Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)setbuffer.c        8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: setbuffer.c,v 1.12 2009/10/25 20:44:13 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+
+void
+setbuffer(fp, buf, size)
+       FILE *fp;
+       char *buf;
+       int size;
+{
+
+       _DIAGASSERT(fp != NULL);
+       /* buf may be NULL */
+
+       (void)setvbuf(fp, buf, buf ? _IOFBF : _IONBF, (size_t)size);
+}
+
+/*
+ * set line buffering
+ */
+int
+setlinebuf(fp)
+       FILE *fp;
+{
+
+       _DIAGASSERT(fp != NULL);
+
+       return (setvbuf(fp, NULL, _IOLBF, (size_t)0));
+}
diff --git a/lib/nbsd_libc/stdio/setvbuf.c b/lib/nbsd_libc/stdio/setvbuf.c
new file mode 100644 (file)
index 0000000..957e043
--- /dev/null
@@ -0,0 +1,175 @@
+/*     $NetBSD: setvbuf.c,v 1.17 2003/08/07 16:43:31 agc Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)setvbuf.c  8.2 (Berkeley) 11/16/93";
+#else
+__RCSID("$NetBSD: setvbuf.c,v 1.17 2003/08/07 16:43:31 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * Set one of the three kinds of buffering, optionally including
+ * a buffer.
+ */
+int
+setvbuf(fp, buf, mode, size)
+       FILE *fp;
+       char *buf;
+       int mode;
+       size_t size;
+{
+       int ret, flags;
+       size_t iosize;
+       int ttyflag;
+
+       _DIAGASSERT(fp != NULL);
+       /* buf may be NULL */
+
+       /*
+        * Verify arguments.  The `int' limit on `size' is due to this
+        * particular implementation.  Note, buf and size are ignored
+        * when setting _IONBF.
+        */
+       if (mode != _IONBF)
+               if ((mode != _IOFBF && mode != _IOLBF) || (int)size < 0)
+                       return (-1);
+
+       FLOCKFILE(fp);
+       /*
+        * Write current buffer, if any.  Discard unread input (including
+        * ungetc data), cancel line buffering, and free old buffer if
+        * malloc()ed.  We also clear any eof condition, as if this were
+        * a seek.
+        */
+       ret = 0;
+       (void)__sflush(fp);
+       if (HASUB(fp))
+               FREEUB(fp);
+       WCIO_FREE(fp);
+       fp->_r = fp->_lbfsize = 0;
+       flags = fp->_flags;
+       if (flags & __SMBF)
+               free((void *)fp->_bf._base);
+       flags &= ~(__SLBF | __SNBF | __SMBF | __SOPT | __SNPT | __SEOF);
+
+       /* If setting unbuffered mode, skip all the hard work. */
+       if (mode == _IONBF)
+               goto nbf;
+
+       /*
+        * Find optimal I/O size for seek optimization.  This also returns
+        * a `tty flag' to suggest that we check isatty(fd), but we do not
+        * care since our caller told us how to buffer.
+        */
+       flags |= __swhatbuf(fp, &iosize, &ttyflag);
+       if (size == 0) {
+               buf = NULL;     /* force local allocation */
+               size = iosize;
+       }
+
+       /* Allocate buffer if needed. */
+       if (buf == NULL) {
+               if ((buf = malloc(size)) == NULL) {
+                       /*
+                        * Unable to honor user's request.  We will return
+                        * failure, but try again with file system size.
+                        */
+                       ret = -1;
+                       if (size != iosize) {
+                               size = iosize;
+                               buf = malloc(size);
+                       }
+               }
+               if (buf == NULL) {
+                       /* No luck; switch to unbuffered I/O. */
+nbf:
+                       fp->_flags = flags | __SNBF;
+                       fp->_w = 0;
+                       fp->_bf._base = fp->_p = fp->_nbuf;
+                       fp->_bf._size = 1;
+                       FUNLOCKFILE(fp);
+                       return (ret);
+               }
+               flags |= __SMBF;
+       }
+
+       /*
+        * Kill any seek optimization if the buffer is not the
+        * right size.
+        *
+        * SHOULD WE ALLOW MULTIPLES HERE (i.e., ok iff (size % iosize) == 0)?
+        */
+       if (size != iosize)
+               flags |= __SNPT;
+
+       /*
+        * Fix up the FILE fields, and set __cleanup for output flush on
+        * exit (since we are buffered in some way).
+        */
+       if (mode == _IOLBF)
+               flags |= __SLBF;
+       fp->_flags = flags;
+       fp->_bf._base = fp->_p = (unsigned char *)buf;
+       fp->_bf._size = size;
+       /* fp->_lbfsize is still 0 */
+       if (flags & __SWR) {
+               /*
+                * Begin or continue writing: see __swsetup().  Note
+                * that __SNBF is impossible (it was handled earlier).
+                */
+               if (flags & __SLBF) {
+                       fp->_w = 0;
+                       fp->_lbfsize = -fp->_bf._size;
+               } else
+                       fp->_w = size;
+       } else {
+               /* begin/continue reading, or stay in intermediate state */
+               fp->_w = 0;
+       }
+       __cleanup = _cleanup;
+
+       FUNLOCKFILE(fp);
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/snprintf.c b/lib/nbsd_libc/stdio/snprintf.c
new file mode 100644 (file)
index 0000000..a3f59fe
--- /dev/null
@@ -0,0 +1,94 @@
+/*     $NetBSD: snprintf.c,v 1.22 2007/10/26 19:48:14 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)snprintf.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: snprintf.c,v 1.22 2007/10/26 19:48:14 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stdio.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+#if defined(_FORTIFY_SOURCE) && !defined(__lint__)
+#undef snprintf
+#define snprintf _snprintf
+#endif
+
+#ifdef __weak_alias
+__weak_alias(snprintf,_snprintf)
+#endif
+
+int
+snprintf(char *str, size_t n, char const *fmt, ...)
+{
+       int ret;
+       va_list ap;
+       FILE f;
+       struct __sfileext fext;
+       unsigned char dummy[1];
+
+       _DIAGASSERT(n == 0 || str != NULL);
+       _DIAGASSERT(fmt != NULL);
+
+       if ((int)n < 0) {
+               errno = EINVAL;
+               return (-1);
+       }
+       va_start(ap, fmt);
+       _FILEEXT_SETUP(&f, &fext);
+       f._file = -1;
+       f._flags = __SWR | __SSTR;
+       if (n == 0) {
+               f._bf._base = f._p = dummy;
+               f._bf._size = f._w = 0;
+       } else {
+               f._bf._base = f._p = (unsigned char *)str;
+               f._bf._size = f._w = n - 1;
+       }
+       ret = __vfprintf_unlocked(&f, fmt, ap);
+       *f._p = 0;
+       va_end(ap);
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/snprintf_ss.c b/lib/nbsd_libc/stdio/snprintf_ss.c
new file mode 100644 (file)
index 0000000..32d004b
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: snprintf_ss.c,v 1.4 2007/02/02 23:00:28 christos Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)snprintf.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: snprintf_ss.c,v 1.4 2007/02/02 23:00:28 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stdio.h>
+
+#include "reentrant.h"
+#include "extern.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(snprintf_ss,_snprintf_ss)
+#endif
+
+int
+snprintf_ss(char *str, size_t n, char const *fmt, ...)
+{
+       va_list ap;
+       int ret;
+
+       va_start(ap, fmt);
+       ret = vsnprintf_ss(str, n, fmt, ap);
+       va_end(ap);
+       return ret;
+}
diff --git a/lib/nbsd_libc/stdio/sprintf.c b/lib/nbsd_libc/stdio/sprintf.c
new file mode 100644 (file)
index 0000000..8045e9c
--- /dev/null
@@ -0,0 +1,78 @@
+/*     $NetBSD: sprintf.c,v 1.15 2007/06/03 17:39:26 christos Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)sprintf.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: sprintf.c,v 1.15 2007/06/03 17:39:26 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdarg.h>
+#include <stdio.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef _FORTIFY_SOURCE
+#undef sprintf
+#endif
+
+int
+sprintf(char *str, char const *fmt, ...)
+{
+       int ret;
+       va_list ap;
+       FILE f;
+       struct __sfileext fext;
+
+       _DIAGASSERT(str != NULL);
+       _DIAGASSERT(fmt != NULL);
+
+       _FILEEXT_SETUP(&f, &fext);
+       f._file = -1;
+       f._flags = __SWR | __SSTR;
+       f._bf._base = f._p = (unsigned char *)str;
+       f._bf._size = f._w = INT_MAX;
+       va_start(ap, fmt);
+       ret = __vfprintf_unlocked(&f, fmt, ap);
+       va_end(ap);
+       *f._p = 0;
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/sscanf.c b/lib/nbsd_libc/stdio/sscanf.c
new file mode 100644 (file)
index 0000000..42463ff
--- /dev/null
@@ -0,0 +1,87 @@
+/*     $NetBSD: sscanf.c,v 1.17 2010/01/11 20:39:29 joerg Exp $        */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)sscanf.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: sscanf.c,v 1.17 2010/01/11 20:39:29 joerg Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+static int eofread __P((void *, char *, int));
+
+/* ARGSUSED */
+static int
+eofread(cookie, buf, len)
+       void *cookie;
+       char *buf;
+       int len;
+{
+
+       return (0);
+}
+
+int
+sscanf(const char *str, char const *fmt, ...)
+{
+       int ret;
+       va_list ap;
+       FILE f;
+       struct __sfileext fext;
+
+       _DIAGASSERT(str != NULL);
+       _DIAGASSERT(fmt != NULL);
+
+       _FILEEXT_SETUP(&f, &fext);
+       f._flags = __SRD;
+       f._bf._base = f._p = __UNCONST(str);
+       f._bf._size = f._r = strlen(str);
+       f._read = eofread;
+       _UB(&f)._base = NULL;
+       va_start(ap, fmt);
+       ret = __svfscanf_unlocked(&f, fmt, ap);
+       va_end(ap);
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/stdio.3 b/lib/nbsd_libc/stdio/stdio.3
new file mode 100644 (file)
index 0000000..eff53c8
--- /dev/null
@@ -0,0 +1,320 @@
+.\"    $NetBSD: stdio.3,v 1.24 2010/05/05 04:13:16 jruoho Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)stdio.3    8.7 (Berkeley) 4/19/94
+.\"
+.Dd May 5, 2010
+.Dt STDIO 3
+.Os
+.Sh NAME
+.Nm stdio
+.Nd standard input/output library functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Vt FILE *stdin;
+.Vt FILE *stdout;
+.Vt FILE *stderr;
+.Sh DESCRIPTION
+The standard
+.Tn I/O
+library provides a simple and efficient buffered stream
+.Tn I/O
+interface.
+Input and output is mapped into logical data streams
+and the physical
+.Tn I/O
+characteristics are concealed.
+.Pp
+A stream is associated with an external file (which may be a physical
+device) by
+.Em opening
+a file, which may involve creating a new file.
+Creating an existing file causes its former contents to be discarded.
+If a file can support positioning requests (such as a disk file, as opposed
+to a terminal) then a
+.Em file position indicator
+associated with the stream is positioned at the start of the file (byte
+zero), unless the file is opened with append mode.
+If append mode
+is used, the position indicator will be placed the end-of-file.
+The position indicator is maintained by subsequent reads, writes
+and positioning requests.
+All input occurs as if the characters
+were read by successive calls to the
+.Xr fgetc 3
+function; all output takes place as if all characters were
+read by successive calls to the
+.Xr fputc 3
+function.
+.Pp
+A file is disassociated from a stream by
+.Em closing
+the file.
+Output streams are flushed (any unwritten buffer contents are transferred
+to the host environment) before the stream is disassociated from the file.
+The value of a pointer to a
+.Dv FILE
+object is indeterminate after a file is closed (garbage).
+.Pp
+A file may be subsequently reopened, by the same or another program
+execution, and its contents reclaimed or modified (if it can be repositioned
+at the start).
+If the main function returns to its original caller, or the
+.Xr exit 3
+function is called, all open files are closed (hence all output
+streams are flushed) before program termination.
+Other methods of program termination, such as
+.Xr abort 3
+do not bother about closing files properly.
+.Pp
+This implementation needs and makes
+no distinction between
+.Dq text
+and
+.Dq binary
+streams.
+In effect, all streams are binary.
+No translation is performed and no extra padding appears on any stream.
+.Pp
+At program startup, three streams are predefined and need not be
+opened explicitly:
+.Bl -enum -offset indent
+.It
+.Em standard input
+for reading conventional input,
+.It
+.Em standard output
+for writing conventional output, and
+.It
+.Em standard error
+for writing diagnostic output.
+.El
+.Pp
+These streams are abbreviated
+.Em stdin ,
+.Em stdout ,
+and
+.Em stderr .
+.Pp
+Initially, the standard error stream
+is unbuffered; the standard input and output streams are
+fully buffered if and only if the streams do not refer to
+an interactive or
+.Dq terminal
+device, as determined by the
+.Xr isatty 3
+function.
+In fact,
+.Em all
+freshly-opened streams that refer to terminal devices
+default to line buffering, and
+pending output to such streams is written automatically
+whenever an such an input stream is read.
+Note that this applies only to
+.Dq "true reads" ;
+if the read request can be satisfied by existing buffered data,
+no automatic flush will occur.
+In these cases,
+or when a large amount of computation is done after printing
+part of a line on an output terminal, it is necessary to
+.Xr fflush 3
+the standard output before going off and computing so that the output
+will appear.
+Alternatively, these defaults may be modified via the
+.Xr setvbuf 3
+function.
+.Sh IMPLEMENTATION NOTES
+In multi-threaded applications, operations on streams perform implicit
+locking, except for the
+.Fn getc_unlocked ,
+.Fn getchar_unlocked ,
+.Fn putc_unlocked ,
+and
+.Fn putchar_unlocked
+functions.
+Explicit control of stream locking is available through the
+.Fn flockfile ,
+.Fn ftrylockfile ,
+and
+.Fn funlockfile
+functions .
+.Pp
+The following are defined as macros; these names may not be re-used
+without first removing their current definitions with
+.Dv #undef :
+.Dv BUFSIZ ,
+.Dv EOF ,
+.Dv FILENAME_MAX ,
+.Dv FOPEN_MAX ,
+.Dv L_cuserid ,
+.Dv L_ctermid ,
+.Dv L_tmpnam ,
+.Dv NULL ,
+.Dv SEEK_END ,
+.Dv SEEK_SET ,
+.Dv SEE_CUR ,
+.Dv TMP_MAX ,
+.Fn clearerr ,
+.Fn feof ,
+.Fn ferror ,
+.Fn fileno ,
+.Fn freopen ,
+.Fn fwopen ,
+.Fn getc ,
+.Fn getc_unlocked ,
+.Fn getchar ,
+.Fn getchar_unlocked ,
+.Fn putc ,
+.Fn putc_unlocked ,
+.Fn putchar ,
+.Fn putchar_unlocked ,
+.Dv stderr ,
+.Dv stdin ,
+.Dv stdout .
+.Pp
+Function versions of the macro functions
+.Fn feof ,
+.Fn ferror ,
+.Fn clearerr ,
+.Fn fileno ,
+.Fn getc ,
+.Fn getc_unlocked ,
+.Fn getchar ,
+.Fn getchar_unlocked ,
+.Fn putc ,
+.Fn putc_unlocked ,
+.Fn putchar ,
+and
+.Fn putchar_unlocked
+exist and will be used if the macros definitions are explicitly removed.
+.Sh SEE ALSO
+.Xr close 2 ,
+.Xr open 2 ,
+.Xr read 2 ,
+.Xr write 2
+.Sh STANDARDS
+The
+.Nm
+library conforms to
+.St -ansiC .
+.Sh LIST OF FUNCTIONS
+.Bl -column "putchar_unlocked" "Description"
+.It Sy Function        Description
+.It clearerr   check and reset stream status
+.It fclose     close a stream
+.It fdopen     stream open functions
+.It feof       check and reset stream status
+.It ferror     check and reset stream status
+.It fflush     flush a stream
+.It fgetc      get next character or word from input stream
+.It fgetln     get a line from a stream
+.It fgetpos    reposition a stream
+.It fgets      get a line from a stream
+.It fgetwc     get next wide character from input stream
+.It fileno     check and reset stream status
+.It flockfile  lock a stream
+.It fopen      stream open functions
+.It fprintf    formatted output conversion
+.It fpurge     flush a stream
+.It fputc      output a character or word to a stream
+.It fputs      output a line to a stream
+.It fputwc     output a wide character to a stream
+.It fread      binary stream input/output
+.It freopen    stream open functions
+.It fropen     open a stream
+.It fscanf     input format conversion
+.It fseek      reposition a stream
+.It fsetpos    reposition a stream
+.It ftell      reposition a stream
+.It ftrylockfile       lock a stream (non-blocking)
+.It funlockfile        unlock a stream
+.It funopen    open a stream
+.It fwide      set/get orientation of a stream
+.It fwopen     open a stream
+.It fwrite     binary stream input/output
+.It getc       get next character or word from input stream
+.It getc_unlocked      get next character or word from input stream
+.It             Ta (no implicit locking)
+.It getchar    get next character or word from input stream
+.It getchar_unlocked   get next character or word from input stream
+.It             Ta (no implicit locking)
+.It getdelim   get a delimited record from a stream
+.It getline    get a line from a stream
+.It gets       get a line from a stream
+.It getw       get next character or word from input stream
+.It getwc      get next wide character from input stream
+.It getwchar   get next wide character from input stream
+.It mkstemp    create unique temporary file
+.It mktemp     create unique temporary file
+.It perror     system error messages
+.It printf     formatted output conversion
+.It putc       output a character or word to a stream
+.It putc_unlocked      output a character or word to a stream
+.It             Ta (no implicit locking)
+.It putchar    output a character or word to a stream
+.It putchar_unlocked   output a character or word to a stream
+.It             Ta (no implicit locking)
+.It puts       output a line to a stream
+.It putw       output a character or word to a stream
+.It putwc      output a wide character to a stream
+.It putwchar   output a wide character to a stream
+.It remove     remove directory entry
+.It rewind     reposition a stream
+.It scanf      input format conversion
+.It setbuf     stream buffering operations
+.It setbuffer  stream buffering operations
+.It setlinebuf stream buffering operations
+.It setvbuf    stream buffering operations
+.It snprintf   formatted output conversion
+.It sprintf    formatted output conversion
+.It sscanf     input format conversion
+.It strerror   system error messages
+.It sys_errlist        system error messages
+.It sys_nerr   system error messages
+.It tempnam    temporary file routines
+.It tmpfile    temporary file routines
+.It tmpnam     temporary file routines
+.It ungetc     un-get character from input stream
+.It ungetwc    un-get wide character from input stream
+.It vfprintf   formatted output conversion
+.It vfscanf    input format conversion
+.It vprintf    formatted output conversion
+.It vscanf     input format conversion
+.It vsnprintf  formatted output conversion
+.It vsprintf   formatted output conversion
+.It vsscanf    input format conversion
+.El
+.Sh BUGS
+The standard buffered functions do not interact well with certain other
+library and system functions, especially
+.Xr vfork 2
+and
+.Xr abort 3 .
diff --git a/lib/nbsd_libc/stdio/stdio.c b/lib/nbsd_libc/stdio/stdio.c
new file mode 100644 (file)
index 0000000..8c1849e
--- /dev/null
@@ -0,0 +1,126 @@
+/*     $NetBSD: stdio.c,v 1.16 2009/10/25 20:44:13 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)stdio.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: stdio.c,v 1.16 2009/10/25 20:44:13 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * Small standard I/O/seek/close functions.
+ * These maintain the `known seek offset' for seek optimisation.
+ */
+int
+__sread(cookie, buf, n)
+       void *cookie;
+       char *buf;
+       int n;
+{
+       FILE *fp = cookie;
+       int ret;
+       
+       _DIAGASSERT(fp != NULL);
+       _DIAGASSERT(buf != NULL);
+
+       ret = read(__sfileno(fp), buf, (size_t)n);
+       /* if the read succeeded, update the current offset */
+       if (ret >= 0)
+               fp->_offset += ret;
+       else
+               fp->_flags &= ~__SOFF;  /* paranoia */
+       return (ret);
+}
+
+int
+__swrite(cookie, buf, n)
+       void *cookie;
+       char const *buf;
+       int n;
+{
+       FILE *fp = cookie;
+
+       _DIAGASSERT(cookie != NULL);
+       _DIAGASSERT(buf != NULL);
+
+       if (fp->_flags & __SAPP)
+               (void) lseek(__sfileno(fp), (off_t)0, SEEK_END);
+       fp->_flags &= ~__SOFF;  /* in case FAPPEND mode is set */
+       return write(__sfileno(fp), buf, (size_t)n);
+}
+
+fpos_t
+__sseek(cookie, offset, whence)
+       void *cookie;
+       fpos_t offset;
+       int whence;
+{
+       FILE *fp = cookie;
+       off_t ret;
+
+       _DIAGASSERT(fp != NULL);
+       
+       ret = lseek(__sfileno(fp), (off_t)offset, whence);
+       if (ret == -1L)
+               fp->_flags &= ~__SOFF;
+       else {
+               fp->_flags |= __SOFF;
+               fp->_offset = ret;
+       }
+       return (ret);
+}
+
+int
+__sclose(cookie)
+       void *cookie;
+{
+
+       _DIAGASSERT(cookie != NULL);
+
+       return close(__sfileno((FILE *)cookie));
+}
diff --git a/lib/nbsd_libc/stdio/swprintf.c b/lib/nbsd_libc/stdio/swprintf.c
new file mode 100644 (file)
index 0000000..b769b31
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: swprintf.c,v 1.1 2005/05/14 23:51:02 christos Exp $    */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/stdio/swprintf.c,v 1.1 2002/09/21 13:00:30 tjr Exp $");
+#else
+__RCSID("$NetBSD: swprintf.c,v 1.1 2005/05/14 23:51:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <wchar.h>
+
+int
+swprintf(wchar_t * __restrict s, size_t n, const wchar_t * __restrict fmt, ...)
+{
+       int ret;
+       va_list ap;
+
+       va_start(ap, fmt);
+       ret = vswprintf(s, n, fmt, ap);
+       va_end(ap);
+
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/swscanf.c b/lib/nbsd_libc/stdio/swscanf.c
new file mode 100644 (file)
index 0000000..9e7eecd
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: swscanf.c,v 1.1 2005/05/14 23:51:02 christos Exp $     */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/stdio/swscanf.c,v 1.1 2002/09/23 12:40:06 tjr Exp $");
+#else
+__RCSID("$NetBSD: swscanf.c,v 1.1 2005/05/14 23:51:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <wchar.h>
+
+int
+swscanf(const wchar_t * __restrict str, const wchar_t * __restrict fmt, ...)
+{
+       va_list ap;
+       int r;
+
+       va_start(ap, fmt);
+       r = vswscanf(str, fmt, ap);
+       va_end(ap);
+
+       return (r);
+}
diff --git a/lib/nbsd_libc/stdio/tempnam.c b/lib/nbsd_libc/stdio/tempnam.c
new file mode 100644 (file)
index 0000000..9fd5dbf
--- /dev/null
@@ -0,0 +1,102 @@
+/*     $NetBSD: tempnam.c,v 1.21 2009/10/25 20:44:13 christos Exp $    */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)tempnam.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: tempnam.c,v 1.21 2009/10/25 20:44:13 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <paths.h>
+#include "reentrant.h"
+#include "local.h"
+
+__warn_references(tempnam,
+    "warning: tempnam() possibly used unsafely, use mkstemp() or mkdtemp()")
+
+static const char *
+trailsl(const char *f)
+{
+       const char *s = f;
+       while (*s)
+               s++;
+       return (f != s && s[-1] == '/') ? "" : "/";
+}
+
+static char *
+gentemp(char *name, size_t len, const char *tmp, const char  *pfx)
+{
+       (void)snprintf(name, len, "%s%s%sXXXXXXXXXX", tmp, trailsl(tmp), pfx);
+       return _mktemp(name);
+}
+
+char *
+tempnam(const char *dir, const char *pfx)
+{
+       int sverrno;
+       char *name, *f;
+       const char *tmp;
+
+       if (!(name = malloc((size_t)MAXPATHLEN)))
+               return NULL;
+
+       if (!pfx)
+               pfx = "tmp.";
+
+       if ((tmp = getenv("TMPDIR")) != NULL &&
+           (f = gentemp(name, (size_t)MAXPATHLEN, tmp, pfx)) != NULL)
+               return f;
+
+       if (dir != NULL &&
+           (f = gentemp(name, (size_t)MAXPATHLEN, dir, pfx)) != NULL)
+               return f;
+
+       if ((f = gentemp(name, (size_t)MAXPATHLEN, P_tmpdir, pfx)) != NULL)
+               return f;
+
+       if ((f = gentemp(name, (size_t)MAXPATHLEN, _PATH_TMP, pfx)) != NULL)
+               return f;
+
+       sverrno = errno;
+       free(name);
+       errno = sverrno;
+       return(NULL);
+}
diff --git a/lib/nbsd_libc/stdio/tmpfile.c b/lib/nbsd_libc/stdio/tmpfile.c
new file mode 100644 (file)
index 0000000..86b6853
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: tmpfile.c,v 1.11 2003/08/07 16:43:33 agc Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)tmpfile.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: tmpfile.c,v 1.11 2003/08/07 16:43:33 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <unistd.h>
+#include <signal.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <paths.h>
+
+FILE *
+tmpfile()
+{
+       sigset_t set, oset;
+       FILE *fp;
+       int fd, sverrno;
+#define        TRAILER "tmp.XXXXXXXXXX"
+       char buf[sizeof(_PATH_TMP) + sizeof(TRAILER)];
+
+       (void)memcpy(buf, _PATH_TMP, sizeof(_PATH_TMP) - 1);
+       (void)memcpy(buf + sizeof(_PATH_TMP) - 1, TRAILER, sizeof(TRAILER));
+
+       sigfillset(&set);
+       (void)sigprocmask(SIG_BLOCK, &set, &oset);
+
+       fd = mkstemp(buf);
+       if (fd != -1)
+               (void)unlink(buf);
+
+       (void)sigprocmask(SIG_SETMASK, &oset, NULL);
+
+       if (fd == -1)
+               return (NULL);
+
+       if ((fp = fdopen(fd, "w+")) == NULL) {
+               sverrno = errno;
+               (void)close(fd);
+               errno = sverrno;
+               return (NULL);
+       }
+       return (fp);
+}
diff --git a/lib/nbsd_libc/stdio/tmpnam.3 b/lib/nbsd_libc/stdio/tmpnam.3
new file mode 100644 (file)
index 0000000..3ece3f9
--- /dev/null
@@ -0,0 +1,261 @@
+.\"    $NetBSD: tmpnam.3,v 1.17 2010/04/30 04:55:10 jruoho Exp $
+.\"
+.\" Copyright (c) 1988, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)tmpnam.3   8.2 (Berkeley) 11/17/93
+.\"
+.Dd April 30, 2010
+.Dt TMPFILE 3
+.Os
+.Sh NAME
+.Nm tempnam ,
+.Nm tmpfile ,
+.Nm tmpnam
+.Nd temporary file routines
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft FILE *
+.Fn tmpfile void
+.Ft char *
+.Fn tmpnam "char *str"
+.Ft char *
+.Fn tempnam "const char *tmpdir" "const char *prefix"
+.Sh DESCRIPTION
+The
+.Fn tmpfile
+function
+returns a pointer to a stream associated with a file descriptor returned
+by the routine
+.Xr mkstemp 3 .
+The created file is unlinked before
+.Fn tmpfile
+returns, causing the file to be automatically deleted when the last
+reference to it is closed.
+The file is opened with the access value
+.Ql w+ .
+.Pp
+The
+.Fn tmpnam
+function
+returns a pointer to a file name, in the
+.Dv P_tmpdir
+directory, which
+did not reference an existing file at some indeterminate point in the
+past.
+.Dv P_tmpdir
+is defined in the include file
+.In stdio.h .
+If the argument
+.Fa s
+is
+.Pf non- Dv NULL ,
+the file name is copied to the buffer it references.
+Otherwise, the file name is copied to a static buffer.
+In either case,
+.Fn tmpnam
+returns a pointer to the file name.
+.Pp
+The buffer referenced by
+.Fa s
+is expected to be at least
+.Dv L_tmpnam
+bytes in length.
+.Dv L_tmpnam
+is defined in the include file
+.In stdio.h .
+.Pp
+The
+.Fn tempnam
+function
+is similar to
+.Fn tmpnam ,
+but provides the ability to specify the directory which will
+contain the temporary file and the file name prefix.
+.Pp
+The environment variable
+.Ev TMPDIR
+(if set), the argument
+.Fa tmpdir
+(if
+.Pf non- Dv NULL ) ,
+the directory
+.Dv P_tmpdir ,
+and the directory
+.Pa /tmp
+are tried, in the listed order, as directories in which to store the
+temporary file.
+.Pp
+The argument
+.Fa prefix ,
+if
+.Pf non- Dv NULL ,
+is used to specify a file name prefix, which will be the
+first part of the created file name.
+.Fn tempnam
+allocates memory in which to store the file name; the returned pointer
+may be used as a subsequent argument to
+.Xr free 3 .
+.Sh RETURN VALUES
+The
+.Fn tmpfile
+function
+returns a pointer to an open file stream on success, and a
+.Dv NULL
+pointer
+on error.
+.Pp
+The
+.Fn tmpnam
+and
+.Fn tempnam
+functions
+return a pointer to a file name on success, and a
+.Dv NULL
+pointer
+on error.
+.Sh ERRORS
+The
+.Fn tmpfile
+function
+may fail and set the global variable
+.Va errno
+for any of the errors specified for the library functions
+.Xr fdopen 3
+or
+.Xr mkstemp 3 .
+.Pp
+The
+.Fn tmpnam
+function
+may fail and set
+.Va errno
+for any of the errors specified for the library function
+.Xr mktemp 3 .
+.Pp
+The
+.Fn tempnam
+function
+may fail and set
+.Va errno
+for any of the errors specified for the library functions
+.Xr malloc 3
+or
+.Xr mktemp 3 .
+.Sh SEE ALSO
+.Xr mkstemp 3 ,
+.Xr mktemp 3
+.Sh STANDARDS
+The
+.Fn tmpfile
+and
+.Fn tmpnam
+functions
+conform to
+.St -ansiC .
+All described functions also conform to
+.St -p1003.1-2001 ,
+albeit the
+.Fn tempnam
+and
+.Fn tmpnam
+functions have been marked as obsolete in the
+.St -p1003.1-2008
+revision.
+.Sh BUGS
+These interfaces are provided for
+.At V
+and
+.Tn ANSI
+compatibility only.
+The
+.Xr mkstemp 3
+interface is strongly preferred.
+.Sh SECURITY CONSIDERATIONS
+There are four important problems with these interfaces (as well as
+with the historic
+.Xr mktemp 3
+interface).
+First, there is an obvious race between file name selection and file
+creation and deletion: the program is typically written to call
+.Fn tmpnam ,
+.Fn tempnam ,
+or
+.Xr mktemp 3 .
+Subsequently, the program calls
+.Xr open 2
+or
+.Xr fopen 3
+and erroneously opens a file (or symbolic link, or fifo or other
+device) that the attacker has placed in the expected file location.
+Hence
+.Xr mkstemp 3
+is recommended, since it atomically creates the file.
+.Pp
+Second, most historic implementations provide only a limited number
+of possible temporary file names (usually 26) before file names will
+start being recycled.
+Third, the
+.At V
+implementations of these functions (and of
+.Xr mktemp 3 )
+use the
+.Xr access 2
+system call to determine whether or not the temporary file may be created.
+This has obvious ramifications for setuid or setgid programs, complicating
+the portable use of these interfaces in such programs.
+Finally, there is no specification of the permissions with which the
+temporary files are created.
+.Pp
+This implementation of
+.Fn tmpfile
+does not have these flaws,
+and that of
+.Fn tmpnam
+and
+.Fn tempnam
+only have the first limitation, but portable software
+cannot depend on that.
+In particular, the
+.Fn tmpfile
+interface should not be used in software expected to be used on other systems
+if there is any possibility that the user does not wish the temporary file to
+be publicly readable and writable.
+.Pp
+A link-time warning will be issued if
+.Fn tmpnam
+or
+.Fn tempnam
+is used, and advises the use of
+.Fn mkstemp
+instead.
diff --git a/lib/nbsd_libc/stdio/tmpnam.c b/lib/nbsd_libc/stdio/tmpnam.c
new file mode 100644 (file)
index 0000000..ac42baf
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: tmpnam.c,v 1.14 2003/08/07 16:43:33 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)tmpnam.c   8.3 (Berkeley) 3/28/94";
+#else
+__RCSID("$NetBSD: tmpnam.c,v 1.14 2003/08/07 16:43:33 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <stdio.h>
+#include <unistd.h>
+#include "reentrant.h"
+#include "local.h"
+
+__warn_references(tmpnam,
+    "warning: tmpnam() possibly used unsafely, use mkstemp() or mkdtemp()")
+
+char *
+tmpnam(s)
+       char *s;
+{
+       static u_long tmpcount;
+       static char buf[L_tmpnam];
+
+       if (s == NULL)
+               s = buf;
+       (void)snprintf(s, L_tmpnam, "%stmp.%lu.XXXXXXXXXX", P_tmpdir, tmpcount);
+       ++tmpcount;
+       return (_mktemp(s));
+}
diff --git a/lib/nbsd_libc/stdio/ungetc.3 b/lib/nbsd_libc/stdio/ungetc.3
new file mode 100644 (file)
index 0000000..a9fe94c
--- /dev/null
@@ -0,0 +1,102 @@
+.\"    $NetBSD: ungetc.3,v 1.10 2010/04/30 05:56:14 jruoho Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)ungetc.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 30, 2010
+.Dt UNGETC 3
+.Os
+.Sh NAME
+.Nm ungetc
+.Nd un-get character from input stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft int
+.Fn ungetc "int c" "FILE *stream"
+.Sh DESCRIPTION
+The
+.Fn ungetc
+function pushes the character
+.Fa c
+(converted to an unsigned char)
+back onto the input stream pointed to by
+.Fa stream .
+The pushed-backed characters will be returned by subsequent reads on the
+stream (in reverse order).
+A successful intervening call, using the same stream, to one of the file
+positioning functions
+.Po
+.Xr fseek 3 ,
+.Xr fsetpos 3 ,
+or
+.Xr rewind 3
+.Pc
+will discard the pushed back characters.
+.Pp
+One character of push-back is guaranteed,
+but as long as there is
+sufficient memory, an effectively infinite amount of pushback is allowed.
+.Pp
+If a character is successfully pushed-back,
+the end-of-file indicator for the stream is cleared.
+.Sh RETURN VALUES
+The
+.Fn ungetc
+function
+returns
+the character pushed-back after the conversion, or
+.Dv EOF
+if the operation fails.
+If the value of the argument
+.Fa c
+character equals
+.Dv EOF ,
+the operation will fail and the stream will remain unchanged.
+.Sh SEE ALSO
+.Xr fseek 3 ,
+.Xr getc 3 ,
+.Xr setvbuf 3
+.Sh STANDARDS
+The
+.Fn ungetc
+function conforms to
+.St -ansiC
+and
+.St -p1003.1-2001 .
+.Sh HISTORY
+An
+.Fn ungetc
+function appeared in
+.At v7 .
diff --git a/lib/nbsd_libc/stdio/ungetc.c b/lib/nbsd_libc/stdio/ungetc.c
new file mode 100644 (file)
index 0000000..10eb301
--- /dev/null
@@ -0,0 +1,172 @@
+/*     $NetBSD: ungetc.c,v 1.16 2009/10/25 20:44:13 christos Exp $     */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ungetc.c   8.2 (Berkeley) 11/3/93";
+#else
+__RCSID("$NetBSD: ungetc.c,v 1.16 2009/10/25 20:44:13 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "reentrant.h"
+#include "local.h"
+
+static int __submore __P((FILE *));
+/*
+ * Expand the ungetc buffer `in place'.  That is, adjust fp->_p when
+ * the buffer moves, so that it points the same distance from the end,
+ * and move the bytes in the buffer around as necessary so that they
+ * are all at the end (stack-style).
+ */
+static int
+__submore(fp)
+       FILE *fp;
+{
+       int i;
+       unsigned char *p;
+
+       _DIAGASSERT(fp != NULL);
+
+       if (_UB(fp)._base == fp->_ubuf) {
+               /*
+                * Get a new buffer (rather than expanding the old one).
+                */
+               if ((p = malloc((size_t)BUFSIZ)) == NULL)
+                       return (EOF);
+               _UB(fp)._base = p;
+               _UB(fp)._size = BUFSIZ;
+               p += BUFSIZ - sizeof(fp->_ubuf);
+               for (i = sizeof(fp->_ubuf); --i >= 0;)
+                       p[i] = fp->_ubuf[i];
+               fp->_p = p;
+               return (0);
+       }
+       i = _UB(fp)._size;
+       p = realloc(_UB(fp)._base, (size_t)(i << 1));
+       if (p == NULL)
+               return (EOF);
+       /* no overlap (hence can use memcpy) because we doubled the size */
+       (void)memcpy((p + i), p, (size_t)i);
+       fp->_p = p + i;
+       _UB(fp)._base = p;
+       _UB(fp)._size = i << 1;
+       return (0);
+}
+
+int
+ungetc(c, fp)
+       int c;
+       FILE *fp;
+{
+
+       _DIAGASSERT(fp != NULL);
+
+       if (c == EOF)
+               return (EOF);
+       if (!__sdidinit)
+               __sinit();
+       FLOCKFILE(fp);
+       _SET_ORIENTATION(fp, -1);
+       if ((fp->_flags & __SRD) == 0) {
+               /*
+                * Not already reading: no good unless reading-and-writing.
+                * Otherwise, flush any current write stuff.
+                */
+               if ((fp->_flags & __SRW) == 0) {
+                       FUNLOCKFILE(fp);
+                       return (EOF);
+               }
+               if (fp->_flags & __SWR) {
+                       if (__sflush(fp)) {
+                               FUNLOCKFILE(fp);
+                               return (EOF);
+                       }
+                       fp->_flags &= ~__SWR;
+                       fp->_w = 0;
+                       fp->_lbfsize = 0;
+               }
+               fp->_flags |= __SRD;
+       }
+       c = (unsigned char)c;
+
+       /*
+        * If we are in the middle of ungetc'ing, just continue.
+        * This may require expanding the current ungetc buffer.
+        */
+       if (HASUB(fp)) {
+               if (fp->_r >= _UB(fp)._size && __submore(fp)) {
+                       FUNLOCKFILE(fp);
+                       return (EOF);
+               }
+               *--fp->_p = c;
+               fp->_r++;
+               FUNLOCKFILE(fp);
+               return (c);
+       }
+       fp->_flags &= ~__SEOF;
+
+       /*
+        * If we can handle this by simply backing up, do so,
+        * but never replace the original character.
+        * (This makes sscanf() work when scanning `const' data.)
+        */
+       if (fp->_bf._base != NULL && fp->_p > fp->_bf._base &&
+           fp->_p[-1] == c) {
+               fp->_p--;
+               fp->_r++;
+               FUNLOCKFILE(fp);
+               return (c);
+       }
+
+       /*
+        * Create an ungetc buffer.
+        * Initially, we will use the `reserve' buffer.
+        */
+       fp->_ur = fp->_r;
+       fp->_up = fp->_p;
+       _UB(fp)._base = fp->_ubuf;
+       _UB(fp)._size = sizeof(fp->_ubuf);
+       fp->_ubuf[sizeof(fp->_ubuf) - 1] = c;
+       fp->_p = &fp->_ubuf[sizeof(fp->_ubuf) - 1];
+       fp->_r = 1;
+       FUNLOCKFILE(fp);
+       return (c);
+}
diff --git a/lib/nbsd_libc/stdio/ungetwc.3 b/lib/nbsd_libc/stdio/ungetwc.3
new file mode 100644 (file)
index 0000000..03c6fb8
--- /dev/null
@@ -0,0 +1,95 @@
+.\"    $NetBSD: ungetwc.3,v 1.8 2010/12/16 17:42:27 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)ungetc.3   8.1 (Berkeley) 6/4/93
+.\"
+.Dd October 24, 2001
+.Dt UNGETWC 3
+.Os
+.Sh NAME
+.Nm ungetwc
+.Nd un-get wide character from input stream
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.In wchar.h
+.Ft wint_t
+.Fn ungetwc "wint_t wc" "FILE *stream"
+.Sh DESCRIPTION
+The
+.Fn ungetwc
+function pushes the wide character
+.Fa wc
+(converted to an wchar_t)
+back onto the input stream pointed to by
+.Fa stream .
+The pushed-backed wide characters will be returned by subsequent reads on the
+stream (in reverse order).
+A successful intervening call, using the same stream, to one of the file
+positioning functions
+.Xr fseek 3 ,
+.Xr fsetpos 3 ,
+or
+.Xr rewind 3
+will discard the pushed back wide characters.
+.Pp
+One wide character of push-back is guaranteed,
+but as long as there is
+sufficient memory, an effectively infinite amount of pushback is allowed.
+.Pp
+If a character is successfully pushed-back,
+the end-of-file indicator for the stream is cleared.
+.Sh RETURN VALUES
+The
+.Fn ungetwc
+function
+returns
+the wide character pushed-back after the conversion, or
+.Dv WEOF
+if the operation fails.
+If the value of the argument
+.Fa c
+character equals
+.Dv WEOF ,
+the operation will fail and the stream will remain unchanged.
+.Sh SEE ALSO
+.Xr fseek 3 ,
+.Xr getwc 3
+.Sh STANDARDS
+The
+.Fn ungetwc
+function conforms to
+.St -isoC-99 .
+.Sh BUGS
+The current implementation uses a fixed sized ungetwc-buffer.
diff --git a/lib/nbsd_libc/stdio/ungetwc.c b/lib/nbsd_libc/stdio/ungetwc.c
new file mode 100644 (file)
index 0000000..982beae
--- /dev/null
@@ -0,0 +1,78 @@
+/* $NetBSD: ungetwc.c,v 1.3 2005/06/12 05:21:27 lukem Exp $ */
+
+/*-
+ * Copyright (c)2001 Citrus Project,
+ * 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.
+ *
+ * $Citrus$
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ungetwc.c,v 1.3 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <wchar.h>
+#include "reentrant.h"
+#include "local.h"
+
+wint_t
+ungetwc(wint_t wc, FILE *fp)
+{
+       struct wchar_io_data *wcio;
+
+       _DIAGASSERT(fp);
+
+       if (wc == WEOF)
+               return WEOF;
+
+       FLOCKFILE(fp);
+       _SET_ORIENTATION(fp, 1);
+       /*
+        * XXX since we have no way to transform a wchar string to
+        * a char string in reverse order, we can't use ungetc.
+        */
+       /* XXX should we flush ungetc buffer? */
+
+       wcio = WCIO_GET(fp);
+       if (wcio == 0) {
+               FUNLOCKFILE(fp);
+               errno = ENOMEM; /* XXX */
+               return WEOF;
+       }
+
+       if (wcio->wcio_ungetwc_inbuf >= WCIO_UNGETWC_BUFSIZE) {
+               FUNLOCKFILE(fp);
+               return WEOF;
+       }
+
+       wcio->wcio_ungetwc_buf[wcio->wcio_ungetwc_inbuf++] = wc;
+       __sclearerr(fp);
+       FUNLOCKFILE(fp);
+
+       return wc;
+}
diff --git a/lib/nbsd_libc/stdio/vasprintf.c b/lib/nbsd_libc/stdio/vasprintf.c
new file mode 100644 (file)
index 0000000..3664d7b
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: vasprintf.c,v 1.12 2009/10/25 20:44:13 christos Exp $  */
+
+/*
+ * Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
+ * 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.
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: vasprintf.c,v 1.12 2009/10/25 20:44:13 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include "reentrant.h"
+#include "local.h"
+
+int
+vasprintf(str, fmt, ap)
+       char **str;
+       const char *fmt;
+       _BSD_VA_LIST_ ap;
+{
+       int ret;
+       FILE f;
+       struct __sfileext fext;
+       unsigned char *_base;
+
+       _DIAGASSERT(str != NULL);
+       _DIAGASSERT(fmt != NULL);
+
+       _FILEEXT_SETUP(&f, &fext);
+       f._file = -1;
+       f._flags = __SWR | __SSTR | __SALC;
+       f._bf._base = f._p = (unsigned char *)malloc(128);
+       if (f._bf._base == NULL)
+               goto err;
+       f._bf._size = f._w = 127;               /* Leave room for the NUL */
+       ret = __vfprintf_unlocked(&f, fmt, ap);
+       if (ret == -1)
+               goto err;
+       *f._p = '\0';
+       _base = realloc(f._bf._base, (size_t)(ret + 1));
+       if (_base == NULL)
+               goto err;
+       *str = (char *)_base;
+       return (ret);
+
+err:
+       if (f._bf._base)
+               free(f._bf._base);
+       *str = NULL;
+       errno = ENOMEM;
+       return (-1);
+}
diff --git a/lib/nbsd_libc/stdio/vdprintf.c b/lib/nbsd_libc/stdio/vdprintf.c
new file mode 100644 (file)
index 0000000..98bf400
--- /dev/null
@@ -0,0 +1,116 @@
+/*     $NetBSD: vdprintf.c,v 1.1 2010/09/06 14:52:55 christos Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: vdprintf.c,v 1.1 2010/09/06 14:52:55 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <limits.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(vdprintf,_vdprintf)
+#endif
+
+int
+vdprintf(int fd, const char * __restrict fmt, _BSD_VA_LIST_ ap)
+{
+       FILE f;
+       struct __sfileext fext;
+       unsigned char buf[BUFSIZ];
+       int ret, fdflags, tmp;
+
+       _DIAGASSERT(fd != -1);
+
+       /*
+        * File descriptors are a full int, but _file is only a short.
+        * If we get a valid file descriptor that is greater or equal to
+        * USHRT_MAX, then the fd will get sign-extended into an
+        * invalid file descriptor.  Handle this case by failing the
+        * open. (We treat the short as unsigned, and special-case -1).
+        */
+       if (fd >= USHRT_MAX) {
+               errno = EMFILE;
+               return EOF;
+       }
+
+       if ((fdflags = fcntl(fd, F_GETFL, 0)) == -1)
+               return EOF;
+
+       tmp = fdflags & O_ACCMODE;
+       if (tmp != O_RDWR && tmp != O_WRONLY) {
+               errno = EINVAL;
+               return EOF;
+       }
+
+       if (fdflags & O_NONBLOCK) {
+               struct stat st;
+               if (fstat(fd, &st) == -1)
+                       return -1;
+               if (!S_ISREG(st.st_mode)) {
+                       errno = EFTYPE;
+                       return EOF;
+               }
+       }
+
+       _FILEEXT_SETUP(&f, &fext);
+       __sfpinit(&f);
+       f._p = buf;
+       f._w = sizeof(buf);
+       f._flags = __SWR;
+       f._file = fd;
+       f._bf._base = buf;
+       f._bf._size = sizeof(buf);
+       f._cookie = &f;
+       f._read = NULL;
+       f._write = __swrite;
+       f._seek = NULL;
+       f._close = NULL;
+
+       if ((ret = vfprintf(&f, fmt, ap)) < 0)
+               return ret;
+
+       return fflush(&f) ? EOF : ret;
+}
diff --git a/lib/nbsd_libc/stdio/vfprintf.c b/lib/nbsd_libc/stdio/vfprintf.c
new file mode 100644 (file)
index 0000000..ae11e25
--- /dev/null
@@ -0,0 +1,2 @@
+#define NARROW
+#include "vfwprintf.c"
diff --git a/lib/nbsd_libc/stdio/vfscanf.c b/lib/nbsd_libc/stdio/vfscanf.c
new file mode 100644 (file)
index 0000000..c7f8906
--- /dev/null
@@ -0,0 +1,1098 @@
+/*     $NetBSD: vfscanf.c,v 1.41 2010/12/16 17:42:27 wiz Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)vfscanf.c  8.1 (Berkeley) 6/4/93";
+__FBSDID("$FreeBSD: src/lib/libc/stdio/vfscanf.c,v 1.41 2007/01/09 00:28:07 imp Exp $");
+#else
+__RCSID("$NetBSD: vfscanf.c,v 1.41 2010/12/16 17:42:27 wiz Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <ctype.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <stdarg.h>
+#include <string.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+#ifndef NO_FLOATING_POINT
+#include <locale.h>
+#endif
+
+/*
+ * Provide an external name for vfscanf.  Note, we don't use the normal
+ * namespace.h method; stdio routines explicitly use the internal name
+ * __svfscanf.
+ */
+#ifdef __weak_alias
+__weak_alias(vfscanf,__svfscanf)
+#endif
+
+#define        BUF             513     /* Maximum length of numeric string. */
+
+/*
+ * Flags used during conversion.
+ */
+#define        LONG            0x0001  /* l: long or double */
+#define        LONGDBL         0x0002  /* L: long double */
+#define        SHORT           0x0004  /* h: short */
+#define        SUPPRESS        0x0008  /* *: suppress assignment */
+#define        POINTER         0x0010  /* p: void * (as hex) */
+#define        NOSKIP          0x0020  /* [ or c: do not skip blanks */
+#define        LONGLONG        0x0400  /* ll: long long (+ deprecated q: quad) */
+#define        INTMAXT         0x0800  /* j: intmax_t */
+#define        PTRDIFFT        0x1000  /* t: ptrdiff_t */
+#define        SIZET           0x2000  /* z: size_t */
+#define        SHORTSHORT      0x4000  /* hh: char */
+#define        UNSIGNED        0x8000  /* %[oupxX] conversions */
+
+/*
+ * The following are used in integral conversions only:
+ * SIGNOK, NDIGITS, PFXOK, and NZDIGITS
+ */
+#define        SIGNOK          0x00040 /* +/- is (still) legal */
+#define        NDIGITS         0x00080 /* no digits detected */
+#define        PFXOK           0x00100 /* 0x prefix is (still) legal */
+#define        NZDIGITS        0x00200 /* no zero digits detected */
+#define        HAVESIGN        0x10000 /* sign detected */
+
+/*
+ * Conversion types.
+ */
+#define        CT_CHAR         0       /* %c conversion */
+#define        CT_CCL          1       /* %[...] conversion */
+#define        CT_STRING       2       /* %s conversion */
+#define        CT_INT          3       /* %[dioupxX] conversion */
+#define        CT_FLOAT        4       /* %[efgEFG] conversion */
+
+static const u_char *__sccl(char *, const u_char *);
+#ifndef NO_FLOATING_POINT
+static int parsefloat(FILE *, char *, char *);
+#endif
+
+int __scanfdebug = 0;
+
+#define __collate_load_error /*CONSTCOND*/0
+static int
+__collate_range_cmp(int c1, int c2)
+{
+       static char s1[2], s2[2];
+
+       s1[0] = c1;
+       s2[0] = c2;
+       return strcoll(s1, s2);
+}
+
+
+/*
+ * __svfscanf - MT-safe version
+ */
+int
+__svfscanf(FILE *fp, char const *fmt0, va_list ap)
+{
+       int ret;
+
+       FLOCKFILE(fp);
+       ret = __svfscanf_unlocked(fp, fmt0, ap);
+       FUNLOCKFILE(fp);
+       return (ret);
+}
+
+#define SCANF_SKIP_SPACE() \
+do { \
+       while ((fp->_r > 0 || __srefill(fp) == 0) && isspace(*fp->_p)) \
+               nread++, fp->_r--, fp->_p++; \
+} while (/*CONSTCOND*/ 0)
+
+/*
+ * __svfscanf_unlocked - non-MT-safe version of __svfscanf
+ */
+int
+__svfscanf_unlocked(FILE *fp, const char *fmt0, va_list ap)
+{
+       const u_char *fmt = (const u_char *)fmt0;
+       int c;                  /* character from format, or conversion */
+       size_t width;           /* field width, or 0 */
+       char *p;                /* points into all kinds of strings */
+       size_t n;               /* handy size_t */
+       int flags;              /* flags as defined above */
+       char *p0;               /* saves original value of p when necessary */
+       int nassigned;          /* number of fields assigned */
+       int nconversions;       /* number of conversions */
+       int nread;              /* number of characters consumed from fp */
+       int base;               /* base argument to conversion function */
+       char ccltab[256];       /* character class table for %[...] */
+       char buf[BUF];          /* buffer for numeric and mb conversions */
+       wchar_t *wcp;           /* handy wide-character pointer */
+       size_t nconv;           /* length of multibyte sequence converted */
+       static const mbstate_t initial;
+       mbstate_t mbs;
+
+       /* `basefix' is used to avoid `if' tests in the integer scanner */
+       static const short basefix[17] =
+               { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
+
+       _DIAGASSERT(fp != NULL);
+       _DIAGASSERT(fmt0 != NULL);
+
+       _SET_ORIENTATION(fp, -1);
+
+       nassigned = 0;
+       nconversions = 0;
+       nread = 0;
+       base = 0;
+       for (;;) {
+               c = (unsigned char)*fmt++;
+               if (c == 0)
+                       return (nassigned);
+               if (isspace(c)) {
+                       while ((fp->_r > 0 || __srefill(fp) == 0) &&
+                           isspace(*fp->_p))
+                               nread++, fp->_r--, fp->_p++;
+                       continue;
+               }
+               if (c != '%')
+                       goto literal;
+               width = 0;
+               flags = 0;
+               /*
+                * switch on the format.  continue if done;
+                * break once format type is derived.
+                */
+again:         c = *fmt++;
+               switch (c) {
+               case '%':
+                       SCANF_SKIP_SPACE();
+literal:
+                       if (fp->_r <= 0 && __srefill(fp))
+                               goto input_failure;
+                       if (*fp->_p != c)
+                               goto match_failure;
+                       fp->_r--, fp->_p++;
+                       nread++;
+                       continue;
+
+               case '*':
+                       flags |= SUPPRESS;
+                       goto again;
+               case 'j':
+                       flags |= INTMAXT;
+                       goto again;
+               case 'l':
+                       if (flags & LONG) {
+                               flags &= ~LONG;
+                               flags |= LONGLONG;
+                       } else
+                               flags |= LONG;
+                       goto again;
+               case 'q':
+                       flags |= LONGLONG;      /* not quite */
+                       goto again;
+               case 't':
+                       flags |= PTRDIFFT;
+                       goto again;
+               case 'z':
+                       flags |= SIZET;
+                       goto again;
+               case 'L':
+                       flags |= LONGDBL;
+                       goto again;
+               case 'h':
+                       if (flags & SHORT) {
+                               flags &= ~SHORT;
+                               flags |= SHORTSHORT;
+                       } else
+                               flags |= SHORT;
+                       goto again;
+
+               case '0': case '1': case '2': case '3': case '4':
+               case '5': case '6': case '7': case '8': case '9':
+                       width = width * 10 + c - '0';
+                       goto again;
+
+               /*
+                * Conversions.
+                */
+               case 'd':
+                       c = CT_INT;
+                       base = 10;
+                       break;
+
+               case 'i':
+                       c = CT_INT;
+                       base = 0;
+                       break;
+
+               case 'o':
+                       c = CT_INT;
+                       flags |= UNSIGNED;
+                       base = 8;
+                       break;
+
+               case 'u':
+                       c = CT_INT;
+                       flags |= UNSIGNED;
+                       base = 10;
+                       break;
+
+               case 'X':
+               case 'x':
+                       flags |= PFXOK; /* enable 0x prefixing */
+                       c = CT_INT;
+                       flags |= UNSIGNED;
+                       base = 16;
+                       break;
+
+#ifndef NO_FLOATING_POINT
+               case 'A': case 'E': case 'F': case 'G':
+               case 'a': case 'e': case 'f': case 'g':
+                       c = CT_FLOAT;
+                       break;
+#endif
+
+               case 'S':
+                       flags |= LONG;
+                       /* FALLTHROUGH */
+               case 's':
+                       c = CT_STRING;
+                       break;
+
+               case '[':
+                       fmt = __sccl(ccltab, fmt);
+                       flags |= NOSKIP;
+                       c = CT_CCL;
+                       break;
+
+               case 'C':
+                       flags |= LONG;
+                       /* FALLTHROUGH */
+               case 'c':
+                       flags |= NOSKIP;
+                       c = CT_CHAR;
+                       break;
+
+               case 'p':       /* pointer format is like hex */
+                       flags |= POINTER | PFXOK;
+                       c = CT_INT;             /* assumes sizeof(uintmax_t) */
+                       flags |= UNSIGNED;      /*      >= sizeof(uintptr_t) */
+                       base = 16;
+                       break;
+
+               case 'n':
+                       nconversions++;
+                       if (flags & SUPPRESS)   /* ??? */
+                               continue;
+                       if (flags & SHORTSHORT)
+                               *va_arg(ap, char *) = nread;
+                       else if (flags & SHORT)
+                               *va_arg(ap, short *) = nread;
+                       else if (flags & LONG)
+                               *va_arg(ap, long *) = nread;
+                       else if (flags & LONGLONG)
+                               *va_arg(ap, long long *) = nread;
+                       else if (flags & INTMAXT)
+                               *va_arg(ap, intmax_t *) = nread;
+                       else if (flags & SIZET)
+                               *va_arg(ap, size_t *) = nread;
+                       else if (flags & PTRDIFFT)
+                               *va_arg(ap, ptrdiff_t *) = nread;
+                       else
+                               *va_arg(ap, int *) = nread;
+                       continue;
+
+               default:
+                       goto match_failure;
+
+               /*
+                * Disgusting backwards compatibility hack.     XXX
+                */
+               case '\0':      /* compat */
+                       return (EOF);
+               }
+
+               /*
+                * We have a conversion that requires input.
+                */
+               if (fp->_r <= 0 && __srefill(fp))
+                       goto input_failure;
+
+               /*
+                * Consume leading white space, except for formats
+                * that suppress this.
+                */
+               if ((flags & NOSKIP) == 0) {
+                       while (isspace(*fp->_p)) {
+                               nread++;
+                               if (--fp->_r > 0)
+                                       fp->_p++;
+                               else if (__srefill(fp))
+                                       goto input_failure;
+                       }
+                       /*
+                        * Note that there is at least one character in
+                        * the buffer, so conversions that do not set NOSKIP
+                        * ca no longer result in an input failure.
+                        */
+               }
+
+               /*
+                * Do the conversion.
+                */
+               switch (c) {
+
+               case CT_CHAR:
+                       /* scan arbitrary characters (sets NOSKIP) */
+                       if (width == 0)
+                               width = 1;
+                       if (flags & LONG) {
+                               if ((flags & SUPPRESS) == 0)
+                                       wcp = va_arg(ap, wchar_t *);
+                               else
+                                       wcp = NULL;
+                               n = 0;
+                               while (width != 0) {
+                                       if (n == MB_CUR_MAX) {
+                                               fp->_flags |= __SERR;
+                                               goto input_failure;
+                                       }
+                                       buf[n++] = *fp->_p;
+                                       fp->_p++;
+                                       fp->_r--;
+                                       mbs = initial;
+                                       nconv = mbrtowc(wcp, buf, n, &mbs);
+                                       if (nconv == (size_t)-1) {
+                                               fp->_flags |= __SERR;
+                                               goto input_failure;
+                                       }
+                                       if (nconv == 0 && !(flags & SUPPRESS))
+                                               *wcp = L'\0';
+                                       if (nconv != (size_t)-2) {
+                                               nread += n;
+                                               width--;
+                                               if (!(flags & SUPPRESS))
+                                                       wcp++;
+                                               n = 0;
+                                       }
+                                       if (fp->_r <= 0 && __srefill(fp)) {
+                                               if (n != 0) {
+                                                       fp->_flags |= __SERR;
+                                                       goto input_failure;
+                                               }
+                                               break;
+                                       }
+                               }
+                               if (!(flags & SUPPRESS))
+                                       nassigned++;
+                       } else if (flags & SUPPRESS) {
+                               size_t sum = 0;
+                               for (;;) {
+                                       if ((n = fp->_r) < width) {
+                                               sum += n;
+                                               width -= n;
+                                               fp->_p += n;
+                                               if (__srefill(fp)) {
+                                                       if (sum == 0)
+                                                           goto input_failure;
+                                                       break;
+                                               }
+                                       } else {
+                                               sum += width;
+                                               fp->_r -= width;
+                                               fp->_p += width;
+                                               break;
+                                       }
+                               }
+                               nread += sum;
+                       } else {
+                               size_t r = fread(va_arg(ap, char *), 1,
+                                   width, fp);
+
+                               if (r == 0)
+                                       goto input_failure;
+                               nread += r;
+                               nassigned++;
+                       }
+                       nconversions++;
+                       break;
+
+               case CT_CCL:
+                       /* scan a (nonempty) character class (sets NOSKIP) */
+                       if (width == 0)
+                               width = (size_t)~0;     /* `infinity' */
+                       /* take only those things in the class */
+                       if (flags & LONG) {
+                               wchar_t twc;
+                               int nchars;
+
+                               if ((flags & SUPPRESS) == 0)
+                                       wcp = va_arg(ap, wchar_t *);
+                               else
+                                       wcp = &twc;
+                               n = 0;
+                               nchars = 0;
+                               while (width != 0) {
+                                       if (n == MB_CUR_MAX) {
+                                               fp->_flags |= __SERR;
+                                               goto input_failure;
+                                       }
+                                       buf[n++] = *fp->_p;
+                                       fp->_p++;
+                                       fp->_r--;
+                                       mbs = initial;
+                                       nconv = mbrtowc(wcp, buf, n, &mbs);
+                                       if (nconv == (size_t)-1) {
+                                               fp->_flags |= __SERR;
+                                               goto input_failure;
+                                       }
+                                       if (nconv == 0)
+                                               *wcp = L'\0';
+                                       if (nconv != (size_t)-2) {
+                                               if (wctob(*wcp) != EOF &&
+                                                   !ccltab[wctob(*wcp)]) {
+                                                       while (n != 0) {
+                                                               n--;
+                                                               (void)ungetc(buf[n],
+                                                                   fp);
+                                                       }
+                                                       break;
+                                               }
+                                               nread += n;
+                                               width--;
+                                               if (!(flags & SUPPRESS))
+                                                       wcp++;
+                                               nchars++;
+                                               n = 0;
+                                       }
+                                       if (fp->_r <= 0 && __srefill(fp)) {
+                                               if (n != 0) {
+                                                       fp->_flags |= __SERR;
+                                                       goto input_failure;
+                                               }
+                                               break;
+                                       }
+                               }
+                               if (n != 0) {
+                                       fp->_flags |= __SERR;
+                                       goto input_failure;
+                               }
+                               n = nchars;
+                               if (n == 0)
+                                       goto match_failure;
+                               if (!(flags & SUPPRESS)) {
+                                       *wcp = L'\0';
+                                       nassigned++;
+                               }
+                       } else if (flags & SUPPRESS) {
+                               n = 0;
+                               while (ccltab[*fp->_p]) {
+                                       n++, fp->_r--, fp->_p++;
+                                       if (--width == 0)
+                                               break;
+                                       if (fp->_r <= 0 && __srefill(fp)) {
+                                               if (n == 0)
+                                                       goto input_failure;
+                                               break;
+                                       }
+                               }
+                               if (n == 0)
+                                       goto match_failure;
+                       } else {
+                               p0 = p = va_arg(ap, char *);
+                               while (ccltab[*fp->_p]) {
+                                       fp->_r--;
+                                       *p++ = *fp->_p++;
+                                       if (--width == 0)
+                                               break;
+                                       if (fp->_r <= 0 && __srefill(fp)) {
+                                               if (p == p0)
+                                                       goto input_failure;
+                                               break;
+                                       }
+                               }
+                               n = p - p0;
+                               if (n == 0)
+                                       goto match_failure;
+                               *p = 0;
+                               nassigned++;
+                       }
+                       nread += n;
+                       nconversions++;
+                       break;
+
+               case CT_STRING:
+                       /* like CCL, but zero-length string OK, & no NOSKIP */
+                       if (width == 0)
+                               width = (size_t)~0;
+                       if (flags & LONG) {
+                               wchar_t twc;
+
+                               if ((flags & SUPPRESS) == 0)
+                                       wcp = va_arg(ap, wchar_t *);
+                               else
+                                       wcp = &twc;
+                               n = 0;
+                               while (!isspace(*fp->_p) && width != 0) {
+                                       if (n == MB_CUR_MAX) {
+                                               fp->_flags |= __SERR;
+                                               goto input_failure;
+                                       }
+                                       buf[n++] = *fp->_p;
+                                       fp->_p++;
+                                       fp->_r--;
+                                       mbs = initial;
+                                       nconv = mbrtowc(wcp, buf, n, &mbs);
+                                       if (nconv == (size_t)-1) {
+                                               fp->_flags |= __SERR;
+                                               goto input_failure;
+                                       }
+                                       if (nconv == 0)
+                                               *wcp = L'\0';
+                                       if (nconv != (size_t)-2) {
+                                               if (iswspace(*wcp)) {
+                                                       while (n != 0) {
+                                                               n--;
+                                                               (void)ungetc(buf[n],
+                                                                   fp);
+                                                       }
+                                                       break;
+                                               }
+                                               nread += n;
+                                               width--;
+                                               if (!(flags & SUPPRESS))
+                                                       wcp++;
+                                               n = 0;
+                                       }
+                                       if (fp->_r <= 0 && __srefill(fp)) {
+                                               if (n != 0) {
+                                                       fp->_flags |= __SERR;
+                                                       goto input_failure;
+                                               }
+                                               break;
+                                       }
+                               }
+                               if (!(flags & SUPPRESS)) {
+                                       *wcp = L'\0';
+                                       nassigned++;
+                               }
+                       } else if (flags & SUPPRESS) {
+                               n = 0;
+                               while (!isspace(*fp->_p)) {
+                                       n++, fp->_r--, fp->_p++;
+                                       if (--width == 0)
+                                               break;
+                                       if (fp->_r <= 0 && __srefill(fp))
+                                               break;
+                               }
+                               nread += n;
+                       } else {
+                               p0 = p = va_arg(ap, char *);
+                               while (!isspace(*fp->_p)) {
+                                       fp->_r--;
+                                       *p++ = *fp->_p++;
+                                       if (--width == 0)
+                                               break;
+                                       if (fp->_r <= 0 && __srefill(fp))
+                                               break;
+                               }
+                               *p = 0;
+                               nread += p - p0;
+                               nassigned++;
+                       }
+                       nconversions++;
+                       continue;
+
+               case CT_INT:
+                       /* scan an integer as if by the conversion function */
+#ifdef hardway
+                       if (width == 0 || width > sizeof(buf) - 1)
+                               width = sizeof(buf) - 1;
+#else
+                       /* size_t is unsigned, hence this optimisation */
+                       if (--width > sizeof(buf) - 2)
+                               width = sizeof(buf) - 2;
+                       width++;
+#endif
+                       flags |= SIGNOK | NDIGITS | NZDIGITS;
+                       for (p = buf; width; width--) {
+                               c = *fp->_p;
+                               /*
+                                * Switch on the character; `goto ok'
+                                * if we accept it as a part of number.
+                                */
+                               switch (c) {
+
+                               /*
+                                * The digit 0 is always legal, but is
+                                * special.  For %i conversions, if no
+                                * digits (zero or nonzero) have been
+                                * scanned (only signs), we will have
+                                * base==0.  In that case, we should set
+                                * it to 8 and enable 0x prefixing.
+                                * Also, if we have not scanned zero digits
+                                * before this, do not turn off prefixing
+                                * (someone else will turn it off if we
+                                * have scanned any nonzero digits).
+                                */
+                               case '0':
+                                       if (base == 0) {
+                                               base = 8;
+                                               flags |= PFXOK;
+                                       }
+                                       if (flags & NZDIGITS)
+                                           flags &= ~(SIGNOK|NZDIGITS|NDIGITS);
+                                       else
+                                           flags &= ~(SIGNOK|PFXOK|NDIGITS);
+                                       goto ok;
+
+                               /* 1 through 7 always legal */
+                               case '1': case '2': case '3':
+                               case '4': case '5': case '6': case '7':
+                                       base = basefix[base];
+                                       flags &= ~(SIGNOK | PFXOK | NDIGITS);
+                                       goto ok;
+
+                               /* digits 8 and 9 ok iff decimal or hex */
+                               case '8': case '9':
+                                       base = basefix[base];
+                                       if (base <= 8)
+                                               break;  /* not legal here */
+                                       flags &= ~(SIGNOK | PFXOK | NDIGITS);
+                                       goto ok;
+
+                               /* letters ok iff hex */
+                               case 'A': case 'B': case 'C':
+                               case 'D': case 'E': case 'F':
+                               case 'a': case 'b': case 'c':
+                               case 'd': case 'e': case 'f':
+                                       /* no need to fix base here */
+                                       if (base <= 10)
+                                               break;  /* not legal here */
+                                       flags &= ~(SIGNOK | PFXOK | NDIGITS);
+                                       goto ok;
+
+                               /* sign ok only as first character */
+                               case '+': case '-':
+                                       if (flags & SIGNOK) {
+                                               flags &= ~SIGNOK;
+                                               flags |= HAVESIGN;
+                                               goto ok;
+                                       }
+                                       break;
+                                       
+                               /*
+                                * x ok iff flag still set & 2nd char (or
+                                * 3rd char if we have a sign).
+                                */
+                               case 'x': case 'X':
+                                       if (flags & PFXOK && p ==
+                                           buf + 1 + !!(flags & HAVESIGN)) {
+                                               base = 16;      /* if %i */
+                                               flags &= ~PFXOK;
+                                               goto ok;
+                                       }
+                                       break;
+                               }
+
+                               /*
+                                * If we got here, c is not a legal character
+                                * for a number.  Stop accumulating digits.
+                                */
+                               break;
+               ok:
+                               /*
+                                * c is legal: store it and look at the next.
+                                */
+                               *p++ = c;
+                               if (--fp->_r > 0)
+                                       fp->_p++;
+                               else if (__srefill(fp))
+                                       break;          /* EOF */
+                       }
+                       /*
+                        * If we had only a sign, it is no good; push
+                        * back the sign.  If the number ends in `x',
+                        * it was [sign] '0' 'x', so push back the x
+                        * and treat it as [sign] '0'.
+                        */
+                       if (flags & NDIGITS) {
+                               if (p > buf)
+                                       (void)ungetc(*(u_char *)--p, fp);
+                               goto match_failure;
+                       }
+                       c = ((u_char *)p)[-1];
+                       if (c == 'x' || c == 'X') {
+                               --p;
+                               (void)ungetc(c, fp);
+                       }
+                       if ((flags & SUPPRESS) == 0) {
+                               uintmax_t res;
+
+                               *p = 0;
+                               if ((flags & UNSIGNED) == 0)
+                                   res = strtoimax(buf, (char **)NULL, base);
+                               else
+                                   res = strtoumax(buf, (char **)NULL, base);
+                               if (flags & POINTER)
+                                       *va_arg(ap, void **) =
+                                                       (void *)(uintptr_t)res;
+                               else if (flags & SHORTSHORT)
+                                       *va_arg(ap, char *) = (char)res;
+                               else if (flags & SHORT)
+                                       *va_arg(ap, short *) = (short)res;
+                               else if (flags & LONG)
+                                       *va_arg(ap, long *) = (long)res;
+                               else if (flags & LONGLONG)
+                                       *va_arg(ap, long long *) = res;
+                               else if (flags & INTMAXT)
+                                       *va_arg(ap, intmax_t *) = res;
+                               else if (flags & PTRDIFFT)
+                                       *va_arg(ap, ptrdiff_t *) =
+                                           (ptrdiff_t)res;
+                               else if (flags & SIZET)
+                                       *va_arg(ap, size_t *) = (size_t)res;
+                               else
+                                       *va_arg(ap, int *) = (int)res;
+                               nassigned++;
+                       }
+                       nread += p - buf;
+                       nconversions++;
+                       break;
+
+#ifndef NO_FLOATING_POINT
+               case CT_FLOAT:
+                       /* scan a floating point number as if by strtod */
+                       if (width == 0 || width > sizeof(buf) - 1)
+                               width = sizeof(buf) - 1;
+                       if ((width = parsefloat(fp, buf, buf + width)) == 0)
+                               goto match_failure;
+                       if ((flags & SUPPRESS) == 0) {
+                               if (flags & LONGDBL) {
+                                       long double res = strtold(buf, &p);
+                                       *va_arg(ap, long double *) = res;
+                               } else if (flags & LONG) {
+                                       double res = strtod(buf, &p);
+                                       *va_arg(ap, double *) = res;
+                               } else {
+                                       float res = strtof(buf, &p);
+                                       *va_arg(ap, float *) = res;
+                               }
+                               if (__scanfdebug && (size_t)(p - buf) != width)
+                                       abort();
+                               nassigned++;
+                       }
+                       nread += width;
+                       nconversions++;
+                       break;
+#endif /* !NO_FLOATING_POINT */
+               }
+       }
+input_failure:
+       return (nconversions != 0 ? nassigned : EOF);
+match_failure:
+       return (nassigned);
+}
+
+/*
+ * Fill in the given table from the scanset at the given format
+ * (just after `[').  Return a pointer to the character past the
+ * closing `]'.  The table has a 1 wherever characters should be
+ * considered part of the scanset.
+ */
+static const u_char *
+__sccl(tab, fmt)
+       char *tab;
+       const u_char *fmt;
+{
+       int c, n, v, i;
+
+       _DIAGASSERT(tab != NULL);
+       _DIAGASSERT(fmt != NULL);
+       /* first `clear' the whole table */
+       c = *fmt++;             /* first char hat => negated scanset */
+       if (c == '^') {
+               v = 1;          /* default => accept */
+               c = *fmt++;     /* get new first char */
+       } else
+               v = 0;          /* default => reject */
+
+       /* XXX: Will not work if sizeof(tab*) > sizeof(char) */
+       (void)memset(tab, v, 256);
+
+       if (c == 0)
+               return (fmt - 1);/* format ended before closing ] */
+
+       /*
+        * Now set the entries corresponding to the actual scanset
+        * to the opposite of the above.
+        *
+        * The first character may be ']' (or '-') without being special;
+        * the last character may be '-'.
+        */
+       v = 1 - v;
+       for (;;) {
+               tab[c] = v;             /* take character c */
+doswitch:
+               n = *fmt++;             /* and examine the next */
+               switch (n) {
+
+               case 0:                 /* format ended too soon */
+                       return (fmt - 1);
+
+               case '-':
+                       /*
+                        * A scanset of the form
+                        *      [01+-]
+                        * is defined as `the digit 0, the digit 1,
+                        * the character +, the character -', but
+                        * the effect of a scanset such as
+                        *      [a-zA-Z0-9]
+                        * is implementation defined.  The V7 Unix
+                        * scanf treats `a-z' as `the letters a through
+                        * z', but treats `a-a' as `the letter a, the
+                        * character -, and the letter a'.
+                        *
+                        * For compatibility, the `-' is not considerd
+                        * to define a range if the character following
+                        * it is either a close bracket (required by ANSI)
+                        * or is not numerically greater than the character
+                        * we just stored in the table (c).
+                        */
+                       n = *fmt;
+                       if (n == ']' || (__collate_load_error ? n < c :
+                           __collate_range_cmp(n, c) < 0)) {
+                               c = '-';
+                               break;  /* resume the for(;;) */
+                       }
+                       fmt++;
+                       /* fill in the range */
+                       if (__collate_load_error) {
+                               do
+                                       tab[++c] = v;
+                               while (c < n);
+                       } else {
+                               for (i = 0; i < 256; i ++)
+                                       if (__collate_range_cmp(c, i) < 0 &&
+                                           __collate_range_cmp(i, n) <= 0)
+                                               tab[i] = v;
+                       }
+#if 1  /* XXX another disgusting compatibility hack */
+                       c = n;
+                       /*
+                        * Alas, the V7 Unix scanf also treats formats
+                        * such as [a-c-e] as `the letters a through e'.
+                        * This too is permitted by the standard....
+                        */
+                       goto doswitch;
+#else
+                       c = *fmt++;
+                       if (c == 0)
+                               return (fmt - 1);
+                       if (c == ']')
+                               return (fmt);
+#endif
+
+               case ']':               /* end of scanset */
+                       return (fmt);
+
+               default:                /* just another character */
+                       c = n;
+                       break;
+               }
+       }
+       /* NOTREACHED */
+}
+
+#ifndef NO_FLOATING_POINT
+static int
+parsefloat(FILE *fp, char *buf, char *end)
+{
+       char *commit, *p;
+       int infnanpos = 0;
+       enum {
+               S_START, S_GOTSIGN, S_INF, S_NAN, S_MAYBEHEX,
+               S_DIGITS, S_FRAC, S_EXP, S_EXPDIGITS
+       } state = S_START;
+       unsigned char c;
+       char decpt = *localeconv()->decimal_point;
+       _Bool gotmantdig = 0, ishex = 0;
+
+       /*
+        * We set commit = p whenever the string we have read so far
+        * constitutes a valid representation of a floating point
+        * number by itself.  At some point, the parse will complete
+        * or fail, and we will ungetc() back to the last commit point.
+        * To ensure that the file offset gets updated properly, it is
+        * always necessary to read at least one character that doesn't
+        * match; thus, we can't short-circuit "infinity" or "nan(...)".
+        */
+       commit = buf - 1;
+       for (p = buf; p < end; ) {
+               c = *fp->_p;
+reswitch:
+               switch (state) {
+               case S_START:
+                       state = S_GOTSIGN;
+                       if (c == '-' || c == '+')
+                               break;
+                       else
+                               goto reswitch;
+               case S_GOTSIGN:
+                       switch (c) {
+                       case '0':
+                               state = S_MAYBEHEX;
+                               commit = p;
+                               break;
+                       case 'I':
+                       case 'i':
+                               state = S_INF;
+                               break;
+                       case 'N':
+                       case 'n':
+                               state = S_NAN;
+                               break;
+                       default:
+                               state = S_DIGITS;
+                               goto reswitch;
+                       }
+                       break;
+               case S_INF:
+                       if (infnanpos > 6 ||
+                           (c != "nfinity"[infnanpos] &&
+                            c != "NFINITY"[infnanpos]))
+                               goto parsedone;
+                       if (infnanpos == 1 || infnanpos == 6)
+                               commit = p;     /* inf or infinity */
+                       infnanpos++;
+                       break;
+               case S_NAN:
+                       switch (infnanpos) {
+                       case -1:        /* XXX kludge to deal with nan(...) */
+                               goto parsedone;
+                       case 0:
+                               if (c != 'A' && c != 'a')
+                                       goto parsedone;
+                               break;
+                       case 1:
+                               if (c != 'N' && c != 'n')
+                                       goto parsedone;
+                               else
+                                       commit = p;
+                               break;
+                       case 2:
+                               if (c != '(')
+                                       goto parsedone;
+                               break;
+                       default:
+                               if (c == ')') {
+                                       commit = p;
+                                       infnanpos = -2;
+                               } else if (!isalnum(c) && c != '_')
+                                       goto parsedone;
+                               break;
+                       }
+                       infnanpos++;
+                       break;
+               case S_MAYBEHEX:
+                       state = S_DIGITS;
+                       if (c == 'X' || c == 'x') {
+                               ishex = 1;
+                               break;
+                       } else {        /* we saw a '0', but no 'x' */
+                               gotmantdig = 1;
+                               goto reswitch;
+                       }
+               case S_DIGITS:
+                       if ((ishex && isxdigit(c)) || isdigit(c))
+                               gotmantdig = 1;
+                       else {
+                               state = S_FRAC;
+                               if (c != decpt)
+                                       goto reswitch;
+                       }
+                       if (gotmantdig)
+                               commit = p;
+                       break;
+               case S_FRAC:
+                       if (((c == 'E' || c == 'e') && !ishex) ||
+                           ((c == 'P' || c == 'p') && ishex)) {
+                               if (!gotmantdig)
+                                       goto parsedone;
+                               else
+                                       state = S_EXP;
+                       } else if ((ishex && isxdigit(c)) || isdigit(c)) {
+                               commit = p;
+                               gotmantdig = 1;
+                       } else
+                               goto parsedone;
+                       break;
+               case S_EXP:
+                       state = S_EXPDIGITS;
+                       if (c == '-' || c == '+')
+                               break;
+                       else
+                               goto reswitch;
+               case S_EXPDIGITS:
+                       if (isdigit(c))
+                               commit = p;
+                       else
+                               goto parsedone;
+                       break;
+               default:
+                       abort();
+               }
+               *p++ = c;
+               if (--fp->_r > 0)
+                       fp->_p++;
+               else if (__srefill(fp))
+                       break;  /* EOF */
+       }
+
+parsedone:
+       while (commit < --p)
+               (void)ungetc(*(u_char *)p, fp);
+       *++commit = '\0';
+       return (commit - buf);
+}
+#endif
diff --git a/lib/nbsd_libc/stdio/vfwprintf.c b/lib/nbsd_libc/stdio/vfwprintf.c
new file mode 100644 (file)
index 0000000..143afc0
--- /dev/null
@@ -0,0 +1,2019 @@
+/*     $NetBSD: vfwprintf.c,v 1.23 2010/12/16 17:42:27 wiz Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
+__FBSDID("$FreeBSD: src/lib/libc/stdio/vfwprintf.c,v 1.27 2007/01/09 00:28:08 imp Exp $");
+#else
+__RCSID("$NetBSD: vfwprintf.c,v 1.23 2010/12/16 17:42:27 wiz Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Actual {w,}printf innards.
+ */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <limits.h>
+#include <locale.h>
+#include <stdarg.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#include "reentrant.h"
+#include "local.h"
+#include "extern.h"
+#include "fvwrite.h"
+
+#ifndef NARROW
+#define MCHAR_T                char
+#define CHAR_T         wchar_t
+#define STRLEN(a)      wcslen(a)
+#define MEMCHR(a, b, c)        wmemchr(a, b, c)
+#define SCONV(a, b)    __mbsconv(a, b)
+#define STRCONST(a)    L ## a
+#define WDECL(a, b)    a ## w ## b
+#define END_OF_FILE    WEOF
+#define MULTI          0
+#else
+#define MCHAR_T                wchar_t
+#define CHAR_T         char
+#define STRLEN(a)      strlen(a)
+#define MEMCHR(a, b, c)        memchr(a, b, c)
+#define SCONV(a, b)    __wcsconv(a, b)
+#define STRCONST(a)    a
+#define WDECL(a, b)    a ## b
+#define END_OF_FILE    EOF
+#define MULTI          LONGINT
+#endif
+
+union arg {
+       int     intarg;
+       u_int   uintarg;
+       long    longarg;
+       u_long  ulongarg;
+       long long longlongarg;
+       unsigned long long ulonglongarg;
+       ptrdiff_t ptrdiffarg;
+       ssize_t ssizearg;
+       size_t  sizearg;
+       intmax_t intmaxarg;
+       uintmax_t uintmaxarg;
+       void    *pvoidarg;
+       char    *pchararg;
+       signed char *pschararg;
+       short   *pshortarg;
+       int     *pintarg;
+       long    *plongarg;
+       long long *plonglongarg;
+       ptrdiff_t *pptrdiffarg;
+       size_t  *psizearg;
+       intmax_t *pintmaxarg;
+#ifndef NO_FLOATING_POINT
+       double  doublearg;
+       long double longdoublearg;
+#endif
+       wint_t  wintarg;
+       wchar_t *pwchararg;
+};
+
+/*
+ * Type ids for argument type table.
+ */
+enum typeid {
+       T_UNUSED, TP_SHORT, T_INT, T_U_INT, TP_INT,
+       T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG,
+       T_PTRDIFFT, TP_PTRDIFFT, T_SSIZET, T_SIZET, TP_SIZET,
+       T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR,
+       T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR
+};
+
+static int     __sbprintf(FILE *, const CHAR_T *, va_list);
+static CHAR_T  *__ujtoa(uintmax_t, CHAR_T *, int, int, const char *, int,
+                   char, const char *);
+static CHAR_T  *__ultoa(u_long, CHAR_T *, int, int, const char *, int,
+                   char, const char *);
+#ifndef NARROW
+static CHAR_T  *__mbsconv(char *, int);
+static wint_t  __xfputwc(CHAR_T, FILE *);
+#else
+static char    *__wcsconv(wchar_t *, int);
+static int     __sprint(FILE *, struct __suio *);
+#endif
+static int     __find_arguments(const CHAR_T *, va_list, union arg **);
+static int     __grow_type_table(int, enum typeid **, int *);
+
+/*
+ * Helper function for `fprintf to unbuffered unix file': creates a
+ * temporary buffer.  We only work on write-only files; this avoids
+ * worries about ungetc buffers and so forth.
+ */
+static int
+__sbprintf(FILE *fp, const CHAR_T *fmt, va_list ap)
+{
+       int ret;
+       FILE fake;
+       struct __sfileext fakeext;
+       unsigned char buf[BUFSIZ];
+
+       _DIAGASSERT(fp != NULL);
+       _DIAGASSERT(fmt != NULL);
+
+       _FILEEXT_SETUP(&fake, &fakeext);
+       memset(WCIO_GET(&fake), 0, sizeof(struct wchar_io_data));
+
+       /* copy the important variables */
+       fake._flags = fp->_flags & ~__SNBF;
+       fake._file = fp->_file;
+       fake._cookie = fp->_cookie;
+       fake._write = fp->_write;
+
+       /* set up the buffer */
+       fake._bf._base = fake._p = buf;
+       fake._bf._size = fake._w = sizeof(buf);
+       fake._lbfsize = 0;      /* not actually used, but Just In Case */
+
+       /* do the work, then copy any error status */
+       ret = WDECL(__vf,printf_unlocked)(&fake, fmt, ap);
+       if (ret >= 0 && fflush(&fake))
+               ret = END_OF_FILE;
+       if (fake._flags & __SERR)
+               fp->_flags |= __SERR;
+       return (ret);
+}
+
+#ifndef NARROW
+/*
+ * Like __fputwc, but handles fake string (__SSTR) files properly.
+ * File must already be locked.
+ */
+static wint_t
+__xfputwc(wchar_t wc, FILE *fp)
+{
+       static const mbstate_t initial;
+       mbstate_t mbs;
+       char buf[MB_LEN_MAX];
+       struct __suio uio;
+       struct __siov iov;
+       size_t len;
+
+       if ((fp->_flags & __SSTR) == 0)
+               return (__fputwc_unlock(wc, fp));
+
+       mbs = initial;
+       if ((len = wcrtomb(buf, wc, &mbs)) == (size_t)-1) {
+               fp->_flags |= __SERR;
+               return (END_OF_FILE);
+       }
+       uio.uio_iov = &iov;
+       uio.uio_resid = len;
+       uio.uio_iovcnt = 1;
+       iov.iov_base = buf;
+       iov.iov_len = len;
+       return (__sfvwrite(fp, &uio) != EOF ? (wint_t)wc : END_OF_FILE);
+}
+#else
+/*
+ * Flush out all the vectors defined by the given uio,
+ * then reset it so that it can be reused.
+ */
+static int
+__sprint(FILE *fp, struct __suio *uio)
+{
+       int err;
+
+       _DIAGASSERT(fp != NULL);
+       _DIAGASSERT(uio != NULL);
+
+       if (uio->uio_resid == 0) {
+               uio->uio_iovcnt = 0;
+               return (0);
+       }
+       err = __sfvwrite(fp, uio);
+       uio->uio_resid = 0;
+       uio->uio_iovcnt = 0;
+       return (err);
+}
+#endif
+
+/*
+ * Macros for converting digits to letters and vice versa
+ */
+#define        to_digit(c)     ((c) - '0')
+#define is_digit(c)    ((unsigned)to_digit(c) <= 9)
+#define        to_char(n)      (CHAR_T)((n) + '0')
+
+/*
+ * Convert an unsigned long to ASCII for printf purposes, returning
+ * a pointer to the first character of the string representation.
+ * Octal numbers can be forced to have a leading zero; hex numbers
+ * use the given digits.
+ */
+static CHAR_T *
+__ultoa(u_long val, CHAR_T *endp, int base, int octzero, const char *xdigs,
+       int needgrp, char thousep, const char *grp)
+{
+       CHAR_T *cp = endp;
+       long sval;
+       int ndig;
+
+       /*
+        * Handle the three cases separately, in the hope of getting
+        * better/faster code.
+        */
+       switch (base) {
+       case 10:
+               if (val < 10) { /* many numbers are 1 digit */
+                       *--cp = to_char(val);
+                       return (cp);
+               }
+               ndig = 0;
+               /*
+                * On many machines, unsigned arithmetic is harder than
+                * signed arithmetic, so we do at most one unsigned mod and
+                * divide; this is sufficient to reduce the range of
+                * the incoming value to where signed arithmetic works.
+                */
+               if (val > LONG_MAX) {
+                       *--cp = to_char(val % 10);
+                       ndig++;
+                       sval = val / 10;
+               } else
+                       sval = val;
+               do {
+                       *--cp = to_char(sval % 10);
+                       ndig++;
+                       /*
+                        * If (*grp == CHAR_MAX) then no more grouping
+                        * should be performed.
+                        */
+                       if (needgrp && ndig == *grp && *grp != CHAR_MAX
+                                       && sval > 9) {
+                               *--cp = thousep;
+                               ndig = 0;
+                               /*
+                                * If (*(grp+1) == '\0') then we have to
+                                * use *grp character (last grouping rule)
+                                * for all next cases
+                                */
+                               if (*(grp+1) != '\0')
+                                       grp++;
+                       }
+                       sval /= 10;
+               } while (sval != 0);
+               break;
+
+       case 8:
+               do {
+                       *--cp = to_char(val & 7);
+                       val >>= 3;
+               } while (val);
+               if (octzero && *cp != '0')
+                       *--cp = '0';
+               break;
+
+       case 16:
+               do {
+                       *--cp = xdigs[(size_t)val & 15];
+                       val >>= 4;
+               } while (val);
+               break;
+
+       default:                        /* oops */
+               abort();
+       }
+       return (cp);
+}
+
+/* Identical to __ultoa, but for intmax_t. */
+static CHAR_T *
+__ujtoa(uintmax_t val, CHAR_T *endp, int base, int octzero,
+       const char *xdigs, int needgrp, char thousep, const char *grp)
+{
+       CHAR_T *cp = endp;
+       intmax_t sval;
+       int ndig;
+
+       /* quick test for small values; __ultoa is typically much faster */
+       /* (perhaps instead we should run until small, then call __ultoa?) */
+       if (val <= ULONG_MAX)
+               return (__ultoa((u_long)val, endp, base, octzero, xdigs,
+                   needgrp, thousep, grp));
+       switch (base) {
+       case 10:
+               if (val < 10) {
+                       *--cp = to_char(val % 10);
+                       return (cp);
+               }
+               ndig = 0;
+               if (val > INTMAX_MAX) {
+                       *--cp = to_char(val % 10);
+                       ndig++;
+                       sval = val / 10;
+               } else
+                       sval = val;
+               do {
+                       *--cp = to_char(sval % 10);
+                       ndig++;
+                       /*
+                        * If (*grp == CHAR_MAX) then no more grouping
+                        * should be performed.
+                        */
+                       if (needgrp && *grp != CHAR_MAX && ndig == *grp
+                                       && sval > 9) {
+                               *--cp = thousep;
+                               ndig = 0;
+                               /*
+                                * If (*(grp+1) == '\0') then we have to
+                                * use *grp character (last grouping rule)
+                                * for all next cases
+                                */
+                               if (*(grp+1) != '\0')
+                                       grp++;
+                       }
+                       sval /= 10;
+               } while (sval != 0);
+               break;
+
+       case 8:
+               do {
+                       *--cp = to_char(val & 7);
+                       val >>= 3;
+               } while (val);
+               if (octzero && *cp != '0')
+                       *--cp = '0';
+               break;
+
+       case 16:
+               do {
+                       *--cp = xdigs[(size_t)val & 15];
+                       val >>= 4;
+               } while (val);
+               break;
+
+       default:
+               abort();
+       }
+       return (cp);
+}
+
+#ifndef NARROW
+/*
+ * Convert a multibyte character string argument for the %s format to a wide
+ * string representation. ``prec'' specifies the maximum number of bytes
+ * to output. If ``prec'' is greater than or equal to zero, we can't assume
+ * that the multibyte char. string ends in a null character.
+ */
+static wchar_t *
+__mbsconv(char *mbsarg, int prec)
+{
+       static const mbstate_t initial;
+       mbstate_t mbs;
+       wchar_t *convbuf, *wcp;
+       const char *p;
+       size_t insize, nchars, nconv;
+
+       if (mbsarg == NULL)
+               return (NULL);
+
+       /*
+        * Supplied argument is a multibyte string; convert it to wide
+        * characters first.
+        */
+       if (prec >= 0) {
+               /*
+                * String is not guaranteed to be NUL-terminated. Find the
+                * number of characters to print.
+                */
+               p = mbsarg;
+               insize = nchars = nconv = 0;
+               mbs = initial;
+               while (nchars != (size_t)prec) {
+                       nconv = mbrlen(p, MB_CUR_MAX, &mbs);
+                       if (nconv == 0 || nconv == (size_t)-1 ||
+                           nconv == (size_t)-2)
+                               break;
+                       p += nconv;
+                       nchars++;
+                       insize += nconv;
+               }
+               if (nconv == (size_t)-1 || nconv == (size_t)-2)
+                       return (NULL);
+       } else
+               insize = strlen(mbsarg);
+
+       /*
+        * Allocate buffer for the result and perform the conversion,
+        * converting at most `size' bytes of the input multibyte string to
+        * wide characters for printing.
+        */
+       convbuf = malloc((insize + 1) * sizeof(*convbuf));
+       if (convbuf == NULL)
+               return (NULL);
+       wcp = convbuf;
+       p = mbsarg;
+       mbs = initial;
+       nconv = 0;
+       while (insize != 0) {
+               nconv = mbrtowc(wcp, p, insize, &mbs);
+               if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
+                       break;
+               wcp++;
+               p += nconv;
+               insize -= nconv;
+       }
+       if (nconv == (size_t)-1 || nconv == (size_t)-2) {
+               free(convbuf);
+               return (NULL);
+       }
+       *wcp = L'\0';
+
+       return (convbuf);
+}
+#else
+/*
+ * Convert a wide-character string argument for the %ls format to a multibyte
+ * string representation. If not -1, prec specifies the maximum number of
+ * bytes to output, and also means that we can't assume that the wide-char.
+ * string ends is null-terminated.
+ */
+static char *
+__wcsconv(wchar_t *wcsarg, int prec)
+{
+       static const mbstate_t initial;
+       mbstate_t mbs;
+       char buf[MB_LEN_MAX];
+       wchar_t *p;
+       char *convbuf;
+       size_t clen, nbytes;
+
+       /* Allocate space for the maximum number of bytes we could output. */
+       if (prec < 0) {
+               p = wcsarg;
+               mbs = initial;
+               nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
+               if (nbytes == (size_t)-1)
+                       return (NULL);
+       } else {
+               /*
+                * Optimisation: if the output precision is small enough,
+                * just allocate enough memory for the maximum instead of
+                * scanning the string.
+                */
+               if (prec < 128)
+                       nbytes = prec;
+               else {
+                       nbytes = 0;
+                       p = wcsarg;
+                       mbs = initial;
+                       for (;;) {
+                               clen = wcrtomb(buf, *p++, &mbs);
+                               if (clen == 0 || clen == (size_t)-1 ||
+                                   nbytes + clen > (size_t)prec)
+                                       break;
+                               nbytes += clen;
+                       }
+               }
+       }
+       if ((convbuf = malloc(nbytes + 1)) == NULL)
+               return (NULL);
+
+       /* Fill the output buffer. */
+       p = wcsarg;
+       mbs = initial;
+       if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
+           nbytes, &mbs)) == (size_t)-1) {
+               free(convbuf);
+               return (NULL);
+       }
+       convbuf[nbytes] = '\0';
+       return (convbuf);
+}
+#endif
+
+/*
+ * MT-safe version
+ */
+int
+WDECL(vf,printf)(FILE * __restrict fp, const CHAR_T * __restrict fmt0, va_list ap)
+{
+       int ret;
+
+       FLOCKFILE(fp);
+       ret = WDECL(__vf,printf_unlocked)(fp, fmt0, ap);
+       FUNLOCKFILE(fp);
+       return (ret);
+}
+
+#ifndef NO_FLOATING_POINT
+
+#include <float.h>
+#include <math.h>
+#include "floatio.h"
+
+#define        DEFPREC         6
+
+static int exponent(CHAR_T *, int, int);
+#ifndef WIDE_DOUBLE
+static char *cvt(double, int, int, char *, int *, int, int *);
+#endif
+
+#endif /* !NO_FLOATING_POINT */
+
+/*
+ * The size of the buffer we use as scratch space for integer
+ * conversions, among other things.  Technically, we would need the
+ * most space for base 10 conversions with thousands' grouping
+ * characters between each pair of digits.  100 bytes is a
+ * conservative overestimate even for a 128-bit uintmax_t.
+ */
+#define        BUF     100
+
+#define STATIC_ARG_TBL_SIZE 8           /* Size of static argument table. */
+
+/*
+ * Flags used during conversion.
+ */
+#define        ALT             0x001           /* alternate form */
+#define        LADJUST         0x004           /* left adjustment */
+#define        LONGDBL         0x008           /* long double */
+#define        LONGINT         0x010           /* long integer */
+#define        LLONGINT        0x020           /* long long integer */
+#define        SHORTINT        0x040           /* short integer */
+#define        ZEROPAD         0x080           /* zero (as opposed to blank) pad */
+#define        FPT             0x100           /* Floating point number */
+#define        GROUPING        0x200           /* use grouping ("'" flag) */
+                                       /* C99 additional size modifiers: */
+#define        SIZET           0x400           /* size_t */
+#define        PTRDIFFT        0x800           /* ptrdiff_t */
+#define        INTMAXT         0x1000          /* intmax_t */
+#define        CHARINT         0x2000          /* print char using int format */
+
+/*
+ * Non-MT-safe version
+ */
+int
+WDECL(__vf,printf_unlocked)(FILE *fp, const CHAR_T *fmt0, va_list ap)
+{
+       CHAR_T *fmt;            /* format string */
+       int ch;                 /* character from fmt */
+       int n, n2;              /* handy integer (short term usage) */
+       CHAR_T *cp;             /* handy char pointer (short term usage) */
+       int flags;              /* flags as above */
+       int ret;                /* return value accumulator */
+       int width;              /* width from format (%8d), or 0 */
+       int prec;               /* precision from format; <0 for N/A */
+       CHAR_T sign;            /* sign prefix (' ', '+', '-', or \0) */
+       char thousands_sep;     /* locale specific thousands separator */
+       const char *grouping;   /* locale specific numeric grouping rules */
+#ifndef NO_FLOATING_POINT
+       /*
+        * We can decompose the printed representation of floating
+        * point numbers into several parts, some of which may be empty:
+        *
+        * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
+        *    A       B     ---C---      D       E   F
+        *
+        * A:   'sign' holds this value if present; '\0' otherwise
+        * B:   ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
+        * C:   cp points to the string MMMNNN.  Leading and trailing
+        *      zeros are not in the string and must be added.
+        * D:   expchar holds this character; '\0' if no exponent, e.g. %f
+        * F:   at least two digits for decimal, at least one digit for hex
+        */
+       char *decimal_point;    /* locale specific decimal point */
+#ifdef WIDE_DOUBLE
+       int signflag;           /* true if float is negative */
+       union {                 /* floating point arguments %[aAeEfFgG] */
+               double dbl;
+               long double ldbl;
+       } fparg;
+       char *dtoaend;          /* pointer to end of converted digits */
+#else
+       double _double;         /* double precision arguments %[eEfgG] */
+       char softsign;          /* temporary negative sign for floats */
+#endif
+       char *dtoaresult;       /* buffer allocated by dtoa */
+       int expt;               /* integer value of exponent */
+       char expchar;           /* exponent character: [eEpP\0] */
+       int expsize;            /* character count for expstr */
+       int lead;               /* sig figs before decimal or group sep */
+       int ndig;               /* actual number of digits returned by dtoa */
+       CHAR_T expstr[MAXEXPDIG+2];     /* buffer for exponent string: e+ZZZ */
+       int nseps;              /* number of group separators with ' */
+       int nrepeats;           /* number of repeats of the last group */
+#endif
+       u_long  ulval;          /* integer arguments %[diouxX] */
+       uintmax_t ujval;        /* %j, %ll, %q, %t, %z integers */
+       int base;               /* base for [diouxX] conversion */
+       int dprec;              /* a copy of prec if [diouxX], 0 otherwise */
+       int realsz;             /* field size expanded by dprec, sign, etc */
+       int size;               /* size of converted field or string */
+       int prsize;             /* max size of printed field */
+       const char *xdigs;      /* digits for %[xX] conversion */
+#ifdef NARROW
+#define NIOV 8
+       struct __siov *iovp;    /* for PRINT macro */
+       struct __suio uio;      /* output information: summary */
+       struct __siov iov[NIOV];/* ... and individual io vectors */
+#else
+       int n3;
+#endif
+       CHAR_T buf[BUF];        /* buffer with space for digits of uintmax_t */
+       CHAR_T ox[2];           /* space for 0x hex-prefix */
+       union arg *argtable;    /* args, built due to positional arg */
+       union arg statargtable [STATIC_ARG_TBL_SIZE];
+       int nextarg;            /* 1-based argument index */
+       va_list orgap;          /* original argument pointer */
+       CHAR_T *convbuf;        /* multibyte to wide conversion result */
+
+       /*
+        * Choose PADSIZE to trade efficiency vs. size.  If larger printf
+        * fields occur frequently, increase PADSIZE and make the initialisers
+        * below longer.
+        */
+#define        PADSIZE 16              /* pad chunk size */
+       static CHAR_T blanks[PADSIZE] =
+        {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
+       static CHAR_T zeroes[PADSIZE] =
+        {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
+
+       static const char xdigs_lower[16] = "0123456789abcdef";
+       static const char xdigs_upper[16] = "0123456789ABCDEF";
+
+       /*
+        * BEWARE, these `goto error' on error, PRINT uses `n2' and
+        * PAD uses `n'.
+        */
+#ifndef NARROW
+#define        PRINT(ptr, len) do {                    \
+       for (n3 = 0; n3 < (len); n3++)          \
+               __xfputwc((ptr)[n3], fp);       \
+} while (/*CONSTCOND*/0)
+#define FLUSH()
+#else
+#define        PRINT(ptr, len) do { \
+       iovp->iov_base = __UNCONST(ptr); \
+       iovp->iov_len = (len); \
+       uio.uio_resid += (len); \
+       iovp++; \
+       if (++uio.uio_iovcnt >= NIOV) { \
+               if (__sprint(fp, &uio)) \
+                       goto error; \
+               iovp = iov; \
+       } \
+} while (/*CONSTCOND*/0)
+#define        FLUSH() do { \
+       if (uio.uio_resid && __sprint(fp, &uio)) \
+               goto error; \
+       uio.uio_iovcnt = 0; \
+       iovp = iov; \
+} while (/*CONSTCOND*/0)
+#endif /* NARROW */
+
+#define        PAD(howmany, with)      do {            \
+       if ((n = (howmany)) > 0) {              \
+               while (n > PADSIZE) {           \
+                       PRINT(with, PADSIZE);   \
+                       n -= PADSIZE;           \
+               }                               \
+               PRINT(with, n);                 \
+       }                                       \
+} while (/*CONSTCOND*/0)
+#define        PRINTANDPAD(p, ep, len, with) do {      \
+       n2 = (ep) - (p);                        \
+       if (n2 > (len))                         \
+               n2 = (len);                     \
+       if (n2 > 0)                             \
+               PRINT((p), n2);                 \
+       PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
+} while(/*CONSTCOND*/0)
+
+       /*
+        * Get the argument indexed by nextarg.   If the argument table is
+        * built, use it to get the argument.  If its not, get the next
+        * argument (and arguments must be gotten sequentially).
+        */
+#define GETARG(type) \
+       ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
+           (nextarg++, va_arg(ap, type)))
+
+       /*
+        * To extend shorts properly, we need both signed and unsigned
+        * argument extraction methods.
+        */
+#define        SARG() \
+       (flags&LONGINT ? GETARG(long) : \
+           flags&SHORTINT ? (long)(short)GETARG(int) : \
+           flags&CHARINT ? (long)(signed char)GETARG(int) : \
+           (long)GETARG(int))
+#define        UARG() \
+       (flags&LONGINT ? GETARG(u_long) : \
+           flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
+           flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
+           (u_long)GETARG(u_int))
+#define        INTMAX_SIZE     (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
+#define SJARG() \
+       (flags&INTMAXT ? GETARG(intmax_t) : \
+           flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
+           flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
+           (intmax_t)GETARG(long long))
+#define        UJARG() \
+       (flags&INTMAXT ? GETARG(uintmax_t) : \
+           flags&SIZET ? (uintmax_t)GETARG(size_t) : \
+           flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
+           (uintmax_t)GETARG(unsigned long long))
+
+       /*
+        * Get * arguments, including the form *nn$.  Preserve the nextarg
+        * that the argument can be gotten once the type is determined.
+        */
+#define GETASTER(val) \
+       n2 = 0; \
+       cp = fmt; \
+       while (is_digit(*cp)) { \
+               n2 = 10 * n2 + to_digit(*cp); \
+               cp++; \
+       } \
+       if (*cp == '$') { \
+               int hold = nextarg; \
+               if (argtable == NULL) { \
+                       argtable = statargtable; \
+                       if (__find_arguments(fmt0, orgap, &argtable) == -1) \
+                               goto oomem; \
+               } \
+               nextarg = n2; \
+               val = GETARG (int); \
+               nextarg = hold; \
+               fmt = ++cp; \
+       } else { \
+               val = GETARG (int); \
+       }
+
+       _DIAGASSERT(fp != NULL);
+       _DIAGASSERT(fmt0 != NULL);
+
+       _SET_ORIENTATION(fp, -1);
+
+       ndig = -1;      /* XXX gcc */
+
+       thousands_sep = '\0';
+       grouping = NULL;
+#ifndef NO_FLOATING_POINT
+       decimal_point = localeconv()->decimal_point;
+       expsize = 0;            /* XXXGCC -Wuninitialized [sh3,m68000] */
+#endif
+       convbuf = NULL;
+       /* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */
+       if (cantwrite(fp)) {
+               errno = EBADF;
+               return (END_OF_FILE);
+       }
+
+       /* optimise fprintf(stderr) (and other unbuffered Unix files) */
+       if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
+           __sfileno(fp) != -1)
+               return (__sbprintf(fp, fmt0, ap));
+
+       fmt = (CHAR_T *)__UNCONST(fmt0);
+       argtable = NULL;
+       nextarg = 1;
+       va_copy(orgap, ap);
+#ifdef NARROW
+       uio.uio_iov = iovp = iov;
+       uio.uio_resid = 0;
+       uio.uio_iovcnt = 0;
+#endif
+       ret = 0;
+
+       /*
+        * Scan the format for conversions (`%' character).
+        */
+       for (;;) {
+               const CHAR_T *result;
+
+               for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
+                       continue;
+               if ((n = fmt - cp) != 0) {
+                       if ((unsigned)ret + n > INT_MAX) {
+                               ret = END_OF_FILE;
+                               goto error;
+                       }
+                       PRINT(cp, n);
+                       ret += n;
+               }
+               if (ch == '\0')
+                       goto done;
+               fmt++;          /* skip over '%' */
+
+               flags = 0;
+               dprec = 0;
+               width = 0;
+               prec = -1;
+               sign = '\0';
+               ox[1] = '\0';
+               expchar = '\0';
+               lead = 0;
+               nseps = nrepeats = 0;
+               ulval = 0;
+               ujval = 0;
+               xdigs = NULL;
+
+rflag:         ch = *fmt++;
+reswitch:      switch (ch) {
+               case ' ':
+                       /*-
+                        * ``If the space and + flags both appear, the space
+                        * flag will be ignored.''
+                        *      -- ANSI X3J11
+                        */
+                       if (!sign)
+                               sign = ' ';
+                       goto rflag;
+               case '#':
+                       flags |= ALT;
+                       goto rflag;
+               case '*':
+                       /*-
+                        * ``A negative field width argument is taken as a
+                        * - flag followed by a positive field width.''
+                        *      -- ANSI X3J11
+                        * They don't exclude field widths read from args.
+                        */
+                       GETASTER (width);
+                       if (width >= 0)
+                               goto rflag;
+                       width = -width;
+                       /* FALLTHROUGH */
+               case '-':
+                       flags |= LADJUST;
+                       goto rflag;
+               case '+':
+                       sign = '+';
+                       goto rflag;
+               case '\'':
+                       flags |= GROUPING;
+                       thousands_sep = *(localeconv()->thousands_sep);
+                       grouping = localeconv()->grouping;
+                       /* If the locale doesn't define the above, use sane
+                        * defaults - otherwise silly things happen! */
+                       if (thousands_sep == 0)
+                               thousands_sep = ',';
+                       if (!grouping || !*grouping)
+                               grouping = "\3";
+                       goto rflag;
+               case '.':
+                       if ((ch = *fmt++) == '*') {
+                               GETASTER (prec);
+                               goto rflag;
+                       }
+                       prec = 0;
+                       while (is_digit(ch)) {
+                               prec = 10 * prec + to_digit(ch);
+                               ch = *fmt++;
+                       }
+                       goto reswitch;
+               case '0':
+                       /*-
+                        * ``Note that 0 is taken as a flag, not as the
+                        * beginning of a field width.''
+                        *      -- ANSI X3J11
+                        */
+                       flags |= ZEROPAD;
+                       goto rflag;
+               case '1': case '2': case '3': case '4':
+               case '5': case '6': case '7': case '8': case '9':
+                       n = 0;
+                       do {
+                               n = 10 * n + to_digit(ch);
+                               ch = *fmt++;
+                       } while (is_digit(ch));
+                       if (ch == '$') {
+                               nextarg = n;
+                               if (argtable == NULL) {
+                                       argtable = statargtable;
+                                       if (__find_arguments(fmt0, orgap,
+                                           &argtable) == -1)
+                                               goto oomem;
+                               }
+                               goto rflag;
+                       }
+                       width = n;
+                       goto reswitch;
+#ifndef NO_FLOATING_POINT
+               case 'L':
+                       flags |= LONGDBL;
+                       goto rflag;
+#endif
+               case 'h':
+                       if (flags & SHORTINT) {
+                               flags &= ~SHORTINT;
+                               flags |= CHARINT;
+                       } else
+                               flags |= SHORTINT;
+                       goto rflag;
+               case 'j':
+                       flags |= INTMAXT;
+                       goto rflag;
+               case 'l':
+                       if (flags & LONGINT) {
+                               flags &= ~LONGINT;
+                               flags |= LLONGINT;
+                       } else
+                               flags |= LONGINT;
+                       goto rflag;
+               case 'q':
+                       flags |= LLONGINT;      /* not necessarily */
+                       goto rflag;
+               case 't':
+                       flags |= PTRDIFFT;
+                       goto rflag;
+               case 'z':
+                       flags |= SIZET;
+                       goto rflag;
+               case 'C':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 'c':
+#ifdef NARROW
+                       if (flags & LONGINT) {
+                               static const mbstate_t initial;
+                               mbstate_t mbs;
+                               size_t mbseqlen;
+
+                               mbs = initial;
+                               mbseqlen = wcrtomb(buf,
+                                   (wchar_t)GETARG(wint_t), &mbs);
+                               if (mbseqlen == (size_t)-1) {
+                                       fp->_flags |= __SERR;
+                                       goto error;
+                               }
+                               size = (int)mbseqlen;
+                       } else {
+                               *buf = GETARG(int);
+                               size = 1;
+                       }
+#else
+                       if (flags & LONGINT)
+                               *buf = (wchar_t)GETARG(wint_t);
+                       else
+                               *buf = (wchar_t)btowc(GETARG(int));
+                       size = 1;
+#endif
+                       result = buf;
+                       sign = '\0';
+                       break;
+               case 'D':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 'd':
+               case 'i':
+                       if (flags & INTMAX_SIZE) {
+                               ujval = SJARG();
+                               if ((intmax_t)ujval < 0) {
+                                       ujval = -ujval;
+                                       sign = '-';
+                               }
+                       } else {
+                               ulval = SARG();
+                               if ((long)ulval < 0) {
+                                       ulval = -ulval;
+                                       sign = '-';
+                               }
+                       }
+                       base = 10;
+                       goto number;
+#ifndef NO_FLOATING_POINT
+#ifdef WIDE_DOUBLE
+               case 'a':
+               case 'A':
+                       if (ch == 'a') {
+                               ox[1] = 'x';
+                               xdigs = xdigs_lower;
+                               expchar = 'p';
+                       } else {
+                               ox[1] = 'X';
+                               xdigs = xdigs_upper;
+                               expchar = 'P';
+                       }
+                       if (prec >= 0)
+                               prec++;
+                       if (flags & LONGDBL) {
+                               fparg.ldbl = GETARG(long double);
+                               dtoaresult =
+                                   __hldtoa(fparg.ldbl, xdigs, prec,
+                                       &expt, &signflag, &dtoaend);
+                       } else {
+                               fparg.dbl = GETARG(double);
+                               dtoaresult =
+                                   __hdtoa(fparg.dbl, xdigs, prec,
+                                       &expt, &signflag, &dtoaend);
+                       }
+                       if (dtoaresult == NULL)
+                               goto oomem;
+                       
+                       if (prec < 0)
+                               prec = dtoaend - dtoaresult;
+                       if (expt == INT_MAX)
+                               ox[1] = '\0';
+                       ndig = dtoaend - dtoaresult;
+                       if (convbuf != NULL)
+                               free(convbuf);
+#ifndef NARROW
+                       result = convbuf = __mbsconv(dtoaresult, -1);
+#else
+                       /*XXX inefficient*/
+                       result = convbuf = strdup(dtoaresult);
+#endif
+                       if (result == NULL)
+                               goto oomem;
+                       __freedtoa(dtoaresult);
+                       goto fp_common;
+               case 'e':
+               case 'E':
+                       expchar = ch;
+                       if (prec < 0)   /* account for digit before decpt */
+                               prec = DEFPREC + 1;
+                       else
+                               prec++;
+                       goto fp_begin;
+               case 'f':
+               case 'F':
+                       expchar = '\0';
+                       goto fp_begin;
+               case 'g':
+               case 'G':
+                       expchar = ch - ('g' - 'e');
+                       if (prec == 0)
+                               prec = 1;
+fp_begin:
+                       if (prec < 0)
+                               prec = DEFPREC;
+                       if (flags & LONGDBL) {
+                               fparg.ldbl = GETARG(long double);
+                               dtoaresult =
+                                   __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
+                                   &expt, &signflag, &dtoaend);
+                       } else {
+                               fparg.dbl = GETARG(double);
+                               dtoaresult =
+                                   __dtoa(fparg.dbl, expchar ? 2 : 3, prec,
+                                   &expt, &signflag, &dtoaend);
+                               if (expt == 9999)
+                                       expt = INT_MAX;
+                       }
+                       if (dtoaresult == NULL)
+                               goto oomem;
+                       ndig = dtoaend - dtoaresult;
+                       if (convbuf != NULL)
+                               free(convbuf);
+#ifndef NARROW
+                       result = convbuf = __mbsconv(dtoaresult, -1);
+#else
+                       /*XXX inefficient*/
+                       result = convbuf = strdup(dtoaresult);
+#endif
+                       if (result == NULL)
+                               goto oomem;
+                       __freedtoa(dtoaresult);
+fp_common:
+                       if (signflag)
+                               sign = '-';
+                       if (expt == INT_MAX) {  /* inf or nan */
+                               if (*result == 'N') {
+                                       result = (ch >= 'a') ? STRCONST("nan") :
+                                           STRCONST("NAN");
+                                       sign = '\0';
+                               } else
+                                       result = (ch >= 'a') ? STRCONST("inf") :
+                                           STRCONST("INF");
+                               size = 3;
+                               flags &= ~ZEROPAD;
+                               break;
+                       }
+#else
+               case 'e':
+               case 'E':
+               case 'f':
+               case 'F':
+               case 'g':
+               case 'G':
+                       if (prec == -1) {
+                               prec = DEFPREC;
+                       } else if ((ch == 'g' || ch == 'G') && prec == 0) {
+                               prec = 1;
+                       }
+
+                       if (flags & LONGDBL) {
+                               _double = (double) GETARG(long double);
+                       } else {
+                               _double = GETARG(double);
+                       }
+
+                       /* do this before tricky precision changes */
+                       if (isinf(_double)) {
+                               if (_double < 0)
+                                       sign = '-';
+                               if (ch == 'E' || ch == 'F' || ch == 'G')
+                                       result = STRCONST("INF");
+                               else
+                                       result = STRCONST("inf");
+                               size = 3;
+                               flags &= ~ZEROPAD;
+                               break;
+                       }
+                       if (isnan(_double)) {
+                               if (ch == 'E' || ch == 'F' || ch == 'G')
+                                       result = STRCONST("NAN");
+                               else
+                                       result = STRCONST("nan");
+                               size = 3;
+                               flags &= ~ZEROPAD;
+                               break;
+                       }
+
+                       flags |= FPT;
+                       dtoaresult = cvt(_double, prec, flags, &softsign,
+                           &expt, ch, &ndig);
+                       if (dtoaresult == NULL)
+                               goto oomem;
+                       if (convbuf != NULL)
+                               free(convbuf);
+#ifndef NARROW
+                       result = convbuf = __mbsconv(dtoaresult, -1);
+#else
+                       /*XXX inefficient*/
+                       result = convbuf = strdup(dtoaresult);
+#endif
+                       if (result == NULL)
+                               goto oomem;
+                       __freedtoa(dtoaresult);
+                       if (softsign)
+                               sign = '-';
+#endif
+                       flags |= FPT;
+                       if (ch == 'g' || ch == 'G') {
+                               if (expt > -4 && expt <= prec) {
+                                       /* Make %[gG] smell like %[fF] */
+                                       expchar = '\0';
+                                       if (flags & ALT)
+                                               prec -= expt;
+                                       else
+                                               prec = ndig - expt;
+                                       if (prec < 0)
+                                               prec = 0;
+                               } else {
+                                       /*
+                                        * Make %[gG] smell like %[eE], but
+                                        * trim trailing zeroes if no # flag.
+                                        */
+                                       if (!(flags & ALT))
+                                               prec = ndig;
+                               }
+                       }
+                       if (expchar) {
+                               expsize = exponent(expstr, expt - 1, expchar);
+                               size = expsize + prec;
+                               if (prec > 1 || flags & ALT)
+                                       ++size;
+                       } else {
+                               /* space for digits before decimal point */
+                               if (expt > 0)
+                                       size = expt;
+                               else    /* "0" */
+                                       size = 1;
+                               /* space for decimal pt and following digits */
+                               if (prec || flags & ALT)
+                                       size += prec + 1;
+                               if (grouping && expt > 0) {
+                                       /* space for thousands' grouping */
+                                       nseps = nrepeats = 0;
+                                       lead = expt;
+                                       while (*grouping != CHAR_MAX) {
+                                               if (lead <= *grouping)
+                                                       break;
+                                               lead -= *grouping;
+                                               if (*(grouping+1)) {
+                                                       nseps++;
+                                                       grouping++;
+                                               } else
+                                                       nrepeats++;
+                                       }
+                                       size += nseps + nrepeats;
+                               } else
+                                       lead = expt;
+                       }
+                       break;
+#endif /* !NO_FLOATING_POINT */
+               case 'n':
+                       /*
+                        * Assignment-like behavior is specified if the
+                        * value overflows or is otherwise unrepresentable.
+                        * C99 says to use `signed char' for %hhn conversions.
+                        */
+                       if (flags & LLONGINT)
+                               *GETARG(long long *) = ret;
+                       else if (flags & SIZET)
+                               *GETARG(ssize_t *) = (ssize_t)ret;
+                       else if (flags & PTRDIFFT)
+                               *GETARG(ptrdiff_t *) = ret;
+                       else if (flags & INTMAXT)
+                               *GETARG(intmax_t *) = ret;
+                       else if (flags & LONGINT)
+                               *GETARG(long *) = ret;
+                       else if (flags & SHORTINT)
+                               *GETARG(short *) = ret;
+                       else if (flags & CHARINT)
+                               *GETARG(signed char *) = ret;
+                       else
+                               *GETARG(int *) = ret;
+                       continue;       /* no output */
+               case 'O':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 'o':
+                       if (flags & INTMAX_SIZE)
+                               ujval = UJARG();
+                       else
+                               ulval = UARG();
+                       base = 8;
+                       goto nosign;
+               case 'p':
+                       /*-
+                        * ``The argument shall be a pointer to void.  The
+                        * value of the pointer is converted to a sequence
+                        * of printable characters, in an implementation-
+                        * defined manner.''
+                        *      -- ANSI X3J11
+                        */
+                       ujval = (uintmax_t)(uintptr_t)GETARG(void *);
+                       base = 16;
+                       xdigs = xdigs_lower;
+                       flags = flags | INTMAXT;
+                       ox[1] = 'x';
+                       goto nosign;
+               case 'S':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 's':
+                       if ((flags & LONGINT) != MULTI) {
+                               if ((result = GETARG(CHAR_T *)) == NULL)
+                                       result = STRCONST("(null)");
+                       } else {
+                               MCHAR_T *mc;
+
+                               if (convbuf != NULL)
+                                       free(convbuf);
+                               if ((mc = GETARG(MCHAR_T *)) == NULL)
+                                       result = STRCONST("(null)");
+                               else {
+                                       convbuf = SCONV(mc, prec);
+                                       if (convbuf == NULL) {
+                                               fp->_flags |= __SERR;
+                                               goto error;
+                                       }
+                                       result = convbuf;
+                               }
+                       }
+
+                       if (prec >= 0) {
+                               /*
+                                * can't use STRLEN; can only look for the
+                                * NUL in the first `prec' characters, and
+                                * STRLEN() will go further.
+                                */
+                               CHAR_T *p = MEMCHR(result, 0, (size_t)prec);
+
+                               if (p != NULL) {
+                                       size = p - result;
+                                       if (size > prec)
+                                               size = prec;
+                               } else
+                                       size = prec;
+                       } else
+                               size = STRLEN(result);
+                       sign = '\0';
+                       break;
+               case 'U':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 'u':
+                       if (flags & INTMAX_SIZE)
+                               ujval = UJARG();
+                       else
+                               ulval = UARG();
+                       base = 10;
+                       goto nosign;
+               case 'X':
+                       xdigs = xdigs_upper;
+                       goto hex;
+               case 'x':
+                       xdigs = xdigs_lower;
+hex:
+                       if (flags & INTMAX_SIZE)
+                               ujval = UJARG();
+                       else
+                               ulval = UARG();
+                       base = 16;
+                       /* leading 0x/X only if non-zero */
+                       if (flags & ALT &&
+                           (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
+                               ox[1] = ch;
+
+                       flags &= ~GROUPING;
+                       /* unsigned conversions */
+nosign:                        sign = '\0';
+                       /*-
+                        * ``... diouXx conversions ... if a precision is
+                        * specified, the 0 flag will be ignored.''
+                        *      -- ANSI X3J11
+                        */
+number:                        if ((dprec = prec) >= 0)
+                               flags &= ~ZEROPAD;
+
+                       /*-
+                        * ``The result of converting a zero value with an
+                        * explicit precision of zero is no characters.''
+                        *      -- ANSI X3J11
+                        *
+                        * ``The C Standard is clear enough as is.  The call
+                        * printf("%#.0o", 0) should print 0.''
+                        *      -- Defect Report #151
+                        */
+                       result = cp = buf + BUF;
+                       if (flags & INTMAX_SIZE) {
+                               if (ujval != 0 || prec != 0 ||
+                                   (flags & ALT && base == 8))
+                                       result = __ujtoa(ujval, cp, base,
+                                           flags & ALT, xdigs,
+                                           flags & GROUPING, thousands_sep,
+                                           grouping);
+                       } else {
+                               if (ulval != 0 || prec != 0 ||
+                                   (flags & ALT && base == 8))
+                                       result = __ultoa(ulval, cp, base,
+                                           flags & ALT, xdigs,
+                                           flags & GROUPING, thousands_sep,
+                                           grouping);
+                       }
+                       size = buf + BUF - result;
+                       if (size > BUF) /* should never happen */
+                               abort();
+                       break;
+               default:        /* "%?" prints ?, unless ? is NUL */
+                       if (ch == '\0')
+                               goto done;
+                       /* pretend it was %c with argument ch */
+                       *buf = ch;
+                       result = buf;
+                       size = 1;
+                       sign = '\0';
+                       break;
+               }
+
+               /*
+                * All reasonable formats wind up here.  At this point, `result'
+                * points to a string which (if not flags&LADJUST) should be
+                * padded out to `width' places.  If flags&ZEROPAD, it should
+                * first be prefixed by any sign or other prefix; otherwise,
+                * it should be blank padded before the prefix is emitted.
+                * After any left-hand padding and prefixing, emit zeroes
+                * required by a decimal [diouxX] precision, then print the
+                * string proper, then emit zeroes required by any leftover
+                * floating precision; finally, if LADJUST, pad with blanks.
+                *
+                * Compute actual size, so we know how much to pad.
+                * size excludes decimal prec; realsz includes it.
+                */
+               realsz = dprec > size ? dprec : size;
+               if (sign)
+                       realsz++;
+               if (ox[1])
+                       realsz += 2;
+
+               prsize = width > realsz ? width : realsz;
+               if ((unsigned)ret + prsize > INT_MAX) {
+                       ret = END_OF_FILE;
+                       goto error;
+               }
+
+               /* right-adjusting blank padding */
+               if ((flags & (LADJUST|ZEROPAD)) == 0)
+                       PAD(width - realsz, blanks);
+
+               /* prefix */
+               if (sign)
+                       PRINT(&sign, 1);
+
+               if (ox[1]) {    /* ox[1] is either x, X, or \0 */
+                       ox[0] = '0';
+                       PRINT(ox, 2);
+               }
+
+               /* right-adjusting zero padding */
+               if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
+                       PAD(width - realsz, zeroes);
+
+               /* leading zeroes from decimal precision */
+               PAD(dprec - size, zeroes);
+
+               /* the string or number proper */
+#ifndef NO_FLOATING_POINT
+               if ((flags & FPT) == 0) {
+                       PRINT(result, size);
+               } else {        /* glue together f_p fragments */
+                       if (!expchar) { /* %[fF] or sufficiently short %[gG] */
+                               if (expt <= 0) {
+                                       PRINT(zeroes, 1);
+                                       if (prec || flags & ALT)
+                                               PRINT(decimal_point, 1);
+                                       PAD(-expt, zeroes);
+                                       /* already handled initial 0's */
+                                       prec += expt;
+                               } else {
+                                       PRINTANDPAD(result, convbuf + ndig,
+                                           lead, zeroes);
+                                       result += lead;
+                                       if (grouping) {
+                                               while (nseps>0 || nrepeats>0) {
+                                                       if (nrepeats > 0)
+                                                               nrepeats--;
+                                                       else {
+                                                               grouping--;
+                                                               nseps--;
+                                                       }
+                                                       PRINT(&thousands_sep,
+                                                           1);
+                                                       PRINTANDPAD(result,
+                                                           convbuf + ndig,
+                                                           *grouping, zeroes);
+                                                       result += *grouping;
+                                               }
+                                               if (result > convbuf + ndig)
+                                                       result = convbuf + ndig;
+                                       }
+                                       if (prec || flags & ALT) {
+                                               buf[0] = *decimal_point;
+                                               PRINT(buf, 1);
+                                       }
+                               }
+                               PRINTANDPAD(result, convbuf + ndig, prec,
+                                   zeroes);
+                       } else {        /* %[eE] or sufficiently long %[gG] */
+                               if (prec > 1 || flags & ALT) {
+                                       buf[0] = *result++;
+                                       buf[1] = *decimal_point;
+                                       PRINT(buf, 2);
+                                       PRINT(result, ndig-1);
+                                       PAD(prec - ndig, zeroes);
+                               } else  /* XeYYY */
+                                       PRINT(result, 1);
+                               PRINT(expstr, expsize);
+                       }
+               }
+#else
+               PRINT(result, size);
+#endif
+               /* left-adjusting padding (always blank) */
+               if (flags & LADJUST)
+                       PAD(width - realsz, blanks);
+
+               /* finally, adjust ret */
+               ret += prsize;
+               FLUSH();
+       }
+done:
+       FLUSH();
+error:
+       va_end(orgap);
+       if (convbuf != NULL)
+               free(convbuf);
+       if (__sferror(fp))
+               ret = END_OF_FILE;
+       if ((argtable != NULL) && (argtable != statargtable))
+               free (argtable);
+       return (ret);
+       /* NOTREACHED */
+oomem:
+       errno = ENOMEM;
+       ret = END_OF_FILE;
+       goto error;
+}
+
+/*
+ * Find all arguments when a positional parameter is encountered.  Returns a
+ * table, indexed by argument number, of pointers to each arguments.  The
+ * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
+ * It will be replaces with a malloc-ed one if it overflows.
+ */ 
+static int
+__find_arguments(const CHAR_T *fmt0, va_list ap, union arg **argtable)
+{
+       CHAR_T *fmt;            /* format string */
+       int ch;                 /* character from fmt */
+       int n, n2;              /* handy integer (short term usage) */
+       CHAR_T *cp;             /* handy char pointer (short term usage) */
+       int flags;              /* flags as above */
+       enum typeid *typetable; /* table of types */
+       enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
+       int tablesize;          /* current size of type table */
+       int tablemax;           /* largest used index in table */
+       int nextarg;            /* 1-based argument index */
+
+       /*
+        * Add an argument type to the table, expanding if necessary.
+        */
+#define ADDTYPE(type) \
+       do { \
+               if (nextarg >= tablesize) \
+                       if (__grow_type_table(nextarg, &typetable, \
+                           &tablesize) == -1) \
+                               return -1; \
+               if (nextarg > tablemax) \
+                       tablemax = nextarg; \
+               typetable[nextarg++] = type; \
+       } while (/*CONSTCOND*/0)
+
+#define        ADDSARG() \
+       do { \
+               if (flags & INTMAXT)  \
+                       ADDTYPE(T_INTMAXT); \
+               else if (flags & SIZET)  \
+                       ADDTYPE(T_SSIZET); \
+               else if (flags & PTRDIFFT) \
+                       ADDTYPE(T_PTRDIFFT); \
+               else if (flags & LLONGINT) \
+                       ADDTYPE(T_LLONG); \
+               else if (flags & LONGINT) \
+                       ADDTYPE(T_LONG); \
+               else \
+                       ADDTYPE(T_INT); \
+       } while (/*CONSTCOND*/0)
+
+#define        ADDUARG() \
+       do { \
+               if (flags & INTMAXT)  \
+                       ADDTYPE(T_UINTMAXT); \
+               else if (flags & SIZET)  \
+                       ADDTYPE(T_SIZET); \
+               else if (flags & PTRDIFFT) \
+                       ADDTYPE(T_PTRDIFFT); \
+               else if (flags & LLONGINT) \
+                       ADDTYPE(T_U_LLONG); \
+               else if (flags & LONGINT) \
+                       ADDTYPE(T_U_LONG); \
+               else \
+                       ADDTYPE(T_U_INT); \
+       } while (/*CONSTCOND*/0)
+       /*
+        * Add * arguments to the type array.
+        */
+#define ADDASTER() \
+       n2 = 0; \
+       cp = fmt; \
+       while (is_digit(*cp)) { \
+               n2 = 10 * n2 + to_digit(*cp); \
+               cp++; \
+       } \
+       if (*cp == '$') { \
+               int hold = nextarg; \
+               nextarg = n2; \
+               ADDTYPE(T_INT); \
+               nextarg = hold; \
+               fmt = ++cp; \
+       } else { \
+               ADDTYPE(T_INT); \
+       }
+       fmt = (CHAR_T *)__UNCONST(fmt0);
+       typetable = stattypetable;
+       tablesize = STATIC_ARG_TBL_SIZE;
+       tablemax = 0; 
+       nextarg = 1;
+       for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
+               typetable[n] = T_UNUSED;
+
+       /*
+        * Scan the format for conversions (`%' character).
+        */
+       for (;;) {
+               for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
+                       /* void */;
+               if (ch == '\0')
+                       goto done;
+               fmt++;          /* skip over '%' */
+
+               flags = 0;
+
+rflag:         ch = *fmt++;
+reswitch:      switch (ch) {
+               case ' ':
+               case '#':
+                       goto rflag;
+               case '*':
+                       ADDASTER ();
+                       goto rflag;
+               case '-':
+               case '+':
+               case '\'':
+                       goto rflag;
+               case '.':
+                       if ((ch = *fmt++) == '*') {
+                               ADDASTER ();
+                               goto rflag;
+                       }
+                       while (is_digit(ch)) {
+                               ch = *fmt++;
+                       }
+                       goto reswitch;
+               case '0':
+                       goto rflag;
+               case '1': case '2': case '3': case '4':
+               case '5': case '6': case '7': case '8': case '9':
+                       n = 0;
+                       do {
+                               n = 10 * n + to_digit(ch);
+                               ch = *fmt++;
+                       } while (is_digit(ch));
+                       if (ch == '$') {
+                               nextarg = n;
+                               goto rflag;
+                       }
+                       goto reswitch;
+#ifndef NO_FLOATING_POINT
+               case 'L':
+                       flags |= LONGDBL;
+                       goto rflag;
+#endif
+               case 'h':
+                       if (flags & SHORTINT) {
+                               flags &= ~SHORTINT;
+                               flags |= CHARINT;
+                       } else
+                               flags |= SHORTINT;
+                       goto rflag;
+               case 'j':
+                       flags |= INTMAXT;
+                       goto rflag;
+               case 'l':
+                       if (flags & LONGINT) {
+                               flags &= ~LONGINT;
+                               flags |= LLONGINT;
+                       } else
+                               flags |= LONGINT;
+                       goto rflag;
+               case 'q':
+                       flags |= LLONGINT;      /* not necessarily */
+                       goto rflag;
+               case 't':
+                       flags |= PTRDIFFT;
+                       goto rflag;
+               case 'z':
+                       flags |= SIZET;
+                       goto rflag;
+               case 'C':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 'c':
+                       if (flags & LONGINT)
+                               ADDTYPE(T_WINT);
+                       else
+                               ADDTYPE(T_INT);
+                       break;
+               case 'D':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 'd':
+               case 'i':
+                       ADDSARG();
+                       break;
+#ifndef NO_FLOATING_POINT
+               case 'a':
+               case 'A':
+               case 'e':
+               case 'E':
+               case 'f':
+               case 'g':
+               case 'G':
+                       if (flags & LONGDBL)
+                               ADDTYPE(T_LONG_DOUBLE);
+                       else
+                               ADDTYPE(T_DOUBLE);
+                       break;
+#endif /* !NO_FLOATING_POINT */
+               case 'n':
+                       if (flags & INTMAXT)
+                               ADDTYPE(TP_INTMAXT);
+                       else if (flags & PTRDIFFT)
+                               ADDTYPE(TP_PTRDIFFT);
+                       else if (flags & SIZET)
+                               ADDTYPE(TP_SIZET);
+                       else if (flags & LLONGINT)
+                               ADDTYPE(TP_LLONG);
+                       else if (flags & LONGINT)
+                               ADDTYPE(TP_LONG);
+                       else if (flags & SHORTINT)
+                               ADDTYPE(TP_SHORT);
+                       else if (flags & CHARINT)
+                               ADDTYPE(TP_SCHAR);
+                       else
+                               ADDTYPE(TP_INT);
+                       continue;       /* no output */
+               case 'O':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 'o':
+                       ADDUARG();
+                       break;
+               case 'p':
+                       ADDTYPE(TP_VOID);
+                       break;
+               case 'S':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 's':
+                       if (flags & LONGINT)
+                               ADDTYPE(TP_WCHAR);
+                       else
+                               ADDTYPE(TP_CHAR);
+                       break;
+               case 'U':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 'u':
+               case 'X':
+               case 'x':
+                       ADDUARG();
+                       break;
+               default:        /* "%?" prints ?, unless ? is NUL */
+                       if (ch == '\0')
+                               goto done;
+                       break;
+               }
+       }
+done:
+       /*
+        * Build the argument table.
+        */
+       if (tablemax >= STATIC_ARG_TBL_SIZE) {
+               *argtable = (union arg *)
+                   malloc (sizeof (union arg) * (tablemax + 1));
+               if (*argtable == NULL)
+                       return -1;
+       }
+
+       (*argtable) [0].intarg = 0;
+       for (n = 1; n <= tablemax; n++) {
+               switch (typetable [n]) {
+                   case T_UNUSED: /* whoops! */
+                       (*argtable) [n].intarg = va_arg (ap, int);
+                       break;
+                   case TP_SCHAR:
+                       (*argtable) [n].pschararg = va_arg (ap, signed char *);
+                       break;
+                   case TP_SHORT:
+                       (*argtable) [n].pshortarg = va_arg (ap, short *);
+                       break;
+                   case T_INT:
+                       (*argtable) [n].intarg = va_arg (ap, int);
+                       break;
+                   case T_U_INT:
+                       (*argtable) [n].uintarg = va_arg (ap, unsigned int);
+                       break;
+                   case TP_INT:
+                       (*argtable) [n].pintarg = va_arg (ap, int *);
+                       break;
+                   case T_LONG:
+                       (*argtable) [n].longarg = va_arg (ap, long);
+                       break;
+                   case T_U_LONG:
+                       (*argtable) [n].ulongarg = va_arg (ap, unsigned long);
+                       break;
+                   case TP_LONG:
+                       (*argtable) [n].plongarg = va_arg (ap, long *);
+                       break;
+                   case T_LLONG:
+                       (*argtable) [n].longlongarg = va_arg (ap, long long);
+                       break;
+                   case T_U_LLONG:
+                       (*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long);
+                       break;
+                   case TP_LLONG:
+                       (*argtable) [n].plonglongarg = va_arg (ap, long long *);
+                       break;
+                   case T_PTRDIFFT:
+                       (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
+                       break;
+                   case TP_PTRDIFFT:
+                       (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
+                       break;
+                   case T_SSIZET:
+                       (*argtable) [n].ssizearg = va_arg (ap, ssize_t);
+                       break;
+                   case T_SIZET:
+                       (*argtable) [n].sizearg = va_arg (ap, size_t);
+                       break;
+                   case TP_SIZET:
+                       (*argtable) [n].psizearg = va_arg (ap, size_t *);
+                       break;
+                   case T_INTMAXT:
+                       (*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
+                       break;
+                   case T_UINTMAXT:
+                       (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
+                       break;
+                   case TP_INTMAXT:
+                       (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
+                       break;
+                   case T_DOUBLE:
+#ifndef NO_FLOATING_POINT
+                       (*argtable) [n].doublearg = va_arg (ap, double);
+#endif
+                       break;
+                   case T_LONG_DOUBLE:
+#ifndef NO_FLOATING_POINT
+                       (*argtable) [n].longdoublearg = va_arg (ap, long double);
+#endif
+                       break;
+                   case TP_CHAR:
+                       (*argtable) [n].pchararg = va_arg (ap, char *);
+                       break;
+                   case TP_VOID:
+                       (*argtable) [n].pvoidarg = va_arg (ap, void *);
+                       break;
+                   case T_WINT:
+                       (*argtable) [n].wintarg = va_arg (ap, wint_t);
+                       break;
+                   case TP_WCHAR:
+                       (*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
+                       break;
+               }
+       }
+
+       if ((typetable != NULL) && (typetable != stattypetable))
+               free (typetable);
+       return 0;
+}
+
+/*
+ * Increase the size of the type table.
+ */
+static int
+__grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
+{
+       enum typeid *const oldtable = *typetable;
+       const int oldsize = *tablesize;
+       enum typeid *newtable;
+       int n, newsize = oldsize * 2;
+
+       if (newsize < nextarg + 1)
+               newsize = nextarg + 1;
+       if (oldsize == STATIC_ARG_TBL_SIZE) {
+               if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
+                       return -1;
+               memcpy(newtable, oldtable, oldsize * sizeof(enum typeid));
+       } else {
+               newtable = realloc(oldtable, newsize * sizeof(enum typeid));
+               if (newtable == NULL) {
+                       free(oldtable);
+                       return -1;
+               }
+       }
+       for (n = oldsize; n < newsize; n++)
+               newtable[n] = T_UNUSED;
+
+       *typetable = newtable;
+       *tablesize = newsize;
+       return 0;
+}
+
+
+#ifndef NO_FLOATING_POINT
+#ifndef WIDE_DOUBLE
+static char *
+cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch,
+    int *length)
+{
+       int mode, dsgn;
+       char *digits, *bp, *rve;
+
+       _DIAGASSERT(decpt != NULL);
+       _DIAGASSERT(length != NULL);
+       _DIAGASSERT(sign != NULL);
+
+       if (ch == 'f') {
+               mode = 3;               /* ndigits after the decimal point */
+       } else {
+               /* To obtain ndigits after the decimal point for the 'e' 
+                * and 'E' formats, round to ndigits + 1 significant 
+                * figures.
+                */
+               if (ch == 'e' || ch == 'E') {
+                       ndigits++;
+               }
+               mode = 2;               /* ndigits significant digits */
+       }
+
+       digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
+       if (digits == NULL)
+               return NULL;
+       if (dsgn) {
+               value = -value;
+               *sign = '-';
+       } else
+               *sign = '\000';
+       if ((ch != 'g' && ch != 'G') || flags & ALT) {  /* Print trailing zeros */
+               bp = digits + ndigits;
+               if (ch == 'f') {
+                       if (*digits == '0' && value)
+                               *decpt = -ndigits + 1;
+                       bp += *decpt;
+               }
+               if (value == 0) /* kludge for __dtoa irregularity */
+                       rve = bp;
+               while (rve < bp)
+                       *rve++ = '0';
+       }
+       *length = rve - digits;
+       return digits;
+}
+#endif
+
+static int
+exponent(CHAR_T *p0, int expo, int fmtch)
+{
+       CHAR_T *p, *t;
+       CHAR_T expbuf[MAXEXPDIG];
+
+       p = p0;
+       *p++ = fmtch;
+       if (expo < 0) {
+               expo = -expo;
+               *p++ = '-';
+       }
+       else
+               *p++ = '+';
+       t = expbuf + MAXEXPDIG;
+       if (expo > 9) {
+               do {
+                       *--t = to_char(expo % 10);
+               } while ((expo /= 10) > 9);
+               *--t = to_char(expo);
+               for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
+       }
+       else {
+               /*
+                * Exponents for decimal floating point conversions
+                * (%[eEgG]) must be at least two characters long,
+                * whereas exponents for hexadecimal conversions can
+                * be only one character long.
+                */
+               if (fmtch == 'e' || fmtch == 'E')
+                       *p++ = '0';
+               *p++ = to_char(expo);
+       }
+       return (p - p0);
+}
+#endif /* !NO_FLOATING_POINT */
diff --git a/lib/nbsd_libc/stdio/vfwscanf.c b/lib/nbsd_libc/stdio/vfwscanf.c
new file mode 100644 (file)
index 0000000..cda05eb
--- /dev/null
@@ -0,0 +1,896 @@
+/*     $NetBSD: vfwscanf.c,v 1.6 2009/02/21 17:20:01 christos Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ftell.c    8.2 (Berkeley) 5/4/95";
+__FBSDID("$FreeBSD: src/lib/libc/stdio/vfwscanf.c,v 1.12 2004/05/02 20:13:29 obrien Exp $");
+#else
+__RCSID("$NetBSD: vfwscanf.c,v 1.6 2009/02/21 17:20:01 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <ctype.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <stdarg.h>
+#include <string.h>
+#include <limits.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+#ifndef NO_FLOATING_POINT
+#include <locale.h>
+#endif
+
+#define        BUF             513     /* Maximum length of numeric string. */
+
+/*
+ * Flags used during conversion.
+ */
+#define        LONG            0x01    /* l: long or double */
+#define        LONGDBL         0x02    /* L: long double */
+#define        SHORT           0x04    /* h: short */
+#define        SUPPRESS        0x08    /* *: suppress assignment */
+#define        POINTER         0x10    /* p: void * (as hex) */
+#define        NOSKIP          0x20    /* [ or c: do not skip blanks */
+#define        LONGLONG        0x400   /* ll: quad_t (+ deprecated q: quad) */
+#define        INTMAXT         0x800   /* j: intmax_t */
+#define        PTRDIFFT        0x1000  /* t: ptrdiff_t */
+#define        SIZET           0x2000  /* z: size_t */
+#define        SHORTSHORT      0x4000  /* hh: char */
+#define        UNSIGNED        0x8000  /* %[oupxX] conversions */
+
+/*
+ * The following are used in integral conversions only:
+ * SIGNOK, NDIGITS, PFXOK, and NZDIGITS
+ */
+#define        SIGNOK          0x40    /* +/- is (still) legal */
+#define        NDIGITS         0x80    /* no digits detected */
+#define        PFXOK           0x100   /* 0x prefix is (still) legal */
+#define        NZDIGITS        0x200   /* no zero digits detected */
+#define        HAVESIGN        0x10000 /* sign detected */
+
+/*
+ * Conversion types.
+ */
+#define        CT_CHAR         0       /* %c conversion */
+#define        CT_CCL          1       /* %[...] conversion */
+#define        CT_STRING       2       /* %s conversion */
+#define        CT_INT          3       /* %[dioupxX] conversion */
+#define        CT_FLOAT        4       /* %[efgEFG] conversion */
+
+static int parsefloat(FILE *, wchar_t *, wchar_t *);
+
+#define        INCCL(_c)       \
+       (cclcompl ? (wmemchr(ccls, (_c), (size_t)(ccle - ccls)) == NULL) : \
+       (wmemchr(ccls, (_c), (size_t)(ccle - ccls)) != NULL))
+
+/*
+ * MT-safe version.
+ */
+int
+vfwscanf(FILE * __restrict fp, const wchar_t * __restrict fmt, va_list ap)
+{
+       int ret;
+
+       FLOCKFILE(fp);
+       _SET_ORIENTATION(fp, 1);
+       ret = __vfwscanf_unlocked(fp, fmt, ap);
+       FUNLOCKFILE(fp);
+       return (ret);
+}
+
+#define SCANF_SKIP_SPACE() \
+do { \
+       wint_t tc; \
+ \
+       while ((tc = __fgetwc_unlock(fp)) != WEOF && iswspace(tc)) \
+               continue; \
+       if (tc != WEOF) \
+               ungetwc(tc, fp); \
+} while (/*CONSTCOND*/ 0)
+
+/*
+ * Non-MT-safe version.
+ */
+int
+__vfwscanf_unlocked(FILE * __restrict fp, const wchar_t * __restrict fmt, va_list ap)
+{
+       wint_t c;               /* character from format, or conversion */
+       size_t width;           /* field width, or 0 */
+       wchar_t *p;             /* points into all kinds of strings */
+       int n;                  /* handy integer */
+       int flags;              /* flags as defined above */
+       wchar_t *p0;            /* saves original value of p when necessary */
+       int nassigned;          /* number of fields assigned */
+       int nconversions;       /* number of conversions */
+       int nread;              /* number of characters consumed from fp */
+       int base;               /* base argument to conversion function */
+       wchar_t buf[BUF];       /* buffer for numeric conversions */
+       const wchar_t *ccls;    /* character class start */
+       const wchar_t *ccle;    /* character class end */
+       int cclcompl;           /* ccl is complemented? */
+       wint_t wi;              /* handy wint_t */
+       char *mbp;              /* multibyte string pointer for %c %s %[ */
+       size_t nconv;           /* number of bytes in mb. conversion */
+       char mbbuf[MB_LEN_MAX]; /* temporary mb. character buffer */
+       static const mbstate_t initial;
+       mbstate_t mbs;
+
+       /* `basefix' is used to avoid `if' tests in the integer scanner */
+       static short basefix[17] =
+               { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
+
+       nassigned = 0;
+       nconversions = 0;
+       nread = 0;
+       ccls = ccle = NULL;
+       base = 0;
+       cclcompl = 0;
+       mbp = NULL;
+       for (;;) {
+               c = *fmt++;
+               if (c == 0)
+                       return (nassigned);
+               if (iswspace(c)) {
+                       while ((c = __fgetwc_unlock(fp)) != WEOF &&
+                           iswspace(c))
+                               ;
+                       if (c != WEOF)
+                               ungetwc(c, fp);
+                       continue;
+               }
+               if (c != '%')
+                       goto literal;
+               width = 0;
+               flags = 0;
+               /*
+                * switch on the format.  continue if done;
+                * break once format type is derived.
+                */
+again:         c = *fmt++;
+               switch (c) {
+               case '%':
+                       SCANF_SKIP_SPACE();
+literal:
+                       if ((wi = __fgetwc_unlock(fp)) == WEOF)
+                               goto input_failure;
+                       if (wi != c) {
+                               ungetwc(wi, fp);
+                               goto input_failure;
+                       }
+                       nread++;
+                       continue;
+
+               case '*':
+                       flags |= SUPPRESS;
+                       goto again;
+               case 'j':
+                       flags |= INTMAXT;
+                       goto again;
+               case 'l':
+                       if (flags & LONG) {
+                               flags &= ~LONG;
+                               flags |= LONGLONG;
+                       } else
+                               flags |= LONG;
+                       goto again;
+               case 'q':
+                       flags |= LONGLONG;      /* not quite */
+                       goto again;
+               case 't':
+                       flags |= PTRDIFFT;
+                       goto again;
+               case 'z':
+                       flags |= SIZET;
+                       goto again;
+               case 'L':
+                       flags |= LONGDBL;
+                       goto again;
+               case 'h':
+                       if (flags & SHORT) {
+                               flags &= ~SHORT;
+                               flags |= SHORTSHORT;
+                       } else
+                               flags |= SHORT;
+                       goto again;
+
+               case '0': case '1': case '2': case '3': case '4':
+               case '5': case '6': case '7': case '8': case '9':
+                       width = width * 10 + c - '0';
+                       goto again;
+
+               /*
+                * Conversions.
+                */
+               case 'd':
+                       c = CT_INT;
+                       base = 10;
+                       break;
+
+               case 'i':
+                       c = CT_INT;
+                       base = 0;
+                       break;
+
+               case 'o':
+                       c = CT_INT;
+                       flags |= UNSIGNED;
+                       base = 8;
+                       break;
+
+               case 'u':
+                       c = CT_INT;
+                       flags |= UNSIGNED;
+                       base = 10;
+                       break;
+
+               case 'X':
+               case 'x':
+                       flags |= PFXOK; /* enable 0x prefixing */
+                       c = CT_INT;
+                       flags |= UNSIGNED;
+                       base = 16;
+                       break;
+
+#ifndef NO_FLOATING_POINT
+               case 'A': case 'E': case 'F': case 'G':
+               case 'a': case 'e': case 'f': case 'g':
+                       c = CT_FLOAT;
+                       break;
+#endif
+
+               case 'S':
+                       flags |= LONG;
+                       /* FALLTHROUGH */
+               case 's':
+                       c = CT_STRING;
+                       break;
+
+               case '[':
+                       ccls = fmt;
+                       if (*fmt == '^') {
+                               cclcompl = 1;
+                               fmt++;
+                       } else
+                               cclcompl = 0;
+                       if (*fmt == ']')
+                               fmt++;
+                       while (*fmt != '\0' && *fmt != ']')
+                               fmt++;
+                       ccle = fmt;
+                       fmt++;
+                       flags |= NOSKIP;
+                       c = CT_CCL;
+                       break;
+
+               case 'C':
+                       flags |= LONG;
+                       /* FALLTHROUGH */
+               case 'c':
+                       flags |= NOSKIP;
+                       c = CT_CHAR;
+                       break;
+
+               case 'p':       /* pointer format is like hex */
+                       flags |= POINTER | PFXOK;
+                       c = CT_INT;             /* assumes sizeof(uintmax_t) */
+                       flags |= UNSIGNED;      /*      >= sizeof(uintptr_t) */
+                       base = 16;
+                       break;
+
+               case 'n':
+                       nconversions++;
+                       if (flags & SUPPRESS)   /* ??? */
+                               continue;
+                       if (flags & SHORTSHORT)
+                               *va_arg(ap, char *) = nread;
+                       else if (flags & SHORT)
+                               *va_arg(ap, short *) = nread;
+                       else if (flags & LONG)
+                               *va_arg(ap, long *) = nread;
+                       else if (flags & LONGLONG)
+                               *va_arg(ap, quad_t *) = nread;
+                       else if (flags & INTMAXT)
+                               *va_arg(ap, intmax_t *) = nread;
+                       else if (flags & SIZET)
+                               *va_arg(ap, size_t *) = nread;
+                       else if (flags & PTRDIFFT)
+                               *va_arg(ap, ptrdiff_t *) = nread;
+                       else
+                               *va_arg(ap, int *) = nread;
+                       continue;
+
+               default:
+                       goto match_failure;
+
+               /*
+                * Disgusting backwards compatibility hack.     XXX
+                */
+               case '\0':      /* compat */
+                       return (EOF);
+               }
+
+               /*
+                * Consume leading white space, except for formats
+                * that suppress this.
+                */
+               if ((flags & NOSKIP) == 0) {
+                       while ((wi = __fgetwc_unlock(fp)) != WEOF && iswspace(wi))
+                               nread++;
+                       if (wi == WEOF)
+                               goto input_failure;
+                       ungetwc(wi, fp);
+               }
+
+               /*
+                * Do the conversion.
+                */
+               switch (c) {
+
+               case CT_CHAR:
+                       /* scan arbitrary characters (sets NOSKIP) */
+                       if (width == 0)
+                               width = 1;
+                       if (flags & LONG) {
+                               if (!(flags & SUPPRESS))
+                                       p = va_arg(ap, wchar_t *);
+                               n = 0;
+                               while (width-- != 0 &&
+                                   (wi = __fgetwc_unlock(fp)) != WEOF) {
+                                       if (!(flags & SUPPRESS))
+                                               *p++ = (wchar_t)wi;
+                                       n++;
+                               }
+                               if (n == 0)
+                                       goto input_failure;
+                               nread += n;
+                               if (!(flags & SUPPRESS))
+                                       nassigned++;
+                       } else {
+                               if (!(flags & SUPPRESS))
+                                       mbp = va_arg(ap, char *);
+                               n = 0;
+                               mbs = initial;
+                               while (width != 0 &&
+                                   (wi = __fgetwc_unlock(fp)) != WEOF) {
+                                       if (width >= MB_CUR_MAX &&
+                                           !(flags & SUPPRESS)) {
+                                               nconv = wcrtomb(mbp, wi, &mbs);
+                                               if (nconv == (size_t)-1)
+                                                       goto input_failure;
+                                       } else {
+                                               nconv = wcrtomb(mbbuf, wi,
+                                                   &mbs);
+                                               if (nconv == (size_t)-1)
+                                                       goto input_failure;
+                                               if (nconv > width) {
+                                                       ungetwc(wi, fp);
+                                                       break;
+                                               }
+                                               if (!(flags & SUPPRESS))
+                                                       memcpy(mbp, mbbuf,
+                                                           nconv);
+                                       }
+                                       if (!(flags & SUPPRESS))
+                                               mbp += nconv;
+                                       width -= nconv;
+                                       n++;
+                               }
+                               if (n == 0)
+                                       goto input_failure;
+                               nread += n;
+                               if (!(flags & SUPPRESS))
+                                       nassigned++;
+                       }
+                       nconversions++;
+                       break;
+
+               case CT_CCL:
+                       /* scan a (nonempty) character class (sets NOSKIP) */
+                       if (width == 0)
+                               width = (size_t)~0;     /* `infinity' */
+                       /* take only those things in the class */
+                       if ((flags & SUPPRESS) && (flags & LONG)) {
+                               n = 0;
+                               while ((wi = __fgetwc_unlock(fp)) != WEOF &&
+                                   width-- != 0 && INCCL(wi))
+                                       n++;
+                               if (wi != WEOF)
+                                       ungetwc(wi, fp);
+                               if (n == 0)
+                                       goto match_failure;
+                       } else if (flags & LONG) {
+                               p0 = p = va_arg(ap, wchar_t *);
+                               while ((wi = __fgetwc_unlock(fp)) != WEOF &&
+                                   width-- != 0 && INCCL(wi))
+                                       *p++ = (wchar_t)wi;
+                               if (wi != WEOF)
+                                       ungetwc(wi, fp);
+                               n = p - p0;
+                               if (n == 0)
+                                       goto match_failure;
+                               *p = 0;
+                               nassigned++;
+                       } else {
+                               if (!(flags & SUPPRESS))
+                                       mbp = va_arg(ap, char *);
+                               n = 0;
+                               mbs = initial;
+                               while ((wi = __fgetwc_unlock(fp)) != WEOF &&
+                                   width != 0 && INCCL(wi)) {
+                                       if (width >= MB_CUR_MAX &&
+                                          !(flags & SUPPRESS)) {
+                                               nconv = wcrtomb(mbp, wi, &mbs);
+                                               if (nconv == (size_t)-1)
+                                                       goto input_failure;
+                                       } else {
+                                               nconv = wcrtomb(mbbuf, wi,
+                                                   &mbs);
+                                               if (nconv == (size_t)-1)
+                                                       goto input_failure;
+                                               if (nconv > width)
+                                                       break;
+                                               if (!(flags & SUPPRESS))
+                                                       memcpy(mbp, mbbuf,
+                                                           nconv);
+                                       }
+                                       if (!(flags & SUPPRESS))
+                                               mbp += nconv;
+                                       width -= nconv;
+                                       n++;
+                               }
+                               if (wi != WEOF)
+                                       ungetwc(wi, fp);
+                               if (!(flags & SUPPRESS)) {
+                                       *mbp = 0;
+                                       nassigned++;
+                               }
+                       }
+                       nread += n;
+                       nconversions++;
+                       break;
+
+               case CT_STRING:
+                       /* like CCL, but zero-length string OK, & no NOSKIP */
+                       if (width == 0)
+                               width = (size_t)~0;
+                       if ((flags & SUPPRESS) && (flags & LONG)) {
+                               while ((wi = __fgetwc_unlock(fp)) != WEOF &&
+                                   width-- != 0 &&
+                                   !iswspace(wi))
+                                       nread++;
+                               if (wi != WEOF)
+                                       ungetwc(wi, fp);
+                       } else if (flags & LONG) {
+                               p0 = p = va_arg(ap, wchar_t *);
+                               while ((wi = __fgetwc_unlock(fp)) != WEOF &&
+                                   width-- != 0 &&
+                                   !iswspace(wi)) {
+                                       *p++ = (wchar_t)wi;
+                                       nread++;
+                               }
+                               if (wi != WEOF)
+                                       ungetwc(wi, fp);
+                               *p = '\0';
+                               nassigned++;
+                       } else {
+                               if (!(flags & SUPPRESS))
+                                       mbp = va_arg(ap, char *);
+                               mbs = initial;
+                               while ((wi = __fgetwc_unlock(fp)) != WEOF &&
+                                   width != 0 &&
+                                   !iswspace(wi)) {
+                                       if (width >= MB_CUR_MAX &&
+                                           !(flags & SUPPRESS)) {
+                                               nconv = wcrtomb(mbp, wi, &mbs);
+                                               if (nconv == (size_t)-1)
+                                                       goto input_failure;
+                                       } else {
+                                               nconv = wcrtomb(mbbuf, wi,
+                                                   &mbs);
+                                               if (nconv == (size_t)-1)
+                                                       goto input_failure;
+                                               if (nconv > width)
+                                                       break;
+                                               if (!(flags & SUPPRESS))
+                                                       memcpy(mbp, mbbuf,
+                                                           nconv);
+                                       }
+                                       if (!(flags & SUPPRESS))
+                                               mbp += nconv;
+                                       width -= nconv;
+                                       nread++;
+                               }
+                               if (wi != WEOF)
+                                       ungetwc(wi, fp);
+                               if (!(flags & SUPPRESS)) {
+                                       *mbp = 0;
+                                       nassigned++;
+                               }
+                       }
+                       nconversions++;
+                       continue;
+
+               case CT_INT:
+                       /* scan an integer as if by the conversion function */
+                       if (width == 0 || width > sizeof(buf) /
+                           sizeof(*buf) - 1)
+                               width = sizeof(buf) / sizeof(*buf) - 1;
+                       flags |= SIGNOK | NDIGITS | NZDIGITS;
+                       for (p = buf; width; width--) {
+                               c = __fgetwc_unlock(fp);
+                               /*
+                                * Switch on the character; `goto ok'
+                                * if we accept it as a part of number.
+                                */
+                               switch (c) {
+
+                               /*
+                                * The digit 0 is always legal, but is
+                                * special.  For %i conversions, if no
+                                * digits (zero or nonzero) have been
+                                * scanned (only signs), we will have
+                                * base==0.  In that case, we should set
+                                * it to 8 and enable 0x prefixing.
+                                * Also, if we have not scanned zero digits
+                                * before this, do not turn off prefixing
+                                * (someone else will turn it off if we
+                                * have scanned any nonzero digits).
+                                */
+                               case '0':
+                                       if (base == 0) {
+                                               base = 8;
+                                               flags |= PFXOK;
+                                       }
+                                       if (flags & NZDIGITS)
+                                           flags &= ~(SIGNOK|NZDIGITS|NDIGITS);
+                                       else
+                                           flags &= ~(SIGNOK|PFXOK|NDIGITS);
+                                       goto ok;
+
+                               /* 1 through 7 always legal */
+                               case '1': case '2': case '3':
+                               case '4': case '5': case '6': case '7':
+                                       base = basefix[base];
+                                       flags &= ~(SIGNOK | PFXOK | NDIGITS);
+                                       goto ok;
+
+                               /* digits 8 and 9 ok iff decimal or hex */
+                               case '8': case '9':
+                                       base = basefix[base];
+                                       if (base <= 8)
+                                               break;  /* not legal here */
+                                       flags &= ~(SIGNOK | PFXOK | NDIGITS);
+                                       goto ok;
+
+                               /* letters ok iff hex */
+                               case 'A': case 'B': case 'C':
+                               case 'D': case 'E': case 'F':
+                               case 'a': case 'b': case 'c':
+                               case 'd': case 'e': case 'f':
+                                       /* no need to fix base here */
+                                       if (base <= 10)
+                                               break;  /* not legal here */
+                                       flags &= ~(SIGNOK | PFXOK | NDIGITS);
+                                       goto ok;
+
+                               /* sign ok only as first character */
+                               case '+': case '-':
+                                       if (flags & SIGNOK) {
+                                               flags &= ~SIGNOK;
+                                               flags |= HAVESIGN;
+                                               goto ok;
+                                       }
+                                       break;
+                                       
+                               /*
+                                * x ok iff flag still set & 2nd char (or
+                                * 3rd char if we have a sign).
+                                */
+                               case 'x': case 'X':
+                                       if (flags & PFXOK && p ==
+                                           buf + 1 + !!(flags & HAVESIGN)) {
+                                               base = 16;      /* if %i */
+                                               flags &= ~PFXOK;
+                                               goto ok;
+                                       }
+                                       break;
+                               }
+
+                               /*
+                                * If we got here, c is not a legal character
+                                * for a number.  Stop accumulating digits.
+                                */
+                               if (c != WEOF)
+                                       ungetwc(c, fp);
+                               break;
+               ok:
+                               /*
+                                * c is legal: store it and look at the next.
+                                */
+                               *p++ = (wchar_t)c;
+                       }
+                       /*
+                        * If we had only a sign, it is no good; push
+                        * back the sign.  If the number ends in `x',
+                        * it was [sign] '0' 'x', so push back the x
+                        * and treat it as [sign] '0'.
+                        */
+                       if (flags & NDIGITS) {
+                               if (p > buf)
+                                       ungetwc(*--p, fp);
+                               goto match_failure;
+                       }
+                       c = p[-1];
+                       if (c == 'x' || c == 'X') {
+                               --p;
+                               ungetwc(c, fp);
+                       }
+                       if ((flags & SUPPRESS) == 0) {
+                               uintmax_t res;
+
+                               *p = 0;
+                               if ((flags & UNSIGNED) == 0)
+                                   res = wcstoimax(buf, NULL, base);
+                               else
+                                   res = wcstoumax(buf, NULL, base);
+                               if (flags & POINTER)
+                                       *va_arg(ap, void **) =
+                                                       (void *)(uintptr_t)res;
+                               else if (flags & SHORTSHORT)
+                                       *va_arg(ap, char *) = (char)res;
+                               else if (flags & SHORT)
+                                       *va_arg(ap, short *) = (short)res;
+                               else if (flags & LONG)
+                                       *va_arg(ap, long *) = (long)res;
+                               else if (flags & LONGLONG)
+                                       *va_arg(ap, quad_t *) = res;
+                               else if (flags & INTMAXT)
+                                       *va_arg(ap, intmax_t *) = res;
+                               else if (flags & PTRDIFFT)
+                                       *va_arg(ap, ptrdiff_t *) = (ptrdiff_t)res;
+                               else if (flags & SIZET)
+                                       *va_arg(ap, size_t *) = (size_t)res;
+                               else
+                                       *va_arg(ap, int *) = (int)res;
+                               nassigned++;
+                       }
+                       nread += p - buf;
+                       nconversions++;
+                       break;
+
+#ifndef NO_FLOATING_POINT
+               case CT_FLOAT:
+                       /* scan a floating point number as if by strtod */
+                       if (width == 0 || width > sizeof(buf) /
+                           sizeof(*buf) - 1)
+                               width = sizeof(buf) / sizeof(*buf) - 1;
+                       if ((width = parsefloat(fp, buf, buf + width)) == 0)
+                               goto match_failure;
+                       if ((flags & SUPPRESS) == 0) {
+                               if (flags & LONGDBL) {
+                                       long double res = wcstold(buf, &p);
+                                       *va_arg(ap, long double *) = res;
+                               } else
+                               if (flags & LONG) {
+                                       double res = wcstod(buf, &p);
+                                       *va_arg(ap, double *) = res;
+                               } else {
+                                       float res = wcstof(buf, &p);
+                                       *va_arg(ap, float *) = res;
+                               }
+#ifdef DEBUG
+                               if (p - buf != (ptrdiff_t)width)
+                                       abort();
+#endif
+                               nassigned++;
+                       }
+                       nread += width;
+                       nconversions++;
+                       break;
+#endif /* !NO_FLOATING_POINT */
+               }
+       }
+input_failure:
+       return (nconversions != 0 ? nassigned : EOF);
+match_failure:
+       return (nassigned);
+}
+
+#ifndef NO_FLOATING_POINT
+static int
+parsefloat(FILE *fp, wchar_t *buf, wchar_t *end)
+{
+       wchar_t *commit, *p;
+       int infnanpos = 0;
+       enum {
+               S_START, S_GOTSIGN, S_INF, S_NAN, S_MAYBEHEX,
+               S_DIGITS, S_FRAC, S_EXP, S_EXPDIGITS
+       } state = S_START;
+       wchar_t c;
+       wchar_t decpt = (wchar_t)(unsigned char)*localeconv()->decimal_point;
+       int gotmantdig = 0, ishex = 0;
+
+       /*
+        * We set commit = p whenever the string we have read so far
+        * constitutes a valid representation of a floating point
+        * number by itself.  At some point, the parse will complete
+        * or fail, and we will ungetc() back to the last commit point.
+        * To ensure that the file offset gets updated properly, it is
+        * always necessary to read at least one character that doesn't
+        * match; thus, we can't short-circuit "infinity" or "nan(...)".
+        */
+       commit = buf - 1;
+       c = WEOF;
+       for (p = buf; p < end; ) {
+               if ((c = __fgetwc_unlock(fp)) == WEOF)
+                       break;
+reswitch:
+               switch (state) {
+               case S_START:
+                       state = S_GOTSIGN;
+                       if (c == '-' || c == '+')
+                               break;
+                       else
+                               goto reswitch;
+               case S_GOTSIGN:
+                       switch (c) {
+                       case '0':
+                               state = S_MAYBEHEX;
+                               commit = p;
+                               break;
+                       case 'I':
+                       case 'i':
+                               state = S_INF;
+                               break;
+                       case 'N':
+                       case 'n':
+                               state = S_NAN;
+                               break;
+                       default:
+                               state = S_DIGITS;
+                               goto reswitch;
+                       }
+                       break;
+               case S_INF:
+                       if (infnanpos > 6 ||
+                           (c != "nfinity"[infnanpos] &&
+                            c != "NFINITY"[infnanpos]))
+                               goto parsedone;
+                       if (infnanpos == 1 || infnanpos == 6)
+                               commit = p;     /* inf or infinity */
+                       infnanpos++;
+                       break;
+               case S_NAN:
+                       switch (infnanpos) {
+                       case -1:        /* XXX kludge to deal with nan(...) */
+                               goto parsedone;
+                       case 0:
+                               if (c != 'A' && c != 'a')
+                                       goto parsedone;
+                               break;
+                       case 1:
+                               if (c != 'N' && c != 'n')
+                                       goto parsedone;
+                               else
+                                       commit = p;
+                               break;
+                       case 2:
+                               if (c != '(')
+                                       goto parsedone;
+                               break;
+                       default:
+                               if (c == ')') {
+                                       commit = p;
+                                       infnanpos = -2;
+                               } else if (!iswalnum(c) && c != '_')
+                                       goto parsedone;
+                               break;
+                       }
+                       infnanpos++;
+                       break;
+               case S_MAYBEHEX:
+                       state = S_DIGITS;
+                       if (c == 'X' || c == 'x') {
+                               ishex = 1;
+                               break;
+                       } else {        /* we saw a '0', but no 'x' */
+                               gotmantdig = 1;
+                               goto reswitch;
+                       }
+               case S_DIGITS:
+                       if ((ishex && iswxdigit(c)) || iswdigit(c))
+                               gotmantdig = 1;
+                       else {
+                               state = S_FRAC;
+                               if (c != decpt)
+                                       goto reswitch;
+                       }
+                       if (gotmantdig)
+                               commit = p;
+                       break;
+               case S_FRAC:
+                       if (((c == 'E' || c == 'e') && !ishex) ||
+                           ((c == 'P' || c == 'p') && ishex)) {
+                               if (!gotmantdig)
+                                       goto parsedone;
+                               else
+                                       state = S_EXP;
+                       } else if ((ishex && iswxdigit(c)) || iswdigit(c)) {
+                               commit = p;
+                               gotmantdig = 1;
+                       } else
+                               goto parsedone;
+                       break;
+               case S_EXP:
+                       state = S_EXPDIGITS;
+                       if (c == '-' || c == '+')
+                               break;
+                       else
+                               goto reswitch;
+               case S_EXPDIGITS:
+                       if (iswdigit(c))
+                               commit = p;
+                       else
+                               goto parsedone;
+                       break;
+               default:
+                       abort();
+               }
+               *p++ = c;
+               c = WEOF;
+       }
+
+parsedone:
+       if (c != WEOF)
+               ungetwc(c, fp);
+       while (commit < --p)
+               ungetwc(*p, fp);
+       *++commit = '\0';
+       return (commit - buf);
+}
+#endif
diff --git a/lib/nbsd_libc/stdio/vprintf.c b/lib/nbsd_libc/stdio/vprintf.c
new file mode 100644 (file)
index 0000000..7118840
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: vprintf.c,v 1.10 2003/08/07 16:43:34 agc Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)vprintf.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: vprintf.c,v 1.10 2003/08/07 16:43:34 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+
+int
+vprintf(fmt, ap)
+       char const *fmt;
+       _BSD_VA_LIST_ ap;
+{
+
+       _DIAGASSERT(fmt != NULL);
+
+       return (vfprintf(stdout, fmt, ap));
+}
diff --git a/lib/nbsd_libc/stdio/vscanf.c b/lib/nbsd_libc/stdio/vscanf.c
new file mode 100644 (file)
index 0000000..6959b5e
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: vscanf.c,v 1.12 2003/08/07 16:43:35 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Donn Seeley at UUNET Technologies, 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)vscanf.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: vscanf.c,v 1.12 2003/08/07 16:43:35 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+
+#include "reentrant.h"
+#include "local.h"
+
+int
+vscanf(fmt, ap)
+       const char *fmt;
+       _BSD_VA_LIST_ ap;
+{
+
+       _DIAGASSERT(fmt != NULL);
+
+       return (__svfscanf(stdin, fmt, ap));
+}
diff --git a/lib/nbsd_libc/stdio/vsnprintf.c b/lib/nbsd_libc/stdio/vsnprintf.c
new file mode 100644 (file)
index 0000000..e967847
--- /dev/null
@@ -0,0 +1,94 @@
+/*     $NetBSD: vsnprintf.c,v 1.22 2007/10/26 19:48:14 christos Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)vsnprintf.c        8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: vsnprintf.c,v 1.22 2007/10/26 19:48:14 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+#if defined(_FORTIFY_SOURCE) && !defined(__lint__)
+#undef vsnprintf
+#define vsnprintf _vsnprintf
+#endif
+
+#ifdef __weak_alias
+__weak_alias(vsnprintf,_vsnprintf)
+#endif
+
+int
+vsnprintf(str, n, fmt, ap)
+       char *str;
+       size_t n;
+       const char *fmt;
+       _BSD_VA_LIST_ ap;
+{
+       int ret;
+       FILE f;
+       struct __sfileext fext;
+       unsigned char dummy[1];
+
+       _DIAGASSERT(n == 0 || str != NULL);
+       _DIAGASSERT(fmt != NULL);
+
+       if ((int)n < 0) {
+               errno = EINVAL;
+               return (-1);
+       }
+
+       _FILEEXT_SETUP(&f, &fext);
+       f._file = -1;
+       f._flags = __SWR | __SSTR;
+       if (n == 0) {
+               f._bf._base = f._p = dummy;
+               f._bf._size = f._w = 0;
+       } else {
+               f._bf._base = f._p = (unsigned char *)str;
+               f._bf._size = f._w = n - 1;
+       }
+       ret = __vfprintf_unlocked(&f, fmt, ap);
+       *f._p = 0;
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/vsnprintf_ss.c b/lib/nbsd_libc/stdio/vsnprintf_ss.c
new file mode 100644 (file)
index 0000000..6ca5259
--- /dev/null
@@ -0,0 +1,498 @@
+/*     $NetBSD: vsnprintf_ss.c,v 1.9 2009/12/17 15:19:48 christos Exp $        */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)vsnprintf.c        8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: vsnprintf_ss.c,v 1.9 2009/12/17 15:19:48 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <inttypes.h>
+#include <assert.h>
+#include <stdio.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <string.h>
+#include "reentrant.h"
+#include "extern.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(vsnprintf_ss,_vsnprintf_ss)
+#endif
+
+/*
+ * vsnprintf_ss: scaled down version of printf(3).
+ *
+ * this version based on vfprintf() from libc which was derived from
+ * software contributed to Berkeley by Chris Torek.
+ *
+ */
+
+/*
+ * macros for converting digits to letters and vice versa
+ */
+#define        to_digit(c)     ((c) - '0')
+#define is_digit(c)    ((unsigned)to_digit(c) <= 9)
+#define        to_char(n)      (char)((n) + '0')
+
+/*
+ * flags used during conversion.
+ */
+#define        ALT             0x001           /* alternate form */
+#define        HEXPREFIX       0x002           /* add 0x or 0X prefix */
+#define        LADJUST         0x004           /* left adjustment */
+#define        LONGDBL         0x008           /* long double; unimplemented */
+#define        LONGINT         0x010           /* long integer */
+#define        QUADINT         0x020           /* quad integer */
+#define        SHORTINT        0x040           /* short integer */
+#define        MAXINT          0x080           /* intmax_t */
+#define        PTRINT          0x100           /* intptr_t */
+#define        SIZEINT         0x200           /* size_t */
+#define        ZEROPAD         0x400           /* zero (as opposed to blank) pad */
+#define FPT            0x800           /* Floating point number */
+
+       /*
+        * To extend shorts properly, we need both signed and unsigned
+        * argument extraction methods.
+        */
+#define        SARG() \
+       (flags&MAXINT ? va_arg(ap, intmax_t) : \
+           flags&PTRINT ? va_arg(ap, intptr_t) : \
+           flags&SIZEINT ? va_arg(ap, ssize_t) : /* XXX */ \
+           flags&QUADINT ? va_arg(ap, quad_t) : \
+           flags&LONGINT ? va_arg(ap, long) : \
+           flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
+           (long)va_arg(ap, int))
+#define        UARG() \
+       (flags&MAXINT ? va_arg(ap, uintmax_t) : \
+           flags&PTRINT ? va_arg(ap, uintptr_t) : \
+           flags&SIZEINT ? va_arg(ap, size_t) : \
+           flags&QUADINT ? va_arg(ap, u_quad_t) : \
+           flags&LONGINT ? va_arg(ap, u_long) : \
+           flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
+           (u_long)va_arg(ap, u_int))
+
+#define PUTCHAR(C) do {                                        \
+       if (sbuf < tailp)                               \
+               *sbuf++ = (C);                          \
+} while (/*CONSTCOND*/0)
+
+int
+vsnprintf_ss(char *sbuf, size_t slen, const char *fmt0, _BSD_VA_LIST_ ap)
+{
+       const char *fmt;        /* format string */
+       int ch;                 /* character from fmt */
+       int n;                  /* handy integer (short term usage) */
+       char *cp;               /* handy char pointer (short term usage) */
+       int flags;              /* flags as above */
+       int ret;                /* return value accumulator */
+       int width;              /* width from format (%8d), or 0 */
+       int prec;               /* precision from format (%.3d), or -1 */
+       char sign;              /* sign prefix (' ', '+', '-', or \0) */
+
+       u_quad_t _uquad;        /* integer arguments %[diouxX] */
+       enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
+       int dprec;              /* a copy of prec if [diouxX], 0 otherwise */
+       int realsz;             /* field size expanded by dprec */
+       int size;               /* size of converted field or string */
+       const char *xdigs;      /* digits for [xX] conversion */
+       char bf[128];           /* space for %c, %[diouxX] */
+       char *tailp;            /* tail pointer for snprintf */
+
+       static const char xdigs_lower[16] = "0123456789abcdef";
+       static const char xdigs_upper[16] = "0123456789ABCDEF";
+
+       _DIAGASSERT(slen == 0 || sbuf != NULL);
+       _DIAGASSERT(fmt0 != NULL);
+
+       if ((int)slen < 0) {
+               errno = EINVAL;
+               return (-1);
+       }
+
+       tailp = sbuf + slen;
+
+       cp = NULL;      /* XXX: shutup gcc */
+       size = 0;       /* XXX: shutup gcc */
+
+       fmt = fmt0;
+       ret = 0;
+
+       xdigs = NULL;           /* XXX: shut up gcc warning */
+
+       /*
+        * Scan the format for conversions (`%' character).
+        */
+       for (;;) {
+               while (*fmt != '%' && *fmt) {
+                       ret++;
+                       PUTCHAR(*fmt);
+                       fmt++;
+               }
+               if (*fmt == 0)
+                       goto done;
+
+               fmt++;          /* skip over '%' */
+
+               flags = 0;
+               dprec = 0;
+               width = 0;
+               prec = -1;
+               sign = '\0';
+
+rflag:         ch = *fmt++;
+reswitch:      switch (ch) {
+               case ' ':
+                       /*
+                        * ``If the space and + flags both appear, the space
+                        * flag will be ignored.''
+                        *      -- ANSI X3J11
+                        */
+                       if (!sign)
+                               sign = ' ';
+                       goto rflag;
+               case '#':
+                       flags |= ALT;
+                       goto rflag;
+               case '*':
+                       /*
+                        * ``A negative field width argument is taken as a
+                        * - flag followed by a positive field width.''
+                        *      -- ANSI X3J11
+                        * They don't exclude field widths read from args.
+                        */
+                       if ((width = va_arg(ap, int)) >= 0)
+                               goto rflag;
+                       width = -width;
+                       /* FALLTHROUGH */
+               case '-':
+                       flags |= LADJUST;
+                       goto rflag;
+               case '+':
+                       sign = '+';
+                       goto rflag;
+               case '.':
+                       if ((ch = *fmt++) == '*') {
+                               n = va_arg(ap, int);
+                               prec = n < 0 ? -1 : n;
+                               goto rflag;
+                       }
+                       n = 0;
+                       while (is_digit(ch)) {
+                               n = 10 * n + to_digit(ch);
+                               ch = *fmt++;
+                       }
+                       prec = n < 0 ? -1 : n;
+                       goto reswitch;
+               case '0':
+                       /*
+                        * ``Note that 0 is taken as a flag, not as the
+                        * beginning of a field width.''
+                        *      -- ANSI X3J11
+                        */
+                       flags |= ZEROPAD;
+                       goto rflag;
+               case '1': case '2': case '3': case '4':
+               case '5': case '6': case '7': case '8': case '9':
+                       n = 0;
+                       do {
+                               n = 10 * n + to_digit(ch);
+                               ch = *fmt++;
+                       } while (is_digit(ch));
+                       width = n;
+                       goto reswitch;
+               case 'h':
+                       flags |= SHORTINT;
+                       goto rflag;
+               case 'j':
+                       flags |= MAXINT;
+                       goto rflag;
+               case 'l':
+                       if (*fmt == 'l') {
+                               fmt++;
+                               flags |= QUADINT;
+                       } else {
+                               flags |= LONGINT;
+                       }
+                       goto rflag;
+               case 'q':
+                       flags |= QUADINT;
+                       goto rflag;
+               case 't':
+                       flags |= PTRINT;
+                       goto rflag;
+               case 'z':
+                       flags |= SIZEINT;
+                       goto rflag;
+               case 'c':
+                       *(cp = bf) = va_arg(ap, int);
+                       size = 1;
+                       sign = '\0';
+                       break;
+               case 'D':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 'd':
+               case 'i':
+                       _uquad = SARG();
+                       if ((quad_t)_uquad < 0) {
+                               _uquad = -_uquad;
+                               sign = '-';
+                       }
+                       base = DEC;
+                       goto number;
+               case 'n':
+                       if (flags & MAXINT)
+                               *va_arg(ap, intmax_t *) = ret;
+                       else if (flags & PTRINT)
+                               *va_arg(ap, intptr_t *) = ret;
+                       else if (flags & SIZEINT)
+                               *va_arg(ap, ssize_t *) = ret;
+                       else if (flags & QUADINT)
+                               *va_arg(ap, quad_t *) = ret;
+                       else if (flags & LONGINT)
+                               *va_arg(ap, long *) = ret;
+                       else if (flags & SHORTINT)
+                               *va_arg(ap, short *) = ret;
+                       else
+                               *va_arg(ap, int *) = ret;
+                       continue;       /* no output */
+               case 'O':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 'o':
+                       _uquad = UARG();
+                       base = OCT;
+                       goto nosign;
+               case 'p':
+                       /*
+                        * ``The argument shall be a pointer to void.  The
+                        * value of the pointer is converted to a sequence
+                        * of printable characters, in an implementation-
+                        * defined manner.''
+                        *      -- ANSI X3J11
+                        */
+                       /* NOSTRICT */
+                       _uquad = (u_long)va_arg(ap, void *);
+                       base = HEX;
+                       xdigs = xdigs_lower;
+                       flags |= HEXPREFIX;
+                       ch = 'x';
+                       goto nosign;
+               case 's':
+                       if ((cp = va_arg(ap, char *)) == NULL)
+                               /*XXXUNCONST*/
+                               cp = __UNCONST("(null)");
+                       if (prec >= 0) {
+                               /*
+                                * can't use strlen; can only look for the
+                                * NUL in the first `prec' characters, and
+                                * strlen() will go further.
+                                */
+                               char *p = memchr(cp, 0, (size_t)prec);
+
+                               if (p != NULL) {
+                                       size = p - cp;
+                                       if (size > prec)
+                                               size = prec;
+                               } else
+                                       size = prec;
+                       } else
+                               size = strlen(cp);
+                       sign = '\0';
+                       break;
+               case 'U':
+                       flags |= LONGINT;
+                       /*FALLTHROUGH*/
+               case 'u':
+                       _uquad = UARG();
+                       base = DEC;
+                       goto nosign;
+               case 'X':
+                       xdigs = xdigs_upper;
+                       goto hex;
+               case 'x':
+                       xdigs = xdigs_lower;
+hex:                   _uquad = UARG();
+                       base = HEX;
+                       /* leading 0x/X only if non-zero */
+                       if (flags & ALT && _uquad != 0)
+                               flags |= HEXPREFIX;
+
+                       /* unsigned conversions */
+nosign:                        sign = '\0';
+                       /*
+                        * ``... diouXx conversions ... if a precision is
+                        * specified, the 0 flag will be ignored.''
+                        *      -- ANSI X3J11
+                        */
+number:                        if ((dprec = prec) >= 0)
+                               flags &= ~ZEROPAD;
+
+                       /*
+                        * ``The result of converting a zero value with an
+                        * explicit precision of zero is no characters.''
+                        *      -- ANSI X3J11
+                        */
+                       cp = bf + sizeof(bf);
+                       if (_uquad != 0 || prec != 0) {
+                               /*
+                                * Unsigned mod is hard, and unsigned mod
+                                * by a constant is easier than that by
+                                * a variable; hence this switch.
+                                */
+                               switch (base) {
+                               case OCT:
+                                       do {
+                                               *--cp = to_char(_uquad & 7);
+                                               _uquad >>= 3;
+                                       } while (_uquad);
+                                       /* handle octal leading 0 */
+                                       if (flags & ALT && *cp != '0')
+                                               *--cp = '0';
+                                       break;
+
+                               case DEC:
+                                       /* many numbers are 1 digit */
+                                       while (_uquad >= 10) {
+                                               *--cp = to_char(_uquad % 10);
+                                               _uquad /= 10;
+                                       }
+                                       *--cp = to_char(_uquad);
+                                       break;
+
+                               case HEX:
+                                       do {
+                                               *--cp = xdigs[(size_t)_uquad & 15];
+                                               _uquad >>= 4;
+                                       } while (_uquad);
+                                       break;
+
+                               default:
+                                       /*XXXUNCONST*/
+                                       cp = __UNCONST("bug bad base");
+                                       size = strlen(cp);
+                                       goto skipsize;
+                               }
+                       }
+                       size = bf + sizeof(bf) - cp;
+               skipsize:
+                       break;
+               default:        /* "%?" prints ?, unless ? is NUL */
+                       if (ch == '\0')
+                               goto done;
+                       /* pretend it was %c with argument ch */
+                       cp = bf;
+                       *cp = ch;
+                       size = 1;
+                       sign = '\0';
+                       break;
+               }
+
+               /*
+                * All reasonable formats wind up here.  At this point, `cp'
+                * points to a string which (if not flags&LADJUST) should be
+                * padded out to `width' places.  If flags&ZEROPAD, it should
+                * first be prefixed by any sign or other prefix; otherwise,
+                * it should be blank padded before the prefix is emitted.
+                * After any left-hand padding and prefixing, emit zeroes
+                * required by a decimal [diouxX] precision, then print the
+                * string proper, then emit zeroes required by any leftover
+                * floating precision; finally, if LADJUST, pad with blanks.
+                *
+                * Compute actual size, so we know how much to pad.
+                * size excludes decimal prec; realsz includes it.
+                */
+               realsz = dprec > size ? dprec : size;
+               if (sign)
+                       realsz++;
+               else if (flags & HEXPREFIX)
+                       realsz+= 2;
+
+               /* adjust ret */
+               ret += width > realsz ? width : realsz;
+
+               /* right-adjusting blank padding */
+               if ((flags & (LADJUST|ZEROPAD)) == 0) {
+                       n = width - realsz;
+                       while (n-- > 0)
+                               PUTCHAR(' ');
+               }
+
+               /* prefix */
+               if (sign) {
+                       PUTCHAR(sign);
+               } else if (flags & HEXPREFIX) {
+                       PUTCHAR('0');
+                       PUTCHAR(ch);
+               }
+
+               /* right-adjusting zero padding */
+               if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) {
+                       n = width - realsz;
+                       while (n-- > 0)
+                               PUTCHAR('0');
+               }
+
+               /* leading zeroes from decimal precision */
+               n = dprec - size;
+               while (n-- > 0)
+                       PUTCHAR('0');
+
+               /* the string or number proper */
+               while (size--)
+                       PUTCHAR(*cp++);
+               /* left-adjusting padding (always blank) */
+               if (flags & LADJUST) {
+                       n = width - realsz;
+                       while (n-- > 0)
+                               PUTCHAR(' ');
+               }
+       }
+
+done:
+       if (sbuf == tailp)
+               sbuf[-1] = '\0';
+       else
+               *sbuf = '\0';
+       return (ret);
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/stdio/vsprintf.c b/lib/nbsd_libc/stdio/vsprintf.c
new file mode 100644 (file)
index 0000000..ad0fb5b
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: vsprintf.c,v 1.15 2007/06/03 17:39:27 christos Exp $   */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)vsprintf.c 8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: vsprintf.c,v 1.15 2007/06/03 17:39:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef _FORTIFY_SOURCE
+#undef vsprintf
+#endif
+
+int
+vsprintf(str, fmt, ap)
+       char *str;
+       const char *fmt;
+       _BSD_VA_LIST_ ap;
+{
+       int ret;
+       FILE f;
+       struct __sfileext fext;
+
+       _DIAGASSERT(str != NULL);
+       _DIAGASSERT(fmt != NULL);
+
+       _FILEEXT_SETUP(&f, &fext);
+       f._file = -1;
+       f._flags = __SWR | __SSTR;
+       f._bf._base = f._p = (unsigned char *)str;
+       f._bf._size = f._w = INT_MAX;
+       ret = __vfprintf_unlocked(&f, fmt, ap);
+       *f._p = 0;
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/vsscanf.c b/lib/nbsd_libc/stdio/vsscanf.c
new file mode 100644 (file)
index 0000000..1069fc7
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: vsscanf.c,v 1.15 2010/01/11 20:39:29 joerg Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Donn Seeley at UUNET Technologies, 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)vsscanf.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: vsscanf.c,v 1.15 2010/01/11 20:39:29 joerg Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include "reentrant.h"
+#include "local.h"
+
+static int eofread __P((void *, char *, int));
+
+/* ARGSUSED */
+static int
+eofread(cookie, buf, len)
+       void *cookie;
+       char *buf;
+       int len;
+{
+       return (0);
+}
+
+int
+vsscanf(str, fmt, ap)
+       const char *str;
+       const char *fmt;
+       _BSD_VA_LIST_ ap;
+{
+       FILE f;
+       struct __sfileext fext;
+
+       _DIAGASSERT(str != NULL);
+       _DIAGASSERT(fmt != NULL);
+
+       _FILEEXT_SETUP(&f, &fext);
+       f._flags = __SRD;
+       f._bf._base = f._p = __UNCONST(str);
+       f._bf._size = f._r = strlen(str);
+       f._read = eofread;
+       _UB(&f)._base = NULL;
+       return (__svfscanf_unlocked(&f, fmt, ap));
+}
diff --git a/lib/nbsd_libc/stdio/vswprintf.c b/lib/nbsd_libc/stdio/vswprintf.c
new file mode 100644 (file)
index 0000000..caa89ad
--- /dev/null
@@ -0,0 +1,100 @@
+/*     $NetBSD: vswprintf.c,v 1.1 2005/05/14 23:51:02 christos Exp $   */
+
+/*
+ * Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
+ * 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.
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/stdio/vswprintf.c,v 1.6 2005/02/21 19:41:44 fjoe Exp $");
+#else
+__RCSID("$NetBSD: vswprintf.c,v 1.1 2005/05/14 23:51:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include <stdarg.h>
+#include "reentrant.h"
+#include "local.h"
+
+int
+vswprintf(wchar_t * __restrict s, size_t n, const wchar_t * __restrict fmt,
+    va_list ap)
+{
+       static const mbstate_t initial;
+       mbstate_t mbs;
+       FILE f;
+       char *mbp;
+       int ret, sverrno;
+       size_t nwc;
+       struct __sfileext fext;
+
+       if (n == 0) {
+               errno = EINVAL;
+               return (-1);
+       }
+
+       _FILEEXT_SETUP(&f, &fext);
+       f._file = -1;
+       f._flags = __SWR | __SSTR | __SALC;
+       f._bf._base = f._p = (unsigned char *)malloc(128);
+       if (f._bf._base == NULL) {
+               errno = ENOMEM;
+               return (-1);
+       }
+       f._bf._size = f._w = 127;               /* Leave room for the NUL */
+       ret = __vfwprintf_unlocked(&f, fmt, ap);
+       if (ret < 0) {
+               sverrno = errno;
+               free(f._bf._base);
+               errno = sverrno;
+               return (-1);
+       }
+       *f._p = '\0';
+       mbp = (char *)f._bf._base;
+       /*
+        * XXX Undo the conversion from wide characters to multibyte that
+        * fputwc() did in __vfwprintf().
+        */
+       mbs = initial;
+       nwc = mbsrtowcs(s, (const char **)&mbp, n, &mbs);
+       free(f._bf._base);
+       if (nwc == (size_t)-1) {
+               errno = EILSEQ;
+               return (-1);
+       }
+       if (nwc == n) {
+               s[n - 1] = L'\0';
+               errno = EOVERFLOW;
+               return (-1);
+       }
+
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/vswscanf.c b/lib/nbsd_libc/stdio/vswscanf.c
new file mode 100644 (file)
index 0000000..c01aa23
--- /dev/null
@@ -0,0 +1,104 @@
+/*     $NetBSD: vswscanf.c,v 1.6 2010/01/11 20:39:29 joerg Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Donn Seeley at UUNET Technologies, 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)vsscanf.c  8.1 (Berkeley) 6/4/93";
+__FBSDID("$FreeBSD: src/lib/libc/stdio/vswscanf.c,v 1.3 2004/04/07 09:55:05 tjr Exp $");
+#else
+__RCSID("$NetBSD: vswscanf.c,v 1.6 2010/01/11 20:39:29 joerg Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <limits.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <wchar.h>
+#include "reentrant.h"
+#include "local.h"
+
+static int     eofread(void *, char *, int);
+
+static int
+/*ARGSUSED*/
+eofread(void *cookie, char *buf, int len)
+{
+
+       return (0);
+}
+
+int
+vswscanf(const wchar_t * __restrict str, const wchar_t * __restrict fmt,
+    va_list ap)
+{
+       static const mbstate_t initial;
+       mbstate_t mbs;
+       FILE f;
+       char *mbstr;
+       size_t mlen;
+       int r;
+       const wchar_t *rstr = str;
+       struct __sfileext fext;
+
+       /*
+        * XXX Convert the wide character string to multibyte, which
+        * __vfwscanf() will convert back to wide characters.
+        */
+       if ((mbstr = malloc(wcslen(str) * MB_CUR_MAX + 1)) == NULL)
+               return (EOF);
+       mbs = initial;
+       if ((mlen = wcsrtombs(mbstr, &rstr, SIZE_T_MAX, &mbs)) == (size_t)-1) {
+               free(mbstr);
+               return (EOF);
+       }
+       _FILEEXT_SETUP(&f, &fext);
+       (void)memset(WCIO_GET(&f), 0, sizeof(struct wchar_io_data));
+       f._file = -1;
+       f._flags = __SRD;
+       f._bf._base = f._p = (unsigned char *)mbstr;
+       f._bf._size = f._r = mlen;
+       f._read = eofread;
+       _UB(&f)._base = NULL;
+       r = __vfwscanf_unlocked(&f, fmt, ap);
+       free(mbstr);
+
+       return (r);
+}
diff --git a/lib/nbsd_libc/stdio/vwprintf.c b/lib/nbsd_libc/stdio/vwprintf.c
new file mode 100644 (file)
index 0000000..aa7db0e
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: vwprintf.c,v 1.1 2005/05/14 23:51:02 christos Exp $    */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/stdio/vwprintf.c,v 1.1 2002/09/21 13:00:30 tjr Exp $");
+#else
+__RCSID("$NetBSD: vwprintf.c,v 1.1 2005/05/14 23:51:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <wchar.h>
+
+int
+vwprintf(const wchar_t * __restrict fmt, va_list ap)
+{
+
+       return (vfwprintf(stdout, fmt, ap));
+}
diff --git a/lib/nbsd_libc/stdio/vwscanf.c b/lib/nbsd_libc/stdio/vwscanf.c
new file mode 100644 (file)
index 0000000..e908cbf
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: vwscanf.c,v 1.1 2005/05/14 23:51:02 christos Exp $     */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/stdio/vwscanf.c,v 1.1 2002/09/23 12:40:06 tjr Exp $");
+#else
+__RCSID("$NetBSD: vwscanf.c,v 1.1 2005/05/14 23:51:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <wchar.h>
+
+int
+vwscanf(const wchar_t * __restrict fmt, va_list ap)
+{
+
+       return (vfwscanf(stdin, fmt, ap));
+}
diff --git a/lib/nbsd_libc/stdio/wbuf.c b/lib/nbsd_libc/stdio/wbuf.c
new file mode 100644 (file)
index 0000000..35f9aee
--- /dev/null
@@ -0,0 +1,101 @@
+/*     $NetBSD: wbuf.c,v 1.13 2003/08/07 16:43:35 agc Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)wbuf.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: wbuf.c,v 1.13 2003/08/07 16:43:35 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * Write the given character into the (probably full) buffer for
+ * the given file.  Flush the buffer out if it is or becomes full,
+ * or if c=='\n' and the file is line buffered.
+ */
+int
+__swbuf(c, fp)
+       int c;
+       FILE *fp;
+{
+       int n;
+
+       _DIAGASSERT(fp != NULL);
+
+       _SET_ORIENTATION(fp, -1);
+
+       /*
+        * In case we cannot write, or longjmp takes us out early,
+        * make sure _w is 0 (if fully- or un-buffered) or -_bf._size
+        * (if line buffered) so that we will get called again.
+        * If we did not do this, a sufficient number of putc()
+        * calls might wrap _w from negative to positive.
+        */
+       fp->_w = fp->_lbfsize;
+       if (cantwrite(fp)) {
+               errno = EBADF;
+               return (EOF);
+       }
+       c = (unsigned char)c;
+
+       /*
+        * If it is completely full, flush it out.  Then, in any case,
+        * stuff c into the buffer.  If this causes the buffer to fill
+        * completely, or if c is '\n' and the file is line buffered,
+        * flush it (perhaps a second time).  The second flush will always
+        * happen on unbuffered streams, where _bf._size==1; fflush()
+        * guarantees that putc() will always call wbuf() by setting _w
+        * to 0, so we need not do anything else.
+        */
+       n = fp->_p - fp->_bf._base;
+       if (n >= fp->_bf._size) {
+               if (fflush(fp))
+                       return (EOF);
+               n = 0;
+       }
+       fp->_w--;
+       *fp->_p++ = c;
+       if (++n == fp->_bf._size || (fp->_flags & __SLBF && c == '\n'))
+               if (fflush(fp))
+                       return (EOF);
+       return (c);
+}
diff --git a/lib/nbsd_libc/stdio/wcio.h b/lib/nbsd_libc/stdio/wcio.h
new file mode 100644 (file)
index 0000000..7fb7711
--- /dev/null
@@ -0,0 +1,70 @@
+/* $NetBSD: wcio.h,v 1.3 2003/01/18 11:30:00 thorpej Exp $ */
+
+/*-
+ * Copyright (c)2001 Citrus Project,
+ * 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.
+ *
+ * $Citrus$
+ */
+
+#ifndef _WCIO_H_
+#define _WCIO_H_
+
+#include <wchar.h> /* for mbstate_t and wchar_t */
+
+/* minimal requirement of SUSv2 */
+#define WCIO_UNGETWC_BUFSIZE 1
+
+struct wchar_io_data {
+       mbstate_t wcio_mbstate_in;
+       mbstate_t wcio_mbstate_out;
+
+       wchar_t wcio_ungetwc_buf[WCIO_UNGETWC_BUFSIZE];
+       size_t wcio_ungetwc_inbuf;
+
+       int wcio_mode; /* orientation */
+};
+
+#define _SET_ORIENTATION(fp, mode) \
+do {\
+       struct wchar_io_data *_wcio = WCIO_GET(fp);\
+       if (_wcio && _wcio->wcio_mode == 0)\
+               _wcio->wcio_mode = (mode);\
+} while (/*CONSTCOND*/0)
+
+/*
+ * WCIO_FREE should be called by fclose
+ */
+#define WCIO_GET(fp) (&(_EXT(fp)->_wcio))
+#define WCIO_FREE(fp) \
+do {\
+       _EXT(fp)->_wcio.wcio_mode = 0;\
+       WCIO_FREEUB(fp);\
+} while (/*CONSTCOND*/0)
+#define WCIO_FREEUB(fp) \
+do {\
+       _EXT(fp)->_wcio.wcio_ungetwc_inbuf = 0;\
+} while (/*CONSTCOND*/0)
+
+#endif /*_WCIO_H_*/
diff --git a/lib/nbsd_libc/stdio/wprintf.3 b/lib/nbsd_libc/stdio/wprintf.3
new file mode 100644 (file)
index 0000000..4213c38
--- /dev/null
@@ -0,0 +1,618 @@
+.\" $NetBSD: wprintf.3,v 1.8 2010/12/16 17:42:27 wiz Exp $
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"    This product includes software developed by the University of
+.\"    California, Berkeley and its contributors.
+.\" 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.
+.\"
+.\"     @(#)printf.3   8.1 (Berkeley) 6/4/93
+.\" FreeBSD: src/lib/libc/stdio/printf.3,v 1.47 2002/09/06 11:23:55 tjr Exp
+.\" $FreeBSD: src/lib/libc/stdio/wprintf.3,v 1.5 2003/07/05 07:55:34 tjr Exp $
+.\"
+.Dd April 30, 2010
+.Dt WPRINTF 3
+.Os
+.Sh NAME
+.Nm wprintf , fwprintf , swprintf ,
+.Nm vwprintf , vfwprintf , vswprintf
+.Nd formatted wide character output conversion
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.In wchar.h
+.Ft int
+.Fn fwprintf "FILE * restrict stream" "const wchar_t * restrict format" ...
+.Ft int
+.Fn swprintf "wchar_t * restrict ws" "size_t n" "const wchar_t * restrict format" ...
+.Ft int
+.Fn wprintf "const wchar_t * restrict format" ...
+.In stdarg.h
+.Ft int
+.Fn vfwprintf "FILE * restrict stream" "const wchar_t * restrict" "va_list ap"
+.Ft int
+.Fn vswprintf "wchar_t * restrict ws" "size_t n" "const wchar_t *restrict format" "va_list ap"
+.Ft int
+.Fn vwprintf "const wchar_t * restrict format" "va_list ap"
+.Sh DESCRIPTION
+The
+.Fn wprintf
+family of functions produces output according to a
+.Fa format
+as described below.
+The
+.Fn wprintf
+and
+.Fn vwprintf
+functions
+write output to
+.Dv stdout ,
+the standard output stream;
+.Fn fwprintf
+and
+.Fn vfwprintf
+write output to the given output
+.Fa stream ;
+.Fn swprintf
+and
+.Fn vswprintf
+write to the wide-character string
+.Fa ws .
+.Pp
+These functions write the output under the control of a
+.Fa format
+string that specifies how subsequent arguments
+(or arguments accessed via the variable-length argument facilities of
+.Xr stdarg 3 )
+are converted for output.
+.Pp
+The
+.Fn swprintf
+and
+.Fn vswprintf
+functions will fail if
+.Fa n
+or more wide characters were requested to be written,
+.Pp
+The format string is composed of zero or more directives:
+ordinary
+characters (not
+.Cm % ) ,
+which are copied unchanged to the output stream;
+and conversion specifications, each of which results
+in fetching zero or more subsequent arguments.
+Each conversion specification is introduced by
+the
+.Cm %
+character.
+The arguments must correspond properly (after type promotion)
+with the conversion specifier.
+After the
+.Cm % ,
+the following appear in sequence:
+.Bl -bullet
+.It
+An optional field, consisting of a decimal digit string followed by a
+.Cm $ ,
+specifying the next argument to access.
+If this field is not provided, the argument following the last
+argument accessed will be used.
+Arguments are numbered starting at
+.Cm 1 .
+If unaccessed arguments in the format string are interspersed with ones that
+are accessed the results will be indeterminate.
+.It
+Zero or more of the following flags:
+.Bl -tag -width ".So \  Sc (space)"
+.It Sq Cm #
+The value should be converted to an
+.Dq alternate form .
+For
+.Cm c , d , i , n , p , s ,
+and
+.Cm u
+conversions, this option has no effect.
+For
+.Cm o
+conversions, the precision of the number is increased to force the first
+character of the output string to a zero (except if a zero value is printed
+with an explicit precision of zero).
+For
+.Cm x
+and
+.Cm X
+conversions, a non-zero result has the string
+.Ql 0x
+(or
+.Ql 0X
+for
+.Cm X
+conversions) prepended to it.
+For
+.Cm a , A , e , E , f , F , g ,
+and
+.Cm G
+conversions, the result will always contain a decimal point, even if no
+digits follow it (normally, a decimal point appears in the results of
+those conversions only if a digit follows).
+For
+.Cm g
+and
+.Cm G
+conversions, trailing zeros are not removed from the result as they
+would otherwise be.
+.It So Cm 0 Sc (zero)
+Zero padding.
+For all conversions except
+.Cm n ,
+the converted value is padded on the left with zeros rather than blanks.
+If a precision is given with a numeric conversion
+.Cm ( d , i , o , u , i , x ,
+and
+.Cm X ) ,
+the
+.Cm 0
+flag is ignored.
+.It Sq Cm \-
+A negative field width flag;
+the converted value is to be left adjusted on the field boundary.
+Except for
+.Cm n
+conversions, the converted value is padded on the right with blanks,
+rather than on the left with blanks or zeros.
+A
+.Cm \-
+overrides a
+.Cm 0
+if both are given.
+.It So "\ " Sc (space)
+A blank should be left before a positive number
+produced by a signed conversion
+.Cm ( a , A , d , e , E , f , F , g , G ,
+or
+.Cm i ) .
+.It Sq Cm +
+A sign must always be placed before a
+number produced by a signed conversion.
+A
+.Cm +
+overrides a space if both are used.
+.It Sq Cm '
+Decimal conversions
+.Cm ( d , u ,
+or
+.Cm i )
+or the integral portion of a floating point conversion
+.Cm ( f
+or
+.Cm F )
+should be grouped and separated by thousands using
+the non-monetary separator returned by
+.Xr localeconv 3 .
+.El
+.It
+An optional decimal digit string specifying a minimum field width.
+If the converted value has fewer characters than the field width, it will
+be padded with spaces on the left (or right, if the left-adjustment
+flag has been given) to fill out
+the field width.
+.It
+An optional precision, in the form of a period
+.Cm \&.
+followed by an
+optional digit string.
+If the digit string is omitted, the precision is taken as zero.
+This gives the minimum number of digits to appear for
+.Cm d , i , o , u , x ,
+and
+.Cm X
+conversions, the number of digits to appear after the decimal-point for
+.Cm a , A , e , E , f ,
+and
+.Cm F
+conversions, the maximum number of significant digits for
+.Cm g
+and
+.Cm G
+conversions, or the maximum number of characters to be printed from a
+string for
+.Cm s
+conversions.
+.It
+An optional length modifier, that specifies the size of the argument.
+The following length modifiers are valid for the
+.Cm d , i , n , o , u , x ,
+or
+.Cm X
+conversion:
+.Bl -column ".Cm q Em (deprecated)" ".Vt signed char" ".Vt unsigned long long" ".Vt long long *"
+.It Sy Modifier Ta Cm d , i Ta Cm o , u , x , X Ta Cm n
+.It Cm hh Ta Vt "signed char" Ta Vt "unsigned char" Ta Vt "signed char *"
+.It Cm h Ta Vt short Ta Vt "unsigned short" Ta Vt "short *"
+.It Cm l No (ell) Ta Vt long Ta Vt "unsigned long" Ta Vt "long *"
+.It Cm ll No (ell ell) Ta Vt "long long" Ta Vt "unsigned long long" Ta Vt "long long *"
+.It Cm j Ta Vt intmax_t Ta Vt uintmax_t Ta Vt "intmax_t *"
+.It Cm t Ta Vt ptrdiff_t Ta (see note) Ta Vt "ptrdiff_t *"
+.It Cm z Ta (see note) Ta Vt size_t Ta (see note)
+.It Cm q Em (deprecated) Ta Vt quad_t Ta Vt u_quad_t Ta Vt "quad_t *"
+.El
+.Pp
+Note:
+the
+.Cm t
+modifier, when applied to a
+.Cm o , u , x ,
+or
+.Cm X
+conversion, indicates that the argument is of an unsigned type
+equivalent in size to a
+.Vt ptrdiff_t .
+The
+.Cm z
+modifier, when applied to a
+.Cm d
+or
+.Cm i
+conversion, indicates that the argument is of a signed type equivalent in
+size to a
+.Vt size_t .
+Similarly, when applied to an
+.Cm n
+conversion, it indicates that the argument is a pointer to a signed type
+equivalent in size to a
+.Vt size_t .
+.Pp
+The following length modifier is valid for the
+.Cm a , A , e , E , f , F , g ,
+or
+.Cm G
+conversion:
+.Bl -column ".Sy Modifier" ".Cm a , A , e , E , f , F , g , G"
+.It Sy Modifier Ta Cm a , A , e , E , f , F , g , G
+.It Cm L Ta Vt "long double"
+.El
+.Pp
+The following length modifier is valid for the
+.Cm c
+or
+.Cm s
+conversion:
+.Bl -column ".Sy Modifier" ".Vt wint_t" ".Vt wchar_t *"
+.It Sy Modifier Ta Cm c Ta Cm s
+.It Cm l No (ell) Ta Vt wint_t Ta Vt "wchar_t *"
+.El
+.It
+A character that specifies the type of conversion to be applied.
+.El
+.Pp
+A field width or precision, or both, may be indicated by
+an asterisk
+.Ql *
+or an asterisk followed by one or more decimal digits and a
+.Ql $
+instead of a
+digit string.
+In this case, an
+.Vt int
+argument supplies the field width or precision.
+A negative field width is treated as a left adjustment flag followed by a
+positive field width; a negative precision is treated as though it were
+missing.
+If a single format directive mixes positional
+.Pq Li nn$
+and non-positional arguments, the results are undefined.
+.Pp
+The conversion specifiers and their meanings are:
+.Bl -tag -width ".Cm diouxX"
+.It Cm diouxX
+The
+.Vt int
+(or appropriate variant) argument is converted to signed decimal
+.Cm ( d
+and
+.Cm i ) ,
+unsigned octal
+.Pq Cm o ,
+unsigned decimal
+.Pq Cm u ,
+or unsigned hexadecimal
+.Cm ( x
+and
+.Cm X )
+notation.
+The letters
+.Dq Li abcdef
+are used for
+.Cm x
+conversions; the letters
+.Dq Li ABCDEF
+are used for
+.Cm X
+conversions.
+The precision, if any, gives the minimum number of digits that must
+appear; if the converted value requires fewer digits, it is padded on
+the left with zeros.
+.It Cm DOU
+The
+.Vt "long int"
+argument is converted to signed decimal, unsigned octal, or unsigned
+decimal, as if the format had been
+.Cm ld , lo ,
+or
+.Cm lu
+respectively.
+These conversion characters are deprecated, and will eventually disappear.
+.It Cm eE
+The
+.Vt double
+argument is rounded and converted in the style
+.Sm off
+.Oo \- Oc Ar d Li \&. Ar ddd Li e \*[Pm] Ar dd
+.Sm on
+where there is one digit before the
+decimal-point character
+and the number of digits after it is equal to the precision;
+if the precision is missing,
+it is taken as 6; if the precision is
+zero, no decimal-point character appears.
+An
+.Cm E
+conversion uses the letter
+.Ql E
+(rather than
+.Ql e )
+to introduce the exponent.
+The exponent always contains at least two digits; if the value is zero,
+the exponent is 00.
+.Pp
+For
+.Cm a , A , e , E , f , F , g ,
+and
+.Cm G
+conversions, positive and negative infinity are represented as
+.Li inf
+and
+.Li -inf
+respectively when using the lowercase conversion character, and
+.Li INF
+and
+.Li -INF
+respectively when using the uppercase conversion character.
+Similarly, NaN is represented as
+.Li nan
+when using the lowercase conversion, and
+.Li NAN
+when using the uppercase conversion.
+.It Cm fF
+The
+.Vt double
+argument is rounded and converted to decimal notation in the style
+.Sm off
+.Oo \- Oc Ar ddd Li \&. Ar ddd ,
+.Sm on
+where the number of digits after the decimal-point character
+is equal to the precision specification.
+If the precision is missing, it is taken as 6; if the precision is
+explicitly zero, no decimal-point character appears.
+If a decimal point appears, at least one digit appears before it.
+.It Cm gG
+The
+.Vt double
+argument is converted in style
+.Cm f
+or
+.Cm e
+(or
+.Cm F
+or
+.Cm E
+for
+.Cm G
+conversions).
+The precision specifies the number of significant digits.
+If the precision is missing, 6 digits are given; if the precision is zero,
+it is treated as 1.
+Style
+.Cm e
+is used if the exponent from its conversion is less than \-4 or greater than
+or equal to the precision.
+Trailing zeros are removed from the fractional part of the result; a
+decimal point appears only if it is followed by at least one digit.
+.It Cm aA
+The
+.Vt double
+argument is converted to hexadecimal notation in the style
+.Sm off
+.Oo \- Oc Li 0x Ar h Li \&. Ar hhhp Oo \*[Pm] Oc Ar d ,
+.Sm on
+where the number of digits after the hexadecimal-point character
+is equal to the precision specification.
+If the precision is missing, it is taken as enough to exactly
+represent the floating-point number; if the precision is
+explicitly zero, no hexadecimal-point character appears.
+This is an exact conversion of the mantissa+exponent internal
+floating point representation; the
+.Sm off
+.Oo \- Oc Li 0x Ar h Li \&. Ar hhh
+.Sm on
+portion represents exactly the mantissa; only denormalized
+mantissas have a zero value to the left of the hexadecimal
+point.
+The
+.Cm p
+is a literal character
+.Ql p ;
+the exponent is preceded by a positive or negative sign
+and is represented in decimal, using only enough characters
+to represent the exponent.
+The
+.Cm A
+conversion uses the prefix
+.Dq Li 0X
+(rather than
+.Dq Li 0x ) ,
+the letters
+.Dq Li ABCDEF
+(rather than
+.Dq Li abcdef )
+to represent the hex digits, and the letter
+.Ql P
+(rather than
+.Ql p )
+to separate the mantissa and exponent.
+.It Cm C
+Treated as
+.Cm c
+with the
+.Cm l
+(ell) modifier.
+.It Cm c
+The
+.Vt int
+argument is converted to an
+.Vt "unsigned char" ,
+then to a
+.Vt wchar_t
+as if by
+.Xr btowc 3 ,
+and the resulting character is written.
+.Pp
+If the
+.Cm l
+(ell) modifier is used, the
+.Vt wint_t
+argument is converted to a
+.Vt wchar_t
+and written.
+.It Cm S
+Treated as
+.Cm s
+with the
+.Cm l
+(ell) modifier.
+.It Cm s
+The
+.Vt "char *"
+argument is expected to be a pointer to an array of character type (pointer
+to a string) containing a multibyte sequence.
+Characters from the array are converted to wide characters and written up to
+(but not including)
+a terminating
+.Dv NUL
+character;
+if a precision is specified, no more than the number specified are
+written.
+If a precision is given, no null character
+need be present; if the precision is not specified, or is greater than
+the size of the array, the array must contain a terminating
+.Dv NUL
+character.
+.Pp
+If the
+.Cm l
+(ell) modifier is used, the
+.Vt "wchar_t *"
+argument is expected to be a pointer to an array of wide characters
+(pointer to a wide string).
+Each wide character in the string
+is written.
+Wide characters from the array are written up to (but not including)
+a terminating wide
+.Dv NUL
+character;
+if a precision is specified, no more than the number specified are
+written (including shift sequences).
+If a precision is given, no null character
+need be present; if the precision is not specified, or is greater than
+the number of characters in
+the string, the array must contain a terminating wide
+.Dv NUL
+character.
+.It Cm p
+The
+.Vt "void *"
+pointer argument is printed in hexadecimal (as if by
+.Ql %#x
+or
+.Ql %#lx ) .
+.It Cm n
+The number of characters written so far is stored into the
+integer indicated by the
+.Vt "int *"
+(or variant) pointer argument.
+No argument is converted.
+.It Cm %
+A
+.Ql %
+is written.
+No argument is converted.
+The complete conversion specification
+is
+.Ql %% .
+.El
+.Pp
+The decimal point
+character is defined in the program's locale (category
+.Dv LC_NUMERIC ) .
+.Pp
+In no case does a non-existent or small field width cause truncation of
+a numeric field; if the result of a conversion is wider than the field
+width, the
+field is expanded to contain the conversion result.
+.Sh RETURN VALUES
+These functions return the number of characters printed
+(not including the trailing
+.Ql \e0
+used to end output to strings).
+.Sh SEE ALSO
+.Xr btowc 3 ,
+.Xr fputws 3 ,
+.Xr printf 3 ,
+.Xr putwc 3 ,
+.Xr setlocale 3 ,
+.Xr wcsrtombs 3 ,
+.Xr wscanf 3
+.Sh STANDARDS
+The
+.Fn wprintf ,
+.Fn fwprintf ,
+.Fn swprintf ,
+.Fn vwprintf ,
+.Fn vfwprintf
+and
+.Fn vswprintf
+functions
+conform to
+.St -isoC-99 .
+.Sh SECURITY CONSIDERATIONS
+Subject to the caveats noted in the
+.Xr printf 3 .
diff --git a/lib/nbsd_libc/stdio/wprintf.c b/lib/nbsd_libc/stdio/wprintf.c
new file mode 100644 (file)
index 0000000..6f6cd7b
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: wprintf.c,v 1.1 2005/05/14 23:51:02 christos Exp $     */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/stdio/wprintf.c,v 1.1 2002/09/21 13:00:30 tjr Exp $");
+#else
+__RCSID("$NetBSD: wprintf.c,v 1.1 2005/05/14 23:51:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <wchar.h>
+
+int
+wprintf(const wchar_t * __restrict fmt, ...)
+{
+       int ret;
+       va_list ap;
+
+       va_start(ap, fmt);
+       ret = vfwprintf(stdout, fmt, ap);
+       va_end(ap);
+
+       return (ret);
+}
diff --git a/lib/nbsd_libc/stdio/wscanf.3 b/lib/nbsd_libc/stdio/wscanf.3
new file mode 100644 (file)
index 0000000..9b53ef8
--- /dev/null
@@ -0,0 +1,484 @@
+.\" $NetBSD: wscanf.3,v 1.3 2010/12/16 17:42:27 wiz Exp $
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"    This product includes software developed by the University of
+.\"    California, Berkeley and its contributors.
+.\" 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.
+.\"
+.\"     @(#)scanf.3    8.2 (Berkeley) 12/11/93
+.\" FreeBSD: src/lib/libc/stdio/scanf.3,v 1.24 2003/06/28 09:03:25 das Exp
+.\" $FreeBSD: src/lib/libc/stdio/wscanf.3,v 1.6 2003/07/05 07:47:55 tjr Exp $
+.\"
+.Dd July 5, 2003
+.Dt WSCANF 3
+.Os
+.Sh NAME
+.Nm wscanf ,
+.Nm fwscanf ,
+.Nm swscanf ,
+.Nm vwscanf ,
+.Nm vswscanf ,
+.Nm vfwscanf
+.Nd wide character input format conversion
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.In wchar.h
+.Ft int
+.Fn wscanf "const wchar_t * restrict format" ...
+.Ft int
+.Fn fwscanf "FILE * restrict stream" "const wchar_t * restrict format" ...
+.Ft int
+.Fn swscanf "const wchar_t * restrict str" "const wchar_t * restrict format" ...
+.In stdarg.h
+.Ft int
+.Fn vwscanf "const wchar_t * restrict format" "va_list ap"
+.Ft int
+.Fn vswscanf "const wchar_t * restrict str" "const wchar_t * restrict format" "va_list ap"
+.Ft int
+.Fn vfwscanf "FILE * restrict stream" "const wchar_t * restrict format" "va_list ap"
+.Sh DESCRIPTION
+The
+.Fn wscanf
+family of functions scans input according to a
+.Fa format
+as described below.
+This format may contain
+.Em conversion specifiers ;
+the results from such conversions, if any,
+are stored through the
+.Em pointer
+arguments.
+The
+.Fn wscanf
+function
+reads input from the standard input stream
+.Dv stdin ,
+.Fn fwscanf
+reads input from the stream pointer
+.Fa stream ,
+and
+.Fn swscanf
+reads its input from the wide-character string pointed to by
+.Fa str .
+The
+.Fn vfwscanf
+function
+is analogous to
+.Xr vfwprintf 3
+and reads input from the stream pointer
+.Fa stream
+using a variable argument list of pointers (see
+.Xr stdarg 3 ) .
+The
+.Fn vwscanf
+function scans a variable argument list from the standard input and
+the
+.Fn vswscanf
+function scans it from a wide-character string;
+these are analogous to
+the
+.Fn vwprintf
+and
+.Fn vswprintf
+functions respectively.
+Each successive
+.Em pointer
+argument must correspond properly with
+each successive conversion specifier
+(but see the
+.Cm *
+conversion below).
+All conversions are introduced by the
+.Cm %
+(percent sign) character.
+The
+.Fa format
+string
+may also contain other characters.
+White space (such as blanks, tabs, or newlines) in the
+.Fa format
+string match any amount of white space, including none, in the input.
+Everything else
+matches only itself.
+Scanning stops
+when an input character does not match such a format character.
+Scanning also stops
+when an input conversion cannot be made (see below).
+.Sh CONVERSIONS
+Following the
+.Cm %
+character introducing a conversion
+there may be a number of
+.Em flag
+characters, as follows:
+.Bl -tag -width ".Cm l No (ell)"
+.It Cm *
+Suppresses assignment.
+The conversion that follows occurs as usual, but no pointer is used;
+the result of the conversion is simply discarded.
+.It Cm hh
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Vt char
+(rather than
+.Vt int ) .
+.It Cm h
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Vt "short int"
+(rather than
+.Vt int ) .
+.It Cm l No (ell)
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Vt "long int"
+(rather than
+.Vt int ) ,
+that the conversion will be one of
+.Cm a , e , f ,
+or
+.Cm g
+and the next pointer is a pointer to
+.Vt double
+(rather than
+.Vt float ) ,
+or that the conversion will be one of
+.Cm c
+or
+.Cm s
+and the next pointer is a pointer to an array of
+.Vt wchar_t
+(rather than
+.Vt char ) .
+.It Cm ll No (ell ell)
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Vt "long long int"
+(rather than
+.Vt int ) .
+.It Cm L
+Indicates that the conversion will be one of
+.Cm a , e , f ,
+or
+.Cm g
+and the next pointer is a pointer to
+.Vt "long double" .
+.It Cm j
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Vt intmax_t
+(rather than
+.Vt int ) .
+.It Cm t
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Vt ptrdiff_t
+(rather than
+.Vt int ) .
+.It Cm z
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Vt size_t
+(rather than
+.Vt int ) .
+.It Cm q
+(deprecated.)
+Indicates that the conversion will be one of
+.Cm dioux
+or
+.Cm n
+and the next pointer is a pointer to a
+.Vt "long long int"
+(rather than
+.Vt int ) .
+.El
+.Pp
+In addition to these flags,
+there may be an optional maximum field width,
+expressed as a decimal integer,
+between the
+.Cm %
+and the conversion.
+If no width is given,
+a default of
+.Dq infinity
+is used (with one exception, below);
+otherwise at most this many characters are scanned
+in processing the conversion.
+Before conversion begins,
+most conversions skip white space;
+this white space is not counted against the field width.
+.Pp
+The following conversions are available:
+.Bl -tag -width XXXX
+.It Cm %
+Matches a literal
+.Ql % .
+That is,
+.Dq Li %%
+in the format string
+matches a single input
+.Ql %
+character.
+No conversion is done, and assignment does not occur.
+.It Cm d
+Matches an optionally signed decimal integer;
+the next pointer must be a pointer to
+.Vt int .
+.It Cm i
+Matches an optionally signed integer;
+the next pointer must be a pointer to
+.Vt int .
+The integer is read in base 16 if it begins
+with
+.Ql 0x
+or
+.Ql 0X ,
+in base 8 if it begins with
+.Ql 0 ,
+and in base 10 otherwise.
+Only characters that correspond to the base are used.
+.It Cm o
+Matches an octal integer;
+the next pointer must be a pointer to
+.Vt "unsigned int" .
+.It Cm u
+Matches an optionally signed decimal integer;
+the next pointer must be a pointer to
+.Vt "unsigned int" .
+.It Cm x , X
+Matches an optionally signed hexadecimal integer;
+the next pointer must be a pointer to
+.Vt "unsigned int" .
+.It Cm a , A , e , E , f , F , g , G
+Matches a floating-point number in the style of
+.Xr wcstod 3 .
+The next pointer must be a pointer to
+.Vt float
+(unless
+.Cm l
+or
+.Cm L
+is specified.)
+.It Cm s
+Matches a sequence of non-white-space wide characters;
+the next pointer must be a pointer to
+.Vt char ,
+and the array must be large enough to accept the multibyte representation
+of all the sequence and the
+terminating
+.Dv NUL
+character.
+The input string stops at white space
+or at the maximum field width, whichever occurs first.
+.Pp
+If an
+.Cm l
+qualifier is present, the next pointer must be a pointer to
+.Vt wchar_t ,
+into which the input will be placed.
+.It Cm S
+The same as
+.Cm ls .
+.It Cm c
+Matches a sequence of
+.Em width
+count
+wide characters (default 1);
+the next pointer must be a pointer to
+.Vt char ,
+and there must be enough room for the multibyte representation
+of all the characters
+(no terminating
+.Dv NUL
+is added).
+The usual skip of leading white space is suppressed.
+To skip white space first, use an explicit space in the format.
+.Pp
+If an
+.Cm l
+qualifier is present, the next pointer must be a pointer to
+.Vt wchar_t ,
+into which the input will be placed.
+.It Cm C
+The same as
+.Cm lc .
+.It Cm \&[
+Matches a nonempty sequence of characters from the specified set
+of accepted characters;
+the next pointer must be a pointer to
+.Vt char ,
+and there must be enough room for the multibyte representation of
+all the characters in the string,
+plus a terminating
+.Dv NUL
+character.
+The usual skip of leading white space is suppressed.
+The string is to be made up of characters in
+(or not in)
+a particular set;
+the set is defined by the characters between the open bracket
+.Cm \&[
+character
+and a close bracket
+.Cm \&]
+character.
+The set
+.Em excludes
+those characters
+if the first character after the open bracket is a circumflex
+.Cm ^ .
+To include a close bracket in the set,
+make it the first character after the open bracket
+or the circumflex;
+any other position will end the set.
+To include a hyphen in the set,
+make it the last character before the final close bracket;
+some implementations of
+.Fn wscanf
+use
+.Dq Li A-Z
+to represent the range of characters between
+.Ql A
+and
+.Ql Z .
+The string ends with the appearance of a character not in the
+(or, with a circumflex, in) set
+or when the field width runs out.
+.Pp
+If an
+.Cm l
+qualifier is present, the next pointer must be a pointer to
+.Vt wchar_t ,
+into which the input will be placed.
+.It Cm p
+Matches a pointer value (as printed by
+.Ql %p
+in
+.Xr wprintf 3 ) ;
+the next pointer must be a pointer to
+.Vt void .
+.It Cm n
+Nothing is expected;
+instead, the number of characters consumed thus far from the input
+is stored through the next pointer,
+which must be a pointer to
+.Vt int .
+This is
+.Em not
+a conversion, although it can be suppressed with the
+.Cm *
+flag.
+.El
+.Pp
+The decimal point
+character is defined in the program's locale (category
+.Dv LC_NUMERIC ) .
+.Pp
+For backwards compatibility, a
+.Dq conversion
+of
+.Ql %\e0
+causes an immediate return of
+.Dv EOF .
+.Sh RETURN VALUES
+These
+functions
+return
+the number of input items assigned, which can be fewer than provided
+for, or even zero, in the event of a matching failure.
+Zero
+indicates that, while there was input available,
+no conversions were assigned;
+typically this is due to an invalid input character,
+such as an alphabetic character for a
+.Ql %d
+conversion.
+The value
+.Dv EOF
+is returned if an input failure occurs before any conversion such as an
+end-of-file occurs.
+If an error or end-of-file occurs after conversion
+has begun,
+the number of conversions which were successfully completed is returned.
+.Sh SEE ALSO
+.Xr fgetwc 3 ,
+.Xr scanf 3 ,
+.Xr wcrtomb 3 ,
+.Xr wcstod 3 ,
+.Xr wcstol 3 ,
+.Xr wcstoul 3 ,
+.Xr wprintf 3
+.Sh STANDARDS
+The
+.Fn fwscanf ,
+.Fn wscanf ,
+.Fn swscanf ,
+.Fn vfwscanf ,
+.Fn vwscanf
+and
+.Fn vswscanf
+functions
+conform to
+.St -isoC-99 .
+.Sh BUGS
+In addition to the bugs documented in
+.Xr scanf 3 ,
+.Fn wscanf
+does not support the
+.Dq Li A-Z
+notation for specifying character ranges with the character
+class conversion
+.Pq Sq Cm %[ .
diff --git a/lib/nbsd_libc/stdio/wscanf.c b/lib/nbsd_libc/stdio/wscanf.c
new file mode 100644 (file)
index 0000000..7bf3f33
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: wscanf.c,v 1.1 2005/05/14 23:51:02 christos Exp $      */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/stdio/wscanf.c,v 1.1 2002/09/23 12:40:06 tjr Exp $");
+#else
+__RCSID("$NetBSD: wscanf.c,v 1.1 2005/05/14 23:51:02 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <wchar.h>
+
+int
+wscanf(const wchar_t * __restrict fmt, ...)
+{
+       va_list ap;
+       int r;
+
+       va_start(ap, fmt);
+       r = vfwscanf(stdin, fmt, ap);
+       va_end(ap);
+
+       return (r);
+}
diff --git a/lib/nbsd_libc/stdio/wsetup.c b/lib/nbsd_libc/stdio/wsetup.c
new file mode 100644 (file)
index 0000000..f30e423
--- /dev/null
@@ -0,0 +1,100 @@
+/*     $NetBSD: wsetup.c,v 1.11 2003/08/07 16:43:35 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)wsetup.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: wsetup.c,v 1.11 2003/08/07 16:43:35 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * Various output routines call wsetup to be sure it is safe to write,
+ * because either _flags does not include __SWR, or _buf is NULL.
+ * _wsetup returns 0 if OK to write, nonzero otherwise.
+ */
+int
+__swsetup(fp)
+       FILE *fp;
+{
+
+       _DIAGASSERT(fp != NULL);
+
+       /* make sure stdio is set up */
+       if (!__sdidinit)
+               __sinit();
+
+       /*
+        * If we are not writing, we had better be reading and writing.
+        */
+       if ((fp->_flags & __SWR) == 0) {
+               if ((fp->_flags & __SRW) == 0)
+                       return (EOF);
+               if (fp->_flags & __SRD) {
+                       /* clobber any ungetc data */
+                       if (HASUB(fp))
+                               FREEUB(fp);
+                       fp->_flags &= ~(__SRD|__SEOF);
+                       fp->_r = 0;
+                       fp->_p = fp->_bf._base;
+               }
+               fp->_flags |= __SWR;
+       }
+
+       /*
+        * Make a buffer if necessary, then set _w.
+        */
+       if (fp->_bf._base == NULL)
+               __smakebuf(fp);
+       if (fp->_flags & __SLBF) {
+               /*
+                * It is line buffered, so make _lbfsize be -_bufsize
+                * for the putc() macro.  We will change _lbfsize back
+                * to 0 whenever we turn off __SWR.
+                */
+               fp->_w = 0;
+               fp->_lbfsize = -fp->_bf._size;
+       } else
+               fp->_w = fp->_flags & __SNBF ? 0 : fp->_bf._size;
+       return (0);
+}
diff --git a/lib/nbsd_libc/stdlib/Lint_abs.c b/lib/nbsd_libc/stdlib/Lint_abs.c
new file mode 100644 (file)
index 0000000..47f4b0e
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint_abs.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <stdlib.h>
+
+/*ARGSUSED*/
+int
+abs(j)
+       int j;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/stdlib/Lint_div.c b/lib/nbsd_libc/stdlib/Lint_div.c
new file mode 100644 (file)
index 0000000..38c8bbd
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_div.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <stdlib.h>
+
+/*ARGSUSED*/
+div_t
+div(num, denom)
+       int num, denom;
+{
+       div_t rv = { 0 };
+       return (rv);
+}
diff --git a/lib/nbsd_libc/stdlib/Lint_imaxabs.c b/lib/nbsd_libc/stdlib/Lint_imaxabs.c
new file mode 100644 (file)
index 0000000..2dfc790
--- /dev/null
@@ -0,0 +1,15 @@
+/*     $NetBSD: Lint_imaxabs.c,v 1.1 2008/08/04 21:29:27 matt Exp $    */
+
+/*
+ * This file placed in the public domain.
+ * Matt Thomas, August 4, 2008.
+ */
+
+#include <inttypes.h>
+
+/* ARGSUSED */
+intmax_t
+imaxabs(intmax_t j)
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/stdlib/Lint_labs.c b/lib/nbsd_libc/stdlib/Lint_labs.c
new file mode 100644 (file)
index 0000000..c8f96cf
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint_labs.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <stdlib.h>
+
+/*ARGSUSED*/
+long
+labs(j)
+       long j;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/stdlib/Lint_ldiv.c b/lib/nbsd_libc/stdlib/Lint_ldiv.c
new file mode 100644 (file)
index 0000000..8899a15
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_ldiv.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <stdlib.h>
+
+/*ARGSUSED*/
+ldiv_t
+ldiv(num, denom)
+       long num, denom;
+{
+       ldiv_t rv = { 0 };
+       return (rv);
+}
diff --git a/lib/nbsd_libc/stdlib/Lint_llabs.c b/lib/nbsd_libc/stdlib/Lint_llabs.c
new file mode 100644 (file)
index 0000000..7297875
--- /dev/null
@@ -0,0 +1,16 @@
+/*     $NetBSD: Lint_llabs.c,v 1.2 2000/03/07 20:02:00 kleink Exp $    */
+
+/*
+ * This file placed in the public domain.
+ * Klaus Klein, March 6, 2000.
+ */
+
+#include <stdlib.h>
+
+/* ARGSUSED */ /* LONGLONG */
+long long int
+llabs(j)
+       long long int j;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/stdlib/Makefile.inc b/lib/nbsd_libc/stdlib/Makefile.inc
new file mode 100644 (file)
index 0000000..1067d2c
--- /dev/null
@@ -0,0 +1,81 @@
+#      $NetBSD: Makefile.inc,v 1.75 2010/11/14 18:11:43 tron Exp $
+#      from: @(#)Makefile.inc  8.3 (Berkeley) 2/4/95
+
+# stdlib sources
+.PATH: ${ARCHDIR}/stdlib ${.CURDIR}/stdlib
+
+SRCS+= _env.c _rand48.c \
+       a64l.c abort.c atexit.c atof.c atoi.c atol.c atoll.c \
+       bsearch.c drand48.c exit.c \
+       getenv.c getopt.c getopt_long.c getsubopt.c \
+       hcreate.c heapsort.c imaxdiv.c insque.c jrand48.c l64a.c lldiv.c \
+       lcong48.c lrand48.c lsearch.c merge.c mi_vector_hash.c mrand48.c \
+       nrand48.c putenv.c qabs.c qdiv.c qsort.c posix_openpt.c pty.c \
+       radixsort.c rand.c rand_r.c random.c remque.c \
+       seed48.c setenv.c srand48.c strsuftoll.c \
+       strtoimax.c strtol.c strtoll.c strtoq.c strtoul.c strtoull.c \
+       strtoumax.c strtouq.c system.c tdelete.c tfind.c tsearch.c twalk.c \
+       unsetenv.c strfmon.c
+
+# These are often replaced by MD .S versions
+SRCS+= abs.c labs.c llabs.c imaxabs.c
+SRCS+= div.c ldiv.c imaxdiv.c
+
+# This might be replaced by erand48.c
+SRCS+= erand48_ieee754.c
+
+.if (${USE_JEMALLOC} != "no")
+SRCS+= jemalloc.c
+.else
+SRCS+= malloc.c
+.endif
+
+CPPFLAGS.strtoimax.c+= -I${LIBCDIR}/../../common/lib/libc/stdlib
+CPPFLAGS.strtol.c+=    -I${LIBCDIR}/../../common/lib/libc/stdlib
+CPPFLAGS.strtoq.c+=    -I${LIBCDIR}/../../common/lib/libc/stdlib
+CPPFLAGS.strtouq.c+=   -I${LIBCDIR}/../../common/lib/libc/stdlib
+
+.include "${ARCHDIR}/stdlib/Makefile.inc"
+
+MAN+=  a64l.3 abort.3 abs.3 alloca.3 atexit.3 atof.3 atoi.3 atol.3 atoll.3 \
+       bsearch.3 \
+       div.3 \
+       exit.3 \
+       getenv.3 getopt.3 getopt_long.3 getsubopt.3 grantpt.3 \
+       hcreate.3 \
+       imaxabs.3 imaxdiv.3 insque.3 \
+       jemalloc.3 \
+       labs.3 ldiv.3 llabs.3 lldiv.3 lsearch.3 \
+       malloc.3 memory.3 mi_vector_hash.3 \
+       posix_memalign.3 posix_openpt.3 ptsname.3 \
+       qabs.3 qdiv.3 qsort.3 \
+       radixsort.3 rand48.3 rand.3 random.3 \
+       strfmon.3 strsuftoll.3 strtod.3 strtol.3 strtoul.3 system.3 \
+       tsearch.3 \
+       unlockpt.3
+
+MLINKS+=a64l.3 l64a.3
+MLINKS+=a64l.3 l64a_r.3
+MLINKS+=getenv.3 setenv.3 getenv.3 unsetenv.3 getenv.3 putenv.3
+MLINKS+=getenv.3 getenv_r.3
+MLINKS+=hcreate.3 hdestroy.3 hcreate.3 hsearch.3
+MLINKS+=insque.3 remque.3
+MLINKS+=lsearch.3 lfind.3
+MLINKS+=malloc.3 calloc.3 malloc.3 realloc.3 malloc.3 free.3
+MLINKS+=qsort.3 heapsort.3 qsort.3 mergesort.3
+MLINKS+=rand.3 rand_r.3
+MLINKS+=rand.3 srand.3
+MLINKS+=rand48.3 drand48.3 rand48.3 erand48.3 rand48.3 lrand48.3
+MLINKS+=rand48.3 mrand48.3 rand48.3 nrand48.3 rand48.3 jrand48.3
+MLINKS+=rand48.3 srand48.3 rand48.3 seed48.3 rand48.3 lcong48.3
+MLINKS+=random.3 initstate.3 random.3 setstate.3 random.3 srandom.3
+MLINKS+=radixsort.3 sradixsort.3
+MLINKS+=strsuftoll.3 strsuftollx.3
+MLINKS+=strtod.3 strtof.3 strtod.3 strtold.3
+MLINKS+=strtol.3 strtoimax.3
+MLINKS+=strtol.3 strtoll.3
+MLINKS+=strtol.3 strtoq.3
+MLINKS+=strtoul.3 strtoull.3
+MLINKS+=strtoul.3 strtoumax.3
+MLINKS+=strtoul.3 strtouq.3
+MLINKS+=tsearch.3 tfind.3 tsearch.3 twalk.3 tsearch.3 tdelete.3
diff --git a/lib/nbsd_libc/stdlib/_env.c b/lib/nbsd_libc/stdlib/_env.c
new file mode 100644 (file)
index 0000000..93a6ab6
--- /dev/null
@@ -0,0 +1,405 @@
+/*     $NetBSD: _env.c,v 1.5 2010/11/17 13:25:53 tron Exp $ */
+
+/*-
+ * Copyright (c) 2010 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matthias Scheler.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _env.c,v 1.5 2010/11/17 13:25:53 tron Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/rbtree.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+
+#include "env.h"
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * Red-Black tree node for tracking memory used by environment variables.
+ * The tree is sorted by the address of the nodes themselves.
+ */
+typedef struct {
+       rb_node_t       rb_node;
+       size_t          length;
+       uint8_t         marker;
+       char            data[];
+} env_node_t;
+
+/* Compare functions for above tree. */
+static signed int env_tree_compare_nodes(void *, const void *, const void *);
+static signed int env_tree_compare_key(void *, const void *, const void *);
+
+/* Operations for above tree. */
+static const rb_tree_ops_t env_tree_ops = {
+       .rbto_compare_nodes = env_tree_compare_nodes,
+       .rbto_compare_key = env_tree_compare_key,
+       .rbto_node_offset = offsetof(env_node_t, rb_node),
+       .rbto_context = NULL
+};
+
+/* The single instance of above tree. */
+static rb_tree_t       env_tree;
+
+/* The allocated environment. */
+static char    **allocated_environ;
+static size_t  allocated_environ_size;
+
+#define        ENV_ARRAY_SIZE_MIN      16
+
+/* The lock protecting access to the environment. */
+#ifdef _REENTRANT
+static rwlock_t env_lock = RWLOCK_INITIALIZER;
+#endif
+
+/* Compatibility function. */
+char *__findenv(const char *name, int *offsetp);
+
+__warn_references(__findenv,
+    "warning: __findenv is an internal obsolete function.")
+
+/* Our initialization function. */
+void __libc_env_init(void);
+
+/*ARGSUSED*/
+static signed int
+env_tree_compare_nodes(void *ctx, const void *node_a, const void *node_b)
+{
+       uintptr_t addr_a, addr_b;
+
+       addr_a = (uintptr_t)node_a;
+       addr_b = (uintptr_t)node_b;
+
+       if (addr_a < addr_b)
+               return -1;
+
+       if (addr_a > addr_b)
+               return 1;
+
+       return 0;
+}
+
+static signed int
+env_tree_compare_key(void *ctx, const void *node, const void *key)
+{
+       return env_tree_compare_nodes(ctx, node,
+           (const uint8_t *)key - offsetof(env_node_t, data));
+}
+
+/*
+ * Determine the of the name in an environment string. Return 0 if the
+ * name is not valid.
+ */
+size_t
+__envvarnamelen(const char *str, bool withequal)
+{
+       size_t l_name;
+
+       if (str == NULL)
+               return 0;
+
+       l_name = strcspn(str, "=");
+       if (l_name == 0)
+               return 0;
+
+       if (withequal) {
+               if (str[l_name] != '=')
+                       return 0;
+       } else {
+               if (str[l_name] == '=')
+                       return 0;
+       }
+
+       return l_name;
+}
+
+/*
+ * Free memory occupied by environment variable if possible. This function
+ * must be called with the environment write locked.
+ */
+void
+__freeenvvar(char *envvar)
+{
+       env_node_t *node;
+
+       _DIAGASSERT(envvar != NULL);
+       node = rb_tree_find_node(&env_tree, envvar);
+       if (node != NULL) {
+               rb_tree_remove_node(&env_tree, node);
+               free(node);
+       }
+}
+
+/*
+ * Allocate memory for an environment variable. This function must be called
+ * with the environment write locked.
+ */
+char *
+__allocenvvar(size_t length)
+{
+       env_node_t *node;
+
+       node = malloc(sizeof(*node) + length);
+       if (node != NULL) {
+               node->length = length;
+               node->marker = 0;
+               rb_tree_insert_node(&env_tree, node);
+               return node->data;
+       } else {
+               return NULL;
+       }
+}
+
+/*
+ * Check whether an environment variable is writable. This function must be
+ * called with the environment write locked as the caller will probably
+ * overwrite the environment variable afterwards.
+ */
+bool
+__canoverwriteenvvar(char *envvar, size_t length)
+{
+       env_node_t *node;
+
+       _DIAGASSERT(envvar != NULL);
+
+       node = rb_tree_find_node(&env_tree, envvar);
+       return (node != NULL && length <= node->length);
+}
+
+/* Free all allocated environment variables that are no longer used. */
+static void
+__scrubenv(void)
+{
+       static uint8_t marker = 0;
+       size_t num_entries;
+       env_node_t *node, *next;
+
+       while (++marker == 0);
+
+       /* Mark all nodes which are currently used. */
+       for (num_entries = 0; environ[num_entries] != NULL; num_entries++) {
+               node = rb_tree_find_node(&env_tree, environ[num_entries]);
+               if (node != NULL)
+                       node->marker = marker;
+       }
+
+       /* Free all nodes which are currently not used. */
+       for (node = RB_TREE_MIN(&env_tree); node != NULL; node = next) {
+               next = rb_tree_iterate(&env_tree, node, RB_DIR_RIGHT);
+
+               if (node->marker != marker) {
+                       rb_tree_remove_node(&env_tree, node);
+                       free(node);
+               }
+       }
+
+       /* Deal with the environment array itself. */
+       if (environ == allocated_environ) {
+               /* Clear out spurious entries in the environment. */
+               (void)memset(&environ[num_entries + 1], 0,
+                   (allocated_environ_size - num_entries - 1) *
+                   sizeof(*environ));
+       } else {
+               /*
+                * The environment array was not allocated by "libc".
+                * Free our array if we allocated one.
+                */
+               free(allocated_environ);
+               allocated_environ = NULL;
+               allocated_environ_size = 0;
+       }
+}
+
+/*
+ * Get a (new) slot in the environment. This function must be called with
+ * the environment write locked.
+ */
+ssize_t
+__getenvslot(const char *name, size_t l_name, bool allocate)
+{
+       size_t new_size, num_entries, required_size;
+       char **new_environ;
+
+       /* Does the environ need scrubbing? */
+       if (environ != allocated_environ && allocated_environ != NULL)
+               __scrubenv();
+
+       /* Search for an existing environment variable of the given name. */
+       num_entries = 0;
+       while (environ[num_entries] != NULL) {
+               if (strncmp(environ[num_entries], name, l_name) == 0 &&
+                   environ[num_entries][l_name] == '=') {
+                       /* We found a match. */
+                       return num_entries;
+               }
+               num_entries ++;
+       }
+
+       /* No match found, return if we don't want to allocate a new slot. */
+       if (!allocate)
+               return -1;
+
+       /* Create a new slot in the environment. */
+       required_size = num_entries + 1;
+       if (environ == allocated_environ &&
+           required_size < allocated_environ_size) {
+               /* Does the environment need scrubbing? */
+               if (required_size < allocated_environ_size &&
+                   allocated_environ[required_size] != NULL) {
+                       __scrubenv();
+               }
+
+               /* Return a free slot. */
+               return num_entries;
+       }
+
+       /* Determine size of a new environment array. */
+       new_size = ENV_ARRAY_SIZE_MIN;
+       while (new_size <= required_size)
+               new_size <<= 1;
+
+       /* Allocate a new environment array. */
+       if (environ == allocated_environ) {
+               new_environ = realloc(environ,
+                   new_size * sizeof(*new_environ));
+               if (new_environ == NULL)
+                       return -1;
+       } else {
+               free(allocated_environ);
+               allocated_environ = NULL;
+               allocated_environ_size = 0;
+
+               new_environ = malloc(new_size * sizeof(*new_environ));
+               if (new_environ == NULL)
+                       return -1;
+               (void)memcpy(new_environ, environ,
+                   num_entries * sizeof(*new_environ));
+       }
+
+       /* Clear remaining entries. */
+       (void)memset(&new_environ[num_entries], 0,
+           (new_size - num_entries) * sizeof(*new_environ));
+
+       /* Use the new environment array. */
+       environ = allocated_environ = new_environ;
+       allocated_environ_size = new_size;
+
+       /* Return a free slot. */
+       return num_entries;
+}
+
+/* Find a string in the environment. */
+char *
+__findenvvar(const char *name, size_t l_name)
+{
+       ssize_t offset;
+
+       offset = __getenvslot(name, l_name, false);
+       return (offset != -1) ? environ[offset] + l_name + 1 : NULL;
+}
+
+/* Compatibility interface, do *not* call this function. */
+char *
+__findenv(const char *name, int *offsetp)
+{
+       size_t l_name;
+       ssize_t offset;
+
+       l_name = __envvarnamelen(name, false);
+       if (l_name == 0)
+               return NULL;
+
+       offset = __getenvslot(name, l_name, false);
+       if (offset < 0 || offset > INT_MAX)
+               return NULL;
+
+       *offsetp = (int)offset;
+       return environ[offset] + l_name + 1;
+}
+
+#ifdef _REENTRANT
+
+/* Lock the environment for read. */
+bool
+__readlockenv(void)
+{
+       int error;
+
+       error = rwlock_rdlock(&env_lock);
+       if (error == 0)
+               return true;
+
+       errno = error;
+       return false;
+}
+
+/* Lock the environment for write. */
+bool
+__writelockenv(void)
+{
+       int error;
+
+       error = rwlock_wrlock(&env_lock);
+       if (error == 0)
+               return true;
+
+       errno = error;
+       return false;
+}
+
+/* Unlock the environment for write. */
+bool
+__unlockenv(void)
+{
+       int error;
+
+       error = rwlock_unlock(&env_lock);
+       if (error == 0)
+               return true;
+
+       errno = error;
+       return false;
+}
+
+#endif
+
+/* Initialize environment memory RB tree. */
+void
+__libc_env_init(void)
+{
+       rb_tree_init(&env_tree, &env_tree_ops);
+}
diff --git a/lib/nbsd_libc/stdlib/_rand48.c b/lib/nbsd_libc/stdlib/_rand48.c
new file mode 100644 (file)
index 0000000..0468026
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: _rand48.c,v 1.7 2005/06/12 05:21:27 lukem Exp $        */
+
+/*
+ * Copyright (c) 1993 Martin Birgmeier
+ * All rights reserved.
+ *
+ * You may redistribute unmodified or modified versions of this source
+ * code provided that the above copyright notice and this and the
+ * following conditions are retained.
+ *
+ * This software is provided ``as is'', and comes with no warranties
+ * of any kind. I shall in no event be liable for anything that happens
+ * to anyone/anything when using this software.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _rand48.c,v 1.7 2005/06/12 05:21:27 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+
+#include "rand48.h"
+
+unsigned short __rand48_seed[3] = {
+       RAND48_SEED_0,
+       RAND48_SEED_1,
+       RAND48_SEED_2
+};
+unsigned short __rand48_mult[3] = {
+       RAND48_MULT_0,
+       RAND48_MULT_1,
+       RAND48_MULT_2
+};
+unsigned short __rand48_add = RAND48_ADD;
+
+void
+__dorand48(unsigned short xseed[3])
+{
+       unsigned long accu;
+       unsigned short temp[2];
+
+       _DIAGASSERT(xseed != NULL);
+
+       accu = (unsigned long) __rand48_mult[0] * (unsigned long) xseed[0] +
+        (unsigned long) __rand48_add;
+       temp[0] = (unsigned short) accu;        /* lower 16 bits */
+       accu >>= sizeof(unsigned short) * 8;
+       accu += (unsigned long) __rand48_mult[0] * (unsigned long) xseed[1] +
+        (unsigned long) __rand48_mult[1] * (unsigned long) xseed[0];
+       temp[1] = (unsigned short) accu;        /* middle 16 bits */
+       accu >>= sizeof(unsigned short) * 8;
+       accu += __rand48_mult[0] * xseed[2] + __rand48_mult[1] * xseed[1] + __rand48_mult[2] * xseed[0];
+       xseed[0] = temp[0];
+       xseed[1] = temp[1];
+       xseed[2] = (unsigned short) accu;
+}
diff --git a/lib/nbsd_libc/stdlib/a64l.3 b/lib/nbsd_libc/stdlib/a64l.3
new file mode 100644 (file)
index 0000000..7f00802
--- /dev/null
@@ -0,0 +1,133 @@
+.\" $NetBSD: a64l.3,v 1.10 2010/05/06 18:55:34 jruoho Exp $
+.\"
+.\" Copyright (c) 1998, 1999 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 6, 2010
+.Dt A64L 3
+.Os
+.Sh NAME
+.Nm a64l ,
+.Nm l64a ,
+.Nm l64a_r
+.Nd "convert between a long integer and a base-64 ASCII string"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft long
+.Fn a64l "const char *s"
+.Ft char *
+.Fn l64a "long int l"
+.Ft int
+.Fn l64a_r "long int l" "char *buffer" "int buflen"
+.Sh DESCRIPTION
+The
+.Fn a64l
+and
+.Fn l64a
+functions convert between a long integer and its base-64 ASCII string
+representation.
+.Pp
+The characters used to represent ``digits'' are
+`.' for 0,
+`/' for 1,
+`0' - `9' for 2 - 11,
+`A' - `Z' for 12 - 37, and
+`a' - `z' for 38 - 63.
+.Pp
+.Fn a64l
+takes a pointer to a NUL-terminated base-64 ASCII string
+representation,
+.Fa s ,
+and returns the corresponding long integer value.
+.Pp
+.Fn l64a
+takes a long integer value,
+.Fa l ,
+and returns a pointer to the corresponding NUL-terminated base-64
+ASCII string representation.
+.Pp
+.Fn l64a_r
+performs a conversion identical to that of
+.Fn l64a
+and stores the resulting representation in the memory area pointed to by
+.Fa buffer ,
+consuming at most
+.Fa buflen
+characters including the terminating NUL character.
+.Sh RETURN VALUES
+On successful completion,
+.Fn a64l
+returns the long integer value corresponding to the input string.
+If the string pointed to by
+.Fa s
+is an empty string,
+.Fn a64l
+returns a value of 0L.
+.Pp
+.Fn l64a
+returns a pointer to the base-64 ASCII string representation corresponding to
+the input value.
+If
+.Fa l
+is 0L,
+.Fn l64a
+returns a pointer to an empty string.
+.Pp
+On successful completion,
+.Fn l64a_r
+returns 0; if
+.Fa buffer
+is of insufficient length, -1 is returned.
+.Sh SEE ALSO
+.Xr strtol 3
+.Sh STANDARDS
+The
+.Fn a64l
+and
+.Fn l64a
+functions conform to
+.St -xpg4.2
+and
+.St -p1003.1-2004 .
+The
+.Fn l64a_r
+function conforms to
+.St -svid4 ,
+Multithreading Extension.
+.Sh BUGS
+The
+.Fn l64a
+function is not reentrant.
+The value returned by it points into a static buffer area;
+subsequent calls to
+.Fn la64a
+may overwrite this buffer.
+In multi-threaded applications,
+.Fn l64a_r
+should be used instead.
diff --git a/lib/nbsd_libc/stdlib/a64l.c b/lib/nbsd_libc/stdlib/a64l.c
new file mode 100644 (file)
index 0000000..2e616b9
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: a64l.c,v 1.9 2003/07/26 19:24:53 salo Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(a64l,_a64l)
+#endif
+
+long
+a64l(s)
+       const char *s;
+{
+       long value, digit, shift;
+       int i;
+
+       _DIAGASSERT(s != NULL);
+
+       value = 0;
+       shift = 0;
+       for (i = 0; *s && i < 6; i++, s++) {
+               if (*s <= '/')
+                       digit = *s - '.';
+               else if (*s <= '9')
+                       digit = *s - '0' + 2;
+               else if (*s <= 'Z')
+                       digit = *s - 'A' + 12;
+               else
+                       digit = *s - 'a' + 38; 
+
+               value |= digit << shift;
+               shift += 6;
+       }
+
+       return (long) value;
+}
diff --git a/lib/nbsd_libc/stdlib/abort.3 b/lib/nbsd_libc/stdlib/abort.3
new file mode 100644 (file)
index 0000000..1fca505
--- /dev/null
@@ -0,0 +1,73 @@
+.\"    $NetBSD: abort.3,v 1.12 2003/08/07 16:43:37 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)abort.3      8.1 (Berkeley) 6/4/93
+.\"
+.Dd August 11, 2002
+.Dt ABORT 3
+.Os
+.Sh NAME
+.Nm abort
+.Nd cause abnormal program termination
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft void
+.Fn abort void
+.Sh DESCRIPTION
+The
+.Fn abort
+function causes abnormal program termination to occur, unless the
+signal
+.Dv SIGABRT
+is being caught and the signal handler does not return.
+.Pp
+Calling the
+.Fn abort
+function results in temporary files being removed.
+Any open streams are flushed and closed.
+.Sh RETURN VALUES
+The
+.Nm abort
+function
+never returns.
+.Sh SEE ALSO
+.Xr sigaction 2 ,
+.Xr exit 3
+.Sh STANDARDS
+The
+.Fn abort
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdlib/abort.c b/lib/nbsd_libc/stdlib/abort.c
new file mode 100644 (file)
index 0000000..577bec1
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: abort.c,v 1.13 2009/01/30 23:21:03 ad Exp $    */
+
+/*
+ * Copyright (c) 1985, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)abort.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: abort.c,v 1.13 2009/01/30 23:21:03 ad Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <signal.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+extern void (*__cleanup) __P((void));
+static int aborting = 0;
+
+void
+abort()
+{
+       sigset_t mask;
+
+       sigfillset(&mask);
+       /*
+        * don't block SIGABRT to give any handler a chance; we ignore
+        * any errors -- X311J doesn't allow abort to return anyway.
+        */
+       sigdelset(&mask, SIGABRT);
+       (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
+
+       /* 
+        * POSIX.1 requires that stdio buffers be flushed on abort.
+        * We ensure the cleanup routines are only called once in
+        * case the user calls abort() in a SIGABRT handler.
+        */
+       if (!aborting) {
+               aborting = 1;
+
+               if (__cleanup)
+                       (*__cleanup)();
+       }
+
+       (void)raise(SIGABRT);
+
+       /*
+        * if SIGABRT ignored, or caught and the handler returns, do
+        * it again, only harder.
+        */
+       (void)signal(SIGABRT, SIG_DFL);
+       (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
+       (void)raise(SIGABRT);
+       _exit(1);
+}
diff --git a/lib/nbsd_libc/stdlib/abs.3 b/lib/nbsd_libc/stdlib/abs.3
new file mode 100644 (file)
index 0000000..d9a8238
--- /dev/null
@@ -0,0 +1,76 @@
+.\"    $NetBSD: abs.3,v 1.13 2008/08/04 21:29:27 matt Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)abs.3        8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt ABS 3
+.Os
+.Sh NAME
+.Nm abs
+.Nd integer absolute value function
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn abs "int j"
+.Sh DESCRIPTION
+The
+.Fn abs
+function
+computes
+the absolute value of the integer
+.Ar j .
+.Sh RETURN VALUES
+The
+.Fn abs
+function
+returns
+the absolute value.
+.Sh SEE ALSO
+.Xr cabs 3 ,
+.Xr fabs 3 ,
+.Xr floor 3 ,
+.Xr hypot 3 ,
+.Xr imaxabs 3 ,
+.Xr labs 3 ,
+.Xr llabs 3 ,
+.Xr math 3
+.Sh STANDARDS
+The
+.Fn abs
+function conforms to
+.St -ansiC .
+.Sh BUGS
+The absolute value of the most negative integer remains negative.
diff --git a/lib/nbsd_libc/stdlib/abs.c b/lib/nbsd_libc/stdlib/abs.c
new file mode 100644 (file)
index 0000000..52bd8b4
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: abs.c,v 1.7 2003/08/07 16:43:37 agc Exp $      */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)abs.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: abs.c,v 1.7 2003/08/07 16:43:37 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdlib.h>
+
+int
+abs(j)
+       int j;
+{
+       return(j < 0 ? -j : j);
+}
diff --git a/lib/nbsd_libc/stdlib/alloca.3 b/lib/nbsd_libc/stdlib/alloca.3
new file mode 100644 (file)
index 0000000..e61c927
--- /dev/null
@@ -0,0 +1,102 @@
+.\"    $NetBSD: alloca.3,v 1.13 2010/05/03 06:11:38 jruoho Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)alloca.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 3, 2010
+.Dt ALLOCA 3
+.Os
+.Sh NAME
+.Nm alloca
+.Nd memory allocator
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft void *
+.Fn alloca "size_t size"
+.Sh DESCRIPTION
+The
+.Fn alloca
+function
+allocates
+.Fa size
+bytes of space in the stack frame of the caller.
+This temporary space is automatically freed on
+return.
+.Sh RETURN VALUES
+The
+.Fn alloca
+function returns a pointer to the beginning of the allocated space.
+If the allocation failed, a
+.Dv NULL
+pointer is returned.
+.Sh SEE ALSO
+.Xr brk 2 ,
+.Xr calloc 3 ,
+.Xr getpagesize 3 ,
+.Xr malloc 3 ,
+.Xr realloc 3
+.Sh CAVEATS
+Few limitations can be mentioned:
+.Bl -bullet
+.It
+The
+.Fn alloca
+function
+is machine dependent; its use is discouraged.
+.It
+The
+.Fn alloca
+function is slightly unsafe because it cannot ensure that the pointer
+returned points to a valid and usable block of memory.
+The allocation made may exceed the bounds of the stack, or even go
+further into other objects in memory, and
+.Fn alloca
+cannot determine such an error.
+Avoid
+.Fn alloca
+with large unbounded allocations.
+.It
+Since
+.Fn alloca
+modifies the stack at runtime,
+it causes problems to certain security features.
+See
+.Xr security 8
+for a discussion.
+.El
+.\" .Sh HISTORY
+.\" The
+.\" .Fn alloca
+.\" function appeared in
+.\" .Bx ?? .
+.\" The function appeared in 32v, pwb and pwb.2 and in 3bsd 4bsd
+.\" The first man page (or link to a man page that I can find at the
+.\" moment is 4.3...
diff --git a/lib/nbsd_libc/stdlib/atexit.3 b/lib/nbsd_libc/stdlib/atexit.3
new file mode 100644 (file)
index 0000000..15805d6
--- /dev/null
@@ -0,0 +1,77 @@
+.\"    $NetBSD: atexit.3,v 1.9 2003/08/07 16:43:38 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)atexit.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt ATEXIT 3
+.Os
+.Sh NAME
+.Nm atexit
+.Nd register a function to be called on exit
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn atexit "void (*function)(void)"
+.Sh DESCRIPTION
+The
+.Fn atexit
+function
+registers the given
+.Ar function
+to be called at program exit, whether via
+.Xr exit 3
+or via return from the program's
+.Em main .
+Functions so registered are called in reverse order;
+no arguments are passed.
+At least 32 functions can always be registered,
+and more are allowed as long as sufficient memory can be allocated.
+.Sh RETURN VALUES
+.Rv -std atexit
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er ENOMEM
+No memory was available to add the function to the list.
+The existing list of functions is unmodified.
+.El
+.Sh SEE ALSO
+.Xr exit 3
+.Sh STANDARDS
+The
+.Fn atexit
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdlib/atexit.c b/lib/nbsd_libc/stdlib/atexit.c
new file mode 100644 (file)
index 0000000..695f0ce
--- /dev/null
@@ -0,0 +1,246 @@
+/*     $NetBSD: atexit.c,v 1.24 2009/10/08 16:33:45 pooka Exp $        */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: atexit.c,v 1.24 2009/10/08 16:33:45 pooka Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "reentrant.h"
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include "atexit.h"
+
+struct atexit_handler {
+       struct atexit_handler *ah_next;
+       union {
+               void (*fun_atexit)(void);
+               void (*fun_cxa_atexit)(void *);
+       } ah_fun;
+#define        ah_atexit       ah_fun.fun_atexit
+#define        ah_cxa_atexit   ah_fun.fun_cxa_atexit
+
+       void *ah_arg;   /* argument for cxa_atexit handlers */
+       void *ah_dso;   /* home DSO for cxa_atexit handlers */
+};
+
+/*
+ * There must be at least 32 to guarantee ANSI conformance, plus
+ * 3 additional ones for the benefit of the startup code, which
+ * may use them to register the dynamic loader's cleanup routine,
+ * the profiling cleanup routine, and the global destructor routine.
+ */
+#define        NSTATIC_HANDLERS        (32 + 3)
+static struct atexit_handler atexit_handler0[NSTATIC_HANDLERS];
+
+#define        STATIC_HANDLER_P(ah)                                            \
+       (ah >= &atexit_handler0[0] && ah < &atexit_handler0[NSTATIC_HANDLERS])
+
+/*
+ * Stack of atexit handlers.  Handlers must be called in the opposite
+ * order they were registered.
+ */
+static struct atexit_handler *atexit_handler_stack;
+
+#ifdef _REENTRANT
+/* ..and a mutex to protect it all. */
+static mutex_t atexit_mutex;
+#endif /* _REENTRANT */
+
+void   __libc_atexit_init(void) __attribute__ ((visibility("hidden")));
+
+/*
+ * Allocate an atexit handler descriptor.  If "dso" is NULL, it indicates
+ * a normal atexit handler, which must be allocated from the static pool,
+ * if possible. cxa_atexit handlers are never allocated from the static
+ * pool.
+ *
+ * atexit_mutex must be held.
+ */
+static struct atexit_handler *
+atexit_handler_alloc(void *dso)
+{
+       struct atexit_handler *ah;
+       int i;
+
+       if (dso == NULL) {
+               for (i = 0; i < NSTATIC_HANDLERS; i++) {
+                       ah = &atexit_handler0[i];
+                       if (ah->ah_atexit == NULL && ah->ah_next == NULL) {
+                               /* Slot is free. */
+                               return (ah);
+                       }
+               }
+       }
+
+       /*
+        * Either no static slot was free, or this is a cxa_atexit
+        * handler.  Allocate a new one.  We keep the atexit_mutex
+        * held to prevent handlers from being run while we (potentially)
+        * block in malloc().
+        */
+       ah = malloc(sizeof(*ah));
+       return (ah);
+}
+
+/*
+ * Initialize atexit_mutex with the PTHREAD_MUTEX_RECURSIVE attribute.
+ * Note that __cxa_finalize may generate calls to __cxa_atexit.
+ */
+void
+__libc_atexit_init(void)
+{
+       mutexattr_t atexit_mutex_attr;
+       mutexattr_init(&atexit_mutex_attr);
+       mutexattr_settype(&atexit_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
+       mutex_init(&atexit_mutex, &atexit_mutex_attr);
+}
+
+/*
+ * Register an atexit routine.  This is suitable either for a cxa_atexit
+ * or normal atexit type handler.  The __cxa_atexit() name and arguments
+ * are specified by the C++ ABI.  See:
+ *
+ *     http://www.codesourcery.com/cxx-abi/abi.html#dso-dtor
+ */
+int
+__cxa_atexit(void (*func)(void *), void *arg, void *dso)
+{
+       struct atexit_handler *ah;
+
+       _DIAGASSERT(func != NULL);
+
+       mutex_lock(&atexit_mutex);
+
+       ah = atexit_handler_alloc(dso);
+       if (ah == NULL) {
+               mutex_unlock(&atexit_mutex);
+               return (-1);
+       }
+
+       ah->ah_cxa_atexit = func;
+       ah->ah_arg = arg;
+       ah->ah_dso = dso;
+
+       ah->ah_next = atexit_handler_stack;
+       atexit_handler_stack = ah;
+
+       mutex_unlock(&atexit_mutex);
+       return (0);
+}
+
+/*
+ * Run the list of atexit handlers.  If dso is NULL, run all of them,
+ * otherwise run only those matching the specified dso.
+ *
+ * Note that we can be recursively invoked; rtld cleanup is via an
+ * atexit handler, and rtld cleanup invokes _fini() for DSOs, which
+ * in turn invokes __cxa_finalize() for the DSO.
+ */
+void
+__cxa_finalize(void *dso)
+{
+       static u_int call_depth;
+       struct atexit_handler *ah, *dead_handlers = NULL, **prevp;
+       void (*cxa_func)(void *);
+       void (*atexit_func)(void);
+
+       mutex_lock(&atexit_mutex);
+       call_depth++;
+
+       /*
+        * If we are at call depth 1 (which is usually the "do everything"
+        * call from exit(3)), we go ahead and remove elements from the
+        * list as we call them.  This will prevent any nested calls from
+        * having to traverse elements we've already processed.  If we are
+        * at call depth > 1, we simply mark elements we process as unused.
+        * When the depth 1 caller sees those, it will simply unlink them
+        * for us.
+        */
+again:
+       for (prevp = &atexit_handler_stack; (ah = (*prevp)) != NULL;) {
+               if (dso == NULL || dso == ah->ah_dso || ah->ah_atexit == NULL) {
+                       if (ah->ah_atexit != NULL) {
+                               void *p = atexit_handler_stack;
+                               if (ah->ah_dso != NULL) {
+                                       cxa_func = ah->ah_cxa_atexit;
+                                       ah->ah_cxa_atexit = NULL;
+                                       (*cxa_func)(ah->ah_arg);
+                               } else {
+                                       atexit_func = ah->ah_atexit;
+                                       ah->ah_atexit = NULL;
+                                       (*atexit_func)();
+                               }
+                               /* Restart if new atexit handler was added. */
+                               if (p != atexit_handler_stack)
+                                       goto again;
+                       }
+
+                       if (call_depth == 1) {
+                               *prevp = ah->ah_next;
+                               if (STATIC_HANDLER_P(ah))
+                                       ah->ah_next = NULL;
+                               else {
+                                       ah->ah_next = dead_handlers;
+                                       dead_handlers = ah;
+                               }
+                       } else
+                               prevp = &ah->ah_next;
+               } else
+                       prevp = &ah->ah_next;
+       }
+       call_depth--;
+       mutex_unlock(&atexit_mutex);
+
+       if (call_depth > 0)
+               return;
+
+       /*
+        * Now free any dead handlers.  Do this even if we're about to
+        * exit, in case a leak-detecting malloc is being used.
+        */
+       while ((ah = dead_handlers) != NULL) {
+               dead_handlers = ah->ah_next;
+               free(ah);
+       }
+}
+
+/*
+ * Register a function to be performed at exit.
+ */
+int
+atexit(void (*func)(void))
+{
+
+       return (__cxa_atexit((void (*)(void *))func, NULL, NULL));
+}
diff --git a/lib/nbsd_libc/stdlib/atexit.h b/lib/nbsd_libc/stdlib/atexit.h
new file mode 100644 (file)
index 0000000..7aae85a
--- /dev/null
@@ -0,0 +1,33 @@
+/*     $NetBSD: atexit.h,v 1.11 2008/04/28 20:23:00 martin Exp $       */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+int    __cxa_atexit(void (*)(void *), void *, void *);
+void   __cxa_finalize(void *);
diff --git a/lib/nbsd_libc/stdlib/atof.3 b/lib/nbsd_libc/stdlib/atof.3
new file mode 100644 (file)
index 0000000..1d620f7
--- /dev/null
@@ -0,0 +1,73 @@
+.\"    $NetBSD: atof.3,v 1.9 2003/08/07 16:43:38 agc Exp $
+.\"
+.\" Copyright (c) 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)atof.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt ATOF 3
+.Os
+.Sh NAME
+.Nm atof
+.Nd convert
+.Tn ASCII
+string to double
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft double
+.Fn atof "const char *nptr"
+.Sh DESCRIPTION
+The
+.Fn atof
+function converts the initial portion of the string pointed to by
+.Ar nptr
+to
+.Ar double
+representation.
+.Pp
+It is equivalent to:
+.Bd -literal -offset indent
+strtod(nptr, (char **)NULL);
+.Ed
+.Sh SEE ALSO
+.Xr atoi 3 ,
+.Xr atol 3 ,
+.Xr strtod 3 ,
+.Xr strtol 3 ,
+.Xr strtoul 3
+.Sh STANDARDS
+The
+.Fn atof
+function conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdlib/atof.c b/lib/nbsd_libc/stdlib/atof.c
new file mode 100644 (file)
index 0000000..0a89197
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: atof.c,v 1.12 2003/08/07 16:43:38 agc Exp $    */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)atof.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: atof.c,v 1.12 2003/08/07 16:43:38 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <stdlib.h>
+
+double
+atof(ascii)
+       const char *ascii;
+{
+       _DIAGASSERT(ascii != NULL);
+
+       return (strtod(ascii, NULL));
+}
diff --git a/lib/nbsd_libc/stdlib/atoi.3 b/lib/nbsd_libc/stdlib/atoi.3
new file mode 100644 (file)
index 0000000..f3aab7e
--- /dev/null
@@ -0,0 +1,85 @@
+.\"    $NetBSD: atoi.3,v 1.10 2003/08/07 16:43:38 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)atoi.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt ATOI 3
+.Os
+.Sh NAME
+.Nm atoi
+.Nd convert
+.Tn ASCII
+string to integer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn atoi "const char *nptr"
+.Sh DESCRIPTION
+The
+.Fn atoi
+function converts the initial portion of the string pointed to by
+.Em nptr
+to
+.Em integer
+representation.
+.Pp
+It is equivalent to:
+.Bd -literal -offset indent
+(int)strtol(nptr, (char **)NULL, 10);
+.Ed
+.Sh SEE ALSO
+.Xr atof 3 ,
+.Xr atol 3 ,
+.Xr strtod 3 ,
+.Xr strtol 3 ,
+.Xr strtoul 3
+.Sh STANDARDS
+The
+.Fn atoi
+function conforms to
+.St -ansiC .
+.Sh CAVEATS
+.Nm
+does no overflow checking, handles unsigned numbers poorly,
+and handles strings containing trailing extra characters
+(like
+.Dq 123abc )
+poorly.
+Careful use of
+.Xr strtol 3
+and
+.Xr strtoul 3
+can alleviate these problems.
diff --git a/lib/nbsd_libc/stdlib/atoi.c b/lib/nbsd_libc/stdlib/atoi.c
new file mode 100644 (file)
index 0000000..06c9fee
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: atoi.c,v 1.11 2003/08/07 16:43:38 agc Exp $    */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)atoi.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: atoi.c,v 1.11 2003/08/07 16:43:38 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <stdlib.h>
+
+int
+atoi(str)
+       const char *str;
+{
+       _DIAGASSERT(str != NULL);
+
+       return((int)strtol(str, (char **)NULL, 10));
+}
diff --git a/lib/nbsd_libc/stdlib/atol.3 b/lib/nbsd_libc/stdlib/atol.3
new file mode 100644 (file)
index 0000000..1206ade
--- /dev/null
@@ -0,0 +1,74 @@
+.\"    $NetBSD: atol.3,v 1.8 2003/08/07 16:43:38 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)atol.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt ATOL 3
+.Os
+.Sh NAME
+.Nm atol
+.Nd convert
+.Tn ASCII
+string to long integer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft long
+.Fn atol "const char *nptr"
+.Sh DESCRIPTION
+The
+.Fn atol
+function converts the initial portion of the string pointed to by
+.Ar nptr
+to
+.Em long integer
+representation.
+.Pp
+It is equivalent to:
+.Bd -literal -offset indent
+strtol(nptr, (char **)NULL, 10);
+.Ed
+.Sh SEE ALSO
+.Xr atof 3 ,
+.Xr atoi 3 ,
+.Xr strtod 3 ,
+.Xr strtol 3 ,
+.Xr strtoul 3
+.Sh STANDARDS
+The
+.Fn atol
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdlib/atol.c b/lib/nbsd_libc/stdlib/atol.c
new file mode 100644 (file)
index 0000000..41d3aae
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: atol.c,v 1.10 2003/08/07 16:43:38 agc Exp $    */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)atol.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: atol.c,v 1.10 2003/08/07 16:43:38 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <stdlib.h>
+
+long
+atol(str)
+       const char *str;
+{
+       _DIAGASSERT(str != NULL);
+
+       return(strtol(str, (char **)NULL, 10));
+}
diff --git a/lib/nbsd_libc/stdlib/atoll.3 b/lib/nbsd_libc/stdlib/atoll.3
new file mode 100644 (file)
index 0000000..0bdcd60
--- /dev/null
@@ -0,0 +1,77 @@
+.\"    $NetBSD: atoll.3,v 1.6 2003/09/08 17:54:33 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)atol.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd March 6, 2000
+.Dt ATOLL 3
+.Os
+.Sh NAME
+.Nm atoll
+.Nd convert
+.Tn ASCII
+string to long long integer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft long long int
+.Fn atoll "const char *nptr"
+.Sh DESCRIPTION
+The
+.Fn atoll
+function converts the initial portion of the string pointed to by
+.Ar nptr
+to
+.Em long long integer
+representation.
+.Pp
+It is equivalent to:
+.Bd -literal -offset indent
+strtoll(nptr, (char **)NULL, 10);
+.Ed
+.Sh SEE ALSO
+.Xr atof 3 ,
+.Xr atoi 3 ,
+.Xr atol 3 ,
+.Xr strtod 3 ,
+.Xr strtol 3 ,
+.Xr strtoll 3 ,
+.Xr strtoul 3 ,
+.Xr strtoull 3
+.Sh STANDARDS
+The
+.Fn atoll
+function
+conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/stdlib/atoll.c b/lib/nbsd_libc/stdlib/atoll.c
new file mode 100644 (file)
index 0000000..46f1383
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: atoll.c,v 1.5 2003/10/27 00:12:42 lukem Exp $  */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "from: @(#)atol.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: atoll.c,v 1.5 2003/10/27 00:12:42 lukem Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef _LIBC
+#include "namespace.h"
+#endif
+
+#include <stdlib.h>
+
+#ifdef _LIBC
+#ifdef __weak_alias
+__weak_alias(atoll, _atoll)
+#endif
+#endif
+
+#if !HAVE_ATOLL
+/* LONGLONG */
+long long int
+atoll(str)
+       const char *str;
+{
+       return (strtoll(str, (char **)NULL, 10));
+}
+#endif
diff --git a/lib/nbsd_libc/stdlib/bsearch.3 b/lib/nbsd_libc/stdlib/bsearch.3
new file mode 100644 (file)
index 0000000..5653e9d
--- /dev/null
@@ -0,0 +1,90 @@
+.\"    $NetBSD: bsearch.3,v 1.10 2003/08/07 16:43:38 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993, 1994
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)bsearch.3    8.3 (Berkeley) 4/19/94
+.\"
+.Dd April 19, 1994
+.Dt BSEARCH 3
+.Os
+.Sh NAME
+.Nm bsearch
+.Nd binary search of a sorted table
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft void *
+.Fn bsearch "const void *key" "const void *base" "size_t nmemb" "size_t size" "int (*compar) (const void *, const void *)"
+.Sh DESCRIPTION
+The
+.Fn bsearch
+function searches an array of
+.Fa nmemb
+objects, the initial member of which is
+pointed to by
+.Fa base ,
+for a member that matches the object pointed to by
+.Fa key .
+The size of each member of the array is specified by
+.Fa size .
+.Pp
+The contents of the array should be in ascending sorted order according
+to the comparison function referenced by
+.Fa compar .
+The
+.Fa compar
+routine
+is expected to have
+two arguments which point to the
+.Fa key
+object and to an array member, in that order, and should return an integer
+less than, equal to, or greater than zero if the
+.Fa key
+object is found, respectively, to be less than, to match, or be
+greater than the array member.
+.Sh RETURN VALUES
+The
+.Fn bsearch
+function returns a pointer to a matching member of the array, or a null
+pointer if no match is found.
+If two members compare as equal, which member is matched is unspecified.
+.Sh SEE ALSO
+.Xr db 3 ,
+.Xr lsearch 3 ,
+.Xr qsort 3 ,
+.Xr tsearch 3
+.Sh STANDARDS
+The
+.Fn bsearch
+function conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdlib/bsearch.c b/lib/nbsd_libc/stdlib/bsearch.c
new file mode 100644 (file)
index 0000000..a8ab299
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: bsearch.c,v 1.14 2010/11/27 18:33:54 christos Exp $    */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)bsearch.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: bsearch.c,v 1.14 2010/11/27 18:33:54 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+
+/*
+ * Perform a binary search.
+ *
+ * The code below is a bit sneaky.  After a comparison fails, we
+ * divide the work in half by moving either left or right. If lim
+ * is odd, moving left simply involves halving lim: e.g., when lim
+ * is 5 we look at item 2, so we change lim to 2 so that we will
+ * look at items 0 & 1.  If lim is even, the same applies.  If lim
+ * is odd, moving right again involes halving lim, this time moving
+ * the base up one item past p: e.g., when lim is 5 we change base
+ * to item 3 and make lim 2 so that we will look at items 3 and 4.
+ * If lim is even, however, we have to shrink it by one before
+ * halving: e.g., when lim is 4, we still looked at item 2, so we
+ * have to make lim 3, then halve, obtaining 1, so that we will only
+ * look at item 3.
+ */
+void *
+bsearch(const void *key, const void *base0, size_t nmemb, size_t size,
+    int (*compar)(const void *, const void *))
+{
+       const char *base = base0;
+       size_t lim;
+       int cmp;
+       const void *p;
+
+       _DIAGASSERT(key != NULL);
+       _DIAGASSERT(base0 != NULL);
+       _DIAGASSERT(compar != NULL);
+
+       for (lim = nmemb; lim != 0; lim >>= 1) {
+               p = base + (lim >> 1) * size;
+               cmp = (*compar)(key, p);
+               if (cmp == 0)
+                       return __UNCONST(p);
+               if (cmp > 0) {  /* key > p: move right */
+                       base = (const char *)p + size;
+                       lim--;
+               }               /* else move left */
+       }
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/stdlib/div.3 b/lib/nbsd_libc/stdlib/div.3
new file mode 100644 (file)
index 0000000..062837d
--- /dev/null
@@ -0,0 +1,71 @@
+.\"    $NetBSD: div.3,v 1.12 2008/08/04 21:29:27 matt Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\" 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. 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.
+.\"
+.\"     from: @(#)div.3        8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt DIV 3
+.Os
+.Sh NAME
+.Nm div
+.Nd return quotient and remainder from division
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft div_t
+.Fn div "int num" "int denom"
+.Sh DESCRIPTION
+The
+.Fn div
+function
+computes the value
+.Fa num/denom
+and returns the quotient and remainder in a structure named
+.Fa div_t
+that contains two
+.Em int
+members named
+.Fa quot
+and
+.Fa rem .
+.Sh SEE ALSO
+.Xr imaxdiv 3 ,
+.Xr ldiv 3 ,
+.Xr lldiv 3 ,
+.Xr math 3 ,
+.Xr qdiv 3
+.Sh STANDARDS
+The
+.Fn div
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdlib/div.c b/lib/nbsd_libc/stdlib/div.c
new file mode 100644 (file)
index 0000000..262f594
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: div.c,v 1.7 2003/08/07 16:43:39 agc Exp $      */
+
+/*
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)div.c      8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: div.c,v 1.7 2003/08/07 16:43:39 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdlib.h>            /* div_t */
+
+div_t
+div(num, denom)
+       int num, denom;
+{
+       div_t r;
+
+       r.quot = num / denom;
+       r.rem = num % denom;
+       /*
+        * The ANSI standard says that |r.quot| <= |n/d|, where
+        * n/d is to be computed in infinite precision.  In other
+        * words, we should always truncate the quotient towards
+        * 0, never -infinity.
+        *
+        * Machine division and remainer may work either way when
+        * one or both of n or d is negative.  If only one is
+        * negative and r.quot has been truncated towards -inf,
+        * r.rem will have the same sign as denom and the opposite
+        * sign of num; if both are negative and r.quot has been
+        * truncated towards -inf, r.rem will be positive (will
+        * have the opposite sign of num).  These are considered
+        * `wrong'.
+        *
+        * If both are num and denom are positive, r will always
+        * be positive.
+        *
+        * This all boils down to:
+        *      if num >= 0, but r.rem < 0, we got the wrong answer.
+        * In that case, to get the right answer, add 1 to r.quot and
+        * subtract denom from r.rem.
+        */
+       if (num >= 0 && r.rem < 0) {
+               r.quot++;
+               r.rem -= denom;
+       }
+       return (r);
+}
diff --git a/lib/nbsd_libc/stdlib/drand48.c b/lib/nbsd_libc/stdlib/drand48.c
new file mode 100644 (file)
index 0000000..6fba607
--- /dev/null
@@ -0,0 +1,32 @@
+/*     $NetBSD: drand48.c,v 1.6 2005/06/12 05:21:28 lukem Exp $        */
+
+/*
+ * Copyright (c) 1993 Martin Birgmeier
+ * All rights reserved.
+ *
+ * You may redistribute unmodified or modified versions of this source
+ * code provided that the above copyright notice and this and the
+ * following conditions are retained.
+ *
+ * This software is provided ``as is'', and comes with no warranties
+ * of any kind. I shall in no event be liable for anything that happens
+ * to anyone/anything when using this software.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: drand48.c,v 1.6 2005/06/12 05:21:28 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "rand48.h"
+
+#ifdef __weak_alias
+__weak_alias(drand48,_drand48)
+#endif
+
+double
+drand48(void)
+{
+       return erand48(__rand48_seed);
+}
diff --git a/lib/nbsd_libc/stdlib/erand48.c b/lib/nbsd_libc/stdlib/erand48.c
new file mode 100644 (file)
index 0000000..f1d8b4d
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: erand48.c,v 1.9 2006/03/22 20:52:16 drochner Exp $     */
+
+/*
+ * Copyright (c) 1993 Martin Birgmeier
+ * All rights reserved.
+ *
+ * You may redistribute unmodified or modified versions of this source
+ * code provided that the above copyright notice and this and the
+ * following conditions are retained.
+ *
+ * This software is provided ``as is'', and comes with no warranties
+ * of any kind. I shall in no event be liable for anything that happens
+ * to anyone/anything when using this software.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: erand48.c,v 1.9 2006/03/22 20:52:16 drochner Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <math.h>
+
+#include "rand48.h"
+
+#ifdef __weak_alias
+__weak_alias(erand48,_erand48)
+#endif
+
+double
+erand48(unsigned short xseed[3])
+{
+
+       _DIAGASSERT(xseed != NULL);
+
+       __dorand48(xseed);
+       return ldexp((double) xseed[0], -48) +
+              ldexp((double) xseed[1], -32) +
+              ldexp((double) xseed[2], -16);
+}
diff --git a/lib/nbsd_libc/stdlib/erand48_ieee754.c b/lib/nbsd_libc/stdlib/erand48_ieee754.c
new file mode 100644 (file)
index 0000000..d2dee47
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: erand48_ieee754.c,v 1.2 2006/03/31 11:42:31 drochner Exp $     */
+
+/*
+ * Copyright (c) 1993 Martin Birgmeier
+ * All rights reserved.
+ *
+ * You may redistribute unmodified or modified versions of this source
+ * code provided that the above copyright notice and this and the
+ * following conditions are retained.
+ *
+ * This software is provided ``as is'', and comes with no warranties
+ * of any kind. I shall in no event be liable for anything that happens
+ * to anyone/anything when using this software.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: erand48_ieee754.c,v 1.2 2006/03/31 11:42:31 drochner Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <machine/ieee.h>
+
+#include "rand48.h"
+
+#ifdef __weak_alias
+__weak_alias(erand48,_erand48)
+#endif
+
+double
+erand48(unsigned short xseed[3])
+{
+       union ieee_double_u u;
+
+       _DIAGASSERT(xseed != NULL);
+
+       __dorand48(xseed);
+       u.dblu_dbl.dbl_sign = 0;
+       u.dblu_dbl.dbl_exp = DBL_EXP_BIAS; /* so we get [1,2) */
+       u.dblu_dbl.dbl_frach = ((unsigned int)xseed[2] << 4)
+                               | ((unsigned int)xseed[1] >> 12);
+       u.dblu_dbl.dbl_fracl = (((unsigned int)xseed[1] & 0x0fff) << 20)
+                               | ((unsigned int)xseed[0] << 4);
+       return (u.dblu_d - 1);
+}
diff --git a/lib/nbsd_libc/stdlib/exit.3 b/lib/nbsd_libc/stdlib/exit.3
new file mode 100644 (file)
index 0000000..27ee4d9
--- /dev/null
@@ -0,0 +1,101 @@
+.\" $NetBSD: exit.3,v 1.14 2003/08/07 16:43:39 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)exit.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd August 11, 2002
+.Dt EXIT 3
+.Os
+.Sh NAME
+.Nm exit
+.Nd perform normal program termination
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft void
+.Fn exit "int status"
+.Sh DESCRIPTION
+.Fn exit
+terminates a process.
+The
+.Fa status
+values
+.Dv EXIT_SUCCESS
+and
+.Dv EXIT_FAILURE
+can be used to indicate successful and unsuccessful
+termination, respectively.
+.Pp
+Before termination it performs the following functions in the
+order listed:
+.Bl -enum -offset indent
+.It
+Call the functions registered with the
+.Xr atexit 3
+function, in the reverse order of their registration.
+.It
+Flush all open output streams.
+.It
+Close all open streams.
+.It
+Unlink all files created with the
+.Xr tmpfile 3
+function.
+.El
+.Pp
+Following this,
+.Fn exit
+calls
+.Xr _exit 2 .
+Note that typically
+.Xr _exit 2
+only passes the lower 8 bits of
+.Fa status
+on to the parent, thus negative values have less meaning.
+.Sh RETURN VALUES
+The
+.Fn exit
+function
+never returns.
+.Sh SEE ALSO
+.Xr _exit 2 ,
+.Xr atexit 3 ,
+.Xr intro 3 ,
+.Xr tmpfile 3
+.Sh STANDARDS
+The
+.Fn exit
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdlib/exit.c b/lib/nbsd_libc/stdlib/exit.c
new file mode 100644 (file)
index 0000000..c5bcd67
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: exit.c,v 1.13 2010/09/09 10:19:31 skrll Exp $  */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)exit.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: exit.c,v 1.13 2010/09/09 10:19:31 skrll Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdlib.h>
+#include <unistd.h>
+#ifdef _LIBC
+#include "reentrant.h"
+#include "atexit.h"
+#endif
+
+#ifdef _LIBC
+extern void __libc_init(void);
+#ifndef __lint
+static void (*force_ref)(void) __used = __libc_init;
+#endif
+#endif
+
+void (*__cleanup) __P((void));
+
+/*
+ * Exit, flushing stdio buffers if necessary.
+ */
+void
+exit(int status)
+{
+
+#ifdef _LIBC
+       __cxa_finalize(NULL);
+#endif
+       if (__cleanup)
+               (*__cleanup)();
+       _exit(status);
+}
diff --git a/lib/nbsd_libc/stdlib/getenv.3 b/lib/nbsd_libc/stdlib/getenv.3
new file mode 100644 (file)
index 0000000..930df41
--- /dev/null
@@ -0,0 +1,227 @@
+.\"    $NetBSD: getenv.3,v 1.25 2010/10/26 22:34:33 wiz Exp $
+.\"
+.\" Copyright (c) 1988, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)getenv.3     8.2 (Berkeley) 12/11/93
+.\"
+.Dd October 25, 2010
+.Dt GETENV 3
+.Os
+.Sh NAME
+.Nm getenv ,
+.Nm getenv_r ,
+.Nm putenv ,
+.Nm setenv ,
+.Nm unsetenv
+.Nd environment variable functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft char *
+.Fn getenv "const char *name"
+.Ft int
+.Fn getenv_r "const char *name" "char *buf" "size_t len"
+.Ft int
+.Fn setenv "const char *name" "const char *value" "int overwrite"
+.Ft int
+.Fn putenv "char *string"
+.Ft int
+.Fn unsetenv "const char *name"
+.Sh DESCRIPTION
+These functions set, unset and fetch environment variables from the
+host
+.Em environment list .
+For compatibility with differing environment conventions,
+the
+.Fn getenv
+or
+.Fn getenv_r
+given argument
+.Ar name
+may be appended with an equal sign
+.Dq Li \&= .
+.Pp
+The
+.Fn getenv
+function obtains the current value of the environment variable
+.Ar name .
+If the variable
+.Ar name
+is not in the current environment, a
+.Dv NULL
+pointer is returned.
+.Pp
+The
+.Fn getenv_r
+function obtains the current value of the environment variable
+.Fa name
+and copies it to
+.Fa buf .
+If
+.Fa name
+is not in the current environment, or the string length of the value of
+.Fa name
+is longer than
+.Fa len
+characters, then \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Pp
+The
+.Fn setenv
+function inserts or resets the environment variable
+.Ar name
+in the current environment list.
+If the variable
+.Ar name
+does not exist in the list,
+it is inserted with the given
+.Ar value .
+If the variable does exist, the argument
+.Ar overwrite
+is tested; if
+.Ar overwrite is
+zero, the
+variable is not reset, otherwise it is reset
+to the given
+.Ar value .
+.Pp
+The
+.Fn putenv
+function takes an argument of the form
+.Dq name=value
+and it will set the environment variable
+.Dq name
+equal to
+.Dq value
+by altering an existing entry, or creating a new one if an existing
+one does not exist.
+The actual string argument passed to
+.Fn putenv
+will become part of the environment.
+If one changes the string, the environment will also change.
+.Pp
+The
+.Fn unsetenv
+function
+deletes all instances of the variable name pointed to by
+.Fa name
+from the list.
+.Sh RETURN VALUES
+The functions
+.Fn getenv_r ,
+.Fn setenv ,
+.Fn putenv ,
+and
+.Fn unsetenv
+return zero if successful; otherwise the global variable
+.Va errno
+is set to indicate the error and a
+\-1 is returned.
+.Pp
+If
+.Fn getenv
+is successful, the string returned should be considered read-only.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa name
+argument to
+.Fn setenv
+or
+.Fn unsetenv
+is a null pointer, points to an empty string, or points to a string
+containing an
+.Dq Li \&=
+character.
+The
+.Fa value
+argument to
+.Fn setenv
+is a null pointer.
+The
+.Fa string
+argument to
+.Fn putenv
+is a null pointer, or points to a string that either starts with a
+.Dq Li \&=
+character or does not contain one at all.
+.It Bq Er ENOMEM
+The function
+.Fn setenv
+or
+.Fn putenv
+failed because they were unable to allocate memory for the environment.
+.El
+.Pp
+The function
+.Fn getenv_r
+can return the following errors:
+.Bl -tag -width Er
+.It Bq Er ENOENT
+The variable
+.Fa name
+was not found in the environment.
+.It Bq Er ERANGE
+The value of the named variable is too long to fit in the supplied buffer.
+.El
+.Sh SEE ALSO
+.Xr csh 1 ,
+.Xr sh 1 ,
+.Xr execve 2 ,
+.Xr environ 7
+.Sh STANDARDS
+The
+.Fn getenv
+function conforms to
+.St -ansiC .
+The
+.Fn putenv
+function conforms to
+.St -xpg4 .
+The
+.Fn unsetenv
+function conforms to
+.St -p1003.1-2001 .
+.Sh HISTORY
+The functions
+.Fn setenv
+and
+.Fn unsetenv
+appeared in
+.At v7 .
+The
+.Fn putenv
+function appeared in
+.Bx 4.3 Reno .
diff --git a/lib/nbsd_libc/stdlib/getenv.c b/lib/nbsd_libc/stdlib/getenv.c
new file mode 100644 (file)
index 0000000..ccd52e7
--- /dev/null
@@ -0,0 +1,113 @@
+/*     $NetBSD: getenv.c,v 1.35 2010/11/14 22:04:36 tron Exp $ */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getenv.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getenv.c,v 1.35 2010/11/14 22:04:36 tron Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "env.h"
+#include "reentrant.h"
+#include "local.h"
+
+__weak_alias(getenv_r, _getenv_r)
+
+/*
+ * getenv --
+ *     Returns ptr to value associated with name, if any, else NULL.
+ *     XXX: we cannot use getenv_r to implement this, because getenv()
+ *     cannot use a shared buffer, because if it did, subsequent calls
+ *     to getenv would trash previous results.
+ */
+char *
+getenv(const char *name)
+{
+       size_t l_name;
+       char *result;
+
+       _DIAGASSERT(name != NULL);
+
+       l_name = __envvarnamelen(name, false);
+       if (l_name == 0)
+               return NULL;
+
+       result = NULL;
+       if (__readlockenv()) {
+               result = __findenvvar(name, l_name);
+               (void)__unlockenv();
+       }
+       
+       return result;
+}
+
+int
+getenv_r(const char *name, char *buf, size_t len)
+{
+       size_t l_name;
+       int rv;
+
+       _DIAGASSERT(name != NULL);
+
+       l_name = __envvarnamelen(name, false);
+       if (l_name == 0) {
+               errno = ENOENT;
+               return -1;
+       }
+
+       rv = -1;
+       if (__readlockenv()) {
+               const char *value;
+
+               value = __findenvvar(name, l_name);
+               if (value != NULL) {
+                       if (strlcpy(buf, value, len) < len) {
+                               rv = 0;
+                       } else {
+                               errno = ERANGE;
+                       }
+               } else {
+                       errno = ENOENT;
+               }
+               (void)__unlockenv();
+       }
+       
+       return rv;
+}
diff --git a/lib/nbsd_libc/stdlib/getopt.3 b/lib/nbsd_libc/stdlib/getopt.3
new file mode 100644 (file)
index 0000000..1e51d03
--- /dev/null
@@ -0,0 +1,299 @@
+.\"    $NetBSD: getopt.3,v 1.32 2010/03/22 19:30:54 joerg Exp $
+.\"
+.\" Copyright (c) 1988, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getopt.3   8.5 (Berkeley) 4/27/95
+.\"
+.Dd September 10, 2003
+.Dt GETOPT 3
+.Os
+.Sh NAME
+.Nm getopt
+.Nd get option character from command line argument list
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Vt extern char *optarg;
+.Vt extern int   optind;
+.Vt extern int   optopt;
+.Vt extern int   opterr;
+.Vt extern int   optreset;
+.Ft int
+.Fn getopt "int argc" "char * const argv[]" "const char *optstring"
+.Sh DESCRIPTION
+The
+.Fn getopt
+function incrementally parses a command line argument list
+.Fa argv
+and returns the next
+.Em known
+option character.
+An option character is
+.Em known
+if it has been specified in the string of accepted option characters,
+.Fa optstring .
+.Pp
+The option string
+.Fa optstring
+may contain the following elements: individual characters, and
+characters followed by a colon to indicate an option argument
+is to follow.
+For example, an option string
+.Qq x
+recognizes an option
+.Dq Fl x ,
+and an option string
+.Qq x:
+recognizes an option and argument
+.Dq Fl x Ar argument .
+It does not matter to
+.Fn getopt
+if a following argument has leading whitespace.
+.Pp
+On return from
+.Fn getopt ,
+.Va optarg
+points to an option argument, if it is anticipated,
+and the variable
+.Va optind
+contains the index to the next
+.Fa argv
+argument for a subsequent call
+to
+.Fn getopt .
+The variable
+.Va optopt
+saves the last
+.Em known
+option character returned by
+.Fn getopt .
+.Pp
+The variables
+.Va opterr
+and
+.Va optind
+are both initialized to 1.
+The
+.Va optind
+variable may be set to another value before a set of calls to
+.Fn getopt
+in order to skip over more or less argv entries.
+.Pp
+In order to use
+.Fn getopt
+to evaluate multiple sets of arguments, or to evaluate a single set of
+arguments multiple times,
+the variable
+.Va optreset
+must be set to 1 before the second and each additional set of calls to
+.Fn getopt ,
+and the variable
+.Va optind
+must be reinitialized.
+.Pp
+The
+.Fn getopt
+function returns \-1 when the argument list is exhausted.
+The interpretation of options in the argument list may be cancelled
+by the option
+.Dq --
+(double dash) which causes
+.Fn getopt
+to signal the end of argument processing and return \-1.
+When all options have been processed (i.e., up to the first non-option
+argument),
+.Fn getopt
+returns \-1.
+.Sh RETURN VALUES
+The
+.Fn getopt
+function returns the next known option character in
+.Fa optstring .
+If
+.Fn getopt
+encounters a character not found in
+.Fa optstring
+or if it detects a missing option argument,
+it returns
+.Sq \&?
+(question mark).
+If
+.Fa optstring
+has a leading
+.Sq \&:
+then a missing option argument causes
+.Sq \&:
+to be returned instead of
+.Sq \&? .
+In either case, the variable
+.Va optopt
+is set to the character that caused the error.
+The
+.Fn getopt
+function returns \-1 when the argument list is exhausted.
+.Sh EXAMPLES
+.Bd -literal -compact
+extern char *optarg;
+extern int optind;
+int bflag, ch, fd;
+
+bflag = 0;
+while ((ch = getopt(argc, argv, "bf:")) != -1) {
+       switch (ch) {
+       case 'b':
+               bflag = 1;
+               break;
+       case 'f':
+               if ((fd = open(optarg, O_RDONLY, 0)) \*[Lt] 0) {
+                       (void)fprintf(stderr,
+                           "myname: %s: %s\en", optarg, strerror(errno));
+                       exit(1);
+               }
+               break;
+       case '?':
+       default:
+               usage();
+       }
+}
+argc -= optind;
+argv += optind;
+.Ed
+.Sh DIAGNOSTICS
+If the
+.Fn getopt
+function encounters a character not found in the string
+.Fa optstring
+or detects
+a missing option argument it writes an error message to
+.Em stderr
+and returns
+.Sq \&? .
+Setting
+.Va opterr
+to a zero will disable these error messages.
+If
+.Fa optstring
+has a leading
+.Sq \&:
+then a missing option argument causes a
+.Sq \&:
+to be returned in addition to suppressing any error messages.
+.Pp
+Option arguments are allowed to begin with
+.Sq - ;
+this is reasonable but reduces the amount of error checking possible.
+.Sh SEE ALSO
+.Xr getopt 1 ,
+.Xr getopt_long 3 ,
+.Xr getsubopt 3
+.Sh STANDARDS
+The
+.Va optreset
+variable was added to make it possible to call the
+.Fn getopt
+function multiple times.
+This is an extension to the
+.St -p1003.2
+specification.
+.Sh HISTORY
+The
+.Fn getopt
+function appeared in
+.Bx 4.3 .
+.Sh BUGS
+The
+.Fn getopt
+function was once specified to return
+.Dv EOF
+instead of \-1.
+This was changed by
+.St -p1003.2-92
+to decouple
+.Fn getopt
+from
+.In stdio.h .
+.Pp
+A single dash
+.Pq Sq -
+may be specified as a character in
+.Fa optstring ,
+however it should
+.Em never
+have an argument associated with it.
+This allows
+.Fn getopt
+to be used with programs that expect
+.Sq -
+as an option flag.
+This practice is wrong, and should not be used in any current development.
+It is provided for backward compatibility
+.Em only .
+Care should be taken not to use
+.Sq -
+as the first character in
+.Fa optstring
+to avoid a semantic conflict with
+.Tn GNU
+.Fn getopt ,
+which assigns different meaning to an
+.Fa optstring
+that begins with a
+.Sq - .
+By default, a single dash causes
+.Fn getopt
+to return \-1.
+.Pp
+It is also possible to handle digits as option letters.
+This allows
+.Fn getopt
+to be used with programs that expect a number
+.Pq Dq Li \-3
+as an option.
+This practice is wrong, and should not be used in any current development.
+It is provided for backward compatibility
+.Em only .
+The following code fragment works in most cases.
+.Bd -literal -offset indent
+int ch;
+long length;
+char *p;
+
+while ((ch = getopt(argc, argv, "0123456789")) != -1) {
+       switch (ch) {
+       case '0': case '1': case '2': case '3': case '4':
+       case '5': case '6': case '7': case '8': case '9':
+               p = argv[optind - 1];
+               if (p[0] == '-' \*[Am]\*[Am] p[1] == ch \*[Am]\*[Am] !p[2])
+                       length = ch - '0';
+               else
+                       length = strtol(argv[optind] + 1, NULL, 10);
+               break;
+       }
+}
+.Ed
diff --git a/lib/nbsd_libc/stdlib/getopt.c b/lib/nbsd_libc/stdlib/getopt.c
new file mode 100644 (file)
index 0000000..976a06c
--- /dev/null
@@ -0,0 +1,136 @@
+/*     $NetBSD: getopt.c,v 1.28 2009/03/20 13:56:57 joerg Exp $        */
+
+/*
+ * Copyright (c) 1987, 1993, 1994
+ *     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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: getopt.c,v 1.28 2009/03/20 13:56:57 joerg Exp $");
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(getopt,_getopt)
+#endif
+
+int    opterr = 1,             /* if error message should be printed */
+       optind = 1,             /* index into parent argv vector */
+       optopt,                 /* character checked for validity */
+       optreset;               /* reset getopt */
+char   *optarg;                /* argument associated with option */
+
+#define        BADCH   (int)'?'
+#define        BADARG  (int)':'
+#define        EMSG    ""
+
+/*
+ * getopt --
+ *     Parse argc/argv argument vector.
+ */
+int
+getopt(int nargc, char * const nargv[], const char *ostr)
+{
+       static const char *place = EMSG;        /* option letter processing */
+       char *oli;                              /* option letter list index */
+
+       _DIAGASSERT(nargv != NULL);
+       _DIAGASSERT(ostr != NULL);
+
+       if (optreset || *place == 0) {          /* update scanning pointer */
+               optreset = 0;
+               place = nargv[optind];
+               if (optind >= nargc || *place++ != '-') {
+                       /* Argument is absent or is not an option */
+                       place = EMSG;
+                       return (-1);
+               }
+               optopt = *place++;
+               if (optopt == '-' && *place == 0) {
+                       /* "--" => end of options */
+                       ++optind;
+                       place = EMSG;
+                       return (-1);
+               }
+               if (optopt == 0) {
+                       /* Solitary '-', treat as a '-' option
+                          if the program (eg su) is looking for it. */
+                       place = EMSG;
+                       if (strchr(ostr, '-') == NULL)
+                               return -1;
+                       optopt = '-';
+               }
+       } else
+               optopt = *place++;
+
+       /* See if option letter is one the caller wanted... */
+       if (optopt == ':' || (oli = strchr(ostr, optopt)) == NULL) {
+               if (*place == 0)
+                       ++optind;
+               if (opterr && *ostr != ':')
+                       (void)fprintf(stderr,
+                           "%s: unknown option -- %c\n", getprogname(),
+                           optopt);
+               return (BADCH);
+       }
+
+       /* Does this option need an argument? */
+       if (oli[1] != ':') {
+               /* don't need argument */
+               optarg = NULL;
+               if (*place == 0)
+                       ++optind;
+       } else {
+               /* Option-argument is either the rest of this argument or the
+                  entire next argument. */
+               if (*place)
+                       optarg = __UNCONST(place);
+               else if (nargc > ++optind)
+                       optarg = nargv[optind];
+               else {
+                       /* option-argument absent */
+                       place = EMSG;
+                       if (*ostr == ':')
+                               return (BADARG);
+                       if (opterr)
+                               (void)fprintf(stderr,
+                                   "%s: option requires an argument -- %c\n",
+                                   getprogname(), optopt);
+                       return (BADCH);
+               }
+               place = EMSG;
+               ++optind;
+       }
+       return (optopt);                        /* return option letter */
+}
diff --git a/lib/nbsd_libc/stdlib/getopt_long.3 b/lib/nbsd_libc/stdlib/getopt_long.3
new file mode 100644 (file)
index 0000000..6d03631
--- /dev/null
@@ -0,0 +1,310 @@
+.\"    $NetBSD: getopt_long.3,v 1.18 2007/07/02 17:56:17 ginsbach Exp $
+.\"
+.\" Copyright (c) 1988, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getopt.3   8.5 (Berkeley) 4/27/95
+.\"
+.Dd July 2, 2007
+.Dt GETOPT_LONG 3
+.Os
+.Sh NAME
+.Nm getopt_long
+.Nd get long options from command line argument list
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In getopt.h
+.Ft int
+.Fn getopt_long "int argc" "char * const *argv" "const char *optstring" "struct option *long_options" "int *index"
+.Sh DESCRIPTION
+The
+.Fn getopt_long
+function is similar to
+.Xr getopt 3
+but it accepts options in two forms: words and characters.
+The
+.Fn getopt_long
+function provides a superset of the functionality of
+.Xr getopt 3 .
+.Fn getopt_long
+can be used in two ways.
+In the first way, every long option understood by the program has a
+corresponding short option, and the option structure is only used to
+translate from long options to short options.
+When used in this fashion,
+.Fn getopt_long
+behaves identically to
+.Xr getopt 3 .
+This is a good way to add long option processing to an existing program
+with the minimum of rewriting.
+.Pp
+In the second mechanism, a long option sets a flag in the
+.Fa option
+structure passed, or will store a pointer to the command line argument
+in the
+.Fa option
+structure passed to it for options that take arguments.
+Additionally, the long option's argument may be specified as a single
+argument with an equal sign, e.g.
+.Bd -literal
+myprogram --myoption=somevalue
+.Ed
+.Pp
+When a long option is processed the call to
+.Fn getopt_long
+will return 0.
+For this reason, long option processing without
+shortcuts is not backwards compatible with
+.Xr getopt 3 .
+.Pp
+It is possible to combine these methods, providing for long options
+processing with short option equivalents for some options.
+Less frequently used options would be processed as long options only.
+.Pp
+Abbreviated long option names are accepted when
+.Fn getopt_long
+processes long options if the abbreviation is unique.
+An exact match is always preferred for a defined long option.
+.Pp
+The
+.Fn getopt_long
+call requires a structure to be initialized describing the long options.
+The structure is:
+.Bd -literal
+struct option {
+       char *name;
+       int has_arg;
+       int *flag;
+       int val;
+};
+.Ed
+.Pp
+The
+.Fa name
+field should contain the option name without the leading double dash.
+.Pp
+The
+.Fa has_arg
+field should be one of:
+.Bl -tag -width "optional_argument"
+.It Li no_argument
+no argument to the option is expect.
+.It Li required_argument
+an argument to the option is required.
+.It Li optional_argument
+an argument to the option may be presented.
+.El
+.Pp
+If
+.Fa flag
+is not
+.Dv NULL ,
+then the integer pointed to by it will be set to the value in the
+.Fa val
+field.
+If the
+.Fa flag
+field is
+.Dv NULL ,
+then the
+.Fa val
+field will be returned.
+Setting
+.Fa flag
+to
+.Dv NULL
+and setting
+.Fa val
+to the corresponding short option will make this function act just
+like
+.Xr getopt 3 .
+.Pp
+If the
+.Fa index
+field is not
+.Dv NULL ,
+the integer it points to will be set to the index of the long option
+in the
+.Fa long_options
+array.
+.Pp
+The last element of the
+.Fa long_options
+array has to be filled with zeroes (see
+.Sx EXAMPLES
+section).
+.Sh EXAMPLES
+.Bd -literal -compact
+extern char *optarg;
+extern int optind;
+int bflag, ch, fd;
+int daggerset;
+
+/* options descriptor */
+static struct option longopts[] = {
+       { "buffy",      no_argument,            0,              'b' },
+       { "fluoride",   required_argument,      0,              'f' },
+       { "daggerset",  no_argument,            \*[Am]daggerset,        1 },
+       { NULL,         0,                      NULL,           0 }
+};
+
+bflag = 0;
+while ((ch = getopt_long(argc, argv, "bf:", longopts, NULL)) != -1)
+       switch (ch) {
+       case 'b':
+               bflag = 1;
+               break;
+       case 'f':
+               if ((fd = open(optarg, O_RDONLY, 0)) \*[Lt] 0) {
+                       (void)fprintf(stderr,
+                           "myname: %s: %s\en", optarg, strerror(errno));
+                       exit(1);
+               }
+               break;
+       case 0:
+               if(daggerset) {
+                       fprintf(stderr,"Buffy will use her dagger to "
+                                      "apply fluoride to dracula's teeth\en");
+               }
+               break;
+       case '?':
+       default:
+               usage();
+}
+argc -= optind;
+argv += optind;
+.Ed
+.Sh IMPLEMENTATION DIFFERENCES
+This section describes differences to the GNU implementation
+found in glibc-2.1.3:
+.Bl -tag -width "xxx"
+.It Li o
+handling of - as first char of option string in presence of
+environment variable POSIXLY_CORRECT:
+.Bl -tag -width "NetBSD"
+.It Li GNU
+ignores POSIXLY_CORRECT and returns non-options as
+arguments to option '\e1'.
+.It Li NetBSD
+honors POSIXLY_CORRECT and stops at the first non-option.
+.El
+.It Li o
+handling of :: in options string in presence of POSIXLY_CORRECT:
+.Bl -tag -width "NetBSD"
+.It Li Both
+GNU and NetBSD ignore POSIXLY_CORRECT here and take :: to
+mean the preceding option takes an optional argument.
+.El
+.It Li o
+return value in case of missing argument if first character
+(after + or -) in option string is not ':':
+.Bl -tag -width "NetBSD"
+.It Li GNU
+returns '?'
+.It NetBSD
+returns ':' (since NetBSD's getopt does).
+.El
+.It Li o
+handling of --a in getopt:
+.Bl -tag -width "NetBSD"
+.It Li GNU
+parses this as option '-', option 'a'.
+.It Li NetBSD
+parses this as '--', and returns \-1 (ignoring the a).
+(Because the original getopt does.)
+.El
+.It Li o
+setting of optopt for long options with flag !=
+.Dv NULL :
+.Bl -tag -width "NetBSD"
+.It Li GNU
+sets optopt to val.
+.It Li NetBSD
+sets optopt to 0 (since val would never be returned).
+.El
+.It Li o
+handling of -W with W; in option string in getopt (not getopt_long):
+.Bl -tag -width "NetBSD"
+.It Li GNU
+causes a segfault.
+.It Li NetBSD
+returns \-1, with optind pointing past the argument of -W
+(as if `-W arg' were `--arg', and thus '--' had been found).
+.\" How should we treat W; in the option string when called via
+.\" getopt?  Ignore the ';' or treat it as a ':'? Issue a warning?
+.El
+.It Li o
+setting of optarg for long options without an argument that are
+invoked via -W (W; in option string):
+.Bl -tag -width "NetBSD"
+.It Li GNU
+sets optarg to the option name (the argument of -W).
+.It Li NetBSD
+sets optarg to
+.Dv NULL
+(the argument of the long option).
+.El
+.It Li o
+handling of -W with an argument that is not (a prefix to) a known
+long option (W; in option string):
+.Bl -tag -width "NetBSD"
+.It Li GNU
+returns -W with optarg set to the unknown option.
+.It Li NetBSD
+treats this as an error (unknown option) and returns '?' with
+optopt set to 0 and optarg set to
+.Dv NULL
+(as GNU's man page documents).
+.El
+.It Li o
+The error messages are different.
+.It Li o
+NetBSD does not permute the argument vector at the same points in
+the calling sequence as GNU does.
+The aspects normally used by the caller
+(ordering after \-1 is returned, value of optind relative
+to current positions) are the same, though.
+(We do fewer variable swaps.)
+.El
+.Sh SEE ALSO
+.Xr getopt 3
+.Sh HISTORY
+The
+.Fn getopt_long
+function first appeared in GNU libiberty.
+The first
+.Nx
+implementation appeared in 1.5.
+.Sh BUGS
+The implementation can completely replace
+.Xr getopt 3 ,
+but right now we are using separate code.
+.Pp
+The
+.Fa argv
+argument is not really const.
diff --git a/lib/nbsd_libc/stdlib/getopt_long.c b/lib/nbsd_libc/stdlib/getopt_long.c
new file mode 100644 (file)
index 0000000..70844e3
--- /dev/null
@@ -0,0 +1,482 @@
+/*     $NetBSD: getopt_long.c,v 1.25 2009/03/20 14:05:54 joerg Exp $   */
+
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dieter Baron and Thomas Klausner.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: getopt_long.c,v 1.25 2009/03/20 14:05:54 joerg Exp $");
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <err.h>
+#include <errno.h>
+#if HAVE_NBTOOL_CONFIG_H
+#include "compat_getopt.h"
+#else
+#include <getopt.h>
+#endif
+#include <stdlib.h>
+#include <string.h>
+
+#if HAVE_NBTOOL_CONFIG_H && !HAVE_GETOPT_LONG && !HAVE_DECL_OPTIND
+#define REPLACE_GETOPT
+#endif
+
+#ifdef REPLACE_GETOPT
+#ifdef __weak_alias
+__weak_alias(getopt,_getopt)
+#endif
+int    opterr = 1;             /* if error message should be printed */
+int    optind = 1;             /* index into parent argv vector */
+int    optopt = '?';           /* character checked for validity */
+int    optreset;               /* reset getopt */
+char    *optarg;               /* argument associated with option */
+#elif HAVE_NBTOOL_CONFIG_H && !HAVE_DECL_OPTRESET
+static int optreset;
+#endif
+
+#ifdef __weak_alias
+__weak_alias(getopt_long,_getopt_long)
+#endif
+
+#define IGNORE_FIRST   (*options == '-' || *options == '+')
+#define PRINT_ERROR    ((opterr) && ((*options != ':') \
+                                     || (IGNORE_FIRST && options[1] != ':')))
+#define IS_POSIXLY_CORRECT (getenv("POSIXLY_CORRECT") != NULL)
+#define PERMUTE         (!IS_POSIXLY_CORRECT && !IGNORE_FIRST)
+/* XXX: GNU ignores PC if *options == '-' */
+#define IN_ORDER        (!IS_POSIXLY_CORRECT && *options == '-')
+
+/* return values */
+#define        BADCH   (int)'?'
+#define        BADARG          ((IGNORE_FIRST && options[1] == ':') \
+                        || (*options == ':') ? (int)':' : (int)'?')
+#define INORDER (int)1
+
+#define        EMSG    ""
+
+static int getopt_internal(int, char **, const char *);
+static int gcd(int, int);
+static void permute_args(int, int, int, char **);
+
+static const char *place = EMSG; /* option letter processing */
+
+/* XXX: set optreset to 1 rather than these two */
+static int nonopt_start = -1; /* first non option argument (for permute) */
+static int nonopt_end = -1;   /* first option after non options (for permute) */
+
+/* Error messages */
+static const char recargchar[] = "option requires an argument -- %c";
+static const char recargstring[] = "option requires an argument -- %s";
+static const char ambig[] = "ambiguous option -- %.*s";
+static const char noarg[] = "option doesn't take an argument -- %.*s";
+static const char illoptchar[] = "unknown option -- %c";
+static const char illoptstring[] = "unknown option -- %s";
+
+
+/*
+ * Compute the greatest common divisor of a and b.
+ */
+static int
+gcd(int a, int b)
+{
+       int c;
+
+       c = a % b;
+       while (c != 0) {
+               a = b;
+               b = c;
+               c = a % b;
+       }
+          
+       return b;
+}
+
+/*
+ * Exchange the block from nonopt_start to nonopt_end with the block
+ * from nonopt_end to opt_end (keeping the same order of arguments
+ * in each block).
+ */
+static void
+permute_args(int panonopt_start, int panonopt_end, int opt_end, char **nargv)
+{
+       int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
+       char *swap;
+
+       _DIAGASSERT(nargv != NULL);
+
+       /*
+        * compute lengths of blocks and number and size of cycles
+        */
+       nnonopts = panonopt_end - panonopt_start;
+       nopts = opt_end - panonopt_end;
+       ncycle = gcd(nnonopts, nopts);
+       cyclelen = (opt_end - panonopt_start) / ncycle;
+
+       for (i = 0; i < ncycle; i++) {
+               cstart = panonopt_end+i;
+               pos = cstart;
+               for (j = 0; j < cyclelen; j++) {
+                       if (pos >= panonopt_end)
+                               pos -= nnonopts;
+                       else
+                               pos += nopts;
+                       swap = nargv[pos];
+                       nargv[pos] = nargv[cstart];
+                       nargv[cstart] = swap;
+               }
+       }
+}
+
+/*
+ * getopt_internal --
+ *     Parse argc/argv argument vector.  Called by user level routines.
+ *  Returns -2 if -- is found (can be long option or end of options marker).
+ */
+static int
+getopt_internal(int nargc, char **nargv, const char *options)
+{
+       char *oli;                              /* option letter list index */
+       int optchar;
+
+       _DIAGASSERT(nargv != NULL);
+       _DIAGASSERT(options != NULL);
+
+       optarg = NULL;
+
+       /*
+        * XXX Some programs (like rsyncd) expect to be able to
+        * XXX re-initialize optind to 0 and have getopt_long(3)
+        * XXX properly function again.  Work around this braindamage.
+        */
+       if (optind == 0)
+               optind = 1;
+
+       if (optreset)
+               nonopt_start = nonopt_end = -1;
+start:
+       if (optreset || !*place) {              /* update scanning pointer */
+               optreset = 0;
+               if (optind >= nargc) {          /* end of argument vector */
+                       place = EMSG;
+                       if (nonopt_end != -1) {
+                               /* do permutation, if we have to */
+                               permute_args(nonopt_start, nonopt_end,
+                                   optind, nargv);
+                               optind -= nonopt_end - nonopt_start;
+                       }
+                       else if (nonopt_start != -1) {
+                               /*
+                                * If we skipped non-options, set optind
+                                * to the first of them.
+                                */
+                               optind = nonopt_start;
+                       }
+                       nonopt_start = nonopt_end = -1;
+                       return -1;
+               }
+               if ((*(place = nargv[optind]) != '-')
+                   || (place[1] == '\0')) {    /* found non-option */
+                       place = EMSG;
+                       if (IN_ORDER) {
+                               /*
+                                * GNU extension: 
+                                * return non-option as argument to option 1
+                                */
+                               optarg = nargv[optind++];
+                               return INORDER;
+                       }
+                       if (!PERMUTE) {
+                               /*
+                                * if no permutation wanted, stop parsing
+                                * at first non-option
+                                */
+                               return -1;
+                       }
+                       /* do permutation */
+                       if (nonopt_start == -1)
+                               nonopt_start = optind;
+                       else if (nonopt_end != -1) {
+                               permute_args(nonopt_start, nonopt_end,
+                                   optind, nargv);
+                               nonopt_start = optind -
+                                   (nonopt_end - nonopt_start);
+                               nonopt_end = -1;
+                       }
+                       optind++;
+                       /* process next argument */
+                       goto start;
+               }
+               if (nonopt_start != -1 && nonopt_end == -1)
+                       nonopt_end = optind;
+               if (place[1] && *++place == '-') {      /* found "--" */
+                       place++;
+                       return -2;
+               }
+       }
+       if ((optchar = (int)*place++) == (int)':' ||
+           (oli = strchr(options + (IGNORE_FIRST ? 1 : 0), optchar)) == NULL) {
+               /* option letter unknown or ':' */
+               if (!*place)
+                       ++optind;
+               if (PRINT_ERROR)
+                       warnx(illoptchar, optchar);
+               optopt = optchar;
+               return BADCH;
+       }
+       if (optchar == 'W' && oli[1] == ';') {          /* -W long-option */
+               /* XXX: what if no long options provided (called by getopt)? */
+               if (*place) 
+                       return -2;
+
+               if (++optind >= nargc) {        /* no arg */
+                       place = EMSG;
+                       if (PRINT_ERROR)
+                               warnx(recargchar, optchar);
+                       optopt = optchar;
+                       return BADARG;
+               } else                          /* white space */
+                       place = nargv[optind];
+               /*
+                * Handle -W arg the same as --arg (which causes getopt to
+                * stop parsing).
+                */
+               return -2;
+       }
+       if (*++oli != ':') {                    /* doesn't take argument */
+               if (!*place)
+                       ++optind;
+       } else {                                /* takes (optional) argument */
+               optarg = NULL;
+               if (*place)                     /* no white space */
+                       optarg = __UNCONST(place);
+               /* XXX: disable test for :: if PC? (GNU doesn't) */
+               else if (oli[1] != ':') {       /* arg not optional */
+                       if (++optind >= nargc) {        /* no arg */
+                               place = EMSG;
+                               if (PRINT_ERROR)
+                                       warnx(recargchar, optchar);
+                               optopt = optchar;
+                               return BADARG;
+                       } else
+                               optarg = nargv[optind];
+               }
+               place = EMSG;
+               ++optind;
+       }
+       /* dump back option letter */
+       return optchar;
+}
+
+#ifdef REPLACE_GETOPT
+/*
+ * getopt --
+ *     Parse argc/argv argument vector.
+ *
+ * [eventually this will replace the real getopt]
+ */
+int
+getopt(nargc, nargv, options)
+       int nargc;
+       char * const *nargv;
+       const char *options;
+{
+       int retval;
+
+       _DIAGASSERT(nargv != NULL);
+       _DIAGASSERT(options != NULL);
+
+       retval = getopt_internal(nargc, __UNCONST(nargv), options);
+       if (retval == -2) {
+               ++optind;
+               /*
+                * We found an option (--), so if we skipped non-options,
+                * we have to permute.
+                */
+               if (nonopt_end != -1) {
+                       permute_args(nonopt_start, nonopt_end, optind,
+                                      nargv);
+                       optind -= nonopt_end - nonopt_start;
+               }
+               nonopt_start = nonopt_end = -1;
+               retval = -1;
+       }
+       return retval;
+}
+#endif
+
+/*
+ * getopt_long --
+ *     Parse argc/argv argument vector.
+ */
+int
+getopt_long(int nargc, char * const *nargv, const char *options,
+    const struct option *long_options, int *idx)
+{
+       int retval;
+
+#define IDENTICAL_INTERPRETATION(_x, _y)                               \
+       (long_options[(_x)].has_arg == long_options[(_y)].has_arg &&    \
+        long_options[(_x)].flag == long_options[(_y)].flag &&          \
+        long_options[(_x)].val == long_options[(_y)].val)
+
+       _DIAGASSERT(nargv != NULL);
+       _DIAGASSERT(options != NULL);
+       _DIAGASSERT(long_options != NULL);
+       /* idx may be NULL */
+
+       retval = getopt_internal(nargc, __UNCONST(nargv), options);
+       if (retval == -2) {
+               char *current_argv, *has_equal;
+               size_t current_argv_len;
+               int i, ambiguous, match;
+
+               current_argv = __UNCONST(place);
+               match = -1;
+               ambiguous = 0;
+
+               optind++;
+               place = EMSG;
+
+               if (*current_argv == '\0') {            /* found "--" */
+                       /*
+                        * We found an option (--), so if we skipped
+                        * non-options, we have to permute.
+                        */
+                       if (nonopt_end != -1) {
+                               permute_args(nonopt_start, nonopt_end,
+                                   optind, __UNCONST(nargv));
+                               optind -= nonopt_end - nonopt_start;
+                       }
+                       nonopt_start = nonopt_end = -1;
+                       return -1;
+               }
+               if ((has_equal = strchr(current_argv, '=')) != NULL) {
+                       /* argument found (--option=arg) */
+                       current_argv_len = has_equal - current_argv;
+                       has_equal++;
+               } else
+                       current_argv_len = strlen(current_argv);
+           
+               for (i = 0; long_options[i].name; i++) {
+                       /* find matching long option */
+                       if (strncmp(current_argv, long_options[i].name,
+                           current_argv_len))
+                               continue;
+
+                       if (strlen(long_options[i].name) ==
+                           (unsigned)current_argv_len) {
+                               /* exact match */
+                               match = i;
+                               ambiguous = 0;
+                               break;
+                       }
+                       if (match == -1)                /* partial match */
+                               match = i;
+                       else if (!IDENTICAL_INTERPRETATION(i, match))
+                               ambiguous = 1;
+               }
+               if (ambiguous) {
+                       /* ambiguous abbreviation */
+                       if (PRINT_ERROR)
+                               warnx(ambig, (int)current_argv_len,
+                                    current_argv);
+                       optopt = 0;
+                       return BADCH;
+               }
+               if (match != -1) {                      /* option found */
+                       if (long_options[match].has_arg == no_argument
+                           && has_equal) {
+                               if (PRINT_ERROR)
+                                       warnx(noarg, (int)current_argv_len,
+                                            current_argv);
+                               /*
+                                * XXX: GNU sets optopt to val regardless of
+                                * flag
+                                */
+                               if (long_options[match].flag == NULL)
+                                       optopt = long_options[match].val;
+                               else
+                                       optopt = 0;
+                               return BADARG;
+                       }
+                       if (long_options[match].has_arg == required_argument ||
+                           long_options[match].has_arg == optional_argument) {
+                               if (has_equal)
+                                       optarg = has_equal;
+                               else if (long_options[match].has_arg ==
+                                   required_argument) {
+                                       /*
+                                        * optional argument doesn't use
+                                        * next nargv
+                                        */
+                                       optarg = nargv[optind++];
+                               }
+                       }
+                       if ((long_options[match].has_arg == required_argument)
+                           && (optarg == NULL)) {
+                               /*
+                                * Missing argument; leading ':'
+                                * indicates no error should be generated
+                                */
+                               if (PRINT_ERROR)
+                                       warnx(recargstring, current_argv);
+                               /*
+                                * XXX: GNU sets optopt to val regardless
+                                * of flag
+                                */
+                               if (long_options[match].flag == NULL)
+                                       optopt = long_options[match].val;
+                               else
+                                       optopt = 0;
+                               --optind;
+                               return BADARG;
+                       }
+               } else {                        /* unknown option */
+                       if (PRINT_ERROR)
+                               warnx(illoptstring, current_argv);
+                       optopt = 0;
+                       return BADCH;
+               }
+               if (long_options[match].flag) {
+                       *long_options[match].flag = long_options[match].val;
+                       retval = 0;
+               } else 
+                       retval = long_options[match].val;
+               if (idx)
+                       *idx = match;
+       }
+       return retval;
+#undef IDENTICAL_INTERPRETATION
+}
diff --git a/lib/nbsd_libc/stdlib/getsubopt.3 b/lib/nbsd_libc/stdlib/getsubopt.3
new file mode 100644 (file)
index 0000000..9a791cb
--- /dev/null
@@ -0,0 +1,148 @@
+.\"    $NetBSD: getsubopt.3,v 1.14 2009/11/17 15:02:08 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getsubopt.3        8.1 (Berkeley) 6/9/93
+.\"
+.Dd November 17, 2009
+.Dt GETSUBOPT 3
+.Os
+.Sh NAME
+.Nm getsubopt
+.Nd get sub options from an argument
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Vt extern char *suboptarg
+.Ft int
+.Fn getsubopt "char **optionp" "char * const *tokens" "char **valuep"
+.Sh DESCRIPTION
+The
+.Fn getsubopt
+function
+parses a string containing tokens delimited by one or more tab, space or
+comma
+.Pq Ql \&,
+characters.
+It is intended for use in parsing groups of option arguments provided
+as part of a utility command line.
+.Pp
+The argument
+.Fa optionp
+is a pointer to a pointer to the string.
+The argument
+.Fa tokens
+is a pointer to a
+.Dv NULL Ns -terminated
+array of pointers to strings.
+.Pp
+The
+.Fn getsubopt
+function
+returns the zero-based offset of the pointer in the
+.Fa tokens
+array referencing a string which matches the first token
+in the string, or \-1 if the string contains no tokens or
+.Fa tokens
+does not contain a matching string.
+.Pp
+If the token is of the form ``name=value'', the location referenced by
+.Fa valuep
+will be set to point to the start of the ``value'' portion of the token.
+.Pp
+On return from
+.Fn getsubopt ,
+.Fa optionp
+will be set to point to the start of the next token in the string,
+or the null at the end of the string if no more tokens are present.
+The external variable
+.Fa suboptarg
+will be set to point to the start of the current token, or
+.Dv NULL
+if no
+tokens were present.
+The argument
+.Fa valuep
+will be set to point to the ``value'' portion of the token, or
+.Dv NULL
+if no ``value'' portion was present.
+.Sh EXAMPLES
+.Bd -literal -compact
+char *tokens[] = {
+       #define ONE     0
+               "one",
+       #define TWO     1
+               "two",
+       NULL
+};
+
+\&...
+
+extern char *optarg, *suboptarg;
+char *options, *value;
+
+while ((ch = getopt(argc, argv, "ab:")) != \-1) {
+       switch(ch) {
+       case 'a':
+               /* process ``a'' option */
+               break;
+       case 'b':
+               options = optarg;
+               while (*options) {
+                       switch(getsubopt(\*[Am]options, tokens, \*[Am]value)) {
+                       case ONE:
+                               /* process ``one'' sub option */
+                               break;
+                       case TWO:
+                               /* process ``two'' sub option */
+                               if (!value)
+                                       error("no value for two");
+                               i = atoi(value);
+                               break;
+                       case \-1:
+                               if (suboptarg)
+                                       error("unknown sub option %s",
+                                         suboptarg);
+                               else
+                                       error("missing sub option");
+                               break;
+               }
+               break;
+       }
+.Ed
+.Sh SEE ALSO
+.Xr getopt 3 ,
+.Xr strsep 3
+.Sh HISTORY
+The
+.Fn getsubopt
+function first appeared in
+.Bx 4.4 ,
+and is included in
+.St -p1003.1-2008 .
diff --git a/lib/nbsd_libc/stdlib/getsubopt.c b/lib/nbsd_libc/stdlib/getsubopt.c
new file mode 100644 (file)
index 0000000..3590a67
--- /dev/null
@@ -0,0 +1,114 @@
+/*     $NetBSD: getsubopt.c,v 1.8 2004/05/09 19:34:11 kleink Exp $     */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)getsubopt.c        8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: getsubopt.c,v 1.8 2004/05/09 19:34:11 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(getsubopt,_getsubopt)
+#endif
+
+/*
+ * The SVID interface to getsubopt provides no way of figuring out which
+ * part of the suboptions list wasn't matched.  This makes error messages
+ * tricky...  The extern variable suboptarg is a pointer to the token
+ * which didn't match.
+ */
+char *suboptarg;
+
+int
+getsubopt(optionp, tokens, valuep)
+       char **optionp, **valuep;
+       char * const *tokens;
+{
+       int cnt;
+       char *p;
+
+       _DIAGASSERT(tokens != NULL);
+       _DIAGASSERT(valuep != NULL);
+       /* optionp is tested below */
+
+       suboptarg = *valuep = NULL;
+
+       if (!optionp || !*optionp)
+               return(-1);
+
+       /* skip leading white-space, commas */
+       for (p = *optionp; *p && (*p == ',' || *p == ' ' || *p == '\t'); ++p);
+
+       if (!*p) {
+               *optionp = p;
+               return(-1);
+       }
+
+       /* save the start of the token, and skip the rest of the token. */
+       for (suboptarg = p;
+           *++p && *p != ',' && *p != '=' && *p != ' ' && *p != '\t';);
+
+       if (*p) {
+               /*
+                * If there's an equals sign, set the value pointer, and
+                * skip over the value part of the token.  Terminate the
+                * token.
+                */
+               if (*p == '=') {
+                       *p = '\0';
+                       for (*valuep = ++p;
+                           *p && *p != ',' && *p != ' ' && *p != '\t'; ++p);
+                       if (*p) 
+                               *p++ = '\0';
+               } else
+                       *p++ = '\0';
+               /* Skip any whitespace or commas after this token. */
+               for (; *p && (*p == ',' || *p == ' ' || *p == '\t'); ++p);
+       }
+
+       /* set optionp for next round. */
+       *optionp = p;
+
+       for (cnt = 0; *tokens; ++tokens, ++cnt)
+               if (!strcmp(suboptarg, *tokens))
+                       return(cnt);
+       return(-1);
+}
diff --git a/lib/nbsd_libc/stdlib/grantpt.3 b/lib/nbsd_libc/stdlib/grantpt.3
new file mode 100644 (file)
index 0000000..6da0e90
--- /dev/null
@@ -0,0 +1,97 @@
+.\" $NetBSD: grantpt.3,v 1.4 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2004 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Christos Zoulas.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 25, 2004
+.Dt GRANTPT 3
+.Os
+.Sh NAME
+.Nm grantpt
+.Nd grant access to a slave pseudo-terminal device
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn grantpt "int fildes"
+.Sh DESCRIPTION
+The
+.Fn grantpt
+function changes the mode and ownership of the slave pseudo-terminal device
+that corresponds to the master pseudo-terminal device associated with
+.Fa fildes
+to be owned by the real user id of the calling process, group id of
+.Dv tty .
+The permissions are set to readable and writable by owner, and writable by
+group.
+If the slave pseudo-terminal device was being accessed by other file
+descriptors at the time, all such access will be revoked.
+.Sh RETURN VALUES
+If successful,
+.Fn grantpt
+returns 0; otherwise a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn grantpt
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCESS
+the corresponding pseudo-terminal device could not be accessed.
+.It Bq Er EBADF
+.Fa fildes
+is not a valid descriptor.
+.It Bq Er EINVAL
+.Fa fildes
+is not associated with a master pseudo-terminal device.
+.El
+.Sh NOTES
+Setting the group to
+.Dv tty
+and revoking accesses by other file descriptors are
+.Nx
+extensions.
+Calling
+.Fn grantpt
+is equivalent to:
+.Bd -literal
+       ioctl(fildes, TIOCGRANTPT, 0);
+.Ed
+.Sh SEE ALSO
+.Xr ioctl 2 ,
+.Xr posix_openpt 3 ,
+.Xr ptsname 3 ,
+.Xr unlockpt 3
+.Sh STANDARDS
+The
+.Fn grantpt
+function conforms to
+.St -p1003.1-2001 .
+Its first release was in
+.St -xpg4.2 .
diff --git a/lib/nbsd_libc/stdlib/hcreate.3 b/lib/nbsd_libc/stdlib/hcreate.3
new file mode 100644 (file)
index 0000000..0bc844f
--- /dev/null
@@ -0,0 +1,240 @@
+.\"    $NetBSD: hcreate.3,v 1.8 2010/05/01 06:18:03 jruoho Exp $
+.\"
+.\" Copyright (c) 1999 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 1, 2010
+.Dt HCREATE 3
+.Os
+.Sh NAME
+.Nm hcreate ,
+.Nm hdestroy ,
+.Nm hsearch
+.Nd manage hash search table
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In search.h
+.Ft int
+.Fn hcreate "size_t nel"
+.Ft void
+.Fn hdestroy "void"
+.Ft ENTRY *
+.Fn hsearch "ENTRY item" "ACTION action"
+.Sh DESCRIPTION
+The
+.Fn hcreate ,
+.Fn hdestroy
+and
+.Fn hsearch
+functions manage hash search tables.
+.Pp
+The
+.Fn hcreate
+function allocates and initializes the table.
+The
+.Fa nel
+argument specifies an estimate of the maximum number of entries to be held
+by the table.
+Unless further memory allocation fails, supplying an insufficient
+.Fa nel
+value will not result in functional harm, although a performance degradation
+may occur.
+Initialization using the
+.Fn hcreate
+function is mandatory prior to any access operations using
+.Fn hsearch .
+.Pp
+The
+.Fn hdestroy
+function destroys a table previously created using
+.Fn hcreate .
+After a call to
+.Fn hdestroy ,
+the data can no longer be accessed.
+.Pp
+The
+.Fn hsearch
+function is used to search to the hash table.
+It returns a pointer into the
+hash table indicating the address of an item.
+The
+.Fa item
+argument is of type
+.Vt ENTRY ,
+defined in the
+.In search.h
+header.
+This is a structure type that contains two pointers:
+.Pp
+.Bl -tag -compact -offset indent -width "void *data "
+.It Fa char *key
+comparison key
+.It Fa void *data
+pointer to data associated with
+.Fa key
+.El
+.Pp
+The key comparison function used by
+.Fn hsearch
+is
+.Xr strcmp 3 .
+.Pp
+The
+.Fa action
+argument is of type
+.Vt ACTION ,
+an enumeration type which defines the following values:
+.Bl -tag -offset indent -width ENTERXX
+.It Dv ENTER
+Insert
+.Fa item
+into the hash table.
+If an existing item with the same key is found, it is not replaced.
+Note that the
+.Fa key
+and
+.Fa data
+elements of
+.Fa item
+are used directly by the new table entry.
+The storage for the
+key must not be modified during the lifetime of the hash table.
+.It Dv FIND
+Search the hash table without inserting
+.Fa item .
+.El
+.Pp
+Note that the comparison
+.Fa key
+must be allocated using
+.Xr malloc 3
+or
+.Xr calloc 3
+if action is
+.Dv ENTER
+and
+.Fn hdestroy
+will be called.
+This is because
+.Fn hdestroy
+will call
+.Xr free 3
+for each comparison
+.Fa key
+(but not
+.Fa data ) .
+Typically the comparison
+.Fa key
+is allocated by using
+.Xr strdup 3 .
+.Sh RETURN VALUES
+If successful, the
+.Fn hcreate
+function returns a non-zero value.
+Otherwise, a value of 0 is returned and
+.Va errno
+is set to indicate the error.
+.Pp
+The
+.Fn hdestroy
+functions
+returns no value.
+.Pp
+If successful, the
+.Fn hsearch
+function returns a pointer to hash table entry matching
+the provided key.
+If the action is
+.Dv FIND
+and the item was not found, or if the action is
+.Dv ENTER
+and the insertion failed,
+.Dv NULL
+is returned and
+.Va errno
+is set to indicate the error.
+If the action is
+.Dv ENTER
+and an entry already existed in the table matching the given
+key, the existing entry is returned and is not replaced.
+.Sh ERRORS
+The
+.Fn hcreate
+and
+.Fn hsearch
+functions will fail if:
+.Bl -tag -width Er
+.It Bq Er ENOMEM
+Insufficient memory is available.
+.El
+.Sh SEE ALSO
+.Xr bsearch 3 ,
+.Xr lsearch 3 ,
+.Xr malloc 3 ,
+.Xr strcmp 3
+.Sh STANDARDS
+The
+.Fn hcreate ,
+.Fn hdestroy
+and
+.Fn hsearch
+functions conform to
+.St -xpg4.2 .
+.Sh HISTORY
+The
+.Fn hcreate ,
+.Fn hdestroy
+and
+.Fn hsearch
+functions first appeared in
+.At V .
+.Sh CAVEATS
+At least the following limitations can be mentioned:
+.Bl -bullet
+.It
+The interface permits the use of only one hash table at a time.
+.It
+Individual hash table entries can be added, but not deleted.
+.It
+The standard is indecipherable about the
+internal memory usage of the functions,
+mentioning only that
+.Do
+.Fn hcreate
+and
+.Fn hsearch
+functions may use
+.Fn malloc
+to allocate space
+.Dc .
+This limits the portability of the functions,
+given that other implementations may not
+.Xr free 3
+the buffer pointed by
+.Fa key .
+.El
diff --git a/lib/nbsd_libc/stdlib/hcreate.c b/lib/nbsd_libc/stdlib/hcreate.c
new file mode 100644 (file)
index 0000000..8f06fdf
--- /dev/null
@@ -0,0 +1,196 @@
+/* $NetBSD: hcreate.c,v 1.6 2008/07/21 12:05:43 lukem Exp $ */
+
+/*
+ * Copyright (c) 2001 Christopher G. Demetriou
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *          This product includes software developed for the
+ *          NetBSD Project.  See http://www.NetBSD.org/ for
+ *          information about NetBSD.
+ * 4. 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 ``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 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.
+ * 
+ * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+ */
+
+/*
+ * hcreate() / hsearch() / hdestroy()
+ *
+ * SysV/XPG4 hash table functions.
+ *
+ * Implementation done based on NetBSD manual page and Solaris manual page,
+ * plus my own personal experience about how they're supposed to work.
+ *
+ * I tried to look at Knuth (as cited by the Solaris manual page), but
+ * nobody had a copy in the office, so...
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: hcreate.c,v 1.6 2008/07/21 12:05:43 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(lint)
+__COPYRIGHT("@(#) Copyright (c) 2001\
+ Christopher G. Demetriou.  All rights reserved.");
+#endif /* not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <search.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/queue.h>
+
+/*
+ * DO NOT MAKE THIS STRUCTURE LARGER THAN 32 BYTES (4 ptrs on 64-bit
+ * ptr machine) without adjusting MAX_BUCKETS_LG2 below.
+ */
+struct internal_entry {
+       SLIST_ENTRY(internal_entry) link;
+       ENTRY ent;
+};
+SLIST_HEAD(internal_head, internal_entry);
+
+#define        MIN_BUCKETS_LG2 4
+#define        MIN_BUCKETS     (1 << MIN_BUCKETS_LG2)
+
+/*
+ * max * sizeof internal_entry must fit into size_t.
+ * assumes internal_entry is <= 32 (2^5) bytes.
+ */
+#define        MAX_BUCKETS_LG2 (sizeof (size_t) * 8 - 1 - 5)
+#define        MAX_BUCKETS     ((size_t)1 << MAX_BUCKETS_LG2)
+
+/* Default hash function, from db/hash/hash_func.c */
+extern u_int32_t (*__default_hash)(const void *, size_t);
+
+static struct internal_head *htable;
+static size_t htablesize;
+
+int
+hcreate(size_t nel)
+{
+       size_t idx;
+       unsigned int p2;
+
+       /* Make sure this isn't called when a table already exists. */
+       _DIAGASSERT(htable == NULL);
+       if (htable != NULL) {
+               errno = EINVAL;
+               return 0;
+       }
+
+       /* If nel is too small, make it min sized. */
+       if (nel < MIN_BUCKETS)
+               nel = MIN_BUCKETS;
+
+       /* If it's too large, cap it. */
+       if (nel > MAX_BUCKETS)
+               nel = MAX_BUCKETS;
+
+       /* If it's is not a power of two in size, round up. */
+       if ((nel & (nel - 1)) != 0) {
+               for (p2 = 0; nel != 0; p2++)
+                       nel >>= 1;
+               _DIAGASSERT(p2 <= MAX_BUCKETS_LG2);
+               nel = 1 << p2;
+       }
+       
+       /* Allocate the table. */
+       htablesize = nel;
+       htable = malloc(htablesize * sizeof htable[0]);
+       if (htable == NULL) {
+               errno = ENOMEM;
+               return 0;
+       }
+
+       /* Initialize it. */
+       for (idx = 0; idx < htablesize; idx++)
+               SLIST_INIT(&htable[idx]);
+
+       return 1;
+}
+
+void
+hdestroy(void)
+{
+       struct internal_entry *ie;
+       size_t idx;
+
+       _DIAGASSERT(htable != NULL);
+       if (htable == NULL)
+               return;
+
+       for (idx = 0; idx < htablesize; idx++) {
+               while (!SLIST_EMPTY(&htable[idx])) {
+                       ie = SLIST_FIRST(&htable[idx]);
+                       SLIST_REMOVE_HEAD(&htable[idx], link);
+                       free(ie->ent.key);
+                       free(ie);
+               }
+       }
+       free(htable);
+       htable = NULL;
+}
+
+ENTRY *
+hsearch(ENTRY item, ACTION action)
+{
+       struct internal_head *head;
+       struct internal_entry *ie;
+       uint32_t hashval;
+       size_t len;
+
+       _DIAGASSERT(htable != NULL);
+       _DIAGASSERT(item.key != NULL);
+       _DIAGASSERT(action == ENTER || action == FIND);
+
+       len = strlen(item.key);
+       hashval = (*__default_hash)(item.key, len);
+
+       head = &htable[hashval & (htablesize - 1)];
+       ie = SLIST_FIRST(head);
+       while (ie != NULL) {
+               if (strcmp(ie->ent.key, item.key) == 0)
+                       break;
+               ie = SLIST_NEXT(ie, link);
+       }
+
+       if (ie != NULL)
+               return &ie->ent;
+       else if (action == FIND)
+               return NULL;
+
+       ie = malloc(sizeof *ie);
+       if (ie == NULL)
+               return NULL;
+       ie->ent.key = item.key;
+       ie->ent.data = item.data;
+
+       SLIST_INSERT_HEAD(head, ie, link);
+       return &ie->ent;
+}
diff --git a/lib/nbsd_libc/stdlib/imaxabs.3 b/lib/nbsd_libc/stdlib/imaxabs.3
new file mode 100644 (file)
index 0000000..0f43026
--- /dev/null
@@ -0,0 +1,70 @@
+.\"    $NetBSD: imaxabs.3,v 1.2 2010/03/21 13:39:51 jruoho Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)labs.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd March 6, 2000
+.Dt IMAXABS 3
+.Os
+.Sh NAME
+.Nm imaxabs
+.Nd return the absolute value of a imaxint_t
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In inttypes.h
+.Ft intmax_t
+.Fn imaxabs "intmax_t i"
+.Sh DESCRIPTION
+The
+.Fn imaxabs
+function
+returns the absolute value of the
+.Vt imaxint_t
+integer
+.Ar j .
+.Sh SEE ALSO
+.Xr abs 3 ,
+.Xr cabs 3 ,
+.Xr floor 3 ,
+.Xr labs 3 ,
+.Xr llabs 3 ,
+.Xr math 3
+.Sh STANDARDS
+The
+.Fn imaxabs
+function
+conforms to
+.St -isoC-99 .
+.Sh BUGS
+The absolute value of the most negative integer remains negative.
diff --git a/lib/nbsd_libc/stdlib/imaxabs.c b/lib/nbsd_libc/stdlib/imaxabs.c
new file mode 100644 (file)
index 0000000..f7fe28c
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: imaxabs.c,v 1.1 2008/08/04 21:29:27 matt Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if !defined(lint)
+__RCSID("$NetBSD: imaxabs.c,v 1.1 2008/08/04 21:29:27 matt Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <inttypes.h>
+
+#ifdef __weak_alias
+__weak_alias(imaxabs, _imaxabs)
+#endif
+
+intmax_t
+imaxabs(intmax_t i)
+{
+       return i < 0 ? -i : i;
+}
diff --git a/lib/nbsd_libc/stdlib/imaxdiv.3 b/lib/nbsd_libc/stdlib/imaxdiv.3
new file mode 100644 (file)
index 0000000..ebfd7f1
--- /dev/null
@@ -0,0 +1,75 @@
+.\"    $NetBSD: imaxdiv.3,v 1.1 2008/08/04 21:29:27 matt Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)ldiv.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd March 6, 2000
+.Dt IMAXDIV 3
+.Os
+.Sh NAME
+.Nm imaxdiv
+.Nd return quotient and remainder from division
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In inttypes.h
+.Ft imaxdiv_t
+.Fn imaxdiv "intmax_t num" "intmax_t denom"
+.Sh DESCRIPTION
+The
+.Fn imaxdiv
+function
+divides
+.Ar num
+by
+.Ar denom
+and returns the resulting quotient and remainder in a structure named
+.Ar imaxdiv_t
+that contains two
+.Em imaxint_t
+members named
+.Ar quot
+and
+.Ar rem .
+.Sh SEE ALSO
+.Xr div 3 ,
+.Xr ldiv 3 ,
+.Xr lldiv 3 ,
+.Xr math 3 ,
+.Xr qdiv 3
+.Sh STANDARDS
+The
+.Fn imaxdiv
+function
+conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/stdlib/imaxdiv.c b/lib/nbsd_libc/stdlib/imaxdiv.c
new file mode 100644 (file)
index 0000000..f9e1dc1
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: imaxdiv.c,v 1.1 2008/08/04 21:29:27 matt Exp $ */
+
+/*
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  Aimax rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the foimaxowing conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the foimaxowing disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the foimaxowing disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "from: @(#)ldiv.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: imaxdiv.c,v 1.1 2008/08/04 21:29:27 matt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <inttypes.h>          /* imaxdiv_t */
+
+#ifdef __weak_alias
+__weak_alias(imaxdiv, _imaxdiv)
+#endif
+
+/* LONGLONG */
+imaxdiv_t
+imaxdiv(intmax_t num, intmax_t denom)
+{
+       imaxdiv_t r;
+
+       /* see div.c for comments */
+
+       r.quot = num / denom;
+       r.rem = num % denom;
+       if (num >= 0 && r.rem < 0) {
+               r.quot++;
+               r.rem -= denom;
+       }
+       return (r);
+}
diff --git a/lib/nbsd_libc/stdlib/insque.3 b/lib/nbsd_libc/stdlib/insque.3
new file mode 100644 (file)
index 0000000..fdb86b7
--- /dev/null
@@ -0,0 +1,80 @@
+.\" Copyright (c) 1993 John Brezak
+.\" 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.
+.\" 3. The name of the author may be used to endorse or promote products
+.\"    derived from this software without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR `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 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.
+.\"
+.\"    $NetBSD: insque.3,v 1.5 2010/04/30 10:24:02 jruoho Exp $
+.\"
+.Dd April 30, 2010
+.Dt INSQUE 3
+.Os
+.Sh NAME
+.Nm insque ,
+.Nm remque
+.Nd insert/remove element from a queue
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In search.h
+.Ft void
+.Fn insque "void *elem" "void *pred"
+.Ft void
+.Fn remque "void *elem"
+.Sh DESCRIPTION
+.Fn insque
+and
+.Fn remque
+manipulate queues built from doubly linked lists.
+The queue can be either circular or linear.
+The functions expect their
+arguments to point to a structure whose first and second members are
+pointers to the next and previous element, respectively.
+The
+.Fn insque
+function also allows the
+.Fa pred
+argument to be a
+.Dv NULL
+pointer for the initialization of a new linear list's
+head element.
+.Sh STANDARDS
+The
+.Fn insque
+and
+.Fn remque
+functions conform to
+.St -p1003.1-2001 .
+.Sh HISTORY
+The
+.Fn insque
+and
+.Fn remque
+are derived from the
+.Sq insque
+and
+.Sq remque
+instructions on the
+.Tn VAX .
+They first appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/stdlib/insque.c b/lib/nbsd_libc/stdlib/insque.c
new file mode 100644 (file)
index 0000000..20633e8
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ *  Copyright (c) 1993 John Brezak
+ *  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.
+ *  3. The name of the author may be used to endorse or promote products
+ *     derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: insque.c,v 1.2 2005/07/06 17:17:15 drochner Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <search.h>
+
+struct qelem {
+        struct qelem *q_forw;
+        struct qelem *q_back;
+};
+
+void
+insque(entry, pred)
+       void *entry;
+       void *pred;
+{
+       struct qelem *e = (struct qelem *) entry;
+       struct qelem *p = (struct qelem *) pred;
+
+       _DIAGASSERT(e != 0);
+
+       e->q_back = p;
+       if (p) {
+               e->q_forw = p->q_forw;
+               if (p->q_forw)
+                       p->q_forw->q_back = e;
+               p->q_forw = e;
+       } else
+               e->q_forw = 0;
+}
diff --git a/lib/nbsd_libc/stdlib/jemalloc.3 b/lib/nbsd_libc/stdlib/jemalloc.3
new file mode 100644 (file)
index 0000000..524448a
--- /dev/null
@@ -0,0 +1,385 @@
+.\" $NetBSD $
+.\"
+.\" Copyright (c) 1980, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)malloc.3   8.1 (Berkeley) 6/4/93
+.\" $FreeBSD: src/lib/libc/stdlib/malloc.3,v 1.73 2007/06/15 22:32:33 jasone Exp $
+.\"
+.Dd May 14, 2010
+.Os
+.Dt JEMALLOC 3
+.Sh NAME
+.Nm jemalloc
+.Nd the default system allocator
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.Ft const char *
+.Va _malloc_options ;
+.Sh DESCRIPTION
+The
+.Nm
+is a general-purpose concurrent
+.Xr malloc 3
+implementation specifically designed to be scalable
+on modern multi-processor systems.
+It is the default user space system allocator in
+.Nx .
+.Pp
+When the first call is made to one of the memory allocation
+routines such as
+.Fn malloc
+or
+.Fn realloc ,
+various flags that affect the workings of the allocator are set or reset.
+These are described below.
+.Pp
+The
+.Dq name
+of the file referenced by the symbolic link named
+.Pa /etc/malloc.conf ,
+the value of the environment variable
+.Ev MALLOC_OPTIONS ,
+and the string pointed to by the global variable
+.Va _malloc_options
+will be interpreted, in that order, character by character as flags.
+.Pp
+Most flags are single letters.
+Uppercase letters indicate that the behavior is set, or on,
+and lowercase letters mean that the behavior is not set, or off.
+The following options are available.
+.Bl -tag -width "A   " -offset 3n
+.It Em A
+All warnings (except for the warning about unknown
+flags being set) become fatal.
+The process will call
+.Xr abort 3
+in these cases.
+.It Em H
+Use
+.Xr madvise 2
+when pages within a chunk are no longer in use, but the chunk as a whole cannot
+yet be deallocated.
+This is primarily of use when swapping is a real possibility, due to the high
+overhead of the
+.Fn madvise
+system call.
+.It Em J
+Each byte of new memory allocated by
+.Fn malloc ,
+.Fn realloc
+will be initialized to 0xa5.
+All memory returned by
+.Fn free ,
+.Fn realloc
+will be initialized to 0x5a.
+This is intended for debugging and will impact performance negatively.
+.It Em K
+Increase/decrease the virtual memory chunk size by a factor of two.
+The default chunk size is 1 MB.
+This option can be specified multiple times.
+.It Em N
+Increase/decrease the number of arenas by a factor of two.
+The default number of arenas is four times the number of CPUs, or one if there
+is a single CPU.
+This option can be specified multiple times.
+.It Em P
+Various statistics are printed at program exit via an
+.Xr atexit 3
+function.
+This has the potential to cause deadlock for a multi-threaded process that exits
+while one or more threads are executing in the memory allocation functions.
+Therefore, this option should only be used with care; it is primarily intended
+as a performance tuning aid during application development.
+.It Em Q
+Increase/decrease the size of the allocation quantum by a factor of two.
+The default quantum is the minimum allowed by the architecture (typically 8 or
+16 bytes).
+This option can be specified multiple times.
+.It Em S
+Increase/decrease the size of the maximum size class that is a multiple of the
+quantum by a factor of two.
+Above this size, power-of-two spacing is used for size classes.
+The default value is 512 bytes.
+This option can be specified multiple times.
+.It Em U
+Generate
+.Dq utrace
+entries for
+.Xr ktrace 1 ,
+for all operations.
+Consult the source for details on this option.
+.It Em V
+Attempting to allocate zero bytes will return a
+.Dv NULL
+pointer instead of a valid pointer.
+(The default behavior is to make a minimal allocation and return a
+pointer to it.)
+This option is provided for System V compatibility.
+This option is incompatible with the
+.Em X
+option.
+.It Em X
+Rather than return failure for any allocation function,
+display a diagnostic message on
+.Dv stderr
+and cause the program to drop
+core (using
+.Xr abort 3 ) .
+This option should be set at compile time by including the following in
+the source code:
+.Bd -literal -offset indent
+_malloc_options = "X";
+.Ed
+.Pp
+.It Em Z
+Each byte of new memory allocated by
+.Fn malloc ,
+.Fn realloc
+will be initialized to 0.
+Note that this initialization only happens once for each byte, so
+.Fn realloc
+does not zero memory that was previously allocated.
+This is intended for debugging and will impact performance negatively.
+.El
+.Pp
+The
+.Em J
+and
+.Em Z
+options are intended for testing and debugging.
+An application which changes its behavior when these options are used
+is flawed.
+.Sh IMPLEMENTATION NOTES
+The
+.Nm
+allocator uses multiple arenas in order to reduce lock
+contention for threaded programs on multi-processor systems.
+This works well with regard to threading scalability, but incurs some costs.
+There is a small fixed per-arena overhead, and additionally, arenas manage
+memory completely independently of each other, which means a small fixed
+increase in overall memory fragmentation.
+These overheads are not generally an issue,
+given the number of arenas normally used.
+Note that using substantially more arenas than the default is not likely to
+improve performance, mainly due to reduced cache performance.
+However, it may make sense to reduce the number of arenas if an application
+does not make much use of the allocation functions.
+.Pp
+Memory is conceptually broken into equal-sized chunks,
+where the chunk size is a power of two that is greater than the page size.
+Chunks are always aligned to multiples of the chunk size.
+This alignment makes it possible to find
+metadata for user objects very quickly.
+.Pp
+User objects are broken into three categories according to size:
+.Bl -enum -offset 3n
+.It
+Small objects are smaller than one page.
+.It
+Large objects are smaller than the chunk size.
+.It
+Huge objects are a multiple of the chunk size.
+.El
+.Pp
+Small and large objects are managed by arenas; huge objects are managed
+separately in a single data structure that is shared by all threads.
+Huge objects are used by applications infrequently enough that this single
+data structure is not a scalability issue.
+.Pp
+Each chunk that is managed by an arena tracks its contents in a page map as
+runs of contiguous pages (unused, backing a set of small objects, or backing
+one large object).
+The combination of chunk alignment and chunk page maps makes it possible to
+determine all metadata regarding small and large allocations in constant time.
+.Pp
+Small objects are managed in groups by page runs.
+Each run maintains a bitmap that tracks which regions are in use.
+Allocation requests can be grouped as follows.
+.Pp
+.Bl -bullet -offset 3n
+.It
+Allocation requests that are no more than half the quantum (see the
+.Em Q
+option) are rounded up to the nearest power of two (typically 2, 4, or 8).
+.It
+Allocation requests that are more than half the quantum, but no more than the
+maximum quantum-multiple size class (see the
+.Em S
+option) are rounded up to the nearest multiple of the quantum.
+.It
+Allocation requests that are larger than the maximum quantum-multiple size
+class, but no larger than one half of a page, are rounded up to the nearest
+power of two.
+.It
+Allocation requests that are larger than half of a page, but small enough to
+fit in an arena-managed chunk (see the
+.Em K
+option), are rounded up to the nearest run size.
+.It
+Allocation requests that are too large to fit in an arena-managed chunk are
+rounded up to the nearest multiple of the chunk size.
+.El
+.Pp
+Allocations are packed tightly together, which can be an issue for
+multi-threaded applications.
+If you need to assure that allocations do not suffer from cache line sharing,
+round your allocation requests up to the nearest multiple of the cache line
+size.
+.Sh DEBUGGING
+The first thing to do is to set the
+.Em A
+option.
+This option forces a coredump (if possible) at the first sign of trouble,
+rather than the normal policy of trying to continue if at all possible.
+.Pp
+It is probably also a good idea to recompile the program with suitable
+options and symbols for debugger support.
+.Pp
+If the program starts to give unusual results, coredump or generally behave
+differently without emitting any of the messages mentioned in the next
+section, it is likely because it depends on the storage being filled with
+zero bytes.
+Try running it with the
+.Em Z
+option set;
+if that improves the situation, this diagnosis has been confirmed.
+If the program still misbehaves,
+the likely problem is accessing memory outside the allocated area.
+.Pp
+Alternatively, if the symptoms are not easy to reproduce, setting the
+.Em J
+option may help provoke the problem.
+In truly difficult cases, the
+.Em U
+option, if supported by the kernel, can provide a detailed trace of
+all calls made to these functions.
+.Pp
+Unfortunately,
+.Nm
+does not provide much detail about the problems it detects;
+the performance impact for storing such information would be prohibitive.
+There are a number of allocator implementations available on the Internet
+which focus on detecting and pinpointing problems by trading performance for
+extra sanity checks and detailed diagnostics.
+.Sh DIAGNOSTICS
+If any of the memory allocation/deallocation functions detect an error or
+warning condition, a message will be printed to file descriptor
+.Dv STDERR_FILENO .
+Errors will result in the process dumping core.
+If the
+.Em A
+option is set, all warnings are treated as errors.
+.Pp
+.\"
+.\" XXX: The _malloc_message should be documented
+.\"     better in order to be worth mentioning.
+.\"
+The
+.Va _malloc_message
+variable allows the programmer to override the function which emits
+the text strings forming the errors and warnings if for some reason
+the
+.Dv stderr
+file descriptor is not suitable for this.
+Please note that doing anything which tries to allocate memory in
+this function is likely to result in a crash or deadlock.
+.Pp
+All messages are prefixed by
+.Dq Ao Ar progname Ac Ns Li \&: Pq malloc .
+.Sh ENVIRONMENT
+The following environment variables affect the execution of the allocation
+functions:
+.Bl -tag -width ".Ev MALLOC_OPTIONS"
+.It Ev MALLOC_OPTIONS
+If the environment variable
+.Ev MALLOC_OPTIONS
+is set, the characters it contains will be interpreted as flags to the
+allocation functions.
+.El
+.Sh EXAMPLES
+To dump core whenever a problem occurs:
+.Pp
+.Bd -literal -offset indent
+ln -s 'A' /etc/malloc.conf
+.Ed
+.Pp
+To specify in the source that a program does no return value checking
+on calls to these functions:
+.Bd -literal -offset indent
+_malloc_options = "X";
+.Ed
+.Sh SEE ALSO
+.Xr emalloc 3 ,
+.Xr malloc 3 ,
+.Xr memory 3 ,
+.Xr memoryallocators 9
+.\"
+.\" XXX: Add more references that could be worth reading.
+.\"
+.Rs
+.%A Jason Evans
+.%T "A Scalable Concurrent malloc(3) Implementation for FreeBSD"
+.%D April 16, 2006
+.%O BSDCan 2006
+.%U http://people.freebsd.org/~jasone/jemalloc/bsdcan2006/jemalloc.pdf
+.Re
+.Rs
+.%A Poul-Henning Kamp
+.%T "Malloc(3) revisited"
+.%I USENIX Association
+.%B Proceedings of the FREENIX Track: 1998 USENIX Annual Technical Conference
+.%D June 15-19, 1998
+.%U http://www.usenix.org/publications/library/proceedings/usenix98/freenix/kamp.pdf
+.Re
+.Rs
+.%A Paul R. Wilson
+.%A Mark S. Johnstone
+.%A Michael Neely
+.%A David Boles
+.%T "Dynamic Storage Allocation: A Survey and Critical Review"
+.%D 1995
+.%I University of Texas at Austin
+.%U ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps
+.Re
+.Sh HISTORY
+The
+.Nm
+allocator became the default system allocator first in
+.Fx 7.0
+and then in
+.Nx 5.0 .
+In both systems it replaced the older so-called
+.Dq phkmalloc
+implementation.
+.Sh AUTHORS
+.An Jason Evans Aq jasone@canonware.com
diff --git a/lib/nbsd_libc/stdlib/jemalloc.c b/lib/nbsd_libc/stdlib/jemalloc.c
new file mode 100644 (file)
index 0000000..d01327a
--- /dev/null
@@ -0,0 +1,3941 @@
+/*     $NetBSD: jemalloc.c,v 1.21 2010/03/04 22:48:31 enami Exp $      */
+
+/*-
+ * Copyright (C) 2006,2007 Jason Evans <jasone@FreeBSD.org>.
+ * 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(s), this list of conditions and the following disclaimer as
+ *    the first lines of this file unmodified other than the possible
+ *    addition of one or more copyright notices.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice(s), 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 COPYRIGHT HOLDER(S) ``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 HOLDER(S) 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.
+ *
+ *******************************************************************************
+ *
+ * This allocator implementation is designed to provide scalable performance
+ * for multi-threaded programs on multi-processor systems.  The following
+ * features are included for this purpose:
+ *
+ *   + Multiple arenas are used if there are multiple CPUs, which reduces lock
+ *     contention and cache sloshing.
+ *
+ *   + Cache line sharing between arenas is avoided for internal data
+ *     structures.
+ *
+ *   + Memory is managed in chunks and runs (chunks can be split into runs),
+ *     rather than as individual pages.  This provides a constant-time
+ *     mechanism for associating allocations with particular arenas.
+ *
+ * Allocation requests are rounded up to the nearest size class, and no record
+ * of the original request size is maintained.  Allocations are broken into
+ * categories according to size class.  Assuming runtime defaults, 4 kB pages
+ * and a 16 byte quantum, the size classes in each category are as follows:
+ *
+ *   |=====================================|
+ *   | Category | Subcategory    |    Size |
+ *   |=====================================|
+ *   | Small    | Tiny           |       2 |
+ *   |          |                |       4 |
+ *   |          |                |       8 |
+ *   |          |----------------+---------|
+ *   |          | Quantum-spaced |      16 |
+ *   |          |                |      32 |
+ *   |          |                |      48 |
+ *   |          |                |     ... |
+ *   |          |                |     480 |
+ *   |          |                |     496 |
+ *   |          |                |     512 |
+ *   |          |----------------+---------|
+ *   |          | Sub-page       |    1 kB |
+ *   |          |                |    2 kB |
+ *   |=====================================|
+ *   | Large                     |    4 kB |
+ *   |                           |    8 kB |
+ *   |                           |   12 kB |
+ *   |                           |     ... |
+ *   |                           | 1012 kB |
+ *   |                           | 1016 kB |
+ *   |                           | 1020 kB |
+ *   |=====================================|
+ *   | Huge                      |    1 MB |
+ *   |                           |    2 MB |
+ *   |                           |    3 MB |
+ *   |                           |     ... |
+ *   |=====================================|
+ *
+ * A different mechanism is used for each category:
+ *
+ *   Small : Each size class is segregated into its own set of runs.  Each run
+ *           maintains a bitmap of which regions are free/allocated.
+ *
+ *   Large : Each allocation is backed by a dedicated run.  Metadata are stored
+ *           in the associated arena chunk header maps.
+ *
+ *   Huge : Each allocation is backed by a dedicated contiguous set of chunks.
+ *          Metadata are stored in a separate red-black tree.
+ *
+ *******************************************************************************
+ */
+
+/* LINTLIBRARY */
+
+#ifdef __NetBSD__
+#  define xutrace(a, b)                utrace("malloc", (a), (b))
+#  define __DECONST(x, y)      ((x)__UNCONST(y))
+#  define NO_TLS
+#else
+#  define xutrace(a, b)                utrace((a), (b))
+#endif /* __NetBSD__ */
+
+/*
+ * MALLOC_PRODUCTION disables assertions and statistics gathering.  It also
+ * defaults the A and J runtime options to off.  These settings are appropriate
+ * for production systems.
+ */
+#define MALLOC_PRODUCTION
+
+#ifndef MALLOC_PRODUCTION
+#  define MALLOC_DEBUG
+#endif
+
+#include <sys/cdefs.h>
+/* __FBSDID("$FreeBSD: src/lib/libc/stdlib/malloc.c,v 1.147 2007/06/15 22:00:16 jasone Exp $"); */ 
+__RCSID("$NetBSD: jemalloc.c,v 1.21 2010/03/04 22:48:31 enami Exp $");
+
+#ifdef __FreeBSD__
+#include "libc_private.h"
+#ifdef MALLOC_DEBUG
+#  define _LOCK_DEBUG
+#endif
+#include "spinlock.h"
+#endif
+#include "namespace.h"
+#include <sys/mman.h>
+#include <sys/param.h>
+#ifdef __FreeBSD__
+#include <sys/stddef.h>
+#endif
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/sysctl.h>
+#include <sys/tree.h>
+#include <sys/uio.h>
+#include <sys/ktrace.h> /* Must come after several other sys/ includes. */
+
+#ifdef __FreeBSD__
+#include <machine/atomic.h>
+#include <machine/cpufunc.h>
+#endif
+#include <machine/vmparam.h>
+
+#include <errno.h>
+#include <limits.h>
+#include <pthread.h>
+#include <sched.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <unistd.h>
+
+#ifdef __NetBSD__
+#  include <reentrant.h>
+#  include "extern.h"
+
+#define STRERROR_R(a, b, c)    __strerror_r(a, b, c);
+/*
+ * A non localized version of strerror, that avoids bringing in
+ * stdio and the locale code. All the malloc messages are in English
+ * so why bother?
+ */
+static int
+__strerror_r(int e, char *s, size_t l)
+{
+       int rval;
+       size_t slen;
+
+       if (e >= 0 && e < sys_nerr) {
+               slen = strlcpy(s, sys_errlist[e], l);
+               rval = 0;
+       } else {
+               slen = snprintf_ss(s, l, "Unknown error %u", e);
+               rval = EINVAL;
+       }
+       return slen >= l ? ERANGE : rval;
+}
+#endif
+
+#ifdef __FreeBSD__
+#define STRERROR_R(a, b, c)    strerror_r(a, b, c);
+#include "un-namespace.h"
+#endif
+
+/* MALLOC_STATS enables statistics calculation. */
+#ifndef MALLOC_PRODUCTION
+#  define MALLOC_STATS
+#endif
+
+#ifdef MALLOC_DEBUG
+#  ifdef NDEBUG
+#    undef NDEBUG
+#  endif
+#else
+#  ifndef NDEBUG
+#    define NDEBUG
+#  endif
+#endif
+#include <assert.h>
+
+#ifdef MALLOC_DEBUG
+   /* Disable inlining to make debugging easier. */
+#  define inline
+#endif
+
+/* Size of stack-allocated buffer passed to strerror_r(). */
+#define        STRERROR_BUF            64
+
+/* Minimum alignment of allocations is 2^QUANTUM_2POW_MIN bytes. */
+#ifdef __i386__
+#  define QUANTUM_2POW_MIN     4
+#  define SIZEOF_PTR_2POW      2
+#  define USE_BRK
+#endif
+#ifdef __ia64__
+#  define QUANTUM_2POW_MIN     4
+#  define SIZEOF_PTR_2POW      3
+#endif
+#ifdef __alpha__
+#  define QUANTUM_2POW_MIN     4
+#  define SIZEOF_PTR_2POW      3
+#  define NO_TLS
+#endif
+#ifdef __sparc64__
+#  define QUANTUM_2POW_MIN     4
+#  define SIZEOF_PTR_2POW      3
+#  define NO_TLS
+#endif
+#ifdef __amd64__
+#  define QUANTUM_2POW_MIN     4
+#  define SIZEOF_PTR_2POW      3
+#endif
+#ifdef __arm__
+#  define QUANTUM_2POW_MIN     3
+#  define SIZEOF_PTR_2POW      2
+#  define USE_BRK
+#  define NO_TLS
+#endif
+#ifdef __powerpc__
+#  define QUANTUM_2POW_MIN     4
+#  define SIZEOF_PTR_2POW      2
+#  define USE_BRK
+#endif
+#if defined(__sparc__) && !defined(__sparc64__)
+#  define QUANTUM_2POW_MIN     4
+#  define SIZEOF_PTR_2POW      2
+#  define USE_BRK
+#endif
+#ifdef __vax__
+#  define QUANTUM_2POW_MIN     4
+#  define SIZEOF_PTR_2POW      2
+#  define USE_BRK
+#endif
+#ifdef __sh__
+#  define QUANTUM_2POW_MIN     4
+#  define SIZEOF_PTR_2POW      2
+#  define USE_BRK
+#endif
+#ifdef __m68k__
+#  define QUANTUM_2POW_MIN     4
+#  define SIZEOF_PTR_2POW      2
+#  define USE_BRK
+#endif
+#ifdef __mips__
+#  define QUANTUM_2POW_MIN     4
+#  define SIZEOF_PTR_2POW      2
+#  define USE_BRK
+#endif
+#ifdef __hppa__                                                                                                                                         
+#  define QUANTUM_2POW_MIN     4                                                                                                                        
+#  define SIZEOF_PTR_2POW      2                                                                                                                        
+#  define USE_BRK                                                                                                                                       
+#endif           
+
+#define        SIZEOF_PTR              (1 << SIZEOF_PTR_2POW)
+
+/* sizeof(int) == (1 << SIZEOF_INT_2POW). */
+#ifndef SIZEOF_INT_2POW
+#  define SIZEOF_INT_2POW      2
+#endif
+
+/* We can't use TLS in non-PIC programs, since TLS relies on loader magic. */
+#if (!defined(PIC) && !defined(NO_TLS))
+#  define NO_TLS
+#endif
+
+/*
+ * Size and alignment of memory chunks that are allocated by the OS's virtual
+ * memory system.
+ */
+#define        CHUNK_2POW_DEFAULT      20
+
+/*
+ * Maximum size of L1 cache line.  This is used to avoid cache line aliasing,
+ * so over-estimates are okay (up to a point), but under-estimates will
+ * negatively affect performance.
+ */
+#define        CACHELINE_2POW          6
+#define        CACHELINE               ((size_t)(1 << CACHELINE_2POW))
+
+/* Smallest size class to support. */
+#define        TINY_MIN_2POW           1
+
+/*
+ * Maximum size class that is a multiple of the quantum, but not (necessarily)
+ * a power of 2.  Above this size, allocations are rounded up to the nearest
+ * power of 2.
+ */
+#define        SMALL_MAX_2POW_DEFAULT  9
+#define        SMALL_MAX_DEFAULT       (1 << SMALL_MAX_2POW_DEFAULT)
+
+/*
+ * Maximum desired run header overhead.  Runs are sized as small as possible
+ * such that this setting is still honored, without violating other constraints.
+ * The goal is to make runs as small as possible without exceeding a per run
+ * external fragmentation threshold.
+ *
+ * Note that it is possible to set this low enough that it cannot be honored
+ * for some/all object sizes, since there is one bit of header overhead per
+ * object (plus a constant).  In such cases, this constraint is relaxed.
+ *
+ * RUN_MAX_OVRHD_RELAX specifies the maximum number of bits per region of
+ * overhead for which RUN_MAX_OVRHD is relaxed.
+ */
+#define RUN_MAX_OVRHD          0.015
+#define RUN_MAX_OVRHD_RELAX    1.5
+
+/* Put a cap on small object run size.  This overrides RUN_MAX_OVRHD. */
+#define RUN_MAX_SMALL_2POW     15
+#define RUN_MAX_SMALL          (1 << RUN_MAX_SMALL_2POW)
+
+/******************************************************************************/
+
+#ifdef __FreeBSD__
+/*
+ * Mutexes based on spinlocks.  We can't use normal pthread mutexes, because
+ * they require malloc()ed memory.
+ */
+typedef struct {
+       spinlock_t      lock;
+} malloc_mutex_t;
+
+/* Set to true once the allocator has been initialized. */
+static bool malloc_initialized = false;
+
+/* Used to avoid initialization races. */
+static malloc_mutex_t init_lock = {_SPINLOCK_INITIALIZER};
+#else
+#define        malloc_mutex_t  mutex_t
+
+/* Set to true once the allocator has been initialized. */
+static bool malloc_initialized = false;
+
+/* Used to avoid initialization races. */
+static mutex_t init_lock = MUTEX_INITIALIZER;
+#endif
+
+/******************************************************************************/
+/*
+ * Statistics data structures.
+ */
+
+#ifdef MALLOC_STATS
+
+typedef struct malloc_bin_stats_s malloc_bin_stats_t;
+struct malloc_bin_stats_s {
+       /*
+        * Number of allocation requests that corresponded to the size of this
+        * bin.
+        */
+       uint64_t        nrequests;
+
+       /* Total number of runs created for this bin's size class. */
+       uint64_t        nruns;
+
+       /*
+        * Total number of runs reused by extracting them from the runs tree for
+        * this bin's size class.
+        */
+       uint64_t        reruns;
+
+       /* High-water mark for this bin. */
+       unsigned long   highruns;
+
+       /* Current number of runs in this bin. */
+       unsigned long   curruns;
+};
+
+typedef struct arena_stats_s arena_stats_t;
+struct arena_stats_s {
+       /* Number of bytes currently mapped. */
+       size_t          mapped;
+
+       /* Per-size-category statistics. */
+       size_t          allocated_small;
+       uint64_t        nmalloc_small;
+       uint64_t        ndalloc_small;
+
+       size_t          allocated_large;
+       uint64_t        nmalloc_large;
+       uint64_t        ndalloc_large;
+};
+
+typedef struct chunk_stats_s chunk_stats_t;
+struct chunk_stats_s {
+       /* Number of chunks that were allocated. */
+       uint64_t        nchunks;
+
+       /* High-water mark for number of chunks allocated. */
+       unsigned long   highchunks;
+
+       /*
+        * Current number of chunks allocated.  This value isn't maintained for
+        * any other purpose, so keep track of it in order to be able to set
+        * highchunks.
+        */
+       unsigned long   curchunks;
+};
+
+#endif /* #ifdef MALLOC_STATS */
+
+/******************************************************************************/
+/*
+ * Chunk data structures.
+ */
+
+/* Tree of chunks. */
+typedef struct chunk_node_s chunk_node_t;
+struct chunk_node_s {
+       /* Linkage for the chunk tree. */
+       RB_ENTRY(chunk_node_s) link;
+
+       /*
+        * Pointer to the chunk that this tree node is responsible for.  In some
+        * (but certainly not all) cases, this data structure is placed at the
+        * beginning of the corresponding chunk, so this field may point to this
+        * node.
+        */
+       void    *chunk;
+
+       /* Total chunk size. */
+       size_t  size;
+};
+typedef struct chunk_tree_s chunk_tree_t;
+RB_HEAD(chunk_tree_s, chunk_node_s);
+
+/******************************************************************************/
+/*
+ * Arena data structures.
+ */
+
+typedef struct arena_s arena_t;
+typedef struct arena_bin_s arena_bin_t;
+
+typedef struct arena_chunk_map_s arena_chunk_map_t;
+struct arena_chunk_map_s {
+       /* Number of pages in run. */
+       uint32_t        npages;
+       /*
+        * Position within run.  For a free run, this is POS_FREE for the first
+        * and last pages.  The POS_FREE special value makes it possible to
+        * quickly coalesce free runs.
+        *
+        * This is the limiting factor for chunksize; there can be at most 2^31
+        * pages in a run.
+        */
+#define POS_FREE ((uint32_t)0xffffffffU)
+       uint32_t        pos;
+};
+
+/* Arena chunk header. */
+typedef struct arena_chunk_s arena_chunk_t;
+struct arena_chunk_s {
+       /* Arena that owns the chunk. */
+       arena_t *arena;
+
+       /* Linkage for the arena's chunk tree. */
+       RB_ENTRY(arena_chunk_s) link;
+
+       /*
+        * Number of pages in use.  This is maintained in order to make
+        * detection of empty chunks fast.
+        */
+       uint32_t pages_used;
+
+       /*
+        * Every time a free run larger than this value is created/coalesced,
+        * this value is increased.  The only way that the value decreases is if
+        * arena_run_alloc() fails to find a free run as large as advertised by
+        * this value.
+        */
+       uint32_t max_frun_npages;
+
+       /*
+        * Every time a free run that starts at an earlier page than this value
+        * is created/coalesced, this value is decreased.  It is reset in a
+        * similar fashion to max_frun_npages.
+        */
+       uint32_t min_frun_ind;
+
+       /*
+        * Map of pages within chunk that keeps track of free/large/small.  For
+        * free runs, only the map entries for the first and last pages are
+        * kept up to date, so that free runs can be quickly coalesced.
+        */
+       arena_chunk_map_t map[1]; /* Dynamically sized. */
+};
+typedef struct arena_chunk_tree_s arena_chunk_tree_t;
+RB_HEAD(arena_chunk_tree_s, arena_chunk_s);
+
+typedef struct arena_run_s arena_run_t;
+struct arena_run_s {
+       /* Linkage for run trees. */
+       RB_ENTRY(arena_run_s) link;
+
+#ifdef MALLOC_DEBUG
+       uint32_t        magic;
+#  define ARENA_RUN_MAGIC 0x384adf93
+#endif
+
+       /* Bin this run is associated with. */
+       arena_bin_t     *bin;
+
+       /* Index of first element that might have a free region. */
+       unsigned        regs_minelm;
+
+       /* Number of free regions in run. */
+       unsigned        nfree;
+
+       /* Bitmask of in-use regions (0: in use, 1: free). */
+       unsigned        regs_mask[1]; /* Dynamically sized. */
+};
+typedef struct arena_run_tree_s arena_run_tree_t;
+RB_HEAD(arena_run_tree_s, arena_run_s);
+
+struct arena_bin_s {
+       /*
+        * Current run being used to service allocations of this bin's size
+        * class.
+        */
+       arena_run_t     *runcur;
+
+       /*
+        * Tree of non-full runs.  This tree is used when looking for an
+        * existing run when runcur is no longer usable.  We choose the
+        * non-full run that is lowest in memory; this policy tends to keep
+        * objects packed well, and it can also help reduce the number of
+        * almost-empty chunks.
+        */
+       arena_run_tree_t runs;
+
+       /* Size of regions in a run for this bin's size class. */
+       size_t          reg_size;
+
+       /* Total size of a run for this bin's size class. */
+       size_t          run_size;
+
+       /* Total number of regions in a run for this bin's size class. */
+       uint32_t        nregs;
+
+       /* Number of elements in a run's regs_mask for this bin's size class. */
+       uint32_t        regs_mask_nelms;
+
+       /* Offset of first region in a run for this bin's size class. */
+       uint32_t        reg0_offset;
+
+#ifdef MALLOC_STATS
+       /* Bin statistics. */
+       malloc_bin_stats_t stats;
+#endif
+};
+
+struct arena_s {
+#ifdef MALLOC_DEBUG
+       uint32_t                magic;
+#  define ARENA_MAGIC 0x947d3d24
+#endif
+
+       /* All operations on this arena require that mtx be locked. */
+       malloc_mutex_t          mtx;
+
+#ifdef MALLOC_STATS
+       arena_stats_t           stats;
+#endif
+
+       /*
+        * Tree of chunks this arena manages.
+        */
+       arena_chunk_tree_t      chunks;
+
+       /*
+        * In order to avoid rapid chunk allocation/deallocation when an arena
+        * oscillates right on the cusp of needing a new chunk, cache the most
+        * recently freed chunk.  This caching is disabled by opt_hint.
+        *
+        * There is one spare chunk per arena, rather than one spare total, in
+        * order to avoid interactions between multiple threads that could make
+        * a single spare inadequate.
+        */
+       arena_chunk_t *spare;
+
+       /*
+        * bins is used to store rings of free regions of the following sizes,
+        * assuming a 16-byte quantum, 4kB pagesize, and default MALLOC_OPTIONS.
+        *
+        *   bins[i] | size |
+        *   --------+------+
+        *        0  |    2 |
+        *        1  |    4 |
+        *        2  |    8 |
+        *   --------+------+
+        *        3  |   16 |
+        *        4  |   32 |
+        *        5  |   48 |
+        *        6  |   64 |
+        *           :      :
+        *           :      :
+        *       33  |  496 |
+        *       34  |  512 |
+        *   --------+------+
+        *       35  | 1024 |
+        *       36  | 2048 |
+        *   --------+------+
+        */
+       arena_bin_t             bins[1]; /* Dynamically sized. */
+};
+
+/******************************************************************************/
+/*
+ * Data.
+ */
+
+/* Number of CPUs. */
+static unsigned                ncpus;
+
+/* VM page size. */
+static size_t          pagesize;
+static size_t          pagesize_mask;
+static int             pagesize_2pow;
+
+/* Various bin-related settings. */
+static size_t          bin_maxclass; /* Max size class for bins. */
+static unsigned                ntbins; /* Number of (2^n)-spaced tiny bins. */
+static unsigned                nqbins; /* Number of quantum-spaced bins. */
+static unsigned                nsbins; /* Number of (2^n)-spaced sub-page bins. */
+static size_t          small_min;
+static size_t          small_max;
+
+/* Various quantum-related settings. */
+static size_t          quantum;
+static size_t          quantum_mask; /* (quantum - 1). */
+
+/* Various chunk-related settings. */
+static size_t          chunksize;
+static size_t          chunksize_mask; /* (chunksize - 1). */
+static int             chunksize_2pow;
+static unsigned                chunk_npages;
+static unsigned                arena_chunk_header_npages;
+static size_t          arena_maxclass; /* Max size class for arenas. */
+
+/********/
+/*
+ * Chunks.
+ */
+
+/* Protects chunk-related data structures. */
+static malloc_mutex_t  chunks_mtx;
+
+/* Tree of chunks that are stand-alone huge allocations. */
+static chunk_tree_t    huge;
+
+#ifdef USE_BRK
+/*
+ * Try to use brk for chunk-size allocations, due to address space constraints.
+ */
+/*
+ * Protects sbrk() calls.  This must be separate from chunks_mtx, since
+ * base_pages_alloc() also uses sbrk(), but cannot lock chunks_mtx (doing so
+ * could cause recursive lock acquisition).
+ */
+static malloc_mutex_t  brk_mtx;
+/* Result of first sbrk(0) call. */
+static void            *brk_base;
+/* Current end of brk, or ((void *)-1) if brk is exhausted. */
+static void            *brk_prev;
+/* Current upper limit on brk addresses. */
+static void            *brk_max;
+#endif
+
+#ifdef MALLOC_STATS
+/* Huge allocation statistics. */
+static uint64_t                huge_nmalloc;
+static uint64_t                huge_ndalloc;
+static uint64_t                huge_nralloc;
+static size_t          huge_allocated;
+#endif
+
+/*
+ * Tree of chunks that were previously allocated.  This is used when allocating
+ * chunks, in an attempt to re-use address space.
+ */
+static chunk_tree_t    old_chunks;
+
+/****************************/
+/*
+ * base (internal allocation).
+ */
+
+/*
+ * Current pages that are being used for internal memory allocations.  These
+ * pages are carved up in cacheline-size quanta, so that there is no chance of
+ * false cache line sharing.
+ */
+static void            *base_pages;
+static void            *base_next_addr;
+static void            *base_past_addr; /* Addr immediately past base_pages. */
+static chunk_node_t    *base_chunk_nodes; /* LIFO cache of chunk nodes. */
+static malloc_mutex_t  base_mtx;
+#ifdef MALLOC_STATS
+static size_t          base_mapped;
+#endif
+
+/********/
+/*
+ * Arenas.
+ */
+
+/*
+ * Arenas that are used to service external requests.  Not all elements of the
+ * arenas array are necessarily used; arenas are created lazily as needed.
+ */
+static arena_t         **arenas;
+static unsigned                narenas;
+static unsigned                next_arena;
+static malloc_mutex_t  arenas_mtx; /* Protects arenas initialization. */
+
+#ifndef NO_TLS
+/*
+ * Map of pthread_self() --> arenas[???], used for selecting an arena to use
+ * for allocations.
+ */
+static __thread arena_t        *arenas_map;
+#define        get_arenas_map()        (arenas_map)
+#define        set_arenas_map(x)       (arenas_map = x)
+#else
+static thread_key_t arenas_map_key;
+#define        get_arenas_map()        thr_getspecific(arenas_map_key)
+#define        set_arenas_map(x)       thr_setspecific(arenas_map_key, x)
+#endif
+
+#ifdef MALLOC_STATS
+/* Chunk statistics. */
+static chunk_stats_t   stats_chunks;
+#endif
+
+/*******************************/
+/*
+ * Runtime configuration options.
+ */
+const char     *_malloc_options;
+
+#ifndef MALLOC_PRODUCTION
+static bool    opt_abort = true;
+static bool    opt_junk = true;
+#else
+static bool    opt_abort = false;
+static bool    opt_junk = false;
+#endif
+static bool    opt_hint = false;
+static bool    opt_print_stats = false;
+static int     opt_quantum_2pow = QUANTUM_2POW_MIN;
+static int     opt_small_max_2pow = SMALL_MAX_2POW_DEFAULT;
+static int     opt_chunk_2pow = CHUNK_2POW_DEFAULT;
+static bool    opt_utrace = false;
+static bool    opt_sysv = false;
+static bool    opt_xmalloc = false;
+static bool    opt_zero = false;
+static int32_t opt_narenas_lshift = 0;
+
+typedef struct {
+       void    *p;
+       size_t  s;
+       void    *r;
+} malloc_utrace_t;
+
+#define        UTRACE(a, b, c)                                                 \
+       if (opt_utrace) {                                               \
+               malloc_utrace_t ut;                                     \
+               ut.p = a;                                               \
+               ut.s = b;                                               \
+               ut.r = c;                                               \
+               xutrace(&ut, sizeof(ut));                               \
+       }
+
+/******************************************************************************/
+/*
+ * Begin function prototypes for non-inline static functions.
+ */
+
+static void    wrtmessage(const char *p1, const char *p2, const char *p3,
+               const char *p4);
+#ifdef MALLOC_STATS
+static void    malloc_printf(const char *format, ...);
+#endif
+static char    *umax2s(uintmax_t x, char *s);
+static bool    base_pages_alloc(size_t minsize);
+static void    *base_alloc(size_t size);
+static chunk_node_t *base_chunk_node_alloc(void);
+static void    base_chunk_node_dealloc(chunk_node_t *node);
+#ifdef MALLOC_STATS
+static void    stats_print(arena_t *arena);
+#endif
+static void    *pages_map(void *addr, size_t size);
+static void    *pages_map_align(void *addr, size_t size, int align);
+static void    pages_unmap(void *addr, size_t size);
+static void    *chunk_alloc(size_t size);
+static void    chunk_dealloc(void *chunk, size_t size);
+static void    arena_run_split(arena_t *arena, arena_run_t *run, size_t size);
+static arena_chunk_t *arena_chunk_alloc(arena_t *arena);
+static void    arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk);
+static arena_run_t *arena_run_alloc(arena_t *arena, size_t size);
+static void    arena_run_dalloc(arena_t *arena, arena_run_t *run, size_t size);
+static arena_run_t *arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin);
+static void *arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin);
+static size_t arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size);
+static void    *arena_malloc(arena_t *arena, size_t size);
+static void    *arena_palloc(arena_t *arena, size_t alignment, size_t size,
+    size_t alloc_size);
+static size_t  arena_salloc(const void *ptr);
+static void    *arena_ralloc(void *ptr, size_t size, size_t oldsize);
+static void    arena_dalloc(arena_t *arena, arena_chunk_t *chunk, void *ptr);
+static bool    arena_new(arena_t *arena);
+static arena_t *arenas_extend(unsigned ind);
+static void    *huge_malloc(size_t size);
+static void    *huge_palloc(size_t alignment, size_t size);
+static void    *huge_ralloc(void *ptr, size_t size, size_t oldsize);
+static void    huge_dalloc(void *ptr);
+static void    *imalloc(size_t size);
+static void    *ipalloc(size_t alignment, size_t size);
+static void    *icalloc(size_t size);
+static size_t  isalloc(const void *ptr);
+static void    *iralloc(void *ptr, size_t size);
+static void    idalloc(void *ptr);
+static void    malloc_print_stats(void);
+static bool    malloc_init_hard(void);
+
+/*
+ * End function prototypes.
+ */
+/******************************************************************************/
+/*
+ * Begin mutex.
+ */
+
+#ifdef __NetBSD__
+#define        malloc_mutex_init(m)    mutex_init(m, NULL)
+#define        malloc_mutex_lock(m)    mutex_lock(m)
+#define        malloc_mutex_unlock(m)  mutex_unlock(m)
+#else  /* __NetBSD__ */
+static inline void
+malloc_mutex_init(malloc_mutex_t *a_mutex)
+{
+       static const spinlock_t lock = _SPINLOCK_INITIALIZER;
+
+       a_mutex->lock = lock;
+}
+
+static inline void
+malloc_mutex_lock(malloc_mutex_t *a_mutex)
+{
+
+       if (__isthreaded)
+               _SPINLOCK(&a_mutex->lock);
+}
+
+static inline void
+malloc_mutex_unlock(malloc_mutex_t *a_mutex)
+{
+
+       if (__isthreaded)
+               _SPINUNLOCK(&a_mutex->lock);
+}
+#endif /* __NetBSD__ */
+
+/*
+ * End mutex.
+ */
+/******************************************************************************/
+/*
+ * Begin Utility functions/macros.
+ */
+
+/* Return the chunk address for allocation address a. */
+#define        CHUNK_ADDR2BASE(a)                                              \
+       ((void *)((uintptr_t)(a) & ~chunksize_mask))
+
+/* Return the chunk offset of address a. */
+#define        CHUNK_ADDR2OFFSET(a)                                            \
+       ((size_t)((uintptr_t)(a) & chunksize_mask))
+
+/* Return the smallest chunk multiple that is >= s. */
+#define        CHUNK_CEILING(s)                                                \
+       (((s) + chunksize_mask) & ~chunksize_mask)
+
+/* Return the smallest cacheline multiple that is >= s. */
+#define        CACHELINE_CEILING(s)                                            \
+       (((s) + (CACHELINE - 1)) & ~(CACHELINE - 1))
+
+/* Return the smallest quantum multiple that is >= a. */
+#define        QUANTUM_CEILING(a)                                              \
+       (((a) + quantum_mask) & ~quantum_mask)
+
+/* Return the smallest pagesize multiple that is >= s. */
+#define        PAGE_CEILING(s)                                                 \
+       (((s) + pagesize_mask) & ~pagesize_mask)
+
+/* Compute the smallest power of 2 that is >= x. */
+static inline size_t
+pow2_ceil(size_t x)
+{
+
+       x--;
+       x |= x >> 1;
+       x |= x >> 2;
+       x |= x >> 4;
+       x |= x >> 8;
+       x |= x >> 16;
+#if (SIZEOF_PTR == 8)
+       x |= x >> 32;
+#endif
+       x++;
+       return (x);
+}
+
+static void
+wrtmessage(const char *p1, const char *p2, const char *p3, const char *p4)
+{
+
+       write(STDERR_FILENO, p1, strlen(p1));
+       write(STDERR_FILENO, p2, strlen(p2));
+       write(STDERR_FILENO, p3, strlen(p3));
+       write(STDERR_FILENO, p4, strlen(p4));
+}
+
+void   (*_malloc_message)(const char *p1, const char *p2, const char *p3,
+           const char *p4) = wrtmessage;
+
+#ifdef MALLOC_STATS
+/*
+ * Print to stderr in such a way as to (hopefully) avoid memory allocation.
+ */
+static void
+malloc_printf(const char *format, ...)
+{
+       char buf[4096];
+       va_list ap;
+
+       va_start(ap, format);
+       vsnprintf(buf, sizeof(buf), format, ap);
+       va_end(ap);
+       _malloc_message(buf, "", "", "");
+}
+#endif
+
+/*
+ * We don't want to depend on vsnprintf() for production builds, since that can
+ * cause unnecessary bloat for static binaries.  umax2s() provides minimal
+ * integer printing functionality, so that malloc_printf() use can be limited to
+ * MALLOC_STATS code.
+ */
+#define UMAX2S_BUFSIZE 21
+static char *
+umax2s(uintmax_t x, char *s)
+{
+       unsigned i;
+
+       /* Make sure UMAX2S_BUFSIZE is large enough. */
+       /* LINTED */
+       assert(sizeof(uintmax_t) <= 8);
+
+       i = UMAX2S_BUFSIZE - 1;
+       s[i] = '\0';
+       do {
+               i--;
+               s[i] = "0123456789"[(int)x % 10];
+               x /= (uintmax_t)10LL;
+       } while (x > 0);
+
+       return (&s[i]);
+}
+
+/******************************************************************************/
+
+static bool
+base_pages_alloc(size_t minsize)
+{
+       size_t csize = 0;
+
+#ifdef USE_BRK
+       /*
+        * Do special brk allocation here, since base allocations don't need to
+        * be chunk-aligned.
+        */
+       if (brk_prev != (void *)-1) {
+               void *brk_cur;
+               intptr_t incr;
+
+               if (minsize != 0)
+                       csize = CHUNK_CEILING(minsize);
+
+               malloc_mutex_lock(&brk_mtx);
+               do {
+                       /* Get the current end of brk. */
+                       brk_cur = sbrk(0);
+
+                       /*
+                        * Calculate how much padding is necessary to
+                        * chunk-align the end of brk.  Don't worry about
+                        * brk_cur not being chunk-aligned though.
+                        */
+                       incr = (intptr_t)chunksize
+                           - (intptr_t)CHUNK_ADDR2OFFSET(brk_cur);
+                       assert(incr >= 0);
+                       if ((size_t)incr < minsize)
+                               incr += csize;
+
+                       brk_prev = sbrk(incr);
+                       if (brk_prev == brk_cur) {
+                               /* Success. */
+                               malloc_mutex_unlock(&brk_mtx);
+                               base_pages = brk_cur;
+                               base_next_addr = base_pages;
+                               base_past_addr = (void *)((uintptr_t)base_pages
+                                   + incr);
+#ifdef MALLOC_STATS
+                               base_mapped += incr;
+#endif
+                               return (false);
+                       }
+               } while (brk_prev != (void *)-1);
+               malloc_mutex_unlock(&brk_mtx);
+       }
+       if (minsize == 0) {
+               /*
+                * Failure during initialization doesn't matter, so avoid
+                * falling through to the mmap-based page mapping code.
+                */
+               return (true);
+       }
+#endif
+       assert(minsize != 0);
+       csize = PAGE_CEILING(minsize);
+       base_pages = pages_map(NULL, csize);
+       if (base_pages == NULL)
+               return (true);
+       base_next_addr = base_pages;
+       base_past_addr = (void *)((uintptr_t)base_pages + csize);
+#ifdef MALLOC_STATS
+       base_mapped += csize;
+#endif
+       return (false);
+}
+
+static void *
+base_alloc(size_t size)
+{
+       void *ret;
+       size_t csize;
+
+       /* Round size up to nearest multiple of the cacheline size. */
+       csize = CACHELINE_CEILING(size);
+
+       malloc_mutex_lock(&base_mtx);
+
+       /* Make sure there's enough space for the allocation. */
+       if ((uintptr_t)base_next_addr + csize > (uintptr_t)base_past_addr) {
+               if (base_pages_alloc(csize)) {
+                       ret = NULL;
+                       goto RETURN;
+               }
+       }
+
+       /* Allocate. */
+       ret = base_next_addr;
+       base_next_addr = (void *)((uintptr_t)base_next_addr + csize);
+
+RETURN:
+       malloc_mutex_unlock(&base_mtx);
+       return (ret);
+}
+
+static chunk_node_t *
+base_chunk_node_alloc(void)
+{
+       chunk_node_t *ret;
+
+       malloc_mutex_lock(&base_mtx);
+       if (base_chunk_nodes != NULL) {
+               ret = base_chunk_nodes;
+               /* LINTED */
+               base_chunk_nodes = *(chunk_node_t **)ret;
+               malloc_mutex_unlock(&base_mtx);
+       } else {
+               malloc_mutex_unlock(&base_mtx);
+               ret = (chunk_node_t *)base_alloc(sizeof(chunk_node_t));
+       }
+
+       return (ret);
+}
+
+static void
+base_chunk_node_dealloc(chunk_node_t *node)
+{
+
+       malloc_mutex_lock(&base_mtx);
+       /* LINTED */
+       *(chunk_node_t **)node = base_chunk_nodes;
+       base_chunk_nodes = node;
+       malloc_mutex_unlock(&base_mtx);
+}
+
+/******************************************************************************/
+
+#ifdef MALLOC_STATS
+static void
+stats_print(arena_t *arena)
+{
+       unsigned i;
+       int gap_start;
+
+       malloc_printf(
+           "          allocated/mapped            nmalloc      ndalloc\n");
+
+       malloc_printf("small: %12zu %-12s %12llu %12llu\n",
+           arena->stats.allocated_small, "", arena->stats.nmalloc_small,
+           arena->stats.ndalloc_small);
+       malloc_printf("large: %12zu %-12s %12llu %12llu\n",
+           arena->stats.allocated_large, "", arena->stats.nmalloc_large,
+           arena->stats.ndalloc_large);
+       malloc_printf("total: %12zu/%-12zu %12llu %12llu\n",
+           arena->stats.allocated_small + arena->stats.allocated_large,
+           arena->stats.mapped,
+           arena->stats.nmalloc_small + arena->stats.nmalloc_large,
+           arena->stats.ndalloc_small + arena->stats.ndalloc_large);
+
+       malloc_printf("bins:     bin   size regs pgs  requests   newruns"
+           "    reruns maxruns curruns\n");
+       for (i = 0, gap_start = -1; i < ntbins + nqbins + nsbins; i++) {
+               if (arena->bins[i].stats.nrequests == 0) {
+                       if (gap_start == -1)
+                               gap_start = i;
+               } else {
+                       if (gap_start != -1) {
+                               if (i > gap_start + 1) {
+                                       /* Gap of more than one size class. */
+                                       malloc_printf("[%u..%u]\n",
+                                           gap_start, i - 1);
+                               } else {
+                                       /* Gap of one size class. */
+                                       malloc_printf("[%u]\n", gap_start);
+                               }
+                               gap_start = -1;
+                       }
+                       malloc_printf(
+                           "%13u %1s %4u %4u %3u %9llu %9llu"
+                           " %9llu %7lu %7lu\n",
+                           i,
+                           i < ntbins ? "T" : i < ntbins + nqbins ? "Q" : "S",
+                           arena->bins[i].reg_size,
+                           arena->bins[i].nregs,
+                           arena->bins[i].run_size >> pagesize_2pow,
+                           arena->bins[i].stats.nrequests,
+                           arena->bins[i].stats.nruns,
+                           arena->bins[i].stats.reruns,
+                           arena->bins[i].stats.highruns,
+                           arena->bins[i].stats.curruns);
+               }
+       }
+       if (gap_start != -1) {
+               if (i > gap_start + 1) {
+                       /* Gap of more than one size class. */
+                       malloc_printf("[%u..%u]\n", gap_start, i - 1);
+               } else {
+                       /* Gap of one size class. */
+                       malloc_printf("[%u]\n", gap_start);
+               }
+       }
+}
+#endif
+
+/*
+ * End Utility functions/macros.
+ */
+/******************************************************************************/
+/*
+ * Begin chunk management functions.
+ */
+
+#ifndef lint
+static inline int
+chunk_comp(chunk_node_t *a, chunk_node_t *b)
+{
+
+       assert(a != NULL);
+       assert(b != NULL);
+
+       if ((uintptr_t)a->chunk < (uintptr_t)b->chunk)
+               return (-1);
+       else if (a->chunk == b->chunk)
+               return (0);
+       else
+               return (1);
+}
+
+/* Generate red-black tree code for chunks. */
+RB_GENERATE_STATIC(chunk_tree_s, chunk_node_s, link, chunk_comp);
+#endif
+
+static void *
+pages_map_align(void *addr, size_t size, int align)
+{
+       void *ret;
+
+       /*
+        * We don't use MAP_FIXED here, because it can cause the *replacement*
+        * of existing mappings, and we only want to create new mappings.
+        */
+       ret = mmap(addr, size, PROT_READ | PROT_WRITE,
+           MAP_PRIVATE | MAP_ANON | MAP_ALIGNED(align), -1, 0);
+       assert(ret != NULL);
+
+       if (ret == MAP_FAILED)
+               ret = NULL;
+       else if (addr != NULL && ret != addr) {
+               /*
+                * We succeeded in mapping memory, but not in the right place.
+                */
+               if (munmap(ret, size) == -1) {
+                       char buf[STRERROR_BUF];
+
+                       STRERROR_R(errno, buf, sizeof(buf));
+                       _malloc_message(getprogname(),
+                           ": (malloc) Error in munmap(): ", buf, "\n");
+                       if (opt_abort)
+                               abort();
+               }
+               ret = NULL;
+       }
+
+       assert(ret == NULL || (addr == NULL && ret != addr)
+           || (addr != NULL && ret == addr));
+       return (ret);
+}
+
+static void *
+pages_map(void *addr, size_t size)
+{
+
+       return pages_map_align(addr, size, 0);
+}
+
+static void
+pages_unmap(void *addr, size_t size)
+{
+
+       if (munmap(addr, size) == -1) {
+               char buf[STRERROR_BUF];
+
+               STRERROR_R(errno, buf, sizeof(buf));
+               _malloc_message(getprogname(),
+                   ": (malloc) Error in munmap(): ", buf, "\n");
+               if (opt_abort)
+                       abort();
+       }
+}
+
+static void *
+chunk_alloc(size_t size)
+{
+       void *ret, *chunk;
+       chunk_node_t *tchunk, *delchunk;
+
+       assert(size != 0);
+       assert((size & chunksize_mask) == 0);
+
+       malloc_mutex_lock(&chunks_mtx);
+
+       if (size == chunksize) {
+               /*
+                * Check for address ranges that were previously chunks and try
+                * to use them.
+                */
+
+               /* LINTED */
+               tchunk = RB_MIN(chunk_tree_s, &old_chunks);
+               while (tchunk != NULL) {
+                       /* Found an address range.  Try to recycle it. */
+
+                       chunk = tchunk->chunk;
+                       delchunk = tchunk;
+                       /* LINTED */
+                       tchunk = RB_NEXT(chunk_tree_s, &old_chunks, delchunk);
+
+                       /* Remove delchunk from the tree. */
+                       /* LINTED */
+                       RB_REMOVE(chunk_tree_s, &old_chunks, delchunk);
+                       base_chunk_node_dealloc(delchunk);
+
+#ifdef USE_BRK
+                       if ((uintptr_t)chunk >= (uintptr_t)brk_base
+                           && (uintptr_t)chunk < (uintptr_t)brk_max) {
+                               /* Re-use a previously freed brk chunk. */
+                               ret = chunk;
+                               goto RETURN;
+                       }
+#endif
+                       if ((ret = pages_map(chunk, size)) != NULL) {
+                               /* Success. */
+                               goto RETURN;
+                       }
+               }
+       }
+
+       /*
+        * Try to over-allocate, but allow the OS to place the allocation
+        * anywhere.  Beware of size_t wrap-around.
+        */
+       if (size + chunksize > size) {
+               if ((ret = pages_map_align(NULL, size, chunksize_2pow))
+                   != NULL) {
+                       goto RETURN;
+               }
+       }
+
+#ifdef USE_BRK
+       /*
+        * Try to create allocations in brk, in order to make full use of
+        * limited address space.
+        */
+       if (brk_prev != (void *)-1) {
+               void *brk_cur;
+               intptr_t incr;
+
+               /*
+                * The loop is necessary to recover from races with other
+                * threads that are using brk for something other than malloc.
+                */
+               malloc_mutex_lock(&brk_mtx);
+               do {
+                       /* Get the current end of brk. */
+                       brk_cur = sbrk(0);
+
+                       /*
+                        * Calculate how much padding is necessary to
+                        * chunk-align the end of brk.
+                        */
+                       incr = (intptr_t)size
+                           - (intptr_t)CHUNK_ADDR2OFFSET(brk_cur);
+                       if (incr == (intptr_t)size) {
+                               ret = brk_cur;
+                       } else {
+                               ret = (void *)((intptr_t)brk_cur + incr);
+                               incr += size;
+                       }
+
+                       brk_prev = sbrk(incr);
+                       if (brk_prev == brk_cur) {
+                               /* Success. */
+                               malloc_mutex_unlock(&brk_mtx);
+                               brk_max = (void *)((intptr_t)ret + size);
+                               goto RETURN;
+                       }
+               } while (brk_prev != (void *)-1);
+               malloc_mutex_unlock(&brk_mtx);
+       }
+#endif
+
+       /* All strategies for allocation failed. */
+       ret = NULL;
+RETURN:
+       if (ret != NULL) {
+               chunk_node_t key;
+               /*
+                * Clean out any entries in old_chunks that overlap with the
+                * memory we just allocated.
+                */
+               key.chunk = ret;
+               /* LINTED */
+               tchunk = RB_NFIND(chunk_tree_s, &old_chunks, &key);
+               while (tchunk != NULL
+                   && (uintptr_t)tchunk->chunk >= (uintptr_t)ret
+                   && (uintptr_t)tchunk->chunk < (uintptr_t)ret + size) {
+                       delchunk = tchunk;
+                       /* LINTED */
+                       tchunk = RB_NEXT(chunk_tree_s, &old_chunks, delchunk);
+                       /* LINTED */
+                       RB_REMOVE(chunk_tree_s, &old_chunks, delchunk);
+                       base_chunk_node_dealloc(delchunk);
+               }
+
+       }
+#ifdef MALLOC_STATS
+       if (ret != NULL) {
+               stats_chunks.nchunks += (size / chunksize);
+               stats_chunks.curchunks += (size / chunksize);
+       }
+       if (stats_chunks.curchunks > stats_chunks.highchunks)
+               stats_chunks.highchunks = stats_chunks.curchunks;
+#endif
+       malloc_mutex_unlock(&chunks_mtx);
+
+       assert(CHUNK_ADDR2BASE(ret) == ret);
+       return (ret);
+}
+
+static void
+chunk_dealloc(void *chunk, size_t size)
+{
+       chunk_node_t *node;
+
+       assert(chunk != NULL);
+       assert(CHUNK_ADDR2BASE(chunk) == chunk);
+       assert(size != 0);
+       assert((size & chunksize_mask) == 0);
+
+       malloc_mutex_lock(&chunks_mtx);
+
+#ifdef USE_BRK
+       if ((uintptr_t)chunk >= (uintptr_t)brk_base
+           && (uintptr_t)chunk < (uintptr_t)brk_max) {
+               void *brk_cur;
+
+               malloc_mutex_lock(&brk_mtx);
+               /* Get the current end of brk. */
+               brk_cur = sbrk(0);
+
+               /*
+                * Try to shrink the data segment if this chunk is at the end
+                * of the data segment.  The sbrk() call here is subject to a
+                * race condition with threads that use brk(2) or sbrk(2)
+                * directly, but the alternative would be to leak memory for
+                * the sake of poorly designed multi-threaded programs.
+                */
+               if (brk_cur == brk_max
+                   && (void *)((uintptr_t)chunk + size) == brk_max
+                   && sbrk(-(intptr_t)size) == brk_max) {
+                       malloc_mutex_unlock(&brk_mtx);
+                       if (brk_prev == brk_max) {
+                               /* Success. */
+                               brk_prev = (void *)((intptr_t)brk_max
+                                   - (intptr_t)size);
+                               brk_max = brk_prev;
+                       }
+               } else {
+                       size_t offset;
+
+                       malloc_mutex_unlock(&brk_mtx);
+                       madvise(chunk, size, MADV_FREE);
+
+                       /*
+                        * Iteratively create records of each chunk-sized
+                        * memory region that 'chunk' is comprised of, so that
+                        * the address range can be recycled if memory usage
+                        * increases later on.
+                        */
+                       for (offset = 0; offset < size; offset += chunksize) {
+                               node = base_chunk_node_alloc();
+                               if (node == NULL)
+                                       break;
+
+                               node->chunk = (void *)((uintptr_t)chunk
+                                   + (uintptr_t)offset);
+                               node->size = chunksize;
+                               /* LINTED */
+                               RB_INSERT(chunk_tree_s, &old_chunks, node);
+                       }
+               }
+       } else {
+#endif
+               pages_unmap(chunk, size);
+
+               /*
+                * Make a record of the chunk's address, so that the address
+                * range can be recycled if memory usage increases later on.
+                * Don't bother to create entries if (size > chunksize), since
+                * doing so could cause scalability issues for truly gargantuan
+                * objects (many gigabytes or larger).
+                */
+               if (size == chunksize) {
+                       node = base_chunk_node_alloc();
+                       if (node != NULL) {
+                               node->chunk = (void *)(uintptr_t)chunk;
+                               node->size = chunksize;
+                               /* LINTED */
+                               RB_INSERT(chunk_tree_s, &old_chunks, node);
+                       }
+               }
+#ifdef USE_BRK
+       }
+#endif
+
+#ifdef MALLOC_STATS
+       stats_chunks.curchunks -= (size / chunksize);
+#endif
+       malloc_mutex_unlock(&chunks_mtx);
+}
+
+/*
+ * End chunk management functions.
+ */
+/******************************************************************************/
+/*
+ * Begin arena.
+ */
+
+/*
+ * Choose an arena based on a per-thread and (optimistically) per-CPU value.
+ *
+ * We maintain at least one block of arenas.  Usually there are more.
+ * The blocks are $ncpu arenas in size.  Whole blocks are 'hashed'
+ * amongst threads.  To accomplish this, next_arena advances only in
+ * ncpu steps.
+ */
+static __noinline arena_t *
+choose_arena_hard(void)
+{
+       unsigned i, curcpu;
+       arena_t **map;
+
+       /* Initialize the current block of arenas and advance to next. */
+       malloc_mutex_lock(&arenas_mtx);
+       assert(next_arena % ncpus == 0);
+       assert(narenas % ncpus == 0);
+       map = &arenas[next_arena];
+       set_arenas_map(map);
+       for (i = 0; i < ncpus; i++) {
+               if (arenas[next_arena] == NULL)
+                       arenas_extend(next_arena);
+               next_arena = (next_arena + 1) % narenas;
+       }
+       malloc_mutex_unlock(&arenas_mtx);
+
+       /*
+        * If we were unable to allocate an arena above, then default to
+        * the first arena, which is always present.
+        */
+       curcpu = thr_curcpu();
+       if (map[curcpu] != NULL)
+               return map[curcpu];
+       return arenas[0];
+}
+
+static inline arena_t *
+choose_arena(void)
+{
+       unsigned curcpu;
+       arena_t **map;
+
+       map = get_arenas_map();
+       curcpu = thr_curcpu();
+       if (__predict_true(map != NULL && map[curcpu] != NULL))
+               return map[curcpu];
+
+        return choose_arena_hard();
+}
+
+#ifndef lint
+static inline int
+arena_chunk_comp(arena_chunk_t *a, arena_chunk_t *b)
+{
+
+       assert(a != NULL);
+       assert(b != NULL);
+
+       if ((uintptr_t)a < (uintptr_t)b)
+               return (-1);
+       else if (a == b)
+               return (0);
+       else
+               return (1);
+}
+
+/* Generate red-black tree code for arena chunks. */
+RB_GENERATE_STATIC(arena_chunk_tree_s, arena_chunk_s, link, arena_chunk_comp);
+#endif
+
+#ifndef lint
+static inline int
+arena_run_comp(arena_run_t *a, arena_run_t *b)
+{
+
+       assert(a != NULL);
+       assert(b != NULL);
+
+       if ((uintptr_t)a < (uintptr_t)b)
+               return (-1);
+       else if (a == b)
+               return (0);
+       else
+               return (1);
+}
+
+/* Generate red-black tree code for arena runs. */
+RB_GENERATE_STATIC(arena_run_tree_s, arena_run_s, link, arena_run_comp);
+#endif
+
+static inline void *
+arena_run_reg_alloc(arena_run_t *run, arena_bin_t *bin)
+{
+       void *ret;
+       unsigned i, mask, bit, regind;
+
+       assert(run->magic == ARENA_RUN_MAGIC);
+       assert(run->regs_minelm < bin->regs_mask_nelms);
+
+       /*
+        * Move the first check outside the loop, so that run->regs_minelm can
+        * be updated unconditionally, without the possibility of updating it
+        * multiple times.
+        */
+       i = run->regs_minelm;
+       mask = run->regs_mask[i];
+       if (mask != 0) {
+               /* Usable allocation found. */
+               bit = ffs((int)mask) - 1;
+
+               regind = ((i << (SIZEOF_INT_2POW + 3)) + bit);
+               ret = (void *)(((uintptr_t)run) + bin->reg0_offset
+                   + (bin->reg_size * regind));
+
+               /* Clear bit. */
+               mask ^= (1 << bit);
+               run->regs_mask[i] = mask;
+
+               return (ret);
+       }
+
+       for (i++; i < bin->regs_mask_nelms; i++) {
+               mask = run->regs_mask[i];
+               if (mask != 0) {
+                       /* Usable allocation found. */
+                       bit = ffs((int)mask) - 1;
+
+                       regind = ((i << (SIZEOF_INT_2POW + 3)) + bit);
+                       ret = (void *)(((uintptr_t)run) + bin->reg0_offset
+                           + (bin->reg_size * regind));
+
+                       /* Clear bit. */
+                       mask ^= (1 << bit);
+                       run->regs_mask[i] = mask;
+
+                       /*
+                        * Make a note that nothing before this element
+                        * contains a free region.
+                        */
+                       run->regs_minelm = i; /* Low payoff: + (mask == 0); */
+
+                       return (ret);
+               }
+       }
+       /* Not reached. */
+       /* LINTED */
+       assert(0);
+       return (NULL);
+}
+
+static inline void
+arena_run_reg_dalloc(arena_run_t *run, arena_bin_t *bin, void *ptr, size_t size)
+{
+       /*
+        * To divide by a number D that is not a power of two we multiply
+        * by (2^21 / D) and then right shift by 21 positions.
+        *
+        *   X / D
+        *
+        * becomes
+        *
+        *   (X * size_invs[(D >> QUANTUM_2POW_MIN) - 3]) >> SIZE_INV_SHIFT
+        */
+#define SIZE_INV_SHIFT 21
+#define SIZE_INV(s) (((1 << SIZE_INV_SHIFT) / (s << QUANTUM_2POW_MIN)) + 1)
+       static const unsigned size_invs[] = {
+           SIZE_INV(3),
+           SIZE_INV(4), SIZE_INV(5), SIZE_INV(6), SIZE_INV(7),
+           SIZE_INV(8), SIZE_INV(9), SIZE_INV(10), SIZE_INV(11),
+           SIZE_INV(12),SIZE_INV(13), SIZE_INV(14), SIZE_INV(15),
+           SIZE_INV(16),SIZE_INV(17), SIZE_INV(18), SIZE_INV(19),
+           SIZE_INV(20),SIZE_INV(21), SIZE_INV(22), SIZE_INV(23),
+           SIZE_INV(24),SIZE_INV(25), SIZE_INV(26), SIZE_INV(27),
+           SIZE_INV(28),SIZE_INV(29), SIZE_INV(30), SIZE_INV(31)
+#if (QUANTUM_2POW_MIN < 4)
+           ,
+           SIZE_INV(32), SIZE_INV(33), SIZE_INV(34), SIZE_INV(35),
+           SIZE_INV(36), SIZE_INV(37), SIZE_INV(38), SIZE_INV(39),
+           SIZE_INV(40), SIZE_INV(41), SIZE_INV(42), SIZE_INV(43),
+           SIZE_INV(44), SIZE_INV(45), SIZE_INV(46), SIZE_INV(47),
+           SIZE_INV(48), SIZE_INV(49), SIZE_INV(50), SIZE_INV(51),
+           SIZE_INV(52), SIZE_INV(53), SIZE_INV(54), SIZE_INV(55),
+           SIZE_INV(56), SIZE_INV(57), SIZE_INV(58), SIZE_INV(59),
+           SIZE_INV(60), SIZE_INV(61), SIZE_INV(62), SIZE_INV(63)
+#endif
+       };
+       unsigned diff, regind, elm, bit;
+
+       /* LINTED */
+       assert(run->magic == ARENA_RUN_MAGIC);
+       assert(((sizeof(size_invs)) / sizeof(unsigned)) + 3
+           >= (SMALL_MAX_DEFAULT >> QUANTUM_2POW_MIN));
+
+       /*
+        * Avoid doing division with a variable divisor if possible.  Using
+        * actual division here can reduce allocator throughput by over 20%!
+        */
+       diff = (unsigned)((uintptr_t)ptr - (uintptr_t)run - bin->reg0_offset);
+       if ((size & (size - 1)) == 0) {
+               /*
+                * log2_table allows fast division of a power of two in the
+                * [1..128] range.
+                *
+                * (x / divisor) becomes (x >> log2_table[divisor - 1]).
+                */
+               static const unsigned char log2_table[] = {
+                   0, 1, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4,
+                   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
+                   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6,
+                   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7
+               };
+
+               if (size <= 128)
+                       regind = (diff >> log2_table[size - 1]);
+               else if (size <= 32768)
+                       regind = diff >> (8 + log2_table[(size >> 8) - 1]);
+               else {
+                       /*
+                        * The page size is too large for us to use the lookup
+                        * table.  Use real division.
+                        */
+                       regind = (unsigned)(diff / size);
+               }
+       } else if (size <= ((sizeof(size_invs) / sizeof(unsigned))
+           << QUANTUM_2POW_MIN) + 2) {
+               regind = size_invs[(size >> QUANTUM_2POW_MIN) - 3] * diff;
+               regind >>= SIZE_INV_SHIFT;
+       } else {
+               /*
+                * size_invs isn't large enough to handle this size class, so
+                * calculate regind using actual division.  This only happens
+                * if the user increases small_max via the 'S' runtime
+                * configuration option.
+                */
+               regind = (unsigned)(diff / size);
+       };
+       assert(diff == regind * size);
+       assert(regind < bin->nregs);
+
+       elm = regind >> (SIZEOF_INT_2POW + 3);
+       if (elm < run->regs_minelm)
+               run->regs_minelm = elm;
+       bit = regind - (elm << (SIZEOF_INT_2POW + 3));
+       assert((run->regs_mask[elm] & (1 << bit)) == 0);
+       run->regs_mask[elm] |= (1 << bit);
+#undef SIZE_INV
+#undef SIZE_INV_SHIFT
+}
+
+static void
+arena_run_split(arena_t *arena, arena_run_t *run, size_t size)
+{
+       arena_chunk_t *chunk;
+       unsigned run_ind, map_offset, total_pages, need_pages, rem_pages;
+       unsigned i;
+
+       chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
+       run_ind = (unsigned)(((uintptr_t)run - (uintptr_t)chunk)
+           >> pagesize_2pow);
+       total_pages = chunk->map[run_ind].npages;
+       need_pages = (unsigned)(size >> pagesize_2pow);
+       assert(need_pages <= total_pages);
+       rem_pages = total_pages - need_pages;
+
+       /* Split enough pages from the front of run to fit allocation size. */
+       map_offset = run_ind;
+       for (i = 0; i < need_pages; i++) {
+               chunk->map[map_offset + i].npages = need_pages;
+               chunk->map[map_offset + i].pos = i;
+       }
+
+       /* Keep track of trailing unused pages for later use. */
+       if (rem_pages > 0) {
+               /* Update map for trailing pages. */
+               map_offset += need_pages;
+               chunk->map[map_offset].npages = rem_pages;
+               chunk->map[map_offset].pos = POS_FREE;
+               chunk->map[map_offset + rem_pages - 1].npages = rem_pages;
+               chunk->map[map_offset + rem_pages - 1].pos = POS_FREE;
+       }
+
+       chunk->pages_used += need_pages;
+}
+
+static arena_chunk_t *
+arena_chunk_alloc(arena_t *arena)
+{
+       arena_chunk_t *chunk;
+
+       if (arena->spare != NULL) {
+               chunk = arena->spare;
+               arena->spare = NULL;
+
+               /* LINTED */
+               RB_INSERT(arena_chunk_tree_s, &arena->chunks, chunk);
+       } else {
+               chunk = (arena_chunk_t *)chunk_alloc(chunksize);
+               if (chunk == NULL)
+                       return (NULL);
+#ifdef MALLOC_STATS
+               arena->stats.mapped += chunksize;
+#endif
+
+               chunk->arena = arena;
+
+               /* LINTED */
+               RB_INSERT(arena_chunk_tree_s, &arena->chunks, chunk);
+
+               /*
+                * Claim that no pages are in use, since the header is merely
+                * overhead.
+                */
+               chunk->pages_used = 0;
+
+               chunk->max_frun_npages = chunk_npages -
+                   arena_chunk_header_npages;
+               chunk->min_frun_ind = arena_chunk_header_npages;
+
+               /*
+                * Initialize enough of the map to support one maximal free run.
+                */
+               chunk->map[arena_chunk_header_npages].npages = chunk_npages -
+                   arena_chunk_header_npages;
+               chunk->map[arena_chunk_header_npages].pos = POS_FREE;
+               chunk->map[chunk_npages - 1].npages = chunk_npages -
+                   arena_chunk_header_npages;
+               chunk->map[chunk_npages - 1].pos = POS_FREE;
+       }
+
+       return (chunk);
+}
+
+static void
+arena_chunk_dealloc(arena_t *arena, arena_chunk_t *chunk)
+{
+
+       /*
+        * Remove chunk from the chunk tree, regardless of whether this chunk
+        * will be cached, so that the arena does not use it.
+        */
+       /* LINTED */
+       RB_REMOVE(arena_chunk_tree_s, &chunk->arena->chunks, chunk);
+
+       if (opt_hint == false) {
+               if (arena->spare != NULL) {
+                       chunk_dealloc((void *)arena->spare, chunksize);
+#ifdef MALLOC_STATS
+                       arena->stats.mapped -= chunksize;
+#endif
+               }
+               arena->spare = chunk;
+       } else {
+               assert(arena->spare == NULL);
+               chunk_dealloc((void *)chunk, chunksize);
+#ifdef MALLOC_STATS
+               arena->stats.mapped -= chunksize;
+#endif
+       }
+}
+
+static arena_run_t *
+arena_run_alloc(arena_t *arena, size_t size)
+{
+       arena_chunk_t *chunk;
+       arena_run_t *run;
+       unsigned need_npages, limit_pages, compl_need_npages;
+
+       assert(size <= (chunksize - (arena_chunk_header_npages <<
+           pagesize_2pow)));
+       assert((size & pagesize_mask) == 0);
+
+       /*
+        * Search through arena's chunks in address order for a free run that is
+        * large enough.  Look for the first fit.
+        */
+       need_npages = (unsigned)(size >> pagesize_2pow);
+       limit_pages = chunk_npages - arena_chunk_header_npages;
+       compl_need_npages = limit_pages - need_npages;
+       /* LINTED */
+       RB_FOREACH(chunk, arena_chunk_tree_s, &arena->chunks) {
+               /*
+                * Avoid searching this chunk if there are not enough
+                * contiguous free pages for there to possibly be a large
+                * enough free run.
+                */
+               if (chunk->pages_used <= compl_need_npages &&
+                   need_npages <= chunk->max_frun_npages) {
+                       arena_chunk_map_t *mapelm;
+                       unsigned i;
+                       unsigned max_frun_npages = 0;
+                       unsigned min_frun_ind = chunk_npages;
+
+                       assert(chunk->min_frun_ind >=
+                           arena_chunk_header_npages);
+                       for (i = chunk->min_frun_ind; i < chunk_npages;) {
+                               mapelm = &chunk->map[i];
+                               if (mapelm->pos == POS_FREE) {
+                                       if (mapelm->npages >= need_npages) {
+                                               run = (arena_run_t *)
+                                                   ((uintptr_t)chunk + (i <<
+                                                   pagesize_2pow));
+                                               /* Update page map. */
+                                               arena_run_split(arena, run,
+                                                   size);
+                                               return (run);
+                                       }
+                                       if (mapelm->npages >
+                                           max_frun_npages) {
+                                               max_frun_npages =
+                                                   mapelm->npages;
+                                       }
+                                       if (i < min_frun_ind) {
+                                               min_frun_ind = i;
+                                               if (i < chunk->min_frun_ind)
+                                                       chunk->min_frun_ind = i;
+                                       }
+                               }
+                               i += mapelm->npages;
+                       }
+                       /*
+                        * Search failure.  Reset cached chunk->max_frun_npages.
+                        * chunk->min_frun_ind was already reset above (if
+                        * necessary).
+                        */
+                       chunk->max_frun_npages = max_frun_npages;
+               }
+       }
+
+       /*
+        * No usable runs.  Create a new chunk from which to allocate the run.
+        */
+       chunk = arena_chunk_alloc(arena);
+       if (chunk == NULL)
+               return (NULL);
+       run = (arena_run_t *)((uintptr_t)chunk + (arena_chunk_header_npages <<
+           pagesize_2pow));
+       /* Update page map. */
+       arena_run_split(arena, run, size);
+       return (run);
+}
+
+static void
+arena_run_dalloc(arena_t *arena, arena_run_t *run, size_t size)
+{
+       arena_chunk_t *chunk;
+       unsigned run_ind, run_pages;
+
+       chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
+
+       run_ind = (unsigned)(((uintptr_t)run - (uintptr_t)chunk)
+           >> pagesize_2pow);
+       assert(run_ind >= arena_chunk_header_npages);
+       assert(run_ind < (chunksize >> pagesize_2pow));
+       run_pages = (unsigned)(size >> pagesize_2pow);
+       assert(run_pages == chunk->map[run_ind].npages);
+
+       /* Subtract pages from count of pages used in chunk. */
+       chunk->pages_used -= run_pages;
+
+       /* Mark run as deallocated. */
+       assert(chunk->map[run_ind].npages == run_pages);
+       chunk->map[run_ind].pos = POS_FREE;
+       assert(chunk->map[run_ind + run_pages - 1].npages == run_pages);
+       chunk->map[run_ind + run_pages - 1].pos = POS_FREE;
+
+       /*
+        * Tell the kernel that we don't need the data in this run, but only if
+        * requested via runtime configuration.
+        */
+       if (opt_hint)
+               madvise(run, size, MADV_FREE);
+
+       /* Try to coalesce with neighboring runs. */
+       if (run_ind > arena_chunk_header_npages &&
+           chunk->map[run_ind - 1].pos == POS_FREE) {
+               unsigned prev_npages;
+
+               /* Coalesce with previous run. */
+               prev_npages = chunk->map[run_ind - 1].npages;
+               run_ind -= prev_npages;
+               assert(chunk->map[run_ind].npages == prev_npages);
+               assert(chunk->map[run_ind].pos == POS_FREE);
+               run_pages += prev_npages;
+
+               chunk->map[run_ind].npages = run_pages;
+               assert(chunk->map[run_ind].pos == POS_FREE);
+               chunk->map[run_ind + run_pages - 1].npages = run_pages;
+               assert(chunk->map[run_ind + run_pages - 1].pos == POS_FREE);
+       }
+
+       if (run_ind + run_pages < chunk_npages &&
+           chunk->map[run_ind + run_pages].pos == POS_FREE) {
+               unsigned next_npages;
+
+               /* Coalesce with next run. */
+               next_npages = chunk->map[run_ind + run_pages].npages;
+               run_pages += next_npages;
+               assert(chunk->map[run_ind + run_pages - 1].npages ==
+                   next_npages);
+               assert(chunk->map[run_ind + run_pages - 1].pos == POS_FREE);
+
+               chunk->map[run_ind].npages = run_pages;
+               chunk->map[run_ind].pos = POS_FREE;
+               chunk->map[run_ind + run_pages - 1].npages = run_pages;
+               assert(chunk->map[run_ind + run_pages - 1].pos == POS_FREE);
+       }
+
+       if (chunk->map[run_ind].npages > chunk->max_frun_npages)
+               chunk->max_frun_npages = chunk->map[run_ind].npages;
+       if (run_ind < chunk->min_frun_ind)
+               chunk->min_frun_ind = run_ind;
+
+       /* Deallocate chunk if it is now completely unused. */
+       if (chunk->pages_used == 0)
+               arena_chunk_dealloc(arena, chunk);
+}
+
+static arena_run_t *
+arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin)
+{
+       arena_run_t *run;
+       unsigned i, remainder;
+
+       /* Look for a usable run. */
+       /* LINTED */
+       if ((run = RB_MIN(arena_run_tree_s, &bin->runs)) != NULL) {
+               /* run is guaranteed to have available space. */
+               /* LINTED */
+               RB_REMOVE(arena_run_tree_s, &bin->runs, run);
+#ifdef MALLOC_STATS
+               bin->stats.reruns++;
+#endif
+               return (run);
+       }
+       /* No existing runs have any space available. */
+
+       /* Allocate a new run. */
+       run = arena_run_alloc(arena, bin->run_size);
+       if (run == NULL)
+               return (NULL);
+
+       /* Initialize run internals. */
+       run->bin = bin;
+
+       for (i = 0; i < bin->regs_mask_nelms; i++)
+               run->regs_mask[i] = UINT_MAX;
+       remainder = bin->nregs & ((1 << (SIZEOF_INT_2POW + 3)) - 1);
+       if (remainder != 0) {
+               /* The last element has spare bits that need to be unset. */
+               run->regs_mask[i] = (UINT_MAX >> ((1 << (SIZEOF_INT_2POW + 3))
+                   - remainder));
+       }
+
+       run->regs_minelm = 0;
+
+       run->nfree = bin->nregs;
+#ifdef MALLOC_DEBUG
+       run->magic = ARENA_RUN_MAGIC;
+#endif
+
+#ifdef MALLOC_STATS
+       bin->stats.nruns++;
+       bin->stats.curruns++;
+       if (bin->stats.curruns > bin->stats.highruns)
+               bin->stats.highruns = bin->stats.curruns;
+#endif
+       return (run);
+}
+
+/* bin->runcur must have space available before this function is called. */
+static inline void *
+arena_bin_malloc_easy(arena_t *arena, arena_bin_t *bin, arena_run_t *run)
+{
+       void *ret;
+
+       assert(run->magic == ARENA_RUN_MAGIC);
+       assert(run->nfree > 0);
+
+       ret = arena_run_reg_alloc(run, bin);
+       assert(ret != NULL);
+       run->nfree--;
+
+       return (ret);
+}
+
+/* Re-fill bin->runcur, then call arena_bin_malloc_easy(). */
+static void *
+arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin)
+{
+
+       bin->runcur = arena_bin_nonfull_run_get(arena, bin);
+       if (bin->runcur == NULL)
+               return (NULL);
+       assert(bin->runcur->magic == ARENA_RUN_MAGIC);
+       assert(bin->runcur->nfree > 0);
+
+       return (arena_bin_malloc_easy(arena, bin, bin->runcur));
+}
+
+/*
+ * Calculate bin->run_size such that it meets the following constraints:
+ *
+ *   *) bin->run_size >= min_run_size
+ *   *) bin->run_size <= arena_maxclass
+ *   *) bin->run_size <= RUN_MAX_SMALL
+ *   *) run header overhead <= RUN_MAX_OVRHD (or header overhead relaxed).
+ *
+ * bin->nregs, bin->regs_mask_nelms, and bin->reg0_offset are
+ * also calculated here, since these settings are all interdependent.
+ */
+static size_t
+arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size)
+{
+       size_t try_run_size, good_run_size;
+       unsigned good_nregs, good_mask_nelms, good_reg0_offset;
+       unsigned try_nregs, try_mask_nelms, try_reg0_offset;
+       float max_ovrhd = RUN_MAX_OVRHD;
+
+       assert(min_run_size >= pagesize);
+       assert(min_run_size <= arena_maxclass);
+       assert(min_run_size <= RUN_MAX_SMALL);
+
+       /*
+        * Calculate known-valid settings before entering the run_size
+        * expansion loop, so that the first part of the loop always copies
+        * valid settings.
+        *
+        * The do..while loop iteratively reduces the number of regions until
+        * the run header and the regions no longer overlap.  A closed formula
+        * would be quite messy, since there is an interdependency between the
+        * header's mask length and the number of regions.
+        */
+       try_run_size = min_run_size;
+       try_nregs = (unsigned)(((try_run_size - sizeof(arena_run_t)) /
+           bin->reg_size) + 1); /* Counter-act the first line of the loop. */
+       do {
+               try_nregs--;
+               try_mask_nelms = (try_nregs >> (SIZEOF_INT_2POW + 3)) +
+                   ((try_nregs & ((1 << (SIZEOF_INT_2POW + 3)) - 1)) ? 1 : 0);
+               try_reg0_offset = (unsigned)(try_run_size -
+                   (try_nregs * bin->reg_size));
+       } while (sizeof(arena_run_t) + (sizeof(unsigned) * (try_mask_nelms - 1))
+           > try_reg0_offset);
+
+       /* run_size expansion loop. */
+       do {
+               /*
+                * Copy valid settings before trying more aggressive settings.
+                */
+               good_run_size = try_run_size;
+               good_nregs = try_nregs;
+               good_mask_nelms = try_mask_nelms;
+               good_reg0_offset = try_reg0_offset;
+
+               /* Try more aggressive settings. */
+               try_run_size += pagesize;
+               try_nregs = (unsigned)(((try_run_size - sizeof(arena_run_t)) /
+                   bin->reg_size) + 1); /* Counter-act try_nregs-- in loop. */
+               do {
+                       try_nregs--;
+                       try_mask_nelms = (try_nregs >> (SIZEOF_INT_2POW + 3)) +
+                           ((try_nregs & ((1 << (SIZEOF_INT_2POW + 3)) - 1)) ?
+                           1 : 0);
+                       try_reg0_offset = (unsigned)(try_run_size - (try_nregs *
+                           bin->reg_size));
+               } while (sizeof(arena_run_t) + (sizeof(unsigned) *
+                   (try_mask_nelms - 1)) > try_reg0_offset);
+       } while (try_run_size <= arena_maxclass && try_run_size <= RUN_MAX_SMALL
+           && max_ovrhd > RUN_MAX_OVRHD_RELAX / ((float)(bin->reg_size << 3))
+           && ((float)(try_reg0_offset)) / ((float)(try_run_size)) >
+           max_ovrhd);
+
+       assert(sizeof(arena_run_t) + (sizeof(unsigned) * (good_mask_nelms - 1))
+           <= good_reg0_offset);
+       assert((good_mask_nelms << (SIZEOF_INT_2POW + 3)) >= good_nregs);
+
+       /* Copy final settings. */
+       bin->run_size = good_run_size;
+       bin->nregs = good_nregs;
+       bin->regs_mask_nelms = good_mask_nelms;
+       bin->reg0_offset = good_reg0_offset;
+
+       return (good_run_size);
+}
+
+static void *
+arena_malloc(arena_t *arena, size_t size)
+{
+       void *ret;
+
+       assert(arena != NULL);
+       assert(arena->magic == ARENA_MAGIC);
+       assert(size != 0);
+       assert(QUANTUM_CEILING(size) <= arena_maxclass);
+
+       if (size <= bin_maxclass) {
+               arena_bin_t *bin;
+               arena_run_t *run;
+
+               /* Small allocation. */
+
+               if (size < small_min) {
+                       /* Tiny. */
+                       size = pow2_ceil(size);
+                       bin = &arena->bins[ffs((int)(size >> (TINY_MIN_2POW +
+                           1)))];
+#if (!defined(NDEBUG) || defined(MALLOC_STATS))
+                       /*
+                        * Bin calculation is always correct, but we may need
+                        * to fix size for the purposes of assertions and/or
+                        * stats accuracy.
+                        */
+                       if (size < (1 << TINY_MIN_2POW))
+                               size = (1 << TINY_MIN_2POW);
+#endif
+               } else if (size <= small_max) {
+                       /* Quantum-spaced. */
+                       size = QUANTUM_CEILING(size);
+                       bin = &arena->bins[ntbins + (size >> opt_quantum_2pow)
+                           - 1];
+               } else {
+                       /* Sub-page. */
+                       size = pow2_ceil(size);
+                       bin = &arena->bins[ntbins + nqbins
+                           + (ffs((int)(size >> opt_small_max_2pow)) - 2)];
+               }
+               assert(size == bin->reg_size);
+
+               malloc_mutex_lock(&arena->mtx);
+               if ((run = bin->runcur) != NULL && run->nfree > 0)
+                       ret = arena_bin_malloc_easy(arena, bin, run);
+               else
+                       ret = arena_bin_malloc_hard(arena, bin);
+
+               if (ret == NULL) {
+                       malloc_mutex_unlock(&arena->mtx);
+                       return (NULL);
+               }
+
+#ifdef MALLOC_STATS
+               bin->stats.nrequests++;
+               arena->stats.nmalloc_small++;
+               arena->stats.allocated_small += size;
+#endif
+       } else {
+               /* Large allocation. */
+               size = PAGE_CEILING(size);
+               malloc_mutex_lock(&arena->mtx);
+               ret = (void *)arena_run_alloc(arena, size);
+               if (ret == NULL) {
+                       malloc_mutex_unlock(&arena->mtx);
+                       return (NULL);
+               }
+#ifdef MALLOC_STATS
+               arena->stats.nmalloc_large++;
+               arena->stats.allocated_large += size;
+#endif
+       }
+
+       malloc_mutex_unlock(&arena->mtx);
+
+       if (opt_junk)
+               memset(ret, 0xa5, size);
+       else if (opt_zero)
+               memset(ret, 0, size);
+       return (ret);
+}
+
+static inline void
+arena_palloc_trim(arena_t *arena, arena_chunk_t *chunk, unsigned pageind,
+    unsigned npages)
+{
+       unsigned i;
+
+       assert(npages > 0);
+
+       /*
+        * Modifiy the map such that arena_run_dalloc() sees the run as
+        * separately allocated.
+        */
+       for (i = 0; i < npages; i++) {
+               chunk->map[pageind + i].npages = npages;
+               chunk->map[pageind + i].pos = i;
+       }
+       arena_run_dalloc(arena, (arena_run_t *)((uintptr_t)chunk + (pageind <<
+           pagesize_2pow)), npages << pagesize_2pow);
+}
+
+/* Only handles large allocations that require more than page alignment. */
+static void *
+arena_palloc(arena_t *arena, size_t alignment, size_t size, size_t alloc_size)
+{
+       void *ret;
+       size_t offset;
+       arena_chunk_t *chunk;
+       unsigned pageind, i, npages;
+
+       assert((size & pagesize_mask) == 0);
+       assert((alignment & pagesize_mask) == 0);
+
+       npages = (unsigned)(size >> pagesize_2pow);
+
+       malloc_mutex_lock(&arena->mtx);
+       ret = (void *)arena_run_alloc(arena, alloc_size);
+       if (ret == NULL) {
+               malloc_mutex_unlock(&arena->mtx);
+               return (NULL);
+       }
+
+       chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ret);
+
+       offset = (uintptr_t)ret & (alignment - 1);
+       assert((offset & pagesize_mask) == 0);
+       assert(offset < alloc_size);
+       if (offset == 0) {
+               pageind = (unsigned)(((uintptr_t)ret - (uintptr_t)chunk) >>
+                   pagesize_2pow);
+
+               /* Update the map for the run to be kept. */
+               for (i = 0; i < npages; i++) {
+                       chunk->map[pageind + i].npages = npages;
+                       assert(chunk->map[pageind + i].pos == i);
+               }
+
+               /* Trim trailing space. */
+               arena_palloc_trim(arena, chunk, pageind + npages,
+                   (unsigned)((alloc_size - size) >> pagesize_2pow));
+       } else {
+               size_t leadsize, trailsize;
+
+               leadsize = alignment - offset;
+               ret = (void *)((uintptr_t)ret + leadsize);
+               pageind = (unsigned)(((uintptr_t)ret - (uintptr_t)chunk) >>
+                   pagesize_2pow);
+
+               /* Update the map for the run to be kept. */
+               for (i = 0; i < npages; i++) {
+                       chunk->map[pageind + i].npages = npages;
+                       chunk->map[pageind + i].pos = i;
+               }
+
+               /* Trim leading space. */
+               arena_palloc_trim(arena, chunk,
+                   (unsigned)(pageind - (leadsize >> pagesize_2pow)),
+                   (unsigned)(leadsize >> pagesize_2pow));
+
+               trailsize = alloc_size - leadsize - size;
+               if (trailsize != 0) {
+                       /* Trim trailing space. */
+                       assert(trailsize < alloc_size);
+                       arena_palloc_trim(arena, chunk, pageind + npages,
+                           (unsigned)(trailsize >> pagesize_2pow));
+               }
+       }
+
+#ifdef MALLOC_STATS
+       arena->stats.nmalloc_large++;
+       arena->stats.allocated_large += size;
+#endif
+       malloc_mutex_unlock(&arena->mtx);
+
+       if (opt_junk)
+               memset(ret, 0xa5, size);
+       else if (opt_zero)
+               memset(ret, 0, size);
+       return (ret);
+}
+
+/* Return the size of the allocation pointed to by ptr. */
+static size_t
+arena_salloc(const void *ptr)
+{
+       size_t ret;
+       arena_chunk_t *chunk;
+       arena_chunk_map_t *mapelm;
+       unsigned pageind;
+
+       assert(ptr != NULL);
+       assert(CHUNK_ADDR2BASE(ptr) != ptr);
+
+       /*
+        * No arena data structures that we query here can change in a way that
+        * affects this function, so we don't need to lock.
+        */
+       chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
+       pageind = (unsigned)(((uintptr_t)ptr - (uintptr_t)chunk) >>
+           pagesize_2pow);
+       mapelm = &chunk->map[pageind];
+       if (mapelm->pos != 0 || ptr != (char *)((uintptr_t)chunk) + (pageind <<
+           pagesize_2pow)) {
+               arena_run_t *run;
+
+               pageind -= mapelm->pos;
+
+               run = (arena_run_t *)((uintptr_t)chunk + (pageind <<
+                   pagesize_2pow));
+               assert(run->magic == ARENA_RUN_MAGIC);
+               ret = run->bin->reg_size;
+       } else
+               ret = mapelm->npages << pagesize_2pow;
+
+       return (ret);
+}
+
+static void *
+arena_ralloc(void *ptr, size_t size, size_t oldsize)
+{
+       void *ret;
+
+       /* Avoid moving the allocation if the size class would not change. */
+       if (size < small_min) {
+               if (oldsize < small_min &&
+                   ffs((int)(pow2_ceil(size) >> (TINY_MIN_2POW + 1)))
+                   == ffs((int)(pow2_ceil(oldsize) >> (TINY_MIN_2POW + 1))))
+                       goto IN_PLACE;
+       } else if (size <= small_max) {
+               if (oldsize >= small_min && oldsize <= small_max &&
+                   (QUANTUM_CEILING(size) >> opt_quantum_2pow)
+                   == (QUANTUM_CEILING(oldsize) >> opt_quantum_2pow))
+                       goto IN_PLACE;
+       } else {
+               /*
+                * We make no attempt to resize runs here, though it would be
+                * possible to do so.
+                */
+               if (oldsize > small_max && PAGE_CEILING(size) == oldsize)
+                       goto IN_PLACE;
+       }
+
+       /*
+        * If we get here, then size and oldsize are different enough that we
+        * need to use a different size class.  In that case, fall back to
+        * allocating new space and copying.
+        */
+       ret = arena_malloc(choose_arena(), size);
+       if (ret == NULL)
+               return (NULL);
+
+       /* Junk/zero-filling were already done by arena_malloc(). */
+       if (size < oldsize)
+               memcpy(ret, ptr, size);
+       else
+               memcpy(ret, ptr, oldsize);
+       idalloc(ptr);
+       return (ret);
+IN_PLACE:
+       if (opt_junk && size < oldsize)
+               memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize - size);
+       else if (opt_zero && size > oldsize)
+               memset((void *)((uintptr_t)ptr + oldsize), 0, size - oldsize);
+       return (ptr);
+}
+
+static void
+arena_dalloc(arena_t *arena, arena_chunk_t *chunk, void *ptr)
+{
+       unsigned pageind;
+       arena_chunk_map_t *mapelm;
+       size_t size;
+
+       assert(arena != NULL);
+       assert(arena->magic == ARENA_MAGIC);
+       assert(chunk->arena == arena);
+       assert(ptr != NULL);
+       assert(CHUNK_ADDR2BASE(ptr) != ptr);
+
+       pageind = (unsigned)(((uintptr_t)ptr - (uintptr_t)chunk) >>
+           pagesize_2pow);
+       mapelm = &chunk->map[pageind];
+       if (mapelm->pos != 0 || ptr != (char *)((uintptr_t)chunk) + (pageind <<
+           pagesize_2pow)) {
+               arena_run_t *run;
+               arena_bin_t *bin;
+
+               /* Small allocation. */
+
+               pageind -= mapelm->pos;
+
+               run = (arena_run_t *)((uintptr_t)chunk + (pageind <<
+                   pagesize_2pow));
+               assert(run->magic == ARENA_RUN_MAGIC);
+               bin = run->bin;
+               size = bin->reg_size;
+
+               if (opt_junk)
+                       memset(ptr, 0x5a, size);
+
+               malloc_mutex_lock(&arena->mtx);
+               arena_run_reg_dalloc(run, bin, ptr, size);
+               run->nfree++;
+
+               if (run->nfree == bin->nregs) {
+                       /* Deallocate run. */
+                       if (run == bin->runcur)
+                               bin->runcur = NULL;
+                       else if (bin->nregs != 1) {
+                               /*
+                                * This block's conditional is necessary because
+                                * if the run only contains one region, then it
+                                * never gets inserted into the non-full runs
+                                * tree.
+                                */
+                               /* LINTED */
+                               RB_REMOVE(arena_run_tree_s, &bin->runs, run);
+                       }
+#ifdef MALLOC_DEBUG
+                       run->magic = 0;
+#endif
+                       arena_run_dalloc(arena, run, bin->run_size);
+#ifdef MALLOC_STATS
+                       bin->stats.curruns--;
+#endif
+               } else if (run->nfree == 1 && run != bin->runcur) {
+                       /*
+                        * Make sure that bin->runcur always refers to the
+                        * lowest non-full run, if one exists.
+                        */
+                       if (bin->runcur == NULL)
+                               bin->runcur = run;
+                       else if ((uintptr_t)run < (uintptr_t)bin->runcur) {
+                               /* Switch runcur. */
+                               if (bin->runcur->nfree > 0) {
+                                       /* Insert runcur. */
+                                       /* LINTED */
+                                       RB_INSERT(arena_run_tree_s, &bin->runs,
+                                           bin->runcur);
+                               }
+                               bin->runcur = run;
+                       } else {
+                               /* LINTED */
+                               RB_INSERT(arena_run_tree_s, &bin->runs, run);
+                       }
+               }
+#ifdef MALLOC_STATS
+               arena->stats.allocated_small -= size;
+               arena->stats.ndalloc_small++;
+#endif
+       } else {
+               /* Large allocation. */
+
+               size = mapelm->npages << pagesize_2pow;
+               assert((((uintptr_t)ptr) & pagesize_mask) == 0);
+
+               if (opt_junk)
+                       memset(ptr, 0x5a, size);
+
+               malloc_mutex_lock(&arena->mtx);
+               arena_run_dalloc(arena, (arena_run_t *)ptr, size);
+#ifdef MALLOC_STATS
+               arena->stats.allocated_large -= size;
+               arena->stats.ndalloc_large++;
+#endif
+       }
+
+       malloc_mutex_unlock(&arena->mtx);
+}
+
+static bool
+arena_new(arena_t *arena)
+{
+       unsigned i;
+       arena_bin_t *bin;
+       size_t prev_run_size;
+
+       malloc_mutex_init(&arena->mtx);
+
+#ifdef MALLOC_STATS
+       memset(&arena->stats, 0, sizeof(arena_stats_t));
+#endif
+
+       /* Initialize chunks. */
+       RB_INIT(&arena->chunks);
+       arena->spare = NULL;
+
+       /* Initialize bins. */
+       prev_run_size = pagesize;
+
+       /* (2^n)-spaced tiny bins. */
+       for (i = 0; i < ntbins; i++) {
+               bin = &arena->bins[i];
+               bin->runcur = NULL;
+               RB_INIT(&bin->runs);
+
+               bin->reg_size = (1 << (TINY_MIN_2POW + i));
+               prev_run_size = arena_bin_run_size_calc(bin, prev_run_size);
+
+#ifdef MALLOC_STATS
+               memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
+#endif
+       }
+
+       /* Quantum-spaced bins. */
+       for (; i < ntbins + nqbins; i++) {
+               bin = &arena->bins[i];
+               bin->runcur = NULL;
+               RB_INIT(&bin->runs);
+
+               bin->reg_size = quantum * (i - ntbins + 1);
+/*
+               pow2_size = pow2_ceil(quantum * (i - ntbins + 1));
+*/
+               prev_run_size = arena_bin_run_size_calc(bin, prev_run_size);
+
+#ifdef MALLOC_STATS
+               memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
+#endif
+       }
+
+       /* (2^n)-spaced sub-page bins. */
+       for (; i < ntbins + nqbins + nsbins; i++) {
+               bin = &arena->bins[i];
+               bin->runcur = NULL;
+               RB_INIT(&bin->runs);
+
+               bin->reg_size = (small_max << (i - (ntbins + nqbins) + 1));
+
+               prev_run_size = arena_bin_run_size_calc(bin, prev_run_size);
+
+#ifdef MALLOC_STATS
+               memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
+#endif
+       }
+
+#ifdef MALLOC_DEBUG
+       arena->magic = ARENA_MAGIC;
+#endif
+
+       return (false);
+}
+
+/* Create a new arena and insert it into the arenas array at index ind. */
+static arena_t *
+arenas_extend(unsigned ind)
+{
+       arena_t *ret;
+
+       /* Allocate enough space for trailing bins. */
+       ret = (arena_t *)base_alloc(sizeof(arena_t)
+           + (sizeof(arena_bin_t) * (ntbins + nqbins + nsbins - 1)));
+       if (ret != NULL && arena_new(ret) == false) {
+               arenas[ind] = ret;
+               return (ret);
+       }
+       /* Only reached if there is an OOM error. */
+
+       /*
+        * OOM here is quite inconvenient to propagate, since dealing with it
+        * would require a check for failure in the fast path.  Instead, punt
+        * by using arenas[0].  In practice, this is an extremely unlikely
+        * failure.
+        */
+       _malloc_message(getprogname(),
+           ": (malloc) Error initializing arena\n", "", "");
+       if (opt_abort)
+               abort();
+
+       return (arenas[0]);
+}
+
+/*
+ * End arena.
+ */
+/******************************************************************************/
+/*
+ * Begin general internal functions.
+ */
+
+static void *
+huge_malloc(size_t size)
+{
+       void *ret;
+       size_t csize;
+       chunk_node_t *node;
+
+       /* Allocate one or more contiguous chunks for this request. */
+
+       csize = CHUNK_CEILING(size);
+       if (csize == 0) {
+               /* size is large enough to cause size_t wrap-around. */
+               return (NULL);
+       }
+
+       /* Allocate a chunk node with which to track the chunk. */
+       node = base_chunk_node_alloc();
+       if (node == NULL)
+               return (NULL);
+
+       ret = chunk_alloc(csize);
+       if (ret == NULL) {
+               base_chunk_node_dealloc(node);
+               return (NULL);
+       }
+
+       /* Insert node into huge. */
+       node->chunk = ret;
+       node->size = csize;
+
+       malloc_mutex_lock(&chunks_mtx);
+       RB_INSERT(chunk_tree_s, &huge, node);
+#ifdef MALLOC_STATS
+       huge_nmalloc++;
+       huge_allocated += csize;
+#endif
+       malloc_mutex_unlock(&chunks_mtx);
+
+       if (opt_junk)
+               memset(ret, 0xa5, csize);
+       else if (opt_zero)
+               memset(ret, 0, csize);
+
+       return (ret);
+}
+
+/* Only handles large allocations that require more than chunk alignment. */
+static void *
+huge_palloc(size_t alignment, size_t size)
+{
+       void *ret;
+       size_t alloc_size, chunk_size, offset;
+       chunk_node_t *node;
+
+       /*
+        * This allocation requires alignment that is even larger than chunk
+        * alignment.  This means that huge_malloc() isn't good enough.
+        *
+        * Allocate almost twice as many chunks as are demanded by the size or
+        * alignment, in order to assure the alignment can be achieved, then
+        * unmap leading and trailing chunks.
+        */
+       assert(alignment >= chunksize);
+
+       chunk_size = CHUNK_CEILING(size);
+
+       if (size >= alignment)
+               alloc_size = chunk_size + alignment - chunksize;
+       else
+               alloc_size = (alignment << 1) - chunksize;
+
+       /* Allocate a chunk node with which to track the chunk. */
+       node = base_chunk_node_alloc();
+       if (node == NULL)
+               return (NULL);
+
+       ret = chunk_alloc(alloc_size);
+       if (ret == NULL) {
+               base_chunk_node_dealloc(node);
+               return (NULL);
+       }
+
+       offset = (uintptr_t)ret & (alignment - 1);
+       assert((offset & chunksize_mask) == 0);
+       assert(offset < alloc_size);
+       if (offset == 0) {
+               /* Trim trailing space. */
+               chunk_dealloc((void *)((uintptr_t)ret + chunk_size), alloc_size
+                   - chunk_size);
+       } else {
+               size_t trailsize;
+
+               /* Trim leading space. */
+               chunk_dealloc(ret, alignment - offset);
+
+               ret = (void *)((uintptr_t)ret + (alignment - offset));
+
+               trailsize = alloc_size - (alignment - offset) - chunk_size;
+               if (trailsize != 0) {
+                   /* Trim trailing space. */
+                   assert(trailsize < alloc_size);
+                   chunk_dealloc((void *)((uintptr_t)ret + chunk_size),
+                       trailsize);
+               }
+       }
+
+       /* Insert node into huge. */
+       node->chunk = ret;
+       node->size = chunk_size;
+
+       malloc_mutex_lock(&chunks_mtx);
+       RB_INSERT(chunk_tree_s, &huge, node);
+#ifdef MALLOC_STATS
+       huge_nmalloc++;
+       huge_allocated += chunk_size;
+#endif
+       malloc_mutex_unlock(&chunks_mtx);
+
+       if (opt_junk)
+               memset(ret, 0xa5, chunk_size);
+       else if (opt_zero)
+               memset(ret, 0, chunk_size);
+
+       return (ret);
+}
+
+static void *
+huge_ralloc(void *ptr, size_t size, size_t oldsize)
+{
+       void *ret;
+
+       /* Avoid moving the allocation if the size class would not change. */
+       if (oldsize > arena_maxclass &&
+           CHUNK_CEILING(size) == CHUNK_CEILING(oldsize)) {
+               if (opt_junk && size < oldsize) {
+                       memset((void *)((uintptr_t)ptr + size), 0x5a, oldsize
+                           - size);
+               } else if (opt_zero && size > oldsize) {
+                       memset((void *)((uintptr_t)ptr + oldsize), 0, size
+                           - oldsize);
+               }
+               return (ptr);
+       }
+
+       if (CHUNK_ADDR2BASE(ptr) == ptr
+#ifdef USE_BRK
+           && ((uintptr_t)ptr < (uintptr_t)brk_base
+           || (uintptr_t)ptr >= (uintptr_t)brk_max)
+#endif
+           ) {
+               chunk_node_t *node, key;
+               void *newptr;
+               size_t oldcsize;
+               size_t newcsize;
+
+               newcsize = CHUNK_CEILING(size);
+               oldcsize = CHUNK_CEILING(oldsize);
+               assert(oldcsize != newcsize);
+               if (newcsize == 0) {
+                       /* size_t wrap-around */
+                       return (NULL);
+               }
+
+               /*
+                * Remove the old region from the tree now.  If mremap()
+                * returns the region to the system, other thread may
+                * map it for same huge allocation and insert it to the
+                * tree before we acquire the mutex lock again.
+                */
+               malloc_mutex_lock(&chunks_mtx);
+               key.chunk = __DECONST(void *, ptr);
+               /* LINTED */
+               node = RB_FIND(chunk_tree_s, &huge, &key);
+               assert(node != NULL);
+               assert(node->chunk == ptr);
+               assert(node->size == oldcsize);
+               RB_REMOVE(chunk_tree_s, &huge, node);
+               malloc_mutex_unlock(&chunks_mtx);
+
+               newptr = mremap(ptr, oldcsize, NULL, newcsize,
+                   MAP_ALIGNED(chunksize_2pow));
+               if (newptr == MAP_FAILED) {
+                       /* We still own the old region. */
+                       malloc_mutex_lock(&chunks_mtx);
+                       RB_INSERT(chunk_tree_s, &huge, node);
+                       malloc_mutex_unlock(&chunks_mtx);
+               } else {
+                       assert(CHUNK_ADDR2BASE(newptr) == newptr);
+
+                       /* Insert new or resized old region. */
+                       malloc_mutex_lock(&chunks_mtx);
+                       node->size = newcsize;
+                       node->chunk = newptr;
+                       RB_INSERT(chunk_tree_s, &huge, node);
+#ifdef MALLOC_STATS
+                       huge_nralloc++;
+                       huge_allocated += newcsize - oldcsize;
+                       if (newcsize > oldcsize) {
+                               stats_chunks.curchunks +=
+                                   (newcsize - oldcsize) / chunksize;
+                               if (stats_chunks.curchunks >
+                                   stats_chunks.highchunks)
+                                       stats_chunks.highchunks =
+                                           stats_chunks.curchunks;
+                       } else {
+                               stats_chunks.curchunks -=
+                                   (oldcsize - newcsize) / chunksize;
+                       }
+#endif
+                       malloc_mutex_unlock(&chunks_mtx);
+
+                       if (opt_junk && size < oldsize) {
+                               memset((void *)((uintptr_t)newptr + size), 0x5a,
+                                   newcsize - size);
+                       } else if (opt_zero && size > oldsize) {
+                               memset((void *)((uintptr_t)newptr + oldsize), 0,
+                                   size - oldsize);
+                       }
+                       return (newptr);
+               }
+       }
+
+       /*
+        * If we get here, then size and oldsize are different enough that we
+        * need to use a different size class.  In that case, fall back to
+        * allocating new space and copying.
+        */
+       ret = huge_malloc(size);
+       if (ret == NULL)
+               return (NULL);
+
+       if (CHUNK_ADDR2BASE(ptr) == ptr) {
+               /* The old allocation is a chunk. */
+               if (size < oldsize)
+                       memcpy(ret, ptr, size);
+               else
+                       memcpy(ret, ptr, oldsize);
+       } else {
+               /* The old allocation is a region. */
+               assert(oldsize < size);
+               memcpy(ret, ptr, oldsize);
+       }
+       idalloc(ptr);
+       return (ret);
+}
+
+static void
+huge_dalloc(void *ptr)
+{
+       chunk_node_t key;
+       chunk_node_t *node;
+
+       malloc_mutex_lock(&chunks_mtx);
+
+       /* Extract from tree of huge allocations. */
+       key.chunk = ptr;
+       /* LINTED */
+       node = RB_FIND(chunk_tree_s, &huge, &key);
+       assert(node != NULL);
+       assert(node->chunk == ptr);
+       /* LINTED */
+       RB_REMOVE(chunk_tree_s, &huge, node);
+
+#ifdef MALLOC_STATS
+       huge_ndalloc++;
+       huge_allocated -= node->size;
+#endif
+
+       malloc_mutex_unlock(&chunks_mtx);
+
+       /* Unmap chunk. */
+#ifdef USE_BRK
+       if (opt_junk)
+               memset(node->chunk, 0x5a, node->size);
+#endif
+       chunk_dealloc(node->chunk, node->size);
+
+       base_chunk_node_dealloc(node);
+}
+
+static void *
+imalloc(size_t size)
+{
+       void *ret;
+
+       assert(size != 0);
+
+       if (size <= arena_maxclass)
+               ret = arena_malloc(choose_arena(), size);
+       else
+               ret = huge_malloc(size);
+
+       return (ret);
+}
+
+static void *
+ipalloc(size_t alignment, size_t size)
+{
+       void *ret;
+       size_t ceil_size;
+
+       /*
+        * Round size up to the nearest multiple of alignment.
+        *
+        * This done, we can take advantage of the fact that for each small
+        * size class, every object is aligned at the smallest power of two
+        * that is non-zero in the base two representation of the size.  For
+        * example:
+        *
+        *   Size |   Base 2 | Minimum alignment
+        *   -----+----------+------------------
+        *     96 |  1100000 |  32
+        *    144 | 10100000 |  32
+        *    192 | 11000000 |  64
+        *
+        * Depending on runtime settings, it is possible that arena_malloc()
+        * will further round up to a power of two, but that never causes
+        * correctness issues.
+        */
+       ceil_size = (size + (alignment - 1)) & (-alignment);
+       /*
+        * (ceil_size < size) protects against the combination of maximal
+        * alignment and size greater than maximal alignment.
+        */
+       if (ceil_size < size) {
+               /* size_t overflow. */
+               return (NULL);
+       }
+
+       if (ceil_size <= pagesize || (alignment <= pagesize
+           && ceil_size <= arena_maxclass))
+               ret = arena_malloc(choose_arena(), ceil_size);
+       else {
+               size_t run_size;
+
+               /*
+                * We can't achieve sub-page alignment, so round up alignment
+                * permanently; it makes later calculations simpler.
+                */
+               alignment = PAGE_CEILING(alignment);
+               ceil_size = PAGE_CEILING(size);
+               /*
+                * (ceil_size < size) protects against very large sizes within
+                * pagesize of SIZE_T_MAX.
+                *
+                * (ceil_size + alignment < ceil_size) protects against the
+                * combination of maximal alignment and ceil_size large enough
+                * to cause overflow.  This is similar to the first overflow
+                * check above, but it needs to be repeated due to the new
+                * ceil_size value, which may now be *equal* to maximal
+                * alignment, whereas before we only detected overflow if the
+                * original size was *greater* than maximal alignment.
+                */
+               if (ceil_size < size || ceil_size + alignment < ceil_size) {
+                       /* size_t overflow. */
+                       return (NULL);
+               }
+
+               /*
+                * Calculate the size of the over-size run that arena_palloc()
+                * would need to allocate in order to guarantee the alignment.
+                */
+               if (ceil_size >= alignment)
+                       run_size = ceil_size + alignment - pagesize;
+               else {
+                       /*
+                        * It is possible that (alignment << 1) will cause
+                        * overflow, but it doesn't matter because we also
+                        * subtract pagesize, which in the case of overflow
+                        * leaves us with a very large run_size.  That causes
+                        * the first conditional below to fail, which means
+                        * that the bogus run_size value never gets used for
+                        * anything important.
+                        */
+                       run_size = (alignment << 1) - pagesize;
+               }
+
+               if (run_size <= arena_maxclass) {
+                       ret = arena_palloc(choose_arena(), alignment, ceil_size,
+                           run_size);
+               } else if (alignment <= chunksize)
+                       ret = huge_malloc(ceil_size);
+               else
+                       ret = huge_palloc(alignment, ceil_size);
+       }
+
+       assert(((uintptr_t)ret & (alignment - 1)) == 0);
+       return (ret);
+}
+
+static void *
+icalloc(size_t size)
+{
+       void *ret;
+
+       if (size <= arena_maxclass) {
+               ret = arena_malloc(choose_arena(), size);
+               if (ret == NULL)
+                       return (NULL);
+               memset(ret, 0, size);
+       } else {
+               /*
+                * The virtual memory system provides zero-filled pages, so
+                * there is no need to do so manually, unless opt_junk is
+                * enabled, in which case huge_malloc() fills huge allocations
+                * with junk.
+                */
+               ret = huge_malloc(size);
+               if (ret == NULL)
+                       return (NULL);
+
+               if (opt_junk)
+                       memset(ret, 0, size);
+#ifdef USE_BRK
+               else if ((uintptr_t)ret >= (uintptr_t)brk_base
+                   && (uintptr_t)ret < (uintptr_t)brk_max) {
+                       /*
+                        * This may be a re-used brk chunk.  Therefore, zero
+                        * the memory.
+                        */
+                       memset(ret, 0, size);
+               }
+#endif
+       }
+
+       return (ret);
+}
+
+static size_t
+isalloc(const void *ptr)
+{
+       size_t ret;
+       arena_chunk_t *chunk;
+
+       assert(ptr != NULL);
+
+       chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
+       if (chunk != ptr) {
+               /* Region. */
+               assert(chunk->arena->magic == ARENA_MAGIC);
+
+               ret = arena_salloc(ptr);
+       } else {
+               chunk_node_t *node, key;
+
+               /* Chunk (huge allocation). */
+
+               malloc_mutex_lock(&chunks_mtx);
+
+               /* Extract from tree of huge allocations. */
+               key.chunk = __DECONST(void *, ptr);
+               /* LINTED */
+               node = RB_FIND(chunk_tree_s, &huge, &key);
+               assert(node != NULL);
+
+               ret = node->size;
+
+               malloc_mutex_unlock(&chunks_mtx);
+       }
+
+       return (ret);
+}
+
+static void *
+iralloc(void *ptr, size_t size)
+{
+       void *ret;
+       size_t oldsize;
+
+       assert(ptr != NULL);
+       assert(size != 0);
+
+       oldsize = isalloc(ptr);
+
+       if (size <= arena_maxclass)
+               ret = arena_ralloc(ptr, size, oldsize);
+       else
+               ret = huge_ralloc(ptr, size, oldsize);
+
+       return (ret);
+}
+
+static void
+idalloc(void *ptr)
+{
+       arena_chunk_t *chunk;
+
+       assert(ptr != NULL);
+
+       chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
+       if (chunk != ptr) {
+               /* Region. */
+               arena_dalloc(chunk->arena, chunk, ptr);
+       } else
+               huge_dalloc(ptr);
+}
+
+static void
+malloc_print_stats(void)
+{
+
+       if (opt_print_stats) {
+               char s[UMAX2S_BUFSIZE];
+               _malloc_message("___ Begin malloc statistics ___\n", "", "",
+                   "");
+               _malloc_message("Assertions ",
+#ifdef NDEBUG
+                   "disabled",
+#else
+                   "enabled",
+#endif
+                   "\n", "");
+               _malloc_message("Boolean MALLOC_OPTIONS: ",
+                   opt_abort ? "A" : "a",
+                   opt_junk ? "J" : "j",
+                   opt_hint ? "H" : "h");
+               _malloc_message(opt_utrace ? "PU" : "Pu",
+                   opt_sysv ? "V" : "v",
+                   opt_xmalloc ? "X" : "x",
+                   opt_zero ? "Z\n" : "z\n");
+
+               _malloc_message("CPUs: ", umax2s(ncpus, s), "\n", "");
+               _malloc_message("Max arenas: ", umax2s(narenas, s), "\n", "");
+               _malloc_message("Pointer size: ", umax2s(sizeof(void *), s),
+                   "\n", "");
+               _malloc_message("Quantum size: ", umax2s(quantum, s), "\n", "");
+               _malloc_message("Max small size: ", umax2s(small_max, s), "\n",
+                   "");
+
+               _malloc_message("Chunk size: ", umax2s(chunksize, s), "", "");
+               _malloc_message(" (2^", umax2s(opt_chunk_2pow, s), ")\n", "");
+
+#ifdef MALLOC_STATS
+               {
+                       size_t allocated, mapped;
+                       unsigned i;
+                       arena_t *arena;
+
+                       /* Calculate and print allocated/mapped stats. */
+
+                       /* arenas. */
+                       for (i = 0, allocated = 0; i < narenas; i++) {
+                               if (arenas[i] != NULL) {
+                                       malloc_mutex_lock(&arenas[i]->mtx);
+                                       allocated +=
+                                           arenas[i]->stats.allocated_small;
+                                       allocated +=
+                                           arenas[i]->stats.allocated_large;
+                                       malloc_mutex_unlock(&arenas[i]->mtx);
+                               }
+                       }
+
+                       /* huge/base. */
+                       malloc_mutex_lock(&chunks_mtx);
+                       allocated += huge_allocated;
+                       mapped = stats_chunks.curchunks * chunksize;
+                       malloc_mutex_unlock(&chunks_mtx);
+
+                       malloc_mutex_lock(&base_mtx);
+                       mapped += base_mapped;
+                       malloc_mutex_unlock(&base_mtx);
+
+                       malloc_printf("Allocated: %zu, mapped: %zu\n",
+                           allocated, mapped);
+
+                       /* Print chunk stats. */
+                       {
+                               chunk_stats_t chunks_stats;
+
+                               malloc_mutex_lock(&chunks_mtx);
+                               chunks_stats = stats_chunks;
+                               malloc_mutex_unlock(&chunks_mtx);
+
+                               malloc_printf("chunks: nchunks   "
+                                   "highchunks    curchunks\n");
+                               malloc_printf("  %13llu%13lu%13lu\n",
+                                   chunks_stats.nchunks,
+                                   chunks_stats.highchunks,
+                                   chunks_stats.curchunks);
+                       }
+
+                       /* Print chunk stats. */
+                       malloc_printf(
+                           "huge: nmalloc      ndalloc      "
+                           "nralloc    allocated\n");
+                       malloc_printf(" %12llu %12llu %12llu %12zu\n",
+                           huge_nmalloc, huge_ndalloc, huge_nralloc,
+                           huge_allocated);
+
+                       /* Print stats for each arena. */
+                       for (i = 0; i < narenas; i++) {
+                               arena = arenas[i];
+                               if (arena != NULL) {
+                                       malloc_printf(
+                                           "\narenas[%u] @ %p\n", i, arena);
+                                       malloc_mutex_lock(&arena->mtx);
+                                       stats_print(arena);
+                                       malloc_mutex_unlock(&arena->mtx);
+                               }
+                       }
+               }
+#endif /* #ifdef MALLOC_STATS */
+               _malloc_message("--- End malloc statistics ---\n", "", "", "");
+       }
+}
+
+/*
+ * FreeBSD's pthreads implementation calls malloc(3), so the malloc
+ * implementation has to take pains to avoid infinite recursion during
+ * initialization.
+ */
+static inline bool
+malloc_init(void)
+{
+
+       if (malloc_initialized == false)
+               return (malloc_init_hard());
+
+       return (false);
+}
+
+static bool
+malloc_init_hard(void)
+{
+       unsigned i, j;
+       ssize_t linklen;
+       char buf[PATH_MAX + 1];
+       const char *opts = "";
+
+       malloc_mutex_lock(&init_lock);
+       if (malloc_initialized) {
+               /*
+                * Another thread initialized the allocator before this one
+                * acquired init_lock.
+                */
+               malloc_mutex_unlock(&init_lock);
+               return (false);
+       }
+
+       /* Get number of CPUs. */
+       {
+               int mib[2];
+               size_t len;
+
+               mib[0] = CTL_HW;
+               mib[1] = HW_NCPU;
+               len = sizeof(ncpus);
+               if (sysctl(mib, 2, &ncpus, &len, (void *) 0, 0) == -1) {
+                       /* Error. */
+                       ncpus = 1;
+               }
+       }
+
+       /* Get page size. */
+       {
+               long result;
+
+               result = sysconf(_SC_PAGESIZE);
+               assert(result != -1);
+               pagesize = (unsigned) result;
+
+               /*
+                * We assume that pagesize is a power of 2 when calculating
+                * pagesize_mask and pagesize_2pow.
+                */
+               assert(((result - 1) & result) == 0);
+               pagesize_mask = result - 1;
+               pagesize_2pow = ffs((int)result) - 1;
+       }
+
+       for (i = 0; i < 3; i++) {
+               /* Get runtime configuration. */
+               switch (i) {
+               case 0:
+                       if ((linklen = readlink("/etc/malloc.conf", buf,
+                                               sizeof(buf) - 1)) != -1) {
+                               /*
+                                * Use the contents of the "/etc/malloc.conf"
+                                * symbolic link's name.
+                                */
+                               buf[linklen] = '\0';
+                               opts = buf;
+                       } else {
+                               /* No configuration specified. */
+                               buf[0] = '\0';
+                               opts = buf;
+                       }
+                       break;
+               case 1:
+                       if ((opts = getenv("MALLOC_OPTIONS")) != NULL &&
+                           issetugid() == 0) {
+                               /*
+                                * Do nothing; opts is already initialized to
+                                * the value of the MALLOC_OPTIONS environment
+                                * variable.
+                                */
+                       } else {
+                               /* No configuration specified. */
+                               buf[0] = '\0';
+                               opts = buf;
+                       }
+                       break;
+               case 2:
+                       if (_malloc_options != NULL) {
+                           /*
+                            * Use options that were compiled into the program.
+                            */
+                           opts = _malloc_options;
+                       } else {
+                               /* No configuration specified. */
+                               buf[0] = '\0';
+                               opts = buf;
+                       }
+                       break;
+               default:
+                       /* NOTREACHED */
+                       /* LINTED */
+                       assert(false);
+               }
+
+               for (j = 0; opts[j] != '\0'; j++) {
+                       switch (opts[j]) {
+                       case 'a':
+                               opt_abort = false;
+                               break;
+                       case 'A':
+                               opt_abort = true;
+                               break;
+                       case 'h':
+                               opt_hint = false;
+                               break;
+                       case 'H':
+                               opt_hint = true;
+                               break;
+                       case 'j':
+                               opt_junk = false;
+                               break;
+                       case 'J':
+                               opt_junk = true;
+                               break;
+                       case 'k':
+                               /*
+                                * Chunks always require at least one header
+                                * page, so chunks can never be smaller than
+                                * two pages.
+                                */
+                               if (opt_chunk_2pow > pagesize_2pow + 1)
+                                       opt_chunk_2pow--;
+                               break;
+                       case 'K':
+                               if (opt_chunk_2pow + 1 <
+                                   (int)(sizeof(size_t) << 3))
+                                       opt_chunk_2pow++;
+                               break;
+                       case 'n':
+                               opt_narenas_lshift--;
+                               break;
+                       case 'N':
+                               opt_narenas_lshift++;
+                               break;
+                       case 'p':
+                               opt_print_stats = false;
+                               break;
+                       case 'P':
+                               opt_print_stats = true;
+                               break;
+                       case 'q':
+                               if (opt_quantum_2pow > QUANTUM_2POW_MIN)
+                                       opt_quantum_2pow--;
+                               break;
+                       case 'Q':
+                               if (opt_quantum_2pow < pagesize_2pow - 1)
+                                       opt_quantum_2pow++;
+                               break;
+                       case 's':
+                               if (opt_small_max_2pow > QUANTUM_2POW_MIN)
+                                       opt_small_max_2pow--;
+                               break;
+                       case 'S':
+                               if (opt_small_max_2pow < pagesize_2pow - 1)
+                                       opt_small_max_2pow++;
+                               break;
+                       case 'u':
+                               opt_utrace = false;
+                               break;
+                       case 'U':
+                               opt_utrace = true;
+                               break;
+                       case 'v':
+                               opt_sysv = false;
+                               break;
+                       case 'V':
+                               opt_sysv = true;
+                               break;
+                       case 'x':
+                               opt_xmalloc = false;
+                               break;
+                       case 'X':
+                               opt_xmalloc = true;
+                               break;
+                       case 'z':
+                               opt_zero = false;
+                               break;
+                       case 'Z':
+                               opt_zero = true;
+                               break;
+                       default: {
+                               char cbuf[2];
+                               
+                               cbuf[0] = opts[j];
+                               cbuf[1] = '\0';
+                               _malloc_message(getprogname(),
+                                   ": (malloc) Unsupported character in "
+                                   "malloc options: '", cbuf, "'\n");
+                       }
+                       }
+               }
+       }
+
+       /* Take care to call atexit() only once. */
+       if (opt_print_stats) {
+               /* Print statistics at exit. */
+               atexit(malloc_print_stats);
+       }
+
+       /* Set variables according to the value of opt_small_max_2pow. */
+       if (opt_small_max_2pow < opt_quantum_2pow)
+               opt_small_max_2pow = opt_quantum_2pow;
+       small_max = (1 << opt_small_max_2pow);
+
+       /* Set bin-related variables. */
+       bin_maxclass = (pagesize >> 1);
+       assert(opt_quantum_2pow >= TINY_MIN_2POW);
+       ntbins = (unsigned)(opt_quantum_2pow - TINY_MIN_2POW);
+       assert(ntbins <= opt_quantum_2pow);
+       nqbins = (unsigned)(small_max >> opt_quantum_2pow);
+       nsbins = (unsigned)(pagesize_2pow - opt_small_max_2pow - 1);
+
+       /* Set variables according to the value of opt_quantum_2pow. */
+       quantum = (1 << opt_quantum_2pow);
+       quantum_mask = quantum - 1;
+       if (ntbins > 0)
+               small_min = (quantum >> 1) + 1;
+       else
+               small_min = 1;
+       assert(small_min <= quantum);
+
+       /* Set variables according to the value of opt_chunk_2pow. */
+       chunksize = (1LU << opt_chunk_2pow);
+       chunksize_mask = chunksize - 1;
+       chunksize_2pow = (unsigned)opt_chunk_2pow;
+       chunk_npages = (unsigned)(chunksize >> pagesize_2pow);
+       {
+               unsigned header_size;
+
+               header_size = (unsigned)(sizeof(arena_chunk_t) +
+                   (sizeof(arena_chunk_map_t) * (chunk_npages - 1)));
+               arena_chunk_header_npages = (header_size >> pagesize_2pow);
+               if ((header_size & pagesize_mask) != 0)
+                       arena_chunk_header_npages++;
+       }
+       arena_maxclass = chunksize - (arena_chunk_header_npages <<
+           pagesize_2pow);
+
+       UTRACE(0, 0, 0);
+
+#ifdef MALLOC_STATS
+       memset(&stats_chunks, 0, sizeof(chunk_stats_t));
+#endif
+
+       /* Various sanity checks that regard configuration. */
+       assert(quantum >= sizeof(void *));
+       assert(quantum <= pagesize);
+       assert(chunksize >= pagesize);
+       assert(quantum * 4 <= chunksize);
+
+       /* Initialize chunks data. */
+       malloc_mutex_init(&chunks_mtx);
+       RB_INIT(&huge);
+#ifdef USE_BRK
+       malloc_mutex_init(&brk_mtx);
+       brk_base = sbrk(0);
+       brk_prev = brk_base;
+       brk_max = brk_base;
+#endif
+#ifdef MALLOC_STATS
+       huge_nmalloc = 0;
+       huge_ndalloc = 0;
+       huge_nralloc = 0;
+       huge_allocated = 0;
+#endif
+       RB_INIT(&old_chunks);
+
+       /* Initialize base allocation data structures. */
+#ifdef MALLOC_STATS
+       base_mapped = 0;
+#endif
+#ifdef USE_BRK
+       /*
+        * Allocate a base chunk here, since it doesn't actually have to be
+        * chunk-aligned.  Doing this before allocating any other chunks allows
+        * the use of space that would otherwise be wasted.
+        */
+       base_pages_alloc(0);
+#endif
+       base_chunk_nodes = NULL;
+       malloc_mutex_init(&base_mtx);
+
+       if (ncpus > 1) {
+               /*
+                * For SMP systems, create four times as many arenas as there
+                * are CPUs by default.
+                */
+               opt_narenas_lshift += 2;
+       }
+
+#ifdef NO_TLS
+       /* Initialize arena key. */
+       (void)thr_keycreate(&arenas_map_key, NULL);
+#endif
+
+       /* Determine how many arenas to use. */
+       narenas = ncpus;
+       if (opt_narenas_lshift > 0) {
+               if ((narenas << opt_narenas_lshift) > narenas)
+                       narenas <<= opt_narenas_lshift;
+               /*
+                * Make sure not to exceed the limits of what base_malloc()
+                * can handle.
+                */
+               if (narenas * sizeof(arena_t *) > chunksize)
+                       narenas = (unsigned)(chunksize / sizeof(arena_t *));
+       } else if (opt_narenas_lshift < 0) {
+               if ((narenas << opt_narenas_lshift) < narenas)
+                       narenas <<= opt_narenas_lshift;
+               /* Make sure there is at least one arena. */
+               if (narenas == 0)
+                       narenas = 1;
+       }
+
+       next_arena = 0;
+
+       /* Allocate and initialize arenas. */
+       arenas = (arena_t **)base_alloc(sizeof(arena_t *) * narenas);
+       if (arenas == NULL) {
+               malloc_mutex_unlock(&init_lock);
+               return (true);
+       }
+       /*
+        * Zero the array.  In practice, this should always be pre-zeroed,
+        * since it was just mmap()ed, but let's be sure.
+        */
+       memset(arenas, 0, sizeof(arena_t *) * narenas);
+
+       /*
+        * Initialize one arena here.  The rest are lazily created in
+        * arena_choose_hard().
+        */
+       arenas_extend(0);
+       if (arenas[0] == NULL) {
+               malloc_mutex_unlock(&init_lock);
+               return (true);
+       }
+
+       malloc_mutex_init(&arenas_mtx);
+
+       malloc_initialized = true;
+       malloc_mutex_unlock(&init_lock);
+       return (false);
+}
+
+/*
+ * End general internal functions.
+ */
+/******************************************************************************/
+/*
+ * Begin malloc(3)-compatible functions.
+ */
+
+void *
+malloc(size_t size)
+{
+       void *ret;
+
+       if (malloc_init()) {
+               ret = NULL;
+               goto RETURN;
+       }
+
+       if (size == 0) {
+               if (opt_sysv == false)
+                       size = 1;
+               else {
+                       ret = NULL;
+                       goto RETURN;
+               }
+       }
+
+       ret = imalloc(size);
+
+RETURN:
+       if (ret == NULL) {
+               if (opt_xmalloc) {
+                       _malloc_message(getprogname(),
+                           ": (malloc) Error in malloc(): out of memory\n", "",
+                           "");
+                       abort();
+               }
+               errno = ENOMEM;
+       }
+
+       UTRACE(0, size, ret);
+       return (ret);
+}
+
+int
+posix_memalign(void **memptr, size_t alignment, size_t size)
+{
+       int ret;
+       void *result;
+
+       if (malloc_init())
+               result = NULL;
+       else {
+               /* Make sure that alignment is a large enough power of 2. */
+               if (((alignment - 1) & alignment) != 0
+                   || alignment < sizeof(void *)) {
+                       if (opt_xmalloc) {
+                               _malloc_message(getprogname(),
+                                   ": (malloc) Error in posix_memalign(): "
+                                   "invalid alignment\n", "", "");
+                               abort();
+                       }
+                       result = NULL;
+                       ret = EINVAL;
+                       goto RETURN;
+               }
+
+               result = ipalloc(alignment, size);
+       }
+
+       if (result == NULL) {
+               if (opt_xmalloc) {
+                       _malloc_message(getprogname(),
+                       ": (malloc) Error in posix_memalign(): out of memory\n",
+                       "", "");
+                       abort();
+               }
+               ret = ENOMEM;
+               goto RETURN;
+       }
+
+       *memptr = result;
+       ret = 0;
+
+RETURN:
+       UTRACE(0, size, result);
+       return (ret);
+}
+
+void *
+calloc(size_t num, size_t size)
+{
+       void *ret;
+       size_t num_size;
+
+       if (malloc_init()) {
+               num_size = 0;
+               ret = NULL;
+               goto RETURN;
+       }
+
+       num_size = num * size;
+       if (num_size == 0) {
+               if ((opt_sysv == false) && ((num == 0) || (size == 0)))
+                       num_size = 1;
+               else {
+                       ret = NULL;
+                       goto RETURN;
+               }
+       /*
+        * Try to avoid division here.  We know that it isn't possible to
+        * overflow during multiplication if neither operand uses any of the
+        * most significant half of the bits in a size_t.
+        */
+       } else if ((unsigned long long)((num | size) &
+          ((unsigned long long)SIZE_T_MAX << (sizeof(size_t) << 2))) &&
+          (num_size / size != num)) {
+               /* size_t overflow. */
+               ret = NULL;
+               goto RETURN;
+       }
+
+       ret = icalloc(num_size);
+
+RETURN:
+       if (ret == NULL) {
+               if (opt_xmalloc) {
+                       _malloc_message(getprogname(),
+                           ": (malloc) Error in calloc(): out of memory\n", "",
+                           "");
+                       abort();
+               }
+               errno = ENOMEM;
+       }
+
+       UTRACE(0, num_size, ret);
+       return (ret);
+}
+
+void *
+realloc(void *ptr, size_t size)
+{
+       void *ret;
+
+       if (size == 0) {
+               if (opt_sysv == false)
+                       size = 1;
+               else {
+                       if (ptr != NULL)
+                               idalloc(ptr);
+                       ret = NULL;
+                       goto RETURN;
+               }
+       }
+
+       if (ptr != NULL) {
+               assert(malloc_initialized);
+
+               ret = iralloc(ptr, size);
+
+               if (ret == NULL) {
+                       if (opt_xmalloc) {
+                               _malloc_message(getprogname(),
+                                   ": (malloc) Error in realloc(): out of "
+                                   "memory\n", "", "");
+                               abort();
+                       }
+                       errno = ENOMEM;
+               }
+       } else {
+               if (malloc_init())
+                       ret = NULL;
+               else
+                       ret = imalloc(size);
+
+               if (ret == NULL) {
+                       if (opt_xmalloc) {
+                               _malloc_message(getprogname(),
+                                   ": (malloc) Error in realloc(): out of "
+                                   "memory\n", "", "");
+                               abort();
+                       }
+                       errno = ENOMEM;
+               }
+       }
+
+RETURN:
+       UTRACE(ptr, size, ret);
+       return (ret);
+}
+
+void
+free(void *ptr)
+{
+
+       UTRACE(ptr, 0, 0);
+       if (ptr != NULL) {
+               assert(malloc_initialized);
+
+               idalloc(ptr);
+       }
+}
+
+/*
+ * End malloc(3)-compatible functions.
+ */
+/******************************************************************************/
+/*
+ * Begin non-standard functions.
+ */
+#ifndef __NetBSD__
+size_t
+malloc_usable_size(const void *ptr)
+{
+
+       assert(ptr != NULL);
+
+       return (isalloc(ptr));
+}
+#endif
+
+/*
+ * End non-standard functions.
+ */
+/******************************************************************************/
+/*
+ * Begin library-private functions, used by threading libraries for protection
+ * of malloc during fork().  These functions are only called if the program is
+ * running in threaded mode, so there is no need to check whether the program
+ * is threaded here.
+ */
+
+void
+_malloc_prefork(void)
+{
+       unsigned i;
+
+       /* Acquire all mutexes in a safe order. */
+
+       malloc_mutex_lock(&arenas_mtx);
+       for (i = 0; i < narenas; i++) {
+               if (arenas[i] != NULL)
+                       malloc_mutex_lock(&arenas[i]->mtx);
+       }
+       malloc_mutex_unlock(&arenas_mtx);
+
+       malloc_mutex_lock(&base_mtx);
+
+       malloc_mutex_lock(&chunks_mtx);
+}
+
+void
+_malloc_postfork(void)
+{
+       unsigned i;
+
+       /* Release all mutexes, now that fork() has completed. */
+
+       malloc_mutex_unlock(&chunks_mtx);
+
+       malloc_mutex_unlock(&base_mtx);
+
+       malloc_mutex_lock(&arenas_mtx);
+       for (i = 0; i < narenas; i++) {
+               if (arenas[i] != NULL)
+                       malloc_mutex_unlock(&arenas[i]->mtx);
+       }
+       malloc_mutex_unlock(&arenas_mtx);
+}
+
+/*
+ * End library-private functions.
+ */
+/******************************************************************************/
diff --git a/lib/nbsd_libc/stdlib/jrand48.c b/lib/nbsd_libc/stdlib/jrand48.c
new file mode 100644 (file)
index 0000000..0ab594e
--- /dev/null
@@ -0,0 +1,39 @@
+/*     $NetBSD: jrand48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $        */
+
+/*
+ * Copyright (c) 1993 Martin Birgmeier
+ * All rights reserved.
+ *
+ * You may redistribute unmodified or modified versions of this source
+ * code provided that the above copyright notice and this and the
+ * following conditions are retained.
+ *
+ * This software is provided ``as is'', and comes with no warranties
+ * of any kind. I shall in no event be liable for anything that happens
+ * to anyone/anything when using this software.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: jrand48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+
+#include "rand48.h"
+
+#ifdef __weak_alias
+__weak_alias(jrand48,_jrand48)
+#endif
+
+long
+jrand48(unsigned short xseed[3])
+{
+
+       _DIAGASSERT(xseed != NULL);
+
+       __dorand48(xseed);
+       return ((long) xseed[2] << 16) + (long) xseed[1];
+}
diff --git a/lib/nbsd_libc/stdlib/l64a.c b/lib/nbsd_libc/stdlib/l64a.c
new file mode 100644 (file)
index 0000000..68f6251
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: l64a.c,v 1.13 2003/07/26 19:24:54 salo Exp $   */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: l64a.c,v 1.13 2003/07/26 19:24:54 salo Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(l64a,_l64a)
+__weak_alias(l64a_r,_l64a_r)
+#endif
+
+char *
+l64a (value)
+       long value;
+{
+       static char buf[8];
+
+       (void)l64a_r(value, buf, sizeof (buf));
+       return buf;
+}
+
+int
+l64a_r (value, buffer, buflen)
+       long value;
+       char *buffer;
+       int buflen;
+{
+       char *s = buffer;
+       int digit;
+       unsigned long v = value;
+
+       _DIAGASSERT(buffer != NULL);
+
+       if (value == 0UL) 
+               goto out;
+
+       for (; v != 0 && buflen > 1; s++, buflen--) {
+               digit = (int)(v & 0x3f);
+
+               if (digit < 2) 
+                       *s = digit + '.';
+               else if (digit < 12)
+                       *s = digit + '0' - 2;
+               else if (digit < 38)
+                       *s = digit + 'A' - 12;
+               else
+                       *s = digit + 'a' - 38;
+               v >>= 6;
+       }
+
+out:
+       *s = '\0';
+
+       return (v == 0UL ? 0 : -1);
+}
diff --git a/lib/nbsd_libc/stdlib/labs.3 b/lib/nbsd_libc/stdlib/labs.3
new file mode 100644 (file)
index 0000000..3d07816
--- /dev/null
@@ -0,0 +1,68 @@
+.\"    $NetBSD: labs.3,v 1.11 2008/08/04 21:29:27 matt Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)labs.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt LABS 3
+.Os
+.Sh NAME
+.Nm labs
+.Nd return the absolute value of a long integer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft long int
+.Fn labs "long int j"
+.Sh DESCRIPTION
+The
+.Fn labs
+function
+returns the absolute value of the long integer
+.Ar j .
+.Sh SEE ALSO
+.Xr abs 3 ,
+.Xr cabs 3 ,
+.Xr floor 3 ,
+.Xr imaxabs 3 ,
+.Xr llabs 3 ,
+.Xr math 3
+.Sh STANDARDS
+The
+.Fn labs
+function
+conforms to
+.St -ansiC .
+.Sh BUGS
+The absolute value of the most negative integer remains negative.
diff --git a/lib/nbsd_libc/stdlib/labs.c b/lib/nbsd_libc/stdlib/labs.c
new file mode 100644 (file)
index 0000000..a696228
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: labs.c,v 1.7 2003/08/07 16:43:41 agc Exp $     */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)labs.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: labs.c,v 1.7 2003/08/07 16:43:41 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdlib.h>
+
+long
+labs(j)
+       long j;
+{
+       return(j < 0 ? -j : j);
+}
diff --git a/lib/nbsd_libc/stdlib/lcong48.c b/lib/nbsd_libc/stdlib/lcong48.c
new file mode 100644 (file)
index 0000000..42ce979
--- /dev/null
@@ -0,0 +1,43 @@
+/*     $NetBSD: lcong48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $        */
+
+/*
+ * Copyright (c) 1993 Martin Birgmeier
+ * All rights reserved.
+ *
+ * You may redistribute unmodified or modified versions of this source
+ * code provided that the above copyright notice and this and the
+ * following conditions are retained.
+ *
+ * This software is provided ``as is'', and comes with no warranties
+ * of any kind. I shall in no event be liable for anything that happens
+ * to anyone/anything when using this software.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: lcong48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+
+#include "rand48.h"
+
+#ifdef __weak_alias
+__weak_alias(lcong48,_lcong48)
+#endif
+
+void
+lcong48(unsigned short p[7])
+{
+       _DIAGASSERT(p != NULL);
+
+       __rand48_seed[0] = p[0];
+       __rand48_seed[1] = p[1];
+       __rand48_seed[2] = p[2];
+       __rand48_mult[0] = p[3];
+       __rand48_mult[1] = p[4];
+       __rand48_mult[2] = p[5];
+       __rand48_add = p[6];
+}
diff --git a/lib/nbsd_libc/stdlib/ldiv.3 b/lib/nbsd_libc/stdlib/ldiv.3
new file mode 100644 (file)
index 0000000..95852ce
--- /dev/null
@@ -0,0 +1,73 @@
+.\"    $NetBSD: ldiv.3,v 1.13 2008/08/04 21:29:27 matt Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)ldiv.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt LDIV 3
+.Os
+.Sh NAME
+.Nm ldiv
+.Nd return quotient and remainder from division
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft ldiv_t
+.Fn ldiv "long int num" "long int denom"
+.Sh DESCRIPTION
+The
+.Fn ldiv
+function
+computes the value
+.Ar num/denom
+and returns the quotient and remainder in a structure named
+.Ar ldiv_t
+that contains two
+.Em long integer
+members named
+.Ar quot
+and
+.Ar rem .
+.Sh SEE ALSO
+.Xr div 3 ,
+.Xr imaxdiv 3 ,
+.Xr lldiv 3 ,
+.Xr math 3 ,
+.Xr qdiv 3
+.Sh STANDARDS
+The
+.Fn ldiv
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdlib/ldiv.c b/lib/nbsd_libc/stdlib/ldiv.c
new file mode 100644 (file)
index 0000000..4c72547
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: ldiv.c,v 1.7 2003/08/07 16:43:41 agc Exp $     */
+
+/*
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ldiv.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: ldiv.c,v 1.7 2003/08/07 16:43:41 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <stdlib.h>            /* ldiv_t */
+
+ldiv_t
+ldiv(num, denom)
+       long num, denom;
+{
+       ldiv_t r;
+
+       /* see div.c for comments */
+
+       r.quot = num / denom;
+       r.rem = num % denom;
+       if (num >= 0 && r.rem < 0) {
+               r.quot++;
+               r.rem -= denom;
+       }
+       return (r);
+}
diff --git a/lib/nbsd_libc/stdlib/llabs.3 b/lib/nbsd_libc/stdlib/llabs.3
new file mode 100644 (file)
index 0000000..f36619b
--- /dev/null
@@ -0,0 +1,68 @@
+.\"    $NetBSD: llabs.3,v 1.7 2008/08/04 21:29:27 matt Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)labs.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd March 6, 2000
+.Dt LLABS 3
+.Os
+.Sh NAME
+.Nm llabs
+.Nd return the absolute value of a long long integer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft long long int
+.Fn llabs "long long int j"
+.Sh DESCRIPTION
+The
+.Fn llabs
+function
+returns the absolute value of the long long integer
+.Ar j .
+.Sh SEE ALSO
+.Xr abs 3 ,
+.Xr cabs 3 ,
+.Xr floor 3 ,
+.Xr imaxabs 3 ,
+.Xr labs 3 ,
+.Xr math 3
+.Sh STANDARDS
+The
+.Fn llabs
+function
+conforms to
+.St -isoC-99 .
+.Sh BUGS
+The absolute value of the most negative integer remains negative.
diff --git a/lib/nbsd_libc/stdlib/llabs.c b/lib/nbsd_libc/stdlib/llabs.c
new file mode 100644 (file)
index 0000000..32b5ae2
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: llabs.c,v 1.3 2003/08/07 16:43:41 agc Exp $    */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "from: @(#)labs.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: llabs.c,v 1.3 2003/08/07 16:43:41 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(llabs, _llabs)
+#endif
+
+/* LONGLONG */
+long long int
+llabs(j)
+       long long int j;
+{
+       return (j < 0 ? -j : j);
+}
diff --git a/lib/nbsd_libc/stdlib/lldiv.3 b/lib/nbsd_libc/stdlib/lldiv.3
new file mode 100644 (file)
index 0000000..4d2ccb0
--- /dev/null
@@ -0,0 +1,73 @@
+.\"    $NetBSD: lldiv.3,v 1.7 2008/08/04 21:29:27 matt Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)ldiv.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd March 6, 2000
+.Dt LLDIV 3
+.Os
+.Sh NAME
+.Nm lldiv
+.Nd return quotient and remainder from division
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft lldiv_t
+.Fn lldiv "long long int num" "long long int denom"
+.Sh DESCRIPTION
+The
+.Fn lldiv
+function
+computes the value
+.Ar num/denom
+and returns the quotient and remainder in a structure named
+.Ar lldiv_t
+that contains two
+.Em long long integer
+members named
+.Ar quot
+and
+.Ar rem .
+.Sh SEE ALSO
+.Xr div 3 ,
+.Xr imaxdiv 3 ,
+.Xr ldiv 3 ,
+.Xr math 3 ,
+.Xr qdiv 3
+.Sh STANDARDS
+The
+.Fn lldiv
+function
+conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/stdlib/lldiv.c b/lib/nbsd_libc/stdlib/lldiv.c
new file mode 100644 (file)
index 0000000..589db7e
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: lldiv.c,v 1.3 2003/08/07 16:43:41 agc Exp $    */
+
+/*
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "from: @(#)ldiv.c       8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: lldiv.c,v 1.3 2003/08/07 16:43:41 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <stdlib.h>            /* lldiv_t */
+
+#ifdef __weak_alias
+__weak_alias(lldiv, _lldiv)
+#endif
+
+/* LONGLONG */
+lldiv_t
+lldiv(num, denom)
+       long long int num, denom;
+{
+       lldiv_t r;
+
+       /* see div.c for comments */
+
+       r.quot = num / denom;
+       r.rem = num % denom;
+       if (num >= 0 && r.rem < 0) {
+               r.quot++;
+               r.rem -= denom;
+       }
+       return (r);
+}
diff --git a/lib/nbsd_libc/stdlib/local.h b/lib/nbsd_libc/stdlib/local.h
new file mode 100644 (file)
index 0000000..285a9b4
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: local.h,v 1.6 2010/11/14 18:11:43 tron Exp $   */
+
+/*
+ * Copyright (c) 1997 Christos Zoulas.  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 ``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 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.
+ */
+
+/* Environment handling. */
+
+#include <sys/types.h>
+#include <stdbool.h>
+
+extern size_t __envvarnamelen(const char *str, bool withequal);
+
+extern void __freeenvvar(char *envvar);
+extern char *__allocenvvar(size_t length);
+extern bool __canoverwriteenvvar(char *envvar, size_t length);
diff --git a/lib/nbsd_libc/stdlib/lrand48.c b/lib/nbsd_libc/stdlib/lrand48.c
new file mode 100644 (file)
index 0000000..78f869e
--- /dev/null
@@ -0,0 +1,34 @@
+/*     $NetBSD: lrand48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $        */
+
+/*
+ * Copyright (c) 1993 Martin Birgmeier
+ * All rights reserved.
+ *
+ * You may redistribute unmodified or modified versions of this source
+ * code provided that the above copyright notice and this and the
+ * following conditions are retained.
+ *
+ * This software is provided ``as is'', and comes with no warranties
+ * of any kind. I shall in no event be liable for anything that happens
+ * to anyone/anything when using this software.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: lrand48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "rand48.h"
+
+#ifdef __weak_alias
+__weak_alias(lrand48,_lrand48)
+#endif
+
+long
+lrand48(void)
+{
+       __dorand48(__rand48_seed);
+       return (long)((unsigned long) __rand48_seed[2] << 15) +
+           ((unsigned long) __rand48_seed[1] >> 1);
+}
diff --git a/lib/nbsd_libc/stdlib/lsearch.3 b/lib/nbsd_libc/stdlib/lsearch.3
new file mode 100644 (file)
index 0000000..d34a5a8
--- /dev/null
@@ -0,0 +1,97 @@
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)lsearch.3    8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: lsearch.3,v 1.3 2005/07/12 08:28:42 wiz Exp $
+.\"
+.Dd July 6, 2005
+.Dt LSEARCH 3
+.Os
+.Sh NAME
+.Nm lsearch ,
+.Nm lfind
+.Nd linear searching routines
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In search.h
+.Ft void *
+.Fn lsearch "const void *key" "void *base" "size_t *nelp" "size_t width" "int (*compar)(const void *, const void *)"
+.Ft void *
+.Fn lfind "const void *key" "const void *base" "size_t *nelp" "size_t width" "int (*compar)(const void *, const void *)"
+.Sh DESCRIPTION
+The functions
+.Fn lsearch ,
+and
+.Fn lfind
+provide basic linear searching functionality.
+.Pp
+.Fa base
+is the pointer to the beginning of an array.
+The argument
+.Fa nelp
+is the current number of elements in the array, where each element
+is
+.Fa width
+bytes long.
+The
+.Fa compar
+argument points to a function which compares its two arguments and returns
+zero if they are matching, and non-zero otherwise.
+.Pp
+The
+.Fn lsearch
+and
+.Fn lfind
+functions
+return a pointer into the array referenced by
+.Fa base
+where
+.Fa key
+is located.
+If
+.Fa key
+does not exist,
+.Fn lfind
+will return a null pointer and
+.Fn lsearch
+will add it to the array.
+When an element is added to the array by
+.Fn lsearch
+the location referenced by the argument
+.Fa nelp
+is incremented by one.
+.Sh SEE ALSO
+.Xr bsearch 3 ,
+.Xr db 3
+.Sh STANDARDS
+The
+.Fn lsearch
+and
+.Fn lfind
+functions conform to
+.St -p1003.1-2001 .
diff --git a/lib/nbsd_libc/stdlib/lsearch.c b/lib/nbsd_libc/stdlib/lsearch.c
new file mode 100644 (file)
index 0000000..81d4e39
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Roger L. Snyder.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)lsearch.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: lsearch.c,v 1.4 2005/07/16 17:32:09 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <search.h>
+
+typedef int (*cmp_fn_t) __P((const void *, const void *));
+static void *linear_base __P((const void *, void *, size_t *, size_t,
+                            cmp_fn_t, int));
+
+void *
+lsearch(key, base, nelp, width, compar)
+       const void *key;
+       void *base;
+       size_t *nelp, width;
+       cmp_fn_t compar;
+{
+
+       _DIAGASSERT(key != NULL);
+       _DIAGASSERT(base != NULL);
+       _DIAGASSERT(compar != NULL);
+
+       return(linear_base(key, base, nelp, width, compar, 1));
+}
+
+void *
+lfind(key, base, nelp, width, compar)
+       const void *key, *base;
+       size_t *nelp, width;
+       cmp_fn_t compar;
+{
+
+       _DIAGASSERT(key != NULL);
+       _DIAGASSERT(base != NULL);
+       _DIAGASSERT(compar != NULL);
+
+       return(linear_base(key, __UNCONST(base), nelp, width, compar, 0));
+}
+
+static void *
+linear_base(key, base, nelp, width, compar, add_flag)
+       const void *key;
+       void *base;
+       size_t *nelp, width;
+       cmp_fn_t compar;
+       int add_flag;
+{
+       char *element, *end;
+
+       _DIAGASSERT(key != NULL);
+       _DIAGASSERT(base != NULL);
+       _DIAGASSERT(compar != NULL);
+
+       end = (char *)base + *nelp * width;
+       for (element = (char *)base; element < end; element += width)
+               if (!compar(element, key))              /* key found */
+                       return element;
+
+       if (!add_flag)                                  /* key not found */
+               return(NULL);
+
+       /*
+        * The UNIX System User's Manual, 1986 edition claims that
+        * a NULL pointer is returned by lsearch with errno set
+        * appropriately, if there is not enough room in the table
+        * to add a new item.  This can't be done as none of these
+        * routines have any method of determining the size of the
+        * table.  This comment isn't in the 1986-87 System V
+        * manual.
+        */
+       ++*nelp;
+       memcpy(end, key, width);
+       return end;
+}
diff --git a/lib/nbsd_libc/stdlib/malloc.3 b/lib/nbsd_libc/stdlib/malloc.3
new file mode 100644 (file)
index 0000000..1b892c8
--- /dev/null
@@ -0,0 +1,229 @@
+.\" $NetBSD: malloc.3,v 1.38 2010/05/03 08:23:20 jruoho Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)malloc.3   8.1 (Berkeley) 6/4/93
+.\" $FreeBSD: src/lib/libc/stdlib/malloc.3,v 1.73 2007/06/15 22:32:33 jasone Exp $
+.\"
+.Dd May 3, 2010
+.Dt MALLOC 3
+.Os
+.Sh NAME
+.Nm malloc , calloc , realloc , free
+.Nd general purpose memory allocation functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft void *
+.Fn malloc "size_t size"
+.Ft void *
+.Fn calloc "size_t number" "size_t size"
+.Ft void *
+.Fn realloc "void *ptr" "size_t size"
+.Ft void
+.Fn free "void *ptr"
+.Sh DESCRIPTION
+The
+.Fn malloc
+function allocates
+.Fa size
+bytes of uninitialized memory.
+The allocated space is suitably aligned (after possible pointer coercion)
+for storage of any type of object.
+.Pp
+The
+.Fn calloc
+function allocates space for
+.Fa number
+objects,
+each
+.Fa size
+bytes in length.
+The result is identical to calling
+.Fn malloc
+with an argument of
+.Dq "number * size" ,
+with the exception that the allocated memory is explicitly initialized
+to zero bytes.
+.Pp
+The
+.Fn realloc
+function changes the size of the previously allocated memory referenced by
+.Fa ptr
+to
+.Fa size
+bytes.
+The contents of the memory are unchanged up to the lesser of the new and
+old sizes.
+If the new size is larger,
+the value of the newly allocated portion of the memory is undefined.
+Upon success, the memory referenced by
+.Fa ptr
+is freed and a pointer to the newly allocated memory is returned.
+Note that
+.Fn realloc
+may move the memory allocation, resulting in a different return value than
+.Fa ptr .
+If
+.Fa ptr
+is
+.Dv NULL ,
+the
+.Fn realloc
+function behaves identically to
+.Fn malloc
+for the specified size.
+.Pp
+The
+.Fn free
+function causes the allocated memory referenced by
+.Fa ptr
+to be made available for future allocations.
+If
+.Fa ptr
+is
+.Dv NULL ,
+no action occurs.
+.Sh RETURN VALUES
+The
+.Fn malloc
+and
+.Fn calloc
+functions return a pointer to the allocated memory if successful; otherwise
+a
+.Dv NULL
+pointer is returned and
+.Va errno
+is set to
+.Er ENOMEM .
+.Pp
+The
+.Fn realloc
+function returns a pointer, possibly identical to
+.Fa ptr ,
+to the allocated memory
+if successful; otherwise a
+.Dv NULL
+pointer is returned, and
+.Va errno
+is set to
+.Er ENOMEM
+if the error was the result of an allocation failure.
+The
+.Fn realloc
+function always leaves the original buffer intact
+when an error occurs.
+.Pp
+The
+.Fn free
+function returns no value.
+.Sh EXAMPLES
+When using
+.Fn malloc ,
+be careful to avoid the following idiom:
+.Bd -literal -offset indent
+if ((p = malloc(number * size)) == NULL)
+       err(EXIT_FAILURE, "malloc");
+.Ed
+.Pp
+The multiplication may lead to an integer overflow.
+To avoid this,
+.Fn calloc
+is recommended.
+.Pp
+If
+.Fn malloc
+must be used, be sure to test for overflow:
+.Bd -literal -offset indent
+if (size && number > SIZE_MAX / size) {
+       errno = EOVERFLOW;
+       err(EXIT_FAILURE, "allocation");
+}
+.Ed
+.Pp
+When using
+.Fn realloc ,
+one must be careful to avoid the following idiom:
+.Pp
+.Bd -literal -offset indent
+nsize += 50;
+
+if ((p = realloc(p, nsize)) == NULL)
+       return NULL;
+.Ed
+.Pp
+Do not adjust the variable describing how much memory has been allocated
+until it is known that the allocation has been successful.
+This can cause aberrant program behavior if the incorrect size value is used.
+In most cases, the above example will also leak memory.
+As stated earlier, a return value of
+.Dv NULL
+indicates that the old object still remains allocated.
+Better code looks like this:
+.Bd -literal -offset indent
+newsize = size + 50;
+
+if ((p2 = realloc(p, newsize)) == NULL) {
+
+       if (p != NULL)
+               free(p);
+
+       p = NULL;
+       return NULL;
+}
+
+p = p2;
+size = newsize;
+.Ed
+.Sh SEE ALSO
+.\" .Xr limits 1 ,
+.Xr madvise 2 ,
+.Xr mmap 2 ,
+.Xr sbrk 2 ,
+.Xr alloca 3 ,
+.Xr atexit 3 ,
+.Xr getpagesize 3 ,
+.Xr memory 3 ,
+.Xr posix_memalign 3
+.Pp
+For the implementation details, see
+.Xr jemalloc 3 .
+.Sh STANDARDS
+The
+.Fn malloc ,
+.Fn calloc ,
+.Fn realloc
+and
+.Fn free
+functions conform to
+.St -isoC .
diff --git a/lib/nbsd_libc/stdlib/malloc.c b/lib/nbsd_libc/stdlib/malloc.c
new file mode 100644 (file)
index 0000000..7fccd87
--- /dev/null
@@ -0,0 +1,1290 @@
+/*     $NetBSD: malloc.c,v 1.52 2008/02/03 22:56:53 christos Exp $     */
+
+/*
+ * ----------------------------------------------------------------------------
+ * "THE BEER-WARE LICENSE" (Revision 42):
+ * <phk@FreeBSD.ORG> 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.   Poul-Henning Kamp
+ * ----------------------------------------------------------------------------
+ *
+ * From FreeBSD: malloc.c,v 1.91 2006/01/12 07:28:20 jasone
+ *
+ */
+
+/*
+ * Defining MALLOC_EXTRA_SANITY will enable extra checks which are related
+ * to internal conditions and consistency in malloc.c. This has a
+ * noticeable runtime performance hit, and generally will not do you
+ * any good unless you fiddle with the internals of malloc or want
+ * to catch random pointer corruption as early as possible.
+ */
+#ifndef MALLOC_EXTRA_SANITY
+#undef MALLOC_EXTRA_SANITY
+#endif
+
+/*
+ * What to use for Junk.  This is the byte value we use to fill with
+ * when the 'J' option is enabled.
+ */
+#define SOME_JUNK      0xd0            /* as in "Duh" :-) */
+
+/*
+ * The basic parameters you can tweak.
+ *
+ * malloc_minsize      minimum size of an allocation in bytes.
+ *                     If this is too small it's too much work
+ *                     to manage them.  This is also the smallest
+ *                     unit of alignment used for the storage
+ *                     returned by malloc/realloc.
+ *
+ */
+
+#include "namespace.h"
+#if defined(__FreeBSD__)
+#   if defined(__i386__)
+#       define malloc_minsize          16U
+#   endif
+#   if defined(__ia64__)
+#      define malloc_pageshift         13U
+#      define malloc_minsize           16U
+#   endif
+#   if defined(__alpha__)
+#       define malloc_pageshift                13U
+#       define malloc_minsize          16U
+#   endif
+#   if defined(__sparc64__)
+#       define malloc_pageshift                13U
+#       define malloc_minsize          16U
+#   endif
+#   if defined(__amd64__)
+#       define malloc_pageshift                12U
+#       define malloc_minsize          16U
+#   endif
+#   if defined(__arm__)
+#       define malloc_pageshift         12U
+#       define malloc_minsize           16U
+#   endif
+#   define HAS_UTRACE
+#   define UTRACE_LABEL
+
+#include <sys/cdefs.h>
+void utrace(struct ut *, int);
+
+    /*
+     * Make malloc/free/realloc thread-safe in libc for use with
+     * kernel threads.
+     */
+#   include "libc_private.h"
+#   include "spinlock.h"
+    static spinlock_t thread_lock      = _SPINLOCK_INITIALIZER;
+#   define _MALLOC_LOCK()              if (__isthreaded) _SPINLOCK(&thread_lock);
+#   define _MALLOC_UNLOCK()            if (__isthreaded) _SPINUNLOCK(&thread_lock);
+#endif /* __FreeBSD__ */
+
+#include <sys/types.h>
+#if defined(__NetBSD__)
+#   define malloc_minsize               16U
+#   define HAS_UTRACE
+#   define UTRACE_LABEL "malloc",
+#include <sys/cdefs.h>
+#include "extern.h"
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: malloc.c,v 1.52 2008/02/03 22:56:53 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+int utrace(const char *, void *, size_t);
+
+#include <reentrant.h>
+extern int __isthreaded;
+static mutex_t thread_lock = MUTEX_INITIALIZER;
+#define _MALLOC_LOCK() if (__isthreaded) mutex_lock(&thread_lock);
+#define _MALLOC_UNLOCK()       if (__isthreaded) mutex_unlock(&thread_lock);
+#endif /* __NetBSD__ */
+
+#if defined(__sparc__) && defined(sun)
+#   define malloc_minsize              16U
+#   define MAP_ANON                    (0)
+    static int fdzero;
+#   define MMAP_FD     fdzero
+#   define INIT_MMAP() \
+       { if ((fdzero = open(_PATH_DEVZERO, O_RDWR, 0000)) == -1) \
+           wrterror("open of /dev/zero"); }
+#endif /* __sparc__ */
+
+/* Insert your combination here... */
+#if defined(__FOOCPU__) && defined(__BAROS__)
+#   define malloc_minsize              16U
+#endif /* __FOOCPU__ && __BAROS__ */
+
+#ifndef ZEROSIZEPTR
+#define ZEROSIZEPTR    ((void *)(uintptr_t)(1UL << (malloc_pageshift - 1)))
+#endif
+
+/*
+ * No user serviceable parts behind this point.
+ */
+#include <sys/types.h>
+#include <sys/mman.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <paths.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+/*
+ * This structure describes a page worth of chunks.
+ */
+
+struct pginfo {
+    struct pginfo      *next;  /* next on the free list */
+    void               *page;  /* Pointer to the page */
+    u_short            size;   /* size of this page's chunks */
+    u_short            shift;  /* How far to shift for this size chunks */
+    u_short            free;   /* How many free chunks */
+    u_short            total;  /* How many chunk */
+    u_int              bits[1]; /* Which chunks are free */
+};
+
+/*
+ * This structure describes a number of free pages.
+ */
+
+struct pgfree {
+    struct pgfree      *next;  /* next run of free pages */
+    struct pgfree      *prev;  /* prev run of free pages */
+    void               *page;  /* pointer to free pages */
+    void               *end;   /* pointer to end of free pages */
+    size_t             size;   /* number of bytes free */
+};
+
+/*
+ * How many bits per u_int in the bitmap.
+ * Change only if not 8 bits/byte
+ */
+#define        MALLOC_BITS     ((int)(8*sizeof(u_int)))
+
+/*
+ * Magic values to put in the page_directory
+ */
+#define MALLOC_NOT_MINE        ((struct pginfo*) 0)
+#define MALLOC_FREE    ((struct pginfo*) 1)
+#define MALLOC_FIRST   ((struct pginfo*) 2)
+#define MALLOC_FOLLOW  ((struct pginfo*) 3)
+#define MALLOC_MAGIC   ((struct pginfo*) 4)
+
+/*
+ * Page size related parameters, computed at run-time.
+ */
+static size_t malloc_pagesize;
+static size_t malloc_pageshift;
+static size_t malloc_pagemask;
+
+#ifndef malloc_minsize
+#define malloc_minsize                 16U
+#endif
+
+#ifndef malloc_maxsize
+#define malloc_maxsize                 ((malloc_pagesize)>>1)
+#endif
+
+#define pageround(foo) (((foo) + (malloc_pagemask))&(~(malloc_pagemask)))
+#define ptr2idx(foo) \
+    (((size_t)(uintptr_t)(foo) >> malloc_pageshift)-malloc_origo)
+
+#ifndef _MALLOC_LOCK
+#define _MALLOC_LOCK()
+#endif
+
+#ifndef _MALLOC_UNLOCK
+#define _MALLOC_UNLOCK()
+#endif
+
+#ifndef MMAP_FD
+#define MMAP_FD (-1)
+#endif
+
+#ifndef INIT_MMAP
+#define INIT_MMAP()
+#endif
+
+#ifndef MADV_FREE
+#define MADV_FREE MADV_DONTNEED
+#endif
+
+/* Number of free pages we cache */
+static size_t malloc_cache = 16;
+
+/* The offset from pagenumber to index into the page directory */
+static size_t malloc_origo;
+
+/* The last index in the page directory we care about */
+static size_t last_idx;
+
+/* Pointer to page directory. Allocated "as if with" malloc */
+static struct  pginfo **page_dir;
+
+/* How many slots in the page directory */
+static size_t  malloc_ninfo;
+
+/* Free pages line up here */
+static struct pgfree free_list;
+
+/* Abort(), user doesn't handle problems.  */
+static int malloc_abort;
+
+/* Are we trying to die ?  */
+static int suicide;
+
+/* always realloc ?  */
+static int malloc_realloc;
+
+/* pass the kernel a hint on free pages ?  */
+#if defined(MADV_FREE)
+static int malloc_hint = 0;
+#endif
+
+/* xmalloc behaviour ?  */
+static int malloc_xmalloc;
+
+/* sysv behaviour for malloc(0) ?  */
+static int malloc_sysv;
+
+/* zero fill ?  */
+static int malloc_zero;
+
+/* junk fill ?  */
+static int malloc_junk;
+
+#ifdef HAS_UTRACE
+
+/* utrace ?  */
+static int malloc_utrace;
+
+struct ut { void *p; size_t s; void *r; };
+
+#define UTRACE(a, b, c) \
+       if (malloc_utrace) {                    \
+               struct ut u;                    \
+               u.p=a; u.s = b; u.r=c;          \
+               utrace(UTRACE_LABEL (void *) &u, sizeof u);     \
+       }
+#else /* !HAS_UTRACE */
+#define UTRACE(a,b,c)
+#endif /* HAS_UTRACE */
+
+/* my last break. */
+static void *malloc_brk;
+
+/* one location cache for free-list holders */
+static struct pgfree *px;
+
+/* compile-time options */
+const char *_malloc_options;
+
+/* Name of the current public function */
+static const char *malloc_func;
+
+/* Macro for mmap */
+#define MMAP(size) \
+       mmap(NULL, (size), PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, \
+           MMAP_FD, (off_t)0);
+
+/*
+ * Necessary function declarations
+ */
+static int extend_pgdir(size_t idx);
+static void *imalloc(size_t size);
+static void ifree(void *ptr);
+static void *irealloc(void *ptr, size_t size);
+
+static void
+wrtmessage(const char *p1, const char *p2, const char *p3, const char *p4)
+{
+
+    write(STDERR_FILENO, p1, strlen(p1));
+    write(STDERR_FILENO, p2, strlen(p2));
+    write(STDERR_FILENO, p3, strlen(p3));
+    write(STDERR_FILENO, p4, strlen(p4));
+}
+
+void (*_malloc_message)(const char *p1, const char *p2, const char *p3,
+           const char *p4) = wrtmessage;
+static void
+wrterror(const char *p)
+{
+
+    suicide = 1;
+    _malloc_message(getprogname(), malloc_func, " error: ", p);
+    abort();
+}
+
+static void
+wrtwarning(const char *p)
+{
+
+    /*
+     * Sensitive processes, somewhat arbitrarily defined here as setuid,
+     * setgid, root and wheel cannot afford to have malloc mistakes.
+     */
+    if (malloc_abort || issetugid() || getuid() == 0 || getgid() == 0)
+       wrterror(p);
+}
+
+/*
+ * Allocate a number of pages from the OS
+ */
+static void *
+map_pages(size_t pages)
+{
+    caddr_t result, rresult, tail;
+    intptr_t bytes = pages << malloc_pageshift;
+
+    if (bytes < 0 || (size_t)bytes < pages) {
+       errno = ENOMEM;
+       return NULL;
+    }
+
+    if ((result = sbrk(bytes)) == (void *)-1)
+       return NULL;
+
+    /*
+     * Round to a page, in case sbrk(2) did not do this for us
+     */
+    rresult = (caddr_t)pageround((size_t)(uintptr_t)result);
+    if (result < rresult) {
+       /* make sure we have enough space to fit bytes */
+       if (sbrk((intptr_t)(rresult - result)) == (void *) -1) {
+           /* we failed, put everything back */
+           if (brk(result)) {
+               wrterror("brk(2) failed [internal error]\n");
+           }
+       }
+    }
+    tail = rresult + (size_t)bytes;
+
+    last_idx = ptr2idx(tail) - 1;
+    malloc_brk = tail;
+
+    if ((last_idx+1) >= malloc_ninfo && !extend_pgdir(last_idx)) {
+       malloc_brk = result;
+       last_idx = ptr2idx(malloc_brk) - 1;
+       /* Put back break point since we failed. */
+       if (brk(malloc_brk))
+           wrterror("brk(2) failed [internal error]\n");
+       return 0;
+    }
+
+    return rresult;
+}
+
+/*
+ * Extend page directory
+ */
+static int
+extend_pgdir(size_t idx)
+{
+    struct  pginfo **new, **old;
+    size_t newlen, oldlen;
+
+    /* check for overflow */
+    if ((((~(1UL << ((sizeof(size_t) * NBBY) - 1)) / sizeof(*page_dir)) + 1)
+       + (malloc_pagesize / sizeof *page_dir)) < idx) {
+       errno = ENOMEM;
+       return 0;
+    }
+
+    /* Make it this many pages */
+    newlen = pageround(idx * sizeof *page_dir) + malloc_pagesize;
+
+    /* remember the old mapping size */
+    oldlen = malloc_ninfo * sizeof *page_dir;
+
+    /*
+     * NOTE: we allocate new pages and copy the directory rather than tempt
+     * fate by trying to "grow" the region.. There is nothing to prevent
+     * us from accidentally re-mapping space that's been allocated by our caller
+     * via dlopen() or other mmap().
+     *
+     * The copy problem is not too bad, as there is 4K of page index per
+     * 4MB of malloc arena.
+     *
+     * We can totally avoid the copy if we open a file descriptor to associate
+     * the anon mappings with.  Then, when we remap the pages at the new
+     * address, the old pages will be "magically" remapped..  But this means
+     * keeping open a "secret" file descriptor.....
+     */
+
+    /* Get new pages */
+    new = MMAP(newlen);
+    if (new == MAP_FAILED)
+       return 0;
+
+    /* Copy the old stuff */
+    memcpy(new, page_dir, oldlen);
+
+    /* register the new size */
+    malloc_ninfo = newlen / sizeof *page_dir;
+
+    /* swap the pointers */
+    old = page_dir;
+    page_dir = new;
+
+    /* Now free the old stuff */
+    munmap(old, oldlen);
+    return 1;
+}
+
+/*
+ * Initialize the world
+ */
+static void
+malloc_init(void)
+{
+    const char *p;
+    char b[64];
+    size_t i;
+    ssize_t j;
+    int save_errno = errno;
+
+    /*
+     * Compute page-size related variables.
+     */
+    malloc_pagesize = (size_t)sysconf(_SC_PAGESIZE);
+    malloc_pagemask = malloc_pagesize - 1;
+    for (malloc_pageshift = 0;
+        (1UL << malloc_pageshift) != malloc_pagesize;
+        malloc_pageshift++)
+       /* nothing */ ;
+
+    INIT_MMAP();
+
+#ifdef MALLOC_EXTRA_SANITY
+    malloc_junk = 1;
+#endif /* MALLOC_EXTRA_SANITY */
+
+    for (i = 0; i < 3; i++) {
+       if (i == 0) {
+           j = readlink("/etc/malloc.conf", b, sizeof b - 1);
+           if (j <= 0)
+               continue;
+           b[j] = '\0';
+           p = b;
+       } else if (i == 1 && issetugid() == 0) {
+           p = getenv("MALLOC_OPTIONS");
+       } else if (i == 1) {
+           continue;
+       } else {
+           p = _malloc_options;
+       }
+       for (; p != NULL && *p != '\0'; p++) {
+           switch (*p) {
+               case '>': malloc_cache   <<= 1; break;
+               case '<': malloc_cache   >>= 1; break;
+               case 'a': malloc_abort   = 0; break;
+               case 'A': malloc_abort   = 1; break;
+               case 'h': malloc_hint    = 0; break;
+               case 'H': malloc_hint    = 1; break;
+               case 'r': malloc_realloc = 0; break;
+               case 'R': malloc_realloc = 1; break;
+               case 'j': malloc_junk    = 0; break;
+               case 'J': malloc_junk    = 1; break;
+#ifdef HAS_UTRACE
+               case 'u': malloc_utrace  = 0; break;
+               case 'U': malloc_utrace  = 1; break;
+#endif
+               case 'v': malloc_sysv    = 0; break;
+               case 'V': malloc_sysv    = 1; break;
+               case 'x': malloc_xmalloc = 0; break;
+               case 'X': malloc_xmalloc = 1; break;
+               case 'z': malloc_zero    = 0; break;
+               case 'Z': malloc_zero    = 1; break;
+               default:
+                   _malloc_message(getprogname(), malloc_func,
+                        " warning: ", "unknown char in MALLOC_OPTIONS\n");
+                   break;
+           }
+       }
+    }
+
+    UTRACE(0, 0, 0);
+
+    /*
+     * We want junk in the entire allocation, and zero only in the part
+     * the user asked for.
+     */
+    if (malloc_zero)
+       malloc_junk = 1;
+
+    /* Allocate one page for the page directory */
+    page_dir = MMAP(malloc_pagesize);
+
+    if (page_dir == MAP_FAILED)
+       wrterror("mmap(2) failed, check limits.\n");
+
+    /*
+     * We need a maximum of malloc_pageshift buckets, steal these from the
+     * front of the page_directory;
+     */
+    malloc_origo = pageround((size_t)(uintptr_t)sbrk((intptr_t)0))
+       >> malloc_pageshift;
+    malloc_origo -= malloc_pageshift;
+
+    malloc_ninfo = malloc_pagesize / sizeof *page_dir;
+
+    /* Recalculate the cache size in bytes, and make sure it's nonzero */
+
+    if (!malloc_cache)
+       malloc_cache++;
+
+    malloc_cache <<= malloc_pageshift;
+
+    /*
+     * This is a nice hack from Kaleb Keithly (kaleb@x.org).
+     * We can sbrk(2) further back when we keep this on a low address.
+     */
+    px = imalloc(sizeof *px);
+
+    errno = save_errno;
+}
+
+/*
+ * Allocate a number of complete pages
+ */
+static void *
+malloc_pages(size_t size)
+{
+    void *p, *delay_free = NULL;
+    size_t i;
+    struct pgfree *pf;
+    size_t idx;
+
+    idx = pageround(size);
+    if (idx < size) {
+       errno = ENOMEM;
+       return NULL;
+    } else
+       size = idx;
+
+    p = NULL;
+
+    /* Look for free pages before asking for more */
+    for(pf = free_list.next; pf; pf = pf->next) {
+
+#ifdef MALLOC_EXTRA_SANITY
+       if (pf->size & malloc_pagemask)
+           wrterror("(ES): junk length entry on free_list.\n");
+       if (!pf->size)
+           wrterror("(ES): zero length entry on free_list.\n");
+       if (pf->page == pf->end)
+           wrterror("(ES): zero entry on free_list.\n");
+       if (pf->page > pf->end)
+           wrterror("(ES): sick entry on free_list.\n");
+       if ((void*)pf->page >= (void*)sbrk(0))
+           wrterror("(ES): entry on free_list past brk.\n");
+       if (page_dir[ptr2idx(pf->page)] != MALLOC_FREE)
+           wrterror("(ES): non-free first page on free-list.\n");
+       if (page_dir[ptr2idx(pf->end)-1] != MALLOC_FREE)
+           wrterror("(ES): non-free last page on free-list.\n");
+#endif /* MALLOC_EXTRA_SANITY */
+
+       if (pf->size < size)
+           continue;
+
+       if (pf->size == size) {
+           p = pf->page;
+           if (pf->next != NULL)
+                   pf->next->prev = pf->prev;
+           pf->prev->next = pf->next;
+           delay_free = pf;
+           break;
+       } 
+
+       p = pf->page;
+       pf->page = (char *)pf->page + size;
+       pf->size -= size;
+       break;
+    }
+
+#ifdef MALLOC_EXTRA_SANITY
+    if (p != NULL && page_dir[ptr2idx(p)] != MALLOC_FREE)
+       wrterror("(ES): allocated non-free page on free-list.\n");
+#endif /* MALLOC_EXTRA_SANITY */
+
+    size >>= malloc_pageshift;
+
+    /* Map new pages */
+    if (p == NULL)
+       p = map_pages(size);
+
+    if (p != NULL) {
+
+       idx = ptr2idx(p);
+       page_dir[idx] = MALLOC_FIRST;
+       for (i=1;i<size;i++)
+           page_dir[idx+i] = MALLOC_FOLLOW;
+
+       if (malloc_junk)
+           memset(p, SOME_JUNK, size << malloc_pageshift);
+    }
+
+    if (delay_free) {
+       if (px == NULL)
+           px = delay_free;
+       else
+           ifree(delay_free);
+    }
+
+    return p;
+}
+
+/*
+ * Allocate a page of fragments
+ */
+
+static inline int
+malloc_make_chunks(int bits)
+{
+    struct  pginfo *bp;
+    void *pp;
+    int i, k;
+    long l;
+
+    /* Allocate a new bucket */
+    pp = malloc_pages(malloc_pagesize);
+    if (pp == NULL)
+       return 0;
+
+    /* Find length of admin structure */
+    l = (long)offsetof(struct pginfo, bits[0]);
+    l += (long)sizeof bp->bits[0] *
+       (((malloc_pagesize >> bits)+MALLOC_BITS-1) / MALLOC_BITS);
+
+    /* Don't waste more than two chunks on this */
+    if ((1<<(bits)) <= l+l) {
+       bp = (struct  pginfo *)pp;
+    } else {
+       bp = imalloc((size_t)l);
+       if (bp == NULL) {
+           ifree(pp);
+           return 0;
+       }
+    }
+
+    bp->size = (1<<bits);
+    bp->shift = bits;
+    bp->total = bp->free = (u_short)(malloc_pagesize >> bits);
+    bp->page = pp;
+
+    /* set all valid bits in the bitmap */
+    k = bp->total;
+    i = 0;
+
+    /* Do a bunch at a time */
+    for(;k-i >= MALLOC_BITS; i += MALLOC_BITS)
+       bp->bits[i / MALLOC_BITS] = ~0U;
+
+    for(; i < k; i++)
+        bp->bits[i/MALLOC_BITS] |= 1<<(i%MALLOC_BITS);
+
+    if (bp == bp->page) {
+       /* Mark the ones we stole for ourselves */
+       for(i = 0; l > 0; i++) {
+           bp->bits[i / MALLOC_BITS] &= ~(1 << (i % MALLOC_BITS));
+           bp->free--;
+           bp->total--;
+           l -= (long)(1 << bits);
+       }
+    }
+
+    /* MALLOC_LOCK */
+
+    page_dir[ptr2idx(pp)] = bp;
+
+    bp->next = page_dir[bits];
+    page_dir[bits] = bp;
+
+    /* MALLOC_UNLOCK */
+
+    return 1;
+}
+
+/*
+ * Allocate a fragment
+ */
+static void *
+malloc_bytes(size_t size)
+{
+    size_t i;
+    int j;
+    u_int u;
+    struct  pginfo *bp;
+    size_t k;
+    u_int *lp;
+
+    /* Don't bother with anything less than this */
+    if (size < malloc_minsize)
+       size = malloc_minsize;
+
+
+    /* Find the right bucket */
+    j = 1;
+    i = size-1;
+    while (i >>= 1)
+       j++;
+
+    /* If it's empty, make a page more of that size chunks */
+    if (page_dir[j] == NULL && !malloc_make_chunks(j))
+       return NULL;
+
+    bp = page_dir[j];
+
+    /* Find first word of bitmap which isn't empty */
+    for (lp = bp->bits; !*lp; lp++)
+       ;
+
+    /* Find that bit, and tweak it */
+    u = 1;
+    k = 0;
+    while (!(*lp & u)) {
+       u += u;
+       k++;
+    }
+    *lp ^= u;
+
+    /* If there are no more free, remove from free-list */
+    if (!--bp->free) {
+       page_dir[j] = bp->next;
+       bp->next = NULL;
+    }
+
+    /* Adjust to the real offset of that chunk */
+    k += (lp-bp->bits)*MALLOC_BITS;
+    k <<= bp->shift;
+
+    if (malloc_junk)
+       memset((u_char*)bp->page + k, SOME_JUNK, (size_t)bp->size);
+
+    return (u_char *)bp->page + k;
+}
+
+/*
+ * Allocate a piece of memory
+ */
+static void *
+imalloc(size_t size)
+{
+    void *result;
+
+    if (suicide)
+       abort();
+
+    if ((size + malloc_pagesize) < size)       /* Check for overflow */
+       result = NULL;
+    else if ((size + malloc_pagesize) >= (uintptr_t)page_dir)
+       result = NULL;
+    else if (size <= malloc_maxsize)
+       result = malloc_bytes(size);
+    else
+       result = malloc_pages(size);
+
+    if (malloc_abort && result == NULL)
+       wrterror("allocation failed.\n");
+
+    if (malloc_zero && result != NULL)
+       memset(result, 0, size);
+
+    return result;
+}
+
+/*
+ * Change the size of an allocation.
+ */
+static void *
+irealloc(void *ptr, size_t size)
+{
+    void *p;
+    size_t osize, idx;
+    struct pginfo **mp;
+    size_t i;
+
+    if (suicide)
+       abort();
+
+    idx = ptr2idx(ptr);
+
+    if (idx < malloc_pageshift) {
+       wrtwarning("junk pointer, too low to make sense.\n");
+       return 0;
+    }
+
+    if (idx > last_idx) {
+       wrtwarning("junk pointer, too high to make sense.\n");
+       return 0;
+    }
+
+    mp = &page_dir[idx];
+
+    if (*mp == MALLOC_FIRST) {                 /* Page allocation */
+
+       /* Check the pointer */
+       if ((size_t)(uintptr_t)ptr & malloc_pagemask) {
+           wrtwarning("modified (page-) pointer.\n");
+           return NULL;
+       }
+
+       /* Find the size in bytes */
+       for (osize = malloc_pagesize; *++mp == MALLOC_FOLLOW;)
+           osize += malloc_pagesize;
+
+        if (!malloc_realloc &&                         /* unless we have to, */
+         size <= osize &&                      /* .. or are too small, */
+         size > (osize - malloc_pagesize)) {   /* .. or can free a page, */
+           if (malloc_junk)
+               memset((u_char *)ptr + size, SOME_JUNK, osize-size);
+           return ptr;                         /* don't do anything. */
+       }
+
+    } else if (*mp >= MALLOC_MAGIC) {          /* Chunk allocation */
+
+       /* Check the pointer for sane values */
+       if (((size_t)(uintptr_t)ptr & ((*mp)->size-1))) {
+           wrtwarning("modified (chunk-) pointer.\n");
+           return NULL;
+       }
+
+       /* Find the chunk index in the page */
+       i = ((size_t)(uintptr_t)ptr & malloc_pagemask) >> (*mp)->shift;
+
+       /* Verify that it isn't a free chunk already */
+        if ((*mp)->bits[i/MALLOC_BITS] & (1UL << (i % MALLOC_BITS))) {
+           wrtwarning("chunk is already free.\n");
+           return NULL;
+       }
+
+       osize = (*mp)->size;
+
+       if (!malloc_realloc &&          /* Unless we have to, */
+         size <= osize &&              /* ..or are too small, */
+         (size > osize / 2 ||          /* ..or could use a smaller size, */
+         osize == malloc_minsize)) {   /* ..(if there is one) */
+           if (malloc_junk)
+               memset((u_char *)ptr + size, SOME_JUNK, osize-size);
+           return ptr;                 /* ..Don't do anything */
+       }
+
+    } else {
+       wrtwarning("pointer to wrong page.\n");
+       return NULL;
+    }
+
+    p = imalloc(size);
+
+    if (p != NULL) {
+       /* copy the lesser of the two sizes, and free the old one */
+       if (!size || !osize)
+           ;
+       else if (osize < size)
+           memcpy(p, ptr, osize);
+       else
+           memcpy(p, ptr, size);
+       ifree(ptr);
+    } 
+    return p;
+}
+
+/*
+ * Free a sequence of pages
+ */
+
+static inline void
+free_pages(void *ptr, size_t idx, struct pginfo *info)
+{
+    size_t i;
+    struct pgfree *pf, *pt=NULL;
+    size_t l;
+    void *tail;
+
+    if (info == MALLOC_FREE) {
+       wrtwarning("page is already free.\n");
+       return;
+    }
+
+    if (info != MALLOC_FIRST) {
+       wrtwarning("pointer to wrong page.\n");
+       return;
+    }
+
+    if ((size_t)(uintptr_t)ptr & malloc_pagemask) {
+       wrtwarning("modified (page-) pointer.\n");
+       return;
+    }
+
+    /* Count how many pages and mark them free at the same time */
+    page_dir[idx] = MALLOC_FREE;
+    for (i = 1; page_dir[idx+i] == MALLOC_FOLLOW; i++)
+       page_dir[idx + i] = MALLOC_FREE;
+
+    l = i << malloc_pageshift;
+
+    if (malloc_junk)
+       memset(ptr, SOME_JUNK, l);
+
+    if (malloc_hint)
+       madvise(ptr, l, MADV_FREE);
+
+    tail = (char *)ptr+l;
+
+    /* add to free-list */
+    if (px == NULL)
+       px = imalloc(sizeof *px);       /* This cannot fail... */
+    px->page = ptr;
+    px->end =  tail;
+    px->size = l;
+    if (free_list.next == NULL) {
+
+       /* Nothing on free list, put this at head */
+       px->next = free_list.next;
+       px->prev = &free_list;
+       free_list.next = px;
+       pf = px;
+       px = NULL;
+
+    } else {
+
+       /* Find the right spot, leave pf pointing to the modified entry. */
+       tail = (char *)ptr+l;
+
+       for(pf = free_list.next; pf->end < ptr && pf->next != NULL;
+           pf = pf->next)
+           ; /* Race ahead here */
+
+       if (pf->page > tail) {
+           /* Insert before entry */
+           px->next = pf;
+           px->prev = pf->prev;
+           pf->prev = px;
+           px->prev->next = px;
+           pf = px;
+           px = NULL;
+       } else if (pf->end == ptr ) {
+           /* Append to the previous entry */
+           pf->end = (char *)pf->end + l;
+           pf->size += l;
+           if (pf->next != NULL && pf->end == pf->next->page ) {
+               /* And collapse the next too. */
+               pt = pf->next;
+               pf->end = pt->end;
+               pf->size += pt->size;
+               pf->next = pt->next;
+               if (pf->next != NULL)
+                   pf->next->prev = pf;
+           }
+       } else if (pf->page == tail) {
+           /* Prepend to entry */
+           pf->size += l;
+           pf->page = ptr;
+       } else if (pf->next == NULL) {
+           /* Append at tail of chain */
+           px->next = NULL;
+           px->prev = pf;
+           pf->next = px;
+           pf = px;
+           px = NULL;
+       } else {
+           wrterror("freelist is destroyed.\n");
+       }
+    }
+    
+    /* Return something to OS ? */
+    if (pf->next == NULL &&                    /* If we're the last one, */
+      pf->size > malloc_cache &&               /* ..and the cache is full, */
+      pf->end == malloc_brk &&                 /* ..and none behind us, */
+      malloc_brk == sbrk((intptr_t)0)) {       /* ..and it's OK to do... */
+
+       /*
+        * Keep the cache intact.  Notice that the '>' above guarantees that
+        * the pf will always have at least one page afterwards.
+        */
+       pf->end = (char *)pf->page + malloc_cache;
+       pf->size = malloc_cache;
+
+       brk(pf->end);
+       malloc_brk = pf->end;
+
+       idx = ptr2idx(pf->end);
+
+       for(i=idx;i <= last_idx;)
+           page_dir[i++] = MALLOC_NOT_MINE;
+
+       last_idx = idx - 1;
+
+       /* XXX: We could realloc/shrink the pagedir here I guess. */
+    }
+    if (pt != NULL)
+       ifree(pt);
+}
+
+/*
+ * Free a chunk, and possibly the page it's on, if the page becomes empty.
+ */
+
+static inline void
+free_bytes(void *ptr, size_t idx, struct pginfo *info)
+{
+    size_t i;
+    struct pginfo **mp;
+    void *vp;
+
+    /* Find the chunk number on the page */
+    i = ((size_t)(uintptr_t)ptr & malloc_pagemask) >> info->shift;
+
+    if (((size_t)(uintptr_t)ptr & (info->size-1))) {
+       wrtwarning("modified (chunk-) pointer.\n");
+       return;
+    }
+
+    if (info->bits[i/MALLOC_BITS] & (1UL << (i % MALLOC_BITS))) {
+       wrtwarning("chunk is already free.\n");
+       return;
+    }
+
+    if (malloc_junk)
+       memset(ptr, SOME_JUNK, (size_t)info->size);
+
+    info->bits[i/MALLOC_BITS] |= (u_int)(1UL << (i % MALLOC_BITS));
+    info->free++;
+
+    mp = page_dir + info->shift;
+
+    if (info->free == 1) {
+
+       /* Page became non-full */
+
+       mp = page_dir + info->shift;
+       /* Insert in address order */
+       while (*mp && (*mp)->next && (*mp)->next->page < info->page)
+           mp = &(*mp)->next;
+       info->next = *mp;
+       *mp = info;
+       return;
+    }
+
+    if (info->free != info->total)
+       return;
+
+    /* Find & remove this page in the queue */
+    while (*mp != info) {
+       mp = &((*mp)->next);
+#ifdef MALLOC_EXTRA_SANITY
+       if (!*mp)
+               wrterror("(ES): Not on queue.\n");
+#endif /* MALLOC_EXTRA_SANITY */
+    }
+    *mp = info->next;
+
+    /* Free the page & the info structure if need be */
+    page_dir[idx] = MALLOC_FIRST;
+    vp = info->page;           /* Order is important ! */
+    if(vp != (void*)info) 
+       ifree(info);
+    ifree(vp);
+}
+
+static void
+ifree(void *ptr)
+{
+    struct pginfo *info;
+    size_t idx;
+
+    /* This is legal */
+    if (ptr == NULL)
+       return;
+
+    /* If we're already sinking, don't make matters any worse. */
+    if (suicide)
+       return;
+
+    idx = ptr2idx(ptr);
+
+    if (idx < malloc_pageshift) {
+       wrtwarning("junk pointer, too low to make sense.\n");
+       return;
+    }
+
+    if (idx > last_idx) {
+       wrtwarning("junk pointer, too high to make sense.\n");
+       return;
+    }
+
+    info = page_dir[idx];
+
+    if (info < MALLOC_MAGIC)
+        free_pages(ptr, idx, info);
+    else
+       free_bytes(ptr, idx, info);
+    return;
+}
+
+static int malloc_active; /* Recusion flag for public interface. */
+static unsigned malloc_started; /* Set when initialization has been done */
+
+static void *
+pubrealloc(void *ptr, size_t size, const char *func)
+{
+    void *r;
+    int err = 0;
+
+    /*
+     * If a thread is inside our code with a functional lock held, and then
+     * catches a signal which calls us again, we would get a deadlock if the
+     * lock is not of a recursive type.
+     */
+    _MALLOC_LOCK();
+    malloc_func = func;
+    if (malloc_active > 0) {
+       if (malloc_active == 1) {
+           wrtwarning("recursive call\n");
+           malloc_active = 2;
+       }
+        _MALLOC_UNLOCK();
+       errno = EINVAL;
+       return (NULL);
+    } 
+    malloc_active = 1;
+
+    if (!malloc_started) {
+        if (ptr != NULL) {
+           wrtwarning("malloc() has never been called\n");
+           malloc_active = 0;
+            _MALLOC_UNLOCK();
+           errno = EINVAL;
+           return (NULL);
+       }
+       malloc_init();
+       malloc_started = 1;
+    }
+   
+    if (ptr == ZEROSIZEPTR)
+       ptr = NULL;
+    if (malloc_sysv && !size) {
+       if (ptr != NULL)
+           ifree(ptr);
+       r = NULL;
+    } else if (!size) {
+       if (ptr != NULL)
+           ifree(ptr);
+       r = ZEROSIZEPTR;
+    } else if (ptr == NULL) {
+       r = imalloc(size);
+       err = (r == NULL);
+    } else {
+        r = irealloc(ptr, size);
+       err = (r == NULL);
+    }
+    UTRACE(ptr, size, r);
+    malloc_active = 0;
+    _MALLOC_UNLOCK();
+    if (malloc_xmalloc && err)
+       wrterror("out of memory\n");
+    if (err)
+       errno = ENOMEM;
+    return (r);
+}
+
+/*
+ * These are the public exported interface routines.
+ */
+
+void *
+malloc(size_t size)
+{
+
+    return pubrealloc(NULL, size, " in malloc():");
+}
+
+int
+posix_memalign(void **memptr, size_t alignment, size_t size)
+{
+    int err;
+    void *result;
+
+    if (!malloc_started) {
+           malloc_init();
+           malloc_started = 1;
+    }
+    /* Make sure that alignment is a large enough power of 2. */
+    if (((alignment - 1) & alignment) != 0 || alignment < sizeof(void *) ||
+       alignment > malloc_pagesize)
+           return EINVAL;
+
+    /* 
+     * (size | alignment) is enough to assure the requested alignment, since
+     * the allocator always allocates power-of-two blocks.
+     */
+    err = errno; /* Protect errno against changes in pubrealloc(). */
+    result = pubrealloc(NULL, (size | alignment), " in posix_memalign()");
+    errno = err;
+
+    if (result == NULL)
+       return ENOMEM;
+
+    *memptr = result;
+    return 0;
+}
+
+void *
+calloc(size_t num, size_t size)
+{
+    void *ret;
+
+    if (size != 0 && (num * size) / size != num) {
+       /* size_t overflow. */
+       errno = ENOMEM;
+       return (NULL);
+    }
+
+    ret = pubrealloc(NULL, num * size, " in calloc():");
+
+    if (ret != NULL)
+       memset(ret, 0, num * size);
+
+    return ret;
+}
+
+void
+free(void *ptr)
+{
+
+    pubrealloc(ptr, 0, " in free():");
+}
+
+void *
+realloc(void *ptr, size_t size)
+{
+
+    return pubrealloc(ptr, size, " in realloc():");
+}
+
+/*
+ * Begin library-private functions, used by threading libraries for protection
+ * of malloc during fork().  These functions are only called if the program is
+ * running in threaded mode, so there is no need to check whether the program
+ * is threaded here.
+ */
+
+void
+_malloc_prefork(void)
+{
+
+       _MALLOC_LOCK();
+}
+
+void
+_malloc_postfork(void)
+{
+
+       _MALLOC_UNLOCK();
+}
diff --git a/lib/nbsd_libc/stdlib/memory.3 b/lib/nbsd_libc/stdlib/memory.3
new file mode 100644 (file)
index 0000000..3cef2b8
--- /dev/null
@@ -0,0 +1,70 @@
+.\"    $NetBSD: memory.3,v 1.10 2003/08/07 16:43:42 agc Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)memory.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt MEMORY 3
+.Os
+.Sh NAME
+.Nm malloc ,
+.Nm free ,
+.Nm realloc ,
+.Nm calloc ,
+.Nm alloca
+.Nd general memory allocation operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft void *
+.Fn malloc "size_t size"
+.Ft void
+.Fn free "void *ptr"
+.Ft void *
+.Fn realloc "void *ptr" "size_t size"
+.Ft void *
+.Fn calloc "size_t nelem" "size_t elsize"
+.Ft void *
+.Fn alloca "size_t size"
+.Sh DESCRIPTION
+These functions allocate and free memory for the calling process.
+They are described in the
+individual manual pages.
+.Sh SEE ALSO
+.Xr alloca 3 ,
+.Xr calloc 3 ,
+.Xr free 3 ,
+.Xr malloc 3 ,
+.Xr realloc 3
+.Sh STANDARDS
+These functions, with the exception of
+.Fn alloca
+conform to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdlib/merge.c b/lib/nbsd_libc/stdlib/merge.c
new file mode 100644 (file)
index 0000000..fb425f7
--- /dev/null
@@ -0,0 +1,380 @@
+/*     $NetBSD: merge.c,v 1.12 2009/02/12 03:12:36 lukem Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Peter McIlroy.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "from: @(#)merge.c      8.2 (Berkeley) 2/14/94";
+#else
+__RCSID("$NetBSD: merge.c,v 1.12 2009/02/12 03:12:36 lukem Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Hybrid exponential search/linear search merge sort with hybrid
+ * natural/pairwise first pass.  Requires about .3% more comparisons
+ * for random data than LSMS with pairwise first pass alone.
+ * It works for objects as small as two bytes.
+ */
+
+#define NATURAL
+#define THRESHOLD 16   /* Best choice for natural merge cut-off. */
+
+/* #define NATURAL to get hybrid natural merge.
+ * (The default is pairwise merging.)
+ */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(mergesort,_mergesort)
+#endif
+
+static void setup __P((u_char *, u_char *, size_t, size_t,
+    int (*)(const void *, const void *)));
+static void insertionsort __P((u_char *, size_t, size_t,
+    int (*)(const void *, const void *)));
+
+#define ISIZE sizeof(int)
+#define PSIZE sizeof(u_char *)
+#define ICOPY_LIST(src, dst, last)                             \
+       do                                                      \
+       *(int*)(void *)dst = *(int*)(void *)src,                \
+               src += ISIZE, dst += ISIZE;                     \
+       while(src < last)
+#define ICOPY_ELT(src, dst, i)                                 \
+       do                                                      \
+       *(int*)(void *)dst = *(int*)(void *)src,                \
+       src += ISIZE, dst += ISIZE;                             \
+       while (i -= ISIZE)
+
+#define CCOPY_LIST(src, dst, last)             \
+       do                                      \
+               *dst++ = *src++;                \
+       while (src < last)
+#define CCOPY_ELT(src, dst, i)                 \
+       do                                      \
+               *dst++ = *src++;                \
+       while (i -= 1)
+               
+/*
+ * Find the next possible pointer head.  (Trickery for forcing an array
+ * to do double duty as a linked list when objects do not align with word
+ * boundaries.
+ */
+/* Assumption: PSIZE is a power of 2. */
+#define EVAL(p) ((u_char **)(void *)                                   \
+    ((u_char *)0 +                                                     \
+    (((u_char *)(void *)(p) + PSIZE - 1 - (u_char *) 0) & ~(PSIZE - 1))))
+
+/*
+ * Arguments are as for qsort.
+ */
+int
+mergesort(base, nmemb, size, cmp)
+       void *base;
+       size_t nmemb;
+       size_t size;
+       int (*cmp) __P((const void *, const void *));
+{
+       size_t i;
+       int sense;
+       int big, iflag;
+       u_char *f1, *f2, *t, *b, *tp2, *q, *l1, *l2;
+       u_char *list2, *list1, *p2, *p, *last, **p1;
+
+       _DIAGASSERT(base != NULL);
+       _DIAGASSERT(cmp != NULL);
+
+       if (size < PSIZE / 2) {         /* Pointers must fit into 2 * size. */
+               errno = EINVAL;
+               return (-1);
+       }
+
+       /*
+        * XXX
+        * Stupid subtraction for the Cray.
+        */
+       iflag = 0;
+       if (!(size % ISIZE) && !(((char *)base - (char *)0) % ISIZE))
+               iflag = 1;
+
+       if ((list2 = malloc(nmemb * size + PSIZE)) == NULL)
+               return (-1);
+
+       list1 = base;
+       setup(list1, list2, nmemb, size, cmp);
+       last = list2 + nmemb * size;
+       i = big = 0;
+       while (*EVAL(list2) != last) {
+           l2 = list1;
+           p1 = EVAL(list1);
+           for (tp2 = p2 = list2; p2 != last; p1 = EVAL(l2)) {
+               p2 = *EVAL(p2);
+               f1 = l2;
+               f2 = l1 = list1 + (p2 - list2);
+               if (p2 != last)
+                       p2 = *EVAL(p2);
+               l2 = list1 + (p2 - list2);
+               while (f1 < l1 && f2 < l2) {
+                       if ((*cmp)(f1, f2) <= 0) {
+                               q = f2;
+                               b = f1, t = l1;
+                               sense = -1;
+                       } else {
+                               q = f1;
+                               b = f2, t = l2;
+                               sense = 0;
+                       }
+                       if (!big) {     /* here i = 0 */
+#if 0
+LINEAR:
+#endif
+                               while ((b += size) < t && cmp(q, b) >sense)
+                                       if (++i == 6) {
+                                               big = 1;
+                                               goto EXPONENTIAL;
+                                       }
+                       } else {
+EXPONENTIAL:                   for (i = size; ; i <<= 1)
+                                       if ((p = (b + i)) >= t) {
+                                               if ((p = t - size) > b &&
+                                                   (*cmp)(q, p) <= sense)
+                                                       t = p;
+                                               else
+                                                       b = p;
+                                               break;
+                                       } else if ((*cmp)(q, p) <= sense) {
+                                               t = p;
+                                               if (i == size)
+                                                       big = 0; 
+                                               goto FASTCASE;
+                                       } else
+                                               b = p;
+#if 0
+SLOWCASE:
+#endif
+                               while (t > b+size) {
+                                       i = (((t - b) / size) >> 1) * size;
+                                       if ((*cmp)(q, p = b + i) <= sense)
+                                               t = p;
+                                       else
+                                               b = p;
+                               }
+                               goto COPY;
+FASTCASE:                      while (i > size)
+                                       if ((*cmp)(q,
+                                               p = b +
+                                                   (i = (unsigned int) i >> 1)) <= sense)
+                                               t = p;
+                                       else
+                                               b = p;
+COPY:                          b = t;
+                       }
+                       i = size;
+                       if (q == f1) {
+                               if (iflag) {
+                                       ICOPY_LIST(f2, tp2, b);
+                                       ICOPY_ELT(f1, tp2, i);
+                               } else {
+                                       CCOPY_LIST(f2, tp2, b);
+                                       CCOPY_ELT(f1, tp2, i);
+                               }
+                       } else {
+                               if (iflag) {
+                                       ICOPY_LIST(f1, tp2, b);
+                                       ICOPY_ELT(f2, tp2, i);
+                               } else {
+                                       CCOPY_LIST(f1, tp2, b);
+                                       CCOPY_ELT(f2, tp2, i);
+                               }
+                       }
+               }
+               if (f2 < l2) {
+                       if (iflag)
+                               ICOPY_LIST(f2, tp2, l2);
+                       else
+                               CCOPY_LIST(f2, tp2, l2);
+               } else if (f1 < l1) {
+                       if (iflag)
+                               ICOPY_LIST(f1, tp2, l1);
+                       else
+                               CCOPY_LIST(f1, tp2, l1);
+               }
+               *p1 = l2;
+           }
+           tp2 = list1;        /* swap list1, list2 */
+           list1 = list2;
+           list2 = tp2;
+           last = list2 + nmemb*size;
+       }
+       if (base == list2) {
+               memmove(list2, list1, nmemb*size);
+               list2 = list1;
+       }
+       free(list2);
+       return (0);
+}
+
+#define        swap(a, b) {                                    \
+               s = b;                                  \
+               i = size;                               \
+               do {                                    \
+                       tmp = *a; *a++ = *s; *s++ = tmp; \
+               } while (--i);                          \
+               a -= size;                              \
+       }
+#define reverse(bot, top) {                            \
+       s = top;                                        \
+       do {                                            \
+               i = size;                               \
+               do {                                    \
+                       tmp = *bot; *bot++ = *s; *s++ = tmp; \
+               } while (--i);                          \
+               s -= size2;                             \
+       } while(bot < s);                               \
+}
+
+/*
+ * Optional hybrid natural/pairwise first pass.  Eats up list1 in runs of
+ * increasing order, list2 in a corresponding linked list.  Checks for runs
+ * when THRESHOLD/2 pairs compare with same sense.  (Only used when NATURAL
+ * is defined.  Otherwise simple pairwise merging is used.)
+ */
+
+/* XXX: shouldn't this function be static? - lukem 990810 */
+void
+setup(list1, list2, n, size, cmp)
+       size_t n, size;
+       int (*cmp) __P((const void *, const void *));
+       u_char *list1, *list2;
+{
+       int i, length, size2, tmp, sense;
+       u_char *f1, *f2, *s, *l2, *last, *p2;
+
+       _DIAGASSERT(cmp != NULL);
+       _DIAGASSERT(list1 != NULL);
+       _DIAGASSERT(list2 != NULL);
+
+       size2 = size*2;
+       if (n <= 5) {
+               insertionsort(list1, n, size, cmp);
+               *EVAL(list2) = list2 + n*size;
+               return;
+       }
+       /*
+        * Avoid running pointers out of bounds; limit n to evens
+        * for simplicity.
+        */
+       i = 4 + (n & 1);
+       insertionsort(list1 + (n - i) * size, (size_t)i, size, cmp);
+       last = list1 + size * (n - i);
+       *EVAL(list2 + (last - list1)) = list2 + n * size;
+
+#ifdef NATURAL
+       p2 = list2;
+       f1 = list1;
+       sense = (cmp(f1, f1 + size) > 0);
+       for (; f1 < last; sense = !sense) {
+               length = 2;
+                                       /* Find pairs with same sense. */
+               for (f2 = f1 + size2; f2 < last; f2 += size2) {
+                       if ((cmp(f2, f2+ size) > 0) != sense)
+                               break;
+                       length += 2;
+               }
+               if (length < THRESHOLD) {               /* Pairwise merge */
+                       do {
+                               p2 = *EVAL(p2) = f1 + size2 - list1 + list2;
+                               if (sense > 0)
+                                       swap (f1, f1 + size);
+                       } while ((f1 += size2) < f2);
+               } else {                                /* Natural merge */
+                       l2 = f2;
+                       for (f2 = f1 + size2; f2 < l2; f2 += size2) {
+                               if ((cmp(f2-size, f2) > 0) != sense) {
+                                       p2 = *EVAL(p2) = f2 - list1 + list2;
+                                       if (sense > 0)
+                                               reverse(f1, f2-size);
+                                       f1 = f2;
+                               }
+                       }
+                       if (sense > 0)
+                               reverse (f1, f2-size);
+                       f1 = f2;
+                       if (f2 < last || cmp(f2 - size, f2) > 0)
+                               p2 = *EVAL(p2) = f2 - list1 + list2;
+                       else
+                               p2 = *EVAL(p2) = list2 + n*size;
+               }
+       }
+#else          /* pairwise merge only. */
+       for (f1 = list1, p2 = list2; f1 < last; f1 += size2) {
+               p2 = *EVAL(p2) = p2 + size2;
+               if (cmp (f1, f1 + size) > 0)
+                       swap(f1, f1 + size);
+       }
+#endif /* NATURAL */
+}
+
+/*
+ * This is to avoid out-of-bounds addresses in sorting the
+ * last 4 elements.
+ */
+static void
+insertionsort(a, n, size, cmp)
+       u_char *a;
+       size_t n, size;
+       int (*cmp) __P((const void *, const void *));
+{
+       u_char *ai, *s, *t, *u, tmp;
+       int i;
+
+       _DIAGASSERT(a != NULL);
+       _DIAGASSERT(cmp != NULL);
+
+       for (ai = a+size; --n >= 1; ai += size)
+               for (t = ai; t > a; t -= size) {
+                       u = t - size;
+                       if (cmp(u, t) <= 0)
+                               break;
+                       swap(u, t);
+               }
+}
diff --git a/lib/nbsd_libc/stdlib/mi_vector_hash.3 b/lib/nbsd_libc/stdlib/mi_vector_hash.3
new file mode 100644 (file)
index 0000000..6827e61
--- /dev/null
@@ -0,0 +1,65 @@
+.\"    $NetBSD: mi_vector_hash.3,v 1.2 2009/07/21 12:40:52 joerg Exp $
+.\"
+.\" Copyright (c) 2009 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Joerg Sonnenberger.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd July 13, 2009
+.Dt MI_VECTOR_HASH 3
+.Os
+.Sh NAME
+.Nm mi_vector_hash
+.Nd fast 32bit hash functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft void
+.Fn mi_vector_hash "const void * restrict key" "size_t len" \
+    "uint32_t seed" "uint32_t hashes[3]"
+.Sh DESCRIPTION
+The
+.Nm
+function computes three 32-bit hash values of the memory area starting at
+.Fa key
+with length
+.Fa len .
+.Pp
+The output is identical on all architectures and only depends on
+.Fa key
+and
+.Fa seed .
+.Sh IMPLEMENTATION NOTES
+An optimised code path is used if
+.Fa key
+is aligned on a 32-bit boundary.
+.Sh HISTORY
+The
+.Nm
+function appeared in
+.Nx 6.0 .
+.Sh AUTHORS
+The hash function has been created by Bob Jenkins.
diff --git a/lib/nbsd_libc/stdlib/mi_vector_hash.c b/lib/nbsd_libc/stdlib/mi_vector_hash.c
new file mode 100644 (file)
index 0000000..b867ebe
--- /dev/null
@@ -0,0 +1,171 @@
+/*     $NetBSD: mi_vector_hash.c,v 1.3 2010/03/19 18:11:30 joerg Exp $ */
+/*-
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Joerg Sonnenberger.
+ *
+ * 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 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 HOLDERS 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.
+ */
+
+/*
+ * See http://burtleburtle.net/bob/hash/doobs.html for the full description
+ * and the original version of the code.  This version differs by exposing
+ * the full internal state and avoiding byte operations in the inner loop
+ * if the key is aligned correctly.
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: mi_vector_hash.c,v 1.3 2010/03/19 18:11:30 joerg Exp $");
+
+#include "namespace.h"
+
+#include <sys/endian.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#define mix(a, b, c) do {              \
+       a -= b; a -= c; a ^= (c >> 13); \
+       b -= c; b -= a; b ^= (a << 8);  \
+       c -= a; c -= b; c ^= (b >> 13); \
+       a -= b; a -= c; a ^= (c >> 12); \
+       b -= c; b -= a; b ^= (a << 16); \
+       c -= a; c -= b; c ^= (b >> 5);  \
+       a -= b; a -= c; a ^= (c >> 3);  \
+       b -= c; b -= a; b ^= (a << 10); \
+       c -= a; c -= b; c ^= (b >> 15); \
+} while (/* CONSTCOND */0)
+
+#define FIXED_SEED     0x9e3779b9      /* Golden ratio, arbitrary constant */
+
+#ifdef __weak_alias
+__weak_alias(mi_vector_hash, _mi_vector_hash)
+#endif
+
+void
+mi_vector_hash(const void * __restrict key, size_t len, uint32_t seed,
+    uint32_t hashes[3])
+{
+       static const uint32_t mask[4] = {
+               0x000000ff, 0x0000ffff, 0x00ffffff, 0xffffffff
+       };
+       uint32_t orig_len, a, b, c;
+       const uint8_t *k;
+
+       orig_len = (uint32_t)len;
+
+       a = b = FIXED_SEED;
+       c = seed;
+
+       if ((uintptr_t)key & 3) {
+               k = key;
+               while (len >= 12) {
+                       a += le32dec(k);
+                       b += le32dec(k + 4);
+                       c += le32dec(k + 8);
+                       mix(a, b, c);
+                       k += 12;
+                       len -= 12;
+               }
+               c += orig_len;
+
+               if (len > 8) {
+                       switch (len) {
+                       case 11:
+                               c += (uint32_t)k[10] << 24;
+                               /* FALLTHROUGH */
+                       case 10:
+                               c += (uint32_t)k[9] << 16;
+                               /* FALLTHROUGH */
+                       case 9:
+                               c += (uint32_t)k[8] << 8;
+                               /* FALLTHROUGH */
+                       }
+                       b += le32dec(k + 4);
+                       a += le32dec(k);
+               } else if (len > 4) {
+                       switch (len) {
+                       case 8:
+                               b += (uint32_t)k[7] << 24;
+                               /* FALLTHROUGH */
+                       case 7:
+                               b += (uint32_t)k[6] << 16;
+                               /* FALLTHROUGH */
+                       case 6:
+                               b += (uint32_t)k[5] << 8;
+                               /* FALLTHROUGH */
+                       case 5:
+                               b += k[4];
+                               /* FALLTHROUGH */
+                       }
+                       a += le32dec(k);
+               } else if (len) {
+                       switch (len) {
+                       case 4:
+                               a += (uint32_t)k[3] << 24;
+                               /* FALLTHROUGH */
+                       case 3:
+                               a += (uint32_t)k[2] << 16;
+                               /* FALLTHROUGH */
+                       case 2:
+                               a += (uint32_t)k[1] << 8;
+                               /* FALLTHROUGH */
+                       case 1:
+                               a += k[0];
+                               /* FALLTHROUGH */
+                       }
+               }
+       } else {
+               const uint32_t *key32 = key;
+               while (len >= 12) {
+                       a += le32toh(key32[0]);
+                       b += le32toh(key32[1]);
+                       c += le32toh(key32[2]);
+                       mix(a, b, c);
+                       key32 += 3;
+                       len -= 12;
+               }
+               c += orig_len;
+
+               if (len > 8) {
+                       c += (le32toh(key32[2]) & mask[len - 9]) << 8;
+                       b += le32toh(key32[1]);
+                       a += le32toh(key32[0]);
+               } else if (len > 4) {
+                       b += le32toh(key32[1]) & mask[len - 5];
+                       a += le32toh(key32[0]);
+               } else if (len)
+                       a += le32toh(key32[0]) & mask[len - 1];
+       }
+       mix(a, b, c);
+       hashes[0] = a;
+       hashes[1] = b;
+       hashes[2] = c;
+}
diff --git a/lib/nbsd_libc/stdlib/mrand48.c b/lib/nbsd_libc/stdlib/mrand48.c
new file mode 100644 (file)
index 0000000..c787ce6
--- /dev/null
@@ -0,0 +1,33 @@
+/*     $NetBSD: mrand48.c,v 1.7 2005/06/12 05:21:28 lukem Exp $        */
+
+/*
+ * Copyright (c) 1993 Martin Birgmeier
+ * All rights reserved.
+ *
+ * You may redistribute unmodified or modified versions of this source
+ * code provided that the above copyright notice and this and the
+ * following conditions are retained.
+ *
+ * This software is provided ``as is'', and comes with no warranties
+ * of any kind. I shall in no event be liable for anything that happens
+ * to anyone/anything when using this software.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: mrand48.c,v 1.7 2005/06/12 05:21:28 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "rand48.h"
+
+#ifdef __weak_alias
+__weak_alias(mrand48,_mrand48)
+#endif
+
+long
+mrand48(void)
+{
+       __dorand48(__rand48_seed);
+       return ((long) __rand48_seed[2] << 16) + (long) __rand48_seed[1];
+}
diff --git a/lib/nbsd_libc/stdlib/nrand48.c b/lib/nbsd_libc/stdlib/nrand48.c
new file mode 100644 (file)
index 0000000..fc73185
--- /dev/null
@@ -0,0 +1,39 @@
+/*     $NetBSD: nrand48.c,v 1.9 2005/06/12 05:21:28 lukem Exp $        */
+
+/*
+ * Copyright (c) 1993 Martin Birgmeier
+ * All rights reserved.
+ *
+ * You may redistribute unmodified or modified versions of this source
+ * code provided that the above copyright notice and this and the
+ * following conditions are retained.
+ *
+ * This software is provided ``as is'', and comes with no warranties
+ * of any kind. I shall in no event be liable for anything that happens
+ * to anyone/anything when using this software.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: nrand48.c,v 1.9 2005/06/12 05:21:28 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+
+#include "rand48.h"
+
+#ifdef __weak_alias
+__weak_alias(nrand48,_nrand48)
+#endif
+
+long
+nrand48(unsigned short xseed[3])
+{
+       _DIAGASSERT(xseed != NULL);
+
+       __dorand48(xseed);
+       return (long)((unsigned long) xseed[2] << 15) +
+           ((unsigned long) xseed[1] >> 1);
+}
diff --git a/lib/nbsd_libc/stdlib/posix_memalign.3 b/lib/nbsd_libc/stdlib/posix_memalign.3
new file mode 100644 (file)
index 0000000..2d066f8
--- /dev/null
@@ -0,0 +1,91 @@
+.\"    $NetBSD: posix_memalign.3,v 1.1 2007/11/19 14:48:43 ad Exp $
+.\"
+.\" Copyright (C) 2006 Jason Evans <jasone@FreeBSD.org>.
+.\" 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(s), this list of conditions and the following disclaimer as
+.\"    the first lines of this file unmodified other than the possible
+.\"    addition of one or more copyright notices.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice(s), 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 COPYRIGHT HOLDER(S) ``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 HOLDER(S) 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.
+.\"
+.\" FreeBSD: src/lib/libc/stdlib/posix_memalign.3,v 1.3 2007/03/28 04:32:51 jasone Exp
+.\"
+.Dd November 19, 2007
+.Dt POSIX_MEMALIGN 3
+.Os
+.Sh NAME
+.Nm posix_memalign
+.Nd aligned memory allocation
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn posix_memalign "void **ptr" "size_t alignment" "size_t size"
+.Sh DESCRIPTION
+The
+.Fn posix_memalign
+function allocates
+.Fa size
+bytes of memory such that the allocation's base address is an even multiple of
+.Fa alignment ,
+and returns the allocation in the value pointed to by
+.Fa ptr .
+.Pp
+The requested
+.Fa alignment
+must be a power of 2 at least as large as
+.Fn sizeof "void *" .
+.Pp
+Memory that is allocated via
+.Fn posix_memalign
+can be used as an argument in subsequent calls to
+.Xr realloc 3
+and
+.Xr free 3 .
+.Sh RETURN VALUES
+The
+.Fn posix_memalign
+function returns the value 0 if successful; otherwise it returns an error value.
+.Sh ERRORS
+The
+.Fn posix_memalign
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa alignment
+parameter is not a power of 2 at least as large as
+.Fn sizeof "void *" .
+.It Bq Er ENOMEM
+Memory allocation error.
+.El
+.Sh SEE ALSO
+.Xr free 3 ,
+.Xr malloc 3 ,
+.Xr realloc 3 ,
+.Xr valloc 3
+.Sh STANDARDS
+The
+.Fn posix_memalign
+function conforms to
+.St -p1003.1-2001 .
diff --git a/lib/nbsd_libc/stdlib/posix_openpt.3 b/lib/nbsd_libc/stdlib/posix_openpt.3
new file mode 100644 (file)
index 0000000..3d5acb6
--- /dev/null
@@ -0,0 +1,80 @@
+.\" $NetBSD: posix_openpt.3,v 1.4 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2004 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Christos Zoulas.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 25, 2004
+.Dt POSIX_OPENPT 3
+.Os
+.Sh NAME
+.Nm posix_openpt
+.Nd open a pseudo-terminal device
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.In fcntl.h
+.Ft int
+.Fn posix_openpt "int oflag"
+.Sh DESCRIPTION
+.Fn posix_openpt
+Searches for an unused master pseudo-terminal device, opens it, and returns
+a file descriptor associated the now used pseudo-terminal device.
+The
+.Fa oflag
+argument has the same meaning as in the
+.Xr open 2
+call.
+.Sh RETURN VALUES
+If successful,
+.Fn posix_openpt
+returns a non-negative integer, which corresponds to a file descriptor
+pointing to the master pseudo-terminal device.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh SEE ALSO
+.Xr ioctl 2 ,
+.Xr open 2 ,
+.Xr grantpt 3 ,
+.Xr ptsname 3 ,
+.Xr unlockpt 3
+.Sh RATIONALE
+The standards committee did not want to directly expose the cloning device,
+thus decided to wrap the functionality in this function.
+The equivalent code would be:
+.Bd -literal
+       int
+       posix_openpt(int oflag) {
+               return open("/dev/ptmx", oflag);
+       }
+.Ed
+.Sh STANDARDS
+The
+.Fn posix_openpt
+function conforms to
+.St -p1003.1-2001 .
diff --git a/lib/nbsd_libc/stdlib/posix_openpt.c b/lib/nbsd_libc/stdlib/posix_openpt.c
new file mode 100644 (file)
index 0000000..f4e2cfa
--- /dev/null
@@ -0,0 +1,46 @@
+/*     $NetBSD: posix_openpt.c,v 1.2 2008/04/28 20:23:00 martin Exp $  */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: posix_openpt.c,v 1.2 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <fcntl.h>
+#include <stdlib.h>
+
+int
+posix_openpt(int oflag)
+{
+
+       return open("/dev/ptmx", oflag);
+}
diff --git a/lib/nbsd_libc/stdlib/ptsname.3 b/lib/nbsd_libc/stdlib/ptsname.3
new file mode 100644 (file)
index 0000000..78a9d96
--- /dev/null
@@ -0,0 +1,101 @@
+.\" $NetBSD: ptsname.3,v 1.5 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2004 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Christos Zoulas.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 25, 2004
+.Dt PTSNAME 3
+.Os
+.Sh NAME
+.Nm ptsname
+.Nd get the pathname of the slave pseudo-terminal device
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft char *
+.Fn ptsname "int masterfd"
+.Sh DESCRIPTION
+The
+.Fn ptsname
+function returns the pathname of the slave pseudo-terminal device
+that corresponds to the master pseudo-terminal device associated with
+.Fa masterfd .
+The
+.Fn ptsname
+function is not reentrant or thread-safe.
+.Sh RETURN VALUES
+If successful,
+.Fn ptsname
+returns a pointer to a nul-terminated string containing the pathname
+of the slave pseudo-terminal device.
+If an error occurs
+.Fn ptsname
+will return
+.Dv NULL
+and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn ptsname
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCESS
+the corresponding pseudo-terminal device could not be accessed.
+.It Bq Er EBADF
+.Fa masterfd
+is not a valid descriptor.
+.It Bq Er EINVAL
+.Fa masterfd
+is not associated with a master pseudo-terminal device.
+.El
+.Sh NOTES
+The error returns of
+.Fn ptsname
+are a
+.Nx
+extension.
+The
+.Fn ptsname
+function is equivalent to:
+.Bd -literal
+       struct ptmget pm;
+       return ioctl(masterfd, TIOCPTSNAME, \*[Am]pm) == -1 ? NULL : pm.ps;
+.Ed
+.Sh SEE ALSO
+.Xr ioctl 2 ,
+.Xr grantpt 3 ,
+.Xr posix_openpt 3 ,
+.Xr unlockpt 3
+.Sh STANDARDS
+The
+.Fn ptsname
+function conforms to
+.St -p1003.1-2001 .
+Its first release was in
+.St -xpg4.2 .
diff --git a/lib/nbsd_libc/stdlib/pty.c b/lib/nbsd_libc/stdlib/pty.c
new file mode 100644 (file)
index 0000000..05cef2d
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: pty.c,v 1.2 2008/04/28 20:23:00 martin Exp $   */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: pty.c,v 1.2 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/ioctl.h>
+
+int
+grantpt(int fildes)
+{
+
+       return ioctl(fildes, TIOCGRANTPT, 0);
+}
+
+int
+/*ARGSUSED*/
+unlockpt(int fildes)
+{
+
+       return 0;
+}
+
+char *
+ptsname(int fildes)
+{
+       static struct ptmget pm;
+
+       if (ioctl(fildes, TIOCPTSNAME, &pm) == -1)
+               return NULL;
+
+       return pm.sn;
+}
diff --git a/lib/nbsd_libc/stdlib/putenv.c b/lib/nbsd_libc/stdlib/putenv.c
new file mode 100644 (file)
index 0000000..1f617b4
--- /dev/null
@@ -0,0 +1,87 @@
+/*     $NetBSD: putenv.c,v 1.19 2010/11/14 18:11:43 tron Exp $ */
+
+/*-
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)putenv.c   8.2 (Berkeley) 3/27/94";
+#else
+__RCSID("$NetBSD: putenv.c,v 1.19 2010/11/14 18:11:43 tron Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "env.h"
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(putenv,_putenv)
+#endif
+
+int
+putenv(char *str)
+{
+       size_t l_name;
+       int rv;
+
+       _DIAGASSERT(str != NULL);
+
+       l_name = __envvarnamelen(str, true);
+       if (l_name == 0) {
+               errno = EINVAL;
+               return -1;
+       }
+
+       rv = -1;
+       if (__writelockenv()) {
+               ssize_t offset;
+
+               offset = __getenvslot(str, l_name, true);
+               if (offset != -1) {
+                       if (environ[offset] != NULL)
+                               __freeenvvar(environ[offset]);
+                       environ[offset] = str;
+
+                       rv = 0;
+               }
+
+               (void)__unlockenv();
+       }
+
+       return rv;
+}
diff --git a/lib/nbsd_libc/stdlib/qabs.3 b/lib/nbsd_libc/stdlib/qabs.3
new file mode 100644 (file)
index 0000000..95306af
--- /dev/null
@@ -0,0 +1,63 @@
+.\"    $NetBSD: qabs.3,v 1.9 2008/08/04 21:29:27 matt Exp $
+.\"
+.\" Copyright (c) 1990, 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)labs.3       5.3 (Berkeley) 6/29/91
+.\"
+.Dd June 29, 1991
+.Dt QABS 3
+.Os
+.Sh NAME
+.Nm qabs
+.Nd return the absolute value of a quad integer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft quad_t
+.Fn qabs "quad_t j"
+.Sh DESCRIPTION
+The
+.Fn qabs
+function
+returns the absolute value of the quad integer
+.Ar j .
+.Sh SEE ALSO
+.Xr abs 3 ,
+.Xr cabs 3 ,
+.Xr floor 3 ,
+.Xr imaxabs 3 ,
+.Xr labs 3 ,
+.Xr llabs 3 ,
+.Xr math 3
+.Sh BUGS
+The absolute value of the most negative integer remains negative.
diff --git a/lib/nbsd_libc/stdlib/qabs.c b/lib/nbsd_libc/stdlib/qabs.c
new file mode 100644 (file)
index 0000000..f19fefe
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: qabs.c,v 1.6 2003/08/07 16:43:42 agc Exp $     */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "from: @(#)labs.c        5.2 (Berkeley) 5/17/90";
+#else
+__RCSID("$NetBSD: qabs.c,v 1.6 2003/08/07 16:43:42 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(qabs,_qabs)
+#endif
+
+quad_t
+qabs(j)
+       quad_t j;
+{
+       return(j < 0 ? -j : j);
+}
diff --git a/lib/nbsd_libc/stdlib/qdiv.3 b/lib/nbsd_libc/stdlib/qdiv.3
new file mode 100644 (file)
index 0000000..0d30837
--- /dev/null
@@ -0,0 +1,67 @@
+.\"    $NetBSD: qdiv.3,v 1.9 2008/08/04 21:29:27 matt Exp $
+.\"
+.\" Copyright (c) 1990, 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)qdiv.3       5.3 (Berkeley) 6/29/91
+.\"
+.Dd June 29, 1991
+.Dt QDIV 3
+.Os
+.Sh NAME
+.Nm qdiv
+.Nd return quotient and remainder from division
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft qdiv_t
+.Fn qdiv "quad_t num" "quad_t denom"
+.Sh DESCRIPTION
+The
+.Fn qdiv
+function
+computes the value
+.Ar num/denom
+and returns the quotient and remainder in a structure named
+.Ar qdiv_t
+that contains two
+.Em quad integer
+members named
+.Ar quot
+and
+.Ar rem .
+.Sh SEE ALSO
+.Xr div 3 ,
+.Xr imaxdiv 3 ,
+.Xr ldiv 3 ,
+.Xr lldiv 3 ,
+.Xr math 3
diff --git a/lib/nbsd_libc/stdlib/qdiv.c b/lib/nbsd_libc/stdlib/qdiv.c
new file mode 100644 (file)
index 0000000..34e8c5c
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: qdiv.c,v 1.6 2003/08/07 16:43:42 agc Exp $     */
+
+/*
+ * Copyright (c) 1990 Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "from: @(#)ldiv.c        5.2 (Berkeley) 4/16/91";
+#else
+__RCSID("$NetBSD: qdiv.c,v 1.6 2003/08/07 16:43:42 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <stdlib.h>            /* qdiv_t */
+
+#ifdef __weak_alias
+__weak_alias(qdiv,_qdiv)
+#endif
+
+qdiv_t
+qdiv(num, denom)
+       quad_t num, denom;
+{
+       qdiv_t r;
+
+       /* see div.c for comments */
+
+       r.quot = num / denom;
+       r.rem = num % denom;
+       if (num >= 0 && r.rem < 0) {
+               r.quot++;
+               r.rem -= denom;
+       }
+       return (r);
+}
diff --git a/lib/nbsd_libc/stdlib/qsort.3 b/lib/nbsd_libc/stdlib/qsort.3
new file mode 100644 (file)
index 0000000..6e4bd2c
--- /dev/null
@@ -0,0 +1,238 @@
+.\"    $NetBSD: qsort.3,v 1.13 2003/08/07 16:43:42 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)qsort.3      8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt QSORT 3
+.Os
+.Sh NAME
+.Nm qsort ,
+.Nm heapsort ,
+.Nm mergesort
+.Nd sort functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft void
+.Fn qsort "void *base" "size_t nmemb" "size_t size" "int (*compar)(const void *, const void *)"
+.Ft int
+.Fn heapsort "void *base" "size_t nmemb" "size_t size" "int (*compar)(const void *, const void *)"
+.Ft int
+.Fn mergesort "void *base" "size_t nmemb" "size_t size" "int (*compar)(const void *, const void *)"
+.Sh DESCRIPTION
+The
+.Fn qsort
+function is a modified partition-exchange sort, or quicksort.
+The
+.Fn heapsort
+function is a modified selection sort.
+The
+.Fn mergesort
+function is a modified merge sort with exponential search
+intended for sorting data with pre-existing order.
+.Pp
+The
+.Fn qsort
+and
+.Fn heapsort
+functions sort an array of
+.Fa nmemb
+objects, the initial member of which is pointed to by
+.Fa base .
+The size of each object is specified by
+.Fa size .
+.Fn mergesort
+behaves similarly, but
+.Em requires
+that
+.Fa size
+be greater than
+.Dq "sizeof(void *) / 2" .
+.Pp
+The contents of the array
+.Fa base
+are sorted in ascending order according to
+a comparison function pointed to by
+.Fa compar ,
+which requires two arguments pointing to the objects being
+compared.
+.Pp
+The comparison function must return an integer less than, equal to, or
+greater than zero if the first argument is considered to be respectively
+less than, equal to, or greater than the second.
+.Pp
+The functions
+.Fn qsort
+and
+.Fn heapsort
+are
+.Em not
+stable, that is, if two members compare as equal, their order in
+the sorted array is undefined.
+The function
+.Fn mergesort
+is stable.
+.Pp
+The
+.Fn qsort
+function is an implementation of C.A.R. Hoare's ``quicksort'' algorithm,
+a variant of partition-exchange sorting; in particular, see D.E. Knuth's
+Algorithm Q.
+.Fn qsort
+takes O N lg N average time.
+This implementation uses median selection to avoid its
+O N**2 worst-case behavior.
+.Pp
+The
+.Fn heapsort
+function is an implementation of J.W.J. William's ``heapsort'' algorithm,
+a variant of selection sorting; in particular, see D.E. Knuth's Algorithm H.
+.Fn heapsort
+takes O N lg N worst-case time.
+Its
+.Em only
+advantage over
+.Fn qsort
+is that it uses almost no additional memory; while
+.Fn qsort
+does not allocate memory, it is implemented using recursion.
+.Pp
+The function
+.Fn mergesort
+requires additional memory of size
+.Fa nmemb *
+.Fa size
+bytes; it should be used only when space is not at a premium.
+.Fn mergesort
+is optimized for data with pre-existing order; its worst case
+time is O N lg N; its best case is O N.
+.Pp
+Normally,
+.Fn qsort
+is faster than
+.Fn mergesort
+is faster than
+.Fn heapsort .
+Memory availability and pre-existing order in the data can make this
+untrue.
+.Sh RETURN VALUES
+The
+.Fn qsort
+function
+returns no value.
+.Pp
+Upon successful completion,
+.Fn heapsort
+and
+.Fn mergesort
+return 0.
+Otherwise, they return \-1 and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn heapsort
+function succeeds unless:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa size
+argument is zero, or,
+the
+.Fa size
+argument to
+.Fn mergesort
+is less than
+.Dq "sizeof(void *) / 2" .
+.It Bq Er ENOMEM
+.Fn heapsort
+or
+.Fn mergesort
+were unable to allocate memory.
+.El
+.Sh COMPATIBILITY
+Previous versions of
+.Fn qsort
+did not permit the comparison routine itself to call
+.Fn qsort .
+This is no longer true.
+.Sh SEE ALSO
+.Xr sort 1 ,
+.Xr radixsort 3
+.Rs
+.%A Hoare, C.A.R.
+.%D 1962
+.%T "Quicksort"
+.%J "The Computer Journal"
+.%V 5:1
+.%P pp. 10-15
+.Re
+.Rs
+.%A Williams, J.W.J
+.%D 1964
+.%T "Heapsort"
+.%J "Communications of the ACM"
+.%V 7:1
+.%P pp. 347-348
+.Re
+.Rs
+.%A Knuth, D.E.
+.%D 1968
+.%B "The Art of Computer Programming"
+.%V Vol. 3
+.%T "Sorting and Searching"
+.%P pp. 114-123, 145-149
+.Re
+.Rs
+.%A McIlroy, P.M.
+.%D 1993
+.%T "Optimistic Sorting and Information Theoretic Complexity"
+.%J "Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms"
+.%P pp. 467-474
+.Re
+.Rs
+.%A Bentley, J.L. and McIlroy, M.D.
+.%D 1993
+.%T "Engineering a Sort Function"
+.%J "Software-Practice and Experience"
+.%V Vol. 23
+.%P pp. 1249-1265
+.Re
+.Sh STANDARDS
+The
+.Fn qsort
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/stdlib/qsort.c b/lib/nbsd_libc/stdlib/qsort.c
new file mode 100644 (file)
index 0000000..9652aaf
--- /dev/null
@@ -0,0 +1,171 @@
+/*     $NetBSD: qsort.c,v 1.20 2009/06/01 06:37:40 yamt Exp $  */
+
+/*-
+ * Copyright (c) 1992, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)qsort.c    8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: qsort.c,v 1.20 2009/06/01 06:37:40 yamt Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+
+static inline char     *med3 __P((char *, char *, char *,
+    int (*)(const void *, const void *)));
+static inline void      swapfunc __P((char *, char *, size_t, int));
+
+#define min(a, b)      (a) < (b) ? a : b
+
+/*
+ * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
+ */
+#define swapcode(TYPE, parmi, parmj, n) {              \
+       size_t i = (n) / sizeof (TYPE);                 \
+       TYPE *pi = (TYPE *)(void *)(parmi);             \
+       TYPE *pj = (TYPE *)(void *)(parmj);             \
+       do {                                            \
+               TYPE    t = *pi;                        \
+               *pi++ = *pj;                            \
+               *pj++ = t;                              \
+        } while (--i > 0);                             \
+}
+
+#define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \
+       es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1;
+
+static inline void
+swapfunc(char *a, char *b, size_t n, int swaptype)
+{
+
+       if (swaptype <= 1) 
+               swapcode(long, a, b, n)
+       else
+               swapcode(char, a, b, n)
+}
+
+#define swap(a, b)                                             \
+       if (swaptype == 0) {                                    \
+               long t = *(long *)(void *)(a);                  \
+               *(long *)(void *)(a) = *(long *)(void *)(b);    \
+               *(long *)(void *)(b) = t;                       \
+       } else                                                  \
+               swapfunc(a, b, es, swaptype)
+
+#define vecswap(a, b, n) if ((n) > 0) swapfunc((a), (b), (size_t)(n), swaptype)
+
+static inline char *
+med3(char *a, char *b, char *c,
+    int (*cmp) __P((const void *, const void *)))
+{
+
+       return cmp(a, b) < 0 ?
+              (cmp(b, c) < 0 ? b : (cmp(a, c) < 0 ? c : a ))
+              :(cmp(b, c) > 0 ? b : (cmp(a, c) < 0 ? a : c ));
+}
+
+void
+qsort(void *a, size_t n, size_t es,
+    int (*cmp) __P((const void *, const void *)))
+{
+       char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
+       size_t d, r;
+       int swaptype, cmp_result;
+
+       _DIAGASSERT(a != NULL);
+       _DIAGASSERT(cmp != NULL);
+
+loop:  SWAPINIT(a, es);
+       if (n < 7) {
+               for (pm = (char *) a + es; pm < (char *) a + n * es; pm += es)
+                       for (pl = pm; pl > (char *) a && cmp(pl - es, pl) > 0;
+                            pl -= es)
+                               swap(pl, pl - es);
+               return;
+       }
+       pm = (char *) a + (n / 2) * es;
+       if (n > 7) {
+               pl = (char *) a;
+               pn = (char *) a + (n - 1) * es;
+               if (n > 40) {
+                       d = (n / 8) * es;
+                       pl = med3(pl, pl + d, pl + 2 * d, cmp);
+                       pm = med3(pm - d, pm, pm + d, cmp);
+                       pn = med3(pn - 2 * d, pn - d, pn, cmp);
+               }
+               pm = med3(pl, pm, pn, cmp);
+       }
+       swap(a, pm);
+       pa = pb = (char *) a + es;
+
+       pc = pd = (char *) a + (n - 1) * es;
+       for (;;) {
+               while (pb <= pc && (cmp_result = cmp(pb, a)) <= 0) {
+                       if (cmp_result == 0) {
+                               swap(pa, pb);
+                               pa += es;
+                       }
+                       pb += es;
+               }
+               while (pb <= pc && (cmp_result = cmp(pc, a)) >= 0) {
+                       if (cmp_result == 0) {
+                               swap(pc, pd);
+                               pd -= es;
+                       }
+                       pc -= es;
+               }
+               if (pb > pc)
+                       break;
+               swap(pb, pc);
+               pb += es;
+               pc -= es;
+       }
+
+       pn = (char *) a + n * es;
+       r = min(pa - (char *) a, pb - pa);
+       vecswap(a, pb - r, r);
+       r = min((size_t)(pd - pc), pn - pd - es);
+       vecswap(pb, pn - r, r);
+       if ((r = pb - pa) > es)
+               qsort(a, r / es, es, cmp);
+       if ((r = pd - pc) > es) { 
+               /* Iterate rather than recurse to save stack space */
+               a = pn - r;
+               n = r / es;
+               goto loop;
+       }
+/*             qsort(pn - r, r / es, es, cmp);*/
+}
diff --git a/lib/nbsd_libc/stdlib/radixsort.3 b/lib/nbsd_libc/stdlib/radixsort.3
new file mode 100644 (file)
index 0000000..109466a
--- /dev/null
@@ -0,0 +1,167 @@
+.\"    $NetBSD: radixsort.3,v 1.13 2003/08/07 16:43:43 agc Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)radixsort.3  8.2 (Berkeley) 1/27/94
+.\"
+.Dd January 27, 1994
+.Dt RADIXSORT 3
+.Os
+.Sh NAME
+.Nm radixsort ,
+.Nm sradixsort
+.Nd radix sort
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In limits.h
+.In stdlib.h
+.Ft int
+.Fn radixsort "const u_char **base" "int nmemb" "u_char *table" "u_int endbyte"
+.Ft int
+.Fn sradixsort "const u_char **base" "int nmemb" "u_char *table" "u_int endbyte"
+.Sh DESCRIPTION
+The
+.Fn radixsort
+and
+.Fn sradixsort
+functions
+are implementations of radix sort.
+.Pp
+These functions sort an
+.Fa nmemb
+element array of pointers to byte strings, with
+the initial member of which is referenced by
+.Fa base .
+The byte strings may contain any values.
+End of strings is denoted
+by character which has same weight as user specified value
+.Fa endbyte .
+.Fa endbyte
+has to be between 0 and 255.
+.Pp
+Applications may specify a sort order by providing the
+.Fa table
+argument.
+If
+.Pf non- Dv NULL ,
+.Fa table
+must reference an array of
+.Dv UCHAR_MAX
++ 1 bytes which contains the sort
+weight of each possible byte value.
+The end-of-string byte must have a sort weight of 0 or 255
+(for sorting in reverse order).
+More than one byte may have the same sort weight.
+The
+.Fa table
+argument
+is useful for applications which wish to sort different characters
+equally, for example, providing a table with the same weights
+for A-Z as for a-z will result in a case-insensitive sort.
+If
+.Fa table
+is NULL, the contents of the array are sorted in ascending order
+according to the
+.Tn ASCII
+order of the byte strings they reference and
+.Fa endbyte
+has a sorting weight of 0.
+.Pp
+The
+.Fn sradixsort
+function is stable, that is, if two elements compare as equal, their
+order in the sorted array is unchanged.
+The
+.Fn sradixsort
+function uses additional memory sufficient to hold
+.Fa nmemb
+pointers.
+.Pp
+The
+.Fn radixsort
+function is not stable, but uses no additional memory.
+.Pp
+These functions are variants of most-significant-byte radix sorting; in
+particular, see D.E. Knuth's Algorithm R and section 5.2.5, exercise 10.
+They take linear time relative to the number of bytes in the strings.
+.Sh RETURN VALUES
+Upon successful completion 0 is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The value of the
+.Fa endbyte
+element of
+.Fa table
+is not 0 or 255.
+.El
+.Pp
+Additionally, the
+.Fn sradixsort
+function
+may fail and set
+.Va errno
+for any of the errors specified for the library routine
+.Xr malloc 3 .
+.Sh SEE ALSO
+.Xr sort 1 ,
+.Xr qsort 3
+.Pp
+.Rs
+.%A Knuth, D.E.
+.%D 1968
+.%B "The Art of Computer Programming"
+.%T "Sorting and Searching"
+.%V Vol. 3
+.%P pp. 170-178
+.Re
+.Rs
+.%A Paige, R.
+.%D 1987
+.%T "Three Partition Refinement Algorithms"
+.%J "SIAM J. Comput."
+.%V Vol. 16
+.%N No. 6
+.Re
+.Rs
+.%A McIlroy, P.
+.%D 1993
+.%B "Engineering Radix Sort"
+.%T "Computing Systems"
+.%V Vol. 6:1
+.%P pp. 5-27
+.Re
+.Sh HISTORY
+The
+.Fn radixsort
+function first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/stdlib/radixsort.c b/lib/nbsd_libc/stdlib/radixsort.c
new file mode 100644 (file)
index 0000000..e8435f5
--- /dev/null
@@ -0,0 +1,329 @@
+/*     $NetBSD: radixsort.c,v 1.19 2009/09/05 08:53:06 dsl Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Peter McIlroy and by Dan Bernstein at New York University, 
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)radixsort.c        8.2 (Berkeley) 4/28/95";
+#else
+__RCSID("$NetBSD: radixsort.c,v 1.19 2009/09/05 08:53:06 dsl Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Radixsort routines.
+ * 
+ * Program r_sort_a() is unstable but uses O(logN) extra memory for a stack.
+ * Use radixsort(a, n, trace, endchar) for this case.
+ * 
+ * For stable sorting (using N extra pointers) use sradixsort(), which calls
+ * r_sort_b().
+ * 
+ * For a description of this code, see D. McIlroy, P. McIlroy, K. Bostic,
+ * "Engineering Radix Sort".
+ */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+
+#ifdef __weak_alias
+__weak_alias(radixsort,_radixsort)
+__weak_alias(sradixsort,_sradixsort)
+#endif
+
+typedef struct {
+       const u_char **sa;
+       int sn, si;
+} stack;
+
+static inline void simplesort(const u_char **, int, int, const u_char *, u_int);
+static void r_sort_a(const u_char **, int, int, const u_char *, u_int);
+static void r_sort_b(const u_char **,
+           const u_char **, int, int, const u_char *, u_int);
+
+#define        THRESHOLD       20              /* Divert to simplesort(). */
+#define        SIZE            512             /* Default stack size. */
+
+#define SETUP {                                                                \
+       if (tab == NULL) {                                              \
+               tr = tr0;                                               \
+               for (c = 0; c < endch; c++)                             \
+                       tr0[c] = c + 1;                                 \
+               tr0[c] = 0;                                             \
+               for (c++; c < 256; c++)                                 \
+                       tr0[c] = c;                                     \
+               endch = 0;                                              \
+       } else {                                                        \
+               endch = tab[endch];                                     \
+               tr = tab;                                               \
+               if (endch != 0 && endch != 255) {                       \
+                       errno = EINVAL;                                 \
+                       return (-1);                                    \
+               }                                                       \
+       }                                                               \
+}
+
+int
+radixsort(const u_char **a, int n, const u_char *tab, u_int endch)
+{
+       const u_char *tr;
+       u_int c;
+       u_char tr0[256];
+
+       _DIAGASSERT(a != NULL);
+
+       SETUP;
+       r_sort_a(a, n, 0, tr, endch);
+       return (0);
+}
+
+int
+sradixsort(const u_char **a, int n, const u_char *tab, u_int endch)
+{
+       const u_char *tr, **ta;
+       u_int c;
+       u_char tr0[256];
+
+       _DIAGASSERT(a != NULL);
+       if (a == NULL) {
+               errno = EFAULT;
+               return (-1);
+       }
+
+       SETUP;
+       if (n < THRESHOLD)
+               simplesort(a, n, 0, tr, endch);
+       else {
+               if ((ta = malloc(n * sizeof(a))) == NULL)
+                       return (-1);
+               r_sort_b(a, ta, n, 0, tr, endch);
+               free(ta);
+       }
+       return (0);
+}
+
+#define empty(s)       (s >= sp)
+#define pop(a, n, i)   a = (--sp)->sa, n = sp->sn, i = sp->si
+#define push(a, n, i)  sp->sa = a, sp->sn = n, (sp++)->si = i
+#define swap(a, b, t)  t = a, a = b, b = t
+
+/* Unstable, in-place sort. */
+static void
+r_sort_a(const u_char **a, int n, int i, const u_char *tr, u_int endch)
+{
+       static u_int count[256], nc, bmin;
+       u_int c;
+       const u_char **ak, *r;
+       stack s[SIZE], *sp, *sp0, *sp1, temp;
+       u_int *cp, bigc;
+       const u_char **an, *t, **aj, **top[256];
+
+       _DIAGASSERT(a != NULL);
+       _DIAGASSERT(tr != NULL);
+
+       /* Set up stack. */
+       sp = s;
+       push(a, n, i);
+       while (!empty(s)) {
+               pop(a, n, i);
+               if (n < THRESHOLD) {
+                       simplesort(a, n, i, tr, endch);
+                       continue;
+               }
+               an = a + n;
+
+               /* Make character histogram. */
+               if (nc == 0) {
+                       bmin = 255;     /* First occupied bin, excluding eos. */
+                       for (ak = a; ak < an;) {
+                               c = tr[(*ak++)[i]];
+                               if (++count[c] == 1 && c != endch) {
+                                       if (c < bmin)
+                                               bmin = c;
+                                       nc++;
+                               }
+                       }
+                       if (sp + nc > s + SIZE) {       /* Get more stack. */
+                               r_sort_a(a, n, i, tr, endch);
+                               continue;
+                       }
+               }
+
+               /*
+                * Set top[]; push incompletely sorted bins onto stack.
+                * top[] = pointers to last out-of-place element in bins.
+                * count[] = counts of elements in bins.
+                * Before permuting: top[c-1] + count[c] = top[c];
+                * during deal: top[c] counts down to top[c-1].
+                */
+               sp0 = sp1 = sp;         /* Stack position of biggest bin. */
+               bigc = 2;               /* Size of biggest bin. */
+               if (endch == 0)         /* Special case: set top[eos]. */
+                       top[0] = ak = a + count[0];
+               else {
+                       ak = a;
+                       top[255] = an;
+               }
+               for (cp = count + bmin; nc > 0; cp++) {
+                       while (*cp == 0)        /* Find next non-empty pile. */
+                               cp++;
+                       if (*cp > 1) {
+                               if (*cp > bigc) {
+                                       bigc = *cp;
+                                       sp1 = sp;
+                               }
+                               push(ak, *cp, i+1);
+                       }
+                       top[cp-count] = ak += *cp;
+                       nc--;
+               }
+               swap(*sp0, *sp1, temp); /* Play it safe -- biggest bin last. */
+
+               /*
+                * Permute misplacements home.  Already home: everything
+                * before aj, and in bin[c], items from top[c] on.
+                * Inner loop:
+                *      r = next element to put in place;
+                *      ak = top[r[i]] = location to put the next element.
+                *      aj = bottom of 1st disordered bin.
+                * Outer loop:
+                *      Once the 1st disordered bin is done, ie. aj >= ak,
+                *      aj<-aj + count[c] connects the bins in a linked list;
+                *      reset count[c].
+                */
+               for (aj = a; aj < an;  *aj = r, aj += count[c], count[c] = 0)
+                       for (r = *aj;  aj < (ak = --top[c = tr[r[i]]]);)
+                               swap(*ak, r, t);
+       }
+}
+
+/* Stable sort, requiring additional memory. */
+static void
+r_sort_b(const u_char **a, const u_char **ta, int n, int i, const u_char *tr,
+    u_int endch)
+{
+       static u_int count[256], nc, bmin;
+       u_int c;
+       const u_char **ak, **ai;
+       stack s[512], *sp, *sp0, *sp1, temp;
+       const u_char **top[256];
+       u_int *cp, bigc;
+
+       _DIAGASSERT(a != NULL);
+       _DIAGASSERT(ta != NULL);
+       _DIAGASSERT(tr != NULL);
+
+       sp = s;
+       push(a, n, i);
+       while (!empty(s)) {
+               pop(a, n, i);
+               if (n < THRESHOLD) {
+                       simplesort(a, n, i, tr, endch);
+                       continue;
+               }
+
+               if (nc == 0) {
+                       bmin = 255;
+                       for (ak = a + n; --ak >= a;) {
+                               c = tr[(*ak)[i]];
+                               if (++count[c] == 1 && c != endch) {
+                                       if (c < bmin)
+                                               bmin = c;
+                                       nc++;
+                               }
+                       }
+                       if (sp + nc > s + SIZE) {
+                               r_sort_b(a, ta, n, i, tr, endch);
+                               continue;
+                       }
+               }
+
+               sp0 = sp1 = sp;
+               bigc = 2;
+               if (endch == 0) {
+                       top[0] = ak = a + count[0];
+                       count[0] = 0;
+               } else {
+                       ak = a;
+                       top[255] = a + n;
+                       count[255] = 0;
+               }
+               for (cp = count + bmin; nc > 0; cp++) {
+                       while (*cp == 0)
+                               cp++;
+                       if ((c = *cp) > 1) {
+                               if (c > bigc) {
+                                       bigc = c;
+                                       sp1 = sp;
+                               }
+                               push(ak, c, i+1);
+                       }
+                       top[cp-count] = ak += c;
+                       *cp = 0;                        /* Reset count[]. */
+                       nc--;
+               }
+               swap(*sp0, *sp1, temp);
+
+               for (ak = ta + n, ai = a+n; ak > ta;)   /* Copy to temp. */
+                       *--ak = *--ai;
+               for (ak = ta+n; --ak >= ta;)            /* Deal to piles. */
+                       *--top[tr[(*ak)[i]]] = *ak;
+       }
+}
+
+/* insertion sort */
+static inline void
+simplesort(const u_char **a, int n, int b, const u_char *tr, u_int endch)
+{
+       u_char ch;
+       const u_char  **ak, **ai, *s, *t;
+
+       _DIAGASSERT(a != NULL);
+       _DIAGASSERT(tr != NULL);
+
+       for (ak = a+1; --n >= 1; ak++)
+               for (ai = ak; ai > a; ai--) {
+                       for (s = ai[0] + b, t = ai[-1] + b;
+                           (ch = tr[*s]) != endch; s++, t++)
+                               if (ch != tr[*t])
+                                       break;
+                       if (ch >= tr[*t])
+                               break;
+                       swap(ai[0], ai[-1], s);
+               }
+}
diff --git a/lib/nbsd_libc/stdlib/rand.3 b/lib/nbsd_libc/stdlib/rand.3
new file mode 100644 (file)
index 0000000..85f0423
--- /dev/null
@@ -0,0 +1,100 @@
+.\"    $NetBSD: rand.3,v 1.12 2010/03/22 19:30:54 joerg Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)rand.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt RAND 3
+.Os
+.Sh NAME
+.Nm rand ,
+.Nm srand ,
+.Nm rand_r
+.Nd bad random number generator
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft void
+.Fn srand "unsigned int seed"
+.Ft int
+.Fn rand void
+.Ft int
+.Fn rand_r "unsigned int *seed"
+.Sh DESCRIPTION
+.Bf -symbolic
+These interfaces are obsoleted by
+.Xr random 3 .
+.Ef
+.Pp
+The
+.Fn rand
+function computes a sequence of pseudo-random integers in the range
+of 0 to
+.Dv RAND_MAX
+(as defined by the header file
+.In stdlib.h ) .
+.Pp
+The
+.Fn srand
+function sets its argument as the seed for a new sequence of
+pseudo-random numbers to be returned by
+.Fn rand .
+These sequences are repeatable by calling
+.Fn srand
+with the same seed value.
+.Pp
+If no seed value is provided, the
+.Fn rand
+function is automatically seeded with a value of 1.
+.Pp
+The
+.Fn rand_r
+function is a reentrant interface to
+.Fn rand ;
+the seed has to be supplied and is maintained by the caller.
+.Sh SEE ALSO
+.Xr random 3 ,
+.Xr rnd 4
+.Sh STANDARDS
+The
+.Fn rand
+and
+.Fn srand
+functions
+conform to
+.St -ansiC .
+The
+.Fn rand_r
+function conforms to
+.St -p1003.1c-95 .
diff --git a/lib/nbsd_libc/stdlib/rand.c b/lib/nbsd_libc/stdlib/rand.c
new file mode 100644 (file)
index 0000000..b2e4544
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: rand.c,v 1.10 2003/08/07 16:43:43 agc Exp $    */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)rand.c     8.1 (Berkeley) 6/14/93";
+#else
+__RCSID("$NetBSD: rand.c,v 1.10 2003/08/07 16:43:43 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <stdlib.h>
+
+static u_long next = 1;
+
+int
+rand()
+{
+       /* LINTED integer overflow */
+       return (int)((next = next * 1103515245 + 12345) % ((u_long)RAND_MAX + 1));
+}
+
+void
+srand(seed)
+       u_int seed;
+{
+       next = seed;
+}
diff --git a/lib/nbsd_libc/stdlib/rand48.3 b/lib/nbsd_libc/stdlib/rand48.3
new file mode 100644 (file)
index 0000000..b9939ec
--- /dev/null
@@ -0,0 +1,163 @@
+.\"    $NetBSD: rand48.3,v 1.11 2006/03/31 11:43:54 drochner Exp $
+.\"
+.\" Copyright (c) 1993 Martin Birgmeier
+.\" All rights reserved.
+.\"
+.\" You may redistribute unmodified or modified versions of this source
+.\" code provided that the above copyright notice and this and the
+.\" following conditions are retained.
+.\"
+.\" This software is provided ``as is'', and comes with no warranties
+.\" of any kind. I shall in no event be liable for anything that happens
+.\" to anyone/anything when using this software.
+.\"
+.Dd October 8, 1993
+.Dt RAND48 3
+.Os
+.Sh NAME
+.Nm drand48 ,
+.Nm erand48 ,
+.Nm lrand48 ,
+.Nm nrand48 ,
+.Nm mrand48 ,
+.Nm jrand48 ,
+.Nm srand48 ,
+.Nm seed48 ,
+.Nm lcong48
+.Nd pseudo-random number generators and initialization routines
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft double
+.Fn drand48 void
+.Ft double
+.Fn erand48 "unsigned short xseed[3]"
+.Ft long
+.Fn lrand48 void
+.Ft long
+.Fn nrand48 "unsigned short xseed[3]"
+.Ft long
+.Fn mrand48 void
+.Ft long
+.Fn jrand48 "unsigned short xseed[3]"
+.Ft void
+.Fn srand48 "long seed"
+.Ft "unsigned short *"
+.Fn seed48 "unsigned short xseed[3]"
+.Ft void
+.Fn lcong48 "unsigned short p[7]"
+.Sh DESCRIPTION
+The
+.Fn rand48
+family of functions generates pseudo-random numbers using a linear
+congruential algorithm working on integers 48 bits in size.
+The particular formula employed is
+r(n+1) = (a * r(n) + c) mod m
+where the default values are
+for the multiplicand a = 0x5deece66d = 25214903917 and
+the addend c = 0xb = 11.
+The modulus is always fixed at m = 2 ** 48.
+r(n) is called the seed of the random number generator.
+.Pp
+For all the six generator routines described next, the first
+computational step is to perform a single iteration of the algorithm.
+.Pp
+.Fn drand48
+and
+.Fn erand48
+return values of type double.
+The full 48 bits of r(n+1) are loaded into the mantissa of the
+returned value, with the exponent set such that the values produced
+lie in the interval [0.0, 1.0).
+.Pp
+.Fn lrand48
+and
+.Fn nrand48
+return values of type long in the range [0, 2**31-1].
+The high-order (31) bits of r(n+1) are loaded into the lower bits
+of the returned value, with the topmost (sign) bit set to zero.
+.Pp
+.Fn mrand48
+and
+.Fn jrand48
+return values of type long in the range [-2**31, 2**31-1].
+The high-order (32) bits of r(n+1) are loaded into the returned value.
+.Pp
+.Fn drand48 ,
+.Fn lrand48 ,
+and
+.Fn mrand48
+use an internal buffer to store r(n).
+For these functions
+the initial value of r(0) = 0x1234abcd330e = 20017429951246.
+.Pp
+On the other hand,
+.Fn erand48 ,
+.Fn nrand48 ,
+and
+.Fn jrand48
+use a user-supplied buffer to store the seed r(n), which consists
+of an array of 3 shorts, where the zeroth member holds the least
+significant bits.
+.Pp
+All functions share the same multiplicand and addend.
+.Pp
+.Fn srand48
+is used to initialize the internal buffer r(n) of
+.Fn drand48 ,
+.Fn lrand48 ,
+and
+.Fn mrand48
+such that the 32 bits of the seed value are copied into the upper 32 bits
+of r(n), with the lower 16 bits of r(n) arbitrarily being set to 0x330e.
+Additionally, the constant multiplicand and addend of the algorithm are
+reset to the default values given above.
+.Pp
+.Fn seed48
+also initializes the internal buffer r(n) of
+.Fn drand48 ,
+.Fn lrand48 ,
+and
+.Fn mrand48 ,
+but here all 48 bits of the seed can be specified in an array of 3 shorts,
+where the zeroth member specifies the lowest bits.
+Again, the constant multiplicand and addend of the algorithm are
+reset to the default values given above.
+.Fn seed48
+returns a pointer to an array of 3 shorts which contains the old seed.
+This array is statically allocated, thus its contents are lost after
+each new call to
+.Fn seed48 .
+.Pp
+Finally,
+.Fn lcong48
+allows full control over the multiplicand and addend used in
+.Fn drand48 ,
+.Fn erand48 ,
+.Fn lrand48 ,
+.Fn nrand48 ,
+.Fn mrand48 ,
+and
+.Fn jrand48 ,
+and the seed used in
+.Fn drand48 ,
+.Fn lrand48 ,
+and
+.Fn mrand48 .
+An array of 7 shorts is passed as parameter; the first three shorts are
+used to initialize the seed; the second three are used to initialize the
+multiplicand; and the last short is used to initialize the addend.
+It is thus not possible to use values greater than 0xffff as the addend.
+.Pp
+Note that all three methods of seeding the random number generator
+always also set the multiplicand and addend for any of the six
+generator calls.
+.Pp
+For a more powerful random number generator, see
+.Xr random 3 .
+.Sh SEE ALSO
+.Xr rand 3 ,
+.Xr random 3
+.Sh AUTHORS
+Martin Birgmeier
diff --git a/lib/nbsd_libc/stdlib/rand48.h b/lib/nbsd_libc/stdlib/rand48.h
new file mode 100644 (file)
index 0000000..f652c9d
--- /dev/null
@@ -0,0 +1,34 @@
+/*     $NetBSD: rand48.h,v 1.5 2006/03/22 20:52:16 drochner Exp $      */
+
+/*
+ * Copyright (c) 1993 Martin Birgmeier
+ * All rights reserved.
+ *
+ * You may redistribute unmodified or modified versions of this source
+ * code provided that the above copyright notice and this and the
+ * following conditions are retained.
+ *
+ * This software is provided ``as is'', and comes with no warranties
+ * of any kind. I shall in no event be liable for anything that happens
+ * to anyone/anything when using this software.
+ */
+
+#ifndef _RAND48_H_
+#define _RAND48_H_
+
+#include <stdlib.h>
+
+extern void            __dorand48 __P((unsigned short[3]));
+extern unsigned short  __rand48_seed[3];
+extern unsigned short  __rand48_mult[3];
+extern unsigned short  __rand48_add;
+
+#define        RAND48_SEED_0   (0x330e)
+#define        RAND48_SEED_1   (0xabcd)
+#define        RAND48_SEED_2   (0x1234)
+#define        RAND48_MULT_0   (0xe66d)
+#define        RAND48_MULT_1   (0xdeec)
+#define        RAND48_MULT_2   (0x0005)
+#define        RAND48_ADD      (0x000b)
+
+#endif /* _RAND48_H_ */
diff --git a/lib/nbsd_libc/stdlib/rand_r.c b/lib/nbsd_libc/stdlib/rand_r.c
new file mode 100644 (file)
index 0000000..7b2e9d7
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: rand_r.c,v 1.5 2003/08/07 16:43:43 agc Exp $   */
+
+/*-
+ * Copyright (c) 1990 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "from: @(#)rand.c        5.6 (Berkeley) 6/24/91";
+#else
+__RCSID("$NetBSD: rand_r.c,v 1.5 2003/08/07 16:43:43 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+
+int
+rand_r(seed)
+       unsigned int *seed;
+{
+       _DIAGASSERT(seed != NULL);
+
+       return ((*seed = *seed * 1103515245 + 12345) & RAND_MAX);
+}
diff --git a/lib/nbsd_libc/stdlib/random.3 b/lib/nbsd_libc/stdlib/random.3
new file mode 100644 (file)
index 0000000..48eb01b
--- /dev/null
@@ -0,0 +1,182 @@
+.\"    $NetBSD: random.3,v 1.19 2008/02/28 16:16:35 christos Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)random.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd February 28, 2008
+.Dt RANDOM 3
+.Os
+.Sh NAME
+.Nm random ,
+.Nm srandom ,
+.Nm initstate ,
+.Nm setstate
+.Nd better random number generator; routines for changing generators
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft long
+.Fn random void
+.Ft void
+.Fn srandom "unsigned long seed"
+.Ft char *
+.Fn initstate "unsigned long seed" "char *state" "size_t n"
+.Ft char *
+.Fn setstate "char *state"
+.Sh DESCRIPTION
+The
+.Fn random
+function
+uses a non-linear additive feedback random number generator employing a
+default table of size 31 long integers to return successive pseudo-random
+numbers in the range from 0 to
+.if t 2\u\s731\s10\d\(mi1.
+.if n (2**31)\(mi1.
+The period of this random number generator is very large, approximately
+.if t 16\(mu(2\u\s731\s10\d\(mi1).
+.if n 16*((2**31)\(mi1).
+The maximum value
+.Dv RANDOM_MAX
+is defined in
+.In stdlib.h .
+.Pp
+The
+.Fn random
+and
+.Fn srandom
+have (almost) the same calling sequence and initialization properties as
+.Xr rand 3
+and
+.Xr srand 3 .
+The difference is that
+.Xr rand 3
+produces a much less random sequence \(em in fact, the low dozen bits
+generated by
+.Xr rand 3
+go through a cyclic pattern.
+All the bits generated by
+.Fn random
+are usable.
+For example,
+.Sq Li random()\*[Am]01
+will produce a random binary value.
+.Pp
+Like
+.Xr rand 3 ,
+.Fn random
+will by default produce a sequence of numbers that can be duplicated
+by calling
+.Fn srandom
+with
+.Ql 1
+as the seed.
+.Pp
+The
+.Fn initstate
+routine allows a state array, passed in as an argument, to be initialized
+for future use.
+The size of the state array (in bytes) is used by
+.Fn initstate
+to decide how sophisticated a random number generator it should use \(em the
+more state, the better the random numbers will be.
+(Current "optimal" values for the amount of state information are
+8, 32, 64, 128, and 256 bytes; other amounts will be rounded down to
+the nearest known amount.
+Using less than 8 bytes will cause an error).
+The seed for the initialization (which specifies a starting point for
+the random number sequence, and provides for restarting at the same
+point) is also an argument.
+The state array passed to
+.Fn initstate
+must be aligned to a 32-bit boundary.
+This can be achieved by using
+a suitably-sized array of ints, and casting the array to char * when
+passing it to
+.Fn initstate .
+The
+.Fn initstate
+function
+returns a pointer to the previous state information array.
+.Pp
+Once a state has been initialized, the
+.Fn setstate
+routine provides for rapid switching between states.
+The
+.Fn setstate
+function
+returns a pointer to the previous state array; its
+argument state array is used for further random number generation
+until the next call to
+.Fn initstate
+or
+.Fn setstate .
+.Pp
+Once a state array has been initialized, it may be restarted at a
+different point either by calling
+.Fn initstate
+(with the desired seed, the state array, and its size) or by calling
+both
+.Fn setstate
+(with the state array) and
+.Fn srandom
+(with the desired seed).
+The advantage of calling both
+.Fn setstate
+and
+.Fn srandom
+is that the size of the state array does not have to be remembered after
+it is initialized.
+.Pp
+With 256 bytes of state information, the period of the random number
+generator is greater than
+.if t 2\u\s769\s10\d,
+.if n 2**69
+which should be sufficient for most purposes.
+.Sh DIAGNOSTICS
+If
+.Fn initstate
+is called with less than 8 bytes of state information, or if
+.Fn setstate
+detects that the state information has been garbled, error
+messages are printed on the standard error output.
+.Sh SEE ALSO
+.Xr rand 3 ,
+.Xr srand 3 ,
+.Xr rnd 4 ,
+.Xr rnd 9
+.Sh HISTORY
+These
+functions appeared in
+.Bx 4.2 .
+.Sh AUTHORS
+.An Earl T. Cohen
+.Sh BUGS
+About 2/3 the speed of
+.Xr rand 3 .
diff --git a/lib/nbsd_libc/stdlib/remque.c b/lib/nbsd_libc/stdlib/remque.c
new file mode 100644 (file)
index 0000000..0ebfc07
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ *  Copyright (c) 1993 John Brezak
+ *  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.
+ *  3. The name of the author may be used to endorse or promote products
+ *     derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: remque.c,v 1.2 2005/07/06 17:17:15 drochner Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <search.h>
+
+struct qelem {
+        struct qelem *q_forw;
+        struct qelem *q_back;
+};
+
+void
+remque(element)
+       void *element;
+{
+       struct qelem *e = (struct qelem *) element;
+
+       _DIAGASSERT(e != 0);
+
+       if (e->q_forw)
+               e->q_forw->q_back = e->q_back;
+       if (e->q_back)
+               e->q_back->q_forw = e->q_forw;
+}
diff --git a/lib/nbsd_libc/stdlib/seed48.c b/lib/nbsd_libc/stdlib/seed48.c
new file mode 100644 (file)
index 0000000..36c0570
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: seed48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $ */
+
+/*
+ * Copyright (c) 1993 Martin Birgmeier
+ * All rights reserved.
+ *
+ * You may redistribute unmodified or modified versions of this source
+ * code provided that the above copyright notice and this and the
+ * following conditions are retained.
+ *
+ * This software is provided ``as is'', and comes with no warranties
+ * of any kind. I shall in no event be liable for anything that happens
+ * to anyone/anything when using this software.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: seed48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+
+#include "rand48.h"
+
+#ifdef __weak_alias
+__weak_alias(seed48,_seed48)
+#endif
+
+unsigned short *
+seed48(unsigned short xseed[3])
+{
+       static unsigned short sseed[3];
+
+       _DIAGASSERT(xseed != NULL);
+
+       sseed[0] = __rand48_seed[0];
+       sseed[1] = __rand48_seed[1];
+       sseed[2] = __rand48_seed[2];
+       __rand48_seed[0] = xseed[0];
+       __rand48_seed[1] = xseed[1];
+       __rand48_seed[2] = xseed[2];
+       __rand48_mult[0] = RAND48_MULT_0;
+       __rand48_mult[1] = RAND48_MULT_1;
+       __rand48_mult[2] = RAND48_MULT_2;
+       __rand48_add = RAND48_ADD;
+       return sseed;
+}
diff --git a/lib/nbsd_libc/stdlib/setenv.c b/lib/nbsd_libc/stdlib/setenv.c
new file mode 100644 (file)
index 0000000..0098b7b
--- /dev/null
@@ -0,0 +1,128 @@
+/*     $NetBSD: setenv.c,v 1.43 2010/11/14 18:11:43 tron Exp $ */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)setenv.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: setenv.c,v 1.43 2010/11/14 18:11:43 tron Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "env.h"
+#include "reentrant.h"
+#include "local.h"
+
+#ifdef __weak_alias
+__weak_alias(setenv,_setenv)
+#endif
+
+/*
+ * setenv --
+ *     Set the value of the environmental variable "name" to be
+ *     "value".  If rewrite is set, replace any current value.
+ */
+int
+setenv(const char *name, const char *value, int rewrite)
+{
+       size_t l_name, l_value, length;
+       ssize_t offset;
+       char *envvar;
+
+       _DIAGASSERT(name != NULL);
+       _DIAGASSERT(value != NULL);
+
+       l_name = __envvarnamelen(name, false);
+       if (l_name == 0 || value == NULL) {
+               errno = EINVAL;
+               return -1;
+       }
+
+       if (!__writelockenv())
+               return -1;
+
+       /* Find slot in the enviroment. */
+       offset = __getenvslot(name, l_name, true);
+       if (offset == -1)
+               goto bad;
+
+       l_value = strlen(value);
+       length = l_name + l_value + 2;
+
+       /* Handle overwriting a current environt variable. */
+       envvar = environ[offset];
+       if (envvar != NULL) {
+               if (!rewrite)
+                       goto good;
+               /*
+                * Check whether the buffer was allocated via setenv(3) and
+                * whether there is enough space. If so simply overwrite the
+                * existing value.
+                */
+               if (__canoverwriteenvvar(envvar, length)) {
+                       envvar += l_name + 1;
+                       goto copy;
+               }
+       }
+
+       /* Allocate memory for name + `=' + value + NUL. */
+       if ((envvar = __allocenvvar(length)) == NULL)
+               goto bad;
+
+       if (environ[offset] != NULL)
+               __freeenvvar(environ[offset]);
+
+       environ[offset] = envvar;
+
+       (void)memcpy(envvar, name, l_name);
+
+       envvar += l_name;
+       *envvar++ = '=';
+
+copy:
+       (void)memcpy(envvar, value, l_value + 1);
+
+good:
+       (void)__unlockenv();
+       return 0;
+
+bad:
+       (void)__unlockenv();
+       return -1;
+}
diff --git a/lib/nbsd_libc/stdlib/srand48.c b/lib/nbsd_libc/stdlib/srand48.c
new file mode 100644 (file)
index 0000000..a9673fe
--- /dev/null
@@ -0,0 +1,38 @@
+/*     $NetBSD: srand48.c,v 1.7 2005/06/12 05:21:28 lukem Exp $        */
+
+/*
+ * Copyright (c) 1993 Martin Birgmeier
+ * All rights reserved.
+ *
+ * You may redistribute unmodified or modified versions of this source
+ * code provided that the above copyright notice and this and the
+ * following conditions are retained.
+ *
+ * This software is provided ``as is'', and comes with no warranties
+ * of any kind. I shall in no event be liable for anything that happens
+ * to anyone/anything when using this software.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: srand48.c,v 1.7 2005/06/12 05:21:28 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include "rand48.h"
+
+#ifdef __weak_alias
+__weak_alias(srand48,_srand48)
+#endif
+
+void
+srand48(long seed)
+{
+       __rand48_seed[0] = RAND48_SEED_0;
+       __rand48_seed[1] = (unsigned short) seed;
+       __rand48_seed[2] = (unsigned short) ((unsigned long)seed >> 16);
+       __rand48_mult[0] = RAND48_MULT_0;
+       __rand48_mult[1] = RAND48_MULT_1;
+       __rand48_mult[2] = RAND48_MULT_2;
+       __rand48_add = RAND48_ADD;
+}
diff --git a/lib/nbsd_libc/stdlib/strfmon.3 b/lib/nbsd_libc/stdlib/strfmon.3
new file mode 100644 (file)
index 0000000..7d7fe40
--- /dev/null
@@ -0,0 +1,169 @@
+.\"    $NetBSD: strfmon.3,v 1.3 2005/04/04 08:19:00 wiz Exp $
+.\"
+.\" Copyright (c) 2001 Jeroen Ruigrok van der Werven <asmodai@FreeBSD.org>
+.\" 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 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.
+.\"
+.\"    From: FreeBSD: Id: strfmon.3,v 1.7 2003/01/06 06:21:25 tjr Exp
+.\"
+.Dd October 12, 2002
+.Dt STRFMON 3
+.Os
+.Sh NAME
+.Nm strfmon
+.Nd convert monetary value to string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In monetary.h
+.Ft ssize_t
+.Fn strfmon "char * restrict s" "size_t maxsize" "const char * restrict format" "..."
+.Sh DESCRIPTION
+The
+.Fn strfmon
+function places characters into the array pointed to by
+.Fa s
+as controlled by the string pointed to by
+.Fa format .
+No more than
+.Fa maxsize
+bytes are placed into the array.
+.Pp
+The format string is composed of zero or more directives:
+ordinary characters (not
+.Cm % ) ,
+which are copied unchanged to the output stream; and conversion
+specifications, each of which results in fetching zero or more subsequent
+arguments.
+Each conversion specification is introduced by the
+.Cm %
+character.
+After the
+.Cm % ,
+the following appear in sequence:
+.Bl -bullet
+.It
+Zero or more of the following flags:
+.Bl -tag -width "XXX"
+.It Cm = Ns Ar f
+A
+.Sq Cm =
+character followed by another character
+.Ar f
+which is used as the numeric fill character.
+.It Cm ^
+Do not use grouping characters, regardless of the current locale default.
+.It Cm +
+Represent positive values by prefixing them with a positive sign,
+and negative values by prefixing them with a negative sign.
+This is the default.
+.It Cm \&(
+Enclose negative values in parentheses.
+.It Cm \&!
+Do not include a currency symbol in the output.
+.It Cm \-
+Left justify the result.
+Only valid when a field width is specified.
+.El
+.It
+An optional minimum field width as a decimal number.
+By default, there is no minimum width.
+.It
+A
+.Sq Cm #
+sign followed by a decimal number specifying the maximum
+expected number of digits after the radix character.
+.It
+A
+.Sq Cm \&.
+character followed by a decimal number specifying the number
+of digits after the radix character.
+.It
+One of the following conversion specifiers:
+.Bl -tag -width "XXX"
+.It Cm i
+The
+.Vt double
+argument is formatted as an international monetary amount.
+.It Cm n
+The
+.Vt double
+argument is formatted as a national monetary amount.
+.It Cm %
+A
+.Sq Li %
+character is written.
+.El
+.El
+.Sh RETURN VALUES
+If the total number of resulting bytes including the terminating
+.Dv NULL
+byte is not more than
+.Fa maxsize ,
+.Fn strfmon
+returns the number of bytes placed into the array pointed to by
+.Fa s ,
+not including the terminating
+.Dv NULL
+byte.
+Otherwise, \-1 is returned,
+the contents of the array are indeterminate,
+and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn strfmon
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er E2BIG
+Conversion stopped due to lack of space in the buffer.
+.It Bq Er EINVAL
+The format string is invalid.
+.It Bq Er ENOMEM
+Not enough memory for temporary buffers.
+.El
+.Sh SEE ALSO
+.Xr localeconv 3
+.Sh STANDARDS
+The
+.Fn strfmon
+function
+conforms to
+.St -p1003.1-2001 .
+.Sh AUTHORS
+.An -nosplit
+The
+.Fn strfmon
+function was implemented by
+.An Alexey Zelkin Aq phantom@FreeBSD.org .
+.Pp
+This manual page was written by
+.An Jeroen Ruigrok van der Werven Aq asmodai@FreeBSD.org
+based on the standard's text.
+.Sh BUGS
+The
+.Fn strfmon
+function does not correctly handle multibyte characters in the
+.Fa format
+argument.
diff --git a/lib/nbsd_libc/stdlib/strfmon.c b/lib/nbsd_libc/stdlib/strfmon.c
new file mode 100644 (file)
index 0000000..d53ed7f
--- /dev/null
@@ -0,0 +1,623 @@
+/*     $NetBSD: strfmon.c,v 1.7 2009/01/30 23:46:03 lukem Exp $        */
+
+/*-
+ * Copyright (c) 2001 Alexey Zelkin <phantom@FreeBSD.org>
+ * 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.
+ *
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+__FBSDID("$FreeBSD: src/lib/libc/stdlib/strfmon.c,v 1.14 2003/03/20 08:18:55 ache Exp $");
+#else
+__RCSID("$NetBSD: strfmon.c,v 1.7 2009/01/30 23:46:03 lukem Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__NetBSD__)
+#include "namespace.h"
+#include <monetary.h>
+#endif
+
+#include <sys/types.h>
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <locale.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stddef.h>
+
+/* internal flags */
+#define        NEED_GROUPING           0x01    /* print digits grouped (default) */
+#define        SIGN_POSN_USED          0x02    /* '+' or '(' usage flag */
+#define        LOCALE_POSN             0x04    /* use locale defined +/- (default) */
+#define        PARENTH_POSN            0x08    /* enclose negative amount in () */
+#define        SUPRESS_CURR_SYMBOL     0x10    /* supress the currency from output */
+#define        LEFT_JUSTIFY            0x20    /* left justify */
+#define        USE_INTL_CURRENCY       0x40    /* use international currency symbol */
+#define IS_NEGATIVE            0x80    /* is argument value negative ? */
+
+/* internal macros */
+#define PRINT(CH) do {                                         \
+       if (dst >= s + maxsize)                                 \
+               goto e2big_error;                               \
+       *dst++ = CH;                                            \
+} while (/* CONSTCOND */ 0)
+
+#define PRINTS(STR) do {                                       \
+       const char *tmps = STR;                                 \
+       while (*tmps != '\0')                                   \
+               PRINT(*tmps++);                                 \
+} while (/* CONSTCOND */ 0)
+
+#define GET_NUMBER(VAR)        do {                                    \
+       VAR = 0;                                                \
+       while (isdigit((unsigned char)*fmt)) {                  \
+               VAR *= 10;                                      \
+               VAR += *fmt - '0';                              \
+               if (VAR > 0x00ffffff)                           \
+                       goto e2big_error;                       \
+               fmt++;                                          \
+       }                                                       \
+} while (/* CONSTCOND */ 0)
+
+#define GRPCPY(howmany) do {                                   \
+       int i = howmany;                                        \
+       while (i-- > 0) {                                       \
+               avalue_size--;                                  \
+               *--bufend = *(avalue+avalue_size+padded);       \
+       }                                                       \
+} while (/* CONSTCOND */ 0)
+
+#define GRPSEP do {                                            \
+       *--bufend = thousands_sep;                              \
+       groups++;                                               \
+} while (/* CONSTCOND */ 0)
+
+static void __setup_vars(int, char *, char *, char *, const char **);
+static int __calc_left_pad(int, char *);
+static char *__format_grouped_double(double, int *, int, int, int);
+
+ssize_t
+strfmon(char * __restrict s, size_t maxsize, const char * __restrict format,
+    ...)
+{
+       va_list         ap;
+       char            *dst;           /* output destination pointer */
+       const char      *fmt;           /* current format poistion pointer */
+       struct lconv    *lc;            /* pointer to lconv structure */
+       char            *asciivalue;    /* formatted double pointer */
+
+       int             flags;          /* formatting options */
+       int             pad_char;       /* padding character */
+       int             pad_size;       /* pad size */
+       int             width;          /* field width */
+       int             left_prec;      /* left precision */
+       int             right_prec;     /* right precision */
+       double          value;          /* just value */
+       char            space_char = ' '; /* space after currency */
+
+       char            cs_precedes,    /* values gathered from struct lconv */
+                       sep_by_space,
+                       sign_posn,
+                       *currency_symbol;
+       const char      *signstr;
+
+       char            *tmpptr;        /* temporary vars */
+       int             sverrno;
+
+        va_start(ap, format);
+
+       lc = localeconv();
+       dst = s;
+       fmt = format;
+       asciivalue = NULL;
+       currency_symbol = NULL;
+       pad_size = 0;
+
+       while (*fmt) {
+               /* pass nonformating characters AS IS */
+               if (*fmt != '%')
+                       goto literal;
+
+               /* '%' found ! */
+
+               /* "%%" mean just '%' */
+               if (*(fmt+1) == '%') {
+                       fmt++;
+       literal:
+                       PRINT(*fmt++);
+                       continue;
+               }
+
+               /* set up initial values */
+               flags = (NEED_GROUPING|LOCALE_POSN);
+               pad_char = ' ';         /* padding character is "space" */
+               left_prec = -1;         /* no left precision specified */
+               right_prec = -1;        /* no right precision specified */
+               width = -1;             /* no width specified */
+               value = 0;              /* we have no value to print now */
+
+               /* Flags */
+               while (/* CONSTCOND */ 1) {
+                       switch (*++fmt) {
+                               case '=':       /* fill character */
+                                       pad_char = *++fmt;
+                                       if (pad_char == '\0')
+                                               goto format_error;
+                                       continue;
+                               case '^':       /* not group currency  */
+                                       flags &= ~(NEED_GROUPING);
+                                       continue;
+                               case '+':       /* use locale defined signs */
+                                       if (flags & SIGN_POSN_USED)
+                                               goto format_error;
+                                       flags |= (SIGN_POSN_USED|LOCALE_POSN);
+                                       continue;
+                               case '(':       /* enclose negatives with () */
+                                       if (flags & SIGN_POSN_USED)
+                                               goto format_error;
+                                       flags |= (SIGN_POSN_USED|PARENTH_POSN);
+                                       continue;
+                               case '!':       /* suppress currency symbol */
+                                       flags |= SUPRESS_CURR_SYMBOL;
+                                       continue;
+                               case '-':       /* alignment (left)  */
+                                       flags |= LEFT_JUSTIFY;
+                                       continue;
+                               default:
+                                       break;
+                       }
+                       break;
+               }
+
+               /* field Width */
+               if (isdigit((unsigned char)*fmt)) {
+                       ptrdiff_t d = dst - s;
+                       GET_NUMBER(width);
+                       /* Do we have enough space to put number with
+                        * required width ?
+                        */
+
+                       if ((size_t)(d + width) >= maxsize)
+                               goto e2big_error;
+               }
+
+               /* Left precision */
+               if (*fmt == '#') {
+                       if (!isdigit((unsigned char)*++fmt))
+                               goto format_error;
+                       GET_NUMBER(left_prec);
+               }
+
+               /* Right precision */
+               if (*fmt == '.') {
+                       if (!isdigit((unsigned char)*++fmt))
+                               goto format_error;
+                       GET_NUMBER(right_prec);
+               }
+
+               /* Conversion Characters */
+               switch (*fmt++) {
+                       case 'i':       /* use internaltion currency format */
+                               flags |= USE_INTL_CURRENCY;
+                               break;
+                       case 'n':       /* use national currency format */
+                               flags &= ~(USE_INTL_CURRENCY);
+                               break;
+                       default:        /* required character is missing or
+                                          premature EOS */
+                               goto format_error;
+               }
+
+               if (currency_symbol)
+                       free(currency_symbol);
+               if (flags & USE_INTL_CURRENCY) {
+                       currency_symbol = strdup(lc->int_curr_symbol);
+                       if (currency_symbol != NULL)
+                               space_char = *(currency_symbol+3);
+               } else
+                       currency_symbol = strdup(lc->currency_symbol);
+
+               if (currency_symbol == NULL)
+                       goto end_error;                 /* ENOMEM. */
+
+               /* value itself */
+               value = va_arg(ap, double);
+
+               /* detect sign */
+               if (value < 0) {
+                       flags |= IS_NEGATIVE;
+                       value = -value;
+               }
+
+               /* fill left_prec with amount of padding chars */
+               if (left_prec >= 0) {
+                       pad_size = __calc_left_pad((flags ^ IS_NEGATIVE),
+                                                       currency_symbol) -
+                                  __calc_left_pad(flags, currency_symbol);
+                       if (pad_size < 0)
+                               pad_size = 0;
+               }
+
+               asciivalue = __format_grouped_double(value, &flags,
+                               left_prec, right_prec, pad_char);
+               if (asciivalue == NULL)
+                       goto end_error;         /* errno already set     */
+                                               /* to ENOMEM by malloc() */
+
+               /* set some variables for later use */
+               __setup_vars(flags, &cs_precedes, &sep_by_space,
+                               &sign_posn, &signstr);
+
+               /*
+                * Description of some LC_MONETARY's values:
+                *
+                * p_cs_precedes & n_cs_precedes
+                *
+                * = 1 - $currency_symbol precedes the value
+                *       for a monetary quantity with a non-negative value
+                * = 0 - symbol succeeds the value
+                *
+                * p_sep_by_space & n_sep_by_space
+                 *
+                * = 0 - no space separates $currency_symbol
+                *       from the value for a monetary quantity with a
+                *       non-negative value
+                * = 1 - space separates the symbol from the value
+                * = 2 - space separates the symbol and the sign string,
+                *       if adjacent.
+                 *
+                * p_sign_posn & n_sign_posn
+                 *
+                * = 0 - parentheses enclose the quantity and the
+                *       $currency_symbol
+                * = 1 - the sign string precedes the quantity and the 
+                *       $currency_symbol
+                * = 2 - the sign string succeeds the quantity and the 
+                *       $currency_symbol
+                * = 3 - the sign string precedes the $currency_symbol
+                * = 4 - the sign string succeeds the $currency_symbol
+                 *
+                */
+
+               tmpptr = dst;
+
+               while (pad_size-- > 0)
+                       PRINT(' ');
+
+               if (sign_posn == 0 && (flags & IS_NEGATIVE))
+                       PRINT('(');
+
+               if (cs_precedes == 1) {
+                       if (sign_posn == 1 || sign_posn == 3) {
+                               PRINTS(signstr);
+                               if (sep_by_space == 2)          /* XXX: ? */
+                                       PRINT(' ');
+                       }
+
+                       if (!(flags & SUPRESS_CURR_SYMBOL)) {
+                               PRINTS(currency_symbol);
+
+                               if (sign_posn == 4) {
+                                       if (sep_by_space == 2)
+                                               PRINT(space_char);
+                                       PRINTS(signstr);
+                                       if (sep_by_space == 1)
+                                               PRINT(' ');
+                               } else if (sep_by_space == 1)
+                                       PRINT(space_char);
+                       }
+               } else if (sign_posn == 1)
+                       PRINTS(signstr);
+
+               PRINTS(asciivalue);
+
+               if (cs_precedes == 0) {
+                       if (sign_posn == 3) {
+                               if (sep_by_space == 1)
+                                       PRINT(' ');
+                               PRINTS(signstr);
+                       }
+
+                       if (!(flags & SUPRESS_CURR_SYMBOL)) {
+                               if ((sign_posn == 3 && sep_by_space == 2)
+                                   || (sep_by_space == 1
+                                   && (sign_posn == 0
+                                   || sign_posn == 1
+                                   || sign_posn == 2
+                                   || sign_posn == 4)))
+                                       PRINT(space_char);
+                               PRINTS(currency_symbol); /* XXX: len */
+                               if (sign_posn == 4) {
+                                       if (sep_by_space == 2)
+                                               PRINT(' ');
+                                       PRINTS(signstr);
+                               }
+                       }
+               }
+
+               if (sign_posn == 2) {
+                       if (sep_by_space == 2)
+                               PRINT(' ');
+                       PRINTS(signstr);
+               }
+
+               if (sign_posn == 0 && (flags & IS_NEGATIVE))
+                       PRINT(')');
+
+               if (dst - tmpptr < width) {
+                       if (flags & LEFT_JUSTIFY) {
+                               while (dst - tmpptr < width)
+                                       PRINT(' ');
+                       } else {
+                               pad_size = dst-tmpptr;
+                               memmove(tmpptr + width-pad_size, tmpptr,
+                                   (size_t) pad_size);
+                               memset(tmpptr, ' ', (size_t) width-pad_size);
+                               dst += width-pad_size;
+                       }
+               }
+       }
+
+       PRINT('\0');
+       va_end(ap);
+       free(asciivalue);
+       free(currency_symbol);
+       return (dst - s - 1);   /* return size of put data except trailing '\0' */
+
+e2big_error:
+       errno = E2BIG;
+       goto end_error;
+
+format_error:
+       errno = EINVAL;
+
+end_error:
+       sverrno = errno;
+       if (asciivalue != NULL)
+               free(asciivalue);
+       if (currency_symbol != NULL)
+               free(currency_symbol);
+       errno = sverrno;
+       va_end(ap);
+       return (-1);
+}
+
+static void
+__setup_vars(int flags, char *cs_precedes, char *sep_by_space,
+               char *sign_posn, const char **signstr) {
+       struct lconv *lc = localeconv();
+
+       if ((flags & IS_NEGATIVE) && (flags & USE_INTL_CURRENCY)) {
+               *cs_precedes = lc->int_n_cs_precedes;
+               *sep_by_space = lc->int_n_sep_by_space;
+               *sign_posn = (flags & PARENTH_POSN) ? 0 : lc->int_n_sign_posn;
+               *signstr = (lc->negative_sign == '\0') ? "-"
+                   : lc->negative_sign;
+       } else if (flags & USE_INTL_CURRENCY) {
+               *cs_precedes = lc->int_p_cs_precedes;
+               *sep_by_space = lc->int_p_sep_by_space;
+               *sign_posn = (flags & PARENTH_POSN) ? 0 : lc->int_p_sign_posn;
+               *signstr = lc->positive_sign;
+       } else if (flags & IS_NEGATIVE) {
+               *cs_precedes = lc->n_cs_precedes;
+               *sep_by_space = lc->n_sep_by_space;
+               *sign_posn = (flags & PARENTH_POSN) ? 0 : lc->n_sign_posn;
+               *signstr = (lc->negative_sign == '\0') ? "-"
+                   : lc->negative_sign;
+       } else {
+               *cs_precedes = lc->p_cs_precedes;
+               *sep_by_space = lc->p_sep_by_space;
+               *sign_posn = (flags & PARENTH_POSN) ? 0 : lc->p_sign_posn;
+               *signstr = lc->positive_sign;
+       }
+
+       /* Set defult values for unspecified information. */
+       if (*cs_precedes != 0)
+               *cs_precedes = 1;
+       if (*sep_by_space == CHAR_MAX)
+               *sep_by_space = 0;
+       if (*sign_posn == CHAR_MAX)
+               *sign_posn = 0;
+}
+
+static int
+__calc_left_pad(int flags, char *cur_symb) {
+
+       char cs_precedes, sep_by_space, sign_posn;
+       const char *signstr;
+       int left_chars = 0;
+
+       __setup_vars(flags, &cs_precedes, &sep_by_space, &sign_posn, &signstr);
+
+       if (cs_precedes != 0) {
+               left_chars += strlen(cur_symb);
+               if (sep_by_space != 0)
+                       left_chars++;
+       }
+
+       switch (sign_posn) {
+               case 1:
+                       left_chars += strlen(signstr);
+                       break;
+               case 3:
+               case 4:
+                       if (cs_precedes != 0)
+                               left_chars += strlen(signstr);
+       }
+       return (left_chars);
+}
+
+static int
+get_groups(int size, char *grouping) {
+
+       int     chars = 0;
+
+       if (*grouping == CHAR_MAX || *grouping <= 0)    /* no grouping ? */
+               return (0);
+
+       while (size > (int)*grouping) {
+               chars++;
+               size -= (int)*grouping++;
+               /* no more grouping ? */
+               if (*grouping == CHAR_MAX)
+                       break;
+               /* rest grouping with same value ? */
+               if (*grouping == 0) {
+                       chars += (size - 1) / *(grouping - 1);
+                       break;
+               }
+       }
+       return (chars);
+}
+
+/* convert double to ASCII */
+static char *
+__format_grouped_double(double value, int *flags,
+                       int left_prec, int right_prec, int pad_char) {
+
+       char            *rslt;
+       char            *avalue;
+       int             avalue_size;
+       char            fmt[32];
+
+       size_t          bufsize;
+       char            *bufend;
+
+       int             padded;
+
+       struct lconv    *lc = localeconv();
+       char            *grouping;
+       char            decimal_point;
+       char            thousands_sep;
+
+       int groups = 0;
+
+       grouping = lc->mon_grouping;
+       decimal_point = *lc->mon_decimal_point;
+       if (decimal_point == '\0')
+               decimal_point = *lc->decimal_point;
+       thousands_sep = *lc->mon_thousands_sep;
+       if (thousands_sep == '\0')
+               thousands_sep = *lc->thousands_sep;
+
+       /* fill left_prec with default value */
+       if (left_prec == -1)
+               left_prec = 0;
+
+       /* fill right_prec with default value */
+       if (right_prec == -1) {
+                if (*flags & USE_INTL_CURRENCY)
+                        right_prec = lc->int_frac_digits;
+                else
+                        right_prec = lc->frac_digits;
+
+               if (right_prec == CHAR_MAX)     /* POSIX locale ? */
+                       right_prec = 2;
+       }
+
+       if (*flags & NEED_GROUPING)
+               left_prec += get_groups(left_prec, grouping);
+
+       /* convert to string */
+       snprintf(fmt, sizeof(fmt), "%%%d.%df", left_prec + right_prec + 1,
+           right_prec);
+       avalue_size = asprintf(&avalue, fmt, value);
+       if (avalue_size < 0)
+               return (NULL);
+
+       /* make sure that we've enough space for result string */
+       bufsize = strlen(avalue)*2+1;
+       rslt = malloc(bufsize);
+       if (rslt == NULL) {
+               free(avalue);
+               return (NULL);
+       }
+       memset(rslt, 0, bufsize);
+       bufend = rslt + bufsize - 1;    /* reserve space for trailing '\0' */
+
+       /* skip spaces at beggining */
+       padded = 0;
+       while (avalue[padded] == ' ') {
+               padded++;
+               avalue_size--;
+       }
+
+       if (right_prec > 0) {
+               bufend -= right_prec;
+               memcpy(bufend, avalue + avalue_size+padded-right_prec,
+                   (size_t) right_prec);
+               *--bufend = decimal_point;
+               avalue_size -= (right_prec + 1);
+       }
+
+       if ((*flags & NEED_GROUPING) &&
+           thousands_sep != '\0' &&    /* XXX: need investigation */
+           *grouping != CHAR_MAX &&
+           *grouping > 0) {
+               while (avalue_size > (int)*grouping) {
+                       GRPCPY(*grouping);
+                       GRPSEP;
+                       grouping++;
+
+                       /* no more grouping ? */
+                       if (*grouping == CHAR_MAX)
+                               break;
+
+                       /* rest grouping with same value ? */
+                       if (*grouping == 0) {
+                               grouping--;
+                               while (avalue_size > *grouping) {
+                                       GRPCPY(*grouping);
+                                       GRPSEP;
+                               }
+                       }
+               }
+               if (avalue_size != 0)
+                       GRPCPY(avalue_size);
+               padded -= groups;
+
+       } else {
+               bufend -= avalue_size;
+               memcpy(bufend, avalue+padded, (size_t) avalue_size);
+               if (right_prec == 0)
+                       padded--;       /* decrease assumed $decimal_point */
+       }
+
+       /* do padding with pad_char */
+       if (padded > 0) {
+               bufend -= padded;
+               memset(bufend, pad_char, (size_t) padded);
+       }
+
+       bufsize = bufsize - (bufend - rslt) + 1;
+       memmove(rslt, bufend, bufsize);
+       free(avalue);
+       return (rslt);
+}
diff --git a/lib/nbsd_libc/stdlib/strsuftoll.3 b/lib/nbsd_libc/stdlib/strsuftoll.3
new file mode 100644 (file)
index 0000000..ffaca3e
--- /dev/null
@@ -0,0 +1,150 @@
+.\"    $NetBSD: strsuftoll.3,v 1.11 2010/12/14 13:00:34 jruoho Exp $
+.\"
+.\" Copyright (c) 2002,2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Luke Mewburn.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd December 14, 2010
+.Dt STRSUFTOLL 3
+.Os
+.Sh NAME
+.Nm strsuftoll ,
+.Nm strsuftollx
+.Nd "convert a string to a long long, with suffix parsing"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft long long
+.Fn strsuftoll "const char *desc" "const char *val" "long long min" "long long max"
+.Ft long long
+.Fn strsuftollx "const char *desc" "const char *val" "long long min" "long long max" "char *errbuf" "size_t errbuflen"
+.Sh DESCRIPTION
+The functions
+.Fn strsuftoll
+and
+.Fn strsuftollx
+convert
+.Fa val
+into a number of type
+.Vt long long ,
+checking that the result is not smaller than
+.Fa min
+or larger than
+.Fa max .
+Two or more decimal numbers may be separated by an
+.Dq x
+to indicate a product.
+.Pp
+Each decimal number may have one of the following optional suffixes:
+.Pp
+.Bl -tag -width 3n -offset indent -compact
+.It Em b
+Block; multiply by 512
+.It Em k
+Kibi; multiply by 1024 (1 KiB)
+.It Em m
+Mebi; multiply by 1048576 (1 MiB)
+.It Em g
+Gibi; multiply by 1073741824 (1 GiB)
+.It Em t
+Tebi; multiply by 1099511627776 (1 TiB)
+.It Em w
+Word; multiply by the number of bytes in an integer
+.El
+.Pp
+In the case of an error (range overflow or an invalid number),
+.Fn strsuftollx
+places an error message into
+.Fa errbuf
+(which is
+.Fa errbuflen
+bytes long) and returns 0,
+and
+.Fn strsuftoll
+displays that error and terminates the process.
+The parameter
+.Fa desc
+is used to construct
+.Fa errbuf .
+.Pp
+Neither
+.Fa desc
+nor
+.Fa val
+may be
+.Dv NULL .
+.Sh RETURN VALUES
+The functions
+.Fn strsuftoll
+and
+.Fn strsuftollx
+return either the result of the conversion,
+unless the value overflows or is not a number;
+in the latter case,
+.Fn strsuftoll
+displays an error message and terminates the process with exit code
+.Dv EXIT_FAILURE ,
+and
+.Fn strsuftollx
+returns with 0 and
+.Fa errbuf
+contains a non-empty error message.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er ERANGE
+The given string was out of range; the value converted has been clamped.
+.El
+.Sh SEE ALSO
+.Xr errx 3 ,
+.Xr strtoll 3 ,
+.Xr orders 7
+.Sh BUGS
+At least few limitations should be mentioned:
+.Bl -bullet
+.It
+Both functions ignore the current locale.
+.It
+Neither
+.Fn strsuftoll
+nor
+.Fn strsuftollx
+fail gracefully in case of invalid,
+.Dv NULL ,
+pointers.
+.It
+Arguably the return type should be
+.Vt intmax_t
+instead of
+.Vt long long .
+.It
+The
+.Fn strsuftollx
+function is prone to buffer overflows if used incorrectly.
+Arguably only
+.Fn strsuftoll
+should be exposed to a caller.
+.El
diff --git a/lib/nbsd_libc/stdlib/strsuftoll.c b/lib/nbsd_libc/stdlib/strsuftoll.c
new file mode 100644 (file)
index 0000000..0e29a6d
--- /dev/null
@@ -0,0 +1,240 @@
+/*     $NetBSD: strsuftoll.c,v 1.8 2008/04/28 20:23:00 martin Exp $    */
+/*-
+ * Copyright (c) 2001-2002,2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Luke Mewburn.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+/*-
+ * Copyright (c) 1991, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Keith Muller of the University of California, San Diego and Lance
+ * Visser of Convex Computer Corporation.
+ *
+ * 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. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: strsuftoll.c,v 1.8 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef _LIBC
+#include "namespace.h"
+#endif
+
+#if !HAVE_STRSUFTOLL
+
+#include <sys/types.h>
+#include <sys/time.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <err.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef _LIBC
+# ifdef __weak_alias
+__weak_alias(strsuftoll, _strsuftoll)
+__weak_alias(strsuftollx, _strsuftollx)
+# endif
+#endif /* LIBC */
+
+/*
+ * Convert an expression of the following forms to a (u)int64_t.
+ *     1) A positive decimal number.
+ *     2) A positive decimal number followed by a b (mult by 512).
+ *     3) A positive decimal number followed by a k (mult by 1024).
+ *     4) A positive decimal number followed by a m (mult by 1048576).
+ *     5) A positive decimal number followed by a g (mult by 1073741824).
+ *     6) A positive decimal number followed by a t (mult by 1099511627776).
+ *     7) A positive decimal number followed by a w (mult by sizeof int)
+ *     8) Two or more positive decimal numbers (with/without k,b or w).
+ *        separated by x (also * for backwards compatibility), specifying
+ *        the product of the indicated values.
+ * Returns the result upon successful conversion, or exits with an
+ * appropriate error.
+ * 
+ */
+/* LONGLONG */
+long long
+strsuftoll(const char *desc, const char *val,
+    long long min, long long max)
+{
+       long long result;
+       char    errbuf[100];
+
+       result = strsuftollx(desc, val, min, max, errbuf, sizeof(errbuf));
+       if (*errbuf != '\0')
+               errx(1, "%s", errbuf);
+       return (result);
+}
+
+/*
+ * As strsuftoll(), but returns the error message into the provided buffer
+ * rather than exiting with it.
+ */
+/* LONGLONG */
+long long
+strsuftollx(const char *desc, const char *val,
+    long long min, long long max, char *ebuf, size_t ebuflen)
+{
+       long long num, t;
+       char    *expr;
+
+       _DIAGASSERT(desc != NULL);
+       _DIAGASSERT(val != NULL);
+       _DIAGASSERT(ebuf != NULL);
+
+       errno = 0;
+       ebuf[0] = '\0';
+
+       while (isspace((unsigned char)*val))    /* Skip leading space */
+               val++;
+
+       num = strtoll(val, &expr, 10);
+       if (errno == ERANGE)
+               goto erange;                    /* Overflow */
+
+       if (expr == val)                        /* No digits */
+               goto badnum;
+
+       switch (*expr) {
+       case 'b':
+               t = num;
+               num *= 512;                     /* 1 block */
+               if (t > num)
+                       goto erange;
+               ++expr;
+               break;
+       case 'k':
+               t = num;
+               num *= 1024;                    /* 1 kibibyte */
+               if (t > num)
+                       goto erange;
+               ++expr;
+               break;
+       case 'm':
+               t = num;
+               num *= 1048576;                 /* 1 mebibyte */
+               if (t > num)
+                       goto erange;
+               ++expr;
+               break;
+       case 'g':
+               t = num;
+               num *= 1073741824;              /* 1 gibibyte */
+               if (t > num)
+                       goto erange;
+               ++expr;
+               break;
+       case 't':
+               t = num;
+               num *= 1099511627776LL;         /* 1 tebibyte */
+               if (t > num)
+                       goto erange;
+               ++expr;
+               break;
+       case 'w':
+               t = num;
+               num *= sizeof(int);             /* 1 word */
+               if (t > num)
+                       goto erange;
+               ++expr;
+               break;
+       }
+
+       switch (*expr) {
+       case '\0':
+               break;
+       case '*':                               /* Backward compatible */
+       case 'x':
+               t = num;
+               num *= strsuftollx(desc, expr + 1, min, max, ebuf, ebuflen);
+               if (*ebuf != '\0')
+                       return (0);
+               if (t > num) {
+ erange:               
+                       snprintf(ebuf, ebuflen,
+                           "%s: %s", desc, strerror(ERANGE));
+                       return (0);
+               }
+               break;
+       default:
+ badnum:       snprintf(ebuf, ebuflen,
+                   "%s `%s': illegal number", desc, val);
+               return (0);
+       }
+       if (num < min) {
+                       /* LONGLONG */
+               snprintf(ebuf, ebuflen, "%s %lld is less than %lld.",
+                   desc, (long long)num, (long long)min);
+               return (0);
+       }
+       if (num > max) {
+                       /* LONGLONG */
+               snprintf(ebuf, ebuflen,
+                   "%s %lld is greater than %lld.",
+                   desc, (long long)num, (long long)max);
+               return (0);
+       }
+       *ebuf = '\0';
+       return (num);
+}
+
+#endif /* !HAVE_STRSUFTOLL */
diff --git a/lib/nbsd_libc/stdlib/strtod.3 b/lib/nbsd_libc/stdlib/strtod.3
new file mode 100644 (file)
index 0000000..c20bb4f
--- /dev/null
@@ -0,0 +1,198 @@
+.\"    $NetBSD: strtod.3,v 1.20 2007/10/24 13:42:10 reed Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strtod.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd March 12, 2006
+.Dt STRTOD 3
+.Os
+.Sh NAME
+.Nm strtod ,
+.Nm strtof ,
+.Nm strtold
+.Nd convert
+.Tn ASCII
+string to double, float, or long double
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft double
+.Fn strtod "const char * restrict nptr" "char ** restrict endptr"
+.Ft float
+.Fn strtof "const char * restrict nptr" "char ** restrict endptr"
+.Ft long double
+.Fn strtold "const char * restrict nptr" "char ** restrict endptr"
+.Sh DESCRIPTION
+The
+.Fn strtod
+function converts the initial portion of the string
+pointed to by
+.Fa nptr
+to
+.Em double
+representation.
+.Pp
+The
+.Fn strtof
+function converts the initial portion of the string
+pointed to by
+.Fa nptr
+to
+.Em float
+representation.
+.Pp
+The
+.Fn strtold
+function converts the initial portion of the string
+pointed to by
+.Fa nptr
+to
+.Em long double
+representation.
+.Pp
+The expected form of the string is an optional plus
+.Pq Sq +
+or minus sign
+.Pq Sq \-
+followed by one of the following:
+.Bl -dash
+.It
+a sequence of digits optionally containing
+a decimal-point character, optionally followed by an exponent.
+An exponent consists of an
+.Sq E
+or
+.Sq e ,
+followed by an optional plus
+or minus sign, followed by a sequence of digits.
+.It
+one of
+.Li INF
+or
+.Li INFINITY ,
+ignoring case.
+.It
+one of
+.Li NAN
+or
+.Li NAN(n-char-sequence-opt) ,
+ignoring case.
+This implementation currently does not interpret such a sequence.
+.El
+.Pp
+Leading white-space characters in the string (as defined by the
+.Xr isspace 3
+function) are skipped.
+.Sh RETURN VALUES
+The
+.Fn strtod ,
+.Fn strtof ,
+and
+.Fn strtold
+functions return the converted value, if any.
+.Pp
+A character sequence
+.Li INF
+or
+.Li INFINITY
+is converted to \*(If,
+if supported, else to the largest finite floating-point number representable
+on the machine (i.e.,
+.Tn VAX ) .
+.Pp
+A character sequence
+.Li NAN
+or
+.Li NAN(n-char-sequence-opt)
+is converted to a quiet \*(Na, if supported, else remains unrecognized (i.e.,
+.Tn VAX ) .
+.Pp
+If
+.Fa endptr
+is not
+.Dv NULL ,
+a pointer to the character after the last character used
+in the conversion is stored in the location referenced by
+.Fa endptr .
+.Pp
+If no conversion is performed, zero is returned and the value of
+.Fa nptr
+is stored in the location referenced by
+.Fa endptr .
+.Pp
+If the correct value would cause overflow, plus or minus
+.Dv HUGE_VAL ,
+.Dv HUGE_VALF ,
+or
+.Dv HUGE_VALL
+is returned (according to the return type and sign of the value), and
+.Dv ERANGE
+is stored in
+.Va errno .
+If the correct value would cause underflow, zero is
+returned and
+.Dv ERANGE
+is stored in
+.Va errno .
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er ERANGE
+Overflow or underflow occurred.
+.El
+.Sh SEE ALSO
+.Xr atof 3 ,
+.Xr atoi 3 ,
+.Xr atol 3 ,
+.Xr math 3 ,
+.Xr strtol 3 ,
+.Xr strtoul 3
+.Sh STANDARDS
+The
+.Fn strtod
+function
+conforms to
+.St -ansiC .
+The
+.Fn strtof
+and
+.Fn strtold
+functions conform to
+.St -isoC-99 .
+.Sh HISTORY
+The
+.Fn strtof
+and
+.Fn strtold
+functions appeared in
+.Nx 4.0 .
diff --git a/lib/nbsd_libc/stdlib/strtoimax.c b/lib/nbsd_libc/stdlib/strtoimax.c
new file mode 100644 (file)
index 0000000..be7c36f
--- /dev/null
@@ -0,0 +1,52 @@
+/* $DragonFly: src/lib/libc/stdlib/strtoimax.c,v 1.2 2008/08/19 15:50:24 joerg Exp $ */
+
+/*-
+ * Copyright (c) 2005 The DragonFly Project.  All rights reserved.
+ * Copyright (c) 2003 Citrus Project,
+ * 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.
+ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: strtoimax.c,v 1.7 2008/09/10 18:08:58 joerg Exp $");
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <inttypes.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#define        _FUNCNAME       strtoimax
+#define        __INT           intmax_t
+#define        __INT_MIN       INTMAX_MIN
+#define        __INT_MAX       INTMAX_MAX
+
+#include "_strtol.h"
+
+__strong_alias(_strtoimax, strtoimax)
diff --git a/lib/nbsd_libc/stdlib/strtol.3 b/lib/nbsd_libc/stdlib/strtol.3
new file mode 100644 (file)
index 0000000..512ae43
--- /dev/null
@@ -0,0 +1,294 @@
+.\"    $NetBSD: strtol.3,v 1.26 2009/07/23 13:38:57 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strtol.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd July 23, 2009
+.Dt STRTOL 3
+.Os
+.Sh NAME
+.Nm strtol ,
+.Nm strtoll ,
+.Nm strtoimax ,
+.Nm strtoq
+.Nd convert string value to a long, long long, intmax_t or quad_t integer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.In limits.h
+.Ft long int
+.Fn strtol "const char * restrict nptr" "char ** restrict endptr" "int base"
+.Ft long long int
+.Fn strtoll "const char * restrict nptr" "char ** restrict endptr" "int base"
+.Pp
+.In inttypes.h
+.Ft intmax_t
+.Fn strtoimax "const char * restrict nptr" "char ** restrict endptr" "int base"
+.Pp
+.In sys/types.h
+.In stdlib.h
+.In limits.h
+.Ft quad_t
+.Fn strtoq "const char * restrict nptr" "char ** restrict endptr" "int base"
+.Sh DESCRIPTION
+The
+.Fn strtol
+function
+converts the string in
+.Fa nptr
+to a
+.Ft long int
+value.
+The
+.Fn strtoll
+function
+converts the string in
+.Fa nptr
+to a
+.Ft long long int
+value.
+The
+.Fn strtoimax
+function
+converts the string in
+.Fa nptr
+to an
+.Ft intmax_t
+value.
+The
+.Fn strtoq
+function
+converts the string in
+.Fa nptr
+to a
+.Ft quad_t
+value.
+The conversion is done according to the given
+.Fa base ,
+which must be between 2 and 36 inclusive,
+or be the special value 0.
+.Pp
+The string may begin with an arbitrary amount of white space
+(as determined by
+.Xr isspace 3 )
+followed by a single optional
+.Ql +
+or
+.Ql -
+sign.
+If
+.Fa base
+is zero or 16,
+the string may then include a
+.Ql 0x
+prefix,
+and the number will be read in base 16; otherwise, a zero
+.Fa base
+is taken as 10 (decimal) unless the next character is
+.Ql 0 ,
+in which case it is taken as 8 (octal).
+.Pp
+The remainder of the string is converted to a
+.Em long
+value in the obvious manner,
+stopping at the first character which is not a valid digit
+in the given base.
+(In bases above 10, the letter
+.Ql A
+in either upper or lower case
+represents 10,
+.Ql B
+represents 11, and so forth, with
+.Ql Z
+representing 35.)
+.Pp
+If
+.Fa endptr
+is non-nil,
+.Fn strtol
+stores the address of the first invalid character in
+.Fa *endptr .
+If there were no digits at all, however,
+.Fn strtol
+stores the original value of
+.Fa nptr
+in
+.Fa *endptr .
+(Thus, if
+.Fa *nptr
+is not
+.Ql \e0
+but
+.Fa **endptr
+is
+.Ql \e0
+on return, the entire string was valid.)
+.Sh RETURN VALUES
+The
+.Fn strtol
+function
+returns the result of the conversion,
+unless the value would underflow or overflow.
+If an underflow occurs,
+.Fn strtol
+returns
+.Dv LONG_MIN ,
+.Fn strtoll
+returns
+.Dv LLONG_MIN ,
+and
+.Fn strtoimax
+returns
+.Dv INTMAX_MIN .
+If an overflow occurs,
+.Fn strtol
+returns
+.Dv LONG_MAX ,
+.Fn strtoll
+returns
+.Dv LLONG_MAX ,
+and
+.Fn strtoimax
+returns
+.Dv INTMAX_MAX .
+In these cases,
+.Va errno
+is set to
+.Er ERANGE .
+If the
+.Fa base
+argument is not supported then
+.Va errno
+is set to
+.Er EINVAL
+and the functions return 0.
+.Pp
+If no error occurs,
+.Va errno
+is left unchanged.
+This behavior (which is unlike most library functions) is guaranteed
+by the pertinent standards.
+.Sh EXAMPLES
+Because the return value of
+.Fn strtol
+cannot be used unambiguously to detect an error,
+.Va errno
+is left unchanged after a successful call.
+To ensure that a string is a valid number (i.e., in range and containing no
+trailing characters), clear
+.Va errno
+beforehand explicitly, then check it afterwards:
+.Bd -literal -offset indent
+char *ep;
+long lval;
+
+\&...
+
+errno = 0;
+lval = strtol(buf, \*[Am]ep, 10);
+if (buf[0] == '\e0' || *ep != '\e0')
+       goto not_a_number;
+if (errno == ERANGE \*[Am]\*[Am] (lval == LONG_MAX || lval == LONG_MIN))
+       goto out_of_range;
+.Ed
+.Pp
+This example will accept
+.Dq 12
+but not
+.Dq 12foo
+or
+.Dq 12\en .
+If trailing whitespace is acceptable, further checks must be done on
+.Va *ep ;
+alternately, use
+.Xr sscanf 3 .
+.Pp
+If
+.Fn strtol
+is being used instead of
+.Xr atoi 3 ,
+error checking is further complicated because the desired return value is an
+.Li int
+rather than a
+.Li long ;
+however, on some architectures integers and long integers are the same size.
+Thus the following is necessary:
+.Bd -literal -offset indent
+char *ep;
+int ival;
+long lval;
+
+\&...
+
+errno = 0;
+lval = strtol(buf, \*[Am]ep, 10);
+if (buf[0] == '\e0' || *ep != '\e0')
+       goto not_a_number;
+if ((errno == ERANGE \*[Am]\*[Am] (lval == LONG_MAX || lval == LONG_MIN)) ||
+    (lval \*[Gt] INT_MAX || lval \*[Lt] INT_MIN))
+       goto out_of_range;
+ival = lval;
+.Ed
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Ar base
+is not between 2 and 36 and does not contain the special value 0.
+.It Bq Er ERANGE
+The given string was out of range; the value converted has been clamped.
+.El
+.Sh SEE ALSO
+.Xr atof 3 ,
+.Xr atoi 3 ,
+.Xr atol 3 ,
+.Xr atoll 3 ,
+.Xr strtod 3 ,
+.Xr strtoul 3 ,
+.Xr strtoull 3 ,
+.Xr strtoumax 3
+.Sh STANDARDS
+The
+.Fn strtol
+function
+conforms to
+.St -ansiC .
+The
+.Fn strtoll
+and
+.Fn strtoimax
+functions conform to
+.St -isoC-99 .
+.Sh BUGS
+Ignores the current locale.
diff --git a/lib/nbsd_libc/stdlib/strtol.c b/lib/nbsd_libc/stdlib/strtol.c
new file mode 100644 (file)
index 0000000..9c68c4b
--- /dev/null
@@ -0,0 +1,45 @@
+/* $NetBSD: strtol.c,v 1.18 2008/08/20 12:42:26 joerg Exp $ */
+
+/*-
+ * Copyright (c) 2005 The DragonFly Project.  All rights reserved.
+ * Copyright (c) 2003 Citrus Project,
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: strtol.c,v 1.18 2008/08/20 12:42:26 joerg Exp $");
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#define        _FUNCNAME       strtol
+#define        __INT           long
+#define        __INT_MIN       LONG_MIN
+#define        __INT_MAX       LONG_MAX
+
+#include "_strtol.h"
diff --git a/lib/nbsd_libc/stdlib/strtoq.c b/lib/nbsd_libc/stdlib/strtoq.c
new file mode 100644 (file)
index 0000000..9121837
--- /dev/null
@@ -0,0 +1,44 @@
+/* $NetBSD: strtoq.c,v 1.19 2008/08/20 12:42:26 joerg Exp $ */
+
+/*-
+ * Copyright (c) 2008 Joerg Sonnenberger <joerg@NetBSD.org>
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: strtoq.c,v 1.19 2008/08/20 12:42:26 joerg Exp $");
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#define        _FUNCNAME       strtoq
+#define        __INT           quad_t
+#define        __INT_MIN       QUAD_MIN
+#define        __INT_MAX       QUAD_MAX
+
+#include "_strtol.h"
diff --git a/lib/nbsd_libc/stdlib/strtoul.3 b/lib/nbsd_libc/stdlib/strtoul.3
new file mode 100644 (file)
index 0000000..439ec89
--- /dev/null
@@ -0,0 +1,263 @@
+.\"    $NetBSD: strtoul.3,v 1.25 2009/12/02 12:50:27 pooka Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strtoul.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd December 2, 2009
+.Dt STRTOUL 3
+.Os
+.Sh NAME
+.Nm strtoul ,
+.Nm strtoull ,
+.Nm strtoumax ,
+.Nm strtouq
+.Nd convert a string to an unsigned long, unsigned long long, uintmax_t or uquad_t integer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.In limits.h
+.Ft unsigned long int
+.Fn strtoul "const char * restrict nptr" "char ** restrict endptr" "int base"
+.Ft unsigned long long int
+.Fn strtoull "const char * restrict nptr" "char ** restrict endptr" "int base"
+.Pp
+.In inttypes.h
+.Ft uintmax_t
+.Fn strtoumax "const char * restrict nptr" "char ** restrict endptr" "int base"
+.Pp
+.In sys/types.h
+.In stdlib.h
+.In limits.h
+.Ft u_quad_t
+.Fn strtouq "const char * restrict nptr" "char ** restrict endptr" "int base"
+.Sh DESCRIPTION
+The
+.Fn strtoul
+function
+converts the string in
+.Fa nptr
+to an
+.Ft unsigned long int
+value.
+The
+.Fn strtoull
+function
+converts the string in
+.Fa nptr
+to an
+.Ft unsigned long long int
+value.
+The
+.Fn strtoumax
+function
+converts the string in
+.Fa nptr
+to an
+.Ft uintmax_t
+value.
+The
+.Fn strtouq
+function
+converts the string in
+.Fa nptr
+to a
+.Ft u_quad_t
+value.
+The conversion is done according to the given
+.Fa base ,
+which must be between 2 and 36 inclusive,
+or be the special value 0.
+.Pp
+The string may begin with an arbitrary amount of white space
+(as determined by
+.Xr isspace 3 )
+followed by a single optional
+.Ql +
+or
+.Ql -
+sign.
+If
+.Fa base
+is zero or 16,
+the string may then include a
+.Ql 0x
+prefix,
+and the number will be read in base 16; otherwise, a zero
+.Fa base
+is taken as 10 (decimal) unless the next character is
+.Ql 0 ,
+in which case it is taken as 8 (octal).
+.Pp
+The remainder of the string is converted to an
+.Em unsigned long
+value in the obvious manner,
+stopping at the end of the string
+or at the first character that does not produce a valid digit
+in the given base.
+(In bases above 10, the letter
+.Ql A
+in either upper or lower case
+represents 10,
+.Ql B
+represents 11, and so forth, with
+.Ql Z
+representing 35.)
+.Pp
+If
+.Fa endptr
+is non-nil,
+.Fn strtoul
+stores the address of the first invalid character in
+.Fa *endptr .
+If there were no digits at all, however,
+.Fn strtoul
+stores the original value of
+.Fa nptr
+in
+.Fa *endptr .
+(Thus, if
+.Fa *nptr
+is not
+.Ql \e0
+but
+.Fa **endptr
+is
+.Ql \e0
+on return, the entire string was valid.)
+.Sh RETURN VALUES
+The
+.Fn strtoul
+function
+returns either the result of the conversion
+or, if there was a leading minus sign,
+the negation of the result of the conversion,
+unless the original (non-negated) value would overflow;
+in the latter case,
+.Fn strtoul
+returns
+.Dv ULONG_MAX ,
+.Fn strtoull
+returns
+.Dv ULLONG_MAX ,
+.Fn strtoumax
+returns
+.Dv UINTMAX_MAX ,
+.Fn strtouq
+returns
+.Dv UQUAD_MAX ,
+and the global variable
+.Va errno
+is set to
+.Er ERANGE .
+.Pp
+There is no way to determine if
+.Fn strtoul
+has processed a negative number (and returned an unsigned value) short of
+examining the string in
+.Fa nptr
+directly.
+If the
+.Fa base
+argument is not supported then
+.Va errno
+is set to
+.Er EINVAL
+and the functions return 0.
+.Pp
+If no error occurs,
+.Va errno
+is left unchanged.
+This behavior (which is unlike most library functions) is guaranteed
+by the pertinent standards.
+.Sh EXAMPLES
+Because the return value of
+.Fn strtoul
+cannot be used unambiguously to detect an error,
+.Va errno
+is left unchanged after a successful call.
+To ensure that a string is a valid number (i.e., in range and containing no
+trailing characters), clear
+.Va errno
+beforehand explicitly, then check it afterwards:
+.Bd -literal -offset indent
+char *ep;
+unsigned long ulval;
+
+\&...
+
+errno = 0;
+ulval = strtoul(buf, \*[Am]ep, 10);
+if (buf[0] == '\e0' || *ep != '\e0')
+       goto not_a_number;
+if (errno == ERANGE \*[Am]\*[Am] ulval == ULONG_MAX)
+       goto out_of_range;
+.Ed
+.Pp
+This example will accept
+.Dq 12
+but not
+.Dq 12foo
+or
+.Dq 12\en .
+If trailing whitespace is acceptable, further checks must be done on
+.Va *ep ;
+alternately, use
+.Xr sscanf 3 .
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Ar base
+is not between 2 and 36 and does not contain the special value 0.
+.It Bq Er ERANGE
+The given string was out of range; the value converted has been clamped.
+.El
+.Sh SEE ALSO
+.Xr strtoimax 3 ,
+.Xr strtol 3 ,
+.Xr strtoll 3
+.Sh STANDARDS
+The
+.Fn strtoul
+function
+conforms to
+.St -ansiC .
+The
+.Fn strtoull
+and
+.Fn strtoumax
+functions conform to
+.St -isoC-99 .
+.Sh BUGS
+Ignores the current locale.
diff --git a/lib/nbsd_libc/stdlib/strtouq.c b/lib/nbsd_libc/stdlib/strtouq.c
new file mode 100644 (file)
index 0000000..58894b5
--- /dev/null
@@ -0,0 +1,43 @@
+/* $NetBSD: strtouq.c,v 1.20 2008/08/26 12:21:24 drochner Exp $ */
+
+/*-
+ * Copyright (c) 2008 Joerg Sonnenberger <joerg@NetBSD.org>
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: strtouq.c,v 1.20 2008/08/26 12:21:24 drochner Exp $");
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#define        _FUNCNAME       strtouq
+#define        __UINT          u_quad_t
+#define        __UINT_MAX      UQUAD_MAX
+
+#include "_strtoul.h"
diff --git a/lib/nbsd_libc/stdlib/system.3 b/lib/nbsd_libc/stdlib/system.3
new file mode 100644 (file)
index 0000000..8721e08
--- /dev/null
@@ -0,0 +1,108 @@
+.\"    $NetBSD: system.3,v 1.17 2008/08/27 06:45:02 christos Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)system.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd August 2, 2007
+.Dt SYSTEM 3
+.Os
+.Sh NAME
+.Nm system
+.Nd pass a command to the shell
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn system "const char *string"
+.Sh DESCRIPTION
+The
+.Fn system
+function
+hands the argument
+.Fa string
+to the command interpreter
+.Xr sh 1 .
+The calling process waits for the shell to finish executing the command,
+ignoring
+.Dv SIGINT
+and
+.Dv SIGQUIT ,
+and blocking
+.Dv SIGCHLD .
+.Pp
+If
+.Fa string
+is a
+.Dv NULL
+pointer,
+.Fn system
+will return non-zero, if the command interpreter is available, or zero if none
+is available.
+Otherwise,
+.Fn system
+returns the termination status of the shell in the format specified by
+.Xr waitpid 2 .
+.Sh RETURN VALUES
+If a child process cannot be created, or the termination status of
+the shell cannot be obtained,
+.Fn system
+returns -1 and sets
+.Va errno
+to indicate the error.
+If execution of the shell fails,
+.Fn system
+returns the termination status for a program that terminates with a call of
+.Fn exit 127 .
+.Sh SEE ALSO
+.Xr sh 1 ,
+.Xr execve 2 ,
+.Xr waitpid 2 ,
+.Xr popen 3 ,
+.Xr shquote 3
+.Sh STANDARDS
+The
+.Fn system
+function
+conforms to
+.St -ansiC
+and
+.St -p1003.2-92 .
+.Sh CAVEATS
+Never supply the
+.Fn system
+function with a command containing any part of an unsanitized user-supplied
+string.
+Shell meta-characters present will be honored by the
+.Xr sh 1
+command interpreter.
diff --git a/lib/nbsd_libc/stdlib/system.c b/lib/nbsd_libc/stdlib/system.c
new file mode 100644 (file)
index 0000000..f0fc120
--- /dev/null
@@ -0,0 +1,122 @@
+/*     $NetBSD: system.c,v 1.23 2010/11/14 18:11:43 tron Exp $ */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)system.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: system.c,v 1.23 2010/11/14 18:11:43 tron Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <errno.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <paths.h>
+
+#include "env.h"
+#include "reentrant.h"
+
+int
+system(command)
+       const char *command;
+{
+       pid_t pid;
+       struct sigaction intsa, quitsa, sa;
+       sigset_t nmask, omask;
+       int pstat;
+       const char *argp[] = {"sh", "-c", NULL, NULL};
+       argp[2] = command;
+
+       /*
+        * ISO/IEC 9899:1999 in 7.20.4.6 describes this special case.
+        * We need to check availability of a command interpreter.
+        */
+       if (command == NULL) {
+               if (access(_PATH_BSHELL, X_OK) == 0)
+                       return 1;
+               return 0;
+       }
+
+       sa.sa_handler = SIG_IGN;
+       sigemptyset(&sa.sa_mask);
+       sa.sa_flags = 0;
+
+       if (sigaction(SIGINT, &sa, &intsa) == -1)
+               return -1;
+       if (sigaction(SIGQUIT, &sa, &quitsa) == -1) {
+               sigaction(SIGINT, &intsa, NULL);
+               return -1;
+       }
+
+       sigemptyset(&nmask);
+       sigaddset(&nmask, SIGCHLD);
+       if (sigprocmask(SIG_BLOCK, &nmask, &omask) == -1) {
+               sigaction(SIGINT, &intsa, NULL);
+               sigaction(SIGQUIT, &quitsa, NULL);
+               return -1;
+       }
+
+       (void)__readlockenv();
+       switch(pid = vfork()) {
+       case -1:                        /* error */
+               (void)__unlockenv();
+               sigaction(SIGINT, &intsa, NULL);
+               sigaction(SIGQUIT, &quitsa, NULL);
+               (void)sigprocmask(SIG_SETMASK, &omask, NULL);
+               return -1;
+       case 0:                         /* child */
+               sigaction(SIGINT, &intsa, NULL);
+               sigaction(SIGQUIT, &quitsa, NULL);
+               (void)sigprocmask(SIG_SETMASK, &omask, NULL);
+               execve(_PATH_BSHELL, __UNCONST(argp), environ);
+               _exit(127);
+       }
+       (void)__unlockenv();
+
+       while (waitpid(pid, &pstat, 0) == -1) {
+               if (errno != EINTR) {
+                       pstat = -1;
+                       break;
+               }
+       }
+
+       sigaction(SIGINT, &intsa, NULL);
+       sigaction(SIGQUIT, &quitsa, NULL);
+       (void)sigprocmask(SIG_SETMASK, &omask, NULL);
+
+       return (pstat);
+}
diff --git a/lib/nbsd_libc/stdlib/tdelete.c b/lib/nbsd_libc/stdlib/tdelete.c
new file mode 100644 (file)
index 0000000..5c80668
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: tdelete.c,v 1.4 2006/03/19 01:12:08 christos Exp $     */
+
+/*
+ * Tree search generalized from Knuth (6.2.2) Algorithm T just like
+ * the AT&T man page says.
+ *
+ * The node_t structure is for internal use only, lint doesn't grok it.
+ *
+ * Written by reading the System V Interface Definition, not the code.
+ *
+ * Totally public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: tdelete.c,v 1.4 2006/03/19 01:12:08 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#define _SEARCH_PRIVATE
+#include <search.h>
+#include <stdlib.h>
+
+
+/* delete node with given key */
+void *
+tdelete(vkey, vrootp, compar)
+       const void *vkey;       /* key to be deleted */
+       void      **vrootp;     /* address of the root of tree */
+       int       (*compar) __P((const void *, const void *));
+{
+       node_t **rootp = (node_t **)vrootp;
+       node_t *p, *q, *r;
+       int  cmp;
+
+       _DIAGASSERT(vkey != NULL);
+       _DIAGASSERT(compar != NULL);
+
+       if (rootp == NULL || (p = *rootp) == NULL)
+               return NULL;
+
+       while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0) {
+               p = *rootp;
+               rootp = (cmp < 0) ?
+                   &(*rootp)->llink :          /* follow llink branch */
+                   &(*rootp)->rlink;           /* follow rlink branch */
+               if (*rootp == NULL)
+                       return NULL;            /* key not found */
+       }
+       r = (*rootp)->rlink;                    /* D1: */
+       if ((q = (*rootp)->llink) == NULL)      /* Left NULL? */
+               q = r;
+       else if (r != NULL) {                   /* Right link is NULL? */
+               if (r->llink == NULL) {         /* D2: Find successor */
+                       r->llink = q;
+                       q = r;
+               } else {                        /* D3: Find NULL link */
+                       for (q = r->llink; q->llink != NULL; q = r->llink)
+                               r = q;
+                       r->llink = q->rlink;
+                       q->llink = (*rootp)->llink;
+                       q->rlink = (*rootp)->rlink;
+               }
+       }
+       if (p != *rootp)
+               free(*rootp);                   /* D4: Free node */
+       *rootp = q;                             /* link parent to new node */
+       return p;
+}
diff --git a/lib/nbsd_libc/stdlib/tfind.c b/lib/nbsd_libc/stdlib/tfind.c
new file mode 100644 (file)
index 0000000..c627320
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: tfind.c,v 1.5 2005/03/23 08:16:53 kleink Exp $ */
+
+/*
+ * Tree search generalized from Knuth (6.2.2) Algorithm T just like
+ * the AT&T man page says.
+ *
+ * The node_t structure is for internal use only, lint doesn't grok it.
+ *
+ * Written by reading the System V Interface Definition, not the code.
+ *
+ * Totally public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: tfind.c,v 1.5 2005/03/23 08:16:53 kleink Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#define _SEARCH_PRIVATE
+#include <stdlib.h>
+#include <search.h>
+
+/* find a node, or return 0 */
+void *
+tfind(vkey, vrootp, compar)
+       const void *vkey;               /* key to be found */
+       void * const *vrootp;           /* address of the tree root */
+       int (*compar) __P((const void *, const void *));
+{
+       node_t * const *rootp = (node_t * const*)vrootp;
+
+       _DIAGASSERT(vkey != NULL);
+       _DIAGASSERT(compar != NULL);
+
+       if (rootp == NULL)
+               return NULL;
+
+       while (*rootp != NULL) {                /* T1: */
+               int r;
+
+               if ((r = (*compar)(vkey, (*rootp)->key)) == 0)  /* T2: */
+                       return *rootp;          /* key found */
+               rootp = (r < 0) ?
+                   &(*rootp)->llink :          /* T3: follow left branch */
+                   &(*rootp)->rlink;           /* T4: follow right branch */
+       }
+       return NULL;
+}
diff --git a/lib/nbsd_libc/stdlib/tsearch.3 b/lib/nbsd_libc/stdlib/tsearch.3
new file mode 100644 (file)
index 0000000..5567f4b
--- /dev/null
@@ -0,0 +1,141 @@
+.\" $NetBSD: tsearch.3,v 1.12 2010/04/30 10:09:23 jruoho Exp $
+.\" Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
+.\" 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.
+.\" 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 ``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 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.
+.\"
+.\"    OpenBSD: tsearch.3,v 1.2 1998/06/21 22:13:49 millert Exp
+.\"
+.Dd April 30, 2010
+.Dt TSEARCH 3
+.Os
+.Sh NAME
+.Nm tsearch, tfind, tdelete, twalk
+.Nd manipulate binary search trees
+.Sh SYNOPSIS
+.In search.h
+.Ft void *
+.Fn tdelete "const void * restrict key" "void ** restrict rootp" "int (*compar) (const void *, const void *)"
+.Ft void *
+.Fn tfind "const void *key" "const void * const *rootp" "int (*compar) (const void *, const void *)"
+.Ft void *
+.Fn tsearch "const void *key" "void **rootp" "int (*compar) (const void *, const void *)"
+.Ft void
+.Fn twalk "const void *root" "void (*action) (const void *, VISIT, int)"
+.Sh DESCRIPTION
+The
+.Fn tdelete ,
+.Fn tfind ,
+.Fn tsearch ,
+and
+.Fn twalk
+functions manage binary search trees based on algorithms T and D
+from Knuth (6.2.2).
+The comparison function passed in by
+the user has the same style of return values as
+.Xr strcmp 3 .
+.Pp
+.Fn tfind
+searches for the datum matched by the argument
+.Fa key
+in the binary tree rooted at
+.Fa rootp ,
+returning a pointer to the datum if it is found and NULL
+if it is not.
+.Pp
+.Fn tsearch
+is identical to
+.Fn tfind
+except that if no match is found,
+.Fa key
+is inserted into the tree and a pointer to it is returned.
+If
+.Fa rootp
+points to a NULL value a new binary search tree is created.
+.Pp
+.Fn tdelete
+deletes a node from the specified binary search tree and returns
+a pointer to the parent of the node to be deleted.
+It takes the same arguments as
+.Fn tfind
+and
+.Fn tsearch .
+If the node to be deleted is the root of the binary search tree,
+.Fa rootp
+will be adjusted.
+.Pp
+.Fn twalk
+walks the binary search tree rooted in
+.Va root
+and calls the function
+.Fa action
+on each node.
+.Fa Action
+is called with three arguments: a pointer to the current node,
+a value from the enum
+.Sy "typedef enum { preorder, postorder, endorder, leaf } VISIT;"
+specifying the traversal type, and a node level (where level
+zero is the root of the tree).
+.Sh RETURN VALUES
+The
+.Fn tsearch
+function returns NULL if allocation of a new node fails (usually
+due to a lack of free memory).
+.Pp
+.Fn tfind ,
+.Fn tsearch ,
+and
+.Fn tdelete
+return NULL if
+.Fa rootp
+is NULL or the datum cannot be found.
+.Pp
+The
+.Fn twalk
+function returns no value.
+.Sh SEE ALSO
+.Xr bsearch 3 ,
+.Xr hsearch 3 ,
+.Xr lsearch 3
+.Sh STANDARDS
+These functions conform to
+.St -p1003.1-2001 .
+.Sh CAVEATS
+The
+.St -p1003.1-2001
+standard does not specify what value should be returned when deleting
+the root node.
+Since implementations vary, user of
+.Fn tdelete
+should not rely on any specific behaviour.
+The
+.St -p1003.1-2008
+revision tried to clarify the issue with the following wording:
+.Do
+the
+.Fn tdelete
+function shall return a pointer to the parent of the deleted node,
+or an unspecified non-NULL pointer if the deleted node was the root node, or a
+.Dv NULL
+pointer if the node is not found
+.Dc .
diff --git a/lib/nbsd_libc/stdlib/tsearch.c b/lib/nbsd_libc/stdlib/tsearch.c
new file mode 100644 (file)
index 0000000..b2f1a93
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: tsearch.c,v 1.5 2005/11/29 03:12:00 christos Exp $     */
+
+/*
+ * Tree search generalized from Knuth (6.2.2) Algorithm T just like
+ * the AT&T man page says.
+ *
+ * The node_t structure is for internal use only, lint doesn't grok it.
+ *
+ * Written by reading the System V Interface Definition, not the code.
+ *
+ * Totally public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: tsearch.c,v 1.5 2005/11/29 03:12:00 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#define _SEARCH_PRIVATE
+#include <search.h>
+#include <stdlib.h>
+
+/* find or insert datum into search tree */
+void *
+tsearch(vkey, vrootp, compar)
+       const void *vkey;               /* key to be located */
+       void **vrootp;                  /* address of tree root */
+       int (*compar) __P((const void *, const void *));
+{
+       node_t *q;
+       node_t **rootp = (node_t **)vrootp;
+
+       _DIAGASSERT(vkey != NULL);
+       _DIAGASSERT(compar != NULL);
+
+       if (rootp == NULL)
+               return NULL;
+
+       while (*rootp != NULL) {        /* Knuth's T1: */
+               int r;
+
+               if ((r = (*compar)(vkey, (*rootp)->key)) == 0)  /* T2: */
+                       return *rootp;          /* we found it! */
+
+               rootp = (r < 0) ?
+                   &(*rootp)->llink :          /* T3: follow left branch */
+                   &(*rootp)->rlink;           /* T4: follow right branch */
+       }
+
+       q = malloc(sizeof(node_t));             /* T5: key not found */
+       if (q != 0) {                           /* make new node */
+               *rootp = q;                     /* link new node to old */
+               q->key = __UNCONST(vkey);       /* initialize new node */
+               q->llink = q->rlink = NULL;
+       }
+       return q;
+}
diff --git a/lib/nbsd_libc/stdlib/twalk.c b/lib/nbsd_libc/stdlib/twalk.c
new file mode 100644 (file)
index 0000000..b4298a6
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: twalk.c,v 1.2 1999/09/16 11:45:37 lukem Exp $  */
+
+/*
+ * Tree search generalized from Knuth (6.2.2) Algorithm T just like
+ * the AT&T man page says.
+ *
+ * The node_t structure is for internal use only, lint doesn't grok it.
+ *
+ * Written by reading the System V Interface Definition, not the code.
+ *
+ * Totally public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: twalk.c,v 1.2 1999/09/16 11:45:37 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#define _SEARCH_PRIVATE
+#include <search.h>
+#include <stdlib.h>
+
+static void trecurse __P((const node_t *,
+    void  (*action)(const void *, VISIT, int), int level));
+
+/* Walk the nodes of a tree */
+static void
+trecurse(root, action, level)
+       const node_t *root;     /* Root of the tree to be walked */
+       void (*action) __P((const void *, VISIT, int));
+       int level;
+{
+       _DIAGASSERT(root != NULL);
+       _DIAGASSERT(action != NULL);
+
+       if (root->llink == NULL && root->rlink == NULL)
+               (*action)(root, leaf, level);
+       else {
+               (*action)(root, preorder, level);
+               if (root->llink != NULL)
+                       trecurse(root->llink, action, level + 1);
+               (*action)(root, postorder, level);
+               if (root->rlink != NULL)
+                       trecurse(root->rlink, action, level + 1);
+               (*action)(root, endorder, level);
+       }
+}
+
+/* Walk the nodes of a tree */
+void
+twalk(vroot, action)
+       const void *vroot;      /* Root of the tree to be walked */
+       void (*action) __P((const void *, VISIT, int));
+{
+       if (vroot != NULL && action != NULL)
+               trecurse(vroot, action, 0);
+}
diff --git a/lib/nbsd_libc/stdlib/unlockpt.3 b/lib/nbsd_libc/stdlib/unlockpt.3
new file mode 100644 (file)
index 0000000..7c8de53
--- /dev/null
@@ -0,0 +1,86 @@
+.\" $NetBSD: unlockpt.3,v 1.4 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2004 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Christos Zoulas.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 25, 2004
+.Dt UNLOCKPT 3
+.Os
+.Sh NAME
+.Nm unlockpt
+.Nd unlock the slave pseudo-terminal device
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft int
+.Fn unlockpt "int fildes"
+.Sh DESCRIPTION
+The
+.Fn unlockpt
+unlocks access to the pseudo-terminal device corresponding to the
+master pseudo-terminal device associated with
+.Fa fildes .
+Conforming applications must call this function before opening the
+slave pseudo-terminal device.
+.Sh RETURN VALUES
+If successful,
+.Fn unlockpt
+returns 0; otherwise a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn unlockpt
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCESS
+the corresponding pseudo-terminal device could not be accessed.
+.It Bq Er EBADF
+.Fa fildes
+is not a valid descriptor.
+.It Bq Er EINVAL
+.Fa fildes
+is not associated with a master pseudo-terminal device.
+.El
+.Sh NOTES
+In
+.Nx
+.Fn unlockpt
+does nothing.
+.Sh SEE ALSO
+.Xr ioctl 2 ,
+.Xr grantpt 3 ,
+.Xr posix_openpt 3 ,
+.Xr ptsname 3
+.Sh STANDARDS
+The
+.Fn unlockpt
+function conforms to
+.St -p1003.1-2001 .
+Its first release was in
+.St -xpg4.2 .
diff --git a/lib/nbsd_libc/stdlib/unsetenv.c b/lib/nbsd_libc/stdlib/unsetenv.c
new file mode 100644 (file)
index 0000000..5796f38
--- /dev/null
@@ -0,0 +1,106 @@
+/*     $NetBSD: unsetenv.c,v 1.10 2010/11/14 18:11:43 tron Exp $       */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "from: @(#)setenv.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: unsetenv.c,v 1.10 2010/11/14 18:11:43 tron Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <bitstring.h>
+
+#include "env.h"
+#include "reentrant.h"
+#include "local.h"
+
+/*
+ * unsetenv(name) --
+ *     Delete environmental variable "name".
+ */
+int
+unsetenv(const char *name)
+{
+       size_t l_name;
+       ssize_t r_offset, w_offset;
+
+       _DIAGASSERT(name != NULL);
+
+       l_name = __envvarnamelen(name, false);
+       if (l_name == 0) {
+               errno = EINVAL;
+               return -1;
+       }
+
+       if (!__writelockenv())
+               return -1;
+
+       /* Search for the given name in the environment. */
+       r_offset = __getenvslot(name, l_name, false);
+       if (r_offset == -1) {
+               /* Not found. */
+               (void)__unlockenv();
+               return 0;
+       }
+       __freeenvvar(environ[r_offset]);
+
+       /*
+        * Remove all matches from the environment and free the associated
+        * memory if possible.
+        */
+       w_offset = r_offset;
+       while (environ[++r_offset] != NULL) {
+               if (strncmp(environ[r_offset], name, l_name) != 0 ||
+                   environ[r_offset][l_name] != '=') {
+                       /* Not a match, keep this entry. */
+                       environ[w_offset++] = environ[r_offset];
+               } else {
+                       /* We found another match. */
+                       __freeenvvar(environ[r_offset]);
+               }
+       }
+
+       /* Clear out remaining stale entries in the environment vector. */
+       do {
+               environ[w_offset++] = NULL;
+       } while (w_offset < r_offset);
+
+       (void)__unlockenv();
+       return 0;
+}
diff --git a/lib/nbsd_libc/string/Lint_bcmp.c b/lib/nbsd_libc/string/Lint_bcmp.c
new file mode 100644 (file)
index 0000000..d378c9d
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_bcmp.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+int
+bcmp(b1, b2, len)
+       const void *b1, *b2;
+       size_t len;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_bcopy.c b/lib/nbsd_libc/string/Lint_bcopy.c
new file mode 100644 (file)
index 0000000..475f97f
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_bcopy.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+void
+bcopy(src, dst, len)
+       const void *src;
+       void *dst;
+       size_t len;
+{
+}
diff --git a/lib/nbsd_libc/string/Lint_bzero.c b/lib/nbsd_libc/string/Lint_bzero.c
new file mode 100644 (file)
index 0000000..86dfea3
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint_bzero.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+void
+bzero(src, len)
+       void *src;
+       size_t len;
+{
+}
diff --git a/lib/nbsd_libc/string/Lint_ffs.c b/lib/nbsd_libc/string/Lint_ffs.c
new file mode 100644 (file)
index 0000000..c3d28f6
--- /dev/null
@@ -0,0 +1,15 @@
+/* $NetBSD: Lint_ffs.c,v 1.3 2009/08/05 16:08:00 joerg Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <strings.h>
+
+/*ARGSUSED*/
+int
+ffs(int value)
+{
+       return(0);
+}
diff --git a/lib/nbsd_libc/string/Lint_index.c b/lib/nbsd_libc/string/Lint_index.c
new file mode 100644 (file)
index 0000000..a6aeef3
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_index.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+char *
+index(src, c)
+       const char *src;
+       int c;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_memccpy.c b/lib/nbsd_libc/string/Lint_memccpy.c
new file mode 100644 (file)
index 0000000..a79c875
--- /dev/null
@@ -0,0 +1,19 @@
+/*     $NetBSD: Lint_memccpy.c,v 1.1 1997/12/07 00:24:58 matthias Exp $        */
+
+/*
+ * This file placed in the public domain.
+ * Matthias Pfaller, December 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+void *
+memccpy(dst, src, c, n)
+       void *dst;
+       const void *src;
+       int c;
+       size_t n;
+{
+       return(0);
+}
diff --git a/lib/nbsd_libc/string/Lint_memchr.c b/lib/nbsd_libc/string/Lint_memchr.c
new file mode 100644 (file)
index 0000000..574ff09
--- /dev/null
@@ -0,0 +1,18 @@
+/* $NetBSD: Lint_memchr.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+void *
+memchr(b, c, len)
+       const void *b;
+       int c;
+       size_t len;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_memcmp.c b/lib/nbsd_libc/string/Lint_memcmp.c
new file mode 100644 (file)
index 0000000..a1fd275
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_memcmp.c,v 1.2 2000/06/14 06:49:08 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+int
+memcmp(b1, b2, len)
+       const void *b1, *b2;
+       size_t len;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_memcpy.c b/lib/nbsd_libc/string/Lint_memcpy.c
new file mode 100644 (file)
index 0000000..2aead93
--- /dev/null
@@ -0,0 +1,18 @@
+/* $NetBSD: Lint_memcpy.c,v 1.2 2000/06/14 06:49:08 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+void *
+memcpy(dst, src, len)
+       void *dst;
+       const void *src;
+       size_t len;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_memmove.c b/lib/nbsd_libc/string/Lint_memmove.c
new file mode 100644 (file)
index 0000000..822a296
--- /dev/null
@@ -0,0 +1,18 @@
+/* $NetBSD: Lint_memmove.c,v 1.2 2000/06/14 06:49:08 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+void *
+memmove(dst, src, len)
+       void *dst;
+       const void *src;
+       size_t len;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_memset.c b/lib/nbsd_libc/string/Lint_memset.c
new file mode 100644 (file)
index 0000000..f79b9db
--- /dev/null
@@ -0,0 +1,18 @@
+/* $NetBSD: Lint_memset.c,v 1.2 2000/06/14 06:49:08 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+void *
+memset(b, c, len)
+       void *b;
+       int c;
+       size_t len;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_rindex.c b/lib/nbsd_libc/string/Lint_rindex.c
new file mode 100644 (file)
index 0000000..c96b4d5
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_rindex.c,v 1.2 2000/06/14 06:49:08 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+char *
+rindex(src, c)
+       const char *src;
+       int c;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_strcat.c b/lib/nbsd_libc/string/Lint_strcat.c
new file mode 100644 (file)
index 0000000..279a35d
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_strcat.c,v 1.2 2000/06/14 06:49:08 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+char *
+strcat(s, append)
+       char *s;
+       const char *append;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_strchr.c b/lib/nbsd_libc/string/Lint_strchr.c
new file mode 100644 (file)
index 0000000..de541f3
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_strchr.c,v 1.2 2000/06/14 06:49:09 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+char *
+strchr(src, c)
+       const char *src;
+       int c;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_strcmp.c b/lib/nbsd_libc/string/Lint_strcmp.c
new file mode 100644 (file)
index 0000000..cd6babd
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint_strcmp.c,v 1.2 2000/06/14 06:49:09 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+int
+strcmp(s1, s2)
+       const char *s1, *s2;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_strcpy.c b/lib/nbsd_libc/string/Lint_strcpy.c
new file mode 100644 (file)
index 0000000..550ccde
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_strcpy.c,v 1.2 2000/06/14 06:49:09 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+char *
+strcpy(dst, src)
+       char *dst;
+       const char *src;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_strlen.c b/lib/nbsd_libc/string/Lint_strlen.c
new file mode 100644 (file)
index 0000000..63f51ce
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint_strlen.c,v 1.2 2000/06/14 06:49:10 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+size_t
+strlen(s)
+       const char *s;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_strncat.c b/lib/nbsd_libc/string/Lint_strncat.c
new file mode 100644 (file)
index 0000000..f0181a3
--- /dev/null
@@ -0,0 +1,18 @@
+/*     $NetBSD: Lint_strncat.c,v 1.1 1997/12/07 00:24:58 matthias Exp $        */
+
+/*
+ * This file placed in the public domain.
+ * Matthias Pfaller, December 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+char *
+strncat(dst, src, n)
+       char *dst;
+       const char *src;
+       size_t n;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_strncmp.c b/lib/nbsd_libc/string/Lint_strncmp.c
new file mode 100644 (file)
index 0000000..645f49c
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_strncmp.c,v 1.2 2000/06/14 06:49:10 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+int
+strncmp(s1, s2, len)
+       const char *s1, *s2;
+       size_t len;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_strncpy.c b/lib/nbsd_libc/string/Lint_strncpy.c
new file mode 100644 (file)
index 0000000..6966f6f
--- /dev/null
@@ -0,0 +1,18 @@
+/*     $NetBSD: Lint_strncpy.c,v 1.1 1997/12/07 00:24:58 matthias Exp $        */
+
+/*
+ * This file placed in the public domain.
+ * Matthias Pfaller, December 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+char *
+strncpy(dst, src, n)
+       char *dst;
+       const char *src;
+       size_t n;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_strrchr.c b/lib/nbsd_libc/string/Lint_strrchr.c
new file mode 100644 (file)
index 0000000..fb64549
--- /dev/null
@@ -0,0 +1,17 @@
+/* $NetBSD: Lint_strrchr.c,v 1.2 2000/06/14 06:49:10 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+char *
+strrchr(src, c)
+       const char *src;
+       int c;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/Lint_swab.c b/lib/nbsd_libc/string/Lint_swab.c
new file mode 100644 (file)
index 0000000..64986c6
--- /dev/null
@@ -0,0 +1,14 @@
+/* $NetBSD: Lint_swab.c,v 1.3 2010/07/05 00:45:19 christos Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <string.h>
+
+/*ARGSUSED*/
+void
+swab(const void *src, void *dst, ssize_t len)
+{
+}
diff --git a/lib/nbsd_libc/string/Makefile.inc b/lib/nbsd_libc/string/Makefile.inc
new file mode 100644 (file)
index 0000000..ed2c67e
--- /dev/null
@@ -0,0 +1,78 @@
+#      from: @(#)Makefile.inc  8.1 (Berkeley) 6/4/93
+#      $NetBSD: Makefile.inc,v 1.75 2009/07/30 20:57:15 dsl Exp $
+
+# string sources
+.PATH: ${ARCHDIR}/string ${.CURDIR}/string
+
+# NB: if a .S version of any of these is added in the arch/*/Makefile
+# then the relevant .c file is automatically removed
+# Also adding the .c name to NO_SRCS will have the same effect
+
+SRCS+= bm.c stpcpy.c stpncpy.c \
+       strcasecmp.c strncasecmp.c strcasestr.c strcoll.c strdup.c \
+       strerror.c strlcat.c strlcpy.c strnlen.c \
+       strmode.c strsignal.c strtok.c \
+       strtok_r.c strxfrm.c __strsignal.c strerror_r.c strndup.c \
+       stresep.c memrchr.c
+
+SRCS+= bcmp.c bcopy.c bzero.c ffs.c memchr.c memcmp.c memset.c
+SRCS+= strcat.c strcmp.c strcpy.c strcspn.c strlen.c
+SRCS+= strncat.c strncmp.c strncpy.c strpbrk.c strsep.c
+SRCS+= strspn.c strstr.c swab.c
+
+SRCS+= memccpy.c memcpy.c memmem.c memmove.c
+SRCS+= strchr.c strrchr.c
+SRCS+= popcount32.c popcount64.c
+
+# wide char
+SRCS+= wcscat.c wcschr.c wcscmp.c wcscpy.c wcscspn.c wcslcat.c wcslcpy.c \
+       wcslen.c wcsncat.c wcscasecmp.c wcsdup.c wcsncasecmp.c \
+       wcsncmp.c wcsncpy.c wcspbrk.c wcsrchr.c wcsspn.c wcsstr.c wcstok.c \
+       wcswcs.c wmemchr.c wmemcmp.c wmemcpy.c wmemmove.c wmemset.c
+CPPFLAGS.wcscmp.c+=    -I${LIBCDIR}/locale
+CPPFLAGS.wcsncmp.c+=   -I${LIBCDIR}/locale
+CPPFLAGS.wmemcmp.c+=   -I${LIBCDIR}/locale
+
+# namespace protection wrappers
+SRCS+= _strlcat.c _strlcpy.c _strerror_r.c
+
+.include "${ARCHDIR}/string/Makefile.inc"
+
+MAN+=  bm.3 bcmp.3 bcopy.3 bstring.3 bzero.3 ffs.3 index.3 \
+       memccpy.3 memchr.3 memcmp.3 memcpy.3 memmem.3 memmove.3 memset.3 \
+       popcount.3 \
+       rindex.3 strcasecmp.3 strcat.3 strchr.3 strcmp.3 strcoll.3 \
+       strcpy.3 strcspn.3 strdup.3 strerror.3 string.3 strings.3 strlcpy.3 \
+       strlen.3 strmode.3 strpbrk.3 strrchr.3 strsep.3 \
+       strsignal.3 strspn.3 strstr.3 strtok.3 strxfrm.3 \
+       swab.3 wcstok.3 wcswidth.3 wmemchr.3 wcsdup.3 wcscasecmp.3
+
+MLINKS+=bm.3 bm_comp.3 bm.3 bm_exec.3 bm.3 bm_free.3
+MLINKS+=popcount.3 popcountl.3
+MLINKS+=popcount.3 popcountll.3
+MLINKS+=popcount.3 popcount32.3
+MLINKS+=popcount.3 popcount64.3
+MLINKS+=strcasecmp.3 strncasecmp.3
+MLINKS+=strcat.3 strncat.3
+MLINKS+=strcmp.3 strncmp.3
+MLINKS+=strcpy.3 strncpy.3 strcpy.3 stpcpy.3 strcpy.3 stpncpy.3
+MLINKS+=strlcpy.3 strlcat.3
+MLINKS+=strlen.3 strnlen.3
+MLINKS+=strstr.3 strcasestr.3
+MLINKS+=memchr.3 memrchr.3
+MLINKS+=strtok.3 strtok_r.3
+MLINKS+=strerror.3 strerror_r.3 strerror.3 perror.3 \
+       strerror.3 sys_errlist.3 strerror.3 sys_nerr.3
+MLINKS+=strdup.3 strndup.3
+MLINKS+=strsep.3 stresep.3
+MLINKS+=wmemchr.3 wmemcmp.3 wmemchr.3 wmemcpy.3 \
+       wmemchr.3 wmemmove.3 wmemchr.3 wmemset.3 \
+       wmemchr.3 wcscat.3 wmemchr.3 wcschr.3 \
+       wmemchr.3 wcscmp.3 wmemchr.3 wcscpy.3 \
+       wmemchr.3 wcscspn.3 wmemchr.3 wcslcat.3 \
+       wmemchr.3 wcslcpy.3 wmemchr.3 wcslen.3 \
+       wmemchr.3 wcsncat.3 wmemchr.3 wcsncmp.3 \
+       wmemchr.3 wcsncpy.3 wmemchr.3 wcspbrk.3 \
+       wmemchr.3 wcsrchr.3 wmemchr.3 wcsspn.3 \
+       wmemchr.3 wcsstr.3 wmemchr.3 wcswcs.3
+MLINKS+=wcscasecmp.3 wcsncasecmp.3
diff --git a/lib/nbsd_libc/string/__strsignal.c b/lib/nbsd_libc/string/__strsignal.c
new file mode 100644 (file)
index 0000000..2c5d1e5
--- /dev/null
@@ -0,0 +1,104 @@
+/*     $NetBSD: __strsignal.c,v 1.24 2003/08/07 16:43:46 agc Exp $     */
+
+/*
+ * Copyright (c) 1988 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)strerror.c  5.6 (Berkeley) 5/4/91";
+#else
+__RCSID("$NetBSD: __strsignal.c,v 1.24 2003/08/07 16:43:46 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#ifdef NLS
+#include <limits.h>
+#include <nl_types.h>
+#endif
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include "extern.h"
+#include <signal.h>
+#ifndef SIGRTMIN       /* XXX: Until we remove the #ifdef _KERNEL */
+#define SIGRTMIN       33
+#define SIGRTMAX       63
+#endif
+
+/* ARGSUSED */
+const char *
+__strsignal(num, buf, buflen)
+       int num;
+       char *buf;
+       size_t buflen;
+{
+#define        UPREFIX "Unknown signal: %u"
+#define RPREFIX "Real time signal %u"
+       unsigned int signum;
+
+#ifdef NLS
+       nl_catd catd ;
+       catd = catopen("libc", NL_CAT_LOCALE);
+#endif
+
+       _DIAGASSERT(buf != NULL);
+
+       signum = num;                           /* convert to unsigned */
+       if (signum < (unsigned int) sys_nsig) {
+#ifdef NLS
+               (void)strlcpy(buf, catgets(catd, 2, (int)signum,
+                   sys_siglist[signum]), buflen); 
+#else
+               return((char *)sys_siglist[signum]);
+#endif
+       } else if (signum >= SIGRTMIN && signum <= SIGRTMAX) {
+#ifdef NLS
+               (void)snprintf(buf, buflen, 
+                   catgets(catd, 2, SIGRTMIN, RPREFIX), signum);
+#else
+               (void)snprintf(buf, buflen, RPREFIX, signum);
+#endif
+       } else {
+#ifdef NLS
+               (void)snprintf(buf, buflen, 
+                   catgets(catd, 1, 0xffff, UPREFIX), signum);
+#else
+               (void)snprintf(buf, buflen, UPREFIX, signum);
+#endif
+       }
+
+#ifdef NLS
+       catclose(catd);
+#endif
+
+       return buf;
+}
diff --git a/lib/nbsd_libc/string/_strerror_r.c b/lib/nbsd_libc/string/_strerror_r.c
new file mode 100644 (file)
index 0000000..321c205
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: _strerror_r.c,v 1.3 2008/04/28 20:23:00 martin Exp $   */
+
+/*-
+ * Copyright (c) 2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _strerror_r.c,v 1.3 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_strerror_r, strerror_r)
+#else
+
+#include <string.h>
+int    _strerror_r(int, char *, size_t);
+
+int
+strerror_r(int num, char *buf, size_t siz)
+{
+
+       return _strerror_r(num, buf, siz);
+}
+#endif
diff --git a/lib/nbsd_libc/string/_strlcat.c b/lib/nbsd_libc/string/_strlcat.c
new file mode 100644 (file)
index 0000000..8dd9046
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: _strlcat.c,v 1.5 2009/10/21 01:07:45 snj Exp $ */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _strlcat.c,v 1.5 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_strlcat, strlcat)
+#else
+
+#include <string.h>
+size_t _strlcat(char *, const char *, size_t);
+
+size_t
+strlcat(char *dst, const char *src, size_t siz)
+{
+
+       return _strlcat(dst, src, siz);
+}
+#endif
diff --git a/lib/nbsd_libc/string/_strlcpy.c b/lib/nbsd_libc/string/_strlcpy.c
new file mode 100644 (file)
index 0000000..7a1e498
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: _strlcpy.c,v 1.5 2009/10/21 01:07:45 snj Exp $ */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _strlcpy.c,v 1.5 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_strlcpy, strlcpy)
+#else
+
+#include <string.h>
+size_t _strlcpy(char *, const char *, size_t);
+
+size_t
+strlcpy(char *dst, const char *src, size_t siz)
+{
+
+       return _strlcpy(dst, src, siz);
+}
+#endif
diff --git a/lib/nbsd_libc/string/bcmp.3 b/lib/nbsd_libc/string/bcmp.3
new file mode 100644 (file)
index 0000000..b9ffe6c
--- /dev/null
@@ -0,0 +1,85 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\" 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. 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.
+.\"
+.\"     from: @(#)bcmp.3       8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: bcmp.3,v 1.13 2010/04/29 06:54:26 jruoho Exp $
+.\"
+.Dd April 29, 2010
+.Dt BCMP 3
+.Os
+.Sh NAME
+.Nm bcmp
+.Nd compare byte string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In strings.h
+.Ft int
+.Fn bcmp "const void *b1" "const void *b2" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn bcmp
+function
+compares byte string
+.Fa b1
+against byte string
+.Fa b2 ,
+returning zero if they are identical, non-zero otherwise.
+Both strings are assumed to be
+.Fa len
+bytes long.
+Zero-length strings are always identical.
+.Pp
+The strings may overlap.
+.Sh SEE ALSO
+.Xr memcmp 3 ,
+.Xr strcasecmp 3 ,
+.Xr strcmp 3 ,
+.Xr strcoll 3 ,
+.Xr strxfrm 3
+.Sh STANDARDS
+The
+.Fn bcmp
+function conforms to
+.St -p1003.1-2001 .
+The
+.St -p1003.1-2004
+revision marked it as legacy and recommended the use of
+.Xr memcmp 3
+instead.
+The
+.St -p1003.1-2008
+revision removed
+.Fn bcmp
+from the specification.
+.Sh HISTORY
+A
+.Fn bcmp
+function first appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/string/bcopy.3 b/lib/nbsd_libc/string/bcopy.3
new file mode 100644 (file)
index 0000000..6fa914d
--- /dev/null
@@ -0,0 +1,80 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)bcopy.3      8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: bcopy.3,v 1.13 2010/04/29 07:27:30 wiz Exp $
+.\"
+.Dd April 29, 2010
+.Dt BCOPY 3
+.Os
+.Sh NAME
+.Nm bcopy
+.Nd copy byte string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In strings.h
+.Ft void
+.Fn bcopy "const void *src" "void *dst" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn bcopy
+function
+copies
+.Fa len
+bytes from string
+.Fa src
+to string
+.Fa dst .
+The two strings may overlap.
+If
+.Fa len
+is zero, no bytes are copied.
+.Sh SEE ALSO
+.Xr memccpy 3 ,
+.Xr memcpy 3 ,
+.Xr memmove 3 ,
+.Xr strcpy 3 ,
+.Xr strncpy 3
+.Sh STANDARDS
+The
+.Fn bcmp
+function conforms to
+.St -p1003.1-2001 .
+The
+.St -p1003.1-2004
+revision marked it as legacy; the
+.St -p1003.1-2008
+revision removed it from the specification.
+.Sh HISTORY
+A
+.Fn bcopy
+function appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/string/bm.3 b/lib/nbsd_libc/string/bm.3
new file mode 100644 (file)
index 0000000..d5d3c8f
--- /dev/null
@@ -0,0 +1,114 @@
+.\" $NetBSD: bm.3,v 1.8 2006/10/16 08:48:45 wiz Exp $
+.\"
+.\" Copyright (c) 1994
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Andrew Hume of AT&T Bell Laboratories.
+.\"
+.\" 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. 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.
+.\"
+.\"    from: @(#)bm.3  8.4 (Berkeley) 6/21/94
+.\"
+.Dd April 8, 2001
+.Dt BM 3
+.Os
+.Sh NAME
+.Nm bm_comp ,
+.Nm bm_exec ,
+.Nm bm_free
+.Nd Boyer-Moore string search
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In bm.h
+.Ft bm_pat *
+.Fn bm_comp "u_char *pattern" "size_t patlen" "u_char freq[256]"
+.Ft u_char *
+.Fn bm_exec "bm_pat *pdesc" "u_char *text" "size_t len"
+.Ft void
+.Fn bm_free "bm_pat *pdesc"
+.Sh DESCRIPTION
+These routines implement an efficient mechanism to find an
+occurrence of a byte string within another byte string.
+.Pp
+.Fn bm_comp
+evaluates the
+.Fa patlen
+bytes starting at
+.Fa pattern ,
+and returns a pointer to a structure describing them.
+The bytes referenced by
+.Fa pattern
+may be of any value.
+.Pp
+The search takes advantage of the frequency distribution of the
+bytes in the text to be searched.
+If specified,
+.Fa freq
+should be an array of 256 values,
+with higher values indicating that the corresponding character occurs
+more frequently.
+(A less than optimal frequency distribution can only result in less
+than optimal performance, not incorrect results.)
+If
+.Fa freq
+is
+.Dv NULL ,
+a system default table is used.
+.Pp
+.Fn bm_exec
+returns a pointer to the leftmost occurrence of the string given to
+.Fn bm_comp
+within
+.Fa text ,
+or
+.Dv NULL
+if none occurs.
+The number of bytes in
+.Fa text
+must be specified by
+.Fa len .
+.Pp
+Space allocated for the returned description is discarded
+by calling
+.Fn bm_free
+with the returned description as an argument.
+.Pp
+The asymptotic speed of
+.Fn bm_exec
+is O(len/patlen).
+.Sh SEE ALSO
+.Xr regexp 3 ,
+.Xr strstr 3
+.Rs
+.%A Hume and Sunday
+.%D November 1991
+.%J "Software Practice and Experience"
+.%P pp. 1221-48
+.%T "Fast String Searching"
+.%V Vol. 21, 11
+.Re
diff --git a/lib/nbsd_libc/string/bm.c b/lib/nbsd_libc/string/bm.c
new file mode 100644 (file)
index 0000000..e38fe7d
--- /dev/null
@@ -0,0 +1,239 @@
+/*     $NetBSD: bm.c,v 1.11 2003/08/07 16:43:47 agc Exp $      */
+
+/*-
+ * Copyright (c) 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Andrew Hume of AT&T Bell Laboratories.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)bm.c       8.7 (Berkeley) 6/21/94";
+#else
+__RCSID("$NetBSD: bm.c,v 1.11 2003/08/07 16:43:47 agc Exp $");
+#endif
+#endif /* LIBC_SCCS && not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+
+#include <assert.h>
+#include <bm.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(bm_comp,_bm_comp)
+__weak_alias(bm_exec,_bm_exec)
+__weak_alias(bm_free,_bm_free)
+#endif
+
+/* 
+ * XXX
+ * The default frequency table starts at 99 and counts down.  The default
+ * table should probably be oriented toward text, and will necessarily be
+ * locale specific.  This one is for English.  It was derived from the
+ * OSF/1 and 4.4BSD formatted and unformatted manual pages, and about 100Mb
+ * of email and random text.  Change it if you can find something better.
+ */
+static u_char const freq_def[256] = {
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0, 77, 90,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+       99, 28, 42, 27, 16, 14, 20, 51,
+       66, 65, 59, 24, 75, 76, 84, 56,
+       72, 74, 64, 55, 54, 47, 41, 37,
+       44, 61, 70, 43, 23, 53, 49, 22,
+       33, 58, 40, 46, 45, 57, 60, 26,
+       30, 63, 21, 12, 32, 50, 38, 39,
+       34, 11, 48, 67, 62, 35, 15, 29,
+       71, 18,  9, 17, 25, 13, 10, 52,
+       36, 95, 78, 86, 87, 98, 82, 80,
+       88, 94, 19, 68, 89, 83, 93, 96,
+       81,  7, 91, 92, 97, 85, 69, 73,
+       31, 79,  8,  5,  4,  6,  3,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+};
+
+bm_pat *
+bm_comp(pb, len, freq)
+       u_char const *pb;
+       size_t len;
+       u_char const *freq;
+{
+       u_char const *pe, *p;
+       size_t *d, r;
+       int j;
+       int sv_errno;
+       bm_pat *pat;
+
+       _DIAGASSERT(pb != NULL);
+       /* freq may be NULL */
+
+       if (len == 0) {
+               errno = EINVAL;
+               return (NULL);
+       }
+       if ((pat = malloc(sizeof(*pat))) == NULL)
+               return (NULL);
+       pat->pat = NULL;
+       pat->delta = NULL;
+
+       pat->patlen = len;                      /* copy pattern */
+       if ((pat->pat = malloc(pat->patlen)) == NULL)
+               goto mem;
+       memcpy(pat->pat, pb, pat->patlen);
+                                               /* get skip delta */
+       if ((pat->delta = malloc(256 * sizeof(*d))) == NULL)
+               goto mem;
+       for (j = 0, d = pat->delta; j < 256; j++)
+               d[j] = pat->patlen;
+       for (pe = pb + pat->patlen - 1; pb <= pe; pb++)
+               d[*pb] = pe - pb;
+
+       if (freq == NULL)                       /* default freq table */
+               freq = freq_def;
+       r = 0;                                  /* get guard */
+       for (pb = pat->pat, pe = pb + pat->patlen - 1; pb < pe; pb++)
+               if (freq[*pb] < freq[pat->pat[r]])
+                       r = pb - pat->pat;
+       pat->rarec = pat->pat[r];
+       pat->rareoff = r - (pat->patlen - 1);
+
+                                               /* get md2 shift */
+       for (pe = pat->pat + pat->patlen - 1, p = pe - 1; p >= pat->pat; p--)
+               if (*p == *pe)
+                       break;
+
+       /* *p is first leftward reoccurrence of *pe */
+       pat->md2 = pe - p;
+       return (pat);
+
+mem:   sv_errno = errno;
+       bm_free(pat);
+       errno = sv_errno;
+       return (NULL);
+}
+
+void
+bm_free(pat)
+       bm_pat *pat;
+{
+
+       _DIAGASSERT(pat != NULL);
+
+       if (pat->pat != NULL)
+               free(pat->pat);
+       if (pat->delta != NULL)
+               free(pat->delta);
+       free(pat);
+}
+
+u_char *
+bm_exec(pat, base, n)
+       bm_pat *pat;
+       u_char *base;
+       size_t n;
+{
+       u_char *e, *ep, *p, *q, *s;
+       size_t *d0, k, md2, n1, ro;
+       int rc;
+
+       _DIAGASSERT(pat != NULL);
+       _DIAGASSERT(base != NULL);
+
+       if (n == 0)
+               return (NULL);
+
+       d0 = pat->delta;
+       n1 = pat->patlen - 1;
+       md2 = pat->md2;
+       ro = pat->rareoff;
+       rc = pat->rarec;
+       ep = pat->pat + pat->patlen - 1;
+       s = base + (pat->patlen - 1);
+
+       /* fast loop up to n - 3 * patlen */
+       e = base + n - 3 * pat->patlen;
+       while (s < e) {
+               k = d0[*s];             /* ufast skip loop */
+               while (k) {
+                       k = d0[*(s += k)];
+                       k = d0[*(s += k)];
+               }
+               if (s >= e)
+                       break;
+               if (s[ro] != rc)        /* guard test */
+                       goto mismatch1;
+                                       /* fwd match */
+               for (p = pat->pat, q = s - n1; p < ep;)
+                       if (*q++ != *p++)
+                               goto mismatch1;
+               return (s - n1);
+
+mismatch1:     s += md2;               /* md2 shift */
+       }
+
+       /* slow loop up to end */
+       e = base + n;
+       while (s < e) {
+               s += d0[*s];            /* step */
+               if (s >= e)
+                       break;
+               if (s[ro] != rc)        /* guard test */
+                       goto mismatch2;
+                                       /* fwd match */
+               for (p = pat->pat, q = s - n1; p <= ep;)
+                       if (*q++ != *p++)
+                               goto mismatch2;
+               return (s - n1);
+
+mismatch2:     s += md2;               /* md2 shift */
+       }
+
+       return (NULL);
+}
diff --git a/lib/nbsd_libc/string/bstring.3 b/lib/nbsd_libc/string/bstring.3
new file mode 100644 (file)
index 0000000..b85ef8f
--- /dev/null
@@ -0,0 +1,93 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\" 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. 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.
+.\"
+.\"     from: @(#)bstring.3    8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: bstring.3,v 1.11 2007/02/17 09:04:57 wiz Exp $
+.\"
+.Dd February 9, 2007
+.Dt BSTRING 3
+.Os
+.Sh NAME
+.Nm memccpy ,
+.Nm memchr ,
+.Nm memcmp ,
+.Nm memcpy ,
+.Nm memmem ,
+.Nm memmove ,
+.Nm memset
+.Nd byte string operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft void *
+.Fn memchr "const void *b" "int c" "size_t len"
+.Ft int
+.Fn memcmp "const void *b1" "const void *b2" "size_t len"
+.Ft void *
+.Fn memccpy "void *dst" "const void *src" "int c" "size_t len"
+.Ft void *
+.Fn memcpy "void *dst" "const void *src" "size_t len"
+.Ft void *
+.Fn memmem "const void *block" "size_t blen" "const void *pat" "size_t plen"
+.Ft void *
+.Fn memmove "void *dst" "const void *src" "size_t len"
+.Ft void *
+.Fn memset "void *b" "int c" "size_t len"
+.Sh DESCRIPTION
+These functions operate on variable length strings of bytes.
+They do not check for terminating nul bytes as the routines
+listed in
+.Xr string 3
+do.
+.Pp
+See the specific manual pages for more information.
+.Sh SEE ALSO
+.Xr memccpy 3 ,
+.Xr memchr 3 ,
+.Xr memcmp 3 ,
+.Xr memcpy 3 ,
+.Xr memmem 3 ,
+.Xr memmove 3 ,
+.Xr memset 3
+.Sh STANDARDS
+The functions
+.Fn memchr ,
+.Fn memcmp ,
+.Fn memcpy ,
+.Fn memmove ,
+and
+.Fn memset
+conform to
+.St -ansiC .
+.Sh HISTORY
+The function
+.Fn memccpy
+appeared in
+.Bx 4.3 .
diff --git a/lib/nbsd_libc/string/bzero.3 b/lib/nbsd_libc/string/bzero.3
new file mode 100644 (file)
index 0000000..b47d5b8
--- /dev/null
@@ -0,0 +1,82 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)bzero.3      8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: bzero.3,v 1.13 2010/04/29 06:54:26 jruoho Exp $
+.\"
+.Dd April 29, 2010
+.Dt BZERO 3
+.Os
+.Sh NAME
+.Nm bzero
+.Nd write zeroes to a byte string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In strings.h
+.Ft void
+.Fn bzero "void *b" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn bzero
+function
+writes
+.Fa len
+zero bytes to the string
+.Fa b .
+If
+.Fa len
+is zero,
+.Fn bzero
+does nothing.
+.Sh SEE ALSO
+.Xr memset 3 ,
+.Xr swab 3
+.Sh STANDARDS
+The
+.Fn bzero
+function conforms to
+.St -p1003.1-2001 .
+The
+.St -p1003.1-2004
+revision marked it as legacy and recommended the use of
+.Xr memset 3
+instead.
+The
+.St -p1003.1-2008
+revision removed
+.Fn bzero
+from the specification.
+.Sh HISTORY
+A
+.Fn bzero
+function
+appeared in
+.Bx 4.3 .
diff --git a/lib/nbsd_libc/string/ffs.3 b/lib/nbsd_libc/string/ffs.3
new file mode 100644 (file)
index 0000000..5d6bcc5
--- /dev/null
@@ -0,0 +1,74 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\" 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. 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.
+.\"
+.\"     from: @(#)ffs.3        8.2 (Berkeley) 4/19/94
+.\"    $NetBSD: ffs.3,v 1.13 2010/04/28 07:47:09 jruoho Exp $
+.\"
+.Dd April 28, 2010
+.Dt FFS 3
+.Os
+.Sh NAME
+.Nm ffs
+.Nd find first bit set in a bit string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In strings.h
+.Ft int
+.Fn ffs "int value"
+.Sh DESCRIPTION
+The
+.Fn ffs
+function finds the first bit set in
+.Fa value
+and returns the index of that bit.
+Bits are numbered starting from 1, starting at the right-most
+bit.
+A return value of 0 means that the argument was zero.
+.Sh SEE ALSO
+.Xr bitstring 3 ,
+.Xr ffs32 3 ,
+.Xr popcount 3
+.Sh STANDARDS
+The
+.Fn ffs
+function conforms to
+.St -p1003.1-2001 .
+.Sh HISTORY
+The
+.Fn ffs
+function appeared in
+.Bx 4.3 .
+The prototype for it existed previously in the
+.In string.h
+header before it was moved to
+.In strings.h
+for
+.Tn POSIX
+compliance.
diff --git a/lib/nbsd_libc/string/index.3 b/lib/nbsd_libc/string/index.3
new file mode 100644 (file)
index 0000000..f695555
--- /dev/null
@@ -0,0 +1,94 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\" 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. 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.
+.\"
+.\"     from: @(#)index.3      8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: index.3,v 1.13 2010/04/29 06:54:26 jruoho Exp $
+.\"
+.Dd April 29, 2010
+.Dt INDEX 3
+.Os
+.Sh NAME
+.Nm index
+.Nd locate character in string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In strings.h
+.Ft char *
+.Fn index "const char *s" "int c"
+.Sh DESCRIPTION
+The
+.Fn index
+function
+locates the first character matching
+.Fa c
+(converted to a
+.Em char )
+in the nul-terminated string
+.Fa s .
+.Sh RETURN VALUES
+A pointer to the character is returned if it is found; otherwise
+.Dv NULL
+is returned.
+If
+.Fa c
+is '\e0',
+.Fn index
+locates the terminating '\e0'.
+.Sh SEE ALSO
+.Xr memchr 3 ,
+.Xr rindex 3 ,
+.Xr strchr 3 ,
+.Xr strcspn 3 ,
+.Xr strpbrk 3 ,
+.Xr strrchr 3 ,
+.Xr strsep 3 ,
+.Xr strspn 3 ,
+.Xr strstr 3 ,
+.Xr strtok 3
+.Sh STANDARDS
+The
+.Fn index
+function conforms to
+.St -p1003.1-2001 .
+The
+.St -p1003.1-2004
+revision marked it as legacy and recommended the use of
+.Xr strchr 3
+instead.
+The
+.St -p1003.1-2008
+revision removed
+.Fn index
+from the specification.
+.Sh HISTORY
+An
+.Fn index
+function appeared in
+.At v6 .
diff --git a/lib/nbsd_libc/string/index.c b/lib/nbsd_libc/string/index.c
new file mode 100644 (file)
index 0000000..6258e6b
--- /dev/null
@@ -0,0 +1,3 @@
+/*     $NetBSD: index.c,v 1.15 2005/12/20 19:31:50 christos Exp $      */
+#define INDEX
+#include "strchr.c"
diff --git a/lib/nbsd_libc/string/memccpy.3 b/lib/nbsd_libc/string/memccpy.3
new file mode 100644 (file)
index 0000000..9f6b54e
--- /dev/null
@@ -0,0 +1,72 @@
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)memccpy.3    8.1 (Berkeley) 6/9/93
+.\"    $NetBSD: memccpy.3,v 1.10 2006/10/16 08:48:45 wiz Exp $
+.\"
+.Dd June 9, 1993
+.Dt MEMCCPY 3
+.Os
+.Sh NAME
+.Nm memccpy
+.Nd copy string until character found
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft void *
+.Fn memccpy "void *dst" "const void *src" "int c" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn memccpy
+function
+copies bytes from string
+.Fa src
+to string
+.Fa dst .
+If the character
+.Fa c
+(as converted to an unsigned char) occurs in the string
+.Fa src ,
+the copy stops and a pointer to the byte after the copy of
+.Fa c
+in the string
+.Fa dst
+is returned.
+Otherwise,
+.Fa len
+bytes are copied, and a null pointer is returned.
+.Sh SEE ALSO
+.Xr bcopy 3 ,
+.Xr memcpy 3 ,
+.Xr memmove 3 ,
+.Xr strcpy 3
+.Sh HISTORY
+The
+.Fn memccpy
+function first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/string/memccpy.c b/lib/nbsd_libc/string/memccpy.c
new file mode 100644 (file)
index 0000000..5569692
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: memccpy.c,v 1.12 2003/08/07 16:43:48 agc Exp $ */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)memccpy.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: memccpy.c,v 1.12 2003/08/07 16:43:48 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <string.h>
+
+void *
+memccpy(t, f, c, n)
+       void *t;
+       const void *f;
+       int c;
+       size_t n;
+{
+
+       _DIAGASSERT(t != 0);
+       _DIAGASSERT(f != 0);
+
+       if (n) {
+               unsigned char *tp = t;
+               const unsigned char *fp = f;
+               unsigned char uc = c;
+               do {
+                       if ((*tp++ = *fp++) == uc)
+                               return (tp);
+               } while (--n != 0);
+       }
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/memchr.3 b/lib/nbsd_libc/string/memchr.3
new file mode 100644 (file)
index 0000000..cb3b968
--- /dev/null
@@ -0,0 +1,94 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)memchr.3     8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: memchr.3,v 1.11 2009/04/10 23:24:35 wiz Exp $
+.\"
+.Dd April 10, 2009
+.Dt MEMCHR 3
+.Os
+.Sh NAME
+.Nm memchr ,
+.Nm memrchr
+.Nd locate byte in byte string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft void *
+.Fn memchr "const void *b" "int c" "size_t len"
+.Ft void *
+.Fn memrchr "const void *b" "int c" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn memchr
+function
+locates the first occurrence of
+.Fa c
+(converted to an unsigned char)
+in string
+.Fa b .
+The
+.Fn memrchr
+function
+locates the last occurrence of
+.Fa c
+(converted to an unsigned char)
+in string
+.Fa b .
+.Sh RETURN VALUES
+The
+.Fn memchr
+and
+.Fn memrchr
+functions
+return a pointer to the byte located, or
+.Dv NULL
+if no such byte exists within
+.Fa len
+bytes.
+.Sh SEE ALSO
+.Xr index 3 ,
+.Xr rindex 3 ,
+.Xr strchr 3 ,
+.Xr strcspn 3 ,
+.Xr strpbrk 3 ,
+.Xr strrchr 3 ,
+.Xr strsep 3 ,
+.Xr strspn 3 ,
+.Xr strstr 3 ,
+.Xr strtok 3
+.Sh STANDARDS
+The
+.Fn memchr
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/string/memcmp.3 b/lib/nbsd_libc/string/memcmp.3
new file mode 100644 (file)
index 0000000..ed78604
--- /dev/null
@@ -0,0 +1,81 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)memcmp.3     8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: memcmp.3,v 1.9 2003/08/07 16:43:48 agc Exp $
+.\"
+.Dd June 4, 1993
+.Dt MEMCMP 3
+.Os
+.Sh NAME
+.Nm memcmp
+.Nd compare byte string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft int
+.Fn memcmp "const void *b1" "const void *b2" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn memcmp
+function
+compares byte string
+.Fa b1
+against byte string
+.Fa b2 .
+Both strings are assumed to be
+.Fa len
+bytes long.
+.Sh RETURN VALUES
+The
+.Fn memcmp
+function
+returns zero if the two strings are identical,
+otherwise returns the difference between the first two differing bytes
+(treated as unsigned char values, so that
+.Sq Li \e200
+is greater than
+.Sq Li \&\e0 ,
+for example).
+Zero-length strings are always identical.
+.Sh SEE ALSO
+.Xr bcmp 3 ,
+.Xr strcasecmp 3 ,
+.Xr strcmp 3 ,
+.Xr strcoll 3 ,
+.Xr strxfrm 3
+.Sh STANDARDS
+The
+.Fn memcmp
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/string/memcpy.3 b/lib/nbsd_libc/string/memcpy.3
new file mode 100644 (file)
index 0000000..b432e32
--- /dev/null
@@ -0,0 +1,77 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)memcpy.3     8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: memcpy.3,v 1.13 2003/09/08 17:54:33 wiz Exp $
+.\"
+.Dd June 4, 1993
+.Dt MEMCPY 3
+.Os
+.Sh NAME
+.Nm memcpy
+.Nd copy byte string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft void *
+.Fn memcpy "void * restrict dst" "const void * restrict src" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn memcpy
+function
+copies
+.Fa len
+bytes from string
+.Fa src
+to string
+.Fa dst .
+The arguments must not overlap -- behavior if the arguments overlap is
+undefined.
+To copy byte strings that overlap, use
+.Xr memmove 3 .
+.Sh RETURN VALUES
+The
+.Fn memcpy
+function
+returns the original value of
+.Fa dst .
+.Sh SEE ALSO
+.Xr bcopy 3 ,
+.Xr memccpy 3 ,
+.Xr memmove 3 ,
+.Xr strcpy 3
+.Sh STANDARDS
+The
+.Fn memcpy
+function
+conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/string/memmem.3 b/lib/nbsd_libc/string/memmem.3
new file mode 100644 (file)
index 0000000..4a0387f
--- /dev/null
@@ -0,0 +1,84 @@
+.\"    $NetBSD: memmem.3,v 1.3 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2005 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Perry E. Metzger of Metzger, Dowdeswell & Co. LLC.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd March 12, 2005
+.Dt MEMMEM 3
+.Os
+.Sh NAME
+.Nm memmem
+.Nd locate substring in byte string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft void *
+.Fn memmem "const void *block" "size_t blen" "const void *pat" "size_t plen"
+.Sh DESCRIPTION
+The
+.Fn memmem
+function locates the first occurrence of the binary string
+.Fa pat
+of size
+.Fa plen
+bytes in the byte string
+.Fa block
+of size
+.Fa blen
+bytes.
+.Sh RETURN VALUES
+The
+.Fn memmem
+function returns a pointer to the substring located, or
+.Dv NULL
+if no such substring exists within
+.Fa block .
+.Pp
+If
+.Fa plen
+is zero,
+.Fa block
+is returned, i.e. a zero length
+.Fa pat
+is deemed to match the start of the string, as with
+.Xr strstr 3 .
+.Sh SEE ALSO
+.Xr bm 3 ,
+.Xr memchr 3 ,
+.Xr strchr 3 ,
+.Xr strstr 3
+.Sh STANDARDS
+The
+.Fn memmem
+function is not currently standardized.
+However, it is meant to be API compatible with functions in
+.Fx
+and Linux.
+.Sh HISTORY
+.Fn memmem
+first appeared in the Free Software Foundation's glibc library.
diff --git a/lib/nbsd_libc/string/memmem.c b/lib/nbsd_libc/string/memmem.c
new file mode 100644 (file)
index 0000000..ce49b17
--- /dev/null
@@ -0,0 +1,80 @@
+/*     $NetBSD: memmem.c,v 1.2 2008/04/28 20:23:00 martin Exp $        */
+
+/*-
+ * Copyright (c) 2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Perry E. Metzger of Metzger, Dowdeswell & Co. LLC.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: memmem.c,v 1.2 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <assert.h>
+#include <string.h>
+#else
+#include <lib/libkern/libkern.h>
+#define _DIAGASSERT(x) (void)0
+#define        NULL            ((void *)0)
+#endif
+
+void *
+memmem(const void *block, size_t blen, const void *pat, size_t plen)
+{
+       const unsigned char *bp, *pp, *endp;
+
+       _DIAGASSERT(block != NULL);
+       _DIAGASSERT(pat != NULL);
+
+       /*
+        * Following the precedent in ststr(3) and glibc, a zero
+        * length pattern matches the start of block.
+        */
+       if (plen == 0)
+               return __UNCONST(block);
+
+       if (blen < plen)
+               return NULL;
+
+       bp = block;
+       pp = pat;
+       endp = bp + (blen - plen) + 1;
+
+       /*
+        * As a cheezy optimization, check that the first chars are
+        * the same before calling memcmp. Really we should use bm(3)
+        * to speed this up if blen is large enough.
+        */
+       while (bp < endp) {
+               if ((*bp == *pp) && (memcmp(bp, pp, plen) == 0))
+                       return __UNCONST(bp);
+               bp++;
+       }
+
+       return NULL;
+}
diff --git a/lib/nbsd_libc/string/memmove.3 b/lib/nbsd_libc/string/memmove.3
new file mode 100644 (file)
index 0000000..3c60998
--- /dev/null
@@ -0,0 +1,74 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)memmove.3    8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: memmove.3,v 1.8 2003/08/07 16:43:48 agc Exp $
+.\"
+.Dd June 4, 1993
+.Dt MEMMOVE 3
+.Os
+.Sh NAME
+.Nm memmove
+.Nd copy byte string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft void *
+.Fn memmove "void *dst" "const void *src" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn memmove
+function
+copies
+.Fa len
+bytes from string
+.Fa src
+to string
+.Fa dst .
+The two strings may overlap;
+the copy is always done in a non-destructive manner.
+.Sh RETURN VALUES
+The
+.Fn memmove
+function returns the original value of
+.Fa dst .
+.Sh SEE ALSO
+.Xr bcopy 3 ,
+.Xr memccpy 3 ,
+.Xr memcpy 3 ,
+.Xr strcpy 3
+.Sh STANDARDS
+The
+.Fn memmove
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/string/memrchr.c b/lib/nbsd_libc/string/memrchr.c
new file mode 100644 (file)
index 0000000..92ef328
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: memrchr.c,v 1.2 2009/04/11 21:42:16 christos Exp $     */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: memrchr.c,v 1.2 2009/04/11 21:42:16 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <string.h>
+
+void *
+memrchr(const void *s, int c, size_t n)
+{
+       _DIAGASSERT(s != NULL);
+
+       if (n != 0) {
+               const unsigned char *p = (const unsigned char *)s + n;
+               const unsigned char cmp = c;
+
+               do {
+                       if (*--p == cmp)
+                               return __UNCONST(p);
+               } while (--n != 0);
+       }
+       return NULL;
+}
diff --git a/lib/nbsd_libc/string/memset.3 b/lib/nbsd_libc/string/memset.3
new file mode 100644 (file)
index 0000000..91f9d36
--- /dev/null
@@ -0,0 +1,71 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)memset.3     8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: memset.3,v 1.9 2003/08/07 16:43:49 agc Exp $
+.\"
+.Dd June 4, 1993
+.Dt MEMSET 3
+.Os
+.Sh NAME
+.Nm memset
+.Nd write a byte to byte string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft void *
+.Fn memset "void *b" "int c" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn memset
+function
+writes
+.Fa len
+bytes of value
+.Fa c
+(converted to an unsigned char) to the string
+.Fa b .
+.Sh RETURN VALUES
+The
+.Fn memset
+function
+returns the original value of
+.Fa b .
+.Sh SEE ALSO
+.Xr bzero 3 ,
+.Xr swab 3
+.Sh STANDARDS
+The
+.Fn memset
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/string/popcount.3 b/lib/nbsd_libc/string/popcount.3
new file mode 100644 (file)
index 0000000..3648960
--- /dev/null
@@ -0,0 +1,70 @@
+.\"    $NetBSD: popcount.3,v 1.4 2009/07/22 07:07:27 wiz Exp $
+.\"
+.\" Copyright (c) 2009 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Joerg Sonnenberger.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd July 13, 2009
+.Dt POPCOUNT 3
+.Os
+.Sh NAME
+.Nm popcount ,
+.Nm popcountl ,
+.Nm popcountll ,
+.Nm popcount32 ,
+.Nm popcount64
+.Nd count number of bits set in a bit string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In strings.h
+.Ft unsigned int
+.Fn popcount "unsigned int value"
+.Ft unsigned int
+.Fn popcountl "unsigned long value"
+.Ft unsigned int
+.Fn popcountll "unsigned long long value"
+.Ft unsigned int
+.Fn popcount32 "uint32_t value"
+.Ft unsigned int
+.Fn popcount64 "uint64_t value"
+.Sh DESCRIPTION
+The
+.Nm
+functions returns the number of bits set in
+.Fa value .
+.Sh SEE ALSO
+.Xr ffs 3
+.Sh HISTORY
+The
+.Fn popcount ,
+.Fn popcountl ,
+.Fn popcountll ,
+.Fn popcount32 ,
+and
+.Fn popcount64
+functions appeared in
+.Nx 6.0 .
diff --git a/lib/nbsd_libc/string/rindex.3 b/lib/nbsd_libc/string/rindex.3
new file mode 100644 (file)
index 0000000..f5f91fb
--- /dev/null
@@ -0,0 +1,97 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\" 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. 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.
+.\"
+.\"     from: @(#)rindex.3     8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: rindex.3,v 1.12 2010/04/29 06:54:26 jruoho Exp $
+.\"
+.Dd April 29, 2010
+.Dt RINDEX 3
+.Os
+.Sh NAME
+.Nm rindex
+.Nd locate character in string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In strings.h
+.Ft char *
+.Fn rindex "const char *s" "int c"
+.Sh DESCRIPTION
+The
+.Fn rindex
+function
+locates the last character
+matching
+.Fa c
+(converted to a
+.Em char )
+in the nul-terminated string
+.Fa s .
+.Sh RETURN VALUES
+A pointer to the character is returned if it is found; otherwise
+.Dv NULL
+is returned.
+If
+.Fa c
+is
+.Ql \e0 ,
+.Fn rindex
+locates the terminating
+.Ql \e0 .
+.Sh SEE ALSO
+.Xr index 3 ,
+.Xr memchr 3 ,
+.Xr strchr 3 ,
+.Xr strcspn 3 ,
+.Xr strpbrk 3 ,
+.Xr strrchr 3 ,
+.Xr strsep 3 ,
+.Xr strspn 3 ,
+.Xr strstr 3 ,
+.Xr strtok 3
+.Sh STANDARDS
+The
+.Fn rindex
+function conforms to
+.St -p1003.1-2001 .
+The
+.St -p1003.1-2004
+revision marked it as legacy and recommended the use of
+.Xr strrchr 3
+instead.
+The
+.St -p1003.1-2008
+revision removed
+.Fn rindex
+from the specification.
+.Sh HISTORY
+A
+.Fn rindex
+function appeared in
+.At v6 .
diff --git a/lib/nbsd_libc/string/rindex.c b/lib/nbsd_libc/string/rindex.c
new file mode 100644 (file)
index 0000000..1976d73
--- /dev/null
@@ -0,0 +1,3 @@
+/*     $NetBSD: rindex.c,v 1.15 2005/12/20 19:31:50 christos Exp $     */
+#define RINDEX
+#include "strrchr.c"
diff --git a/lib/nbsd_libc/string/stpcpy.c b/lib/nbsd_libc/string/stpcpy.c
new file mode 100644 (file)
index 0000000..13aa45a
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: stpcpy.c,v 1.1 2009/05/01 17:27:01 perry Exp $ */
+
+/*
+ * Copyright (c) 1999
+ *     David E. O'Brien
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strcpy.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: stpcpy.c,v 1.1 2009/05/01 17:27:01 perry Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+/* FreeBSD: src/lib/libc/string/stpcpy.c,v 1.2 2009/02/28 06:05:37 das Exp */
+
+#include <string.h>
+
+char *
+stpcpy(char * __restrict to, const char * __restrict from)
+{
+
+       for (; (*to = *from); ++from, ++to);
+       return(to);
+}
diff --git a/lib/nbsd_libc/string/stpncpy.c b/lib/nbsd_libc/string/stpncpy.c
new file mode 100644 (file)
index 0000000..b79d427
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: stpncpy.c,v 1.1 2009/05/01 17:27:01 perry Exp $        */
+
+/*-
+ * Copyright (c) 2009 David Schultz <das@FreeBSD.org>
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: stpncpy.c,v 1.1 2009/05/01 17:27:01 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+/* FreeBSD: src/lib/libc/string/stpncpy.c,v 1.1 2009/02/28 06:00:58 das Exp */
+
+#include <string.h>
+
+char *
+stpncpy(char * __restrict dst, const char * __restrict src, size_t n)
+{
+
+       for (; n--; dst++, src++) {
+               if (!(*dst = *src)) {
+                       char *ret = dst;
+                       while (n--)
+                               *++dst = '\0';
+                       return (ret);
+               }
+       }
+       return (dst);
+}
diff --git a/lib/nbsd_libc/string/strcasecmp.3 b/lib/nbsd_libc/string/strcasecmp.3
new file mode 100644 (file)
index 0000000..c38b2b5
--- /dev/null
@@ -0,0 +1,93 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\" 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. 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.
+.\"
+.\"     from: @(#)strcasecmp.3 8.1 (Berkeley) 6/9/93
+.\"    $NetBSD: strcasecmp.3,v 1.17 2006/10/16 08:48:45 wiz Exp $
+.\"
+.Dd June 9, 1993
+.Dt STRCASECMP 3
+.Os
+.Sh NAME
+.Nm strcasecmp ,
+.Nm strncasecmp
+.Nd compare strings, ignoring case
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In strings.h
+.Ft int
+.Fn strcasecmp "const char *s1" "const char *s2"
+.Ft int
+.Fn strncasecmp "const char *s1" "const char *s2" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn strcasecmp
+and
+.Fn strncasecmp
+functions
+compare the nul-terminated strings
+.Fa s1
+and
+.Fa s2
+and return an integer greater than, equal to, or less than 0,
+according to whether
+.Fa s1
+is lexicographically greater than, equal to, or less than
+.Fa s2
+after translation of each corresponding character to lower-case.
+The strings themselves are not modified.
+The comparison is done using unsigned characters, so that
+.Sq Li \e200
+is greater than
+.Ql \e0 .
+.Pp
+The
+.Fn strncasecmp
+compares at most
+.Fa len
+characters.
+.Sh SEE ALSO
+.Xr bcmp 3 ,
+.Xr memcmp 3 ,
+.Xr strcmp 3 ,
+.Xr strcoll 3 ,
+.Xr strxfrm 3
+.Sh HISTORY
+The
+.Fn strcasecmp
+and
+.Fn strncasecmp
+functions first appeared in
+.Bx 4.4 .
+.Sh NOTES
+If
+.Fa len
+is zero
+.Fn strncasecmp
+returns always 0.
diff --git a/lib/nbsd_libc/string/strcasestr.c b/lib/nbsd_libc/string/strcasestr.c
new file mode 100644 (file)
index 0000000..f8a9444
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: strcasestr.c,v 1.3 2005/11/29 03:12:00 christos Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: strcasestr.c,v 1.3 2005/11/29 03:12:00 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <assert.h>
+#include <ctype.h>
+#include <string.h>
+
+/*
+ * Find the first occurrence of find in s, ignore case.
+ */
+char *
+strcasestr(const char *s, const char *find)
+{
+       char c, sc;
+       size_t len;
+
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(find != NULL);
+
+       if ((c = *find++) != 0) {
+               c = tolower((unsigned char)c);
+               len = strlen(find);
+               do {
+                       do {
+                               if ((sc = *s++) == 0)
+                                       return (NULL);
+                       } while ((char)tolower((unsigned char)sc) != c);
+               } while (strncasecmp(s, find, len) != 0);
+               s--;
+       }
+       return __UNCONST(s);
+}
diff --git a/lib/nbsd_libc/string/strcat.3 b/lib/nbsd_libc/string/strcat.3
new file mode 100644 (file)
index 0000000..046b2ee
--- /dev/null
@@ -0,0 +1,138 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strcat.3     8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: strcat.3,v 1.16 2006/10/16 08:48:45 wiz Exp $
+.\"
+.Dd August 11, 2002
+.Dt STRCAT 3
+.Os
+.Sh NAME
+.Nm strcat ,
+.Nm strncat
+.Nd concatenate strings
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft char *
+.Fn strcat "char * restrict s" "const char * restrict append"
+.Ft char *
+.Fn strncat "char * restrict s" "const char * restrict append" "size_t count"
+.Sh DESCRIPTION
+The
+.Fn strcat
+and
+.Fn strncat
+functions
+append a copy of the nul-terminated string
+.Fa append
+to the end of the nul-terminated string
+.Fa s ,
+then add a terminating
+.Ql \e0 .
+The string
+.Fa s
+must have sufficient space to hold the result.
+.Pp
+The
+.Fn strncat
+function
+appends not more than
+.Fa count
+characters where space for the terminating
+.Ql \e0
+should not be included in
+.Fa count .
+.Sh RETURN VALUES
+The
+.Fn strcat
+and
+.Fn strncat
+functions
+return the pointer
+.Fa s .
+.Sh EXAMPLES
+The following appends
+.Dq Li abc
+to
+.Dq Li chararray :
+.Bd -literal -offset indent
+char *letters = "abcdefghi";
+
+(void)strncat(chararray, letters, 3);
+.Ed
+.Pp
+The following example shows how to use
+.Fn strncat
+safely in conjunction with
+.Xr strncpy 3 .
+.Bd -literal -offset indent
+char buf[BUFSIZ];
+char *input, *suffix;
+
+(void)strncpy(buf, input, sizeof(buf) - 1);
+buf[sizeof(buf) - 1] = '\e0';
+(void)strncat(buf, suffix, sizeof(buf) - 1 - strlen(buf));
+.Ed
+.Pp
+The above will copy as many characters from
+.Dq Li input
+to
+.Dq Li buf
+as will fit.
+It then appends as many characters from suffix as will fit (or none
+if there is no space).
+For operations like this, the
+.Xr strlcpy 3
+and
+.Xr strlcat 3
+functions are a better choice, as shown below.
+.Bd -literal -offset indent
+(void)strlcpy(buf, input, sizeof(buf));
+(void)strlcat(buf, suffix, sizeof(buf));
+.Ed
+.Sh SEE ALSO
+.Xr bcopy 3 ,
+.Xr memccpy 3 ,
+.Xr memcpy 3 ,
+.Xr memmove 3 ,
+.Xr strcpy 3 ,
+.Xr strlcat 3 ,
+.Xr strlcpy 3
+.Sh STANDARDS
+The
+.Fn strcat
+and
+.Fn strncat
+functions
+conform to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/string/strchr.3 b/lib/nbsd_libc/string/strchr.3
new file mode 100644 (file)
index 0000000..0ebf60d
--- /dev/null
@@ -0,0 +1,98 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strchr.3     8.2 (Berkeley) 4/19/94
+.\"    $NetBSD: strchr.3,v 1.11 2003/08/07 16:43:49 agc Exp $
+.\"
+.Dd August 11, 2002
+.Dt STRCHR 3
+.Os
+.Sh NAME
+.Nm strchr
+.Nd locate character in string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft char *
+.Fn strchr "const char *s" "int c"
+.Sh DESCRIPTION
+The
+.Fn strchr
+function locates the first occurrence of
+.Ar c
+in the string pointed to by
+.Ar s .
+The terminating
+.Dv NUL
+character is considered part of the string.
+If
+.Fa c
+is
+.Ql \e0 ,
+.Fn strchr
+locates the terminating
+.Ql \e0 .
+.Sh RETURN VALUES
+The function
+.Fn strchr
+returns a pointer to the located character, or
+.Dv NULL
+if the character does not appear in the string.
+.Sh EXAMPLES
+After the following call to
+.Fn strchr ,
+.Va p
+will point to the string
+.Qq oobar :
+.Bd -literal -offset indent
+char *p;
+char *s = "foobar";
+
+p = strchr(s, 'o');
+.Ed
+.Sh SEE ALSO
+.Xr index 3 ,
+.Xr memchr 3 ,
+.Xr rindex 3 ,
+.Xr strcspn 3 ,
+.Xr strpbrk 3 ,
+.Xr strrchr 3 ,
+.Xr strsep 3 ,
+.Xr strspn 3 ,
+.Xr strstr 3 ,
+.Xr strtok 3
+.Sh STANDARDS
+The
+.Fn strchr
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/string/strcmp.3 b/lib/nbsd_libc/string/strcmp.3
new file mode 100644 (file)
index 0000000..bcafe26
--- /dev/null
@@ -0,0 +1,99 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strcmp.3     8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: strcmp.3,v 1.13 2006/10/16 08:48:45 wiz Exp $
+.\"
+.Dd June 4, 1993
+.Dt STRCMP 3
+.Os
+.Sh NAME
+.Nm strcmp ,
+.Nm strncmp
+.Nd compare strings
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft int
+.Fn strcmp "const char *s1" "const char *s2"
+.Ft int
+.Fn strncmp "const char *s1" "const char *s2" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn strcmp
+and
+.Fn strncmp
+functions
+lexicographically compare the nul-terminated strings
+.Fa s1
+and
+.Fa s2 .
+.Sh RETURN VALUES
+The
+.Fn strcmp
+and
+.Fn strncmp
+return an integer greater than, equal to, or less than 0, according
+to whether the string
+.Fa s1
+is greater than, equal to, or less than the string
+.Fa s2 .
+The comparison is done using unsigned characters, so that
+.Ql \e200
+is greater than
+.Ql \e0 .
+.Pp
+The
+.Fn strncmp
+compares not more than
+.Fa len
+characters.
+.Sh SEE ALSO
+.Xr bcmp 3 ,
+.Xr memcmp 3 ,
+.Xr strcasecmp 3 ,
+.Xr strcoll 3 ,
+.Xr strxfrm 3
+.Sh STANDARDS
+The
+.Fn strcmp
+and
+.Fn strncmp
+functions
+conform to
+.St -ansiC .
+.Sh NOTES
+If
+.Fa len
+is zero
+.Fn strncmp
+returns always 0.
diff --git a/lib/nbsd_libc/string/strcoll.3 b/lib/nbsd_libc/string/strcoll.3
new file mode 100644 (file)
index 0000000..79cfb13
--- /dev/null
@@ -0,0 +1,73 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strcoll.3    8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: strcoll.3,v 1.10 2006/10/16 08:48:45 wiz Exp $
+.\"
+.Dd June 4, 1993
+.Dt STRCOLL 3
+.Os
+.Sh NAME
+.Nm strcoll
+.Nd compare strings according to current collation
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft int
+.Fn strcoll "const char *s1" "const char *s2"
+.Sh DESCRIPTION
+The
+.Fn strcoll
+function
+lexicographically compares the nul-terminated strings
+.Fa s1
+and
+.Fa s2
+according to the current locale collation
+and returns an integer greater than, equal to, or less than 0,
+according to whether
+.Fa s1
+is greater than, equal to, or less than
+.Fa s2 .
+.Sh SEE ALSO
+.Xr bcmp 3 ,
+.Xr memcmp 3 ,
+.Xr setlocale 3 ,
+.Xr strcasecmp 3 ,
+.Xr strcmp 3 ,
+.Xr strxfrm 3
+.Sh STANDARDS
+The
+.Fn strcoll
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/string/strcoll.c b/lib/nbsd_libc/string/strcoll.c
new file mode 100644 (file)
index 0000000..1feda44
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: strcoll.c,v 1.9 2003/08/07 16:43:50 agc Exp $  */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strcoll.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strcoll.c,v 1.9 2003/08/07 16:43:50 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <string.h>
+
+/*
+ * Compare strings according to LC_COLLATE category of current locale.
+ */
+int
+strcoll(s1, s2)
+       const char *s1, *s2;
+{
+
+       _DIAGASSERT(s1 != NULL);
+       _DIAGASSERT(s2 != NULL);
+
+       /* LC_COLLATE is unimplemented, hence always "C" */
+       return (strcmp(s1, s2));
+}
diff --git a/lib/nbsd_libc/string/strcpy.3 b/lib/nbsd_libc/string/strcpy.3
new file mode 100644 (file)
index 0000000..daa7b10
--- /dev/null
@@ -0,0 +1,220 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strcpy.3     8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: strcpy.3,v 1.20 2009/05/02 09:37:32 wiz Exp $
+.\"
+.Dd May 1, 2009
+.Dt STRCPY 3
+.Os
+.Sh NAME
+.Nm stpcpy ,
+.Nm stpncpy ,
+.Nm strcpy ,
+.Nm strncpy
+.Nd copy strings
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft char *
+.Fn stpcpy "char * restrict dst" "const char * restrict src"
+.Ft char *
+.Fn stpncpy "char * restrict dst" "const char * restrict src" "size_t len"
+.Ft char *
+.Fn strcpy "char * restrict dst" "const char * restrict src"
+.Ft char *
+.Fn strncpy "char * restrict dst" "const char * restrict src" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn stpcpy
+and
+.Fn strcpy
+functions
+copy the string
+.Fa src
+to
+.Fa dst
+(including the terminating
+.Ql \e0
+character).
+.Pp
+The
+.Fn stpncpy
+and
+.Fn strncpy
+functions copy at most
+.Fa len
+characters from
+.Fa src
+into
+.Fa dst .
+If
+.Fa src
+is less than
+.Fa len
+characters long,
+the remainder of
+.Fa dst
+is filled with
+.Ql \e0
+characters.
+Otherwise,
+.Fa dst
+is
+.Em not
+terminated.
+.Sh RETURN VALUES
+The
+.Fn strcpy
+and
+.Fn strncpy
+functions
+return
+.Fa dst .
+The
+.Fn stpcpy
+and
+.Fn stpncpy
+functions return a pointer to the terminating
+.Ql \e0
+character of
+.Fa dst .
+If
+.Fn stpncpy
+does not terminate
+.Fa dst
+with a
+.Dv NUL
+character, it instead returns a pointer to
+.Li dst[len]
+(which does not necessarily refer to a valid memory location.)
+.Sh EXAMPLES
+The following sets
+.Va chararray
+to
+.Dq Li abc\e0\e0\e0 :
+.Bd -literal -offset indent
+char chararray[6];
+
+(void)strncpy(chararray, "abc", sizeof(chararray));
+.Ed
+.Pp
+The following sets
+.Va chararray
+to
+.Dq Li abcdef :
+.Bd -literal -offset indent
+char chararray[6];
+
+(void)strncpy(chararray, "abcdefgh", sizeof(chararray));
+.Ed
+.Pp
+Note that it does
+.Em not
+.Dv NUL Ns No -terminate
+.Va chararray
+because the length of the source string is greater than or equal
+to the length parameter.
+.Fn strncpy
+.Em only
+.Dv NUL Ns No -terminates
+the destination string when the length of the source
+string is less than the length parameter.
+.Pp
+The following copies as many characters from
+.Va input
+to
+.Va buf
+as will fit and
+.Dv NUL Ns No -terminates
+the result.
+Because
+.Fn strncpy
+does
+.Em not
+guarantee to
+.Dv NUL Ns No -terminate
+the string itself, this must be done explicitly.
+.Bd -literal -offset indent
+char buf[1024];
+
+(void)strncpy(buf, input, sizeof(buf) - 1);
+buf[sizeof(buf) - 1] = '\e0';
+.Ed
+.Pp
+This could be better and more simply achieved using
+.Xr strlcpy 3 ,
+as shown in the following example:
+.Bd -literal -offset indent
+(void)strlcpy(buf, input, sizeof(buf));
+.Ed
+.Pp
+Note that because
+.Xr strlcpy 3
+is not defined in any standards, it should
+only be used when portability is not a concern.
+.Sh SEE ALSO
+.Xr bcopy 3 ,
+.Xr memccpy 3 ,
+.Xr memcpy 3 ,
+.Xr memmove 3 ,
+.Xr strlcpy 3 ,
+.Xr wcscpy 3
+.Sh STANDARDS
+The
+.Fn strcpy
+and
+.Fn strncpy
+functions
+conform to
+.St -isoC-99 .
+The
+.Fn stpcpy
+and
+.Fn stpncpy
+functions conform to
+.St -p1003.1-2008 .
+.Sh HISTORY
+The
+.Fn stpcpy
+and
+.Fn stpncpy
+functions first appeared in
+.Nx 6.0 .
+.Sh SECURITY CONSIDERATIONS
+The
+.Fn strcpy
+and
+.Fn stpcpy
+functions are easily misused in a manner which enables malicious users
+to arbitrarily change a running program's functionality through a
+buffer overflow attack.
diff --git a/lib/nbsd_libc/string/strcspn.3 b/lib/nbsd_libc/string/strcspn.3
new file mode 100644 (file)
index 0000000..3f53015
--- /dev/null
@@ -0,0 +1,97 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strcspn.3    8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: strcspn.3,v 1.10 2006/10/16 08:48:45 wiz Exp $
+.\"
+.Dd August 11, 2002
+.Dt STRCSPN 3
+.Os
+.Sh NAME
+.Nm strcspn
+.Nd span the complement of a string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft size_t
+.Fn strcspn "const char *s" "const char *charset"
+.Sh DESCRIPTION
+The
+.Fn strcspn
+function
+spans the initial part of the nul-terminated string
+.Fa s
+as long as the characters from
+.Fa s
+do not occur in string
+.Fa charset
+(it
+spans the
+.Em complement
+of
+.Fa charset ) .
+.Sh RETURN VALUES
+The
+.Fn strcspn
+function
+returns the number of characters spanned.
+.Sh EXAMPLES
+The following call to
+.Fn strcspn
+will return 3, since the first three characters of string
+.Fa s
+do not occur in string
+.Fa charset :
+.Bd -literal -offset indent
+char *s = "foobar";
+char *charset = "bar";
+size_t span;
+
+span = strcspn(s, charset);
+.Ed
+.Sh SEE ALSO
+.Xr index 3 ,
+.Xr memchr 3 ,
+.Xr rindex 3 ,
+.Xr strchr 3 ,
+.Xr strpbrk 3 ,
+.Xr strrchr 3 ,
+.Xr strsep 3 ,
+.Xr strspn 3 ,
+.Xr strstr 3 ,
+.Xr strtok 3
+.Sh STANDARDS
+The
+.Fn strcspn
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/string/strcspn.c b/lib/nbsd_libc/string/strcspn.c
new file mode 100644 (file)
index 0000000..cc40093
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: strcspn.c,v 1.17 2009/07/30 21:42:06 dsl Exp $ */
+
+/*-
+ * Copyright (c) 2008 Joerg Sonnenberger
+ * 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(S) ``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(S) 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 <sys/cdefs.h>
+__RCSID("$NetBSD: strcspn.c,v 1.17 2009/07/30 21:42:06 dsl Exp $");
+
+#include <assert.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <string.h>
+
+/* 64bit version is in strspn.c */
+#if ULONG_MAX != 0xffffffffffffffffull
+
+size_t
+strcspn(const char *s, const char *charset)
+{
+       static const size_t idx[8] = { 1, 2, 4, 8, 16, 32, 64, 128 };
+       const char *t;
+       uint8_t set[32];
+#define UC(a) ((unsigned int)(unsigned char)(a))
+
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(charset != NULL);
+
+       if (charset[0] == '\0')
+               return strlen(s);
+       if (charset[1] == '\0') {
+               for (t = s; *t != '\0'; ++t)
+                       if (*t == *charset)
+                               break;
+               return t - s;
+       }
+
+       (void)memset(set, 0, sizeof(set));
+
+       for (; *charset != '\0'; ++charset)
+               set[UC(*charset) >> 3] |= idx[UC(*charset) & 7];
+
+       for (t = s; *t != '\0'; ++t)
+               if (set[UC(*t) >> 3] & idx[UC(*t) & 7])
+                       break;
+       return t - s;
+}
+
+#endif
diff --git a/lib/nbsd_libc/string/strdup.3 b/lib/nbsd_libc/string/strdup.3
new file mode 100644 (file)
index 0000000..baab9a6
--- /dev/null
@@ -0,0 +1,109 @@
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)strdup.3     8.1 (Berkeley) 6/9/93
+.\"    $NetBSD: strdup.3,v 1.18 2009/01/29 10:15:39 wiz Exp $
+.\"
+.Dd January 28, 2009
+.Dt STRDUP 3
+.Os
+.Sh NAME
+.Nm strdup ,
+.Nm strndup
+.Nd save a copy of a string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft char *
+.Fn strdup "const char *str"
+.Ft char *
+.Fn strndup "const char *str" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn strdup
+function
+allocates sufficient memory for a copy
+of the string
+.Fa str ,
+does the copy, and returns a pointer to it.
+The pointer may subsequently be used as an
+argument to the function
+.Xr free 3 .
+.Pp
+If insufficient memory is available,
+.Dv NULL
+is returned.
+.Pp
+The
+.Fn strndup
+function copies at most
+.Fa len
+characters from the string
+.Fa str
+always
+.Dv NUL
+terminating the copied string.
+.Sh EXAMPLES
+The following will point
+.Va p
+to an allocated area of memory containing the nul-terminated string
+.Qq foobar :
+.Bd -literal -offset indent
+char *p;
+
+if ((p = strdup("foobar")) == NULL) {
+       fprintf(stderr, "Out of memory.\en");
+       exit(1);
+}
+.Ed
+.Sh ERRORS
+The
+.Fn strdup
+function may fail and set the external variable
+.Va errno
+for any of the errors specified for the library function
+.Xr malloc 3 .
+.Sh SEE ALSO
+.Xr free 3 ,
+.Xr malloc 3 ,
+.Xr strcpy 3 ,
+.Xr strlen 3
+.Sh STANDARDS
+The
+.Fn strdup
+function conforms to
+.St -p1003.1-2001 .
+.Sh HISTORY
+The
+.Fn strdup
+function first appeared in
+.Bx 4.4 .
+The
+.Fn strndup
+function was added in
+.Nx 4.0 .
diff --git a/lib/nbsd_libc/string/strdup.c b/lib/nbsd_libc/string/strdup.c
new file mode 100644 (file)
index 0000000..b56e272
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: strdup.c,v 1.13 2003/08/07 16:43:50 agc Exp $  */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strdup.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strdup.c,v 1.13 2003/08/07 16:43:50 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(strdup,_strdup)
+#endif
+
+char *
+strdup(str)
+       const char *str;
+{
+       size_t len;
+       char *copy;
+
+       _DIAGASSERT(str != NULL);
+
+       len = strlen(str) + 1;
+       if (!(copy = malloc(len)))
+               return (NULL);
+       memcpy(copy, str, len);
+       return (copy);
+}
diff --git a/lib/nbsd_libc/string/strerror.3 b/lib/nbsd_libc/string/strerror.3
new file mode 100644 (file)
index 0000000..7c309b4
--- /dev/null
@@ -0,0 +1,197 @@
+.\" $NetBSD: strerror.3,v 1.17 2010/10/25 07:37:11 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     @(#)strerror.3 8.1 (Berkeley) 6/9/93
+.Dd October 24, 2010
+.Dt STRERROR 3
+.Os
+.Sh NAME
+.Nm perror ,
+.Nm strerror ,
+.Nm strerror_r ,
+.Nm sys_errlist ,
+.Nm sys_nerr
+.Nd system error messages
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft void
+.Fn perror "const char *string"
+.In errno.h
+.Vt extern const char * const sys_errlist[] ;
+.Vt extern const int sys_nerr ;
+.In string.h
+.Ft "char *"
+.Fn strerror "int errnum"
+.Ft int
+.Fn strerror_r "int errnum" "char *strerrbuf" "size_t buflen"
+.Sh DESCRIPTION
+The
+.Fn strerror ,
+.Fn strerror_r ,
+and
+.Fn perror
+functions look up the language-dependent error message
+string corresponding to an error number.
+.Pp
+The
+.Fn strerror
+function accepts an error number argument
+.Fa errnum
+and returns a pointer to the corresponding
+message string.
+.Pp
+The
+.Fn strerror_r
+function renders the same result into
+.Fa strerrbuf
+for a maximum of
+.Fa buflen
+characters and returns 0 upon success.
+.Pp
+The
+.Fn perror
+function finds the error message corresponding to the current
+value of the global variable
+.Va errno
+.Pq Xr intro 2
+and writes it, followed by a newline, to the
+standard error file descriptor.
+If the argument
+.Fa string
+is
+.Pf non- Dv NULL
+and does not point to the nul character,
+this string is prepended to the message
+string and separated from it by
+a colon and space
+.Pq Dq Li ":\ " ;
+otherwise, only the error message string is printed.
+Note that in most cases the
+.Xr err 3
+and
+.Xr warn 3
+family of functions is preferable to
+.Fn perror ;
+they are more flexible and also print the program name.
+.Pp
+If the error number is not recognized, these functions pass an error message
+string containing
+.Dq Li "Unknown error:\ "
+followed by the error number in decimal.
+To warn about this,
+.Fn strerror
+sets
+.Dv errno
+to
+.Er EINVAL ,
+and
+.Fn strerror_r
+returns
+.Er EINVAL .
+Error numbers recognized by this implementation fall in
+the range 0 \*[Lt]
+.Fa errnum
+\*[Lt]
+.Fa sys_nerr .
+.Pp
+If insufficient storage is provided in
+.Fa strerrbuf
+(as specified in
+.Fa buflen )
+to contain the error string,
+.Fn strerror_r
+returns
+.Er ERANGE
+and
+.Fa strerrbuf
+will contain an error message that has been truncated and
+.Dv NUL
+terminated to fit the length specified by
+.Fa buflen .
+.Pp
+The message strings can be accessed directly using the external
+array
+.Va sys_errlist .
+The external value
+.Va sys_nerr
+contains a count of the messages in
+.Va sys_errlist .
+The use of these variables is deprecated;
+.Fn strerror
+or
+.Fn strerror_r
+should be used instead.
+.Sh SEE ALSO
+.Xr intro 2 ,
+.Xr err 3 ,
+.Xr psignal 3 ,
+.Xr warn 3
+.Sh STANDARDS
+The
+.Fn perror
+and
+.Fn strerror
+functions conform to
+.St -isoC-99 .
+The
+.Fn strerror_r
+function conforms to
+.St -p1003.1-2001 .
+.Sh HISTORY
+The
+.Fn strerror
+and
+.Fn perror
+functions first appeared in
+.Bx 4.4 .
+The
+.Fn strerror_r
+function first appeared in
+.Nx 4.0 .
+.Sh BUGS
+For unknown error numbers, the
+.Fn strerror
+function will return its result in a static buffer which
+may be overwritten by subsequent calls.
+.Pp
+The return type for
+.Fn strerror
+is missing a type-qualifier; it should actually be
+.Vt const char * .
+.Pp
+Programs that use the deprecated
+.Va sys_errlist
+variable often fail to compile because they declare it
+inconsistently.
diff --git a/lib/nbsd_libc/string/strerror.c b/lib/nbsd_libc/string/strerror.c
new file mode 100644 (file)
index 0000000..99e2bd1
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: strerror.c,v 1.14 2006/01/26 11:13:42 kleink Exp $     */
+
+/*
+ * Copyright (c) 1988 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)strerror.c  5.6 (Berkeley) 5/4/91";
+#else
+__RCSID("$NetBSD: strerror.c,v 1.14 2006/01/26 11:13:42 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <string.h>
+#include <limits.h>
+#include <errno.h>
+#include "extern.h"
+
+/*
+ * Since perror() is not allowed to change the contents of strerror()'s
+ * static buffer, both functions supply their own buffers to strerror_r()
+ */
+
+__aconst char *
+strerror(int num)
+{
+       static char buf[NL_TEXTMAX];
+       int error = strerror_r(num, buf, sizeof(buf));
+       if (error)
+               errno = error;
+       return buf;
+}
diff --git a/lib/nbsd_libc/string/strerror_r.c b/lib/nbsd_libc/string/strerror_r.c
new file mode 100644 (file)
index 0000000..a900036
--- /dev/null
@@ -0,0 +1,103 @@
+/*     $NetBSD: strerror_r.c,v 1.2 2005/07/30 15:21:21 christos Exp $  */
+
+/*
+ * Copyright (c) 1988 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)strerror.c  5.6 (Berkeley) 5/4/91";
+#else
+__RCSID("$NetBSD: strerror_r.c,v 1.2 2005/07/30 15:21:21 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#ifdef NLS
+#include <limits.h>
+#include <nl_types.h>
+#endif
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include "extern.h"
+
+#ifdef _LIBC
+# ifdef __weak_alias
+__weak_alias(strerror_r, _strerror_r)
+# endif
+#endif
+
+int
+#ifdef _LIBC
+_strerror_r(int num, char *buf, size_t buflen)
+#else
+strerror_r(int num, char *buf, size_t buflen)
+#endif
+{
+#define        UPREFIX "Unknown error: %u"
+       unsigned int errnum = num;
+       int retval = 0;
+       size_t slen;
+#ifdef NLS
+       int saved_errno = errno;
+       nl_catd catd;
+       catd = catopen("libc", NL_CAT_LOCALE);
+#endif
+       _DIAGASSERT(buf != NULL);
+
+       if (errnum < (unsigned int) sys_nerr) {
+#ifdef NLS
+               slen = strlcpy(buf, catgets(catd, 1, (int)errnum,
+                   sys_errlist[errnum]), buflen); 
+#else
+               slen = strlcpy(buf, sys_errlist[errnum], buflen); 
+#endif
+       } else {
+#ifdef NLS
+               slen = snprintf(buf, buflen, 
+                   catgets(catd, 1, 0xffff, UPREFIX), errnum);
+#else
+               slen = snprintf(buf, buflen, UPREFIX, errnum);
+#endif
+               retval = EINVAL;
+       }
+
+       if (slen >= buflen)
+               retval = ERANGE;
+
+#ifdef NLS
+       catclose(catd);
+       errno = saved_errno;
+#endif
+
+       return retval;
+}
diff --git a/lib/nbsd_libc/string/stresep.c b/lib/nbsd_libc/string/stresep.c
new file mode 100644 (file)
index 0000000..34946d4
--- /dev/null
@@ -0,0 +1,94 @@
+/*     $NetBSD: stresep.c,v 1.2 2007/12/06 22:07:07 seb Exp $  */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strsep.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: stresep.c,v 1.2 2007/12/06 22:07:07 seb Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(stresep,_stresep)
+#endif
+
+/*
+ * Get next token from string *stringp, where tokens are possibly-empty
+ * strings separated by characters from delim. If esc is not NUL, then
+ * the characters followed by esc are ignored and are not taken into account
+ * when splitting the string.
+ *
+ * Writes NULs into the string at *stringp to end tokens.
+ * delim need not remain constant from call to call.
+ * On return, *stringp points past the last NUL written (if there might
+ * be further tokens), or is NULL (if there are definitely no more tokens).
+ *
+ * If *stringp is NULL, stresep returns NULL.
+ */
+char *
+stresep(char **stringp, const char *delim, int esc)
+{
+       char *s;
+       const char *spanp;
+       int c, sc;
+       char *tok;
+
+       _DIAGASSERT(stringp != NULL);
+       _DIAGASSERT(delim != NULL);
+
+       if ((s = *stringp) == NULL)
+               return NULL;
+       for (tok = s;;) {
+               c = *s++;
+               while (esc != '\0' && c == esc) {
+                       (void)strcpy(s - 1, s);
+                       c = *s++;
+               }
+               spanp = delim;
+               do {
+                       if ((sc = *spanp++) == c) {
+                               if (c == 0)
+                                       s = NULL;
+                               else
+                                       s[-1] = 0;
+                               *stringp = s;
+                               return tok;
+                       }
+               } while (sc != 0);
+       }
+}
diff --git a/lib/nbsd_libc/string/string.3 b/lib/nbsd_libc/string/string.3
new file mode 100644 (file)
index 0000000..a05a76e
--- /dev/null
@@ -0,0 +1,200 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\" 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. 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.
+.\"
+.\"     from: @(#)string.3     8.2 (Berkeley) 12/11/93
+.\"    $NetBSD: string.3,v 1.16 2009/05/01 17:27:01 perry Exp $
+.\"
+.Dd May 1, 2009
+.Dt STRING 3
+.Os
+.Sh NAME
+.Nm stpcpy ,
+.Nm stpncpy ,
+.Nm strcat ,
+.Nm strlcat ,
+.Nm strncat ,
+.Nm strchr ,
+.Nm strrchr ,
+.Nm strcmp ,
+.Nm strncmp ,
+.Nm strcasecmp ,
+.Nm strncasecmp ,
+.Nm strcoll ,
+.Nm strcpy ,
+.Nm strlcpy ,
+.Nm strncpy ,
+.Nm strerror ,
+.Nm strerror_r ,
+.Nm strlen ,
+.Nm strnlen ,
+.Nm strpbrk ,
+.Nm strsep ,
+.Nm stresep ,
+.Nm strspn ,
+.Nm strcspn ,
+.Nm strdup ,
+.Nm strndup ,
+.Nm strstr ,
+.Nm strcasestr ,
+.Nm strtok ,
+.Nm strtok_r ,
+.Nm strxfrm
+.Nd string specific functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft char *
+.Fn stpcpy "char *dst" "const char *src"
+.Ft char *
+.Fn stpncpy "char *dst" "const char *src" "size_t count"
+.Ft char *
+.Fn strcat "char *s" "const char * append"
+.Ft size_t
+.Fn strlcat "char *dst" "const char *src" "size_t size"
+.Ft char *
+.Fn strncat "char *s" "const char *append" "size_t count"
+.Ft char *
+.Fn strchr "const char *s" "int c"
+.Ft char *
+.Fn strrchr "const char *s" "int c"
+.Ft int
+.Fn strcmp "const char *s1" "const char *s2"
+.Ft int
+.Fn strncmp "const char *s1" "const char *s2" "size_t count"
+.Ft int
+.Fn strcasecmp "const char *s1" "const char *s2"
+.Ft int
+.Fn strncasecmp "const char *s1" "const char *s2" "size_t count"
+.Ft int
+.Fn strcoll "const char *s1" "const char *s2"
+.Ft char *
+.Fn strcpy "char *dst" "const char *src"
+.Ft size_t
+.Fn strlcpy "char *dst" "const char *src" "size_t size"
+.Ft char *
+.Fn strncpy "char *dst" "const char *src" "size_t count"
+.Ft char *
+.Fn strerror "int errno"
+.Ft int
+.Fn strerror_r "int errnum" "char *strerrbuf" "size_t buflen"
+.Ft size_t
+.Fn strlen "const char *s"
+.Ft size_t
+.Fn strnlen "const char *s" "size_t count"
+.Ft char *
+.Fn strpbrk "const char *s" "const char *charset"
+.Ft char *
+.Fn strsep "char **stringp" "const char *delim"
+.Ft char *
+.Fn stresep "char **stringp" "const char *delim" "int escape"
+.Ft size_t
+.Fn strspn "const char *s" "const char *charset"
+.Ft size_t
+.Fn strcspn "const char *s" "const char *charset"
+.Ft char *
+.Fn strdup "const char *str"
+.Ft char *
+.Fn strndup "const char *str" "size_t len"
+.Ft char *
+.Fn strstr "const char *big" "const char *little"
+.Ft char *
+.Fn strcasestr "const char *big" "const char *little"
+.Ft char *
+.Fn strtok "char *s" "const char *delim"
+.Ft char *
+.Fn strtok_r "char *s" "const char *delim" "char **lasts"
+.Ft size_t
+.Fn strxfrm "char *dst" "const char *src" "size_t n"
+.Sh DESCRIPTION
+The string
+functions manipulate strings terminated by a
+nul byte.
+.Pp
+See the specific manual pages for more information.
+For manipulating variable length generic objects as byte
+strings (without the nul byte check), see
+.Xr bstring 3 .
+.Pp
+Except as noted in their specific manual pages,
+the string functions do not test the destination
+for size limitations.
+.Sh SEE ALSO
+.Xr bstring 3 ,
+.Xr strcat 3 ,
+.Xr strchr 3 ,
+.Xr strcmp 3 ,
+.Xr strcoll 3 ,
+.Xr strcpy 3 ,
+.Xr strcspn 3 ,
+.Xr strdup 3 ,
+.Xr strerror 3 ,
+.Xr strings 3 ,
+.Xr strlcat 3 ,
+.Xr strlen 3 ,
+.Xr strpbrk 3 ,
+.Xr strrchr 3 ,
+.Xr strsep 3 ,
+.Xr strspn 3 ,
+.Xr strstr 3 ,
+.Xr strtok 3 ,
+.Xr strxfrm 3
+.Sh STANDARDS
+The
+.Fn strcat ,
+.Fn strncat ,
+.Fn strchr ,
+.Fn strrchr ,
+.Fn strcmp ,
+.Fn strncmp ,
+.Fn strcpy ,
+.Fn strncpy ,
+.Fn strcoll ,
+.Fn strerror ,
+.Fn strlen ,
+.Fn strpbrk ,
+.Fn strsep ,
+.Fn strspn ,
+.Fn strcspn ,
+.Fn strstr ,
+.Fn strtok ,
+and
+.Fn strxfrm
+functions conform to
+.St -ansiC .
+.Pp
+The
+.Fn strtok_r
+function conforms to
+.St -p1003.1c-95 .
+.Pp
+The
+.Fn strerror_r
+function conform to
+.St -p1003.1-2001 .
diff --git a/lib/nbsd_libc/string/strings.3 b/lib/nbsd_libc/string/strings.3
new file mode 100644 (file)
index 0000000..8ce6b98
--- /dev/null
@@ -0,0 +1,98 @@
+.\" $NetBSD: strings.3,v 1.1 2007/02/17 09:32:58 wiz Exp $
+.\"
+.\" Copyright (c) 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Thomas Klausner.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd February 17, 2007
+.Dt STRINGS 3
+.Os
+.Sh NAME
+.Nm bcmp ,
+.Nm bcopy ,
+.Nm bzero ,
+.Nm ffs ,
+.Nm index ,
+.Nm rindex ,
+.Nm strcasecmp ,
+.Nm strncasecmp
+.Nd string operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In strings.h
+.Ft int
+.Fn bcmp "const void *b1" "const void *b2" "size_t len"
+.Ft void
+.Fn bcopy "const void *src" "void *dst" "size_t len"
+.Ft void
+.Fn bzero "void *b" "size_t len"
+.Ft int
+.Fn ffs "int value"
+.Ft char *
+.Fn index "const char *s" "int c"
+.Ft char *
+.Fn rindex "const char *s" "int c"
+.Ft int
+.Fn strcasecmp "const char *s1" "const char *s2"
+.Ft int
+.Fn strncasecmp "const char *s1" "const char *s2" "size_t len"
+.Sh DESCRIPTION
+These functions all live in the
+.Pa strings.h
+header file.
+Except for
+.Fn ffs ,
+they operate on strings.
+.Fn index ,
+.Fn rindex ,
+and
+.Fn strcasecmp
+need nul-terminated strings.
+.Pp
+See the specific manual pages for more information.
+.Pp
+See
+.Xr string 3
+for string functions that follow
+.St -ansiC
+or
+.St -isoC-99 ,
+.Xr bstring 3
+for functions that operate on strings that are not nul-terminated, and
+.Xr bitstring 3
+for bit-string manipulation macros.
+.Sh SEE ALSO
+.Xr bcmp 3 ,
+.Xr bcopy 3 ,
+.Xr bitstring 3 ,
+.Xr bstring 3 ,
+.Xr bzero 3 ,
+.Xr ffs 3 ,
+.Xr index 3 ,
+.Xr rindex 3 ,
+.Xr strcasecmp 3 ,
+.Xr string 3
diff --git a/lib/nbsd_libc/string/strlcpy.3 b/lib/nbsd_libc/string/strlcpy.3
new file mode 100644 (file)
index 0000000..c479459
--- /dev/null
@@ -0,0 +1,212 @@
+.\"    $NetBSD: strlcpy.3,v 1.13 2010/04/14 13:07:51 wiz Exp $
+.\" from OpenBSD: strlcpy.3,v 1.11 2000/11/16 23:27:41 angelos Exp
+.\"
+.\" Copyright (c) 1998, 2000 Todd C. Miller <Todd.Miller@courtesan.com>
+.\" 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.
+.\" 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 ``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 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.
+.\"
+.Dd March 1, 2001
+.Dt STRLCPY 3
+.Os
+.Sh NAME
+.Nm strlcpy ,
+.Nm strlcat
+.Nd size-bounded string copying and concatenation
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft size_t
+.Fn strlcpy "char *dst" "const char *src" "size_t size"
+.Ft size_t
+.Fn strlcat "char *dst" "const char *src" "size_t size"
+.Sh DESCRIPTION
+The
+.Fn strlcpy
+and
+.Fn strlcat
+functions copy and concatenate strings respectively.
+They are designed
+to be safer, more consistent, and less error prone replacements for
+.Xr strncpy 3
+and
+.Xr strncat 3 .
+Unlike those functions,
+.Fn strlcpy
+and
+.Fn strlcat
+take the full size of the buffer (not just the length) and guarantee to
+NUL-terminate the result (as long as
+.Fa size
+is larger than 0 or, in the case of
+.Fn strlcat ,
+as long as there is at least one byte free in
+.Fa dst ) .
+Note that you should include a byte for the NUL in
+.Fa size .
+Also note that
+.Fn strlcpy
+and
+.Fn strlcat
+only operate on true
+.Dq C
+strings.
+This means that for
+.Fn strlcpy
+.Fa src
+must be NUL-terminated and for
+.Fn strlcat
+both
+.Fa src
+and
+.Fa dst
+must be NUL-terminated.
+.Pp
+The
+.Fn strlcpy
+function copies up to
+.Fa size
+- 1 characters from the NUL-terminated string
+.Fa src
+to
+.Fa dst ,
+NUL-terminating the result.
+.Pp
+The
+.Fn strlcat
+function appends the NUL-terminated string
+.Fa src
+to the end of
+.Fa dst .
+It will append at most
+.Fa size
+- strlen(dst) - 1 bytes, NUL-terminating the result.
+.Sh RETURN VALUES
+The
+.Fn strlcpy
+and
+.Fn strlcat
+functions return the total length of the string they tried to create.
+For
+.Fn strlcpy
+that means the length of
+.Fa src .
+For
+.Fn strlcat
+that means the initial length of
+.Fa dst
+plus
+the length of
+.Fa src .
+While this may seem somewhat confusing it was done to make
+truncation detection simple.
+.Pp
+Note however, that if
+.Fn strlcat
+traverses
+.Fa size
+characters without finding a NUL, the length of the string is considered
+to be
+.Fa size
+and the destination string will not be NUL-terminated (since there was
+no space for the NUL).
+This keeps
+.Fn strlcat
+from running off the end of a string.
+In practice this should not happen (as it means that either
+.Fa size
+is incorrect or that
+.Fa dst
+is not a proper
+.Dq C
+string).
+The check exists to prevent potential security problems in incorrect code.
+.Sh EXAMPLES
+The following code fragment illustrates the simple case:
+.Bd -literal -offset indent
+char *s, *p, buf[BUFSIZ];
+
+\&...
+
+(void)strlcpy(buf, s, sizeof(buf));
+(void)strlcat(buf, p, sizeof(buf));
+.Ed
+.Pp
+To detect truncation, perhaps while building a pathname, something
+like the following might be used:
+.Bd -literal -offset indent
+char *dir, *file, pname[MAXPATHLEN];
+
+\&...
+
+if (strlcpy(pname, dir, sizeof(pname)) \*[Ge] sizeof(pname))
+       goto toolong;
+if (strlcat(pname, file, sizeof(pname)) \*[Ge] sizeof(pname))
+       goto toolong;
+.Ed
+.Pp
+Since we know how many characters we copied the first time, we can
+speed things up a bit by using a copy instead of an append:
+.Bd -literal -offset indent
+char *dir, *file, pname[MAXPATHLEN];
+size_t n;
+
+\&...
+
+n = strlcpy(pname, dir, sizeof(pname));
+if (n \*[Ge] sizeof(pname))
+       goto toolong;
+if (strlcpy(pname + n, file, sizeof(pname) - n) \*[Ge] sizeof(pname) - n)
+       goto toolong;
+.Ed
+.Pp
+However, one may question the validity of such optimizations, as they
+defeat the whole purpose of
+.Fn strlcpy
+and
+.Fn strlcat .
+.Sh SEE ALSO
+.Xr snprintf 3 ,
+.Xr strncat 3 ,
+.Xr strncpy 3
+.Rs
+.%A Todd C. Miller
+.%A Theo de Raadt
+.%T strlcpy and strlcat -- Consistent, Safe, String Copy and Concatenation
+.%I USENIX Association
+.%B Proceedings of the FREENIX Track: 1999 USENIX Annual Technical Conference
+.%D June 6-11, 1999
+.%U http://www.usenix.org/publications/library/proceedings/usenix99/full_papers/millert/millert.pdf
+.Re
+.Sh HISTORY
+The
+.Fn strlcpy
+and
+.Fn strlcat
+functions first appeared in
+.Ox 2.4 ,
+then in
+.Nx 1.4.3
+and
+.Fx 3.3 .
diff --git a/lib/nbsd_libc/string/strlen.3 b/lib/nbsd_libc/string/strlen.3
new file mode 100644 (file)
index 0000000..d460f9d
--- /dev/null
@@ -0,0 +1,95 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strlen.3     8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: strlen.3,v 1.9 2009/05/01 17:27:01 perry Exp $
+.\"
+.Dd May 1, 2009
+.Dt STRLEN 3
+.Os
+.Sh NAME
+.Nm strlen ,
+.Nm strnlen
+.Nd find length of string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft size_t
+.Fn strlen "const char *s"
+.Ft size_t
+.Fn strnlen "const char *s" "size_t maxlen"
+.Sh DESCRIPTION
+The
+.Fn strlen
+function
+computes the length of the string
+.Fa s .
+.Pp
+The
+.Fn strnlen
+function attempts to compute the length of
+.Fa s ,
+but never scans beyond the first
+.Fa maxlen
+bytes of
+.Fa s .
+.Sh RETURN VALUES
+The
+.Fn strlen
+function
+returns
+the number of characters that precede the
+terminating
+.Dv NUL
+character.
+.Pp
+The
+.Fn strnlen
+function returns either the same result as
+.Fn strlen
+or
+.Fa maxlen ,
+whichever is smaller.
+.Sh SEE ALSO
+.Xr string 3 ,
+.Xr wcslen 3 ,
+.Xr wcswidth 3
+.Sh STANDARDS
+The
+.Fn strlen
+function
+conforms to
+.St -isoC .
+The
+.Fn strnlen
+function conforms to
+.St -p1003.1-2008 .
diff --git a/lib/nbsd_libc/string/strmode.3 b/lib/nbsd_libc/string/strmode.3
new file mode 100644 (file)
index 0000000..8998009
--- /dev/null
@@ -0,0 +1,156 @@
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)strmode.3    8.3 (Berkeley) 7/28/94
+.\"    $NetBSD: strmode.3,v 1.17 2006/10/16 08:48:45 wiz Exp $
+.\"
+.Dd July 28, 1994
+.Dt STRMODE 3
+.Os
+.Sh NAME
+.Nm strmode
+.Nd convert inode status information into a symbolic string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft void
+.Fn strmode "mode_t mode" "char *bp"
+.Sh DESCRIPTION
+The
+.Fn strmode
+function
+converts a file
+.Fa mode
+(the type and permission information associated with an inode, see
+.Xr stat 2 )
+into a symbolic string which is stored in the location referenced by
+.Fa bp .
+This stored string is eleven characters in length plus a trailing nul byte.
+.Pp
+The first character is the inode type, and will be one of the following:
+.Pp
+.Bl -tag -width flag -offset indent -compact
+.It \-
+regular file
+.It a
+regular file in archive state 1
+.It A
+regular file in archive state 2
+.It b
+block special
+.It c
+character special
+.It d
+directory
+.It l
+symbolic link
+.It p
+fifo
+.It s
+socket
+.It w
+whiteout
+.It ?
+unknown inode type
+.El
+.Pp
+The next nine characters encode three sets of permissions, in three
+characters each.
+The first three characters are the permissions for the owner of the
+file, the second three for the group the file belongs to, and the
+third for the ``other'', or default, set of users.
+.Pp
+Permission checking is done as specifically as possible.
+If read permission is denied to the owner of a file in the first set
+of permissions, the owner of the file will not be able to read the file.
+This is true even if the owner is in the file's group and the group
+permissions allow reading or the ``other'' permissions allow reading.
+.Pp
+If the first character of the three character set is an ``r'', the file is
+readable for that set of users; if a dash ``\-'', it is not readable.
+.Pp
+If the second character of the three character set is a ``w'', the file is
+writable for that set of users; if a dash ``\-'', it is not writable.
+.Pp
+The third character is the first of the following characters that apply:
+.Bl -tag -width xxxx
+.It S
+If the character is part of the owner permissions and the file is not
+executable or the directory is not searchable by the owner, and the
+set-user-id bit is set.
+.It S
+If the character is part of the group permissions and the file is not
+executable or the directory is not searchable by the group, and the
+set-group-id bit is set.
+.It T
+If the character is part of the other permissions and the file is not
+executable or the directory is not searchable by others, and the ``sticky''
+.Pq Dv S_ISVTX
+bit is set.
+.It s
+If the character is part of the owner permissions and the file is
+executable or the directory searchable by the owner, and the set-user-id
+bit is set.
+.It s
+If the character is part of the group permissions and the file is
+executable or the directory searchable by the group, and the set-group-id
+bit is set.
+.It t
+If the character is part of the other permissions and the file is
+executable or the directory searchable by others, and the ``sticky''
+.Pq Dv S_ISVTX
+bit is set.
+.It x
+The file is executable or the directory is searchable.
+.It \-
+None of the above apply.
+.El
+.Pp
+The last character is a plus sign ``+'' if there are any alternative
+or additional access control methods associated with the inode, otherwise
+it will be a space.
+.Pp
+Archive state 1 and archive state 2 represent file system dependent
+archive state for a file.
+Most file systems do not retain file archive
+state, and so will not report files in either archive state.
+msdosfs will report a file in archive state 1 if it has been
+archived more recently than modified.
+Hierarchical storage systems may have multiple archive states for a
+file and may define archive states 1 and 2 as appropriate.
+.Sh SEE ALSO
+.Xr chmod 1 ,
+.Xr find 1 ,
+.Xr stat 2 ,
+.Xr getmode 3 ,
+.Xr setmode 3
+.Sh HISTORY
+The
+.Fn strmode
+function first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/string/strmode.c b/lib/nbsd_libc/string/strmode.c
new file mode 100644 (file)
index 0000000..6d7bd1f
--- /dev/null
@@ -0,0 +1,184 @@
+/*     $NetBSD: strmode.c,v 1.18 2006/10/07 22:04:18 apb Exp $ */
+
+/*-
+ * 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strmode.c  8.3 (Berkeley) 8/15/94";
+#else
+__RCSID("$NetBSD: strmode.c,v 1.18 2006/10/07 22:04:18 apb Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <unistd.h>
+
+#if !HAVE_STRMODE
+void
+strmode(mode, p)
+       mode_t mode;
+       char *p;
+{
+
+       _DIAGASSERT(p != NULL);
+
+        /* print type */
+       switch (mode & S_IFMT) {
+       case S_IFDIR:                   /* directory */
+               *p++ = 'd';
+               break;
+       case S_IFCHR:                   /* character special */
+               *p++ = 'c';
+               break;
+       case S_IFBLK:                   /* block special */
+               *p++ = 'b';
+               break;
+       case S_IFREG:                   /* regular */
+#ifdef S_ARCH2
+               if ((mode & S_ARCH2) != 0) {
+                       *p++ = 'A';
+               } else if ((mode & S_ARCH1) != 0) {
+                       *p++ = 'a';
+               } else {
+#endif
+                       *p++ = '-';
+#ifdef S_ARCH2
+               }
+#endif
+               break;
+       case S_IFLNK:                   /* symbolic link */
+               *p++ = 'l';
+               break;
+#ifdef S_IFSOCK
+       case S_IFSOCK:                  /* socket */
+               *p++ = 's';
+               break;
+#endif
+#ifdef S_IFIFO
+       case S_IFIFO:                   /* fifo */
+               *p++ = 'p';
+               break;
+#endif
+#ifdef S_IFWHT
+       case S_IFWHT:                   /* whiteout */
+               *p++ = 'w';
+               break;
+#endif
+#ifdef S_IFDOOR
+       case S_IFDOOR:                  /* door */
+               *p++ = 'D';
+               break;
+#endif
+       default:                        /* unknown */
+               *p++ = '?';
+               break;
+       }
+       /* usr */
+       if (mode & S_IRUSR)
+               *p++ = 'r';
+       else
+               *p++ = '-';
+       if (mode & S_IWUSR)
+               *p++ = 'w';
+       else
+               *p++ = '-';
+       switch (mode & (S_IXUSR | S_ISUID)) {
+       case 0:
+               *p++ = '-';
+               break;
+       case S_IXUSR:
+               *p++ = 'x';
+               break;
+       case S_ISUID:
+               *p++ = 'S';
+               break;
+       case S_IXUSR | S_ISUID:
+               *p++ = 's';
+               break;
+       }
+       /* group */
+       if (mode & S_IRGRP)
+               *p++ = 'r';
+       else
+               *p++ = '-';
+       if (mode & S_IWGRP)
+               *p++ = 'w';
+       else
+               *p++ = '-';
+       switch (mode & (S_IXGRP | S_ISGID)) {
+       case 0:
+               *p++ = '-';
+               break;
+       case S_IXGRP:
+               *p++ = 'x';
+               break;
+       case S_ISGID:
+               *p++ = 'S';
+               break;
+       case S_IXGRP | S_ISGID:
+               *p++ = 's';
+               break;
+       }
+       /* other */
+       if (mode & S_IROTH)
+               *p++ = 'r';
+       else
+               *p++ = '-';
+       if (mode & S_IWOTH)
+               *p++ = 'w';
+       else
+               *p++ = '-';
+       switch (mode & (S_IXOTH | S_ISVTX)) {
+       case 0:
+               *p++ = '-';
+               break;
+       case S_IXOTH:
+               *p++ = 'x';
+               break;
+       case S_ISVTX:
+               *p++ = 'T';
+               break;
+       case S_IXOTH | S_ISVTX:
+               *p++ = 't';
+               break;
+       }
+       *p++ = ' ';             /* will be a '+' if ACL's implemented */
+       *p = '\0';
+}
+#endif /* !HAVE_STRMODE */
diff --git a/lib/nbsd_libc/string/strncat.c b/lib/nbsd_libc/string/strncat.c
new file mode 100644 (file)
index 0000000..709fa30
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: strncat.c,v 1.11 2007/06/03 17:39:27 christos Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strncat.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strncat.c,v 1.11 2007/06/03 17:39:27 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <string.h>
+
+#ifdef _FORTIFY_SOURCE
+#undef strncat
+#endif
+
+/*
+ * Concatenate src on the end of dst.  At most strlen(dst)+n+1 bytes
+ * are written at dst (at most n+1 bytes being appended).  Return dst.
+ */
+char *
+strncat(dst, src, n)
+       char *dst;
+       const char *src;
+       size_t n;
+{
+
+       _DIAGASSERT(dst != NULL);
+       _DIAGASSERT(src != NULL);
+
+       if (n != 0) {
+               char *d = dst;
+               const char *s = src;
+
+               while (*d != 0)
+                       d++;
+               do {
+                       if ((*d = *s++) == 0)
+                               break;
+                       d++;
+               } while (--n != 0);
+               *d = 0;
+       }
+       return (dst);
+}
diff --git a/lib/nbsd_libc/string/strndup.c b/lib/nbsd_libc/string/strndup.c
new file mode 100644 (file)
index 0000000..28dd39c
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: strndup.c,v 1.4 2007/07/03 12:11:09 nakayama Exp $     */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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 HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strdup.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strndup.c,v 1.4 2007/07/03 12:11:09 nakayama Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(strndup,_strndup)
+#endif
+
+#if !HAVE_STRNDUP
+char *
+strndup(const char *str, size_t n)
+{
+       size_t len;
+       char *copy;
+
+       _DIAGASSERT(str != NULL);
+
+       for (len = 0; len < n && str[len]; len++)
+               continue;
+
+       if (!(copy = malloc(len + 1)))
+               return (NULL);
+       memcpy(copy, str, len);
+       copy[len] = '\0';
+       return (copy);
+}
+#endif /* !HAVE_STRNDUP */
diff --git a/lib/nbsd_libc/string/strnlen.c b/lib/nbsd_libc/string/strnlen.c
new file mode 100644 (file)
index 0000000..8342828
--- /dev/null
@@ -0,0 +1,47 @@
+/*     $NetBSD: strnlen.c,v 1.1 2009/05/01 17:27:01 perry Exp $        */
+
+/*-
+ * Copyright (c) 2009 David Schultz <das@FreeBSD.org>
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: strnlen.c,v 1.1 2009/05/01 17:27:01 perry Exp $");
+#endif /* LIBC_SCCS and not lint */
+/* FreeBSD: src/lib/libc/string/strnlen.c,v 1.1 2009/02/28 06:00:58 das Exp */
+
+#include <string.h>
+
+size_t
+strnlen(const char *s, size_t maxlen)
+{
+       size_t len;
+
+       for (len = 0; len < maxlen; len++, s++) {
+               if (!*s)
+                       break;
+       }
+       return (len);
+}
diff --git a/lib/nbsd_libc/string/strpbrk.3 b/lib/nbsd_libc/string/strpbrk.3
new file mode 100644 (file)
index 0000000..f088670
--- /dev/null
@@ -0,0 +1,79 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strpbrk.3    8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: strpbrk.3,v 1.9 2006/10/16 08:48:45 wiz Exp $
+.\"
+.Dd June 4, 1993
+.Dt STRPBRK 3
+.Os
+.Sh NAME
+.Nm strpbrk
+.Nd locate multiple characters in string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft char *
+.Fn strpbrk "const char *s" "const char *charset"
+.Sh DESCRIPTION
+The
+.Fn strpbrk
+function
+locates in the nul-terminated string
+.Fa s
+the first occurrence of any character in the string
+.Fa charset
+and returns a pointer to this character.
+If no characters from
+.Fa charset
+occur anywhere in
+.Fa s
+.Fn strpbrk
+returns
+.Dv NULL .
+.Sh SEE ALSO
+.Xr index 3 ,
+.Xr memchr 3 ,
+.Xr rindex 3 ,
+.Xr strchr 3 ,
+.Xr strcspn 3 ,
+.Xr strrchr 3 ,
+.Xr strsep 3 ,
+.Xr strspn 3 ,
+.Xr strstr 3 ,
+.Xr strtok 3
+.Sh STANDARDS
+The
+.Fn strpbrk
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/string/strpbrk.c b/lib/nbsd_libc/string/strpbrk.c
new file mode 100644 (file)
index 0000000..095b9b2
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: strpbrk.c,v 1.19 2008/09/24 16:58:53 christos Exp $    */
+
+/*-
+ * Copyright (c) 2008 Joerg Sonnenberger
+ * 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(S) ``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(S) 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 <sys/cdefs.h>
+__RCSID("$NetBSD: strpbrk.c,v 1.19 2008/09/24 16:58:53 christos Exp $");
+
+#include <assert.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <string.h>
+
+#define FAST_STRPBRK 1
+#define UC(a) ((unsigned int)(unsigned char)(a))
+
+#ifdef FAST_STRPBRK
+#define ADD_NEW_TO_SET(i) (set[inv[i] = idx++] = (i))
+#define IS_IN_SET(i) (inv[i] < idx && set[inv[i]] == (i))
+#define ADD_TO_SET(i) (void)(IS_IN_SET(i) || /*LINTED no effect*/ADD_NEW_TO_SET(i))
+#else
+#define IS_IN_SET(i) (set[(i) >> 3] & idx[(i) & 7])
+#define ADD_TO_SET(i) (void)(set[(i) >> 3] |= idx[(i) & 7])
+#endif
+
+char *
+strpbrk(const char *s, const char *charset)
+{
+#ifdef FAST_STRPBRK
+       uint8_t set[256], inv[256], idx = 0;
+#else
+       static const size_t idx[8] = { 1, 2, 4, 8, 16, 32, 64, 128 };
+       uint8_t set[32];
+
+       (void)memset(set, 0, sizeof(set));
+#endif
+
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(charset != NULL);
+
+       for (; *charset != '\0'; ++charset)
+               ADD_TO_SET(UC(*charset));
+
+       for (; *s != '\0'; ++s)
+               if (IS_IN_SET(UC(*s)))
+                       return __UNCONST(s);
+       return NULL;
+}
diff --git a/lib/nbsd_libc/string/strrchr.3 b/lib/nbsd_libc/string/strrchr.3
new file mode 100644 (file)
index 0000000..9e46f9e
--- /dev/null
@@ -0,0 +1,100 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strrchr.3    8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: strrchr.3,v 1.10 2006/10/16 08:48:45 wiz Exp $
+.\"
+.Dd August 11, 2002
+.Dt STRRCHR 3
+.Os
+.Sh NAME
+.Nm strrchr
+.Nd locate character in string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft char *
+.Fn strrchr "const char *s" "int c"
+.Sh DESCRIPTION
+The
+.Fn strrchr
+function
+locates the last occurrence of
+.Fa c
+(converted to a char)
+in the string
+.Fa s .
+If
+.Fa c
+is
+.Ql \e0 ,
+.Fn strrchr
+locates the terminating
+.Ql \e0 .
+.Sh RETURN VALUES
+The
+.Fn strrchr
+function
+returns a pointer to the character,
+or a null pointer if
+.Fa c
+does not occur anywhere in
+.Fa s .
+.Sh EXAMPLES
+After the following call to
+.Fn strrchr ,
+.Va p
+will point to the string
+.Qq obar :
+.Bd -literal -offset indent
+char *p;
+char *s = "foobar";
+
+p = strrchr(s, 'o');
+.Ed
+.Sh SEE ALSO
+.Xr index 3 ,
+.Xr memchr 3 ,
+.Xr rindex 3 ,
+.Xr strchr 3 ,
+.Xr strcspn 3 ,
+.Xr strpbrk 3 ,
+.Xr strsep 3 ,
+.Xr strspn 3 ,
+.Xr strstr 3 ,
+.Xr strtok 3
+.Sh STANDARDS
+The
+.Fn strrchr
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/string/strsep.3 b/lib/nbsd_libc/string/strsep.3
new file mode 100644 (file)
index 0000000..6589283
--- /dev/null
@@ -0,0 +1,120 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strsep.3     8.1 (Berkeley) 6/9/93
+.\"    $NetBSD: strsep.3,v 1.19 2006/10/16 08:48:45 wiz Exp $
+.\"
+.Dd August 12, 2006
+.Dt STRSEP 3
+.Os
+.Sh NAME
+.Nm strsep ,
+.Nm stresep
+.Nd separate strings
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft char *
+.Fn strsep "char **stringp" "const char *delim"
+.Ft char *
+.Fn stresep "char **stringp" "const char *delim" "int escape"
+.Sh DESCRIPTION
+The
+.Fn strsep
+function locates, in the nul-terminated string referenced by
+.Fa *stringp ,
+the first occurrence of any character in the string
+.Fa delim
+(or the terminating
+.Ql \e0
+character) and replaces it with a
+.Ql \e0 .
+The location of the next character after the delimiter character
+(or
+.Dv NULL ,
+if the end of the string was reached) is stored in
+.Fa *stringp .
+The original value of
+.Fa *stringp
+is returned.
+.Pp
+An
+.Dq empty
+field, i.e., one caused by two adjacent delimiter characters,
+can be detected by comparing the location referenced by the pointer returned
+by
+.Fn strsep
+to
+.Ql \e0 .
+.Pp
+If
+.Fa *stringp
+is initially
+.Dv NULL ,
+.Fn strsep
+returns
+.Dv NULL .
+The
+.Fn stresep
+function also takes an escape character that allows quoting the delimiter
+character so that it can be part of the source string.
+.Sh EXAMPLES
+The following uses
+.Fn strsep
+to parse a string, containing tokens delimited by white space, into an
+argument vector:
+.Bd -literal -offset indent
+char **ap, *argv[10], *inputstring;
+
+for (ap = argv; ap \*[Lt] \*[Am]argv[9] \*[Am]\*[Am]
+    (*ap = strsep(\*[Am]inputstring, " \et")) != NULL;) {
+       if (**ap != '\e0')
+               ap++;
+}
+.Ed
+.Sh HISTORY
+The
+.Fn strsep
+function
+is intended as a replacement for the
+.Fn strtok
+function.
+While the
+.Fn strtok
+function should be preferred for portability reasons (it conforms to
+.St -ansiC )
+it is unable to handle empty fields, i.e., detect fields delimited by
+two adjacent delimiter characters, or to be used for more than a single
+string at a time.
+The
+.Fn strsep
+function first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/string/strsignal.3 b/lib/nbsd_libc/string/strsignal.3
new file mode 100644 (file)
index 0000000..9d5daa4
--- /dev/null
@@ -0,0 +1,64 @@
+.\" Copyright (c) 1980, 1991 Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strerror.3   6.9 (Berkeley) 6/29/91
+.\"    $NetBSD: strsignal.3,v 1.10 2009/07/22 19:48:27 kleink Exp $
+.\"
+.Dd July 22, 2009
+.Dt STRSIGNAL 3
+.Os
+.Sh NAME
+.Nm strsignal
+.Nd get signal description string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft char *
+.Fn strsignal "int sig"
+.Sh DESCRIPTION
+The
+.Fn strsignal
+function returns a pointer to the language-dependent string describing
+a signal.
+.Pp
+The array pointed to is not to be modified by the program, but may be
+overwritten by subsequent calls to
+.Fn strsignal .
+.Sh SEE ALSO
+.Xr intro 2 ,
+.Xr psignal 3 ,
+.Xr setlocale 3
+.\" .Sh STANDARDS
+.\" The
+.\" .Fn strsignal
+.\" function conforms to
+.\" .St -p1003.1-2008 .
diff --git a/lib/nbsd_libc/string/strsignal.c b/lib/nbsd_libc/string/strsignal.c
new file mode 100644 (file)
index 0000000..c0a95ce
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: strsignal.c,v 1.14 2009/07/22 19:48:27 kleink Exp $    */
+
+/*
+ * Copyright (c) 1988 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)strerror.c  5.6 (Berkeley) 5/4/91";
+#else
+__RCSID("$NetBSD: strsignal.c,v 1.14 2009/07/22 19:48:27 kleink Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <string.h>
+#include <limits.h>
+#include "extern.h"
+
+#ifdef __weak_alias
+__weak_alias(strsignal,_strsignal)
+#endif
+
+__aconst char *
+strsignal(sig)
+       int sig;
+{
+       static char buf[NL_TEXTMAX];
+
+       return __UNCONST(__strsignal(sig, buf, NL_TEXTMAX));
+}
diff --git a/lib/nbsd_libc/string/strspn.3 b/lib/nbsd_libc/string/strspn.3
new file mode 100644 (file)
index 0000000..0938239
--- /dev/null
@@ -0,0 +1,92 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strspn.3     8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: strspn.3,v 1.11 2006/10/16 08:48:45 wiz Exp $
+.\"
+.Dd August 11, 2002
+.Dt STRSPN 3
+.Os
+.Sh NAME
+.Nm strspn
+.Nd span a string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft size_t
+.Fn strspn "const char *s" "const char *charset"
+.Sh DESCRIPTION
+The
+.Fn strspn
+function
+spans the initial part of the nul-terminated string
+.Fa s
+as long as the characters from
+.Fa s
+occur in string
+.Fa charset .
+.Sh RETURN VALUES
+The
+.Fn strspn
+function
+returns the number of characters spanned.
+.Sh EXAMPLES
+The following call to
+.Fn strspn
+will return 3, since the first three characters of string
+.Fa s
+are part of string
+.Fa charset :
+.Bd -literal -offset indent
+char *s = "foobar";
+char *charset = "of";
+size_t span;
+
+span = strspn(s, charset);
+.Ed
+.Sh SEE ALSO
+.Xr index 3 ,
+.Xr memchr 3 ,
+.Xr rindex 3 ,
+.Xr strchr 3 ,
+.Xr strcspn 3 ,
+.Xr strpbrk 3 ,
+.Xr strrchr 3 ,
+.Xr strsep 3 ,
+.Xr strstr 3 ,
+.Xr strtok 3
+.Sh STANDARDS
+The
+.Fn strspn
+function
+conforms to
+.St -ansiC .
diff --git a/lib/nbsd_libc/string/strspn.c b/lib/nbsd_libc/string/strspn.c
new file mode 100644 (file)
index 0000000..9526cde
--- /dev/null
@@ -0,0 +1,151 @@
+/*     $NetBSD: strspn.c,v 1.17 2009/07/30 21:42:06 dsl Exp $  */
+
+/*-
+ * Copyright (c) 2008 Joerg Sonnenberger
+ * 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(S) ``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(S) 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 <sys/cdefs.h>
+__RCSID("$NetBSD: strspn.c,v 1.17 2009/07/30 21:42:06 dsl Exp $");
+
+#include <assert.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <string.h>
+
+#if ULONG_MAX != 0xffffffffffffffffull
+
+size_t
+strspn(const char *s, const char *charset)
+{
+       static const size_t idx[8] = { 1, 2, 4, 8, 16, 32, 64, 128 };
+       uint8_t set[32];
+       const char *t;
+#define UC(a) ((unsigned int)(unsigned char)(a))
+
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(charset != NULL);
+
+       if (charset[0] == '\0')
+               return 0;
+       if (charset[1] == '\0') {
+               for (t = s; *t != '\0'; ++t) {
+                       if (*t != *charset)
+                               break;
+               }
+               return t - s;
+       }
+
+       (void)memset(set, 0, sizeof(set));
+
+       for (; *charset != '\0'; ++charset)
+               set[UC(*charset) >> 3] |= idx[UC(*charset) & 7];
+
+       for (t = s; *t != '\0'; ++t)
+               if ((set[UC(*t) >> 3] & idx[UC(*t) & 7]) == 0)
+                       break;
+       return t - s;
+}
+
+#else
+
+/* 64 bit system, use four 64 bits registers for bitmask */
+
+static size_t
+strspn_x(const char *s_s, const char *charset_s, unsigned long invert)
+{
+       const unsigned char *s = (const unsigned char *)s_s;
+       const unsigned char *charset = (const unsigned char *)charset_s;
+       unsigned long m_0, m_4, m_8, m_c;
+       unsigned char ch, next_ch;
+       unsigned long bit;
+       unsigned long check;
+       size_t count;
+
+       /* Four 64bit registers have one bit for each character value */
+       m_0 = 0;
+       m_4 = 0;
+       m_8 = 0;
+       m_c = 0;
+
+       for (ch = *charset; ch != 0; ch = next_ch) {
+               next_ch = *++charset;
+               bit = 1ul << (ch & 0x3f);
+               if (__predict_true(ch < 0x80)) {
+                       if (ch < 0x40)
+                               m_0 |= bit;
+                       else
+                               m_4 |= bit;
+               } else {
+                       if (ch < 0xc0)
+                               m_8 |= bit;
+                       else
+                               m_c |= bit;
+               }
+       }
+
+       /* For strcspn() we just invert the validity set */
+       m_0 ^= invert;
+       m_4 ^= invert;
+       m_8 ^= invert;
+       m_c ^= invert;
+
+       /*
+        * We could do remove the lsb from m_0 to terminate at the
+        * end of the input string.
+        * However prefetching the next char is benifitial and we must
+        * not read the byte after the \0 - as it might fault!
+        * So we take the 'hit' of the compare against 0.
+        */
+
+       ch = *s++;
+       for (count = 0; ch != 0; ch = next_ch) {
+               next_ch = s[count];
+               if (__predict_true(ch < 0x80)) {
+                       check = m_0;
+                       if (ch >= 0x40)
+                               check = m_4;
+               } else {
+                       check = m_8;
+                       if (ch >= 0xc0)
+                               check = m_c;
+               }
+               if (!((check >> (ch & 0x3f)) & 1))
+                       break;
+               count++;
+       }
+       return count;
+}
+
+size_t
+strspn(const char *s, const char *charset)
+{
+       return strspn_x(s, charset, 0);
+}
+
+size_t
+strcspn(const char *s, const char *charset)
+{
+       return strspn_x(s, charset, ~0ul);
+}
+#endif
diff --git a/lib/nbsd_libc/string/strstr.3 b/lib/nbsd_libc/string/strstr.3
new file mode 100644 (file)
index 0000000..31fd400
--- /dev/null
@@ -0,0 +1,109 @@
+.\" Copyright (c) 2001 Mike Barcroft <mike@FreeBSD.org>
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strstr.3     8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: strstr.3,v 1.10 2006/10/16 08:48:45 wiz Exp $
+.\"
+.Dd July 3, 2004
+.Dt STRSTR 3
+.Os
+.Sh NAME
+.Nm strstr , strcasestr
+.Nd locate a substring in a string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft char *
+.Fn strstr "const char *big" "const char *little"
+.Ft char *
+.Fn strcasestr "const char *big" "const char *little"
+.Sh DESCRIPTION
+The
+.Fn strstr
+function
+locates the first occurrence of the nul-terminated string
+.Fa little
+in the nul-terminated string
+.Fa big .
+.Pp
+The
+.Fn strcasestr
+function is similar to
+.Fn strstr ,
+but ignores the case of both strings.
+.Sh RETURN VALUES
+If
+.Fa little
+is an empty string,
+.Fa big
+is returned;
+if
+.Fa little
+occurs nowhere in
+.Fa big ,
+.Dv NULL
+is returned;
+otherwise a pointer to the first character of the first occurrence of
+.Fa little
+is returned.
+.Sh EXAMPLES
+The following sets the pointer
+.Va ptr
+to the
+.Qq Li Bar Baz
+portion of
+.Va largestring :
+.Bd -literal -offset indent
+const char *largestring = "Foo Bar Baz";
+const char *smallstring = "Bar";
+char *ptr;
+
+ptr = strstr(largestring, smallstring);
+.Ed
+.Sh SEE ALSO
+.Xr index 3 ,
+.Xr memchr 3 ,
+.Xr rindex 3 ,
+.Xr strchr 3 ,
+.Xr strcspn 3 ,
+.Xr strpbrk 3 ,
+.Xr strrchr 3 ,
+.Xr strsep 3 ,
+.Xr strspn 3 ,
+.Xr strtok 3
+.Sh STANDARDS
+The
+.Fn strstr
+function
+conforms to
+.St -isoC .
diff --git a/lib/nbsd_libc/string/strtok.3 b/lib/nbsd_libc/string/strtok.3
new file mode 100644 (file)
index 0000000..c6f5f6b
--- /dev/null
@@ -0,0 +1,162 @@
+.\" Copyright (c) 1988, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strtok.3     8.2 (Berkeley) 2/3/94
+.\"    $NetBSD: strtok.3,v 1.23 2008/08/29 05:48:40 dholland Exp $
+.\"
+.Dd August 11, 2002
+.Dt STRTOK 3
+.Os
+.Sh NAME
+.Nm strtok, strtok_r
+.Nd string tokens
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft char *
+.Fn strtok "char * restrict str" "const char * restrict sep"
+.Ft char *
+.Fn strtok_r "char *str" "const char *sep" "char **lasts"
+.Sh DESCRIPTION
+The
+.Fn strtok
+function
+is used to isolate sequential tokens in a nul-terminated string,
+.Fa str .
+These tokens are separated in the string by at least one of the
+characters in
+.Fa sep .
+The first time that
+.Fn strtok
+is called,
+.Fa str
+should be specified; subsequent calls, wishing to obtain further tokens
+from the same string, should pass a null pointer instead.
+The separator string,
+.Fa sep ,
+must be supplied each time, and may change between calls.
+.Pp
+The
+.Fn strtok
+function
+returns a pointer to the beginning of each subsequent token in the string,
+after replacing the separator character itself with a
+.Dv NUL
+character.
+Separator characters at the beginning of the string or at the
+continuation point are skipped so that zero length tokens
+are not returned.
+When no more tokens remain, a null pointer is returned.
+.Pp
+The
+.Fn strtok_r
+function implements the functionality of
+.Fn strtok
+but is passed an additional argument,
+.Fa lasts ,
+which points to a user-provided pointer which is used by
+.Fn strtok_r
+to store state which needs to be kept between calls to scan the same string;
+unlike
+.Fn strtok ,
+it is not necessary to limit tokenizing to a single string at a time
+when using
+.Fn strtok_r .
+.Sh EXAMPLES
+The following will construct an array of pointers to each individual word in
+the string
+.Va s :
+.Bd -literal -offset indent
+#define MAXTOKENS      128
+
+char s[512], *p, *tokens[MAXTOKENS];
+char *last;
+int i = 0;
+
+snprintf(s, sizeof(s), "cat dog horse cow");
+
+for ((p = strtok_r(s, " ", &last)); p;
+    (p = strtok_r(NULL, " ", &last)), i++) {
+       if (i < MAXTOKENS - 1)
+               tokens[i] = p;
+}
+tokens[i] = NULL;
+.Ed
+.Pp
+That is,
+.Li tokens[0]
+will point to
+.Qq cat ,
+.Li tokens[1]
+will point to
+.Qq dog ,
+.Li tokens[2]
+will point to
+.Qq horse ,
+and
+.Li tokens[3]
+will point to
+.Qq cow .
+.Sh SEE ALSO
+.Xr index 3 ,
+.Xr memchr 3 ,
+.Xr rindex 3 ,
+.Xr strchr 3 ,
+.Xr strcspn 3 ,
+.Xr strpbrk 3 ,
+.Xr strrchr 3 ,
+.Xr strsep 3 ,
+.Xr strspn 3 ,
+.Xr strstr 3
+.Sh STANDARDS
+The
+.Fn strtok
+function
+conforms to
+.St -ansiC .
+The
+.Fn strtok_r
+function conforms to
+.St -p1003.1c-95 .
+.Sh BUGS
+The System V
+.Fn strtok ,
+if handed a string containing only delimiter characters,
+will not alter the next starting point, so that a call to
+.Fn strtok
+with a different (or empty) delimiter string
+may return a
+.Pf non- Dv NULL
+value.
+Since this implementation always alters the next starting point,
+such a sequence of calls would always return
+.Dv NULL .
diff --git a/lib/nbsd_libc/string/strtok.c b/lib/nbsd_libc/string/strtok.c
new file mode 100644 (file)
index 0000000..4fc6214
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: strtok.c,v 1.12 2004/10/27 19:12:31 dsl Exp $  */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strtok.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strtok.c,v 1.12 2004/10/27 19:12:31 dsl Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <namespace.h>
+#include <string.h>
+
+char *
+strtok(char *s, const char *delim)
+{
+       static char *lasts;
+
+       return strtok_r(s, delim, &lasts);
+}
diff --git a/lib/nbsd_libc/string/strtok_r.c b/lib/nbsd_libc/string/strtok_r.c
new file mode 100644 (file)
index 0000000..88065f2
--- /dev/null
@@ -0,0 +1,102 @@
+/*     $NetBSD: strtok_r.c,v 1.9 2003/08/07 16:43:53 agc Exp $ */
+
+/*
+ * Copyright (c) 1988 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char *sccsid = "@(#)strtok.c    5.8 (Berkeley) 2/24/91";
+#else
+__RCSID("$NetBSD: strtok_r.c,v 1.9 2003/08/07 16:43:53 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <string.h>
+
+#ifdef __weak_alias
+__weak_alias(strtok_r,_strtok_r)
+#endif
+
+char *
+strtok_r(s, delim, lasts)
+       char *s;
+       const char *delim;
+       char **lasts;
+{
+       const char *spanp;
+       int c, sc;
+       char *tok;
+
+       /* s may be NULL */
+       _DIAGASSERT(delim != NULL);
+       _DIAGASSERT(lasts != NULL);
+
+       if (s == NULL && (s = *lasts) == NULL)
+               return (NULL);
+
+       /*
+        * Skip (span) leading delimiters (s += strspn(s, delim), sort of).
+        */
+cont:
+       c = *s++;
+       for (spanp = delim; (sc = *spanp++) != 0;) {
+               if (c == sc)
+                       goto cont;
+       }
+
+       if (c == 0) {           /* no non-delimiter characters */
+               *lasts = NULL;
+               return (NULL);
+       }
+       tok = s - 1;
+
+       /*
+        * Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
+        * Note that delim must have one NUL; we stop if we see that, too.
+        */
+       for (;;) {
+               c = *s++;
+               spanp = delim;
+               do {
+                       if ((sc = *spanp++) == c) {
+                               if (c == 0)
+                                       s = NULL;
+                               else
+                                       s[-1] = 0;
+                               *lasts = s;
+                               return (tok);
+                       }
+               } while (sc != 0);
+       }
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/string/strxfrm.3 b/lib/nbsd_libc/string/strxfrm.3
new file mode 100644 (file)
index 0000000..fcec9a9
--- /dev/null
@@ -0,0 +1,78 @@
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strxfrm.3    8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: strxfrm.3,v 1.11 2007/02/18 00:46:47 wiz Exp $
+.\"
+.Dd February 18, 2007
+.Dt STRXFRM 3
+.Os
+.Sh NAME
+.Nm strxfrm
+.Nd transform a string under locale
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In string.h
+.Ft size_t
+.Fn strxfrm "char * restrict dst" "const char * restrict src" "size_t n"
+.Sh DESCRIPTION
+The idea of
+.Fn strxfrm
+is to
+.Dq un-localize
+a string: the function transforms
+.Ar src ,
+storing the result in
+.Ar dst ,
+such that
+.Xr strcmp 3
+on transformed strings returns what
+.Xr strcoll 3
+on the original untransformed strings would return.
+.Sh SEE ALSO
+.Xr bcmp 3 ,
+.Xr memcmp 3 ,
+.\" .Xr setlocale 3 ,
+.Xr strcasecmp 3 ,
+.Xr strcmp 3 ,
+.Xr strcoll 3
+.Sh STANDARDS
+The
+.Fn strxfrm
+function
+conforms to
+.St -ansiC .
+.Sh BUGS
+Since locales are not fully implemented on
+.Nx ,
+.Fn strxfrm
+just returns a copy of the original string.
diff --git a/lib/nbsd_libc/string/strxfrm.c b/lib/nbsd_libc/string/strxfrm.c
new file mode 100644 (file)
index 0000000..4e25cf8
--- /dev/null
@@ -0,0 +1,73 @@
+/*     $NetBSD: strxfrm.c,v 1.11 2003/08/07 16:43:53 agc Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strxfrm.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: strxfrm.c,v 1.11 2003/08/07 16:43:53 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <string.h>
+
+/*
+ * Transform src, storing the result in dst, such that
+ * strcmp() on transformed strings returns what strcoll()
+ * on the original untransformed strings would return.
+ */
+size_t
+strxfrm(dst, src, n)
+       char *dst;
+       const char *src;
+       size_t n;
+{
+       size_t srclen, copysize;
+
+       _DIAGASSERT(src != NULL);
+
+       /*
+        * Since locales are unimplemented, this is just a copy.
+        */
+       srclen = strlen(src);
+       if (n != 0) {
+               _DIAGASSERT(dst != NULL);
+               copysize = srclen < n ? srclen : n - 1;
+               (void)memcpy(dst, src, copysize);
+               dst[copysize] = 0;
+       }
+       return (srclen);
+}
diff --git a/lib/nbsd_libc/string/swab.3 b/lib/nbsd_libc/string/swab.3
new file mode 100644 (file)
index 0000000..7c91e6b
--- /dev/null
@@ -0,0 +1,92 @@
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)swab.3       8.1 (Berkeley) 6/4/93
+.\"    $NetBSD: swab.3,v 1.15 2010/04/30 03:52:13 jruoho Exp $
+.\"
+.Dd April 30, 2010
+.Dt SWAB 3
+.Os
+.Sh NAME
+.Nm swab
+.Nd swap adjacent bytes
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft void
+.Fn swab "const void * restrict src" "void * restrict dst" "ssize_t len"
+.Sh DESCRIPTION
+The function
+.Fn swab
+copies
+.Fa len
+bytes from the location referenced by
+.Fa src
+to the location referenced by
+.Fa dst ,
+swapping adjacent bytes.
+.Pp
+If
+.Fa len
+is negative or zero,
+.Fn swab
+does nothing.
+If
+.Fa len
+is odd,
+.Fn swab
+copies
+.Fa len - 1
+bytes and the disposition of the last byte is unspecified.
+.Sh SEE ALSO
+.Xr bzero 3 ,
+.Xr memset 3
+.Sh STANDARDS
+The
+.Fn swab
+function conforms to
+.St -p1003.1-2001 .
+.Sh HISTORY
+A
+.Fn swab
+function appeared in
+.At v7 .
+It was originally documented to be
+.Dq useful for carrying binary data between PDP11's and other machines .
+.Pp
+In
+.Nx 6.0
+the type of
+.Fa len
+was changed from
+.Vt size_t
+to
+.Vt ssize_t
+for
+.Tn POSIX
+compliance.
diff --git a/lib/nbsd_libc/string/swab.c b/lib/nbsd_libc/string/swab.c
new file mode 100644 (file)
index 0000000..392b186
--- /dev/null
@@ -0,0 +1,80 @@
+/*     $NetBSD: swab.c,v 1.18 2011/01/04 17:14:07 martin Exp $ */
+
+/*
+ * Copyright (c) 1988, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Jeffrey Mogul.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)swab.c     8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: swab.c,v 1.18 2011/01/04 17:14:07 martin Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <unistd.h>
+
+void
+swab(const void * __restrict from, void * __restrict to, ssize_t len)
+{
+       char temp;
+       const char *fp;
+       char *tp;
+
+       if (len <= 1)
+               return;
+
+       _DIAGASSERT(from != NULL);
+       _DIAGASSERT(to != NULL);
+
+       len /= 2;
+       fp = (const char *)from;
+       tp = (char *)to;
+#define        STEP    temp = *fp++,*tp++ = *fp++,*tp++ = temp
+
+       if (__predict_false(len == 1)) {
+               STEP;
+               return;
+       }
+
+       /* round to multiple of 8 */
+       while ((--len % 8) != 0)
+               STEP;
+       len /= 8;
+       if (len == 0)
+               return;
+       while (len-- != 0) {
+               STEP; STEP; STEP; STEP;
+               STEP; STEP; STEP; STEP;
+       }
+}
diff --git a/lib/nbsd_libc/string/wcscasecmp.3 b/lib/nbsd_libc/string/wcscasecmp.3
new file mode 100644 (file)
index 0000000..ae7ed42
--- /dev/null
@@ -0,0 +1,86 @@
+.\"    $NetBSD: wcscasecmp.3,v 1.3 2010/12/16 17:42:28 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek.
+.\" 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. 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.
+.\"
+.\"     from: @(#)wcscasecmp.3 8.1 (Berkeley) 6/9/93
+.\"
+.Dd August 26, 2006
+.Dt WCSCASECMP 3
+.Os
+.Sh NAME
+.Nm wcscasecmp ,
+.Nm wcsncasecmp
+.Nd compare wide-character strings, ignoring case
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wchar.h
+.Ft int
+.Fn wcscasecmp "const wchar_t *s1" "const wchar_t *s2"
+.Ft int
+.Fn wcsncasecmp "const wchar_t *s1" "const wchar_t *s2" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn wcscasecmp
+and
+.Fn wcsncasecmp
+functions
+compare the nul-terminated strings
+.Fa s1
+and
+.Fa s2
+and return an integer greater than, equal to, or less than 0,
+according to whether
+.Fa s1
+is lexicographically greater than, equal to, or less than
+.Fa s2
+after translation of each corresponding character to lower-case.
+The strings themselves are not modified.
+.Pp
+The
+.Fn wcsncasecmp
+compares at most
+.Fa len
+characters.
+.Sh SEE ALSO
+.Xr wcscmp 3
+.Sh HISTORY
+The
+.Fn wcscasecmp
+and
+.Fn wcsncasecmp
+functions first appeared in
+.Nx 4.0 .
+.Sh NOTES
+If
+.Fa len
+is zero,
+.Fn wcsncasecmp
+returns always 0.
diff --git a/lib/nbsd_libc/string/wcscasecmp.c b/lib/nbsd_libc/string/wcscasecmp.c
new file mode 100644 (file)
index 0000000..683a301
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: wcscasecmp.c,v 1.2 2006/08/26 22:45:52 christos Exp $  */
+
+/*
+ * Copyright (C) 2006 Aleksey Cheusov
+ *
+ * This material is provided "as is", with absolutely no warranty expressed
+ * or implied. Any use is at your own risk.
+ *
+ * Permission to use or copy this software for any purpose is hereby granted 
+ * without fee. Permission to modify the code and to distribute modified
+ * code is also granted without any restrictions.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint) 
+__RCSID("$NetBSD: wcscasecmp.c,v 1.2 2006/08/26 22:45:52 christos Exp $"); 
+#endif /* LIBC_SCCS and not lint */ 
+
+#include "namespace.h"
+#include <assert.h>
+#include <wchar.h>
+#include <wctype.h>
+
+__weak_alias(wcscasecmp,_wcscasecmp)
+
+int
+wcscasecmp(const wchar_t *s1, const wchar_t *s2)
+{
+       int lc1  = 0;
+       int lc2  = 0;
+       int diff = 0;
+
+       _DIAGASSERT(s1);
+       _DIAGASSERT(s2);
+
+       for (;;) {
+               lc1 = towlower(*s1);
+               lc2 = towlower(*s2);
+
+               diff = lc1 - lc2;
+               if (diff)
+                       return diff;
+
+               if (!lc1)
+                       return 0;
+
+               ++s1;
+               ++s2;
+       }
+}
diff --git a/lib/nbsd_libc/string/wcscat.c b/lib/nbsd_libc/string/wcscat.c
new file mode 100644 (file)
index 0000000..d3e6eb8
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: wcscat.c,v 1.2 2001/01/03 14:29:36 lukem Exp $ */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wcscat.c,v 1.1 1999/12/29 21:47:45 tshiozak Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcscat.c,v 1.2 2001/01/03 14:29:36 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+wchar_t *
+wcscat(s1, s2)
+       wchar_t *s1;
+       const wchar_t *s2;
+{
+       wchar_t *p;
+       wchar_t *q;
+       const wchar_t *r;
+
+       _DIAGASSERT(s1 != NULL);
+       _DIAGASSERT(s2 != NULL);
+
+       p = s1;
+       while (*p)
+               p++;
+       q = p;
+       r = s2;
+       while (*r)
+               *q++ = *r++;
+       *q = '\0';
+       return s1;
+}
diff --git a/lib/nbsd_libc/string/wcschr.c b/lib/nbsd_libc/string/wcschr.c
new file mode 100644 (file)
index 0000000..9808ae3
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: wcschr.c,v 1.4 2005/06/04 20:09:56 dsl Exp $   */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wcschr.c,v 1.2 2000/12/21 05:07:25 itojun Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcschr.c,v 1.4 2005/06/04 20:09:56 dsl Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+wchar_t *
+wcschr(const wchar_t *p, wchar_t c)
+{
+       _DIAGASSERT(p != NULL);
+
+       for (;; ++p) {
+               if (*p == c) {
+                       /* LINTED interface specification */
+                       return __UNCONST(p);
+               }
+               if (!*p)
+                       return NULL;
+       }
+       /*NOTREACHED*/
+}
diff --git a/lib/nbsd_libc/string/wcscmp.c b/lib/nbsd_libc/string/wcscmp.c
new file mode 100644 (file)
index 0000000..deb870d
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: wcscmp.c,v 1.8 2009/01/11 02:46:30 christos Exp $      */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strcmp.c   8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: wcscmp.c,v 1.8 2009/01/11 02:46:30 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+#include "runetype_local.h"
+
+/*
+ * Compare strings.
+ */
+int
+wcscmp(s1, s2)
+       const wchar_t *s1, *s2;
+{
+
+       _DIAGASSERT(s1 != NULL);
+       _DIAGASSERT(s2 != NULL);
+
+       while (*s1 == *s2++)
+               if (*s1++ == 0)
+                       return (0);
+       /* XXX assumes wchar_t = int */
+       return (*(const __nbrune_t *)s1 - *(const __nbrune_t *)--s2);
+}
diff --git a/lib/nbsd_libc/string/wcscpy.c b/lib/nbsd_libc/string/wcscpy.c
new file mode 100644 (file)
index 0000000..aabb6d6
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: wcscpy.c,v 1.3 2005/10/13 21:13:05 tnozaki Exp $       */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wcscpy.c,v 1.2 2000/12/21 04:51:09 itojun Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcscpy.c,v 1.3 2005/10/13 21:13:05 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+wchar_t *
+wcscpy(s1, s2)
+       wchar_t *s1;
+       const wchar_t *s2;
+{
+       wchar_t *p;
+
+       _DIAGASSERT(s1 != NULL);
+       _DIAGASSERT(s2 != NULL);
+
+       for (p = s1; (*p = *s2) != L'\0'; ++p, ++s2);
+
+       return s1;
+}
diff --git a/lib/nbsd_libc/string/wcscspn.c b/lib/nbsd_libc/string/wcscspn.c
new file mode 100644 (file)
index 0000000..2fa0989
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: wcscspn.c,v 1.2 2001/01/03 14:29:36 lukem Exp $        */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wcscspn.c,v 1.1 1999/12/29 21:47:45 tshiozak Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcscspn.c,v 1.2 2001/01/03 14:29:36 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+size_t
+wcscspn(s, set)
+       const wchar_t *s;
+       const wchar_t *set;
+{
+       const wchar_t *p;
+       const wchar_t *q;
+
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(set != NULL);
+
+       p = s;
+       while (*p) {
+               q = set;
+               while (*q) {
+                       if (*p == *q)
+                               goto done;
+                       q++;
+               }
+               p++;
+       }
+
+done:
+       return (p - s);
+}
diff --git a/lib/nbsd_libc/string/wcsdup.3 b/lib/nbsd_libc/string/wcsdup.3
new file mode 100644 (file)
index 0000000..8d55635
--- /dev/null
@@ -0,0 +1,87 @@
+.\"    $NetBSD: wcsdup.3,v 1.3 2010/12/16 17:42:28 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)strdup.3     8.1 (Berkeley) 6/9/93
+.\"
+.Dd August 25, 2006
+.Dt WCSDUP 3
+.Os
+.Sh NAME
+.Nm wcsdup
+.Nd save a copy of a string
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wchar.h
+.Ft wchar_t *
+.Fn wcsdup "const wchar_t *str"
+.Sh DESCRIPTION
+The
+.Fn wcsdup
+function
+allocates sufficient memory for a copy
+of the wide-character string
+.Fa str ,
+does the copy, and returns a pointer to it.
+The pointer may subsequently be used as an
+argument to the function
+.Xr free 3 .
+.Pp
+If insufficient memory is available,
+.Dv NULL
+is returned.
+.Sh EXAMPLES
+The following will point
+.Va p
+to an allocated area of memory containing the nul-terminated string
+.Qq foobar :
+.Bd -literal -offset indent
+wchar_t *p;
+
+if (p = wcsdup(L"foobar"), p == NULL) {
+       fprintf(stderr, "Out of memory.\en");
+       exit(1);
+}
+.Ed
+.Sh ERRORS
+The
+.Fn wcsdup
+function may fail and set the external variable
+.Va errno
+for any of the errors specified for the library function
+.Xr malloc 3 .
+.Sh SEE ALSO
+.Xr free 3 ,
+.Xr malloc 3 ,
+.Xr strdup 3
+.Sh HISTORY
+The
+.Fn wcsdup
+function first appeared in
+.Nx 4.0 .
diff --git a/lib/nbsd_libc/string/wcsdup.c b/lib/nbsd_libc/string/wcsdup.c
new file mode 100644 (file)
index 0000000..000ea6a
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: wcsdup.c,v 1.3 2008/05/26 13:17:48 haad Exp $  */
+
+/*
+ * Copyright (C) 2006 Aleksey Cheusov
+ *
+ * This material is provided "as is", with absolutely no warranty expressed
+ * or implied. Any use is at your own risk.
+ *
+ * Permission to use or copy this software for any purpose is hereby granted 
+ * without fee. Permission to modify the code and to distribute modified
+ * code is also granted without any restrictions.
+ */
+
+#include <sys/cdefs.h>
+
+#if defined(LIBC_SCCS) && !defined(lint) 
+__RCSID("$NetBSD: wcsdup.c,v 1.3 2008/05/26 13:17:48 haad Exp $"); 
+#endif /* LIBC_SCCS and not lint */ 
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <assert.h>
+#include <wchar.h>
+
+__weak_alias(wcsdup,_wcsdup)
+
+wchar_t *
+wcsdup(const wchar_t *str)
+{
+       wchar_t *copy;
+       size_t len;
+
+       _DIAGASSERT(str != NULL);
+
+       len = wcslen(str) + 1;
+       copy = malloc(len * sizeof (wchar_t));
+
+       if (!copy)
+               return NULL;
+
+       return wmemcpy(copy, str, len);
+}
diff --git a/lib/nbsd_libc/string/wcslcat.c b/lib/nbsd_libc/string/wcslcat.c
new file mode 100644 (file)
index 0000000..a6d05e7
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: wcslcat.c,v 1.2 2001/01/03 14:33:02 lukem Exp $        */
+/*     from OpenBSD: strlcat.c,v 1.3 2000/11/24 11:10:02 itojun Exp    */
+
+/*
+ * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
+ * 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.
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcslcat.c,v 1.2 2001/01/03 14:33:02 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <wchar.h>
+
+/*
+ * Appends src to string dst of size siz (unlike wcsncat, siz is the
+ * full size of dst, not space left).  At most siz-1 characters
+ * will be copied.  Always NUL terminates (unless siz == 0).
+ * Returns wcslen(initial dst) + wcslen(src); if retval >= siz,
+ * truncation occurred.
+ */
+size_t
+wcslcat(dst, src, siz)
+       wchar_t *dst;
+       const wchar_t *src;
+       size_t siz;
+{
+       wchar_t *d = dst;
+       const wchar_t *s = src;
+       size_t n = siz;
+       size_t dlen;
+
+       _DIAGASSERT(dst != NULL);
+       _DIAGASSERT(src != NULL);
+
+       /* Find the end of dst and adjust bytes left but don't go past end */
+       while (*d != '\0' && n-- != 0)
+               d++;
+       dlen = d - dst;
+       n = siz - dlen;
+
+       if (n == 0)
+               return(dlen + wcslen(s));
+       while (*s != '\0') {
+               if (n != 1) {
+                       *d++ = *s;
+                       n--;
+               }
+               s++;
+       }
+       *d = '\0';
+
+       return(dlen + (s - src));       /* count does not include NUL */
+}
diff --git a/lib/nbsd_libc/string/wcslcpy.c b/lib/nbsd_libc/string/wcslcpy.c
new file mode 100644 (file)
index 0000000..92c857d
--- /dev/null
@@ -0,0 +1,75 @@
+/*     $NetBSD: wcslcpy.c,v 1.2 2001/01/03 14:33:02 lukem Exp $        */
+/*     from OpenBSD: strlcpy.c,v 1.4 1999/05/01 18:56:41 millert Exp   */
+
+/*
+ * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
+ * 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.
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcslcpy.c,v 1.2 2001/01/03 14:33:02 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <assert.h>
+#include <wchar.h>
+
+/*
+ * Copy src to string dst of size siz.  At most siz-1 characters
+ * will be copied.  Always NUL terminates (unless siz == 0).
+ * Returns wcslen(src); if retval >= siz, truncation occurred.
+ */
+size_t
+wcslcpy(dst, src, siz)
+       wchar_t *dst;
+       const wchar_t *src;
+       size_t siz;
+{
+       wchar_t *d = dst;
+       const wchar_t *s = src;
+       size_t n = siz;
+
+       _DIAGASSERT(dst != NULL);
+       _DIAGASSERT(src != NULL);
+
+       /* Copy as many bytes as will fit */
+       if (n != 0 && --n != 0) {
+               do {
+                       if ((*d++ = *s++) == 0)
+                               break;
+               } while (--n != 0);
+       }
+
+       /* Not enough room in dst, add NUL and traverse rest of src */
+       if (n == 0) {
+               if (siz != 0)
+                       *d = '\0';              /* NUL-terminate dst */
+               while (*s++)
+                       ;
+       }
+
+       return(s - src - 1);    /* count does not include NUL */
+}
diff --git a/lib/nbsd_libc/string/wcslen.c b/lib/nbsd_libc/string/wcslen.c
new file mode 100644 (file)
index 0000000..c62c459
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: wcslen.c,v 1.2 2001/01/03 14:29:36 lukem Exp $ */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wcslen.c,v 1.1 1999/12/29 21:47:45 tshiozak Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcslen.c,v 1.2 2001/01/03 14:29:36 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+size_t
+wcslen(s)
+       const wchar_t *s;
+{
+       const wchar_t *p;
+
+       _DIAGASSERT(s != NULL);
+
+       p = s;
+       while (*p)
+               p++;
+
+       return p - s;
+}
diff --git a/lib/nbsd_libc/string/wcsncasecmp.c b/lib/nbsd_libc/string/wcsncasecmp.c
new file mode 100644 (file)
index 0000000..66a4c78
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: wcsncasecmp.c,v 1.2 2006/08/26 22:45:52 christos Exp $ */
+
+/*
+ * Copyright (C) 2006 Aleksey Cheusov
+ *
+ * This material is provided "as is", with absolutely no warranty expressed
+ * or implied. Any use is at your own risk.
+ *
+ * Permission to use or copy this software for any purpose is hereby granted 
+ * without fee. Permission to modify the code and to distribute modified
+ * code is also granted without any restrictions.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint) 
+__RCSID("$NetBSD: wcsncasecmp.c,v 1.2 2006/08/26 22:45:52 christos Exp $"); 
+#endif /* LIBC_SCCS and not lint */ 
+
+#include "namespace.h"
+#include <assert.h>
+#include <wchar.h>
+#include <wctype.h>
+
+__weak_alias(wcsncasecmp,_wcsncasecmp)
+
+int
+wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
+{
+       int lc1  = 0;
+       int lc2  = 0;
+       int diff = 0;
+
+       _DIAGASSERT(s1);
+       _DIAGASSERT(s2);
+
+       while (n--) {
+               lc1 = towlower (*s1);
+               lc2 = towlower (*s2);
+
+               diff = lc1 - lc2;
+               if (diff)
+                       return diff;
+
+               if (!lc1)
+                       return 0;
+
+               ++s1;
+               ++s2;
+       }
+
+       return 0;
+}
diff --git a/lib/nbsd_libc/string/wcsncat.c b/lib/nbsd_libc/string/wcsncat.c
new file mode 100644 (file)
index 0000000..1fdca11
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: wcsncat.c,v 1.2 2001/01/03 14:29:36 lukem Exp $        */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wcsncat.c,v 1.1 1999/12/29 21:47:45 tshiozak Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcsncat.c,v 1.2 2001/01/03 14:29:36 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+wchar_t *
+wcsncat(s1, s2, n)
+       wchar_t *s1;
+       const wchar_t *s2;
+       size_t n;
+{
+       wchar_t *p;
+       wchar_t *q;
+       const wchar_t *r;
+
+       _DIAGASSERT(s1 != NULL);
+       _DIAGASSERT(s2 != NULL);
+
+       p = s1;
+       while (*p)
+               p++;
+       q = p;
+       r = s2;
+       while (*r && n) {
+               *q++ = *r++;
+               n--;
+       }
+       *q = '\0';
+       return s1;
+}
diff --git a/lib/nbsd_libc/string/wcsncmp.c b/lib/nbsd_libc/string/wcsncmp.c
new file mode 100644 (file)
index 0000000..eec477f
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: wcsncmp.c,v 1.8 2009/01/11 02:46:30 christos Exp $     */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)strncmp.c  8.1 (Berkeley) 6/4/93";
+#else
+__RCSID("$NetBSD: wcsncmp.c,v 1.8 2009/01/11 02:46:30 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+#include "runetype_local.h"
+
+int
+wcsncmp(s1, s2, n)
+       const wchar_t *s1, *s2;
+       size_t n;
+{
+
+       _DIAGASSERT(s1 != NULL);
+       _DIAGASSERT(s2 != NULL);
+
+       if (n == 0)
+               return (0);
+       do {
+               if (*s1 != *s2++) {
+                       /* XXX assumes wchar_t = int */
+                       return (*(const __nbrune_t *)s1 -
+                           *(const __nbrune_t *)--s2);
+               }
+               if (*s1++ == 0)
+                       break;
+       } while (--n != 0);
+       return (0);
+}
diff --git a/lib/nbsd_libc/string/wcsncpy.c b/lib/nbsd_libc/string/wcsncpy.c
new file mode 100644 (file)
index 0000000..978ff48
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: wcsncpy.c,v 1.3 2005/10/13 21:13:05 tnozaki Exp $      */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wcsncpy.c,v 1.1 1999/12/29 21:47:45 tshiozak Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcsncpy.c,v 1.3 2005/10/13 21:13:05 tnozaki Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+wchar_t *
+wcsncpy(s1, s2, n)
+       wchar_t *s1;
+       const wchar_t *s2;
+       size_t n;
+{
+       wchar_t *p;
+
+       _DIAGASSERT(s1 != NULL);
+       _DIAGASSERT(s2 != NULL);
+
+       p = s1;
+       while (n && *s2) {
+               *p++ = *s2++;
+               n--;
+       }
+       while (n) {
+               *p++ = L'\0';
+               n--;
+       }
+
+       return s1;
+}
diff --git a/lib/nbsd_libc/string/wcspbrk.c b/lib/nbsd_libc/string/wcspbrk.c
new file mode 100644 (file)
index 0000000..b87a47a
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: wcspbrk.c,v 1.3 2005/11/29 03:12:00 christos Exp $     */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wcspbrk.c,v 1.2 2000/12/21 05:07:25 itojun Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcspbrk.c,v 1.3 2005/11/29 03:12:00 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+wchar_t *
+wcspbrk(s, set)
+       const wchar_t *s;
+       const wchar_t *set;
+{
+       const wchar_t *p;
+       const wchar_t *q;
+
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(set != NULL);
+
+       p = s;
+       while (*p) {
+               q = set;
+               while (*q) {
+                       if (*p == *q)
+                               return __UNCONST(p);
+                       q++;
+               }
+               p++;
+       }
+       return NULL;
+}
diff --git a/lib/nbsd_libc/string/wcsrchr.c b/lib/nbsd_libc/string/wcsrchr.c
new file mode 100644 (file)
index 0000000..f062cd2
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: wcsrchr.c,v 1.3 2005/11/29 03:12:00 christos Exp $     */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wcsrchr.c,v 1.2 2000/12/21 05:07:25 itojun Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcsrchr.c,v 1.3 2005/11/29 03:12:00 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+wchar_t *
+wcsrchr(s, c)
+       const wchar_t *s;
+       wchar_t c;
+{
+       const wchar_t *p;
+
+       _DIAGASSERT(s != NULL);
+
+       p = s;
+       while (*p)
+               p++;
+       while (s <= p) {
+               if (*p == c)
+                       return __UNCONST(p);
+               p--;
+       }
+       return NULL;
+}
diff --git a/lib/nbsd_libc/string/wcsspn.c b/lib/nbsd_libc/string/wcsspn.c
new file mode 100644 (file)
index 0000000..84f2a10
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: wcsspn.c,v 1.3 2001/09/21 16:09:15 yamt Exp $  */
+
+/*-
+ * Copyright (c)1999,2001 Citrus Project,
+ * 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.
+ *
+ *     $Citrus: xpg4dl/FreeBSD/lib/libc/string/wcsspn.c,v 1.3 2001/09/21 16:06:43 yamt Exp $
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcsspn.c,v 1.3 2001/09/21 16:09:15 yamt Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+size_t
+wcsspn(s, set)
+       const wchar_t *s;
+       const wchar_t *set;
+{
+       const wchar_t *p;
+       const wchar_t *q;
+
+       _DIAGASSERT(s != NULL);
+       _DIAGASSERT(set != NULL);
+
+       p = s;
+       while (*p) {
+               q = set;
+               while (*q) {
+                       if (*p == *q)
+                               break;
+                       q++;
+               }
+               if (!*q)
+                       goto done;
+               p++;
+       }
+
+done:
+       return (p - s);
+}
diff --git a/lib/nbsd_libc/string/wcsstr.c b/lib/nbsd_libc/string/wcsstr.c
new file mode 100644 (file)
index 0000000..b136c44
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: wcsstr.c,v 1.4 2005/11/29 03:12:00 christos Exp $      */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wcsstr.c,v 1.2 2000/12/21 05:07:25 itojun Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcsstr.c,v 1.4 2005/11/29 03:12:00 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+wchar_t *
+#ifdef WCSWCS
+wcswcs(big, little)
+#else
+wcsstr(big, little)
+#endif
+       const wchar_t *big;
+       const wchar_t *little;
+{
+       const wchar_t *p;
+       const wchar_t *q;
+       const wchar_t *r;
+
+       _DIAGASSERT(big != NULL);
+       _DIAGASSERT(little != NULL);
+
+       if (!*little)
+               return __UNCONST(big);
+       if (wcslen(big) < wcslen(little))
+               return NULL;
+
+       p = big;
+       q = little;
+       while (*p) {
+               q = little;
+               r = p;
+               while (*q) {
+                       if (*r != *q)
+                               break;
+                       q++;
+                       r++;
+               }
+               if (!*q)
+                       return __UNCONST(p);
+               p++;
+       }
+       return NULL;
+}
diff --git a/lib/nbsd_libc/string/wcstok.3 b/lib/nbsd_libc/string/wcstok.3
new file mode 100644 (file)
index 0000000..a181afe
--- /dev/null
@@ -0,0 +1,135 @@
+.\" $NetBSD: wcstok.3,v 1.6 2010/12/16 17:42:28 wiz Exp $
+.\"
+.\" Copyright (c) 1998 Softweyr LLC.  All rights reserved.
+.\"
+.\" strtok_r, from Berkeley strtok
+.\" Oct 13, 1998 by Wes Peters <wes@softweyr.com>
+.\"
+.\" Copyright (c) 1988, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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
+.\"    notices, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above
+.\"    copyright notices, this list of conditions and the following
+.\"    disclaimer in the documentation and/or other materials provided
+.\"    with the distribution.
+.\"
+.\" 3. All advertising materials mentioning features or use of this
+.\"    software must display the following acknowledgement:
+.\"
+.\"    This product includes software developed by Softweyr LLC, the
+.\"      University of California, Berkeley, and its contributors.
+.\"
+.\" 4. Neither the name of Softweyr LLC, 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 SOFTWEYR LLC, 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 SOFTWEYR LLC, 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.
+.\"
+.\" Original version ID:
+.\" FreeBSD: src/lib/libc/string/wcstok.3,v 1.4 2002/10/15 09:49:54 tjr Exp
+.\"
+.Dd October 3, 2002
+.Dt WCSTOK 3
+.Os
+.Sh NAME
+.Nm wcstok
+.Nd split wide-character string into tokens
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wchar.h
+.Ft wchar_t *
+.Fn wcstok "wchar_t * restrict str" "const wchar_t * restrict sep" "wchar_t ** restrict last"
+.Sh DESCRIPTION
+The
+.Fn wcstok
+function
+is used to isolate sequential tokens in a nul-terminated wide-character
+string,
+.Fa str .
+These tokens are separated in the string by at least one of the
+characters in
+.Fa sep .
+The first time that
+.Fn wcstok
+is called,
+.Fa str
+should be specified; subsequent calls, wishing to obtain further tokens
+from the same string, should pass a null pointer instead.
+The separator string,
+.Fa sep ,
+must be supplied each time, and may change between calls.
+The context pointer
+.Fa last
+must be provided on each call.
+.Pp
+The
+.Fn wcstok
+function is the wide-character counterpart of the
+.Fn strtok_r
+function.
+.Sh RETURN VALUES
+The
+.Fn wcstok
+function
+returns a pointer to the beginning of each subsequent token in the string,
+after replacing the token itself with a nul wide character (L'\e0').
+When no more tokens remain, a null pointer is returned.
+.Sh EXAMPLES
+The following code fragment splits a wide-character string on
+.Tn ASCII
+space, tab and newline characters and writes the tokens to
+standard output:
+.Bd -literal -offset indent
+const wchar_t *seps = L" \et\en";
+wchar_t *last, *tok, text[] = L" \enone\ettwo\et\etthree  \en";
+
+for (tok = wcstok(text, seps, &last); tok != NULL;
+    tok = wcstok(NULL, seps, &last))
+       wprintf(L"%ls\en", tok);
+.Ed
+.Sh SEE ALSO
+.Xr strtok 3 ,
+.Xr wcschr 3 ,
+.Xr wcscspn 3 ,
+.Xr wcspbrk 3 ,
+.Xr wcsrchr 3 ,
+.Xr wcsspn 3
+.Sh STANDARDS
+The
+.Fn wcstok
+function
+conforms to
+.St -isoC-99 .
+.Pp
+Some early implementations of
+.Fn wcstok
+omit the context pointer argument,
+.Fa last ,
+and maintain state across calls in a static variable like
+.Xr strtok 3
+does.
diff --git a/lib/nbsd_libc/string/wcstok.c b/lib/nbsd_libc/string/wcstok.c
new file mode 100644 (file)
index 0000000..ee97cb4
--- /dev/null
@@ -0,0 +1,104 @@
+/* $NetBSD: wcstok.c,v 1.3 2003/07/10 08:50:48 tshiozak Exp $ */
+
+/*-
+ * Copyright (c) 1998 Softweyr LLC.  All rights reserved.
+ *
+ * strtok_r, from Berkeley strtok
+ * Oct 13, 1998 by Wes Peters <wes@softweyr.com>
+ *
+ * Copyright (c) 1988, 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
+ *    notices, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notices, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Softweyr LLC, the
+ *      University of California, Berkeley, and its contributors.
+ * 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 SOFTWEYR LLC, 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 SOFTWEYR LLC, 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.
+ *
+ * Original version ID:
+ * FreeBSD: src/lib/libc/string/wcstok.c,v 1.1 2002/09/07 08:16:57 tjr Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wcstok.c,v 1.3 2003/07/10 08:50:48 tshiozak Exp $");
+#endif
+
+#include <assert.h>
+#include <wchar.h>
+
+wchar_t *
+wcstok(s, delim, last)
+       wchar_t * __restrict s;
+       const wchar_t * __restrict delim;
+       wchar_t ** __restrict last;
+{
+       const wchar_t *spanp;
+       wchar_t c, sc;
+       wchar_t *tok;
+
+       /* s may be NULL */
+       _DIAGASSERT(delim != NULL);
+       _DIAGASSERT(last != NULL);
+
+       if (s == NULL && (s = *last) == NULL)
+               return (NULL);
+
+       /*
+        * Skip (span) leading delimiters (s += wcsspn(s, delim), sort of).
+        */
+cont:
+       c = *s++;
+       for (spanp = delim; (sc = *spanp++) != L'\0';) {
+               if (c == sc)
+                       goto cont;
+       }
+
+       if (c == L'\0') {       /* no non-delimiter characters */
+               *last = NULL;
+               return (NULL);
+       }
+       tok = s - 1;
+
+       /*
+        * Scan token (scan for delimiters: s += wcscspn(s, delim), sort of).
+        * Note that delim must have one NUL; we stop if we see that, too.
+        */
+       for (;;) {
+               c = *s++;
+               spanp = delim;
+               do {
+                       if ((sc = *spanp++) == c) {
+                               if (c == L'\0')
+                                       s = NULL;
+                               else
+                                       s[-1] = L'\0';
+                               *last = s;
+                               return (tok);
+                       }
+               } while (sc != L'\0');
+       }
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/string/wcswcs.c b/lib/nbsd_libc/string/wcswcs.c
new file mode 100644 (file)
index 0000000..a22cf3f
--- /dev/null
@@ -0,0 +1,4 @@
+/* $NetBSD: wcswcs.c,v 1.1 2003/03/05 20:18:17 tshiozak Exp $ */
+
+#define WCSWCS
+#include "wcsstr.c"
diff --git a/lib/nbsd_libc/string/wcswidth.3 b/lib/nbsd_libc/string/wcswidth.3
new file mode 100644 (file)
index 0000000..b7a89a9
--- /dev/null
@@ -0,0 +1,64 @@
+.\" $NetBSD: wcswidth.3,v 1.2 2006/10/16 08:48:45 wiz Exp $
+.\" FreeBSD: src/lib/libc/string/wcswidth.3,v 1.2 2002/12/09 14:04:05 ru Exp
+.\"
+.\" Copyright (c) 2002 Tim J. Robbins
+.\" 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.
+.\"
+.\"
+.Dd August 20, 2002
+.Dt WCSWIDTH 3
+.Os
+.Sh NAME
+.Nm wcswidth
+.Nd "number of column positions in wide-character string"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wchar.h
+.Ft int
+.Fn wcswidth "const wchar_t *pwcs" "size_t n"
+.Sh DESCRIPTION
+The
+.Fn wcswidth
+function determines the number of column positions required for the first
+.Fa n
+characters of
+.Fa pwcs ,
+or until a nul wide character (L'\e0') is encountered.
+.Sh RETURN VALUES
+The
+.Fn wcswidth
+function returns 0 if
+.Fa pwcs
+is an empty string (L""),
+\-1 if a non-printing wide character is encountered,
+otherwise it returns the number of column positions occupied.
+.Sh SEE ALSO
+.Xr iswprint 3 ,
+.Xr wcwidth 3
+.Sh STANDARDS
+The
+.Fn wcswidth
+function conforms to
+.St -p1003.1-2001 .
diff --git a/lib/nbsd_libc/string/wmemchr.3 b/lib/nbsd_libc/string/wmemchr.3
new file mode 100644 (file)
index 0000000..0954f00
--- /dev/null
@@ -0,0 +1,162 @@
+.\"    $NetBSD: wmemchr.3,v 1.15 2010/12/16 17:42:28 wiz Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Chris Torek and the American National Standards Committee X3,
+.\" on Information Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strcpy.3     8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 1, 2009
+.Dt WMEMCHR 3
+.Os
+.Sh NAME
+.Nm wmemchr ,
+.Nm wmemcmp ,
+.Nm wmemcpy ,
+.Nm wmemmove ,
+.Nm wmemset ,
+.Nm wcscat ,
+.Nm wcschr ,
+.Nm wcscmp ,
+.Nm wcscpy ,
+.Nm wcscspn ,
+.Nm wcslcat ,
+.Nm wcslcpy ,
+.Nm wcslen ,
+.Nm wcsncat ,
+.Nm wcsncmp ,
+.Nm wcsncpy ,
+.Nm wcspbrk ,
+.Nm wcsrchr ,
+.Nm wcsspn ,
+.Nm wcsstr
+.Nm wcswcs
+.Nd wide-character string manipulation operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In wchar.h
+.Ft wchar_t *
+.Fn wmemchr "const wchar_t *s" "wchar_t c" "size_t n"
+.Ft int
+.Fn wmemcmp "const wchar_t *s1" "const wchar_t *s2" "size_t n"
+.Ft wchar_t *
+.Fn wmemcpy "wchar_t * restrict s1" "const wchar_t * restrict s2" "size_t n"
+.Ft wchar_t *
+.Fn wmemmove "wchar_t *s1" "const wchar_t *s2" "size_t n"
+.Ft wchar_t *
+.Fn wmemset "wchar_t *s" "wchar_t c" "size_t n"
+.Ft wchar_t *
+.Fn wcscat "wchar_t * restrict s1" "const wchar_t * restrict s2"
+.Ft wchar_t *
+.Fn wcschr "const wchar_t *s" "wchar_t c"
+.Ft int
+.Fn wcscmp "const wchar_t *s1" "const wchar_t *s2"
+.Ft wchar_t *
+.Fn wcscpy "wchar_t * restrict s1" "const wchar_t * restrict s2"
+.Ft size_t
+.Fn wcscspn "const wchar_t *s1" "const wchar_t *s2"
+.Ft size_t
+.Fn wcslcat "wchar_t *s1" "const wchar_t *s2" "size_t n"
+.Ft size_t
+.Fn wcslcpy "wchar_t *s1" "const wchar_t *s2" "size_t n"
+.Ft size_t
+.Fn wcslen "const wchar_t *s"
+.Ft wchar_t *
+.Fn wcsncat "wchar_t * restrict s1" "const wchar_t * restrict s2" "size_t n"
+.Ft int
+.Fn wcsncmp "const wchar_t *s1" "const wchar_t * s2" "size_t n"
+.Ft wchar_t *
+.Fn wcsncpy "wchar_t * restrict s1" "const wchar_t * restrict s2" "size_t n"
+.Ft wchar_t *
+.Fn wcspbrk "const wchar_t *s1" "const wchar_t *s2"
+.Ft wchar_t *
+.Fn wcsrchr "const wchar_t *s" "wchar_t c"
+.Ft size_t
+.Fn wcsspn "const wchar_t *s1" "const wchar_t *s2"
+.Ft wchar_t *
+.Fn wcsstr "const wchar_t *s1" "const wchar_t *s2"
+.Ft wchar_t *
+.Fn wcswcs "const wchar_t *s1" "const wchar_t *s2"
+.Sh DESCRIPTION
+These functions implement string manipulation operations over wide-character
+strings.
+For a detailed description, refer to the documents for the respective
+single-byte counterpart, such as
+.Xr memchr 3 .
+The
+.Fn wcswcs
+function is not a part of
+.St -isoC
+and
+.St -isoC-amd1 ,
+the
+.Fn wcsstr
+function is strongly recommended to be used.
+.Sh SEE ALSO
+.Xr memchr 3 ,
+.Xr memcmp 3 ,
+.Xr memcpy 3 ,
+.Xr memmove 3 ,
+.Xr memset 3 ,
+.Xr stpcpy 3 ,
+.Xr stpncpy 3 ,
+.Xr strcasecmp 3 ,
+.Xr strcat 3 ,
+.Xr strchr 3 ,
+.Xr strcmp 3 ,
+.Xr strcpy 3 ,
+.Xr strcspn 3 ,
+.Xr strdup 3 ,
+.Xr strlcat 3 ,
+.Xr strlcpy 3 ,
+.Xr strlen 3 ,
+.Xr strncat 3 ,
+.Xr strncmp 3 ,
+.Xr strncpy 3 ,
+.Xr strnlen 3 ,
+.Xr strpbrk 3 ,
+.Xr strrchr 3 ,
+.Xr strspn 3 ,
+.Xr strstr 3
+.Sh STANDARDS
+These functions conform to
+.St -isoC-99
+and were first introduced in
+.St -isoC-amd1 ,
+with the exception of
+.Fn wcslcat
+and
+.Fn wcslcpy ,
+which are extensions.
+The
+.Fn wcswcs
+function conforms to
+.St -xpg4.2 .
diff --git a/lib/nbsd_libc/string/wmemchr.c b/lib/nbsd_libc/string/wmemchr.c
new file mode 100644 (file)
index 0000000..899c1ae
--- /dev/null
@@ -0,0 +1,55 @@
+/*     $NetBSD: wmemchr.c,v 1.3 2005/11/29 03:12:00 christos Exp $     */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wmemchr.c,v 1.2 2000/12/20 14:08:31 itojun Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wmemchr.c,v 1.3 2005/11/29 03:12:00 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+wchar_t        *
+wmemchr(s, c, n)
+       const wchar_t *s;
+       wchar_t c;
+       size_t n;
+{
+       size_t i;
+
+       _DIAGASSERT(s != NULL);
+
+       for (i = 0; i < n; i++) {
+               if (*s == c)
+                       return __UNCONST(s);
+               s++;
+       }
+       return NULL;
+}
diff --git a/lib/nbsd_libc/string/wmemcmp.c b/lib/nbsd_libc/string/wmemcmp.c
new file mode 100644 (file)
index 0000000..d9c6eec
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: wmemcmp.c,v 1.6 2009/01/11 02:46:30 christos Exp $     */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wmemcmp.c,v 1.2 2000/12/20 14:08:31 itojun Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wmemcmp.c,v 1.6 2009/01/11 02:46:30 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+#include "runetype_local.h"
+
+int
+wmemcmp(s1, s2, n)
+       const wchar_t *s1;
+       const wchar_t *s2;
+       size_t n;
+{
+       size_t i;
+
+       _DIAGASSERT(s1 != NULL);
+       _DIAGASSERT(s2 != NULL);
+
+       for (i = 0; i < n; i++) {
+               if (*s1 != *s2) {
+                       /* wchar might be unsigned */
+                       return *(const __nbrune_t *)s1 >
+                              *(const __nbrune_t *)s2 ? 1 : -1;
+               }
+               s1++;
+               s2++;
+       }
+       return 0;
+}
diff --git a/lib/nbsd_libc/string/wmemcpy.c b/lib/nbsd_libc/string/wmemcpy.c
new file mode 100644 (file)
index 0000000..07a3f6f
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: wmemcpy.c,v 1.2 2001/01/03 14:29:37 lukem Exp $        */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wmemcpy.c,v 1.2 2000/12/20 14:08:31 itojun Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wmemcpy.c,v 1.2 2001/01/03 14:29:37 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <string.h>
+#include <wchar.h>
+
+wchar_t *
+wmemcpy(d, s, n)
+       wchar_t *d;
+       const wchar_t *s;
+       size_t n;
+{
+
+       _DIAGASSERT(d != NULL);
+       _DIAGASSERT(s != NULL);
+
+       return (wchar_t *)memcpy(d, s, n * sizeof(wchar_t));
+}
diff --git a/lib/nbsd_libc/string/wmemmove.c b/lib/nbsd_libc/string/wmemmove.c
new file mode 100644 (file)
index 0000000..d193e69
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: wmemmove.c,v 1.2 2001/01/03 14:29:37 lukem Exp $       */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wmemmove.c,v 1.2 2000/12/20 14:08:31 itojun Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wmemmove.c,v 1.2 2001/01/03 14:29:37 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <string.h>
+#include <wchar.h>
+
+wchar_t *
+wmemmove(d, s, n)
+       wchar_t *d;
+       const wchar_t *s;
+       size_t n;
+{
+
+       _DIAGASSERT(d != NULL);
+       _DIAGASSERT(s != NULL);
+
+       return (wchar_t *)memmove(d, s, n * sizeof(wchar_t));
+}
diff --git a/lib/nbsd_libc/string/wmemset.c b/lib/nbsd_libc/string/wmemset.c
new file mode 100644 (file)
index 0000000..c35e1d4
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: wmemset.c,v 1.2 2001/01/03 14:29:37 lukem Exp $        */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wmemset.c,v 1.2 2000/12/20 14:08:31 itojun Exp
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: wmemset.c,v 1.2 2001/01/03 14:29:37 lukem Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <assert.h>
+#include <wchar.h>
+
+wchar_t        *
+wmemset(s, c, n)
+       wchar_t *s;
+       wchar_t c;
+       size_t n;
+{
+       size_t i;
+       wchar_t *p;
+
+       _DIAGASSERT(s != NULL);
+
+       p = (wchar_t *)s;
+       for (i = 0; i < n; i++) {
+               *p = c;
+               p++;
+       }
+       return s;
+}
diff --git a/lib/nbsd_libc/sys/Lint___clone.c b/lib/nbsd_libc/sys/Lint___clone.c
new file mode 100644 (file)
index 0000000..3c718d4
--- /dev/null
@@ -0,0 +1,15 @@
+/* $NetBSD: Lint___clone.c,v 1.2 2003/01/18 11:32:58 thorpej Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Jason R. Thorpe, July 16, 2001.
+ */
+
+#include <sched.h>
+
+/*ARGSUSED*/
+pid_t
+__clone(int (*func)(void *), void *stack, int flags, void *arg)
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/sys/Lint___sigaction14.c b/lib/nbsd_libc/sys/Lint___sigaction14.c
new file mode 100644 (file)
index 0000000..d213869
--- /dev/null
@@ -0,0 +1,10 @@
+/* $NetBSD: Lint___sigaction14.c,v 1.1 2009/04/10 23:14:58 christos Exp $ */
+
+#include <signal.h>
+
+/*ARGSUSED*/
+int
+__sigaction14(int sig, const struct sigaction *nact, struct sigaction *oact)
+{
+       return 0;
+}
diff --git a/lib/nbsd_libc/sys/Lint___syscall.c b/lib/nbsd_libc/sys/Lint___syscall.c
new file mode 100644 (file)
index 0000000..e27ec69
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint___syscall.c,v 1.3 2003/01/18 11:32:58 thorpej Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <stdarg.h>
+#include <unistd.h>
+
+/*ARGSUSED*/
+quad_t
+__syscall(quad_t arg1, ...)
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/sys/Lint___vfork14.c b/lib/nbsd_libc/sys/Lint___vfork14.c
new file mode 100644 (file)
index 0000000..badeb40
--- /dev/null
@@ -0,0 +1,15 @@
+/* $NetBSD: Lint___vfork14.c,v 1.2 2000/06/14 06:49:10 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <unistd.h>
+
+/*ARGSUSED*/
+pid_t
+__vfork14()
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/sys/Lint_brk.c b/lib/nbsd_libc/sys/Lint_brk.c
new file mode 100644 (file)
index 0000000..19ae693
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint_brk.c,v 1.3 2000/06/14 06:49:10 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <unistd.h>
+
+/*ARGSUSED*/
+int
+brk(addr)
+       void *addr;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/sys/Lint_clone.c b/lib/nbsd_libc/sys/Lint_clone.c
new file mode 100644 (file)
index 0000000..b4fd98c
--- /dev/null
@@ -0,0 +1,15 @@
+/* $NetBSD: Lint_clone.c,v 1.2 2003/01/18 11:32:58 thorpej Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Jason R. Thorpe, July 16, 2001.
+ */
+
+#include <sched.h>
+
+/*ARGSUSED*/
+pid_t
+clone(int (*func)(void *), void *stack, int flags, void *arg)
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/sys/Lint_exect.c b/lib/nbsd_libc/sys/Lint_exect.c
new file mode 100644 (file)
index 0000000..799107a
--- /dev/null
@@ -0,0 +1,18 @@
+/* $NetBSD: Lint_exect.c,v 1.2 2000/06/14 06:49:10 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <unistd.h>
+
+/*ARGSUSED*/
+int
+exect(path, argv, envp)
+       const char *path;
+       char * const * argv;
+       char * const * envp;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/sys/Lint_getcontext.c b/lib/nbsd_libc/sys/Lint_getcontext.c
new file mode 100644 (file)
index 0000000..a4fc67c
--- /dev/null
@@ -0,0 +1,17 @@
+/*     $NetBSD: Lint_getcontext.c,v 1.2 2003/01/18 11:32:58 thorpej Exp $      */
+
+/*
+ * This file placed in the public domain.
+ * Klaus Klein, January 26, 1999.
+ */
+
+#include <ucontext.h>
+
+/*ARGSUSED*/
+int
+getcontext(ucp)
+       ucontext_t *ucp;
+{
+
+       return (0);
+}
diff --git a/lib/nbsd_libc/sys/Lint_pipe.c b/lib/nbsd_libc/sys/Lint_pipe.c
new file mode 100644 (file)
index 0000000..a86db16
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint_pipe.c,v 1.2 2000/06/14 06:49:10 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <unistd.h>
+
+/*ARGSUSED*/
+int
+pipe(filedes)
+       int filedes[2];
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/sys/Lint_ptrace.c b/lib/nbsd_libc/sys/Lint_ptrace.c
new file mode 100644 (file)
index 0000000..47232dd
--- /dev/null
@@ -0,0 +1,19 @@
+/* $NetBSD: Lint_ptrace.c,v 1.2 2000/06/14 06:49:10 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <unistd.h>
+
+/*ARGSUSED*/
+int
+ptrace(request, pid, addr, data)
+       int request;
+       pid_t pid;
+       caddr_t addr;
+       int data;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/sys/Lint_sbrk.c b/lib/nbsd_libc/sys/Lint_sbrk.c
new file mode 100644 (file)
index 0000000..e8275a6
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint_sbrk.c,v 1.3 2000/06/14 06:49:10 cgd Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <unistd.h>
+
+/*ARGSUSED*/
+void *
+sbrk(incr)
+       intptr_t incr;
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/sys/Lint_syscall.c b/lib/nbsd_libc/sys/Lint_syscall.c
new file mode 100644 (file)
index 0000000..b3ed785
--- /dev/null
@@ -0,0 +1,16 @@
+/* $NetBSD: Lint_syscall.c,v 1.4 2003/01/18 11:32:58 thorpej Exp $ */
+
+/*
+ * This file placed in the public domain.
+ * Chris Demetriou, November 5, 1997.
+ */
+
+#include <stdarg.h>
+#include <unistd.h>
+
+/*ARGSUSED*/
+int
+syscall(int arg1, ...)
+{
+       return (0);
+}
diff --git a/lib/nbsd_libc/sys/Makefile.inc b/lib/nbsd_libc/sys/Makefile.inc
new file mode 100644 (file)
index 0000000..8d3b279
--- /dev/null
@@ -0,0 +1,310 @@
+#      $NetBSD: Makefile.inc,v 1.204 2011/01/10 04:41:27 christos Exp $
+#      @(#)Makefile.inc        8.3 (Berkeley) 10/24/94
+
+# sys sources
+.PATH: ${ARCHDIR}/sys ${.CURDIR}/sys
+
+# modules with non-default implementations on at least one architecture:
+SRCS+= __clone.S __vfork14.S brk.S exect.S fork.S pipe.S \
+       getcontext.S \
+       ptrace.S sbrk.S shmat.S \
+       syscall.S __syscall.S __clone.S cerror.S
+
+# other sources shared with the kernel, used in syscalls
+SRCS+= cpuset.c
+
+_LSRC+=        Lint___clone.c Lint___vfork14.c Lint_brk.c Lint_clone.c \
+       Lint_getcontext.c Lint_exect.c Lint_pipe.c Lint_ptrace.c \
+       Lint_sbrk.c Lint___sigaction14.c Lint_syscall.c Lint___syscall.c \
+       LintSysNormal.c LintSysNoerr.c LintSysPseudoNoerr.c
+
+.if ${MKLINT} != "no"
+LSRCS+=                ${_LSRC}
+DPSRCS+=       ${_LSRC:MLintSys*.c}
+CLEANFILES+=   ${_LSRC:MLintSys*.c}
+.endif
+
+# glue to offer userland wrappers for some syscalls
+SRCS+= posix_fadvise.c posix_madvise.c sched.c sigqueue.c sigtimedwait.c \
+       sigwait.c sigwaitinfo.c statvfs.c swapon.c semctl.c 
+
+# glue to provide compatibility between GCC 1.X and 2.X and for compat
+# with old syscall interfaces.
+GLUE+= ftruncate.c lseek.c mmap.c pread.c preadv.c pwrite.c \
+       pwritev.c truncate.c ntp_adjtime.c
+
+GLUE50+= adjtime.c clock_settime.c settimeofday.c
+
+# 'glue' files might .c or .S depending on the architecture
+.for glue in ${GLUE}
+. if exists(${glue:.c=.S})
+# Build the ASM glue file
+SRCS+=${glue:.c=.S}
+. else
+.  if exists(__${glue:.c=.S})
+SRCS+=__${glue:.c=.S} ${glue}
+.  else
+# Build the C glue file
+SRCS+= ${glue}
+# and an asm entry for __<syscall>
+ASM_GLUE+= tmp_${glue:.c=.S}
+.  endif
+. endif
+.endfor
+
+# 'glue' files might .c or .S depending on the architecture
+.for glue in ${GLUE50}
+. if exists(${glue:.c=.S})
+# Build the ASM glue file
+SRCS+=${glue:.c=.S}
+. else
+.  if exists(__${glue:.c=}50.S)
+SRCS+=__${glue:.c=}50.S ${glue}
+.  else
+# Build the C glue file
+SRCS+= ${glue}
+# and an asm entry for __<syscall>
+ASM_GLUE+= tmp___${glue:.c=}50.S
+.  endif
+. endif
+.endfor
+
+# namespace purity wrappers
+SRCS+= _brk.c _fork.c _getcontext.c _pipe.c _sbrk.c
+
+# modules with default implementations on all architectures:
+ASM=   access.S acct.S \
+       bind.S \
+       chdir.S chflags.S chmod.S chown.S chroot.S __clock_getres50.S \
+               __clock_gettime50.S \
+       dup.S dup2.S  \
+       extattrctl.S \
+               extattr_delete_fd.S extattr_delete_file.S \
+               extattr_delete_link.S extattr_get_fd.S extattr_get_file.S \
+               extattr_get_link.S extattr_list_fd.S extattr_list_file.S \
+               extattr_list_link.S extattr_set_fd.S extattr_set_file.S \
+               extattr_set_link.S \
+       fchdir.S fchflags.S fchmod.S fchown.S fchroot.S \
+               __fhopen40.S __fhstat50.S __fhstatvfs140.S fktrace.S \
+               flock.S fpathconf.S __fstat50.S fstatvfs1.S __futimes50.S \
+       __getcwd.S __getdents30.S __getfh30.S getvfsstat.S getgroups.S\
+               __getitimer50.S __getlogin.S getpeername.S getpgid.S getpgrp.S \
+               getpriority.S getrlimit.S __getrusage50.S getsid.S \
+               getsockname.S getsockopt.S __gettimeofday50.S \
+       ioctl.S \
+       kqueue.S ktrace.S \
+               _ksem_close.S _ksem_destroy.S _ksem_getvalue.S _ksem_init.S \
+               _ksem_post.S _ksem_trywait.S _ksem_unlink.S _ksem_wait.S \
+               _ksem_open.S \
+       lchflags.S lchmod.S lchown.S lfs_bmapv.S lfs_markv.S lfs_segclean.S \
+               __lfs_segwait50.S link.S listen.S __lstat50.S __lutimes50.S \
+               _lwp_create.S _lwp_exit.S _lwp_kill.S ___lwp_park50.S \
+               _lwp_self.S _lwp_wait.S _lwp_unpark.S _lwp_unpark_all.S \
+               _lwp_suspend.S _lwp_continue.S _lwp_wakeup.S _lwp_detach.S \
+               _lwp_setprivate.S \
+               _lwp_setname.S _lwp_getname.S _lwp_ctl.S \
+       madvise.S mincore.S minherit.S mkdir.S mkfifo.S __mknod50.S \
+               mlock.S mlockall.S modctl.S __mount50.S mprotect.S \
+               __msgctl50.S msgget.S munlock.S munlockall.S munmap.S \
+       nfssvc.S __ntp_gettime50.S \
+       pathconf.S pmc_get_info.S pmc_control.S __posix_chown.S \
+               __posix_fchown.S __posix_lchown.S __posix_rename.S profil.S \
+       quotactl.S \
+       rasctl.S reboot.S recvfrom.S recvmsg.S rename.S revoke.S \
+               rmdir.S \
+       sa_register.S sa_stacks.S sa_enable.S sa_setconcurrency.S sa_yield.S \
+               sa_preempt.S semconfig.S semget.S semop.S \
+               sendmsg.S sendto.S setegid.S setcontext.S seteuid.S setgid.S \
+               setgroups.S __setitimer50.S __setlogin.S setpgid.S \
+               setpriority.S \
+               setregid.S setreuid.S setrlimit.S setsid.S setsockopt.S \
+               setuid.S __shmctl50.S shmdt.S shmget.S shutdown.S \
+               sigqueueinfo.S \
+               __sigaltstack14.S __sigpending14.S __sigaction_sigtramp.S \
+               ____sigtimedwait50.S __socket30.S socketpair.S __stat50.S \
+               statvfs1.S swapctl.S symlink.S __sysctl.S \
+       timer_create.S timer_delete.S __timer_gettime50.S timer_getoverrun.S \
+               ____semctl50.S __timer_settime50.S \
+       umask.S undelete.S unlink.S unmount.S __utimes50.S utrace.S uuidgen.S \
+       vadvise.S
+
+# modules with potentially non default implementations
+ASM_MD=        _lwp_getprivate.S mremap.S 
+
+.for f in ${ASM_MD}
+. if !exists(${f})
+   ASM+=       tmp_${f}
+. else
+   SRCS+=      ${f}
+. endif
+.endfor
+
+WEAKASM= accept.S __aio_suspend50.S close.S connect.S execve.S \
+       fcntl.S fdatasync.S fsync.S fsync_range.S __kevent50.S \
+       kill.S mq_receive.S mq_send.S __mq_timedreceive50.S __mq_timedsend50.S \
+       msgrcv.S msgsnd.S __msync13.S  __nanosleep50.S open.S poll.S \
+       __pollts50.S __pselect50.S read.S readlink.S \
+       readv.S _sched_setparam.S _sched_getparam.S _sched_setaffinity.S \
+       _sched_getaffinity.S sched_yield.S \
+       __select50.S __sigprocmask14.S __sigsuspend14.S sysarch.S \
+       __wait450.S write.S writev.S
+
+NOERR= getegid.S geteuid.S getgid.S getpid.S getppid.S getuid.S \
+       issetugid.S sync.S __posix_fadvise50.S
+
+PSEUDONOERR=   _exit.S
+
+SRCS+=         ${ASM} ${WEAKASM} ${NOERR} ${PSEUDONOERR} ${ASM_GLUE}
+CLEANFILES+=   ${ASM} ${WEAKASM} ${NOERR} ${PSEUDONOERR} ${ASM_GLUE}
+
+ASMDEPS=       ${.CURDIR}/sys/Makefile.inc ${ARCHDIR}/SYS.h \
+               ${DESTDIR}/usr/include/sys/syscall.h
+
+_LINTASM=      ${ASM:Nsa_*.S} ${WEAKASM:Nsa_*.S}
+
+${ASM}: ${ASMDEPS}
+       ${_MKTARGET_CREATE}
+       printf '#include "SYS.h"\nRSYSCALL(${.PREFIX:S/tmp_//})\n' >${.TARGET}
+
+${ASM_GLUE}: ${ASMDEPS}
+       ${_MKTARGET_CREATE}
+       printf '#include "SYS.h"\nPSEUDO(${.PREFIX:S/tmp_/__/},${.PREFIX:S/tmp_//})\n' >${.TARGET}
+
+${WEAKASM}: ${ASMDEPS}
+       ${_MKTARGET_CREATE}
+       printf '#include "SYS.h"\nWSYSCALL(${.PREFIX},_sys_${.PREFIX})\nWEAK_ALIAS(_${.PREFIX},_sys_${.PREFIX})\n' >${.TARGET}
+
+${NOERR}: ${ASMDEPS}
+       ${_MKTARGET_CREATE}
+       printf '#include "SYS.h"\nRSYSCALL_NOERROR(${.PREFIX})\n' >${.TARGET}
+
+${PSEUDONOERR}: ${ASMDEPS}
+       ${_MKTARGET_CREATE}
+       printf '#include "SYS.h"\nPSEUDO_NOERROR(${.PREFIX},${.PREFIX:S/_//})\n' >${.TARGET}
+       # add an _Exit alias to _exit
+       printf 'STRONG_ALIAS(${.PREFIX:S/e/E/},${.PREFIX})\n' >>${.TARGET}
+
+LintSysNormal.c: ${LIBCDIR}/sys/makelintstub \
+    ${DESTDIR}/usr/include/sys/syscall.h ${_LINTASM}
+       ${_MKTARGET_CREATE}
+       CPP=${CPP:Q} ${HOST_SH} ${LIBCDIR}/sys/makelintstub -o ${.TARGET} \
+           -s ${DESTDIR}/usr/include/sys/syscall.h ${_LINTASM:S/tmp_//}
+
+LintSysNoerr.c: ${LIBCDIR}/sys/makelintstub \
+    ${DESTDIR}/usr/include/sys/syscall.h
+       ${_MKTARGET_CREATE}
+       CPP=${CPP:Q} ${HOST_SH} ${LIBCDIR}/sys/makelintstub -o ${.TARGET} -n \
+           -s ${DESTDIR}/usr/include/sys/syscall.h ${NOERR}
+
+LintSysPseudoNoerr.c: ${LIBCDIR}/sys/makelintstub \
+    ${DESTDIR}/usr/include/sys/syscall.h
+       ${_MKTARGET_CREATE}
+       CPP=${CPP:Q} ${HOST_SH} ${LIBCDIR}/sys/makelintstub -o ${.TARGET} -p \
+           -s ${DESTDIR}/usr/include/sys/syscall.h ${PSEUDONOERR}
+
+MAN+=  accept.2 access.2 acct.2 adjtime.2 bind.2 brk.2 chdir.2 \
+       chflags.2 chmod.2 chown.2 chroot.2 clock_settime.2 clone.2 close.2 \
+       connect.2 dup.2 execve.2 _exit.2 extattr_get_file.2 \
+       fcntl.2 fdatasync.2 fhopen.2 \
+       flock.2 fork.2 fsync.2 getcontext.2 getdents.2 \
+       getfh.2 getvfsstat.2 getgid.2 getgroups.2 \
+       getitimer.2 getlogin.2 getpeername.2 getpgrp.2 getpid.2 \
+       getpriority.2 getrlimit.2 getrusage.2 getsid.2 getsockname.2 \
+       getsockopt.2 gettimeofday.2 getuid.2 intro.2 ioctl.2 issetugid.2 \
+       kill.2 kqueue.2 ktrace.2 \
+       lfs_bmapv.2 lfs_markv.2 lfs_segclean.2 lfs_segwait.2 \
+       link.2 listen.2 lseek.2 \
+       _lwp_create.2 _lwp_ctl.2 _lwp_detach.2 _lwp_exit.2 \
+       _lwp_self.2 _lwp_setname.2 \
+       _lwp_suspend.2 _lwp_wakeup.2 _lwp_wait.2 _lwp_kill.2 \
+       _lwp_getname.2 _lwp_getprivate.2 \
+       _lwp_park.2 _lwp_unpark.2 _lwp_unpark_all.2 \
+       mkdir.2 mkfifo.2 mknod.2 \
+       madvise.2 mincore.2 minherit.2 mlock.2 mlockall.2 mmap.2 modctl.2 \
+       mount.2 \
+       mprotect.2 mremap.2 msgctl.2 msgget.2 msgrcv.2 msgsnd.2 msync.2 \
+       munmap.2 nanosleep.2 nfssvc.2 ntp_adjtime.2 open.2 pathconf.2 pipe.2 \
+       pmc_control.2 poll.2 posix_fadvise.2 profil.2 ptrace.2 quotactl.2 \
+       rasctl.2 read.2 readlink.2 \
+       reboot.2 recv.2 rename.2 revoke.2 rmdir.2 \
+       select.2 semctl.2 \
+       semget.2 semop.2 send.2 setgroups.2 setpgid.2 setregid.2 \
+       setreuid.2 setsid.2 setuid.2 shmat.2 shmctl.2 shmget.2 \
+       shutdown.2 sigaction.2 sigaltstack.2 sigpending.2 \
+       sigprocmask.2 sigqueue.2 sigstack.2 sigsuspend.2 sigtimedwait.2 \
+       socket.2 \
+       socketpair.2 stat.2 statvfs.2 swapctl.2 swapon.3 symlink.2 \
+       sync.2 sysarch.2 syscall.2 timer_create.2 timer_delete.2 \
+       timer_settime.2 truncate.2 umask.2 undelete.2 \
+       unlink.2 utimes.2 utrace.2 uuidgen.2 vfork.2 wait.2 write.2
+
+MLINKS+=_exit.2 _Exit.2
+MLINKS+=brk.2 sbrk.2
+MLINKS+=clone.2 __clone.2
+MLINKS+=dup.2 dup2.2
+MLINKS+=chdir.2 fchdir.2
+MLINKS+=chflags.2 fchflags.2 chflags.2 lchflags.2
+MLINKS+=chmod.2 fchmod.2 chmod.2 lchmod.2
+MLINKS+=chown.2 fchown.2 chown.2 lchown.2
+MLINKS+=chroot.2 fchroot.2
+MLINKS+=clock_settime.2 clock_gettime.2
+MLINKS+=clock_settime.2 clock_getres.2
+MLINKS+=extattr_get_file.2 extattr_set_file.2 \
+       extattr_get_file.2 extattr_delete_file.2 \
+       extattr_get_file.2 extattr_list_file.2 \
+       extattr_get_file.2 extattr_get_fd.2 \
+       extattr_get_file.2 extattr_set_fd.2 \
+       extattr_get_file.2 extattr_delete_fd.2 \
+       extattr_get_file.2 extattr_list_fd.2 \
+       extattr_get_file.2 extattr_get_link.2 \
+       extattr_get_file.2 extattr_set_link.2 \
+       extattr_get_file.2 extattr_delete_link.2 \
+       extattr_get_file.2 extattr_list_link.2
+MLINKS+=fhopen.2 fhstat.2 fhopen.2 fhstatvfs.2 fhopen.2 fhstatvfs1.2
+MLINKS+=fsync.2 fsync_range.2
+MLINKS+=getcontext.2 setcontext.2
+MLINKS+=getgid.2 getegid.2
+MLINKS+=getitimer.2 setitimer.2
+MLINKS+=getlogin.2 setlogin.2
+MLINKS+=getlogin.2 getlogin_r.2
+MLINKS+=getpgrp.2 getpgid.2
+MLINKS+=getpid.2 getppid.2
+MLINKS+=getpriority.2 setpriority.2
+MLINKS+=getrlimit.2 setrlimit.2
+MLINKS+=getsockopt.2 setsockopt.2
+MLINKS+=gettimeofday.2 settimeofday.2
+MLINKS+=getuid.2 geteuid.2
+MLINKS+=intro.2 errno.2
+MLINKS+=kqueue.2 kevent.2
+MLINKS+=ktrace.2 fktrace.2
+MLINKS+=lseek.2 seek.2
+MLINKS+=_lwp_suspend.2 _lwp_continue.2
+MLINKS+=_lwp_getprivate.2 _lwp_setprivate.2
+MLINKS+=madvise.2 posix_madvise.2
+MLINKS+=mlock.2 munlock.2
+MLINKS+=mlockall.2 munlockall.2
+MLINKS+=mount.2 unmount.2
+MLINKS+=ntp_adjtime.2 ntp_gettime.2
+MLINKS+=pathconf.2 fpathconf.2
+MLINKS+=pmc_control.2 pmc_get_info.2
+MLINKS+=poll.2 pollts.2
+MLINKS+=read.2 readv.2 read.2 pread.2 read.2 preadv.2
+MLINKS+=recv.2 recvfrom.2 recv.2 recvmsg.2
+MLINKS+=select.2 pselect.2
+MLINKS+=send.2 sendmsg.2 send.2 sendto.2
+MLINKS+=setpgid.2 setpgrp.2
+MLINKS+=setuid.2 setegid.2 setuid.2 seteuid.2 setuid.2 setgid.2
+MLINKS+=shmat.2 shmdt.2
+MLINKS+=timer_settime.2 timer_gettime.2 timer_settime.2 timer_getoverrun.2
+MLINKS+=sigqueue.2 sigqueueinfo.2
+MLINKS+=sigtimedwait.2 sigwaitinfo.2
+MLINKS+=sigtimedwait.2 sigwait.2
+MLINKS+=stat.2 fstat.2 stat.2 lstat.2
+MLINKS+=statvfs.2 fstatvfs.2
+MLINKS+=statvfs.2 statvfs1.2
+MLINKS+=statvfs.2 fstatvfs1.2
+MLINKS+=syscall.2 __syscall.2
+MLINKS+=truncate.2 ftruncate.2
+MLINKS+=utimes.2 futimes.2 utimes.2 lutimes.2
+MLINKS+=wait.2 wait3.2 wait.2 wait4.2 wait.2 waitpid.2
+MLINKS+=write.2 writev.2 write.2 pwrite.2 write.2 pwritev.2
diff --git a/lib/nbsd_libc/sys/_brk.c b/lib/nbsd_libc/sys/_brk.c
new file mode 100644 (file)
index 0000000..b0eb0b2
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: _brk.c,v 1.6 2009/10/21 01:07:45 snj Exp $     */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _brk.c,v 1.6 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_brk, brk)
+#else
+
+#include <unistd.h>
+int    _brk(void *);
+
+int
+brk(void *addr)
+{
+
+       return _brk(addr);
+}
+#endif
diff --git a/lib/nbsd_libc/sys/_exit.2 b/lib/nbsd_libc/sys/_exit.2
new file mode 100644 (file)
index 0000000..42b95bb
--- /dev/null
@@ -0,0 +1,123 @@
+.\"    $NetBSD: _exit.2,v 1.18 2003/09/08 17:54:34 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)_exit.2    8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 23, 2002
+.Dt EXIT 2
+.Os
+.Sh NAME
+.Nm _Exit, _exit
+.Nd terminate the calling process
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdlib.h
+.Ft void
+.Fn _Exit "int status"
+.In unistd.h
+.Ft void
+.Fn _exit "int status"
+.Sh DESCRIPTION
+The
+.Fn _Exit
+and
+.Fn _exit
+functions are equivalent.
+They each terminate a process with the following consequences:
+.Bl -bullet
+.It
+All of the descriptors open in the calling process are closed.
+This may entail delays, for example, waiting for output to drain;
+a process in this state may not be killed, as it is already dying.
+.It
+If the parent process of the calling process has an outstanding
+.Xr wait 2
+call
+or catches the
+.Dv SIGCHLD
+signal,
+it is notified of the calling process's termination and
+the
+.Em status
+is set as defined by
+.Xr wait 2 .
+.It
+The parent process-ID of all of the calling process's existing child
+processes are set to 1; the initialization process
+(see the DEFINITIONS section of
+.Xr intro 2 )
+inherits each of these processes.
+.It
+If the termination of the process causes any process group
+to become orphaned (usually because the parents of all members
+of the group have now exited; see
+.Dq orphaned process group
+in
+.Xr intro 2 ) ,
+and if any member of the orphaned group is stopped,
+the
+.Dv SIGHUP
+signal and the
+.Dv SIGCONT
+signal are sent to all members of the newly-orphaned process group.
+.It
+If the process is a controlling process (see
+.Xr intro 2 ) ,
+the
+.Dv SIGHUP
+signal is sent to the foreground process group of the controlling terminal,
+and all current access to the controlling terminal is revoked.
+.El
+.Pp
+Most C programs call the library routine
+.Xr exit 3 ,
+which flushes buffers, closes streams, unlinks temporary files, etc.,
+before
+calling
+.Fn _exit .
+.Sh RETURN VALUES
+.Fn _Exit
+and
+.Fn _exit
+can never return.
+.Sh SEE ALSO
+.Xr fork 2 ,
+.Xr sigaction 2 ,
+.Xr wait 2 ,
+.Xr exit 3
+.Sh STANDARDS
+The
+.Fn _exit
+function conforms to
+.St -p1003.1-90 .
+The
+.Fn _Exit
+function conforms to
+.St -isoC-99 .
diff --git a/lib/nbsd_libc/sys/_fork.c b/lib/nbsd_libc/sys/_fork.c
new file mode 100644 (file)
index 0000000..34a6290
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: _fork.c,v 1.5 2009/10/21 01:07:45 snj Exp $    */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _fork.c,v 1.5 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_fork, fork)
+#else
+
+#include <unistd.h>
+pid_t  _fork(void);
+
+pid_t
+fork(void)
+{
+
+       return _fork();
+}
+#endif
diff --git a/lib/nbsd_libc/sys/_getcontext.c b/lib/nbsd_libc/sys/_getcontext.c
new file mode 100644 (file)
index 0000000..76fd705
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: _getcontext.c,v 1.5 2009/10/21 01:07:45 snj Exp $      */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _getcontext.c,v 1.5 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef __indr_reference
+__indr_reference(_getcontext, getcontext)
+#else
+#error requires either weak aliases or indirect references!
+#endif
diff --git a/lib/nbsd_libc/sys/_lwp_create.2 b/lib/nbsd_libc/sys/_lwp_create.2
new file mode 100644 (file)
index 0000000..708cac1
--- /dev/null
@@ -0,0 +1,100 @@
+.\"    $NetBSD: _lwp_create.2,v 1.4 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, 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.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 13, 2003
+.Dt _LWP_CREATE 2
+.Os
+.Sh NAME
+.Nm _lwp_create
+.Nd create a new light-weight process
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft int
+.Fn _lwp_create "ucontext_t *context" "unsigned long flags" "lwpid_t *new_lwp"
+.Sh DESCRIPTION
+.Fn _lwp_create
+causes creation of a new light-weight process, or LWP, and adds it to the
+current process.
+The
+.Fa context
+argument specifies the initial execution context for the new LWP including
+signal mask, stack, and machine registers.
+.Pp
+The following flags affect the creation of the new LWP:
+.Bl -tag -width LWP_SUSPENDED
+.It LWP_DETACHED
+The LWP is created detached.
+The resources associated with a detached LWP will be automatically
+reclaimed by the system when the LWP exits.
+Otherwise, a terminated LWP's resources will not be reclaimed until
+its status is reported to another LWP via
+.Xr _lwp_wait 2 .
+.It LWP_SUSPENDED
+The LWP is created suspended, and will not begin execution until
+it is resumed by another LWP via
+.Xr _lwp_continue 2 .
+.\" __LWP_ASLWP is not yet implemented by the NetBSD kernel.
+.El
+.Pp
+The LWP ID of the new LWP is stored in the location pointed to by
+.Fa new_lwp .
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn _lwp_create
+returns a value of 0.
+Otherwise, an error code is returned to indicate the error.
+.Sh ERRORS
+.Fn _lwp_create
+will fail and no LWP will be created if:
+.Bl -tag -width [EAGAIN]
+.It Bq Er EAGAIN
+The system-imposed limit on the total
+number of LWPs under execution would be exceeded.
+This limit is configuration-dependent.
+.It Bq Er ENOMEM
+There is insufficient swap space for the new LWP.
+.It Bq Er EFAULT
+The address pointed to by
+.Fa context
+or
+.Fa new_lwp
+is outside the process's allocated address space.
+.El
+.Sh SEE ALSO
+.Xr _lwp_continue 2 ,
+.Xr _lwp_exit 2 ,
+.Xr _lwp_wait 2 ,
+.Xr _lwp_makecontext 3
+.Sh HISTORY
+The
+.Fn _lwp_create
+system call first appeared in
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/sys/_lwp_ctl.2 b/lib/nbsd_libc/sys/_lwp_ctl.2
new file mode 100644 (file)
index 0000000..cb6e066
--- /dev/null
@@ -0,0 +1,96 @@
+.\"     $NetBSD: _lwp_ctl.2,v 1.3 2009/02/17 18:51:56 njoly Exp $
+.\"
+.\" Copyright (c)2007 YAMAMOTO Takashi,
+.\" 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.
+.\"
+.\" ------------------------------------------------------------
+.Dd May 5, 2008
+.Dt _LWP_CTL 2
+.Os
+.Sh NAME
+.Nm _lwp_ctl
+.Nd prepare per-LWP communication area between kernel and userland
+.\" ------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ------------------------------------------------------------
+.Sh SYNOPSIS
+.In lwp.h
+.Ft int
+.Fn _lwp_ctl "int features" "struct lwpctl **address"
+.\" ------------------------------------------------------------
+.Sh DESCRIPTION
+.Fn _lwp_ctl
+prepares per-LWP communication area for the calling LWP,
+and maps it into the calling process' address space.
+It takes the following arguments.
+.Bl -tag -width features
+.It Fa features
+The bitwise-OR of the following flags.
+.Bl -tag -width LWPCTL_FEATURE_CURCPU
+.It Dv LWPCTL_FEATURE_CURCPU
+Request lc_curcpu.
+.It Dv LWPCTL_FEATURE_PCTR
+Request lc_pctr.
+.El
+.It Fa address
+The address to store a pointer to lwpctl structure for the calling LWP.
+.El
+.Pp
+The per-LWP communication area is described by an lwpctl structure.
+It has following members, depending on
+.Fa features .
+.Bl -tag -width int_lc_curcpu
+.It int lc_curcpu
+The integral identifier of the CPU on which the LWP is running,
+or
+.Dv LWPCTL_CPU_NONE
+when the LWP is not running on any CPU.
+It's updated by the kernel and should be considered as read-only for
+userland.
+It's available only if requested with the
+.Dv LWPCTL_FEATURE_CURCPU
+flag.
+.It int lc_pctr
+The integer which is incremented on every context switches to the LWP.
+It can be used to detect preemption of the LWP.
+(thus its name "preemption counter".)
+It's updated by the kernel and should be considered as read-only for
+userland.
+It's available only if requested with the
+.Dv LWPCTL_FEATURE_PCTR
+flag.
+.El
+.\" ------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn _lwp_ctl
+returns 0 on success.
+Otherwise, \-1 is returned and
+.Va errno
+is set to indicate the error.
+.\" ------------------------------------------------------------
+.\".Sh ERRORS
+.\" ------------------------------------------------------------
+.Sh SEE ALSO
+.Xr errno 2
diff --git a/lib/nbsd_libc/sys/_lwp_detach.2 b/lib/nbsd_libc/sys/_lwp_detach.2
new file mode 100644 (file)
index 0000000..6c9f01f
--- /dev/null
@@ -0,0 +1,75 @@
+.\"    $NetBSD: _lwp_detach.2,v 1.4 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2003, 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, Inc, and by Andrew Doran.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 20, 2007
+.Dt _LWP_DETACH 2
+.Os
+.Sh NAME
+.Nm _lwp_detach
+.Nd detach a light-weight process
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft int
+.Fn _lwp_detach "lwpid_t lwp"
+.Sh DESCRIPTION
+.Fn _lwp_detach
+causes a light-weight process to become detached, having the same
+effect as if the LWP was created with the
+.Dv LWP_DETACHED
+flag.
+.Pp
+The resources associated with a detached LWP will be automatically
+reclaimed by the system when the LWP exits.
+Conversely, an attached LWP's resources will not be reclaimed until
+its status is reported to another LWP via
+.Xr _lwp_wait 2 .
+.Sh RETURN VALUES
+A 0 value indicates that the call succeeded.
+A \-1 return value indicates an error occurred and
+.Va errno
+is set to indicate the reason.
+.Sh ERRORS
+.Bl -tag -width [EINVAL]
+.It Bq Er EINVAL
+The LWP is already detached.
+.It Bq Er ESRCH
+No LWP can be found in the current process corresponding to that
+specified by
+.Fa lwp .
+.El
+.Sh SEE ALSO
+.Xr _lwp_create 2 ,
+.Xr _lwp_wait 2
+.Sh HISTORY
+The
+.Fn _lwp_detach
+system call first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/sys/_lwp_exit.2 b/lib/nbsd_libc/sys/_lwp_exit.2
new file mode 100644 (file)
index 0000000..08f78c1
--- /dev/null
@@ -0,0 +1,61 @@
+.\"    $NetBSD: _lwp_exit.2,v 1.5 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, 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.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 13, 2003
+.Dt _LWP_EXIT 2
+.Os
+.Sh NAME
+.Nm _lwp_exit
+.Nd terminate the calling light-weight process
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft void
+.Fn _lwp_exit void
+.Sh DESCRIPTION
+.Fn _lwp_exit
+terminates the calling LWP.
+If it is the last LWP in the process, the process exits with a status of 0.
+If the LWP was not created in a detached state, then the system will not
+reclaim its LWP ID until its status is reported to another LWP in the process
+via
+.Xr _lwp_wait 2 .
+.Sh RETURN VALUES
+.Fn _lwp_exit
+can never return.
+.Sh SEE ALSO
+.Xr _exit 2 ,
+.Xr _lwp_create 2 ,
+.Xr _lwp_wait 2
+.Sh HISTORY
+The
+.Fn _lwp_exit
+system call first appeared in
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/sys/_lwp_getname.2 b/lib/nbsd_libc/sys/_lwp_getname.2
new file mode 100644 (file)
index 0000000..486af3e
--- /dev/null
@@ -0,0 +1,71 @@
+.\"     $NetBSD: _lwp_getname.2,v 1.2 2009/05/18 14:49:35 wiz Exp $
+.\"
+.\" Copyright (c)2007 YAMAMOTO Takashi,
+.\" 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.
+.\"
+.\" ------------------------------------------------------------
+.Dd December 15, 2007
+.Dt _LWP_GETNAME 2
+.Os
+.Sh NAME
+.Nm _lwp_getname
+.Nd get descriptive name of an LWP
+.\" ------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ------------------------------------------------------------
+.Sh SYNOPSIS
+.In lwp.h
+.Ft int
+.Fn _lwp_getname "lwpid_t target" "char *name" "size_t len"
+.\" ------------------------------------------------------------
+.Sh DESCRIPTION
+.Fn _lwp_getname
+gets the descriptive name of the LWP.
+It takes the following arguments.
+.Bl -tag -width target
+.It Fa target
+The LWP whose descriptive name will be obtained.
+.It Fa name
+The buffer to be filled with the descriptive name of the LWP.
+.It Fa len
+The size of the buffer
+.Fa name
+in bytes.
+.El
+.\" ------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn _lwp_getname
+returns 0 on success.
+Otherwise, \-1 is returned and
+.Va errno
+is set to indicate the error.
+.\" ------------------------------------------------------------
+.\".Sh ERRORS
+.\" ------------------------------------------------------------
+.Sh SEE ALSO
+.Xr ps 1 ,
+.Xr top 1 ,
+.Xr _lwp_setname 2 ,
+.Xr errno 2
diff --git a/lib/nbsd_libc/sys/_lwp_getprivate.2 b/lib/nbsd_libc/sys/_lwp_getprivate.2
new file mode 100644 (file)
index 0000000..528b625
--- /dev/null
@@ -0,0 +1,68 @@
+.\"    $NetBSD: _lwp_getprivate.2,v 1.4 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, 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.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 16, 2003
+.Dt _LWP_GETPRIVATE 2
+.Os
+.Sh NAME
+.Nm _lwp_getprivate ,
+.Nm _lwp_setprivate
+.Nd get and set light-weight process private data
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft void *
+.Fn _lwp_getprivate void
+.Ft void
+.Fn _lwp_setprivate "void *ptr"
+.Sh DESCRIPTION
+.Fn _lwp_setprivate
+stores the pointer to private data
+.Fa ptr
+in a location private to the LWP.
+.Pp
+.Fn _lwp_getprivate
+returns the pointer to private data for the LWP.
+.Sh ERRORS
+The
+.Fn _lwp_getprivate
+and
+.Fn _lwp_setprivate
+functions are always successful, and no return value is reserved to indicate
+an error.
+.Sh SEE ALSO
+.Xr _lwp_makecontext 3
+.Sh HISTORY
+The
+.Fn _lwp_getprivate
+and
+.Fn _lwp_setprivate
+system calls first appeared in
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/sys/_lwp_kill.2 b/lib/nbsd_libc/sys/_lwp_kill.2
new file mode 100644 (file)
index 0000000..8b75445
--- /dev/null
@@ -0,0 +1,87 @@
+.\"    $NetBSD: _lwp_kill.2,v 1.4 2009/06/24 22:19:14 zafer Exp $
+.\"
+.\" Copyright (c) 2003, 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, Inc, and by Andrew Doran.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 20, 2007
+.Dt _LWP_KILL 2
+.Os
+.Sh NAME
+.Nm _lwp_kill
+.Nd send a signal to a light-weight process
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft int
+.Fn _lwp_kill "lwpid_t lwp" "int sig"
+.Sh DESCRIPTION
+.Fn _lwp_kill
+sends the signal specified by
+.Fa sig
+to the light-weight process specified by
+.Fa lwp .
+If the
+.Fa sig
+argument is given as 0 (zero),
+.Nm
+will test for the existence of the target LWP, but will take no further
+action.
+.Pp
+Job control signals and uncatchable signals can not be directed to a specific
+LWP: if posted with
+.Nm ,
+they will affect all LWPs in the process.
+.Pp
+Signals will be posted successfully to suspended LWPs, but will not be
+handled further until the LWP has been continued.
+.Sh RETURN VALUES
+A 0 value indicates that the call succeeded.
+A \-1 return value indicates an error occurred and
+.Va errno
+is set to indicate the reason.
+.Sh ERRORS
+.Bl -tag -width [EINVAL]
+.It Bq Er EINVAL
+.Fa sig
+is not a valid signal number.
+.It Bq Er ESRCH
+No LWP can be found in the current process corresponding to that
+specified by
+.Fa lwp .
+.El
+.Sh SEE ALSO
+.Xr _lwp_continue 2 ,
+.Xr _lwp_suspend 2 ,
+.Xr kill 2 ,
+.Xr sigaction 2 ,
+.Xr signal 7
+.Sh HISTORY
+The
+.Fn _lwp_kill
+system call first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/sys/_lwp_park.2 b/lib/nbsd_libc/sys/_lwp_park.2
new file mode 100644 (file)
index 0000000..e707ee1
--- /dev/null
@@ -0,0 +1,146 @@
+.\"    $NetBSD: _lwp_park.2,v 1.7 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2003, 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, Inc, and by Andrew Doran.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd September 25, 2007
+.Dt _LWP_PARK 2
+.Os
+.Sh NAME
+.Nm _lwp_park
+.Nd wait interruptably in the kernel
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft int
+.Fn _lwp_park "const struct timespec *abstime" "lwpid_t unpark" "const void *hint" "const void *unparkhint"
+.Sh DESCRIPTION
+.Fn _lwp_park
+can be used to synchronize access to resources among multiple light-weight
+processes.
+It causes the calling LWP to wait interruptably in the kernel, until one
+of the following conditions is met:
+.Bl -bullet
+.It
+The
+.Fa abstime
+argument is non-NULL, and the absolute UTC time it specifies has passed.
+.It
+The LWP receives a directed signal posted using
+.Fn _lwp_kill ,
+or is elected to handle a signal on behalf of its containing process.
+.It
+The LWP is awoken by another LWP in the same process that has made
+a call to
+.Fn _lwp_wakeup .
+.It
+The LWP is awoken by another LWP in the same process that has made
+a call to
+.Fn _lwp_unpark
+or
+.Fn _lwp_unpark_all .
+.El
+.Pp
+The preferred method to awaken an LWP sleeping as a result of a call
+to
+.Fn _lwp_park
+is to make a call to
+.Fn _lwp_unpark ,
+or
+.Fn _lwp_unpark_all .
+The
+.Fn _lwp_wakeup
+system call is a more general facility, and requires more resources
+to execute.
+.Pp
+The optional
+.Fa hint
+argument specifies the address of object upon which the LWP is
+synchronizing.
+When the
+.Fa hint
+value is matched between calls to
+.Fn _lwp_park
+and
+.Fn _lwp_unpark
+or
+.Fn _lwp_unpark_all ,
+it may reduce the time necessary for the system to resume execution
+of waiting LWPs.
+.Pp
+The
+.Fa unpark
+and
+.Fa unparkhint
+arguments can be used to fold a park operation and unpark operation into a
+single system call.
+If
+.Fa unpark
+is non-zero, the system will behave as if the following call had been made
+before the calling thread begins to wait:
+.Bd -literal
+       _lwp_unpark(unpark, unparkhint);
+.Ed
+.Sh RETURN VALUES
+.Fn _lwp_park
+may return a value of 0.
+Otherwise, \-1 is returned and
+.Va errno
+is set to provide more information.
+.Sh ERRORS
+.Bl -tag -width [EINVAL]
+.It Bq Er EALREADY
+A request was made to wake the LWP before it began to wait in
+the kernel.
+.It Bq Er EINTR
+The LWP has been awoken by a signal or by a call to one of the
+following functions:
+.Fn _lwp_unpark ,
+.Fn _lwp_unpark_all ,
+.Fn _lwp_wakeup .
+.It Bq Er EINVAL
+The time value specified by
+.Fa abstime
+is invalid.
+.It Bq Er ESRCH
+No LWP can be found in the current process corresponding to
+.Fa unpark .
+.It Bq Er ETIMEDOUT
+The UTC time specified by
+.Fa abstime
+has passed.
+.El
+.Sh SEE ALSO
+.Xr _lwp_unpark 2 ,
+.Xr _lwp_unpark_all 2 ,
+.Xr _lwp_wakeup 2
+.Sh HISTORY
+The
+.Fn _lwp_park
+system call first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/sys/_lwp_self.2 b/lib/nbsd_libc/sys/_lwp_self.2
new file mode 100644 (file)
index 0000000..fe43b90
--- /dev/null
@@ -0,0 +1,56 @@
+.\"    $NetBSD: _lwp_self.2,v 1.4 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, 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.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 13, 2003
+.Dt _LWP_SELF 2
+.Os
+.Sh NAME
+.Nm _lwp_self
+.Nd get light-weight process identification
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft lwpid_t
+.Fn _lwp_self void
+.Sh DESCRIPTION
+.Fn _lwp_self
+returns the LWP ID of the calling LWP.
+.Sh ERRORS
+The
+.Fn _lwp_self
+function is always successful, and no return value is reserved to indicate
+an error.
+.Sh SEE ALSO
+.Xr _lwp_create 2
+.Sh HISTORY
+The
+.Fn _lwp_self
+system call first appeared in
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/sys/_lwp_setname.2 b/lib/nbsd_libc/sys/_lwp_setname.2
new file mode 100644 (file)
index 0000000..969e6f1
--- /dev/null
@@ -0,0 +1,71 @@
+.\"     $NetBSD: _lwp_setname.2,v 1.2 2009/05/18 14:50:03 wiz Exp $
+.\"
+.\" Copyright (c)2007 YAMAMOTO Takashi,
+.\" 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.
+.\"
+.\" ------------------------------------------------------------
+.Dd December 15, 2007
+.Dt _LWP_SETNAME 2
+.Os
+.Sh NAME
+.Nm _lwp_setname
+.Nd set descriptive name of an LWP
+.\" ------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ------------------------------------------------------------
+.Sh SYNOPSIS
+.In lwp.h
+.Ft int
+.Fn _lwp_setname "lwpid_t target" "const char *name"
+.\" ------------------------------------------------------------
+.Sh DESCRIPTION
+.Fn _lwp_setname
+sets the descriptive name of the LWP.
+It takes the following arguments.
+.Bl -tag -width target
+.It Fa target
+The LWP whose descriptive name will be set.
+.It Fa name
+The string to be used as the descriptive name of the LWP.
+.El
+.Pp
+The name is used by
+.Xr top 1
+when showing LWPs, for example.
+.\" ------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn _lwp_setname
+returns 0 on success.
+Otherwise, \-1 is returned and
+.Va errno
+is set to indicate the error.
+.\" ------------------------------------------------------------
+.\".Sh ERRORS
+.\" ------------------------------------------------------------
+.Sh SEE ALSO
+.Xr ps 1 ,
+.Xr top 1 ,
+.Xr _lwp_getname 2 ,
+.Xr errno 2
diff --git a/lib/nbsd_libc/sys/_lwp_suspend.2 b/lib/nbsd_libc/sys/_lwp_suspend.2
new file mode 100644 (file)
index 0000000..0f28e5c
--- /dev/null
@@ -0,0 +1,94 @@
+.\"    $NetBSD: _lwp_suspend.2,v 1.4 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, 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.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 13, 2003
+.Dt _LWP_SUSPEND 2
+.Os
+.Sh NAME
+.Nm _lwp_suspend ,
+.Nm _lwp_continue
+.Nd suspend or continue a light-weight process
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft int
+.Fn _lwp_suspend "lwpid_t lwp"
+.Ft int
+.Fn _lwp_continue "lwpid_t lwp"
+.Sh DESCRIPTION
+.Fn _lwp_suspend
+suspends execution of the LWP specified by
+.Fa lwp .
+Once an LWP is suspended, subsequent calls to
+.Fn _lwp_suspend
+have no effect.
+The only way to resume execution of a suspended LWP is via
+.Fn _lwp_continue .
+.Pp
+.Fn _lwp_continue
+resumes execution of the LWP specified by
+.Fa lwp .
+Once an LWP is resumed, subsequent calls to
+.Fn _lwp_continue
+have no effect.
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn _lwp_suspend
+and
+.Fn _lwp_continue
+return a value of 0.
+Otherwise, an error code is returned to indicate the error.
+.Sh ERRORS
+.Fn _lwp_suspend
+and
+.Fn _lwp_continue
+will fail if:
+.Bl -tag -width [EDEADLK]
+.It Bq Er ESRCH
+No LWP can be found in the current process corresponding to that
+specified by
+.Fa lwp .
+.El
+.Pp
+.Fn _lwp_suspend
+will fail if:
+.Bl -tag -width [EDEADLK]
+.It Bq Er EDEADLK
+The LWP specified by
+.Fa lwp
+is the only LWP in the process.
+.El
+.Sh SEE ALSO
+.Xr _lwp_create 2
+.Sh HISTORY
+The
+.Fn _lwp_create
+system call first appeared in
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/sys/_lwp_unpark.2 b/lib/nbsd_libc/sys/_lwp_unpark.2
new file mode 100644 (file)
index 0000000..840da0c
--- /dev/null
@@ -0,0 +1,79 @@
+.\"    $NetBSD: _lwp_unpark.2,v 1.4 2010/11/02 20:49:47 skrll Exp $
+.\"
+.\" Copyright (c) 2003, 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, Inc, and by Andrew Doran.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 20, 2007
+.Dt _LWP_UNPARK 2
+.Os
+.Sh NAME
+.Nm _lwp_unpark
+.Nd resume execution of a waiting LWP
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft int
+.Fn _lwp_unpark "lwpid_t lwp" "const void *hint"
+.Sh DESCRIPTION
+.Fn _lwp_unpark
+resumes execution of the light-weight process
+.Fa lwp .
+.Pp
+The target LWP is assumed to be waiting in the kernel as a result of a
+call to
+.Fn _lwp_park .
+If the target LWP is not currently waiting, it will return immediately
+upon the next call to
+.Fn _lwp_park .
+.Pp
+See
+.Xr _lwp_park 2
+for a description of the
+.Fa hint
+argument.
+.Sh RETURN VALUES
+A 0 value indicates that the call succeeded.
+A \-1 return value indicates an error occurred and
+.Va errno
+is set to indicate the reason.
+.Sh ERRORS
+.Bl -tag -width [EINVAL]
+.It Bq Er ESRCH
+No LWP can be found in the current process corresponding to that
+specified by
+.Fa lwp .
+.El
+.Sh SEE ALSO
+.Xr _lwp_park 2 ,
+.Xr _lwp_unpark_all 2 ,
+.Xr _lwp_wakeup 2
+.Sh HISTORY
+The
+.Fn _lwp_unpark
+system call first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/sys/_lwp_unpark_all.2 b/lib/nbsd_libc/sys/_lwp_unpark_all.2
new file mode 100644 (file)
index 0000000..1f44cbf
--- /dev/null
@@ -0,0 +1,99 @@
+.\"    $NetBSD: _lwp_unpark_all.2,v 1.6 2010/11/02 20:49:47 skrll Exp $
+.\"
+.\" Copyright (c) 2003, 2007 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, Inc, and by Andrew Doran.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd February 10, 2007
+.Dt _LWP_UNPARK_ALL 2
+.Os
+.Sh NAME
+.Nm _lwp_unpark_all
+.Nd resume execution of a waiting LWP
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft ssize_t
+.Fn _lwp_unpark_all "lwpid_t *targets" "size_t ntargets" "const void *hint"
+.Sh DESCRIPTION
+.Fn _lwp_unpark_all
+resumes execution of one or more light-weight processes listed in
+the array pointed to by
+.Fa targets .
+.Pp
+The target LWPs are assumed to be waiting in the kernel as a result of
+calls to
+.Fn _lwp_park .
+If any of the target LWPs are not currently waiting, those LWPs will return
+immediately upon the next call to
+.Fn _lwp_park .
+.Pp
+The value pointed to by
+.Fa ntargets
+specifies the size of the array pointed to by
+.Fa targets .
+If the
+.Fa targets
+argument is given as
+.Dv NULL ,
+the maximum size of the array (expressed
+as the number of entries) is returned.
+.Pp
+See
+.Xr _lwp_park 2
+for a description of the
+.Fa hint
+argument.
+.Sh RETURN VALUES
+If the maximum size of the
+.Fa targets
+array is not being queried, a return of 0 indicates that the call succeeded.
+A \-1 return value indicates an error occurred and
+.Va errno
+is set to indicate the reason.
+.Sh ERRORS
+.Bl -tag -width [EINVAL]
+.It Bq Er EFAULT
+The value specified for
+.Fa targets
+is invalid.
+.It Bq Er EINVAL
+The value specified for
+.Fa ntargets
+is out of range.
+.It Bq Er ENOMEM
+Insufficient resources are available to complete the operation.
+.El
+.Sh SEE ALSO
+.Xr _lwp_park 2 ,
+.Xr _lwp_unpark 2 ,
+.Xr _lwp_wakeup 2
+.Sh HISTORY
+The
+.Fn _lwp_unpark_all
+system call first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/sys/_lwp_wait.2 b/lib/nbsd_libc/sys/_lwp_wait.2
new file mode 100644 (file)
index 0000000..44d96ba
--- /dev/null
@@ -0,0 +1,93 @@
+.\"    $NetBSD: _lwp_wait.2,v 1.4 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, 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.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 13, 2003
+.Dt _LWP_WAIT 2
+.Os
+.Sh NAME
+.Nm _lwp_wait
+.Nd wait for light-weight process termination
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft int
+.Fn _lwp_wait "lwpid_t wlwp" "lwpid_t *rlwp"
+.Sh DESCRIPTION
+.Fn _lwp_wait
+suspends execution of the calling LWP until the LWP specified by
+.Fa wlwp
+terminates.
+The specified LWP must not be detached.
+If
+.Fa wlwp
+is 0, then
+.Fn _lwp_wait
+waits for any undetached LWP in the current process.
+.Pp
+If
+.Fa rlwp
+is not
+.Dv NULL ,
+then it points to the location where the LWP ID of
+the exited LWP is stored.
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn _lwp_wait
+returns a value of 0.
+Otherwise, an error code is returned to indicate the error.
+.Sh ERRORS
+.Fn _lwp_wait
+will fail if:
+.Bl -tag -width [EDEADLK]
+.It Bq Er ESRCH
+No undetached LWP can be found in the current process corresponding to that
+specified by
+.Fa wlwp .
+.It Bq Er EDEADLK
+The calling LWP is the only LWP in the process.
+.It Bq Er EDEADLK
+The LWP ID specified by
+.Fa wlwp
+is the LWP ID of the calling LWP.
+.It Bq Er EINTR
+.Fn _lwp_wait
+was interrupted by a caught signal, or the signal did not
+have the
+.Dv SA_RESTART
+flag set.
+.El
+.Sh SEE ALSO
+.Xr _lwp_create 2 ,
+.Xr _lwp_exit 2
+.Sh HISTORY
+The
+.Fn _lwp_wait
+system call first appeared in
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/sys/_lwp_wakeup.2 b/lib/nbsd_libc/sys/_lwp_wakeup.2
new file mode 100644 (file)
index 0000000..c30c77e
--- /dev/null
@@ -0,0 +1,73 @@
+.\"    $NetBSD: _lwp_wakeup.2,v 1.5 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of Wasabi Systems, 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.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd January 13, 2003
+.Dt _LWP_WAKEUP 2
+.Os
+.Sh NAME
+.Nm _lwp_wakeup
+.Nd make a blocked light-weight process runnable
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In lwp.h
+.Ft int
+.Fn _lwp_wakeup "lwpid_t lwp"
+.Sh DESCRIPTION
+.Fn _lwp_wakeup
+makes a blocked LWP runnable.  The blocked LWP must be in
+.Dv LSSLEEP
+state.
+Unblocking the LWP does not guarantee that it will make progress; it
+may block again as soon as it resumes execution in the kernel.
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn _lwp_wakeup
+returns a value of 0.
+Otherwise, an error code is returned to indicate the error.
+.Sh ERRORS
+.Fn _lwp_wakeup
+will fail if:
+.Bl -tag -width [ENODEV]
+.It Bq Er ESRCH
+No LWP can be found in the current process corresponding to that
+specified by
+.Fa lwp .
+.It Bq Er ENODEV
+The specified LWP is not in
+.Dv LSSLEEP
+state.
+.It Bq Er EBUSY
+The specified LWP is blocked in an uninterruptible sleep.
+.El
+.Sh HISTORY
+The
+.Fn _lwp_wakeup
+system call first appeared in
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/sys/_pipe.c b/lib/nbsd_libc/sys/_pipe.c
new file mode 100644 (file)
index 0000000..a68bc18
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: _pipe.c,v 1.7 2009/10/21 01:07:45 snj Exp $    */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _pipe.c,v 1.7 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_pipe, pipe)
+#else
+
+#include <unistd.h>
+int    _pipe(int *);
+
+int
+pipe(int *fildes)
+{
+
+       return _pipe(fildes);
+}
+#endif
diff --git a/lib/nbsd_libc/sys/_sbrk.c b/lib/nbsd_libc/sys/_sbrk.c
new file mode 100644 (file)
index 0000000..169916a
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: _sbrk.c,v 1.6 2009/10/21 01:07:45 snj Exp $    */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _sbrk.c,v 1.6 2009/10/21 01:07:45 snj Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_sbrk, sbrk)
+#else
+
+#include <unistd.h>
+void * _sbrk(intptr_t);
+
+void *
+sbrk(intptr_t incr)
+{
+
+       return _sbrk(incr);
+}
+#endif
diff --git a/lib/nbsd_libc/sys/accept.2 b/lib/nbsd_libc/sys/accept.2
new file mode 100644 (file)
index 0000000..61f25cb
--- /dev/null
@@ -0,0 +1,185 @@
+.\"    $NetBSD: accept.2,v 1.25 2006/11/17 23:59:33 rillig Exp $
+.\"
+.\" Copyright (c) 1983, 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)accept.2   8.2 (Berkeley) 12/11/93
+.\"
+.Dd November 18, 2006
+.Dt ACCEPT 2
+.Os
+.Sh NAME
+.Nm accept
+.Nd accept a connection on a socket
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft int
+.Fn accept "int s" "struct sockaddr * restrict addr" "socklen_t * restrict addrlen"
+.Sh DESCRIPTION
+The argument
+.Fa s
+is a socket that has been created with
+.Xr socket 2 ,
+bound to an address with
+.Xr bind 2 ,
+and is listening for connections after a
+.Xr listen 2 .
+The
+.Fn accept
+argument
+extracts the first connection request on the queue of pending
+connections, creates a new socket with the same properties of
+.Fa s
+and allocates a new file descriptor
+for the socket.
+If no pending connections are
+present on the queue, and the socket is not marked
+as non-blocking,
+.Fn accept
+blocks the caller until a connection is present.
+If the socket is marked non-blocking and no pending
+connections are present on the queue,
+.Fn accept
+returns an error as described below.
+The accepted socket
+may not be used
+to accept more connections.
+The original socket
+.Fa s
+remains open.
+.Pp
+The argument
+.Fa addr
+is a result parameter that is filled in with
+the address of the connecting entity,
+as known to the communications layer.
+The exact format of the
+.Fa addr
+parameter is determined by the domain in which the communication
+is occurring.
+The
+.Fa addrlen
+is a value-result parameter; it should initially contain the
+amount of space pointed to by
+.Fa addr ;
+on return it will contain the actual length (in bytes) of the
+address returned.
+This call
+is used with connection-based socket types, currently with
+.Dv SOCK_STREAM .
+.Pp
+It is possible to
+.Xr select 2
+or
+.Xr poll 2
+a socket for the purposes of doing an
+.Fn accept
+by selecting or polling it for read.
+.Pp
+For certain protocols which require an explicit confirmation,
+such as
+.Tn ISO
+or
+.Tn DATAKIT ,
+.Fn accept
+can be thought of
+as merely dequeuing the next connection
+request and not implying confirmation.
+Confirmation can be implied by a normal read or write on the new
+file descriptor, and rejection can be implied by closing the
+new socket.
+.Pp
+One can obtain user connection request data without confirming
+the connection by issuing a
+.Xr recvmsg 2
+call with an
+.Fa msg_iovlen
+of 0 and a non-zero
+.Fa msg_controllen ,
+or by issuing a
+.Xr getsockopt 2
+request.
+Similarly, one can provide user connection rejection information
+by issuing a
+.Xr sendmsg 2
+call with providing only the control information,
+or by calling
+.Xr setsockopt 2 .
+.Sh RETURN VALUES
+The call returns \-1 on error.
+If it succeeds, it returns a non-negative
+integer that is a descriptor for the accepted socket.
+.Sh ERRORS
+The
+.Fn accept
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EAGAIN
+The socket is marked non-blocking and no connections
+are present to be accepted.
+.It Bq Er EBADF
+The descriptor is invalid.
+.It Bq Er ECONNABORTED
+A connection has been aborted.
+.It Bq Er EFAULT
+The
+.Fa addr
+parameter is not in a writable part of the
+user address space.
+.It Bq Er EINTR
+The
+.Fn accept
+call has been interrupted by a signal.
+.It Bq Er EINVAL
+The socket has not been set up to accept connections (using
+.Xr bind 2
+and
+.Xr listen 2 ) .
+.It Bq Er EMFILE
+The per-process descriptor table is full.
+.It Bq Er ENFILE
+The system file table is full.
+.It Bq Er ENOTSOCK
+The descriptor references a file, not a socket.
+.It Bq Er EOPNOTSUPP
+The referenced socket is not of type
+.Dv SOCK_STREAM .
+.El
+.Sh SEE ALSO
+.Xr bind 2 ,
+.Xr connect 2 ,
+.Xr listen 2 ,
+.Xr poll 2 ,
+.Xr select 2 ,
+.Xr socket 2
+.Sh HISTORY
+The
+.Fn accept
+function appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/access.2 b/lib/nbsd_libc/sys/access.2
new file mode 100644 (file)
index 0000000..76b76e3
--- /dev/null
@@ -0,0 +1,154 @@
+.\"    $NetBSD: access.2,v 1.26 2010/05/03 05:53:56 jruoho Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)access.2   8.2 (Berkeley) 4/1/94
+.\"
+.Dd May 3, 2010
+.Dt ACCESS 2
+.Os
+.Sh NAME
+.Nm access
+.Nd check access permissions of a file or pathname
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn access "const char *path" "int mode"
+.Sh DESCRIPTION
+The
+.Fn access
+function checks the accessibility of the
+file named by
+.Fa path
+for the access permissions indicated by
+.Fa mode .
+The value of
+.Fa mode
+is the bitwise inclusive OR of the access permissions to be
+checked
+.Pf ( Dv R_OK
+for read permission,
+.Dv W_OK
+for write permission and
+.Dv X_OK
+for execute/search permission) or the existence test,
+.Dv F_OK .
+All components of the pathname
+.Fa path
+are checked for access permissions (including
+.Dv F_OK ) .
+.Pp
+The real user ID is used in place of the effective user ID
+and the real group access list
+(including the real group ID) are
+used in place of the effective ID for verifying permission.
+.Pp
+If a process has super-user privileges and indicates success for
+.Dv R_OK
+or
+.Dv W_OK ,
+the file may not actually have read or write permission bits set.
+If a process has super-user privileges and indicates success for
+.Dv X_OK ,
+at least one of the user, group, or other execute bits is set.
+(However, the file may still not be executable.
+See
+.Xr execve 2 . )
+.Sh RETURN VALUES
+If
+.Fa path
+cannot be found or if any of the desired access modes would
+not be granted, then a \-1 value is returned; otherwise
+a 0 value is returned.
+.Sh ERRORS
+Access to the file is denied if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+Permission bits of the file mode do not permit the requested
+access, or search permission is denied on a component of the
+path prefix.
+The owner of a file has permission checked with respect to the
+.Dq owner
+read, write, and execute mode bits, members of the file's group
+other than the owner have permission checked with respect to the
+.Dq group
+mode bits, and all others have permissions checked with respect to
+the
+.Dq other
+mode bits.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named file does not exist.
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er EROFS
+Write access is requested for a file on a read-only file system.
+.It Bq Er ETXTBSY
+Write access is requested for a pure procedure (shared text)
+file presently being executed.
+.El
+.Sh SEE ALSO
+.Xr chmod 2 ,
+.Xr execve 2 ,
+.Xr stat 2 ,
+.Xr secure_path 3
+.Sh STANDARDS
+The
+.Fn access
+function conforms to
+.St -p1003.1-90 .
+.Sh SECURITY CONSIDERATIONS
+The
+.Fn access
+system call is a potential security hole due to race conditions.
+It should never be used.
+Set-user-ID and set-group-ID applications should restore the
+effective user or group ID, and perform actions directly rather than use
+.Fn access
+to simulate access checks for the real user or group ID.
+.Pp
+The
+.Fn access
+system call may however have some value in providing clues to users as to
+whether certain operations make sense for a particular filesystem object.
+Arguably it also allows a cheaper file existence test than
+.Xr stat 2 .
diff --git a/lib/nbsd_libc/sys/acct.2 b/lib/nbsd_libc/sys/acct.2
new file mode 100644 (file)
index 0000000..4e7f1bf
--- /dev/null
@@ -0,0 +1,131 @@
+.\"    $NetBSD: acct.2,v 1.19 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)acct.2     8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt ACCT 2
+.Os
+.Sh NAME
+.Nm acct
+.Nd enable or disable process accounting
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn acct "const char *file"
+.Sh DESCRIPTION
+The
+.Fn acct
+call enables or disables the collection of system accounting records.
+If
+.Fa file
+is
+.Dv NULL ,
+accounting is disabled.
+If
+.Fa file
+is an existing, NUL-terminated, pathname, record collection is enabled,
+and for every process initiated which terminates under normal
+conditions an accounting record is appended to
+.Fa file .
+Abnormal conditions of termination are reboots or other fatal system problems.
+Records for processes which never terminate can not be
+produced by
+.Fn acct .
+.Pp
+For more information on the record structure used by
+.Fn acct ,
+see
+.Pa /usr/include/sys/acct.h
+and
+.Xr acct 5 .
+.Pp
+This call is permitted only to the super-user.
+.Sh NOTES
+Accounting is automatically disabled when the file system the
+accounting file resides on runs out of space; it is enabled when
+space once again becomes available.
+For this purpose,
+.Fn acct
+creates a kernel thread called
+.Dq acctwatch .
+.Sh RETURN VALUES
+On success, zero is returned.
+Otherwise, \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn acct
+will fail if one of the following is true:
+.Bl -tag -width Er
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix,
+or the path name is not a regular file.
+.It Bq Er EFAULT
+.Fa file
+points outside the process's allocated address space.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named file does not exist.
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er EPERM
+The caller is not the super-user.
+.It Bq Er EROFS
+The named file resides on a read-only file system.
+.El
+.Pp
+Also,
+.Fn acct
+fails if failed to create kernel thread described above.
+See
+.Xr fork 2
+for
+.Va errno
+value.
+.Sh SEE ALSO
+.Xr fork 2 ,
+.Xr acct 5 ,
+.Xr sa 8
+.Sh HISTORY
+An
+.Fn acct
+function call appeared in
+.At v7 .
diff --git a/lib/nbsd_libc/sys/adjtime.2 b/lib/nbsd_libc/sys/adjtime.2
new file mode 100644 (file)
index 0000000..1053717
--- /dev/null
@@ -0,0 +1,122 @@
+.\"    $NetBSD: adjtime.2,v 1.20 2004/05/13 10:20:57 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)adjtime.2  8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt ADJTIME 2
+.Os
+.Sh NAME
+.Nm adjtime
+.Nd "correct the time to allow synchronization of the system clock"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/time.h
+.Ft int
+.Fn adjtime "const struct timeval *delta" "struct timeval *olddelta"
+.Sh DESCRIPTION
+.Fn adjtime
+makes small adjustments to the system time, as returned by
+.Xr gettimeofday 2 ,
+advancing or retarding it
+by the time specified by the timeval
+.Fa delta .
+If
+.Fa delta
+is negative, the clock is
+slowed down by incrementing it more slowly than normal until
+the correction is complete.
+If
+.Fa delta
+is positive, a larger increment than normal
+is used.
+The skew used to perform the correction is generally a fraction of one percent.
+Thus, the time is always
+a monotonically increasing function.
+A time correction from an earlier call to
+.Fn adjtime
+may not be finished when
+.Fn adjtime
+is called again.
+If
+.Fa olddelta
+is non-nil,
+the structure pointed to will contain, upon return, the
+number of microseconds still to be corrected
+from the earlier call.
+.Pp
+This call may be used by time servers that synchronize the clocks
+of computers in a local area network.
+Such time servers would slow down the clocks of some machines
+and speed up the clocks of others to bring them to the average network time.
+.Pp
+If the calling user is not the super user, then the
+.Fn adjtime
+function in the standard C library will try to use the
+.Xr clockctl 4
+device if present, thus making possible for non privileged users to
+adjust the system time.
+If
+.Xr clockctl 4
+is not present or not accessible, then
+.Fn adjtime
+reverts to the
+.Fn adjtime
+system call, which is restricted to the super user.
+.Sh RETURN VALUES
+A return value of 0 indicates that the call succeeded.
+A return value of \-1 indicates that an error occurred, and in this
+case an error code is stored in the global variable
+.Va errno .
+.Sh ERRORS
+.Fn adjtime
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+An argument points outside the process's allocated address space.
+.It Bq Er EPERM
+The process's effective user ID is not that of the super user.
+.El
+.Sh SEE ALSO
+.Xr date 1 ,
+.Xr gettimeofday 2 ,
+.Xr clockctl 4 ,
+.Xr timed 8 ,
+.Xr timedc 8
+.Rs
+.%T "TSP: The Time Synchronization Protocol for UNIX 4.3BSD"
+.%A R. Gusella
+.%A S. Zatti
+.Re
+.Sh HISTORY
+The
+.Fn adjtime
+function call appeared in
+.Bx 4.3 .
diff --git a/lib/nbsd_libc/sys/adjtime.c b/lib/nbsd_libc/sys/adjtime.c
new file mode 100644 (file)
index 0000000..ecc6d6e
--- /dev/null
@@ -0,0 +1,96 @@
+/*     $NetBSD: adjtime.c,v 1.11 2009/01/11 02:46:30 christos Exp $ */
+
+/*
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.      
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Emmanuel Dreyfus.
+ *
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: adjtime.c,v 1.11 2009/01/11 02:46:30 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <errno.h>
+#include <fcntl.h>
+#include <paths.h>
+#include <unistd.h>
+#include <time.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/syscall.h>
+
+#include <sys/clockctl.h>
+extern int __clockctl_fd;
+
+int ____adjtime50(const struct timeval *, struct timeval *);
+
+int
+adjtime(const struct timeval *delta, struct timeval *olddelta)
+{
+       struct clockctl_adjtime args;
+       int rv;
+
+       /*
+        * we always attempt the syscall first and switch to 
+        * clockctl if that fails with EPERM
+        */
+       if (__clockctl_fd == -1) {
+               rv = ____adjtime50(delta, olddelta);
+       
+               /*
+                * try via clockctl if the call fails with EPERM
+                */
+               if (rv != -1 || errno != EPERM)
+                       return rv;
+
+               /*
+                * If this fails, it means that we are not root
+                * and we cannot open clockctl. This is a failure.
+                */
+               __clockctl_fd = open(_PATH_CLOCKCTL, O_WRONLY, 0);
+               if (__clockctl_fd == -1) {
+                       /* original error was EPERM - don't leak open errors */
+                       errno = EPERM;
+                       return -1;
+               }
+
+               (void) fcntl(__clockctl_fd, F_SETFD, FD_CLOEXEC);
+       }
+
+       /* 
+        * If __clockctl_fd >=0, clockctl has already been open
+        * and used, so we carry on using it.
+        */
+       args.delta = delta;
+       args.olddelta = olddelta;
+       return ioctl(__clockctl_fd, CLOCKCTL_ADJTIME, &args);
+}
diff --git a/lib/nbsd_libc/sys/bind.2 b/lib/nbsd_libc/sys/bind.2
new file mode 100644 (file)
index 0000000..b5fc707
--- /dev/null
@@ -0,0 +1,185 @@
+.\"    $NetBSD: bind.2,v 1.27 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" 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.
+.\" 3. 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.
+.\"
+.\"     @(#)bind.2     8.1 (Berkeley) 6/4/93
+.\"
+.Dd August 30, 2005
+.Dt BIND 2
+.Os
+.Sh NAME
+.Nm bind
+.Nd bind a name to a socket
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft int
+.Fn bind "int s" "const struct sockaddr *name" "socklen_t namelen"
+.Sh DESCRIPTION
+.Fn bind
+assigns a name to an unnamed socket.
+When a socket is created
+with
+.Xr socket 2
+it exists in a name space (address family)
+but has no name assigned.
+.Fn bind
+requests that
+.Fa name
+be assigned to the socket.
+.Fa namelen
+indicates the amount of space pointed to by
+.Fa name ,
+in bytes.
+.Sh NOTES
+Binding a name in the
+.Ux
+domain creates a socket in the file
+system that must be deleted by the caller when it is no longer
+needed (using
+.Xr unlink 2 ) .
+.Pp
+The rules used in name binding vary between communication domains.
+Consult the manual entries in section 4 for detailed information.
+.Sh RETURN VALUES
+If the bind is successful, a 0 value is returned.
+A return value of \-1 indicates an error, which is
+further specified in the global
+.Va errno .
+.Sh ERRORS
+The
+.Fn bind
+call will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa s
+is not a valid descriptor.
+.It Bq Er ENOTSOCK
+.Fa s
+is not a socket.
+.It Bq Er EADDRNOTAVAIL
+The specified address is not available from the local machine.
+.It Bq Er EADDRINUSE
+The specified address is already in use.
+.It Bq Er EINVAL
+The socket is already bound to an address.
+.It Bq Er EINVAL
+The family of the socket and that requested in
+.Fa name-\*[Gt]sa_family
+are not equivalent.
+.It Bq Er EACCES
+The requested address is protected, and the current user
+has inadequate permission to access it.
+.It Bq Er EFAULT
+The
+.Fa name
+parameter is not in a valid part of the user
+address space.
+.El
+.Pp
+The following errors are specific to binding names in the
+.Ux
+domain.
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+A prefix component of the path name does not exist.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EIO
+An I/O error occurred while making the directory entry or allocating the inode.
+.It Bq Er EROFS
+The name would reside on a read-only file system.
+.It Bq Er EISDIR
+An empty pathname was specified.
+.El
+.Sh SEE ALSO
+.Xr connect 2 ,
+.Xr getsockname 2 ,
+.Xr listen 2 ,
+.Xr socket 2
+.Sh HISTORY
+The
+.Fn bind
+function call appeared in
+.Bx 4.2 .
+.Sh SECURITY CONSIDERATIONS
+.Fn bind
+was changed in
+.Nx 1.4
+to prevent the binding of a socket to the same port as an existing
+socket when all of the following is true:
+.Bl -bullet -compact -offset indent
+.It
+either of the existing or new addresses is
+.Li INADDR_ANY ,
+.It
+the uid of the new socket is not root, and
+the uids of the creators of the sockets are different,
+.It
+the address is not a multicast address, and
+.It
+both sockets are not bound to
+.Li INADDR_ANY
+with
+.Li SO_REUSEPORT
+set.
+.El
+.Pp
+This prevents an attack where a user could bind to a port with
+the host's IP address (after setting
+.Li SO_REUSEADDR )
+and
+.Sq steal
+packets destined for a server that bound to the
+same port with
+.Li INADDR_ANY .
+.Pp
+.Fn bind
+was changed in
+.Nx 4.0
+to honor the user's umask when binding sockets in the local domain.
+This was done to match the behavior of other operating systems,
+including
+.Fx ,
+.Ox ,
+and
+Linux, and to improve compatibility with some third-party software.
+Please note that this behavior
+.Em is not portable .
+If you must bind a local socket in a portable and secure way, you need
+to make a directory with tight permissions and then create the socket
+inside it.
diff --git a/lib/nbsd_libc/sys/brk.2 b/lib/nbsd_libc/sys/brk.2
new file mode 100644 (file)
index 0000000..f117e6a
--- /dev/null
@@ -0,0 +1,174 @@
+.\"    $NetBSD: brk.2,v 1.32 2004/05/13 10:20:57 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)brk.2      8.4 (Berkeley) 5/1/95
+.\"
+.Dd July 12, 1999
+.Dt BRK 2
+.Os
+.Sh NAME
+.Nm brk ,
+.Nm sbrk
+.Nd change data segment size
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn brk "void *addr"
+.Ft void *
+.Fn sbrk "intptr_t incr"
+.Sh DESCRIPTION
+.Bf -symbolic
+The brk and sbrk functions are legacy interfaces from before the
+advent of modern virtual memory management.
+.Ef
+.Pp
+The
+.Fn brk
+and
+.Fn sbrk
+functions are used to change the amount of memory allocated in a
+process's data segment.
+They do this by moving the location of the
+.Dq break .
+The break is the first address after the end of the process's
+uninitialized data segment (also known as the
+.Dq BSS ) .
+.Pp
+While the actual process data segment size maintained by the kernel will only
+grow or shrink in page sizes, these functions allow setting the break
+to unaligned values (i.e. it may point to any address inside the last
+page of the data segment).
+.Pp
+The
+.Fn brk
+function sets the break to
+.Fa addr .
+.Pp
+The
+.Fn sbrk
+function raises the break by at least
+.Fa incr
+bytes, thus allocating at least
+.Fa incr
+bytes of new memory in the data segment.
+If
+.Fa incr
+is negative,
+the break is lowered by
+.Fa incr
+bytes.
+.Pp
+.Fn sbrk
+returns the prior address of the break.
+The current value of the program break may be determined by calling
+.Fn sbrk 0 .
+(See also
+.Xr end 3 ) .
+.Pp
+The
+.Xr getrlimit 2
+system call may be used to determine
+the maximum permissible size of the
+.Em data
+segment;
+it will not be possible to set the break
+beyond the
+.Dv RLIMIT_DATA
+.Em rlim_max
+value returned from a call to
+.Xr getrlimit 2 ,
+e.g.
+.Dq etext + rlim.rlim_max .
+(see
+.Xr end 3
+for the definition of
+.Em etext ) .
+.Sh RETURN VALUES
+.Fn brk
+returns 0 if successful;
+otherwise \-1 with
+.Va errno
+set to indicate why the allocation failed.
+.Pp
+The
+.Fn sbrk
+function returns the prior break value if successful;
+otherwise ((void *)\-1) is returned and
+.Va errno
+is set to indicate why the allocation failed.
+.Sh ERRORS
+.Fn brk
+or
+.Fn sbrk
+will fail and no additional memory will be allocated if
+one of the following are true:
+.Bl -tag -width Er
+.It Bq Er ENOMEM
+The limit, as set by
+.Xr setrlimit 2 ,
+was exceeded.
+.It Bq Er ENOMEM
+The maximum possible size of a data segment (compiled into the
+system) was exceeded.
+.It Bq Er ENOMEM
+Insufficient space existed in the swap area
+to support the expansion.
+.El
+.Sh SEE ALSO
+.Xr execve 2 ,
+.Xr getrlimit 2 ,
+.Xr mmap 2 ,
+.Xr end 3 ,
+.Xr free 3 ,
+.Xr malloc 3 ,
+.Xr sysconf 3
+.Sh HISTORY
+A
+.Fn brk
+function call appeared in
+.At v7 .
+.Sh BUGS
+Note that
+mixing
+.Fn brk
+and
+.Fn sbrk
+with
+.Xr malloc 3 ,
+.Xr free 3 ,
+and similar functions may result in non-portable program
+behavior.
+Caution is advised.
+.Pp
+Setting the break may fail due to a temporary lack of swap space.
+It is not possible to distinguish this from a failure caused by
+exceeding the maximum size of the data segment without consulting
+.Xr getrlimit 2 .
diff --git a/lib/nbsd_libc/sys/chdir.2 b/lib/nbsd_libc/sys/chdir.2
new file mode 100644 (file)
index 0000000..b28227a
--- /dev/null
@@ -0,0 +1,136 @@
+.\"    $NetBSD: chdir.2,v 1.21 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)chdir.2    8.2 (Berkeley) 12/11/93
+.\"
+.Dd December 11, 1993
+.Dt CHDIR 2
+.Os
+.Sh NAME
+.Nm chdir ,
+.Nm fchdir
+.Nd change current working directory
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn chdir "const char *path"
+.Ft int
+.Fn fchdir "int fd"
+.Sh DESCRIPTION
+The
+.Fa path
+argument points to the pathname of a directory.
+The
+.Fn chdir
+function
+causes the named directory
+to become the current working directory, that is,
+the starting point for path searches of pathnames not beginning with
+a slash,
+.Ql / .
+.Pp
+The
+.Fn fchdir
+function
+causes the directory referenced by
+.Fa fd
+to become the current working directory,
+the starting point for path searches of pathnames not beginning with
+a slash,
+.Ql / .
+.Pp
+In order for a directory to become the current directory,
+a process must have execute (search) access to the directory.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate
+the error.
+.Sh ERRORS
+.Fn chdir
+will fail and the current working directory will be unchanged if
+one or more of the following are true:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named directory does not exist.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EACCES
+Search permission is denied for any component of
+the path name.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.El
+.Pp
+.Fn fchdir
+will fail and the current working directory will be unchanged if
+one or more of the following are true:
+.Bl -tag -width Er
+.It Bq Er EACCES
+Search permission is denied for the directory referenced by the
+file descriptor.
+.It Bq Er ENOTDIR
+The file descriptor does not reference a directory.
+.It Bq Er EBADF
+The argument
+.Fa fd
+is not a valid file descriptor.
+.It Bq Er EPERM
+The argument
+.Fa fd
+references a directory which is not at or below the current process's
+root directory.
+.El
+.Sh SEE ALSO
+.Xr chroot 2
+.Sh STANDARDS
+The
+.Fn chdir
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+The
+.Fn fchdir
+function call
+appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/chflags.2 b/lib/nbsd_libc/sys/chflags.2
new file mode 100644 (file)
index 0000000..875e2d7
--- /dev/null
@@ -0,0 +1,187 @@
+.\"    $NetBSD: chflags.2,v 1.26 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1989, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)chflags.2   8.3 (Berkeley) 5/2/95
+.\"
+.Dd May 2, 1995
+.Dt CHFLAGS 2
+.Os
+.Sh NAME
+.Nm chflags ,
+.Nm lchflags ,
+.Nm fchflags
+.Nd set file flags
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/stat.h
+.In unistd.h
+.Ft int
+.Fn chflags "const char *path"  "u_long flags"
+.Ft int
+.Fn lchflags "const char *path"  "u_long flags"
+.Ft int
+.Fn fchflags "int fd" "u_long flags"
+.Sh DESCRIPTION
+The file whose name
+is given by
+.Fa path
+or referenced by the descriptor
+.Fa fd
+has its flags changed to
+.Fa flags .
+For
+.Fn lchflags ,
+symbolic links are not traversed and thus their modes may be changed with
+this call.
+.Pp
+The flags specified are formed by
+.Em or Ns 'ing
+the following values:
+.Pp
+.Bl -tag -width "SF_IMMUTABLE" -compact -offset indent
+.It Dv UF_NODUMP
+Do not dump the file.
+.It Dv UF_IMMUTABLE
+The file may not be changed.
+.It Dv UF_APPEND
+The file may only be appended to.
+.It Dv UF_OPAQUE
+The file (if a directory) is opaque for union mounts.
+.It Dv SF_ARCHIVED
+The file is archived.
+.It Dv SF_IMMUTABLE
+The file may not be changed.
+.It Dv SF_APPEND
+The file may only be appended to.
+.El
+.Pp
+The
+.Dv UF_NODUMP ,
+.Dv UF_IMMUTABLE ,
+.Dv UF_APPEND ,
+and
+.Dv UF_OPAQUE
+flags may be set or unset by either the owner of a file or the super-user,
+except on block and character devices, where only the super-user may set
+or unset them.
+.Pp
+The
+.Dv SF_ARCHIVED ,
+.Dv SF_IMMUTABLE ,
+and
+.Dv SF_APPEND
+flags may only be set or unset by the super-user.
+Attempts by the non-super-user to set the super-user only flags
+are silently ignored.
+These flags may be set at any time, but normally may only be unset when
+the system is in single-user mode.
+(See
+.Xr init 8
+for details.)
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn chflags
+will fail if:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named file does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EPERM
+The effective user ID does not match the owner of the file and
+the effective user ID is not the super-user, or
+the effective user ID is not the super-user and one or more of the
+super-user-only flags for the named file would be changed.
+.It Bq Er EOPNOTSUPP
+The named file resides on a file system that does not support file
+flags.
+.It Bq Er EROFS
+The named file resides on a read-only file system.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.It Bq Er EIO
+An
+.Tn I/O
+error occurred while reading from or writing to the file system.
+.El
+.Pp
+.Fn fchflags
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The descriptor is not valid.
+.It Bq Er EINVAL
+.Fa fd
+refers to a socket, not to a file.
+.It Bq Er EPERM
+The effective user ID does not match the owner of the file and
+the effective user ID is not the super-user, or
+the effective user ID is not the super-user and one or more of the
+super-user-only flags for the file would be changed.
+.It Bq Er EOPNOTSUPP
+The file resides on a file system that does not support file flags.
+.It Bq Er EROFS
+The file resides on a read-only file system.
+.It Bq Er EIO
+An
+.Tn I/O
+error occurred while reading from or writing to the file system.
+.El
+.Sh SEE ALSO
+.Xr chflags 1 ,
+.Xr stat 2 ,
+.Xr init 8 ,
+.Xr mount_union 8
+.Sh HISTORY
+The
+.Fn chflags
+and
+.Fn fchflags
+functions first appeared in
+.Bx 4.4 .
+The
+.Fn lchflags
+function first appeared in
+.Nx 1.5 .
diff --git a/lib/nbsd_libc/sys/chmod.2 b/lib/nbsd_libc/sys/chmod.2
new file mode 100644 (file)
index 0000000..2f34754
--- /dev/null
@@ -0,0 +1,248 @@
+.\"    $NetBSD: chmod.2,v 1.37 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)chmod.2    8.1 (Berkeley) 6/4/93
+.\"
+.Dd January 4, 2009
+.Dt CHMOD 2
+.Os
+.Sh NAME
+.Nm chmod ,
+.Nm lchmod ,
+.Nm fchmod
+.Nd change mode of file
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/stat.h
+.Ft int
+.Fn chmod "const char *path" "mode_t mode"
+.Ft int
+.Fn lchmod "const char *path" "mode_t mode"
+.Ft int
+.Fn fchmod "int fd" "mode_t mode"
+.Sh DESCRIPTION
+The function
+.Fn chmod
+sets the file permission bits
+of the file
+specified by the pathname
+.Fa path
+to
+.Fa mode .
+.Fn fchmod
+sets the permission bits of the specified
+file descriptor
+.Fa fd .
+.Fn lchmod
+is like
+.Fn chmod
+except in the case where the named file is a symbolic link,
+in which case
+.Fn lchmod
+sets the permission bits of the link,
+while
+.Fn chmod
+sets the bits of the file the link references.
+.Fn chmod
+verifies that the process owner (user) either owns
+the file specified by
+.Fa path
+(or
+.Fa fd ) ,
+or
+is the super-user.
+A mode is created from
+.Em or'd
+permission bit masks
+defined in
+.In sys/stat.h :
+.Bd -literal -offset indent -compact
+#define S_IRWXU 0000700    /* RWX mask for owner */
+#define S_IRUSR 0000400    /* R for owner */
+#define S_IWUSR 0000200    /* W for owner */
+#define S_IXUSR 0000100    /* X for owner */
+
+#define S_IRWXG 0000070    /* RWX mask for group */
+#define S_IRGRP 0000040    /* R for group */
+#define S_IWGRP 0000020    /* W for group */
+#define S_IXGRP 0000010    /* X for group */
+
+#define S_IRWXO 0000007    /* RWX mask for other */
+#define S_IROTH 0000004    /* R for other */
+#define S_IWOTH 0000002    /* W for other */
+#define S_IXOTH 0000001    /* X for other */
+
+#define S_ISUID 0004000    /* set user id on execution */
+#define S_ISGID 0002000    /* set group id on execution */
+#define S_ISVTX 0001000    /* save swapped text even after use */
+.Ed
+.Pp
+If mode
+.Dv ISVTX
+(the
+.Sq sticky bit )
+is set on a regular file, it historically meant that the system should
+save a shareable copy of the program text in the swap area.
+When applied to commonly used programs like the shell or editor, this
+would decrease memory usage and startup time.
+In
+.Nx ,
+the sticky bit may still be set on regular files by the super-user,
+but has no effect.
+The historical meaning became obsolete in the 1980s with the advent of
+memory-mapped executables, and is only documented as a matter of
+historical interest.
+.Pp
+If mode
+.Dv ISVTX
+(the
+.Sq sticky bit )
+is set on a directory,
+an unprivileged user may not delete or rename
+files of other users in that directory.
+The sticky bit may be set by any user on a directory which the user
+owns or has appropriate permissions.
+.Pp
+For more information about the properties of the sticky bit, see
+.Xr sticky 7 .
+.Pp
+Changing the owner of a file
+turns off the set-user-id and set-group-id bits;
+writing to a file
+turns off the set-user-id and set-group-id bits
+unless the user is the super-user.
+This makes the system somewhat more secure
+by protecting set-user-id (set-group-id) files
+from remaining set-user-id (set-group-id) if they are modified,
+at the expense of a degree of compatibility.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn chmod
+and
+.Fn lchmod
+will fail and the file mode will be unchanged if:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named file does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EPERM
+The effective user ID does not match the owner of the file and
+the effective user ID is not the super-user.
+.It Bq Er EPERM
+The mode includes the setgid bit
+.Pq Dv S_ISGID
+but the file's group is neither the effective group ID nor is it in the
+group access list.
+.It Bq Er EROFS
+The named file resides on a read-only file system.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.It Bq Er EFTYPE
+The effective user ID is not the super-user, the
+.Fa mode
+includes the sticky bit
+.Pq Dv S_ISVTX ,
+and
+.Fa path
+does not refer to a directory.
+.El
+.Pp
+.Fn fchmod
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The descriptor is not valid.
+.It Bq Er EINVAL
+.Fa fd
+refers to a socket, not to a file.
+.It Bq Er EPERM
+The effective user ID does not match the owner of the file and
+the effective user ID is not the super-user.
+.It Bq Er EPERM
+The mode includes the setgid bit
+.Pq Dv S_ISGID
+but the file's group is neither the effective group ID nor is it in the
+group access list.
+.It Bq Er EROFS
+The file resides on a read-only file system.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.It Bq Er EFTYPE
+The effective user ID is not the super-user, the
+.Fa mode
+includes the sticky bit
+.Pq Dv S_ISVTX ,
+and
+.Fa fd
+does not refer to a directory.
+.El
+.Sh SEE ALSO
+.Xr chmod 1 ,
+.Xr chflags 2 ,
+.Xr chown 2 ,
+.Xr open 2 ,
+.Xr stat 2 ,
+.Xr getmode 3 ,
+.Xr setmode 3 ,
+.Xr sticky 7 ,
+.Xr symlink 7
+.Sh STANDARDS
+The
+.Fn chmod
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+The
+.Fn fchmod
+function call
+appeared in
+.Bx 4.2 .
+The
+.Fn lchmod
+function call appeared in
+.Nx 1.3 .
diff --git a/lib/nbsd_libc/sys/chown.2 b/lib/nbsd_libc/sys/chown.2
new file mode 100644 (file)
index 0000000..b3962d5
--- /dev/null
@@ -0,0 +1,214 @@
+.\"    $NetBSD: chown.2,v 1.31 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 1993, 1994
+.\"    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.
+.\" 3. 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.
+.\"
+.\"     @(#)chown.2    8.4 (Berkeley) 4/19/94
+.\"
+.Dd April 19, 1994
+.Dt CHOWN 2
+.Os
+.Sh NAME
+.Nm chown ,
+.Nm lchown ,
+.Nm fchown
+.Nd change owner and group of a file
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn chown "const char *path" "uid_t owner" "gid_t group"
+.Ft int
+.Fn lchown "const char *path" "uid_t owner" "gid_t group"
+.Ft int
+.Fn fchown "int fd" "uid_t owner" "gid_t group"
+.Sh DESCRIPTION
+The owner ID and group ID of the file
+named by
+.Fa path
+or referenced by
+.Fa fd
+is changed as specified by the arguments
+.Fa owner
+and
+.Fa group .
+The owner of a file may change the
+.Fa group
+to a group of which
+he or she is a member,
+but the change
+.Fa owner
+capability is restricted to the super-user.
+.Pp
+When called to change the owner of a file,
+.Fn chown ,
+.Fn lchown
+and
+.Fn fchown
+clear the set-user-id
+.Dv ( S_ISUID )
+bit on the file.
+When a called to change the group of a file,
+.Fn chown ,
+.Fn lchown
+and
+.Fn fchown
+clear the set-group-id
+.Dv ( S_ISGID )
+bit on the file.
+These actions are taken to prevent accidental or mischievous creation of
+set-user-id and set-group-id programs.
+.Pp
+.Fn lchown
+is like
+.Fn chown
+except in the case where the named file is a symbolic link,
+in which case
+.Fn lchown
+changes the owner and group of the link,
+while
+.Fn chown
+changes the owner and group of the file the link references.
+.Pp
+.Fn fchown
+is particularly useful when used in conjunction
+with the file locking primitives (see
+.Xr flock 2 ) .
+.Pp
+One of the owner or group id's
+may be left unchanged by specifying it as (uid_t)\-1 or (gid_t)\-1 respectively.
+.Sh RETURN VALUES
+Zero is returned if the operation was successful;
+\-1 is returned if an error occurs, with a more specific
+error code being placed in the global variable
+.Va errno .
+.Sh ERRORS
+.Fn chown
+and
+.Fn lchown
+will fail and the file will be unchanged if:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named file does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EPERM
+The effective user ID is not the super-user.
+.It Bq Er EROFS
+The named file resides on a read-only file system.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.El
+.Pp
+.Fn fchown
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa fd
+does not refer to a valid descriptor.
+.It Bq Er EINVAL
+.Fa fd
+refers to a socket, not a file.
+.It Bq Er EPERM
+The effective user ID is not the super-user.
+.It Bq Er EROFS
+The named file resides on a read-only file system.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.El
+.Sh SEE ALSO
+.Xr chgrp 1 ,
+.Xr chmod 2 ,
+.Xr flock 2 ,
+.Xr symlink 7 ,
+.Xr chown 8
+.Sh STANDARDS
+The
+.Fn chown
+function deviates from the semantics defined in
+.St -p1003.1-90 ,
+which specifies that, unless the caller is the super-user, both the
+set-user-id and set-group-id bits on a file shall be cleared, regardless
+of the file attribute changed.
+The
+.Fn lchown
+and
+.Fn fchown
+functions, as defined by
+.St -xpg4.2 ,
+provide the same semantics.
+.Pp
+To retain conformance to these standards, compatibility interfaces
+are provided by the
+.Lb libposix
+as follows:
+.Bl -bullet -compact
+.It
+The
+.Fn chown
+function conforms to
+.St -p1003.1-90
+and
+.St -xpg4.2 .
+.It
+The
+.Fn lchown
+and
+.Fn fchown
+functions conform to
+.St -xpg4.2 .
+.El
+.Sh HISTORY
+The
+.Fn fchown
+function call appeared in
+.Bx 4.2 .
+.Pp
+The
+.Fn chown
+and
+.Fn fchown
+functions were changed to follow symbolic links in
+.Bx 4.4 .
+The
+.Fn lchown
+function call appeared in
+.Nx 1.3 .
diff --git a/lib/nbsd_libc/sys/chroot.2 b/lib/nbsd_libc/sys/chroot.2
new file mode 100644 (file)
index 0000000..069a047
--- /dev/null
@@ -0,0 +1,152 @@
+.\"    $NetBSD: chroot.2,v 1.23 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)chroot.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 18, 2001
+.Dt CHROOT 2
+.Os
+.Sh NAME
+.Nm chroot
+.Nd change root directory
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn chroot "const char *dirname"
+.Ft int
+.Fn fchroot "int fd"
+.Sh DESCRIPTION
+.Fa dirname
+is the address of the pathname of a directory, terminated by an ASCII NUL.
+.Fn chroot
+causes
+.Fa dirname
+to become the root directory,
+that is, the starting point for path searches of pathnames
+beginning with
+.Ql / .
+.Pp
+In order for a directory to become the root directory
+a process must have execute (search) access for that directory.
+.Pp
+If the current working directory is not at or under the new root
+directory, it is silently set to the new root directory.
+It should be noted that, on most other systems,
+.Fn chroot
+has no effect on the process's current directory.
+.Pp
+This call is restricted to the super-user.
+.Pp
+The
+.Fn fchroot
+function performs the same operation on an open directory file
+known by the file descriptor
+.Fa fd .
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate an error.
+.Sh ERRORS
+.Fn chroot
+will fail and the root directory will be unchanged if:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path name is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named directory does not exist.
+.It Bq Er EACCES
+Search permission is denied for any component of the path name.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EFAULT
+.Fa dirname
+points outside the process's allocated address space.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.It Bq Er EPERM
+The effective user ID of the calling process is not the super-user.
+.El
+.Pp
+.Fn fchroot
+will fail and the root directory will be unchanged if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+Search permission is denied for the directory referenced
+by the file descriptor.
+.It Bq Er EBADF
+The argument
+.Fa fd
+is not a valid file descriptor.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.It Bq Er ENOTDIR
+The argument
+.Fa fd
+does not reference a directory.
+.It Bq Er EPERM
+The effective user ID of the calling process is not the super-user.
+.El
+.Sh SEE ALSO
+.Xr chdir 2
+.Sh STANDARDS
+The
+.Fn chroot
+function conforms to
+.St -xsh5 ,
+with the restriction that the calling process' working directory must be at
+or under the new root directory.
+Otherwise, the working directory is silently set to the new root directory;
+this is an extension to the standard.
+.Pp
+.Fn chroot
+was declared a legacy interface, and subsequently removed in
+.St -p1003.1-2001 .
+.Sh HISTORY
+The
+.Fn chroot
+function call appeared in
+.Bx 4.2 .
+Working directory handling was changed in
+.Nx 1.4
+to prevent one way a process could use a second
+.Fn chroot
+call to a different directory to "escape" from the restricted subtree.
+The
+.Fn fchroot
+function appeared in
+.Nx 1.4 .
diff --git a/lib/nbsd_libc/sys/clock_settime.2 b/lib/nbsd_libc/sys/clock_settime.2
new file mode 100644 (file)
index 0000000..20337f1
--- /dev/null
@@ -0,0 +1,189 @@
+.\" $NetBSD: clock_settime.2,v 1.20 2009/03/11 13:39:14 joerg Exp $
+.\"
+.\" Copyright (c) 1999 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd February 11, 1999
+.Dt CLOCK_SETTIME 2
+.Os
+.Sh NAME
+.Nm clock_settime ,
+.Nm clock_gettime ,
+.Nm clock_getres
+.Nd clock and timer functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Ft int
+.Fn clock_settime "clockid_t clock_id" "const struct timespec *tp"
+.Ft int
+.Fn clock_gettime "clockid_t clock_id" "struct timespec *tp"
+.Ft int
+.Fn clock_getres "clockid_t clock_id" "struct timespec *res"
+.Sh DESCRIPTION
+The
+.Fn clock_settime
+function sets the clock identified by
+.Fa clock_id
+to the absolute time specified by
+.Fa tp .
+If the time specified by
+.Fa tp
+is not a multiple of the resolution of the clock,
+.Fa tp
+is truncated to a multiple of the resolution.
+.Pp
+The
+.Fn clock_gettime
+function stores the time of the clock identified by
+.Fa clock_id
+into the location specified by
+.Fa tp .
+.Pp
+The
+.Fn clock_getres
+function stores the resolution of the clock identified by
+.Fa clock_id
+into the location specified by
+.Fa res ,
+unless
+.Fa res
+is
+.Dv NULL .
+.Pp
+A
+.Fa clock_id
+of
+.Dv CLOCK_REALTIME
+identifies the realtime clock for the system.
+For this clock, the values specified by
+.Fn clock_settime
+and obtained by
+.Fn clock_gettime
+represent the amount of time (in seconds and nanoseconds)
+since 00:00 Universal Coordinated Time, January 1, 1970.
+.Pp
+A
+.Fa clock_id
+of
+.Dv CLOCK_MONOTONIC
+identifies a clock that increases at a steady rate (monotonically).
+This clock
+is not affected by calls to
+.Xr adjtime 2
+and
+.Xr settimeofday 2
+and will
+fail with an
+.Er EINVAL
+error if it's the clock specified in a call to
+.Fn clock_settime .
+The origin of the clock is unspecified.
+.Pp
+If the calling user is not the super-user, then the
+.Fn clock_settime
+function in the standard C library will try to use the
+.Xr clockctl 4
+device if present, thus making possible for non privileged users to
+set the system time.
+If
+.Xr clockctl 4
+is not present or not accessible, then
+.Fn clock_settime
+reverts to the
+.Fn clock_settime
+system call, which is restricted to the super user.
+.Sh RETURN VALUES
+A value of 0 is returned on success.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn clock_settime ,
+.Fn clock_gettime
+and
+.Fn clock_getres
+functions will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa clock_id
+argument does not specify a known clock.
+.It Bq Er ENOSYS
+The function is not supported by this implementation.
+.El
+.Pp
+The
+.Fn clock_settime
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa tp
+argument is outside the range for the specified clock,
+.Fa clock_id .
+.It Bq Er EINVAL
+The
+.Fa tp
+argument specified a nanosecond value less than zero of greater than or equal
+1000 million.
+.It Bq Er EINVAL
+The
+.Fa clock_id
+argument is a clock that can not be adjusted.
+.It Bq Er EPERM
+The
+calling process does not have the appropriate privilege to set the specified
+clock,
+.Fa clock_id .
+.El
+.Pp
+The
+.Fn clock_gettime
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+The
+.Fa tp
+argument specifies an address that is not a valid part of the process address
+space.
+.El
+.Sh SEE ALSO
+.Xr ctime 3 ,
+.Xr time 3 ,
+.\" .Xr timer_gettime 3 ,
+.Xr clockctl 4
+.Sh STANDARDS
+The
+.Fn clock_settime ,
+.Fn clock_gettime
+and
+.Fn clock_getres
+functions conform to
+.St -p1003.1b-93 .
diff --git a/lib/nbsd_libc/sys/clock_settime.c b/lib/nbsd_libc/sys/clock_settime.c
new file mode 100644 (file)
index 0000000..5c0bd72
--- /dev/null
@@ -0,0 +1,98 @@
+/*     $NetBSD: clock_settime.c,v 1.11 2009/01/11 02:46:30 christos Exp $ */
+
+/*
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.      
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Emmanuel Dreyfus.
+ *
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: clock_settime.c,v 1.11 2009/01/11 02:46:30 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/syscall.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <paths.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <sys/clockctl.h>
+extern int __clockctl_fd;
+
+int ____clock_settime50(clockid_t, const struct timespec *);
+
+int
+clock_settime(clockid_t clock_id, const struct timespec *tp)
+{
+       struct clockctl_clock_settime args;
+       int rv;
+
+       /*
+        * always try the syscall first and attempt to switch to
+        * clockctl if that fails.
+        */
+       if (__clockctl_fd == -1) {
+               rv = ____clock_settime50(clock_id, tp);
+       
+               /*
+                * return unless we failed with EPERM
+                */
+               if (rv != -1 || errno != EPERM)
+                       return rv;
+
+               /*
+                * If this fails, it means that we are not root
+                * and we cannot open clockctl. This is a failure.
+                */
+               __clockctl_fd = open(_PATH_CLOCKCTL, O_WRONLY, 0);
+               if (__clockctl_fd == -1) {
+                       /* original error was EPERM - don't leak open errors */
+                       errno = EPERM;
+                       return -1;
+               }
+
+               (void) fcntl(__clockctl_fd, F_SETFD, FD_CLOEXEC);
+       }
+
+       /* 
+        * If __clockctl_fd >=0, clockctl has already been open
+        * and used, so we carry on using it.
+        */
+       args.clock_id = clock_id;
+       args.tp = tp;
+       return ioctl(__clockctl_fd, CLOCKCTL_CLOCK_SETTIME, &args);
+}
diff --git a/lib/nbsd_libc/sys/clone.2 b/lib/nbsd_libc/sys/clone.2
new file mode 100644 (file)
index 0000000..9ef070b
--- /dev/null
@@ -0,0 +1,204 @@
+.\"    $NetBSD: clone.2,v 1.12 2010/05/04 06:13:43 jruoho Exp $
+.\"
+.\" Copyright (c) 2001 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 4, 2010
+.Dt CLONE 2
+.Os
+.Sh NAME
+.Nm clone
+.Nd spawn new process with options
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sched.h
+.Ft pid_t
+.Fn clone "int (*func)(void *arg)" "void *stack" "int flags" "void *arg"
+.Ft pid_t
+.Fn __clone "int (*func)(void *arg)" "void *stack" "int flags" "void *arg"
+.Sh DESCRIPTION
+The
+.Nm
+system call (and associated library support code) creates a new process
+in a way that allows the caller to specify several options for the new
+process creation.
+.Pp
+Unlike
+.Xr fork 2
+or
+.Xr vfork 2 ,
+in which the child process returns to the call site,
+.Nm
+causes the child process to begin execution at the function specified
+by
+.Ar func .
+The argument
+.Ar arg
+is passed to the entry point, as a means for the parent to provide
+context to the child.
+The stack pointer for the child process will be set to
+.Ar stack .
+Note that the
+.Nm
+interface requires that the application know the stack direction
+for the architecture, and that the caller initialize the
+.Ar stack
+argument as appropriate for the stack direction.
+.Pp
+The
+.Ar flags
+argument specifies several options that control how the child process
+is created.
+The lower 8 bits of
+.Ar flags
+specify the signal that is to be sent to the parent when the child
+exits.
+The following flags may also be specified by bitwise-or'ing
+them with the signal value:
+.Bl -tag -width "CLONE_SIGHAND" -offset 2n
+.It Dv CLONE_VM
+Share the virtual address space with the parent.
+The address space is shared in the same way as
+.Xr vfork 2 .
+.It Dv CLONE_FS
+Share the
+.Dq file system information
+with the parent.
+This include the current working directory and file creation mask.
+.It Dv CLONE_FILES
+Share the file descriptor table with the parent.
+.It Dv CLONE_SIGHAND
+Share the signal handler set with the parent.
+Note that the signal mask
+is never shared between the parent and the child, even if
+.Dv CLONE_SIGHAND
+is set.
+.It Dv CLONE_VFORK
+Preserve the synchronization semantics of
+.Xr vfork 2 ;
+the parent blocks until the child exits.
+.El
+.Pp
+The
+.Nm
+call returns the pid of the child in the parent's context.
+The child is provided no return value, since it begins execution at
+a different address.
+.Pp
+If the child process's entry point returns, the value it returns
+is passed to
+.Xr _exit 2 ,
+and the child process exits.
+Note that if the child process wants to exit directly, it should use
+.Xr _exit 2 ,
+and not
+.Xr exit 3 ,
+since
+.Xr exit 3
+will flush and close standard I/O channels, and thereby corrupt the
+parent process's standard I/O data structures (even with
+.Xr fork 2
+it is wrong to call
+.Xr exit 3
+since buffered data would then be flushed twice).
+.Pp
+Note that
+.Nm
+is not intended to be used for new native
+.Nx
+applications.
+It is provided as a means to port software
+originally written for the Linux operating system to
+.Nx .
+.Sh RETURN VALUES
+Same as for
+.Xr fork 2 .
+.Sh ERRORS
+Same as for
+.Xr fork 2 .
+.Sh SEE ALSO
+.Xr chdir 2 ,
+.Xr chroot 2 ,
+.Xr fork 2 ,
+.Xr sigaction 2 ,
+.Xr sigprocmask 2 ,
+.Xr umask 2 ,
+.Xr vfork 2 ,
+.Xr wait 2
+.Sh HISTORY
+The
+.Fn clone
+function call appeared in
+.Nx 1.6 .
+It is compatible with the Linux function call of the same name
+with respect to the described options.
+.Sh BUGS
+The
+.Nx
+implementation of
+.Fn clone
+does not implement the following
+.Ar flags
+that are present in the Linux implementation:
+.Pp
+.Bl -bullet -offset indent -compact
+.It
+.Dv CLONE_CHILD_CLEARTID
+.It
+.Dv CLONE_CHILD_SETTID
+.It
+.Dv CLONE_IO
+.It
+.Dv CLONE_NEWIPC
+.It
+.Dv CLONE_NEWNET
+.It
+.Dv CLONE_NEWNS
+.It
+.Dv CLONE_NEWPID
+.It
+.Dv CLONE_NEWUTS
+.It
+.Dv CLONE_PARENT
+.It
+.Dv CLONE_PARENT_SETTID
+.It
+.Dv CLONE_PID
+.It
+.Dv CLONE_PTRACE
+.It
+.Dv CLONE_SETTLS
+.It
+.Dv CLONE_STOPPED
+.It
+.Dv CLONE_SYSVSEM
+.It
+.Dv CLONE_THREAD
+.It
+.Dv CLONE_UNTRACED
+.El
diff --git a/lib/nbsd_libc/sys/close.2 b/lib/nbsd_libc/sys/close.2
new file mode 100644 (file)
index 0000000..6f89c57
--- /dev/null
@@ -0,0 +1,132 @@
+.\"    $NetBSD: close.2,v 1.17 2004/06/01 16:14:10 kleink Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 1993, 1994
+.\"    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.
+.\" 3. 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.
+.\"
+.\"     @(#)close.2    8.2 (Berkeley) 4/19/94
+.\"
+.Dd April 19, 1994
+.Dt CLOSE 2
+.Os
+.Sh NAME
+.Nm close
+.Nd delete a descriptor
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn close "int d"
+.Sh DESCRIPTION
+The
+.Fn close
+system call deletes a descriptor from the per-process object
+reference table.
+If this is the last reference to the underlying object, the
+object will be deactivated.
+For example, on the last close of a file the current
+.Em seek
+pointer associated with the file is lost; on the last close of a
+.Xr socket 2
+associated naming information and queued data are discarded; on
+the last close of a file holding an advisory lock the lock is
+released (see
+.Xr flock 2 ) .
+.Pp
+When a process exits, all associated descriptors are freed, but
+since there is a limit on active descriptors per processes, the
+.Fn close
+system call
+is useful when a large quantity of file descriptors are being handled.
+.Pp
+When a process calls
+.Xr fork 2 ,
+all descriptors for the new child process reference the same
+objects as they did in the parent before the
+.Fn fork .
+If a new process is then to be run using
+.Xr execve 2 ,
+the process would normally inherit these descriptors.
+Most of the descriptors can be rearranged with
+.Xr dup2 2
+or deleted with
+.Fn close
+before the
+.Fn execve
+is attempted, but if some of these descriptors will still be needed if the
+.Fn execve
+fails, it is necessary to arrange for them to be closed only if the
+.Fn execve
+succeeds.
+For this reason, the system call
+.Bl -item -offset indent
+.It
+.Fn fcntl d F_SETFD 1 ;
+.El
+.Pp
+is provided,
+which arranges that a descriptor
+.Dq Fa d
+will be closed after a successful
+.Fn execve ;
+the system call
+.Bl -item -offset indent
+.It
+.Fn fcntl d F_SETFD 0 ;
+.El
+.Pp
+restores the default, which is to not close descriptor
+.Dq Fa d .
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn close
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa d
+is not an active descriptor.
+.It Bq Er EINTR
+An interrupt was received.
+.El
+.Sh SEE ALSO
+.Xr accept 2 ,
+.Xr execve 2 ,
+.Xr fcntl 2 ,
+.Xr flock 2 ,
+.Xr open 2 ,
+.Xr pipe 2 ,
+.Xr socket 2 ,
+.Xr socketpair 2
+.Sh STANDARDS
+The
+.Fn close
+function conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/sys/connect.2 b/lib/nbsd_libc/sys/connect.2
new file mode 100644 (file)
index 0000000..f2d283c
--- /dev/null
@@ -0,0 +1,178 @@
+.\"    $NetBSD: connect.2,v 1.28 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" 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.
+.\" 3. 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.
+.\"
+.\"     @(#)connect.2  8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 18, 2004
+.Dt CONNECT 2
+.Os
+.Sh NAME
+.Nm connect
+.Nd initiate a connection on a socket
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft int
+.Fn connect "int s" "const struct sockaddr *name" "socklen_t namelen"
+.Sh DESCRIPTION
+The parameter
+.Fa s
+is a socket.
+If it is of type
+.Dv SOCK_DGRAM ,
+this call specifies the peer with which the socket is to be associated;
+this address is that to which datagrams are to be sent,
+and the only address from which datagrams are to be received.
+If the socket is of type
+.Dv SOCK_STREAM ,
+this call attempts to make a connection to
+another socket.
+The other socket is specified by
+.Fa name ,
+which is an address in the communications space of the socket.
+.Fa namelen
+indicates the amount of space pointed to by
+.Fa name ,
+in bytes.
+Each communications space interprets the
+.Fa name
+parameter in its own way.
+Generally, stream sockets may successfully
+.Fn connect
+only once; datagram sockets may use
+.Fn connect
+multiple times to change their association.
+Datagram sockets may dissolve the association
+by connecting to an invalid address, such as a null address.
+.Pp
+If a
+.Fn connect
+call is interrupted by a signal, it will return with errno set to
+.Er EINTR
+and the connection attempt will proceed as if the socket was non-blocking.
+Subsequent calls to
+.Fn connect
+will set errno to
+.Er EALREADY .
+.Sh RETURN VALUES
+If the connection or binding succeeds, 0 is returned.
+Otherwise a \-1 is returned, and a more specific error
+code is stored in
+.Va errno .
+.Sh ERRORS
+The
+.Fn connect
+call fails if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa s
+is not a valid descriptor.
+.It Bq Er ENOTSOCK
+.Fa s
+is a descriptor for a file, not a socket.
+.It Bq Er EADDRNOTAVAIL
+The specified address is not available on this machine.
+.It Bq Er EAFNOSUPPORT
+Addresses in the specified address family cannot be used with this socket.
+.It Bq Er EISCONN
+The socket is already connected.
+.It Bq Er ETIMEDOUT
+Connection establishment timed out without establishing a connection.
+.It Bq Er ECONNREFUSED
+The attempt to connect was forcefully rejected.
+.It Bq Er ENETUNREACH
+The network isn't reachable from this host.
+.It Bq Er EADDRINUSE
+The address is already in use.
+.It Bq Er EFAULT
+The
+.Fa name
+parameter specifies an area outside
+the process address space.
+.It Bq Er EINPROGRESS
+The socket is non-blocking and the connection cannot be completed immediately.
+It is possible to
+.Xr select 2
+or
+.Xr poll 2
+for completion by selecting or polling the socket for writing.
+The success or failure of the connect operation may be determined by using
+.Xr getsockopt 2
+to read the socket error status with the
+.Dv SO_ERROR
+option at the
+.Dv SOL_SOCKET
+level.
+The returned socket error status is zero on success, or one of the
+error codes listed here on failure.
+.It Bq Er EALREADY
+Either the socket is non-blocking mode or a previous call to
+.Fn connect
+was interrupted by a signal, and the connection attempt has not yet
+been completed.
+.It Bq Er EINTR
+The connection attempt was interrupted by a signal.
+.El
+.Pp
+The following errors are specific to connecting names in the
+.Ux
+domain.
+These errors may not apply in future versions of the
+.Ux
+IPC domain.
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named socket does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix, or
+write access to the named socket is denied.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.El
+.Sh SEE ALSO
+.Xr accept 2 ,
+.Xr getsockname 2 ,
+.Xr getsockopt 2 ,
+.Xr poll 2 ,
+.Xr select 2 ,
+.Xr socket 2
+.Sh HISTORY
+The
+.Fn connect
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/dup.2 b/lib/nbsd_libc/sys/dup.2
new file mode 100644 (file)
index 0000000..6cf0d51
--- /dev/null
@@ -0,0 +1,138 @@
+.\"    $NetBSD: dup.2,v 1.21 2009/01/11 02:46:30 christos Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)dup.2      8.1 (Berkeley) 6/4/93
+.\"
+.Dd December 2, 2008
+.Dt DUP 2
+.Os
+.Sh NAME
+.Nm dup ,
+.Nm dup2
+.Nd duplicate an existing file descriptor
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn dup "int oldd"
+.Ft int
+.Fn dup2 "int oldd" "int newd"
+.Sh DESCRIPTION
+.Fn dup
+duplicates an existing object descriptor and returns its value to
+the calling process
+.Fa ( newd
+=
+.Fn dup oldd ) .
+The argument
+.Fa oldd
+is a small non-negative integer index in
+the per-process descriptor table.
+The value must be less than the size of the table, which is returned by
+.Xr getdtablesize 3 .
+The new descriptor returned by the call
+is the lowest numbered descriptor currently not in use by the process.
+.Pp
+The object referenced by the descriptor does not distinguish
+between
+.Fa oldd
+and
+.Fa newd
+in any way.
+Thus if
+.Fa newd
+and
+.Fa oldd
+are duplicate references to an open
+file,
+.Xr read 2 ,
+.Xr write 2
+and
+.Xr lseek 2
+calls all move a single pointer into the file,
+and append mode, non-blocking I/O and asynchronous I/O options
+are shared between the references.
+If a separate pointer into the file is desired, a different
+object reference to the file must be obtained by issuing an
+additional
+.Xr open 2
+call.
+The close-on-exec flag on the new file descriptor is unset.
+.Pp
+In
+.Fn dup2 ,
+the value of the new descriptor
+.Fa newd
+is specified.
+If this descriptor is already
+in use, the descriptor is first deallocated as if a
+.Xr close 2
+call had been done first.
+If
+.Fa newd
+and
+.Fa oldd
+are the same, the call has no effect.
+.Sh RETURN VALUES
+The value \-1 is returned if an error occurs in either call.
+The external variable
+.Va errno
+indicates the cause of the error.
+.Sh ERRORS
+.Fn dup
+and
+.Fn dup2
+fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa oldd
+is not a valid active descriptor
+or
+.Fa newd
+is not in the range of valid file descriptors.
+.It Bq Er EMFILE
+Too many descriptors are active.
+.El
+.Sh SEE ALSO
+.Xr accept 2 ,
+.Xr close 2 ,
+.Xr fcntl 2 ,
+.Xr open 2 ,
+.Xr pipe 2 ,
+.Xr socket 2 ,
+.Xr socketpair 2 ,
+.Xr getdtablesize 3
+.Sh STANDARDS
+The
+.Fn dup
+and
+.Fn dup2
+functions conform to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/sys/execve.2 b/lib/nbsd_libc/sys/execve.2
new file mode 100644 (file)
index 0000000..0b390f5
--- /dev/null
@@ -0,0 +1,293 @@
+.\"    $NetBSD: execve.2,v 1.40 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)execve.2   8.5 (Berkeley) 6/1/94
+.\"
+.Dd February 24, 2008
+.Dt EXECVE 2
+.Os
+.Sh NAME
+.Nm execve
+.Nd execute a file
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn execve "const char *path" "char *const argv[]" "char *const envp[]"
+.Sh DESCRIPTION
+.Fn execve
+transforms the calling process into a new process.
+The new process is constructed from an ordinary file,
+whose name is pointed to by
+.Fa path ,
+called the
+.Em new process file .
+This file is either an executable object file,
+or a file of data for an interpreter.
+An executable object file consists of an identifying header,
+followed by pages of data representing the initial program (text)
+and initialized data pages.
+Additional pages may be specified
+by the header to be initialized with zero data;  see
+.Xr a.out 5 .
+.Pp
+An interpreter file begins with a line of the form:
+.Pp
+.Bd -filled -offset indent -compact
+.Sy \&#!
+.Em interpreter
+.Bq Em arg
+.Ed
+.Pp
+When an interpreter file is
+.Fn execve Ns d
+the system runs the specified
+.Em interpreter .
+If the optional
+.Em arg
+is specified, it becomes the first argument to the
+.Em interpreter ,
+and the name of the originally
+.Fn execve Ns d
+file becomes the second argument;
+otherwise, the name of the originally
+.Fn execve Ns d
+file becomes the first argument.
+The original arguments are shifted over to become the subsequent arguments.
+The zeroth argument, normally the name of the
+.Fn execve Ns d
+file, is left unchanged.
+The interpreter named by
+.Em interpreter
+must not itself be an interpreter file.
+(See
+.Xr script 7
+for a detailed discussion of interpreter file execution.)
+.Pp
+The argument
+.Fa argv
+is a pointer to a null-terminated array of
+character pointers to null-terminated character strings.
+These strings construct the argument list to be made available to the new
+process.
+By custom, the first element should be
+the name of the executed program (for example, the last component of
+.Fa path ) .
+.Pp
+The argument
+.Fa envp
+is also a pointer to a null-terminated array of
+character pointers to null-terminated strings.
+A pointer to this array is normally stored in the global variable
+.Va environ .
+These strings pass information to the
+new process that is not directly an argument to the command (see
+.Xr environ 7 ) .
+.Pp
+File descriptors open in the calling process image remain open in
+the new process image, except for those for which the close-on-exec
+flag is set (see
+.Xr close 2
+and
+.Xr fcntl 2 ) .
+Descriptors that remain open are unaffected by
+.Fn execve .
+.Pp
+In the case of a new setuid or setgid executable being executed, if
+file descriptors 0, 1, or 2 (representing stdin, stdout, and stderr)
+are currently unallocated, these descriptors will be opened to point to
+some system file like
+.Pa /dev/null .
+The intent is to ensure these descriptors are not unallocated, since
+many libraries make assumptions about the use of these 3 file descriptors.
+.Pp
+Signals set to be ignored in the calling process are set to be ignored in
+the new process.
+Signals which are set to be caught in the calling process image
+are set to default action in the new process image.
+Blocked signals remain blocked regardless of changes to the signal action.
+The signal stack is reset to be undefined (see
+.Xr sigaction 2
+for more information).
+.Pp
+If the set-user-ID mode bit of the new process image file is set
+(see
+.Xr chmod 2 ) ,
+the effective user ID of the new process image is set to the owner ID
+of the new process image file.
+If the set-group-ID mode bit of the new process image file is set,
+the effective group ID of the new process image is set to the group ID
+of the new process image file.
+(The effective group ID is the first element of the group list.)
+The real user ID, real group ID and
+other group IDs of the new process image remain the same as the calling
+process image.
+After any set-user-ID and set-group-ID processing,
+the effective user ID is recorded as the saved set-user-ID,
+and the effective group ID is recorded as the saved set-group-ID.
+These values may be used in changing the effective IDs later (see
+.Xr setuid 2 ) .
+.Pp
+The new process also inherits the following attributes from
+the calling process:
+.Pp
+.Bl -column parent_process_ID -offset indent -compact
+.It process ID Ta see Xr getpid 2
+.It parent process ID Ta see Xr getppid 2
+.It process group ID Ta see Xr getpgrp 2
+.It access groups Ta see Xr getgroups 2
+.It working directory Ta see Xr chdir 2
+.It root directory Ta see Xr chroot 2
+.It control terminal Ta see Xr termios 4
+.It resource usages Ta see Xr getrusage 2
+.It interval timers Ta see Xr getitimer 2
+.It resource limits Ta see Xr getrlimit 2
+.It file mode mask Ta see Xr umask 2
+.It signal mask Ta see Xr sigaction 2 ,
+.Xr sigprocmask 2
+.El
+.Pp
+When a program is executed as a result of an
+.Fn execve
+call, it is entered as follows:
+.Bd -literal -offset indent
+main(argc, argv, envp)
+int argc;
+char **argv, **envp;
+.Ed
+.Pp
+where
+.Fa argc
+is the number of elements in
+.Fa argv
+(the
+.Dq arg count )
+and
+.Fa argv
+points to the array of character pointers
+to the arguments themselves.
+.Sh RETURN VALUES
+As the
+.Fn execve
+function overlays the current process image
+with a new process image the successful call
+has no process to return to.
+If
+.Fn execve
+does return to the calling process an error has occurred; the
+return value will be \-1 and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn execve
+will fail and return to the calling process if:
+.Bl -tag -width Er
+.It Bq Er E2BIG
+The number of bytes in the new process's argument list
+is larger than the system-imposed limit.
+The limit in the system as released is 262144 bytes
+.Dv ( NCARGS
+in
+.Ao Pa sys/param.h Ac ) .
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix,
+the new process file is not an ordinary file,
+its file mode denies execute permission, or
+it is on a filesystem mounted with execution
+disabled
+.Dv ( MNT_NOEXEC
+in
+.Ao Pa sys/mount.h Ac ) .
+.It Bq Er EAGAIN
+A
+.Xr setuid 7
+process has exceeded the current resource limit for the number of
+processes it is allowed to run concurrently.
+.It Bq Er EFAULT
+The new process file is not as long as indicated by
+the size values in its header; or
+.Fa path ,
+.Fa argv ,
+or
+.Fa envp
+point to an illegal address.
+.It Bq Er EIO
+An I/O error occurred while reading from the file system.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The new process file does not exist, or
+the new process file is a script starting with
+.Li #!
+and the script interpreter does not exist.
+.It Bq Er ENOEXEC
+The new process file has the appropriate access
+permission, but has an invalid magic number in its header.
+.It Bq Er ENOMEM
+The new process requires more virtual memory than
+is allowed by the imposed maximum
+.Pq Xr getrlimit 2 .
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ETXTBSY
+The new process file is a pure procedure (shared text)
+file that is currently open for writing or reading by some process.
+.El
+.Sh SEE ALSO
+.Xr _exit 2 ,
+.Xr fork 2 ,
+.Xr execl 3 ,
+.Xr environ 7 ,
+.Xr script 7
+.Sh STANDARDS
+The
+.Fn execve
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+The
+.Fn execve
+function call first appeared in
+.At v7 .
+.Sh BUGS
+If a program is
+.Em setuid
+to a non-super-user, but is executed when
+the real
+.Em uid
+is
+.Dq root ,
+then the program has some of the powers of a super-user as well.
diff --git a/lib/nbsd_libc/sys/extattr_get_file.2 b/lib/nbsd_libc/sys/extattr_get_file.2
new file mode 100644 (file)
index 0000000..df37b9c
--- /dev/null
@@ -0,0 +1,256 @@
+.\"    $NetBSD: extattr_get_file.2,v 1.3 2005/01/02 18:28:48 wiz Exp $
+.\"
+.\" Copyright (c) 2001 Dima Dorfman <dima@unixfreak.org>
+.\" Copyright (c) 2003 Robert Watson <rwatson@FreeBSD.org>
+.\" 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.
+.\"
+.\" FreeBSD: src/lib/libc/sys/extattr_get_file.2,v 1.14 2004/07/05 17:12:52 ru Exp
+.\"
+.Dd January 2, 2004
+.Dt EXTATTR_GET_FILE 2
+.Os
+.Sh NAME
+.Nm extattr_get_fd ,
+.Nm extattr_set_fd ,
+.Nm extattr_delete_fd ,
+.Nm extattr_list_fd ,
+.Nm extattr_get_file ,
+.Nm extattr_set_file ,
+.Nm extattr_delete_file ,
+.Nm extattr_list_file ,
+.Nm extattr_get_link ,
+.Nm extattr_set_link ,
+.Nm extattr_delete_link ,
+.Nm extattr_list_link
+.Nd system calls to manipulate VFS extended attributes
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/extattr.h
+.Ft ssize_t
+.Fn extattr_get_fd "int fd" "int attrnamespace" "const char *attrname" "void *data" "size_t nbytes"
+.Ft int
+.Fn extattr_set_fd "int fd" "int attrnamespace" "const char *attrname" "const void *data" "size_t nbytes"
+.Ft int
+.Fn extattr_delete_fd "int fd" "int attrnamespace" "const char *attrname"
+.Ft ssize_t
+.Fn extattr_list_fd "int fd" "int attrnamespace" "void *data" "size_t nbytes"
+.Ft ssize_t
+.Fn extattr_get_file "const char *path" "int attrnamespace" "const char *attrname" "void *data" "size_t nbytes"
+.Ft int
+.Fn extattr_set_file "const char *path" "int attrnamespace" "const char *attrname" "const void *data" "size_t nbytes"
+.Ft int
+.Fn extattr_delete_file "const char *path" "int attrnamespace" "const char *attrname"
+.Ft ssize_t
+.Fn extattr_list_file "const char *path" "int attrnamespace" "void *data" "size_t nbytes"
+.Ft ssize_t
+.Fn extattr_get_link "const char *path" "int attrnamespace" "const char *attrname" "void *data" "size_t nbytes"
+.Ft int
+.Fn extattr_set_link "const char *path" "int attrnamespace" "const char *attrname" "const void *data" "size_t nbytes"
+.Ft int
+.Fn extattr_delete_link "const char *path" "int attrnamespace" "const char *attrname"
+.Ft ssize_t
+.Fn extattr_list_link "const char *path" "int attrnamespace" "void *data" "size_t nbytes"
+.Sh DESCRIPTION
+Named extended attributes are meta-data associated with vnodes
+representing files and directories.
+They exist as
+.Qq Li name=value
+pairs within a set of namespaces.
+.Pp
+The
+.Fn extattr_get_file
+system call retrieves the value of the specified extended attribute into
+a buffer pointed to by
+.Fa data
+of size
+.Fa nbytes .
+The
+.Fn extattr_set_file
+system call sets the value of the specified extended attribute to the data
+described by
+.Fa data .
+The
+.Fn extattr_delete_file
+system call deletes the extended attribute specified.
+The
+.Fn extattr_list_file
+returns a list of attributes present in the requested namespace, separated
+by ASCII 0 (nul) characters.
+The
+.Fn extattr_get_file
+and
+.Fn extattr_list_file
+calls consume the
+.Fa data
+and
+.Fa nbytes
+arguments in the style of
+.Xr read 2 ;
+.Fn extattr_set_file
+consumes these arguments in the style of
+.Xr write 2 .
+.Pp
+If
+.Fa data
+is
+.Dv NULL
+in a call to
+.Fn extattr_get_file
+then the size of defined extended attribute data will be returned, rather
+than the quantity read, permitting applications to test the size of the
+data without performing a read.
+.Pp
+The
+.Fn extattr_delete_link ,
+.Fn extattr_get_link ,
+and
+.Fn extattr_set_link
+system calls behave in the same way as their _file counterparts, except that
+they do not follow symlinks.
+.Pp
+The
+.Fn extattr_get_fd ,
+.Fn extattr_set_fd ,
+and
+.Fn extattr_delete_fd
+calls are identical to their
+.Qq Li _file
+counterparts except for the first argument.
+The
+.Qq Li _fd
+functions take a file descriptor, while the
+.Qq Li _file
+functions take a path.
+Both arguments describe a file associated with the extended attribute
+that should be manipulated.
+.Pp
+The following arguments are common to all the system calls described here:
+.Bl -tag -width attrnamespace
+.It Fa attrnamespace
+the namespace in which the extended attribute resides; see
+.Xr extattr 9
+.It Fa attrname
+the name of the extended attribute
+.El
+.Pp
+Named extended attribute semantics vary by file system implementing the call.
+Not all operations may be supported for a particular attribute.
+Additionally, the format of the data in
+.Fa data
+is attribute-specific.
+.Pp
+For more information on named extended attributes, please see
+.Xr extattr 9 .
+.Sh RETURN VALUES
+If successful, the
+.Fn extattr_get_file
+and
+.Fn extattr_set_file
+calls return the number of bytes
+that were read or written from the
+.Fa data ,
+respectively, or if
+.Fa data
+was
+.Dv NULL ,
+then
+.Fn extattr_get_file
+returns the number of bytes available to read.
+If any of the calls are unsuccessful, the value \-1 is returned
+and the global variable
+.Va errno
+is set to indicate the error.
+.Pp
+.Rv -std extattr_delete_file
+.Sh ERRORS
+The following errors may be returned by the system calls themselves.
+Additionally, the file system implementing the call may return any
+other errors it desires.
+.Bl -tag -width Er
+.It Bq Er EFAULT
+The
+.Fa attrnamespace
+and
+.Fa attrname
+arguments,
+or the memory range defined by
+.Fa data
+and
+.Fa nbytes
+point outside the process's allocated address space.
+.It Bq Er ENAMETOOLONG
+The attribute name was longer than
+.Dv EXTATTR_MAXNAMELEN .
+.El
+.Pp
+The
+.Fn extattr_get_fd ,
+.Fn extattr_set_fd ,
+and
+.Fn extattr_delete_fd
+system calls may also fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The file descriptor referenced by
+.Fa fd
+was invalid.
+.El
+.Pp
+Additionally, the
+.Fn extattr_get_file ,
+.Fn extattr_set_file ,
+and
+.Fn extattr_delete_file
+calls may also fail due to the following errors:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded 255 characters,
+or an entire path name exceeded 1023 characters.
+.It Bq Er ENOENT
+A component of the path name that must exist does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.\" XXX are any missing?
+.El
+.Sh SEE ALSO
+.Xr getextattr 1 ,
+.Xr extattr 3 ,
+.Xr extattr 9
+.Sh HISTORY
+Extended attribute support was developed as part of the
+.Tn TrustedBSD
+Project, and introduced in
+.Fx 5.0
+and
+.Nx 3.0 .
+It was developed to support security extensions requiring additional labels
+to be associated with each file or directory.
+.Sh CAVEATS
+This interface is under active development, and as such is subject to
+change as applications are adapted to use it.
+Developers are discouraged from relying on its stability.
diff --git a/lib/nbsd_libc/sys/fcntl.2 b/lib/nbsd_libc/sys/fcntl.2
new file mode 100644 (file)
index 0000000..a22fe04
--- /dev/null
@@ -0,0 +1,526 @@
+.\"    $NetBSD: fcntl.2,v 1.37 2010/05/17 12:16:43 jruoho Exp $
+.\"
+.\" 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.
+.\" 3. 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.
+.\"
+.\"     @(#)fcntl.2    8.2 (Berkeley) 1/12/94
+.\"
+.Dd May 17, 2010
+.Dt FCNTL 2
+.Os
+.Sh NAME
+.Nm fcntl
+.Nd file descriptor control
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In fcntl.h
+.Ft int
+.Fn fcntl "int fd" "int cmd" "..."
+.Sh DESCRIPTION
+.Fn fcntl
+provides for control over descriptors.
+The argument
+.Fa fd
+is a descriptor to be operated on by
+.Fa cmd
+as described below.
+The third parameter is called
+.Fa arg
+and is technically a pointer to void, but it is
+interpreted as an int by some commands and ignored by others.
+.Pp
+Commands are:
+.Bl -tag -width F_GETOWNX
+.It Dv F_DUPFD
+Return a new descriptor as follows:
+.Pp
+.Bl -bullet -compact -offset 4n
+.It
+Lowest numbered available descriptor greater than or equal to
+.Fa arg ,
+which is interpreted as an int.
+.It
+Same object references as the original descriptor.
+.It
+New descriptor shares the same file offset if the object
+was a file.
+.It
+Same access mode (read, write or read/write).
+.It
+Same file status flags (i.e., both file descriptors
+share the same file status flags).
+.It
+The close-on-exec flag associated with the new file descriptor
+is cleared to remain open across
+.Xr execve 2
+system calls.
+.El
+.It Dv F_GETFD
+Get the close-on-exec flag associated with the file descriptor
+.Fa fd
+as
+.Dv FD_CLOEXEC .
+If the returned value ANDed with
+.Dv FD_CLOEXEC
+is 0,
+the file will remain open across
+.Fn exec ,
+otherwise the file will be closed upon execution of
+.Fn exec
+.Fa ( arg
+is ignored).
+.It Dv F_SETFD
+Set the close-on-exec flag associated with
+.Fa fd
+to
+.Fa arg ,
+where
+.Fa arg
+is either 0 or
+.Dv FD_CLOEXEC ,
+as described above.
+.It Dv F_GETFL
+Get descriptor status flags, as described below
+.Fa ( arg
+is ignored).
+.It Dv F_SETFL
+Set descriptor status flags to
+.Fa arg ,
+which is interpreted as an int.
+.It Dv F_GETOWN
+Get the process ID or process group
+currently receiving
+.Dv SIGIO
+and
+.Dv SIGURG
+signals; process groups are returned
+as negative values
+.Fa ( arg
+is ignored).
+.It Dv F_SETOWN
+Set the process or process group
+to receive
+.Dv SIGIO
+and
+.Dv SIGURG
+signals;
+process groups are specified by supplying
+.Fa arg
+as negative, otherwise
+.Fa arg
+is interpreted as a process ID.
+The argument
+.Fa arg
+is interpreted as an int.
+.It Dv F_CLOSEM
+Close all file descriptors greater than or equal to
+.Ar fd .
+.It Dv F_MAXFD
+Return the maximum file descriptor number currently open by the process.
+.El
+.Pp
+The flags for the
+.Dv F_GETFL
+and
+.Dv F_SETFL
+flags are as follows:
+.Bl -tag -width O_NONBLOCKX
+.It Dv O_NONBLOCK
+Non-blocking I/O; if no data is available to a
+.Xr read 2
+call, or if a
+.Xr write 2
+operation would block,
+the read or write call returns \-1 with the error
+.Er EAGAIN .
+.It Dv O_APPEND
+Force each write to append at the end of file;
+corresponds to the
+.Dv O_APPEND
+flag of
+.Xr open 2 .
+.It Dv O_ASYNC
+Enable the
+.Dv SIGIO
+signal to be sent to the process group
+when I/O is possible, e.g.,
+upon availability of data to be read.
+.El
+.Pp
+Several commands are available for doing advisory file locking;
+they all operate on the following structure:
+.Bd -literal
+struct flock {
+       off_t   l_start;        /* starting offset */
+       off_t   l_len;          /* len = 0 means until end of file */
+       pid_t   l_pid;          /* lock owner */
+       short   l_type;         /* lock type: read/write, etc. */
+       short   l_whence;       /* type of l_start */
+};
+.Ed
+.Pp
+The commands available for advisory record locking are as follows:
+.Bl -tag -width F_SETLKWX
+.It Dv F_GETLK
+Get the first lock that blocks the lock description pointed to by the
+third argument,
+.Fa arg ,
+taken as a pointer to a
+.Fa "struct flock"
+(see above).
+The information retrieved overwrites the information passed to
+.Nm
+in the
+.Fa flock
+structure.
+If no lock is found that would prevent this lock from being created,
+the structure is left unchanged by this function call except for the
+lock type
+.Fa l_type ,
+which is set to
+.Dv F_UNLCK .
+.It Dv F_SETLK
+Set or clear a file segment lock according to the lock description
+pointed to by the third argument,
+.Fa arg ,
+taken as a pointer to a
+.Fa "struct flock"
+(see above).
+As specified by the value of
+.Fa l_type ,
+.Dv F_SETLK
+is used to establish shared (or read) locks
+.Pq Dv F_RDLCK
+or exclusive (or write) locks,
+.Pq Dv F_WRLCK ,
+as well as remove either type of lock
+.Pq Dv F_UNLCK .
+If a shared or exclusive lock cannot be set,
+.Nm
+returns immediately with
+.Er EAGAIN .
+.It Dv F_SETLKW
+This command is the same as
+.Dv F_SETLK
+except that if a shared or exclusive lock is blocked by other locks,
+the process waits until the request can be satisfied.
+If a signal that is to be caught is received while
+.Nm
+is waiting for a region, the
+.Nm
+will be interrupted if the signal handler has not specified the
+.Dv SA_RESTART
+(see
+.Xr sigaction 2 ) .
+.El
+.Pp
+When a shared lock has been set on a segment of a file,
+other processes can set shared locks on that segment
+or a portion of it.
+A shared lock prevents any other process from setting an exclusive
+lock on any portion of the protected area.
+A request for a shared lock fails if the file descriptor was not
+opened with read access.
+.Pp
+An exclusive lock prevents any other process from setting a shared lock or
+an exclusive lock on any portion of the protected area.
+A request for an exclusive lock fails if the file was not
+opened with write access.
+.Pp
+The value of
+.Fa l_whence
+is
+.Dv SEEK_SET ,
+.Dv SEEK_CUR ,
+or
+.Dv SEEK_END
+to indicate that the relative offset,
+.Fa l_start
+bytes, will be measured from the start of the file,
+current position, or end of the file, respectively.
+The value of
+.Fa l_len
+is the number of consecutive bytes to be locked.
+If
+.Fa l_len
+is negative, the result is undefined.
+The
+.Fa l_pid
+field is only used with
+.Dv F_GETLK
+to return the process ID of the process holding a blocking lock.
+After a successful
+.Dv F_GETLK
+request, the value of
+.Fa l_whence
+is
+.Dv SEEK_SET .
+.Pp
+Locks may start and extend beyond the current end of a file,
+but may not start or extend before the beginning of the file.
+A lock is set to extend to the largest possible value of the
+file offset for that file if
+.Fa l_len
+is set to zero.
+If
+.Fa l_whence
+and
+.Fa l_start
+point to the beginning of the file, and
+.Fa l_len
+is zero, the entire file is locked.
+If an application wishes only to do entire file locking, the
+.Xr flock 2
+system call is much more efficient.
+.Pp
+There is at most one type of lock set for each byte in the file.
+Before a successful return from an
+.Dv F_SETLK
+or an
+.Dv F_SETLKW
+request when the calling process has previously existing locks
+on bytes in the region specified by the request,
+the previous lock type for each byte in the specified
+region is replaced by the new lock type.
+As specified above under the descriptions
+of shared locks and exclusive locks, an
+.Dv F_SETLK
+or an
+.Dv F_SETLKW
+request fails or blocks respectively when another process has existing
+locks on bytes in the specified region and the type of any of those
+locks conflicts with the type specified in the request.
+.Sh COMPATIBILITY
+This interface follows the completely stupid semantics of
+.At V
+and
+.St -p1003.1-88
+that require that all locks associated with a file for a given process are
+removed when \fIany\fP file descriptor for that file is closed by that process.
+This semantic means that applications must be aware of any files that
+a subroutine library may access.
+For example if an application for updating the password file locks the
+password file database while making the update, and then calls
+.Xr getpwnam 3
+to retrieve a record,
+the lock will be lost because
+.Xr getpwnam 3
+opens, reads, and closes the password database.
+The database close will release all locks that the process has
+associated with the database, even if the library routine never
+requested a lock on the database.
+.Pp
+Another minor semantic problem with this interface is that
+locks are not inherited by a child process created using the
+.Xr fork 2
+function.
+The
+.Xr flock 2
+interface has much more rational last close semantics and
+allows locks to be inherited by child processes.
+Calling
+.Xr flock 2
+is recommended for applications that want to ensure the integrity
+of their locks when using library routines or wish to pass locks
+to their children.
+Note that
+.Xr flock 2
+and
+.Nm
+locks may be safely used concurrently.
+.Pp
+All locks associated with a file for a given process are
+removed when the process terminates.
+.Pp
+A potential for deadlock occurs if a process controlling a locked region
+is put to sleep by attempting to lock the locked region of another process.
+This implementation detects that sleeping until a locked region is unlocked
+would cause a deadlock and fails with an
+.Er EDEADLK
+error.
+.Sh RETURN VALUES
+Upon successful completion, the value returned depends on
+.Fa cmd
+as follows:
+.Bl -tag -width F_GETOWNX -offset indent
+.It Dv F_DUPFD
+A new file descriptor.
+.It Dv F_GETFD
+Value of flag (only the low-order bit is defined).
+.It Dv F_GETFL
+Value of flags.
+.It Dv F_GETOWN
+Value of file descriptor owner.
+.It Dv F_MAXFD
+Value of the highest file descriptor open by the process.
+.It other
+Value other than \-1.
+.El
+.Pp
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn fcntl
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EAGAIN
+The argument
+.Fa arg
+is
+.Dv F_SETLK ,
+the type of lock
+.Pq Fa l_type
+is a shared lock
+.Pq Dv F_RDLCK
+or exclusive lock
+.Pq Dv F_WRLCK ,
+and the segment of a file to be locked is already
+exclusive-locked by another process;
+or the type is an exclusive lock and some portion of the
+segment of a file to be locked is already shared-locked or
+exclusive-locked by another process.
+.It Bq Er EBADF
+.Fa fildes
+is not a valid open file descriptor.
+.Pp
+The argument
+.Fa cmd
+is
+.Dv F_SETLK
+or
+.Dv F_SETLKW ,
+the type of lock
+.Pq Fa l_type
+is a shared lock
+.Pq Dv F_RDLCK ,
+and
+.Fa fildes
+is not a valid file descriptor open for reading.
+.Pp
+The argument
+.Fa cmd
+is
+.Dv F_SETLK
+or
+.Dv F_SETLKW ,
+the type of lock
+.Pq Fa l_type
+is an exclusive lock
+.Pq Dv F_WRLCK ,
+and
+.Fa fildes
+is not a valid file descriptor open for writing.
+.It Bq Er EDEADLK
+The argument
+.Fa cmd
+is
+.Dv F_SETLKW ,
+and a deadlock condition was detected.
+.It Bq Er EINTR
+The argument
+.Fa cmd
+is
+.Dv F_SETLKW ,
+and the function was interrupted by a signal.
+.It Bq Er EINVAL
+The argument
+.Fa cmd
+is invalid.
+.Pp
+The argument
+.Fa cmd
+is
+.Dv F_DUPFD
+and
+.Fa arg
+is negative or greater than the maximum allowable number
+(see
+.Xr getdtablesize 3 ) .
+.Pp
+The argument
+.Fa cmd
+is
+.Dv F_GETLK ,
+.Dv F_SETLK ,
+or
+.Dv F_SETLKW
+and the data to which
+.Fa arg
+points is not valid, or
+.Fa fildes
+refers to a file that does not support locking.
+.It Bq Er EMFILE
+The argument
+.Fa cmd
+is
+.Dv F_DUPFD
+and the maximum number of file descriptors permitted for the
+process are already in use,
+or no file descriptors greater than or equal to
+.Fa arg
+are available.
+.It Bq Er ENFILE
+.Fa cmd
+is
+.Dv F_DUPFD
+and system-wide the maximum allowed number of file descriptors are
+currently open.
+.It Bq Er ENOLCK
+The argument
+.Fa cmd
+is
+.Dv F_SETLK
+or
+.Dv F_SETLKW ,
+and satisfying the lock or unlock request would result in the
+number of locked regions in the system exceeding a system-imposed limit.
+.It Bq Er ESRCH
+.Fa cmd
+is
+.Dv F_SETOWN
+and
+the process ID given as argument is not in use.
+.El
+.Sh SEE ALSO
+.Xr close 2 ,
+.Xr execve 2 ,
+.Xr flock 2 ,
+.Xr open 2 ,
+.Xr sigaction 2 ,
+.Xr getdtablesize 3
+.Sh STANDARDS
+The
+.Fn fcntl
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+The
+.Fn fcntl
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/fdatasync.2 b/lib/nbsd_libc/sys/fdatasync.2
new file mode 100644 (file)
index 0000000..3f12119
--- /dev/null
@@ -0,0 +1,96 @@
+.\"    $NetBSD: fdatasync.2,v 1.16 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 1998 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd October 25, 2003
+.Dt FDATASYNC 2
+.Os
+.Sh NAME
+.Nm fdatasync
+.Nd synchronize the data of a file
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn fdatasync "int fd"
+.Sh DESCRIPTION
+The
+.Fn fdatasync
+function forces all modified data associated with the file descriptor
+.Fa fd
+to be flushed to stable storage.
+.Pp
+The functionality is as described for
+.Xr fsync 2 ,
+with the exception that file status information need not be synchronized,
+which may result in a performance gain, compared to
+.Xr fsync 2 .
+This behaviour is commonly known as
+.Bf -symbolic
+synchronized I/O data integrity completion.
+.Ef
+.Sh RETURN VALUES
+A value of 0 is returned on success.
+Otherwise, a value \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn fdatasync
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa fd
+argument is not a valid file descriptor open for writing.
+.It Bq Er EINVAL
+This implementation does not support synchronized I/O for this file.
+.It Bq Er ENOSYS
+The
+.Fn fdatasync
+function is not supported by this implementation.
+.El
+.Pp
+In the event that any of the I/O operations to be performed fail,
+.Fn fdatasync
+returns the error conditions defined for
+.Xr read 2
+and
+.Xr write 2 ,
+and outstanding I/O operations are not guaranteed to have been completed.
+.Sh SEE ALSO
+.Xr fsync 2 ,
+.Xr open 2 ,
+.Xr read 2 ,
+.Xr write 2
+.Sh STANDARDS
+The
+.Fn fdatasync
+function conforms to
+.St -p1003.1b-93 .
diff --git a/lib/nbsd_libc/sys/fhopen.2 b/lib/nbsd_libc/sys/fhopen.2
new file mode 100644 (file)
index 0000000..1a71377
--- /dev/null
@@ -0,0 +1,152 @@
+.\"    $NetBSD: fhopen.2,v 1.17 2009/08/05 23:15:52 wiz Exp $
+.\"
+.\" Copyright (c) 1999 National Aeronautics & Space Administration
+.\" All rights reserved.
+.\"
+.\" This software was written by William Studenmund of the
+.\" Numerical Aerospace Simulation Facility, NASA Ames Research Center.
+.\"
+.\" 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. Neither the name of the National Aeronautics & Space Administration
+.\"    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 NATIONAL AERONAUTICS & SPACE ADMINISTRATION
+.\" ``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 ADMINISTRATION OR CONTRIB-
+.\" UTORS 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.
+.\"/
+.Dd August 5, 2009
+.Dt FHOPEN 2
+.Os
+.Sh NAME
+.Nm fhopen ,
+.Nm fhstat ,
+.Nm fhstatvfs
+.Nd access file via file handle
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/mount.h
+.Ft int
+.Fn fhopen "const void *fhp" "size_t fh_size" "int flags"
+.In sys/stat.h
+.Ft int
+.Fn fhstat "const void *fhp" "size_t fh_size" "struct stat *sb"
+.In sys/statvfs.h
+.Ft int
+.Fn fhstatvfs "const void *fhp" "size_t fh_size" "struct statvfs *buf"
+.Ft int
+.Fn fhstatvfs1 "const void *fhp" "size_t fh_size" "struct statvfs *buf" "int flags"
+.Sh DESCRIPTION
+These functions provide a means to access a file given the opaque file handle
+.Fa fhp
+and the size
+.Fa fh_size
+of the opaque object as returned by
+.Xr getfh 2 .
+As this method bypasses directory access restrictions, these calls are
+restricted to the superuser.
+.Pp
+.Fn fhopen
+opens the file referenced by
+.Fa fhp
+for reading and/or writing as specified by the argument
+.Fa flags
+and returns the file descriptor to the calling process.
+The
+.Fa flags
+are specified by
+.Em or Ns 'ing
+together the flags used for the
+.Xr open 2
+call.
+All said flags are valid except for
+.Dv O_CREAT .
+.Pp
+.Fn fhstat ,
+.Fn fhstatvfs ,
+and
+.Fn fhstatvfs1
+provide the functionality of the
+.Xr fstat 2 ,
+.Xr fstatvfs 2 ,
+and
+.Xr fstatvfs1 2
+calls except that they return information for the file referred to by
+.Fa fhp
+rather than an open file.
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn fhopen
+returns the file descriptor for the opened file, while
+.Fn fhstat ,
+.Fn fhstatvfs ,
+and
+.Fn fhstatvfs1
+return 0.
+Otherwise, \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+In addition to the errors returned by
+.Xr open 2 ,
+.Xr fstat 2 ,
+.Xr fstatvfs 2 ,
+and
+.Xr fstatvfs1 2 ,
+respectively,
+.Fn fhopen ,
+.Fn fhstat ,
+.Fn fhstatvfs ,
+and
+.Fn fhstatvfs1
+will return
+.Bl -tag -width Er
+.It Bq Er EINVAL
+Calling
+.Fn fhopen
+with
+.Dv O_CREAT
+set or invalid
+.Fa fh_size .
+.It Bq Er ESTALE
+The file handle
+.Fa fhp
+is no longer valid.
+.El
+.Sh SEE ALSO
+.Xr fstat 2 ,
+.Xr fstatvfs 2 ,
+.Xr fstatvfs1 2 ,
+.Xr getfh 2 ,
+.Xr open 2
+.Sh HISTORY
+The
+.Fn fhopen ,
+and
+.Fn fhstat
+functions first appeared in
+.Nx 1.5 .
+The
+.Fn fhstatvfs
+function replaced
+.Fn fhstatfs
+in
+.Nx 3.0 .
diff --git a/lib/nbsd_libc/sys/flock.2 b/lib/nbsd_libc/sys/flock.2
new file mode 100644 (file)
index 0000000..9463422
--- /dev/null
@@ -0,0 +1,155 @@
+.\"    $NetBSD: flock.2,v 1.21 2009/10/29 01:52:01 wiz Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)flock.2    8.2 (Berkeley) 12/11/93
+.\"
+.Dd October 26, 2009
+.Dt FLOCK 2
+.Os
+.Sh NAME
+.Nm flock
+.Nd "apply or remove an advisory lock on an open file"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In fcntl.h
+.Fd #define    LOCK_SH 1       /* shared lock */
+.Fd #define    LOCK_EX 2       /* exclusive lock */
+.Fd #define    LOCK_NB 4       /* don't block when locking */
+.Fd #define    LOCK_UN 8       /* unlock */
+.Ft int
+.Fn flock "int fd" "int operation"
+.Sh DESCRIPTION
+.Fn flock
+applies or removes an
+.Em advisory
+lock on the file associated with the file descriptor
+.Fa fd .
+A lock is applied by specifying an
+.Fa operation
+parameter that is one of
+.Dv LOCK_SH
+or
+.Dv LOCK_EX
+with the optional addition of
+.Dv LOCK_NB .
+To unlock
+an existing lock
+.Dv operation
+should be
+.Dv LOCK_UN .
+.Pp
+Advisory locks allow cooperating processes to perform
+consistent operations on files, but do not guarantee
+consistency (i.e., processes may still access files
+without using advisory locks possibly resulting in
+inconsistencies).
+.Pp
+The locking mechanism allows two types of locks:
+.Em shared
+locks and
+.Em exclusive
+locks.
+At any time multiple shared locks may be applied to a file,
+but at no time are multiple exclusive, or both shared and exclusive,
+locks allowed simultaneously on a file.
+.Pp
+A shared lock may be
+.Em upgraded
+to an exclusive lock, and vice versa, simply by specifying
+the appropriate lock type; this results in the previous
+lock being released and the new lock applied (possibly
+after other processes have gained and released the lock).
+.Pp
+Requesting a lock on an object that is already locked
+normally causes the caller to be blocked until the lock may be
+acquired.
+If
+.Dv LOCK_NB
+is included in
+.Fa operation ,
+then this will not happen; instead the call will fail and
+the error
+.Er EAGAIN
+will be returned.
+.Sh NOTES
+Locks are on files, not file descriptors.
+That is, file descriptors duplicated through
+.Xr dup 2
+or
+.Xr fork 2
+do not result in multiple instances of a lock, but rather multiple
+references to a single lock.
+If a process holding a lock on a file
+forks and the child explicitly unlocks the file, the parent will
+lose its lock.
+.Pp
+Processes blocked awaiting a lock may be awakened by signals.
+.Sh RETURN VALUES
+Zero is returned if the operation was successful;
+on an error a \-1 is returned and an error code is left in
+the global location
+.Va errno .
+.Sh ERRORS
+The
+.Fn flock
+call fails if:
+.Bl -tag -width Er
+.It Bq Er EAGAIN
+The file is locked and the
+.Dv LOCK_NB
+option was specified.
+.It Bq Er EBADF
+The argument
+.Fa fd
+is an invalid descriptor.
+.It Bq Er EINVAL
+The argument
+.Fa operation
+does not include exactly one of
+.Dv LOCK_EX ,
+.Dv LOCK_SH ,
+or
+.Dv LOCK_UN .
+.It Bq Er EOPNOTSUPP
+The argument
+.Fa fd
+refers to an object other than a file.
+.El
+.Sh SEE ALSO
+.Xr close 2 ,
+.Xr dup 2 ,
+.Xr execve 2 ,
+.Xr fork 2 ,
+.Xr open 2
+.Sh HISTORY
+The
+.Fn flock
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/fork.2 b/lib/nbsd_libc/sys/fork.2
new file mode 100644 (file)
index 0000000..64eb1ad
--- /dev/null
@@ -0,0 +1,138 @@
+.\"    $NetBSD: fork.2,v 1.22 2004/06/25 15:29:25 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)fork.2      8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 10, 2004
+.Dt FORK 2
+.Os
+.Sh NAME
+.Nm fork
+.Nd create a new process
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft pid_t
+.Fn fork void
+.Sh DESCRIPTION
+.Fn fork
+causes creation of a new process.
+The new process (child process) is an exact copy of the
+calling process (parent process) except for the following:
+.Bl -bullet -offset indent
+.It
+The child process has a unique process ID.
+.It
+The child process has a different parent
+process ID (i.e., the process ID of the parent process).
+.It
+The child process has its own copy of the parent's descriptors.
+These descriptors reference the same underlying objects, so that,
+for instance, file pointers in file objects are shared between
+the child and the parent, so that an
+.Xr lseek 2
+on a descriptor in the child process can affect a subsequent
+.Xr read 2
+or
+.Xr write 2
+by the parent.
+This descriptor copying is also used by the shell to
+establish standard input and output for newly created processes
+as well as to set up pipes.
+.It
+The child process' resource utilizations
+are set to 0; see
+.Xr setrlimit 2 .
+.El
+.Pp
+In general, the child process should call
+.Xr _exit 2
+rather than
+.Xr exit 3 .
+Otherwise, any stdio buffers that exist both in the parent and child
+will be flushed twice.
+Similarly,
+.Xr _exit 2
+should be used to prevent
+.Xr atexit 3
+routines from being called twice (once in the parent and once in the child).
+.Pp
+In case of a threaded program, only the thread calling
+.Fn fork
+is still running in the child processes.
+.Pp
+Child processes of a threaded program have additional restrictions,
+a child must only call functions that are async-signal-safe.
+Very few functions are asynchronously safe and applications should
+make sure they call
+.Xr exec 3
+as soon as possible.
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn fork
+returns a value
+of 0 to the child process and returns the process ID of the child
+process to the parent process.
+Otherwise, a value of \-1 is returned to the parent process, no
+child process is created, and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn fork
+will fail and no child process will be created if:
+.Bl -tag -width [EAGAIN]
+.It Bq Er EAGAIN
+The system-imposed limit on the total
+number of processes under execution would be exceeded.
+This limit is configuration-dependent.
+.It Bq Er EAGAIN
+The limit
+.Dv RLIMIT_NPROC
+on the total number of
+processes under execution by this user id would be exceeded.
+.It Bq Er ENOMEM
+There is insufficient swap space for the new process.
+.El
+.Sh SEE ALSO
+.Xr execve 2 ,
+.Xr setrlimit 2 ,
+.Xr vfork 2 ,
+.Xr wait 2 ,
+.Xr pthread_atfork 3
+.Sh STANDARDS
+The
+.Fn fork
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+A
+.Fn fork
+system call appeared in
+.At v6 .
diff --git a/lib/nbsd_libc/sys/fsync.2 b/lib/nbsd_libc/sys/fsync.2
new file mode 100644 (file)
index 0000000..e2fe405
--- /dev/null
@@ -0,0 +1,155 @@
+.\"    $NetBSD: fsync.2,v 1.17 2010/05/17 12:38:04 jruoho Exp $
+.\"
+.\" 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.
+.\" 3. 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.
+.\"
+.\"     @(#)fsync.2    8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 17, 2010
+.Dt FSYNC 2
+.Os
+.Sh NAME
+.Nm fsync ,
+.Nm fsync_range
+.Nd "synchronize a file's in-core state with that on disk"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn fsync "int fd"
+.Ft int
+.Fn fsync_range "int fd" "int how" "off_t start" "off_t length"
+.Sh DESCRIPTION
+.Fn fsync
+causes all modified data and attributes of
+.Fa fd
+to be moved to a permanent storage device.
+This normally results in all in-core modified copies
+of buffers for the associated file to be written to a disk.
+.Pp
+.Fn fsync
+should be used by programs that require a file to be
+in a known state, for example, in building a simple transaction
+facility.
+.Pp
+.Fn fsync_range
+causes all modified data starting at
+.Fa start
+for length
+.Fa length
+of
+.Fa fd
+to be written to permanent storage.
+Note that
+.Fn fsync_range
+requires that the file
+.Fa fd
+must be open for writing.
+.Pp
+.Fn fsync_range
+may flush the file data in one of two manners:
+.Bl -tag -width FDATASYNC -offset indent
+.It Dv FDATASYNC
+Synchronize the file data and sufficient meta-data to retrieve the
+data for the specified range.
+.It Dv FFILESYNC
+Synchronize all modified file data and meta-data for the specified range.
+.El
+.Pp
+By default,
+.Fn fsync_range
+does not flush disk caches, assuming that storage media are able to ensure
+completed writes are transfered to media.
+The
+.Dv FDISKSYNC
+flag may be included in the
+.Fa how
+parameter to trigger flushing of all disk caches for the file.
+.Pp
+If the
+.Fa length
+parameter is zero,
+.Fn fsync_range
+will synchronize all of the file data.
+.Sh RETURN VALUES
+A 0 value is returned on success.
+A \-1 value indicates an error.
+.Sh ERRORS
+.Fn fsync
+or
+.Fn fsync_range
+fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa fd
+is not a valid descriptor.
+.It Bq Er EINVAL
+.Fa fd
+refers to a socket, not to a file.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.El
+.Pp
+Additionally,
+.Fn fsync_range
+fails if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa fd
+is not open for writing.
+.It Bq Er EINVAL
+.Fa start
++
+.Fa length
+is less than
+.Fa start .
+.El
+.Sh NOTES
+For optimal efficiency, the
+.Fn fsync_range
+call requires that the file system containing the file referenced by
+.Fa fd
+support partial synchronization of file data.
+For file systems which do
+not support partial synchronization, the entire file will be synchronized
+and the call will be the equivalent of calling
+.Fn fsync .
+.Sh SEE ALSO
+.Xr sync 2 ,
+.Xr sync 8
+.Sh HISTORY
+The
+.Fn fsync
+function call appeared in
+.Bx 4.2 .
+.Pp
+The
+.Fn fsync_range
+function call first appeared in
+.Nx 2.0
+and is modeled after the function available in AIX.
diff --git a/lib/nbsd_libc/sys/ftruncate.c b/lib/nbsd_libc/sys/ftruncate.c
new file mode 100644 (file)
index 0000000..8436be5
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: ftruncate.c,v 1.13 2007/11/23 12:39:15 uebayasi Exp $  */
+
+/*
+ * Copyright (c) 1992, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)ftruncate.c        8.1 (Berkeley) 6/17/93";
+#else
+__RCSID("$NetBSD: ftruncate.c,v 1.13 2007/11/23 12:39:15 uebayasi Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(ftruncate,_ftruncate)
+#endif
+
+int __ftruncate(int, int, off_t);
+
+/*
+ * This function provides 64-bit offset padding that
+ * is not supplied by GCC 1.X but is supplied by GCC 2.X.
+ */
+int
+ftruncate(fd, length)
+       int     fd;
+       off_t   length;
+{
+
+       return __ftruncate(fd, 0, length);
+}
diff --git a/lib/nbsd_libc/sys/getcontext.2 b/lib/nbsd_libc/sys/getcontext.2
new file mode 100644 (file)
index 0000000..ac3f638
--- /dev/null
@@ -0,0 +1,152 @@
+.\"    $NetBSD: getcontext.2,v 1.7 2010/04/29 06:07:35 jruoho Exp $
+.\"
+.\" Copyright (c) 1999 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 28, 2010
+.Dt GETCONTEXT 2
+.Os
+.Sh NAME
+.Nm getcontext ,
+.Nm setcontext
+.Nd get and set current user context
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ucontext.h
+.Ft int
+.Fn getcontext "ucontext_t *ucp"
+.Ft int
+.Fn setcontext "const ucontext_t *ucp"
+.Sh DESCRIPTION
+The
+.Fn getcontext
+function initializes the object pointed to by
+.Fa ucp
+to the current user context of the calling thread.
+The user context defines a thread's execution environment and includes
+the contents of its machine registers,
+its signal mask,
+and its current execution stack.
+.Pp
+The
+.Fn setcontext
+function restores the user context defined in the object pointed to by
+.Fa ucp
+as most recently initialized by a previous call to either
+.Fn getcontext
+or
+.Xr makecontext 3 .
+.\" TODO: signal handler
+If successful, execution of the program resumes as defined in the
+.Fa ucp
+argument, and
+.Fn setcontext
+will not return.
+If
+.Fa ucp
+was initialized by the
+.Fn getcontext
+function, program execution continues as if the corresponding invocation of
+.Fn getcontext
+had just returned (successfully).
+If
+.Fa ucp
+was initialized by the
+.Xr makecontext 3
+function, program execution continues with the function (and function
+arguments) passed to
+.Xr makecontext 3 .
+.Sh RETURN VALUES
+On successful completion,
+.Fn getcontext
+returns 0 and
+.Fn setcontext
+does not return.
+Otherwise a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn getcontext
+and
+.Fn setcontext
+functions will fail if:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+The
+.Fa ucp
+argument points to an invalid address.
+.El
+.Pp
+The
+.Fn setcontext
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The contents of the datum pointed to by
+.Fa ucp
+are invalid.
+.El
+.Sh SEE ALSO
+.Xr sigprocmask 2 ,
+.Xr longjmp 3 ,
+.Xr makecontext 3 ,
+.Xr setjmp 3 ,
+.Xr swapcontext 3
+.Sh STANDARDS
+The
+.Fn getcontext
+and
+.Fn setcontext
+functions conform to
+.St -xsh5
+and
+.St -p1003.1-2001 .
+The
+.Va errno
+indications are an extension to the standard.
+.Pp
+The
+.St -p1003.1-2004
+revision marked the functions
+.Fn getcontext
+and
+.Fn setcontext
+as obsolete, citing portability issues and recommending the use of
+.Tn POSIX
+threads instead.
+The
+.St -p1003.1-2008
+revision removed the functions from the specification.
+.Sh HISTORY
+The
+.Fn getcontext
+and
+.Fn setcontext
+functions first appeared in
+.At V.4 .
diff --git a/lib/nbsd_libc/sys/getdents.2 b/lib/nbsd_libc/sys/getdents.2
new file mode 100644 (file)
index 0000000..1d58079
--- /dev/null
@@ -0,0 +1,133 @@
+.\"    $NetBSD: getdents.2,v 1.22 2010/06/04 05:42:24 jruoho Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)getdirentries.2     8.1 (Berkeley) 6/9/93
+.\"
+.Dd June 4, 2010
+.Dt GETDENTS 2
+.Os
+.Sh NAME
+.Nm getdents
+.Nd "get directory entries in a filesystem independent format"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In dirent.h
+.Ft int
+.Fn getdents "int fd" "char *buf" "size_t nbytes"
+.Sh DESCRIPTION
+.Fn getdents
+reads directory entries from the directory
+referenced by the file descriptor
+.Fa fd
+into the buffer pointed to by
+.Fa buf ,
+in a filesystem independent format.
+Up to
+.Fa nbytes
+of data will be transferred.
+.Fa nbytes
+must be greater than or equal to the
+block size associated with the file,
+see
+.Xr stat 2 .
+Some filesystems may not support
+.Fn getdents
+with buffers smaller than this size.
+.Pp
+The data in the buffer is a series of
+.Em dirent
+structures:
+.Bd -literal -offset indent
+struct dirent {
+       ino_t    d_fileno;              /* file number of entry */
+       uint16_t d_reclen;              /* length of this record */
+       uint16_t d_namlen;              /* length of d_name */
+       uint8_t  d_type;                /* file type, see below */
+       char     d_name[MAXNAMELEN + 1];
+};
+.Ed
+.Pp
+The structure is described in
+.Xr dirent 3 .
+.Pp
+Entries may be separated by extra space.
+The
+.Fa d_reclen
+entry may be used as an offset from the start of a
+.Fa dirent
+structure to the next structure, if any.
+.Pp
+The actual number of bytes transferred is returned.
+The current position pointer associated with
+.Fa fd
+is set to point to the next block of entries.
+The pointer may not advance by the number of bytes returned by
+.Fn getdents .
+A value of zero is returned when
+the end of the directory has been reached.
+.Pp
+The current position pointer may be set and retrieved by
+.Xr lseek 2 .
+The current position pointer should only be set to a value returned by
+.Xr lseek 2 ,
+or zero.
+.Sh RETURN VALUES
+If successful, the number of bytes actually transferred is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn getdents
+will fail if:
+.Bl -tag -width "[EINVAL]"
+.It Bq Er EBADF
+.Fa fd
+is not a valid file descriptor open for reading.
+.It Bq Er EFAULT
+Either
+.Fa buf
+points outside the allocated address space.
+.It Bq Er EINVAL
+A directory was being read on NFS, but it was modified on the server while
+it was being read.
+.It Bq Er EIO
+An
+.Tn I/O
+error occurred while reading from or writing to the file system.
+.El
+.Sh SEE ALSO
+.Xr lseek 2 ,
+.Xr open 2 ,
+.Xr dirent 3
+.Sh HISTORY
+The
+.Fn getdents
+function first appeared in
+.Nx 1.3 .
diff --git a/lib/nbsd_libc/sys/getfh.2 b/lib/nbsd_libc/sys/getfh.2
new file mode 100644 (file)
index 0000000..4076739
--- /dev/null
@@ -0,0 +1,122 @@
+.\"    $NetBSD: getfh.2,v 1.21 2006/10/30 18:53:42 mjf Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)getfh.2     8.1 (Berkeley) 6/9/93
+.\"
+.Dd October 30, 2006
+.Dt GETFH 2
+.Os
+.Sh NAME
+.Nm getfh
+.Nd get file handle
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/mount.h
+.Ft int
+.Fn getfh "const char *path" "void *fhp" "size_t *fh_size"
+.Sh DESCRIPTION
+.Fn getfh
+returns a file handle for the specified file or directory
+in the file handle pointed to by
+.Fa fhp .
+The variable pointed to by
+.Fa fh_size
+has to be initialized to the memory allocated for the variable sized file
+handle.
+On return the value will be replaced by the actual size
+needed (which will vary depending on the file system the path is on).
+This system call is restricted to the superuser.
+To query the necessary size for the filehandle, a
+.Dv NULL
+pointer may
+be passed as
+.Fa fhp ,
+and the value pointed to by
+.Fa fh_size
+should be initialized to zero.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn getfh
+fails if one or more of the following are true:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix of
+.Fa path
+is not a directory.
+.It Bq Er ENAMETOOLONG
+The length of a component of
+.Fa path
+exceeds
+.Brq Dv NAME_MAX
+characters, or the length of
+.Fa path
+exceeds
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The file referred to by
+.Fa path
+does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix of
+.Fa path .
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating
+.Fa path .
+.It Bq Er EFAULT
+.Fa fhp
+points to an invalid address.
+.It Bq Er EIO
+An
+.Tn I/O
+error occurred while reading from or writing to the file system.
+.It Bq Er E2BIG
+The memory allocated for the file handle is too small.
+The size needed has been written to the variable pointed to by
+.Fa fh_size .
+.It Bq Er ENOMEM
+The kernel failed to allocate temporary memory to create a filehandle of the
+requested size.
+.El
+.Sh SEE ALSO
+.Xr fhstat 2 ,
+.Xr fhstatvfs 2 ,
+.Xr fhstatvfs1 2
+.Sh HISTORY
+The
+.Fn getfh
+function
+first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/sys/getgid.2 b/lib/nbsd_libc/sys/getgid.2
new file mode 100644 (file)
index 0000000..fe0b926
--- /dev/null
@@ -0,0 +1,85 @@
+.\"    $NetBSD: getgid.2,v 1.19 2010/04/03 15:13:43 jruoho Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getgid.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 3, 2010
+.Dt GETGID 2
+.Os
+.Sh NAME
+.Nm getgid ,
+.Nm getegid
+.Nd get group process identification
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft gid_t
+.Fn getgid void
+.Ft gid_t
+.Fn getegid void
+.Sh DESCRIPTION
+The
+.Fn getgid
+function returns the real group ID of the calling process,
+.Fn getegid
+returns the effective group ID of the calling process.
+.Pp
+The real group ID is specified at login time.
+.Pp
+The real group ID is the group of the user who invoked the program.
+As the effective group ID gives the process additional permissions
+during the execution of
+.Dq Em set-group-ID
+mode processes,
+.Fn getgid
+is used to determine the real-group-id of the calling process.
+.Sh ERRORS
+The
+.Fn getgid
+and
+.Fn getegid
+functions are always successful, and no return value is reserved to
+indicate an error.
+.Sh SEE ALSO
+.Xr getuid 2 ,
+.Xr setgid 2 ,
+.Xr setgroups 2 ,
+.Xr setregid 2
+.Sh STANDARDS
+.Fn getgid
+and
+.Fn getegid
+conform to
+.St -p1003.1-90 .
+.Sh HISTORY
+The
+.Fn getgid
+function appeared in
+.At v4 .
diff --git a/lib/nbsd_libc/sys/getgroups.2 b/lib/nbsd_libc/sys/getgroups.2
new file mode 100644 (file)
index 0000000..ffe8482
--- /dev/null
@@ -0,0 +1,103 @@
+.\"    $NetBSD: getgroups.2,v 1.22 2006/10/13 20:51:28 wiz Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getgroups.2        8.2 (Berkeley) 4/16/94
+.\"
+.Dd October 7, 2006
+.Dt GETGROUPS 2
+.Os
+.Sh NAME
+.Nm getgroups
+.Nd get group access list
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn getgroups "int gidsetlen" "gid_t *gidset"
+.Sh DESCRIPTION
+.Fn getgroups
+gets the current group access list of the current user process
+and stores it in the array
+.Fa gidset .
+The parameter
+.Fa gidsetlen
+indicates the number of entries that may be placed in
+.Fa gidset .
+.Fn getgroups
+returns the actual number of groups returned in
+.Fa gidset .
+No more than
+.Dv {NGROUPS_MAX}
+will ever
+be returned.
+If
+.Fa gidsetlen
+is 0,
+.Fn getgroups
+returns the number of groups without modifying the
+.Fa gidset
+array.
+.Pp
+This system call only returns the secondary groups.
+.Sh RETURN VALUES
+A successful call returns the number of groups in the group set.
+A value of \-1 indicates that an error occurred, and the error
+code is stored in the global variable
+.Va errno .
+.Sh ERRORS
+The possible errors for
+.Fn getgroups
+are:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The argument
+.Fa gidsetlen
+is non-zero and is smaller than the number of groups in the group set.
+.It Bq Er EFAULT
+The argument
+.Fa gidset
+specifies
+an invalid address.
+.El
+.Sh SEE ALSO
+.Xr getegid 2 ,
+.Xr getgid 2 ,
+.Xr setgroups 2 ,
+.Xr initgroups 3
+.Sh STANDARDS
+The
+.Fn getgroups
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+The
+.Fn getgroups
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/getitimer.2 b/lib/nbsd_libc/sys/getitimer.2
new file mode 100644 (file)
index 0000000..e0cf51f
--- /dev/null
@@ -0,0 +1,192 @@
+.\"    $NetBSD: getitimer.2,v 1.24 2010/04/30 04:17:45 jruoho Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getitimer.2        8.3 (Berkeley) 5/16/95
+.\"
+.Dd April 30, 2010
+.Dt GETITIMER 2
+.Os
+.Sh NAME
+.Nm getitimer ,
+.Nm setitimer
+.Nd get/set value of interval timer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/time.h
+.Fd #define ITIMER_REAL                0
+.Fd #define ITIMER_VIRTUAL     1
+.Fd #define ITIMER_PROF                2
+.Ft int
+.Fn getitimer "int which" "struct itimerval *value"
+.Ft int
+.Fn setitimer "int which" "const struct itimerval * restrict value" "struct itimerval * restrict ovalue"
+.Sh DESCRIPTION
+The system provides each process with three interval timers,
+defined in
+.Ao Pa sys/time.h Ac .
+The
+.Fn getitimer
+call returns the current value for the timer specified in
+.Fa which
+in the structure at
+.Fa value .
+The
+.Fn setitimer
+call sets a timer to the specified
+.Fa value
+(returning the previous value of the timer if
+.Fa ovalue
+is non-nil).
+.Pp
+A timer value is defined by the
+.Fa itimerval
+structure:
+.Bd -literal -offset indent
+struct itimerval {
+       struct  timeval it_interval;    /* timer interval */
+       struct  timeval it_value;       /* current value */
+};
+.Ed
+.Pp
+If
+.Fa it_value
+is non-zero, it indicates the time to the next timer expiration.
+If
+.Fa it_interval
+is non-zero, it specifies a value to be used in reloading
+.Fa it_value
+when the timer expires.
+Setting
+.Fa it_value
+to 0 disables a timer.
+Setting
+.Fa it_interval
+to 0 causes a timer to be disabled after its next expiration (assuming
+.Fa it_value
+is non-zero).
+.Pp
+Time values smaller than the resolution of the
+system clock are rounded up to this resolution
+(typically 10 milliseconds).
+.Pp
+The
+.Dv ITIMER_REAL
+timer decrements in real time.
+A
+.Dv SIGALRM
+signal is
+delivered when this timer expires.
+.Pp
+The
+.Dv ITIMER_VIRTUAL
+timer decrements in process virtual time.
+It runs only when the process is executing.
+A
+.Dv SIGVTALRM
+signal
+is delivered when it expires.
+.Pp
+The
+.Dv ITIMER_PROF
+timer decrements both in process virtual time and
+when the system is running on behalf of the process.
+It is designed to be used by interpreters in statistically profiling
+the execution of interpreted programs.
+Each time the
+.Dv ITIMER_PROF
+timer expires, the
+.Dv SIGPROF
+signal is
+delivered.
+Because this signal may interrupt in-progress
+system calls, programs using this timer must be prepared to
+restart interrupted system calls.
+.Sh NOTES
+Macros for manipulating time values are defined in the
+.In sys/time.h
+header;
+.Fn timerclear
+sets a time value to zero,
+.Fn timerisset
+tests if a time value is non-zero,
+.Fn timercmp
+compares two time values,
+.Fn timeradd
+adds a time value to another time value,
+.Fn timersub
+computes the time difference between two time values.
+For additional details, see
+.Xr timeradd 3 .
+.Sh RETURN VALUES
+If the calls succeed, a value of 0 is returned.
+If an error occurs, the value \-1 is returned, and a more precise error
+code is placed in the global variable
+.Va errno .
+.Sh ERRORS
+.Fn getitimer
+and
+.Fn setitimer
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+The
+.Fa value
+parameter specified a bad address.
+.It Bq Er EINVAL
+A
+.Fa value
+parameter specified a time that was too large
+to be handled.
+.El
+.Sh SEE ALSO
+.Xr gettimeofday 2 ,
+.Xr poll 2 ,
+.Xr select 2 ,
+.Xr sigaction 2
+.Sh STANDARDS
+The
+.Fn getitimer
+and
+.Fn setitimer
+functions conform to
+.St -p1003.1-2001 .
+The later
+.St -p1003.1-2008
+revision however marked both functions as obsolescent,
+recommending the use of
+.Xr timer_gettime 2
+and
+.Xr timer_settime 2
+instead.
+.Sh HISTORY
+The
+.Fn getitimer
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/getlogin.2 b/lib/nbsd_libc/sys/getlogin.2
new file mode 100644 (file)
index 0000000..316c294
--- /dev/null
@@ -0,0 +1,208 @@
+.\"    $NetBSD: getlogin.2,v 1.22 2009/01/11 02:46:30 christos Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)getlogin.2  8.1 (Berkeley) 6/9/93
+.\"
+.Dd January 6, 2009
+.Dt GETLOGIN 2
+.Os
+.Sh NAME
+.Nm getlogin ,
+.Nm getlogin_r ,
+.Nm setlogin
+.Nd get/set login name
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft char *
+.Fn getlogin void
+.Ft int
+.Fn getlogin_r "char *name" "size_t len"
+.Ft int
+.Fn setlogin "const char *name"
+.Sh DESCRIPTION
+The
+.Fn getlogin
+routine
+returns the login name of the user associated with the current session,
+as previously set by
+.Fn setlogin .
+The name is normally associated with a login shell
+at the time a session is created,
+and is inherited by all processes descended from the login shell.
+(This is true even if some of those processes assume another user ID,
+for example when
+.Xr su 1
+is used.)
+.Pp
+The
+.Fn getlogin_r
+function
+provides the same service as
+.Fn getlogin ,
+however the caller must provide the buffer
+.Fa name
+with length
+.Fa len
+bytes
+to hold the result.
+The buffer should be at least
+.Dv MAXLOGNAME
+bytes in length.
+.Pp
+.Fn setlogin
+sets the login name of the user associated with the current session to
+.Fa name .
+This call is restricted to the super-user, and
+is normally used only when a new session is being created on behalf
+of the named user
+(for example, at login time, or when a remote shell is invoked).
+.Pp
+.Em NOTE :
+There is only one login name per session.
+.Pp
+It is
+.Em CRITICALLY
+important to ensure that
+.Fn setlogin
+is only ever called after the process has taken adequate steps to ensure
+that it is detached from its parent's session.
+The
+.Em ONLY
+way to do this is via the
+.Fn setsid
+function.
+The
+.Fn daemon
+function calls
+.Fn setsid
+which is an ideal way of detaching from a controlling terminal and
+forking into the background.
+.Pp
+In particular, neither
+.Fn ioctl ttyfd TIOCNOTTY ...
+nor
+.Fn setpgid ...
+is sufficient to create a new session.
+.Pp
+Once a parent process has called
+.Fn setsid ,
+it is acceptable for some child of that process to then call
+.Fn setlogin ,
+even though it is not the session leader.
+Beware, however, that
+.Em ALL
+processes in the session will change their login name at the same time,
+even the parent.
+.Pp
+This is different from traditional
+.Ux
+privilege inheritance and as such can be counter-intuitive.
+.Pp
+Since the
+.Fn setlogin
+routine is restricted to the super-user, it is assumed that (like
+all other privileged programs) the programmer has taken adequate
+precautions to prevent security violations.
+.Sh RETURN VALUES
+If a call to
+.Fn getlogin
+succeeds, it returns a pointer to a null-terminated string in a static buffer.
+If the name has not been set, it returns
+.Dv NULL .
+.Pp
+If a call to
+.Fn setlogin
+succeeds, a value of 0 is returned.
+If
+.Fn setlogin
+fails, a value of \-1 is returned and an error code is
+placed in the global location
+.Va errno .
+.Pp
+The
+.Fn getlogin_r
+function
+returns zero if successful, or the error number upon failure.
+.Sh ERRORS
+The following errors may be returned by these calls:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+The
+.Fa name
+parameter gave an
+invalid address.
+.It Bq Er EINVAL
+The
+.Fa name
+parameter
+pointed to a string that was too long.
+Login names are limited to
+.Dv MAXLOGNAME
+(from
+.Ao Pa sys/param.h Ac )
+characters, currently 16.
+.It Bq Er EPERM
+The caller tried to set the login name and was not the super-user.
+.It Bq Er ERANGE
+The size of the buffer is smaller than the result to be returned.
+.El
+.Sh SEE ALSO
+.Xr setsid 2
+.Sh STANDARDS
+The
+.Fn getlogin
+and
+.Fn getlogin_r
+functions conform to
+.St -p1003.1-96 .
+.Sh HISTORY
+The
+.Fn getlogin
+function first appeared in
+.Bx 4.4 .
+.Sh BUGS
+Login names are limited in length by
+.Fn setlogin .
+However, lower limits are placed on login names elsewhere in the system
+.Pf ( Dv UT_NAMESIZE
+in
+.Ao Pa utmp.h Ac ) .
+.Pp
+In earlier versions of the system,
+.Fn getlogin
+failed unless the process was associated with a login terminal.
+The current implementation (using
+.Fn setlogin )
+allows getlogin to succeed even when the process has no controlling terminal.
+In earlier versions of the system, the value returned by
+.Fn getlogin
+could not be trusted without checking the user ID.
+Portable programs should probably still make this check.
diff --git a/lib/nbsd_libc/sys/getpeername.2 b/lib/nbsd_libc/sys/getpeername.2
new file mode 100644 (file)
index 0000000..48c08a0
--- /dev/null
@@ -0,0 +1,135 @@
+.\"    $NetBSD: getpeername.2,v 1.19 2006/03/05 22:06:08 agc Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getpeername.2      8.1 (Berkeley) 6/4/93
+.\"
+.Dd March 5, 2006
+.Dt GETPEERNAME 2
+.Os
+.Sh NAME
+.Nm getpeername
+.Nd get name of connected peer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft int
+.Fn getpeername "int s" "struct sockaddr * restrict name" "socklen_t * restrict namelen"
+.Sh DESCRIPTION
+.Fn getpeername
+returns the name of the peer connected to
+socket
+.Fa s .
+One common use occurs when a process inherits an open socket, such as
+TCP servers forked from
+.Xr inetd 8 .
+In this scenario,
+.Fn getpeername
+is used to determine the connecting client's IP address.
+.Pp
+.Fn getpeername
+takes three parameters:
+.Pp
+.Fa s
+contains the file descriptor of the socket whose peer should be looked up.
+.Pp
+.Fa name
+points to a
+.Li sockaddr
+structure that will hold the address information for the connected peer.
+Normal use requires one to use a structure
+specific to the protocol family in use, such as
+.Li sockaddr_in
+(IPv4) or
+.Li sockaddr_in6
+(IPv6), cast to a (struct sockaddr *).
+.Pp
+For greater portability, especially with the newer protocol families, the new
+.Li struct sockaddr_storage
+should be used.
+.Li sockaddr_storage
+is large enough to hold any of the other sockaddr_* variants.
+On return, it can be cast to the correct sockaddr type,
+based on the protocol family contained in its ss_family field.
+.Pp
+.Fa namelen
+indicates the amount of space pointed to by
+.Fa name ,
+in bytes.
+.Pp
+If address information for the local end of the socket is required, the
+.Xr getsockname 2
+function should be used instead.
+.Pp
+If
+.Fa name
+does not point to enough space to hold the entire socket address, the
+result will be truncated to
+.Fa namelen
+bytes.
+.Sh RETURN VALUES
+If the call succeeds, a 0 is returned and
+.Fa namelen
+is set to the actual size of the socket address returned in
+.Fa name .
+Otherwise,
+.Va errno
+is set and a value of \-1 is returned.
+.Sh ERRORS
+The call succeeds unless:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The argument
+.Fa s
+is not a valid descriptor.
+.It Bq Er ENOTSOCK
+The argument
+.Fa s
+is a file, not a socket.
+.It Bq Er ENOTCONN
+The socket is not connected.
+.It Bq Er ENOBUFS
+Insufficient resources were available in the system
+to perform the operation.
+.It Bq Er EFAULT
+The
+.Fa name
+parameter points to memory not in a valid part of the
+process address space.
+.El
+.Sh SEE ALSO
+.Xr accept 2 ,
+.Xr bind 2 ,
+.Xr getsockname 2 ,
+.Xr socket 2
+.Sh HISTORY
+The
+.Fn getpeername
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/getpgrp.2 b/lib/nbsd_libc/sys/getpgrp.2
new file mode 100644 (file)
index 0000000..bdb5a8e
--- /dev/null
@@ -0,0 +1,129 @@
+.\"    $NetBSD: getpgrp.2,v 1.23 2009/03/23 14:11:27 joerg Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getpgrp.2  8.1 (Berkeley) 6/4/93
+.\"
+.Dd August 11, 2002
+.Dt GETPGRP 2
+.Os
+.Sh NAME
+.Nm getpgrp ,
+.Nm getpgid
+.Nd get process group
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft pid_t
+.Fn getpgrp "void"
+.Ft pid_t
+.Fn getpgid "pid_t pid"
+.Sh DESCRIPTION
+The process group of the current process is returned by
+.Fn getpgrp .
+The process group of the
+.Fa pid
+process is returned by
+.Fn getpgid .
+.Pp
+Process groups are used for distribution of signals, and
+by terminals to arbitrate requests for their input: processes
+that have the same process group as the terminal are foreground
+and may read, while others will block with a signal if they attempt
+to read.
+.Pp
+This call is thus used by programs such as
+.Xr csh 1
+to create
+process groups
+in implementing job control.
+The
+.Fn tcgetpgrp
+and
+.Fn tcsetpgrp
+calls
+are used to get/set the process group of the control terminal.
+.Sh ERRORS
+.Fn getpgrp
+always succeeds, however
+.Fn getpgid
+will succeed unless:
+.Bl -tag -width Er
+.It Bq Er ESRCH
+if there is no process with a process ID equal to
+.Fa pid .
+.El
+.Sh SEE ALSO
+.Xr setpgid 2 ,
+.Xr termios 4
+.Sh STANDARDS
+The
+.Fn getpgrp
+function conforms to
+.St -p1003.1-88 .
+.Sh HISTORY
+The
+.Fn getpgrp
+function call appeared in
+.Bx 4.0 .
+The
+.Fn getpgid
+function call is derived from its usage in
+.At V.4 ,
+and first appeared in
+.Nx 1.3 .
+.Sh COMPATIBILITY
+This version of
+.Fn getpgrp
+differs from past Berkeley versions by not taking a
+.Fa "pid_t pid"
+argument.
+This incompatibility is required by
+.St -p1003.1-90 .
+.Pp
+From the
+.St -p1003.1-90
+Rationale:
+.Lp
+.Bx 4.3
+provides a
+.Fn getpgrp
+function that returns the process group ID for a specified process.
+Although this function is used to support job control, all known
+job-control shells always specify the calling process with this
+function.
+Thus, the simpler System V
+.Fn getpgrp
+suffices, and the added complexity of the
+.Bx 4.3
+.Fn getpgrp
+has been omitted from POSIX.1.
+The old functionality is available from the
+.Fn getpgid
+function.
diff --git a/lib/nbsd_libc/sys/getpid.2 b/lib/nbsd_libc/sys/getpid.2
new file mode 100644 (file)
index 0000000..9373a85
--- /dev/null
@@ -0,0 +1,77 @@
+.\"    $NetBSD: getpid.2,v 1.17 2010/04/03 15:13:43 jruoho Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getpid.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 3, 2010
+.Dt GETPID 2
+.Os
+.Sh NAME
+.Nm getpid ,
+.Nm getppid
+.Nd get parent or calling process identification
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft pid_t
+.Fn getpid void
+.Ft pid_t
+.Fn getppid void
+.Sh DESCRIPTION
+.Fn getpid
+returns
+the process ID of
+the calling process.
+The ID is guaranteed to be unique and is
+useful for constructing temporary file names.
+.Pp
+.Fn getppid
+returns the process ID of the parent
+of the calling process.
+.Sh ERRORS
+The
+.Fn getpid
+and
+.Fn getppid
+functions are always successful, and no return value is reserved to
+indicate an error.
+.Sh SEE ALSO
+.Xr gethostid 3
+.Sh STANDARDS
+.Fn getpid
+and
+.Fn getppid
+conform to
+.St -p1003.1-90 .
+.Sh HISTORY
+The
+.Fn getpid
+function appeared in
+.At v5 .
diff --git a/lib/nbsd_libc/sys/getpriority.2 b/lib/nbsd_libc/sys/getpriority.2
new file mode 100644 (file)
index 0000000..3969f5d
--- /dev/null
@@ -0,0 +1,146 @@
+.\"    $NetBSD: getpriority.2,v 1.18 2009/03/11 13:39:14 joerg Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getpriority.2      8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 25, 2004
+.Dt GETPRIORITY 2
+.Os
+.Sh NAME
+.Nm getpriority ,
+.Nm setpriority
+.Nd get/set program scheduling priority
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/resource.h
+.Ft int
+.Fn getpriority "int which" "id_t who"
+.Ft int
+.Fn setpriority "int which" "id_t who" "int prio"
+.Sh DESCRIPTION
+The scheduling
+priority of the process, process group, or user, as indicated by
+.Fa which
+and
+.Fa who
+is obtained with the
+.Fn getpriority
+call and set with the
+.Fn setpriority
+call.
+.Fa which
+is one of
+.Dv PRIO_PROCESS ,
+.Dv PRIO_PGRP ,
+or
+.Dv PRIO_USER ,
+and
+.Fa who
+is interpreted relative to
+.Fa which
+(a process identifier for
+.Dv PRIO_PROCESS ,
+process group
+identifier for
+.Dv PRIO_PGRP ,
+and a user ID for
+.Dv PRIO_USER ) .
+A zero value of
+.Fa who
+denotes the current process, process group, or user.
+.Fa prio
+is a value in the range -20 to 20.
+The default priority is 0;
+lower priorities cause more favorable scheduling.
+A value of 19 or 20
+will schedule a process only when nothing at priority \*(Le 0 is runnable.
+.Pp
+The
+.Fn getpriority
+call returns the highest priority (lowest numerical value)
+enjoyed by any of the specified processes.
+The
+.Fn setpriority
+call sets the priorities of all of the specified processes
+to the specified value.
+Only the super-user may lower priorities.
+.Sh RETURN VALUES
+Since
+.Fn getpriority
+can legitimately return the value \-1, it is necessary
+to clear the external variable
+.Va errno
+prior to the
+call, then check it afterward to determine
+if a \-1 is an error or a legitimate value.
+The
+.Fn setpriority
+call returns 0 if there is no error, or
+\-1 if there is.
+.Sh ERRORS
+.Fn getpriority
+and
+.Fn setpriority
+will fail if:
+.Bl -tag -width Er
+.It Bq Er ESRCH
+No process was located using the
+.Fa which
+and
+.Fa who
+values specified.
+.It Bq Er EINVAL
+.Fa which
+was not one of
+.Dv PRIO_PROCESS ,
+.Dv PRIO_PGRP ,
+or
+.Dv PRIO_USER .
+.El
+.Pp
+In addition to the errors indicated above,
+.Fn setpriority
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EPERM
+A process was located, but neither its effective nor real user
+ID matched the effective user ID of the caller.
+.It Bq Er EACCES
+A non super-user attempted to lower a process priority.
+.El
+.Sh SEE ALSO
+.Xr nice 1 ,
+.Xr fork 2 ,
+.Xr renice 8
+.Sh HISTORY
+The
+.Fn getpriority
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/getrlimit.2 b/lib/nbsd_libc/sys/getrlimit.2
new file mode 100644 (file)
index 0000000..9e6d5bd
--- /dev/null
@@ -0,0 +1,232 @@
+.\"    $NetBSD: getrlimit.2,v 1.32 2009/07/01 11:25:50 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getrlimit.2        8.1 (Berkeley) 6/4/93
+.\"
+.Dd July 1, 2009
+.Dt GETRLIMIT 2
+.Os
+.Sh NAME
+.Nm getrlimit ,
+.Nm setrlimit
+.Nd control maximum system resource consumption
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/resource.h
+.Ft int
+.Fn getrlimit "int resource" "struct rlimit *rlp"
+.Ft int
+.Fn setrlimit "int resource" "const struct rlimit *rlp"
+.Sh DESCRIPTION
+Limits on the consumption of system resources by the current process
+and each process it creates may be obtained with the
+.Fn getrlimit
+call, and set with the
+.Fn setrlimit
+call.
+Resources of an arbitrary process can be obtained/changed using
+.Xr sysctl 3 .
+.Pp
+The
+.Fa resource
+parameter is one of the following:
+.Bl -tag -width RLIMIT_FSIZEAA
+.It Li RLIMIT_AS
+The maximum amount (in bytes) of virtual memory the process is allowed to map.
+.It Li RLIMIT_CORE
+The largest size (in bytes)
+.Pa core
+file that may be created.
+.It Li RLIMIT_CPU
+The maximum amount of CPU time (in seconds) to be used by
+each process.
+.It Li RLIMIT_DATA
+The maximum size (in bytes) of the data segment for a process;
+this defines how far a program may extend its break with the
+.Xr sbrk 2
+system call.
+.It Li RLIMIT_FSIZE
+The largest size (in bytes) file that may be created.
+.It Li RLIMIT_MEMLOCK
+The maximum size (in bytes) which a process may lock into memory
+using the
+.Xr mlock 2
+function.
+.It Li RLIMIT_NOFILE
+The maximum number of open files for this process.
+.It Li RLIMIT_NPROC
+The maximum number of simultaneous processes for this user id.
+.It Li RLIMIT_RSS
+The maximum size (in bytes) to which a process's resident set size may
+grow.
+This imposes a limit on the amount of physical memory to be given to
+a process; if memory is tight, the system will prefer to take memory
+from processes that are exceeding their declared resident set size.
+.It Li RLIMIT_SBSIZE
+The maximum size (in bytes) of the socket buffers
+set by the
+.Xr setsockopt 2
+.Dv SO_RCVBUF
+and
+.Dv SO_SNDBUF
+options.
+.It Li RLIMIT_STACK
+The maximum size (in bytes) of the stack segment for a process;
+this defines how far a program's stack segment may be extended.
+Stack extension is performed automatically by the system.
+.El
+.Pp
+A resource limit is specified as a soft limit and a hard limit.
+When a soft limit is exceeded a process may receive a signal (for example,
+if the CPU time or file size is exceeded), but it will be allowed to
+continue execution until it reaches the hard limit (or modifies
+its resource limit).
+The
+.Em rlimit
+structure is used to specify the hard and soft limits on a resource,
+.Bd -literal -offset indent
+struct rlimit {
+       rlim_t  rlim_cur;       /* current (soft) limit */
+       rlim_t  rlim_max;       /* hard limit */
+};
+.Ed
+.Pp
+Only the super-user may raise the maximum limits.
+Other users may only alter
+.Fa rlim_cur
+within the range from 0 to
+.Fa rlim_max
+or (irreversibly) lower
+.Fa rlim_max .
+.Pp
+An
+.Dq infinite
+value for a limit is defined as
+.Dv RLIM_INFINITY .
+.Pp
+Because this information is stored in the per-process information,
+this system call must be executed directly by the shell if it
+is to affect all future processes created by the shell.
+Thus, shells provide built-in commands to change the limits
+.Ic ( limit
+for
+.Xr csh 1 ,
+or
+.Ic ulimit
+for
+.Xr sh 1 ) .
+.Pp
+The system refuses to extend the data or stack space when the limits
+would be exceeded in the normal way: a
+.Xr brk 2
+call fails if the data space limit is reached.
+When the stack limit is reached, the process receives
+a segmentation fault
+.Pq Dv SIGSEGV ;
+if this signal is not
+caught by a handler using the signal stack, this signal
+will kill the process.
+.Pp
+A file I/O operation that would create a file larger that the process'
+soft limit will cause the write to fail and a signal
+.Dv SIGXFSZ
+to be
+generated; this normally terminates the process, but may be caught.
+When the soft CPU time limit is exceeded, a signal
+.Dv SIGXCPU
+is sent to the
+offending process.
+.Sh RETURN VALUES
+A 0 return value indicates that the call succeeded, changing
+or returning the resource limit.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn getrlimit
+and
+.Fn setrlimit
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+The address specified for
+.Fa rlp
+is invalid.
+.It Bq Er EINVAL
+Specified
+.Fa resource
+was invalid.
+.It Bq Er EINVAL
+In the
+.Fn setrlimit
+call, the specified
+.Fa rlim_cur
+exceeds the specified
+.Fa rlim_max .
+.It Bq Er EPERM
+The limit specified to
+.Fn setrlimit
+would have
+raised the maximum limit value, and the caller is not the super-user.
+.El
+.Pp
+The
+.Fn setrlimit
+function may fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The limit specified to
+.Fn setrlimit
+cannot be lowered, because current usage is already higher than the limit.
+.El
+.Sh SEE ALSO
+.Xr csh 1 ,
+.Xr sh 1 ,
+.Xr mlock 2 ,
+.Xr quotactl 2 ,
+.Xr setsockopt 2 ,
+.Xr sigaction 2 ,
+.Xr sigaltstack 2 ,
+.Xr sysctl 3
+.\" Sh STANDARDS
+.\" With exception of
+.\" .Li RLIMIT_AS
+.\" (which is not currently supported), the
+.\" .Fn getrlimit
+.\" and
+.\" .Fn setrlimit
+.\" functions conform to
+.\" .St -susv2 .
+.Sh HISTORY
+The
+.Fn getrlimit
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/getrusage.2 b/lib/nbsd_libc/sys/getrusage.2
new file mode 100644 (file)
index 0000000..26ea982
--- /dev/null
@@ -0,0 +1,164 @@
+.\"    $NetBSD: getrusage.2,v 1.18 2004/05/13 10:20:58 wiz Exp $
+.\"
+.\" Copyright (c) 1985, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getrusage.2        8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt GETRUSAGE 2
+.Os
+.Sh NAME
+.Nm getrusage
+.Nd get information about resource utilization
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/resource.h
+.Fd #define    RUSAGE_SELF      0
+.Fd #define    RUSAGE_CHILDREN \-1
+.Ft int
+.Fn getrusage "int who" "struct rusage *rusage"
+.Sh DESCRIPTION
+.Fn getrusage
+returns information describing the resources used by the current
+process, or all its terminated child processes.
+The
+.Fa who
+parameter is either
+.Dv RUSAGE_SELF
+or
+.Dv RUSAGE_CHILDREN .
+The buffer to which
+.Fa rusage
+points will be filled in with
+the following structure:
+.Bd -literal
+struct rusage {
+        struct timeval ru_utime; /* user time used */
+        struct timeval ru_stime; /* system time used */
+        long ru_maxrss;          /* max resident set size */
+        long ru_ixrss;           /* integral shared text memory size */
+        long ru_idrss;           /* integral unshared data size */
+        long ru_isrss;           /* integral unshared stack size */
+        long ru_minflt;          /* page reclaims */
+        long ru_majflt;          /* page faults */
+        long ru_nswap;           /* swaps */
+        long ru_inblock;         /* block input operations */
+        long ru_oublock;         /* block output operations */
+        long ru_msgsnd;          /* messages sent */
+        long ru_msgrcv;          /* messages received */
+        long ru_nsignals;        /* signals received */
+        long ru_nvcsw;           /* voluntary context switches */
+        long ru_nivcsw;          /* involuntary context switches */
+};
+.Ed
+.Pp
+The fields are interpreted as follows:
+.Bl -tag -width ru_minfltaa
+.It Fa ru_utime
+the total amount of time spent executing in user mode.
+.It Fa ru_stime
+the total amount of time spent in the system executing on behalf
+of the process(es).
+.It Fa ru_maxrss
+the maximum resident set size used (in kilobytes).
+.It Fa ru_ixrss
+an \*(lqintegral\*(rq value indicating the amount of memory used
+by the text segment
+that was also shared among other processes.
+This value is expressed
+in units of kilobytes * ticks-of-execution.
+.It Fa ru_idrss
+an integral value of the amount of unshared memory residing in the
+data segment of a process (expressed in units of
+kilobytes * ticks-of-execution).
+.It Fa ru_isrss
+an integral value of the amount of unshared memory residing in the
+stack segment of a process (expressed in units of
+kilobytes * ticks-of-execution).
+.It Fa ru_minflt
+the number of page faults serviced without any I/O activity; here
+I/O activity is avoided by \*(lqreclaiming\*(rq a page frame from
+the list of pages awaiting reallocation.
+.It Fa ru_majflt
+the number of page faults serviced that required I/O activity.
+.It Fa ru_nswap
+the number of times a process was \*(lqswapped\*(rq out of main
+memory.
+.It Fa ru_inblock
+the number of times the file system had to perform input.
+.It Fa ru_oublock
+the number of times the file system had to perform output.
+.It Fa ru_msgsnd
+the number of IPC messages sent.
+.It Fa ru_msgrcv
+the number of IPC messages received.
+.It Fa ru_nsignals
+the number of signals delivered.
+.It Fa ru_nvcsw
+the number of times a context switch resulted due to a process
+voluntarily giving up the processor before its time slice was
+completed (usually to await availability of a resource).
+.It Fa ru_nivcsw
+the number of times a context switch resulted due to a higher
+priority process becoming runnable or because the current process
+exceeded its time slice.
+.El
+.Sh NOTES
+The numbers
+.Fa ru_inblock
+and
+.Fa ru_oublock
+account only for real
+I/O; data supplied by the caching mechanism is charged only
+to the first process to read or write the data.
+.Sh ERRORS
+.Fn getrusage
+returns \-1 on error.
+The possible errors are:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa who
+parameter is not a valid value.
+.It Bq Er EFAULT
+The address specified by the
+.Fa rusage
+parameter is not in a valid part of the process address space.
+.El
+.Sh SEE ALSO
+.Xr gettimeofday 2 ,
+.Xr wait 2
+.Sh HISTORY
+The
+.Fn getrusage
+function call appeared in
+.Bx 4.2 .
+.Sh BUGS
+There is no way to obtain information about a child process
+that has not yet terminated.
diff --git a/lib/nbsd_libc/sys/getsid.2 b/lib/nbsd_libc/sys/getsid.2
new file mode 100644 (file)
index 0000000..910599e
--- /dev/null
@@ -0,0 +1,73 @@
+.\"    $NetBSD: getsid.2,v 1.10 2006/10/07 21:03:51 elad Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getpgrp.2  8.1 (Berkeley) 6/4/93
+.\"
+.Dd October 7, 2006
+.Dt GETSID 2
+.Os
+.Sh NAME
+.Nm getsid
+.Nd get session ID
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft pid_t
+.Fn getsid "pid_t pid"
+.Sh DESCRIPTION
+The
+.Nm
+function returns the session ID of the process specified by
+.Ar pid .
+If
+.Ar pid
+is 0, the session ID of the calling process is returned.
+The session ID is defined as the process group ID of the
+process that is the session leader.
+.Sh ERRORS
+If an error occurs,
+.Nm
+returns \-1 and the global variable
+.Va errno
+is set to indicate the error, as follows:
+.Bl -tag -width Er
+.It Bq Er ESRCH
+No process can be found corresponding to that specified by
+.Ar pid .
+.El
+.Sh SEE ALSO
+.Xr getpgid 2 ,
+.Xr setsid 2 ,
+.Xr termios 4
+.Sh STANDARDS
+The
+.Fn getsid
+function conforms to
+.St -xpg4.2 .
diff --git a/lib/nbsd_libc/sys/getsockname.2 b/lib/nbsd_libc/sys/getsockname.2
new file mode 100644 (file)
index 0000000..6411615
--- /dev/null
@@ -0,0 +1,155 @@
+.\"    $NetBSD: getsockname.2,v 1.23 2003/08/07 16:43:59 agc Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getsockname.2      8.1 (Berkeley) 6/4/93
+.\"
+.Dd August 11, 2002
+.Dt GETSOCKNAME 2
+.Os
+.Sh NAME
+.Nm getsockname
+.Nd get socket name
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft int
+.Fn getsockname "int s" "struct sockaddr * restrict name" "socklen_t * restrict namelen"
+.Sh DESCRIPTION
+.Fn getsockname
+returns the locally bound address information for a specified socket.
+.Pp
+Common uses of this function are as follows:
+.Bl -bullet
+.It
+When
+.Xr bind 2
+is called with a port number of 0 (indicating the kernel should pick
+an ephemeral port)
+.Fn getsockname
+is used to retrieve the kernel-assigned port number.
+.It
+When a process calls
+.Xr bind 2
+on a wildcard IP address,
+.Fn getsockname
+is used to retrieve the local IP address for the connection.
+.It
+When a function wishes to know the address family of a socket,
+.Fn getsockname
+can be used.
+.El
+.Pp
+.Fn getsockname
+takes three parameters:
+.Pp
+.Fa s ,
+Contains the file descriptor for the socket to be looked up.
+.Pp
+.Fa name
+points to a
+.Li sockaddr
+structure which will hold the resulting address information.
+Normal use requires one to use a structure
+specific to the protocol family in use, such as
+.Li sockaddr_in
+(IPv4) or
+.Li sockaddr_in6
+(IPv6), cast to a (struct sockaddr *).
+.Pp
+For greater portability (such as newer protocol families) the new
+structure sockaddr_storage exists.
+.Li sockaddr_storage
+is large enough to hold any of the other sockaddr_* variants.
+On return, it should be cast to the correct sockaddr type,
+according to the current protocol family.
+.Pp
+.Fa namelen
+indicates the amount of space pointed to by
+.Fa name ,
+in bytes.
+Upon return,
+.Fa namelen
+is set to the actual size of the returned address information.
+.Pp
+If the address of the destination socket for a given socket connection is
+needed, the
+.Xr getpeername 2
+function should be used instead.
+.Pp
+If
+.Fa name
+does not point to enough space to hold the entire socket address, the
+result will be truncated to
+.Fa namelen
+bytes.
+.Sh RETURN VALUES
+On success,
+.Fn getsockname
+returns a 0, and
+.Fa namelen
+is set to the actual size of the socket address returned in
+.Fa name .
+Otherwise,
+.Va errno
+is set, and a value of \-1 is returned.
+.Sh ERRORS
+The call succeeds unless:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The argument
+.Fa s
+is not a valid descriptor.
+.It Bq Er ENOTSOCK
+The argument
+.Fa s
+is a file, not a socket.
+.It Bq Er EINVAL
+The socket has been shut down.
+.It Bq Er ENOBUFS
+Insufficient resources were available in the system to perform the operation.
+.It Bq Er EFAULT
+The
+.Fa name
+parameter points to memory not in a valid part of the process address space.
+.El
+.Sh SEE ALSO
+.Xr bind 2 ,
+.Xr socket 2
+.Sh HISTORY
+The
+.Fn getsockname
+function call appeared in
+.Bx 4.2 .
+.Sh BUGS
+Names bound to sockets in the
+.Ux
+domain are inaccessible;
+.Fn getsockname
+returns a zero length name.
diff --git a/lib/nbsd_libc/sys/getsockopt.2 b/lib/nbsd_libc/sys/getsockopt.2
new file mode 100644 (file)
index 0000000..677049d
--- /dev/null
@@ -0,0 +1,444 @@
+.\"    $NetBSD: getsockopt.2,v 1.34 2009/06/29 08:38:07 wiz Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getsockopt.2       8.4 (Berkeley) 5/2/95
+.\"
+.Dd June 28, 2009
+.Dt GETSOCKOPT 2
+.Os
+.Sh NAME
+.Nm getsockopt ,
+.Nm setsockopt
+.Nd get and set options on sockets
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft int
+.Fn getsockopt "int s" "int level" "int optname" "void * restrict optval" "socklen_t * restrict optlen"
+.Ft int
+.Fn setsockopt "int s" "int level" "int optname" "const void *optval" "socklen_t optlen"
+.Sh DESCRIPTION
+.Fn getsockopt
+and
+.Fn setsockopt
+manipulate the
+.Em options
+associated with a socket.
+Options may exist at multiple
+protocol levels; they are always present at the uppermost
+.Dq socket
+level.
+.Pp
+When manipulating socket options the level at which the
+option resides and the name of the option must be specified.
+To manipulate options at the socket level,
+.Fa level
+is specified as
+.Dv SOL_SOCKET .
+To manipulate options at any
+other level the protocol number of the appropriate protocol
+controlling the option is supplied.
+For example, to indicate that an option is to be interpreted by the
+.Tn TCP
+protocol,
+.Fa level
+should be set to the protocol number of
+.Tn TCP ;
+see
+.Xr getprotoent 3 .
+.Pp
+The parameters
+.Fa optval
+and
+.Fa optlen
+are used to access option values for
+.Fn setsockopt .
+For
+.Fn getsockopt
+they identify a buffer in which the value for the
+requested option(s) are to be returned.
+For
+.Fn getsockopt ,
+.Fa optlen
+is a value-result parameter, initially containing the
+size of the buffer pointed to by
+.Fa optval ,
+and modified on return to indicate the actual size of
+the value returned.
+If no option value is to be supplied or returned,
+.Fa optval
+may be
+.Dv NULL .
+.Pp
+.Fa optname
+and any specified options are passed uninterpreted to the appropriate
+protocol module for interpretation.
+The include file
+.Ao Pa sys/socket.h Ac
+contains definitions for
+socket level options, described below.
+Options at other protocol levels vary in format and
+name; consult the appropriate entries in
+section
+4 of the manual, including:
+.Xr clnp 4 ,
+.Xr faith 4 ,
+.Xr icmp6 4 ,
+.Xr ip 4 ,
+.Xr ip6 4 ,
+.Xr ipsec 4 ,
+.Xr multicast 4 ,
+.Xr pim 4 ,
+.Xr route 4 ,
+.Xr tcp 4 ,
+.Xr tp 4 ,
+and
+.Xr unix 4 .
+.Pp
+Most socket-level options use an
+.Fa int
+parameter for
+.Fa optval .
+For
+.Fn setsockopt ,
+the parameter should be non-zero to enable a boolean option,
+or zero if the option is to be disabled.
+.Dv SO_LINGER
+uses a
+.Fa struct linger
+parameter, defined in
+.Ao Pa sys/socket.h Ac ,
+which specifies the desired state of the option and the
+linger interval (see below).
+.Dv SO_SNDTIMEO
+and
+.Dv SO_RCVTIMEO
+use a
+.Fa struct timeval
+parameter, defined in
+.Ao Pa sys/time.h Ac .
+.Pp
+The following options are recognized at the socket level.
+Except as noted, each may be examined with
+.Fn getsockopt
+and set with
+.Fn setsockopt .
+.Bl -column SO_ACCEPTFILTER data -offset indent
+.It Dv SO_DEBUG Ta "enables recording of debugging information"
+.It Dv SO_REUSEADDR Ta "enables local address reuse"
+.It Dv SO_REUSEPORT Ta "enables duplicate address and port bindings"
+.It Dv SO_KEEPALIVE Ta "enables keep connections alive"
+.It Dv SO_DONTROUTE Ta "enables routing bypass for outgoing messages"
+.It Dv SO_LINGER  Ta "linger on close if data present"
+.It Dv SO_BROADCAST Ta "enables permission to transmit broadcast messages"
+.It Dv SO_OOBINLINE Ta "enables reception of out-of-band data in band"
+.It Dv SO_SNDBUF Ta "set buffer size for output"
+.It Dv SO_RCVBUF Ta "set buffer size for input"
+.It Dv SO_SNDLOWAT Ta "set minimum count for output"
+.It Dv SO_RCVLOWAT Ta "set minimum count for input"
+.It Dv SO_SNDTIMEO Ta "set timeout value for output"
+.It Dv SO_RCVTIMEO Ta "set timeout value for input"
+.It Dv SO_TIMESTAMP Ta "enables reception of a timestamp with datagrams"
+.It Dv SO_ACCEPTFILTER Ta "set accept filter on listening socket"
+.It Dv SO_TYPE Ta "get the type of the socket (get only)"
+.It Dv SO_ERROR Ta "get and clear error on the socket (get only)"
+.El
+.Pp
+.Dv SO_DEBUG
+enables debugging in the underlying protocol modules.
+.Dv SO_REUSEADDR
+indicates that the rules used in validating addresses supplied
+in a
+.Xr bind 2
+call should allow reuse of local addresses.
+.Dv SO_REUSEPORT
+allows completely duplicate bindings by multiple processes
+if they all set
+.Dv SO_REUSEPORT
+before binding the port.
+This option permits multiple instances of a program to each
+receive UDP/IP multicast or broadcast datagrams destined for the bound port.
+.Dv SO_KEEPALIVE
+enables the
+periodic transmission of messages on a connected socket.
+Should the connected party fail to respond to these messages, the connection
+is considered broken and processes using the socket are notified via a
+.Dv SIGPIPE
+signal when attempting to send data.
+.Dv SO_DONTROUTE
+indicates that outgoing messages should
+bypass the standard routing facilities.
+Instead, messages are directed to the appropriate network interface
+according to the network portion of the destination address.
+.Pp
+.Dv SO_LINGER
+controls the action taken when unsent messages
+are queued on socket and a
+.Xr close 2
+is performed.
+If the socket promises reliable delivery of data and
+.Dv SO_LINGER
+is set, the system will block the process on the
+.Xr close 2
+attempt until it is able to transmit the data or until it decides it
+is unable to deliver the information (a timeout period, measured in
+seconds, termed the linger interval, is specified in the
+.Fn setsockopt
+call when
+.Dv SO_LINGER
+is requested).
+If
+.Dv SO_LINGER
+is disabled and a
+.Xr close 2
+is issued, the system will process the close in a manner that allows
+the process to continue as quickly as possible.
+.Pp
+The option
+.Dv SO_BROADCAST
+requests permission to send broadcast datagrams
+on the socket.
+Broadcast was a privileged operation in earlier versions of the system.
+With protocols that support out-of-band data, the
+.Dv SO_OOBINLINE
+option
+requests that out-of-band data be placed in the normal data input queue
+as received; it will then be accessible with
+.Xr recv 2
+or
+.Xr read 2
+calls without the
+.Dv MSG_OOB
+flag.
+Some protocols always behave as if this option is set.
+.Dv SO_SNDBUF
+and
+.Dv SO_RCVBUF
+are options to adjust the normal
+buffer sizes allocated for output and input buffers, respectively.
+The buffer size may be increased for high-volume connections,
+or may be decreased to limit the possible backlog of incoming data.
+The system places an absolute limit on these values.
+.Pp
+.Dv SO_SNDLOWAT
+is an option to set the minimum count for output operations.
+Most output operations process all of the data supplied
+by the call, delivering data to the protocol for transmission
+and blocking as necessary for flow control.
+Nonblocking output operations will process as much data as permitted
+subject to flow control without blocking, but will process no data
+if flow control does not allow the smaller of the low water mark value
+or the entire request to be processed.
+A
+.Xr select 2
+or
+.Xr poll 2
+operation testing the ability to write to a socket will return true
+only if the low water mark amount could be processed.
+The default value for
+.Dv SO_SNDLOWAT
+is set to a convenient size for network efficiency, often 1024.
+.Dv SO_RCVLOWAT
+is an option to set the minimum count for input operations.
+In general, receive calls will block until any (non-zero) amount of data
+is received, then return with the smaller of the amount available or the amount
+requested.
+The default value for
+.Dv SO_RCVLOWAT
+is 1.
+If
+.Dv SO_RCVLOWAT
+is set to a larger value, blocking receive calls normally
+wait until they have received the smaller of the low water mark value
+or the requested amount.
+Receive calls may still return less than the low water mark if an error
+occurs, a signal is caught, or the type of data next in the receive queue
+is different than that returned.
+.Pp
+.Dv SO_SNDTIMEO
+is an option to set a timeout value for output operations.
+It accepts a
+.Fa struct timeval
+parameter with the number of seconds and microseconds
+used to limit waits for output operations to complete.
+If a send operation has blocked for this much time,
+it returns with a partial count
+or with the error
+.Er EAGAIN
+if no data were sent.
+In the current implementation, this timer is restarted each time additional
+data are delivered to the protocol,
+implying that the limit applies to output portions ranging in size
+from the low water mark to the high water mark for output.
+.Dv SO_RCVTIMEO
+is an option to set a timeout value for input operations.
+It accepts a
+.Fa struct timeval
+parameter with the number of seconds and microseconds
+used to limit waits for input operations to complete.
+In the current implementation, this timer is restarted each time additional
+data are received by the protocol,
+and thus the limit is in effect an inactivity timer.
+If a receive operation has been blocked for this much time without
+receiving additional data, it returns with a short count
+or with the error
+.Er EAGAIN
+if no data were received.
+.Pp
+If the
+.Dv SO_TIMESTAMP
+option is enabled on a
+.Dv SOCK_DGRAM
+socket, the
+.Xr recvmsg 2
+call will return a timestamp corresponding to when the datagram was
+received.
+The msg_control field in the msghdr structure points to a buffer
+that contains a cmsghdr structure followed by a struct timeval.
+The cmsghdr fields have the following values:
+.Bd -literal
+cmsg_len = sizeof(struct timeval)
+cmsg_level = SOL_SOCKET
+cmsg_type = SCM_TIMESTAMP
+.Ed
+.Pp
+.Dv SO_ACCEPTFILTER
+places an
+.Xr accept_filter 9
+on the socket, which will filter incoming connections on a listening
+socket before being presented for
+.Xr accept 2 .
+The
+.Fn setsockopt
+system call will fail if the socket already has a filter set, and
+.Xr listen 2
+must be called on the socket before trying to install a filter.
+The
+.Fa optval
+argument
+should point to a
+.Fa struct accept_filter_arg
+that will select and configure the
+.Xr accept_filter 9 ,
+defined as follows:
+.Bd -literal
+struct  accept_filter_arg {
+        char    af_name[16];
+        char    af_arg[256-16];
+};
+.Ed
+.Lp
+The
+.Fa af_name
+argument should be filled with the name of the accept filter
+that the application wishes to place on the listening socket.
+The optional argument
+.Fa af_arg
+can be passed to the accept filter specified by
+.Fa af_name
+to provide additional configuration options at attach time.
+Passing in an
+.Fa optval
+of
+.Dv NULL
+will remove the filter.
+.Pp
+Finally,
+.Dv SO_TYPE
+and
+.Dv SO_ERROR
+are options used only with
+.Fn getsockopt .
+.Dv SO_TYPE
+returns the type of the socket, such as
+.Dv SOCK_STREAM ;
+it is useful for servers that inherit sockets on startup.
+.Dv SO_ERROR
+returns any pending error on the socket and clears
+the error status.
+It may be used to check for asynchronous errors on connected
+datagram sockets or for other asynchronous errors.
+.Sh RETURN VALUES
+A 0 is returned if the call succeeds, \-1 if it fails.
+.Sh ERRORS
+The call succeeds unless:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The argument
+.Fa s
+is not a valid descriptor.
+.It Bq Er EFAULT
+The address pointed to by
+.Fa optval
+is not in a valid part of the process address space.
+For
+.Fn getsockopt ,
+this error may also be returned if
+.Fa optlen
+is not in a valid part of the process address space.
+.It Bq Er EINVAL
+The socket
+.Fa s
+was not suitable for installing an
+.Xr accept_filter 9 .
+.It Bq Er ENOPROTOOPT
+The option is unknown at the level indicated.
+.It Bq Er ENOTSOCK
+The argument
+.Fa s
+is a file, not a socket.
+.El
+.Sh SEE ALSO
+.Xr ioctl 2 ,
+.Xr poll 2 ,
+.Xr select 2 ,
+.Xr socket 2 ,
+.Xr getprotoent 3 ,
+.Xr clnp 4 ,
+.Xr faith 4 ,
+.Xr icmp6 4 ,
+.Xr ip 4 ,
+.Xr ip6 4 ,
+.Xr ipsec 4 ,
+.Xr multicast 4 ,
+.Xr pim 4 ,
+.Xr route 4 ,
+.Xr tcp 4 ,
+.Xr tp 4 ,
+.Xr unix 4 ,
+.Xr protocols 5 ,
+.Xr accept_filter 9
+.Sh HISTORY
+The
+.Fn getsockopt
+system call appeared in
+.Bx 4.2 .
+.Sh BUGS
+Several of the socket options should be handled at lower levels of the system.
diff --git a/lib/nbsd_libc/sys/gettimeofday.2 b/lib/nbsd_libc/sys/gettimeofday.2
new file mode 100644 (file)
index 0000000..4cb857c
--- /dev/null
@@ -0,0 +1,155 @@
+.\"    $NetBSD: gettimeofday.2,v 1.27 2010/05/18 07:14:18 jruoho Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)gettimeofday.2     8.2 (Berkeley) 5/26/95
+.\"
+.Dd May 18, 2010
+.Dt GETTIMEOFDAY 2
+.Os
+.Sh NAME
+.Nm gettimeofday ,
+.Nm settimeofday
+.Nd get/set date and time
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/time.h
+.Ft int
+.Fn gettimeofday "struct timeval * restrict tp" "void * restrict tzp"
+.Ft int
+.Fn settimeofday "const struct timeval * restrict tp" "const void * restrict tzp"
+.Sh DESCRIPTION
+.Bf -symbolic
+Note: time zone information is no longer provided by this interface.
+See
+.Xr localtime 3
+for information on how to retrieve it.
+.Ef
+.Pp
+The system's notion of the current UTC time is obtained with the
+.Fn gettimeofday
+call, and set with the
+.Fn settimeofday
+call.
+The time is expressed in seconds and microseconds
+since midnight (0 hour), January 1, 1970.
+The resolution of the system clock is hardware dependent,
+and the time may be updated continuously or in
+.Dq ticks .
+.Pp
+If
+.Fa tp
+is NULL, the time will not be returned or set.
+Despite being declared
+.Fa void * ,
+the objects pointed to by
+.Fa tzp
+shall be of type
+.Fa struct timezone .
+.Pp
+The structures pointed to by
+.Fa tp
+and
+.Fa tzp
+are defined in
+.In sys/time.h .
+The first one is described in
+.Xr timeval 3
+and the latter legacy structure is defined as:
+.Bd -literal -offset indent
+struct timezone {
+       int     tz_minuteswest; /* of Greenwich */
+       int     tz_dsttime;     /* type of dst correction to apply */
+};
+.Ed
+.Pp
+The
+.Fa timezone
+structure is provided only for source compatibility.
+It is ignored by
+.Fn settimeofday ,
+and
+.Fn gettimeofday
+will always return zeroes.
+.Pp
+If the calling user is not the super-user, then the
+.Fn settimeofday
+function in the standard C library will try to use the
+.Xr clockctl 4
+device if present, thus making possible for non privileged users to
+set the system time.
+If
+.Xr clockctl 4
+is not present or not accessible, then
+.Fn settimeofday
+reverts to the
+.Fn settimeofday
+system call, which is restricted to the super user.
+.\" XXX uncomment when/if this is put into place!
+.\" If the system is running in secure mode (see
+.\" .Xr init 8 ),
+.\" the time may only be advanced.
+.\" This limitation is imposed to prevent a malicious super user
+.\" from setting arbitrary time stamps on files.
+.\" The system time can still be adjusted backwards using the
+.\" .Xr adjtime 2
+.\" system call even when the system is secure.
+.Sh RETURN VALUES
+A return value 0 indicates that the call succeeded.
+A return value \-1 indicates an error occurred, and in this
+case an error code is stored into the global variable
+.Va errno .
+.Sh ERRORS
+The following error codes may be set in
+.Va errno :
+.Bl -tag -width Er
+.It Bq Er EFAULT
+An argument address referenced invalid memory.
+.It Bq Er EPERM
+A user other than the super user attempted to set the time, or the specified
+time was less than the current time, which was not permitted at the current
+security level.
+.El
+.Sh SEE ALSO
+.Xr date 1 ,
+.Xr adjtime 2 ,
+.Xr ctime 3 ,
+.Xr localtime 3 ,
+.Xr clockctl 4 ,
+.Xr timed 8
+.Sh HISTORY
+The
+.Fn gettimeofday
+function call appeared in
+.Bx 4.2 .
+The
+.Fa tzp
+argument was deprecated in
+.Bx 4.4
+(and many other systems).
diff --git a/lib/nbsd_libc/sys/getuid.2 b/lib/nbsd_libc/sys/getuid.2
new file mode 100644 (file)
index 0000000..f514fa1
--- /dev/null
@@ -0,0 +1,85 @@
+.\"    $NetBSD: getuid.2,v 1.17 2010/04/05 07:44:28 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)getuid.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 3, 2010
+.Dt GETUID 2
+.Os
+.Sh NAME
+.Nm getuid ,
+.Nm geteuid
+.Nd get user identification
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft uid_t
+.Fn getuid void
+.Ft uid_t
+.Fn geteuid void
+.Sh DESCRIPTION
+The
+.Fn getuid
+function returns the real user ID of the calling process.
+The
+.Fn geteuid
+function
+returns the effective user ID of the calling process.
+.Pp
+The real user ID is that of the user who has invoked the program.
+As the effective user ID
+gives the process additional permissions during
+execution of
+.Dq Em set-user-ID
+mode processes,
+.Fn getuid
+is used to determine the real-user-id of the calling process.
+.Sh ERRORS
+The
+.Fn getuid
+and
+.Fn geteuid
+functions are always successful, and no return value is reserved to
+indicate an error.
+.Sh SEE ALSO
+.Xr getgid 2 ,
+.Xr setreuid 2
+.Sh STANDARDS
+The
+.Fn geteuid
+and
+.Fn getuid
+functions conform to
+.St -p1003.1-90 .
+.Sh HISTORY
+The
+.Fn getuid
+function appeared in
+.At v4 .
diff --git a/lib/nbsd_libc/sys/getvfsstat.2 b/lib/nbsd_libc/sys/getvfsstat.2
new file mode 100644 (file)
index 0000000..ed49398
--- /dev/null
@@ -0,0 +1,114 @@
+.\"    $NetBSD: getvfsstat.2,v 1.3 2006/05/19 17:59:28 tsutsui Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)getvfsstat.2        8.3 (Berkeley) 5/25/95
+.\"
+.Dd May 19, 2006
+.Dt GETVFSSTAT 2
+.Os
+.Sh NAME
+.Nm getvfsstat
+.Nd get list of all mounted file systems
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/statvfs.h
+.Ft int
+.Fn getvfsstat "struct statvfs *buf" "size_t bufsize" "int flags"
+.Sh DESCRIPTION
+.Fn getvfsstat
+returns information about all mounted file systems.
+.Fa buf
+is a pointer to an array of
+.Nm statvfs
+structures defined in
+.Xr statvfs 5 .
+.Pp
+The buffer is filled with an array of
+.Fa statvfs
+structures, one for each mounted file system
+up to the size specified by
+.Fa bufsize .
+.Pp
+If
+.Fa buf
+is given as
+.Dv NULL ,
+.Fn getvfsstat
+returns just the number of mounted file systems.
+.Pp
+Normally
+.Fa flags
+should be specified as
+.Dv ST_WAIT .
+If
+.Fa flags
+is set to
+.Dv ST_NOWAIT ,
+.Fn getvfsstat
+will return the information it has available without requesting
+an update from each file system.
+Thus, some of the information will be out of date, but
+.Fn getvfsstat
+will not block waiting for information from a file system that is
+unable to respond.
+.Sh RETURN VALUES
+Upon successful completion, the number of
+.Fa statvfs
+structures is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn getvfsstat
+fails if one or more of the following are true:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+.Fa buf
+points to an invalid address.
+.It Bq Er EIO
+An
+.Tn I/O
+error occurred while reading from or writing to the file system.
+.El
+.Sh SEE ALSO
+.Xr statvfs 2 ,
+.Xr getmntinfo 3 ,
+.Xr fstab 5 ,
+.Xr mount 8
+.Sh HISTORY
+The
+.Fn getvfsstat
+function first appeared in
+.Nx 3.0
+to replace
+.Fn getfsstat
+which appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/sys/intro.2 b/lib/nbsd_libc/sys/intro.2
new file mode 100644 (file)
index 0000000..9718746
--- /dev/null
@@ -0,0 +1,832 @@
+.\"    $NetBSD: intro.2,v 1.55 2010/03/22 19:30:55 joerg Exp $
+.\"
+.\" Copyright (c) 1980, 1983, 1986, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)intro.2    8.5 (Berkeley) 2/27/95
+.\"
+.Dd July 23, 2009
+.Dt INTRO 2
+.Os
+.Sh NAME
+.Nm intro ,
+.Nm errno
+.Nd introduction to system calls and error numbers
+.Sh SYNOPSIS
+.In errno.h
+.Sh DESCRIPTION
+This section provides an overview of the system calls,
+their error returns, and other common definitions and concepts.
+.\".Pp
+.\".Sy System call restart
+.\".Pp
+.\"<more later...>
+.Sh DIAGNOSTICS
+Nearly all of the system calls provide an error number in the external
+variable
+.Va errno .
+.Va errno
+is implemented as a macro which expands to a modifiable lvalue of type
+.Fa int .
+.Pp
+When a system call detects an error,
+it returns an integer value
+indicating failure (usually \-1)
+and sets the variable
+.Va errno
+accordingly.
+(This allows interpretation of the failure on receiving
+a \-1 and to take action accordingly.)
+Successful calls never set
+.Va errno ;
+once set, it remains until another error occurs.
+It should only be examined after an error has been reported, because
+otherwise a leftover value from some previous error may be found
+instead.
+.Po
+Many library functions that are not system calls also set
+.Va errno
+on return, in the same fashion.
+In these cases a nonzero value may be left in
+.Va errno
+even upon successful return if some internal action failed.
+.Pc
+.Pp
+The manual page for each system call will list some of the common
+errno codes that system call can return, but that should not be
+considered an exhaustive list, i.e.
+a properly written program should be able to gracefully recover from
+any error that a system call might return.
+Documenting all the error codes that a system call can return in
+a more specification-like manner would take more resources than
+this project has available.
+.Pp
+Note also that a number of system calls overload the meanings of these
+error numbers, and that in these cases the meanings must be
+interpreted according to the type and circumstances of the call.
+.Pp
+The following is a complete list of the errors and their
+names as given in
+.In errno.h .
+.Bl -hang -width Ds
+.It Er 0 Em "Error 0" .
+Not used.
+.It Er 1 EPERM Em "Operation not permitted" .
+An attempt was made to perform an operation limited to processes
+with appropriate privileges or to the owner of a file or other
+resources.
+.It Er 2 ENOENT Em "No such file or directory" .
+A component of a specified pathname did not exist, or the
+pathname was an empty string.
+.It Er 3 ESRCH Em "No such process" .
+No process could be found corresponding to that specified by the given
+process ID.
+.It Er 4 EINTR Em "Interrupted function call" .
+An asynchronous signal (such as
+.Dv SIGINT
+or
+.Dv SIGQUIT )
+was caught by the process during the execution of an interruptible
+function.
+If the signal handler performs a normal return, the
+interrupted function call will seem to have returned the error condition.
+.It Er 5 EIO Em "Input/output error" .
+Some physical input or output error occurred.
+This error will not be reported until a subsequent operation on the same file
+descriptor and may be lost (over written) by any subsequent errors.
+.It Er 6 ENXIO Em "Device not configured" .
+Input or output on a special file referred to a device that did not
+exist, or
+made a request beyond the limits of the device.
+This error may also occur when, for example,
+a tape drive is not online or no disk pack is
+loaded on a drive.
+.It Er 7 E2BIG Em "Arg list too long" .
+The number of bytes used for the argument and environment
+list of the new process exceeded the current limit of
+.if t 2\u\s-218\s+2\d
+.if n 2**18
+bytes
+.Pf ( Dv ARG_MAX
+in
+.In sys/syslimits.h ) .
+.It Er 8 ENOEXEC Em "Exec format error" .
+A request was made to execute a file
+that, although it has the appropriate permissions,
+was not in the format required for an
+executable file.
+.It Er 9 EBADF Em "Bad file descriptor" .
+A file descriptor argument was out of range, referred to no open file,
+had been revoked by
+.Xr revoke 2 ,
+or a
+.Xr read 2
+(or
+.Xr write 2 )
+request was made to a file that was
+only open for writing (or reading).
+.It Er 10 ECHILD Em "\&No child processes" .
+A
+.Xr wait 2
+or
+.Xr waitpid 2
+function was executed by a process that had no existing or unwaited-for
+child processes.
+.It Er 11 EDEADLK Em "Resource deadlock avoided" .
+An attempt was made to lock a system resource that
+would have resulted in a deadlock situation.
+.It Er 12 ENOMEM Em "Cannot allocate memory" .
+The new process image required more memory than was allowed by the hardware
+or by system-imposed memory management constraints.
+A lack of swap space is normally temporary; however,
+a lack of core is not.
+Soft limits may be increased to their corresponding hard limits.
+.It Er 13 EACCES Em "Permission denied" .
+An attempt was made to access a file in a way forbidden
+by its file access permissions.
+.It Er 14 EFAULT Em "Bad address" .
+The system detected an invalid address in attempting to
+use an argument of a call.
+The reliable detection of this error cannot be guaranteed and when not detected
+may result in the generation of a signal, indicating an address violation,
+which is sent to the process.
+.It Er 15 ENOTBLK Em "Block device required" .
+A block device operation was attempted on a non-block device or file.
+.It Er 16 EBUSY Em "Resource busy" .
+An attempt to use a system resource which was in use at the time
+in a manner which would have conflicted with the request.
+.It Er 17 EEXIST Em "File exists" .
+An existing file was mentioned in an inappropriate context,
+for instance, as the new link name in a
+.Xr link 2
+function.
+.It Er 18 EXDEV Em "Improper link" .
+A hard link to a file on another file system
+was attempted.
+.It Er 19 ENODEV Em "Operation not supported by device" .
+An attempt was made to apply an inappropriate
+function to a device,
+for example,
+trying to read a write-only device such as a printer.
+.It Er 20 ENOTDIR Em "Not a directory" .
+A component of the specified pathname existed, but it was
+not a directory, when a directory was expected.
+.It Er 21 EISDIR Em "Is a directory" .
+An attempt was made to open a directory with write mode specified.
+.It Er 22 EINVAL Em "Invalid argument" .
+Some invalid argument was supplied.
+(For example, specifying an undefined signal to a
+.Xr signal 3
+or
+.Xr kill 2
+function).
+.It Er 23 ENFILE Em "Too many open files in system" .
+Maximum number of file descriptors allowable on the system
+has been reached and a requests for an open cannot be satisfied
+until at least one has been closed.
+.It Er 24 EMFILE Em "Too many open files" .
+\*[Lt]As released, the limit on the number of
+open files per process is 64.\*[Gt]
+The
+.Xr getrlimit 2
+call with the
+.Ar RLIMIT_NOFILE
+resource will obtain the current limit.
+.It Er 25 ENOTTY Em "Inappropriate ioctl for device" .
+A control function (see
+.Xr ioctl 2 )
+was attempted for a file or
+special device for which the operation was inappropriate.
+.It Er 26 ETXTBSY Em "Text file busy" .
+The new process was a pure procedure (shared text) file
+which was open for writing by another process, or
+while the pure procedure file was being executed an
+.Xr open 2
+call requested write access.
+.It Er 27 EFBIG Em "File too large" .
+The size of a file exceeded the maximum.
+(The system-wide maximum file size is
+.if t 2\u\s-263\s+2\d
+.if n 2**63
+bytes.
+Each file system may impose a lower limit for files contained within it).
+.It Er 28 ENOSPC Em "Device out of space" .
+A
+.Xr write 2
+to an ordinary file, the creation of a
+directory or symbolic link, or the creation of a directory
+entry failed because no more disk blocks were available
+on the file system, or the allocation of an inode for a newly
+created file failed because no more inodes were available
+on the file system.
+.It Er 29 ESPIPE Em "Illegal seek" .
+An
+.Xr lseek 2
+function was issued on a socket, pipe or
+.Tn FIFO .
+.It Er 30 EROFS Em "Read-only file system" .
+An attempt was made to modify a file or directory
+was made
+on a file system that was read-only at the time.
+.It Er 31 EMLINK Em "Too many links" .
+The number of hard links to a single file has exceeded the maximum.
+(The system-wide maximum number of hard links is 32767.
+Each file system may impose a lower limit for files contained within it).
+.It Er 32 EPIPE Em "Broken pipe" .
+A write on a pipe, socket or
+.Tn FIFO
+for which there is no process
+to read the data.
+.It Er 33 EDOM Em "Numerical argument out of domain" .
+A numerical input argument was outside the defined domain of the mathematical
+function.
+.It Er 34 ERANGE Em "Result too large or too small" .
+The result of the function is too large or too small to be represented
+in the available space.
+.It Er 35 EAGAIN Em "Resource temporarily unavailable" .
+This is a temporary condition and later calls to the
+same routine may complete normally.
+.It Er 36 EINPROGRESS Em "Operation now in progress" .
+An operation that takes a long time to complete (such as
+a
+.Xr connect 2 )
+was attempted on a non-blocking object (see
+.Xr fcntl 2 ) .
+.It Er 37 EALREADY Em "Operation already in progress" .
+An operation was attempted on a non-blocking object that already
+had an operation in progress.
+.It Er 38 ENOTSOCK Em "Socket operation on non-socket" .
+Self-explanatory.
+.It Er 39 EDESTADDRREQ Em "Destination address required" .
+A required address was omitted from an operation on a socket.
+.It Er 40 EMSGSIZE Em "Message too long" .
+A message sent on a socket was larger than the internal message buffer
+or some other network limit.
+.It Er 41 EPROTOTYPE Em "Protocol wrong type for socket" .
+A protocol was specified that does not support the semantics of the
+socket type requested.
+For example, you cannot use the
+.Tn ARPA
+Internet
+.Tn UDP
+protocol with type
+.Dv SOCK_STREAM .
+.It Er 42 ENOPROTOOPT Em "Protocol option not available" .
+A bad option or level was specified in a
+.Xr getsockopt 2
+or
+.Xr setsockopt 2
+call.
+.It Er 43 EPROTONOSUPPORT Em "Protocol not supported" .
+The protocol has not been configured into the
+system or no implementation for it exists.
+.It Er 44 ESOCKTNOSUPPORT Em "Socket type not supported" .
+The support for the socket type has not been configured into the
+system or no implementation for it exists.
+.It Er 45 EOPNOTSUPP Em "Operation not supported" .
+The attempted operation is not supported for the type of object referenced.
+Usually this occurs when a file descriptor refers to a file or socket
+that cannot support this operation,
+for example, trying to
+.Em accept
+a connection on a datagram socket.
+.It Er 46 EPFNOSUPPORT Em "Protocol family not supported" .
+The protocol family has not been configured into the
+system or no implementation for it exists.
+.It Er 47 EAFNOSUPPORT Em "Address family not supported by protocol family" .
+An address incompatible with the requested protocol was used.
+For example, you shouldn't necessarily expect to be able to use
+.Tn NS
+addresses with
+.Tn ARPA
+Internet protocols.
+.It Er 48 EADDRINUSE Em "Address already in use" .
+Only one usage of each address is normally permitted.
+.It Er 49 EADDRNOTAVAIL Em "Cannot assign requested address" .
+Normally results from an attempt to create a socket with an
+address not on this machine.
+.It Er 50 ENETDOWN Em "Network is down" .
+A socket operation encountered a dead network.
+.It Er 51 ENETUNREACH Em "Network is unreachable" .
+A socket operation was attempted to an unreachable network.
+.It Er 52 ENETRESET Em "Network dropped connection on reset" .
+The host you were connected to crashed and rebooted.
+.It Er 53 ECONNABORTED Em "Software caused connection abort" .
+A connection abort was caused internal to your host machine.
+.It Er 54 ECONNRESET Em "Connection reset by peer" .
+A connection was forcibly closed by a peer.
+This normally results from a loss of the connection on the remote
+socket due to a timeout or a reboot.
+.It Er 55 ENOBUFS Em "\&No buffer space available" .
+An operation on a socket or pipe was not performed because
+the system lacked sufficient buffer space or because a queue was full.
+.It Er 56 EISCONN Em "Socket is already connected" .
+A
+.Xr connect 2
+request was made on an already connected socket; or,
+a
+.Xr sendto 2
+or
+.Xr sendmsg 2
+request on a connected socket specified a destination
+when already connected.
+.It Er 57 ENOTCONN Em "Socket is not connected" .
+An request to send or receive data was disallowed because
+the socket was not connected and (when sending on a datagram socket)
+no address was supplied.
+.It Er 58 ESHUTDOWN Em "Cannot send after socket shutdown" .
+A request to send data was disallowed because the socket
+had already been shut down with a previous
+.Xr shutdown 2
+call.
+.It Er 59 ETOOMANYREFS Em "Too many references: can't splice" .
+The resource is used up to capacity.
+.It Er 60 ETIMEDOUT Em "Operation timed out" .
+A
+.Xr connect 2
+or
+.Xr send 2
+request failed because the connected party did not
+properly respond after a period of time.
+(The timeout period is dependent on the communication protocol).
+.It Er 61 ECONNREFUSED Em "Connection refused" .
+No connection could be made because the target machine actively
+refused it.
+This usually results from trying to connect
+to a service that is inactive on the foreign host.
+.It Er 62 ELOOP Em "Too many levels of symbolic links" .
+A path name lookup involved more than 32
+.Pq Dv MAXSYMLINKS
+symbolic links.
+.It Er 63 ENAMETOOLONG Em "File name too long" .
+A component of a path name exceeded 255
+.Pq Dv MAXNAMELEN
+characters, or an entire
+path name exceeded 1023
+.Pq Dv MAXPATHLEN Ns \-1
+characters.
+.It Er 64 EHOSTDOWN Em "Host is down" .
+A socket operation failed because the destination host was down.
+.It Er 65 EHOSTUNREACH Em "No route to host" .
+A socket operation was attempted to an unreachable host.
+.It Er 66 ENOTEMPTY Em "Directory not empty" .
+A directory with entries other than
+.Ql \&.
+and
+.Ql \&..
+was supplied to a remove directory or rename call.
+.It Er 67 EPROCLIM Em "Too many processes" .
+.It Er 68 EUSERS Em "Too many users" .
+The quota system ran out of table entries.
+.It Er 69 EDQUOT Em "Disc quota exceeded" .
+A
+.Xr write 2
+to an ordinary file, the creation of a
+directory or symbolic link, or the creation of a directory
+entry failed because the user's quota of disk blocks was
+exhausted, or the allocation of an inode for a newly
+created file failed because the user's quota of inodes
+was exhausted.
+.It Er 70 ESTALE Em "Stale NFS file handle" .
+An attempt was made to access an open file (on an
+.Tn NFS
+filesystem)
+which is now unavailable as referenced by the file descriptor.
+This may indicate the file was deleted on the
+.Tn NFS
+server or some other catastrophic event occurred.
+.It Er 71 EREMOTE Em "Too many levels of remote in path" .
+.Tn NFS
+version 3 RPC return code 71.
+.It Er 72 EBADRPC Em "RPC struct is bad" .
+Exchange of
+.Tn RPC
+information was unsuccessful.
+.It Er 73 ERPCMISMATCH Em "RPC version wrong" .
+The version of
+.Tn RPC
+on the remote peer is not compatible with
+the local version.
+.It Er 74 EPROGUNAVAIL Em "RPC prog. not avail" .
+The requested program is not registered on the remote host.
+.It Er 75 EPROGMISMATCH Em "Program version wrong" .
+The requested version of the program is not available
+on the remote host
+.Pq Tn RPC .
+.It Er 76 EPROCUNAVAIL Em "Bad procedure for program" .
+An
+.Tn RPC
+call was attempted for a procedure which doesn't exist
+in the remote program.
+.It Er 77 ENOLCK Em "No locks available" .
+A system-imposed limit on the number of simultaneous file
+locks was reached.
+.It Er 78 ENOSYS Em "Function not implemented" .
+Attempted a system call that is not available on this
+system.
+.It Er 79 EFTYPE Em "Inappropriate file type or format" .
+Attempted a file operation on a file of a type for which it was invalid.
+.It Er 80 EAUTH Em "Authentication error" .
+Attempted to use an invalid authentication ticket to mount an
+.Tn NFS
+filesystem.
+.It Er 81 ENEEDAUTH Em "Need authenticator" .
+An authentication ticket must be obtained before the given
+.Tn NFS
+filesystem may be mounted.
+.It Er 82 EIDRM Em "Identifier removed" .
+An IPC identifier was removed while the current process was waiting on it.
+.It Er 83 ENOMSG Em "No message of the desired type" .
+An IPC message queue does not contain a message of the desired type,
+or a message catalog does not contain the requested message.
+.It Er 84 EOVERFLOW Em "Value too large to be stored in data type" .
+A numerical result of the function was too large to be stored in the
+caller-provided space.
+.It Er 85 EILSEQ Em "Illegal byte sequence" .
+A wide character/multibyte character encoding error occurred.
+.It Er 86 ENOTSUP Em "Not supported" .
+An attempt was made to set or change a parameter to an unsupported
+value.
+.It Er 87 ECANCELED Em "Operation canceled" .
+The requested operation was canceled.
+.It Er 88 EBADMSG Em "Bad or corrupt message" .
+A message in the specified message catalog did not satisfy implementation
+defined criteria, or a STREAMS operation encountered an invalid message or
+a file descriptor at the STREAM head.
+.It Er 89 ENODATA Em "No message available" .
+No message is available on the STREAM head read queue
+.It Er 90 ENOSR Em "No STREAM resources" .
+Buffers could not be allocated due to insufficient STREAMs memory resources.
+.It Er 91 ENOSTR Em "Not a STREAM" .
+A STREAM is not associated with the specified file descriptor.
+.It Er 92 ETIME Em "STREAM ioctl timeout" .
+The timer set for a STREAMS
+.Xr ioctl 2
+operation has expired.
+.It Er 93 ENOATTR Em "Attribute not found" .
+The specified extended attribute does not exist.
+.It Er 94 EMULTIHOP Em "Multihop attempted" .
+Components of path require hopping to multiple remote machines and the
+file system does not allow it.
+It occurs when users try to access remote resources which are not directly
+accessible.
+.It Er 95 ENOLINK Em "Link has been severed" .
+Occurs when the link (virtual circuit) connecting to a remote machine is gone.
+.It Er 96 EPROTO Em "Protocol error" .
+Some protocol error occurred.
+This error is device-specific, but is generally not related to a hardware
+failure.
+.El
+.Sh DEFINITIONS
+.Bl -tag -width Ds
+.It Process ID
+Each active process in the system is uniquely identified by a non-negative
+integer called a process ID.
+The range of this ID is from 0 to 30000.
+.It Parent process ID
+A new process is created by a currently active process; (see
+.Xr fork 2 ) .
+The parent process ID of a process is initially the process ID of its creator.
+If the creating process exits,
+the parent process ID of each child is set to the ID of a system process,
+.Xr init 8 .
+.It Process Group
+Each active process is a member of a process group that is identified by
+a non-negative integer called the process group ID.
+This is the process ID of the group leader.
+This grouping permits the signaling of related processes (see
+.Xr termios 4 )
+and the job control mechanisms of
+.Xr csh 1 .
+.It Session
+A session is a set of one or more process groups.
+A session is created by a successful call to
+.Xr setsid 2 ,
+which causes the caller to become the only member of the only process
+group in the new session.
+.It Session leader
+A process that has created a new session by a successful call to
+.Xr setsid 2 ,
+is known as a session leader.
+Only a session leader may acquire a terminal as its controlling terminal (see
+.Xr termios 4 ) .
+.It Controlling process
+A session leader with a controlling terminal is a controlling process.
+.It Controlling terminal
+A terminal that is associated with a session is known as the controlling
+terminal for that session and its members.
+.It "Terminal Process Group ID"
+A terminal may be acquired by a session leader as its controlling terminal.
+Once a terminal is associated with a session, any of the process groups
+within the session may be placed into the foreground by setting
+the terminal process group ID to the ID of the process group.
+This facility is used
+to arbitrate between multiple jobs contending for the same terminal.
+(See
+.Xr csh 1
+and
+.Xr tty 4
+for more information on job control.)
+.It "Orphaned Process Group"
+A process group is considered to be
+.Em orphaned
+if it is not under the control of a job control shell.
+More precisely, a process group is orphaned
+when none of its members has a parent process that is in the same session
+as the group,
+but is in a different process group.
+Note that when a process exits, the parent process for its children
+is changed to be
+.Xr init 8 ,
+which is in a separate session.
+Not all members of an orphaned process group are necessarily orphaned
+processes (those whose creating process has exited).
+The process group of a session leader is orphaned by definition.
+.It "Real User ID and Real Group ID"
+Each user on the system is identified by a positive integer
+termed the real user ID.
+.Pp
+Each user is also a member of one or more groups.
+One of these groups is distinguished from others and
+used in implementing accounting facilities.
+The positive integer corresponding to this distinguished group is
+termed the real group ID.
+.Pp
+All processes have a real user ID and real group ID.
+These are initialized from the equivalent attributes
+of the process that created it.
+.It "Effective User Id, Effective Group Id, and Group Access List"
+Access to system resources is governed by two values:
+the effective user ID, and the group access list.
+The first member of the group access list is also known as the
+effective group ID.
+(In POSIX.1, the group access list is known as the set of supplementary
+group IDs, and it is unspecified whether the effective group ID is
+a member of the list.)
+.Pp
+The effective user ID and effective group ID are initially the
+process's real user ID and real group ID respectively.
+Either may be modified through execution of a set-user-ID or
+set-group-ID file (possibly by one of its ancestors) (see
+.Xr execve 2 ) .
+By convention, the effective group ID (the first member of the group access
+list) is duplicated, so that the execution of a set-group-ID program
+does not result in the loss of the original (real) group ID.
+.Pp
+The group access list is a set of group IDs
+used only in determining resource accessibility.
+Access checks are performed as described below in
+.Qq File Access Permissions .
+.It "Saved Set User ID and Saved Set Group ID"
+When a process executes a new file, the effective user ID is set
+to the owner of the file if the file is set-user-ID, and the effective
+group ID (first element of the group access list) is set to the group
+of the file if the file is set-group-ID.
+The effective user ID of the process is then recorded as the saved set-user-ID,
+and the effective group ID of the process is recorded as the saved set-group-ID.
+These values may be used to regain those values as the effective user
+or group ID after reverting to the real ID (see
+.Xr setuid 2 ) .
+(In POSIX.1, the saved set-user-ID and saved set-group-ID are optional,
+and are used in setuid and setgid, but this does not work as desired
+for the super-user.)
+.It Super-user
+A process is recognized as a
+.Em super-user
+process and is granted special privileges if its effective user ID is 0.
+.It Special Processes
+The processes with process IDs of 0 and 1 are special.
+Process 0 is the scheduler.
+Process 1 is the initialization process
+.Xr init 8 ,
+and is the ancestor (parent) of every other process in the system.
+It is used to control the process structure.
+The kernel will allocate other kernel threads to handle certain
+periodic tasks or device related tasks, such as:
+.Bl -tag -width pagedaemon
+.It Sy acctwatch
+System accounting disk watcher, see
+.Xr acct 2 ,
+.Xr acct 5 .
+.It Sy aiodoned
+Asynchronous I/O done handler, see
+.Xr uvm 9 .
+.It Sy atabusX
+ATA bus handler, see
+.Xr ata 4 .
+.It Sy cardslotX
+CardBus slot watcher thread, see
+.Xr cardslot 4 .
+.It Sy cryptoret
+The software crypto daemon.
+.It Sy fssbsX
+File system snapshot thread, see
+.Xr fss 4 .
+.It Sy ioflush
+The in-kernel periodic flush the buffer cache to disk task,
+which replaces the old
+.Sy update
+program.
+.It Sy nfsio , nfskqpoll
+NFS handing daemons.
+.It Sy lfs_writer
+Log filesystem writer.
+.It Sy pagedaemon
+The page daemon.
+.It Sy raidX , raidioX , raid_parity , raid_recon , raid_reconip , raid_copyback
+Raid framework related threads, see
+.Xr raid 4 .
+.It Sy scsibusX
+SCSI bus handler, see
+.Xr scsi 4 .
+.It Sy smbiodX , smbkq
+SMBFS handling daemon, see
+.Xr netsmb 4 .
+.It Sy swdmover
+The software data mover I/O thread, see
+.Xr dmoverio 4 .
+.It Sy sysmon
+The systems monitoring framework daemon.
+.It Sy usbX , usbtask
+USB bus handler, see
+.Xr usb 4 .
+.El
+.Pp
+There are more machine-dependent kernel threads allocated by
+different drivers.
+See the specific driver manual pages for more information.
+.It Descriptor
+An integer assigned by the system when a file is referenced
+by
+.Xr open 2
+or
+.Xr dup 2 ,
+or when a socket is created by
+.Xr pipe 2 ,
+.Xr socket 2 ,
+or
+.Xr socketpair 2 ,
+which uniquely identifies an access path to that file or socket from
+a given process or any of its children.
+.It File Name
+Names consisting of up to 255
+.Pq Dv MAXNAMELEN
+characters may be used to name
+an ordinary file, special file, or directory.
+.Pp
+These characters may be selected from the set of all
+.Tn ASCII
+character
+excluding 0 (NUL) and the
+.Tn ASCII
+code for
+.Ql \&/
+(slash).
+(The parity bit, bit 7, must be 0).
+.Pp
+Note that it is generally unwise to use
+.Ql \&* ,
+.Ql \&? ,
+.Ql \&[
+or
+.Ql \&]
+as part of
+file names because of the special meaning attached to these characters
+by the shell.
+.It Pathname
+A path name is a
+.Tn NUL Ns -terminated
+character string starting with an
+optional slash
+.Ql \&/ ,
+followed by zero or more directory names separated
+by slashes, optionally followed by a file name.
+The total length of a path name must be less than 1024
+.Pq Dv MAXPATHLEN
+characters.
+.Pp
+If a path name begins with a slash, the path search begins at the
+.Em root
+directory.
+Otherwise, the search begins from the current working directory.
+A slash by itself names the root directory.
+An empty string is not a valid pathname.
+.It Directory
+A directory is a special type of file that contains entries
+that are references to other files.
+Directory entries are called links.
+By convention, a directory contains at least two links,
+.Ql \&.
+and
+.Ql \&.. ,
+referred to as
+.Em dot
+and
+.Em dot-dot
+respectively.
+Dot refers to the directory itself and dot-dot refers to its parent directory.
+.It "Root Directory and Current Working Directory"
+Each process has associated with it a concept of a root directory
+and a current working directory for the purpose of resolving path
+name searches.
+A process's root directory need not be the root
+directory of the root file system.
+.It File Access Permissions
+Every file in the file system has a set of access permissions.
+These permissions are used in determining whether a process
+may perform a requested operation on the file (such as opening
+a file for writing).
+Access permissions are established at the time a file is created.
+They may be changed at some later time through the
+.Xr chmod 2
+call.
+.Pp
+File access is broken down according to whether a file may be: read,
+written, or executed.
+Directory files use the execute permission to control if the
+directory may be searched.
+.Pp
+File access permissions are interpreted by the system as
+they apply to three different classes of users: the owner
+of the file, those users in the file's group, anyone else.
+Every file has an independent set of access permissions for
+each of these classes.
+When an access check is made, the system decides if permission should be
+granted by checking the access information applicable to the caller.
+.Pp
+Read, write, and execute/search permissions on
+a file are granted to a process if:
+.Pp
+The process's effective user ID is that of the super-user.
+(Note: even the super-user cannot execute a non-executable file).
+.Pp
+The process's effective user ID matches the user ID of the owner
+of the file and the owner permissions allow the access.
+.Pp
+The process's effective user ID does not match the user ID of the
+owner of the file, and either the process's effective
+group ID matches the group ID
+of the file, or the group ID of the file is in
+the process's group access list,
+and the group permissions allow the access.
+.Pp
+Neither the effective user ID nor effective group ID
+and group access list of the process
+match the corresponding user ID and group ID of the file,
+but the permissions for ``other users'' allow access.
+.Pp
+Otherwise, permission is denied.
+.It Sockets and Address Families
+A socket is an endpoint for communication between processes.
+Each socket has queues for sending and receiving data.
+.Pp
+Sockets are typed according to their communications properties.
+These properties include whether messages sent and received
+at a socket require the name of the partner, whether communication
+is reliable, the format used in naming message recipients, etc.
+.Pp
+Each instance of the system supports some
+collection of socket types; consult
+.Xr socket 2
+for more information about the types available and
+their properties.
+.Pp
+Each instance of the system supports some number of sets of
+communications protocols.
+Each protocol set supports addresses of a certain format.
+An Address Family is the set of addresses for a specific group of protocols.
+Each socket has an address
+chosen from the address family in which the socket was created.
+.El
+.Sh SEE ALSO
+.Xr intro 3 ,
+.Xr perror 3
+.Sh HISTORY
+An
+.Nm intro
+manual page appeared in
+.At v6 .
diff --git a/lib/nbsd_libc/sys/ioctl.2 b/lib/nbsd_libc/sys/ioctl.2
new file mode 100644 (file)
index 0000000..5c801e1
--- /dev/null
@@ -0,0 +1,220 @@
+.\"    $NetBSD: ioctl.2,v 1.23 2010/12/19 22:19:27 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)ioctl.2    8.2 (Berkeley) 12/11/93
+.\"
+.Dd December 19, 2010
+.Dt IOCTL 2
+.Os
+.Sh NAME
+.Nm ioctl
+.Nd control device
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/ioctl.h
+.Ft int
+.Fn ioctl "int d" "unsigned long request" "..."
+.Sh DESCRIPTION
+The
+.Fn ioctl
+function manipulates the underlying device parameters of special files.
+In particular, many operating
+characteristics of character special files (e.g. terminals)
+may be controlled with
+.Fn ioctl
+requests.
+The argument
+.Fa d
+must be an open file descriptor.
+.Pp
+An
+.Fn ioctl
+.Fa request
+has encoded in it whether the argument is an
+.Dq in ,
+.Dq out ,
+or
+.Dq inout
+parameter, and the size of the first variadic argument
+in bytes.
+Note that there can be only one variadic argument but cannot be represented as
+a
+.Ft "void *"
+argument in the prototype because this would require a cast to pass integral
+types without warnings.
+Macros and defines used in specifying an
+.Fn ioctl
+.Fa request
+are located in the header
+.In sys/ioctl.h .
+.Sh GENERIC IOCTLS
+Some ioctls are applicable to any file descriptor.
+These include:
+.Bl -tag -width "xxxxxx"
+.It Dv FIOCLEX
+Set close-on-exec flag.
+The file will be closed when
+.Xr exec 3
+is invoked
+(This is equivalent to
+.Fn fcntl
+.Dv F_SETFD
+.Dv FD_CLOEXEC
+and the
+.Fn fcntl
+form should be preferred).
+.It Dv FIONCLEX
+Clear close-on-exec flag.
+The file will remain open across
+.Xr exec 3
+(This is equivalent to
+.Fn fcntl
+.Dv F_SETFD
+.Dv 0
+and the
+.Fn fcntl
+form should be preferred).
+.El
+.Pp
+Some generic ioctls are not implemented for all types of file
+descriptors.
+These include:
+.Bl -tag -width "xxxxxx"
+.It Dv FIONREAD "int"
+Get the number of bytes that are immediately available for reading.
+.It Dv FIONWRITE "int"
+Get the number of bytes in the descriptor's send queue.
+These bytes are data which has been written to the descriptor but
+which are being held by the kernel for further processing.
+The nature of the required processing depends on the underlying device.
+For tty devices, these bytes are typically queued for delivery
+to the tty hardware.
+For TCP sockets, these bytes have not yet been acknowledged by the
+other side of the connection.
+For files, this operation always returns zero as files do not have
+send queues.
+.It Dv FIONSPACE "int"
+Get the free space in the descriptor's send queue.
+This value is the size of the send queue minus the number of bytes
+being held in the queue.
+Note: while this value represents the number of bytes that may be
+added to the queue, other resource limitations may cause a write
+not larger than the send queue's space to be blocked.
+One such limitation would be a lack of network buffers for a write
+to a network connection.
+.It Dv FIONBIO "int"
+Set non-blocking I/O mode if the argument is non-zero.
+In non-blocking mode,
+.Xr read 2
+or
+.Xr write 2
+calls return
+.Dv \-1
+and set
+.Va errno
+to
+.Er EAGAIN
+immediately when no data is available
+(This is equivalent to
+.Fn fcntl
+.Dv F_SETFL
+.Dv O_NONBLOCK
+and the
+.Fn fcntl
+form should be preferred).
+.It Dv FIOASYNC "int"
+Set asynchronous I/O mode if the argument is non-zero
+(This is equivalent to
+.Fn fcntl
+.Dv F_SETFL
+.Dv O_ASYNC
+and the
+.Fn fcntl
+form should be preferred).
+In asynchronous mode, the process or process group specified by
+.Dv FIOSETOWN
+will start receiving
+.Dv SIGIO
+signals when data is available.
+The
+.Dv SIGIO
+signal will be delivered when data is available on the file
+descriptor.
+.It Dv FIOSETOWN, FIOGETOWN "int"
+Set/get the process or the process group (if negative) that should receive
+.Dv SIGIO
+signals when data is available
+(This is equivalent to
+.Fn fcntl
+.Dv F_SETOWN
+.Ft pid_t
+and the
+.Ft fcntl
+form should be preferred).
+.El
+.Sh RETURN VALUES
+If an error has occurred, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn ioctl
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa d
+is not a valid descriptor.
+.It Bq Er EFAULT
+.Fa argp
+points outside the process's allocated address space.
+.It Bq Er EINVAL
+.Fa request
+or
+.Fa argp
+is not valid.
+.It Bq Er ENOTTY
+.Fa d
+is not associated with a character
+special device; or
+the specified request does not apply to the kind
+of object that the descriptor
+.Fa d
+references.
+.El
+.Sh SEE ALSO
+.Xr mt 1 ,
+.Xr execve 2 ,
+.Xr fcntl 2 ,
+.Xr intro 4 ,
+.Xr tty 4
+.Sh HISTORY
+An
+.Fn ioctl
+function call appeared in
+.At v7 .
diff --git a/lib/nbsd_libc/sys/issetugid.2 b/lib/nbsd_libc/sys/issetugid.2
new file mode 100644 (file)
index 0000000..becbdcb
--- /dev/null
@@ -0,0 +1,101 @@
+.\"    $NetBSD: issetugid.2,v 1.11 2003/08/07 16:44:00 agc Exp $
+.\"    OpenBSD: issetugid.2,v 1.7 1997/02/18 00:16:09 deraadt Exp
+.\" FreeBSD: src/lib/libc/sys/issetugid.2,v 1.5.2.2 1999/09/18 16:18:59 phantom Exp
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\" FreeBSD: src/lib/libc/sys/issetugid.2,v 1.5.2.2 1999/09/18 16:18:59 phantom Exp
+.\"
+.Dd April 22, 2000
+.Dt ISSETUGID 2
+.Os
+.Sh NAME
+.Nm issetugid
+.Nd is current process tainted by uid or gid changes
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn issetugid void
+.Sh DESCRIPTION
+The
+.Fn issetugid
+function returns 1 if the process environment or memory address space
+is considered
+.Dq tainted ,
+and returns 0 otherwise.
+.Pp
+A process is tainted if it was created as a result of an
+.Xr execve 2
+system call which had either of the setuid or setgid bits set (and extra
+privileges were given as a result) or if it has changed any of its real,
+effective or saved user or group ID's since it began execution.
+.Pp
+This system call exists so that library routines (e.g., libc, libtermcap)
+can reliably determine if it is safe to use information
+that was obtained from the user, in particular the results from
+.Xr getenv 3
+should be viewed with suspicion if it is used to control operation.
+.Pp
+A
+.Dq tainted
+status is inherited by child processes as a result of the
+.Xr fork 2
+system call (or other library code that calls fork, such as
+.Xr popen 3 ) .
+.Pp
+It is assumed that a program that clears all privileges as it prepares
+to execute another will also reset the environment, hence the
+.Dq tainted
+status will not be passed on.
+This is important for programs such as
+.Xr su 1
+which begin setuid but need to be able to create an untainted process.
+.Sh ERRORS
+The
+.Fn issetugid
+function is always successful, and no return value is reserved to
+indicate an error.
+.Sh SEE ALSO
+.Xr execve 2 ,
+.Xr fork 2 ,
+.Xr setegid 2 ,
+.Xr seteuid 2 ,
+.Xr setgid 2 ,
+.Xr setregid 2 ,
+.Xr setreuid 2 ,
+.Xr setuid 2
+.Sh HISTORY
+A
+.Fn issetugid
+function call first appeared in
+.Ox 2.0
+and was also implemented in
+.Fx 3.0 .
+.Fx
+implementation was imported in
+.Nx 1.5 .
diff --git a/lib/nbsd_libc/sys/kill.2 b/lib/nbsd_libc/sys/kill.2
new file mode 100644 (file)
index 0000000..07d398f
--- /dev/null
@@ -0,0 +1,131 @@
+.\"    $NetBSD: kill.2,v 1.21 2008/07/13 15:16:26 dholland Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)kill.2     8.3 (Berkeley) 4/19/94
+.\"
+.Dd April 19, 1994
+.Dt KILL 2
+.Os
+.Sh NAME
+.Nm kill
+.Nd send signal to a process
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn kill "pid_t pid" "int sig"
+.Sh DESCRIPTION
+The
+.Fn kill
+function sends the signal given by
+.Fa sig
+to
+.Fa pid ,
+a
+process or a group of processes.
+.Fa sig
+may be one of the signals specified in
+.Xr sigaction 2
+or it may be 0, in which case
+error checking is performed but no
+signal is actually sent.
+This can be used to check the validity of
+.Fa pid .
+.Pp
+For a process to have permission to send a signal to a process designated
+by
+.Fa pid ,
+the real or effective user ID of the receiving process must match
+that of the sending process or the user must have appropriate privileges
+(such as given by a set-user-ID program or the user is the super-user).
+A single exception is the signal SIGCONT, which may always be sent
+to any descendant of the current process.
+.Bl -tag -width Ds
+.It \&If Fa pid No \&is greater than zero :
+.Fa sig
+is sent to the process whose ID is equal to
+.Fa pid .
+.It \&If Fa pid No \&is zero :
+.Fa sig
+is sent to all processes whose process group ID is equal
+to the process group ID of the sender, and for which the
+process has permission;
+this is a variant of
+.Xr killpg 3 .
+.It \&If Fa pid No \&is \-1 :
+If the user has super-user privileges,
+the signal is sent to all processes excluding
+system processes and the process sending the signal.
+If the user is not the super user, the signal is sent to all processes
+with the same uid as the user excluding the process sending the signal.
+No error is returned if any process could be signaled.
+.El
+.Pp
+For compatibility with System V,
+if the process number is negative but not \-1,
+the signal is sent to all processes whose process group ID
+is equal to the absolute value of the process number.
+This is a variant of
+.Xr killpg 3 .
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn kill
+will fail and no signal will be sent if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+.Fa sig
+is not a valid signal number.
+.It Bq Er ESRCH
+No process can be found corresponding to that specified by
+.Fa pid .
+.It Bq Er ESRCH
+The process id was given as 0
+but the sending process does not have a process group.
+.It Bq Er EPERM
+The sending process is not the super-user and its effective
+user id does not match the effective user-id of the receiving process.
+When signaling a process group, this error is returned if any members
+of the group could not be signaled.
+.El
+.Sh SEE ALSO
+.Xr getpgrp 2 ,
+.Xr getpid 2 ,
+.Xr sigaction 2 ,
+.Xr killpg 3 ,
+.Xr signal 7
+.Sh STANDARDS
+The
+.Fn kill
+function is expected to conform to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/sys/kqueue.2 b/lib/nbsd_libc/sys/kqueue.2
new file mode 100644 (file)
index 0000000..2a81ccd
--- /dev/null
@@ -0,0 +1,619 @@
+.\"    $NetBSD: kqueue.2,v 1.29 2010/04/13 10:45:46 wiz Exp $
+.\"
+.\" Copyright (c) 2000 Jonathan Lemon
+.\" All rights reserved.
+.\"
+.\" Copyright (c) 2001, 2002, 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" Portions of this documentation is derived from text contributed by
+.\" Luke Mewburn.
+.\"
+.\" 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 ``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.
+.\"
+.\" $FreeBSD: src/lib/libc/sys/kqueue.2,v 1.22 2001/06/27 19:55:57 dd Exp $
+.\"
+.Dd April 13, 2010
+.Dt KQUEUE 2
+.Os
+.Sh NAME
+.Nm kqueue ,
+.Nm kevent
+.Nd kernel event notification mechanism
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/event.h
+.In sys/time.h
+.Ft int
+.Fn kqueue "void"
+.Ft int
+.Fn kevent "int kq" "const struct kevent *changelist" "size_t nchanges" "struct kevent *eventlist" "size_t nevents" "const struct timespec *timeout"
+.Fn EV_SET "\*[Am]kev" ident filter flags fflags data udata
+.Sh DESCRIPTION
+.Fn kqueue
+provides a generic method of notifying the user when an event
+happens or a condition holds, based on the results of small
+pieces of kernel code termed filters.
+A kevent is identified by the (ident, filter) pair; there may only
+be one unique kevent per kqueue.
+.Pp
+The filter is executed upon the initial registration of a kevent
+in order to detect whether a preexisting condition is present, and is also
+executed whenever an event is passed to the filter for evaluation.
+If the filter determines that the condition should be reported,
+then the kevent is placed on the kqueue for the user to retrieve.
+.Pp
+The filter is also run when the user attempts to retrieve the kevent
+from the kqueue.
+If the filter indicates that the condition that triggered
+the event no longer holds, the kevent is removed from the kqueue and
+is not returned.
+.Pp
+Multiple events which trigger the filter do not result in multiple
+kevents being placed on the kqueue; instead, the filter will aggregate
+the events into a single struct kevent.
+Calling
+.Fn close
+on a file descriptor will remove any kevents that reference the descriptor.
+.Pp
+.Fn kqueue
+creates a new kernel event queue and returns a descriptor.
+The queue is not inherited by a child created with
+.Xr fork 2 .
+.\" However, if
+.\" .Xr rfork 2
+.\" is called without the
+.\" .Dv RFFDG
+.\" flag, then the descriptor table is shared,
+.\" which will allow sharing of the kqueue between two processes.
+.Pp
+.Fn kevent
+is used to register events with the queue, and return any pending
+events to the user.
+.Fa changelist
+is a pointer to an array of
+.Va kevent
+structures, as defined in
+.In sys/event.h .
+All changes contained in the
+.Fa changelist
+are applied before any pending events are read from the queue.
+.Fa nchanges
+gives the size of
+.Fa changelist .
+.Fa eventlist
+is a pointer to an array of kevent structures.
+.Fa nevents
+determines the size of
+.Fa eventlist .
+If
+.Fa timeout
+is a
+.No non- Ns Dv NULL
+pointer, it specifies a maximum interval to wait
+for an event, which will be interpreted as a struct timespec.
+If
+.Fa timeout
+is a
+.Dv NULL
+pointer,
+.Fn kevent
+waits indefinitely.
+To effect a poll, the
+.Fa timeout
+argument should be
+.No non- Ns Dv NULL ,
+pointing to a zero-valued
+.Va timespec
+structure.
+The same array may be used for the
+.Fa changelist
+and
+.Fa eventlist .
+.Pp
+.Fn EV_SET
+is a macro which is provided for ease of initializing a
+kevent structure.
+.Pp
+The
+.Va kevent
+structure is defined as:
+.Bd -literal
+struct kevent {
+       uintptr_t ident;        /* identifier for this event */
+       uint32_t  filter;       /* filter for event */
+       uint32_t  flags;        /* action flags for kqueue */
+       uint32_t  fflags;       /* filter flag value */
+       int64_t   data;         /* filter data value */
+       intptr_t  udata;        /* opaque user data identifier */
+};
+.Ed
+.Pp
+The fields of
+.Fa struct kevent
+are:
+.Bl -tag -width XXXfilter -offset indent
+.It ident
+Value used to identify this event.
+The exact interpretation is determined by the attached filter,
+but often is a file descriptor.
+.It filter
+Identifies the kernel filter used to process this event.
+There are pre-defined system filters (which are described below), and
+other filters may be added by kernel subsystems as necessary.
+.It flags
+Actions to perform on the event.
+.It fflags
+Filter-specific flags.
+.It data
+Filter-specific data value.
+.It udata
+Opaque user-defined value passed through the kernel unchanged.
+.El
+.Pp
+The
+.Va flags
+field can contain the following values:
+.Bl -tag -width XXXEV_ONESHOT -offset indent
+.It EV_ADD
+Adds the event to the kqueue.
+Re-adding an existing event will modify the parameters of the original
+event, and not result in a duplicate entry.
+Adding an event automatically enables it,
+unless overridden by the EV_DISABLE flag.
+.It EV_ENABLE
+Permit
+.Fn kevent
+to return the event if it is triggered.
+.It EV_DISABLE
+Disable the event so
+.Fn kevent
+will not return it.
+The filter itself is not disabled.
+.It EV_DELETE
+Removes the event from the kqueue.
+Events which are attached to file descriptors are automatically deleted
+on the last close of the descriptor.
+.It EV_ONESHOT
+Causes the event to return only the first occurrence of the filter
+being triggered.
+After the user retrieves the event from the kqueue, it is deleted.
+.It EV_CLEAR
+After the event is retrieved by the user, its state is reset.
+This is useful for filters which report state transitions
+instead of the current state.
+Note that some filters may automatically set this flag internally.
+.It EV_EOF
+Filters may set this flag to indicate filter-specific EOF condition.
+.It EV_ERROR
+See
+.Sx RETURN VALUES
+below.
+.El
+.Ss Filters
+Filters are identified by a number.
+There are two types of filters; pre-defined filters which
+are described below, and third-party filters that may be added with
+.Xr kfilter_register 9
+by kernel sub-systems, third-party device drivers, or loadable
+kernel modules.
+.Pp
+As a third-party filter is referenced by a well-known name instead
+of a statically assigned number, two
+.Xr ioctl 2 Ns s
+are supported on the file descriptor returned by
+.Fn kqueue
+to map a filter name to a filter number, and vice-versa (passing
+arguments in a structure described below):
+.Bl -tag -width KFILTER_BYFILTER -offset indent
+.It KFILTER_BYFILTER
+Map
+.Va filter
+to
+.Va name ,
+which is of size
+.Va len .
+.It KFILTER_BYNAME
+Map
+.Va name
+to
+.Va filter .
+.Va len
+is ignored.
+.El
+.Pp
+The following structure is used to pass arguments in and out of the
+.Xr ioctl 2 :
+.Bd -literal -offset indent
+struct kfilter_mapping {
+       char     *name;         /* name to lookup or return */
+       size_t   len;           /* length of name */
+       uint32_t filter;        /* filter to lookup or return */
+};
+.Ed
+.Pp
+Arguments may be passed to and from the filter via the
+.Va fflags
+and
+.Va data
+fields in the kevent structure.
+.Pp
+The predefined system filters are:
+.Bl -tag -width EVFILT_SIGNAL
+.It EVFILT_READ
+Takes a descriptor as the identifier, and returns whenever
+there is data available to read.
+The behavior of the filter is slightly different depending
+on the descriptor type.
+.Pp
+.Bl -tag -width 2n
+.It Sockets
+Sockets which have previously been passed to
+.Fn listen
+return when there is an incoming connection pending.
+.Va data
+contains the size of the listen backlog (i.e., the number of
+connections ready to be accepted with
+.Xr accept 2 . )
+.Pp
+Other socket descriptors return when there is data to be read,
+subject to the
+.Dv SO_RCVLOWAT
+value of the socket buffer.
+This may be overridden with a per-filter low water mark at the
+time the filter is added by setting the
+NOTE_LOWAT
+flag in
+.Va fflags ,
+and specifying the new low water mark in
+.Va data .
+On return,
+.Va data
+contains the number of bytes in the socket buffer.
+.Pp
+If the read direction of the socket has shutdown, then the filter
+also sets EV_EOF in
+.Va flags ,
+and returns the socket error (if any) in
+.Va fflags .
+It is possible for EOF to be returned (indicating the connection is gone)
+while there is still data pending in the socket buffer.
+.It Vnodes
+Returns when the file pointer is not at the end of file.
+.Va data
+contains the offset from current position to end of file,
+and may be negative.
+.It "Fifos, Pipes"
+Returns when there is data to read;
+.Va data
+contains the number of bytes available.
+.Pp
+When the last writer disconnects, the filter will set EV_EOF in
+.Va flags .
+This may be cleared by passing in EV_CLEAR, at which point the
+filter will resume waiting for data to become available before
+returning.
+.El
+.It EVFILT_WRITE
+Takes a descriptor as the identifier, and returns whenever
+it is possible to write to the descriptor.
+For sockets, pipes, fifos, and ttys,
+.Va data
+will contain the amount of space remaining in the write buffer.
+The filter will set EV_EOF when the reader disconnects, and for
+the fifo case, this may be cleared by use of EV_CLEAR.
+Note that this filter is not supported for vnodes.
+.Pp
+For sockets, the low water mark and socket error handling is
+identical to the EVFILT_READ case.
+.It EVFILT_AIO
+This is not implemented in
+.Nx .
+.ig
+The sigevent portion of the AIO request is filled in, with
+.Va sigev_notify_kqueue
+containing the descriptor of the kqueue that the event should
+be attached to,
+.Va sigev_value
+containing the udata value, and
+.Va sigev_notify
+set to SIGEV_EVENT.
+When the aio_* function is called, the event will be registered
+with the specified kqueue, and the
+.Va ident
+argument set to the
+.Fa struct aiocb
+returned by the aio_* function.
+The filter returns under the same conditions as aio_error.
+.Pp
+Alternatively, a kevent structure may be initialized, with
+.Va ident
+containing the descriptor of the kqueue, and the
+address of the kevent structure placed in the
+.Va aio_lio_opcode
+field of the AIO request.
+However, this approach will not work on
+architectures with 64-bit pointers, and should be considered deprecated.
+..
+.It EVFILT_VNODE
+Takes a file descriptor as the identifier and the events to watch for in
+.Va fflags ,
+and returns when one or more of the requested events occurs on the descriptor.
+The events to monitor are:
+.Bl -tag -width XXNOTE_RENAME
+.It NOTE_DELETE
+.Fn unlink
+was called on the file referenced by the descriptor.
+.It NOTE_WRITE
+A write occurred on the file referenced by the descriptor.
+.It NOTE_EXTEND
+The file referenced by the descriptor was extended.
+.It NOTE_ATTRIB
+The file referenced by the descriptor had its attributes changed.
+.It NOTE_LINK
+The link count on the file changed.
+.It NOTE_RENAME
+The file referenced by the descriptor was renamed.
+.It NOTE_REVOKE
+Access to the file was revoked via
+.Xr revoke 2
+or the underlying fileystem was unmounted.
+.El
+.Pp
+On return,
+.Va fflags
+contains the events which triggered the filter.
+.It EVFILT_PROC
+Takes the process ID to monitor as the identifier and the events to watch for
+in
+.Va fflags ,
+and returns when the process performs one or more of the requested events.
+If a process can normally see another process, it can attach an event to it.
+The events to monitor are:
+.Bl -tag -width XXNOTE_TRACKERR
+.It NOTE_EXIT
+The process has exited.
+.It NOTE_FORK
+The process has called
+.Fn fork .
+.It NOTE_EXEC
+The process has executed a new process via
+.Xr execve 2
+or similar call.
+.It NOTE_TRACK
+Follow a process across
+.Fn fork
+calls.
+The parent process will return with NOTE_TRACK set in the
+.Va fflags
+field, while the child process will return with NOTE_CHILD set in
+.Va fflags
+and the parent PID in
+.Va data .
+.It NOTE_TRACKERR
+This flag is returned if the system was unable to attach an event to
+the child process, usually due to resource limitations.
+.El
+.Pp
+On return,
+.Va fflags
+contains the events which triggered the filter.
+.It EVFILT_SIGNAL
+Takes the signal number to monitor as the identifier and returns
+when the given signal is delivered to the current process.
+This coexists with the
+.Fn signal
+and
+.Fn sigaction
+facilities, and has a lower precedence.
+The filter will record
+all attempts to deliver a signal to a process, even if the signal has
+been marked as SIG_IGN.
+Event notification happens after normal signal delivery processing.
+.Va data
+returns the number of times the signal has occurred since the last call to
+.Fn kevent .
+This filter automatically sets the EV_CLEAR flag internally.
+.It EVFILT_TIMER
+Establishes an arbitrary timer identified by
+.Va ident .
+When adding a timer,
+.Va data
+specifies the timeout period in milliseconds.
+The timer will be periodic unless EV_ONESHOT is specified.
+On return,
+.Va data
+contains the number of times the timeout has expired since the last call to
+.Fn kevent .
+This filter automatically sets the EV_CLEAR flag internally.
+.El
+.Sh RETURN VALUES
+.Fn kqueue
+creates a new kernel event queue and returns a file descriptor.
+If there was an error creating the kernel event queue, a value of \-1 is
+returned and errno set.
+.Pp
+.Fn kevent
+returns the number of events placed in the
+.Fa eventlist ,
+up to the value given by
+.Fa nevents .
+If an error occurs while processing an element of the
+.Fa changelist
+and there is enough room in the
+.Fa eventlist ,
+then the event will be placed in the
+.Fa eventlist
+with
+.Dv EV_ERROR
+set in
+.Va flags
+and the system error in
+.Va data .
+Otherwise,
+.Dv \-1
+will be returned, and
+.Dv errno
+will be set to indicate the error condition.
+If the time limit expires, then
+.Fn kevent
+returns 0.
+.Sh EXAMPLES
+The following example program monitors a file (provided to it as the first
+argument) and prints information about some common events it receives
+notifications for:
+.Bd -literal -offset indent
+#include \*[Lt]sys/types.h\*[Gt]
+#include \*[Lt]sys/event.h\*[Gt]
+#include \*[Lt]sys/time.h\*[Gt]
+#include \*[Lt]stdio.h\*[Gt]
+#include \*[Lt]unistd.h\*[Gt]
+#include \*[Lt]stdlib.h\*[Gt]
+#include \*[Lt]fcntl.h\*[Gt]
+#include \*[Lt]err.h\*[Gt]
+
+int
+main(int argc, char *argv[])
+{
+        int fd, kq, nev;
+        struct kevent ev;
+        static const struct timespec tout = { 1, 0 };
+
+        if ((fd = open(argv[1], O_RDONLY)) == -1)
+                err(1, "Cannot open `%s'", argv[1]);
+
+        if ((kq = kqueue()) == -1)
+                err(1, "Cannot create kqueue");
+
+        EV_SET(\*[Am]ev, fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR,
+            NOTE_DELETE|NOTE_WRITE|NOTE_EXTEND|NOTE_ATTRIB|NOTE_LINK|
+            NOTE_RENAME|NOTE_REVOKE, 0, 0);
+       if (kevent(kq, \*[Am]ch, 1, NULL, 0, \*[Am]tout) == -1)
+               err(1, "kevent");
+        for (;;) {
+                nev = kevent(kq, NULL, 0, \*[Am]ev, 1, \*[Am]tout);
+                if (nev == -1)
+                        err(1, "kevent");
+                if (nev == 0)
+                        continue;
+                if (ev.fflags \*[Am] NOTE_DELETE) {
+                        printf("deleted ");
+                        ev.fflags \*[Am]= ~NOTE_DELETE;
+                }
+                if (ev.fflags \*[Am] NOTE_WRITE) {
+                        printf("written ");
+                        ev.fflags \*[Am]= ~NOTE_WRITE;
+                }
+                if (ev.fflags \*[Am] NOTE_EXTEND) {
+                        printf("extended ");
+                        ev.fflags \*[Am]= ~NOTE_EXTEND;
+                }
+                if (ev.fflags \*[Am] NOTE_ATTRIB) {
+                        printf("chmod/chown/utimes ");
+                        ev.fflags \*[Am]= ~NOTE_ATTRIB;
+                }
+                if (ev.fflags \*[Am] NOTE_LINK) {
+                        printf("hardlinked ");
+                        ev.fflags \*[Am]= ~NOTE_LINK;
+                }
+                if (ev.fflags \*[Am] NOTE_RENAME) {
+                        printf("renamed ");
+                        ev.fflags \*[Am]= ~NOTE_RENAME;
+                }
+                if (ev.fflags \*[Am] NOTE_REVOKE) {
+                        printf("revoked ");
+                        ev.fflags \*[Am]= ~NOTE_REVOKE;
+                }
+                printf("\\n");
+                if (ev.fflags)
+                        warnx("unknown event 0x%x\\n", ev.fflags);
+        }
+}
+.Ed
+.Sh ERRORS
+The
+.Fn kqueue
+function fails if:
+.Bl -tag -width Er
+.It Bq Er EMFILE
+The per-process descriptor table is full.
+.It Bq Er ENFILE
+The system file table is full.
+.It Bq Er ENOMEM
+The kernel failed to allocate enough memory for the kernel queue.
+.El
+.Pp
+The
+.Fn kevent
+function fails if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+The process does not have permission to register a filter.
+.It Bq Er EBADF
+The specified descriptor is invalid.
+.It Bq Er EFAULT
+There was an error reading or writing the
+.Va kevent
+structure.
+.It Bq Er EINTR
+A signal was delivered before the timeout expired and before any
+events were placed on the kqueue for return.
+.It Bq Er EINVAL
+The specified time limit or filter is invalid.
+.It Bq Er ENOENT
+The event could not be found to be modified or deleted.
+.It Bq Er ENOMEM
+No memory was available to register the event.
+.It Bq Er ESRCH
+The specified process to attach to does not exist.
+.El
+.Sh SEE ALSO
+.\" .Xr aio_error 2 ,
+.\" .Xr aio_read 2 ,
+.\" .Xr aio_return 2 ,
+.Xr ioctl 2 ,
+.Xr poll 2 ,
+.Xr read 2 ,
+.Xr select 2 ,
+.Xr sigaction 2 ,
+.Xr write 2 ,
+.Xr signal 3 ,
+.Xr kfilter_register 9 ,
+.Xr knote 9
+.Rs
+.%A Jonathan Lemon
+.%T "Kqueue: A Generic and Scalable Event Notification Facility"
+.%I USENIX Association
+.%B Proceedings of the FREENIX Track: 2001 USENIX Annual Technical Conference
+.%D June 25-30, 2001
+.%U http://www.usenix.org/event/usenix01/freenix01/full_papers/lemon/lemon.pdf
+.Re
+.Sh HISTORY
+The
+.Fn kqueue
+and
+.Fn kevent
+functions first appeared in
+.Fx 4.1 ,
+and then in
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/sys/ktrace.2 b/lib/nbsd_libc/sys/ktrace.2
new file mode 100644 (file)
index 0000000..43cbd38
--- /dev/null
@@ -0,0 +1,173 @@
+.\"    $NetBSD: ktrace.2,v 1.17 2004/05/13 10:20:58 wiz Exp $
+.\"
+.\" Copyright (c) 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.
+.\" 3. 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.
+.\"
+.\"     @(#)ktrace.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt KTRACE 2
+.Os
+.Sh NAME
+.Nm ktrace
+.Nd process tracing
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/uio.h
+.In sys/ktrace.h
+.Ft int
+.Fn ktrace "const char *tracefile" "int ops" "int trpoints" "pid_t pid"
+.Ft int
+.Fn fktrace "int fd" "int ops" "int trpoints" "pid_t pid"
+.Sh DESCRIPTION
+The
+.Fn ktrace
+function enables or disables tracing of one or more processes.
+Users may only trace their own processes.
+Only the super-user can trace setuid or setgid programs.
+.Pp
+The
+.Ar tracefile
+gives the pathname of the file to be used for tracing.
+The file must exist and be writable by the calling process.
+All trace records are always appended to the file,
+so the file must be truncated to zero length to discard
+previous trace data.
+If tracing points are being disabled (see KTROP_CLEAR below),
+.Ar tracefile
+may be NULL.
+If using
+.Fn fktrace
+then instead of passing a filename as
+.Ar tracefile ,
+a file descriptor is passed as
+.Ar fd
+and behaviour is otherwise the same.
+.Pp
+The
+.Nm ops
+parameter specifies the requested ktrace operation.
+The defined operations are:
+.Bl -column KTRFLAG_DESCENDXXX -offset indent
+.It KTROP_SET  Enable trace points specified in Ar trpoints .
+.It KTROP_CLEAR        Disable trace points specified in Ar trpoints .
+.It KTROP_CLEARFILE    Stop all tracing.
+.It KTRFLAG_DESCEND    The tracing change should apply to the
+specified process and all its current children.
+.El
+.Pp
+The
+.Nm trpoints
+parameter specifies the trace points of interest.
+The defined trace points are:
+.Bl -column KTRFAC_SYSCALLXXX -offset indent
+.It KTRFAC_SYSCALL     Trace system calls.
+.It KTRFAC_SYSRET      Trace return values from system calls.
+.It KTRFAC_NAMEI       Trace name lookup operations.
+.It KTRFAC_GENIO       Trace all I/O (note that this option can
+generate much output).
+.It KTRFAC_PSIG        Trace posted signals.
+.It KTRFAC_CSW Trace context switch points.
+.It KTRFAC_EMUL        Trace emulation changes.
+.It KTRFAC_INHERIT     Inherit tracing to future children.
+.El
+.Pp
+Each tracing event outputs a record composed of a generic header
+followed by a trace point specific structure.
+The generic header is:
+.Bd -literal
+struct ktr_header {
+       int     ktr_len;                /* length of buf */
+       short   ktr_type;               /* trace record type */
+       pid_t   ktr_pid;                /* process id */
+       char    ktr_comm[MAXCOMLEN+1];  /* command name */
+       struct  timeval ktr_time;       /* timestamp */
+       caddr_t ktr_buf;
+};
+.Ed
+.Pp
+The
+.Nm ktr_len
+field specifies the length of the
+.Nm ktr_type
+data that follows this header.
+The
+.Nm ktr_pid
+and
+.Nm ktr_comm
+fields specify the process and command generating the record.
+The
+.Nm ktr_time
+field gives the time (with microsecond resolution)
+that the record was generated.
+The
+.Nm ktr_buf
+is an internal kernel pointer and is not useful.
+.Pp
+The generic header is followed by
+.Nm ktr_len
+bytes of a
+.Nm ktr_type
+record.
+The type specific records are defined in the
+.Pa \*[Lt]sys/ktrace.h\*[Gt]
+include file.
+.Sh RETURN VALUES
+On successful completion a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to show the error.
+.Sh ERRORS
+.Fn ktrace
+will fail if:
+.Bl -tag -width ENAMETOOLONGAA
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er EINVAL
+The pathname contains a character with the high-order bit set.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded 255 characters,
+or an entire path name exceeded 1023 characters.
+.It Bq Er ENOENT
+The named tracefile does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.El
+.Sh SEE ALSO
+.Xr kdump 1 ,
+.Xr ktrace 1
+.Sh HISTORY
+A
+.Nm ktrace
+function call first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/sys/lfs_bmapv.2 b/lib/nbsd_libc/sys/lfs_bmapv.2
new file mode 100644 (file)
index 0000000..70bfdd3
--- /dev/null
@@ -0,0 +1,105 @@
+.\"    $NetBSD: lfs_bmapv.2,v 1.10 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2000 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Konrad Schroder.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 23, 2000
+.Dt LFS_BMAPV 2
+.Os
+.Sh NAME
+.Nm lfs_bmapv
+.Nd retrieve disk addresses for arrays of blocks
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In ufs/lfs/lfs.h
+.Ft int
+.Fn lfs_bmapv "fsid_t *fsidp" "BLOCK_INFO *blkiov" "int blkcnt"
+.Sh DESCRIPTION
+.Fn lfs_bmapv
+fills in the bi_daddr field for every block listed in the block array
+.Fa blkiov
+with the disk address corresponding to the logical block
+.Fa bi_lbn
+of the file with inode
+.Fa bi_inode .
+If
+.Fa bi_lbn
+is LFS_UNUSED_LBN, the disk location of the inode block containing the
+file's inode will be returned in
+.Fa bi_daddr
+instead.
+.Pp
+The
+.Fa fsidp
+argument contains the id of the file system to which the inodes and
+blocks belong.
+The
+.Fa blkiov
+argument is an array of BLOCK_INFO structures (see below).
+The
+.Fa blkcnt
+argument determines the size of the
+.Fa blkiov
+array.
+.Bd -literal
+typedef struct block_info {
+    ino_t       bi_inode;     /* inode # */
+    ufs_daddr_t bi_lbn;       /* logical block w/in file */
+    ufs_daddr_t bi_daddr;     /* disk address of block */
+    time_t      bi_segcreate; /* origin segment create time */
+    int         bi_version;   /* file version number */
+    void       *bi_bp;        /* data buffer */
+    int         bi_size;      /* size of the block (if fragment) */
+} BLOCK_INFO;
+.Ed
+.Sh RETURN VALUES
+.Fn lfs_bmapv
+returns 0 on success, or \-1 on error.
+.Sh ERRORS
+An error return from
+.Fn lfs_bmapv
+indicates:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+.Fa fsidp
+points outside the process's allocated address space.
+.It Bq Er EINVAL
+.Fa *fsidp
+does not specify a valid file system.
+.El
+.Sh SEE ALSO
+.Xr lfs_markv 2 ,
+.Xr lfs_segclean 2 ,
+.Xr lfs_segwait 2 ,
+.Xr lfs_cleanerd 8
+.Sh HISTORY
+The
+.Fn lfs_bmapv
+function call appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/sys/lfs_markv.2 b/lib/nbsd_libc/sys/lfs_markv.2
new file mode 100644 (file)
index 0000000..24854a8
--- /dev/null
@@ -0,0 +1,129 @@
+.\"    $NetBSD: lfs_markv.2,v 1.11 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2000 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Konrad Schroder.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 23, 2000
+.Dt LFS_MARKV 2
+.Os
+.Sh NAME
+.Nm lfs_markv
+.Nd rewrite disk blocks to new disk locations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In ufs/lfs/lfs.h
+.Ft int
+.Fn lfs_markv "fsid_t *fsidp" "BLOCK_INFO *blkiov" "int blkcnt"
+.Sh DESCRIPTION
+.Fn lfs_markv
+rewrites the blocks specified in
+.Fa blkiov
+to new disk locations, for the purposes of grouping them next to one
+another, or to move them out of a segment to clean it.
+All fields of the BLOCK_INFO structure must be filled in, except for
+.Fa bi_segcreate .
+If
+.Fa bi_daddr
+is not the correct current address for logical block
+.Fa bi_lbn
+of the file with inode number
+.Fa bi_inode ,
+or if the file's version number does not match
+.Fa bi_version ,
+the block will not be written to disk, but no error will be returned.
+.Pp
+The
+.Fa fsidp
+argument contains the id of the filesystem to which the inodes and
+blocks belong.
+The
+.Fa bi_bp
+field contains
+.Fa bi_size
+bytes of data to be written into the appropriate block.
+If
+.Fa bi_lbn
+is specified as LFS_UNUSED_LBN, the inode itself will be rewritten.
+.Pp
+The
+.Fa blkiov
+argument is an array of BLOCK_INFO structures (see below).
+The
+.Fa blkcnt
+argument determines the size of the
+.Fa blkiov
+array.
+.Bd -literal
+typedef struct block_info {
+    ino_t       bi_inode;     /* inode # */
+    ufs_daddr_t bi_lbn;       /* logical block w/in file */
+    ufs_daddr_t bi_daddr;     /* disk address of block */
+    time_t      bi_segcreate; /* origin segment create time */
+    int         bi_version;   /* file version number */
+    void       *bi_bp;        /* data buffer */
+    int         bi_size;      /* size of the block (if fragment) */
+} BLOCK_INFO;
+.Ed
+.Sh RETURN VALUES
+.Fn lfs_markv
+returns 0 on success, or \-1 on error.
+.Sh ERRORS
+An error return from
+.Fn lfs_markv
+indicates:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+.Fa fsidp
+points outside the process's allocated address space.
+.It Bq Er EINVAL
+.Fa *fsidp
+does not specify a valid filesystem.
+.It Bq Er EBUSY
+One or more of the inodes whose blocks were to be written was locked,
+and its blocks were not rewritten.
+.El
+.Sh SEE ALSO
+.Xr lfs_segclean 2 ,
+.Xr lfs_segwait 2 ,
+.Xr lfs_cleanerd 8
+.Sh HISTORY
+The
+.Fn lfs_markv
+function call appeared in
+.Bx 4.4 .
+.Sh BUGS
+The functionality of
+.Fn lfs_markv
+does not really belong in user space.
+Among other things it could be used to work around the
+SF_IMMUTABLE
+and
+SF_APPEND
+file flags (see
+.Xr chflags 2 ) .
diff --git a/lib/nbsd_libc/sys/lfs_segclean.2 b/lib/nbsd_libc/sys/lfs_segclean.2
new file mode 100644 (file)
index 0000000..4864c2e
--- /dev/null
@@ -0,0 +1,76 @@
+.\"    $NetBSD: lfs_segclean.2,v 1.8 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2000 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Konrad Schroder.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 23, 2000
+.Dt LFS_SEGCLEAN 2
+.Os
+.Sh NAME
+.Nm lfs_segclean
+.Nd mark a segment clean
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.Ft int
+.Fn lfs_segclean "fsid_t *fsidp" "u_long segment"
+.Sh DESCRIPTION
+.Fn lfs_segclean
+marks segment number
+.Fa segment
+in LFS filesystem
+.Fa *fsidp
+"clean" or available for writing.
+.Sh RETURN VALUES
+.Fn lfs_segclean
+returns 0 on success, or \-1 on error.
+.Sh ERRORS
+An error return from
+.Fn lfs_segclean
+indicates:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+.Fa fsidp
+points outside the process's allocated address space.
+.It Bq Er EINVAL
+.Fa *fsidp
+does not specify a valid filesystem.
+.It Bq Er EBUSY
+.Fa segment
+is marked SU_ACTIVE, meaning that it does not yet belong to a valid checkpoint.
+.El
+.Sh SEE ALSO
+.Xr lfs_bmapv 2 ,
+.Xr lfs_markv 2 ,
+.Xr lfs_segwait 2 ,
+.Xr lfs_cleanerd 8
+.Sh HISTORY
+The
+.Fn lfs_segclean
+function call appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/sys/lfs_segwait.2 b/lib/nbsd_libc/sys/lfs_segwait.2
new file mode 100644 (file)
index 0000000..e476d12
--- /dev/null
@@ -0,0 +1,85 @@
+.\"    $NetBSD: lfs_segwait.2,v 1.8 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2000 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Konrad Schroder.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 23, 2000
+.Dt LFS_SEGWAIT 2
+.Os
+.Sh NAME
+.Nm lfs_segwait
+.Nd wait until a segment is written
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.Ft int
+.Fn lfs_segwait "fsid_t *fsidp" "struct timeval *tv"
+.Sh DESCRIPTION
+.Fn lfs_segwait
+blocks until a new segment is acquired for writing by the filesystem
+specified by
+.Fa *fsidp
+or if
+.Fa *fsidp
+is \-1, until a segment is acquired for writing by any LFS filesystem.
+.Pp
+If
+.Fa timeout
+is non-zero,
+.Fn lfs_segwait
+will return after
+.Fa timeout
+milliseconds regardless of whether a new segment has been designated for
+writing or not.
+.Sh RETURN VALUES
+.Fn lfs_segwait
+returns 0 if a new segment was acquired; 1 if it timed out; or \-1 on error.
+.Sh ERRORS
+An error return from
+.Fn lfs_segwait
+indicates:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+.Fa fsidp
+points outside the process's allocated address space.
+.It Bq Er EINTR
+A signal was delivered before the time limit expired and
+before a new segment was designated for writing.
+.It Bq Er EINVAL
+The specified time limit is negative.
+.El
+.Sh SEE ALSO
+.Xr lfs_bmapv 2 ,
+.Xr lfs_markv 2 ,
+.Xr lfs_segclean 2 ,
+.Xr lfs_cleanerd 8
+.Sh HISTORY
+The
+.Fn lfs_segwait
+function call appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/sys/link.2 b/lib/nbsd_libc/sys/link.2
new file mode 100644 (file)
index 0000000..7887dfa
--- /dev/null
@@ -0,0 +1,162 @@
+.\"    $NetBSD: link.2,v 1.24 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)link.2     8.3 (Berkeley) 1/12/94
+.\"
+.Dd January 12, 1994
+.Dt LINK 2
+.Os
+.Sh NAME
+.Nm link
+.Nd make a hard file link
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn link "const char *name1" "const char *name2"
+.Sh DESCRIPTION
+The
+.Fn link
+function call
+atomically creates the specified directory entry (hard link)
+.Fa name2
+with the attributes of the underlying object pointed at by
+.Fa name1 .
+If the link is successful: the link count of the underlying object
+is incremented;
+.Fa name1
+and
+.Fa name2
+share equal access and rights
+to the
+underlying object.
+.Pp
+If
+.Fa name1
+is removed, the file
+.Fa name2
+is not deleted and the link count of the
+underlying object is
+decremented.
+.Pp
+.Fa name1
+must exist for the hard link to
+succeed and
+both
+.Fa name1
+and
+.Fa name2
+must be in the same file system.
+.Fa name1
+may not be a directory unless the caller is the super-user
+and the file system containing it supports linking to directories.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn link
+will fail and no link will be created if:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of either path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+A component of either path prefix does not exist.
+.It Bq Er EACCES
+A component of either path prefix denies search permission, or
+the requested link requires writing in a directory with a mode
+that denies write permission.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating one of the pathnames.
+.It Bq Er ENOENT
+The file named by
+.Fa name1
+does not exist.
+.It Bq Er EOPNOTSUPP
+The file system containing the file named by
+.Fa name1
+does not support links.
+.It Bq Er EMLINK
+The link count of the file named by
+.Fa name1
+would exceed
+.Dv {LINK_MAX} .
+.It Bq Er EEXIST
+The link named by
+.Fa name2
+does exist.
+.It Bq Er EPERM
+The file named by
+.Fa name1
+is a directory and the effective
+user ID is not super-user,
+or the file system containing the file does not permit the use of
+.Fn link
+on a directory.
+.It Bq Er EXDEV
+The link named by
+.Fa name2
+and the file named by
+.Fa name1
+are on different file systems.
+.It Bq Er ENOSPC
+The directory in which the entry for the new link is being placed
+cannot be extended because there is no space left on the file
+system containing the directory.
+.It Bq Er EDQUOT
+The directory in which the entry for the new link
+is being placed cannot be extended because the
+user's quota of disk blocks on the file system
+containing the directory has been exhausted.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to
+the file system to make the directory entry.
+.It Bq Er EROFS
+The requested link requires writing in a directory on a read-only file
+system.
+.It Bq Er EFAULT
+One of the pathnames specified
+is outside the process's allocated address space.
+.El
+.Sh SEE ALSO
+.Xr symlink 2 ,
+.Xr unlink 2
+.Sh STANDARDS
+The
+.Fn link
+function conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/sys/listen.2 b/lib/nbsd_libc/sys/listen.2
new file mode 100644 (file)
index 0000000..3fe0ea6
--- /dev/null
@@ -0,0 +1,101 @@
+.\"    $NetBSD: listen.2,v 1.16 2004/05/13 10:20:58 wiz Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)listen.2   8.2 (Berkeley) 12/11/93
+.\"
+.Dd December 11, 1993
+.Dt LISTEN 2
+.Os
+.Sh NAME
+.Nm listen
+.Nd listen for connections on a socket
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft int
+.Fn listen "int s" "int backlog"
+.Sh DESCRIPTION
+To accept connections, a socket
+is first created with
+.Xr socket 2 ,
+a willingness to accept incoming connections and
+a queue limit for incoming connections are specified with
+.Fn listen ,
+and then the connections are
+accepted with
+.Xr accept 2 .
+The
+.Fn listen
+call applies only to sockets of type
+.Dv SOCK_STREAM
+or
+.Dv SOCK_SEQPACKET .
+.Pp
+The
+.Fa backlog
+parameter defines the maximum length the queue of
+pending connections may grow to.
+If a connection
+request arrives with the queue full the client may
+receive an error with an indication of
+.Er ECONNREFUSED ,
+or, if the underlying protocol supports retransmission,
+the request may be ignored so that retries may succeed.
+.Sh RETURN VALUES
+A 0 return value indicates success; \-1 indicates an error.
+.Sh ERRORS
+.Fn listen
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The argument
+.Fa s
+is not a valid descriptor.
+.It Bq Er ENOTSOCK
+The argument
+.Fa s
+is not a socket.
+.It Bq Er EOPNOTSUPP
+The socket is not of a type that supports the operation
+.Fn listen .
+.El
+.Sh SEE ALSO
+.Xr accept 2 ,
+.Xr connect 2 ,
+.Xr socket 2
+.Sh HISTORY
+The
+.Fn listen
+function call appeared in
+.Bx 4.2 .
+.Sh BUGS
+The
+.Fa backlog
+is currently limited (silently) to 128.
diff --git a/lib/nbsd_libc/sys/lseek.2 b/lib/nbsd_libc/sys/lseek.2
new file mode 100644 (file)
index 0000000..bb58666
--- /dev/null
@@ -0,0 +1,148 @@
+.\"    $NetBSD: lseek.2,v 1.24 2010/04/05 07:53:47 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)lseek.2    8.3 (Berkeley) 4/19/94
+.\"
+.Dd April 3, 2010
+.Dt LSEEK 2
+.Os
+.Sh NAME
+.Nm lseek ,
+.Nm seek
+.Nd reposition read/write file offset
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft off_t
+.Fn lseek "int fildes" "off_t offset" "int whence"
+.Sh DESCRIPTION
+The
+.Fn lseek
+function repositions the offset of the file descriptor
+.Fa fildes
+to the
+argument
+.Fa offset
+according to the directive
+.Fa whence .
+The argument
+.Fa fildes
+must be an open
+file descriptor.
+.Fn lseek
+repositions the file pointer
+.Fa fildes
+as follows:
+.Bl -item -offset indent
+.It
+If
+.Fa whence
+is
+.Dv SEEK_SET ,
+the offset is set to
+.Fa offset
+bytes.
+.It
+If
+.Fa whence
+is
+.Dv SEEK_CUR ,
+the offset is set to its current location plus
+.Fa offset
+bytes.
+.It
+If
+.Fa whence
+is
+.Dv SEEK_END ,
+the offset is set to the size of the
+file plus
+.Fa offset
+bytes.
+.El
+.Pp
+The
+.Fn lseek
+function allows the file offset to be set beyond the end
+of the existing end-of-file of the file.
+If data is later written
+at this point, subsequent reads of the data in the gap return
+bytes of zeros (until data is actually written into the gap).
+.Pp
+Some devices are incapable of seeking.
+The value of the pointer associated with such a device is undefined.
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn lseek
+returns the resulting offset location as measured in bytes from the
+beginning of the file.
+Otherwise,
+a value of \-1 is returned and
+.Va errno
+is set to indicate
+the error.
+.Sh ERRORS
+.Fn lseek
+will fail and the file pointer will remain unchanged if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa fildes
+is not an open file descriptor.
+.It Bq Er EINVAL
+.Fa whence
+is not a proper value, or the resulting file offset would be invalid.
+.It Bq Er ESPIPE
+.Fa fildes
+is associated with a pipe, socket, or FIFO.
+.El
+.Sh SEE ALSO
+.Xr dup 2 ,
+.Xr open 2
+.Sh STANDARDS
+The
+.Fn lseek
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+A
+.Fn seek
+function appeared in
+.At v2 ,
+later renamed into
+.Fn lseek
+for
+.Dq long seek
+due to a larger
+.Fa offset
+argument type.
+.Sh BUGS
+This document's use of
+.Fa whence
+is incorrect English, but is maintained for historical reasons.
diff --git a/lib/nbsd_libc/sys/lseek.c b/lib/nbsd_libc/sys/lseek.c
new file mode 100644 (file)
index 0000000..96d4dc3
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: lseek.c,v 1.10 2007/11/23 12:39:15 uebayasi Exp $      */
+
+/*
+ * Copyright (c) 1992, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)lseek.c    8.1 (Berkeley) 6/17/93";
+#else
+__RCSID("$NetBSD: lseek.c,v 1.10 2007/11/23 12:39:15 uebayasi Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(lseek,_lseek)
+#endif
+
+off_t __lseek(int, int, off_t, int);
+
+/*
+ * This function provides 64-bit offset padding that
+ * is not supplied by GCC 1.X but is supplied by GCC 2.X.
+ */
+off_t
+lseek(fd, offset, whence)
+       int     fd;
+       off_t   offset;
+       int     whence;
+{
+
+       return __lseek(fd, 0, offset, whence);
+}
diff --git a/lib/nbsd_libc/sys/madvise.2 b/lib/nbsd_libc/sys/madvise.2
new file mode 100644 (file)
index 0000000..2744bc6
--- /dev/null
@@ -0,0 +1,133 @@
+.\"    $NetBSD: madvise.2,v 1.26 2009/06/03 09:04:18 wiz Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)madvise.2   8.1 (Berkeley) 6/9/93
+.\"
+.Dd June 2, 2009
+.Dt MADVISE 2
+.Os
+.Sh NAME
+.Nm madvise
+.Nd give advice about use of memory
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/mman.h
+.Ft int
+.Fn madvise "void *addr" "size_t len" "int behav"
+.Ft int
+.Fn posix_madvise "void *addr" "size_t len" "int advice"
+.Sh DESCRIPTION
+The
+.Fn madvise
+system call
+allows a process that has knowledge of its memory behavior
+to describe it to the system.
+The
+.Fn posix_madvise
+interface is identical and is provided for standards conformance.
+.Pp
+The known behaviors are:
+.Bl -tag -width MADV_NORMAL
+.It Dv MADV_NORMAL
+Tells the system to revert to the default paging
+behavior.
+.It Dv MADV_RANDOM
+Is a hint that pages will be accessed randomly, and prefetching
+is likely not advantageous.
+.It Dv MADV_SEQUENTIAL
+Is a hint that pages will be accessed sequentially, from the lower address to
+higher address.
+It might cause the VM system to depress the priority of
+pages immediately preceding a given page when it is faulted in.
+.It Dv MADV_WILLNEED
+Is a hint that pages will be accessed in the near future.
+It might cause the VM system to make pages that are in a given virtual
+address range to temporarily have higher priority, and if they are in
+memory, decrease the likelihood of them being freed.
+It might immediately map the pages that are already in memory into the
+process, thereby eliminating unnecessary overhead of going through
+the entire process of faulting the pages in.
+It might or might not fault pages in from backing store.
+.It Dv MADV_DONTNEED
+Is a hint that pages will not be accessed in the near future.
+It might allow the VM system to decrease the in-memory priority
+of pages in the specified range.
+.It Dv MADV_FREE
+Gives the VM system the freedom to free pages,
+and tells the system that information in the specified page range
+is no longer important.
+.El
+.Pp
+Portable programs that call the
+.Fn posix_madvise
+interface should use the aliases
+.Dv POSIX_MADV_NORMAL , POSIX_MADV_SEQUENTIAL ,
+.Dv POSIX_MADV_RANDOM , POSIX_MADV_WILLNEED ,
+and
+.Dv POSIX_MADV_DONTNEED
+rather than the flags described above.
+.Sh RETURN VALUES
+Upon successful completion,
+a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn madvise
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+Invalid parameters were provided.
+.El
+.Sh SEE ALSO
+.Xr mincore 2 ,
+.Xr mprotect 2 ,
+.Xr msync 2 ,
+.Xr munmap 2 ,
+.Xr posix_fadvise 2
+.Sh STANDARDS
+The
+.Fn posix_madvise
+system call is expected to conform to the
+.St -p1003.1-2001
+standard.
+.Sh HISTORY
+The
+.Nm madvise
+system call first appeared in
+.Bx 4.4 ,
+but until
+.Nx 1.5
+it did not perform any of the requests on, or change any behavior of the
+address range given.
+The
+.Fn posix_madvise
+was invented in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/sys/makelintstub b/lib/nbsd_libc/sys/makelintstub
new file mode 100755 (executable)
index 0000000..e073881
--- /dev/null
@@ -0,0 +1,242 @@
+#!/bin/sh -
+# $NetBSD: makelintstub,v 1.23 2008/08/05 02:08:13 lukem Exp $
+#
+# Copyright (c) 1996, 1997 Christopher G. Demetriou
+# 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.
+# 3. All advertising materials mentioning features or use of this software
+#    must display the following acknowledgement:
+#          This product includes software developed for the
+#          NetBSD Project.  See http://www.NetBSD.org/ for
+#          information about NetBSD.
+# 4. 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 ``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 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.
+# 
+# <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
+
+usage()
+{
+
+cat << _EOF 1>&2
+Usage: $PROG [-n|-p] [-o filename] [-s syscall.h] object ...
+       -n              Create SYSCALL_NOERROR.
+       -p              Create PSEUDO_NOERROR.
+                       (also removes leading "_" on syscall name).
+       -o filename     Output to filename.
+       -s syscall.h    Header to #include instead of <sys/syscall.h>.
+
+       The CPP environment variable must be set
+       to the path to the C preprocessor.
+_EOF
+       exit 1
+}
+
+header()
+{
+
+       cat <<- __EOF__
+       /*
+        * THIS IS AN AUTOMATICALLY GENERATED FILE.  DO NOT EDIT.
+        */
+
+       #include <sys/param.h>
+       #include <sys/aio.h>
+       #include <sys/time.h>
+       #include <sys/mount.h>
+       #include <sys/stat.h>
+       #include <ufs/ufs/dinode.h>
+       #include <ufs/lfs/lfs.h>
+       #include <sys/resource.h>
+       #include <sys/poll.h>
+       #include <sys/uio.h>
+       #include <sys/ipc.h>
+       #include <sys/lwpctl.h>
+       #include <sys/mqueue.h>
+       #include <sys/msg.h>
+       #include <sys/sem.h>
+       #include <sys/shm.h>
+       #include <sys/sched.h>
+       #include <sys/timex.h>
+       #include <sys/socket.h>
+       #include <sys/event.h>
+       #include <sys/uuid.h>
+       #ifdef __STDC__
+       #include <stdarg.h>
+       #else
+       #include <varargs.h>
+       #endif
+
+       __EOF__
+}
+
+syscall_stub()
+{
+
+       syscalldump="$1"
+       syscallname="$2"
+       funcname="$3"
+
+       arglist="$(
+       sed -e 'ta
+               :a
+               s,^/\* syscall: \"'"$syscallname"'\" ,,
+               tb
+               d
+               :b
+               s, \*/$,,' $syscalldump
+       )"
+
+       eval set -f -- "$arglist"
+
+       if [ $# -lt 3 ]; then
+               echo syscall $syscallname not found! 1>&2
+               exit 1
+       fi
+
+       shift                   # kill "ret:"
+       returntype=$1; shift
+       shift                   # kill "args:"
+
+       cat <<- __EOF__
+       /*ARGSUSED*/
+       $returntype
+       __EOF__
+
+       # do ANSI C function header
+       echo    "#ifdef __STDC__"
+
+       echo "$funcname("
+       first=true; i=1
+       for arg; do
+               if $first; then
+                       first=false
+               else
+                       echo ", "
+               fi
+               case "$arg" in
+               "...") echo "...";;
+               *) echo "$arg arg$i"; i=$(($i + 1));;
+               esac
+       done
+       if $first; then
+               echo "void"
+       fi
+       echo    ")"
+
+       # do K&R C function header
+       echo    "#else"
+
+       echo "$funcname("
+       first=true; i=1
+       for arg; do
+               if $first; then
+                       first=false
+               else
+                       echo ", "
+               fi
+               case "$arg" in
+               "...") echo "va_alist";;
+               *) echo "arg$i"; i=$(($i + 1));;
+               esac
+       done
+       echo    ")"
+       i=1
+       for arg; do
+               case "$arg" in
+               "...") echo "   va_dcl";;
+               *) echo "       $arg arg$i;"; i=$(($i + 1));;
+               esac
+       done
+
+       # do function body
+       echo    "#endif"
+
+       echo    "{"
+       if [ "$returntype" != "void" ]; then
+               echo "        return (($returntype)0);"
+       fi
+       echo    "}"
+}
+
+trailer()
+{
+
+       cat <<- __EOF__
+       /* END */
+       __EOF__
+}
+
+
+pflag=false
+nflag=false
+oarg=""
+syscallhdr=/usr/include/sys/syscall.h
+syscalldump=/tmp/makelintstub.$$
+PROG="$(basename "$0")"
+
+if [ -z "${CPP}" ]; then
+       usage
+fi
+
+while getopts no:ps: i
+do
+       case "$i" in
+       n)      nflag=true;;
+       o)      oarg=$OPTARG;;
+       p)      pflag=true;;
+       s)      syscallhdr=$OPTARG;;
+       *)      usage;;
+       esac
+done
+
+shift $(expr $OPTIND - 1)
+
+if $pflag && $nflag
+then
+       echo "$PROG: -n flag and -p flag may not be used together" 1>&2
+       usage
+fi
+
+if [ -n "$oarg" ]; then
+       exec > $oarg
+fi
+
+trap "rm -f $syscalldump" 0 1 2 3 15
+
+header
+
+echo "#include \"$syscallhdr\"" | ${CPP} -D_LIBC -C > $syscalldump
+
+for syscall; do
+       fnname=${syscall%.S}
+       if $pflag; then
+               scname=${fnname#_}
+       else
+               scname=$fnname
+       fi
+       syscall_stub $syscalldump $scname $fnname
+       echo ""
+done
+
+trailer
+
+exit 0
diff --git a/lib/nbsd_libc/sys/mincore.2 b/lib/nbsd_libc/sys/mincore.2
new file mode 100644 (file)
index 0000000..8d252af
--- /dev/null
@@ -0,0 +1,99 @@
+.\"    $NetBSD: mincore.2,v 1.19 2004/05/13 10:20:58 wiz Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)mincore.2   8.1 (Berkeley) 6/9/93
+.\"
+.Dd June 6, 1999
+.Dt MINCORE 2
+.Os
+.Sh NAME
+.Nm mincore
+.Nd determine residency of memory pages
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/mman.h
+.Ft int
+.Fn mincore "void *addr" "size_t len" "char *vec"
+.Sh DESCRIPTION
+The
+.Fn mincore
+system call
+allows a process to obtain information about whether pages are
+core resident.
+The status of the memory range is returned in the character-per-page array
+.Ar vec .
+If the page is resident, the least significant bit of the corresponding
+character in
+.Ar vec
+will be set.
+Other bits are reserved for additional information
+which future implementations may return.
+.Pp
+Note that the status of each page may change between the call to
+.Fn mincore
+and the return of the page status information.
+In order to guarantee
+that pages will remain in core, the address range must be locked with
+.Xr mlock 2 .
+.Sh RETURN VALUES
+.Fn mincore
+returns 0 on success, or \-1 on failure and sets the variable
+.Va errno
+to indicate the error.
+.Sh ERRORS
+The
+.Fn mincore
+call will fail if:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+.Ar vec
+points to an illegal address.
+.It Bq Er EINVAL
+.Ar addr
+is not a multiple of the system page size.
+.It Bq Er EINVAL
+.Ar len
+is equal to 0.
+.It Bq Er ENOMEM
+The address range specified is invalid for the calling process,
+or one or more of the pages specified in the range are not mapped.
+.El
+.Sh SEE ALSO
+.Xr madvise 2 ,
+.Xr mlock 2 ,
+.Xr mprotect 2 ,
+.Xr msync 2 ,
+.Xr munmap 2 ,
+.Xr sysconf 3
+.Sh HISTORY
+The
+.Fn mincore
+function first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/sys/minherit.2 b/lib/nbsd_libc/sys/minherit.2
new file mode 100644 (file)
index 0000000..9472448
--- /dev/null
@@ -0,0 +1,99 @@
+.\"    $NetBSD: minherit.2,v 1.18 2006/10/13 20:52:57 wiz Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)minherit.2  8.1 (Berkeley) 6/9/93
+.\"
+.Dd October 7, 2006
+.Dt MINHERIT 2
+.Os
+.Sh NAME
+.Nm minherit
+.Nd control the inheritance of pages
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/mman.h
+.Ft int
+.Fn minherit "void *addr" "size_t len" "int inherit"
+.Sh DESCRIPTION
+The
+.Fn minherit
+system call
+changes the specified range of virtual addresses to have the specified
+fork-time inheritance characteristic
+.Fa inherit ,
+which can be set to
+.Dv MAP_INHERIT_NONE ,
+.Dv MAP_INHERIT_COPY ,
+or
+.Dv MAP_INHERIT_SHARE .
+Also possible is
+.Dv MAP_INHERIT_DEFAULT ,
+which defaults to
+.Dv MAP_INHERIT_COPY .
+Not all implementations will guarantee that the inheritance characteristic
+can be set on a page basis;
+the granularity of changes may be as large as an entire region.
+.Pp
+Normally, the entire address space is marked
+.Dv MAP_INHERIT_COPY ;
+when the process calls
+.Fn fork ,
+the child receives a (virtual) copy of the entire address space.
+Pages or regions marked
+.Dv MAP_INHERIT_SHARE
+are shared between the address spaces, while pages or regions marked
+.Dv MAP_INHERIT_NONE
+will be unmapped in the child.
+.Sh RETURN VALUES
+.Rv -std minherit
+.Sh ERRORS
+.Fn minherit
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+An invalid region or invalid parameters were specified.
+.El
+.Sh SEE ALSO
+.Xr fork 2 ,
+.Xr madvise 2 ,
+.Xr mincore 2 ,
+.Xr mprotect 2 ,
+.Xr msync 2 ,
+.Xr munmap 2
+.Sh HISTORY
+The
+.Fn minherit
+function first appeared in
+.Ox .
+.Sh BUGS
+If a particular port does not support page-granularity
+inheritance, there's no way to figure out how large a region is
+actually affected by
+.Fn minherit .
diff --git a/lib/nbsd_libc/sys/mkdir.2 b/lib/nbsd_libc/sys/mkdir.2
new file mode 100644 (file)
index 0000000..e58437c
--- /dev/null
@@ -0,0 +1,111 @@
+.\"    $NetBSD: mkdir.2,v 1.24 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)mkdir.2    8.2 (Berkeley) 12/11/93
+.\"
+.Dd December 27, 2005
+.Dt MKDIR 2
+.Os
+.Sh NAME
+.Nm mkdir
+.Nd make a directory file
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/stat.h
+.Ft int
+.Fn mkdir "const char *path" "mode_t mode"
+.Sh DESCRIPTION
+The directory
+.Fa path
+is created with the access permissions specified by
+.Fa mode
+and restricted by the
+.Xr umask 2
+of the calling process.
+.Pp
+The directory's owner ID is set to the process's effective user ID.
+The directory's group ID is set to that of the parent directory in
+which it is created.
+.Sh RETURN VALUES
+A 0 return value indicates success.
+A \-1 return value indicates an error, and an error code is stored in
+.Va errno .
+.Sh ERRORS
+.Fn mkdir
+will fail and no directory will be created if:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+A component of the path prefix does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EROFS
+The named file resides on a read-only file system.
+.It Bq Er EEXIST
+The named file exists.
+.It Bq Er ENOSPC
+The new directory cannot be created because there is no space left
+on the file system that will contain the directory.
+.It Bq Er ENOSPC
+There are no free inodes on the file system on which the
+directory is being created.
+.It Bq Er EDQUOT
+The new directory cannot be created because the user's
+quota of disk blocks on the file system that will
+contain the directory has been exhausted.
+.It Bq Er EDQUOT
+The user's quota of inodes on the file system on
+which the directory is being created has been exhausted.
+.It Bq Er EIO
+An I/O error occurred while making the directory entry or allocating the inode.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.El
+.Sh SEE ALSO
+.Xr chmod 2 ,
+.Xr stat 2 ,
+.Xr umask 2
+.Sh STANDARDS
+The
+.Fn mkdir
+function conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/sys/mkfifo.2 b/lib/nbsd_libc/sys/mkfifo.2
new file mode 100644 (file)
index 0000000..835565b
--- /dev/null
@@ -0,0 +1,121 @@
+.\"    $NetBSD: mkfifo.2,v 1.20 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)mkfifo.2    8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt MKFIFO 2
+.Os
+.Sh NAME
+.Nm mkfifo
+.Nd make a fifo file
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/stat.h
+.Ft int
+.Fn mkfifo "const char *path" "mode_t mode"
+.Sh DESCRIPTION
+.Fn mkfifo
+creates a new fifo file with name
+.Fa path .
+The access permissions are
+specified by
+.Fa mode
+and restricted by the
+.Xr umask 2
+of the calling process.
+.Pp
+The fifo's owner ID is set to the process's effective user ID.
+The fifo's group ID is set to that of the parent directory in
+which it is created.
+.Sh RETURN VALUES
+A 0 return value indicates success.
+A \-1 return value indicates an error, and an error code is stored in
+.Va errno .
+.Sh ERRORS
+.Fn mkfifo
+will fail and no fifo will be created if:
+.Bl -tag -width Er
+.It Bq Er EOPNOTSUPP
+The kernel has not been configured to support fifo's.
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+A component of the path prefix does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EROFS
+The named file resides on a read-only file system.
+.It Bq Er EEXIST
+The named file exists.
+.It Bq Er ENOSPC
+The directory in which the entry for the new fifo is being placed
+cannot be extended because there is no space left on the file
+system containing the directory.
+.It Bq Er ENOSPC
+There are no free inodes on the file system on which the
+fifo is being created.
+.It Bq Er EDQUOT
+The directory in which the entry for the new fifo
+is being placed cannot be extended because the
+user's quota of disk blocks on the file system
+containing the directory has been exhausted.
+.It Bq Er EDQUOT
+The user's quota of inodes on the file system on
+which the fifo is being created has been exhausted.
+.It Bq Er EIO
+An
+.Tn I/O
+error occurred while making the directory entry or allocating the inode.
+.It Bq Er EIO
+An
+.Tn I/O
+error occurred while reading from or writing to the file system.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.El
+.Sh SEE ALSO
+.Xr chmod 2 ,
+.Xr stat 2 ,
+.Xr umask 2
+.Sh STANDARDS
+The
+.Nm mkfifo
+function call conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/sys/mknod.2 b/lib/nbsd_libc/sys/mknod.2
new file mode 100644 (file)
index 0000000..373a44b
--- /dev/null
@@ -0,0 +1,119 @@
+.\"    $NetBSD: mknod.2,v 1.20 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)mknod.2    8.1 (Berkeley) 6/4/93
+.\"
+.Dd January 18, 2007
+.Dt MKNOD 2
+.Os
+.Sh NAME
+.Nm mknod
+.Nd make a special file node
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/stat.h
+.Ft int
+.Fn mknod "const char *path" "mode_t mode" "dev_t dev"
+.Sh DESCRIPTION
+The device special file
+.Fa path
+is created with the major and minor
+device numbers specified by
+.Fa dev .
+The access permissions of
+.Fa path
+are extracted from
+.Fa mode ,
+modified by the
+.Xr umask 2
+of the parent process.
+.Pp
+.Fn mknod
+requires super-user privileges.
+.Sh RETURN VALUES
+Upon successful completion a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn mknod
+will fail and the file will be not created if:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+A component of the path prefix does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EPERM
+The process's effective user ID is not super-user.
+.It Bq Er EIO
+An I/O error occurred while making the directory entry or allocating the inode.
+.It Bq Er ENOSPC
+The directory in which the entry for the new node is being placed
+cannot be extended because there is no space left on the file
+system containing the directory.
+.It Bq Er ENOSPC
+There are no free inodes on the file system on which the
+node is being created.
+.It Bq Er EDQUOT
+The directory in which the entry for the new node
+is being placed cannot be extended because the
+user's quota of disk blocks on the file system
+containing the directory has been exhausted.
+.It Bq Er EDQUOT
+The user's quota of inodes on the file system on
+which the node is being created has been exhausted.
+.It Bq Er EROFS
+The named file resides on a read-only file system.
+.It Bq Er EEXIST
+The named file exists.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.El
+.Sh SEE ALSO
+.Xr chmod 2 ,
+.Xr mkfifo 2 ,
+.Xr stat 2 ,
+.Xr umask 2
+.Sh HISTORY
+A
+.Fn mknod
+function call appeared in
+.At v6 .
diff --git a/lib/nbsd_libc/sys/mlock.2 b/lib/nbsd_libc/sys/mlock.2
new file mode 100644 (file)
index 0000000..51c4b25
--- /dev/null
@@ -0,0 +1,164 @@
+.\"    $NetBSD: mlock.2,v 1.18 2004/05/13 10:20:58 wiz Exp $
+.\"
+.\" Copyright (c) 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.
+.\" 3. 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.
+.\"
+.\"    @(#)mlock.2     8.2 (Berkeley) 12/11/93
+.\"
+.Dd June 2, 1993
+.Dt MLOCK 2
+.Os
+.Sh NAME
+.Nm mlock ,
+.Nm munlock
+.Nd lock (unlock) physical pages in memory
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/mman.h
+.Ft int
+.Fn mlock "void *addr" "size_t len"
+.Ft int
+.Fn munlock "void *addr" "size_t len"
+.Sh DESCRIPTION
+The
+.Nm mlock
+system call
+locks into memory the physical pages associated with the virtual address
+range starting at
+.Fa addr
+for
+.Fa len
+bytes.
+The
+.Nm munlock
+call unlocks pages previously locked by one or more
+.Nm mlock
+calls.
+For both, the
+.Fa addr
+parameter should be aligned to a multiple of the page size.
+If the
+.Fa len
+parameter is not a multiple of the page size, it will be rounded up
+to be so.
+The entire range must be allocated.
+.Pp
+After an
+.Nm mlock
+call, the indicated pages will cause neither a non-resident page
+nor address-translation fault until they are unlocked.
+They may still cause protection-violation faults or TLB-miss faults on
+architectures with software-managed TLBs.
+The physical pages remain in memory until all locked mappings for the pages
+are removed.
+Multiple processes may have the same physical pages locked via their own
+virtual address mappings.
+A single process may likewise have pages multiply-locked via different virtual
+mappings of the same pages or via nested
+.Nm mlock
+calls on the same address range.
+Unlocking is performed explicitly by
+.Nm munlock
+or implicitly by a call to
+.Nm munmap
+which deallocates the unmapped address range.
+Locked mappings are not inherited by the child process after a
+.Xr fork 2 .
+.Pp
+Since physical memory is a potentially scarce resource, processes are
+limited in how much they can lock down.
+A single process can
+.Nm mlock
+the minimum of
+a system-wide ``wired pages'' limit and
+the per-process
+.Li RLIMIT_MEMLOCK
+resource limit.
+.Sh RETURN VALUES
+A return value of 0 indicates that the call
+succeeded and all pages in the range have either been locked or unlocked.
+A return value of \-1 indicates an error occurred and the locked
+status of all pages in the range remains unchanged.
+In this case, the global location
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn mlock
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The address given is not page aligned or the length is negative.
+.It Bq Er EAGAIN
+Locking the indicated range would exceed either the system or per-process
+limit for locked memory.
+.It Bq Er ENOMEM
+Some portion of the indicated address range is not allocated.
+There was an error faulting/mapping a page.
+.It Bq Er EPERM
+.Fn mlock
+was called by non-root on an architecture where locked page accounting
+is not implemented.
+.Pp
+.El
+.Fn munlock
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The address given is not page aligned or the length is negative.
+.It Bq Er ENOMEM
+Some portion of the indicated address range is not allocated.
+Some portion of the indicated address range is not locked.
+.El
+.Sh SEE ALSO
+.Xr fork 2 ,
+.Xr mincore 2 ,
+.Xr mmap 2 ,
+.Xr munmap 2 ,
+.Xr setrlimit 2 ,
+.Xr getpagesize 3
+.Sh STANDARDS
+The
+.Fn mlock
+and
+.Fn munlock
+functions conform to
+.St -p1003.1b-93 .
+.Sh HISTORY
+The
+.Fn mlock
+and
+.Fn munlock
+functions first appeared in
+.Bx 4.4 .
+.Sh BUGS
+The per-process resource limit is a limit on the amount of virtual
+memory locked, while the system-wide limit is for the number of locked
+physical pages.
+Hence a process with two distinct locked mappings of the same physical page
+counts as 2 pages against the per-process limit and as only a single page
+in the system limit.
diff --git a/lib/nbsd_libc/sys/mlockall.2 b/lib/nbsd_libc/sys/mlockall.2
new file mode 100644 (file)
index 0000000..f27838e
--- /dev/null
@@ -0,0 +1,131 @@
+.\"    $NetBSD: mlockall.2,v 1.13 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 1999 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+.\" NASA Ames Research Center.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd June 12, 1999
+.Dt MLOCKALL 2
+.Os
+.Sh NAME
+.Nm mlockall ,
+.Nm munlockall
+.Nd lock (unlock) the address space of a process
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/mman.h
+.Ft int
+.Fn mlockall "int flags"
+.Ft int
+.Fn munlockall "void"
+.Sh DESCRIPTION
+The
+.Nm mlockall
+system call locks into memory the physical pages associated with the
+address space of a process until the address space is unlocked, the
+process exits, or execs another program image.
+.Pp
+The following flags affect the behavior of
+.Nm mlockall :
+.Bl -tag -width MCL_CURRENT
+.It Dv MCL_CURRENT
+Lock all pages currently mapped into the process's address space.
+.It Dv MCL_FUTURE
+Lock all pages mapped into the process's address space in the future,
+at the time the mapping is established.
+Note that this may cause future mappings to fail if those mappings
+cause resource limits to be exceeded.
+.El
+.Pp
+Since physical memory is a potentially scarce resource, processes are
+limited in how much they can lock down.
+A single process can lock the minimum of a system-wide
+.Dq wired pages
+limit and the per-process
+.Li RLIMIT_MEMLOCK
+resource limit.
+.Pp
+The
+.Nm munlockall
+call unlocks any locked memory regions in the process address space.
+Any regions mapped after an
+.Nm munlockall
+call will not be locked.
+.Sh RETURN VALUES
+A return value of 0 indicates that the call
+succeeded and all pages in the range have either been locked or unlocked.
+A return value of \-1 indicates an error occurred and the locked
+status of all pages in the range remains unchanged.
+In this case, the global location
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn mlockall
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Ar flags
+argument is zero, or includes unimplemented flags.
+.It Bq Er ENOMEM
+Locking the indicated range would exceed either the system or per-process
+limit for locked memory.
+.It Bq Er EAGAIN
+Some or all of the memory mapped into the process's address space
+could not be locked when the call was made.
+.It Bq Er EPERM
+The calling process does not have the appropriate privilege to perform
+the requested operation.
+.El
+.Sh SEE ALSO
+.Xr mincore 2 ,
+.Xr mlock 2 ,
+.Xr mmap 2 ,
+.Xr munmap 2 ,
+.Xr setrlimit 2
+.Sh STANDARDS
+The
+.Fn mlockall
+and
+.Fn munlockall
+functions conform to
+.St -p1003.1b-93 .
+.Sh HISTORY
+The
+.Fn mlockall
+and
+.Fn munlockall
+functions first appeared in
+.Nx 1.5 .
+.Sh BUGS
+The per-process resource limit is a limit on the amount of virtual
+memory locked, while the system-wide limit is for the number of locked
+physical pages.
+Hence a process with two distinct locked mappings of the same physical page
+counts as 2 pages against the per-process limit and as only a single page
+in the system limit.
diff --git a/lib/nbsd_libc/sys/mmap.2 b/lib/nbsd_libc/sys/mmap.2
new file mode 100644 (file)
index 0000000..30e38c2
--- /dev/null
@@ -0,0 +1,289 @@
+.\"    $NetBSD: mmap.2,v 1.41 2009/02/27 16:48:02 wiz Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)mmap.2      8.4 (Berkeley) 5/11/95
+.\"
+.Dd February 27, 2009
+.Dt MMAP 2
+.Os
+.Sh NAME
+.Nm mmap
+.Nd map files or devices into memory
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/mman.h
+.Ft void *
+.Fn mmap "void *addr" "size_t len" "int prot" "int flags" "int fd" "off_t offset"
+.Sh DESCRIPTION
+The
+.Nm mmap
+function causes the pages starting at
+.Fa addr
+and continuing for at most
+.Fa len
+bytes to be mapped from the object described by
+.Fa fd ,
+starting at byte offset
+.Fa offset .
+If
+.Fa len
+is not a multiple of the pagesize, the mapped region may extend past the
+specified range.
+Any such extension beyond the end of the mapped object will be zero-filled.
+.Pp
+If
+.Fa addr
+is non-zero, it is used as a hint to the system.
+(As a convenience to the system, the actual address of the region may differ
+from the address supplied.)
+If
+.Fa addr
+is zero, an address will be selected by the system.
+The actual starting address of the region is returned.
+A successful
+.Fa mmap
+deletes any previous mapping in the allocated address range.
+.Pp
+The protections (region accessibility) are specified in the
+.Fa prot
+argument by
+.Em OR Ns 'ing
+the following values:
+.Pp
+.Bl -tag -width PROT_WRITEXX
+.It Dv PROT_EXEC
+Pages may be executed.
+.It Dv PROT_READ
+Pages may be read.
+.It Dv PROT_WRITE
+Pages may be written.
+.It Dv PROT_NONE
+Pages may not be accessed.
+.El
+.Pp
+.Bf -symbolic
+Note that, due to hardware limitations, on some platforms
+.Dv PROT_WRITE
+may imply
+.Dv PROT_READ ,
+and
+.Dv PROT_READ
+may imply
+.Dv PROT_EXEC .
+Portable programs should not rely on these flags being separately
+enforceable.
+.Ef
+.Pp
+The
+.Fa flags
+parameter specifies the type of the mapped object, mapping options and
+whether modifications made to the mapped copy of the page are private
+to the process or are to be shared with other references.
+Note that either
+.Dv MAP_SHARED
+or
+.Dv MAP_PRIVATE
+must be specified.
+Sharing, mapping type and options are specified in the
+.Fa flags
+argument by
+.Em OR Ns 'ing
+the following values:
+.Pp
+.Bl -tag -width MAP_HASSEMAPHOREXX
+.It Dv MAP_ALIGNED(n)
+Request that the allocation be aligned to the given boundary.
+The parameter
+.Ar n
+should be the base 2 logarithm of the desired alignment (e.g., to
+request alignment to 16K, use 14 as the value for n).
+The alignment must be equal to or greater than the platform's page
+size as returned by
+.Xr sysconf 3
+with the
+.Dv _SC_PAGESIZE
+request.
+.It Dv MAP_ANON
+Map anonymous memory not associated with any specific file.
+The file descriptor is not used for creating
+.Dv MAP_ANON
+regions, and must be specified as \-1.
+The mapped memory will be zero filled.
+.It Dv MAP_FILE
+Mapped from a regular file or character-special device memory.
+.It Dv MAP_FIXED
+Do not permit the system to select a different address than the one
+specified.
+If the specified address cannot be used,
+.Nm mmap
+will fail.
+If MAP_FIXED is specified,
+.Fa addr
+must be a multiple of the pagesize.
+Use of this option is discouraged.
+.It Dv MAP_HASSEMAPHORE
+Notify the kernel that the region may contain semaphores and that special
+handling may be necessary.
+.It Dv MAP_INHERIT
+Permit regions to be inherited across
+.Xr execve 2
+system calls.
+.It Dv MAP_TRYFIXED
+Attempt to use the address
+.Fa addr
+even if it falls within the normally protected process data or
+text segment memory regions.
+If the requested region of memory
+is actually present in the memory map, a different address will
+be selected as if
+.Dv MAP_TRYFIXED
+had not been specified.
+If
+.Fa addr
+is
+.Fa NULL ,
+this flag is ignored and the system will select a mapping address.
+.It Dv MAP_WIRED
+Lock the mapped region into memory as with
+.Xr mlock 2 .
+.It Dv MAP_PRIVATE
+Modifications made by this process are private, however modifications made by
+other processes using
+.Dv MAP_SHARED
+will be seen.
+.It Dv MAP_SHARED
+Modifications are shared.
+.El
+.Pp
+The
+.Xr close 2
+function does not unmap pages, see
+.Xr munmap 2
+for further information.
+.Pp
+The current design does not allow a process to specify the location of
+swap space.
+In the future we may define an additional mapping type,
+.Dv MAP_SWAP ,
+in which
+the file descriptor argument specifies a file or device to which swapping
+should be done.
+.Pp
+If
+.Dv MAP_FIXED
+is not specified, the system will attempt to place the mapping in an
+unused portion of the address space chosen to minimize possible
+collision between mapped regions and the heap.
+.Sh RETURN VALUES
+Upon successful completion,
+.Nm mmap
+returns a pointer to the mapped region.
+Otherwise, a value of
+.Dv MAP_FAILED
+is returned and
+.Va errno
+is set to indicate the error.
+The symbol
+.Dv MAP_FAILED
+is defined in the header
+.Ao Pa sys/mman.h Ac .
+No successful return from
+.Fn mmap
+will return the value
+.Dv MAP_FAILED .
+.Sh ERRORS
+.Fn mmap
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+The flag
+.Dv PROT_READ
+was specified as part of the
+.Fa prot
+parameter and
+.Fa fd
+was not open for reading.
+The flags
+.Dv MAP_SHARED
+and
+.Dv PROT_WRITE
+were specified as part of the
+.Fa flags
+and
+.Fa prot
+parameters and
+.Fa fd
+was not open for writing.
+.It Bq Er EBADF
+.Fa fd
+is not a valid open file descriptor.
+.It Bq Er EINVAL
+.\"One of
+.\".Dv MAP_ANON
+.\"or
+.\".Dv MAP_FILE
+.\"was not specified as part of the
+.\".Fa flags
+.\"parameter.
+.Dv MAP_FIXED
+was specified and the
+.Fa addr
+parameter was not page aligned or was outside of the
+valid address range for a process.
+.Dv MAP_ANON was specified and
+.Fa fd
+was not \-1.
+.It Bq Er ENODEV
+.Fa fd
+did not reference a regular or character special file.
+.It Bq Er ENOMEM
+.Dv MAP_FIXED
+was specified and the
+.Fa addr
+parameter wasn't available.
+.Dv MAP_ANON
+was specified and insufficient memory was available.
+.It Bq Er EOVERFLOW
+.Fa fd
+references a regular file and the value of
+.Fa offset
+plus
+.Fa len
+would exceed the offset maximum established in its open file description.
+.El
+.Sh SEE ALSO
+.Xr madvise 2 ,
+.Xr mincore 2 ,
+.Xr mlock 2 ,
+.Xr mprotect 2 ,
+.Xr msync 2 ,
+.Xr munmap 2 ,
+.Xr getpagesize 3 ,
+.Xr sysconf 3
diff --git a/lib/nbsd_libc/sys/mmap.c b/lib/nbsd_libc/sys/mmap.c
new file mode 100644 (file)
index 0000000..9b60fcd
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: mmap.c,v 1.14 2007/11/23 12:39:15 uebayasi Exp $       */
+
+/*
+ * Copyright (c) 1992, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)mmap.c     8.1 (Berkeley) 6/17/93";
+#else
+__RCSID("$NetBSD: mmap.c,v 1.14 2007/11/23 12:39:15 uebayasi Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/mman.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(mmap,_mmap)
+#endif
+
+void *__mmap(void *, size_t, int, int, int, int, off_t);
+
+/*
+ * This function provides 64-bit offset padding that
+ * is not supplied by GCC 1.X but is supplied by GCC 2.X.
+ */
+void *
+mmap(addr, len, prot, flags, fd, offset)
+       void   *addr;
+       size_t  len;
+       int     prot;
+       int     flags;
+       int     fd;
+       off_t   offset;
+{
+
+       return __mmap(addr, len, prot, flags, fd, 0, offset);
+}
diff --git a/lib/nbsd_libc/sys/modctl.2 b/lib/nbsd_libc/sys/modctl.2
new file mode 100644 (file)
index 0000000..d967e0d
--- /dev/null
@@ -0,0 +1,279 @@
+.\"    $NetBSD: modctl.2,v 1.8 2010/12/14 16:23:59 jruoho Exp $
+.\"
+.\" Copyright (c) 2009 The NetBSD Foundation, Inc.
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd December 14, 2010
+.Dt MODCTL 2
+.Os
+.Sh NAME
+.Nm modctl
+.Nd module control
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/module.h
+.Ft int
+.Fn modctl "int operation" "void *argp"
+.Sh DESCRIPTION
+.Fn modctl
+provides control over loaded kernel modules.
+The argument
+.Fa operation
+is one of
+.Dv MODCTL_LOAD ,
+.Dv MODCTL_UNLOAD ,
+or
+.Dv MODCTL_STAT .
+The argument
+.Fa argp
+depends on the
+.Fa operation
+to be performed.
+.Pp
+Operations are:
+.Bl -tag -width MODCTL_UNLOAD
+.It Dv MODCTL_LOAD
+Load a module.
+The
+.Fa argp
+argument should be a pointer to a
+.Em modctl_load_t
+structure, described below.
+.It Dv MODCTL_UNLOAD
+Unload a module.
+In this case,
+.Fa argp
+should be a string containing the name of the module to be unloaded.
+.It Dv MODCTL_STAT
+Return a list of loaded modules.
+In this case, the
+.Fa argp
+argument should be a
+.Em struct iovec
+pointing to a suitable block of memory.
+The kernel will fill this block with an array of
+.Em modstat_t
+structures, one per loaded module.
+If the block is not large enough, the data returned will be truncated
+to fit.
+The kernel will then update the
+.Fa iov_len
+member of the
+.Em iovec
+to reflect the size of the complete report, regardless of whether this
+is larger or smaller than the size passed in.
+.El
+.Ss Data Types
+The
+.Em modctl_load_t
+structure used with
+.Dv MODCTL_LOAD
+contains the following elements, which should be filled in by the caller:
+.Bl -tag -width aaaaaaaa
+.It Fa "const char *ml_filename"
+The name/path of the module to load.
+.It Fa "int ml_flags"
+Zero or more of the following flag values:
+.Bl -tag -compact -width "MODCTL_LOAD_FORCE"
+.It Dv MODCTL_NO_PROP
+Don't load \*[Lt]module\*[Gt].plist.
+.It Dv MODCTL_LOAD_FORCE
+Ignore kernel version mismatch.
+.El
+.It Fa "const char *ml_props"
+Externalized proplib dictionary to pass to module.
+.It Fa "size_t ml_propslen"
+Size of the dictionary blob.
+.Fa ml_props
+may be
+.Dv NULL
+in which case
+.Fa ml_propslen
+must be
+.Dv 0 .
+.El
+.Pp
+The
+.Em modstat_t
+structure used with
+.Dv MODCTL_STAT
+contains the following elements, which are filled in by the kernel:
+.Bl -tag -width aaaaaaaa
+.It Fa "char ms_name[MAXMODNAME]"
+The name of the module.
+.It Fa "char ms_required[MAXMODNAME * MAXMODDEPS]"
+The list of modules required by this module
+as a comma-delimited list of module names.
+.It Fa "modsrc_t ms_source"
+One of the following enumerated constants:
+.Bl -tag -compact -width "MODULE_SOURCE_FILESYS"
+.It Dv MODULE_SOURCE_KERNEL
+The module is compiled into the kernel.
+.It Dv MODULE_SOURCE_BOOT
+The module was provided by the bootstrap loader.
+.It Dv MODULE_SOURCE_FILESYS
+The module was loaded from the file system.
+.El
+.It Fa "modclass_t ms_class"
+One of the following enumerated constants:
+.Bl -tag -compact -width "MODULE_SOURCE_FILESYS"
+.It Dv MODULE_CLASS_SECMODEL
+Security model.
+.It Dv MODULE_CLASS_VFS
+File system.
+.It Dv MODULE_CLASS_DRIVER
+Device driver.
+.It Dv MODULE_CLASS_EXEC
+Executable file format.
+.It Dv MODULE_CLASS_MISC
+Miscellaneous.
+.It Dv MODULE_CLASS_ANY
+Any module class.
+.\" XXX: is MODULE_CLASS_ANY ever returned by this interface?
+.El
+.It Fa "uint64_t ms_addr"
+The load address within the kernel.
+.It Fa "u_int ms_size"
+Loaded size of the module.
+.It Fa "u_int ms_refcnt"
+Current number of live references to this module.
+.El
+.Sh RETURN VALUES
+Upon successful completion, the value returned is 0.
+.Pp
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn modctl
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EBUSY
+The argument
+.Fa operation
+is
+.Dv MODCTL_UNLOAD
+and the module is in use or the module is compiled into the kernel.
+.It Bq Er EDEADLK
+The argument
+.Fa operation
+is
+.Dv MODCTL_LOAD
+and there is a circular dependency in the module's dependency chain.
+.It Bq Er EEXIST
+The argument
+.Fa operation
+is
+.Dv MODCTL_LOAD
+and the module is already loaded.
+.It Bq Er EFAULT
+A bad address was given for
+.Fa argp .
+.It Bq Er EFBIG
+The argument
+.Fa operation
+is
+.Dv MODCTL_LOAD ,
+the specified module resides in the file system, and the module's default
+proplib file was too large.
+.It Bq Er EINVAL
+The argument
+.Fa operation
+is invalid.
+.Pp
+The argument
+.Fa operation
+is
+.Dv MODCTL_LOAD
+and ml_props is not
+.Dv NULL
+and
+.Dq ml_propslen
+is
+.Dv 0 ,
+or
+ml_props is
+.Dv NULL
+and
+.Dq ml_propslen
+is not
+.Dv 0 .
+The kernel is unable to internalize the plist.
+Or, there is a problem with the module or \*[Lt]module\*[Gt].plist.
+.It Bq Er EMLINK
+The argument
+.Fa operation
+is
+.Dv MODCTL_LOAD
+and the module has too many dependencies.
+.It Bq Er ENAMETOOLONG
+A module name/path is too long.
+.It Bq Er ENOENT
+The argument
+.Fa operation
+is
+.Dv MODCTL_LOAD
+and the module or a dependency can't be found.
+The argument
+.Fa operation
+is
+.Dv MODCTL_UNLOAD
+and no module by the name of
+.Fa argp
+is loaded.
+.It Bq Er ENOEXEC
+The argument
+.Fa operation
+is
+.Dv MODCTL_LOAD
+and the module is not a valid object for the system.
+.It Bq Er ENOMEM
+There was not enough memory to perform the
+.Fa operation .
+.It Bq Er EPERM
+Not allowed to perform the
+.Fa operation .
+.It Bq Er EPROGMISMATCH
+The argument
+.Fa operation
+is
+.Dv MODCTL_LOAD ,
+the
+.Fa ml_flags
+field in the
+.Em modctl_load_t
+structure does not include
+.Dv MODCTL_LOAD_FORCE ,
+and the requested module does not match the current kernel's version
+information.
+.El
+.Sh SEE ALSO
+.Xr module 7 ,
+.Xr module 9
+.Sh HISTORY
+The
+.Fn modctl
+function call first appeared in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/sys/mount.2 b/lib/nbsd_libc/sys/mount.2
new file mode 100644 (file)
index 0000000..da131fd
--- /dev/null
@@ -0,0 +1,434 @@
+.\"    $NetBSD: mount.2,v 1.45 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1980, 1989, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)mount.2    8.3 (Berkeley) 5/24/95
+.\"
+.Dd April 10, 2009
+.Dt MOUNT 2
+.Os
+.Sh NAME
+.Nm mount ,
+.Nm unmount
+.Nd mount or dismount a file system
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/param.h
+.In sys/mount.h
+.Ft int
+.Fn mount "const char *type" "const char *dir" "int flags" "void *data" "size_t data_len"
+.Ft int
+.Fn unmount "const char *dir" "int flags"
+.Sh DESCRIPTION
+The
+.Fn mount
+function grafts
+a file system object onto the system file tree
+at the point
+.Ar dir .
+The argument
+.Ar data
+describes the file system object to be mounted, and is
+.Ar data_len
+bytes long.
+The argument
+.Ar type
+tells the kernel how to interpret
+.Ar data
+(See
+.Ar type
+below).
+The contents of the file system
+become available through the new mount point
+.Ar dir .
+Any files in
+.Ar dir
+at the time
+of a successful mount are swept under the carpet so to speak, and
+are unavailable until the file system is unmounted.
+.Pp
+The following
+.Ar flags
+may be specified to
+suppress default semantics which affect file system access.
+.Bl -tag -width MNT_SYNCHRONOUS
+.It Dv MNT_RDONLY
+The file system should be treated as read-only;
+even the super-user may not write on it.
+.It Dv MNT_UNION
+Union with underlying filesystem instead of obscuring it.
+.It Dv MNT_HIDDEN
+Cause the
+.Xr df 1
+program, and perhaps others, to, by default,
+exclude this filesystem from its output.
+.It Dv MNT_NOEXEC
+Do not allow files to be executed from the file system.
+.It Dv MNT_NOSUID
+Do not honor setuid or setgid bits on files when executing them.
+.It Dv MNT_NODEV
+Do not interpret special files on the file system.
+.It Dv MNT_NOCOREDUMP
+Do not allow programs to dump core files on the file system.
+.It Dv MNT_NOATIME
+Never update access time in the file system.
+.It Dv MNT_NODEVMTIME
+Never update modification time of device files.
+.It Dv MNT_SYMPERM
+Recognize the permission of symbolic link when reading or traversing.
+.It Dv MNT_SYNCHRONOUS
+All I/O to the file system should be done synchronously.
+This will slow I/O performance considerably, but
+enhances overall filesystem reliability.
+.It Dv MNT_ASYNC
+All I/O to the file system should be done asynchronously.
+This vastly improves I/O throughput,
+but at a cost of making the filesystem likely to be
+completely unrecoverable should the system crash while
+unwritten data is pending in kernel buffers.
+.It Dv MNT_LOG
+Use a filesystem journal.
+.Dv MNT_LOG
+causes a journal (or log) to be created in the
+filesystem, creating a record of meta-data writes to be
+performed, allowing the actual writes to be deferred.
+This improves performance in most cases.
+.El
+.Pp
+The
+.Dv MNT_UPDATE ,
+.Dv MNT_RELOAD ,
+and
+.Dv MNT_GETARGS
+flags indicate that the mount command is being applied
+to an already mounted file system.
+The
+.Dv MNT_UPDATE
+flag allows the mount flags to be changed without requiring
+that the file system be unmounted and remounted.
+A conversion from read-write to read-only will fail if any files
+are currently open for writing on the filesystem, unless the
+.Dv MNT_FORCE
+flag is also applied.
+Some file systems may not allow all flags to be changed.
+For example,
+some file systems will not allow a change from read-write to read-only.
+The
+.Dv MNT_RELOAD
+flag causes kernel filesystem data to be reloaded from
+the filesystem device.
+It is only permitted on filesystems mounted read-only.
+Its purpose is to notify the system that the filesystem
+data has been modified by some external process.
+The
+.Dv MNT_GETARGS
+flag does not alter any of the mounted filesystem's properties,
+but returns the filesystem-specific arguments for the currently mounted
+filesystem.
+.Pp
+The
+.Fa type
+argument defines the type of the file system.
+The types of file systems known to the system are defined in
+.In sys/mount.h ,
+and those supported by the current running kernel obtained
+using
+.Xr sysctl 8
+to obtain the node
+.\" .Bd -literal -offset indent
+vfs.generic.fstypes.
+.\" XXX from lite-2:
+.\" The types of filesystems known to the system can be obtained with
+.\" .Xr sysctl 8
+.\" by using the command:
+.\" .Bd -literal -offset indent
+.\" sysctl vfs
+.\" .Ed
+.\" .Pp
+.Fa data
+is a pointer to a structure that contains the type
+specific arguments to mount.
+Some of the currently supported types of file systems and
+their type specific data are:
+.Pp
+.Dv MOUNT_FFS
+.Bd -literal -offset indent -compact
+struct ufs_args {
+      char      *fspec;             /* block special file to mount */
+};
+.Ed
+.Pp
+.Dv MOUNT_NFS
+.Bd -literal -offset indent -compact
+struct nfs_args {
+      int             version;      /* args structure version */
+      struct sockaddr *addr;        /* file server address */
+      int             addrlen;      /* length of address */
+      int             sotype;       /* Socket type */
+      int             proto;        /* and Protocol */
+      u_char          *fh;          /* File handle to be mounted */
+      int             fhsize;       /* Size, in bytes, of fh */
+      int             flags;        /* flags */
+      int             wsize;        /* write size in bytes */
+      int             rsize;        /* read size in bytes */
+      int             readdirsize;  /* readdir size in bytes */
+      int             timeo;        /* initial timeout in .1 secs */
+      int             retrans;      /* times to retry send */
+      int             maxgrouplist; /* Max. size of group list */
+      int             readahead;    /* # of blocks to readahead */
+      int             leaseterm;    /* Term (sec) of lease */
+      int             deadthresh;   /* Retrans threshold */
+      char            *hostname;    /* server's name */
+};
+.Ed
+.Pp
+.Dv MOUNT_MFS
+.Bd -literal -offset indent -compact
+struct mfs_args {
+      char     *fspec;             /* name to export for statfs */
+      struct   export_args30 pad;  /* unused */
+      caddr_t  base;               /* base of file system in mem */
+      u_long   size;               /* size of file system */
+};
+.Ed
+.\" XXX from lite-2:
+.\" The format for these argument structures is described in the
+.\" manual page for each filesystem.
+.\" By convention filesystem manual pages are named
+.\" by prefixing ``mount_'' to the name of the filesystem as returned by
+.\" .Xr sysctl 8 .
+.\" Thus the
+.\" .Nm NFS
+.\" filesystem is described by the
+.\" .Xr mount_nfs 8
+.\" manual page.
+.Pp
+The
+.Fn unmount
+function call disassociates the file system from the specified
+mount point
+.Fa dir .
+.Pp
+The
+.Fa flags
+argument may specify
+.Dv MNT_FORCE
+to specify that the file system should be forcibly unmounted even if files are
+still active.
+Active special devices continue to work,
+but any further accesses to any other active files result in errors
+even if the file system is later remounted.
+.Sh RETURN VALUES
+.Fn mount
+returns the value 0 if the mount was successful,
+the number of bytes written to
+.Ar data
+for
+.Dv MNT_GETARGS ,
+otherwise \-1 is returned and the variable
+.Va errno
+is set to indicate the error.
+.Pp
+.Fn unmount
+returns the value 0 if the unmount succeeded; otherwise \-1 is returned
+and the variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn mount
+will fail when one of the following occurs:
+.Bl -tag -width Er
+.It Bq Er EBUSY
+Another process currently holds a reference to
+.Fa dir ,
+or for an update from read-write to read-only
+there are files on the filesystem open for writes.
+.It Bq Er EFAULT
+.Fa dir
+points outside the process's allocated address space.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating a pathname.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+A component of
+.Fa dir
+does not exist.
+.It Bq Er ENOTDIR
+A component of
+.Ar name
+is not a directory,
+or a path prefix of
+.Ar special
+is not a directory.
+.It Bq Er EPERM
+The caller is not the super-user,
+and ordinary user mounts are not permitted or
+this particular request violates the rules.
+.El
+.Pp
+The following errors can occur for a
+.Em ufs
+file system mount:
+.Bl -tag -width Er
+.It Bq Er EBUSY
+.Ar Fspec
+is already mounted.
+.It Bq Er EFAULT
+.Ar Fspec
+points outside the process's allocated address space.
+.It Bq Er EINVAL
+The super block for the file system had a bad magic
+number or an out of range block size.
+.It Bq Er EIO
+An I/O error occurred while reading the super block or
+cylinder group information.
+.It Bq Er EMFILE
+No space remains in the mount table.
+.It Bq Er ENODEV
+A component of ufs_args
+.Ar fspec
+does not exist.
+.It Bq Er ENOMEM
+Not enough memory was available to read the cylinder
+group information for the file system.
+.It Bq Er ENOTBLK
+.Ar Fspec
+is not a block device.
+.It Bq Er ENXIO
+The major device number of
+.Ar fspec
+is out of range (this indicates no device driver exists
+for the associated hardware).
+.El
+.Pp
+The following errors can occur for a
+.Em nfs
+file system mount:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+Some part of the information described by nfs_args
+points outside the process's allocated address space.
+.It Bq Er ETIMEDOUT
+.Em Nfs
+timed out trying to contact the server.
+.El
+.Pp
+The following errors can occur for a
+.Em mfs
+file system mount:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+.Em Name
+points outside the process's allocated address space.
+.It Bq Er EINVAL
+The super block for the file system had a bad magic
+number or an out of range block size.
+.It Bq Er EIO
+A paging error occurred while reading the super block or
+cylinder group information.
+.It Bq Er EMFILE
+No space remains in the mount table.
+.It Bq Er ENOMEM
+Not enough memory was available to read the cylinder
+group information for the file system.
+.El
+.Pp
+.Fn unmount
+may fail with one of the following errors:
+.Bl -tag -width Er
+.It Bq Er EBUSY
+A process is holding a reference to a file located
+on the file system.
+.It Bq Er EFAULT
+.Fa dir
+points outside the process's allocated address space.
+.It Bq Er EINVAL
+The requested directory is not in the mount table.
+.It Bq Er EIO
+An I/O error occurred while writing cached file system information.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOTDIR
+A component of the path is not a directory.
+.It Bq Er EPERM
+The caller is not the super-user.
+.El
+.Pp
+A
+.Em ufs
+or
+.Em mfs
+mount can also fail if the maximum number of file systems are currently
+mounted.
+.Sh SEE ALSO
+.Xr df 1 ,
+.Xr getvfsstat 2 ,
+.Xr nfssvc 2 ,
+.Xr getmntinfo 3 ,
+.Xr symlink 7 ,
+.Xr mount 8 ,
+.Xr sysctl 8 ,
+.Xr umount 8
+.Sh HISTORY
+The
+.Fn mount
+and
+.Fn umount
+(now
+.Fn unmount )
+function calls were all present in
+.At v6 .
+.Pp
+Prior to
+.Nx 4.0
+the
+.Nm
+call was used to export NFS filesystems.
+This is now done through
+.Fn nfssvc .
+.Pp
+The
+.Dv data_len
+argument was added for
+.Nx 5.0 .
+.Sh BUGS
+Some of the error codes need translation to more obvious messages.
+.Pp
+Far more filesystems are supported than those those listed.
diff --git a/lib/nbsd_libc/sys/mprotect.2 b/lib/nbsd_libc/sys/mprotect.2
new file mode 100644 (file)
index 0000000..7b0a4d4
--- /dev/null
@@ -0,0 +1,98 @@
+.\"    $NetBSD: mprotect.2,v 1.22 2009/01/11 02:46:30 christos Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)mprotect.2  8.1 (Berkeley) 6/9/93
+.\"
+.Dd January 6, 2009
+.Dt MPROTECT 2
+.Os
+.Sh NAME
+.Nm mprotect
+.Nd control the protection of pages
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/mman.h
+.Ft int
+.Fn mprotect "void *addr" "size_t len" "int prot"
+.Sh DESCRIPTION
+The
+.Fn mprotect
+system call
+changes the specified pages to have protection
+.Fa prot .
+Not all implementations will guarantee protection on a page basis;
+the granularity of protection changes may be as large as an entire region.
+.Pp
+The protections (region accessibility) are specified in the
+.Fa prot
+argument by
+.Tn OR Ns 'ing
+the following values:
+.Pp
+.Bl -tag -width MAP_FIXEDX
+.It Dv PROT_EXEC
+Pages may be executed.
+.It Dv PROT_READ
+Pages may be read.
+.It Dv PROT_WRITE
+Pages may be written.
+.It Dv PROT_NONE
+No permissions.
+.El
+.Sh RETURN VALUES
+Upon successful completion,
+a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EACCES
+A memory protection violation occurred, or the
+.Dv PROT_EXEC
+flag was attempted on pages which belong to a filesystem mounted with the
+.Dv NOEXEC
+flag.
+.It Bq Er EINVAL
+An invalid memory range, or invalid parameters were provided.
+.It Bq Er ENOMEM
+A resource shortage occurred while internally calling
+.Fn uvm_map_protect .
+.El
+.Sh SEE ALSO
+.Xr madvise 2 ,
+.Xr mincore 2 ,
+.Xr msync 2 ,
+.Xr munmap 2
+.Sh HISTORY
+The
+.Fn mprotect
+function first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/sys/mremap.2 b/lib/nbsd_libc/sys/mremap.2
new file mode 100644 (file)
index 0000000..ef13e72
--- /dev/null
@@ -0,0 +1,109 @@
+.\"    $NetBSD: mremap.2,v 1.3 2008/02/16 17:45:39 tnn Exp $
+.\"
+.\" Copyright (c) 2007 Thomas Klausner and Joerg Sonnenberger
+.\" 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 AUTHORS ``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 AUTHORS 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.
+.\"
+.\" ------------------------------------------------------------
+.Dd February 14, 2008
+.Dt MREMAP 2
+.Os
+.Sh NAME
+.Nm mremap
+.Nd re-map a virtual memory address
+.\" ------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/mman.h
+.Ft void *
+.Fn mremap "void *oldp" "size_t oldsize" "void *newp" "size_t newsize" \
+"int flags"
+.\" ------------------------------------------------------------
+.Sh DESCRIPTION
+The
+.Fn mremap
+function resizes the mapped range (see
+.Xr mmap 2 )
+starting at
+.Ar oldp
+and having size
+.Ar oldsize
+to
+.Ar newsize .
+The following arguments can be
+.Dv OR Ap ed
+together in the
+.Ar flags
+argument:
+.Bl -tag -width XXMAPXALIGNEDXnXX
+.It Dv MAP_ALIGNED Ns Pq Ar n
+The allocation should be aligned to the given boundary, i.e. ensure
+that the lowest
+.Ar n
+bits of the address are zero.
+The parameter
+.Ar n
+should be the base 2 logarithm of the desired alignment (e.g., to
+request alignment to 16K, use 14 as the value for n).
+The alignment must be equal to or greater than the platform's page
+size as returned by
+.Xr sysconf 3
+with the
+.Dv _SC_PAGESIZE
+request.
+.It Dv MAP_FIXED
+.Ar newp
+is tried and
+.Fn mremap
+fails if that address can't be used as new base address for the range.
+Otherwise,
+.Ar oldp
+and
+.Ar newp
+are used as hints for the position, factoring in the given alignment.
+.El
+.Sh RETURN VALUES
+.Fn mremap
+returns the new address or
+.Dv MAP_FAILED ,
+if the remap failed.
+.Sh HISTORY
+The 
+.Fn mremap
+system call appeared in
+.Nx 5.0 .
+It was based on the code that supports
+.Fn mremap
+compatibility for Linux binaries.
+.Sh COMPATIBILITY
+The semantics of
+.Fn mremap
+differ from the one provided by glibc on Linux in that the
+.Ar newp
+argument was added and a different set of
+.Ar flags
+are implemented.
+.Sh SEE ALSO
+.Xr mmap 2 ,
+.Xr munmap 2
diff --git a/lib/nbsd_libc/sys/msgctl.2 b/lib/nbsd_libc/sys/msgctl.2
new file mode 100644 (file)
index 0000000..5c56888
--- /dev/null
@@ -0,0 +1,199 @@
+.\"    $NetBSD: msgctl.2,v 1.15 2010/03/22 19:30:55 joerg Exp $
+.\"
+.\" Copyright (c) 1995 Frank van der Linden
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"      This product includes software developed for the NetBSD Project
+.\"      by Frank van der Linden
+.\" 4. 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 ``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 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.
+.\"
+.Dd August 25, 1999
+.Dt MSGCTL 2
+.Os
+.Sh NAME
+.Nm msgctl
+.Nd message control operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/msg.h
+.Ft int
+.Fn msgctl "int msqid" "int cmd" "struct msqid_ds *buf"
+.Sh DESCRIPTION
+The
+.Fn msgctl
+system call performs control operations on the message queue specified
+by
+.Fa msqid .
+.Pp
+Each message queue has a
+.Sy msqid_ds
+structure associated with it which contains the following members:
+.Bd -literal
+    struct ipc_perm msg_perm; /* msg queue permission bits */
+    msgqnum_t msg_qnum;       /* # of msgs in the queue */
+    msglen_t  msg_qbytes;     /* max # of bytes on the queue */
+    pid_t     msg_lspid;      /* pid of last msgsnd() */
+    pid_t     msg_lrpid;      /* pid of last msgrcv() */
+    time_t    msg_stime;      /* time of last msgsnd() */
+    time_t    msg_rtime;      /* time of last msgrcv() */
+    time_t    msg_ctime;      /* time of last msgctl() */
+.Ed
+.Pp
+The
+.Sy ipc_perm
+structure used inside the
+.Sy msgid_ds
+structure is defined in
+.In sys/ipc.h
+and contains the following members:
+.Bd -literal
+    uid_t cuid;  /* creator user id */
+    gid_t cgid;  /* creator group id */
+    uid_t uid;   /* user id */
+    gid_t gid;   /* group id */
+    mode_t mode; /* permission (lower 9 bits) */
+.Ed
+.Pp
+The operation to be performed by
+.Fn msgctl
+is specified in
+.Fa cmd
+and is one of:
+.Bl -tag -width IPC_RMIDX
+.It Dv IPC_STAT
+Gather information about the message queue and place it in the
+structure pointed to by
+.Fa buf .
+.It Dv IPC_SET
+Set the value of the
+.Va msg_perm.uid ,
+.Va msg_perm.gid ,
+.Va msg_perm.mode
+and
+.Va msg_qbytes
+fields in the structure associated with
+.Fa msqid .
+The values are taken from the corresponding fields in the structure
+pointed to by
+.Fa buf .
+This operation can only be executed by the super-user, or a process that
+has an effective user id equal to either
+.Va msg_perm.cuid
+or
+.Va msg_perm.uid
+in the data structure associated with the message queue.
+The value of
+.Va msg_qbytes
+can only be increased by the super-user.
+Values for
+.Va msg_qbytes
+that exceed the system limit
+.Pf ( Dv MSGMNB
+from
+.In sys/msg.h )
+are silently truncated to that limit.
+.It Dv IPC_RMID
+Remove the message queue specified by
+.Fa msqid
+and destroy the data associated with it.
+Only the super-user or a process with an effective uid equal to the
+.Va msg_perm.cuid
+or
+.Va msg_perm.uid
+values in the data structure associated with the queue can do this.
+.El
+.Pp
+The permission to read from or write to a message queue (see
+.Xr msgsnd 2
+and
+.Xr msgrcv 2 )
+is determined by the
+.Va msg_perm.mode
+field in the same way as is done with files (see
+.Xr chmod 2 ) ,
+but the effective uid can match either the
+.Va msg_perm.cuid
+field or the
+.Va msg_perm.uid
+field, and the
+effective gid can match either
+.Va msg_perm.cgid
+or
+.Va msg_perm.gid .
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn msgctl
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EPERM
+.Fa cmd
+is equal to
+.Dv IPC_SET
+or
+.Dv IPC_RMID
+and the caller is not the super-user, nor does
+the effective uid match either the
+.Va msg_perm.uid
+or
+.Va msg_perm.cuid
+fields of the data structure associated with the message queue.
+.Pp
+An attempt was made to increase the value of
+.Va msg_qbytes
+through
+.Dv IPC_SET ,
+but the caller is not the super-user.
+.It Bq Er EACCES
+.Fa cmd
+is
+.Dv IPC_STAT
+and the caller has no read permission for this message queue.
+.It Bq Er EINVAL
+.Fa msqid
+is not a valid message queue identifier.
+.Pp
+.Fa cmd
+is not a valid command.
+.It Bq Er EFAULT
+.Fa buf
+specifies an invalid address.
+.El
+.Sh SEE ALSO
+.Xr msgget 2 ,
+.Xr msgrcv 2 ,
+.Xr msgsnd 2
+.Sh STANDARDS
+The
+.Nm
+system call conforms to
+.St -xsh5 .
+.Sh HISTORY
+Message queues appeared in the first release of
+.At V .
diff --git a/lib/nbsd_libc/sys/msgget.2 b/lib/nbsd_libc/sys/msgget.2
new file mode 100644 (file)
index 0000000..e711b3c
--- /dev/null
@@ -0,0 +1,151 @@
+.\"    $NetBSD: msgget.2,v 1.14 2004/05/13 10:20:58 wiz Exp $
+.\"
+.\" Copyright (c) 1995 Frank van der Linden
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"      This product includes software developed for the NetBSD Project
+.\"      by Frank van der Linden
+.\" 4. 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 ``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 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.
+.\"
+.Dd May 13, 2004
+.Dt MSGGET 2
+.Os
+.Sh NAME
+.Nm msgget
+.Nd get message queue identifier
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/msg.h
+.Ft int
+.Fn msgget "key_t key" "int msgflg"
+.Sh DESCRIPTION
+The
+.Fn msgget
+system call returns the message queue identifier associated with
+.Fa key .
+A message queue identifier is a unique integer greater than zero.
+.Pp
+A message queue is created if either
+.Fa key
+is equal to
+.Dv IPC_PRIVATE ,
+or
+.Fa key
+does not have a message queue identifier associated with it and the
+.Dv IPC_CREAT
+bit is set in
+.Fa msgflg .
+If both the
+.Dv IPC_CREAT
+bit and the
+.Dv IPC_EXCL
+bit are set in
+.Fa msgflg ,
+and
+.Fa key
+has a message queue identifier associated with it already,
+the operation will fail.
+.Pp
+If a new message queue is created, the data structure associated with it (the
+.Va msqid_ds
+structure, see
+.Xr msgctl 2 )
+is initialized as follows:
+.Bl -bullet
+.It
+.Va msg_perm.cuid
+and
+.Va msg_perm.uid
+are set to the effective uid of the calling process.
+.It
+.Va msg_perm.gid
+and
+.Va msg_perm.cgid
+are set to the effective gid of the calling process.
+.It
+.Va msg_perm.mode
+is set to the lower 9 bits of
+.Fa msgflg .
+.It
+.Va msg_qnum ,
+.Va msg_lspid ,
+.Va msg_lrpid ,
+.Va msg_rtime ,
+and
+.Va msg_stime
+are set to 0.
+.It
+.Va msg_qbytes
+is set to the system wide maximum value for the number of bytes in a queue
+.Pq Dv MSGMNB .
+.It
+.Va msg_ctime
+is set to the current time.
+.El
+.Sh RETURN VALUES
+Upon successful completion a positive message queue identifier is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EACCES
+A message queue is already associated with
+.Fa key
+and the caller has no permission to access it.
+.It Bq Er EEXIST
+Both
+.Dv IPC_CREAT
+and
+.Dv IPC_EXCL
+are set in
+.Fa msgflg ,
+and a message queue is already associated with
+.Fa key .
+.It Bq Er ENOSPC
+A new message queue could not be created because the system limit for
+the number of message queues has been reached.
+.It Bq Er ENOENT
+.Dv IPC_CREAT
+is not set in
+.Fa msgflg
+and no message queue associated with
+.Fa key
+was found.
+.El
+.Sh SEE ALSO
+.Xr msgctl 2 ,
+.Xr msgrcv 2 ,
+.Xr msgsnd 2 ,
+.Xr ftok 3
+.Sh STANDARDS
+The
+.Nm
+system call conforms to
+.St -xsh5 .
+.Sh HISTORY
+Message queues appeared in the first release of
+.At V .
diff --git a/lib/nbsd_libc/sys/msgrcv.2 b/lib/nbsd_libc/sys/msgrcv.2
new file mode 100644 (file)
index 0000000..ce594db
--- /dev/null
@@ -0,0 +1,218 @@
+.\"    $NetBSD: msgrcv.2,v 1.19 2009/01/28 08:57:02 wiz Exp $
+.\"
+.\" Copyright (c) 1995 Frank van der Linden
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"      This product includes software developed for the NetBSD Project
+.\"      by Frank van der Linden
+.\" 4. 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 ``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 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.
+.\"
+.Dd January 26, 2009
+.Dt MSGRCV 2
+.Os
+.Sh NAME
+.Nm msgrcv
+.Nd receive a message from a message queue
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/msg.h
+.Ft ssize_t
+.Fn msgrcv "int msqid" "void *msgp" "size_t msgsz" "long msgtyp" "int msgflg"
+.Sh DESCRIPTION
+The
+.Fn msgrcv
+function receives a message from the message queue specified in
+.Fa msqid ,
+and places it into the user-defined structure pointed to by
+.Fa msgp .
+This structure must contain a first field of type
+.Sy long
+that will indicate the user-defined type of the message.
+The remaining fields will contain the contents of the message.
+The following is an example of what this user-defined structure might
+look like:
+.Bd -literal
+struct mymsg {
+    long mtype;    /* message type */
+    char mtext[1]; /* body of message */
+};
+.Ed
+.Pp
+.Va mtype
+is an integer greater than 0 that can be used to select messages.
+.Va mtext
+is an array of bytes, with size up to the system limit
+.Dv MSGMAX .
+.Pp
+The value of
+.Fa msgtyp
+has one of the following meanings:
+.Bl -bullet
+.It
+.Fa msgtyp
+is greater than 0.
+The first message of type
+.Fa msgtyp
+will be received.
+.It
+.Fa msgtyp
+is equal to 0.
+The first message on the queue will be received.
+.It
+.Fa msgtyp
+is less than 0.
+The first message of the lowest message type that is
+less than or equal to the absolute value of
+.Fa msgtyp
+will be received.
+.El
+.Pp
+.Fa msgsz
+specifies the maximum length of the requested message.
+If the received message has a length greater than
+.Fa msgsz
+it will be silently truncated if the
+.Dv MSG_NOERROR
+flag is set in
+.Fa msgflg ,
+otherwise an error will be returned.
+.Pp
+If no matching message is present on the message queue specified by
+.Fa msqid ,
+the behaviour of
+.Fn msgrcv
+depends on whether the
+.Dv IPC_NOWAIT
+flag is set in
+.Fa msgflg
+or not.
+If
+.Dv IPC_NOWAIT
+is set, then
+.Fn msgrcv
+will immediately return a value of \-1 and set
+.Va errno
+to
+.Er EAGAIN .
+If
+.Dv IPC_NOWAIT
+is not set, the calling process will block until:
+.Bl -bullet
+.It
+A message of the requested type becomes available on the message queue.
+.It
+The message queue is removed, in which case \-1 will be returned and
+.Va errno
+set to
+.Er EIDRM .
+.It
+A signal is received and caught.
+\-1 is returned and
+.Va errno
+is set to
+.Er EINTR .
+.El
+.Pp
+If a message is successfully received, the data structure associated with
+.Fa msqid
+is updated as follows:
+.Bl -bullet
+.It
+.Va msg_lrpid
+is set to the pid of the caller.
+.It
+.Va msg_lrtime
+is set to the current time.
+.It
+.Va msg_qnum
+is decremented by 1.
+.El
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn msgrcv
+returns the number of bytes received into the
+.Va mtext
+field of the structure pointed to by
+.Fa msgp .
+Otherwise, \-1 is returned, and
+.Va errno
+set to indicate the error.
+.Sh ERRORS
+.Fn msgrcv
+will fail if:
+.Bl -tag -width Er
+.It Bq Er E2BIG
+A matching message was received, but its size was greater than
+.Fa msgsz
+and the
+.Dv MSG_NOERROR
+flag was not set in
+.Fa msgflg .
+.It Bq Er EACCES
+The calling process does not have read access to the message queue.
+.It Bq Er EAGAIN
+There is no message of the requested type available on the message queue,
+and
+.Dv IPC_NOWAIT
+is set in
+.Fa msgflg .
+.It Bq Er EFAULT
+.Fa msgp
+points to an invalid address.
+.It Bq Er EIDRM
+The message queue identifier
+.Fa msqid
+is removed from the system.
+.It Bq Er EINTR
+The system call was interrupted by the delivery of a signal.
+.It Bq Er EINVAL
+.Fa msqid
+is not a valid message queue identifier
+.Pp
+The message queue was removed while
+.Fn msgrcv
+was waiting for a message of the requested type to become available in it.
+.Pp
+.Fa msgsz
+is greater than
+.Dv SSIZE_MAX .
+.It Bq Er ENOMSG
+The queue does not contain a message of the desired type and
+.Dv IPC_NOWAIT
+is set.
+.El
+.Sh SEE ALSO
+.Xr msgctl 2 ,
+.Xr msgget 2 ,
+.Xr msgsnd 2
+.Sh STANDARDS
+The
+.Nm
+system call conforms to
+.St -xsh5 .
+.Sh HISTORY
+Message queues appeared in the first release of
+.At V .
diff --git a/lib/nbsd_libc/sys/msgsnd.2 b/lib/nbsd_libc/sys/msgsnd.2
new file mode 100644 (file)
index 0000000..87621c0
--- /dev/null
@@ -0,0 +1,181 @@
+.\"    $NetBSD: msgsnd.2,v 1.18 2010/04/30 04:06:20 jruoho Exp $
+.\"
+.\" Copyright (c) 1995 Frank van der Linden
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"      This product includes software developed for the NetBSD Project
+.\"      by Frank van der Linden
+.\" 4. 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 ``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 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.
+.\"
+.Dd April 30, 2010
+.Dt MSGSND 2
+.Os
+.Sh NAME
+.Nm msgsnd
+.Nd send a message to a message queue
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/msg.h
+.Ft int
+.Fn msgsnd "int msqid" "const void *msgp" "size_t msgsz" "int msgflg"
+.Sh DESCRIPTION
+The
+.Fn msgsnd
+function sends a message from the message queue specified in
+.Fa msqid .
+The
+.Fa msgp
+argument is a pointer to a user-defined structure containing the message.
+This structure must contain a first field of type
+.Vt long
+that will indicate the user-defined type of the message.
+The remaining fields will contain the contents of the message.
+The following is an example of what this user-defined
+structure might look like:
+.Bd -literal -offset indent
+struct mymsg {
+    long mtype;    /* message type */
+    char mtext[1]; /* body of message */
+};
+.Ed
+.Pp
+The
+.Va mtype
+field is an integer greater than 0 that can
+be used for selecting messages (see
+.Xr msgrcv 2 ) .
+The
+.Va mtext
+field is an array of bytes, with size up to the system limit
+.Dv MSGMAX .
+.Pp
+If the number of bytes already on the message queue plus
+.Fa msgsz
+is greater than the maximum number of bytes in the message queue
+.Pf ( Va msg_qbytes ,
+see
+.Xr msgctl 2 ) ,
+or if the number of messages on all queues system-wide is already equal to
+the system limit,
+.Fa msgflg
+determines the action of
+.Fn msgsnd .
+If
+.Fa msgflg
+has
+.Dv IPC_NOWAIT
+mask set in it, the call will return immediately.
+If
+.Fa msgflg
+does not have
+.Dv IPC_NOWAIT
+set in it, the call will block until:
+.Bl -bullet -offset indent
+.It
+The condition which caused the call to block no longer exists.
+The message was sent.
+.It
+The message queue is removed, in which case \-1 will be returned and
+.Va errno
+set to
+.Er EINVAL .
+.It
+The caller catches a signal.
+The call returns with
+.Va errno
+set to
+.Er EINTR .
+.El
+.Pp
+After a successful call, the data structure associated with the message
+queue is updated in the following way:
+.Bl -bullet -offset indent
+.It
+.Va msg_qnum
+is incremented by 1.
+.It
+.Va msg_lspid
+is set to the pid of the calling process.
+.It
+.Va msg_stime
+is set to the current time.
+.El
+.Sh RETURN VALUES
+Upon successful completion, 0 is returned.
+Otherwise, \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn msgsnd
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+The calling process does not have write access to the message queue.
+.It Bq Er EAGAIN
+There was no space for this message either on the queue or in the whole
+system, and
+.Dv IPC_NOWAIT
+was set in
+.Fa msgflg .
+.It Bq Er EFAULT
+.Fa msgp
+points to an invalid address.
+.It Bq Er EINTR
+The system call was interrupted by the delivery of a signal.
+.It Bq Er EINVAL
+The
+.Fa msqid
+argument is not a valid message queue identifier,
+or the value of
+.Fa mtype
+is less than 1.
+.Pp
+The message queue was removed while
+.Fn msgsnd
+was waiting for a resource to become available in order to deliver the
+message.
+.Pp
+The
+.Fa msgsz
+argument is greater than
+.Va msg_qbytes
+or
+.Dv SSIZE_MAX .
+.El
+.Sh SEE ALSO
+.Xr msgctl 2 ,
+.Xr msgget 2 ,
+.Xr msgrcv 2
+.Sh STANDARDS
+The
+.Nm
+system call conforms to
+.St -xsh5
+and
+.St -p1003.1-2001 .
+.Sh HISTORY
+Message queues appeared in the first release of
+.At V .
diff --git a/lib/nbsd_libc/sys/msync.2 b/lib/nbsd_libc/sys/msync.2
new file mode 100644 (file)
index 0000000..144c631
--- /dev/null
@@ -0,0 +1,131 @@
+.\"    $NetBSD: msync.2,v 1.23 2005/10/18 03:18:16 chs Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)msync.2     8.2 (Berkeley) 6/21/94
+.\"
+.Dd October 17, 2005
+.Dt MSYNC 2
+.Os
+.Sh NAME
+.Nm msync
+.Nd synchronize a mapped region
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/mman.h
+.Ft int
+.Fn msync "void *addr" "size_t len" "int flags"
+.Sh DESCRIPTION
+The
+.Fn msync
+system call writes all pages with shared modifications
+in the specified
+region of the process's address space back to permanent
+storage, and, if requested, invalidates cached data mapped
+in the region.
+If
+.Fa len
+is 0, all modified pages within the region containing
+.Fa addr
+will be flushed;
+if
+.Fa len
+is non-zero, only modified pages containing
+.Fa addr
+and
+.Fa len
+succeeding locations will be flushed.
+Any required synchronization of memory caches
+will also take place at this time.
+Filesystem operations on a file that is mapped for shared modifications
+are unpredictable except after an
+.Fn msync .
+.Pp
+The
+.Fa flags
+argument is formed by
+.Em or Ns 'ing
+the following values
+.Pp
+.Bl -column -offset indent -compact MS_INVALIDATE
+.It Dv MS_ASYNC Ta Perform asynchronous writes.
+.It Dv MS_SYNC Ta Perform synchronous writes.
+.It Dv MS_INVALIDATE Ta Invalidate cached data after writing.
+.El
+.Sh RETURN VALUES
+Upon successful completion,
+a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The following errors may be reported:
+.Bl -tag -width Er
+.It Bq Er EBUSY
+The
+.Dv MS_INVALIDATE
+flag was specified and a portion of the specified region
+was locked with
+.Xr mlock 2 .
+.It Bq Er EINVAL
+The specified
+.Fa flags
+argument was invalid.
+.It Bq Er EINVAL
+The
+.Fa addr
+parameter was not page aligned.
+.It Bq Er EINVAL
+The
+.Fa addr
+parameter did not specify an address part of a mapped region.
+.It Bq Er EINVAL
+The
+.Fa len
+parameter was negative.
+.It Bq Er EIO
+An I/O error occurred while writing to the file system.
+.It Bq Er ENOMEM
+Addresses in the specified region are outside the range allowed
+for the address space of the process, or specify one or more pages
+which are unmapped.
+.El
+.Sh SEE ALSO
+.Xr mlock 2 ,
+.Xr mmap 2 ,
+.Xr munlock 2
+.Sh HISTORY
+The
+.Fn msync
+function first appeared in
+.Bx 4.4 .
+It was modified to conform to
+.St -p1003.1b-93
+in
+.Nx 1.3 .
diff --git a/lib/nbsd_libc/sys/munmap.2 b/lib/nbsd_libc/sys/munmap.2
new file mode 100644 (file)
index 0000000..b8bc741
--- /dev/null
@@ -0,0 +1,83 @@
+.\"    $NetBSD: munmap.2,v 1.19 2004/05/13 10:20:58 wiz Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)munmap.2    8.3 (Berkeley) 5/27/94
+.\"
+.Dd May 27, 1994
+.Dt MUNMAP 2
+.Os
+.Sh NAME
+.Nm munmap
+.Nd remove a mapping
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/mman.h
+.Ft int
+.Fn munmap "void *addr" "size_t len"
+.Sh DESCRIPTION
+The
+.Fn munmap
+system call
+deletes the mappings for the specified address range,
+and causes further references to addresses within the range
+to generate invalid memory references.
+.Sh RETURN VALUES
+Upon successful completion,
+.Nm munmap
+returns zero.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn munmap
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The
+.Fa addr
+parameter was not page aligned, the
+.Fa len
+parameter was negative, or
+some part of the region being unmapped is outside the
+valid address range for a process.
+.El
+.Sh SEE ALSO
+.Xr madvise 2 ,
+.Xr mincore 2 ,
+.Xr mlock 2 ,
+.Xr mmap 2 ,
+.Xr mprotect 2 ,
+.Xr msync 2 ,
+.Xr getpagesize 3
+.Sh HISTORY
+The
+.Fn munmap
+function first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/sys/nanosleep.2 b/lib/nbsd_libc/sys/nanosleep.2
new file mode 100644 (file)
index 0000000..1838e29
--- /dev/null
@@ -0,0 +1,108 @@
+.\"    $NetBSD: nanosleep.2,v 1.11 2010/05/17 07:22:03 jruoho Exp $
+.\"
+.\" Copyright (c) 1986, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)sleep.3    8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 17, 2010
+.Dt NANOSLEEP 2
+.Os
+.Sh NAME
+.Nm nanosleep
+.Nd high resolution sleep
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Ft int
+.Fn nanosleep "const struct timespec *rqtp" "struct timespec *rmtp"
+.Sh DESCRIPTION
+The
+.Fn nanosleep
+suspends execution of the calling process until either the number of
+seconds and nanoseconds specified by
+.Fa rqtp
+have elapsed or a signal is delivered to the calling process and its
+action is to invoke a signal catching function or to terminate the
+process.
+The suspension time may be longer than requested due to the
+scheduling of other activity by the system.
+The
+.Em struct timespec
+is described in
+.Xr timespec 3 .
+.Sh RETURN VALUES
+If the
+.Fn nanosleep
+function returns because the requested time has elapsed, the value
+returned will be zero.
+.Pp
+If the
+.Fn nanosleep
+function returns due to the delivery of a signal, the value returned
+will be the \-1, and the global variable
+.Va errno
+will be set to indicate the interruption.
+If
+.Fa rmtp
+is
+.Pf non- Dv NULL ,
+the timespec structure it references is updated to contain the
+unslept amount (the request time minus the time actually slept).
+.Sh ERRORS
+If any of the following conditions occur, the
+.Nm
+function shall return \-1 and set
+.Va errno
+to the corresponding value.
+.Bl -tag -width Er
+.It Bq Er EFAULT
+Either
+.Fa rqtp
+or
+.Fa rmtp
+points to memory that is not a valid part of the process
+address space.
+.It Bq Er EINTR
+.Nm
+was interrupted by the delivery of a signal.
+.It Bq Er EINVAL
+.Fa rqtp
+specified a nanosecond value less than zero or greater than 1000 million.
+.It Bq Er ENOSYS
+.Nm
+is not supported by this implementation.
+.El
+.Sh SEE ALSO
+.Xr sleep 3 ,
+.Xr timespec 3
+.Sh STANDARDS
+The
+.Fn nanosleep
+function conforms to
+.St -p1003.1b-93 .
diff --git a/lib/nbsd_libc/sys/nfssvc.2 b/lib/nbsd_libc/sys/nfssvc.2
new file mode 100644 (file)
index 0000000..5f27a5f
--- /dev/null
@@ -0,0 +1,195 @@
+.\"    $NetBSD: nfssvc.2,v 1.24 2009/03/10 21:00:47 joerg Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)nfssvc.2    8.1 (Berkeley) 6/9/93
+.\"
+.Dd December 30, 2006
+.Dt NFSSVC 2
+.Os
+.Sh NAME
+.Nm nfssvc
+.Nd NFS services
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.In nfs/nfs.h
+.Ft int
+.Fn nfssvc "int flags" "void *argstructp"
+.Sh DESCRIPTION
+The
+.Fn nfssvc
+function is used by the NFS daemons to pass information into and out
+of the kernel and also to enter the kernel as a server daemon.
+The
+.Fa flags
+argument consists of several bits that show what action is to be taken
+once in the kernel and the
+.Fa argstructp
+points to one of three structures depending on which bits are set in
+flags.
+.Ss Calls used by Xr nfsd 8
+On the server side,
+.Fn nfssvc
+is called with the flag
+.Dv NFSSVC_NFSD
+and a pointer to a
+.Bd -literal
+struct nfsd_srvargs {
+       struct nfsd     *nsd_nfsd;      /* Pointer to in kernel nfsd struct */
+       uid_t           nsd_uid;        /* Effective uid mapped to cred */
+       u_long          nsd_haddr;      /* Ip address of client */
+       struct ucred    nsd_cr;         /* Cred. uid maps to */
+       int             nsd_authlen;    /* Length of auth string (ret) */
+       char            *nsd_authstr;   /* Auth string (ret) */
+};
+.Ed
+.Pp
+to enter the kernel as an
+.Xr nfsd 8
+daemon.
+Whenever an
+.Xr nfsd 8
+daemon receives a Kerberos authentication ticket, it will return from
+.Fn nfssvc
+with errno set to
+.Er ENEEDAUTH .
+The
+.Xr nfsd 8
+will attempt to authenticate the ticket and generate a set of credentials
+on the server for the
+.Dq user id
+specified in the field nsd_uid.
+This is done by first authenticating the Kerberos ticket and then mapping
+the Kerberos principal to a local name and getting a set of credentials for
+that user via
+.Xr getpwnam 3
+and
+.Xr getgrouplist 3 .
+If successful, the
+.Xr nfsd 8
+will call
+.Fn nfssvc
+with the
+.Dv NFSSVC_NFSD
+and
+.Dv NFSSVC_AUTHIN
+flags set to pass the credential mapping in nsd_cr into the
+kernel to be cached on the server socket for that client.
+If the authentication failed,
+.Xr nfsd 8
+calls
+.Fn nfssvc
+with the flags
+.Dv NFSSVC_NFSD
+and
+.Dv NFSSVC_AUTHINFAIL
+to denote an authentication failure.
+.Pp
+The master
+.Xr nfsd 8
+server daemon calls
+.Fn nfssvc
+with the flag
+.Dv NFSSVC_ADDSOCK
+and a pointer to a
+.Bd -literal
+struct nfsd_args {
+       int     sock;           /* Socket to serve */
+       caddr_t name;           /* Client address for connection based sockets */
+       int     namelen;        /* Length of name */
+};
+.Ed
+.Pp
+to pass a server side
+.Tn NFS
+socket into the kernel for servicing by the
+.Xr nfsd 8
+daemons.
+.Ss Calls used by Xr mountd 8
+The
+.Xr mountd 8
+server daemon calls
+.Fn nfssvc
+with the flag
+.Dv NFSSVC_SETEXPORTSLIST
+and a pointer to a
+.Ft struct mountd_exports_list
+object to atomically change the exports lists of a specific file system.
+This structure has the following fields:
+.Bl -tag -width ".Vt const char *mel_path"
+.It Vt const char *mel_path
+Path to the file system that will have its exports list replaced by the
+one described in the other fields.
+.It Vt size_t mel_nexports
+Number of valid entries in the
+.Vt mel_export
+field.
+If zero, the exports list will be cleared for the given file system.
+.It Vt struct export_args mel_export[AF_MAX]
+Set of exports to be used for the given file system.
+.El
+.Sh RETURN VALUES
+Usually
+.Nm
+does not return unless the server
+is terminated by a signal when a value of 0 is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to specify the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er ENEEDAUTH
+This special error value is really used for authentication support,
+particularly Kerberos, as explained above.
+.It Bq Er EPERM
+The caller is not the super-user.
+.El
+.Sh SEE ALSO
+.Xr mount_nfs 8 ,
+.Xr nfsd 8
+.Sh HISTORY
+The
+.Nm
+function first appeared in
+.Bx 4.4 .
+.Sh BUGS
+The
+.Nm
+system call is designed specifically for the
+.Tn NFS
+support daemons and as such is specific to their requirements.
+It should really return values to indicate the need for authentication
+support, since
+.Er ENEEDAUTH
+is not really an error.
+Several fields of the argument structures are assumed to be valid and
+sometimes to be unchanged from a previous call, such that
+.Nm
+must be used with extreme care.
diff --git a/lib/nbsd_libc/sys/ntp_adjtime.2 b/lib/nbsd_libc/sys/ntp_adjtime.2
new file mode 100644 (file)
index 0000000..b473d36
--- /dev/null
@@ -0,0 +1,307 @@
+.\"    $NetBSD: ntp_adjtime.2,v 1.10 2009/05/18 09:28:51 wiz Exp $
+.\"
+.\" Copyright (c) 2001 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Thomas Klausner.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd October 22, 2007
+.Dt NTP_ADJTIME 2
+.Os
+.Sh NAME
+.Nm ntp_adjtime ,
+.Nm ntp_gettime
+.Nd Network Time Protocol (NTP) daemon interface system calls
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/time.h
+.In sys/timex.h
+.Ft int
+.Fn ntp_adjtime "struct timex *"
+.Ft int
+.Fn ntp_gettime "struct ntptimeval *"
+.Sh DESCRIPTION
+The two system calls
+.Fn ntp_adjtime
+and
+.Fn ntp_gettime
+are the kernel interface to the Network Time Protocol (NTP) daemon
+.Xr ntpd 8 .
+.Pp
+The
+.Fn ntp_adjtime
+function is used by the NTP daemon to adjust the system clock to an
+externally derived time.
+The time offset and related variables which are set by
+.Fn ntp_adjtime
+are used by
+.Xr hardclock 9
+to adjust the phase and frequency of the phase- or frequency-lock loop
+(PLL resp. FLL) which controls the system clock.
+.Pp
+The
+.Fn ntp_gettime
+function provides the time, maximum error (sync distance) and
+estimated error (dispersion) to client user application programs.
+.Pp
+In the following, all variables that refer PPS are only relevant if
+the
+.Em PPS_SYNC
+option (see
+.Xr options 4 )
+is enabled in the kernel.
+.Pp
+.Fn ntp_adjtime
+has as argument a
+.Va struct timex *
+of the following form:
+.Bd -literal
+struct timex {
+       unsigned int modes;     /* clock mode bits (wo) */
+       long offset;            /* time offset (us) (rw) */
+       long freq;              /* frequency offset (scaled ppm) (rw) */
+       long maxerror;          /* maximum error (us) (rw) */
+       long esterror;          /* estimated error (us) (rw) */
+       int status;             /* clock status bits (rw) */
+       long constant;          /* pll time constant (rw) */
+       long precision;         /* clock precision (us) (ro) */
+       long tolerance;         /* clock frequency tolerance (scaled
+                                * ppm) (ro) */
+       /*
+        * The following read-only structure members are implemented
+        * only if the PPS signal discipline is configured in the
+        * kernel.
+        */
+       long ppsfreq;           /* pps frequency (scaled ppm) (ro) */
+       long jitter;            /* pps jitter (us) (ro) */
+       int shift;              /* interval duration (s) (shift) (ro) */
+       long stabil;            /* pps stability (scaled ppm) (ro) */
+       long jitcnt;            /* jitter limit exceeded (ro) */
+       long calcnt;            /* calibration intervals (ro) */
+       long errcnt;            /* calibration errors (ro) */
+       long stbcnt;            /* stability limit exceeded (ro) */
+};
+.Ed
+.Pp
+The members of this struct have the following meanings when used as
+argument for
+.Fn ntp_adjtime :
+.Bl -tag -width tolerance -compact
+.It Fa modes
+Defines what settings should be changed with the current
+.Fn ntp_adjtime
+call (write-only).
+Bitwise OR of the following:
+.Bl -tag -width MOD_TIMECONST -compact -offset indent
+.It MOD_OFFSET
+set time offset
+.It MOD_FREQUENCY
+set frequency offset
+.It MOD_MAXERROR
+set maximum time error
+.It MOD_ESTERROR
+set estimated time error
+.It MOD_STATUS
+set clock status bits
+.It MOD_TIMECONST
+set PLL time constant
+.It MOD_CLKA
+set clock A
+.It MOD_CLKB
+set clock B
+.El
+.It Fa offset
+Time offset (in microseconds), used by the PLL/FLL to adjust the
+system time in small increments (read-write).
+.It Fa freq
+Frequency offset (scaled ppm) (read-write).
+.It Fa maxerror
+Maximum error (in microseconds).
+Initialized by an
+.Fn ntp_adjtime
+call, and increased by the kernel once each second to reflect the maximum
+error bound growth (read-write).
+.It Fa esterror
+Estimated error (in microseconds).
+Set and read by
+.Fn ntp_adjtime ,
+but unused by the kernel (read-write).
+.It Fa status
+System clock status bits (read-write).
+Bitwise OR of the following:
+.Bl -tag -width STA_PPSJITTER -compact -offset indent
+.It STA_PLL
+Enable PLL updates (read-write).
+.It STA_PPSFREQ
+Enable PPS freq discipline (read-write).
+.It STA_PPSTIME
+Enable PPS time discipline (read-write).
+.It STA_FLL
+Select frequency-lock mode (read-write).
+.It STA_INS
+Insert leap (read-write).
+.It STA_DEL
+Delete leap (read-write).
+.It STA_UNSYNC
+Clock unsynchronized (read-write).
+.It STA_FREQHOLD
+Hold frequency (read-write).
+.It STA_PPSSIGNAL
+PPS signal present (read-only).
+.It STA_PPSJITTER
+PPS signal jitter exceeded (read-only).
+.It STA_PPSWANDER
+PPS signal wander exceeded (read-only).
+.It STA_PPSERROR
+PPS signal calibration error (read-only).
+.It STA_CLOCKERR
+Clock hardware fault (read-only).
+.El
+.It Fa constant
+PLL time constant, determines the bandwidth, or
+.Dq stiffness ,
+of the PLL (read-write).
+.It Fa precision
+Clock precision (in microseconds).
+In most cases the same as the kernel tick variable (see
+.Xr hz 9 ) .
+If a precision clock counter or external time-keeping signal is available,
+it could be much lower (and depend on the state of the signal)
+(read-only).
+.It Fa tolerance
+Maximum frequency error, or tolerance of the CPU clock oscillator (scaled
+ppm).
+Ordinarily a property of the architecture, but could change under
+the influence of external time-keeping signals (read-only).
+.It Fa ppsfreq
+PPS frequency offset produced by the frequency median filter (scaled
+ppm) (read-only).
+.It Fa jitter
+PPS jitter measured by the time median filter in microseconds
+(read-only).
+.It Fa shift
+Logarithm to base 2 of the interval duration in seconds (PPS,
+read-only).
+.It Fa stabil
+PPS stability (scaled ppm); dispersion (wander) measured by the
+frequency median filter (read-only).
+.It Fa jitcnt
+Number of seconds that have been discarded because the jitter measured
+by the time median filter exceeded the limit
+.Em MAXTIME
+(PPS, read-only).
+.It Fa calcnt
+Count of calibration intervals (PPS, read-only).
+.It Fa errcnt
+Number of calibration intervals that have been discarded because the
+wander exceeded the limit
+.Em MAXFREQ
+or where the calibration interval jitter exceeded two ticks (PPS,
+read-only).
+.It Fa stbcnt
+Number of calibration intervals that have been discarded because the
+frequency wander exceeded the limit
+.Em MAXFREQ Ns /4
+(PPS, read-only).
+.El
+After the
+.Fn ntp_adjtime
+call, the
+.Va struct timex *
+structure contains the current values of the corresponding variables.
+.Pp
+.Fn ntp_gettime
+has as argument a
+.Va struct ntptimeval *
+with the following members:
+.Bd -literal
+struct ntptimeval {
+       struct timespec time;   /* current time (ro) */
+       long maxerror;          /* maximum error (us) (ro) */
+       long esterror;          /* estimated error (us) (ro) */
+       /* the following are placeholders for now */
+       long tai;               /* TAI offset */
+       int time_state;         /* time status */
+};
+.Ed
+.Pp
+These have the following meaning:
+.Bl -tag -width tolerance -compact
+.It Fa time
+Current time (read-only).
+.It Fa maxerror
+Maximum error in microseconds (read-only).
+.It Fa esterror
+Estimated error in microseconds (read-only).
+.El
+.Sh RETURN VALUES
+.Fn ntp_adjtime
+and
+.Fn ntp_gettime
+return the current state of the clock on success, or any of the errors
+of
+.Xr copyin 9
+and
+.Xr copyout 9 .
+.Fn ntp_adjtime
+may additionally return
+.Er EPERM
+if the user calling
+.Fn ntp_adjtime
+does not have sufficient permissions.
+.Pp
+Possible states of the clock are:
+.Bl -tag -width TIME_ERROR -compact -offset indent
+.It TIME_OK
+Everything okay, no leap second warning.
+.It TIME_INS
+.Dq insert leap second
+warning.
+.It TIME_DEL
+.Dq delete leap second
+warning.
+.It TIME_OOP
+Leap second in progress.
+.It TIME_WAIT
+Leap second has occurred.
+.It TIME_ERROR
+Clock not synchronized.
+.El
+.Sh SEE ALSO
+.Xr options 4 ,
+.Xr ntpd 8 ,
+.Xr hardclock 9 ,
+.Xr hz 9
+.Rs
+.%A J. Mogul
+.%A D. Mills
+.%A J. Brittenson
+.%A J. Stone
+.%A U. Windl
+.%T Pulse-Per-Second API for UNIX-like Operating Systems
+.%R RFC 2783
+.%D March 2000
+.Re
diff --git a/lib/nbsd_libc/sys/ntp_adjtime.c b/lib/nbsd_libc/sys/ntp_adjtime.c
new file mode 100644 (file)
index 0000000..a7d8fb8
--- /dev/null
@@ -0,0 +1,117 @@
+/*     $NetBSD: ntp_adjtime.c,v 1.11 2007/11/23 12:39:15 uebayasi Exp $ */
+
+/*
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.      
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Emmanuel Dreyfus.
+ *
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ntp_adjtime.c,v 1.11 2007/11/23 12:39:15 uebayasi Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/timex.h>
+#include <sys/ioctl.h>
+#include <sys/syscall.h>
+
+#include <sys/clockctl.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <paths.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(ntp_adjtime,_ntp_adjtime)
+#endif
+
+extern int __clockctl_fd;
+
+int __ntp_adjtime(struct timex *);
+
+int
+ntp_adjtime(tp)
+       struct timex *tp;
+{
+       struct clockctl_ntp_adjtime args;
+       int error;
+       int rv;
+
+       /*
+        * we always attempt to use the syscall unless we had to
+        * use the clockctl device before
+        *
+        * ntp_adjtime() is callable for mortals if tp->modes == 0 !
+        */
+       if (__clockctl_fd == -1) {
+               rv = __ntp_adjtime(tp);
+       
+               /*
+                * if we fail with EPERM we try the clockctl device
+                */
+               if (rv != -1 || errno != EPERM)
+                       return rv;
+
+               /*
+                * If this fails, it means that we are not root
+                * and we cannot open clockctl. This is a true
+                * failure.
+                */
+               __clockctl_fd = open(_PATH_CLOCKCTL, O_WRONLY, 0);
+               if (__clockctl_fd == -1) {
+                       /* original error was EPERM - don't leak open errors */
+                       errno = EPERM;
+                       return -1;
+               }
+
+               (void) fcntl(__clockctl_fd, F_SETFD, FD_CLOEXEC);
+       }
+
+       /*
+        * If __clockctl_fd >=0, clockctl has already been open
+        * and used, so we carry on using it.
+        */
+       args.tp = tp;
+       error = ioctl(__clockctl_fd, CLOCKCTL_NTP_ADJTIME, &args);
+
+       /*
+        * There is no way to get retval set through ioctl(), hence we
+        * have to handle it here, using args.retval
+        */
+       if (error == 0) {
+               rv = (int)args.retval;
+               return rv;
+       }
+
+       return error;
+}
diff --git a/lib/nbsd_libc/sys/open.2 b/lib/nbsd_libc/sys/open.2
new file mode 100644 (file)
index 0000000..1e5fb44
--- /dev/null
@@ -0,0 +1,377 @@
+.\"    $NetBSD: open.2,v 1.47 2010/09/22 17:58:09 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)open.2     8.2 (Berkeley) 11/16/93
+.\"
+.Dd September 22, 2010
+.Dt OPEN 2
+.Os
+.Sh NAME
+.Nm open
+.Nd open or create a file for reading or writing
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In fcntl.h
+.Ft int
+.Fn open "const char *path" "int flags" "mode_t mode"
+.Sh DESCRIPTION
+The file name specified by
+.Fa path
+is opened
+for reading and/or writing as specified by the
+argument
+.Fa flags
+and the file descriptor returned to the calling process.
+The
+.Fa flags
+are specified by
+.Em or Ns 'ing
+the values listed below.
+Applications must specify exactly one of the first three values
+(file access methods):
+.Bl -tag -offset indent -width O_NONBLOCK
+.It Dv O_RDONLY
+Open for reading only.
+.It Dv O_WRONLY
+Open for writing only.
+.It Dv O_RDWR
+Open for reading and writing.
+.El
+.Pp
+Any combination of the following may be used:
+.Bl -tag -offset indent -width O_NONBLOCK
+.It Dv O_NONBLOCK
+Do not block on open or for data to become available.
+.It Dv O_APPEND
+Append to the file on each write.
+.It Dv O_CREAT
+Create the file if it does not exist, in which case the file is
+created with mode
+.Ar mode
+as described in
+.Xr chmod 2
+and modified by the process' umask value (see
+.Xr umask 2 ) .
+.It Dv O_TRUNC
+Truncate size to 0.
+.It Dv O_EXCL
+Error if
+.Dv O_CREAT
+and the file already exists.
+.It Dv O_SHLOCK
+Atomically obtain a shared lock.
+.It Dv O_EXLOCK
+Atomically obtain an exclusive lock.
+.It Dv O_NOFOLLOW
+If last path element is a symlink, don't follow it.
+This option is provided for compatibility with other operating
+systems, but its security value is questionable.
+.It Dv O_DSYNC
+If set, write operations will be performed according to synchronized
+I/O data integrity completion:
+each write will wait for the file data to be committed to stable
+storage.
+.It Dv O_SYNC
+If set, write operations will be performed according to synchronized
+I/O file integrity completion:
+each write will wait for both the file data and file status to be
+committed to stable storage.
+.It Dv O_RSYNC
+If set, read operations will complete at the same level of
+integrity which is in effect for write operations:
+if specified together with
+.Dv O_SYNC ,
+each read will wait for the file status to be committed to stable
+storage.
+.Pp
+Combining
+.Dv O_RSYNC
+with
+.Dv O_DSYNC
+only, or specifying it without any other synchronized I/O integrity
+completion flag set, has no further effect.
+.It Dv O_ALT_IO
+Alternate I/O semantics will be used for read and write operations
+on the file descriptor.
+Alternate semantics are defined by the underlying layers and will not
+have any alternate effect in most cases.
+.It Dv O_NOCTTY
+If the file is a terminal device, the opened device is not
+made the controlling terminal for the session.
+This flag has no effect on
+.Nx ,
+since the system defaults to the abovementioned behaviour.
+The flag is present only for standards conformance.
+.It Dv O_DIRECT
+If set on a regular file, data I/O operations will not buffer the data
+being transferred in the kernel's cache, but rather transfer the data
+directly between user memory and the underlying device driver if possible.
+This flag is advisory; the request may be performed in the normal
+buffered fashion if certain conditions are not met, e.g. if the request
+is not sufficiently aligned or if the file is mapped.
+.Pp
+To meet the alignment requirements for direct I/O, the file offset,
+the length of the I/O and the address of the buffer in memory must all
+be multiples of
+.Dv DEV_BSIZE
+(512 bytes).
+If the I/O request is made
+using an interface that supports scatter/gather via struct iovec, each
+element of the request must meet the above alignment constraints.
+.It Dv O_DIRECTORY
+Fail if the file is not a directory.
+.El
+.Pp
+Opening a file with
+.Dv O_APPEND
+set causes each write on the file
+to be appended to the end.
+If
+.Dv O_TRUNC
+is specified and the
+file exists, the file is truncated to zero length.
+.Pp
+If
+.Dv O_EXCL
+is set with
+.Dv O_CREAT
+and the file already
+exists,
+.Fn open
+returns an error.
+This may be used to implement a simple exclusive access locking mechanism.
+If
+.Dv O_EXCL
+is set and the last component of the pathname is
+a symbolic link,
+.Fn open
+will fail even if the symbolic
+link points to a non-existent name.
+.Pp
+If the
+.Dv O_NONBLOCK
+flag is specified, do not wait for the device or file to be ready or
+available.
+If the
+.Fn open
+call would result
+in the process being blocked for some reason (e.g., waiting for
+carrier on a dialup line),
+.Fn open
+returns immediately.
+This flag also has the effect of making all subsequent I/O on the open file non-blocking.
+.Pp
+When opening a file, a lock with
+.Xr flock 2
+semantics can be obtained by setting
+.Dv O_SHLOCK
+for a shared lock, or
+.Dv O_EXLOCK
+for an exclusive lock.
+If creating a file with
+.Dv O_CREAT ,
+the request for the lock will never fail
+(provided that the underlying filesystem supports locking).
+.Pp
+If
+.Fn open
+is successful, the file pointer used to mark the current position within
+the file is set to the beginning of the file.
+.Pp
+When a new file is created it is given the group of the directory
+which contains it.
+.Pp
+The new descriptor is set to remain open across
+.Xr execve 2
+system calls; see
+.Xr close 2
+and
+.Xr fcntl 2 .
+.Pp
+The system imposes a limit on the number of file descriptors
+open simultaneously by one process.
+Calling
+.Xr getdtablesize 3
+returns the current system limit.
+.Sh RETURN VALUES
+If successful,
+.Fn open
+returns a non-negative integer, termed a file descriptor.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The named file is opened unless:
+.Bl -tag -width Er
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix,
+the required permissions (for reading and/or writing)
+are denied for the given flags, or
+.Dv O_CREAT
+is specified,
+the file does not exist,
+and the directory in which it is to be created
+does not permit writing.
+.It Bq Er EDQUOT
+.Dv O_CREAT
+is specified,
+the file does not exist,
+and the directory in which the entry for the new file
+is being placed cannot be extended because the
+user's quota of disk blocks on the file system
+containing the directory has been exhausted; or
+.Dv O_CREAT
+is specified,
+the file does not exist,
+and the user's quota of inodes on the file system on
+which the file is being created has been exhausted.
+.It Bq Er EEXIST
+.Dv O_CREAT
+and
+.Dv O_EXCL
+were specified and the file exists.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.It Bq Er EFTYPE
+.Dv O_NOFOLLOW
+was specified, but the last path component is a symlink.
+.Em Note :
+.St -p1003.1-2008
+specifies returning
+.Bq Er ELOOP
+for this case.
+.It Bq Er EINTR
+The
+.Fn open
+operation was interrupted by a signal.
+.It Bq Er EIO
+An I/O error occurred while making the directory entry or
+allocating the inode for
+.Dv O_CREAT .
+.It Bq Er EISDIR
+The named file is a directory, and the arguments specify
+it is to be opened for writing.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EMFILE
+The process has already reached its limit for open file descriptors.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENFILE
+The system file table is full.
+.It Bq Er ENOENT
+.Dv O_CREAT
+is not set and the named file does not exist, or
+a component of the path name that must exist does not exist.
+.It Bq Er ENOSPC
+.Dv O_CREAT
+is specified,
+the file does not exist,
+and the directory in which the entry for the new file is being placed
+cannot be extended because there is no space left on the file
+system containing the directory; or
+.Dv O_CREAT
+is specified,
+the file does not exist,
+and there are no free inodes on the file system on which the
+file is being created.
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory; or
+.Dv O_DIRECTORY
+is specified and the last path component is not a directory.
+.It Bq Er ENXIO
+The named file is a character special or block
+special file, and the device associated with this special file
+does not exist, or
+the named file is a
+.Tn FIFO ,
+.Dv O_NONBLOCK
+and
+.Dv O_WRONLY
+is set and no process has the file open for reading.
+.It Bq Er EOPNOTSUPP
+.Dv O_SHLOCK
+or
+.Dv O_EXLOCK
+is specified but the underlying filesystem does not support locking; or
+an attempt was made to open a socket (not currently implemented).
+.It Bq Er EPERM
+The file's flags (see
+.Xr chflags 2 )
+don't allow the file to be opened.
+.It Bq Er EROFS
+The named file resides on a read-only file system,
+and the file is to be modified.
+.It Bq Er ETXTBSY
+The file is a pure procedure (shared text) file that is being
+executed and the
+.Fn open
+call requests write access.
+.El
+.Sh SEE ALSO
+.Xr chmod 2 ,
+.Xr close 2 ,
+.Xr dup 2 ,
+.Xr lseek 2 ,
+.Xr read 2 ,
+.Xr umask 2 ,
+.Xr write 2 ,
+.Xr getdtablesize 3
+.Sh STANDARDS
+The
+.Fn open
+function conforms to
+.St -p1003.1-90 .
+The
+.Fa flags
+values
+.Dv O_DSYNC ,
+.Dv O_SYNC
+and
+.Dv O_RSYNC
+are extensions defined in
+.St -p1003.1b-93 .
+.Pp
+The
+.Dv O_SHLOCK
+and
+.Dv O_EXLOCK
+flags are non-standard extensions and should not be used if portability
+is of concern.
+.Sh HISTORY
+An
+.Fn open
+function call appeared in
+.At v2 .
diff --git a/lib/nbsd_libc/sys/pathconf.2 b/lib/nbsd_libc/sys/pathconf.2
new file mode 100644 (file)
index 0000000..e0fc456
--- /dev/null
@@ -0,0 +1,190 @@
+.\"    $NetBSD: pathconf.2,v 1.27 2010/07/26 12:30:16 njoly Exp $
+.\"
+.\" Copyright (c) 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.
+.\" 3. 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.
+.\"
+.\"    @(#)pathconf.2  8.1 (Berkeley) 6/4/93
+.\"
+.Dd July 26, 2010
+.Dt PATHCONF 2
+.Os
+.Sh NAME
+.Nm pathconf ,
+.Nm fpathconf
+.Nd get configurable pathname variables
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft long
+.Fn pathconf "const char *path" "int name"
+.Ft long
+.Fn fpathconf "int fd" "int name"
+.Sh DESCRIPTION
+The
+.Fn pathconf
+and
+.Fn fpathconf
+functions provide a method for applications to determine the current
+value of a configurable system limit or option variable associated
+with a pathname or file descriptor.
+.Pp
+For
+.Nm pathconf ,
+the
+.Fa path
+argument is the name of a file or directory.
+For
+.Nm fpathconf ,
+the
+.Fa fd
+argument is an open file descriptor.
+The
+.Fa name
+argument specifies the system variable to be queried.
+Symbolic constants for each name value are found in the
+.In unistd.h
+header.
+.Pp
+The available values are as follows:
+.Pp
+.Bl -tag -width "123456"
+.It Li _PC_LINK_MAX
+The maximum file link count.
+.It Li _PC_MAX_CANON
+The maximum number of bytes in terminal canonical input line.
+.It Li _PC_MAX_INPUT
+The minimum maximum number of bytes for which space is available in
+a terminal input queue.
+.It Li _PC_NAME_MAX
+The maximum number of bytes in a filename,
+not including a terminating null character.
+.It Li _PC_PATH_MAX
+The maximum number of bytes in a pathname,
+including the terminating null character.
+.It Li _PC_PIPE_BUF
+The maximum number of bytes which will be written atomically to a pipe.
+.It Li _PC_CHOWN_RESTRICTED
+Return 1 if appropriate privileges are required for the
+.Xr chown 2
+system call, otherwise 0.
+.It Li _PC_NO_TRUNC
+Return 0 if filenames longer than
+.Brq Dv NAME_MAX
+are silently truncated, or non-zero if an error is generated when
+.Brq Dv NAME_MAX
+is exceeded.
+.It Li _PC_VDISABLE
+Returns the terminal character disabling value.
+.It Li _PC_SYNC_IO
+Returns 1 if synchronized I/O is supported, otherwise 0.
+.It Li _PC_FILESIZEBITS
+If the maximum size file that could ever exist on the mounted file system is
+.Dv maxsize ,
+then the returned value is 2 plus the floor of the base 2 logarithm of
+.Dv maxsize .
+.It Li _PC_SYMLINK_MAX
+The maximum number of bytes in a symbolic link.
+.It Li _PC_2_SYMLINKS
+When referring to a directory the system supports the creation of symbolic
+links within that directory; for nondirectory files, the meaning of
+.Dv {_PC_2_SYMLINKS}
+is undefined.
+.El
+.Sh RETURN VALUES
+If the call to
+.Nm pathconf
+or
+.Nm fpathconf
+is not successful, \-1 is returned and
+.Va errno
+is set appropriately.
+Otherwise, if the variable is associated with functionality that does
+not have a limit in the system, \-1 is returned and
+.Va errno
+is not modified.
+Otherwise, the current variable value is returned.
+.Sh ERRORS
+If any of the following conditions occur, the
+.Nm pathconf
+and
+.Nm fpathconf
+functions shall return \-1 and set
+.Va errno
+to the corresponding value.
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The value of the
+.Fa name
+argument is invalid, or
+the implementation does not support an association of the variable
+name with the associated file.
+.El
+.Pp
+.Fn pathconf
+will fail if:
+.Bl -tag -width ENAMETOOLONGAA
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded 255 characters,
+or an entire path name exceeded 1023 characters.
+.It Bq Er ENOENT
+The named file does not exist.
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.El
+.Pp
+.Fn fpathconf
+will fail if:
+.Bl -tag -width [EFAULT]
+.It Bq Er EBADF
+.Fa fd
+is not a valid open file descriptor.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.El
+.Sh SEE ALSO
+.Xr sysctl 3
+.Sh STANDARDS
+The
+.Fn pathconf
+and
+.Fn fpathconf
+functions conform to
+.St -p1003.1-90 .
+.Sh HISTORY
+The
+.Nm pathconf
+and
+.Nm fpathconf
+functions first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/sys/pipe.2 b/lib/nbsd_libc/sys/pipe.2
new file mode 100644 (file)
index 0000000..98dac5a
--- /dev/null
@@ -0,0 +1,119 @@
+.\"    $NetBSD: pipe.2,v 1.22 2004/05/13 10:20:58 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)pipe.2     8.1 (Berkeley) 6/4/93
+.\"
+.Dd July 17, 1994
+.Dt PIPE 2
+.Os
+.Sh NAME
+.Nm pipe
+.Nd create descriptor pair for interprocess communication
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn pipe "int fildes[2]"
+.Sh DESCRIPTION
+The
+.Fn pipe
+function
+creates a
+.Em pipe ,
+which is an object allowing
+unidirectional data flow,
+and allocates a pair of file descriptors.
+The first descriptor connects to the
+.Em read end
+of the pipe,
+and the second connects to the
+.Em write end  ,
+so that data written to
+.Fa fildes[1]
+appears on (i.e., can be read from)
+.Fa fildes[0] .
+This allows the output of one program to be
+sent
+to another program:
+the source's standard output is set up to be
+the write end of the pipe,
+and the sink's standard input is set up to be
+the read end of the pipe.
+The pipe itself persists until all its associated descriptors are
+closed.
+.Pp
+A pipe whose read or write end has been closed is considered
+.Em widowed .
+Writing on such a pipe causes the writing process to receive
+a
+.Dv SIGPIPE
+signal.
+Widowing a pipe is the only way to deliver end-of-file to a reader:
+after the reader consumes any buffered data, reading a widowed pipe
+returns a zero count.
+.Sh RETURN VALUES
+On successful creation of the pipe, zero is returned.
+Otherwise, a value of \-1 is returned and the variable
+.Va errno
+set to indicate the
+error.
+.Sh ERRORS
+The
+.Fn pipe
+call will fail if:
+.Bl -tag -width Er
+.It Bq Er EMFILE
+Too many descriptors are active.
+.It Bq Er ENFILE
+The system file table is full.
+.It Bq Er EFAULT
+The
+.Fa fildes
+buffer is in an invalid area of the process's address space.
+The reliable detection of this error cannot be guaranteed; when not
+detected, a signal may be delivered to the process, indicating an
+address violation.
+.El
+.Sh SEE ALSO
+.Xr sh 1 ,
+.Xr fork 2 ,
+.Xr read 2 ,
+.Xr socketpair 2 ,
+.Xr write 2
+.Sh STANDARDS
+The
+.Fn pipe
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+A
+.Fn pipe
+function call appeared in
+.At v6 .
diff --git a/lib/nbsd_libc/sys/pmc_control.2 b/lib/nbsd_libc/sys/pmc_control.2
new file mode 100644 (file)
index 0000000..352e789
--- /dev/null
@@ -0,0 +1,236 @@
+.\" $NetBSD: pmc_control.2,v 1.7 2005/10/31 11:34:16 wiz Exp $
+.\"
+.\" Copyright (c) 2002 Wasabi Systems, Inc.
+.\" All rights reserved.
+.\"
+.\" Written by Allen Briggs for Wasabi Systems, 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. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"      This product includes software developed for the NetBSD Project by
+.\"      Wasabi Systems, Inc.
+.\" 4. The name of Wasabi Systems, Inc. may not be used to endorse
+.\"    or promote products derived from this software without specific prior
+.\"    written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC
+.\" 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.
+.\"
+.Dd October 27, 2005
+.Dt PMC_CONTROL 2
+.Os
+.Sh NAME
+.Nm pmc_control ,
+.Nm pmc_get_info
+.Nd Hardware Performance Monitoring Interface
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/pmc.h
+.Ft int
+.Fn pmc_control "int ctr" "int op" "void *argp"
+.Ft int
+.Fn pmc_get_info "int ctr" "int op" "void *argp"
+.Sh DESCRIPTION
+.Fn pmc_get_info
+returns the number of counters in the system or information on a specified
+counter
+.Fa ctr .
+The possible values for
+.Fa op
+are:
+.Bl -tag -width width
+.It Dv PMC_INFO_NCOUNTERS
+When querying the number of counters in the system,
+.Fa ctr
+is ignored and
+.Fa argp
+is of type
+.Ft int * .
+Upon return, the integer pointed to by
+.Fa argp
+will contain the number of counters that are available in the system.
+.It Dv PMC_INFO_CPUCTR_TYPE
+When querying the type of a counter in the system,
+.Fa ctr
+refers to the counter being queried, and
+.Fa argp
+is of type
+.Ft int * .
+Upon return, the integer pointed to by
+.Fa argp
+will contain the implementation-dependent type of the specified counter.
+.Pp
+If
+.Fa ctr
+is \-1, the integer pointed to by
+.Fa argp
+will contain the machine-dependent type
+describing the CPU or counter configuration.
+.It Dv PMC_INFO_COUNTER_VALUE
+When querying the value of a counter in the system,
+.Fa ctr
+refers to the counter being queried, and
+.Fa argp
+is of type
+.Ft uint64_t * .
+Upon return, the 64-bit integer pointed to by
+.Fa argp
+will contain the value of the specified counter.
+.It Dv PMC_INFO_ACCUMULATED_COUNTER_VALUE
+When querying the value of a counter in the system,
+.Fa ctr
+refers to the counter being queried, and
+.Fa argp
+is of type
+.Ft uint64_t * .
+Upon return, the 64-bit integer pointed to by
+.Fa argp
+will contain the sum of the accumulated values of specified counter in
+all exited subprocesses of the current process.
+.El
+.Pp
+.Fn pmc_control
+manipulates the specified counter
+.Fa ctr
+in one of several fashions.
+The
+.Fa op
+parameter determines the action taken by the kernel and also the interpretation of the
+.Fa argp
+parameter.
+The possible values for
+.Fa op
+are:
+.Bl -tag -width width
+.It Dv PMC_OP_START
+Starts the specified
+.Fa ctr
+running.
+It must be preceded by a call with
+.Dv PMC_OP_CONFIGURE .
+.Fa argp
+is ignored in this case and may be
+.Dv NULL .
+.It Dv PMC_OP_STOP
+Stops the specified
+.Fa ctr
+from running.
+.Fa argp
+is ignored in this case and may be
+.Dv NULL .
+.It Dv PMC_OP_CONFIGURE
+Configures the specified
+.Fa ctr
+prior to running.
+.Fa argp
+is a pointer to a
+.Ft struct pmc_counter_cfg .
+.Bd -literal
+       struct pmc_counter_cfg {
+               pmc_evid_t      event_id;
+               pmc_ctr_t       reset_value;
+               uint32_t        flags;
+       };
+.Ed
+.Bl -tag -width width
+.It Dv event_id
+is the event ID to be counted.
+.It Dv reset_value
+is a value to which the counter should be reset on overflow (if supported
+by the implementation).
+This is most useful when profiling (see
+.Dv PMC_OP_PROFSTART ,
+below).
+This value is defined to be the number of counter ticks before
+the next overflow.
+So, to get a profiling tick on every hundredth data cache miss, set the
+.Dv event_id
+to the proper value for
+.Dq dcache-miss
+and set
+.Dv reset_value
+to 100.
+.It Dv flags
+Currently unused.
+.El
+.It Dv PMC_OP_PROFSTART
+Configures the specified
+.Fa ctr
+for use in profiling.
+.Fa argp
+is a pointer to a
+.Ft struct pmc_counter_cfg
+as in
+.Dv PMC_OP_CONFIGURE ,
+above.
+This request allocates a kernel counter, which will fail if any
+process is using the requested counter.
+Not all implementations or counters may support this option.
+.It Dv PMC_OP_PROFSTOP
+Stops the specified
+.Fa ctr
+from being used for profiling.
+.Fa argp
+is ignored in this case and may be
+.Dv NULL .
+.El
+.Sh RETURN VALUES
+A return value of 0 indicates that the call succeeded.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+Among the possible error codes from
+.Fn pmc_control
+and
+.Fn pmc_get_info
+are
+.Bl -tag -width Er
+.It Bq Er EFAULT
+The address specified for the
+.Fa argp
+is invalid.
+.It Bq Er ENXIO
+Specified counter is not yet configured.
+.It Bq Er EINPROGRESS
+.Dv PMC_OP_START
+was passed for a counter that is already running.
+.It Bq Er EINVAL
+Specified counter was invalid.
+.It Bq Er EBUSY
+If the requested counter is already in use--either by the current process
+or by the kernel.
+.It Bq Er ENODEV
+If and only if the specified counter event is not valid for the specified
+counter when configuring a counter or starting profiling.
+.It Bq Er ENOMEM
+If the kernel is unable to allocate memory.
+.El
+.Sh SEE ALSO
+.Xr pmc 1 ,
+.Xr pmc 9
+.Sh HISTORY
+The
+.Fn pmc_control
+and
+.Fn pmc_get_info
+system calls appeared in
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/sys/poll.2 b/lib/nbsd_libc/sys/poll.2
new file mode 100644 (file)
index 0000000..bfc3ccf
--- /dev/null
@@ -0,0 +1,246 @@
+.\"    $NetBSD: poll.2,v 1.28 2010/03/22 19:30:55 joerg Exp $
+.\"
+.\" Copyright (c) 1998, 2005 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Charles M. Hannum.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd September 8, 2006
+.Dt POLL 2
+.Os
+.Sh NAME
+.Nm poll, pollts
+.Nd synchronous I/O multiplexing
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In poll.h
+.Ft int
+.Fn poll "struct pollfd *fds" "nfds_t nfds" "int timeout"
+.In poll.h
+.In signal.h
+.In time.h
+.Ft int
+.Fn pollts "struct pollfd * restrict fds" "nfds_t nfds" "const struct timespec * restrict ts" "const sigset_t * restrict sigmask"
+.Sh DESCRIPTION
+.Fn poll
+and
+.Fn pollts
+examine a set of file descriptors to see if some of them are ready for
+I/O.
+The
+.Fa fds
+argument is a pointer to an array of pollfd structures as defined in
+.In poll.h
+(shown below).
+The
+.Fa nfds
+argument determines the size of the
+.Fa fds
+array.
+.Bd -literal
+struct pollfd {
+    int    fd;       /* file descriptor */
+    short  events;   /* events to look for */
+    short  revents;  /* events returned */
+};
+.Ed
+.Pp
+The fields of
+.Fa struct pollfd
+are as follows:
+.Bl -tag -width XXXrevents
+.It fd
+File descriptor to poll.
+If the value in
+.Em fd
+is negative, the file descriptor is ignored and
+.Em revents
+is set to 0.
+.It events
+Events to poll for.
+(See below.)
+.It revents
+Events which may occur.
+(See below.)
+.El
+.Pp
+The event bitmasks in
+.Fa events
+and
+.Fa revents
+have the following bits:
+.Bl -tag -width XXXPOLLWRNORM
+.It POLLIN
+Data other than high priority data may be read without blocking.
+.It POLLRDNORM
+Normal data may be read without blocking.
+.It POLLRDBAND
+Data with a non-zero priority may be read without blocking.
+.It POLLPRI
+High priority data may be read without blocking.
+.It POLLOUT
+Normal data may be written without blocking.
+.It POLLWRNORM
+Equivalent to
+POLLOUT.
+.It POLLWRBAND
+Data with a non-zero priority may be written without blocking.
+.It POLLERR
+An exceptional condition has occurred on the device or socket.
+This flag is always checked, even if not present in the
+.Fa events
+bitmask.
+.It POLLHUP
+The device or socket has been disconnected.
+This flag is always
+checked, even if not present in the
+.Fa events
+bitmask.
+Note that
+POLLHUP
+and
+POLLOUT
+should never be present in the
+.Fa revents
+bitmask at the same time.
+If the remote end of a socket is closed,
+.Fn poll
+returns a
+POLLIN
+event, rather than a
+POLLHUP.
+.It POLLNVAL
+The file descriptor is not open.
+This flag is always checked, even
+if not present in the
+.Fa events
+bitmask.
+.El
+.Pp
+If
+.Fa timeout
+is neither zero nor INFTIM (\-1), it specifies a maximum interval to
+wait for any file descriptor to become ready, in milliseconds.
+If
+.Fa timeout
+is INFTIM (\-1), the poll blocks indefinitely.
+If
+.Fa timeout
+is zero, then
+.Fn poll
+will return without blocking.
+.Pp
+If
+.Fa ts
+is a non-null pointer, it references a timespec structure which specifies a
+maximum interval to wait for any file descriptor to become ready.
+If
+.Fa ts
+is a null pointer,
+.Fn pollts
+blocks indefinitely.
+If
+.Fa ts
+is a non-null pointer, referencing a zero-valued timespec structure, then
+.Fn pollts
+will return without blocking.
+.Pp
+If
+.Fa sigmask
+is a non-null pointer, then the
+.Fn pollts
+function shall replace the signal mask of the caller by the set of
+signals pointed to by
+.Fa sigmask
+before examining the descriptors, and shall restore the signal mask
+of the caller before returning.
+.Sh RETURN VALUES
+.Fn poll
+returns the number of descriptors that are ready for I/O, or \-1 if an
+error occurred.
+If the time limit expires,
+.Fn poll
+returns 0.
+If
+.Fn poll
+returns with an error,
+including one due to an interrupted call,
+the
+.Fa fds
+array will be unmodified.
+.Sh COMPATIBILITY
+This implementation differs from the historical one in that a given
+file descriptor may not cause
+.Fn poll
+to return with an error.
+In cases where this would have happened in the historical implementation
+(e.g. trying to poll a
+.Xr revoke 2 Ns d
+descriptor), this implementation instead copies the
+.Fa events
+bitmask to the
+.Fa revents
+bitmask.
+Attempting to perform I/O on this descriptor will then return an error.
+This behaviour is believed to be more useful.
+.Sh ERRORS
+An error return from
+.Fn poll
+indicates:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+.Fa fds
+points outside the process's allocated address space.
+.It Bq Er EINTR
+A signal was delivered before the time limit expired and
+before any of the selected events occurred.
+.It Bq Er EINVAL
+The specified time limit is negative.
+.El
+.Sh SEE ALSO
+.Xr accept 2 ,
+.Xr connect 2 ,
+.Xr read 2 ,
+.Xr recv 2 ,
+.Xr select 2 ,
+.Xr send 2 ,
+.Xr write 2
+.Sh HISTORY
+The
+.Fn poll
+function appeared in
+.At V.3 .
+The
+.Fn pollts
+function first appeared in
+.Nx 3.0 .
+.Sh BUGS
+The distinction between some of the fields in the
+.Fa events
+and
+.Fa revents
+bitmasks is really not useful without STREAMS.
+The fields are defined for compatibility with existing software.
diff --git a/lib/nbsd_libc/sys/posix_fadvise.2 b/lib/nbsd_libc/sys/posix_fadvise.2
new file mode 100644 (file)
index 0000000..9190fe7
--- /dev/null
@@ -0,0 +1,102 @@
+.\"    $NetBSD: posix_fadvise.2,v 1.3 2009/06/09 11:21:33 yamt Exp $
+.\"
+.\" Copyright (c)2006,2009 YAMAMOTO Takashi,
+.\" 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.
+.\"
+.\" ------------------------------------------------------------
+.Dd June 9, 2009
+.Dt POSIX_FADVISE 2
+.Os
+.Sh NAME
+.Nm posix_fadvise
+.Nd hint at the future access pattern of a file
+.\" ------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ------------------------------------------------------------
+.Sh SYNOPSIS
+.In sys/fcntl.h
+.Ft int
+.Fn posix_fadvise "int fd" "off_t offset" "off_t size" "int hint"
+.\" ------------------------------------------------------------
+.Sh DESCRIPTION
+.Fn posix_fadvise
+hints at the application's access pattern to the file and range
+given by
+the file descriptor,
+.Fa fd ,
+and
+.Fa offset
+and
+.Fa size .
+If
+.Fa size
+is zero, it means to the end of file.
+.Pp
+.Fa hint
+should be one of the followings.
+.Pp
+.Bl -tag -offset indent -width POSIX_FADV_SEQUENTIAL -compact
+.It POSIX_FADV_NORMAL
+No hint.
+(default)
+.It POSIX_FADV_RANDOM
+Random access.
+.It POSIX_FADV_SEQUENTIAL
+Sequential access.
+(from lower offset to higher offset.)
+.It POSIX_FADV_WILLNEED
+Will be accessed.
+.It POSIX_FADV_DONTNEED
+Will not be accessed.
+.It POSIX_FADV_NOREUSE
+Will be accessed just once.
+.El
+.Pp
+Calling
+.Fn posix_fadvise
+doesn't alter the semantics of the operations,
+it is only a matter of performance.
+.\" ------------------------------------------------------------
+.Sh RETURN VALUES
+On success,
+.Fn posix_fadvise
+returns 0.
+Otherwise, it returns an error number.
+.\" ------------------------------------------------------------
+.Sh SEE ALSO
+.Xr errno 2 ,
+.Xr madvise 2
+.\" ------------------------------------------------------------
+.Sh BUGS
+For
+.Dv POSIX_FADV_NORMAL ,
+.Dv POSIX_FADV_RANDOM ,
+and
+.Dv POSIX_FADV_SEQUENTIAL ,
+the current implementation ignores
+.Fa offset
+and
+.Fa size ,
+and applies the hint to the whole file.
diff --git a/lib/nbsd_libc/sys/posix_fadvise.c b/lib/nbsd_libc/sys/posix_fadvise.c
new file mode 100644 (file)
index 0000000..d27ed15
--- /dev/null
@@ -0,0 +1,40 @@
+/* $NetBSD: posix_fadvise.c,v 1.2 2008/04/28 20:23:00 martin Exp $ */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Martin Husemann <martin@NetBSD.org>.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/fcntl.h>
+
+int __posix_fadvise50(int fd, int pad, off_t offset, off_t size, int hint);
+
+int
+posix_fadvise(int fd, off_t offset, off_t size, int hint)
+{
+       return __posix_fadvise50(fd, 0, offset, size, hint);
+}
diff --git a/lib/nbsd_libc/sys/posix_madvise.c b/lib/nbsd_libc/sys/posix_madvise.c
new file mode 100644 (file)
index 0000000..c16ba6e
--- /dev/null
@@ -0,0 +1,36 @@
+/*     $NetBSD: posix_madvise.c,v 1.1 2008/04/22 10:42:16 rmind Exp $  */
+
+/*
+ * Copyright (c) 2008, Mindaugas Rasiukevicius <rmind at NetBSD org>
+ * 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.
+ */
+
+#include <sys/mman.h>
+
+int
+posix_madvise(void *addr, size_t len, int advice)
+{
+
+       return madvise(addr, len, advice);
+}
diff --git a/lib/nbsd_libc/sys/pread.c b/lib/nbsd_libc/sys/pread.c
new file mode 100644 (file)
index 0000000..d8352f4
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: pread.c,v 1.9 2007/11/22 21:11:31 dsl Exp $    */
+
+/*
+ * Copyright (c) 1992, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: pread.c,v 1.9 2007/11/22 21:11:31 dsl Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(pread,_sys_pread)
+__weak_alias(_pread,_sys_pread)
+#endif
+#ifdef __lint__
+#define _sys_pread pread
+#endif
+
+ssize_t         _sys_pread(int, void *, size_t, off_t);
+ssize_t         __pread(int, void *, size_t, int, off_t);
+
+/*
+ * This function provides 64-bit offset padding that
+ * is not supplied by GCC 1.X but is supplied by GCC 2.X.
+ */
+ssize_t
+_sys_pread(int fd, void *buf, size_t nbyte, off_t offset)
+{
+
+       return __pread(fd, buf, nbyte, 0, offset);
+}
diff --git a/lib/nbsd_libc/sys/preadv.c b/lib/nbsd_libc/sys/preadv.c
new file mode 100644 (file)
index 0000000..e09d173
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: preadv.c,v 1.6 2007/11/23 12:39:15 uebayasi Exp $      */
+
+/*
+ * Copyright (c) 1992, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: preadv.c,v 1.6 2007/11/23 12:39:15 uebayasi Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <sys/uio.h>
+#include <unistd.h>
+
+ssize_t __preadv(int, const struct iovec *, int, int, off_t);
+
+/*
+ * This function provides 64-bit offset padding that
+ * is not supplied by GCC 1.X but is supplied by GCC 2.X.
+ */
+ssize_t
+preadv(fd, iovp, iovcnt, offset)
+       int fd;
+       const struct iovec *iovp;
+       int iovcnt;
+       off_t offset;
+{
+
+       return __preadv(fd, iovp, iovcnt, 0, offset);
+}
diff --git a/lib/nbsd_libc/sys/profil.2 b/lib/nbsd_libc/sys/profil.2
new file mode 100644 (file)
index 0000000..e628d17
--- /dev/null
@@ -0,0 +1,132 @@
+.\"    $NetBSD: profil.2,v 1.13 2003/08/07 16:44:04 agc Exp $
+.\"
+.\" Copyright (c) 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Donn Seeley of BSDI.
+.\"
+.\" 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. 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.
+.\"
+.\"    @(#)profil.2    8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt PROFIL 2
+.Os
+.Sh NAME
+.Nm profil
+.Nd control process profiling
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn profil "char *samples" "size_t size" "u_long offset" "u_int scale"
+.Sh DESCRIPTION
+The
+.Fn profil
+function enables or disables
+program counter profiling of the current process.
+If profiling is enabled,
+then at every clock tick,
+the kernel updates an appropriate count in the
+.Fa samples
+buffer.
+.Pp
+The buffer
+.Fa samples
+contains
+.Fa size
+bytes and is divided into
+a series of 16-bit bins.
+Each bin counts the number of times the program counter
+was in a particular address range in the process
+when a clock tick occurred while profiling was enabled.
+For a given program counter address,
+the number of the corresponding bin is given
+by the relation:
+.Bd -literal -offset indent
+[(pc - offset) / 2] * scale / 65536
+.Ed
+.Pp
+The
+.Fa offset
+parameter is the lowest address at which
+the kernel takes program counter samples.
+The
+.Fa scale
+parameter ranges from 1 to 65536 and
+can be used to change the span of the bins.
+A scale of 65536 maps each bin to 2 bytes of address range;
+a scale of 32768 gives 4 bytes, 16384 gives 8 bytes and so on.
+Intermediate values provide approximate intermediate ranges.
+A
+.Fa scale
+value of 0 disables profiling.
+.Sh RETURN VALUES
+If the
+.Fa scale
+value is nonzero and the buffer
+.Fa samples
+contains an illegal address,
+.Fn profil
+returns \-1,
+profiling is terminated and
+.Va errno
+is set appropriately.
+Otherwise
+.Fn profil
+returns 0.
+.Sh FILES
+.Bl -tag -width /usr/lib/gcrt0.o -compact
+.It Pa /usr/lib/gcrt0.o
+profiling C run-time startup file
+.It Pa gmon.out
+conventional name for profiling output file.
+This may be different if the PROFDIR environment variable is set.
+.El
+.Sh ERRORS
+The following error may be reported:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+The buffer
+.Fa samples
+contains an invalid address.
+.El
+.Sh SEE ALSO
+.Xr gprof 1 ,
+.Xr moncontrol 3
+.\" .Sh HISTORY
+.\" wish I knew...  probably v7.
+.Sh BUGS
+This routine should be named
+.Fn profile .
+.Pp
+The
+.Fa samples
+argument should really be a vector of type
+.Fa "unsigned short" .
+.Pp
+The format of the gmon.out file is undocumented.
diff --git a/lib/nbsd_libc/sys/ptrace.2 b/lib/nbsd_libc/sys/ptrace.2
new file mode 100644 (file)
index 0000000..25c501b
--- /dev/null
@@ -0,0 +1,600 @@
+.\"    $NetBSD: ptrace.2,v 1.34 2010/04/14 08:57:21 jruoho Exp $
+.\"
+.\" This file is in the public domain.
+.Dd April 14, 2010
+.Dt PTRACE 2
+.Os
+.Sh NAME
+.Nm ptrace
+.Nd process tracing and debugging
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/ptrace.h
+.Ft int
+.Fn ptrace "int request" "pid_t pid" "void *addr" "int data"
+.Sh DESCRIPTION
+.Fn ptrace
+provides tracing and debugging facilities.
+It allows one process (the
+.Em tracing
+process) to control another (the
+.Em traced
+process).
+Most of the time, the traced process runs normally, but when
+it receives a signal
+.Po
+see
+.Xr sigaction 2
+.Pc ,
+it stops.
+The tracing process is expected to notice this via
+.Xr wait 2
+or the delivery of a
+.Dv SIGCHLD
+signal, examine the state of the stopped process, and cause it to
+terminate or continue as appropriate.
+.Fn ptrace
+is the mechanism by which all this happens.
+.Pp
+The
+.Fa request
+argument specifies what operation is being performed; the meaning of
+the rest of the arguments depends on the operation, but except for one
+special case noted below, all
+.Fn ptrace
+calls are made by the tracing process, and the
+.Fa pid
+argument specifies the process ID of the traced process.
+.Fa request
+can be:
+.Bl -tag -width 12n
+.It Dv PT_TRACE_ME
+This request is the only one used by the traced process; it declares
+that the process expects to be traced by its parent.
+All the other arguments are ignored.
+(If the parent process does not expect to trace
+the child, it will probably be rather confused by the results; once the
+traced process stops, it cannot be made to continue except via
+.Fn ptrace . )
+When a process has used this request and calls
+.Xr execve 2
+or any of the routines built on it
+.Po
+such as
+.Xr execv 3
+.Pc ,
+it will stop before executing the first instruction of the new image.
+Also, any setuid or setgid bits on the executable being executed will
+be ignored.
+.It Dv PT_READ_I , Dv PT_READ_D
+These requests read a single
+.Li int
+of data from the traced process' address space.
+Traditionally,
+.Fn ptrace
+has allowed for machines with distinct address spaces for instruction
+and data, which is why there are two requests: conceptually,
+.Dv PT_READ_I
+reads from the instruction space and
+.Dv PT_READ_D
+reads from the data space.
+In the current
+.Nx
+implementation, these
+two requests are completely identical.
+The
+.Fa addr
+argument specifies the address (in the traced process' virtual address
+space) at which the read is to be done.
+This address does not have to meet any alignment constraints.
+The value read is returned as the return value from
+.Eo \&
+.Fn ptrace
+.Ec .
+.It Dv PT_WRITE_I , Dv PT_WRITE_D
+These requests parallel
+.Dv PT_READ_I
+and
+.Dv PT_READ_D ,
+except that they write rather than read.
+The
+.Fa data
+argument supplies the value to be written.
+.\" .It Dv PT_READ_U
+.\" This request reads an
+.\" .Li int
+.\" from the traced process' user structure.
+.\" The
+.\" .Fa addr
+.\" argument specifies the location of the int relative to the base of the
+.\" user structure; it will usually be an integer value cast to
+.\" .Li caddr_t
+.\" either explicitly or via the presence of a prototype for
+.\" .Eo \&
+.\" .Fn ptrace
+.\" .Ec .
+.\" Unlike
+.\" .Dv PT_READ_I
+.\" and
+.\" .Dv PT_READ_D ,
+.\" .Fa addr
+.\" must be aligned on an
+.\" .Li int
+.\" boundary.
+.\" The value read is returned as the return value from
+.\" .Eo \&
+.\" .Fn ptrace
+.\" .Ec .
+.\" .It Dv PT_WRITE_U
+.\" This request writes an
+.\" .Li int
+.\" into the traced process' user structure.
+.\" .Fa addr
+.\" specifies the offset, just as for
+.\" .Dv PT_READ_U ,
+.\" and
+.\" .Fa data
+.\" specifies the value to be written, just as for
+.\" .Dv PT_WRITE_I
+.\" and
+.\" .Dv PT_WRITE_D .
+.It Dv PT_CONTINUE
+The traced process continues execution.
+.Fa addr
+is an address specifying the place where execution is to be resumed (a
+new value for the program counter), or
+.Li (caddr_t)1
+to indicate that execution is to pick up where it left off.
+.Fa data
+provides a signal number to be delivered to the traced process as it
+resumes execution, or 0 if no signal is to be sent.
+If a negative value is supplied, that is the negative of the LWP
+ID of the thread to be resumed, and only that thread executes.
+.It Dv PT_KILL
+The traced process terminates, as if
+.Dv PT_CONTINUE
+had been used with
+.Dv SIGKILL
+given as the signal to be delivered.
+.It Dv PT_ATTACH
+This request allows a process to gain control of an otherwise unrelated
+process and begin tracing it.
+It does not need any cooperation from the to-be-traced process.
+In this case,
+.Fa pid
+specifies the process ID of the to-be-traced process, and the other two
+arguments are ignored.
+This request requires that the target process
+must have the same real UID as the tracing process, and that it must
+not be executing a setuid or setgid executable.
+(If the tracing process is running as root,
+these restrictions do not apply.)
+The tracing process will see the newly-traced process stop and may then
+control it as if it had been traced all along.
+.Pp
+Three other restrictions apply to all tracing processes, even those
+running as root.
+First, no process may trace a system process.
+Second, no process may trace the process running
+.Xr init 8 .
+Third, if a process has its root directory set with
+.Xr chroot 2 ,
+it may not trace another process unless that process's root directory
+is at or below the tracing process's root.
+.It Dv PT_DETACH
+This request is like PT_CONTINUE, except that after it
+succeeds, the traced process is no longer traced and continues
+execution normally.
+.It Dv PT_IO
+This request is a more general interface that can be used instead of
+.Dv PT_READ_D ,
+.Dv PT_WRITE_D ,
+.Dv PT_READ_I ,
+and
+.Dv PT_WRITE_I .
+The I/O request is encoded in a
+.Dq Li "struct ptrace_io_desc"
+defined as:
+.Bd -literal -offset indent
+struct ptrace_io_desc {
+       int     piod_op;
+       void    *piod_offs;
+       void    *piod_addr;
+       size_t  piod_len;
+};
+.Ed
+.Pp
+where
+.Fa piod_offs
+is the offset within the traced process where the I/O operation should
+take place,
+.Fa piod_addr
+is the buffer in the tracing process, and
+.Fa piod_len
+is the length of the I/O request.
+The
+.Fa piod_op
+field specifies which type of I/O operation to perform.
+Possible values are:
+.Pp
+.Bl -tag -width 18n -offset indent -compact
+.It Dv PIOD_READ_D
+.It Dv PIOD_WRITE_D
+.It Dv PIOD_READ_I
+.It Dv PIOD_WRITE_I
+.El
+.Pp
+See the description of
+.Dv PT_READ_I
+for the difference between I and D spaces.
+A pointer to the I/O descriptor is passed in the
+.Fa addr
+argument to
+.Fn ptrace .
+On return, the
+.Fa piod_len
+field in the I/O descriptor will be updated with the actual number of
+bytes transferred.
+If the requested I/O could not be successfully performed,
+.Fn ptrace
+will return
+.Li \-1
+and set
+.Va errno .
+.It Dv PT_DUMPCORE
+Makes the process specified in the
+.Fa pid
+pid generate a core dump.
+The
+.Fa addr
+argument should contain the name of the core file to be generated
+and the
+.Fa data
+argument should contain the length of the core filename.
+This
+.Nm
+call currently does not stop the child process so it can generate
+inconsistent data.
+.It Dv PT_LWPINFO
+Returns information about a thread from the list of threads for the
+process specified in the
+.Fa pid
+argument.
+The
+.Fa addr
+argument should contain a
+.Dq Li "struct ptrace_lwpinfo"
+defined as:
+.Bd -literal -offset indent
+struct ptrace_lwpinfo {
+       lwpid_t pl_lwpid;
+       int pl_event;
+};
+.Ed
+.Pp
+where
+.Fa pl_lwpid
+contains a thread LWP ID.
+Information is returned for the thread following the one with the
+specified ID in the process thread list, or for the first thread
+if
+.Fa pl_lwpid
+is 0.
+Upon return
+.Fa pl_lwpid
+contains the LWP ID of the thread that was found, or 0 if there is
+no thread after the one whose LWP ID was supplied in the call.
+.Fa pl_event
+contains the event that stopped the thread.
+Possible values are:
+.Pp
+.Bl -tag -width 30n -offset indent -compact
+.It Dv PL_EVENT_NONE
+.It Dv PL_EVENT_SIGNAL
+.El
+.Pp
+The
+.Fa data
+argument should contain
+.Dq Li "sizeof(struct ptrace_lwpinfo)" .
+.It Dv PT_SYSCALL
+Stops a process before and after executing each system call.
+.El
+.Pp
+Additionally, the following requests exist but are
+not available on all machine architectures.
+The file
+.In machine/ptrace.h
+lists which requests exist on a given machine.
+.Bl -tag -width 12n
+.It Dv PT_STEP
+Execution continues as in request PT_CONTINUE; however
+as soon as possible after execution of at least one
+instruction, execution stops again.
+If the
+.Fa data
+argument is greater than 0, it contains the LWP ID of the thread to be
+stepped, and any other threads are continued.
+If the
+.Fa data
+argument is less than zero, it contains the negative of the LWP ID of
+the thread to be stepped, and only that thread executes.
+.It Dv PT_GETREGS
+This request reads the traced process' machine registers into the
+.Dq Li "struct reg"
+(defined in
+.In machine/reg.h )
+pointed to by
+.Fa addr .
+The
+.Fa data
+argument contains the LWP ID of the thread whose registers are to
+be read.
+If zero is supplied, the first thread of the process is read.
+.It Dv PT_SETREGS
+This request is the converse of
+.Dv PT_GETREGS ;
+it loads the traced process' machine registers from the
+.Dq Li "struct reg"
+(defined in
+.In machine/reg.h )
+pointed to by
+.Fa addr .
+The
+.Fa data
+argument contains the LWP ID of the thread whose registers are to
+be written.
+If zero is supplied, the first thread of the process is written.
+.It Dv PT_GETFPREGS
+This request reads the traced process' floating-point registers into
+the
+.Dq Li "struct fpreg"
+(defined in
+.In machine/reg.h )
+pointed to by
+.Fa addr .
+The
+.Fa data
+argument contains the LWP ID of the thread whose registers are to
+be read.
+If zero is supplied, the first thread of the process is read.
+.It Dv PT_SETFPREGS
+This request is the converse of
+.Dv PT_GETFPREGS ;
+it loads the traced process' floating-point registers from the
+.Dq Li "struct fpreg"
+(defined in
+.In machine/reg.h )
+pointed to by
+.Fa addr .
+The
+.Fa data
+argument contains the LWP ID of the thread whose registers are to
+be written.
+If zero is supplied, the first thread of the process is written.
+.\" .It Dv PT_SYSCALL
+.\" This request is like
+.\" .Dv PT_CONTINUE
+.\" except that the process will stop next time it executes any system
+.\" call.
+.\" Information about the system call can be examined with
+.\" .Dv PT_READ_U
+.\" and potentially modified with
+.\" .Dv PT_WRITE_U
+.\" through the
+.\" .Li u_kproc.kp_proc.p_md
+.\" element of the user structure (see below).
+.\" If the process is continued
+.\" with another
+.\" .Dv PT_SYSCALL
+.\" request, it will stop again on exit from the syscall, at which point
+.\" the return values can be examined and potentially changed.
+.\" The
+.\" .Li u_kproc.kp_proc.p_md
+.\" element is of type
+.\" .Dq Li "struct mdproc" ,
+.\" which should be declared by including
+.\" .In sys/param.h ,
+.\" .In sys/user.h ,
+.\" and
+.\" .In machine/proc.h ,
+.\" and contains the following fields (among others):
+.\" .Bl -item -compact -offset indent
+.\" .It
+.\" .Li syscall_num
+.\" .It
+.\" .Li syscall_nargs
+.\" .It
+.\" .Li syscall_args[8]
+.\" .It
+.\" .Li syscall_err
+.\" .It
+.\" .Li syscall_rv[2]
+.\" .El
+.\" When a process stops on entry to a syscall,
+.\" .Li syscall_num
+.\" holds the number of the syscall,
+.\" .Li syscall_nargs
+.\" holds the number of arguments it expects, and
+.\" .Li syscall_args
+.\" holds the arguments themselves.
+.\" (Only the first
+.\" .Li syscall_nargs
+.\" elements of
+.\" .Li syscall_args
+.\" are guaranteed to be useful.)
+.\" When a process stops on exit from a syscall,
+.\" .Li syscall_num
+.\" is
+.\" .Eo \&
+.\" .Li \-1
+.\" .Ec ,
+.\" .Li syscall_err
+.\" holds the error number
+.\" .Po
+.\" see
+.\" .Xr errno 2
+.\" .Pc ,
+.\" or 0 if no error occurred, and
+.\" .Li syscall_rv
+.\" holds the return values.
+.\" (If the syscall returns only one value, only
+.\" .Li syscall_rv[0]
+.\" is useful.)
+.\" The tracing process can modify any of these with
+.\" .Dv PT_WRITE_U ;
+.\" only some modifications are useful.
+.\" .Pp
+.\" On entry to a syscall,
+.\" .Li syscall_num
+.\" can be changed, and the syscall actually performed will correspond to
+.\" the new number (it is the responsibility of the tracing process to fill
+.\" in
+.\" .Li syscall_args
+.\" appropriately for the new call, but there is no need to modify
+.\" .Eo \&
+.\" .Li syscall_nargs
+.\" .Ec ).
+.\" If the new syscall number is 0, no syscall is actually performed;
+.\" instead,
+.\" .Li syscall_err
+.\" and
+.\" .Li syscall_rv
+.\" are passed back to the traced process directly (and therefore should be
+.\" filled in).
+.\" If the syscall number is otherwise out of range, a dummy
+.\" syscall which simply produces an
+.\" .Er ENOSYS
+.\" error is effectively performed.
+.\" .Pp
+.\" On exit from a syscall, only
+.\" .Li syscall_err
+.\" and
+.\" .Li syscall_rv
+.\" can usefully be changed; they are set to the values returned by the
+.\" syscall and will be passed back to the traced process by the normal
+.\" syscall return mechanism.
+.It Dv PT_DUMPCORE
+Cause the traced process to dump core.
+If the
+.Fa addr
+argument is not
+.Dv NULL
+it is taken to be the pathname of the core file to be generated and the
+.Fa data
+argument should contain the length of the pathname.
+The pathname may contain
+.Dv %
+patterns that are expanded as described in
+.Xr sysctl 8 .
+If the
+.Fa data
+argument is
+.Dv NULL ,
+the default core file path generation rules are followed.
+.El
+.Sh ERRORS
+Some requests can cause
+.Fn ptrace
+to return
+.Li \-1
+as a non-error value; to disambiguate,
+.Va errno
+can be set to 0 before the call and checked afterwards.
+The possible errors are:
+.Bl -tag -width "[EINVAL]"
+.It Bq Er EAGAIN
+Process is currently exec'ing and cannot be traced.
+.It Bq Er EBUSY
+.Bl -bullet -compact
+.It
+.Dv PT_ATTACH
+was attempted on a process that was already being traced.
+.It
+A request attempted to manipulate a process that was being traced by
+some process other than the one making the request.
+.It
+A request (other than
+.Dv PT_ATTACH )
+specified a process that wasn't stopped.
+.El
+.It Bq Er EINVAL
+.Bl -bullet -compact
+.It
+A process attempted to use
+.Dv PT_ATTACH
+on itself.
+.It
+The
+.Fa request
+was not a legal request on this machine architecture.
+.\" .It
+.\" The
+.\" .Fa addr
+.\" to
+.\" .Dv PT_READ_U
+.\" or
+.\" .Dv PT_WRITE_U
+.\" was not
+.\" .Li int Ns \&-aligned.
+.It
+The signal number (in
+.Fa data )
+to
+.Dv PT_CONTINUE
+.\" or
+.\" .Dv PT_SYSCALL
+was neither 0 nor a legal signal number.
+.It
+.Dv PT_GETREGS ,
+.Dv PT_SETREGS ,
+.Dv PT_GETFPREGS ,
+or
+.Dv PT_SETFPREGS
+was attempted on a process with no valid register set.
+(This is normally true only of system processes.)
+.El
+.It Bq Er EPERM
+.Bl -bullet -compact
+.It
+A request (other than
+.Dv PT_ATTACH )
+attempted to manipulate a process that wasn't being traced at all.
+.It
+An attempt was made to use
+.Dv PT_ATTACH
+on a process in violation of the requirements listed under
+.Dv PT_ATTACH
+above.
+.El
+.It Bq Er ESRCH
+No process having the specified process ID exists.
+.El
+.Sh SEE ALSO
+.Xr sigaction 2 ,
+.Xr signal 7
+.Sh BUGS
+On the SPARC, the PC is set to the provided PC value for
+.Dv PT_CONTINUE
+and similar calls,
+but the NPC is set willy-nilly to 4 greater than the PC value.
+Using
+.Dv PT_GETREGS
+and
+.Dv PT_SETREGS
+to modify the PC, passing
+.Li (caddr_t)1
+to
+.Eo \&
+.Fn ptrace
+.Ec ,
+should be able to sidestep this.
+.\" .Pp
+.\" When using
+.\" .Dv PT_SYSCALL ,
+.\" there is no easy way to tell whether the traced process stopped because
+.\" it made a syscall or because a signal was sent at a moment that it just
+.\" happened to have valid-looking garbage in its
+.\" .Dq Li "struct mdproc" .
diff --git a/lib/nbsd_libc/sys/pwrite.c b/lib/nbsd_libc/sys/pwrite.c
new file mode 100644 (file)
index 0000000..2a7b233
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: pwrite.c,v 1.9 2007/11/22 21:11:32 dsl Exp $   */
+
+/*
+ * Copyright (c) 1992, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: pwrite.c,v 1.9 2007/11/22 21:11:32 dsl Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(pwrite,_sys_pwrite)
+__weak_alias(_pwrite,_sys_pwrite)
+#endif
+#ifdef __lint__
+#define _sys_pwrite pwrite
+#endif
+
+ssize_t         _sys_pwrite(int, const void *, size_t, off_t);
+ssize_t         __pwrite(int, const void *, size_t, int, off_t);
+
+/*
+ * This function provides 64-bit offset padding that
+ * is not supplied by GCC 1.X but is supplied by GCC 2.X.
+ */
+ssize_t
+_sys_pwrite(int fd, const void *buf, size_t nbyte, off_t offset)
+{
+
+       return __pwrite(fd, buf, nbyte, 0, offset);
+}
diff --git a/lib/nbsd_libc/sys/pwritev.c b/lib/nbsd_libc/sys/pwritev.c
new file mode 100644 (file)
index 0000000..bb7918b
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: pwritev.c,v 1.6 2007/11/23 12:39:16 uebayasi Exp $     */
+
+/*
+ * Copyright (c) 1992, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: pwritev.c,v 1.6 2007/11/23 12:39:16 uebayasi Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <sys/uio.h>
+#include <unistd.h>
+
+ssize_t __pwritev(int, const struct iovec *, int, int, off_t);
+
+/*
+ * This function provides 64-bit offset padding that
+ * is not supplied by GCC 1.X but is supplied by GCC 2.X.
+ */
+ssize_t
+pwritev(fd, iovp, iovcnt, offset)
+       int fd;
+       const struct iovec *iovp;
+       int iovcnt;
+       off_t offset;
+{
+
+       return __pwritev(fd, iovp, iovcnt, 0, offset);
+}
diff --git a/lib/nbsd_libc/sys/quotactl.2 b/lib/nbsd_libc/sys/quotactl.2
new file mode 100644 (file)
index 0000000..b84777e
--- /dev/null
@@ -0,0 +1,213 @@
+.\"    $NetBSD: quotactl.2,v 1.26 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1983, 1990, 1991, 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Robert Elz at The University of Melbourne.
+.\"
+.\" 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. 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.
+.\"
+.\"    @(#)quotactl.2  8.2 (Berkeley) 3/10/95
+.\"
+.Dd October 9, 2008
+.Dt QUOTACTL 2
+.Os
+.Sh NAME
+.Nm quotactl
+.Nd manipulate filesystem quotas
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In ufs/ufs/quota.h
+.Ft int
+.Fn quotactl "const char *path" "int cmd" "int id" "void *addr"
+.Sh DESCRIPTION
+The
+.Fn quotactl
+call enables, disables and
+manipulates filesystem quotas.
+A quota control command
+given by
+.Fa cmd
+operates on the given filename
+.Fa path
+for the given user
+.Fa id .
+The address of an optional command specific data structure,
+.Fa addr ,
+may be given; its interpretation
+is discussed below with each command.
+.Pp
+Currently quotas are supported only for the ``ffs''
+and ``lfs'' filesystem.
+For both of them,
+a command is composed of a primary command (see below)
+and a command type used to interpret the
+.Fa id .
+Types are supported for interpretation of user identifiers
+and group identifiers.
+The ``ffs'' and ``lfs'' specific commands are:
+.Bl -tag -width Q_QUOTAON
+.It Dv Q_QUOTAON
+Enable disk quotas for the filesystem specified by
+.Fa path .
+The command type specifies the type of the quotas being enabled.
+The
+.Fa addr
+argument specifies a file from which to take the quotas.
+The quota file must exist;
+it is normally created with the
+.Xr quotacheck 8
+program.
+The
+.Fa id
+argument is unused.
+Only the super-user may turn quotas on.
+.It Dv Q_QUOTAOFF
+Disable disk quotas for the filesystem specified by
+.Fa path .
+The command type specifies the type of the quotas being disabled.
+The
+.Fa addr
+and
+.Fa id
+arguments are unused.
+Only the super-user may turn quotas off.
+.It Dv Q_GETQUOTA
+Get disk quota limits and current usage for the user or group
+(as determined by the command type) with identifier
+.Fa id .
+.Fa addr
+is a pointer to a
+.Fa struct dqblk
+structure (defined in
+.In ufs/ufs/quota.h ) .
+.It Dv Q_SETQUOTA
+Set disk quota limits for the user or group
+(as determined by the command type) with identifier
+.Fa id .
+.Fa addr
+is a pointer to a
+.Fa struct dqblk
+structure (defined in
+.In ufs/ufs/quota.h ) .
+The usage fields of the
+.Fa dqblk
+structure are ignored.
+This call is restricted to the super-user.
+.It Dv Q_SETUSE
+Set disk usage for the user or group
+(as determined by the command type) with identifier
+.Fa id .
+.Fa addr
+is a pointer to a
+.Fa struct dqblk
+structure (defined in
+.In ufs/ufs/quota.h ) .
+Only the usage fields are used.
+This call is restricted to the super-user.
+.It Dv Q_SYNC
+Update the on-disk copy of quota usages.
+The command type specifies which type of quotas are to be updated.
+The
+.Fa id
+and
+.Fa addr
+parameters are ignored.
+.El
+.Sh RETURN VALUES
+A successful call returns 0,
+otherwise the value \-1 is returned and the global variable
+.Va errno
+indicates the reason for the failure.
+.Sh ERRORS
+A
+.Fn quotactl
+call will fail if:
+.Bl -tag -width Er
+.It Bq Er EOPNOTSUPP
+The kernel has not been compiled with the
+.Dv QUOTA
+option.
+.It Bq Er EUSERS
+The quota table cannot be expanded.
+.It Bq Er EINVAL
+.Fa cmd
+or the command type is invalid.
+.It Bq Er EACCES
+In
+.Dv Q_QUOTAON ,
+the quota file is not a plain file, or
+search permission is denied for a component of a path prefix.
+.It Bq Er ENOTDIR
+A component of a path prefix was not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+A filename does not exist.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating a pathname.
+.It Bq Er EROFS
+In
+.Dv Q_QUOTAON ,
+the quota file resides on a read-only filesystem.
+.It Bq Er EIO
+An
+.Tn I/O
+error occurred while reading from or writing
+to a file containing quotas.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space, or
+an invalid
+.Fa addr
+was supplied; the associated structure could not be copied in or out
+of the kernel.
+.It Bq Er EPERM
+The call was privileged and the caller was not the super-user.
+.El
+.Sh SEE ALSO
+.Xr quota 1 ,
+.Xr fstab 5 ,
+.Xr edquota 8 ,
+.Xr quotacheck 8 ,
+.Xr quotaon 8 ,
+.Xr repquota 8
+.Sh HISTORY
+The
+.Fn quotactl
+function call appeared in
+.Bx 4.3 Reno .
+.Sh BUGS
+There should be some way to integrate this call with the resource
+limit interface provided by
+.Xr setrlimit 2
+and
+.Xr getrlimit 2 .
diff --git a/lib/nbsd_libc/sys/rasctl.2 b/lib/nbsd_libc/sys/rasctl.2
new file mode 100644 (file)
index 0000000..1d1b7e8
--- /dev/null
@@ -0,0 +1,212 @@
+.\"     $NetBSD: rasctl.2,v 1.13 2008/04/29 21:06:28 scw Exp $
+.\"
+.\" Copyright (c) 2002 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Gregory McGarry.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd April 29, 2008
+.Dt RASCTL 2
+.Os
+.Sh NAME
+.Nm rasctl
+.Nd restartable atomic sequences
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/ras.h
+.Ft int
+.Fn rasctl "void *addr" "size_t len" "int op"
+.Sh DESCRIPTION
+Restartable atomic sequences are code sequences which are guaranteed
+to execute without preemption.
+This property is assured by the kernel
+by re-executing a preempted sequence from the start.
+This functionality enables applications to build atomic sequences which,
+when executed to completion, will have executed atomically.
+Restartable atomic sequences are intended to be used on systems that
+do not have hardware support for low-overhead atomic primitives.
+.Pp
+The
+.Nm
+function manipulates a process's set of restartable atomic sequences.
+If a restartable atomic sequence is registered and the process is
+preempted within the range
+.Fa addr
+and
+.Fa addr Ns + Ns Fa len ,
+then the process is resumed at
+.Fa addr .
+.Pp
+As the process execution can be rolled-back, the code in the sequence
+should have no side effects other than a final store at
+.Fa addr Ns + Ns Fa len Ns \-1 .
+The kernel does not guarantee that the sequences are successfully
+restartable.
+It assumes that the application knows what it is doing.
+Restartable atomic sequences should adhere to the following guidelines:
+.Pp
+.Bl -bullet -compact
+.It
+have a single entry point and a single exit point;
+.It
+not execute emulated instructions; and
+.It
+not invoke any functions or system calls.
+.El
+.Pp
+Restartable atomic sequences are inherited from the parent by the
+child during the
+.Xr fork 2
+operation.
+Restartable atomic sequences for a process are removed during
+.Xr exec 3 .
+.Pp
+The operations that can be applied to a restartable atomic sequence
+are specified by the
+.Fa op
+argument.
+Possible operations are:
+.Pp
+.Bl -tag -compact -width RAS_PURGE_ALLXXX
+.It Dv RAS_INSTALL
+Install this sequence.
+.It Dv RAS_PURGE
+Remove the specified registered sequence for this process.
+.It Dv RAS_PURGE_ALL
+Remove all registered sequences for this process.
+.El
+.Pp
+The
+.Dv RAS_PURGE
+and
+.Dv RAS_PURGE_ALL
+operations should be considered to have
+undefined behaviour if there are any other runnable threads in the
+address space which might be executing within the restartable atomic
+sequence(s) at the time of the purge.
+The caller must be responsible for ensuring that there is some form of
+coordination with other threads to prevent unexpected behaviour.
+.Pp
+To preserve the atomicity of sequences, the kernel attempts to protect
+the sequences from alteration by the
+.Xr ptrace 2
+facility.
+.Sh RETURN VALUES
+Upon successful completion,
+.Fn rasctl
+returns zero.
+Otherwise, \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Nm
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+Invalid input was supplied, such as an invalid operation, an invalid
+address, or an invalid length.
+A process may have a finite number of
+atomic sequences that is defined at compile time.
+.It Bq Er EOPNOTSUPP
+Restartable atomic sequences are not supported by the kernel.
+.It Bq Er ESRCH
+Restartable atomic sequence not registered.
+.El
+.Sh SEE ALSO
+.Xr ptrace 2
+.\" .Xr lock 9
+.Sh HISTORY
+The
+.Nm
+functionality first appeared in
+.Nx 2.0
+based on a similar interface that appeared in Mach 2.5.
+.Sh CAVEATS
+Modern compilers reorder instruction sequences to optimize speed.
+The start address and size of a
+.Nm RAS
+need to be protected against this.
+One level of protection is created by compiler dependent instructions,
+abstracted from user level code via the following macros:
+.Bl -tag -width RAS_START(name)
+.It Dv RAS_DECL(name)
+Declares the start and end labels used internally by the
+other macros to mark a
+.Nm RAS .
+The name uniquely identifies the
+.Nm RAS .
+.It Dv RAS_START(name)
+Marks the start of the code.
+Each restart returns to the instruction following this macro.
+.It Dv RAS_END(name)
+Marks the end of the restartable code.
+.It Dv RAS_ADDR(name)
+Returns the start address of a
+.Nm RAS
+and is used to create the first argument to
+.Nm .
+.It Dv RAS_SIZE(name)
+Returns the size of a
+.Nm RAS
+and is used as second argument to
+.Nm .
+.El
+Recent versions of
+.Xr gcc 1
+require the
+.Fl fno-reorder-blocks
+flag to prevent blocks of code wrapped with
+.Dv RAS_START Ns / Ns Dv RAS_END
+being moved outside these labels.
+However, be aware that this may not always be sufficient to prevent
+.Xr gcc 1
+from generating non-restartable code within the
+.Nm RAS
+due to register clobbers.
+It is, therefore, strongly recommended that restartable atomic sequences
+are coded in assembly.
+.Nm RAS
+blocks within assembly code can be specified by using the following macros:
+.Bl -tag -width RAS_START_ASM_HIDDEN(name)
+.It Dv RAS_START_ASM(name)
+Similar to
+.Nm RAS_START
+but for use in assembly source code.
+.It Dv RAS_END_ASM(name)
+Similar to
+.Nm RAS_END
+but for use in assembly source code.
+.It Dv RAS_START_ASM_HIDDEN(name)
+Similar to
+.Nm RAS_START_ASM
+except that the symbol will not be placed in the dynamic symbol table.
+.It Dv RAS_END_ASM_HIDDEN(name)
+Similar to
+.Nm RAS_END_ASM
+except that the symbol will not be placed in the dynamic symbol table.
+.El
diff --git a/lib/nbsd_libc/sys/read.2 b/lib/nbsd_libc/sys/read.2
new file mode 100644 (file)
index 0000000..8891504
--- /dev/null
@@ -0,0 +1,263 @@
+.\"    $NetBSD: read.2,v 1.33 2010/04/05 07:53:47 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)read.2     8.4 (Berkeley) 2/26/94
+.\"
+.Dd April 3, 2010
+.Dt READ 2
+.Os
+.Sh NAME
+.Nm read ,
+.Nm readv ,
+.Nm pread ,
+.Nm preadv
+.Nd read input
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft ssize_t
+.Fn read "int d" "void *buf" "size_t nbytes"
+.Ft ssize_t
+.Fn pread "int d" "void *buf" "size_t nbytes" "off_t offset"
+.In sys/uio.h
+.Ft ssize_t
+.Fn readv "int d" "const struct iovec *iov" "int iovcnt"
+.Ft ssize_t
+.Fn preadv "int d" "const struct iovec *iov" "int iovcnt" "off_t offset"
+.Sh DESCRIPTION
+.Fn read
+attempts to read
+.Fa nbytes
+of data from the object referenced by the descriptor
+.Fa d
+into the buffer pointed to by
+.Fa buf .
+.Fn readv
+performs the same action, but scatters the input data
+into the
+.Fa iovcnt
+buffers specified by the members of the
+.Fa iov
+array: iov[0], iov[1], ..., iov[iovcnt\|\-\|1].
+.Fn pread
+and
+.Fn preadv
+perform the same functions, but read from the specified position in
+the file without modifying the file pointer.
+.Pp
+For
+.Fn readv
+and
+.Fn preadv ,
+the
+.Fa iovec
+structure is defined as:
+.Pp
+.Bd -literal -offset indent -compact
+struct iovec {
+       void *iov_base;
+       size_t iov_len;
+};
+.Ed
+.Pp
+Each
+.Fa iovec
+entry specifies the base address and length of an area
+in memory where data should be placed.
+.Fn readv
+will always fill an area completely before proceeding
+to the next.
+.Pp
+On objects capable of seeking, the
+.Fn read
+starts at a position
+given by the file pointer associated with
+.Fa d
+(see
+.Xr lseek 2 ) .
+Upon return from
+.Fn read ,
+the file pointer is incremented by the number of bytes actually read.
+.Pp
+Objects that are not capable of seeking always read from the current
+position.
+The value of the file pointer associated with such an object is undefined.
+.Pp
+Upon successful completion,
+.Fn read ,
+.Fn readv ,
+.Fn pread ,
+and
+.Fn preadv
+return the number of bytes actually read and placed in the buffer.
+The system guarantees to read the number of bytes requested if
+the descriptor references a normal file that has that many bytes left
+before the end-of-file, but in no other case.
+.Sh RETURN VALUES
+If successful, the
+number of bytes actually read is returned.
+Upon reading end-of-file, zero is returned.
+Otherwise, a \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn read ,
+.Fn readv ,
+.Fn pread ,
+and
+.Fn preadv
+will succeed unless:
+.Bl -tag -width Er
+.It Bq Er EAGAIN
+The file was marked for non-blocking I/O,
+and no data were ready to be read.
+.It Bq Er EBADF
+.Fa d
+is not a valid file or socket descriptor open for reading.
+.It Bq Er EFAULT
+.Fa buf
+points outside the allocated address space.
+.It Bq Er EINTR
+A read from a slow device
+(i.e. one that might block for an arbitrary amount of time)
+was interrupted by the delivery of a signal
+before any data arrived.
+See
+.Xr sigaction 2
+for more information on the interaction between signals and system
+calls.
+.It Bq Er EINVAL
+The file pointer associated with
+.Fa d
+was negative; or
+the total length of the I/O is more than can be expressed by the ssize_t
+return value.
+.It Bq Er EIO
+An I/O error occurred while reading from the file system.
+.El
+.Pp
+In addition,
+.Fn readv
+and
+.Fn preadv
+may return one of the following errors:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+Part of the
+.Fa iov
+points outside the process's allocated address space.
+.It Bq Er EINVAL
+.Fa iovcnt
+was less than or equal to 0, or greater than
+.Dv {IOV_MAX} ;
+or one of the
+.Fa iov_len
+values in the
+.Fa iov
+array was negative; or
+the sum of the
+.Fa iov_len
+values in the
+.Fa iov
+array overflowed a 32-bit integer.
+.El
+.Pp
+The
+.Fn pread
+and
+.Fn preadv
+calls may also return the following errors:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The specified file offset is invalid.
+.It Bq Er ESPIPE
+The file descriptor is associated with a pipe, socket, or FIFO.
+.El
+.Sh SEE ALSO
+.Xr dup 2 ,
+.Xr fcntl 2 ,
+.Xr open 2 ,
+.Xr pipe 2 ,
+.Xr poll 2 ,
+.Xr select 2 ,
+.Xr sigaction 2 ,
+.Xr socket 2 ,
+.Xr socketpair 2
+.Sh STANDARDS
+The
+.Fn read
+function conforms to
+.St -p1003.1-90 .
+The
+.Fn readv
+and
+.Fn pread
+functions conform to
+.St -xpg4.2 .
+.Sh HISTORY
+The
+.Fn preadv
+function call
+appeared in
+.Nx 1.4 .
+The
+.Fn pread
+function call
+appeared in
+.At V.4 .
+The
+.Fn readv
+function call
+appeared in
+.Bx 4.2 .
+The
+.Fn read
+function call appeared in
+.At v2 .
+.Sh CAVEATS
+Error checks should explicitly test for \-1.
+Code such as
+.Bd -literal
+       while ((nr = read(fd, buf, sizeof(buf))) \*[Gt] 0)
+.Ed
+.Pp
+is not maximally portable, as some platforms allow for
+.Va nbytes
+to range between
+.Dv SSIZE_MAX
+and
+.Dv SIZE_MAX
+\- 2, in which case the return value of an error-free
+.Fn read
+may appear as a negative number distinct from \-1.
+Proper loops should use
+.Bd -literal
+       while ((nr = read(fd, buf, sizeof(buf))) != -1 \*[Am]\*[Am] nr != 0)
+.Ed
diff --git a/lib/nbsd_libc/sys/readlink.2 b/lib/nbsd_libc/sys/readlink.2
new file mode 100644 (file)
index 0000000..ac9cc99
--- /dev/null
@@ -0,0 +1,124 @@
+.\"    $NetBSD: readlink.2,v 1.26 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)readlink.2 8.1 (Berkeley) 6/4/93
+.\"
+.Dd May 11, 2004
+.Dt READLINK 2
+.Os
+.Sh NAME
+.Nm readlink
+.Nd read value of a symbolic link
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft ssize_t
+.Fn readlink "const char * restrict path" "char * restrict buf" "size_t bufsiz"
+.Sh DESCRIPTION
+.Fn readlink
+places the contents of the symbolic link
+.Fa path
+in the buffer
+.Fa buf ,
+which has size
+.Fa bufsiz .
+.Fn readlink
+does not append a
+.Dv NUL
+character to
+.Fa buf .
+.Sh RETURN VALUES
+The call returns the count of characters placed in the buffer
+if it succeeds, or a \-1 if an error occurs, placing the error
+code in the global variable
+.Va errno .
+.Sh EXAMPLES
+A typical use is illustrated in the following piece of code
+which reads the contents of a symbolic link named
+.Pa /symbolic/link
+and stores them as null-terminated string:
+.Bd -literal -offset indent
+#include \*[Lt]limits.h\*[Gt]
+#include \*[Lt]unistd.h\*[Gt]
+
+char buf[PATH_MAX];
+ssize_t len;
+
+if ((len = readlink("/symbolic/link", buf, sizeof(buf)-1)) == -1)
+       error handling;
+buf[len] = '\e0';
+.Ed
+.Sh ERRORS
+.Fn readlink
+will fail if:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named file does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EINVAL
+The named file is not a symbolic link.
+.It Bq Er EIO
+An I/O error occurred while reading from the file system.
+.It Bq Er EFAULT
+.Fa buf
+extends outside the process's allocated address space.
+.El
+.Sh SEE ALSO
+.Xr lstat 2 ,
+.Xr stat 2 ,
+.Xr symlink 2 ,
+.Xr symlink 7
+.Sh STANDARDS
+The
+.Fn readlink
+function conforms to
+.St -p1003.1-2001 .
+.Sh HISTORY
+The
+.Fn readlink
+function appeared in
+.Bx 4.2 .
+The type returned was changed from
+.Ft int
+to
+.Ft ssize_t
+in
+.Nx 2.1 .
diff --git a/lib/nbsd_libc/sys/reboot.2 b/lib/nbsd_libc/sys/reboot.2
new file mode 100644 (file)
index 0000000..a748635
--- /dev/null
@@ -0,0 +1,185 @@
+.\"    $NetBSD: reboot.2,v 1.29 2010/03/22 19:30:55 joerg Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)reboot.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd September 4, 2009
+.Dt REBOOT 2
+.Os
+.Sh NAME
+.Nm reboot
+.Nd reboot system or halt processor
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.In sys/reboot.h
+.Ft int
+.Fn reboot "int howto" "char *bootstr"
+.Sh DESCRIPTION
+.Fn reboot
+reboots the system.
+Only the super-user may reboot a machine on demand.
+However, a reboot is invoked
+automatically in the event of unrecoverable system failures.
+.Pp
+.Fa howto
+is a mask of options; the system call interface allows the following
+options, defined in the include file
+.In sys/reboot.h ,
+to be passed
+to the new kernel or the new bootstrap and init programs.
+In addition to the options described below, other options
+described in
+.Xr boothowto 9
+may be set, but such options may be ignored by the system.
+.Pp
+Options can be combined together by OR'ing them, eg.
+.Dv RB_DUMP |
+.Dv RB_NOSYNC
+would be interpreted as
+.Dq dump kernel memory before rebooting and don't sync the disks .
+.Bl -column RB_INITNAMEA 0x0000
+.It Dv RB_AUTOBOOT Ta Li 0x0000 Ta
+The default, causing the system to reboot in its usual fashion.
+.It Dv RB_ASKNAME Ta Li 0x0001 Ta
+Interpreted by the bootstrap program itself, causing it to
+prompt on the console as to what file should be booted.
+Normally, the system is booted from the file
+.Dq Em xx Ns No (0,0)netbsd ,
+where
+.Em xx
+is the default disk name,
+without prompting for the file name.
+.\" Obsolete!
+.\" .It Dv RB_DFLTROOT Ta Li 0x0020 Ta
+.\" Use the compiled in root device.
+.\" Normally, the system uses the device from which it was booted
+.\" as the root device if possible.
+.\" (The default behavior is dependent on the ability of the bootstrap program
+.\" to determine the drive from which it was loaded, which is not possible
+.\" on all systems.)
+.It Dv RB_DUMP Ta Li 0x0100 Ta
+Dump kernel memory before rebooting; see
+.Xr savecore 8
+for more information.
+.It Dv RB_HALT Ta Li 0x0008 Ta
+the processor is simply halted; no reboot takes place.
+This option should be used with caution.
+.It Dv RB_POWERDOWN Ta Li 0x0808 Ta
+This option is always used in conjunction with
+.Dv RB_HALT ,
+and if the system hardware supports the function, the system will be
+powered off, otherwise it has no effect.
+.It Dv RB_INITNAME Ta Li 0x0010 Ta
+An option allowing the specification of an init program (see
+.Xr init 8 )
+other than
+.Pa /sbin/init
+to be run when the system reboots.
+This switch is not currently available.
+.It Dv RB_KDB Ta Li 0x0040 Ta
+Load the symbol table and enable a built-in debugger in the system.
+This option will have no useful function if the kernel is not configured
+for debugging.
+Several other options have different meaning if combined
+with this option, although their use may not be possible
+via the
+.Fn reboot
+call.
+See
+.Xr ddb 4
+for more information.
+.It Dv RB_NOSYNC Ta Li 0x0004 Ta
+Normally, the disks are sync'd (see
+.Xr sync 8 )
+before the processor is halted or rebooted.
+This option may be useful if file system changes have been made manually
+or if the processor is on fire.
+.It Dv RB_RDONLY Ta Li 0x0080 Ta
+Initially mount the root file system read-only.
+This is currently the default, and this option has been deprecated.
+.It Dv RB_SINGLE Ta Li 0x0002 Ta
+Normally, the reboot procedure involves an automatic disk consistency
+check and then multi-user operations.
+.Dv RB_SINGLE
+prevents this, booting the system with a single-user shell
+on the console.
+.Dv RB_SINGLE
+is actually interpreted by the
+.Xr init 8
+program in the newly booted system.
+.Pp
+When no options are given (i.e.,
+.Dv RB_AUTOBOOT
+is used), the system is
+rebooted from file ``netbsd'' in the root file system of unit 0
+of a disk chosen in a processor specific way.
+An automatic consistency check of the disks is normally performed
+(see
+.Xr fsck 8 ) .
+.It Dv RB_STRING Ta Li 0x0400 Ta
+.Fa bootstr
+is a string passed to the firmware on the machine, if possible, if this
+option is set.
+Currently this is only implemented on the sparc and the sun3 ports.
+.It Dv RB_USERCONF Ta Li 0x1000 Ta
+Initially invoke the
+.Xr userconf 4
+facility when the system starts up again, if it has been compiled into
+the kernel that is loaded.
+.El
+.Sh RETURN VALUES
+If successful, this call never returns.
+Otherwise, a \-1 is returned and an error is returned in the global
+variable
+.Va errno .
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EPERM
+The caller is not the super-user.
+.El
+.Sh SEE ALSO
+.Xr ddb 4 ,
+.Xr crash 8 ,
+.Xr halt 8 ,
+.Xr init 8 ,
+.Xr reboot 8 ,
+.Xr savecore 8 ,
+.Xr boothowto 9
+.Sh HISTORY
+The
+.Fn reboot
+function call appeared in
+.Bx 4.0 .
+.Pp
+The
+.Dv RB_DFLTROOT
+option is now
+.Em obsolete .
diff --git a/lib/nbsd_libc/sys/recv.2 b/lib/nbsd_libc/sys/recv.2
new file mode 100644 (file)
index 0000000..134cdb1
--- /dev/null
@@ -0,0 +1,289 @@
+.\"    $NetBSD: recv.2,v 1.27 2006/04/23 19:06:59 wiz Exp $
+.\"
+.\" Copyright (c) 1983, 1990, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)recv.2     8.3 (Berkeley) 2/21/94
+.\"
+.Dd April 23, 2006
+.Dt RECV 2
+.Os
+.Sh NAME
+.Nm recv ,
+.Nm recvfrom ,
+.Nm recvmsg
+.Nd receive a message from a socket
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft ssize_t
+.Fn recv "int s" "void *buf" "size_t len" "int flags"
+.Ft ssize_t
+.Fn recvfrom "int s" "void * restrict buf" "size_t len" "int flags" "struct sockaddr * restrict from" "socklen_t * restrict fromlen"
+.Ft ssize_t
+.Fn recvmsg "int s" "struct msghdr *msg" "int flags"
+.Sh DESCRIPTION
+.Fn recvfrom
+and
+.Fn recvmsg
+are used to receive messages from a socket,
+and may be used to receive data on a socket whether or not
+it is connection-oriented.
+.Pp
+If
+.Fa from
+is non-nil, and the socket is not connection-oriented,
+the source address of the message is filled in.
+.Fa fromlen
+is a value-result parameter, initialized to the size of
+the buffer associated with
+.Fa from ,
+and modified on return to indicate the actual size of the
+address stored there.
+.Pp
+The
+.Fn recv
+call is normally used only on a
+.Em connected
+socket (see
+.Xr connect 2 )
+and is identical to
+.Fn recvfrom
+with a nil
+.Fa from
+parameter.
+As it is redundant, it may not be supported in future releases.
+.Pp
+All three routines return the length of the message on successful
+completion.
+If a message is too long to fit in the supplied buffer,
+excess bytes may be discarded depending on the type of socket
+the message is received from (see
+.Xr socket 2 ) .
+.Pp
+If no messages are available at the socket, the
+receive call waits for a message to arrive, unless
+the socket is nonblocking (see
+.Xr fcntl 2 )
+in which case the value
+\-1 is returned and the external variable
+.Va errno
+set to
+.Er EAGAIN .
+The receive calls normally return any data available,
+up to the requested amount,
+rather than waiting for receipt of the full amount requested;
+this behavior is affected by the socket-level options
+.Dv SO_RCVLOWAT
+and
+.Dv SO_RCVTIMEO
+described in
+.Xr getsockopt 2 .
+.Pp
+The
+.Xr select 2
+or
+.Xr poll 2
+call may be used to determine when more data arrive.
+.Pp
+The
+.Fa flags
+argument to a recv call is formed by
+.Em or Ap ing
+one or more of the values:
+.Bl -column MSG_WAITALL -offset indent
+.It Dv MSG_OOB Ta process out-of-band data
+.It Dv MSG_PEEK Ta peek at incoming message
+.It Dv MSG_WAITALL Ta wait for full request or error
+.El
+The
+.Dv MSG_OOB
+flag requests receipt of out-of-band data
+that would not be received in the normal data stream.
+Some protocols place expedited data at the head of the normal
+data queue, and thus this flag cannot be used with such protocols.
+The
+.Dv MSG_PEEK
+flag causes the receive operation to return data
+from the beginning of the receive queue without removing that
+data from the queue.
+Thus, a subsequent receive call will return the same data.
+The
+.Dv MSG_WAITALL
+flag requests that the operation block until
+the full request is satisfied.
+However, the call may still return less data than requested
+if a signal is caught, an error or disconnect occurs,
+or the next data to be received is of a different type than that returned.
+.Pp
+The
+.Fn recvmsg
+call uses a
+.Fa msghdr
+structure to minimize the number of directly supplied parameters.
+This structure has the following form, as defined in
+.Ao Pa sys/socket.h Ac :
+.Pp
+.Bd -literal
+struct msghdr {
+       void            *msg_name;      /* optional address */
+       socklen_t       msg_namelen;    /* size of address */
+       struct iovec    *msg_iov;       /* scatter/gather array */
+       int             msg_iovlen;     /* # elements in msg_iov */
+       void            *msg_control;   /* ancillary data, see below */
+       socklen_t       msg_controllen; /* ancillary data buffer len */
+       int             msg_flags;      /* flags on received message */
+};
+.Ed
+.Pp
+Here
+.Fa msg_name
+and
+.Fa msg_namelen
+specify the source address if the socket is unconnected;
+.Fa msg_name
+may be given as a null pointer if no names are desired or required.
+If the socket is connected,
+.Fa msg_name
+and
+.Fa msg_namelen
+are ignored.
+.Fa msg_iov
+and
+.Fa msg_iovlen
+describe scatter gather locations, as discussed in
+.Xr read 2 .
+.Fa msg_control ,
+which has length
+.Fa msg_controllen ,
+points to a buffer for other protocol control related messages
+or other miscellaneous ancillary data.
+The messages are of the form:
+.Bd -literal
+struct cmsghdr {
+       socklen_t       cmsg_len;       /* data byte count, including hdr */
+       int             cmsg_level;     /* originating protocol */
+       int             cmsg_type;      /* protocol-specific type */
+/* followed by
+       u_char          cmsg_data[]; */
+};
+.Ed
+As an example, one could use this to learn of changes in the data-stream
+in XNS/SPP, or in ISO, to obtain user-connection-request data by requesting
+a recvmsg with no data buffer provided immediately after an
+.Fn accept
+call.
+.Pp
+Open file descriptors are now passed as ancillary data for
+.Dv AF_LOCAL
+domain sockets, with
+.Fa cmsg_level
+set to
+.Dv SOL_SOCKET
+and
+.Fa cmsg_type
+set to
+.Dv SCM_RIGHTS .
+.Pp
+The
+.Fa msg_flags
+field is set on return according to the message received.
+.Dv MSG_EOR
+indicates end-of-record;
+the data returned completed a record (generally used with sockets of type
+.Dv SOCK_SEQPACKET ) .
+.Dv MSG_TRUNC
+indicates that
+the trailing portion of a datagram was discarded because the datagram
+was larger than the buffer supplied.
+.Dv MSG_CTRUNC
+indicates that some
+control data were discarded due to lack of space in the buffer
+for ancillary data.
+.Dv MSG_OOB
+is returned to indicate that expedited or out-of-band data were received.
+.Sh RETURN VALUES
+These calls return the number of bytes received, or \-1
+if an error occurred.
+.Sh ERRORS
+The calls fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The argument
+.Fa s
+is an invalid descriptor.
+.It Bq Er ENOTCONN
+The socket is associated with a connection-oriented protocol
+and has not been connected (see
+.Xr connect 2
+and
+.Xr accept 2 ) .
+.It Bq Er ENOTSOCK
+The argument
+.Fa s
+does not refer to a socket.
+.It Bq Er EAGAIN
+The socket is marked non-blocking, and the receive operation
+would block, or
+a receive timeout had been set,
+and the timeout expired before data were received.
+.It Bq Er EINTR
+The receive was interrupted by delivery of a signal before
+any data were available.
+.It Bq Er EFAULT
+The receive buffer pointer(s) point outside the process's
+address space.
+.It Bq Er EINVAL
+The total length of the I/O is more than can be expressed by the ssize_t
+return value.
+.El
+.Pp
+.Fn recvmsg
+will also fail if:
+.Bl -tag -width Er
+.It Bq Er EMSGSIZE
+The
+.Fa msg_iovlen
+member of the
+.Fa msg
+structure is less than or equal to 0
+or is greater than
+.Dv {IOV_MAX} .
+.El
+.Sh SEE ALSO
+.Xr fcntl 2 ,
+.Xr getsockopt 2 ,
+.Xr poll 2 ,
+.Xr read 2 ,
+.Xr select 2 ,
+.Xr socket 2
+.Sh HISTORY
+The
+.Fn recv
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/rename.2 b/lib/nbsd_libc/sys/rename.2
new file mode 100644 (file)
index 0000000..f6321fe
--- /dev/null
@@ -0,0 +1,241 @@
+.\"    $NetBSD: rename.2,v 1.23 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)rename.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd December 27, 2005
+.Dt RENAME 2
+.Os
+.Sh NAME
+.Nm rename
+.Nd change the name of a file
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In stdio.h
+.Ft int
+.Fn rename "const char *from" "const char *to"
+.Sh DESCRIPTION
+.Fn rename
+causes the link named
+.Fa from
+to be renamed as
+.Fa to .
+If
+.Fa to
+exists, it is first removed.
+Both
+.Fa from
+and
+.Fa to
+must be of the same type (that is, both directories or both
+non-directories), and must reside on the same file system.
+.Pp
+.Fn rename
+guarantees that an instance of
+.Fa to
+will always exist, even if the system should crash in
+the middle of the operation.
+.Pp
+If the final component of
+.Fa from
+is a symbolic link,
+the symbolic link is renamed,
+not the file or directory to which it points.
+.Pp
+If both
+.Fa from
+and
+.Fa to
+are pathnames of the same existing file in the file system's name space,
+.Fn rename
+returns successfully and performs no other action.
+.Sh RETURN VALUES
+A 0 value is returned if the operation succeeds, otherwise
+.Fn rename
+returns \-1 and the global variable
+.Va errno
+indicates the reason for the failure.
+.Sh ERRORS
+.Fn rename
+will fail and neither of the argument files will be
+affected if:
+.Bl -tag -width Er
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+A component of the
+.Fa from
+path does not exist,
+or a path prefix of
+.Fa to
+does not exist.
+.It Bq Er EACCES
+A component of either path prefix denies search permission, or
+the requested link requires writing in a directory with a mode
+that denies write permission.
+.It Bq Er EPERM
+The directory containing
+.Fa from
+is marked sticky,
+and neither the containing directory nor
+.Fa from
+are owned by the effective user ID.
+Or the
+.Fa to
+file exists,
+the directory containing
+.Fa to
+is marked sticky,
+and neither the containing directory nor
+.Fa to
+are owned by the effective user ID.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating either pathname.
+.It Bq Er ENOTDIR
+A component of either path prefix is not a directory, or
+.Fa from
+is a directory, but
+.Fa to
+is not a directory.
+.It Bq Er EISDIR
+.Fa to
+is a directory, but
+.Fa from
+is not a directory.
+.It Bq Er EXDEV
+The link named by
+.Fa to
+and the file named by
+.Fa from
+are on different logical devices (file systems).
+Note that this error code will not be returned if the implementation
+permits cross-device links.
+.It Bq Er ENOSPC
+The directory in which the entry for the new name is being placed
+cannot be extended because there is no space left on the file
+system containing the directory.
+.It Bq Er EDQUOT
+The directory in which the entry for the new name
+is being placed cannot be extended because the
+user's quota of disk blocks on the file system
+containing the directory has been exhausted.
+.It Bq Er EIO
+An I/O error occurred while making or updating a directory entry.
+.It Bq Er EROFS
+The requested link requires writing in a directory on a read-only file
+system.
+.It Bq Er EFAULT
+.Em Path
+points outside the process's allocated address space.
+.It Bq Er EINVAL
+.Fa from
+is a parent directory of
+.Fa to ,
+or an attempt is made to rename
+.Ql \&.
+or
+.Ql \&.. .
+.It Bq Er ENOTEMPTY
+.Fa to
+is a directory and is not empty.
+.It Bq Er EBUSY
+.Fa from
+or
+.Fa to
+is the mount point for a mounted file system.
+.El
+.Sh SEE ALSO
+.Xr open 2 ,
+.Xr symlink 7
+.Sh STANDARDS
+The
+.Fn rename
+function deviates from the semantics defined in
+.St -p1003.1-90 ,
+which specifies that if both
+.Fa from
+and
+.Fa to
+.Em link
+to the same existing file,
+.Fn rename
+shall return successfully and performs no further action, whereas this
+implementation will remove the file specified by
+.Fa from
+unless both
+.Fa from
+and
+.Fa to
+are pathnames of the same file in the file system's name space.
+.Pp
+To retain conformance, a compatibility interface is provided by the
+.Lb libposix
+which is also be brought into scope if any of the
+.Dv _POSIX_SOURCE ,
+.Dv _POSIX_C_SOURCE
+or
+.Dv _XOPEN_SOURCE
+preprocessor symbols are defined at compile-time:
+the
+.Fn rename
+function conforms to
+.St -p1003.1-90
+and
+.St -xpg4.2 .
+.Sh BUGS
+The system can deadlock if a loop in the file system graph is present.
+This loop takes the form of an entry in directory
+.Ql Pa a ,
+say
+.Ql Pa a/foo ,
+being a hard link to directory
+.Ql Pa b ,
+and an entry in
+directory
+.Ql Pa b ,
+say
+.Ql Pa b/bar ,
+being a hard link
+to directory
+.Ql Pa a .
+When such a loop exists and two separate processes attempt to
+perform
+.Ql rename a/foo b/bar
+and
+.Ql rename b/bar a/foo ,
+respectively,
+the system may deadlock attempting to lock
+both directories for modification.
+Hard links to directories should be
+replaced by symbolic links by the system administrator.
diff --git a/lib/nbsd_libc/sys/revoke.2 b/lib/nbsd_libc/sys/revoke.2
new file mode 100644 (file)
index 0000000..b7f3e28
--- /dev/null
@@ -0,0 +1,107 @@
+.\"    $NetBSD: revoke.2,v 1.12 2003/08/07 16:44:05 agc Exp $
+.\"
+.\" Copyright (c) 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Berkeley Software Design, 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. 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.
+.\"
+.\"     @(#)revoke.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd March 22, 1999
+.Dt REVOKE 2
+.Os
+.Sh NAME
+.Nm revoke
+.Nd revoke file access
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn revoke "const char *path"
+.Sh DESCRIPTION
+The
+.Nm revoke
+function invalidates all current open file descriptors in the system
+for the file named by
+.Fa path .
+Subsequent operations on any such descriptors
+fail, with the exceptions that a
+.Fn read
+from a character device file which has been revoked
+returns a count of zero (end of file),
+and a
+.Fn close
+call will succeed.
+If the file is a special file for a device which is open,
+the device close function
+is called as if all open references to the file had been closed.
+.Pp
+Access to a file may be revoked only by its owner or the super user.
+.Pp
+.Nm revoke
+is normally used to prepare a terminal device for a new login session,
+preventing any access by a previous user of the terminal.
+.Sh RETURN VALUES
+A 0 value indicates that the call succeeded.
+A \-1 return value indicates an error occurred and
+.Va errno
+is set to indicate the reason.
+.Sh ERRORS
+Access to the named file is revoked unless one of the following:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded 255 characters,
+or an entire path name exceeded 1024 characters.
+.It Bq Er ENOENT
+The named file or a component of the path name does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.It Bq Er EPERM
+The caller is neither the owner of the file nor the super user.
+.El
+.Sh SEE ALSO
+.Xr close 2 ,
+.Xr dup 2 ,
+.Xr fcntl 2 ,
+.Xr flock 2 ,
+.Xr fstat 2 ,
+.Xr read 2 ,
+.Xr write 2
+.Sh HISTORY
+The
+.Nm revoke
+function was introduced in
+.Bx 4.3 Reno .
diff --git a/lib/nbsd_libc/sys/rmdir.2 b/lib/nbsd_libc/sys/rmdir.2
new file mode 100644 (file)
index 0000000..354b602
--- /dev/null
@@ -0,0 +1,111 @@
+.\"    $NetBSD: rmdir.2,v 1.20 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)rmdir.2    8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt RMDIR 2
+.Os
+.Sh NAME
+.Nm rmdir
+.Nd remove a directory file
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn rmdir "const char *path"
+.Sh DESCRIPTION
+.Fn rmdir
+removes a directory file
+whose name is given by
+.Fa path .
+The directory must not have any entries other
+than
+.Ql \&.
+and
+.Ql \&.. .
+.Sh RETURN VALUES
+A 0 is returned if the remove succeeds; otherwise a \-1 is
+returned and an error code is stored in the global location
+.Va errno .
+.Sh ERRORS
+The named file is removed unless:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named directory does not exist.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er ENOTEMPTY
+The named directory contains files other than
+.Ql \&.
+and
+.Ql \&..
+in it.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix, or
+write permission is denied on the directory containing the link
+to be removed.
+.It Bq Er EPERM
+The directory containing the directory to be removed is marked sticky,
+and neither the containing directory nor the directory to be removed
+are owned by the effective user ID.
+.It Bq Er EBUSY
+The directory to be removed is the mount point
+for a mounted file system.
+.It Bq Er EIO
+An I/O error occurred while deleting the directory entry
+or deallocating the inode.
+.It Bq Er EROFS
+The directory entry to be removed resides on a read-only file system.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.El
+.Sh SEE ALSO
+.Xr mkdir 2 ,
+.Xr unlink 2
+.Sh STANDARDS
+The
+.Fn rmdir
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+The
+.Fn rmdir
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/sa_enable.2 b/lib/nbsd_libc/sys/sa_enable.2
new file mode 100644 (file)
index 0000000..c125d71
--- /dev/null
@@ -0,0 +1,67 @@
+.\"     $NetBSD: sa_enable.2,v 1.4 2004/03/14 23:05:09 yamt Exp $
+.\"
+.\" Copyright (c)2004 YAMAMOTO Takashi,
+.\" 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.
+.\"
+.\" ------------------------------------------------------------
+.Dd March 14, 2004
+.Dt SA_ENABLE 2
+.Os
+.Sh NAME
+.Nm sa_enable
+.Nd enable scheduler activation
+.\" ------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ------------------------------------------------------------
+.Sh SYNOPSIS
+.In sa.h
+.Ft int
+.Fn sa_enable
+.\" ------------------------------------------------------------
+.Sh DESCRIPTION
+.Fn sa_enable
+is used to enable scheduler activation.
+.Pp
+An upcall handler and upcall stacks should be registered with
+.Fn sa_register
+and
+.Fn sa_stacks
+beforehand.
+.\" ------------------------------------------------------------
+.Sh RETURN VALUES
+On success,
+.Fn sa_enable
+will not return to userland in the normal way.
+It returns into the upcall hander with an
+.Dv SA_UPCALL_NEWPROC
+upcall.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.\" ------------------------------------------------------------
+.Sh SEE ALSO
+.Xr sa_register 2 ,
+.Xr sa_stacks 2 ,
+.Xr pthread 3
diff --git a/lib/nbsd_libc/sys/sa_register.2 b/lib/nbsd_libc/sys/sa_register.2
new file mode 100644 (file)
index 0000000..e66767d
--- /dev/null
@@ -0,0 +1,75 @@
+.\"     $NetBSD: sa_register.2,v 1.2 2004/03/14 10:19:59 snj Exp $
+.\"
+.\" Copyright (c)2004 YAMAMOTO Takashi,
+.\" 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.
+.\"
+.\" ------------------------------------------------------------
+.Dd March 14, 2004
+.Dt SA_REGISTER 2
+.Os
+.Sh NAME
+.Nm sa_register
+.Nd register a scheduler activation upcall handler
+.\" ------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ------------------------------------------------------------
+.Sh SYNOPSIS
+.In sa.h
+.Ft int
+.Fn sa_register \
+    "sa_upcall_t new" \
+    "sa_upcall_t *old" \
+    "int flags" \
+    "ssize_t stackinfo_offset"
+.\" ------------------------------------------------------------
+.Sh DESCRIPTION
+.Nm
+is used to prepare scheduler activation.
+It registers the upcall handler specified by
+.Fa new .
+If
+.Fa old
+isn't
+.Dv NULL ,
+the previous handler will be returned to the location pointed by it.
+If
+.Dv SA_FLAG_STACKINFO
+is specified in
+.Fa flags ,
+.Fa stackinfo_offset
+is used to locate per upcall stack memory areas shared between
+userland and kernel.
+.Fa stackinfo_offset
+is a byte offset from the corresponding upcall stack.
+.\" ------------------------------------------------------------
+.Sh RETURN VALUES
+.Fn sa_register
+returns zero on success.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.\" ------------------------------------------------------------
+.Sh SEE ALSO
+.Xr pthread 3
diff --git a/lib/nbsd_libc/sys/sa_setconcurrency.2 b/lib/nbsd_libc/sys/sa_setconcurrency.2
new file mode 100644 (file)
index 0000000..e2b007f
--- /dev/null
@@ -0,0 +1,70 @@
+.\"     $NetBSD: sa_setconcurrency.2,v 1.4 2005/09/05 21:57:35 yamt Exp $
+.\"
+.\" Copyright (c)2004 YAMAMOTO Takashi,
+.\" 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.
+.\"
+.\" ------------------------------------------------------------
+.Dd September 6, 2005
+.Dt SA_CONCURRENCY 2
+.Os
+.Sh NAME
+.Nm sa_setconcurrency
+.Nd increase the number of virtual processors
+.\" ------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ------------------------------------------------------------
+.Sh SYNOPSIS
+.In sa.h
+.Ft int
+.Fn sa_setconcurrency \
+    "int concurrency"
+.\" ------------------------------------------------------------
+.Sh DESCRIPTION
+.Fn sa_setconcurrency
+is used to increase the number of scheduler activation virtual processors
+used by the process.
+.Fn sa_setconcurrency
+increases the number of virtual processors, i.e., execution concurrency,
+up to
+.Fa concurrency .
+However,
+.Fn sa_setconcurrency
+won't try to allocate more virtual processors than there are physical
+processors on the system.
+.Pp
+Scheduler activation should be enabled by
+.Fn sa_enable
+beforehand.
+.\" ------------------------------------------------------------
+.Sh RETURN VALUES
+On success,
+.Fn sa_setconcurrency
+returns the number of newly added virtual processors.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.\" ------------------------------------------------------------
+.Sh SEE ALSO
+.Xr pthread 3
diff --git a/lib/nbsd_libc/sys/sa_stacks.2 b/lib/nbsd_libc/sys/sa_stacks.2
new file mode 100644 (file)
index 0000000..61ca0e3
--- /dev/null
@@ -0,0 +1,68 @@
+.\"     $NetBSD: sa_stacks.2,v 1.6 2004/12/12 05:56:45 snj Exp $
+.\"
+.\" Copyright (c)2004 YAMAMOTO Takashi,
+.\" 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.
+.\"
+.\" ------------------------------------------------------------
+.Dd December 12, 2004
+.Dt SA_STACKS 2
+.Os
+.Sh NAME
+.Nm sa_stacks
+.Nd register scheduler activation upcall stacks
+.\" ------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ------------------------------------------------------------
+.Sh SYNOPSIS
+.In sa.h
+.Ft int
+.Fn sa_stacks \
+    "int num" \
+    "stack_t *stacks"
+.\" ------------------------------------------------------------
+.Sh DESCRIPTION
+.Fn sa_stacks
+is used to register scheduler activation upcall stacks.
+.Fa stacks
+is an array of
+.Fa num
+of
+.Vt stack_t .
+.Pp
+An upcall handler should be registered by
+.Fn sa_register
+beforehand.
+.\" ------------------------------------------------------------
+.Sh RETURN VALUES
+On success,
+.Fn sa_stacks
+returns the number of stacks registered.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.\" ------------------------------------------------------------
+.Sh SEE ALSO
+.Xr sa_register 2 ,
+.Xr pthread 3
diff --git a/lib/nbsd_libc/sys/sa_yield.2 b/lib/nbsd_libc/sys/sa_yield.2
new file mode 100644 (file)
index 0000000..4e8f80b
--- /dev/null
@@ -0,0 +1,64 @@
+.\"     $NetBSD: sa_yield.2,v 1.4 2004/05/09 11:28:58 yamt Exp $
+.\"
+.\" Copyright (c)2004 YAMAMOTO Takashi,
+.\" 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.
+.\"
+.\" ------------------------------------------------------------
+.Dd May 9, 2004
+.Dt SA_YIELD 2
+.Os
+.Sh NAME
+.Nm sa_yield
+.Nd idle a virtual processor
+.\" ------------------------------------------------------------
+.Sh LIBRARY
+.Lb libc
+.\" ------------------------------------------------------------
+.Sh SYNOPSIS
+.In sa.h
+.Ft int
+.Fn sa_yield
+.\" ------------------------------------------------------------
+.Sh DESCRIPTION
+.Fn sa_yield
+is used to idle a virtual processor on which the calling thread is running.
+It's typically used when the process's userland scheduler has no userland
+thread to run.
+.Pp
+Scheduler activation should be enabled by
+.Fn sa_enable
+beforehand.
+.\" ------------------------------------------------------------
+.Sh RETURN VALUES
+On success,
+.Fn sa_yield
+will not return to userland in the normal way.
+It returns into an upcall hander with an upcall.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.\" ------------------------------------------------------------
+.Sh SEE ALSO
+.Xr sa_enable 2 ,
+.Xr pthread 3
diff --git a/lib/nbsd_libc/sys/sched.c b/lib/nbsd_libc/sys/sched.c
new file mode 100644 (file)
index 0000000..3d143db
--- /dev/null
@@ -0,0 +1,147 @@
+/*     $NetBSD: sched.c,v 1.2 2008/10/31 00:29:19 rmind Exp $  */
+
+/*
+ * Copyright (c) 2008, Mindaugas Rasiukevicius <rmind at NetBSD org>
+ * 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.
+ */
+
+#include <sys/cdefs.h>
+__RCSID("$NetBSD: sched.c,v 1.2 2008/10/31 00:29:19 rmind Exp $");
+
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sched.h>
+#include <sys/param.h>
+#include <sys/types.h>
+
+/* All LWPs in the process */
+#define        P_ALL_LWPS              0
+
+/*
+ * Scheduling parameters.
+ */
+
+int
+sched_setparam(pid_t pid, const struct sched_param *param)
+{
+       struct sched_param sp;
+
+       memset(&sp, 0, sizeof(struct sched_param));
+       sp.sched_priority = param->sched_priority;
+       return _sched_setparam(pid, P_ALL_LWPS, SCHED_NONE, &sp);
+}
+
+int
+sched_getparam(pid_t pid, struct sched_param *param)
+{
+
+       return _sched_getparam(pid, P_ALL_LWPS, NULL, param);
+}
+
+int
+sched_setscheduler(pid_t pid, int policy, const struct sched_param *param)
+{
+       struct sched_param sp;
+       int ret, old_policy;
+
+       ret = _sched_getparam(pid, P_ALL_LWPS, &old_policy, &sp);
+       if (ret < 0)
+               return ret;
+
+       memset(&sp, 0, sizeof(struct sched_param));
+       sp.sched_priority = param->sched_priority;
+       ret = _sched_setparam(pid, P_ALL_LWPS, policy, &sp);
+       if (ret < 0)
+               return ret;
+
+       return old_policy;
+}
+
+int
+sched_getscheduler(pid_t pid)
+{
+       struct sched_param sp;
+       int ret, policy;
+
+       ret = _sched_getparam(pid, P_ALL_LWPS, &policy, &sp);
+       if (ret < 0)
+               return ret;
+
+       return policy;
+}
+
+/*
+ * Scheduling priorities.
+ */
+
+int
+sched_get_priority_max(int policy)
+{
+
+       if (policy < SCHED_OTHER || policy > SCHED_RR) {
+               errno = EINVAL;
+               return -1;
+       }
+       return sysconf(_SC_SCHED_PRI_MAX);
+}
+
+int
+sched_get_priority_min(int policy)
+{
+
+       if (policy < SCHED_OTHER || policy > SCHED_RR) {
+               errno = EINVAL;
+               return -1;
+       }
+       return sysconf(_SC_SCHED_PRI_MIN);
+}
+
+int
+/*ARGSUSED*/
+sched_rr_get_interval(pid_t pid, struct timespec *interval)
+{
+
+       interval->tv_sec = 0;
+       interval->tv_nsec = sysconf(_SC_SCHED_RT_TS) * 1000;
+       return 0;
+}
+
+/*
+ * Process affinity.
+ */
+
+int
+sched_getaffinity_np(pid_t pid, size_t size, cpuset_t *cpuset)
+{
+
+       return _sched_getaffinity(pid, P_ALL_LWPS, size, cpuset);
+}
+
+int
+sched_setaffinity_np(pid_t pid, size_t size, cpuset_t *cpuset)
+{
+
+       return _sched_setaffinity(pid, P_ALL_LWPS, size, cpuset);
+}
diff --git a/lib/nbsd_libc/sys/select.2 b/lib/nbsd_libc/sys/select.2
new file mode 100644 (file)
index 0000000..5379c38
--- /dev/null
@@ -0,0 +1,353 @@
+.\"    $NetBSD: select.2,v 1.38 2010/04/05 21:25:56 joerg Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)select.2   8.2 (Berkeley) 3/25/94
+.\"
+.Dd October 18, 2008
+.Dt SELECT 2
+.Os
+.Sh NAME
+.Nm select ,
+.Nm pselect
+.Nd synchronous I/O multiplexing
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/select.h
+.Ft int
+.Fn select "int nfds" "fd_set * restrict readfds" "fd_set * restrict writefds" "fd_set * restrict exceptfds" "struct timeval * restrict timeout"
+.Ft int
+.Fn pselect "int nfds" "fd_set * restrict readfds" "fd_set * restrict writefds" "fd_set * restrict exceptfds" "const struct timespec *restrict timeout" "const sigset_t * restrict sigmask"
+.Fn FD_SET "int fd" "fd_set *fdset"
+.Fn FD_CLR "int fd" "fd_set *fdset"
+.Fn FD_ISSET "int fd" "fd_set *fdset"
+.Fn FD_ZERO "fd_set *fdset"
+.Sh DESCRIPTION
+.Fn select
+and
+.Fn pselect
+examine the I/O descriptor sets whose addresses are passed in
+.Fa readfds ,
+.Fa writefds ,
+and
+.Fa exceptfds
+to see if some of their descriptors
+are ready for reading, are ready for writing, or have an exceptional
+condition pending, respectively.
+The first
+.Fa nfds
+descriptors are checked in each set;
+i.e., the descriptors from 0 through
+.Fa nfds Ns No \-1
+in the descriptor sets are examined.
+This means that
+.Fa nfds
+must be set to the highest file descriptor of the three sets, plus one.
+On return,
+.Fn select
+and
+.Fn pselect
+replace the given descriptor sets
+with subsets consisting of those descriptors that are ready
+for the requested operation.
+.Fn select
+and
+.Fn pselect
+return the total number of ready descriptors in all the sets.
+.Pp
+The descriptor sets are stored as bit fields in arrays of integers.
+The following macros are provided for manipulating such descriptor sets:
+.Fn FD_ZERO fdset
+initializes a descriptor set pointed to by
+.Fa fdset
+to the null set.
+.Fn FD_SET fd fdset
+includes a particular descriptor
+.Fa fd
+in
+.Fa fdset .
+.Fn FD_CLR fd fdset
+removes
+.Fa fd
+from
+.Fa fdset .
+.Fn FD_ISSET fd fdset
+is non-zero if
+.Fa fd
+is a member of
+.Fa fdset ,
+zero otherwise.
+The behavior of these macros is undefined if
+a descriptor value is less than zero or greater than or equal to
+.Dv FD_SETSIZE ,
+which is normally at least equal
+to the maximum number of descriptors supported by the system.
+.Pp
+If
+.Fa timeout
+is a non-null pointer, it specifies a maximum interval to wait for the
+selection to complete.
+If
+.Fa timeout
+is a null pointer, the select blocks indefinitely.
+To poll without blocking, the
+.Fa timeout
+argument should be non-null, pointing to a zero-valued timeval or timespec
+structure, as appropriate.
+.Fa timeout
+is not changed by
+.Fn select ,
+and may be reused on subsequent calls; however, it is good style to
+re-initialize it before each invocation of
+.Fn select .
+.Pp
+If
+.Fa sigmask
+is a non-null pointer, then the
+.Fn pselect
+function shall replace the signal mask of the caller by the set of
+signals pointed to by
+.Fa sigmask
+before examining the descriptors, and shall restore the signal mask
+of the calling thread before returning.
+.Pp
+Any of
+.Fa readfds ,
+.Fa writefds ,
+and
+.Fa exceptfds
+may be given as null pointers if no descriptors are of interest.
+.Sh NOTES
+It is recommended to use the
+.Xr poll 2
+interface instead, which tends to be more portable and efficient.
+.Sh RETURN VALUES
+.Fn select
+returns the number of ready descriptors that are contained in
+the descriptor sets,
+or \-1 if an error occurred.
+If the time limit expires,
+.Fn select
+returns 0.
+If
+.Fn select
+returns with an error,
+including one due to an interrupted call,
+the descriptor sets will be unmodified.
+.Sh EXAMPLES
+.Bd -literal
+#include \*[Lt]stdio.h\*[Gt]
+#include \*[Lt]stdlib.h\*[Gt]
+#include \*[Lt]unistd.h\*[Gt]
+#include \*[Lt]string.h\*[Gt]
+#include \*[Lt]err.h\*[Gt]
+#include \*[Lt]errno.h\*[Gt]
+#include \*[Lt]sys/types.h\*[Gt]
+#include \*[Lt]sys/time.h\*[Gt]
+
+int
+main(int argc, char **argv)
+{
+       fd_set read_set;
+       struct timeval timeout;
+       int ret, fd, i;
+
+       /* file descriptor 1 is stdout */
+       fd = 1;
+
+       /* Wait for ten seconds. */
+       timeout.tv_sec = 10;
+       timeout.tv_usec = 0;
+
+       /* Initialize the read set to null */
+       FD_ZERO(\*[Am]read_set);
+
+       /* Add file descriptor 1 to read_set */
+       FD_SET(fd, \*[Am]read_set);
+
+       /*
+        * Check if data is ready to be readen on
+        * file descriptor 1, give up after 10 seconds.
+        */
+       ret = select(fd + 1, \*[Am]read_set, NULL, NULL, \*[Am]timeout);
+
+       /*
+        * Returned value is the number of file
+        * descriptors ready for I/O, or -1 on error.
+        */
+       switch (ret) {
+       case \-1:
+               err(EXIT_FAILURE, "select() failed");
+               break;
+
+       case 0:
+               printf("Timeout, no data received.\en");
+               break;
+
+       default:
+               printf("Data received on %d file desciptor(s)\en", ret);
+
+               /*
+                * select(2) hands back a file descriptor set where
+                * only descriptors ready for I/O are set. These can
+                * be tested using FD_ISSET
+                */
+               for (i = 0; i \*[Lt]= fd; i++) {
+                       if (FD_ISSET(i, \*[Am]read_set)) {
+                               printf("Data on file descriptor %d\en", i);
+                               /* Remove the file descriptor from the set */
+                               FD_CLR(fd, \*[Am]read_set);
+                       }
+               }
+               break;
+       }
+
+       return 0;
+}
+.Ed
+.Sh ERRORS
+An error return from
+.Fn select
+indicates:
+.Bl -tag -width Er
+.It Bq Er EBADF
+One of the descriptor sets specified an invalid descriptor.
+.It Bq Er EFAULT
+One or more of
+.Fa readfds ,
+.Fa writefds ,
+or
+.Fa exceptfds
+points outside the process's allocated address space.
+.It Bq Er EINTR
+A signal was delivered before the time limit expired and
+before any of the selected events occurred.
+.It Bq Er EINVAL
+The specified time limit is invalid.
+One of its components is negative or too large.
+.El
+.Sh SEE ALSO
+.Xr accept 2 ,
+.Xr connect 2 ,
+.Xr gettimeofday 2 ,
+.Xr poll 2 ,
+.Xr read 2 ,
+.Xr recv 2 ,
+.Xr send 2 ,
+.Xr write 2 ,
+.Xr getdtablesize 3
+.Sh HISTORY
+The
+.Fn select
+function call appeared in
+.Bx 4.2 .
+.Sh BUGS
+Although the provision of
+.Xr getdtablesize 3
+was intended to allow user programs to be written independent
+of the kernel limit on the number of open files, the dimension
+of a sufficiently large bit field for select remains a problem.
+The default bit size of
+.Ft fd_set
+is based on the symbol
+.Dv FD_SETSIZE
+(currently 256),
+but that is somewhat smaller than the current kernel limit
+to the number of open files.
+However, in order to accommodate programs which might potentially
+use a larger number of open files with select, it is possible
+to increase this size within a program by providing
+a larger definition of
+.Dv FD_SETSIZE
+before the inclusion of
+.In sys/types.h .
+The kernel will cope, and the userland libraries provided with the
+system are also ready for large numbers of file descriptors.
+.Pp
+Note:
+.Xr rpc 3
+library uses
+.Ft fd_set
+with the default
+.Dv FD_SETSIZE
+as part of its ABI.
+Therefore, programs that use
+.Xr rpc 3
+routines cannot change
+.Dv FD_SETSIZE .
+.Pp
+Alternatively, to be really safe, it is possible to allocate
+.Ft fd_set
+bit-arrays dynamically.
+The idea is to permit a program to work properly even if it is
+.Xr execve 2 Ns 'd
+with 4000 file descriptors pre-allocated.
+The following illustrates the technique which is used by
+userland libraries:
+.Pp
+.Bd -literal -offset indent -compact
+       fd_set *fdsr;
+       int max = fd;
+
+       fdsr = (fd_set *)calloc(howmany(max+1, NFDBITS),
+           sizeof(fd_mask));
+       if (fdsr == NULL) {
+               ...
+               return (-1);
+       }
+       FD_SET(fd, fdsr);
+       n = select(max+1, fdsr, NULL, NULL, \*[Am]tv);
+       ...
+       free(fdsr);
+.Ed
+.Pp
+.Fn select
+should probably have been designed to return the time remaining from the
+original timeout, if any, by modifying the time value in place.
+Even though some systems stupidly act in this different way, it is
+unlikely this semantic will ever be commonly implemented, as the
+change causes massive source code compatibility problems.
+Furthermore, recent new standards have dictated the current behaviour.
+In general, due to the existence of those
+non-conforming systems, it is unwise to assume that the timeout
+value will be unmodified by the
+.Fn select
+call, and the caller should reinitialize it on each invocation.
+Calculating the delta is easily done by calling
+.Xr gettimeofday 2
+before and after the call to
+.Fn select ,
+and using
+.Fn timersub
+(as described in
+.Xr getitimer 2 ) .
+.Pp
+Internally to the kernel,
+.Fn select
+works poorly if multiple processes wait on the same file descriptor.
diff --git a/lib/nbsd_libc/sys/semctl.2 b/lib/nbsd_libc/sys/semctl.2
new file mode 100644 (file)
index 0000000..99ad0e7
--- /dev/null
@@ -0,0 +1,244 @@
+.\"    $NetBSD: semctl.2,v 1.20 2010/03/22 19:30:55 joerg Exp $
+.\"
+.\" Copyright (c) 1995 Frank van der Linden
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"      This product includes software developed for the NetBSD Project
+.\"      by Frank van der Linden
+.\" 4. 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 ``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 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.
+.\"
+.Dd August 25, 1999
+.Dt SEMCTL 2
+.Os
+.Sh NAME
+.Nm semctl
+.Nd semaphore control operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/sem.h
+.Ft int
+.Fn semctl "int semid" "int semnum" "int cmd" "..."
+.Sh DESCRIPTION
+The
+.Fn semctl
+system call provides a number of control operations on the semaphore specified
+by
+.Fa semnum
+and
+.Fa semid .
+The operation to be performed is specified in
+.Fa cmd
+(see below).
+The fourth argument is optional and depends upon the operation requested.
+If required, it is a union of the following fields:
+.Bd -literal
+    int     val;            /* value for SETVAL */
+    struct  semid_ds *buf;  /* buffer for IPC_{STAT,SET} */
+    u_short *array;         /* array for GETALL \*[Am] SETALL */
+.Ed
+.Pp
+The
+.Sy semid_ds
+structure used in the
+.Dv IPC_SET
+and
+.Dv IPC_STAT
+commands is defined in
+.In sys/sem.h
+and contains the following members:
+.Bd -literal
+    struct ipc_perm sem_perm; /* operation permissions */
+    unsigned short sem_nsems; /* number of sems in set */
+    time_t sem_otime;         /* last operation time */
+    time_t sem_ctime;         /* last change time */
+.Ed
+.Pp
+The
+.Sy ipc_perm
+structure used inside the
+.Sy semid_ds
+structure is defined in
+.In sys/ipc.h
+and contains the following members:
+.Bd -literal
+    uid_t cuid;  /* creator user id */
+    gid_t cgid;  /* creator group id */
+    uid_t uid;  /* user id */
+    gid_t gid;  /* group id */
+    mode_t mode; /* permission (lower 9 bits) */
+.Ed
+.Pp
+.Fn semctl
+provides the following operations:
+.Bl -tag -width IPC_RMIDX
+.It Dv GETVAL
+Return the value of the semaphore.
+.It Dv SETVAL
+Set the value of the semaphore to
+.Fa arg.val ,
+where
+.Fa arg
+is the fourth argument to
+.Fn semctl .
+.It Dv GETPID
+Return the pid of the last process that did an operation on this semaphore.
+.It Dv GETNCNT
+Return the number of processes waiting to acquire the semaphore.
+.It Dv GETZCNT
+Return the number of processes waiting for the value of the semaphore to
+reach 0.
+.It Dv GETALL
+Return the values of all the semaphores associated with
+.Fa semid .
+.It Dv SETALL
+Set the values of all the semaphores that are associated with the semaphore
+identifier
+.Fa semid
+to the corresponding values in
+.Fa arg.array ,
+where
+.Fa arg
+is the fourth argument to
+.Fn semctl .
+.It Dv IPC_STAT
+Gather information about a semaphore and place the information in the
+structure pointed to by
+.Fa arg.buf ,
+where
+.Fa arg
+is the fourth argument to
+.Fn semctl .
+.It Dv IPC_SET
+Set the value of the
+.Va sem_perm.uid ,
+.Va sem_perm.gid
+and
+.Va sem_perm.mode
+fields in the structure associated with the semaphore.
+The values are taken from the corresponding fields in the structure
+pointed to by
+.Fa arg.buf ,
+there
+.Fa arg
+is the fourth argument to
+.Fn semctl .
+This operation can only be executed by the super-user, or a process that
+has an effective user id equal to either
+.Va sem_perm.cuid
+or
+.Va sem_perm.uid
+in the data structure associated with the semaphore.
+.It Dv IPC_RMID
+Remove the semaphores associated with
+.Fa semid
+from the system and destroy the data structures associated with it.
+Only the super-user or a process with an effective uid equal to the
+.Va sem_perm.cuid
+or
+.Va sem_perm.uid
+values in the data structure associated with the semaphore can do this.
+.El
+.Pp
+The permission to read or change a semaphore (see
+.Xr semop 2 )
+is determined by the
+.Va sem_perm.mode
+field in the same way as is
+done with files (see
+.Xr chmod 2 ) ,
+but the effective uid can match either the
+.Va sem_perm.cuid
+field or the
+.Va sem_perm.uid
+field, and the
+effective gid can match either
+.Va sem_perm.cgid
+or
+.Va sem_perm.gid .
+.Sh RETURN VALUES
+For the
+.Dv GETVAL ,
+.Dv GETPID ,
+.Dv GETNCNT ,
+and
+.Dv GETZCNT
+operations,
+.Fn semctl
+returns one of the values described above if successful.
+All other operations will make
+.Fn semctl
+return 0 if no errors occur.
+Otherwise \-1 is returned and
+.Va errno
+set to reflect the error.
+.Sh ERRORS
+.Fn semctl
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+The caller has no operation permission for this semaphore.
+.It Bq Er EFAULT
+.Fa arg.buf
+or
+.Fa arg.array
+specifies an invalid address.
+.It Bq Er EINVAL
+.Fa semid
+is not a valid message semaphore identifier.
+.Pp
+.Va cmd
+is not a valid command.
+.It Bq Er EPERM
+.Fa cmd
+is equal to
+.Dv IPC_SET
+or
+.Dv IPC_RMID
+and the caller is not the super-user, nor does
+the effective uid match either the
+.Va sem_perm.uid
+or
+.Va sem_perm.cuid
+fields of the data structure associated with the semaphore.
+.It Bq Er ERANGE
+.Fa cmd
+is equal to
+.Dv SETVAL
+or
+.Dv SETALL
+and the value to be set is greater than the system semaphore maximum value.
+.El
+.Sh SEE ALSO
+.Xr semget 2 ,
+.Xr semop 2
+.Sh STANDARDS
+The
+.Nm
+system call conforms to
+.St -xsh5 .
+.Sh HISTORY
+Semaphores appeared in the first release of
+.At V .
diff --git a/lib/nbsd_libc/sys/semctl.c b/lib/nbsd_libc/sys/semctl.c
new file mode 100644 (file)
index 0000000..1f96563
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: semctl.c,v 1.15 2009/01/16 00:02:57 christos Exp $     */
+
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: semctl.c,v 1.15 2009/01/16 00:02:57 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/ipc.h>
+#include <sys/sem.h>
+#include <stdarg.h>
+
+/* The kernel version [... == union semun *] */
+int ____semctl50(int, int, int, ...);
+
+int
+semctl(int semid, int semnum, int cmd, ...)
+{
+       va_list ap;
+       union __semun semun;
+
+       va_start(ap, cmd);
+       switch (cmd) {
+       case IPC_SET:
+       case IPC_STAT:
+       case GETALL:
+       case SETVAL:
+       case SETALL:
+#ifdef __lint__
+               memcpy(&semun, &ap, sizeof(semun));
+#else
+               semun = va_arg(ap, union __semun);
+#endif
+       }
+       va_end(ap);
+       return ____semctl50(semid, semnum, cmd, &semun);
+}
diff --git a/lib/nbsd_libc/sys/semget.2 b/lib/nbsd_libc/sys/semget.2
new file mode 100644 (file)
index 0000000..e51548f
--- /dev/null
@@ -0,0 +1,158 @@
+.\"    $NetBSD: semget.2,v 1.18 2006/10/08 08:22:34 rillig Exp $
+.\"
+.\" Copyright (c) 1995 Frank van der Linden
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"      This product includes software developed for the NetBSD Project
+.\"      by Frank van der Linden
+.\" 4. 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 ``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 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.
+.\"
+.Dd May 13, 2004
+.Dt SEMGET 2
+.Os
+.Sh NAME
+.Nm semget
+.Nd get set of semaphores
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/sem.h
+.Ft int
+.Fn semget "key_t key" "int nsems" "int semflg"
+.Sh DESCRIPTION
+The
+.Fn semget
+system call returns the semaphore identifier associated with
+.Fa key .
+.Pp
+A new set containing
+.Fa nsems
+semaphores is created if either
+.Fa key
+is equal to
+.Dv IPC_PRIVATE ,
+or
+.Fa key
+does not have a semaphore set associated with it and the
+.Dv IPC_CREAT
+bit is set in
+.Fa semflg .
+If both the
+.Dv IPC_CREAT
+bit and the
+.Dv IPC_EXCL
+bit are set in
+.Fa semflg ,
+and
+.Fa key
+has a semaphore set associated with it already,
+the operation will fail.
+.Pp
+If a new set of semaphores is created, the data structure associated with it
+(the
+.Va semid_ds
+structure, see
+.Xr semctl 2 )
+is initialized as follows:
+.Bl -bullet
+.It
+.Va sem_perm.cuid
+and
+.Va sem_perm.uid
+are set to the effective uid of the calling process.
+.It
+.Va sem_perm.gid
+and
+.Va sem_perm.cgid
+are set to the effective gid of the calling process.
+.It
+.Va sem_perm.mode
+is set to the lower 9 bits of
+.Fa semflg .
+.It
+.Va sem_nsems
+is set to the value of
+.Fa nsems .
+.It
+.Va sem_ctime
+is set to the current time.
+.It
+.Va sem_otime
+is set to 0.
+.El
+.Sh RETURN VALUES
+.Fn semget
+returns a non-negative semaphore identifier if successful.
+Otherwise, \-1 is returned and
+.Va errno
+is set to reflect the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EACCES
+The caller has no permission to access a semaphore set already associated with
+.Fa key .
+.It Bq Er EEXIST
+Both
+.Dv IPC_CREAT
+and
+.Dv IPC_EXCL
+are set in
+.Fa semflg ,
+and a semaphore set is already associated with
+.Fa key .
+.It Bq Er EINVAL
+.Va nsems
+is less than 0 or greater than the system limit for the number in a semaphore
+set.
+.Pp
+A semaphore set associated with
+.Fa key
+exists, but has fewer semaphores than the number specified in
+.Fa nsems .
+.It Bq Er ENOSPC
+A new set of semaphores could not be created because the system limit
+for the number of semaphores or the number of semaphore sets has been
+reached.
+.It Bq Er ENOENT
+.Dv IPC_CREAT
+is not set in
+.Fa semflg
+and no semaphore set associated with
+.Fa key
+was found.
+.El
+.Sh SEE ALSO
+.Xr ipcs 1 ,
+.Xr semctl 2 ,
+.Xr semop 2 ,
+.Xr ftok 3
+.Sh STANDARDS
+The
+.Nm
+system call conforms to
+.St -xsh5 .
+.Sh HISTORY
+Semaphores appeared in the first release of
+.At V .
diff --git a/lib/nbsd_libc/sys/semop.2 b/lib/nbsd_libc/sys/semop.2
new file mode 100644 (file)
index 0000000..d232789
--- /dev/null
@@ -0,0 +1,170 @@
+.\"    $NetBSD: semop.2,v 1.17 2010/03/22 19:30:55 joerg Exp $
+.\"
+.\" Copyright (c) 1995 Frank van der Linden
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"      This product includes software developed for the NetBSD Project
+.\"      by Frank van der Linden
+.\" 4. 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 ``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 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.
+.\"
+.Dd November 3, 2005
+.Dt SEMOP 2
+.Os
+.Sh NAME
+.Nm semop
+.Nd semaphore operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/sem.h
+.Ft int
+.Fn semop "int semid" "struct sembuf *sops" "size_t nsops"
+.Sh DESCRIPTION
+.Fn semop
+provides a number of atomic operations on a set of semaphores.
+The semaphore set is specified by
+.Fa semid ,
+.Fa sops
+is an array of semaphore operations, and
+.Fa nsops
+is the number of operations in this array.
+The
+.Va sembuf
+structures in the array contain the following members:
+.Bd -literal
+    unsigned short sem_num; /* semaphore # */
+    short          sem_op;  /* semaphore operation */
+    short          sem_flg; /* operation flags */
+.Ed
+.Pp
+Each operation (specified in
+.Va sem_op )
+is applied to semaphore number
+.Va sem_num
+in the set of semaphores specified by
+.Fa semid .
+The value of
+.Va sem_op
+determines the action taken in the following way:
+.Bl -bullet
+.It
+.Va sem_op
+is less than 0.
+The current process is blocked until the value of the
+semaphore is greater than or equal to the absolute value of
+.Va sem_op .
+The absolute value of
+.Va sem_op
+is then subtracted from the value of the semaphore, and the calling
+process continues.
+Negative values of
+.Va sem_op
+are thus used to enter critical regions.
+.It
+.Va sem_op
+is greater than 0.
+Its value is added to the value of the specified semaphore.
+This is used to leave critical regions.
+.It
+.Va sem_op
+is equal to 0.
+The calling process is blocked until the value of the
+specified semaphore reaches 0.
+.El
+.Pp
+The behaviour of each operation is influenced by the flags set in
+.Va sem_flg
+in the following way:
+.Bl -tag -width IPC_NOWAITX
+.It Dv IPC_NOWAIT
+In the case where the calling process would normally block, waiting
+for a semaphore to reach a certain value,
+.Dv IPC_NOWAIT
+makes the
+call return immediately, returning a value of \-1 and setting
+.Va errno
+to
+.Er EAGAIN .
+.It SEM_UNDO
+Keep track of the changes that this call makes to the value of a semaphore,
+so that they can be undone when the calling process terminates.
+This is useful to prevent other processes waiting on a semaphore to block
+forever, should the process that has the semaphore locked terminate in a
+critical section.
+.El
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn semop
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+There is no semaphore associated with
+.Fa semid .
+.It Bq Er EIDRM
+The semaphore set was removed while the process was waiting for one of
+its semaphores to reach a certain value.
+.It Bq Er EACCES
+The calling process has no permission to access the specified semaphore set.
+.It Bq Er E2BIG
+The value of
+.Fa nsops
+is too big.
+The maximum is defined as
+.Dv MAX_SOPS
+in
+.In sys/sem.h .
+.It Bq Er EFBIG
+.Va sem_num
+in one of the sem_buf structures is less than 0, or greater than the actual
+number of semaphores in the set specified by
+.Fa semid .
+.It Bq Er ENOSPC
+.Dv SEM_UNDO
+was requested, and there is not enough space left in the kernel to
+store the undo information.
+.It Bq Er EAGAIN
+The requested operation can not immediately be performed, and
+.Dv IPC_NOWAIT
+was set in
+.Va sem_flg .
+.It Bq Er EFAULT
+.Fa sops
+points to an illegal address.
+.El
+.Sh SEE ALSO
+.Xr semctl 2 ,
+.Xr semget 2
+.Sh STANDARDS
+The
+.Nm
+system call conforms to
+.St -xsh5 .
+.Sh HISTORY
+Semaphores appeared in the first release of
+.At V .
diff --git a/lib/nbsd_libc/sys/send.2 b/lib/nbsd_libc/sys/send.2
new file mode 100644 (file)
index 0000000..fe468af
--- /dev/null
@@ -0,0 +1,221 @@
+.\"    $NetBSD: send.2,v 1.27 2008/05/09 15:52:50 christos Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)send.2     8.2 (Berkeley) 2/21/94
+.\"
+.Dd May 9, 2008
+.Dt SEND 2
+.Os
+.Sh NAME
+.Nm send ,
+.Nm sendto ,
+.Nm sendmsg
+.Nd send a message from a socket
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft ssize_t
+.Fn send "int s" "const void *msg" "size_t len" "int flags"
+.Ft ssize_t
+.Fn sendto "int s" "const void *msg" "size_t len" "int flags" "const struct sockaddr *to" "socklen_t tolen"
+.Ft ssize_t
+.Fn sendmsg "int s" "const struct msghdr *msg" "int flags"
+.Sh DESCRIPTION
+.Fn send ,
+.Fn sendto ,
+and
+.Fn sendmsg
+are used to transmit a message to another socket.
+.Fn send
+may be used only when the socket is in a
+.Em connected
+state, while
+.Fn sendto
+and
+.Fn sendmsg
+may be used at any time.
+.Pp
+The address of the target is given by
+.Fa to
+with
+.Fa tolen
+specifying its size.
+The length of the message is given by
+.Fa len .
+If the message is too long to pass atomically through the
+underlying protocol, the error
+.Er EMSGSIZE
+is returned, and
+the message is not transmitted.
+.Pp
+No indication of failure to deliver is implicit in a
+.Fn send .
+Locally detected errors are indicated by a return value of \-1.
+.Pp
+If no messages space is available at the socket to hold
+the message to be transmitted, then
+.Fn send
+normally blocks, unless the socket has been placed in
+non-blocking I/O mode.
+The
+.Xr select 2
+or
+.Xr poll 2
+call may be used to determine when it is possible to
+send more data.
+.Pp
+The
+.Fa flags
+parameter may include one or more of the following:
+.Bd -literal
+#define        MSG_OOB         0x0001 /* process out-of-band data */
+#define        MSG_PEEK        0x0002 /* peek at incoming message */
+#define        MSG_DONTROUTE   0x0004 /* bypass routing, use direct interface */
+#define        MSG_EOR         0x0008 /* data completes record */
+#define        MSG_NOSIGNAL    0x0400 /* do not generate SIGPIPE on EOF */
+.Ed
+.Pp
+The flag
+.Dv MSG_OOB
+is used to send
+.Dq out-of-band
+data on sockets that support this notion (e.g.
+.Dv SOCK_STREAM ) ;
+the underlying protocol must also support
+.Dq out-of-band
+data.
+.Dv MSG_EOR
+is used to indicate a record mark for protocols which support the
+concept.
+.\" .Dv MSG_EOF
+.\" requests that the sender side of a socket be shut down, and that an
+.\" appropriate indication be sent at the end of the specified data;
+.\" this flag is only implemented for
+.\" .Dv SOCK_STREAM
+.\" sockets in the
+.\" .Dv PF_INET
+.\" protocol family, and is used to implement Transaction
+.\" .Tn TCP
+.\" (see
+.\" .Xr ttcp 4 ) .
+.Dv MSG_DONTROUTE
+is usually used only by diagnostic or routing programs.
+.Pp
+See
+.Xr recv 2
+for a description of the
+.Fa msghdr
+structure.
+.Dv MSG_NOSIGNAL
+is used to prevent
+.Dv SIGPIPE
+generation when writing a socket that
+may be closed.
+.Sh RETURN VALUES
+The call returns the number of characters sent, or \-1
+if an error occurred.
+.Sh ERRORS
+.Fn send ,
+.Fn sendto ,
+and
+.Fn sendmsg
+fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+An invalid descriptor was specified.
+.It Bq Er ENOTSOCK
+The argument
+.Fa s
+is not a socket.
+.It Bq Er EFAULT
+An invalid user space address was specified for a parameter.
+.It Bq Er EMSGSIZE
+The socket requires that message be sent atomically,
+and the size of the message to be sent made this impossible.
+.It Bq Er EPIPE
+In a connected socket the connection has been broken.
+.It Bq Er EDSTADDRREQ
+In a non-connected socket a destination address has not been specified.
+.It Bq Er EAGAIN|EWOULDBLOCK
+The socket is marked non-blocking and the requested operation
+would block.
+.It Bq Er ENOBUFS
+The system was unable to allocate an internal buffer.
+The operation may succeed when buffers become available.
+.It Bq Er ENOBUFS
+The output queue for a network interface was full.
+This generally indicates that the interface has stopped sending,
+but may be caused by transient congestion.
+.It Bq Er EACCES
+The SO_BROADCAST option is not set on the socket, and a broadcast address
+was given as the destination.
+.It Bq Er EHOSTUNREACH
+The destination for the message is unreachable.
+.It Bq Er EHOSTDOWN
+The destination is a host on the local subnet and does not respond to 
+.Xr arp 4 .
+.It Bq Er EINVAL
+The total length of the I/O is more than can be expressed by the ssize_t
+return value.
+.It Bq Er EAFNOSUPPORT
+Addresses in the specified address family cannot be used with this socket.
+.El
+.Pp
+.Fn sendto
+will also fail if:
+.Bl -tag -width Er
+.It Bq Er EISCONN
+A destination address was specified and the socket is already connected.
+.El
+.Pp
+.Fn sendmsg
+will also fail if:
+.Bl -tag -width Er
+.It Bq Er EMSGSIZE
+The
+.Fa msg_iovlen
+member of the
+.Fa msg
+structure is less than or equal to 0
+or is greater than
+.Dv {IOV_MAX} .
+.El
+.Sh SEE ALSO
+.Xr fcntl 2 ,
+.Xr getsockopt 2 ,
+.Xr recv 2 ,
+.Xr select 2 ,
+.Xr socket 2 ,
+.Xr write 2
+.Sh HISTORY
+The
+.Fn send
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/setgroups.2 b/lib/nbsd_libc/sys/setgroups.2
new file mode 100644 (file)
index 0000000..4f74ec0
--- /dev/null
@@ -0,0 +1,91 @@
+.\"    $NetBSD: setgroups.2,v 1.18 2006/10/13 20:53:21 wiz Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 1993, 1994
+.\"    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.
+.\" 3. 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.
+.\"
+.\"     @(#)setgroups.2        8.2 (Berkeley) 4/16/94
+.\"
+.Dd October 7, 2006
+.Dt SETGROUPS 2
+.Os
+.Sh NAME
+.Nm setgroups
+.Nd set group access list
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/param.h
+.In unistd.h
+.Ft int
+.Fn setgroups "int ngroups" "const gid_t *gidset"
+.Sh DESCRIPTION
+.Fn setgroups
+sets the group access list of the current user process
+according to the array
+.Fa gidset .
+The parameter
+.Fa ngroups
+indicates the number of entries in the array and must be no
+more than
+.Dv {NGROUPS_MAX} .
+.Pp
+Only the super-user may set new groups.
+.Pp
+This system call affects only secondary groups.
+.Sh RETURN VALUES
+A 0 value is returned on success, \-1 on error, with
+an error code stored in
+.Va errno .
+.Sh ERRORS
+The
+.Fn setgroups
+call will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The value of
+.Fa ngroups
+is greater than
+.Dv {NGROUPS_MAX} .
+.It Bq Er EPERM
+The caller is not the super-user.
+.It Bq Er EFAULT
+The address specified for
+.Fa gidset
+is outside the process
+address space.
+.El
+.Sh SEE ALSO
+.Xr getgroups 2 ,
+.Xr setegid 2 ,
+.Xr setgid 2 ,
+.Xr setregid 2 ,
+.Xr initgroups 3
+.Sh HISTORY
+The
+.Fn setgroups
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/setpgid.2 b/lib/nbsd_libc/sys/setpgid.2
new file mode 100644 (file)
index 0000000..bfb97ca
--- /dev/null
@@ -0,0 +1,107 @@
+.\"    $NetBSD: setpgid.2,v 1.22 2004/05/13 10:20:58 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)setpgid.2  8.1 (Berkeley) 6/4/93
+.\"
+.Dd December 18, 2003
+.Dt SETPGID 2
+.Os
+.Sh NAME
+.Nm setpgid ,
+.Nm setpgrp
+.Nd set process group
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn setpgid "pid_t pid" "pid_t pgrp"
+.Ft int
+.Fn setpgrp "pid_t pid" "pid_t pgrp"
+.Sh DESCRIPTION
+.Fn setpgid
+sets the process group of the specified process
+.Ar pid
+to the specified
+.Ar pgrp .
+If
+.Ar pid
+is zero, then the call applies to the current process.
+If
+.Ar pgrp
+is zero, then the process id of the process specified by
+.Ar pid
+is used instead.
+.Pp
+If the invoker is not the super-user, then the affected process
+must have the same effective user-id as the invoker or be a descendant
+of the invoking process.
+.Sh RETURN VALUES
+.Fn setpgid
+returns 0 when the operation was successful.
+If the request failed, \-1 is returned and the global variable
+.Va errno
+indicates the reason.
+.Sh ERRORS
+.Fn setpgid
+will fail and the process group will not be altered if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+The value of the
+.Fa pid
+argument matches the process ID of a child process of the calling process,
+and the child process has successfully executed one of the exec functions.
+.It Bq Er EINVAL
+The value of the
+.Fa pgrp
+argument is less than zero.
+.It Bq Er EPERM
+The effective user ID of the requested process is different
+from that of the caller and the process is not a descendant
+of the calling process.
+.It Bq Er ESRCH
+The value of the
+.Fa pid
+argument does not match the process ID of the calling process or of a
+child process of the calling process.
+.El
+.Sh SEE ALSO
+.Xr getpgrp 2
+.Sh STANDARDS
+The
+.Fn setpgid
+function conforms to
+.St -p1003.1-90 .
+.Sh COMPATIBILITY
+.Fn setpgrp
+is identical to
+.Fn setpgid ,
+and is retained for calling convention compatibility with historical
+versions of
+.Bx .
diff --git a/lib/nbsd_libc/sys/setregid.2 b/lib/nbsd_libc/sys/setregid.2
new file mode 100644 (file)
index 0000000..fdaf9dc
--- /dev/null
@@ -0,0 +1,141 @@
+.\"    $NetBSD: setregid.2,v 1.23 2008/05/02 18:11:05 martin Exp $
+.\"
+.\" Copyright (c) 1998, 2000, 2001 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Charles M. Hannum.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.\"
+.\" Copyright (c) 1983, 1991 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)setregid.2   6.4 (Berkeley) 3/10/91
+.\"
+.Dd January 5, 2001
+.Dt SETREGID 2
+.Os
+.Sh NAME
+.Nm setregid
+.Nd set real and effective group ID's
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn setregid "gid_t rgid" "gid_t egid"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is made obsolete by the saved ID functionality in
+.Xr setgid 2
+and
+.Xr setegid 2 .
+.Ef
+.Pp
+The real and effective group ID's of the
+current process are set according to the arguments.
+If the real group ID is changed, the saved group ID is changed to the
+new value of the effective group ID.
+.Pp
+If
+.Fa rgid
+or
+.Fa egid
+is \-1, the current gid is filled in by the system.
+Unprivileged users may change the real group
+ID to the effective group ID, and may change the effective group ID to the
+real group ID or the saved group ID; only the super-user may
+make other changes.
+.Pp
+The
+.Fn setregid
+function has been used to swap the real and effective group
+IDs in set-group-ID programs to temporarily relinquish the set-group-ID
+value.
+This purpose is now better served by the use of the
+.Fn setegid
+function (see
+.Xr setgid 2 ) .
+.Pp
+When setting the real and effective group IDs to the same value, this
+function is equivalent to the
+.Fn setgid
+function.
+When setting only the effective group ID, this function is equivalent to
+the
+.Fn setegid
+function.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EPERM
+The current process is not the super-user and a change
+other than changing the effective group-id to the real group-id
+was specified.
+.El
+.Sh SEE ALSO
+.Xr getgid 2 ,
+.Xr setegid 2 ,
+.Xr setgid 2 ,
+.Xr setuid 2
+.Sh HISTORY
+The
+.Fn setregid
+function call appeared in
+.Bx 4.2 .
+An incompatible version was implemented in
+.Bx 4.4 .
+It was reimplemented in
+.Nx 1.2
+in a way compatible with
+.Bx 4.3 ,
+SunOS and Linux, but should not be used in new code.
diff --git a/lib/nbsd_libc/sys/setreuid.2 b/lib/nbsd_libc/sys/setreuid.2
new file mode 100644 (file)
index 0000000..ea998c7
--- /dev/null
@@ -0,0 +1,141 @@
+.\"    $NetBSD: setreuid.2,v 1.23 2008/05/02 18:11:05 martin Exp $
+.\"
+.\" Copyright (c) 1998, 2000, 2001 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Charles M. Hannum.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.\"
+.\" Copyright (c) 1980, 1991 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)setreuid.2   6.4 (Berkeley) 3/10/91
+.\"
+.Dd January 5, 2001
+.Dt SETREUID 2
+.Os
+.Sh NAME
+.Nm setreuid
+.Nd set real and effective user ID's
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn setreuid "uid_t ruid" "uid_t euid"
+.Sh DESCRIPTION
+.Bf -symbolic
+This interface is made obsolete by the saved ID functionality in
+.Xr setuid 2
+and
+.Xr seteuid 2 .
+.Ef
+.Pp
+The real and effective user ID's of the
+current process are set according to the arguments.
+If the real user ID is changed, the saved user ID is changed to the new
+value of the effective user ID.
+.Pp
+If
+.Fa ruid
+or
+.Fa euid
+is \-1, the current uid is filled in by the system.
+Unprivileged users may change the real user
+ID to the effective user ID, and may change the effective user ID to the
+real user ID or the saved user ID; only the super-user may
+make other changes.
+.Pp
+The
+.Fn setreuid
+function has been used to swap the real and effective user
+IDs in set-user-ID programs to temporarily relinquish the set-user-ID
+value.
+This purpose is now better served by the use of the
+.Fn seteuid
+function (see
+.Xr setuid 2 ) .
+.Pp
+When setting the real and effective user IDs to the same value, this
+function is equivalent to the
+.Fn setuid
+function.
+When setting only the effective user ID, this function is equivalent to
+the
+.Fn seteuid
+function.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EPERM
+The current process is not the super-user and a change
+other than changing the effective user-id to the real user-id
+was specified.
+.El
+.Sh SEE ALSO
+.Xr getuid 2 ,
+.Xr seteuid 2 ,
+.Xr setgid 2 ,
+.Xr setuid 2
+.Sh HISTORY
+The
+.Fn setreuid
+function call appeared in
+.Bx 4.2 .
+An incompatible version was implemented in
+.Bx 4.4 .
+It was reimplemented in
+.Nx 1.2
+in a way compatible with
+.Bx 4.3 ,
+SunOS and Linux, but should not be used in new code.
diff --git a/lib/nbsd_libc/sys/setsid.2 b/lib/nbsd_libc/sys/setsid.2
new file mode 100644 (file)
index 0000000..1338585
--- /dev/null
@@ -0,0 +1,79 @@
+.\"    $NetBSD: setsid.2,v 1.14 2006/10/07 21:03:51 elad Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)setsid.2    8.1 (Berkeley) 6/4/93
+.\"
+.Dd October 7, 2006
+.Dt SETSID 2
+.Os
+.Sh NAME
+.Nm setsid
+.Nd create session and set process group ID
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft pid_t
+.Fn setsid "void"
+.Sh DESCRIPTION
+The
+.Nm setsid
+function creates a new session.
+The calling process is the session leader of the new session, is the
+process group leader of a new process group and has no controlling
+terminal.
+The calling process is the only process in either the session or the
+process group.
+.Pp
+Upon successful completion, the
+.Nm setsid
+function returns the value of the process group ID of the new process
+group, which is the same as the process ID of the calling process.
+.Sh ERRORS
+If an error occurs,
+.Nm setsid
+returns \-1 and the global variable
+.Va errno
+is set to indicate the error, as follows:
+.Bl -tag -width Er
+.It Bq Er EPERM
+The calling process is already a process group leader, or the process
+group ID of a process other than the calling process matches the process
+ID of the calling process.
+.El
+.Sh SEE ALSO
+.Xr getsid 2 ,
+.Xr setpgid 2 ,
+.Xr tcgetpgrp 3 ,
+.Xr tcsetpgrp 3
+.Sh STANDARDS
+The
+.Nm setsid
+function conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/sys/settimeofday.c b/lib/nbsd_libc/sys/settimeofday.c
new file mode 100644 (file)
index 0000000..9991271
--- /dev/null
@@ -0,0 +1,97 @@
+/*     $NetBSD: settimeofday.c,v 1.13 2009/01/11 02:46:30 christos Exp $ */
+
+/*
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.      
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Emmanuel Dreyfus.
+ *
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: settimeofday.c,v 1.13 2009/01/11 02:46:30 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/syscall.h>
+
+#include <sys/clockctl.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <paths.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+int __clockctl_fd = -1;
+
+int ____settimeofday50(const struct timeval *, const void *);
+
+int
+settimeofday(const struct timeval *tv, const void *tzp)
+{
+       struct clockctl_settimeofday args;
+       int rv;
+
+       /*
+        * try syscal first and attempt to switch to clockctl
+        * if that fails with EPERM
+        */
+       if (__clockctl_fd == -1) {
+               rv = ____settimeofday50(tv, tzp);
+       
+               /*
+                * switch to clockctl if we fail with EPERM, this
+                * may be cause by an attempt to set the time backwards
+                * but we should leave the access permission checking
+                * entirely to the kernel
+                */
+               if (rv != -1 || errno != EPERM)
+                       return rv;
+
+               __clockctl_fd = open(_PATH_CLOCKCTL, O_WRONLY, 0);
+               if (__clockctl_fd == -1) {
+                       /* original error was EPERM - don't leak open errors */
+                       errno = EPERM;
+                       return -1;
+               }
+
+               (void) fcntl(__clockctl_fd, F_SETFD, FD_CLOEXEC);
+       }
+
+       /* 
+        * If __clockctl_fd >=0, clockctl has already been open
+        * and used, so we carry on using it.
+        */
+       args.tv = tv;
+       args.tzp = tzp;
+       return ioctl(__clockctl_fd, CLOCKCTL_SETTIMEOFDAY, &args);
+}
diff --git a/lib/nbsd_libc/sys/setuid.2 b/lib/nbsd_libc/sys/setuid.2
new file mode 100644 (file)
index 0000000..7c1532d
--- /dev/null
@@ -0,0 +1,135 @@
+.\"    $NetBSD: setuid.2,v 1.22 2010/04/05 07:44:28 wiz Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)setuid.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 3, 2010
+.Dt SETUID 2
+.Os
+.Sh NAME
+.Nm setuid ,
+.Nm seteuid ,
+.Nm setgid ,
+.Nm setegid
+.Nd set user and group ID
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn setuid "uid_t uid"
+.Ft int
+.Fn seteuid "uid_t euid"
+.Ft int
+.Fn setgid "gid_t gid"
+.Ft int
+.Fn setegid "gid_t egid"
+.Sh DESCRIPTION
+The
+.Fn setuid
+function
+sets the real and effective
+user IDs and the saved set-user-ID of the current process
+to the specified value.
+The
+.Fn setuid
+function is permitted if the specified ID is equal to the real user ID
+of the process, or if the effective user ID is that of the super user.
+.Pp
+The
+.Fn setgid
+function
+sets the real and effective
+group IDs and the saved set-group-ID of the current process
+to the specified value.
+The
+.Fn setgid
+function is permitted if the specified ID is equal to the real group ID
+of the process, or if the effective user ID is that of the super user.
+Supplementary group IDs remain unchanged.
+.Pp
+The
+.Fn seteuid
+function
+.Pq Fn setegid
+sets the effective user ID (group ID) of the
+current process.
+The effective user ID may be set to the value
+of the real user ID or the saved set-user-ID (see
+.Xr intro 2
+and
+.Xr execve 2 ) ;
+in this way, the effective user ID of a set-user-ID executable
+may be toggled by switching to the real user ID, then re-enabled
+by reverting to the set-user-ID value.
+Similarly, the effective group ID may be set to the value
+of the real group ID or the saved set-group-ID.
+.Sh RETURN VALUES
+Upon success, these functions return 0;
+otherwise \-1 is returned.
+.Pp
+If the user is not the super user, or the uid
+specified is not the real, effective ID, or saved ID,
+these functions return \-1.
+.Sh SEE ALSO
+.Xr getgid 2 ,
+.Xr getgroups 2 ,
+.Xr getuid 2
+.Sh STANDARDS
+The
+.Fn setuid
+and
+.Fn setgid
+functions are compliant with the
+.St -p1003.1-90
+specification with
+.Li _POSIX_SAVED_IDS
+not defined.
+We do not implement the
+.Li _POSIX_SAVED_IDS
+option as specified in the standard
+because this would make it impossible for a set-user-ID executable owned
+by a user other than the super-user to permanently revoke its privileges.
+.Pp
+The
+.Fn seteuid
+and
+.Fn setegid
+functions are compliant with
+.St -p1003.1-2001 .
+.Sh HISTORY
+The
+.Fn setuid
+and
+.Fn setgid
+functions appeared in
+.At v2
+and
+.At v4 ,
+respectively.
diff --git a/lib/nbsd_libc/sys/shmat.2 b/lib/nbsd_libc/sys/shmat.2
new file mode 100644 (file)
index 0000000..f5a9676
--- /dev/null
@@ -0,0 +1,140 @@
+.\"    $NetBSD: shmat.2,v 1.18 2010/03/22 19:30:55 joerg Exp $
+.\"
+.\" Copyright (c) 1995 Frank van der Linden
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"      This product includes software developed for the NetBSD Project
+.\"      by Frank van der Linden
+.\" 4. 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 ``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 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.
+.\"
+.Dd June 17, 2002
+.Dt SHMAT 2
+.Os
+.Sh NAME
+.Nm shmat ,
+.Nm shmdt
+.Nd map/unmap shared memory
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/shm.h
+.Ft void *
+.Fn shmat "int shmid" "const void *shmaddr" "int shmflg"
+.Ft int
+.Fn shmdt "const void *shmaddr"
+.Sh DESCRIPTION
+.Fn shmat
+maps the shared memory segment associated with the shared memory identifier
+.Fa shmid
+into the address space of the calling process.
+The address at which the segment is mapped is determined by the
+.Fa shmaddr
+parameter.
+If it is equal to 0, the system will pick an address itself.
+Otherwise, an attempt is made to map the shared memory segment at the
+address
+.Fa shmaddr
+specifies.
+If
+.Dv SHM_RND
+is set in
+.Fa shmflg ,
+the system will round the address down to a multiple of
+.Dv SHMLBA
+bytes
+.Pf ( Dv SHMLBA
+is defined in
+.In sys/shm.h ) .
+.Pp
+A shared memory segment can be mapped read-only by specifying the
+.Dv SHM_RDONLY
+flag in
+.Fa shmflg .
+.Pp
+.Fn shmdt
+unmaps the shared memory segment that is currently mapped at
+.Fa shmaddr
+from the calling process' address space.
+.Fa shmaddr
+must be a value returned by a prior
+.Fn shmat
+call.
+A shared memory segment will remain in existence until it is
+removed by a call to
+.Xr shmctl 2
+with the
+.Dv IPC_RMID
+command.
+.Sh RETURN VALUES
+.Fn shmat
+returns the address at which the shared memory segment has been mapped into
+the calling process' address space when successful,
+.Fn shmdt
+returns 0 on successful completion.
+Otherwise, a value of \-1 is returned, and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn shmat
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+The calling process has no permission to access this shared memory segment.
+.It Bq Er ENOMEM
+There is not enough available data space for the calling process to
+map the shared memory segment.
+.It Bq Er EINVAL
+.Fa shmid
+is not a valid shared memory identifier.
+.Pp
+.Fa shmaddr
+specifies an illegal address.
+.It Bq Er EMFILE
+The number of shared memory segments has reached the system-wide limit.
+.El
+.Pp
+.Fn shmdt
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+.Fa shmaddr
+is not the start address of a mapped shared memory segment.
+.El
+.Sh SEE ALSO
+.Xr ipcrm 1 ,
+.Xr ipcs 1 ,
+.Xr mmap 2 ,
+.Xr shmctl 2 ,
+.Xr shmget 2
+.Sh STANDARDS
+The
+.Nm shmat
+and
+.Nm shmdt
+system calls conform to
+.St -xsh5 .
+.Sh HISTORY
+Shared memory segments appeared in the first release of
+.At V .
diff --git a/lib/nbsd_libc/sys/shmctl.2 b/lib/nbsd_libc/sys/shmctl.2
new file mode 100644 (file)
index 0000000..2f0b68a
--- /dev/null
@@ -0,0 +1,209 @@
+.\"    $NetBSD: shmctl.2,v 1.21 2010/03/22 19:30:55 joerg Exp $
+.\"
+.\" Copyright (c) 1995 Frank van der Linden
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"      This product includes software developed for the NetBSD Project
+.\"      by Frank van der Linden
+.\" 4. 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 ``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 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.
+.\"
+.Dd November 25, 2006
+.Dt SHMCTL 2
+.Os
+.Sh NAME
+.Nm shmctl
+.Nd shared memory control operations
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/shm.h
+.Ft int
+.Fn shmctl "int shmid" "int cmd" "struct shmid_ds *buf"
+.Sh DESCRIPTION
+The
+.Fn shmctl
+system call performs control operations on the shared memory segment
+specified by
+.Fa shmid .
+.Pp
+Each shared memory segment has a
+.Sy shmid_ds
+structure associated with it which contains the following members:
+.Bd -literal
+    struct ipc_perm shm_perm;   /* operation permissions */
+    size_t          shm_segsz;  /* size of segment in bytes */
+    pid_t           shm_lpid;   /* pid of last shm op */
+    pid_t           shm_cpid;   /* pid of creator */
+    shmatt_t        shm_nattch; /* # of current attaches */
+    time_t          shm_atime;  /* last shmat() time */
+    time_t          shm_dtime;  /* last shmdt() time */
+    time_t          shm_ctime;  /* last change by shmctl() */
+.Ed
+.Pp
+The
+.Sy ipc_perm
+structure used inside the
+.Sy shmid_ds
+structure is defined in
+.In sys/ipc.h
+and contains the following members:
+.Bd -literal
+    uid_t cuid;  /* creator user id */
+    gid_t cgid;  /* creator group id */
+    uid_t uid;  /* user id */
+    gid_t gid;  /* group id */
+    mode_t mode; /* permission (lower 9 bits) */
+.Ed
+.Pp
+The operation to be performed by
+.Fn shmctl
+is specified in
+.Fa cmd
+and is one of:
+.Bl -tag -width IPC_RMIDX
+.It Dv IPC_STAT
+Gather information about the shared memory segment and place it in the
+structure pointed to by
+.Fa buf .
+.It Dv IPC_SET
+Set the value of the
+.Va shm_perm.uid ,
+.Va shm_perm.gid
+and
+.Va shm_perm.mode
+fields in the structure associated with
+.Fa shmid .
+The values are taken from the corresponding fields in the structure
+pointed to by
+.Fa buf .
+This operation can only be executed by the super-user, or a process that
+has an effective user id equal to either
+.Va shm_perm.cuid
+or
+.Va shm_perm.uid
+in the data structure associated with the shared memory segment.
+.It Dv IPC_RMID
+Remove the shared memory segment specified by
+.Fa shmid
+and destroy the data associated with it.
+Only the super-user or a process with an effective uid equal to the
+.Va shm_perm.cuid
+or
+.Va shm_perm.uid
+values in the data structure associated with the segment can do this.
+.It Dv SHM_LOCK
+Lock the shared memory segment specified by
+.Fa shmid
+in memory.
+This operation can only be executed by the super-user.
+.It Dv SHM_UNLOCK
+Unlock the shared memory segment specified by
+.Fa shmid .
+This operation can only be executed by the super-user.
+.El
+.Pp
+The read and write permissions on a shared memory identifier
+are determined by the
+.Va shm_perm.mode
+field in the same way as is
+done with files (see
+.Xr chmod 2 ) ,
+but the effective uid can match either the
+.Va shm_perm.cuid
+field or the
+.Va shm_perm.uid
+field, and the
+effective gid can match either
+.Va shm_perm.cgid
+or
+.Va shm_perm.gid .
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn shmctl
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+The command is
+.Dv IPC_STAT
+and the caller has no read permission for this shared memory segment.
+.It Bq Er EFAULT
+.Fa buf
+specifies an invalid address.
+.It Bq Er EINVAL
+.Fa shmid
+is not a valid shared memory segment identifier.
+.Pp
+.Va cmd
+is not a valid command.
+.It Bq Er ENOMEM
+The
+.Fa cmd
+is equal to
+.Dv SHM_LOCK
+and there is not enough physical memory.
+.It Bq Er EPERM
+.Fa cmd
+is equal to
+.Dv IPC_SET
+or
+.Dv IPC_RMID
+and the caller is not the super-user, nor does
+the effective uid match either the
+.Va shm_perm.uid
+or
+.Va shm_perm.cuid
+fields of the data structure associated with the shared memory segment.
+.Pp
+An attempt was made to increase the value of
+.Va shm_qbytes
+through
+.Dv IPC_SET
+but the caller is not the super-user.
+.Pp
+The
+.Fa cmd
+is equal to
+.Dv SHM_LOCK
+or
+.Dv SHM_UNLOCK
+and the caller is not the super-user.
+.El
+.Sh SEE ALSO
+.Xr ipcrm 1 ,
+.Xr ipcs 1 ,
+.Xr shmat 2 ,
+.Xr shmget 2
+.Sh STANDARDS
+The
+.Nm
+system call conforms to
+.St -xsh5 .
+.Sh HISTORY
+Shared memory segments appeared in the first release of
+.At V .
diff --git a/lib/nbsd_libc/sys/shmget.2 b/lib/nbsd_libc/sys/shmget.2
new file mode 100644 (file)
index 0000000..1f8ef34
--- /dev/null
@@ -0,0 +1,174 @@
+.\"    $NetBSD: shmget.2,v 1.22 2008/10/27 16:49:10 wiz Exp $
+.\"
+.\" Copyright (c) 1995 Frank van der Linden
+.\" 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.
+.\" 3. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"      This product includes software developed for the NetBSD Project
+.\"      by Frank van der Linden
+.\" 4. 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 ``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 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.
+.\"
+.Dd October 27, 2008
+.Dt SHMGET 2
+.Os
+.Sh NAME
+.Nm shmget
+.Nd get shared memory segment
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/shm.h
+.Ft int
+.Fn shmget "key_t key" "size_t size" "int shmflg"
+.Sh DESCRIPTION
+.Fn shmget
+returns the shared memory identifier associated with the key
+.Fa key .
+.Pp
+A shared memory segment is created if either
+.Fa key
+is equal to
+.Dv IPC_PRIVATE ,
+or
+.Fa key
+does not have a shared memory segment identifier associated with it, and the
+.Dv IPC_CREAT
+bit is set in
+.Fa shmflg .
+If both the
+.Dv IPC_CREAT
+bit and the
+.Dv IPC_EXCL
+bit are set in
+.Fa shmflg ,
+and
+.Fa key
+has a shared memory segment identifier associated with it already,
+the operation will fail.
+.Pp
+If a new shared memory segment is created, the data structure
+associated with it (the
+.Va shmid_ds
+structure, see
+.Xr shmctl 2 )
+is initialized as follows:
+.Bl -bullet
+.It
+.Va shm_perm.cuid
+and
+.Va shm_perm.uid
+are set to the effective uid of the calling process.
+.It
+.Va shm_perm.gid
+and
+.Va shm_perm.cgid
+are set to the effective gid of the calling process.
+.It
+.Va shm_perm.mode
+is set to the lower 9 bits of
+.Fa shmflg .
+.It
+.Va shm_lpid ,
+.Va shm_nattch ,
+.Va shm_atime ,
+and
+.Va shm_dtime
+are set to 0.
+.It
+.Va shm_ctime
+is set to the current time.
+.It
+.Va shm_segsz
+is set to the value of
+.Fa size .
+.El
+.Sh RETURN VALUES
+Upon successful completion a positive shared memory segment identifier
+is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er EACCES
+A shared memory segment is already associated with
+.Fa key
+and the caller has no permission to access it.
+.It Bq Er EEXIST
+Both
+.Dv IPC_CREAT
+and
+.Dv IPC_EXCL
+are set in
+.Fa shmflg ,
+and a shared memory segment is already associated with
+.Fa key .
+.It Bq Er EINVAL
+No shared memory segment is to be created, and a shared memory segment
+exists for
+.Fa key ,
+but the size of the segment associated with it is less
+than
+.Fa size ,
+which is non-zero.
+.Pp
+A shared memory segment
+.Em is
+to be created, and
+.Fa size
+is less than the system imposed minimum, or greater than the system
+imposed maximum (refer to the
+.Li kern.ipc
+values in
+.Xr sysctl 7 ) .
+.It Bq Er ENOENT
+.Dv IPC_CREAT
+is not set in
+.Fa shmflg
+and no shared memory segment associated with
+.Fa key
+was found.
+.It Bq Er ENOMEM
+There is not enough memory left to create a shared memory segment of the
+requested size.
+.It Bq Er ENOSPC
+A new shared memory identifier could not be created because the system limit
+for the number of shared memory identifiers has been reached.
+.El
+.Sh SEE ALSO
+.Xr ipcrm 1 ,
+.Xr ipcs 1 ,
+.Xr mmap 2 ,
+.Xr shmat 2 ,
+.Xr shmctl 2 ,
+.Xr ftok 3 ,
+.Xr sysctl 7
+.Sh STANDARDS
+The
+.Nm
+system call conforms to
+.St -xsh5 .
+.Sh HISTORY
+Shared memory segments appeared in the first release of
+.At V .
diff --git a/lib/nbsd_libc/sys/shutdown.2 b/lib/nbsd_libc/sys/shutdown.2
new file mode 100644 (file)
index 0000000..3e38962
--- /dev/null
@@ -0,0 +1,93 @@
+.\"    $NetBSD: shutdown.2,v 1.17 2004/05/13 10:20:58 wiz Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)shutdown.2 8.1 (Berkeley) 6/4/93
+.\"
+.Dd August 18, 2002
+.Dt SHUTDOWN 2
+.Os
+.Sh NAME
+.Nm shutdown
+.Nd shut down part of a full-duplex connection
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft int
+.Fn shutdown "int s" "int how"
+.Sh DESCRIPTION
+The
+.Fn shutdown
+call causes all or part of a full-duplex connection on
+the socket associated with
+.Fa s
+to be shut down.
+The
+.Fa how
+argument specifies which part of the connection will be shut down.
+Permissible values are:
+.Bl -tag -width SHUT_RDWRXX -offset indent
+.It SHUT_RD
+further receives will be disallowed.
+.It SHUT_WR
+further sends will be disallowed.
+.It SHUT_RDWR
+further sends and receives will be disallowed.
+.El
+.Sh RETURN VALUES
+A 0 is returned if the call succeeds, \-1 if it fails.
+.Sh ERRORS
+The call succeeds unless:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa s
+is not a valid descriptor.
+.It Bq Er EINVAL
+The
+.Fa how
+argument is invalid.
+.It Bq Er ENOTCONN
+The specified socket is not connected.
+.It Bq Er ENOTSOCK
+.Fa s
+is a file, not a socket.
+.El
+.Sh SEE ALSO
+.Xr connect 2 ,
+.Xr socket 2
+.Sh HISTORY
+The
+.Fn shutdown
+function call appeared in
+.Bx 4.2 .
+The
+.Fa how
+arguments used to be simply 0, 1, and 2, but now have named values
+as specified by
+.St -xpg4 .
diff --git a/lib/nbsd_libc/sys/sigaction.2 b/lib/nbsd_libc/sys/sigaction.2
new file mode 100644 (file)
index 0000000..e33f6c9
--- /dev/null
@@ -0,0 +1,363 @@
+.\"    $NetBSD: sigaction.2,v 1.43 2006/06/03 18:23:52 christos Exp $
+.\"
+.\" Copyright (c) 1980, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)sigaction.2 8.2 (Berkeley) 4/3/94
+.\"
+.Dd June 3, 2006
+.Dt SIGACTION 2
+.Os
+.Sh NAME
+.Nm sigaction
+.Nd software signal facilities
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigaction "int sig" "const struct sigaction * restrict act" "struct sigaction * restrict oact"
+.Sh DESCRIPTION
+The system defines a set of signals that may be delivered to a process.
+Signal delivery resembles the occurrence of a hardware interrupt:
+the signal is blocked from further occurrence, the current process
+context is saved, and a new one is built.
+A process may specify a
+.Em handler
+to which a signal is delivered, or specify that a signal is to be
+.Em ignored .
+A process may also specify that a default action is to be taken
+by the system when a signal occurs.
+A signal may also be
+.Em blocked ,
+in which case its delivery is postponed until it is
+.Em unblocked .
+The action to be taken on delivery is determined at the time of delivery.
+Normally, signal handlers execute on the current stack of the process.
+This may be changed, on a per-handler basis, so that signals are
+taken on a special
+.Em "signal stack" .
+.Pp
+Signal routines execute with the signal that caused their
+invocation
+.Em blocked ,
+but other signals may yet occur.
+A global
+.Em "signal mask"
+defines the set of signals currently blocked from delivery
+to a process.
+The signal mask for a process is initialized from that of its parent
+(normally empty).
+It may be changed with a
+.Xr sigprocmask 2
+call, or when a signal is delivered to the process.
+Signal masks are represented using the
+.Em sigset_t
+type; the
+.Xr sigsetops 3
+interface is used to modify such data.
+.Pp
+When a signal
+condition arises for a process, the signal is added to a set of
+signals pending for the process.
+If the signal is not currently
+.Em blocked
+by the process then it is delivered to the process.
+Signals may be delivered any time a process enters the operating system
+(e.g., during a system call, page fault or trap, or clock interrupt).
+If multiple signals are ready to be delivered at the same time,
+any signals that could be caused by traps are delivered first.
+Additional signals may be processed at the same time, with each
+appearing to interrupt the handlers for the previous signals
+before their first instructions.
+The set of pending signals is returned by the
+.Xr sigpending 2
+function.
+When a caught signal
+is delivered, the current state of the process is saved,
+a new signal mask is calculated (as described below),
+and the signal handler is invoked.
+The call to the handler is arranged so that if the signal handling
+routine returns normally the process will resume execution in the
+context from before the signal's delivery.
+If the process wishes to resume in a different context, then it
+must arrange to restore the previous context itself.
+.Pp
+.Em "struct sigaction"
+includes the following members:
+.Bd -literal -offset indent
+void     (*sa_sigaction)(int sig, siginfo_t *info, void *ctx);
+void      (*sa_handler)(int sig);
+sigset_t  sa_mask;
+int       sa_flags;
+.Ed
+.Pp
+When a signal is delivered to a process a new signal mask is
+installed for the duration of the process' signal handler
+(or until a
+.Xr sigprocmask 2
+call is made).
+This mask is formed by taking the union of the current signal mask,
+the signal to be delivered, and
+the signal mask associated with the handler to be invoked,
+.Em sa_mask .
+.Pp
+.Fn sigaction
+assigns an action for a specific signal.
+If
+.Fa act
+is non-zero, it
+specifies an action
+.Pf ( Dv SIG_DFL ,
+.Dv SIG_IGN ,
+or a handler routine) and mask
+to be used when delivering the specified signal.
+If
+.Fa oact
+is non-zero, the previous handling information for the signal
+is returned to the user.
+.Pp
+Once a signal handler is installed, it remains installed
+until another
+.Fn sigaction
+call is made, or an
+.Xr execve 2
+is performed.
+A signal-specific default action may be reset by
+setting
+.Fa sa_handler
+to
+.Dv SIG_DFL .
+The defaults are process termination, possibly with core dump;
+no action; stopping the process; or continuing the process.
+See the signal list below for each signal's default action.
+If
+.Fa sa_handler
+is set to
+.Dv SIG_DFL ,
+the default action for the signal is to discard the signal,
+and if a signal is pending,
+the pending signal is discarded even if the signal is masked.
+If
+.Fa sa_handler
+is set to
+.Dv SIG_IGN ,
+current and pending instances
+of the signal are ignored and discarded.
+.Pp
+Options may be specified by setting
+.Em sa_flags .
+.Bl -tag -width SA_NOKERNINFO
+.It Dv SA_NODEFER
+If set, then the signal that caused the handler to be executed is not added
+to the list of block signals.
+Please note that
+.Fa sa_mask
+takes precedence over
+.Dv SA_NODEFER ,
+so that if the specified signal is blocked in
+.Fa sa_mask ,
+then
+.Dv SA_NODEFER
+will have no effect.
+.It Dv SA_NOCLDSTOP
+If set when installing a catching function
+for the
+.Dv SIGCHLD
+signal,
+the
+.Dv SIGCHLD
+signal will be generated only when a child process exits,
+not when a child process stops.
+.It Dv SA_NOCLDWAIT
+If set, the system will not create a zombie when the child exits,
+but the child process will be automatically waited for.
+The same effect can be achieved by setting the signal handler for
+.Dv SIGCHLD
+to
+.Dv SIG_IGN .
+.It Dv SA_ONSTACK
+If set, the system will deliver the signal to the process on a
+.Em "signal stack" ,
+specified with
+.Xr sigaltstack 2 .
+.It Dv SA_RESETHAND
+If set, the default action will be reinstated when the signal
+is first posted.
+.It Dv SA_RESTART
+Normally, if a signal is caught during the system calls listed below,
+the call may be forced to terminate
+with the error
+.Er EINTR ,
+the call may return with a data transfer shorter than requested,
+or the call may be restarted.
+Restarting of pending calls is requested
+by setting the
+.Dv SA_RESTART
+bit in
+.Ar sa_flags .
+The affected system calls include
+.Xr open 2 ,
+.Xr read 2 ,
+.Xr write 2 ,
+.Xr sendto 2 ,
+.Xr recvfrom 2 ,
+.Xr sendmsg 2
+and
+.Xr recvmsg 2
+on a communications channel or a slow device (such as a terminal,
+but not a regular file)
+and during a
+.Xr wait 2
+or
+.Xr ioctl 2 .
+However, calls that have already committed are not restarted,
+but instead return a partial success (for example, a short read count).
+.Pp
+After a
+.Xr fork 2
+or
+.Xr vfork 2
+all signals, the signal mask, the signal stack,
+and the restart/interrupt flags are inherited by the child.
+.Pp
+The
+.Xr execve 2
+system call reinstates the default
+action for all signals which were caught and
+resets all signals to be caught on the user stack.
+Ignored signals remain ignored;
+the signal mask remains the same;
+signals that restart pending system calls continue to do so.
+.Pp
+See
+.Xr signal 7
+for comprehensive list of supported signals.
+.It Dv SA_SIGINFO
+If set, the signal handler function will receive additional information
+about the caught signal.
+An alternative handler that gets passed additional arguments will
+be called which is named
+.Fa sa_sigaction .
+The
+.Ar sig
+argument of this handler contains the signal number that was caught.
+The
+.Ar info
+argument contains additional signal specific information which
+is listed in
+.Xr siginfo 2 .
+The
+.Ar ctx
+argument
+is a pointer to the
+.Xr ucontext 2
+context where the signal handler will return to.
+.It Dv SA_NOKERNINFO
+This flag is relevant only to
+.Dv SIGINFO ,
+and turns off printing kernel messages on the tty.
+It is similar to the
+.Dv NOKERNINFO
+flag in
+.Xr termios 4 .
+.El
+.Pp
+Only functions that are async-signal-safe can safely be used in signal
+handlers, see
+.Xr signal 7
+for a complete list.
+.Sh NOTES
+The mask specified in
+.Fa act
+is not allowed to block
+.Dv SIGKILL
+or
+.Dv SIGSTOP .
+This is enforced silently by the system.
+.Sh RETURN VALUES
+A 0 value indicates that the call succeeded.
+A \-1 return value indicates an error occurred and
+.Va errno
+is set to indicate the reason.
+.Sh ERRORS
+.Fn sigaction
+will fail and no new signal handler will be installed if one
+of the following occurs:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+Either
+.Fa act
+or
+.Fa oact
+points to memory that is not a valid part of the process
+address space.
+.It Bq Er EINVAL
+.Fa sig
+is not a valid signal number.
+.It Bq Er EINVAL
+An attempt is made to ignore or supply a handler for
+.Dv SIGKILL
+or
+.Dv SIGSTOP .
+.It Bq Er EINVAL
+The
+.Em sa_flags
+word contains bits other than
+.Dv SA_NOCLDSTOP ,
+.Dv SA_NOCLDWAIT ,
+.Dv SA_NODEFER ,
+.Dv SA_ONSTACK ,
+.Dv SA_RESETHAND ,
+.Dv SA_RESTART ,
+and
+.Dv SA_SIGINFO .
+.El
+.Sh SEE ALSO
+.Xr kill 1 ,
+.Xr kill 2 ,
+.Xr ptrace 2 ,
+.Xr sigaltstack 2 ,
+.Xr siginfo 2 ,
+.Xr sigprocmask 2 ,
+.Xr sigsuspend 2 ,
+.Xr setjmp 3 ,
+.Xr sigsetops 3 ,
+.Xr tty 4 ,
+.Xr signal 7
+.Sh STANDARDS
+The
+.Fn sigaction
+function conforms to
+.St -p1003.1-90 .
+The
+.Dv SA_ONSTACK
+and
+.Dv SA_RESTART
+flags are Berkeley extensions, available on most
+.Bx Ns \-derived
+systems.
diff --git a/lib/nbsd_libc/sys/sigaltstack.2 b/lib/nbsd_libc/sys/sigaltstack.2
new file mode 100644 (file)
index 0000000..e9cb57d
--- /dev/null
@@ -0,0 +1,178 @@
+.\"    $NetBSD: sigaltstack.2,v 1.22 2009/04/16 18:37:29 wiz Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 1992, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)sigaltstack.2      8.2 (Berkeley) 5/1/95
+.\"
+.Dd April 16, 2009
+.Dt SIGALTSTACK 2
+.Os
+.Sh NAME
+.Nm sigaltstack
+.Nd set and/or get signal stack context
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Pp
+.Bd -literal
+typedef struct sigaltstack {
+       void   *ss_sp;
+       size_t  ss_size;
+       int     ss_flags;
+} stack_t;
+.Ed
+.Ft int
+.Fn sigaltstack "const stack_t * restrict ss" "stack_t * restrict oss"
+.Sh DESCRIPTION
+.Fn sigaltstack
+allows users to define an alternative stack on which signals
+are to be processed.
+If
+.Fa ss
+is non-zero,
+it specifies a pointer to and the size of a
+.Em "signal stack"
+on which to deliver signals,
+and tells the system if the process is currently executing
+on that stack.
+When a signal's action indicates its handler
+should execute on the signal stack (specified with a
+.Xr sigaction 2
+call), the system checks to see
+if the process is currently executing on that stack.
+If the process is not currently executing on the signal stack,
+the system arranges a switch to the signal stack for the
+duration of the signal handler's execution.
+.Pp
+If
+.Dv SS_DISABLE
+is set in
+.Fa ss_flags ,
+.Fa ss_sp
+and
+.Fa ss_size
+are ignored and the signal stack will be disabled.
+Trying to disable an active stack will cause
+.Nm
+to return \-1 with
+.Va errno
+set to
+.Er EINVAL .
+A disabled stack will cause all signals to be
+taken on the regular user stack.
+If the stack is later re-enabled then all signals that were specified
+to be processed on an alternative stack will resume doing so.
+.Pp
+If
+.Fa oss
+is non-zero, the current signal stack state is returned.
+The
+.Fa ss_flags
+field will contain the value
+.Dv SS_ONSTACK
+if the process is currently on a signal stack and
+.Dv SS_DISABLE
+if the signal stack is currently disabled.
+.Sh NOTES
+The value
+.Dv SIGSTKSZ
+is defined to be the number of bytes/chars that would be used to cover
+the usual case when allocating an alternative stack area.
+The following code fragment is typically used to allocate an alternative stack.
+.Bd -literal -offset indent
+if ((sigstk.ss_sp = malloc(SIGSTKSZ)) == NULL)
+       /* error return */
+sigstk.ss_size = SIGSTKSZ;
+sigstk.ss_flags = 0;
+if (sigaltstack(\*[Am]sigstk,0) \*[Lt] 0)
+       perror("sigaltstack");
+.Ed
+.Pp
+An alternative approach is provided for programs with signal handlers
+that require a specific amount of stack space other than the default size.
+The value
+.Dv MINSIGSTKSZ
+is defined to be the number of bytes/chars that is required by
+the operating system to implement the alternative stack feature.
+In computing an alternative stack size,
+programs should add
+.Dv MINSIGSTKSZ
+to their stack requirements to allow for the operating system overhead.
+.Pp
+Signal stacks are automatically adjusted for the direction of stack
+growth and alignment requirements.
+Signal stacks may or may not be protected by the hardware and
+are not ``grown'' automatically as is done for the normal stack.
+If the stack overflows and this space is not protected
+unpredictable results may occur.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn sigaltstack
+will fail and the signal stack context will remain unchanged
+if one of the following occurs.
+.Bl -tag -width Er
+.It Bq Er EFAULT
+Either
+.Fa ss
+or
+.Fa oss
+points to memory that is not a valid part of the process
+address space.
+.It Bq Er EINVAL
+An attempt was made to disable an active stack.
+.It Bq Er ENOMEM
+Size of alternative stack area is less than
+.Dv MINSIGSTKSZ .
+.El
+.Sh SEE ALSO
+.Xr sigaction 2 ,
+.Xr setjmp 3 ,
+.Xr signal 7
+.Sh STANDARDS
+The
+.Fn sigaltstack
+function conforms to
+.St -xpg4.2 .
+.Sh HISTORY
+The predecessor to
+.Nm sigaltstack ,
+the
+.Fn sigstack
+system call, appeared in
+.Bx 4.2 .
+.Sh CAVEATS
+Due to limitations in the current pthread implementation,
+.Nm
+should not be used in programs which link against the
+.Xr pthread 3
+library (whether threads are used or not).
diff --git a/lib/nbsd_libc/sys/sigpending.2 b/lib/nbsd_libc/sys/sigpending.2
new file mode 100644 (file)
index 0000000..e3e627a
--- /dev/null
@@ -0,0 +1,77 @@
+.\"    $NetBSD: sigpending.2,v 1.15 2008/10/24 15:40:21 wiz Exp $
+.\"
+.\" Copyright (c) 1993
+.\"    The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Berkeley Software Design, 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. 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.
+.\"
+.\"    @(#)sigpending.2        8.3 (Berkeley) 1/12/94
+.\"
+.Dd October 24, 2008
+.Dt SIGPENDING 2
+.Os
+.Sh NAME
+.Nm sigpending
+.Nd get pending signals
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigpending "sigset_t *set"
+.Sh DESCRIPTION
+The
+.Nm sigpending
+function returns a mask of the signals pending for delivery
+to the calling process in the location indicated by
+.Fa set .
+Signals may be pending because they are currently masked,
+or they are in transition before delivery (although the latter case is not
+normally detectable).
+.Sh RETURN VALUES
+A 0 value indicates that the call succeeded.
+A \-1 return value indicates an error occurred and
+.Va errno
+is set to indicate the reason.
+.Sh ERRORS
+.Fn sigpending
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+.Fa set
+specifies an invalid address.
+.El
+.Sh SEE ALSO
+.Xr sigaction 2 ,
+.Xr sigprocmask 2 ,
+.Xr signal 7
+.Sh STANDARDS
+The
+.Nm sigpending
+function conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/sys/sigprocmask.2 b/lib/nbsd_libc/sys/sigprocmask.2
new file mode 100644 (file)
index 0000000..0504d51
--- /dev/null
@@ -0,0 +1,121 @@
+.\"    $NetBSD: sigprocmask.2,v 1.22 2006/01/07 20:11:30 kleink Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)sigprocmask.2       8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt SIGPROCMASK 2
+.Os
+.Sh NAME
+.Nm sigprocmask
+.Nd manipulate current signal mask
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigprocmask "int how" "const sigset_t * restrict set" "sigset_t * restrict oset"
+.Sh DESCRIPTION
+The
+.Fn sigprocmask
+function examines and/or changes the current signal mask (those signals
+that are blocked from delivery).
+Signals are blocked if they are members of the current signal mask set.
+.Pp
+If
+.Fa set
+is not null, the action of
+.Fn sigprocmask
+depends on the value of the parameter
+.Fa how .
+The signal mask is changed as a function of the specified
+.Fa set
+and the current mask.
+The function is specified by
+.Fa how
+using one of the following values:
+.Bl -tag -width SIG_UNBLOCK
+.It Dv SIG_BLOCK
+The new mask is the union of the current mask and the specified
+.Fa set .
+.It Dv SIG_UNBLOCK
+The new mask is the intersection of the current mask
+and the complement of the specified
+.Fa set .
+.It Dv SIG_SETMASK
+The current mask is replaced by the specified
+.Fa set .
+.El
+.Pp
+If
+.Fa oset
+is not null, it is set to
+the previous value of the signal mask.
+.Pp
+When
+.Fa set
+is null,
+the value of
+.Ar how
+is insignificant and the mask remains unset
+providing a way to examine the signal mask without modification.
+.Pp
+The system
+quietly disallows
+.Dv SIGKILL
+or
+.Dv SIGSTOP
+to be blocked.
+.Sh RETURN VALUES
+A 0 value indicates that the call succeeded.
+A \-1 return value indicates an error occurred and
+.Va errno
+is set to indicate the reason.
+.Sh ERRORS
+The
+.Fn sigprocmask
+call will fail and the signal mask will be unchanged if one
+of the following occurs:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+.Fa how
+has a value other than those listed here.
+.El
+.Sh SEE ALSO
+.Xr kill 2 ,
+.Xr sigaction 2 ,
+.Xr sigsuspend 2 ,
+.Xr pthread_sigmask 3 ,
+.Xr sigsetops 3 ,
+.Xr signal 7
+.Sh STANDARDS
+The
+.Fn sigprocmask
+function conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/sys/sigqueue.2 b/lib/nbsd_libc/sys/sigqueue.2
new file mode 100644 (file)
index 0000000..115500f
--- /dev/null
@@ -0,0 +1,157 @@
+.\" $NetBSD: sigqueue.2,v 1.2 2011/01/10 06:26:30 wiz Exp $
+.\" Copyright (c) 2005 David Xu <davidxu@FreeBSD.org>
+.\" 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(s), this list of conditions and the following disclaimer as
+.\"    the first lines of this file unmodified other than the possible
+.\"    addition of one or more copyright notices.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice(s), 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 COPYRIGHT HOLDER(S) ``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 HOLDER(S) 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.
+.\"
+.\" $FreeBSD: src/lib/libc/sys/sigqueue.2,v 1.8 2006/09/17 21:27:34 ru Exp $
+.\"
+.Dd January 9, 2011
+.Dt SIGQUEUE 2
+.Os
+.Sh NAME
+.Nm sigqueue
+.Nd queue a signal to a process (REALTIME)
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigqueue "pid_t pid" "int signo" "const union sigval value"
+.Ft int
+.Fn sigqueueinfo "pid_t pid" "const siginfo_t *info"
+.Sh DESCRIPTION
+The
+.Fn sigqueue
+system call causes the signal specified by
+.Fa signo
+to be sent with the value specified by
+.Fa value
+to the process specified by
+.Fa pid .
+If
+.Fa signo
+is zero (the null signal), error checking is performed but
+no signal is actually sent.
+The null signal can be used to check the
+validity of PID.
+.Pp
+The conditions required for a process to have permission to queue a
+signal to another process are the same as for the
+.Xr kill 2
+system call.
+The
+.Fn sigqueue
+system call queues a signal to a single process specified by the
+.Fa pid
+argument.
+.Pp
+The
+.Fn sigqueue
+system call is implemented using
+.Fn sigqueueinfo
+and passing the appropriate information in the
+.Fa info
+argument.
+.Pp
+The
+.Fn sigqueue
+system call returns immediately.
+If the resources were
+available to queue the signal, the signal will be queued and sent to
+the receiving process.
+.Pp
+If the value of
+.Fa pid
+causes
+.Fa signo
+to be generated for the sending process, and if
+.Fa signo
+is not blocked for the calling thread and if no other thread has
+.Fa signo
+unblocked or is waiting in a
+.Fn sigwait
+system call for
+.Fa signo ,
+either
+.Fa signo
+or at least the pending, unblocked signal will be delivered to the
+calling thread before
+.Fn sigqueue
+returns.
+Should any multiple pending signals in the range
+.Dv SIGRTMIN
+to
+.Dv SIGRTMAX
+be selected for delivery, it is the lowest numbered
+one.
+The selection order between realtime and non-realtime signals, or
+between multiple pending non-realtime signals, is unspecified.
+.Sh RETURN VALUES
+.Rv -std
+.Sh ERRORS
+The
+.Fn sigqueue
+system call
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EAGAIN
+No resources are available to queue the signal.
+The process has already queued
+.Brq Dv SIGQUEUE_MAX
+signals that are still pending at the receiver(s),
+or a system-wide resource limit has been exceeded.
+.It Bq Er EEPERM
+The process does not have the appropriate privilege to send the signal
+to the receiving process.
+.It Bq Er EINVAL
+The value of the
+.Fa signo
+argument is an invalid or unsupported signal number.
+.It Bq Er ESRCH
+The process
+.Fa pid
+does not exist.
+.El
+.Sh SEE ALSO
+.Xr sigaction 2 ,
+.Xr siginfo 2 ,
+.Xr sigpending 2 ,
+.Xr sigsuspend 2 ,
+.Xr sigtimedwait 2 ,
+.Xr sigwait 2 ,
+.Xr sigwaitinfo 2 ,
+.Xr pause 3 ,
+.Xr pthread_sigmask 3
+.Sh STANDARDS
+The
+.Fn sigqueue
+system call conforms to
+.St -p1003.1-2004 .
+.Sh HISTORY
+Support for
+.Tn POSIX
+realtime signal queue first appeared in
+.Nx 6.0 .
diff --git a/lib/nbsd_libc/sys/sigqueue.c b/lib/nbsd_libc/sys/sigqueue.c
new file mode 100644 (file)
index 0000000..2bf09ad
--- /dev/null
@@ -0,0 +1,61 @@
+/* $NetBSD: sigqueue.c,v 1.2 2011/01/10 16:42:36 christos Exp $ */
+
+/*-
+ * Copyright (c) 2011 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sigqueue.c,v 1.2 2011/01/10 16:42:36 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+
+/*
+ * This is wrapper around sigqueueinfo(2), providing a sigqueue()
+ * implementation for userland.
+ */
+int
+sigqueue(pid_t pid, int signo, const union sigval value)
+{
+       siginfo_t info;
+
+       (void)memset(&info, 0, sizeof(info));
+
+       info.si_signo = signo;
+       info.si_code = SI_QUEUE;
+       info.si_pid = getpid();
+       info.si_uid = geteuid();
+       info.si_value = value;
+
+       return sigqueueinfo(pid, &info);
+}
diff --git a/lib/nbsd_libc/sys/sigstack.2 b/lib/nbsd_libc/sys/sigstack.2
new file mode 100644 (file)
index 0000000..d227f56
--- /dev/null
@@ -0,0 +1,54 @@
+.\"    $NetBSD: sigstack.2,v 1.12 2003/08/07 16:44:09 agc Exp $
+.\"
+.\" Copyright (c) 1983, 1992, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)sigstack.2 8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt SIGSTACK 2
+.Os
+.Sh NAME
+.Nm sigstack
+.Nd set and/or get signal stack context
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigstack "const struct sigstack *" "struct sigstack *"
+.Sh DESCRIPTION
+The
+.Fn sigstack
+function has been deprecated in favor of the interface described in
+.Xr sigaltstack 2 .
+.Sh SEE ALSO
+.Xr sigaltstack 2 ,
+.Xr signal 7
+.Sh HISTORY
+The
+.Nm
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/sigsuspend.2 b/lib/nbsd_libc/sys/sigsuspend.2
new file mode 100644 (file)
index 0000000..d462342
--- /dev/null
@@ -0,0 +1,80 @@
+.\"    $NetBSD: sigsuspend.2,v 1.17 2004/05/13 10:20:58 wiz Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)sigsuspend.2        8.2 (Berkeley) 5/16/95
+.\"
+.Dd May 16, 1995
+.Dt SIGSUSPEND 2
+.Os
+.Sh NAME
+.Nm sigsuspend
+.Nd atomically release blocked signals and wait for interrupt
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigsuspend "const sigset_t *sigmask"
+.Sh DESCRIPTION
+.Fn sigsuspend
+temporarily changes the blocked signal mask to the set to which
+.Fa sigmask
+points,
+and then waits for a signal to arrive;
+on return the previous set of masked signals is restored.
+The signal mask set
+is usually empty to indicate that all
+signals are to be unblocked for the duration of the call.
+.Pp
+In normal usage, a signal is blocked using
+.Xr sigprocmask 2
+to begin a critical section, variables modified on the occurrence
+of the signal are examined to determine that there is no work
+to be done, and the process pauses awaiting work by using
+.Fn sigsuspend
+with the previous mask returned by
+.Xr sigprocmask 2 .
+.Sh RETURN VALUES
+The
+.Fn sigsuspend
+function
+always terminates by being interrupted, returning \-1 with
+.Va errno
+set to
+.Er EINTR .
+.Sh SEE ALSO
+.Xr sigaction 2 ,
+.Xr sigprocmask 2 ,
+.Xr sigsetops 3 ,
+.Xr signal 7
+.Sh STANDARDS
+The
+.Nm sigsuspend
+function call conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/sys/sigtimedwait.2 b/lib/nbsd_libc/sys/sigtimedwait.2
new file mode 100644 (file)
index 0000000..c7a410c
--- /dev/null
@@ -0,0 +1,154 @@
+.\" $NetBSD: sigtimedwait.2,v 1.7 2010/05/31 11:02:24 drochner Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jaromir Dolecek.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 30, 2010
+.Dt SIGTIMEDWAIT 2
+.Os
+.Sh NAME
+.Nm sigtimedwait ,
+.Nm sigwaitinfo ,
+.Nm sigwait
+.Nd wait for queued signals
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In signal.h
+.Ft int
+.Fn sigtimedwait "const sigset_t * restrict set" "siginfo_t * restrict info" "const struct timespec * restrict timeout"
+.Ft int
+.Fn sigwaitinfo "const sigset_t * restrict set" "siginfo_t * restrict info"
+.Ft int
+.Fn sigwait "const sigset_t * restrict set" "int * restrict sig"
+.Sh DESCRIPTION
+.Fn sigwaitinfo
+and
+.Fn sigwait
+return the first pending signal from the set specified by
+.Fa set .
+Should multiple signals from
+.Fa set
+be pending, the lowest numbered one is returned.
+The selection order between realtime and non-realtime signals is unspecified.
+If there is no signal from
+.Ar set
+pending at the time of the call, the calling thread
+is suspended until one of the specified signals is generated.
+.Pp
+.Fn sigtimedwait
+is exactly equal to
+.Fn sigwaitinfo ,
+except
+.Fa timeout
+specifies the maximum time interval for which the calling thread will
+be suspended.
+If
+.Fa timeout
+is zero (tv_sec == tv_nsec == 0),
+.Fn sigtimedwait
+only checks the currently pending signals and returns immediately.
+If
+.Dv NULL
+is used for
+.Fa timeout ,
+.Fn sigtimedwait
+behaves exactly like
+.Fn sigwaitinfo
+in all regards.
+.Pp
+If several threads are waiting for a given signal, exactly one of them
+returns from the signal wait when the signal is generated.
+.Pp
+Behaviour of these functions is unspecified if any of the signals in
+.Fa set
+are unblocked at the time these functions are called.
+.Sh RETURN VALUES
+Upon successful completion of
+.Fn sigtimedwait
+or
+.Fn sigwaitinfo
+.Fa info
+is updated with signal information, and the function returns the signal number.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+indicates the error.
+Upon successful completion of
+.Fn sigwait
+.Fa sig
+is updated with ihe signal number, and the function returns 0.
+Otherwise, a non-zero error code is returned,
+.Sh ERRORS
+.Fn sigwaitinfo
+and
+.Fn sigwait
+always succeed.
+.Pp
+.Fn sigtimedwait
+will fail and the
+.Fa info
+pointer will remain unchanged if:
+.Bl -tag -width Er
+.It Bq Er EAGAIN
+No signal specified in
+.Fa set
+was generated in the specified
+.Fa timeout .
+.El
+.Pp
+.Fn sigtimedwait
+may also fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The specified
+.Fa timeout
+was invalid.
+.El
+.Pp
+This error is only checked if no signal from
+.Fa set
+is pending and it would be necessary to wait.
+.Sh SEE ALSO
+.Xr sigaction 2 ,
+.Xr sigprocmask 2 ,
+.Xr signal 7
+.Sh STANDARDS
+The functions
+.Fn sigtimedwait ,
+.Fn sigwaitinfo ,
+and
+.Fn sigwait
+conform to
+.St -p1003.1-2001 .
+.Sh HISTORY
+The
+.Fn sigtimedwait ,
+.Fn sigwaitinfo ,
+and
+.Fn sigwait
+functions appeared in
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/sys/sigtimedwait.c b/lib/nbsd_libc/sys/sigtimedwait.c
new file mode 100644 (file)
index 0000000..00b46cc
--- /dev/null
@@ -0,0 +1,58 @@
+/* $NetBSD: sigtimedwait.c,v 1.3 2009/01/11 02:46:30 christos Exp $ */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jaromir Dolecek.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sigtimedwait.c,v 1.3 2009/01/11 02:46:30 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+#include <signal.h>
+#include <time.h>
+
+/*
+ * Copy timeout to local variable and call the syscall.
+ */
+int
+sigtimedwait(const sigset_t * __restrict set, siginfo_t * __restrict info,
+    const struct timespec * __restrict timeout)
+{
+       struct timespec ts;
+
+       if (timeout) {
+               ts = *timeout;
+               return __sigtimedwait(set, info, &ts);
+       } else
+               return __sigtimedwait(set, info, NULL);
+}
diff --git a/lib/nbsd_libc/sys/sigwait.c b/lib/nbsd_libc/sys/sigwait.c
new file mode 100644 (file)
index 0000000..fbdef15
--- /dev/null
@@ -0,0 +1,67 @@
+/* $NetBSD: sigwait.c,v 1.4 2010/05/31 11:02:24 drochner Exp $ */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jaromir Dolecek.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sigwait.c,v 1.4 2010/05/31 11:02:24 drochner Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+#include <signal.h>
+#include <errno.h>
+
+#ifdef __weak_alias
+__weak_alias(sigwait,_sigwait)
+#endif
+
+int    _sigwait __P((const sigset_t * __restrict, int * __restrict));
+
+/*
+ * This is wrapper around sigtimedwait(2), providing sigwait()
+ * implementation for userland.
+ */
+int
+_sigwait(const sigset_t * __restrict set, int * __restrict signum)
+{
+       int saved_errno, new_errno, sig;
+       
+       saved_errno = errno;
+       sig = __sigtimedwait(set, NULL, NULL);
+       new_errno = errno;
+       errno = saved_errno;
+       if (sig < 0)
+               return (new_errno);
+       *signum = sig;
+       return (0);
+}
diff --git a/lib/nbsd_libc/sys/sigwaitinfo.c b/lib/nbsd_libc/sys/sigwaitinfo.c
new file mode 100644 (file)
index 0000000..de66825
--- /dev/null
@@ -0,0 +1,58 @@
+/* $NetBSD: sigwaitinfo.c,v 1.2 2008/04/28 20:23:00 martin Exp $ */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jaromir Dolecek.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: sigwaitinfo.c,v 1.2 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+#include <signal.h>
+
+#ifdef __weak_alias
+__weak_alias(sigwaitinfo,_sigwaitinfo)
+#endif
+
+int    _sigwaitinfo __P((const sigset_t * __restrict,
+           siginfo_t * __restrict info));
+
+/*
+ * This is wrapper around sigtimedwait(2), providing sigwaitinfo()
+ * implementation for userland.
+ */
+int
+_sigwaitinfo(const sigset_t * __restrict set, siginfo_t * __restrict info)
+{
+       return (sigtimedwait(set, info, NULL));
+}
diff --git a/lib/nbsd_libc/sys/socket.2 b/lib/nbsd_libc/sys/socket.2
new file mode 100644 (file)
index 0000000..e13148b
--- /dev/null
@@ -0,0 +1,280 @@
+.\"    $NetBSD: socket.2,v 1.36 2007/09/06 09:32:52 jnemeth Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)socket.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd September 6, 2007
+.Dt SOCKET 2
+.Os
+.Sh NAME
+.Nm socket
+.Nd create an endpoint for communication
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft int
+.Fn socket "int domain" "int type" "int protocol"
+.Sh DESCRIPTION
+.Fn socket
+creates an endpoint for communication and returns a descriptor.
+.Pp
+The
+.Fa domain
+parameter specifies a communications domain within which
+communication will take place; this selects the protocol family
+which should be used.
+These families are defined in the include file
+.Ao Pa sys/socket.h Ac .
+The currently understood formats are:
+.Pp
+.Bd -literal -offset indent -compact
+PF_LOCAL       local (previously UNIX) domain protocols
+PF_INET                ARPA Internet protocols
+PF_INET6       IPv6 (Internet Protocol version 6) protocols
+PF_ISO         ISO protocols
+PF_NS          Xerox Network Systems protocols
+PF_IMPLINK     IMP \*(lqhost at IMP\*(rq link layer
+PF_APPLETALK   AppleTalk protocols
+PF_BLUETOOTH   Bluetooth protocols
+.Ed
+.Pp
+The socket has the indicated
+.Fa type ,
+which specifies the semantics of communication.
+Currently defined types are:
+.Pp
+.Bd -literal -offset indent -compact
+SOCK_STREAM
+SOCK_DGRAM
+SOCK_RAW
+SOCK_SEQPACKET
+SOCK_RDM
+.Ed
+.Pp
+A
+.Dv SOCK_STREAM
+type provides sequenced, reliable,
+two-way connection based byte streams.
+An out-of-band data transmission mechanism may be supported.
+A
+.Dv SOCK_DGRAM
+socket supports
+datagrams (connectionless, unreliable messages of
+a fixed (typically small) maximum length).
+A
+.Dv SOCK_SEQPACKET
+socket may provide a sequenced, reliable,
+two-way connection-based data transmission path for datagrams
+of fixed maximum length; a consumer may be required to read
+an entire packet with each read system call.
+This facility is protocol specific, and presently implemented
+only for
+.Dv PF_NS .
+.Dv SOCK_RAW
+sockets provide access to internal network protocols and interfaces.
+The types
+.Dv SOCK_RAW ,
+which is available only to the super-user, and
+.Dv SOCK_RDM ,
+which is planned,
+but not yet implemented, are not described here.
+.Pp
+The
+.Fa protocol
+specifies a particular protocol to be used with the socket.
+Normally only a single protocol exists to support a particular
+socket type within a given protocol family.
+However, it is possible that many protocols may exist, in which case
+a particular protocol must be specified in this manner.
+The protocol number to use is
+particular to the \*(lqcommunication domain\*(rq in which communication
+is to take place; see
+.Xr protocols 5 .
+.Pp
+Sockets of type
+.Dv SOCK_STREAM
+are full-duplex byte streams.
+A stream socket must be in a
+.Em connected
+state before any data may be sent or received
+on it.
+A connection to another socket is created with a
+.Xr connect 2
+call.
+Once connected, data may be transferred using
+.Xr read 2
+and
+.Xr write 2
+calls or some variant of the
+.Xr send 2
+and
+.Xr recv 2
+calls.
+When a session has been completed a
+.Xr close 2
+may be performed.
+Out-of-band data may also be transmitted as described in
+.Xr send 2
+and received as described in
+.Xr recv 2 .
+.Pp
+The communications protocols used to implement a
+.Dv SOCK_STREAM
+ensure that data
+is not lost or duplicated.
+If a piece of data for which the
+peer protocol has buffer space cannot be successfully transmitted
+within a reasonable length of time, then
+the connection is considered broken and calls
+will indicate an error with
+\-1 returns and with
+.Er ETIMEDOUT
+as the specific code
+in the global variable
+.Va errno .
+The protocols optionally keep sockets
+.Dq warm
+by forcing transmissions
+roughly every minute in the absence of other activity.
+An error is then indicated if no response can be
+elicited on an otherwise
+idle connection for an extended period (e.g., 5 minutes).
+A
+.Dv SIGPIPE
+signal is raised if a process sends
+on a broken stream; this causes naive processes,
+which do not handle the signal, to exit.
+.Pp
+.Dv SOCK_SEQPACKET
+sockets employ the same system calls
+as
+.Dv SOCK_STREAM
+sockets.
+The only difference is that
+.Xr read 2
+calls will return only the amount of data requested,
+and any remaining in the arriving packet will be discarded.
+.Pp
+.Dv SOCK_DGRAM
+and
+.Dv SOCK_RAW
+sockets allow sending of datagrams to correspondents
+named in
+.Xr send 2
+calls.
+Datagrams are generally received with
+.Xr recvfrom 2 ,
+which returns the next datagram with its return address.
+.Pp
+An
+.Xr fcntl 2
+call can be used to specify a process group to receive
+a
+.Dv SIGURG
+signal when the out-of-band data arrives.
+It may also enable non-blocking I/O
+and asynchronous notification of I/O events
+via
+.Dv SIGIO .
+.Pp
+The operation of sockets is controlled by socket level
+.Em options .
+These options are defined in the file
+.Ao Pa sys/socket.h Ac .
+The
+.Xr setsockopt 2
+and
+.Xr getsockopt 2
+system calls are used to set and get options, respectively.
+.Sh RETURN VALUES
+A \-1 is returned if an error occurs, otherwise the return
+value is a descriptor referencing the socket.
+.Sh ERRORS
+The
+.Fn socket
+call fails if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+Permission to create a socket of the specified type and/or protocol
+is denied.
+.It Bq Er EAFNOSUPPORT
+The address family (domain) is not supported or
+the specified domain is not supported by this protocol family.
+.It Bq Er EMFILE
+The per-process descriptor table is full.
+.It Bq Er ENFILE
+The system file table is full.
+.It Bq Er ENOBUFS
+Insufficient buffer space is available.
+The socket cannot be created until sufficient resources are freed.
+.It Bq Er EPROTONOSUPPORT
+The protocol family is not supported or
+the specified protocol is not supported within this domain.
+.It Bq Er EPROTOTYPE
+The socket type is not supported by the protocol.
+.El
+.Sh SEE ALSO
+.Xr accept 2 ,
+.Xr bind 2 ,
+.Xr connect 2 ,
+.Xr getsockname 2 ,
+.Xr getsockopt 2 ,
+.Xr ioctl 2 ,
+.Xr listen 2 ,
+.Xr poll 2 ,
+.Xr read 2 ,
+.Xr recv 2 ,
+.Xr select 2 ,
+.Xr send 2 ,
+.Xr setsockopt 2 ,
+.Xr shutdown 2 ,
+.Xr socketpair 2 ,
+.Xr write 2 ,
+.Xr getprotoent 3
+.Rs
+.%T "An Introductory 4.4BSD Interprocess Communication Tutorial"
+.%A Stuart Sechrest
+.Re
+.Pq see Pa /usr/share/doc/psd/20.ipctut
+.Rs
+.%T "Advanced 4.4BSD IPC Tutorial"
+.%A Samuel J. Leffler
+.%A Robert S. Fabry
+.%A William N. Joy
+.%A Phil Lapsley
+.%A Steve Miller
+.%A Chris Torek
+.Re
+.Pq see Pa /usr/share/doc/psd/21.ipc
+.Sh HISTORY
+The
+.Fn socket
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/socketpair.2 b/lib/nbsd_libc/sys/socketpair.2
new file mode 100644 (file)
index 0000000..ac64b0c
--- /dev/null
@@ -0,0 +1,93 @@
+.\"    $NetBSD: socketpair.2,v 1.21 2009/12/20 02:16:40 wiz Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)socketpair.2       8.1 (Berkeley) 6/4/93
+.\"
+.Dd December 20, 2009
+.Dt SOCKETPAIR 2
+.Os
+.Sh NAME
+.Nm socketpair
+.Nd create a pair of connected sockets
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/socket.h
+.Ft int
+.Fn socketpair "int d" "int type" "int protocol" "int *sv"
+.Sh DESCRIPTION
+The
+.Fn socketpair
+call creates an unnamed pair of connected sockets in
+the specified domain
+.Fa d ,
+of the specified
+.Fa type ,
+and using the optionally specified
+.Fa protocol .
+The descriptors used in referencing the new sockets
+are returned in
+.Fa sv Ns [0]
+and
+.Fa sv Ns [1] .
+The two sockets are indistinguishable.
+.Sh RETURN VALUES
+A 0 is returned if the call succeeds, \-1 if it fails.
+.Sh ERRORS
+The call succeeds unless:
+.Bl -tag -width Er
+.It Bq Er EAFNOSUPPORT
+The specified address family is not supported on this machine.
+.It Bq Er EFAULT
+The address
+.Fa sv
+does not specify a valid part of the
+process address space.
+.It Bq Er EMFILE
+Too many descriptors are in use by this process.
+.It Bq Er ENFILE
+The system file table is full.
+.It Bq Er EOPNOTSUPP
+The specified protocol does not support creation of socket pairs.
+.It Bq Er EPROTONOSUPPORT
+The specified protocol is not supported on this machine.
+.El
+.Sh SEE ALSO
+.Xr pipe 2 ,
+.Xr read 2 ,
+.Xr write 2
+.Sh HISTORY
+The
+.Fn socketpair
+function call appeared in
+.Bx 4.2 .
+.Sh BUGS
+This call is currently implemented only for the
+.Dv PF_LOCAL
+domain.
diff --git a/lib/nbsd_libc/sys/stat.2 b/lib/nbsd_libc/sys/stat.2
new file mode 100644 (file)
index 0000000..f15aae5
--- /dev/null
@@ -0,0 +1,360 @@
+.\"    $NetBSD: stat.2,v 1.47 2010/11/25 20:53:23 dholland Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 1993, 1994
+.\"    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.
+.\" 3. 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.
+.\"
+.\"     @(#)stat.2     8.4 (Berkeley) 5/1/95
+.\"
+.Dd November 25, 2010
+.Dt STAT 2
+.Os
+.Sh NAME
+.Nm stat ,
+.Nm lstat ,
+.Nm fstat
+.Nd get file status
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/stat.h
+.Ft int
+.Fn stat "const char *path" "struct stat *sb"
+.Ft int
+.Fn lstat "const char *path" "struct stat *sb"
+.Ft int
+.Fn fstat "int fd" "struct stat *sb"
+.Sh DESCRIPTION
+The
+.Fn stat
+function obtains information about the file pointed to by
+.Fa path .
+Read, write or execute
+permission of the named file is not required, but all directories
+listed in the path name leading to the file must be searchable.
+.Pp
+The function
+.Fn lstat
+is like
+.Fn stat
+except in the case where the named file is a symbolic link,
+in which case
+.Fn lstat
+returns information about the link,
+while
+.Fn stat
+returns information about the file the link references.
+The
+.Fn fstat
+function obtains the same information about an open file
+known by the file descriptor
+.Fa fd .
+.Pp
+The
+.Fa sb
+argument is a pointer to a
+.Fa stat
+structure
+as defined by
+.In sys/stat.h
+and into which information is placed concerning the file.
+.Ss The Standard Structure
+The following standards-compliant fields are defined in the structure:
+.Bl -column -offset indent \
+"nlink_t " "st_nlink " "Description"
+.It Sy Type Ta Sy Entry Ta Sy Description
+.It Vt dev_t Ta st_dev Ta device ID containing the file
+.It Vt ino_t Ta st_ino Ta serial number of the file
+.It Vt mode_t Ta st_mode Ta mode of the file
+.It Vt nlink_t Ta st_nlink Ta number of hard links to the file
+.It Vt uid_t Ta st_uid Ta user ID of the owner
+.It Vt gid_t Ta st_gid Ta group ID of the owner
+.It Vt dev_t Ta st_rdev Ta device type (character or block special)
+.It Vt off_t Ta st_size Ta size of the file in bytes
+.It Vt time_t Ta st_atime Ta time of last access
+.It Vt time_t Ta st_mtime Ta time of last data modification
+.It Vt time_t Ta st_ctime Ta  time of last file status change
+.It Vt blksize_t Ta st_blksize Ta preferred I/O block size (fs-specific)
+.It Vt blkcnt_t Ta st_block Ta blocks allocated for the file
+.El
+.Pp
+These are specified in the
+.St -p1003.1-2004
+standard.
+The
+.Va st_ino
+and
+.Va st_dev
+fields taken together to uniquely identify the file within the system.
+Most of the types are defined in
+.Xr types 3 .
+.Pp
+The time-related fields are:
+.Bl -tag -width st_blksize -offset indent
+.It Va st_atime
+Time when file data was last accessed.
+Changed by the
+.Xr mknod 2 ,
+.Xr utimes 2 ,
+and
+.Xr read 2
+system calls.
+.It Va st_mtime
+Time when file data was last modified.
+Changed by the
+.Xr mknod 2 ,
+.Xr utimes 2 ,
+and
+.Xr write 2
+system calls.
+.It Va st_ctime
+Time when file status was last changed (file metadata modification).
+Changed by the
+.Xr chflags 2 ,
+.Xr chmod 2 ,
+.Xr chown 2 ,
+.Xr link 2 ,
+.Xr mknod 2 ,
+.Xr rename 2 ,
+.Xr unlink 2 ,
+.Xr utimes 2 ,
+and
+.Xr write 2
+system calls.
+.El
+.Pp
+The size-related fields of the
+.Fa struct stat
+are as follows:
+.Bl -tag -width st_blksize -offset indent
+.It Va st_size
+The size of the file in bytes.
+The meaning of the size reported for a directory is file system
+dependent.
+Some file systems (e.g. FFS) return the total size used for the
+directory metadata, possibly including free slots; others (notably
+ZFS) return the number of entries in the directory.
+Some may also return other things or always report zero.
+.It Va st_blksize
+The optimal I/O block size for the file.
+.It Va st_blocks
+The actual number of blocks allocated for the file in 512-byte units.
+As short symbolic links are stored in the inode, this number may
+be zero.
+.El
+.Pp
+The status information word
+.Fa st_mode
+contains bits that define the access mode (see
+.Xr chmod 2 )
+and the type (see
+.Xr dirent 3 )
+of the file.
+The following macros can be used to test
+whether a file is of the specified type.
+The value
+.Fa m
+supplied to the macros is the value of
+.Va st_mode .
+.Bl -tag -width "S_ISSOCK(m)" -offset indent
+.It Fn S_ISBLK "m"
+Test for a block special file.
+.It Fn S_ISCHR "m"
+Test for a character special file.
+.It Fn S_ISDIR "m"
+Test for a directory.
+.It Fn S_ISFIFO "m"
+Test for a pipe or FIFO special file.
+.It Fn S_ISREG "m"
+Test for a regular file.
+.It Fn S_ISLNK "m"
+Test for a symbolic link.
+.It Fn S_ISSOCK "m"
+Test for a socket.
+.El
+.Pp
+The macros evaluate to a non-zero value if the test
+is true or to the value 0 if the test is false.
+.Ss NetBSD Extensions
+The following additional
+.Nx
+specific fields are present:
+.Bl -column -offset indent \
+"uint32_t" "st_birthtimensec" "Description"
+.It Sy Type Ta Sy Entry Ta Sy Description
+.It Vt long Ta st_atimensec Ta last access (nanoseconds)
+.It Vt long Ta st_mtimensec Ta last modification (nanoseconds)
+.It Vt long Ta st_ctimensec Ta last status change (nanoseconds)
+.It Vt time_t Ta st_birthtime Ta time of inode creation
+.It Vt long Ta st_birthtimensec Ta inode creation (nanoseconds)
+.It Vt uint32_t Ta st_flags Ta user defined flags for the file
+.It Vt uint32_t Ta st_gen Ta file generation number
+.\"
+.\" XXX: What is this?
+.\"
+.It Vt uint32_t Ta st_spare[2] Ta implementation detail
+.El
+.Pp
+However, if
+_NETBSD_SOURCE
+is furthermore defined, instead of the above,
+the following are present in the structure:
+.Bl -column -offset indent \
+"struct timespec " "st_birthtimensec" "Description"
+.It Sy Type Ta Sy Entry Ta Sy Description
+.It Vt struct timespec Ta st_atimespec Ta time of last access
+.It Vt struct timespec Ta st_mtimespec Ta time of last modification
+.It Vt struct timespec Ta st_birthtimespec Ta time of creation
+.It Vt uint32_t Ta st_flags Ta user defined flags
+.It Vt uint32_t Ta st_gen Ta file generation number
+.\"
+.\" XXX: What is this?
+.\"
+.It Vt uint32_t Ta st_spare[2] Ta implementation detail
+.El
+.Pp
+In this case the following macros are provided for convenience:
+.Bd -literal -offset indent
+#if defined(_NETBSD_SOURCE)
+  #define st_atime                st_atimespec.tv_sec
+  #define st_atimensec            st_atimespec.tv_nsec
+  #define st_mtime                st_mtimespec.tv_sec
+  #define st_mtimensec            st_mtimespec.tv_nsec
+  #define st_ctime                st_ctimespec.tv_sec
+  #define st_ctimensec            st_ctimespec.tv_nsec
+  #define st_birthtime            st_birthtimespec.tv_sec
+  #define st_birthtimensec        st_birthtimespec.tv_nsec
+#endif
+.Ed
+.Pp
+The status information word
+.Fa st_flags
+has the following bits:
+.Bl -column -offset indent \
+"struct timespec " "st_birthtimensec"
+.It Sy Constant Ta Sy Description
+.It Dv UF_NODUMP Ta do not dump a file
+.It Dv UF_IMMUTABLE Ta file may not be changed
+.It Dv UF_APPEND Ta writes to file may only append
+.It Dv UF_OPAQUE Ta directory is opaque wrt. union
+.It Dv SF_ARCHIVED Ta file is archived
+.It Dv SF_IMMUTABLE Ta file may not be changed
+.It Dv SF_APPEND Ta writes to file may only append
+.El
+.Pp
+For a description of the flags, see
+.Xr chflags 2 .
+.Sh RETURN VALUES
+Upon successful completion a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh COMPATIBILITY
+Previous versions of the system used different types for the
+.Li st_dev ,
+.Li st_uid ,
+.Li st_gid ,
+.Li st_rdev ,
+.Li st_size ,
+.Li st_blksize
+and
+.Li st_blocks
+fields.
+.Sh ERRORS
+.Fn stat
+and
+.Fn lstat
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er EBADF
+A badly formed v-node was encountered.
+This can happen if a file system information node is incorrect.
+.It Bq Er EFAULT
+.Fa sb
+or
+.Em name
+points to an invalid address.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named file does not exist.
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENXIO
+The named file is a character special or block
+special file, and the device associated with this special file
+does not exist.
+.El
+.Pp
+.Fn fstat
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa fd
+is not a valid open file descriptor.
+.It Bq Er EFAULT
+.Fa sb
+points to an invalid address.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.El
+.Sh SEE ALSO
+.Xr chflags 2 ,
+.Xr chmod 2 ,
+.Xr chown 2 ,
+.Xr utimes 2 ,
+.Xr dirent 3 ,
+.Xr types 3 ,
+.Xr symlink 7
+.Sh STANDARDS
+The described functions conform to
+.St -p1003.1-2004 .
+.Sh HISTORY
+A
+.Fn stat
+function call appeared in
+.At v2 .
+A
+.Fn lstat
+function call appeared in
+.Bx 4.2 .
+.Sh BUGS
+Applying
+.Fn fstat
+to a socket (and thus to a pipe)
+returns a zero'd buffer,
+except for the blocksize field,
+and a unique device and file serial number.
diff --git a/lib/nbsd_libc/sys/statvfs.2 b/lib/nbsd_libc/sys/statvfs.2
new file mode 100644 (file)
index 0000000..d0aa61b
--- /dev/null
@@ -0,0 +1,178 @@
+.\"    $NetBSD: statvfs.2,v 1.5 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1989, 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)statfs.2    8.5 (Berkeley) 5/24/95
+.\"
+.Dd April 14, 2004
+.Dt STATVFS 2
+.Os
+.Sh NAME
+.Nm statvfs ,
+.Nm statvfs1 ,
+.Nm fstatvfs ,
+.Nm fstatvfs1
+.Nd get file system statistics
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/statvfs.h
+.Ft int
+.Fn statvfs "const char *path" "struct statvfs *buf"
+.Ft int
+.Fn statvfs1 "const char *path" "struct statvfs *buf" "int flags"
+.Ft int
+.Fn fstatvfs "int fd" "struct statvfs *buf"
+.Ft int
+.Fn fstatvfs1 "int fd" "struct statvfs *buf" "int flags"
+.Sh DESCRIPTION
+.Fn statvfs
+and
+.Fn statvfs1
+return information about a mounted file system.
+.Fa path
+is the path name of any file within the mounted file system.
+.Fa buf
+is a pointer to a
+.Nm statvfs
+structure defined in
+.Xr statvfs 5 .
+.Pp
+.Fn fstatvfs
+and
+.Fn fstatvfs1
+return the same information about an open file referenced by descriptor
+.Fa fd .
+.Pp
+The
+.Fn statvfs1
+and
+.Fn fstatvfs1
+functions allow an extra
+.Fa flags
+argument which can be
+.Dv ST_WAIT
+and
+.Dv ST_NOWAIT .
+When
+.Dv ST_NOWAIT
+is specified, then only cached statistics are returned.
+This can result in significant savings on non-local filesystems, where
+gathering statistics involves a network communication.
+.Pp
+The
+.Fn statvfs
+and
+.Fn fstatvfs
+calls are equivalent to the respective
+.Fn statvfs1
+and
+.Fn fstatvfs1
+calls with
+.Dv ST_WAIT
+specified as the
+.Fa flags
+argument.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn statvfs
+and
+.Fn statvfs1
+fail if one or more of the following are true:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix of
+.Fa path
+is not a directory.
+.It Bq Er ENAMETOOLONG
+The length of a component of
+.Fa path
+exceeds
+.Brq Dv NAME_MAX
+characters, or the length of
+.Fa path
+exceeds
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The file referred to by
+.Fa path
+does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix of
+.Fa path .
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating
+.Fa path .
+.It Bq Er EFAULT
+.Fa buf
+or
+.Fa path
+points to an invalid address.
+.It Bq Er EIO
+An
+.Tn I/O
+error occurred while reading from or writing to the file system.
+.El
+.Pp
+.Fn fstatvfs
+and
+.Fn fstatvfs1
+fail if one or more of the following are true:
+.Bl -tag -width Er
+.It Bq Er EBADF
+.Fa fd
+is not a valid open file descriptor.
+.It Bq Er EFAULT
+.Fa buf
+points to an invalid address.
+.It Bq Er EIO
+An
+.Tn I/O
+error occurred while reading from or writing to the file system.
+.El
+.Sh SEE ALSO
+.Xr statvfs 5
+.Sh HISTORY
+The
+.Fn statvfs ,
+.Fn statvfs1 ,
+.Fn fstatvfs ,
+and
+.Fn fstatvfs1
+functions first appeared in
+.Nx 3.0
+to replace
+the
+.Fn statfs
+family of functions which first appeared in
+.Bx 4.4 .
diff --git a/lib/nbsd_libc/sys/statvfs.c b/lib/nbsd_libc/sys/statvfs.c
new file mode 100644 (file)
index 0000000..669bcae
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: statvfs.c,v 1.6 2008/04/28 20:23:00 martin Exp $       */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: statvfs.c,v 1.6 2008/04/28 20:23:00 martin Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/statvfs.h>
+
+#ifdef __weak_alias
+__weak_alias(statvfs,_statvfs)
+__weak_alias(fstatvfs,_fstatvfs)
+#endif
+
+int
+statvfs(const char *file, struct statvfs *st)
+{
+       return statvfs1(file, st, ST_WAIT);
+}
+
+int
+fstatvfs(int f, struct statvfs *st)
+{
+       return fstatvfs1(f, st, ST_WAIT);
+}
+
+int    __fhstatvfs140(const void *fhp, size_t fh_size, struct statvfs *buf,
+       int flags);
+int    __fhstatvfs40(const void *fh, size_t fh_size, struct statvfs *st);
+
+int
+__fhstatvfs40(const void *fh, size_t fh_size, struct statvfs *st)
+{
+       return __fhstatvfs140(fh, fh_size, st, ST_WAIT);
+}
diff --git a/lib/nbsd_libc/sys/swapctl.2 b/lib/nbsd_libc/sys/swapctl.2
new file mode 100644 (file)
index 0000000..7c62344
--- /dev/null
@@ -0,0 +1,285 @@
+.\"    $NetBSD: swapctl.2,v 1.37 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1997 Matthew R. Green
+.\" 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 ``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 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.
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.Dd May 17, 2010
+.Dt SWAPCTL 2
+.Os
+.Sh NAME
+.Nm swapctl
+.Nd modify swap configuration
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.In sys/swap.h
+.Ft int
+.Fn swapctl "int cmd" "void *arg" "int misc"
+.Sh DESCRIPTION
+The
+.Nm
+function is used to add and delete swap devices, and modify their
+configuration.
+.Pp
+The
+.Fa cmd
+parameter specifies the operation to be performed.
+The
+.Fa arg
+and
+.Fa misc
+parameters have different meanings, depending on the
+.Fa cmd
+parameter.
+.Bl -enum -offset indent
+.It
+If
+.Fa cmd
+is
+.Dv SWAP_NSWAP ,
+the current number of swap devices in the system is returned.
+The
+.Fa arg
+and
+.Fa misc
+parameters are ignored.
+.It
+If
+.Fa cmd
+is
+.Dv SWAP_STATS ,
+the current statistics for swap devices are returned in the
+.Fa arg
+parameter.
+No more than
+.Fa misc
+swap devices are returned.
+The
+.Fa arg
+parameter should point to an array of at least
+.Fa misc
+struct swapent structures:
+.Bd -literal
+struct swapent {
+       dev_t   se_dev;                 /* device id */
+       int     se_flags;               /* entry flags */
+       int     se_nblks;               /* total blocks */
+       int     se_inuse;               /* blocks in use */
+       int     se_priority;            /* priority */
+       char    se_path[PATH_MAX+1];    /* path to entry */
+};
+.Ed
+.Pp
+The flags are defined as
+.Bd -literal
+       SWF_INUSE       in use: we have swapped here
+       SWF_ENABLE      enabled: we can swap here
+       SWF_BUSY        busy: I/O happening here
+       SWF_FAKE        fake: still being built
+.Ed
+.It
+If
+.Fa cmd
+is
+.Dv SWAP_ON ,
+the
+.Fa arg
+parameter is used as a pathname of a file to enable swapping to.
+The
+.Fa misc
+parameter is used to set the priority of this swap device.
+.It
+If
+.Fa cmd
+is
+.Dv SWAP_OFF ,
+the
+.Fa arg
+parameter is used as the pathname of a file to disable swapping from.
+The
+.Fa misc
+parameter is ignored.
+.It
+If
+.Fa cmd
+is
+.Dv SWAP_CTL ,
+the
+.Fa arg
+and
+.Fa misc
+parameters have the same function as for the
+.Dv SWAP_ON
+case, except that they change the priority of a currently enabled swap device.
+.It
+If
+.Fa cmd
+is
+.Dv SWAP_DUMPDEV ,
+the
+.Fa arg
+parameter is used as the pathname of a device to use as the dump device,
+should the system panic.
+.It
+If
+.Fa cmd
+is
+.Dv SWAP_GETDUMPDEV ,
+the
+.Fa arg
+parameter points to a dev_t, which is filled in by the current dump device.
+.El
+.Pp
+When swapping is enabled on a block device, the first portion of the disk is
+left unused to prevent any disklabel present from being overwritten.
+This space is allocated from the swap device when the
+.Dv SWAP_ON
+command is used.
+.Pp
+The priority of a swap device can be used to fill faster swap devices before
+slower ones.
+A priority of 0 is the highest, with larger numbers having lower priority.
+For a fuller discussion on swap priority, see the
+.Sx SWAP PRIORITY
+section in
+.Xr swapctl 8 .
+.Sh RETURN VALUES
+If the
+.Fa cmd
+parameter is
+.Dv SWAP_NSWAP
+or
+.Dv SWAP_STATS ,
+.Fn swapctl
+returns the number of swap devices, if successful.
+The
+.Dv SWAP_NSWAP
+command is always successful.
+Otherwise it returns 0 on success and \-1
+on failure, setting the global variable
+.Va errno
+to indicate the error.
+.Sh ERRORS
+.Fn swapctl
+succeeds unless:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named device does not exist.
+For the
+.Dv SWAP_CTL
+command, the named device is not currently enabled for swapping.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EPERM
+The caller is not the super-user.
+.It Bq Er EBUSY
+The device specified by
+.Fa arg
+has already been made available for swapping.
+.It Bq Er EINVAL
+The device configured by
+.Fa arg
+has no associated size, or the
+.Fa cmd
+was unknown.
+.It Bq Er ENXIO
+The major device number of
+.Fa arg
+is out of range (this indicates no device driver exists
+for the associated hardware).
+.It Bq Er ENXIO
+The block device specified by
+.Fa arg
+is not marked as a swap partition in the disklabel.
+.It Bq Er EIO
+An I/O error occurred while opening the swap device.
+.It Bq Er EFAULT
+.Fa arg
+points outside the process' allocated address space.
+.El
+.Sh SEE ALSO
+.Xr swapctl 8
+.Sh HISTORY
+The
+.Fn swapctl
+function call appeared in
+.Nx 1.3 .
+The
+.Fa se_path
+member was added to
+.Va struct swapent
+in
+.Nx 1.4 ,
+when the header file was also moved from
+.In vm/vm_swap.h
+to its current location in
+.In sys/swap.h .
+.Sh AUTHORS
+The current swap system was designed and implemented by
+Matthew Green
+.Aq mrg@eterna.com.au ,
+with help from Paul Kranenburg
+.Aq pk@NetBSD.org
+and Leo Weppelman
+.Aq leo@NetBSD.org ,
+and insights from Jason R. Thorpe
+.Aq thorpej@NetBSD.org .
diff --git a/lib/nbsd_libc/sys/swapon.3 b/lib/nbsd_libc/sys/swapon.3
new file mode 100644 (file)
index 0000000..38ac7ed
--- /dev/null
@@ -0,0 +1,121 @@
+.\"    $NetBSD: swapon.3,v 1.16 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)swapon.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt SWAPON 3
+.Os
+.Sh NAME
+.Nm swapon
+.Nd add a swap device for interleaved paging/swapping
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn swapon "const char *special"
+.Sh DESCRIPTION
+.Bf -symbolic
+.\" This interface is available from the compatibility library, libcompat and
+This interface is provided for compatibility only and
+has been obsoleted by
+.Xr swapctl 2 .
+.Ef
+.Pp
+.Fn swapon
+makes the block device
+.Fa special
+available to the system for
+allocation for paging and swapping.
+The names of potentially available devices are known to the system
+and defined at system configuration time.
+The size of the swap area on
+.Fa special
+is calculated at the time the device is first made available
+for swapping.
+.Sh RETURN VALUES
+If an error has occurred, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn swapon
+succeeds unless:
+.Bl -tag -width ENAMETOOLONG
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named device does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EPERM
+The caller is not the super-user.
+.It Bq Er ENOTBLK
+.Fa special
+is not a block device.
+.It Bq Er EBUSY
+The device specified by
+.Fa special
+has already
+been made available for swapping
+.It Bq Er EINVAL
+The device configured by
+.Fa special
+was not
+configured into the system as a swap device.
+.It Bq Er ENXIO
+The major device number of
+.Fa special
+is out of range (this indicates no device driver exists
+for the associated hardware).
+.It Bq Er EIO
+An I/O error occurred while opening the swap device.
+.It Bq Er EFAULT
+.Fa special
+points outside the process's allocated address space.
+.El
+.Sh SEE ALSO
+.Xr swapctl 2 ,
+.Xr swapctl 8 ,
+.Xr swapon 8
+.Sh HISTORY
+The
+.Fn swapon
+function call appeared in
+.Bx 4.0
+and was removed
+.Nx 1.3
+.Sh BUGS
+This call will be upgraded in future versions of the system.
diff --git a/lib/nbsd_libc/sys/swapon.c b/lib/nbsd_libc/sys/swapon.c
new file mode 100644 (file)
index 0000000..a624409
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: swapon.c,v 1.10 2008/05/29 14:51:25 mrg Exp $  */
+
+/*
+ * Copyright (c) 1997 Matthew R. Green
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: swapon.c,v 1.10 2008/05/29 14:51:25 mrg Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/swap.h>
+#include <unistd.h>
+
+int
+swapon(name)
+       const char *name;
+{
+
+       return (swapctl(SWAP_ON, __UNCONST(name), 0));
+}
diff --git a/lib/nbsd_libc/sys/symlink.2 b/lib/nbsd_libc/sys/symlink.2
new file mode 100644 (file)
index 0000000..2479180
--- /dev/null
@@ -0,0 +1,140 @@
+.\"    $NetBSD: symlink.2,v 1.20 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)symlink.2  8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt SYMLINK 2
+.Os
+.Sh NAME
+.Nm symlink
+.Nd make symbolic link to a file
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn symlink "const char *name1" "const char *name2"
+.Sh DESCRIPTION
+A symbolic link
+.Fa name2
+is created to
+.Fa name1
+.Pf ( Fa name2
+is the name of the
+file created,
+.Fa name1
+is the string
+used in creating the symbolic link).
+Either name may be an arbitrary path name; the files need neither
+to be on the same file system nor to exist.
+.Sh RETURN VALUES
+Upon successful completion, a zero value is returned.
+If an error occurs, the error code is stored in
+.Va errno
+and a \-1 value is returned.
+.Sh ERRORS
+The symbolic link succeeds unless:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the
+.Fa name2
+prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+A component of the
+.Fa name2
+path does not exist.
+.It Bq Er EACCES
+A component of the
+.Fa name2
+path prefix denies search permission.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EEXIST
+.Fa name2
+already exists.
+.It Bq Er EIO
+An I/O error occurred while making the directory entry for
+.Fa name2 ,
+or allocating the inode for
+.Fa name2 ,
+or writing out the link contents of
+.Fa name2 .
+.It Bq Er EROFS
+The file
+.Fa name2
+would reside on a read-only file system.
+.It Bq Er ENOSPC
+The directory in which the entry for the new symbolic link is being placed
+cannot be extended because there is no space left on the file
+system containing the directory.
+.It Bq Er ENOSPC
+The new symbolic link cannot be created because there
+there is no space left on the file
+system that will contain the symbolic link.
+.It Bq Er ENOSPC
+There are no free inodes on the file system on which the
+symbolic link is being created.
+.It Bq Er EDQUOT
+The directory in which the entry for the new symbolic link
+is being placed cannot be extended because the
+user's quota of disk blocks on the file system
+containing the directory has been exhausted.
+.It Bq Er EDQUOT
+The new symbolic link cannot be created because the user's
+quota of disk blocks on the file system that will
+contain the symbolic link has been exhausted.
+.It Bq Er EDQUOT
+The user's quota of inodes on the file system on
+which the symbolic link is being created has been exhausted.
+.It Bq Er EIO
+An I/O error occurred while making the directory entry or allocating the inode.
+.It Bq Er EFAULT
+.Fa name1
+or
+.Fa name2
+points outside the process's allocated address space.
+.El
+.Sh SEE ALSO
+.Xr ln 1 ,
+.Xr link 2 ,
+.Xr readlink 2 ,
+.Xr unlink 2 ,
+.Xr symlink 7
+.Sh HISTORY
+The
+.Fn symlink
+function call appeared in
+.Bx 4.2 .
diff --git a/lib/nbsd_libc/sys/sync.2 b/lib/nbsd_libc/sys/sync.2
new file mode 100644 (file)
index 0000000..c45a65a
--- /dev/null
@@ -0,0 +1,102 @@
+.\"    $NetBSD: sync.2,v 1.17 2009/03/25 06:46:21 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)sync.2     8.1 (Berkeley) 6/4/93
+.\"
+.Dd March 25, 2009
+.Dt SYNC 2
+.Os
+.Sh NAME
+.Nm sync
+.Nd "synchronize disk block in-core status with that on disk"
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft void
+.Fn sync void
+.Sh DESCRIPTION
+The
+.Fn sync
+function forces a write of dirty (modified) buffers
+in the block buffer cache out
+to disk.
+The kernel keeps this information in core to reduce
+the number of disk I/O transfers required by the system.
+As information in the cache is lost after a system crash,
+kernel thread
+.Nm ioflush
+ensures that dirty buffers are synced to disk
+eventually.
+By default, a dirty buffer is synced after 30 seconds,
+but some filesystems exploit
+.Nm ioflush
+features to sync directory data and metadata faster
+(after 15 and 10 seconds, respectively).
+.Pp
+The function
+.Xr fsync 2
+may be used to synchronize individual file descriptor
+attributes.
+.Sh CAUTIONS
+Many modern disks contain write-back caches.
+In theory
+.Fn sync
+flushes these.
+In practice there are many possible ways for this mechanism to go
+astray.
+It is prudent (where possible) to allow a few seconds after syncing
+for everything to settle before e.g. turning off the power.
+.Pp
+It may also be desirable to use
+.Xr dkctl 8
+or
+.Xr scsictl 8
+to disable the write-back cache entirely.
+.Sh SEE ALSO
+.Xr fsync 2 ,
+.Xr dkctl 8 ,
+.Xr scsictl 8 ,
+.Xr sync 8
+.Sh HISTORY
+A
+.Fn sync
+function call appeared in
+.At v6 .
+.Pp
+Historically,
+.Fn sync
+would schedule buffers for writing but not actually wait for the
+writes to finish.
+It was necessary to issue a second or sometimes a third call to ensure
+that all buffers had in fact been written out.
+In
+.Nx ,
+.Fn sync
+does not return until all buffers have been written.
diff --git a/lib/nbsd_libc/sys/sysarch.2 b/lib/nbsd_libc/sys/sysarch.2
new file mode 100644 (file)
index 0000000..ae07014
--- /dev/null
@@ -0,0 +1,70 @@
+.\"    $NetBSD: sysarch.2,v 1.15 2003/08/07 16:44:10 agc Exp $
+.\"
+.\" Copyright (c) 1980, 1991 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.
+.\" 3. 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.
+.\"
+.\"     from: @(#)syscall.2    6.3 (Berkeley) 3/10/91
+.\"
+.Dd October 11, 1993
+.Dt SYSARCH 2
+.Os
+.Sh NAME
+.Nm sysarch
+.Nd architecture-dependent system call
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In machine/sysarch.h
+.Ft int
+.Fn sysarch "int number" "void *args"
+.Sh DESCRIPTION
+.Fn sysarch
+performs the architecture-dependent function
+specified by
+.Fa number
+with the arguments specified by the
+.Fa args
+pointer.
+.Fa args
+is a pointer to a structure defining the actual arguments of the function.
+Symbolic constants and argument structures for the architecture-dependent
+functions can be found in the header file
+.Ao Pa machine/sysarch.h Ac .
+.Pp
+The
+.Fn sysarch
+system call should never be called directly by user programs.
+Instead, they should access its functions using the architecture-dependent
+library.
+.Sh RETURN VALUES
+See the manual pages for specific architecture-dependent function calls
+for information about their return values.
+.Sh HISTORY
+The
+.Fn sysarch
+function call appeared in
+.Nx 1.0 .
diff --git a/lib/nbsd_libc/sys/syscall.2 b/lib/nbsd_libc/sys/syscall.2
new file mode 100644 (file)
index 0000000..056c406
--- /dev/null
@@ -0,0 +1,99 @@
+.\"    $NetBSD: syscall.2,v 1.18 2009/08/07 19:34:46 dsl Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)syscall.2  8.1 (Berkeley) 6/16/93
+.\"
+.Dd August 7, 2009
+.Dt SYSCALL 2
+.Os
+.Sh NAME
+.Nm syscall ,
+.Nm __syscall
+.Nd indirect system call
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/syscall.h
+.In unistd.h
+.Ft int
+.Fn syscall "int number" "..."
+.Ft quad_t
+.Fn __syscall "quad_t number" "..."
+.Sh DESCRIPTION
+.Fn syscall
+performs the system call whose assembly language
+interface has the specified
+.Fa number
+with the specified arguments.
+Symbolic constants for system calls can be found in the header file
+.Ao Pa sys/syscall.h Ac .
+The
+.Nm __syscall
+form should be used when one or more of the parameters is a
+64-bit argument to ensure that argument alignment is correct.
+.Pp
+This system call is useful for testing new system calls that
+do not have entries in the C library.
+It should not be used in normal applications.
+.Sh RETURN VALUES
+The return values are defined by the system call being invoked.
+In general, a 0 return value indicates success.
+A \-1 return value indicates an error,
+and an error code is stored in
+.Va errno .
+.Sh HISTORY
+The
+.Fn syscall
+function call appeared in
+.Bx 4.0 .
+.Sh BUGS
+There is no way to simulate system calls that have multiple return values
+such as
+.Xr pipe 2 .
+.Pp
+Since architectures return 32 bit and 64 bit results in different registers,
+it may be impossible to portably convert the result of
+.Fn __syscall
+to a 32bit value.
+For instance sparc returns 32 bit values in %o0 and 64 bit values in %o0:%o1
+(with %o0 containing the most significant part) so a 32 bit right shift
+of the result is needed to get a correct 32 bit result.
+.Pp
+Many architectures mask off the unwanted high bits of the syscall number,
+rather than returning an error.
+.Pp
+Due to ABI implementation differences in passing struct or union
+type arguments to system calls between different processors, all
+system calls pass instead pointers to such structs or unions, even
+when the documentation of the system call mentions otherwise.
+The conversion between passing structs and unions is handled normally
+via userland stubs.
+The correct arguments for the kernel entry
+points for each system call can be found in the header file
+.Ao Pa sys/syscallargs.h Ac
diff --git a/lib/nbsd_libc/sys/timer_create.2 b/lib/nbsd_libc/sys/timer_create.2
new file mode 100644 (file)
index 0000000..21cbd66
--- /dev/null
@@ -0,0 +1,119 @@
+.\"    $NetBSD: timer_create.2,v 1.11 2010/05/19 06:44:51 jruoho Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Christos Zoulas.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 19, 2010
+.Dt TIMER_CREATE 2
+.Os
+.Sh NAME
+.Nm timer_create
+.Nd create a per-process timer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.In signal.h
+.Ft int
+.Fn timer_create "clockid_t clockid" "struct sigevent * restrict evp" "timer_t * restrict timerid"
+.Sh DESCRIPTION
+The
+.Fn timer_create
+function creates a per-process timer using the clock specified in the
+.Ar clockid
+argument.
+If it succeeds, the
+.Fn timer_create
+function fills in the
+.Ar timerid
+argument with an id associated with the timer created that can be used by
+other timer related calls.
+The
+.Ar clockid
+must be a valid clock id as defined in
+.In time.h .
+The timer is created in a disarmed state.
+.Pp
+An optional
+.Pq non- Ns Dv NULL
+.Em struct sigevent
+argument can be specified by the
+.Ar evp
+argument.
+If the
+.Ar evp
+argument is
+.Dv NULL ,
+then
+.Fa evp-\*[Gt]sigev_notify
+defaults to
+.Dv SIGEV_SIGNAL
+and
+.Fa evp-\*[Gt]sigev_value
+is set to
+.Ar timerid .
+Refer to
+.Xr sigevent 3
+for more details.
+.Sh NOTES
+Timers are not inherited after a
+.Xr fork 2
+and are disarmed and deleted by an
+.Xr exec 3 .
+.Sh RETURN VALUES
+If successful, the
+.Fn timer_create
+function returns 0, and fills in the
+.Ar timerid
+argument with the id of the new timer that was created.
+Otherwise, it returns \-1, and sets
+.Dv errno
+to indicate the error.
+.Sh ERRORS
+The
+.Fn timer_create
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EAGAIN
+The system is out of resources to satisfy this request, or the process has
+created all the timers it is allowed.
+.It Bq Er EINVAL
+The argument
+.Ar clockid
+is not a valid clock id.
+.El
+.Sh SEE ALSO
+.Xr clock_getres 2 ,
+.Xr clock_gettime 2 ,
+.Xr clock_settime 2 ,
+.Xr timer_delete 2 ,
+.Xr timer_getoverrun 2 ,
+.Xr timer_gettime 2 ,
+.Xr timer_settime 2
+.Sh STANDARDS
+.St -p1003.1b-93 ,
+.St -p1003.1i-95
diff --git a/lib/nbsd_libc/sys/timer_delete.2 b/lib/nbsd_libc/sys/timer_delete.2
new file mode 100644 (file)
index 0000000..faf5cc1
--- /dev/null
@@ -0,0 +1,78 @@
+.\"    $NetBSD: timer_delete.2,v 1.5 2008/04/30 13:10:51 martin Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Christos Zoulas.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd September 13, 2003
+.Dt TIMER_DELETE 2
+.Os
+.Sh NAME
+.Nm timer_delete
+.Nd delete a per-process timer
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Ft int
+.Fn timer_delete "timer_t timerid"
+.Sh DESCRIPTION
+The
+.Fn timer_delete
+functions deletes the timer specified in the
+.Ar timerid
+argument.
+The
+.Ar timerid
+argument must point to valid timer id, created by
+.Xr timer_create 2 .
+If the deletion is successful, the timer is disarmed and deleted.
+Pending notification events (signals) may or may not be delivered.
+.Sh RETURN VALUES
+If successful, the
+.Fn timer_delete
+functions returns 0.
+Otherwise, it returns \-1, and sets
+.Dv errno
+to indicate error.
+.Sh ERRORS
+The
+.Fn timer_delete
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The argument
+.Ar timerid
+is not a valid timer id.
+.El
+.Sh SEE ALSO
+.Xr timer_create 2 ,
+.Xr timer_getoverrun 2 ,
+.Xr timer_gettime 2 ,
+.Xr timer_settime 2
+.Sh STANDARDS
+.St -p1003.1b-93 ,
+.St -p1003.1i-95
diff --git a/lib/nbsd_libc/sys/timer_settime.2 b/lib/nbsd_libc/sys/timer_settime.2
new file mode 100644 (file)
index 0000000..1ffe3c6
--- /dev/null
@@ -0,0 +1,171 @@
+.\"    $NetBSD: timer_settime.2,v 1.6 2010/05/17 07:22:03 jruoho Exp $
+.\"
+.\" Copyright (c) 2003 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Christos Zoulas.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 17, 2010
+.Dt TIMER_SETTIME 2
+.Os
+.Sh NAME
+.Nm timer_settime ,
+.Nm timer_gettime ,
+.Nm timer_getoverrun
+.Nd process timer manipulation
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Ft int
+.Fn timer_settime "timer_t timerid" "int flags" "const struct itimerspec * restrict tim" "struct itimerspec * restrict otim"
+.Ft int
+.Fn timer_gettime "timer_t timerid" "struct itimerspec *tim"
+.Ft int
+.Fn timer_getoverrun "timer_t timerid"
+.Sh DESCRIPTION
+The
+.Fn timer_settime
+sets the next expiration time of the timer with ID
+.Ar timerid
+to the
+.Fa it_value
+(see
+.Xr itimerspec 3 )
+specified in the
+.Ar tim
+argument.
+If the value is 0, the timer is disarmed.
+If the argument
+.Ar otim
+is not
+.Dv NULL
+the old timer settingas are returned.
+.Pp
+If the
+.Ar flags
+argument is set to
+.Dv TIMER_RELTIME
+then the expiration time is set to the value in nanoseconds specified
+in the
+.Ar tim
+argument from the time the call to
+.Fn timer_settime
+was made.
+If the
+.Ar flags
+argument is set to
+.Dv TIMER_ABSTIME
+then the expiration time is set to be equal to the difference between the
+clock associated with this timer, and the value specified in the
+.Ar tim
+argument.
+If that time has already passed, then the call succeeds, and the
+expiration notification occurs.
+.Pp
+If the
+.Fa it_interval
+of the
+.Ar tim
+argument is non-zero, then the timer reloads upon expiration.
+.Pp
+The
+.Fn timer_gettime
+function returns the current settings of the timer
+specified by the
+.Ar timerid
+argument in the
+.Ar tim
+argument.
+.Pp
+Only one notification event (signal) can be pending for a given timer
+and process.
+If a timer expires while the signal is still queued for delivery, then
+the overrun counter for that timer is increased.
+The counter can store values up to
+.Dv DELAYTIMER_MAX .
+When the signal is finally delivered to the process, then the
+.Fn timer_getoverrun
+function can be used to retrieve the overrun counter for the timer
+specified in the
+.Ar timerid
+argument.
+.Sh NOTES
+Expiration time values are always rounded up to the resolution of the timer,
+so a notification will never be sent before the requested time.
+Values returned in the
+.Ar otim
+argument of
+.Fn timer_settime
+or in the
+.Ar tim
+argment of
+.Fn timer_gettime
+are subject to the above rounding effect and might not exactly match the
+requested values by the user.
+.Sh RETURN VALUES
+If successful, the
+.Fn timer_gettime
+and
+.Fn timer_settime
+functions return 0, and the
+.Fn timer_getoverrun
+function returns the expiration overrun count for the specified timer.
+Otherwise, the functions return \-1, and set
+.Dv errno
+to indicate the error.
+.Sh ERRORS
+The
+.Fn timer_gettime ,
+.Fn timer_getoverrun ,
+and
+.Fn timer_settime
+functions will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The argument
+.Ar timerid
+does not correspond to a valid timer id as returned by
+.Fn timer_create
+or that timer id has been deleted by
+.Fn timer_delete .
+.El
+.Pp
+The
+.Fn timer_settime
+function will fail if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+A nanosecond field in the
+.Ar tim
+structure specified a value less than zero or greater than or equal to 10e9.
+.El
+.Sh SEE ALSO
+.Xr clock_gettime 2 ,
+.Xr timer_create 2 ,
+.Xr timer_delete 2
+.Sh STANDARDS
+.St -p1003.1b-93 ,
+.St -p1003.1i-95
diff --git a/lib/nbsd_libc/sys/truncate.2 b/lib/nbsd_libc/sys/truncate.2
new file mode 100644 (file)
index 0000000..24e91c7
--- /dev/null
@@ -0,0 +1,152 @@
+.\"    $NetBSD: truncate.2,v 1.26 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1983, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)truncate.2 8.1 (Berkeley) 6/4/93
+.\"
+.Dd March 16, 2008
+.Dt TRUNCATE 2
+.Os
+.Sh NAME
+.Nm truncate ,
+.Nm ftruncate
+.Nd truncate a file to a specified length
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn truncate "const char *path" "off_t length"
+.Ft int
+.Fn ftruncate "int fd" "off_t length"
+.Sh DESCRIPTION
+.Fn truncate
+causes the file named by
+.Fa path
+or referenced by
+.Fa fd
+to have a size of
+.Fa length
+bytes.
+If the file previously was larger than this size, the extra data is discarded.
+If it was previously shorter than
+.Fa length ,
+its size is increased to the specified value and
+the extended area appears as if it were zero-filled.
+.Pp
+With
+.Fn ftruncate ,
+the file must be open for writing; for
+.Fn truncate ,
+the process must have write permissions for the file.
+.Sh RETURN VALUES
+A value of 0 is returned if the call succeeds.
+If the call fails a \-1 is returned, and the global variable
+.Va errno
+specifies the error.
+.Sh ERRORS
+Error return codes common to
+.Fn truncate
+and
+.Fn ftruncate
+are:
+.Bl -tag -width Er
+.It Bq Er EISDIR
+The named file is a directory.
+.It Bq Er EROFS
+The named file resides on a read-only file system.
+.It Bq Er ETXTBSY
+The file is a pure procedure (shared text) file that is being executed.
+.It Bq Er EIO
+An I/O error occurred updating the inode.
+.It Bq Er ENOSPC
+There was no space in the filesystem to complete the operation.
+.El
+.Pp
+Error codes specific to
+.Fn truncate
+are:
+.Bl -tag -width Er
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named file does not exist.
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix, or
+the named file is not writable by the user.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.El
+.Pp
+Error codes specific to
+.Fn ftruncate
+are:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa fd
+is not a valid descriptor.
+.It Bq Er EINVAL
+The
+.Fa fd
+references a socket, not a file, or
+the
+.Fa fd
+is not open for writing.
+.El
+.Sh SEE ALSO
+.Xr open 2
+.Sh STANDARDS
+Use of
+.Fn truncate
+to extend a file is an
+.St -p1003.1-2004
+extension, and is thus not portable.
+Files can be extended in a portable way seeking (using
+.Xr lseek 2 )
+to the required size and writing a single character with
+.Xr write 2 .
+.Sh HISTORY
+The
+.Fn truncate
+and
+.Fn ftruncate
+function calls appeared in
+.Bx 4.2 .
+.Sh BUGS
+These calls should be generalized to allow ranges
+of bytes in a file to be discarded.
diff --git a/lib/nbsd_libc/sys/truncate.c b/lib/nbsd_libc/sys/truncate.c
new file mode 100644 (file)
index 0000000..475d047
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: truncate.c,v 1.12 2007/11/23 12:39:16 uebayasi Exp $   */
+
+/*
+ * Copyright (c) 1992, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)truncate.c 8.1 (Berkeley) 6/17/93";
+#else
+__RCSID("$NetBSD: truncate.c,v 1.12 2007/11/23 12:39:16 uebayasi Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+int __truncate(const char *, int, off_t);
+
+/*
+ * This function provides 64-bit offset padding that
+ * is not supplied by GCC 1.X but is supplied by GCC 2.X.
+ */
+int
+truncate(path, length)
+       const char *path;
+       off_t length;
+{
+
+       return __truncate(path, 0, length);
+}
diff --git a/lib/nbsd_libc/sys/umask.2 b/lib/nbsd_libc/sys/umask.2
new file mode 100644 (file)
index 0000000..afb66fd
--- /dev/null
@@ -0,0 +1,84 @@
+.\"    $NetBSD: umask.2,v 1.16 2003/08/07 16:44:10 agc Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)umask.2    8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt UMASK 2
+.Os
+.Sh NAME
+.Nm umask
+.Nd set file creation mode mask
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/stat.h
+.Ft mode_t
+.Fn umask "mode_t numask"
+.Sh DESCRIPTION
+The
+.Fn umask
+routine sets the process's file mode creation mask to
+.Fa numask
+and returns the previous value of the mask.
+The 9 low-order access permission bits of
+.Fa numask
+are used by system calls, including
+.Xr open 2 ,
+.Xr mkdir 2 ,
+.Xr mkfifo 2
+and
+.Xr mknod 2
+to turn off corresponding bits
+requested in file mode.
+(See
+.Xr chmod 2 ) .
+This clearing allows each user to restrict the default access
+to his files.
+.Pp
+The default mask value is S_IWGRP|S_IWOTH (022, write access for the
+owner only).
+Child processes inherit the mask of the calling process.
+.Sh RETURN VALUES
+The previous value of the file mode mask is returned by the call.
+.Sh ERRORS
+The
+.Fn umask
+function is always successful.
+.Sh SEE ALSO
+.Xr chmod 2 ,
+.Xr mkdir 2 ,
+.Xr mkfifo 2 ,
+.Xr mknod 2 ,
+.Xr open 2
+.Sh STANDARDS
+The
+.Fn umask
+function conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/sys/undelete.2 b/lib/nbsd_libc/sys/undelete.2
new file mode 100644 (file)
index 0000000..be98d7a
--- /dev/null
@@ -0,0 +1,128 @@
+.\"    $NetBSD: undelete.2,v 1.15 2009/01/11 02:46:30 christos Exp $
+.\"
+.\" Copyright (c) 1994
+.\"    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.
+.\" 3. 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.
+.\"
+.\" Copyright (c) 1994
+.\"    Jan-Simon Pendry
+.\"
+.\" 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. All advertising materials mentioning features or use of this software
+.\"    must display the following acknowledgement:
+.\"    This product includes software developed by the University of
+.\"    California, Berkeley and its contributors.
+.\" 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.
+.\"
+.\"     @(#)undelete.2 8.4 (Berkeley) 10/18/94
+.\"
+.Dd November 28, 2008
+.Dt UNDELETE 2
+.Os
+.Sh NAME
+.Nm undelete
+.Nd remove whiteout
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn undelete "const char *path"
+.Sh DESCRIPTION
+Currently
+.Nm
+works only when the named object
+is a whiteout in a union filesystem.
+The system call removes the whiteout causing
+any objects in a lower layer of the
+union stack to become visible once more.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn undelete
+succeeds unless:
+.Bl -tag -width ENAMETOOLONGAA
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix, or
+write permission is denied on the directory containing the name
+to be undeleted.
+.It Bq Er EEXIST
+The path does not reference a whiteout.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.It Bq Er EINVAL
+The pathname contains a character with the high-order bit set.
+.It Bq Er EIO
+An I/O error occurred while updating the directory entry.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded 255 characters,
+or an entire path name exceeded 1023 characters.
+.It Bq Er ENOENT
+The named whiteout does not exist.
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er EPERM
+The directory containing the name is marked sticky,
+and the containing directory is not owned by the effective user ID.
+.It Bq Er EROFS
+The name resides on a read-only file system.
+.El
+.Sh SEE ALSO
+.Xr unlink 2 ,
+.Xr mount_union 8
+.Sh HISTORY
+An
+.Nm undelete
+function call first appeared in
+.Bx 4.4 -Lite .
diff --git a/lib/nbsd_libc/sys/unlink.2 b/lib/nbsd_libc/sys/unlink.2
new file mode 100644 (file)
index 0000000..7067eff
--- /dev/null
@@ -0,0 +1,120 @@
+.\"    $NetBSD: unlink.2,v 1.23 2010/05/31 12:16:20 njoly Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)unlink.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 3, 2010
+.Dt UNLINK 2
+.Os
+.Sh NAME
+.Nm unlink
+.Nd remove directory entry
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn unlink "const char *path"
+.Sh DESCRIPTION
+The
+.Fn unlink
+function
+removes the link named by
+.Fa path
+from its directory and decrements the link count of the
+file which was referenced by the link.
+If that decrement reduces the link count of the file
+to zero,
+and no process has the file open, then
+all resources associated with the file are reclaimed.
+If one or more process have the file open when the last link is removed,
+the link is removed, but the removal of the file is delayed until
+all references to it have been closed.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+The
+.Fn unlink
+succeeds unless:
+.Bl -tag -width Er
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix, or
+write permission is denied on the directory containing the link
+to be removed.
+.It Bq Er EBUSY
+The entry to be unlinked is the mount point for a
+mounted file system.
+.It Bq Er EFAULT
+.Fa path
+points outside the process's allocated address space.
+.It Bq Er EIO
+An I/O error occurred while deleting the directory entry
+or deallocating the inode.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named file does not exist.
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er EPERM
+The named file is a directory and the effective user ID
+of the process is not the super-user, the file system
+containing the file does not permit the use of
+.Fn unlink
+on a directory,
+or the directory containing the file is marked sticky,
+and neither the containing directory nor the file to be removed
+are owned by the effective user ID.
+.It Bq Er EROFS
+The named file resides on a read-only file system.
+.El
+.Sh SEE ALSO
+.Xr close 2 ,
+.Xr link 2 ,
+.Xr rmdir 2 ,
+.Xr symlink 7
+.Sh STANDARDS
+The
+.Fn unlink
+function conforms to
+.St -p1003.1-90 .
+.Sh HISTORY
+An
+.Fn unlink
+function call appeared in
+.At v2 .
diff --git a/lib/nbsd_libc/sys/utimes.2 b/lib/nbsd_libc/sys/utimes.2
new file mode 100644 (file)
index 0000000..1d25a30
--- /dev/null
@@ -0,0 +1,201 @@
+.\"    $NetBSD: utimes.2,v 1.26 2010/04/29 17:02:38 jruoho Exp $
+.\"
+.\" 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.
+.\" 3. 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.
+.\"
+.\"     @(#)utimes.2   8.1 (Berkeley) 6/4/93
+.\"
+.Dd April 29, 2010
+.Dt UTIMES 2
+.Os
+.Sh NAME
+.Nm utimes ,
+.Nm lutimes ,
+.Nm futimes
+.Nd set file access and modification times
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/time.h
+.Ft int
+.Fn utimes "const char *path" "const struct timeval times[2]"
+.Ft int
+.Fn lutimes "const char *path" "const struct timeval times[2]"
+.Ft int
+.Fn futimes "int fd" "const struct timeval times[2]"
+.Sh DESCRIPTION
+The access and modification times of the file named by
+.Fa path
+or referenced by
+.Fa fd
+are changed as specified by the argument
+.Fa times .
+.Pp
+If
+.Fa times
+is
+.Dv NULL ,
+the access and modification times are set to the current time.
+The caller must be the owner of the file, have permission to
+write the file, or be the super-user.
+.Pp
+If
+.Fa times
+is
+.Pf non- Dv NULL ,
+it is assumed to point to an array of two timeval structures.
+The access time is set to the value of the first element, and the
+modification time is set to the value of the second element.
+For file systems that support file birth (creation) times (such as
+UFS2), the birth time will be set to the value of the second element
+if the second element is older than the currently set birth time.
+To set both a birth time and a modification time, two calls are
+required; the first to set the birth time and the second to set
+the (presumably newer) modification time.
+Ideally a new system call will be added that allows the setting of
+all three times at once.
+The caller must be the owner of the file or be the super-user.
+.Pp
+In either case, the inode-change-time of the file is set to the current
+time.
+.Pp
+.Fn lutimes
+is like
+.Fn utimes
+except in the case where the named file is a symbolic link,
+in which case
+.Fn lutimes
+changes the access and modification times of the link,
+while
+.Fn utimes
+changes the times of the file the link references.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn utimes
+and
+.Fn lutimes
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+Search permission is denied for a component of the path prefix;
+or the
+.Fa times
+argument is
+.Dv NULL
+and the effective user ID of the process does not
+match the owner of the file, and is not the super-user, and write
+access is denied.
+.It Bq Er EFAULT
+.Fa path
+or
+.Fa times
+points outside the process's allocated address space.
+.It Bq Er EIO
+An I/O error occurred while reading or writing the affected inode.
+.It Bq Er ELOOP
+Too many symbolic links were encountered in translating the pathname.
+.It Bq Er ENAMETOOLONG
+A component of a pathname exceeded
+.Brq Dv NAME_MAX
+characters, or an entire path name exceeded
+.Brq Dv PATH_MAX
+characters.
+.It Bq Er ENOENT
+The named file does not exist.
+.It Bq Er ENOTDIR
+A component of the path prefix is not a directory.
+.It Bq Er EPERM
+The
+.Fa times
+argument is not
+.Dv NULL
+and the calling process's effective user ID
+does not match the owner of the file and is not the super-user.
+.It Bq Er EROFS
+The file system containing the file is mounted read-only.
+.El
+.Pp
+.Fn futimes
+will fail if:
+.Bl -tag -width Er
+.It Bq Er EACCES
+The
+.Fa times
+argument is
+.Dv NULL
+and the effective user ID of the process does not
+match the owner of the file, and is not the super-user, and write
+access is denied.
+.It Bq Er EBADF
+.Fa fd
+does not refer to a valid descriptor.
+.It Bq Er EFAULT
+.Fa times
+points outside the process's allocated address space.
+.It Bq Er EIO
+An I/O error occurred while reading or writing the affected inode.
+.It Bq Er EPERM
+The
+.Fa times
+argument is not
+.Dv NULL
+and the calling process's effective user ID
+does not match the owner of the file and is not the super-user.
+.It Bq Er EROFS
+The file system containing the file is mounted read-only.
+.El
+.Sh SEE ALSO
+.Xr stat 2 ,
+.Xr utime 3 ,
+.Xr symlink 7
+.Sh STANDARDS
+The
+.Fn utimes
+function conforms to
+.St -p1003.1-2001 .
+It was however marked as legacy in the
+.St -p1003.1-2004
+revision.
+.Sh HISTORY
+The
+.Fn utimes
+function call appeared in
+.Bx 4.2 .
+The
+.Fn futimes
+function call appeared in
+.Nx 1.2 .
+The
+.Fn lutimes
+function call appeared in
+.Nx 1.3 .
+Birthtime setting support was added in
+.Nx 5.0 .
diff --git a/lib/nbsd_libc/sys/utrace.2 b/lib/nbsd_libc/sys/utrace.2
new file mode 100644 (file)
index 0000000..73936a7
--- /dev/null
@@ -0,0 +1,92 @@
+.\"    $NetBSD: utrace.2,v 1.13 2008/05/02 18:38:32 martin Exp $
+.\"
+.\" Copyright (c) 2000 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Gregory McGarry <g.mcgarry@ieee.org>.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd December 28, 2000
+.Dt UTRACE 2
+.Os
+.Sh NAME
+.Nm utrace
+.Nd insert user record in ktrace log
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/param.h
+.In sys/time.h
+.In sys/uio.h
+.In sys/ktrace.h
+.Ft int
+.Fn utrace "const char *label" "void *addr" "size_t len"
+.Sh DESCRIPTION
+Adds a record to the process trace with information supplied by user.
+The record is identified by
+.Fa label
+and contains
+.Fa len
+bytes from memory pointed to by
+.Fa addr .
+This call only has an effect if the calling process is being traced.
+.Sh RETURN VALUES
+Upon successful completion, a value of 0 is returned.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Bl -tag -width Er
+.It Bq Er ENOSYS
+Currently running kernel was compiled without
+.Xr ktrace 2
+support (option KTRACE).
+.It Bq Er EINVAL
+Specified data length
+.Fa len
+was bigger than
+.Dv KTR_USER_MAXLEN .
+.El
+.Sh SEE ALSO
+.Xr kdump 1 ,
+.Xr ktrace 1 ,
+.Xr ktruss 1 ,
+.Xr fktrace 2 ,
+.Xr ktrace 2 ,
+.Xr options 4
+.Sh HISTORY
+The
+.Fn utrace
+system call first appeared in
+.Fx 2.2 .
+It was added to
+.Nx
+in
+.Nx 1.6 .
+The
+.Fa label
+argument is a
+.Nx
+extension.
diff --git a/lib/nbsd_libc/sys/uuidgen.2 b/lib/nbsd_libc/sys/uuidgen.2
new file mode 100644 (file)
index 0000000..f1c6a60
--- /dev/null
@@ -0,0 +1,147 @@
+.\" $NetBSD: uuidgen.2,v 1.4 2005/01/30 18:13:04 jwise Exp $
+.\" $FreeBSD: src/lib/libc/sys/uuidgen.2,v 1.7 2003/06/27 13:41:29 yar Exp $
+.\" Copyright (c) 2002 Marcel Moolenaar
+.\" 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 ``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 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.
+.\"
+.\" $FreeBSD: src/lib/libc/sys/uuidgen.2,v 1.7 2003/06/27 13:41:29 yar Exp $
+.\"
+.Dd May 26, 2002
+.Dt UUIDGEN 2
+.Os
+.Sh NAME
+.Nm uuidgen
+.Nd generate universally unique identifiers
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In sys/uuid.h
+.Ft int
+.Fn uuidgen "struct uuid *store" "int count"
+.Sh DESCRIPTION
+The
+.Fn uuidgen
+system call generates
+.Fa count
+universally unique identifiers (UUIDs) and writes them to the buffer
+pointed to by
+.Fa store .
+The identifiers are generated according to the syntax and semantics of the
+DCE version 1 variant of universally unique identifiers.
+See below for a more in-depth description of the identifiers.
+When no IEEE 802
+address is available for the node field, a random multi-cast address is
+generated for each invocation of the system call.
+According to the algorithm of generating time-based UUIDs, this will also
+force a new random clock sequence, thereby increasing the likelihood for
+the identifier to be unique.
+.Pp
+When multiple identifiers are to be generated, the
+.Fn uuidgen
+system call will generate a set of identifiers that is dense in such a way
+that there is no identifier that is larger than the smallest identifier in the
+set and smaller than the largest identifier in the set and that is not already
+in the set.
+.Pp
+Universally unique identifiers, also known as globally unique identifiers
+(GUIDs), have a binary representation of 128-bits.
+The grouping and meaning of these bits is described by the following
+structure and its description of the fields that follow it:
+.Bd -literal
+struct uuid {
+       uint32_t        time_low;
+       uint16_t        time_mid;
+       uint16_t        time_hi_and_version;
+       uint8_t         clock_seq_hi_and_reserved;
+       uint8_t         clock_seq_low;
+       uint8_t         node[_UUID_NODE_LEN];
+};
+.Ed
+.Bl -tag -width ".Va clock_seq_hi_and_reserved"
+.It Va time_low
+The least significant 32 bits of a 60-bit timestamp.
+This field is stored in the native byte-order.
+.It Va time_mid
+The least significant 16 bits of the most significant 28 bits of the 60-bit
+timestamp.
+This field is stored in the native byte-order.
+.It Va time_hi_and_version
+The most significant 12 bits of the 60-bit timestamp multiplexed with a 4-bit
+version number.
+The version number is stored in the most significant 4 bits of the 16-bit
+field.
+This field is stored in the native byte-order.
+.It Va clock_seq_hi_and_reserved
+The most significant 6 bits of a 14-bit sequence number multiplexed with a
+2-bit variant value.
+Note that the width of the variant value is determined by the variant itself.
+Identifiers generated by the
+.Fn uuidgen
+system call have variant value 10b.
+the variant value is stored in the most significant bits of the field.
+.It Va clock_seq_low
+The least significant 8 bits of a 14-bit sequence number.
+.It Va node
+The 6-byte IEEE 802 (MAC) address of one of the interfaces of the node.
+If no such interface exists, a random multi-cast address is used instead.
+.El
+.Pp
+The binary representation is sensitive to byte ordering.
+Any multi-byte field is to be stored in the local or native byte-order and
+identifiers must be converted when transmitted to hosts that do not agree
+on the byte-order.
+The specification does not however document what this means in concrete
+terms and is otherwise beyond the scope of this system call.
+.Sh RETURN VALUES
+.Rv -std
+.Sh ERRORS
+The
+.Fn uuidgen
+system call can fail with:
+.Bl -tag -width Er
+.It Bq Er EFAULT
+The buffer pointed to by
+.Fa store
+could not be written to for any or all identifiers.
+.It Bq Er EINVAL
+The
+.Fa count
+argument is less than 1 or larger than the hard upper limit of 2048.
+.El
+.Sh SEE ALSO
+.Xr uuidgen 1 ,
+.Xr uuid 3
+.Sh STANDARDS
+The identifiers are represented and generated in conformance with the DCE 1.1
+RPC specification.
+The
+.Fn uuidgen
+system call is itself not part of the specification.
+.Sh HISTORY
+The
+.Fn uuidgen
+system call first appeared in
+.Fx 5.0
+and was subsequently added to
+.Nx 2.0 .
diff --git a/lib/nbsd_libc/sys/vfork.2 b/lib/nbsd_libc/sys/vfork.2
new file mode 100644 (file)
index 0000000..586490b
--- /dev/null
@@ -0,0 +1,137 @@
+.\"    $NetBSD: vfork.2,v 1.24 2003/08/07 16:44:11 agc Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)vfork.2    8.1 (Berkeley) 6/4/93
+.\"
+.Dd January 3, 1998
+.Dt VFORK 2
+.Os
+.Sh NAME
+.Nm vfork
+.Nd spawn new process in a virtual memory efficient way
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft pid_t
+.Fn vfork void
+.Sh DESCRIPTION
+The
+.Nm
+system call creates a new process that does not have a new
+virtual address space, but rather shares address space with the
+parent, thus avoiding potentially expensive copy-on-write operations
+normally associated with creating a new process.
+It is useful when the purpose of
+.Xr fork 2
+would have been to create a new system context for an
+.Xr execve 2 .
+The
+.Nm
+system call differs from
+.Xr fork 2
+in that the child borrows the parent's memory and thread of
+control until a call to
+.Xr execve 2
+or an exit (either by a call to
+.Xr _exit 2
+or abnormally).
+The parent process is suspended while the child is using its resources.
+.Pp
+The
+.Nm
+system call returns 0 in the child's context and (later) the pid
+of the child in the parent's context.
+.Pp
+The
+.Nm
+system call can normally be used just like
+.Xr fork 2 .
+It does not work, however, to return while running in the childs context
+from the procedure that called
+.Fn vfork
+since the eventual return from
+.Fn vfork
+would then return to a no longer existent stack frame.
+Be careful, also, to call
+.Xr _exit 2
+rather than
+.Xr exit 3
+if you can't
+.Xr execve 2 ,
+since
+.Xr exit 3
+will flush and close standard I/O channels, and thereby mess up the
+standard I/O data structures
+in the parent process.
+(Even with
+.Xr fork 2
+it is wrong to call
+.Xr exit 3
+since buffered data would then be flushed twice.)
+.Sh RETURN VALUES
+Same as for
+.Xr fork 2 .
+.Sh ERRORS
+Same as for
+.Xr fork 2 .
+.Sh SEE ALSO
+.Xr execve 2 ,
+.Xr fork 2 ,
+.Xr sigaction 2 ,
+.Xr wait 2
+.Sh HISTORY
+The
+.Fn vfork
+function call appeared in
+.Bx 3.0 .
+In
+.Bx 4.4 ,
+the semantics were changed to only suspend the parent.
+The original semantics were reintroduced in
+.Nx 1.4 .
+.Sh BUGS
+.\" XXX We reintroduced the original semantics.
+.\" This system call will be eliminated when proper system sharing
+.\" mechanisms are implemented.
+Users should not depend on the memory sharing semantics of
+.Fn vfork
+as other ways of speeding up the fork process may be developed in
+the future.
+.Pp
+To avoid a possible deadlock situation, processes that are children
+in the middle of a
+.Fn vfork
+are never sent
+.Dv SIGTTOU
+or
+.Dv SIGTTIN
+signals; rather, output or
+.Xr ioctl 2
+calls are allowed and input attempts result in an end-of-file indication.
diff --git a/lib/nbsd_libc/sys/wait.2 b/lib/nbsd_libc/sys/wait.2
new file mode 100644 (file)
index 0000000..08c47b1
--- /dev/null
@@ -0,0 +1,335 @@
+.\"    $NetBSD: wait.2,v 1.27 2010/04/03 15:43:46 jruoho Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 1993, 1994
+.\"    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.
+.\" 3. 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.
+.\"
+.\"     @(#)wait.2     8.2 (Berkeley) 4/19/94
+.\"
+.Dd April 3, 2010
+.Dt WAIT 2
+.Os
+.Sh NAME
+.Nm wait ,
+.Nm waitpid ,
+.Nm wait4 ,
+.Nm wait3
+.Nd wait for process termination
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/wait.h
+.Ft pid_t
+.Fn wait "int *status"
+.Ft pid_t
+.Fn waitpid "pid_t wpid" "int *status" "int options"
+.In sys/resource.h
+.Ft pid_t
+.Fn wait3 "int *status" "int options" "struct rusage *rusage"
+.Ft pid_t
+.Fn wait4 "pid_t wpid" "int *status" "int options" "struct rusage *rusage"
+.Sh DESCRIPTION
+The
+.Fn wait
+function suspends execution of its calling process until
+.Fa status
+information is available for a terminated child process,
+or a signal is received.
+On return from a successful
+.Fn wait
+call,
+the
+.Fa status
+area contains termination information about the process that exited
+as defined below.
+.Pp
+The
+.Fn wait4
+call provides a more general interface for programs
+that need to wait for certain child processes,
+that need resource utilization statistics accumulated by child processes,
+or that require options.
+The other wait functions are implemented using
+.Fn wait4 .
+.Pp
+The
+.Fa wpid
+parameter specifies the set of child processes for which to wait.
+If
+.Fa wpid
+is \-1, the call waits for any child process.
+If
+.Fa wpid
+is 0,
+the call waits for any child process in the process group of the caller.
+If
+.Fa wpid
+is greater than zero, the call waits for the process with process id
+.Fa wpid .
+If
+.Fa wpid
+is less than \-1, the call waits for any process whose process group id
+equals the absolute value of
+.Fa wpid .
+.Pp
+The
+.Fa status
+parameter is defined below.
+.Pp
+The
+.Fa options
+parameter contains the bitwise OR of any of the following options:
+.Bl -tag -width WUNTRACED
+.It Dv WNOHANG
+This option is used to indicate that the call should not block if
+there are no processes that wish to report status.
+.It Dv WUNTRACED
+If this option is set, children of the current process that are stopped
+due to a
+.Dv SIGTTIN , SIGTTOU , SIGTSTP ,
+or
+.Dv SIGSTOP
+signal also have their status reported.
+.It Dv WALTSIG
+If this option is specified, the call will wait only for processes that
+are configured to post a signal other than
+.Dv SIGCHLD
+when they exit.
+If
+.Dv WALTSIG
+is not specified, the call will wait only for processes that
+are configured to post
+.Dv SIGCHLD .
+.It Dv __WCLONE
+This is an alias for
+.Dv WALTSIG .
+It is provided for compatibility with the Linux
+.Xr clone 2
+API.
+.It Dv WALLSIG
+If this option is specified, the call will wait for all children regardless
+of what exit signal they post.
+.It Dv __WALL
+This is an alias for
+.Dv WALLSIG .
+It is provided for compatibility with the Linux
+.Xr clone 2
+API .
+.El
+.Pp
+If
+.Fa rusage
+is non-zero, a summary of the resources used by the terminated
+process and all its
+children is returned (this information is currently not available
+for stopped processes).
+.Pp
+When the
+.Dv WNOHANG
+option is specified and no processes
+wish to report status,
+.Fn wait4
+returns a
+process id
+of 0.
+.Pp
+The
+.Fn waitpid
+call is identical to
+.Fn wait4
+with an
+.Fa rusage
+value of zero.
+The older
+.Fn wait3
+call is the same as
+.Fn wait4
+with a
+.Fa wpid
+value of \-1.
+.Pp
+The following macros may be used to test the manner of exit of the process.
+Note that these macros expect the
+.Fa status
+value itself, not a pointer to the
+.Fa status
+value.
+One of the first three macros will evaluate to a non-zero (true) value:
+.Bl -tag -width Ds
+.It Fn WIFEXITED status
+True if the process terminated normally by a call to
+.Xr _exit 2
+or
+.Xr exit 3 .
+.It Fn WIFSIGNALED status
+True if the process terminated due to receipt of a signal.
+.It Fn WIFSTOPPED status
+True if the process has not terminated, but has stopped and can be restarted.
+This macro can be true only if the wait call specified the
+.Dv WUNTRACED
+option
+or if the child process is being traced (see
+.Xr ptrace 2 ) .
+.El
+.Pp
+Depending on the values of those macros, the following macros
+produce the remaining status information about the child process:
+.Bl -tag -width Ds
+.It Fn WEXITSTATUS status
+If
+.Fn WIFEXITED status
+is true, evaluates to the low-order 8 bits
+of the argument passed to
+.Xr _exit 2
+or
+.Xr exit 3
+by the child.
+.It Fn WTERMSIG status
+If
+.Fn WIFSIGNALED status
+is true, evaluates to the number of the signal
+that caused the termination of the process.
+.It Fn WCOREDUMP status
+If
+.Fn WIFSIGNALED status
+is true, evaluates as true if the termination
+of the process was accompanied by the creation of a core file
+containing an image of the process when the signal was received.
+.It Fn WSTOPSIG status
+If
+.Fn WIFSTOPPED status
+is true, evaluates to the number of the signal
+that caused the process to stop.
+.El
+.Sh NOTES
+See
+.Xr sigaction 2
+for a list of termination signals.
+A status of 0 indicates normal termination.
+.Pp
+If a parent process terminates without
+waiting for all of its child processes to terminate,
+the remaining child processes are assigned the parent
+process 1 ID (the init process ID).
+.Pp
+If a signal is caught while any of the
+.Fn wait
+calls is pending,
+the call may be interrupted or restarted when the signal-catching routine
+returns,
+depending on the options in effect for the signal;
+see
+.Xr intro 2 ,
+System call restart.
+.Sh RETURN VALUES
+If
+.Fn wait
+returns due to a stopped
+or terminated child process, the process ID of the child
+is returned to the calling process.
+Otherwise, a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Pp
+If
+.Fn wait4 ,
+.Fn wait3
+or
+.Fn waitpid
+returns due to a stopped
+or terminated child process, the process ID of the child
+is returned to the calling process.
+If there are no children not previously awaited,
+\-1 is returned with
+.Va errno
+set to
+.Bq Er ECHILD .
+Otherwise, if
+.Dv WNOHANG
+is specified and there are
+no stopped or exited children, 0 is returned.
+If an error is detected or a caught signal aborts the call,
+a value of \-1 is returned and
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn wait
+will fail and return immediately if:
+.Bl -tag -width Er
+.It Bq Er ECHILD
+The calling process has no existing unwaited-for child processes.
+.It Bq Er EFAULT
+The
+.Fa status
+or
+.Fa rusage
+arguments point to an illegal address.
+(May not be detected before exit of a child process.)
+.It Bq Er EINTR
+The call was interrupted by a caught signal,
+or the signal did not have the
+.Dv SA_RESTART
+flag set.
+.El
+.Pp
+In addition,
+.Fn wait3 ,
+.Fn wait4 ,
+and
+.Fn waitpid
+will fail and return immediately if:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+An invalid value was specified for
+.Fa options .
+.El
+.Sh SEE ALSO
+.Xr _exit 2 ,
+.Xr sigaction 2
+.Sh STANDARDS
+The
+.Fn wait
+and
+.Fn waitpid
+functions conform to
+.St -p1003.1-90 ;
+the
+.Fn wait3
+function conforms to
+.St -xpg4 ;
+.Fn wait4
+is an extension.
+The
+.Fn WCOREDUMP
+macro
+and the ability to restart a pending
+.Fn wait
+call are extensions to the POSIX interface.
+.Sh HISTORY
+A
+.Fn wait
+function call appeared in
+.At v2 .
diff --git a/lib/nbsd_libc/sys/write.2 b/lib/nbsd_libc/sys/write.2
new file mode 100644 (file)
index 0000000..0e0a1b6
--- /dev/null
@@ -0,0 +1,287 @@
+.\"    $NetBSD: write.2,v 1.32 2010/04/05 07:53:47 wiz Exp $
+.\"
+.\" Copyright (c) 1980, 1991, 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.
+.\" 3. 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.
+.\"
+.\"     @(#)write.2    8.5 (Berkeley) 4/2/94
+.\"
+.Dd April 3, 2010
+.Dt WRITE 2
+.Os
+.Sh NAME
+.Nm write ,
+.Nm writev ,
+.Nm pwrite ,
+.Nm pwritev
+.Nd write output
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft ssize_t
+.Fn write "int d" "const void *buf" "size_t nbytes"
+.Ft ssize_t
+.Fn pwrite "int d" "const void *buf" "size_t nbytes" "off_t offset"
+.In sys/uio.h
+.Ft ssize_t
+.Fn writev "int d" "const struct iovec *iov" "int iovcnt"
+.Ft ssize_t
+.Fn pwritev "int d" "const struct iovec *iov" "int iovcnt" "off_t offset"
+.Sh DESCRIPTION
+.Fn write
+attempts to write
+.Fa nbytes
+of data to the object referenced by the descriptor
+.Fa d
+from the buffer pointed to by
+.Fa buf .
+.Fn writev
+performs the same action, but gathers the output data
+from the
+.Fa iovcnt
+buffers specified by the members of the
+.Fa iov
+array: iov[0], iov[1], ..., iov[iovcnt\|-\|1].
+.Fn pwrite
+and
+.Fn pwritev
+perform the same functions, but write to the specified position in
+the file without modifying the file pointer.
+.Pp
+For
+.Fn writev
+and
+.Fn pwritev ,
+the
+.Fa iovec
+structure is defined as:
+.Pp
+.Bd -literal -offset indent -compact
+struct iovec {
+       void *iov_base;
+       size_t iov_len;
+};
+.Ed
+.Pp
+Each
+.Fa iovec
+entry specifies the base address and length of an area
+in memory from which data should be written.
+.Fn writev
+and
+.Fn pwritev
+will always write a complete area before proceeding
+to the next.
+.Pp
+On objects capable of seeking, the
+.Fn write
+starts at a position
+given by the pointer associated with
+.Fa d
+(see
+.Xr lseek 2 ) .
+Upon return from
+.Fn write ,
+the pointer is incremented by the number of bytes which were written.
+.Pp
+Objects that are not capable of seeking always write from the current
+position.
+The value of the pointer associated with such an object
+is undefined.
+.Pp
+If the real user is not the super-user, then
+.Fn write
+clears the set-user-id bit on a file.
+This prevents penetration of system security
+by a user who
+.Dq captures
+a writable set-user-id file
+owned by the super-user.
+.Pp
+If
+.Fn write
+succeeds it will update the st_ctime and st_mtime fields of the file's
+meta-data (see
+.Xr stat 2 ) .
+.Pp
+When using non-blocking I/O on objects such as sockets that are subject
+to flow control,
+.Fn write
+and
+.Fn writev
+may write fewer bytes than requested;
+the return value must be noted,
+and the remainder of the operation should be retried when possible.
+.Sh RETURN VALUES
+Upon successful completion the number of bytes which were written
+is returned.
+Otherwise a \-1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh ERRORS
+.Fn write ,
+.Fn writev ,
+.Fn pwrite ,
+and
+.Fn pwritev
+will fail and the file pointer will remain unchanged if:
+.Bl -tag -width Er
+.It Bq Er EAGAIN
+The file was marked for non-blocking I/O,
+and no data could be written immediately.
+.It Bq Er EBADF
+.Fa d
+is not a valid descriptor open for writing.
+.It Bq Er EDQUOT
+The user's quota of disk blocks on the file system
+containing the file has been exhausted.
+.It Bq Er EFAULT
+Part of
+.Fa iov
+or data to be written to the file
+points outside the process's allocated address space.
+.It Bq Er EFBIG
+An attempt was made to write a file that exceeds the process's
+file size limit or the maximum file size.
+.It Bq Er EINTR
+A signal was received before any data could be written to a slow
+device.
+See
+.Xr sigaction 2
+for more information on the interaction between signals and system
+calls.
+.It Bq Er EINVAL
+The pointer associated with
+.Fa d
+was negative; or
+the total length of the I/O is more than can be expressed by the ssize_t
+return value.
+.It Bq Er EIO
+An I/O error occurred while reading from or writing to the file system.
+.It Bq Er ENOSPC
+There is no free space remaining on the file system
+containing the file.
+.It Bq Er EPIPE
+An attempt is made to write to a pipe that is not open
+for reading by any process; or
+an attempt is made to write to a socket of type
+.Dv SOCK_STREAM
+that is not connected to a peer socket.
+.El
+.Pp
+In addition,
+.Fn writev
+and
+.Fn pwritev
+may return one of the following errors:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+.Fa iovcnt
+was less than or equal to 0, or greater than
+.Dv {IOV_MAX} ;
+or one of the
+.Fa iov_len
+values in the
+.Fa iov
+array was negative; or
+the sum of the
+.Fa iov_len
+values in the
+.Fa iov
+array overflowed a 32-bit integer.
+.El
+.Pp
+The
+.Fn pwrite
+and
+.Fn pwritev
+calls may also return the following errors:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The specified file offset is invalid.
+.It Bq Er ESPIPE
+The file descriptor is associated with a pipe, socket, or FIFO.
+.El
+.Sh SEE ALSO
+.Xr fcntl 2 ,
+.Xr lseek 2 ,
+.Xr open 2 ,
+.Xr pipe 2 ,
+.Xr poll 2 ,
+.Xr select 2 ,
+.Xr sigaction 2
+.Sh STANDARDS
+The
+.Fn write
+function is expected to conform to
+.St -p1003.1-88 .
+The
+.Fn writev
+and
+.Fn pwrite
+functions conform to
+.St -xpg4.2 .
+.Sh HISTORY
+The
+.Fn pwritev
+function call
+appeared in
+.Nx 1.4 .
+The
+.Fn pwrite
+function call
+appeared in
+.At V.4 .
+The
+.Fn writev
+function call
+appeared in
+.Bx 4.2 .
+The
+.Fn write
+function call appeared in
+.At v2 .
+.Sh CAVEATS
+Error checks should explicitly test for \-1.
+Code such as
+.Bd -literal
+       while ((nr = write(fd, buf, sizeof(buf))) \*[Gt] 0)
+.Ed
+.Pp
+is not maximally portable, as some platforms allow for
+.Va nbytes
+to range between
+.Dv SSIZE_MAX
+and
+.Dv SIZE_MAX
+\- 2, in which case the return value of an error-free
+.Fn write
+may appear as a negative number distinct from \-1.
+Proper loops should use
+.Bd -literal
+       while ((nr = write(fd, buf, sizeof(buf))) != -1 \*[Am]\*[Am] nr != 0)
+.Ed
diff --git a/lib/nbsd_libc/termios/Makefile.inc b/lib/nbsd_libc/termios/Makefile.inc
new file mode 100644 (file)
index 0000000..c3b62d4
--- /dev/null
@@ -0,0 +1,16 @@
+#      $NetBSD: Makefile.inc,v 1.4 1998/02/14 20:20:44 kleink Exp $
+
+.PATH: ${.CURDIR}/termios
+
+SRCS+= cfgetispeed.c cfgetospeed.c cfmakeraw.c cfsetispeed.c cfsetospeed.c \
+       cfsetspeed.c tcdrain.c tcflow.c tcflush.c tcgetattr.c tcgetpgrp.c \
+       tcgetsid.c tcsendbreak.c tcsetattr.c tcsetpgrp.c
+
+MAN+=  tcgetpgrp.3 tcgetsid.3 tcsendbreak.3 tcsetattr.3 tcsetpgrp.3
+
+MLINKS+=tcsendbreak.3 tcdrain.3 tcsendbreak.3 tcflow.3 \
+       tcsendbreak.3 tcflush.3
+MLINKS+=tcsetattr.3 tcgetattr.3 tcsetattr.3 cfgetispeed.3 \
+       tcsetattr.3 cfgetospeed.3 tcsetattr.3 cfmakeraw.3 \
+       tcsetattr.3 cfsetispeed.3 tcsetattr.3 cfsetospeed.3 \
+       tcsetattr.3 cfsetspeed.3
diff --git a/lib/nbsd_libc/termios/cfgetispeed.c b/lib/nbsd_libc/termios/cfgetispeed.c
new file mode 100644 (file)
index 0000000..1dc8be9
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: cfgetispeed.c,v 1.7 2003/08/07 16:44:12 agc Exp $      */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: cfgetispeed.c,v 1.7 2003/08/07 16:44:12 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <stdio.h>
+#include <termios.h>
+
+#ifdef __weak_alias
+__weak_alias(cfgetispeed,_cfgetispeed)
+#endif
+
+speed_t
+cfgetispeed(t)
+       const struct termios *t;
+{
+
+       _DIAGASSERT(t != NULL);
+
+       return (t->c_ispeed);
+}
diff --git a/lib/nbsd_libc/termios/cfgetospeed.c b/lib/nbsd_libc/termios/cfgetospeed.c
new file mode 100644 (file)
index 0000000..746313f
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: cfgetospeed.c,v 1.7 2003/08/07 16:44:12 agc Exp $      */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: cfgetospeed.c,v 1.7 2003/08/07 16:44:12 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <stdio.h>
+#include <termios.h>
+
+#ifdef __weak_alias
+__weak_alias(cfgetospeed,_cfgetospeed)
+#endif
+
+speed_t
+cfgetospeed(t)
+       const struct termios *t;
+{
+
+       _DIAGASSERT(t != NULL);
+
+       return (t->c_ospeed);
+}
diff --git a/lib/nbsd_libc/termios/cfmakeraw.c b/lib/nbsd_libc/termios/cfmakeraw.c
new file mode 100644 (file)
index 0000000..cb2c1ff
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: cfmakeraw.c,v 1.9 2003/08/07 16:44:12 agc Exp $        */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: cfmakeraw.c,v 1.9 2003/08/07 16:44:12 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <stdio.h>
+#include <termios.h>
+
+#ifdef __weak_alias
+__weak_alias(cfmakeraw,_cfmakeraw)
+#endif
+
+/*
+ * Make a pre-existing termios structure into "raw" mode: character-at-a-time
+ * mode with no characters interpreted, 8-bit data path.
+ */
+void
+cfmakeraw(t)
+       struct termios *t;
+{
+
+       _DIAGASSERT(t != NULL);
+
+       t->c_iflag &= ~(IMAXBEL|IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
+       t->c_oflag &= ~OPOST;
+       t->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
+       t->c_cflag &= ~(CSIZE|PARENB);
+       t->c_cflag |= CS8;
+       /* XXX set MIN/TIME */
+}
diff --git a/lib/nbsd_libc/termios/cfsetispeed.c b/lib/nbsd_libc/termios/cfsetispeed.c
new file mode 100644 (file)
index 0000000..d59db90
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: cfsetispeed.c,v 1.7 2003/08/07 16:44:12 agc Exp $      */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: cfsetispeed.c,v 1.7 2003/08/07 16:44:12 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <stdio.h>
+#include <termios.h>
+
+#ifdef __weak_alias
+__weak_alias(cfsetispeed,_cfsetispeed)
+#endif
+
+int
+cfsetispeed(t, speed)
+       struct termios *t;
+       speed_t speed;
+{
+
+       _DIAGASSERT(t != NULL);
+
+       t->c_ispeed = speed;
+       return (0);
+}
diff --git a/lib/nbsd_libc/termios/cfsetospeed.c b/lib/nbsd_libc/termios/cfsetospeed.c
new file mode 100644 (file)
index 0000000..98797ab
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: cfsetospeed.c,v 1.7 2003/08/07 16:44:12 agc Exp $      */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: cfsetospeed.c,v 1.7 2003/08/07 16:44:12 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <stdio.h>
+#include <termios.h>
+
+#ifdef __weak_alias
+__weak_alias(cfsetospeed,_cfsetospeed)
+#endif
+
+int
+cfsetospeed(t, speed)
+       struct termios *t;
+       speed_t speed;
+{
+
+       _DIAGASSERT(t != NULL);
+
+       t->c_ospeed = speed;
+       return (0);
+}
diff --git a/lib/nbsd_libc/termios/cfsetspeed.c b/lib/nbsd_libc/termios/cfsetspeed.c
new file mode 100644 (file)
index 0000000..8105969
--- /dev/null
@@ -0,0 +1,61 @@
+/*     $NetBSD: cfsetspeed.c,v 1.7 2003/08/07 16:44:13 agc Exp $       */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: cfsetspeed.c,v 1.7 2003/08/07 16:44:13 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <stdio.h>
+#include <termios.h>
+
+#ifdef __weak_alias
+__weak_alias(cfsetspeed,_cfsetspeed)
+#endif
+
+int
+cfsetspeed(t, speed)
+       struct termios *t;
+       speed_t speed;
+{
+
+       _DIAGASSERT(t != NULL);
+
+       t->c_ispeed = t->c_ospeed = speed;
+       return (0);
+}
diff --git a/lib/nbsd_libc/termios/tcdrain.c b/lib/nbsd_libc/termios/tcdrain.c
new file mode 100644 (file)
index 0000000..155d3d3
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: tcdrain.c,v 1.8 2003/08/07 16:44:13 agc Exp $  */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: tcdrain.c,v 1.8 2003/08/07 16:44:13 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/ioctl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <termios.h>
+
+#ifdef __weak_alias
+__weak_alias(tcdrain,_tcdrain)
+#endif
+
+int
+tcdrain(fd)
+       int fd;
+{
+
+       _DIAGASSERT(fd != -1);
+
+       return (ioctl(fd, TIOCDRAIN, 0));
+}
diff --git a/lib/nbsd_libc/termios/tcflow.c b/lib/nbsd_libc/termios/tcflow.c
new file mode 100644 (file)
index 0000000..c426cd1
--- /dev/null
@@ -0,0 +1,80 @@
+/*     $NetBSD: tcflow.c,v 1.8 2003/08/07 16:44:13 agc Exp $   */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: tcflow.c,v 1.8 2003/08/07 16:44:13 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/ioctl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <termios.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(tcflow,_tcflow)
+#endif
+
+int
+tcflow(fd, action)
+       int fd, action;
+{
+       struct termios term;
+       u_char c;
+
+       _DIAGASSERT(fd != -1);
+
+       switch (action) {
+       case TCOOFF:
+               return (ioctl(fd, TIOCSTOP, 0));
+       case TCOON:
+               return (ioctl(fd, TIOCSTART, 0));
+       case TCION:
+       case TCIOFF:
+               if (tcgetattr(fd, &term) == -1)
+                       return (-1);
+               c = term.c_cc[action == TCIOFF ? VSTOP : VSTART];
+               if (c != _POSIX_VDISABLE && write(fd, &c, sizeof(c)) == -1)
+                       return (-1);
+               return (0);
+       default:
+               errno = EINVAL;
+               return (-1);
+       }
+       /* NOTREACHED */
+}
diff --git a/lib/nbsd_libc/termios/tcflush.c b/lib/nbsd_libc/termios/tcflush.c
new file mode 100644 (file)
index 0000000..6c03f9a
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: tcflush.c,v 1.9 2003/08/07 16:44:13 agc Exp $  */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: tcflush.c,v 1.9 2003/08/07 16:44:13 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/ioctl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <termios.h>
+
+#ifdef __weak_alias
+__weak_alias(tcflush,_tcflush)
+#endif
+
+int
+tcflush(fd, which)
+       int fd, which;
+{
+       int com;
+
+       _DIAGASSERT(fd != -1);
+
+       switch (which) {
+       case TCIFLUSH:
+               com = FREAD;
+               break;
+       case TCOFLUSH:
+               com = FWRITE;
+               break;
+       case TCIOFLUSH:
+               com = FREAD | FWRITE;
+               break;
+       default:
+               errno = EINVAL;
+               return (-1);
+       }
+       return (ioctl(fd, TIOCFLUSH, &com));
+}
diff --git a/lib/nbsd_libc/termios/tcgetattr.c b/lib/nbsd_libc/termios/tcgetattr.c
new file mode 100644 (file)
index 0000000..6583ba5
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: tcgetattr.c,v 1.9 2003/08/07 16:44:13 agc Exp $        */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: tcgetattr.c,v 1.9 2003/08/07 16:44:13 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/ioctl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <termios.h>
+
+#ifdef __weak_alias
+__weak_alias(tcgetattr,_tcgetattr)
+#endif
+
+int
+tcgetattr(fd, t)
+       int fd;
+       struct termios *t;
+{
+
+       _DIAGASSERT(t != NULL);
+
+       return (ioctl(fd, TIOCGETA, t));
+}
diff --git a/lib/nbsd_libc/termios/tcgetpgrp.3 b/lib/nbsd_libc/termios/tcgetpgrp.3
new file mode 100644 (file)
index 0000000..c3f44f8
--- /dev/null
@@ -0,0 +1,77 @@
+.\"    $NetBSD: tcgetpgrp.3,v 1.11 2003/08/07 16:44:13 agc Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)tcgetpgrp.3 8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt TCGETPGRP 3
+.Os
+.Sh NAME
+.Nm tcgetpgrp
+.Nd get foreground process group ID
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft pid_t
+.Fn tcgetpgrp "int fd"
+.Sh DESCRIPTION
+The
+.Nm tcgetpgrp
+function returns the value of the process group ID of the foreground
+process group associated with the terminal device.
+If there is no foreground process group,
+.Nm tcgetpgrp
+returns an invalid process ID.
+.Sh ERRORS
+If an error occurs,
+.Nm tcgetpgrp
+returns -1 and the global variable
+.Va errno
+is set to indicate the error, as follows:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa fd
+argument is not a valid file descriptor.
+.It Bq Er ENOTTY
+The calling process does not have a controlling terminal or the
+underlying terminal device represented by
+.Fa fd
+is not the controlling terminal.
+.El
+.Sh SEE ALSO
+.Xr setpgid 2 ,
+.Xr setsid 2 ,
+.Xr tcsetpgrp 3
+.Sh STANDARDS
+The
+.Nm tcgetpgrp
+function conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/termios/tcgetpgrp.c b/lib/nbsd_libc/termios/tcgetpgrp.c
new file mode 100644 (file)
index 0000000..8694c80
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: tcgetpgrp.c,v 1.9 2004/12/01 21:37:15 dsl Exp $        */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: tcgetpgrp.c,v 1.9 2004/12/01 21:37:15 dsl Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/ioctl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <termios.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(tcgetpgrp,_tcgetpgrp)
+#endif
+
+pid_t
+tcgetpgrp(fd)
+       int fd;
+{
+       int s;
+
+       _DIAGASSERT(fd != -1);
+
+       if (ioctl(fd, TIOCGPGRP, &s) < 0)
+               return ((pid_t)-1);
+
+       if (s == (pid_t)-1)
+               /* SVID requires a number > 1 that isn't a valid PGID... */
+               s = (uint)(pid_t)~0u >> 1;
+       return ((pid_t)s);
+}
diff --git a/lib/nbsd_libc/termios/tcgetsid.3 b/lib/nbsd_libc/termios/tcgetsid.3
new file mode 100644 (file)
index 0000000..b494c89
--- /dev/null
@@ -0,0 +1,76 @@
+.\"    $NetBSD: tcgetsid.3,v 1.5 2003/08/07 16:44:13 agc Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)tcgetpgrp.3 8.1 (Berkeley) 6/4/93
+.\"
+.Dd February 13, 1998
+.Dt TCGETSID 3
+.Os
+.Sh NAME
+.Nm tcgetsid
+.Nd get session ID associated with a controlling terminal
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In unistd.h
+.Ft pid_t
+.Fn tcgetsid "int fd"
+.Sh DESCRIPTION
+The
+.Nm tcgetsid
+function returns the value of the session ID associated with the specified
+controlling terminal device.
+The session ID is defined as the process group ID of the session leader.
+.Sh ERRORS
+If an error occurs,
+.Nm tcgetsid
+returns -1 and the global variable
+.Va errno
+is set to indicate the error, as follows:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa fd
+argument is not a valid file descriptor.
+.It Bq Er ENOTTY
+The calling process does not have a controlling terminal or the
+underlying terminal device represented by
+.Fa fd
+is not the controlling terminal.
+.El
+.Sh SEE ALSO
+.Xr getsid 2 ,
+.Xr setsid 2 ,
+.Xr tcgetpgrp 3
+.Sh STANDARDS
+The
+.Nm tcgetsid
+function conforms to
+.St -xpg4.2 .
diff --git a/lib/nbsd_libc/termios/tcgetsid.c b/lib/nbsd_libc/termios/tcgetsid.c
new file mode 100644 (file)
index 0000000..e6a7969
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: tcgetsid.c,v 1.6 2003/08/07 16:44:13 agc Exp $ */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: tcgetsid.c,v 1.6 2003/08/07 16:44:13 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/ioctl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <termios.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(tcgetsid,_tcgetsid)
+#endif
+
+pid_t
+tcgetsid(fd)
+       int fd;
+{
+       int s;
+
+       _DIAGASSERT(fd != -1);
+
+       if (ioctl(fd, TIOCGSID, &s) < 0)
+               return ((pid_t)-1);
+
+       return ((pid_t)s);
+}
diff --git a/lib/nbsd_libc/termios/tcsendbreak.3 b/lib/nbsd_libc/termios/tcsendbreak.3
new file mode 100644 (file)
index 0000000..27e7658
--- /dev/null
@@ -0,0 +1,154 @@
+.\"    $NetBSD: tcsendbreak.3,v 1.9 2003/08/07 16:44:13 agc Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)tcsendbreak.3       8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt TCSENDBREAK 3
+.Os
+.Sh NAME
+.Nm tcsendbreak ,
+.Nm tcdrain ,
+.Nm tcflush ,
+.Nm tcflow
+.Nd line control functions
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In termios.h
+.Ft int
+.Fn tcdrain "int fd"
+.Ft int
+.Fn tcflow "int fd" "int action"
+.Ft int
+.Fn tcflush "int fd" "int action"
+.Ft int
+.Fn tcsendbreak "int fd" "int len"
+.Sh DESCRIPTION
+The
+.Nm tcdrain
+function waits until all output written to the terminal referenced by
+.Fa fd
+has been transmitted to the terminal.
+.Pp
+The
+.Nm tcflow
+function suspends transmission of data to or the reception of data from
+the terminal referenced by
+.Fa fd
+depending on the value of
+.Fa action .
+The value of
+.Fa action
+must be one of the following:
+.Bl -tag -width "TCIOFF"
+.It Fa TCOOFF
+Suspend output.
+.It Fa TCOON
+Restart suspended output.
+.It Fa TCIOFF
+Transmit a STOP character, which is intended to cause the terminal to stop
+transmitting data to the system.
+(See the description of IXOFF in the
+.Ql Input Modes
+section of
+.Xr termios 4 ) .
+.It Fa TCION
+Transmit a START character, which is intended to cause the terminal to start
+transmitting data to the system.
+(See the description of IXOFF in the
+.Ql Input Modes
+section of
+.Xr termios 4 ) .
+.El
+.Pp
+The
+.Nm tcflush
+function discards any data written to the terminal referenced by
+.Fa fd
+which has not been transmitted to the terminal, or any data received
+from the terminal but not yet read, depending on the value of
+.Fa action .
+The value of
+.Fa action
+must be one of the following:
+.Bl -tag -width "TCIOFLUSH"
+.It Fa TCIFLUSH
+Flush data received but not read.
+.It Fa TCOFLUSH
+Flush data written but not transmitted.
+.It Fa TCIOFLUSH
+Flush both data received but not read and data written but not transmitted.
+.El
+.Pp
+The
+.Nm tcsendbreak
+function transmits a continuous stream of zero-valued bits for four-tenths
+of a second to the terminal referenced by
+.Fa fd .
+The
+.Fa len
+parameter is ignored in this implementation.
+.Sh RETURN VALUES
+Upon successful completion, all of these functions return a value of zero.
+.Sh ERRORS
+If any error occurs, a value of -1 is returned and the global variable
+.Va errno
+is set to indicate the error, as follows:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa fd
+argument is not a valid file descriptor.
+.It Bq Er EINVAL
+The
+.Fa action
+argument is not a proper value.
+.It Bq Er ENOTTY
+The file associated with
+.Fa fd
+is not a terminal.
+.It Bq Er EINTR
+A signal interrupted the
+.Nm tcdrain
+function.
+.El
+.Sh SEE ALSO
+.Xr tcsetattr 3 ,
+.Xr termios 4
+.Sh STANDARDS
+The
+.Nm tcsendbreak ,
+.Nm tcdrain ,
+.Nm tcflush
+and
+.Nm tcflow
+functions are expected to be compliant with the
+.St -p1003.1-88
+specification.
diff --git a/lib/nbsd_libc/termios/tcsendbreak.c b/lib/nbsd_libc/termios/tcsendbreak.c
new file mode 100644 (file)
index 0000000..1406147
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: tcsendbreak.c,v 1.9 2003/08/07 16:44:14 agc Exp $      */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: tcsendbreak.c,v 1.9 2003/08/07 16:44:14 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/time.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <termios.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(tcsendbreak,_tcsendbreak)
+#endif
+
+/*ARGSUSED*/
+int
+tcsendbreak(fd, len)
+       int fd, len;
+{
+       static const struct timespec sleepytime = { 0, 400000000 };
+
+       _DIAGASSERT(fd != -1);
+
+       if (ioctl(fd, TIOCSBRK, 0) == -1)
+               return (-1);
+       (void)nanosleep(&sleepytime, NULL);
+       if (ioctl(fd, TIOCCBRK, 0) == -1)
+               return (-1);
+       return (0);
+}
diff --git a/lib/nbsd_libc/termios/tcsetattr.3 b/lib/nbsd_libc/termios/tcsetattr.3
new file mode 100644 (file)
index 0000000..b5a3123
--- /dev/null
@@ -0,0 +1,331 @@
+.\"    $NetBSD: tcsetattr.3,v 1.13 2010/03/22 19:30:55 joerg Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)tcsetattr.3 8.3 (Berkeley) 1/2/94
+.\"
+.Dd May 1, 2004
+.Dt TCSETATTR 3
+.Os
+.Sh NAME
+.Nm cfgetispeed ,
+.Nm cfsetispeed ,
+.Nm cfgetospeed ,
+.Nm cfsetospeed ,
+.Nm cfsetspeed ,
+.Nm cfmakeraw ,
+.Nm tcgetattr ,
+.Nm tcsetattr
+.Nd manipulating the termios structure
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In termios.h
+.Ft speed_t
+.Fn cfgetispeed "const struct termios *t"
+.Ft int
+.Fn cfsetispeed "struct termios *t" "speed_t speed"
+.Ft speed_t
+.Fn cfgetospeed "const struct termios *t"
+.Ft int
+.Fn cfsetospeed "struct termios *t" "speed_t speed"
+.Ft int
+.Fn cfsetspeed "struct termios *t" "speed_t speed"
+.Ft void
+.Fn cfmakeraw "struct termios *t"
+.Ft int
+.Fn tcgetattr "int fd" "struct termios *t"
+.Ft int
+.Fn tcsetattr "int fd" "int action" "const struct termios *t"
+.Sh DESCRIPTION
+The
+.Nm cfmakeraw ,
+.Nm tcgetattr
+and
+.Nm tcsetattr
+functions are provided for getting and setting the termios structure.
+.Pp
+The
+.Nm cfgetispeed ,
+.Nm cfsetispeed ,
+.Nm cfgetospeed ,
+.Nm cfsetospeed
+and
+.Nm cfsetspeed
+functions are provided for getting and setting the baud rate values in
+the termios structure.
+The effects of the functions on the terminal as described below
+do not become effective, nor are all errors detected, until the
+.Nm tcsetattr
+function is called.
+Certain values for baud rates set in the termios structure and passed to
+.Nm tcsetattr
+have special meanings.
+These are discussed in the portion of the manual page that describes the
+.Nm tcsetattr
+function.
+.Sh GETTING AND SETTING THE BAUD RATE
+The input and output baud rates are found in the termios structure.
+The unsigned integer
+.Li speed_t
+is typdef'd in the include file
+.In termios.h .
+The value of the integer corresponds directly to the baud rate being
+represented, however, the following symbolic values are defined.
+.Bd -literal
+#define B0     0
+#define B50    50
+#define B75    75
+#define B110   110
+#define B134   134
+#define B150   150
+#define B200   200
+#define B300   300
+#define B600   600
+#define B1200  1200
+#define        B1800   1800
+#define B2400  2400
+#define B4800  4800
+#define B9600  9600
+#define B19200 19200
+#define B38400 38400
+#ifndef _POSIX_SOURCE
+#define EXTA   19200
+#define EXTB   38400
+#endif  /*_POSIX_SOURCE */
+.Ed
+.Pp
+The
+.Nm cfgetispeed
+function returns the input baud rate in the termios structure referenced by
+.Fa tp .
+.Pp
+The
+.Nm cfsetispeed
+function sets the input baud rate in the termios structure referenced by
+.Fa tp
+to
+.Fa speed .
+.Pp
+The
+.Nm cfgetospeed
+function returns the output baud rate in the termios structure referenced by
+.Fa tp .
+.Pp
+The
+.Nm cfsetospeed
+function sets the output baud rate in the termios structure referenced by
+.Fa tp
+to
+.Fa speed .
+.Pp
+The
+.Nm cfsetspeed
+function sets both the input and output baud rate in the termios structure
+referenced by
+.Fa tp
+to
+.Fa speed .
+.Pp
+Upon successful completion, the functions
+.Nm cfsetispeed ,
+.Nm cfsetospeed ,
+and
+.Nm cfsetspeed
+return a value of 0.
+Otherwise, a value of -1 is returned and the global variable
+.Va errno
+is set to indicate the error.
+.Sh GETTING AND SETTING THE TERMIOS STATE
+This section describes the functions that are used to control the general
+terminal interface.
+Unless otherwise noted for a specific command, these functions are restricted
+from use by background processes.
+Attempts to perform these operations shall cause the process group to be sent
+a SIGTTOU signal.
+If the calling process is blocking or ignoring SIGTTOU signals, the process
+is allowed to perform the operation and the SIGTTOU signal is not sent.
+.Pp
+In all the functions, although
+.Fa fd
+is an open file descriptor, the functions affect the underlying terminal
+file, not just the open file description associated with the particular
+file descriptor.
+.Pp
+The
+.Nm cfmakeraw
+function sets the flags stored in the termios structure (initialized by
+.Nm tcgetattr )
+to a state disabling all input and output processing, giving a
+.Dq raw I/O path .
+It should be noted that there is no function to reverse this effect.
+This is because there are a variety of processing options that could be
+re-enabled and the correct method is for an application to snapshot the
+current terminal state using the function
+.Nm tcgetattr ,
+setting raw mode with
+.Nm cfmakeraw
+and the subsequent
+.Nm tcsetattr ,
+and then using another
+.Nm tcsetattr
+with the saved state to revert to the previous terminal state.
+.Pp
+The
+.Nm tcgetattr
+function copies the parameters associated with the terminal referenced
+by
+.Fa fd
+to the termios structure referenced by
+.Fa tp .
+This function is allowed from a background process, however, the terminal
+attributes may be subsequently changed by a foreground process.
+.Pp
+The
+.Nm tcsetattr
+function sets the parameters associated with the terminal from the
+termios structure referenced by
+.Fa tp .
+The
+.Fa action
+field is created by
+.Em or Ns 'ing
+the following values, as specified in the include file
+.In termios.h .
+.Bl -tag -width "TCSADRAIN"
+.It Fa TCSANOW
+The change occurs immediately.
+.It Fa TCSADRAIN
+The change occurs after all output written to
+.Fa fd
+has been transmitted to the terminal.
+This value of
+.Fa action
+should be used when changing parameters that affect output.
+.It Fa TCSAFLUSH
+The change occurs after all output written to
+.Fa fd
+has been transmitted to the terminal.
+Additionally, any input that has been received but not read is discarded.
+.It Fa TCSASOFT
+If this value is
+.Em or Ns 'ed
+into the
+.Fa action
+value, the values of the
+.Em c_cflag ,
+.Em c_ispeed ,
+and
+.Em c_ospeed
+fields are ignored.
+.El
+.Pp
+The 0 baud rate is used to terminate the connection.
+If 0 is specified as the output speed to the function
+.Nm tcsetattr ,
+modem control will no longer be asserted on the terminal, disconnecting
+the terminal.
+.Pp
+If zero is specified as the input speed to the function
+.Nm tcsetattr ,
+the input baud rate will be set to the same value as that specified by
+the output baud rate.
+.Sh RETURN VALUES
+If
+.Nm tcsetattr
+is unable to make any of the requested changes, it returns -1 and
+sets errno.
+Otherwise, it makes all of the requested changes it can.
+If the specified input and output baud rates differ and are a combination
+that is not supported, neither baud rate is changed.
+.Pp
+Upon successful completion, the functions
+.Nm tcgetattr
+and
+.Nm tcsetattr
+return a value of 0.
+Otherwise, they
+return -1 and the global variable
+.Va errno
+is set to indicate the error, as follows:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa fd
+argument to
+.Nm tcgetattr
+or
+.Nm tcsetattr
+was not a valid file descriptor.
+.It Bq Er EINTR
+The
+.Nm tcsetattr
+function was interrupted by a signal.
+.It Bq Er EINVAL
+The
+.Fa action
+argument to the
+.Nm tcsetattr
+function was not valid, or an attempt was made to change an attribute
+represented in the termios structure to an unsupported value.
+.It Bq Er ENOTTY
+The file associated with the
+.Fa fd
+argument to
+.Nm tcgetattr
+or
+.Nm tcsetattr
+is not a terminal.
+.El
+.Sh SEE ALSO
+.Xr tcsendbreak 3 ,
+.Xr termios 4
+.Sh STANDARDS
+The
+.Nm cfgetispeed ,
+.Nm cfsetispeed ,
+.Nm cfgetospeed ,
+.Nm cfsetospeed ,
+.Nm tcgetattr
+and
+.Nm tcsetattr
+functions are expected to be compliant with the
+.St -p1003.1-88
+specification.
+The
+.Nm cfmakeraw
+and
+.Nm cfsetspeed
+functions,
+as well as the
+.Li TCSASOFT
+option to the
+.Nm tcsetattr
+function are extensions to the
+.St -p1003.1-88
+specification.
diff --git a/lib/nbsd_libc/termios/tcsetattr.c b/lib/nbsd_libc/termios/tcsetattr.c
new file mode 100644 (file)
index 0000000..8e8d27d
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: tcsetattr.c,v 1.8 2003/08/07 16:44:14 agc Exp $        */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: tcsetattr.c,v 1.8 2003/08/07 16:44:14 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/ioctl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <termios.h>
+
+#ifdef __weak_alias
+__weak_alias(tcsetattr,_tcsetattr)
+#endif
+
+int
+tcsetattr(fd, opt, t)
+       int fd, opt;
+       const struct termios *t;
+{
+       struct termios localterm;
+
+       _DIAGASSERT(fd != -1);
+       _DIAGASSERT(t != NULL);
+
+       if (opt & TCSASOFT) {
+               localterm = *t;
+               localterm.c_cflag |= CIGNORE;
+               t = &localterm;
+       }
+       switch (opt & ~TCSASOFT) {
+       case TCSANOW:
+               return (ioctl(fd, TIOCSETA, t));
+       case TCSADRAIN:
+               return (ioctl(fd, TIOCSETAW, t));
+       case TCSAFLUSH:
+               return (ioctl(fd, TIOCSETAF, t));
+       default:
+               errno = EINVAL;
+               return (-1);
+       }
+}
diff --git a/lib/nbsd_libc/termios/tcsetpgrp.3 b/lib/nbsd_libc/termios/tcsetpgrp.3
new file mode 100644 (file)
index 0000000..b0db4e0
--- /dev/null
@@ -0,0 +1,98 @@
+.\"    $NetBSD: tcsetpgrp.3,v 1.10 2003/08/07 16:44:14 agc Exp $
+.\"
+.\" Copyright (c) 1991, 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.
+.\" 3. 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.
+.\"
+.\"    @(#)tcsetpgrp.3 8.1 (Berkeley) 6/4/93
+.\"
+.Dd June 4, 1993
+.Dt TCSETPGRP 3
+.Os
+.Sh NAME
+.Nm tcsetpgrp
+.Nd set foreground process group ID
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In unistd.h
+.Ft int
+.Fn tcsetpgrp "int fd" "pid_t pgrp_id"
+.Sh DESCRIPTION
+If the process has a controlling terminal, the
+.Nm tcsetpgrp
+function sets the foreground process group ID associated with the
+terminal device to
+.Fa pgrp_id .
+The terminal device associated with
+.Fa fd
+must be the controlling terminal of the calling process and the
+controlling terminal must be currently associated with the session
+of the calling process.
+The value of
+.Fa pgrp_id
+must be the same as the process group ID of a process in the same
+session as the calling process.
+.Pp
+Upon successful completion,
+.Nm tcsetpgrp
+returns a value of zero.
+.Sh ERRORS
+If an error occurs,
+.Nm tcgetpgrp
+returns -1 and the global variable
+.Va errno
+is set to indicate the error, as follows:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa fd
+argument is not a valid file descriptor.
+.It Bq Er EINVAL
+An invalid value of
+.Fa pgrp_id
+was specified.
+.It Bq Er ENOTTY
+The calling process does not have a controlling terminal, or the file
+represented by
+.Fa fd
+is not the controlling terminal, or the controlling terminal is no
+longer associated with the session of the calling process.
+.It Bq Er EPERM
+The
+.Fa pgrp_id
+argument does not match the process group ID of a process in the same
+session as the calling process.
+.El
+.Sh SEE ALSO
+.Xr setpgid 2 ,
+.Xr setsid 2 ,
+.Xr tcgetpgrp 3
+.Sh STANDARDS
+The
+.Nm tcsetpgprp
+function conforms to
+.St -p1003.1-90 .
diff --git a/lib/nbsd_libc/termios/tcsetpgrp.c b/lib/nbsd_libc/termios/tcsetpgrp.c
new file mode 100644 (file)
index 0000000..8ce1d69
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: tcsetpgrp.c,v 1.9 2003/08/07 16:44:14 agc Exp $        */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)termios.c  8.2 (Berkeley) 2/21/94";
+#else
+__RCSID("$NetBSD: tcsetpgrp.c,v 1.9 2003/08/07 16:44:14 agc Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+#include <sys/types.h>
+#include <sys/ioctl.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <termios.h>
+#include <unistd.h>
+
+#ifdef __weak_alias
+__weak_alias(tcsetpgrp,_tcsetpgrp)
+#endif
+
+int
+tcsetpgrp(int fd, pid_t pgrp)
+{
+       int s;
+
+       _DIAGASSERT(fd != -1);
+
+       s = pgrp;
+       return (ioctl(fd, TIOCSPGRP, &s));
+}
diff --git a/lib/nbsd_libc/thread-stub/Makefile.inc b/lib/nbsd_libc/thread-stub/Makefile.inc
new file mode 100644 (file)
index 0000000..6c6c0a9
--- /dev/null
@@ -0,0 +1,8 @@
+#      $NetBSD: Makefile.inc,v 1.3 2003/01/18 11:33:18 thorpej Exp $
+
+.include <bsd.own.mk>
+
+# Our sources
+.PATH: ${.CURDIR}/thread-stub
+
+SRCS+= __isthreaded.c thread-stub.c
diff --git a/lib/nbsd_libc/thread-stub/__isthreaded.c b/lib/nbsd_libc/thread-stub/__isthreaded.c
new file mode 100644 (file)
index 0000000..50c1b6f
--- /dev/null
@@ -0,0 +1,37 @@
+/*     $NetBSD: __isthreaded.c,v 1.3 2009/12/01 01:33:25 explorer Exp $        */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Michael Graff.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: __isthreaded.c,v 1.3 2009/12/01 01:33:25 explorer Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+int __isthreaded = 0;
diff --git a/lib/nbsd_libc/thread-stub/thread-stub.c b/lib/nbsd_libc/thread-stub/thread-stub.c
new file mode 100644 (file)
index 0000000..29f4982
--- /dev/null
@@ -0,0 +1,466 @@
+/*     $NetBSD: thread-stub.c,v 1.21 2009/01/30 23:21:03 ad Exp $      */
+
+/*-
+ * Copyright (c) 2003, 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: thread-stub.c,v 1.21 2009/01/30 23:21:03 ad Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+/*
+ * Stubs for thread operations, for use when threads are not used by
+ * the application.  See "reentrant.h" for details.
+ */
+
+#ifdef _REENTRANT
+
+#define        __LIBC_THREAD_STUBS
+
+#include "namespace.h"
+#include "reentrant.h"
+
+#include <errno.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+extern int __isthreaded;
+
+#define        DIE()   (void)raise(SIGABRT)
+
+#define        CHECK_NOT_THREADED_ALWAYS()     \
+do {                                   \
+       if (__isthreaded)               \
+               DIE();                  \
+} while (/*CONSTCOND*/0)
+
+#if 1
+#define        CHECK_NOT_THREADED()    CHECK_NOT_THREADED_ALWAYS()
+#else
+#define        CHECK_NOT_THREADED()    /* nothing */
+#endif
+
+/* libpthread init */
+
+void   __libc_thr_init(void);
+void   __libc_thr_init_stub(void);
+
+__weak_alias(__libc_thr_init,__libc_thr_init_stub)
+
+void
+__libc_thr_init_stub(void)
+{
+
+       /* nothing, may be overridden by libpthread */
+}
+
+/* mutexes */
+
+int    __libc_mutex_init_stub(mutex_t *, const mutexattr_t *);
+int    __libc_mutex_catchall_stub(mutex_t *);
+
+__weak_alias(__libc_mutex_init,__libc_mutex_init_stub)
+__weak_alias(__libc_mutex_lock,__libc_mutex_catchall_stub)
+__weak_alias(__libc_mutex_trylock,__libc_mutex_catchall_stub)
+__weak_alias(__libc_mutex_unlock,__libc_mutex_catchall_stub)
+__weak_alias(__libc_mutex_destroy,__libc_mutex_catchall_stub)
+
+int    __libc_mutexattr_catchall_stub(mutexattr_t *);
+int    __libc_mutexattr_settype_stub(mutexattr_t *, int);
+
+__weak_alias(__libc_mutexattr_init,__libc_mutexattr_catchall_stub)
+__weak_alias(__libc_mutexattr_destroy,__libc_mutexattr_catchall_stub)
+__weak_alias(__libc_mutexattr_settype,__libc_mutexattr_settype_stub)
+
+int
+__libc_mutex_init_stub(mutex_t *m, const mutexattr_t *a)
+{
+       /* LINTED deliberate lack of effect */
+       (void)m;
+       /* LINTED deliberate lack of effect */
+       (void)a;
+
+       CHECK_NOT_THREADED();
+
+       return (0);
+}
+
+int
+__libc_mutex_catchall_stub(mutex_t *m)
+{
+       /* LINTED deliberate lack of effect */
+       (void)m;
+
+       CHECK_NOT_THREADED();
+
+       return (0);
+}
+
+int
+__libc_mutexattr_settype_stub(mutexattr_t *ma, int type)
+{
+       /* LINTED deliberate lack of effect */
+       (void)ma;
+       /* LINTED deliberate lack of effect */
+       (void)type;
+
+       return (0);
+}
+
+int
+__libc_mutexattr_catchall_stub(mutexattr_t *ma)
+{
+       /* LINTED deliberate lack of effect */
+       (void)ma;
+
+       CHECK_NOT_THREADED();
+
+       return (0);
+}
+
+/* condition variables */
+
+int    __libc_cond_init_stub(cond_t *, const condattr_t *);
+int    __libc_cond_wait_stub(cond_t *, mutex_t *);
+int    __libc_cond_timedwait_stub(cond_t *, mutex_t *,
+                                  const struct timespec *);
+int    __libc_cond_catchall_stub(cond_t *);
+
+__weak_alias(__libc_cond_init,__libc_cond_init_stub)
+__weak_alias(__libc_cond_signal,__libc_cond_catchall_stub)
+__weak_alias(__libc_cond_broadcast,__libc_cond_catchall_stub)
+__weak_alias(__libc_cond_wait,__libc_cond_wait_stub)
+__weak_alias(__libc_cond_timedwait,__libc_cond_timedwait_stub)
+__weak_alias(__libc_cond_destroy,__libc_cond_catchall_stub)
+
+int
+__libc_cond_init_stub(cond_t *c, const condattr_t *a)
+{
+       /* LINTED deliberate lack of effect */
+       (void)c;
+       /* LINTED deliberate lack of effect */
+       (void)a;
+
+       CHECK_NOT_THREADED();
+
+       return (0);
+}
+
+int
+__libc_cond_wait_stub(cond_t *c, mutex_t *m)
+{
+       /* LINTED deliberate lack of effect */
+       (void)c;
+       /* LINTED deliberate lack of effect */
+       (void)m;
+
+       CHECK_NOT_THREADED();
+
+       return (0);
+}
+
+int
+__libc_cond_timedwait_stub(cond_t *c, mutex_t *m, const struct timespec *t)
+{
+       /* LINTED deliberate lack of effect */
+       (void)c;
+       /* LINTED deliberate lack of effect */
+       (void)m;
+       /* LINTED deliberate lack of effect */
+       (void)t;
+
+       CHECK_NOT_THREADED();
+
+       return (0);
+}
+
+int
+__libc_cond_catchall_stub(cond_t *c)
+{
+       /* LINTED deliberate lack of effect */
+       (void)c;
+
+       CHECK_NOT_THREADED();
+
+       return (0);
+}
+
+
+/* read-write locks */
+
+int    __libc_rwlock_init_stub(rwlock_t *, rwlockattr_t *);
+int    __libc_rwlock_catchall_stub(rwlock_t *);
+
+__weak_alias(__libc_rwlock_init,__libc_rwlock_init_stub)
+__weak_alias(__libc_rwlock_rdlock,__libc_rwlock_catchall_stub)
+__weak_alias(__libc_rwlock_wrlock,__libc_rwlock_catchall_stub)
+__weak_alias(__libc_rwlock_tryrdlock,__libc_rwlock_catchall_stub)
+__weak_alias(__libc_rwlock_trywrlock,__libc_rwlock_catchall_stub)
+__weak_alias(__libc_rwlock_unlock,__libc_rwlock_catchall_stub)
+__weak_alias(__libc_rwlock_destroy,__libc_rwlock_catchall_stub)
+
+int
+__libc_rwlock_init_stub(rwlock_t *l, rwlockattr_t *a)
+{
+       /* LINTED deliberate lack of effect */
+       (void)l;
+       /* LINTED deliberate lack of effect */
+       (void)a;
+
+       CHECK_NOT_THREADED();
+
+       return (0);
+}
+
+int
+__libc_rwlock_catchall_stub(rwlock_t *l)
+{
+       /* LINTED deliberate lack of effect */
+       (void)l;
+
+       CHECK_NOT_THREADED();
+
+       return (0);
+}
+
+
+/*
+ * thread-specific data; we need to actually provide a simple TSD
+ * implementation, since some thread-safe libraries want to use it.
+ */
+
+#define        TSD_KEYS_MAX    64
+
+static struct {
+       void *tsd_val;
+       void (*tsd_dtor)(void *);
+       int tsd_inuse;
+} __libc_tsd[TSD_KEYS_MAX];
+static int __libc_tsd_nextkey;
+
+int    __libc_thr_keycreate_stub(thread_key_t *, void (*)(void *));
+int    __libc_thr_setspecific_stub(thread_key_t, const void *);
+void   *__libc_thr_getspecific_stub(thread_key_t);
+int    __libc_thr_keydelete_stub(thread_key_t);
+
+__weak_alias(__libc_thr_keycreate,__libc_thr_keycreate_stub)
+__weak_alias(__libc_thr_setspecific,__libc_thr_setspecific_stub)
+__weak_alias(__libc_thr_getspecific,__libc_thr_getspecific_stub)
+__weak_alias(__libc_thr_keydelete,__libc_thr_keydelete_stub)
+
+int
+__libc_thr_keycreate_stub(thread_key_t *k, void (*d)(void *))
+{
+       int i;
+
+       for (i = __libc_tsd_nextkey; i < TSD_KEYS_MAX; i++) {
+               if (__libc_tsd[i].tsd_inuse == 0)
+                       goto out;
+       }
+
+       for (i = 0; i < __libc_tsd_nextkey; i++) {
+               if (__libc_tsd[i].tsd_inuse == 0)
+                       goto out;
+       }
+
+       return (EAGAIN);
+
+ out:
+       /*
+        * XXX We don't actually do anything with the destructor.  We
+        * XXX probably should.
+        */
+       __libc_tsd[i].tsd_inuse = 1;
+       __libc_tsd_nextkey = (i + i) % TSD_KEYS_MAX;
+       __libc_tsd[i].tsd_dtor = d;
+       *k = i;
+
+       return (0);
+}
+
+int
+__libc_thr_setspecific_stub(thread_key_t k, const void *v)
+{
+
+       __libc_tsd[k].tsd_val = __UNCONST(v);
+
+       return (0);
+}
+
+void *
+__libc_thr_getspecific_stub(thread_key_t k)
+{
+
+       return (__libc_tsd[k].tsd_val);
+}
+
+int
+__libc_thr_keydelete_stub(thread_key_t k)
+{
+
+       /*
+        * XXX Do not recycle key; see big comment in libpthread.
+        */
+
+       __libc_tsd[k].tsd_dtor = NULL;
+
+       return (0);
+}
+
+
+/* misc. */
+
+int    __libc_thr_once_stub(once_t *, void (*)(void));
+int    __libc_thr_sigsetmask_stub(int, const sigset_t *, sigset_t *);
+thr_t  __libc_thr_self_stub(void);
+int    __libc_thr_yield_stub(void);
+int    __libc_thr_create_stub(thr_t *, const thrattr_t *,
+           void *(*)(void *), void *);
+void   __libc_thr_exit_stub(void *);
+int    *__libc_thr_errno_stub(void);
+int    __libc_thr_setcancelstate_stub(int, int *);
+int    __libc_thr_equal_stub(pthread_t, pthread_t);
+unsigned int __libc_thr_curcpu_stub(void);
+
+__weak_alias(__libc_thr_once,__libc_thr_once_stub)
+__weak_alias(__libc_thr_sigsetmask,__libc_thr_sigsetmask_stub)
+__weak_alias(__libc_thr_self,__libc_thr_self_stub)
+__weak_alias(__libc_thr_yield,__libc_thr_yield_stub)
+__weak_alias(__libc_thr_create,__libc_thr_create_stub)
+__weak_alias(__libc_thr_exit,__libc_thr_exit_stub)
+__weak_alias(__libc_thr_errno,__libc_thr_errno_stub)
+__weak_alias(__libc_thr_setcancelstate,__libc_thr_setcancelstate_stub)
+__weak_alias(__libc_thr_equal,__libc_thr_equal_stub)
+__weak_alias(__libc_thr_curcpu,__libc_thr_curcpu_stub)
+
+
+int
+__libc_thr_once_stub(once_t *o, void (*r)(void))
+{
+
+       /* XXX Knowledge of libpthread types. */
+
+       if (o->pto_done == 0) {
+               (*r)();
+               o->pto_done = 1;
+       }
+
+       return (0);
+}
+
+int
+__libc_thr_sigsetmask_stub(int h, const sigset_t *s, sigset_t *o)
+{
+
+       CHECK_NOT_THREADED();
+
+       return sigprocmask(h, s, o);
+}
+
+thr_t
+__libc_thr_self_stub(void)
+{
+
+       return ((thr_t) -1);
+}
+
+int
+__libc_thr_yield_stub(void)
+{
+
+       /* Nothing to do. */
+       return (0);
+}
+
+int
+__libc_thr_create_stub(thr_t *tp, const thrattr_t *ta,
+    void *(*f)(void *), void *a)
+{
+       /* LINTED deliberate lack of effect */
+       (void)tp;
+       /* LINTED deliberate lack of effect */
+       (void)ta;
+       /* LINTED deliberate lack of effect */
+       (void)f;
+       /* LINTED deliberate lack of effect */
+       (void)a;
+
+       DIE();
+
+       return (EOPNOTSUPP);
+}
+
+void
+__libc_thr_exit_stub(void *v)
+{
+       /* LINTED deliberate lack of effect */
+       (void)v;
+       exit(0);
+}
+
+int
+__libc_thr_setcancelstate_stub(int new, int *old)
+{
+       /* LINTED deliberate lack of effect */
+       (void)new;
+
+       /* LINTED deliberate lack of effect */
+       (void)old;
+
+       CHECK_NOT_THREADED();
+
+       return (0);
+}
+
+int
+__libc_thr_equal_stub(pthread_t t1, pthread_t t2)
+{
+
+       /* assert that t1=t2=pthread_self() */
+       return (t1 == t2);
+}
+
+int *
+__libc_thr_errno_stub(void)
+{
+
+       DIE();
+
+       return (NULL);
+}
+
+unsigned int
+__libc_thr_curcpu_stub(void)
+{
+
+       return (0);
+}
+
+#endif /* _REENTRANT */
diff --git a/lib/nbsd_libc/time/Makefile b/lib/nbsd_libc/time/Makefile
new file mode 100644 (file)
index 0000000..dd154b3
--- /dev/null
@@ -0,0 +1,421 @@
+# <pre>
+# @(#)Makefile 8.8
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
+
+# Change the line below for your time zone (after finding the zone you want in
+# the time zone files, or adding it to a time zone file).
+# Alternately, if you discover you've got the wrong time zone, you can just
+#      zic -l rightzone
+# to correct things.
+# Use the command
+#      make zonenames
+# to get a list of the values you can use for LOCALTIME.
+
+LOCALTIME=     Factory
+
+# If you want something other than Eastern United States time as a template
+# for handling POSIX-style time zone environment variables,
+# change the line below (after finding the zone you want in the
+# time zone files, or adding it to a time zone file).
+# (When a POSIX-style environment variable is handled, the rules in the
+# template file are used to determine "spring forward" and "fall back" days and
+# times; the environment variable itself specifies UTC offsets of standard and
+# summer time.)
+# Alternately, if you discover you've got the wrong time zone, you can just
+#      zic -p rightzone
+# to correct things.
+# Use the command
+#      make zonenames
+# to get a list of the values you can use for POSIXRULES.
+# If you want POSIX compatibility, use "America/New_York".
+
+POSIXRULES=    America/New_York
+
+# Also see TZDEFRULESTRING below, which takes effect only
+# if the time zone files cannot be accessed.
+
+# Everything gets put in subdirectories of. . .
+
+TOPDIR=                /usr/local
+
+# "Compiled" time zone information is placed in the "TZDIR" directory
+# (and subdirectories).
+# Use an absolute path name for TZDIR unless you're just testing the software.
+
+TZDIR=         $(TOPDIR)/etc/zoneinfo
+
+# The "tzselect", "zic", and "zdump" commands get installed in. . .
+
+ETCDIR=                $(TOPDIR)/etc
+
+# If you "make INSTALL", the "date" command gets installed in. . .
+
+BINDIR=                $(TOPDIR)/bin
+
+# Manual pages go in subdirectories of. . .
+
+MANDIR=                $(TOPDIR)/man
+
+# Library functions are put in an archive in LIBDIR.
+
+LIBDIR=                $(TOPDIR)/lib
+TZLIB=         $(LIBDIR)/libtz.a
+
+# If you always want time values interpreted as "seconds since the epoch
+# (not counting leap seconds)", use
+#      REDO=           posix_only
+# below.  If you always want right time values interpreted as "seconds since
+# the epoch" (counting leap seconds)", use
+#      REDO=           right_only
+# below.  If you want both sets of data available, with leap seconds not
+# counted normally, use
+#      REDO=           posix_right
+# below.  If you want both sets of data available, with leap seconds counted
+# normally, use
+#      REDO=           right_posix
+# below.
+# POSIX mandates that leap seconds not be counted; for compatibility with it,
+# use either "posix_only" or "posix_right".
+
+REDO=          posix_right
+
+# Since "." may not be in PATH...
+
+YEARISTYPE=    ./yearistype
+
+# Non-default libraries needed to link.
+# Add -lintl if you want to use `gettext' on Solaris.
+LDLIBS=
+
+# Add the following to the end of the "CFLAGS=" line as needed.
+#  -DHAVE_ADJTIME=0 if `adjtime' does not exist (SVR0?)
+#  -DHAVE_GETTEXT=1 if `gettext' works (GNU, Linux, Solaris); also see LDLIBS
+#  -DHAVE_INCOMPATIBLE_CTIME_R=1 if your system's time.h declares
+#      ctime_r and asctime_r incompatibly with the POSIX standard (Solaris 8).
+#  -DHAVE_SETTIMEOFDAY=0 if settimeofday does not exist (SVR0?)
+#  -DHAVE_SETTIMEOFDAY=1 if settimeofday has just 1 arg (SVR4)
+#  -DHAVE_SETTIMEOFDAY=2 if settimeofday uses 2nd arg (4.3BSD)
+#  -DHAVE_SETTIMEOFDAY=3 if settimeofday ignores 2nd arg (4.4BSD)
+#  -DHAVE_STDINT_H=1 if you have a pre-C99 compiler with "stdint.h"
+#  -DHAVE_SYMLINK=0 if your system lacks the symlink function
+#  -DHAVE_SYS_STAT_H=0 if your compiler lacks a "sys/stat.h"
+#  -DHAVE_SYS_WAIT_H=0 if your compiler lacks a "sys/wait.h"
+#  -DLOCALE_HOME=\"path\" if locales are in "path", not "/usr/lib/locale"
+#  -DHAVE_UNISTD_H=0 if your compiler lacks a "unistd.h" (Microsoft C++ 7?)
+#  -DHAVE_UTMPX_H=1 if your compiler has a "utmpx.h"
+#  -DTZDEFRULESTRING=\",date/time,date/time\" to default to the specified
+#      DST transitions if the time zone files cannot be accessed
+#  -DTZ_DOMAIN=\"foo\" to use "foo" for gettext domain name; default is "tz"
+#  -TTZ_DOMAINDIR=\"/path\" to use "/path" for gettext directory;
+#      the default is system-supplied, typically "/usr/lib/locale"
+#  $(GCC_DEBUG_FLAGS) if you are using GCC and want lots of checking
+#  -DNO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU=1
+#      if you do not want run time warnings about formats that may cause
+#      year 2000 grief
+#  -DZIC_MAX_ABBR_LEN_WO_WARN=3
+#      (or some other number) to set the maximum time zone abbreviation length
+#      that zic will accept without a warning (the default is 6)
+GCC_DEBUG_FLAGS = -Dlint -g -O -fno-common \
+       -Wall -Wcast-qual -Wconversion -Wmissing-prototypes \
+       -Wnested-externs -Wpointer-arith -Wshadow \
+       -Wtraditional # -Wstrict-prototypes -Wwrite-strings
+#
+# If you want to use System V compatibility code, add
+#      -DUSG_COMPAT
+# to the end of the "CFLAGS=" line.  This arrange for "timezone" and "daylight"
+# variables to be kept up-to-date by the time conversion functions.  Neither
+# "timezone" nor "daylight" is described in X3J11's work.
+#
+# If your system has a "GMT offset" field in its "struct tm"s
+# (or if you decide to add such a field in your system's "time.h" file),
+# add the name to a define such as
+#      -DTM_GMTOFF=tm_gmtoff
+# or
+#      -DTM_GMTOFF=_tm_gmtoff
+# to the end of the "CFLAGS=" line.
+# Neither tm_gmtoff nor _tm_gmtoff is described in X3J11's work;
+# in its work, use of "tm_gmtoff" is described as non-conforming.
+# Both Linux and BSD have done the equivalent of defining TM_GMTOFF in
+# their recent releases.
+#
+# If your system has a "zone abbreviation" field in its "struct tm"s
+# (or if you decide to add such a field in your system's "time.h" file),
+# add the name to a define such as
+#      -DTM_ZONE=tm_zone
+# or
+#      -DTM_ZONE=_tm_zone
+# to the end of the "CFLAGS=" line.
+# Neither tm_zone nor _tm_zone is described in X3J11's work;
+# in its work, use of "tm_zone" is described as non-conforming.
+# Both UCB and Sun have done the equivalent of defining TM_ZONE in
+# their recent releases.
+#
+# If you want functions that were inspired by early versions of X3J11's work,
+# add
+#      -DSTD_INSPIRED
+# to the end of the "CFLAGS=" line.  This arranges for the functions
+# "tzsetwall", "offtime", "timelocal", "timegm", "timeoff",
+# "posix2time", and "time2posix" to be added to the time conversion library.
+# "tzsetwall" is like "tzset" except that it arranges for local wall clock
+# time (rather than the time specified in the TZ environment variable)
+# to be used.
+# "offtime" is like "gmtime" except that it accepts a second (long) argument
+# that gives an offset to add to the time_t when converting it.
+# "timelocal" is equivalent to "mktime".
+# "timegm" is like "timelocal" except that it turns a struct tm into
+# a time_t using UTC (rather than local time as "timelocal" does).
+# "timeoff" is like "timegm" except that it accepts a second (long) argument
+# that gives an offset to use when converting to a time_t.
+# "posix2time" and "time2posix" are described in an included manual page.
+# X3J11's work does not describe any of these functions.
+# Sun has provided "tzsetwall", "timelocal", and "timegm" in SunOS 4.0.
+# These functions may well disappear in future releases of the time
+# conversion package.
+#
+# If you want Source Code Control System ID's left out of object modules, add
+#      -DNOID
+# to the end of the "CFLAGS=" line.
+#
+# If you'll never want to handle solar-time-based time zones, add
+#      -DNOSOLAR
+# to the end of the "CFLAGS=" line
+# (and comment out the "SDATA=" line below).
+# This reduces (slightly) the run-time data-space requirements of
+# the time conversion functions; it may reduce the acceptability of your system
+# to folks in oil- and cash-rich places.
+#
+# If you want to allocate state structures in localtime, add
+#      -DALL_STATE
+# to the end of the "CFLAGS=" line.  Storage is obtained by calling malloc.
+#
+# If you want an "altzone" variable (a la System V Release 3.1), add
+#      -DALTZONE
+# to the end of the "CFLAGS=" line.
+# This variable is not described in X3J11's work.
+#
+# If you want a "gtime" function (a la MACH), add
+#      -DCMUCS
+# to the end of the "CFLAGS=" line
+# This function is not described in X3J11's work.
+#
+# NIST-PCTS:151-2, Version 1.4, (1993-12-03) is a test suite put
+# out by the National Institute of Standards and Technology
+# which claims to test C and Posix conformance.  If you want to pass PCTS, add
+#      -DPCTS
+# to the end of the "CFLAGS=" line.
+#
+# If you want strict compliance with XPG4 as of 1994-04-09, add
+#      -DXPG4_1994_04_09
+# to the end of the "CFLAGS=" line.  This causes "strftime" to always return
+# 53 as a week number (rather than 52 or 53) for those days in January that
+# before the first Monday in January when a "%V" format is used and January 1
+# falls on a Friday, Saturday, or Sunday.
+
+CFLAGS=
+
+# If you want zic's -s option used when installing, uncomment the next line
+# ZFLAGS=      -s
+
+zic=           ./zic
+ZIC=           $(zic) $(ZFLAGS)
+
+# The name of a Posix-compliant `awk' on your system.
+AWK=           nawk
+
+# The path where SGML DTDs are kept.
+SGML_SEARCH_PATH= $(TOPDIR)/share/doc/sgml-lib/REC-html401-19991224/
+
+# The catalog file(s) to use when validating.
+SGML_CATALOG_FILES= HTML4.cat
+
+# The name, arguments and environment of a program to validate your web pages.
+# See <http://www.jclark.com/sp/> for a validator, and
+# <http://validator.w3.org/source/> for a validation library.
+VALIDATE = nsgmls
+VALIDATE_FLAGS = -s -B -wall -wno-unused-param
+VALIDATE_ENV = \
+  SGML_CATALOG_FILES=$(SGML_CATALOG_FILES) \
+  SGML_SEARCH_PATH=$(SGML_SEARCH_PATH) \
+  SP_CHARSET_FIXED=YES \
+  SP_ENCODING=UTF-8
+
+###############################################################################
+
+cc=            cc
+CC=            $(cc) -DTZDIR=\"$(TZDIR)\"
+
+TZCSRCS=       zic.c localtime.c asctime.c scheck.c ialloc.c
+TZCOBJS=       zic.o localtime.o asctime.o scheck.o ialloc.o
+TZDSRCS=       zdump.c localtime.c ialloc.c
+TZDOBJS=       zdump.o localtime.o ialloc.o
+DATESRCS=      date.c localtime.c strftime.c asctime.c
+DATEOBJS=      date.o localtime.o strftime.o asctime.o
+LIBSRCS=       localtime.c asctime.c difftime.c
+LIBOBJS=       localtime.o asctime.o difftime.o
+HEADERS=       tzfile.h private.h
+NONLIBSRCS=    zic.c zdump.c scheck.c ialloc.c
+NEWUCBSRCS=    date.c strftime.c
+SOURCES=       $(HEADERS) $(LIBSRCS) $(NONLIBSRCS) $(NEWUCBSRCS) tzselect.ksh
+MANS=          newctime.3 newstrftime.3 newtzset.3 time2posix.3 \
+                       tzfile.5 tzselect.8 zic.8 zdump.8
+DOCS=          README Theory $(MANS) date.1 Makefile
+PRIMARY_YDATA= africa antarctica asia australasia \
+               europe northamerica southamerica
+YDATA=         $(PRIMARY_YDATA) pacificnew etcetera factory backward
+NDATA=         systemv
+SDATA=         solar87 solar88 solar89
+TDATA=         $(YDATA) $(NDATA) $(SDATA)
+TABDATA=       iso3166.tab zone.tab
+DATA=          $(YDATA) $(NDATA) $(SDATA) $(TABDATA) leapseconds yearistype.sh
+WEB_PAGES=     tz-art.htm tz-link.htm
+MISC=          usno1988 usno1989 usno1989a usno1995 usno1997 usno1998 \
+                       itca.jpg $(WEB_PAGES) checktab.awk workman.sh \
+                       zoneinfo2tdf.pl
+ENCHILADA=     $(DOCS) $(SOURCES) $(DATA) $(MISC)
+
+# And for the benefit of csh users on systems that assume the user
+# shell should be used to handle commands in Makefiles. . .
+
+SHELL=         /bin/sh
+
+all:           tzselect zic zdump $(LIBOBJS)
+
+ALL:           all date
+
+install:       all $(DATA) $(REDO) $(TZLIB) $(MANS) $(TABDATA)
+               $(ZIC) -y $(YEARISTYPE) \
+                       -d $(TZDIR) -l $(LOCALTIME) -p $(POSIXRULES)
+               -rm -f $(TZDIR)/iso3166.tab $(TZDIR)/zone.tab
+               cp iso3166.tab zone.tab $(TZDIR)/.
+               -mkdir $(TOPDIR) $(ETCDIR)
+               cp tzselect zic zdump $(ETCDIR)/.
+               -mkdir $(TOPDIR) $(MANDIR) \
+                       $(MANDIR)/man3 $(MANDIR)/man5 $(MANDIR)/man8
+               -rm -f $(MANDIR)/man3/newctime.3 \
+                       $(MANDIR)/man3/newtzset.3 \
+                       $(MANDIR)/man5/tzfile.5 \
+                       $(MANDIR)/man8/tzselect.8 \
+                       $(MANDIR)/man8/zdump.8 \
+                       $(MANDIR)/man8/zic.8
+               cp newctime.3 newtzset.3 $(MANDIR)/man3/.
+               cp tzfile.5 $(MANDIR)/man5/.
+               cp tzselect.8 zdump.8 zic.8 $(MANDIR)/man8/.
+
+INSTALL:       ALL install date.1
+               -mkdir $(TOPDIR) $(BINDIR)
+               cp date $(BINDIR)/.
+               -mkdir $(TOPDIR) $(MANDIR) $(MANDIR)/man1
+               -rm -f $(MANDIR)/man1/date.1
+               cp date.1 $(MANDIR)/man1/.
+
+zdump:         $(TZDOBJS)
+               $(CC) $(CFLAGS) $(LFLAGS) $(TZDOBJS) $(LDLIBS) -o $@
+
+zic:           $(TZCOBJS) yearistype
+               $(CC) $(CFLAGS) $(LFLAGS) $(TZCOBJS) $(LDLIBS) -o $@
+
+yearistype:    yearistype.sh
+               cp yearistype.sh yearistype
+               chmod +x yearistype
+
+posix_only:    zic $(TDATA)
+               $(ZIC) -y $(YEARISTYPE) -d $(TZDIR) -L /dev/null $(TDATA)
+
+right_only:    zic leapseconds $(TDATA)
+               $(ZIC) -y $(YEARISTYPE) -d $(TZDIR) -L leapseconds $(TDATA)
+
+# In earlier versions of this makefile, the other two directories were
+# subdirectories of $(TZDIR).  However, this led to configuration errors.
+# For example, with posix_right under the earlier scheme,
+# TZ='right/Australia/Adelaide' got you localtime with leap seconds,
+# but gmtime without leap seconds, which led to problems with applications
+# like sendmail that subtract gmtime from localtime.
+# Therefore, the other two directories are now siblings of $(TZDIR).
+# You must replace all of $(TZDIR) to switch from not using leap seconds
+# to using them, or vice versa.
+other_two:     zic leapseconds $(TDATA)
+               $(ZIC) -y $(YEARISTYPE) -d $(TZDIR)-posix -L /dev/null $(TDATA)
+               $(ZIC) -y $(YEARISTYPE) \
+                       -d $(TZDIR)-leaps -L leapseconds $(TDATA)
+
+posix_right:   posix_only other_two
+
+right_posix:   right_only other_two
+
+zones:         $(REDO)
+
+$(TZLIB):      $(LIBOBJS)
+               -mkdir $(TOPDIR) $(LIBDIR)
+               ar ru $@ $(LIBOBJS)
+               if [ -x /usr/ucb/ranlib -o -x /usr/bin/ranlib ] ; \
+                       then ranlib $@ ; fi
+
+date:          $(DATEOBJS)
+               $(CC) $(CFLAGS) date.o localtime.o asctime.o strftime.o \
+                       $(LDLIBS) -lc -o $@
+
+tzselect:      tzselect.ksh
+               sed \
+                       -e 's|AWK=[^}]*|AWK=$(AWK)|g' \
+                       -e 's|TZDIR=[^}]*|TZDIR=$(TZDIR)|' \
+                       <$? >$@
+               chmod +x $@
+
+check:         check_tables check_web
+
+check_tables:  checktab.awk $(PRIMARY_YDATA)
+               $(AWK) -f checktab.awk $(PRIMARY_YDATA)
+
+check_web:     $(WEB_PAGES)
+               $(VALIDATE_ENV) $(VALIDATE) $(VALIDATE_FLAGS) $(WEB_PAGES)
+
+clean:
+               rm -f core *.o *.out tzselect zdump zic yearistype date
+
+maintainer-clean: clean
+               @echo 'This command is intended for maintainers to use; it'
+               @echo 'deletes files that may need special tools to rebuild.'
+               rm -f *.[1-8].txt tzcode.tar.gz tzdata.tar.gz
+
+names:
+               @echo $(ENCHILADA)
+
+# The zics below ensure that each data file can stand on its own.
+# We also do an all-files run to catch links to links.
+
+public:                $(ENCHILADA)
+               make maintainer-clean
+               make "CFLAGS=$(GCC_DEBUG_FLAGS)"
+               -mkdir /tmp/,tzpublic
+               -for i in $(TDATA) ; do zic -v -d /tmp/,tzpublic $$i 2>&1 | grep -v "starting year" ; done
+               for i in $(TDATA) ; do zic -d /tmp/,tzpublic $$i || exit; done
+               zic -v -d /tmp/,tzpublic $(TDATA) || exit
+               rm -f -r /tmp/,tzpublic
+               for i in *.[1-8] ; do sh workman.sh $$i > $$i.txt || exit; done
+               $(AWK) -f checktab.awk $(PRIMARY_YDATA)
+               tar cf - $(DOCS) $(SOURCES) $(MISC) *.[1-8].txt | gzip -9 > tzcode.tar.gz
+               tar cf - $(DATA) | gzip -9 > tzdata.tar.gz
+
+typecheck:
+               make clean
+               for i in "long long" unsigned double; \
+               do \
+                       make CFLAGS="-DTYPECHECK -D_TIME_T \"-Dtime_t=$$i\"" ; \
+                       ./zdump -v Europe/Rome ; \
+                       make clean ; \
+               done
+
+zonenames:     $(TDATA)
+               @$(AWK) '/^Zone/ { print $$2 } /^Link/ { print $$3 }' $(TDATA)
+
+asctime.o:     private.h tzfile.h
+date.o:                private.h
+difftime.o:    private.h
+ialloc.o:      private.h
+localtime.o:   private.h tzfile.h
+scheck.o:      private.h
+strftime.o:    tzfile.h
+zic.o:         private.h tzfile.h
+
+.KEEP_STATE:
diff --git a/lib/nbsd_libc/time/Makefile.inc b/lib/nbsd_libc/time/Makefile.inc
new file mode 100644 (file)
index 0000000..31899a9
--- /dev/null
@@ -0,0 +1,36 @@
+#      $NetBSD: Makefile.inc,v 1.16 2010/12/16 22:18:37 christos Exp $
+
+.PATH: ${.CURDIR}/time
+
+SRCS+= _daylight.c                                                     \
+       asctime.c difftime.c localtime.c getdate.c strftime.c strptime.c
+MAN+=  ctime.3 getdate.3 offtime.3 strftime.3 strptime.3               \
+       time2posix.3 tzfile.5 tzset.3
+CPPFLAGS+=-DALL_STATE -DUSG_COMPAT
+
+MLINKS+=ctime.3 ctime_r.3      \
+       ctime.3 ctime_rz.3      \
+       ctime.3 asctime.3       \
+       ctime.3 asctime_r.3     \
+       ctime.3 difftime.3      \
+       ctime.3 gmtime.3        \
+       ctime.3 gmtime_r.3      \
+       ctime.3 localtime.3     \
+       ctime.3 localtime_r.3   \
+       ctime.3 localtime_rz.3  \
+       ctime.3 mktime.3        \
+       ctime.3 mktime_z.3      \
+       ctime.3 tzalloc.3       \
+       ctime.3 tzfree.3        \
+       ctime.3 tzgetname.3     \
+       getdate.3 getdate_err.3 \
+       offtime.3 offtime_r.3   \
+       offtime.3 timeoff.3     \
+       offtime.3 timegm.3      \
+       offtime.3 timelocal.3   \
+       time2posix.3 posix2time.3 \
+       time2posix.3 posix2time_z.3 \
+       time2posix.3 time2posix_z.3 \
+       tzset.3 daylight.3      \
+       tzset.3 tzsetwall.3     \
+       strftime.3 strftime_z.3
diff --git a/lib/nbsd_libc/time/README b/lib/nbsd_libc/time/README
new file mode 100644 (file)
index 0000000..427b6a0
--- /dev/null
@@ -0,0 +1,86 @@
+@(#)README     8.3
+This file is in the public domain, so clarified as of
+2009-05-17 by Arthur David Olson.
+
+"What time is it?" -- Richard Deacon as The King
+"Any time you want it to be." -- Frank Baxter as The Scientist
+                                       (from the Bell System film "About Time")
+
+The 1989 update of the time zone package featured
+
+*      POSIXization (including interpretation of POSIX-style TZ environment
+       variables, provided by Guy Harris),
+*      ANSIfication (including versions of "mktime" and "difftime"),
+*      SVIDulation (an "altzone" variable)
+*      MACHination (the "gtime" function)
+*      corrections to some time zone data (including corrections to the rules
+       for Great Britain and New Zealand)
+*      reference data from the United States Naval Observatory for folks who
+       want to do additional time zones
+*      and the 1989 data for Saudi Arabia.
+
+(Since this code will be treated as "part of the implementation" in some places
+and as "part of the application" in others, there's no good way to name
+functions, such as timegm, that are not part of the proposed ANSI C standard;
+such functions have kept their old, underscore-free names in this update.)
+
+And the "dysize" function has disappeared; it was present to allow compilation
+of the "date" command on old BSD systems, and a version of "date" is now
+provided in the package.  The "date" command is not created when you "make all"
+since it may lack options provided by the version distributed with your
+operating system, or may not interact with the system in the same way the
+native version does.
+
+Since POSIX frowns on correct leap second handling, the default behavior of
+the "zic" command (in the absence of a "-L" option) has been changed to omit
+leap second information from its output files.
+
+Here is a recipe for acquiring, building, installing, and testing the
+tz distribution on a GNU/Linux or similar host.
+
+       mkdir tz
+       cd tz
+       wget 'ftp://elsie.nci.nih.gov/pub/tz*.tar.gz'
+       gzip -dc tzcode*.tar.gz | tar -xf -
+       gzip -dc tzdata*.tar.gz | tar -xf -
+
+Be sure to read the comments in "Makefile" and make any changes needed
+to make things right for your system, especially if you are using some
+platform other than GNU/Linux.  Then run the following commands,
+substituting your desired installation directory for "$HOME/tzdir":
+
+       make TOPDIR=$HOME/tzdir install
+       $HOME/tzdir/etc/zdump -v America/Los_Angeles
+
+To use the new functions, use a "-ltz" option when compiling or linking.
+
+Historical local time information has been included here to:
+
+*      provide a compendium of data about the history of civil time
+       that is useful even if the data are not 100% accurate;
+
+*      give an idea of the variety of local time rules that have
+       existed in the past and thus an idea of the variety that may be
+       expected in the future;
+
+*      provide a test of the generality of the local time rule description
+       system.
+
+The information in the time zone data files is by no means authoritative;
+the files currently do not even attempt to cover all time stamps before
+1970, and there are undoubtedly errors even for time stamps since 1970.
+If you know that the rules are different from those in a file, by all means
+feel free to change file (and please send the changed version to
+tz@elsie.nci.nih.gov for use in the future).  Europeans take note!
+
+Thanks to these Timezone Caballeros who've made major contributions to the
+time conversion package:  Keith Bostic; Bob Devine; Paul Eggert; Robert Elz;
+Guy Harris; Mark Horton; John Mackin; and Bradley White.  Thanks also to
+Michael Bloom, Art Neilson, Stephen Prince, John Sovereign, and Frank Wales
+for testing work, and to Gwillim Law for checking local mean time data.
+None of them are responsible for remaining errors.
+
+Look in the ~ftp/pub directory of elsie.nci.nih.gov
+for updated versions of these files.
+
+Please send comments or information to tz@elsie.nci.nih.gov.
diff --git a/lib/nbsd_libc/time/Theory b/lib/nbsd_libc/time/Theory
new file mode 100644 (file)
index 0000000..605a62a
--- /dev/null
@@ -0,0 +1,570 @@
+#      $NetBSD: Theory,v 1.9 2009/12/31 22:49:15 mlelstv Exp $
+@(#)Theory     8.3
+This file is in the public domain, so clarified as of
+2009-05-17 by Arthur David Olson.
+
+----- Outline -----
+
+       Time and date functions
+       Names of time zone regions
+       Time zone abbreviations
+       Calendrical issues
+       Time and time zones on Mars
+
+----- Time and date functions -----
+
+These time and date functions are upwards compatible with POSIX,
+an international standard for UNIX-like systems.
+As of this writing, the current edition of POSIX is:
+
+  Standard for Information technology
+  -- Portable Operating System Interface (POSIX (R))
+  -- System Interfaces
+  IEEE Std 1003.1, 2004 Edition
+  <http://www.opengroup.org/online-pubs?DOC=7999959899>
+  <http://www.opengroup.org/pubs/catalog/t041.htm>
+
+POSIX has the following properties and limitations.
+
+*      In POSIX, time display in a process is controlled by the
+       environment variable TZ.  Unfortunately, the POSIX TZ string takes
+       a form that is hard to describe and is error-prone in practice.
+       Also, POSIX TZ strings can't deal with other (for example, Israeli)
+       daylight saving time rules, or situations where more than two
+       time zone abbreviations are used in an area.
+
+       The POSIX TZ string takes the following form:
+
+               stdoffset[dst[offset],date[/time],date[/time]]
+
+       where:
+
+       std and dst
+               are 3 or more characters specifying the standard
+               and daylight saving time (DST) zone names.
+               Starting with POSIX.1-2001, std and dst may also be
+               in a quoted form like "<UTC+10>"; this allows
+               "+" and "-" in the names.
+       offset
+               is of the form `[-]hh:[mm[:ss]]' and specifies the
+               offset west of UTC.  The default DST offset is one hour
+               ahead of standard time.
+       date[/time],date[/time]
+               specifies the beginning and end of DST.  If this is absent,
+               the system supplies its own rules for DST, and these can
+               differ from year to year; typically US DST rules are used.
+       time
+               takes the form `hh:[mm[:ss]]' and defaults to 02:00.
+       date
+               takes one of the following forms:
+               Jn (1<=n<=365)
+                       origin-1 day number not counting February 29
+               n (0<=n<=365)
+                       origin-0 day number counting February 29 if present
+               Mm.n.d (0[Sunday]<=d<=6[Saturday], 1<=n<=5, 1<=m<=12)
+                       for the dth day of week n of month m of the year,
+                       where week 1 is the first week in which day d appears,
+                       and `5' stands for the last week in which day d appears
+                       (which may be either the 4th or 5th week).
+
+       Here is an example POSIX TZ string, for US Pacific time using rules
+       appropriate from 1987 through 2006:
+
+               TZ='PST8PDT,M4.1.0/02:00,M10.5.0/02:00'
+
+       This POSIX TZ string is hard to remember, and mishandles time stamps
+       before 1987 and after 2006.  With this package you can use this
+       instead:
+
+               TZ='America/Los_Angeles'
+
+*      POSIX does not define the exact meaning of TZ values like "EST5EDT".
+       Typically the current US DST rules are used to interpret such values,
+       but this means that the US DST rules are compiled into each program
+       that does time conversion.  This means that when US time conversion
+       rules change (as in the United States in 1987), all programs that
+       do time conversion must be recompiled to ensure proper results.
+
+*      In POSIX, there's no tamper-proof way for a process to learn the
+       system's best idea of local wall clock.  (This is important for
+       applications that an administrator wants used only at certain times--
+       without regard to whether the user has fiddled the "TZ" environment
+       variable.  While an administrator can "do everything in UTC" to get
+       around the problem, doing so is inconvenient and precludes handling
+       daylight saving time shifts--as might be required to limit phone
+       calls to off-peak hours.)
+
+*      POSIX requires that systems ignore leap seconds.
+
+These are the extensions that have been made to the POSIX functions:
+
+*      The "TZ" environment variable is used in generating the name of a file
+       from which time zone information is read (or is interpreted a la
+       POSIX); "TZ" is no longer constrained to be a three-letter time zone
+       name followed by a number of hours and an optional three-letter
+       daylight time zone name.  The daylight saving time rules to be used
+       for a particular time zone are encoded in the time zone file;
+       the format of the file allows U.S., Australian, and other rules to be
+       encoded, and allows for situations where more than two time zone
+       abbreviations are used.
+
+       It was recognized that allowing the "TZ" environment variable to
+       take on values such as "America/New_York" might cause "old" programs
+       (that expect "TZ" to have a certain form) to operate incorrectly;
+       consideration was given to using some other environment variable
+       (for example, "TIMEZONE") to hold the string used to generate the
+       time zone information file name.  In the end, however, it was decided
+       to continue using "TZ":  it is widely used for time zone purposes;
+       separately maintaining both "TZ" and "TIMEZONE" seemed a nuisance;
+       and systems where "new" forms of "TZ" might cause problems can simply
+       use TZ values such as "EST5EDT" which can be used both by
+       "new" programs (a la POSIX) and "old" programs (as zone names and
+       offsets).
+
+*      To handle places where more than two time zone abbreviations are used,
+       the functions "localtime" and "gmtime" set tzname[tmp->tm_isdst]
+       (where "tmp" is the value the function returns) to the time zone
+       abbreviation to be used.  This differs from POSIX, where the elements
+       of tzname are only changed as a result of calls to tzset.
+
+*      Since the "TZ" environment variable can now be used to control time
+       conversion, the "daylight" and "timezone" variables are no longer
+       needed.  (These variables are defined and set by "tzset"; however, their
+       values will not be used by "localtime.")
+
+*      The "localtime" function has been set up to deliver correct results
+       for near-minimum or near-maximum time_t values.  (A comment in the
+       source code tells how to get compatibly wrong results).
+
+*      A function "tzsetwall" has been added to arrange for the system's
+       best approximation to local wall clock time to be delivered by
+       subsequent calls to "localtime."  Source code for portable
+       applications that "must" run on local wall clock time should call
+       "tzsetwall();" if such code is moved to "old" systems that don't
+       provide tzsetwall, you won't be able to generate an executable program.
+       (These time zone functions also arrange for local wall clock time to be
+       used if tzset is called--directly or indirectly--and there's no "TZ"
+       environment variable; portable applications should not, however, rely
+       on this behavior since it's not the way SVR2 systems behave.)
+
+*      These functions can account for leap seconds, thanks to Bradley White.
+
+Points of interest to folks with other systems:
+
+*      This package is already part of many POSIX-compliant hosts,
+       including BSD, HP, Linux, Network Appliance, SCO, SGI, and Sun.
+       On such hosts, the primary use of this package
+       is to update obsolete time zone rule tables.
+       To do this, you may need to compile the time zone compiler
+       `zic' supplied with this package instead of using the system `zic',
+       since the format of zic's input changed slightly in late 1994,
+       and many vendors still do not support the new input format.
+
+*      The UNIX Version 7 "timezone" function is not present in this package;
+       it's impossible to reliably map timezone's arguments (a "minutes west
+       of GMT" value and a "daylight saving time in effect" flag) to a
+       time zone abbreviation, and we refuse to guess.
+       Programs that in the past used the timezone function may now examine
+       tzname[localtime(&clock)->tm_isdst] to learn the correct time
+       zone abbreviation to use.  Alternatively, use
+       localtime(&clock)->tm_zone if this has been enabled.
+
+*      The 4.2BSD gettimeofday function is not used in this package.
+       This formerly let users obtain the current UTC offset and DST flag,
+       but this functionality was removed in later versions of BSD.
+
+*      In SVR2, time conversion fails for near-minimum or near-maximum
+       time_t values when doing conversions for places that don't use UTC.
+       This package takes care to do these conversions correctly.
+
+The functions that are conditionally compiled if STD_INSPIRED is defined
+should, at this point, be looked on primarily as food for thought.  They are
+not in any sense "standard compatible"--some are not, in fact, specified in
+*any* standard.  They do, however, represent responses of various authors to
+standardization proposals.
+
+Other time conversion proposals, in particular the one developed by folks at
+Hewlett Packard, offer a wider selection of functions that provide capabilities
+beyond those provided here.  The absence of such functions from this package
+is not meant to discourage the development, standardization, or use of such
+functions.  Rather, their absence reflects the decision to make this package
+contain valid extensions to POSIX, to ensure its broad acceptability.  If
+more powerful time conversion functions can be standardized, so much the
+better.
+
+
+----- Names of time zone rule files -----
+
+The time zone rule file naming conventions attempt to strike a balance
+among the following goals:
+
+ * Uniquely identify every national region where clocks have all
+   agreed since 1970.  This is essential for the intended use: static
+   clocks keeping local civil time.
+
+ * Indicate to humans as to where that region is.  This simplifes use.
+
+ * Be robust in the presence of political changes.  This reduces the
+   number of updates and backward-compatibility hacks.  For example,
+   names of countries are ordinarily not used, to avoid
+   incompatibilities when countries change their name
+   (e.g. Zaire->Congo) or when locations change countries
+   (e.g. Hong Kong from UK colony to China).
+
+ * Be portable to a wide variety of implementations.
+   This promotes use of the technology.
+
+ * Use a consistent naming convention over the entire world.
+   This simplifies both use and maintenance.
+
+This naming convention is not intended for use by inexperienced users
+to select TZ values by themselves (though they can of course examine
+and reuse existing settings).  Distributors should provide
+documentation and/or a simple selection interface that explains the
+names; see the 'tzselect' program supplied with this distribution for
+one example.
+
+Names normally have the form AREA/LOCATION, where AREA is the name
+of a continent or ocean, and LOCATION is the name of a specific
+location within that region.  North and South America share the same
+area, `America'.  Typical names are `Africa/Cairo', `America/New_York',
+and `Pacific/Honolulu'.
+
+Here are the general rules used for choosing location names,
+in decreasing order of importance:
+
+       Use only valid POSIX file name components (i.e., the parts of
+               names other than `/').  Within a file name component,
+               use only ASCII letters, `.', `-' and `_'.  Do not use
+               digits, as that might create an ambiguity with POSIX
+               TZ strings.  A file name component must not exceed 14
+               characters or start with `-'.  E.g., prefer `Brunei'
+               to `Bandar_Seri_Begawan'.
+       Include at least one location per time zone rule set per country.
+               One such location is enough.  Use ISO 3166 (see the file
+               iso3166.tab) to help decide whether something is a country.
+               However, uninhabited ISO 3166 regions like Bouvet Island
+               do not need locations, since local time is not defined there.
+       If all the clocks in a country's region have agreed since 1970,
+               don't bother to include more than one location
+               even if subregions' clocks disagreed before 1970.
+               Otherwise these tables would become annoyingly large.
+       If a name is ambiguous, use a less ambiguous alternative;
+               e.g. many cities are named San Jose and Georgetown, so
+               prefer `Costa_Rica' to `San_Jose' and `Guyana' to `Georgetown'.
+       Keep locations compact.  Use cities or small islands, not countries
+               or regions, so that any future time zone changes do not split
+               locations into different time zones.  E.g. prefer `Paris'
+               to `France', since France has had multiple time zones.
+       Use mainstream English spelling, e.g. prefer `Rome' to `Roma', and
+               prefer `Athens' to the true name (which uses Greek letters).
+               The POSIX file name restrictions encourage this rule.
+       Use the most populous among locations in a country's time zone,
+               e.g. prefer `Shanghai' to `Beijing'.  Among locations with
+               similar populations, pick the best-known location,
+               e.g. prefer `Rome' to `Milan'.
+       Use the singular form, e.g. prefer `Canary' to `Canaries'.
+       Omit common suffixes like `_Islands' and `_City', unless that
+               would lead to ambiguity.  E.g. prefer `Cayman' to
+               `Cayman_Islands' and `Guatemala' to `Guatemala_City',
+               but prefer `Mexico_City' to `Mexico' because the country
+               of Mexico has several time zones.
+       Use `_' to represent a space.
+       Omit `.' from abbreviations in names, e.g. prefer `St_Helena'
+               to `St._Helena'.
+       Do not change established names if they only marginally
+               violate the above rules.  For example, don't change
+               the existing name `Rome' to `Milan' merely because
+               Milan's population has grown to be somewhat greater
+               than Rome's.
+       If a name is changed, put its old spelling in the `backward' file.
+
+The file `zone.tab' lists the geographical locations used to name
+time zone rule files.  It is intended to be an exhaustive list
+of canonical names for geographic regions.
+
+Older versions of this package used a different naming scheme,
+and these older names are still supported.
+See the file `backward' for most of these older names
+(e.g. `US/Eastern' instead of `America/New_York').
+The other old-fashioned names still supported are
+`WET', `CET', `MET', `EET' (see the file `europe'),
+and `Factory' (see the file `factory').
+
+
+----- Time zone abbreviations -----
+
+When this package is installed, it generates time zone abbreviations
+like `EST' to be compatible with human tradition and POSIX.
+Here are the general rules used for choosing time zone abbreviations,
+in decreasing order of importance:
+
+       Use abbreviations that consist of three or more ASCII letters.
+               Previous editions of this database also used characters like
+               ' ' and '?', but these characters have a special meaning to
+               the shell and cause commands like
+                       set `date`
+               to have unexpected effects.
+               Previous editions of this rule required upper-case letters,
+               but the Congressman who introduced Chamorro Standard Time
+               preferred "ChST", so the rule has been relaxed.
+
+               This rule guarantees that all abbreviations could have
+               been specified by a POSIX TZ string.  POSIX
+               requires at least three characters for an
+               abbreviation.  POSIX through 2000 says that an abbreviation
+               cannot start with ':', and cannot contain ',', '-',
+               '+', NUL, or a digit.  POSIX from 2001 on changes this
+               rule to say that an abbreviation can contain only '-', '+',
+               and alphanumeric characters from the portable character set
+               in the current locale.  To be portable to both sets of
+               rules, an abbreviation must therefore use only ASCII
+               letters.
+
+       Use abbreviations that are in common use among English-speakers,
+               e.g. `EST' for Eastern Standard Time in North America.
+               We assume that applications translate them to other languages
+               as part of the normal localization process; for example,
+               a French application might translate `EST' to `HNE'.
+
+       For zones whose times are taken from a city's longitude, use the
+               traditional xMT notation, e.g. `PMT' for Paris Mean Time.
+               The only name like this in current use is `GMT'.
+
+       If there is no common English abbreviation, abbreviate the English
+               translation of the usual phrase used by native speakers.
+               If this is not available or is a phrase mentioning the country
+               (e.g. ``Cape Verde Time''), then:
+
+               When a country has a single or principal time zone region,
+                       append `T' to the country's ISO code, e.g. `CVT' for
+                       Cape Verde Time.  For summer time append `ST';
+                       for double summer time append `DST'; etc.
+               When a country has multiple time zones, take the first three
+                       letters of an English place name identifying each zone
+                       and then append `T', `ST', etc. as before;
+                       e.g. `VLAST' for VLAdivostok Summer Time.
+
+       Use UTC (with time zone abbreviation "zzz") for locations while
+               uninhabited.  The "zzz" mnemonic is that these locations are,
+               in some sense, asleep.
+
+Application writers should note that these abbreviations are ambiguous
+in practice: e.g. `EST' has a different meaning in Australia than
+it does in the United States.  In new applications, it's often better
+to use numeric UTC offsets like `-0500' instead of time zone
+abbreviations like `EST'; this avoids the ambiguity.
+
+
+----- Calendrical issues -----
+
+Calendrical issues are a bit out of scope for a time zone database,
+but they indicate the sort of problems that we would run into if we
+extended the time zone database further into the past.  An excellent
+resource in this area is Edward M. Reingold and Nachum Dershowitz,
+<a href="http://emr.cs.uiuc.edu/home/reingold/calendar-book/second-edition/">
+Calendrical Calculations: The Millennium Edition
+</a>, Cambridge University Press (2001).  Other information and
+sources are given below.  They sometimes disagree.
+
+
+France
+
+Gregorian calendar adopted 1582-12-20.
+French Revolutionary calendar used 1793-11-24 through 1805-12-31,
+and (in Paris only) 1871-05-06 through 1871-05-23.
+
+
+Russia
+
+From Chris Carrier (1996-12-02):
+On 1929-10-01 the Soviet Union instituted an ``Eternal Calendar''
+with 30-day months plus 5 holidays, with a 5-day week.
+On 1931-12-01 it changed to a 6-day week; in 1934 it reverted to the
+Gregorian calendar while retaining the 6-day week; on 1940-06-27 it
+reverted to the 7-day week.  With the 6-day week the usual days
+off were the 6th, 12th, 18th, 24th and 30th of the month.
+(Source: Evitiar Zerubavel, _The Seven Day Circle_)
+
+
+Mark Brader reported a similar story in "The Book of Calendars", edited
+by Frank Parise (1982, Facts on File, ISBN 0-8719-6467-8), page 377.  But:
+
+From: Petteri Sulonen (via Usenet)
+Date: 14 Jan 1999 00:00:00 GMT
+...
+
+If your source is correct, how come documents between 1929 -- 1940 were
+still dated using the conventional, Gregorian calendar?
+
+I can post a scan of a document dated December 1, 1934, signed by
+Yenukidze, the secretary, on behalf of Kalinin, the President of the
+Executive Committee of the Supreme Soviet, if you like.
+
+
+
+Sweden (and Finland)
+
+From: Mark Brader
+<a href="news:1996Jul6.012937.29190@sq.com">
+Subject: Re: Gregorian reform -- a part of locale?
+</a>
+Date: 1996-07-06
+
+In 1700, Denmark made the transition from Julian to Gregorian.  Sweden
+decided to *start* a transition in 1700 as well, but rather than have one of
+those unsightly calendar gaps :-), they simply decreed that the next leap
+year after 1696 would be in 1744 -- putting the whole country on a calendar
+different from both Julian and Gregorian for a period of 40 years.
+
+However, in 1704 something went wrong and the plan was not carried through;
+they did, after all, have a leap year that year.  And one in 1708.  In 1712
+they gave it up and went back to Julian, putting 30 days in February that
+year!...
+
+Then in 1753, Sweden made the transition to Gregorian in the usual manner,
+getting there only 13 years behind the original schedule.
+
+(A previous posting of this story was challenged, and Swedish readers
+produced the following references to support it: "Tiderakning och historia"
+by Natanael Beckman (1924) and "Tid, en bok om tiderakning och
+kalendervasen" by Lars-Olof Lode'n (no date was given).)
+
+
+Grotefend's data
+
+From: "Michael Palmer" [with one obvious typo fixed]
+Subject: Re: Gregorian Calendar (was Re: Another FHC related question
+Newsgroups: soc.genealogy.german
+Date: Tue, 9 Feb 1999 02:32:48 -800
+...
+
+The following is a(n incomplete) listing, arranged chronologically, of
+European states, with the date they converted from the Julian to the
+Gregorian calendar:
+
+04/15 Oct 1582 - Italy (with exceptions), Spain, Portugal, Poland (Roman
+                 Catholics and Danzig only)
+09/20 Dec 1582 - France, Lorraine
+
+21 Dec 1582/
+   01 Jan 1583 - Holland, Brabant, Flanders, Hennegau
+10/21 Feb 1583 - bishopric of Liege (L"uttich)
+13/24 Feb 1583 - bishopric of Augsburg
+04/15 Oct 1583 - electorate of Trier
+05/16 Oct 1583 - Bavaria, bishoprics of Freising, Eichstedt, Regensburg,
+                 Salzburg, Brixen
+13/24 Oct 1583 - Austrian Oberelsass and Breisgau
+20/31 Oct 1583 - bishopric of Basel
+02/13 Nov 1583 - duchy of J"ulich-Berg
+02/13 Nov 1583 - electorate and city of K"oln
+04/15 Nov 1583 - bishopric of W"urzburg
+11/22 Nov 1583 - electorate of Mainz
+16/27 Nov 1583 - bishopric of Strassburg and the margraviate of Baden
+17/28 Nov 1583 - bishopric of M"unster and duchy of Cleve
+14/25 Dec 1583 - Steiermark
+
+06/17 Jan 1584 - Austria and Bohemia
+11/22 Jan 1584 - Luzern, Uri, Schwyz, Zug, Freiburg, Solothurn
+12/23 Jan 1584 - Silesia and the Lausitz
+22 Jan/
+   02 Feb 1584 - Hungary (legally on 21 Oct 1587)
+      Jun 1584 - Unterwalden
+01/12 Jul 1584 - duchy of Westfalen
+
+16/27 Jun 1585 - bishopric of Paderborn
+
+14/25 Dec 1590 - Transylvania
+
+22 Aug/
+   02 Sep 1612 - duchy of Prussia
+
+13/24 Dec 1614 - Pfalz-Neuburg
+
+          1617 - duchy of Kurland (reverted to the Julian calendar in
+                 1796)
+
+          1624 - bishopric of Osnabr"uck
+
+          1630 - bishopric of Minden
+
+15/26 Mar 1631 - bishopric of Hildesheim
+
+          1655 - Kanton Wallis
+
+05/16 Feb 1682 - city of Strassburg
+
+18 Feb/
+   01 Mar 1700 - Protestant Germany (including Swedish possessions in
+                 Germany), Denmark, Norway
+30 Jun/
+   12 Jul 1700 - Gelderland, Zutphen
+10 Nov/
+   12 Dec 1700 - Utrecht, Overijssel
+
+31 Dec 1700/
+   12 Jan 1701 - Friesland, Groningen, Z"urich, Bern, Basel, Geneva,
+                 Turgau, and Schaffhausen
+
+          1724 - Glarus, Appenzell, and the city of St. Gallen
+
+01 Jan 1750    - Pisa and Florence
+
+02/14 Sep 1752 - Great Britain
+
+17 Feb/
+   01 Mar 1753 - Sweden
+
+1760-1812      - Graub"unden
+
+The Russian empire (including Finland and the Baltic states) did not
+convert to the Gregorian calendar until the Soviet revolution of 1917.
+
+Source:  H. Grotefend, _Taschenbuch der Zeitrechnung des deutschen
+Mittelalters und der Neuzeit_, herausgegeben von Dr. O. Grotefend
+(Hannover:  Hahnsche Buchhandlung, 1941), pp. 26-28.
+
+
+----- Time and time zones on Mars -----
+
+Some people have adjusted their work schedules to fit Mars time.
+Dozens of special Mars watches were built for Jet Propulsion
+Laboratory workers who kept Mars time during the Mars Exploration
+Rovers mission (2004).  These timepieces look like normal Seikos and
+Citizens but use Mars seconds rather than terrestrial seconds.
+
+A Mars solar day is called a "sol" and has a mean period equal to
+about 24 hours 39 minutes 35.244 seconds in terrestrial time.  It is
+divided into a conventional 24-hour clock, so each Mars second equals
+about 1.02749125 terrestrial seconds.
+
+The prime meridian of Mars goes through the center of the crater
+Airy-0, named in honor of the British astronomer who built the
+Greenwich telescope that defines Earth's prime meridian.  Mean solar
+time on the Mars prime meridian is called Mars Coordinated Time (MTC).
+
+Each landed mission on Mars has adopted a different reference for
+solar time keeping, so there is no real standard for Mars time zones.
+For example, the Mars Exploration Rover project (2004) defined two
+time zones "Local Solar Time A" and "Local Solar Time B" for its two
+missions, each zone designed so that its time equals local true solar
+time at approximately the middle of the nominal mission.  Such a "time
+zone" is not particularly suited for any application other than the
+mission itself.
+
+Many calendars have been proposed for Mars, but none have achieved
+wide acceptance.  Astronomers often use Mars Sol Date (MSD) which is a
+sequential count of Mars solar days elapsed since about 1873-12-29
+12:00 GMT.
+
+The tz database does not currently support Mars time, but it is
+documented here in the hopes that support will be added eventually.
+
+Sources:
+
+Michael Allison and Robert Schmunk,
+"Technical Notes on Mars Solar Time as Adopted by the Mars24 Sunclock"
+<http://www.giss.nasa.gov/tools/mars24/help/notes.html> (2004-07-30).
+
+Jia-Rui Chong, "Workdays Fit for a Martian", Los Angeles Times
+(2004-01-14), pp A1, A20-A21.
diff --git a/lib/nbsd_libc/time/_daylight.c b/lib/nbsd_libc/time/_daylight.c
new file mode 100644 (file)
index 0000000..9f7f5fc
--- /dev/null
@@ -0,0 +1,16 @@
+/*     $NetBSD: _daylight.c,v 1.4 2005/09/13 01:44:10 christos Exp $   */
+
+/*
+ * Written by Klaus Klein, December 27, 2000.
+ * Public domain.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: _daylight.c,v 1.4 2005/09/13 01:44:10 christos Exp $");
+#endif /* LIBC_SCCS and not lint */
+
+#if defined(__indr_reference)
+__indr_reference(_daylight, daylight)
+#endif
+/* LINTED empty translation unit */
diff --git a/lib/nbsd_libc/time/asctime.c b/lib/nbsd_libc/time/asctime.c
new file mode 100644 (file)
index 0000000..8dc5c48
--- /dev/null
@@ -0,0 +1,155 @@
+/*     $NetBSD: asctime.c,v 1.13 2009/12/31 22:49:16 mlelstv Exp $     */
+
+/*
+** This file is in the public domain, so clarified as of
+** 1996-06-05 by Arthur David Olson.
+*/
+
+/*
+** Avoid the temptation to punt entirely to strftime;
+** the output of strftime is supposed to be locale specific
+** whereas the output of asctime is supposed to be constant.
+*/
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char    elsieid[] = "@(#)asctime.c      8.2";
+#else
+__RCSID("$NetBSD: asctime.c,v 1.13 2009/12/31 22:49:16 mlelstv Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*LINTLIBRARY*/
+
+#include "namespace.h"
+#include "private.h"
+#include "tzfile.h"
+
+#ifdef __weak_alias
+__weak_alias(asctime_r,_asctime_r)
+#endif
+
+/*
+** Some systems only handle "%.2d"; others only handle "%02d";
+** "%02.2d" makes (most) everybody happy.
+** At least some versions of gcc warn about the %02.2d;
+** we conditionalize below to avoid the warning.
+*/
+/*
+** All years associated with 32-bit time_t values are exactly four digits long;
+** some years associated with 64-bit time_t values are not.
+** Vintage programs are coded for years that are always four digits long
+** and may assume that the newline always lands in the same place.
+** For years that are less than four digits, we pad the output with
+** leading zeroes to get the newline in the traditional place.
+** The -4 ensures that we get four characters of output even if
+** we call a strftime variant that produces fewer characters for some years.
+** The ISO C 1999 and POSIX 1003.1-2004 standards prohibit padding the year,
+** but many implementations pad anyway; most likely the standards are buggy.
+*/
+#ifdef __GNUC__
+#define ASCTIME_FMT    "%.3s %.3s%3d %2.2d:%2.2d:%2.2d %-4s\n"
+#else /* !defined __GNUC__ */
+#define ASCTIME_FMT    "%.3s %.3s%3d %02.2d:%02.2d:%02.2d %-4s\n"
+#endif /* !defined __GNUC__ */
+/*
+** For years that are more than four digits we put extra spaces before the year
+** so that code trying to overwrite the newline won't end up overwriting
+** a digit within a year and truncating the year (operating on the assumption
+** that no output is better than wrong output).
+*/
+#ifdef __GNUC__
+#define ASCTIME_FMT_B  "%.3s %.3s%3d %2.2d:%2.2d:%2.2d     %s\n"
+#else /* !defined __GNUC__ */
+#define ASCTIME_FMT_B  "%.3s %.3s%3d %02.2d:%02.2d:%02.2d     %s\n"
+#endif /* !defined __GNUC__ */
+
+#define STD_ASCTIME_BUF_SIZE   26
+/*
+** Big enough for something such as
+** ??? ???-2147483648 -2147483648:-2147483648:-2147483648     -2147483648\n
+** (two three-character abbreviations, five strings denoting integers,
+** seven explicit spaces, two explicit colons, a newline,
+** and a trailing ASCII nul).
+** The values above are for systems where an int is 32 bits and are provided
+** as an example; the define below calculates the maximum for the system at
+** hand.
+*/
+#define MAX_ASCTIME_BUF_SIZE   (2*3+5*INT_STRLEN_MAXIMUM(int)+7+2+1+1)
+
+static char    buf_asctime[MAX_ASCTIME_BUF_SIZE];
+
+/*
+** A la ISO/IEC 9945-1, ANSI/IEEE Std 1003.1, 2004 Edition.
+*/
+
+/*
+** Big enough for something such as
+** ??? ???-2147483648 -2147483648:-2147483648:-2147483648 -2147483648\n
+** (two three-character abbreviations, five strings denoting integers,
+** three explicit spaces, two explicit colons, a newline,
+** and a trailing ASCII nul).
+*/
+#define        ASCTIME_BUFLEN  (3 * 2 + 5 * INT_STRLEN_MAXIMUM(int) + 3 + 2 + 1 + 1)
+
+char *
+asctime_r(timeptr, buf)
+register const struct tm *     timeptr;
+char *                         buf;
+{
+       static const char       *wday_name[7] = {
+               "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+       };
+       static const char       *mon_name[12] = {
+               "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+               "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+       };
+       register const char *   wn;
+       register const char *   mn;
+       char                    year[INT_STRLEN_MAXIMUM(int) + 2];
+       char                    result[MAX_ASCTIME_BUF_SIZE];
+
+       if (timeptr->tm_wday < 0 || timeptr->tm_wday >= DAYSPERWEEK)
+               wn = "???";
+       else    wn = wday_name[timeptr->tm_wday];
+       if (timeptr->tm_mon < 0 || timeptr->tm_mon >= MONSPERYEAR)
+               mn = "???";
+       else    mn = mon_name[timeptr->tm_mon];
+       /*
+       ** Use strftime's %Y to generate the year, to avoid overflow problems
+       ** when computing timeptr->tm_year + TM_YEAR_BASE.
+       ** Assume that strftime is unaffected by other out-of-range members
+       ** (e.g., timeptr->tm_mday) when processing "%Y".
+       */
+       (void) strftime(year, sizeof year, "%Y", timeptr);
+       (void) snprintf(result,
+               sizeof(result),
+               ((strlen(year) <= 4) ? ASCTIME_FMT : ASCTIME_FMT_B),
+               wn, mn,
+               timeptr->tm_mday, timeptr->tm_hour,
+               timeptr->tm_min, timeptr->tm_sec,
+               year);
+       if (strlen(result) < STD_ASCTIME_BUF_SIZE || buf == buf_asctime) {
+               (void) strcpy(buf, result);
+               return buf;
+       } else {
+#ifdef EOVERFLOW
+               errno = EOVERFLOW;
+#else /* !defined EOVERFLOW */
+               errno = EINVAL;
+#endif /* !defined EOVERFLOW */
+               return NULL;
+       }
+}
+
+/*
+** A la ISO/IEC 9945-1, ANSI/IEEE Std 1003.1, 2004 Edition.
+*/
+
+char *
+asctime(timeptr)
+register const struct tm *     timeptr;
+{
+       return asctime_r(timeptr, buf_asctime);
+}
diff --git a/lib/nbsd_libc/time/checktab.awk b/lib/nbsd_libc/time/checktab.awk
new file mode 100644 (file)
index 0000000..1263a3b
--- /dev/null
@@ -0,0 +1,161 @@
+#      $NetBSD: checktab.awk,v 1.4 2009/12/31 22:49:16 mlelstv Exp $
+
+# Check tz tables for consistency.
+
+# @(#)checktab.awk     8.1
+
+# Contributed by Paul Eggert.
+
+BEGIN {
+       FS = "\t"
+
+       if (!iso_table) iso_table = "iso3166.tab"
+       if (!zone_table) zone_table = "zone.tab"
+       if (!want_warnings) want_warnings = -1
+
+       while (getline <iso_table) {
+               iso_NR++
+               if ($0 ~ /^#/) continue
+               if (NF != 2) {
+                       printf "%s:%d: wrong number of columns\n", \
+                               iso_table, iso_NR >>"/dev/stderr"
+                       status = 1
+               }
+               cc = $1
+               name = $2
+               if (cc !~ /^[A-Z][A-Z]$/) {
+                       printf "%s:%d: invalid country code `%s'\n", \
+                               iso_table, iso_NR, cc >>"/dev/stderr"
+                       status = 1
+               }
+               if (cc <= cc0) {
+                       if (cc == cc0) {
+                               s = "duplicate";
+                       } else {
+                               s = "out of order";
+                       }
+
+                       printf "%s:%d: country code `%s' is %s\n", \
+                               iso_table, iso_NR, cc, s \
+                               >>"/dev/stderr"
+                       status = 1
+               }
+               cc0 = cc
+               if (name2cc[name]) {
+                       printf "%s:%d: `%s' and `%s' have the sname name\n", \
+                               iso_table, iso_NR, name2cc[name], cc \
+                               >>"/dev/stderr"
+                       status = 1
+               }
+               name2cc[name] = cc
+               cc2name[cc] = name
+               cc2NR[cc] = iso_NR
+       }
+
+       zone_table = "zone.tab"
+       cc0 = ""
+
+       while (getline <zone_table) {
+               zone_NR++
+               if ($0 ~ /^#/) continue
+               if (NF != 3 && NF != 4) {
+                       printf "%s:%d: wrong number of columns\n", \
+                               zone_table, zone_NR >>"/dev/stderr"
+                       status = 1
+               }
+               cc = $1
+               coordinates = $2
+               tz = $3
+               comments = $4
+               if (cc < cc0) {
+                       printf "%s:%d: country code `%s' is out of order\n", \
+                               zone_table, zone_NR, cc >>"/dev/stderr"
+                       status = 1
+               }
+               cc0 = cc
+               if (tz2cc[tz]) {
+                       printf "%s:%d: %s: duplicate TZ column\n", \
+                               zone_table, zone_NR, tz >>"/dev/stderr"
+                       status = 1
+               }
+               tz2cc[tz] = cc
+               tz2comments[tz] = comments
+               tz2NR[tz] = zone_NR
+               if (cc2name[cc]) {
+                       cc_used[cc]++
+               } else {
+                       printf "%s:%d: %s: unknown country code\n", \
+                               zone_table, zone_NR, cc >>"/dev/stderr"
+                       status = 1
+               }
+               if (coordinates !~ /^[-+][0-9][0-9][0-5][0-9][-+][01][0-9][0-9][0-5][0-9]$/ \
+                   && coordinates !~ /^[-+][0-9][0-9][0-5][0-9][0-5][0-9][-+][01][0-9][0-9][0-5][0-9][0-5][0-9]$/) {
+                       printf "%s:%d: %s: invalid coordinates\n", \
+                               zone_table, zone_NR, coordinates >>"/dev/stderr"
+                       status = 1
+               }
+       }
+
+       for (tz in tz2cc) {
+               if (cc_used[tz2cc[tz]] == 1) {
+                       if (tz2comments[tz]) {
+                               printf "%s:%d: unnecessary comment `%s'\n", \
+                                       zone_table, tz2NR[tz], tz2comments[tz] \
+                                       >>"/dev/stderr"
+                               status = 1
+                       }
+               } else {
+                       if (!tz2comments[tz]) {
+                               printf "%s:%d: missing comment\n", \
+                                       zone_table, tz2NR[tz] >>"/dev/stderr"
+                               status = 1
+                       }
+               }
+       }
+
+       FS = " "
+}
+
+{
+       tz = ""
+       if ($1 == "Zone") tz = $2
+       if ($1 == "Link") {
+               # Ignore Link commands if source and destination basenames
+               # are identical, e.g. Europe/Istanbul versus Asia/Istanbul.
+               src = $2
+               dst = $3
+               while ((i = index(src, "/"))) src = substr(src, i+1)
+               while ((i = index(dst, "/"))) dst = substr(dst, i+1)
+               if (src != dst) tz = $3
+       }
+       if (tz && tz ~ /\//) {
+               if (!tz2cc[tz]) {
+                       printf "%s: no data for `%s'\n", zone_table, tz \
+                               >>"/dev/stderr"
+                       status = 1
+               }
+               zoneSeen[tz] = 1
+       }
+}
+
+END {
+       for (tz in tz2cc) {
+               if (!zoneSeen[tz]) {
+                       printf "%s:%d: no Zone table for `%s'\n", \
+                               zone_table, tz2NR[tz], tz >>"/dev/stderr"
+                       status = 1
+               }
+       }
+
+       if (0 < want_warnings) {
+               for (cc in cc2name) {
+                       if (!cc_used[cc]) {
+                               printf "%s:%d: warning: " \
+                                       "no Zone entries for %s (%s)\n", \
+                                       iso_table, cc2NR[cc], cc, cc2name[cc]
+                       }
+               }
+       }
+
+       exit status
+}
diff --git a/lib/nbsd_libc/time/ctime.3 b/lib/nbsd_libc/time/ctime.3
new file mode 100644 (file)
index 0000000..0399e57
--- /dev/null
@@ -0,0 +1,456 @@
+.\" $NetBSD: ctime.3,v 1.37 2010/12/17 01:30:50 wiz Exp $
+.Dd December 14, 2010
+.Dt CTIME 3
+.Os
+.Sh NAME
+.Nm asctime ,
+.Nm asctime_r ,
+.Nm ctime ,
+.Nm ctime_r ,
+.Nm ctime_rz ,
+.Nm difftime ,
+.Nm gmtime ,
+.Nm gmtime_r ,
+.Nm localtime ,
+.Nm localtime_r ,
+.Nm localtime_rz ,
+.Nm mktime ,
+.Nm mktime_z ,
+.Nm tzalloc ,
+.Nm tzgetname ,
+.Nm tzfree ,
+.Nd convert date and time to ASCII
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Dv extern char *tzname[2];
+.Ft char *
+.Fn ctime "const time_t *clock"
+.Ft char *
+.Fn ctime_r "const time_t *clock"  "char *buf"
+.Ft char *
+.Fn ctime_rz "const timezone_t tz" "const time_t *clock"  "char *buf"
+.Ft double
+.Fn difftime "time_t time1" "time_t time0"
+.Ft char *
+.Fn asctime "const struct tm *tm"
+.Ft char *
+.Fn asctime_r "const struct tm restrict tm" "char * restrict buf"
+.Ft struct tm *
+.Fn localtime "const time_t *clock"
+.Ft struct tm *
+.Fn localtime_r "const time_t * restrict clock" "struct tm * restrict result"
+.Ft struct tm *
+.Fn localtime_rz "const timezone_t tz" "const time_t * restrict clock" "struct tm * restrict result"
+.Ft struct tm *
+.Fn gmtime "const time_t *clock"
+.Ft struct tm *
+.Fn gmtime_r "const time_t * restrict clock" "struct tm * restrict result"
+.Ft time_t
+.Fn mktime "struct tm *tm"
+.Ft time_t
+.Fn mktime_z "const timezone_t tz" "struct tm *tm"
+.Ft timezone_t
+.Fn tzalloc "const char *zone"
+.Ft const char *
+.Fn tzgetname "const timezone_t tz" "int isdst"
+.Ft void
+.Fn tzfree "const timezone_t tz"
+.Sh DESCRIPTION
+.Fn ctime
+converts a
+.Tp time_t ,
+pointed to by
+.Fa clock ,
+representing the time in seconds since
+00:00:00 UTC, 1970-01-01,
+and returns a pointer to a
+string of the form
+.D1 Thu Nov 24 18:22:48 1986\en\e0
+Years requiring fewer than four characters are padded with leading zeroes.
+For years longer than four characters, the string is of the form
+.D1 Thu Nov 24 18:22:48     81986\en\e0
+with five spaces before the year.
+These unusual formats are designed to make it less likely that older
+software that expects exactly 26 bytes of output will mistakenly output
+misleading values for out-of-range years.
+.Pp
+.Fn ctime_r
+is similar to
+.Fn ctime ,
+except it places the result of the conversion on the
+.Fa buf
+argument which should be 26 or more bytes long, instead of using a global
+static buffer.
+.Pp
+.Fn ctime_rz
+is similar to
+.Fn ctime_r ,
+but it also takes a
+.Ft "const timezone_t"
+argument, returned by a previous call to
+.Fn tzalloc .
+.Pp
+.Fn localtime
+and
+.Fn gmtime
+return pointers to
+.Va tm
+structures, described below.
+.Fn localtime
+corrects for the time zone and any time zone adjustments
+(such as Daylight Saving Time in the U.S.A.).
+After filling in the
+.Va tm
+structure,
+.Fn localtime
+sets the
+.Fa tm_isdst Ns 'th
+element of
+.Fa tzname
+to a pointer to an
+ASCII string that's the time zone abbreviation to be used with
+.Fn localtime Ns 's
+return value.
+.Pp
+.Fn gmtime
+converts to Coordinated Universal Time.
+.Pp
+The
+.Fn gmtime_r
+and
+.Fn localtime_r
+functions provide the same functionality as
+.Fn gmtime
+and
+.Fn localtime
+differing in that the caller must supply a buffer area
+.Fa result
+in which the result is stored; also,
+.Fn localtime_r
+does not imply initialization of the local time conversion information;
+the application may need to do so by calling
+.Xr tzset 3 .
+.Pp
+.Fn localtime_rz
+is similar to
+.Fn localtime_r ,
+but it also takes a
+.Ft "const timezone_t"
+argument, returned by a previous call to
+.Fn tzalloc .
+.Pp
+.Fn asctime
+converts a time value contained in a
+.Dq tm
+structure to a string,
+as shown in the above example,
+and returns a pointer to the string.
+.Pp
+.Fn mktime
+converts the broken-down time,
+expressed as local time,
+in the structure pointed to by
+.Fa tm
+into a calendar time value with the same encoding as that of the values
+returned by the
+.Xr time 3
+function.
+The original values of the
+.Fa tm_wday
+and
+.Fa tm_yday
+components of the structure are ignored,
+and the original values of the other components are not restricted
+to their normal ranges.
+(A positive or zero value for
+.Fa tm_isdst
+causes
+.Fn mktime
+to presume initially that summer time (for example, Daylight Saving Time
+in the U.S.A.) respectively,
+is or is not in effect for the specified time.
+A negative value for
+.Fa tm_isdst
+causes the
+.Fn mktime
+function to attempt to divine whether summer time is in effect
+for the specified time; in this case it does not use a consistent
+rule and may give a different answer when later
+presented with the same argument.)
+On successful completion, the values of the
+.Fa tm_wday
+and
+.Fa tm_yday
+components of the structure are set appropriately,
+and the other components are set to represent the specified calendar time,
+but with their values forced to their normal ranges; the final value of
+.Fa tm_mday
+is not set until
+.Fa tm_mon
+and
+.Fa tm_year
+are determined.
+.Fn mktime
+returns the specified calendar time; if the calendar time cannot be
+represented, it returns
+.Va "(time_t)-1" .
+.Pp
+.Fn mktime_z
+is similar to
+.Fn mktime
+but it also takes a
+.Ft "const timezone_t"
+argument, returned by a previous call to
+.Fn tzalloc .
+.Pp
+.Fn difftime
+returns the difference between two calendar times,
+.Fa ( time1 No - Fa time0 ) ,
+expressed in seconds.
+.Pp
+.Fn tzalloc
+takes as an argument a timezone name and returns a
+.Ft timezone_t
+object suitable to be used in
+.Fn ctime_rz ,
+.Fn localtime_rz ,
+and
+.Fn mktime_z .
+Instead of setting the environment variable
+.Va TZ ,
+and globally changing the behavior of the calling program, one can use
+multiple timezones at the same time by using separate
+.Ft timezone_t
+objects allocated by
+.Fn tzalloc
+and calling the
+.Dq z
+variants of the functions.
+.Pp
+.Fn tzgetname
+returns the name for the given
+.Fa tz .
+If
+.Fa isdst
+is
+.Va 0 ,
+the call is equivalent to
+.Va tzname[0] .
+If
+.Fa isdst
+is set to
+.Va 1
+the call is equivalent to
+.Va tzname[1] .
+.Pp
+.Fn tzfree
+frees the
+.Fa tz
+argument previously returned by
+.Fa tzalloc .
+.Pp
+The structure (of type)
+.Va "struct tm"
+includes the following fields:
+.Bd -literal -offset indent
+int tm_sec;    /* seconds after the minute [0,61] */
+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;   /* day of week [0,6] (Sunday = 0) */
+int tm_yday;   /* day of year [0,365] (Jan 1 = 0) */
+int tm_isdst;  /* daylight savings flag */
+long tm_gmtoff;        /* offset from UTC in seconds */
+char *tm_zone; /* abbreviation of timezone name */
+.Ed
+.Pp
+The
+.Fa tm_zone
+and
+.Fa tm_gmtoff
+fields exist, and are filled in, only if arrangements to do
+so were made when the library containing these functions was
+created.
+There is no guarantee that these fields will continue to exist
+in this form in future releases of this code.
+The
+.Fa tm_zone
+field will become invalid and point to freed storage if the corresponding
+.Va "struct tm"
+was returned by
+.Fn localtime_rz
+and the
+.Ft "const timezone_t"
+.Fa tz
+argument has been freed by
+.Fn tzfree .
+.Pp
+.Fa tm_isdst
+is non-zero if summer time is in effect.
+.Pp
+.Fa tm_gmtoff
+is the offset (in seconds) of the time represented
+from UTC, with positive values indicating east
+of the Prime Meridian.
+.Sh RETURN VALUES
+On success the
+.Fn asctime
+and
+.Fn ctime
+functions return a pointer to a static character buffer, and the
+.Fn asctime_r ,
+.Fn ctime_r ,
+and
+.Fn ctime_rz
+function return a pointer to the user-supplied buffer.
+On failure they all return
+.Dv NULL
+and no errors are defined for them.
+On success the
+.Fn gmtime ,
+and
+.Fn localtime
+functions return a pointer to a statically allocated
+.Va "struct tm"
+whereas the
+.Fn gmtime_r ,
+.Fn localtime_r ,
+and
+.Fn localtime_rz ,
+functions return a pointer to the user-supplied
+.Va "struct tm" .
+On failure they all return
+.Dv NULL
+and the global variable
+.Va errno
+is set to indicate the error.
+The
+.Fn mktime
+and
+.Fn mktime_z
+function returns the specified time since the Epoch as a
+.Va time_t
+type value.
+If the time cannot be represented, then
+.Fn mktime
+and
+.Fn mktime_z
+return
+.Va "(time_t)-1"
+setting the global variable
+.Va errno
+to indicate the error.
+The
+.Fn tzalloc
+function returns a pointer to a
+.Ft timezone_t
+object or
+.Dv NULL
+on failure, setting
+.Va errno
+to indicate the error.
+.Fn tzgetzone
+function returns string containing the name of the timezone given in
+.Fa tz .
+.Sh FILES
+.Bl -tag -width /usr/share/zoneinfo/posixrules -compact
+.It Pa /etc/localtime
+local time zone file
+.It Pa /usr/share/zoneinfo
+time zone information directory
+.It Pa /usr/share/zoneinfo/posixrules
+used with POSIX-style TZ's
+.It Pa /usr/share/zoneinfo/GMT
+for UTC leap seconds
+.El
+.Pp
+If
+.Pa /usr/share/zoneinfo/GMT
+is absent, UTC leap seconds are loaded from
+.Pa /usr/share/zoneinfo/posixrules .
+.Sh ERRORS
+The
+.Fn gmtime_r ,
+.Fn localtime_r ,
+.Fn localtime_rz ,
+.Fn gmtime ,
+.Fn localtime ,
+and
+.Fn mktime ,
+and
+.Fn mktime_z
+will fail when:
+.Bl -tag -width Er
+.It Bq Er EINVAL
+The result cannot be represented.
+.It Bq Er EOVERFLOW
+The result cannot be represented.
+.El
+.Pp
+All functions that return values except their
+.Dq z
+variants, can also return the same errors as
+.Xr open 2
+and
+.Xr malloc 3 .
+.Sh SEE ALSO
+.Xr getenv 3 ,
+.Xr strftime 3 ,
+.Xr time 3 ,
+.Xr tzset 3 ,
+.Xr tzfile 5
+.Sh STANDARDS
+The
+.Fn ctime ,
+.Fn difftime ,
+.Fn asctime ,
+.Fn localtime ,
+.Fn gmtime
+and
+.Fn mktime
+functions conform to
+.St -ansiC
+The
+.Fn ctime_r ,
+.Fn asctime_r ,
+.Fn localtime_r
+and
+.Fn gmtime_r
+functions conform to
+.St -p1003.1c-95 .
+.Sh NOTES
+The return values point to static data; the data is overwritten by
+each call.
+The
+.Fa tm_zone
+field of a returned
+.Va "struct tm"
+points to a static array of characters, which
+will also be overwritten at the next call
+(and by calls to
+.Xr tzset 3 ) .
+.Pp
+.Fn asctime
+and
+.Fn ctime
+behave strangely for years before 1000 or after 9999.
+The 1989 and 1999 editions of the C Standard say
+that years from \-99 through 999 are converted without
+extra spaces, but this conflicts with longstanding
+tradition and with this implementation.
+Traditional implementations of these two functions are
+restricted to years in the range 1900 through 2099.
+To avoid this portability mess, new programs should use
+.Fn strftime
+instead.
+.Pp
+Avoid using out-of-range values with
+.Fn mktime
+when setting up lunch with promptness sticklers in Riyadh.
+.\" @(#)newctime.3     8.3
+.\" This file is in the public domain, so clarified as of
+.\" 2009-05-17 by Arthur David Olson.
diff --git a/lib/nbsd_libc/time/difftime.c b/lib/nbsd_libc/time/difftime.c
new file mode 100644 (file)
index 0000000..648f8fc
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: difftime.c,v 1.10 2009/12/31 22:49:16 mlelstv Exp $    */
+
+/*
+** This file is in the public domain, so clarified as of
+** 1996-06-05 by Arthur David Olson.
+*/
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char    elsieid[] = "@(#)difftime.c     8.1";
+#else
+__RCSID("$NetBSD: difftime.c,v 1.10 2009/12/31 22:49:16 mlelstv Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*LINTLIBRARY*/
+
+#include "private.h"   /* for time_t, TYPE_INTEGRAL, and TYPE_SIGNED */
+
+double
+difftime(time1, time0)
+const time_t   time1;
+const time_t   time0;
+{
+       /*
+       ** If (sizeof (double) > sizeof (time_t)) simply convert and subtract
+       ** (assuming that the larger type has more precision).
+       ** This is the common real-world case circa 2004.
+       */
+/* LINTED constant */
+       if (sizeof (double) > sizeof (time_t))
+               return (double) time1 - (double) time0;
+/* LINTED constant */
+       if (!TYPE_INTEGRAL(time_t)) {
+               /*
+               ** time_t is floating.
+               */
+               return time1 - time0;
+       }
+/* LINTED constant */
+       if (!TYPE_SIGNED(time_t)) {
+               /*
+               ** time_t is integral and unsigned.
+               ** The difference of two unsigned values can't overflow
+               ** if the minuend is greater than or equal to the subtrahend.
+               */
+               if (time1 >= time0)
+                       return time1 - time0;
+               else    return -((double) (time0 - time1));
+       }
+       /*
+       ** time_t is integral and signed.
+       ** Handle cases where both time1 and time0 have the same sign
+       ** (meaning that their difference cannot overflow).
+       */
+       if ((time1 < 0) == (time0 < 0))
+               return time1 - time0;
+       /*
+       ** time1 and time0 have opposite signs.
+       ** Punt if unsigned long is too narrow.
+       */
+/* CONSTCOND */
+       if (sizeof (unsigned long) < sizeof (time_t))
+               return (double) time1 - (double) time0;
+       /*
+       ** Stay calm...decent optimizers will eliminate the complexity below.
+       */
+       if (time1 >= 0 /* && time0 < 0 */)
+               return (unsigned long) time1 +
+                       (unsigned long) (-(time0 + 1)) + 1;
+       return -(double) ((unsigned long) time0 +
+               (unsigned long) (-(time1 + 1)) + 1);
+}
diff --git a/lib/nbsd_libc/time/getdate.3 b/lib/nbsd_libc/time/getdate.3
new file mode 100644 (file)
index 0000000..c501ad7
--- /dev/null
@@ -0,0 +1,234 @@
+.\"    $NetBSD: getdate.3,v 1.1 2009/05/14 02:37:36 ginsbach Exp $
+.\"
+.\" Copyright (c) 2009, The NetBSD Foundation.
+.\" All Rights Reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Brian Ginsbach.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 8, 2009
+.Dt GETDATE 3
+.Os
+.Sh NAME
+.Nm getdate ,
+.Nm getdate_err
+.Nd convert user format date and time
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Ft "struct tm *"
+.Fo "getdate"
+.Fa "const char *str"
+.Fc
+.Vt extern int getdate_err ;
+.Sh DESCRIPTION
+The
+.Fn getdate
+function converts a date or time character string pointed to by
+.Fa str
+into a static
+.Va tm
+structure.
+.Pp
+The input string is parsed and interpreted using templates.
+A text file containing templates is specified by the
+environment variable
+.Ev DATEMSK .
+This should contain the full path to the template file.
+Lines in the template file represent acceptable date and/or time
+conversion specifications.
+These specifications are similar to those given for
+.Xr strptime 3 .
+The first line in the template file that matches the input string
+is used to interpret and convert to internal time format.
+.Ss Internal Format Conversion
+The following rules apply to converting the input into the internal format.
+.Bl -bullet -offset indent
+.It
+If only the weekday is given, the conversion assumes today when the
+weekday matches today or the first future matching weekday.
+.It
+If only the month and no year is given, the conversion assumes the
+current month when the month matches or the first future matching month.
+The first day of the month is assumed if no day is given.
+.It
+If only the year is given, the values of the
+.Fa tm_mon ,
+.Fa tm_mday ,
+.Fa tm_wday ,
+.Fa tm_yday ,
+and
+.Fa tm_isdst
+members of the returned
+.Va "struct tm"
+are unspecified.
+.It
+If the century is given, but the year within the century is not given,
+the conversion assumes the current year.
+.It
+If no hour, minute, and second are given, the conversion assumes
+the current hour, minute, and second.
+.It
+If no date is given, the conversion assumes today when the given hour
+is greater than the current hour and tomorrow when the given hour is less.
+.It
+If
+.Cm \&%Z
+is being scanned, then the broken-down time is based on the the
+current time of the matched timezone and not the current runtime
+environment timezone.
+.El
+.Sh RETURN VALUES
+If successful, the
+.Fn getdate
+function returns a pointer to a static
+.Va tm
+structure containing the broken-down time.
+Otherwise, a null pointer is returned and
+.Va getdate_err
+is set to indicate the error.
+.Pp
+The variable
+.Va getdate_err
+can have the following values:
+.Bl -tag -width NNN
+.It 1
+.Ev DATEMSK
+environment variable is null or undefined.
+.It 2
+Cannot open the template file for reading.
+.It 3
+Get file status failed for template file.
+.It 4
+Template file is not a regular file.
+.It 5
+Encountered an error while reading the template file.
+.It 6
+Cannot allocate memory.
+.It 7
+Input string does not match any line in the template file.
+.It 8
+Input string is invalid
+.Pq for example February 31
+or could not be represented in a
+.Va time_t .
+.El
+.Sh ENVIRONMENT
+.Bl -tag -width DATEMSK
+.It Ev DATEMSK
+The full path to the text file containing the templates
+for acceptable date and/or time conversions.
+.El
+.Sh FILES
+.Bl -tag -width DATEMSK
+.It  Pa /usr/share/examples/getdate/datemsk.template
+An example template file that could be specified via the
+.Ev DATEMSK
+environment variable.
+.El
+.Sh EXAMPLES
+The following example shows the possible contents of a template file:
+.Pp
+.Bd -literal -offset indent -compact
+%m
+%A %B %d, %Y, %H:%M:%S
+%A
+%B
+%m/%d/%y %I %p
+%d,%m,%Y %H:%M
+at %A the %dst of %B in %Y
+run job at %I %p, %B %dnd
+%A den %d. %B %Y %H.%M Uhr
+.Ed
+.Pp
+The following are examples of valid input for the above template:
+.Pp
+.Bd -literal -offset indent -compact
+10/1/87 4 PM
+Friday
+Firday September 18, 1987, 10:30:30
+24,9,1986 10:30
+at monday the 1st of december in 1986
+run job at 3 PM, december 2nd
+.Ed
+.Pp
+The following examples show how local data and time specification can be
+defined in the template.
+.Pp
+.Bl -column -offset indent ".Sy Input String" ".Sy Line in Template"
+.It Sy "Input String" Ta Sy "Line in Template"
+.It Li 11/27/86 Ta Li \&%m/\&%d/\&%y
+.It Li 27.11.86 Ta Li \&%d.\&%m/\&%y
+.It Li 86-11-27 Ta Li \&%y-\&%m-\&%d
+.It Li "Friday 12:00:00" Ta "\&%A \&%H:\&%M:\&%S"
+.El
+.Pp
+The following examples illustrate the Internal Format Conversion rules
+given that the current date is
+.Li "Mon Sep 22 12:19:47 EDT 1986"
+and the
+.Ev LC_TIME
+environment variable is set to the default C locale.
+.Pp
+.Bl -column -offset indent ".Sy Input String" ".Sy Line in Template" ".Sy Date"
+.It Sy Input String Ta Sy Line in Template Ta Sy Date
+.It Li Mon Ta Li \&%a Ta Li "Mon Sep 22 12:19:47 EDT 1986"
+.It Li Sun Ta Li \&%a Ta Li "Sun Sep 28 12:19:47 EDT 1986"
+.It Li Fri Ta Li \&%a Ta Li "Sun Sep 26 12:19:47 EDT 1986"
+.It Li September Ta Li \&%B Ta Li "Mon Sep  1 12:19:47 EDT 1986"
+.It Li January Ta Li \&%B Ta Li "Thu Jan  1 12:19:47 EST 1987"
+.It Li December Ta Li \&%B Ta Li "Mon Dec  1 12:19:47 EST 1987"
+.It Li "Sep Mon" Ta Li "\&%b %a" Ta Li "Mon Sep  1 12:19:47 EDT 1986"
+.It Li "Jan Fri" Ta Li "\&%b %a" Ta Li "Fri Jan  2 12:19:47 EDT 1987"
+.It Li "Dec Mon" Ta Li "\&%b %a" Ta Li "Mon Dec  1 12:19:47 EDT 1986"
+.It Li "Jan Wed 1989" Ta Li "\&%b \&%a \&%Y" Ta Li "Wed Jan  4 12:19:47 EST 1989"
+.It Li "Fri 9" Ta Li "\&%a \&%H" Ta Li "Fri Sep 26 09:00:00 EDT 1986"
+.It Li "Feb 10:30" Ta Li "\&%b \&%H:\&%S" Ta Li "Sun Feb  1 10:00:30 EST 1987"
+.It Li 10:30 Ta Li "\&%H:\&%M" Ta Li "Tue Sep 23 10:30:00 EDT 1986"
+.It Li 13:30 Ta Li "\&%H:\&%M" Ta Li "Tue Sep 22 13:30:00 EDT 1986"
+.El
+.Sh SEE ALSO
+.Xr ctime 3 ,
+.Xr localtime 3 ,
+.Xr mktime 3 ,
+.Xr strftime 3 ,
+.Xr strptime 3 ,
+.Xr time 3
+.Sh STANDARDS
+The
+.Fn getdate
+function conforms to
+.St -p1003.1-2001 .
+.Sh HISTORY
+The
+.Nm
+function appeared in
+.At V.4 .
+.Sh BUGS
+The
+.Nm
+interface is inherently unsafe for multi-threaded programs or libraries,
+since it returns a pointer to a static variable and uses a global state
+variable.
diff --git a/lib/nbsd_libc/time/getdate.c b/lib/nbsd_libc/time/getdate.c
new file mode 100644 (file)
index 0000000..a35af32
--- /dev/null
@@ -0,0 +1,270 @@
+/*     $NetBSD: getdate.c,v 1.2 2009/11/22 18:07:39 mbalmer Exp $      */
+/*
+ * Copyright (c) 2009 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Brian Ginsbach.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/stat.h>
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+#include <util.h>
+
+#define TMSENTINEL     (-1)
+
+/*
+ * getdate_err is set to one of the following values on error.
+ *
+ * 1   The DATEMSK environment variable is null or undefined.
+ * 2   The template file cannot be opened for reading.
+ * 3   Failed to get file status information.
+ * 4   Template file is not a regular file.
+ * 5   Encountered an error while reading the template file.
+ * 6   Cannot allocate memory.
+ * 7   Input string does not match any line in the template.
+ * 8   Input string is invalid (for example, February 31) or could not
+ *     be represented in a time_t.
+ */
+
+int getdate_err;
+
+struct tm *
+getdate(const char *str)
+{
+       char *datemsk, *line, *rp;
+       FILE *fp;
+       struct stat sb;
+       static struct tm rtm, tmnow;
+       struct tm *tmp, *rtmp = &rtm;
+       size_t lineno = 0;
+       time_t now;
+
+       if (((datemsk = getenv("DATEMSK")) == NULL) || *datemsk == '\0') {
+               getdate_err = 1;
+               return (NULL);
+       }
+
+       if (stat(datemsk, &sb) < 0) {
+               getdate_err = 3;
+               return (NULL);
+       }
+
+       if ((sb.st_mode & S_IFMT) != S_IFREG) {
+               getdate_err = 4;
+               return (NULL);
+       }
+
+       if ((fp = fopen(datemsk, "r")) == NULL) {
+               getdate_err = 2;
+               return (NULL);
+       }
+
+       /* loop through datemsk file */
+       errno = 0;
+       rp = NULL;
+       while ((line = fparseln(fp, NULL, &lineno, NULL, 0)) != NULL) {
+               /* initialize tmp with sentinels */
+               rtm.tm_sec = rtm.tm_min = rtm.tm_hour = TMSENTINEL;
+               rtm.tm_mday = rtm.tm_mon = rtm.tm_year = TMSENTINEL;
+               rtm.tm_wday = rtm.tm_yday = rtm.tm_isdst = TMSENTINEL;
+               rtm.tm_gmtoff = 0;
+               rtm.tm_zone = NULL;
+               rp = strptime(str, line, rtmp);
+               free(line);
+               if (rp != NULL) 
+                       break;
+               errno = 0;
+       }
+       if (errno != 0 || ferror(fp)) {
+               if (errno == ENOMEM)
+                       getdate_err = 6;
+               else
+                       getdate_err = 5;
+               fclose(fp);
+               return (NULL);
+       }
+       if (feof(fp) || (rp != NULL && *rp != '\0')) {
+               getdate_err = 7;
+               return (NULL);
+       }
+       fclose(fp);
+
+       time(&now);
+       tmp = localtime(&now);
+       tmnow = *tmp;
+
+       /*
+        * This implementation does not accept setting the broken-down time
+        * to anything other than the localtime().  It is not possible to
+        * change the scanned timezone with %Z.
+        *
+        * Note IRIX and Solaris accept only the current zone for %Z.
+        * XXX Is there any implementation that matches the standard?
+        * XXX (Or am I reading the standard wrong?)
+        *
+        * Note: Neither XPG 6 (POSIX 2004) nor XPG 7 (POSIX 2008)
+        * requires strptime(3) support for %Z.
+        */
+
+       /*
+        * Given only a weekday find the first matching weekday starting
+        * with the current weekday and moving into the future.
+        */
+       if (rtm.tm_wday != TMSENTINEL && rtm.tm_year == TMSENTINEL &&
+           rtm.tm_mon == TMSENTINEL && rtm.tm_mday == TMSENTINEL) {
+               rtm.tm_year = tmnow.tm_year;
+               rtm.tm_mon = tmnow.tm_mon;
+               rtm.tm_mday = tmnow.tm_mday +
+                       (rtm.tm_wday - tmnow.tm_wday + 7) % 7;
+       }
+
+       /*
+        * Given only a month (and no year) find the first matching month
+        * starting with the current month and moving into the future.
+        */
+       if (rtm.tm_mon != TMSENTINEL) {
+               if (rtm.tm_year == TMSENTINEL) {
+                       rtm.tm_year = tmnow.tm_year +
+                               ((rtm.tm_mon < tmnow.tm_mon)? 1 : 0);
+               }
+               if (rtm.tm_mday == TMSENTINEL) {
+                       /* assume the first of the month */
+                       rtm.tm_mday = 1;
+                       /*
+                        * XXX This isn't documented! Just observed behavior.
+                        *
+                        * Given the weekday find the first matching weekday
+                        * starting with the weekday of the first day of the
+                        * the month and moving into the future.
+                        */
+                       if (rtm.tm_wday != TMSENTINEL) {
+                               struct tm tm;
+
+                               memset(&tm, 0, sizeof(struct tm));
+                               tm.tm_year = rtm.tm_year;
+                               tm.tm_mon = rtm.tm_mon;
+                               tm.tm_mday = 1;
+                               mktime(&tm);
+                               rtm.tm_mday +=
+                                       (rtm.tm_wday - tm.tm_wday + 7) % 7;
+                       }
+               }
+       }
+
+       /*
+        * Given no time of day assume the current time of day.
+        */
+       if (rtm.tm_hour == TMSENTINEL &&
+           rtm.tm_min == TMSENTINEL && rtm.tm_sec == TMSENTINEL) {
+               rtm.tm_hour = tmnow.tm_hour;
+               rtm.tm_min = tmnow.tm_min;
+               rtm.tm_sec = tmnow.tm_sec;
+       }
+       /*
+        * Given an hour and no date, find the first matching hour starting
+        * with the current hour and moving into the future
+        */
+       if (rtm.tm_hour != TMSENTINEL &&
+           rtm.tm_year == TMSENTINEL && rtm.tm_mon == TMSENTINEL &&
+           rtm.tm_mday == TMSENTINEL) {
+               rtm.tm_year = tmnow.tm_year;
+               rtm.tm_mon = tmnow.tm_mon;
+               rtm.tm_mday = tmnow.tm_mday;
+               if (rtm.tm_hour < tmnow.tm_hour)
+                       rtm.tm_hour += 24;
+       }
+
+       /*
+        * Set to 'sane' values; mktime(3) does funny things otherwise.
+        * No hours, no minutes, no seconds, no service.
+        */
+       if (rtm.tm_hour == TMSENTINEL)
+               rtm.tm_hour = 0;
+       if (rtm.tm_min == TMSENTINEL)
+               rtm.tm_min = 0;
+       if (rtm.tm_sec == TMSENTINEL)
+               rtm.tm_sec = 0;
+
+       /*
+        * Given only a year the values of month, day of month, day of year,
+        * week day and is daylight (summer) time are unspecified.
+        * (Specified on the Solaris man page not POSIX.)
+        */
+       if (rtm.tm_year != TMSENTINEL &&
+           rtm.tm_mon == TMSENTINEL && rtm.tm_mday == TMSENTINEL) {
+               rtm.tm_mon = 0;
+               rtm.tm_mday = 1;
+               /*
+                * XXX More undocumented functionality but observed.
+                *
+                * Given the weekday find the first matching weekday
+                * starting with the weekday of the first day of the
+                * month and moving into the future.
+                */
+               if (rtm.tm_wday != TMSENTINEL) {
+                       struct tm tm;
+
+                       memset(&tm, 0, sizeof(struct tm));
+                       tm.tm_year = rtm.tm_year;
+                       tm.tm_mon = rtm.tm_mon;
+                       tm.tm_mday = 1;
+                       mktime(&tm);
+                       rtm.tm_mday += (rtm.tm_wday - tm.tm_wday + 7) % 7;
+               }
+       }
+
+       /*
+        * Given only the century but no year within, the current year
+        * is assumed.  (Specified on the Solaris man page not POSIX.)
+        *
+        * Warning ugly end case
+        *
+        * This is more work since strptime(3) doesn't "do the right thing".
+        */
+       if (rtm.tm_year != TMSENTINEL && (rtm.tm_year - 1900) >= 0) {
+               rtm.tm_year -= 1900;
+               rtm.tm_year += (tmnow.tm_year % 100);
+       }
+
+       /*
+        * mktime() will normalize all values and also check that the
+        * value will fit into a time_t.
+        *
+        * This is only for POSIX correctness.  A date >= 1900 is
+        * really ok, but using a time_t limits things.
+        */
+       if (mktime(rtmp) < 0) {
+               getdate_err = 8;
+               return (NULL);
+       }
+
+       return (rtmp);
+}
diff --git a/lib/nbsd_libc/time/ialloc.c b/lib/nbsd_libc/time/ialloc.c
new file mode 100644 (file)
index 0000000..949631f
--- /dev/null
@@ -0,0 +1,92 @@
+/*     $NetBSD: ialloc.c,v 1.7 2010/01/02 10:42:49 tsutsui Exp $       */
+/*
+** This file is in the public domain, so clarified as of
+** 2006-07-17 by Arthur David Olson.
+*/
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+
+#if 0
+static char    elsieid[] = "@(#)ialloc.c       8.30";
+#else
+__RCSID("$NetBSD: ialloc.c,v 1.7 2010/01/02 10:42:49 tsutsui Exp $");
+#endif
+
+#include "private.h"
+
+#define nonzero(n)     (((n) == 0) ? 1 : (n))
+
+char *
+imalloc(n)
+const int      n;
+{
+       return malloc((size_t) nonzero(n));
+}
+
+char *
+icalloc(nelem, elsize)
+int    nelem;
+int    elsize;
+{
+       if (nelem == 0 || elsize == 0)
+               nelem = elsize = 1;
+       return calloc((size_t) nelem, (size_t) elsize);
+}
+
+void *
+irealloc(pointer, size)
+void * const   pointer;
+const int      size;
+{
+       if (pointer == NULL)
+               return imalloc(size);
+       return realloc((void *) pointer, (size_t) nonzero(size));
+}
+
+char *
+icatalloc(old, new)
+char * const           old;
+const char * const     new;
+{
+       register char * result;
+       register int    oldsize, newsize;
+
+       newsize = (new == NULL) ? 0 : strlen(new);
+       if (old == NULL)
+               oldsize = 0;
+       else if (newsize == 0)
+               return old;
+       else
+               oldsize = strlen(old);
+       if ((result = irealloc(old, oldsize + newsize + 1)) != NULL)
+               if (new != NULL)
+                       (void) strcpy(result + oldsize, new); /* XXX strcpy is safe */
+       return result;
+}
+
+char *
+icpyalloc(string)
+const char * const     string;
+{
+       return icatalloc((char *) NULL, string);
+}
+
+void
+ifree(p)
+char * const   p;
+{
+       if (p != NULL)
+               (void) free(p);
+}
+
+void
+icfree(p)
+char * const   p;
+{
+       if (p != NULL)
+               (void) free(p);
+}
diff --git a/lib/nbsd_libc/time/localtime.c b/lib/nbsd_libc/time/localtime.c
new file mode 100644 (file)
index 0000000..194fd9c
--- /dev/null
@@ -0,0 +1,2209 @@
+/*     $NetBSD: localtime.c,v 1.54 2011/01/15 15:42:10 christos Exp $  */
+
+/*
+** This file is in the public domain, so clarified as of
+** 1996-06-05 by Arthur David Olson.
+*/
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char    elsieid[] = "@(#)localtime.c    8.9";
+#else
+__RCSID("$NetBSD: localtime.c,v 1.54 2011/01/15 15:42:10 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+/*
+** Leap second handling from Bradley White.
+** POSIX-style TZ environment variable handling from Guy Harris.
+*/
+
+/*LINTLIBRARY*/
+
+#include "namespace.h"
+#include "private.h"
+#include "tzfile.h"
+#include "fcntl.h"
+#include "reentrant.h"
+
+#if defined(__weak_alias)
+__weak_alias(ctime_r,_ctime_r)
+__weak_alias(ctime_rz,_ctime_rz)
+__weak_alias(daylight,_daylight)
+__weak_alias(mktime_z,_mktime_z)
+__weak_alias(localtime_r,_localtime_r)
+__weak_alias(localtime_rz,_localtime_rz)
+__weak_alias(posix2time,_posix2time)
+__weak_alias(posix2time_z,_posix2time_z)
+__weak_alias(tzname,_tzname)
+#endif
+
+#include "float.h"     /* for FLT_MAX and DBL_MAX */
+
+#ifndef TZ_ABBR_MAX_LEN
+#define TZ_ABBR_MAX_LEN        16
+#endif /* !defined TZ_ABBR_MAX_LEN */
+
+#ifndef TZ_ABBR_CHAR_SET
+#define TZ_ABBR_CHAR_SET \
+       "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._"
+#endif /* !defined TZ_ABBR_CHAR_SET */
+
+#ifndef TZ_ABBR_ERR_CHAR
+#define TZ_ABBR_ERR_CHAR       '_'
+#endif /* !defined TZ_ABBR_ERR_CHAR */
+
+/*
+** SunOS 4.1.1 headers lack O_BINARY.
+*/
+
+#ifdef O_BINARY
+#define OPEN_MODE      (O_RDONLY | O_BINARY)
+#endif /* defined O_BINARY */
+#ifndef O_BINARY
+#define OPEN_MODE      O_RDONLY
+#endif /* !defined O_BINARY */
+
+#ifndef WILDABBR
+/*
+** Someone might make incorrect use of a time zone abbreviation:
+**     1.      They might reference tzname[0] before calling tzset (explicitly
+**             or implicitly).
+**     2.      They might reference tzname[1] before calling tzset (explicitly
+**             or implicitly).
+**     3.      They might reference tzname[1] after setting to a time zone
+**             in which Daylight Saving Time is never observed.
+**     4.      They might reference tzname[0] after setting to a time zone
+**             in which Standard Time is never observed.
+**     5.      They might reference tm.TM_ZONE after calling offtime.
+** What's best to do in the above cases is open to debate;
+** for now, we just set things up so that in any of the five cases
+** WILDABBR is used. Another possibility: initialize tzname[0] to the
+** string "tzname[0] used before set", and similarly for the other cases.
+** And another: initialize tzname[0] to "ERA", with an explanation in the
+** manual page of what this "time zone abbreviation" means (doing this so
+** that tzname[0] has the "normal" length of three characters).
+*/
+#define WILDABBR       "   "
+#endif /* !defined WILDABBR */
+
+static const char      wildabbr[] = WILDABBR;
+
+static char            gmt[] = "GMT";
+
+/*
+** The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
+** We default to US rules as of 1999-08-17.
+** POSIX 1003.1 section 8.1.1 says that the default DST rules are
+** implementation dependent; for historical reasons, US rules are a
+** common default.
+*/
+#ifndef TZDEFRULESTRING
+#define TZDEFRULESTRING ",M4.1.0,M10.5.0"
+#endif /* !defined TZDEFDST */
+
+struct ttinfo {                                /* time type information */
+       long            tt_gmtoff;      /* UTC offset in seconds */
+       int             tt_isdst;       /* used to set tm_isdst */
+       int             tt_abbrind;     /* abbreviation list index */
+       int             tt_ttisstd;     /* TRUE if transition is std time */
+       int             tt_ttisgmt;     /* TRUE if transition is UTC */
+};
+
+struct lsinfo {                                /* leap second information */
+       time_t          ls_trans;       /* transition time */
+       long            ls_corr;        /* correction to apply */
+};
+
+#define BIGGEST(a, b)  (((a) > (b)) ? (a) : (b))
+
+#ifdef TZNAME_MAX
+#define MY_TZNAME_MAX  TZNAME_MAX
+#endif /* defined TZNAME_MAX */
+#ifndef TZNAME_MAX
+#define MY_TZNAME_MAX  255
+#endif /* !defined TZNAME_MAX */
+
+struct __state {
+       int             leapcnt;
+       int             timecnt;
+       int             typecnt;
+       int             charcnt;
+       int             goback;
+       int             goahead;
+       time_t          ats[TZ_MAX_TIMES];
+       unsigned char   types[TZ_MAX_TIMES];
+       struct ttinfo   ttis[TZ_MAX_TYPES];
+       char            chars[/*CONSTCOND*/BIGGEST(BIGGEST(TZ_MAX_CHARS + 1, sizeof gmt),
+                               (2 * (MY_TZNAME_MAX + 1)))];
+       struct lsinfo   lsis[TZ_MAX_LEAPS];
+};
+
+struct rule {
+       int             r_type;         /* type of rule--see below */
+       int             r_day;          /* day number of rule */
+       int             r_week;         /* week number of rule */
+       int             r_mon;          /* month number of rule */
+       long            r_time;         /* transition time of rule */
+};
+
+#define JULIAN_DAY             0       /* Jn - Julian day */
+#define DAY_OF_YEAR            1       /* n - day of year */
+#define MONTH_NTH_DAY_OF_WEEK  2       /* Mm.n.d - month, week, day of week */
+
+typedef struct tm *(*subfun_t)(const timezone_t sp, const time_t *timep,
+                              long offset, struct tm *tmp);
+
+/*
+** Prototypes for static functions.
+*/
+
+static long            detzcode(const char * codep);
+static time_t          detzcode64(const char * codep);
+static int             differ_by_repeat(time_t t1, time_t t0);
+static const char *    getzname(const char * strp);
+static const char *    getqzname(const char * strp, const int delim);
+static const char *    getnum(const char * strp, int * nump, int min,
+                               int max);
+static const char *    getsecs(const char * strp, long * secsp);
+static const char *    getoffset(const char * strp, long * offsetp);
+static const char *    getrule(const char * strp, struct rule * rulep);
+static void            gmtload(timezone_t sp);
+static struct tm *     gmtsub(const timezone_t sp, const time_t *timep,
+                               long offset, struct tm * tmp);
+static struct tm *     localsub(const timezone_t sp, const time_t *timep,
+                               long offset, struct tm *tmp);
+static int             increment_overflow(int * number, int delta);
+static int             leaps_thru_end_of(int y);
+static int             long_increment_overflow(long * number, int delta);
+static int             long_normalize_overflow(long * tensptr,
+                               int * unitsptr, int base);
+static int             normalize_overflow(int * tensptr, int * unitsptr,
+                               int base);
+static void            settzname(void);
+static time_t          time1(const timezone_t sp, struct tm * const tmp,
+                               subfun_t funcp, long offset);
+static time_t          time2(const timezone_t sp, struct tm * const tmp,
+                               subfun_t funcp,
+                               const long offset, int *const okayp);
+static time_t          time2sub(const timezone_t sp, struct tm * consttmp,
+                               subfun_t funcp, const long offset,
+                               int *const okayp, const int do_norm_secs);
+static struct tm *     timesub(const timezone_t sp, const time_t * timep,
+                               long offset, struct tm * tmp);
+static int             tmcomp(const struct tm * atmp,
+                               const struct tm * btmp);
+static time_t          transtime(time_t janfirst, int year,
+                               const struct rule * rulep, long offset);
+static int             typesequiv(const timezone_t sp, int a, int b);
+static int             tzload(timezone_t sp, const char * name,
+                               int doextend);
+static int             tzparse(timezone_t sp, const char * name,
+                               int lastditch);
+static void            tzset_unlocked(void);
+static void            tzsetwall_unlocked(void);
+static long            leapcorr(const timezone_t sp, time_t * timep);
+
+static timezone_t lclptr;
+static timezone_t gmtptr;
+
+#ifndef TZ_STRLEN_MAX
+#define TZ_STRLEN_MAX 255
+#endif /* !defined TZ_STRLEN_MAX */
+
+static char            lcl_TZname[TZ_STRLEN_MAX + 1];
+static int             lcl_is_set;
+static int             gmt_is_set;
+
+#if !defined(__LIBC12_SOURCE__)
+
+__aconst char *                tzname[2] = {
+       (__aconst char *)__UNCONST(wildabbr),
+       (__aconst char *)__UNCONST(wildabbr)
+};
+
+#else
+
+extern __aconst char * tzname[2];
+
+#endif
+
+#ifdef _REENTRANT
+static rwlock_t lcl_lock = RWLOCK_INITIALIZER;
+#endif
+
+/*
+** Section 4.12.3 of X3.159-1989 requires that
+**     Except for the strftime function, these functions [asctime,
+**     ctime, gmtime, localtime] return values in one of two static
+**     objects: a broken-down time structure and an array of char.
+** Thanks to Paul Eggert for noting this.
+*/
+
+static struct tm       tm;
+
+#ifdef USG_COMPAT
+#if !defined(__LIBC12_SOURCE__)
+long                   timezone = 0;
+int                    daylight = 0;
+#else
+extern int             daylight;
+extern long            timezone __RENAME(__timezone13);
+#endif
+#endif /* defined USG_COMPAT */
+
+#ifdef ALTZONE
+time_t                 altzone = 0;
+#endif /* defined ALTZONE */
+
+static long
+detzcode(const char *const codep)
+{
+       long    result;
+       int     i;
+
+       result = (codep[0] & 0x80) ? ~0L : 0;
+       for (i = 0; i < 4; ++i)
+               result = (result << 8) | (codep[i] & 0xff);
+       return result;
+}
+
+static time_t
+detzcode64(const char *const codep)
+{
+       time_t  result;
+       int     i;
+
+       result = (codep[0] & 0x80) ? -1 : 0;
+       for (i = 0; i < 8; ++i)
+               result = result * 256 + (codep[i] & 0xff);
+       return result;
+}
+
+const char *
+tzgetname(const timezone_t sp, int isdst)
+{
+       int i;
+       for (i = 0; i < sp->timecnt; ++i) {
+               const struct ttinfo *const ttisp = &sp->ttis[sp->types[i]];
+
+               if (ttisp->tt_isdst == isdst)
+                       return &sp->chars[ttisp->tt_abbrind];
+       }
+       return NULL;
+}
+
+static void
+settzname_z(timezone_t sp)
+{
+       int                     i;
+
+       /*
+       ** Scrub the abbreviations.
+       ** First, replace bogus characters.
+       */
+       for (i = 0; i < sp->charcnt; ++i)
+               if (strchr(TZ_ABBR_CHAR_SET, sp->chars[i]) == NULL)
+                       sp->chars[i] = TZ_ABBR_ERR_CHAR;
+       /*
+       ** Second, truncate long abbreviations.
+       */
+       for (i = 0; i < sp->typecnt; ++i) {
+               const struct ttinfo * const     ttisp = &sp->ttis[i];
+               char *                          cp = &sp->chars[ttisp->tt_abbrind];
+
+               if (strlen(cp) > TZ_ABBR_MAX_LEN &&
+                       strcmp(cp, GRANDPARENTED) != 0)
+                               *(cp + TZ_ABBR_MAX_LEN) = '\0';
+       }
+}
+
+static void
+settzname(void)
+{
+       timezone_t const        sp = lclptr;
+       int                     i;
+
+       tzname[0] = (__aconst char *)__UNCONST(wildabbr);
+       tzname[1] = (__aconst char *)__UNCONST(wildabbr);
+#ifdef USG_COMPAT
+       daylight = 0;
+       timezone = 0;
+#endif /* defined USG_COMPAT */
+#ifdef ALTZONE
+       altzone = 0;
+#endif /* defined ALTZONE */
+       if (sp == NULL) {
+               tzname[0] = tzname[1] = (__aconst char *)__UNCONST(gmt);
+               return;
+       }
+       for (i = 0; i < sp->typecnt; ++i) {
+               const struct ttinfo * const     ttisp = &sp->ttis[i];
+
+               tzname[ttisp->tt_isdst] =
+                       &sp->chars[ttisp->tt_abbrind];
+#ifdef USG_COMPAT
+               if (ttisp->tt_isdst)
+                       daylight = 1;
+               if (i == 0 || !ttisp->tt_isdst)
+                       timezone = -(ttisp->tt_gmtoff);
+#endif /* defined USG_COMPAT */
+#ifdef ALTZONE
+               if (i == 0 || ttisp->tt_isdst)
+                       altzone = -(ttisp->tt_gmtoff);
+#endif /* defined ALTZONE */
+       }
+       /*
+       ** And to get the latest zone names into tzname. . .
+       */
+       for (i = 0; i < sp->timecnt; ++i) {
+               register const struct ttinfo * const    ttisp =
+                                                       &sp->ttis[
+                                                               sp->types[i]];
+
+               tzname[ttisp->tt_isdst] =
+                       &sp->chars[ttisp->tt_abbrind];
+       }
+       settzname_z(sp);
+}
+
+static int
+differ_by_repeat(const time_t t1, const time_t t0)
+{
+/* CONSTCOND */
+       if (TYPE_INTEGRAL(time_t) &&
+               TYPE_BIT(time_t) - TYPE_SIGNED(time_t) < SECSPERREPEAT_BITS)
+                       return 0;
+       return (int_fast64_t)t1 - (int_fast64_t)t0 == SECSPERREPEAT;
+}
+
+static int
+tzload(timezone_t sp, const char *name, const int doextend)
+{
+       const char *            p;
+       int                     i;
+       int                     fid;
+       int                     stored;
+       int                     nread;
+       union {
+               struct tzhead   tzhead;
+               char            buf[2 * sizeof(struct tzhead) +
+                                       2 * sizeof *sp +
+                                       4 * TZ_MAX_TIMES];
+       } u;
+
+       sp->goback = sp->goahead = FALSE;
+       if (name == NULL && (name = TZDEFAULT) == NULL)
+               return -1;
+       {
+               int     doaccess;
+               /*
+               ** Section 4.9.1 of the C standard says that
+               ** "FILENAME_MAX expands to an integral constant expression
+               ** that is the size needed for an array of char large enough
+               ** to hold the longest file name string that the implementation
+               ** guarantees can be opened."
+               */
+               char            fullname[FILENAME_MAX + 1];
+
+               if (name[0] == ':')
+                       ++name;
+               doaccess = name[0] == '/';
+               if (!doaccess) {
+                       if ((p = TZDIR) == NULL)
+                               return -1;
+                       if ((strlen(p) + strlen(name) + 1) >= sizeof fullname)
+                               return -1;
+                       (void) strcpy(fullname, p);     /* XXX strcpy is safe */
+                       (void) strcat(fullname, "/");   /* XXX strcat is safe */
+                       (void) strcat(fullname, name);  /* XXX strcat is safe */
+                       /*
+                       ** Set doaccess if '.' (as in "../") shows up in name.
+                       */
+                       if (strchr(name, '.') != NULL)
+                               doaccess = TRUE;
+                       name = fullname;
+               }
+               if (doaccess && access(name, R_OK) != 0)
+                       return -1;
+               /*
+                * XXX potential security problem here if user of a set-id
+                * program has set TZ (which is passed in as name) here,
+                * and uses a race condition trick to defeat the access(2)
+                * above.
+                */
+               if ((fid = open(name, OPEN_MODE)) == -1)
+                       return -1;
+       }
+       nread = read(fid, u.buf, sizeof u.buf);
+       if (close(fid) < 0 || nread <= 0)
+               return -1;
+       for (stored = 4; stored <= 8; stored *= 2) {
+               int             ttisstdcnt;
+               int             ttisgmtcnt;
+
+               ttisstdcnt = (int) detzcode(u.tzhead.tzh_ttisstdcnt);
+               ttisgmtcnt = (int) detzcode(u.tzhead.tzh_ttisgmtcnt);
+               sp->leapcnt = (int) detzcode(u.tzhead.tzh_leapcnt);
+               sp->timecnt = (int) detzcode(u.tzhead.tzh_timecnt);
+               sp->typecnt = (int) detzcode(u.tzhead.tzh_typecnt);
+               sp->charcnt = (int) detzcode(u.tzhead.tzh_charcnt);
+               p = u.tzhead.tzh_charcnt + sizeof u.tzhead.tzh_charcnt;
+               if (sp->leapcnt < 0 || sp->leapcnt > TZ_MAX_LEAPS ||
+                       sp->typecnt <= 0 || sp->typecnt > TZ_MAX_TYPES ||
+                       sp->timecnt < 0 || sp->timecnt > TZ_MAX_TIMES ||
+                       sp->charcnt < 0 || sp->charcnt > TZ_MAX_CHARS ||
+                       (ttisstdcnt != sp->typecnt && ttisstdcnt != 0) ||
+                       (ttisgmtcnt != sp->typecnt && ttisgmtcnt != 0))
+                               return -1;
+               if (nread - (p - u.buf) <
+                       sp->timecnt * stored +          /* ats */
+                       sp->timecnt +                   /* types */
+                       sp->typecnt * 6 +               /* ttinfos */
+                       sp->charcnt +                   /* chars */
+                       sp->leapcnt * (stored + 4) +    /* lsinfos */
+                       ttisstdcnt +                    /* ttisstds */
+                       ttisgmtcnt)                     /* ttisgmts */
+                               return -1;
+               for (i = 0; i < sp->timecnt; ++i) {
+                       sp->ats[i] = (stored == 4) ?
+                               detzcode(p) : detzcode64(p);
+                       p += stored;
+               }
+               for (i = 0; i < sp->timecnt; ++i) {
+                       sp->types[i] = (unsigned char) *p++;
+                       if (sp->types[i] >= sp->typecnt)
+                               return -1;
+               }
+               for (i = 0; i < sp->typecnt; ++i) {
+                       struct ttinfo * ttisp;
+
+                       ttisp = &sp->ttis[i];
+                       ttisp->tt_gmtoff = detzcode(p);
+                       p += 4;
+                       ttisp->tt_isdst = (unsigned char) *p++;
+                       if (ttisp->tt_isdst != 0 && ttisp->tt_isdst != 1)
+                               return -1;
+                       ttisp->tt_abbrind = (unsigned char) *p++;
+                       if (ttisp->tt_abbrind < 0 ||
+                               ttisp->tt_abbrind > sp->charcnt)
+                                       return -1;
+               }
+               for (i = 0; i < sp->charcnt; ++i)
+                       sp->chars[i] = *p++;
+               sp->chars[i] = '\0';    /* ensure '\0' at end */
+               for (i = 0; i < sp->leapcnt; ++i) {
+                       struct lsinfo * lsisp;
+
+                       lsisp = &sp->lsis[i];
+                       lsisp->ls_trans = (stored == 4) ?
+                               detzcode(p) : detzcode64(p);
+                       p += stored;
+                       lsisp->ls_corr = detzcode(p);
+                       p += 4;
+               }
+               for (i = 0; i < sp->typecnt; ++i) {
+                       struct ttinfo * ttisp;
+
+                       ttisp = &sp->ttis[i];
+                       if (ttisstdcnt == 0)
+                               ttisp->tt_ttisstd = FALSE;
+                       else {
+                               ttisp->tt_ttisstd = *p++;
+                               if (ttisp->tt_ttisstd != TRUE &&
+                                       ttisp->tt_ttisstd != FALSE)
+                                               return -1;
+                       }
+               }
+               for (i = 0; i < sp->typecnt; ++i) {
+                       struct ttinfo * ttisp;
+
+                       ttisp = &sp->ttis[i];
+                       if (ttisgmtcnt == 0)
+                               ttisp->tt_ttisgmt = FALSE;
+                       else {
+                               ttisp->tt_ttisgmt = *p++;
+                               if (ttisp->tt_ttisgmt != TRUE &&
+                                       ttisp->tt_ttisgmt != FALSE)
+                                               return -1;
+                       }
+               }
+               /*
+               ** Out-of-sort ats should mean we're running on a
+               ** signed time_t system but using a data file with
+               ** unsigned values (or vice versa).
+               */
+               for (i = 0; i < sp->timecnt - 2; ++i)
+                       if (sp->ats[i] > sp->ats[i + 1]) {
+                               ++i;
+/* CONSTCOND */
+                               if (TYPE_SIGNED(time_t)) {
+                                       /*
+                                       ** Ignore the end (easy).
+                                       */
+                                       sp->timecnt = i;
+                               } else {
+                                       /*
+                                       ** Ignore the beginning (harder).
+                                       */
+                                       int     j;
+
+                                       for (j = 0; j + i < sp->timecnt; ++j) {
+                                               sp->ats[j] = sp->ats[j + i];
+                                               sp->types[j] = sp->types[j + i];
+                                       }
+                                       sp->timecnt = j;
+                               }
+                               break;
+                       }
+               /*
+               ** If this is an old file, we're done.
+               */
+               if (u.tzhead.tzh_version[0] == '\0')
+                       break;
+               nread -= p - u.buf;
+               for (i = 0; i < nread; ++i)
+                       u.buf[i] = p[i];
+               /*
+               ** If this is a narrow integer time_t system, we're done.
+               */
+               if (stored >= (int) sizeof(time_t)
+/* CONSTCOND */
+                               && TYPE_INTEGRAL(time_t))
+                       break;
+       }
+       if (doextend && nread > 2 &&
+               u.buf[0] == '\n' && u.buf[nread - 1] == '\n' &&
+               sp->typecnt + 2 <= TZ_MAX_TYPES) {
+                       struct __state ts;
+                       int     result;
+
+                       u.buf[nread - 1] = '\0';
+                       result = tzparse(&ts, &u.buf[1], FALSE);
+                       if (result == 0 && ts.typecnt == 2 &&
+                               sp->charcnt + ts.charcnt <= TZ_MAX_CHARS) {
+                                       for (i = 0; i < 2; ++i)
+                                               ts.ttis[i].tt_abbrind +=
+                                                       sp->charcnt;
+                                       for (i = 0; i < ts.charcnt; ++i)
+                                               sp->chars[sp->charcnt++] =
+                                                       ts.chars[i];
+                                       i = 0;
+                                       while (i < ts.timecnt &&
+                                               ts.ats[i] <=
+                                               sp->ats[sp->timecnt - 1])
+                                                       ++i;
+                                       while (i < ts.timecnt &&
+                                           sp->timecnt < TZ_MAX_TIMES) {
+                                               sp->ats[sp->timecnt] =
+                                                       ts.ats[i];
+                                               sp->types[sp->timecnt] =
+                                                       sp->typecnt +
+                                                       ts.types[i];
+                                               ++sp->timecnt;
+                                               ++i;
+                                       }
+                                       sp->ttis[sp->typecnt++] = ts.ttis[0];
+                                       sp->ttis[sp->typecnt++] = ts.ttis[1];
+                       }
+       }
+       if (sp->timecnt > 1) {
+               for (i = 1; i < sp->timecnt; ++i)
+                       if (typesequiv(sp, sp->types[i], sp->types[0]) &&
+                               differ_by_repeat(sp->ats[i], sp->ats[0])) {
+                                       sp->goback = TRUE;
+                                       break;
+                               }
+               for (i = sp->timecnt - 2; i >= 0; --i)
+                       if (typesequiv(sp, sp->types[sp->timecnt - 1],
+                               sp->types[i]) &&
+                               differ_by_repeat(sp->ats[sp->timecnt - 1],
+                               sp->ats[i])) {
+                                       sp->goahead = TRUE;
+                                       break;
+               }
+       }
+       return 0;
+}
+
+static int
+typesequiv(const timezone_t sp, const int a, const int b)
+{
+       int     result;
+
+       if (sp == NULL ||
+               a < 0 || a >= sp->typecnt ||
+               b < 0 || b >= sp->typecnt)
+                       result = FALSE;
+       else {
+               const struct ttinfo *   ap = &sp->ttis[a];
+               const struct ttinfo *   bp = &sp->ttis[b];
+               result = ap->tt_gmtoff == bp->tt_gmtoff &&
+                       ap->tt_isdst == bp->tt_isdst &&
+                       ap->tt_ttisstd == bp->tt_ttisstd &&
+                       ap->tt_ttisgmt == bp->tt_ttisgmt &&
+                       strcmp(&sp->chars[ap->tt_abbrind],
+                       &sp->chars[bp->tt_abbrind]) == 0;
+       }
+       return result;
+}
+
+static const int       mon_lengths[2][MONSPERYEAR] = {
+       { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
+       { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
+};
+
+static const int       year_lengths[2] = {
+       DAYSPERNYEAR, DAYSPERLYEAR
+};
+
+/*
+** Given a pointer into a time zone string, scan until a character that is not
+** a valid character in a zone name is found. Return a pointer to that
+** character.
+*/
+
+static const char *
+getzname(strp)
+const char *   strp;
+{
+       char    c;
+
+       while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
+               c != '+')
+                       ++strp;
+       return strp;
+}
+
+/*
+** Given a pointer into an extended time zone string, scan until the ending
+** delimiter of the zone name is located. Return a pointer to the delimiter.
+**
+** As with getzname above, the legal character set is actually quite
+** restricted, with other characters producing undefined results.
+** We don't do any checking here; checking is done later in common-case code.
+*/
+
+static const char *
+getqzname(const char *strp, const int delim)
+{
+       int     c;
+
+       while ((c = *strp) != '\0' && c != delim)
+               ++strp;
+       return strp;
+}
+
+/*
+** Given a pointer into a time zone string, extract a number from that string.
+** Check that the number is within a specified range; if it is not, return
+** NULL.
+** Otherwise, return a pointer to the first character not part of the number.
+*/
+
+static const char *
+getnum(strp, nump, min, max)
+const char *   strp;
+int * const            nump;
+const int              min;
+const int              max;
+{
+       char    c;
+       int     num;
+
+       if (strp == NULL || !is_digit(c = *strp)) {
+               errno = EINVAL;
+               return NULL;
+       }
+       num = 0;
+       do {
+               num = num * 10 + (c - '0');
+               if (num > max) {
+                       errno = EOVERFLOW;
+                       return NULL;    /* illegal value */
+               }
+               c = *++strp;
+       } while (is_digit(c));
+       if (num < min) {
+               errno = EINVAL;
+               return NULL;            /* illegal value */
+       }
+       *nump = num;
+       return strp;
+}
+
+/*
+** Given a pointer into a time zone string, extract a number of seconds,
+** in hh[:mm[:ss]] form, from the string.
+** If any error occurs, return NULL.
+** Otherwise, return a pointer to the first character not part of the number
+** of seconds.
+*/
+
+static const char *
+getsecs(const char *strp, long *const secsp)
+{
+       int     num;
+
+       /*
+       ** `HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
+       ** "M10.4.6/26", which does not conform to Posix,
+       ** but which specifies the equivalent of
+       ** ``02:00 on the first Sunday on or after 23 Oct''.
+       */
+       strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
+       if (strp == NULL)
+               return NULL;
+       *secsp = num * (long) SECSPERHOUR;
+       if (*strp == ':') {
+               ++strp;
+               strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
+               if (strp == NULL)
+                       return NULL;
+               *secsp += num * SECSPERMIN;
+               if (*strp == ':') {
+                       ++strp;
+                       /* `SECSPERMIN' allows for leap seconds. */
+                       strp = getnum(strp, &num, 0, SECSPERMIN);
+                       if (strp == NULL)
+                               return NULL;
+                       *secsp += num;
+               }
+       }
+       return strp;
+}
+
+/*
+** Given a pointer into a time zone string, extract an offset, in
+** [+-]hh[:mm[:ss]] form, from the string.
+** If any error occurs, return NULL.
+** Otherwise, return a pointer to the first character not part of the time.
+*/
+
+static const char *
+getoffset(const char *strp, long *const offsetp)
+{
+       int     neg = 0;
+
+       if (*strp == '-') {
+               neg = 1;
+               ++strp;
+       } else if (*strp == '+')
+               ++strp;
+       strp = getsecs(strp, offsetp);
+       if (strp == NULL)
+               return NULL;            /* illegal time */
+       if (neg)
+               *offsetp = -*offsetp;
+       return strp;
+}
+
+/*
+** Given a pointer into a time zone string, extract a rule in the form
+** date[/time]. See POSIX section 8 for the format of "date" and "time".
+** If a valid rule is not found, return NULL.
+** Otherwise, return a pointer to the first character not part of the rule.
+*/
+
+static const char *
+getrule(const char *strp, struct rule *const rulep)
+{
+       if (*strp == 'J') {
+               /*
+               ** Julian day.
+               */
+               rulep->r_type = JULIAN_DAY;
+               ++strp;
+               strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
+       } else if (*strp == 'M') {
+               /*
+               ** Month, week, day.
+               */
+               rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
+               ++strp;
+               strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
+               if (strp == NULL)
+                       return NULL;
+               if (*strp++ != '.')
+                       return NULL;
+               strp = getnum(strp, &rulep->r_week, 1, 5);
+               if (strp == NULL)
+                       return NULL;
+               if (*strp++ != '.')
+                       return NULL;
+               strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
+       } else if (is_digit(*strp)) {
+               /*
+               ** Day of year.
+               */
+               rulep->r_type = DAY_OF_YEAR;
+               strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
+       } else  return NULL;            /* invalid format */
+       if (strp == NULL)
+               return NULL;
+       if (*strp == '/') {
+               /*
+               ** Time specified.
+               */
+               ++strp;
+               strp = getsecs(strp, &rulep->r_time);
+       } else  rulep->r_time = 2 * SECSPERHOUR;        /* default = 2:00:00 */
+       return strp;
+}
+
+/*
+** Given the Epoch-relative time of January 1, 00:00:00 UTC, in a year, the
+** year, a rule, and the offset from UTC at the time that rule takes effect,
+** calculate the Epoch-relative time that rule takes effect.
+*/
+
+static time_t
+transtime(const time_t janfirst, const int year, const struct rule *const rulep,
+    const long offset)
+{
+       int     leapyear;
+       time_t  value;
+       int     i;
+       int             d, m1, yy0, yy1, yy2, dow;
+
+       INITIALIZE(value);
+       leapyear = isleap(year);
+       switch (rulep->r_type) {
+
+       case JULIAN_DAY:
+               /*
+               ** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
+               ** years.
+               ** In non-leap years, or if the day number is 59 or less, just
+               ** add SECSPERDAY times the day number-1 to the time of
+               ** January 1, midnight, to get the day.
+               */
+               value = janfirst + (rulep->r_day - 1) * SECSPERDAY;
+               if (leapyear && rulep->r_day >= 60)
+                       value += SECSPERDAY;
+               break;
+
+       case DAY_OF_YEAR:
+               /*
+               ** n - day of year.
+               ** Just add SECSPERDAY times the day number to the time of
+               ** January 1, midnight, to get the day.
+               */
+               value = janfirst + rulep->r_day * SECSPERDAY;
+               break;
+
+       case MONTH_NTH_DAY_OF_WEEK:
+               /*
+               ** Mm.n.d - nth "dth day" of month m.
+               */
+               value = janfirst;
+               for (i = 0; i < rulep->r_mon - 1; ++i)
+                       value += mon_lengths[leapyear][i] * SECSPERDAY;
+
+               /*
+               ** Use Zeller's Congruence to get day-of-week of first day of
+               ** month.
+               */
+               m1 = (rulep->r_mon + 9) % 12 + 1;
+               yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
+               yy1 = yy0 / 100;
+               yy2 = yy0 % 100;
+               dow = ((26 * m1 - 2) / 10 +
+                       1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
+               if (dow < 0)
+                       dow += DAYSPERWEEK;
+
+               /*
+               ** "dow" is the day-of-week of the first day of the month. Get
+               ** the day-of-month (zero-origin) of the first "dow" day of the
+               ** month.
+               */
+               d = rulep->r_day - dow;
+               if (d < 0)
+                       d += DAYSPERWEEK;
+               for (i = 1; i < rulep->r_week; ++i) {
+                       if (d + DAYSPERWEEK >=
+                               mon_lengths[leapyear][rulep->r_mon - 1])
+                                       break;
+                       d += DAYSPERWEEK;
+               }
+
+               /*
+               ** "d" is the day-of-month (zero-origin) of the day we want.
+               */
+               value += d * SECSPERDAY;
+               break;
+       }
+
+       /*
+       ** "value" is the Epoch-relative time of 00:00:00 UTC on the day in
+       ** question. To get the Epoch-relative time of the specified local
+       ** time on that day, add the transition time and the current offset
+       ** from UTC.
+       */
+       return value + rulep->r_time + offset;
+}
+
+/*
+** Given a POSIX section 8-style TZ string, fill in the rule tables as
+** appropriate.
+*/
+
+static int
+tzparse(timezone_t sp, const char *name, const int lastditch)
+{
+       const char *                    stdname;
+       const char *                    dstname;
+       size_t                          stdlen;
+       size_t                          dstlen;
+       long                            stdoffset;
+       long                            dstoffset;
+       time_t *                atp;
+       unsigned char * typep;
+       char *                  cp;
+       int                     load_result;
+
+       INITIALIZE(dstname);
+       stdname = name;
+       if (lastditch) {
+               stdlen = strlen(name);  /* length of standard zone name */
+               name += stdlen;
+               if (stdlen >= sizeof sp->chars)
+                       stdlen = (sizeof sp->chars) - 1;
+               stdoffset = 0;
+       } else {
+               if (*name == '<') {
+                       name++;
+                       stdname = name;
+                       name = getqzname(name, '>');
+                       if (*name != '>')
+                               return (-1);
+                       stdlen = name - stdname;
+                       name++;
+               } else {
+                       name = getzname(name);
+                       stdlen = name - stdname;
+               }
+               if (*name == '\0')
+                       return -1;
+               name = getoffset(name, &stdoffset);
+               if (name == NULL)
+                       return -1;
+       }
+       load_result = tzload(sp, TZDEFRULES, FALSE);
+       if (load_result != 0)
+               sp->leapcnt = 0;                /* so, we're off a little */
+       if (*name != '\0') {
+               if (*name == '<') {
+                       dstname = ++name;
+                       name = getqzname(name, '>');
+                       if (*name != '>')
+                               return -1;
+                       dstlen = name - dstname;
+                       name++;
+               } else {
+                       dstname = name;
+                       name = getzname(name);
+                       dstlen = name - dstname; /* length of DST zone name */
+               }
+               if (*name != '\0' && *name != ',' && *name != ';') {
+                       name = getoffset(name, &dstoffset);
+                       if (name == NULL)
+                               return -1;
+               } else  dstoffset = stdoffset - SECSPERHOUR;
+               if (*name == '\0' && load_result != 0)
+                       name = TZDEFRULESTRING;
+               if (*name == ',' || *name == ';') {
+                       struct rule     start;
+                       struct rule     end;
+                       int     year;
+                       time_t  janfirst;
+                       time_t          starttime;
+                       time_t          endtime;
+
+                       ++name;
+                       if ((name = getrule(name, &start)) == NULL)
+                               return -1;
+                       if (*name++ != ',')
+                               return -1;
+                       if ((name = getrule(name, &end)) == NULL)
+                               return -1;
+                       if (*name != '\0')
+                               return -1;
+                       sp->typecnt = 2;        /* standard time and DST */
+                       /*
+                       ** Two transitions per year, from EPOCH_YEAR forward.
+                       */
+                       sp->ttis[0].tt_gmtoff = -dstoffset;
+                       sp->ttis[0].tt_isdst = 1;
+                       sp->ttis[0].tt_abbrind = stdlen + 1;
+                       sp->ttis[1].tt_gmtoff = -stdoffset;
+                       sp->ttis[1].tt_isdst = 0;
+                       sp->ttis[1].tt_abbrind = 0;
+                       atp = sp->ats;
+                       typep = sp->types;
+                       janfirst = 0;
+                       sp->timecnt = 0;
+                       for (year = EPOCH_YEAR;
+                           sp->timecnt + 2 <= TZ_MAX_TIMES;
+                           ++year) {
+                               time_t  newfirst;
+
+                               starttime = transtime(janfirst, year, &start,
+                                       stdoffset);
+                               endtime = transtime(janfirst, year, &end,
+                                       dstoffset);
+                               if (starttime > endtime) {
+                                       *atp++ = endtime;
+                                       *typep++ = 1;   /* DST ends */
+                                       *atp++ = starttime;
+                                       *typep++ = 0;   /* DST begins */
+                               } else {
+                                       *atp++ = starttime;
+                                       *typep++ = 0;   /* DST begins */
+                                       *atp++ = endtime;
+                                       *typep++ = 1;   /* DST ends */
+                               }
+                               sp->timecnt += 2;
+                               newfirst = janfirst;
+                               newfirst += year_lengths[isleap(year)] *
+                                       SECSPERDAY;
+                               if (newfirst <= janfirst)
+                                       break;
+                               janfirst = newfirst;
+                       }
+               } else {
+                       long    theirstdoffset;
+                       long    theirdstoffset;
+                       long    theiroffset;
+                       int     isdst;
+                       int     i;
+                       int     j;
+
+                       if (*name != '\0')
+                               return -1;
+                       /*
+                       ** Initial values of theirstdoffset
+                       */
+                       theirstdoffset = 0;
+                       for (i = 0; i < sp->timecnt; ++i) {
+                               j = sp->types[i];
+                               if (!sp->ttis[j].tt_isdst) {
+                                       theirstdoffset =
+                                               -sp->ttis[j].tt_gmtoff;
+                                       break;
+                               }
+                       }
+                       theirdstoffset = 0;
+                       for (i = 0; i < sp->timecnt; ++i) {
+                               j = sp->types[i];
+                               if (sp->ttis[j].tt_isdst) {
+                                       theirdstoffset =
+                                               -sp->ttis[j].tt_gmtoff;
+                                       break;
+                               }
+                       }
+                       /*
+                       ** Initially we're assumed to be in standard time.
+                       */
+                       isdst = FALSE;
+                       theiroffset = theirstdoffset;
+                       /*
+                       ** Now juggle transition times and types
+                       ** tracking offsets as you do.
+                       */
+                       for (i = 0; i < sp->timecnt; ++i) {
+                               j = sp->types[i];
+                               sp->types[i] = sp->ttis[j].tt_isdst;
+                               if (sp->ttis[j].tt_ttisgmt) {
+                                       /* No adjustment to transition time */
+                               } else {
+                                       /*
+                                       ** If summer time is in effect, and the
+                                       ** transition time was not specified as
+                                       ** standard time, add the summer time
+                                       ** offset to the transition time;
+                                       ** otherwise, add the standard time
+                                       ** offset to the transition time.
+                                       */
+                                       /*
+                                       ** Transitions from DST to DDST
+                                       ** will effectively disappear since
+                                       ** POSIX provides for only one DST
+                                       ** offset.
+                                       */
+                                       if (isdst && !sp->ttis[j].tt_ttisstd) {
+                                               sp->ats[i] += dstoffset -
+                                                       theirdstoffset;
+                                       } else {
+                                               sp->ats[i] += stdoffset -
+                                                       theirstdoffset;
+                                       }
+                               }
+                               theiroffset = -sp->ttis[j].tt_gmtoff;
+                               if (!sp->ttis[j].tt_isdst)
+                                       theirstdoffset = theiroffset;
+                               else    theirdstoffset = theiroffset;
+                       }
+                       /*
+                       ** Finally, fill in ttis.
+                       ** ttisstd and ttisgmt need not be handled.
+                       */
+                       sp->ttis[0].tt_gmtoff = -stdoffset;
+                       sp->ttis[0].tt_isdst = FALSE;
+                       sp->ttis[0].tt_abbrind = 0;
+                       sp->ttis[1].tt_gmtoff = -dstoffset;
+                       sp->ttis[1].tt_isdst = TRUE;
+                       sp->ttis[1].tt_abbrind = stdlen + 1;
+                       sp->typecnt = 2;
+               }
+       } else {
+               dstlen = 0;
+               sp->typecnt = 1;                /* only standard time */
+               sp->timecnt = 0;
+               sp->ttis[0].tt_gmtoff = -stdoffset;
+               sp->ttis[0].tt_isdst = 0;
+               sp->ttis[0].tt_abbrind = 0;
+       }
+       sp->charcnt = stdlen + 1;
+       if (dstlen != 0)
+               sp->charcnt += dstlen + 1;
+       if ((size_t) sp->charcnt > sizeof sp->chars)
+               return -1;
+       cp = sp->chars;
+       (void) strncpy(cp, stdname, stdlen);
+       cp += stdlen;
+       *cp++ = '\0';
+       if (dstlen != 0) {
+               (void) strncpy(cp, dstname, dstlen);
+               *(cp + dstlen) = '\0';
+       }
+       return 0;
+}
+
+static void
+gmtload(timezone_t sp)
+{
+       if (tzload(sp, gmt, TRUE) != 0)
+               (void) tzparse(sp, gmt, TRUE);
+}
+
+timezone_t
+tzalloc(const char *name)
+{
+       timezone_t sp = calloc(1, sizeof *sp);
+       if (sp == NULL)
+               return NULL;
+       if (tzload(sp, name, TRUE) != 0) {
+               free(sp);
+               return NULL;
+       }
+       settzname_z(sp);
+       return sp;
+}
+
+void
+tzfree(const timezone_t sp)
+{
+       free(sp);
+}
+
+static void
+tzsetwall_unlocked(void)
+{
+       if (lcl_is_set < 0)
+               return;
+       lcl_is_set = -1;
+
+       if (lclptr == NULL) {
+               int saveerrno = errno;
+               lclptr = calloc(1, sizeof *lclptr);
+               errno = saveerrno;
+               if (lclptr == NULL) {
+                       settzname();    /* all we can do */
+                       return;
+               }
+       }
+       if (tzload(lclptr, NULL, TRUE) != 0)
+               gmtload(lclptr);
+       settzname();
+}
+
+#ifndef STD_INSPIRED
+/*
+** A non-static declaration of tzsetwall in a system header file
+** may cause a warning about this upcoming static declaration...
+*/
+static
+#endif /* !defined STD_INSPIRED */
+void
+tzsetwall(void)
+{
+       rwlock_wrlock(&lcl_lock);
+       tzsetwall_unlocked();
+       rwlock_unlock(&lcl_lock);
+}
+
+#ifndef STD_INSPIRED
+/*
+** A non-static declaration of tzsetwall in a system header file
+** may cause a warning about this upcoming static declaration...
+*/
+static
+#endif /* !defined STD_INSPIRED */
+void
+tzset_unlocked(void)
+{
+       const char *    name;
+       int saveerrno;
+
+       saveerrno = errno;
+       name = getenv("TZ");
+       errno = saveerrno;
+       if (name == NULL) {
+               tzsetwall_unlocked();
+               return;
+       }
+
+       if (lcl_is_set > 0 && strcmp(lcl_TZname, name) == 0)
+               return;
+       lcl_is_set = strlen(name) < sizeof lcl_TZname;
+       if (lcl_is_set)
+               (void)strlcpy(lcl_TZname, name, sizeof(lcl_TZname));
+
+       if (lclptr == NULL) {
+               saveerrno = errno;
+               lclptr = calloc(1, sizeof *lclptr);
+               errno = saveerrno;
+               if (lclptr == NULL) {
+                       settzname();    /* all we can do */
+                       return;
+               }
+       }
+       if (*name == '\0') {
+               /*
+               ** User wants it fast rather than right.
+               */
+               lclptr->leapcnt = 0;            /* so, we're off a little */
+               lclptr->timecnt = 0;
+               lclptr->typecnt = 0;
+               lclptr->ttis[0].tt_isdst = 0;
+               lclptr->ttis[0].tt_gmtoff = 0;
+               lclptr->ttis[0].tt_abbrind = 0;
+               (void) strlcpy(lclptr->chars, gmt, sizeof(lclptr->chars));
+       } else if (tzload(lclptr, name, TRUE) != 0)
+               if (name[0] == ':' || tzparse(lclptr, name, FALSE) != 0)
+                       (void) gmtload(lclptr);
+       settzname();
+}
+
+void
+tzset(void)
+{
+       rwlock_wrlock(&lcl_lock);
+       tzset_unlocked();
+       rwlock_unlock(&lcl_lock);
+}
+
+/*
+** The easy way to behave "as if no library function calls" localtime
+** is to not call it--so we drop its guts into "localsub", which can be
+** freely called. (And no, the PANS doesn't require the above behavior--
+** but it *is* desirable.)
+**
+** The unused offset argument is for the benefit of mktime variants.
+*/
+
+/*ARGSUSED*/
+static struct tm *
+localsub(const timezone_t sp, const time_t * const timep, const long offset,
+    struct tm *const tmp)
+{
+       const struct ttinfo *   ttisp;
+       int                     i;
+       struct tm *             result;
+       const time_t                    t = *timep;
+
+       if ((sp->goback && t < sp->ats[0]) ||
+               (sp->goahead && t > sp->ats[sp->timecnt - 1])) {
+                       time_t                  newt = t;
+                       time_t          seconds;
+                       time_t          tcycles;
+                       int_fast64_t    icycles;
+
+                       if (t < sp->ats[0])
+                               seconds = sp->ats[0] - t;
+                       else    seconds = t - sp->ats[sp->timecnt - 1];
+                       --seconds;
+                       tcycles = seconds / YEARSPERREPEAT / AVGSECSPERYEAR;
+                       ++tcycles;
+                       icycles = tcycles;
+                       if (tcycles - icycles >= 1 || icycles - tcycles >= 1)
+                               return NULL;
+                       seconds = (time_t) icycles;
+                       seconds *= YEARSPERREPEAT;
+                       seconds *= AVGSECSPERYEAR;
+                       if (t < sp->ats[0])
+                               newt += seconds;
+                       else    newt -= seconds;
+                       if (newt < sp->ats[0] ||
+                               newt > sp->ats[sp->timecnt - 1])
+                                       return NULL;    /* "cannot happen" */
+                       result = localsub(sp, &newt, offset, tmp);
+                       if (result == tmp) {
+                               time_t  newy;
+
+                               newy = tmp->tm_year;
+                               if (t < sp->ats[0])
+                                       newy -= (time_t)icycles * YEARSPERREPEAT;
+                               else    newy += (time_t)icycles * YEARSPERREPEAT;
+                               tmp->tm_year = (int)newy;
+                               if (tmp->tm_year != newy)
+                                       return NULL;
+                       }
+                       return result;
+       }
+       if (sp->timecnt == 0 || t < sp->ats[0]) {
+               i = 0;
+               while (sp->ttis[i].tt_isdst)
+                       if (++i >= sp->typecnt) {
+                               i = 0;
+                               break;
+                       }
+       } else {
+               int     lo = 1;
+               int     hi = sp->timecnt;
+
+               while (lo < hi) {
+                       int     mid = (lo + hi) / 2;
+
+                       if (t < sp->ats[mid])
+                               hi = mid;
+                       else    lo = mid + 1;
+               }
+               i = (int) sp->types[lo - 1];
+       }
+       ttisp = &sp->ttis[i];
+       /*
+       ** To get (wrong) behavior that's compatible with System V Release 2.0
+       ** you'd replace the statement below with
+       **      t += ttisp->tt_gmtoff;
+       **      timesub(&t, 0L, sp, tmp);
+       */
+       result = timesub(sp, &t, ttisp->tt_gmtoff, tmp);
+       tmp->tm_isdst = ttisp->tt_isdst;
+       tzname[tmp->tm_isdst] = &sp->chars[ttisp->tt_abbrind];
+#ifdef TM_ZONE
+       tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
+#endif /* defined TM_ZONE */
+       return result;
+}
+
+/*
+** Re-entrant version of localtime.
+*/
+
+struct tm *
+localtime_r(const time_t * __restrict timep, struct tm *tmp)
+{
+       rwlock_rdlock(&lcl_lock);
+       tzset_unlocked();
+       tmp = localtime_rz(lclptr, timep, tmp);
+       rwlock_unlock(&lcl_lock);
+       return tmp;
+}
+
+struct tm *
+localtime(const time_t *const timep)
+{
+       return localtime_r(timep, &tm);
+}
+
+struct tm *
+localtime_rz(const timezone_t sp, const time_t * __restrict timep, struct tm *tmp)
+{
+       if (sp == NULL)
+               tmp = gmtsub(NULL, timep, 0L, tmp);
+       else
+               tmp = localsub(sp, timep, 0L, tmp);
+       if (tmp == NULL)
+               errno = EOVERFLOW;
+       return tmp;
+}
+
+/*
+** gmtsub is to gmtime as localsub is to localtime.
+*/
+
+static struct tm *
+gmtsub(const timezone_t sp, const time_t * const timep, const long offset,
+    struct tm *const tmp)
+{
+       struct tm *     result;
+#ifdef _REENTRANT
+       static mutex_t gmt_mutex = MUTEX_INITIALIZER;
+#endif
+
+       mutex_lock(&gmt_mutex);
+       if (!gmt_is_set) {
+               int saveerrno;
+               gmt_is_set = TRUE;
+               saveerrno = errno;
+               gmtptr = calloc(1, sizeof *gmtptr);
+               errno = saveerrno;
+               if (gmtptr != NULL)
+                       gmtload(gmtptr);
+       }
+       mutex_unlock(&gmt_mutex);
+       result = timesub(gmtptr, timep, offset, tmp);
+#ifdef TM_ZONE
+       /*
+       ** Could get fancy here and deliver something such as
+       ** "UTC+xxxx" or "UTC-xxxx" if offset is non-zero,
+       ** but this is no time for a treasure hunt.
+       */
+       if (offset != 0)
+               tmp->TM_ZONE = (__aconst char *)__UNCONST(wildabbr);
+       else {
+               if (gmtptr == NULL)
+                       tmp->TM_ZONE = (__aconst char *)__UNCONST(gmt);
+               else    tmp->TM_ZONE = gmtptr->chars;
+       }
+#endif /* defined TM_ZONE */
+       return result;
+}
+
+struct tm *
+gmtime(const time_t *const timep)
+{
+       return gmtsub(NULL, timep, 0L, &tm);
+}
+
+/*
+** Re-entrant version of gmtime.
+*/
+
+struct tm *
+gmtime_r(const time_t * const timep, struct tm *tmp)
+{
+       return gmtsub(NULL, timep, 0L, tmp);
+}
+
+#ifdef STD_INSPIRED
+
+struct tm *
+offtime(const time_t *const timep, long offset)
+{
+       return gmtsub(NULL, timep, offset, &tm);
+}
+
+struct tm *
+offtime_r(const time_t *timep, long offset, struct tm *tmp)
+{
+       return gmtsub(NULL, timep, offset, tmp);
+}
+
+#endif /* defined STD_INSPIRED */
+
+/*
+** Return the number of leap years through the end of the given year
+** where, to make the math easy, the answer for year zero is defined as zero.
+*/
+
+static int
+leaps_thru_end_of(const int y)
+{
+       return (y >= 0) ? (y / 4 - y / 100 + y / 400) :
+               -(leaps_thru_end_of(-(y + 1)) + 1);
+}
+
+static struct tm *
+timesub(const timezone_t sp, const time_t *const timep, const long offset,
+    struct tm *const tmp)
+{
+       const struct lsinfo *   lp;
+       time_t                  tdays;
+       int                     idays;  /* unsigned would be so 2003 */
+       long                    rem;
+       int                     y;
+       const int *             ip;
+       long                    corr;
+       int                     hit;
+       int                     i;
+
+       corr = 0;
+       hit = 0;
+       i = (sp == NULL) ? 0 : sp->leapcnt;
+       while (--i >= 0) {
+               lp = &sp->lsis[i];
+               if (*timep >= lp->ls_trans) {
+                       if (*timep == lp->ls_trans) {
+                               hit = ((i == 0 && lp->ls_corr > 0) ||
+                                       lp->ls_corr > sp->lsis[i - 1].ls_corr);
+                               if (hit)
+                                       while (i > 0 &&
+                                               sp->lsis[i].ls_trans ==
+                                               sp->lsis[i - 1].ls_trans + 1 &&
+                                               sp->lsis[i].ls_corr ==
+                                               sp->lsis[i - 1].ls_corr + 1) {
+                                                       ++hit;
+                                                       --i;
+                                       }
+                       }
+                       corr = lp->ls_corr;
+                       break;
+               }
+       }
+       y = EPOCH_YEAR;
+       tdays = *timep / SECSPERDAY;
+       rem = (long) (*timep - tdays * SECSPERDAY);
+       while (tdays < 0 || tdays >= year_lengths[isleap(y)]) {
+               int             newy;
+               time_t  tdelta;
+               int     idelta;
+               int     leapdays;
+
+               tdelta = tdays / DAYSPERLYEAR;
+               idelta = (int) tdelta;
+               if (tdelta - idelta >= 1 || idelta - tdelta >= 1)
+                       return NULL;
+               if (idelta == 0)
+                       idelta = (tdays < 0) ? -1 : 1;
+               newy = y;
+               if (increment_overflow(&newy, idelta))
+                       return NULL;
+               leapdays = leaps_thru_end_of(newy - 1) -
+                       leaps_thru_end_of(y - 1);
+               tdays -= ((time_t) newy - y) * DAYSPERNYEAR;
+               tdays -= leapdays;
+               y = newy;
+       }
+       {
+               long    seconds;
+
+               seconds = tdays * SECSPERDAY + 0.5;
+               tdays = seconds / SECSPERDAY;
+               rem += (long) (seconds - tdays * SECSPERDAY);
+       }
+       /*
+       ** Given the range, we can now fearlessly cast...
+       */
+       idays = (int) tdays;
+       rem += offset - corr;
+       while (rem < 0) {
+               rem += SECSPERDAY;
+               --idays;
+       }
+       while (rem >= SECSPERDAY) {
+               rem -= SECSPERDAY;
+               ++idays;
+       }
+       while (idays < 0) {
+               if (increment_overflow(&y, -1))
+                       return NULL;
+               idays += year_lengths[isleap(y)];
+       }
+       while (idays >= year_lengths[isleap(y)]) {
+               idays -= year_lengths[isleap(y)];
+               if (increment_overflow(&y, 1))
+                       return NULL;
+       }
+       tmp->tm_year = y;
+       if (increment_overflow(&tmp->tm_year, -TM_YEAR_BASE))
+               return NULL;
+       tmp->tm_yday = idays;
+       /*
+       ** The "extra" mods below avoid overflow problems.
+       */
+       tmp->tm_wday = EPOCH_WDAY +
+               ((y - EPOCH_YEAR) % DAYSPERWEEK) *
+               (DAYSPERNYEAR % DAYSPERWEEK) +
+               leaps_thru_end_of(y - 1) -
+               leaps_thru_end_of(EPOCH_YEAR - 1) +
+               idays;
+       tmp->tm_wday %= DAYSPERWEEK;
+       if (tmp->tm_wday < 0)
+               tmp->tm_wday += DAYSPERWEEK;
+       tmp->tm_hour = (int) (rem / SECSPERHOUR);
+       rem %= SECSPERHOUR;
+       tmp->tm_min = (int) (rem / SECSPERMIN);
+       /*
+       ** A positive leap second requires a special
+       ** representation. This uses "... ??:59:60" et seq.
+       */
+       tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
+       ip = mon_lengths[isleap(y)];
+       for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
+               idays -= ip[tmp->tm_mon];
+       tmp->tm_mday = (int) (idays + 1);
+       tmp->tm_isdst = 0;
+#ifdef TM_GMTOFF
+       tmp->TM_GMTOFF = offset;
+#endif /* defined TM_GMTOFF */
+       return tmp;
+}
+
+char *
+ctime(const time_t *const timep)
+{
+/*
+** Section 4.12.3.2 of X3.159-1989 requires that
+**     The ctime function converts the calendar time pointed to by timer
+**     to local time in the form of a string. It is equivalent to
+**             asctime(localtime(timer))
+*/
+       struct tm *rtm = localtime(timep);
+       if (rtm == NULL)
+               return NULL;
+       return asctime(rtm);
+}
+
+char *
+ctime_r(const time_t *const timep, char *buf)
+{
+       struct tm       mytm, *rtm;
+
+       rtm = localtime_r(timep, &mytm);
+       if (rtm == NULL)
+               return NULL;
+       return asctime_r(rtm, buf);
+}
+
+char *
+ctime_rz(const timezone_t sp, const time_t * timep, char *buf)
+{
+       struct tm       mytm, *rtm;
+
+       rtm = localtime_rz(sp, timep, &mytm);
+       if (rtm == NULL)
+               return NULL;
+       return asctime_r(rtm, buf);
+}
+
+/*
+** Adapted from code provided by Robert Elz, who writes:
+**     The "best" way to do mktime I think is based on an idea of Bob
+**     Kridle's (so its said...) from a long time ago.
+**     It does a binary search of the time_t space. Since time_t's are
+**     just 32 bits, its a max of 32 iterations (even at 64 bits it
+**     would still be very reasonable).
+*/
+
+#ifndef WRONG
+#define WRONG  ((time_t)-1)
+#endif /* !defined WRONG */
+
+/*
+** Simplified normalize logic courtesy Paul Eggert.
+*/
+
+static int
+increment_overflow(int *number, int delta)
+{
+       int     number0;
+
+       number0 = *number;
+       if (delta < 0 ? number0 < INT_MIN - delta : INT_MAX - delta < number0)
+                 return 1;
+       *number += delta;
+       return 0;
+}
+
+static int
+long_increment_overflow(long *number, int delta)
+{
+       long    number0;
+
+       number0 = *number;
+       if (delta < 0 ? number0 < LONG_MIN - delta : LONG_MAX - delta < number0)
+                 return 1;
+       *number += delta;
+       return 0;
+}
+
+static int
+normalize_overflow(int *const tensptr, int *const unitsptr, const int base)
+{
+       int     tensdelta;
+
+       tensdelta = (*unitsptr >= 0) ?
+               (*unitsptr / base) :
+               (-1 - (-1 - *unitsptr) / base);
+       *unitsptr -= tensdelta * base;
+       return increment_overflow(tensptr, tensdelta);
+}
+
+static int
+long_normalize_overflow(long *const tensptr, int *const unitsptr,
+    const int base)
+{
+       int     tensdelta;
+
+       tensdelta = (*unitsptr >= 0) ?
+               (*unitsptr / base) :
+               (-1 - (-1 - *unitsptr) / base);
+       *unitsptr -= tensdelta * base;
+       return long_increment_overflow(tensptr, tensdelta);
+}
+
+static int
+tmcomp(const struct tm *const atmp, const struct tm *const btmp)
+{
+       int     result;
+
+       if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
+               (result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
+               (result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
+               (result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
+               (result = (atmp->tm_min - btmp->tm_min)) == 0)
+                       result = atmp->tm_sec - btmp->tm_sec;
+       return result;
+}
+
+static time_t
+time2sub(const timezone_t sp, struct tm *const tmp, subfun_t funcp,
+    const long offset, int *const okayp, const int do_norm_secs)
+{
+       int                     dir;
+       int                     i, j;
+       int                     saved_seconds;
+       long                    li;
+       time_t                  lo;
+       time_t                  hi;
+       long                            y;
+       time_t                          newt;
+       time_t                          t;
+       struct tm                       yourtm, mytm;
+
+       *okayp = FALSE;
+       yourtm = *tmp;
+       if (do_norm_secs) {
+               if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
+                       SECSPERMIN))
+                               return WRONG;
+       }
+       if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
+               return WRONG;
+       if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
+               return WRONG;
+       y = yourtm.tm_year;
+       if (long_normalize_overflow(&y, &yourtm.tm_mon, MONSPERYEAR))
+               return WRONG;
+       /*
+       ** Turn y into an actual year number for now.
+       ** It is converted back to an offset from TM_YEAR_BASE later.
+       */
+       if (long_increment_overflow(&y, TM_YEAR_BASE))
+               return WRONG;
+       while (yourtm.tm_mday <= 0) {
+               if (long_increment_overflow(&y, -1))
+                       return WRONG;
+               li = y + (1 < yourtm.tm_mon);
+               yourtm.tm_mday += year_lengths[isleap(li)];
+       }
+       while (yourtm.tm_mday > DAYSPERLYEAR) {
+               li = y + (1 < yourtm.tm_mon);
+               yourtm.tm_mday -= year_lengths[isleap(li)];
+               if (long_increment_overflow(&y, 1))
+                       return WRONG;
+       }
+       for ( ; ; ) {
+               i = mon_lengths[isleap(y)][yourtm.tm_mon];
+               if (yourtm.tm_mday <= i)
+                       break;
+               yourtm.tm_mday -= i;
+               if (++yourtm.tm_mon >= MONSPERYEAR) {
+                       yourtm.tm_mon = 0;
+                       if (long_increment_overflow(&y, 1))
+                               return WRONG;
+               }
+       }
+       if (long_increment_overflow(&y, -TM_YEAR_BASE))
+               return WRONG;
+       yourtm.tm_year = y;
+       if (yourtm.tm_year != y)
+               return WRONG;
+       if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
+               saved_seconds = 0;
+       else if (y + TM_YEAR_BASE < EPOCH_YEAR) {
+               /*
+               ** We can't set tm_sec to 0, because that might push the
+               ** time below the minimum representable time.
+               ** Set tm_sec to 59 instead.
+               ** This assumes that the minimum representable time is
+               ** not in the same minute that a leap second was deleted from,
+               ** which is a safer assumption than using 58 would be.
+               */
+               if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
+                       return WRONG;
+               saved_seconds = yourtm.tm_sec;
+               yourtm.tm_sec = SECSPERMIN - 1;
+       } else {
+               saved_seconds = yourtm.tm_sec;
+               yourtm.tm_sec = 0;
+       }
+       /*
+       ** Do a binary search (this works whatever time_t's type is).
+       */
+/* LINTED constant */
+       if (!TYPE_SIGNED(time_t)) {
+               lo = 0;
+               hi = lo - 1;
+/* LINTED constant */
+       } else if (!TYPE_INTEGRAL(time_t)) {
+/* CONSTCOND */
+               if (sizeof(time_t) > sizeof(float))
+/* LINTED assumed double */
+                       hi = (time_t) DBL_MAX;
+/* LINTED assumed float */
+               else    hi = (time_t) FLT_MAX;
+               lo = -hi;
+       } else {
+               lo = 1;
+               for (i = 0; i < (int) TYPE_BIT(time_t) - 1; ++i)
+                       lo *= 2;
+               hi = -(lo + 1);
+       }
+       for ( ; ; ) {
+               t = lo / 2 + hi / 2;
+               if (t < lo)
+                       t = lo;
+               else if (t > hi)
+                       t = hi;
+               if ((*funcp)(sp, &t, offset, &mytm) == NULL) {
+                       /*
+                       ** Assume that t is too extreme to be represented in
+                       ** a struct tm; arrange things so that it is less
+                       ** extreme on the next pass.
+                       */
+                       dir = (t > 0) ? 1 : -1;
+               } else  dir = tmcomp(&mytm, &yourtm);
+               if (dir != 0) {
+                       if (t == lo) {
+                               ++t;
+                               if (t <= lo)
+                                       return WRONG;
+                               ++lo;
+                       } else if (t == hi) {
+                               --t;
+                               if (t >= hi)
+                                       return WRONG;
+                               --hi;
+                       }
+                       if (lo > hi)
+                               return WRONG;
+                       if (dir > 0)
+                               hi = t;
+                       else    lo = t;
+                       continue;
+               }
+               if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
+                       break;
+               /*
+               ** Right time, wrong type.
+               ** Hunt for right time, right type.
+               ** It's okay to guess wrong since the guess
+               ** gets checked.
+               */
+               if (sp == NULL)
+                       return WRONG;
+               for (i = sp->typecnt - 1; i >= 0; --i) {
+                       if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
+                               continue;
+                       for (j = sp->typecnt - 1; j >= 0; --j) {
+                               if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
+                                       continue;
+                               newt = t + sp->ttis[j].tt_gmtoff -
+                                       sp->ttis[i].tt_gmtoff;
+                               if ((*funcp)(sp, &newt, offset, &mytm) == NULL)
+                                       continue;
+                               if (tmcomp(&mytm, &yourtm) != 0)
+                                       continue;
+                               if (mytm.tm_isdst != yourtm.tm_isdst)
+                                       continue;
+                               /*
+                               ** We have a match.
+                               */
+                               t = newt;
+                               goto label;
+                       }
+               }
+               return WRONG;
+       }
+label:
+       newt = t + saved_seconds;
+       if ((newt < t) != (saved_seconds < 0))
+               return WRONG;
+       t = newt;
+       if ((*funcp)(sp, &t, offset, tmp)) {
+               *okayp = TRUE;
+               return t;
+       } else
+               return WRONG;
+}
+
+static time_t
+time2(const timezone_t sp, struct tm *const tmp, subfun_t funcp,
+    const long offset, int *const okayp)
+{
+       time_t  t;
+
+       /*
+       ** First try without normalization of seconds
+       ** (in case tm_sec contains a value associated with a leap second).
+       ** If that fails, try with normalization of seconds.
+       */
+       t = time2sub(sp, tmp, funcp, offset, okayp, FALSE);
+       return *okayp ? t : time2sub(sp, tmp, funcp, offset, okayp, TRUE);
+}
+
+static time_t
+time1(const timezone_t sp, struct tm *const tmp, subfun_t funcp,
+    long offset)
+{
+       time_t                  t;
+       int                     samei, otheri;
+       int                     sameind, otherind;
+       int                     i;
+       int                     nseen;
+       int                             seen[TZ_MAX_TYPES];
+       int                             types[TZ_MAX_TYPES];
+       int                             okay;
+
+       if (tmp->tm_isdst > 1)
+               tmp->tm_isdst = 1;
+       t = time2(sp, tmp, funcp, offset, &okay);
+#ifdef PCTS
+       /*
+       ** PCTS code courtesy Grant Sullivan.
+       */
+       if (okay)
+               return t;
+       if (tmp->tm_isdst < 0)
+               tmp->tm_isdst = 0;      /* reset to std and try again */
+#endif /* defined PCTS */
+#ifndef PCTS
+       if (okay || tmp->tm_isdst < 0)
+               return t;
+#endif /* !defined PCTS */
+       /*
+       ** We're supposed to assume that somebody took a time of one type
+       ** and did some math on it that yielded a "struct tm" that's bad.
+       ** We try to divine the type they started from and adjust to the
+       ** type they need.
+       */
+       if (sp == NULL)
+               return WRONG;
+       for (i = 0; i < sp->typecnt; ++i)
+               seen[i] = FALSE;
+       nseen = 0;
+       for (i = sp->timecnt - 1; i >= 0; --i)
+               if (!seen[sp->types[i]]) {
+                       seen[sp->types[i]] = TRUE;
+                       types[nseen++] = sp->types[i];
+               }
+       for (sameind = 0; sameind < nseen; ++sameind) {
+               samei = types[sameind];
+               if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
+                       continue;
+               for (otherind = 0; otherind < nseen; ++otherind) {
+                       otheri = types[otherind];
+                       if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
+                               continue;
+                       tmp->tm_sec += (int)(sp->ttis[otheri].tt_gmtoff -
+                                       sp->ttis[samei].tt_gmtoff);
+                       tmp->tm_isdst = !tmp->tm_isdst;
+                       t = time2(sp, tmp, funcp, offset, &okay);
+                       if (okay)
+                               return t;
+                       tmp->tm_sec -= (int)(sp->ttis[otheri].tt_gmtoff -
+                                       sp->ttis[samei].tt_gmtoff);
+                       tmp->tm_isdst = !tmp->tm_isdst;
+               }
+       }
+       return WRONG;
+}
+
+time_t
+mktime_z(const timezone_t sp, struct tm *tmp)
+{
+       time_t t;
+       if (sp == NULL)
+               t = time1(NULL, tmp, gmtsub, 0L);
+       else
+               t = time1(sp, tmp, localsub, 0L);
+       if (t == WRONG)
+               errno = EOVERFLOW;
+       return t;
+}
+
+time_t
+mktime(struct tm * const       tmp)
+{
+       time_t result;
+
+       rwlock_wrlock(&lcl_lock);
+       tzset_unlocked();
+       result = mktime_z(lclptr, tmp);
+       rwlock_unlock(&lcl_lock);
+       return result;
+}
+
+#ifdef STD_INSPIRED
+
+time_t
+timelocal_z(const timezone_t sp, struct tm *tmp)
+{
+       if (tmp != NULL)
+               tmp->tm_isdst = -1;     /* in case it wasn't initialized */
+       return mktime_z(sp, tmp);
+}
+
+time_t
+timelocal(struct tm *const tmp)
+{
+       tmp->tm_isdst = -1;     /* in case it wasn't initialized */
+       return mktime(tmp);
+}
+
+time_t
+timegm(struct tm *const tmp)
+{
+       time_t t;
+
+       tmp->tm_isdst = 0;
+       t = time1(gmtptr, tmp, gmtsub, 0L);
+       if (t == WRONG)
+               errno = EOVERFLOW;
+       return t;
+}
+
+time_t
+timeoff(struct tm *const tmp, const long offset)
+{
+       time_t t;
+
+       tmp->tm_isdst = 0;
+       t = time1(gmtptr, tmp, gmtsub, offset);
+       if (t == WRONG)
+               errno = EOVERFLOW;
+       return t;
+}
+
+#endif /* defined STD_INSPIRED */
+
+#ifdef CMUCS
+
+/*
+** The following is supplied for compatibility with
+** previous versions of the CMUCS runtime library.
+*/
+
+long
+gtime(struct tm *const tmp)
+{
+       const time_t t = mktime(tmp);
+
+       if (t == WRONG)
+               return -1;
+       return t;
+}
+
+#endif /* defined CMUCS */
+
+/*
+** XXX--is the below the right way to conditionalize??
+*/
+
+#ifdef STD_INSPIRED
+
+/*
+** IEEE Std 1003.1-1988 (POSIX) legislates that 536457599
+** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
+** is not the case if we are accounting for leap seconds.
+** So, we provide the following conversion routines for use
+** when exchanging timestamps with POSIX conforming systems.
+*/
+
+static long
+leapcorr(const timezone_t sp, time_t *timep)
+{
+       struct lsinfo * lp;
+       int             i;
+
+       i = sp->leapcnt;
+       while (--i >= 0) {
+               lp = &sp->lsis[i];
+               if (*timep >= lp->ls_trans)
+                       return lp->ls_corr;
+       }
+       return 0;
+}
+
+time_t
+time2posix_z(const timezone_t sp, time_t t)
+{
+       return t - leapcorr(sp, &t);
+}
+
+time_t
+time2posix(time_t t)
+{
+       time_t result;
+       rwlock_wrlock(&lcl_lock);
+       tzset_unlocked();
+       result = t - leapcorr(lclptr, &t);
+       rwlock_unlock(&lcl_lock);
+       return (result);
+}
+
+time_t
+posix2time_z(const timezone_t sp, time_t t)
+{
+       time_t  x;
+       time_t  y;
+
+       /*
+       ** For a positive leap second hit, the result
+       ** is not unique. For a negative leap second
+       ** hit, the corresponding time doesn't exist,
+       ** so we return an adjacent second.
+       */
+       x = t + leapcorr(sp, &t);
+       y = x - leapcorr(sp, &x);
+       if (y < t) {
+               do {
+                       x++;
+                       y = x - leapcorr(sp, &x);
+               } while (y < t);
+               if (t != y) {
+                       return x - 1;
+               }
+       } else if (y > t) {
+               do {
+                       --x;
+                       y = x - leapcorr(sp, &x);
+               } while (y > t);
+               if (t != y) {
+                       return x + 1;
+               }
+       }
+       return x;
+}
+
+
+
+time_t
+posix2time(time_t t)
+{
+       time_t result;
+
+       rwlock_wrlock(&lcl_lock);
+       tzset_unlocked();
+       result = posix2time_z(lclptr, t);
+       rwlock_unlock(&lcl_lock);
+       return result;
+}
+
+#endif /* defined STD_INSPIRED */
diff --git a/lib/nbsd_libc/time/offtime.3 b/lib/nbsd_libc/time/offtime.3
new file mode 100644 (file)
index 0000000..3e706eb
--- /dev/null
@@ -0,0 +1,74 @@
+.\"    $NetBSD: offtime.3,v 1.2 2010/12/16 18:38:07 christos Exp $
+.\" Written by Klaus Klein, May 10, 2004.
+.\" Public domain.
+.Dd December 14, 2010
+.Dt OFFTIME 3
+.Os
+.Sh NAME
+.Nm offtime ,
+.Nm timeoff ,
+.Nm timegm ,
+.Nm timelocal
+.Nd convert date and time
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Ft struct tm *
+.Fn offtime "const time_t * clock" "long int offset"
+.Ft struct tm *
+.Fn offtime_r "const time_t * clock" "long int offset" "struct tm *ret"
+.Ft time_t
+.Fn timeoff "struct tm * tm" "long int offset"
+.Ft time_t
+.Fn timegm "struct tm * tm"
+.Ft time_t
+.Fn timelocal "struct tm * tm"
+.Sh DESCRIPTION
+These functions are inspired by C standard interfaces named similarly.
+.Pp
+.Fn offtime
+converts the calendar time
+.Fa clock ,
+offset by
+.Fa offset
+seconds,
+into broken-down time, expressed as Coordinated Universal Time (UTC).
+.Pp
+.Fn offtime_r
+is similar to
+.Fn offtime
+but it places the returned
+.Ft "struct tm *"
+in the user supplied
+.Fa ret
+argument.
+.Pp
+.Fn timeoff
+converts the broken-down time
+.Fa tm ,
+expressed as UTC,
+offset by
+.Fa offset
+seconds,
+into a calendar time value.
+.Pp
+.Fn timegm
+converts the broken-down time
+.Fa tm
+into a calendar time value, effectively being the inverse of
+.Xr gmtime 3 .
+It is equivalent to the C standard function
+.Xr mktime 3
+operating in UTC.
+.Pp
+.Fn timelocal
+converts the broken down time
+.Fa tm ,
+expressed as local time, into a calendar time value.
+It is equivalent to the C standard function
+.Xr mktime 3 ,
+and is provided for symmetry only.
+.Sh SEE ALSO
+.Xr ctime 3 ,
+.Xr tzset 3
diff --git a/lib/nbsd_libc/time/private.h b/lib/nbsd_libc/time/private.h
new file mode 100644 (file)
index 0000000..5f31d68
--- /dev/null
@@ -0,0 +1,312 @@
+/*     $NetBSD: private.h,v 1.25 2009/12/31 22:49:16 mlelstv Exp $     */
+
+#ifndef PRIVATE_H
+#define PRIVATE_H
+
+/* NetBSD defaults */
+#define TM_GMTOFF      tm_gmtoff
+#define TM_ZONE                tm_zone
+#define STD_INSPIRED   1
+#define HAVE_LONG_DOUBLE 1
+
+/* For when we build zic as a host tool. */
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+/*
+** This file is in the public domain, so clarified as of
+** 1996-06-05 by Arthur David Olson.
+*/
+
+/*
+** This header is for use ONLY with the time conversion code.
+** There is no guarantee that it will remain unchanged,
+** or that it will remain at all.
+** Do NOT copy it to any system include directory.
+** Thank you!
+*/
+
+/*
+** ID
+*/
+
+#ifndef lint
+#ifndef NOID
+#if 0
+static char    privatehid[] = "@(#)private.h   8.6";
+#endif
+#endif /* !defined NOID */
+#endif /* !defined lint */
+
+#define GRANDPARENTED  "Local time zone must be set--see zic manual page"
+
+/*
+** Defaults for preprocessor symbols.
+** You can override these in your C compiler options, e.g. `-DHAVE_ADJTIME=0'.
+*/
+
+#ifndef HAVE_ADJTIME
+#define HAVE_ADJTIME           1
+#endif /* !defined HAVE_ADJTIME */
+
+#ifndef HAVE_GETTEXT
+#define HAVE_GETTEXT           0
+#endif /* !defined HAVE_GETTEXT */
+
+#ifndef HAVE_INCOMPATIBLE_CTIME_R
+#define HAVE_INCOMPATIBLE_CTIME_R      0
+#endif /* !defined INCOMPATIBLE_CTIME_R */
+
+#ifndef HAVE_SETTIMEOFDAY
+#define HAVE_SETTIMEOFDAY      3
+#endif /* !defined HAVE_SETTIMEOFDAY */
+
+#ifndef HAVE_SYMLINK
+#define HAVE_SYMLINK           1
+#endif /* !defined HAVE_SYMLINK */
+
+#ifndef HAVE_SYS_STAT_H
+#define HAVE_SYS_STAT_H                1
+#endif /* !defined HAVE_SYS_STAT_H */
+
+#ifndef HAVE_SYS_WAIT_H
+#define HAVE_SYS_WAIT_H                1
+#endif /* !defined HAVE_SYS_WAIT_H */
+
+#ifndef HAVE_UNISTD_H
+#define HAVE_UNISTD_H          1
+#endif /* !defined HAVE_UNISTD_H */
+
+#ifndef HAVE_UTMPX_H
+#define HAVE_UTMPX_H           0
+#endif /* !defined HAVE_UTMPX_H */
+
+#ifdef LOCALE_HOME
+#undef LOCALE_HOME             /* not to be handled by tzcode itself */
+#endif /* defined LOCALE_HOME */
+
+#if HAVE_INCOMPATIBLE_CTIME_R
+#define asctime_r _incompatible_asctime_r
+#define ctime_r _incompatible_ctime_r
+#endif /* HAVE_INCOMPATIBLE_CTIME_R */
+
+/*
+** Nested includes
+*/
+
+#include "sys/types.h" /* for time_t */
+#include "stdio.h"
+#include "errno.h"
+#include "string.h"
+#include "limits.h"    /* for CHAR_BIT et al. */
+#include "time.h"
+#include "stdlib.h"
+
+#if HAVE_GETTEXT
+#include "libintl.h"
+#endif /* HAVE_GETTEXT */
+
+#if HAVE_SYS_WAIT_H
+#include <sys/wait.h>  /* for WIFEXITED and WEXITSTATUS */
+#endif /* HAVE_SYS_WAIT_H */
+
+#ifndef WIFEXITED
+#define WIFEXITED(status)      (((status) & 0xff) == 0)
+#endif /* !defined WIFEXITED */
+#ifndef WEXITSTATUS
+#define WEXITSTATUS(status)    (((status) >> 8) & 0xff)
+#endif /* !defined WEXITSTATUS */
+
+#if HAVE_UNISTD_H
+#include "unistd.h"    /* for F_OK, R_OK, and other POSIX goodness */
+#endif /* HAVE_UNISTD_H */
+
+#ifndef F_OK
+#define F_OK   0
+#endif /* !defined F_OK */
+#ifndef R_OK
+#define R_OK   4
+#endif /* !defined R_OK */
+
+/* Unlike <ctype.h>'s isdigit, this also works if c < 0 | c > UCHAR_MAX. */
+#define is_digit(c) ((unsigned)(c) - '0' <= 9)
+
+/*
+** Define HAVE_STDINT_H's default value here, rather than at the
+** start, since __GLIBC__'s value depends on previously-included
+** files.
+** (glibc 2.1 and later have stdint.h, even with pre-C99 compilers.)
+*/
+#ifndef HAVE_STDINT_H
+#define HAVE_STDINT_H \
+       (199901 <= __STDC_VERSION__ || \
+       2 < (__GLIBC__ + (0 < __GLIBC_MINOR__)))
+#endif /* !defined HAVE_STDINT_H */
+
+#if HAVE_STDINT_H
+#include "stdint.h"
+#endif /* !HAVE_STDINT_H */
+
+#ifndef INT_FAST64_MAX
+/* Pre-C99 GCC compilers define __LONG_LONG_MAX__ instead of LLONG_MAX.  */
+#if defined LLONG_MAX || defined __LONG_LONG_MAX__
+typedef long long      int_fast64_t;
+#else /* ! (defined LLONG_MAX || defined __LONG_LONG_MAX__) */
+#if (LONG_MAX >> 31) < 0xffffffff
+Please use a compiler that supports a 64-bit integer type (or wider);
+you may need to compile with "-DHAVE_STDINT_H".
+#endif /* (LONG_MAX >> 31) < 0xffffffff */
+typedef long           int_fast64_t;
+#endif /* ! (defined LLONG_MAX || defined __LONG_LONG_MAX__) */
+#endif /* !defined INT_FAST64_MAX */
+
+#ifndef INT32_MAX
+#define INT32_MAX 0x7fffffff
+#endif /* !defined INT32_MAX */
+#ifndef INT32_MIN
+#define INT32_MIN (-1 - INT32_MAX)
+#endif /* !defined INT32_MIN */
+
+/*
+** Workarounds for compilers/systems.
+*/
+
+/*
+** Some time.h implementations don't declare asctime_r.
+** Others might define it as a macro.
+** Fix the former without affecting the latter.
+*/
+
+#ifndef asctime_r
+extern char *  asctime_r(struct tm const *, char *);
+#endif
+
+/*
+** Private function declarations.
+*/
+
+char *         icalloc(int nelem, int elsize);
+char *         icatalloc(char * old, const char * new);
+char *         icpyalloc(const char * string);
+char *         imalloc(int n);
+void *         irealloc(void * pointer, int size);
+void           icfree(char * pointer);
+void           ifree(char * pointer);
+const char *   scheck(const char * string, const char * format);
+
+/*
+** Finally, some convenience items.
+*/
+
+#ifndef TRUE
+#define TRUE   1
+#endif /* !defined TRUE */
+
+#ifndef FALSE
+#define FALSE  0
+#endif /* !defined FALSE */
+
+#ifndef TYPE_BIT
+#define TYPE_BIT(type) (sizeof (type) * CHAR_BIT)
+#endif /* !defined TYPE_BIT */
+
+#ifndef TYPE_SIGNED
+#define TYPE_SIGNED(type) (((type) -1) < 0)
+#endif /* !defined TYPE_SIGNED */
+
+/*
+** Since the definition of TYPE_INTEGRAL contains floating point numbers,
+** it cannot be used in preprocessor directives.
+*/
+
+#ifndef TYPE_INTEGRAL
+#define TYPE_INTEGRAL(type) (((type) 0.5) != 0.5)
+#endif /* !defined TYPE_INTEGRAL */
+
+#ifndef INT_STRLEN_MAXIMUM
+/*
+** 302 / 1000 is log10(2.0) rounded up.
+** Subtract one for the sign bit if the type is signed;
+** add one for integer division truncation;
+** add one more for a minus sign if the type is signed.
+*/
+#define INT_STRLEN_MAXIMUM(type) \
+       ((TYPE_BIT(type) - TYPE_SIGNED(type)) * 302 / 1000 + \
+       1 + TYPE_SIGNED(type))
+#endif /* !defined INT_STRLEN_MAXIMUM */
+
+/*
+** INITIALIZE(x)
+*/
+
+#ifndef GNUC_or_lint
+#ifdef lint
+#define GNUC_or_lint
+#endif /* defined lint */
+#ifndef lint
+#ifdef __GNUC__
+#define GNUC_or_lint
+#endif /* defined __GNUC__ */
+#endif /* !defined lint */
+#endif /* !defined GNUC_or_lint */
+
+#ifndef INITIALIZE
+#ifdef GNUC_or_lint
+#define INITIALIZE(x)  ((x) = 0)
+#endif /* defined GNUC_or_lint */
+#ifndef GNUC_or_lint
+#define INITIALIZE(x)
+#endif /* !defined GNUC_or_lint */
+#endif /* !defined INITIALIZE */
+
+/*
+** For the benefit of GNU folk...
+** `_(MSGID)' uses the current locale's message library string for MSGID.
+** The default is to use gettext if available, and use MSGID otherwise.
+*/
+
+#ifndef _
+#if HAVE_GETTEXT
+#define _(msgid) gettext(msgid)
+#else /* !HAVE_GETTEXT */
+#define _(msgid) msgid
+#endif /* !HAVE_GETTEXT */
+#endif /* !defined _ */
+
+#ifndef TZ_DOMAIN
+#define TZ_DOMAIN "tz"
+#endif /* !defined TZ_DOMAIN */
+
+#if HAVE_INCOMPATIBLE_CTIME_R
+#undef asctime_r
+#undef ctime_r
+char *asctime_r(struct tm const *, char *);
+char *ctime_r(time_t const *, char *);
+#endif /* HAVE_INCOMPATIBLE_CTIME_R */
+
+#ifndef YEARSPERREPEAT
+#define YEARSPERREPEAT         400     /* years before a Gregorian repeat */
+#endif /* !defined YEARSPERREPEAT */
+
+/*
+** The Gregorian year averages 365.2425 days, which is 31556952 seconds.
+*/
+
+#ifndef AVGSECSPERYEAR
+#define AVGSECSPERYEAR         31556952L
+#endif /* !defined AVGSECSPERYEAR */
+
+#ifndef SECSPERREPEAT
+#define SECSPERREPEAT          ((int_fast64_t) YEARSPERREPEAT * (int_fast64_t) AVGSECSPERYEAR)
+#endif /* !defined SECSPERREPEAT */
+
+#ifndef SECSPERREPEAT_BITS
+#define SECSPERREPEAT_BITS     34      /* ceil(log2(SECSPERREPEAT)) */
+#endif /* !defined SECSPERREPEAT_BITS */
+
+/*
+** UNIX was a registered trademark of The Open Group in 2003.
+*/
+
+#endif /* !defined PRIVATE_H */
diff --git a/lib/nbsd_libc/time/scheck.c b/lib/nbsd_libc/time/scheck.c
new file mode 100644 (file)
index 0000000..3a118da
--- /dev/null
@@ -0,0 +1,73 @@
+/*     $NetBSD: scheck.c,v 1.8 2010/01/02 10:42:49 tsutsui Exp $       */
+
+/*
+** This file is in the public domain, so clarified as of
+** 2006-07-17 by Arthur David Olson.
+*/
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+
+#ifndef lint
+#if 0
+static char    elsieid[] = "@(#)scheck.c       8.19";
+#else
+__RCSID("$NetBSD: scheck.c,v 1.8 2010/01/02 10:42:49 tsutsui Exp $");
+#endif
+#endif /* !defined lint */
+
+/*LINTLIBRARY*/
+
+#include "private.h"
+
+const char *
+scheck(string, format)
+const char * const     string;
+const char * const     format;
+{
+       register char *         fbuf;
+       register const char *   fp;
+       register char *         tp;
+       register int            c;
+       register const char *   result;
+       char                    dummy;
+
+       result = "";
+       if (string == NULL || format == NULL)
+               return result;
+       fbuf = imalloc((int) (2 * strlen(format) + 4));
+       if (fbuf == NULL)
+               return result;
+       fp = format;
+       tp = fbuf;
+       while ((*tp++ = c = *fp++) != '\0') {
+               if (c != '%')
+                       continue;
+               if (*fp == '%') {
+                       *tp++ = *fp++;
+                       continue;
+               }
+               *tp++ = '*';
+               if (*fp == '*')
+                       ++fp;
+               while (is_digit(*fp))
+                       *tp++ = *fp++;
+               if (*fp == 'l' || *fp == 'h')
+                       *tp++ = *fp++;
+               else if (*fp == '[')
+                       do *tp++ = *fp++;
+                               while (*fp != '\0' && *fp != ']');
+               if ((*tp++ = *fp++) == '\0')
+                       break;
+       }
+       *(tp - 1) = '%';
+       *tp++ = 'c';
+       *tp = '\0';
+       if (sscanf(string, fbuf, &dummy) != 1)
+               result = (char *) format;
+       ifree(fbuf);
+       return result;
+}
diff --git a/lib/nbsd_libc/time/strftime.3 b/lib/nbsd_libc/time/strftime.3
new file mode 100644 (file)
index 0000000..d72e8e7
--- /dev/null
@@ -0,0 +1,264 @@
+.\" Copyright (c) 1989, 1991 The Regents of the University of California.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" the American National Standards Committee X3, on Information
+.\" Processing Systems.
+.\"
+.\" 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. 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.
+.\"
+.\"     from: @(#)strftime.3   5.12 (Berkeley) 6/29/91
+.\"    $NetBSD: strftime.3,v 1.27 2010/12/16 18:38:07 christos Exp $
+.\"
+.Dd December 14, 2010
+.Dt STRFTIME 3
+.Os
+.Sh NAME
+.Nm strftime ,
+.Nm strftime_z
+.Nd format date and time
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Ft size_t
+.Fn strftime "char * restrict buf" "size_t maxsize" "const char * restrict format" "const struct tm * restrict timeptr"
+.Ft size_t
+.Fn strftime_z "const timezone_t tz" "char * restrict buf" "size_t maxsize" "const char * restrict format" "const struct tm * restrict timeptr"
+.Sh DESCRIPTION
+The
+.Fn strftime
+function formats the information from
+.Fa timeptr
+into the buffer
+.Fa buf
+according to the string pointed to by
+.Fa format .
+.Pp
+The
+.Fa format
+string consists of zero or more conversion specifications and
+ordinary characters.
+All ordinary characters are copied directly into the buffer.
+A conversion specification consists of a percent sign
+.Ql %
+and one other character.
+.Pp
+No more than
+.Fa maxsize
+characters will be placed into the array.
+If the total number of resulting characters, including the terminating
+null character, is not more than
+.Fa maxsize ,
+.Fn strftime
+returns the number of characters in the array, not counting the
+terminating null.
+Otherwise, zero is returned and the contents of the array are undefined.
+.Pp
+Each conversion specification is replaced by the characters as
+follows which are then copied into the buffer.
+.Bl -tag -width "xxxx"
+.It Cm \&%A
+is replaced by the locale's full weekday name.
+.It Cm %a
+is replaced by the locale's abbreviated weekday name.
+.It Cm \&%B
+is replaced by the locale's full month name.
+.It Cm \&%b No or Cm \&%h
+is replaced by the locale's abbreviated month name.
+.It Cm \&%C
+is replaced by the century (a year divided by 100 and truncated to an integer)
+as a decimal number [00,99].
+.It Cm \&%c
+is replaced by the locale's appropriate date and time representation.
+.It Cm \&%D
+is replaced by the date in the format
+.Dq Li %m/%d/%y .
+.It Cm \&%d
+is replaced by the day of the month as a decimal number [01,31].
+.It Cm \&%e
+is replaced by the day of month as a decimal number [1,31];
+single digits are preceded by a blank.
+.It Cm \&%F
+is replaced by the date in the format
+.Dq Li %Y-%m-%d
+(the ISO 8601 date format).
+.It Cm \&%G
+is replaced by the ISO 8601 year with century as a decimal number.
+.It Cm \&%g
+is replaced by the ISO 8601 year without century as a decimal number (00-99).
+This is the year that includes the greater part of the week.
+(Monday as the first day of a week).
+See also the
+.Ql \&%V
+conversion specification.
+.It Cm \&%H
+is replaced by the hour (24-hour clock) as a decimal number [00,23].
+.It Cm \&%I
+is replaced by the hour (12-hour clock) as a decimal number [01,12].
+.It Cm \&%j
+is replaced by the day of the year as a decimal number [001,366].
+.It Cm \&%k
+is replaced by the hour (24-hour clock) as a decimal number [0,23];
+single digits are preceded by a blank.
+.It Cm \&%l
+is replaced by the hour (12-hour clock) as a decimal number [1,12];
+single digits are preceded by a blank.
+.It Cm \&%M
+is replaced by the minute as a decimal number [00,59].
+.It Cm %m
+is replaced by the month as a decimal number [01,12].
+.It Cm %n
+is replaced by a newline.
+.It Cm %p
+is replaced by the locale's equivalent of either
+.Dq Tn AM
+or
+.Dq Tn PM .
+.It Cm \&%R
+is replaced by the time in the format
+.Dq Li %H:%M .
+.It Cm \&%r
+is replaced by the locale's representation of 12-hour clock time
+using AM/PM notation.
+.It Cm \&%S
+is replaced by the second as a decimal number [00,61].
+The range of
+seconds is (00-61) instead of (00-59) to allow for the periodic occurrence
+of leap seconds and double leap seconds.
+.It Cm %s
+is replaced by the number of seconds since the Epoch, UTC (see
+.Xr mktime 3 ) .
+.It Cm \&%T
+is replaced by the time in the format
+.Dq Li %H:%M:%S .
+.It Cm \&%t
+is replaced by a tab.
+.It Cm \&%U
+is replaced by the week number of the year (Sunday as the first day of
+the week) as a decimal number [00,53].
+.It Cm \&%u
+is replaced by the weekday (Monday as the first day of the week)
+as a decimal number [1,7].
+.It Cm \&%V
+is replaced by the week number of the year (Monday as the first day of
+the week) as a decimal number [01,53]. According to ISO 8601 the week
+containing January 1 is week 1 if it has four or more days in the new year,
+otherwise it is week 53 of the previous year, and the next week is week 1.
+The year is given by the
+.Ql \&%G
+conversion specification.
+.It Cm \&%v
+is replaced by the date in the format
+.Dq Li %e-%b-%Y .
+.It Cm \&%W
+is replaced by the week number of the year (Monday as the first day of
+the week) as a decimal number [00,53].
+.It Cm \&%w
+is replaced by the weekday (Sunday as the first day of the week)
+as a decimal number [0,6].
+.It Cm \&%X
+is replaced by the locale's appropriate time representation.
+.It Cm \&%x
+is replaced by the locale's appropriate date representation.
+.It Cm \&%Y
+is replaced by the year with century as a decimal number.
+.It Cm \&%y
+is replaced by the year without century as a decimal number [00,99].
+.It Cm \&%Z
+is replaced by the time zone name.
+.It Cm \&%z
+is replaced by the offset from ITC in the ISO 8601 format
+.Dq Li [-]hhmm .
+.It Cm %%
+is replaced by
+.Ql % .
+.El
+.Pp
+The
+.Fn strftime_z
+function is similar to
+.Fn strftime ,
+but it also takes a
+.Ft "const timezone_t"
+.Fa tz
+argument.
+.Sh SEE ALSO
+.Xr date 1 ,
+.Xr printf 1 ,
+.Xr ctime 3 ,
+.Xr printf 3 ,
+.Xr strptime 3
+.Sh STANDARDS
+The
+.Fn strftime
+function
+conforms to
+.St -isoC-99 .
+The
+.Ql \&%C ,
+.Ql \&%D ,
+.Ql \&%e ,
+.Ql \&%g ,
+.Ql \&%G ,
+.Ql \&%h ,
+.Ql \&%k ,
+.Ql \&%l ,
+.Ql \&%n ,
+.Ql \&%r ,
+.Ql \&%R ,
+.Ql \&%s ,
+.Ql \&%t ,
+.Ql \&%T ,
+.Ql \&%u ,
+.Ql \&%V ,
+and
+.Ql \&%v
+conversion specifications are extensions.
+.Pp
+Use of the ISO 8601 conversions may produce non-intuitive results.
+Week 01 of a year is per definition the first week which has the Thursday
+in this year, which is equivalent to the week which contains the fourth
+day of January.
+In other words, the first week of a new year is the week which has the
+majority of its days in the new year.
+Week 01 might also contain days from the previous year and the week
+before week 01 of a year is the last week (52 or 53) of the previous
+year even if it contains days from the new year.
+A week starts with Monday (day 1) and ends with Sunday (day 7).
+For example, the first week of the year 1997 lasts from
+1996-12-30 to 1997-01-05.
+.Sh BUGS
+There is no conversion specification for the phase of the moon.
+.Pp
+A return value of zero does not necessarily indicate an error.
+If the resulting string is an empty string, the result value is
+zero and it is not possible to distinguish between success and error.
+For example, in many locales
+.Cm \&%p
+yields an empty string.
+This problem can be avoided by inserting an extra space at the
+beginning of the format string and then skipping over it or removing
+it from the result.
diff --git a/lib/nbsd_libc/time/strftime.c b/lib/nbsd_libc/time/strftime.c
new file mode 100644 (file)
index 0000000..1cd8ac4
--- /dev/null
@@ -0,0 +1,771 @@
+/*     $NetBSD: strftime.c,v 1.21 2010/12/16 18:38:07 christos Exp $   */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char    elsieid[] = "@(#)strftime.c     7.64";
+static char    elsieid[] = "@(#)strftime.c     8.3";
+#else
+__RCSID("$NetBSD: strftime.c,v 1.21 2010/12/16 18:38:07 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "namespace.h"
+
+/*
+** Based on the UCB version with the ID appearing below.
+** This is ANSIish only when "multibyte character == plain character".
+*/
+
+#include "private.h"
+
+/*
+** We don't use these extensions in strftime operation even when
+** supported by the local tzcode configuration.  A strictly
+** conforming C application may leave them in undefined state.
+*/
+
+#ifdef _LIBC
+#undef TM_ZONE
+#undef TM_GMTOFF
+#endif
+
+/*
+** Copyright (c) 1989, 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.
+** 3. All advertising materials mentioning features or use of this software
+**    must display the following acknowledgement:
+**     This product includes software developed by the University of
+**     California, Berkeley and its contributors.
+** 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.
+*/
+
+#ifndef LIBC_SCCS
+#ifndef lint
+static const char      sccsid[] = "@(#)strftime.c      5.4 (Berkeley) 3/14/89";
+#endif /* !defined lint */
+#endif /* !defined LIBC_SCCS */
+
+#include "tzfile.h"
+#include "fcntl.h"
+#include "locale.h"
+
+#ifdef __weak_alias
+__weak_alias(strftime_z, _strftime_z)
+#endif
+
+#include "sys/localedef.h"
+#define Locale _CurrentTimeLocale
+#define c_fmt   d_t_fmt
+
+static char *  _add(const char *, char *, const char *);
+static char *  _conv(int, const char *, char *, const char *);
+static char *  _fmt(const timezone_t, const char *, const struct tm *, char *,
+                       const char *, int *);
+static char *  _yconv(int, int, int, int, char *, const char *);
+
+extern char *  tzname[];
+
+#ifndef YEAR_2000_NAME
+#define YEAR_2000_NAME "CHECK_STRFTIME_FORMATS_FOR_TWO_DIGIT_YEARS"
+#endif /* !defined YEAR_2000_NAME */
+
+#define IN_NONE        0
+#define IN_SOME        1
+#define IN_THIS        2
+#define IN_ALL 3
+
+size_t
+strftime_z(const timezone_t sp, char * const s, const size_t maxsize,
+    const char * const format, const struct tm * const t)
+{
+       char *  p;
+       int     warn;
+
+       warn = IN_NONE;
+       p = _fmt(sp, ((format == NULL) ? "%c" : format), t, s, s + maxsize,
+           &warn);
+#ifndef NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU
+       if (warn != IN_NONE && getenv(YEAR_2000_NAME) != NULL) {
+               (void) fprintf(stderr, "\n");
+               if (format == NULL)
+                       (void) fprintf(stderr, "NULL strftime format ");
+               else    (void) fprintf(stderr, "strftime format \"%s\" ",
+                               format);
+               (void) fprintf(stderr, "yields only two digits of years in ");
+               if (warn == IN_SOME)
+                       (void) fprintf(stderr, "some locales");
+               else if (warn == IN_THIS)
+                       (void) fprintf(stderr, "the current locale");
+               else    (void) fprintf(stderr, "all locales");
+               (void) fprintf(stderr, "\n");
+       }
+#endif /* !defined NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU */
+       if (p == s + maxsize)
+               return 0;
+       *p = '\0';
+       return p - s;
+}
+
+static char *
+_fmt(const timezone_t sp, const char *format, const struct tm * const t,
+       char *pt, const char *const ptlim, int *warnp)
+{
+       for ( ; *format; ++format) {
+               if (*format == '%') {
+label:
+                       switch (*++format) {
+                       case '\0':
+                               --format;
+                               break;
+                       case 'A':
+                               pt = _add((t->tm_wday < 0 ||
+                                       t->tm_wday >= DAYSPERWEEK) ?
+                                       "?" : Locale->day[t->tm_wday],
+                                       pt, ptlim);
+                               continue;
+                       case 'a':
+                               pt = _add((t->tm_wday < 0 ||
+                                       t->tm_wday >= DAYSPERWEEK) ?
+                                       "?" : Locale->abday[t->tm_wday],
+                                       pt, ptlim);
+                               continue;
+                       case 'B':
+                               pt = _add((t->tm_mon < 0 ||
+                                       t->tm_mon >= MONSPERYEAR) ?
+                                       "?" : Locale->mon[t->tm_mon],
+                                       pt, ptlim);
+                               continue;
+                       case 'b':
+                       case 'h':
+                               pt = _add((t->tm_mon < 0 ||
+                                       t->tm_mon >= MONSPERYEAR) ?
+                                       "?" : Locale->abmon[t->tm_mon],
+                                       pt, ptlim);
+                               continue;
+                       case 'C':
+                               /*
+                               ** %C used to do a...
+                               **      _fmt("%a %b %e %X %Y", t);
+                               ** ...whereas now POSIX 1003.2 calls for
+                               ** something completely different.
+                               ** (ado, 1993-05-24)
+                               */
+                               pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 0,
+                                       pt, ptlim);
+                               continue;
+                       case 'c':
+                               {
+                               int warn2 = IN_SOME;
+
+                               pt = _fmt(sp, Locale->c_fmt, t, pt, ptlim, &warn2);
+                               if (warn2 == IN_ALL)
+                                       warn2 = IN_THIS;
+                               if (warn2 > *warnp)
+                                       *warnp = warn2;
+                               }
+                               continue;
+                       case 'D':
+                               pt = _fmt(sp, "%m/%d/%y", t, pt, ptlim, warnp);
+                               continue;
+                       case 'd':
+                               pt = _conv(t->tm_mday, "%02d", pt, ptlim);
+                               continue;
+                       case 'E':
+                       case 'O':
+                               /*
+                               ** C99 locale modifiers.
+                               ** The sequences
+                               **      %Ec %EC %Ex %EX %Ey %EY
+                               **      %Od %oe %OH %OI %Om %OM
+                               **      %OS %Ou %OU %OV %Ow %OW %Oy
+                               ** are supposed to provide alternate
+                               ** representations.
+                               */
+                               goto label;
+                       case 'e':
+                               pt = _conv(t->tm_mday, "%2d", pt, ptlim);
+                               continue;
+                       case 'F':
+                               pt = _fmt(sp, "%Y-%m-%d", t, pt, ptlim, warnp);
+                               continue;
+                       case 'H':
+                               pt = _conv(t->tm_hour, "%02d", pt, ptlim);
+                               continue;
+                       case 'I':
+                               pt = _conv((t->tm_hour % 12) ?
+                                       (t->tm_hour % 12) : 12,
+                                       "%02d", pt, ptlim);
+                               continue;
+                       case 'j':
+                               pt = _conv(t->tm_yday + 1, "%03d", pt, ptlim);
+                               continue;
+                       case 'k':
+                               /*
+                               ** This used to be...
+                               **      _conv(t->tm_hour % 12 ?
+                               **              t->tm_hour % 12 : 12, 2, ' ');
+                               ** ...and has been changed to the below to
+                               ** match SunOS 4.1.1 and Arnold Robbins'
+                               ** strftime version 3.0. That is, "%k" and
+                               ** "%l" have been swapped.
+                               ** (ado, 1993-05-24)
+                               */
+                               pt = _conv(t->tm_hour, "%2d", pt, ptlim);
+                               continue;
+#ifdef KITCHEN_SINK
+                       case 'K':
+                               /*
+                               ** After all this time, still unclaimed!
+                               */
+                               pt = _add("kitchen sink", pt, ptlim);
+                               continue;
+#endif /* defined KITCHEN_SINK */
+                       case 'l':
+                               /*
+                               ** This used to be...
+                               **      _conv(t->tm_hour, 2, ' ');
+                               ** ...and has been changed to the below to
+                               ** match SunOS 4.1.1 and Arnold Robbin's
+                               ** strftime version 3.0. That is, "%k" and
+                               ** "%l" have been swapped.
+                               ** (ado, 1993-05-24)
+                               */
+                               pt = _conv((t->tm_hour % 12) ?
+                                       (t->tm_hour % 12) : 12,
+                                       "%2d", pt, ptlim);
+                               continue;
+                       case 'M':
+                               pt = _conv(t->tm_min, "%02d", pt, ptlim);
+                               continue;
+                       case 'm':
+                               pt = _conv(t->tm_mon + 1, "%02d", pt, ptlim);
+                               continue;
+                       case 'n':
+                               pt = _add("\n", pt, ptlim);
+                               continue;
+                       case 'p':
+                               pt = _add((t->tm_hour >= (HOURSPERDAY / 2)) ?
+                                       Locale->am_pm[1] :
+                                       Locale->am_pm[0],
+                                       pt, ptlim);
+                               continue;
+                       case 'R':
+                               pt = _fmt(sp, "%H:%M", t, pt, ptlim, warnp);
+                               continue;
+                       case 'r':
+                               pt = _fmt(sp, Locale->t_fmt_ampm, t, pt, ptlim,
+                                       warnp);
+                               continue;
+                       case 'S':
+                               pt = _conv(t->tm_sec, "%02d", pt, ptlim);
+                               continue;
+                       case 's':
+                               {
+                                       struct tm       tm;
+                                       char            buf[INT_STRLEN_MAXIMUM(
+                                                               time_t) + 1];
+                                       time_t          mkt;
+
+                                       tm = *t;
+                                       mkt = mktime(&tm);
+                                       /* CONSTCOND */
+                                       if (TYPE_SIGNED(time_t))
+                                               (void) snprintf(buf, sizeof(buf),
+                                                   "%lld", (long long) mkt);
+                                       else    (void) snprintf(buf, sizeof(buf),
+                                                   "%llu", (unsigned long long)
+                                                   mkt);
+                                       pt = _add(buf, pt, ptlim);
+                               }
+                               continue;
+                       case 'T':
+                               pt = _fmt(sp, "%H:%M:%S", t, pt, ptlim, warnp);
+                               continue;
+                       case 't':
+                               pt = _add("\t", pt, ptlim);
+                               continue;
+                       case 'U':
+                               pt = _conv((t->tm_yday + DAYSPERWEEK -
+                                       t->tm_wday) / DAYSPERWEEK,
+                                       "%02d", pt, ptlim);
+                               continue;
+                       case 'u':
+                               /*
+                               ** From Arnold Robbins' strftime version 3.0:
+                               ** "ISO 8601: Weekday as a decimal number
+                               ** [1 (Monday) - 7]"
+                               ** (ado, 1993-05-24)
+                               */
+                               pt = _conv((t->tm_wday == 0) ?
+                                       DAYSPERWEEK : t->tm_wday,
+                                       "%d", pt, ptlim);
+                               continue;
+                       case 'V':       /* ISO 8601 week number */
+                       case 'G':       /* ISO 8601 year (four digits) */
+                       case 'g':       /* ISO 8601 year (two digits) */
+/*
+** From Arnold Robbins' strftime version 3.0: "the week number of the
+** year (the first Monday as the first day of week 1) as a decimal number
+** (01-53)."
+** (ado, 1993-05-24)
+**
+** From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
+** "Week 01 of a year is per definition the first week which has the
+** Thursday in this year, which is equivalent to the week which contains
+** the fourth day of January. In other words, the first week of a new year
+** is the week which has the majority of its days in the new year. Week 01
+** might also contain days from the previous year and the week before week
+** 01 of a year is the last week (52 or 53) of the previous year even if
+** it contains days from the new year. A week starts with Monday (day 1)
+** and ends with Sunday (day 7). For example, the first week of the year
+** 1997 lasts from 1996-12-30 to 1997-01-05..."
+** (ado, 1996-01-02)
+*/
+                               {
+                                       int     year;
+                                       int     base;
+                                       int     yday;
+                                       int     wday;
+                                       int     w;
+
+                                       year = t->tm_year;
+                                       base = TM_YEAR_BASE;
+                                       yday = t->tm_yday;
+                                       wday = t->tm_wday;
+                                       for ( ; ; ) {
+                                               int     len;
+                                               int     bot;
+                                               int     top;
+
+                                               len = isleap_sum(year, base) ?
+                                                       DAYSPERLYEAR :
+                                                       DAYSPERNYEAR;
+                                               /*
+                                               ** What yday (-3 ... 3) does
+                                               ** the ISO year begin on?
+                                               */
+                                               bot = ((yday + 11 - wday) %
+                                                       DAYSPERWEEK) - 3;
+                                               /*
+                                               ** What yday does the NEXT
+                                               ** ISO year begin on?
+                                               */
+                                               top = bot -
+                                                       (len % DAYSPERWEEK);
+                                               if (top < -3)
+                                                       top += DAYSPERWEEK;
+                                               top += len;
+                                               if (yday >= top) {
+                                                       ++base;
+                                                       w = 1;
+                                                       break;
+                                               }
+                                               if (yday >= bot) {
+                                                       w = 1 + ((yday - bot) /
+                                                               DAYSPERWEEK);
+                                                       break;
+                                               }
+                                               --base;
+                                               yday += isleap_sum(year, base) ?
+                                                       DAYSPERLYEAR :
+                                                       DAYSPERNYEAR;
+                                       }
+#ifdef XPG4_1994_04_09
+                                       if ((w == 52 &&
+                                               t->tm_mon == TM_JANUARY) ||
+                                               (w == 1 &&
+                                               t->tm_mon == TM_DECEMBER))
+                                                       w = 53;
+#endif /* defined XPG4_1994_04_09 */
+                                       if (*format == 'V')
+                                               pt = _conv(w, "%02d",
+                                                       pt, ptlim);
+                                       else if (*format == 'g') {
+                                               *warnp = IN_ALL;
+                                               pt = _yconv(year, base, 0, 1,
+                                                       pt, ptlim);
+                                       } else  pt = _yconv(year, base, 1, 1,
+                                                       pt, ptlim);
+                               }
+                               continue;
+                       case 'v':
+                               /*
+                               ** From Arnold Robbins' strftime version 3.0:
+                               ** "date as dd-bbb-YYYY"
+                               ** (ado, 1993-05-24)
+                               */
+                               pt = _fmt(sp, "%e-%b-%Y", t, pt, ptlim, warnp);
+                               continue;
+                       case 'W':
+                               pt = _conv((t->tm_yday + DAYSPERWEEK -
+                                       (t->tm_wday ?
+                                       (t->tm_wday - 1) :
+                                       (DAYSPERWEEK - 1))) / DAYSPERWEEK,
+                                       "%02d", pt, ptlim);
+                               continue;
+                       case 'w':
+                               pt = _conv(t->tm_wday, "%d", pt, ptlim);
+                               continue;
+                       case 'X':
+                               pt = _fmt(sp, Locale->t_fmt, t, pt, ptlim, warnp);
+                               continue;
+                       case 'x':
+                               {
+                               int     warn2 = IN_SOME;
+
+                               pt = _fmt(sp, Locale->d_fmt, t, pt, ptlim, &warn2);
+                               if (warn2 == IN_ALL)
+                                       warn2 = IN_THIS;
+                               if (warn2 > *warnp)
+                                       *warnp = warn2;
+                               }
+                               continue;
+                       case 'y':
+                               *warnp = IN_ALL;
+                               pt = _yconv(t->tm_year, TM_YEAR_BASE, 0, 1,
+                                       pt, ptlim);
+                               continue;
+                       case 'Y':
+                               pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 1,
+                                       pt, ptlim);
+                               continue;
+                       case 'Z':
+#ifdef TM_ZONE
+                               if (t->TM_ZONE != NULL)
+                                       pt = _add(t->TM_ZONE, pt, ptlim);
+                               else
+#endif /* defined TM_ZONE */
+                               if (t->tm_isdst >= 0)
+                                       pt = _add((sp ?
+                                           tzgetname(sp, t->tm_isdst) :
+                                           tzname[t->tm_isdst != 0]),
+                                           pt, ptlim);
+                               /*
+                               ** C99 says that %Z must be replaced by the
+                               ** empty string if the time zone is not
+                               ** determinable.
+                               */
+                               continue;
+                       case 'z':
+                               {
+                               int             diff;
+                               char const *    sign;
+
+                               if (t->tm_isdst < 0)
+                                       continue;
+#ifdef TM_GMTOFF
+                               diff = (int)t->TM_GMTOFF;
+#else /* !defined TM_GMTOFF */
+                               /*
+                               ** C99 says that the UTC offset must
+                               ** be computed by looking only at
+                               ** tm_isdst. This requirement is
+                               ** incorrect, since it means the code
+                               ** must rely on magic (in this case
+                               ** altzone and timezone), and the
+                               ** magic might not have the correct
+                               ** offset. Doing things correctly is
+                               ** tricky and requires disobeying C99;
+                               ** see GNU C strftime for details.
+                               ** For now, punt and conform to the
+                               ** standard, even though it's incorrect.
+                               **
+                               ** C99 says that %z must be replaced by the
+                               ** empty string if the time zone is not
+                               ** determinable, so output nothing if the
+                               ** appropriate variables are not available.
+                               */
+#ifndef STD_INSPIRED
+                               if (t->tm_isdst == 0)
+#ifdef USG_COMPAT
+                                       diff = -timezone;
+#else /* !defined USG_COMPAT */
+                                       continue;
+#endif /* !defined USG_COMPAT */
+                               else
+#ifdef ALTZONE
+                                       diff = -altzone;
+#else /* !defined ALTZONE */
+                                       continue;
+#endif /* !defined ALTZONE */
+#else /* defined STD_INSPIRED */
+                               {
+                                       struct tm tmp;
+                                       time_t lct, gct;
+
+                                       /*
+                                       ** Get calendar time from t
+                                       ** being treated as local.
+                                       */
+                                       tmp = *t; /* mktime discards const */
+                                       lct = mktime(&tmp);
+
+                                       if (lct == (time_t)-1)
+                                               continue;
+
+                                       /*
+                                       ** Get calendar time from t
+                                       ** being treated as GMT.
+                                       **/
+                                       tmp = *t; /* mktime discards const */
+                                       gct = timegm(&tmp);
+
+                                       if (gct == (time_t)-1)
+                                               continue;
+
+                                       /* LINTED difference will fit int */
+                                       diff = (intmax_t)gct - (intmax_t)lct;
+                               }
+#endif /* defined STD_INSPIRED */
+#endif /* !defined TM_GMTOFF */
+                               if (diff < 0) {
+                                       sign = "-";
+                                       diff = -diff;
+                               } else  sign = "+";
+                               pt = _add(sign, pt, ptlim);
+                               diff /= SECSPERMIN;
+                               diff = (diff / MINSPERHOUR) * 100 +
+                                       (diff % MINSPERHOUR);
+                               pt = _conv(diff, "%04d", pt, ptlim);
+                               }
+                               continue;
+#if 0
+                       case '+':
+                               pt = _fmt(sp, Locale->date_fmt, t, pt, ptlim,
+                                       warnp);
+                               continue;
+#endif
+                       case '%':
+                       /*
+                       ** X311J/88-090 (4.12.3.5): if conversion char is
+                       ** undefined, behavior is undefined. Print out the
+                       ** character itself as printf(3) also does.
+                       */
+                       default:
+                               break;
+                       }
+               }
+               if (pt == ptlim)
+                       break;
+               *pt++ = *format;
+       }
+       return pt;
+}
+
+size_t
+strftime(char * const s, const size_t maxsize,
+    const char * const format, const struct tm * const t)
+{
+       tzset();
+       return strftime_z(NULL, s, maxsize, format, t);
+}
+
+static char *
+_conv(n, format, pt, ptlim)
+const int              n;
+const char * const     format;
+char * const           pt;
+const char * const     ptlim;
+{
+       char    buf[INT_STRLEN_MAXIMUM(int) + 1];
+
+       (void) snprintf(buf, sizeof(buf), format, n);
+       return _add(buf, pt, ptlim);
+}
+
+static char *
+_add(str, pt, ptlim)
+const char *           str;
+char *                 pt;
+const char * const     ptlim;
+{
+       while (pt < ptlim && (*pt = *str++) != '\0')
+               ++pt;
+       return pt;
+}
+
+/*
+** POSIX and the C Standard are unclear or inconsistent about
+** what %C and %y do if the year is negative or exceeds 9999.
+** Use the convention that %C concatenated with %y yields the
+** same output as %Y, and that %Y contains at least 4 bytes,
+** with more only if necessary.
+*/
+
+static char *
+_yconv(a, b, convert_top, convert_yy, pt, ptlim)
+const int              a;
+const int              b;
+const int              convert_top;
+const int              convert_yy;
+char *                 pt;
+const char * const     ptlim;
+{
+       register int    lead;
+       register int    trail;
+
+#define DIVISOR        100
+       trail = a % DIVISOR + b % DIVISOR;
+       lead = a / DIVISOR + b / DIVISOR + trail / DIVISOR;
+       trail %= DIVISOR;
+       if (trail < 0 && lead > 0) {
+               trail += DIVISOR;
+               --lead;
+       } else if (lead < 0 && trail > 0) {
+               trail -= DIVISOR;
+               ++lead;
+       }
+       if (convert_top) {
+               if (lead == 0 && trail < 0)
+                       pt = _add("-0", pt, ptlim);
+               else    pt = _conv(lead, "%02d", pt, ptlim);
+       }
+       if (convert_yy)
+               pt = _conv(((trail < 0) ? -trail : trail), "%02d", pt, ptlim);
+       return pt;
+}
+
+#ifdef LOCALE_HOME
+static struct lc_time_T *
+_loc(void)
+{
+       static const char       locale_home[] = LOCALE_HOME;
+       static const char       lc_time[] = "LC_TIME";
+       static char *           locale_buf;
+
+       int                     fd;
+       int                     oldsun; /* "...ain't got nothin' to do..." */
+       char *                  lbuf;
+       char *                  name;
+       char *                  p;
+       const char **           ap;
+       const char *            plim;
+       char                    filename[FILENAME_MAX];
+       struct stat             st;
+       size_t                  namesize;
+       size_t                  bufsize;
+
+       /*
+       ** Use localebuf.mon[0] to signal whether locale is already set up.
+       */
+       if (localebuf.mon[0])
+               return &localebuf;
+       name = setlocale(LC_TIME, (char *) NULL);
+       if (name == NULL || *name == '\0')
+               goto no_locale;
+       /*
+       ** If the locale name is the same as our cache, use the cache.
+       */
+       lbuf = locale_buf;
+       if (lbuf != NULL && strcmp(name, lbuf) == 0) {
+               p = lbuf;
+               for (ap = (const char **) &localebuf;
+                       ap < (const char **) (&localebuf + 1);
+                               ++ap)
+                                       *ap = p += strlen(p) + 1;
+               return &localebuf;
+       }
+       /*
+       ** Slurp the locale file into the cache.
+       */
+       namesize = strlen(name) + 1;
+       if (sizeof filename <
+               ((sizeof locale_home) + namesize + (sizeof lc_time)))
+                       goto no_locale;
+       oldsun = 0;
+       (void) sprintf(filename, "%s/%s/%s", locale_home, name, lc_time);
+       fd = open(filename, O_RDONLY);
+       if (fd < 0) {
+               /*
+               ** Old Sun systems have a different naming and data convention.
+               */
+               oldsun = 1;
+               (void) sprintf(filename, "%s/%s/%s", locale_home,
+                       lc_time, name);
+               fd = open(filename, O_RDONLY);
+               if (fd < 0)
+                       goto no_locale;
+       }
+       if (fstat(fd, &st) != 0)
+               goto bad_locale;
+       if (st.st_size <= 0)
+               goto bad_locale;
+       bufsize = namesize + st.st_size;
+       locale_buf = NULL;
+       lbuf = (lbuf == NULL) ? malloc(bufsize) : realloc(lbuf, bufsize);
+       if (lbuf == NULL)
+               goto bad_locale;
+       (void) strcpy(lbuf, name);
+       p = lbuf + namesize;
+       plim = p + st.st_size;
+       if (read(fd, p, (size_t) st.st_size) != st.st_size)
+               goto bad_lbuf;
+       if (close(fd) != 0)
+               goto bad_lbuf;
+       /*
+       ** Parse the locale file into localebuf.
+       */
+       if (plim[-1] != '\n')
+               goto bad_lbuf;
+       for (ap = (const char **) &localebuf;
+               ap < (const char **) (&localebuf + 1);
+                       ++ap) {
+                               if (p == plim)
+                                       goto bad_lbuf;
+                               *ap = p;
+                               while (*p != '\n')
+                                       ++p;
+                               *p++ = '\0';
+       }
+       if (oldsun) {
+               /*
+               ** SunOS 4 used an obsolescent format; see localdtconv(3).
+               ** c_fmt had the ``short format for dates and times together''
+               ** (SunOS 4 date, "%a %b %e %T %Z %Y" in the C locale);
+               ** date_fmt had the ``long format for dates''
+               ** (SunOS 4 strftime %C, "%A, %B %e, %Y" in the C locale).
+               ** Discard the latter in favor of the former.
+               */
+               localebuf.date_fmt = localebuf.c_fmt;
+       }
+       /*
+       ** Record the successful parse in the cache.
+       */
+       locale_buf = lbuf;
+
+       return &localebuf;
+
+bad_lbuf:
+       free(lbuf);
+bad_locale:
+       (void) close(fd);
+no_locale:
+       localebuf = C_time_locale;
+       locale_buf = NULL;
+       return &localebuf;
+}
+#endif /* defined LOCALE_HOME */
diff --git a/lib/nbsd_libc/time/strptime.3 b/lib/nbsd_libc/time/strptime.3
new file mode 100644 (file)
index 0000000..95843ac
--- /dev/null
@@ -0,0 +1,340 @@
+.\"    $NetBSD: strptime.3,v 1.27 2009/05/24 02:30:17 ginsbach Exp $
+.\"
+.\" Copyright (c) 1997, 1998, 2008 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This file was contributed to The NetBSD Foundation by Klaus Klein.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 24, 2009
+.Dt STRPTIME 3
+.Os
+.Sh NAME
+.Nm strptime
+.Nd converts a character string to a time value
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Ft char *
+.Fn strptime "const char * restrict buf" "const char * restrict format" "struct tm * restrict tm"
+.Sh DESCRIPTION
+The
+.Fn strptime
+function converts the character string pointed to by
+.Fa buf
+to values which are stored in the
+.Va tm
+structure pointed to by
+.Fa tm ,
+using the format specified by
+.Fa format .
+.Pp
+The
+.Fa format
+string consists of zero or more conversion specifications, whitespace
+characters as defined by
+.Fn isspace ,
+and ordinary characters.
+All ordinary characters in
+.Fa format
+are compared directly against the corresponding characters in
+.Fa buf ;
+comparisons which fail will cause
+.Fn strptime
+to fail.
+Whitespace characters in
+.Fa format
+match any number of whitespace characters in
+.Fa buf ,
+including none.
+.Pp
+A conversion specification consists of a percent sign
+.Ql %
+followed by one
+or two conversion characters which specify the replacement required.
+There must be white-space or other non-alphanumeric characters between any
+two conversion specifications.
+.Pp
+Conversion of alphanumeric strings (such as month and weekday names) is
+done without regard to case.
+Conversion specifications which cannot be matched will cause
+.Fn strptime
+to fail.
+.Pp
+The LC_TIME category defines the locale values for the conversion
+specifications.
+The following conversion specifications are supported:
+.Bl -tag -width "xxxx"
+.It Cm \&%a
+the day of week, using the locale's weekday names;
+either the abbreviated or full name may be specified.
+.It Cm \&%A
+the same as
+.Cm \&%a .
+.It Cm \&%b
+the month, using the locale's month names;
+either the abbreviated or full name may be specified.
+.It Cm \&%B
+the same as
+.Cm \&%b .
+.It Cm \&%c
+the date and time, using the locale's date and time format.
+.It Cm \&%C
+the century number [0,99];
+leading zeros are permitted but not required.
+This conversion should be used in conjunction with the \&%y conversion.
+.It Cm \&%d
+the day of month [1,31];
+leading zeros are permitted but not required.
+.It Cm \&%D
+the date as %m/%d/%y.
+.It Cm \&%e
+the same as
+.Cm \&%d .
+.It Cm \&%F
+the date as %Y-%m-%d
+(the ISO 8601 date format).
+.It Cm \&%g
+the year corresponding to the ISO week number, without the century.
+.Po
+A
+.Nx
+extension.
+.Pc
+.It Cm \&%G
+the year corresponding to the ISO week number, with the century.
+.Po
+A
+.Nx
+extension.
+.Pc
+.It Cm \&%h
+the same as
+.Cm \&%b .
+.It Cm \&%H
+the hour (24-hour clock) [0,23];
+leading zeros are permitted but not required.
+.It Cm \&%I
+the hour (12-hour clock) [1,12];
+leading zeros are permitted but not required.
+.It Cm \&%j
+the day number of the year [1,366];
+leading zeros are permitted but not required.
+.It Cm \&%k
+the same as
+.Cm \&%H .
+.It Cm \&%l
+the same as
+.Cm \&%I .
+.It Cm \&%m
+the month number [1,12];
+leading zeros are permitted but not required.
+.It Cm \&%M
+the minute [0,59];
+leading zeros are permitted but not required.
+.It Cm \&%n
+any white-space, including none.
+.It Cm \&%p
+the locale's equivalent of a.m. or p.m.
+.It Cm \&%r
+the time (12-hour clock) with %p, using the locale's time format.
+.It Cm \&%R
+the time as %H:%M.
+.It Cm \&%S
+the seconds [0,61];
+leading zeros are permitted but not required.
+.It Cm \&%s
+the number of seconds since the Epoch, UTC (see
+.Xr mktime 3 ) .
+.Po
+A
+.Nx
+extension.
+.Pc
+.It Cm \&%t
+any white-space, including none.
+.It Cm \&%T
+the time as %H:%M:%S.
+.It Cm \&%u
+the day of the week as a decimal number, where Monday = 1.
+.Po
+A
+.Nx
+extension.
+.Pc
+.It Cm \&%U
+the week number of the year (Sunday as the first day of the week)
+as a decimal number [0,53];
+leading zeros are permitted but not required.
+All days in a year preceding the first Sunday are considered to be in week 0.
+.It Cm \&%V
+the ISO 8601:1988 week number as a decimal number.
+If the week (starting on Monday) that contains January 1 has more than
+three days in the new year, then it is considered the first week of the
+year.
+If it has fewer than four days in the new year, then it is considered
+the last week of the previous year.
+Weeks are numbered from 1 to 53.
+.Po
+A
+.Nx
+extension.
+.Pc
+.It Cm \&%w
+the weekday as a decimal number [0,6], with 0 representing Sunday;
+leading zeros are permitted but not required.
+.It Cm \&%W
+the week number of the year (Monday as the first day of the week)
+as a decimal number [0,53];
+leading zeros are permitted but not required.
+All days in a year preceding the first Monday are considered to be in week 0.
+.It Cm \&%x
+the date, using the locale's date format.
+.It Cm \&%X
+the time, using the locale's time format.
+.It Cm \&%y
+the year within the 20th century [69,99] or the 21st century [0,68];
+leading zeros are permitted but not required.
+If specified in conjunction
+with \&%C, specifies the year [0,99] within that century.
+.It Cm \&%Y
+the year, including the century (i.e., 1996).
+.It Cm \&%z
+an ISO 8601 or RFC-2822 timezone specification.
+This is one of the following:
+the offset from
+Coordinated Universal Time
+.Pq Ql UTC
+specified as:
+.Dq [+-]hhmm ,
+.Dq [+-]hh:mm ,
+or
+.Dq [+-]hh ;
+.Ql UTC
+specified as:
+.Dq GMT
+.Pq Ql Greenwich Mean Time ,
+.Dq UT
+.Pq Ql Universal Time ,
+or
+.Dq Z
+.Pq Ql Zulu Time ;
+a three character US timezone specified as:
+.Dq EDT ,
+.Dq EST ,
+.Dq CDT ,
+.Dq CST ,
+.Dq MDT ,
+.Dq MST ,
+.Dq PDT ,
+or
+.Dq PST ,
+with the first letter standing for
+.Ql Eastern
+.Pq Dq E ,
+.Ql Central
+.Pq Dq C ,
+.Ql Mountain
+.Pq Dq M
+or
+.Ql Pacific
+.Pq Dq P ,
+and the second letter standing for
+.Ql Daylight
+.Po
+.Dq D
+or summer
+.Pc
+time
+or
+.Ql Standard
+.Pq Dq S
+time;
+a single letter military timezone specified as:
+.Dq A
+through
+.Dq I
+and
+.Dq K
+through
+.Dq Y .
+.Po
+A
+.Nx
+extension.
+.Pc
+.It Cm \&%Z
+timezone name or no characters when time zone information is unavailable.
+.Po
+A
+.Nx
+extension.
+.Pc
+.It Cm \&%%
+matches a literal `%'.
+No argument is converted.
+.El
+.Ss Modified conversion specifications
+For compatibility, certain conversion specifications can be modified
+by the
+.Cm E
+and
+.Cm O
+modifier characters to indicate that an alternative format or specification
+should be used rather than the one normally used by the unmodified
+conversion specification.
+As there are currently neither alternative formats
+nor specifications supported by the system, the behavior will be as if the
+unmodified conversion specification were used.
+.Pp
+Case is ignored when matching string items in
+.Fa buf ,
+such as month and weekday names.
+.Sh RETURN VALUES
+If successful, the
+.Fn strptime
+function returns a pointer to the character following the last character
+parsed.
+Otherwise, a null pointer is returned.
+.Sh SEE ALSO
+.Xr ctime 3 ,
+.Xr isspace 3 ,
+.Xr localtime 3 ,
+.Xr strftime 3
+.Sh STANDARDS
+The
+.Fn strptime
+function conforms to
+.St -xpg4 .
+.Sh BUGS
+The
+.Cm \&%Z
+format specifier only accepts timezone
+abbreviations of the local timezone,
+or the value
+.Dq GMT .
+This limitation is caused by the ambiguity
+of overloaded timezone abbreviations,
+for example EST is both Eastern Standard
+Time and Eastern Australia Summer Time.
diff --git a/lib/nbsd_libc/time/strptime.c b/lib/nbsd_libc/time/strptime.c
new file mode 100644 (file)
index 0000000..f043c52
--- /dev/null
@@ -0,0 +1,572 @@
+/*     $NetBSD: strptime.c,v 1.35 2009/12/14 20:45:02 matt Exp $       */
+
+/*-
+ * Copyright (c) 1997, 1998, 2005, 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code was contributed to The NetBSD Foundation by Klaus Klein.
+ * Heavily optimised by David Laight
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: strptime.c,v 1.35 2009/12/14 20:45:02 matt Exp $");
+#endif
+
+#include "namespace.h"
+#include <sys/localedef.h>
+#include <ctype.h>
+#include <locale.h>
+#include <string.h>
+#include <time.h>
+#include <tzfile.h>
+#include "private.h"
+
+#ifdef __weak_alias
+__weak_alias(strptime,_strptime)
+#endif
+
+#define        _ctloc(x)               (_CurrentTimeLocale->x)
+
+/*
+ * We do not implement alternate representations. However, we always
+ * check whether a given modifier is allowed for a certain conversion.
+ */
+#define ALT_E                  0x01
+#define ALT_O                  0x02
+#define        LEGAL_ALT(x)            { if (alt_format & ~(x)) return NULL; }
+
+static char gmt[] = { "GMT" };
+static char utc[] = { "UTC" };
+/* RFC-822/RFC-2822 */
+static const char * const nast[5] = {
+       "EST",    "CST",    "MST",    "PST",    "\0\0\0"
+};
+static const char * const nadt[5] = {
+       "EDT",    "CDT",    "MDT",    "PDT",    "\0\0\0"
+};
+
+static const u_char *conv_num(const unsigned char *, int *, uint, uint);
+static const u_char *find_string(const u_char *, int *, const char * const *,
+       const char * const *, int);
+
+
+char *
+strptime(const char *buf, const char *fmt, struct tm *tm)
+{
+       unsigned char c;
+       const unsigned char *bp, *ep;
+       int alt_format, i, split_year = 0, neg = 0, offs;
+       const char *new_fmt;
+
+       bp = (const u_char *)buf;
+
+       while (bp != NULL && (c = *fmt++) != '\0') {
+               /* Clear `alternate' modifier prior to new conversion. */
+               alt_format = 0;
+               i = 0;
+
+               /* Eat up white-space. */
+               if (isspace(c)) {
+                       while (isspace(*bp))
+                               bp++;
+                       continue;
+               }
+
+               if (c != '%')
+                       goto literal;
+
+
+again:         switch (c = *fmt++) {
+               case '%':       /* "%%" is converted to "%". */
+literal:
+                       if (c != *bp++)
+                               return NULL;
+                       LEGAL_ALT(0);
+                       continue;
+
+               /*
+                * "Alternative" modifiers. Just set the appropriate flag
+                * and start over again.
+                */
+               case 'E':       /* "%E?" alternative conversion modifier. */
+                       LEGAL_ALT(0);
+                       alt_format |= ALT_E;
+                       goto again;
+
+               case 'O':       /* "%O?" alternative conversion modifier. */
+                       LEGAL_ALT(0);
+                       alt_format |= ALT_O;
+                       goto again;
+
+               /*
+                * "Complex" conversion rules, implemented through recursion.
+                */
+               case 'c':       /* Date and time, using the locale's format. */
+                       new_fmt = _ctloc(d_t_fmt);
+                       goto recurse;
+
+               case 'D':       /* The date as "%m/%d/%y". */
+                       new_fmt = "%m/%d/%y";
+                       LEGAL_ALT(0);
+                       goto recurse;
+
+               case 'F':       /* The date as "%Y-%m-%d". */
+                       new_fmt = "%Y-%m-%d";
+                       LEGAL_ALT(0);
+                       goto recurse;
+
+               case 'R':       /* The time as "%H:%M". */
+                       new_fmt = "%H:%M";
+                       LEGAL_ALT(0);
+                       goto recurse;
+
+               case 'r':       /* The time in 12-hour clock representation. */
+                       new_fmt =_ctloc(t_fmt_ampm);
+                       LEGAL_ALT(0);
+                       goto recurse;
+
+               case 'T':       /* The time as "%H:%M:%S". */
+                       new_fmt = "%H:%M:%S";
+                       LEGAL_ALT(0);
+                       goto recurse;
+
+               case 'X':       /* The time, using the locale's format. */
+                       new_fmt =_ctloc(t_fmt);
+                       goto recurse;
+
+               case 'x':       /* The date, using the locale's format. */
+                       new_fmt =_ctloc(d_fmt);
+                   recurse:
+                       bp = (const u_char *)strptime((const char *)bp,
+                                                           new_fmt, tm);
+                       LEGAL_ALT(ALT_E);
+                       continue;
+
+               /*
+                * "Elementary" conversion rules.
+                */
+               case 'A':       /* The day of week, using the locale's form. */
+               case 'a':
+                       bp = find_string(bp, &tm->tm_wday, _ctloc(day),
+                                       _ctloc(abday), 7);
+                       LEGAL_ALT(0);
+                       continue;
+
+               case 'B':       /* The month, using the locale's form. */
+               case 'b':
+               case 'h':
+                       bp = find_string(bp, &tm->tm_mon, _ctloc(mon),
+                                       _ctloc(abmon), 12);
+                       LEGAL_ALT(0);
+                       continue;
+
+               case 'C':       /* The century number. */
+                       i = 20;
+                       bp = conv_num(bp, &i, 0, 99);
+
+                       i = i * 100 - TM_YEAR_BASE;
+                       if (split_year)
+                               i += tm->tm_year % 100;
+                       split_year = 1;
+                       tm->tm_year = i;
+                       LEGAL_ALT(ALT_E);
+                       continue;
+
+               case 'd':       /* The day of month. */
+               case 'e':
+                       bp = conv_num(bp, &tm->tm_mday, 1, 31);
+                       LEGAL_ALT(ALT_O);
+                       continue;
+
+               case 'k':       /* The hour (24-hour clock representation). */
+                       LEGAL_ALT(0);
+                       /* FALLTHROUGH */
+               case 'H':
+                       bp = conv_num(bp, &tm->tm_hour, 0, 23);
+                       LEGAL_ALT(ALT_O);
+                       continue;
+
+               case 'l':       /* The hour (12-hour clock representation). */
+                       LEGAL_ALT(0);
+                       /* FALLTHROUGH */
+               case 'I':
+                       bp = conv_num(bp, &tm->tm_hour, 1, 12);
+                       if (tm->tm_hour == 12)
+                               tm->tm_hour = 0;
+                       LEGAL_ALT(ALT_O);
+                       continue;
+
+               case 'j':       /* The day of year. */
+                       i = 1;
+                       bp = conv_num(bp, &i, 1, 366);
+                       tm->tm_yday = i - 1;
+                       LEGAL_ALT(0);
+                       continue;
+
+               case 'M':       /* The minute. */
+                       bp = conv_num(bp, &tm->tm_min, 0, 59);
+                       LEGAL_ALT(ALT_O);
+                       continue;
+
+               case 'm':       /* The month. */
+                       i = 1;
+                       bp = conv_num(bp, &i, 1, 12);
+                       tm->tm_mon = i - 1;
+                       LEGAL_ALT(ALT_O);
+                       continue;
+
+               case 'p':       /* The locale's equivalent of AM/PM. */
+                       bp = find_string(bp, &i, _ctloc(am_pm), NULL, 2);
+                       if (tm->tm_hour > 11)
+                               return NULL;
+                       tm->tm_hour += i * 12;
+                       LEGAL_ALT(0);
+                       continue;
+
+               case 'S':       /* The seconds. */
+                       bp = conv_num(bp, &tm->tm_sec, 0, 61);
+                       LEGAL_ALT(ALT_O);
+                       continue;
+
+#ifndef TIME_MAX
+#define TIME_MAX       INT64_MAX
+#endif
+               case 's':       /* seconds since the epoch */
+                       {
+                               time_t sse = 0;
+                               uint64_t rulim = TIME_MAX;
+
+                               if (*bp < '0' || *bp > '9') {
+                                       bp = NULL;
+                                       continue;
+                               }
+
+                               do {
+                                       sse *= 10;
+                                       sse += *bp++ - '0';
+                                       rulim /= 10;
+                               } while ((sse * 10 <= TIME_MAX) &&
+                                        rulim && *bp >= '0' && *bp <= '9');
+
+                               if (sse < 0 || (uint64_t)sse > TIME_MAX) {
+                                       bp = NULL;
+                                       continue;
+                               }
+
+                               if (localtime_r(&sse, tm) == NULL)
+                                       bp = NULL;
+                       }
+                       continue;
+
+               case 'U':       /* The week of year, beginning on sunday. */
+               case 'W':       /* The week of year, beginning on monday. */
+                       /*
+                        * XXX This is bogus, as we can not assume any valid
+                        * information present in the tm structure at this
+                        * point to calculate a real value, so just check the
+                        * range for now.
+                        */
+                        bp = conv_num(bp, &i, 0, 53);
+                        LEGAL_ALT(ALT_O);
+                        continue;
+
+               case 'w':       /* The day of week, beginning on sunday. */
+                       bp = conv_num(bp, &tm->tm_wday, 0, 6);
+                       LEGAL_ALT(ALT_O);
+                       continue;
+
+               case 'u':       /* The day of week, monday = 1. */
+                       bp = conv_num(bp, &i, 1, 7);
+                       tm->tm_wday = i % 7;
+                       LEGAL_ALT(ALT_O);
+                       continue;
+
+               case 'g':       /* The year corresponding to the ISO week
+                                * number but without the century.
+                                */
+                       bp = conv_num(bp, &i, 0, 99);
+                       continue;
+
+               case 'G':       /* The year corresponding to the ISO week
+                                * number with century.
+                                */
+                       do
+                               bp++;
+                       while (isdigit(*bp));
+                       continue;
+
+               case 'V':       /* The ISO 8601:1988 week number as decimal */
+                       bp = conv_num(bp, &i, 0, 53);
+                       continue;
+
+               case 'Y':       /* The year. */
+                       i = TM_YEAR_BASE;       /* just for data sanity... */
+                       bp = conv_num(bp, &i, 0, 9999);
+                       tm->tm_year = i - TM_YEAR_BASE;
+                       LEGAL_ALT(ALT_E);
+                       continue;
+
+               case 'y':       /* The year within 100 years of the epoch. */
+                       /* LEGAL_ALT(ALT_E | ALT_O); */
+                       bp = conv_num(bp, &i, 0, 99);
+
+                       if (split_year)
+                               /* preserve century */
+                               i += (tm->tm_year / 100) * 100;
+                       else {
+                               split_year = 1;
+                               if (i <= 68)
+                                       i = i + 2000 - TM_YEAR_BASE;
+                               else
+                                       i = i + 1900 - TM_YEAR_BASE;
+                       }
+                       tm->tm_year = i;
+                       continue;
+
+               case 'Z':
+                       tzset();
+                       if (strncmp((const char *)bp, gmt, 3) == 0) {
+                               tm->tm_isdst = 0;
+#ifdef TM_GMTOFF
+                               tm->TM_GMTOFF = 0;
+#endif
+#ifdef TM_ZONE
+                               tm->TM_ZONE = gmt;
+#endif
+                               bp += 3;
+                       } else {
+                               ep = find_string(bp, &i,
+                                                (const char * const *)tzname,
+                                                 NULL, 2);
+                               if (ep != NULL) {
+                                       tm->tm_isdst = i;
+#ifdef TM_GMTOFF
+                                       tm->TM_GMTOFF = -(timezone);
+#endif
+#ifdef TM_ZONE
+                                       tm->TM_ZONE = tzname[i];
+#endif
+                               }
+                               bp = ep;
+                       }
+                       continue;
+
+               case 'z':
+                       /*
+                        * We recognize all ISO 8601 formats:
+                        * Z    = Zulu time/UTC
+                        * [+-]hhmm
+                        * [+-]hh:mm
+                        * [+-]hh
+                        * We recognize all RFC-822/RFC-2822 formats:
+                        * UT|GMT
+                        *          North American : UTC offsets
+                        * E[DS]T = Eastern : -4 | -5
+                        * C[DS]T = Central : -5 | -6
+                        * M[DS]T = Mountain: -6 | -7
+                        * P[DS]T = Pacific : -7 | -8
+                        *          Military
+                        * [A-IL-M] = -1 ... -9 (J not used)
+                        * [N-Y]  = +1 ... +12
+                        */
+                       while (isspace(*bp))
+                               bp++;
+
+                       switch (*bp++) {
+                       case 'G':
+                               if (*bp++ != 'M')
+                                       return NULL;
+                               /*FALLTHROUGH*/
+                       case 'U':
+                               if (*bp++ != 'T')
+                                       return NULL;
+                               /*FALLTHROUGH*/
+                       case 'Z':
+                               tm->tm_isdst = 0;
+#ifdef TM_GMTOFF
+                               tm->TM_GMTOFF = 0;
+#endif
+#ifdef TM_ZONE
+                               tm->TM_ZONE = utc;
+#endif
+                               continue;
+                       case '+':
+                               neg = 0;
+                               break;
+                       case '-':
+                               neg = 1;
+                               break;
+                       default:
+                               --bp;
+                               ep = find_string(bp, &i, nast, NULL, 4);
+                               if (ep != NULL) {
+#ifdef TM_GMTOFF
+                                       tm->TM_GMTOFF = -5 - i;
+#endif
+#ifdef TM_ZONE
+                                       tm->TM_ZONE = __UNCONST(nast[i]);
+#endif
+                                       bp = ep;
+                                       continue;
+                               }
+                               ep = find_string(bp, &i, nadt, NULL, 4);
+                               if (ep != NULL) {
+                                       tm->tm_isdst = 1;
+#ifdef TM_GMTOFF
+                                       tm->TM_GMTOFF = -4 - i;
+#endif
+#ifdef TM_ZONE
+                                       tm->TM_ZONE = __UNCONST(nadt[i]);
+#endif
+                                       bp = ep;
+                                       continue;
+                               }
+
+                               if ((*bp >= 'A' && *bp <= 'I') ||
+                                   (*bp >= 'L' && *bp <= 'Y')) {
+#ifdef TM_GMTOFF
+                                       /* Argh! No 'J'! */
+                                       if (*bp >= 'A' && *bp <= 'I')
+                                               tm->TM_GMTOFF =
+                                                   ('A' - 1) - (int)*bp;
+                                       else if (*bp >= 'L' && *bp <= 'M')
+                                               tm->TM_GMTOFF = 'A' - (int)*bp;
+                                       else if (*bp >= 'N' && *bp <= 'Y')
+                                               tm->TM_GMTOFF = (int)*bp - 'M';
+#endif
+#ifdef TM_ZONE
+                                       tm->TM_ZONE = NULL; /* XXX */
+#endif
+                                       bp++;
+                                       continue;
+                               }
+                               return NULL;
+                       }
+                       offs = 0;
+                       for (i = 0; i < 4; ) {
+                               if (isdigit(*bp)) {
+                                       offs = offs * 10 + (*bp++ - '0');
+                                       i++;
+                                       continue;
+                               }
+                               if (i == 2 && *bp == ':') {
+                                       bp++;
+                                       continue;
+                               }
+                               break;
+                       }
+                       switch (i) {
+                       case 2:
+                               offs *= 100;
+                               break;
+                       case 4:
+                               i = offs % 100;
+                               if (i >= 60)
+                                       return NULL;
+                               /* Convert minutes into decimal */
+                               offs = (offs / 100) * 100 + (i * 50) / 30;
+                               break;
+                       default:
+                               return NULL;
+                       }
+                       if (neg)
+                               offs = -offs;
+                       tm->tm_isdst = 0;       /* XXX */
+#ifdef TM_GMTOFF
+                       tm->TM_GMTOFF = offs;
+#endif
+#ifdef TM_ZONE
+                       tm->TM_ZONE = NULL;     /* XXX */
+#endif
+                       continue;
+
+               /*
+                * Miscellaneous conversions.
+                */
+               case 'n':       /* Any kind of white-space. */
+               case 't':
+                       while (isspace(*bp))
+                               bp++;
+                       LEGAL_ALT(0);
+                       continue;
+
+
+               default:        /* Unknown/unsupported conversion. */
+                       return NULL;
+               }
+       }
+
+       return __UNCONST(bp);
+}
+
+
+static const u_char *
+conv_num(const unsigned char *buf, int *dest, uint llim, uint ulim)
+{
+       uint result = 0;
+       unsigned char ch;
+
+       /* The limit also determines the number of valid digits. */
+       uint rulim = ulim;
+
+       ch = *buf;
+       if (ch < '0' || ch > '9')
+               return NULL;
+
+       do {
+               result *= 10;
+               result += ch - '0';
+               rulim /= 10;
+               ch = *++buf;
+       } while ((result * 10 <= ulim) && rulim && ch >= '0' && ch <= '9');
+
+       if (result < llim || result > ulim)
+               return NULL;
+
+       *dest = result;
+       return buf;
+}
+
+static const u_char *
+find_string(const u_char *bp, int *tgt, const char * const *n1,
+               const char * const *n2, int c)
+{
+       int i;
+       unsigned int len;
+
+       /* check full name - then abbreviated ones */
+       for (; n1 != NULL; n1 = n2, n2 = NULL) {
+               for (i = 0; i < c; i++, n1++) {
+                       len = strlen(*n1);
+                       if (strncasecmp(*n1, (const char *)bp, len) == 0) {
+                               *tgt = i;
+                               return bp + len;
+                       }
+               }
+       }
+
+       /* Nothing matched */
+       return NULL;
+}
diff --git a/lib/nbsd_libc/time/time2posix.3 b/lib/nbsd_libc/time/time2posix.3
new file mode 100644 (file)
index 0000000..ddccea0
--- /dev/null
@@ -0,0 +1,150 @@
+.\"    $NetBSD: time2posix.3,v 1.17 2010/12/17 01:30:14 wiz Exp $
+.Dd December 4, 2010
+.Dt TIME2POSIX 3
+.Os
+.Sh NAME
+.Nm time2posix ,
+.Nm time2posix_z ,
+.Nm posix2time ,
+.Nm posix2time_z ,
+.Nd convert seconds since the Epoch
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Ft time_t
+.Fn time2posix "time_t t"
+.Ft time_t
+.Fn time2posix_z "const timezone_t tz" "time_t t"
+.Ft time_t
+.Fn posix2time "time_t t"
+.Ft time_t
+.Fn posix2time_z "const timezone_t tz" "time_t t"
+.Sh DESCRIPTION
+.St -p1003.1
+legislates that a
+.Va time_t
+value of 536457599 shall correspond to
+.Dl Wed Dec 31 23:59:59 UTC 1986 .
+This effectively implies that POSIX
+.Va time_t Ns 's
+cannot include leap seconds and, therefore,
+that the system time must be adjusted as each leap occurs.
+.Pp
+If the time package is configured with leap-second support
+enabled, however, no such adjustment is needed and
+.Va time_t
+values continue to increase over leap events
+(as a true `seconds since...' value).
+This means that these values will differ from those required by POSIX
+by the net number of leap seconds inserted since the Epoch.
+.Pp
+Typically this is not a problem as the type
+.Va time_t
+is intended to be (mostly)
+opaque \(em
+.Va time_t
+values should only be obtained-from and
+passed-to functions such as
+.Xr time 3 ,
+.Xr localtime 3 ,
+.Xr localtime_r 3 ,
+.Xr localtime_rz 3 ,
+.Xr mktime 3 ,
+.Xr mktime_z 3 ,
+and
+.Xr difftime 3 .
+However, POSIX gives an arithmetic expression for directly computing a
+.Va time_t
+value from a given date/time, and the same relationship is assumed by
+some (usually older) applications.
+Any programs creating/dissecting
+.Va time_t Ns 's
+using such a relationship will typically not handle intervals over
+leap seconds correctly.
+.Pp
+The
+.Fn time2posix ,
+.Fn time2posix_z ,
+.Fn posix2time ,
+and
+.Fn posix2time_z
+functions are provided to address this
+.Va time_t
+mismatch by converting between local
+.Va time_t
+values and their POSIX equivalents.
+This is done by accounting for the number of time-base changes that would
+have taken place on a POSIX system as leap seconds were inserted or deleted.
+These converted values can then be used in lieu of correcting the
+older applications, or when communicating with POSIX-compliant systems.
+.Pp
+.Fn time2posix
+and
+.Fn time2posix_z
+are single-valued.
+That is, every local
+.Va time_t
+corresponds to a single POSIX
+.Va time_t .
+.Fn posix2time
+and
+.Fn posix2time
+are less well-behaved: for a positive leap second hit the result is not
+unique, and for a negative leap second hit the corresponding POSIX
+.Va time_t
+doesn't exist so an adjacent value is returned.
+Both of these are good indicators of the inferiority of the POSIX
+representation.
+.Pp
+The
+.Dq z
+variants of the two functions behave exactly like their counterparts,
+but they operate in the given
+.Fa tz
+argument which was previously allocated using
+.Xr tzalloc 3
+and are re-entrant.
+.Pp
+The following table summarizes the relationship between a
+.Va time_t
+and its conversion to, and back from, the POSIX representation over
+the leap second inserted at the end of June, 1993.
+.Bl -column "93/06/30" "23:59:59" "A+0" "X=time2posix(T)" "posix2time(X)" -offset indent
+.It Sy DATE    TIME    T       X=time2posix(T) posix2time(X)
+.It 93/06/30   23:59:59        A+0     B+0     A+0
+.It 93/06/30   23:59:60        A+1     B+1     A+1 or A+2
+.It 93/07/01   00:00:00        A+2     B+1     A+1 or A+2
+.It 93/07/01   00:00:01        A+3     B+2     A+3
+.El
+.Pp
+A leap second deletion would look like...
+.Bl -column "??/06/30" "23:59:58" "A+0" "X=time2posix(T)" "posix2time(X)" -offset indent
+.It Sy DATE    TIME    T       X=time2posix(T) posix2time(X)
+.It ??/06/30   23:59:58        A+0     B+0     A+0
+.It ??/07/01   00:00:00        A+1     B+2     A+1
+.It ??/07/01   00:00:01        A+2     B+3     A+2
+.El
+[Note: posix2time(B+1) =\*[Gt] A+0 or A+1]
+.Pp
+If leap-second support is not enabled, local
+.Va time_t Ns 's
+and POSIX
+.Va time_t Ns 's
+are equivalent, and both
+.Fn time2posix
+and
+.Fn posix2time
+degenerate to the identity function.
+.Sh SEE ALSO
+.Xr difftime 3 ,
+.Xr localtime 3 ,
+.Xr localtime_r 3 ,
+.Xr localtime_rz 3 ,
+.Xr mktime 3 ,
+.Xr mktime_z 3 ,
+.Xr time 3 ,
+.Xr tzalloc 3
+.\" @(#)time2posix.3   7.7
+.\" This file is in the public domain, so clarified as of
+.\" 1996-06-05 by Arthur David Olson.
diff --git a/lib/nbsd_libc/time/tz-art.htm b/lib/nbsd_libc/time/tz-art.htm
new file mode 100644 (file)
index 0000000..cba330e
--- /dev/null
@@ -0,0 +1,417 @@
+<!DOCTYPE html
+PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+<meta http-equiv="Content-type" content='text/html; charset="US-ASCII"'>
+<title>Time and the Arts</title>
+</head>
+<body>
+<h1>Time and the Arts</h1>
+<address>
+@(#)tz-art.htm 8.13
+</address>
+<p>
+This file is in the public domain, so clarified as of
+2009-05-17 by Arthur David Olson.
+</p>
+<p>
+Please send corrections to this web page to the
+<a href="mailto:tz@elsie.nci.nih.gov">time zone mailing list</a>.</p>
+<p>
+See also <a href="tz-link.htm">Sources for Time Zone and Daylight Saving Time Data</a>.</p>
+<hr>
+<p>
+Data on recordings of "Save That Time," Russ Long, Serrob Publishing, BMI:</p>
+<table>
+<tr><td>Artist</td><td>Karrin Allyson</td></tr>
+<tr><td>CD</td><td>I Didn't Know About You</td></tr>
+<tr><td>Copyright Date</td><td>1993</td></tr>
+<tr><td>Label</td><td>Concord Jazz, Inc.</td></tr>
+<tr><td>ID</td><td>CCD-4543</td></tr>
+<tr><td>Track Time</td><td>3:44</td></tr>
+<tr><td>Personnel</td><td>Karrin Allyson, vocal;
+Russ Long, piano;
+Gerald Spaits, bass;
+Todd Strait, drums</td></tr>
+<tr><td>Notes</td><td>CD notes "additional lyric by Karrin Allyson;
+arranged by Russ Long and Karrin Allyson"</td></tr>
+<tr><td>ADO Rating</td><td>1 star</td></tr>
+<tr><td><a href="http://www.allmusic.com/cg/amg.dll?p=amg&amp;sql=A1fdovw9ta92k">AMG Rating</a></td><td>4 stars</td></tr>
+<tr><td>Penguin Rating</td><td>3.5 stars</td></tr>
+<tr><td>&nbsp;</td></tr>
+<tr><td>Artist</td><td>Kevin Mahogany</td></tr>
+<tr><td>CD</td><td>Double Rainbow</td></tr>
+<tr><td>Copyright Date</td><td>1993</td></tr>
+<tr><td>Label</td><td>Enja Records</td></tr>
+<tr><td>ID</td><td>ENJ-7097 2</td></tr>
+<tr><td>Track Time</td><td>6:27</td></tr>
+<tr><td>Personnel</td><td>Kevin Mahogany, vocal;
+Kenny Barron, piano;
+Ray Drummond, bass;
+Ralph Moore, tenor saxophone;
+Lewis Nash, drums</td></tr>
+<tr><td>ADO Rating</td><td>1.5 stars</td></tr>
+<tr><td><a href="http://www.allmusic.com/cg/amg.dll?p=amg&amp;sql=Akikbikzjbb19">AMG Rating</a></td><td>3 stars</td></tr>
+<tr><td>Penguin Rating</td><td>3 stars</td></tr>
+<tr><td>&nbsp;</td></tr>
+<tr><td>Artist</td><td>Joe Williams</td></tr>
+<tr><td>CD</td><td>Here's to Life</td></tr>
+<tr><td>Copyright Date</td><td>1994</td></tr>
+<tr><td>Label</td><td>Telarc International Corporation</td></tr>
+<tr><td>ID</td><td>CD-83357</td></tr>
+<tr><td>Track Time</td><td>3:58</td></tr>
+<tr><td>Personnel</td><td>Joe Williams, vocal
+The Robert Farnon [39 piece] Orchestra</td></tr>
+<tr><td>Notes</td><td>This CD is also available as part of a 3-CD package from
+Telarc, "Triple Play" (CD-83461)</td></tr>
+<tr><td>ADO Rating</td><td>black dot</td></tr>
+<tr><td><a href="http://www.allmusic.com/cg/amg.dll?p=amg&amp;sql=Amyyvad6kt8w1">AMG Rating</a></td><td>2 stars</td></tr>
+<tr><td>Penguin Rating</td><td>3 stars</td></tr>
+<tr><td>&nbsp;</td></tr>
+<tr><td>Artist</td><td>Charles Fambrough</td></tr>
+<tr><td>CD</td><td>Keeper of the Spirit</td></tr>
+<tr><td>Copyright Date</td><td>1995</td></tr>
+<tr><td>Label</td><td>AudioQuest Music</td></tr>
+<tr><td>ID</td><td>AQ-CD1033</td></tr>
+<tr><td>Track Time</td><td>7:07</td></tr>
+<tr><td>Personnel</td><td>Charles Fambrough, bass;
+Joel Levine, tenor recorder;
+Edward Simon, piano;
+Lenny White, drums;
+Marion Simon, percussion</td></tr>
+<tr><td>Notes</td><td>On-line information and samples available at
+<a href="http://wwmusic.com/~music/audioq/rel/1033.html">http://wwmusic.com/~music/audioq/rel/1033.html</a></td></tr>
+<tr><td>ADO Rating</td><td>2 stars</td></tr>
+<tr><td><a href="http://www.allmusic.com/cg/amg.dll?p=amg&amp;sql=A5rkcikcjbb89">AMG Rating</a></td><td>unrated</td></tr>
+<tr><td>Penguin Rating</td><td>3 stars</td></tr>
+</table>
+<hr>
+<p>Also of note:</p>
+<table>
+<tr><td>Artist</td><td>Holly Cole Trio</td></tr>
+<tr><td>CD</td><td>Blame It On My Youth</td></tr>
+<tr><td>Copyright Date</td><td>1992</td></tr>
+<tr><td>Label</td><td>Manhattan</td></tr>
+<tr><td>ID</td><td>CDP 7 97349 2</td></tr>
+<tr><td>Total Time</td><td>37:45</td></tr>
+<tr><td>Personnel</td><td>Holly Cole, voice;
+Aaron Davis, piano;
+David Piltch, string bass</td></tr>
+<tr><td>Notes</td><td>Lyrical reference to "Eastern Standard Time" in
+Tom Waits' "Purple Avenue"</td></tr>
+<tr><td>ADO Rating</td><td>2.5 stars</td></tr>
+<tr><td><a href="http://www.allmusic.com/cg/amg.dll?p=amg&amp;sql=A3a9ds37ya3dg">AMG Rating</a></td><td>3 stars</td></tr>
+<tr><td>Penguin Rating</td><td>unrated</td></tr>
+<tr><td>&nbsp;</td></tr>
+<tr><td>Artist</td><td>Milt Hinton</td></tr>
+<tr><td>CD</td><td>Old Man Time</td></tr>
+<tr><td>Copyright Date</td><td>1990</td></tr>
+<tr><td>Label</td><td>Chiaroscuro</td></tr>
+<tr><td>ID</td><td>CR(D) 310</td></tr>
+<tr><td>Total Time</td><td>149:38 (two CDs)</td></tr>
+<tr><td>Personnel</td><td>Milt Hinton, bass;
+Doc Cheatham, Dizzy Gillespie, Clark Terry, trumpet;
+Al Grey, trombone;
+Eddie Barefield, Joe Camel (Flip Phillips), Buddy Tate,
+clarinet and saxophone;
+John Bunch, Red Richards, Norman Simmons, Derek Smith,
+Ralph Sutton, piano;
+Danny Barker, Al Casey, guitar;
+Gus Johnson, Gerryck King, Bob Rosengarden, Jackie Williams,
+drums;
+Lionel Hampton, vibraphone;
+Cab Calloway, Joe Williams, vocal;
+Buck Clayton, arrangements</td></tr>
+<tr><td>Notes</td><td>tunes include Old Man Time, Time After Time,
+Sometimes I'm Happy,
+A Hot Time in the Old Town Tonight,
+Four or Five Times, Now's the Time,
+Time on My Hands, This Time It's Us,
+and Good Time Charlie
+On-line samples available at
+<a href="http://www.chiaroscurojazz.com/albuminfo.php4?albumid=49">http://www.chiaroscurojazz.com/albuminfo.php3?albumid=49</a></td></tr>
+<tr><td>ADO Rating</td><td>3 stars</td></tr>
+<tr><td><a href="http://www.allmusic.com/cg/amg.dll?p=amg&amp;sql=A1cbyxdab8ola">AMG Rating</a></td><td>4.5 stars</td></tr>
+<tr><td>Penguin Rating</td><td>3 stars</td></tr>
+<tr><td>&nbsp;</td></tr>
+<tr><td>Artist</td><td>Alan Broadbent</td></tr>
+<tr><td>CD</td><td>Pacific Standard Time</td></tr>
+<tr><td>Copyright Date</td><td>1995</td></tr>
+<tr><td>Label</td><td>Concord Jazz, Inc.</td></tr>
+<tr><td>ID</td><td>CCD-4664</td></tr>
+<tr><td>Total Time</td><td>62:42</td></tr>
+<tr><td>Personnel</td><td>Alan Broadbent, piano;
+Putter Smith, Bass;
+Frank Gibson, Jr., drums</td></tr>
+<tr><td>Notes</td><td>The CD cover features an analemma for equation-of-time fans</td></tr>
+<tr><td>ADO Rating</td><td>1 star</td></tr>
+<tr><td><a href="http://www.allmusic.com/cg/amg.dll?p=amg&amp;sql=Asl8zefuk8gfo">AMG Rating</a></td><td>4 stars</td></tr>
+<tr><td>Penguin Rating</td><td>3.5 stars</td></tr>
+<tr><td>&nbsp;</td></tr>
+<tr><td>Artist</td><td>Anthony Braxton/Richard Teitelbaum</td></tr>
+<tr><td>CD</td><td>Silence/Time Zones</td></tr>
+<tr><td>Copyright Date</td><td>1996</td></tr>
+<tr><td>Label</td><td>Black Lion</td></tr>
+<tr><td>ID</td><td>BLCD 760221</td></tr>
+<tr><td>Total Time</td><td>72:58</td></tr>
+<tr><td>Personnel</td><td>Anthony Braxton, sopranino and alto saxophones,
+contrebasse clarinet, miscellaneous instruments;
+Leo Smith, trumpet and miscellaneous instruments;
+Leroy Jenkins, violin and miscellaneous instruments;
+Richard Teitelbaum, modular moog and micromoog synthesizer</td></tr>
+<tr><td>ADO Rating</td><td>black dot</td></tr>
+<tr><td><a href="http://www.allmusic.com/cg/amg.dll?p=amg&amp;sql=A5bkvu3xjan1k">AMG Rating</a></td><td>unrated</td></tr>
+<tr><td>&nbsp;</td></tr>
+<tr><td>Artist</td><td>Charles Gayle</td></tr>
+<tr><td>CD</td><td>Time Zones</td></tr>
+<tr><td>Copyright Date</td><td>2006</td></tr>
+<tr><td>Label</td><td>Tompkins Square</td></tr>
+<tr><td>ID</td><td>TSQ2839</td></tr>
+<tr><td>Total Time</td><td>49:06</td></tr>
+<tr><td>Personnel</td><td>Charles Gayle, piano</td></tr>
+<tr><td>ADO Rating</td><td>1 star</td></tr>
+<tr><td><a href="http://www.allmusic.com/cg/amg.dll?p=amg&amp;sql=10:13rc28vw054a">AMG Rating</a></td><td>4.5 stars</td></tr>
+<tr><td>&nbsp;</td></tr>
+<tr><td>Artist</td><td>The Get Up Kids</td></tr>
+<tr><td>CD</td><td>Eudora</td></tr>
+<tr><td>Copyright Date</td><td>2001</td></tr>
+<tr><td>Label</td><td>Vagrant</td></tr>
+<tr><td>ID</td><td>357</td></tr>
+<tr><td>Total Time</td><td>65:12</td></tr>
+<tr><td>Notes</td><td>Includes the song "Central Standard Time." Thanks to Colin Bowern for this information.</td></tr>
+<tr><td><a href="http://www.allmusic.com/cg/amg.dll?p=amg&amp;sql=10:7ddovwvla9xk">AMG Rating</a></td><td>2.5 stars</td></tr>
+<tr><td>&nbsp;</td></tr>
+
+<tr><td>Artist</td><td>Coldplay</td></tr>
+<tr><td>Song</td><td>Clocks</td></tr>
+<tr><td>Copyright Date</td><td>2003</td></tr>
+<tr><td>Label</td><td>Capitol Records</td></tr>
+<tr><td>ID</td><td>52608</td></tr>
+<tr><td>Total Time</td><td>4:13</td></tr>
+<tr><td>Notes</td><td>Won the 2004 Record of the Year honor at the
+Grammy Awards. Co-written and performed by Chris Martin,
+great-great-grandson of DST inventor William Willett. The song's first
+line is "Lights go out and I can't be saved".</td></tr>
+<tr><td>&nbsp;</td></tr>
+
+<tr><td>Artist</td><td>Irving Kahal and Harry Richman</td></tr>
+<tr><td>Song</td><td>There Ought to be a Moonlight Saving Time</td></tr>
+<tr><td>Copyright Date</td><td>1931</td>
+<tr><td>Notes</td><td>This musical standard was a #1 hit for Guy Lombardo
+in 1931, and was also performed by Maurice Chevalier, Blossom Dearie
+and many others. The phrase "Moonlight saving time" also appears in
+the 1995 country song "Not Enough Hours in the Night" written by Aaron
+Barker, Kim Williams and Rob Harbin and performed by Doug
+Supernaw.</td></tr>
+<tr><td>&nbsp;</td></tr>
+
+<tr><td>Artist</td><td>The Microscopic Septet</td></tr>
+<tr><td>CD</td><td>Lobster Leaps In</td></tr>
+<tr><td>Copyright Date</td><td>2008</td></tr>
+<tr><td>Label</td><td>Cuneiform</td></tr>
+<tr><td>ID</td><td>272</td></tr>
+<tr><td>Total Time</td><td>73:05</td></tr>
+<tr><td>Notes</td><td>Includes the song "Twilight Time Zone."</td></tr>
+<tr><td><a href="http://www.allmusic.com/cg/amg.dll?p=amg&sql=10:w9fpxzykldje">AMG Rating</a></td><td>3.5 stars</td></tr>
+<tr><td>ADO Rating</td><td>2 stars</td></tr>
+
+<tr><td>&nbsp;</td></tr>
+
+<tr><td>Artist</td><td>Bob Dylan</td></tr>
+<tr><td>CD</td><td>The Time They Are A-Changin'</td></tr>
+<tr><td>Copyright Date</td><td>1964</td></tr>
+<tr><td>Label</td><td>Columbia</td></tr>
+<tr><td>ID</td><td>CK-8905</td></tr>
+<tr><td>Total Time</td><td>45:36</td></tr>
+<tr><td><a href="http://www.allmusic.com/cg/amg.dll?p=amg&sql=10:gifqxqt5ld0e">AMG Rating</a></td><td>4.5 stars</td></tr>
+<tr><td>ADO Rating</td><td>1.5 stars</td></tr>
+<tr><td>Notes<td>The title song is also available on "Bob Dylan's Greatest Hits" and "The Essential Bob Dylan."</td></tr>
+
+<tr><td>&nbsp;</td></tr>
+
+<tr><td>TV episode title</td><td>The Lost Hour</td>
+<tr><td>TV series</td><td><em>Eerie, Indiana</em></td>
+<tr><td>TV episode number</td><td>10</td>
+<tr><td>Network</td><td>NBC</td>
+<tr><td>Air date</td><td>1991-12-01</td>
+<tr><td>Notes</td><td>Despite Indiana's then-lack of DST, Marshall changes his clock with unusual consequences.</td></tr>
+<tr><td>&nbsp;</td></tr>
+
+<tr><td>TV episode title</td><td>Time Tunnel</td>
+<tr><td>TV series</td><td><em>The Adventures of Pete &amp; Pete</em></td>
+<tr><td>TV episode number</td><td>5, season 2</td>
+<tr><td>Network</td><td>Nickelodeon</td>
+<tr><td>Air date</td><td>1994-10-23</td>
+<tr><td>Notes</td><td>The two Petes travel back in time an hour on the day that DST ends.</td></tr>
+<tr><td>&nbsp;</td></tr>
+
+<tr><td>TV episode title</td><td>King-Size Homer</td>
+<tr><td>TV series</td><td><em>The Simpsons</em></td>
+<tr><td>TV episode number</td><td>135</td>
+<tr><td>Network</td><td>Fox</td>
+<tr><td>Air date</td><td>1995-11-05</td>
+<tr><td>Notes</td><td>Homer, working from home, remarks "8:58, first
+time I've ever been early for work. Except for all those daylight
+savings days. Lousy farmers."</td></tr>
+<tr><td>&nbsp;</td></tr>
+
+<tr><td>Artist</td><td>Jules Verne</td></tr>
+<tr><td>Book</td><td>Le Tour du Monde en Quatre-Vingts Jours
+(Around the World in Eighty Days)</td></tr>
+<tr><td>Notes</td><td>Wall-clock time plays a central role in the plot.
+European readers of the 1870s clearly held the U.S. press in
+deep contempt; the protagonists cross the U.S. without once
+reading a paper.
+An on-line French-language version of the book
+"with illustrations from the original 1873 French-language edition"
+is available at
+<a href="http://fourmilab.ch/etexts/www/tdm80j">http://fourmilab.ch/etexts/www/tdm80j</a>
+An on-line English-language translation of the book is available at
+<a href="http://www.literature.org/Works/Jules-Verne/eighty">http://www.literature.org/Works/Jules-Verne/eighty</a></td></tr>
+
+<tr><td>&nbsp;</td></tr>
+<tr><td>Artist</td><td>Umberto Eco</td></tr>
+<tr><td>Book</td><td>The Island of the Day Before
+(L'isola del giorno prima)</td></tr>
+<tr><td>Copyright Date</td><td>1994</td></tr>
+<tr><td>Notes</td><td>
+"...the story of a 17th century Italian nobleman trapped near an island
+on the International Date Line.  Time and time zones play an integral
+part in the novel." (Paul Eggert, 2006-04-22)
+</td></tr>
+<tr><td>&nbsp;</td></tr>
+<tr><td>Artist</td><td>David Jebb</td></tr>
+<tr><td>Book</td><td><a href="http://www.thethirteenthtimezone.com">
+The Thirteenth Time Zone</a></td></tr>
+<tr><td>Notes</td><td>
+"It's fiction, but it's based on his experiences and travels." (Paul Eggert, 2006-04-22)
+</td></tr>
+<tr><td>&nbsp;</td></tr>
+<tr><td>Artist</td><td>John Dunning</td></tr>
+<tr><td>Book</td><td><a
+href="http://www.simonsays.com/content/book.cfm?sid=33&amp;pid=479719">Two
+O'Clock, Eastern Wartime</a></td></tr>
+<tr><td>Copyright Date</td><td>2001</td></tr>
+<tr><td>Notes</td><td>
+Mystery, history, daylight saving time, and old-time radio.
+</td></tr>
+<tr><td>&nbsp;</td></tr>
+<tr><td>Film</td><td>Bell Science - About Time</td></tr>
+<tr><td>Notes</td><td>The Frank Baxter/Richard Deacon extravaganza.
+Information is available at
+<a href="http://www.videoflicks.com/titles/1035/1035893.htm">http://www.videoflicks.com/titles/1035/1035893.htm</a></td></tr>
+</table>
+<hr>
+<ul>
+<li>
+An episode of "The Adventures of Superman" entitled "The Mysterious
+Cube," first aired 1958-02-24, had Superman convincing the controllers
+of WWV to broadcast time signals five minutes ahead of actual time;
+doing so got a crook trying to beat the statute of limitations to
+emerge a bit too early from the titular enclosure.
+</li>
+<li>
+The 1960s ITC television series "The Prisoner" included an episode
+entitled "The Chimes of Big Ben" in which our protagonist tumbled to
+the fraudulent nature of a Poland-to-England escape upon hearing "Big
+Ben" chiming on Polish local time.
+</li>
+<li>
+The series "Seinfeld" included an episode entitled "The Susie," first
+broadcast 1997-02-13, in which Kramer decides that daylight saving time
+isn't coming fast enough, so he sets his watch ahead an hour.
+</li>
+<li>
+The syndicated comic strip "Dilbert" featured an all-too-rare example of
+time zone humor on 1998-03-14.
+</li>
+<li>
+Surrealist artist Guy Billout's work "Date Line" appeared on page 103
+of the 1999-11 Atlantic Monthly.
+</li>
+<li>
+"Gloom, Gloom, Go Away" by Walter Kirn appeared on page 106 of Time
+Magazine's 2002-11-11 issue; among other things, it proposed
+year-round DST as a way of lessening wintertime despair.
+</li>
+<li>
+The "20 Hours in America" episode of "The West Wing," first aired 2002-09-25,
+saw White House staffers stranded in Indiana; they thought they had time to
+catch Air Force One but were done in by intra-Indiana local time changes.
+</li>
+<li>
+"In what time zone would you find New York City?" was a $200 question on
+the 1999-11-13 United States airing of "Who Wants to Be a Millionaire?"
+"In 1883, what industry led the movement to divide the U.S. into four time
+zones?" was a $32,000 question on the 2001-05-23 United States airing of
+"Who Wants to Be a Millionaire?" At this rate, the million-dollar time-zone
+question should have been asked 2002-06-04.
+</li>
+<li>
+A private jet's mid-flight change of time zones distorts Alison Dubois'
+premonition in the "We Had a Dream" episode of "Medium"
+(originally aired 2007-02-28).
+</li>
+<li>
+In the 1946 "A Matter of Life and Death,"
+there is a reference to British Double Summer Time.
+The time does not play a large part in the plot;
+it's just a passing reference to the time when one of the
+characters was supposed to have died (but didn't).
+The IMDb page is at
+<a href="http://us.imdb.com/title/tt0038733/">
+http://us.imdb.com/title/tt0038733/
+</a>. (Dave Cantor)
+</li>
+</ul>
+<hr>
+<ul>
+<li>
+"We're been using the five-cent nickle in this country since 1492.
+Now that's pretty near 100 years, daylight savings [sic]."
+(Groucho Marx as Captain Spaulding in "Animal Crackers", 1930,
+as noted by Will Fitzerald)
+</li>
+<li>
+"Good news."
+"What did they do? Extend Daylight Saving Time year round?"
+(Professional tanner George Hamilton, in dialog from a
+May, 1999 episode of the syndicated television series "Baywatch")
+</li>
+<li>
+"A fundamental belief held by Americans is that if you are on land, you
+cannot be killed by a fish...So most Americans remain on land, believing
+they're safe. Unfortunately, this belief&mdash;like so many myths, such as that
+there's a reason for 'Daylight Saving Time'&mdash;is false."
+(Dave Barry column, 2000-07-02)
+</li>
+<li>
+"I once had sex for an hour and five minutes, but that was on the day
+when you turn the clocks ahead."
+(Garry Shandling, 52nd Annual Emmys, 2000-09-10)
+</li>
+<li>
+"Would it impress you if I told you I invented Daylight Savings Time?"
+("Sahjhan" to "Lilah" in dialog from the "Loyalty" episode of "Angel,"
+originally aired 2002-02-25)
+</li>
+<li>
+"I thought you said Tulsa was a three hour flight."
+"Well, you're forgetting about the time difference."
+("Chandler" and "Joey" in dialog from the episode of "Friends" first
+aired 2002-12-05)
+</li>
+<li>
+"Is that a pertinent fact,
+or are you trying to dazzle me with your command of time zones?"
+(Kelsey Grammer as "Frasier Crane")
+</li>
+<li>
+"Don't worry about the world coming to an end today.
+It is already tomorrow in Australia."
+(Charles M. Schulz, provided by Steve Summit)
+</li>
+</ul>
+</body>
+</html>
diff --git a/lib/nbsd_libc/time/tz-link.htm b/lib/nbsd_libc/time/tz-link.htm
new file mode 100644 (file)
index 0000000..fe58bf7
--- /dev/null
@@ -0,0 +1,648 @@
+<!DOCTYPE html
+       PUBLIC "-//W3C//DTD HTML 4.01//EN"
+       "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+<title>Sources for Time Zone and Daylight Saving Time Data</title>
+<link rel="schema.DC" href="http://purl.org/DC/elements/1.1/">
+<meta http-equiv="Content-type" content='text/html; charset="US-ASCII"'>
+<meta name="DC.Creator" content="Eggert, Paul">
+<meta name="DC.Contributor" content="Olson, Arthur David">
+<meta name="DC.Date" content="2007-12-26">
+<meta name="DC.Description"
+ content="Sources of information about time zones and daylight saving time">
+<meta name="DC.Identifier" content="http://www.twinsun.com/tz/tz-link.htm">
+<meta name="Keywords"
+ content="database,daylight saving,DST,time zone,timezone,tz,zoneinfo">
+</head>
+<body>
+<h1>Sources for Time Zone and Daylight Saving Time Data</h1>
+<address>
+@(#)tz-link.htm        8.22
+</address>
+<p>
+This file is in the public domain, so clarified as of
+2009-05-17 by Arthur David Olson.
+</p>
+<p>
+Please send corrections to this web page to the
+<a href="mailto:tz@elsie.nci.nih.gov">time zone mailing list</a>.</p>
+<h2>The <code>tz</code> database</h2>
+<p>
+The <a href="http://en.wikipedia.org/wiki/Public_domain">public-domain</a>
+time zone database contains code and data
+that represent the history of local time
+for many representative locations around the globe.
+It is updated periodically to reflect changes made by political bodies
+to <a href="http://en.wikipedia.org/wiki/Time_zone">time zone</a>
+boundaries, <a
+href="http://en.wikipedia.org/wiki/Coordinated_Universal_Time"><abbr
+title="Coordinated Universal Time">UTC</abbr></a> offsets, and
+<a href="http://en.wikipedia.org/wiki/Daylight_saving">daylight-saving</a>
+rules.
+This database (often called <code>tz</code> or <a
+href="http://en.wikipedia.org/wiki/Zoneinfo"><code>zoneinfo</code></a>)
+is used by several implementations,
+including
+<a href="http://www.gnu.org/software/libc/">the
+<abbr title="GNU's Not Unix">GNU</abbr>
+C Library</a> used in
+<a href="http://www.linux.org/"><abbr>GNU</abbr>/Linux</a>,
+<a href="http://www.freebsd.org/">FreeBSD</a>,
+<a href="http://netbsd.org/">NetBSD</a>,
+<a href="http://openbsd.org/">OpenBSD</a>,
+<a href="http://cygwin.com/">Cygwin</a>,
+<a href="http://www.delorie.com/djgpp/"><abbr
+title="DJ's GNU Programming Platform">DJGPP</abbr></a>,
+<a href="http://ibm.com/aix">AIX</a>,
+<a href="http://www.apple.com/macosx/">Mac OS X</a>,
+<a href="http://h71000.www7.hp.com/">OpenVMS</a>,
+<a href="http://oracle.com/database">Oracle Database</a>,
+<a href="http://sun.com/software/solaris">Solaris</a>,
+<a href="http://h30097.www3.hp.com/">Tru64</a>, and
+<a href="http://sco.com/products/unixware">UnixWare</a>.</p>
+<p>
+Each location in the database represents a national region where all
+clocks keeping local time have agreed since 1970.
+Locations are identified by continent or ocean and then by the name of
+the location, which is typically the largest city within the region.
+For example, <code>America/New_York</code>
+represents most of the <abbr title="United States">US</abbr> eastern time zone;
+<code>America/Phoenix</code> represents most of Arizona, which
+uses mountain time without daylight saving time (<abbr
+title="daylight saving time">DST</abbr>);
+<code>America/Detroit</code> represents most of Michigan, which uses
+eastern time but with different <abbr>DST</abbr> rules in 1975;
+and other entries represent smaller regions like Starke County,
+Indiana, which switched from central to eastern time in 1991
+and switched back in 2006.
+To use the database on an extended <a
+href="http://en.wikipedia.org/wiki/POSIX"><abbr
+title="Portable Operating System Interface">POSIX</abbr></a>
+implementation set the <code>TZ</code> environment variable to
+the location's full name, e.g., <code>TZ="America/New_York"</code>.</p>
+<p>
+In the <code>tz</code> database's
+<a href="ftp://elsie.nci.nih.gov/pub"><abbr
+title="File Transfer Protocol">FTP</abbr> distribution</a>
+the code is in the file <code>tzcode<var>C</var>.tar.gz</code>,
+where <code><var>C</var></code> is the code's version;
+similarly, the data are in <code>tzdata<var>D</var>.tar.gz</code>,
+where <code><var>D</var></code> is the data's version.
+The following <a
+href="http://en.wikipedia.org/wiki/Unix_shell">shell</a> commands download
+these files to a <abbr>GNU</abbr>/Linux or similar host;
+see the downloaded
+<code>README</code> file for what to do next.</p>
+<pre style="margin-left: 2em"><code><a href="http://www.gnu.org/software/wget/">wget</a> 'ftp://elsie.nci.nih.gov/pub/tz*.tar.gz'
+<a href="http://www.gnu.org/software/gzip/">gzip</a> -dc tzcode*.tar.gz | <a href="http://www.gnu.org/software/tar/">tar</a> -xf -
+gzip -dc tzdata*.tar.gz | tar -xf -
+</code></pre>
+<p>
+The code lets you compile the <code>tz</code> source files into
+machine-readable binary files, one for each location. It also lets
+you read a <code>tz</code> binary file and interpret time stamps for that
+location.</p>
+<p>
+The data are by no means authoritative. If you find errors, please
+send changes to the <a href="mailto:tz@elsie.nci.nih.gov">time zone
+mailing list</a>. You can also <a
+href="http://news.gmane.org/gmane.comp.time.tz">browse recent
+messages</a> sent to the mailing list, <a
+href="mailto:tz-request@elsie.nci.nih.gov">subscribe</a> to it,
+retrieve the <a
+href="ftp://elsie.nci.nih.gov/pub/tzarchive.gz">full archive of old
+messages</a> (in gzip compressed format), or retrieve <a
+href="ftp://munnari.oz.au/pub/oldtz">archived older versions of code
+and data</a>.</p>
+<p>
+The Web has several other sources for time zone and daylight saving time data.
+Here are some recent links that may be of interest.
+</p>
+<h2>Web pages using recent versions of the <code>tz</code> database</h2>
+<p>
+These are listed roughly in ascending order of complexity and fanciness.
+</p>
+<ul>
+<li><a href="http://twiki.org/cgi-bin/xtra/tzdatepick.html">Date and Time Gateway</a>
+lets you see the <code>TZ</code> values directly.</li>
+<li><a
+href="http://convertit.com/Go/ConvertIt/World_Time/Current_Time.ASP">Current
+Time in 1000 Places</a> uses descriptions of the values.</li>
+<li><a href="http://www.timezoneconverter.com/">Time Zone Converter</a>
+uses a pulldown menu.</li>
+<li><a href="http://home.tiscali.nl/~t876506/TZworld.html">Complete
+timezone information for all countries</a> displays tables of DST rules.
+<li><a href="http://timeanddate.com/worldclock/">The World Clock -
+Time Zones</a> lets you sort zone names and convert times.</li>
+<li><a href="http://daylight-savings-time.info/">Graphical Display of
+Time Zones and Daylight Saving Times</a> shows a graph of time
+difference versus time for any pair of locations.</li>
+<li>The <a href="http://worldtimeengine.com/">World Time Engine</a>
+also contains data about time zone boundaries; it supports queries via place
+names and shows location maps.</li>
+</ul>
+<h2>Other time zone database formats</h2>
+<ul>
+<li>The <a href="ftp://ftp.rfc-editor.org/in-notes/rfc2445.txt">
+Internet Calendaring and Scheduling Core Object Specification
+(iCalendar)</a>, Internet <abbr title="Request For
+Comments">RFC</abbr> 2445, published by the (now-concluded) <a
+href="http://ietf.org/html.charters/OLD/calsch-charter.html"><abbr
+title="Internet Engineering Task Force">IETF</abbr>
+Calendaring and Scheduling Working Group (<abbr
+title="Calendaring and Scheduling Working Group">calsch</abbr>)</a>
+covers time zone
+data; see its VTIMEZONE calendar component.
+The <a href="http://calconnect.org/">Calendaring and Scheduling
+Consortium</a> is promoting further work in this area. <a
+href="http://calconnect.org/publications/icalendartimezoneproblemsandrecommendationsv1.0.pdf">iCalendar
+TIMEZONE Problems and Recommendations</a> offers guidelines and
+recommendations for the use of VTIMEZONE and <code>tz</code>.</li>
+<li><a href="http://calconnect.org/dstlinks.shtml">Extended Daylight
+Saving Time Links, Advisories and Changes</a> lists vendor material on recent
+daylight saving time changes.</li>
+<li><a
+href="http://calconnect.org/publications/timezoneregistryandservicerecommendationsv1.0.pdf">Timezone
+Registry and Service Recommendations</a> discusses a
+strategy for defining and deploying a time zone
+registration process that would establish unique names for each
+version of each <code>tz</code> zone, along with a polygonal
+representation of the geographical area corresponding to the
+zone.</li>
+<li>The <a
+href="http://lists.w3.org/Archives/Public/www-rdf-calendar/">www-rdf-calendar</a>
+list discusses <a
+href="http://www.w3.org/RDF/"><abbr
+title="Resource Description Framework">RDF</abbr></a>-based calendar
+and group scheduling systems, and has a <a
+href="http://www.w3.org/2002/12/cal/#tzd">workspace on time zone
+data</a> converted from <code>tz</code>. An earlier <a
+href="http://www.w3.org/2000/01/foo">schema</a> was sketched out.</li>
+</ul>
+<h2>Other <code>tz</code> compilers</h2>
+<ul>
+<li><a href="http://www.dachaplin.dsl.pipex.com/vzic/">Vzic iCalendar
+Timezone Converter</a> describes a <a
+href="http://en.wikipedia.org/wiki/C_%28programming_language%29">C</a>
+program that compiles
+<code>tz</code> source into iCalendar-compatible VTIMEZONE files.
+Vzic is freely
+available under the <a
+href="http://www.gnu.org/copyleft/gpl.html"><abbr>GNU</abbr>
+General Public License (<abbr
+title="General Public License">GPL</abbr>)</a>.</li>
+<li><a href="http://sourceforge.net/projects/tzical">tziCal - tz
+database conversion utility</a> is like Vzic, except for the <a
+href="http://msdn.microsoft.com/netframework">.NET framework</a>.</li>
+<li><a
+href="http://search.cpan.org/dist/DateTime-TimeZone/">DateTime::TimeZone</a>
+contains a script <code>parse_olson</code> that compiles
+<code>tz</code> source into <a href="http://www.perl.org/">Perl</a>
+modules. It is part of the Perl <a
+href="http://datetime.perl.org/">DateTime Project</a>, which is freely
+available under both the <abbr>GPL</abbr> and the Perl Artistic
+License. DateTime::TimeZone also contains a script
+<code>tests_from_zdump</code> that generates test cases for each clock
+transition in the <code>tz</code> database.</li>
+<li><a href="http://icu-project.org/">International Components for
+Unicode (<abbr>ICU</abbr>)</a> contains C/C++ and <a
+href="http://en.wikipedia.org/wiki/Java_%28programming_language%29">Java</a>
+libraries for internationalization that
+has a compiler from <code>tz</code> source
+into an <abbr>ICU</abbr>-specific format.
+<abbr>ICU</abbr> is freely available under a
+<abbr title="Berkeley Software Distribution">BSD</abbr>-style license.</li>
+<li><a href="http://joda-time.sourceforge.net/">Joda Time - Java date
+and time <abbr title="Application Program Interface">API</abbr></a>
+contains a class
+<code>org.joda.time.tz.ZoneInfoCompiler</code> that compiles
+<code>tz</code> source into a Joda-specific binary format. Joda Time
+is freely available under a <abbr>BSD</abbr>-style license.</li>
+<li><a href="http://pytz.sourceforge.net">PyTZ - Python Time
+Zone Library</a> compiles <code>tz</code> source into
+<a href="http://python.org/">Python</a>.
+It is freely available under a <abbr>BSD</abbr>-style license.</li>
+<li><a href="http://tzinfo.rubyforge.org/">TZInfo - Ruby Timezone Library</a>
+compiles <code>tz</code> source into
+<a href="http://ruby-lang.org">Ruby</a>.
+It is freely available under the <abbr
+title="Massachusetts Institute of Technology">MIT</abbr> license.</li>
+<li>The <a href="http://chronos-st.org/">Chronos Date/Time
+Library</a> is a <a href="http://smalltalk.org">Smalltalk</a> class
+library that compiles <code>tz</code> source into a <a
+href="http://date-time-zone.com/">time zone repository</a> whose format
+is either proprietary or an <a href="http://www.w3.org/XML/"><abbr
+title="Extensible Markup Language">XML</abbr></a>-encoded
+representation.</li>
+<li>Starting with version 8.5, <a href="http://tcl.tk/">Tcl</a>
+contains a developer-oriented parser that compiles <samp>tz</samp>
+source into text files, along with a runtime that can read those
+files. Tcl is freely available under a <abbr>BSD</abbr>-style
+license.</li>
+</ul>
+<h2>Other <code>tz</code> binary file readers</h2>
+<ul>
+<li>The <a
+href="http://www.gnu.org/software/libc/"><abbr>GNU</abbr> C
+Library</a>
+has an independent, thread-safe implementation of
+a <code>tz</code> binary file reader.
+This library is freely available under the
+<a href="http://www.gnu.org/copyleft/lesser.html">
+<abbr>GNU</abbr> Lesser General Public License
+(<abbr title="Lesser General Public License">LGPL</abbr>)</a>,
+and is widely used in <abbr>GNU</abbr>/Linux systems.</li>
+<li><a href="http://bmsi.com/java/#TZ">ZoneInfo.java</a>
+is a <code>tz</code> binary file reader written in Java.
+It is freely available under the <abbr>LGPL</abbr>.</li>
+<li>Tcl, mentioned above, also contains a
+<code>tz</code> binary file reader.</li>
+</ul>
+<h2>Other <code>tz</code>-based time zone software</h2>
+<ul>
+<li><a href="http://stemhaus.com/firefox/foxclocks/">FoxClocks</a>
+is an extension for <a
+href="http://developer.mozilla.org/en/docs/Toolkit_API">Mozilla
+Toolkit</a> applications like <a
+href="http://mozilla.com/firefox">Firefox</a>, <a
+href="http://mozilla.com/thunderbird">Thunderbird</a>, and
+<a
+href="http://www.mozilla.org/projects/calendar/sunbird/">Sunbird</a>.
+It displays multiple clocks in the application window, and has a mapping
+interface to <a href="http://earth.google.com/">Google Earth</a>.
+It is freely available under the <abbr>GPL</abbr>.</li>
+<li><a
+href="http://users.skynet.be/Peter.Verthez/projects/intclock/">International
+clock (intclock)</a> is a multi-timezone clock for
+<abbr>GNU</abbr>/Linux and similar systems. It is freely available
+under the <abbr>GPL</abbr>.</li>
+<li><a href="http://codeplex.com/publicdomain">PublicDomain</a>
+has a copy of a recent <code>tz</code> database, accessed via a <a
+href="http://en.wikipedia.org/wiki/C_Sharp">C#</a> library. As its
+name suggests, it is in the public domain. Only current time stamps
+are well supported; historical data are compiled into the runtime but
+are not easily accessible.</li>
+<li><a href="http://java.sun.com/">Sun Java</a> releases since 1.4
+contain a copy of a subset of a recent <code>tz</code> database in a
+Java-specific format.</li>
+<li><a href="http://kimmo.suominen.com/sw/timezone/">Time Zone</a> is
+a <a href="http://wordpress.org/">WordPress</a> plugin. It is freely
+available under a <abbr>BSD</abbr>-style license.</li>
+<li><a
+href="http://veladg.com/velaterra.html">VelaTerra</a> is
+a Mac OS X program. Its developers
+<a href="http://veladg.com/tzoffer.html">offer free
+licenses</a> to <code>tz</code> contributors.</li>
+<li><a
+href="http://worldtimeexplorer.com/">World Time Explorer</a> is a
+Microsoft Windows program.</li>
+</ul>
+<h2>Other time zone databases</h2>
+<ul>
+<li><a href="http://www.astro.com/cgi/aq.cgi">Atlas Query</a>
+is Astrodienst's Web version of Shanks's
+excellent time zone history atlases published in both <a
+href="http://astrocom.com/products/software.php?software_id=ibmwboth">computer</a>
+and book form (<a
+href="http://astrocom.com/products/book.php?book_id=b110x">one volume
+for the USA</a>, and <a
+href="http://astrocom.com/products/book.php?book_id=b112x">one for
+other locations</a>) by <a
+href="http://astrocom.com/">Astro Communications Services</a>.</li>
+<li><a href="http://worldtime.com/">WORLDTIME: interactive atlas,
+time info, public holidays</a>
+contains information on local time, sunrise and sunset,
+and public holidays in several hundred cities around the world.</li>
+<li><a href="http://worldtimeserver.com/">World Time Server</a>
+is another time zone database.</li>
+<li><a href="http://tycho.usno.navy.mil/tzones.html">World Time Zones</a>
+contains data from the Time Service Department of the
+<abbr>US</abbr> Naval Observatory, used as the source
+for the <code>usno*</code> files in the <code>tz</code> distribution.</li>
+<li>The <a href="http://iata.org/ps/publications/SSIM.htm">Standard
+Schedules Information Manual</a> of the
+<a href="http://iata.org/index.htm">International Air Transport
+Association</a>
+gives current time zone rules for airports served by commercial aviation.</li>
+<li>Some Microsoft Windows versions contain time zone information in
+an undocumented format, with IDs that can be mapped to <code>TZ</code>
+values using the <a
+href="http://unicode.org/cldr/data/diff/supplemental/windows_tzid.html">Windows
+&rarr; Tzid table</a> maintained by the <abbr
+title="Common Locale Data Repository">CLDR</abbr> data mentioned
+below.</li>
+</ul>
+<h2>Maps</h2>
+<ul>
+<li>The <a href="https://www.cia.gov/">United States Central
+Intelligence Agency (<abbr
+title="Central Intelligence Agency">CIA</abbr>)</a> publishes a <a
+href="https://www.cia.gov/library/publications/the-world-factbook/reference_maps/pdf/time_zones.pdf">time
+zone map</a>; the
+<a
+href="http://www.lib.utexas.edu/maps/world.html">Perry-Casta&ntilde;eda
+Library Map Collection</a>
+of the University of Texas at Austin has copies of
+recent editions.
+The pictorial quality is good,
+but the maps do not indicate summer time,
+and parts of the data are a few years out of date.</li>
+<li><a href="http://worldtimezone.com/">Current time around the world
+and standard time zones map of the world</a>
+has several fancy time zone maps; it covers Russia particularly well.
+The maps' pictorial quality is not quite as good as the
+<abbr>CIA</abbr>'s
+but the maps are more up to date.</li>
+</ul>
+<h2>Time zone boundaries</h2>
+<ul>
+<li><a href="http://efele.net/maps/tz/">TZ timezone maps</a> contains a <a
+href="http://en.wikipedia.org/wiki/Shapefile">shapefile</a> of the
+<code>tz</code> regions in the world.</li>
+<li><a href="http://statoids.com/statoids.html">Administrative Divisions
+of Countries ("Statoids")</a> contains detailed lists of
+<code>tz</code>-related zone subdivision data.</li>
+<li><a href="http://home.tiscali.nl/~t876506/Multizones.html">Time
+zone boundaries for multizone countries</a> summarizes legal
+boundaries between time zones within countries.</li>
+<li>Manifold.net's <a
+href="http://www.manifold.net/download/freemaps.html">Free Maps and
+<abbr title="Geographic Information Systems">GIS</abbr>
+Data</a> includes a Manifold-format map of
+world time zone boundaries distributed under the
+<abbr>GPL</abbr>.</li>
+<li>The <abbr>US</abbr> Geological Survey's National Atlas of
+the United States
+publishes the <a href="http://nationalatlas.gov/mld/timeznp.html">Time
+Zones of the United States</a> in the public domain.</li>
+<li>The GeoCommunity lists several commercial sources for <a
+href="http://spatialnews.geocomm.com/features/timezones/">International
+Time Zones and Time Zone Data</a>.</li>
+<li>A ship within the <a
+href="http://en.wikipedia.org/wiki/Territorial_waters">territorial
+waters</a> of any nation uses that nation's time. In international
+waters, time zone boundaries are meridians 15&deg; apart, except that
+UTC&minus;12 and UTC+12 are each 7.5&deg; wide and are separated by
+the 180&deg; meridian (not by the International Date Line, which is
+for land and territorial waters only). A captain can change ship's
+clocks any time after entering a new time zone; midnight changes are
+common.</li>
+</ul>
+<h2>Civil time concepts and history</h2>
+<ul>
+<li><a href="http://physics.nist.gov/GenInt/Time/time.html">A
+Walk through Time</a>
+surveys the evolution of timekeeping.</li>
+<li><a href="http://webexhibits.org/daylightsaving/">About Daylight
+Saving Time - History, rationale, laws &amp; dates</a>
+is an overall history of <abbr>DST</abbr>.</li>
+<li><a href="http://energy.ca.gov/daylightsaving.html">Saving Time,
+Saving Energy</a> discusses a primary justification for <abbr>DST</abbr>.</li>
+<li><a href="http://seizethedaylight.com/dst/">Who Knew? A Brief
+History of Daylight Saving Time</a> summarizes some of the contentious
+history of <abbr>DST</abbr>.</li>
+<li><a href="http://toi.iriti.cnr.it/">The
+Time of Internet</a>
+describes time zones and daylight saving time,
+with diagrams.
+The time zone map is out of date, however.</li>
+<li><a href="http://www.phys.uu.nl/~vgent/idl/idl.htm">A History of
+the International Date Line</a> tells the story of the most important
+time zone boundary.</li>
+<li><a href="http://statoids.com/tconcept.html">Basic Time
+Zone Concepts</a> discusses terminological issues behind time zones.</li>
+</ul>
+<h2>National histories of legal time</h2>
+<dl>
+<dt>Australia</dt>
+<dd>The Parliamentary Library has commissioned <a
+href="http://www.aph.gov.au/LIBRARY/Pubs/rn/2006-07/07rn13.pdf">research
+note on daylight saving time in Australia</a>.
+The Bureau of Meteorology publishes a list of
+<a href="http://www.bom.gov.au/climate/averages/tables/dst_times.shtml">Implementation Dates of Daylight Savings Time within Australia</a>.</dd>
+<dt>Belgium</dt>
+<dd>The Royal Observatory of Belgium maintains a table of <a
+href="http://www.astro.oma.be/GENERAL/INFO/nli001a.html"
+hreflang="nl">time in Belgium (in Dutch)</a>.</dd>
+<dt>Brazil</dt>
+<dd>The Time Service Department of the National Observatory
+records <a href="http://pcdsh01.on.br/DecHV.html"
+hreflang="pt-BR">Brazil's daylight saving time decrees (in
+Portuguese)</a>.</dd>
+<dt>Canada</dt>
+<dd>The Institute for National Measurement Standards publishes current
+and some older information about <a
+href="http://inms-ienm.nrc-cnrc.gc.ca/time_services/daylight_saving_e.html">Time
+Zones &amp; Daylight Saving Time</a>.</dd>
+<dt>Chile</dt>
+<dd>The Chilean Hydrographic and Oceanographic Service publishes a <a
+href="http://www.horaoficial.cl/horaof.htm" hreflang="es"> history of
+official time (in Spanish)</a>.</dd>
+<dt>Germany</dt>
+<dd>The National Institute for Science and Technology maintains the <a
+href="http://www.ptb.de/en/org/4/44/441/dars_e.htm">Realisation of
+Legal Time in Germany</a>.</dd>
+<dt>Israel</dt>
+<dd>The Interior Ministry periodically issues <a
+href="ftp://ftp.cs.huji.ac.il/pub/tz/announcements"
+hreflang="he">announcements (in Hebrew)</a>.</dd>
+<dt>Mexico</dt>
+<dd>The Investigation and Analysis Service of the Mexican Library of
+Congress has published a <a
+href="http://www.cddhcu.gob.mx/bibliot/publica/inveyana/polisoc/horver/"
+hreflang="es">history of Mexican local time (in Spanish)</a>.</dd>
+<dt>Malaysia</dt>
+<dd>See Singapore below.</dd>
+<dt>Netherlands</dt>
+<dd><a href="http://www.phys.uu.nl/~vgent/wettijd/wettijd.htm"
+hreflang="nl">Legal time in the Netherlands (in Dutch)</a>
+covers the history of local time in the Netherlands from ancient times.</dd>
+<dt>New Zealand</dt>
+<dd>The Department of Internal Affairs maintains a brief history <a
+href="http://dia.govt.nz/diawebsite.nsf/wpg_URL/Resource-material-Information-We-Provide-About-Daylight-Saving">About
+Daylight Saving</a>. The privately-maintained <a
+href="http://astrologyschool.com/nztime.html">History of New Zealand
+time</a> has more details.</dd>
+<dt>Norway</dt>
+<dd>The Norwegian Meteorological Institute lists
+<a href="http://met.no/met/met_lex/q_u/sommertid.html" hreflang="no">Summer
+time in Norway (in Norwegian)</a>, citing the
+Institute of Theoretical Astrophysics, Oslo.</dd>
+<dt>Singapore</dt>
+<dd><a
+href="http://www.math.nus.edu.sg/aslaksen/teaching/timezone.html">Why
+is Singapore in the "Wrong" Time Zone?</a> details the
+history of legal time in Singapore and Malaysia.</dd>
+<dt>United Kingdom</dt>
+<dd><a
+href="http://www.srcf.ucam.org/~jsm28/british-time/">History of
+legal time in Britain</a> discusses in detail the country
+with perhaps the best-documented history of clock adjustments.
+The National Physical Laboratory also maintains an <a
+href="http://www.npl.co.uk/server.php?show=ConWebDoc.2714">Archive
+of Summer time dates</a>.</dd>
+</dl>
+<h2>Precision timekeeping</h2>
+<ul>
+<li><a
+href="http://literature.agilent.com/litweb/pdf/5965-7984E.pdf">The
+Science of Timekeeping</a> is a thorough introduction
+to the theory and practice of precision timekeeping.</li>
+<li><a href="http://www.ntp.org/"><abbr
+title="Network Time Protocol">NTP</abbr>: The Network
+Time Protocol</a>
+discusses how to synchronize clocks of
+Internet hosts.</li>
+<li><a
+href="ftp://ftp.rfc-editor.org/in-notes/rfc4833.txt">Timezone
+Options for <abbr title="Dynamic Host Configuration Protocol">DHCP</abbr></a>
+(Internet <abbr>RFC</abbr> 4833)
+specifies a <a
+href="http://www.dhcp.org/">DHCP</a> option for a server to configure
+a client's time zone and daylight saving settings automatically.</li>
+<li><a href="http://gauss.gge.unb.ca/GMT.UT.and.the.RGO.html">A Few
+Facts Concerning <abbr title="Greenwich Mean Time">GMT</abbr>, <abbr
+title="Universal Time">UT</abbr>, and
+the <abbr title="Royal Greenwich Observatory">RGO</abbr></a>
+answers questions like "What is the
+difference between <abbr>GMT</abbr> and <abbr>UTC</abbr>?"</li>
+<li><a
+href="http://www.cv.nrao.edu/~rfisher/Ephemerides/times.html">Astronomical
+Times</a> explains more abstruse astronomical time scales like
+<abbr title="Terrestrial Dynamic Time">TDT</abbr>,
+<abbr title="Geocentric Coordinate Time">TCG</abbr>, and
+<abbr title="Barycentric Dynamic Time">TDB</abbr>.
+<a href="http://www.ucolick.org/~sla/leapsecs/timescales.html">Time
+Scales</a> goes into more detail, particularly for historical variants.</li>
+<li>The <a href="http://iau.org/"><abbr
+title="International Astronomical Union">IAU</abbr></a>'s <a
+href="http://www.iau-sofa.rl.ac.uk/"><abbr
+title="Standards Of Fundamental Astronomy">SOFA</abbr></a>
+initiative publishes Fortran
+code for converting among time scales like
+<abbr title="International Atomic Time">TAI</abbr>,
+<abbr>TDB</abbr>, <abbr>TDT</abbr> and
+<abbr>UTC</abbr>.</li>
+<li><a href="http://jpl.nasa.gov/basics/bsf2-3.htm">Basics of
+Space Flight - Reference Systems - Time Conventions</a>
+briefly explains interplanetary space flight timekeeping.</li>
+<li><a
+href="http://www.giss.nasa.gov/tools/mars24/help/notes.html">Technical
+Notes on Mars Solar Time as Adopted by the Mars24 Sunclock</a> briefly
+describes Mars Coordinated Time (<abbr
+title="Mars Coordinated Time">MTC</abbr>) and the
+diverse local time
+scales used by each landed mission on Mars.</li>
+<li><a href="http://leapsecond.com/">LeapSecond.com</a> is
+dedicated not only to leap seconds but to precise time and frequency
+in general. It covers the state of the art in amateur timekeeping, and
+how the art has progressed over the past few decades.</li>
+<li><a
+href="http://hpiers.obspm.fr/eop-pc/products/bulletins/bulletins.html">Bulletins
+maintained by the
+<abbr title="International Earth Rotation Service">IERS</abbr>
+<abbr title="Earth Orientation Parameters">EOP</abbr>
+(<abbr title="Product Center">PC</abbr>)</a> contains official publications of
+the Earth Orientation Parameters Product Center of the
+International Earth Rotation Service, the committee that decides
+when leap seconds occur.</li>
+<li>The <a
+href="http://six.pairlist.net/mailman/listinfo/leapsecs">Leap
+Second Discussion List</a> covers <a
+href="http://gauss.gge.unb.ca/papers.pdf/gpsworld.november99.pdf">McCarthy
+and Klepczynski's proposal to discontinue leap seconds</a>,
+discussed further in
+<a href="http://www.cl.cam.ac.uk/~mgk25/time/metrologia-leapsecond.pdf">The
+leap second: its history and possible future</a>.
+The (now disbanded) <a href="http://members.aas.org/comms/leap.cfm"><abbr
+title="American Astronomical Society">AAS</abbr> Leap Second
+Committee</a> has solicited input on this proposal.
+<a href="http://www.ucolick.org/~sla/leapsecs/">The
+Future of Leap Seconds</a> covers this
+contentious issue.</li>
+</ul>
+<h2>Time notation</h2>
+<ul>
+<li>
+<a href="http://www.cl.cam.ac.uk/~mgk25/iso-time.html">A Summary of
+the International Standard Date and Time Notation</a> is a good
+summary of
+<a
+href="http://www.iso.org/iso/en/CatalogueDetailPage.CatalogueDetail?CSNUMBER=40874"><abbr
+title="International Organization for Standardization">ISO</abbr>
+8601:2004 -- Data elements and interchange formats -- Information
+interchange -- Representation of dates and times</a>.</li>
+<li>
+<a href="http://www.w3.org/TR/xmlschema-2/#dateTime"><abbr>XML</abbr>
+Schema: Datatypes - dateTime</a> specifies a format inspired by
+<abbr>ISO</abbr> 8601 that is in common use in XML data.</li>
+<li>
+<a href="ftp://ftp.rfc-editor.org/in-notes/rfc2822.txt">Internet
+Message Format</a> (Internet <abbr>RFC</abbr> 2822) &sect;3.3
+specifies the time notation used in email and <a
+href="ftp://ftp.rfc-editor.org/in-notes/rfc2616.txt"><abbr>HTTP</abbr></a>
+headers.</li>
+<li>
+<a href="ftp://ftp.rfc-editor.org/in-notes/rfc3339.txt">Date and Time
+on the Internet: Timestamps</a> (Internet <abbr>RFC</abbr> 3339)
+specifies an <abbr>ISO</abbr> 8601
+profile for use in new Internet
+protocols.</li>
+<li>
+<a href="http://www.hackcraft.net/web/datetime/">Date &amp; Time
+Formats on the Web</a> surveys web- and Internet-oriented date and time
+formats.</li>
+<li>
+<a href="http://exit109.com/~ghealton/y2k/yrexamples.html">The
+Best of Dates, the Worst of Dates</a> covers many problems encountered
+by software developers when handling dates and time stamps.</li>
+<li>The <a
+href="http://unicode.org/cldr/">Unicode Common Locale Data Repository
+(<abbr>CLDR</abbr>) Project</a> has localizations for time zone names,
+abbreviations, identifiers, and formats. For example, it contains
+French translations for "Eastern European Summer Time", "<abbr
+title="Eastern European Summer Time">EEST</abbr>", and
+"Bucharest". <a
+href="http://unicode.org/cldr/data/charts/by_type/names.metazone.html">By-Type
+Chart: names.metazone</a> shows these values for many locales.
+<abbr>ICU</abbr> contains a mechanism for using this data.</li>
+<li>Alphabetic time zone abbreviations should not be used as unique
+identifiers for <abbr>UTC</abbr> offsets as they are ambiguous in
+practice. For example, "<abbr>EST</abbr>" denotes 5 hours behind
+<abbr>UTC</abbr> in English-speaking North America, but it denotes 10
+or 11 hours ahead of <abbr>UTC</abbr> in Australia; and
+French-speaking North Americans prefer
+"<abbr title="Heure Normale de l'Est">HNE</abbr>" to
+"<abbr>EST</abbr>". For <abbr>POSIX</abbr> the <code>tz</code>
+database contains English abbreviations for all time stamps but in
+many cases these are merely inventions of the database
+maintainers.</li>
+<li>Numeric time zone abbreviations typically count hours east of
+<abbr>UTC</abbr>, e.g., <code>+09</code> for Japan and
+<code>-10</code> for Hawaii. However, the <abbr>POSIX</abbr>
+<code>TZ</code> environment variable uses the opposite convention. For
+example, one might use <code>TZ="JST-9"</code> and
+<code>TZ="HST10"</code> for Japan and Hawaii, respectively. If the
+<code>tz</code> database is available, it is usually better to use
+settings like <code>TZ="Asia/Tokyo"</code> and
+<code>TZ="Pacific/Honolulu"</code> instead, as this should avoid
+confusion, handle old time stamps better, and insulate you better from
+any future changes to the rules. One should never set
+<abbr>POSIX</abbr> <code>TZ</code> to a value like
+<code>"GMT-9"</code>, though, since this would falsely claim that
+local time is nine hours ahead of <abbr>UTC</abbr> and the time zone
+is called "<abbr>GMT</abbr>".</li>
+</ul>
+<h2>Related indexes</h2>
+<ul>
+<li><a href="tz-art.htm">Time and the Arts</a></li>
+<li><a href="http://www.dmoz.org/Reference/Time/">Open Directory -
+Reference: Time</a></li>
+<li><a href="http://directory.google.com/Top/Reference/Time/">Google Directory
+- Reference &gt; Time</a></li>
+<li><a href="http://dir.yahoo.com/Science/Measurements_and_Units/Time">Yahoo!
+Directory &gt; Science &gt; Measurements and Units &gt; Time</a></li>
+</ul>
+</body>
+</html>
diff --git a/lib/nbsd_libc/time/tzcode2netbsd b/lib/nbsd_libc/time/tzcode2netbsd
new file mode 100755 (executable)
index 0000000..e08e182
--- /dev/null
@@ -0,0 +1,33 @@
+#! /bin/sh
+
+#
+# $NetBSD: tzcode2netbsd,v 1.5 2004/05/27 20:33:31 kleink Exp $
+#
+# Convert an extracted tzcode distribution into the format suitable
+# for importing it into the NetBSD source tree.
+# Last updated for: tzcode2004a.
+# 
+
+NOIMPORT="Makefile
+       date.1 date.1.txt date.c
+       gccdiffs
+       itca.jpg
+       logwtmp.c
+       newctime.3.txt
+       newstrftime.3 newstrftime.3.txt
+       newtzset.3.txt
+       time2posix.3.txt
+       tzfile.5.txt
+       tzselect.8.txt
+       usno1988 usno1989 usno1989a usno1995 usno1997 usno1998
+       zdump.8.txt
+       zic.8.txt"
+
+NEWTONORMAL="ctime.3
+       tzset.3"
+
+rm -f ${NOIMPORT}
+
+for f in ${NEWTONORMAL}; do
+       mv new${f} ${f};
+done
diff --git a/lib/nbsd_libc/time/tzfile.5 b/lib/nbsd_libc/time/tzfile.5
new file mode 100644 (file)
index 0000000..efb8d52
--- /dev/null
@@ -0,0 +1,159 @@
+.\"    $NetBSD: tzfile.5,v 1.15 2010/01/08 23:14:13 joerg Exp $
+.\"
+.\" @(#)tzfile.5       7.11
+.\" This file is in the public domain, so clarified as of
+.\" 1996-06-05 by Arthur David Olson (arthur_david_olson@nih.gov).
+.Dd September 16, 2001
+.Dt TZFILE 5
+.Os
+.Sh NAME
+.Nm tzfile
+.Nd time zone information
+.Sh SYNOPSIS
+.In tzfile.h
+.Sh DESCRIPTION
+The time zone information files used by
+.Xr tzset 3
+begin with the magic characters
+.Dq TZif
+to identify them as time zone information files,
+followed by a character identifying the version of the file's format
+(as of 2005, either an ASCII NUL or a '2')
+followed by fifteen bytes containing zeroes reserved for future use,
+followed by six four-byte values of type
+.Fa long ,
+written in a
+.Dq standard
+byte order (the high-order byte of the value is written first).
+These values are, in order:
+.Bl -tag -width XXXXXX -compact
+.It Va tzh_ttisgmtcnt
+The number of UTC/local indicators stored in the file.
+.It Va tzh_ttisstdcnt
+The number of standard/wall indicators stored in the file.
+.It Va tzh_leapcnt
+The number of leap seconds for which data is stored in the file.
+.It Va tzh_timecnt
+The number of
+.Dq transition times
+for which data is stored in the file.
+.It Va tzh_typecnt
+The number of
+.Dq local time types
+for which data is stored in the file (must not be zero).
+.It Va tzh_charcnt
+The number of characters of "time zone abbreviation strings"
+stored in the file.
+.El
+.Pp
+The above header is followed by
+.Va tzh_timecnt
+four-byte values of type
+.Fa long ,
+sorted in ascending order.
+These values are written in
+.Dq standard
+byte order.
+Each is used as a transition time (as returned by
+.Xr time 3 )
+at which the rules for computing local time change.
+Next come
+.Va tzh_timecnt
+one-byte values of type
+.Fa unsigned char ;
+each one tells which of the different types of
+.Dq local time
+types described in the file is associated with the same-indexed
+transition time.
+These values serve as indices into an array of
+.Fa ttinfo
+structures (with
+.Va tzh_typecnt
+entries) that appears next in the file;
+these structures are defined as follows:
+.Bd -literal
+struct ttinfo {
+       long    tt_gmtoff;
+       int     tt_isdst;
+       unsigned int    tt_abbrind;
+};
+.Ed
+Each structure is written as a four-byte value for
+.Va tt_gmtoff
+of type
+.Fa long ,
+in a standard byte order, followed by a one-byte value for
+.Va tt_isdst
+and a one-byte value for
+.Va tt_abbrind .
+In each structure,
+.Va tt_gmtoff
+gives the number of seconds to be added to UTC,
+.Va tt_isdst
+tells whether
+.Va tm_isdst
+should be set by
+.Xr localtime 3
+and
+.Va tt_abbrind
+serves as an index into the array of time zone abbreviation characters
+that follow the
+.Va ttinfo
+structure(s) in the file.
+.Pp
+Then there are
+.Va tzh_leapcnt
+pairs of four-byte values, written in standard byte order;
+the first value of each pair gives the time
+(as returned by
+.Xr time 3 )
+at which a leap second occurs;
+the second gives the
+.Em total
+number of leap seconds to be applied after the given time.
+The pairs of values are sorted in ascending order by time.
+.Pp
+Then there are
+.Va tzh_ttisstdcnt
+standard/wall indicators, each stored as a one-byte value;
+they tell whether the transition times associated with local time types
+were specified as standard time or wall clock time,
+and are used when a time zone file is used in handling POSIX-style
+time zone environment variables.
+.Pp
+Finally there are
+.Va tzh_ttisgmtcnt
+UTC/local indicators, each stored as a one-byte value;
+they tell whether the transition times associated with local time types
+were specified as UTC or local time,
+and are used when a time zone file is used in handling POSIX-style
+time zone environment variables.
+.Pp
+.Xr localtime 3
+uses the first standard-time
+.Fa ttinfo
+structure in the file
+(or simply the first
+.Fa ttinfo
+structure in the absence of a standard-time structure)
+if either
+.Va tzh_timecnt
+is zero or the time argument is less than the first transition time recorded
+in the file.
+.Pp
+For version-2-format time zone files,
+the above header and data is followed by a second header and data,
+identical in format except that
+eight bytes are used for each transition time or leap second time.
+After the second header and data comes a newline-enclosed,
+POSIX-TZ-environment-variable-style string for use in handling instants
+after the last transition time stored in the file
+(with nothing between the newlines if there is no POSIX representation for
+such instants).
+.Sh SEE ALSO
+.Xr ctime 3 ,
+.Xr localtime 3 ,
+.Xr time 3
+.\" @(#)tzfile.5       8.2
+.\" This file is in the public domain, so clarified as of
+.\" 1996-06-05 by Arthur David Olson.
diff --git a/lib/nbsd_libc/time/tzfile.h b/lib/nbsd_libc/time/tzfile.h
new file mode 100644 (file)
index 0000000..2b4b421
--- /dev/null
@@ -0,0 +1,183 @@
+/*     $NetBSD: tzfile.h,v 1.9 2009/12/31 22:49:16 mlelstv Exp $       */
+
+#ifndef TZFILE_H
+#define TZFILE_H
+
+/*
+** This file is in the public domain, so clarified as of
+** 1996-06-05 by Arthur David Olson.
+*/
+
+/*
+** This header is for use ONLY with the time conversion code.
+** There is no guarantee that it will remain unchanged,
+** or that it will remain at all.
+** Do NOT copy it to any system include directory.
+** Thank you!
+*/
+
+/*
+** ID
+*/
+
+#ifndef lint
+#ifndef NOID
+#if 0
+static char    tzfilehid[] = "@(#)tzfile.h     8.1";
+#endif
+#endif /* !defined NOID */
+#endif /* !defined lint */
+
+/*
+** Information about time zone files.
+*/
+
+#ifndef TZDIR          /* Time zone object file directory */
+#define TZDIR          "/usr/share/zoneinfo"
+#endif /* !defined TZDIR */
+
+#ifndef TZDEFAULT
+#define TZDEFAULT      "/etc/localtime"
+#endif /* !defined TZDEFAULT */
+
+#ifndef TZDEFRULES
+#define TZDEFRULES     "posixrules"
+#endif /* !defined TZDEFRULES */
+
+/*
+** Each file begins with. . .
+*/
+
+#define        TZ_MAGIC        "TZif"
+
+struct tzhead {
+       char    tzh_magic[4];           /* TZ_MAGIC */
+       char    tzh_version[1];         /* '\0' or '2' as of 2005 */
+       char    tzh_reserved[15];       /* reserved--must be zero */
+       char    tzh_ttisgmtcnt[4];      /* coded number of trans. time flags */
+       char    tzh_ttisstdcnt[4];      /* coded number of trans. time flags */
+       char    tzh_leapcnt[4];         /* coded number of leap seconds */
+       char    tzh_timecnt[4];         /* coded number of transition times */
+       char    tzh_typecnt[4];         /* coded number of local time types */
+       char    tzh_charcnt[4];         /* coded number of abbr. chars */
+};
+
+/*
+** . . .followed by. . .
+**
+**     tzh_timecnt (char [4])s         coded transition times a la time(2)
+**     tzh_timecnt (unsigned char)s    types of local time starting at above
+**     tzh_typecnt repetitions of
+**             one (char [4])          coded UTC offset in seconds
+**             one (unsigned char)     used to set tm_isdst
+**             one (unsigned char)     that's an abbreviation list index
+**     tzh_charcnt (char)s             '\0'-terminated zone abbreviations
+**     tzh_leapcnt repetitions of
+**             one (char [4])          coded leap second transition times
+**             one (char [4])          total correction after above
+**     tzh_ttisstdcnt (char)s          indexed by type; if TRUE, transition
+**                                     time is standard time, if FALSE,
+**                                     transition time is wall clock time
+**                                     if absent, transition times are
+**                                     assumed to be wall clock time
+**     tzh_ttisgmtcnt (char)s          indexed by type; if TRUE, transition
+**                                     time is UTC, if FALSE,
+**                                     transition time is local time
+**                                     if absent, transition times are
+**                                     assumed to be local time
+*/
+
+/*
+** If tzh_version is '2' or greater, the above is followed by a second instance
+** of tzhead and a second instance of the data in which each coded transition
+** time uses 8 rather than 4 chars,
+** then a POSIX-TZ-environment-variable-style string for use in handling
+** instants after the last transition time stored in the file
+** (with nothing between the newlines if there is no POSIX representation for
+** such instants).
+*/
+
+/*
+** In the current implementation, "tzset()" refuses to deal with files that
+** exceed any of the limits below.
+*/
+
+#ifndef TZ_MAX_TIMES
+#define TZ_MAX_TIMES   1200
+#endif /* !defined TZ_MAX_TIMES */
+
+#ifndef TZ_MAX_TYPES
+#ifndef NOSOLAR
+#define TZ_MAX_TYPES   256 /* Limited by what (unsigned char)'s can hold */
+#endif /* !defined NOSOLAR */
+#ifdef NOSOLAR
+/*
+** Must be at least 14 for Europe/Riga as of Jan 12 1995,
+** as noted by Earl Chew.
+*/
+#define TZ_MAX_TYPES   20      /* Maximum number of local time types */
+#endif /* !defined NOSOLAR */
+#endif /* !defined TZ_MAX_TYPES */
+
+#ifndef TZ_MAX_CHARS
+#define TZ_MAX_CHARS   50      /* Maximum number of abbreviation characters */
+                               /* (limited by what unsigned chars can hold) */
+#endif /* !defined TZ_MAX_CHARS */
+
+#ifndef TZ_MAX_LEAPS
+#define TZ_MAX_LEAPS   50      /* Maximum number of leap second corrections */
+#endif /* !defined TZ_MAX_LEAPS */
+
+#define SECSPERMIN     60
+#define MINSPERHOUR    60
+#define HOURSPERDAY    24
+#define DAYSPERWEEK    7
+#define DAYSPERNYEAR   365
+#define DAYSPERLYEAR   366
+#define SECSPERHOUR    (SECSPERMIN * MINSPERHOUR)
+#define SECSPERDAY     ((long) SECSPERHOUR * HOURSPERDAY)
+#define MONSPERYEAR    12
+
+#define TM_SUNDAY      0
+#define TM_MONDAY      1
+#define TM_TUESDAY     2
+#define TM_WEDNESDAY   3
+#define TM_THURSDAY    4
+#define TM_FRIDAY      5
+#define TM_SATURDAY    6
+
+#define TM_JANUARY     0
+#define TM_FEBRUARY    1
+#define TM_MARCH       2
+#define TM_APRIL       3
+#define TM_MAY         4
+#define TM_JUNE                5
+#define TM_JULY                6
+#define TM_AUGUST      7
+#define TM_SEPTEMBER   8
+#define TM_OCTOBER     9
+#define TM_NOVEMBER    10
+#define TM_DECEMBER    11
+
+#define TM_YEAR_BASE   1900
+
+#define EPOCH_YEAR     1970
+#define EPOCH_WDAY     TM_THURSDAY
+
+#define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0))
+
+/*
+** Since everything in isleap is modulo 400 (or a factor of 400), we know that
+**     isleap(y) == isleap(y % 400)
+** and so
+**     isleap(a + b) == isleap((a + b) % 400)
+** or
+**     isleap(a + b) == isleap(a % 400 + b % 400)
+** This is true even if % means modulo rather than Fortran remainder
+** (which is allowed by C89 but not C99).
+** We use this to avoid addition overflow problems.
+*/
+
+#define isleap_sum(a, b)       isleap((a) % 400 + (b) % 400)
+
+#endif /* !defined TZFILE_H */
diff --git a/lib/nbsd_libc/time/tzselect.8 b/lib/nbsd_libc/time/tzselect.8
new file mode 100644 (file)
index 0000000..f75da26
--- /dev/null
@@ -0,0 +1,45 @@
+.\"    $NetBSD: tzselect.8,v 1.4 2009/12/31 22:49:16 mlelstv Exp $
+.\"
+.TH TZSELECT 8
+.SH NAME
+tzselect \- select a time zone
+.SH SYNOPSIS
+.B tzselect
+.SH DESCRIPTION
+The
+.B tzselect
+program asks the user for information about the current location,
+and outputs the resulting time zone description to standard output.
+The output is suitable as a value for the TZ environment variable.
+.PP
+All interaction with the user is done via standard input and standard error.
+.SH "ENVIRONMENT VARIABLES"
+.TP
+\f3AWK\fP
+Name of a Posix-compliant
+.I awk
+program (default:
+.BR awk ).
+.TP
+\f3TZDIR\fP
+Name of the directory containing time zone data files (default:
+.BR /usr/local/etc/zoneinfo ).
+.SH FILES
+.TP
+\f2TZDIR\fP\f3/iso3166.tab\fP
+Table of ISO 3166 2-letter country codes and country names.
+.TP
+\f2TZDIR\fP\f3/zone.tab\fP
+Table of country codes, latitude and longitude, TZ values, and
+descriptive comments.
+.TP
+\f2TZDIR\fP\f3/\fP\f2TZ\fP
+Time zone data file for time zone \f2TZ\fP.
+.SH "EXIT STATUS"
+The exit status is zero if a time zone was successfully obtained from the user,
+nonzero otherwise.
+.SH "SEE ALSO"
+newctime(3), tzfile(5), zdump(8), zic(8)
+.\" @(#)tzselect.8     8.2
+.\" This file is in the public domain, so clarified as of
+.\" 2009-05-17 by Arthur David Olson.
diff --git a/lib/nbsd_libc/time/tzselect.ksh b/lib/nbsd_libc/time/tzselect.ksh
new file mode 100644 (file)
index 0000000..86db644
--- /dev/null
@@ -0,0 +1,325 @@
+#! /bin/ksh
+#
+#      $NetBSD: tzselect.ksh,v 1.6 2009/12/31 22:49:16 mlelstv Exp $
+#
+VERSION='@(#)tzselect.ksh      8.2'
+
+# Ask the user about the time zone, and output the resulting TZ value to stdout.
+# Interact with the user via stderr and stdin.
+
+# Contributed by Paul Eggert.
+
+# Porting notes:
+#
+# This script requires several features of the Korn shell.
+# If your host lacks the Korn shell,
+# you can use either of the following free programs instead:
+#
+#      <a href=ftp://ftp.gnu.org/pub/gnu/>
+#      Bourne-Again shell (bash)
+#      </a>
+#
+#      <a href=ftp://ftp.cs.mun.ca/pub/pdksh/pdksh.tar.gz>
+#      Public domain ksh
+#      </a>
+#
+# This script also uses several features of modern awk programs.
+# If your host lacks awk, or has an old awk that does not conform to Posix.2,
+# you can use either of the following free programs instead:
+#
+#      <a href=ftp://ftp.gnu.org/pub/gnu/>
+#      GNU awk (gawk)
+#      </a>
+#
+#      <a href=ftp://ftp.whidbey.net/pub/brennan/>
+#      mawk
+#      </a>
+
+
+# Specify default values for environment variables if they are unset.
+: ${AWK=awk}
+: ${TZDIR=$(pwd)}
+
+# Check for awk Posix compliance.
+($AWK -v x=y 'BEGIN { exit 123 }') </dev/null >/dev/null 2>&1
+[ $? = 123 ] || {
+       echo >&2 "$0: Sorry, your \`$AWK' program is not Posix compatible."
+       exit 1
+}
+
+if [ "$1" = "--help" ]; then
+    cat <<EOF
+Usage: tzselect
+Select a time zone interactively.
+
+Report bugs to tz@elsie.nci.nih.gov.
+EOF
+    exit 0
+elif [ "$1" = "--version" ]; then
+    cat <<EOF
+tzselect $VERSION
+EOF
+    exit 0
+fi
+
+# Make sure the tables are readable.
+TZ_COUNTRY_TABLE=$TZDIR/iso3166.tab
+TZ_ZONE_TABLE=$TZDIR/zone.tab
+for f in $TZ_COUNTRY_TABLE $TZ_ZONE_TABLE
+do
+       <$f || {
+               echo >&2 "$0: time zone files are not set up correctly"
+               exit 1
+       }
+done
+
+newline='
+'
+IFS=$newline
+
+
+# Work around a bug in bash 1.14.7 and earlier, where $PS3 is sent to stdout.
+case $(echo 1 | (select x in x; do break; done) 2>/dev/null) in
+?*) PS3=
+esac
+
+
+# Begin the main loop.  We come back here if the user wants to retry.
+while
+
+       echo >&2 'Please identify a location' \
+               'so that time zone rules can be set correctly.'
+
+       continent=
+       country=
+       region=
+
+
+       # Ask the user for continent or ocean.
+
+       echo >&2 'Please select a continent or ocean.'
+
+       select continent in \
+           Africa \
+           Americas \
+           Antarctica \
+           'Arctic Ocean' \
+           Asia \
+           'Atlantic Ocean' \
+           Australia \
+           Europe \
+           'Indian Ocean' \
+           'Pacific Ocean' \
+           'none - I want to specify the time zone using the Posix TZ format.'
+       do
+           case $continent in
+           '')
+               echo >&2 'Please enter a number in range.';;
+           ?*)
+               case $continent in
+               Americas) continent=America;;
+               *' '*) continent=$(expr "$continent" : '\([^ ]*\)')
+               esac
+               break
+           esac
+       done
+       case $continent in
+       '')
+               exit 1;;
+       none)
+               # Ask the user for a Posix TZ string.  Check that it conforms.
+               while
+                       echo >&2 'Please enter the desired value' \
+                               'of the TZ environment variable.'
+                       echo >&2 'For example, GST-10 is a zone named GST' \
+                               'that is 10 hours ahead (east) of UTC.'
+                       read TZ
+                       $AWK -v TZ="$TZ" 'BEGIN {
+                               tzname = "[^-+,0-9][^-+,0-9][^-+,0-9]+"
+                               time = "[0-2]?[0-9](:[0-5][0-9](:[0-5][0-9])?)?"
+                               offset = "[-+]?" time
+                               date = "(J?[0-9]+|M[0-9]+\.[0-9]+\.[0-9]+)"
+                               datetime = "," date "(/" time ")?"
+                               tzpattern = "^(:.*|" tzname offset "(" tzname \
+                                 "(" offset ")?(" datetime datetime ")?)?)$"
+                               if (TZ ~ tzpattern) exit 1
+                               exit 0
+                       }'
+               do
+                       echo >&2 "\`$TZ' is not a conforming" \
+                               'Posix time zone string.'
+               done
+               TZ_for_date=$TZ;;
+       *)
+               # Get list of names of countries in the continent or ocean.
+               countries=$($AWK -F'\t' \
+                       -v continent="$continent" \
+                       -v TZ_COUNTRY_TABLE="$TZ_COUNTRY_TABLE" \
+               '
+                       /^#/ { next }
+                       $3 ~ ("^" continent "/") {
+                               if (!cc_seen[$1]++) cc_list[++ccs] = $1
+                       }
+                       END {
+                               while (getline <TZ_COUNTRY_TABLE) {
+                                       if ($0 !~ /^#/) cc_name[$1] = $2
+                               }
+                               for (i = 1; i <= ccs; i++) {
+                                       country = cc_list[i]
+                                       if (cc_name[country]) {
+                                         country = cc_name[country]
+                                       }
+                                       print country
+                               }
+                       }
+               ' <$TZ_ZONE_TABLE | sort -f)
+
+
+               # If there's more than one country, ask the user which one.
+               case $countries in
+               *"$newline"*)
+                       echo >&2 'Please select a country.'
+                       select country in $countries
+                       do
+                           case $country in
+                           '') echo >&2 'Please enter a number in range.';;
+                           ?*) break
+                           esac
+                       done
+
+                       case $country in
+                       '') exit 1
+                       esac;;
+               *)
+                       country=$countries
+               esac
+
+
+               # Get list of names of time zone rule regions in the country.
+               regions=$($AWK -F'\t' \
+                       -v country="$country" \
+                       -v TZ_COUNTRY_TABLE="$TZ_COUNTRY_TABLE" \
+               '
+                       BEGIN {
+                               cc = country
+                               while (getline <TZ_COUNTRY_TABLE) {
+                                       if ($0 !~ /^#/  &&  country == $2) {
+                                               cc = $1
+                                               break
+                                       }
+                               }
+                       }
+                       $1 == cc { print $4 }
+               ' <$TZ_ZONE_TABLE)
+
+
+               # If there's more than one region, ask the user which one.
+               case $regions in
+               *"$newline"*)
+                       echo >&2 'Please select one of the following' \
+                               'time zone regions.'
+                       select region in $regions
+                       do
+                               case $region in
+                               '') echo >&2 'Please enter a number in range.';;
+                               ?*) break
+                               esac
+                       done
+                       case $region in
+                       '') exit 1
+                       esac;;
+               *)
+                       region=$regions
+               esac
+
+               # Determine TZ from country and region.
+               TZ=$($AWK -F'\t' \
+                       -v country="$country" \
+                       -v region="$region" \
+                       -v TZ_COUNTRY_TABLE="$TZ_COUNTRY_TABLE" \
+               '
+                       BEGIN {
+                               cc = country
+                               while (getline <TZ_COUNTRY_TABLE) {
+                                       if ($0 !~ /^#/  &&  country == $2) {
+                                               cc = $1
+                                               break
+                                       }
+                               }
+                       }
+                       $1 == cc && $4 == region { print $3 }
+               ' <$TZ_ZONE_TABLE)
+
+               # Make sure the corresponding zoneinfo file exists.
+               TZ_for_date=$TZDIR/$TZ
+               <$TZ_for_date || {
+                       echo >&2 "$0: time zone files are not set up correctly"
+                       exit 1
+               }
+       esac
+
+
+       # Use the proposed TZ to output the current date relative to UTC.
+       # Loop until they agree in seconds.
+       # Give up after 8 unsuccessful tries.
+
+       extra_info=
+       for i in 1 2 3 4 5 6 7 8
+       do
+               TZdate=$(LANG=C TZ="$TZ_for_date" date)
+               UTdate=$(LANG=C TZ=UTC0 date)
+               TZsec=$(expr "$TZdate" : '.*:\([0-5][0-9]\)')
+               UTsec=$(expr "$UTdate" : '.*:\([0-5][0-9]\)')
+               case $TZsec in
+               $UTsec)
+                       extra_info="
+Local time is now:     $TZdate.
+Universal Time is now: $UTdate."
+                       break
+               esac
+       done
+
+
+       # Output TZ info and ask the user to confirm.
+
+       echo >&2 ""
+       echo >&2 "The following information has been given:"
+       echo >&2 ""
+       case $country+$region in
+       ?*+?*)  echo >&2 "      $country$newline        $region";;
+       ?*+)    echo >&2 "      $country";;
+       +)      echo >&2 "      TZ='$TZ'"
+       esac
+       echo >&2 ""
+       echo >&2 "Therefore TZ='$TZ' will be used.$extra_info"
+       echo >&2 "Is the above information OK?"
+
+       ok=
+       select ok in Yes No
+       do
+           case $ok in
+           '') echo >&2 'Please enter 1 for Yes, or 2 for No.';;
+           ?*) break
+           esac
+       done
+       case $ok in
+       '') exit 1;;
+       Yes) break
+       esac
+do :
+done
+
+case $SHELL in
+*csh) file=.login line="setenv TZ '$TZ'";;
+*) file=.profile line="TZ='$TZ'; export TZ"
+esac
+
+echo >&2 "
+You can make this change permanent for yourself by appending the line
+       $line
+to the file '$file' in your home directory; then log out and log in again.
+
+Here is that TZ value again, this time on standard output so that you
+can use the $0 command in shell scripts:"
+
+echo "$TZ"
diff --git a/lib/nbsd_libc/time/tzset.3 b/lib/nbsd_libc/time/tzset.3
new file mode 100644 (file)
index 0000000..f546222
--- /dev/null
@@ -0,0 +1,268 @@
+.\"    $NetBSD: tzset.3,v 1.25 2010/12/17 01:29:45 wiz Exp $
+.Dd April 1, 2001
+.Dt TZSET 3
+.Os
+.Sh NAME
+.Nm tzset
+.Nd initialize time conversion information
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In time.h
+.Ft void
+.Fn tzset "void"
+.Sh DESCRIPTION
+The
+.Fn tzset
+function uses the value of the environment variable
+.Ev TZ
+to set time conversion information used by
+.Xr localtime 3 .
+If
+.Ev TZ
+does not appear in the environment,
+the best available approximation to local wall clock time, as
+specified by the
+.Xr tzfile 5
+format file
+.Pa /etc/localtime
+is used by
+.Xr localtime 3 .
+If
+.Ev TZ
+appears in the environment but its value is a null string,
+Coordinated Universal Time (UTC) is used (without leap second
+correction).
+If
+.Ev TZ
+appears in the environment and its value is not a null string:
+.Bl -dash
+.It
+if the value begins with a colon, it is used as a pathname of a file
+from which to read the time conversion information;
+.It
+if the value does not begin with a colon, it is first used as the
+pathname of a file from which to read the time conversion information,
+and, if that file cannot be read, is used directly as a specification
+of the time conversion information.
+.El
+.Pp
+When
+.Ev TZ
+is used as a pathname, if it begins with a slash, it is used as an
+absolute pathname; otherwise, it is used as a pathname relative to
+.Pa /usr/share/zoneinfo .
+The file must be in the format specified in
+.Xr tzfile 5 .
+.Pp
+When
+.Ev TZ
+is used directly as a specification of the time conversion information,
+it must have the following syntax (spaces inserted for clarity):
+.Sm off
+.Bd -literal -offset indent
+.Cm std Cm offset Oo
+.Cm dst Oo
+.Cm offset Oc Oo
+.No , Cm rule Oc Oc
+.Ed
+.Sm on
+.Pp
+where:
+.Bl -tag -width "std and dst" -compact
+.It Cm std No and Cm dst
+Three or more bytes that are the designation for the standard
+.Cm ( std )
+or summer
+.Cm ( dst )
+time zone.
+Only
+.Cm std
+is required; if
+.Cm dst
+is missing, then summer time does not apply in this locale.
+Upper- and lowercase letters are explicitly allowed.
+Any characters except a leading colon (:), digits, comma (,), minus (-),
+plus (+), and ASCII NUL are allowed.
+.It Cm offset
+Indicates the value one must add to the local time to arrive at
+Coordinated Universal Time.
+The
+.Cm offset
+has the form:
+.Sm off
+.Bd -literal -offset indent
+.Cm hh Oo
+.Cm :mm Oo
+.Cm :ss Oc Oc
+.Ed
+.Sm on
+.Pp
+The minutes
+.Cm ( mm )
+and seconds
+.Cm ( ss )
+are optional.
+The hour
+.Cm ( hh )
+is required and may be a single digit.
+The
+.Cm offset
+following
+.Cm std
+is required.
+If no
+.Cm offset
+follows
+.Cm dst ,
+summer time is assumed to be one hour ahead of standard time.
+One or more digits may be used; the value is always interpreted as a
+decimal number.
+The hour must be between zero and 24, and the minutes (and
+seconds) \(em if present \(em between zero and 59.
+If preceded by a
+.Dq -
+the time zone shall be east of the Prime Meridian; otherwise it shall be
+west (which may be indicated by an optional preceding
+.Dq + ) .
+.It Cm rule
+Indicates when to change to and back from summer time.
+The
+.Cm rule
+has the form:
+.Sm off
+.Bd -literal -offset indent
+.Xo
+.Cm date No /
+.Cm time No ,
+.Cm date No /
+.Cm time
+.Xc
+.Ed
+.Sm on
+.Pp
+where the first
+.Cm date
+describes when the change from standard to summer time occurs and the
+second
+.Cm date
+describes when the change back happens.
+Each
+.Cm time
+field describes when, in current local time, the change to the other
+time is made.
+The format of
+.Fa date
+is one of the following:
+.Bl -tag -width "The Julian day" -compact
+.It Cm J Ns Ar n
+The Julian day
+.Ar n
+(1 \*[Le]
+.Ar n
+\*[Le] 365).
+Leap days are not counted; that is, in all years \(em including leap
+years \(em February 28 is day 59 and March 1 is day 60.
+It is impossible to explicitly refer to the occasional February 29.
+.It Ar n
+The zero-based Julian day (0\ \*[Le]
+.Ar n
+\*[Le]\ 365).
+Leap days are counted, and it is possible to refer to
+February 29.
+.Sm off
+.It Cm M Ns Ar m No . Ar n No . Ar d
+.Sm on
+The
+.Ar d Ns 'th
+day
+(0 \*[Le]
+.Ar d
+\*[Le]\ 6) of week
+.Ar n
+of month
+.Ar m
+of the year
+(1 \*[Le]
+.Ar n
+\*[Le]\ 5, 1 \*[Le]
+.Ar m
+\*[Le]\ 12, where week 5 means
+.Dq the\ last Ar d No day\ in\ month Ar m
+which may occur in either the fourth or the fifth week).
+Week 1 is the first week in which the
+.Ar d Ns 'th
+day occurs.
+Day zero is Sunday.
+.El
+The
+.Cm time
+has the same format as
+.Cm offset
+except that no leading sign
+.Dq -
+or
+.Dq +
+is allowed.
+The default, if
+.Cm time
+is not given, is
+.Cm 02:00:00 .
+.El
+If no
+.Cm rule
+is present in
+.Ev TZ ,
+the rules specified by the
+.Xr tzfile 5
+format file
+.Pa posixrules
+in
+.Pa /usr/share/zoneinfo
+are used, with the standard and summer time offsets from UTC replaced
+by those specified by the
+.Cm offset
+values in
+.Ev TZ .
+.Pp
+For compatibility with System V Release 3.1, a semicolon (;) may be
+used to separate the
+.Cm rule
+from the rest of the specification.
+.Pp
+If the
+.Ev TZ
+environment variable does not specify a
+.Xr tzfile 5
+format file and cannot be interpreted as a direct specification, UTC
+is used.
+.Sh FILES
+.Bl -tag -width /usr/share/zoneinfo/posixrules -compact
+.It Pa /etc/localtime
+local time zone file
+.It Pa /usr/share/zoneinfo
+time zone information directory
+.It Pa /usr/share/zoneinfo/posixrules
+used with POSIX-style TZ's
+.It Pa /usr/share/zoneinfo/GMT
+for UTC leap seconds
+.El
+.Pp
+If
+.Pa /usr/share/zoneinfo/GMT
+is absent, UTC leap seconds are loaded from
+.Pa /usr/share/zoneinfo/posixrules .
+.Sh SEE ALSO
+.Xr ctime 3 ,
+.Xr getenv 3 ,
+.Xr strftime 3 ,
+.Xr time 3 ,
+.Xr tzfile 5
+.Sh STANDARDS
+The
+.Fn tzset
+function conforms to
+.St -p1003.1-88 .
+.\" @(#)newtzset.3     8.2
+.\" This file is in the public domain, so clarified as of
+.\" 2009-05-17 by Arthur David Olson.
diff --git a/lib/nbsd_libc/time/zdump.8 b/lib/nbsd_libc/time/zdump.8
new file mode 100644 (file)
index 0000000..c761cc4
--- /dev/null
@@ -0,0 +1,61 @@
+.\"    $NetBSD: zdump.8,v 1.8 2010/01/08 23:14:13 joerg Exp $
+.\" @(#)zdump.8        7.4
+.Dd October 29, 2003
+.Dt ZDUMP 8
+.Os
+.Sh NAME
+.Nm zdump
+.Nd time zone dumper
+.Sh SYNOPSIS
+.Nm zdump
+.Op Fl \-version
+.Op Fl v
+.Op Fl c Ar [loyear,]highyear
+.Op Ar zonename ...
+.Sh DESCRIPTION
+.Nm
+prints the current time in each
+.Ar zonename
+named on the command line.
+.Pp
+These options are available:
+.Bl -tag -width XXXXXXXXX -compact
+.It Fl \-version
+Output version information and exit.
+.It Fl v
+For each
+.Ar zonename
+on the command line,
+print the time at the lowest possible time value,
+the time one day after the lowest possible time value,
+the times both one second before and exactly at
+each detected time discontinuity,
+the time at one day less than the highest possible time value,
+and the time at the highest possible time value,
+Each line ends with
+.Dl isdst=1
+if the given time is Daylight Saving Time or
+.Dl isdst=0
+otherwise.
+.It Fl c Ar [loyear,]highyear
+Cut off the verbose output near the start of the given year(s).
+By default,
+the program cuts off verbose output near the starts of the years -500 and 2500.
+.El
+.Sh LIMITATIONS
+The
+.Fl v
+option may not be used on systems with floating-point time_t values
+that are neither float nor double.
+.Pp
+Time discontinuities are found by sampling the results returned by localtime
+at twelve-hour intervals.
+This works in all real-world cases;
+one can construct artificial time zones for which this fails.
+.Sh SEE ALSO
+.Xr ctime 3 ,
+.Xr tzfile 5 ,
+.Xr zic 8
+.\" @(#)zdump.8        8.2
+.\" This file is in the public domain, so clarified as of
+.\" 2009-05-17 by Arthur David Olson.
diff --git a/lib/nbsd_libc/time/zdump.c b/lib/nbsd_libc/time/zdump.c
new file mode 100644 (file)
index 0000000..691b3eb
--- /dev/null
@@ -0,0 +1,685 @@
+/*     $NetBSD: zdump.c,v 1.19 2011/01/15 12:31:57 martin Exp $        */
+/*
+** This file is in the public domain, so clarified as of
+** 2009-05-17 by Arthur David Olson.
+*/
+
+#include <sys/cdefs.h>
+#ifndef lint
+#ifndef NOID
+__RCSID("$NetBSD: zdump.c,v 1.19 2011/01/15 12:31:57 martin Exp $");
+#endif /* !defined NOID */
+#endif /* !defined lint */
+
+static char    elsieid[] = "@(#)zdump.c        8.9";
+
+/*
+** This code has been made independent of the rest of the time
+** conversion package to increase confidence in the verification it provides.
+** You can use this code to help in verifying other implementations.
+*/
+
+#include "stdio.h"     /* for stdout, stderr */
+#include "string.h"    /* for strcpy */
+#include "sys/types.h" /* for time_t */
+#include "time.h"      /* for struct tm */
+#include "stdlib.h"    /* for exit, malloc, atoi */
+#include <err.h>
+#include "float.h"     /* for FLT_MAX and DBL_MAX */
+#include "ctype.h"     /* for isalpha et al. */
+#ifndef isascii
+#define isascii(x) 1
+#endif /* !defined isascii */
+
+#ifndef ZDUMP_LO_YEAR
+#define ZDUMP_LO_YEAR  (-500)
+#endif /* !defined ZDUMP_LO_YEAR */
+
+#ifndef ZDUMP_HI_YEAR
+#define ZDUMP_HI_YEAR  2500
+#endif /* !defined ZDUMP_HI_YEAR */
+
+#ifndef MAX_STRING_LENGTH
+#define MAX_STRING_LENGTH      1024
+#endif /* !defined MAX_STRING_LENGTH */
+
+#ifndef TRUE
+#define TRUE           1
+#endif /* !defined TRUE */
+
+#ifndef FALSE
+#define FALSE          0
+#endif /* !defined FALSE */
+
+#ifndef EXIT_SUCCESS
+#define EXIT_SUCCESS   0
+#endif /* !defined EXIT_SUCCESS */
+
+#ifndef EXIT_FAILURE
+#define EXIT_FAILURE   1
+#endif /* !defined EXIT_FAILURE */
+
+#ifndef SECSPERMIN
+#define SECSPERMIN     60
+#endif /* !defined SECSPERMIN */
+
+#ifndef MINSPERHOUR
+#define MINSPERHOUR    60
+#endif /* !defined MINSPERHOUR */
+
+#ifndef SECSPERHOUR
+#define SECSPERHOUR    (SECSPERMIN * MINSPERHOUR)
+#endif /* !defined SECSPERHOUR */
+
+#ifndef HOURSPERDAY
+#define HOURSPERDAY    24
+#endif /* !defined HOURSPERDAY */
+
+#ifndef EPOCH_YEAR
+#define EPOCH_YEAR     1970
+#endif /* !defined EPOCH_YEAR */
+
+#ifndef TM_YEAR_BASE
+#define TM_YEAR_BASE   1900
+#endif /* !defined TM_YEAR_BASE */
+
+#ifndef DAYSPERNYEAR
+#define DAYSPERNYEAR   365
+#endif /* !defined DAYSPERNYEAR */
+
+#ifndef isleap
+#define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0))
+#endif /* !defined isleap */
+
+#ifndef isleap_sum
+/*
+** See tzfile.h for details on isleap_sum.
+*/
+#define isleap_sum(a, b)       isleap((a) % 400 + (b) % 400)
+#endif /* !defined isleap_sum */
+
+#define SECSPERDAY     ((long) SECSPERHOUR * HOURSPERDAY)
+#define SECSPERNYEAR   (SECSPERDAY * DAYSPERNYEAR)
+#define SECSPERLYEAR   (SECSPERNYEAR + SECSPERDAY)
+
+#ifndef HAVE_GETTEXT
+#define HAVE_GETTEXT 0
+#endif
+#if HAVE_GETTEXT
+#include "locale.h"    /* for setlocale */
+#include "libintl.h"
+#endif /* HAVE_GETTEXT */
+
+#ifndef GNUC_or_lint
+#ifdef lint
+#define GNUC_or_lint
+#else /* !defined lint */
+#ifdef __GNUC__
+#define GNUC_or_lint
+#endif /* defined __GNUC__ */
+#endif /* !defined lint */
+#endif /* !defined GNUC_or_lint */
+
+#ifndef INITIALIZE
+#ifdef GNUC_or_lint
+#define INITIALIZE(x)  ((x) = 0)
+#else /* !defined GNUC_or_lint */
+#define INITIALIZE(x)
+#endif /* !defined GNUC_or_lint */
+#endif /* !defined INITIALIZE */
+
+/*
+** For the benefit of GNU folk...
+** `_(MSGID)' uses the current locale's message library string for MSGID.
+** The default is to use gettext if available, and use MSGID otherwise.
+*/
+
+#ifndef _
+#if HAVE_GETTEXT
+#define _(msgid) gettext(msgid)
+#else /* !HAVE_GETTEXT */
+#define _(msgid) __UNCONST(msgid)
+#endif /* !HAVE_GETTEXT */
+#endif /* !defined _ */
+
+#ifndef TZ_DOMAIN
+#define TZ_DOMAIN "tz"
+#endif /* !defined TZ_DOMAIN */
+
+extern char ** environ;
+extern int     getopt(int argc, char * const argv[],
+                       const char * options);
+extern char *  optarg;
+extern int     optind;
+
+static time_t  absolute_min_time;
+static time_t  absolute_max_time;
+static size_t  longest;
+static char *  progname;
+static int     warned;
+
+static const char *    abbr(struct tm * tmp);
+static void    abbrok(const char * abbrp, const char * zone);
+static long    delta(struct tm * newp, struct tm * oldp);
+static void    dumptime(const struct tm * tmp);
+static time_t  hunt(char * name, time_t lot, time_t    hit);
+int            main(int, char **);
+static void    setabsolutes(void);
+static void    show(char * zone, time_t t, int v);
+static const char *    tformat(void);
+static time_t  yeartot(long y);
+
+#ifndef TYPECHECK
+#define my_localtime   localtime
+#else /* !defined TYPECHECK */
+static struct tm *
+my_localtime(tp)
+time_t *       tp;
+{
+       register struct tm *    tmp;
+
+       tmp = localtime(tp);
+       if (tp != NULL && tmp != NULL) {
+               struct tm       tm;
+               register time_t t;
+
+               tm = *tmp;
+               t = mktime(&tm);
+               if (t - *tp >= 1 || *tp - t >= 1) {
+                       (void) fflush(stdout);
+                       (void) fprintf(stderr, "\n%s: ", progname);
+                       (void) fprintf(stderr, tformat(), *tp);
+                       (void) fprintf(stderr, " ->");
+                       (void) fprintf(stderr, " year=%d", tmp->tm_year);
+                       (void) fprintf(stderr, " mon=%d", tmp->tm_mon);
+                       (void) fprintf(stderr, " mday=%d", tmp->tm_mday);
+                       (void) fprintf(stderr, " hour=%d", tmp->tm_hour);
+                       (void) fprintf(stderr, " min=%d", tmp->tm_min);
+                       (void) fprintf(stderr, " sec=%d", tmp->tm_sec);
+                       (void) fprintf(stderr, " isdst=%d", tmp->tm_isdst);
+                       (void) fprintf(stderr, " -> ");
+                       (void) fprintf(stderr, tformat(), t);
+                       (void) fprintf(stderr, "\n");
+               }
+       }
+       return tmp;
+}
+#endif /* !defined TYPECHECK */
+
+static void
+abbrok(abbrp, zone)
+const char * const     abbrp;
+const char * const     zone;
+{
+       register const char *   cp;
+       register char *         wp;
+
+       if (warned)
+               return;
+       cp = abbrp;
+       wp = NULL;
+       while (isascii((unsigned char) *cp) && isalpha((unsigned char) *cp))
+               ++cp;
+       if (cp - abbrp == 0)
+               wp = _("lacks alphabetic at start");
+       else if (cp - abbrp < 3)
+               wp = _("has fewer than 3 alphabetics");
+       else if (cp - abbrp > 6)
+               wp = _("has more than 6 alphabetics");
+       if (wp == NULL && (*cp == '+' || *cp == '-')) {
+               ++cp;
+               if (isascii((unsigned char) *cp) &&
+                       isdigit((unsigned char) *cp))
+                               if (*cp++ == '1' && *cp >= '0' && *cp <= '4')
+                                       ++cp;
+               if (*cp != '\0')
+                       wp = _("differs from POSIX standard");
+       }
+       if (wp == NULL)
+               return;
+       (void) fflush(stdout);
+       (void) fprintf(stderr,
+               _("%s: warning: zone \"%s\" abbreviation \"%s\" %s\n"),
+               progname, zone, abbrp, wp);
+       warned = TRUE;
+}
+
+static void
+usage(const char *xprogname, FILE *stream, int status)
+{
+       (void) fprintf(stream,
+_("%s: usage is %s [ --version ] [ --help ] [ -v ] [ -c [loyear,]hiyear ] zonename ...\n\
+\n\
+Report bugs to tz@elsie.nci.nih.gov.\n"),
+                      xprogname, xprogname);
+       exit(status);
+}
+
+int
+main(argc, argv)
+int    argc;
+char * argv[];
+{
+       register int            i;
+       register int            c;
+       register int            vflag;
+       register char *         cutarg;
+       register long           cutloyear = ZDUMP_LO_YEAR;
+       register long           cuthiyear = ZDUMP_HI_YEAR;
+       register time_t         cutlotime;
+       register time_t         cuthitime;
+       register char **        fakeenv;
+       time_t                  now;
+       time_t                  t;
+       time_t                  newt;
+       struct tm               tm;
+       struct tm               newtm;
+       register struct tm *    tmp;
+       register struct tm *    newtmp;
+
+       INITIALIZE(cutlotime);
+       INITIALIZE(cuthitime);
+#if HAVE_GETTEXT
+       (void) setlocale(LC_ALL, "");
+#ifdef TZ_DOMAINDIR
+       (void) bindtextdomain(TZ_DOMAIN, TZ_DOMAINDIR);
+#endif /* defined TEXTDOMAINDIR */
+       (void) textdomain(TZ_DOMAIN);
+#endif /* HAVE_GETTEXT */
+       progname = argv[0];
+       for (i = 1; i < argc; ++i)
+               if (strcmp(argv[i], "--version") == 0) {
+                       (void) printf("%s\n", elsieid);
+                       exit(EXIT_SUCCESS);
+               } else if (strcmp(argv[i], "--help") == 0) {
+                       usage(progname, stdout, EXIT_SUCCESS);
+               }
+       vflag = 0;
+       cutarg = NULL;
+       while ((c = getopt(argc, argv, "c:v")) == 'c' || c == 'v')
+               if (c == 'v')
+                       vflag = 1;
+               else    cutarg = optarg;
+       if ((c != EOF && c != -1) ||
+               (optind == argc - 1 && strcmp(argv[optind], "=") == 0)) {
+                       usage(progname, stderr, EXIT_FAILURE);
+       }
+       if (vflag) {
+               if (cutarg != NULL) {
+                       long    lo;
+                       long    hi;
+                       char    dummy;
+
+                       if (sscanf(cutarg, "%ld%c", &hi, &dummy) == 1) {
+                               cuthiyear = hi;
+                       } else if (sscanf(cutarg, "%ld,%ld%c",
+                               &lo, &hi, &dummy) == 2) {
+                                       cutloyear = lo;
+                                       cuthiyear = hi;
+                       } else {
+(void) fprintf(stderr, _("%s: wild -c argument %s\n"),
+                                       progname, cutarg);
+                               exit(EXIT_FAILURE);
+                       }
+               }
+               setabsolutes();
+               cutlotime = yeartot(cutloyear);
+               cuthitime = yeartot(cuthiyear);
+       }
+       (void) time(&now);
+       longest = 0;
+       for (i = optind; i < argc; ++i)
+               if (strlen(argv[i]) > longest)
+                       longest = strlen(argv[i]);
+       {
+               register int    from;
+               register int    to;
+
+               for (i = 0; environ[i] != NULL; ++i)
+                       continue;
+               fakeenv = (char **) malloc((size_t) ((i + 2) *
+                       sizeof *fakeenv));
+               if (fakeenv == NULL ||
+                       (fakeenv[0] = (char *) malloc(longest + 4)) == NULL) {
+                       err(EXIT_FAILURE, "Can't allocated %zu bytes",
+                           longest + 4);
+               }
+               to = 0;
+               (void)strcpy(fakeenv[to++], "TZ=");     /* XXX strcpy is safe */
+               for (from = 0; environ[from] != NULL; ++from)
+                       if (strncmp(environ[from], "TZ=", 3) != 0)
+                               fakeenv[to++] = environ[from];
+               fakeenv[to] = NULL;
+               environ = fakeenv;
+       }
+       for (i = optind; i < argc; ++i) {
+               static char     buf[MAX_STRING_LENGTH];
+
+               (void) strcpy(&fakeenv[0][3], argv[i]); /* XXX strcpy is safe */
+               if (!vflag) {
+                       show(argv[i], now, FALSE);
+                       continue;
+               }
+               warned = FALSE;
+               t = absolute_min_time;
+               show(argv[i], t, TRUE);
+               t += SECSPERHOUR * HOURSPERDAY;
+               show(argv[i], t, TRUE);
+               if (t < cutlotime)
+                       t = cutlotime;
+               tmp = my_localtime(&t);
+               if (tmp != NULL) {
+                       tm = *tmp;
+                       (void) strncpy(buf, abbr(&tm), (sizeof buf) - 1);
+               }
+               for ( ; ; ) {
+                       if (t >= cuthitime || t >= cuthitime - SECSPERHOUR * 12)
+                               break;
+                       newt = t + SECSPERHOUR * 12;
+                       newtmp = localtime(&newt);
+                       if (newtmp != NULL)
+                               newtm = *newtmp;
+                       if ((tmp == NULL || newtmp == NULL) ? (tmp != newtmp) :
+                               (delta(&newtm, &tm) != (newt - t) ||
+                               newtm.tm_isdst != tm.tm_isdst ||
+                               strcmp(abbr(&newtm), buf) != 0)) {
+                                       newt = hunt(argv[i], t, newt);
+                                       newtmp = localtime(&newt);
+                                       if (newtmp != NULL) {
+                                               newtm = *newtmp;
+                                               (void) strncpy(buf,
+                                                       abbr(&newtm),
+                                                       (sizeof buf) - 1);
+                                       }
+                       }
+                       t = newt;
+                       tm = newtm;
+                       tmp = newtmp;
+               }
+               t = absolute_max_time;
+               t -= SECSPERHOUR * HOURSPERDAY;
+               show(argv[i], t, TRUE);
+               t += SECSPERHOUR * HOURSPERDAY;
+               show(argv[i], t, TRUE);
+       }
+       if (fflush(stdout) || ferror(stdout)) {
+               err(EXIT_FAILURE, _("Error writing standard output"));
+       }
+       exit(EXIT_SUCCESS);
+       /* If exit fails to exit... */
+       return EXIT_FAILURE;
+}
+
+static void
+setabsolutes(void)
+{
+       if (0.5 == (time_t) 0.5) {
+               /*
+               ** time_t is floating.
+               */
+               if (sizeof (time_t) == sizeof (float)) {
+                       absolute_min_time = (time_t) -FLT_MAX;
+                       absolute_max_time = (time_t) FLT_MAX;
+               } else if (sizeof (time_t) == sizeof (double)) {
+                       absolute_min_time = (time_t) -DBL_MAX;
+                       absolute_max_time = (time_t) DBL_MAX;
+               } else {
+                       (void) fprintf(stderr,
+_("%s: use of -v on system with floating time_t other than float or double\n"),
+                               progname);
+                       exit(EXIT_FAILURE);
+               }
+       } else if (0 > (time_t) -1) {
+               /*
+               ** time_t is signed.  Assume overflow wraps around.
+               */
+               time_t t = 0;
+               time_t t1 = 1;
+
+               while (t < t1) {
+                       t = t1;
+                       t1 = 2 * t1 + 1;
+               }
+
+               absolute_max_time = t;
+               t = -t;
+               absolute_min_time = t - 1;
+               if (t < absolute_min_time)
+                       absolute_min_time = t;
+       } else {
+               /*
+               ** time_t is unsigned.
+               */
+               absolute_min_time = 0;
+               absolute_max_time = absolute_min_time - 1;
+       }
+}
+
+static time_t
+yeartot(y)
+const long     y;
+{
+       register long   myy;
+       register long   seconds;
+       register time_t t;
+
+       myy = EPOCH_YEAR;
+       t = 0;
+       while (myy != y) {
+               if (myy < y) {
+                       seconds = isleap(myy) ? SECSPERLYEAR : SECSPERNYEAR;
+                       ++myy;
+                       if (t > absolute_max_time - seconds) {
+                               t = absolute_max_time;
+                               break;
+                       }
+                       t += seconds;
+               } else {
+                       --myy;
+                       seconds = isleap(myy) ? SECSPERLYEAR : SECSPERNYEAR;
+                       if (t < absolute_min_time + seconds) {
+                               t = absolute_min_time;
+                               break;
+                       }
+                       t -= seconds;
+               }
+       }
+       return t;
+}
+
+static time_t
+hunt(char *name, time_t lot, time_t hit)
+{
+       time_t                  t;
+       long                    diff;
+       struct tm               lotm;
+       register struct tm *    lotmp;
+       struct tm               tm;
+       register struct tm *    tmp;
+       char                    loab[MAX_STRING_LENGTH];
+
+       lotmp = my_localtime(&lot);
+       if (lotmp != NULL) {
+               lotm = *lotmp;
+               (void) strncpy(loab, abbr(&lotm), (sizeof loab) - 1);
+       }
+       for ( ; ; ) {
+               diff = (long) (hit - lot);
+               if (diff < 2)
+                       break;
+               t = lot;
+               t += diff / 2;
+               if (t <= lot)
+                       ++t;
+               else if (t >= hit)
+                       --t;
+               tmp = my_localtime(&t);
+               if (tmp != NULL)
+                       tm = *tmp;
+               if ((lotmp == NULL || tmp == NULL) ? (lotmp == tmp) :
+                       (delta(&tm, &lotm) == (t - lot) &&
+                       tm.tm_isdst == lotm.tm_isdst &&
+                       strcmp(abbr(&tm), loab) == 0)) {
+                               lot = t;
+                               lotm = tm;
+                               lotmp = tmp;
+               } else  hit = t;
+       }
+       show(name, lot, TRUE);
+       show(name, hit, TRUE);
+       return hit;
+}
+
+/*
+** Thanks to Paul Eggert for logic used in delta.
+*/
+
+static long
+delta(newp, oldp)
+struct tm *    newp;
+struct tm *    oldp;
+{
+       register long   result;
+       register int    tmy;
+
+       if (newp->tm_year < oldp->tm_year)
+               return -delta(oldp, newp);
+       result = 0;
+       for (tmy = oldp->tm_year; tmy < newp->tm_year; ++tmy)
+               result += DAYSPERNYEAR + isleap_sum(tmy, TM_YEAR_BASE);
+       result += newp->tm_yday - oldp->tm_yday;
+       result *= HOURSPERDAY;
+       result += newp->tm_hour - oldp->tm_hour;
+       result *= MINSPERHOUR;
+       result += newp->tm_min - oldp->tm_min;
+       result *= SECSPERMIN;
+       result += newp->tm_sec - oldp->tm_sec;
+       return result;
+}
+
+static void
+show(char *zone, time_t t, int v)
+{
+       register struct tm *    tmp;
+
+       (void) printf("%-*s  ", (int) longest, zone);
+       if (v) {
+               tmp = gmtime(&t);
+               if (tmp == NULL) {
+                       (void) printf(tformat(), t);
+               } else {
+                       dumptime(tmp);
+                       (void) printf(" UTC");
+               }
+               (void) printf(" = ");
+       }
+       tmp = my_localtime(&t);
+       dumptime(tmp);
+       if (tmp != NULL) {
+               if (*abbr(tmp) != '\0')
+                       (void) printf(" %s", abbr(tmp));
+               if (v) {
+                       (void) printf(" isdst=%d", tmp->tm_isdst);
+#ifdef TM_GMTOFF
+                       (void) printf(" gmtoff=%ld", tmp->TM_GMTOFF);
+#endif /* defined TM_GMTOFF */
+               }
+       }
+       (void) printf("\n");
+       if (tmp != NULL && *abbr(tmp) != '\0')
+               abbrok(abbr(tmp), zone);
+}
+
+static const char *
+abbr(tmp)
+struct tm *    tmp;
+{
+       register const char *   result;
+       static const char       nada;
+
+       if (tmp->tm_isdst != 0 && tmp->tm_isdst != 1)
+               return &nada;
+       result = tzname[tmp->tm_isdst];
+       return (result == NULL) ? &nada : result;
+}
+
+/*
+** The code below can fail on certain theoretical systems;
+** it works on all known real-world systems as of 2004-12-30.
+*/
+
+static const char *
+tformat(void)
+{
+       if (0.5 == (time_t) 0.5) {      /* floating */
+               if (sizeof (time_t) > sizeof (double))
+                       return "%Lg";
+               return "%g";
+       }
+       if (0 > (time_t) -1) {          /* signed */
+               if (sizeof (time_t) > sizeof (long))
+                       return "%lld";
+               if (sizeof (time_t) > sizeof (int))
+                       return "%ld";
+               return "%d";
+       }
+       if (sizeof (time_t) > sizeof (unsigned long))
+               return "%llu";
+       if (sizeof (time_t) > sizeof (unsigned int))
+               return "%lu";
+       return "%u";
+}
+
+static void
+dumptime(timeptr)
+register const struct tm *     timeptr;
+{
+       static const char       wday_name[][3] = {
+               "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+       };
+       static const char       mon_name[][3] = {
+               "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+               "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+       };
+       register const char *   wn;
+       register const char *   mn;
+       register int            lead;
+       register int            trail;
+
+       if (timeptr == NULL) {
+               (void) printf("NULL");
+               return;
+       }
+       /*
+       ** The packaged versions of localtime and gmtime never put out-of-range
+       ** values in tm_wday or tm_mon, but since this code might be compiled
+       ** with other (perhaps experimental) versions, paranoia is in order.
+       */
+       if (timeptr->tm_wday < 0 || timeptr->tm_wday >=
+               (int) (sizeof wday_name / sizeof wday_name[0]))
+                       wn = "???";
+       else            wn = wday_name[timeptr->tm_wday];
+       if (timeptr->tm_mon < 0 || timeptr->tm_mon >=
+               (int) (sizeof mon_name / sizeof mon_name[0]))
+                       mn = "???";
+       else            mn = mon_name[timeptr->tm_mon];
+       (void) printf("%.3s %.3s%3d %.2d:%.2d:%.2d ",
+               wn, mn,
+               timeptr->tm_mday, timeptr->tm_hour,
+               timeptr->tm_min, timeptr->tm_sec);
+#define DIVISOR        10
+       trail = timeptr->tm_year % DIVISOR + TM_YEAR_BASE % DIVISOR;
+       lead = timeptr->tm_year / DIVISOR + TM_YEAR_BASE / DIVISOR +
+               trail / DIVISOR;
+       trail %= DIVISOR;
+       if (trail < 0 && lead > 0) {
+               trail += DIVISOR;
+               --lead;
+       } else if (lead < 0 && trail > 0) {
+               trail -= DIVISOR;
+               ++lead;
+       }
+       if (lead == 0)
+               (void) printf("%d", trail);
+       else    (void) printf("%d%d", lead, ((trail < 0) ? -trail : trail));
+}
diff --git a/lib/nbsd_libc/time/zic.8 b/lib/nbsd_libc/time/zic.8
new file mode 100644 (file)
index 0000000..f1e00e0
--- /dev/null
@@ -0,0 +1,427 @@
+.\"    $NetBSD: zic.8,v 1.18 2010/05/30 07:57:08 wiz Exp $
+.\" @(#)zic.8  7.22
+.Dd December 20, 2003
+.Dt ZIC 8
+.Os
+.Sh NAME
+.Nm zic
+.Nd time zone compiler
+.Sh SYNOPSIS
+.Nm
+.Op Fl \-version
+.Op Fl d Ar directory
+.Op Fl L Ar leapsecondfilename
+.Op Fl l Ar localtime
+.Op Fl p Ar posixrules
+.Op Fl s
+.Op Fl v
+.Op Fl y Ar command
+.Op Ar Filename ...
+.Sh DESCRIPTION
+.Nm
+reads text from the file(s) named on the command line
+and creates the time conversion information files specified in this input.
+If a
+.Ar filename
+is
+.Ar \&- ,
+the standard input is read.
+.Pp
+These options are available:
+.Bl -tag -width XXXXXXXXXX -compact
+.It Fl \-version
+Output version information and exit.
+.It Fl d Ar directory
+Create time conversion information files in the named directory rather than
+in the standard directory named below.
+.It Fl L Ar leapsecondfilename
+Read leap second information from the file with the given name.
+If this option is not used,
+no leap second information appears in output files.
+.It Fl l Ar timezone
+Use the given time zone as local time.
+.Nm
+will act as if the input contained a link line of the form
+.Dl Link       timezone        localtime
+.It Fl p Ar timezone
+Use the given time zone's rules when handling POSIX-format
+time zone environment variables.
+.Nm
+will act as if the input contained a link line of the form
+.Dl Link       timezone        posixrules
+.It Fl s
+Limit time values stored in output files to values that are the same
+whether they're taken to be signed or unsigned.
+You can use this option to generate SVVS-compatible files.
+.It Fl v
+Complain if a year that appears in a data file is outside the range
+of years representable by
+.Xr time 3
+values.
+Also complain if a time of 24:00
+.Pq which cannot be handled by pre-1998 versions of Nm
+appears in the input.
+.It Fl y Ar command
+Use the given
+.Ar command
+rather than
+.Em yearistype
+when checking year types (see below).
+.Pp
+Input lines are made up of fields.
+Fields are separated from one another by any number of white space characters.
+Leading and trailing white space on input lines is ignored.
+An unquoted sharp character (#) in the input introduces a comment which extends
+to the end of the line the sharp character appears on.
+White space characters and sharp characters may be enclosed in double
+quotes
+.Pq \&"
+.\" XXX "
+if they're to be used as part of a field.
+Any line that is blank (after comment stripping) is ignored.
+Non-blank lines are expected to be of one of three types:
+rule lines, zone lines, and link lines.
+.Pp
+A rule line has the form
+.Dl Rule       NAME    FROM    TO      TYPE    IN      ON      AT      SAVE    LETTER/S
+For example:
+.Dl Rule       US      1967    1973    \-      Apr     lastSun 2:00    1:00    D
+The fields that make up a rule line are:
+.Bl -tag -width "LETTER/S" -compact
+.It NAME
+Gives the (arbitrary) name of the set of rules this rule is part of.
+.It FROM
+Gives the first year in which the rule applies.
+Any integer year can be supplied; the Gregorian calendar is assumed.
+The word
+.Em minimum
+(or an abbreviation) means the minimum year representable as an integer.
+The word
+.Em maximum
+(or an abbreviation) means the maximum year representable as an integer.
+Rules can describe times that are not representable as time values,
+with the unrepresentable times ignored; this allows rules to be portable
+among hosts with differing time value types.
+.It TO
+Gives the final year in which the rule applies.
+In addition to
+.Em minimum
+and
+.Em maximum
+(as above),
+the word
+.Em only
+(or an abbreviation)
+may be used to repeat the value of the
+.Em FROM
+field.
+.It TYPE
+Gives the type of year in which the rule applies.
+If
+.Em TYPE
+is
+.Em \&-
+then the rule applies in all years between
+.Em FROM
+and
+.Em TO
+inclusive.
+If
+.Em TYPE
+is something else, then
+.Nm
+executes the command
+.Pp
+.Ic yearistype Ar year type
+.Pp
+to check the type of a year:
+an exit status of zero is taken to mean that the year is of the given type;
+an exit status of one is taken to mean that the year is not of the given type.
+.It IN
+Names the month in which the rule takes effect.
+Month names may be abbreviated.
+.It ON
+Gives the day on which the rule takes effect.
+Recognized forms include:
+.Bl -tag -width lastSun -compact -offset indent
+.It 5
+the fifth of the month
+.It lastSun
+the last Sunday in the month
+.It lastMon
+the last Monday in the month
+.It Sun\*[Ge]8
+first Sunday on or after the eighth
+.It Sun\*[Le]25
+last Sunday on or before the 25th
+.El
+Names of days of the week may be abbreviated or spelled out in full.
+Note that there must be no spaces within the
+.Em ON
+field.
+.It AT
+Gives the time of day at which the rule takes effect.
+Recognized forms include:
+.Bl -tag -width "1X28X14" -compact -offset indent
+.It 2
+time in hours
+.It 2:00
+time in hours and minutes
+.It 15:00
+24-hour format time (for times after noon)
+.It 1:28:14
+time in hours, minutes, and seconds
+.It \-
+equivalent to 0
+.El
+where hour 0 is midnight at the start of the day,
+and hour 24 is midnight at the end of the day.
+Any of these forms may be followed by the letter
+.Em w
+if the given time is local
+.Dq wall clock
+time,
+.Em s
+if the given time is local
+.Dq standard
+time, or
+.Em u
+(or
+.Em g
+or
+.Em z )
+if the given time is universal time;
+in the absence of an indicator,
+wall clock time is assumed.
+.It SAVE
+Gives the amount of time to be added to local standard time when the rule is in
+effect.
+This field has the same format as the
+.Em AT
+field
+(although, of course, the
+.Em w
+and
+.Em s
+suffixes are not used).
+.It LETTER/S
+Gives the
+.Dq variable part
+(for example, the
+.Dq S
+or
+.Dq D
+in
+.Dq EST
+or
+.Dq EDT )
+of time zone abbreviations to be used when this rule is in effect.
+If this field is
+.Em \&- ,
+the variable part is null.
+.El
+.Pp
+A zone line has the form
+.sp
+.Dl Zone       NAME                    GMTOFF  RULES/SAVE      FORMAT  [UNTILYEAR [MONTH [DAY [TIME]]]]
+For example:
+.Dl Zone       Australia/Adelaide      9:30    Aus     CST     1971 Oct 31 2:00
+The fields that make up a zone line are:
+.Bl -tag -width "RULES/SAVE" -compact
+.It NAME
+The name of the time zone.
+This is the name used in creating the time conversion information file for the
+zone.
+.It GMTOFF
+The amount of time to add to UTC to get standard time in this zone.
+This field has the same format as the
+.Em AT
+and
+.Em SAVE
+fields of rule lines;
+begin the field with a minus sign if time must be subtracted from UTC.
+.It RULES/SAVE
+The name of the rule(s) that apply in the time zone or,
+alternatively, an amount of time to add to local standard time.
+If this field is
+.Em \&-
+then standard time always applies in the time zone.
+.It FORMAT
+The format for time zone abbreviations in this time zone.
+The pair of characters
+.Em %s
+is used to show where the
+.Dq variable part
+of the time zone abbreviation goes.
+Alternatively,
+a slash
+.Pq \&/
+separates standard and daylight abbreviations.
+.It UNTILYEAR [MONTH [DAY [TIME]]]
+The time at which the UTC offset or the rule(s) change for a location.
+It is specified as a year, a month, a day, and a time of day.
+If this is specified,
+the time zone information is generated from the given UTC offset
+and rule change until the time specified.
+The month, day, and time of day have the same format as the IN, ON, and AT
+fields of a rule; trailing fields can be omitted, and default to the
+earliest possible value for the missing fields.
+.El
+The next line must be a
+.Dq continuation
+line; this has the same form as a zone line except that the
+string
+.Dq Zone
+and the name are omitted, as the continuation line will
+place information starting at the time specified as the
+.Em until
+information in the previous line in the file used by the previous line.
+Continuation lines may contain
+.Em until
+information, just as zone lines do, indicating that the next line is a further
+continuation.
+.Pp
+A link line has the form
+.Dl Link       LINK-FROM       LINK-TO
+For example:
+.Dl Link       Europe/Istanbul Asia/Istanbul
+The
+.Em LINK-FROM
+field should appear as the
+.Em NAME
+field in some zone line;
+the
+.Em LINK-TO
+field is used as an alternative name for that zone.
+.Pp
+Except for continuation lines,
+lines may appear in any order in the input.
+.Pp
+Lines in the file that describes leap seconds have the following form:
+.Dl Leap       YEAR    MONTH   DAY     HH:MM:SS        CORR    R/S
+For example:
+.Dl Leap       1974    Dec     31      23:59:60        +       S
+The
+.Em YEAR ,
+.Em MONTH ,
+.Em DAY ,
+and
+.Em HH:MM:SS
+fields tell when the leap second happened.
+The
+.Em CORR
+field
+should be
+.Dq \&+
+if a second was added
+or
+.Dq \&-
+if a second was skipped.
+.\" There's no need to document the following, since it's impossible for more
+.\" than one leap second to be inserted or deleted at a time.
+.\" The C Standard is in error in suggesting the possibility.
+.\" See Terry J Quinn, The BIPM and the accurate measure of time,
+.\" Proc IEEE 79, 7 (July 1991), 894-905.
+.\"    or
+.\"    .Dq ++
+.\"    if two seconds were added
+.\"    or
+.\"    .Dq --
+.\"    if two seconds were skipped.
+The
+.Em R/S
+field
+should be (an abbreviation of)
+.Dq Stationary
+if the leap second time given by the other fields should be interpreted as UTC
+or
+(an abbreviation of)
+.Dq Rolling
+if the leap second time given by the other fields should be interpreted as
+local wall clock time.
+.El
+.Sh EXTENDED EXAMPLE
+Here is an extended example of
+.Ic zic
+input, intended to illustrate many of its features.
+.Bl -column -compact "# Rule" "Swiss" "FROM" "1995" "TYPE" "Oct" "lastSun" "1:00u" "SAVE" "LETTER/S"
+.It # Rule     NAME    FROM    TO      TYPE    IN      ON      AT      SAVE    LETTER/S
+.It Rule       Swiss   1940    only    -       Nov     2       0:00    1:00    S
+.It Rule       Swiss   1940    only    -       Dec     31      0:00    0       -
+.It Rule       Swiss   1941    1942    -       May     Sun>=1  2:00    1:00    S
+.It Rule       Swiss   1941    1942    -       Oct     Sun>=1  0:00    0
+.Pp
+.It Rule       EU      1977    1980    -       Apr     Sun>=1  1:00u   1:00    S
+.It Rule       EU      1977    only    -       Sep     lastSun 1:00u   0       -
+.It Rule       EU      1978    only    -       Oct      1      1:00u   0       -
+.It Rule       EU      1979    1995    -       Sep     lastSun 1:00u   0       -
+.It Rule       EU      1981    max     -       Mar     lastSun 1:00u   1:00    S
+.It Rule       EU      1996    max     -       Oct     lastSun 1:00u   0       -
+.El
+.Pp
+.Bl -column -compact "# Zone" "Europe/Zurich" "0:29:44" "RULES" "FORMAT" "UNTIL"
+.It # Zone     NAME    GMTOFF  RULES   FORMAT  UNTIL
+.It Zone       Europe/Zurich   0:34:08 -       LMT     1848 Sep 12
+.It            0:29:44 -       BMT     1894 Jun
+.It            1:00    Swiss   CE%sT   1981
+.It            1:00    EU      CE%sT
+.It Link       Europe/Zurich   Switzerland
+.El
+.Pp
+In this example, the zone is named Europe/Zurich but it has an alias
+as Switzerland.
+Zurich was 34 minutes and 8 seconds west of GMT until
+1848-09-12 at 00:00, when the offset changed to 29 minutes and 44
+seconds.
+After 1894-06-01 at 00:00 Swiss daylight saving rules (defined
+with lines beginning with "Rule Swiss") apply, and the GMT offset
+became one hour.
+From 1981 to the present, EU daylight saving rules have
+applied, and the UTC offset has remained at one hour.
+.Pp
+In 1940, daylight saving time applied from November 2 at 00:00 to
+December 31 at 00:00.
+In 1941 and 1942, daylight saving time applied
+from the first Sunday in May at 02:00 to the first Sunday in October
+at 00:00.
+The pre-1981 EU daylight-saving rules have no effect
+here, but are included for completeness.
+Since 1981, daylight
+saving has begun on the last Sunday in March at 01:00 UTC.
+Until 1995 it ended the last Sunday in September at 01:00 UTC,
+but this changed to the last Sunday in October starting in 1996.
+.Pp
+For purposes of
+display, "LMT" and "BMT" were initially used, respectively.
+Since
+Swiss rules and later EU rules were applied, the display name for the
+timezone has been CET for standard time and CEST for daylight saving
+time.
+.Sh NOTES
+For areas with more than two types of local time,
+you may need to use local standard time in the
+.Em AT
+field of the earliest transition time's rule to ensure that
+the earliest transition time recorded in the compiled file is correct.
+.Pp
+If,
+for a particular zone,
+a clock advance caused by the start of daylight saving
+coincides with and is equal to
+a clock retreat caused by a change in UTC offset,
+.Ic zic
+produces a single transition to daylight saving at the new UTC offset
+(without any change in wall clock time).
+To get separate transitions
+use multiple zone continuation lines
+specifying transition instants using universal time.
+.Sh FILES
+.Pa /usr/share/zoneinfo
+- standard directory used for created files
+.Sh SEE ALSO
+.Xr ctime 3 ,
+.Xr tzfile 5 ,
+.Xr zdump 8
+.\" @(#)zic.8  8.5
+.\" This file is in the public domain, so clarified as of
+.\" 2009-05-17 by Arthur David Olson.
diff --git a/lib/nbsd_libc/time/zic.c b/lib/nbsd_libc/time/zic.c
new file mode 100644 (file)
index 0000000..3b59b6c
--- /dev/null
@@ -0,0 +1,2734 @@
+/*     $NetBSD: zic.c,v 1.28 2011/01/15 12:31:57 martin Exp $  */
+/*
+** This file is in the public domain, so clarified as of
+** 2006-07-17 by Arthur David Olson.
+*/
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/cdefs.h>
+#ifndef lint
+__RCSID("$NetBSD: zic.c,v 1.28 2011/01/15 12:31:57 martin Exp $");
+#endif /* !defined lint */
+
+static char    elsieid[] = "@(#)zic.c  8.20";
+
+#include "private.h"
+#include "locale.h"
+#include "tzfile.h"
+
+#define        ZIC_VERSION     '2'
+
+typedef int_fast64_t   zic_t;
+
+#ifndef ZIC_MAX_ABBR_LEN_WO_WARN
+#define ZIC_MAX_ABBR_LEN_WO_WARN       6
+#endif /* !defined ZIC_MAX_ABBR_LEN_WO_WARN */
+
+#if HAVE_SYS_STAT_H
+#include "sys/stat.h"
+#endif
+#ifdef S_IRUSR
+#define MKDIR_UMASK (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)
+#else
+#define MKDIR_UMASK 0755
+#endif
+
+#include "unistd.h"
+
+/*
+** On some ancient hosts, predicates like `isspace(C)' are defined
+** only if isascii(C) || C == EOF. Modern hosts obey the C Standard,
+** which says they are defined only if C == ((unsigned char) C) || C == EOF.
+** Neither the C Standard nor Posix require that `isascii' exist.
+** For portability, we check both ancient and modern requirements.
+** If isascii is not defined, the isascii check succeeds trivially.
+*/
+#include "ctype.h"
+#ifndef isascii
+#define isascii(x) 1
+#endif
+
+#define OFFSET_STRLEN_MAXIMUM  (7 + INT_STRLEN_MAXIMUM(long))
+#define RULE_STRLEN_MAXIMUM    8       /* "Mdd.dd.d" */
+
+#define end(cp)        (strchr((cp), '\0'))
+
+struct rule {
+       const char *    r_filename;
+       int             r_linenum;
+       const char *    r_name;
+
+       int             r_loyear;       /* for example, 1986 */
+       int             r_hiyear;       /* for example, 1986 */
+       const char *    r_yrtype;
+       int             r_lowasnum;
+       int             r_hiwasnum;
+
+       int             r_month;        /* 0..11 */
+
+       int             r_dycode;       /* see below */
+       int             r_dayofmonth;
+       int             r_wday;
+
+       long            r_tod;          /* time from midnight */
+       int             r_todisstd;     /* above is standard time if TRUE */
+                                       /* or wall clock time if FALSE */
+       int             r_todisgmt;     /* above is GMT if TRUE */
+                                       /* or local time if FALSE */
+       long            r_stdoff;       /* offset from standard time */
+       const char *    r_abbrvar;      /* variable part of abbreviation */
+
+       int             r_todo;         /* a rule to do (used in outzone) */
+       zic_t           r_temp;         /* used in outzone */
+};
+
+/*
+**     r_dycode                r_dayofmonth    r_wday
+*/
+
+#define DC_DOM         0       /* 1..31 */     /* unused */
+#define DC_DOWGEQ      1       /* 1..31 */     /* 0..6 (Sun..Sat) */
+#define DC_DOWLEQ      2       /* 1..31 */     /* 0..6 (Sun..Sat) */
+
+struct zone {
+       const char *    z_filename;
+       int             z_linenum;
+
+       const char *    z_name;
+       long            z_gmtoff;
+       const char *    z_rule;
+       const char *    z_format;
+
+       long            z_stdoff;
+
+       struct rule *   z_rules;
+       int             z_nrules;
+
+       struct rule     z_untilrule;
+       zic_t           z_untiltime;
+};
+
+extern int     getopt(int argc, char * const argv[],
+                       const char * options);
+extern int     link(const char * fromname, const char * toname);
+extern char *  optarg;
+extern int     optind;
+
+static void    addtt(zic_t starttime, int type);
+static int     addtype(long gmtoff, const char * abbr, int isdst,
+                               int ttisstd, int ttisgmt);
+static void    leapadd(zic_t t, int positive, int rolling, int count);
+static void    adjleap(void);
+static void    associate(void);
+static int     ciequal(const char * ap, const char * bp);
+static void    convert(long val, char * buf);
+static void    convert64(zic_t val, char * buf);
+static void    dolink(const char * fromfield, const char * tofield);
+static void    doabbr(char * abbr, const int, const char * format,
+                       const char * letters, int isdst, int doquotes);
+static void    eat(const char * name, int num);
+static void    eats(const char * name, int num,
+                       const char * rname, int rnum);
+static long    eitol(int i);
+static void    error(const char * message);
+static char ** getfields(char * buf);
+static long    gethms(const char * string, const char * errstrng,
+                       int signable);
+static void    infile(const char * filename);
+static void    inleap(char ** fields, int nfields);
+static void    inlink(char ** fields, int nfields);
+static void    inrule(char ** fields, int nfields);
+static int     inzcont(char ** fields, int nfields);
+static int     inzone(char ** fields, int nfields);
+static int     inzsub(char ** fields, int nfields, int iscont);
+static int     is32(zic_t x);
+static int     itsabbr(const char * abbr, const char * word);
+static int     itsdir(const char * name);
+static int     lowerit(int c);
+int            main(int, char **);
+static char *  memcheck(char * tocheck);
+static int     mkdirs(char * filename);
+static void    newabbr(const char * abbr);
+static long    oadd(long t1, long t2);
+static void    outzone(const struct zone * zp, int ntzones);
+static void    puttzcode(long code, FILE * fp);
+static void    puttzcode64(zic_t code, FILE * fp);
+static int     rcomp(const void * leftp, const void * rightp);
+static zic_t   rpytime(const struct rule * rp, int wantedy);
+static void    rulesub(struct rule * rp,
+                       const char * loyearp, const char * hiyearp,
+                       const char * typep, const char * monthp,
+                       const char * dayp, const char * timep);
+static int     stringoffset(char * result, long offset);
+static int     stringrule(char * result, const struct rule * rp,
+                       long dstoff, long gmtoff);
+static void    stringzone(char * result, const int,
+                       const struct zone * zp, int ntzones);
+static void    setboundaries(void);
+static zic_t   tadd(zic_t t1, long t2);
+static void    usage(FILE *stream, int status);
+static void    warning(const char * const);
+static void    writezone(const char * name, const char * string);
+static int     yearistype(int year, const char * type);
+static int     atcomp(const void *avp, const void *bvp);
+static void    updateminmax(int x);
+
+static int             charcnt;
+static int             errors;
+static const char *    filename;
+static int             leapcnt;
+static int             leapseen;
+static int             leapminyear;
+static int             leapmaxyear;
+static int             linenum;
+static int             max_abbrvar_len;
+static int             max_format_len;
+static zic_t           max_time;
+static int             max_year;
+static zic_t           min_time;
+static int             min_year;
+static int             noise;
+static const char *    rfilename;
+static int             rlinenum;
+static const char *    progname;
+static int             timecnt;
+static int             typecnt;
+
+/*
+** Line codes.
+*/
+
+#define LC_RULE                0
+#define LC_ZONE                1
+#define LC_LINK                2
+#define LC_LEAP                3
+
+/*
+** Which fields are which on a Zone line.
+*/
+
+#define ZF_NAME                1
+#define ZF_GMTOFF      2
+#define ZF_RULE                3
+#define ZF_FORMAT      4
+#define ZF_TILYEAR     5
+#define ZF_TILMONTH    6
+#define ZF_TILDAY      7
+#define ZF_TILTIME     8
+#define ZONE_MINFIELDS 5
+#define ZONE_MAXFIELDS 9
+
+/*
+** Which fields are which on a Zone continuation line.
+*/
+
+#define ZFC_GMTOFF     0
+#define ZFC_RULE       1
+#define ZFC_FORMAT     2
+#define ZFC_TILYEAR    3
+#define ZFC_TILMONTH   4
+#define ZFC_TILDAY     5
+#define ZFC_TILTIME    6
+#define ZONEC_MINFIELDS        3
+#define ZONEC_MAXFIELDS        7
+
+/*
+** Which files are which on a Rule line.
+*/
+
+#define RF_NAME                1
+#define RF_LOYEAR      2
+#define RF_HIYEAR      3
+#define RF_COMMAND     4
+#define RF_MONTH       5
+#define RF_DAY         6
+#define RF_TOD         7
+#define RF_STDOFF      8
+#define RF_ABBRVAR     9
+#define RULE_FIELDS    10
+
+/*
+** Which fields are which on a Link line.
+*/
+
+#define LF_FROM                1
+#define LF_TO          2
+#define LINK_FIELDS    3
+
+/*
+** Which fields are which on a Leap line.
+*/
+
+#define LP_YEAR                1
+#define LP_MONTH       2
+#define LP_DAY         3
+#define LP_TIME                4
+#define LP_CORR                5
+#define LP_ROLL                6
+#define LEAP_FIELDS    7
+
+/*
+** Year synonyms.
+*/
+
+#define YR_MINIMUM     0
+#define YR_MAXIMUM     1
+#define YR_ONLY                2
+
+static struct rule *   rules;
+static int             nrules; /* number of rules */
+
+static struct zone *   zones;
+static int             nzones; /* number of zones */
+
+struct link {
+       const char *    l_filename;
+       int             l_linenum;
+       const char *    l_from;
+       const char *    l_to;
+};
+
+static struct link *   links;
+static int             nlinks;
+
+struct lookup {
+       const char *    l_word;
+       const int       l_value;
+};
+
+static struct lookup const *   byword(const char * string,
+                                       const struct lookup * lp);
+
+static struct lookup const     line_codes[] = {
+       { "Rule",       LC_RULE },
+       { "Zone",       LC_ZONE },
+       { "Link",       LC_LINK },
+       { "Leap",       LC_LEAP },
+       { NULL,         0}
+};
+
+static struct lookup const     mon_names[] = {
+       { "January",    TM_JANUARY },
+       { "February",   TM_FEBRUARY },
+       { "March",      TM_MARCH },
+       { "April",      TM_APRIL },
+       { "May",        TM_MAY },
+       { "June",       TM_JUNE },
+       { "July",       TM_JULY },
+       { "August",     TM_AUGUST },
+       { "September",  TM_SEPTEMBER },
+       { "October",    TM_OCTOBER },
+       { "November",   TM_NOVEMBER },
+       { "December",   TM_DECEMBER },
+       { NULL,         0 }
+};
+
+static struct lookup const     wday_names[] = {
+       { "Sunday",     TM_SUNDAY },
+       { "Monday",     TM_MONDAY },
+       { "Tuesday",    TM_TUESDAY },
+       { "Wednesday",  TM_WEDNESDAY },
+       { "Thursday",   TM_THURSDAY },
+       { "Friday",     TM_FRIDAY },
+       { "Saturday",   TM_SATURDAY },
+       { NULL,         0 }
+};
+
+static struct lookup const     lasts[] = {
+       { "last-Sunday",        TM_SUNDAY },
+       { "last-Monday",        TM_MONDAY },
+       { "last-Tuesday",       TM_TUESDAY },
+       { "last-Wednesday",     TM_WEDNESDAY },
+       { "last-Thursday",      TM_THURSDAY },
+       { "last-Friday",        TM_FRIDAY },
+       { "last-Saturday",      TM_SATURDAY },
+       { NULL,                 0 }
+};
+
+static struct lookup const     begin_years[] = {
+       { "minimum",    YR_MINIMUM },
+       { "maximum",    YR_MAXIMUM },
+       { NULL,         0 }
+};
+
+static struct lookup const     end_years[] = {
+       { "minimum",    YR_MINIMUM },
+       { "maximum",    YR_MAXIMUM },
+       { "only",       YR_ONLY },
+       { NULL,         0 }
+};
+
+static struct lookup const     leap_types[] = {
+       { "Rolling",    TRUE },
+       { "Stationary", FALSE },
+       { NULL,         0 }
+};
+
+static const int       len_months[2][MONSPERYEAR] = {
+       { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
+       { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
+};
+
+static const int       len_years[2] = {
+       DAYSPERNYEAR, DAYSPERLYEAR
+};
+
+static struct attype {
+       zic_t           at;
+       unsigned char   type;
+}                      attypes[TZ_MAX_TIMES];
+static long            gmtoffs[TZ_MAX_TYPES];
+static char            isdsts[TZ_MAX_TYPES];
+static unsigned char   abbrinds[TZ_MAX_TYPES];
+static char            ttisstds[TZ_MAX_TYPES];
+static char            ttisgmts[TZ_MAX_TYPES];
+static char            chars[TZ_MAX_CHARS];
+static zic_t           trans[TZ_MAX_LEAPS];
+static long            corr[TZ_MAX_LEAPS];
+static char            roll[TZ_MAX_LEAPS];
+
+/*
+** Memory allocation.
+*/
+
+static char *
+memcheck(ptr)
+char * const   ptr;
+{
+       if (ptr == NULL) {
+               const char *e = strerror(errno);
+
+               (void) fprintf(stderr, _("%s: Memory exhausted: %s\n"),
+                       progname, e);
+               exit(EXIT_FAILURE);
+       }
+       return ptr;
+}
+
+#define emalloc(size)          memcheck(imalloc(size))
+#define erealloc(ptr, size)    memcheck(irealloc((ptr), (size)))
+#define ecpyalloc(ptr)         memcheck(icpyalloc(ptr))
+#define ecatalloc(oldp, newp)  memcheck(icatalloc((oldp), (newp)))
+
+/*
+** Error handling.
+*/
+
+static void
+eats(name, num, rname, rnum)
+const char * const     name;
+const int              num;
+const char * const     rname;
+const int              rnum;
+{
+       filename = name;
+       linenum = num;
+       rfilename = rname;
+       rlinenum = rnum;
+}
+
+static void
+eat(name, num)
+const char * const     name;
+const int              num;
+{
+       eats(name, num, (char *) NULL, -1);
+}
+
+static void
+error(string)
+const char * const     string;
+{
+       /*
+       ** Match the format of "cc" to allow sh users to
+       **      zic ... 2>&1 | error -t "*" -v
+       ** on BSD systems.
+       */
+       (void) fprintf(stderr, _("\"%s\", line %d: %s"),
+               filename, linenum, string);
+       if (rfilename != NULL)
+               (void) fprintf(stderr, _(" (rule from \"%s\", line %d)"),
+                       rfilename, rlinenum);
+       (void) fprintf(stderr, "\n");
+       ++errors;
+}
+
+static void
+warning(string)
+const char * const     string;
+{
+       char *  cp;
+
+       cp = ecpyalloc(_("warning: "));
+       cp = ecatalloc(cp, string);
+       error(cp);
+       ifree(cp);
+       --errors;
+}
+
+static void
+usage(FILE *stream, int status)
+{
+       (void) fprintf(stream, _("%s: usage is %s \
+[ --version ] [ --help ] [ -v ] [ -l localtime ] [ -p posixrules ] \\\n\
+\t[ -d directory ] [ -L leapseconds ] [ -y yearistype ] [ filename ... ]\n\
+\n\
+Report bugs to tz@elsie.nci.nih.gov.\n"),
+                      progname, progname);
+       exit(status);
+}
+
+static const char *    psxrules;
+static const char *    lcltime;
+static const char *    directory;
+static const char *    leapsec;
+static const char *    yitcommand;
+
+int
+main(argc, argv)
+int    argc;
+char * argv[];
+{
+       register int    i;
+       register int    j;
+       register int    c;
+
+#ifdef _POSIX_VERSION
+       (void) umask(umask(S_IWGRP | S_IWOTH) | (S_IWGRP | S_IWOTH));
+#endif /* defined _POSIX_VERSION */
+#if HAVE_GETTEXT - 0
+       (void) setlocale(LC_MESSAGES, "");
+#ifdef TZ_DOMAINDIR
+       (void) bindtextdomain(TZ_DOMAIN, TZ_DOMAINDIR);
+#endif /* defined TEXTDOMAINDIR */
+       (void) textdomain(TZ_DOMAIN);
+#endif /* HAVE_GETTEXT */
+       progname = argv[0];
+       if (TYPE_BIT(zic_t) < 64) {
+               (void) fprintf(stderr, "%s: %s\n", progname,
+                       _("wild compilation-time specification of zic_t"));
+               exit(EXIT_FAILURE);
+       }
+       for (i = 1; i < argc; ++i)
+               if (strcmp(argv[i], "--version") == 0) {
+                       (void) printf("%s\n", elsieid);
+                       exit(EXIT_SUCCESS);
+               } else if (strcmp(argv[i], "--help") == 0) {
+                       usage(stdout, EXIT_SUCCESS);
+               }
+       while ((c = getopt(argc, argv, "d:l:p:L:vsy:")) != EOF && c != -1)
+               switch (c) {
+                       default:
+                               usage(stderr, EXIT_FAILURE);
+                       case 'd':
+                               if (directory == NULL)
+                                       directory = optarg;
+                               else {
+                                       (void) fprintf(stderr,
+_("%s: More than one -d option specified\n"),
+                                               progname);
+                                       exit(EXIT_FAILURE);
+                               }
+                               break;
+                       case 'l':
+                               if (lcltime == NULL)
+                                       lcltime = optarg;
+                               else {
+                                       (void) fprintf(stderr,
+_("%s: More than one -l option specified\n"),
+                                               progname);
+                                       exit(EXIT_FAILURE);
+                               }
+                               break;
+                       case 'p':
+                               if (psxrules == NULL)
+                                       psxrules = optarg;
+                               else {
+                                       (void) fprintf(stderr,
+_("%s: More than one -p option specified\n"),
+                                               progname);
+                                       exit(EXIT_FAILURE);
+                               }
+                               break;
+                       case 'y':
+                               if (yitcommand == NULL)
+                                       yitcommand = optarg;
+                               else {
+                                       (void) fprintf(stderr,
+_("%s: More than one -y option specified\n"),
+                                               progname);
+                                       exit(EXIT_FAILURE);
+                               }
+                               break;
+                       case 'L':
+                               if (leapsec == NULL)
+                                       leapsec = optarg;
+                               else {
+                                       (void) fprintf(stderr,
+_("%s: More than one -L option specified\n"),
+                                               progname);
+                                       exit(EXIT_FAILURE);
+                               }
+                               break;
+                       case 'v':
+                               noise = TRUE;
+                               break;
+                       case 's':
+                               (void) printf("%s: -s ignored\n", progname);
+                               break;
+               }
+       if (optind == argc - 1 && strcmp(argv[optind], "=") == 0)
+               usage(stderr, EXIT_FAILURE);    /* usage message by request */
+       if (directory == NULL)
+               directory = TZDIR;
+       if (yitcommand == NULL)
+               yitcommand = "yearistype";
+
+       setboundaries();
+
+       if (optind < argc && leapsec != NULL) {
+               infile(leapsec);
+               adjleap();
+       }
+
+       for (i = optind; i < argc; ++i)
+               infile(argv[i]);
+       if (errors)
+               exit(EXIT_FAILURE);
+       associate();
+       for (i = 0; i < nzones; i = j) {
+               /*
+               ** Find the next non-continuation zone entry.
+               */
+               for (j = i + 1; j < nzones && zones[j].z_name == NULL; ++j)
+                       continue;
+               outzone(&zones[i], j - i);
+       }
+       /*
+       ** Make links.
+       */
+       for (i = 0; i < nlinks; ++i) {
+               eat(links[i].l_filename, links[i].l_linenum);
+               dolink(links[i].l_from, links[i].l_to);
+               if (noise)
+                       for (j = 0; j < nlinks; ++j)
+                               if (strcmp(links[i].l_to,
+                                       links[j].l_from) == 0)
+                                               warning(_("link to link"));
+       }
+       if (lcltime != NULL) {
+               eat("command line", 1);
+               dolink(lcltime, TZDEFAULT);
+       }
+       if (psxrules != NULL) {
+               eat("command line", 1);
+               dolink(psxrules, TZDEFRULES);
+       }
+       return (errors == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
+}
+
+static void
+dolink(fromfield, tofield)
+const char * const     fromfield;
+const char * const     tofield;
+{
+       register char * fromname;
+       register char * toname;
+
+       if (fromfield[0] == '/')
+               fromname = ecpyalloc(fromfield);
+       else {
+               fromname = ecpyalloc(directory);
+               fromname = ecatalloc(fromname, "/");
+               fromname = ecatalloc(fromname, fromfield);
+       }
+       if (tofield[0] == '/')
+               toname = ecpyalloc(tofield);
+       else {
+               toname = ecpyalloc(directory);
+               toname = ecatalloc(toname, "/");
+               toname = ecatalloc(toname, tofield);
+       }
+       /*
+       ** We get to be careful here since
+       ** there's a fair chance of root running us.
+       */
+       if (!itsdir(toname))
+               (void) remove(toname);
+       if (link(fromname, toname) != 0) {
+               int     result;
+
+               if (mkdirs(toname) != 0)
+                       exit(EXIT_FAILURE);
+
+               result = link(fromname, toname);
+#if HAVE_SYMLINK
+               if (result != 0 &&
+                       access(fromname, F_OK) == 0 &&
+                       !itsdir(fromname)) {
+                               const char *s = tofield;
+                               register char * symlinkcontents = NULL;
+
+                               while ((s = strchr(s+1, '/')) != NULL)
+                                       symlinkcontents =
+                                               ecatalloc(symlinkcontents,
+                                               "../");
+                               symlinkcontents =
+                                       ecatalloc(symlinkcontents,
+                                       fromname);
+                               result = symlink(symlinkcontents,
+                                       toname);
+                               if (result == 0)
+warning(_("hard link failed, symbolic link used"));
+                               ifree(symlinkcontents);
+               }
+#endif /* HAVE_SYMLINK */
+               if (result != 0) {
+                       const char *e = strerror(errno);
+
+                       (void) fprintf(stderr,
+                               _("%s: Can't link from %s to %s: %s\n"),
+                               progname, fromname, toname, e);
+                       exit(EXIT_FAILURE);
+               }
+       }
+       ifree(fromname);
+       ifree(toname);
+}
+
+#define TIME_T_BITS_IN_FILE    64
+
+static void
+setboundaries(void)
+{
+       register int    i;
+
+       min_time = -1;
+       for (i = 0; i < TIME_T_BITS_IN_FILE - 1; ++i)
+               min_time *= 2;
+       max_time = -(min_time + 1);
+}
+
+static int
+itsdir(name)
+const char * const     name;
+{
+       register char * myname;
+       register int    accres;
+
+       myname = ecpyalloc(name);
+       myname = ecatalloc(myname, "/.");
+       accres = access(myname, F_OK);
+       ifree(myname);
+       return accres == 0;
+}
+
+/*
+** Associate sets of rules with zones.
+*/
+
+/*
+** Sort by rule name.
+*/
+
+static int
+rcomp(cp1, cp2)
+const void *   cp1;
+const void *   cp2;
+{
+       return strcmp(((const struct rule *) cp1)->r_name,
+               ((const struct rule *) cp2)->r_name);
+}
+
+static void
+associate(void)
+{
+       register struct zone *  zp;
+       register struct rule *  rp;
+       register int            base, out;
+       register int            i, j;
+
+       if (nrules != 0) {
+               (void) qsort((void *) rules, (size_t) nrules,
+                       (size_t) sizeof *rules, rcomp);
+               for (i = 0; i < nrules - 1; ++i) {
+                       if (strcmp(rules[i].r_name,
+                               rules[i + 1].r_name) != 0)
+                                       continue;
+                       if (strcmp(rules[i].r_filename,
+                               rules[i + 1].r_filename) == 0)
+                                       continue;
+                       eat(rules[i].r_filename, rules[i].r_linenum);
+                       warning(_("same rule name in multiple files"));
+                       eat(rules[i + 1].r_filename, rules[i + 1].r_linenum);
+                       warning(_("same rule name in multiple files"));
+                       for (j = i + 2; j < nrules; ++j) {
+                               if (strcmp(rules[i].r_name,
+                                       rules[j].r_name) != 0)
+                                               break;
+                               if (strcmp(rules[i].r_filename,
+                                       rules[j].r_filename) == 0)
+                                               continue;
+                               if (strcmp(rules[i + 1].r_filename,
+                                       rules[j].r_filename) == 0)
+                                               continue;
+                               break;
+                       }
+                       i = j - 1;
+               }
+       }
+       for (i = 0; i < nzones; ++i) {
+               zp = &zones[i];
+               zp->z_rules = NULL;
+               zp->z_nrules = 0;
+       }
+       for (base = 0; base < nrules; base = out) {
+               rp = &rules[base];
+               for (out = base + 1; out < nrules; ++out)
+                       if (strcmp(rp->r_name, rules[out].r_name) != 0)
+                               break;
+               for (i = 0; i < nzones; ++i) {
+                       zp = &zones[i];
+                       if (strcmp(zp->z_rule, rp->r_name) != 0)
+                               continue;
+                       zp->z_rules = rp;
+                       zp->z_nrules = out - base;
+               }
+       }
+       for (i = 0; i < nzones; ++i) {
+               zp = &zones[i];
+               if (zp->z_nrules == 0) {
+                       /*
+                       ** Maybe we have a local standard time offset.
+                       */
+                       eat(zp->z_filename, zp->z_linenum);
+                       zp->z_stdoff = gethms(zp->z_rule, _("unruly zone"),
+                               TRUE);
+                       /*
+                       ** Note, though, that if there's no rule,
+                       ** a '%s' in the format is a bad thing.
+                       */
+                       if (strchr(zp->z_format, '%') != 0)
+                               error(_("%s in ruleless zone"));
+               }
+       }
+       if (errors)
+               exit(EXIT_FAILURE);
+}
+
+static void
+infile(name)
+const char *   name;
+{
+       register FILE *                 fp;
+       register char **                fields;
+       register char *                 cp;
+       register const struct lookup *  lp;
+       register int                    nfields;
+       register int                    wantcont;
+       register int                    num;
+       char                            buf[BUFSIZ];
+
+       if (strcmp(name, "-") == 0) {
+               name = _("standard input");
+               fp = stdin;
+       } else if ((fp = fopen(name, "r")) == NULL) {
+               const char *e = strerror(errno);
+
+               (void) fprintf(stderr, _("%s: Can't open %s: %s\n"),
+                       progname, name, e);
+               exit(EXIT_FAILURE);
+       }
+       wantcont = FALSE;
+       for (num = 1; ; ++num) {
+               eat(name, num);
+               if (fgets(buf, (int) sizeof buf, fp) != buf)
+                       break;
+               cp = strchr(buf, '\n');
+               if (cp == NULL) {
+                       error(_("line too long"));
+                       exit(EXIT_FAILURE);
+               }
+               *cp = '\0';
+               fields = getfields(buf);
+               nfields = 0;
+               while (fields[nfields] != NULL) {
+                       static char     nada;
+
+                       if (strcmp(fields[nfields], "-") == 0)
+                               fields[nfields] = &nada;
+                       ++nfields;
+               }
+               if (nfields == 0) {
+                       /* nothing to do */
+               } else if (wantcont) {
+                       wantcont = inzcont(fields, nfields);
+               } else {
+                       lp = byword(fields[0], line_codes);
+                       if (lp == NULL)
+                               error(_("input line of unknown type"));
+                       else switch ((int) (lp->l_value)) {
+                               case LC_RULE:
+                                       inrule(fields, nfields);
+                                       wantcont = FALSE;
+                                       break;
+                               case LC_ZONE:
+                                       wantcont = inzone(fields, nfields);
+                                       break;
+                               case LC_LINK:
+                                       inlink(fields, nfields);
+                                       wantcont = FALSE;
+                                       break;
+                               case LC_LEAP:
+                                       if (name != leapsec)
+                                               (void) fprintf(stderr,
+_("%s: Leap line in non leap seconds file %s\n"),
+                                                       progname, name);
+                                       else    inleap(fields, nfields);
+                                       wantcont = FALSE;
+                                       break;
+                               default:        /* "cannot happen" */
+                                       (void) fprintf(stderr,
+_("%s: panic: Invalid l_value %d\n"),
+                                               progname, lp->l_value);
+                                       exit(EXIT_FAILURE);
+                       }
+               }
+               ifree((char *) fields);
+       }
+       if (ferror(fp)) {
+               (void) fprintf(stderr, _("%s: Error reading %s\n"),
+                       progname, filename);
+               exit(EXIT_FAILURE);
+       }
+       if (fp != stdin && fclose(fp)) {
+               const char *e = strerror(errno);
+
+               (void) fprintf(stderr, _("%s: Error closing %s: %s\n"),
+                       progname, filename, e);
+               exit(EXIT_FAILURE);
+       }
+       if (wantcont)
+               error(_("expected continuation line not found"));
+}
+
+/*
+** Convert a string of one of the forms
+**     h       -h      hh:mm   -hh:mm  hh:mm:ss        -hh:mm:ss
+** into a number of seconds.
+** A null string maps to zero.
+** Call error with errstring and return zero on errors.
+*/
+
+static long
+gethms(string, errstring, signable)
+const char *           string;
+const char * const     errstring;
+const int              signable;
+{
+       long    hh;
+       int     mm, ss, sign;
+
+       if (string == NULL || *string == '\0')
+               return 0;
+       if (!signable)
+               sign = 1;
+       else if (*string == '-') {
+               sign = -1;
+               ++string;
+       } else  sign = 1;
+       if (sscanf(string, scheck(string, "%ld"), &hh) == 1)
+               mm = ss = 0;
+       else if (sscanf(string, scheck(string, "%ld:%d"), &hh, &mm) == 2)
+               ss = 0;
+       else if (sscanf(string, scheck(string, "%ld:%d:%d"),
+               &hh, &mm, &ss) != 3) {
+                       error(errstring);
+                       return 0;
+       }
+       if (hh < 0 ||
+               mm < 0 || mm >= MINSPERHOUR ||
+               ss < 0 || ss > SECSPERMIN) {
+                       error(errstring);
+                       return 0;
+       }
+       if (LONG_MAX / SECSPERHOUR < hh) {
+               error(_("time overflow"));
+               return 0;
+       }
+       if (noise && hh == HOURSPERDAY && mm == 0 && ss == 0)
+               warning(_("24:00 not handled by pre-1998 versions of zic"));
+       if (noise && (hh > HOURSPERDAY ||
+               (hh == HOURSPERDAY && (mm != 0 || ss != 0))))
+warning(_("values over 24 hours not handled by pre-2007 versions of zic"));
+       return oadd(eitol(sign) * hh * eitol(SECSPERHOUR),
+                   eitol(sign) * (eitol(mm) * eitol(SECSPERMIN) + eitol(ss)));
+}
+
+static void
+inrule(fields, nfields)
+register char ** const fields;
+const int              nfields;
+{
+       static struct rule      r;
+
+       if (nfields != RULE_FIELDS) {
+               error(_("wrong number of fields on Rule line"));
+               return;
+       }
+       if (*fields[RF_NAME] == '\0') {
+               error(_("nameless rule"));
+               return;
+       }
+       r.r_filename = filename;
+       r.r_linenum = linenum;
+       r.r_stdoff = gethms(fields[RF_STDOFF], _("invalid saved time"), TRUE);
+       rulesub(&r, fields[RF_LOYEAR], fields[RF_HIYEAR], fields[RF_COMMAND],
+               fields[RF_MONTH], fields[RF_DAY], fields[RF_TOD]);
+       r.r_name = ecpyalloc(fields[RF_NAME]);
+       r.r_abbrvar = ecpyalloc(fields[RF_ABBRVAR]);
+       if (max_abbrvar_len < strlen(r.r_abbrvar))
+               max_abbrvar_len = strlen(r.r_abbrvar);
+       rules = (struct rule *) (void *) erealloc((char *) rules,
+               (int) ((nrules + 1) * sizeof *rules));
+       rules[nrules++] = r;
+}
+
+static int
+inzone(fields, nfields)
+register char ** const fields;
+const int              nfields;
+{
+       register int    i;
+       static char *   buf;
+
+       if (nfields < ZONE_MINFIELDS || nfields > ZONE_MAXFIELDS) {
+               error(_("wrong number of fields on Zone line"));
+               return FALSE;
+       }
+       if (strcmp(fields[ZF_NAME], TZDEFAULT) == 0 && lcltime != NULL) {
+               buf = erealloc(buf, (int) (132 + strlen(TZDEFAULT)));
+               (void)sprintf(buf,      /* XXX: sprintf is safe */
+_("\"Zone %s\" line and -l option are mutually exclusive"),
+                       TZDEFAULT);
+               error(buf);
+               return FALSE;
+       }
+       if (strcmp(fields[ZF_NAME], TZDEFRULES) == 0 && psxrules != NULL) {
+               buf = erealloc(buf, (int) (132 + strlen(TZDEFRULES)));
+               (void)sprintf(buf,      /* XXX: sprintf is safe */
+_("\"Zone %s\" line and -p option are mutually exclusive"),
+                       TZDEFRULES);
+               error(buf);
+               return FALSE;
+       }
+       for (i = 0; i < nzones; ++i)
+               if (zones[i].z_name != NULL &&
+                       strcmp(zones[i].z_name, fields[ZF_NAME]) == 0) {
+                               buf = erealloc(buf, (int) (132 +
+                                       strlen(fields[ZF_NAME]) +
+                                       strlen(zones[i].z_filename)));
+                               (void)sprintf(buf,      /* XXX: sprintf is safe */
+_("duplicate zone name %s (file \"%s\", line %d)"),
+                                       fields[ZF_NAME],
+                                       zones[i].z_filename,
+                                       zones[i].z_linenum);
+                               error(buf);
+                               return FALSE;
+               }
+       return inzsub(fields, nfields, FALSE);
+}
+
+static int
+inzcont(fields, nfields)
+register char ** const fields;
+const int              nfields;
+{
+       if (nfields < ZONEC_MINFIELDS || nfields > ZONEC_MAXFIELDS) {
+               error(_("wrong number of fields on Zone continuation line"));
+               return FALSE;
+       }
+       return inzsub(fields, nfields, TRUE);
+}
+
+static int
+inzsub(fields, nfields, iscont)
+register char ** const fields;
+const int              nfields;
+const int              iscont;
+{
+       register char *         cp;
+       static struct zone      z;
+       register int            i_gmtoff, i_rule, i_format;
+       register int            i_untilyear, i_untilmonth;
+       register int            i_untilday, i_untiltime;
+       register int            hasuntil;
+
+       if (iscont) {
+               i_gmtoff = ZFC_GMTOFF;
+               i_rule = ZFC_RULE;
+               i_format = ZFC_FORMAT;
+               i_untilyear = ZFC_TILYEAR;
+               i_untilmonth = ZFC_TILMONTH;
+               i_untilday = ZFC_TILDAY;
+               i_untiltime = ZFC_TILTIME;
+               z.z_name = NULL;
+       } else {
+               i_gmtoff = ZF_GMTOFF;
+               i_rule = ZF_RULE;
+               i_format = ZF_FORMAT;
+               i_untilyear = ZF_TILYEAR;
+               i_untilmonth = ZF_TILMONTH;
+               i_untilday = ZF_TILDAY;
+               i_untiltime = ZF_TILTIME;
+               z.z_name = ecpyalloc(fields[ZF_NAME]);
+       }
+       z.z_filename = filename;
+       z.z_linenum = linenum;
+       z.z_gmtoff = gethms(fields[i_gmtoff], _("invalid UTC offset"), TRUE);
+       if ((cp = strchr(fields[i_format], '%')) != 0) {
+               if (*++cp != 's' || strchr(cp, '%') != 0) {
+                       error(_("invalid abbreviation format"));
+                       return FALSE;
+               }
+       }
+       z.z_rule = ecpyalloc(fields[i_rule]);
+       z.z_format = ecpyalloc(fields[i_format]);
+       if (max_format_len < strlen(z.z_format))
+               max_format_len = strlen(z.z_format);
+       hasuntil = nfields > i_untilyear;
+       if (hasuntil) {
+               z.z_untilrule.r_filename = filename;
+               z.z_untilrule.r_linenum = linenum;
+               rulesub(&z.z_untilrule,
+                       fields[i_untilyear],
+                       "only",
+                       "",
+                       (nfields > i_untilmonth) ?
+                       fields[i_untilmonth] : "Jan",
+                       (nfields > i_untilday) ? fields[i_untilday] : "1",
+                       (nfields > i_untiltime) ? fields[i_untiltime] : "0");
+               z.z_untiltime = rpytime(&z.z_untilrule,
+                       z.z_untilrule.r_loyear);
+               if (iscont && nzones > 0 &&
+                       z.z_untiltime > min_time &&
+                       z.z_untiltime < max_time &&
+                       zones[nzones - 1].z_untiltime > min_time &&
+                       zones[nzones - 1].z_untiltime < max_time &&
+                       zones[nzones - 1].z_untiltime >= z.z_untiltime) {
+                               error(_(
+"Zone continuation line end time is not after end time of previous line"
+                                       ));
+                               return FALSE;
+               }
+       }
+       zones = (struct zone *) (void *) erealloc((char *) zones,
+               (int) ((nzones + 1) * sizeof *zones));
+       zones[nzones++] = z;
+       /*
+       ** If there was an UNTIL field on this line,
+       ** there's more information about the zone on the next line.
+       */
+       return hasuntil;
+}
+
+static void
+inleap(fields, nfields)
+register char ** const fields;
+const int              nfields;
+{
+       register const char *           cp;
+       register const struct lookup *  lp;
+       register int                    i, j;
+       int                             year, month, day;
+       long                            dayoff, tod;
+       zic_t                           t;
+
+       if (nfields != LEAP_FIELDS) {
+               error(_("wrong number of fields on Leap line"));
+               return;
+       }
+       dayoff = 0;
+       cp = fields[LP_YEAR];
+       if (sscanf(cp, scheck(cp, "%d"), &year) != 1) {
+               /*
+               ** Leapin' Lizards!
+               */
+               error(_("invalid leaping year"));
+               return;
+       }
+       if (!leapseen || leapmaxyear < year)
+               leapmaxyear = year;
+       if (!leapseen || leapminyear > year)
+               leapminyear = year;
+       leapseen = TRUE;
+       j = EPOCH_YEAR;
+       while (j != year) {
+               if (year > j) {
+                       i = len_years[isleap(j)];
+                       ++j;
+               } else {
+                       --j;
+                       i = -len_years[isleap(j)];
+               }
+               dayoff = oadd(dayoff, eitol(i));
+       }
+       if ((lp = byword(fields[LP_MONTH], mon_names)) == NULL) {
+               error(_("invalid month name"));
+               return;
+       }
+       month = lp->l_value;
+       j = TM_JANUARY;
+       while (j != month) {
+               i = len_months[isleap(year)][j];
+               dayoff = oadd(dayoff, eitol(i));
+               ++j;
+       }
+       cp = fields[LP_DAY];
+       if (sscanf(cp, scheck(cp, "%d"), &day) != 1 ||
+               day <= 0 || day > len_months[isleap(year)][month]) {
+                       error(_("invalid day of month"));
+                       return;
+       }
+       dayoff = oadd(dayoff, eitol(day - 1));
+       if (dayoff < 0 && !TYPE_SIGNED(zic_t)) {
+               error(_("time before zero"));
+               return;
+       }
+       if (dayoff < min_time / SECSPERDAY) {
+               error(_("time too small"));
+               return;
+       }
+       if (dayoff > max_time / SECSPERDAY) {
+               error(_("time too large"));
+               return;
+       }
+       t = (zic_t) dayoff * SECSPERDAY;
+       tod = gethms(fields[LP_TIME], _("invalid time of day"), FALSE);
+       cp = fields[LP_CORR];
+       {
+               register int    positive;
+               int             count;
+
+               if (strcmp(cp, "") == 0) { /* infile() turns "-" into "" */
+                       positive = FALSE;
+                       count = 1;
+               } else if (strcmp(cp, "--") == 0) {
+                       positive = FALSE;
+                       count = 2;
+               } else if (strcmp(cp, "+") == 0) {
+                       positive = TRUE;
+                       count = 1;
+               } else if (strcmp(cp, "++") == 0) {
+                       positive = TRUE;
+                       count = 2;
+               } else {
+                       error(_("illegal CORRECTION field on Leap line"));
+                       return;
+               }
+               if ((lp = byword(fields[LP_ROLL], leap_types)) == NULL) {
+                       error(_(
+                               "illegal Rolling/Stationary field on Leap line"
+                               ));
+                       return;
+               }
+               leapadd(tadd(t, tod), positive, lp->l_value, count);
+       }
+}
+
+static void
+inlink(fields, nfields)
+register char ** const fields;
+const int              nfields;
+{
+       struct link     l;
+
+       if (nfields != LINK_FIELDS) {
+               error(_("wrong number of fields on Link line"));
+               return;
+       }
+       if (*fields[LF_FROM] == '\0') {
+               error(_("blank FROM field on Link line"));
+               return;
+       }
+       if (*fields[LF_TO] == '\0') {
+               error(_("blank TO field on Link line"));
+               return;
+       }
+       l.l_filename = filename;
+       l.l_linenum = linenum;
+       l.l_from = ecpyalloc(fields[LF_FROM]);
+       l.l_to = ecpyalloc(fields[LF_TO]);
+       links = (struct link *) (void *) erealloc((char *) links,
+               (int) ((nlinks + 1) * sizeof *links));
+       links[nlinks++] = l;
+}
+
+static void
+rulesub(rp, loyearp, hiyearp, typep, monthp, dayp, timep)
+register struct rule * const   rp;
+const char * const             loyearp;
+const char * const             hiyearp;
+const char * const             typep;
+const char * const             monthp;
+const char * const             dayp;
+const char * const             timep;
+{
+       register const struct lookup *  lp;
+       register const char *           cp;
+       register char *                 dp;
+       register char *                 ep;
+
+       if ((lp = byword(monthp, mon_names)) == NULL) {
+               error(_("invalid month name"));
+               return;
+       }
+       rp->r_month = lp->l_value;
+       rp->r_todisstd = FALSE;
+       rp->r_todisgmt = FALSE;
+       dp = ecpyalloc(timep);
+       if (*dp != '\0') {
+               ep = dp + strlen(dp) - 1;
+               switch (lowerit(*ep)) {
+                       case 's':       /* Standard */
+                               rp->r_todisstd = TRUE;
+                               rp->r_todisgmt = FALSE;
+                               *ep = '\0';
+                               break;
+                       case 'w':       /* Wall */
+                               rp->r_todisstd = FALSE;
+                               rp->r_todisgmt = FALSE;
+                               *ep = '\0';
+                               break;
+                       case 'g':       /* Greenwich */
+                       case 'u':       /* Universal */
+                       case 'z':       /* Zulu */
+                               rp->r_todisstd = TRUE;
+                               rp->r_todisgmt = TRUE;
+                               *ep = '\0';
+                               break;
+               }
+       }
+       rp->r_tod = gethms(dp, _("invalid time of day"), FALSE);
+       ifree(dp);
+       /*
+       ** Year work.
+       */
+       cp = loyearp;
+       lp = byword(cp, begin_years);
+       rp->r_lowasnum = lp == NULL;
+       if (!rp->r_lowasnum) switch ((int) lp->l_value) {
+               case YR_MINIMUM:
+                       rp->r_loyear = INT_MIN;
+                       break;
+               case YR_MAXIMUM:
+                       rp->r_loyear = INT_MAX;
+                       break;
+               default:        /* "cannot happen" */
+                       (void) fprintf(stderr,
+                               _("%s: panic: Invalid l_value %d\n"),
+                               progname, lp->l_value);
+                       exit(EXIT_FAILURE);
+       } else if (sscanf(cp, scheck(cp, "%d"), &rp->r_loyear) != 1) {
+               error(_("invalid starting year"));
+               return;
+       }
+       cp = hiyearp;
+       lp = byword(cp, end_years);
+       rp->r_hiwasnum = lp == NULL;
+       if (!rp->r_hiwasnum) switch ((int) lp->l_value) {
+               case YR_MINIMUM:
+                       rp->r_hiyear = INT_MIN;
+                       break;
+               case YR_MAXIMUM:
+                       rp->r_hiyear = INT_MAX;
+                       break;
+               case YR_ONLY:
+                       rp->r_hiyear = rp->r_loyear;
+                       break;
+               default:        /* "cannot happen" */
+                       (void) fprintf(stderr,
+                               _("%s: panic: Invalid l_value %d\n"),
+                               progname, lp->l_value);
+                       exit(EXIT_FAILURE);
+       } else if (sscanf(cp, scheck(cp, "%d"), &rp->r_hiyear) != 1) {
+               error(_("invalid ending year"));
+               return;
+       }
+       if (rp->r_loyear > rp->r_hiyear) {
+               error(_("starting year greater than ending year"));
+               return;
+       }
+       if (*typep == '\0')
+               rp->r_yrtype = NULL;
+       else {
+               if (rp->r_loyear == rp->r_hiyear) {
+                       error(_("typed single year"));
+                       return;
+               }
+               rp->r_yrtype = ecpyalloc(typep);
+       }
+       /*
+       ** Day work.
+       ** Accept things such as:
+       **      1
+       **      last-Sunday
+       **      Sun<=20
+       **      Sun>=7
+       */
+       dp = ecpyalloc(dayp);
+       if ((lp = byword(dp, lasts)) != NULL) {
+               rp->r_dycode = DC_DOWLEQ;
+               rp->r_wday = lp->l_value;
+               rp->r_dayofmonth = len_months[1][rp->r_month];
+       } else {
+               if ((ep = strchr(dp, '<')) != 0)
+                       rp->r_dycode = DC_DOWLEQ;
+               else if ((ep = strchr(dp, '>')) != 0)
+                       rp->r_dycode = DC_DOWGEQ;
+               else {
+                       ep = dp;
+                       rp->r_dycode = DC_DOM;
+               }
+               if (rp->r_dycode != DC_DOM) {
+                       *ep++ = 0;
+                       if (*ep++ != '=') {
+                               error(_("invalid day of month"));
+                               ifree(dp);
+                               return;
+                       }
+                       if ((lp = byword(dp, wday_names)) == NULL) {
+                               error(_("invalid weekday name"));
+                               ifree(dp);
+                               return;
+                       }
+                       rp->r_wday = lp->l_value;
+               }
+               if (sscanf(ep, scheck(ep, "%d"), &rp->r_dayofmonth) != 1 ||
+                       rp->r_dayofmonth <= 0 ||
+                       (rp->r_dayofmonth > len_months[1][rp->r_month])) {
+                               error(_("invalid day of month"));
+                               ifree(dp);
+                               return;
+               }
+       }
+       ifree(dp);
+}
+
+static void
+convert(val, buf)
+const long     val;
+char * const   buf;
+{
+       register int    i;
+       register int    shift;
+
+       for (i = 0, shift = 24; i < 4; ++i, shift -= 8)
+               buf[i] = val >> shift;
+}
+
+static void
+convert64(val, buf)
+const zic_t    val;
+char * const   buf;
+{
+       register int    i;
+       register int    shift;
+
+       for (i = 0, shift = 56; i < 8; ++i, shift -= 8)
+               buf[i] = val >> shift;
+}
+
+static void
+puttzcode(val, fp)
+const long     val;
+FILE * const   fp;
+{
+       char    buf[4];
+
+       convert(val, buf);
+       (void) fwrite((void *) buf, (size_t) sizeof buf, (size_t) 1, fp);
+}
+
+static void
+puttzcode64(val, fp)
+const zic_t    val;
+FILE * const   fp;
+{
+       char    buf[8];
+
+       convert64(val, buf);
+       (void) fwrite((void *) buf, (size_t) sizeof buf, (size_t) 1, fp);
+}
+
+static int
+atcomp(avp, bvp)
+const void *   avp;
+const void *   bvp;
+{
+       const zic_t     a = ((const struct attype *) avp)->at;
+       const zic_t     b = ((const struct attype *) bvp)->at;
+
+       return (a < b) ? -1 : (a > b);
+}
+
+static int
+is32(x)
+const zic_t    x;
+{
+       return INT32_MIN <= x && x <= INT32_MAX;
+}
+
+static void
+writezone(name, string)
+const char * const     name;
+const char * const     string;
+{
+       register FILE *                 fp;
+       register int                    i, j;
+       register int                    leapcnt32, leapi32;
+       register int                    timecnt32, timei32;
+       register int                    pass;
+       static char *                   fullname;
+       static const struct tzhead      tzh0;
+       static struct tzhead            tzh;
+       zic_t                           ats[TZ_MAX_TIMES];
+       unsigned char                   types[TZ_MAX_TIMES];
+
+       /*
+       ** Sort.
+       */
+       if (timecnt > 1)
+               (void) qsort((void *) attypes, (size_t) timecnt,
+                       (size_t) sizeof *attypes, atcomp);
+       /*
+       ** Optimize.
+       */
+       {
+               int     fromi;
+               int     toi;
+
+               toi = 0;
+               fromi = 0;
+               while (fromi < timecnt && attypes[fromi].at < min_time)
+                       ++fromi;
+               if (isdsts[0] == 0)
+                       while (fromi < timecnt && attypes[fromi].type == 0)
+                               ++fromi;        /* handled by default rule */
+               for ( ; fromi < timecnt; ++fromi) {
+                       if (toi != 0 && ((attypes[fromi].at +
+                               gmtoffs[attypes[toi - 1].type]) <=
+                               (attypes[toi - 1].at + gmtoffs[toi == 1 ? 0
+                               : attypes[toi - 2].type]))) {
+                                       attypes[toi - 1].type =
+                                               attypes[fromi].type;
+                                       continue;
+                       }
+                       if (toi == 0 ||
+                               attypes[toi - 1].type != attypes[fromi].type)
+                                       attypes[toi++] = attypes[fromi];
+               }
+               timecnt = toi;
+       }
+       /*
+       ** Transfer.
+       */
+       for (i = 0; i < timecnt; ++i) {
+               ats[i] = attypes[i].at;
+               types[i] = attypes[i].type;
+       }
+       /*
+       ** Correct for leap seconds.
+       */
+       for (i = 0; i < timecnt; ++i) {
+               j = leapcnt;
+               while (--j >= 0)
+                       if (ats[i] > trans[j] - corr[j]) {
+                               ats[i] = tadd(ats[i], corr[j]);
+                               break;
+                       }
+       }
+       /*
+       ** Figure out 32-bit-limited starts and counts.
+       */
+       timecnt32 = timecnt;
+       timei32 = 0;
+       leapcnt32 = leapcnt;
+       leapi32 = 0;
+       while (timecnt32 > 0 && !is32(ats[timecnt32 - 1]))
+               --timecnt32;
+       while (timecnt32 > 0 && !is32(ats[timei32])) {
+               --timecnt32;
+               ++timei32;
+       }
+       while (leapcnt32 > 0 && !is32(trans[leapcnt32 - 1]))
+               --leapcnt32;
+       while (leapcnt32 > 0 && !is32(trans[leapi32])) {
+               --leapcnt32;
+               ++leapi32;
+       }
+       fullname = erealloc(fullname,
+               (int) (strlen(directory) + 1 + strlen(name) + 1));
+       (void) sprintf(fullname, "%s/%s", directory, name);     /* XXX: sprintf is safe */
+       /*
+       ** Remove old file, if any, to snap links.
+       */
+       if (!itsdir(fullname) && remove(fullname) != 0 && errno != ENOENT) {
+               const char *e = strerror(errno);
+
+               (void) fprintf(stderr, _("%s: Can't remove %s: %s\n"),
+                       progname, fullname, e);
+               exit(EXIT_FAILURE);
+       }
+       if ((fp = fopen(fullname, "wb")) == NULL) {
+               if (mkdirs(fullname) != 0)
+                       exit(EXIT_FAILURE);
+               if ((fp = fopen(fullname, "wb")) == NULL) {
+                       const char *e = strerror(errno);
+
+                       (void) fprintf(stderr, _("%s: Can't create %s: %s\n"),
+                               progname, fullname, e);
+                       exit(EXIT_FAILURE);
+               }
+       }
+       for (pass = 1; pass <= 2; ++pass) {
+               register int    thistimei, thistimecnt;
+               register int    thisleapi, thisleapcnt;
+               register int    thistimelim, thisleaplim;
+               int             writetype[TZ_MAX_TIMES];
+               int             typemap[TZ_MAX_TYPES];
+               register int    thistypecnt;
+               char            thischars[TZ_MAX_CHARS];
+               char            thischarcnt;
+               int             indmap[TZ_MAX_CHARS];
+
+               if (pass == 1) {
+                       thistimei = timei32;
+                       thistimecnt = timecnt32;
+                       thisleapi = leapi32;
+                       thisleapcnt = leapcnt32;
+               } else {
+                       thistimei = 0;
+                       thistimecnt = timecnt;
+                       thisleapi = 0;
+                       thisleapcnt = leapcnt;
+               }
+               thistimelim = thistimei + thistimecnt;
+               thisleaplim = thisleapi + thisleapcnt;
+               for (i = 0; i < typecnt; ++i)
+                       writetype[i] = thistimecnt == timecnt;
+               if (thistimecnt == 0) {
+                       /*
+                       ** No transition times fall in the current
+                       ** (32- or 64-bit) window.
+                       */
+                       if (typecnt != 0)
+                               writetype[typecnt - 1] = TRUE;
+               } else {
+                       for (i = thistimei - 1; i < thistimelim; ++i)
+                               if (i >= 0)
+                                       writetype[types[i]] = TRUE;
+                       /*
+                       ** For America/Godthab and Antarctica/Palmer
+                       */
+                       if (thistimei == 0)
+                               writetype[0] = TRUE;
+               }
+               thistypecnt = 0;
+               for (i = 0; i < typecnt; ++i)
+                       typemap[i] = writetype[i] ?  thistypecnt++ : -1;
+               for (i = 0; i < sizeof indmap / sizeof indmap[0]; ++i)
+                       indmap[i] = -1;
+               thischarcnt = 0;
+               for (i = 0; i < typecnt; ++i) {
+                       register char * thisabbr;
+
+                       if (!writetype[i])
+                               continue;
+                       if (indmap[abbrinds[i]] >= 0)
+                               continue;
+                       thisabbr = &chars[abbrinds[i]];
+                       for (j = 0; j < thischarcnt; ++j)
+                               if (strcmp(&thischars[j], thisabbr) == 0)
+                                       break;
+                       if (j == thischarcnt) {
+                               (void) strcpy(&thischars[(int) thischarcnt],
+                                       thisabbr);
+                               thischarcnt += strlen(thisabbr) + 1;
+                       }
+                       indmap[abbrinds[i]] = j;
+               }
+#define DO(field)      (void) fwrite((void *) tzh.field, \
+                               (size_t) sizeof tzh.field, (size_t) 1, fp)
+               tzh = tzh0;
+               (void) strncpy(tzh.tzh_magic, TZ_MAGIC, sizeof tzh.tzh_magic);
+               tzh.tzh_version[0] = ZIC_VERSION;
+               convert(eitol(thistypecnt), tzh.tzh_ttisgmtcnt);
+               convert(eitol(thistypecnt), tzh.tzh_ttisstdcnt);
+               convert(eitol(thisleapcnt), tzh.tzh_leapcnt);
+               convert(eitol(thistimecnt), tzh.tzh_timecnt);
+               convert(eitol(thistypecnt), tzh.tzh_typecnt);
+               convert(eitol(thischarcnt), tzh.tzh_charcnt);
+               DO(tzh_magic);
+               DO(tzh_version);
+               DO(tzh_reserved);
+               DO(tzh_ttisgmtcnt);
+               DO(tzh_ttisstdcnt);
+               DO(tzh_leapcnt);
+               DO(tzh_timecnt);
+               DO(tzh_typecnt);
+               DO(tzh_charcnt);
+#undef DO
+               for (i = thistimei; i < thistimelim; ++i)
+                       if (pass == 1)
+                               puttzcode((long) ats[i], fp);
+                       else    puttzcode64(ats[i], fp);
+               for (i = thistimei; i < thistimelim; ++i) {
+                       unsigned char   uc;
+
+                       uc = typemap[types[i]];
+                       (void) fwrite((void *) &uc,
+                               (size_t) sizeof uc,
+                               (size_t) 1,
+                               fp);
+               }
+               for (i = 0; i < typecnt; ++i)
+                       if (writetype[i]) {
+                               puttzcode(gmtoffs[i], fp);
+                               (void) putc(isdsts[i], fp);
+                               (void) putc((unsigned char) indmap[abbrinds[i]], fp);
+                       }
+               if (thischarcnt != 0)
+                       (void) fwrite((void *) thischars,
+                               (size_t) sizeof thischars[0],
+                               (size_t) thischarcnt, fp);
+               for (i = thisleapi; i < thisleaplim; ++i) {
+                       register zic_t  todo;
+
+                       if (roll[i]) {
+                               if (timecnt == 0 || trans[i] < ats[0]) {
+                                       j = 0;
+                                       while (isdsts[j])
+                                               if (++j >= typecnt) {
+                                                       j = 0;
+                                                       break;
+                                               }
+                               } else {
+                                       j = 1;
+                                       while (j < timecnt &&
+                                               trans[i] >= ats[j])
+                                                       ++j;
+                                       j = types[j - 1];
+                               }
+                               todo = tadd(trans[i], -gmtoffs[j]);
+                       } else  todo = trans[i];
+                       if (pass == 1)
+                               puttzcode((long) todo, fp);
+                       else    puttzcode64(todo, fp);
+                       puttzcode(corr[i], fp);
+               }
+               for (i = 0; i < typecnt; ++i)
+                       if (writetype[i])
+                               (void) putc(ttisstds[i], fp);
+               for (i = 0; i < typecnt; ++i)
+                       if (writetype[i])
+                               (void) putc(ttisgmts[i], fp);
+       }
+       (void) fprintf(fp, "\n%s\n", string);
+       if (ferror(fp) || fclose(fp)) {
+               (void) fprintf(stderr, _("%s: Error writing %s\n"),
+                       progname, fullname);
+               exit(EXIT_FAILURE);
+       }
+}
+
+static void
+doabbr(abbr, abbrlen, format, letters, isdst, doquotes)
+char * const           abbr;
+const int              abbrlen;
+const char * const     format;
+const char * const     letters;
+const int              isdst;
+const int              doquotes;
+{
+       register char * cp;
+       register char * slashp;
+       register int    len;
+
+       slashp = strchr(format, '/');
+       if (slashp == NULL) {
+               if (letters == NULL)
+                       (void) strlcpy(abbr, format, abbrlen);
+               else    (void) snprintf(abbr, abbrlen, format, letters);
+       } else if (isdst) {
+               (void) strlcpy(abbr, slashp + 1, abbrlen);
+       } else {
+               if (slashp > format)
+                       (void) strncpy(abbr, format,
+                               (unsigned) (slashp - format));
+               abbr[slashp - format] = '\0';
+       }
+       if (!doquotes)
+               return;
+       for (cp = abbr; *cp != '\0'; ++cp)
+               if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", *cp) == NULL &&
+                       strchr("abcdefghijklmnopqrstuvwxyz", *cp) == NULL)
+                               break;
+       len = strlen(abbr);
+       if (len > 0 && *cp == '\0')
+               return;
+       abbr[len + 2] = '\0';
+       abbr[len + 1] = '>';
+       for ( ; len > 0; --len)
+               abbr[len] = abbr[len - 1];
+       abbr[0] = '<';
+}
+
+static void
+updateminmax(x)
+const int      x;
+{
+       if (min_year > x)
+               min_year = x;
+       if (max_year < x)
+               max_year = x;
+}
+
+static int
+stringoffset(result, offset)
+char * result;
+long   offset;
+{
+       register int    hours;
+       register int    minutes;
+       register int    seconds;
+
+       result[0] = '\0';
+       if (offset < 0) {
+               (void) strcpy(result, "-");
+               offset = -offset;
+       }
+       seconds = offset % SECSPERMIN;
+       offset /= SECSPERMIN;
+       minutes = offset % MINSPERHOUR;
+       offset /= MINSPERHOUR;
+       hours = offset;
+       if (hours >= HOURSPERDAY) {
+               result[0] = '\0';
+               return -1;
+       }
+       (void) sprintf(end(result), "%d", hours);
+       if (minutes != 0 || seconds != 0) {
+               (void) sprintf(end(result), ":%02d", minutes);
+               if (seconds != 0)
+                       (void) sprintf(end(result), ":%02d", seconds);
+       }
+       return 0;
+}
+
+static int
+stringrule(result, rp, dstoff, gmtoff)
+char *                         result;
+const struct rule * const      rp;
+const long                     dstoff;
+const long                     gmtoff;
+{
+       register long   tod;
+
+       result = end(result);
+       if (rp->r_dycode == DC_DOM) {
+               register int    month, total;
+
+               if (rp->r_dayofmonth == 29 && rp->r_month == TM_FEBRUARY)
+                       return -1;
+               total = 0;
+               for (month = 0; month < rp->r_month; ++month)
+                       total += len_months[0][month];
+               (void) sprintf(result, "J%d", total + rp->r_dayofmonth);
+       } else {
+               register int    week;
+
+               if (rp->r_dycode == DC_DOWGEQ) {
+                       week = 1 + rp->r_dayofmonth / DAYSPERWEEK;
+                       if ((week - 1) * DAYSPERWEEK + 1 != rp->r_dayofmonth)
+                               return -1;
+               } else if (rp->r_dycode == DC_DOWLEQ) {
+                       if (rp->r_dayofmonth == len_months[1][rp->r_month])
+                               week = 5;
+                       else {
+                               week = 1 + rp->r_dayofmonth / DAYSPERWEEK;
+                               if (week * DAYSPERWEEK - 1 != rp->r_dayofmonth)
+                                       return -1;
+                       }
+               } else  return -1;      /* "cannot happen" */
+               (void) sprintf(result, "M%d.%d.%d",
+                       rp->r_month + 1, week, rp->r_wday);
+       }
+       tod = rp->r_tod;
+       if (rp->r_todisgmt)
+               tod += gmtoff;
+       if (rp->r_todisstd && rp->r_stdoff == 0)
+               tod += dstoff;
+       if (tod < 0) {
+               result[0] = '\0';
+               return -1;
+       }
+       if (tod != 2 * SECSPERMIN * MINSPERHOUR) {
+               (void) strcat(result, "/");
+               if (stringoffset(end(result), tod) != 0)
+                       return -1;
+       }
+       return 0;
+}
+
+static void
+stringzone(result, resultlen, zpfirst, zonecount)
+char *                         result;
+const int                      resultlen;
+const struct zone * const      zpfirst;
+const int                      zonecount;
+{
+       register const struct zone *    zp;
+       register struct rule *          rp;
+       register struct rule *          stdrp;
+       register struct rule *          dstrp;
+       register int                    i;
+       register const char *           abbrvar;
+
+       result[0] = '\0';
+       zp = zpfirst + zonecount - 1;
+       stdrp = dstrp = NULL;
+       for (i = 0; i < zp->z_nrules; ++i) {
+               rp = &zp->z_rules[i];
+               if (rp->r_hiwasnum || rp->r_hiyear != INT_MAX)
+                       continue;
+               if (rp->r_yrtype != NULL)
+                       continue;
+               if (rp->r_stdoff == 0) {
+                       if (stdrp == NULL)
+                               stdrp = rp;
+                       else    return;
+               } else {
+                       if (dstrp == NULL)
+                               dstrp = rp;
+                       else    return;
+               }
+       }
+       if (stdrp == NULL && dstrp == NULL) {
+               /*
+               ** There are no rules running through "max".
+               ** Let's find the latest rule.
+               */
+               for (i = 0; i < zp->z_nrules; ++i) {
+                       rp = &zp->z_rules[i];
+                       if (stdrp == NULL || rp->r_hiyear > stdrp->r_hiyear ||
+                               (rp->r_hiyear == stdrp->r_hiyear &&
+                               rp->r_month > stdrp->r_month))
+                                       stdrp = rp;
+               }
+               if (stdrp != NULL && stdrp->r_stdoff != 0)
+                       return; /* We end up in DST (a POSIX no-no). */
+               /*
+               ** Horrid special case: if year is 2037,
+               ** presume this is a zone handled on a year-by-year basis;
+               ** do not try to apply a rule to the zone.
+               */
+               if (stdrp != NULL && stdrp->r_hiyear == 2037)
+                       return;
+       }
+       if (stdrp == NULL && (zp->z_nrules != 0 || zp->z_stdoff != 0))
+               return;
+       abbrvar = (stdrp == NULL) ? "" : stdrp->r_abbrvar;
+       doabbr(result, resultlen, zp->z_format, abbrvar, FALSE, TRUE);
+       if (stringoffset(end(result), -zp->z_gmtoff) != 0) {
+               result[0] = '\0';
+               return;
+       }
+       if (dstrp == NULL)
+               return;
+       doabbr(end(result), resultlen - strlen(result),
+               zp->z_format, dstrp->r_abbrvar, TRUE, TRUE);
+       if (dstrp->r_stdoff != SECSPERMIN * MINSPERHOUR)
+               if (stringoffset(end(result),
+                       -(zp->z_gmtoff + dstrp->r_stdoff)) != 0) {
+                               result[0] = '\0';
+                               return;
+               }
+       (void) strcat(result, ",");
+       if (stringrule(result, dstrp, dstrp->r_stdoff, zp->z_gmtoff) != 0) {
+               result[0] = '\0';
+               return;
+       }
+       (void) strcat(result, ",");
+       if (stringrule(result, stdrp, dstrp->r_stdoff, zp->z_gmtoff) != 0) {
+               result[0] = '\0';
+               return;
+       }
+}
+
+static void
+outzone(zpfirst, zonecount)
+const struct zone * const      zpfirst;
+const int                      zonecount;
+{
+       register const struct zone *    zp;
+       register struct rule *          rp;
+       register int                    i, j;
+       register int                    usestart, useuntil;
+       register zic_t                  starttime, untiltime;
+       register long                   gmtoff;
+       register long                   stdoff;
+       register int                    year;
+       register long                   startoff;
+       register int                    startttisstd;
+       register int                    startttisgmt;
+       register int                    type;
+       register char *                 startbuf;
+       register char *                 ab;
+       register char *                 envvar;
+       register int                    max_abbr_len;
+       register int                    max_envvar_len;
+
+       max_abbr_len = 2 + max_format_len + max_abbrvar_len;
+       max_envvar_len = 2 * max_abbr_len + 5 * 9;
+       startbuf = emalloc(max_abbr_len + 1);
+       ab = emalloc(max_abbr_len + 1);
+       envvar = emalloc(max_envvar_len + 1);
+       INITIALIZE(untiltime);
+       INITIALIZE(starttime);
+       /*
+       ** Now. . .finally. . .generate some useful data!
+       */
+       timecnt = 0;
+       typecnt = 0;
+       charcnt = 0;
+       /*
+       ** Thanks to Earl Chew
+       ** for noting the need to unconditionally initialize startttisstd.
+       */
+       startttisstd = FALSE;
+       startttisgmt = FALSE;
+       min_year = max_year = EPOCH_YEAR;
+       if (leapseen) {
+               updateminmax(leapminyear);
+               updateminmax(leapmaxyear + (leapmaxyear < INT_MAX));
+       }
+       for (i = 0; i < zonecount; ++i) {
+               zp = &zpfirst[i];
+               if (i < zonecount - 1)
+                       updateminmax(zp->z_untilrule.r_loyear);
+               for (j = 0; j < zp->z_nrules; ++j) {
+                       rp = &zp->z_rules[j];
+                       if (rp->r_lowasnum)
+                               updateminmax(rp->r_loyear);
+                       if (rp->r_hiwasnum)
+                               updateminmax(rp->r_hiyear);
+               }
+       }
+       /*
+       ** Generate lots of data if a rule can't cover all future times.
+       */
+       stringzone(envvar, max_envvar_len+1, zpfirst, zonecount);
+       if (noise && envvar[0] == '\0') {
+               register char * wp;
+
+wp = ecpyalloc(_("no POSIX environment variable for zone"));
+               wp = ecatalloc(wp, " ");
+               wp = ecatalloc(wp, zpfirst->z_name);
+               warning(wp);
+               ifree(wp);
+       }
+       if (envvar[0] == '\0') {
+               if (min_year >= INT_MIN + YEARSPERREPEAT)
+                       min_year -= YEARSPERREPEAT;
+               else    min_year = INT_MIN;
+               if (max_year <= INT_MAX - YEARSPERREPEAT)
+                       max_year += YEARSPERREPEAT;
+               else    max_year = INT_MAX;
+       }
+       /*
+       ** For the benefit of older systems,
+       ** generate data from 1900 through 2037.
+       */
+       if (min_year > 1900)
+               min_year = 1900;
+       if (max_year < 2037)
+               max_year = 2037;
+       for (i = 0; i < zonecount; ++i) {
+               /*
+               ** A guess that may well be corrected later.
+               */
+               stdoff = 0;
+               zp = &zpfirst[i];
+               usestart = i > 0 && (zp - 1)->z_untiltime > min_time;
+               useuntil = i < (zonecount - 1);
+               if (useuntil && zp->z_untiltime <= min_time)
+                       continue;
+               gmtoff = zp->z_gmtoff;
+               eat(zp->z_filename, zp->z_linenum);
+               *startbuf = '\0';
+               startoff = zp->z_gmtoff;
+               if (zp->z_nrules == 0) {
+                       stdoff = zp->z_stdoff;
+                       doabbr(startbuf, max_abbr_len + 1, zp->z_format,
+                               (char *) NULL, stdoff != 0, FALSE);
+                       type = addtype(oadd(zp->z_gmtoff, stdoff),
+                               startbuf, stdoff != 0, startttisstd,
+                               startttisgmt);
+                       if (usestart) {
+                               addtt(starttime, type);
+                               usestart = FALSE;
+                       } else if (stdoff != 0)
+                               addtt(min_time, type);
+               } else for (year = min_year; year <= max_year; ++year) {
+                       if (useuntil && year > zp->z_untilrule.r_hiyear)
+                               break;
+                       /*
+                       ** Mark which rules to do in the current year.
+                       ** For those to do, calculate rpytime(rp, year);
+                       */
+                       for (j = 0; j < zp->z_nrules; ++j) {
+                               rp = &zp->z_rules[j];
+                               eats(zp->z_filename, zp->z_linenum,
+                                       rp->r_filename, rp->r_linenum);
+                               rp->r_todo = year >= rp->r_loyear &&
+                                               year <= rp->r_hiyear &&
+                                               yearistype(year, rp->r_yrtype);
+                               if (rp->r_todo)
+                                       rp->r_temp = rpytime(rp, year);
+                       }
+                       for ( ; ; ) {
+                               register int    k;
+                               register zic_t  jtime, ktime;
+                               register long   offset;
+
+                               INITIALIZE(ktime);
+                               if (useuntil) {
+                                       /*
+                                       ** Turn untiltime into UTC
+                                       ** assuming the current gmtoff and
+                                       ** stdoff values.
+                                       */
+                                       untiltime = zp->z_untiltime;
+                                       if (!zp->z_untilrule.r_todisgmt)
+                                               untiltime = tadd(untiltime,
+                                                       -gmtoff);
+                                       if (!zp->z_untilrule.r_todisstd)
+                                               untiltime = tadd(untiltime,
+                                                       -stdoff);
+                               }
+                               /*
+                               ** Find the rule (of those to do, if any)
+                               ** that takes effect earliest in the year.
+                               */
+                               k = -1;
+                               for (j = 0; j < zp->z_nrules; ++j) {
+                                       rp = &zp->z_rules[j];
+                                       if (!rp->r_todo)
+                                               continue;
+                                       eats(zp->z_filename, zp->z_linenum,
+                                               rp->r_filename, rp->r_linenum);
+                                       offset = rp->r_todisgmt ? 0 : gmtoff;
+                                       if (!rp->r_todisstd)
+                                               offset = oadd(offset, stdoff);
+                                       jtime = rp->r_temp;
+                                       if (jtime == min_time ||
+                                               jtime == max_time)
+                                                       continue;
+                                       jtime = tadd(jtime, -offset);
+                                       if (k < 0 || jtime < ktime) {
+                                               k = j;
+                                               ktime = jtime;
+                                       }
+                               }
+                               if (k < 0)
+                                       break;  /* go on to next year */
+                               rp = &zp->z_rules[k];
+                               rp->r_todo = FALSE;
+                               if (useuntil && ktime >= untiltime)
+                                       break;
+                               stdoff = rp->r_stdoff;
+                               if (usestart && ktime == starttime)
+                                       usestart = FALSE;
+                               if (usestart) {
+                                       if (ktime < starttime) {
+                                               startoff = oadd(zp->z_gmtoff,
+                                                       stdoff);
+                                               doabbr(startbuf,
+                                                       max_abbr_len + 1,
+                                                       zp->z_format,
+                                                       rp->r_abbrvar,
+                                                       rp->r_stdoff != 0,
+                                                       FALSE);
+                                               continue;
+                                       }
+                                       if (*startbuf == '\0' &&
+                                               startoff == oadd(zp->z_gmtoff,
+                                               stdoff)) {
+                                                       doabbr(startbuf,
+                                                               max_abbr_len + 1,
+                                                               zp->z_format,
+                                                               rp->r_abbrvar,
+                                                               rp->r_stdoff !=
+                                                               0,
+                                                               FALSE);
+                                       }
+                               }
+                               eats(zp->z_filename, zp->z_linenum,
+                                       rp->r_filename, rp->r_linenum);
+                               doabbr(ab, max_abbr_len+1, zp->z_format, rp->r_abbrvar,
+                                       rp->r_stdoff != 0, FALSE);
+                               offset = oadd(zp->z_gmtoff, rp->r_stdoff);
+                               type = addtype(offset, ab, rp->r_stdoff != 0,
+                                       rp->r_todisstd, rp->r_todisgmt);
+                               addtt(ktime, type);
+                       }
+               }
+               if (usestart) {
+                       if (*startbuf == '\0' &&
+                               zp->z_format != NULL &&
+                               strchr(zp->z_format, '%') == NULL &&
+                               strchr(zp->z_format, '/') == NULL)
+                                       (void)strncpy(startbuf, zp->z_format,
+                                           max_abbr_len + 1 - 1);
+                       eat(zp->z_filename, zp->z_linenum);
+                       if (*startbuf == '\0')
+error(_("can't determine time zone abbreviation to use just after until time"));
+                       else    addtt(starttime,
+                                       addtype(startoff, startbuf,
+                                               startoff != zp->z_gmtoff,
+                                               startttisstd,
+                                               startttisgmt));
+               }
+               /*
+               ** Now we may get to set starttime for the next zone line.
+               */
+               if (useuntil) {
+                       startttisstd = zp->z_untilrule.r_todisstd;
+                       startttisgmt = zp->z_untilrule.r_todisgmt;
+                       starttime = zp->z_untiltime;
+                       if (!startttisstd)
+                               starttime = tadd(starttime, -stdoff);
+                       if (!startttisgmt)
+                               starttime = tadd(starttime, -gmtoff);
+               }
+       }
+       writezone(zpfirst->z_name, envvar);
+       ifree(startbuf);
+       ifree(ab);
+       ifree(envvar);
+}
+
+static void
+addtt(starttime, type)
+const zic_t    starttime;
+int            type;
+{
+       if (starttime <= min_time ||
+               (timecnt == 1 && attypes[0].at < min_time)) {
+               gmtoffs[0] = gmtoffs[type];
+               isdsts[0] = isdsts[type];
+               ttisstds[0] = ttisstds[type];
+               ttisgmts[0] = ttisgmts[type];
+               if (abbrinds[type] != 0)
+                       (void) strcpy(chars, &chars[abbrinds[type]]);
+               abbrinds[0] = 0;
+               charcnt = strlen(chars) + 1;
+               typecnt = 1;
+               timecnt = 0;
+               type = 0;
+       }
+       if (timecnt >= TZ_MAX_TIMES) {
+               error(_("too many transitions?!"));
+               exit(EXIT_FAILURE);
+       }
+       attypes[timecnt].at = starttime;
+       attypes[timecnt].type = type;
+       ++timecnt;
+}
+
+static int
+addtype(gmtoff, abbr, isdst, ttisstd, ttisgmt)
+const long             gmtoff;
+const char * const     abbr;
+const int              isdst;
+const int              ttisstd;
+const int              ttisgmt;
+{
+       register int    i, j;
+
+       if (isdst != TRUE && isdst != FALSE) {
+               error(_("internal error - addtype called with bad isdst"));
+               exit(EXIT_FAILURE);
+       }
+       if (ttisstd != TRUE && ttisstd != FALSE) {
+               error(_("internal error - addtype called with bad ttisstd"));
+               exit(EXIT_FAILURE);
+       }
+       if (ttisgmt != TRUE && ttisgmt != FALSE) {
+               error(_("internal error - addtype called with bad ttisgmt"));
+               exit(EXIT_FAILURE);
+       }
+       /*
+       ** See if there's already an entry for this zone type.
+       ** If so, just return its index.
+       */
+       for (i = 0; i < typecnt; ++i) {
+               if (gmtoff == gmtoffs[i] && isdst == isdsts[i] &&
+                       strcmp(abbr, &chars[abbrinds[i]]) == 0 &&
+                       ttisstd == ttisstds[i] &&
+                       ttisgmt == ttisgmts[i])
+                               return i;
+       }
+       /*
+       ** There isn't one; add a new one, unless there are already too
+       ** many.
+       */
+       if (typecnt >= TZ_MAX_TYPES) {
+               error(_("too many local time types"));
+               exit(EXIT_FAILURE);
+       }
+       if (! (-1L - 2147483647L <= gmtoff && gmtoff <= 2147483647L)) {
+               error(_("UTC offset out of range"));
+               exit(EXIT_FAILURE);
+       }
+       gmtoffs[i] = gmtoff;
+       isdsts[i] = isdst;
+       ttisstds[i] = ttisstd;
+       ttisgmts[i] = ttisgmt;
+
+       for (j = 0; j < charcnt; ++j)
+               if (strcmp(&chars[j], abbr) == 0)
+                       break;
+       if (j == charcnt)
+               newabbr(abbr);
+       abbrinds[i] = j;
+       ++typecnt;
+       return i;
+}
+
+static void
+leapadd(t, positive, rolling, count)
+const zic_t    t;
+const int      positive;
+const int      rolling;
+int            count;
+{
+       register int    i, j;
+
+       if (leapcnt + (positive ? count : 1) > TZ_MAX_LEAPS) {
+               error(_("too many leap seconds"));
+               exit(EXIT_FAILURE);
+       }
+       for (i = 0; i < leapcnt; ++i)
+               if (t <= trans[i]) {
+                       if (t == trans[i]) {
+                               error(_("repeated leap second moment"));
+                               exit(EXIT_FAILURE);
+                       }
+                       break;
+               }
+       do {
+               for (j = leapcnt; j > i; --j) {
+                       trans[j] = trans[j - 1];
+                       corr[j] = corr[j - 1];
+                       roll[j] = roll[j - 1];
+               }
+               trans[i] = t;
+               corr[i] = positive ? 1L : eitol(-count);
+               roll[i] = rolling;
+               ++leapcnt;
+       } while (positive && --count != 0);
+}
+
+static void
+adjleap(void)
+{
+       register int    i;
+       register long   last = 0;
+
+       /*
+       ** propagate leap seconds forward
+       */
+       for (i = 0; i < leapcnt; ++i) {
+               trans[i] = tadd(trans[i], last);
+               last = corr[i] += last;
+       }
+}
+
+static int
+yearistype(year, type)
+const int              year;
+const char * const     type;
+{
+       static char *   buf;
+       int             result;
+
+       if (type == NULL || *type == '\0')
+               return TRUE;
+       buf = erealloc(buf, (int) (132 + strlen(yitcommand) + strlen(type)));
+       (void)sprintf(buf, "%s %d %s", yitcommand, year, type); /* XXX: sprintf is safe */
+       result = system(buf);
+       if (WIFEXITED(result)) switch (WEXITSTATUS(result)) {
+               case 0:
+                       return TRUE;
+               case 1:
+                       return FALSE;
+       }
+       error(_("Wild result from command execution"));
+       (void) fprintf(stderr, _("%s: command was '%s', result was %d\n"),
+               progname, buf, result);
+       for ( ; ; )
+               exit(EXIT_FAILURE);
+}
+
+static int
+lowerit(a)
+int    a;
+{
+       a = (unsigned char) a;
+       return (isascii(a) && isupper(a)) ? tolower(a) : a;
+}
+
+static int
+ciequal(ap, bp)                /* case-insensitive equality */
+register const char *  ap;
+register const char *  bp;
+{
+       while (lowerit(*ap) == lowerit(*bp++))
+               if (*ap++ == '\0')
+                       return TRUE;
+       return FALSE;
+}
+
+static int
+itsabbr(abbr, word)
+register const char *  abbr;
+register const char *  word;
+{
+       if (lowerit(*abbr) != lowerit(*word))
+               return FALSE;
+       ++word;
+       while (*++abbr != '\0')
+               do {
+                       if (*word == '\0')
+                               return FALSE;
+               } while (lowerit(*word++) != lowerit(*abbr));
+       return TRUE;
+}
+
+static const struct lookup *
+byword(word, table)
+register const char * const            word;
+register const struct lookup * const   table;
+{
+       register const struct lookup *  foundlp;
+       register const struct lookup *  lp;
+
+       if (word == NULL || table == NULL)
+               return NULL;
+       /*
+       ** Look for exact match.
+       */
+       for (lp = table; lp->l_word != NULL; ++lp)
+               if (ciequal(word, lp->l_word))
+                       return lp;
+       /*
+       ** Look for inexact match.
+       */
+       foundlp = NULL;
+       for (lp = table; lp->l_word != NULL; ++lp)
+               if (itsabbr(word, lp->l_word)) {
+                       if (foundlp == NULL)
+                               foundlp = lp;
+                       else    return NULL;    /* multiple inexact matches */
+               }
+       return foundlp;
+}
+
+static char **
+getfields(cp)
+register char *        cp;
+{
+       register char *         dp;
+       register char **        array;
+       register int            nsubs;
+
+       if (cp == NULL)
+               return NULL;
+       array = (char **) (void *)
+               emalloc((int) ((strlen(cp) + 1) * sizeof *array));
+       nsubs = 0;
+       for ( ; ; ) {
+               while (isascii((unsigned char) *cp) &&
+                       isspace((unsigned char) *cp))
+                               ++cp;
+               if (*cp == '\0' || *cp == '#')
+                       break;
+               array[nsubs++] = dp = cp;
+               do {
+                       if ((*dp = *cp++) != '"')
+                               ++dp;
+                       else while ((*dp = *cp++) != '"')
+                               if (*dp != '\0')
+                                       ++dp;
+                               else {
+                                       error(_(
+                                               "Odd number of quotation marks"
+                                               ));
+                                       exit(1);
+                               }
+               } while (*cp != '\0' && *cp != '#' &&
+                       (!isascii(*cp) || !isspace((unsigned char) *cp)));
+               if (isascii(*cp) && isspace((unsigned char) *cp))
+                       ++cp;
+               *dp = '\0';
+       }
+       array[nsubs] = NULL;
+       return array;
+}
+
+static long
+oadd(t1, t2)
+const long     t1;
+const long     t2;
+{
+       register long   t;
+
+       t = t1 + t2;
+       if ((t2 > 0 && t <= t1) || (t2 < 0 && t >= t1)) {
+               error(_("time overflow"));
+               exit(EXIT_FAILURE);
+       }
+       return t;
+}
+
+static zic_t
+tadd(t1, t2)
+const zic_t    t1;
+const long     t2;
+{
+       register zic_t  t;
+
+       if (t1 == max_time && t2 > 0)
+               return max_time;
+       if (t1 == min_time && t2 < 0)
+               return min_time;
+       t = t1 + t2;
+       if ((t2 > 0 && t <= t1) || (t2 < 0 && t >= t1)) {
+               error(_("time overflow"));
+               exit(EXIT_FAILURE);
+       }
+       return t;
+}
+
+/*
+** Given a rule, and a year, compute the date - in seconds since January 1,
+** 1970, 00:00 LOCAL time - in that year that the rule refers to.
+*/
+
+static zic_t
+rpytime(rp, wantedy)
+register const struct rule * const     rp;
+register const int                     wantedy;
+{
+       register int    y, m, i;
+       register long   dayoff;                 /* with a nod to Margaret O. */
+       register zic_t  t;
+
+       if (wantedy == INT_MIN)
+               return min_time;
+       if (wantedy == INT_MAX)
+               return max_time;
+       dayoff = 0;
+       m = TM_JANUARY;
+       y = EPOCH_YEAR;
+       while (wantedy != y) {
+               if (wantedy > y) {
+                       i = len_years[isleap(y)];
+                       ++y;
+               } else {
+                       --y;
+                       i = -len_years[isleap(y)];
+               }
+               dayoff = oadd(dayoff, eitol(i));
+       }
+       while (m != rp->r_month) {
+               i = len_months[isleap(y)][m];
+               dayoff = oadd(dayoff, eitol(i));
+               ++m;
+       }
+       i = rp->r_dayofmonth;
+       if (m == TM_FEBRUARY && i == 29 && !isleap(y)) {
+               if (rp->r_dycode == DC_DOWLEQ)
+                       --i;
+               else {
+                       error(_("use of 2/29 in non leap-year"));
+                       exit(EXIT_FAILURE);
+               }
+       }
+       --i;
+       dayoff = oadd(dayoff, eitol(i));
+       if (rp->r_dycode == DC_DOWGEQ || rp->r_dycode == DC_DOWLEQ) {
+               register long   wday;
+
+#define LDAYSPERWEEK   ((long) DAYSPERWEEK)
+               wday = eitol(EPOCH_WDAY);
+               /*
+               ** Don't trust mod of negative numbers.
+               */
+               if (dayoff >= 0)
+                       wday = (wday + dayoff) % LDAYSPERWEEK;
+               else {
+                       wday -= ((-dayoff) % LDAYSPERWEEK);
+                       if (wday < 0)
+                               wday += LDAYSPERWEEK;
+               }
+               while (wday != eitol(rp->r_wday))
+                       if (rp->r_dycode == DC_DOWGEQ) {
+                               dayoff = oadd(dayoff, (long) 1);
+                               if (++wday >= LDAYSPERWEEK)
+                                       wday = 0;
+                               ++i;
+                       } else {
+                               dayoff = oadd(dayoff, (long) -1);
+                               if (--wday < 0)
+                                       wday = LDAYSPERWEEK - 1;
+                               --i;
+                       }
+               if (i < 0 || i >= len_months[isleap(y)][m]) {
+                       if (noise)
+                               warning(_("rule goes past start/end of month--\
+will not work with pre-2004 versions of zic"));
+               }
+       }
+       if (dayoff < min_time / SECSPERDAY)
+               return min_time;
+       if (dayoff > max_time / SECSPERDAY)
+               return max_time;
+       t = (zic_t) dayoff * SECSPERDAY;
+       return tadd(t, rp->r_tod);
+}
+
+static void
+newabbr(string)
+const char * const     string;
+{
+       register int    i;
+
+       if (strcmp(string, GRANDPARENTED) != 0) {
+               register const char *   cp;
+               register char *         wp;
+
+               /*
+               ** Want one to ZIC_MAX_ABBR_LEN_WO_WARN alphabetics
+               ** optionally followed by a + or - and a number from 1 to 14.
+               */
+               cp = string;
+               wp = NULL;
+               while (isascii((unsigned char) *cp) &&
+                       isalpha((unsigned char) *cp))
+                               ++cp;
+               if (cp - string == 0)
+wp = _("time zone abbreviation lacks alphabetic at start");
+               if (noise && cp - string > 3)
+wp = _("time zone abbreviation has more than 3 alphabetics");
+               if (cp - string > ZIC_MAX_ABBR_LEN_WO_WARN)
+wp = _("time zone abbreviation has too many alphabetics");
+               if (wp == NULL && (*cp == '+' || *cp == '-')) {
+                       ++cp;
+                       if (isascii((unsigned char) *cp) &&
+                               isdigit((unsigned char) *cp))
+                                       if (*cp++ == '1' &&
+                                               *cp >= '0' && *cp <= '4')
+                                                       ++cp;
+               }
+               if (*cp != '\0')
+wp = _("time zone abbreviation differs from POSIX standard");
+               if (wp != NULL) {
+                       wp = ecpyalloc(wp);
+                       wp = ecatalloc(wp, " (");
+                       wp = ecatalloc(wp, string);
+                       wp = ecatalloc(wp, ")");
+                       warning(wp);
+                       ifree(wp);
+               }
+       }
+       i = strlen(string) + 1;
+       if (charcnt + i > TZ_MAX_CHARS) {
+               error(_("too many, or too long, time zone abbreviations"));
+               exit(EXIT_FAILURE);
+       }
+       (void)strncpy(&chars[charcnt], string, sizeof(chars) - charcnt - 1);
+       charcnt += eitol(i);
+}
+
+static int
+mkdirs(argname)
+char *         argname;
+{
+       register char * name;
+       register char * cp;
+
+       if (argname == NULL || *argname == '\0')
+               return 0;
+       cp = name = ecpyalloc(argname);
+       while ((cp = strchr(cp + 1, '/')) != 0) {
+               *cp = '\0';
+#ifndef __NetBSD__
+               /*
+               ** DOS drive specifier?
+               */
+               if (isalpha((unsigned char) name[0]) &&
+                       name[1] == ':' && name[2] == '\0') {
+                               *cp = '/';
+                               continue;
+               }
+#endif /* !defined __NetBSD__ */
+               if (!itsdir(name)) {
+                       /*
+                       ** It doesn't seem to exist, so we try to create it.
+                       ** Creation may fail because of the directory being
+                       ** created by some other multiprocessor, so we get
+                       ** to do extra checking.
+                       */
+                       if (mkdir(name, MKDIR_UMASK) != 0) {
+                               const char *e = strerror(errno);
+
+                               if (errno != EEXIST || !itsdir(name)) {
+                                       (void) fprintf(stderr,
+_("%s: Can't create directory %s: %s\n"),
+                                               progname, name, e);
+                                       ifree(name);
+                                       return -1;
+                               }
+                       }
+               }
+               *cp = '/';
+       }
+       ifree(name);
+       return 0;
+}
+
+static long
+eitol(i)
+const int      i;
+{
+       long    l;
+
+       l = i;
+       if ((i < 0 && l >= 0) || (i == 0 && l != 0) || (i > 0 && l <= 0)) {
+               (void) fprintf(stderr,
+                       _("%s: %d did not sign extend correctly\n"),
+                       progname, i);
+               exit(EXIT_FAILURE);
+       }
+       return l;
+}
+
+/*
+** UNIX was a registered trademark of The Open Group in 2003.
+*/
diff --git a/lib/nbsd_libc/uuid/Makefile.inc b/lib/nbsd_libc/uuid/Makefile.inc
new file mode 100644 (file)
index 0000000..45ca2ce
--- /dev/null
@@ -0,0 +1,25 @@
+#      $NetBSD: Makefile.inc,v 1.1 2004/09/13 21:44:54 thorpej Exp $
+
+# DCE 1.1 compatible UUID implementation sources
+
+.PATH: ${.CURDIR}/uuid
+
+SRCS+= uuid_compare.c uuid_create.c uuid_create_nil.c uuid_equal.c \
+       uuid_from_string.c uuid_hash.c uuid_is_nil.c uuid_stream.c \
+       uuid_to_string.c
+
+MAN+=  uuid.3
+
+MLINKS+=uuid.3 uuid_compare.3
+MLINKS+=uuid.3 uuid_create.3
+MLINKS+=uuid.3 uuid_create_nil.3
+MLINKS+=uuid.3 uuid_equal.3
+MLINKS+=uuid.3 uuid_from_string.3
+MLINKS+=uuid.3 uuid_hash.3
+MLINKS+=uuid.3 uuid_is_nil.3
+MLINKS+=uuid.3 uuid_to_string.3
+
+MLINKS+=uuid.3 uuid_enc_le.3
+MLINKS+=uuid.3 uuid_dec_le.3
+MLINKS+=uuid.3 uuid_enc_be.3
+MLINKS+=uuid.3 uuid_dec_be.3
diff --git a/lib/nbsd_libc/uuid/uuid.3 b/lib/nbsd_libc/uuid/uuid.3
new file mode 100644 (file)
index 0000000..1720268
--- /dev/null
@@ -0,0 +1,211 @@
+.\"    $NetBSD: uuid.3,v 1.7 2008/05/02 18:11:05 martin Exp $
+.\"
+.\" Copyright (c) 2004 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.\" Copyright (c) 2002 Marcel Moolenaar
+.\" Copyright (c) 2002 Hiten Mahesh Pandya
+.\" 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 ``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 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.
+.\"
+.\" $FreeBSD: src/lib/libc/uuid/uuid.3,v 1.4 2003/08/08 19:12:28 marcel Exp $
+.\"
+.Dd April 22, 2008
+.Dt UUID 3
+.Os
+.Sh NAME
+.Nm uuid_compare , uuid_create , uuid_create_nil , uuid_equal ,
+.Nm uuid_from_string , uuid_hash , uuid_is_nil , uuid_to_string ,
+.Nm uuid_enc_le , uuid_dec_le , uuid_enc_be , uuid_dec_be
+.Nd Universally Unique Identifier routines
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In uuid.h
+.Ft int32_t
+.Fn uuid_compare "const uuid_t *uuid1" "const uuid_t *uuid2" "uint32_t *status"
+.Ft void
+.Fn uuid_create "uuid_t *uuid" "uint32_t *status"
+.Ft void
+.Fn uuid_create_nil "uuid_t *uuid" "uint32_t *status"
+.Ft int32_t
+.Fn uuid_equal "const uuid_t *uuid1" "const uuid_t *uuid2" "uint32_t *status"
+.Ft void
+.Fn uuid_from_string "const char *str" "uuid_t *uuid" "uint32_t *status"
+.Ft uint16_t
+.Fn uuid_hash "const uuid_t *uuid" "uint32_t *status"
+.Ft int32_t
+.Fn uuid_is_nil "const uuid_t *uuid" "uint32_t *status"
+.Ft void
+.Fn uuid_to_string "const uuid_t *uuid" "char **str" "uint32_t *status"
+.Ft void
+.Fn uuid_enc_le "void *buf" "const uuid_t *uuid"
+.Ft void
+.Fn uuid_dec_le "const void *buf" "uuid_t *"
+.Ft void
+.Fn uuid_enc_be "void *buf" "const uuid_t *uuid"
+.Ft void
+.Fn uuid_dec_be "const void *buf" "uuid_t *"
+.Sh DESCRIPTION
+These routines provide for the creation and manipulation of Universally
+Unique Identifiers
+.Pq UUIDs ,
+also referred to as Globally Unique Identifiers
+.Pq GUIDs .
+.Pp
+The
+.Fn uuid_compare
+function compares two UUIDs.
+It returns \-1 if
+.Fa uuid1
+precedes
+.Fa uuid2 ,
+0 if they are equal, or 1 if
+.Fa uuid1
+follows
+.Fa uuid2 .
+.Pp
+The
+.Fn uuid_create
+function creates a new UUID.
+Storage for the new UUID must be pre-allocated by the caller.
+.Pp
+The
+.Fn uuid_create_nil
+function creates a nil-valued UUID.
+Storage for the new UUID must be pre-allocated by the caller.
+.Pp
+The
+.Fn uuid_equal
+function compares two UUIDs to determine if they are equal.
+It returns 1 if they are equal, and 0 if they are not equal.
+.Pp
+The
+.Fn uuid_from_string
+function parses a 36-character string representation of a UUID and
+converts it to binary representation.
+Storage for the UUID must be pre-allocated by the caller.
+.Pp
+The
+.Fn uuid_hash
+function generates a hash value for the specified UUID.
+Note that the hash value is not a cryptographic hash, and should not be
+assumed to be unique given two different UUIDs.
+.Pp
+The
+.Fn uuid_is_nil
+function returns 1 if the UUID is nil-valued and 0 if it is not.
+.Pp
+The
+.Fn uuid_to_string
+function converts a UUID from binary representation to string representation.
+Storage for the string is dynamically allocated and returned via the
+.Fa str
+argument.
+This pointer should be passed to
+.Xr free 3
+to release the allocated storage when it is no longer needed.
+.Pp
+The
+.Fn uuid_enc_le
+and
+.Fn uuid_enc_be
+functions encode a binary representation of a UUID into an octet stream
+in little-endian and big-endian byte-order, respectively.
+The destination buffer must be pre-allocated by the caller, and must be
+large enough to hold the 16-octet binary UUID.
+.Pp
+The
+.Fn uuid_dec_le
+and
+.Fn uuid_dec_be
+functions decode a UUID from an octet stream in little-endian and
+big-endian byte-order, respectively.
+.Sh RETURN VALUES
+The
+.Fn uuid_compare ,
+.Fn uuid_create ,
+.Fn uuid_create_nil ,
+.Fn uuid_equal ,
+.Fn uuid_from_string ,
+.Fn uuid_hash ,
+.Fn uuid_is_nil ,
+and
+.Fn uuid_to_string
+functions return successful or unsuccessful completion status in the
+.Fa status
+argument.
+Possible values are:
+.Pp
+.Bl -tag -width ".Dv uuid_s_invalid_string_uuid"
+.It Dv uuid_s_ok
+The function completed successfully.
+.It Dv uuid_s_bad_version
+The UUID does not have a known version.
+.It Dv uuid_s_invalid_string_uuid
+The string representation of a UUID is not valid.
+.It Dv uuid_s_no_memory
+Memory could not be allocated for the operation.
+.El
+.Sh SEE ALSO
+.Xr uuidgen 1 ,
+.Xr uuidgen 2
+.Sh STANDARDS
+The
+.Fn uuid_compare ,
+.Fn uuid_create ,
+.Fn uuid_create_nil ,
+.Fn uuid_equal ,
+.Fn uuid_from_string ,
+.Fn uuid_hash ,
+.Fn uuid_is_nil ,
+and
+.Fn uuid_to_string
+functions are compatible with the DCE 1.1 RPC specification.
+.Sh HISTORY
+The UUID functions first appeared in
+.Nx 3.0 .
diff --git a/lib/nbsd_libc/uuid/uuid_compare.c b/lib/nbsd_libc/uuid/uuid_compare.c
new file mode 100644 (file)
index 0000000..439c827
--- /dev/null
@@ -0,0 +1,87 @@
+/*     $NetBSD: uuid_compare.c,v 1.2 2008/04/23 07:52:32 plunky Exp $  */
+
+/*-
+ * Copyright (c) 2002 Marcel Moolenaar
+ * Copyright (c) 2002 Hiten Mahesh Pandya
+ * 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.
+ *
+ * $FreeBSD: src/lib/libc/uuid/uuid_compare.c,v 1.3 2003/08/08 19:18:43 marcel Exp $
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: uuid_compare.c,v 1.2 2008/04/23 07:52:32 plunky Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <string.h>
+#include <uuid.h>
+
+/*
+ * uuid_compare() - compare two UUIDs.
+ * See also:
+ *     http://www.opengroup.org/onlinepubs/009629399/uuid_compare.htm
+ *
+ * NOTE: Either UUID can be NULL, meaning a nil UUID. nil UUIDs are smaller
+ *      than any non-nil UUID.
+ */
+int32_t
+uuid_compare(const uuid_t *a, const uuid_t *b, uint32_t *status)
+{
+       int res;
+
+       if (status != NULL)
+               *status = uuid_s_ok;
+
+       /* Deal with NULL or equal pointers. */
+       if (a == b)
+               return (0);
+       if (a == NULL)
+               return ((uuid_is_nil(b, NULL)) ? 0 : -1);
+       if (b == NULL)
+               return ((uuid_is_nil(a, NULL)) ? 0 : 1);
+
+       /* We have to compare the hard way. */
+       res = (int)((int64_t)a->time_low - (int64_t)b->time_low);
+       if (res)
+               return ((res < 0) ? -1 : 1);
+       res = (int)a->time_mid - (int)b->time_mid;
+       if (res)
+               return ((res < 0) ? -1 : 1);
+       res = (int)a->time_hi_and_version - (int)b->time_hi_and_version;
+       if (res)
+               return ((res < 0) ? -1 : 1);
+       res = (int)a->clock_seq_hi_and_reserved -
+           (int)b->clock_seq_hi_and_reserved;
+       if (res)
+               return ((res < 0) ? -1 : 1);
+       res = (int)a->clock_seq_low - (int)b->clock_seq_low;
+       if (res)
+               return ((res < 0) ? -1 : 1);
+       res = memcmp(a->node, b->node, sizeof(a->node));
+       if (res)
+               return ((res < 0) ? -1 : 1);
+       return (0);
+}
diff --git a/lib/nbsd_libc/uuid/uuid_create.c b/lib/nbsd_libc/uuid/uuid_create.c
new file mode 100644 (file)
index 0000000..bb40f20
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: uuid_create.c,v 1.1 2004/09/13 21:44:54 thorpej Exp $  */
+
+/*-
+ * Copyright (c) 2002 Marcel Moolenaar
+ * Copyright (c) 2002 Hiten Mahesh Pandya
+ * 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.
+ *
+ * $FreeBSD: src/lib/libc/uuid/uuid_create.c,v 1.2 2003/08/08 19:18:43 marcel Exp $
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: uuid_create.c,v 1.1 2004/09/13 21:44:54 thorpej Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <uuid.h>
+
+/*
+ * uuid_create() - create an UUID.
+ * See also:
+ *     http://www.opengroup.org/onlinepubs/009629399/uuid_create.htm
+ */
+void
+uuid_create(uuid_t *u, uint32_t *status)
+{
+       uint32_t s;
+
+       if (uuidgen(u, 1) == -1)
+               s = uuid_s_no_memory;   /* XXX */
+       else
+               s = uuid_s_ok;
+
+       if (status)
+               *status = s;
+}
diff --git a/lib/nbsd_libc/uuid/uuid_create_nil.c b/lib/nbsd_libc/uuid/uuid_create_nil.c
new file mode 100644 (file)
index 0000000..e48dc26
--- /dev/null
@@ -0,0 +1,59 @@
+/*     $NetBSD: uuid_create_nil.c,v 1.2 2005/02/09 21:35:47 kleink Exp $       */
+
+/*-
+ * Copyright (c) 2002 Marcel Moolenaar
+ * Copyright (c) 2002 Hiten Mahesh Pandya
+ * 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.
+ *
+ * $FreeBSD: src/lib/libc/uuid/uuid_create_nil.c,v 1.2 2003/08/08 19:18:43 marcel Exp $
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: uuid_create_nil.c,v 1.2 2005/02/09 21:35:47 kleink Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <string.h>
+#include <uuid.h>
+
+#ifdef __weak_alias
+__weak_alias(uuid_create_nil,_uuid_create_nil)
+#endif
+
+/*
+ * uuid_create_nil() - create a nil UUID.
+ * See also:
+ *     http://www.opengroup.org/onlinepubs/009629399/uuid_create_nil.htm
+ */
+void
+uuid_create_nil(uuid_t *u, uint32_t *status)
+{
+
+       memset(u, 0, sizeof(*u));
+
+       if (status)
+               *status = uuid_s_ok;
+}
diff --git a/lib/nbsd_libc/uuid/uuid_equal.c b/lib/nbsd_libc/uuid/uuid_equal.c
new file mode 100644 (file)
index 0000000..c7c83e8
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: uuid_equal.c,v 1.2 2008/04/23 07:52:32 plunky Exp $    */
+
+/*-
+ * Copyright (c) 2002 Marcel Moolenaar
+ * Copyright (c) 2002 Hiten Mahesh Pandya
+ * 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.
+ *
+ * $FreeBSD: src/lib/libc/uuid/uuid_equal.c,v 1.2 2003/08/08 19:18:43 marcel Exp $
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: uuid_equal.c,v 1.2 2008/04/23 07:52:32 plunky Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <string.h>
+#include <uuid.h>
+
+/*
+ * uuid_equal() - compare for equality.
+ * See also:
+ *     http://www.opengroup.org/onlinepubs/009629399/uuid_equal.htm
+ */
+int32_t
+uuid_equal(const uuid_t *a, const uuid_t *b, uint32_t *status)
+{
+
+       if (status != NULL)
+               *status = uuid_s_ok;
+
+       /* Deal with equal or NULL pointers. */
+       if (a == b)
+               return (1);
+       if (a == NULL)
+               return (uuid_is_nil(b, NULL));
+       if (b == NULL)
+               return (uuid_is_nil(a, NULL));
+
+       /* Do a byte for byte comparison. */
+       return ((memcmp(a, b, sizeof(uuid_t))) ? 0 : 1);
+}
diff --git a/lib/nbsd_libc/uuid/uuid_from_string.c b/lib/nbsd_libc/uuid/uuid_from_string.c
new file mode 100644 (file)
index 0000000..f339068
--- /dev/null
@@ -0,0 +1,101 @@
+/*     $NetBSD: uuid_from_string.c,v 1.1 2004/09/13 21:44:54 thorpej Exp $     */
+
+/*-
+ * Copyright (c) 2002 Marcel Moolenaar
+ * Copyright (c) 2002 Hiten Mahesh Pandya
+ * 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.
+ *
+ * $FreeBSD: src/lib/libc/uuid/uuid_from_string.c,v 1.2 2003/08/08 19:18:43 marcel Exp $
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: uuid_from_string.c,v 1.1 2004/09/13 21:44:54 thorpej Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <stdio.h>
+#include <string.h>
+#include <uuid.h>
+
+/*
+ * uuid_from_string() - convert a string representation of an UUID into
+ *                     a binary representation.
+ * See also:
+ *     http://www.opengroup.org/onlinepubs/009629399/uuid_from_string.htm
+ *
+ * NOTE: The sequence field is in big-endian, while the time fields are in
+ *      native byte order.
+ */
+void
+uuid_from_string(const char *s, uuid_t *u, uint32_t *status)
+{
+       int n;
+
+       /* Short-circuit 2 special cases: NULL pointer and empty string. */
+       if (s == NULL || *s == '\0') {
+               uuid_create_nil(u, status);
+               return;
+       }
+
+       /* Assume the worst. */
+       if (status != NULL)
+               *status = uuid_s_invalid_string_uuid;
+
+       /* The UUID string representation has a fixed length. */
+       if (strlen(s) != 36)
+               return;
+
+       /*
+        * We only work with "new" UUIDs. New UUIDs have the form:
+        *      01234567-89ab-cdef-0123-456789abcdef
+        * The so called "old" UUIDs, which we don't support, have the form:
+        *      0123456789ab.cd.ef.01.23.45.67.89.ab
+        */
+       if (s[8] != '-')
+               return;
+
+       n = sscanf(s,
+           "%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
+           &u->time_low, &u->time_mid, &u->time_hi_and_version,
+           &u->clock_seq_hi_and_reserved, &u->clock_seq_low, &u->node[0],
+           &u->node[1], &u->node[2], &u->node[3], &u->node[4], &u->node[5]);
+
+       /* Make sure we have all conversions. */
+       if (n != 11)
+               return;
+
+       /* We have a successful scan. Check semantics... */
+       n = u->clock_seq_hi_and_reserved;
+       if ((n & 0x80) != 0x00 &&                       /* variant 0? */
+           (n & 0xc0) != 0x80 &&                       /* variant 1? */
+           (n & 0xe0) != 0xc0) {                       /* variant 2? */
+               if (status != NULL)
+                       *status = uuid_s_bad_version;
+       } else {
+               if (status != NULL)
+                       *status = uuid_s_ok;
+       }
+}
diff --git a/lib/nbsd_libc/uuid/uuid_hash.c b/lib/nbsd_libc/uuid/uuid_hash.c
new file mode 100644 (file)
index 0000000..996989d
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: uuid_hash.c,v 1.2 2008/04/23 07:52:32 plunky Exp $     */
+
+/*-
+ * Copyright (c) 2002 Marcel Moolenaar
+ * Copyright (c) 2002 Hiten Mahesh Pandya
+ * 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.
+ *
+ * $FreeBSD: src/lib/libc/uuid/uuid_hash.c,v 1.2 2003/08/08 19:18:43 marcel Exp $
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: uuid_hash.c,v 1.2 2008/04/23 07:52:32 plunky Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <uuid.h>
+
+/*
+ * uuid_hash() - generate a hash value.
+ * See also:
+ *     http://www.opengroup.org/onlinepubs/009629399/uuid_hash.htm
+ */
+uint16_t
+uuid_hash(const uuid_t *u, uint32_t *status)
+{
+
+       if (status)
+               *status = uuid_s_ok;
+
+       /*
+        * Use the most frequently changing bits in the UUID as the hash
+        * value. This should yield a good enough distribution...
+        */
+       return ((u) ? u->time_low & 0xffff : 0);
+}
diff --git a/lib/nbsd_libc/uuid/uuid_is_nil.c b/lib/nbsd_libc/uuid/uuid_is_nil.c
new file mode 100644 (file)
index 0000000..3c9ab2d
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: uuid_is_nil.c,v 1.4 2008/04/23 07:52:32 plunky Exp $   */
+
+/*-
+ * Copyright (c) 2002 Marcel Moolenaar
+ * Copyright (c) 2002 Hiten Mahesh Pandya
+ * 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.
+ *
+ * $FreeBSD: src/lib/libc/uuid/uuid_is_nil.c,v 1.2 2003/08/08 19:18:43 marcel Exp $
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: uuid_is_nil.c,v 1.4 2008/04/23 07:52:32 plunky Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <string.h>
+#include <uuid.h>
+
+#ifdef __weak_alias
+__weak_alias(uuid_is_nil,_uuid_is_nil)
+#endif
+
+/*
+ * uuid_is_nil() - return whether the UUID is a nil UUID.
+ * See also:
+ *     http://www.opengroup.org/onlinepubs/009629399/uuid_is_nil.htm
+ */
+int32_t
+uuid_is_nil(const uuid_t *u, uint32_t *status)
+{
+       static const uuid_t nil = { .time_low = 0 };
+
+       if (status)
+               *status = uuid_s_ok;
+
+       if (!u)
+               return (1);
+
+       return (memcmp(u, &nil, sizeof(uuid_t)) == 0 ? 1 : 0);
+}
diff --git a/lib/nbsd_libc/uuid/uuid_stream.c b/lib/nbsd_libc/uuid/uuid_stream.c
new file mode 100644 (file)
index 0000000..4d08c45
--- /dev/null
@@ -0,0 +1,117 @@
+/*     $NetBSD: uuid_stream.c,v 1.3 2008/04/19 18:21:38 plunky Exp $   */
+
+/*
+ * Copyright (c) 2002 Marcel Moolenaar
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: uuid_stream.c,v 1.3 2008/04/19 18:21:38 plunky Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <machine/endian.h>
+#include <uuid.h>
+
+/*
+ * Encode/Decode UUID into octet-stream.
+ *   http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
+ *
+ * 0                   1                   2                   3
+ *   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ *  |                          time_low                             |
+ *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ *  |       time_mid                |         time_hi_and_version   |
+ *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ *  |clk_seq_hi_res |  clk_seq_low  |         node (0-1)            |
+ *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ *  |                         node (2-5)                            |
+ *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ *
+ * NOTE: These routines are not part of the DCE RPC API.  There are
+ * provided for convenience.
+ */
+
+void
+uuid_enc_le(void *buf, const uuid_t *uuid)
+{
+       uint8_t *p = buf;
+       int i;
+
+       le32enc(p, uuid->time_low);
+       le16enc(p + 4, uuid->time_mid);
+       le16enc(p + 6, uuid->time_hi_and_version);
+       p[8] = uuid->clock_seq_hi_and_reserved;
+       p[9] = uuid->clock_seq_low;
+       for (i = 0; i < _UUID_NODE_LEN; i++)
+               p[10 + i] = uuid->node[i];
+}
+
+void
+uuid_dec_le(const void *buf, uuid_t *uuid)
+{
+       const uint8_t *p = buf;
+       int i;
+
+       uuid->time_low = le32dec(p);
+       uuid->time_mid = le16dec(p + 4);
+       uuid->time_hi_and_version = le16dec(p + 6);
+       uuid->clock_seq_hi_and_reserved = p[8];
+       uuid->clock_seq_low = p[9];
+       for (i = 0; i < _UUID_NODE_LEN; i++)
+               uuid->node[i] = p[10 + i];
+}
+
+void
+uuid_enc_be(void *buf, const uuid_t *uuid)
+{
+       uint8_t *p = buf;
+       int i;
+
+       be32enc(p, uuid->time_low);
+       be16enc(p + 4, uuid->time_mid);
+       be16enc(p + 6, uuid->time_hi_and_version);
+       p[8] = uuid->clock_seq_hi_and_reserved;
+       p[9] = uuid->clock_seq_low;
+       for (i = 0; i < _UUID_NODE_LEN; i++)
+               p[10 + i] = uuid->node[i];
+}
+
+void
+uuid_dec_be(const void *buf, uuid_t *uuid)
+{
+       const uint8_t *p = buf;
+       int i;
+
+       uuid->time_low = be32dec(p);
+       uuid->time_mid = be16dec(p + 4);
+       uuid->time_hi_and_version = be16dec(p + 6);
+       uuid->clock_seq_hi_and_reserved = p[8];
+       uuid->clock_seq_low = p[9];
+       for (i = 0; i < _UUID_NODE_LEN; i++)
+               uuid->node[i] = p[10 + i];
+}
diff --git a/lib/nbsd_libc/uuid/uuid_to_string.c b/lib/nbsd_libc/uuid/uuid_to_string.c
new file mode 100644 (file)
index 0000000..7f46e39
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: uuid_to_string.c,v 1.2 2008/04/23 07:52:32 plunky Exp $        */
+
+/*-
+ * Copyright (c) 2002 Marcel Moolenaar
+ * Copyright (c) 2002 Hiten Mahesh Pandya
+ * 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.
+ *
+ * $FreeBSD: src/lib/libc/uuid/uuid_to_string.c,v 1.2 2003/08/08 19:18:43 marcel Exp $
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: uuid_to_string.c,v 1.2 2008/04/23 07:52:32 plunky Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <stdio.h>
+#include <string.h>
+#include <uuid.h>
+
+/*
+ * uuid_to_string() - Convert a binary UUID into a string representation.
+ * See also:
+ *     http://www.opengroup.org/onlinepubs/009629399/uuid_to_string.htm
+ *
+ * NOTE: The references given above do not have a status code for when
+ *      the string could not be allocated. The status code has been
+ *      taken from the Hewlett-Packard implementation.
+ */
+void
+uuid_to_string(const uuid_t *u, char **s, uint32_t *status)
+{
+       static const uuid_t nil = { .time_low = 0 };
+
+       if (status != NULL)
+               *status = uuid_s_ok;
+
+       /* Why allow a NULL-pointer here? */
+       if (s == 0)
+               return;
+
+       if (u == NULL)
+               u = &nil;
+
+       asprintf(s, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+           u->time_low, u->time_mid, u->time_hi_and_version,
+           u->clock_seq_hi_and_reserved, u->clock_seq_low, u->node[0],
+           u->node[1], u->node[2], u->node[3], u->node[4], u->node[5]);
+
+       if (*s == NULL && status != NULL)
+               *status = uuid_s_no_memory;
+}
diff --git a/lib/nbsd_libc/yp/Makefile.inc b/lib/nbsd_libc/yp/Makefile.inc
new file mode 100644 (file)
index 0000000..2f687f4
--- /dev/null
@@ -0,0 +1,13 @@
+#      $NetBSD: Makefile.inc,v 1.14 1999/02/24 15:05:21 drochner Exp $
+
+# yp sources
+.PATH: ${ARCHDIR}/yp ${.CURDIR}/yp
+
+SRCS+= xdryp.c yp_all.c yp_first.c yp_maplist.c yp_master.c yp_match.c \
+       yp_order.c yplib.c yperr_string.c ypprot_err.c
+MAN+=  ypclnt.3
+
+MLINKS+=ypclnt.3 yp_all.3 ypclnt.3 yp_bind.3 ypclnt.3 yp_first.3 \
+       ypclnt.3 yp_get_default_domain.3 ypclnt.3 yp_master.3 \
+       ypclnt.3 yp_match.3 ypclnt.3 yp_next.3 ypclnt.3 yp_order.3 \
+       ypclnt.3 yp_unbind.3 ypclnt.3 yperr_string.3 ypclnt.3 ypprot_err.3
diff --git a/lib/nbsd_libc/yp/local.h b/lib/nbsd_libc/yp/local.h
new file mode 100644 (file)
index 0000000..de72df0
--- /dev/null
@@ -0,0 +1,30 @@
+/*     $NetBSD: local.h,v 1.3 2009/10/21 01:07:46 snj Exp $    */
+
+/*
+ * Copyright (c) 1996 Christos Zoulas.  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 ``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 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.
+ */
+
+__BEGIN_DECLS
+void __yp_unbind __P((struct dom_binding *));
+int _yp_invalid_domain __P((const char *));
+__END_DECLS
diff --git a/lib/nbsd_libc/yp/xdryp.c b/lib/nbsd_libc/yp/xdryp.c
new file mode 100644 (file)
index 0000000..05f301a
--- /dev/null
@@ -0,0 +1,600 @@
+/*     $NetBSD: xdryp.c,v 1.30 2006/05/11 17:11:57 mrg Exp $   */
+
+/*
+ * Copyright (c) 1996 Jason R. Thorpe <thorpej@NetBSD.org>.
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed for the NetBSD Project
+ *     by Jason R. Thorpe.
+ * 4. 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 ``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 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.
+ */
+
+/*
+ * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca>
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: xdryp.c,v 1.30 2006/05/11 17:11:57 mrg Exp $");
+#endif
+
+/*
+ * XDR routines used by the YP protocol.  Note that these routines do
+ * not strictly conform to the RPC definition in yp.x.  This file
+ * replicates the functions exported by the Sun YP API; reality is
+ * often inaccurate.
+ */
+
+#include "namespace.h"
+
+#include <sys/param.h>
+#include <sys/socket.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <rpc/rpc.h>
+#include <rpc/xdr.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+
+#ifdef __weak_alias
+__weak_alias(xdr_datum,_xdr_datum)
+__weak_alias(xdr_domainname,_xdr_domainname)
+__weak_alias(xdr_mapname,_xdr_mapname)
+__weak_alias(xdr_peername,_xdr_peername)
+__weak_alias(xdr_yp_inaddr,_xdr_yp_inaddr)
+__weak_alias(xdr_ypall,_xdr_ypall)
+__weak_alias(xdr_ypbind_resp,_xdr_ypbind_resp)
+__weak_alias(xdr_ypbind_setdom,_xdr_ypbind_setdom)
+__weak_alias(xdr_ypdomain_wrap_string,_xdr_ypdomain_wrap_string)
+__weak_alias(xdr_ypmap_parms,_xdr_ypmap_parms)
+__weak_alias(xdr_ypmap_wrap_string,_xdr_ypmap_wrap_string)
+__weak_alias(xdr_ypmaplist,_xdr_ypmaplist)
+__weak_alias(xdr_ypowner_wrap_string,_xdr_ypowner_wrap_string)
+__weak_alias(xdr_yppushresp_xfr,_xdr_yppushresp_xfr)
+__weak_alias(xdr_ypreq_key,_xdr_ypreq_key)
+__weak_alias(xdr_ypreq_nokey,_xdr_ypreq_nokey)
+__weak_alias(xdr_ypreq_xfr,_xdr_ypreq_xfr)
+__weak_alias(xdr_ypresp_key_val,_xdr_ypresp_key_val)
+__weak_alias(xdr_ypresp_maplist,_xdr_ypresp_maplist)
+__weak_alias(xdr_ypresp_master,_xdr_ypresp_master)
+__weak_alias(xdr_ypresp_order,_xdr_ypresp_order)
+__weak_alias(xdr_ypresp_val,_xdr_ypresp_val)
+#endif
+
+/*
+ * Functions used only within this file.
+ */
+static bool_t xdr_ypbind_binding __P((XDR *, struct ypbind_binding *));
+static bool_t xdr_ypbind_resptype __P((XDR *, enum ypbind_resptype *));
+static bool_t xdr_ypstat __P((XDR *, enum ypbind_resptype *));
+static bool_t xdr_ypmaplist_str __P((XDR *, char *));
+
+__warn_references(xdr_domainname,
+    "warning: this program uses xdr_domainname(), which is deprecated and buggy.")
+
+bool_t
+xdr_domainname(xdrs, objp)
+       XDR *xdrs;
+       char *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       return xdr_string(xdrs, &objp, YPMAXDOMAIN);
+}
+
+__warn_references(xdr_peername,
+    "warning: this program uses xdr_peername(), which is deprecated and buggy.")
+
+bool_t
+xdr_peername(xdrs, objp)
+       XDR *xdrs;
+       char *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       return xdr_string(xdrs, &objp, YPMAXPEER);
+}
+
+__warn_references(xdr_mapname,
+    "warning: this program uses xdr_mapname(), which is deprecated and buggy.")
+
+bool_t
+xdr_mapname(xdrs, objp)
+       XDR *xdrs;
+       char *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       return xdr_string(xdrs, &objp, YPMAXMAP);
+}
+
+bool_t
+xdr_ypdomain_wrap_string(xdrs, objp)
+       XDR *xdrs;
+       char **objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       return xdr_string(xdrs, objp, YPMAXDOMAIN);
+}
+
+bool_t
+xdr_ypmap_wrap_string(xdrs, objp)
+       XDR *xdrs;
+       char **objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       return xdr_string(xdrs, objp, YPMAXMAP);
+}
+
+bool_t
+xdr_ypowner_wrap_string(xdrs, objp)
+       XDR *xdrs;
+       char **objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       return xdr_string(xdrs, objp, YPMAXPEER);
+}
+
+bool_t
+xdr_datum(xdrs, objp)
+       XDR *xdrs;
+       datum *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       return xdr_bytes(xdrs, __UNCONST(&objp->dptr),
+           (u_int *)&objp->dsize, YPMAXRECORD);
+}
+
+bool_t
+xdr_ypreq_key(xdrs, objp)
+       XDR *xdrs;
+       struct ypreq_key *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_ypdomain_wrap_string(xdrs, __UNCONST(&objp->domain)))
+               return FALSE;
+
+       if (!xdr_ypmap_wrap_string(xdrs, __UNCONST(&objp->map)))
+               return FALSE;
+
+       if (!xdr_datum(xdrs, &objp->keydat))
+               return FALSE;
+
+       return TRUE;
+}
+
+bool_t
+xdr_ypreq_nokey(xdrs, objp)
+       XDR *xdrs;
+       struct ypreq_nokey *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_ypdomain_wrap_string(xdrs, __UNCONST(&objp->domain)))
+               return FALSE;
+
+       if (!xdr_ypmap_wrap_string(xdrs, __UNCONST(&objp->map)))
+               return FALSE;
+
+       return TRUE;
+}
+
+bool_t
+xdr_yp_inaddr(xdrs, objp)
+       XDR *xdrs;
+       struct in_addr *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       return xdr_opaque(xdrs, (caddr_t)(void *)&objp->s_addr,
+           sizeof objp->s_addr);
+}
+
+static bool_t
+xdr_ypbind_binding(xdrs, objp)
+       XDR *xdrs;
+       struct ypbind_binding *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_yp_inaddr(xdrs, &objp->ypbind_binding_addr))
+               return FALSE;
+
+       if (!xdr_opaque(xdrs, (void *)&objp->ypbind_binding_port,
+           sizeof objp->ypbind_binding_port))
+               return FALSE;
+
+       return TRUE;
+}
+
+static bool_t
+xdr_ypbind_resptype(xdrs, objp)
+       XDR *xdrs;
+       enum ypbind_resptype *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       return xdr_enum(xdrs, (enum_t *)(void *)objp);
+}
+
+static bool_t
+xdr_ypstat(xdrs, objp)
+       XDR *xdrs;
+       enum ypbind_resptype *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       return xdr_enum(xdrs, (enum_t *)(void *)objp);
+}
+
+bool_t
+xdr_ypbind_resp(xdrs, objp)
+       XDR *xdrs;
+       struct ypbind_resp *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_ypbind_resptype(xdrs, &objp->ypbind_status))
+               return FALSE;
+
+       switch (objp->ypbind_status) {
+       case YPBIND_FAIL_VAL:
+               return xdr_u_int(xdrs,
+                   (u_int *)&objp->ypbind_respbody.ypbind_error);
+
+       case YPBIND_SUCC_VAL:
+               return xdr_ypbind_binding(xdrs,
+                   &objp->ypbind_respbody.ypbind_bindinfo);
+
+       default:
+               return FALSE;
+       }
+       /* NOTREACHED */
+}
+
+bool_t
+xdr_ypresp_val(xdrs, objp)
+       XDR *xdrs;
+       struct ypresp_val *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_ypstat(xdrs, (enum ypbind_resptype *)(void *)&objp->status))
+               return FALSE;
+
+       if (!xdr_datum(xdrs, &objp->valdat))
+               return FALSE;
+
+       return TRUE;
+}
+
+bool_t
+xdr_ypbind_setdom(xdrs, objp)
+       XDR *xdrs;
+       struct ypbind_setdom *objp;
+{
+       char *cp;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       cp = objp->ypsetdom_domain;
+
+       if (!xdr_ypdomain_wrap_string(xdrs, &cp))
+               return FALSE;
+
+       if (!xdr_ypbind_binding(xdrs, &objp->ypsetdom_binding))
+               return FALSE;
+
+       if (!xdr_u_int(xdrs, &objp->ypsetdom_vers))
+               return FALSE;
+
+       return TRUE;
+}
+
+bool_t
+xdr_ypresp_key_val(xdrs, objp)
+       XDR *xdrs;
+       struct ypresp_key_val *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_ypstat(xdrs, (enum ypbind_resptype *)(void *)&objp->status))
+               return FALSE;
+
+       if (!xdr_datum(xdrs, &objp->valdat))
+               return FALSE;
+
+       if (!xdr_datum(xdrs, &objp->keydat))
+               return FALSE;
+
+       return TRUE;
+}
+
+bool_t
+xdr_ypall(xdrs, incallback)
+       XDR *xdrs;
+       struct ypall_callback *incallback;
+{
+       struct ypresp_key_val out;
+       char key[YPMAXRECORD], val[YPMAXRECORD];
+       bool_t more, status;
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(incallback != NULL);
+
+       /*
+        * Set up key/val struct to be used during the transaction.
+        */
+       memset(&out, 0, sizeof out);
+       out.keydat.dptr = key;
+       out.keydat.dsize = sizeof(key);
+       out.valdat.dptr = val;
+       out.valdat.dsize = sizeof(val);
+
+       for (;;) {
+               /* Values pending? */
+               if (!xdr_bool(xdrs, &more))
+                       return FALSE;           /* can't tell! */
+               if (!more)
+                       return TRUE;            /* no more */
+
+               /* Transfer key/value pair. */
+               status = xdr_ypresp_key_val(xdrs, &out);
+
+               /*
+                * If we succeeded, call the callback function.
+                * The callback will return TRUE when it wants
+                * no more values.  If we fail, indicate the
+                * error.
+                */
+               if (status) {
+                       if ((*incallback->foreach)((int)out.status,
+                           __UNCONST(out.keydat.dptr), out.keydat.dsize,
+                           __UNCONST(out.valdat.dptr), out.valdat.dsize,
+                           incallback->data))
+                               return TRUE;
+               } else
+                       return FALSE;
+       }
+}
+
+bool_t
+xdr_ypresp_master(xdrs, objp)
+       XDR *xdrs;
+       struct ypresp_master *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_ypstat(xdrs, (enum ypbind_resptype *)(void *)&objp->status))
+               return FALSE;
+
+       if (!xdr_string(xdrs, &objp->master, YPMAXPEER))
+               return FALSE;
+
+       return TRUE;
+}
+
+static bool_t
+xdr_ypmaplist_str(xdrs, objp)
+       XDR *xdrs;
+       char *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       return xdr_string(xdrs, &objp, YPMAXMAP+1);
+}
+
+bool_t
+xdr_ypmaplist(xdrs, objp)
+       XDR *xdrs;
+       struct ypmaplist *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_ypmaplist_str(xdrs, objp->ypml_name))
+               return FALSE;
+
+       if (!xdr_pointer(xdrs, (char **)(void *)&objp->ypml_next,
+           sizeof(struct ypmaplist), (xdrproc_t)xdr_ypmaplist))
+               return FALSE;
+
+       return TRUE;
+}
+
+bool_t
+xdr_ypresp_maplist(xdrs, objp)
+       XDR *xdrs;
+       struct ypresp_maplist *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_ypstat(xdrs, (enum ypbind_resptype *)(void *)&objp->status))
+               return FALSE;
+
+       if (!xdr_pointer(xdrs, (char **)(void *)&objp->list,
+           sizeof(struct ypmaplist), (xdrproc_t)xdr_ypmaplist))
+               return FALSE;
+
+       return TRUE;
+}
+
+bool_t
+xdr_ypresp_order(xdrs, objp)
+       XDR *xdrs;
+       struct ypresp_order *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_ypstat(xdrs, (enum ypbind_resptype *)(void *)&objp->status))
+               return FALSE;
+
+       if (!xdr_u_int(xdrs, &objp->ordernum))
+               return FALSE;
+
+       return TRUE;
+}
+
+bool_t
+xdr_ypreq_xfr(xdrs, objp)
+       XDR *xdrs;
+       struct ypreq_xfr *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_ypmap_parms(xdrs, &objp->map_parms))
+               return FALSE;
+
+       if (!xdr_u_int(xdrs, &objp->transid))
+               return FALSE;
+
+       if (!xdr_u_int(xdrs, &objp->proto))
+               return FALSE;
+
+       if (!xdr_u_int(xdrs, &objp->port))
+               return FALSE;
+
+       return TRUE;
+}
+
+bool_t
+xdr_ypmap_parms(xdrs, objp)
+       XDR *xdrs;
+       struct ypmap_parms *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_ypdomain_wrap_string(xdrs, __UNCONST(&objp->domain)))
+               return FALSE;
+
+       if (!xdr_ypmap_wrap_string(xdrs, __UNCONST(&objp->map)))
+               return FALSE;
+
+       if (!xdr_u_int(xdrs, &objp->ordernum))
+               return FALSE;
+
+       if (!xdr_ypowner_wrap_string(xdrs, &objp->owner))
+               return FALSE;
+
+       return TRUE;
+}
+
+bool_t
+xdr_yppushresp_xfr(xdrs, objp)
+       XDR *xdrs;
+       struct yppushresp_xfr *objp;
+{
+
+       _DIAGASSERT(xdrs != NULL);
+       _DIAGASSERT(objp != NULL);
+
+       if (!xdr_u_int(xdrs, &objp->transid))
+               return FALSE;
+
+       if (!xdr_enum(xdrs, (enum_t *)&objp->status))
+               return FALSE;
+
+       return TRUE;
+}
diff --git a/lib/nbsd_libc/yp/yp_all.c b/lib/nbsd_libc/yp/yp_all.c
new file mode 100644 (file)
index 0000000..6d97ce7
--- /dev/null
@@ -0,0 +1,95 @@
+/*     $NetBSD: yp_all.c,v 1.12 2003/12/10 12:06:25 agc Exp $   */
+
+/*
+ * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca>
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: yp_all.c,v 1.12 2003/12/10 12:06:25 agc Exp $");
+#endif
+
+#include "namespace.h"
+#include <string.h>
+#include <err.h>
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+#include "local.h"
+
+extern struct timeval _yplib_timeout;
+
+#ifdef __weak_alias
+__weak_alias(yp_all,_yp_all)
+#endif
+
+int
+yp_all(indomain, inmap, incallback)
+       const char     *indomain;
+       const char     *inmap;
+       struct ypall_callback *incallback;
+{
+       struct ypreq_nokey yprnk;
+       struct dom_binding *ysd;
+       struct sockaddr_in clnt_sin;
+       enum clnt_stat  status;
+       CLIENT         *clnt;
+       int             clnt_sock;
+
+       if (_yp_invalid_domain(indomain))
+               return YPERR_BADARGS;
+       if (inmap == NULL || *inmap == '\0'
+           || strlen(inmap) > YPMAXMAP)
+               return YPERR_BADARGS;
+       if (incallback == NULL)
+               return YPERR_BADARGS;
+
+       if (_yp_dobind(indomain, &ysd) != 0)
+               return YPERR_DOMAIN;
+
+       clnt_sock = RPC_ANYSOCK;
+       clnt_sin = ysd->dom_server_addr;
+       clnt_sin.sin_port = 0;
+       clnt = clnttcp_create(&clnt_sin, YPPROG, YPVERS, &clnt_sock, 0, 0);
+       if (clnt == NULL) {
+               warnx("clnttcp_create failed");
+               return YPERR_PMAP;
+       }
+       yprnk.domain = indomain;
+       yprnk.map = inmap;
+
+       status = clnt_call(clnt, (rpcproc_t)YPPROC_ALL,
+           (xdrproc_t)xdr_ypreq_nokey, &yprnk,
+           (xdrproc_t)xdr_ypall, (char *)(void *)incallback, _yplib_timeout);
+       clnt_destroy(clnt);
+
+       /* not really needed... */
+       __yp_unbind(ysd);
+
+       if (status != RPC_SUCCESS)
+               return YPERR_RPC;
+
+       return 0;
+}
diff --git a/lib/nbsd_libc/yp/yp_first.c b/lib/nbsd_libc/yp/yp_first.c
new file mode 100644 (file)
index 0000000..482faaf
--- /dev/null
@@ -0,0 +1,208 @@
+/*     $NetBSD: yp_first.c,v 1.14 2003/12/10 12:06:25 agc Exp $         */
+
+/*
+ * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca>
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: yp_first.c,v 1.14 2003/12/10 12:06:25 agc Exp $");
+#endif
+
+#include "namespace.h"
+#include <stdlib.h>
+#include <string.h>
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+#include "local.h"
+
+extern struct timeval _yplib_timeout;
+extern int _yplib_nerrs;
+
+#ifdef __weak_alias
+__weak_alias(yp_first,_yp_first)
+__weak_alias(yp_next,_yp_next)
+#endif
+
+int
+yp_first(indomain, inmap, outkey, outkeylen, outval, outvallen)
+       const char     *indomain;
+       const char     *inmap;
+       char          **outkey;
+       int            *outkeylen;
+       char          **outval;
+       int            *outvallen;
+{
+       struct ypresp_key_val yprkv;
+       struct ypreq_nokey yprnk;
+       struct dom_binding *ysd;
+       int r, nerrs = 0;
+
+       if (outkey == NULL || outkeylen == NULL || \
+           outval == NULL || outvallen == NULL)
+               return YPERR_BADARGS;
+       *outkey = *outval = NULL;
+       *outkeylen = *outvallen = 0;
+       if (_yp_invalid_domain(indomain))
+               return YPERR_BADARGS;
+       if (inmap == NULL || *inmap == '\0'
+           || strlen(inmap) > YPMAXMAP)
+               return YPERR_BADARGS;
+
+again:
+       if (_yp_dobind(indomain, &ysd) != 0)
+               return YPERR_DOMAIN;
+
+       yprnk.domain = indomain;
+       yprnk.map = inmap;
+       (void)memset(&yprkv, 0, sizeof yprkv);
+
+       r = clnt_call(ysd->dom_client, (rpcproc_t)YPPROC_FIRST,
+           (xdrproc_t)xdr_ypreq_nokey,
+           &yprnk, (xdrproc_t)xdr_ypresp_key_val, &yprkv, _yplib_timeout);
+       if (r != RPC_SUCCESS) {
+               if (++nerrs == _yplib_nerrs) {
+                       clnt_perror(ysd->dom_client, "yp_first: clnt_call");
+                       nerrs = 0;
+               }
+               ysd->dom_vers = -1;
+               goto again;
+       }
+       if (!(r = ypprot_err(yprkv.status))) {
+               *outkeylen = yprkv.keydat.dsize;
+               if ((*outkey = malloc((size_t)(*outkeylen + 1))) == NULL)
+                       r = YPERR_RESRC;
+               else {
+                       (void)memcpy(*outkey, yprkv.keydat.dptr, 
+                           (size_t)*outkeylen);
+                       (*outkey)[*outkeylen] = '\0';
+               }
+               *outvallen = yprkv.valdat.dsize;
+               if ((*outval = malloc((size_t)(*outvallen + 1))) == NULL)
+                       r = YPERR_RESRC;
+               else {
+                       (void)memcpy(*outval, yprkv.valdat.dptr,
+                           (size_t)*outvallen);
+                       (*outval)[*outvallen] = '\0';
+               }
+       }
+       xdr_free((xdrproc_t)xdr_ypresp_key_val, (char *)(void *)&yprkv);
+       __yp_unbind(ysd);
+       if (r != 0) {
+               if (*outkey) {
+                       free(*outkey);
+                       *outkey = NULL;
+               }
+               if (*outval) {
+                       free(*outval);
+                       *outval = NULL;
+               }
+       }
+       return r;
+}
+
+int
+yp_next(indomain, inmap, inkey, inkeylen, outkey, outkeylen, outval, outvallen)
+       const char     *indomain;
+       const char     *inmap;
+       const char     *inkey;
+       int             inkeylen;
+       char          **outkey;
+       int            *outkeylen;
+       char          **outval;
+       int            *outvallen;
+{
+       struct ypresp_key_val yprkv;
+       struct ypreq_key yprk;
+       struct dom_binding *ysd;
+       int r, nerrs = 0;
+
+       if (outkey == NULL || outkeylen == NULL || \
+           outval == NULL || outvallen == NULL || \
+           inkey == NULL)
+               return YPERR_BADARGS;
+       *outkey = *outval = NULL;
+       *outkeylen = *outvallen = 0;
+
+       if (_yp_invalid_domain(indomain))
+               return YPERR_BADARGS;
+       if (inmap == NULL || *inmap == '\0'
+           || strlen(inmap) > YPMAXMAP)
+               return YPERR_BADARGS;
+
+again:
+       if (_yp_dobind(indomain, &ysd) != 0)
+               return YPERR_DOMAIN;
+
+       yprk.domain = indomain;
+       yprk.map = inmap;
+       yprk.keydat.dptr = inkey;
+       yprk.keydat.dsize = inkeylen;
+       (void)memset(&yprkv, 0, sizeof yprkv);
+
+       r = clnt_call(ysd->dom_client, (rpcproc_t)YPPROC_NEXT,
+           (xdrproc_t)xdr_ypreq_key,
+           &yprk, (xdrproc_t)xdr_ypresp_key_val, &yprkv, _yplib_timeout);
+       if (r != RPC_SUCCESS) {
+               if (++nerrs == _yplib_nerrs) {
+                       clnt_perror(ysd->dom_client, "yp_next: clnt_call");
+                       nerrs = 0;
+               }
+               ysd->dom_vers = -1;
+               goto again;
+       }
+       if (!(r = ypprot_err(yprkv.status))) {
+               *outkeylen = yprkv.keydat.dsize;
+               if ((*outkey = malloc((size_t)(*outkeylen + 1))) == NULL)
+                       r = YPERR_RESRC;
+               else {
+                       (void)memcpy(*outkey, yprkv.keydat.dptr,
+                           (size_t)*outkeylen);
+                       (*outkey)[*outkeylen] = '\0';
+               }
+               *outvallen = yprkv.valdat.dsize;
+               if ((*outval = malloc((size_t)(*outvallen + 1))) == NULL)
+                       r = YPERR_RESRC;
+               else {
+                       (void)memcpy(*outval, yprkv.valdat.dptr,
+                           (size_t)*outvallen);
+                       (*outval)[*outvallen] = '\0';
+               }
+       }
+       xdr_free((xdrproc_t)xdr_ypresp_key_val, (char *)(void *)&yprkv);
+       __yp_unbind(ysd);
+       if (r != 0) {
+               if (*outkey) {
+                       free(*outkey);
+                       *outkey = NULL;
+               }
+               if (*outval) {
+                       free(*outval);
+                       *outval = NULL;
+               }
+       }
+       return r;
+}
diff --git a/lib/nbsd_libc/yp/yp_maplist.c b/lib/nbsd_libc/yp/yp_maplist.c
new file mode 100644 (file)
index 0000000..b814312
--- /dev/null
@@ -0,0 +1,82 @@
+/*     $NetBSD: yp_maplist.c,v 1.11 2003/12/10 12:06:25 agc Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca>
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: yp_maplist.c,v 1.11 2003/12/10 12:06:25 agc Exp $");
+#endif
+
+#include "namespace.h"
+#include <string.h>
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+#include "local.h"
+
+extern struct timeval _yplib_timeout;
+extern int _yplib_nerrs;
+
+#ifdef __weak_alias
+__weak_alias(yp_maplist,_yp_maplist)
+#endif
+
+int
+yp_maplist(indomain, outmaplist)
+       const char     *indomain;
+       struct ypmaplist **outmaplist;
+{
+       struct dom_binding *ysd;
+       struct ypresp_maplist ypml;
+       int r, nerrs = 0;
+
+       if (_yp_invalid_domain(indomain))
+               return YPERR_BADARGS;
+       if (outmaplist == NULL)
+               return YPERR_BADARGS;
+again:
+       if (_yp_dobind(indomain, &ysd) != 0)
+               return YPERR_DOMAIN;
+
+       memset(&ypml, 0, sizeof ypml);
+
+       r = clnt_call(ysd->dom_client, (rpcproc_t)YPPROC_MAPLIST,
+                  (xdrproc_t)xdr_ypdomain_wrap_string, &indomain,
+                  (xdrproc_t)xdr_ypresp_maplist, &ypml, _yplib_timeout);
+       if (r != RPC_SUCCESS) {
+               if (++nerrs == _yplib_nerrs) {
+                       clnt_perror(ysd->dom_client, "yp_maplist: clnt_call");
+                       nerrs = 0;
+               }
+               ysd->dom_vers = -1;
+               goto again;
+       }
+       *outmaplist = ypml.list;
+       /* NO: xdr_free(xdr_ypresp_maplist, &ypml); */
+       __yp_unbind(ysd);
+       return ypprot_err(ypml.status);
+}
diff --git a/lib/nbsd_libc/yp/yp_master.c b/lib/nbsd_libc/yp/yp_master.c
new file mode 100644 (file)
index 0000000..7eaa96f
--- /dev/null
@@ -0,0 +1,103 @@
+/*     $NetBSD: yp_master.c,v 1.13 2003/12/10 12:06:25 agc Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca>
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: yp_master.c,v 1.13 2003/12/10 12:06:25 agc Exp $");
+#endif
+
+#include "namespace.h"
+#include <string.h>
+#include <stdlib.h>
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+#include "local.h"
+
+extern struct timeval _yplib_timeout;
+extern int _yplib_nerrs;
+
+#ifdef __weak_alias
+__weak_alias(yp_master,_yp_master)
+#endif
+
+int
+yp_master(indomain, inmap, outname)
+       const char     *indomain;
+       const char     *inmap;
+       char          **outname;
+{
+       struct dom_binding *ysd;
+       struct ypresp_master yprm;
+       struct ypreq_nokey yprnk;
+       int r, nerrs = 0;
+
+       if (outname == NULL)
+               return YPERR_BADARGS;
+       *outname = NULL;
+
+       if (_yp_invalid_domain(indomain))
+               return YPERR_BADARGS;
+       if (inmap == NULL || *inmap == '\0'
+           || strlen(inmap) > YPMAXMAP)
+               return YPERR_BADARGS;
+
+again:
+       if (_yp_dobind(indomain, &ysd) != 0)
+               return YPERR_DOMAIN;
+
+       yprnk.domain = indomain;
+       yprnk.map = inmap;
+
+       (void)memset(&yprm, 0, sizeof yprm);
+
+       r = clnt_call(ysd->dom_client, (rpcproc_t)YPPROC_MASTER,
+                     (xdrproc_t)xdr_ypreq_nokey, &yprnk,
+                     (xdrproc_t)xdr_ypresp_master, &yprm, _yplib_timeout);
+       if (r != RPC_SUCCESS) {
+               if (++nerrs == _yplib_nerrs) {
+                       clnt_perror(ysd->dom_client, "yp_master: clnt_call");
+                       nerrs = 0;
+               }
+               ysd->dom_vers = -1;
+               goto again;
+       }
+       if (!(r = ypprot_err(yprm.status))) {
+               if ((*outname = strdup(yprm.master)) == NULL)
+                       r = YPERR_RESRC;
+       }
+       xdr_free((xdrproc_t)xdr_ypresp_master, (char *)(void *)&yprm);
+       __yp_unbind(ysd);
+       if (r != 0) {
+               if (*outname) {
+                       free(*outname);
+                       *outname = NULL;
+               }
+       }
+       return r;
+}
diff --git a/lib/nbsd_libc/yp/yp_match.c b/lib/nbsd_libc/yp/yp_match.c
new file mode 100644 (file)
index 0000000..ce3ffdd
--- /dev/null
@@ -0,0 +1,261 @@
+/*     $NetBSD: yp_match.c,v 1.17 2005/11/29 03:12:01 christos Exp $    */
+
+/*
+ * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca>
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: yp_match.c,v 1.17 2005/11/29 03:12:01 christos Exp $");
+#endif
+
+#include "namespace.h"
+
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+#include "local.h"
+
+#define YPMATCHCACHE
+
+extern struct timeval _yplib_timeout;
+extern int _yplib_nerrs;
+extern char _yp_domain[];
+
+#ifdef __weak_alias
+__weak_alias(yp_match,_yp_match)
+#endif
+
+#ifdef YPMATCHCACHE
+int _yplib_cache = 5;
+
+static struct ypmatch_ent {
+       struct ypmatch_ent      *next;
+       char                    *map, *key;
+       char                    *val;
+       int                      keylen, vallen;
+       time_t                   expire_t;
+} *ypmc;
+
+static bool_t ypmatch_add __P((const char *, const char *, int, char *, int));
+static bool_t ypmatch_find __P((const char *, const char *, int, const char **,
+    int *));
+
+static bool_t
+ypmatch_add(map, key, keylen, val, vallen)
+       const char     *map;
+       const char     *key;
+       int             keylen;
+       char           *val;
+       int             vallen;
+{
+       struct ypmatch_ent *ep;
+       time_t t;
+
+       _DIAGASSERT(map != NULL);
+       _DIAGASSERT(key != NULL);
+       _DIAGASSERT(val != NULL);
+
+       (void)time(&t);
+
+       for (ep = ypmc; ep; ep = ep->next)
+               if (ep->expire_t < t)
+                       break;
+       if (ep == NULL) {
+               if ((ep = malloc(sizeof *ep)) == NULL)
+                       return 0;
+               (void)memset(ep, 0, sizeof *ep);
+               if (ypmc)
+                       ep->next = ypmc;
+               ypmc = ep;
+       }
+
+       if (ep->key) {
+               free(ep->key);
+               ep->key = NULL;
+       }
+       if (ep->val) {
+               free(ep->val);
+               ep->val = NULL;
+       }
+
+       if ((ep->key = malloc((size_t)keylen)) == NULL)
+               return 0;
+
+       if ((ep->val = malloc((size_t)vallen)) == NULL) {
+               free(ep->key);
+               ep->key = NULL;
+               return 0;
+       }
+
+       ep->keylen = keylen;
+       ep->vallen = vallen;
+
+       (void)memcpy(ep->key, key, (size_t)ep->keylen);
+       (void)memcpy(ep->val, val, (size_t)ep->vallen);
+
+       if (ep->map) {
+               if (strcmp(ep->map, map)) {
+                       free(ep->map);
+                       if ((ep->map = strdup(map)) == NULL)
+                               return 0;
+               }
+       } else {
+               if ((ep->map = strdup(map)) == NULL)
+                       return 0;
+       }
+
+       ep->expire_t = t + _yplib_cache;
+       return 1;
+}
+
+static bool_t
+ypmatch_find(map, key, keylen, val, vallen)
+       const char     *map;
+       const char     *key;
+       int             keylen;
+       const char    **val;
+       int            *vallen;
+{
+       struct ypmatch_ent *ep;
+       time_t          t;
+
+       _DIAGASSERT(map != NULL);
+       _DIAGASSERT(key != NULL);
+       _DIAGASSERT(val != NULL);
+
+       if (ypmc == NULL)
+               return 0;
+
+       (void) time(&t);
+
+       for (ep = ypmc; ep; ep = ep->next) {
+               if (ep->keylen != keylen)
+                       continue;
+               if (strcmp(ep->map, map))
+                       continue;
+               if (memcmp(ep->key, key, (size_t)keylen))
+                       continue;
+               if (t > ep->expire_t)
+                       continue;
+
+               *val = ep->val;
+               *vallen = ep->vallen;
+               return 1;
+       }
+       return 0;
+}
+#endif
+
+int
+yp_match(indomain, inmap, inkey, inkeylen, outval, outvallen)
+       const char     *indomain;
+       const char     *inmap;
+       const char     *inkey;
+       int             inkeylen;
+       char          **outval;
+       int            *outvallen;
+{
+       struct dom_binding *ysd;
+       struct ypresp_val yprv;
+       struct ypreq_key yprk;
+       int r, nerrs = 0;
+
+       if (outval == NULL || outvallen == NULL)
+               return YPERR_BADARGS;
+       *outval = NULL;
+       *outvallen = 0;
+
+       if (_yp_invalid_domain(indomain))
+               return YPERR_BADARGS;
+       if (inmap == NULL || *inmap == '\0'
+           || strlen(inmap) > YPMAXMAP)
+               return YPERR_BADARGS;
+       if (inkey == NULL || inkeylen == 0)
+               return YPERR_BADARGS;
+
+again:
+       if (_yp_dobind(indomain, &ysd) != 0)
+               return YPERR_DOMAIN;
+
+#ifdef YPMATCHCACHE
+       if (!strcmp(_yp_domain, indomain) && ypmatch_find(inmap, inkey,
+                        inkeylen, &yprv.valdat.dptr, &yprv.valdat.dsize)) {
+               *outvallen = yprv.valdat.dsize;
+               if ((*outval = malloc((size_t)(*outvallen + 1))) == NULL)
+                       return YPERR_YPERR;
+               (void)memcpy(*outval, yprv.valdat.dptr, (size_t)*outvallen);
+               (*outval)[*outvallen] = '\0';
+               return 0;
+       }
+#endif
+
+       yprk.domain = indomain;
+       yprk.map = inmap;
+       yprk.keydat.dptr = __UNCONST(inkey);
+       yprk.keydat.dsize = inkeylen;
+
+       memset(&yprv, 0, sizeof yprv);
+
+       r = clnt_call(ysd->dom_client, (rpcproc_t)YPPROC_MATCH,
+                     (xdrproc_t)xdr_ypreq_key, &yprk,
+                     (xdrproc_t)xdr_ypresp_val, &yprv, 
+                     _yplib_timeout);
+       if (r != RPC_SUCCESS) {
+               if (++nerrs == _yplib_nerrs) {
+                       clnt_perror(ysd->dom_client, "yp_match: clnt_call");
+                       nerrs = 0;
+               }
+               ysd->dom_vers = -1;
+               goto again;
+       }
+       if (!(r = ypprot_err(yprv.status))) {
+               *outvallen = yprv.valdat.dsize;
+               if ((*outval = malloc((size_t)(*outvallen + 1))) == NULL)
+                       return YPERR_YPERR;
+               (void)memcpy(*outval, yprv.valdat.dptr, (size_t)*outvallen);
+               (*outval)[*outvallen] = '\0';
+#ifdef YPMATCHCACHE
+               if (strcmp(_yp_domain, indomain) == 0)
+                       if (!ypmatch_add(inmap, inkey, inkeylen,
+                                        *outval, *outvallen))
+                               r = YPERR_RESRC;
+#endif
+       }
+       xdr_free((xdrproc_t)xdr_ypresp_val, (char *)(void *)&yprv);
+       __yp_unbind(ysd);
+       if (r != 0) {
+               if (*outval) {
+                       free(*outval);
+                       *outval = NULL;
+               }
+       }
+       return r;
+}
diff --git a/lib/nbsd_libc/yp/yp_order.c b/lib/nbsd_libc/yp/yp_order.c
new file mode 100644 (file)
index 0000000..ad7d963
--- /dev/null
@@ -0,0 +1,99 @@
+/*     $NetBSD: yp_order.c,v 1.12 2003/12/10 12:06:25 agc Exp $         */
+
+/*
+ * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca>
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: yp_order.c,v 1.12 2003/12/10 12:06:25 agc Exp $");
+#endif
+
+#include "namespace.h"
+#include <string.h>
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+#include "local.h"
+
+extern struct timeval _yplib_timeout;
+extern int _yplib_nerrs;
+
+#ifdef __weak_alias
+__weak_alias(yp_order,_yp_order)
+#endif
+
+int
+yp_order(indomain, inmap, outorder)
+       const char     *indomain;
+       const char     *inmap;
+       int            *outorder;
+{
+       struct dom_binding *ysd;
+       struct ypresp_order ypro;
+       struct ypreq_nokey yprnk;
+       int r, nerrs = 0;
+
+       if (_yp_invalid_domain(indomain))
+               return YPERR_BADARGS;
+       if (inmap == NULL || *inmap == '\0'
+           || strlen(inmap) > YPMAXMAP)
+               return YPERR_BADARGS;
+       if (outorder == NULL)
+               return YPERR_BADARGS;
+
+again:
+       if (_yp_dobind(indomain, &ysd) != 0)
+               return YPERR_DOMAIN;
+
+       yprnk.domain = indomain;
+       yprnk.map = inmap;
+
+       (void)memset(&ypro, 0, sizeof ypro);
+
+       r = clnt_call(ysd->dom_client, (rpcproc_t)YPPROC_ORDER,
+                     (xdrproc_t)xdr_ypreq_nokey, &yprnk,
+                     (xdrproc_t)xdr_ypresp_order, &ypro, 
+                     _yplib_timeout);
+       if (r != RPC_SUCCESS) {
+               if (++nerrs == _yplib_nerrs) {
+                       clnt_perror(ysd->dom_client, "yp_order: clnt_call");
+                       nerrs = 0;
+               }
+               if (r == RPC_PROCUNAVAIL) {
+                       /* Case of NIS+ server in NIS compat mode */
+                       r = YPERR_YPERR;
+                       goto bail;
+               } 
+               ysd->dom_vers = -1;
+               goto again;
+       }
+       *outorder = ypro.ordernum;
+       xdr_free((xdrproc_t)xdr_ypresp_order, (char *)(void *)&ypro);
+       r = ypprot_err(ypro.status);
+bail:
+       __yp_unbind(ysd);
+       return r;
+}
diff --git a/lib/nbsd_libc/yp/ypclnt.3 b/lib/nbsd_libc/yp/ypclnt.3
new file mode 100644 (file)
index 0000000..a395477
--- /dev/null
@@ -0,0 +1,410 @@
+.\"    $NetBSD: ypclnt.3,v 1.24 2010/03/22 19:30:55 joerg Exp $
+.\"
+.\" Copyright (c) 1996 The NetBSD Foundation, Inc.
+.\" All rights reserved.
+.\"
+.\" This code is derived from software contributed to The NetBSD Foundation
+.\" by Jason R. Thorpe.
+.\"
+.\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+.\"
+.Dd May 21, 1997
+.Dt YPCLNT 3
+.Os
+.Sh NAME
+.Nm yp_all ,
+.Nm yp_bind ,
+.Nm yp_first ,
+.Nm yp_get_default_domain ,
+.Nm yp_master ,
+.Nm yp_match ,
+.Nm yp_next ,
+.Nm yp_order ,
+.Nm yp_unbind ,
+.Nm yperr_string ,
+.Nm ypprot_err
+.Nd Interface to the YP subsystem
+.Sh LIBRARY
+.Lb libc
+.Sh SYNOPSIS
+.In sys/types.h
+.In rpc/rpc.h
+.In rpcsvc/ypclnt.h
+.In rpcsvc/yp_prot.h
+.Ft int
+.Fn yp_all "const char *indomain" "const char *inmap" "struct ypall_callback *incallback"
+.Ft int
+.Fn yp_bind "const char *dom"
+.Ft int
+.Fn yp_first "const char *indomain" "const char *inmap" "char **outkey" "int *outkeylen" "char **outval" "int *outvallen"
+.Ft int
+.Fn yp_get_default_domain "char **outdomain"
+.Ft int
+.Fn yp_master "const char *indomain" "const char *inmap" "char **outname"
+.Ft int
+.Fn yp_match "const char *indomain" "const char *inmap" "const char *inkey" "int inkeylen" "char **outval" "int *outvallen"
+.Ft int
+.Fn yp_next "const char *indomain" "const char *inmap" "const char *inkey" "int inkeylen" "char **outkey" "int *outkeylen" "char **outval" "int *outvallen"
+.Ft int
+.Fn yp_order "const char *indomain" "const char *inmap" "int *outorder"
+.Ft void
+.Fn yp_unbind "const char *dom"
+.Ft char *
+.Fn yperr_string "int incode"
+.Ft int
+.Fn ypprot_err "unsigned int incode"
+.Sh DESCRIPTION
+The
+.Nm ypclnt
+suite provides an interface to the
+.Tn YP
+subsystem.
+For a general description of the
+.Tn YP
+subsystem, see
+.Xr yp 8 .
+.Pp
+For all functions, input values begin with
+.Pa in
+and output values begin with
+.Pa out .
+.Pp
+Any output values of type
+.Em char **
+should be the addresses of uninitialized character pointers.
+These values will be reset to the null pointer (unless the address
+itself is the null pointer, in which case the error
+.Er YPERR_BADARGS
+will be returned).
+If necessary,
+memory will be allocated by the
+.Tn YP
+client routines using
+.Fn malloc ,
+and the result will be stored in the appropriate output value.
+If the invocation of a
+.Tn YP
+client routine doesn't return an error,
+and an output value is not the null pointer, then this memory
+should be freed by the user when there is no additional need for
+the data stored there.
+For
+.Pa outkey
+and
+.Pa outval ,
+two extra bytes of memory are allocated for a
+.Ql \en
+and
+.Ql \e0 ,
+which are not
+reflected in the values of
+.Pa outkeylen
+or
+.Pa outvallen .
+.Pp
+All occurrences of
+.Pa indomain
+and
+.Pa inmap
+must be non-null, NUL-terminated strings.
+All input strings which also have
+a corresponding length parameter cannot be the null pointer unless the
+corresponding length value is zero.
+Such strings need not be NUL-terminated.
+.Pp
+All
+.Tn YP
+lookup calls (the functions
+.Fn yp_all ,
+.Fn yp_first ,
+.Fn yp_master ,
+.Fn yp_match ,
+.Fn yp_next ,
+.Fn yp_order )
+require a
+.Tn YP
+domain name and a
+.Tn YP
+map name.
+The default domain name may be obtained by calling
+.Fn yp_get_default_domain ,
+and should thus be used before all other
+.Tn YP
+calls in a client program.
+The value it places
+.Pa outdomain
+is suitable for use as the
+.Pa indomain
+parameter to all subsequent
+.Tn YP
+calls.
+.Pp
+In order for
+.Tn YP
+lookup calls to succeed, the client process must be bound
+to a
+.Tn YP
+server process.
+The client process need not explicitly bind to
+the server, as it happens automatically whenever a lookup occurs.
+The function
+.Fn yp_bind
+is provided for a backup strategy, e.g. a local file, when a
+.Tn YP
+server process is not available.
+Each binding uses one socket descriptor on the client
+process, which may be explicitly freed using
+.Fn yp_unbind ,
+which frees all per-process and per-node resources to bind the domain and
+marks the domain unbound.
+.Pp
+If, during a
+.Tn YP
+lookup, an RPC failure occurs, the domain used in the lookup
+is automatically marked unbound and the
+.Nm ypclnt
+layer retries the lookup as long as
+.Xr ypbind 8
+is running and either the client process cannot bind to a server for the domain
+specified in the lookup, or RPC requests to the
+.Tn YP
+server process fail.
+If an error is not RPC-related, one of the
+.Tn YP
+error codes described below
+is returned and control given back to the user code.
+.Pp
+The
+.Nm ypclnt
+suite provides the following functionality:
+.Bl -tag -width yp_match()xx
+.It Fn yp_match
+Provides the value associated with the given key.
+.It Fn yp_first
+Provides the first key-value pair from the given map in the named domain.
+.It Fn yp_next
+Provides the next key-value pair in the given map.
+To obtain the second pair,
+the
+.Pa inkey
+value should be the
+.Pa outkey
+value provided by the initial call to
+.Fn yp_first .
+In the general case, the next key-value pair may be obtained by using the
+.Pa outkey
+value from the previous call to
+.Fn yp_next
+as the value for
+.Pa inkey .
+.Pp
+Of course, the notions of
+.Dq first
+and
+.Dq next
+are particular to the
+type of
+.Tn YP
+map being accessed, and thus there is no guarantee of lexical order.
+The only guarantees provided with
+.Fn yp_first
+and
+.Fn yp_next ,
+providing that the same map on the same server is polled repeatedly until
+.Fn yp_next
+returns YPERR_NOMORE, are that all key-value pairs in that map will be accessed
+exactly once, and if the entire procedure is repeated, the order will be
+the same.
+.Pp
+If the server is heavily loaded or the server fails for some reason, the
+domain being used may become unbound.
+If this happens, and the client process re-binds, the retrieval rules
+will break: some entries may be seen twice, and others not at all.
+For this reason, the function
+.Fn yp_all
+provides a better solution for reading all of the entries in a particular map.
+.It Fn yp_all
+This function provides a way to transfer an entire map from
+the server to the client process with a single request.
+This transfer uses TCP, unlike all other functions in the
+.Nm ypclnt
+suite, which use UDP.
+The entire transaction occurs in a single RPC request-response.
+The third argument to this function provides a way to supply
+the name of a function to process each key-value pair in the map.
+.Fn yp_all
+returns after the entire transaction is complete, or the
+.Pa foreach
+function decides that it does not want any more key-value pairs.
+The third argument to
+.Fn yp_all
+is:
+.Bd -literal -offset indent
+struct ypall_callback *incallback {
+       int (*foreach)();
+       char *data;
+};
+.Ed
+.Pp
+The
+.Em char *data
+argument is an opaque pointer for use by the callback function.
+The
+.Pa foreach
+function should return non-zero when it no longer wishes to process
+key-value pairs, at which time
+.Fn yp_all
+returns a value of 0, and is called with the following arguments:
+.Pp
+.Bd -literal -offset indent
+int foreach (
+       int instatus,
+       char *inkey,
+       int inkeylen,
+       char *inval,
+       int invallen,
+       char *indata
+);
+.Ed
+.Pp
+Where:
+.Bl -tag -width "inkey, inval"
+.It Fa instatus
+Holds one of the return status values described in
+.In rpcsvc/yp_prot.h :
+see
+.Fn ypprot_err
+below for a function that will translate
+.Tn YP
+protocol errors into a
+.Nm ypclnt
+layer error code as described in
+.In rpcsvc/ypclnt.h .
+.It Fa inkey, inval
+The key and value arguments are somewhat different here than described
+above.
+In this case, the memory pointed to by
+.Fa inkey
+and
+.Fa inval
+is private to
+.Fn yp_all ,
+and is overwritten with each subsequent key-value pair, thus the
+.Pa foreach
+function should do something useful with the contents of that memory during
+each iteration.
+If the key-value pairs are not terminated with either
+.Ql \en
+or
+.Ql \e0
+in the map, then they will not be terminated as such when given to the
+.Pa foreach
+function, either.
+.It Fa indata
+This is the contents of the
+.Pa incallback-\*[Gt]data
+element of the callback structure.
+It is provided as a means to share state between the
+.Pa foreach
+function and the user code.
+Its use is completely optional: cast it to
+something useful or simply ignore it.
+.El
+.It Fn yp_order
+Returns the order number for a map.
+.It Fn yp_master
+Returns the hostname for the machine on which the master
+.Tn YP
+server process for
+a map is running.
+.It Fn yperr_string
+Returns a pointer to a NUL-terminated error string that does not contain a
+.Ql \&.
+or
+.Ql \en .
+.It Fn ypprot_err
+Converts a
+.Tn YP
+protocol error code to a
+.Nm ypclnt
+error code suitable for
+.Fn yperr_string .
+.El
+.Sh RETURN VALUES
+All functions in the
+.Nm ypclnt
+suite which are of type
+.Em int
+return 0 upon success or one of the following error codes upon failure:
+.Bl -tag -width "YPERR_BADARGS   "
+.It Bq Er YPERR_BADARGS
+The passed arguments to the function are invalid.
+.It Bq Er YPERR_BADDB
+The
+.Tn YP
+map that was polled is defective.
+.It Bq Er YPERR_DOMAIN
+Client process cannot bind to server on this
+.Tn YP
+domain.
+.It Bq Er YPERR_KEY
+The key passed does not exist.
+.It Bq Er YPERR_MAP
+There is no such map in the server's domain.
+.It Bq Er YPERR_DOM
+The local
+.Tn YP
+domain is not set.
+.It Bq Er YPERR_NOMORE
+There are no more records in the queried map.
+.It Bq Er YPERR_PMAP
+Cannot communicate with portmapper (see
+.Xr rpcbind 8 ) .
+.It Bq Er YPERR_RESRC
+A resource allocation failure occurred.
+.It Bq Er YPERR_RPC
+An RPC failure has occurred.
+The domain has been marked unbound.
+.It Bq Er YPERR_VERS
+Client/server version mismatch.
+If the server is running version 1 of the
+.Tn YP
+protocol,
+.Fn yp_all
+functionality does not exist.
+.It Bq Er YPERR_BIND
+Cannot communicate with
+.Xr ypbind 8 .
+.It Bq Er YPERR_YPERR
+An internal server or client error has occurred.
+.It Bq Er YPERR_YPSERV
+The client cannot communicate with the
+.Tn YP
+server process.
+.El
+.Sh SEE ALSO
+.Xr malloc 3 ,
+.Xr yp 8 ,
+.Xr ypbind 8 ,
+.Xr ypserv 8
+.Sh AUTHORS
+.An Theo De Raadt
diff --git a/lib/nbsd_libc/yp/yperr_string.c b/lib/nbsd_libc/yp/yperr_string.c
new file mode 100644 (file)
index 0000000..6604696
--- /dev/null
@@ -0,0 +1,91 @@
+/*     $NetBSD: yperr_string.c,v 1.7 2005/11/29 03:12:01 christos Exp $         */
+
+/*
+ * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca>
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: yperr_string.c,v 1.7 2005/11/29 03:12:01 christos Exp $");
+#endif
+
+#include "namespace.h"
+#include <stdio.h>
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+
+#ifdef __weak_alias
+__weak_alias(yperr_string,_yperr_string)
+#endif
+
+char *
+yperr_string(incode)
+       int             incode;
+{
+       static char     err[80];
+
+       switch (incode) {
+       case 0:
+               return __UNCONST("Success");
+       case YPERR_BADARGS:
+               return __UNCONST("Request arguments bad");
+       case YPERR_RPC:
+               return __UNCONST("RPC failure");
+       case YPERR_DOMAIN:
+               return __UNCONST(
+                   "Can't bind to server which serves this domain");
+       case YPERR_MAP:
+               return __UNCONST("No such map in server's domain");
+       case YPERR_KEY:
+               return __UNCONST("No such key in map");
+       case YPERR_YPERR:
+               return __UNCONST("YP server error");
+       case YPERR_RESRC:
+               return __UNCONST("Local resource allocation failure");
+       case YPERR_NOMORE:
+               return __UNCONST("No more records in map database");
+       case YPERR_PMAP:
+               return __UNCONST("Can't communicate with portmapper");
+       case YPERR_YPBIND:
+               return __UNCONST("Can't communicate with ypbind");
+       case YPERR_YPSERV:
+               return __UNCONST("Can't communicate with ypserv");
+       case YPERR_NODOM:
+               return __UNCONST("Local domain name not set");
+       case YPERR_BADDB:
+               return __UNCONST("Server data base is bad");
+       case YPERR_VERS:
+               return __UNCONST(
+                   "YP server version mismatch - server can't supply service."
+                   );
+       case YPERR_ACCESS:
+               return __UNCONST("Access violation");
+       case YPERR_BUSY:
+               return __UNCONST("Database is busy");
+       }
+       (void) snprintf(err, sizeof(err), "YP unknown error %d\n", incode);
+       return err;
+}
diff --git a/lib/nbsd_libc/yp/yplib.c b/lib/nbsd_libc/yp/yplib.c
new file mode 100644 (file)
index 0000000..ea92f50
--- /dev/null
@@ -0,0 +1,368 @@
+/*     $NetBSD: yplib.c,v 1.43 2006/11/03 20:18:49 christos Exp $       */
+
+/*
+ * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca>
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: yplib.c,v 1.43 2006/11/03 20:18:49 christos Exp $");
+#endif
+
+#include "namespace.h"
+#include "reentrant.h"
+
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/file.h>
+#include <sys/uio.h>
+
+#include <arpa/nameser.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <rpc/rpc.h>
+#include <rpc/xdr.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+#include "local.h"
+
+#define BINDINGDIR     "/var/yp/binding"
+#define YPBINDLOCK     "/var/run/ypbind.lock"
+
+struct dom_binding *_ypbindlist;
+char _yp_domain[MAXHOSTNAMELEN];
+
+#define YPLIB_TIMEOUT          10
+#define YPLIB_RPC_RETRIES      4
+
+struct timeval _yplib_timeout = { YPLIB_TIMEOUT, 0 };
+struct timeval _yplib_rpc_timeout = { YPLIB_TIMEOUT / YPLIB_RPC_RETRIES,
+       1000000 * (YPLIB_TIMEOUT % YPLIB_RPC_RETRIES) / YPLIB_RPC_RETRIES };
+int _yplib_nerrs = 5;
+
+#ifdef __weak_alias
+__weak_alias(yp_bind, _yp_bind)
+__weak_alias(yp_unbind, _yp_unbind)
+__weak_alias(yp_get_default_domain, _yp_get_default_domain)
+#endif
+
+#ifdef _REENTRANT
+static         mutex_t                 _ypmutex = MUTEX_INITIALIZER;
+#define YPLOCK()               mutex_lock(&_ypmutex)
+#define YPUNLOCK()             mutex_unlock(&_ypmutex)
+#else
+#define YPLOCK()
+#define YPUNLOCK()
+#endif
+
+int
+_yp_dobind(dom, ypdb)
+       const char     *dom;
+       struct dom_binding **ypdb;
+{
+       static int      pid = -1;
+       char            path[MAXPATHLEN];
+       struct dom_binding *ysd, *ysd2;
+       struct ypbind_resp ypbr;
+       struct sockaddr_in clnt_sin;
+       int             clnt_sock, fd, gpid;
+       CLIENT         *client;
+       int             new = 0;
+       int             nerrs = 0;
+       ssize_t         r;
+
+       if (dom == NULL || *dom == '\0')
+               return YPERR_BADARGS;
+
+       /*
+        * test if YP is running or not
+        */
+       if ((fd = open(YPBINDLOCK, O_RDONLY)) == -1)
+               return YPERR_YPBIND;
+       if (!(flock(fd, LOCK_EX | LOCK_NB) == -1 && errno == EWOULDBLOCK)) {
+               (void)close(fd);
+               return YPERR_YPBIND;
+       }
+       (void)close(fd);
+
+       gpid = getpid();
+       if (!(pid == -1 || pid == gpid)) {
+               ysd = _ypbindlist;
+               while (ysd) {
+                       if (ysd->dom_client)
+                               clnt_destroy(ysd->dom_client);
+                       ysd2 = ysd->dom_pnext;
+                       free(ysd);
+                       ysd = ysd2;
+               }
+               _ypbindlist = NULL;
+       }
+       pid = gpid;
+
+       if (ypdb != NULL)
+               *ypdb = NULL;
+
+       for (ysd = _ypbindlist; ysd; ysd = ysd->dom_pnext)
+               if (strcmp(dom, ysd->dom_domain) == 0)
+                       break;
+       if (ysd == NULL) {
+               if ((ysd = malloc(sizeof *ysd)) == NULL)
+                       return YPERR_YPERR;
+               (void)memset(ysd, 0, sizeof *ysd);
+               ysd->dom_socket = -1;
+               ysd->dom_vers = 0;
+               new = 1;
+       }
+again:
+       if (ysd->dom_vers == 0) {
+               (void) snprintf(path, sizeof(path), "%s/%s.%d",
+                               BINDINGDIR, dom, 2);
+               if ((fd = open(path, O_RDONLY)) == -1) {
+                       /*
+                        * no binding file, YP is dead, or not yet fully
+                        * alive.
+                        */
+                       goto trynet;
+               }
+               if (flock(fd, LOCK_EX | LOCK_NB) == -1 &&
+                   errno == EWOULDBLOCK) {
+                       struct iovec    iov[2];
+                       struct ypbind_resp ybr;
+                       u_short         ypb_port;
+                       struct ypbind_binding *bn;
+
+                       iov[0].iov_base = &ypb_port;
+                       iov[0].iov_len = sizeof ypb_port;
+                       iov[1].iov_base = &ybr;
+                       iov[1].iov_len = sizeof ybr;
+
+                       r = readv(fd, iov, 2);
+                       if (r != (ssize_t)(iov[0].iov_len + iov[1].iov_len)) {
+                               (void)close(fd);
+                               ysd->dom_vers = -1;
+                               goto again;
+                       }
+                       (void)memset(&ysd->dom_server_addr, 0,
+                                    sizeof ysd->dom_server_addr);
+                       ysd->dom_server_addr.sin_len =
+                               sizeof(struct sockaddr_in);
+                       ysd->dom_server_addr.sin_family = AF_INET;
+                       bn = &ybr.ypbind_respbody.ypbind_bindinfo;
+                       ysd->dom_server_addr.sin_port =
+                               bn->ypbind_binding_port;
+                               
+                       ysd->dom_server_addr.sin_addr =
+                               bn->ypbind_binding_addr;
+
+                       ysd->dom_server_port = ysd->dom_server_addr.sin_port;
+                       (void)close(fd);
+                       goto gotit;
+               } else {
+                       /* no lock on binding file, YP is dead. */
+                       (void)close(fd);
+                       if (new)
+                               free(ysd);
+                       return YPERR_YPBIND;
+               }
+       }
+trynet:
+       if (ysd->dom_vers == -1 || ysd->dom_vers == 0) {
+               struct ypbind_binding *bn;
+               (void)memset(&clnt_sin, 0, sizeof clnt_sin);
+               clnt_sin.sin_len = sizeof(struct sockaddr_in);
+               clnt_sin.sin_family = AF_INET;
+               clnt_sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+
+               clnt_sock = RPC_ANYSOCK;
+               client = clnttcp_create(&clnt_sin, YPBINDPROG, YPBINDVERS,
+                                       &clnt_sock, 0, 0);
+               if (client == NULL) {
+                       clnt_pcreateerror("clnttcp_create");
+                       if (new)
+                               free(ysd);
+                       return YPERR_YPBIND;
+               }
+               r = clnt_call(client, (rpcproc_t)YPBINDPROC_DOMAIN,
+                   (xdrproc_t)xdr_ypdomain_wrap_string, &dom,
+                   (xdrproc_t)xdr_ypbind_resp, &ypbr, _yplib_timeout);
+               if (r != RPC_SUCCESS) {
+                       if (new == 0 && ++nerrs == _yplib_nerrs) {
+                               nerrs = 0;
+                               fprintf(stderr,
+                   "YP server for domain %s not responding, still trying\n",
+                                   dom);
+                       }
+                       clnt_destroy(client);
+                       ysd->dom_vers = -1;
+                       goto again;
+               }
+               clnt_destroy(client);
+
+               (void)memset(&ysd->dom_server_addr, 0, 
+                            sizeof ysd->dom_server_addr);
+               ysd->dom_server_addr.sin_len = sizeof(struct sockaddr_in);
+               ysd->dom_server_addr.sin_family = AF_INET;
+               bn = &ypbr.ypbind_respbody.ypbind_bindinfo;
+               ysd->dom_server_addr.sin_port =
+                       bn->ypbind_binding_port;
+               ysd->dom_server_addr.sin_addr.s_addr =
+                       bn->ypbind_binding_addr.s_addr;
+               ysd->dom_server_port =
+                       bn->ypbind_binding_port;
+gotit:
+               ysd->dom_vers = YPVERS;
+               (void)strlcpy(ysd->dom_domain, dom, sizeof(ysd->dom_domain));
+       }
+       if (ysd->dom_client)
+               clnt_destroy(ysd->dom_client);
+       ysd->dom_socket = RPC_ANYSOCK;
+       ysd->dom_client = clntudp_create(&ysd->dom_server_addr,
+           YPPROG, YPVERS, _yplib_rpc_timeout, &ysd->dom_socket);
+       if (ysd->dom_client == NULL) {
+               clnt_pcreateerror("clntudp_create");
+               ysd->dom_vers = -1;
+               goto again;
+       }
+       if (fcntl(ysd->dom_socket, F_SETFD, FD_CLOEXEC) == -1)
+               perror("fcntl: F_SETFD");
+
+       if (new) {
+               ysd->dom_pnext = _ypbindlist;
+               _ypbindlist = ysd;
+       }
+       if (ypdb != NULL)
+               *ypdb = ysd;
+       return 0;
+}
+
+void
+__yp_unbind(ypb)
+       struct dom_binding *ypb;
+{
+
+       _DIAGASSERT(ypb != NULL);
+
+       clnt_destroy(ypb->dom_client);
+       ypb->dom_client = NULL;
+       ypb->dom_socket = -1;
+}
+
+int
+yp_bind(dom)
+       const char     *dom;
+{
+       if (_yp_invalid_domain(dom))
+               return YPERR_BADARGS;
+
+       return _yp_dobind(dom, NULL);
+}
+
+void
+yp_unbind(dom)
+       const char     *dom;
+{
+       struct dom_binding *ypb, *ypbp;
+
+       if (_yp_invalid_domain(dom))
+               return;
+
+       ypbp = NULL;
+       for (ypb = _ypbindlist; ypb; ypb = ypb->dom_pnext) {
+               if (strcmp(dom, ypb->dom_domain) == 0) {
+                       clnt_destroy(ypb->dom_client);
+                       if (ypbp)
+                               ypbp->dom_pnext = ypb->dom_pnext;
+                       else
+                               _ypbindlist = ypb->dom_pnext;
+                       free(ypb);
+                       return;
+               }
+               ypbp = ypb;
+       }
+       return;
+}
+
+int
+yp_get_default_domain(domp)
+       char          **domp;
+{
+       if (domp == NULL)
+               return YPERR_BADARGS;
+       *domp = NULL;
+       if (_yp_domain[0] == '\0')
+               if (getdomainname(_yp_domain, sizeof _yp_domain))
+                       return YPERR_NODOM;
+       *domp = _yp_domain;
+       return 0;
+}
+
+int
+_yp_check(dom)
+       char          **dom;
+{
+       char           *unused;
+       int             good;
+
+       YPLOCK();
+
+       if (_yp_domain[0] == '\0')
+               if (yp_get_default_domain(&unused)) {
+                       good = 0;
+                       goto done;
+               }
+       if (dom)
+               *dom = _yp_domain;
+
+       good = yp_bind(_yp_domain) == 0;
+done:
+       YPUNLOCK();
+       return good;
+}
+
+/*
+ * _yp_invalid_domain: check if given domainname isn't legal.
+ * returns non-zero if invalid
+ */
+int
+_yp_invalid_domain(dom)
+       const char *dom;
+{
+       if (dom == NULL || *dom == '\0')
+               return 1;
+
+       if (strlen(dom) > YPMAXDOMAIN)
+               return 1;
+
+       if (strchr(dom, '/') != NULL)
+               return 1;
+
+       return 0;
+}
diff --git a/lib/nbsd_libc/yp/ypprot_err.c b/lib/nbsd_libc/yp/ypprot_err.c
new file mode 100644 (file)
index 0000000..84cb119
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: ypprot_err.c,v 1.5 2003/12/10 12:06:25 agc Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca>
+ * 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 ``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 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 <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: ypprot_err.c,v 1.5 2003/12/10 12:06:25 agc Exp $");
+#endif
+
+#include "namespace.h"
+#include <rpc/rpc.h>
+#include <rpcsvc/yp_prot.h>
+#include <rpcsvc/ypclnt.h>
+
+#ifdef __weak_alias
+__weak_alias(ypprot_err,_ypprot_err)
+#endif
+
+int
+ypprot_err(incode)
+       unsigned int    incode;
+{
+       switch (incode) {
+       case YP_TRUE:
+               return 0;
+       case YP_FALSE:
+               return YPERR_YPBIND;
+       case YP_NOMORE:
+               return YPERR_NOMORE;
+       case YP_NOMAP:
+               return YPERR_MAP;
+       case YP_NODOM:
+               return YPERR_NODOM;
+       case YP_NOKEY:
+               return YPERR_KEY;
+       case YP_BADOP:
+               return YPERR_YPERR;
+       case YP_BADDB:
+               return YPERR_BADDB;
+       case YP_YPERR:
+               return YPERR_YPERR;
+       case YP_BADARGS:
+               return YPERR_BADARGS;
+       case YP_VERS:
+               return YPERR_VERS;
+       }
+       return YPERR_YPERR;
+}
diff --git a/nbsd_include/Makefile b/nbsd_include/Makefile
new file mode 100644 (file)
index 0000000..bb2f8ca
--- /dev/null
@@ -0,0 +1,49 @@
+#      $NetBSD: Makefile,v 1.133 2010/07/31 21:47:53 joerg Exp $
+#      @(#)Makefile    8.2 (Berkeley) 1/4/94
+
+# Doing a make includes builds /usr/include
+
+NOOBJ=         # defined
+
+# Missing: mp.h
+
+INCS=  a.out.h aio.h ar.h assert.h atomic.h \
+       bitstring.h bm.h cdbr.h cdbw.h complex.h cpio.h ctype.h \
+       db.h dirent.h disktab.h dlfcn.h err.h errno.h fenv.h fmtmsg.h fnmatch.h \
+       fstab.h fts.h ftw.h getopt.h glob.h grp.h ifaddrs.h iconv.h \
+       inttypes.h iso646.h kvm.h langinfo.h libgen.h \
+       limits.h link.h link_aout.h link_elf.h locale.h \
+       login_cap.h lwp.h malloc.h math.h md2.h \
+       memory.h mntopts.h monetary.h mpool.h mqueue.h \
+       ndbm.h netconfig.h netdb.h netgroup.h nlist.h nl_types.h nsswitch.h \
+       paths.h pwd.h randomid.h ranlib.h re_comp.h regex.h regexp.h \
+       resolv.h res_update.h rmt.h sched.h search.h semaphore.h setjmp.h \
+       sgtty.h signal.h stab.h stdbool.h stddef.h stdio.h stdlib.h string.h \
+       strings.h stringlist.h struct.h sysexits.h tar.h time.h \
+       ttyent.h tzfile.h ucontext.h ulimit.h unistd.h util.h utime.h utmp.h \
+       utmpx.h uuid.h varargs.h vis.h wchar.h wctype.h wordexp.h
+INCS+= arpa/ftp.h arpa/inet.h arpa/nameser.h arpa/nameser_compat.h \
+       arpa/telnet.h arpa/tftp.h
+INCS+= protocols/dumprestore.h protocols/routed.h protocols/rwhod.h \
+       protocols/talkd.h protocols/timed.h
+
+INCS+= hesiod.h
+
+INCS+= rpcsvc/yp_prot.h rpcsvc/ypclnt.h
+
+INCS+=  ssp/ssp.h ssp/stdio.h ssp/string.h ssp/strings.h ssp/unistd.h
+
+.if (${MACHINE_ARCH} != "vax")
+INCS+= ieeefp.h
+.endif
+
+.include <bsd.own.mk>
+
+
+INCSDIR=       /usr/include
+
+SUBDIR=                rpc
+SUBDIR+=       ../common/include/prop
+
+.include <bsd.prog.mk>
+.include <bsd.subdir.mk>
diff --git a/nbsd_include/a.out.h b/nbsd_include/a.out.h
new file mode 100644 (file)
index 0000000..325cf4b
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: a.out.h,v 1.20 2009/08/16 17:12:47 pgoyette Exp $      */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ *
+ *     @(#)a.out.h     8.1 (Berkeley) 6/2/93
+ */
+
+/*-
+ * Copyright (c) 1993 Theo de Raadt.  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 ``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 BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROUREMENT 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.out.h     8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef        _AOUT_H_
+#define        _AOUT_H_
+
+#include <sys/exec_aout.h>
+
+#define        _AOUT_INCLUDE_
+#include <nlist.h>
+
+#endif /* !_AOUT_H_ */
diff --git a/nbsd_include/aio.h b/nbsd_include/aio.h
new file mode 100644 (file)
index 0000000..326ca63
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: aio.h,v 1.7 2009/01/13 15:11:09 christos Exp $ */
+
+/*
+ * Copyright (c) 2007, Mindaugas Rasiukevicius <rmind at NetBSD org>
+ * 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.
+ */
+
+#ifndef        _AIO_H_
+#define        _AIO_H_
+
+#include <fcntl.h>
+#include <signal.h>
+#include <time.h>
+
+#include <sys/cdefs.h>
+#include <sys/signal.h>
+
+#include <sys/aio.h>
+
+__BEGIN_DECLS
+int    aio_cancel(int, struct aiocb *);
+int    aio_error(const struct aiocb *);
+int    aio_fsync(int, struct aiocb *);
+int    aio_read(struct aiocb *);
+ssize_t        aio_return(struct aiocb *);
+#ifndef __LIBC12_SOURCE__
+int    aio_suspend(const struct aiocb * const [], int,
+    const struct timespec *) __RENAME(__aio_suspend50);
+#endif
+int    aio_write(struct aiocb *);
+int    lio_listio(int, struct aiocb * const * __restrict,
+                   int, struct sigevent * __restrict);
+__END_DECLS
+
+#endif /* _AIO_H_ */
diff --git a/nbsd_include/ar.h b/nbsd_include/ar.h
new file mode 100644 (file)
index 0000000..37d7347
--- /dev/null
@@ -0,0 +1,65 @@
+/*     $NetBSD: ar.h,v 1.5 2003/08/07 09:44:09 agc Exp $       */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, Inc.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Hugh Smith at The University of Guelph.
+ *
+ * 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. 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.
+ *
+ *     @(#)ar.h        8.2 (Berkeley) 1/21/94
+ */
+
+#ifndef _AR_H_
+#define        _AR_H_
+
+/* Pre-4BSD archives had these magic numbers in them. */
+#define        OARMAG1 0177555
+#define        OARMAG2 0177545
+
+#define        ARMAG           "!<arch>\n"     /* ar "magic number" */
+#define        SARMAG          8               /* strlen(ARMAG); */
+
+#define        AR_EFMT1        "#1/"           /* extended format #1 */
+
+struct ar_hdr {
+       char ar_name[16];               /* name */
+       char ar_date[12];               /* modification time */
+       char ar_uid[6];                 /* user id */
+       char ar_gid[6];                 /* group id */
+       char ar_mode[8];                /* octal file permissions */
+       char ar_size[10];               /* size in bytes */
+#define        ARFMAG  "`\n"
+       char ar_fmag[2];                /* consistency check */
+};
+
+#endif /* !_AR_H_ */
diff --git a/nbsd_include/arpa/ftp.h b/nbsd_include/arpa/ftp.h
new file mode 100644 (file)
index 0000000..544e530
--- /dev/null
@@ -0,0 +1,107 @@
+/*     $NetBSD: ftp.h,v 1.6 2003/08/07 09:44:12 agc Exp $      */
+
+/*
+ * Copyright (c) 1983, 1989, 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.
+ * 3. 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.
+ *
+ *     @(#)ftp.h       8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _ARPA_FTP_H_
+#define        _ARPA_FTP_H_
+
+/* Definitions for FTP; see RFC-765. */
+
+/*
+ * Reply codes.
+ */
+#define PRELIM         1       /* positive preliminary */
+#define COMPLETE       2       /* positive completion */
+#define CONTINUE       3       /* positive intermediate */
+#define TRANSIENT      4       /* transient negative completion */
+#define ERROR          5       /* permanent negative completion */
+
+/*
+ * Type codes
+ */
+#define        TYPE_A          1       /* ASCII */
+#define        TYPE_E          2       /* EBCDIC */
+#define        TYPE_I          3       /* image */
+#define        TYPE_L          4       /* local byte size */
+
+#ifdef FTP_NAMES
+char *typenames[] =  {"0", "ASCII", "EBCDIC", "Image", "Local" };
+#endif
+
+/*
+ * Form codes
+ */
+#define        FORM_N          1       /* non-print */
+#define        FORM_T          2       /* telnet format effectors */
+#define        FORM_C          3       /* carriage control (ASA) */
+#ifdef FTP_NAMES
+char *formnames[] =  {"0", "Nonprint", "Telnet", "Carriage-control" };
+#endif
+
+/*
+ * Structure codes
+ */
+#define        STRU_F          1       /* file (no record structure) */
+#define        STRU_R          2       /* record structure */
+#define        STRU_P          3       /* page structure */
+#ifdef FTP_NAMES
+char *strunames[] =  {"0", "File", "Record", "Page" };
+#endif
+
+/*
+ * Mode types
+ */
+#define        MODE_S          1       /* stream */
+#define        MODE_B          2       /* block */
+#define        MODE_C          3       /* compressed */
+#ifdef FTP_NAMES
+char *modenames[] =  {"0", "Stream", "Block", "Compressed" };
+#endif
+
+/*
+ * Record Tokens
+ */
+#define        REC_ESC         '\377'  /* Record-mode Escape */
+#define        REC_EOR         '\001'  /* Record-mode End-of-Record */
+#define REC_EOF                '\002'  /* Record-mode End-of-File */
+
+/*
+ * Block Header
+ */
+#define        BLK_EOR         0x80    /* Block is End-of-Record */
+#define        BLK_EOF         0x40    /* Block is End-of-File */
+#define BLK_ERRORS     0x20    /* Block is suspected of containing errors */
+#define        BLK_RESTART     0x10    /* Block is Restart Marker */
+
+#define        BLK_BYTECOUNT   2       /* Bytes in this block */
+
+#endif /* _ARPA_FTP_H_ */
diff --git a/nbsd_include/arpa/inet.h b/nbsd_include/arpa/inet.h
new file mode 100644 (file)
index 0000000..0f2e9f2
--- /dev/null
@@ -0,0 +1,105 @@
+/*     $NetBSD: inet.h,v 1.24 2008/06/21 20:12:49 christos Exp $       */
+
+/*
+ * ++Copyright++ 1983, 1993
+ * -
+ * 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.
+ * 3. 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.
+ * -
+ * Portions Copyright (c) 1993 by Digital Equipment Corporation.
+ * 
+ * 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, and that
+ * the name of Digital Equipment Corporation not be used in advertising or
+ * publicity pertaining to distribution of the document or software without
+ * specific, written prior permission.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
+ * CORPORATION 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.
+ * -
+ * --Copyright--
+ */
+
+/*%
+ *     @(#)inet.h      8.1 (Berkeley) 6/2/93
+ *     Id: inet.h,v 1.3 2005/04/27 04:56:16 sra Exp
+ */
+
+#ifndef _ARPA_INET_H_
+#define        _ARPA_INET_H_
+
+/* External definitions for functions in inet(3) */
+
+#include <sys/ansi.h>
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <sys/types.h>
+
+#include <netinet/in.h>
+
+#if (_POSIX_C_SOURCE - 0) >= 200112L || (_XOPEN_SOURCE - 0) >= 520 || \
+    defined(_NETBSD_SOURCE)
+#ifndef socklen_t
+typedef __socklen_t    socklen_t;
+#define socklen_t      __socklen_t
+#endif
+#endif /* _POSIX_C_SOURCE >= 200112 || XOPEN_SOURCE >= 520 || _NETBSD_SOURCE */
+
+__BEGIN_DECLS
+in_addr_t       inet_addr(const char *);
+in_addr_t       inet_lnaof(struct in_addr);
+struct in_addr  inet_makeaddr(in_addr_t, in_addr_t);
+in_addr_t       inet_netof(struct in_addr);
+in_addr_t       inet_network(const char *);
+char           *inet_ntoa(struct in_addr);
+#if (_POSIX_C_SOURCE - 0) >= 200112L || (_XOPEN_SOURCE - 0) >= 520 || \
+    defined(_NETBSD_SOURCE)
+const char     *inet_ntop(int, const void * __restrict,
+                               char * __restrict, socklen_t);
+int             inet_pton(int, const char * __restrict,
+                               void * __restrict);
+#endif
+#if defined(_NETBSD_SOURCE)
+int             inet_aton(const char *, struct in_addr *);
+char *          inet_neta(u_long, char *, size_t);
+char           *inet_net_ntop(int, const void *, int, char *, size_t);
+int             inet_net_pton(int, const char *, void *, size_t);
+char           *inet_cidr_ntop(int, const void *, int, char *, size_t);
+int             inet_cidr_pton(int, const char *, void *, int *);
+u_int           inet_nsap_addr(const char *, u_char *, int);
+char           *inet_nsap_ntoa(int, const u_char *, char *);
+#endif
+__END_DECLS
+
+#endif /* _ARPA_INET_H_ */
diff --git a/nbsd_include/arpa/nameser.h b/nbsd_include/arpa/nameser.h
new file mode 100644 (file)
index 0000000..1fcdbb9
--- /dev/null
@@ -0,0 +1,681 @@
+/*     $NetBSD: nameser.h,v 1.25 2009/04/12 17:07:34 christos Exp $    */
+
+/*
+ * Portions Copyright (C) 2004, 2005, 2008, 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (C) 1996-2003  Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and/or 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 ISC DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/*
+ * Copyright (c) 1983, 1989, 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.
+ * 3. 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.
+ */
+
+/*
+ *     Id: nameser.h,v 1.16 2009/03/03 01:52:48 each Exp
+ */
+
+#ifndef _ARPA_NAMESER_H_
+#define _ARPA_NAMESER_H_
+
+#define BIND_4_COMPAT
+
+#include <sys/param.h>
+#if (!defined(BSD)) || (BSD < 199306)
+# include <sys/bitypes.h>
+#else
+# include <sys/types.h>
+#endif
+#include <sys/cdefs.h>
+
+/*%
+ * Revision information.  This is the release date in YYYYMMDD format.
+ * It can change every day so the right thing to do with it is use it
+ * in preprocessor commands such as "#if (__NAMESER > 19931104)".  Do not
+ * compare for equality; rather, use it to determine whether your libbind.a
+ * contains a new enough lib/nameser/ to support the feature you need.
+ */
+
+#define __NAMESER      20090302        /*%< New interface version stamp. */
+/*
+ * Define constants based on RFC0883, RFC1034, RFC 1035
+ */
+#define NS_PACKETSZ    512     /*%< default UDP packet size */
+#define NS_MAXDNAME    1025    /*%< maximum domain name (presentation format)*/
+#define NS_MAXMSG      65535   /*%< maximum message size */
+#define NS_MAXCDNAME   255     /*%< maximum compressed domain name */
+#define NS_MAXLABEL    63      /*%< maximum length of domain label */
+#define NS_MAXLABELS   128     /*%< theoretical max #/labels per domain name */
+#define NS_MAXNNAME    256     /*%< maximum uncompressed (binary) domain name*/
+#define        NS_MAXPADDR     (sizeof "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
+#define NS_HFIXEDSZ    12      /*%< #/bytes of fixed data in header */
+#define NS_QFIXEDSZ    4       /*%< #/bytes of fixed data in query */
+#define NS_RRFIXEDSZ   10      /*%< #/bytes of fixed data in r record */
+#define NS_INT32SZ     4       /*%< #/bytes of data in a uint32_t */
+#define NS_INT16SZ     2       /*%< #/bytes of data in a uint16_t */
+#define NS_INT8SZ      1       /*%< #/bytes of data in a u_int8_t */
+#define NS_INADDRSZ    4       /*%< IPv4 T_A */
+#define NS_IN6ADDRSZ   16      /*%< IPv6 T_AAAA */
+#define NS_CMPRSFLGS   0xc0    /*%< Flag bits indicating name compression. */
+#define NS_DEFAULTPORT 53      /*%< For both TCP and UDP. */
+
+/*
+ * These can be expanded with synonyms, just keep ns_parse.c:ns_parserecord()
+ * in synch with it.
+ */
+typedef enum __ns_sect {
+       ns_s_qd = 0,            /*%< Query: Question. */
+       ns_s_zn = 0,            /*%< Update: Zone. */
+       ns_s_an = 1,            /*%< Query: Answer. */
+       ns_s_pr = 1,            /*%< Update: Prerequisites. */
+       ns_s_ns = 2,            /*%< Query: Name servers. */
+       ns_s_ud = 2,            /*%< Update: Update. */
+       ns_s_ar = 3,            /*%< Query|Update: Additional records. */
+       ns_s_max = 4
+} ns_sect;
+
+/*%
+ * Network name (compressed or not) type.  Equivilent to a pointer when used
+ * in a function prototype.  Can be const'd.
+ */
+typedef u_char ns_nname[NS_MAXNNAME];
+typedef const u_char *ns_nname_ct;
+typedef u_char *ns_nname_t;
+
+struct ns_namemap { ns_nname_ct base; int len; };
+typedef struct ns_namemap *ns_namemap_t;
+typedef const struct ns_namemap *ns_namemap_ct;
+
+/*%
+ * This is a message handle.  It is caller allocated and has no dynamic data.
+ * This structure is intended to be opaque to all but ns_parse.c, thus the
+ * leading _'s on the member names.  Use the accessor functions, not the _'s.
+ */
+typedef struct __ns_msg {
+       const u_char    *_msg, *_eom;
+       uint16_t        _id, _flags, _counts[ns_s_max];
+       const u_char    *_sections[ns_s_max];
+       ns_sect         _sect;
+       int             _rrnum;
+       const u_char    *_msg_ptr;
+} ns_msg;
+
+/*
+ * This is a newmsg handle, used when constructing new messages with
+ * ns_newmsg_init, et al.
+ */
+struct ns_newmsg {
+       ns_msg          msg;
+       const u_char    *dnptrs[25];
+       const u_char    **lastdnptr;
+};
+typedef struct ns_newmsg ns_newmsg;
+
+/* Private data structure - do not use from outside library. */
+struct _ns_flagdata {  int mask, shift;  };
+extern struct _ns_flagdata _ns_flagdata[];
+
+/* Accessor macros - this is part of the public interface. */
+
+#define ns_msg_id(handle) ((handle)._id + 0)
+#define ns_msg_base(handle) ((handle)._msg + 0)
+#define ns_msg_end(handle) ((handle)._eom + 0)
+#define ns_msg_size(handle) ((size_t)((handle)._eom - (handle)._msg))
+#define ns_msg_count(handle, section) ((handle)._counts[section] + 0)
+
+/*%
+ * This is a parsed record.  It is caller allocated and has no dynamic data.
+ */
+typedef        struct __ns_rr {
+       char            name[NS_MAXDNAME];
+       uint16_t        type;
+       uint16_t        rr_class;
+       uint32_t        ttl;
+       uint16_t        rdlength;
+       const u_char *  rdata;
+} ns_rr;
+
+/*
+ * Same thing, but using uncompressed network binary names, and real C types.
+ */
+typedef        struct __ns_rr2 {
+       ns_nname        nname;
+       size_t          nnamel;
+       int             type;
+       int             rr_class;
+       u_int           ttl;
+       int             rdlength;
+       const u_char *  rdata;
+} ns_rr2;
+
+/* Accessor macros - this is part of the public interface. */
+#define ns_rr_name(rr) (((rr).name[0] != '\0') ? (rr).name : ".")
+#define ns_rr_nname(rr)        ((const ns_nname_t)(rr).nname)
+#define ns_rr_nnamel(rr) ((rr).nnamel + 0)
+#define ns_rr_type(rr) ((ns_type)((rr).type + 0))
+#define ns_rr_class(rr)        ((ns_class)((rr).rr_class + 0))
+#define ns_rr_ttl(rr)  ((u_long)(rr).ttl + 0)
+#define ns_rr_rdlen(rr)        ((size_t)(rr).rdlength + 0)
+#define ns_rr_rdata(rr)        ((rr).rdata + 0)
+
+/*%
+ * These don't have to be in the same order as in the packet flags word,
+ * and they can even overlap in some cases, but they will need to be kept
+ * in synch with ns_parse.c:ns_flagdata[].
+ */
+typedef enum __ns_flag {
+       ns_f_qr,                /*%< Question/Response. */
+       ns_f_opcode,            /*%< Operation code. */
+       ns_f_aa,                /*%< Authoritative Answer. */
+       ns_f_tc,                /*%< Truncation occurred. */
+       ns_f_rd,                /*%< Recursion Desired. */
+       ns_f_ra,                /*%< Recursion Available. */
+       ns_f_z,                 /*%< MBZ. */
+       ns_f_ad,                /*%< Authentic Data (DNSSEC). */
+       ns_f_cd,                /*%< Checking Disabled (DNSSEC). */
+       ns_f_rcode,             /*%< Response code. */
+       ns_f_max
+} ns_flag;
+
+/*%
+ * Currently defined opcodes.
+ */
+typedef enum __ns_opcode {
+       ns_o_query = 0,         /*%< Standard query. */
+       ns_o_iquery = 1,        /*%< Inverse query (deprecated/unsupported). */
+       ns_o_status = 2,        /*%< Name server status query (unsupported). */
+                               /* Opcode 3 is undefined/reserved. */
+       ns_o_notify = 4,        /*%< Zone change notification. */
+       ns_o_update = 5,        /*%< Zone update message. */
+       ns_o_max = 6
+} ns_opcode;
+
+/*%
+ * Currently defined response codes.
+ */
+typedef        enum __ns_rcode {
+       ns_r_noerror = 0,       /*%< No error occurred. */
+       ns_r_formerr = 1,       /*%< Format error. */
+       ns_r_servfail = 2,      /*%< Server failure. */
+       ns_r_nxdomain = 3,      /*%< Name error. */
+       ns_r_notimpl = 4,       /*%< Unimplemented. */
+       ns_r_refused = 5,       /*%< Operation refused. */
+       /* these are for BIND_UPDATE */
+       ns_r_yxdomain = 6,      /*%< Name exists */
+       ns_r_yxrrset = 7,       /*%< RRset exists */
+       ns_r_nxrrset = 8,       /*%< RRset does not exist */
+       ns_r_notauth = 9,       /*%< Not authoritative for zone */
+       ns_r_notzone = 10,      /*%< Zone of record different from zone section */
+       ns_r_max = 11,
+       /* The following are EDNS extended rcodes */
+       ns_r_badvers = 16,
+       /* The following are TSIG errors */
+       ns_r_badsig = 16,
+       ns_r_badkey = 17,
+       ns_r_badtime = 18
+} ns_rcode;
+
+/* BIND_UPDATE */
+typedef enum __ns_update_operation {
+       ns_uop_delete = 0,
+       ns_uop_add = 1,
+       ns_uop_max = 2
+} ns_update_operation;
+
+/*%
+ * This structure is used for TSIG authenticated messages
+ */
+struct ns_tsig_key {
+       char name[NS_MAXDNAME], alg[NS_MAXDNAME];
+       unsigned char *data;
+       int len;
+};
+typedef struct ns_tsig_key ns_tsig_key;
+
+/*%
+ * This structure is used for TSIG authenticated TCP messages
+ */
+struct ns_tcp_tsig_state {
+       int counter;
+       struct dst_key *key;
+       void *ctx;
+       unsigned char sig[NS_PACKETSZ];
+       int siglen;
+};
+typedef struct ns_tcp_tsig_state ns_tcp_tsig_state;
+
+#define NS_TSIG_FUDGE 300
+#define NS_TSIG_TCP_COUNT 100
+#define NS_TSIG_ALG_HMAC_MD5 "HMAC-MD5.SIG-ALG.REG.INT"
+
+#define NS_TSIG_ERROR_NO_TSIG -10
+#define NS_TSIG_ERROR_NO_SPACE -11
+#define NS_TSIG_ERROR_FORMERR -12
+
+/*%
+ * Currently defined type values for resources and queries.
+ */
+typedef enum __ns_type {
+       ns_t_invalid = 0,       /*%< Cookie. */
+       ns_t_a = 1,             /*%< Host address. */
+       ns_t_ns = 2,            /*%< Authoritative server. */
+       ns_t_md = 3,            /*%< Mail destination. */
+       ns_t_mf = 4,            /*%< Mail forwarder. */
+       ns_t_cname = 5,         /*%< Canonical name. */
+       ns_t_soa = 6,           /*%< Start of authority zone. */
+       ns_t_mb = 7,            /*%< Mailbox domain name. */
+       ns_t_mg = 8,            /*%< Mail group member. */
+       ns_t_mr = 9,            /*%< Mail rename name. */
+       ns_t_null = 10,         /*%< Null resource record. */
+       ns_t_wks = 11,          /*%< Well known service. */
+       ns_t_ptr = 12,          /*%< Domain name pointer. */
+       ns_t_hinfo = 13,        /*%< Host information. */
+       ns_t_minfo = 14,        /*%< Mailbox information. */
+       ns_t_mx = 15,           /*%< Mail routing information. */
+       ns_t_txt = 16,          /*%< Text strings. */
+       ns_t_rp = 17,           /*%< Responsible person. */
+       ns_t_afsdb = 18,        /*%< AFS cell database. */
+       ns_t_x25 = 19,          /*%< X_25 calling address. */
+       ns_t_isdn = 20,         /*%< ISDN calling address. */
+       ns_t_rt = 21,           /*%< Router. */
+       ns_t_nsap = 22,         /*%< NSAP address. */
+       ns_t_nsap_ptr = 23,     /*%< Reverse NSAP lookup (deprecated). */
+       ns_t_sig = 24,          /*%< Security signature. */
+       ns_t_key = 25,          /*%< Security key. */
+       ns_t_px = 26,           /*%< X.400 mail mapping. */
+       ns_t_gpos = 27,         /*%< Geographical position (withdrawn). */
+       ns_t_aaaa = 28,         /*%< IPv6 Address. */
+       ns_t_loc = 29,          /*%< Location Information. */
+       ns_t_nxt = 30,          /*%< Next domain (security). */
+       ns_t_eid = 31,          /*%< Endpoint identifier. */
+       ns_t_nimloc = 32,       /*%< Nimrod Locator. */
+       ns_t_srv = 33,          /*%< Server Selection. */
+       ns_t_atma = 34,         /*%< ATM Address */
+       ns_t_naptr = 35,        /*%< Naming Authority PoinTeR */
+       ns_t_kx = 36,           /*%< Key Exchange */
+       ns_t_cert = 37,         /*%< Certification record */
+       ns_t_a6 = 38,           /*%< IPv6 address (experimental) */
+       ns_t_dname = 39,        /*%< Non-terminal DNAME */
+       ns_t_sink = 40,         /*%< Kitchen sink (experimentatl) */
+       ns_t_opt = 41,          /*%< EDNS0 option (meta-RR) */
+       ns_t_apl = 42,          /*%< Address prefix list (RFC3123) */
+       ns_t_ds = 43,           /*%< Delegation Signer */
+       ns_t_sshfp = 44,        /*%< SSH Fingerprint */
+       ns_t_ipseckey = 45,     /*%< IPSEC Key */
+       ns_t_rrsig = 46,        /*%< RRset Signature */
+       ns_t_nsec = 47,         /*%< Negative security */
+       ns_t_dnskey = 48,       /*%< DNS Key */
+       ns_t_dhcid = 49,        /*%< Dynamic host configuratin identifier */
+       ns_t_nsec3 = 50,        /*%< Negative security type 3 */
+       ns_t_nsec3param = 51,   /*%< Negative security type 3 parameters */
+       ns_t_hip = 55,          /*%< Host Identity Protocol */
+       ns_t_spf = 99,          /*%< Sender Policy Framework */
+       ns_t_tkey = 249,        /*%< Transaction key */
+       ns_t_tsig = 250,        /*%< Transaction signature. */
+       ns_t_ixfr = 251,        /*%< Incremental zone transfer. */
+       ns_t_axfr = 252,        /*%< Transfer zone of authority. */
+       ns_t_mailb = 253,       /*%< Transfer mailbox records. */
+       ns_t_maila = 254,       /*%< Transfer mail agent records. */
+       ns_t_any = 255,         /*%< Wildcard match. */
+       ns_t_zxfr = 256,        /*%< BIND-specific, nonstandard. */
+       ns_t_dlv = 32769,       /*%< DNSSEC look-aside validatation. */
+       ns_t_max = 65536
+} ns_type;
+
+/* Exclusively a QTYPE? (not also an RTYPE) */
+#define        ns_t_qt_p(t) (ns_t_xfr_p(t) || (t) == ns_t_any || \
+                     (t) == ns_t_mailb || (t) == ns_t_maila)
+/* Some kind of meta-RR? (not a QTYPE, but also not an RTYPE) */
+#define        ns_t_mrr_p(t) ((t) == ns_t_tsig || (t) == ns_t_opt)
+/* Exclusively an RTYPE? (not also a QTYPE or a meta-RR) */
+#define ns_t_rr_p(t) (!ns_t_qt_p(t) && !ns_t_mrr_p(t))
+#define ns_t_udp_p(t) ((t) != ns_t_axfr && (t) != ns_t_zxfr)
+#define ns_t_xfr_p(t) ((t) == ns_t_axfr || (t) == ns_t_ixfr || \
+                      (t) == ns_t_zxfr)
+
+/*%
+ * Values for class field
+ */
+typedef enum __ns_class {
+       ns_c_invalid = 0,       /*%< Cookie. */
+       ns_c_in = 1,            /*%< Internet. */
+       ns_c_2 = 2,             /*%< unallocated/unsupported. */
+       ns_c_chaos = 3,         /*%< MIT Chaos-net. */
+       ns_c_hs = 4,            /*%< MIT Hesiod. */
+       /* Query class values which do not appear in resource records */
+       ns_c_none = 254,        /*%< for prereq. sections in update requests */
+       ns_c_any = 255,         /*%< Wildcard match. */
+       ns_c_max = 65536
+} ns_class;
+
+/* DNSSEC constants. */
+
+typedef enum __ns_key_types {
+       ns_kt_rsa = 1,          /*%< key type RSA/MD5 */
+       ns_kt_dh  = 2,          /*%< Diffie Hellman */
+       ns_kt_dsa = 3,          /*%< Digital Signature Standard (MANDATORY) */
+       ns_kt_private = 254     /*%< Private key type starts with OID */
+} ns_key_types;
+
+typedef enum __ns_cert_types {
+       cert_t_pkix = 1,        /*%< PKIX (X.509v3) */
+       cert_t_spki = 2,        /*%< SPKI */
+       cert_t_pgp  = 3,        /*%< PGP */
+       cert_t_url  = 253,      /*%< URL private type */
+       cert_t_oid  = 254       /*%< OID private type */
+} ns_cert_types;
+
+/* Flags field of the KEY RR rdata. */
+#define        NS_KEY_TYPEMASK         0xC000  /*%< Mask for "type" bits */
+#define        NS_KEY_TYPE_AUTH_CONF   0x0000  /*%< Key usable for both */
+#define        NS_KEY_TYPE_CONF_ONLY   0x8000  /*%< Key usable for confidentiality */
+#define        NS_KEY_TYPE_AUTH_ONLY   0x4000  /*%< Key usable for authentication */
+#define        NS_KEY_TYPE_NO_KEY      0xC000  /*%< No key usable for either; no key */
+/* The type bits can also be interpreted independently, as single bits: */
+#define        NS_KEY_NO_AUTH          0x8000  /*%< Key unusable for authentication */
+#define        NS_KEY_NO_CONF          0x4000  /*%< Key unusable for confidentiality */
+#define        NS_KEY_RESERVED2        0x2000  /* Security is *mandatory* if bit=0 */
+#define        NS_KEY_EXTENDED_FLAGS   0x1000  /*%< reserved - must be zero */
+#define        NS_KEY_RESERVED4        0x0800  /*%< reserved - must be zero */
+#define        NS_KEY_RESERVED5        0x0400  /*%< reserved - must be zero */
+#define        NS_KEY_NAME_TYPE        0x0300  /*%< these bits determine the type */
+#define        NS_KEY_NAME_USER        0x0000  /*%< key is assoc. with user */
+#define        NS_KEY_NAME_ENTITY      0x0200  /*%< key is assoc. with entity eg host */
+#define        NS_KEY_NAME_ZONE        0x0100  /*%< key is zone key */
+#define        NS_KEY_NAME_RESERVED    0x0300  /*%< reserved meaning */
+#define        NS_KEY_RESERVED8        0x0080  /*%< reserved - must be zero */
+#define        NS_KEY_RESERVED9        0x0040  /*%< reserved - must be zero */
+#define        NS_KEY_RESERVED10       0x0020  /*%< reserved - must be zero */
+#define        NS_KEY_RESERVED11       0x0010  /*%< reserved - must be zero */
+#define        NS_KEY_SIGNATORYMASK    0x000F  /*%< key can sign RR's of same name */
+#define        NS_KEY_RESERVED_BITMASK ( NS_KEY_RESERVED2 | \
+                                 NS_KEY_RESERVED4 | \
+                                 NS_KEY_RESERVED5 | \
+                                 NS_KEY_RESERVED8 | \
+                                 NS_KEY_RESERVED9 | \
+                                 NS_KEY_RESERVED10 | \
+                                 NS_KEY_RESERVED11 )
+#define NS_KEY_RESERVED_BITMASK2 0xFFFF /*%< no bits defined here */
+
+/* The Algorithm field of the KEY and SIG RR's is an integer, {1..254} */
+#define        NS_ALG_MD5RSA           1       /*%< MD5 with RSA */
+#define        NS_ALG_DH               2       /*%< Diffie Hellman KEY */
+#define        NS_ALG_DSA              3       /*%< DSA KEY */
+#define        NS_ALG_DSS              NS_ALG_DSA
+#define        NS_ALG_EXPIRE_ONLY      253     /*%< No alg, no security */
+#define        NS_ALG_PRIVATE_OID      254     /*%< Key begins with OID giving alg */
+
+/* Protocol values  */
+/* value 0 is reserved */
+#define NS_KEY_PROT_TLS         1
+#define NS_KEY_PROT_EMAIL       2
+#define NS_KEY_PROT_DNSSEC      3
+#define NS_KEY_PROT_IPSEC       4
+#define NS_KEY_PROT_ANY                255
+
+/* Signatures */
+#define        NS_MD5RSA_MIN_BITS       512    /*%< Size of a mod or exp in bits */
+#define        NS_MD5RSA_MAX_BITS      4096
+       /* Total of binary mod and exp */
+#define        NS_MD5RSA_MAX_BYTES     ((NS_MD5RSA_MAX_BITS+7/8)*2+3)
+       /* Max length of text sig block */
+#define        NS_MD5RSA_MAX_BASE64    (((NS_MD5RSA_MAX_BYTES+2)/3)*4)
+#define NS_MD5RSA_MIN_SIZE     ((NS_MD5RSA_MIN_BITS+7)/8)
+#define NS_MD5RSA_MAX_SIZE     ((NS_MD5RSA_MAX_BITS+7)/8)
+
+#define NS_DSA_SIG_SIZE         41
+#define NS_DSA_MIN_SIZE         213
+#define NS_DSA_MAX_BYTES        405
+
+/* Offsets into SIG record rdata to find various values */
+#define        NS_SIG_TYPE     0       /*%< Type flags */
+#define        NS_SIG_ALG      2       /*%< Algorithm */
+#define        NS_SIG_LABELS   3       /*%< How many labels in name */
+#define        NS_SIG_OTTL     4       /*%< Original TTL */
+#define        NS_SIG_EXPIR    8       /*%< Expiration time */
+#define        NS_SIG_SIGNED   12      /*%< Signature time */
+#define        NS_SIG_FOOT     16      /*%< Key footprint */
+#define        NS_SIG_SIGNER   18      /*%< Domain name of who signed it */
+
+/* How RR types are represented as bit-flags in NXT records */
+#define        NS_NXT_BITS 8
+#define        NS_NXT_BIT_SET(  n,p) (p[(n)/NS_NXT_BITS] |=  (0x80>>((n)%NS_NXT_BITS)))
+#define        NS_NXT_BIT_CLEAR(n,p) (p[(n)/NS_NXT_BITS] &= ~(0x80>>((n)%NS_NXT_BITS)))
+#define        NS_NXT_BIT_ISSET(n,p) (p[(n)/NS_NXT_BITS] &   (0x80>>((n)%NS_NXT_BITS)))
+#define NS_NXT_MAX 127
+
+/*%
+ * EDNS0 extended flags and option codes, host order.
+ */
+#define NS_OPT_DNSSEC_OK       0x8000U
+#define NS_OPT_NSID             3
+
+/*%
+ * Inline versions of get/put short/long.  Pointer is advanced.
+ */
+#define NS_GET16(s, cp) do { \
+       const u_char *t_cp = (const u_char *)(cp); \
+       (s) = ((uint16_t)t_cp[0] << 8) \
+           | ((uint16_t)t_cp[1]) \
+           ; \
+       (cp) += NS_INT16SZ; \
+} while (/*CONSTCOND*/0)
+
+#define NS_GET32(l, cp) do { \
+       const u_char *t_cp = (const u_char *)(cp); \
+       (l) = ((uint32_t)t_cp[0] << 24) \
+           | ((uint32_t)t_cp[1] << 16) \
+           | ((uint32_t)t_cp[2] << 8) \
+           | ((uint32_t)t_cp[3]) \
+           ; \
+       (cp) += NS_INT32SZ; \
+} while (/*CONSTCOND*/0)
+
+#define NS_PUT16(s, cp) do { \
+       uint32_t t_s = (uint32_t)(s); \
+       u_char *t_cp = (u_char *)(cp); \
+       *t_cp++ = t_s >> 8; \
+       *t_cp   = t_s; \
+       (cp) += NS_INT16SZ; \
+} while (/*CONSTCOND*/0)
+
+#define NS_PUT32(l, cp) do { \
+       uint32_t t_l = (uint32_t)(l); \
+       u_char *t_cp = (u_char *)(cp); \
+       *t_cp++ = t_l >> 24; \
+       *t_cp++ = t_l >> 16; \
+       *t_cp++ = t_l >> 8; \
+       *t_cp   = t_l; \
+       (cp) += NS_INT32SZ; \
+} while (/*CONSTCOND*/0)
+
+/*%
+ * ANSI C identifier hiding for bind's lib/nameser.
+ */
+#define        ns_msg_getflag          __ns_msg_getflag
+#define ns_get16               __ns_get16
+#define ns_get32               __ns_get32
+#define ns_put16               __ns_put16
+#define ns_put32               __ns_put32
+#define ns_initparse           __ns_initparse
+#define ns_skiprr              __ns_skiprr
+#define ns_parserr             __ns_parserr
+#define ns_parserr2            __ns_parserr2
+#define        ns_sprintrr             __ns_sprintrr
+#define        ns_sprintrrf            __ns_sprintrrf
+#define        ns_format_ttl           __ns_format_ttl
+#define        ns_parse_ttl            __ns_parse_ttl
+#define ns_datetosecs          __ns_datetosecs
+#define        ns_name_ntol            __ns_name_ntol
+#define        ns_name_ntop            __ns_name_ntop
+#define        ns_name_pton            __ns_name_pton
+#define        ns_name_pton2           __ns_name_pton2
+#define        ns_name_unpack          __ns_name_unpack
+#define        ns_name_unpack2         __ns_name_unpack2
+#define        ns_name_pack            __ns_name_pack
+#define        ns_name_compress        __ns_name_compress
+#define        ns_name_uncompress      __ns_name_uncompress
+#define        ns_name_skip            __ns_name_skip
+#define        ns_name_rollback        __ns_name_rollback
+#define        ns_name_length          __ns_name_length
+#define        ns_name_eq              __ns_name_eq
+#define        ns_name_owned           __ns_name_owned
+#define        ns_name_map             __ns_name_map
+#define        ns_name_labels          __ns_name_labels
+#define        ns_sign                 __ns_sign
+#define        ns_sign2                __ns_sign2
+#define        ns_sign_tcp             __ns_sign_tcp
+#define        ns_sign_tcp2            __ns_sign_tcp2
+#define        ns_sign_tcp_init        __ns_sign_tcp_init
+#define ns_find_tsig           __ns_find_tsig
+#define        ns_verify               __ns_verify
+#define        ns_verify_tcp           __ns_verify_tcp
+#define        ns_verify_tcp_init      __ns_verify_tcp_init
+#define        ns_samedomain           __ns_samedomain
+#define        ns_subdomain            __ns_subdomain
+#define        ns_makecanon            __ns_makecanon
+#define        ns_samename             __ns_samename
+#define        ns_newmsg_init          __ns_newmsg_init
+#define        ns_newmsg_copy          __ns_newmsg_copy
+#define        ns_newmsg_id            __ns_newmsg_id
+#define        ns_newmsg_flag          __ns_newmsg_flag
+#define        ns_newmsg_q             __ns_newmsg_q
+#define        ns_newmsg_rr            __ns_newmsg_rr
+#define        ns_newmsg_done          __ns_newmsg_done
+#define        ns_rdata_unpack         __ns_rdata_unpack
+#define        ns_rdata_equal          __ns_rdata_equal
+#define        ns_rdata_refers         __ns_rdata_refers
+
+__BEGIN_DECLS
+int            ns_msg_getflag(ns_msg, int);
+uint16_t       ns_get16(const u_char *);
+uint32_t       ns_get32(const u_char *);
+void           ns_put16(uint16_t, u_char *);
+void           ns_put32(uint32_t, u_char *);
+int            ns_initparse(const u_char *, int, ns_msg *);
+int            ns_skiprr(const u_char *, const u_char *, ns_sect, int);
+int            ns_parserr(ns_msg *, ns_sect, int, ns_rr *);
+int            ns_parserr2(ns_msg *, ns_sect, int, ns_rr2 *);
+int            ns_sprintrr(const ns_msg *, const ns_rr *,
+                                const char *, const char *, char *, size_t);
+int            ns_sprintrrf(const u_char *, size_t, const char *,
+                                 ns_class, ns_type, u_long, const u_char *,
+                                 size_t, const char *, const char *,
+                                 char *, size_t);
+int            ns_format_ttl(u_long, char *, size_t);
+int            ns_parse_ttl(const char *, u_long *);
+uint32_t       ns_datetosecs(const char *cp, int *errp);
+int            ns_name_ntol(const u_char *, u_char *, size_t);
+int            ns_name_ntop(const u_char *, char *, size_t);
+int            ns_name_pton(const char *, u_char *, size_t);
+int            ns_name_pton2(const char *, u_char *, size_t, size_t *);
+int            ns_name_unpack(const u_char *, const u_char *,
+                                   const u_char *, u_char *, size_t);
+int            ns_name_unpack2(const u_char *, const u_char *,
+                                    const u_char *, u_char *, size_t,
+                                    size_t *);
+int            ns_name_pack(const u_char *, u_char *, int,
+                                 const u_char **, const u_char **);
+int            ns_name_uncompress(const u_char *, const u_char *,
+                                       const u_char *, char *, size_t);
+int            ns_name_compress(const char *, u_char *, size_t,
+                                     const u_char **, const u_char **);
+int            ns_name_skip(const u_char **, const u_char *);
+void           ns_name_rollback(const u_char *, const u_char **,
+                                     const u_char **);
+#ifndef __LIBC12_SOURCE__
+int            ns_sign(u_char *, int *, int, int, void *,
+                            const u_char *, int, u_char *, int *, time_t)
+    __RENAME(__ns_sign50);
+int            ns_sign2(u_char *, int *, int, int, void *,
+                             const u_char *, int, u_char *, int *, time_t,
+                             u_char **, u_char **)
+    __RENAME(__ns_sign250);
+#endif
+ssize_t                ns_name_length(ns_nname_ct, size_t);
+int            ns_name_eq(ns_nname_ct, size_t, ns_nname_ct, size_t);
+int            ns_name_owned(ns_namemap_ct, int, ns_namemap_ct, int);
+int            ns_name_map(ns_nname_ct, size_t, ns_namemap_t, int);
+int            ns_name_labels(ns_nname_ct, size_t);
+int            ns_sign_tcp(u_char *, int *, int, int,
+                                ns_tcp_tsig_state *, int);
+int            ns_sign_tcp2(u_char *, int *, int, int,
+                                 ns_tcp_tsig_state *, int,
+                                 u_char **, u_char **);
+int            ns_sign_tcp_init(void *, const u_char *, int,
+                                       ns_tcp_tsig_state *);
+u_char         *ns_find_tsig(u_char *, u_char *);
+#ifndef __LIBC12_SOURCE__
+int            ns_verify(u_char *, int *, void *,
+                              const u_char *, int, u_char *, int *,
+                              time_t *, int)
+    __RENAME(__ns_verify50);
+#endif
+int            ns_verify_tcp(u_char *, int *, ns_tcp_tsig_state *, int);
+int            ns_verify_tcp_init(void *, const u_char *, int,
+                                       ns_tcp_tsig_state *);
+int            ns_samedomain(const char *, const char *);
+int            ns_subdomain(const char *, const char *);
+int            ns_makecanon(const char *, char *, size_t);
+int            ns_samename(const char *, const char *);
+int            ns_newmsg_init(u_char *buffer, size_t bufsiz, ns_newmsg *);
+int            ns_newmsg_copy(ns_newmsg *, ns_msg *);
+void           ns_newmsg_id(ns_newmsg *handle, uint16_t id);
+void           ns_newmsg_flag(ns_newmsg *handle, ns_flag flag, u_int value);
+int            ns_newmsg_q(ns_newmsg *handle, ns_nname_ct qname,
+                           ns_type qtype, ns_class qclass);
+int            ns_newmsg_rr(ns_newmsg *handle, ns_sect sect,
+                            ns_nname_ct name, ns_type type,
+                            ns_class rr_class, uint32_t ttl,
+                            uint16_t rdlen, const u_char *rdata);
+size_t         ns_newmsg_done(ns_newmsg *handle);
+ssize_t                ns_rdata_unpack(const u_char *, const u_char *, ns_type,
+                               const u_char *, size_t, u_char *, size_t);
+int            ns_rdata_equal(ns_type,
+                              const u_char *, size_t,
+                              const u_char *, size_t);
+int            ns_rdata_refers(ns_type,
+                               const u_char *, size_t,
+                               const u_char *);
+__END_DECLS
+
+#ifdef BIND_4_COMPAT
+#include <arpa/nameser_compat.h>
+#endif
+
+#endif /* !_ARPA_NAMESER_H_ */
diff --git a/nbsd_include/arpa/nameser_compat.h b/nbsd_include/arpa/nameser_compat.h
new file mode 100644 (file)
index 0000000..3f2d66c
--- /dev/null
@@ -0,0 +1,236 @@
+/*     $NetBSD: nameser_compat.h,v 1.5 2009/04/12 17:07:34 christos Exp $      */
+
+/* Copyright (c) 1983, 1989
+ *    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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ */
+
+/*%
+ *      from nameser.h 8.1 (Berkeley) 6/2/93
+ *     Id: nameser_compat.h,v 1.8 2006/05/19 02:33:40 marka Exp
+ */
+
+#ifndef _ARPA_NAMESER_COMPAT_
+#define        _ARPA_NAMESER_COMPAT_
+
+#define        __BIND          19950621        /*%< (DEAD) interface version stamp. */
+
+#ifndef BYTE_ORDER
+#if (BSD >= 199103)
+# include <machine/endian.h>
+#else
+#ifdef __linux
+# include <endian.h>
+#else
+#define        LITTLE_ENDIAN   1234    /*%< least-significant byte first (vax, pc) */
+#define        BIG_ENDIAN      4321    /*%< most-significant byte first (IBM, net) */
+#define        PDP_ENDIAN      3412    /*%< LSB first in word, MSW first in long (pdp) */
+
+#if defined(vax) || defined(ns32000) || defined(sun386) || defined(i386) || \
+    defined(MIPSEL) || defined(_MIPSEL) || defined(BIT_ZERO_ON_RIGHT) || \
+    defined(__i386__) || defined(__i386) || defined(__amd64__) || \
+    defined(__x86_64__) || defined(MIPSEL) || defined(_MIPSEL) || \
+    defined(BIT_ZERO_ON_RIGHT) || defined(__alpha__) || defined(__alpha) || \
+    (defined(__Lynx__) && defined(__x86__))
+#define BYTE_ORDER     LITTLE_ENDIAN
+#endif
+
+#if defined(sel) || defined(pyr) || defined(mc68000) || defined(sparc) || \
+    defined(is68k) || defined(tahoe) || defined(ibm032) || defined(ibm370) || \
+    defined(MIPSEB) || defined(_MIPSEB) || defined(_IBMR2) || defined(DGUX) ||\
+    defined(apollo) || defined(__convex__) || defined(_CRAY) || \
+    defined(__hppa) || defined(__hp9000) || \
+    defined(__hp9000s300) || defined(__hp9000s700) || \
+    defined(__hp3000s900) || defined(__hpux) || defined(MPE) || \
+    defined (BIT_ZERO_ON_LEFT) || defined(m68k) || defined(__sparc) ||  \
+    (defined(__Lynx__) && \
+     (defined(__68k__) || defined(__sparc__) || defined(__powerpc__)))
+#define BYTE_ORDER     BIG_ENDIAN
+#endif
+#endif /* __linux */
+#endif /* BSD */
+#endif /* BYTE_ORDER */
+
+#if !defined(BYTE_ORDER) || \
+    (BYTE_ORDER != BIG_ENDIAN && BYTE_ORDER != LITTLE_ENDIAN && \
+    BYTE_ORDER != PDP_ENDIAN)
+       /* you must determine what the correct bit order is for
+        * your compiler - the next line is an intentional error
+        * which will force your compiles to bomb until you fix
+        * the above macros.
+        */
+  error "Undefined or invalid BYTE_ORDER";
+#endif
+
+/*%
+ * Structure for query header.  The order of the fields is machine- and
+ * compiler-dependent, depending on the byte/bit order and the layout
+ * of bit fields.  We use bit fields only in int variables, as this
+ * is all ANSI requires.  This requires a somewhat confusing rearrangement.
+ */
+
+typedef struct {
+       unsigned        id :16;         /*%< query identification number */
+#if BYTE_ORDER == BIG_ENDIAN
+                       /* fields in third byte */
+       unsigned        qr: 1;          /*%< response flag */
+       unsigned        opcode: 4;      /*%< purpose of message */
+       unsigned        aa: 1;          /*%< authoritive answer */
+       unsigned        tc: 1;          /*%< truncated message */
+       unsigned        rd: 1;          /*%< recursion desired */
+                       /* fields in fourth byte */
+       unsigned        ra: 1;          /*%< recursion available */
+       unsigned        unused :1;      /*%< unused bits (MBZ as of 4.9.3a3) */
+       unsigned        ad: 1;          /*%< authentic data from named */
+       unsigned        cd: 1;          /*%< checking disabled by resolver */
+       unsigned        rcode :4;       /*%< response code */
+#endif
+#if BYTE_ORDER == LITTLE_ENDIAN || BYTE_ORDER == PDP_ENDIAN
+                       /* fields in third byte */
+       unsigned        rd :1;          /*%< recursion desired */
+       unsigned        tc :1;          /*%< truncated message */
+       unsigned        aa :1;          /*%< authoritive answer */
+       unsigned        opcode :4;      /*%< purpose of message */
+       unsigned        qr :1;          /*%< response flag */
+                       /* fields in fourth byte */
+       unsigned        rcode :4;       /*%< response code */
+       unsigned        cd: 1;          /*%< checking disabled by resolver */
+       unsigned        ad: 1;          /*%< authentic data from named */
+       unsigned        unused :1;      /*%< unused bits (MBZ as of 4.9.3a3) */
+       unsigned        ra :1;          /*%< recursion available */
+#endif
+                       /* remaining bytes */
+       unsigned        qdcount :16;    /*%< number of question entries */
+       unsigned        ancount :16;    /*%< number of answer entries */
+       unsigned        nscount :16;    /*%< number of authority entries */
+       unsigned        arcount :16;    /*%< number of resource entries */
+} HEADER;
+
+#define PACKETSZ       NS_PACKETSZ
+#define MAXDNAME       NS_MAXDNAME
+#define MAXCDNAME      NS_MAXCDNAME
+#define MAXLABEL       NS_MAXLABEL
+#define        HFIXEDSZ        NS_HFIXEDSZ
+#define QFIXEDSZ       NS_QFIXEDSZ
+#define RRFIXEDSZ      NS_RRFIXEDSZ
+#define        INT32SZ         NS_INT32SZ
+#define        INT16SZ         NS_INT16SZ
+#define        INT8SZ          NS_INT8SZ
+#define        INADDRSZ        NS_INADDRSZ
+#define        IN6ADDRSZ       NS_IN6ADDRSZ
+#define        INDIR_MASK      NS_CMPRSFLGS
+#define NAMESERVER_PORT        NS_DEFAULTPORT
+
+#define S_ZONE         ns_s_zn
+#define S_PREREQ       ns_s_pr
+#define S_UPDATE       ns_s_ud
+#define S_ADDT         ns_s_ar
+
+#define QUERY          ns_o_query
+#define IQUERY         ns_o_iquery
+#define STATUS         ns_o_status
+#define        NS_NOTIFY_OP    ns_o_notify
+#define        NS_UPDATE_OP    ns_o_update
+
+#define NOERROR                ns_r_noerror
+#define FORMERR                ns_r_formerr
+#define SERVFAIL       ns_r_servfail
+#define NXDOMAIN       ns_r_nxdomain
+#define NOTIMP         ns_r_notimpl
+#define REFUSED                ns_r_refused
+#define YXDOMAIN       ns_r_yxdomain
+#define YXRRSET                ns_r_yxrrset
+#define NXRRSET                ns_r_nxrrset
+#define NOTAUTH                ns_r_notauth
+#define NOTZONE                ns_r_notzone
+/*#define BADSIG               ns_r_badsig*/
+/*#define BADKEY               ns_r_badkey*/
+/*#define BADTIME              ns_r_badtime*/
+
+
+#define DELETE         ns_uop_delete
+#define ADD            ns_uop_add
+
+#define T_A            ns_t_a
+#define T_NS           ns_t_ns
+#define T_MD           ns_t_md
+#define T_MF           ns_t_mf
+#define T_CNAME                ns_t_cname
+#define T_SOA          ns_t_soa
+#define T_MB           ns_t_mb
+#define T_MG           ns_t_mg
+#define T_MR           ns_t_mr
+#define T_NULL         ns_t_null
+#define T_WKS          ns_t_wks
+#define T_PTR          ns_t_ptr
+#define T_HINFO                ns_t_hinfo
+#define T_MINFO                ns_t_minfo
+#define T_MX           ns_t_mx
+#define T_TXT          ns_t_txt
+#define        T_RP            ns_t_rp
+#define T_AFSDB                ns_t_afsdb
+#define T_X25          ns_t_x25
+#define T_ISDN         ns_t_isdn
+#define T_RT           ns_t_rt
+#define T_NSAP         ns_t_nsap
+#define T_NSAP_PTR     ns_t_nsap_ptr
+#define        T_SIG           ns_t_sig
+#define        T_KEY           ns_t_key
+#define        T_PX            ns_t_px
+#define        T_GPOS          ns_t_gpos
+#define        T_AAAA          ns_t_aaaa
+#define        T_LOC           ns_t_loc
+#define        T_NXT           ns_t_nxt
+#define        T_EID           ns_t_eid
+#define        T_NIMLOC        ns_t_nimloc
+#define        T_SRV           ns_t_srv
+#define T_ATMA         ns_t_atma
+#define T_NAPTR                ns_t_naptr
+#define T_A6           ns_t_a6
+#define        T_TSIG          ns_t_tsig
+#define        T_IXFR          ns_t_ixfr
+#define T_AXFR         ns_t_axfr
+#define T_MAILB                ns_t_mailb
+#define T_MAILA                ns_t_maila
+#define T_ANY          ns_t_any
+
+#define C_IN           ns_c_in
+#define C_CHAOS                ns_c_chaos
+#define C_HS           ns_c_hs
+/* BIND_UPDATE */
+#define C_NONE         ns_c_none
+#define C_ANY          ns_c_any
+
+#define        GETSHORT                NS_GET16
+#define        GETLONG                 NS_GET32
+#define        PUTSHORT                NS_PUT16
+#define        PUTLONG                 NS_PUT32
+
+#endif /* _ARPA_NAMESER_COMPAT_ */
diff --git a/nbsd_include/arpa/telnet.h b/nbsd_include/arpa/telnet.h
new file mode 100644 (file)
index 0000000..3cf2f1e
--- /dev/null
@@ -0,0 +1,354 @@
+/*     $NetBSD: telnet.h,v 1.12 2006/01/24 17:13:59 christos Exp $     */
+
+/*
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)telnet.h    8.2 (Berkeley) 12/15/93
+ */
+
+#ifndef _ARPA_TELNET_H_
+#define        _ARPA_TELNET_H_
+
+/*
+ * Definitions for the TELNET protocol.
+ */
+#define        IAC     255             /* interpret as command: */
+#define        DONT    254             /* you are not to use option */
+#define        DO      253             /* please, you use option */
+#define        WONT    252             /* I won't use option */
+#define        WILL    251             /* I will use option */
+#define        SB      250             /* interpret as subnegotiation */
+#define        GA      249             /* you may reverse the line */
+#define        EL      248             /* erase the current line */
+#define        EC      247             /* erase the current character */
+#define        AYT     246             /* are you there */
+#define        AO      245             /* abort output--but let prog finish */
+#define        IP      244             /* interrupt process--permanently */
+#define        BREAK   243             /* break */
+#define        DM      242             /* data mark--for connect. cleaning */
+#define        NOP     241             /* nop */
+#define        SE      240             /* end sub negotiation */
+#define EOR     239             /* end of record (transparent mode) */
+#define        ABORT   238             /* Abort process */
+#define        SUSP    237             /* Suspend process */
+#define        xEOF    236             /* End of file: EOF is already used... */
+
+#define SYNCH  242             /* for telfunc calls */
+
+#ifdef TELCMDS
+const char *telcmds[] = {
+       "EOF", "SUSP", "ABORT", "EOR",
+       "SE", "NOP", "DMARK", "BRK", "IP", "AO", "AYT", "EC",
+       "EL", "GA", "SB", "WILL", "WONT", "DO", "DONT", "IAC", 0
+};
+#else
+extern const char *telcmds[];
+#endif
+
+#define        TELCMD_FIRST    xEOF
+#define        TELCMD_LAST     IAC
+#define        TELCMD_OK(x)    ((unsigned int)(x) <= TELCMD_LAST && \
+                        (unsigned int)(x) >= TELCMD_FIRST)
+#define        TELCMD(x)       telcmds[(x)-TELCMD_FIRST]
+
+/* telnet options */
+#define TELOPT_BINARY  0       /* 8-bit data path */
+#define TELOPT_ECHO    1       /* echo */
+#define        TELOPT_RCP      2       /* prepare to reconnect */
+#define        TELOPT_SGA      3       /* suppress go ahead */
+#define        TELOPT_NAMS     4       /* approximate message size */
+#define        TELOPT_STATUS   5       /* give status */
+#define        TELOPT_TM       6       /* timing mark */
+#define        TELOPT_RCTE     7       /* remote controlled transmission and echo */
+#define TELOPT_NAOL    8       /* negotiate about output line width */
+#define TELOPT_NAOP    9       /* negotiate about output page size */
+#define TELOPT_NAOCRD  10      /* negotiate about CR disposition */
+#define TELOPT_NAOHTS  11      /* negotiate about horizontal tabstops */
+#define TELOPT_NAOHTD  12      /* negotiate about horizontal tab disposition */
+#define TELOPT_NAOFFD  13      /* negotiate about formfeed disposition */
+#define TELOPT_NAOVTS  14      /* negotiate about vertical tab stops */
+#define TELOPT_NAOVTD  15      /* negotiate about vertical tab disposition */
+#define TELOPT_NAOLFD  16      /* negotiate about output LF disposition */
+#define TELOPT_XASCII  17      /* extended ascic character set */
+#define        TELOPT_LOGOUT   18      /* force logout */
+#define        TELOPT_BM       19      /* byte macro */
+#define        TELOPT_DET      20      /* data entry terminal */
+#define        TELOPT_SUPDUP   21      /* supdup protocol */
+#define        TELOPT_SUPDUPOUTPUT 22  /* supdup output */
+#define        TELOPT_SNDLOC   23      /* send location */
+#define        TELOPT_TTYPE    24      /* terminal type */
+#define        TELOPT_EOR      25      /* end or record */
+#define        TELOPT_TUID     26      /* TACACS user identification */
+#define        TELOPT_OUTMRK   27      /* output marking */
+#define        TELOPT_TTYLOC   28      /* terminal location number */
+#define        TELOPT_3270REGIME 29    /* 3270 regime */
+#define        TELOPT_X3PAD    30      /* X.3 PAD */
+#define        TELOPT_NAWS     31      /* window size */
+#define        TELOPT_TSPEED   32      /* terminal speed */
+#define        TELOPT_LFLOW    33      /* remote flow control */
+#define TELOPT_LINEMODE        34      /* Linemode option */
+#define TELOPT_XDISPLOC        35      /* X Display Location */
+#define TELOPT_OLD_ENVIRON 36  /* Old - Environment variables */
+#define        TELOPT_AUTHENTICATION 37/* Authenticate */
+#define        TELOPT_ENCRYPT  38      /* Encryption option */
+#define TELOPT_NEW_ENVIRON 39  /* New - Environment variables */
+#define        TELOPT_TN3270E  40      /* RFC2355 - TN3270 Enhancements */
+#define        TELOPT_CHARSET  42      /* RFC2066 - Charset */
+#define        TELOPT_COMPORT  44      /* RFC2217 - Com Port Control */
+#define        TELOPT_KERMIT   47      /* RFC2840 - Kermit */
+#define        TELOPT_EXOPL    255     /* extended-options-list */
+
+
+#define        TELOPT_FIRST    TELOPT_BINARY
+#define        TELOPT_LAST     TELOPT_KERMIT
+#define        TELOPT_OK(x)    ((unsigned int)(x) <= TELOPT_LAST)
+#define        TELOPT(x)       telopts[(x)-TELOPT_FIRST]
+
+#define        NTELOPTS        (1+TELOPT_LAST)
+
+#ifdef TELOPTS
+const char *telopts[NTELOPTS+1] = {
+       "BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD", "NAME",
+       "STATUS", "TIMING MARK", "RCTE", "NAOL", "NAOP",
+       "NAOCRD", "NAOHTS", "NAOHTD", "NAOFFD", "NAOVTS",
+       "NAOVTD", "NAOLFD", "EXTEND ASCII", "LOGOUT", "BYTE MACRO",
+       "DATA ENTRY TERMINAL", "SUPDUP", "SUPDUP OUTPUT",
+       "SEND LOCATION", "TERMINAL TYPE", "END OF RECORD",
+       "TACACS UID", "OUTPUT MARKING", "TTYLOC",
+       "3270 REGIME", "X.3 PAD", "NAWS", "TSPEED", "LFLOW",
+       "LINEMODE", "XDISPLOC", "OLD-ENVIRON", "AUTHENTICATION",
+       "ENCRYPT", "NEW-ENVIRON", "TN3270E", "CHARSET", "COM-PORT",
+       "KERMIT",
+       0
+};
+#else
+extern const char *telopts[NTELOPTS+1];
+#endif
+
+/* sub-option qualifiers */
+#define        TELQUAL_IS      0       /* option is... */
+#define        TELQUAL_SEND    1       /* send option */
+#define        TELQUAL_INFO    2       /* ENVIRON: informational version of IS */
+#define        TELQUAL_REPLY   2       /* AUTHENTICATION: client version of IS */
+#define        TELQUAL_NAME    3       /* AUTHENTICATION: client version of IS */
+
+#define        LFLOW_OFF               0       /* Disable remote flow control */
+#define        LFLOW_ON                1       /* Enable remote flow control */
+#define        LFLOW_RESTART_ANY       2       /* Restart output on any char */
+#define        LFLOW_RESTART_XON       3       /* Restart output only on XON */
+
+/*
+ * LINEMODE suboptions
+ */
+
+#define        LM_MODE         1
+#define        LM_FORWARDMASK  2
+#define        LM_SLC          3
+
+#define        MODE_EDIT       0x01
+#define        MODE_TRAPSIG    0x02
+#define        MODE_ACK        0x04
+#define MODE_SOFT_TAB  0x08
+#define MODE_LIT_ECHO  0x10
+
+#define        MODE_MASK       0x1f
+
+/* Not part of protocol, but needed to simplify things... */
+#define MODE_FLOW              0x0100
+#define MODE_ECHO              0x0200
+#define MODE_INBIN             0x0400
+#define MODE_OUTBIN            0x0800
+#define MODE_FORCE             0x1000
+
+#define        SLC_SYNCH       1
+#define        SLC_BRK         2
+#define        SLC_IP          3
+#define        SLC_AO          4
+#define        SLC_AYT         5
+#define        SLC_EOR         6
+#define        SLC_ABORT       7
+#define        SLC_EOF         8
+#define        SLC_SUSP        9
+#define        SLC_EC          10
+#define        SLC_EL          11
+#define        SLC_EW          12
+#define        SLC_RP          13
+#define        SLC_LNEXT       14
+#define        SLC_XON         15
+#define        SLC_XOFF        16
+#define        SLC_FORW1       17
+#define        SLC_FORW2       18
+#define        SLC_MCL         19
+#define        SLC_MCR         20
+#define        SLC_MCWL        21
+#define        SLC_MCWR        22
+#define        SLC_MCBOL       23
+#define        SLC_MCEOL       24
+#define        SLC_INSRT       25
+#define        SLC_OVER        26
+#define        SLC_ECR         27
+#define        SLC_EWR         28
+#define        SLC_EBOL        29
+#define        SLC_EEOL        30
+
+#define        NSLC            30
+
+/*
+ * For backwards compatibility, we define SLC_NAMES to be the
+ * list of names if SLC_NAMES is not defined.
+ */
+#define        SLC_NAMELIST    "0", "SYNCH", "BRK", "IP", "AO", "AYT", "EOR",  \
+                       "ABORT", "EOF", "SUSP", "EC", "EL", "EW", "RP", \
+                       "LNEXT", "XON", "XOFF", "FORW1", "FORW2",       \
+                       "MCL", "MCR", "MCWL", "MCWR", "MCBOL",          \
+                       "MCEOL", "INSRT", "OVER", "ECR", "EWR",         \
+                       "EBOL", "EEOL",                                 \
+                       0
+
+#ifdef SLC_NAMES
+char *slc_names[] = {
+       SLC_NAMELIST
+};
+#else
+extern char *slc_names[];
+#define        SLC_NAMES SLC_NAMELIST
+#endif
+
+#define        SLC_NAME_OK(x)  ((unsigned int)(x) <= NSLC)
+#define SLC_NAME(x)    slc_names[x]
+
+#define        SLC_NOSUPPORT   0
+#define        SLC_CANTCHANGE  1
+#define        SLC_VARIABLE    2
+#define        SLC_DEFAULT     3
+#define        SLC_LEVELBITS   0x03
+
+#define        SLC_FUNC        0
+#define        SLC_FLAGS       1
+#define        SLC_VALUE       2
+
+#define        SLC_ACK         0x80
+#define        SLC_FLUSHIN     0x40
+#define        SLC_FLUSHOUT    0x20
+
+#define        OLD_ENV_VAR     1
+#define        OLD_ENV_VALUE   0
+#define        NEW_ENV_VAR     0
+#define        NEW_ENV_VALUE   1
+#define        ENV_ESC         2
+#define ENV_USERVAR    3
+
+/*
+ * AUTHENTICATION suboptions
+ */
+
+/*
+ * Who is authenticating who ...
+ */
+#define        AUTH_WHO_CLIENT         0       /* Client authenticating server */
+#define        AUTH_WHO_SERVER         1       /* Server authenticating client */
+#define        AUTH_WHO_MASK           1
+
+/*
+ * amount of authentication done
+ */
+#define        AUTH_HOW_ONE_WAY        0
+#define        AUTH_HOW_MUTUAL         2
+#define        AUTH_HOW_MASK           2
+
+/*
+ * should we be encrypting? (not yet formally standardized)
+ */
+#define AUTH_ENCRYPT_OFF       0
+#define AUTH_ENCRYPT_ON                4
+#define AUTH_ENCRYPT_MASK      4
+
+#define        AUTHTYPE_NULL           0
+#define        AUTHTYPE_KERBEROS_V4    1
+#define        AUTHTYPE_KERBEROS_V5    2
+#define        AUTHTYPE_SPX            3
+#define        AUTHTYPE_MINK           4
+#define        AUTHTYPE_SRA            6
+#define        AUTHTYPE_CNT            7
+
+#define        AUTHTYPE_TEST           99
+
+#ifdef AUTH_NAMES
+const char *authtype_names[] = {
+       "NULL", "KERBEROS_V4", "KERBEROS_V5", "SPX", "MINK", NULL, "SRA",
+       0
+};
+#else
+extern const char *authtype_names[];
+#endif
+
+#define        AUTHTYPE_NAME_OK(x)     ((unsigned int)(x) < AUTHTYPE_CNT)
+#define        AUTHTYPE_NAME(x)        authtype_names[x]
+
+/*
+ * ENCRYPTion suboptions
+ */
+#define        ENCRYPT_IS              0       /* I pick encryption type ... */
+#define        ENCRYPT_SUPPORT         1       /* I support encryption types ... */
+#define        ENCRYPT_REPLY           2       /* Initial setup response */
+#define        ENCRYPT_START           3       /* Am starting to send encrypted */
+#define        ENCRYPT_END             4       /* Am ending encrypted */
+#define        ENCRYPT_REQSTART        5       /* Request you start encrypting */
+#define        ENCRYPT_REQEND          6       /* Request you send encrypting */
+#define        ENCRYPT_ENC_KEYID       7
+#define        ENCRYPT_DEC_KEYID       8
+#define        ENCRYPT_CNT             9
+
+#define        ENCTYPE_ANY             0
+#define        ENCTYPE_DES_CFB64       1
+#define        ENCTYPE_DES_OFB64       2
+#define        ENCTYPE_CNT             3
+
+#ifdef ENCRYPT_NAMES
+const char *encrypt_names[] = {
+       "IS", "SUPPORT", "REPLY", "START", "END",
+       "REQUEST-START", "REQUEST-END", "ENC-KEYID", "DEC-KEYID",
+       0
+};
+const char *enctype_names[] = {
+       "ANY", "DES_CFB64",  "DES_OFB64",
+       0
+};
+#else
+extern const char *encrypt_names[];
+extern const char *enctype_names[];
+#endif
+
+
+#define        ENCRYPT_NAME_OK(x)      ((unsigned int)(x) < ENCRYPT_CNT)
+#define        ENCRYPT_NAME(x)         encrypt_names[x]
+
+#define        ENCTYPE_NAME_OK(x)      ((unsigned int)(x) < ENCTYPE_CNT)
+#define        ENCTYPE_NAME(x)         enctype_names[x]
+
+#endif /* _ARPA_TELNET_H_ */
diff --git a/nbsd_include/arpa/tftp.h b/nbsd_include/arpa/tftp.h
new file mode 100644 (file)
index 0000000..70c3356
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: tftp.h,v 1.8 2003/08/07 09:44:12 agc Exp $     */
+
+/*
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)tftp.h      8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _ARPA_TFTP_H_
+#define        _ARPA_TFTP_H_
+
+/*
+ * Trivial File Transfer Protocol (IEN-133)
+ */
+#define        SEGSIZE         512     /* data segment size */
+#define        MAXSEGSIZE      65464   /* maximum negotiated data segment size */
+
+#define PKTSIZE                SEGSIZE + 4
+#define MAXPKTSIZE     MAXSEGSIZE + 4
+
+/*
+ * Packet types.
+ */
+#define        RRQ     01                      /* read request */
+#define        WRQ     02                      /* write request */
+#define        DATA    03                      /* data packet */
+#define        ACK     04                      /* acknowledgement */
+#define        ERROR   05                      /* error code */
+#define        OACK    06                      /* option acknowledgement */
+
+struct tftphdr {
+       short   th_opcode;              /* packet type */
+       union {
+               unsigned short tu_block; /* block # */
+               short   tu_code;        /* error code */
+               char    tu_stuff[1];    /* request packet stuff */
+       } th_u;
+       char    th_data[1];             /* data or error string */
+};
+
+#define        th_block        th_u.tu_block
+#define        th_code         th_u.tu_code
+#define        th_stuff        th_u.tu_stuff
+#define        th_msg          th_data
+
+/*
+ * Error codes.
+ */
+#define        EUNDEF          0               /* not defined */
+#define        ENOTFOUND       1               /* file not found */
+#define        EACCESS         2               /* access violation */
+#define        ENOSPACE        3               /* disk full or allocation exceeded */
+#define        EBADOP          4               /* illegal TFTP operation */
+#define        EBADID          5               /* unknown transfer ID */
+#define        EEXISTS         6               /* file already exists */
+#define        ENOUSER         7               /* no such user */
+#define        EOPTNEG         8               /* option negotiation failed */
+
+#endif /* _ARPA_TFTP_H_ */
diff --git a/nbsd_include/assert.h b/nbsd_include/assert.h
new file mode 100644 (file)
index 0000000..95d3034
--- /dev/null
@@ -0,0 +1,106 @@
+/*     $NetBSD: assert.h,v 1.20 2008/11/02 14:27:44 christos Exp $     */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     @(#)assert.h    8.2 (Berkeley) 1/21/94
+ */
+
+/*
+ * Unlike other ANSI header files, <assert.h> may usefully be included
+ * multiple times, with and without NDEBUG defined.
+ */
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <sys/null.h>
+
+#undef assert
+
+#ifdef NDEBUG
+# ifndef __lint__
+#  define assert(e)    (__static_cast(void,0))
+# else /* !__lint__ */
+#  define assert(e)
+# endif /* __lint__ */
+#else /* !NDEBUG */
+# if __STDC__
+#  define assert(e)                                                    \
+       ((e) ? __static_cast(void,0) : __assert13(__FILE__, __LINE__,   \
+                                                 __assert_function__, #e))
+# else /* PCC */
+#  define assert(e)                                                    \
+       ((e) ? __static_cast(void,0) : __assert13(__FILE__, __LINE__,   \
+                                                 __assert_function__, "e"))
+# endif /* !__STDC__ */
+#endif /* NDEBUG */
+
+#undef _DIAGASSERT
+#if !defined(_DIAGNOSTIC)
+# if !defined(__lint__)
+#  define _DIAGASSERT(e) (__static_cast(void,0))
+# else /* !__lint__ */
+#  define _DIAGASSERT(e)
+# endif /* __lint__ */
+#else /* _DIAGNOSTIC */
+# if __STDC__
+#  define _DIAGASSERT(e)                                               \
+       ((e) ? __static_cast(void,0) : __diagassert13(__FILE__, __LINE__, \
+                                                     __assert_function__, #e))
+# else /* !__STDC__ */
+#  define _DIAGASSERT(e)                                               \
+       ((e) ? __static_cast(void,0) : __diagassert13(__FILE__, __LINE__, \
+                                                     __assert_function__, "e"))
+# endif
+#endif /* _DIAGNOSTIC */
+
+
+#if defined(__lint__)
+#define        __assert_function__     (__static_cast(const void *,0))
+#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+#define        __assert_function__     __func__
+#elif __GNUC_PREREQ__(2, 6)
+#define        __assert_function__     __PRETTY_FUNCTION__
+#else
+#define        __assert_function__     (__static_cast(const void *,0))
+#endif
+
+#ifndef __ASSERT_DECLARED
+#define __ASSERT_DECLARED
+__BEGIN_DECLS
+void __assert(const char *, int, const char *);
+void __assert13(const char *, int, const char *, const char *);
+void __diagassert(const char *, int, const char *);
+void __diagassert13(const char *, int, const char *, const char *);
+__END_DECLS
+#endif /* __ASSERT_DECLARED */
diff --git a/nbsd_include/atomic.h b/nbsd_include/atomic.h
new file mode 100644 (file)
index 0000000..71c6dcd
--- /dev/null
@@ -0,0 +1,29 @@
+/*     $NetBSD: atomic.h,v 1.1 2008/05/28 12:28:12 ad Exp $    */
+
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/atomic.h>
diff --git a/nbsd_include/bitstring.h b/nbsd_include/bitstring.h
new file mode 100644 (file)
index 0000000..36065d9
--- /dev/null
@@ -0,0 +1,134 @@
+/*     $NetBSD: bitstring.h,v 1.9 2010/05/06 18:54:22 christos Exp $   */
+
+/*
+ * Copyright (c) 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Paul Vixie.
+ *
+ * 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. 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.
+ *
+ *     @(#)bitstring.h 8.1 (Berkeley) 7/19/93
+ */
+
+#ifndef _BITSTRING_H_
+#define        _BITSTRING_H_
+
+/* modified for SV/AT and bitstring bugfix by M.R.Murphy, 11oct91
+ * bitstr_size changed gratuitously, but shorter
+ * bit_alloc   spelling error fixed
+ * the following were efficient, but didn't work, they've been made to
+ * work, but are no longer as efficient :-)
+ * bit_nclear, bit_nset, bit_ffc, bit_ffs
+ */
+/*
+ * The comment above may or may not bear any resemblance to reality.
+ * This code has been maintained in a confusing way, with little
+ * information available on the provenance of much of it. "At least it
+ * works."
+ *  /s/ Perry E. Metzger, 2 Feb 98
+ */
+typedef        unsigned char bitstr_t;
+
+/* internal macros */
+                               /* byte of the bitstring bit is in */
+#define        _bit_byte(bit) \
+       (uint32_t)((bit) >> 3)
+
+                               /* mask for the bit within its byte */
+#define        _bit_mask(bit) \
+       (uint32_t)((1 << (uint32_t)((bit)&0x7)))
+
+/* external macros */
+                               /* bytes in a bitstring of nbits bits */
+#define        bitstr_size(nbits) \
+       (size_t)((uint32_t)((nbits) + 7) >> 3)
+
+                               /* allocate a bitstring */
+#define        bit_alloc(nbits) \
+       calloc(bitstr_size(nbits), sizeof(bitstr_t))
+
+                               /* allocate a bitstring on the stack */
+#define        bit_decl(name, nbits) \
+       ((name)[bitstr_size(nbits)])
+
+                               /* is bit N of bitstring name set? */
+#define        bit_test(name, bit) \
+       /*LINTED bitwise on signed*/((name)[_bit_byte(bit)] & _bit_mask(bit))
+
+                               /* set bit N of bitstring name */
+#define        bit_set(name, bit) \
+       /*LINTED bitwise on signed*/((name)[_bit_byte(bit)] |= _bit_mask(bit))
+
+                               /* clear bit N of bitstring name */
+#define        bit_clear(name, bit) \
+       /*LINTED bitwise on signed*/((name)[_bit_byte(bit)] &= ~_bit_mask(bit))
+
+                               /* clear bits start ... stop in bitstring */
+#define        bit_nclear(name, start, stop) do { \
+       bitstr_t *_name = name; \
+       int _start = start, _stop = stop; \
+       while (_start <= _stop) { \
+               bit_clear(_name, _start); \
+               _start++; \
+       } \
+} while(/*CONSTCOND*/0)
+
+                               /* set bits start ... stop in bitstring */
+#define        bit_nset(name, start, stop) do { \
+       bitstr_t *_name = name; \
+       int _start = start, _stop = stop; \
+       while (_start <= _stop) { \
+               bit_set(_name, _start); \
+               _start++; \
+       } \
+} while(/*CONSTCOND*/0)
+
+                               /* find first bit clear in name */
+#define        bit_ffc(name, nbits, value) do { \
+       bitstr_t *_name = name; \
+       int _bit, _nbits = nbits, _value = -1; \
+       for (_bit = 0; _bit < _nbits; ++_bit) \
+               if (!bit_test(_name, _bit)) { \
+                       _value = _bit; \
+                       break; \
+               } \
+       *(value) = _value; \
+} while(/*CONSTCOND*/0)
+
+                               /* find first bit set in name */
+#define        bit_ffs(name, nbits, value) do { \
+       bitstr_t *_name = name; \
+       int _bit, _nbits = nbits, _value = -1; \
+       for (_bit = 0; _bit < _nbits; ++_bit) \
+               if (bit_test(_name, _bit)) { \
+                       _value = _bit; \
+                       break; \
+               } \
+       *(value) = _value; \
+} while(/*CONSTCOND*/0)
+
+#endif /* !_BITSTRING_H_ */
diff --git a/nbsd_include/bm.h b/nbsd_include/bm.h
new file mode 100644 (file)
index 0000000..13edc08
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: bm.h,v 1.5 2005/02/03 04:39:32 perry Exp $     */
+
+/*-
+ * Copyright (c) 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Andrew Hume of AT&T Bell Laboratories.
+ *
+ * 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. 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.
+ *
+ *     @(#)bm.h        8.6 (Berkeley) 6/21/94
+ */
+
+#ifndef _BM_H_
+#define        _BM_H_
+
+typedef struct {
+       u_char  *pat;                   /* pattern */
+       size_t   patlen;                /* pattern length */
+       size_t  *delta;                 /* skip delta */
+       int      rarec;                 /* rare character */
+       size_t   rareoff;               /* rare offset */
+       size_t   md2;                   /* mini delta */
+} bm_pat;
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+bm_pat *bm_comp(u_char const *, size_t, u_char const *);
+u_char *bm_exec(bm_pat *, u_char *, size_t);
+void    bm_free(bm_pat *);
+__END_DECLS
+
+#endif /* !_BM_H_ */
diff --git a/nbsd_include/cdbr.h b/nbsd_include/cdbr.h
new file mode 100644 (file)
index 0000000..6a2e35c
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: cdbr.h,v 1.1 2010/04/25 00:54:45 joerg Exp $   */
+/*-
+ * Copyright (c) 2010 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Joerg Sonnenberger.
+ *
+ * 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 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 HOLDERS 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        _CDBR_H
+#define        _CDBR_H
+
+#include <sys/cdefs.h>
+#include <inttypes.h>
+#include <stddef.h>
+
+#define        CDBR_DEFAULT    0
+
+struct cdbr;
+
+__BEGIN_DECLS
+
+struct cdbr    *cdbr_open(const char *, int);
+uint32_t        cdbr_entries(struct cdbr *);
+int             cdbr_get(struct cdbr *, uint32_t, const void **, size_t *);
+int             cdbr_find(struct cdbr *, const void *, size_t,
+    const void **, size_t *);
+void            cdbr_close(struct cdbr *);
+
+__END_DECLS
+
+#endif /* _CDBR_H */
diff --git a/nbsd_include/cdbw.h b/nbsd_include/cdbw.h
new file mode 100644 (file)
index 0000000..3625705
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: cdbw.h,v 1.1 2010/04/25 00:54:45 joerg Exp $   */
+/*-
+ * Copyright (c) 2010 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Joerg Sonnenberger.
+ *
+ * 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 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 HOLDERS 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        _CDBW_H
+#define        _CDBW_H
+
+#include <sys/cdefs.h>
+#include <inttypes.h>
+#include <stddef.h>
+
+struct cdbw;
+
+__BEGIN_DECLS
+
+struct cdbw    *cdbw_open(void);
+int             cdbw_put(struct cdbw *, const void *, size_t,
+    const void *, size_t);
+int             cdbw_put_data(struct cdbw *, const void *, size_t,
+    uint32_t *);
+int             cdbw_put_key(struct cdbw *, const void *, size_t,
+    uint32_t);
+int             cdbw_output(struct cdbw *, int, const char[16],
+    uint32_t (*)(void));
+void            cdbw_close(struct cdbw *);
+
+__END_DECLS
+
+#endif /* _CDBW_H */
diff --git a/nbsd_include/complex.h b/nbsd_include/complex.h
new file mode 100644 (file)
index 0000000..332be6f
--- /dev/null
@@ -0,0 +1,121 @@
+/* $NetBSD: complex.h,v 1.3 2010/09/15 16:11:30 christos Exp $ */
+
+/*
+ * Written by Matthias Drochner.
+ * Public domain.
+ */
+
+#ifndef        _COMPLEX_H
+#define        _COMPLEX_H
+
+#define complex _Complex
+#define _Complex_I 1.0fi
+#define I _Complex_I
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+
+/* 7.3.5 Trigonometric functions */
+/* 7.3.5.1 The cacos functions */
+double complex cacos(double complex);
+float complex cacosf(float complex);
+
+/* 7.3.5.2 The casin functions */
+double complex casin(double complex);
+float complex casinf(float complex);
+
+/* 7.3.5.1 The catan functions */
+double complex catan(double complex);
+float complex catanf(float complex);
+
+/* 7.3.5.1 The ccos functions */
+double complex ccos(double complex);
+float complex ccosf(float complex);
+
+/* 7.3.5.1 The csin functions */
+double complex csin(double complex);
+float complex csinf(float complex);
+
+/* 7.3.5.1 The ctan functions */
+double complex ctan(double complex);
+float complex ctanf(float complex);
+
+/* 7.3.6 Hyperbolic functions */
+/* 7.3.6.1 The cacosh functions */
+double complex cacosh(double complex);
+float complex cacoshf(float complex);
+
+/* 7.3.6.2 The casinh functions */
+double complex casinh(double complex);
+float complex casinhf(float complex);
+
+/* 7.3.6.3 The catanh functions */
+double complex catanh(double complex);
+float complex catanhf(float complex);
+
+/* 7.3.6.4 The ccosh functions */
+double complex ccosh(double complex);
+float complex ccoshf(float complex);
+
+/* 7.3.6.5 The csinh functions */
+double complex csinh(double complex);
+float complex csinhf(float complex);
+
+/* 7.3.6.6 The ctanh functions */
+double complex ctanh(double complex);
+float complex ctanhf(float complex);
+
+/* 7.3.7 Exponential and logarithmic functions */
+/* 7.3.7.1 The cexp functions */
+double complex cexp(double complex);
+float complex cexpf(float complex);
+
+/* 7.3.7.2 The clog functions */
+double complex clog(double complex);
+float complex clogf(float complex);
+
+/* 7.3.8 Power and absolute-value functions */
+/* 7.3.8.1 The cabs functions */
+#ifndef __LIBM0_SOURCE__
+/* avoid conflict with historical cabs(struct complex) */
+double cabs(double complex) __RENAME(__c99_cabs);
+float cabsf(float complex) __RENAME(__c99_cabsf);
+#endif
+
+/* 7.3.8.2 The cpow functions */
+double complex cpow(double complex, double complex);
+float complex cpowf(float complex, float complex);
+
+/* 7.3.8.3 The csqrt functions */
+double complex csqrt(double complex);
+float complex csqrtf(float complex);
+
+/* 7.3.9 Manipulation functions */
+/* 7.3.9.1 The carg functions */ 
+double carg(double complex);
+float cargf(float complex);
+
+/* 7.3.9.2 The cimag functions */
+double cimag(double complex);
+float cimagf(float complex);
+long double cimagl(long double complex);
+
+/* 7.3.9.3 The conj functions */
+double complex conj(double complex);
+float complex conjf(float complex);
+long double complex conjl(long double complex);
+
+/* 7.3.9.4 The cproj functions */
+double complex cproj(double complex);
+float complex cprojf(float complex);
+long double complex cprojl(long double complex);
+
+/* 7.3.9.5 The creal functions */
+double creal(double complex);
+float crealf(float complex);
+long double creall(long double complex);
+
+__END_DECLS
+
+#endif /* ! _COMPLEX_H */
diff --git a/nbsd_include/cpio.h b/nbsd_include/cpio.h
new file mode 100644 (file)
index 0000000..b0af1f8
--- /dev/null
@@ -0,0 +1,58 @@
+/*     $NetBSD: cpio.h,v 1.3 2008/04/28 20:22:54 martin Exp $  */
+
+/*-
+ * Copyright (c) 1996 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _CPIO_H_
+#define _CPIO_H_
+
+#define C_IRUSR                0000400
+#define C_IWUSR                0000200
+#define C_IXUSR                0000100
+#define C_IRGRP                0000040
+#define C_IWGRP                0000020
+#define C_IXGRP                0000010
+#define C_IROTH                0000004
+#define C_IWOTH                0000002
+#define C_IXOTH                0000001
+#define C_ISUID                0004000
+#define C_ISGID                0002000
+#define C_ISVTX                0001000
+#define C_ISDIR                0040000
+#define C_ISFIFO       0010000
+#define C_ISREG                0100000
+#define C_ISBLK                0060000
+#define C_ISCHR                0020000
+#define C_ISCTG                0110000
+#define C_ISLNK                0120000
+#define C_ISSOCK       0140000
+#define MAGIC          "070707"
+
+#endif /* _CPIO_H_ */
diff --git a/nbsd_include/ctype.h b/nbsd_include/ctype.h
new file mode 100644 (file)
index 0000000..daef1b8
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: ctype.h,v 1.31 2010/06/01 13:52:08 tnozaki Exp $       */
+
+/*
+ * Copyright (c) 1989 The Regents of the University of California.
+ * All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     @(#)ctype.h     5.3 (Berkeley) 4/3/91
+ */
+
+#ifndef _CTYPE_H_
+#define _CTYPE_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+
+__BEGIN_DECLS
+int    isalnum(int);
+int    isalpha(int);
+int    iscntrl(int);
+int    isdigit(int);
+int    isgraph(int);
+int    islower(int);
+int    isprint(int);
+int    ispunct(int);
+int    isspace(int);
+int    isupper(int);
+int    isxdigit(int);
+int    tolower(int);
+int    toupper(int);
+
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+int    isascii(int);
+int    toascii(int);
+int    _tolower(int);
+int    _toupper(int);
+#endif
+
+#if defined(_ISOC99_SOURCE) || (_POSIX_C_SOURCE - 0) > 200112L || \
+    (_XOPEN_SOURCE - 0) > 600 || defined(_NETBSD_SOURCE)
+int    isblank(int);
+#endif
+__END_DECLS
+
+#if defined(_NETBSD_SOURCE) && !defined(_CTYPE_NOINLINE)
+#include <sys/ctype_inline.h>
+#endif
+
+#endif /* !_CTYPE_H_ */
diff --git a/nbsd_include/db.h b/nbsd_include/db.h
new file mode 100644 (file)
index 0000000..6e2fb7d
--- /dev/null
@@ -0,0 +1,226 @@
+/*     $NetBSD: db.h,v 1.24 2008/08/26 21:18:38 joerg Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993, 1994
+ *     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.
+ * 3. 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.
+ *
+ *     @(#)db.h        8.7 (Berkeley) 6/16/94
+ */
+
+#ifndef _DB_H_
+#define        _DB_H_
+
+#include <sys/types.h>
+#include <sys/cdefs.h>
+
+#include <limits.h>
+
+#define        RET_ERROR       -1              /* Return values. */
+#define        RET_SUCCESS      0
+#define        RET_SPECIAL      1
+
+#define        MAX_PAGE_NUMBER 0xffffffff      /* >= # of pages in a file */
+typedef uint32_t       pgno_t;
+#define        MAX_PAGE_OFFSET 65535           /* >= # of bytes in a page */
+typedef uint16_t       indx_t;
+#define        MAX_REC_NUMBER  0xffffffff      /* >= # of records in a tree */
+typedef uint32_t       recno_t;
+
+/* Key/data structure -- a Data-Base Thang. */
+typedef struct {
+       void    *data;                  /* data */
+       size_t   size;                  /* data length */
+} DBT;
+
+/* Routine flags. */
+#define        R_CURSOR        1               /* del, put, seq */
+#define        __R_UNUSED      2               /* UNUSED */
+#define        R_FIRST         3               /* seq */
+#define        R_IAFTER        4               /* put (RECNO) */
+#define        R_IBEFORE       5               /* put (RECNO) */
+#define        R_LAST          6               /* seq (BTREE, RECNO) */
+#define        R_NEXT          7               /* seq */
+#define        R_NOOVERWRITE   8               /* put */
+#define        R_PREV          9               /* seq (BTREE, RECNO) */
+#define        R_SETCURSOR     10              /* put (RECNO) */
+#define        R_RECNOSYNC     11              /* sync (RECNO) */
+
+typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE;
+
+/*
+ * !!!
+ * The following flags are included in the dbopen(3) call as part of the
+ * open(2) flags.  In order to avoid conflicts with the open flags, start
+ * at the top of the 16 or 32-bit number space and work our way down.  If
+ * the open flags were significantly expanded in the future, it could be
+ * a problem.  Wish I'd left another flags word in the dbopen call.
+ *
+ * !!!
+ * None of this stuff is implemented yet.  The only reason that it's here
+ * is so that the access methods can skip copying the key/data pair when
+ * the DB_LOCK flag isn't set.
+ */
+#if UINT_MAX > 65535
+#define        DB_LOCK         0x20000000      /* Do locking. */
+#define        DB_SHMEM        0x40000000      /* Use shared memory. */
+#define        DB_TXN          0x80000000      /* Do transactions. */
+#else
+#define        DB_LOCK             0x2000      /* Do locking. */
+#define        DB_SHMEM            0x4000      /* Use shared memory. */
+#define        DB_TXN              0x8000      /* Do transactions. */
+#endif
+
+/* Access method description structure. */
+typedef struct __db {
+       DBTYPE type;                    /* Underlying db type. */
+       int (*close)    (struct __db *);
+       int (*del)      (const struct __db *, const DBT *, unsigned int);
+       int (*get)      (const struct __db *, const DBT *, DBT *, unsigned int);
+       int (*put)      (const struct __db *, DBT *, const DBT *, unsigned int);
+       int (*seq)      (const struct __db *, DBT *, DBT *, unsigned int);
+       int (*sync)     (const struct __db *, unsigned int);
+       void *internal;                 /* Access method private. */
+       int (*fd)       (const struct __db *);
+} DB;
+
+#define        BTREEMAGIC      0x053162
+#define        BTREEVERSION    3
+
+/* Structure used to pass parameters to the btree routines. */
+typedef struct {
+#define        R_DUP           0x01    /* duplicate keys */
+       unsigned long   flags;
+       unsigned int    cachesize;      /* bytes to cache */
+       int             maxkeypage;     /* maximum keys per page */
+       int             minkeypage;     /* minimum keys per page */
+       unsigned int    psize;          /* page size */
+       int     (*compare)      /* comparison function */
+               (const DBT *, const DBT *);
+       size_t  (*prefix)       /* prefix function */
+               (const DBT *, const DBT *);
+       int     lorder;         /* byte order */
+} BTREEINFO;
+
+#define        HASHMAGIC       0x061561
+#define        HASHVERSION     2
+
+/* Structure used to pass parameters to the hashing routines. */
+typedef struct {
+       unsigned int    bsize;          /* bucket size */
+       unsigned int    ffactor;        /* fill factor */
+       unsigned int    nelem;          /* number of elements */
+       unsigned int    cachesize;      /* bytes to cache */
+       uint32_t                /* hash function */
+               (*hash)(const void *, size_t);
+       int     lorder;         /* byte order */
+} HASHINFO;
+
+/* Structure used to pass parameters to the record routines. */
+typedef struct {
+#define        R_FIXEDLEN      0x01    /* fixed-length records */
+#define        R_NOKEY         0x02    /* key not required */
+#define        R_SNAPSHOT      0x04    /* snapshot the input */
+       unsigned long   flags;
+       unsigned int    cachesize;      /* bytes to cache */
+       unsigned int    psize;          /* page size */
+       int             lorder;         /* byte order */
+       size_t          reclen;         /* record length (fixed-length records) */
+       uint8_t         bval;           /* delimiting byte (variable-length records */
+       char            *bfname;        /* btree file name */ 
+} RECNOINFO;
+
+#ifdef __DBINTERFACE_PRIVATE
+/*
+ * Little endian <==> big endian 32-bit swap macros.
+ *     M_32_SWAP       swap a memory location
+ *     P_32_SWAP       swap a referenced memory location
+ *     P_32_COPY       swap from one location to another
+ */
+#define        M_32_SWAP(a) {                                                  \
+       uint32_t _tmp = a;                                              \
+       ((char *)(void *)&a)[0] = ((char *)(void *)&_tmp)[3];           \
+       ((char *)(void *)&a)[1] = ((char *)(void *)&_tmp)[2];           \
+       ((char *)(void *)&a)[2] = ((char *)(void *)&_tmp)[1];           \
+       ((char *)(void *)&a)[3] = ((char *)(void *)&_tmp)[0];           \
+}
+#define        P_32_SWAP(a) {                                                  \
+       char  _tmp[4];                                                  \
+       _tmp[0] = ((char *)(void *)a)[0];                               \
+       _tmp[1] = ((char *)(void *)a)[1];                               \
+       _tmp[2] = ((char *)(void *)a)[2];                               \
+       _tmp[3] = ((char *)(void *)a)[3];                               \
+       ((char *)(void *)a)[0] = _tmp[3];                               \
+       ((char *)(void *)a)[1] = _tmp[2];                               \
+       ((char *)(void *)a)[2] = _tmp[1];                               \
+       ((char *)(void *)a)[3] = _tmp[0];                               \
+}
+#define        P_32_COPY(a, b) {                                               \
+       ((char *)(void *)&(b))[0] = ((char *)(void *)&(a))[3];          \
+       ((char *)(void *)&(b))[1] = ((char *)(void *)&(a))[2];          \
+       ((char *)(void *)&(b))[2] = ((char *)(void *)&(a))[1];          \
+       ((char *)(void *)&(b))[3] = ((char *)(void *)&(a))[0];          \
+}
+
+/*
+ * Little endian <==> big endian 16-bit swap macros.
+ *     M_16_SWAP       swap a memory location
+ *     P_16_SWAP       swap a referenced memory location
+ *     P_16_COPY       swap from one location to another
+ */
+#define        M_16_SWAP(a) {                                                  \
+       uint16_t _tmp = a;                                              \
+       ((char *)(void *)&a)[0] = ((char *)(void *)&_tmp)[1];           \
+       ((char *)(void *)&a)[1] = ((char *)(void *)&_tmp)[0];           \
+}
+#define        P_16_SWAP(a) {                                                  \
+       char  _tmp[2];                                                  \
+       _tmp[0] = ((char *)(void *)a)[0];                               \
+       _tmp[1] = ((char *)(void *)a)[1];                               \
+       ((char *)(void *)a)[0] = _tmp[1];                               \
+       ((char *)(void *)a)[1] = _tmp[0];                               \
+}
+#define        P_16_COPY(a, b) {                                               \
+       ((char *)(void *)&(b))[0] = ((char *)(void *)&(a))[1];          \
+       ((char *)(void *)&(b))[1] = ((char *)(void *)&(a))[0];          \
+}
+#endif
+
+__BEGIN_DECLS
+DB *dbopen(const char *, int, mode_t, DBTYPE, const void *);
+
+#ifdef __DBINTERFACE_PRIVATE
+
+#define _DBMASK(a) (~((1ULL << (sizeof(a) * NBBY)) - 1))
+#define _DBFIT(a, t) _DIAGASSERT(((a) & _DBMASK(t)) == 0)
+
+DB     *__bt_open(const char *, int, mode_t, const BTREEINFO *, int);
+DB     *__hash_open(const char *, int, mode_t, const HASHINFO *, int);
+DB     *__rec_open(const char *, int, mode_t, const RECNOINFO *, int);
+void    __dbpanic(DB *);
+#endif
+__END_DECLS
+#endif /* !_DB_H_ */
diff --git a/nbsd_include/dirent.h b/nbsd_include/dirent.h
new file mode 100644 (file)
index 0000000..6598b0e
--- /dev/null
@@ -0,0 +1,116 @@
+/*     $NetBSD: dirent.h,v 1.34 2010/09/26 02:26:59 yamt Exp $ */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ *
+ *     @(#)dirent.h    8.2 (Berkeley) 7/28/94
+ */
+
+#ifndef _DIRENT_H_
+#define _DIRENT_H_
+
+#include <sys/featuretest.h>
+#include <sys/types.h>
+
+/*
+ * The kernel defines the format of directory entries returned by 
+ * the getdents(2) system call.
+ */
+#include <sys/dirent.h>
+
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+#define        d_ino           d_fileno        /* backward compatibility */
+#endif
+
+typedef struct _dirdesc DIR;
+
+#if defined(_NETBSD_SOURCE)
+
+/* definitions for library routines operating on directories. */
+#define        DIRBLKSIZ       1024
+
+/* structure describing an open directory. */
+struct _dirdesc {
+       int     dd_fd;          /* file descriptor associated with directory */
+       long    dd_loc;         /* offset in current buffer */
+       long    dd_size;        /* amount of data returned by getdents */
+       char    *dd_buf;        /* data buffer */
+       int     dd_len;         /* size of data buffer */
+       off_t   dd_seek;        /* magic cookie returned by getdents */
+       void    *dd_internal;   /* state for seekdir/telldir */
+       int     dd_flags;       /* flags for readdir */
+       void    *dd_lock;       /* lock for concurrent access */
+};
+
+#define        dirfd(dirp)     ((dirp)->dd_fd)
+
+/* flags for __opendir2() */
+#define DTF_HIDEW      0x0001  /* hide whiteout entries */
+#define DTF_NODUP      0x0002  /* don't return duplicate names */
+#define DTF_REWIND     0x0004  /* rewind after reading union stack */
+#define __DTF_READALL  0x0008  /* everything has been read */
+#define __DTF_RETRY_ON_BADCOOKIE 0x0001        /* retry on EINVAL
+                                       (only valid with __DTF_READALL) */
+
+#include <sys/null.h>
+
+#endif
+
+#ifndef _KERNEL
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+int closedir(DIR *);
+void rewinddir(DIR *);
+#ifndef __LIBC12_SOURCE__
+DIR *opendir(const char *) __RENAME(__opendir30);
+struct dirent *readdir(DIR *) __RENAME(__readdir30);
+int readdir_r(DIR * __restrict, struct dirent * __restrict,
+    struct dirent ** __restrict) __RENAME(__readdir_r30);
+#endif
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+void seekdir(DIR *, long);
+long telldir(DIR *);
+#endif /* defined(_NETBSD_SOURCE) || defined(_XOPEN_SOURCE) */
+#if defined(_NETBSD_SOURCE)
+#ifndef __LIBC12_SOURCE__
+DIR *fdopendir(int);
+DIR *__opendir2(const char *, int) __RENAME(__opendir230);
+int scandir(const char *, struct dirent ***,
+    int (*)(const struct dirent *), int (*)(const void *, const void *))
+    __RENAME(__scandir30);
+int getdents(int, char *, size_t) __RENAME(__getdents30);
+int alphasort(const void *, const void *) __RENAME(__alphasort30);
+#endif
+#endif /* defined(_NETBSD_SOURCE) */
+__END_DECLS
+
+#endif /* !_KERNEL */
+
+#endif /* !_DIRENT_H_ */
diff --git a/nbsd_include/disktab.h b/nbsd_include/disktab.h
new file mode 100644 (file)
index 0000000..8ee7279
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: disktab.h,v 1.10 2005/02/03 04:39:32 perry Exp $       */
+
+/*
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)disktab.h   8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef        _DISKTAB_H_
+#define        _DISKTAB_H_
+
+#include <sys/cdefs.h>
+
+/*
+ * Disk description table, see disktab(5)
+ */
+#define        _PATH_DISKTAB   "/etc/disktab"
+
+__BEGIN_DECLS
+int setdisktab(const char *);
+struct disklabel *getdiskbyname(const char *);
+__END_DECLS
+
+#endif /* !_DISKTAB_H_ */
diff --git a/nbsd_include/dlfcn.h b/nbsd_include/dlfcn.h
new file mode 100644 (file)
index 0000000..d50fe64
--- /dev/null
@@ -0,0 +1,113 @@
+/*     $NetBSD: dlfcn.h,v 1.22 2010/12/24 12:41:42 skrll Exp $ */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Paul Kranenburg.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _DLFCN_H_
+#define _DLFCN_H_
+
+#include <sys/featuretest.h>
+#include <sys/cdefs.h>
+
+#if defined(_NETBSD_SOURCE)
+typedef struct _dl_info {
+       const char      *dli_fname;     /* File defining the symbol */
+       void            *dli_fbase;     /* Base address */
+       const char      *dli_sname;     /* Symbol name */
+       const void      *dli_saddr;     /* Symbol address */
+} Dl_info;
+#endif /* defined(_NETBSD_SOURCE) */
+
+/*
+ * User interface to the run-time linker.
+ */
+__BEGIN_DECLS
+void   *dlopen(const char *, int);
+int    dlclose(void *);
+void   *dlsym(void * __restrict, const char * __restrict);
+#if defined(_NETBSD_SOURCE)
+int    dladdr(const void * __restrict, Dl_info * __restrict);
+int    dlctl(void *, int, void *);
+int    dlinfo(void *, int, void *);
+#endif
+__aconst char *dlerror(void);
+__END_DECLS
+
+/* Values for dlopen `mode'. */
+#define RTLD_LAZY      1
+#define RTLD_NOW       2
+#define RTLD_GLOBAL    0x100           /* Allow global searches in object */
+#define RTLD_LOCAL     0x200
+#define RTLD_NODELETE  0x01000         /* Do not remove members. */
+#define RTLD_NOLOAD    0x02000         /* Do not load if not already loaded. */
+#if defined(_NETBSD_SOURCE)
+#define DL_LAZY                RTLD_LAZY       /* Compat */
+#endif
+
+/* 
+ * Special handle arguments for dlsym().
+ */   
+#define        RTLD_NEXT       ((void *) -1)   /* Search subsequent objects. */
+#define        RTLD_DEFAULT    ((void *) -2)   /* Use default search algorithm. */
+#define        RTLD_SELF       ((void *) -3)   /* Search the caller itself. */
+
+/*
+ * dlctl() commands
+ */
+#if defined(_NETBSD_SOURCE)
+#define DL_GETERRNO    1
+#define DL_GETSYMBOL   2
+#if 0
+#define DL_SETSRCHPATH x
+#define DL_GETLIST     x
+#define DL_GETREFCNT   x
+#define DL_GETLOADADDR x
+#endif /* 0 */
+#endif /* defined(_NETBSD_SOURCE) */
+
+/*
+ * dlinfo() commands
+ *
+ * From Solaris: http://docs.sun.com/app/docs/doc/816-5168/dlinfo-3c?a=view
+ */
+#if defined(_NETBSD_SOURCE)
+#define RTLD_DI_LINKMAP                3
+#if 0
+#define RTLD_DI_ARGSINFO       1
+#define RTLD_DI_CONFIGADDR     2
+#define RTLD_DI_LMID           4
+#define RTLD_DI_SERINFO                5
+#define RTLD_DI_SERINFOSIZE    6
+#define RTLD_DI_ORIGIN         7
+#define RTLD_DI_GETSIGNAL      8
+#define RTLD_DI_SETSIGNAL      9
+#endif
+#endif /* _NETBSD_SOURCE */
+
+#endif /* !defined(_DLFCN_H_) */
diff --git a/nbsd_include/err.h b/nbsd_include/err.h
new file mode 100644 (file)
index 0000000..b29a971
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: err.h,v 1.15 2010/02/25 18:37:12 joerg Exp $   */
+
+/*-
+ * Copyright (c) 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.
+ * 3. 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.
+ *
+ *     @(#)err.h       8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _ERR_H_
+#define        _ERR_H_
+
+/*
+ * Don't use va_list in the err/warn prototypes.   Va_list is typedef'd in two
+ * places (<machine/varargs.h> and <machine/stdarg.h>), so if we include one
+ * of them here we may collide with the utility's includes.  It's unreasonable
+ * for utilities to have to include one of them to include err.h, so we get
+ * _BSD_VA_LIST_ from <machine/ansi.h> and use it.
+ */
+#include <machine/ansi.h>
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+__dead void    err(int, const char *, ...)
+                    __printflike(2, 3) __dead;
+__dead void    verr(int, const char *, _BSD_VA_LIST_)
+                   __printflike(2, 0) __dead;
+__dead void    errx(int, const char *, ...)
+                    __printflike(2, 3) __dead;
+__dead void    verrx(int, const char *, _BSD_VA_LIST_)
+                   __printflike(2, 0) __dead;
+void           warn(const char *, ...)
+                   __printflike(1, 2);
+void           vwarn(const char *, _BSD_VA_LIST_)
+                   __printflike(1, 0);
+void           warnx(const char *, ...)
+                   __printflike(1, 2);
+void           vwarnx(const char *, _BSD_VA_LIST_)
+                   __printflike(1, 0);
+__END_DECLS
+
+#endif /* !_ERR_H_ */
diff --git a/nbsd_include/errno.h b/nbsd_include/errno.h
new file mode 100644 (file)
index 0000000..d343d63
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: errno.h,v 1.11 2008/03/03 06:57:48 dholland Exp $      */
+
+/*
+ * Copyright (c) 1982, 1986, 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     from: @(#)errno.h       8.5 (Berkeley) 1/21/94
+ */
+
+#ifndef _ERRNO_H_
+#define _ERRNO_H_
+
+#include <sys/cdefs.h>
+#include <sys/errno.h>
+#include <sys/featuretest.h>
+
+__BEGIN_DECLS
+
+/* note: this appears in both errno.h and signal.h */
+#ifndef __errno
+int *__errno(void);
+#define __errno __errno
+#endif
+
+#ifndef errno
+#define errno (*__errno())
+#endif
+
+#if defined(_NETBSD_SOURCE)
+#ifndef __LIBC12_SOURCE__
+extern const int sys_nerr __RENAME(__sys_nerr14);
+extern const char *const *sys_errlist __RENAME(__sys_errlist14);
+#endif
+#endif
+__END_DECLS
+
+#endif /* !_ERRNO_H_ */
diff --git a/nbsd_include/fenv.h b/nbsd_include/fenv.h
new file mode 100644 (file)
index 0000000..dcae51e
--- /dev/null
@@ -0,0 +1,62 @@
+/*     $NetBSD: fenv.h,v 1.2 2010/08/02 17:49:04 joerg Exp $   */
+/*
+ * Copyright (c) 2010 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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(__i386__) && !defined(__amd64__)
+#error "fenv.h is currently not supported for this architecture"
+#endif
+
+#ifndef _FENV_H_
+#define _FENV_H_
+
+#include <machine/fenv.h>
+
+__BEGIN_DECLS
+
+/* Function prototypes */
+int    feclearexcept(int);
+int    fegetexceptflag(fexcept_t *, int);
+int    feraiseexcept(int);
+int    fesetexceptflag(const fexcept_t *, int);
+int    fetestexcept(int);
+int    fegetround(void);
+int    fesetround(int);
+int    fegetenv(fenv_t *);
+int    feholdexcept(fenv_t *);
+int    fesetenv(const fenv_t *);
+int    feupdateenv(const fenv_t *);
+
+#if defined(_NETBSD_SOURCE) || defined(_GNU_SOURCE)
+
+int    feenableexcept(int mask);
+int    fedisableexcept(int mask);
+int    fegetexcept(void);
+
+#endif /* _NETBDS_SOURCE || _GNU_SOURCE */
+
+__END_DECLS
+
+#endif /* ! _FENV_H_ */
diff --git a/nbsd_include/fmtmsg.h b/nbsd_include/fmtmsg.h
new file mode 100644 (file)
index 0000000..4724b35
--- /dev/null
@@ -0,0 +1,81 @@
+/*     $NetBSD: fmtmsg.h,v 1.3 2008/04/28 20:22:54 martin Exp $        */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _FMTMSG_H_
+#define _FMTMSG_H_
+
+/* Major Classifications: identifies the source of the condition. */
+#define MM_HARD                0x01L   /* Hardware */
+#define MM_SOFT                0x02L   /* Software */
+#define MM_FIRM                0x03L   /* Firmware */
+
+/* Message Source Subclassifications: type of software. */
+#define MM_APPL                0x04L   /* Application */
+#define MM_UTIL                0x08L   /* Utility */
+#define MM_OPSYS       0x0cL   /* Operating system */
+
+/* Display Subclassifications: where to display the message. */
+#define MM_PRINT       0x10L   /* Display on standard error */
+#define MM_CONSOLE     0x20L   /* Display on system console */
+
+/* Status subclassifications: whether the application will recover. */
+#define MM_RECOVER     0x40L   /* Recoverable */
+#define MM_NRECOV      0x80L   /* Non-recoverable */
+
+/* Severity: seriousness of the condition. */
+#define MM_NOSEV       0       /* No severity level provided */
+#define MM_HALT                1       /* Error causing application to halt */
+#define MM_ERROR       2       /* Encountered a non-fatal fault */
+#define MM_WARNING     3       /* Unusual non-error condition */
+#define MM_INFO                4       /* Informative message */
+
+/* `Null' values for message components. */
+#define MM_NULLMC      0L              /* `Null' classsification component */
+#define MM_NULLLBL     (char *)0       /* `Null' label component */
+#define MM_NULLSEV     0               /* `Null' severity component */
+#define MM_NULLTXT     (char *)0       /* `Null' text component */
+#define MM_NULLACT     (char *)0       /* `Null' action component */
+#define MM_NULLTAG     (char *)0       /* `Null' tag component */
+
+/* Return values for fmtmsg(). */
+#define MM_OK          0       /* Function succeeded */
+#define MM_NOTOK       (-1)    /* Function failed completely */
+#define MM_NOMSG       0x01    /* Unable to perform MM_PRINT */
+#define MM_NOCON       0x02    /* Unable to perform MM_CONSOLE */
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+int    fmtmsg(long, const char *, int, const char *, const char *,
+           const char *);
+__END_DECLS
+
+#endif /* !_FMTMSG_H_ */
diff --git a/nbsd_include/fnmatch.h b/nbsd_include/fnmatch.h
new file mode 100644 (file)
index 0000000..b7533d5
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: fnmatch.h,v 1.12 2005/02/03 04:39:32 perry Exp $       */
+
+/*-
+ * Copyright (c) 1992, 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.
+ * 3. 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.
+ *
+ *     @(#)fnmatch.h   8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef        _FNMATCH_H_
+#define        _FNMATCH_H_
+
+#include <sys/featuretest.h>
+
+#define        FNM_NOMATCH     1       /* Match failed. */
+#define        FNM_NOSYS       2       /* Function not implemented. */
+
+#define        FNM_NOESCAPE    0x01    /* Disable backslash escaping. */
+#define        FNM_PATHNAME    0x02    /* Slash must be matched by slash. */
+#define        FNM_PERIOD      0x04    /* Period must be matched by period. */
+#if defined(_NETBSD_SOURCE)
+#define        FNM_CASEFOLD    0x08    /* Pattern is matched case-insensitive */
+#define        FNM_LEADING_DIR 0x10    /* Ignore /<tail> after Imatch. */
+#endif
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+int     fnmatch(const char *, const char *, int);
+__END_DECLS
+
+#endif /* !_FNMATCH_H_ */
diff --git a/nbsd_include/fstab.h b/nbsd_include/fstab.h
new file mode 100644 (file)
index 0000000..dd986bb
--- /dev/null
@@ -0,0 +1,78 @@
+/*     $NetBSD: fstab.h,v 1.11 2005/02/03 04:39:32 perry Exp $ */
+
+/*
+ * Copyright (c) 1980, 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.
+ * 3. 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.
+ *
+ *     @(#)fstab.h     8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _FSTAB_H_
+#define _FSTAB_H_
+
+#include <sys/cdefs.h>
+
+/*
+ * File system table, see fstab(5).
+ *
+ * Used by dump, mount, umount, swapon, fsck, df, ...
+ *
+ * For ufs fs_spec field is the block special name.  Programs that want to
+ * use the character special name must create that name by prepending a 'r'
+ * after the right most slash.  Quota files are always named "quotas", so
+ * if type is "rq", then use concatenation of fs_file and "quotas" to locate
+ * quota file.
+ */
+#define        _PATH_FSTAB     "/etc/fstab"
+#define        FSTAB           "/etc/fstab"    /* deprecated */
+
+#define        FSTAB_RW        "rw"            /* read/write device */
+#define        FSTAB_RQ        "rq"            /* read/write with quotas */
+#define        FSTAB_RO        "ro"            /* read-only device */
+#define        FSTAB_SW        "sw"            /* swap device */
+#define        FSTAB_DP        "dp"            /* dump device */
+#define        FSTAB_XX        "xx"            /* ignore totally */
+
+struct fstab {
+       __aconst char *fs_spec;         /* block special device name */
+       __aconst char *fs_file;         /* file system path prefix */
+       __aconst char *fs_vfstype;      /* File system type, ufs, nfs */
+       __aconst char *fs_mntops;       /* Mount options ala -o */
+       __aconst char *fs_type;         /* FSTAB_* from fs_mntops */
+       int     fs_freq;                /* dump frequency, in days */
+       int     fs_passno;              /* pass number on parallel fsck */
+};
+
+__BEGIN_DECLS
+struct fstab *getfsent(void);
+struct fstab *getfsspec(const char *);
+struct fstab *getfsfile(const char *);
+int setfsent(void);
+void endfsent(void);
+__END_DECLS
+
+#endif /* !_FSTAB_H_ */
diff --git a/nbsd_include/fts.h b/nbsd_include/fts.h
new file mode 100644 (file)
index 0000000..394948c
--- /dev/null
@@ -0,0 +1,151 @@
+/*     $NetBSD: fts.h,v 1.19 2009/08/16 19:33:38 christos Exp $        */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ *
+ *     @(#)fts.h       8.3 (Berkeley) 8/14/94
+ */
+
+#ifndef        _FTS_H_
+#define        _FTS_H_
+
+#ifndef        __fts_stat_t
+#define        __fts_stat_t    struct stat
+#endif
+#ifndef        __fts_nlink_t
+#define        __fts_nlink_t   nlink_t
+#endif
+#ifndef        __fts_ino_t
+#define        __fts_ino_t     ino_t
+#endif
+#ifndef        __fts_length_t
+#define        __fts_length_t  unsigned int
+#endif
+#ifndef        __fts_number_t
+#define        __fts_number_t  int64_t
+#endif
+#ifndef        __fts_dev_t
+#define        __fts_dev_t     dev_t
+#endif
+#ifndef        __fts_level_t
+#define        __fts_level_t   int
+#endif
+
+typedef struct {
+       struct _ftsent *fts_cur;        /* current node */
+       struct _ftsent *fts_child;      /* linked list of children */
+       struct _ftsent **fts_array;     /* sort array */
+       dev_t fts_dev;                  /* starting device # */
+       char *fts_path;                 /* path for this descent */
+       int fts_rfd;                    /* fd for root */
+       unsigned int fts_pathlen;       /* sizeof(path) */
+       unsigned int fts_nitems;        /* elements in the sort array */
+       int (*fts_compar)               /* compare function */
+               (const struct _ftsent **, const struct _ftsent **);
+
+#define        FTS_COMFOLLOW   0x001           /* follow command line symlinks */
+#define        FTS_LOGICAL     0x002           /* logical walk */
+#define        FTS_NOCHDIR     0x004           /* don't change directories */
+#define        FTS_NOSTAT      0x008           /* don't get stat info */
+#define        FTS_PHYSICAL    0x010           /* physical walk */
+#define        FTS_SEEDOT      0x020           /* return dot and dot-dot */
+#define        FTS_XDEV        0x040           /* don't cross devices */
+#define        FTS_WHITEOUT    0x080           /* return whiteout information */
+#define        FTS_OPTIONMASK  0x0ff           /* valid user option mask */
+
+#define        FTS_NAMEONLY    0x100           /* (private) child names only */
+#define        FTS_STOP        0x200           /* (private) unrecoverable error */
+       int fts_options;                /* fts_open options, global flags */
+} FTS;
+
+typedef struct _ftsent {
+       struct _ftsent *fts_cycle;      /* cycle node */
+       struct _ftsent *fts_parent;     /* parent directory */
+       struct _ftsent *fts_link;       /* next file in directory */
+       __fts_number_t fts_number;      /* local numeric value */
+       void *fts_pointer;              /* local address value */
+       char *fts_accpath;              /* access path */
+       char *fts_path;                 /* root path */
+       int fts_errno;                  /* errno for this node */
+       int fts_symfd;                  /* fd for symlink */
+       __fts_length_t fts_pathlen;     /* strlen(fts_path) */
+       __fts_length_t fts_namelen;     /* strlen(fts_name) */
+
+       __fts_ino_t fts_ino;            /* inode */
+       __fts_dev_t fts_dev;            /* device */
+       __fts_nlink_t fts_nlink;        /* link count */
+
+#define        FTS_ROOTPARENTLEVEL     -1
+#define        FTS_ROOTLEVEL            0
+       __fts_level_t fts_level;                /* depth (-1 to N) */
+
+#define        FTS_D            1              /* preorder directory */
+#define        FTS_DC           2              /* directory that causes cycles */
+#define        FTS_DEFAULT      3              /* none of the above */
+#define        FTS_DNR          4              /* unreadable directory */
+#define        FTS_DOT          5              /* dot or dot-dot */
+#define        FTS_DP           6              /* postorder directory */
+#define        FTS_ERR          7              /* error; errno is set */
+#define        FTS_F            8              /* regular file */
+#define        FTS_INIT         9              /* initialized only */
+#define        FTS_NS          10              /* stat(2) failed */
+#define        FTS_NSOK        11              /* no stat(2) requested */
+#define        FTS_SL          12              /* symbolic link */
+#define        FTS_SLNONE      13              /* symbolic link without target */
+#define        FTS_W           14              /* whiteout object */
+       unsigned short fts_info;        /* user flags for FTSENT structure */
+
+#define        FTS_DONTCHDIR    0x01           /* don't chdir .. to the parent */
+#define        FTS_SYMFOLLOW    0x02           /* followed a symlink to get here */
+#define        FTS_ISW          0x04           /* this is a whiteout object */
+       unsigned short fts_flags;       /* private flags for FTSENT structure */
+
+#define        FTS_AGAIN        1              /* read node again */
+#define        FTS_FOLLOW       2              /* follow symbolic link */
+#define        FTS_NOINSTR      3              /* no instructions */
+#define        FTS_SKIP         4              /* discard node */
+       unsigned short fts_instr;       /* fts_set() instructions */
+
+       __fts_stat_t *fts_statp;        /* stat(2) information */
+       char fts_name[1];               /* file name */
+} FTSENT;
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+#ifndef        __LIBC12_SOURCE__
+FTSENT *fts_children(FTS *, int)               __RENAME(__fts_children60);
+int     fts_close(FTS *)                       __RENAME(__fts_close60);
+FTS    *fts_open(char * const *, int,
+    int (*)(const FTSENT **, const FTSENT **)) __RENAME(__fts_open60);
+FTSENT *fts_read(FTS *)                        __RENAME(__fts_read60);
+int     fts_set(FTS *, FTSENT *, int)          __RENAME(__fts_set60);
+#endif
+__END_DECLS
+
+#endif /* !_FTS_H_ */
diff --git a/nbsd_include/ftw.h b/nbsd_include/ftw.h
new file mode 100644 (file)
index 0000000..3bebea3
--- /dev/null
@@ -0,0 +1,62 @@
+/* $NetBSD: ftw.h,v 1.1 2005/12/30 23:07:33 agc Exp $ */
+
+/*     From OpenBSD: ftw.h,v 1.1 2003/07/21 21:13:18 millert Exp       */
+
+/*
+ * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
+ *
+ * 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.
+ *
+ * Sponsored in part by the Defense Advanced Research Projects
+ * Agency (DARPA) and Air Force Research Laboratory, Air Force
+ * Materiel Command, USAF, under agreement number F39502-99-1-0512.
+ */
+
+#ifndef        _FTW_H
+#define        _FTW_H
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+/*
+ * Valid flags for the 3rd argument to the function that is passed as the
+ * second argument to ftw(3) and nftw(3).  Say it three times fast!
+ */
+#define        FTW_F           0       /* File.  */
+#define        FTW_D           1       /* Directory.  */
+#define        FTW_DNR         2       /* Directory without read permission.  */
+#define        FTW_DP          3       /* Directory with subdirectories visited.  */
+#define        FTW_NS          4       /* Unknown type; stat() failed.  */
+#define        FTW_SL          5       /* Symbolic link.  */
+#define        FTW_SLN         6       /* Sym link that names a nonexistent file.  */
+
+/*
+ * Flags for use as the 4th argument to nftw(3).  These may be ORed together.
+ */
+#define        FTW_PHYS        0x01    /* Physical walk, don't follow sym links.  */
+#define        FTW_MOUNT       0x02    /* The walk does not cross a mount point.  */
+#define        FTW_DEPTH       0x04    /* Subdirs visited before the dir itself. */
+#define        FTW_CHDIR       0x08    /* Change to a directory before reading it. */
+
+struct FTW {
+       int base;
+       int level;
+};
+
+__BEGIN_DECLS
+int    ftw(const char *, int (*)(const char *, const struct stat *, int), int);
+int    nftw(const char *, int (*)(const char *, const struct stat *, int,
+           struct FTW *), int, int);
+__END_DECLS
+
+#endif /* !_FTW_H */
diff --git a/nbsd_include/getopt.h b/nbsd_include/getopt.h
new file mode 100644 (file)
index 0000000..71409fe
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: getopt.h,v 1.11 2008/04/28 20:22:54 martin Exp $       */
+
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dieter Baron and Thomas Klausner.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _GETOPT_H_
+#define _GETOPT_H_
+
+#include <sys/cdefs.h>
+#include <unistd.h>
+
+/*
+ * Gnu like getopt_long() and BSD4.4 getsubopt()/optreset extensions
+ */
+#define no_argument        0
+#define required_argument  1
+#define optional_argument  2
+
+struct option {
+       /* name of long option */
+       const char *name;
+       /*
+        * one of no_argument, required_argument, and optional_argument:
+        * whether option takes an argument
+        */
+       int has_arg;
+       /* if not NULL, set *flag to val when option found */
+       int *flag;
+       /* if flag not NULL, value to set *flag to; else return value */
+       int val;
+};
+
+__BEGIN_DECLS
+int getopt_long(int, char * const *, const char *,
+    const struct option *, int *);
+__END_DECLS
+#endif /* !_GETOPT_H_ */
diff --git a/nbsd_include/glob.h b/nbsd_include/glob.h
new file mode 100644 (file)
index 0000000..1111a1c
--- /dev/null
@@ -0,0 +1,113 @@
+/*     $NetBSD: glob.h,v 1.26 2010/09/06 14:38:56 christos Exp $       */
+
+/*
+ * Copyright (c) 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Guido van Rossum.
+ *
+ * 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. 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.
+ *
+ *     @(#)glob.h      8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _GLOB_H_
+#define        _GLOB_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#ifndef __gl_size_t
+#define __gl_size_t    size_t
+#endif
+#ifndef __gl_stat_t
+#define __gl_stat_t    struct stat
+#endif
+
+typedef struct {
+       __gl_size_t gl_pathc;   /* Count of total paths so far. */
+       __gl_size_t gl_matchc;  /* Count of paths matching pattern. */
+       __gl_size_t gl_offs;    /* Reserved at beginning of gl_pathv. */
+       int gl_flags;           /* Copy of flags parameter to glob. */
+       char **gl_pathv;        /* List of paths matching pattern. */
+                               /* Copy of errfunc parameter to glob. */
+       int (*gl_errfunc)(const char *, int);
+
+       /*
+        * Alternate filesystem access methods for glob; replacement
+        * versions of closedir(3), readdir(3), opendir(3), stat(2)
+        * and lstat(2).
+        */
+       void (*gl_closedir)(void *);
+       struct dirent *(*gl_readdir)(void *);   
+       void *(*gl_opendir)(const char *);
+       int (*gl_lstat)(const char *, __gl_stat_t *);
+       int (*gl_stat)(const char *, __gl_stat_t *);
+} glob_t;
+
+#define        GLOB_APPEND     0x0001  /* Append to output from previous call. */
+#define        GLOB_DOOFFS     0x0002  /* Use gl_offs. */
+#define        GLOB_ERR        0x0004  /* Return on error. */
+#define        GLOB_MARK       0x0008  /* Append / to matching directories. */
+#define        GLOB_NOCHECK    0x0010  /* Return pattern itself if nothing matches. */
+#define        GLOB_NOSORT     0x0020  /* Don't sort. */
+#define        GLOB_NOESCAPE   0x1000  /* Disable backslash escaping. */
+
+#define        GLOB_NOSPACE    (-1)    /* Malloc call failed. */
+#define        GLOB_ABORTED    (-2)    /* Unignored error. */
+#define        GLOB_NOMATCH    (-3)    /* No match, and GLOB_NOCHECK was not set. */
+#define        GLOB_NOSYS      (-4)    /* Implementation does not support function. */
+
+#if defined(_NETBSD_SOURCE) || defined(HAVE_NBTOOL_CONFIG_H)
+#define        GLOB_ALTDIRFUNC 0x0040  /* Use alternately specified directory funcs. */
+#define        GLOB_BRACE      0x0080  /* Expand braces ala csh. */
+#define        GLOB_MAGCHAR    0x0100  /* Pattern had globbing characters. */
+#define        GLOB_NOMAGIC    0x0200  /* GLOB_NOCHECK without magic chars (csh). */
+#define        GLOB_LIMIT      0x0400  /* Limit memory used by matches to ARG_MAX */
+#define        GLOB_TILDE      0x0800  /* Expand tilde names from the passwd file. */
+/*     GLOB_NOESCAPE   0x1000  above */
+#define        GLOB_PERIOD     0x2000  /* Allow metachars to match leading periods. */
+#define        GLOB_NO_DOTDIRS 0x4000  /* Make . and .. vanish from wildcards. */
+#define        GLOB_STAR       0x8000  /* Use glob ** to recurse directories */
+#define        GLOB_QUOTE      0       /* source compatibility */
+
+#define        GLOB_ABEND      GLOB_ABORTED    /* source compatibility */
+#endif
+
+__BEGIN_DECLS
+#ifndef __LIBC12_SOURCE__
+int    glob(const char * __restrict, int,
+    int (*)(const char *, int), glob_t * __restrict)    __RENAME(__glob30);
+void   globfree(glob_t *)                               __RENAME(__globfree30);
+#endif
+#ifdef _NETBSD_SOURCE
+int    glob_pattern_p(const char *, int);
+#endif
+__END_DECLS
+
+#endif /* !_GLOB_H_ */
diff --git a/nbsd_include/grp.h b/nbsd_include/grp.h
new file mode 100644 (file)
index 0000000..9c74784
--- /dev/null
@@ -0,0 +1,84 @@
+/*     $NetBSD: grp.h,v 1.24 2007/10/19 15:58:52 christos Exp $        */
+
+/*-
+ * Copyright (c) 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     @(#)grp.h       8.2 (Berkeley) 1/21/94
+ */
+
+#ifndef _GRP_H_
+#define        _GRP_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <sys/types.h>
+
+#if defined(_NETBSD_SOURCE)
+#define        _PATH_GROUP             "/etc/group"
+#endif
+
+struct group {
+       __aconst char *gr_name;                 /* group name */
+       __aconst char *gr_passwd;               /* group password */
+       gid_t   gr_gid;                         /* group id */
+       __aconst char *__aconst *gr_mem;        /* group members */
+};
+
+__BEGIN_DECLS
+struct group   *getgrgid(gid_t);
+struct group   *getgrnam(const char *);
+#if (_POSIX_C_SOURCE - 0) >= 199506L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_REENTRANT) || defined(_NETBSD_SOURCE)
+int             getgrgid_r(gid_t, struct group *, char *, size_t,
+                               struct group **);
+int             getgrnam_r(const char *, struct group *, char *, size_t,
+                               struct group **);
+#endif
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+struct group   *getgrent(void);
+void            setgrent(void);
+void            endgrent(void);
+#endif
+#if defined(_NETBSD_SOURCE)
+void            setgrfile(const char *);
+int             setgroupent(int);
+int             getgrent_r(struct group *, char *, size_t, struct group **);
+const char     *group_from_gid(gid_t, int);
+int             gid_from_group(const char *, gid_t *);
+int             pwcache_groupdb(int (*)(int), void (*)(void),
+                                   struct group * (*)(const char *),
+                                   struct group * (*)(gid_t));
+#endif
+__END_DECLS
+
+#endif /* !_GRP_H_ */
diff --git a/nbsd_include/heimdal/config.h b/nbsd_include/heimdal/config.h
new file mode 100644 (file)
index 0000000..965e28c
--- /dev/null
@@ -0,0 +1,1477 @@
+/* include/config.h.  Generated from config.h.in by configure.  */
+/* include/config.h.in.  Generated from configure.in by autoheader.  */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#else
+
+#if 0
+#ifndef __RCSID
+#define __RCSID(msg) \
+static /**/const char *const rcsid[] = { (const char *)rcsid, "@(#)" msg }
+#endif
+#endif
+
+/* Maximum values on all known systems */
+#define MaxHostNameLen (64+4)
+#define MaxPathLen (1024+4)
+
+
+
+#ifdef BUILD_KRB5_LIB
+#ifndef KRB5_LIB_FUNCTION
+#ifdef _WIN32_
+#define KRB5_LIB_FUNCTION _export _stdcall
+#else
+#define KRB5_LIB_FUNCTION
+#endif
+#endif
+#endif
+
+
+#ifdef BUILD_ROKEN_LIB
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32_
+#define ROKEN_LIB_FUNCTION _export _stdcall
+#else
+#define ROKEN_LIB_FUNCTION
+#endif
+#endif
+#endif
+
+
+/* Define if you want authentication support in telnet. */
+#define AUTHENTICATION 1
+
+/* path to bin */
+#define BINDIR "/usr/heimdal/bin"
+
+/* Define if realloc(NULL) doesn't work. */
+/* #undef BROKEN_REALLOC */
+
+/* Define if you want support for DCE/DFS PAG's. */
+/* #undef DCE */
+
+/* Define if you want to use DES encryption in telnet. */
+#define DES_ENCRYPTION 1
+
+/* Define this to enable diagnostics in telnet. */
+#define DIAGNOSTICS 1
+
+/* Define if want to use the weak AFS string to key functions. */
+#define ENABLE_AFS_STRING_TO_KEY 1
+
+/* Define if you want have a thread safe libraries */
+#define ENABLE_PTHREAD_SUPPORT 1
+
+/* Define if you want encryption support in telnet. */
+#define ENCRYPTION 1
+
+/* define if sys/param.h defines the endiness */
+#define ENDIANESS_IN_SYS_PARAM_H 1
+
+/* Define this if you want support for broken ENV_{VAR,VAL} telnets. */
+/* #undef ENV_HACK */
+
+/* define if prototype of gethostbyaddr is compatible with struct hostent
+   *gethostbyaddr(const void *, size_t, int) */
+/* #undef GETHOSTBYADDR_PROTO_COMPATIBLE */
+
+/* define if prototype of gethostbyname is compatible with struct hostent
+   *gethostbyname(const char *) */
+#define GETHOSTBYNAME_PROTO_COMPATIBLE 1
+
+/* define if prototype of getservbyname is compatible with struct servent
+   *getservbyname(const char *, const char *) */
+#define GETSERVBYNAME_PROTO_COMPATIBLE 1
+
+/* define if prototype of getsockname is compatible with int getsockname(int,
+   struct sockaddr*, socklen_t*) */
+#define GETSOCKNAME_PROTO_COMPATIBLE 1
+
+/* Define if you have the `altzone' variable. */
+/* #undef HAVE_ALTZONE */
+
+/* Define to 1 if you have the `arc4random' function. */
+#define HAVE_ARC4RANDOM 1
+
+/* Define to 1 if you have the <arpa/ftp.h> header file. */
+#define HAVE_ARPA_FTP_H 1
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+#define HAVE_ARPA_INET_H 1
+
+/* Define to 1 if you have the <arpa/nameser.h> header file. */
+#define HAVE_ARPA_NAMESER_H 1
+
+/* Define to 1 if you have the <arpa/telnet.h> header file. */
+#define HAVE_ARPA_TELNET_H 1
+
+/* Define to 1 if you have the `asnprintf' function. */
+/* #undef HAVE_ASNPRINTF */
+
+/* Define to 1 if you have the `asprintf' function. */
+#define HAVE_ASPRINTF 1
+
+/* Define to 1 if you have the `atexit' function. */
+#define HAVE_ATEXIT 1
+
+/* Define to 1 if you have the <bind/bitypes.h> header file. */
+/* #undef HAVE_BIND_BITYPES_H */
+
+/* Define to 1 if you have the <bsdsetjmp.h> header file. */
+/* #undef HAVE_BSDSETJMP_H */
+
+/* Define to 1 if you have the `bswap16' function. */
+#define HAVE_BSWAP16 1
+
+/* Define to 1 if you have the `bswap32' function. */
+#define HAVE_BSWAP32 1
+
+/* Define to 1 if you have the <capability.h> header file. */
+/* #undef HAVE_CAPABILITY_H */
+
+/* Define to 1 if you have the `cap_set_proc' function. */
+/* #undef HAVE_CAP_SET_PROC */
+
+/* Define to 1 if you have the `cgetent' function. */
+#define HAVE_CGETENT 1
+
+/* Define if you have the function `chown'. */
+#define HAVE_CHOWN 1
+
+/* Define if you have the function `closefrom'. */
+#define HAVE_CLOSEFROM 1
+
+/* Define to 1 if you have the <config.h> header file. */
+/* #undef HAVE_CONFIG_H */
+
+/* Define if you have the function `copyhostent'. */
+/* #undef HAVE_COPYHOSTENT */
+
+/* Define to 1 if you have the `crypt' function. */
+#define HAVE_CRYPT 1
+
+/* Define to 1 if you have the <crypt.h> header file. */
+/* #undef HAVE_CRYPT_H */
+
+/* Define to 1 if you have the <curses.h> header file. */
+#define HAVE_CURSES_H 1
+
+/* Define if you have the function `daemon'. */
+#define HAVE_DAEMON 1
+
+/* define if you have a berkeley db1/2 library */
+#define HAVE_DB1 1
+
+/* define if you have a berkeley db3/4 library */
+/* #undef HAVE_DB3 */
+
+/* Define to 1 if you have the <db3/db.h> header file. */
+/* #undef HAVE_DB3_DB_H */
+
+/* Define to 1 if you have the <db4/db.h> header file. */
+/* #undef HAVE_DB4_DB_H */
+
+/* Define to 1 if you have the `dbm_firstkey' function. */
+#define HAVE_DBM_FIRSTKEY 1
+
+/* Define to 1 if you have the <dbm.h> header file. */
+/* #undef HAVE_DBM_H */
+
+/* Define to 1 if you have the `dbopen' function. */
+#define HAVE_DBOPEN 1
+
+/* Define to 1 if you have the <db_185.h> header file. */
+/* #undef HAVE_DB_185_H */
+
+/* Define to 1 if you have the `db_create' function. */
+/* #undef HAVE_DB_CREATE */
+
+/* Define to 1 if you have the <db.h> header file. */
+#define HAVE_DB_H 1
+
+/* define if you have ndbm compat in db */
+/* #undef HAVE_DB_NDBM */
+
+/* Define to 1 if you have the declaration of `altzone', and to 0 if you
+   don't. */
+/* #undef HAVE_DECL_ALTZONE */
+
+/* Define to 1 if you have the declaration of `environ', and to 0 if you
+   don't. */
+#define HAVE_DECL_ENVIRON 0
+
+/* Define to 1 if you have the declaration of `h_errlist', and to 0 if you
+   don't. */
+#define HAVE_DECL_H_ERRLIST 0
+
+/* Define to 1 if you have the declaration of `h_errno', and to 0 if you
+   don't. */
+#define HAVE_DECL_H_ERRNO 1
+
+/* Define to 1 if you have the declaration of `h_nerr', and to 0 if you don't.
+   */
+#define HAVE_DECL_H_NERR 0
+
+/* Define to 1 if you have the declaration of `optarg', and to 0 if you don't.
+   */
+#define HAVE_DECL_OPTARG 1
+
+/* Define to 1 if you have the declaration of `opterr', and to 0 if you don't.
+   */
+#define HAVE_DECL_OPTERR 1
+
+/* Define to 1 if you have the declaration of `optind', and to 0 if you don't.
+   */
+#define HAVE_DECL_OPTIND 1
+
+/* Define to 1 if you have the declaration of `optopt', and to 0 if you don't.
+   */
+#define HAVE_DECL_OPTOPT 1
+
+/* Define to 1 if you have the declaration of `timezone', and to 0 if you
+   don't. */
+#define HAVE_DECL_TIMEZONE 1
+
+/* Define to 1 if you have the declaration of `_res', and to 0 if you don't.
+   */
+#define HAVE_DECL__RES 1
+
+/* Define to 1 if you have the declaration of `__progname', and to 0 if you
+   don't. */
+#define HAVE_DECL___PROGNAME 0
+
+/* Define to 1 if you have the <dirent.h> header file. */
+#define HAVE_DIRENT_H 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define to 1 if you have the `dlopen' function. */
+#define HAVE_DLOPEN 1
+
+/* Define to 1 if you have the `dn_expand' function. */
+#define HAVE_DN_EXPAND 1
+
+/* Define to 1 if you have the `door_create' function. */
+/* #undef HAVE_DOOR_CREATE */
+
+/* Define if you have the function `ecalloc'. */
+/* #undef HAVE_ECALLOC */
+
+/* Define to 1 if you have the `el_init' function. */
+#define HAVE_EL_INIT 1
+
+/* Define if you have the function `emalloc'. */
+/* #undef HAVE_EMALLOC */
+
+/* Define if you have the function `erealloc'. */
+/* #undef HAVE_EREALLOC */
+
+/* Define if you have the function `err'. */
+#define HAVE_ERR 1
+
+/* Define to 1 if you have the <errno.h> header file. */
+#define HAVE_ERRNO_H 1
+
+/* Define if you have the function `errx'. */
+#define HAVE_ERRX 1
+
+/* Define to 1 if you have the <err.h> header file. */
+#define HAVE_ERR_H 1
+
+/* Define if you have the function `estrdup'. */
+/* #undef HAVE_ESTRDUP */
+
+/* Define if you have the function `fchown'. */
+#define HAVE_FCHOWN 1
+
+/* Define to 1 if you have the `fcntl' function. */
+#define HAVE_FCNTL 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define HAVE_FCNTL_H 1
+
+/* Define if you have the function `flock'. */
+#define HAVE_FLOCK 1
+
+/* Define if you have the function `fnmatch'. */
+#define HAVE_FNMATCH 1
+
+/* Define to 1 if you have the <fnmatch.h> header file. */
+#define HAVE_FNMATCH_H 1
+
+/* Define if el_init takes four arguments. */
+#define HAVE_FOUR_VALUED_EL_INIT 1
+
+/* Have -framework Security */
+/* #undef HAVE_FRAMEWORK_SECURITY */
+
+/* Define to 1 if you have the `freeaddrinfo' function. */
+#define HAVE_FREEADDRINFO 1
+
+/* Define if you have the function `freehostent'. */
+/* #undef HAVE_FREEHOSTENT */
+
+/* Define to 1 if you have the `gai_strerror' function. */
+#define HAVE_GAI_STRERROR 1
+
+/* Define to 1 if you have the <gdbm/ndbm.h> header file. */
+/* #undef HAVE_GDBM_NDBM_H */
+
+/* Define to 1 if you have the `getaddrinfo' function. */
+#define HAVE_GETADDRINFO 1
+
+/* Define to 1 if you have the `getconfattr' function. */
+/* #undef HAVE_GETCONFATTR */
+
+/* Define if you have the function `getcwd'. */
+#define HAVE_GETCWD 1
+
+/* Define if you have the function `getdtablesize'. */
+#define HAVE_GETDTABLESIZE 1
+
+/* Define if you have the function `getegid'. */
+#define HAVE_GETEGID 1
+
+/* Define if you have the function `geteuid'. */
+#define HAVE_GETEUID 1
+
+/* Define if you have the function `getgid'. */
+#define HAVE_GETGID 1
+
+/* Define to 1 if you have the `gethostbyname' function. */
+#define HAVE_GETHOSTBYNAME 1
+
+/* Define to 1 if you have the `gethostbyname2' function. */
+#define HAVE_GETHOSTBYNAME2 1
+
+/* Define if you have the function `gethostname'. */
+#define HAVE_GETHOSTNAME 1
+
+/* Define if you have the function `getifaddrs'. */
+#define HAVE_GETIFADDRS 1
+
+/* Define if you have the function `getipnodebyaddr'. */
+/* #undef HAVE_GETIPNODEBYADDR */
+
+/* Define if you have the function `getipnodebyname'. */
+/* #undef HAVE_GETIPNODEBYNAME */
+
+/* Define to 1 if you have the `getlogin' function. */
+#define HAVE_GETLOGIN 1
+
+/* Define if you have a working getmsg. */
+/* #undef HAVE_GETMSG */
+
+/* Define to 1 if you have the `getnameinfo' function. */
+#define HAVE_GETNAMEINFO 1
+
+/* Define if you have the function `getopt'. */
+#define HAVE_GETOPT 1
+
+/* Define to 1 if you have the `getpagesize' function. */
+#define HAVE_GETPAGESIZE 1
+
+/* Define to 1 if you have the `getpeereid' function. */
+/* #undef HAVE_GETPEEREID */
+
+/* Define to 1 if you have the `getpeerucred' function. */
+/* #undef HAVE_GETPEERUCRED */
+
+/* Define to 1 if you have the `getprogname' function. */
+#define HAVE_GETPROGNAME 1
+
+/* Define to 1 if you have the `getpwnam_r' function. */
+#define HAVE_GETPWNAM_R 1
+
+/* Define to 1 if you have the `getrlimit' function. */
+#define HAVE_GETRLIMIT 1
+
+/* Define to 1 if you have the `getsockopt' function. */
+#define HAVE_GETSOCKOPT 1
+
+/* Define to 1 if you have the `getspnam' function. */
+/* #undef HAVE_GETSPNAM */
+
+/* Define if you have the function `gettimeofday'. */
+#define HAVE_GETTIMEOFDAY 1
+
+/* Define to 1 if you have the `getudbnam' function. */
+/* #undef HAVE_GETUDBNAM */
+
+/* Define if you have the function `getuid'. */
+#define HAVE_GETUID 1
+
+/* Define if you have the function `getusershell'. */
+#define HAVE_GETUSERSHELL 1
+
+/* define if you have a glob() that groks GLOB_BRACE, GLOB_NOCHECK,
+   GLOB_QUOTE, GLOB_TILDE, and GLOB_LIMIT */
+#define HAVE_GLOB 1
+
+/* Define to 1 if you have the `grantpt' function. */
+#define HAVE_GRANTPT 1
+
+/* Define to 1 if you have the <grp.h> header file. */
+#define HAVE_GRP_H 1
+
+/* Define to 1 if you have the `hstrerror' function. */
+#define HAVE_HSTRERROR 1
+
+/* Define if you have the `h_errlist' variable. */
+#define HAVE_H_ERRLIST 1
+
+/* Define if you have the `h_errno' variable. */
+#define HAVE_H_ERRNO 1
+
+/* Define if you have the `h_nerr' variable. */
+#define HAVE_H_NERR 1
+
+/* Define to 1 if you have the <ifaddrs.h> header file. */
+#define HAVE_IFADDRS_H 1
+
+/* Define if you have the in6addr_loopback variable */
+#define HAVE_IN6ADDR_LOOPBACK 1
+
+/* define */
+#define HAVE_INET_ATON 1
+
+/* define */
+#define HAVE_INET_NTOP 1
+
+/* define */
+#define HAVE_INET_PTON 1
+
+/* Define if you have the function `initgroups'. */
+#define HAVE_INITGROUPS 1
+
+/* Define to 1 if you have the `initstate' function. */
+#define HAVE_INITSTATE 1
+
+/* Define if you have the function `innetgr'. */
+#define HAVE_INNETGR 1
+
+/* Define to 1 if the system has the type `int16_t'. */
+#define HAVE_INT16_T 1
+
+/* Define to 1 if the system has the type `int32_t'. */
+#define HAVE_INT32_T 1
+
+/* Define to 1 if the system has the type `int64_t'. */
+#define HAVE_INT64_T 1
+
+/* Define to 1 if the system has the type `int8_t'. */
+#define HAVE_INT8_T 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the <io.h> header file. */
+/* #undef HAVE_IO_H */
+
+/* Define if you have IPv6. */
+/* #define HAVE_IPV6 1 -- defined by Makefile if (${USE_INET6} != "no") */
+
+/* Define if you have the function `iruserok'. */
+#define HAVE_IRUSEROK 1
+
+/* Define to 1 if you have the `issetugid' function. */
+#define HAVE_ISSETUGID 1
+
+/* Define if you want to use the Kerberos Credentials Manager. */
+#define HAVE_KCM 1
+
+/* Define to 1 if you have the <libutil.h> header file. */
+/* #undef HAVE_LIBUTIL_H */
+
+/* Define to 1 if you have the <limits.h> header file. */
+#define HAVE_LIMITS_H 1
+
+/* Define to 1 if you have the `loadquery' function. */
+/* #undef HAVE_LOADQUERY */
+
+/* Define if you have the function `localtime_r'. */
+#define HAVE_LOCALTIME_R 1
+
+/* Define to 1 if you have the `logout' function. */
+#define HAVE_LOGOUT 1
+
+/* Define to 1 if you have the `logwtmp' function. */
+#define HAVE_LOGWTMP 1
+
+/* Define to 1 if the system has the type `long long'. */
+#define HAVE_LONG_LONG 1
+
+/* Define if you have the function `lstat'. */
+#define HAVE_LSTAT 1
+
+/* Define to 1 if you have the <maillock.h> header file. */
+/* #undef HAVE_MAILLOCK_H */
+
+/* Define if you have the function `memmove'. */
+#define HAVE_MEMMOVE 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define if you have the function `mkstemp'. */
+#define HAVE_MKSTEMP 1
+
+/* Define to 1 if you have the `mktime' function. */
+#define HAVE_MKTIME 1
+
+/* Define to 1 if you have a working `mmap' system call. */
+#define HAVE_MMAP 1
+
+/* define if you have a ndbm library */
+#define HAVE_NDBM 1
+
+/* Define to 1 if you have the <ndbm.h> header file. */
+#define HAVE_NDBM_H 1
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#define HAVE_NETDB_H 1
+
+/* Define to 1 if you have the <netgroup.h> header file. */
+#define HAVE_NETGROUP_H 1
+
+/* Define to 1 if you have the <netinet6/in6.h> header file. */
+/* #undef HAVE_NETINET6_IN6_H */
+
+/* Define to 1 if you have the <netinet6/in6_var.h> header file. */
+/* #undef HAVE_NETINET6_IN6_VAR_H */
+
+/* Define to 1 if you have the <netinet/in6.h> header file. */
+/* #undef HAVE_NETINET_IN6_H */
+
+/* Define to 1 if you have the <netinet/in6_machtypes.h> header file. */
+/* #undef HAVE_NETINET_IN6_MACHTYPES_H */
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#define HAVE_NETINET_IN_H 1
+
+/* Define to 1 if you have the <netinet/in_systm.h> header file. */
+#define HAVE_NETINET_IN_SYSTM_H 1
+
+/* Define to 1 if you have the <netinet/ip.h> header file. */
+#define HAVE_NETINET_IP_H 1
+
+/* Define to 1 if you have the <netinet/tcp.h> header file. */
+#define HAVE_NETINET_TCP_H 1
+
+/* Define if you want to use Netinfo instead of krb5.conf. */
+/* #undef HAVE_NETINFO */
+
+/* Define to 1 if you have the <netinfo/ni.h> header file. */
+/* #undef HAVE_NETINFO_NI_H */
+
+/* Define to 1 if you have the <net/if.h> header file. */
+#define HAVE_NET_IF_H 1
+
+/* Define if NDBM really is DB (creates files *.db) */
+#define HAVE_NEW_DB 1
+
+/* Define to 1 if you have the `on_exit' function. */
+/* #undef HAVE_ON_EXIT */
+
+/* Define to 1 if you have the `openpty' function. */
+#define HAVE_OPENPTY 1
+
+/* define to use openssl's libcrypto */
+#define HAVE_OPENSSL 1
+
+/* Define to enable basic OSF C2 support. */
+/* #undef HAVE_OSFC2 */
+
+/* Define to 1 if you have the <paths.h> header file. */
+#define HAVE_PATHS_H 1
+
+/* Define to 1 if you have the `pidfile' function. */
+#define HAVE_PIDFILE 1
+
+/* Define to 1 if you have the `poll' function. */
+#define HAVE_POLL 1
+
+/* Define to 1 if you have the <poll.h> header file. */
+#define HAVE_POLL_H 1
+
+/* Define to 1 if you have the <pthread.h> header file. */
+#define HAVE_PTHREAD_H 1
+
+/* Define to 1 if you have the `ptsname' function. */
+#define HAVE_PTSNAME 1
+
+/* Define to 1 if you have the <pty.h> header file. */
+/* #undef HAVE_PTY_H */
+
+/* Define if you have the function `putenv'. */
+#define HAVE_PUTENV 1
+
+/* Define to 1 if you have the <pwd.h> header file. */
+#define HAVE_PWD_H 1
+
+/* Define to 1 if you have the `rand' function. */
+#define HAVE_RAND 1
+
+/* Define to 1 if you have the `random' function. */
+#define HAVE_RANDOM 1
+
+/* Define if you have the function `rcmd'. */
+#define HAVE_RCMD 1
+
+/* Define if you have a readline compatible library. */
+#define HAVE_READLINE 1
+
+/* Define if you have the function `readv'. */
+#define HAVE_READV 1
+
+/* Define if you have the function `recvmsg'. */
+#define HAVE_RECVMSG 1
+
+/* Define to 1 if you have the <resolv.h> header file. */
+#define HAVE_RESOLV_H 1
+
+/* Define to 1 if you have the `res_ndestroy' function. */
+#define HAVE_RES_NDESTROY 1
+
+/* Define to 1 if you have the `res_nsearch' function. */
+#define HAVE_RES_NSEARCH 1
+
+/* Define to 1 if you have the `res_search' function. */
+#define HAVE_RES_SEARCH 1
+
+/* Define to 1 if you have the `revoke' function. */
+#define HAVE_REVOKE 1
+
+/* Define to 1 if you have the <rpcsvc/ypclnt.h> header file. */
+#define HAVE_RPCSVC_YPCLNT_H 1
+
+/* Define to 1 if you have the <sac.h> header file. */
+/* #undef HAVE_SAC_H */
+
+/* Define to 1 if the system has the type `sa_family_t'. */
+#define HAVE_SA_FAMILY_T 1
+
+/* Define to 1 if you have the <security/pam_modules.h> header file. */
+#define HAVE_SECURITY_PAM_MODULES_H 1
+
+/* Define to 1 if you have the `select' function. */
+#define HAVE_SELECT 1
+
+/* Define if you have the function `sendmsg'. */
+#define HAVE_SENDMSG 1
+
+/* Define if you have the function `setegid'. */
+#define HAVE_SETEGID 1
+
+/* Define if you have the function `setenv'. */
+#define HAVE_SETENV 1
+
+/* Define if you have the function `seteuid'. */
+#define HAVE_SETEUID 1
+
+/* Define to 1 if you have the `setitimer' function. */
+#define HAVE_SETITIMER 1
+
+/* Define to 1 if you have the `setlim' function. */
+/* #undef HAVE_SETLIM */
+
+/* Define to 1 if you have the `setlogin' function. */
+#define HAVE_SETLOGIN 1
+
+/* Define to 1 if you have the `setpcred' function. */
+/* #undef HAVE_SETPCRED */
+
+/* Define to 1 if you have the `setpgid' function. */
+#define HAVE_SETPGID 1
+
+/* Define to 1 if you have the `setproctitle' function. */
+#define HAVE_SETPROCTITLE 1
+
+/* Define to 1 if you have the `setprogname' function. */
+#define HAVE_SETPROGNAME 1
+
+/* Define to 1 if you have the `setregid' function. */
+#define HAVE_SETREGID 1
+
+/* Define to 1 if you have the `setresgid' function. */
+/* #undef HAVE_SETRESGID */
+
+/* Define to 1 if you have the `setresuid' function. */
+/* #undef HAVE_SETRESUID */
+
+/* Define to 1 if you have the `setreuid' function. */
+#define HAVE_SETREUID 1
+
+/* Define to 1 if you have the `setsid' function. */
+#define HAVE_SETSID 1
+
+/* Define to 1 if you have the `setsockopt' function. */
+#define HAVE_SETSOCKOPT 1
+
+/* Define to 1 if you have the `setstate' function. */
+#define HAVE_SETSTATE 1
+
+/* Define to 1 if you have the `setutent' function. */
+#define HAVE_SETUTENT 1
+
+/* Define to 1 if you have the `sgi_getcapabilitybyname' function. */
+/* #undef HAVE_SGI_GETCAPABILITYBYNAME */
+
+/* Define to 1 if you have the <sgtty.h> header file. */
+#define HAVE_SGTTY_H 1
+
+/* Define to 1 if you have the <shadow.h> header file. */
+/* #undef HAVE_SHADOW_H */
+
+/* Define to 1 if you have the <siad.h> header file. */
+/* #undef HAVE_SIAD_H */
+
+/* Define to 1 if you have the `sigaction' function. */
+#define HAVE_SIGACTION 1
+
+/* Define to 1 if you have the <signal.h> header file. */
+#define HAVE_SIGNAL_H 1
+
+/* define if you have a working snprintf */
+#define HAVE_SNPRINTF 1
+
+/* Define to 1 if you have the `socket' function. */
+#define HAVE_SOCKET 1
+
+/* Define to 1 if the system has the type `socklen_t'. */
+#define HAVE_SOCKLEN_T 1
+
+/* Define to 1 if the system has the type `ssize_t'. */
+#define HAVE_SSIZE_T 1
+
+/* Define to 1 if you have the <standards.h> header file. */
+/* #undef HAVE_STANDARDS_H */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define if you have the function `strcasecmp'. */
+#define HAVE_STRCASECMP 1
+
+/* Define if you have the function `strdup'. */
+#define HAVE_STRDUP 1
+
+/* Define if you have the function `strerror'. */
+#define HAVE_STRERROR 1
+
+/* Define if you have the function `strftime'. */
+#define HAVE_STRFTIME 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define if you have the function `strlcat'. */
+#define HAVE_STRLCAT 1
+
+/* Define if you have the function `strlcpy'. */
+#define HAVE_STRLCPY 1
+
+/* Define if you have the function `strlwr'. */
+/* #undef HAVE_STRLWR */
+
+/* Define if you have the function `strncasecmp'. */
+#define HAVE_STRNCASECMP 1
+
+/* Define if you have the function `strndup'. */
+#define HAVE_STRNDUP 1
+
+/* Define if you have the function `strnlen'. */
+/* #undef HAVE_STRNLEN */
+
+/* Define to 1 if you have the <stropts.h> header file. */
+/* #undef HAVE_STROPTS_H */
+
+/* Define if you have the function `strptime'. */
+#define HAVE_STRPTIME 1
+
+/* Define if you have the function `strsep'. */
+#define HAVE_STRSEP 1
+
+/* Define if you have the function `strsep_copy'. */
+/* #undef HAVE_STRSEP_COPY */
+
+/* Define to 1 if you have the `strstr' function. */
+#define HAVE_STRSTR 1
+
+/* Define to 1 if you have the `strsvis' function. */
+#define HAVE_STRSVIS 1
+
+/* Define if you have the function `strtok_r'. */
+#define HAVE_STRTOK_R 1
+
+/* Define to 1 if the system has the type `struct addrinfo'. */
+#define HAVE_STRUCT_ADDRINFO 1
+
+/* Define to 1 if the system has the type `struct ifaddrs'. */
+#define HAVE_STRUCT_IFADDRS 1
+
+/* Define to 1 if the system has the type `struct iovec'. */
+#define HAVE_STRUCT_IOVEC 1
+
+/* Define to 1 if the system has the type `struct msghdr'. */
+#define HAVE_STRUCT_MSGHDR 1
+
+/* Define to 1 if the system has the type `struct sockaddr'. */
+#define HAVE_STRUCT_SOCKADDR 1
+
+/* Define if struct sockaddr has field sa_len. */
+#define HAVE_STRUCT_SOCKADDR_SA_LEN 1
+
+/* Define to 1 if the system has the type `struct sockaddr_storage'. */
+#define HAVE_STRUCT_SOCKADDR_STORAGE 1
+
+/* define if you have struct spwd */
+/* #undef HAVE_STRUCT_SPWD */
+
+/* Define if struct tm has field tm_gmtoff. */
+#define HAVE_STRUCT_TM_TM_GMTOFF 1
+
+/* Define if struct tm has field tm_zone. */
+#define HAVE_STRUCT_TM_TM_ZONE 1
+
+/* Define if struct utmpx has field ut_exit. */
+#define HAVE_STRUCT_UTMPX_UT_EXIT 1
+
+/* Define if struct utmpx has field ut_syslen. */
+/* #undef HAVE_STRUCT_UTMPX_UT_SYSLEN */
+
+/* Define if struct utmp has field ut_addr. */
+/* #undef HAVE_STRUCT_UTMP_UT_ADDR */
+
+/* Define if struct utmp has field ut_host. */
+/* #undef HAVE_STRUCT_UTMP_UT_HOST */
+
+/* Define if struct utmp has field ut_id. */
+/* #undef HAVE_STRUCT_UTMP_UT_ID */
+
+/* Define if struct utmp has field ut_pid. */
+/* #undef HAVE_STRUCT_UTMP_UT_PID */
+
+/* Define if struct utmp has field ut_type. */
+/* #undef HAVE_STRUCT_UTMP_UT_TYPE */
+
+/* Define if struct utmp has field ut_user. */
+/* #undef HAVE_STRUCT_UTMP_UT_USER */
+
+/* define if struct winsize is declared in sys/termios.h */
+#define HAVE_STRUCT_WINSIZE 1
+
+/* Define to 1 if you have the `strunvis' function. */
+#define HAVE_STRUNVIS 1
+
+/* Define if you have the function `strupr'. */
+/* #undef HAVE_STRUPR */
+
+/* Define to 1 if you have the `strvis' function. */
+#define HAVE_STRVIS 1
+
+/* Define to 1 if you have the `strvisx' function. */
+#define HAVE_STRVISX 1
+
+/* Define to 1 if you have the `svis' function. */
+#define HAVE_SVIS 1
+
+/* Define if you have the function `swab'. */
+#define HAVE_SWAB 1
+
+/* Define to 1 if you have the `sysconf' function. */
+#define HAVE_SYSCONF 1
+
+/* Define to 1 if you have the `sysctl' function. */
+#define HAVE_SYSCTL 1
+
+/* Define to 1 if you have the `syslog' function. */
+#define HAVE_SYSLOG 1
+
+/* Define to 1 if you have the <syslog.h> header file. */
+#define HAVE_SYSLOG_H 1
+
+/* Define to 1 if you have the <sys/bitypes.h> header file. */
+/* #undef HAVE_SYS_BITYPES_H */
+
+/* Define to 1 if you have the <sys/bswap.h> header file. */
+#define HAVE_SYS_BSWAP_H 1
+
+/* Define to 1 if you have the <sys/capability.h> header file. */
+/* #undef HAVE_SYS_CAPABILITY_H */
+
+/* Define to 1 if you have the <sys/category.h> header file. */
+/* #undef HAVE_SYS_CATEGORY_H */
+
+/* Define to 1 if you have the <sys/file.h> header file. */
+#define HAVE_SYS_FILE_H 1
+
+/* Define to 1 if you have the <sys/filio.h> header file. */
+#define HAVE_SYS_FILIO_H 1
+
+/* Define to 1 if you have the <sys/ioccom.h> header file. */
+#define HAVE_SYS_IOCCOM_H 1
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#define HAVE_SYS_IOCTL_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#define HAVE_SYS_PARAM_H 1
+
+/* Define to 1 if you have the <sys/proc.h> header file. */
+#define HAVE_SYS_PROC_H 1
+
+/* Define to 1 if you have the <sys/ptyio.h> header file. */
+/* #undef HAVE_SYS_PTYIO_H */
+
+/* Define to 1 if you have the <sys/ptyvar.h> header file. */
+/* #undef HAVE_SYS_PTYVAR_H */
+
+/* Define to 1 if you have the <sys/pty.h> header file. */
+/* #undef HAVE_SYS_PTY_H */
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#define HAVE_SYS_RESOURCE_H 1
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+#define HAVE_SYS_SELECT_H 1
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#define HAVE_SYS_SOCKET_H 1
+
+/* Define to 1 if you have the <sys/sockio.h> header file. */
+#define HAVE_SYS_SOCKIO_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/stream.h> header file. */
+/* #undef HAVE_SYS_STREAM_H */
+
+/* Define to 1 if you have the <sys/stropts.h> header file. */
+/* #undef HAVE_SYS_STROPTS_H */
+
+/* Define to 1 if you have the <sys/strtty.h> header file. */
+/* #undef HAVE_SYS_STRTTY_H */
+
+/* Define to 1 if you have the <sys/str_tty.h> header file. */
+/* #undef HAVE_SYS_STR_TTY_H */
+
+/* Define to 1 if you have the <sys/syscall.h> header file. */
+#define HAVE_SYS_SYSCALL_H 1
+
+/* Define to 1 if you have the <sys/sysctl.h> header file. */
+#define HAVE_SYS_SYSCTL_H 1
+
+/* Define to 1 if you have the <sys/termio.h> header file. */
+/* #undef HAVE_SYS_TERMIO_H */
+
+/* Define to 1 if you have the <sys/timeb.h> header file. */
+#define HAVE_SYS_TIMEB_H 1
+
+/* Define to 1 if you have the <sys/times.h> header file. */
+#define HAVE_SYS_TIMES_H 1
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#define HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/tty.h> header file. */
+#define HAVE_SYS_TTY_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/ucred.h> header file. */
+#define HAVE_SYS_UCRED_H 1
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#define HAVE_SYS_UIO_H 1
+
+/* Define to 1 if you have the <sys/un.h> header file. */
+#define HAVE_SYS_UN_H 1
+
+/* Define to 1 if you have the <sys/utsname.h> header file. */
+#define HAVE_SYS_UTSNAME_H 1
+
+/* Define to 1 if you have the <sys/wait.h> header file. */
+#define HAVE_SYS_WAIT_H 1
+
+/* Define to 1 if you have the <termcap.h> header file. */
+#define HAVE_TERMCAP_H 1
+
+/* Define to 1 if you have the <termios.h> header file. */
+#define HAVE_TERMIOS_H 1
+
+/* Define to 1 if you have the <termio.h> header file. */
+/* #undef HAVE_TERMIO_H */
+
+/* Define to 1 if you have the <term.h> header file. */
+/* #undef HAVE_TERM_H */
+
+/* Define to 1 if you have the `tgetent' function. */
+#define HAVE_TGETENT 1
+
+/* Define if you have the function `timegm'. */
+#define HAVE_TIMEGM 1
+
+/* Define if you have the `timezone' variable. */
+#define HAVE_TIMEZONE 1
+
+/* Define to 1 if you have the <time.h> header file. */
+#define HAVE_TIME_H 1
+
+/* Define to 1 if you have the <tmpdir.h> header file. */
+/* #undef HAVE_TMPDIR_H */
+
+/* Define to 1 if you have the `ttyname' function. */
+#define HAVE_TTYNAME 1
+
+/* Define to 1 if you have the `ttyslot' function. */
+#define HAVE_TTYSLOT 1
+
+/* Define to 1 if you have the <udb.h> header file. */
+/* #undef HAVE_UDB_H */
+
+/* Define to 1 if the system has the type `uint16_t'. */
+#define HAVE_UINT16_T 1
+
+/* Define to 1 if the system has the type `uint32_t'. */
+#define HAVE_UINT32_T 1
+
+/* Define to 1 if the system has the type `uint64_t'. */
+#define HAVE_UINT64_T 1
+
+/* Define to 1 if the system has the type `uint8_t'. */
+#define HAVE_UINT8_T 1
+
+/* Define to 1 if the system has the type `uintptr_t'. */
+#define HAVE_UINTPTR_T 1
+
+/* Define to 1 if you have the `umask' function. */
+#define HAVE_UMASK 1
+
+/* Define to 1 if you have the `uname' function. */
+#define HAVE_UNAME 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the `unlockpt' function. */
+#define HAVE_UNLOCKPT 1
+
+/* Define if you have the function `unsetenv'. */
+#define HAVE_UNSETENV 1
+
+/* Define to 1 if you have the `unvis' function. */
+#define HAVE_UNVIS 1
+
+/* Define to 1 if you have the <userconf.h> header file. */
+/* #undef HAVE_USERCONF_H */
+
+/* Define to 1 if you have the <usersec.h> header file. */
+/* #undef HAVE_USERSEC_H */
+
+/* Define to 1 if you have the <util.h> header file. */
+#define HAVE_UTIL_H 1
+
+/* Define to 1 if you have the <utmpx.h> header file. */
+#define HAVE_UTMPX_H 1
+
+/* Define to 1 if you have the <utmp.h> header file. */
+#define HAVE_UTMP_H 1
+
+/* Define to 1 if the system has the type `u_int16_t'. */
+#define HAVE_U_INT16_T 1
+
+/* Define to 1 if the system has the type `u_int32_t'. */
+#define HAVE_U_INT32_T 1
+
+/* Define to 1 if the system has the type `u_int64_t'. */
+#define HAVE_U_INT64_T 1
+
+/* Define to 1 if the system has the type `u_int8_t'. */
+#define HAVE_U_INT8_T 1
+
+/* Define to 1 if you have the `vasnprintf' function. */
+/* #undef HAVE_VASNPRINTF */
+
+/* Define to 1 if you have the `vasprintf' function. */
+#define HAVE_VASPRINTF 1
+
+/* Define if you have the function `verr'. */
+#define HAVE_VERR 1
+
+/* Define if you have the function `verrx'. */
+#define HAVE_VERRX 1
+
+/* Define to 1 if you have the `vhangup' function. */
+/* #undef HAVE_VHANGUP */
+
+/* Define to 1 if you have the `vis' function. */
+#define HAVE_VIS 1
+
+/* Define to 1 if you have the <vis.h> header file. */
+#define HAVE_VIS_H 1
+
+/* define if you have a working vsnprintf */
+#define HAVE_VSNPRINTF 1
+
+/* Define if you have the function `vsyslog'. */
+#define HAVE_VSYSLOG 1
+
+/* Define if you have the function `vwarn'. */
+#define HAVE_VWARN 1
+
+/* Define if you have the function `vwarnx'. */
+#define HAVE_VWARNX 1
+
+/* Define if you have the function `warn'. */
+#define HAVE_WARN 1
+
+/* Define if you have the function `warnx'. */
+#define HAVE_WARNX 1
+
+/* Define if you have the function `writev'. */
+#define HAVE_WRITEV 1
+
+/* define if struct winsize has ws_xpixel */
+#define HAVE_WS_XPIXEL 1
+
+/* define if struct winsize has ws_ypixel */
+#define HAVE_WS_YPIXEL 1
+
+/* Define to 1 if you have the `XauFileName' function. */
+/* #undef HAVE_XAUFILENAME */
+
+/* Define to 1 if you have the `XauReadAuth' function. */
+/* #undef HAVE_XAUREADAUTH */
+
+/* Define to 1 if you have the `XauWriteAuth' function. */
+/* #undef HAVE_XAUWRITEAUTH */
+
+/* Define to 1 if you have the `yp_get_default_domain' function. */
+#define HAVE_YP_GET_DEFAULT_DOMAIN 1
+
+/* Define to 1 if you have the `_getpty' function. */
+/* #undef HAVE__GETPTY */
+
+/* Define if you have the `_res' variable. */
+#define HAVE__RES 1
+
+/* Define to 1 if you have the `_scrsize' function. */
+/* #undef HAVE__SCRSIZE */
+
+/* define if your compiler has __attribute__ */
+#define HAVE___ATTRIBUTE__ 1
+
+/* Define if you have the `__progname' variable. */
+#define HAVE___PROGNAME 1
+
+/* Define if you have the hesiod package. */
+/* #undef HESIOD */
+
+/* Define if you are running IRIX 4. */
+/* #undef IRIX4 */
+
+/* Enable Kerberos 5 support in applications. */
+#define KRB5 1
+
+/* path to lib */
+#define LIBDIR "/usr/heimdal/lib"
+
+/* path to libexec */
+#define LIBEXECDIR "/usr/heimdal/libexec"
+
+/* path to localstate */
+#define LOCALSTATEDIR "/var/heimdal"
+
+/* define if the system is missing a prototype for asnprintf() */
+#define NEED_ASNPRINTF_PROTO 1
+
+/* define if the system is missing a prototype for asprintf() */
+/* #undef NEED_ASPRINTF_PROTO */
+
+/* define if the system is missing a prototype for crypt() */
+/* #undef NEED_CRYPT_PROTO */
+
+/* define if the system is missing a prototype for daemon() */
+#define NEED_DAEMON_PROTO 1
+
+/* define if the system is missing a prototype for gethostname() */
+/* #undef NEED_GETHOSTNAME_PROTO */
+
+/* define if the system is missing a prototype for getusershell() */
+/* #undef NEED_GETUSERSHELL_PROTO */
+
+/* define if the system is missing a prototype for glob() */
+/* #undef NEED_GLOB_PROTO */
+
+/* define if the system is missing a prototype for hstrerror() */
+/* #undef NEED_HSTRERROR_PROTO */
+
+/* define if the system is missing a prototype for inet_aton() */
+/* #undef NEED_INET_ATON_PROTO */
+
+/* define if the system is missing a prototype for iruserok() */
+/* #undef NEED_IRUSEROK_PROTO */
+
+/* define if the system is missing a prototype for mkstemp() */
+#define NEED_MKSTEMP_PROTO 1
+
+/* define if the system is missing a prototype for setenv() */
+/* #undef NEED_SETENV_PROTO */
+
+/* define if the system is missing a prototype for snprintf() */
+/* #undef NEED_SNPRINTF_PROTO */
+
+/* define if the system is missing a prototype for strndup() */
+/* #undef NEED_STRNDUP_PROTO */
+
+/* define if the system is missing a prototype for strsep() */
+/* #undef NEED_STRSEP_PROTO */
+
+/* define if the system is missing a prototype for strsvis() */
+/* #undef NEED_STRSVIS_PROTO */
+
+/* define if the system is missing a prototype for strtok_r() */
+/* #undef NEED_STRTOK_R_PROTO */
+
+/* define if the system is missing a prototype for strunvis() */
+/* #undef NEED_STRUNVIS_PROTO */
+
+/* define if the system is missing a prototype for strvisx() */
+/* #undef NEED_STRVISX_PROTO */
+
+/* define if the system is missing a prototype for strvis() */
+/* #undef NEED_STRVIS_PROTO */
+
+/* define if the system is missing a prototype for svis() */
+/* #undef NEED_SVIS_PROTO */
+
+/* define if the system is missing a prototype for unsetenv() */
+/* #undef NEED_UNSETENV_PROTO */
+
+/* define if the system is missing a prototype for unvis() */
+/* #undef NEED_UNVIS_PROTO */
+
+/* define if the system is missing a prototype for vasnprintf() */
+#define NEED_VASNPRINTF_PROTO 1
+
+/* define if the system is missing a prototype for vasprintf() */
+/* #undef NEED_VASPRINTF_PROTO */
+
+/* define if the system is missing a prototype for vis() */
+/* #undef NEED_VIS_PROTO */
+
+/* define if the system is missing a prototype for vsnprintf() */
+/* #undef NEED_VSNPRINTF_PROTO */
+
+/* Define if you don't wan't support for AFS. */
+/* #undef NO_AFS */
+
+/* Define to 1 if your C compiler doesn't accept -c and -o together. */
+/* #undef NO_MINUS_C_MINUS_O */
+
+/* Define if you don't want to use mmap. */
+/* #undef NO_MMAP */
+
+/* Define this to enable old environment option in telnet. */
+#define OLD_ENVIRON 1
+
+/* Define if you have the openldap package. */
+/* #undef OPENLDAP */
+
+/* Define if you want support for hdb ldap module */
+/* #undef OPENLDAP_MODULE */
+
+/* define if prototype of openlog is compatible with void openlog(const char
+   *, int, int) */
+#define OPENLOG_PROTO_COMPATIBLE 1
+
+/* Define if you want OTP support in applications. */
+#define OTP 1
+
+/* Name of package */
+#define PACKAGE "heimdal"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "heimdal-bugs@h5l.se"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "Heimdal"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "Heimdal 1.1"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "heimdal"
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "1.1"
+
+/* Define to enable PKINIT. */
+#define PKINIT 1
+
+/* Define if getlogin has POSIX flavour (and not BSD). */
+/* #undef POSIX_GETLOGIN */
+
+/* Define if getpwnam_r has POSIX flavour. */
+/* #undef POSIX_GETPWNAM_R */
+
+/* Define if you have the readline package. */
+/* #undef READLINE */
+
+/* Define as the return type of signal handlers (`int' or `void'). */
+#define RETSIGTYPE void
+
+/* path to sbin */
+#define SBINDIR "/usr/heimdal/sbin"
+
+/* Define if you want to use samba socket wrappers. */
+/* #undef SOCKET_WRAPPER_REPLACE */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if you have streams ptys. */
+/* #undef STREAMSPTY */
+
+/* path to sysconf */
+#define SYSCONFDIR "/etc"
+
+/* Define to what version of SunOS you are running. */
+/* #undef SunOS */
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define TIME_WITH_SYS_TIME 1
+
+/* Define to 1 if your <sys/time.h> declares `struct tm'. */
+/* #undef TM_IN_SYS_TIME */
+
+/* Version number of package */
+#define VERSION "1.1"
+
+/* Define if signal handlers return void. */
+#define VOID_RETSIGTYPE 1
+
+/* define if target is big endian */
+/* #undef WORDS_BIGENDIAN */
+
+/* Define to 1 if the X Window System is missing or not being used. */
+/* #undef X_DISPLAY_MISSING */
+
+/* Define to 1 if `lex' declares `yytext' as a `char *' by default, not a
+   `char[]'. */
+#define YYTEXT_POINTER 1
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+/* #undef _FILE_OFFSET_BITS */
+
+/* Define to enable extensions on glibc-based systems such as Linux. */
+#define _GNU_SOURCE 1
+
+/* Define for large files, on AIX-style hosts. */
+/* #undef _LARGE_FILES */
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* Define to `int' if <sys/types.h> doesn't define. */
+/* #undef gid_t */
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+   calls it, or to nothing if 'inline' is not supported under any name.  */
+#ifndef __cplusplus
+/* #undef inline */
+#endif
+
+/* Define this to what the type mode_t should be. */
+/* #undef mode_t */
+
+/* Define to `long int' if <sys/types.h> does not define. */
+/* #undef off_t */
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef pid_t */
+
+/* Define this to what the type sig_atomic_t should be. */
+/* #undef sig_atomic_t */
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+/* Define to `int' if <sys/types.h> doesn't define. */
+/* #undef uid_t */
+
+#ifdef ROKEN_RENAME
+#include "roken_rename.h"
+#endif
+
+#ifdef VOID_RETSIGTYPE
+#define SIGRETURN(x) return
+#else
+#define SIGRETURN(x) return (RETSIGTYPE)(x)
+#endif
+
+#ifdef BROKEN_REALLOC
+#define realloc(X, Y) rk_realloc((X), (Y))
+#endif
+
+
+#if ENDIANESS_IN_SYS_PARAM_H
+#  include <sys/types.h>
+#  include <sys/param.h>
+#  if BYTE_ORDER == BIG_ENDIAN
+#  define WORDS_BIGENDIAN 1
+#  endif
+#endif
+
+
+#if _AIX
+#define _ALL_SOURCE
+/* XXX this is gross, but kills about a gazillion warnings */
+struct ether_addr;
+struct sockaddr;
+struct sockaddr_dl;
+struct sockaddr_in;
+#endif
+
+
+/* IRIX 4 braindamage */
+#if IRIX == 4 && !defined(__STDC__)
+#define __STDC__ 0
+#endif
+
+
+
+#if defined(ENCRYPTION) && !defined(AUTHENTICATION)
+#define AUTHENTICATION 1
+#endif
+
+/* Set this to the default system lead string for telnetd 
+ * can contain %-escapes: %s=sysname, %m=machine, %r=os-release
+ * %v=os-version, %t=tty, %h=hostname, %d=date and time
+ */
+/* #undef USE_IM */
+
+/* Used with login -p */
+/* #undef LOGIN_ARGS */
+
+/* set this to a sensible login */
+#ifndef LOGIN_PATH
+#define LOGIN_PATH BINDIR "/login"
+#endif
+
+#endif /* !HAVE_NBTOOL_CONFIG_H */
diff --git a/nbsd_include/heimdal/crypto-headers.h b/nbsd_include/heimdal/crypto-headers.h
new file mode 100644 (file)
index 0000000..7e29410
--- /dev/null
@@ -0,0 +1,27 @@
+#ifndef __crypto_headers_h__
+#define __crypto_headers_h__
+#ifdef KRB5
+#include <krb5-types.h>
+#endif
+#ifndef OPENSSL_DES_LIBDES_COMPATIBILITY
+#define OPENSSL_DES_LIBDES_COMPATIBILITY
+#endif
+#include <openssl/evp.h>
+#include <openssl/des.h>
+#include <openssl/md2.h>
+#include <openssl/md4.h>
+#include <openssl/md5.h>
+#include <openssl/sha.h>
+#include <openssl/rc4.h>
+#include <openssl/rc2.h>
+#include <openssl/aes.h>
+#include <openssl/ui.h>
+#include <openssl/rand.h>
+#include <openssl/engine.h>
+#include <openssl/pkcs12.h>
+#include <openssl/hmac.h>
+#ifndef BN_is_negative
+#define BN_set_negative(bn, flag) ((bn)->neg=(flag)?1:0)
+#define BN_is_negative(bn) ((bn)->neg != 0)
+#endif
+#endif /* __crypto_headers_h__ */
diff --git a/nbsd_include/heimdal/hx509_err.h b/nbsd_include/heimdal/hx509_err.h
new file mode 100644 (file)
index 0000000..a8f5636
--- /dev/null
@@ -0,0 +1,88 @@
+/* Generated from hx509_err.et */
+/* $Id: hx509_err.h,v 1.1 2008/03/22 08:37:24 mlelstv Exp $ */
+
+#ifndef __hx509_err_h__
+#define __hx509_err_h__
+
+struct et_list;
+
+void initialize_hx_error_table_r(struct et_list **);
+
+void initialize_hx_error_table(void);
+#define init_hx_err_tbl initialize_hx_error_table
+
+typedef enum hx_error_number{
+       HX509_BAD_TIMEFORMAT = 569856,
+       HX509_EXTENSION_NOT_FOUND = 569857,
+       HX509_NO_PATH = 569858,
+       HX509_PARENT_NOT_CA = 569859,
+       HX509_CA_PATH_TOO_DEEP = 569860,
+       HX509_SIG_ALG_NO_SUPPORTED = 569861,
+       HX509_SIG_ALG_DONT_MATCH_KEY_ALG = 569862,
+       HX509_CERT_USED_BEFORE_TIME = 569863,
+       HX509_CERT_USED_AFTER_TIME = 569864,
+       HX509_PRIVATE_KEY_MISSING = 569865,
+       HX509_ALG_NOT_SUPP = 569866,
+       HX509_ISSUER_NOT_FOUND = 569867,
+       HX509_VERIFY_CONSTRAINTS = 569868,
+       HX509_RANGE = 569869,
+       HX509_NAME_CONSTRAINT_ERROR = 569870,
+       HX509_PATH_TOO_LONG = 569871,
+       HX509_KU_CERT_MISSING = 569872,
+       HX509_CERT_NOT_FOUND = 569873,
+       HX509_UNKNOWN_LOCK_COMMAND = 569874,
+       HX509_PARENT_IS_CA = 569875,
+       HX509_EXTRA_DATA_AFTER_STRUCTURE = 569876,
+       HX509_PROXY_CERT_INVALID = 569877,
+       HX509_PROXY_CERT_NAME_WRONG = 569878,
+       HX509_NAME_MALFORMED = 569879,
+       HX509_CERTIFICATE_MALFORMED = 569880,
+       HX509_CERTIFICATE_MISSING_EKU = 569881,
+       HX509_PROXY_CERTIFICATE_NOT_CANONICALIZED = 569882,
+       HX509_CMS_FAILED_CREATE_SIGATURE = 569888,
+       HX509_CMS_MISSING_SIGNER_DATA = 569889,
+       HX509_CMS_SIGNER_NOT_FOUND = 569890,
+       HX509_CMS_NO_DATA_AVAILABLE = 569891,
+       HX509_CMS_INVALID_DATA = 569892,
+       HX509_CMS_PADDING_ERROR = 569893,
+       HX509_CMS_NO_RECIPIENT_CERTIFICATE = 569894,
+       HX509_CMS_DATA_OID_MISMATCH = 569895,
+       HX509_CRYPTO_INTERNAL_ERROR = 569920,
+       HX509_CRYPTO_EXTERNAL_ERROR = 569921,
+       HX509_CRYPTO_SIGNATURE_MISSING = 569922,
+       HX509_CRYPTO_BAD_SIGNATURE = 569923,
+       HX509_CRYPTO_SIG_NO_CONF = 569924,
+       HX509_CRYPTO_SIG_INVALID_FORMAT = 569925,
+       HX509_CRYPTO_OID_MISMATCH = 569926,
+       HX509_CRYPTO_NO_PROMPTER = 569927,
+       HX509_CRYPTO_SIGNATURE_WITHOUT_SIGNER = 569928,
+       HX509_CRYPTO_RSA_PUBLIC_ENCRYPT = 569929,
+       HX509_CRYPTO_RSA_PRIVATE_ENCRYPT = 569930,
+       HX509_CRYPTO_RSA_PUBLIC_DECRYPT = 569931,
+       HX509_CRYPTO_RSA_PRIVATE_DECRYPT = 569932,
+       HX509_CRL_USED_BEFORE_TIME = 569952,
+       HX509_CRL_USED_AFTER_TIME = 569953,
+       HX509_CRL_INVALID_FORMAT = 569954,
+       HX509_CRL_CERT_REVOKED = 569955,
+       HX509_REVOKE_STATUS_MISSING = 569956,
+       HX509_CRL_UNKNOWN_EXTENSION = 569957,
+       HX509_REVOKE_WRONG_DATA = 569958,
+       HX509_REVOKE_NOT_SAME_PARENT = 569959,
+       HX509_CERT_NOT_IN_OCSP = 569960,
+       HX509_LOCAL_ATTRIBUTE_MISSING = 569964,
+       HX509_PARSING_KEY_FAILED = 569965,
+       HX509_UNSUPPORTED_OPERATION = 569966,
+       HX509_UNIMPLEMENTED_OPERATION = 569967,
+       HX509_PARSING_NAME_FAILED = 569968,
+       HX509_PKCS11_NO_SLOT = 569984,
+       HX509_PKCS11_NO_TOKEN = 569985,
+       HX509_PKCS11_NO_MECH = 569986,
+       HX509_PKCS11_TOKEN_CONFUSED = 569987,
+       HX509_PKCS11_OPEN_SESSION = 569988,
+       HX509_PKCS11_LOGIN = 569989,
+       HX509_PKCS11_LOAD = 569990
+} hx_error_number;
+
+#define ERROR_TABLE_BASE_hx 569856
+
+#endif /* __hx509_err_h__ */
diff --git a/nbsd_include/heimdal/krb5-types.h b/nbsd_include/heimdal/krb5-types.h
new file mode 100644 (file)
index 0000000..8b14281
--- /dev/null
@@ -0,0 +1,16 @@
+/* krb5-types.h -- this file was generated for i386-unknown-netbsdelf4.0. by
+                   $Id: krb5-types.h,v 1.4 2008/03/22 08:37:24 mlelstv Exp $ */
+
+#ifndef __krb5_types_h__
+#define __krb5_types_h__
+
+#include <inttypes.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+
+
+typedef socklen_t krb5_socklen_t;
+#include <unistd.h>
+typedef ssize_t krb5_ssize_t;
+
+#endif /* __krb5_types_h__ */
diff --git a/nbsd_include/heimdal/krb_err.h b/nbsd_include/heimdal/krb_err.h
new file mode 100644 (file)
index 0000000..4bea686
--- /dev/null
@@ -0,0 +1,65 @@
+/* Generated from krb_err.et */
+/* $Id: krb_err.h,v 1.1 2008/03/22 08:37:24 mlelstv Exp $ */
+
+#ifndef __krb_err_h__
+#define __krb_err_h__
+
+struct et_list;
+
+void initialize_krb_error_table_r(struct et_list **);
+
+void initialize_krb_error_table(void);
+#define init_krb_err_tbl initialize_krb_error_table
+
+typedef enum krb_error_number{
+       KRB4ET_KSUCCESS = 39525376,
+       KRB4ET_KDC_NAME_EXP = 39525377,
+       KRB4ET_KDC_SERVICE_EXP = 39525378,
+       KRB4ET_KDC_AUTH_EXP = 39525379,
+       KRB4ET_KDC_PKT_VER = 39525380,
+       KRB4ET_KDC_P_MKEY_VER = 39525381,
+       KRB4ET_KDC_S_MKEY_VER = 39525382,
+       KRB4ET_KDC_BYTE_ORDER = 39525383,
+       KRB4ET_KDC_PR_UNKNOWN = 39525384,
+       KRB4ET_KDC_PR_N_UNIQUE = 39525385,
+       KRB4ET_KDC_NULL_KEY = 39525386,
+       KRB4ET_KDC_GEN_ERR = 39525396,
+       KRB4ET_GC_TKFIL = 39525397,
+       KRB4ET_GC_NOTKT = 39525398,
+       KRB4ET_MK_AP_TGTEXP = 39525402,
+       KRB4ET_RD_AP_UNDEC = 39525407,
+       KRB4ET_RD_AP_EXP = 39525408,
+       KRB4ET_RD_AP_NYV = 39525409,
+       KRB4ET_RD_AP_REPEAT = 39525410,
+       KRB4ET_RD_AP_NOT_US = 39525411,
+       KRB4ET_RD_AP_INCON = 39525412,
+       KRB4ET_RD_AP_TIME = 39525413,
+       KRB4ET_RD_AP_BADD = 39525414,
+       KRB4ET_RD_AP_VERSION = 39525415,
+       KRB4ET_RD_AP_MSG_TYPE = 39525416,
+       KRB4ET_RD_AP_MODIFIED = 39525417,
+       KRB4ET_RD_AP_ORDER = 39525418,
+       KRB4ET_RD_AP_UNAUTHOR = 39525419,
+       KRB4ET_GT_PW_NULL = 39525427,
+       KRB4ET_GT_PW_BADPW = 39525428,
+       KRB4ET_GT_PW_PROT = 39525429,
+       KRB4ET_GT_PW_KDCERR = 39525430,
+       KRB4ET_GT_PW_NULLTKT = 39525431,
+       KRB4ET_SKDC_RETRY = 39525432,
+       KRB4ET_SKDC_CANT = 39525433,
+       KRB4ET_INTK_W_NOTALL = 39525437,
+       KRB4ET_INTK_BADPW = 39525438,
+       KRB4ET_INTK_PROT = 39525439,
+       KRB4ET_INTK_ERR = 39525446,
+       KRB4ET_AD_NOTGT = 39525447,
+       KRB4ET_NO_TKT_FIL = 39525452,
+       KRB4ET_TKT_FIL_ACC = 39525453,
+       KRB4ET_TKT_FIL_LCK = 39525454,
+       KRB4ET_TKT_FIL_FMT = 39525455,
+       KRB4ET_TKT_FIL_INI = 39525456,
+       KRB4ET_KNAME_FMT = 39525457
+} krb_error_number;
+
+#define ERROR_TABLE_BASE_krb 39525376
+
+#endif /* __krb_err_h__ */
diff --git a/nbsd_include/heimdal/protos.h b/nbsd_include/heimdal/protos.h
new file mode 100644 (file)
index 0000000..1973be8
--- /dev/null
@@ -0,0 +1,277 @@
+/* -*- C -*-
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * 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.
+ * 
+ * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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.
+ */
+
+/*
+ * Add here functions that don't have a prototype on your system.
+ *
+ * $Id: protos.h,v 1.1.1.1 2000/06/16 19:18:30 thorpej Exp $
+ */
+
+#ifdef NEED_CRYPT_PROTO
+char *crypt(const char*, const char*);
+#endif
+
+#ifdef NEED_STRTOK_R_PROTO
+char *strtok_r (char *s1, const char *s2, char **lasts);
+#endif
+
+#ifndef HAVE_OPTARG_DECLARATION
+extern char *optarg;
+#endif
+#ifndef HAVE_OPTERR_DECLARATION
+extern int opterr;
+#endif
+#ifndef HAVE_OPTIND_DECLARATION
+extern int optind;
+#endif
+#ifndef HAVE_OPTOPT_DECLARATION
+extern int optopt;
+#endif
+
+#if defined(__GNUC__) && SunOS == 4
+
+/* To get type fd_set */
+#include <sys/types.h>
+#include <sys/time.h>
+
+/* To get struct sockaddr, struct in_addr and struct hostent */
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netdb.h>
+
+/* To get struct stat */
+#include <sys/stat.h>
+
+/* To get struct utimbuf */
+#include <utime.h>
+
+#if !defined(HAVE_ATEXIT) && defined(HAVE_ON_EXIT)
+#define atexit(X) on_exit(X, NULL)
+#define HAVE_ATEXIT 1
+#endif
+#ifdef NEED_UTIME_PROTO
+int utime(const char *, const struct utimbuf *);
+#endif
+int syscall(int, ...);
+pid_t getpid(void);
+int ftruncate(int, off_t);
+int fchmod(int, mode_t);
+int fchown(int fd, int owner, int group);
+int fsync(int);
+int seteuid(uid_t);
+int setreuid(int, int);
+int flock(int, int);
+int gettimeofday(struct timeval *tp, struct timezone *tzp);
+int lstat(const char *, struct stat *);
+int ioctl(int, int, void *); 
+int getpriority(int which, int who);
+int setpriority(int which, int who, int priority);
+int getdtablesize(void);
+int initgroups(const char *name, int basegid);
+long ulimit(int cmd, long newlimit);
+int vhangup(void);
+
+int sigblock(int);
+int sigsetmask(int);
+int setitimer(int which, struct itimerval *value, struct itimerval *ovalue);
+
+int munmap(caddr_t addr, int len);
+
+int socket(int, int, int);
+int setsockopt(int, int, int, void *, int);
+int bind(int, void *, int);
+int getsockname(int, struct sockaddr *, int *);
+int accept(int, struct sockaddr *, int *);
+int connect(int, struct sockaddr *, int);
+int listen(int, int);
+int recv(int s, void *buf, int len, int flags);
+int recvfrom(int, char *, int, int, void *, int *);
+int sendto(int, const char *, int, int, void *, int);
+int select(int, fd_set *, fd_set *, fd_set *, struct timeval *);
+int shutdown(int, int);
+int getpeername(int, struct sockaddr *, int *);
+int getsockopt(int, int, int, void *, int *);
+int send(int s, const void *msg, int len, int flags);
+struct strbuf;
+int getmsg(int fd, struct strbuf *ctlptr, struct strbuf *dataptr, int *flags);
+
+char *inet_ntoa(struct in_addr in);
+unsigned long inet_addr(const char *cp);
+int gethostname(char *, int);
+struct hostent *gethostbyname(const char *);
+int dn_expand(const u_char *msg,
+             const u_char *eomorig,
+             const u_char *comp_dn,
+             char *exp_dn,
+             int length);
+int res_search(const char *dname,
+              int class,
+              int type,
+              u_char *answer,
+              int anslen);
+
+int yp_get_default_domain (char **outdomain);
+int innetgr(const char *netgroup, const char *machine,
+           const char *user, const char *domain);
+
+char *getwd(char *pathname);
+
+void bzero(char *b, int length);
+int strcasecmp(const char *, const char *);
+void swab(const char *, char *, int);
+int atoi(const char *str);
+char *mktemp(char *);
+void srandom(int seed);
+int random(void);
+
+int rcmd(char **, unsigned short, char *, char *, char *, int *);
+int rresvport(int *);
+int openlog(const char *ident, int logopt, int facility);
+int syslog(int priority, const char *message, ...);
+int ttyslot(void);
+
+char *getpass(const char *);
+
+char *getusershell(void);
+void setpwent();
+void endpwent();
+
+#include <stdio.h>
+int fclose(FILE *);
+
+#endif /* SunOS4 */
+
+#if SunOS == 5
+
+#include <sys/types.h>
+#include <sys/resource.h>
+
+char *getusershell(void);
+char *strtok_r(char *, const char *, char **);
+int getpriority (int which, id_t who);
+int setpriority (int which, id_t who, int prio);
+int getdtablesize (void);
+char *getusershell(void);
+void setusershell(void);
+void endusershell(void);
+
+#if defined(__GNUC__)
+
+int syscall(int, ...);
+int gethostname(char *, int);
+
+struct timeval;
+int gettimeofday(struct timeval *tp, void *);
+
+#endif
+#endif
+
+#if defined(__osf__) /* OSF/1 */
+
+#if 0
+/* To get type fd_set */
+#include <sys/types.h>
+#include <sys/time.h>
+
+int select(int, fd_set *, fd_set *, fd_set *, struct timeval *);
+int fsync(int fildes);
+int gethostname(char *address, int address_len);
+int setreuid(int ruid, int euid);
+int ioctl(int d, unsigned long request, void * arg);
+#endif
+int flock(int fildes, int operation);
+int syscall(int, ...);
+
+unsigned short htons(unsigned short hostshort);
+unsigned int   htonl(unsigned int hostint);
+unsigned short ntohs(unsigned short netshort);
+unsigned int   ntohl(unsigned int netint);
+
+char *mktemp(char *template);
+char *getusershell(void);
+
+int rcmd(char **, unsigned short, char *, char *, char *, int *);
+int rresvport (int *port);
+
+#endif /* OSF/1 */
+
+#if defined(__sgi)
+#include <sys/types.h>
+
+char *ptsname(int fd);
+struct spwd *getspuid(uid_t);
+#endif /* IRIX */
+
+#if defined(__GNUC__) && defined(_AIX) /* AIX */
+
+struct timeval;
+struct timezone;
+int gettimeofday (struct timeval *Tp, void *Tzp);
+
+#endif /* AIX */
+
+#if defined(__GNUC__) && defined(__hpux) /* HP-UX */
+
+int syscall(int, ...);
+
+int vhangup(void);
+
+char *ptsname(int fildes);
+
+void utmpname(const char *file);
+
+int innetgr(const char *netgroup, const char *machine,
+           const char *user, const char *domain);
+
+int dn_comp(char *exp_dn, char *comp_dn, int length,
+           char **dnptrs, char **lastdnptr);
+
+int res_query(char *dname, int class, int type,
+             unsigned char *answer, int anslen);
+
+int dn_expand(char *msg, char *eomorig, char *comp_dn,
+             char *exp_dn, int length);
+
+int res_search(char *dname, int class, int type,
+              unsigned char *answer, int anslen);
+
+#endif /* HP-UX */
+
+#if defined(WIN32)     /* Visual C++ 4.0 (Windows95/NT) */
+
+int open(const char *, int, ...);
+int close(int);
+int    read(int, void *, unsigned int);
+int write(int, const void *, unsigned int);
+
+#endif /* WIN32 */
diff --git a/nbsd_include/heimdal/roken.h b/nbsd_include/heimdal/roken.h
new file mode 100644 (file)
index 0000000..7917f2b
--- /dev/null
@@ -0,0 +1,235 @@
+/* This is an OS dependent, generated file */
+
+
+#ifndef __ROKEN_H__
+#define __ROKEN_H__
+
+/* -*- C -*- */
+/*
+ * Copyright (c) 1995-2005 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * 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.
+ * 
+ * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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.
+ */
+
+/* $Id: roken.h,v 1.14 2010/01/25 00:26:04 christos Exp $ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <stdint.h>
+#include <string.h>
+#include <signal.h>
+
+#include <sys/param.h>
+#include <inttypes.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include <sys/uio.h>
+#include <grp.h>
+#include <sys/stat.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <arpa/nameser.h>
+#include <resolv.h>
+#include <syslog.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <err.h>
+#include <termios.h>
+#include <sys/ioctl.h>
+#include <sys/time.h>
+#include <time.h>
+#include <strings.h>
+
+#include <paths.h>
+
+
+#include <roken-common.h>
+
+ROKEN_CPP_START
+
+#define rk_UNCONST(x) ((void *)(uintptr_t)(const void *)(x))
+
+
+
+char * ROKEN_LIB_FUNCTION strlwr(char *);
+
+size_t ROKEN_LIB_FUNCTION strnlen(const char*, size_t);
+
+
+ssize_t ROKEN_LIB_FUNCTION strsep_copy(const char**, const char*, char*, size_t);
+
+
+
+
+char * ROKEN_LIB_FUNCTION strupr(char *);
+
+
+
+
+
+
+
+
+
+
+
+#include <pwd.h>
+struct passwd * ROKEN_LIB_FUNCTION k_getpwnam (const char *);
+struct passwd * ROKEN_LIB_FUNCTION k_getpwuid (uid_t);
+
+const char * ROKEN_LIB_FUNCTION get_default_username (void);
+
+
+
+
+int ROKEN_LIB_FUNCTION mkstemp(char *);
+
+
+
+
+int ROKEN_LIB_FUNCTION daemon(int, int);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+time_t ROKEN_LIB_FUNCTION tm2time (struct tm, int);
+
+int ROKEN_LIB_FUNCTION unix_verify_user(char *, char *);
+
+int ROKEN_LIB_FUNCTION roken_concat (char *, size_t, ...);
+
+size_t ROKEN_LIB_FUNCTION roken_mconcat (char **, size_t, ...);
+
+int ROKEN_LIB_FUNCTION roken_vconcat (char *, size_t, va_list);
+
+size_t ROKEN_LIB_FUNCTION
+    roken_vmconcat (char **, size_t, va_list);
+
+ssize_t ROKEN_LIB_FUNCTION net_write (int, const void *, size_t);
+
+ssize_t ROKEN_LIB_FUNCTION net_read (int, void *, size_t);
+
+int ROKEN_LIB_FUNCTION issuid(void);
+
+
+int ROKEN_LIB_FUNCTION get_window_size(int fd, int *, int *);
+
+
+
+extern char **environ;
+
+struct hostent * ROKEN_LIB_FUNCTION
+getipnodebyname (const char *, int, int, int *);
+
+struct hostent * ROKEN_LIB_FUNCTION
+getipnodebyaddr (const void *, size_t, int, int *);
+
+void ROKEN_LIB_FUNCTION
+freehostent (struct hostent *);
+
+struct hostent * ROKEN_LIB_FUNCTION
+copyhostent (const struct hostent *);
+
+
+
+
+
+
+
+
+int ROKEN_LIB_FUNCTION
+getnameinfo_verified(const struct sockaddr *, socklen_t,
+                    char *, size_t,
+                    char *, size_t,
+                    int);
+
+int ROKEN_LIB_FUNCTION
+roken_getaddrinfo_hostspec(const char *, int, struct addrinfo **); 
+int ROKEN_LIB_FUNCTION
+roken_getaddrinfo_hostspec2(const char *, int, int, struct addrinfo **);
+
+
+
+void * ROKEN_LIB_FUNCTION emalloc (size_t);
+void * ROKEN_LIB_FUNCTION ecalloc(size_t, size_t);
+void * ROKEN_LIB_FUNCTION erealloc (void *, size_t);
+char * ROKEN_LIB_FUNCTION estrdup (const char *);
+
+/*
+ * kludges and such
+ */
+
+int ROKEN_LIB_FUNCTION
+roken_gethostby_setup(const char*, const char*);
+struct hostent* ROKEN_LIB_FUNCTION
+roken_gethostbyname(const char*);
+struct hostent* ROKEN_LIB_FUNCTION 
+roken_gethostbyaddr(const void*, size_t, int);
+
+#define roken_getservbyname(x,y) getservbyname(x,y)
+
+#define roken_openlog(a,b,c) openlog(a,b,c)
+
+#define roken_getsockname(a,b,c) getsockname(a,b,c)
+
+
+
+
+void ROKEN_LIB_FUNCTION mini_inetd_addrinfo (struct addrinfo*);
+void ROKEN_LIB_FUNCTION mini_inetd (int);
+
+
+
+
+
+
+
+
+
+
+
+
+ROKEN_CPP_END
+#define ROKEN_VERSION 1.1
+
+#endif /* __ROKEN_H__ */
diff --git a/nbsd_include/heimdal/version.h b/nbsd_include/heimdal/version.h
new file mode 100644 (file)
index 0000000..08f5cd1
--- /dev/null
@@ -0,0 +1,2 @@
+const char *heimdal_long_version = "@(#)$Version: Heimdal 1.1 (NetBSD) $";
+const char *heimdal_version = "Heimdal 1.1";
diff --git a/nbsd_include/hesiod.h b/nbsd_include/hesiod.h
new file mode 100644 (file)
index 0000000..07d0cad
--- /dev/null
@@ -0,0 +1,89 @@
+/*     $NetBSD: hesiod.h,v 1.5 2008/04/28 20:22:54 martin Exp $        */
+
+/*-
+ * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc.
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * Copyright (c) 1996 by Internet Software Consortium.
+ *
+ * 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 INTERNET SOFTWARE CONSORTIUM DISCLAIMS
+ * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
+ * CONSORTIUM 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.
+ */
+
+#ifndef _HESIOD_H_
+#define _HESIOD_H_
+
+       /* Application-visible indication that we have the new interfaces */
+
+#define HESIOD_INTERFACES
+
+       /* Configuration information. */
+
+#ifndef _PATH_HESIOD_CONF                      /* Configuration file. */
+#define _PATH_HESIOD_CONF      "/etc/hesiod.conf"
+#endif
+
+#define DEF_RHS                ""                      /* Defaults if HESIOD_CONF */
+#define DEF_LHS                ""                      /*    file is not present. */
+
+       /* Error codes (for backwards compatibility) */
+
+#define        HES_ER_UNINIT   -1      /* uninitialized */
+#define        HES_ER_OK       0       /* no error */
+#define        HES_ER_NOTFOUND 1       /* Hesiod name not found by server */
+#define HES_ER_CONFIG  2       /* local problem (no config file?) */
+#define HES_ER_NET     3       /* network problem */
+
+       /* Declaration of routines */
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+int    hesiod_init     (void **);
+char  **hesiod_resolve (void *, const char *, const char *);
+void   hesiod_free_list(void *, char **);
+char   *hesiod_to_bind (void *, const char *, const char *);
+void   hesiod_end      (void *);
+
+                               /* backwards compatibility */
+int    hes_init        (void);
+char   *hes_to_bind    (const char *, const char *);
+char  **hes_resolve    (const char *, const char *);
+int    hes_error       (void);
+void   hes_free        (char **);
+__END_DECLS
+
+#endif /* ! _HESIOD_H_ */
diff --git a/nbsd_include/iconv.h b/nbsd_include/iconv.h
new file mode 100644 (file)
index 0000000..d045507
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: iconv.h,v 1.6 2005/02/03 04:39:32 perry Exp $  */
+
+/*-
+ * Copyright (c)2003 Citrus Project,
+ * 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.
+ *
+ */
+
+#ifndef _ICONV_H_
+#define _ICONV_H_
+
+#include <sys/cdefs.h>
+#include <machine/ansi.h>
+
+#ifdef _BSD_SIZE_T_
+typedef        _BSD_SIZE_T_    size_t;
+#undef _BSD_SIZE_T_
+#endif
+
+struct __tag_iconv_t;
+typedef        struct __tag_iconv_t    *iconv_t;
+
+__BEGIN_DECLS
+iconv_t        iconv_open(const char *, const char *);
+size_t iconv(iconv_t, const char ** __restrict,
+                    size_t * __restrict, char ** __restrict,
+                    size_t * __restrict);
+int    iconv_close(iconv_t);
+/*
+ * non-portable interfaces for iconv
+ */
+int    __iconv_get_list(char ***, size_t *);
+void   __iconv_free_list(char **, size_t);
+size_t __iconv(iconv_t, const char **, size_t *, char **,
+                    size_t *, __uint32_t, size_t *);
+#define __ICONV_F_HIDE_INVALID 0x0001
+__END_DECLS
+
+#endif /* !_ICONV_H_ */
diff --git a/nbsd_include/ieeefp.h b/nbsd_include/ieeefp.h
new file mode 100644 (file)
index 0000000..9b9cce1
--- /dev/null
@@ -0,0 +1,23 @@
+/*     $NetBSD: ieeefp.h,v 1.7 2005/11/18 20:02:59 christos Exp $      */
+
+/* 
+ * Written by J.T. Conklin, Apr 6, 1995
+ * Public domain.
+ */
+
+#ifndef _IEEEFP_H_
+#define _IEEEFP_H_
+
+#include <sys/cdefs.h>
+#include <machine/ieeefp.h>
+
+__BEGIN_DECLS
+fp_rnd    fpgetround(void);
+fp_rnd    fpsetround(fp_rnd);
+fp_except fpgetmask(void);
+fp_except fpsetmask(fp_except);
+fp_except fpgetsticky(void);
+fp_except fpsetsticky(fp_except);
+__END_DECLS
+
+#endif /* _IEEEFP_H_ */
diff --git a/nbsd_include/ifaddrs.h b/nbsd_include/ifaddrs.h
new file mode 100644 (file)
index 0000000..d9ac733
--- /dev/null
@@ -0,0 +1,56 @@
+/*     $NetBSD: ifaddrs.h,v 1.5 2005/02/03 04:39:32 perry Exp $        */
+
+/*
+ * Copyright (c) 1995, 1999
+ *     Berkeley Software Design, Inc.  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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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.
+ *
+ *     BSDI ifaddrs.h,v 2.5 2000/02/23 14:51:59 dab Exp
+ */
+
+#ifndef        _IFADDRS_H_
+#define        _IFADDRS_H_
+
+struct ifaddrs {
+       struct ifaddrs  *ifa_next;
+       char            *ifa_name;
+       u_int            ifa_flags;
+       struct sockaddr *ifa_addr;
+       struct sockaddr *ifa_netmask;
+       struct sockaddr *ifa_dstaddr;
+       void            *ifa_data;
+};
+
+/*
+ * This may have been defined in <net/if.h>.  Note that if <net/if.h> is
+ * to be included it must be included before this header file.
+ */
+#ifndef        ifa_broadaddr
+#define        ifa_broadaddr   ifa_dstaddr     /* broadcast address interface */
+#endif
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+int getifaddrs(struct ifaddrs **);
+void freeifaddrs(struct ifaddrs *);
+__END_DECLS
+
+#endif /* !_IFADDRS_H_ */
diff --git a/nbsd_include/inttypes.h b/nbsd_include/inttypes.h
new file mode 100644 (file)
index 0000000..8c08a40
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: inttypes.h,v 1.7 2009/11/15 22:21:03 christos Exp $    */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _INTTYPES_H_
+#define _INTTYPES_H_
+
+#include <sys/cdefs.h>
+#include <sys/inttypes.h>
+#include <machine/ansi.h>
+
+#if defined(_BSD_WCHAR_T_) && !defined(__cplusplus)
+typedef        _BSD_WCHAR_T_   wchar_t;
+#undef _BSD_WCHAR_T_
+#endif
+
+__BEGIN_DECLS
+intmax_t       strtoimax(const char * __restrict,
+                   char ** __restrict, int);
+uintmax_t      strtoumax(const char * __restrict,
+                   char ** __restrict, int);
+intmax_t       wcstoimax(const wchar_t * __restrict,
+                   wchar_t ** __restrict, int);
+uintmax_t      wcstoumax(const wchar_t * __restrict,
+                   wchar_t ** __restrict, int);
+
+intmax_t       imaxabs(intmax_t);
+
+typedef struct {
+       intmax_t quot;
+       intmax_t rem;
+} imaxdiv_t;
+
+imaxdiv_t      imaxdiv(intmax_t, intmax_t);
+__END_DECLS
+
+#endif /* !_INTTYPES_H_ */
diff --git a/nbsd_include/iso646.h b/nbsd_include/iso646.h
new file mode 100644 (file)
index 0000000..56ea2fe
--- /dev/null
@@ -0,0 +1,23 @@
+/*     $NetBSD: iso646.h,v 1.1 1995/02/17 09:08:10 jtc Exp $   */
+
+/* 
+ * Written by J.T. Conklin <jtc@wimsey.com> 02/16/95.
+ * Public domain.
+ */
+
+#ifndef _ISO646_H_
+#define _ISO646_H_
+
+#define and    &&
+#define and_eq &=
+#define bitand &
+#define bitor  |
+#define compl  ~
+#define not    !
+#define not_eq !=
+#define or     ||
+#define or_eq  |=
+#define xor    ^
+#define xor_eq ^=
+
+#endif /* !_ISO646_H_ */
diff --git a/nbsd_include/kvm.h b/nbsd_include/kvm.h
new file mode 100644 (file)
index 0000000..174ade4
--- /dev/null
@@ -0,0 +1,88 @@
+/*     $NetBSD: kvm.h,v 1.15 2007/11/08 20:48:04 joerg Exp $   */
+
+/*-
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ *
+ *     @(#)kvm.h       8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _KVM_H_
+#define        _KVM_H_
+
+/* Default version symbol. */
+#define        VRS_SYM         "_version"
+#define        VRS_KEY         "VERSION"
+
+/*
+ * Flag for kvm_open*() to disable opening of kernel files - used
+ * by programs that use only sysctl() function to access kernel
+ * information.
+ */
+#define KVM_NO_FILES   ((int)0x80000000)
+
+#include <nlist.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+#include <stdbool.h>
+#include <stdio.h>
+
+__BEGIN_DECLS
+
+typedef struct __kvm kvm_t;
+
+struct kinfo_proc;
+struct kinfo_proc2;
+int      kvm_close(kvm_t *);
+int      kvm_dump_inval(kvm_t *);
+int      kvm_dump_mkheader(kvm_t *, off_t);
+int      kvm_dump_header(kvm_t *, bool (*)(void *, const void *, size_t),
+                         void *, int);
+int      kvm_dump_wrtheader(kvm_t *, FILE *, int);
+char   **kvm_getargv(kvm_t *, const struct kinfo_proc *, int);
+char   **kvm_getargv2(kvm_t *, const struct kinfo_proc2 *, int);
+char   **kvm_getenvv(kvm_t *, const struct kinfo_proc *, int);
+char   **kvm_getenvv2(kvm_t *, const struct kinfo_proc2 *, int);
+char    *kvm_geterr(kvm_t *);
+int      kvm_getloadavg(kvm_t *, double [], int);
+char    *kvm_getfiles(kvm_t *, int, int, int *);
+struct kinfo_lwp *
+         kvm_getlwps(kvm_t *, int, u_long, size_t, int *);
+struct kinfo_proc2 *
+         kvm_getproc2(kvm_t *, int, int, size_t, int *);
+struct kinfo_proc *
+         kvm_getprocs(kvm_t *, int, int, int *);
+int      kvm_nlist(kvm_t *, struct nlist *);
+kvm_t   *kvm_open
+           (const char *, const char *, const char *, int, const char *);
+kvm_t   *kvm_openfiles(const char *, const char *, const char *, int, char *);
+ssize_t          kvm_read(kvm_t *, u_long, void *, size_t);
+ssize_t          kvm_write(kvm_t *, u_long, const void *, size_t);
+
+__END_DECLS
+
+#endif /* !_KVM_H_ */
diff --git a/nbsd_include/langinfo.h b/nbsd_include/langinfo.h
new file mode 100644 (file)
index 0000000..8fb4c39
--- /dev/null
@@ -0,0 +1,91 @@
+/*     $NetBSD: langinfo.h,v 1.9 2005/02/03 04:39:32 perry Exp $       */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>
+ * Public domain.
+ */
+
+#ifndef _LANGINFO_H_
+#define _LANGINFO_H_
+
+#include <sys/cdefs.h>
+#include <nl_types.h>
+
+#define D_T_FMT                ((nl_item)0)    /* String for formatting date and
+                                          time */
+#define D_FMT          ((nl_item)1)    /* Date format string */
+#define        T_FMT           ((nl_item)2)    /* Time format string */
+#define T_FMT_AMPM     ((nl_item)3)    /* Time format string with 12 hour
+                                          clock */
+#define AM_STR         ((nl_item)4)    /* Ante Meridiem afix */
+#define PM_STR         ((nl_item)5)    /* Post Meridiem afix */
+
+#define DAY_1          ((nl_item)6)    /* Name of the first day of the week */
+#define DAY_2          ((nl_item)7)
+#define DAY_3          ((nl_item)8)
+#define DAY_4          ((nl_item)9)
+#define DAY_5          ((nl_item)10)
+#define DAY_6          ((nl_item)11)
+#define DAY_7          ((nl_item)12)
+
+#define ABDAY_1                ((nl_item)13)   /* Abbrev. name of the first day of
+                                          the week */
+#define ABDAY_2                ((nl_item)14)
+#define ABDAY_3                ((nl_item)15)
+#define ABDAY_4                ((nl_item)16)
+#define ABDAY_5                ((nl_item)17)
+#define ABDAY_6                ((nl_item)18)
+#define ABDAY_7                ((nl_item)19)
+
+#define MON_1          ((nl_item)20)   /* Name of the first month */
+#define MON_2          ((nl_item)21)
+#define MON_3          ((nl_item)22)
+#define MON_4          ((nl_item)23)
+#define MON_5          ((nl_item)24)
+#define MON_6          ((nl_item)25)
+#define MON_7          ((nl_item)26)
+#define MON_8          ((nl_item)27)
+#define MON_9          ((nl_item)28)
+#define MON_10         ((nl_item)29)
+#define MON_11         ((nl_item)30)
+#define MON_12         ((nl_item)31)
+
+#define ABMON_1                ((nl_item)32)   /* Abbrev. name of the first month */
+#define ABMON_2                ((nl_item)33)
+#define ABMON_3                ((nl_item)34)
+#define ABMON_4                ((nl_item)35)
+#define ABMON_5                ((nl_item)36)
+#define ABMON_6                ((nl_item)37)
+#define ABMON_7                ((nl_item)38)
+#define ABMON_8                ((nl_item)39)
+#define ABMON_9                ((nl_item)40)
+#define ABMON_10       ((nl_item)41)
+#define ABMON_11       ((nl_item)42)
+#define ABMON_12       ((nl_item)43)
+
+#define RADIXCHAR      ((nl_item)44)   /* Radix character */
+#define THOUSEP                ((nl_item)45)   /* Separator for thousands */
+#define YESSTR         ((nl_item)46)   /* Affirmitive response for yes/no
+                                          queries */
+#define YESEXPR                ((nl_item)47)   /* Affirmitive response for yes/no
+                                          queries */
+#define NOSTR          ((nl_item)48)   /* Negative response for yes/no
+                                          queries */
+#define NOEXPR         ((nl_item)49)   /* Negative response for yes/no
+                                          queries */
+#define CRNCYSTR       ((nl_item)50)   /* Currency symbol */
+
+#define CODESET                ((nl_item)51)   /* codeset name */
+
+#define ERA            ((nl_item)52)   /* Era description segments */
+#define ERA_D_FMT      ((nl_item)53)   /* Era date format string */
+#define ERA_D_T_FMT    ((nl_item)54)   /* Era date and time format string */
+#define ERA_T_FMT      ((nl_item)55)   /* Era time format string */
+
+#define ALT_DIGITS     ((nl_item)56)   /* Alternative symbols for digits */
+
+__BEGIN_DECLS
+char *nl_langinfo(nl_item);
+__END_DECLS
+
+#endif /* _LANGINFO_H_ */
diff --git a/nbsd_include/libgen.h b/nbsd_include/libgen.h
new file mode 100644 (file)
index 0000000..7a4985e
--- /dev/null
@@ -0,0 +1,42 @@
+/*     $NetBSD: libgen.h,v 1.5 2008/05/10 22:37:42 christos Exp $      */
+
+/*-
+ * Copyright (c) 1997 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _LIBGEN_H_
+#define _LIBGEN_H_
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+char   *basename(char *);
+char   *dirname(char *);
+__END_DECLS
+
+#endif /* !_LIBGEN_H_ */
diff --git a/nbsd_include/limits.h b/nbsd_include/limits.h
new file mode 100644 (file)
index 0000000..dd633b1
--- /dev/null
@@ -0,0 +1,116 @@
+/*     $NetBSD: limits.h,v 1.29 2010/06/07 13:52:29 tnozaki Exp $      */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ *
+ *     @(#)limits.h    8.2 (Berkeley) 1/4/94
+ */
+
+#ifndef _LIMITS_H_
+#define        _LIMITS_H_
+
+#include <sys/featuretest.h>
+
+#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+#define        _POSIX_AIO_LISTIO_MAX   2
+#define        _POSIX_AIO_MAX          1
+#define        _POSIX_ARG_MAX          4096
+#define        _POSIX_CHILD_MAX        25
+#define        _POSIX_HOST_NAME_MAX    255
+#define        _POSIX_LINK_MAX         8
+#define        _POSIX_LOGIN_NAME_MAX   9
+#define        _POSIX_MAX_CANON        255
+#define        _POSIX_MAX_INPUT        255
+#define        _POSIX_MQ_OPEN_MAX      8
+#define        _POSIX_MQ_PRIO_MAX      32
+#define        _POSIX_NAME_MAX         14
+#define        _POSIX_NGROUPS_MAX      8
+#define        _POSIX_OPEN_MAX         20
+#define        _POSIX_PATH_MAX         256
+#define        _POSIX_PIPE_BUF         512
+#define        _POSIX_RE_DUP_MAX       255
+#define        _POSIX_SSIZE_MAX        32767
+#define        _POSIX_STREAM_MAX       8
+#define        _POSIX_SYMLINK_MAX      255
+#define        _POSIX_SYMLOOP_MAX      8
+#define        _POSIX_THREAD_DESTRUCTOR_ITERATIONS     4
+#define        _POSIX_THREAD_KEYS_MAX  128
+#define        _POSIX_THREAD_THREADS_MAX               64
+#define        _POSIX_TIMER_MAX        32
+#define        _POSIX_TTY_NAME_MAX     9
+#define        _POSIX_TZNAME_MAX       6
+
+#define        _POSIX2_BC_BASE_MAX     99
+#define        _POSIX2_BC_DIM_MAX      2048
+#define        _POSIX2_BC_SCALE_MAX    99
+#define        _POSIX2_BC_STRING_MAX   1000
+#define        _POSIX2_CHARCLASS_NAME_MAX      14
+#define        _POSIX2_COLL_WEIGHTS_MAX        2
+#define        _POSIX2_EXPR_NEST_MAX   32
+#define        _POSIX2_LINE_MAX        2048
+#define        _POSIX2_RE_DUP_MAX      255
+
+/*
+ * X/Open CAE Specifications,
+ * adopted in IEEE Std 1003.1-2001 XSI.
+ */
+#if (_POSIX_C_SOURCE - 0) >= 200112L || defined(_XOPEN_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+#define        _XOPEN_IOV_MAX          16
+#define        _XOPEN_NAME_MAX         256
+#define        _XOPEN_PATH_MAX         1024
+
+#define PASS_MAX               128             /* Legacy */
+
+#define CHARCLASS_NAME_MAX     14
+#define NL_ARGMAX              9
+#define NL_LANGMAX             14
+#define NL_MSGMAX              32767
+#define NL_NMAX                        1
+#define NL_SETMAX              255
+#define NL_TEXTMAX             2048
+
+       /* IEEE Std 1003.1-2001 TSF */
+#define        _GETGR_R_SIZE_MAX       1024
+#define        _GETPW_R_SIZE_MAX       1024
+
+/* Always ensure that this is consistent with <stdio.h> */
+#ifndef TMP_MAX
+#define TMP_MAX                        308915776       /* Legacy */
+#endif
+#endif /* _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE || _NETBSD_SOURCE */
+
+#endif /* _POSIX_C_SOURCE || _XOPEN_SOURCE || _NETBSD_SOURCE */
+
+#define MB_LEN_MAX             32      /* Allow ISO/IEC 2022 */
+
+#include <machine/limits.h>
+#include <sys/syslimits.h>
+
+#endif /* !_LIMITS_H_ */
diff --git a/nbsd_include/link.h b/nbsd_include/link.h
new file mode 100644 (file)
index 0000000..c93efd9
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: link.h,v 1.13 2008/04/28 20:22:54 martin Exp $ */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
+ * NASA Ames Research Center.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _LINK_H_
+#define        _LINK_H_
+
+/*
+ * Pull in the correct definitions for our toolchain target.
+ */
+#ifdef __ELF__
+#include <link_elf.h>
+#else
+#include <link_aout.h>
+#endif
+
+#endif /* _LINK_H_ */
diff --git a/nbsd_include/link_aout.h b/nbsd_include/link_aout.h
new file mode 100644 (file)
index 0000000..e10ede2
--- /dev/null
@@ -0,0 +1,288 @@
+/*     $NetBSD: link_aout.h,v 1.21 2008/04/28 20:22:54 martin Exp $    */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Paul Kranenburg.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * RRS section definitions.
+ *
+ * The layout of some data structures defined in this header file is
+ * such that we can provide compatibility with the SunOS 4.x shared
+ * library scheme.
+ */
+
+#ifndef _LINK_AOUT_H_
+#define _LINK_AOUT_H_
+
+#include <dlfcn.h>                     /* for Dl_info */
+#include <a.out.h>                     /* for struct nlist */
+
+/*
+ * A `Shared Object Descriptor' describes a shared object that is needed
+ * to complete the link edit process of the object containing it.
+ * A list of such objects (chained through `sod_next') is pointed at
+ * by `sdt_sods' in the section_dispatch_table structure.
+ */
+
+struct sod {   /* Shared Object Descriptor */
+       long    sod_name;               /* name (relative to load address) */
+       u_int   sod_library  : 1,       /* Searched for by library rules */
+               sod_reserved : 31;
+       short   sod_major;              /* major version number */
+       short   sod_minor;              /* minor version number */
+       long    sod_next;               /* next sod */
+};
+
+/*
+ * `Shared Object Map's are used by the run-time link editor (ld.so) to
+ * keep track of all shared objects loaded into a process' address space.
+ * These structures are only used at run-time and do not occur within
+ * the text or data segment of an executable or shared library.
+ */
+struct so_map {                /* Shared Object Map */
+       caddr_t         som_addr;       /* Address at which object mapped */
+       char            *som_path;      /* Path to mmap'ed file */
+       struct so_map   *som_next;      /* Next map in chain */
+       struct sod      *som_sod;       /* Sod responsible for this map */
+       caddr_t         som_sodbase;    /* Base address of this sod */
+       u_int           som_write : 1;  /* Text is currently writable */
+       struct _dynamic *som_dynamic;   /* _dynamic structure */
+       caddr_t         som_spd;        /* Private data */
+};
+
+/*
+ * Symbol description with size. This is simply an `nlist' with
+ * one field (nz_size) added.
+ * Used to convey size information on items in the data segment
+ * of shared objects. An array of these live in the shared object's
+ * text segment and is addressed by the `sdt_nzlist' field.
+ */
+struct nzlist {
+       struct nlist    nlist;
+       u_long          nz_size;
+#define nz_un          nlist.n_un
+#define nz_strx                nlist.n_un.n_strx
+#define nz_name                nlist.n_un.n_name
+#define nz_type                nlist.n_type
+#define nz_value       nlist.n_value
+#define nz_desc                nlist.n_desc
+#define nz_other       nlist.n_other
+};
+
+#define N_AUX(p)       ((p)->n_other & 0xf)
+#define N_BIND(p)      (((unsigned int)(p)->n_other >> 4) & 0xf)
+#define N_OTHER(r, v)  (((unsigned int)(r) << 4) | ((v) & 0xf))
+
+#define AUX_OBJECT     1
+#define AUX_FUNC       2
+#define AUX_LABEL      3
+/*#define BIND_LOCAL   0       not used */
+/*#define BIND_GLOBAL  1       not used */
+#define BIND_WEAK      2
+
+
+/*
+ * The `section_dispatch_table' structure contains offsets to various data
+ * structures needed to do run-time relocation.
+ */
+struct section_dispatch_table {
+       struct so_map *sdt_loaded;      /* List of loaded objects */
+       long    sdt_sods;               /* List of shared objects descriptors */
+       long    sdt_paths;              /* Library search paths */
+       long    sdt_got;                /* Global offset table */
+       long    sdt_plt;                /* Procedure linkage table */
+       long    sdt_rel;                /* Relocation table */
+       long    sdt_hash;               /* Symbol hash table */
+       long    sdt_nzlist;             /* Symbol table itself */
+       long    sdt_filler2;            /* Unused (was: stab_hash) */
+       long    sdt_buckets;            /* Number of hash buckets */
+       long    sdt_strings;            /* Symbol strings */
+       long    sdt_str_sz;             /* Size of symbol strings */
+       long    sdt_text_sz;            /* Size of text area */
+       long    sdt_plt_sz;             /* Size of procedure linkage table */
+};
+
+/*
+ * RRS symbol hash table, addressed by `sdt_hash' in section_dispatch_table.
+ * Used to quickly lookup symbols of the shared object by hashing
+ * on the symbol's name. `rh_symbolnum' is the index of the symbol
+ * in the shared object's symbol list (`sdt_nzlist'), `rh_next' is
+ * the next symbol in the hash bucket (in case of collisions).
+ */
+struct rrs_hash {
+       int     rh_symbolnum;           /* Symbol number */
+       int     rh_next;                /* Next hash entry */
+};
+
+/*
+ * `rt_symbols' is used to keep track of run-time allocated commons
+ * and data items copied from shared objects.
+ */
+struct rt_symbol {
+       struct nzlist           *rt_sp;         /* The symbol */
+       struct rt_symbol        *rt_next;       /* Next in linear list */
+       struct rt_symbol        *rt_link;       /* Next in bucket */
+       caddr_t                 rt_srcaddr;     /* Address of "master" copy */
+       struct so_map           *rt_smp;        /* Originating map */
+};
+
+/*
+ * Debugger interface structure.
+ */
+struct so_debug {
+       int     dd_version;             /* Version # of interface */
+       int     dd_in_debugger;         /* Set when run by debugger */
+       int     dd_sym_loaded;          /* Run-time linking brought more
+                                          symbols into scope */
+       char     *dd_bpt_addr;          /* Address of rtld-generated bpt */
+       int     dd_bpt_shadow;          /* Original contents of bpt */
+       struct rt_symbol *dd_cc;        /* Allocated commons/copied data */
+};
+
+/*
+ * Entry points into ld.so - user interface to the run-time linker.
+ */
+struct ld_entry {
+       void    *(*dlopen)(const char *, int);
+       int     (*dlclose)(void *);
+       void    *(*dlsym)(void *, const char *);
+       int     (*dlctl)(void *, int, void *);
+       void    (*dlexit)(void);
+       int     (*dladdr)(const void *, Dl_info *);
+       void    (*dlrsrvd[2])(void);
+};
+
+/*
+ * This is the structure pointed at by the __DYNAMIC symbol if an
+ * executable requires the attention of the run-time link editor.
+ * __DYNAMIC is given the value zero if no run-time linking needs to
+ * be done (it is always present in shared objects).
+ * The union `d_un' provides for different versions of the dynamic
+ * linking mechanism (switched on by `d_version'). The last version
+ * used by Sun is 3. We leave some room here and go to version number
+ * 8 for NetBSD, the main difference lying in the support for the
+ * `nz_list' type of symbols.
+ */
+
+struct _dynamic {
+       int             d_version;      /* version # of this interface */
+       struct so_debug *d_debug;
+       union {
+               struct section_dispatch_table *d_sdt;
+       } d_un;
+       struct ld_entry *d_entry;       /* compat - now in crt_ldso */
+};
+
+#define LD_VERSION_SUN         (3)
+#define LD_VERSION_BSD         (8)
+#define LD_VERSION_NZLIST_P(v) ((v) >= 8)
+
+#define LD_GOT(x)      ((x)->d_un.d_sdt->sdt_got)
+#define LD_PLT(x)      ((x)->d_un.d_sdt->sdt_plt)
+#define LD_REL(x)      ((x)->d_un.d_sdt->sdt_rel)
+#define LD_SYMBOL(x)   ((x)->d_un.d_sdt->sdt_nzlist)
+#define LD_HASH(x)     ((x)->d_un.d_sdt->sdt_hash)
+#define LD_STRINGS(x)  ((x)->d_un.d_sdt->sdt_strings)
+#define LD_NEED(x)     ((x)->d_un.d_sdt->sdt_sods)
+#define LD_BUCKETS(x)  ((x)->d_un.d_sdt->sdt_buckets)
+#define LD_PATHS(x)    ((x)->d_un.d_sdt->sdt_paths)
+
+#define LD_GOTSZ(x)    ((x)->d_un.d_sdt->sdt_plt - (x)->d_un.d_sdt->sdt_got)
+#define LD_RELSZ(x)    ((x)->d_un.d_sdt->sdt_hash - (x)->d_un.d_sdt->sdt_rel)
+#define LD_HASHSZ(x)   ((x)->d_un.d_sdt->sdt_nzlist - (x)->d_un.d_sdt->sdt_hash)
+#define LD_STABSZ(x)   ((x)->d_un.d_sdt->sdt_strings - (x)->d_un.d_sdt->sdt_nzlist)
+#define LD_PLTSZ(x)    ((x)->d_un.d_sdt->sdt_plt_sz)
+#define LD_STRSZ(x)    ((x)->d_un.d_sdt->sdt_str_sz)
+#define LD_TEXTSZ(x)   ((x)->d_un.d_sdt->sdt_text_sz)
+
+/*
+ * Interface to ld.so
+ */
+struct crt_ldso {
+       int             crt_ba;         /* Base address of ld.so */
+       int             crt_dzfd;       /* "/dev/zero" file descriptor (SunOS) */
+       int             crt_ldfd;       /* ld.so file descriptor */
+       struct _dynamic *crt_dp;        /* Main's __DYNAMIC */
+       char            **crt_ep;       /* environment strings */
+       caddr_t         crt_bp;         /* Breakpoint if run from debugger */
+       char            *crt_prog;      /* Program name (v3) */
+       char            *crt_ldso;      /* Link editor name (v4) */
+       struct ld_entry *crt_ldentry;   /* dl*() access (v4) */
+};
+
+/*
+ * Version passed from crt0 to ld.so (1st argument to _rtld()).
+ */
+#define CRT_VERSION_SUN                1
+#define CRT_VERSION_BSD_2      2
+#define CRT_VERSION_BSD_3      3
+#define CRT_VERSION_BSD_4      4
+
+
+/*
+ * Maximum number of recognized shared object version numbers.
+ */
+#define MAXDEWEY       8
+
+/*
+ * Header of the hints file.
+ */
+struct hints_header {
+       long            hh_magic;
+#define HH_MAGIC       011421044151
+       long            hh_version;     /* Interface version number */
+#define LD_HINTS_VERSION_1     1
+#define LD_HINTS_VERSION_2     2
+       long            hh_hashtab;     /* Location of hash table */
+       long            hh_nbucket;     /* Number of buckets in hashtab */
+       long            hh_strtab;      /* Location of strings */
+       long            hh_strtab_sz;   /* Size of strings */
+       long            hh_ehints;      /* End of hints (max offset in file) */
+       long            hh_dirlist;     /* Colon-separated list of srch dirs */
+};
+
+#define HH_BADMAG(hdr) ((hdr).hh_magic != HH_MAGIC)
+
+/*
+ * Hash table element in hints file.
+ */
+struct hints_bucket {
+       /* namex and pathx are indices into the string table */
+       int             hi_namex;               /* Library name */
+       int             hi_pathx;               /* Full path */
+       int             hi_dewey[MAXDEWEY];     /* The versions */
+       int             hi_ndewey;              /* Number of version numbers */
+#define hi_major hi_dewey[0]
+#define hi_minor hi_dewey[1]
+       int             hi_next;                /* Next in this bucket */
+};
+
+#define _PATH_LD_HINTS         "/var/run/ld.so.hints"
+
+#endif /* _LINK_AOUT_H_ */
diff --git a/nbsd_include/link_elf.h b/nbsd_include/link_elf.h
new file mode 100644 (file)
index 0000000..8da504a
--- /dev/null
@@ -0,0 +1,53 @@
+/*     $NetBSD: link_elf.h,v 1.10 2010/10/16 10:27:06 skrll Exp $      */
+
+#ifndef _LINK_ELF_H_
+#define        _LINK_ELF_H_
+
+#include <sys/types.h>
+#include <sys/exec_elf.h>
+
+typedef struct link_map {
+       caddr_t          l_addr;        /* Base Address of library */
+#ifdef __mips__
+       caddr_t          l_offs;        /* Load Offset of library */
+#endif
+       const char      *l_name;        /* Absolute Path to Library */
+       void            *l_ld;          /* Pointer to .dynamic in memory */
+       struct link_map *l_next;        /* linked list of of mapped libs */
+       struct link_map *l_prev;
+} Link_map;
+
+/*
+ * This only exists for GDB.
+ */
+struct r_debug {
+       int r_version;                  /* not used */
+       struct link_map *r_map;         /* list of loaded images */
+       void (*r_brk)(void);            /* pointer to break point */
+       enum {
+               RT_CONSISTENT,          /* things are stable */
+               RT_ADD,                 /* adding a shared library */
+               RT_DELETE               /* removing a shared library */
+       } r_state;
+};
+
+struct dl_phdr_info
+{
+       Elf_Addr dlpi_addr;                     /* module relocation base */
+       const char *dlpi_name;                  /* module name */
+       const Elf_Phdr *dlpi_phdr;              /* pointer to module's phdr */
+       Elf_Half dlpi_phnum;                    /* number of entries in phdr */
+       unsigned long long int dlpi_adds;       /* total # of loads */
+       unsigned long long int dlpi_subs;       /* total # of unloads */
+       size_t dlpi_tls_modid;
+       void *dlpi_tls_data;
+};
+
+__BEGIN_DECLS
+
+int dl_iterate_phdr(int (*)(struct dl_phdr_info *, size_t, void *),
+    void *);
+
+__END_DECLS
+
+#endif /* _LINK_ELF_H_ */
diff --git a/nbsd_include/locale.h b/nbsd_include/locale.h
new file mode 100644 (file)
index 0000000..59c6879
--- /dev/null
@@ -0,0 +1,91 @@
+/*     $NetBSD: locale.h,v 1.17 2010/06/07 13:52:29 tnozaki Exp $      */
+
+/*
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ *
+ *     @(#)locale.h    8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _LOCALE_H_
+#define _LOCALE_H_
+
+struct lconv {
+       char    *decimal_point;
+       char    *thousands_sep;
+       char    *grouping;
+       char    *int_curr_symbol;
+       char    *currency_symbol;
+       char    *mon_decimal_point;
+       char    *mon_thousands_sep;
+       char    *mon_grouping;
+       char    *positive_sign;
+       char    *negative_sign;
+       char    int_frac_digits;
+       char    frac_digits;
+       char    p_cs_precedes;
+       char    p_sep_by_space;
+       char    n_cs_precedes;
+       char    n_sep_by_space;
+       char    p_sign_posn;
+       char    n_sign_posn;
+       char    int_p_cs_precedes;
+       char    int_n_cs_precedes;
+       char    int_p_sep_by_space;
+       char    int_n_sep_by_space;
+       char    int_p_sign_posn;
+       char    int_n_sign_posn;
+};
+
+#include <sys/null.h>
+
+#define        LC_ALL          0
+#define        LC_COLLATE      1
+#define        LC_CTYPE        2
+#define        LC_MONETARY     3
+#define        LC_NUMERIC      4
+#define        LC_TIME         5
+#define LC_MESSAGES    6
+
+#define        _LC_LAST        7               /* marks end */
+
+#include <sys/cdefs.h>
+
+#ifdef __SETLOCALE_SOURCE__
+
+typedef struct _locale_impl_t          *_locale_t;
+
+#define _LC_GLOBAL_LOCALE              ((_locale_t)-1)
+
+#endif
+
+__BEGIN_DECLS
+struct lconv *localeconv(void);
+char *setlocale(int, const char *) __RENAME(__setlocale50);
+__END_DECLS
+
+#endif /* _LOCALE_H_ */
diff --git a/nbsd_include/login_cap.h b/nbsd_include/login_cap.h
new file mode 100644 (file)
index 0000000..d1dc7d0
--- /dev/null
@@ -0,0 +1,92 @@
+/*     $NetBSD: login_cap.h,v 1.11 2009/01/11 03:04:12 christos Exp $  */
+
+/*-
+ * Copyright (c) 1995,1997 Berkeley Software Design, Inc. 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by Berkeley Software Design,
+ *     Inc.
+ * 4. The name of Berkeley Software Design, Inc.  may not be used to endorse
+ *    or promote products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN, INC. ``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 BERKELEY SOFTWARE DESIGN, INC. 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.
+ *
+ *     BSDI login_cap.h,v 2.10 1997/08/07 21:35:19 prb Exp
+ */
+
+#ifndef _LOGIN_CAP_H_
+#define _LOGIN_CAP_H_
+
+#define        LOGIN_DEFCLASS          "default"
+#define        LOGIN_DEFSERVICE        "login"
+#define        LOGIN_DEFUMASK          022
+#define        _PATH_LOGIN_CONF        "/etc/login.conf"
+
+#define        LOGIN_OSETGROUP         0x0001  /* Obsolete setgroup */
+#define        LOGIN_SETLOGIN          0x0002  /* Set login */
+#define        LOGIN_SETPATH           0x0004  /* Set path */
+#define        LOGIN_SETPRIORITY       0x0008  /* Set priority */
+#define        LOGIN_SETRESOURCES      0x0010  /* Set resource limits */
+#define        LOGIN_SETUMASK          0x0020  /* Set umask */
+#define        LOGIN_SETUSER           0x0040  /* Set user */
+#define        LOGIN_SETENV            0x0080  /* Set user environment */
+#define        LOGIN_SETGID            0x0100  /* Set group id */
+#define        LOGIN_SETGROUPS         0x0200  /* Set group membership (initgroups) */
+#define        LOGIN_SETALL            0x03fe  /* Set all. 0x0001 is obsolete! */
+#define        LOGIN_SETGROUP          (LOGIN_SETGID|LOGIN_SETGROUPS) /* Set group */
+
+typedef struct {
+       char    *lc_class;
+       char    *lc_cap;
+       char    *lc_style;
+} login_cap_t;
+
+typedef int (*envfunc_t)(void *, const char *, const char *, int);
+
+#include <sys/cdefs.h>
+__BEGIN_DECLS
+struct passwd;
+
+login_cap_t *login_getclass(const char *);
+#ifndef __LIBC12_SOURCE__
+login_cap_t *login_getpwclass(const struct passwd *)
+    __RENAME(__login_getpwclass50);
+#endif
+void    login_close(login_cap_t *);
+int     login_getcapbool(login_cap_t *, const char *, u_int);
+quad_t  login_getcapnum(login_cap_t *, const char *, quad_t, quad_t);
+quad_t  login_getcapsize(login_cap_t *, const char *, quad_t, quad_t);
+char   *login_getcapstr(login_cap_t *, const char *, char *, char *);
+quad_t  login_getcaptime(login_cap_t *, const char *, quad_t, quad_t);
+
+int    setclasscontext(const char *, u_int);
+#ifndef __LIBC12_SOURCE__
+int    setusercontext(login_cap_t *, struct passwd *, uid_t, u_int)
+    __RENAME(__setusercontext50);
+#endif
+void   setuserpath(login_cap_t *, const char *, envfunc_t, void *);
+int    setuserenv(login_cap_t *, envfunc_t, void *);
+
+__END_DECLS
+
+#endif /* !_LOGIN_CAP_H_ */
diff --git a/nbsd_include/lwp.h b/nbsd_include/lwp.h
new file mode 100644 (file)
index 0000000..9edc24a
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: lwp.h,v 1.11 2009/01/11 03:04:12 christos Exp $        */
+
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Nathan Williams.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _LWP_H_
+#define _LWP_H_
+
+#include <sys/cdefs.h>
+#include <sys/types.h>
+#include <sys/ucontext.h>
+#include <sys/time.h>
+
+struct lwpctl;
+
+__BEGIN_DECLS
+lwpid_t        _lwp_self(void);
+int    _lwp_create(const ucontext_t *, unsigned  long, lwpid_t *);
+int    _lwp_exit(void);
+int    _lwp_wait(lwpid_t, lwpid_t *);
+int    _lwp_suspend(lwpid_t);
+int    _lwp_continue(lwpid_t);
+int    _lwp_wakeup(lwpid_t);
+void   _lwp_makecontext(ucontext_t *, void (*)(void *), void *, void *, 
+           caddr_t, size_t);
+void   *_lwp_getprivate(void);
+void   _lwp_setprivate(void *);
+int    _lwp_kill(lwpid_t, int);
+int    _lwp_detach(lwpid_t);
+#ifndef __LIBC12_SOURCE__
+int    _lwp_park(const struct timespec *, lwpid_t, const void *, const void *)
+    __RENAME(___lwp_park50);
+#endif
+int    _lwp_unpark(lwpid_t, const void *);
+ssize_t        _lwp_unpark_all(const lwpid_t *, size_t, const void *);
+int    _lwp_setname(lwpid_t, const char *);
+int    _lwp_getname(lwpid_t, char *, size_t);
+int    _lwp_ctl(int, struct lwpctl **);
+__END_DECLS
+
+#endif /* !_LWP_H_ */
diff --git a/nbsd_include/malloc.h b/nbsd_include/malloc.h
new file mode 100644 (file)
index 0000000..fd313a3
--- /dev/null
@@ -0,0 +1,3 @@
+/*     $NetBSD: malloc.h,v 1.3 1994/10/26 00:56:03 cgd Exp $   */
+
+#include <stdlib.h>
diff --git a/nbsd_include/math.h b/nbsd_include/math.h
new file mode 100644 (file)
index 0000000..fe0251c
--- /dev/null
@@ -0,0 +1,498 @@
+/*     $NetBSD: math.h,v 1.53 2010/09/15 16:11:30 christos Exp $       */
+
+/*
+ * ====================================================
+ * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+ *
+ * Developed at SunPro, a Sun Microsystems, Inc. business.
+ * Permission to use, copy, modify, and distribute this
+ * software is freely granted, provided that this notice
+ * is preserved.
+ * ====================================================
+ */
+
+/*
+ * @(#)fdlibm.h 5.1 93/09/24
+ */
+
+#ifndef _MATH_H_
+#define _MATH_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+
+union __float_u {
+       unsigned char __dummy[sizeof(float)];
+       float __val;
+};
+
+union __double_u {
+       unsigned char __dummy[sizeof(double)];
+       double __val;
+};
+
+union __long_double_u {
+       unsigned char __dummy[sizeof(long double)];
+       long double __val;
+};
+
+#include <machine/math.h>              /* may use __float_u, __double_u,
+                                          or __long_double_u */
+
+#ifdef __HAVE_LONG_DOUBLE
+#define        __fpmacro_unary_floating(__name, __arg0)                        \
+       /* LINTED */                                                    \
+       ((sizeof (__arg0) == sizeof (float))                            \
+       ?       __ ## __name ## f (__arg0)                              \
+       : (sizeof (__arg0) == sizeof (double))                          \
+       ?       __ ## __name ## d (__arg0)                              \
+       :       __ ## __name ## l (__arg0))
+#else
+#define        __fpmacro_unary_floating(__name, __arg0)                        \
+       /* LINTED */                                                    \
+       ((sizeof (__arg0) == sizeof (float))                            \
+       ?       __ ## __name ## f (__arg0)                              \
+       :       __ ## __name ## d (__arg0))
+#endif /* __HAVE_LONG_DOUBLE */
+
+/*
+ * ANSI/POSIX
+ */
+/* 7.12#3 HUGE_VAL, HUGELF, HUGE_VALL */
+#if __GNUC_PREREQ__(3, 3)
+#define HUGE_VAL       __builtin_huge_val()
+#else
+extern const union __double_u __infinity;
+#define HUGE_VAL       __infinity.__val
+#endif
+
+/*
+ * ISO C99
+ */
+#if !defined(_ANSI_SOURCE) && !defined(_POSIX_C_SOURCE) && \
+    !defined(_XOPEN_SOURCE) || \
+    ((__STDC_VERSION__ - 0) >= 199901L) || \
+    ((_POSIX_C_SOURCE - 0) >= 200112L) || \
+    ((_XOPEN_SOURCE  - 0) >= 600) || \
+    defined(_ISOC99_SOURCE) || defined(_NETBSD_SOURCE)
+/* 7.12#3 HUGE_VAL, HUGELF, HUGE_VALL */
+#if __GNUC_PREREQ__(3, 3)
+#define        HUGE_VALF       __builtin_huge_valf()
+#define        HUGE_VALL       __builtin_huge_vall()
+#else
+extern const union __float_u __infinityf;
+#define        HUGE_VALF       __infinityf.__val
+
+extern const union __long_double_u __infinityl;
+#define        HUGE_VALL       __infinityl.__val
+#endif
+
+/* 7.12#4 INFINITY */
+#if __GNUC_PREREQ__(3, 3)
+#define        INFINITY        __builtin_inff()
+#elif defined(__INFINITY)
+#define        INFINITY        __INFINITY      /* float constant which overflows */
+#else
+#define        INFINITY        HUGE_VALF       /* positive infinity */
+#endif /* __INFINITY */
+
+/* 7.12#5 NAN: a quiet NaN, if supported */
+#ifdef __HAVE_NANF
+#if __GNUC_PREREQ__(3,3)
+#define        NAN     __builtin_nanf("")
+#else
+extern const union __float_u __nanf;
+#define        NAN             __nanf.__val
+#endif
+#endif /* __HAVE_NANF */
+
+/* 7.12#6 number classification macros */
+#define        FP_INFINITE     0x00
+#define        FP_NAN          0x01
+#define        FP_NORMAL       0x02
+#define        FP_SUBNORMAL    0x03
+#define        FP_ZERO         0x04
+/* NetBSD extensions */
+#define        _FP_LOMD        0x80            /* range for machine-specific classes */
+#define        _FP_HIMD        0xff
+
+#endif /* !_ANSI_SOURCE && ... */
+
+/*
+ * XOPEN/SVID
+ */
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+#define        M_E             2.7182818284590452354   /* e */
+#define        M_LOG2E         1.4426950408889634074   /* log 2e */
+#define        M_LOG10E        0.43429448190325182765  /* log 10e */
+#define        M_LN2           0.69314718055994530942  /* log e2 */
+#define        M_LN10          2.30258509299404568402  /* log e10 */
+#define        M_PI            3.14159265358979323846  /* pi */
+#define        M_PI_2          1.57079632679489661923  /* pi/2 */
+#define        M_PI_4          0.78539816339744830962  /* pi/4 */
+#define        M_1_PI          0.31830988618379067154  /* 1/pi */
+#define        M_2_PI          0.63661977236758134308  /* 2/pi */
+#define        M_2_SQRTPI      1.12837916709551257390  /* 2/sqrt(pi) */
+#define        M_SQRT2         1.41421356237309504880  /* sqrt(2) */
+#define        M_SQRT1_2       0.70710678118654752440  /* 1/sqrt(2) */
+
+#define        MAXFLOAT        ((float)3.40282346638528860e+38)
+extern int signgam;
+#endif /* _XOPEN_SOURCE || _NETBSD_SOURCE */
+
+#if defined(_NETBSD_SOURCE)
+enum fdversion {fdlibm_ieee = -1, fdlibm_svid, fdlibm_xopen, fdlibm_posix};
+
+#define _LIB_VERSION_TYPE enum fdversion
+#define _LIB_VERSION _fdlib_version
+
+/* if global variable _LIB_VERSION is not desirable, one may
+ * change the following to be a constant by:
+ *     #define _LIB_VERSION_TYPE const enum version
+ * In that case, after one initializes the value _LIB_VERSION (see
+ * s_lib_version.c) during compile time, it cannot be modified
+ * in the middle of a program
+ */
+extern  _LIB_VERSION_TYPE  _LIB_VERSION;
+
+#define _IEEE_  fdlibm_ieee
+#define _SVID_  fdlibm_svid
+#define _XOPEN_ fdlibm_xopen
+#define _POSIX_ fdlibm_posix
+
+#ifndef __cplusplus
+struct exception {
+       int type;
+       const char *name;
+       double arg1;
+       double arg2;
+       double retval;
+};
+#endif
+
+#define        HUGE            MAXFLOAT
+
+/*
+ * set X_TLOSS = pi*2**52, which is possibly defined in <values.h>
+ * (one may replace the following line by "#include <values.h>")
+ */
+
+#define X_TLOSS                1.41484755040568800000e+16
+
+#define        DOMAIN          1
+#define        SING            2
+#define        OVERFLOW        3
+#define        UNDERFLOW       4
+#define        TLOSS           5
+#define        PLOSS           6
+
+#endif /* _NETBSD_SOURCE */
+
+__BEGIN_DECLS
+/*
+ * ANSI/POSIX
+ */
+double acos(double);
+double asin(double);
+double atan(double);
+double atan2(double, double);
+double cos(double);
+double sin(double);
+double tan(double);
+
+double cosh(double);
+double sinh(double);
+double tanh(double);
+
+double exp(double);
+double exp2(double);
+double frexp(double, int *);
+double ldexp(double, int);
+double log(double);
+double log2(double);
+double log10(double);
+double modf(double, double *);
+
+double pow(double, double);
+double sqrt(double);
+
+double ceil(double);
+double fabs(double);
+double floor(double);
+double fmod(double, double);
+
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+double erf(double);
+double erfc(double);
+double gamma(double);
+double hypot(double, double);
+int    finite(double);
+double j0(double);
+double j1(double);
+double jn(int, double);
+double lgamma(double);
+double y0(double);
+double y1(double);
+double yn(int, double);
+
+#if (_XOPEN_SOURCE - 0) >= 500 || defined(_NETBSD_SOURCE)
+double acosh(double);
+double asinh(double);
+double atanh(double);
+double cbrt(double);
+double expm1(double);
+int    ilogb(double);
+double log1p(double);
+double logb(double);
+double nextafter(double, double);
+double remainder(double, double);
+double rint(double);
+double scalb(double, double);
+#endif /* (_XOPEN_SOURCE - 0) >= 500 || defined(_NETBSD_SOURCE)*/
+#endif /* _XOPEN_SOURCE || _NETBSD_SOURCE */
+
+/*
+ * ISO C99
+ */
+#if !defined(_ANSI_SOURCE) && !defined(_POSIX_C_SOURCE) && \
+    !defined(_XOPEN_SOURCE) || \
+    ((__STDC_VERSION__ - 0) >= 199901L) || \
+    ((_POSIX_C_SOURCE - 0) >= 200112L) || \
+    ((_XOPEN_SOURCE  - 0) >= 600) || \
+    defined(_ISOC99_SOURCE) || defined(_NETBSD_SOURCE)
+/* 7.12.3.1 int fpclassify(real-floating x) */
+#define        fpclassify(__x) __fpmacro_unary_floating(fpclassify, __x)
+
+/* 7.12.3.2 int isfinite(real-floating x) */
+#define        isfinite(__x)   __fpmacro_unary_floating(isfinite, __x)
+
+/* 7.12.3.5 int isnormal(real-floating x) */
+#define        isnormal(__x)   (fpclassify(__x) == FP_NORMAL)
+
+/* 7.12.3.6 int signbit(real-floating x) */
+#define        signbit(__x)    __fpmacro_unary_floating(signbit, __x)
+
+/* 7.12.4 trigonometric */
+
+float  acosf(float);
+float  asinf(float);
+float  atanf(float);
+float  atan2f(float, float);
+float  cosf(float);
+float  sinf(float);
+float  tanf(float);
+
+/* 7.12.5 hyperbolic */
+
+float  acoshf(float);
+float  asinhf(float);
+float  atanhf(float);
+float  coshf(float);
+float  sinhf(float);
+float  tanhf(float);
+
+/* 7.12.6 exp / log */
+
+float  expf(float);
+float  exp2f(float);
+float  expm1f(float);
+float  frexpf(float, int *);
+int    ilogbf(float);
+float  ldexpf(float, int);
+float  logf(float);
+float  log2f(float);
+float  log10f(float);
+float  log1pf(float);
+float  logbf(float);
+float  modff(float, float *);
+float  scalbnf(float, int);
+
+/* 7.12.7 power / absolute */
+
+float  cbrtf(float);
+float  fabsf(float);
+long double    fabsl(long double);
+float  hypotf(float, float);
+float  powf(float, float);
+float  sqrtf(float);
+
+/* 7.12.8 error / gamma */
+
+float  erff(float);
+float  erfcf(float);
+float  lgammaf(float);
+
+/* 7.12.9 nearest integer */
+
+float  ceilf(float);
+float  floorf(float);
+float  rintf(float);
+double round(double);
+float  roundf(float);
+double trunc(double);
+float  truncf(float);
+long int       lrint(double);
+long int       lrintf(float);
+/* LONGLONG */
+long long int  llrint(double);
+/* LONGLONG */
+long long int  llrintf(float);
+long int       lround(double);
+long int       lroundf(float);
+/* LONGLONG */
+long long int  llround(double);
+/* LONGLONG */
+long long int  llroundf(float);
+
+/* 7.12.10 remainder */
+
+float  fmodf(float, float);
+float  remainderf(float, float);
+
+/* 7.12.11 manipulation */
+
+float  copysignf(float, float);
+long double    copysignl(long double, long double);
+double nan(const char *);
+float  nanf(const char *);
+long double    nanl(const char *);
+float  nextafterf(float, float);
+long double     nextafterl(long double, long double);
+double nexttoward(double, long double);
+
+/* 7.12.14 comparison */
+
+#define isunordered(x, y)      (isnan(x) || isnan(y))
+#define isgreater(x, y)                (!isunordered((x), (y)) && (x) > (y))
+#define isgreaterequal(x, y)   (!isunordered((x), (y)) && (x) >= (y))
+#define isless(x, y)           (!isunordered((x), (y)) && (x) < (y))
+#define islessequal(x, y)      (!isunordered((x), (y)) && (x) <= (y))
+#define islessgreater(x, y)    (!isunordered((x), (y)) && \
+                                ((x) > (y) || (y) > (x)))
+double fdim(double, double);
+double fmax(double, double);
+double fmin(double, double);
+float  fdimf(float, float);
+float  fmaxf(float, float);
+float  fminf(float, float);
+long double fdiml(long double, long double);
+long double fmaxl(long double, long double);
+long double fminl(long double, long double);
+
+#endif /* !_ANSI_SOURCE && ... */
+
+#if !defined(_ANSI_SOURCE) && !defined(_POSIX_C_SOURCE) || \
+    !defined(_XOPEN_SOURCE) || \
+    ((__STDC_VERSION__ - 0) >= 199901L) || \
+    ((_POSIX_C_SOURCE - 0) >= 200112L) || \
+    defined(_ISOC99_SOURCE) || defined(_NETBSD_SOURCE)
+/* 7.12.3.3 int isinf(real-floating x) */
+#ifdef __isinf
+#define        isinf(__x)      __isinf(__x)
+#else
+#define        isinf(__x)      __fpmacro_unary_floating(isinf, __x)
+#endif
+
+/* 7.12.3.4 int isnan(real-floating x) */
+#ifdef __isnan
+#define        isnan(__x)      __isnan(__x)
+#else
+#define        isnan(__x)      __fpmacro_unary_floating(isnan, __x)
+#endif
+#endif /* !_ANSI_SOURCE && ... */
+
+#if defined(_NETBSD_SOURCE)
+#ifndef __cplusplus
+int    matherr(struct exception *);
+#endif
+
+/*
+ * IEEE Test Vector
+ */
+double significand(double);
+
+/*
+ * Functions callable from C, intended to support IEEE arithmetic.
+ */
+double copysign(double, double);
+double scalbn(double, int);
+
+/*
+ * BSD math library entry points
+ */
+double drem(double, double);
+
+#endif /* _NETBSD_SOURCE */
+
+#if defined(_NETBSD_SOURCE) || defined(_REENTRANT)
+/*
+ * Reentrant version of gamma & lgamma; passes signgam back by reference
+ * as the second argument; user must allocate space for signgam.
+ */
+double gamma_r(double, int *);
+double lgamma_r(double, int *);
+#endif /* _NETBSD_SOURCE || _REENTRANT */
+
+
+#if defined(_NETBSD_SOURCE)
+
+/* float versions of ANSI/POSIX functions */
+
+float  gammaf(float);
+int    isinff(float);
+int    isnanf(float);
+int    finitef(float);
+float  j0f(float);
+float  j1f(float);
+float  jnf(int, float);
+float  y0f(float);
+float  y1f(float);
+float  ynf(int, float);
+
+float  scalbf(float, float);
+
+/*
+ * float version of IEEE Test Vector
+ */
+float  significandf(float);
+
+/*
+ * float versions of BSD math library entry points
+ */
+float  dremf(float, float);
+#endif /* _NETBSD_SOURCE */
+
+#if defined(_NETBSD_SOURCE) || defined(_REENTRANT)
+/*
+ * Float versions of reentrant version of gamma & lgamma; passes
+ * signgam back by reference as the second argument; user must
+ * allocate space for signgam.
+ */
+float  gammaf_r(float, int *);
+float  lgammaf_r(float, int *);
+#endif /* !... || _REENTRANT */
+
+/*
+ * Library implementation
+ */
+int    __fpclassifyf(float);
+int    __fpclassifyd(double);
+int    __isfinitef(float);
+int    __isfinited(double);
+int    __isinff(float);
+int    __isinfd(double);
+int    __isnanf(float);
+int    __isnand(double);
+int    __signbitf(float);
+int    __signbitd(double);
+
+#ifdef __HAVE_LONG_DOUBLE
+int    __fpclassifyl(long double);
+int    __isfinitel(long double);
+int    __isinfl(long double);
+int    __isnanl(long double);
+int    __signbitl(long double);
+#endif
+__END_DECLS
+
+#endif /* _MATH_H_ */
diff --git a/nbsd_include/md2.h b/nbsd_include/md2.h
new file mode 100644 (file)
index 0000000..b89f0a7
--- /dev/null
@@ -0,0 +1,29 @@
+/*     $NetBSD: md2.h,v 1.6 2005/12/26 19:01:47 perry Exp $    */
+
+#ifndef _MD2_H_
+#define _MD2_H_
+
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+#define        MD2_DIGEST_LENGTH               16
+#define        MD2_DIGEST_STRING_LENGTH        33
+
+/* MD2 context. */
+typedef struct MD2Context {
+       uint32_t i;
+       unsigned char C[16];            /* checksum */
+       unsigned char X[48];            /* input buffer */
+} MD2_CTX;
+
+__BEGIN_DECLS
+void   MD2Init(MD2_CTX *);
+void   MD2Update(MD2_CTX *, const unsigned char *, unsigned int);
+void   MD2Final(unsigned char[16], MD2_CTX *);
+char   *MD2End(MD2_CTX *, char *);
+char   *MD2File(const char *, char *);
+char   *MD2FileChunk(const char *, char *, off_t, off_t);
+char   *MD2Data(const unsigned char *, size_t, char *);
+__END_DECLS
+
+#endif /* _MD2_H_ */
diff --git a/nbsd_include/memory.h b/nbsd_include/memory.h
new file mode 100644 (file)
index 0000000..a4c1b0c
--- /dev/null
@@ -0,0 +1,34 @@
+/*     $NetBSD: memory.h,v 1.5 2003/08/07 09:44:10 agc Exp $   */
+
+/*
+ * Copyright (c) 1988, 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.
+ * 3. 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.
+ *
+ *     @(#)memory.h    8.1 (Berkeley) 6/2/93
+ */
+
+#include <string.h>
diff --git a/nbsd_include/mntopts.h b/nbsd_include/mntopts.h
new file mode 100644 (file)
index 0000000..8e76a6e
--- /dev/null
@@ -0,0 +1,106 @@
+/*     $NetBSD: mntopts.h,v 1.13 2009/01/12 18:14:20 pooka Exp $       */
+
+/*-
+ * Copyright (c) 1994
+ *      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.
+ * 3. 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.
+ *
+ *     @(#)mntopts.h   8.7 (Berkeley) 3/29/95
+ */
+#ifndef _MNTOPTS_H_
+#define _MNTOPTS_H_
+
+struct mntopt {
+       const char *m_option;   /* option name */
+       int m_inverse;          /* if a negative option, eg "dev" */
+       int m_flag;             /* bit to set, eg. MNT_RDONLY */
+       int m_altloc;           /* 1 => set bit in altflags */
+};
+
+/* User-visible MNT_ flags. */
+#define MOPT_ASYNC             { "async",      0, MNT_ASYNC, 0 }
+#define MOPT_NOCOREDUMP                { "coredump",   1, MNT_NOCOREDUMP, 0 }
+#define MOPT_NODEV             { "dev",        1, MNT_NODEV, 0 }
+#define MOPT_NODEVMTIME                { "devmtime",   1, MNT_NODEVMTIME, 0 }
+#define MOPT_NOEXEC            { "exec",       1, MNT_NOEXEC, 0 }
+#define MOPT_NOSUID            { "suid",       1, MNT_NOSUID, 0 }
+#define MOPT_RDONLY            { "rdonly",     0, MNT_RDONLY, 0 }
+#define MOPT_SYNC              { "sync",       0, MNT_SYNCHRONOUS, 0 }
+#define MOPT_UNION             { "union",      0, MNT_UNION, 0 }
+#define MOPT_USERQUOTA         { "userquota",  0, 0, 0 }
+#define MOPT_GROUPQUOTA                { "groupquota", 0, 0, 0 }
+#define MOPT_NOATIME           { "atime",      1, MNT_NOATIME, 0 }
+#define MOPT_SYMPERM           { "symperm",    0, MNT_SYMPERM, 0 }
+#define MOPT_SOFTDEP           { "softdep",    0, MNT_SOFTDEP, 0 }
+#define MOPT_LOG               { "log",        0, MNT_LOG, 0 }
+#define MOPT_IGNORE            { "hidden",     0, MNT_IGNORE, 0 }
+
+/* Control flags. */
+#define MOPT_FORCE             { "force",      0, MNT_FORCE, 0 }
+#define MOPT_UPDATE            { "update",     0, MNT_UPDATE, 0 }
+#define MOPT_RELOAD            { "reload",     0, MNT_RELOAD, 0 }
+#define MOPT_GETARGS           { "getargs",    0, MNT_GETARGS, 0 }
+
+/* Support for old-style "ro", "rw" flags. */
+#define MOPT_RO                        { "ro",         0, MNT_RDONLY, 0 }
+#define MOPT_RW                        { "rw",         1, MNT_RDONLY, 0 }
+
+/* This is parsed by mount(8), but is ignored by specific mount_*(8)s. */
+#define MOPT_AUTO              { "auto",       0, 0, 0 }
+#define MOPT_RUMP              { "rump",       0, 0, 0 }
+#define MOPT_NULL              { NULL,         0, 0, 0 }
+
+#define MOPT_FSTAB_COMPAT                                              \
+       MOPT_RO,                                                        \
+       MOPT_RW,                                                        \
+       MOPT_AUTO
+
+/* Standard options which all mounts can understand. */
+#define MOPT_STDOPTS                                                   \
+       MOPT_USERQUOTA,                                                 \
+       MOPT_GROUPQUOTA,                                                \
+       MOPT_FSTAB_COMPAT,                                              \
+       MOPT_NOCOREDUMP,                                                \
+       MOPT_NODEV,                                                     \
+       MOPT_NOEXEC,                                                    \
+       MOPT_NOSUID,                                                    \
+       MOPT_RDONLY,                                                    \
+       MOPT_UNION,                                                     \
+       MOPT_IGNORE,                                                    \
+       MOPT_SYMPERM,                                                   \
+       MOPT_RUMP
+
+__BEGIN_DECLS
+typedef struct mntoptparse *mntoptparse_t;
+mntoptparse_t getmntopts(const char *, const struct mntopt *, int *, int *);
+const char *getmntoptstr(mntoptparse_t, const char *);
+long getmntoptnum(mntoptparse_t, const char *);
+void freemntopts(mntoptparse_t);
+
+extern int getmnt_silent;
+__END_DECLS
+
+#endif /* _MNTOPTS_H_ */
diff --git a/nbsd_include/monetary.h b/nbsd_include/monetary.h
new file mode 100644 (file)
index 0000000..76951d7
--- /dev/null
@@ -0,0 +1,52 @@
+/*     $NetBSD: monetary.h,v 1.2 2008/09/21 16:59:46 christos Exp $    */
+
+/*-
+ * Copyright (c) 2001 Alexey Zelkin <phantom@FreeBSD.org>
+ * 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.
+ *
+ * $FreeBSD: src/include/monetary.h,v 1.7 2002/09/20 08:22:48 mike Exp $
+ */
+
+#ifndef _MONETARY_H_
+#define        _MONETARY_H_
+
+#include <sys/cdefs.h>
+#include <machine/ansi.h>
+
+#ifdef _BSD_SIZE_T_
+typedef        _BSD_SIZE_T_    size_t;
+#undef _BSD_SIZE_T_
+#endif
+
+#ifdef _BSD_SSIZE_T_
+typedef        _BSD_SSIZE_T_   ssize_t;
+#undef _BSD_SSIZE_T_
+#endif
+
+__BEGIN_DECLS
+ssize_t        strfmon(char * __restrict, size_t, const char * __restrict, ...)
+    __attribute__((__format__(__strfmon__, 3, 4)));
+__END_DECLS
+
+#endif /* !_MONETARY_H_ */
diff --git a/nbsd_include/mpool.h b/nbsd_include/mpool.h
new file mode 100644 (file)
index 0000000..800efae
--- /dev/null
@@ -0,0 +1,103 @@
+/*     $NetBSD: mpool.h,v 1.13 2008/08/26 21:18:38 joerg Exp $ */
+
+/*-
+ * Copyright (c) 1991, 1993, 1994
+ *     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.
+ * 3. 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.
+ *
+ *     @(#)mpool.h     8.2 (Berkeley) 7/14/94
+ */
+
+#ifndef _MPOOL_H_
+#define _MPOOL_H_
+
+#include <sys/cdefs.h>
+#include <sys/queue.h>
+
+/*
+ * The memory pool scheme is a simple one.  Each in-memory page is referenced
+ * by a bucket which is threaded in up to two of three ways.  All active pages
+ * are threaded on a hash chain (hashed by page number) and an lru chain.
+ * Inactive pages are threaded on a free chain.  Each reference to a memory
+ * pool is handed an opaque MPOOL cookie which stores all of this information.
+ */
+#define        HASHSIZE        128
+#define        HASHKEY(pgno)   ((pgno - 1) % HASHSIZE)
+
+/* The BKT structures are the elements of the queues. */
+typedef struct _bkt {
+       CIRCLEQ_ENTRY(_bkt) hq;         /* hash queue */
+       CIRCLEQ_ENTRY(_bkt) q;          /* lru queue */
+       void    *page;                  /* page */
+       pgno_t   pgno;                  /* page number */
+
+#define        MPOOL_DIRTY     0x01            /* page needs to be written */
+#define        MPOOL_PINNED    0x02            /* page is pinned into memory */
+       uint8_t flags;                  /* flags */
+} BKT;
+
+typedef struct MPOOL {
+       CIRCLEQ_HEAD(_lqh, _bkt) lqh;   /* lru queue head */
+                                       /* hash queue array */
+       CIRCLEQ_HEAD(_hqh, _bkt) hqh[HASHSIZE];
+       pgno_t  curcache;               /* current number of cached pages */
+       pgno_t  maxcache;               /* max number of cached pages */
+       pgno_t  npages;                 /* number of pages in the file */
+       unsigned long   pagesize;               /* file page size */
+       int     fd;                     /* file descriptor */
+                                       /* page in conversion routine */
+       void    (*pgin)(void *, pgno_t, void *);
+                                       /* page out conversion routine */
+       void    (*pgout)(void *, pgno_t, void *);
+       void    *pgcookie;              /* cookie for page in/out routines */
+#ifdef STATISTICS
+       unsigned long   cachehit;
+       unsigned long   cachemiss;
+       unsigned long   pagealloc;
+       unsigned long   pageflush;
+       unsigned long   pageget;
+       unsigned long   pagenew;
+       unsigned long   pageput;
+       unsigned long   pageread;
+       unsigned long   pagewrite;
+#endif
+} MPOOL;
+
+__BEGIN_DECLS
+MPOOL  *mpool_open(void *, int, pgno_t, pgno_t);
+void    mpool_filter(MPOOL *, void (*)(void *, pgno_t, void *),
+           void (*)(void *, pgno_t, void *), void *);
+void   *mpool_new(MPOOL *, pgno_t *);
+void   *mpool_get(MPOOL *, pgno_t, unsigned int);
+int     mpool_put(MPOOL *, void *, unsigned int);
+int     mpool_sync(MPOOL *);
+int     mpool_close(MPOOL *);
+#ifdef STATISTICS
+void    mpool_stat(MPOOL *);
+#endif
+__END_DECLS
+
+#endif /* _MPOOL_H_ */
diff --git a/nbsd_include/mqueue.h b/nbsd_include/mqueue.h
new file mode 100644 (file)
index 0000000..d845eb4
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: mqueue.h,v 1.4 2009/01/11 03:04:12 christos Exp $      */
+
+/*
+ * Copyright (c) 2007, Mindaugas Rasiukevicius <rmind at NetBSD org>
+ * 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.
+ */
+
+#ifndef _MQUEUE_H_
+#define _MQUEUE_H_
+
+#include <fcntl.h>
+#include <signal.h>
+#include <time.h>
+
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+#include <sys/mqueue.h>
+
+__BEGIN_DECLS
+int    mq_close(mqd_t);
+int    mq_getattr(mqd_t, struct mq_attr *);
+int    mq_notify(mqd_t, const struct sigevent *);
+mqd_t  mq_open(const char *, int, ...);
+ssize_t        mq_receive(mqd_t, char *, size_t, unsigned *);
+int    mq_send(mqd_t, const char *, size_t, unsigned);
+int    mq_setattr(mqd_t, const struct mq_attr * __restrict,
+                   struct mq_attr * __restrict);
+#ifndef __LIBC12_SOURCE__
+ssize_t        mq_timedreceive(mqd_t, char * __restrict, size_t,
+    unsigned * __restrict, const struct timespec * __restrict)
+    __RENAME(__mq_timedreceive50);
+int    mq_timedsend(mqd_t, const char *, size_t, unsigned,
+    const struct timespec *) __RENAME(__mq_timedsend50);
+#endif
+int    mq_unlink(const char *);
+__END_DECLS
+
+#endif /* _MQUEUE_H_ */
diff --git a/nbsd_include/ndbm.h b/nbsd_include/ndbm.h
new file mode 100644 (file)
index 0000000..23b993d
--- /dev/null
@@ -0,0 +1,89 @@
+/*     $NetBSD: ndbm.h,v 1.15 2010/02/03 15:34:40 roy Exp $    */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Margo Seltzer.
+ *
+ * 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. 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.
+ *
+ *     @(#)ndbm.h      8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _NDBM_H_
+#define        _NDBM_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <stdint.h>
+#include <db.h>
+
+#if defined(_NETBSD_SOURCE)
+/* Map dbm interface onto db(3). */
+#define DBM_RDONLY     O_RDONLY
+#endif
+
+/* Flags to dbm_store(). */
+#define DBM_INSERT      0
+#define DBM_REPLACE     1
+
+#if defined(_NETBSD_SOURCE)
+/*
+ * The db(3) support for ndbm(3) always appends this suffix to the
+ * file name to avoid overwriting the user's original database.
+ */
+#define        DBM_SUFFIX      ".db"
+#endif
+
+typedef struct {
+       void    *dptr;
+       size_t   dsize;         /* XPG4.2 */
+} datum;
+
+typedef DB DBM;
+#if defined(_NETBSD_SOURCE)
+#define        dbm_pagfno(a)   DBM_PAGFNO_NOT_AVAILABLE
+#endif
+
+__BEGIN_DECLS
+void    dbm_close(DBM *);
+DBM    *dbm_open(const char *, int, mode_t);
+int     dbm_error(DBM *);
+int     dbm_clearerr(DBM *);
+#if defined(_NETBSD_SOURCE)
+int     dbm_dirfno(DBM *);
+#endif
+#ifndef __LIBC12_SOURCE__
+int     dbm_delete(DBM *, datum)               __RENAME(__dbm_delete13);
+datum   dbm_fetch(DBM *, datum)                __RENAME(__dbm_fetch13);
+datum   dbm_firstkey(DBM *)                    __RENAME(__dbm_firstkey13);
+datum   dbm_nextkey(DBM *)                     __RENAME(__dbm_nextkey13);
+int     dbm_store(DBM *, datum, datum, int)    __RENAME(__dbm_store13);
+#endif
+__END_DECLS
+
+#endif /* !_NDBM_H_ */
diff --git a/nbsd_include/netconfig.h b/nbsd_include/netconfig.h
new file mode 100644 (file)
index 0000000..c47808a
--- /dev/null
@@ -0,0 +1,123 @@
+/*     $NetBSD: netconfig.h,v 1.6 2008/04/28 20:22:54 martin Exp $     */
+
+/*-
+ * Copyright (c) 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Frank van der Linden.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _NETCONFIG_H_
+#define _NETCONFIG_H_
+
+#include <sys/cdefs.h>
+
+#define NETCONFIG      "/etc/netconfig"
+#define NETPATH                "NETPATH"
+
+struct netconfig {
+       char *nc_netid;                 /* Network ID */
+       unsigned long nc_semantics;     /* Semantics (see below) */
+       unsigned long nc_flag;          /* Flags (see below) */
+       char *nc_protofmly;             /* Protocol family */
+       char *nc_proto;                 /* Protocol name */
+       char *nc_device;                /* Network device pathname */
+       unsigned long nc_nlookups;      /* Number of directory lookup libs */
+       char **nc_lookups;              /* Names of the libraries */
+       unsigned long nc_unused[9];     /* reserved */
+};
+
+typedef struct {
+       struct netconfig **nc_head;
+       struct netconfig **nc_curr;
+} NCONF_HANDLE;
+
+/*
+ * nc_semantics values
+ */
+#define NC_TPI_CLTS    1       /* Connectionless transport */
+#define NC_TPI_COTS    2       /* Connection oriented transport */
+#define NC_TPI_COTS_ORD        3       /* Connection oriented, ordered transport */
+#define NC_TPI_RAW     4       /* Raw connection */
+
+/*
+ * nc_flag values
+ */
+#define NC_NOFLAG      0x00
+#define NC_VISIBLE     0x01
+#define NC_BROADCAST   0x02
+
+/*
+ * nc_protofmly values
+ */
+#define NC_NOPROTOFMLY "-"
+#define NC_LOOPBACK    "loopback"
+#define NC_INET                "inet"
+#define NC_INET6       "inet6"
+#define NC_IMPLINK     "implink"
+#define NC_PUP         "pup"
+#define NC_CHAOS       "chaos"
+#define NC_NS          "ns"
+#define NC_NBS         "nbs"
+#define NC_ECMA                "ecma"
+#define NC_DATAKIT     "datakit"
+#define NC_CCITT       "ccitt"
+#define NC_SNA         "sna"
+#define NC_DECNET      "decnet"
+#define NC_DLI         "dli"
+#define NC_LAT         "lat"
+#define NC_HYLINK      "hylink"
+#define NC_APPLETALK   "appletalk"
+#define NC_NIT         "nit"
+#define NC_IEEE802     "ieee802"
+#define NC_OSI         "osi"
+#define NC_X25         "x25"
+#define NC_OSINET      "osinet"
+#define NC_GOSIP       "gosip"
+
+/*
+ * nc_proto values
+ */
+#define NC_NOPROTO     "-"
+#define NC_TCP         "tcp"
+#define NC_UDP         "udp"
+#define NC_ICMP                "icmp"
+
+__BEGIN_DECLS
+void *setnetconfig(void);
+struct netconfig *getnetconfig(void *);
+struct netconfig *getnetconfigent(const char *);
+void freenetconfigent(struct netconfig *);
+int endnetconfig(void *);
+
+void *setnetpath(void);
+struct netconfig *getnetpath(void *);
+int endnetpath(void *);
+
+void nc_perror(const char *);
+char *nc_sperror(void);
+__END_DECLS
+
+#endif /* _NETCONFIG_H_ */
diff --git a/nbsd_include/netdb.h b/nbsd_include/netdb.h
new file mode 100644 (file)
index 0000000..24761fa
--- /dev/null
@@ -0,0 +1,355 @@
+/*     $NetBSD: netdb.h,v 1.64 2010/05/05 17:12:29 christos Exp $      */
+
+/*
+ * ++Copyright++ 1980, 1983, 1988, 1993
+ * -
+ * Copyright (c) 1980, 1983, 1988, 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.
+ * 3. 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.
+ * -
+ * Portions Copyright (c) 1993 by Digital Equipment Corporation.
+ *
+ * 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, and that
+ * the name of Digital Equipment Corporation not be used in advertising or
+ * publicity pertaining to distribution of the document or software without
+ * specific, written prior permission.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
+ * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
+ * CORPORATION 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.
+ * -
+ * Portions Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
+ * 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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *    This product includes software developed by WIDE Project and
+ *    its contributors.
+ * 4. Neither the name of the project 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 PROJECT 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 PROJECT 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.
+ * -
+ * --Copyright--
+ */
+
+/*
+ *      @(#)netdb.h    8.1 (Berkeley) 6/2/93
+ *     Id: netdb.h,v 1.22 2008/02/28 05:34:17 marka Exp
+ */
+
+#ifndef _NETDB_H_
+#define        _NETDB_H_
+
+#include <machine/ansi.h>
+#include <machine/endian_machdep.h>
+#include <sys/ansi.h>
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <inttypes.h>
+/*
+ * Data types
+ */
+#ifndef socklen_t
+typedef __socklen_t    socklen_t;
+#define        socklen_t       __socklen_t
+#endif
+
+#ifdef  _BSD_SIZE_T_
+typedef _BSD_SIZE_T_   size_t;
+#undef  _BSD_SIZE_T_
+#endif
+
+#if defined(_NETBSD_SOURCE)
+#ifndef _PATH_HEQUIV
+#define        _PATH_HEQUIV    "/etc/hosts.equiv"
+#endif
+#ifndef _PATH_HOSTS
+#define        _PATH_HOSTS     "/etc/hosts"
+#endif
+#ifndef _PATH_NETWORKS
+#define        _PATH_NETWORKS  "/etc/networks"
+#endif
+#ifndef _PATH_PROTOCOLS
+#define        _PATH_PROTOCOLS "/etc/protocols"
+#endif
+#ifndef _PATH_SERVICES
+#define        _PATH_SERVICES  "/etc/services"
+#endif
+#ifndef _PATH_SERVICES_CDB
+#define        _PATH_SERVICES_CDB "/var/db/services.cdb"
+#endif
+#ifndef _PATH_SERVICES_DB
+#define        _PATH_SERVICES_DB "/var/db/services.db"
+#endif
+#endif
+
+__BEGIN_DECLS
+extern int h_errno;
+extern int * __h_errno(void);
+#ifdef _REENTRANT
+#define        h_errno (*__h_errno())
+#endif
+__END_DECLS
+
+/*%
+ * Structures returned by network data base library.  All addresses are
+ * supplied in host order, and returned in network order (suitable for
+ * use in system calls).
+ */
+struct hostent {
+       char    *h_name;        /*%< official name of host */
+       char    **h_aliases;    /*%< alias list */
+       int     h_addrtype;     /*%< host address type */
+       int     h_length;       /*%< length of address */
+       char    **h_addr_list;  /*%< list of addresses from name server */
+#define        h_addr  h_addr_list[0]  /*%< address, for backward compatiblity */
+};
+
+/*%
+ * Assumption here is that a network number
+ * fits in an unsigned long -- probably a poor one.
+ */
+struct netent {
+       char            *n_name;        /*%< official name of net */
+       char            **n_aliases;    /*%< alias list */
+       int             n_addrtype;     /*%< net address type */
+#if (defined(__sparc__) && defined(_LP64)) || \
+    (defined(__sh__) && defined(_LP64) && (_BYTE_ORDER == _BIG_ENDIAN))
+       int             __n_pad0;       /* ABI compatibility */
+#endif
+       uint32_t        n_net;          /*%< network # */
+#if defined(__alpha__) || (defined(__i386__) && defined(_LP64)) || \
+    (defined(__sh__) && defined(_LP64) && (_BYTE_ORDER == _LITTLE_ENDIAN))
+       int             __n_pad0;       /* ABI compatibility */
+#endif
+};
+
+struct servent {
+       char    *s_name;        /*%< official service name */
+       char    **s_aliases;    /*%< alias list */
+       int     s_port;         /*%< port # */
+       char    *s_proto;       /*%< protocol to use */
+};
+
+struct protoent {
+       char    *p_name;        /*%< official protocol name */
+       char    **p_aliases;    /*%< alias list */
+       int     p_proto;        /*%< protocol # */
+};
+
+/*
+ * Note: ai_addrlen used to be a size_t, per RFC 2553.
+ * In XNS5.2, and subsequently in POSIX-2001 and
+ * draft-ietf-ipngwg-rfc2553bis-02.txt it was changed to a socklen_t.
+ * To accommodate for this while preserving binary compatibility with the
+ * old interface, we prepend or append 32 bits of padding, depending on
+ * the (LP64) architecture's endianness.
+ *
+ * This should be deleted the next time the libc major number is
+ * incremented.
+ */
+#if (_POSIX_C_SOURCE - 0) >= 200112L || (_XOPEN_SOURCE - 0) >= 520 || \
+    defined(_NETBSD_SOURCE)
+struct addrinfo {
+       int             ai_flags;       /*%< AI_PASSIVE, AI_CANONNAME */
+       int             ai_family;      /*%< PF_xxx */
+       int             ai_socktype;    /*%< SOCK_xxx */
+       int             ai_protocol;    /*%< 0 or IPPROTO_xxx for IPv4 and IPv6 */
+#if defined(__sparc__) && defined(_LP64)
+       int             __ai_pad0;      /* ABI compatibility */
+#endif
+       socklen_t        ai_addrlen;    /*%< length of ai_addr */
+#if defined(__alpha__) || (defined(__i386__) && defined(_LP64))
+       int             __ai_pad0;      /* ABI compatibility */
+#endif
+       char            *ai_canonname;  /*%< canonical name for hostname */
+       struct sockaddr *ai_addr;       /*%< binary address */
+       struct addrinfo *ai_next;       /*%< next structure in linked list */
+};
+#endif
+
+/*%
+ * Error return codes from gethostbyname() and gethostbyaddr()
+ * (left in extern int h_errno).
+ */
+
+#if defined(_NETBSD_SOURCE)
+#define        NETDB_INTERNAL  -1      /*%< see errno */
+#define        NETDB_SUCCESS   0       /*%< no problem */
+#endif
+#define        NO_ADDRESS      NO_DATA         /* no address, look for MX record */
+#define        HOST_NOT_FOUND  1 /*%< Authoritative Answer Host not found */
+#define        TRY_AGAIN       2 /*%< Non-Authoritive Host not found, or SERVERFAIL */
+#define        NO_RECOVERY     3 /*%< Non recoverable errors, FORMERR, REFUSED, NOTIMP */
+#define        NO_DATA         4 /*%< Valid name, no data record of requested type */
+#if defined(_NETBSD_SOURCE)
+#define        NO_ADDRESS      NO_DATA         /*%< no address, look for MX record */
+#endif
+
+/*
+ * Error return codes from getaddrinfo()
+ */
+#if (_POSIX_C_SOURCE - 0) >= 200112L || (_XOPEN_SOURCE - 0) >= 520 || \
+    defined(_NETBSD_SOURCE)
+#define        EAI_ADDRFAMILY   1      /*%< address family for hostname not supported */
+#define        EAI_AGAIN        2      /*%< temporary failure in name resolution */
+#define        EAI_BADFLAGS     3      /*%< invalid value for ai_flags */
+#define        EAI_FAIL         4      /*%< non-recoverable failure in name resolution */
+#define        EAI_FAMILY       5      /*%< ai_family not supported */
+#define        EAI_MEMORY       6      /*%< memory allocation failure */
+#define        EAI_NODATA       7      /*%< no address associated with hostname */
+#define        EAI_NONAME       8      /*%< hostname nor servname provided, or not known */
+#define        EAI_SERVICE      9      /*%< servname not supported for ai_socktype */
+#define        EAI_SOCKTYPE    10      /*%< ai_socktype not supported */
+#define        EAI_SYSTEM      11      /*%< system error returned in errno */
+#define        EAI_BADHINTS    12      /* invalid value for hints */
+#define        EAI_PROTOCOL    13      /* resolved protocol is unknown */
+#define        EAI_OVERFLOW    14      /* argument buffer overflow */
+#define        EAI_MAX         15
+#endif /* _POSIX_C_SOURCE >= 200112 || _XOPEN_SOURCE >= 520 || _NETBSD_SOURCE */
+
+/*%
+ * Flag values for getaddrinfo()
+ */
+#if (_POSIX_C_SOURCE - 0) >= 200112L || (_XOPEN_SOURCE - 0) >= 520 || \
+    defined(_NETBSD_SOURCE)
+#define        AI_PASSIVE      0x00000001 /* get address to use bind() */
+#define        AI_CANONNAME    0x00000002 /* fill ai_canonname */
+#define        AI_NUMERICHOST  0x00000004 /* prevent host name resolution */
+#define        AI_NUMERICSERV  0x00000008 /* prevent service name resolution */
+/* valid flags for addrinfo (not a standard def, apps should not use it) */
+#define        AI_MASK \
+    (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST | AI_NUMERICSERV)
+#endif
+
+#if (_POSIX_C_SOURCE - 0) >= 200112L || (_XOPEN_SOURCE - 0) >= 520 || \
+    defined(_NETBSD_SOURCE)
+/*%
+ * Constants for getnameinfo()
+ */
+#if defined(_NETBSD_SOURCE)
+#define        NI_MAXHOST      1025
+#define        NI_MAXSERV      32
+#endif
+
+/*%
+ * Flag values for getnameinfo()
+ */
+#define        NI_NOFQDN       0x00000001
+#define        NI_NUMERICHOST  0x00000002
+#define        NI_NAMEREQD     0x00000004
+#define        NI_NUMERICSERV  0x00000008
+#define        NI_DGRAM        0x00000010
+#define        NI_WITHSCOPEID  0x00000020
+#define        NI_NUMERICSCOPE 0x00000040
+
+/*%
+ * Scope delimit character
+ */
+#if defined(_NETBSD_SOURCE)
+#define        SCOPE_DELIMITER '%'
+#endif
+#endif /* (_POSIX_C_SOURCE - 0) >= 200112L || ... */
+
+__BEGIN_DECLS
+void           endhostent(void);
+void           endnetent(void);
+void           endprotoent(void);
+void           endservent(void);
+#if (_XOPEN_SOURCE - 0) >= 520 && (_XOPEN_SOURCE - 0) < 600 || \
+    defined(_NETBSD_SOURCE)
+#if 0 /* we do not ship this */
+void           freehostent(struct hostent *);
+#endif
+#endif
+struct hostent *gethostbyaddr(const char *, socklen_t, int);
+struct hostent *gethostbyname(const char *);
+#if defined(_NETBSD_SOURCE)
+struct hostent *gethostbyname2(const char *, int);
+#endif
+struct hostent *gethostent(void);
+struct netent  *getnetbyaddr(uint32_t, int);
+struct netent  *getnetbyname(const char *);
+struct netent  *getnetent(void);
+struct protoent        *getprotobyname(const char *);
+struct protoent        *getprotobynumber(int);
+struct protoent        *getprotoent(void);
+struct servent *getservbyname(const char *, const char *);
+struct servent *getservbyport(int, const char *);
+struct servent *getservent(void);
+#if defined(_NETBSD_SOURCE)
+void           herror(const char *);
+const char     *hstrerror(int);
+#endif
+void           sethostent(int);
+#if defined(_NETBSD_SOURCE)
+/* void                sethostfile(const char *); */
+#endif
+void           setnetent(int);
+void           setprotoent(int);
+void           setservent(int);
+#if (_POSIX_C_SOURCE - 0) >= 200112L || (_XOPEN_SOURCE - 0) >= 520 || \
+    defined(_NETBSD_SOURCE)
+int            getaddrinfo(const char * __restrict, const char * __restrict,
+                                const struct addrinfo * __restrict,
+                                struct addrinfo ** __restrict);
+int            getnameinfo(const struct sockaddr * __restrict, socklen_t,
+                                char * __restrict, socklen_t,
+                                char * __restrict, socklen_t, int);
+struct addrinfo *allocaddrinfo(socklen_t);
+void           freeaddrinfo(struct addrinfo *);
+const char     *gai_strerror(int);
+#endif
+__END_DECLS
+
+#endif /* !_NETDB_H_ */
diff --git a/nbsd_include/netgroup.h b/nbsd_include/netgroup.h
new file mode 100644 (file)
index 0000000..c3dd480
--- /dev/null
@@ -0,0 +1,71 @@
+/*     $NetBSD: netgroup.h,v 1.10 2009/10/21 01:07:45 snj Exp $        */
+
+/*
+ * Copyright (c) 1994 Christos Zoulas
+ * 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 ``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 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 _NETGROUP_H_
+#define        _NETGROUP_H_
+
+#include <sys/cdefs.h>
+
+#define        _PATH_NETGROUP          "/etc/netgroup"
+
+#define        _PATH_NETGROUP_DB       "/var/db/netgroup.db"
+
+#define        _PATH_NETGROUP_MKDB     "/usr/sbin/netgroup_mkdb"
+
+#define        _NG_KEYBYNAME           '1'     /* stored by name */
+#define        _NG_KEYBYUSER           '2'     /* stored by user */
+#define        _NG_KEYBYHOST           '3'     /* stored by host */
+
+#define _NG_ERROR      -1
+#define _NG_NONE        0
+#define _NG_NAME        1
+#define _NG_GROUP       2
+
+struct netgroup {
+       __aconst char *ng_host;         /* host name */
+       __aconst char *ng_user;         /* user name */
+       __aconst char *ng_domain;       /* domain name */
+       struct  netgroup *ng_next;      /* thread */
+};
+
+__BEGIN_DECLS
+void   setnetgrent     (const char *);
+int    getnetgrent     (const char **, const char **, const char **);
+void   endnetgrent     (void);
+int    innetgr         (const char *, const char *, const char *,
+                            const char *);
+#ifdef _NETGROUP_PRIVATE
+char    *_ng_makekey(const char *, const char *, size_t);
+int    _ng_parse(char **, char **, struct netgroup **);
+void   _ng_print(char *, size_t, const struct netgroup *);
+void   _ng_cycle(const char *, const StringList *);
+#endif /* _NETGROUP_PRIVATE */
+
+__END_DECLS
+
+#endif /* !_NETGROUP_H_ */
diff --git a/nbsd_include/nl_types.h b/nbsd_include/nl_types.h
new file mode 100644 (file)
index 0000000..fa36eba
--- /dev/null
@@ -0,0 +1,91 @@
+/*     $NetBSD: nl_types.h,v 1.12 2008/04/28 20:22:54 martin Exp $     */
+
+/*-
+ * Copyright (c) 1996 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _NL_TYPES_H_
+#define _NL_TYPES_H_
+#include <sys/cdefs.h>
+
+#ifdef _NLS_PRIVATE
+/*
+ * MESSAGE CATALOG FILE FORMAT.
+ *
+ * The NetBSD message catalog format is similar to the format used by
+ * Svr4 systems.  The differences are:
+ *   * fixed byte order (big endian)
+ *   * fixed data field sizes
+ *
+ * A message catalog contains four data types: a catalog header, one
+ * or more set headers, one or more message headers, and one or more
+ * text strings.
+ */
+
+#define _NLS_MAGIC     0xff88ff89
+
+struct _nls_cat_hdr {
+       int32_t __magic;
+       int32_t __nsets;
+       int32_t __mem;
+       int32_t __msg_hdr_offset;
+       int32_t __msg_txt_offset;
+} ;
+
+struct _nls_set_hdr {
+       int32_t __setno;        /* set number: 0 < x <= NL_SETMAX */
+       int32_t __nmsgs;        /* number of messages in the set  */
+       int32_t __index;        /* index of first msg_hdr in msg_hdr table */
+} ;
+
+struct _nls_msg_hdr {
+       int32_t __msgno;        /* msg number: 0 < x <= NL_MSGMAX */
+       int32_t __msglen;
+       int32_t __offset;
+} ;
+
+#endif
+
+#define        NL_SETD         1
+#define NL_CAT_LOCALE   1
+
+typedef struct __nl_cat_d {
+       void    *__data;
+       int     __size;
+} *nl_catd;
+
+typedef long   nl_item;
+
+__BEGIN_DECLS
+nl_catd  catopen(const char *, int);
+char    *catgets(nl_catd, int, int, const char *)
+       __attribute__((__format_arg__(4)));
+int     catclose(nl_catd);
+__END_DECLS
+
+#endif /* _NL_TYPES_H_ */
diff --git a/nbsd_include/nlist.h b/nbsd_include/nlist.h
new file mode 100644 (file)
index 0000000..12cc0c0
--- /dev/null
@@ -0,0 +1,94 @@
+/*     $NetBSD: nlist.h,v 1.14 2009/08/21 08:42:02 he Exp $    */
+
+/*-
+ * Copyright (c) 1991, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     @(#)nlist.h     8.2 (Berkeley) 1/21/94
+ */
+
+#ifndef _NLIST_H_
+#define        _NLIST_H_
+
+#include <sys/cdefs.h>
+
+/*
+ * Symbol table entry format.  The #ifdef's are so that programs including
+ * nlist.h can initialize nlist structures statically.
+ */
+struct nlist {
+#ifdef _AOUT_INCLUDE_
+       union {
+               __aconst char *n_name;  /* symbol name (in memory) */
+               long n_strx;            /* file string table offset (on disk) */
+       } n_un;
+# define N_NAME(nlp)   ((nlp)->n_un.n_name)
+#else
+       const char *n_name;             /* symbol name (in memory) */
+# define N_NAME(nlp)   ((nlp)->n_name)
+#endif
+
+#define        N_UNDF  0x00            /* undefined */
+#define        N_ABS   0x02            /* absolute address */
+#define        N_TEXT  0x04            /* text segment */
+#define        N_DATA  0x06            /* data segment */
+#define        N_BSS   0x08            /* bss segment */
+#define        N_INDR  0x0a            /* alias definition */
+#define        N_SIZE  0x0c            /* pseudo type, defines a symbol's size */
+#define        N_COMM  0x12            /* common reference */
+#define N_SETA 0x14            /* absolute set element symbol */
+#define N_SETT 0x16            /* text set element symbol */
+#define N_SETD 0x18            /* data set element symbol */
+#define N_SETB 0x1a            /* bss set element symbol */
+#define N_SETV 0x1c            /* set vector symbol */
+#define        N_FN    0x1e            /* file name (N_EXT on) */
+#define        N_WARN  0x1e            /* warning message (N_EXT off) */
+
+#define        N_EXT   0x01            /* external (global) bit, OR'ed in */
+#define        N_TYPE  0x1e            /* mask for all the type bits */
+       unsigned char n_type;   /* type defines */
+
+       char n_other;           /* spare */
+#define        n_hash  n_desc          /* used internally by ld(1); XXX */
+       short n_desc;           /* used by stab entries */
+       unsigned long n_value;  /* address/value of the symbol */
+};
+
+#define        N_FORMAT        "%08x"  /* namelist value format; XXX */
+#define        N_STAB          0x0e0   /* mask for debugger symbols -- stab(5) */
+
+__BEGIN_DECLS
+int nlist(const char *, struct nlist *);
+int __fdnlist(int, struct nlist *);            /* XXX for libkvm */
+__END_DECLS
+
+#endif /* !_NLIST_H_ */
diff --git a/nbsd_include/nsswitch.h b/nbsd_include/nsswitch.h
new file mode 100644 (file)
index 0000000..d429b93
--- /dev/null
@@ -0,0 +1,237 @@
+/*     $NetBSD: nsswitch.h,v 1.20 2008/04/28 20:22:54 martin Exp $     */
+
+/*-
+ * Copyright (c) 1997, 1998, 1999, 2004 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Luke Mewburn.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _NSSWITCH_H
+#define _NSSWITCH_H    1
+
+/*
+ * Don't use va_list in prototypes.   va_list is typedef'd in two places
+ * (<machine/varargs.h> and <machine/stdarg.h>), so if we include one of
+ * them here we may collide with the utility's includes.  It's unreasonable
+ * for utilities to have to include one of them to include nsswitch.h, so
+ * we get _BSD_VA_LIST_ from <machine/ansi.h> and use it.
+ */
+#include <machine/ansi.h>
+#include <sys/types.h>
+
+#define        NSS_MODULE_INTERFACE_VERSION    0
+
+#ifndef _PATH_NS_CONF
+#define _PATH_NS_CONF  "/etc/nsswitch.conf"
+#endif
+
+#define        NS_CONTINUE     0
+#define        NS_RETURN       1
+
+/*
+ * Layout of:
+ *     uint32_t ns_src.flags
+ */ 
+       /* nsswitch.conf status codes and nsdispatch(3) return values */
+#define        NS_SUCCESS      (1<<0)          /* entry was found */
+#define        NS_UNAVAIL      (1<<1)          /* source not responding, or corrupt */
+#define        NS_NOTFOUND     (1<<2)          /* source responded 'no such entry' */
+#define        NS_TRYAGAIN     (1<<3)          /* source busy, may respond to retrys */
+#define        NS_STATUSMASK   0x000000ff      /* bitmask to get the status flags */
+
+       /* internal nsdispatch(3) flags; not settable in nsswitch.conf(5)  */
+#define        NS_FORCEALL     (1<<8)          /* force all methods to be invoked; */
+
+/*
+ * Currently implemented sources.
+ */
+#define NSSRC_FILES    "files"         /* local files */
+#define        NSSRC_DNS       "dns"           /* DNS; IN for hosts, HS for others */
+#define        NSSRC_NIS       "nis"           /* YP/NIS */
+#define        NSSRC_COMPAT    "compat"        /* passwd,group in YP compat mode */
+
+/*
+ * Currently implemented databases.
+ */
+#define NSDB_HOSTS             "hosts"
+#define NSDB_GROUP             "group"
+#define NSDB_GROUP_COMPAT      "group_compat"
+#define NSDB_NETGROUP          "netgroup"
+#define NSDB_NETWORKS          "networks"
+#define NSDB_PASSWD            "passwd"
+#define NSDB_PASSWD_COMPAT     "passwd_compat"
+#define NSDB_SHELLS            "shells"
+
+/*
+ * Suggested databases to implement.
+ */
+#define NSDB_ALIASES           "aliases"
+#define NSDB_AUTH              "auth"
+#define NSDB_AUTOMOUNT         "automount"
+#define NSDB_BOOTPARAMS                "bootparams"
+#define NSDB_ETHERS            "ethers"
+#define NSDB_EXPORTS           "exports"
+#define NSDB_NETMASKS          "netmasks"
+#define NSDB_PHONES            "phones"
+#define NSDB_PRINTCAP          "printcap"
+#define NSDB_PROTOCOLS         "protocols"
+#define NSDB_REMOTE            "remote"
+#define NSDB_RPC               "rpc"
+#define NSDB_SENDMAILVARS      "sendmailvars"
+#define NSDB_SERVICES          "services"
+#define NSDB_TERMCAP           "termcap"
+#define NSDB_TTYS              "ttys"
+
+/*
+ * ns_dtab `callback' function signature.
+ */
+typedef        int (*nss_method)(void *, void *, _BSD_VA_LIST_);
+
+/*
+ * ns_dtab - `nsswitch dispatch table'
+ * Contains an entry for each source and the appropriate function to call.
+ */
+typedef struct {
+       const char       *src;
+       nss_method       callback;
+       void             *cb_data;
+} ns_dtab;
+
+/*
+ * Macros to help build an ns_dtab[]
+ */
+#define NS_FILES_CB(F,C)       { NSSRC_FILES,  F,      __UNCONST(C) },
+#define NS_COMPAT_CB(F,C)      { NSSRC_COMPAT, F,      __UNCONST(C) },
+#ifdef HESIOD
+#   define NS_DNS_CB(F,C)      { NSSRC_DNS,    F,      __UNCONST(C) },
+#else
+#   define NS_DNS_CB(F,C)
+#endif
+
+#ifdef YP
+#   define NS_NIS_CB(F,C)      { NSSRC_NIS,    F,      __UNCONST(C) },
+#else
+#   define NS_NIS_CB(F,C)
+#endif
+#define        NS_NULL_CB              { .src = NULL },
+
+/*
+ * ns_src - `nsswitch source'
+ * Used by the nsparser routines to store a mapping between a source
+ * and its dispatch control flags for a given database.
+ */
+typedef struct {
+       const char      *name;
+       uint32_t         flags;
+} ns_src;
+
+
+/*
+ * Default sourcelists (if nsswitch.conf is missing, corrupt,
+ * or the requested database doesn't have an entry)
+ */
+extern const ns_src __nsdefaultsrc[];
+extern const ns_src __nsdefaultcompat[];
+extern const ns_src __nsdefaultcompat_forceall[];
+extern const ns_src __nsdefaultfiles[];
+extern const ns_src __nsdefaultfiles_forceall[];
+extern const ns_src __nsdefaultnis[];
+extern const ns_src __nsdefaultnis_forceall[];
+
+
+/*
+ * ns_mtab - `nsswitch method table'
+ * An nsswitch module provides a mapping from (database name, method name)
+ * tuples to the nss_method and associated callback data.  Effectively,
+ * ns_dtab, but used for dynamically loaded modules.
+ */
+typedef struct {
+       const char      *database;
+       const char      *name;
+       nss_method       method;
+       void            *mdata;
+} ns_mtab;
+
+/*
+ * nss_module_register_fn - module registration function
+ *     called at module load
+ * nss_module_unregister_fn - module un-registration function
+ *     called at module unload
+ */
+typedef        void (*nss_module_unregister_fn)(ns_mtab *, u_int);
+typedef        ns_mtab *(*nss_module_register_fn)(const char *, u_int *,
+                                          nss_module_unregister_fn *);
+
+#ifdef _NS_PRIVATE
+
+/*
+ * Private data structures for back-end nsswitch implementation.
+ */
+
+/*
+ * ns_dbt - `nsswitch database thang'
+ * For each database in /etc/nsswitch.conf there is a ns_dbt, with its
+ * name and a list of ns_src's containing the source information.
+ */
+typedef struct {
+       const char      *name;          /* name of database */
+       ns_src          *srclist;       /* list of sources */
+       u_int            srclistsize;   /* size of srclist */
+} ns_dbt;
+
+/*
+ * ns_mod - `nsswitch module'
+ */
+typedef struct {
+       const char      *name;          /* module name */
+       void            *handle;        /* handle from dlopen() */
+       ns_mtab         *mtab;          /* method table */
+       u_int            mtabsize;      /* size of mtab */
+                                       /* called to unload module */
+       nss_module_unregister_fn unregister;
+} ns_mod;
+
+#endif /* _NS_PRIVATE */
+
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+int    nsdispatch(void *, const ns_dtab [], const char *,
+                       const char *, const ns_src [], ...);
+
+#ifdef _NS_PRIVATE
+int             _nsdbtaddsrc(ns_dbt *, const ns_src *);
+void            _nsdbtdump(const ns_dbt *);
+int             _nsdbtput(const ns_dbt *);
+void            _nsyyerror(const char *);
+int             _nsyylex(void);
+#endif /* _NS_PRIVATE */
+
+__END_DECLS
+
+#endif /* !_NSSWITCH_H */
diff --git a/nbsd_include/paths.h b/nbsd_include/paths.h
new file mode 100644 (file)
index 0000000..00e4f6b
--- /dev/null
@@ -0,0 +1,128 @@
+/*     $NetBSD: paths.h,v 1.39 2010/12/29 15:53:57 pooka Exp $ */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ *
+ *     @(#)paths.h     8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _PATHS_H_
+#define        _PATHS_H_
+
+/*
+ * Default user search path.
+ * Set by login(1), rshd(8), rexecd(8)
+ * Used by execvp(3) absent PATH from the environ(7)
+ */
+#ifdef RESCUEDIR
+#define        _PATH_DEFPATH   RESCUEDIR ":/usr/bin:/bin:/usr/pkg/bin:/usr/local/bin"
+#else
+#define        _PATH_DEFPATH   "/usr/bin:/bin:/usr/pkg/bin:/usr/local/bin"
+#endif
+
+/*
+ * All standard utilities path.
+ * Set by init(8) for system programs & scripts (e.g. /etc/rc)
+ * Used by ttyaction(3), whereis(1)
+ */
+#define        _PATH_STDPATH \
+       "/usr/bin:/bin:/usr/sbin:/sbin:/usr/pkg/bin:/usr/pkg/sbin:/usr/local/bin:/usr/local/sbin"
+
+#define        _PATH_AUDIO     "/dev/audio"
+#define        _PATH_AUDIO0    "/dev/audio0"
+#define        _PATH_AUDIOCTL  "/dev/audioctl"
+#define        _PATH_AUDIOCTL0 "/dev/audioctl0"
+#define        _PATH_BPF       "/dev/bpf"
+#define        _PATH_CLOCKCTL  "/dev/clockctl"
+#define        _PATH_CONSOLE   "/dev/console"
+#define        _PATH_CONSTTY   "/dev/constty"
+#define        _PATH_CSMAPPER  "/usr/share/i18n/csmapper"
+#define        _PATH_DEFTAPE   "/dev/nrst0"
+#define        _PATH_DEVDB     "/var/run/dev.db"
+#define        _PATH_DEVNULL   "/dev/null"
+#define        _PATH_DRUM      "/dev/drum"
+#define        _PATH_ESDB      "/usr/share/i18n/esdb"
+#define        _PATH_FTPUSERS  "/etc/ftpusers"
+#define        _PATH_GETTYTAB  "/etc/gettytab"
+#define        _PATH_I18NMODULE "/usr/lib/i18n"
+#define        _PATH_ICONV     "/usr/share/i18n/iconv"
+#define        _PATH_KMEM      "/dev/kmem"
+#define        _PATH_KSYMS     "/dev/ksyms"
+#define        _PATH_KVMDB     "/var/db/kvm.db"
+#define        _PATH_LOCALE    "/usr/share/locale"
+#define        _PATH_MAILDIR   "/var/mail"
+#define        _PATH_MAN       "/usr/share/man"
+#define        _PATH_MEM       "/dev/mem"
+#define        _PATH_MIXER     "/dev/mixer"
+#define        _PATH_MIXER0    "/dev/mixer0"
+#define        _PATH_NOLOGIN   "/etc/nologin"
+#define _PATH_POWER    "/dev/power"
+#define        _PATH_PRINTCAP  "/etc/printcap"
+#define        _PATH_PUD       "/dev/pud"
+#define        _PATH_PUFFS     "/dev/puffs"
+#define        _PATH_RANDOM    "/dev/random"
+#define        _PATH_SENDMAIL  "/usr/sbin/sendmail"
+#define        _PATH_SHELLS    "/etc/shells"
+#define        _PATH_SKEYKEYS  "/etc/skeykeys"
+#define        _PATH_SOUND     "/dev/sound"
+#define        _PATH_SOUND0    "/dev/sound0"
+#define        _PATH_SYSMON    "/dev/sysmon"
+#define        _PATH_TTY       "/dev/tty"
+#define        _PATH_UNIX      "/netbsd"
+#define        _PATH_URANDOM   "/dev/urandom"
+#define        _PATH_VIDEO     "/dev/video"
+#define        _PATH_VIDEO0    "/dev/video0"
+
+/*
+ * Provide trailing slash, since mostly used for building pathnames.
+ * See the __CONCAT() macro from <sys/cdefs.h> for cpp examples.
+ */
+#define        _PATH_DEV       "/dev/"
+#define        _PATH_DEV_PTS   "/dev/pts/"
+#define        _PATH_EMUL_AOUT "/emul/aout/"
+#define        _PATH_TMP       "/tmp/"
+#define        _PATH_VARDB     "/var/db/"
+#define        _PATH_VARRUN    "/var/run/"
+#define        _PATH_VARTMP    "/var/tmp/"
+
+/*
+ * Paths that may change if RESCUEDIR is defined.
+ * Used by tools in /rescue.
+ */
+#ifdef RESCUEDIR
+#define        _PATH_BSHELL    RESCUEDIR "/sh"
+#define        _PATH_CSHELL    RESCUEDIR "/csh"
+#define        _PATH_VI        RESCUEDIR "/vi"
+#else
+#define        _PATH_BSHELL    "/bin/sh"
+#define        _PATH_CSHELL    "/bin/csh"
+#define        _PATH_VI        "/usr/bin/vi"
+#endif
+
+#endif /* !_PATHS_H_ */
+
diff --git a/nbsd_include/protocols/dumprestore.h b/nbsd_include/protocols/dumprestore.h
new file mode 100644 (file)
index 0000000..5169057
--- /dev/null
@@ -0,0 +1,159 @@
+/*     $NetBSD: dumprestore.h,v 1.16 2009/01/11 03:04:12 christos Exp $        */
+
+/*
+ * Copyright (c) 1980, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     @(#)dumprestore.h       8.2 (Berkeley) 1/21/94
+ */
+
+#ifndef _PROTOCOLS_DUMPRESTORE_H_
+#define _PROTOCOLS_DUMPRESTORE_H_
+
+/*
+ * TP_BSIZE is the size of file blocks on the dump tapes.
+ * Note that TP_BSIZE must be a multiple of DEV_BSIZE.
+ *
+ * NTREC is the number of TP_BSIZE blocks that are written
+ * in each tape record. HIGHDENSITYTREC is the number of
+ * TP_BSIZE blocks that are written in each tape record on
+ * 6250 BPI or higher density tapes.
+ *
+ * TP_NINDIR is the number of indirect pointers in a TS_INODE
+ * or TS_ADDR record. Note that it must be a power of two.
+ */
+#define TP_BSIZE       1024
+#define NTREC          10
+#define HIGHDENSITYTREC        32
+#define TP_NINDIR      (TP_BSIZE/2)
+#define LBLSIZE                16
+#define NAMELEN                64
+
+#define OFS_MAGIC      (int)60011
+#define NFS_MAGIC      (int)60012
+#ifndef FS_UFS2_MAGIC
+#define FS_UFS2_MAGIC   (int)0x19540119
+#endif
+#define CHECKSUM       (int)84446
+
+union u_spcl {
+       char dummy[TP_BSIZE];
+       struct  s_spcl {
+               int32_t c_type;             /* record type (see below) */
+               int32_t c_old_date;         /* date of this dump */
+               int32_t c_old_ddate;        /* date of previous dump */
+               int32_t c_volume;           /* dump volume number */
+               int32_t c_old_tapea;        /* logical block of this record */
+               uint32_t c_inumber;         /* number of inode */
+               int32_t c_magic;            /* magic number (see above) */
+               int32_t c_checksum;         /* record checksum */
+               union {
+                       struct ufs1_dinode __uc_dinode;
+                       struct {
+                               uint16_t __uc_mode;
+                               int16_t __uc_spare1[3];
+                               uint64_t __uc_size;
+                               int32_t __uc_old_atime;
+                               int32_t __uc_atimensec;
+                               int32_t __uc_old_mtime;
+                               int32_t __uc_mtimensec;
+                               int32_t __uc_spare2[2];
+                               int32_t __uc_rdev;
+                               int32_t __uc_birthtimensec;
+                               int64_t __uc_birthtime;
+                               int64_t __uc_atime;
+                               int64_t __uc_mtime;
+                               int32_t __uc_spare4[7];
+                               uint32_t __uc_file_flags;
+                               int32_t __uc_spare5[2];
+                               uint32_t __uc_uid;
+                               uint32_t __uc_gid;
+                               int32_t __uc_spare6[2];
+                       } __uc_ino;
+               } __c_ino;
+               int32_t c_count;            /* number of valid c_addr entries */
+               char    c_addr[TP_NINDIR];  /* 1 => data; 0 => hole in inode */
+               char    c_label[LBLSIZE];   /* dump label */
+               int32_t c_level;            /* level of this dump */
+               char    c_filesys[NAMELEN]; /* name of dumpped file system */
+               char    c_dev[NAMELEN];     /* name of dumpped device */
+               char    c_host[NAMELEN];    /* name of dumpped host */
+               int32_t c_flags;            /* additional information */
+               int32_t c_old_firstrec;     /* first record on volume */
+               int64_t c_date;             /* date of this dump */
+               int64_t c_ddate;            /* date of previous dump */
+               int64_t c_tapea;            /* logical block of this record */
+               int64_t c_firstrec;         /* first record on volume */
+               int32_t c_spare[24];        /* reserved for future uses */
+       } s_spcl;
+} u_spcl;
+#define spcl u_spcl.s_spcl
+
+#define c_dinode       __c_ino.__uc_dinode
+#define c_mode         __c_ino.__uc_ino.__uc_mode
+#define c_spare1       __c_ino.__uc_ino.__uc_spare1
+#define c_size         __c_ino.__uc_ino.__uc_size
+#define c_old_atime    __c_ino.__uc_ino.__uc_old_atime
+#define c_atime                __c_ino.__uc_ino.__uc_atime
+#define c_atimensec    __c_ino.__uc_ino.__uc_atimensec
+#define c_mtime                __c_ino.__uc_ino.__uc_mtime
+#define c_mtimensec    __c_ino.__uc_ino.__uc_mtimensec
+#define c_birthtime    __c_ino.__uc_ino.__uc_birthtime
+#define c_birthtimensec        __c_ino.__uc_ino.__uc_birthtimensec
+#define c_old_mtime    __c_ino.__uc_ino.__uc_old_mtime
+#define c_rdev         __c_ino.__uc_ino.__uc_rdev
+#define c_file_flags   __c_ino.__uc_ino.__uc_file_flags
+#define c_uid          __c_ino.__uc_ino.__uc_uid
+#define c_gid          __c_ino.__uc_ino.__uc_gid
+
+/*
+ * special record types
+ */
+#define TS_TAPE        1       /* dump tape header */
+#define TS_INODE       2       /* beginning of file record */
+#define TS_ADDR        4       /* continuation of file record */
+#define TS_BITS        3       /* map of inodes on tape */
+#define TS_CLRI        6       /* map of inodes deleted since last dump */
+#define TS_END         5       /* end of volume marker */
+
+/*
+ * flag values
+ */
+#define DR_NEWHEADER   0x0001  /* new format tape header */
+#define DR_NEWINODEFMT 0x0002  /* new format inodes on tape */
+#define DR_EXTATTRIBUTES 0x8000        /* linux: extended attributes */
+
+#define        DUMPOUTFMT      "%-16s %c %s"           /* for printf */
+                                               /* name, level, ctime(date) */
+#define        DUMPINFMT       "%16s %c %[^\n]\n"      /* inverse for scanf */
+
+#endif /* !_PROTOCOLS_DUMPRESTORE_H_ */
diff --git a/nbsd_include/protocols/routed.h b/nbsd_include/protocols/routed.h
new file mode 100644 (file)
index 0000000..62a08c0
--- /dev/null
@@ -0,0 +1,175 @@
+/*     $NetBSD: routed.h,v 1.14 2005/12/26 19:01:47 perry Exp $        */
+
+/*-
+ * Copyright (c) 1983, 1989, 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.
+ * 3. 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.
+ *
+ *     @(#)routed.h    8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _PROTOCOLS_ROUTED_H_
+#define        _PROTOCOLS_ROUTED_H_
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Routing Information Protocol
+ *
+ * Derived from Xerox NS Routing Information Protocol
+ * by changing 32-bit net numbers to sockaddr's and
+ * padding stuff to 32-bit boundaries.
+ */
+
+#define RIP_VERSION_0  0
+#define        RIP_VERSION_1   1
+#define        RIP_VERSION_2   2
+
+#define        RIPv1           RIP_VERSION_1
+#define        RIPv2           RIP_VERSION_2
+#ifndef RIPVERSION
+#define        RIPVERSION      RIPv1
+#endif
+
+#define RIP_PORT       520
+
+#if RIPVERSION == 1
+/* We include the V2 fields to get the right size */
+struct netinfo {
+       uint16_t   rip_family;
+       uint16_t   rip_tag;
+       uint32_t   rip_dst;             /* destination net/host */
+       uint32_t   rip_dst_mask;        /* destination mask (V2 only) */
+       uint32_t   rip_router;          /* next host (V2 only) */
+       uint32_t   rip_metric;          /* cost of route */
+};
+#else
+struct netinfo {
+       uint16_t   n_family;
+#define            RIP_AF_INET     htons(AF_INET)
+#define            RIP_AF_UNSPEC   0
+#define            RIP_AF_AUTH     0xffff
+       uint16_t   n_tag;               /* optional in RIPv2 */
+       uint32_t   n_dst;               /* destination net or host */
+#define            RIP_DEFAULT     0
+       uint32_t   n_mask;              /* netmask in RIPv2 */
+       uint32_t   n_nhop;              /* optional next hop in RIPv2 */
+       uint32_t   n_metric;            /* cost of route */
+};
+#endif
+
+/* RIPv2 authentication */
+struct netauth {
+       uint16_t   a_family;            /* always RIP_AF_AUTH */
+       uint16_t   a_type;
+#define            RIP_AUTH_NONE   0
+#define            RIP_AUTH_PW     htons(2)    /* password type */
+#define            RIP_AUTH_MD5    htons(3)    /* Keyed MD5 */
+       union {
+#define            RIP_AUTH_PW_LEN 16
+           uint8_t    au_pw[RIP_AUTH_PW_LEN];
+           struct a_md5 {
+               int16_t md5_pkt_len;    /* RIP-II packet length */
+               int8_t  md5_keyid;      /* key ID and auth data len */
+               int8_t  md5_auth_len;   /* 16 */
+               uint32_t md5_seqno;     /* sequence number */
+               uint32_t rsvd[2];       /* must be 0 */
+#define            RIP_AUTH_MD5_KEY_LEN   RIP_AUTH_PW_LEN
+#define            RIP_AUTH_MD5_HASH_XTRA (sizeof(struct netauth)-sizeof(struct a_md5))
+#define            RIP_AUTH_MD5_HASH_LEN  (RIP_AUTH_MD5_KEY_LEN+RIP_AUTH_MD5_HASH_XTRA)
+           } a_md5;
+       } au;
+};
+
+struct rip {
+       uint8_t    rip_cmd;             /* request/response */
+       uint8_t    rip_vers;            /* protocol version # */
+       uint16_t   rip_res1;            /* pad to 32-bit boundary */
+       union {                         /* variable length... */
+           struct netinfo ru_nets[1];
+           int8_t    ru_tracefile[1];
+           struct netauth ru_auth[1];
+       } ripun;
+#define        rip_nets        ripun.ru_nets
+#define rip_auths      ripun.ru_auth
+#define        rip_tracefile   ripun.ru_tracefile
+};
+
+/* Packet types.
+ */
+#define        RIPCMD_REQUEST          1       /* want info */
+#define        RIPCMD_RESPONSE         2       /* responding to request */
+#define        RIPCMD_TRACEON          3       /* turn tracing on */
+#define        RIPCMD_TRACEOFF         4       /* turn it off */
+
+/* Gated extended RIP to include a "poll" command instead of using
+ * RIPCMD_REQUEST with (RIP_AF_UNSPEC, RIP_DEFAULT).  RFC 1058 says
+ * command 5 is used by Sun Microsystems for its own purposes.
+ */
+#define RIPCMD_POLL            5
+
+#define        RIPCMD_MAX              6
+
+#ifdef RIPCMDS
+const char *ripcmds[RIPCMD_MAX] = {
+       "#0", "REQUEST", "RESPONSE", "TRACEON", "TRACEOFF"
+};
+#endif
+
+#define        HOPCNT_INFINITY         16
+#define        MAXPACKETSIZE           512     /* max broadcast size */
+#define NETS_LEN ((MAXPACKETSIZE-sizeof(struct rip))   \
+                     / sizeof(struct netinfo) +1)
+
+#define INADDR_RIP_GROUP (uint32_t)0xe0000009  /* 224.0.0.9 */
+
+
+/* Timer values used in managing the routing table.
+ *
+ * Complete tables are broadcast every SUPPLY_INTERVAL seconds.
+ * If changes occur between updates, dynamic updates containing only changes
+ * may be sent.  When these are sent, a timer is set for a random value
+ * between MIN_WAITTIME and MAX_WAITTIME, and no additional dynamic updates
+ * are sent until the timer expires.
+ *
+ * Every update of a routing entry forces an entry's timer to be reset.
+ * After EXPIRE_TIME without updates, the entry is marked invalid,
+ * but held onto until GARBAGE_TIME so that others may see it, to
+ * "poison" the bad route.
+ */
+#define        SUPPLY_INTERVAL         30      /* time to supply tables */
+#define        MIN_WAITTIME            2       /* min sec until next flash updates */
+#define        MAX_WAITTIME            5       /* max sec until flash update */
+
+#define STALE_TIME             90      /* switch to a new gateway */
+#define        EXPIRE_TIME             180     /* time to mark entry invalid */
+#define        GARBAGE_TIME            240     /* time to garbage collect */
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !_PROTOCOLS_ROUTED_H_ */
diff --git a/nbsd_include/protocols/rwhod.h b/nbsd_include/protocols/rwhod.h
new file mode 100644 (file)
index 0000000..2f35150
--- /dev/null
@@ -0,0 +1,66 @@
+/*     $NetBSD: rwhod.h,v 1.7 2003/08/07 09:44:13 agc Exp $    */
+
+/*
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)rwhod.h     8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _PROTOCOLS_RWHOD_H_
+#define        _PROTOCOLS_RWHOD_H_
+
+/*
+ * rwho protocol packet format.
+ */
+struct outmp {
+       char    out_line[8];            /* tty name */
+       char    out_name[8];            /* user id */
+       int32_t out_time;               /* time on */
+};
+
+struct whod {
+       char    wd_vers;                /* protocol version # */
+       char    wd_type;                /* packet type, see below */
+       char    wd_pad[2];
+       int32_t wd_sendtime;            /* time stamp by sender */
+       int32_t wd_recvtime;            /* time stamp applied by receiver */
+       char    wd_hostname[32];        /* hosts's name */
+       int32_t wd_loadav[3];           /* load average as in uptime */
+       int32_t wd_boottime;            /* time system booted */
+       struct  whoent {
+               struct  outmp we_utmp;  /* active tty info */
+               int32_t we_idle;        /* tty idle time */
+       } wd_we[1024 / sizeof (struct whoent)];
+};
+
+#define        WHODVERSION     1
+#define        WHODTYPE_STATUS 1               /* host status */
+
+#define        _PATH_RWHODIR   "/var/rwho"
+
+#endif /* !_PROTOCOLS_RWHOD_H_ */
diff --git a/nbsd_include/protocols/talkd.h b/nbsd_include/protocols/talkd.h
new file mode 100644 (file)
index 0000000..c6cf898
--- /dev/null
@@ -0,0 +1,120 @@
+/*     $NetBSD: talkd.h,v 1.10 2005/12/26 19:01:47 perry Exp $ */
+
+/*
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)talkd.h     8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _PROTOCOLS_TALKD_H_
+#define        _PROTOCOLS_TALKD_H_
+
+/*
+ * This describes the protocol used by the talk server and clients.
+ *
+ * The talk server acts a repository of invitations, responding to
+ * requests by clients wishing to rendezvous for the purpose of
+ * holding a conversation.  In normal operation, a client, the caller,
+ * initiates a rendezvous by sending a CTL_MSG to the server of
+ * type LOOK_UP.  This causes the server to search its invitation
+ * tables to check if an invitation currently exists for the caller
+ * (to speak to the callee specified in the message).  If the lookup
+ * fails, the caller then sends an ANNOUNCE message causing the server
+ * to broadcast an announcement on the callee's login ports requesting
+ * contact.  When the callee responds, the local server uses the
+ * recorded invitation to respond with the appropriate rendezvous
+ * address and the caller and callee client programs establish a
+ * stream connection through which the conversation takes place.
+ */
+
+/*
+ * 4.3 compat sockaddr
+ */
+struct talkd_sockaddr {
+       uint16_t        sa_family;      /* address family */
+       char            sa_data[14];    /* up to 14 bytes of direct address */
+};
+
+/*
+ * Client->server request message format.
+ */
+typedef struct {
+       u_char    vers;                 /* protocol version */
+       u_char    type;                 /* request type, see below */
+       u_char    answer;               /* not used */
+       u_char    pad;
+       uint32_t id_num;                /* message id */
+       struct    talkd_sockaddr addr;  /* old (4.3) style */
+       struct    talkd_sockaddr ctl_addr;/* old (4.3) style */
+       int32_t   pid;                  /* caller's process id */
+#define        NAME_SIZE       12
+       char      l_name[NAME_SIZE];    /* caller's name */
+       char      r_name[NAME_SIZE];    /* callee's name */
+#define        TTY_SIZE        16
+       char      r_tty[TTY_SIZE];      /* callee's tty name */
+} CTL_MSG;
+
+/*
+ * Server->client response message format.
+ */
+typedef struct {
+       u_char    vers;         /* protocol version */
+       u_char    type;         /* type of request message, see below */
+       u_char    answer;       /* respose to request message, see below */
+       u_char    pad;
+       uint32_t id_num;        /* message id */
+       struct    talkd_sockaddr addr; /* address for establishing conversation */
+} CTL_RESPONSE;
+
+#define        TALK_VERSION    1               /* protocol version */
+
+/* message type values */
+#define LEAVE_INVITE   0       /* leave invitation with server */
+#define LOOK_UP                1       /* check for invitation by callee */
+#define DELETE         2       /* delete invitation by caller */
+#define ANNOUNCE       3       /* announce invitation by caller */
+
+/* answer values */
+#define SUCCESS                0       /* operation completed properly */
+#define NOT_HERE       1       /* callee not logged in */
+#define FAILED         2       /* operation failed for unexplained reason */
+#define MACHINE_UNKNOWN        3       /* caller's machine name unknown */
+#define PERMISSION_DENIED 4    /* callee's tty doesn't permit announce */
+#define UNKNOWN_REQUEST        5       /* request has invalid type value */
+#define        BADVERSION      6       /* request has invalid protocol version */
+#define        BADADDR         7       /* request has invalid addr value */
+#define        BADCTLADDR      8       /* request has invalid ctl_addr value */
+
+/*
+ * Operational parameters.
+ */
+#define MAX_LIFE       60      /* max time daemon saves invitations */
+/* RING_WAIT should be 10's of seconds less than MAX_LIFE */
+#define RING_WAIT      30      /* time to wait before resending invitation */
+
+#endif /* !_PROTOCOLS_TALKD_H_ */
diff --git a/nbsd_include/protocols/timed.h b/nbsd_include/protocols/timed.h
new file mode 100644 (file)
index 0000000..311fb3a
--- /dev/null
@@ -0,0 +1,100 @@
+/*     $NetBSD: timed.h,v 1.11 2008/02/16 07:30:15 matt Exp $  */
+
+/*
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)timed.h     8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef        _PROTOCOLS_TIMED_H_
+#define        _PROTOCOLS_TIMED_H_
+
+/*
+ * Time Synchronization Protocol
+ */
+
+#define        TSPVERSION      1
+#define ANYADDR        NULL
+
+struct tsp {
+       uint8_t tsp_type;
+       uint8_t tsp_vers;
+       uint16_t tsp_seq;
+       union {
+               struct {
+                       int32_t tv_sec;
+                       int32_t tv_usec;
+               } tspu_time;
+               char tspu_hopcnt;
+       } tsp_u;
+       char tsp_name[MAXHOSTNAMELEN];
+};
+
+#define        tsp_time        tsp_u.tspu_time
+#define        tsp_hopcnt      tsp_u.tspu_hopcnt
+/*
+ * Command types.
+ */
+#define        TSP_ANY                 0       /* match any types */
+#define        TSP_ADJTIME             1       /* send adjtime */
+#define        TSP_ACK                 2       /* generic acknowledgement */
+#define        TSP_MASTERREQ           3       /* ask for master's name */ 
+#define        TSP_MASTERACK           4       /* acknowledge master request */
+#define        TSP_SETTIME             5       /* send network time */
+#define        TSP_MASTERUP            6       /* inform slaves that master is up */
+#define        TSP_SLAVEUP             7       /* slave is up but not polled */
+#define        TSP_ELECTION            8       /* advance candidature for master */
+#define        TSP_ACCEPT              9       /* support candidature of master */
+#define        TSP_REFUSE              10      /* reject candidature of master */
+#define        TSP_CONFLICT            11      /* two or more masters present */
+#define        TSP_RESOLVE             12      /* masters' conflict resolution */
+#define        TSP_QUIT                13      /* reject candidature if master is up */
+#define        TSP_DATE                14      /* reset the time (date command) */
+#define        TSP_DATEREQ             15      /* remote request to reset the time */
+#define        TSP_DATEACK             16      /* acknowledge time setting  */
+#define        TSP_TRACEON             17      /* turn tracing on */
+#define        TSP_TRACEOFF            18      /* turn tracing off */
+#define        TSP_MSITE               19      /* find out master's site */
+#define        TSP_MSITEREQ            20      /* remote master's site request */
+#define        TSP_TEST                21      /* for testing election algo */
+#define        TSP_SETDATE             22      /* New from date command */
+#define        TSP_SETDATEREQ          23      /* New remote for above */
+#define        TSP_LOOP                24      /* loop detection packet */
+
+#define        TSPTYPENUMBER           25
+
+#ifdef TSPTYPES
+const char * const tsptype[TSPTYPENUMBER] =
+  { "ANY", "ADJTIME", "ACK", "MASTERREQ", "MASTERACK", "SETTIME", "MASTERUP", 
+  "SLAVEUP", "ELECTION", "ACCEPT", "REFUSE", "CONFLICT", "RESOLVE", "QUIT", 
+  "DATE", "DATEREQ", "DATEACK", "TRACEON", "TRACEOFF", "MSITE", "MSITEREQ",
+  "TEST", "SETDATE", "SETDATEREQ", "LOOP" };
+#endif
+
+#endif /* !_PROTOCOLS_TIMED_H_ */
diff --git a/nbsd_include/pwd.h b/nbsd_include/pwd.h
new file mode 100644 (file)
index 0000000..4a471f0
--- /dev/null
@@ -0,0 +1,159 @@
+/*     $NetBSD: pwd.h,v 1.42 2009/01/11 03:04:12 christos Exp $        */
+
+/*-
+ * Copyright (c) 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     @(#)pwd.h       8.2 (Berkeley) 1/21/94
+ */
+
+/*-
+ * Portions Copyright(C) 1995, Jason Downs.  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(S) ``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(S) 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 _PWD_H_
+#define        _PWD_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <sys/types.h>
+
+#if defined(_NETBSD_SOURCE) || defined(HAVE_NBTOOL_CONFIG_H)
+#define        _PATH_PASSWD            "/etc/passwd"
+#define        _PATH_MASTERPASSWD      "/etc/master.passwd"
+#define        _PATH_MASTERPASSWD_LOCK "/etc/ptmp"
+
+#define        _PATH_PASSWD_CONF       "/etc/passwd.conf"
+#define        _PATH_PASSWDCONF        _PATH_PASSWD_CONF       /* XXX: compat */
+#define        _PATH_USERMGMT_CONF     "/etc/usermgmt.conf"
+
+#define        _PATH_MP_DB             "/etc/pwd.db"
+#define        _PATH_SMP_DB            "/etc/spwd.db"
+
+#define        _PATH_PWD_MKDB          "/usr/sbin/pwd_mkdb"
+
+#define        _PW_KEYBYNAME           '1'     /* stored by name */
+#define        _PW_KEYBYNUM            '2'     /* stored by entry in the "file" */
+#define        _PW_KEYBYUID            '3'     /* stored by uid */
+
+#define        _PASSWORD_EFMT1         '_'     /* extended DES encryption format */
+#define        _PASSWORD_NONDES        '$'     /* non-DES encryption formats */
+
+#define        _PASSWORD_LEN           128     /* max length, not counting NUL */
+
+#define _PASSWORD_NOUID                0x01    /* flag for no specified uid. */
+#define _PASSWORD_NOGID                0x02    /* flag for no specified gid. */
+#define _PASSWORD_NOCHG                0x04    /* flag for no specified change. */
+#define _PASSWORD_NOEXP                0x08    /* flag for no specified expire. */
+
+#define _PASSWORD_OLDFMT       0x10    /* flag to expect an old style entry */
+#define _PASSWORD_NOWARN       0x20    /* no warnings for bad entries */
+
+#define _PASSWORD_WARNDAYS     14      /* days to warn about expiry */
+#define _PASSWORD_CHGNOW       -1      /* special day to force password
+                                        * change at next login */
+#endif
+
+struct passwd {
+       __aconst char *pw_name;         /* user name */
+       __aconst char *pw_passwd;       /* encrypted password */
+       uid_t          pw_uid;          /* user uid */
+       gid_t          pw_gid;          /* user gid */
+       time_t         pw_change;       /* password change time */
+       __aconst char *pw_class;        /* user login class */
+       __aconst char *pw_gecos;        /* general information */
+       __aconst char *pw_dir;          /* home directory */
+       __aconst char *pw_shell;        /* default shell */
+       time_t         pw_expire;       /* account expiration */
+};
+
+__BEGIN_DECLS
+#ifndef __LIBC12_SOURCE__
+struct passwd  *getpwuid(uid_t) __RENAME(__getpwuid50);
+struct passwd  *getpwnam(const char *) __RENAME(__getpwnam50);
+#endif
+#if (_POSIX_C_SOURCE - 0) >= 199506L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_REENTRANT) || defined(_NETBSD_SOURCE)
+#ifndef __LIBC12_SOURCE__
+int             getpwnam_r(const char *, struct passwd *, char *, size_t,
+    struct passwd **) __RENAME(__getpwnam_r50);
+int             getpwuid_r(uid_t, struct passwd *, char *, size_t,
+    struct passwd **) __RENAME(__getpwuid_r50);
+#endif
+#endif
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+#ifndef __LIBC12_SOURCE__
+struct passwd  *getpwent(void) __RENAME(__getpwent50);
+#endif
+void            setpwent(void);
+void            endpwent(void);
+#endif
+#if defined(_NETBSD_SOURCE)
+int             pw_gensalt(char *, size_t, const char *, const char *);
+#ifndef __LIBC12_SOURCE__
+int             pw_scan(char *, struct passwd *, int *) __RENAME(__pw_scan50);
+int             getpwent_r(struct passwd *, char *, size_t, struct passwd **)
+    __RENAME(__getpwent_r50);
+#endif
+int             setpassent(int);
+const char     *user_from_uid(uid_t, int);
+int             uid_from_user(const char *, uid_t *);
+#ifndef __LIBC12_SOURCE__
+int             pwcache_userdb(int (*)(int), void (*)(void),
+    struct passwd * (*)(const char *), struct passwd * (*)(uid_t))
+    __RENAME(__pwcache_userdb50);
+#endif
+#endif
+__END_DECLS
+
+#endif /* !_PWD_H_ */
diff --git a/nbsd_include/randomid.h b/nbsd_include/randomid.h
new file mode 100644 (file)
index 0000000..e0734f1
--- /dev/null
@@ -0,0 +1,83 @@
+/*     $NetBSD: randomid.h,v 1.2 2005/12/26 19:01:47 perry Exp $       */
+/*     $KAME: ip6_id.c,v 1.8 2003/09/06 13:41:06 itojun Exp $  */
+/*     $OpenBSD: ip_id.c,v 1.6 2002/03/15 18:19:52 millert Exp $       */
+
+/*
+ * Copyright (C) 2003 WIDE Project.
+ * 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.
+ * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
+ */
+
+/*
+ * Copyright 1998 Niels Provos <provos@citi.umich.edu>
+ * All rights reserved.
+ *
+ * Theo de Raadt <deraadt@openbsd.org> came up with the idea of using
+ * such a mathematical system to generate more random (yet non-repeating)
+ * ids to solve the resolver/named problem.  But Niels designed the
+ * actual system based on the constraints.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by Niels Provos.
+ * 4. 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 ``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 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 _RANDOMID_H_
+#define _RANDOMID_H_
+
+struct randomid_ctx;
+
+typedef struct randomid_ctx *randomid_t;
+
+extern uint32_t randomid(randomid_t);
+extern randomid_t randomid_new(int, long);
+extern void randomid_delete(randomid_t);
+
+#define RANDOMID_TIMEO_MIN     ((long)60)
+#define RANDOMID_TIMEO_DEFAULT ((long)180)
+
+#endif /*_RANDOMID_H_*/
diff --git a/nbsd_include/ranlib.h b/nbsd_include/ranlib.h
new file mode 100644 (file)
index 0000000..7921c98
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: ranlib.h,v 1.6 2003/08/07 09:44:11 agc Exp $   */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)ranlib.h    8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _RANLIB_H_
+#define        _RANLIB_H_
+
+#define        RANLIBMAG       "__.SYMDEF"     /* archive file name */
+#define        RANLIBSKEW      3               /* creation time offset */
+
+struct ranlib {
+       union {
+               long ran_strx;          /* string table index */
+               char *ran_name;         /* in memory symbol name */
+       } ran_un;
+       long ran_off;                   /* archive file offset */
+};
+
+#endif /* !_RANLIB_H_ */
diff --git a/nbsd_include/re_comp.h b/nbsd_include/re_comp.h
new file mode 100644 (file)
index 0000000..40ae28a
--- /dev/null
@@ -0,0 +1,41 @@
+/*     $NetBSD: re_comp.h,v 1.4 2008/04/28 20:22:54 martin Exp $       */
+
+/*-
+ * Copyright (c) 1996 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by J.T. Conklin.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _RE_COMP_H_
+#define _RE_COMP_H_
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+char   *re_comp(const char *);
+int    re_exec(const char *);
+__END_DECLS
+
+#endif /* _RE_COMP_H_ */
diff --git a/nbsd_include/regex.h b/nbsd_include/regex.h
new file mode 100644 (file)
index 0000000..b02a82e
--- /dev/null
@@ -0,0 +1,142 @@
+/*     $NetBSD: regex.h,v 1.13 2005/09/13 01:44:32 christos Exp $      */
+
+/*-
+ * Copyright (c) 1992, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer of the University of Toronto.
+ *
+ * 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. 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.
+ *
+ *     @(#)regex.h     8.2 (Berkeley) 1/3/94
+ */
+
+/*-
+ * Copyright (c) 1992 Henry Spencer.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Henry Spencer of the University of Toronto.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ *     @(#)regex.h     8.2 (Berkeley) 1/3/94
+ */
+
+#ifndef _REGEX_H_
+#define        _REGEX_H_
+
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+/* types */
+typedef off_t regoff_t;
+
+typedef struct {
+       int re_magic;
+       size_t re_nsub;         /* number of parenthesized subexpressions */
+       const char *re_endp;    /* end pointer for REG_PEND */
+       struct re_guts *re_g;   /* none of your business :-) */
+} regex_t;
+
+typedef struct {
+       regoff_t rm_so;         /* start of match */
+       regoff_t rm_eo;         /* end of match */
+} regmatch_t;
+
+/* regcomp() flags */
+#define        REG_BASIC       0000
+#define        REG_EXTENDED    0001
+#define        REG_ICASE       0002
+#define        REG_NOSUB       0004
+#define        REG_NEWLINE     0010
+#define        REG_NOSPEC      0020
+#define        REG_PEND        0040
+#define        REG_DUMP        0200
+
+/* regerror() flags */
+#define        REG_NOMATCH      1
+#define        REG_BADPAT       2
+#define        REG_ECOLLATE     3
+#define        REG_ECTYPE       4
+#define        REG_EESCAPE      5
+#define        REG_ESUBREG      6
+#define        REG_EBRACK       7
+#define        REG_EPAREN       8
+#define        REG_EBRACE       9
+#define        REG_BADBR       10
+#define        REG_ERANGE      11
+#define        REG_ESPACE      12
+#define        REG_BADRPT      13
+#define        REG_EMPTY       14
+#define        REG_ASSERT      15
+#define        REG_INVARG      16
+#define        REG_ENOSYS      17
+#define        REG_ATOI        255     /* convert name to number (!) */
+#define        REG_ITOA        0400    /* convert number to name (!) */
+
+/* regexec() flags */
+#define        REG_NOTBOL      00001
+#define        REG_NOTEOL      00002
+#define        REG_STARTEND    00004
+#define        REG_TRACE       00400   /* tracing of execution */
+#define        REG_LARGE       01000   /* force large representation */
+#define        REG_BACKR       02000   /* force use of backref code */
+
+__BEGIN_DECLS
+int    regcomp(regex_t * __restrict, const char * __restrict, int);
+size_t regerror(int, const regex_t * __restrict, char * __restrict, size_t);
+int    regexec(const regex_t * __restrict,
+           const char * __restrict, size_t, regmatch_t [], int);
+void   regfree(regex_t *);
+__END_DECLS
+
+#endif /* !_REGEX_H_ */
diff --git a/nbsd_include/regexp.h b/nbsd_include/regexp.h
new file mode 100644 (file)
index 0000000..b79955c
--- /dev/null
@@ -0,0 +1,109 @@
+/*     $NetBSD: regexp.h,v 1.7 2005/02/03 04:39:32 perry Exp $ */
+
+/*
+ * Copyright (c) 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley
+ * by Henry Spencer.
+ *
+ * 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. 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.
+ *
+ *     @(#)regexp.h    8.1 (Berkeley) 6/2/93
+ */
+
+/*
+ * Copyright (c) 1986 by University of Toronto.
+ *
+ * This code is derived from software contributed to Berkeley
+ * by Henry Spencer.
+ *
+ * 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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 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.
+ *
+ *     @(#)regexp.h    8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef        _REGEXP_H_
+#define        _REGEXP_H_
+
+/*
+ * Definitions etc. for regexp(3) routines.
+ *
+ * Caveat:  this is V8 regexp(3) [actually, a reimplementation thereof],
+ * not the System V one.
+ */
+#define NSUBEXP  10
+typedef struct regexp {
+       char *startp[NSUBEXP];
+       char *endp[NSUBEXP];
+       char regstart;          /* Internal use only. */
+       char reganch;           /* Internal use only. */
+       char *regmust;          /* Internal use only. */
+       int regmlen;            /* Internal use only. */
+       char program[1];        /* Unwarranted chumminess with compiler. */
+} regexp;
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+#ifdef __LIBCOMPAT_SOURCE__
+regexp *__compat_regcomp(const char *);
+int __compat_regexec(const  regexp *, const char *);
+void __compat_regsub(const  regexp *, const char *, char *);
+void __compat_regerror(const char *);
+#endif
+regexp *regcomp(const char *) __RENAME(__compat_regcomp);
+int regexec(const  regexp *, const char *) __RENAME(__compat_regexec);
+void regsub(const  regexp *, const char *, char *) __RENAME(__compat_regsub);
+void regerror(const char *) __RENAME(__compat_regerror);
+__END_DECLS
+
+#endif /* !_REGEXP_H_ */
diff --git a/nbsd_include/res_update.h b/nbsd_include/res_update.h
new file mode 100644 (file)
index 0000000..b53a355
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: res_update.h,v 1.7 2009/04/12 17:07:33 christos Exp $  */
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1999 by Internet Software Consortium, Inc.
+ *
+ * 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 ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/*
+ *     Id: res_update.h,v 1.3 2005/04/27 04:56:15 sra Exp
+ */
+
+#ifndef __RES_UPDATE_H
+#define __RES_UPDATE_H
+
+#include <sys/types.h>
+#include <arpa/nameser.h>
+#include <isc/list.h>
+#include <resolv.h>
+
+/*%
+ * This RR-like structure is particular to UPDATE.
+ */
+struct ns_updrec {
+       LINK(struct ns_updrec) r_link, r_glink;
+       ns_sect         r_section;      /*%< ZONE/PREREQUISITE/UPDATE */
+       char *          r_dname;        /*%< owner of the RR */
+       ns_class        r_class;        /*%< class number */
+       ns_type         r_type;         /*%< type number */
+       uint32_t        r_ttl;          /*%< time to live */
+       u_char *        r_data;         /*%< rdata fields as text string */
+       u_int           r_size;         /*%< size of r_data field */
+       int             r_opcode;       /*%< type of operation */
+       /* following fields for private use by the resolver/server routines */
+       struct databuf *r_dp;           /*%< databuf to process */
+       struct databuf *r_deldp;        /*%< databuf's deleted/overwritten */
+       u_int           r_zone;         /*%< zone number on server */
+};
+typedef struct ns_updrec ns_updrec;
+typedef        LIST(ns_updrec) ns_updque;
+
+#define res_mkupdate           __res_mkupdate
+#define res_update             __res_update
+#define res_mkupdrec           __res_mkupdrec
+#define res_freeupdrec         __res_freeupdrec
+#define res_nmkupdate          __res_nmkupdate
+#define res_nupdate            __res_nupdate
+
+int            res_mkupdate(ns_updrec *, u_char *, int);
+int            res_update(ns_updrec *);
+ns_updrec *    res_mkupdrec(int, const char *, u_int, u_int, u_long);
+void           res_freeupdrec(ns_updrec *);
+int            res_nmkupdate(res_state, ns_updrec *, u_char *, int);
+int            res_nupdate(res_state, ns_updrec *, ns_tsig_key *);
+
+#endif /*__RES_UPDATE_H*/
diff --git a/nbsd_include/resolv.h b/nbsd_include/resolv.h
new file mode 100644 (file)
index 0000000..c5325f8
--- /dev/null
@@ -0,0 +1,509 @@
+/*     $NetBSD: resolv.h,v 1.38 2009/10/24 17:23:34 christos Exp $     */
+
+/*
+ * Portions Copyright (C) 2004, 2005, 2008, 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Portions Copyright (C) 1995-2003  Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and/or 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 ISC DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS.  IN NO EVENT SHALL ISC 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.
+ */
+
+/*
+ * Copyright (c) 1983, 1987, 1989
+ *    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.
+ * 3. 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.
+ */
+
+/*%
+ *     @(#)resolv.h    8.1 (Berkeley) 6/2/93
+ *     Id: resolv.h,v 1.30 2009/03/03 01:52:48 each Exp
+ */
+
+#ifndef _RESOLV_H_
+#define        _RESOLV_H_
+
+#include <sys/param.h>
+#if (!defined(BSD)) || (BSD < 199306)
+# include <sys/bitypes.h>
+#else
+#include <sys/types.h>
+#endif
+#include <sys/cdefs.h>
+#include <sys/socket.h>
+#include <stdio.h>
+#include <arpa/nameser.h>
+
+/*%
+ * Revision information.  This is the release date in YYYYMMDD format.
+ * It can change every day so the right thing to do with it is use it
+ * in preprocessor commands such as "#if (__RES > 19931104)".  Do not
+ * compare for equality; rather, use it to determine whether your resolver
+ * is new enough to contain a certain feature.
+ */
+
+#define        __RES   20090302
+
+/*%
+ * This used to be defined in res_query.c, now it's in herror.c.
+ * [XXX no it's not.  It's in irs/irs_data.c]
+ * It was
+ * never extern'd by any *.h file before it was placed here.  For thread
+ * aware programs, the last h_errno value set is stored in res->h_errno.
+ *
+ * XXX:        There doesn't seem to be a good reason for exposing RES_SET_H_ERRNO
+ *     (and __h_errno_set) to the public via <resolv.h>.
+ * XXX:        __h_errno_set is really part of IRS, not part of the resolver.
+ *     If somebody wants to build and use a resolver that doesn't use IRS,
+ *     what do they do?  Perhaps something like
+ *             #ifdef WANT_IRS
+ *             # define RES_SET_H_ERRNO(r,x) __h_errno_set(r,x)
+ *             #else
+ *             # define RES_SET_H_ERRNO(r,x) (h_errno = (r)->res_h_errno = (x))
+ *             #endif
+ */
+
+#define RES_SET_H_ERRNO(r,x) __h_errno_set(r,x)
+struct __res_state; /*%< forward */
+__BEGIN_DECLS
+void __h_errno_set(struct __res_state *, int);
+__END_DECLS
+
+/*%
+ * Resolver configuration file.
+ * Normally not present, but may contain the address of the
+ * initial name server(s) to query and the domain search list.
+ */
+
+#ifndef _PATH_RESCONF
+#define _PATH_RESCONF        "/etc/resolv.conf"
+#endif
+
+typedef enum { res_goahead, res_nextns, res_modified, res_done, res_error }
+       res_sendhookact;
+
+typedef res_sendhookact (*res_send_qhook)(struct sockaddr * const *,
+                                             const u_char **, int *,
+                                             u_char *, int, int *);
+
+typedef res_sendhookact (*res_send_rhook)(const struct sockaddr *,
+                                             const u_char *, int, u_char *,
+                                             int, int *);
+
+struct res_sym {
+       int             number;    /*%< Identifying number, like T_MX */
+       const char *    name;      /*%< Its symbolic name, like "MX" */
+       const char *    humanname; /*%< Its fun name, like "mail exchanger" */
+};
+
+/*%
+ * Global defines and variables for resolver stub.
+ */
+#define        MAXNS                   3       /*%< max # name servers we'll track */
+#define        MAXDFLSRCH              3       /*%< # default domain levels to try */
+#define        MAXDNSRCH               6       /*%< max # domains in search path */
+#define        LOCALDOMAINPARTS        2       /*%< min levels in name that is "local" */
+#define        RES_TIMEOUT             5       /*%< min. seconds between retries */
+#define        MAXRESOLVSORT           10      /*%< number of net to sort on */
+#define        RES_MAXNDOTS            15      /*%< should reflect bit field size */
+#define        RES_MAXRETRANS          30      /*%< only for resolv.conf/RES_OPTIONS */
+#define        RES_MAXRETRY            5       /*%< only for resolv.conf/RES_OPTIONS */
+#define        RES_DFLRETRY            2       /*%< Default #/tries. */
+#define        RES_MAXTIME             65535   /*%< Infinity, in milliseconds. */
+
+struct __res_state_ext;
+
+struct __res_state {
+       int     retrans;                /*%< retransmission time interval */
+       int     retry;                  /*%< number of times to retransmit */
+#ifdef sun
+       u_int   options;                /*%< option flags - see below. */
+#else
+       u_long  options;                /*%< option flags - see below. */
+#endif
+       int     nscount;                /*%< number of name servers */
+       struct sockaddr_in
+               nsaddr_list[MAXNS];     /*%< address of name server */
+#define        nsaddr  nsaddr_list[0]          /*%< for backward compatibility */
+       u_short id;                     /*%< current message id */
+       char    *dnsrch[MAXDNSRCH+1];   /*%< components of domain to search */
+       char    defdname[256];          /*%< default domain (deprecated) */
+#ifdef sun
+       u_int   pfcode;                 /*%< RES_PRF_ flags - see below. */
+#else
+       u_long  pfcode;                 /*%< RES_PRF_ flags - see below. */
+#endif
+       unsigned ndots:4;               /*%< threshold for initial abs. query */
+       unsigned nsort:4;               /*%< number of elements in sort_list[] */
+       char    unused[3];
+       struct {
+               struct in_addr  addr;
+               uint32_t        mask;
+       } sort_list[MAXRESOLVSORT];
+#ifdef __OLD_RES_STATE
+       char lookups[4];
+#else
+       res_send_qhook qhook;           /*%< query hook */
+       res_send_rhook rhook;           /*%< response hook */
+       int     res_h_errno;            /*%< last one set for this context */
+       int     _vcsock;                /*%< PRIVATE: for res_send VC i/o */
+       u_int   _flags;                 /*%< PRIVATE: see below */
+       u_int   _pad;                   /*%< make _u 64 bit aligned */
+       union {
+               /* On an 32-bit arch this means 512b total. */
+               char    pad[56 - 4*sizeof (int) - 3*sizeof (void *)];
+               struct {
+                       uint16_t                nscount;
+                       uint16_t                nstimes[MAXNS]; /*%< ms. */
+                       int                     nssocks[MAXNS];
+                       struct __res_state_ext *ext;    /*%< extention for IPv6 */
+               } _ext;
+       } _u;
+       u_char  *_rnd;                  /*%< PRIVATE: random state */
+#endif
+};
+
+typedef struct __res_state *res_state;
+
+union res_sockaddr_union {
+       struct sockaddr_in      sin;
+#ifdef IN6ADDR_ANY_INIT
+       struct sockaddr_in6     sin6;
+#endif
+#ifdef ISC_ALIGN64
+       int64_t                 __align64;      /*%< 64bit alignment */
+#else
+       int32_t                 __align32;      /*%< 32bit alignment */
+#endif
+       char                    __space[128];   /* max size */
+};
+
+/*%
+ * Resolver flags (used to be discrete per-module statics ints).
+ */
+#define        RES_F_VC        0x00000001      /*%< socket is TCP */
+#define        RES_F_CONN      0x00000002      /*%< socket is connected */
+#define        RES_F_EDNS0ERR  0x00000004      /*%< EDNS0 caused errors */
+#define        RES_F__UNUSED   0x00000008      /*%< (unused) */
+#define        RES_F_LASTMASK  0x000000F0      /*%< ordinal server of last res_nsend */
+#define        RES_F_LASTSHIFT 4               /*%< bit position of LASTMASK "flag" */
+#define        RES_GETLAST(res) (((res)._flags & RES_F_LASTMASK) >> RES_F_LASTSHIFT)
+
+/* res_findzonecut2() options */
+#define        RES_EXHAUSTIVE  0x00000001      /*%< always do all queries */
+#define        RES_IPV4ONLY    0x00000002      /*%< IPv4 only */
+#define        RES_IPV6ONLY    0x00000004      /*%< IPv6 only */
+
+/*%
+ * Resolver options (keep these in synch with res_debug.c, please)
+ */
+#define RES_INIT       0x00000001      /*%< address initialized */
+#define RES_DEBUG      0x00000002      /*%< print debug messages */
+#define RES_AAONLY     0x00000004      /*%< authoritative answers only (!IMPL)*/
+#define RES_USEVC      0x00000008      /*%< use virtual circuit */
+#define RES_PRIMARY    0x00000010      /*%< query primary server only (!IMPL) */
+#define RES_IGNTC      0x00000020      /*%< ignore trucation errors */
+#define RES_RECURSE    0x00000040      /*%< recursion desired */
+#define RES_DEFNAMES   0x00000080      /*%< use default domain name */
+#define RES_STAYOPEN   0x00000100      /*%< Keep TCP socket open */
+#define RES_DNSRCH     0x00000200      /*%< search up local domain tree */
+#define        RES_INSECURE1   0x00000400      /*%< type 1 security disabled */
+#define        RES_INSECURE2   0x00000800      /*%< type 2 security disabled */
+#define        RES_NOALIASES   0x00001000      /*%< shuts off HOSTALIASES feature */
+#define        RES_USE_INET6   0x00002000      /*%< use/map IPv6 in gethostbyname() */
+#define RES_ROTATE     0x00004000      /*%< rotate ns list after each query */
+#define        RES_NOCHECKNAME 0x00008000      /*%< do not check names for sanity. */
+#define        RES_KEEPTSIG    0x00010000      /*%< do not strip TSIG records */
+#define        RES_BLAST       0x00020000      /*%< blast all recursive servers */
+#define RES_NSID       0x00040000      /*%< request name server ID */
+#define RES_NOTLDQUERY 0x00100000      /*%< don't unqualified name as a tld */
+#define RES_USE_DNSSEC 0x00200000      /*%< use DNSSEC using OK bit in OPT */
+/* #define RES_DEBUG2  0x00400000 */   /* nslookup internal */
+/* KAME extensions: use higher bit to avoid conflict with ISC use */
+#define RES_USE_DNAME  0x10000000      /*%< use DNAME */
+#define RES_USE_EDNS0  0x40000000      /*%< use EDNS0 if configured */
+#define RES_NO_NIBBLE2 0x80000000      /*%< disable alternate nibble lookup */
+
+#define RES_DEFAULT    (RES_RECURSE | RES_DEFNAMES | \
+                        RES_DNSRCH | RES_NO_NIBBLE2)
+
+/*%
+ * Resolver "pfcode" values.  Used by dig.
+ */
+#define RES_PRF_STATS  0x00000001
+#define RES_PRF_UPDATE 0x00000002
+#define RES_PRF_CLASS   0x00000004
+#define RES_PRF_CMD    0x00000008
+#define RES_PRF_QUES   0x00000010
+#define RES_PRF_ANS    0x00000020
+#define RES_PRF_AUTH   0x00000040
+#define RES_PRF_ADD    0x00000080
+#define RES_PRF_HEAD1  0x00000100
+#define RES_PRF_HEAD2  0x00000200
+#define RES_PRF_TTLID  0x00000400
+#define RES_PRF_HEADX  0x00000800
+#define RES_PRF_QUERY  0x00001000
+#define RES_PRF_REPLY  0x00002000
+#define RES_PRF_INIT   0x00004000
+#define RES_PRF_TRUNC  0x00008000
+/*                     0x00010000      */
+
+/* Things involving an internal (static) resolver context. */
+__BEGIN_DECLS
+extern struct __res_state *__res_get_state(void);
+extern void __res_put_state(struct __res_state *);
+
+/*
+ * Source and Binary compatibility; _res will not work properly
+ * with multi-threaded programs.
+ */
+extern struct __res_state *__res_state(void);
+#define _res (*__res_state())
+
+__END_DECLS
+
+#ifndef __BIND_NOSTATIC
+#define fp_nquery              __fp_nquery
+#define fp_query               __fp_query
+#define hostalias              __hostalias
+#define p_query                        __p_query
+#define res_close              __res_close
+#define res_isourserver                __res_isourserver
+#define        res_opt                 __res_opt
+#define        res_querydomain         __res_querydomain
+#define res_send               __res_send
+#define res_sendsigned         __res_sendsigned
+
+#ifdef notdef
+/* NetBSD protects these via weak symbols. */
+#define        res_init                __res_init
+#define        res_query               __res_query
+#define        res_mkquery             __res_mkquery
+#define        dn_expand               __dn_expand
+#define        res_search              __res_search
+#endif
+
+__BEGIN_DECLS
+void           fp_nquery(const u_char *, int, FILE *);
+void           fp_query(const u_char *, FILE *);
+const char *   hostalias(const char *);
+void           p_query(const u_char *);
+void           res_close(void);
+int            res_init(void);
+int            res_opt(int, u_char *, int, int);
+int            res_isourserver(const struct sockaddr_in *);
+int            res_mkquery(int, const char *, int, int, const u_char *,
+                                int, const u_char *, u_char *, int);
+int            res_query(const char *, int, int, u_char *, int);
+int            res_querydomain(const char *, const char *, int, int,
+                                    u_char *, int);
+int            res_search(const char *, int, int, u_char *, int);
+int            res_send(const u_char *, int, u_char *, int);
+int            res_sendsigned(const u_char *, int, ns_tsig_key *,
+                                   u_char *, int);
+__END_DECLS
+#endif
+
+#if !defined(SHARED_LIBBIND) || defined(LIB)
+/*
+ * If libbind is a shared object (well, DLL anyway)
+ * these externs break the linker when resolv.h is
+ * included by a lib client (like named)
+ * Make them go away if a client is including this
+ *
+ */
+extern const struct res_sym __p_key_syms[];
+extern const struct res_sym __p_cert_syms[];
+extern const struct res_sym __p_class_syms[];
+extern const struct res_sym __p_type_syms[];
+extern const struct res_sym __p_rcode_syms[];
+#endif /* SHARED_LIBBIND */
+
+#define b64_ntop               __b64_ntop
+#define b64_pton               __b64_pton
+#define dn_comp                        __dn_comp
+#define dn_count_labels                __dn_count_labels
+#define dn_skipname            __dn_skipname
+#define fp_resstat             __fp_resstat
+#define loc_aton               __loc_aton
+#define loc_ntoa               __loc_ntoa
+#define p_cdname               __p_cdname
+#define p_cdnname              __p_cdnname
+#define p_class                        __p_class
+#define p_fqname               __p_fqname
+#define p_fqnname              __p_fqnname
+#define p_option               __p_option
+#define p_secstodate           __p_secstodate
+#define p_section              __p_section
+#define p_time                 __p_time
+#define p_type                 __p_type
+#define p_rcode                        __p_rcode
+#define p_sockun               __p_sockun
+#define putlong                        __putlong
+#define putshort               __putshort
+#define        res_check               __res_check
+#define res_dnok               __res_dnok
+#define res_findzonecut                __res_findzonecut
+#define res_findzonecut2       __res_findzonecut2
+#define res_hnok               __res_hnok
+#define res_hostalias          __res_hostalias
+#define res_mailok             __res_mailok
+#define res_nameinquery                __res_nameinquery
+#define res_nclose             __res_nclose
+#define res_ninit              __res_ninit
+#define res_nmkquery           __res_nmkquery
+#define res_pquery             __res_pquery
+#define res_nquery             __res_nquery
+#define res_nquerydomain       __res_nquerydomain
+#define res_nsearch            __res_nsearch
+#define res_nsend              __res_nsend
+#define res_nsendsigned                __res_nsendsigned
+#define res_nisourserver       __res_nisourserver
+#define res_ownok              __res_ownok
+#define res_queriesmatch       __res_queriesmatch
+#define res_rndinit            __res_rndinit
+#define res_randomid           __res_randomid
+#define res_nrandomid          __res_nrandomid
+#define sym_ntop               __sym_ntop
+#define sym_ntos               __sym_ntos
+#define sym_ston               __sym_ston
+#define res_nopt               __res_nopt
+#define res_nopt_rdata         __res_nopt_rdata
+#define res_ndestroy           __res_ndestroy
+#define        res_nametoclass         __res_nametoclass
+#define        res_nametotype          __res_nametotype
+#define        res_setservers          __res_setservers
+#define        res_getservers          __res_getservers
+#define        res_buildprotolist      __res_buildprotolist
+#define        res_destroyprotolist    __res_destroyprotolist
+#define        res_destroyservicelist  __res_destroyservicelist
+#define        res_get_nibblesuffix    __res_get_nibblesuffix
+#define        res_get_nibblesuffix2   __res_get_nibblesuffix2
+#define        res_ourserver_p         __res_ourserver_p
+#define        res_protocolname        __res_protocolname
+#define        res_protocolnumber      __res_protocolnumber
+#define        res_send_setqhook       __res_send_setqhook
+#define        res_send_setrhook       __res_send_setrhook
+#define        res_servicename         __res_servicename
+#define        res_servicenumber       __res_servicenumber
+__BEGIN_DECLS
+int            res_hnok(const char *);
+int            res_ownok(const char *);
+int            res_mailok(const char *);
+struct timespec;
+int            res_check(res_state, struct timespec *);
+int            res_dnok(const char *);
+int            sym_ston(const struct res_sym *, const char *, int *);
+const char *   sym_ntos(const struct res_sym *, int, int *);
+const char *   sym_ntop(const struct res_sym *, int, int *);
+int            b64_ntop(u_char const *, size_t, char *, size_t);
+int            b64_pton(char const *, u_char *, size_t);
+int            loc_aton(const char *, u_char *);
+const char *   loc_ntoa(const u_char *, char *);
+int            dn_skipname(const u_char *, const u_char *);
+void           putlong(uint32_t, u_char *);
+void           putshort(uint16_t, u_char *);
+#ifndef __ultrix__
+uint16_t       _getshort(const u_char *);
+uint32_t       _getlong(const u_char *);
+#endif
+const char *   p_class(int);
+const char *   p_time(uint32_t);
+const char *   p_type(int);
+const char *   p_rcode(int);
+const char *   p_sockun(union res_sockaddr_union, char *, size_t);
+const u_char * p_cdnname(const u_char *, const u_char *, int, FILE *);
+const u_char * p_cdname(const u_char *, const u_char *, FILE *);
+const u_char * p_fqnname(const u_char *, const u_char *,
+                              int, char *, int);
+const u_char * p_fqname(const u_char *, const u_char *, FILE *);
+const char *   p_option(u_long);
+char *         p_secstodate(u_long);
+int            dn_count_labels(const char *);
+int            dn_comp(const char *, u_char *, int, u_char **, u_char **);
+int            dn_expand(const u_char *, const u_char *, const u_char *,
+                              char *, int);
+void           res_rndinit(res_state);
+u_int          res_randomid(void);
+u_int          res_nrandomid(res_state);
+int            res_nameinquery(const char *, int, int, const u_char *,
+                                    const u_char *);
+int            res_queriesmatch(const u_char *, const u_char *,
+                                     const u_char *, const u_char *);
+const char *   p_section(int, int);
+/* Things involving a resolver context. */
+int            res_ninit(res_state);
+int            res_nisourserver(const res_state, const struct sockaddr_in *);
+void           fp_resstat(const res_state, FILE *);
+void           res_pquery(const res_state, const u_char *, int, FILE *);
+const char *   res_hostalias(const res_state, const char *, char *, size_t);
+int            res_nquery(res_state, const char *, int, int, u_char *, int);
+int            res_nsearch(res_state, const char *, int, int, u_char *, int);
+int            res_nquerydomain(res_state, const char *, const char *,
+                                     int, int, u_char *, int);
+int            res_nmkquery(res_state, int, const char *, int, int,
+                                 const u_char *, int, const u_char *,
+                                 u_char *, int);
+int            res_nsend(res_state, const u_char *, int, u_char *, int);
+int            res_nsendsigned(res_state, const u_char *, int,
+                                    ns_tsig_key *, u_char *, int);
+int            res_findzonecut(res_state, const char *, ns_class, int,
+                                    char *, size_t, struct in_addr *, int);
+int            res_findzonecut2(res_state, const char *, ns_class, int,
+                                     char *, size_t,
+                                     union res_sockaddr_union *, int);
+void           res_nclose(res_state);
+int            res_nopt(res_state, int, u_char *, int, int);
+int            res_nopt_rdata(res_state, int, u_char *, int, u_char *,
+                                   u_short, u_short, u_char *);
+void           res_send_setqhook(res_send_qhook);
+void           res_send_setrhook(res_send_rhook);
+int            __res_vinit(res_state, int);
+void           res_destroyservicelist(void);
+const char *   res_servicename(uint16_t, const char *);
+const char *   res_protocolname(int);
+void           res_destroyprotolist(void);
+void           res_buildprotolist(void);
+const char *   res_get_nibblesuffix(res_state);
+const char *   res_get_nibblesuffix2(res_state);
+void           res_ndestroy(res_state);
+uint16_t       res_nametoclass(const char *, int *);
+uint16_t       res_nametotype(const char *, int *);
+void           res_setservers(res_state,
+                                   const union res_sockaddr_union *, int);
+int            res_getservers(res_state,
+                                   union res_sockaddr_union *, int);
+__END_DECLS
+
+#endif /* !_RESOLV_H_ */
diff --git a/nbsd_include/rmt.h b/nbsd_include/rmt.h
new file mode 100644 (file)
index 0000000..75b4efc
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: rmt.h,v 1.6 2010/08/31 05:12:35 enami Exp $    */
+
+/*
+ *     rmt.h
+ *
+ *     Added routines to replace open(), close(), lseek(), ioctl(), etc.
+ *     The preprocessor can be used to remap these the rmtopen(), etc
+ *     thus minimizing source changes.
+ *
+ *     This file must be included before <sys/stat.h>, since it redefines
+ *     stat to be rmtstat, so that struct stat xyzzy; declarations work
+ *     properly.
+ *
+ *     -- Fred Fish (w/some changes by Arnold Robbins)
+ */
+
+#ifndef _RMT_H_
+#define _RMT_H_
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+int    isrmt(int);
+int    rmtaccess(const char *, int);
+int    rmtclose(int);
+int    rmtcreat(const char *, mode_t);
+int    rmtdup(int);
+int    rmtfcntl(int, int, ...);
+int    rmtfstat(int, struct stat *);
+int    rmtioctl(int, unsigned long, ...);
+int    rmtisatty(int);
+off_t  rmtlseek(int, off_t, int);
+int    rmtlstat(const char *, struct stat *);
+int    rmtopen(const char *, int, ...);
+ssize_t        rmtread(int, void *, size_t);
+int    rmtstat(const char *, struct stat *);
+ssize_t        rmtwrite(int, const void *, size_t);
+__END_DECLS
+
+#ifndef __RMTLIB_PRIVATE       /* don't remap if building librmt */
+#define access rmtaccess
+#define close rmtclose
+#define creat rmtcreat
+#define dup rmtdup
+#define fcntl rmtfcntl
+#define fstat rmtfstat
+#define ioctl rmtioctl
+#define isatty rmtisatty
+#define lseek rmtlseek
+#define lstat rmtlstat
+#define open rmtopen
+#define read rmtread
+#define stat rmtstat
+#define write rmtwrite
+#endif /* __RMTLIB_PRIVATE */
+
+#endif /* _RMT_H_ */
diff --git a/nbsd_include/rpc/Makefile b/nbsd_include/rpc/Makefile
new file mode 100644 (file)
index 0000000..b37d99d
--- /dev/null
@@ -0,0 +1,13 @@
+#      $NetBSD: Makefile,v 1.12 2003/01/11 13:28:43 tron Exp $
+#
+
+INCS=  auth.h auth_unix.h clnt.h clnt_soc.h nettype.h \
+       pmap_clnt.h pmap_prot.h pmap_rmt.h raw.h rpc.h \
+       rpc_com.h rpc_msg.h rpcb_clnt.h rpcb_prot.h rpcent.h \
+       svc.h svc_auth.h svc_soc.h types.h xdr.h
+RPC_INCS=      rpcb_prot.h
+
+INCSDIR=       /usr/include/rpc
+
+.include <bsd.rpc.mk>
+.include <bsd.prog.mk>
diff --git a/nbsd_include/rpc/auth.h b/nbsd_include/rpc/auth.h
new file mode 100644 (file)
index 0000000..d06a1b8
--- /dev/null
@@ -0,0 +1,193 @@
+/*     $NetBSD: auth.h,v 1.17 2005/12/26 19:01:47 perry Exp $  */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ *
+ *     from: @(#)auth.h 1.17 88/02/08 SMI
+ *     @(#)auth.h      2.3 88/08/07 4.0 RPCSRC
+ */
+
+/*
+ * auth.h, Authentication interface.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ * The data structures are completely opaque to the client.  The client
+ * is required to pass a AUTH * to routines that create rpc
+ * "sessions".
+ */
+
+#ifndef _RPC_AUTH_H_
+#define _RPC_AUTH_H_
+#include <sys/cdefs.h>
+
+#define MAX_AUTH_BYTES 400
+#define MAXNETNAMELEN  255     /* maximum length of network user's name */
+
+/*
+ * Status returned from authentication check
+ */
+enum auth_stat {
+       AUTH_OK=0,
+       /*
+        * failed at remote end
+        */
+       AUTH_BADCRED=1,                 /* bogus credentials (seal broken) */
+       AUTH_REJECTEDCRED=2,            /* client should begin new session */
+       AUTH_BADVERF=3,                 /* bogus verifier (seal broken) */
+       AUTH_REJECTEDVERF=4,            /* verifier expired or was replayed */
+       AUTH_TOOWEAK=5,                 /* rejected due to security reasons */
+       /*
+        * failed locally
+       */
+       AUTH_INVALIDRESP=6,             /* bogus response verifier */
+       AUTH_FAILED=7                   /* some unknown reason */
+};
+
+union des_block {
+       struct {
+               uint32_t high;
+               uint32_t low;
+       } key;
+       char c[8];
+};
+typedef union des_block des_block;
+__BEGIN_DECLS
+extern bool_t xdr_des_block(XDR *, des_block *);
+__END_DECLS
+
+/*
+ * Authentication info.  Opaque to client.
+ */
+struct opaque_auth {
+       enum_t  oa_flavor;              /* flavor of auth */
+       caddr_t oa_base;                /* address of more auth stuff */
+       u_int   oa_length;              /* not to exceed MAX_AUTH_BYTES */
+};
+
+
+/*
+ * Auth handle, interface to client side authenticators.
+ */
+typedef struct __rpc_auth {
+       struct  opaque_auth     ah_cred;
+       struct  opaque_auth     ah_verf;
+       union   des_block       ah_key;
+       const struct auth_ops {
+               void    (*ah_nextverf)(struct __rpc_auth *);
+               /* nextverf & serialize */
+               int     (*ah_marshal)(struct __rpc_auth *, XDR *);
+               /* validate varifier */
+               int     (*ah_validate)(struct __rpc_auth *,
+                           struct opaque_auth *);
+               /* refresh credentials */
+               int     (*ah_refresh)(struct __rpc_auth *);
+               /* destroy this structure */
+               void    (*ah_destroy)(struct __rpc_auth *);
+       } *ah_ops;
+       void *ah_private;
+} AUTH;
+
+
+/*
+ * Authentication ops.
+ * The ops and the auth handle provide the interface to the authenticators.
+ *
+ * AUTH        *auth;
+ * XDR *xdrs;
+ * struct opaque_auth verf;
+ */
+#define AUTH_NEXTVERF(auth)            \
+               ((*((auth)->ah_ops->ah_nextverf))(auth))
+#define auth_nextverf(auth)            \
+               ((*((auth)->ah_ops->ah_nextverf))(auth))
+
+#define AUTH_MARSHALL(auth, xdrs)      \
+               ((*((auth)->ah_ops->ah_marshal))(auth, xdrs))
+#define auth_marshall(auth, xdrs)      \
+               ((*((auth)->ah_ops->ah_marshal))(auth, xdrs))
+
+#define AUTH_VALIDATE(auth, verfp)     \
+               ((*((auth)->ah_ops->ah_validate))((auth), verfp))
+#define auth_validate(auth, verfp)     \
+               ((*((auth)->ah_ops->ah_validate))((auth), verfp))
+
+#define AUTH_REFRESH(auth)             \
+               ((*((auth)->ah_ops->ah_refresh))(auth))
+#define auth_refresh(auth)             \
+               ((*((auth)->ah_ops->ah_refresh))(auth))
+
+#define AUTH_DESTROY(auth)             \
+               ((*((auth)->ah_ops->ah_destroy))(auth))
+#define auth_destroy(auth)             \
+               ((*((auth)->ah_ops->ah_destroy))(auth))
+
+
+extern struct opaque_auth _null_auth;
+
+
+/*
+ * These are the various implementations of client side authenticators.
+ */
+
+/*
+ * Unix style authentication
+ * AUTH *authunix_create(machname, uid, gid, len, aup_gids)
+ *     char *machname;
+ *     int uid;
+ *     int gid;
+ *     int len;
+ *     int *aup_gids;
+ */
+__BEGIN_DECLS
+struct sockaddr_in;
+extern AUTH *authunix_create           (char *, int, int, int, int *);
+extern AUTH *authunix_create_default   (void);
+extern AUTH *authnone_create           (void);
+extern AUTH *authdes_create            (char *, u_int,
+                                           struct sockaddr_in *, des_block *);
+extern bool_t xdr_opaque_auth          (XDR *, struct opaque_auth *);
+
+#define authsys_create(c,i1,i2,i3,ip) authunix_create((c),(i1),(i2),(i3),(ip))
+#define authsys_create_default() authunix_create_default()
+
+struct svc_req;
+struct rpc_msg;
+enum auth_stat _svcauth_null(struct svc_req *, struct rpc_msg *);
+enum auth_stat _svcauth_short(struct svc_req *, struct rpc_msg *);
+enum auth_stat _svcauth_unix(struct svc_req *, struct rpc_msg *);
+__END_DECLS
+
+#define AUTH_NONE      0               /* no authentication */
+#define        AUTH_NULL       0               /* backward compatibility */
+#define        AUTH_SYS        1               /* unix style (uid, gids) */
+#define AUTH_UNIX      AUTH_SYS        /* backward compatibility */
+#define        AUTH_SHORT      2               /* short hand unix style */
+#define AUTH_DES       3               /* des style (encrypted timestamps) */
+
+#endif /* !_RPC_AUTH_H_ */
diff --git a/nbsd_include/rpc/auth_unix.h b/nbsd_include/rpc/auth_unix.h
new file mode 100644 (file)
index 0000000..c24b357
--- /dev/null
@@ -0,0 +1,83 @@
+/*     $NetBSD: auth_unix.h,v 1.8 2005/02/03 04:39:32 perry Exp $      */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ *
+ *     from: @(#)auth_unix.h 1.8 88/02/08 SMI
+ *     @(#)auth_unix.h 2.2 88/07/29 4.0 RPCSRC
+ */
+
+/*
+ * auth_unix.h, Protocol for UNIX style authentication parameters for RPC
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+/*
+ * The system is very weak.  The client uses no encryption for  it
+ * credentials and only sends null verifiers.  The server sends backs
+ * null verifiers or optionally a verifier that suggests a new short hand
+ * for the credentials.
+ */
+
+#ifndef _RPC_AUTH_UNIX_H_
+#define _RPC_AUTH_UNIX_H_
+#include <sys/cdefs.h>
+
+/* The machine name is part of a credential; it may not exceed 255 bytes */
+#define MAX_MACHINE_NAME 255
+
+/* gids compose part of a credential; there may not be more than 16 of them */
+#define NGRPS 16
+
+/*
+ * Unix style credentials.
+ */
+struct authunix_parms {
+       u_long   aup_time;
+       char    *aup_machname;
+       int      aup_uid;
+       int      aup_gid;
+       u_int    aup_len;
+       int     *aup_gids;
+};
+
+__BEGIN_DECLS
+extern bool_t xdr_authunix_parms(XDR *, struct authunix_parms *);
+__END_DECLS
+
+/* 
+ * If a response verifier has flavor AUTH_SHORT, 
+ * then the body of the response verifier encapsulates the following structure;
+ * again it is serialized in the obvious fashion.
+ */
+struct short_hand_verf {
+       struct opaque_auth new_cred;
+};
+
+#endif /* !_RPC_AUTH_UNIX_H_ */
diff --git a/nbsd_include/rpc/clnt.h b/nbsd_include/rpc/clnt.h
new file mode 100644 (file)
index 0000000..557f78b
--- /dev/null
@@ -0,0 +1,539 @@
+/*     $NetBSD: clnt.h,v 1.20 2005/12/03 15:16:19 yamt Exp $   */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ *
+ *     from: @(#)clnt.h 1.31 94/04/29 SMI
+ *     @(#)clnt.h      2.1 88/07/29 4.0 RPCSRC
+ */
+
+/*
+ * clnt.h - Client side remote procedure call interface.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#ifndef _RPC_CLNT_H_
+#define _RPC_CLNT_H_
+#include <sys/cdefs.h>
+
+#include <rpc/rpc_com.h>
+
+/*
+ * Well-known IPV6 RPC broadcast address.
+ */
+#define RPCB_MULTICAST_ADDR "ff02::202"
+
+/*
+ * Rpc calls return an enum clnt_stat.  This should be looked at more,
+ * since each implementation is required to live with this (implementation
+ * independent) list of errors.
+ */
+enum clnt_stat {
+       RPC_SUCCESS=0,                  /* call succeeded */
+       /*
+        * local errors
+        */
+       RPC_CANTENCODEARGS=1,           /* can't encode arguments */
+       RPC_CANTDECODERES=2,            /* can't decode results */
+       RPC_CANTSEND=3,                 /* failure in sending call */
+       RPC_CANTRECV=4,                 /* failure in receiving result */
+       RPC_TIMEDOUT=5,                 /* call timed out */
+       /*
+        * remote errors
+        */
+       RPC_VERSMISMATCH=6,             /* rpc versions not compatible */
+       RPC_AUTHERROR=7,                /* authentication error */
+       RPC_PROGUNAVAIL=8,              /* program not available */
+       RPC_PROGVERSMISMATCH=9,         /* program version mismatched */
+       RPC_PROCUNAVAIL=10,             /* procedure unavailable */
+       RPC_CANTDECODEARGS=11,          /* decode arguments error */
+       RPC_SYSTEMERROR=12,             /* generic "other problem" */
+
+       /*
+        * rpc_call & clnt_create errors
+        */
+       RPC_UNKNOWNHOST=13,             /* unknown host name */
+       RPC_UNKNOWNPROTO=17,            /* unknown protocol */
+       RPC_UNKNOWNADDR = 19,           /* Remote address unknown */
+       RPC_NOBROADCAST = 21,           /* Broadcasting not supported */
+
+       /*
+        * rpcbind errors
+        */
+       RPC_RPCBFAILURE=14,             /* the pmapper failed in its call */
+#define RPC_PMAPFAILURE RPC_RPCBFAILURE
+       RPC_PROGNOTREGISTERED=15,       /* remote program is not registered */
+       RPC_N2AXLATEFAILURE = 22,       /* name -> addr translation failed */
+
+       /*
+        * Misc error in the TLI library (provided for compatibility)
+        */
+       RPC_TLIERROR = 20,
+
+       /*
+        * unspecified error
+        */
+       RPC_FAILED=16,
+
+       /*
+        * asynchronous errors
+        */
+       RPC_INPROGRESS = 24,
+       RPC_STALERACHANDLE = 25
+};
+
+
+/*
+ * Error info.
+ */
+struct rpc_err {
+       enum clnt_stat re_status;
+       union {
+               int RE_errno;           /* related system error */
+               enum auth_stat RE_why;  /* why the auth error occurred */
+               struct {
+                       rpcvers_t low;  /* lowest version supported */
+                       rpcvers_t high; /* highest version supported */
+               } RE_vers;
+               struct {                /* maybe meaningful if RPC_FAILED */
+                       int32_t s1;
+                       int32_t s2;
+               } RE_lb;                /* life boot & debugging only */
+       } ru;
+#define        re_errno        ru.RE_errno
+#define        re_why          ru.RE_why
+#define        re_vers         ru.RE_vers
+#define        re_lb           ru.RE_lb
+};
+
+
+/*
+ * Client rpc handle.
+ * Created by individual implementations
+ * Client is responsible for initializing auth, see e.g. auth_none.c.
+ */
+typedef struct __rpc_client {
+       AUTH    *cl_auth;                       /* authenticator */
+       const struct clnt_ops {
+               /* call remote procedure */
+               enum clnt_stat  (*cl_call)(struct __rpc_client *,
+                                   rpcproc_t, xdrproc_t, const char *,
+                                   xdrproc_t, caddr_t, struct timeval);
+               /* abort a call */
+               void            (*cl_abort)(struct __rpc_client *);
+               /* get specific error code */
+               void            (*cl_geterr)(struct __rpc_client *,
+                                   struct rpc_err *);
+               /* frees results */
+               bool_t          (*cl_freeres)(struct __rpc_client *,
+                                   xdrproc_t, caddr_t);
+               /* destroy this structure */
+               void            (*cl_destroy)(struct __rpc_client *);
+               /* the ioctl() of rpc */
+               bool_t          (*cl_control)(struct __rpc_client *, u_int,
+                                   char *);
+       } *cl_ops;
+       void                    *cl_private;    /* private stuff */
+       char                    *cl_netid;      /* network token */
+       char                    *cl_tp;         /* device name */
+} CLIENT;
+
+
+/*
+ * Timers used for the pseudo-transport protocol when using datagrams
+ */
+struct rpc_timers {
+       u_short         rt_srtt;        /* smoothed round-trip time */
+       u_short         rt_deviate;     /* estimated deviation */
+       u_long          rt_rtxcur;      /* current (backed-off) rto */
+};
+
+/*      
+ * Feedback values used for possible congestion and rate control
+ */
+#define FEEDBACK_REXMIT1       1       /* first retransmit */
+#define FEEDBACK_OK            2       /* no retransmits */    
+
+/* Used to set version of portmapper used in broadcast */
+  
+#define CLCR_SET_LOWVERS       3
+#define CLCR_GET_LOWVERS       4
+#define RPCSMALLMSGSIZE 400    /* a more reasonable packet size */
+
+/*
+ * client side rpc interface ops
+ *
+ * Parameter types are:
+ *
+ */
+
+/*
+ * enum clnt_stat
+ * CLNT_CALL(rh, proc, xargs, argsp, xres, resp, timeout)
+ *     CLIENT *rh;
+ *     rpcproc_t proc;
+ *     xdrproc_t xargs;
+ *     caddr_t argsp;
+ *     xdrproc_t xres;
+ *     caddr_t resp;
+ *     struct timeval timeout;
+ */
+#define        CLNT_CALL(rh, proc, xargs, argsp, xres, resp, secs)             \
+       ((*(rh)->cl_ops->cl_call)(rh, proc, xargs,                      \
+       (const char *)(const void *)(argsp), xres, (caddr_t)(void *)resp, secs))
+#define        clnt_call(rh, proc, xargs, argsp, xres, resp, secs)             \
+       ((*(rh)->cl_ops->cl_call)(rh, proc, xargs,                      \
+       (const char *)(const void *)(argsp), xres, (caddr_t)(void *)resp, secs))
+
+/*
+ * void
+ * CLNT_ABORT(rh);
+ *     CLIENT *rh;
+ */
+#define        CLNT_ABORT(rh)  ((*(rh)->cl_ops->cl_abort)(rh))
+#define        clnt_abort(rh)  ((*(rh)->cl_ops->cl_abort)(rh))
+
+/*
+ * struct rpc_err
+ * CLNT_GETERR(rh);
+ *     CLIENT *rh;
+ */
+#define        CLNT_GETERR(rh,errp)    ((*(rh)->cl_ops->cl_geterr)(rh, errp))
+#define        clnt_geterr(rh,errp)    ((*(rh)->cl_ops->cl_geterr)(rh, errp))
+
+
+/*
+ * bool_t
+ * CLNT_FREERES(rh, xres, resp);
+ *     CLIENT *rh;
+ *     xdrproc_t xres;
+ *     caddr_t resp;
+ */
+#define        CLNT_FREERES(rh,xres,resp) ((*(rh)->cl_ops->cl_freeres)(rh,xres,resp))
+#define        clnt_freeres(rh,xres,resp) ((*(rh)->cl_ops->cl_freeres)(rh,xres,resp))
+
+/*
+ * bool_t
+ * CLNT_CONTROL(cl, request, info)
+ *      CLIENT *cl;
+ *      u_int request;
+ *      char *info;
+ */
+#define        CLNT_CONTROL(cl,rq,in) ((*(cl)->cl_ops->cl_control)(cl,rq,in))
+#define        clnt_control(cl,rq,in) ((*(cl)->cl_ops->cl_control)(cl,rq,in))
+
+/*
+ * control operations that apply to both udp and tcp transports
+ */
+#define CLSET_TIMEOUT          1       /* set timeout (timeval) */
+#define CLGET_TIMEOUT          2       /* get timeout (timeval) */
+#define CLGET_SERVER_ADDR      3       /* get server's address (sockaddr) */
+#define        CLGET_FD                6       /* get connections file descriptor */
+#define        CLGET_SVC_ADDR          7       /* get server's address (netbuf) */
+#define        CLSET_FD_CLOSE          8       /* close fd while clnt_destroy */
+#define        CLSET_FD_NCLOSE         9       /* Do not close fd while clnt_destroy */
+#define        CLGET_XID               10      /* Get xid */
+#define        CLSET_XID               11      /* Set xid */
+#define        CLGET_VERS              12      /* Get version number */
+#define        CLSET_VERS              13      /* Set version number */
+#define        CLGET_PROG              14      /* Get program number */
+#define        CLSET_PROG              15      /* Set program number */
+#define        CLSET_SVC_ADDR          16      /* get server's address (netbuf) */
+#define        CLSET_PUSH_TIMOD        17      /* push timod if not already present */
+#define        CLSET_POP_TIMOD         18      /* pop timod */
+/*
+ * Connectionless only control operations
+ */
+#define CLSET_RETRY_TIMEOUT 4   /* set retry timeout (timeval) */
+#define CLGET_RETRY_TIMEOUT 5   /* get retry timeout (timeval) */
+
+/*
+ * void
+ * CLNT_DESTROY(rh);
+ *     CLIENT *rh;
+ */
+#define        CLNT_DESTROY(rh)        ((*(rh)->cl_ops->cl_destroy)(rh))
+#define        clnt_destroy(rh)        ((*(rh)->cl_ops->cl_destroy)(rh))
+
+
+/*
+ * RPCTEST is a test program which is accessible on every rpc
+ * transport/port.  It is used for testing, performance evaluation,
+ * and network administration.
+ */
+
+#define RPCTEST_PROGRAM                ((rpcprog_t)1)
+#define RPCTEST_VERSION                ((rpcvers_t)1)
+#define RPCTEST_NULL_PROC      ((rpcproc_t)2)
+#define RPCTEST_NULL_BATCH_PROC        ((rpcproc_t)3)
+
+/*
+ * By convention, procedure 0 takes null arguments and returns them
+ */
+
+#define NULLPROC ((rpcproc_t)0)
+
+/*
+ * Below are the client handle creation routines for the various
+ * implementations of client side rpc.  They can return NULL if a
+ * creation failure occurs.             
+ */     
+
+/*
+ * Generic client creation routine. Supported protocols are those that
+ * belong to the nettype namespace (/etc/netconfig).
+ * CLIENT *
+ * clnt_create(host, prog, vers, prot);
+ *     const char *host;       -- hostname
+ *     const rpcprog_t prog;   -- program number
+ *     const rpcvers_t vers;   -- version number
+ *     const char *prot;       -- protocol
+ */
+__BEGIN_DECLS
+extern CLIENT *clnt_create(const char *, const rpcprog_t, const rpcvers_t,
+                               const char *);
+/*
+ *
+ *     const char *hostname;                   -- hostname
+ *     const rpcprog_t prog;                   -- program number
+ *     const rpcvers_t vers;                   -- version number
+ *     const char *nettype;                    -- network type
+ */
+
+/*
+ * Generic client creation routine. Supported protocols are which belong
+ * to the nettype name space.
+ */
+extern CLIENT *clnt_create_vers(const char *, const rpcprog_t, rpcvers_t *,
+                                    const rpcvers_t, const rpcvers_t,
+                                    const char *);
+/*
+ *     const char *host;               -- hostname
+ *     const rpcprog_t prog;           -- program number
+ *     rpcvers_t *vers_out;            -- servers highest available version
+ *     const rpcvers_t vers_low;       -- low version number
+ *     const rpcvers_t vers_high;      -- high version number
+ *     const char *nettype;            -- network type
+ */
+
+
+/*
+ * Generic client creation routine. It takes a netconfig structure
+ * instead of nettype
+ */
+extern CLIENT *clnt_tp_create(const char *, const rpcprog_t,
+                                  const rpcvers_t, const struct netconfig *);
+/*
+ *     const char *hostname;                   -- hostname
+ *     const rpcprog_t prog;                   -- program number
+ *     const rpcvers_t vers;                   -- version number
+ *     const struct netconfig *netconf;        -- network config structure
+ */
+
+/*
+ * Generic TLI create routine. Only provided for compatibility.
+ */
+
+extern CLIENT *clnt_tli_create(const int, const struct netconfig *,
+                                   const struct netbuf *, const rpcprog_t,
+                                   const rpcvers_t, const u_int, const u_int);
+/*
+ *     const register int fd;          -- fd
+ *     const struct netconfig *nconf;  -- netconfig structure
+ *     const struct netbuf *svcaddr;           -- servers address
+ *     const u_long prog;                      -- program number
+ *     const u_long vers;                      -- version number
+ *     const u_int sendsz;                     -- send size
+ *     const u_int recvsz;                     -- recv size
+ */
+
+/*
+ * Low level clnt create routine for connectionful transports, e.g. tcp.
+ */
+extern CLIENT *clnt_vc_create(const int, const struct netbuf *,
+                                  const rpcprog_t, const rpcvers_t,
+                                  const u_int, const u_int);
+/*
+ *     const int fd;                           -- open file descriptor
+ *     const struct netbuf *svcaddr;           -- servers address
+ *     const rpcprog_t prog;                   -- program number
+ *     const rpcvers_t vers;                   -- version number
+ *     const u_int sendsz;                     -- buffer recv size
+ *     const u_int recvsz;                     -- buffer send size
+ */
+
+/*
+ * Low level clnt create routine for connectionless transports, e.g. udp.
+ */
+extern CLIENT *clnt_dg_create(const int, const struct netbuf *,
+                                  const rpcprog_t, const rpcvers_t,
+                                  const u_int, const u_int);
+/*
+ *     const int fd;                           -- open file descriptor
+ *     const struct netbuf *svcaddr;           -- servers address
+ *     const rpcprog_t program;                -- program number
+ *     const rpcvers_t version;                -- version number
+ *     const u_int sendsz;                     -- buffer recv size
+ *     const u_int recvsz;                     -- buffer send size
+ */
+
+/*
+ * Memory based rpc (for speed check and testing)
+ * CLIENT *
+ * clnt_raw_create(prog, vers)
+ *     u_long prog;
+ *     u_long vers;
+ */
+extern CLIENT *clnt_raw_create (rpcprog_t, rpcvers_t);
+
+__END_DECLS
+
+
+/*
+ * Print why creation failed
+ */
+__BEGIN_DECLS
+extern void clnt_pcreateerror  (const char *);         /* stderr */
+extern char *clnt_spcreateerror        (const char *);         /* string */
+__END_DECLS
+
+/*
+ * Like clnt_perror(), but is more verbose in its output
+ */ 
+__BEGIN_DECLS
+extern void clnt_perrno                (enum clnt_stat);               /* stderr */
+extern char *clnt_sperrno      (enum clnt_stat);               /* string */
+__END_DECLS
+
+/*
+ * Print an English error message, given the client error code
+ */
+__BEGIN_DECLS
+extern void clnt_perror                (CLIENT *, const char *);       /* stderr */
+extern char *clnt_sperror      (CLIENT *, const char *);       /* string */
+__END_DECLS
+
+
+/* 
+ * If a creation fails, the following allows the user to figure out why.
+ */
+struct rpc_createerr {
+       enum clnt_stat cf_stat;
+       struct rpc_err cf_error; /* useful when cf_stat == RPC_PMAPFAILURE */
+};
+
+#ifdef _REENTRANT
+__BEGIN_DECLS
+extern struct rpc_createerr    *__rpc_createerr(void);
+__END_DECLS
+#define rpc_createerr          (*(__rpc_createerr()))
+#else
+extern struct rpc_createerr rpc_createerr;
+#endif /* _REENTRANT */
+
+/*
+ * The simplified interface:
+ * enum clnt_stat
+ * rpc_call(host, prognum, versnum, procnum, inproc, in, outproc, out, nettype)
+ *     const char *host;
+ *     const rpcprog_t prognum;
+ *     const rpcvers_t versnum;
+ *     const rpcproc_t procnum;
+ *     const xdrproc_t inproc, outproc;
+ *     const char *in;
+ *     char *out;
+ *     const char *nettype;
+ */
+__BEGIN_DECLS
+extern enum clnt_stat rpc_call(const char *, const rpcprog_t,
+                                   const rpcvers_t, const rpcproc_t,
+                                   const xdrproc_t, const char *,
+                                   const xdrproc_t, char *, const char *);
+__END_DECLS
+
+/*
+ * RPC broadcast interface
+ * The call is broadcasted to all locally connected nets.
+ *
+ * extern enum clnt_stat
+ * rpc_broadcast(prog, vers, proc, xargs, argsp, xresults, resultsp,
+ *                     eachresult, nettype)
+ *     const rpcprog_t         prog;           -- program number
+ *     const rpcvers_t         vers;           -- version number
+ *     const rpcproc_t         proc;           -- procedure number
+ *     const xdrproc_t xargs;          -- xdr routine for args
+ *     caddr_t         argsp;          -- pointer to args
+ *     const xdrproc_t xresults;       -- xdr routine for results
+ *     caddr_t         resultsp;       -- pointer to results
+ *     const resultproc_t      eachresult;     -- call with each result
+ *     const char              *nettype;       -- Transport type
+ *
+ * For each valid response received, the procedure eachresult is called.
+ * Its form is:
+ *             done = eachresult(resp, raddr, nconf)
+ *                     bool_t done;
+ *                     caddr_t resp;
+ *                     struct netbuf *raddr;
+ *                     struct netconfig *nconf;
+ * where resp points to the results of the call and raddr is the
+ * address if the responder to the broadcast.  nconf is the transport
+ * on which the response was received.
+ *
+ * extern enum clnt_stat
+ * rpc_broadcast_exp(prog, vers, proc, xargs, argsp, xresults, resultsp,
+ *                     eachresult, inittime, waittime, nettype)
+ *     const rpcprog_t         prog;           -- program number
+ *     const rpcvers_t         vers;           -- version number
+ *     const rpcproc_t         proc;           -- procedure number
+ *     const xdrproc_t xargs;          -- xdr routine for args
+ *     caddr_t         argsp;          -- pointer to args
+ *     const xdrproc_t xresults;       -- xdr routine for results
+ *     caddr_t         resultsp;       -- pointer to results
+ *     const resultproc_t      eachresult;     -- call with each result
+ *     const int               inittime;       -- how long to wait initially
+ *     const int               waittime;       -- maximum time to wait
+ *     const char              *nettype;       -- Transport type
+ */
+
+typedef bool_t (*resultproc_t)(caddr_t, ...);
+
+__BEGIN_DECLS
+extern enum clnt_stat rpc_broadcast(const rpcprog_t, const rpcvers_t,
+    const rpcproc_t, const xdrproc_t, const char *, const xdrproc_t, caddr_t,
+    const resultproc_t, const char *);
+extern enum clnt_stat rpc_broadcast_exp(const rpcprog_t, const rpcvers_t,
+    const rpcproc_t, const xdrproc_t, const char *, const xdrproc_t, caddr_t,
+    const resultproc_t, const int, const int, const char *);
+__END_DECLS
+
+/* For backward compatibility */
+#include <rpc/clnt_soc.h>
+
+#endif /* !_RPC_CLNT_H_ */
diff --git a/nbsd_include/rpc/clnt_soc.h b/nbsd_include/rpc/clnt_soc.h
new file mode 100644 (file)
index 0000000..185bb19
--- /dev/null
@@ -0,0 +1,117 @@
+/*     $NetBSD: clnt_soc.h,v 1.3 2005/02/06 04:40:51 perry Exp $       */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1984 - 1991 by Sun Microsystems, Inc.
+ */
+
+/*
+ * clnt.h - Client side remote procedure call interface.
+ */
+
+#ifndef _RPC_CLNT_SOC_H
+#define _RPC_CLNT_SOC_H
+
+/* derived from clnt_soc.h 1.3 88/12/17 SMI     */
+
+/*
+ * All the following declarations are only for backward compatibility
+ * with TS-RPC.
+ */
+
+#include <sys/cdefs.h>
+
+#define UDPMSGSIZE      8800    /* rpc imposed limit on udp msg size */  
+
+/*
+ * TCP based rpc
+ * CLIENT *
+ * clnttcp_create(raddr, prog, vers, sockp, sendsz, recvsz)
+ *     struct sockaddr_in *raddr;
+ *     u_long prog;
+ *     u_long version;
+ *     int *sockp;
+ *     u_int sendsz;
+ *     u_int recvsz;
+ */
+__BEGIN_DECLS
+extern CLIENT *clnttcp_create(struct sockaddr_in *,
+                               u_long,
+                               u_long,
+                               int *,
+                               u_int,
+                               u_int);
+__END_DECLS
+
+/*
+ * Raw (memory) rpc.
+ */
+__BEGIN_DECLS
+extern CLIENT *clntraw_create  (u_long, u_long);
+__END_DECLS
+
+
+/*
+ * UDP based rpc.
+ * CLIENT *
+ * clntudp_create(raddr, program, version, wait, sockp)
+ *     struct sockaddr_in *raddr;
+ *     u_long program;
+ *     u_long version;
+ *     struct timeval wait;
+ *     int *sockp;
+ *
+ * Same as above, but you specify max packet sizes.
+ * CLIENT *
+ * clntudp_bufcreate(raddr, program, version, wait, sockp, sendsz, recvsz)
+ *     struct sockaddr_in *raddr;
+ *     u_long program;
+ *     u_long version;
+ *     struct timeval wait;
+ *     int *sockp;
+ *     u_int sendsz;
+ *     u_int recvsz;
+ */
+__BEGIN_DECLS
+extern CLIENT *clntudp_create(struct sockaddr_in *,
+                               u_long,
+                               u_long,
+                               struct timeval,
+                               int *);
+extern CLIENT *clntudp_bufcreate(struct sockaddr_in *,
+                                    u_long,
+                                    u_long,
+                                    struct timeval,
+                                    int *,
+                                    u_int,
+                                    u_int);
+__END_DECLS
+
+#endif /* _RPC_CLNT_SOC_H */
diff --git a/nbsd_include/rpc/nettype.h b/nbsd_include/rpc/nettype.h
new file mode 100644 (file)
index 0000000..a7859ed
--- /dev/null
@@ -0,0 +1,63 @@
+/*     $NetBSD: nettype.h,v 1.3 2005/02/03 04:39:32 perry Exp $        */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986 - 1991 by Sun Microsystems, Inc.
+ */
+
+/*
+ * nettype.h, Nettype definitions.
+ * All for the topmost layer of rpc
+ *
+ */
+
+#ifndef        _RPC_NETTYPE_H
+#define        _RPC_NETTYPE_H
+
+#include <netconfig.h>
+
+#define        _RPC_NONE       0
+#define        _RPC_NETPATH    1
+#define        _RPC_VISIBLE    2
+#define        _RPC_CIRCUIT_V  3
+#define        _RPC_DATAGRAM_V 4
+#define        _RPC_CIRCUIT_N  5
+#define        _RPC_DATAGRAM_N 6
+#define        _RPC_TCP        7
+#define        _RPC_UDP        8
+
+__BEGIN_DECLS
+extern void *__rpc_setconf(const char *);
+extern void __rpc_endconf(void *);
+extern struct netconfig *__rpc_getconf(void *);
+extern struct netconfig *__rpc_getconfip(const char *);
+__END_DECLS
+
+#endif /* !_RPC_NETTYPE_H */
diff --git a/nbsd_include/rpc/pmap_clnt.h b/nbsd_include/rpc/pmap_clnt.h
new file mode 100644 (file)
index 0000000..a59509c
--- /dev/null
@@ -0,0 +1,88 @@
+/*     $NetBSD: pmap_clnt.h,v 1.11 2009/01/11 03:04:12 christos Exp $  */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ *
+ *     from: @(#)pmap_clnt.h 1.11 88/02/08 SMI 
+ *     @(#)pmap_clnt.h 2.1 88/07/29 4.0 RPCSRC
+ */
+
+/*
+ * pmap_clnt.h
+ * Supplies C routines to get to portmap services.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+/*
+ * Usage:
+ *     success = pmap_set(program, version, protocol, port);
+ *     success = pmap_unset(program, version);
+ *     port = pmap_getport(address, program, version, protocol);
+ *     head = pmap_getmaps(address);
+ *     clnt_stat = pmap_rmtcall(address, program, version, procedure,
+ *             xdrargs, argsp, xdrres, resp, tout, port_ptr)
+ *             (works for udp only.) 
+ *     clnt_stat = clnt_broadcast(program, version, procedure,
+ *             xdrargs, argsp, xdrres, resp, eachresult)
+ *             (like pmap_rmtcall, except the call is broadcasted to all
+ *             locally connected nets.  For each valid response received,
+ *             the procedure eachresult is called.  Its form is:
+ *     done = eachresult(resp, raddr)
+ *             bool_t done;
+ *             caddr_t resp;
+ *             struct sockaddr_in raddr;
+ *             where resp points to the results of the call and raddr is the
+ *             address if the responder to the broadcast.
+ */
+
+#ifndef _RPC_PMAP_CLNT_H_
+#define _RPC_PMAP_CLNT_H_
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+extern bool_t          pmap_set(u_long, u_long, int, int);
+extern bool_t          pmap_unset(u_long, u_long);
+extern struct pmaplist *pmap_getmaps(struct sockaddr_in *);
+#ifndef __LIBC12_SOURCE__
+extern enum clnt_stat  pmap_rmtcall(struct sockaddr_in *,
+                                       u_long, u_long, u_long,
+                                       xdrproc_t, caddr_t,
+                                       xdrproc_t, caddr_t,
+                                       struct timeval, u_long *)
+                                       __RENAME(__pmap_rmtcall50);
+#endif
+extern enum clnt_stat  clnt_broadcast(u_long, u_long, u_long,
+                                       xdrproc_t, char *,
+                                       xdrproc_t, char *,
+                                       resultproc_t);
+extern u_short         pmap_getport(struct sockaddr_in *,
+                                       u_long, u_long, u_int);
+__END_DECLS
+
+#endif /* !_RPC_PMAP_CLNT_H_ */
diff --git a/nbsd_include/rpc/pmap_prot.h b/nbsd_include/rpc/pmap_prot.h
new file mode 100644 (file)
index 0000000..bf80276
--- /dev/null
@@ -0,0 +1,106 @@
+/*     $NetBSD: pmap_prot.h,v 1.9 2005/02/03 04:39:32 perry Exp $      */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ *
+ *     from: @(#)pmap_prot.h 1.14 88/02/08 SMI 
+ *     @(#)pmap_prot.h 2.1 88/07/29 4.0 RPCSRC
+ */
+
+/*
+ * pmap_prot.h
+ * Protocol for the local binder service, or pmap.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ *
+ * The following procedures are supported by the protocol:
+ *
+ * PMAPPROC_NULL() returns ()
+ *     takes nothing, returns nothing
+ *
+ * PMAPPROC_SET(struct pmap) returns (bool_t)
+ *     TRUE is success, FALSE is failure.  Registers the tuple
+ *     [prog, vers, prot, port].
+ *
+ * PMAPPROC_UNSET(struct pmap) returns (bool_t)
+ *     TRUE is success, FALSE is failure.  Un-registers pair
+ *     [prog, vers].  prot and port are ignored.
+ *
+ * PMAPPROC_GETPORT(struct pmap) returns (long unsigned).
+ *     0 is failure.  Otherwise returns the port number where the pair
+ *     [prog, vers] is registered.  It may lie!
+ *
+ * PMAPPROC_DUMP() RETURNS (struct pmaplist *)
+ *
+ * PMAPPROC_CALLIT(unsigned, unsigned, unsigned, string<>)
+ *     RETURNS (port, string<>);
+ * usage: encapsulatedresults = PMAPPROC_CALLIT(prog, vers, proc, encapsulatedargs);
+ *     Calls the procedure on the local machine.  If it is not registered,
+ *     this procedure is quite; ie it does not return error information!!!
+ *     This procedure only is supported on rpc/udp and calls via
+ *     rpc/udp.  This routine only passes null authentication parameters.
+ *     This file has no interface to xdr routines for PMAPPROC_CALLIT.
+ *
+ * The service supports remote procedure calls on udp/ip or tcp/ip socket 111.
+ */
+
+#ifndef _RPC_PMAP_PROT_H_
+#define _RPC_PMAP_PROT_H_
+#include <sys/cdefs.h>
+
+#define PMAPPORT               ((u_short)111)
+#define PMAPPROG               ((u_long)100000)
+#define PMAPVERS               ((u_long)2)
+#define PMAPVERS_PROTO         ((u_long)2)
+#define PMAPVERS_ORIG          ((u_long)1)
+#define PMAPPROC_NULL          ((u_long)0)
+#define PMAPPROC_SET           ((u_long)1)
+#define PMAPPROC_UNSET         ((u_long)2)
+#define PMAPPROC_GETPORT       ((u_long)3)
+#define PMAPPROC_DUMP          ((u_long)4)
+#define PMAPPROC_CALLIT                ((u_long)5)
+
+struct pmap {
+       long unsigned pm_prog;
+       long unsigned pm_vers;
+       long unsigned pm_prot;
+       long unsigned pm_port;
+};
+
+struct pmaplist {
+       struct pmap     pml_map;
+       struct pmaplist *pml_next;
+};
+
+__BEGIN_DECLS
+extern bool_t xdr_pmap         (XDR *, struct pmap *);
+extern bool_t xdr_pmaplist     (XDR *, struct pmaplist **);
+extern bool_t xdr_pmaplist_ptr (XDR *, struct pmaplist *);
+__END_DECLS
+
+#endif /* !_RPC_PMAP_PROT_H_ */
diff --git a/nbsd_include/rpc/pmap_rmt.h b/nbsd_include/rpc/pmap_rmt.h
new file mode 100644 (file)
index 0000000..59a79ca
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: pmap_rmt.h,v 1.9 2005/12/03 15:16:19 yamt Exp $        */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ *
+ *     from: @(#)pmap_rmt.h 1.2 88/02/08 SMI 
+ *     @(#)pmap_rmt.h  2.1 88/07/29 4.0 RPCSRC
+ */
+
+/*
+ * Structures and XDR routines for parameters to and replies from
+ * the portmapper remote-call-service.
+ *
+ * Copyright (C) 1986, Sun Microsystems, Inc.
+ */
+
+#ifndef _RPC_PMAP_RMT_H_
+#define _RPC_PMAP_RMT_H_
+#include <sys/cdefs.h>
+
+struct rmtcallargs {
+       u_long prog, vers, proc, arglen;
+       const char *args_ptr;
+       xdrproc_t xdr_args;
+};
+
+struct rmtcallres {
+       u_long *port_ptr;
+       u_long resultslen;
+       caddr_t results_ptr;
+       xdrproc_t xdr_results;
+};
+
+__BEGIN_DECLS
+extern bool_t xdr_rmtcall_args (XDR *, struct rmtcallargs *);
+extern bool_t xdr_rmtcallres   (XDR *, struct rmtcallres *);
+__END_DECLS
+
+#endif /* !_RPC_PMAP_RMT_H_ */
diff --git a/nbsd_include/rpc/raw.h b/nbsd_include/rpc/raw.h
new file mode 100644 (file)
index 0000000..a049f88
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: raw.h,v 1.1 2000/06/02 22:57:56 fvdl Exp $     */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986 - 1991 by Sun Microsystems, Inc.
+ */
+
+#ifndef _RPC_RAW_H
+#define        _RPC_RAW_H
+
+/* #pragma ident       "@(#)raw.h      1.11    94/04/25 SMI" */
+/*     @(#)raw.h 1.2 88/10/25 SMI      */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * raw.h
+ *
+ * Raw interface
+ * The common memory area over which they will communicate
+ */
+extern char *__rpc_rawcombuf;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _RPC_RAW_H */
diff --git a/nbsd_include/rpc/rpc.h b/nbsd_include/rpc/rpc.h
new file mode 100644 (file)
index 0000000..573e5a0
--- /dev/null
@@ -0,0 +1,108 @@
+/*     $NetBSD: rpc.h,v 1.15 2006/06/22 19:35:34 christos Exp $        */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ *
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ *
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ *
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ *
+ *     from: @(#)rpc.h 1.9 88/02/08 SMI 
+ *     @(#)rpc.h       2.4 89/07/11 4.0 RPCSRC
+ */
+
+/*
+ * rpc.h, Just includes the billions of rpc header files necessary to
+ * do remote procedure calling.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+#ifndef _RPC_RPC_H_
+#define _RPC_RPC_H_
+
+#include <rpc/types.h>         /* some typedefs */
+#include <netinet/in.h>
+
+/* external data representation interfaces */
+#include <rpc/xdr.h>           /* generic (de)serializer */
+
+/* Client side only authentication */
+#include <rpc/auth.h>          /* generic authenticator (client side) */
+
+/* Client side (mostly) remote procedure call */
+#include <rpc/clnt.h>          /* generic rpc stuff */
+
+/* semi-private protocol headers */
+#include <rpc/rpc_msg.h>       /* protocol for rpc messages */
+#include <rpc/auth_unix.h>     /* protocol for unix style cred */
+/*
+ *  Uncomment-out the next line if you are building the rpc library with    
+ *  DES Authentication (see the README file in the secure_rpc/ directory).
+ */
+#ifdef notdef
+#include <rpc/auth_des.h>      /* protocol for des style cred */
+#endif
+
+/* Server side only remote procedure callee */
+#include <rpc/svc.h>           /* service manager and multiplexer */
+#include <rpc/svc_auth.h>      /* service side authenticator */
+
+/* Portmapper client, server, and protocol headers */
+#include <rpc/pmap_clnt.h>
+#include <rpc/pmap_prot.h>
+
+#include <rpc/rpcb_clnt.h>     /* rpcbind interface functions */
+
+#include <rpc/rpcent.h>
+
+__BEGIN_DECLS
+extern int get_myaddress(struct sockaddr_in *);
+extern int bindresvport(int, struct sockaddr_in *);
+extern int registerrpc(int, int, int, char *(*)(char [UDPMSGSIZE]),
+    xdrproc_t, xdrproc_t);
+extern int callrpc(char *, int, int, int, xdrproc_t, char *,
+    xdrproc_t , char *);
+extern int getrpcport(char *, int, int, int);
+
+char *taddr2uaddr(const struct netconfig *, const struct netbuf *);
+struct netbuf *uaddr2taddr(const struct netconfig *, const char *);
+
+struct sockaddr;
+extern int bindresvport_sa(int, struct sockaddr *);
+__END_DECLS
+
+/*
+ * The following are not exported interfaces, they are for internal library
+ * and rpcbind use only. Do not use, they may change without notice.
+ */
+__BEGIN_DECLS
+int __rpc_nconf2fd(const struct netconfig *);
+int __rpc_nconf2sockinfo(const struct netconfig *,
+                             struct __rpc_sockinfo *);
+int __rpc_fd2sockinfo(int, struct __rpc_sockinfo *);
+int __rpc_setnodelay(int, const struct __rpc_sockinfo *);
+u_int __rpc_get_t_size(int, int, int);
+__END_DECLS
+
+#endif /* !_RPC_RPC_H_ */
diff --git a/nbsd_include/rpc/rpc_com.h b/nbsd_include/rpc/rpc_com.h
new file mode 100644 (file)
index 0000000..399f370
--- /dev/null
@@ -0,0 +1,64 @@
+/*     $NetBSD: rpc_com.h,v 1.2 2005/02/03 04:39:32 perry Exp $        */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986 - 1991 by Sun Microsystems, Inc.
+ */
+
+/*
+ * rpc_com.h, Common definitions for both the server and client side.
+ * All for the topmost layer of rpc
+ */
+
+#ifndef _RPC_RPCCOM_H
+#define        _RPC_RPCCOM_H
+
+#include <sys/cdefs.h>
+
+/* #pragma ident       "@(#)rpc_com.h  1.11    93/07/05 SMI" */
+
+/*
+ * The max size of the transport, if the size cannot be determined
+ * by other means.
+ */
+#define        RPC_MAXDATASIZE 9000
+#define        RPC_MAXADDRSIZE 1024
+
+__BEGIN_DECLS
+bool_t rpc_control(int, void *);
+__END_DECLS
+
+/*
+ * Operations for rpc_control().
+ */
+#define RPC_SVC_CONNMAXREC_SET 0       /* set max rec size, enable nonblock */
+#define RPC_SVC_CONNMAXREC_GET 1
+
+#endif /* _RPC_RPCCOM_H */
diff --git a/nbsd_include/rpc/rpc_msg.h b/nbsd_include/rpc/rpc_msg.h
new file mode 100644 (file)
index 0000000..a5ee9d0
--- /dev/null
@@ -0,0 +1,213 @@
+/*     $NetBSD: rpc_msg.h,v 1.15 2006/02/25 00:58:34 wiz Exp $ */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ *
+ *     from: @(#)rpc_msg.h 1.7 86/07/16 SMI
+ *     @(#)rpc_msg.h   2.1 88/07/29 4.0 RPCSRC
+ */
+
+/*
+ * rpc_msg.h
+ * rpc message definition
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#ifndef _RPC_RPC_MSG_H_
+#define _RPC_RPC_MSG_H_
+
+#define RPC_MSG_VERSION                ((uint32_t) 2)
+#define RPC_SERVICE_PORT       ((u_short) 2048)
+
+/*
+ * Bottom up definition of an rpc message.
+ * NOTE: call and reply use the same overall struct but
+ * different parts of unions within it.
+ */
+
+enum msg_type {
+       CALL=0,
+       REPLY=1
+};
+
+enum reply_stat {
+       MSG_ACCEPTED=0,
+       MSG_DENIED=1
+};
+
+enum accept_stat {
+       SUCCESS=0,
+       PROG_UNAVAIL=1,
+       PROG_MISMATCH=2,
+       PROC_UNAVAIL=3,
+       GARBAGE_ARGS=4,
+       SYSTEM_ERR=5
+};
+
+enum reject_stat {
+       RPC_MISMATCH=0,
+       AUTH_ERROR=1
+};
+
+/*
+ * Reply part of an rpc exchange
+ */
+
+/*
+ * Reply to an rpc request that was accepted by the server.
+ * Note: there could be an error even though the request was
+ * accepted.
+ */
+struct accepted_reply {
+       struct opaque_auth      ar_verf;
+       enum accept_stat        ar_stat;
+       union {
+               struct {
+                       rpcvers_t low;
+                       rpcvers_t high;
+               } AR_versions;
+               struct {
+                       const char *where;
+                       xdrproc_t proc;
+               } AR_results;
+               /* and many other null cases */
+       } ru;
+#define        ar_results      ru.AR_results
+#define        ar_vers         ru.AR_versions
+};
+
+/*
+ * Reply to an rpc request that was rejected by the server.
+ */
+struct rejected_reply {
+       enum reject_stat rj_stat;
+       union {
+               struct {
+                       rpcvers_t low;
+                       rpcvers_t high;
+               } RJ_versions;
+               enum auth_stat RJ_why;  /* why authentication did not work */
+       } ru;
+#define        rj_vers ru.RJ_versions
+#define        rj_why  ru.RJ_why
+};
+
+/*
+ * Body of a reply to an rpc request.
+ */
+struct reply_body {
+       enum reply_stat rp_stat;
+       union {
+               struct accepted_reply RP_ar;
+               struct rejected_reply RP_dr;
+       } ru;
+#define        rp_acpt ru.RP_ar
+#define        rp_rjct ru.RP_dr
+};
+
+/*
+ * Body of an rpc request call.
+ */
+struct call_body {
+       rpcvers_t cb_rpcvers;   /* must be equal to two */
+       rpcprog_t cb_prog;
+       rpcvers_t cb_vers;
+       rpcproc_t cb_proc;
+       struct opaque_auth cb_cred;
+       struct opaque_auth cb_verf; /* protocol specific - provided by client */
+};
+
+/*
+ * The rpc message
+ */
+struct rpc_msg {
+       uint32_t                rm_xid;
+       enum msg_type           rm_direction;
+       union {
+               struct call_body RM_cmb;
+               struct reply_body RM_rmb;
+       } ru;
+#define        rm_call         ru.RM_cmb
+#define        rm_reply        ru.RM_rmb
+};
+#define        acpted_rply     ru.RM_rmb.ru.RP_ar
+#define        rjcted_rply     ru.RM_rmb.ru.RP_dr
+
+__BEGIN_DECLS
+/*
+ * XDR routine to handle an rpc message.
+ * xdr_callmsg(xdrs, cmsg)
+ *     XDR *xdrs;
+ *     struct rpc_msg *cmsg;
+ */
+extern bool_t  xdr_callmsg     (XDR *, struct rpc_msg *);
+
+/*
+ * XDR routine to pre-serialize the static part of an rpc message.
+ * xdr_callhdr(xdrs, cmsg)
+ *     XDR *xdrs;
+ *     struct rpc_msg *cmsg;
+ */
+extern bool_t  xdr_callhdr     (XDR *, struct rpc_msg *);
+
+/*
+ * XDR routine to handle an rpc reply.
+ * xdr_replymsg(xdrs, rmsg)
+ *     XDR *xdrs;
+ *     struct rpc_msg *rmsg;
+ */
+extern bool_t  xdr_replymsg    (XDR *, struct rpc_msg *);
+
+
+/*
+ * XDR routine to handle a accepted rpc reply.
+ * xdr_accepted_reply(xdrs, rej)
+ *     XDR *xdrs;
+ *     struct accepted_reply *rej;
+ */
+extern bool_t  xdr_accepted_reply      (XDR *, struct accepted_reply *);
+
+/*
+ * XDR routine to handle a rejected rpc reply.
+ * xdr_rejected_reply(xdrs, rej)
+ *     XDR *xdrs;
+ *     struct rejected_reply *rej;
+ */
+extern bool_t  xdr_rejected_reply      (XDR *, struct rejected_reply *);
+
+/*
+ * Fills in the error part of a reply message.
+ * _seterr_reply(msg, error)
+ *     struct rpc_msg *msg;
+ *     struct rpc_err *error;
+ */
+extern void    _seterr_reply   (struct rpc_msg *, struct rpc_err *);
+__END_DECLS
+
+#endif /* !_RPC_RPC_MSG_H_ */
diff --git a/nbsd_include/rpc/rpcb_clnt.h b/nbsd_include/rpc/rpcb_clnt.h
new file mode 100644 (file)
index 0000000..ad9ae84
--- /dev/null
@@ -0,0 +1,90 @@
+/*     $NetBSD: rpcb_clnt.h,v 1.4 2009/01/11 03:04:12 christos Exp $   */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986 - 1991 by Sun Microsystems, Inc.
+ */
+
+/*
+ * rpcb_clnt.h
+ * Supplies C routines to get to rpcbid services.
+ *
+ */
+
+/*
+ * Usage:
+ *     success = rpcb_set(program, version, nconf, address);
+ *     success = rpcb_unset(program, version, nconf);
+ *     success = rpcb_getaddr(program, version, nconf, host);
+ *     head = rpcb_getmaps(nconf, host);
+ *     clnt_stat = rpcb_rmtcall(nconf, host, program, version, procedure,
+ *             xdrargs, argsp, xdrres, resp, tout, addr_ptr)
+ *     success = rpcb_gettime(host, timep)
+ *     uaddr = rpcb_taddr2uaddr(nconf, taddr);
+ *     taddr = rpcb_uaddr2uaddr(nconf, uaddr);
+ */
+
+#ifndef _RPC_RPCB_CLNT_H
+#define        _RPC_RPCB_CLNT_H
+
+/* #pragma ident       "@(#)rpcb_clnt.h        1.13    94/04/25 SMI" */
+/* rpcb_clnt.h 1.3 88/12/05 SMI */
+
+#include <rpc/types.h>
+#include <rpc/rpcb_prot.h>
+
+__BEGIN_DECLS
+extern bool_t rpcb_set(const rpcprog_t, const rpcvers_t,
+                       const struct netconfig  *, const struct netbuf *);
+extern bool_t rpcb_unset(const rpcprog_t, const rpcvers_t,
+                        const struct netconfig *);
+extern rpcblist        *rpcb_getmaps(const struct netconfig *, const char *);
+#ifndef __LIBC12_SOURCE__
+extern enum clnt_stat rpcb_rmtcall(const struct netconfig *,
+                                  const char *, const rpcprog_t,
+                                  const rpcvers_t, const rpcproc_t,
+                                  const xdrproc_t, const char *,
+                                  const xdrproc_t, caddr_t,
+                                  const struct timeval,
+                                  const struct netbuf *)
+                                  __RENAME(__rpcb_rmtcall50);
+#endif
+extern bool_t rpcb_getaddr(const rpcprog_t, const rpcvers_t,
+                          const struct netconfig *, struct netbuf *,
+                          const  char *);
+#ifndef __LIBC12_SOURCE__
+extern bool_t rpcb_gettime(const char *, time_t *)
+    __RENAME(__rpcb_gettime50);
+#endif
+extern char *rpcb_taddr2uaddr(struct netconfig *, struct netbuf *);
+extern struct netbuf *rpcb_uaddr2taddr(struct netconfig *, char *);
+__END_DECLS
+
+#endif /* !_RPC_RPCB_CLNT_H */
diff --git a/nbsd_include/rpc/rpcb_prot.x b/nbsd_include/rpc/rpcb_prot.x
new file mode 100644 (file)
index 0000000..ac848d0
--- /dev/null
@@ -0,0 +1,559 @@
+%/*
+% * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+% * unrestricted use provided that this legend is included on all tape
+% * media and as a part of the software program in whole or part.  Users
+% * may copy or modify Sun RPC without charge, but are not authorized
+% * to license or distribute it to anyone else except as part of a product or
+% * program developed by the user.
+% *
+% * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+% * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+% * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+% *
+% * Sun RPC is provided with no support and without any obligation on the
+% * part of Sun Microsystems, Inc. to assist in its use, correction,
+% * modification or enhancement.
+% *
+% * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+% * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+% * OR ANY PART THEREOF.
+% *
+% * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+% * or profits or other special, indirect and consequential damages, even if
+% * Sun has been advised of the possibility of such damages.
+% *
+% * Sun Microsystems, Inc.
+% * 2550 Garcia Avenue
+% * Mountain View, California  94043
+% */
+%/*
+% * Copyright (c) 1988 by Sun Microsystems, Inc.
+% */
+
+%/* from rpcb_prot.x */
+
+#ifdef RPC_HDR
+%
+%/* #pragma ident      "@(#)rpcb_prot.x        1.5     94/04/29 SMI" */
+%
+%#ifndef _KERNEL
+%
+#endif
+
+/*
+ * rpcb_prot.x
+ * rpcbind protocol, versions 3 and 4, in RPC Language
+ */
+%
+%/*
+% * The following procedures are supported by the protocol in version 3:
+% *
+% * RPCBPROC_NULL() returns ()
+% *    takes nothing, returns nothing
+% *
+% * RPCBPROC_SET(rpcb) returns (bool_t)
+% *    TRUE is success, FALSE is failure.  Registers the tuple
+% *    [prog, vers, address, owner, netid].
+% *    Finds out owner and netid information on its own.
+% *
+% * RPCBPROC_UNSET(rpcb) returns (bool_t)
+% *    TRUE is success, FALSE is failure.  Un-registers tuple
+% *    [prog, vers, netid].  addresses is ignored.
+% *    If netid is NULL, unregister all.
+% *
+% * RPCBPROC_GETADDR(rpcb) returns (string).
+% *    0 is failure.  Otherwise returns the universal address where the
+% *    triple [prog, vers, netid] is registered.  Ignore address and owner.
+% *
+% * RPCBPROC_DUMP() RETURNS (rpcblist_ptr)
+% *    used to dump the entire rpcbind maps
+% *
+% * RPCBPROC_CALLIT(rpcb_rmtcallargs)
+% *    RETURNS (rpcb_rmtcallres);
+% *    Calls the procedure on the remote machine.  If it is not registered,
+% *    this procedure is quiet; i.e. it does not return error information!!!
+% *    This routine only passes null authentication parameters.
+% *    It has no interface to xdr routines for RPCBPROC_CALLIT.
+% *
+% * RPCBPROC_GETTIME() returns (int).
+% *    Gets the remote machines time
+% *
+% * RPCBPROC_UADDR2TADDR(strint) RETURNS (struct netbuf)
+% *    Returns the netbuf address from universal address.
+% *
+% * RPCBPROC_TADDR2UADDR(struct netbuf) RETURNS (string)
+% *    Returns the universal address from netbuf address.
+% *
+% * END OF RPCBIND VERSION 3 PROCEDURES
+% */
+%/*
+% * Except for RPCBPROC_CALLIT, the procedures above are carried over to
+% * rpcbind version 4.  Those below are added or modified for version 4.
+% * NOTE: RPCBPROC_BCAST HAS THE SAME FUNCTIONALITY AND PROCEDURE NUMBER
+% * AS RPCBPROC_CALLIT.
+% *
+% * RPCBPROC_BCAST(rpcb_rmtcallargs)
+% *    RETURNS (rpcb_rmtcallres);
+% *    Calls the procedure on the remote machine.  If it is not registered,
+% *    this procedure IS quiet; i.e. it DOES NOT return error information!!!
+% *    This routine should be used for broadcasting and nothing else.
+% *
+% * RPCBPROC_GETVERSADDR(rpcb) returns (string).
+% *    0 is failure.  Otherwise returns the universal address where the
+% *    triple [prog, vers, netid] is registered.  Ignore address and owner.
+% *    Same as RPCBPROC_GETADDR except that if the given version number
+% *    is not available, the address is not returned.
+% *
+% * RPCBPROC_INDIRECT(rpcb_rmtcallargs)
+% *    RETURNS (rpcb_rmtcallres);
+% *    Calls the procedure on the remote machine.  If it is not registered,
+% *    this procedure is NOT quiet; i.e. it DOES return error information!!!
+% *    as any normal application would expect.
+% *
+% * RPCBPROC_GETADDRLIST(rpcb) returns (rpcb_entry_list_ptr).
+% *    Same as RPCBPROC_GETADDR except that it returns a list of all the
+% *    addresses registered for the combination (prog, vers) (for all
+% *    transports).
+% *
+% * RPCBPROC_GETSTAT(void) returns (rpcb_stat_byvers)
+% *    Returns the statistics about the kind of requests received by rpcbind.
+% */
+%
+%/*
+% * A mapping of (program, version, network ID) to address
+% */
+struct rpcb {
+       rpcprog_t r_prog;               /* program number */
+       rpcvers_t r_vers;               /* version number */
+       string r_netid<>;               /* network id */
+       string r_addr<>;                /* universal address */
+       string r_owner<>;               /* owner of this service */
+};
+#ifdef RPC_HDR
+%
+%typedef rpcb RPCB;
+%
+#endif
+%
+%/*
+% * A list of mappings
+% *
+% * Below are two definitions for the rpcblist structure.  This is done because
+% * xdr_rpcblist() is specified to take a struct rpcblist **, rather than a
+% * struct rpcblist * that rpcgen would produce.  One version of the rpcblist
+% * structure (actually called rp__list) is used with rpcgen, and the other is
+% * defined only in the header file for compatibility with the specified
+% * interface.
+% */
+
+struct rp__list {
+       rpcb rpcb_map;
+       struct rp__list *rpcb_next;
+};
+
+typedef rp__list *rpcblist_ptr;                /* results of RPCBPROC_DUMP */
+
+#ifdef RPC_HDR
+%
+%typedef struct rp__list rpcblist;
+%typedef struct rp__list RPCBLIST;
+%
+%#ifndef __cplusplus
+%struct rpcblist {
+%      RPCB rpcb_map;
+%      struct rpcblist *rpcb_next;
+%};
+%#endif
+%
+%#ifdef __cplusplus
+%extern "C" {
+%#endif
+%#if __STDC__
+%extern  bool_t xdr_rpcblist(XDR *, rpcblist**);
+%#else /* K&R C */
+%bool_t xdr_rpcblist();
+%#endif
+%#ifdef        __cplusplus
+%}
+%#endif
+%
+#endif
+
+%
+%/*
+% * Arguments of remote calls
+% */
+struct rpcb_rmtcallargs {
+       rpcprog_t prog;                 /* program number */
+       rpcvers_t vers;                 /* version number */
+       rpcproc_t proc;                 /* procedure number */
+       opaque args<>;                  /* argument */
+};
+#ifdef RPC_HDR
+%
+%/*
+% * Client-side only representation of rpcb_rmtcallargs structure.
+% *
+% * The routine that XDRs the rpcb_rmtcallargs structure must deal with the
+% * opaque arguments in the "args" structure.  xdr_rpcb_rmtcallargs() needs to
+% * be passed the XDR routine that knows the args' structure.  This routine
+% * doesn't need to go over-the-wire (and it wouldn't make sense anyway) since
+% * the application being called already knows the args structure.  So we use a
+% * different "XDR" structure on the client side, r_rpcb_rmtcallargs, which
+% * includes the args' XDR routine.
+% */
+%struct r_rpcb_rmtcallargs {
+%      rpcprog_t prog;
+%      rpcvers_t vers;
+%      rpcproc_t proc;
+%      struct {
+%              u_int args_len;
+%              const char *args_val;
+%      } args;
+%      xdrproc_t       xdr_args;       /* encodes args */
+%};
+%
+#endif /* def RPC_HDR */
+%
+%/*
+% * Results of the remote call
+% */
+struct rpcb_rmtcallres {
+       string addr<>;                  /* remote universal address */
+       opaque results<>;               /* result */
+};
+#ifdef RPC_HDR
+%
+%/*
+% * Client-side only representation of rpcb_rmtcallres structure.
+% */
+%struct r_rpcb_rmtcallres {
+%      char *addr;
+%      struct {
+%              u_int32_t results_len;
+%              char *results_val;
+%      } results;
+%      xdrproc_t       xdr_res;        /* decodes results */
+%};
+#endif /* RPC_HDR */
+%
+%/*
+% * rpcb_entry contains a merged address of a service on a particular
+% * transport, plus associated netconfig information.  A list of rpcb_entrys
+% * is returned by RPCBPROC_GETADDRLIST.  See netconfig.h for values used
+% * in r_nc_* fields.
+% */
+struct rpcb_entry {
+       string          r_maddr<>;      /* merged address of service */
+       string          r_nc_netid<>;   /* netid field */
+       unsigned int    r_nc_semantics; /* semantics of transport */
+       string          r_nc_protofmly<>; /* protocol family */
+       string          r_nc_proto<>;   /* protocol name */
+};
+%
+%/*
+% * A list of addresses supported by a service.
+% */
+struct rpcb_entry_list {
+       rpcb_entry rpcb_entry_map;
+       struct rpcb_entry_list *rpcb_entry_next;
+};
+
+typedef rpcb_entry_list *rpcb_entry_list_ptr;
+
+%
+%/*
+% * rpcbind statistics
+% */
+%
+const rpcb_highproc_2 = RPCBPROC_CALLIT;
+const rpcb_highproc_3 = RPCBPROC_TADDR2UADDR;
+const rpcb_highproc_4 = RPCBPROC_GETSTAT;
+
+const RPCBSTAT_HIGHPROC = 13;  /* # of procs in rpcbind V4 plus one */
+const RPCBVERS_STAT = 3;       /* provide only for rpcbind V2, V3 and V4 */
+const RPCBVERS_4_STAT = 2;
+const RPCBVERS_3_STAT = 1;
+const RPCBVERS_2_STAT = 0;
+%
+%/* Link list of all the stats about getport and getaddr */
+struct rpcbs_addrlist {
+       rpcprog_t prog;
+       rpcvers_t vers;
+       int success;
+       int failure;
+       string netid<>;
+       struct rpcbs_addrlist *next;
+};
+%
+%/* Link list of all the stats about rmtcall */
+struct rpcbs_rmtcalllist {
+       rpcprog_t prog;
+       rpcvers_t vers;
+       rpcproc_t proc;
+       int success;
+       int failure;
+       int indirect;   /* whether callit or indirect */
+       string netid<>;
+       struct rpcbs_rmtcalllist *next;
+};
+
+typedef int rpcbs_proc[RPCBSTAT_HIGHPROC];
+typedef rpcbs_addrlist *rpcbs_addrlist_ptr;
+typedef rpcbs_rmtcalllist *rpcbs_rmtcalllist_ptr;
+
+struct rpcb_stat {
+       rpcbs_proc              info;
+       int                     setinfo;
+       int                     unsetinfo;
+       rpcbs_addrlist_ptr      addrinfo;
+       rpcbs_rmtcalllist_ptr   rmtinfo;
+};
+%
+%/*
+% * One rpcb_stat structure is returned for each version of rpcbind
+% * being monitored.
+% */
+
+typedef rpcb_stat rpcb_stat_byvers[RPCBVERS_STAT];
+
+#ifdef RPC_HDR
+%
+%/*
+% * We don't define netbuf in RPCL, since it would contain structure member
+% * names that would conflict with the definition of struct netbuf in
+% * <tiuser.h>.  Instead we merely declare the XDR routine xdr_netbuf() here,
+% * and implement it ourselves in rpc/rpcb_prot.c.
+% */
+%#ifdef __cplusplus
+%extern "C" bool_t xdr_netbuf(XDR *, struct netbuf *);
+%
+%#elif __STDC__
+%extern  bool_t xdr_netbuf(XDR *, struct netbuf *);
+%
+%#else /* K&R C */
+%bool_t xdr_netbuf();
+%
+%#endif /* K&R C*/
+#endif /* def RPC_HDR */
+
+/*
+ * rpcbind procedures
+ */
+program RPCBPROG {
+       version RPCBVERS {
+               bool
+               RPCBPROC_SET(rpcb) = 1;
+
+               bool
+               RPCBPROC_UNSET(rpcb) = 2;
+
+               string
+               RPCBPROC_GETADDR(rpcb) = 3;
+
+               rpcblist_ptr
+               RPCBPROC_DUMP(void) = 4;
+
+               rpcb_rmtcallres
+               RPCBPROC_CALLIT(rpcb_rmtcallargs) = 5;
+
+               unsigned int
+               RPCBPROC_GETTIME(void) = 6;
+
+               struct netbuf
+               RPCBPROC_UADDR2TADDR(string) = 7;
+
+               string
+               RPCBPROC_TADDR2UADDR(struct netbuf) = 8;
+       } = 3;
+
+       version RPCBVERS4 {
+               bool
+               RPCBPROC_SET(rpcb) = 1;
+
+               bool
+               RPCBPROC_UNSET(rpcb) = 2;
+
+               string
+               RPCBPROC_GETADDR(rpcb) = 3;
+
+               rpcblist_ptr
+               RPCBPROC_DUMP(void) = 4;
+
+               /*
+                * NOTE: RPCBPROC_BCAST has the same functionality as CALLIT;
+                * the new name is intended to indicate that this
+                * procedure should be used for broadcast RPC, and
+                * RPCBPROC_INDIRECT should be used for indirect calls.
+                */
+               rpcb_rmtcallres
+               RPCBPROC_BCAST(rpcb_rmtcallargs) = RPCBPROC_CALLIT;
+
+               unsigned int
+               RPCBPROC_GETTIME(void) = 6;
+
+               struct netbuf
+               RPCBPROC_UADDR2TADDR(string) = 7;
+
+               string
+               RPCBPROC_TADDR2UADDR(struct netbuf) = 8;
+
+               string
+               RPCBPROC_GETVERSADDR(rpcb) = 9;
+
+               rpcb_rmtcallres
+               RPCBPROC_INDIRECT(rpcb_rmtcallargs) = 10;
+
+               rpcb_entry_list_ptr
+               RPCBPROC_GETADDRLIST(rpcb) = 11;
+
+               rpcb_stat_byvers
+               RPCBPROC_GETSTAT(void) = 12;
+       } = 4;
+} = 100000;
+#ifdef RPC_HDR
+%
+%#define       RPCBVERS_3              RPCBVERS
+%#define       RPCBVERS_4              RPCBVERS4
+%
+%#define       _PATH_RPCBINDSOCK       "/var/run/rpcbind.sock"
+%
+%#else         /* ifndef _KERNEL */
+%#ifdef __cplusplus
+%extern "C" {
+%#endif
+%
+%/*
+% * A mapping of (program, version, network ID) to address
+% */
+%struct rpcb {
+%      rpcprog_t r_prog;               /* program number */
+%      rpcvers_t r_vers;               /* version number */
+%      char *r_netid;                  /* network id */
+%      char *r_addr;                   /* universal address */
+%      char *r_owner;                  /* owner of the mapping */
+%};
+%typedef struct rpcb RPCB;
+%
+%/*
+% * A list of mappings
+% */
+%struct rpcblist {
+%      RPCB rpcb_map;
+%      struct rpcblist *rpcb_next;
+%};
+%typedef struct rpcblist RPCBLIST;
+%typedef struct rpcblist *rpcblist_ptr;
+%
+%/*
+% * Remote calls arguments
+% */
+%struct rpcb_rmtcallargs {
+%      rpcprog_t prog;                 /* program number */
+%      rpcvers_t vers;                 /* version number */
+%      rpcproc_t proc;                 /* procedure number */
+%      u_int32_t arglen;                       /* arg len */
+%      caddr_t args_ptr;               /* argument */
+%      xdrproc_t xdr_args;             /* XDR routine for argument */
+%};
+%typedef struct rpcb_rmtcallargs rpcb_rmtcallargs;
+%
+%/*
+% * Remote calls results
+% */
+%struct rpcb_rmtcallres {
+%      char *addr_ptr;                 /* remote universal address */
+%      u_int32_t resultslen;           /* results length */
+%      caddr_t results_ptr;            /* results */
+%      xdrproc_t xdr_results;          /* XDR routine for result */
+%};
+%typedef struct rpcb_rmtcallres rpcb_rmtcallres;
+%
+%struct rpcb_entry {
+%      char *r_maddr;
+%      char *r_nc_netid;
+%      unsigned int r_nc_semantics;
+%      char *r_nc_protofmly;
+%      char *r_nc_proto;
+%};
+%typedef struct rpcb_entry rpcb_entry;
+%
+%/*
+% * A list of addresses supported by a service.
+% */
+%
+%struct rpcb_entry_list {
+%      rpcb_entry rpcb_entry_map;
+%      struct rpcb_entry_list *rpcb_entry_next;
+%};
+%typedef struct rpcb_entry_list rpcb_entry_list;
+%
+%typedef rpcb_entry_list *rpcb_entry_list_ptr;
+%
+%/*
+% * rpcbind statistics
+% */
+%
+%#define       rpcb_highproc_2 RPCBPROC_CALLIT
+%#define       rpcb_highproc_3 RPCBPROC_TADDR2UADDR
+%#define       rpcb_highproc_4 RPCBPROC_GETSTAT
+%#define       RPCBSTAT_HIGHPROC 13
+%#define       RPCBVERS_STAT 3
+%#define       RPCBVERS_4_STAT 2
+%#define       RPCBVERS_3_STAT 1
+%#define       RPCBVERS_2_STAT 0
+%
+%/* Link list of all the stats about getport and getaddr */
+%
+%struct rpcbs_addrlist {
+%      rpcprog_t prog;
+%      rpcvers_t vers;
+%      int success;
+%      int failure;
+%      char *netid;
+%      struct rpcbs_addrlist *next;
+%};
+%typedef struct rpcbs_addrlist rpcbs_addrlist;
+%
+%/* Link list of all the stats about rmtcall */
+%
+%struct rpcbs_rmtcalllist {
+%      rpcprog_t prog;
+%      rpcvers_t vers;
+%      rpcproc_t proc;
+%      int success;
+%      int failure;
+%      int indirect;
+%      char *netid;
+%      struct rpcbs_rmtcalllist *next;
+%};
+%typedef struct rpcbs_rmtcalllist rpcbs_rmtcalllist;
+%
+%typedef int rpcbs_proc[RPCBSTAT_HIGHPROC];
+%
+%typedef rpcbs_addrlist *rpcbs_addrlist_ptr;
+%
+%typedef rpcbs_rmtcalllist *rpcbs_rmtcalllist_ptr;
+%
+%struct rpcb_stat {
+%      rpcbs_proc info;
+%      int setinfo;
+%      int unsetinfo;
+%      rpcbs_addrlist_ptr addrinfo;
+%      rpcbs_rmtcalllist_ptr rmtinfo;
+%};
+%typedef struct rpcb_stat rpcb_stat;
+%
+%/*
+% * One rpcb_stat structure is returned for each version of rpcbind
+% * being monitored.
+% */
+%
+%typedef rpcb_stat rpcb_stat_byvers[RPCBVERS_STAT];
+%
+%#ifdef __cplusplus
+%}
+%#endif
+%
+%#endif                /* ifndef _KERNEL */
+#endif         /* RPC_HDR */
diff --git a/nbsd_include/rpc/rpcent.h b/nbsd_include/rpc/rpcent.h
new file mode 100644 (file)
index 0000000..02da3fa
--- /dev/null
@@ -0,0 +1,68 @@
+/*     $NetBSD: rpcent.h,v 1.3 2005/02/03 04:39:32 perry Exp $ */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986 - 1991 by Sun Microsystems, Inc.
+ */
+
+/*
+ * rpcent.h,
+ * For converting rpc program numbers to names etc.
+ *
+ */
+
+#ifndef _RPC_RPCENT_H
+#define _RPC_RPCENT_H
+
+/*     #pragma ident "@(#)rpcent.h   1.13    94/04/25 SMI"     */
+/*      @(#)rpcent.h 1.1 88/12/06 SMI   */
+
+
+struct rpcent {
+      char    *r_name;        /* name of server for this rpc program */
+      char    **r_aliases;    /* alias list */
+      int     r_number;       /* rpc program number */
+};
+
+__BEGIN_DECLS
+extern struct rpcent *getrpcbyname_r(const char *, struct rpcent *,
+                                         char *, int);
+extern struct rpcent *getrpcbynumber_r(int, struct rpcent *, char *, int);
+extern struct rpcent *getrpcent_r(struct rpcent *, char *, int);
+
+/* Old interfaces that return a pointer to a static area;  MT-unsafe */
+extern struct rpcent *getrpcbyname(const char *);
+extern struct rpcent *getrpcbynumber(int);
+extern struct rpcent *getrpcent(void);
+extern void setrpcent(int);
+extern void endrpcent(void);
+__END_DECLS
+
+#endif /* !_RPC_ENT_H_ */
diff --git a/nbsd_include/rpc/svc.h b/nbsd_include/rpc/svc.h
new file mode 100644 (file)
index 0000000..93fb4b0
--- /dev/null
@@ -0,0 +1,420 @@
+/*     $NetBSD: svc.h,v 1.23 2005/12/26 19:01:47 perry Exp $   */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ *
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ *
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ *
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ *
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ *
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ *
+ *     from: @(#)svc.h 1.35 88/12/17 SMI
+ *     @(#)svc.h      1.27    94/04/25 SMI
+ */
+
+/*
+ * svc.h, Server-side remote procedure call interface.
+ *
+ * Copyright (C) 1986-1993 by Sun Microsystems, Inc.
+ */
+
+#ifndef _RPC_SVC_H_
+#define _RPC_SVC_H_
+#include <sys/cdefs.h>
+
+#include <rpc/rpc_com.h>
+
+/*
+ * This interface must manage two items concerning remote procedure calling:
+ *
+ * 1) An arbitrary number of transport connections upon which rpc requests
+ * are received.  The two most notable transports are TCP and UDP;  they are
+ * created and registered by routines in svc_tcp.c and svc_udp.c, respectively;
+ * they in turn call xprt_register and xprt_unregister.
+ *
+ * 2) An arbitrary number of locally registered services.  Services are
+ * described by the following four data: program number, version number,
+ * "service dispatch" function, a transport handle, and a boolean that
+ * indicates whether or not the exported program should be registered with a
+ * local binder service;  if true the program's number and version and the
+ * port number from the transport handle are registered with the binder.
+ * These data are registered with the rpc svc system via svc_register.
+ *
+ * A service's dispatch function is called whenever an rpc request comes in
+ * on a transport.  The request's program and version numbers must match
+ * those of the registered service.  The dispatch function is passed two
+ * parameters, struct svc_req * and SVCXPRT *, defined below.
+ */
+
+/*
+ *     Service control requests
+ */
+#define SVCGET_VERSQUIET       1
+#define SVCSET_VERSQUIET       2
+#define SVCGET_CONNMAXREC      3
+#define SVCSET_CONNMAXREC      4
+
+
+enum xprt_stat {
+       XPRT_DIED,
+       XPRT_MOREREQS,
+       XPRT_IDLE
+};
+
+/*
+ * Server side transport handle
+ */
+typedef struct __rpc_svcxprt {
+       int             xp_fd;
+       u_short         xp_port;         /* associated port number */
+       const struct xp_ops {
+               /* receive incomming requests */
+               bool_t  (*xp_recv)(struct __rpc_svcxprt *, struct rpc_msg *);
+               /* get transport status */
+               enum xprt_stat (*xp_stat)(struct __rpc_svcxprt *);
+               /* get arguments */
+               bool_t  (*xp_getargs)(struct __rpc_svcxprt *, xdrproc_t,
+                           caddr_t);
+               /* send reply */
+               bool_t  (*xp_reply)(struct __rpc_svcxprt *, struct rpc_msg *);
+               /* free mem allocated for args */
+               bool_t  (*xp_freeargs)(struct __rpc_svcxprt *, xdrproc_t,
+                           caddr_t);
+               /* destroy this struct */
+               void    (*xp_destroy)(struct __rpc_svcxprt *);
+       } *xp_ops;
+       int             xp_addrlen;      /* length of remote address */
+       struct sockaddr_in xp_raddr;     /* rem. addr. (backward ABI compat) */
+       /* XXX - fvdl stick this here for ABI backward compat reasons */
+       const struct xp_ops2 {
+               /* catch-all function */
+               bool_t  (*xp_control)(struct __rpc_svcxprt *, const u_int,
+                                          void *);
+       } *xp_ops2;
+       char            *xp_tp;          /* transport provider device name */
+       char            *xp_netid;       /* network token */
+       struct netbuf   xp_ltaddr;       /* local transport address */
+       struct netbuf   xp_rtaddr;       /* remote transport address */
+       struct opaque_auth xp_verf;      /* raw response verifier */
+       void            *xp_p1;          /* private: for use by svc ops */
+       void            *xp_p2;          /* private: for use by svc ops */
+       void            *xp_p3;          /* private: for use by svc lib */
+       int             xp_type;         /* transport type */
+} SVCXPRT;
+
+/*
+ * Service request
+ */
+struct svc_req {
+       uint32_t        rq_prog;        /* service program number */
+       uint32_t        rq_vers;        /* service protocol version */
+       uint32_t        rq_proc;        /* the desired procedure */
+       struct opaque_auth rq_cred;     /* raw creds from the wire */
+       void            *rq_clntcred;   /* read only cooked cred */
+       SVCXPRT         *rq_xprt;       /* associated transport */
+};
+
+/*
+ * Approved way of getting address of caller
+ */
+#define svc_getrpccaller(x) (&(x)->xp_rtaddr)
+
+/*
+ * NetBSD-only definition to get the creds of the caller (AF_LOCAL).
+ */
+#define __svc_getcallercreds(x) ((struct sockcred *)(x)->xp_p2)
+
+/*
+ * Operations defined on an SVCXPRT handle
+ *
+ * SVCXPRT             *xprt;
+ * struct rpc_msg      *msg;
+ * xdrproc_t            xargs;
+ * caddr_t              argsp;
+ */
+#define SVC_RECV(xprt, msg)                            \
+       (*(xprt)->xp_ops->xp_recv)((xprt), (msg))
+#define svc_recv(xprt, msg)                            \
+       (*(xprt)->xp_ops->xp_recv)((xprt), (msg))
+
+#define SVC_STAT(xprt)                                 \
+       (*(xprt)->xp_ops->xp_stat)(xprt)
+#define svc_stat(xprt)                                 \
+       (*(xprt)->xp_ops->xp_stat)(xprt)
+
+#define SVC_GETARGS(xprt, xargs, argsp)                        \
+       (*(xprt)->xp_ops->xp_getargs)((xprt), (xargs), (argsp))
+#define svc_getargs(xprt, xargs, argsp)                        \
+       (*(xprt)->xp_ops->xp_getargs)((xprt), (xargs), (argsp))
+
+#define SVC_REPLY(xprt, msg)                           \
+       (*(xprt)->xp_ops->xp_reply) ((xprt), (msg))
+#define svc_reply(xprt, msg)                           \
+       (*(xprt)->xp_ops->xp_reply) ((xprt), (msg))
+
+#define SVC_FREEARGS(xprt, xargs, argsp)               \
+       (*(xprt)->xp_ops->xp_freeargs)((xprt), (xargs), (argsp))
+#define svc_freeargs(xprt, xargs, argsp)               \
+       (*(xprt)->xp_ops->xp_freeargs)((xprt), (xargs), (argsp))
+
+#define SVC_DESTROY(xprt)                              \
+       (*(xprt)->xp_ops->xp_destroy)(xprt)
+#define svc_destroy(xprt)                              \
+       (*(xprt)->xp_ops->xp_destroy)(xprt)
+
+#define SVC_CONTROL(xprt, rq, in)                      \
+       (*(xprt)->xp_ops2->xp_control)((xprt), (rq), (in))
+
+/*
+ * Service registration
+ *
+ * svc_reg(xprt, prog, vers, dispatch, nconf)
+ *     const SVCXPRT *xprt;
+ *     const rpcprog_t prog;
+ *     const rpcvers_t vers;
+ *     const void (*dispatch)(...);
+ *     const struct netconfig *nconf;
+ */
+
+__BEGIN_DECLS
+extern bool_t  svc_reg(SVCXPRT *, const rpcprog_t, const rpcvers_t,
+                       void (*)(struct svc_req *, SVCXPRT *),
+                       const struct netconfig *);
+__END_DECLS
+
+/*
+ * Service un-registration
+ *
+ * svc_unreg(prog, vers)
+ *     const rpcprog_t prog;
+ *     const rpcvers_t vers;
+ */
+
+__BEGIN_DECLS
+extern void    svc_unreg(const rpcprog_t, const rpcvers_t);
+__END_DECLS
+
+/*
+ * Transport registration.
+ *
+ * xprt_register(xprt)
+ *     SVCXPRT *xprt;
+ */
+__BEGIN_DECLS
+extern void    xprt_register   (SVCXPRT *);
+__END_DECLS
+
+/*
+ * Transport un-register
+ *
+ * xprt_unregister(xprt)
+ *     SVCXPRT *xprt;
+ */
+__BEGIN_DECLS
+extern void    xprt_unregister (SVCXPRT *);
+__END_DECLS
+
+
+/*
+ * When the service routine is called, it must first check to see if it
+ * knows about the procedure;  if not, it should call svcerr_noproc
+ * and return.  If so, it should deserialize its arguments via
+ * SVC_GETARGS (defined above).  If the deserialization does not work,
+ * svcerr_decode should be called followed by a return.  Successful
+ * decoding of the arguments should be followed the execution of the
+ * procedure's code and a call to svc_sendreply.
+ *
+ * Also, if the service refuses to execute the procedure due to too-
+ * weak authentication parameters, svcerr_weakauth should be called.
+ * Note: do not confuse access-control failure with weak authentication!
+ *
+ * NB: In pure implementations of rpc, the caller always waits for a reply
+ * msg.  This message is sent when svc_sendreply is called.
+ * Therefore pure service implementations should always call
+ * svc_sendreply even if the function logically returns void;  use
+ * xdr.h - xdr_void for the xdr routine.  HOWEVER, tcp based rpc allows
+ * for the abuse of pure rpc via batched calling or pipelining.  In the
+ * case of a batched call, svc_sendreply should NOT be called since
+ * this would send a return message, which is what batching tries to avoid.
+ * It is the service/protocol writer's responsibility to know which calls are
+ * batched and which are not.  Warning: responding to batch calls may
+ * deadlock the caller and server processes!
+ */
+
+__BEGIN_DECLS
+extern bool_t  svc_sendreply   (SVCXPRT *, xdrproc_t, const char *);
+extern void    svcerr_decode   (SVCXPRT *);
+extern void    svcerr_weakauth (SVCXPRT *);
+extern void    svcerr_noproc   (SVCXPRT *);
+extern void    svcerr_progvers (SVCXPRT *, rpcvers_t, rpcvers_t);
+extern void    svcerr_auth     (SVCXPRT *, enum auth_stat);
+extern void    svcerr_noprog   (SVCXPRT *);
+extern void    svcerr_systemerr(SVCXPRT *);
+extern int     rpc_reg(rpcprog_t, rpcvers_t, rpcproc_t,
+                            char *(*)(char *), xdrproc_t, xdrproc_t,
+                            char *);
+__END_DECLS
+
+/*
+ * Lowest level dispatching -OR- who owns this process anyway.
+ * Somebody has to wait for incoming requests and then call the correct
+ * service routine.  The routine svc_run does infinite waiting; i.e.,
+ * svc_run never returns.
+ * Since another (co-existent) package may wish to selectively wait for
+ * incoming calls or other events outside of the rpc architecture, the
+ * routine svc_getreq is provided.  It must be passed readfds, the
+ * "in-place" results of a select system call (see select, section 2).
+ */
+
+/*
+ * Global keeper of rpc service descriptors in use
+ * dynamic; must be inspected before each call to select
+ */
+extern int svc_maxfd;
+#ifdef FD_SETSIZE
+extern fd_set svc_fdset;
+#define svc_fds svc_fdset.fds_bits[0]  /* compatibility */
+#else
+extern int svc_fds;
+#endif /* def FD_SETSIZE */
+
+/*
+ * a small program implemented by the svc_rpc implementation itself;
+ * also see clnt.h for protocol numbers.
+ */
+__BEGIN_DECLS
+extern void rpctest_service(void);
+__END_DECLS
+
+__BEGIN_DECLS
+extern void    svc_getreq      (int);
+extern void    svc_getreqset   (fd_set *);
+extern void    svc_getreq_common       (int);
+struct pollfd;
+extern void    svc_getreq_poll(struct pollfd *, int);
+
+extern void    svc_run         (void);
+extern void    svc_exit        (void);
+__END_DECLS
+
+/*
+ * Socket to use on svcxxx_create call to get default socket
+ */
+#define        RPC_ANYSOCK     -1
+#define RPC_ANYFD      RPC_ANYSOCK
+
+/*
+ * These are the existing service side transport implementations
+ */
+
+__BEGIN_DECLS
+/*
+ * Transport independent svc_create routine.
+ */
+extern int svc_create(void (*)(struct svc_req *, SVCXPRT *),
+                          const rpcprog_t, const rpcvers_t, const char *);
+/*
+ *     void (*dispatch)(...);          -- dispatch routine
+ *     const rpcprog_t prognum;        -- program number
+ *     const rpcvers_t versnum;        -- version number
+ *     const char *nettype;            -- network type
+ */
+
+
+/*
+ * Generic server creation routine. It takes a netconfig structure
+ * instead of a nettype.
+ */
+
+extern SVCXPRT *svc_tp_create(void (*)(struct svc_req *, SVCXPRT *),
+                                  const rpcprog_t, const rpcvers_t,
+                                  const struct netconfig *);
+/*
+ *     void (*dispatch)(...);          -- dispatch routine
+ *     const rpcprog_t prognum;        -- program number
+ *     const rpcvers_t versnum;        -- version number
+ *     const struct netconfig *nconf;  -- netconfig structure
+ */
+
+
+/*
+ * Generic TLI create routine
+ */
+extern SVCXPRT *svc_tli_create(const int, const struct netconfig *,
+                                   const struct t_bind *, const u_int,
+                                   const u_int);
+/*
+ *     const int fd;                   -- connection end point
+ *     const struct netconfig *nconf;  -- netconfig structure for network
+ *     const struct t_bind *bindaddr;  -- local bind address
+ *     const u_int sendsz;             -- max sendsize
+ *     const u_int recvsz;             -- max recvsize
+ */
+
+/*
+ * Connectionless and connectionful create routines
+ */
+
+extern SVCXPRT *svc_vc_create(const int, const u_int, const u_int);
+/*
+ *     const int fd;                   -- open connection end point
+ *     const u_int sendsize;           -- max send size
+ *     const u_int recvsize;           -- max recv size
+ */
+
+extern SVCXPRT *svc_dg_create(const int, const u_int, const u_int);
+/*
+ *     const int fd;                   -- open connection
+ *     const u_int sendsize;           -- max send size
+ *     const u_int recvsize;           -- max recv size
+ */
+
+
+/*
+ * the routine takes any *open* connection
+ * descriptor as its first input and is used for open connections.
+ */
+extern SVCXPRT *svc_fd_create(const int, const u_int, const u_int);
+/*
+ *     const int fd;                   -- open connection end point
+ *     const u_int sendsize;           -- max send size
+ *     const u_int recvsize;           -- max recv size
+ */
+
+/*
+ * Memory based rpc (for speed check and testing)
+ */
+extern SVCXPRT *svc_raw_create(void);
+
+/*
+ * svc_dg_enable_cache() enables the cache on dg transports.
+ */
+int svc_dg_enablecache(SVCXPRT *, const u_int);
+
+__END_DECLS
+
+
+/* for backward compatibility */
+#include <rpc/svc_soc.h>
+
+#endif /* !_RPC_SVC_H_ */
diff --git a/nbsd_include/rpc/svc_auth.h b/nbsd_include/rpc/svc_auth.h
new file mode 100644 (file)
index 0000000..8cc85a6
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: svc_auth.h,v 1.9 2005/02/03 04:39:32 perry Exp $       */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ *
+ *     from: @(#)svc_auth.h 1.6 86/07/16 SMI
+ *     @(#)svc_auth.h  2.1 88/07/29 4.0 RPCSRC
+ */
+
+/*
+ * svc_auth.h, Service side of rpc authentication.
+ * 
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#ifndef _RPC_SVC_AUTH_H_
+#define _RPC_SVC_AUTH_H_
+
+/*
+ * Server side authenticator
+ */
+__BEGIN_DECLS
+extern enum auth_stat _authenticate(struct svc_req *, struct rpc_msg *);
+extern int svc_auth_reg(int, enum auth_stat (*)(struct svc_req *,
+                                                         struct rpc_msg *));
+
+__END_DECLS
+
+#endif /* !_RPC_SVC_AUTH_H_ */
diff --git a/nbsd_include/rpc/svc_soc.h b/nbsd_include/rpc/svc_soc.h
new file mode 100644 (file)
index 0000000..ff5e3db
--- /dev/null
@@ -0,0 +1,115 @@
+/*     $NetBSD: svc_soc.h,v 1.2 2005/02/03 04:39:33 perry Exp $        */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+/*
+ * Copyright (c) 1986 - 1991 by Sun Microsystems, Inc.
+ */
+
+/*
+ * svc.h, Server-side remote procedure call interface.
+ */
+
+#ifndef _RPC_SVC_SOC_H
+#define _RPC_SVC_SOC_H
+#include <sys/cdefs.h>
+
+/* #pragma ident   "@(#)svc_soc.h  1.11    94/04/25 SMI" */
+/*      svc_soc.h 1.8 89/05/01 SMI      */
+
+/*
+ * All the following declarations are only for backward compatibility
+ * with TS-RPC
+ */
+
+/*
+ *  Approved way of getting address of caller
+ */
+#define svc_getcaller(x) (&(x)->xp_raddr)
+
+/*
+ * Service registration
+ *
+ * svc_register(xprt, prog, vers, dispatch, protocol)
+ *     SVCXPRT *xprt;
+ *     u_long prog;
+ *     u_long vers;
+ *     void (*dispatch)();
+ *     int protocol;    like TCP or UDP, zero means do not register 
+ */
+__BEGIN_DECLS
+extern bool_t  svc_register(SVCXPRT *, u_long, u_long,
+                   void (*)(struct svc_req *, SVCXPRT *), int);
+__END_DECLS
+
+/*
+ * Service un-registration
+ *
+ * svc_unregister(prog, vers)
+ *     u_long prog;
+ *     u_long vers;
+ */
+__BEGIN_DECLS
+extern void    svc_unregister(u_long, u_long);
+__END_DECLS
+
+
+/*
+ * Memory based rpc for testing and timing.
+ */
+__BEGIN_DECLS
+extern SVCXPRT *svcraw_create(void);
+__END_DECLS
+
+
+/*
+ * Udp based rpc.
+ */
+__BEGIN_DECLS
+extern SVCXPRT *svcudp_create(int);
+extern SVCXPRT *svcudp_bufcreate(int, u_int, u_int);
+extern int svcudp_enablecache(SVCXPRT *, u_long);
+__END_DECLS
+
+
+/*
+ * Tcp based rpc.
+ */
+__BEGIN_DECLS
+extern SVCXPRT *svctcp_create(int, u_int, u_int);
+__END_DECLS
+
+/*
+ * Fd based rpc.
+ */
+__BEGIN_DECLS
+extern SVCXPRT *svcfd_create(int, u_int, u_int);
+__END_DECLS
+
+#endif /* !_RPC_SVC_SOC_H */
diff --git a/nbsd_include/rpc/types.h b/nbsd_include/rpc/types.h
new file mode 100644 (file)
index 0000000..a5fa568
--- /dev/null
@@ -0,0 +1,107 @@
+/*     $NetBSD: types.h,v 1.15 2005/12/26 19:01:47 perry Exp $ */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ *
+ *     from: @(#)types.h 1.18 87/07/24 SMI
+ *     @(#)types.h     2.3 88/08/15 4.0 RPCSRC
+ */
+
+/*
+ * Rpc additions to <sys/types.h>
+ */
+#ifndef _RPC_TYPES_H_
+#define _RPC_TYPES_H_
+
+#include <sys/types.h>
+
+typedef int32_t bool_t;
+typedef int32_t enum_t;
+
+typedef uint32_t rpcprog_t;
+typedef uint32_t rpcvers_t;
+typedef uint32_t rpcproc_t;
+typedef uint32_t rpcprot_t;
+typedef uint32_t rpcport_t;
+typedef   int32_t rpc_inline_t;
+
+#define __dontcare__   -1
+
+#ifndef FALSE
+#      define FALSE    (0)
+#endif
+#ifndef TRUE
+#      define TRUE     (1)
+#endif
+#ifndef NULL
+#      define NULL     0
+#endif
+
+#define mem_alloc(bsize)       calloc((size_t)1, bsize)
+#define mem_free(ptr, bsize)   free(ptr)
+
+#include <sys/time.h>
+#include <netconfig.h>
+
+/*
+ * The netbuf structure is defined here, because NetBSD only uses it inside
+ * the RPC code. It's in <xti.h> on SVR4, but it would be confusing to
+ * have an xti.h, since NetBSD does not support XTI/TLI.
+ */
+
+/*
+ * The netbuf structure is used for transport-independent address storage.
+ */
+struct netbuf {
+       unsigned int maxlen;
+       unsigned int len;
+       void *buf;
+};
+
+/*
+ * The format of the addres and options arguments of the XTI t_bind call.
+ * Only provided for compatibility, it should not be used.
+ */
+
+struct t_bind {
+       struct netbuf   addr;
+       unsigned int    qlen;
+};
+
+/*
+ * Internal library and rpcbind use. This is not an exported interface, do
+ * not use.
+ */
+struct __rpc_sockinfo {
+       int si_af; 
+       int si_proto;
+       int si_socktype;
+       int si_alen;
+};
+
+#endif /* !_RPC_TYPES_H_ */
diff --git a/nbsd_include/rpc/xdr.h b/nbsd_include/rpc/xdr.h
new file mode 100644 (file)
index 0000000..e506f6a
--- /dev/null
@@ -0,0 +1,359 @@
+/*     $NetBSD: xdr.h,v 1.25 2005/12/28 15:26:06 yamt Exp $    */
+
+/*
+ * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
+ * unrestricted use provided that this legend is included on all tape
+ * media and as a part of the software program in whole or part.  Users
+ * may copy or modify Sun RPC without charge, but are not authorized
+ * to license or distribute it to anyone else except as part of a product or
+ * program developed by the user.
+ * 
+ * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
+ * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ * 
+ * Sun RPC is provided with no support and without any obligation on the
+ * part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ * 
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
+ * OR ANY PART THEREOF.
+ * 
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ * 
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ *
+ *     from: @(#)xdr.h 1.19 87/04/22 SMI
+ *     @(#)xdr.h       2.2 88/07/29 4.0 RPCSRC
+ */
+
+/*
+ * xdr.h, External Data Representation Serialization Routines.
+ *
+ * Copyright (C) 1984, Sun Microsystems, Inc.
+ */
+
+#ifndef _RPC_XDR_H_
+#define _RPC_XDR_H_
+#include <sys/cdefs.h>
+
+/*
+ * XDR provides a conventional way for converting between C data
+ * types and an external bit-string representation.  Library supplied
+ * routines provide for the conversion on built-in C data types.  These
+ * routines and utility routines defined here are used to help implement
+ * a type encode/decode routine for each user-defined type.
+ *
+ * Each data type provides a single procedure which takes two arguments:
+ *
+ *     bool_t
+ *     xdrproc(xdrs, argresp)
+ *             XDR *xdrs;
+ *             <type> *argresp;
+ *
+ * xdrs is an instance of a XDR handle, to which or from which the data
+ * type is to be converted.  argresp is a pointer to the structure to be
+ * converted.  The XDR handle contains an operation field which indicates
+ * which of the operations (ENCODE, DECODE * or FREE) is to be performed.
+ *
+ * XDR_DECODE may allocate space if the pointer argresp is null.  This
+ * data can be freed with the XDR_FREE operation.
+ *
+ * We write only one procedure per data type to make it easy
+ * to keep the encode and decode procedures for a data type consistent.
+ * In many cases the same code performs all operations on a user defined type,
+ * because all the hard work is done in the component type routines.
+ * decode as a series of calls on the nested data types.
+ */
+
+/*
+ * Xdr operations.  XDR_ENCODE causes the type to be encoded into the
+ * stream.  XDR_DECODE causes the type to be extracted from the stream.
+ * XDR_FREE can be used to release the space allocated by an XDR_DECODE
+ * request.
+ */
+enum xdr_op {
+       XDR_ENCODE=0,
+       XDR_DECODE=1,
+       XDR_FREE=2
+};
+
+/*
+ * This is the number of bytes per unit of external data.
+ */
+#define BYTES_PER_XDR_UNIT     (4)
+#define RNDUP(x)  ((((x) + BYTES_PER_XDR_UNIT - 1) / BYTES_PER_XDR_UNIT) \
+                   * BYTES_PER_XDR_UNIT)
+
+/*
+ * The XDR handle.
+ * Contains operation which is being applied to the stream,
+ * an operations vector for the paticular implementation (e.g. see xdr_mem.c),
+ * and two private fields for the use of the particular impelementation.
+ */
+typedef struct __rpc_xdr {
+       enum xdr_op     x_op;           /* operation; fast additional param */
+       const struct xdr_ops {
+               /* get a long from underlying stream */
+               bool_t  (*x_getlong)(struct __rpc_xdr *, long *);
+               /* put a long to " */
+               bool_t  (*x_putlong)(struct __rpc_xdr *, const long *);
+               /* get some bytes from " */
+               bool_t  (*x_getbytes)(struct __rpc_xdr *, char *, u_int);
+               /* put some bytes to " */
+               bool_t  (*x_putbytes)(struct __rpc_xdr *, const char *, u_int);
+               /* returns bytes off from beginning */
+               u_int   (*x_getpostn)(struct __rpc_xdr *);
+               /* lets you reposition the stream */
+               bool_t  (*x_setpostn)(struct __rpc_xdr *, u_int);
+               /* buf quick ptr to buffered data */
+               int32_t *(*x_inline)(struct __rpc_xdr *, u_int);
+               /* free privates of this xdr_stream */
+               void    (*x_destroy)(struct __rpc_xdr *);
+               bool_t  (*x_control)(struct __rpc_xdr *, int, void *);
+       } *x_ops;
+       char *          x_public;       /* users' data */
+       void *          x_private;      /* pointer to private data */
+       char *          x_base;         /* private used for position info */
+       u_int           x_handy;        /* extra private word */
+} XDR;
+
+/*
+ * A xdrproc_t exists for each data type which is to be encoded or decoded.
+ *
+ * The second argument to the xdrproc_t is a pointer to an opaque pointer.
+ * The opaque pointer generally points to a structure of the data type
+ * to be decoded.  If this pointer is 0, then the type routines should
+ * allocate dynamic storage of the appropriate size and return it.
+ *
+ * XXX can't actually prototype it, because some take three args!!!
+ */
+typedef        bool_t (*xdrproc_t)(/* XDR *, void *, u_int */);
+
+/*
+ * Operations defined on a XDR handle
+ *
+ * XDR         *xdrs;
+ * long                *longp;
+ * char *       addr;
+ * u_int        len;
+ * u_int        pos;
+ */
+#define XDR_GETLONG(xdrs, longp)                       \
+       (*(xdrs)->x_ops->x_getlong)(xdrs, longp)
+#define xdr_getlong(xdrs, longp)                       \
+       (*(xdrs)->x_ops->x_getlong)(xdrs, longp)
+
+#define XDR_PUTLONG(xdrs, longp)                       \
+       (*(xdrs)->x_ops->x_putlong)(xdrs, longp)
+#define xdr_putlong(xdrs, longp)                       \
+       (*(xdrs)->x_ops->x_putlong)(xdrs, longp)
+
+static __inline int
+xdr_getint32(XDR *xdrs, int32_t *ip)
+{
+       long l;
+
+       if (!xdr_getlong(xdrs, &l))
+               return 0;
+       *ip = (int32_t)l;
+       return 1;
+}
+
+static __inline int
+xdr_putint32(XDR *xdrs, int32_t *ip)
+{
+       long l;
+
+       l = (long)*ip;
+       return xdr_putlong(xdrs, &l);
+}
+
+#define XDR_GETINT32(xdrs, int32p)     xdr_getint32(xdrs, int32p)
+#define XDR_PUTINT32(xdrs, int32p)     xdr_putint32(xdrs, int32p)
+
+#define XDR_GETBYTES(xdrs, addr, len)                  \
+       (*(xdrs)->x_ops->x_getbytes)(xdrs, addr, len)
+#define xdr_getbytes(xdrs, addr, len)                  \
+       (*(xdrs)->x_ops->x_getbytes)(xdrs, addr, len)
+
+#define XDR_PUTBYTES(xdrs, addr, len)                  \
+       (*(xdrs)->x_ops->x_putbytes)(xdrs, addr, len)
+#define xdr_putbytes(xdrs, addr, len)                  \
+       (*(xdrs)->x_ops->x_putbytes)(xdrs, addr, len)
+
+#define XDR_GETPOS(xdrs)                               \
+       (*(xdrs)->x_ops->x_getpostn)(xdrs)
+#define xdr_getpos(xdrs)                               \
+       (*(xdrs)->x_ops->x_getpostn)(xdrs)
+
+#define XDR_SETPOS(xdrs, pos)                          \
+       (*(xdrs)->x_ops->x_setpostn)(xdrs, pos)
+#define xdr_setpos(xdrs, pos)                          \
+       (*(xdrs)->x_ops->x_setpostn)(xdrs, pos)
+
+#define        XDR_INLINE(xdrs, len)                           \
+       (*(xdrs)->x_ops->x_inline)(xdrs, len)
+#define        xdr_inline(xdrs, len)                           \
+       (*(xdrs)->x_ops->x_inline)(xdrs, len)
+
+#define        XDR_DESTROY(xdrs)                               \
+       if ((xdrs)->x_ops->x_destroy)                   \
+               (*(xdrs)->x_ops->x_destroy)(xdrs)
+#define        xdr_destroy(xdrs)                               \
+       if ((xdrs)->x_ops->x_destroy)                   \
+               (*(xdrs)->x_ops->x_destroy)(xdrs)
+
+#define XDR_CONTROL(xdrs, req, op)                     \
+       if ((xdrs)->x_ops->x_control)                   \
+               (*(xdrs)->x_ops->x_control)(xdrs, req, op)
+#define xdr_control(xdrs, req, op) XDR_CONTROL(xdrs, req, op)
+
+/*
+ * Solaris strips the '_t' from these types -- not sure why.
+ * But, let's be compatible.
+ */
+#define xdr_rpcvers(xdrs, versp) xdr_u_int32(xdrs, versp)
+#define xdr_rpcprog(xdrs, progp) xdr_u_int32(xdrs, progp)
+#define xdr_rpcproc(xdrs, procp) xdr_u_int32(xdrs, procp)
+#define xdr_rpcprot(xdrs, protp) xdr_u_int32(xdrs, protp)
+#define xdr_rpcport(xdrs, portp) xdr_u_int32(xdrs, portp)
+
+/*
+ * Support struct for discriminated unions.
+ * You create an array of xdrdiscrim structures, terminated with
+ * a entry with a null procedure pointer.  The xdr_union routine gets
+ * the discriminant value and then searches the array of structures
+ * for a matching value.  If a match is found the associated xdr routine
+ * is called to handle that part of the union.  If there is
+ * no match, then a default routine may be called.
+ * If there is no match and no default routine it is an error.
+ */
+#define NULL_xdrproc_t ((xdrproc_t)0)
+struct xdr_discrim {
+       int     value;
+       xdrproc_t proc;
+};
+
+/*
+ * In-line routines for fast encode/decode of primitive data types.
+ * Caveat emptor: these use single memory cycles to get the
+ * data from the underlying buffer, and will fail to operate
+ * properly if the data is not aligned.  The standard way to use these
+ * is to say:
+ *     if ((buf = XDR_INLINE(xdrs, count)) == NULL)
+ *             return (0);
+ *     <<< macro calls >>>
+ * where ``count'' is the number of bytes of data occupied
+ * by the primitive data types.
+ *
+ * N.B. and frozen for all time: each data type here uses 4 bytes
+ * of external representation.
+ */
+#define IXDR_GET_INT32(buf)            ((int32_t)ntohl((uint32_t)*(buf)++))
+#define IXDR_PUT_INT32(buf, v)         (*(buf)++ =(int32_t)htonl((uint32_t)v))
+#define IXDR_GET_U_INT32(buf)          ((uint32_t)IXDR_GET_INT32(buf))
+#define IXDR_PUT_U_INT32(buf, v)       IXDR_PUT_INT32((buf), ((int32_t)(v)))
+
+#define IXDR_GET_LONG(buf)             ((long)ntohl((uint32_t)*(buf)++))
+#define IXDR_PUT_LONG(buf, v)          (*(buf)++ =(int32_t)htonl((uint32_t)v))
+
+#define IXDR_GET_BOOL(buf)             ((bool_t)IXDR_GET_LONG(buf))
+#define IXDR_GET_ENUM(buf, t)          ((t)IXDR_GET_LONG(buf))
+#define IXDR_GET_U_LONG(buf)           ((u_long)IXDR_GET_LONG(buf))
+#define IXDR_GET_SHORT(buf)            ((short)IXDR_GET_LONG(buf))
+#define IXDR_GET_U_SHORT(buf)          ((u_short)IXDR_GET_LONG(buf))
+
+#define IXDR_PUT_BOOL(buf, v)          IXDR_PUT_LONG((buf), (v))
+#define IXDR_PUT_ENUM(buf, v)          IXDR_PUT_LONG((buf), (v))
+#define IXDR_PUT_U_LONG(buf, v)                IXDR_PUT_LONG((buf), (v))
+#define IXDR_PUT_SHORT(buf, v)         IXDR_PUT_LONG((buf), (v))
+#define IXDR_PUT_U_SHORT(buf, v)       IXDR_PUT_LONG((buf), (v))
+
+/*
+ * These are the "generic" xdr routines.
+ */
+__BEGIN_DECLS
+extern bool_t  xdr_void(void);
+extern bool_t  xdr_int(XDR *, int *);
+extern bool_t  xdr_u_int(XDR *, u_int *);
+extern bool_t  xdr_long(XDR *, long *);
+extern bool_t  xdr_u_long(XDR *, u_long *);
+extern bool_t  xdr_short(XDR *, short *);
+extern bool_t  xdr_u_short(XDR *, u_short *);
+extern bool_t  xdr_int16_t(XDR *, int16_t *);
+extern bool_t  xdr_u_int16_t(XDR *, uint16_t *);
+extern bool_t  xdr_int32_t(XDR *, int32_t *);
+extern bool_t  xdr_u_int32_t(XDR *, uint32_t *);
+extern bool_t  xdr_int64_t(XDR *, int64_t *);
+extern bool_t  xdr_u_int64_t(XDR *, uint64_t *);
+extern bool_t  xdr_bool(XDR *, bool_t *);
+extern bool_t  xdr_enum(XDR *, enum_t *);
+extern bool_t  xdr_array(XDR *, char **, u_int *, u_int, u_int, xdrproc_t);
+extern bool_t  xdr_bytes(XDR *, char **, u_int *, u_int);
+extern bool_t  xdr_opaque(XDR *, char *, u_int);
+extern bool_t  xdr_string(XDR *, char **, u_int);
+extern bool_t  xdr_union(XDR *, enum_t *, char *, const struct xdr_discrim *, xdrproc_t);
+extern bool_t  xdr_char(XDR *, char *);
+extern bool_t  xdr_u_char(XDR *, u_char *);
+extern bool_t  xdr_vector(XDR *, char *, u_int, u_int, xdrproc_t);
+extern bool_t  xdr_float(XDR *, float *);
+extern bool_t  xdr_double(XDR *, double *);
+extern bool_t  xdr_quadruple(XDR *, long double *);
+extern bool_t  xdr_reference(XDR *, char **, u_int, xdrproc_t);
+extern bool_t  xdr_pointer(XDR *, char **, u_int, xdrproc_t);
+extern bool_t  xdr_wrapstring(XDR *, char **);
+extern void    xdr_free(xdrproc_t, char *);
+extern bool_t  xdr_hyper(XDR *, longlong_t *);
+extern bool_t  xdr_u_hyper(XDR *, u_longlong_t *);
+extern bool_t  xdr_longlong_t(XDR *, longlong_t *);
+extern bool_t  xdr_u_longlong_t(XDR *, u_longlong_t *);
+__END_DECLS
+
+/*
+ * Common opaque bytes objects used by many rpc protocols;
+ * declared here due to commonality.
+ */
+#define MAX_NETOBJ_SZ 1024 
+struct netobj {
+       u_int   n_len;
+       char    *n_bytes;
+};
+typedef struct netobj netobj;
+extern bool_t   xdr_netobj(XDR *, struct netobj *);
+
+/*
+ * These are the public routines for the various implementations of
+ * xdr streams.
+ */
+__BEGIN_DECLS
+/* XDR using memory buffers */
+extern void   xdrmem_create(XDR *, char *, u_int, enum xdr_op);
+
+/* XDR using stdio library */
+#ifdef _STDIO_H_
+extern void   xdrstdio_create(XDR *, FILE *, enum xdr_op);
+#endif
+
+/* XDR pseudo records for tcp */
+extern void   xdrrec_create(XDR *, u_int, u_int, char *,
+                               int (*)(char *, char *, int),
+                               int (*)(char *, char *, int));
+
+/* make end of xdr record */
+extern bool_t xdrrec_endofrecord(XDR *, int);
+
+/* move to beginning of next record */
+extern bool_t xdrrec_skiprecord(XDR *);
+
+/* true if no more input */
+extern bool_t xdrrec_eof(XDR *);
+extern u_int xdrrec_readbytes(XDR *, caddr_t, u_int);
+__END_DECLS
+
+#endif /* !_RPC_XDR_H_ */
diff --git a/nbsd_include/rpcsvc/yp_prot.h b/nbsd_include/rpcsvc/yp_prot.h
new file mode 100644 (file)
index 0000000..5cd56cb
--- /dev/null
@@ -0,0 +1,330 @@
+/*     $NetBSD: yp_prot.h,v 1.17 2007/10/06 16:17:34 yamt Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca>
+ * 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 ``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 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 _RPCSVC_YP_PROT_H_
+#define _RPCSVC_YP_PROT_H_
+
+/*
+ * YPSERV PROTOCOL:
+ * 
+ * ypserv supports the following procedures:
+ * 
+ * YPPROC_NULL         takes (void), returns (void).
+ *                     called to check if server is alive.
+ * YPPROC_DOMAIN       takes (char *), returns (bool_t).
+ *                     true if ypserv serves the named domain.
+ * YPPROC_DOMAIN_NOACK takes (char *), returns (bool_t).
+ *                     true if ypserv serves the named domain.
+ *                     used for broadcasts, does not ack if ypserv
+ *                     doesn't handle named domain.
+ * YPPROC_MATCH                takes (struct ypreq_key), returns (struct ypresp_val)
+ *                     does a lookup.
+ * YPPROC_FIRST                takes (struct ypreq_nokey) returns (ypresp_key_val).
+ *                     gets the first key/datum from the map.
+ * YPPROC_NEXT         takes (struct ypreq_key) returns (ypresp_key_val).
+ *                     gets the next key/datum from the map.
+ * YPPROC_XFR          takes (struct ypreq_xfr), returns (void).
+ *                     tells ypserv to check if there is a new version of
+ *                     the map.
+ * YPPROC_CLEAR                takes (void), returns (void).
+ *                     tells ypserv to flush its file cache, so that
+ *                     newly transferred files will get read.
+ * YPPROC_ALL          takes (struct ypreq_nokey), returns (bool_t and
+ *                     struct ypresp_key_val).
+ *                     returns an array of data, with the bool_t being
+ *                     false on the last datum. read the source, it's
+ *                     convoluted.
+ * YPPROC_MASTER       takes (struct ypreq_nokey), returns (ypresp_master).
+ * YPPROC_ORDER                takes (struct ypreq_nokey), returns (ypresp_order).
+ * YPPROC_MAPLIST      takes (char *), returns (struct ypmaplist *).
+ */
+
+/* Program and version symbols, magic numbers */
+#define YPPROG         ((unsigned long)100004)
+#define YPVERS         ((unsigned long)2)
+#define YPVERS_ORIG    ((unsigned long)1)
+
+#define YPMAXRECORD    1024
+#define YPMAXDOMAIN    64
+#define YPMAXMAP       64
+#define YPMAXPEER      256
+
+/*
+ * I don't know if anything of sun's depends on this, or if they
+ * simply defined it so that their own code wouldn't try to send
+ * packets over the ethernet MTU. This YP code doesn't use it.
+ */
+#define YPMSGSZ                1600
+
+#ifndef DATUM
+typedef struct {
+       const char      *dptr;
+       int              dsize;
+} datum;
+#define DATUM
+#endif
+
+struct ypmap_parms {
+       const char *domain;
+       const char *map;
+       unsigned int ordernum;
+       char *owner;
+};
+
+struct ypreq_key {
+       const char *domain;
+       const char *map;
+       datum keydat;
+};
+
+struct ypreq_nokey {
+       const char *domain;
+       const char *map;
+};
+
+struct ypreq_xfr {
+       struct ypmap_parms map_parms;
+       unsigned int transid;
+       unsigned int proto;
+       unsigned int port;
+};
+#define ypxfr_domain   map_parms.domain
+#define ypxfr_map      map_parms.map
+#define ypxfr_ordernum map_parms.ordernum
+#define ypxfr_owner    map_parms.owner
+
+struct ypresp_val {
+       unsigned int status;
+       datum valdat;
+};
+
+struct ypresp_key_val {
+       unsigned int status;
+       datum keydat;
+       datum valdat;
+};
+
+struct ypresp_master {
+       unsigned int status;
+       char *master;
+};
+
+struct ypresp_order {
+       unsigned int status;
+       unsigned int ordernum;
+};
+
+struct ypmaplist {
+       char ypml_name[YPMAXMAP + 1];
+       struct ypmaplist *ypml_next;
+};
+
+struct ypresp_maplist {
+       unsigned int status;
+       struct ypmaplist *list;
+};
+
+/* ypserv procedure numbers */
+#define YPPROC_NULL            ((unsigned long)0)
+#define YPPROC_DOMAIN          ((unsigned long)1)
+#define YPPROC_DOMAIN_NONACK   ((unsigned long)2)
+#define YPPROC_MATCH           ((unsigned long)3)
+#define YPPROC_FIRST           ((unsigned long)4)
+#define YPPROC_NEXT            ((unsigned long)5)
+#define YPPROC_XFR             ((unsigned long)6)
+#define YPPROC_CLEAR           ((unsigned long)7)
+#define YPPROC_ALL             ((unsigned long)8)
+#define YPPROC_MASTER          ((unsigned long)9)
+#define YPPROC_ORDER           ((unsigned long)10)
+#define YPPROC_MAPLIST         ((unsigned long)11)
+
+/* ypserv procedure return status values */
+#define YP_TRUE                ((unsigned int)1)       /* general purpose success code */
+#define YP_NOMORE      ((unsigned int)2)       /* no more entries in map */
+#define YP_FALSE       ((unsigned int)0)       /* general purpose failure code */
+#define YP_NOMAP       ((unsigned int)-1)      /* no such map in domain */
+#define YP_NODOM       ((unsigned int)-2)      /* domain not supported */
+#define YP_NOKEY       ((unsigned int)-3)      /* no such key in map */
+#define YP_BADOP       ((unsigned int)-4)      /* invalid operation */
+#define YP_BADDB       ((unsigned int)-5)      /* server data base is bad */
+#define YP_YPERR       ((unsigned int)-6)      /* YP server error */
+#define YP_BADARGS     ((unsigned int)-7)      /* request arguments bad */
+#define YP_VERS                ((unsigned int)-8)      /* YP server version mismatch */
+
+/*
+ * Sun's header file says:
+ * "Domain binding data structure, used by ypclnt package and ypserv modules.
+ * Users of the ypclnt package (or of this protocol) don't HAVE to know about
+ * it, but it must be available to users because _yp_dobind is a public
+ * interface."
+ * 
+ * This is totally bogus! Nowhere else does Sun state that _yp_dobind() is
+ * a public interface, and I don't know any reason anyone would want to call
+ * it. But, just in case anyone does actually expect it to be available..
+ * we provide this.. exactly as Sun wants it.
+ */
+struct dom_binding {
+       struct dom_binding *dom_pnext;
+       char dom_domain[YPMAXDOMAIN + 1];
+       struct sockaddr_in dom_server_addr;
+       u_short dom_server_port;
+       int dom_socket;
+       CLIENT *dom_client;
+       u_short dom_local_port;
+       long dom_vers;
+};
+
+/*
+ * YPBIND PROTOCOL:
+ * 
+ * ypbind supports the following procedures:
+ *
+ * YPBINDPROC_NULL     takes (void), returns (void).
+ *                     to check if ypbind is running.
+ * YPBINDPROC_DOMAIN   takes (char *), returns (struct ypbind_resp).
+ *                     requests that ypbind start to serve the
+ *                     named domain (if it doesn't already)
+ * YPBINDPROC_SETDOM   takes (struct ypbind_setdom), returns (void).
+ *                     used by ypset.
+ */
+#define YPBINDPROG             ((unsigned long)100007)
+#define YPBINDVERS             ((unsigned long)2)
+#define YPBINDVERS_ORIG                ((unsigned long)1)
+
+/* ypbind procedure numbers */
+#define YPBINDPROC_NULL                ((unsigned long)0)
+#define YPBINDPROC_DOMAIN      ((unsigned long)1)
+#define YPBINDPROC_SETDOM      ((unsigned long)2)
+
+/* error code in ypbind_resp.ypbind_status */
+enum ypbind_resptype {
+       YPBIND_SUCC_VAL = 1,
+       YPBIND_FAIL_VAL = 2
+};
+
+/* network order, of course */
+struct ypbind_binding {
+       struct in_addr  ypbind_binding_addr;
+       uint16_t        ypbind_binding_port;
+};
+
+struct ypbind_resp {
+       enum ypbind_resptype    ypbind_status;
+       union {
+               unsigned int            ypbind_error;
+               struct ypbind_binding   ypbind_bindinfo;
+       } ypbind_respbody;
+};
+
+/* error code in ypbind_resp.ypbind_respbody.ypbind_error */
+#define YPBIND_ERR_ERR         1       /* internal error */
+#define YPBIND_ERR_NOSERV      2       /* no bound server for passed domain */
+#define YPBIND_ERR_RESC                3       /* system resource allocation failure */
+
+/*
+ * Request data structure for ypbind "Set domain" procedure.
+ */
+struct ypbind_setdom {
+       char ypsetdom_domain[YPMAXDOMAIN + 1];
+       struct ypbind_binding ypsetdom_binding;
+       unsigned int ypsetdom_vers;
+};
+#define ypsetdom_addr ypsetdom_binding.ypbind_binding_addr
+#define ypsetdom_port ypsetdom_binding.ypbind_binding_port
+
+/*
+ * YPPUSH PROTOCOL:
+ * 
+ * Sun says:
+ * "Protocol between clients (ypxfr, only) and yppush
+ *  yppush speaks a protocol in the transient range, which
+ *  is supplied to ypxfr as a command-line parameter when it
+ *  is activated by ypserv."
+ * 
+ * This protocol is not implimented, naturally, because this YP
+ * implimentation only does the client side.
+ */
+#define YPPUSHVERS             ((unsigned long)1)
+#define YPPUSHVERS_ORIG                ((unsigned long)1)
+
+/* yppush procedure numbers */
+#define YPPUSHPROC_NULL                ((unsigned long)0)
+#define YPPUSHPROC_XFRRESP     ((unsigned long)1)
+
+struct yppushresp_xfr {
+       unsigned int    transid;
+       unsigned int    status;
+};
+
+/* yppush status value in yppushresp_xfr.status */
+#define YPPUSH_SUCC    ((unsigned int)1)       /* Success */
+#define YPPUSH_AGE     ((unsigned int)2)       /* Master's version not newer */
+#define YPPUSH_NOMAP   ((unsigned int)-1)      /* Can't find server for map */
+#define YPPUSH_NODOM   ((unsigned int)-2)      /* Domain not supported */
+#define YPPUSH_RSRC    ((unsigned int)-3)      /* Local resouce alloc failure */
+#define YPPUSH_RPC     ((unsigned int)-4)      /* RPC failure talking to server */
+#define YPPUSH_MADDR   ((unsigned int)-5)      /* Can't get master address */
+#define YPPUSH_YPERR   ((unsigned int)-6)      /* YP server/map db error */
+#define YPPUSH_BADARGS         ((unsigned int)-7)      /* Request arguments bad */
+#define YPPUSH_DBM     ((unsigned int)-8)      /* Local dbm operation failed */
+#define YPPUSH_FILE    ((unsigned int)-9)      /* Local file I/O operation failed */
+#define YPPUSH_SKEW    ((unsigned int)-10)     /* Map version skew during transfer */
+#define YPPUSH_CLEAR   ((unsigned int)-11)     /* Can't send "Clear" req to local ypserv */
+#define YPPUSH_FORCE   ((unsigned int)-12)     /* No local order number in map - use -f */
+#define YPPUSH_XFRERR  ((unsigned int)-13)     /* ypxfr error */
+#define YPPUSH_REFUSED ((unsigned int)-14)     /* Transfer request refused by ypserv */
+
+struct ypall_callback;
+
+__BEGIN_DECLS
+bool_t xdr_domainname(XDR *, char *);  /* obsolete */
+bool_t xdr_peername(XDR *, char *);    /* obsolete */
+bool_t xdr_mapname(XDR *, char *);     /* obsolete */
+bool_t xdr_datum(XDR *, datum *);
+bool_t xdr_ypdomain_wrap_string(XDR *, char **);
+bool_t xdr_ypmap_wrap_string(XDR *, char **);
+bool_t xdr_ypreq_key(XDR *, struct ypreq_key *);
+bool_t xdr_ypreq_nokey(XDR *, struct ypreq_nokey *);
+bool_t xdr_ypreq_xfr(XDR *, struct ypreq_xfr *);
+bool_t xdr_ypresp_val(XDR *, struct ypresp_val *);
+bool_t xdr_ypresp_key_val(XDR *, struct ypresp_key_val *);
+bool_t xdr_ypmap_parms(XDR *, struct ypmap_parms *);
+bool_t xdr_ypowner_wrap_string(XDR *, char **);
+bool_t xdr_yppushresp_xfr(XDR *, struct yppushresp_xfr *);
+bool_t xdr_ypresp_order(XDR *, struct ypresp_order *);
+bool_t xdr_ypresp_master(XDR *, struct ypresp_master *);
+bool_t xdr_ypall(XDR *, struct ypall_callback *);
+bool_t xdr_ypresp_maplist(XDR *, struct ypresp_maplist *);
+bool_t xdr_ypbind_resp(XDR *, struct ypbind_resp *);
+bool_t xdr_ypbind_setdom(XDR *, struct ypbind_setdom *);
+bool_t xdr_ypmaplist(XDR *, struct ypmaplist *);
+bool_t xdr_yp_inaddr(XDR *, struct in_addr *);
+__END_DECLS
+
+#endif /* _RPCSVC_YP_PROT_H_ */
diff --git a/nbsd_include/rpcsvc/ypclnt.h b/nbsd_include/rpcsvc/ypclnt.h
new file mode 100644 (file)
index 0000000..4a20db4
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: ypclnt.h,v 1.13 2005/02/03 04:39:33 perry Exp $        */
+
+/*
+ * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca>
+ * 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 ``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 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 _RPCSVC_YPCLNT_H_
+#define _RPCSVC_YPCLNT_H_
+
+#define YPERR_BADARGS  1               /* args to function are bad */
+#define YPERR_RPC      2               /* RPC failure */
+#define YPERR_DOMAIN   3               /* can't bind to a server for domain */
+#define YPERR_MAP      4               /* no such map in server's domain */
+#define YPERR_KEY      5               /* no such key in map */
+#define YPERR_YPERR    6               /* some internal YP server or client error */
+#define YPERR_RESRC    7               /* local resource allocation failure */
+#define YPERR_NOMORE   8               /* no more records in map database */
+#define YPERR_PMAP     9               /* can't communicate with portmapper */
+#define YPERR_YPBIND   10              /* can't communicate with ypbind */
+#define YPERR_YPSERV   11              /* can't communicate with ypserv */
+#define YPERR_NODOM    12              /* local domain name not set */
+#define YPERR_BADDB    13              /* YP data base is bad */
+#define YPERR_VERS     14              /* YP version mismatch */
+#define YPERR_ACCESS   15              /* access violation */
+#define YPERR_BUSY     16              /* database is busy */
+
+/*
+ * Types of update operations
+ */
+#define YPOP_CHANGE    1               /* change, do not add */
+#define YPOP_INSERT    2               /* add, do not change */
+#define YPOP_DELETE    3               /* delete this entry */
+#define YPOP_STORE     4               /* add, or change */
+struct ypall_callback {
+       /* return non-0 to stop getting called */
+       int (*foreach)(int, char *, int, char *, int, char *);
+       char *data;             /* opaque pointer for use of callback fn */
+};
+
+__BEGIN_DECLS
+int    yp_bind         (const char *);
+struct dom_binding;
+int    _yp_dobind      (const char *, struct dom_binding **);
+int    _yp_check       (char **);
+void   yp_unbind       (const char *);
+int    yp_get_default_domain(char **);
+struct ypmaplist;
+int    yp_maplist      (const char *, struct ypmaplist **);
+int    yp_match        (const char *, const char *, const char *,
+                            int , char **, int *);
+int    yp_first        (const char *, const char *, char **, int *,
+                            char **, int *);
+int    yp_next         (const char *, const char *, const char *,
+                            int, char **, int *, char **, int *);
+int    yp_master       (const char *, const char *, char **);
+int    yp_order        (const char *, const char *, int *);
+int    yp_all          (const char *, const char *, struct ypall_callback *);
+char * yperr_string    (int);
+int    ypprot_err      (unsigned int);
+__END_DECLS
+
+#endif /* _RPCSVC_YPCLNT_H_ */
diff --git a/nbsd_include/sa.h b/nbsd_include/sa.h
new file mode 100644 (file)
index 0000000..89700ab
--- /dev/null
@@ -0,0 +1,51 @@
+/*     $NetBSD: sa.h,v 1.6 2008/04/28 20:22:54 martin Exp $    */
+
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Nathan Williams.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _SA_H_
+#define _SA_H_
+
+#include <sys/cdefs.h>
+#include <sys/types.h>
+#include <sys/ucontext.h>
+#include <sys/sa.h>
+
+
+__BEGIN_DECLS
+int    sa_register(sa_upcall_t, sa_upcall_t *, int, ssize_t);
+int    sa_stacks(int, stack_t *);
+size_t sa_getstacksize(void);
+int    sa_enable(void);
+int    sa_setconcurrency(int);
+int    sa_yield(void);
+int    sa_preempt(int);
+__END_DECLS
+
+#endif /* !_SA_H_ */
diff --git a/nbsd_include/sched.h b/nbsd_include/sched.h
new file mode 100644 (file)
index 0000000..0a3e423
--- /dev/null
@@ -0,0 +1,78 @@
+/*     $NetBSD: sched.h,v 1.12 2009/01/11 03:04:12 christos Exp $      */
+
+/*-
+ * Copyright (c) 2001 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Nathan J. Williams.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _SCHED_H_
+#define _SCHED_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <sys/sched.h>
+
+/* Required by POSIX 1003.1, section 13.1, lines 12-13. */
+#include <time.h>
+
+__BEGIN_DECLS
+int    sched_setparam(pid_t, const struct sched_param *);
+int    sched_getparam(pid_t, struct sched_param *);
+int    sched_setscheduler(pid_t, int, const struct sched_param *);
+int    sched_getscheduler(pid_t);
+int    sched_get_priority_max(int);
+int    sched_get_priority_min(int);
+#ifndef __LIBC12_SOURCE__
+int    sched_rr_get_interval(pid_t, struct timespec *)
+    __RENAME(__sched_rr_get_interval50);
+#endif
+
+int    sched_yield(void);
+int    __libc_thr_yield(void);
+__END_DECLS
+
+#ifndef __LIBPTHREAD_SOURCE__
+#define sched_yield            __libc_thr_yield
+#endif /* __LIBPTHREAD_SOURCE__ */
+
+#if defined(_NETBSD_SOURCE)
+
+__BEGIN_DECLS
+
+/* Process affinity functions (not portable) */
+int    sched_getaffinity_np(pid_t, size_t, cpuset_t *);
+int    sched_setaffinity_np(pid_t, size_t, cpuset_t *);
+
+/* Historical functions, not defined in standard */
+pid_t   clone(int (*)(void *), void *, int, void *);
+pid_t  __clone(int (*)(void *), void *, int, void *);
+
+__END_DECLS
+
+#endif /* _NETBSD_SOURCE */
+
+#endif /* _SCHED_H_ */
diff --git a/nbsd_include/search.h b/nbsd_include/search.h
new file mode 100644 (file)
index 0000000..bf488f4
--- /dev/null
@@ -0,0 +1,69 @@
+/*     $NetBSD: search.h,v 1.18 2005/07/06 15:47:15 drochner Exp $     */
+
+/*
+ * Written by J.T. Conklin <jtc@NetBSD.org>
+ * Public domain.
+ */
+
+#ifndef _SEARCH_H_
+#define _SEARCH_H_
+
+#include <sys/cdefs.h>
+#include <machine/ansi.h>
+
+#ifdef _BSD_SIZE_T_
+typedef        _BSD_SIZE_T_    size_t;
+#undef _BSD_SIZE_T_
+#endif
+
+typedef struct entry {
+       char *key;
+       void *data;
+} ENTRY;
+
+typedef enum {
+       FIND, ENTER
+} ACTION;
+
+typedef enum {
+       preorder,
+       postorder,
+       endorder,
+       leaf
+} VISIT;
+
+#ifdef _SEARCH_PRIVATE
+typedef struct node {
+       char         *key;
+       struct node  *llink, *rlink;
+} node_t;
+#endif
+
+__BEGIN_DECLS
+#ifndef __BSEARCH_DECLARED
+#define __BSEARCH_DECLARED
+/* also in stdlib.h */
+void   *bsearch(const void *, const void *, size_t, size_t,
+                     int (*)(const void *, const void *));
+#endif /* __BSEARCH_DECLARED */
+int     hcreate(size_t);
+void    hdestroy(void);
+ENTRY  *hsearch(ENTRY, ACTION);
+
+void   *lfind(const void *, const void *, size_t *, size_t,
+                     int (*)(const void *, const void *));
+void   *lsearch(const void *, void *, size_t *, size_t,
+                     int (*)(const void *, const void *));
+void    insque(void *, void *);
+void    remque(void *);
+
+void   *tdelete(const void * __restrict, void ** __restrict,
+                     int (*)(const void *, const void *));
+void   *tfind(const void *, void * const *,
+                     int (*)(const void *, const void *));
+void   *tsearch(const void *, void **, 
+                     int (*)(const void *, const void *));
+void    twalk(const void *, void (*)(const void *, VISIT, int));
+__END_DECLS
+
+#endif /* !_SEARCH_H_ */
diff --git a/nbsd_include/semaphore.h b/nbsd_include/semaphore.h
new file mode 100644 (file)
index 0000000..55047f7
--- /dev/null
@@ -0,0 +1,57 @@
+/* $NetBSD: semaphore.h,v 1.3 2008/04/28 20:22:54 martin Exp $ */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _SEMAPHORE_H_
+#define _SEMAPHORE_H_
+
+/* POSIX 1003.1b semaphores */
+
+struct _sem_st;
+typedef        struct _sem_st *sem_t;
+
+#define        SEM_FAILED      ((sem_t *)0)
+#define        SEM_VALUE_MAX   (~0U)
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+int     sem_close(sem_t *);
+int     sem_destroy(sem_t *);
+int     sem_getvalue(sem_t * __restrict, int * __restrict);
+int     sem_init(sem_t *, int, unsigned int);
+int     sem_post(sem_t *);
+int     sem_trywait(sem_t *);
+int     sem_unlink(const char *);
+int     sem_wait(sem_t *);
+sem_t  *sem_open(const char *, int, ...);
+__END_DECLS
+
+#endif /* !_SEMAPHORE_H_ */
diff --git a/nbsd_include/setjmp.h b/nbsd_include/setjmp.h
new file mode 100644 (file)
index 0000000..b951235
--- /dev/null
@@ -0,0 +1,85 @@
+/*     $NetBSD: setjmp.h,v 1.25 2009/08/12 04:57:36 matt Exp $ */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     @(#)setjmp.h    8.2 (Berkeley) 1/21/94
+ */
+
+#ifndef _SETJMP_H_
+#define _SETJMP_H_
+
+#include <sys/featuretest.h>
+
+#include <machine/setjmp.h>
+
+#ifndef _JB_ATTRIBUTES
+#define _JB_ATTRIBUTES /**/
+#else
+#endif
+#ifndef _BSD_JBSLOT_T_
+#define        _BSD_JBSLOT_T_  long
+#endif
+
+#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+typedef _BSD_JBSLOT_T_ sigjmp_buf[_JBLEN + 1] _JB_ATTRIBUTES;
+#endif /* not ANSI */
+
+typedef _BSD_JBSLOT_T_ jmp_buf[_JBLEN] _JB_ATTRIBUTES;
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+#ifndef __LIBC12_SOURCE__
+int    setjmp(jmp_buf)                  __RENAME(__setjmp14);
+void   longjmp(jmp_buf, int)            __RENAME(__longjmp14) __dead;
+
+#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+int    sigsetjmp(sigjmp_buf, int)      __RENAME(__sigsetjmp14);
+void   siglongjmp(sigjmp_buf, int)      __RENAME(__siglongjmp14) __dead;
+#endif /* not ANSI */
+#endif /* __LIBC12_SOURCE__ */
+
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+int    _setjmp(jmp_buf);
+void   _longjmp(jmp_buf, int) __dead;
+#endif
+
+#if defined(_NETBSD_SOURCE)
+void   longjmperror(void);
+#endif
+__END_DECLS
+
+#endif /* !_SETJMP_H_ */
diff --git a/nbsd_include/sgtty.h b/nbsd_include/sgtty.h
new file mode 100644 (file)
index 0000000..1ac3100
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: sgtty.h,v 1.8 2005/02/03 04:39:32 perry Exp $  */
+
+/*
+ * Copyright (c) 1985, 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.
+ * 3. 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.
+ *
+ *     @(#)sgtty.h     8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _SGTTY_H_
+#define _SGTTY_H_
+
+#ifndef USE_OLD_TTY
+#define        USE_OLD_TTY
+#endif
+#include <sys/ioctl.h>
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+int gtty(int, struct sgttyb *);
+int stty(int, struct sgttyb *);
+__END_DECLS
+
+#endif /* _SGTTY_H_ */
diff --git a/nbsd_include/signal.h b/nbsd_include/signal.h
new file mode 100644 (file)
index 0000000..eddb2f4
--- /dev/null
@@ -0,0 +1,210 @@
+/*     $NetBSD: signal.h,v 1.54 2010/08/27 08:40:38 christos Exp $     */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ *
+ *     @(#)signal.h    8.3 (Berkeley) 3/30/94
+ */
+
+#ifndef _SIGNAL_H_
+#define _SIGNAL_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+
+#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+#include <sys/types.h>
+#endif
+
+#include <sys/signal.h>
+
+#if defined(_NETBSD_SOURCE)
+extern const char *const *sys_signame __RENAME(__sys_signame14);
+#ifndef __SYS_SIGLIST_DECLARED
+#define __SYS_SIGLIST_DECLARED
+/* also in unistd.h */
+extern const char *const *sys_siglist __RENAME(__sys_siglist14);
+#endif /* __SYS_SIGLIST_DECLARED */
+extern const int sys_nsig __RENAME(__sys_nsig14);
+#endif
+
+__BEGIN_DECLS
+int    raise(int);
+#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+int    kill(pid_t, int);
+int    __libc_sigaction14(int, const struct sigaction * __restrict,
+           struct sigaction * __restrict);
+
+#if (_POSIX_C_SOURCE - 0L) >= 199506L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_NETBSD_SOURCE)
+int    pthread_sigmask(int, const sigset_t * __restrict,
+           sigset_t * __restrict);
+int    pthread_kill(pthread_t, int);
+int    __libc_thr_sigsetmask(int, const sigset_t * __restrict,
+           sigset_t * __restrict);
+#ifndef __LIBPTHREAD_SOURCE__
+#define        pthread_sigmask         __libc_thr_sigsetmask
+#endif /* __LIBPTHREAD_SOURCE__ */
+#endif
+
+#ifndef __LIBC12_SOURCE__
+int    sigaction(int, const struct sigaction * __restrict,
+    struct sigaction * __restrict) __RENAME(__sigaction14);
+int    sigaddset(sigset_t *, int) __RENAME(__sigaddset14);
+int    sigdelset(sigset_t *, int) __RENAME(__sigdelset14);
+int    sigemptyset(sigset_t *) __RENAME(__sigemptyset14);
+int    sigfillset(sigset_t *) __RENAME(__sigfillset14);
+int    sigismember(const sigset_t *, int) __RENAME(__sigismember14);
+int    sigpending(sigset_t *) __RENAME(__sigpending14);
+int    sigprocmask(int, const sigset_t * __restrict, sigset_t * __restrict)
+    __RENAME(__sigprocmask14);
+int    sigsuspend(const sigset_t *) __RENAME(__sigsuspend14);
+
+#if defined(__c99inline) || defined(__SIGSETOPS_BODY)
+
+#if defined(__SIGSETOPS_BODY)
+#undef __c99inline
+#define        __c99inline
+#endif
+
+/* note: this appears in both errno.h and signal.h */
+#ifndef __errno
+int *__errno(void);
+#define __errno __errno
+#endif
+
+/* the same as "errno" - but signal.h is not allowed to define that */
+#ifndef ___errno
+#define ___errno (*__errno())
+#endif
+
+__c99inline int
+sigaddset(sigset_t *set, int signo)
+{
+       if (signo <= 0 || signo >= _NSIG) {
+               ___errno = 22;                  /* EINVAL */
+               return (-1);
+       }
+       __sigaddset(set, signo);
+       return (0);
+}
+
+__c99inline int
+sigdelset(sigset_t *set, int signo)
+{
+       if (signo <= 0 || signo >= _NSIG) {
+               ___errno = 22;                  /* EINVAL */
+               return (-1);
+       }
+       __sigdelset(set, signo);
+       return (0);
+}
+
+__c99inline int
+sigismember(const sigset_t *set, int signo)
+{
+       if (signo <= 0 || signo >= _NSIG) {
+               ___errno = 22;                  /* EINVAL */
+               return (-1);
+       }
+       return (__sigismember(set, signo));
+}
+
+__c99inline int
+sigemptyset(sigset_t *set)
+{
+       __sigemptyset(set);
+       return (0);
+}
+
+__c99inline int
+sigfillset(sigset_t *set)
+{
+       __sigfillset(set);
+       return (0);
+}
+#endif /* __c99inline */
+#endif /* !__LIBC12_SOURCE__ */
+
+/*
+ * X/Open CAE Specification Issue 4 Version 2
+ */      
+#if (defined(_XOPEN_SOURCE) && defined(_XOPEN_SOURCE_EXTENDED)) || \
+    (_XOPEN_SOURCE - 0) >= 500 || defined(_NETBSD_SOURCE)
+int    killpg(pid_t, int);
+int    siginterrupt(int, int);
+int    sigstack(const struct sigstack *, struct sigstack *);
+#ifndef __LIBC12_SOURCE__
+int    sigaltstack(const stack_t * __restrict, stack_t * __restrict)
+    __RENAME(__sigaltstack14);
+#endif
+int    sighold(int);
+int    sigignore(int);
+int    sigpause(int);
+int    sigrelse(int);
+void   (*sigset (int, void (*)(int)))(int);
+#endif /* _XOPEN_SOURCE_EXTENDED || _XOPEN_SOURCE >= 500 || _NETBSD_SOURCE */
+
+
+/*
+ * X/Open CAE Specification Issue 5; IEEE Std 1003.1b-1993 (POSIX)
+ */      
+#if (_POSIX_C_SOURCE - 0) >= 199309L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_NETBSD_SOURCE)
+int    sigwait (const sigset_t * __restrict, int * __restrict);
+int    sigwaitinfo(const sigset_t * __restrict, siginfo_t * __restrict);
+void   psiginfo(const siginfo_t *, const char *);
+
+#ifndef __LIBC12_SOURCE__
+struct timespec;
+int    sigtimedwait(const sigset_t * __restrict,
+    siginfo_t * __restrict, const struct timespec * __restrict)
+    __RENAME(__sigtimedwait50);
+int    __sigtimedwait(const sigset_t * __restrict,
+    siginfo_t * __restrict, struct timespec * __restrict)
+    __RENAME(____sigtimedwait50);
+#endif
+#endif /* _POSIX_C_SOURCE >= 200112 || _XOPEN_SOURCE_EXTENDED || ... */
+
+
+#if defined(_NETBSD_SOURCE)
+#ifndef __PSIGNAL_DECLARED
+#define __PSIGNAL_DECLARED
+/* also in unistd.h */
+void   psignal(int, const char *);
+#endif /* __PSIGNAL_DECLARED */
+int    sigblock(int);
+int    sigsetmask(int);
+#endif /* _NETBSD_SOURCE */
+
+#endif /* _POSIX_C_SOURCE || _XOPEN_SOURCE || _NETBSD_SOURCE */
+__END_DECLS
+
+#endif /* !_SIGNAL_H_ */
diff --git a/nbsd_include/ssp/ssp.h b/nbsd_include/ssp/ssp.h
new file mode 100644 (file)
index 0000000..af22894
--- /dev/null
@@ -0,0 +1,76 @@
+/*     $NetBSD: ssp.h,v 1.6 2011/01/20 02:58:17 christos Exp $ */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _SSP_SSP_H_
+#define _SSP_SSP_H_
+
+#include <sys/cdefs.h>
+
+#if !defined(__cplusplus)
+# if _FORTIFY_SOURCE > 0 && __OPTIMIZE__ > 0 && __GNUC_PREREQ__(4, 1)
+#  if _FORTIFY_SOURCE > 1
+#   define __SSP_FORTIFY_LEVEL 2
+#  else
+#   define __SSP_FORTIFY_LEVEL 1
+#  endif
+# endif
+#endif
+
+#ifdef _NAMESPACE_H_
+#define __ssp_weak_name(fun) _sys ## fun
+#else
+#define __ssp_weak_name(fun) _sys_ ## fun
+#endif
+
+#define __ssp_inline static __inline __attribute__((__always_inline__))
+
+#define __ssp_bos(ptr) __builtin_object_size(ptr, __SSP_FORTIFY_LEVEL > 1)
+#define __ssp_bos0(ptr) __builtin_object_size(ptr, 0)
+
+#define __ssp_redirect_raw(rtype, fun, args, call, bos) \
+rtype __ssp_weak_name(fun) args; \
+__ssp_inline rtype fun args; \
+__ssp_inline rtype fun args { \
+       if (bos(__buf) != (size_t)-1 && __len > bos(__buf)) \
+               __chk_fail(); \
+       return __ssp_weak_name(fun) call; \
+}
+
+#define __ssp_redirect(rtype, fun, args, call) \
+    __ssp_redirect_raw(rtype, fun, args, call, __ssp_bos)
+#define __ssp_redirect0(rtype, fun, args, call) \
+    __ssp_redirect_raw(rtype, fun, args, call, __ssp_bos0)
+
+__BEGIN_DECLS
+void __stack_chk_fail(void) __dead;
+void __chk_fail(void) __dead;
+__END_DECLS
+
+#endif /* _SSP_SSP_H_ */
diff --git a/nbsd_include/ssp/stdio.h b/nbsd_include/ssp/stdio.h
new file mode 100644 (file)
index 0000000..28d8ace
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: stdio.h,v 1.4 2010/02/25 18:37:13 joerg Exp $  */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _SSP_STDIO_H_
+#define _SSP_STDIO_H_
+
+#include <ssp/ssp.h>
+
+__BEGIN_DECLS
+int __sprintf_chk(char *__restrict, int, size_t, const char *__restrict, ...)
+    __printflike(4, 5);
+int __vsprintf_chk(char *__restrict, int, size_t, const char *__restrict,
+    _BSD_VA_LIST_)
+    __printflike(4, 0);
+int __snprintf_chk(char *__restrict, size_t, int, size_t,
+    const char *__restrict, ...)
+    __printflike(5, 6);
+int __vsnprintf_chk(char *__restrict, size_t, int, size_t,
+     const char *__restrict, _BSD_VA_LIST_)
+    __printflike(5, 0);
+char *__gets_chk(char *, size_t);
+char *__fgets_chk(char *, int, size_t, FILE *);
+__END_DECLS
+
+#if __SSP_FORTIFY_LEVEL > 0
+
+
+#define sprintf(str, ...) \
+    __builtin___sprintf_chk(str, 0, __ssp_bos(str), __VA_ARGS__)
+
+#define vsprintf(str, fmt, ap) \
+    __builtin___vsprintf_chk(str, 0, __ssp_bos(str), fmt, ap)
+
+#define snprintf(str, len, ...) \
+    __builtin___snprintf_chk(str, len, 0, __ssp_bos(str), __VA_ARGS__)
+
+#define vsnprintf(str, len, fmt, ap) \
+    __builtin___vsnprintf_chk(str, len, 0, __ssp_bos(str), fmt, ap)
+
+#define gets(str) \
+    __gets_chk(str, __ssp_bos(str))
+
+#define fgets(str, len, fp) \
+    __fgets_chk(str, len, __ssp_bos(str), fp)
+#endif /* __SSP_FORTIFY_LEVEL > 0 */
+
+#endif /* _SSP_STDIO_H_ */
diff --git a/nbsd_include/ssp/string.h b/nbsd_include/ssp/string.h
new file mode 100644 (file)
index 0000000..d94b679
--- /dev/null
@@ -0,0 +1,95 @@
+/*     $NetBSD: string.h,v 1.4 2009/11/17 20:47:59 drochner Exp $      */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _SSP_STRING_H_
+#define _SSP_STRING_H_
+
+#include <ssp/ssp.h>
+
+#if __SSP_FORTIFY_LEVEL > 0
+
+#define __ssp_bos_check3(fun, dst, src, len) \
+    ((__ssp_bos0(dst) != (size_t)-1) ? \
+    __builtin___ ## fun ## _chk(dst, src, len, __ssp_bos0(dst)) : \
+    __ ## fun ## _ichk(dst, src, len))
+
+#define __ssp_bos_check2(fun, dst, src) \
+    ((__ssp_bos0(dst) != (size_t)-1) ? \
+    __builtin___ ## fun ## _chk(dst, src, __ssp_bos0(dst)) : \
+    __ ## fun ## _ichk(dst, src))
+
+#define __ssp_bos_icheck3_restrict(fun, type1, type2) \
+static __inline type1 __ ## fun ## _ichk(type1 __restrict, type2 __restrict, size_t); \
+static __inline __attribute__((__always_inline__)) type1 \
+__ ## fun ## _ichk(type1 __restrict dst, type2 __restrict src, size_t len) { \
+       return __builtin___ ## fun ## _chk(dst, src, len, __ssp_bos0(dst)); \
+}
+
+#define __ssp_bos_icheck3(fun, type1, type2) \
+static __inline type1 __ ## fun ## _ichk(type1, type2, size_t); \
+static __inline __attribute__((__always_inline__)) type1 \
+__ ## fun ## _ichk(type1 dst, type2 src, size_t len) { \
+       return __builtin___ ## fun ## _chk(dst, src, len, __ssp_bos0(dst)); \
+}
+
+#define __ssp_bos_icheck2_restrict(fun, type1, type2) \
+static __inline type1 __ ## fun ## _ichk(type1, type2); \
+static __inline __attribute__((__always_inline__)) type1 \
+__ ## fun ## _ichk(type1 __restrict dst, type2 __restrict src) { \
+       return __builtin___ ## fun ## _chk(dst, src, __ssp_bos0(dst)); \
+}
+
+__BEGIN_DECLS
+__ssp_bos_icheck3_restrict(memcpy, void *, const void *)
+__ssp_bos_icheck3(memmove, void *, const void *)
+__ssp_bos_icheck3(memset, void *, int)
+__ssp_bos_icheck2_restrict(strcpy, char *, const char *)
+__ssp_bos_icheck2_restrict(strcat, char *, const char *)
+__ssp_bos_icheck3_restrict(strncpy, char *, const char *)
+__ssp_bos_icheck3_restrict(strncat, char *, const char *)
+void *__memcpy_chk(void *, const void *, size_t, size_t);
+void *__memmove_chk(void *, void *, size_t, size_t);
+void *__memset_chk(void *, int, size_t, size_t);
+char *__strcat_chk(char *, const char *, size_t);
+char *__strcpy_chk(char *, const char *, size_t);
+char *__strncat_chk(char *, const char *, size_t, size_t);
+char *__strncpy_chk(char *, const char *, size_t, size_t);
+__END_DECLS
+
+#define memcpy(dst, src, len) __ssp_bos_check3(memcpy, dst, src, len)
+#define memmove(dst, src, len) __ssp_bos_check3(memmove, dst, src, len)
+#define memset(dst, val, len) __ssp_bos_check3(memset, dst, val, len)
+#define strcpy(dst, src) __ssp_bos_check2(strcpy, dst, src)
+#define strcat(dst, src) __ssp_bos_check2(strcat, dst, src)
+#define strncpy(dst, src, len) __ssp_bos_check3(strncpy, dst, src, len)
+#define strncat(dst, src, len) __ssp_bos_check3(strncat, dst, src, len)
+
+#endif /* __SSP_FORTIFY_LEVEL > 0 */
+#endif /* _SSP_STRING_H_ */
diff --git a/nbsd_include/ssp/strings.h b/nbsd_include/ssp/strings.h
new file mode 100644 (file)
index 0000000..1341a0f
--- /dev/null
@@ -0,0 +1,48 @@
+/*     $NetBSD: strings.h,v 1.3 2008/04/28 20:22:54 martin Exp $       */
+
+/*-
+ * Copyright (c) 2007 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _SSP_STRINGS_H_
+#define _SSP_STRINGS_H_
+
+#include <ssp/ssp.h>
+
+#if __SSP_FORTIFY_LEVEL > 0
+
+#define bcopy(src, dst, len) \
+    ((__ssp_bos0(dst) != (size_t)-1) ? \
+    __builtin___memmove_chk(dst, src, len, __ssp_bos0(dst)) : \
+    __memmove_ichk(dst, src, len))
+#define bzero(dst, len) \
+    ((__ssp_bos0(dst) != (size_t)-1) ? \
+    __builtin___memset_chk(dst, 0, len, __ssp_bos0(dst)) : \
+    __memset_ichk(dst, 0, len))
+
+#endif /* __SSP_FORTIFY_LEVEL > 0 */
+#endif /* _SSP_STRINGS_H_ */
diff --git a/nbsd_include/ssp/unistd.h b/nbsd_include/ssp/unistd.h
new file mode 100644 (file)
index 0000000..ee14bc0
--- /dev/null
@@ -0,0 +1,50 @@
+/*     $NetBSD: unistd.h,v 1.5 2011/01/19 19:21:29 christos Exp $      */
+
+/*-
+ * Copyright (c) 2006 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _SSP_UNISTD_H_
+#define _SSP_UNISTD_H_
+
+#include <ssp/ssp.h>
+
+#if __SSP_FORTIFY_LEVEL > 0
+__BEGIN_DECLS
+
+__ssp_redirect0(ssize_t, read, (int __fd, void *__buf, size_t __len), \
+    (__fd, __buf, __len));
+
+__ssp_redirect(int, readlink, (const char *__restrict __path, \
+    char *__restrict __buf, size_t __len), (__path, __buf, __len));
+
+__ssp_redirect(char *, getcwd, (char *__buf, size_t __len), (__buf, __len));
+
+__END_DECLS
+
+#endif /* __SSP_FORTIFY_LEVEL > 0 */
+#endif /* _SSP_UNISTD_H_ */
diff --git a/nbsd_include/stab.h b/nbsd_include/stab.h
new file mode 100644 (file)
index 0000000..15b5f84
--- /dev/null
@@ -0,0 +1,70 @@
+/*     $NetBSD: stab.h,v 1.6 2003/08/07 09:44:11 agc Exp $     */
+
+/*-
+ * Copyright (c) 1991, 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.
+ * 3. 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.
+ *
+ *     @(#)stab.h      8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _STAB_H_
+#define _STAB_H_
+
+/*
+ * The following are symbols used by various debuggers and by the Pascal
+ * compiler.  Each of them must have one (or more) of the bits defined by
+ * the N_STAB mask set.
+ */
+
+#define        N_GSYM          0x20    /* global symbol */
+#define        N_FNAME         0x22    /* F77 function name */
+#define        N_FUN           0x24    /* procedure name */
+#define        N_STSYM         0x26    /* data segment variable */
+#define        N_LCSYM         0x28    /* bss segment variable */
+#define        N_MAIN          0x2a    /* main function name */
+#define        N_PC            0x30    /* global Pascal symbol */
+#define        N_RSYM          0x40    /* register variable */
+#define        N_SLINE         0x44    /* text segment line number */
+#define        N_DSLINE        0x46    /* data segment line number */
+#define        N_BSLINE        0x48    /* bss segment line number */
+#define        N_SSYM          0x60    /* structure/union element */
+#define        N_SO            0x64    /* main source file name */
+#define        N_LSYM          0x80    /* stack variable */
+#define        N_BINCL         0x82    /* include file beginning */
+#define        N_SOL           0x84    /* included source file name */
+#define        N_PSYM          0xa0    /* parameter variable */
+#define        N_EINCL         0xa2    /* include file end */
+#define        N_ENTRY         0xa4    /* alternate entry point */
+#define        N_LBRAC         0xc0    /* left bracket */
+#define        N_EXCL          0xc2    /* deleted include file */
+#define        N_RBRAC         0xe0    /* right bracket */
+#define        N_BCOMM         0xe2    /* begin common */
+#define        N_ECOMM         0xe4    /* end common */
+#define        N_ECOML         0xe8    /* end common (local name) */
+#define        N_LENG          0xfe    /* length of preceding entry */
+
+#endif /* !_STAB_H_ */
diff --git a/nbsd_include/stdbool.h b/nbsd_include/stdbool.h
new file mode 100644 (file)
index 0000000..a1fb896
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: stdbool.h,v 1.3 2008/04/28 20:22:54 martin Exp $       */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe of Wasabi Systems, 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _STDBOOL_H_
+#define        _STDBOOL_H_
+
+#ifndef __cplusplus
+#define        bool    _Bool
+
+#define        true    1
+#define        false   0
+#else
+#define        bool    bool
+
+#define        true    true
+#define        false   false
+#endif /* __cplusplus */
+
+#define        __bool_true_false_are_defined   1
+
+#endif /* _STDBOOL_H_ */
diff --git a/nbsd_include/stddef.h b/nbsd_include/stddef.h
new file mode 100644 (file)
index 0000000..e7635ad
--- /dev/null
@@ -0,0 +1,67 @@
+/*     $NetBSD: stddef.h,v 1.16 2009/11/15 22:21:03 christos Exp $     */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)stddef.h    8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _STDDEF_H_
+#define _STDDEF_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <machine/ansi.h>
+
+typedef        _BSD_PTRDIFF_T_ ptrdiff_t;
+
+#ifdef _BSD_SIZE_T_
+typedef        _BSD_SIZE_T_    size_t;
+#undef _BSD_SIZE_T_
+#endif
+
+#if defined(_BSD_WCHAR_T_) && !defined(__cplusplus)
+typedef        _BSD_WCHAR_T_   wchar_t;
+#undef _BSD_WCHAR_T_
+#endif
+
+#include <sys/null.h>
+
+#if __GNUC_PREREQ__(4, 0)
+#define        offsetof(type, member)  __builtin_offsetof(type, member)
+#elif !defined(__cplusplus)
+#define        offsetof(type, member)  ((size_t)(unsigned long)(&((type *)0)->member))
+#else
+#if !__GNUC_PREREQ__(3, 4)
+#define __offsetof__(a) a
+#endif
+#define        offsetof(type, member) __offsetof__((reinterpret_cast<size_t> \
+    (&reinterpret_cast<const volatile char &>(static_cast<type *>(0)->member))))
+#endif  
+#endif /* _STDDEF_H_ */
diff --git a/nbsd_include/stdio.h b/nbsd_include/stdio.h
new file mode 100644 (file)
index 0000000..31bdb04
--- /dev/null
@@ -0,0 +1,520 @@
+/*     $NetBSD: stdio.h,v 1.78 2010/09/24 09:21:53 tnozaki Exp $       */
+
+/*-
+ * Copyright (c) 1990, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * 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. 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.
+ *
+ *     @(#)stdio.h     8.5 (Berkeley) 4/29/95
+ */
+
+#ifndef        _STDIO_H_
+#define        _STDIO_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <sys/ansi.h>
+
+#include <machine/ansi.h>
+#ifdef _BSD_SIZE_T_
+typedef        _BSD_SIZE_T_    size_t;
+#undef _BSD_SIZE_T_
+#endif
+#ifdef _BSD_SSIZE_T_
+typedef        _BSD_SSIZE_T_   ssize_t;
+#undef _BSD_SSIZE_T_
+#endif
+
+#include <sys/null.h>
+
+/*      
+ * This is fairly grotesque, but pure ANSI code must not inspect the
+ * innards of an fpos_t anyway.  The library internally uses off_t,
+ * which we assume is exactly as big as eight chars.
+ */
+#if (!defined(_ANSI_SOURCE) && !defined(__STRICT_ANSI__)) || defined(_LIBC)
+typedef __off_t fpos_t;
+#else
+typedef struct __sfpos {
+       __off_t _pos;
+} fpos_t;
+#endif
+
+#define        _FSTDIO                 /* Define for new stdio with functions. */
+
+/*
+ * NB: to fit things in six character monocase externals, the stdio
+ * code uses the prefix `__s' for stdio objects, typically followed
+ * by a three-character attempt at a mnemonic.
+ */
+
+/* stdio buffers */
+struct __sbuf {
+       unsigned char *_base;
+       int     _size;
+};
+
+/*
+ * stdio state variables.
+ *
+ * The following always hold:
+ *
+ *     if (_flags&(__SLBF|__SWR)) == (__SLBF|__SWR),
+ *             _lbfsize is -_bf._size, else _lbfsize is 0
+ *     if _flags&__SRD, _w is 0
+ *     if _flags&__SWR, _r is 0
+ *
+ * This ensures that the getc and putc macros (or inline functions) never
+ * try to write or read from a file that is in `read' or `write' mode.
+ * (Moreover, they can, and do, automatically switch from read mode to
+ * write mode, and back, on "r+" and "w+" files.)
+ *
+ * _lbfsize is used only to make the inline line-buffered output stream
+ * code as compact as possible.
+ *
+ * _ub, _up, and _ur are used when ungetc() pushes back more characters
+ * than fit in the current _bf, or when ungetc() pushes back a character
+ * that does not match the previous one in _bf.  When this happens,
+ * _ub._base becomes non-nil (i.e., a stream has ungetc() data iff
+ * _ub._base!=NULL) and _up and _ur save the current values of _p and _r.
+ *
+ * NB: see WARNING above before changing the layout of this structure!
+ */
+typedef        struct __sFILE {
+       unsigned char *_p;      /* current position in (some) buffer */
+       int     _r;             /* read space left for getc() */
+       int     _w;             /* write space left for putc() */
+       unsigned short _flags;  /* flags, below; this FILE is free if 0 */
+       short   _file;          /* fileno, if Unix descriptor, else -1 */
+       struct  __sbuf _bf;     /* the buffer (at least 1 byte, if !NULL) */
+       int     _lbfsize;       /* 0 or -_bf._size, for inline putc */
+
+       /* operations */
+       void    *_cookie;       /* cookie passed to io functions */
+       int     (*_close)(void *);
+       int     (*_read) (void *, char *, int);
+       fpos_t  (*_seek) (void *, fpos_t, int);
+       int     (*_write)(void *, const char *, int);
+
+       /* file extension */
+       struct  __sbuf _ext;
+
+       /* separate buffer for long sequences of ungetc() */
+       unsigned char *_up;     /* saved _p when _p is doing ungetc data */
+       int     _ur;            /* saved _r when _r is counting ungetc data */
+
+       /* tricks to meet minimum requirements even when malloc() fails */
+       unsigned char _ubuf[3]; /* guarantee an ungetc() buffer */
+       unsigned char _nbuf[1]; /* guarantee a getc() buffer */
+
+       /* Formerly used by fgetln/fgetwln; kept for binary compatibility */
+       struct  __sbuf _lb__unused;
+
+       /* Unix stdio files get aligned to block boundaries on fseek() */
+       int     _blksize;       /* stat.st_blksize (may be != _bf._size) */
+       fpos_t  _offset;        /* current lseek offset */
+} FILE;
+
+__BEGIN_DECLS
+extern FILE __sF[];
+__END_DECLS
+
+#define        __SLBF  0x0001          /* line buffered */
+#define        __SNBF  0x0002          /* unbuffered */
+#define        __SRD   0x0004          /* OK to read */
+#define        __SWR   0x0008          /* OK to write */
+       /* RD and WR are never simultaneously asserted */
+#define        __SRW   0x0010          /* open for reading & writing */
+#define        __SEOF  0x0020          /* found EOF */
+#define        __SERR  0x0040          /* found error */
+#define        __SMBF  0x0080          /* _buf is from malloc */
+#define        __SAPP  0x0100          /* fdopen()ed in append mode */
+#define        __SSTR  0x0200          /* this is an sprintf/snprintf string */
+#define        __SOPT  0x0400          /* do fseek() optimization */
+#define        __SNPT  0x0800          /* do not do fseek() optimization */
+#define        __SOFF  0x1000          /* set iff _offset is in fact correct */
+#define        __SMOD  0x2000          /* true => fgetln modified _p text */
+#define        __SALC  0x4000          /* allocate string space dynamically */
+
+/*
+ * The following three definitions are for ANSI C, which took them
+ * from System V, which brilliantly took internal interface macros and
+ * made them official arguments to setvbuf(), without renaming them.
+ * Hence, these ugly _IOxxx names are *supposed* to appear in user code.
+ *
+ * Although numbered as their counterparts above, the implementation
+ * does not rely on this.
+ */
+#define        _IOFBF  0               /* setvbuf should set fully buffered */
+#define        _IOLBF  1               /* setvbuf should set line buffered */
+#define        _IONBF  2               /* setvbuf should set unbuffered */
+
+#define        BUFSIZ  1024            /* size of buffer used by setbuf */
+#define        EOF     (-1)
+
+/*
+ * FOPEN_MAX is a minimum maximum, and is the number of streams that
+ * stdio can provide without attempting to allocate further resources
+ * (which could fail).  Do not use this for anything.
+ */
+                               /* must be == _POSIX_STREAM_MAX <limits.h> */
+#define        FOPEN_MAX       20      /* must be <= OPEN_MAX <sys/syslimits.h> */
+#define        FILENAME_MAX    1024    /* must be <= PATH_MAX <sys/syslimits.h> */
+
+/* System V/ANSI C; this is the wrong way to do this, do *not* use these. */
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+#define        P_tmpdir        "/var/tmp/"
+#endif
+#define        L_tmpnam        1024    /* XXX must be == PATH_MAX */
+/* Always ensure that this is consistent with <limits.h> */
+#ifndef TMP_MAX
+#define TMP_MAX                        308915776       /* Legacy */
+#endif
+
+/* Always ensure that these are consistent with <fcntl.h> and <unistd.h>! */
+#ifndef SEEK_SET
+#define        SEEK_SET        0       /* set file offset to offset */
+#endif
+#ifndef SEEK_CUR
+#define        SEEK_CUR        1       /* set file offset to current plus offset */
+#endif
+#ifndef SEEK_END
+#define        SEEK_END        2       /* set file offset to EOF plus offset */
+#endif
+
+#define        stdin   (&__sF[0])
+#define        stdout  (&__sF[1])
+#define        stderr  (&__sF[2])
+
+/*
+ * Functions defined in ANSI C standard.
+ */
+__BEGIN_DECLS
+void    clearerr(FILE *);
+int     fclose(FILE *);
+int     feof(FILE *);
+int     ferror(FILE *);
+int     fflush(FILE *);
+int     fgetc(FILE *);
+int     fgetpos(FILE * __restrict, fpos_t * __restrict);
+char   *fgets(char * __restrict, int, FILE * __restrict);
+FILE   *fopen(const char * __restrict , const char * __restrict);
+int     fprintf(FILE * __restrict , const char * __restrict, ...)
+               __printflike(2, 3);
+int     fputc(int, FILE *);
+int     fputs(const char * __restrict, FILE * __restrict);
+size_t  fread(void * __restrict, size_t, size_t, FILE * __restrict);
+FILE   *freopen(const char * __restrict, const char * __restrict,
+           FILE * __restrict);
+int     fscanf(FILE * __restrict, const char * __restrict, ...)
+               __scanflike(2, 3);
+int     fseek(FILE *, long, int);
+int     fsetpos(FILE *, const fpos_t *);
+long    ftell(FILE *);
+size_t  fwrite(const void * __restrict, size_t, size_t, FILE * __restrict);
+int     getc(FILE *);
+int     getchar(void);
+ssize_t         getdelim(char ** __restrict, size_t * __restrict, int,
+           FILE * __restrict);
+ssize_t         getline(char ** __restrict, size_t * __restrict, FILE * __restrict);
+void    perror(const char *);
+int     printf(const char * __restrict, ...)
+               __printflike(1, 2);
+int     putc(int, FILE *);
+int     putchar(int);
+int     puts(const char *);
+int     remove(const char *);
+void    rewind(FILE *);
+int     scanf(const char * __restrict, ...)
+               __scanflike(1, 2);
+void    setbuf(FILE * __restrict, char * __restrict);
+int     setvbuf(FILE * __restrict, char * __restrict, int, size_t);
+int     sscanf(const char * __restrict, const char * __restrict, ...)
+               __scanflike(2, 3);
+FILE   *tmpfile(void);
+int     ungetc(int, FILE *);
+int     vfprintf(FILE * __restrict, const char * __restrict, _BSD_VA_LIST_)
+               __printflike(2, 0);
+int     vprintf(const char * __restrict, _BSD_VA_LIST_)
+               __printflike(1, 0);
+
+#ifndef __AUDIT__
+char   *gets(char *);
+int     sprintf(char * __restrict, const char * __restrict, ...)
+               __printflike(2, 3);
+char   *tmpnam(char *);
+int     vsprintf(char * __restrict, const char * __restrict,
+    _BSD_VA_LIST_)
+               __printflike(2, 0);
+#endif
+
+#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE)
+int     rename (const char *, const char *) __RENAME(__posix_rename);
+#else
+int     rename (const char *, const char *);
+#endif
+__END_DECLS
+
+/*
+ * IEEE Std 1003.1-90
+ */
+#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+#define        L_ctermid       1024    /* size for ctermid(); PATH_MAX */
+#define L_cuserid      9       /* size for cuserid(); UT_NAMESIZE + 1 */
+
+__BEGIN_DECLS
+char   *ctermid(char *);
+#ifndef __CUSERID_DECLARED
+#define __CUSERID_DECLARED
+/* also declared in unistd.h */
+char   *cuserid(char *);
+#endif /* __CUSERID_DECLARED */
+FILE   *fdopen(int, const char *);
+int     fileno(FILE *);
+__END_DECLS
+#endif /* not ANSI */
+
+/*
+ * IEEE Std 1003.1c-95, also adopted by X/Open CAE Spec Issue 5 Version 2
+ */
+#if (_POSIX_C_SOURCE - 0) >= 199506L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_REENTRANT) || defined(_NETBSD_SOURCE)
+__BEGIN_DECLS
+void   flockfile(FILE *);
+int    ftrylockfile(FILE *);
+void   funlockfile(FILE *);
+int    getc_unlocked(FILE *);
+int    getchar_unlocked(void);
+int    putc_unlocked(int, FILE *);
+int    putchar_unlocked(int);
+__END_DECLS
+#endif /* _POSIX_C_SOURCE >= 1995056 || _XOPEN_SOURCE >= 500 || ... */
+
+/*
+ * Functions defined in POSIX 1003.2 and XPG2 or later.
+ */
+#if (_POSIX_C_SOURCE - 0) >= 2 || (_XOPEN_SOURCE - 0) >= 2 || \
+    defined(_NETBSD_SOURCE)
+__BEGIN_DECLS
+int     pclose(FILE *);
+FILE   *popen(const char *, const char *);
+__END_DECLS
+#endif
+
+/*
+ * Functions defined in ISO XPG4.2, ISO C99, POSIX 1003.1-2001 or later.
+ */
+#if ((__STDC_VERSION__ - 0) >= 199901L) || \
+    ((_POSIX_C_SOURCE - 0) >= 200112L) || \
+    (defined(_XOPEN_SOURCE) && defined(_XOPEN_SOURCE_EXTENDED)) || \
+    ((_XOPEN_SOURCE - 0) >= 500) || \
+    defined(_ISOC99_SOURCE) || defined(_NETBSD_SOURCE)
+__BEGIN_DECLS
+int     snprintf(char * __restrict, size_t, const char * __restrict, ...)
+               __printflike(3, 4);
+int     vsnprintf(char * __restrict, size_t, const char * __restrict,
+           _BSD_VA_LIST_)
+               __printflike(3, 0);
+__END_DECLS
+#endif
+
+/*
+ * Functions defined in XPG4.2.
+ */
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+__BEGIN_DECLS
+int     getw(FILE *);
+int     putw(int, FILE *);
+
+#ifndef __AUDIT__
+char   *tempnam(const char *, const char *);
+#endif
+__END_DECLS
+#endif
+
+/*
+ * X/Open CAE Specification Issue 5 Version 2
+ */
+#if (_XOPEN_SOURCE - 0) >= 500 || defined(_LARGEFILE_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+#ifndef        off_t
+typedef        __off_t         off_t;
+#define        off_t           __off_t
+#endif /* off_t */
+
+__BEGIN_DECLS
+int     fseeko(FILE *, off_t, int);
+off_t   ftello(FILE *);
+__END_DECLS
+#endif /* _XOPEN_SOURCE >= 500 || _LARGEFILE_SOURCE || _NETBSD_SOURCE */
+
+/*
+ * Functions defined in ISO C99.  Still put under _NETBSD_SOURCE due to
+ * backward compatible.
+ */
+#if defined(_ISOC99_SOURCE) || defined(_NETBSD_SOURCE)
+__BEGIN_DECLS
+int     vscanf(const char * __restrict, _BSD_VA_LIST_)
+               __scanflike(1, 0);
+int     vfscanf(FILE * __restrict, const char * __restrict, _BSD_VA_LIST_)
+               __scanflike(2, 0);
+int     vsscanf(const char * __restrict, const char * __restrict,
+    _BSD_VA_LIST_)
+    __scanflike(2, 0);
+__END_DECLS
+#endif /* _ISOC99_SOURCE || _NETBSD_SOURCE */
+
+/*
+ * Routines that are purely local.
+ */
+#if defined(_NETBSD_SOURCE)
+
+#define        FPARSELN_UNESCESC       0x01
+#define        FPARSELN_UNESCCONT      0x02
+#define        FPARSELN_UNESCCOMM      0x04
+#define        FPARSELN_UNESCREST      0x08
+#define        FPARSELN_UNESCALL       0x0f
+
+__BEGIN_DECLS
+int     asprintf(char ** __restrict, const char * __restrict, ...)
+               __printflike(2, 3);
+char   *fgetln(FILE * __restrict, size_t * __restrict);
+char   *fparseln(FILE *, size_t *, size_t *, const char[3], int);
+int     fpurge(FILE *);
+void    setbuffer(FILE *, char *, int);
+int     setlinebuf(FILE *);
+int     vasprintf(char ** __restrict, const char * __restrict,
+    _BSD_VA_LIST_)
+               __printflike(2, 0);
+const char *fmtcheck(const char *, const char *)
+               __format_arg(2);
+__END_DECLS
+
+/*
+ * Stdio function-access interface.
+ */
+__BEGIN_DECLS
+FILE   *funopen(const void *,
+               int (*)(void *, char *, int),
+               int (*)(void *, const char *, int),
+               fpos_t (*)(void *, fpos_t, int),
+               int (*)(void *));
+__END_DECLS
+#define        fropen(cookie, fn) funopen(cookie, fn, 0, 0, 0)
+#define        fwopen(cookie, fn) funopen(cookie, 0, fn, 0, 0)
+#endif /* _NETBSD_SOURCE */
+
+/*
+ * Functions internal to the implementation.
+ */
+__BEGIN_DECLS
+int    __srget(FILE *);
+int    __swbuf(int, FILE *);
+__END_DECLS
+
+/*
+ * The __sfoo macros are here so that we can 
+ * define function versions in the C library.
+ */
+#define        __sgetc(p) (--(p)->_r < 0 ? __srget(p) : (int)(*(p)->_p++))
+#if defined(__GNUC__) && defined(__STDC__)
+static __inline int __sputc(int _c, FILE *_p) {
+       if (--_p->_w >= 0 || (_p->_w >= _p->_lbfsize && (char)_c != '\n'))
+               return (*_p->_p++ = _c);
+       else
+               return (__swbuf(_c, _p));
+}
+#else
+/*
+ * This has been tuned to generate reasonable code on the vax using pcc.
+ */
+#define        __sputc(c, p) \
+       (--(p)->_w < 0 ? \
+               (p)->_w >= (p)->_lbfsize ? \
+                       (*(p)->_p = (c)), *(p)->_p != '\n' ? \
+                               (int)*(p)->_p++ : \
+                               __swbuf('\n', p) : \
+                       __swbuf((int)(c), p) : \
+               (*(p)->_p = (c), (int)*(p)->_p++))
+#endif
+
+#define        __sfeof(p)      (((p)->_flags & __SEOF) != 0)
+#define        __sferror(p)    (((p)->_flags & __SERR) != 0)
+#define        __sclearerr(p)  ((void)((p)->_flags &= ~(__SERR|__SEOF)))
+#define        __sfileno(p)    \
+    ((p)->_file == -1 ? -1 : (int)(unsigned short)(p)->_file)
+
+#ifndef __lint__
+#if !defined(_REENTRANT) && !defined(_PTHREADS)
+#define        feof(p)         __sfeof(p)
+#define        ferror(p)       __sferror(p)
+#define        clearerr(p)     __sclearerr(p)
+
+#define        getc(fp)        __sgetc(fp)
+#define putc(x, fp)    __sputc(x, fp)
+#endif /* !_REENTRANT && !_PTHREADS */
+#endif /* __lint__ */
+
+#define        getchar()       getc(stdin)
+#define        putchar(x)      putc(x, stdout)
+
+#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+#if !defined(_REENTRANT) && !defined(_PTHREADS)
+#define        fileno(p)       __sfileno(p)
+#endif /* !_REENTRANT && !_PTHREADS */
+#endif /* !_ANSI_SOURCE */
+
+#if (_POSIX_C_SOURCE - 0) >= 200809L || defined(_NETBSD_SOURCE)
+int     vdprintf(int, const char * __restrict, _BSD_VA_LIST_)
+               __printflike(2, 0);
+int     dprintf(int, const char * __restrict, ...)
+               __printflike(2, 3);
+#endif /* (_POSIX_C_SOURCE - 0) >= 200809L || defined(_NETBSD_SOURCE) */
+
+#if (_POSIX_C_SOURCE - 0) >= 199506L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_REENTRANT) || defined(_NETBSD_SOURCE)
+#define getc_unlocked(fp)      __sgetc(fp)
+#define putc_unlocked(x, fp)   __sputc(x, fp)
+
+#define getchar_unlocked()     getc_unlocked(stdin)
+#define putchar_unlocked(x)    putc_unlocked(x, stdout)
+#endif /* _POSIX_C_SOURCE >= 199506 || _XOPEN_SOURCE >= 500 || _REENTRANT... */
+
+#if (_POSIX_C_SOURCE - 0) >= 200809L || (_XOPEN_SOURCE - 0) >= 700 || \
+    defined(_NETBSD_SOURCE)
+FILE *fmemopen(void * __restrict, size_t, const char * __restrict);
+#endif
+
+#if _FORTIFY_SOURCE > 0
+#include <ssp/stdio.h>
+#endif
+
+#endif /* _STDIO_H_ */
diff --git a/nbsd_include/stdlib.h b/nbsd_include/stdlib.h
new file mode 100644 (file)
index 0000000..1ef7d0b
--- /dev/null
@@ -0,0 +1,328 @@
+/*     $NetBSD: stdlib.h,v 1.94 2010/12/22 19:47:56 jruoho Exp $       */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)stdlib.h    8.5 (Berkeley) 5/19/95
+ */
+
+#ifndef _STDLIB_H_
+#define _STDLIB_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+
+#if defined(_NETBSD_SOURCE)
+#include <sys/types.h>         /* for quad_t, etc. */
+#endif
+
+#include <machine/ansi.h>
+
+#ifdef _BSD_SIZE_T_
+typedef        _BSD_SIZE_T_    size_t;
+#undef _BSD_SIZE_T_
+#endif
+
+#if defined(_BSD_WCHAR_T_) && !defined(__cplusplus)
+typedef        _BSD_WCHAR_T_   wchar_t;
+#undef _BSD_WCHAR_T_
+#endif
+
+typedef struct {
+       int quot;               /* quotient */
+       int rem;                /* remainder */
+} div_t;
+
+typedef struct {
+       long quot;              /* quotient */
+       long rem;               /* remainder */
+} ldiv_t;
+
+#if !defined(_ANSI_SOURCE) && \
+    (defined(_ISOC99_SOURCE) || (__STDC_VERSION__ - 0) >= 199901L || \
+     defined(_NETBSD_SOURCE))
+typedef struct {
+       /* LONGLONG */
+       long long int quot;     /* quotient */
+       /* LONGLONG */
+       long long int rem;      /* remainder */
+} lldiv_t;
+#endif
+
+#if defined(_NETBSD_SOURCE)
+typedef struct {
+       quad_t quot;            /* quotient */
+       quad_t rem;             /* remainder */
+} qdiv_t;
+#endif
+
+
+#include <sys/null.h>
+
+#define        EXIT_FAILURE    1
+#define        EXIT_SUCCESS    0
+
+#define        RAND_MAX        0x7fffffff
+
+extern size_t __mb_cur_max;
+#define        MB_CUR_MAX      __mb_cur_max
+
+__BEGIN_DECLS
+__dead  void _Exit(int);
+__dead  void abort(void);
+__pure  int abs(int);
+int     atexit(void (*)(void));
+double  atof(const char *);
+int     atoi(const char *);
+long    atol(const char *);
+#ifndef __BSEARCH_DECLARED
+#define __BSEARCH_DECLARED
+/* also in search.h */
+void   *bsearch(const void *, const void *, size_t, size_t,
+    int (*)(const void *, const void *));
+#endif /* __BSEARCH_DECLARED */
+void   *calloc(size_t, size_t);
+div_t   div(int, int);
+__dead  void exit(int);
+void    free(void *);
+__aconst char *getenv(const char *);
+__pure long
+        labs(long);
+ldiv_t  ldiv(long, long);
+void   *malloc(size_t);
+void    qsort(void *, size_t, size_t, int (*)(const void *, const void *));
+int     rand(void);
+void   *realloc(void *, size_t);
+void    srand(unsigned);
+double  strtod(const char * __restrict, char ** __restrict);
+long    strtol(const char * __restrict, char ** __restrict, int);
+unsigned long
+        strtoul(const char * __restrict, char ** __restrict, int);
+int     system(const char *);
+
+/* These are currently just stubs. */
+int     mblen(const char *, size_t);
+size_t  mbstowcs(wchar_t * __restrict, const char * __restrict, size_t);
+int     wctomb(char *, wchar_t);
+int     mbtowc(wchar_t * __restrict, const char * __restrict, size_t);
+size_t  wcstombs(char * __restrict, const wchar_t * __restrict, size_t);
+
+#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+
+
+/*
+ * IEEE Std 1003.1c-95, also adopted by X/Open CAE Spec Issue 5 Version 2
+ */
+#if (_POSIX_C_SOURCE - 0) >= 199506L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_REENTRANT) || defined(_NETBSD_SOURCE)
+int     rand_r(unsigned int *);
+#endif
+
+
+/*
+ * X/Open Portability Guide >= Issue 4
+ */
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+double  drand48(void);
+double  erand48(unsigned short[3]);
+long    jrand48(unsigned short[3]);
+void    lcong48(unsigned short[7]);
+long    lrand48(void);
+long    mrand48(void);
+long    nrand48(unsigned short[3]);
+unsigned short *
+        seed48(unsigned short[3]);
+void    srand48(long);
+
+int     putenv(char *);
+#endif
+
+
+/*
+ * X/Open Portability Guide >= Issue 4 Version 2
+ */
+#if (defined(_XOPEN_SOURCE) && defined(_XOPEN_SOURCE_EXTENDED)) || \
+    (_XOPEN_SOURCE - 0) >= 500 || defined(_NETBSD_SOURCE)
+long    a64l(const char *);
+char   *l64a(long);
+
+char   *initstate(unsigned long, char *, size_t);
+long    random(void);
+char   *setstate(char *);
+void    srandom(unsigned long);
+#ifdef _NETBSD_SOURCE
+#define        RANDOM_MAX      0x7fffffff      /* (((long)1 << 31) - 1) */
+#endif
+
+char   *mkdtemp(char *);
+int     mkstemp(char *);
+char   *mktemp(char *)
+#ifdef __MKTEMP_OK__
+       __RENAME(_mktemp)
+#endif
+       ;
+
+int     setkey(const char *);
+
+char   *realpath(const char *, char *);
+
+int     ttyslot(void);
+
+void   *valloc(size_t);                /* obsoleted by malloc() */
+
+int     grantpt(int);
+int     unlockpt(int);
+char   *ptsname(int);
+#endif
+
+/*
+ * ISO C99
+ */
+#if defined(_ISOC99_SOURCE) || (__STDC_VERSION__ - 0) >= 199901L || \
+    defined(_NETBSD_SOURCE)
+/* LONGLONG */
+long long int  atoll(const char *);
+/* LONGLONG */
+long long int  llabs(long long int);
+/* LONGLONG */
+lldiv_t                lldiv(long long int, long long int);
+/* LONGLONG */
+long long int  strtoll(const char * __restrict, char ** __restrict, int);
+/* LONGLONG */
+unsigned long long int
+               strtoull(const char * __restrict, char ** __restrict, int);
+float          strtof(const char * __restrict, char ** __restrict);
+long double    strtold(const char * __restrict, char ** __restrict);
+#endif
+
+/*
+ * The Open Group Base Specifications, Issue 6; IEEE Std 1003.1-2001 (POSIX)
+ */
+#if (_POSIX_C_SOURCE - 0) >= 200112L || (_XOPEN_SOURCE - 0) >= 600 || \
+    defined(_NETBSD_SOURCE)
+int     setenv(const char *, const char *, int);
+#ifndef __LIBC12_SOURCE__
+int     unsetenv(const char *) __RENAME(__unsetenv13);
+#endif
+
+int     posix_openpt(int);
+int     posix_memalign(void **, size_t, size_t);
+#endif
+
+/*
+ * Implementation-defined extensions
+ */
+#if defined(_NETBSD_SOURCE)
+#if defined(alloca) && (alloca == __builtin_alloca) && \
+       defined(__GNUC__) && (__GNUC__ < 2)
+void   *alloca(int);     /* built-in for gcc */
+#elif defined(__PCC__) && !defined(__GNUC__)
+#define alloca(size) __builtin_alloca(size)
+#else
+void   *alloca(size_t);
+#endif /* __GNUC__ */
+
+uint32_t arc4random(void);
+void    arc4random_stir(void);
+void    arc4random_addrandom(u_char *, int);
+char   *getbsize(int *, long *);
+char   *cgetcap(char *, const char *, int);
+int     cgetclose(void);
+int     cgetent(char **, const char * const *, const char *);
+int     cgetfirst(char **, const char * const *);
+int     cgetmatch(const char *, const char *);
+int     cgetnext(char **, const char * const *);
+int     cgetnum(char *, const char *, long *);
+int     cgetset(const char *);
+int     cgetstr(char *, const char *, char **);
+int     cgetustr(char *, const char *, char **);
+void    csetexpandtc(int);
+
+int     daemon(int, int);
+#ifndef __LIBC12_SOURCE__
+__aconst char *devname(dev_t, mode_t) __RENAME(__devname50);
+#endif
+
+#define        HN_DECIMAL              0x01
+#define        HN_NOSPACE              0x02
+#define        HN_B                    0x04
+#define        HN_DIVISOR_1000         0x08
+
+#define        HN_GETSCALE             0x10
+#define        HN_AUTOSCALE            0x20
+
+int     humanize_number(char *, size_t, int64_t, const char *, int, int);
+int     dehumanize_number(const char *, int64_t *);
+
+devmajor_t getdevmajor(const char *, mode_t);
+int     getloadavg(double [], int);
+
+int     getenv_r(const char *, char *, size_t);
+
+void    cfree(void *);
+
+int     heapsort(void *, size_t, size_t, int (*)(const void *, const void *));
+int     mergesort(void *, size_t, size_t,
+           int (*)(const void *, const void *));
+int     radixsort(const unsigned char **, int, const unsigned char *,
+           unsigned);
+int     sradixsort(const unsigned char **, int, const unsigned char *,
+           unsigned);
+
+void    mi_vector_hash(const void * __restrict, size_t, uint32_t,
+           uint32_t[3]);
+
+void    setproctitle(const char *, ...)
+           __printflike(1, 2);
+const char *getprogname(void) __constfunc;
+void   setprogname(const char *);
+
+quad_t  qabs(quad_t);
+quad_t  strtoq(const char * __restrict, char ** __restrict, int);
+u_quad_t strtouq(const char * __restrict, char ** __restrict, int);
+
+       /* LONGLONG */
+long long strsuftoll(const char *, const char *, long long, long long);
+       /* LONGLONG */
+long long strsuftollx(const char *, const char *, long long, long long,
+                       char *, size_t);
+
+int     l64a_r(long, char *, int);
+
+size_t shquote(const char *, char *, size_t);
+size_t shquotev(int, char * const *, char *, size_t);
+#endif /* _NETBSD_SOURCE */
+#endif /* _POSIX_C_SOURCE || _XOPEN_SOURCE || _NETBSD_SOURCE */
+
+#if defined(_NETBSD_SOURCE)
+qdiv_t  qdiv(quad_t, quad_t);
+#endif
+__END_DECLS
+
+#endif /* !_STDLIB_H_ */
diff --git a/nbsd_include/string.h b/nbsd_include/string.h
new file mode 100644 (file)
index 0000000..98825fb
--- /dev/null
@@ -0,0 +1,116 @@
+/*     $NetBSD: string.h,v 1.39 2009/07/22 19:48:27 kleink Exp $       */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)string.h    8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _STRING_H_
+#define        _STRING_H_
+#include <machine/ansi.h>
+
+#ifdef _BSD_SIZE_T_
+typedef        _BSD_SIZE_T_    size_t;
+#undef _BSD_SIZE_T_
+#endif
+
+#include <sys/null.h>
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+
+__BEGIN_DECLS
+void   *memchr(const void *, int, size_t);
+int     memcmp(const void *, const void *, size_t);
+void   *memcpy(void * __restrict, const void * __restrict, size_t);
+void   *memmove(void *, const void *, size_t);
+void   *memset(void *, int, size_t);
+char   *strcat(char * __restrict, const char * __restrict);
+char   *strchr(const char *, int);
+int     strcmp(const char *, const char *);
+int     strcoll(const char *, const char *);
+char   *strcpy(char * __restrict, const char * __restrict);
+size_t  strcspn(const char *, const char *);
+__aconst char *strerror(int);
+size_t  strlen(const char *);
+char   *strncat(char * __restrict, const char * __restrict, size_t);
+int     strncmp(const char *, const char *, size_t);
+char   *strncpy(char * __restrict, const char * __restrict, size_t);
+char   *strpbrk(const char *, const char *);
+char   *strrchr(const char *, int);
+size_t  strspn(const char *, const char *);
+char   *strstr(const char *, const char *);
+char   *strtok(char * __restrict, const char * __restrict);
+#if (_POSIX_C_SOURCE - 0 >= 199506L) || (_XOPEN_SOURCE - 0 >= 500) || \
+    defined(_REENTRANT) || defined(_NETBSD_SOURCE)
+char   *strtok_r(char *, const char *, char **);
+int     strerror_r(int, char *, size_t);
+#endif /* _POSIX_C_SOURCE >= 199506 || XOPEN_SOURCE >= 500 || ... */
+size_t  strxfrm(char * __restrict, const char * __restrict, size_t);
+
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+void   *memccpy(void *, const void *, int, size_t);
+char   *strdup(const char *);
+#endif
+
+#if (_POSIX_C_SOURCE - 0 >= 200809L) || (_XOPEN_SOURCE - 0 >= 700) || \
+    defined(_NETBSD_SOURCE)
+char   *stpcpy(char * __restrict, const char * __restrict);
+char   *stpncpy(char * __restrict, const char * __restrict, size_t);
+size_t strnlen(const char *, size_t);
+#ifndef __STRSIGNAL_DECLARED
+#define __STRSIGNAL_DECLARED
+/* also in unistd.h */
+__aconst char *strsignal(int);
+#endif /* __STRSIGNAL_DECLARED */
+/*
+ * For POSIX compliance, we still need:
+ * strcoll_l
+ * strerror_l
+ * strxfrm_l
+ */
+#endif
+
+#if defined(_NETBSD_SOURCE)
+#include <strings.h>           /* for backwards-compatibilty */
+void   *memmem(const void *, size_t, const void *, size_t);
+char   *strcasestr(const char *, const char *);
+size_t  strlcat(char *, const char *, size_t);
+size_t  strlcpy(char *, const char *, size_t);
+char   *strsep(char **, const char *);
+char   *stresep(char **, const char *, int);
+char   *strndup(const char *, size_t);
+void   *memrchr(const void *, int, size_t);
+#endif
+__END_DECLS
+
+#if _FORTIFY_SOURCE > 0
+#include <ssp/string.h>
+#endif
+#endif /* !defined(_STRING_H_) */
diff --git a/nbsd_include/stringlist.h b/nbsd_include/stringlist.h
new file mode 100644 (file)
index 0000000..4056ed0
--- /dev/null
@@ -0,0 +1,54 @@
+/*     $NetBSD: stringlist.h,v 1.7 2008/04/28 20:22:54 martin Exp $    */
+
+/*-
+ * Copyright (c) 1994 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _STRINGLIST_H
+#define _STRINGLIST_H 
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+/*
+ * Simple string list
+ */
+typedef struct _stringlist {
+       char    **sl_str;
+       size_t    sl_max;
+       size_t    sl_cur;
+} StringList;
+
+__BEGIN_DECLS
+StringList     *sl_init(void);
+int             sl_add(StringList *, char *);
+void            sl_free(StringList *, int);
+char           *sl_find(StringList *, const char *);
+int             sl_delete(StringList *, const char *, int);
+__END_DECLS
+
+#endif /* _STRINGLIST_H */
diff --git a/nbsd_include/strings.h b/nbsd_include/strings.h
new file mode 100644 (file)
index 0000000..dc90dcb
--- /dev/null
@@ -0,0 +1,74 @@
+/*     $NetBSD: strings.h,v 1.17 2009/08/19 04:22:53 yamt Exp $        */
+
+/*-
+ * Copyright (c) 1998 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _STRINGS_H_
+#define _STRINGS_H_
+
+#include <machine/ansi.h>
+#include <sys/featuretest.h>
+
+#ifdef _BSD_SIZE_T_
+typedef        _BSD_SIZE_T_    size_t;
+#undef _BSD_SIZE_T_
+#endif
+
+#if defined(_NETBSD_SOURCE)
+#include <sys/null.h>
+#endif
+
+#include <sys/cdefs.h>
+
+#include <stdint.h>
+
+__BEGIN_DECLS
+int     bcmp(const void *, const void *, size_t);
+void    bcopy(const void *, void *, size_t);
+void    bzero(void *, size_t);
+int     ffs(int);
+char   *index(const char *, int);
+unsigned int   popcount(unsigned int) __constfunc;
+unsigned int   popcountl(unsigned long) __constfunc;
+unsigned int   popcountll(unsigned long long) __constfunc;
+unsigned int   popcount32(uint32_t) __constfunc;
+unsigned int   popcount64(uint64_t) __constfunc;
+char   *rindex(const char *, int);
+int     strcasecmp(const char *, const char *);
+int     strncasecmp(const char *, const char *, size_t);
+__END_DECLS
+
+#if defined(_NETBSD_SOURCE)
+#include <string.h>
+#endif
+
+#if _FORTIFY_SOURCE > 0
+#include <ssp/strings.h>
+#endif
+#endif /* !defined(_STRINGS_H_) */
diff --git a/nbsd_include/struct.h b/nbsd_include/struct.h
new file mode 100644 (file)
index 0000000..615557b
--- /dev/null
@@ -0,0 +1,49 @@
+/*     $NetBSD: struct.h,v 1.5 2003/08/07 09:44:11 agc Exp $   */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)struct.h    8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _STRUCT_H_
+#define        _STRUCT_H_
+
+/* Offset of the field in the structure. */
+#define        fldoff(name, field) \
+       ((int)&(((struct name *)0)->field))
+
+/* Size of the field in the structure. */
+#define        fldsiz(name, field) \
+       (sizeof(((struct name *)0)->field))
+
+/* Address of the structure from a field. */
+#define        strbase(name, addr, field) \
+       ((struct name *)((char *)(addr) - fldoff(name, field)))
+
+#endif /* !_STRUCT_H_ */
diff --git a/nbsd_include/sysexits.h b/nbsd_include/sysexits.h
new file mode 100644 (file)
index 0000000..8dfc9f7
--- /dev/null
@@ -0,0 +1,118 @@
+/*     $NetBSD: sysexits.h,v 1.7 2005/09/30 20:56:19 rpaulo Exp $      */
+
+/*
+ * Copyright (c) 1987, 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.
+ * 3. 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.
+ *
+ *     @(#)sysexits.h  8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef        _SYSEXITS_H_
+#define        _SYSEXITS_H_
+
+/*
+ *  SYSEXITS.H -- Exit status codes for system programs.
+ *
+ *     This include file attempts to categorize possible error
+ *     exit statuses for system programs, notably delivermail
+ *     and the Berkeley network.
+ *
+ *     Error numbers begin at EX__BASE to reduce the possibility of
+ *     clashing with other exit statuses that random programs may
+ *     already return.  The meaning of the codes is approximately
+ *     as follows:
+ *
+ *     EX_USAGE -- The command was used incorrectly, e.g., with
+ *             the wrong number of arguments, a bad flag, a bad
+ *             syntax in a parameter, or whatever.
+ *     EX_DATAERR -- The input data was incorrect in some way.
+ *             This should only be used for user's data & not
+ *             system files.
+ *     EX_NOINPUT -- An input file (not a system file) did not
+ *             exist or was not readable.  This could also include
+ *             errors like "No message" to a mailer (if it cared
+ *             to catch it).
+ *     EX_NOUSER -- The user specified did not exist.  This might
+ *             be used for mail addresses or remote logins.
+ *     EX_NOHOST -- The host specified did not exist.  This is used
+ *             in mail addresses or network requests.
+ *     EX_UNAVAILABLE -- A service is unavailable.  This can occur
+ *             if a support program or file does not exist.  This
+ *             can also be used as a catchall message when something
+ *             you wanted to do doesn't work, but you don't know
+ *             why.
+ *     EX_SOFTWARE -- An internal software error has been detected.
+ *             This should be limited to non-operating system related
+ *             errors as possible.
+ *     EX_OSERR -- An operating system error has been detected.
+ *             This is intended to be used for such things as "cannot
+ *             fork", "cannot create pipe", or the like.  It includes
+ *             things like getuid returning a user that does not
+ *             exist in the passwd file.
+ *     EX_OSFILE -- Some system file (e.g., /etc/passwd, /etc/utmp,
+ *             etc.) does not exist, cannot be opened, or has some
+ *             sort of error (e.g., syntax error).
+ *     EX_CANTCREAT -- A (user specified) output file cannot be
+ *             created.
+ *     EX_IOERR -- An error occurred while doing I/O on some file.
+ *     EX_TEMPFAIL -- temporary failure, indicating something that
+ *             is not really an error.  In sendmail, this means
+ *             that a mailer (e.g.) could not create a connection,
+ *             and the request should be reattempted later.
+ *     EX_PROTOCOL -- the remote system returned something that
+ *             was "not possible" during a protocol exchange.
+ *     EX_NOPERM -- You did not have sufficient permission to
+ *             perform the operation.  This is not intended for
+ *             file system problems, which should use NOINPUT or
+ *             CANTCREAT, but rather for higher level permissions.
+ *
+ *     Please update the sysexits(3) man page after adding more entries.
+ */
+
+#define EX_OK          0       /* successful termination */
+
+#define EX__BASE       64      /* base value for error messages */
+
+#define EX_USAGE       64      /* command line usage error */
+#define EX_DATAERR     65      /* data format error */
+#define EX_NOINPUT     66      /* cannot open input */
+#define EX_NOUSER      67      /* addressee unknown */
+#define EX_NOHOST      68      /* host name unknown */
+#define EX_UNAVAILABLE 69      /* service unavailable */
+#define EX_SOFTWARE    70      /* internal software error */
+#define EX_OSERR       71      /* system error (e.g., can't fork) */
+#define EX_OSFILE      72      /* critical OS file missing */
+#define EX_CANTCREAT   73      /* can't create (user) output file */
+#define EX_IOERR       74      /* input/output error */
+#define EX_TEMPFAIL    75      /* temp failure; user is invited to retry */
+#define EX_PROTOCOL    76      /* remote error in protocol */
+#define EX_NOPERM      77      /* permission denied */
+#define EX_CONFIG      78      /* configuration error */
+
+#define EX__MAX        78      /* maximum listed value */
+
+#endif /* !_SYSEXITS_H_ */
diff --git a/nbsd_include/tar.h b/nbsd_include/tar.h
new file mode 100644 (file)
index 0000000..8e77417
--- /dev/null
@@ -0,0 +1,71 @@
+/*     $NetBSD: tar.h,v 1.4 2003/08/07 09:44:11 agc Exp $      */
+
+/*-
+ * Copyright (c) 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chuck Karish of Mindcraft, 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. 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.
+ *
+ *     @(#)tar.h       8.2 (Berkeley) 1/4/94
+ */
+
+#ifndef _TAR_H
+#define _TAR_H
+
+#define        TMAGIC          "ustar" /* ustar and a null */
+#define        TMAGLEN         6
+#define        TVERSION        "00"    /* 00 and no null */
+#define        TVERSLEN        2
+
+/* Values used in typeflag field */
+#define        REGTYPE         '0'     /* Regular file */
+#define        AREGTYPE        '\0'    /* Regular file */
+#define        LNKTYPE         '1'     /* Link */
+#define        SYMTYPE         '2'     /* Reserved */
+#define        CHRTYPE         '3'     /* Character special */
+#define        BLKTYPE         '4'     /* Block special */
+#define        DIRTYPE         '5'     /* Directory */
+#define        FIFOTYPE        '6'     /* FIFO special */
+#define        CONTTYPE        '7'     /* Reserved */
+
+/* Bits used in the mode field - values in octal */
+#define        TSUID           04000   /* Set UID on execution */
+#define        TSGID           02000   /* Set GID on execution */
+#define        TSVTX           01000   /* Reserved */
+                               /* File permissions */
+#define        TUREAD          00400   /* Read by owner */
+#define        TUWRITE         00200   /* Write by owner */
+#define        TUEXEC          00100   /* Execute/Search by owner */
+#define        TGREAD          00040   /* Read by group */
+#define        TGWRITE         00020   /* Write by group */
+#define        TGEXEC          00010   /* Execute/Search by group */
+#define        TOREAD          00004   /* Read by other */
+#define        TOWRITE         00002   /* Write by other */
+#define        TOEXEC          00001   /* Execute/Search by other */
+
+#endif
diff --git a/nbsd_include/tgmath.h b/nbsd_include/tgmath.h
new file mode 100644 (file)
index 0000000..9961303
--- /dev/null
@@ -0,0 +1,192 @@
+/*-
+ * Copyright (c) 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matt Thomas <matt@3am-software.com>
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _TGMATH_H_
+#define        _TGMATH_H_
+
+#include <math.h>
+#include <complex.h>
+
+/*
+ * C99 Type-generic math (7.22)
+ */
+#ifdef __GNUC__
+#define        __TG_CHOOSE(p, a, b)    __builtin_choose_expr((p), (a), (b))
+#define        __TG_IS_EQUIV_TYPE_P(v, t)      \
+        __builtin_types_compatible_p(__typeof__(v), t)
+#else
+#error how does this compler do type-generic macros?
+#endif
+
+#define        __TG_IS_FCOMPLEX_P(t)   __TG_IS_EQUIV_TYPE_P(t, float complex)
+#define        __TG_IS_DCOMPLEX_P(t)   __TG_IS_EQUIV_TYPE_P(t, double complex)
+#define        __TG_IS_LCOMPLEX_P(t)   __TG_IS_EQUIV_TYPE_P(t, long double complex)
+#define        __TG_IS_FLOAT_P(t)      __TG_IS_EQUIV_TYPE_P(t, float)
+#define        __TG_IS_LDOUBLE_P(t)    __TG_IS_EQUIV_TYPE_P(t, long double)
+#define        __TG_IS_FREAL_P(t)      (__TG_IS_FLOAT_P(t) || __TG_IS_FCOMPLEX_P(t))
+#define        __TG_IS_LREAL_P(t)      (__TG_IS_LDOUBLE_P(t) || __TG_IS_LCOMPLEX_P(t))
+
+#define        __TG_IS_COMPLEX_P(t)                                    \
+       (__TG_IS_FCOMPLEX_P(t)                                  \
+        || __TG_IS_DCOMPLEX_P(t)                               \
+        || __TG_IS_LCOMPLEX_P(t))
+
+#define        __TG_GFN1(fn, a, ftype, ltype)                          \
+       __TG_CHOOSE(__TG_IS_##ftype##_P(a),                     \
+                   fn##f(a),                                   \
+                   __TG_CHOOSE(__TG_IS_##ltype##_P(a),         \
+                               fn##l(a),                       \
+                               fn(a)))
+
+#define        __TG_GFN1x(fn, a, b, ftype, ltype)                      \
+       __TG_CHOOSE(__TG_IS_##ftype##_P(a),                     \
+                   fn##f((a), (b)),                            \
+                   __TG_CHOOSE(__TG_IS_##ltype##_P(a),         \
+                               fn##l((a), (b)),                \
+                               fn((a), (b))))
+
+#define        __TG_GFN2(fn, a, b, ftype, ltype)                       \
+       __TG_CHOOSE(__TG_IS_##ftype##_P(a)                      \
+                   && __TG_IS_##ftype##_P(b),                  \
+                   fn##f((a), (b)),                            \
+                   __TG_CHOOSE(__TG_IS_##ltype##_P(a)          \
+                               || __TG_IS_##ltype##_P(b),      \
+                               fn##l((a), (b)),                \
+                               fn((a), (b))))
+
+#define        __TG_GFN2x(fn, a, b, c, ftype, ltype)                   \
+       __TG_CHOOSE(__TG_IS_##ftype##_P(a)                      \
+                   && __TG_IS_##ftype##_P(b),                  \
+                   fn##f((a), (b), (c)),                       \
+                   __TG_CHOOSE(__TG_IS_##ltype##_P(a)          \
+                               || __TG_IS_##ltype##_P(b),      \
+                               fn##l((a), (b), (c)),           \
+                               fn((a), (b), (c))))
+
+#define        __TG_GFN3(fn, a, b, c, ftype, ltype)                    \
+       __TG_CHOOSE(__TG_IS_##ftype##_P(a)                      \
+                   && __TG_IS_##ftype##_P(b)                   \
+                   && __TG_IS_##ftype##_P(c),                  \
+                   fn##f((a), (b), (c)),                       \
+                   __TG_CHOOSE(__TG_IS_##ltype##_P(a)          \
+                               || __TG_IS_##ltype##_P(b)       \
+                               || __TG_IS_##ltype##_P(c),      \
+                               fn##l((a), (b), (c)),           \
+                               fn((a), (b), (c))))
+
+
+#define        __TG_CFN1(cfn, a)       __TG_GFN1(cfn, a, FREAL, LREAL)
+#define        __TG_CFN2(cfn, a, b)    __TG_GFN2(cfn, a, b, FREAL, LREAL)
+
+#define        __TG_FN1(fn, a)         __TG_GFN1(fn, a, FLOAT, LDOUBLE)
+#define        __TG_FN1x(fn, a, b)     __TG_GFN1x(fn, a, b, FLOAT, LDOUBLE)
+#define        __TG_FN2(fn, a, b)      __TG_GFN2(fn, a, b, FLOAT, LDOUBLE)
+#define        __TG_FN2x(fn, a, b, c)  __TG_GFN2x(fn, a, b, c, FLOAT, LDOUBLE)
+#define        __TG_FN3(fn, a, b, c)   __TG_GFN3(fn, a, b, c, FLOAT, LDOUBLE)
+
+#define        __TG_COMPLEX(a, fn)                     \
+       __TG_CHOOSE(__TG_IS_COMPLEX_P(a),       \
+                   __TG_CFN1(c##fn, (a)),      \
+                   __TG_FN1(fn, (a)))
+
+#define        __TG_COMPLEX1(a, cfn, fn)               \
+       __TG_CHOOSE(__TG_IS_COMPLEX_P(a),       \
+                   __TG_CFN1(cfn, (a)),        \
+                   __TG_FN1(fn, (a)))
+
+#define        __TG_COMPLEX2(a, b, fn)                 \
+       __TG_CHOOSE(__TG_IS_COMPLEX_P(a)        \
+                   || __TG_IS_COMPLEX_P(b),    \
+                   __TG_CFN2(c##fn, (a), (b)), \
+                   __TG_FN2(fn, (a), (b)))
+
+#define        acos(a)         __TG_COMPLEX((a), acos)
+#define        asin(a)         __TG_COMPLEX((a), asin)
+#define        atan(a)         __TG_COMPLEX((a), atan)
+#define        acosh(a)        __TG_COMPLEX((a), acosh)
+#define        asinh(a)        __TG_COMPLEX((a), asinh)
+#define        atanh(a)        __TG_COMPLEX((a), atanh)
+#define        cos(a)          __TG_COMPLEX((a), cos)
+#define        sin(a)          __TG_COMPLEX((a), sin)
+#define        tan(a)          __TG_COMPLEX((a), tan)
+#define        cosh(a)         __TG_COMPLEX((a), cosh)
+#define        sinh(a)         __TG_COMPLEX((a), sinh)
+#define        tanh(a)         __TG_COMPLEX((a), tanh)
+#define        exp(a)          __TG_COMPLEX((a), exp)
+#define        log(a)          __TG_COMPLEX((a), log)
+#define        pow(a,b)        __TG_COMPLEX2((a), (b), pow)
+#define        sqrt(a)         __TG_COMPLEX((a), sqrt)
+#define        fabs(a)         __TG_COMPLEX1((a), cabs, fabs)
+
+#define        atan2(a,b)      __TG_FN2(atan2, (a), (b))
+#define        cbrt(a)         __TG_FN1(cbrt, (a))
+#define        ceil(a)         __TG_FN1(ceil, (a))
+#define        copysign(a,b)   __TG_FN2(copysign, (a), (b))
+#define        erf(a)          __TG_FN1(erf, (a))
+#define        erfc(a)         __TG_FN1(erfc, (a))
+#define        exp2(a)         __TG_FN1(exp2, (a))
+#define        expm1(a)        __TG_FN1(expm1, (a))
+#define        fdim(a,b)       __TG_FN2(fdim, (a), (b))
+#define        floor(a)        __TG_FN1(floor, (a))
+#define        fma(a,b,c)      __TG_FN3(fma, (a), (b), (c))
+#define        fmax(a,b)       __TG_FN2(fmax, (a), (b))
+#define        fmin(a,b)       __TG_FN2(fmin, (a), (b))
+#define        fmod(a,b)       __TG_FN2(fmod, (a), (b))
+#define        frexp(a,b)      __TG_FN1x(frexp, (a), (b))
+#define        hypot(a,b)      __TG_FN2(hypot, (a), (b))
+#define        ilogb(a)        __TG_FN1(ilogb, (a))
+#define        ldexp(a,b)      __TG_FN1x(ldexp, (a), (b))
+#define        lgamma(a)       __TG_FN1(lgamma, (a))
+#define        llrint(a)       __TG_FN1(llrint, (a))
+#define        llround(a)      __TG_FN1(llround, (a))
+#define        log10(a)        __TG_FN1(log10, (a))
+#define        log1p(a)        __TG_FN1(log1p, (a))
+#define        log2(a)         __TG_FN1(log2, (a))
+#define        logb(a)         __TG_FN1(logb, (a))
+#define        lrint(a)        __TG_FN1(lrint, (a))
+#define        lround(a)       __TG_FN1(lround, (a))
+#define        nearbyint(a)    __TG_FN1(nearbyint, (a))
+#define        nextafter(a,b)  __TG_FN2(nextafter, (a), (b))
+#define        nexttoward(a,b) __TG_FN2(nexttoward, (a), (b))
+#define        remainder(a,b)  __TG_FN2(remainder, (a), (b))
+#define        remquo(a,b,c)   __TG_FN2x(remquo, (a), (b), (c))
+#define        rint(a)         __TG_FN1(rint, (a))
+#define        round(a)        __TG_FN1(round, (a))
+#define        scalbn(a,b)     __TG_FN1x(scalbn, (a), (b))
+#define        scalb1n(a,b)    __TG_FN1x(scalb1n, (a), (b))
+#define        tgamma(a)       __TG_FN1(tgamma, (a))
+#define        trunc(a)        __TG_FN1(trunc, (a))
+
+#define        carg(a)         __TG_CFN1(carg, (a))
+#define        cimag(a)        __TG_CFN1(cimag, (a))
+#define        conj(a)         __TG_CFN1(conj, (a))
+#define        cproj(a)        __TG_CFN1(cproj, (a))
+#define        creal(a)        __TG_CFN1(creal, (a))
+
+#endif /* !_TGMATH_H_ */
diff --git a/nbsd_include/time.h b/nbsd_include/time.h
new file mode 100644 (file)
index 0000000..8108eff
--- /dev/null
@@ -0,0 +1,210 @@
+/*     $NetBSD: time.h,v 1.40 2010/12/16 18:36:47 christos Exp $       */
+
+/*
+ * Copyright (c) 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     @(#)time.h      8.3 (Berkeley) 1/21/94
+ */
+
+#ifndef _TIME_H_
+#define        _TIME_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <machine/ansi.h>
+
+#include <sys/null.h>
+
+#ifdef _BSD_CLOCK_T_
+typedef        _BSD_CLOCK_T_   clock_t;
+#undef _BSD_CLOCK_T_
+#endif
+
+#ifdef _BSD_TIME_T_
+typedef        _BSD_TIME_T_    time_t;
+#undef _BSD_TIME_T_
+#endif
+
+#ifdef _BSD_SIZE_T_
+typedef        _BSD_SIZE_T_    size_t;
+#undef _BSD_SIZE_T_
+#endif
+
+#ifdef _BSD_CLOCKID_T_
+typedef        _BSD_CLOCKID_T_ clockid_t;
+#undef _BSD_CLOCKID_T_
+#endif
+
+#ifdef _BSD_TIMER_T_
+typedef        _BSD_TIMER_T_   timer_t;
+#undef _BSD_TIMER_T_
+#endif
+
+#define CLOCKS_PER_SEC 100
+
+struct tm {
+       int     tm_sec;         /* seconds after the minute [0-61] */
+       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 UTC in seconds */
+       __aconst char *tm_zone; /* timezone abbreviation */
+};
+
+__BEGIN_DECLS
+char *asctime(const struct tm *);
+clock_t clock(void);
+#ifndef __LIBC12_SOURCE__
+char *ctime(const time_t *) __RENAME(__ctime50);
+double difftime(time_t, time_t) __RENAME(__difftime50);
+struct tm *gmtime(const time_t *) __RENAME(__gmtime50);
+struct tm *localtime(const time_t *) __RENAME(__locatime50);
+time_t time(time_t *) __RENAME(__time50);
+time_t mktime(struct tm *) __RENAME(__mktime50);
+#endif
+size_t strftime(char * __restrict, size_t, const char * __restrict,
+    const struct tm * __restrict)
+    __attribute__((__format__(__strftime__, 3, 0)));
+
+#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+#ifndef __LIBC12_SOURCE__
+/*
+ * CLK_TCK uses libc's internal __sysconf() to retrieve the machine's
+ * HZ. The value of _SC_CLK_TCK is 39 -- we hard code it so we do not
+ * need to include unistd.h
+ */
+long __sysconf(int);
+#define CLK_TCK                (__sysconf(39))
+#endif
+#endif
+
+extern __aconst char *tzname[2];
+#ifndef __LIBC12_SOURCE__
+void tzset(void) __RENAME(__tzset50);
+#endif
+
+/*
+ * X/Open Portability Guide >= Issue 4
+ */
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+extern int daylight;
+#ifndef __LIBC12_SOURCE__
+extern long int timezone __RENAME(__timezone13);
+#endif
+char *strptime(const char * __restrict, const char * __restrict,
+    struct tm * __restrict);
+#endif
+
+#if (defined(_XOPEN_SOURCE) && defined(_XOPEN_SOURCE_EXTENDED)) || \
+    defined(_NETBSD_SOURCE)
+struct tm *getdate(const char *);
+extern int getdate_err;
+#endif
+
+#if (_POSIX_C_SOURCE - 0) >= 199309L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_NETBSD_SOURCE)
+#include <sys/time.h>          /* XXX for struct timespec */
+struct sigevent;
+struct itimerspec;
+#ifndef __LIBC12_SOURCE__
+int clock_getres(clockid_t, struct timespec *)
+    __RENAME(__clock_getres50);
+int clock_gettime(clockid_t, struct timespec *)
+    __RENAME(__clock_gettime50);
+int clock_settime(clockid_t, const struct timespec *)
+    __RENAME(__clock_settime50);
+int nanosleep(const struct timespec *, struct timespec *)
+    __RENAME(__nanosleep50);
+int timer_gettime(timer_t, struct itimerspec *) __RENAME(__timer_gettime50);
+int timer_settime(timer_t, int, const struct itimerspec * __restrict, 
+    struct itimerspec * __restrict) __RENAME(__timer_settime50);
+#endif
+int timer_create(clockid_t, struct sigevent * __restrict,
+    timer_t * __restrict);
+int timer_delete(timer_t);
+int timer_getoverrun(timer_t);
+#endif /* _POSIX_C_SOURCE >= 199309 || _XOPEN_SOURCE >= 500 || ... */
+
+#if (_POSIX_C_SOURCE - 0) >= 199506L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_REENTRANT) || defined(_NETBSD_SOURCE)
+char *asctime_r(const struct tm * __restrict, char * __restrict);
+#ifndef __LIBC12_SOURCE__
+char *ctime_r(const time_t *, char *) __RENAME(__ctime_r50);
+struct tm *gmtime_r(const time_t * __restrict, struct tm * __restrict)
+    __RENAME(__gmtime_r50);
+struct tm *localtime_r(const time_t * __restrict, struct tm * __restrict)
+    __RENAME(__localtime_r50);
+#endif
+#endif
+
+#if defined(_NETBSD_SOURCE)
+
+typedef struct __state *timezone_t;
+
+#ifndef __LIBC12_SOURCE__
+time_t time2posix(time_t) __RENAME(__time2posix50);
+time_t posix2time(time_t) __RENAME(__posix2time50);
+time_t timegm(struct tm *) __RENAME(__timegm50);
+time_t timeoff(struct tm *, long) __RENAME(__timeoff50);
+time_t timelocal(struct tm *) __RENAME(__timelocal50);
+struct tm *offtime(const time_t *, long) __RENAME(__offtime50);
+void tzsetwall(void) __RENAME(__tzsetwall50);
+
+struct tm *offtime_r(const time_t *, long, struct tm *) __RENAME(__offtime_r50);
+struct tm *localtime_rz(const timezone_t, const time_t * __restrict,
+    struct tm * __restrict) __RENAME(__localtime_rz50);
+char *ctime_rz(const timezone_t, const time_t *, char *) __RENAME(__ctime_rz50);
+time_t mktime_z(const timezone_t, struct tm *) __RENAME(__mktime_z50);
+time_t timelocal_z(const timezone_t, struct tm *) __RENAME(__timelocal_z50);
+time_t time2posix_z(const timezone_t, time_t) __RENAME(__time2posix_z50);
+time_t posix2time_z(const timezone_t, time_t) __RENAME(__posix2time_z50);
+timezone_t tzalloc(const char *) __RENAME(__tzalloc50);
+void tzfree(const timezone_t) __RENAME(__tzfree50);
+const char *tzgetname(const timezone_t, int) __RENAME(__tzgetname50);
+#endif
+
+size_t strftime_z(const timezone_t, char * __restrict, size_t,
+    const char * __restrict, const struct tm * __restrict)
+    __attribute__((__format__(__strftime__, 4, 0)));
+
+#endif /* _NETBSD_SOURCE */
+
+__END_DECLS
+
+#endif /* !_TIME_H_ */
diff --git a/nbsd_include/ttyent.h b/nbsd_include/ttyent.h
new file mode 100644 (file)
index 0000000..da30f13
--- /dev/null
@@ -0,0 +1,79 @@
+/*     $NetBSD: ttyent.h,v 1.14 2006/04/17 23:29:21 salo Exp $ */
+
+/*
+ * Copyright (c) 1989, 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.
+ * 3. 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.
+ *
+ *     @(#)ttyent.h    8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef        _TTYENT_H_
+#define        _TTYENT_H_
+
+#include <sys/cdefs.h>
+
+#define        _PATH_TTYS      "/etc/ttys"
+
+#define        _TTYS_OFF       "off"
+#define        _TTYS_ON        "on"
+#define        _TTYS_SECURE    "secure"
+#define        _TTYS_WINDOW    "window"
+#define        _TTYS_CLASS     "class"
+#define        _TTYS_LOCAL     "local"
+#define        _TTYS_RTSCTS    "rtscts"
+#define        _TTYS_DTRCTS    "dtrcts"
+#define        _TTYS_SOFTCAR   "softcar"
+#define        _TTYS_MDMBUF    "mdmbuf"
+
+struct ttyent {
+       __aconst char *ty_name; /* terminal device name */
+       __aconst char *ty_getty;/* command to execute, usually getty */
+       __aconst char *ty_type; /* terminal type for termcap */
+#define        TTY_ON          0x01    /* enable logins (start ty_getty program) */
+#define        TTY_SECURE      0x02    /* allow uid of 0 to login */
+#define        TTY_LOCAL       0x04    /* set 'CLOCAL' on open (dev. specific) */
+#define        TTY_RTSCTS      0x08    /* set 'CRTSCTS' on open (dev. specific) */
+#define        TTY_SOFTCAR     0x10    /* ignore hardware carrier (dev. spec.) */
+#define        TTY_MDMBUF      0x20    /* set 'MDMBUF' on open (dev. specific) */
+#define TTY_DTRCTS      0x40    /* set 'CDTRCTS' on open (dev. specific) */
+       int     ty_status;      /* status flags */
+       __aconst char *ty_window;/* command to start up window manager */
+       __aconst char *ty_comment;/* comment field */
+       __aconst char *ty_class;/* category of tty usage */
+};
+
+__BEGIN_DECLS
+struct ttyent *getttyent(void);
+struct ttyent *getttynam(const char *);
+#if defined(_NETBSD_SOURCE)
+int setttyentpath(const char *);
+#endif /* defined(_NETBSD_SOURCE) */
+int setttyent(void);
+int endttyent(void);
+__END_DECLS
+
+#endif /* !_TTYENT_H_ */
diff --git a/nbsd_include/tzfile.h b/nbsd_include/tzfile.h
new file mode 100644 (file)
index 0000000..0029eae
--- /dev/null
@@ -0,0 +1,158 @@
+/*     $NetBSD: tzfile.h,v 1.7 2003/08/07 09:44:11 agc Exp $   */
+
+/*
+ * Copyright (c) 1988, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Arthur David Olson of the National Cancer Institute.
+ *
+ * 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. 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.
+ *
+ *     @(#)tzfile.h    8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _TZFILE_H_
+#define        _TZFILE_H_
+
+/*
+ * Information about time zone files.
+ */
+                       /* Time zone object file directory */
+#define TZDIR          "/usr/share/zoneinfo"
+#define TZDEFAULT      "/etc/localtime"
+#define TZDEFRULES     "posixrules"
+
+/*
+** Each file begins with. . .
+*/
+
+#define TZ_MAGIC       "TZif"
+
+struct tzhead {
+       char    tzh_magic[4];           /* TZ_MAGIC */
+       char    tzh_reserved[16];       /* reserved for future use */
+       char    tzh_ttisgmtcnt[4];      /* coded number of trans. time flags */
+       char    tzh_ttisstdcnt[4];      /* coded number of trans. time flags */
+       char    tzh_leapcnt[4];         /* coded number of leap seconds */
+       char    tzh_timecnt[4];         /* coded number of transition times */
+       char    tzh_typecnt[4];         /* coded number of local time types */
+       char    tzh_charcnt[4];         /* coded number of abbr. chars */
+};
+
+/*
+** . . .followed by. . .
+**
+**     tzh_timecnt (char [4])s         coded transition times a la time(2)
+**     tzh_timecnt (unsigned char)s    types of local time starting at above
+**     tzh_typecnt repetitions of
+**             one (char [4])          coded UTC offset in seconds
+**             one (unsigned char)     used to set tm_isdst
+**             one (unsigned char)     that's an abbreviation list index
+**     tzh_charcnt (char)s             '\0'-terminated zone abbreviations
+**     tzh_leapcnt repetitions of
+**             one (char [4])          coded leap second transition times
+**             one (char [4])          total correction after above
+**     tzh_ttisstdcnt (char)s          indexed by type; if TRUE, transition
+**                                     time is standard time, if FALSE,
+**                                     transition time is wall clock time
+**                                     if absent, transition times are
+**                                     assumed to be wall clock time
+**     tzh_ttisgmtcnt (char)s          indexed by type; if TRUE, transition
+**                                     time is UTC, if FALSE,
+**                                     transition time is wall clock time
+**                                     if absent, transition times are
+**                                     assumed to be local time
+*/
+
+/*
+** In the current implementation, "tzset()" refuses to deal with files that
+** exceed any of the limits below.
+*/
+
+/*
+** The TZ_MAX_TIMES value below is enough to handle a bit more than a
+** year's worth of solar time (corrected daily to the nearest second) or
+** 138 years of Pacific Presidential Election time
+** (where there are three time zone transitions every fourth year).
+*/
+#define TZ_MAX_TIMES   370
+
+#define NOSOLAR                        /* 4BSD doesn't currently handle solar time */
+
+#ifndef NOSOLAR
+#define TZ_MAX_TYPES   256     /* Limited by what (unsigned char)'s can hold */
+#else
+#define TZ_MAX_TYPES   10      /* Maximum number of local time types */
+#endif
+
+#define TZ_MAX_CHARS   50      /* Maximum number of abbreviation characters */
+
+#define        TZ_MAX_LEAPS    50      /* Maximum number of leap second corrections */
+
+#define SECSPERMIN     60
+#define MINSPERHOUR    60
+#define HOURSPERDAY    24
+#define DAYSPERWEEK    7
+#define DAYSPERNYEAR   365
+#define DAYSPERLYEAR   366
+#define SECSPERHOUR    (SECSPERMIN * MINSPERHOUR)
+#define SECSPERDAY     ((long) SECSPERHOUR * HOURSPERDAY)
+#define MONSPERYEAR    12
+
+#define TM_SUNDAY      0
+#define TM_MONDAY      1
+#define TM_TUESDAY     2
+#define TM_WEDNESDAY   3
+#define TM_THURSDAY    4
+#define TM_FRIDAY      5
+#define TM_SATURDAY    6
+
+#define TM_JANUARY     0
+#define TM_FEBRUARY    1
+#define TM_MARCH       2
+#define TM_APRIL       3
+#define TM_MAY         4
+#define TM_JUNE                5
+#define TM_JULY                6
+#define TM_AUGUST      7
+#define TM_SEPTEMBER   8
+#define TM_OCTOBER     9
+#define TM_NOVEMBER    10
+#define TM_DECEMBER    11
+
+#define TM_YEAR_BASE   1900
+
+#define EPOCH_YEAR     1970
+#define EPOCH_WDAY     TM_THURSDAY
+
+/*
+** Accurate only for the past couple of centuries;
+** that will probably do.
+*/
+
+#define isleap(y) ((((y) % 4) == 0 && ((y) % 100) != 0) || ((y) % 400) == 0)
+
+#endif /* !_TZFILE_H_ */
diff --git a/nbsd_include/ucontext.h b/nbsd_include/ucontext.h
new file mode 100644 (file)
index 0000000..8dad20d
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: ucontext.h,v 1.6 2009/03/19 08:04:38 uebayasi Exp $    */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _UCONTEXT_H_
+#define _UCONTEXT_H_
+
+#include <sys/cdefs.h>
+#include <sys/ucontext.h>
+
+__BEGIN_DECLS
+int    getcontext(ucontext_t *);
+int    setcontext(const ucontext_t *);
+void   makecontext(ucontext_t *, void (*)(), int, ...);
+int    swapcontext(ucontext_t * __restrict, const ucontext_t * __restrict);
+__END_DECLS
+
+#endif /* !_UCONTEXT_H_ */
diff --git a/nbsd_include/ulimit.h b/nbsd_include/ulimit.h
new file mode 100644 (file)
index 0000000..b18c2dd
--- /dev/null
@@ -0,0 +1,44 @@
+/*     $NetBSD: ulimit.h,v 1.3 2008/04/28 20:22:54 martin Exp $        */
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _ULIMIT_H_
+#define _ULIMIT_H_
+
+#define UL_GETFSIZE    1       /* Get maximum file size */
+#define UL_SETFSIZE    2       /* Set maximum file size */
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+long int ulimit(int, ...);
+__END_DECLS
+
+#endif /* !_ULIMIT_H_ */
diff --git a/nbsd_include/unistd.h b/nbsd_include/unistd.h
new file mode 100644 (file)
index 0000000..32dbb29
--- /dev/null
@@ -0,0 +1,367 @@
+/*     $NetBSD: unistd.h,v 1.125 2011/01/19 19:21:29 christos Exp $    */
+
+/*-
+ * Copyright (c) 1998, 1999, 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Klaus Klein.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+/*
+ * Copyright (c) 1991, 1993, 1994
+ *     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.
+ * 3. 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.
+ *
+ *     @(#)unistd.h    8.12 (Berkeley) 4/27/95
+ */
+
+#ifndef _UNISTD_H_
+#define        _UNISTD_H_
+
+#include <machine/ansi.h>
+#include <machine/int_types.h>
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <sys/types.h>
+#include <sys/unistd.h>
+
+#if _FORTIFY_SOURCE > 0
+#include <ssp/unistd.h>
+#endif
+
+/*
+ * IEEE Std 1003.1-90
+ */
+#define        STDIN_FILENO    0       /* standard input file descriptor */
+#define        STDOUT_FILENO   1       /* standard output file descriptor */
+#define        STDERR_FILENO   2       /* standard error file descriptor */
+
+#include <sys/null.h>
+
+__BEGIN_DECLS
+__dead  void _exit(int);
+int     access(const char *, int);
+unsigned int alarm(unsigned int);
+int     chdir(const char *);
+#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE)
+int    chown(const char *, uid_t, gid_t) __RENAME(__posix_chown);
+#else
+int    chown(const char *, uid_t, gid_t);
+#endif /* defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) */
+int     close(int);
+size_t  confstr(int, char *, size_t);
+#ifndef __CUSERID_DECLARED
+#define __CUSERID_DECLARED
+/* also declared in stdio.h */
+char   *cuserid(char *);       /* obsolete */
+#endif /* __CUSERID_DECLARED */
+int     dup(int);
+int     dup2(int, int);
+int     execl(const char *, const char *, ...);
+int     execle(const char *, const char *, ...);
+int     execlp(const char *, const char *, ...);
+int     execv(const char *, char * const *);
+int     execve(const char *, char * const *, char * const *);
+int     execvp(const char *, char * const *);
+pid_t   fork(void);
+long    fpathconf(int, int);
+#if __SSP_FORTIFY_LEVEL == 0
+char   *getcwd(char *, size_t);
+#endif
+gid_t   getegid(void);
+uid_t   geteuid(void);
+gid_t   getgid(void);
+int     getgroups(int, gid_t []);
+__aconst char *getlogin(void);
+int     getlogin_r(char *, size_t);
+pid_t   getpgrp(void);
+pid_t   getpid(void);
+pid_t   getppid(void);
+uid_t   getuid(void);
+int     isatty(int);
+int     link(const char *, const char *);
+long    pathconf(const char *, int);
+int     pause(void);
+int     pipe(int *);
+#if __SSP_FORTIFY_LEVEL == 0
+ssize_t         read(int, void *, size_t);
+#endif
+int     rmdir(const char *);
+int     setgid(gid_t);
+int     setpgid(pid_t, pid_t);
+pid_t   setsid(void);
+int     setuid(uid_t);
+unsigned int    sleep(unsigned int);
+long    sysconf(int);
+pid_t   tcgetpgrp(int);
+int     tcsetpgrp(int, pid_t);
+__aconst char *ttyname(int);
+int     unlink(const char *);
+ssize_t         write(int, const void *, size_t);
+
+
+/*
+ * IEEE Std 1003.2-92, adopted in X/Open Portability Guide Issue 4 and later
+ */
+#if (_POSIX_C_SOURCE - 0) >= 2 || defined(_XOPEN_SOURCE) || \
+    defined(_NETBSD_SOURCE)
+int     getopt(int, char * const [], const char *);
+
+extern  char *optarg;                  /* getopt(3) external variables */
+extern  int opterr;
+extern  int optind;
+extern  int optopt;
+#endif
+
+/*
+ * The Open Group Base Specifications, Issue 6; IEEE Std 1003.1-2001 (POSIX)
+ */
+#if (_POSIX_C_SOURCE - 0) >= 200112L || (_XOPEN_SOURCE - 0) >= 600 || \
+    defined(_NETBSD_SOURCE)
+int     setegid(gid_t);
+int     seteuid(uid_t);
+#endif
+
+/*
+ * The following three syscalls are also defined in <sys/types.h>
+ * We protect them against double declarations.
+ */
+#ifndef __OFF_T_SYSCALLS_DECLARED
+#define __OFF_T_SYSCALLS_DECLARED
+off_t   lseek(int, off_t, int);
+int     truncate(const char *, off_t);
+/*
+ * IEEE Std 1003.1b-93,
+ * also found in X/Open Portability Guide >= Issue 4 Verion 2
+ */
+#if (_POSIX_C_SOURCE - 0) >= 199309L || \
+    (defined(_XOPEN_SOURCE) && defined(_XOPEN_SOURCE_EXTENDED)) || \
+    (_XOPEN_SOURCE - 0) >= 500 || defined(_NETBSD_SOURCE)
+int     ftruncate(int, off_t);
+#endif
+#endif /* __OFF_T_SYSCALLS_DECLARED */
+
+
+/*
+ * IEEE Std 1003.1b-93, adopted in X/Open CAE Specification Issue 5 Version 2
+ */
+#if (_POSIX_C_SOURCE - 0) >= 199309L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_NETBSD_SOURCE)
+int     fdatasync(int);
+int     fsync(int);
+#endif
+
+
+/*
+ * IEEE Std 1003.1c-95, also adopted by X/Open CAE Spec Issue 5 Version 2
+ */
+#if (_POSIX_C_SOURCE - 0) >= 199506L || (_XOPEN_SOURCE - 0) >= 500 || \
+    defined(_REENTRANT) || defined(_NETBSD_SOURCE)
+int     ttyname_r(int, char *, size_t);
+int     pthread_atfork(void (*)(void), void (*)(void), void (*)(void));
+#endif
+
+/*
+ * X/Open Portability Guide, all issues
+ */
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+int     chroot(const char *);
+int     nice(int);
+#endif
+
+
+/*
+ * X/Open Portability Guide >= Issue 4
+ */
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+__aconst char *crypt(const char *, const char *);
+int     encrypt(char *, int);
+char   *getpass(const char *);
+pid_t   getsid(pid_t);
+#endif
+
+
+/*
+ * X/Open Portability Guide >= Issue 4 Version 2
+ */
+#if (defined(_XOPEN_SOURCE) && defined(_XOPEN_SOURCE_EXTENDED)) || \
+    (_XOPEN_SOURCE - 0) >= 500 || defined(_NETBSD_SOURCE)
+#ifndef        intptr_t
+typedef        __intptr_t      intptr_t;
+#define        intptr_t        __intptr_t
+#endif
+
+#define F_ULOCK                0
+#define F_LOCK         1
+#define F_TLOCK                2
+#define F_TEST         3
+
+int     brk(void *);
+int     fchdir(int);
+#if defined(_XOPEN_SOURCE)
+int     fchown(int, uid_t, gid_t) __RENAME(__posix_fchown);
+#else
+int     fchown(int, uid_t, gid_t);
+#endif
+int     getdtablesize(void);
+long    gethostid(void);
+int     gethostname(char *, size_t);
+__pure int
+        getpagesize(void);             /* legacy */
+pid_t   getpgid(pid_t);
+#if defined(_XOPEN_SOURCE)
+int     lchown(const char *, uid_t, gid_t) __RENAME(__posix_lchown);
+#else
+int     lchown(const char *, uid_t, gid_t);
+#endif
+int     lockf(int, int, off_t);
+#if __SSP_FORTIFY_LEVEL == 0
+ssize_t         readlink(const char * __restrict, char * __restrict, size_t);
+#endif
+void   *sbrk(intptr_t);
+/* XXX prototype wrong! */
+int     setpgrp(pid_t, pid_t);                 /* obsoleted by setpgid() */
+int     setregid(gid_t, gid_t);
+int     setreuid(uid_t, uid_t);
+void    swab(const void * __restrict, void * __restrict, ssize_t);
+int     symlink(const char *, const char *);
+void    sync(void);
+useconds_t ualarm(useconds_t, useconds_t);
+int     usleep(useconds_t);
+#ifndef __LIBC12_SOURCE__
+pid_t   vfork(void) __RENAME(__vfork14);
+#endif
+
+#ifndef __AUDIT__
+char   *getwd(char *);                         /* obsoleted by getcwd() */
+#endif
+#endif /* _XOPEN_SOURCE_EXTENDED || _XOPEN_SOURCE >= 500 || _NETBSD_SOURCE */
+
+
+/*
+ * X/Open CAE Specification Issue 5 Version 2
+ */
+#if (_XOPEN_SOURCE - 0) >= 500 || defined(_NETBSD_SOURCE)
+ssize_t         pread(int, void *, size_t, off_t);
+ssize_t         pwrite(int, const void *, size_t, off_t);
+#endif
+
+
+/*
+ * Implementation-defined extensions
+ */
+#if defined(_NETBSD_SOURCE)
+int     acct(const char *);
+int     closefrom(int);
+int     des_cipher(const char *, char *, long, int);
+int     des_setkey(const char *);
+void    endusershell(void);
+int     exect(const char *, char * const *, char * const *);
+int     fchroot(int);
+int     fsync_range(int, int, off_t, off_t);
+int     getdomainname(char *, size_t);
+int     getgrouplist(const char *, gid_t, gid_t *, int *);
+int     getgroupmembership(const char *, gid_t, gid_t *, int, int *);
+mode_t  getmode(const void *, mode_t);
+int     getpeereid(int, uid_t *, gid_t *);
+int     getsubopt(char **, char * const *, char **);
+__aconst char *getusershell(void);
+int     initgroups(const char *, gid_t);
+int     iruserok(uint32_t, int, const char *, const char *);
+int      issetugid(void);
+int     nfssvc(int, void *);
+int     profil(char *, size_t, u_long, u_int);
+#ifndef __PSIGNAL_DECLARED
+#define __PSIGNAL_DECLARED
+/* also in signal.h */
+void   psignal(int, const char *);
+#endif /* __PSIGNAL_DECLARED */
+int     rcmd(char **, int, const char *, const char *, const char *, int *);
+int     reboot(int, char *);
+int     revoke(const char *);
+int     rresvport(int *);
+int     ruserok(const char *, int, const char *, const char *);
+int     setdomainname(const char *, size_t);
+int     setgroups(int, const gid_t *);
+int     sethostid(long);
+int     sethostname(const char *, size_t);
+int     setlogin(const char *);
+void   *setmode(const char *);
+int     setrgid(gid_t);
+int     setruid(uid_t);
+void    setusershell(void);
+void    strmode(mode_t, char *);
+#ifndef __STRSIGNAL_DECLARED
+#define __STRSIGNAL_DECLARED
+/* backwards-compatibility; also in string.h */
+__aconst char *strsignal(int);
+#endif /* __STRSIGNAL_DECLARED */
+int     swapctl(int, void *, int);
+int     swapon(const char *);                  /* obsoleted by swapctl() */
+int     syscall(int, ...);
+quad_t  __syscall(quad_t, ...);
+int     undelete(const char *);
+
+#if 1 /*INET6*/
+int     rcmd_af(char **, int, const char *,
+           const char *, const char *, int *, int);
+int     rresvport_af(int *, int);
+int     iruserok_sa(const void *, int, int, const char *, const char *);
+#endif
+
+#ifndef __SYS_SIGLIST_DECLARED
+#define __SYS_SIGLIST_DECLARED
+/* also in signal.h */
+extern const char *const *sys_siglist __RENAME(__sys_siglist14);
+#endif /* __SYS_SIGLIST_DECLARED */
+extern  int optreset;          /* getopt(3) external variable */
+extern  char *suboptarg;       /* getsubopt(3) external variable */
+#endif
+
+__END_DECLS
+#endif /* !_UNISTD_H_ */
diff --git a/nbsd_include/util.h b/nbsd_include/util.h
new file mode 100644 (file)
index 0000000..34252cc
--- /dev/null
@@ -0,0 +1,146 @@
+/*     $NetBSD: util.h,v 1.55 2010/02/25 18:37:12 joerg Exp $  */
+
+/*-
+ * Copyright (c) 1995
+ *     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.
+ * 3. 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.
+ */
+
+#ifndef _UTIL_H_
+#define        _UTIL_H_
+
+#include <sys/cdefs.h>
+#include <sys/ttycom.h>
+#include <sys/types.h>
+#include <stdio.h>
+#include <pwd.h>
+#include <termios.h>
+#include <utmp.h>
+#include <utmpx.h>
+#include <machine/ansi.h>
+
+#ifdef  _BSD_TIME_T_
+typedef _BSD_TIME_T_    time_t;
+#undef  _BSD_TIME_T_
+#endif
+
+#define        PIDLOCK_NONBLOCK        1
+#define        PIDLOCK_USEHOSTNAME     2
+
+#define        PW_POLICY_BYSTRING      0
+#define        PW_POLICY_BYPASSWD      1
+#define        PW_POLICY_BYGROUP       2
+
+__BEGIN_DECLS
+struct disklabel;
+struct iovec;
+struct passwd;
+struct termios;
+struct utmp;
+struct winsize;
+struct sockaddr;
+
+char          *flags_to_string(unsigned long, const char *);
+pid_t          forkpty(int *, char *, struct termios *, struct winsize *);
+const char     *getbootfile(void);
+off_t          getlabeloffset(void);
+int            getlabelsector(void);
+int            getmaxpartitions(void);
+int            getrawpartition(void);
+#ifndef __LIBC12_SOURCE__
+void           login(const struct utmp *) __RENAME(__login50);
+void           loginx(const struct utmpx *) __RENAME(__loginx50);
+#endif
+int            login_tty(int);
+int            logout(const char *);
+int            logoutx(const char *, int, int);
+void           logwtmp(const char *, const char *, const char *);
+void           logwtmpx(const char *, const char *, const char *, int, int);
+int            opendisk(const char *, int, char *, size_t, int);
+int            opendisk1(const char *, int, char *, size_t, int,
+                         int (*)(const char *, int, ...));
+int            openpty(int *, int *, char *, struct termios *,
+    struct winsize *);
+#ifndef __LIBC12_SOURCE__
+time_t         parsedate(const char *, const time_t *, const int *)
+    __RENAME(__parsedate50);
+#endif
+int            pidfile(const char *);
+int            pidlock(const char *, int, pid_t *, const char *);
+int            pw_abort(void);
+#ifndef __LIBC12_SOURCE__
+void           pw_copy(int, int, struct passwd *, struct passwd *)
+    __RENAME(__pw_copy50);
+int            pw_copyx(int, int, struct passwd *, struct passwd *,
+    char *, size_t) __RENAME(__pw_copyx50);
+#endif
+void           pw_edit(int, const char *);
+void           pw_error(const char *, int, int);
+void           pw_getconf(char *, size_t, const char *, const char *);
+#ifndef __LIBC12_SOURCE__
+void           pw_getpwconf(char *, size_t, const struct passwd *,
+    const char *) __RENAME(__pw_getpwconf50);
+#endif
+const char     *pw_getprefix(void);
+void           pw_init(void);
+int            pw_lock(int);
+int            pw_mkdb(const char *, int);
+void           pw_prompt(void);
+int            pw_setprefix(const char *);
+int            raise_default_signal(int);
+int            secure_path(const char *);
+int            snprintb_m(char *, size_t, const char *, uint64_t, size_t);
+int            snprintb(char *, size_t, const char *, uint64_t);
+int            sockaddr_snprintf(char *, size_t, const char *,
+    const struct sockaddr *);
+int            string_to_flags(char **, unsigned long *, unsigned long *);
+int            ttyaction(const char *, const char *, const char *);
+int            ttylock(const char *, int, pid_t *);
+char          *ttymsg(struct iovec *, int, const char *, int);
+int            ttyunlock(const char *);
+
+uint16_t       disklabel_dkcksum(struct disklabel *);
+int            disklabel_scan(struct disklabel *, char *, size_t);
+
+/* Error checked functions */
+void           (*esetfunc(void (*)(int, const char *, ...)))
+    (int, const char *, ...);
+size_t                 estrlcpy(char *, const char *, size_t);
+size_t                 estrlcat(char *, const char *, size_t);
+char           *estrdup(const char *);
+char           *estrndup(const char *, size_t);
+void           *ecalloc(size_t, size_t);
+void           *emalloc(size_t);
+void           *erealloc(void *, size_t);
+struct __sFILE *efopen(const char *, const char *);
+int            easprintf(char ** __restrict, const char * __restrict, ...)
+                       __printflike(2, 3);
+int            evasprintf(char ** __restrict, const char * __restrict,
+    _BSD_VA_LIST_)
+                       __printflike(2, 0);
+__END_DECLS
+
+#endif /* !_UTIL_H_ */
diff --git a/nbsd_include/utime.h b/nbsd_include/utime.h
new file mode 100644 (file)
index 0000000..bf82611
--- /dev/null
@@ -0,0 +1,57 @@
+/*     $NetBSD: utime.h,v 1.9 2009/01/11 03:04:12 christos Exp $       */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)utime.h     8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef        _UTIME_H_
+#define        _UTIME_H_
+
+#include <machine/ansi.h>
+
+#ifdef _BSD_TIME_T_
+typedef        _BSD_TIME_T_    time_t;
+#undef _BSD_TIME_T_
+#endif
+
+struct utimbuf {
+       time_t actime;          /* Access time */
+       time_t modtime;         /* Modification time */
+};
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+#ifndef __LIBC12_SOURCE__
+int utime(const char *, const struct utimbuf *) __RENAME(__utime50);
+#endif
+__END_DECLS
+
+#endif /* !_UTIME_H_ */
diff --git a/nbsd_include/utmp.h b/nbsd_include/utmp.h
new file mode 100644 (file)
index 0000000..a489cb3
--- /dev/null
@@ -0,0 +1,72 @@
+/*     $NetBSD: utmp.h,v 1.12 2009/01/11 03:04:12 christos Exp $       */
+
+/*
+ * Copyright (c) 1988, 1993
+ *     The Regents of the University of California.  All rights reserved.
+ * (c) UNIX System Laboratories, Inc.
+ * All or some portions of this file are derived from material licensed
+ * to the University of California by American Telephone and Telegraph
+ * Co. or Unix System Laboratories, Inc. and are reproduced herein with
+ * the permission of UNIX System Laboratories, 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. 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.
+ *
+ *     @(#)utmp.h      8.2 (Berkeley) 1/21/94
+ */
+
+#ifndef        _UTMP_H_
+#define        _UTMP_H_
+
+#define        _PATH_UTMP      "/var/run/utmp"
+#define        _PATH_WTMP      "/var/log/wtmp"
+#define        _PATH_LASTLOG   "/var/log/lastlog"
+
+#define        UT_NAMESIZE     8
+#define        UT_LINESIZE     8
+#define        UT_HOSTSIZE     16
+
+struct lastlog {
+       time_t  ll_time;
+       char    ll_line[UT_LINESIZE];
+       char    ll_host[UT_HOSTSIZE];
+};
+
+struct utmp {
+       char    ut_line[UT_LINESIZE];
+       char    ut_name[UT_NAMESIZE];
+       char    ut_host[UT_HOSTSIZE];
+       time_t  ut_time;
+};
+
+__BEGIN_DECLS
+int utmpname(const char *);
+void setutent(void);
+#ifndef __LIBC12_SOURCE__
+struct utmp *getutent(void) __RENAME(__getutent50);
+#endif
+void endutent(void);
+__END_DECLS
+
+#endif /* !_UTMP_H_ */
diff --git a/nbsd_include/utmpx.h b/nbsd_include/utmpx.h
new file mode 100644 (file)
index 0000000..2217f47
--- /dev/null
@@ -0,0 +1,159 @@
+/*     $NetBSD: utmpx.h,v 1.17 2009/01/11 19:09:29 christos Exp $       */
+
+/*-
+ * Copyright (c) 2002 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Christos Zoulas.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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        _UTMPX_H_
+#define        _UTMPX_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+
+#define        _PATH_UTMPX             "/var/run/utmpx"
+#define        _PATH_WTMPX             "/var/log/wtmpx"
+#define        _PATH_LASTLOGX          "/var/log/lastlogx"
+#define        _PATH_UTMP_UPDATE       "/usr/libexec/utmp_update"
+
+#define _UTX_USERSIZE  32
+#define _UTX_LINESIZE  32
+#define        _UTX_IDSIZE     4
+#define _UTX_HOSTSIZE  256
+
+#if defined(_NETBSD_SOURCE)
+#define UTX_USERSIZE   _UTX_USERSIZE
+#define UTX_LINESIZE   _UTX_LINESIZE
+#define        UTX_IDSIZE      _UTX_IDSIZE
+#define UTX_HOSTSIZE   _UTX_HOSTSIZE
+#endif
+
+#define EMPTY          0
+#define RUN_LVL                1
+#define BOOT_TIME      2
+#define OLD_TIME       3
+#define NEW_TIME       4
+#define INIT_PROCESS   5
+#define LOGIN_PROCESS  6
+#define USER_PROCESS   7
+#define DEAD_PROCESS   8
+
+#if defined(_NETBSD_SOURCE)
+#define ACCOUNTING     9
+#define SIGNATURE      10
+#define DOWN_TIME      11
+
+/*
+ * Strings placed in the ut_line field to indicate special type entries
+ */
+#define        RUNLVL_MSG      "run-level %c"
+#define        BOOT_MSG        "system boot"
+#define        OTIME_MSG       "old time"
+#define        NTIME_MSG       "new time"
+#define        DOWN_MSG        "system down"
+#endif
+
+/*
+ * The following structure describes the fields of the utmpx entries
+ * stored in _PATH_UTMPX or _PATH_WTMPX. This is not the format the
+ * entries are stored in the files, and application should only access
+ * entries using routines described in getutxent(3).
+ */
+
+#define ut_user ut_name
+#define ut_xtime ut_tv.tv_sec
+
+/*
+ * This should be:
+ * 40 - (sizeof(struct timeval) - sizeof(struct { long s; long u; })))
+ * but g++ does not like it, to retain size compatibility with v1.00,
+ * so we do it manually.
+ */
+#ifdef _LP64
+#define _UTX_PADSIZE 36
+#else
+#define _UTX_PADSIZE 40
+#endif
+
+struct utmpx {
+       char ut_name[_UTX_USERSIZE];    /* login name */
+       char ut_id[_UTX_IDSIZE];        /* inittab id */
+       char ut_line[_UTX_LINESIZE];    /* tty name */
+       char ut_host[_UTX_HOSTSIZE];    /* host name */
+       uint16_t ut_session;            /* session id used for windowing */
+       uint16_t ut_type;               /* type of this entry */
+       pid_t ut_pid;                   /* process id creating the entry */
+       struct {
+               uint16_t e_termination; /* process termination signal */
+               uint16_t e_exit;        /* process exit status */
+       } ut_exit;
+       struct sockaddr_storage ut_ss;  /* address where entry was made from */
+       struct timeval ut_tv;           /* time entry was created */
+       uint8_t ut_pad[_UTX_PADSIZE];   /* reserved for future use */
+};
+
+#if defined(_NETBSD_SOURCE)
+struct lastlogx {
+       struct timeval ll_tv;           /* time entry was created */
+       char ll_line[_UTX_LINESIZE];    /* tty name */
+       char ll_host[_UTX_HOSTSIZE];    /* host name */
+       struct sockaddr_storage ll_ss;  /* address where entry was made from */
+};
+#endif /* !_XOPEN_SOURCE */
+
+__BEGIN_DECLS
+
+void setutxent(void);
+void endutxent(void);
+
+#ifndef __LIBC12_SOURCE__
+struct utmpx *getutxent(void) __RENAME(__getutxent50);
+struct utmpx *getutxid(const struct utmpx *) __RENAME(__getutxid50);
+struct utmpx *getutxline(const struct utmpx *) __RENAME(__getutxline50);
+struct utmpx *pututxline(const struct utmpx *) __RENAME(__pututxline50);
+#endif
+
+#if defined(_NETBSD_SOURCE)
+#ifndef __LIBC12_SOURCE__
+int updwtmpx(const char *, const struct utmpx *) __RENAME(__updwtmpx50);
+struct lastlogx *getlastlogx(const char *, uid_t, struct lastlogx *)
+    __RENAME(__getlastlogx50);
+int updlastlogx(const char *, uid_t, struct lastlogx *)
+    __RENAME(__updlastlogx50);
+struct utmp;
+void getutmp(const struct utmpx *, struct utmp *) __RENAME(__getutmp50);
+void getutmpx(const struct utmp *, struct utmpx *) __RENAME(__getutmpx50);
+#endif
+
+int utmpxname(const char *);
+
+#endif /* _NETBSD_SOURCE */
+
+__END_DECLS
+
+#endif /* !_UTMPX_H_ */
diff --git a/nbsd_include/uuid.h b/nbsd_include/uuid.h
new file mode 100644 (file)
index 0000000..1813158
--- /dev/null
@@ -0,0 +1,60 @@
+/*     $NetBSD: uuid.h,v 1.2 2008/04/23 07:52:32 plunky Exp $  */
+
+/*-
+ * Copyright (c) 2002 Marcel Moolenaar
+ * Copyright (c) 2002 Hiten Mahesh Pandya
+ * 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.
+ *
+ * $FreeBSD: src/include/uuid.h,v 1.2 2002/11/05 10:55:16 jmallett Exp $
+ */
+
+#ifndef _UUID_H_
+#define        _UUID_H_
+
+#include <sys/types.h>
+#include <sys/uuid.h>
+
+/* Status codes returned by the functions. */
+#define        uuid_s_ok                       0
+#define        uuid_s_bad_version              1
+#define        uuid_s_invalid_string_uuid      2
+#define        uuid_s_no_memory                3
+
+__BEGIN_DECLS
+int32_t        uuid_compare(const uuid_t *, const uuid_t *, uint32_t *);
+void   uuid_create(uuid_t *, uint32_t *);
+void   uuid_create_nil(uuid_t *, uint32_t *);
+int32_t        uuid_equal(const uuid_t *, const uuid_t *, uint32_t *);
+void   uuid_from_string(const char *, uuid_t *, uint32_t *);
+uint16_t uuid_hash(const uuid_t *, uint32_t *);
+int32_t        uuid_is_nil(const uuid_t *, uint32_t *);
+void   uuid_to_string(const uuid_t *, char **, uint32_t *);
+
+void   uuid_enc_le(void *, const uuid_t *);
+void   uuid_dec_le(const void *, uuid_t *);
+void   uuid_enc_be(void *, const uuid_t *);
+void   uuid_dec_be(const void *, uuid_t *);
+__END_DECLS
+
+#endif /* _UUID_H_ */
diff --git a/nbsd_include/varargs.h b/nbsd_include/varargs.h
new file mode 100644 (file)
index 0000000..8d33ca0
--- /dev/null
@@ -0,0 +1,45 @@
+/*     $NetBSD: varargs.h,v 1.3 2008/04/28 20:22:54 martin Exp $       */
+
+/*-
+ * Copyright (c) 2003 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Matthias Scheler.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _VARARGS_H_
+#define        _VARARGS_H_
+
+#include <sys/cdefs.h>
+
+#if __GNUC_PREREQ__(3, 3)
+#error "GCC 3.3 and newer no longer implements <varargs.h>."
+#error "Revise your code to use <stdarg.h>."
+#else
+#include <machine/varargs.h>
+#endif
+
+#endif /* !_VARARGS_H_ */
+
diff --git a/nbsd_include/vis.h b/nbsd_include/vis.h
new file mode 100644 (file)
index 0000000..7c06b04
--- /dev/null
@@ -0,0 +1,95 @@
+/*     $NetBSD: vis.h,v 1.18 2010/11/27 19:44:54 christos Exp $        */
+
+/*-
+ * 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.
+ * 3. 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.
+ *
+ *     @(#)vis.h       8.1 (Berkeley) 6/2/93
+ */
+
+#ifndef _VIS_H_
+#define        _VIS_H_
+
+#include <sys/types.h>
+
+/*
+ * to select alternate encoding format
+ */
+#define        VIS_OCTAL       0x001   /* use octal \ddd format */
+#define        VIS_CSTYLE      0x002   /* use \[nrft0..] where appropiate */
+
+/*
+ * to alter set of characters encoded (default is to encode all
+ * non-graphic except space, tab, and newline).
+ */
+#define        VIS_SP          0x004   /* also encode space */
+#define        VIS_TAB         0x008   /* also encode tab */
+#define        VIS_NL          0x010   /* also encode newline */
+#define        VIS_WHITE       (VIS_SP | VIS_TAB | VIS_NL)
+#define        VIS_SAFE        0x020   /* only encode "unsafe" characters */
+
+/*
+ * other
+ */
+#define        VIS_NOSLASH     0x040   /* inhibit printing '\' */
+#define        VIS_HTTP1808    0x080   /* http-style escape % hex hex */
+#define        VIS_HTTPSTYLE   0x080   /* http-style escape % hex hex */
+#define        VIS_MIMESTYLE   0x100   /* mime-style escape = HEX HEX */
+#define        VIS_HTTP1866    0x200   /* http-style &#num; or &string; */
+#define        VIS_NOESCAPE    0x400   /* don't decode `\' */
+
+/*
+ * unvis return codes
+ */
+#define        UNVIS_VALID      1      /* character valid */
+#define        UNVIS_VALIDPUSH  2      /* character valid, push back passed char */
+#define        UNVIS_NOCHAR     3      /* valid sequence, no character produced */
+#define        UNVIS_SYNBAD    -1      /* unrecognized escape sequence */
+#define        UNVIS_ERROR     -2      /* decoder in unknown state (unrecoverable) */
+
+/*
+ * unvis flags
+ */
+#define        UNVIS_END       1       /* no more characters */
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+char   *vis(char *, int, int, int);
+char   *svis(char *, int, int, int, const char *);
+int    strvis(char *, const char *, int);
+int    strsvis(char *, const char *, int, const char *);
+int    strvisx(char *, const char *, size_t, int);
+int    strsvisx(char *, const char *, size_t, int, const char *);
+int    strunvis(char *, const char *);
+int    strunvisx(char *, const char *, int);
+#ifndef __LIBC12_SOURCE__
+int    unvis(char *, int, int *, int) __RENAME(__unvis13);
+#endif
+__END_DECLS
+
+#endif /* !_VIS_H_ */
diff --git a/nbsd_include/wchar.h b/nbsd_include/wchar.h
new file mode 100644 (file)
index 0000000..e7fc283
--- /dev/null
@@ -0,0 +1,202 @@
+/*     $NetBSD: wchar.h,v 1.29 2010/03/27 22:14:09 tnozaki Exp $       */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ */
+
+/*-
+ * Copyright (c) 1999, 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Julian Coleman.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 _WCHAR_H_
+#define _WCHAR_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <machine/wchar_limits.h>
+#include <sys/ansi.h>
+#include <sys/null.h>
+
+#include <stdio.h> /* for FILE* */
+
+#if defined(_BSD_WCHAR_T_) && !defined(__cplusplus)
+typedef        _BSD_WCHAR_T_   wchar_t;
+#undef _BSD_WCHAR_T_
+#endif
+
+#ifdef _BSD_MBSTATE_T_
+typedef        _BSD_MBSTATE_T_ mbstate_t;
+#undef _BSD_MBSTATE_T_
+#endif
+
+#ifdef _BSD_WINT_T_
+typedef        _BSD_WINT_T_    wint_t;
+#undef _BSD_WINT_T_
+#endif
+
+#ifdef _BSD_SIZE_T_
+typedef        _BSD_SIZE_T_    size_t;
+#undef _BSD_SIZE_T_
+#endif
+
+struct tm;
+
+__BEGIN_DECLS
+wint_t btowc(int);
+size_t mbrlen(const char * __restrict, size_t, mbstate_t * __restrict);
+size_t mbrtowc(wchar_t * __restrict, const char * __restrict, size_t,
+           mbstate_t * __restrict);
+int    mbsinit(const mbstate_t *);
+size_t mbsrtowcs(wchar_t * __restrict, const char ** __restrict, size_t,
+           mbstate_t * __restrict);
+size_t wcrtomb(char * __restrict, wchar_t, mbstate_t * __restrict);
+wchar_t        *wcscat(wchar_t * __restrict, const wchar_t * __restrict);
+wchar_t        *wcschr(const wchar_t *, wchar_t);
+int    wcscmp(const wchar_t *, const wchar_t *);
+int    wcscoll(const wchar_t *, const wchar_t *);
+wchar_t        *wcscpy(wchar_t * __restrict, const wchar_t * __restrict);
+size_t wcscspn(const wchar_t *, const wchar_t *);
+size_t wcsftime(wchar_t * __restrict, size_t, const wchar_t * __restrict,
+           const struct tm * __restrict);
+size_t wcslen(const wchar_t *);
+wchar_t        *wcsncat(wchar_t * __restrict, const wchar_t * __restrict, size_t);
+int    wcsncmp(const wchar_t *, const wchar_t *, size_t);
+wchar_t        *wcsncpy(wchar_t * __restrict , const wchar_t * __restrict, size_t);
+wchar_t        *wcspbrk(const wchar_t *, const wchar_t *);
+wchar_t        *wcsrchr(const wchar_t *, wchar_t);
+size_t wcsrtombs(char * __restrict, const wchar_t ** __restrict, size_t,
+           mbstate_t * __restrict);
+size_t wcsspn(const wchar_t *, const wchar_t *);
+wchar_t        *wcsstr(const wchar_t *, const wchar_t *);
+wchar_t *wcstok(wchar_t * __restrict, const wchar_t * __restrict,
+                    wchar_t ** __restrict);
+size_t wcsxfrm(wchar_t *, const wchar_t *, size_t);
+wchar_t        *wcswcs(const wchar_t *, const wchar_t *);
+wchar_t        *wmemchr(const wchar_t *, wchar_t, size_t);
+int    wmemcmp(const wchar_t *, const wchar_t *, size_t);
+wchar_t        *wmemcpy(wchar_t * __restrict, const wchar_t * __restrict, size_t);
+wchar_t        *wmemmove(wchar_t *, const wchar_t *, size_t);
+wchar_t        *wmemset(wchar_t *, wchar_t, size_t);
+
+size_t wcslcat(wchar_t *, const wchar_t *, size_t);
+size_t wcslcpy(wchar_t *, const wchar_t *, size_t);
+int    wcswidth(const wchar_t *, size_t);
+int    wctob(wint_t);
+int    wcwidth(wchar_t);
+
+unsigned long int wcstoul(const wchar_t * __restrict,
+       wchar_t ** __restrict, int);
+long int wcstol(const wchar_t * __restrict,
+       wchar_t ** __restrict, int);
+double wcstod(const wchar_t * __restrict, wchar_t ** __restrict);
+
+#if defined(_ISOC99_SOURCE) || (__STDC_VERSION__ - 0) > 199901L || \
+    defined(_NETBSD_SOURCE)
+float wcstof(const wchar_t * __restrict, wchar_t ** __restrict);
+long double wcstold(const wchar_t * __restrict, wchar_t ** __restrict);
+
+/* LONGLONG */
+long long int wcstoll(const wchar_t * __restrict,
+       wchar_t ** __restrict, int);
+/* LONGLONG */
+unsigned long long int wcstoull(const wchar_t * __restrict,
+       wchar_t ** __restrict, int);
+#endif
+
+wint_t ungetwc(wint_t, FILE *);
+wint_t fgetwc(FILE *);
+wchar_t *fgetws(wchar_t * __restrict, int, FILE * __restrict);
+wint_t getwc(FILE *);
+wint_t getwchar(void);
+wint_t fputwc(wchar_t, FILE *);
+int fputws(const wchar_t * __restrict, FILE * __restrict);
+wint_t putwc(wchar_t, FILE *);
+wint_t putwchar(wchar_t);
+
+int fwide(FILE *, int);
+
+wchar_t        *fgetwln(FILE * __restrict, size_t * __restrict);
+int fwprintf(FILE * __restrict, const wchar_t * __restrict, ...);
+int fwscanf(FILE * __restrict, const wchar_t * __restrict, ...);
+int swprintf(wchar_t * __restrict, size_t n, const wchar_t * __restrict, ...);
+int swscanf(const wchar_t * __restrict, const wchar_t * __restrict, ...);
+int vfwprintf(FILE * __restrict, const wchar_t * __restrict, _BSD_VA_LIST_);
+int vswprintf(wchar_t * __restrict, size_t, const wchar_t * __restrict,
+    _BSD_VA_LIST_);
+int vwprintf(const wchar_t * __restrict, _BSD_VA_LIST_);
+int wprintf(const wchar_t * __restrict, ...);
+int wscanf(const wchar_t * __restrict, ...);
+#if defined(_ISOC99_SOURCE) || (__STDC_VERSION__ - 0) > 199901L || \
+    defined(_NETBSD_SOURCE)
+int vfwscanf(FILE * __restrict, const wchar_t * __restrict, _BSD_VA_LIST_);
+int vswscanf(const wchar_t * __restrict, const wchar_t * __restrict,
+    _BSD_VA_LIST_);
+int vwscanf(const wchar_t * __restrict, _BSD_VA_LIST_);
+#endif
+#if defined(_NETBSD_SOURCE)
+struct tinfo;
+int t_putws(struct tinfo *, const wchar_t *, int, void (*)(wchar_t, void *),
+    void *);
+wchar_t *wcsdup (const wchar_t *);
+int wcsncasecmp (const wchar_t *, const wchar_t *, size_t);
+int wcscasecmp(const wchar_t *, const wchar_t *);
+#endif
+__END_DECLS
+
+#ifndef WEOF
+#define        WEOF    ((wint_t)-1)
+#endif
+
+#define getwc(f) fgetwc(f)
+#define getwchar() getwc(stdin)
+#define putwc(wc, f) fputwc((wc), (f))
+#define putwchar(wc) putwc((wc), stdout)
+
+#endif /* !_WCHAR_H_ */
diff --git a/nbsd_include/wctype.h b/nbsd_include/wctype.h
new file mode 100644 (file)
index 0000000..b8689b1
--- /dev/null
@@ -0,0 +1,77 @@
+/*     $NetBSD: wctype.h,v 1.7 2010/03/27 22:14:09 tnozaki Exp $       */
+
+/*-
+ * Copyright (c)1999 Citrus Project,
+ * 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.
+ *
+ *     citrus Id: wctype.h,v 1.4 2000/12/21 01:50:21 itojun Exp
+ */
+
+#ifndef _WCTYPE_H_
+#define        _WCTYPE_H_
+
+#include <sys/cdefs.h>
+#include <sys/ansi.h>
+
+#ifdef _BSD_WINT_T_
+typedef        _BSD_WINT_T_    wint_t;
+#undef _BSD_WINT_T_
+#endif
+
+#ifdef _BSD_WCTRANS_T_
+typedef        _BSD_WCTRANS_T_ wctrans_t;
+#undef _BSD_WCTRANS_T_
+#endif
+
+#ifdef _BSD_WCTYPE_T_
+typedef        _BSD_WCTYPE_T_  wctype_t;
+#undef _BSD_WCTYPE_T_
+#endif
+
+#ifndef WEOF
+#define        WEOF    ((wint_t)-1)
+#endif
+
+__BEGIN_DECLS
+int    iswalnum(wint_t);
+int    iswalpha(wint_t);
+int    iswblank(wint_t);
+int    iswcntrl(wint_t);
+int    iswdigit(wint_t);
+int    iswgraph(wint_t);
+int    iswlower(wint_t);
+int    iswprint(wint_t);
+int    iswpunct(wint_t);
+int    iswspace(wint_t);
+int    iswupper(wint_t);
+int    iswxdigit(wint_t);
+int    iswctype(wint_t, wctype_t);
+wint_t towctrans(wint_t, wctrans_t);
+wint_t towlower(wint_t);
+wint_t towupper(wint_t);
+wctrans_t wctrans(const char *);
+wctype_t wctype(const char *);
+__END_DECLS
+
+#endif         /* _WCTYPE_H_ */
diff --git a/nbsd_include/wordexp.h b/nbsd_include/wordexp.h
new file mode 100644 (file)
index 0000000..defc915
--- /dev/null
@@ -0,0 +1,81 @@
+/*     $NetBSD: wordexp.h,v 1.2 2008/04/01 19:23:28 drochner Exp $     */
+
+/*-
+ * Copyright (c) 2002 Tim J. Robbins.
+ * 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.
+ *
+ * $FreeBSD: /repoman/r/ncvs/src/include/wordexp.h,v 1.4 2003/01/03 12:03:38 tjr Exp $
+ */
+
+#ifndef _WORDEXP_H_
+#define        _WORDEXP_H_
+
+#include <sys/cdefs.h>
+#include <sys/featuretest.h>
+#include <machine/ansi.h>
+
+#ifdef _BSD_SIZE_T_
+typedef        _BSD_SIZE_T_    size_t;
+#undef _BSD_SIZE_T_
+#endif
+
+
+typedef struct {
+       size_t  we_wordc;               /* count of words matched */
+       char            **we_wordv;     /* pointer to list of words */
+       size_t  we_offs;                /* slots to reserve in we_wordv */
+                                       /* following are internals */
+       char            *we_strings;    /* storage for wordv strings */
+       size_t  we_nbytes;              /* size of we_strings */
+} wordexp_t;
+
+/*
+ * Flags for wordexp().
+ */
+#define        WRDE_APPEND     0x1             /* append to previously generated */
+#define        WRDE_DOOFFS     0x2             /* we_offs member is valid */
+#define        WRDE_NOCMD      0x4             /* disallow command substitution */
+#define        WRDE_REUSE      0x8             /* reuse wordexp_t */
+#define        WRDE_SHOWERR    0x10            /* don't redirect stderr to /dev/null */
+#define        WRDE_UNDEF      0x20            /* disallow undefined shell vars */
+
+/*
+ * Return values from wordexp().
+ */
+#define        WRDE_BADCHAR    1               /* unquoted special character */
+#define        WRDE_BADVAL     2               /* undefined variable */
+#define        WRDE_CMDSUB     3               /* command substitution not allowed */
+#define        WRDE_NOSPACE    4               /* no memory for result */
+#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
+#define        WRDE_NOSYS      5               /* obsolete, reserved */
+#endif
+#define        WRDE_SYNTAX     6               /* shell syntax error */
+#define WRDE_ERRNO     7               /* other errors see errno */
+
+__BEGIN_DECLS
+int    wordexp(const char * __restrict, wordexp_t * __restrict, int);
+void   wordfree(wordexp_t *);
+__END_DECLS
+
+#endif /* !_WORDEXP_H_ */